Your Program Owns the CPU. The Operating System Is Not Running.

CPU series, post 1 of 5

The operating system is not running right now.

Not on the core that is executing your code. That core belongs to your program, one instruction after another, with no supervisor standing behind it. The kernel sits in memory and does nothing until hardware forces it back in. Without that force, a single while (1); would hold the machine until someone pulled the plug.

So what forces it back? Three things. Gates that compute. A loop that fetches. A timer that interrupts. This post builds each one in code and runs it. Every sample comes with its real output, and every model is labeled as a model.

Every measurement in this series ran on one machine: a 2-vCPU cloud VM, Intel Xeon at 2.1 GHz, Linux 6.18, CONFIG_HZ=250. Your numbers will differ. That is the reason to run them.

Gates compute, and nine NANDs make a full adder

Start at the bottom, but do not stay long. A transistor is a switch that voltage controls. Wire a few into a NAND gate and you hold the only part you strictly need, because every other logic gate can be built from NAND gates alone.

Now make the gates add. Take two one-bit inputs, A and B, plus a carry coming in, Cin. The sum bit and the carry out are:

sum  = A XOR B XOR Cin
cout = (A AND B) OR (Cin AND (A XOR B))

On paper that is five gates of three kinds: two XORs, two ANDs and an OR. In NAND-only form it is nine. The script below builds the nine-gate version, chains eight of them into a ripple-carry adder, and wraps an ALU around the adder. Each wire carries a value and a depth, so the script counts gate delays as well as gates.

# nand_alu.py: a full adder, a ripple-carry adder and a small ALU, all built from one gate: NAND.

class Sig:
    """A wire: its logic value, and how many gate delays after the inputs it settles."""
    def __init__(self, v, d=0):
        self.v, self.d = v, d

GATES = 0

def nand(a, b):
    global GATES
    GATES += 1
    return Sig(1 - (a.v & b.v), max(a.d, b.d) + 1)

def not_(a):    return nand(a, a)
def and_(a, b): return not_(nand(a, b))
def or_(a, b):  return nand(not_(a), not_(b))

def xor_(a, b):
    t = nand(a, b)
    return nand(nand(a, t), nand(b, t))

def full_adder(a, b, cin):
    t1 = nand(a, b)
    p = nand(nand(a, t1), nand(b, t1))        # p = a XOR b, sharing t1
    t5 = nand(p, cin)
    s = nand(nand(p, t5), nand(cin, t5))      # s = p XOR cin
    return s, nand(t1, t5)                    # (sum, carry out)

def ripple_add(a, b, cin):
    out, carry = [], cin
    for x, y in zip(a, b):                    # each carry waits for the stage before it
        s, carry = full_adder(x, y, carry)
        out.append(s)
    return out, carry

def bits(x, w):  return [Sig((x >> i) & 1) for i in range(w)]
def value(sigs): return sum(s.v << i for i, s in enumerate(sigs))

def alu(op, x, y, w=8):
    a, b = bits(x, w), bits(y, w)
    if op == "SUB":
        b = [not_(s) for s in b]              # A - B = A + ~B + 1
    if op in ("ADD", "SUB"):
        r, carry = ripple_add(a, b, Sig(1 if op == "SUB" else 0))
    else:                                     # the opcode picks one unit: a multiplexer
        gate = {"AND": and_, "OR": or_, "XOR": xor_}[op]
        r, carry = [gate(p, q) for p, q in zip(a, b)], Sig(0)
    res, yy = value(r), value(b)
    arith = op in ("ADD", "SUB")
    flags = dict(Z=int(res == 0), N=res >> (w - 1), C=carry.v,
                 V=(((x ^ res) & (yy ^ res)) >> (w - 1)) & 1 if arith else 0)
    return res, flags

if __name__ == "__main__":
    GATES = 0
    s, c = full_adder(Sig(1), Sig(1), Sig(1))
    print(f"full adder: {GATES} NAND gates, sum settles at depth {s.d}, carry out at depth {c.d}")

    ok = sum(alu(op, x, y)[0] == f(x, y) & 255
             for x in range(256) for y in range(256)
             for op, f in (("ADD", lambda p, q: p + q), ("SUB", lambda p, q: p - q)))
    print(f"exhaustive 8-bit check: {ok} of {2 * 256 * 256} ADD and SUB results match Python")

    for w in (8, 16, 32, 64):
        r, _ = ripple_add(bits(0, w), bits(0, w), Sig(0))
        print(f"{w:2d}-bit ripple adder: last sum bit settles after {max(s.d for s in r)} NAND delays")

    for op, x, y in (("ADD", 200, 100), ("ADD", 100, 100), ("SUB", 5, 5), ("SUB", 3, 5), ("XOR", 0xF0, 0xFF)):
        res, f = alu(op, x, y)
        print(f"{op} {x:3d} {y:3d} -> {res:3d}  " + " ".join(f"{k}={v}" for k, v in f.items()))
