SlideShare a Scribd company logo
Linux locking mechanisms
Mark Veltzer
veltzer@gnu.org
Who am I?
● Linux kernel hacker
● Current maintainer of gnu grep(1)
● Free Source evangelist
● CTO of Hinbit
● Political philosopher (checkout my book “‫ןוטלשלטון‬
‫”ההמון‬ at book stores near you...)
● Jazz piano player
Why locking?
● To avoid race conditions in accessing shared memory.
● These occur because of: user space pre-emption which is
based on timer interrupts (userspace), multi-core (userspace),
interrupts in general (kernelspace), multi-core (kernelspace).
● Locking is not the only way to avoid such race conditions
● But this presentation is about locking and only about locking...
● In general locking is bad because it blocks your programs from
executing and so slows your program
● Avoid it when you can.
Avoiding locking - techniques
● Have each thread/CPU have it's own data.
● Use atomic operations (hardware) instead of locking (software).
● Lock free programming.
● RCU/COW.
● Readers/Writer locks.
● Not using the shared memory model but rather the actor model
for multi-processing/multi-threading.
● And many more techniques.
● Alas, we are here to talk about locking.
User space vs kernel space locking
● Is completely different
● Different mechanisms, different performance
considerations, different API
● But ultimately they work in concert.
User space locking
User space locking mechanisms
● Are not allowed to block interrupts. Ever!
● This is derived from the definition of what a secure operating system
is.
● If you have code in the kernel you can expose an API to user space
to block and allow interrupts.
● This is considered a bad idea.
● First of all because it allows user space bugs to lock up your
system.
● Second because it interferes with other kernel mechanisms (like
watchdogs, RCU and more).
● DON'T DO IT!
User space locking primitives
● pthread Spin lock
● Futex
● pthread mutex
● pthread Readers/writer lock.
● POSIX semaphore
● SYS V semaphore
User space spin lock - intro
● Is implemented as a simple TAS/CAS loop with CPU
relaxing and memory barrier.
● Pure user space implementation.
● DOES NOT DISABLE INTERRUPTS!
● Did I mention that it DOES NOT DISABLE
INTERRUPTS?!?
● It is interesting to note that IT DOES NOT DISABLE
INTERRUPTS.
● And finally note that NO INTERRUPTS ARE DISABLED
User space spin lock - issues
● The API is straight forward.
● The problem with this API is that IT DOES NOT
DISABLE INTERRUPTS
● This means that you may end up spinning for a
whole time slice (~1ms) if the two racing contexts are
on the same core.
● This may also happen if two context are on different
cores but one is pre-empted by some other context.
● This is really bad.
User space spin lock – when to
use?
● Use only when the two racing contexts are
running on two different cores and are the
highest priority contexts on these two cores.
● Usually this is only fulfilled on a dedicated RT
patched Linux system.
● Otherwise you get period spinning episodes.
● Kapish?!?
Futex – Fast user space locking
● The idea is to avoid trips to the kernel in the non
contended case.
● A mutex build half in user space and half in kernel
space.
● State of the lock is in user space.
● Wait list is in kernel space.
● Allows to lock/unlock without calling kernel space in
the non contended case.
● A Masterpiece of Linux engineering!
What happens when you die with a
lock held?
● Here are some suggestions:
– OS does nothing → deadlocks
– OS releases the lock → other contexts die because
of inconsistent data
– OS releases the lock and notifies the next context
locking the lock that the previous owner died →
This is what Linux does.
● This feature of locks is called robustness.
Linux has no threads
● Do you remember that Linux has no concept of a “thread”?
● Threads are just processes which happen to share a lot of
memory created with the clone(2) system call.
●
Don't tell this to user space developers in your company (they
tend to freak out about this).
●
This means that every locking mechanism in Linux can be
used for multi-processing as well as for multi-threading.
●
This is why futexes were made robust.
●
Futexes are robust by doing postmortem on dead processes and
examining the locks they leave behind in order to unlock them and
mark them as suspicious.
pthread_mutex
● Is now days just a wrapper for a futex.
● Could be used between processes (strange, but oh so true).
● Could be made robust using the undocumented API
pthread_mutexattr_setrobust(3).
● I found the documentation for this API on MSDN, of all
places…:)
● Supports recursiveness, two types of priority inheritance,
sharing between processes, priority ceiling and more.
● Makes lousy coffee, though...
Pthread readers/writer lock
● Is based on the futex.
● This means good performance.
● Standard, feature poor implementation.
● Build your own if you need more features.
● Could be used to synchronize processes and
threads.
POSIX semaphores
● Based on the futex.
● Again, good performance.
● Use this and not the Sys V version unless
you need the Sys V particular features.
● Could be used to synchronize both processes
and threads.
Sys V semaphore
● Reminder: Sys V is AT&T's version of UNIX
dating to circa 1983. In that version important
API's like this one were first introduced into the
UNIX world.
● Sys V semaphores are, however, crap.
● This is because they always go to the kernel.
Even in the non contended case.
● Do not use. Use POSIX semaphores instead.
Kernel locking
Kernel locking primitives
● Mutex
● Spinlock (3 types)
● Semaphore
● RW semaphores
Mutexes
● Go to sleep when finding the lock locked.
● This means they can only be used in contexts where you are
allowed to go to sleep.
● This means passive(user) context, kernel thread or workqueue
context and threaded IRQ context (?!?).
● Not allowed in IRQ handlers or tasklets.
● Has 3 modes: interruptible, killable and uninterruptible.
● Try to use interruptible as much as possible as bugs in kernel
code may cause non killable processes.
● Support priority inheritance under the RT patch.
Spin locks
● Most common kernel locking primitive.
● Are divided into 3 types: regular, BH and IRQ.
● Regular spin locks just turn off scheduling on the current CPU (in addition
to being a spin lock).
● BH turn off Bottom half mechanisms (including tasklets) on the current
CPU (in addition to being a spin lock).
● IRQ ones turn off interrupts on the local CPU (in addition to being a spin
lock).
● Sleeping, waiting or doing heavy computation with spin locks held is
considered reason for being banned from LKML.
● Turn into Mutexes under the RT patch and then support priority
inheritance.
Spin lock (irq version)
● Turning of IRQs is quite fast (IF, CLI, STI are
really fast on INTEL).
● Very brutal as it increases latency in real time
implementations.
● Try not to access data structure from IRQ
context so you won't have to use this.
● However, this is still one of the most common
locking primitives
When to use each?
● Passive vs Passive
– Use a mutex in interruptible mode (you are allowed to sleep in both).
– Or semaphore in interruptible mode.
– Or a regular spin lock. You are in no danger of spinning for long since scheduling on the current CPU is disabled. Interrupts may
come in and so do tasklets but these are quick.
●
Passive vs BH
– spinlock_bh
● Passive vs IRQ
– Use spin lock irq.
– The irq part prevents races on the current CPU.
– The spin lock part prevents races with other CPUs.
● BH vs BH
– Spinlock
● BH vs IRQ
– Spinlock irq
● IRQ vs IRQ
– Spinlock irq.
● See “Rusty Russells Unreliable Guide to Locking”
Semaphores
● semaphore.h
● Usually used as a mutex and not as a semaphore.
● Up and down methods do not accept ticket number but always
increase and decrease by 1.
● Ticket/permit count can be determined at creation time.
● Semaphores do not offer priority inheritance. Even under the
RT patch.
● This means that any system call that uses this is unfit to be
used in the critical path of a real time application.
● 3 modes of operation (like the mutex).
RW semaphores
● rwsem.h
● Offer more performance when number of readers
outnumbers number of writers.
● Again, does not support priority inheritance. Even
under the RT patch.
● Famous is the current->mm->mmap_sem that
protects each processes virtual memory description.
● Good reason not to use malloc(3) in real time
systems.
RW lock
● rwlock.h
● By Ingo Molnar (author of the real time patch).
● Supports priority inheritance.
● Use this instead of RW semaphores.
● Again, gives better performance when number
of readers out numbers number of writers.
The RT patch
● Runs all irq handlers in their own threads with
other interrupts enabled.
● Turns all spinlocks into mutexes to reduce
latency and allow high priority tasks to get the
CPU ASAP.
● If you really need a spin lock you can use the
raw spinlock API which will give you a true
spinlock even under the RT patch.

