SlideShare a Scribd company logo
1 of 15
Linux Interrupts
1
Liran Ben Haim
liran@discoversdk.com
Rights to Copy
 Attribution – ShareAlike 2.0
 You are free
to copy, distribute, display, and perform the work
to make derivative works
to make commercial use of the work
Under the following conditions
Attribution. You must give the original author credit.
Share Alike. If you alter, transform, or build upon this work, you may
distribute the resulting work only under a license identical to this one.
For any reuse or distribution, you must make clear to others the license
terms of this work.
Any of these conditions can be waived if you get permission from the
copyright holder.
Your fair use and other rights are in no way affected by the above.
License text: http://creativecommons.org/licenses/by-sa/2.0/legalcode
 This kit contains work by the
following authors:
 © Copyright 2004-2009
Michael Opdenacker /Free
Electrons
michael@free-electrons.com
http://www.free-electrons.com
 © Copyright 2003-2006
Oron Peled
oron@actcom.co.il
http://www.actcom.co.il/~oron
 © Copyright 2004–2008
Codefidence ltd.
info@codefidence.com
http://www.codefidence.com
 © Copyright 2009–2010
Bina ltd.
info@bna.co.il
http://www.bna.co.il
2
Interrupt handler constraints
Not run from a user context:
Can't transfer data to and from user space
(need to be done by system call handlers)
Interrupt handler execution is managed by the CPU,
not by the scheduler. Handlers can't run actions that
may sleep, because there is nothing to resume their
execution. In particular, need to allocate memory with
GFP_ATOMIC.
Have to complete their job quickly enough:
they shouldn't block their interrupt line for too long.
3
Registering an interrupt handler (1)
 Defined in include/linux/interrupt.h
int request_irq( Returns 0 if successful
unsigned int irq, Requested irq channel
irqreturn_t handler, Interrupt handler
unsigned long irq_flags, Option mask (see next page)
const char * devname, Registered name
void *dev_id); Pointer to some handler data
Cannot be NULL and must be unique for
shared irqs!
void free_irq( unsigned int irq, void *dev_id);
dev_id cannot be NULL and must be unique for shared irqs.
Otherwise, on a shared interrupt line,
free_irq wouldn't know which handler to free.
4
Registering an interrupt handler (2)
 irq_flags bit values (can be combined, none is fine too)
IRQF_DISABLED
"Quick" interrupt handler. Run with all interrupts disabled on the current cpu
(instead of just the current line). For latency reasons, should only be used
when needed!
IRQF_SHARED
Run with interrupts disabled only on the current irq line and on the local cpu.
The interrupt channel can be shared by several devices. Requires a hardware
status register telling whether an IRQ was raised or not.
IRQF_SAMPLE_RANDOM
Interrupts can be used to contribute to the system entropy pool used by
/dev/random and /dev/urandom. Useful to generate good random numbers.
Don't use this if the interrupt behavior of your device is predictable!
5
Information
 /proc/interrupts
 CPU0
0: 5616905 XT-PIC timer # Registered name
1: 9828 XT-PIC i8042
2: 0 XT-PIC cascade
3: 1014243 XT-PIC orinoco_cs
7: 184 XT-PIC Intel 82801DB-ICH4
8: 1 XT-PIC rtc
9: 2 XT-PIC acpi
11: 566583 XT-PIC ehci_hcd, yenta, yenta, radeon@PCI:1:0:0
12: 5466 XT-PIC i8042
14: 121043 XT-PIC ide0
15: 200888 XT-PIC ide1
NMI: 0 Non Maskable Interrupts
ERR: 0 Spurious interrupt count
6
Interrupt handler prototype
 irqreturn_t (*handler) (
int, // irq number of the current interrupt
void *dev_id, // Pointer used to keep track
// of the corresponding device.
// Useful when several devices
// are managed by the same module
);
 Return value:
