Skip to content

Scheduler and threads (kernel/sched/)

Source: kernel/sched/

Threading::Thread is a flow of execution with its own stack and saved registers; Threading::Scheduler decides which thread runs on the CPU and switches between them. atlOS has one CPU and a cooperative scheduler. The scheduler runs threads only: which process a thread belongs to is the business of kernel/proc, not the scheduler's.

What is it for?

A CPU runs one instruction stream at a time. To let several activities make progress (a shell, a disk driver waiting for data, a timer job) the kernel keeps each one's state — registers, stack pointer, where it stopped — in a thread control block (TCB) and switches the CPU from one TCB to another. That switch is the context switch; choosing who runs next is scheduling.

The big question is when a switch happens.

How could it be designed?

Model When does a thread give up the CPU Plus Minus Used by
Cooperative only when it calls yield, sleep, block or ends simple; no locks needed between threads; switches only at known points one thread that never yields freezes everything classic Mac OS, Windows 3.x, many embedded/RTOS loops, coroutines
Preemptive also when the timer interrupt says its time slice is over a busy thread can not starve others; needed for untrusted (user) code every shared structure needs locking; switches can happen anywhere Linux, Windows NT, xv6

Choosing the next thread:

Policy Idea
Round robin everyone in turn
Priorities higher priority first (risk: starvation)
Multilevel feedback queue priorities that adapt to behavior
CFS (Linux) fair share of CPU time, red-black tree by "virtual runtime"

Where the thread list lives:

Approach Plus Minus Used by
A fixed array of TCB pointers simplest; an index is an id a hard limit; removing shifts entries early toy kernels, xv6 (proc[NPROC])
A linked list through the TCBs (intrusive) no limit but memory; adding and removing allocate nothing and can not fail walking it is O(n) Linux (list_head in task_struct)
Per-CPU run queues, trees by runtime scale to many CPUs and threads much more code Linux CFS/EEVDF (red-black tree), Windows (per-priority lists)

When nothing can run:

Approach Plus Minus Used by
The scheduler halts (hlt) in a loop, on the stack of whoever called it no extra thread the scheduler needs a "nobody" case; idle time belongs to no one xv6 (its per-CPU scheduler loop)
An idle thread that is always runnable and halts the queue always has someone to run; idle time is the idle thread's CPU time one more thread and stack Linux (the idle task, pid 0, one per CPU), Windows (System Idle Process)

Measuring CPU time:

Approach How Plus Minus Used by
Tick sampling each timer tick is charged to the task running when it arrives one increment in the timer interrupt 1 ms resolution; a task that always runs between two ticks is never charged classic Unix, Linux with tick based accounting
Measuring at switches read a cycle counter (TSC) when a task starts and stops, add the difference exact, also for runs shorter than a tick needs the counter's frequency (calibrated against a timer) Linux CFS (sched_clock), most modern kernels

How atlOS does it