More Related Content

What's hot (20)

PPTX
Linux Initialization Process (2)
shimosawa
 
PDF
The Linux Kernel Scheduler (For Beginners) - SFO17-421
Linaro
 
PDF
Linux Performance Profiling and Monitoring
Georg Schönberger
 
PDF
Process Scheduler and Balancer in Linux Kernel
Haifeng Li
 
PDF
Linux Networking Explained
Thomas Graf
 
PDF
10分で分かるLinuxブロックレイヤ
Takashi Hoshino
 
PDF
Fun with Network Interfaces
Kernel TLV
 
PDF
UM2019 Extended BPF: A New Type of Software
Brendan Gregg
 
PDF
Linux Performance Analysis: New Tools and Old Secrets
Brendan Gregg
 
PDF
eBPF Trace from Kernel to Userspace
SUSE Labs Taipei
 
PDF
DPDK in Containers Hands-on Lab
Michelle Holley
 
PPTX
Linux Kernel Module - For NLKB
shimosawa
 
PDF
Part 01 Linux Kernel Compilation (Ubuntu)
Tushar B Kute
 
PDF
BPF Internals (eBPF)
Brendan Gregg
 
PDF
netfilter and iptables
Kernel TLV
 
PDF
Qemu Introduction
Chiawei Wang
 
