Commit Graph

338 Commits

Author SHA1 Message Date
Andreas Kling
62719b85e0 Kernel: Port Thread to ListedRefCounted 2021-08-17 01:21:47 +02:00
Andreas Kling
c1c12497b5 Kernel: Don't hold thread list lock while invoking ~Thread()
There is no need for this, and it can cause deadlocks if ~Thread()
ends up doing something else that requires a lock (e.g ~Process())
2021-08-16 02:22:42 +02:00
Andreas Kling
37304203dd Kernel: Lock thread list while in Thread::unref()
This patch does three things:

- Convert the global thread list from a HashMap to an IntrusiveList
- Combine the thread list and its lock into a SpinLockProtectedValue
- Customize Thread::unref() so it locks the list while unreffing

This closes the same race window for Thread as @sin-ack's recent changes
did for Process.

Note that the HashMap->IntrusiveList conversion means that we lose O(1)
lookups, but the majority of clients of this list are doing traversal,
not lookup. Once we have an intrusive hashing solution, we should port
this to use that, but for now, this gets rid of heap allocations during
a sensitive time.
2021-08-15 12:44:35 +02:00
Andreas Kling
6fd7212476 Kernel+LibC: Share definitions for signal.h 2021-08-14 19:58:11 +02:00
Brian Gianforcaro
bea74f4b77 Kernel: Reduce LOCK_DEBUG ifdefs by utilizing Kernel::LockLocation
The LOCK_DEBUG conditional code is pretty ugly for a feature that we
only use rarely. We can remove a significant amount of this code by
utilizing a zero sized fake type when not building in LOCK_DEBUG mode.

This lets us keep the same API, but just let the compiler optimize it
away when don't actually care about the location the caller came from.
2021-08-13 20:42:39 +02:00
Liav A
7ba991dc37 Kernel: Steer away from heap allocations for ProcFS process data
Instead, use more static patterns to acquire that sort of data.
2021-08-12 20:57:32 +02:00
Gunnar Beutner
3322efd4cd Kernel: Fix kernel panic when blocking on the process' big lock
Another thread might end up marking the blocking thread as holding
the lock before it gets a chance to finish invoking the scheduler.
2021-08-10 22:33:50 +02:00
Andreas Kling
0a02496f04 Kernel/SMP: Change critical sections to not disable interrupts
Leave interrupts enabled so that we can still process IRQs. Critical
sections should only prevent preemption by another thread.

Co-authored-by: Tom <tomut@yahoo.com>
2021-08-10 02:49:37 +02:00
Andreas Kling
9babb92a4b Kernel/SMP: Make entering/leaving critical sections multi-processor safe
By making these functions static we close a window where we could get
preempted after calling Processor::current() and move to another
processor.

Co-authored-by: Tom <tomut@yahoo.com>
2021-08-10 02:49:37 +02:00
Andreas Kling
2be368e4c4 Kernel: Rename queue_runnable_thread() => enqueue_runnable_thread() 2021-08-08 14:24:55 +02:00
Daniel Bertalan
fa8507d1ce Kernel: Fix UB caused by taking a reference to a packed struct's member
Taking a reference or a pointer to a value that's not aligned properly
is undefined behavior. While `[[gnu::packed]]` ensures that reads from
and writes to fields of packed structs is a safe operation, the
information about the reduced alignment is lost when creating pointers
to these values.

Weirdly enough, GCC's undefined behavior sanitizer doesn't flag these,
even though the doc of `-Waddress-of-packed-member` says that it usually
leads to UB. In contrast, x86_64 Clang does flag these, which renders
the 64-bit kernel unable to boot.

For now, the `address-of-packed-member` warning will only be enabled in
the kernel, as it is absolutely crucial there because of KUBSAN, but
might get excessively noisy for the userland in the future.