full adder: 9 NAND gates, sum settles at depth 6, carry out at depth 5
exhaustive 8-bit check: 131072 of 131072 ADD and SUB results match Python
 8-bit ripple adder: last sum bit settles after 20 NAND delays
16-bit ripple adder: last sum bit settles after 36 NAND delays
32-bit ripple adder: last sum bit settles after 68 NAND delays
64-bit ripple adder: last sum bit settles after 132 NAND delays
ADD 200 100 ->  44  Z=0 N=0 C=1 V=0
ADD 100 100 -> 200  Z=0 N=1 C=0 V=1
SUB   5   5 ->   0  Z=1 N=0 C=1 V=0
SUB   3   5 -> 254  Z=0 N=1 C=0 V=0
XOR 240 255 ->  15  Z=0 N=0 C=0 V=0

Read the output from the top. Nine NANDs per full adder. Then an exhaustive check: every one of the 65,536 input pairs went through ADD and SUB, and none disagreed with Python’s own arithmetic. At 8 bits you can afford to test everything, so do.

The depth lines carry the real lesson. The last sum bit settles after 20 NAND delays at 8 bits, 36 at 16, 68 at 32 and 132 at 64. Every extra bit adds two delays, because a carry cannot skip a stage. Real CPUs compute carries ahead of time with lookahead logic instead of letting them ripple.

Now the ALU lines. The dictionary lookup in alu() plays the multiplexer: the opcode picks which unit’s result comes through. SUB costs one inverter per bit and a carry-in of 1, because A plus the inverse of B plus 1 equals A minus B in two’s complement. 5 minus 5 gives 0 and sets Z. 3 minus 5 gives 254, which is minus 2 in 8 bits, and sets N. The carry out of 0 on that line means a borrow happened. Architectures disagree on whether the flag stores the carry or its inverse, so read your manual before you branch on it.

The ADD lines show two different failures. 200 plus 100 wraps to 44 and raises the carry flag: the unsigned answer does not fit. 100 plus 100 gives 200, which fits as unsigned but reads as minus 56 when signed, so the overflow flag V fires. Every conditional branch you have ever written reads one of these flags.

Nine NAND gates make a full adder, and the carry ripples
Figure 1.1. Nine NAND gates make a full adder, and the carry ripples. The two Cin labels are one net.

For the full build, from NAND gates to a working CPU, work through Nand2Tetris or read Charles Petzold’s Code.

The CPU runs one loop, forever

Registers hold the numbers being worked on. One special register, the program counter, holds the address of the next instruction. The CPU repeats three steps. Fetch: send the program counter to memory, receive an instruction, advance the counter. Decode: read the opcode bits and decide which ALU operation, which registers, which memory access. Execute: do it, and write the result back.

At 3 GHz one clock cycle lasts about 0.33 nanoseconds. Real cores overlap many instructions through pipelining and issue several per cycle, so this loop is a model, not a literal photograph. Keep the model anyway, because it hands you one fact. There is a clean moment between instructions when the CPU can safely change course. At that boundary the hardware asks one extra question, and with a few restartable exceptions such as long string copies, it asks it every time. Is anything demanding attention?

That question is the interrupt check. Nothing in your program writes it. It is wired in.

Three words get mixed up here. An interrupt arrives from outside the instruction stream, from a timer, a network card or a disk. An exception comes from inside it, such as a divide by zero or a forbidden instruction. A trap is an exception you raise on purpose, like a system call. Textbooks sort them differently, but the entry mechanism is the same. Only the cause differs.

Who stops an infinite loop?

Take the loop from the top of this post. while (1); compiles to a jump that targets itself. It makes no system call. It waits on no I/O. It never asks the kernel for anything, and the kernel cannot ask it for anything either, because the kernel is not running.

Early systems answered with trust. Under cooperative multitasking, the OS expected each program to hand the CPU back, by making a system call or by yielding on purpose. OSTEP’s chapter on limited direct execution lists early versions of Mac OS in that group, and it states the consequence plainly. A process that loops forever never returns control. The OS’s only recourse is to reboot the machine.

Trust is not a mechanism, so build the mechanism in miniature. The script below is a CPU with a two-instruction ISA, a program counter per process, and a countdown timer that the CPU checks between instructions. When the check fires, a stand-in for the kernel saves the running process and resumes the next one. It is about 50 lines. It is a model, not an x86 emulator.

