Commit Graph

232 Commits

Author SHA1 Message Date
Gunnar Beutner
01c75e3a34 Kernel: Don't log profile data before/after the process/thread lifetime
There were a few cases where we could end up logging profiling events
before or after the associated process or thread exists in the profile:

After enabling profiling we might end up with CPU samples before we
had a chance to synthesize process/thread creation events.

After a thread exits we would still log associated kmalloc/kfree
events. Instead we now just ignore those events.
2021-05-30 19:03:03 +02:00
Gunnar Beutner
b9d693665b Kernel: Make sure we unmap the TLS region when a thread exits
Previously the TLS region would get leaked which was noticible
when creating/destroying a lot of threads and then inspecting
the region map.
2021-05-29 15:53:08 +02:00
Gunnar Beutner
7557f2db90 Kernel: Remove an allocation when blocking a thread
When blocking a thread with a timeout we would previously allocate
a Timer object. This removes the allocation for that Timer object.
2021-05-20 09:09:10 +02:00
Brian Gianforcaro
83fc591cea Kernel: Generate page fault events from the kernel profiler
Hook the kernel page fault handler and capture page fault events when
the fault has a current thread attached in TLS. We capture the eip and
ebp so we can unwind the stack and locate which pieces of code are
generating the most page faults.

Co-authored-by: Gunnar Beutner <gbeutner@serenityos.org>
2021-05-19 22:51:42 +02:00
Nicholas Baron
aa4d41fe2c
AK+Kernel+LibELF: Remove the need for IteratorDecision::Continue
By constraining two implementations, the compiler will select the best
fitting one. All this will require is duplicating the implementation and
simplifying for the `void` case.

This constraining also informs both the caller and compiler by passing
the callback parameter types as part of the constraint
(e.g.: `IterationFunction<int>`).

Some `for_each` functions in LibELF only take functions which return
`void`. This is a minimal correctness check, as it removes one way for a
function to incompletely do something.

There seems to be a possible idiom where inside a lambda, a `return;` is
the same as `continue;` in a for-loop.
2021-05-16 10:36:52 +01:00
Tom
72a61fe137 Kernel: Remove shadowing member variable from FileDescriptionBlocker
FileDescriptionBlocker::m_should_block was shadowing the parent's
FileBlocker::m_should_block variable, which would cause should_block()
to return the wrong value.

Found by @gunnarbeutner
2021-05-05 18:44:40 +02:00
Tom
ec27cbbb2a Kernel: Store whether a thread is the idle thread in Thread directly
This solves a problem where checking whether a thread is an idle
thread may require iterating all processors if it is not the idle
thread of the current processor.
2021-05-04 16:44:02 +02:00
Brian Gianforcaro
04156d53ca Kernel: Utilize AK::SourceLocation for LOCK_DEBUG instrumentation.
The previous `LOCKER(..)` instrumentation only covered some of the
cases where a lock is actually acquired. By utilizing the new
`AK::SourceLocation` functionality we can now reliably instrument
all calls to lock automatically.

Other changes:
- Tweak the message in `Thread::finalize()` which dumps leaked lock
  so it's more readable and includes the function information that is
  now available.

- Make the `LOCKER(..)` define a no-op, it will be cleaned up in a
  follow up change.
2021-04-25 09:38:27 +02:00
Brian Gianforcaro
1682f0b760 Everything: Move to SPDX license identifiers in all files.
SPDX License Identifiers are a more compact / standardized
way of representing file license information.

See: https://spdx.dev/resources/use/#identifiers

This was done with the `ambr` search and replace tool.

 ambr --no-parent-ignore --key-from-file --rep-from-file key.txt rep.txt *
2021-04-22 11:22:27 +02:00
FalseHonesty
3123ffb19d Kernel: Add ptrace commands for reading/writing the debug registers
This adds PT_PEEKDEBUG and PT_POKEDEBUG to allow for reading/writing
the debug registers, and updates the Kernel's debug handler to read the
new information from the debug status register.
2021-04-18 17:02:40 +02:00
FalseHonesty
97a4c627cb Kernel: Add debug register handling
This patch adds functions to read/write from the debug registers,
and implements storing/loading them across context switches.
2021-04-18 17:02:40 +02:00
AnotherTest
e4412f1f59 AK+Kernel: Make IntrusiveList capable of holding non-raw pointers
This should allow creating intrusive lists that have smart pointers,
while remaining free (compared to the impl before this commit) when
holding raw pointers :^)
As a sidenote, this also adds a `RawPtr<T>` type, which is just
equivalent to `T*`.
Note that this does not actually use such functionality, but is only
expected to pave the way for #6369, to replace NonnullRefPtrVector<T>
with intrusive lists.