Also note that we can't append to `CMAKE_CXX_FLAGS` like we do for other
flags in the kernel, because flags added via `add_compile_options` come
after these, so the `-Wno-address-of-packed-member` in the root would
cancel it out.
2021-08-08 10:55:36 +02:00
Andreas Kling
2cd8b21974 Kernel: Add convenience values to the Memory::Region::Access enum
Instead of `Memory::Region::Access::Read | Memory::Region::AccessWrite`
you can now say `Memory::Region::Access::ReadWrite`.
2021-08-06 22:25:00 +02:00
Andreas Kling
208147c77c Kernel: Rename Process::space() => Process::address_space()
We commonly talk about "a process's address space" so let's nudge the
code towards matching how we talk about it. :^)
2021-08-06 14:05:58 +02:00
Andreas Kling
93d98d4976 Kernel: Move Kernel/Memory/ code into Kernel::Memory namespace 2021-08-06 14:05:58 +02:00
Andreas Kling
a1d7ebf85a Kernel: Rename Kernel/VM/ to Kernel/Memory/
This directory isn't just about virtual memory, it's about all kinds
of memory management.
2021-08-06 14:05:58 +02:00
Andreas Kling
584fa525eb Kernel: Don't make a separate allocation for thread FPU state
We were allocating thread FPU state separately in order to ensure a
16-byte alignment. There should be no need to do that.

This patch makes it a regular value member of Thread instead, dodging
one heap allocation during thread creation.
2021-08-06 00:37:47 +02:00
Andreas Kling
d5d8fba579 Kernel: Store Thread name as a KString 2021-08-06 00:37:47 +02:00
Andreas Kling
32a150f2b4 Kernel: Make Thread::state_string() return StringView 2021-08-06 00:37:47 +02:00
Patrick Meyer
83f88df757 Kernel: Add option to build with coverage instrumentation and KCOV
GCC and Clang allow us to inject a call to a function named
__sanitizer_cov_trace_pc on every edge. This function has to be defined
by us. By noting down the caller in that function we can trace the code
we have encountered during execution. Such information is used by
coverage guided fuzzers like AFL and LibFuzzer to determine if a new
input resulted in a new code path. This makes fuzzing much more
effective.

Additionally this adds a basic KCOV implementation. KCOV is an API that
allows user space to request the kernel to start collecting coverage
information for a given user space thread. Furthermore KCOV then exposes
the collected program counters to user space via a BlockDevice which can
be mmaped from user space.