PDF
The linux networking architecture
hugo lu
 
PDF
Scheduling in Android
Opersys inc.
 
PDF
Embedded Recipes 2017 - Introduction to Yocto Project/OpenEmbedded - Mylène J...
Anne Nicolas
 
PDF
BKK16-208 EAS
Linaro
 
Linux Initialization Process (2)
shimosawa
 
The Linux Kernel Scheduler (For Beginners) - SFO17-421
Linaro
 
Linux Performance Profiling and Monitoring
Georg Schönberger
 
Process Scheduler and Balancer in Linux Kernel
Haifeng Li
 
Linux Networking Explained
Thomas Graf
 
10分で分かるLinuxブロックレイヤ
Takashi Hoshino
 
Fun with Network Interfaces
Kernel TLV
 
UM2019 Extended BPF: A New Type of Software
Brendan Gregg
 
Linux Performance Analysis: New Tools and Old Secrets
Brendan Gregg
 
eBPF Trace from Kernel to Userspace
SUSE Labs Taipei
 
DPDK in Containers Hands-on Lab
Michelle Holley
 
Linux Kernel Module - For NLKB
shimosawa
 
Part 01 Linux Kernel Compilation (Ubuntu)
Tushar B Kute
 
BPF Internals (eBPF)
Brendan Gregg
 
netfilter and iptables
Kernel TLV
 
Qemu Introduction
Chiawei Wang
 
The linux networking architecture
hugo lu
 
Scheduling in Android
Opersys inc.
 
Embedded Recipes 2017 - Introduction to Yocto Project/OpenEmbedded - Mylène J...
Anne Nicolas
 
BKK16-208 EAS
Linaro
 

Similar to Linux Locking Mechanisms (20)

PDF
Kernel locking
Kalimuthu Velappan
 
PDF
Linux kernel development_ch9-10_20120410
huangachou
 
PDF
Linux kernel development chapter 10
huangachou
 
DOC
Linux synchronization tools
mukul bhardwaj
 
PDF
Describe synchronization techniques used by programmers who develop .pdf
excellentmobiles
 
PPT
Synchronization linux
Susant Sahani
 
PDF
AOS Lab 4: If you liked it, then you should have put a “lock” on it
Zubair Nabi
 
PPTX
Dead Lock Analysis of spin_lock() in Linux Kernel (english)
Sneeker Yeh
 
PDF
semaphore & mutex.pdf
Adrian Huang
 
PPTX
Operating Systems
Harshith Meela
 
PPTX
Memory model
Yi-Hsiu Hsu
 
PPT
Os4
issbp
 
PPTX
Computer architecture related concepts, process
ssusera979f41
 
PDF
spinlock.pdf
Adrian Huang
 
PPTX
ch 7 POSIX.pptx
sibokac
 
PPTX
Preempt_rt realtime patch
Emre Can Kucukoglu
 
PPTX
Synchronization problem with threads
Syed Zaid Irshad
 