IRQ_HANDLED: recognized and handled interrupt
IRQ_NONE: not on a device managed by the module. Useful to
share interrupt channels and/or report spurious interrupts to the
kernel.
7
Linux Contexts
User Space
Process Context
Interrupt Handlers
Kernel
Space
Interrupt
Context
SoftIRQs
Hiprio
tasklets
Net
Stack
Timers
Regular
tasklets
...
Scheduling
Points
Process
Thread
Kernel Thread
8
Top half and bottom half processing (1)
 Splitting the execution of interrupt handlers in 2 parts
Top half: the interrupt handler must complete as
quickly as possible. Once it acknowledged the
interrupt, it just schedules the lengthy rest of the job
taking care of the data, for a later execution.
Bottom half: completing the rest of the interrupt
handler job. Handles data, and then wakes up any
waiting user process.
Best implemented by tasklets (also called soft irqs).
9
top half and bottom half processing (2)
Declare a Tasklet
interrupt context
Declare a WorkQueue
Kernel thread
Pop the interrupt to user space
10
Handling in User Space
 Sending Signal
 Use send_sig_info
 Using NetLink Socket
 Use netlink_broadcast with GFP_ATOMIC
 Using Wait Queue
 wake_up_interruptible
11
Disabling interrupts
 May be useful in regular driver code...
Can be useful to ensure that an interrupt handler will not preempt your code
(including kernel preemption)
Disabling interrupts on the local CPU:
unsigned long flags;
local_irq_save(flags); // Interrupts disabled
...
local_irq_restore(flags); // Interrupts restored to their previous state.
Note: must be run from within the same function!
12
Masking out an interrupt line
 Useful to disable interrupts on a particular line
void disable_irq (unsigned int irq);
Disables the irq line for all processors in the system.
Waits for all currently executing handlers to complete.
void disable_irq_nosync (unsigned int irq);
Same, except it doesn't wait for handlers to complete.
void enable_irq (unsigned int irq);
Restores interrupts on the irq line.
void synchronize_irq (unsigned int irq);
Waits for irq handlers to complete (if any).
13
Checking interrupt status
 Can be useful for code which can be run from both
process or interrupt context, to know whether it is
allowed or not to call code that may sleep.
irqs_disabled()
Tests whether local interrupt delivery is disabled.
in_interrupt()
Tests whether code is running in interrupt context
in_irq()
Tests whether code is running in an interrupt handler.
14
Thank You
Code examples and more
http://www.discoversdk.com/blog
15

More Related Content

What's hot

High-Performance Networking Using eBPF, XDP, and io_uring
High-Performance Networking Using eBPF, XDP, and io_uringHigh-Performance Networking Using eBPF, XDP, and io_uring
High-Performance Networking Using eBPF, XDP, and io_uring
ScyllaDB
 

What's hot (20)

Understanding das-nas-san
Understanding das-nas-sanUnderstanding das-nas-san
Understanding das-nas-san
 
BPF - in-kernel virtual machine
BPF - in-kernel virtual machineBPF - in-kernel virtual machine
BPF - in-kernel virtual machine
 
Advanced computer architecture
Advanced computer architectureAdvanced computer architecture
Advanced computer architecture
 
ARM and SoC Traning Part I -- Overview
ARM and SoC Traning Part I -- OverviewARM and SoC Traning Part I -- Overview
ARM and SoC Traning Part I -- Overview
 
Beneath the Linux Interrupt handling
Beneath the Linux Interrupt handlingBeneath the Linux Interrupt handling
Beneath the Linux Interrupt handling
 
Understanding DPDK
Understanding DPDKUnderstanding DPDK
Understanding DPDK
 
Making Linux do Hard Real-time
Making Linux do Hard Real-timeMaking Linux do Hard Real-time
Making Linux do Hard Real-time
 
Linux Internals - Part III
Linux Internals - Part IIILinux Internals - Part III
Linux Internals - Part III
 
ARM architcture
ARM architcture ARM architcture
ARM architcture
 
How Linux Processes Your Network Packet - Elazar Leibovich
How Linux Processes Your Network Packet - Elazar LeibovichHow Linux Processes Your Network Packet - Elazar Leibovich
How Linux Processes Your Network Packet - Elazar Leibovich
 