This work is required to add effective support for fuzzing SerenityOS to
the Syzkaller syscall fuzzer. :^) :^)
2021-07-26 17:40:28 +02:00
Gunnar Beutner
36e36507d5 Everywhere: Prefer using {:#x} over 0x{:x}
We have a dedicated format specifier which adds the "0x" prefix, so
let's use that instead of adding it manually.
2021-07-22 08:57:01 +02:00
Gunnar Beutner
31f30e732a Everywhere: Prefix hexadecimal numbers with 0x
Depending on the values it might be difficult to figure out whether a
value is decimal or hexadecimal. So let's make this more obvious. Also
this allows copying and pasting those numbers into GNOME calculator and
probably also other apps which auto-detect the base.
2021-07-22 08:57:01 +02:00
Brian Gianforcaro
1cffecbe8d Kernel: Push ARCH specific ifdef's down into RegisterState functions
The non CPU specific code of the kernel shouldn't need to deal with
architecture specific registers, and should instead deal with an
abstract view of the machine. This allows us to remove a variety of
architecture specific ifdefs and helps keep the code slightly more
portable.

We do this by exposing the abstract representation of instruction
pointer, stack pointer, base pointer, return register, etc on the
RegisterState struct.
2021-07-19 08:46:55 +02:00
Tom
a635ff4e60 Everywhere: Make tracking cpu usage independent from system ticks
This switches tracking CPU usage to more accurately measure time in
user and kernel land using either the TSC or another time source.
This will also come in handy when implementing a tickless kernel mode.
2021-07-18 22:08:26 +02:00
Gunnar Beutner
6c6b778e2e Kernel: Support 64-bit addresses for kernel thread stacks 2021-07-18 17:31:13 +02:00
Tom
ae8472f9ca Kernel: Fix blocking relock of the big_lock while unlocking other Lock
When a Thread is being unblocked and we need to re-lock the process
big_lock and re-locking blocks again, then we may end up in
Thread::block again while still servicing the original lock's
Thread::block. So permit recursion as long as it's only the big_lock
that we block on again.

Fixes #8822
2021-07-18 13:08:51 +02:00
Andreas Kling
cee9528168 Kernel: Rename Lock to Mutex
Let's be explicit about what kind of lock this is meant to be.
2021-07-17 21:10:32 +02:00
Brian Gianforcaro
c0987453e6 Kernel: Remove double RedBlackTree lookup in VM/Space region removal
We should never request a regions removal that we don't currently
own. We currently assert this everywhere else by all callers.

Instead lets just push the assert down into the RedBlackTree removal
and assume that we will always successfully remove the region.
2021-07-17 16:22:59 +02:00
Daniel Bertalan
dd4ed4d22d Kernel: Implement aligned operator new and use it
The compiler will use these to allocate objects that have alignment
requirements greater than that of our normal `operator new` (4/8 byte
aligned).

This means we can now use smart pointers for over-aligned types.

Fixes a FIXME.
2021-07-16 20:51:13 +02:00
Tom
704e1c2e3d Kernel: Rename functions to be less confusing
Thread::yield_and_release_relock_big_lock releases the big lock, yields
and then relocks the big lock.

Thread::yield_assuming_not_holding_big_lock yields assuming the big
lock is not being held.
2021-07-16 20:30:04 +02:00
Tom
0536a4ff41 Kernel: Release big lock when blocking on another lock
When blocking on a Lock other than the big lock and we're holding the
big lock, we need to release the big lock first. This fixes some
deadlocks where a thread blocks while holding the big lock, preventing
other threads from getting the big lock in order to unblock the waiting
thread.
2021-07-16 20:30:04 +02:00
Tom
026ffa343d Kernel: Allow Lock to block from BlockCondition
This enables the Lock class to block a thread even while the thread is
working on a BlockCondition. A thread can still only be either blocked
by a Lock or a BlockCondition.

This also establishes a linked list of threads that are blocked by a
Lock and unblocking directly unlocks threads and wakes them directly.
2021-07-12 11:27:18 +02:00
Andreas Kling
fa9111ac46 Kernel: Rename ProcFSComponentsRegistrar => ProcFSComponentRegistry
This matches the formatting used in SysFS.
2021-07-11 01:40:26 +02:00
Gunnar Beutner
67f0c0d5f0 Kernel+LibELF: Don't demangle symbols in the kernel
Instead we should just generate kernel.map in such a way that it already
contains demangled symbols.
2021-07-06 19:08:22 +02:00
Andreas Kling
565796ae4e Kernel+LibC: Remove sys$donate()
This was an old SerenityOS-specific syscall for donating the remainder
of the calling thread's time-slice to another thread within the same
process.

Now that Threading::Lock uses a pthread_mutex_t internally, we no
longer need this syscall, which allows us to get rid of a surprising
amount of unnecessary scheduler logic. :^)
2021-07-05 23:30:15 +02:00
Tom
908f86b061 Kernel: Print region name+offset for user addresses in thread backtrace
This provides more crucial information to be able to do an addr2line
lookup on a backtrace captured with Thread::backtrace.

Also change the offset to hexadecimal as this is what is require for
addr2line.
2021-07-05 22:59:14 +02:00
Hediadyoin1
d12e14fa95 Userland: Respect red-zone for signal handlers
We were building with red-zone before, but were not accounting for it on
signal handler entries. This should fix that.

Also shorten the stack alignment calculations for this.
2021-07-03 13:20:04 +02:00
Gunnar Beutner
52f9aaa823 Kernel: Use the GS segment for the per-CPU struct
Right now we're using the FS segment for our per-CPU struct. On x86_64
there's an instruction to switch between a kernel and usermode GS
segment (swapgs) which we could use.

This patch doesn't update the rest of the code to use swapgs but it
prepares for that by using the GS segment instead of the FS segment.
2021-07-02 23:33:17 +02:00
Liav A
3344f91fc4 Kernel/ProcFS: Clean dead processes properly
Now we use WeakPtrs to break Ref-counting cycle. Also, we call the
prepare_for_deletion method to ensure deleted objects are ready for
deletion. This is necessary to ensure we don't keep dead processes,
which would become zombies.

In addition to that, add some debug prints to aid debug in the future.
2021-07-02 13:16:12 +02:00
Brian Gianforcaro
60efe18a31 Kernel: Handle OOM when allocating Thread FPUState
Move FPUState allocation to Thread::try_create so that allocation
failure can be observed properly by the caller.
2021-07-01 22:43:48 +02:00
Liav A
12b6e69150 Kernel: Introduce the new ProcFS design
The new ProcFS design consists of two main parts:
1. The representative ProcFS class, which is derived from the FS class.
The ProcFS and its inodes are much more lean - merely 3 classes to
represent the common type of inodes - regular files, symbolic links and
directories. They're backed by a ProcFSExposedComponent object, which
is responsible for the functional operation behind the scenes.
2. The backend of the ProcFS - the ProcFSComponentsRegistrar class
and all derived classes from the ProcFSExposedComponent class. These
together form the entire backend and handle all the functions you can
expect from the ProcFS.

