Interrupt Handling Flow

1. Interrupt Generation A hardware device (e.g., NIC, keyboard) raises an interrupt via the Programmable Interrupt Controller (PIC/APIC). The PIC converts the IRQ line into a vector number and signals the CPU via the INTR/NMI pin. 2. CPU State Save & Context Switch The CPU finishes the current instruction, saves the process context (registers, PC, flags) to the stack, and disables local interrupts Switches to the interrupt context (no associated process, interrupts disabled). 3. IDT Lookup The CPU uses the Interrupt Descriptor Table (IDT) to find the handler address for the interrupt vector. On ARM, the vector table (similar to x86 IDT) is preconfigured with handlers like handle_level_irq or handle_edge_irq. 4. Top Half Execution Immediate Actions: Acknowledge the interrupt at the hardware level (irq_data.chip->irq_ack()) Read device status registers to confirm the interrupt source Minimal Processing: Copy critical data (e.g., network packets) to kernel buffers. Schedule deferred processing via bottom halves (tasklets, softirqs) APIs: request_irq(), free_irq() for driver-level registration. 5. Bottom Half Execution Deferred Work: Process data in safe contexts (e.g., tasklet_schedule() or workqueues). Runs with interrupts enabled (softirq context) or in process context (workqueues). Mechanisms: SoftIRQs: Statically allocated, high-priority (e.g., network RX) Tasklets: Dynamically allocated, atomic (e.g., USB transfers). Workqueues: Sleepable, process context (e.g., filesystem I/O) . 6. Interrupt Completion Send End-of-Interrupt (EOI) to the PIC (e.g., irq_data.chip->irq_eoi()) The result is stored in eax/r0, and the kernel uses iret (x86) or exception return (ARM) to resume user execution. 7. Examples Network Driver (Hardware Interrupt) Top Half: irqreturn_t nic_isr(int irq, void *dev_id) { // Read packet from hardware buffer tasklet_schedule(&nic_tasklet); // Schedule bottom half return IRQ_HANDLED; } Bottom Half: void nic_tasklet_fn(unsigned long data) { // Process packets, update kernel networking stack }

May 4, 2025 · 2 min

Interrupt Questions

Q1: What happens if another interrupt occurs while a top half (ISR) is executing? Answer: By default, interrupts are disabled during the top half execution. When the CPU enters the ISR (via the IDT), it automatically clears the Interrupt Flag (IF) on x86 (using cli), preventing further interrupts until the ISR finishes. Exception: Some architectures or configurations (e.g., nested interrupts) allow interrupts to preempt an ISR. For example: IRQF_DISABLED (now deprecated): Previously controlled whether interrupts were disabled during the ISR. Modern kernels typically disable interrupts for all IRQ handlers by default. Threaded interrupts (using IRQF_ONESHOT or IRQF_THREAD): The “top half” runs in a kernel thread with interrupts enabled. Key Takeaway: ...

May 4, 2025 · 4 min

Interrupt Descriptor Table (IDT)

What it is: A table used by the CPU to map interrupt/exception numbers to their corresponding handlers (ISRs). Setup: The kernel initializes the IDT during boot. Each entry contains: Address of the ISR (Interrupt Service Routine). Privilege level (kernel/user). Type (trap, interrupt gate, etc.). CPU Interaction: The CPU uses the IDTR register (set via lidt instruction) to locate the IDT. When an interrupt occurs, the CPU indexes into the IDT using the interrupt vector number to find the ISR.

May 4, 2025 · 1 min

Interrupt

Overview An interrupt is a signal that breaks the normal execution flow to handle an event. When an interrupt occurs, the CPU pauses its current task, jumps to an interrupt service routine (ISR), and after the ISR completes it resumes the original task. Why are interrupts needed? Avoid Polling: More efficient than continuously checking device status (polling), reducing CPU overhead and increasing system throughput Real-Time Responsiveness: Essential for systems requiring quick reactions to events Automotive airbag systems detecting collisions Network Interface Cards (NICs) processing incoming packets Interrupt Types Hardware Interrupts: Triggered by devices (e.g., keyboard, NIC). Managed by the Programmable Interrupt Controller (PIC) or APIC. Software Interrupts: Generated by software (e.g., int 0x80 for syscalls). Exceptions: CPU-generated (e.g., divide-by-zero, page faults). How the Kernel Registers Interrupts IDT Initialization: At boot, the kernel populates the IDT with default handlers (e.g., for exceptions). Hardware interrupts are mapped to a generic entry (e.g., common_interrupt on x86). Device Drivers: Drivers request a specific IRQ (Interrupt Request Line) using request_irq(). Example: int request_irq(unsigned int irq, irq_handler_t handler, unsigned long flags, const char *name, void *dev); irq: The interrupt number (e.g., IRQ 1 for keyboard). handler: The ISR function. flags: Options like IRQF_SHARED for shared interrupts. dev: A cookie passed to the ISR (used for shared IRQs). What happens when an interrupt is occurred? See Interrupt Handling Flow ...

May 3, 2025 · 2 min

POCO Libraries

The POCO C++ Libraries are powerful cross-platform C++ libraries for building network- and internet-based applications that run on desktop, server, mobile, IoT, and embedded systems. Cross-Compiling With a proper CMake toolchain file (specified via the CMAKE_TOOLCHAIN_FILE CMake variable), the POCO C++ Libraries can be cross-compiled for embedded Linux systems: mkdir cmake-build cd cmake-build cmake .. -DCMAKE_TOOLCHAIN_FILE=/path/to/mytoolchain.cmake -DCMAKE_INSTALL_PREFIX=/path/to/target cmake -DENAMLE-SAMPLE=YES cmake --build . --target install # make all install OR mkdir cmake-build-ipc2 && cd cmake-build-ipc2 && cmake .. -DCMAKE_TOOLCHAIN_FILE= /opt/IPCam2_Host/host/share/buildroot/toolchainfile.cmake -DCMAKE_INSTALL_PREFIX=target -DENABLE_SAMPLES=ON -DBUILD_SHARED_LIBS=ON Installing The POCO C++ Libraries headers and libraries can be optionally be installed by building the install target. ...

April 29, 2025 · 1 min

External Toolchain in Buildroot

Using External Toolchain Option 1: Give tarball URL Specify URL for the tarball in BR_TOOLCHAIN_EXTERNAL_URL Example: BR_TOOLCHAIN_EXTERNAL_URL=http://artifactory/my-toolchain.tar.xz In this case you will have to deselect BR2_PRIMARY_SITE_ONLY option Option 2: Give tarball relative dl path If BR2_PRIMARY_SITE_ONLY option is selected then you have to keep the toolchain inside dl/toolchain-external-custom/ directory and pass the name of tarball to BR_TOOLCHAIN_EXTERNAL_URL Example: BR2_PRIMARY_SITE="http://artifactory/buildroot-sources" BR2_PRIMARY_SITE_ONLY=y BR_TOOLCHAIN_EXTERNAL_URL=my-toolcahin.tar.xz This will extract the toolchain to buildroot’s build directory output/host/opt/ext-toolchain ...

April 4, 2025 · 1 min

Data Structures

Comparison Table Data Structure Structure Type Search Complexity Insertion Complexity Deletion Complexity Use Cases Advantages Disadvantages Array Contiguous block of memory O(1) for access; O(n) for search (unsorted) O(n) (shifting elements) O(n) (shifting elements) Static collections, lookup tables Fast random access, cache friendly Fixed size (static arrays), expensive mid-operations Linked List Node-based (non-contiguous memory) O(n) O(1) (with pointer/reference) O(1) (with pointer/reference) Dynamic lists, implementing stacks/queues Dynamic size, efficient insertions/deletions No random access, additional memory for pointers Stack LIFO (often implemented via array or linked list) O(n) if searching required O(1) (push) O(1) (pop) Function calls, recursion, backtracking Simple, constant-time push/pop Access restricted to the top element Queue FIFO (often implemented via array or linked list) O(n) if searching required O(1) (enqueue) O(1) (dequeue) Scheduling, buffering, process management Simple FIFO order, constant time operations Access restricted to front/rear only Binary Search Tree Hierarchical tree (ordered) O(log n) average; O(n) worst-case O(log n) average; O(n) worst-case O(log n) average; O(n) worst-case Maintaining sorted data, dynamic sets Efficient average-case operations, maintains order Unbalanced trees can degrade to O(n) operations Heap (Binary Heap) Complete binary tree O(n) for arbitrary search O(log n) O(log n) Priority queues, heap sort Fast access to min/max element, efficient insertion/deletion Not efficient for general searching Hash Table Key-value mapping using hashing O(1) average; O(n) worst-case O(1) average; O(n) worst-case O(1) average; O(n) worst-case Dictionaries, caches, indexing Extremely fast average-case operations Performance depends on hash function; worst-case linear; unordered Graph Collection of nodes (vertices) and edges Varies (algorithm dependent) Varies (representation dependent) Varies (representation dependent) Modeling networks, routing, social networks Models complex relationships, versatile Implementation complexity; can be memory-intensive Additional Notes Arrays are best for scenarios where the size is fixed and fast random access is required. Linked Lists shine in situations requiring frequent insertions and deletions with dynamic sizing. Stacks and Queues provide simple, ordered data access patterns suitable for specific algorithmic strategies. Binary Search Trees offer ordered storage with efficient average-case performance, though balanced versions (like AVL or Red-Black trees) are preferred in practice. Heaps are ideal for priority-based tasks. Hash Tables are invaluable for fast lookup tasks, provided a well-designed hash function minimizes collisions. Graphs are essential for representing interconnected data but require careful design regarding representation (adjacency list vs. matrix) based on the use case.

March 15, 2025 · 2 min

Buildroot Relocatable SDK

Overview A relocatable toolchain/SDK is a self-contained set of cross-compilation tools that can be moved to different locations without breaking dependencies. Buildroot provides an option to generate such a toolchain, allowing developers to use it for cross-compiling applications without depending on a fixed absolute path. Prepare Relocatable SDK Configure Buildroot for SDK Generation Disable BusyBox and set /bin/sh to None under System configuration. This prevents unnecessary shell dependencies within the SDK, ensuring better relocatability. ...

March 10, 2025 · 1 min

Bitwise Operators

Truth Table X Y X & Y X | Y X ^ Y 0 0 0 0 0 0 1 0 1 1 1 0 0 1 1 1 1 1 1 0 Points to Remember The left-shift and right-shift operators should not be used for negative numbers Left Shift(<<) just means multiply by 2. Similarly >> results division by 2. XOR results 0 if both bits are same. So a^1=~a , a^0=a and a^a=0. 1’s and 2’s Complement 1’s complement means negation(not) of any number get 2’s complement by adding 1 to 1’s complement Original number: 0000 0101 (5) 1's complement: 1111 1010 Add 1 2's complement: 1111 1011 2's complement = (~binary number) + 1 Questions Q1. How to toggle or flip a particular bit in a number? To toggle any bit in a variable, Use (^) exclusive OR operator. ...

February 19, 2025 · 2 min

Generic GPIO Management in Linux

Introduction GPIO (General Purpose Input/Output) is a fundamental interface in embedded systems and Linux-based platforms. Linux provides multiple methods to control GPIOs, including the deprecated /sys/class/gpio/ interface and the modern libgpiod (GPIO character device) API. This document provides a comprehensive guide to managing GPIOs in Linux. GPIO Interfaces in Linux Linux provides three primary ways to manage GPIOs: Legacy Sysfs Interface (/sys/class/gpio/) - Deprecated but still present on some systems. GPIO Character Device (/dev/gpiochipX) - The recommended approach using libgpiod. Direct Kernel Access - Through kernel drivers or device tree configurations. 1. Sysfs GPIO Interface (Deprecated) The sysfs-based interface was historically used to control GPIOs but has been marked as deprecated in favor of gpiod. If still available, it can be accessed via /sys/class/gpio/. ...

February 19, 2025 · 2 min