PDF
Making Linux do Hard Real-time
National Cheng Kung University
 
PDF
An Introduction to Locks in Go
Yu-Shuan Hsieh
 
Kernel locking
Kalimuthu Velappan
 
Linux kernel development_ch9-10_20120410
huangachou
 
Linux kernel development chapter 10
huangachou
 
Linux synchronization tools
mukul bhardwaj
 
Describe synchronization techniques used by programmers who develop .pdf
excellentmobiles
 
Synchronization linux
Susant Sahani
 
AOS Lab 4: If you liked it, then you should have put a “lock” on it
Zubair Nabi
 
Dead Lock Analysis of spin_lock() in Linux Kernel (english)
Sneeker Yeh
 
semaphore & mutex.pdf
Adrian Huang
 
Operating Systems
Harshith Meela
 
Memory model
Yi-Hsiu Hsu
 
Os4
issbp
 
Computer architecture related concepts, process
ssusera979f41
 
spinlock.pdf
Adrian Huang
 
ch 7 POSIX.pptx
sibokac
 
Preempt_rt realtime patch
Emre Can Kucukoglu
 
Synchronization problem with threads
Syed Zaid Irshad
 
Making Linux do Hard Real-time
National Cheng Kung University
 
An Introduction to Locks in Go
Yu-Shuan Hsieh
 
Ad

More from Kernel TLV (20)

PDF
DPDK In Depth
Kernel TLV
 
PDF
Building Network Functions with eBPF & BCC
Kernel TLV
 
PDF
SGX Trusted Execution Environment
Kernel TLV
 
PDF
Fun with FUSE
Kernel TLV
 
PPTX
Kernel Proc Connector and Containers
Kernel TLV
 
PPTX
Bypassing ASLR Exploiting CVE 2015-7545
Kernel TLV
 
PDF
Present Absence of Linux Filesystem Security
Kernel TLV
 
PDF
OpenWrt From Top to Bottom
Kernel TLV
 
PDF
Make Your Containers Faster: Linux Container Performance Tools
Kernel TLV
 
PDF
Emerging Persistent Memory Hardware and ZUFS - PM-based File Systems in User ...
Kernel TLV
 
PDF
File Systems: Why, How and Where
Kernel TLV
 
PDF
KernelTLV Speaker Guidelines
Kernel TLV
 
PDF
Userfaultfd: Current Features, Limitations and Future Development
Kernel TLV
 
PDF
The Linux Block Layer - Built for Fast Storage
Kernel TLV
 
PDF
Linux Kernel Cryptographic API and Use Cases
Kernel TLV
 
PPTX
DMA Survival Guide
Kernel TLV
 
PPSX
FD.IO Vector Packet Processing
Kernel TLV
 
PPTX
WiFi and the Beast
Kernel TLV
 
PPTX
Introduction to DPDK
Kernel TLV
 
PDF
FreeBSD and Drivers
Kernel TLV
 
DPDK In Depth
Kernel TLV
 
Building Network Functions with eBPF & BCC
Kernel TLV
 
SGX Trusted Execution Environment
Kernel TLV
 
Fun with FUSE
Kernel TLV
 
Kernel Proc Connector and Containers
Kernel TLV
 
Bypassing ASLR Exploiting CVE 2015-7545
Kernel TLV
 
Present Absence of Linux Filesystem Security
Kernel TLV
 
OpenWrt From Top to Bottom
Kernel TLV
 
Make Your Containers Faster: Linux Container Performance Tools
Kernel TLV
 
Emerging Persistent Memory Hardware and ZUFS - PM-based File Systems in User ...
Kernel TLV
 
File Systems: Why, How and Where
Kernel TLV
 
KernelTLV Speaker Guidelines
Kernel TLV
 
Userfaultfd: Current Features, Limitations and Future Development
Kernel TLV
 
The Linux Block Layer - Built for Fast Storage
Kernel TLV
 
Linux Kernel Cryptographic API and Use Cases
Kernel TLV
 
DMA Survival Guide
Kernel TLV
 
FD.IO Vector Packet Processing
Kernel TLV
 
WiFi and the Beast
Kernel TLV
 
Introduction to DPDK
Kernel TLV
 
FreeBSD and Drivers
Kernel TLV
 
Ad

