Skip to content

Several cores

ginnOS runs on computers with several cores (SMP). It starts all the cores, runs processes on each of them, moves work from busy cores to idle ones, and spreads device interrupts over the cores. The design follows Linux on x86, in a smaller form. It was built in steps (M0 to M5).

Step What it adds State
M0 data for each core built
M1 locks that work across cores built
M2 the other cores start built
M3 page table changes reach every core (TLB shootdown) built
M4 a run queue on each core, and the scheduler on all cores built
M5 load balancing, interrupts on all cores, the time of each core, a panic stops all cores built

Per-CPU data

Some state belongs to a core, not to a process: the process that the core runs, the ticks before the scheduler switches, and on x86_64 the stack pointers of the syscall entry. Each core has a cpu_t with this state, in the array cpus[CPU_MAX] (src/kernel/cpu/cpu.h). CPU_MAX is 64.

cpu_current() gives the cpu_t of the core that runs the code. A segment base points at it, so the call is one load:

Architecture Segment How it is set
x86_64 GS the MSR IA32_GS_BASE; swapgs exchanges it with the user's GS base at each change between user and kernel mode
i686 FS GDT entry 8 (GDT_KERNEL_PERCPU, 0x40), whose base is the cpu_t

The first field of a cpu_t points at the cpu_t itself, so cpu_current() reads GS:0 or FS:0. Linux uses the same two registers. User programs keep their thread-local storage in the other register: FS on x86_64, GS on i686.

hal_initialize() calls cpu_init_boot() right after the GDT is loaded, before anything else uses cpu_current().

x86_64: swapgs

While the kernel runs, the GS base is the cpu_t. While a program runs, it is the program's (0). The entries change it:

  • The interrupt entry (isr_common in asm64/isr.asm) reads the CS of the frame. When the CPU came from user mode, it does swapgs before anything else.
  • The syscall entry (asm64/syscall.asm) always comes from user mode. It does swapgs, saves the user stack pointer in the cpu_t, loads the kernel stack from the cpu_t, and continues in the interrupt entry after its swapgs.
  • The return (isr_exit) turns off interrupts, and does swapgs just before iretq when it returns to user mode. With interrupts off, no interrupt can enter the kernel with the program's GS base.
  • arch_jump_to_usermode, which starts the first program, does swapgs before its iretq.

i686: FS

The interrupt entry (asm/isr.asm) loads FS with GDT_KERNEL_PERCPU. The return loads FS with the program's data segment only when it returns to user mode; a return to kernel code keeps the per-CPU segment. The double-fault task loads it too, from its TSS.

Starting the other cores

At boot only one core runs: the boot core. The firmware stops the others (the application processors, APs) until the kernel starts them. The ACPI MADT gives the local APIC id of each core. smp_init() (src/kernel/cpu/smp.c) starts them in the MADT order, one at a time, after interrupts are on. The x86 part is in src/arch/x86/cpu/smp_boot.c. The sequence is the one in the Intel SDM, volume 3, 8.4, as in Linux.

The trampoline

A core starts in 16-bit real mode, at a page below 1 MiB. The kernel takes that page from the PMM right after pmm_init(), before anything else can use low memory (arch_smp_reserve()), and copies the trampoline to it. The trampoline is in asm/ap_trampoline.asm (i686) and asm64/ap_trampoline.asm (x86_64). It uses only offsets from its start, so it runs at any page.

The trampoline:

  1. Loads its own small GDT and goes to protected mode.
  2. Loads CR4, CR3 and CR0 from a data block at the end of the page. On x86_64 it also sets EFER.LME before CR0, which puts the core in long mode, and does a far jump to a 64-bit code segment.
  3. Jumps to smp_ap_entry() in the kernel, on the stack of the core.

CR0 and CR4 are copies of the boot core's values. CR3 is a temporary page table: a copy of the kernel half of the kernel's tables, with the trampoline page also mapped at its own address. When paging comes on, the core still runs from the low address, so that mapping must be there. On x86_64 the trampoline loads CR3 in 32-bit mode, so the table is below 4 GiB (the PMM gives only memory below 4 GiB).

The start sequence

For each core, the boot core:

  1. Gives it a cpu_t, a stack and a double-fault stack. The stacks come from the PMM, not from the kernel stack slots, which are for processes.
  2. Writes the stack and the cpu_t into the data block.
  3. Sends INIT, waits 10 ms, then sends a startup IPI (SIPI) with the page, twice, 200 us apart.
  4. Waits up to 100 ms for the core to set online in its cpu_t.