Linux Programming
Linux ProgrammingLinux Programming
Linux Programming
 
High-Performance Networking Using eBPF, XDP, and io_uring
High-Performance Networking Using eBPF, XDP, and io_uringHigh-Performance Networking Using eBPF, XDP, and io_uring
High-Performance Networking Using eBPF, XDP, and io_uring
 
Pcie drivers basics
Pcie drivers basicsPcie drivers basics
Pcie drivers basics
 
Q4.11: ARM Architecture
Q4.11: ARM ArchitectureQ4.11: ARM Architecture
Q4.11: ARM Architecture
 
Linux Kernel MMC Storage driver Overview
Linux Kernel MMC Storage driver OverviewLinux Kernel MMC Storage driver Overview
Linux Kernel MMC Storage driver Overview
 
Building Embedded Linux Systems Introduction
Building Embedded Linux Systems IntroductionBuilding Embedded Linux Systems Introduction
Building Embedded Linux Systems Introduction
 
Linux Internals - Part I
Linux Internals - Part ILinux Internals - Part I
Linux Internals - Part I
 
Linux Ethernet device driver
Linux Ethernet device driverLinux Ethernet device driver
Linux Ethernet device driver
 
Linux scheduler
Linux schedulerLinux scheduler
Linux scheduler
 
Linux file system
Linux file systemLinux file system
Linux file system
 

Viewers also liked

Modern Linux Tracing Landscape
Modern Linux Tracing LandscapeModern Linux Tracing Landscape
Modern Linux Tracing Landscape
Kernel TLV
 
Windows Internals for Linux Kernel Developers
Windows Internals for Linux Kernel DevelopersWindows Internals for Linux Kernel Developers
Windows Internals for Linux Kernel Developers
Kernel TLV
 
Processes in unix
Processes in unixProcesses in unix
Processes in unix
miau_max
 

Viewers also liked (20)

Linux Kernel Cryptographic API and Use Cases
Linux Kernel Cryptographic API and Use CasesLinux Kernel Cryptographic API and Use Cases
Linux Kernel Cryptographic API and Use Cases
 
Linux interrupts
Linux interruptsLinux interrupts
Linux interrupts
 
Userfaultfd and Post-Copy Migration
Userfaultfd and Post-Copy MigrationUserfaultfd and Post-Copy Migration
Userfaultfd and Post-Copy Migration
 
Modern Linux Tracing Landscape
Modern Linux Tracing LandscapeModern Linux Tracing Landscape
Modern Linux Tracing Landscape
 
WiFi and the Beast
WiFi and the BeastWiFi and the Beast
WiFi and the Beast
 
grsecurity and PaX
grsecurity and PaXgrsecurity and PaX
grsecurity and PaX
 
FreeBSD and Drivers
FreeBSD and DriversFreeBSD and Drivers
FreeBSD and Drivers
 
Windows Internals for Linux Kernel Developers
Windows Internals for Linux Kernel DevelopersWindows Internals for Linux Kernel Developers
Windows Internals for Linux Kernel Developers
 
Fun with Network Interfaces
Fun with Network InterfacesFun with Network Interfaces
Fun with Network Interfaces
 
Linux Locking Mechanisms
Linux Locking MechanismsLinux Locking Mechanisms
Linux Locking Mechanisms
 
Specializing the Data Path - Hooking into the Linux Network Stack
Specializing the Data Path - Hooking into the Linux Network StackSpecializing the Data Path - Hooking into the Linux Network Stack
Specializing the Data Path - Hooking into the Linux Network Stack
 
VLANs in the Linux Kernel
VLANs in the Linux KernelVLANs in the Linux Kernel
VLANs in the Linux Kernel
 
DMA Survival Guide
DMA Survival GuideDMA Survival Guide
DMA Survival Guide
 
Hardware Probing in the Linux Kernel
Hardware Probing in the Linux KernelHardware Probing in the Linux Kernel
Hardware Probing in the Linux Kernel
 