As it is with zero-cost things, this makes the interface a bit less nice
by requiring the type name of what an `IntrusiveListNode` holds (and
optionally its container, if not RawPtr), and also requiring the type of
the container (normally `RawPtr`) on the `IntrusiveList` instance.
2021-04-16 22:26:52 +02:00
Andreas Kling
664571c88f Kernel: Clarify Thread::block() a little bit with a better local name 2021-03-30 11:50:48 +02:00
Hendiadyoin1
611b3c2c49 Kernel: Make TSS use in thread generic
This way it won't be architecture dependent
2021-03-21 09:35:23 +01:00
Hendiadyoin1
0d934fc991 Kernel::CPU: Move headers into common directory
Alot of code is shared between i386/i686/x86 and x86_64
and a lot probably will be used for compatability modes.
So we start by moving the headers into one Directory.
We will probalby be able to move some cpp files aswell.
2021-03-21 09:35:23 +01:00
Andreas Kling
ef1e5db1d0 Everywhere: Remove klog(), dbg() and purge all LogStream usage :^)
Good-bye LogStream. Long live AK::Format!
2021-03-12 17:29:37 +01:00
Andreas Kling
4916b5c130 Kernel: Move process thread lists into protected data 2021-03-11 14:21:49 +01:00
Brian Gianforcaro
5f6ab77352 Kernel: Add bitwise operators for Thread::FileBlocker::BlockFlags enum
Switch to using type-safe bitwise operators for the BlockFlags class,
this cleans up a lot of boilerplate casts which are necessary when the
enum is declared as `enum class`.
2021-03-08 18:47:40 +01:00
Andreas Kling
d96a44a738 Kernel: Avoid transient kmalloc heap allocations in sys$select()
Dynamic Vector allocations in sys$select() were showing up in the
full-system profile and since there will never be more than FD_SETSIZE
file descriptors to worry about, we can confidently add enough inline
capacity to this Vector that it never has to kmalloc.

To compensate for the increased stack usage, reduce the size of the
FDInfo struct while we're here. :^)
2021-03-03 20:37:23 +01:00
Ben Wiederhake
2b6546c40a Kernel: Make Thread use AK::Time internally
This commit is very invasive, because Thread likes to take a pointer and write
to it. This means that translating between timespec/timeval/Time would have been
more difficult than just changing everything that hands a raw pointer to Thread,
in bulk.
2021-03-02 08:36:08 +01:00
Andreas Kling
5d180d1f99 Everywhere: Rename ASSERT => VERIFY
(...and ASSERT_NOT_REACHED => VERIFY_NOT_REACHED)

Since all of these checks are done in release builds as well,
let's rename them to VERIFY to prevent confusion, as everyone is
used to assertions being compiled out in release.

We can introduce a new ASSERT macro that is specifically for debug
checks, but I'm doing this wholesale conversion first since we've
accumulated thousands of these already, and it's not immediately
obvious which ones are suitable for ASSERT.
2021-02-23 20:56:54 +01:00
Brian Gianforcaro
dae071629f Kernel: Switch m_signal_action_data to Array<...> 2021-02-21 12:54:39 +01:00
Brian Gianforcaro
a977cdd9ac Kernel: Remove unneeded Thread::set_default_signal_dispositions
The `default_signal_action(u8 signal)` function already has the
full mapping. The only caveat being that now we need to make
sure the thread constructor and clear_signals() method do the work
of resetting the m_signal_action_data array, instead or relying on
the previous logic in set_default_signal_dispositions.
2021-02-21 12:54:39 +01:00
Brian Gianforcaro
f12754ee10 Kernel: Mark BlockResult as [[nodiscard]]
In the majority of cases we want to force callers to observe the
result of a blocking operation as it's not grantee to succeed as
they expect. Mark BlockResult as [[nodiscard]] to force any callers
to observe the result of the blocking operation.
2021-02-15 08:28:57 +01:00
Andreas Kling
29045f84d4 Kernel: Decrease default userspace stack size to 1 MiB
Not sure why this was 4 MiB in the first place, but that's a lot of
memory to reserve for each thread when we're running with 512 MiB
total in the default testing setup. :^)
2021-02-12 19:17:09 +01:00
Andreas Kling
e8f040139b Kernel: Remove unused Thread::is_runnable_state() 2021-02-08 23:07:33 +01:00
AnotherTest
09a43969ba Everywhere: Replace dbgln<flag>(...) with dbgln_if(flag, ...)
Replacement made by `find Kernel Userland -name '*.h' -o -name '*.cpp' | sed -i -Ee 's/dbgln\b<(\w+)>\(/dbgln_if(\1, /g'`
2021-02-08 18:08:55 +01:00
AnotherTest
53ce923e10 Everywhere: Fix obvious dbgln() bugs
This will allow compiletime dbgln() checks to pass
2021-02-08 18:08:55 +01:00
Andreas Kling
0d8262cbab Kernel: Remove a handful of unused things from Thread 2021-02-07 20:26:53 +01:00
Andreas Kling
b466ede1ea Kernel: Make sure we can allocate kernel stack before creating thread
Wrap thread creation in a Thread::try_create() helper that first
allocates a kernel stack region. If that allocation fails, we propagate
an ENOMEM error to the caller.

