2022-12-07 14:02:46 +00:00
|
|
|
#include "thread/Thread.h"
|
2023-03-12 13:43:58 +00:00
|
|
|
#include <bits/open-flags.h>
|
2022-12-07 14:02:46 +00:00
|
|
|
#include <luna/Alloc.h>
|
2022-12-17 09:50:49 +00:00
|
|
|
#include <luna/Atomic.h>
|
2022-12-07 14:02:46 +00:00
|
|
|
|
2022-12-17 09:50:49 +00:00
|
|
|
static Atomic<u64> g_next_id;
|
2022-12-07 14:02:46 +00:00
|
|
|
|
2022-12-19 11:43:23 +00:00
|
|
|
LinkedList<Thread> g_threads;
|
2022-12-07 14:02:46 +00:00
|
|
|
|
2022-12-17 09:50:49 +00:00
|
|
|
void Thread::init()
|
|
|
|
{
|
|
|
|
g_next_id = 1;
|
|
|
|
}
|
|
|
|
|
2022-12-07 14:02:46 +00:00
|
|
|
Result<Thread*> new_thread()
|
|
|
|
{
|
2023-01-10 18:31:41 +00:00
|
|
|
Thread* const thread = TRY(make<Thread>());
|
2022-12-07 14:02:46 +00:00
|
|
|
|
|
|
|
thread->id = g_next_id++;
|
|
|
|
|
|
|
|
return thread;
|
2023-01-02 12:07:29 +00:00
|
|
|
}
|
2023-03-11 16:45:20 +00:00
|
|
|
|
|
|
|
Result<int> Thread::allocate_fd(int min)
|
|
|
|
{
|
|
|
|
if (min < 0 || min >= FD_MAX) return err(EINVAL);
|
|
|
|
for (int i = min; i < FD_MAX; i++)
|
|
|
|
{
|
|
|
|
// FIXME: Possible race condition if multiple threads share a FileDescriptorTable? Let's not worry about it for
|
|
|
|
// now, we're still a long way away from reaching that point.
|
2023-03-12 12:57:38 +00:00
|
|
|
if (!fd_table[i].has_value()) { return i; }
|
2023-03-11 16:45:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return err(EMFILE);
|
|
|
|
}
|
2023-03-12 12:57:38 +00:00
|
|
|
|
|
|
|
Result<FileDescriptor*> Thread::resolve_fd(int fd)
|
|
|
|
{
|
|
|
|
if (fd < 0 || fd >= FD_MAX) return err(EBADF);
|
|
|
|
|
|
|
|
Option<FileDescriptor>& maybe_descriptor = fd_table[fd];
|
|
|
|
|
|
|
|
if (!maybe_descriptor.has_value()) return err(EBADF);
|
|
|
|
|
|
|
|
return maybe_descriptor.value_ptr();
|
|
|
|
}
|
2023-03-12 13:43:58 +00:00
|
|
|
|
|
|
|
bool FileDescriptor::should_append()
|
|
|
|
{
|
|
|
|
return flags & O_APPEND;
|
|
|
|
}
|
|
|
|
|
2023-03-19 10:25:14 +00:00
|
|
|
bool FileDescriptor::should_block()
|
|
|
|
{
|
2023-03-23 20:34:38 +00:00
|
|
|
return !(flags & O_NONBLOCK);
|
2023-03-19 10:25:14 +00:00
|
|
|
}
|
|
|
|
|
2023-03-12 13:43:58 +00:00
|
|
|
bool FileDescriptor::is_readable()
|
|
|
|
{
|
|
|
|
return flags & O_RDONLY;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool FileDescriptor::is_writable()
|
|
|
|
{
|
|
|
|
return flags & O_WRONLY;
|
|
|
|
}
|