# toy_cpu.py: fetch, decode, execute, and an interrupt check between instructions.

class Proc:
    def __init__(self, name, prog):
        self.name, self.prog, self.pc, self.ran, self.alive = name, prog, 0, 0, True

SPIN = [("INC",), ("JMP", 0)]          # while (1) count++;
MASK = [("CLI",), ("JMP", 0)]          # try to switch the timer off, then loop

def next_alive(procs, cur):
    for k in range(1, len(procs) + 1):
        i = (cur + k) % len(procs)
        if procs[i].alive:
            return i

def run(procs, period, cycles):
    cur, left, entries, log = 0, period, 0, []
    for t in range(cycles):
        if cur is None:
            break
        if period and left == 0:                          # interrupt check, between instructions
            nxt = next_alive(procs, cur)
            log.append(f"t={t:3d} KERNEL timer irq: saved {procs[cur].name} pc={procs[cur].pc}, resume {procs[nxt].name}")
            cur, left, entries = nxt, period, entries + 1
            continue                                      # the kernel used this cycle
        p = procs[cur]
        op = p.prog[p.pc]                                 # fetch
        if op[0] == "CLI":                                # privileged: user mode faults
            p.alive = False
            log.append(f"t={t:3d} KERNEL fault: {p.name} executed CLI in user mode, killed")
            cur, entries = next_alive(procs, cur), entries + 1
            continue
        p.pc = op[1] if op[0] == "JMP" else p.pc + 1      # decode and execute
        p.ran += 1
        left -= 1
    return log, entries

def demo(title, procs, period, cycles):
    log, entries = run(procs, period, cycles)
    print(f"== {title}")
    for line in log[:3]:
        print("  " + line)
    if len(log) > 3:
        print(f"  ... {len(log) - 3} more kernel entries")
    print("  " + ", ".join(f"{p.name} ran {p.ran}" for p in procs) + f"; kernel entries: {entries}")

if __name__ == "__main__":
    demo("no timer, A loops forever", [Proc("A", SPIN), Proc("B", SPIN)], 0, 60)
    demo("timer every 8 instructions", [Proc("A", SPIN), Proc("B", SPIN)], 8, 60)
    demo("C tries to mask the timer", [Proc("A", SPIN), Proc("C", MASK)], 8, 60)
== no timer, A loops forever
  A ran 60, B ran 0; kernel entries: 0
== timer every 8 instructions
  t=  8 KERNEL timer irq: saved A pc=0, resume B
  t= 17 KERNEL timer irq: saved B pc=0, resume A
  t= 26 KERNEL timer irq: saved A pc=0, resume B
  ... 3 more kernel entries
  A ran 30, B ran 24; kernel entries: 6
== C tries to mask the timer
  t=  8 KERNEL timer irq: saved A pc=0, resume C
  t=  9 KERNEL fault: C executed CLI in user mode, killed
  t= 18 KERNEL timer irq: saved A pc=0, resume A
  ... 4 more kernel entries
  A ran 53, C ran 0; kernel entries: 7

Three runs, three lessons. Run one has no timer. A runs 60 instructions, B runs none, and the kernel is entered zero times. A never calls anything, so nothing ever hands control back. That is cooperative multitasking, and it is the original failure.

Run two arms the timer for every eight instructions. The kernel gets control at t=8, saves A at pc=0, resumes B, and repeats. Neither process called the kernel. The interrupt check did.

Run three adds a process that tries CLI, the instruction that masks interrupts. In the model, user mode may not execute it, so the CPU faults and the kernel kills the process. C ran zero instructions of its own. Keep that one in mind for the timer section.

Flowchart of the toy CPU loop with its interrupt check
Figure 1.2. One cycle of the toy CPU, with the interrupt check before every fetch.

Rings, trap tables and one controlled door

x86 defines four privilege rings, 0 through 3. Mainstream operating systems use two. The kernel runs in ring 0 and your program runs in ring 3. In ring 3 a set of instructions is simply forbidden: loading a new page-table base, halting the core, masking interrupts, rewriting the interrupt table. Try one and the CPU raises a fault that jumps into the kernel, which usually ends your process. That is the CLI run from the model. The Intel SDM, Volume 3A, covers the rules in full.

How does a ring 3 program ask for a file, then? Through a door the kernel built. The syscall instruction raises the privilege level and jumps to one address the kernel registered at boot. Your program cannot choose the landing spot. Interrupts follow the same pattern. The kernel fills an interrupt descriptor table, and the hardware looks up the handler there. OSTEP calls the whole arrangement limited direct execution. Programs run directly on the hardware, which is fast. The hardware limits what they can do, which is safe.