This avoids the situation where a thread is half-constructed, without a
valid kernel stack, and avoids having to do messy cleanup in that case.
2021-02-07 19:27:00 +01:00
Andreas Kling
5c45b0d32d Kernel: Combine Thread::backtrace() and backtrace_impl() into one 2021-02-07 19:27:00 +01:00
Andreas Kling
fd3eca3acc Kernel: Add initializer for Thread::m_tss 2021-02-07 19:27:00 +01:00
Andreas Kling
c10e0adaca Kernel: Move perf event backtrace capture out of Thread class
There's no need for this to be generic and support running from an
arbitrary thread context. Perf events are always generated from within
the thread being profiled, so take advantage of that to simplify the
code. Also use Vector capacity to avoid heap allocations.
2021-02-03 11:53:05 +01:00
Tom
d5472426ec Kernel: Retire SchedulerData and add Thread lookup table
This allows us to get rid of the thread lists in SchedulerData.
Also, instead of iterating over all threads to find a thread by id,
just use a lookup table. In the rare case of having to iterate over
all threads, just iterate the lookup table.
2021-01-28 17:35:41 +01:00
Andreas Kling
5ff355c0cd Kernel: Generate coredump backtraces from "threads for coredump" list
This broke with the change that gave each process a list of its own
threads. Since threads are removed slightly earlier from that list
during process teardown, we're not able to use it for generating
coredump backtraces. Fortunately we have the "threads for coredump"
list for just this purpose. :^)
2021-01-28 08:41:18 +01:00
Andreas Kling
b72f067f0d Kernel+Userland: Remove unused "effective priority" from threads
This has been merged with the regular Thread::priority field after
the recent changes to the scheduler.
2021-01-28 08:25:53 +01:00
Tom
ccaeb47401 Kernel: Don't hold scheduler lock while setting up blocker in Thread::block
This fixes a deadlock when one processor is trying to block while another is
trying to unblock the same.
2021-01-27 22:48:41 +01:00
Tom
ac3927086f Kernel: Keep a list of threads per Process
This allow us to iterate only the threads of the process.
2021-01-27 22:48:41 +01:00
Tom
03a9ee79fa Kernel: Implement thread priority queues
Rather than walking all Thread instances and putting them into
a vector to be sorted by priority, queue them into priority sorted
linked lists as soon as they become ready to be executed.
2021-01-27 22:48:41 +01:00
Tom
21d288a10e Kernel: Make Thread::current smp-safe
Change Thread::current to be a static function and read using the fs
register, which eliminates a window between Processor::current()
returning and calling a function on it, which can trigger preemption
and a move to a different processor, which then causes operating
on the wrong object.
2021-01-27 21:12:24 +01:00
Tom
f88a8b16d7 Kernel: Make entering and leaving critical sections atomic
We also need to store m_in_critical in the Thread upon switching,
and we need to restore it. This solves a problem where threads
moving between different processors could end up with an unexpected
value.
2021-01-27 21:12:24 +01:00
Tom
33cdc1d2f1 Kernel: Use new Thread::previous_mode to track ticks 2021-01-27 21:12:24 +01:00
Tom
0bd558081e Kernel: Track previous mode when entering/exiting traps
This allows us to determine what the previous mode (user or kernel)
was, e.g. in the timer interrupt. This is used e.g. to determine
whether a signal handler should be set up.