The waits use PIT channel 2 (pit_delay_us()), which counts without interrupts. A core that does not answer is logged, and the cores after it are not started: it can still start late and read the data block, so the boot core does not change the block again. In that case the trampoline and its page table stay. When all cores start, the boot core frees the temporary page table.

The kernel log gives the result, for example smp: 4 of 4 cores started, and /proc/cpuinfo lists the cores that run.

What each core sets up

smp_ap_entry() loads the kernel's page tables, then sets up the state that each core has for itself:

State Function
the GDT and the TSS (each core has its own) gdt_initialize(core)
the per-CPU segment base arch_cpu_set_base()
the IDT (one table, loaded on each core) idt_load_core()
the PAT (all cores must agree on the memory types) pat_init()
the FPU and SSE arch_fpu_init_core()
the MSRs of the syscall instruction (x86_64) syscall_init_core()
its double-fault stack in its TSS double_fault_init_core()
its local APIC apic_init_ap()

Each core has its own GDT and TSS because they hold per-core values: the kernel stack of an interrupt from user mode, the double-fault stack, the per-CPU segment (i686) and the TLS segment of the thread that runs (i686).

The local APIC timer of each AP runs at the rate the boot core measured, on its own vector, LOCAL_TIMER_VECTOR (0xEC, as in Linux). Only the boot core's timer, on the vector of IRQ 0, counts the system time.

Then the core calls cpu_ap_main(), which sets online and becomes the idle task of the core (see The scheduler on all cores).

Boot options

The kernel reads two options from its command line (the cmdline: line of a Limine entry):

Option What it does
nosmp start only the boot core
maxcpus=N start at most N cores, the boot core included

make run gives QEMU 4 cores. QEMU_SMP changes the number, for example make run QEMU_SMP=1.

Locks

Masking interrupts stops only the core that does it, so on several cores it is not a lock. Each piece of shared state has a spinlock (src/kernel/sync/spinlock.h).

Ticket spinlocks

spinlock_t is a ticket lock, as Linux had before its queued spinlocks. A core takes the next ticket with one atomic add, then spins with pause until the owner field is its ticket. The cores get the lock in the order they asked for it, so no core waits for ever.

The lock does not stop the timer, so a holder must have interrupts masked on its core: spin_lock_irqsave() masks them and takes the lock. spin_lock() is for code that has them masked already, such as an interrupt handler.

The lock records the core that holds it. In a debug build (BUILD_MODE=debug), assertions stop a core that takes a lock it holds or releases a lock it does not hold, and a core that spins for about a second panics with "spinlock: held too long".

The scheduler lock

sched_lock guards the run queues of all cores, the state of each process and the list of each wait queue. It is the innermost lock: code that holds it takes no other lock.

The context switch happens with sched_lock held, and the process that runs next releases it, as in Linux's finish_task_switch. A process that was switched out continues in schedule_locked() and its caller releases the lock. A new process releases it first thing, in scheduler_tail(): the idle task, a new program (process_entry_trampoline) and a fork child (isr_fork_return). So no other core can take a process from the queue while its registers are still being saved.

Sleeping without lost wakeups

A process that waits for a condition tests it with a lock held, then sleeps with wait_queue_block_locked(). That function puts the process on the queue with sched_lock held before it releases the caller's lock. A waker takes the caller's lock to change the condition, then sched_lock to wake, so it always finds the process on the queue.

Two other forms exist for conditions that no single lock guards:

  • wait_queue_wait_word() and timed_queue_wait_word() sleep only while a counter has the value the caller read before its test. A waker changes the counter, then wakes. waitpid uses it (the counter child_events), and so does poll (poll_snapshot()).
  • An interruptible sleep checks for a pending signal with sched_lock held. A sender sets the signal pending, then takes sched_lock to wake the process, so a signal between the test and the sleep is not lost.

A timed queue sets its deadline with sched_lock held, in the same step as the waiter goes on the queue, so a timer tick on another core cannot clear it in between.

The named locks