One correction before Post 4 needs it. You will hear that hypervisors run in “ring -1”. That is shorthand. Intel’s VT-x adds a separate axis, root and non-root mode, that sits beside the rings and does not replace them.

The timer is the one clock the kernel always wins

At boot, before it launches your first process, the kernel does two privileged things. It installs its trap table, and it arms a timer. OSTEP’s protocol table lists both steps in the same boot sequence.

The timer’s job is simple. After X milliseconds it raises an interrupt. The CPU finishes the current instruction, switches to the kernel stack, saves the user program’s stack pointer, flags and instruction pointer, moves to ring 0, and jumps to the handler through the descriptor table. Your program does not get a vote.

On a modern x86 core the timer lives inside the core as the Local APIC timer. Linux commonly programs it in TSC-deadline mode where the CPU supports it: software writes a target value for the timestamp counter, and the interrupt fires when the counter reaches it. The Intel SDM describes the one-shot, periodic and TSC-deadline modes. On modern x86 Linux, the old 8254 chip from early PCs no longer does this job.

How often does it fire? In the classic periodic design Linux ticks between 250 and 1,000 times per second, set at build time by CONFIG_HZ (arXiv 2509.03855). That is 1 to 4 milliseconds apart. At 3 GHz, 1 millisecond is 3,000,000 cycles and 4 milliseconds is 12,000,000. Your program executes millions of instructions before the kernel so much as glances at it.

Ticks burn power and interrupt useful work, so Linux can stop them. Idle CPUs skip them under NO_HZ. With NOHZ_FULL a busy CPU can run without ticks as well, although the same paper notes that some bookkeeping ticks can still occur.

Now measure it. The next program pins itself to one CPU and spins on the clock, logging every moment two consecutive reads land more than 2 microseconds apart. Those are the moments something else owned the core. When it finishes, it asks the kernel how many timer interrupts that CPU handled.

// tick_detector.c: spin on one CPU. Count every time something took the core away, then ask the kernel what it did.
#define _GNU_SOURCE
#include <sched.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX_GAPS (1 << 20)
static uint64_t len[MAX_GAPS];

static inline uint64_t now_ns(void) {
    struct timespec t;
    clock_gettime(CLOCK_MONOTONIC, &t);
    return (uint64_t)t.tv_sec * 1000000000ull + t.tv_nsec;
}

static int cmp(const void *a, const void *b) {
    uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b;
    return (x > y) - (x < y);
}

// Local timer interrupts the kernel has counted on this CPU (the LOC row of /proc/interrupts).
static long loc_count(int cpu) {
    FILE *f = fopen("/proc/interrupts", "r");
    char line[4096], *p;
    long v = -1;
    while (f && fgets(line, sizeof line, f)) {
        if (!(p = strstr(line, "LOC:"))) continue;
        p += 4;
        for (int i = 0; i <= cpu; i++) v = strtol(p, &p, 10);
        break;
    }
    if (f) fclose(f);
    return v;
}

int main(int argc, char **argv) {
    double secs = argc > 1 ? atof(argv[1]) : 3.0;
    cpu_set_t set;
    CPU_ZERO(&set);
    CPU_SET(1, &set);
    sched_setaffinity(0, sizeof set, &set);              // stay on one CPU

    long loc0 = loc_count(1);
    uint64_t prev = now_ns(), end = prev + (uint64_t)(secs * 1e9);
    size_t n = 0, big = 0;
    while (prev < end) {
        uint64_t t = now_ns();
        if (t - prev > 2000 && n < MAX_GAPS) {           // two reads more than 2 us apart: we were away
            len[n++] = t - prev;
            if (t - prev > 100000) big++;
        }
        prev = t;
    }
    long loc1 = loc_count(1);

    qsort(len, n, sizeof len[0], cmp);
    printf("spun %.0f s on CPU 1\n", secs);
    printf("  gaps longer than 2 us seen by this program : %zu (%.0f per second)\n", n, n / secs);
    printf("  median gap %.1f us, gaps longer than 100 us : %zu\n", len[n / 2] / 1e3, big);
    printf("  timer interrupts the kernel counted on CPU 1: %ld (%.0f per second)\n", loc1 - loc0, (loc1 - loc0) / secs);
    return 0;
}
$ zcat /proc/config.gz | grep '^CONFIG_HZ='
CONFIG_HZ=250
$ ./tick_detector 3
spun 3 s on CPU 1
  gaps longer than 2 us seen by this program : 8118 (2706 per second)
  median gap 7.6 us, gaps longer than 100 us : 35
  timer interrupts the kernel counted on CPU 1: 755 (252 per second)

