diff --git a/include/kernel/lock.h b/include/kernel/lock.h new file mode 100644 index 0000000..f9d848a --- /dev/null +++ b/include/kernel/lock.h @@ -0,0 +1,11 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef _LOCK_H_ +#define _LOCK_H_ + +typedef int spinlock_t; + +int atomic_cmpxchg(volatile int *ptr, int cmpval, int newval); +void spinlock_acquire(spinlock_t *lock); +void spinlock_release(spinlock_t *lock); + +#endif /* _LOCK_H_ */ diff --git a/init/atomic.S b/init/atomic.S new file mode 100644 index 0000000..e57a218 --- /dev/null +++ b/init/atomic.S @@ -0,0 +1,18 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#define __ASM__ + +/* int atomic_cmpxchg(volatile int *ptr, int cmpval, int newval) */ +.global atomic_cmpxchg +atomic_cmpxchg: + /* if (*ptr == cmpval) *ptr = newval, but atomic :) */ + movl %esi, %eax + lock cmpxchg %edx, (%rdi) + + /* if ZF is set, the exchange was successful */ + pushfq + popq %rax + andl $0x40, %eax + shrl $6, %eax + xorl $1, %eax + + ret diff --git a/init/lock.c b/init/lock.c new file mode 100644 index 0000000..63a7c81 --- /dev/null +++ b/init/lock.c @@ -0,0 +1,13 @@ +#include +#include + +void spinlock_acquire(spinlock_t *lock) +{ + while (atomic_cmpxchg(lock, 0, 1)) + ; +} + +void spinlock_release(spinlock_t *lock) +{ + atomic_cmpxchg(lock, 1, 0); +}