Cooperative round robin over an intrusive list. It is the smallest scheduler that still shows every essential piece (TCB, context switch, states, sleeping, blocking). Because a thread only loses the CPU where it calls the scheduler, kernel code needs no locks against other threads; the price is that every thread must cooperate.

  • Scheduler(TickSource&, AddressSpace&) (scheduler.hpp): the flow that constructs it becomes task 0 (it has a TCB but no Thread object; for the kernel's scheduler that is kernelMain), its idle thread task 1 (the stack comes from the address space). The timer only counts ticks; it never switches threads.
  • The tasks: Utils::IntrusiveList<TCB, &TCB::schedulerLink> m_tasks, a ring through the TCBs themselves (kernel/lib/intrusive_list.hpp, the idea of Linux's list_head): each TCB carries the links (schedulerLink), so queueing a thread allocates nothing and there is no limit but memory. schedule() walks from the task after the current one around the ring and switches to the first runnable one, leaving the idle thread out.
  • States: Ready, Running (runnable) and Sleeping (until wakeTick), Blocked (until unblock), Terminated (skipped, then dequeued).
  • Nothing else runnable → the idle thread. Its loop turns interrupts off, yields (anyone runnable gets the CPU), then sti; hlt until the next interrupt. Interrupts stay off from the check to the halt: a wake up in between is not missed, and sti takes effect only after hlt has started. Task 0 and the idle thread never leave the queue: they are always first and second (bootTask(), idleTask()).
  • A thread waiting under a Sync::InterruptGuard gets its interrupts back off: switchTask saves and restores rflags with the other registers.
  • Each TCB has a name (kernel for task 0, idle, t1, t2, ... for threads, the file name for a user program's thread), its stack range, an id (Abi::ThreadId: the process id above, a number below; kernel threads are process 0: 0.1, 0.2, ..., the boot flow 0.0), an owner (the user program's process; nullptr: process 0, the kernel) and a pointer back to its Thread.
  • On every switch the scheduler puts the next thread's stack top into the TSS (rsp0): interrupts and system calls from ring 3 use it. The saved cr3 switches the address space with the thread.
  • Waiting for an event (not a time) goes through kernel/sync/: a WaitQueue blocks threads and unblocks them, see kernel/sync/README.md.
  • The current task (Threading::currentTask()): the TCB running now. Each switch sets it, each TCB knows its scheduler (tcb.scheduler). Code finds "this thread" and its scheduler from it instead of being handed a scheduler: Threading::yield(), sleep(ms), exitThread(code), currentThread(), the sync objects, Thread(entry), the system calls. There is still no global scheduler: several can exist (the self tests build their own on a fake tick source), and the current task says which one runs. See The current task below.
  • Each Thread gets a 2 MB stack page from the AddressSpace it is given; the initial stack is laid out like "just after a call", as the System V ABI requires (rsp % 16 == 8 on entry). Its rbp starts at 0, which ends a panic backtrace at the top of the thread.

CPU time

Tick sampling. The timer interrupt adds 1 to cpuTicks of the task the scheduler is running (m_running, set on every switch) and to the clock. Every tick belongs to someone, so the cpuTicks of all tasks add up to ticks(); the idle thread's share is the time the CPU halted. runs counts how often a task was switched to, switchCount() all switches.

It is a sample, not a measurement: a thread that works 0.3 ms and yields is charged a whole tick when one arrives, nothing otherwise; over many ticks it evens out. Measuring with the TSC at every switch would be exact, at the price of calibrating the TSC.

The shell reads the counters with interrupts off, so the clock and the tasks come from the same moment:

atlOS:/> sched
up 2.224 s, 100 context switches
   tid    name         state       cpu ms    cpu     runs
  *0.0    kernel       running        170   7.6%       51
   0.1    idle         ready         2054  92.3%       50
atlOS:/> top 200
201 ms, 2 context switches
   tid    name         state       cpu ms    cpu     runs
  *0.0    kernel       running          1   0.4%        1
   0.1    idle         ready          200  99.5%        1

sched counts since boot; top [ms] samples the counters, sleeps for the window and shows the differences. The shell sleeps meanwhile, so the window shows what the other tasks (here only the idle thread) did.

The context switch (arch/x86_64/cpu/context.S)

switchTask(from, to) stores every general purpose register, rflags, rsp, the return address and cr3 into from->regs, loads the same from to->regs, pushes the saved rip on the new stack and rets into it. A new thread's saved rip is ThreadImpl::threadStartPoint with the ThreadImpl* in rdi, so its first "return" starts it. threadStartPoint calls entry(arg) and passes what it returns to exitThread.

Exit codes and waiting

A thread's entry is int64_t entry(void* arg): it gets the argument it was started with, and what it returns is its exit code, as if it called exitThread(code). Thread::wait() sleeps until the thread has ended and returns that code; again later it returns the same code at once.

sequenceDiagram
    participant W as waiting thread
    participant T as Thread t
    participant S as Scheduler
    W->>T: t.wait(): not ended yet
    T->>T: sleep on t's WaitQueue
    S->>T: t runs, its entry returns 42
    T->>T: exitThread(42): code = 42, ended, wake the waiters
    T->>S: Scheduler::exit(): Terminated, off the list at the switch
    S->>W: W runs (after t is gone from the CPU)
    W->>W: wait() returns 42; delete t is safe now

The ended thread wakes its waiters before it leaves the CPU, but with a cooperative scheduler they can only run after it has switched away for the last time, so a waiter may delete it at once.

The destructor waits (std::jthread does the same): deleting a Thread that is still queued and has not ended waits for it first, so a thread is never freed while it may still run. A thread taken off with Scheduler::removeTask, or never queued, is freed at once. That is how a scheduler deletes its idle thread, which never ends.

Deliberately not done

  • No preemption. User mode will probably need it: a user program that never yields would freeze the system.
  • No priorities and no groups: every thread of every process is in one pool, and a process with more threads gets more of the CPU. No SMP (one run queue per CPU later, each with its idle thread).
  • The scheduler walks the whole list to wake sleepers and to find the next runnable thread: O(n) per switch.
  • CPU time is sampled per tick, not measured (no TSC).
  • The context switch saves all registers; the System V ABI would allow saving only the callee-saved ones (rbx, rbp, r12–r15). Saving all is easier to reason about.
  • No SIMD state is saved (the kernel is built without SSE).

Using it

#include <sched/scheduler.hpp>
#include <sched/thread.hpp>

int64_t worker(void* arg)
{
    auto rounds = reinterpret_cast<int64_t>(arg);
    for (int64_t i = 0; i < rounds; i++) {
        doSomething();
        Threading::yield(); // the running thread's scheduler
    }
    return rounds; // the exit code: returning ends the thread
}

auto* t = new Threading::Thread(worker, reinterpret_cast<void*>(10)); // on the caller's scheduler, queued
int64_t code = t->wait(); // 10, once worker has returned
delete t;                 // would wait too, had nobody waited

User programs have the same class with the same names (User::Threading::Thread, see user/README.md).

  • Thread(entry, arg) uses the caller's scheduler and the kernel address space; Thread(scheduler, space, entry, arg) names both (the self tests use it for their own schedulers). Thread(..., arg, false) creates it without queueing it.
  • The Thread object stays valid after its entry returns, until its owner deletes it. A thread must not delete or wait for itself.
Call (Scheduler) Effect
yield() run the next runnable thread; returns at once if there is none
sleep(ms) Sleeping for at least ms ticks
block() / unblock(tcb) Blocked until another thread (or an IRQ handler) calls unblock
exit() end the current thread (task 0 must not); threads end through exitThread, which also wakes their waiters
removeTask(thread) take a queued thread off, it does not run again
current() TCB of the running thread
ticks() ticks (ms) since construction
taskCount() number of queued tasks, including task 0 and the idle thread
switchCount() context switches since construction
firstTask(), nextTask(tcb) the tasks in queue order: name, state, id, cpuTicks, runs, ...
bootTask(), idleTask() task 0 and the idle thread
Call (Thread) Effect
wait() sleep until it has ended, then its exit code
hasEnded() its entry returned or it called exitThread
id() its Abi::ThreadId
Free function (Threading::) Effect
yield(), sleep(ms) on the running thread's scheduler
exitThread(code) end the running thread with code
currentThread() the running thread's id

The current task

Code that blocks or wakes a thread (a wait queue, a semaphore, a mutex, a new thread, a system call) needs two things: the thread that is running now (to block it) and the scheduler of a given thread (to make it runnable again). Most kernels keep exactly that: Linux has current, xv6 has myproc(). In atlOS:

currentTask()        TCB of the running task          set by Scheduler::switchTo
tcb.scheduler        the scheduler that runs a TCB    set by addTask (task 0: the constructor)
currentScheduler()   currentTask().scheduler
sequenceDiagram
    participant T as thread A
    participant Q as WaitQueue
    participant S as A's scheduler
    participant I as IRQ handler
    T->>Q: wait()
    Q->>Q: self = currentTask()
    Q->>S: self.scheduler->block()
    S->>S: switch to another task (currentTask() = it)
    I->>Q: wakeOne()
    Q->>S: tcb->scheduler->unblock(tcb)

So a Semaphore, Mutex or ConditionVariable is a plain value (Semaphore sem(0, 1);) and one object works for threads of any scheduler; Thread(entry) goes to the caller's scheduler.

It is a boundary global (docs/style.md): one CPU runs one task at a time, so "the current task" is a fact about the CPU. With several CPUs it is one value per CPU (read through gs).

Schedulers nest: a scheduler constructed by a flow makes that flow its task 0, so currentTask() is its boot TCB from then on; its destructor gives the previous task back. The self tests build schedulers this way inside the kernel's task 0.

Flow: two threads yielding

sequenceDiagram
    participant M as task 0 (kernelMain)
    participant S as Scheduler
    participant A as thread A
    participant B as thread B
    M->>S: yield()
    S->>A: switchTask(task0, A)
    A->>S: yield()
    S->>B: switchTask(A, B)
    B->>S: sleep(10)
    Note over B: Sleeping until tick + 10
    S->>M: switchTask(B, task0)
    Note over S: every tick: PIT IRQ -> m_ticks.fetchAdd(1)
    M->>S: yield()
    S->>A: (B still sleeping, skipped)

Thread states

stateDiagram-v2
    [*] --> Ready: new Thread(scheduler, space, entry)
    Ready --> Running: picked by schedule()
    Running --> Ready: yield()
    Running --> Sleeping: sleep(ms)
    Sleeping --> Ready: tick >= wakeTick
    Running --> Blocked: block()
    Blocked --> Ready: unblock(tcb)
    Running --> Terminated: entry returns / exitThread(code)
    Terminated --> [*]: removed from the queue; wait() returns the code, owner deletes the Thread

Tests

kernel/tests/selftest.cpp: Scheduler round robin / sleep (fake ticks) / block / remove (isolated) run on their own schedulers with a FakeTickSource, so sleeping is checked tick by tick; Scheduler idle thread and CPU time (isolated) charges fake ticks to the caller and to a thread, checks runs, the switch count and that the tasks' ticks add up to the clock; Scheduler sleep (kernel, real ticks) uses real time, and the idle thread gets the ticks of the sleep; Thread stack checks the ABI alignment and that the stack page is freed. Scheduler remove takes a thread off before it runs, and deletes a queued one (the destructor waits: it runs to its end first). Thread arguments, exit codes and wait passes an argument in and gets the return value out of wait, ends a thread with exitThread in the middle, and checks the ids of kernel threads (process 0) and currentThread(). Scheduler and WaitQueue without a limit runs 40 threads, all waiting on one queue, and gets each one's exit code. Intrusive list checks the list on its own. The shell tests run tasks, sched and top.

References

  • OSDev Wiki: Cooperative Multitasking, Context Switching, Scheduling Algorithms
  • Operating Systems: Three Easy Pieces: "Limited Direct Execution", "Scheduling: Introduction", "Scheduling: The Multi-Level Feedback Queue"
  • xv6 book (MIT 6.1810): chapter "Scheduling"
  • System V AMD64 ABI: stack alignment and callee-saved registers
  • Linux: include/linux/list.h (list_head, container_of)