High Performance Storage Devices in the Linux Kernel
High Performance Storage Devices in the Linux KernelHigh Performance Storage Devices in the Linux Kernel
High Performance Storage Devices in the Linux Kernel
 
FD.IO Vector Packet Processing
FD.IO Vector Packet ProcessingFD.IO Vector Packet Processing
FD.IO Vector Packet Processing
 
Switchdev - No More SDK
Switchdev - No More SDKSwitchdev - No More SDK
Switchdev - No More SDK
 
Introduction to DPDK
Introduction to DPDKIntroduction to DPDK
Introduction to DPDK
 
Linux Security Overview
Linux Security OverviewLinux Security Overview
Linux Security Overview
 
Processes in unix
Processes in unixProcesses in unix
Processes in unix
 

Similar to Linux Interrupts

Linux synchronization tools
Linux synchronization toolsLinux synchronization tools
Linux synchronization tools
mukul bhardwaj
 
26.1.7 lab snort and firewall rules
26.1.7 lab   snort and firewall rules26.1.7 lab   snort and firewall rules
26.1.7 lab snort and firewall rules
Freddy Buenaño
 

Similar to Linux Interrupts (20)

IRQs: the Hard, the Soft, the Threaded and the Preemptible
IRQs: the Hard, the Soft, the Threaded and the PreemptibleIRQs: the Hard, the Soft, the Threaded and the Preemptible
IRQs: the Hard, the Soft, the Threaded and the Preemptible
 
Linux internals v4
Linux internals v4Linux internals v4
Linux internals v4
 
LCNA14: Why Use Xen for Large Scale Enterprise Deployments? - Konrad Rzeszute...
LCNA14: Why Use Xen for Large Scale Enterprise Deployments? - Konrad Rzeszute...LCNA14: Why Use Xen for Large Scale Enterprise Deployments? - Konrad Rzeszute...
LCNA14: Why Use Xen for Large Scale Enterprise Deployments? - Konrad Rzeszute...
 
Lab6 rtos
Lab6 rtosLab6 rtos
Lab6 rtos
 
Fn project quick installation guide
Fn project quick installation guideFn project quick installation guide
Fn project quick installation guide
 
Trying and evaluating the new features of GlusterFS 3.5
Trying and evaluating the new features of GlusterFS 3.5Trying and evaluating the new features of GlusterFS 3.5
Trying and evaluating the new features of GlusterFS 3.5
 
F9: A Secure and Efficient Microkernel Built for Deeply Embedded Systems
F9: A Secure and Efficient Microkernel Built for Deeply Embedded SystemsF9: A Secure and Efficient Microkernel Built for Deeply Embedded Systems
F9: A Secure and Efficient Microkernel Built for Deeply Embedded Systems
 
Quick and Easy Device Drivers for Embedded Linux Using UIO
Quick and Easy Device Drivers for Embedded Linux Using UIOQuick and Easy Device Drivers for Embedded Linux Using UIO
Quick and Easy Device Drivers for Embedded Linux Using UIO
 
Linux synchronization tools
Linux synchronization toolsLinux synchronization tools
Linux synchronization tools
 
Ubuntu 16.04 LTS Security Features
Ubuntu 16.04 LTS Security FeaturesUbuntu 16.04 LTS Security Features
Ubuntu 16.04 LTS Security Features
 
Arm developement
Arm developementArm developement
Arm developement
 
Hacktivity 2016: Stealthy, hypervisor based malware analysis
Hacktivity 2016: Stealthy, hypervisor based malware analysisHacktivity 2016: Stealthy, hypervisor based malware analysis
Hacktivity 2016: Stealthy, hypervisor based malware analysis
 
Lect17
Lect17Lect17
Lect17
 
Vx works RTOS
Vx works RTOSVx works RTOS
Vx works RTOS
 
Le Device Tree Linux
Le Device Tree LinuxLe Device Tree Linux
Le Device Tree Linux
 