Recently uploaded (20)

PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PDF
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 

Linux Locking Mechanisms

  • 2. Who am I? ● Linux kernel hacker ● Current maintainer of gnu grep(1) ● Free Source evangelist ● CTO of Hinbit ● Political philosopher (checkout my book “‫ןוטלשלטון‬ ‫”ההמון‬ at book stores near you...) ● Jazz piano player
  • 3. Why locking? ● To avoid race conditions in accessing shared memory. ● These occur because of: user space pre-emption which is based on timer interrupts (userspace), multi-core (userspace), interrupts in general (kernelspace), multi-core (kernelspace). ● Locking is not the only way to avoid such race conditions ● But this presentation is about locking and only about locking... ● In general locking is bad because it blocks your programs from executing and so slows your program ● Avoid it when you can.
  • 4. Avoiding locking - techniques ● Have each thread/CPU have it's own data. ● Use atomic operations (hardware) instead of locking (software). ● Lock free programming. ● RCU/COW. ● Readers/Writer locks. ● Not using the shared memory model but rather the actor model for multi-processing/multi-threading. ● And many more techniques. ● Alas, we are here to talk about locking.
  • 5. User space vs kernel space locking ● Is completely different ● Different mechanisms, different performance considerations, different API ● But ultimately they work in concert.
  • 7. User space locking mechanisms ● Are not allowed to block interrupts. Ever! ● This is derived from the definition of what a secure operating system is. ● If you have code in the kernel you can expose an API to user space to block and allow interrupts. ● This is considered a bad idea. ● First of all because it allows user space bugs to lock up your system. ● Second because it interferes with other kernel mechanisms (like watchdogs, RCU and more). ● DON'T DO IT!
  • 8. User space locking primitives ● pthread Spin lock ● Futex ● pthread mutex ● pthread Readers/writer lock. ● POSIX semaphore ● SYS V semaphore
  • 9. User space spin lock - intro ● Is implemented as a simple TAS/CAS loop with CPU relaxing and memory barrier. ● Pure user space implementation. ● DOES NOT DISABLE INTERRUPTS! ● Did I mention that it DOES NOT DISABLE INTERRUPTS?!? ● It is interesting to note that IT DOES NOT DISABLE INTERRUPTS. ● And finally note that NO INTERRUPTS ARE DISABLED
  • 10. User space spin lock - issues ● The API is straight forward. ● The problem with this API is that IT DOES NOT DISABLE INTERRUPTS ● This means that you may end up spinning for a whole time slice (~1ms) if the two racing contexts are on the same core. ● This may also happen if two context are on different cores but one is pre-empted by some other context. ● This is really bad.
  • 11. User space spin lock – when to use? ● Use only when the two racing contexts are running on two different cores and are the highest priority contexts on these two cores. ● Usually this is only fulfilled on a dedicated RT patched Linux system. ● Otherwise you get period spinning episodes. ● Kapish?!?
  • 12. Futex – Fast user space locking ● The idea is to avoid trips to the kernel in the non contended case. ● A mutex build half in user space and half in kernel space. ● State of the lock is in user space. ● Wait list is in kernel space. ● Allows to lock/unlock without calling kernel space in the non contended case. ● A Masterpiece of Linux engineering!
  • 13. What happens when you die with a lock held? ● Here are some suggestions: – OS does nothing → deadlocks – OS releases the lock → other contexts die because of inconsistent data – OS releases the lock and notifies the next context locking the lock that the previous owner died → This is what Linux does. ● This feature of locks is called robustness.
  • 14. Linux has no threads ● Do you remember that Linux has no concept of a “thread”? ● Threads are just processes which happen to share a lot of memory created with the clone(2) system call. ● Don't tell this to user space developers in your company (they tend to freak out about this). ● This means that every locking mechanism in Linux can be used for multi-processing as well as for multi-threading. ● This is why futexes were made robust. ● Futexes are robust by doing postmortem on dead processes and examining the locks they leave behind in order to unlock them and mark them as suspicious.
  • 15. pthread_mutex ● Is now days just a wrapper for a futex. ● Could be used between processes (strange, but oh so true). ● Could be made robust using the undocumented API pthread_mutexattr_setrobust(3). ● I found the documentation for this API on MSDN, of all places…:) ● Supports recursiveness, two types of priority inheritance, sharing between processes, priority ceiling and more. ● Makes lousy coffee, though...
  • 16. Pthread readers/writer lock ● Is based on the futex. ● This means good performance. ● Standard, feature poor implementation. ● Build your own if you need more features. ● Could be used to synchronize processes and threads.
  • 17. POSIX semaphores ● Based on the futex. ● Again, good performance. ● Use this and not the Sys V version unless you need the Sys V particular features. ● Could be used to synchronize both processes and threads.
  • 18. Sys V semaphore ● Reminder: Sys V is AT&T's version of UNIX dating to circa 1983. In that version important API's like this one were first introduced into the UNIX world. ● Sys V semaphores are, however, crap. ● This is because they always go to the kernel. Even in the non contended case. ● Do not use. Use POSIX semaphores instead.
  • 20. Kernel locking primitives ● Mutex ● Spinlock (3 types) ● Semaphore ● RW semaphores
  • 21. Mutexes ● Go to sleep when finding the lock locked. ● This means they can only be used in contexts where you are allowed to go to sleep. ● This means passive(user) context, kernel thread or workqueue context and threaded IRQ context (?!?). ● Not allowed in IRQ handlers or tasklets. ● Has 3 modes: interruptible, killable and uninterruptible. ● Try to use interruptible as much as possible as bugs in kernel code may cause non killable processes. ● Support priority inheritance under the RT patch.
  • 22. Spin locks ● Most common kernel locking primitive. ● Are divided into 3 types: regular, BH and IRQ. ● Regular spin locks just turn off scheduling on the current CPU (in addition to being a spin lock). ● BH turn off Bottom half mechanisms (including tasklets) on the current CPU (in addition to being a spin lock). ● IRQ ones turn off interrupts on the local CPU (in addition to being a spin lock). ● Sleeping, waiting or doing heavy computation with spin locks held is considered reason for being banned from LKML. ● Turn into Mutexes under the RT patch and then support priority inheritance.
  • 23. Spin lock (irq version) ● Turning of IRQs is quite fast (IF, CLI, STI are really fast on INTEL). ● Very brutal as it increases latency in real time implementations. ● Try not to access data structure from IRQ context so you won't have to use this. ● However, this is still one of the most common locking primitives
  • 24. When to use each? ● Passive vs Passive – Use a mutex in interruptible mode (you are allowed to sleep in both). – Or semaphore in interruptible mode. – Or a regular spin lock. You are in no danger of spinning for long since scheduling on the current CPU is disabled. Interrupts may come in and so do tasklets but these are quick. ● Passive vs BH – spinlock_bh ● Passive vs IRQ – Use spin lock irq. – The irq part prevents races on the current CPU. – The spin lock part prevents races with other CPUs. ● BH vs BH – Spinlock ● BH vs IRQ – Spinlock irq ● IRQ vs IRQ – Spinlock irq. ● See “Rusty Russells Unreliable Guide to Locking”
  • 25. Semaphores ● semaphore.h ● Usually used as a mutex and not as a semaphore. ● Up and down methods do not accept ticket number but always increase and decrease by 1. ● Ticket/permit count can be determined at creation time. ● Semaphores do not offer priority inheritance. Even under the RT patch. ● This means that any system call that uses this is unfit to be used in the critical path of a real time application. ● 3 modes of operation (like the mutex).
  • 26. RW semaphores ● rwsem.h ● Offer more performance when number of readers outnumbers number of writers. ● Again, does not support priority inheritance. Even under the RT patch. ● Famous is the current->mm->mmap_sem that protects each processes virtual memory description. ● Good reason not to use malloc(3) in real time systems.
  • 27. RW lock ● rwlock.h ● By Ingo Molnar (author of the real time patch). ● Supports priority inheritance. ● Use this instead of RW semaphores. ● Again, gives better performance when number of readers out numbers number of writers.
  • 28. The RT patch ● Runs all irq handlers in their own threads with other interrupts enabled. ● Turns all spinlocks into mutexes to reduce latency and allow high priority tasks to get the CPU ASAP. ● If you really need a spin lock you can use the raw spinlock API which will give you a true spinlock even under the RT patch.