From 7b2977a0364269acba4194a5f1c2e53b30940d02 Mon Sep 17 00:00:00 2001 From: apio Date: Sat, 23 Nov 2024 20:02:34 +0100 Subject: [PATCH] kernel: Use a mutex to allocate new posix timers for a thread --- kernel/src/sys/setitimer.cpp | 1 - kernel/src/thread/Thread.cpp | 9 +++++++-- kernel/src/thread/Thread.h | 2 ++ 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/kernel/src/sys/setitimer.cpp b/kernel/src/sys/setitimer.cpp index 199eacef..d3b03fa2 100644 --- a/kernel/src/sys/setitimer.cpp +++ b/kernel/src/sys/setitimer.cpp @@ -118,7 +118,6 @@ Result sys_timer_create(Registers*, SyscallArgs args) if (ksevp.sigev_signo <= 0 || ksevp.sigev_signo > NSIG) return err(EINVAL); int id = TRY(current->allocate_timerid()); - current->posix_timers[id] = Timer {}; Timer* timer = current->posix_timers[id].value_ptr(); timer->signo = ksevp.sigev_signo; diff --git a/kernel/src/thread/Thread.cpp b/kernel/src/thread/Thread.cpp index 77b7f42a..1d56b822 100644 --- a/kernel/src/thread/Thread.cpp +++ b/kernel/src/thread/Thread.cpp @@ -61,10 +61,15 @@ Result Thread::resolve_fd(int fd) Result Thread::allocate_timerid() { + ScopedMutexLock lock(posix_timer_mutex); + for (int i = 0; i < MAX_POSIX_TIMERS; i++) { - // FIXME: Possible race condition, this should be used alongside a mutex. - if (!posix_timers[i].has_value()) { return i; } + if (!posix_timers[i].has_value()) + { + posix_timers[i] = Timer {}; + return i; + } } return err(EMFILE); diff --git a/kernel/src/thread/Thread.h b/kernel/src/thread/Thread.h index eb185949..2d19cc69 100644 --- a/kernel/src/thread/Thread.h +++ b/kernel/src/thread/Thread.h @@ -3,6 +3,7 @@ #include "arch/MMU.h" #include "fs/OpenFileDescription.h" #include "fs/VFS.h" +#include "lib/Mutex.h" #include "memory/AddressSpace.h" #include #include @@ -109,6 +110,7 @@ struct Thread : public LinkedListNode Clock profiling_clock; Option posix_timers[MAX_POSIX_TIMERS]; + Mutex posix_timer_mutex; Result allocate_timerid(); Result resolve_timerid(int id);