26.1.7 lab snort and firewall rules
26.1.7 lab   snort and firewall rules26.1.7 lab   snort and firewall rules
26.1.7 lab snort and firewall rules
 
OffensiveCon2022: Case Studies of Fuzzing with Xen
OffensiveCon2022: Case Studies of Fuzzing with XenOffensiveCon2022: Case Studies of Fuzzing with Xen
OffensiveCon2022: Case Studies of Fuzzing with Xen
 
Bottom halves on Linux
Bottom halves on LinuxBottom halves on Linux
Bottom halves on Linux
 
Introduction to FreeRTOS
Introduction to FreeRTOSIntroduction to FreeRTOS
Introduction to FreeRTOS
 
IPS_3M_eng
IPS_3M_engIPS_3M_eng
IPS_3M_eng
 

More from Kernel TLV

Building Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCBuilding Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCC
Kernel TLV
 
netfilter and iptables
netfilter and iptablesnetfilter and iptables
netfilter and iptables
Kernel TLV
 

More from Kernel TLV (15)

DPDK In Depth
DPDK In DepthDPDK In Depth
DPDK In Depth
 
Building Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCBuilding Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCC
 
SGX Trusted Execution Environment
SGX Trusted Execution EnvironmentSGX Trusted Execution Environment
SGX Trusted Execution Environment
 
Fun with FUSE
Fun with FUSEFun with FUSE
Fun with FUSE
 
Kernel Proc Connector and Containers
Kernel Proc Connector and ContainersKernel Proc Connector and Containers
Kernel Proc Connector and Containers
 
Bypassing ASLR Exploiting CVE 2015-7545
Bypassing ASLR Exploiting CVE 2015-7545Bypassing ASLR Exploiting CVE 2015-7545
Bypassing ASLR Exploiting CVE 2015-7545
 
Present Absence of Linux Filesystem Security
Present Absence of Linux Filesystem SecurityPresent Absence of Linux Filesystem Security
Present Absence of Linux Filesystem Security
 
OpenWrt From Top to Bottom
OpenWrt From Top to BottomOpenWrt From Top to Bottom
OpenWrt From Top to Bottom
 
Make Your Containers Faster: Linux Container Performance Tools
Make Your Containers Faster: Linux Container Performance ToolsMake Your Containers Faster: Linux Container Performance Tools
Make Your Containers Faster: Linux Container Performance Tools
 
Emerging Persistent Memory Hardware and ZUFS - PM-based File Systems in User ...
Emerging Persistent Memory Hardware and ZUFS - PM-based File Systems in User ...Emerging Persistent Memory Hardware and ZUFS - PM-based File Systems in User ...
Emerging Persistent Memory Hardware and ZUFS - PM-based File Systems in User ...
 
File Systems: Why, How and Where
File Systems: Why, How and WhereFile Systems: Why, How and Where
File Systems: Why, How and Where
 
netfilter and iptables
netfilter and iptablesnetfilter and iptables
netfilter and iptables
 
KernelTLV Speaker Guidelines
KernelTLV Speaker GuidelinesKernelTLV Speaker Guidelines
KernelTLV Speaker Guidelines
 
Userfaultfd: Current Features, Limitations and Future Development
Userfaultfd: Current Features, Limitations and Future DevelopmentUserfaultfd: Current Features, Limitations and Future Development
Userfaultfd: Current Features, Limitations and Future Development
 
The Linux Block Layer - Built for Fast Storage
The Linux Block Layer - Built for Fast StorageThe Linux Block Layer - Built for Fast Storage
The Linux Block Layer - Built for Fast Storage
 

Recently uploaded

Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
mbmh111980
 

Recently uploaded (20)

The Impact of PLM Software on Fashion Production
The Impact of PLM Software on Fashion ProductionThe Impact of PLM Software on Fashion Production
The Impact of PLM Software on Fashion Production
 
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfImplementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
 
What need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java DevelopersWhat need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java Developers
 