The ProcFSExposedComponent derived classes split to 3 types in the
manner of lifetime in the kernel:
1. Persistent objects - this category includes all basic objects, like
the root folder, /proc/bus folder, main blob files in the root folders,
etc. These objects are persistent and cannot die ever.
2. Semi-persistent objects - this category includes all PID folders,
and subdirectories to the PID folders. It also includes exposed objects
like the unveil JSON'ed blob. These object are persistent as long as the
the responsible process they represent is still alive.
3. Dynamic objects - this category includes files in the subdirectories
of a PID folder, like /proc/PID/fd/* or /proc/PID/stacks/*. Essentially,
these objects are always created dynamically and when no longer in need
after being used, they're deallocated.
Nevertheless, the new allocated backend objects and inodes try to use
the same InodeIndex if possible - this might change only when a thread
dies and a new thread is born with a new thread stack, or when a file
descriptor is closed and a new one within the same file descriptor
number is opened. This is needed to actually be able to do something
useful with these objects.

The new design assures that many ProcFS instances can be used at once,
with one backend for usage for all instances.
2021-06-29 20:53:59 +02:00
Gunnar Beutner
6dde7dac8f Kernel: Implement signal handling for x86_64 2021-06-29 20:03:36 +02:00
Gunnar Beutner
9ed051fe25 Kernel: Implement initializing threads on x86_64 2021-06-27 15:46:42 +02:00
Gunnar Beutner
f285241cb8 Kernel: Rename Thread::tss to Thread::regs and add x86_64 support
We're using software context switches so calling this struct tss is
somewhat misleading.
2021-06-27 15:46:42 +02:00
Gunnar Beutner
233ef26e4d Kernel+Userland: Add x86_64 registers to RegisterState/PtraceRegisters 2021-06-27 15:46:42 +02:00
Daniel Bertalan
f820917a76 Everywhere: Use nothrow new with adopt_{ref,own}_if_nonnull
This commit converts naked `new`s to `AK::try_make` and `AK::try_create`
wherever possible. If the called constructor is private, this can not be
done, so we instead now use the standard-defined and compiler-agnostic
`new (nothrow)`.
2021-06-24 17:35:49 +04:30
Gunnar Beutner
38fca26f54 Kernel: Add stubs for missing x86_64 functionality
This adds just enough stubs to make the kernel compile on x86_64. Obviously
it won't do anything useful - in fact it won't even attempt to boot because
Multiboot doesn't support ELF64 binaries - but it gets those compiler errors
out of the way so more progress can be made getting all the missing
functionality in place.
2021-06-24 09:27:13 +02:00
Hendiadyoin1
62f9377656 Kernel: Move special sections into Sections.h
This also removes a lot of CPU.h includes infavor for Sections.h
2021-06-24 00:38:23 +02:00
Hendiadyoin1
7ca3d413f7 Kernel: Pull apart CPU.h
This does not add any functional changes
2021-06-24 00:38:23 +02:00
Jelle Raaijmakers
5b03b62518 Kernel: Only call Process::die() once on terminating signal
Previously, when e.g. the `SIGABRT` signal was sent to a process,
`Thread::dispatch_signal()` would invoke
`Process::terminate_due_to_signal()` which would then `::die()`. The
result `DispatchSignalResult::Terminate` is then returned to
`Thread::check_dispatch_pending_signal()` which proceeds to invoke
`Process::die()` a second time.

Change the behavior of `::check_dispatch_pending_signal()` to no longer
call `Process::die()` if it receives `::Terminate` as a signal handling
result, since that indicates that the process was already terminated.

This fixes #7289.
2021-06-14 16:27:37 +02:00
Gunnar Beutner
3bac14e19e Kernel: Remove incorrect VERIFY() in Thread::relock_process
Turns are there are legitimate cases where the thread state isn't
Thread::Running.
2021-06-07 14:45:38 +04:30