Lock Guards Linux
sched_lock the run queues, process states, wait queue lists, timed queue deadlines the run queue lock
signal_lock (signal_state_lock()) pending and blocked masks, handlers, stop and continue, the exit and exec state of a thread group, waitpid reports sighand->siglock
the process table lock the process table tasklist_lock
the page lock of a user space (vmas.lock) the areas and the page tables, against page faults in other threads mm->page_table_lock
a lock in each mutex the state of the mutex mutex->wait_lock
a lock in each futex bucket the check of the futex word and the sleep the futex hash bucket lock
a lock in each completion its done flag
the PCI config lock the config address and data ports pci_config_lock
the RTC lock the CMOS index and data ports rtc_lock
the xHCI event lock the event ring of a controller
the console lock the console, and a change of screen mode console_lock
the TLB flush lock the one TLB shootdown that is out the old i386 tlbstate_lock
the I/O APIC lock the select and window registers of the I/O APICs ioapic_lock

Reference counts (open user spaces, fd tables, file system contexts, signal handlers, the threads of a group) are atomics (src/kernel/sync/atomic.h). The timer tick count is a 64-bit atomic, so a read on i686 is not torn.

The lock order

A lock on the left can be held while the lock on its right is taken, never the other way round:

  • a mutex, then any spinlock
  • signal_lock, then the process table lock, then sched_lock
  • the lock of a wait_queue_block_locked() caller, then sched_lock
  • a futex bucket lock, then sched_lock
  • the page lock of a user space, then the frame allocator's lock
  • the page lock of a user space, then the TLB flush lock, which is the last lock: code that holds it takes no other
  • the heap lock, then the frame allocator's lock

A core that waits for a spinlock also does a TLB flush that another core asks of it (see TLB shootdown), because the holder of the lock can wait for that flush.

Where masking stays

Some code masks interrupts on its own core with no lock, because the state belongs to the core: the switch of the address space in execve, the copy of the FPU registers in sigreturn, the panic and power-off paths, and user_space_put() while it frees the space that the core uses.

TLB shootdown

Each core keeps recent translations of virtual to physical addresses in its TLB. When a page table entry is removed or loses a permission, the core that makes the change drops its own entry (invlpg), but another core can still hold the old entry and use it. The kernel must make those cores drop it too, and must not free the frame before they have: this is the TLB shootdown (src/kernel/memory/tlb.h).

Which cores

Each user space has a mask of the cores that have its page tables loaded (cpu_mask). Every change of address space goes through user_space_activate(), which sets the bit of the core before it loads CR3 and clears the bit of the old space after. A core that loads a space after a change reads the new entries, so only the cores in the mask can hold old ones.

Shootdown Cores Callers
tlb_shootdown_user(space, start, end) the other cores in the mask of the space munmap (in batches of 32 frames), mprotect, copy-on-write, fork
tlb_shootdown_kernel(start, end) all the other cores the free of a kernel stack

A permission that grows (a copy-on-write page that becomes writable) needs no shootdown: a core with the old read-only entry takes a page fault, which drops the entry, and the fault handler finds the page writable.

How a shootdown works

One shootdown is out at a time, under the TLB flush lock, as in the i386 flush_tlb_others of Linux 2.6. The caller:

  1. writes the range, and sets tlb_flush_pending in the cpu_t of each target core;
  2. sends each target an IPI on TLB_FLUSH_VECTOR (0xFC);
  3. waits until each target has flushed.

