Day67 - Workqueue Fundamentals¶
Goal¶
Understand how Linux Workqueues provide deferred execution by moving work from interrupt context into process context.
This lab focuses on Workqueue architecture, lifecycle management, cleanup behavior, and driver design patterns.
Deferred Execution¶
Problem¶
Hard IRQ handlers must execute quickly and cannot perform operations that may sleep.
Examples of prohibited operations inside Hard IRQ Context:
To perform these operations safely, work must be deferred into a sleepable context.
Workqueue Solution¶
The work handler executes in process context.
Allowed operations:
- mutex_lock()
- msleep()
- schedule()
- i2c_transfer()
- spi_sync()
Workqueue Lifecycle¶
Global Workqueue¶
Linux provides a default global workqueue:
Equivalent:
Private Workqueue¶
Drivers may create dedicated workqueues:
Submit work:
Advantages:
- Workload isolation
- Dedicated lifecycle
- Independent worker pool
Delayed Work¶
Delayed Work combines:
Initialization:
Schedule:
Reschedule:
Common Driver Patterns¶
Retry Mechanism¶
Typical examples:
- Firmware update
- Device recovery
- Hardware reset sequence
Debounce¶
Monitoring¶
Examples:
- Battery monitor
- Thermal monitor
- Link status monitor
Workqueue Cleanup¶
Work Cancellation¶
Behavior:
- Remove pending work
- Wait for running handler completion
Delayed Work Cancellation¶
Behavior:
- Cancel timer if pending
- Wait for running handler completion
Workqueue Flush¶
Behavior:
The workqueue remains usable.
Workqueue Destroy¶
Behavior:
Driver Remove Sequence¶
Recommended shutdown sequence:
disable_irq()
↓
cancel_work_sync()
↓
cancel_delayed_work_sync()
↓
destroy_workqueue()
↓
free_irq()
↓
release resources
Reason:
Workqueue vs Threaded IRQ¶
Threaded IRQ¶
Suitable for:
- Interrupt-driven processing
- I2C/SPI transactions
- Event reporting
Workqueue¶
Suitable for:
- Retry mechanisms
- Recovery operations
- Deferred processing
- Delayed execution
Workqueue vs Kernel Thread¶
Workqueue¶
Characteristics:
- Event-driven
- Finite execution
- Managed by kernel worker pools
Kernel Thread¶
Characteristics:
- Long-lived execution
- State machine processing
- Monitoring and background services
Summary¶
Key concepts learned:
- Deferred execution moves work into sleepable context.
- Workqueue handlers run in process context.
- Delayed Work combines timers and workqueues.
- Private workqueues isolate driver workloads.
- Workqueue cleanup is essential during driver removal.
- Workqueue is designed for jobs, not permanent services.
- Kernel Threads are better suited for long-lived state machines.