Skip to content

Timers, Interrupts, And Workqueues

Imported from _research/manual-study-linux/timers-workqueues.md.

Timers, Interrupts, And Workqueues

Status: implemented source-backed volume.

Source Surface

  • kernel/time/timer.c: kernel timer lifecycle and delayed callback execution.
  • kernel/workqueue.c: work item queuing, worker pools, delayed work, and execution loops.

Timer Model

Kernel timers schedule callbacks for later execution. They are not threads; they are time-indexed callback objects that eventually run in kernel context. kernel/time/timer.c includes the delayed-work timer callback delayed_work_timer_fn() around lines 665-668, showing the bridge between the timer subsystem and workqueues.

Timers are useful for deadlines and delayed wakeups, but the callback context is constrained. If work can sleep or may be expensive, Linux commonly uses a timer to enqueue work rather than doing all the work inside the timer callback.

Workqueue Model

kernel/workqueue.c implements deferred process-context execution. Its core data types include struct worker_pool around line 195, struct pool_workqueue around line 269, and struct workqueue_struct around line 349. System workqueues are declared around lines 524-544.

The hot path is:

  1. A caller queues work with queue_work_on() around lines 2429-2442.
  2. Internal code reaches __queue_work() around line 2275.
  3. Workers are created or woken as needed.
  4. worker_thread() around lines 3420-3431 runs worker loops.
  5. process_one_work() around lines 3207-3220 invokes the callback.

Delayed work crosses both subsystems: timer code expires first, then queues the work item into a workqueue for execution.

Concurrency And Cancellation

The design has to answer three hard questions:

  • Has work already started?
  • Can the caller cancel it safely?
  • Which CPU or pool should execute it?

Linux handles that with pending-state transitions, worker-pool locks, per-CPU pools, and explicit delayed-work helpers. try_to_grab_pending() around lines 2063-2090 exists because cancellation races are a first-class part of the model, not an edge case.

Rust Translation

A Rust runtime should split:

  • Timer as a non-sleeping deadline object.
  • WorkItem<T> as owned deferred work.
  • WorkQueue as execution policy.
  • DelayedWork as timer plus queued work state.
  • Cancellation APIs that return exact state: not queued, canceled before run, already running, or completed.

The API should prevent stack-owned work from being queued beyond its lifetime.

AI-Native Translation

For AI-native systems, workqueues become the job scheduler. Timers trigger future jobs, but workers carry capability context, cancellation state, audit metadata, and resource budgets. This avoids mixing “wake me later” with “run expensive agent code now.”

  • file-notes/linux__kernel__time__timer.c.md
  • file-notes/linux__kernel__workqueue.c.md