The kernel counted 755 timer interrupts on CPU 1 in three seconds. That is 252 per second on a CPU running nothing but my loop, against a configured 250. The operating system was not running, and it still woke 252 times a second, on schedule, because the hardware made it.

The program saw 8,118 gaps, roughly ten times the kernel’s count. Where did the rest come from? A second script answers the part it can. It reruns the detector, then lists every interrupt and softirq counter that moved on CPU 1.

#!/bin/bash
# irq_diff.sh: run the tick detector, then list every interrupt and softirq counter that moved on CPU 1.
snap()      { awk 'NR>1 {print $1, $3}' /proc/interrupts; }     # column 3 is CPU 1
snap_soft() { awk 'NR>1 {print $1, $3}' /proc/softirqs; }
snap > /tmp/i0; snap_soft > /tmp/s0
../bin/p1_tick_detector 3 &
pid=$!
sleep 2.8
grep -E "^(non)?voluntary_ctxt" /proc/$pid/status                 # did the guest scheduler preempt the spinner?
wait $pid
snap > /tmp/i1; snap_soft > /tmp/s1
echo "interrupts that moved on CPU 1:"
paste /tmp/i0 /tmp/i1 | awk '{d=$4-$2; if (d!=0) printf "  %s %d\n", $1, d}'
echo "softirqs that moved on CPU 1:"
paste /tmp/s0 /tmp/s1 | awk '{d=$4-$2; if (d!=0) printf "  %s %d\n", $1, d}'
voluntary_ctxt_switches:    1
nonvoluntary_ctxt_switches: 12
spun 3 s on CPU 1
  gaps longer than 2 us seen by this program : 9086 (3029 per second)
  median gap 11.1 us, gaps longer than 100 us : 141
  timer interrupts the kernel counted on CPU 1: 757 (252 per second)
interrupts that moved on CPU 1:
  31: 1
  36: 2
  LOC: 759
  RES: 4
  CAL: 5
  TLB: 2
softirqs that moved on CPU 1:
  TIMER: 51
  BLOCK: 2
  SCHED: 53
  RCU: 25

This run saw 9,086 gaps, because the count varies from run to run. The timer accounts for 759 interrupts. Every other interrupt row moved by 5 or fewer, 14 in total, and the guest scheduler preempted the spinner 12 times. About 770 gaps have a cause the guest can see. A loop that makes no system calls enters the guest kernel only through an interrupt or an exception, so the other 8,300 or so gaps are time the guest never saw happen. I cannot tell from inside the VM what the host was doing, and I will not guess. A VM has two owners for every core. Post 4 is about the second one.

Timer interrupts return control to the kernel on a fixed period
Figure 1.3. A timer interrupt every 4 ms hands the core to the kernel, which switches processes.

What the timer does not do

Does the scheduler run on every tick? No, and the shortcut is tempting: tick rate equals time slice. It does not. The tick is the guarantee that the kernel gets a look. At each look, the scheduler decides whether the current task has used its share. How long a share lasts is a scheduler setting. Under EEVDF, the current Linux policy for ordinary tasks, it is sched_base_slice_ns, and HZ does not set it.

The tick is also not the only door into the scheduler. A task that blocks on I/O enters it. A wakeup that deserves to preempt the running task enters it. An inter-processor interrupt from another core enters it. None of them wait for a tick.

So state the claim at its real size. The timer guarantees that control comes back. What the kernel does with that control is Post 2.

What to carry forward

The operating system is not running right now. It is waiting for the clock. The hardware gave it three guarantees: user code cannot touch privileged state, user code can enter the kernel only through doors the kernel built, and a timer pulls control back whether the program cooperates or not. Everything in the next four posts sits on top of those three.

Takeaways

  1. A full adder is five gates, or nine NANDs, and an ALU is adders, logic units and a multiplexer picked by opcode bits.
  2. A ripple carry adds two gate delays per bit, so wide adders need lookahead.
  3. The CPU checks for pending interrupts between instructions, and no user code writes that check.
  4. Ring 3 code reaches the kernel only through entries the kernel registered, and it cannot mask the timer.
  5. The timer guarantees the kernel regains control; it does not by itself define a time slice.
  6. Compare your CONFIG_HZ with the LOC row of /proc/interrupts on a CPU running one loop, then read OSTEP chapter 6 before Post 2.

Published November 22, 2026