SQL Injection Introduction and Prevention
SQL Injection Introduction and PreventionSQL Injection Introduction and Prevention
SQL Injection Introduction and Prevention
 
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesGraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
 
how-to-download-files-safely-from-the-internet.pdf
how-to-download-files-safely-from-the-internet.pdfhow-to-download-files-safely-from-the-internet.pdf
how-to-download-files-safely-from-the-internet.pdf
 
architecting-ai-in-the-enterprise-apis-and-applications.pdf
architecting-ai-in-the-enterprise-apis-and-applications.pdfarchitecting-ai-in-the-enterprise-apis-and-applications.pdf
architecting-ai-in-the-enterprise-apis-and-applications.pdf
 
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
 
INGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by DesignINGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by Design
 
AI Hackathon.pptx
AI                        Hackathon.pptxAI                        Hackathon.pptx
AI Hackathon.pptx
 
Naer Toolbar Redesign - Usability Research Synthesis
Naer Toolbar Redesign - Usability Research SynthesisNaer Toolbar Redesign - Usability Research Synthesis
Naer Toolbar Redesign - Usability Research Synthesis
 
5 Reasons Driving Warehouse Management Systems Demand
5 Reasons Driving Warehouse Management Systems Demand5 Reasons Driving Warehouse Management Systems Demand
5 Reasons Driving Warehouse Management Systems Demand
 
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
 
KLARNA - Language Models and Knowledge Graphs: A Systems Approach
KLARNA -  Language Models and Knowledge Graphs: A Systems ApproachKLARNA -  Language Models and Knowledge Graphs: A Systems Approach
KLARNA - Language Models and Knowledge Graphs: A Systems Approach
 
How to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabberHow to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabber
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
 
10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdf10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdf
 
CompTIA Security+ (Study Notes) for cs.pdf
CompTIA Security+ (Study Notes) for cs.pdfCompTIA Security+ (Study Notes) for cs.pdf
CompTIA Security+ (Study Notes) for cs.pdf
 
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
 

