39 lines
781 B
C
39 lines
781 B
C
#include <stdatomic.h>
|
|
#include <stdint.h>
|
|
#include <stdbool.h>
|
|
#include "spinlock.h"
|
|
#include "hal/hal.h"
|
|
#include "kprintf.h"
|
|
|
|
void spinlock_init(SpinLock *sl) {
|
|
atomic_store(&sl->lock, false);
|
|
sl->flags = 0;
|
|
}
|
|
|
|
uint64_t spinlock_irqsave(void) {
|
|
uint64_t flags;
|
|
asm volatile("pushfq; cli; popq %0" : "=r"(flags) :: "memory");
|
|
return flags;
|
|
}
|
|
|
|
void spinlock_irqrestore(uint64_t flags) {
|
|
if (flags & (1<<9)) {
|
|
asm volatile("sti" ::: "memory");
|
|
}
|
|
}
|
|
|
|
void spinlock_acquire(SpinLock *sl) {
|
|
sl->flags = spinlock_irqsave();
|
|
|
|
while (atomic_test_and_set_explicit(&sl->lock, memory_order_acquire)) {
|
|
SPINLOCK_HINT();
|
|
}
|
|
}
|
|
|
|
void spinlock_release(SpinLock *sl) {
|
|
atomic_clear_flag_explicit(&sl->lock, memory_order_release);
|
|
|
|
spinlock_irqrestore(sl->flags);
|
|
}
|
|
|