Fixes #5096
2021-01-27 21:12:24 +01:00
asynts
7cf0c7cc0d Meta: Split debug defines into multiple headers.
The following script was used to make these changes:

    #!/bin/bash
    set -e

    tmp=$(mktemp -d)

    echo "tmp=$tmp"

    find Kernel \( -name '*.cpp' -o -name '*.h' \) | sort > $tmp/Kernel.files
    find . \( -path ./Toolchain -prune -o -path ./Build -prune -o -path ./Kernel -prune \) -o \( -name '*.cpp' -o -name '*.h' \) -print | sort > $tmp/EverythingExceptKernel.files

    cat $tmp/Kernel.files | xargs grep -Eho '[A-Z0-9_]+_DEBUG' | sort | uniq > $tmp/Kernel.macros
    cat $tmp/EverythingExceptKernel.files | xargs grep -Eho '[A-Z0-9_]+_DEBUG' | sort | uniq > $tmp/EverythingExceptKernel.macros

    comm -23 $tmp/Kernel.macros $tmp/EverythingExceptKernel.macros > $tmp/Kernel.unique
    comm -1 $tmp/Kernel.macros $tmp/EverythingExceptKernel.macros > $tmp/EverythingExceptKernel.unique

    cat $tmp/Kernel.unique | awk '{ print "#cmakedefine01 "$1 }' > $tmp/Kernel.header
    cat $tmp/EverythingExceptKernel.unique | awk '{ print "#cmakedefine01 "$1 }' > $tmp/EverythingExceptKernel.header

    for macro in $(cat $tmp/Kernel.unique)
    do
        cat $tmp/Kernel.files | xargs grep -l $macro >> $tmp/Kernel.new-includes ||:
    done
    cat $tmp/Kernel.new-includes | sort > $tmp/Kernel.new-includes.sorted

    for macro in $(cat $tmp/EverythingExceptKernel.unique)
    do
        cat $tmp/Kernel.files | xargs grep -l $macro >> $tmp/Kernel.old-includes ||:
    done
    cat $tmp/Kernel.old-includes | sort > $tmp/Kernel.old-includes.sorted

    comm -23 $tmp/Kernel.new-includes.sorted $tmp/Kernel.old-includes.sorted > $tmp/Kernel.includes.new
    comm -13 $tmp/Kernel.new-includes.sorted $tmp/Kernel.old-includes.sorted > $tmp/Kernel.includes.old
    comm -12 $tmp/Kernel.new-includes.sorted $tmp/Kernel.old-includes.sorted > $tmp/Kernel.includes.mixed

    for file in $(cat $tmp/Kernel.includes.new)
    do
        sed -i -E 's/#include <AK\/Debug\.h>/#include <Kernel\/Debug\.h>/' $file
    done

    for file in $(cat $tmp/Kernel.includes.mixed)
    do
        echo "mixed include in $file, requires manual editing."
    done
2021-01-26 21:20:00 +01:00
asynts
1a3a0836c0 Everywhere: Use CMake to generate AK/Debug.h.
This was done with the help of several scripts, I dump them here to
easily find them later:

    awk '/#ifdef/ { print "#cmakedefine01 "$2 }' AK/Debug.h.in

    for debug_macro in $(awk '/#ifdef/ { print $2 }' AK/Debug.h.in)
    do
        find . \( -name '*.cpp' -o -name '*.h' -o -name '*.in' \) -not -path './Toolchain/*' -not -path './Build/*' -exec sed -i -E 's/#ifdef '$debug_macro'/#if '$debug_macro'/' {} \;
    done

    # Remember to remove WRAPPER_GERNERATOR_DEBUG from the list.
    awk '/#cmake/ { print "set("$2" ON)" }' AK/Debug.h.in
2021-01-25 09:47:36 +01:00
Andreas Kling
928ee2c791 Kernel: Don't let signals unblock threads while handling a page fault
It was possible to signal a process while it was paging in an inode
backed VM object. This would cause the inode read to EINTR, and the
page fault handler would assert.

Solve this by simply not unblocking threads due to signals if they are
currently busy handling a page fault. This is probably not the best way
to solve this issue, so I've added a FIXME to that effect.
2021-01-21 00:14:56 +01:00
Andreas Kling
19d3f8cab7 Kernel+LibC: Turn errno codes into a strongly typed enum
..and allow implicit creation of KResult and KResultOr from ErrnoCode.
This means that kernel functions that return those types can finally
do "return EINVAL;" and it will just work.

There's a handful of functions that still deal with signed integers
that should be converted to return KResults.
2021-01-20 23:20:02 +01:00
Tom
1d621ab172 Kernel: Some futex improvements
This adds support for FUTEX_WAKE_OP, FUTEX_WAIT_BITSET, FUTEX_WAKE_BITSET,
FUTEX_REQUEUE, and FUTEX_CMP_REQUEUE, as well well as global and private
futex and absolute/relative timeouts against the appropriate clock. This
also changes the implementation so that kernel resources are only used when
a thread is blocked on a futex.

Global futexes are implemented as offsets in VMObjects, so that different
processes can share a futex against the same VMObject despite potentially
being mapped at different virtual addresses.
2021-01-17 20:30:31 +01:00
Tom
b17a889320 Kernel: Add safe atomic functions
This allows us to perform atomic operations on potentially unsafe
user space pointers.
2021-01-17 20:30:31 +01:00
Andreas Kling
01c2480eb3 Kernel+LibC+WindowServer: Remove unused thread/process boost mechanism
The priority boosting mechanism has been broken for a very long time.
Let's remove it from the codebase and we can bring it back the day
someone feels like implementing it in a working way. :^)
2021-01-16 14:52:04 +01:00