Linux Interrupts

  • 1. Linux Interrupts 1 Liran Ben Haim liran@discoversdk.com
  • 2. Rights to Copy  Attribution – ShareAlike 2.0  You are free to copy, distribute, display, and perform the work to make derivative works to make commercial use of the work Under the following conditions Attribution. You must give the original author credit. Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under a license identical to this one. For any reuse or distribution, you must make clear to others the license terms of this work. Any of these conditions can be waived if you get permission from the copyright holder. Your fair use and other rights are in no way affected by the above. License text: http://creativecommons.org/licenses/by-sa/2.0/legalcode  This kit contains work by the following authors:  © Copyright 2004-2009 Michael Opdenacker /Free Electrons michael@free-electrons.com http://www.free-electrons.com  © Copyright 2003-2006 Oron Peled oron@actcom.co.il http://www.actcom.co.il/~oron  © Copyright 2004–2008 Codefidence ltd. info@codefidence.com http://www.codefidence.com  © Copyright 2009–2010 Bina ltd. info@bna.co.il http://www.bna.co.il 2
  • 3. Interrupt handler constraints Not run from a user context: Can't transfer data to and from user space (need to be done by system call handlers) Interrupt handler execution is managed by the CPU, not by the scheduler. Handlers can't run actions that may sleep, because there is nothing to resume their execution. In particular, need to allocate memory with GFP_ATOMIC. Have to complete their job quickly enough: they shouldn't block their interrupt line for too long. 3
  • 4. Registering an interrupt handler (1)  Defined in include/linux/interrupt.h int request_irq( Returns 0 if successful unsigned int irq, Requested irq channel irqreturn_t handler, Interrupt handler unsigned long irq_flags, Option mask (see next page) const char * devname, Registered name void *dev_id); Pointer to some handler data Cannot be NULL and must be unique for shared irqs! void free_irq( unsigned int irq, void *dev_id); dev_id cannot be NULL and must be unique for shared irqs. Otherwise, on a shared interrupt line, free_irq wouldn't know which handler to free. 4
  • 5. Registering an interrupt handler (2)  irq_flags bit values (can be combined, none is fine too) IRQF_DISABLED "Quick" interrupt handler. Run with all interrupts disabled on the current cpu (instead of just the current line). For latency reasons, should only be used when needed! IRQF_SHARED Run with interrupts disabled only on the current irq line and on the local cpu. The interrupt channel can be shared by several devices. Requires a hardware status register telling whether an IRQ was raised or not. IRQF_SAMPLE_RANDOM Interrupts can be used to contribute to the system entropy pool used by /dev/random and /dev/urandom. Useful to generate good random numbers. Don't use this if the interrupt behavior of your device is predictable! 5
  • 6. Information  /proc/interrupts  CPU0 0: 5616905 XT-PIC timer # Registered name 1: 9828 XT-PIC i8042 2: 0 XT-PIC cascade 3: 1014243 XT-PIC orinoco_cs 7: 184 XT-PIC Intel 82801DB-ICH4 8: 1 XT-PIC rtc 9: 2 XT-PIC acpi 11: 566583 XT-PIC ehci_hcd, yenta, yenta, radeon@PCI:1:0:0 12: 5466 XT-PIC i8042 14: 121043 XT-PIC ide0 15: 200888 XT-PIC ide1 NMI: 0 Non Maskable Interrupts ERR: 0 Spurious interrupt count 6
  • 7. Interrupt handler prototype  irqreturn_t (*handler) ( int, // irq number of the current interrupt void *dev_id, // Pointer used to keep track // of the corresponding device. // Useful when several devices // are managed by the same module );  Return value: IRQ_HANDLED: recognized and handled interrupt IRQ_NONE: not on a device managed by the module. Useful to share interrupt channels and/or report spurious interrupts to the kernel. 7
  • 8. Linux Contexts User Space Process Context Interrupt Handlers Kernel Space Interrupt Context SoftIRQs Hiprio tasklets Net Stack Timers Regular tasklets ... Scheduling Points Process Thread Kernel Thread 8
  • 9. Top half and bottom half processing (1)  Splitting the execution of interrupt handlers in 2 parts Top half: the interrupt handler must complete as quickly as possible. Once it acknowledged the interrupt, it just schedules the lengthy rest of the job taking care of the data, for a later execution. Bottom half: completing the rest of the interrupt handler job. Handles data, and then wakes up any waiting user process. Best implemented by tasklets (also called soft irqs). 9
  • 10. top half and bottom half processing (2) Declare a Tasklet interrupt context Declare a WorkQueue Kernel thread Pop the interrupt to user space 10
  • 11. Handling in User Space  Sending Signal  Use send_sig_info  Using NetLink Socket  Use netlink_broadcast with GFP_ATOMIC  Using Wait Queue  wake_up_interruptible 11
  • 12. Disabling interrupts  May be useful in regular driver code... Can be useful to ensure that an interrupt handler will not preempt your code (including kernel preemption) Disabling interrupts on the local CPU: unsigned long flags; local_irq_save(flags); // Interrupts disabled ... local_irq_restore(flags); // Interrupts restored to their previous state. Note: must be run from within the same function! 12
  • 13. Masking out an interrupt line  Useful to disable interrupts on a particular line void disable_irq (unsigned int irq); Disables the irq line for all processors in the system. Waits for all currently executing handlers to complete. void disable_irq_nosync (unsigned int irq); Same, except it doesn't wait for handlers to complete. void enable_irq (unsigned int irq); Restores interrupts on the irq line. void synchronize_irq (unsigned int irq); Waits for irq handlers to complete (if any). 13
  • 14. Checking interrupt status  Can be useful for code which can be run from both process or interrupt context, to know whether it is allowed or not to call code that may sleep. irqs_disabled() Tests whether local interrupt delivery is disabled. in_interrupt() Tests whether code is running in interrupt context in_irq() Tests whether code is running in an interrupt handler. 14
  • 15. Thank You Code examples and more http://www.discoversdk.com/blog 15