A target flushes the range with invlpg, page by page, or reloads CR3 when the range has more than 33 pages (Linux's tlb_single_page_flush_ceiling). The kernel uses no global pages, so a CR3 load drops every entry.

The caller can hold a spinlock with interrupts off while it waits. A target that waits for the same lock, also with interrupts off, cannot take the IPI. So a core that spins in spin_lock() also does a pending flush (tlb_poll()), and the caller gets its answer.

The scheduler on all cores

Each core has a run queue in its cpu_t (run_head, run_tail, run_count) and an idle task, and runs the processes of its own queue in turn. One lock, sched_lock, guards all the queues. Linux has a lock in each run queue; ginnOS can split the lock later if it is contended.

The idle task of the boot core and its stack come from the heap. On the other cores, the code that starts the core becomes its idle task, on the stack the core started on (scheduler_run_core()). The idle task is never in a queue, so it stays on its core.

Where a process runs

scheduler_ready_locked() picks a core with select_core():

  1. A process that ran before goes back to its last core if that core is idle, because the cache of the core can still hold its data.
  2. Else the first idle core gets it.
  3. Else a process that ran before goes to its last core, and a new process goes to the core with the fewest processes (running and queued).

Later, load balancing can move a process that waits in a queue to another core.

Load balancing

scheduler_pull_locked() moves one process from the queue of the busiest other core to the queue of the calling core. The load of a core is the processes in its queue, plus one if it runs a process. The pull takes the head of the queue: that process waited the longest, so the cache of its core is the least likely to still hold its data. Two cases call it, a small form of Linux's balance between run queues:

When Pulls if
a core has nothing to run (its process sleeps or exits, or the idle task's slice ends) another core has a process in its queue
a busy core, each 10 ticks (100 ms) another core has at least two more processes than this core

The second rule stops two cores with nearly the same load from moving a process to and fro. With sched_lock held, no process in a queue is on a core, because a switch away from a process ends before the lock is released. So a process can move between queues at any time under the lock.

Waking an idle core

An idle core halts until an interrupt. When another core puts a process in its queue, it sends the idle core a reschedule IPI on RESCHEDULE_VECTOR (0xFD, as in Linux). The idle loop tests its queue with interrupts off and then runs sti; hlt (arch_safe_halt()), so an IPI that comes after the test still ends the halt. A busy core takes the new process at its next tick.

Time slices

The local APIC timer of each core calls scheduler_tick() for that core and counts the time of the process that runs there. The timer of the boot core also counts the system time (IRQ 0). If the boot core falls back to the PIT, the other cores have no timer: they cannot end a time slice, so they run no processes and only halt.

Exit and the kernel stack

An exit marks the process a zombie and wakes the parent before the core switches away from the kernel stack of the process. The parent can run waitpid on another core at once. So each process has an on_cpu flag, as in Linux: the switch to the process sets it, and the next process on that core clears it when the switch has ended (finish_switch()). process_destroy() waits until on_cpu is clear before it frees the stack.

The kernel reaps orphan zombies on any core. It takes each one under the process table lock and marks it reaped, so two cores cannot free the same zombie, and it leaves a zombie whose on_cpu is still set for a later pass.

A thread that exits loads the kernel's page tables before it drops its reference to the user space, because another thread on another core can drop the last reference and free the page tables at once.

Signals to a thread on another core

A thread acts on a signal when it returns to user mode. If the thread runs on another core, the sender sends that core a reschedule IPI (scheduler_kick(), Linux's kick_process). The return from the IPI delivers the signal, so the thread does not run to the end of its time slice first.

Interrupts on all cores

At boot, the drivers set up their interrupts before the other cores start, so all of them go to the boot core. After smp_init(), irq_spread() (src/kernel/irq/irq.c) gives each one a core, in turn from core 1. Linux also gives each interrupt one core. IRQ 0 (the PIT) stays on the boot core, which counts the system time.

Kind What changes
an ISA IRQ line, or a PCI INTx line the destination field of its I/O APIC entry
an MSI the message address (one 32-bit config write)
an MSI-X the address of table entry 0, with the entry masked during the change

Each vector has one handler for all cores (there is one IDT), so only the destination changes. An interrupt that comes during the change goes to the old core or to the new one, and both handle it the same way. The last column of /proc/interrupts gives the core of each device.

Device handlers can now run on two cores at the same time. Their state already has locks (see The named locks). The entropy pool that each interrupt adds to is one for each core, as in Linux, so it needs no lock.

The time of each core

Each core counts its timer ticks in its cpu_t (times): user code (of a process with nice 0 or less), user code with nice 1 or more, kernel code, and the idle task. /proc/stat gives them in the format of Linux, in ticks of 10 ms:

cpu  1200 0 300 3500 0 0 0 0 0 0
cpu0 200 0 100 2200 0 0 0 0 0 0
cpu1 1000 0 200 1300 0 0 0 0 0 0

The first line is the sum of all cores. The idle time in /proc/uptime is also the sum of all cores, as in Linux, so it can be more than the uptime. Huginn reads /proc/stat and shows the use of each core on its Resources tab.

A panic

The first core that panics sends each other core an NMI, as Linux does when a core does not answer its stop IPI. An NMI comes also when a core has interrupts off, for example while it holds a spinlock. The NMI handler of the other cores sees the panic and halts the core, so the panic message stays on the screen and the state it prints does not change. A core that panics while another core's panic is in progress only halts.

Limits

  • One lock, sched_lock, guards all the run queues. Linux has a lock in each queue.
  • A process cannot be bound to a core (there is no sched_setaffinity).
  • The balance does not look at the cache or at the NUMA layout of the cores, and it does not move a process that runs.
  • The system time comes from the timer of the boot core only.