요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
Spinlock과 mutex 선택
locking.rst:101-160| 조건 | 기본 선택 | 이유 |
|---|---|---|
| Process context끼리, critical section에서 sleep 가능 | mutex | 경쟁 시 CPU를 scheduler에 양보 |
| Interrupt가 접근하거나 atomic context | spinlock 계열 | sleep할 수 없음 |
| 아주 짧고 process context만 접근 | 대개 mutex 우선 | PREEMPT_RT와 유지보수 semantics가 명확 |
Spinlock waiter는 owner가 놓을 때까지 CPU를 사용하므로 보유 구간은 짧고 sleep 함수 호출이 없어야 합니다. Mutex는 competition에서 task가 block되므로 process context만 허용합니다. PREEMPT_RT에서는 spinlock_t semantics가 달라지므로 raw_spinlock_t와 구분합니다.
UP build에서 spinlock instruction이 사라지거나 preemption disable만 남을 수 있어도 source에는 올바른 lock을 그대로 둡니다. CONFIG_SMP와 CONFIG_PREEMPT, lockdep build에서 test해야 빠진 lock과 ordering 문제를 드러낼 수 있습니다.
Process context와 softirq·timer 사이
locking.rst:161-241Process context와 softirq가 같은 data를 공유하면 process side는 spin_lock_bh()로 local softirq를 disable한 뒤 lock을 잡습니다. 다른 CPU softirq와의 경쟁은 spinlock이, 같은 CPU에서 process를 중단시키는 softirq 재진입은 _bh가 막습니다.
Softirq context 쪽은 이미 local bottom half가 실행 중이므로 보통 spin_lock()만 필요합니다. 다른 CPU에서 같은 softirq나 다른 softirq가 동시에 실행될 수 있어 shared global data에는 여전히 lock이 필요합니다. Per-CPU data로 분리하면 inter-CPU lock을 줄일 수 있지만 migration과 PREEMPT_RT 규칙을 적용해야 합니다.
이 역사적 문서에서 tasklet과 timer는 softirq 문맥 예로 함께 설명합니다. 새 code는 tasklet 사용을 피하고 timer callback에서 무거운 작업을 process-context work로 넘기는 현재 subsystem 관례를 따릅니다.
Hardirq와 다른 context 사이
locking.rst:242-290Hardirq와 softirq가 data를 공유하면 softirq side에서 spin_lock_irq()로 local hard IRQ를 막고 lock을 획득합니다. Hardirq side는 이미 해당 local interrupt condition 아래 있으므로 설계에 따라 plain spin_lock을 사용하지만 nested interrupt와 서로 다른 IRQ handler가 같은 lock을 공유하면 irqsave가 안전한 최소 조건입니다.
Process context까지 같은 data를 만지면 모든 caller의 context 중 가장 강한 local exclusion이 필요합니다. IRQ state가 항상 enabled라는 보장이 없으면 spin_lock_irqsave()와 restore를 사용하여 caller의 원래 state를 보존합니다.
최소 locking 요구를 계산하는 법
locking.rst:291-370| 공유 경로 | Process side | Interrupt side |
|---|---|---|
| Process 대 process | mutex 또는 spinlock | 해당 없음 |
| Process 대 softirq/timer | spin_lock_bh | spin_lock |
| Process 대 hardirq | spin_lock_irqsave | spin_lock |
| Softirq 대 hardirq | spin_lock_irq 또는 irqsave | spin_lock |
| Hardirq A 대 hardirq B | 각 handler에서 spin_lock_irqsave | 각 handler에서 동일 |
표는 최소 조건을 찾는 출발점입니다. 특정 IRQ line, threaded handler, PREEMPT_RT와 lock nesting에 따라 실제 요구가 달라집니다. 모호하면 무조건 가장 강한 variant로 끝내기보다 context graph를 문서화하고 lockdep·latency test로 검증합니다.
trylock은 성공하지 못하면 보호 data에 접근하지 않는 완전한 fallback이 있을 때 사용합니다. 실패한 뒤 lock 없이 상태를 읽어 결정을 내리면 race를 숨길 뿐입니다.
Cache object 사례: lock 밖에서 준비하고 안에서 publish
locking.rst:371-573Process context 전용 cache는 mutex로 list와 object를 보호할 수 있습니다. Allocation과 string copy처럼 시간이 걸리거나 실패 가능한 준비 작업은 lock 밖에서 수행하고, 마지막 중복 확인과 list insertion만 lock 안에서 처리해 hold time을 줄입니다.
Cache lookup이 interrupt에서도 호출되면 mutex를 spinlock으로 단순 교체하는 것만으로 충분하지 않습니다. GFP_KERNEL allocation, user copy와 긴 작업을 lock 밖으로 옮기고 interrupt caller가 참조할 object lifetime을 별도로 보장해야 합니다.
Lock 안에서 찾은 pointer를 unlock 뒤 반환하면 list membership 보호는 끝났습니다. Caller가 사용할 동안 object가 삭제되지 않도록 reference를 획득하거나 RCU read-side lifetime을 유지해야 합니다.
외부에 object pointer를 공개할 때
locking.rst:574-788Object를 다른 file과 subsystem에 공개하면 global cache lock을 모두에게 노출하는 방법보다 get/put API로 reference lifetime을 캡슐화하는 편이 낫습니다. Lookup은 lock 아래에서 reference를 증가시키고 caller는 사용을 마친 뒤 put하여 마지막 reference가 0일 때만 free합니다.
obj = cache_find_get(id); /* lookup과 ref 증가가 하나의 atomic protocol */
if (!obj)
return -ENOENT;
use_object(obj);
cache_put(obj); /* 마지막 ref면 destructor */
Reference counter 자체는 refcount_t로 lockless 갱신할 수 있지만 object를 찾는 순간 deletion과 경쟁하지 않는다는 보장이 여전히 필요합니다. Container lock, RCU, xarray의 reference helper 등 lookup과 get 사이를 하나의 protocol로 만듭니다.
Container lock과 object lock 분리
locking.rst:789-870Object field가 생성 후 불변이면 container membership lock과 reference만으로 충분할 수 있습니다. Name 같은 mutable field가 생기면 container lock을 모든 field까지 보호하게 하거나 object별 lock을 추가할 수 있습니다.
Object별 lock은 서로 다른 object의 병렬성을 높이지만 container lock과 중첩 순서를 정해야 합니다. 일반적으로 container에서 object를 찾아 reference를 얻고 container lock을 놓은 뒤 object lock을 잡는 구조가 긴 nesting을 줄입니다. 삭제 path는 reference와 state flag로 새 사용자를 차단합니다.
Self-deadlock, ABBA와 캡슐화
locking.rst:871-953Linux spinlock, rwlock과 mutex는 recursive lock이 아닙니다. 같은 task나 interrupt 재진입이 같은 lock을 다시 잡으면 진행할 수 없습니다. CPU 1이 A 뒤 B, CPU 2가 B 뒤 A를 잡으면 두 CPU가 서로의 lock을 기다리는 ABBA cycle이 됩니다.
전역 lock hierarchy 문서만으로 모든 새 edge를 관리하기는 어렵습니다. 좋은 lock은 file 또는 object implementation 안에 숨기고 보유한 채 외부의 복잡한 callback을 호출하지 않습니다. Callback이 필요하면 필요한 state를 capture하고 lock을 놓은 뒤 호출하거나 contract를 명시합니다.
Read lock에서 검색 실패 후 lock을 놓고 write lock을 다시 잡는 동안 다른 task가 object를 삽입할 수 있습니다. Write lock 아래에서 condition을 반드시 재검사해야 deadlock을 피하려다 중복 insertion race를 만들지 않습니다.
Timer deletion과 callback lifetime race
locking.rst:954-1014Collection을 해제할 때 timer_delete()만 호출하고 object를 free하면 다른 CPU에서 callback이 이미 실행 중일 수 있습니다. Callback이 같은 list lock을 잡는다면 lock을 보유한 채 timer_delete_sync()를 기다리는 것도 deadlock이 될 수 있습니다.
새 callback scheduling을 먼저 차단하고, container에서 object를 분리한 뒤 필요한 lock을 놓고 sync cancellation으로 실행 중 callback을 기다린 다음 free합니다. Module exit에서는 timer뿐 아니라 delayed work, tasklet, IRQ와 RCU callback까지 모두 drain해야 code와 data가 사라지지 않습니다.
Lock 성능과 read/write variant
locking.rst:1015-1063성능은 uncontended acquire 비용보다 contention 빈도와 hold time의 곱에 더 크게 좌우됩니다. Allocation, formatting과 I/O를 lock 밖으로 옮기고 data partitioning으로 같은 lock을 잡는 CPU 수를 줄이는 것이 우선입니다.
rwlock_t와 rw_semaphore는 reader를 병렬화하지만 bookkeeping이 더 비싸고 writer starvation과 PREEMPT_RT 특성이 있습니다. Read-side가 충분히 길고 동시에 실행되는 reader가 실제로 많다는 측정이 있을 때 선택합니다.
RCU로 reader lock을 없애는 원리
locking.rst:1064-1245RCU reader는 rcu_read_lock() 아래에서 pointer를 따라가며 writer lock을 잡지 않습니다. Writer는 새 node를 완성한 뒤 rcu_assign_pointer로 publish하고 삭제 node는 list에서 제거한 뒤 grace period가 지나 기존 reader가 모두 끝난 후 free합니다.
rcu_read_lock();
obj = rcu_dereference(global_obj);
if (obj)
read_fields(obj);
rcu_read_unlock();
old = rcu_replace_pointer(global_obj, new, lockdep_is_held(&update_lock));
synchronize_rcu();
kfree(old);
RCU는 writer synchronization, memory ordering과 object lifetime을 함께 설계해야 합니다. Reader가 pointer를 read-side section 밖으로 가져가려면 별도의 reference를 안전하게 증가시키는 protocol이 필요합니다.
Per-CPU data와 IRQ 중심 data
locking.rst:1246-1292Shared counter가 실제 병목일 때 per-CPU counter로 분할하면 write cacheline 경쟁을 없앨 수 있습니다. 대신 합계가 즉시 일관되지 않고 CPU hotplug, wrap과 batch merge를 처리해야 합니다. 단순하다는 이유가 아니라 측정된 contention을 근거로 사용합니다.
특정 IRQ handler가 대부분 사용하는 data라면 handler path를 lockless하게 두고 드문 process access에서 IRQ를 disable하여 직렬화할 수 있습니다. disable_irq()는 handler completion을 기다릴 수 있어 lock ordering과 sleep 가능 context를 주의해야 하며 PREEMPT_RT의 threaded IRQ도 고려합니다.
Interrupt에서 호출 가능한 함수 판별
locking.rst:1293-1369- copy_from_user, copy_to_user, get_user, put_user는 fault로 sleep할 수 있다.
- kmalloc(GFP_KERNEL), mutex_lock과 down 계열은 sleep할 수 있다.
- printk, kfree와 timer enqueue 일부는 atomic context에서 호출 가능하지만 각 API contract를 확인한다.
- Registration과 deregistration 함수는 대개 process context를 요구하고 내부적으로 sleep한다.
함수 이름이나 현재 구현 우연으로 추측하지 말고 header annotation, kernel-doc, might_sleep(), lockdep warning과 모든 caller를 확인합니다. 호출자가 spinlock을 보유할 수 있다면 callee가 나중에 sleep operation을 추가하지 못하도록 contract를 명시합니다.
Linux 6.18.37에서 함께 볼 문서
locking.rst:1370-1455- Lock 종류와 PREEMPT_RT 규칙
../locking/locktypes.html - Spinlock interrupt 규칙
../locking/spinlocks.html - Mutex 내부 구조와 lifetime
../locking/mutex-design.html - Sequence counter와 seqlock
../locking/seqlock.html - Lockdep graph
../locking/lockdep-design.html
이 guide의 cache 예제와 tasklet 표현은 역사적이지만 race, context, lifetime을 분리해 분석하는 방식은 그대로 유효합니다. 실제 새 code는 current subsystem의 locking rule, PREEMPT_RT build와 lockdep 결과를 최종 기준으로 삼습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
.. _kernel_hacking_lock:
===========================
Unreliable Guide To Locking
===========================
:Author: Rusty Russell
Introduction
============
Welcome, to Rusty's Remarkably Unreliable Guide to Kernel Locking
issues. This document describes the locking systems in the Linux Kernel
in 2.6.
With the wide availability of HyperThreading, and preemption in the
Linux Kernel, everyone hacking on the kernel needs to know the
fundamentals of concurrency and locking for SMP.
The Problem With Concurrency
============================
(Skip this if you know what a Race Condition is).
In a normal program, you can increment a counter like so:
::
very_important_count++;
This is what they would expect to happen:
.. table:: Expected Results
+------------------------------------+------------------------------------+
| Instance 1 | Instance 2 |
+====================================+====================================+
| read very_important_count (5) | |
+------------------------------------+------------------------------------+
| add 1 (6) | |
+------------------------------------+------------------------------------+
| write very_important_count (6) | |
+------------------------------------+------------------------------------+
| | read very_important_count (6) |
+------------------------------------+------------------------------------+
| | add 1 (7) |
+------------------------------------+------------------------------------+
| | write very_important_count (7) |
+------------------------------------+------------------------------------+
This is what might happen:
.. table:: Possible Results
+------------------------------------+------------------------------------+
| Instance 1 | Instance 2 |
+====================================+====================================+
| read very_important_count (5) | |
+------------------------------------+------------------------------------+
| | read very_important_count (5) |
+------------------------------------+------------------------------------+
| add 1 (6) | |
+------------------------------------+------------------------------------+
| | add 1 (6) |
+------------------------------------+------------------------------------+
| write very_important_count (6) | |
+------------------------------------+------------------------------------+
| | write very_important_count (6) |
+------------------------------------+------------------------------------+
Race Conditions and Critical Regions
------------------------------------
This overlap, where the result depends on the relative timing of
multiple tasks, is called a race condition. The piece of code containing
the concurrency issue is called a critical region. And especially since
Linux starting running on SMP machines, they became one of the major
issues in kernel design and implementation.
Preemption can have the same effect, even if there is only one CPU: by
preempting one task during the critical region, we have exactly the same
race condition. In this case the thread which preempts might run the
critical region itself.
The solution is to recognize when these simultaneous accesses occur, and
use locks to make sure that only one instance can enter the critical
region at any time. There are many friendly primitives in the Linux
kernel to help you do this. And then there are the unfriendly
primitives, but I'll pretend they don't exist.
Locking in the Linux Kernel
===========================
If I could give you one piece of advice on locking: **keep it simple**.
Be reluctant to introduce new locks.
Two Main Types of Kernel Locks: Spinlocks and Mutexes
-----------------------------------------------------
There are two main types of kernel locks. The fundamental type is the
spinlock (``include/asm/spinlock.h``), which is a very simple
single-holder lock: if you can't get the spinlock, you keep trying
(spinning) until you can. Spinlocks are very small and fast, and can be
used anywhere.
The second type is a mutex (``include/linux/mutex.h``): it is like a
spinlock, but you may block holding a mutex. If you can't lock a mutex,
your task will suspend itself, and be woken up when the mutex is
released. This means the CPU can do something else while you are
waiting. There are many cases when you simply can't sleep (see
`What Functions Are Safe To Call From Interrupts?`_),
and so have to use a spinlock instead.
Neither type of lock is recursive: see
`Deadlock: Simple and Advanced`_.
Locks and Uniprocessor Kernels
------------------------------
For kernels compiled without ``CONFIG_SMP``, and without
``CONFIG_PREEMPT`` spinlocks do not exist at all. This is an excellent
design decision: when no-one else can run at the same time, there is no
reason to have a lock.
If the kernel is compiled without ``CONFIG_SMP``, but ``CONFIG_PREEMPT``
is set, then spinlocks simply disable preemption, which is sufficient to
prevent any races. For most purposes, we can think of preemption as
equivalent to SMP, and not worry about it separately.
You should always test your locking code with ``CONFIG_SMP`` and
``CONFIG_PREEMPT`` enabled, even if you don't have an SMP test box,
because it will still catch some kinds of locking bugs.
Mutexes still exist, because they are required for synchronization
between user contexts, as we will see below.
Locking Only In User Context
----------------------------
If you have a data structure which is only ever accessed from user
context, then you can use a simple mutex (``include/linux/mutex.h``) to
protect it. This is the most trivial case: you initialize the mutex.
Then you can call mutex_lock_interruptible() to grab the
mutex, and mutex_unlock() to release it. There is also a
mutex_lock(), which should be avoided, because it will
not return if a signal is received.
Example: ``net/netfilter/nf_sockopt.c`` allows registration of new
setsockopt() and getsockopt() calls, with
nf_register_sockopt(). Registration and de-registration
are only done on module load and unload (and boot time, where there is
no concurrency), and the list of registrations is only consulted for an
unknown setsockopt() or getsockopt() system
call. The ``nf_sockopt_mutex`` is perfect to protect this, especially
since the setsockopt and getsockopt calls may well sleep.
Locking Between User Context and Softirqs
-----------------------------------------
If a softirq shares data with user context, you have two problems.
Firstly, the current user context can be interrupted by a softirq, and
secondly, the critical region could be entered from another CPU. This is
where spin_lock_bh() (``include/linux/spinlock.h``) is
used. It disables softirqs on that CPU, then grabs the lock.
spin_unlock_bh() does the reverse. (The '_bh' suffix is
a historical reference to "Bottom Halves", the old name for software
interrupts. It should really be called spin_lock_softirq()' in a
perfect world).
Note that you can also use spin_lock_irq() or
spin_lock_irqsave() here, which stop hardware interrupts
as well: see `Hard IRQ Context`_.
This works perfectly for UP as well: the spin lock vanishes, and this
macro simply becomes local_bh_disable()
(``include/linux/interrupt.h``), which protects you from the softirq
being run.
Locking Between User Context and Tasklets
-----------------------------------------
This is exactly the same as above, because tasklets are actually run
from a softirq.
Locking Between User Context and Timers
---------------------------------------
This, too, is exactly the same as above, because timers are actually run
from a softirq. From a locking point of view, tasklets and timers are
identical.
Locking Between Tasklets/Timers
-------------------------------
Sometimes a tasklet or timer might want to share data with another
tasklet or timer.
The Same Tasklet/Timer
~~~~~~~~~~~~~~~~~~~~~~
Since a tasklet is never run on two CPUs at once, you don't need to
worry about your tasklet being reentrant (running twice at once), even
on SMP.
Different Tasklets/Timers
~~~~~~~~~~~~~~~~~~~~~~~~~
If another tasklet/timer wants to share data with your tasklet or timer
, you will both need to use spin_lock() and
spin_unlock() calls. spin_lock_bh() is
unnecessary here, as you are already in a tasklet, and none will be run
on the same CPU.
Locking Between Softirqs
------------------------
Often a softirq might want to share data with itself or a tasklet/timer.
The Same Softirq
~~~~~~~~~~~~~~~~
The same softirq can run on the other CPUs: you can use a per-CPU array
(see `Per-CPU Data`_) for better performance. If you're
going so far as to use a softirq, you probably care about scalable
performance enough to justify the extra complexity.
You'll need to use spin_lock() and
spin_unlock() for shared data.
Different Softirqs
~~~~~~~~~~~~~~~~~~
You'll need to use spin_lock() and
spin_unlock() for shared data, whether it be a timer,
tasklet, different softirq or the same or another softirq: any of them
could be running on a different CPU.
Hard IRQ Context
================
Hardware interrupts usually communicate with a tasklet or softirq.
Frequently this involves putting work in a queue, which the softirq will
take out.
Locking Between Hard IRQ and Softirqs/Tasklets
----------------------------------------------
If a hardware irq handler shares data with a softirq, you have two
concerns. Firstly, the softirq processing can be interrupted by a
hardware interrupt, and secondly, the critical region could be entered
by a hardware interrupt on another CPU. This is where
spin_lock_irq() is used. It is defined to disable
interrupts on that cpu, then grab the lock.
spin_unlock_irq() does the reverse.
The irq handler does not need to use spin_lock_irq(), because
the softirq cannot run while the irq handler is running: it can use
spin_lock(), which is slightly faster. The only exception
would be if a different hardware irq handler uses the same lock:
spin_lock_irq() will stop that from interrupting us.
This works perfectly for UP as well: the spin lock vanishes, and this
macro simply becomes local_irq_disable()
(``include/asm/smp.h``), which protects you from the softirq/tasklet/BH
being run.
spin_lock_irqsave() (``include/linux/spinlock.h``) is a
variant which saves whether interrupts were on or off in a flags word,
which is passed to spin_unlock_irqrestore(). This means
that the same code can be used inside an hard irq handler (where
interrupts are already off) and in softirqs (where the irq disabling is
required).
Note that softirqs (and hence tasklets and timers) are run on return
from hardware interrupts, so spin_lock_irq() also stops
these. In that sense, spin_lock_irqsave() is the most
general and powerful locking function.
Locking Between Two Hard IRQ Handlers
-------------------------------------
It is rare to have to share data between two IRQ handlers, but if you
do, spin_lock_irqsave() should be used: it is
architecture-specific whether all interrupts are disabled inside irq
handlers themselves.
Cheat Sheet For Locking
=======================
Pete Zaitcev gives the following summary:
- If you are in a process context (any syscall) and want to lock other
process out, use a mutex. You can take a mutex and sleep
(``copy_from_user()`` or ``kmalloc(x,GFP_KERNEL)``).
- Otherwise (== data can be touched in an interrupt), use
spin_lock_irqsave() and
spin_unlock_irqrestore().
- Avoid holding spinlock for more than 5 lines of code and across any
function call (except accessors like readb()).
Table of Minimum Requirements
-----------------------------
The following table lists the **minimum** locking requirements between
various contexts. In some cases, the same context can only be running on
one CPU at a time, so no locking is required for that context (eg. a
particular thread can only run on one CPU at a time, but if it needs
shares data with another thread, locking is required).
Remember the advice above: you can always use
spin_lock_irqsave(), which is a superset of all other
spinlock primitives.
============== ============= ============= ========= ========= ========= ========= ======= ======= ============== ==============
. IRQ Handler A IRQ Handler B Softirq A Softirq B Tasklet A Tasklet B Timer A Timer B User Context A User Context B
============== ============= ============= ========= ========= ========= ========= ======= ======= ============== ==============
IRQ Handler A None
IRQ Handler B SLIS None
Softirq A SLI SLI SL
Softirq B SLI SLI SL SL
Tasklet A SLI SLI SL SL None
Tasklet B SLI SLI SL SL SL None
Timer A SLI SLI SL SL SL SL None
Timer B SLI SLI SL SL SL SL SL None
User Context A SLI SLI SLBH SLBH SLBH SLBH SLBH SLBH None
User Context B SLI SLI SLBH SLBH SLBH SLBH SLBH SLBH MLI None
============== ============= ============= ========= ========= ========= ========= ======= ======= ============== ==============
Table: Table of Locking Requirements
+--------+----------------------------+
| SLIS | spin_lock_irqsave |
+--------+----------------------------+
| SLI | spin_lock_irq |
+--------+----------------------------+
| SL | spin_lock |
+--------+----------------------------+
| SLBH | spin_lock_bh |
+--------+----------------------------+
| MLI | mutex_lock_interruptible |
+--------+----------------------------+
Table: Legend for Locking Requirements Table
The trylock Functions
=====================
There are functions that try to acquire a lock only once and immediately
return a value telling about success or failure to acquire the lock.
They can be used if you need no access to the data protected with the
lock when some other thread is holding the lock. You should acquire the
lock later if you then need access to the data protected with the lock.
spin_trylock() does not spin but returns non-zero if it
acquires the spinlock on the first try or 0 if not. This function can be
used in all contexts like spin_lock(): you must have
disabled the contexts that might interrupt you and acquire the spin
lock.
mutex_trylock() does not suspend your task but returns
non-zero if it could lock the mutex on the first try or 0 if not. This
function cannot be safely used in hardware or software interrupt
contexts despite not sleeping.
Common Examples
===============
Let's step through a simple example: a cache of number to name mappings.
The cache keeps a count of how often each of the objects is used, and
when it gets full, throws out the least used one.
All In User Context
-------------------
For our first example, we assume that all operations are in user context
(ie. from system calls), so we can sleep. This means we can use a mutex
to protect the cache and all the objects within it. Here's the code::
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/mutex.h>
#include <asm/errno.h>
struct object
{
struct list_head list;
int id;
char name[32];
int popularity;
};
/* Protects the cache, cache_num, and the objects within it */
static DEFINE_MUTEX(cache_lock);
static LIST_HEAD(cache);
static unsigned int cache_num = 0;
#define MAX_CACHE_SIZE 10
/* Must be holding cache_lock */
static struct object *__cache_find(int id)
{
struct object *i;
list_for_each_entry(i, &cache, list)
if (i->id == id) {
i->popularity++;
return i;
}
return NULL;
}
/* Must be holding cache_lock */
static void __cache_delete(struct object *obj)
{
BUG_ON(!obj);
list_del(&obj->list);
kfree(obj);
cache_num--;
}
/* Must be holding cache_lock */
static void __cache_add(struct object *obj)
{
list_add(&obj->list, &cache);
if (++cache_num > MAX_CACHE_SIZE) {
struct object *i, *outcast = NULL;
list_for_each_entry(i, &cache, list) {
if (!outcast || i->popularity < outcast->popularity)
outcast = i;
}
__cache_delete(outcast);
}
}
int cache_add(int id, const char *name)
{
struct object *obj;
if ((obj = kmalloc(sizeof(*obj), GFP_KERNEL)) == NULL)
return -ENOMEM;
strscpy(obj->name, name, sizeof(obj->name));
obj->id = id;
obj->popularity = 0;
mutex_lock(&cache_lock);
__cache_add(obj);
mutex_unlock(&cache_lock);
return 0;
}
void cache_delete(int id)
{
mutex_lock(&cache_lock);
__cache_delete(__cache_find(id));
mutex_unlock(&cache_lock);
}
int cache_find(int id, char *name)
{
struct object *obj;
int ret = -ENOENT;
mutex_lock(&cache_lock);
obj = __cache_find(id);
if (obj) {
ret = 0;
strcpy(name, obj->name);
}
mutex_unlock(&cache_lock);
return ret;
}
Note that we always make sure we have the cache_lock when we add,
delete, or look up the cache: both the cache infrastructure itself and
the contents of the objects are protected by the lock. In this case it's
easy, since we copy the data for the user, and never let them access the
objects directly.
There is a slight (and common) optimization here: in
cache_add() we set up the fields of the object before
grabbing the lock. This is safe, as no-one else can access it until we
put it in cache.
Accessing From Interrupt Context
--------------------------------
Now consider the case where cache_find() can be called
from interrupt context: either a hardware interrupt or a softirq. An
example would be a timer which deletes object from the cache.
The change is shown below, in standard patch format: the ``-`` are lines
which are taken away, and the ``+`` are lines which are added.
::
--- cache.c.usercontext 2003-12-09 13:58:54.000000000 +1100
+++ cache.c.interrupt 2003-12-09 14:07:49.000000000 +1100
@@ -12,7 +12,7 @@
int popularity;
};
-static DEFINE_MUTEX(cache_lock);
+static DEFINE_SPINLOCK(cache_lock);
static LIST_HEAD(cache);
static unsigned int cache_num = 0;
#define MAX_CACHE_SIZE 10
@@ -55,6 +55,7 @@
int cache_add(int id, const char *name)
{
struct object *obj;
+ unsigned long flags;
if ((obj = kmalloc(sizeof(*obj), GFP_KERNEL)) == NULL)
return -ENOMEM;
@@ -63,30 +64,33 @@
obj->id = id;
obj->popularity = 0;
- mutex_lock(&cache_lock);
+ spin_lock_irqsave(&cache_lock, flags);
__cache_add(obj);
- mutex_unlock(&cache_lock);
+ spin_unlock_irqrestore(&cache_lock, flags);
return 0;
}
void cache_delete(int id)
{
- mutex_lock(&cache_lock);
+ unsigned long flags;
+
+ spin_lock_irqsave(&cache_lock, flags);
__cache_delete(__cache_find(id));
- mutex_unlock(&cache_lock);
+ spin_unlock_irqrestore(&cache_lock, flags);
}
int cache_find(int id, char *name)
{
struct object *obj;
int ret = -ENOENT;
+ unsigned long flags;
- mutex_lock(&cache_lock);
+ spin_lock_irqsave(&cache_lock, flags);
obj = __cache_find(id);
if (obj) {
ret = 0;
strcpy(name, obj->name);
}
- mutex_unlock(&cache_lock);
+ spin_unlock_irqrestore(&cache_lock, flags);
return ret;
}
Note that the spin_lock_irqsave() will turn off
interrupts if they are on, otherwise does nothing (if we are already in
an interrupt handler), hence these functions are safe to call from any
context.
Unfortunately, cache_add() calls kmalloc()
with the ``GFP_KERNEL`` flag, which is only legal in user context. I
have assumed that cache_add() is still only called in
user context, otherwise this should become a parameter to
cache_add().
Exposing Objects Outside This File
----------------------------------
If our objects contained more information, it might not be sufficient to
copy the information in and out: other parts of the code might want to
keep pointers to these objects, for example, rather than looking up the
id every time. This produces two problems.
The first problem is that we use the ``cache_lock`` to protect objects:
we'd need to make this non-static so the rest of the code can use it.
This makes locking trickier, as it is no longer all in one place.
The second problem is the lifetime problem: if another structure keeps a
pointer to an object, it presumably expects that pointer to remain
valid. Unfortunately, this is only guaranteed while you hold the lock,
otherwise someone might call cache_delete() and even
worse, add another object, re-using the same address.
As there is only one lock, you can't hold it forever: no-one else would
get any work done.
The solution to this problem is to use a reference count: everyone who
has a pointer to the object increases it when they first get the object,
and drops the reference count when they're finished with it. Whoever
drops it to zero knows it is unused, and can actually delete it.
Here is the code::
--- cache.c.interrupt 2003-12-09 14:25:43.000000000 +1100
+++ cache.c.refcnt 2003-12-09 14:33:05.000000000 +1100
@@ -7,6 +7,7 @@
struct object
{
struct list_head list;
+ unsigned int refcnt;
int id;
char name[32];
int popularity;
@@ -17,6 +18,35 @@
static unsigned int cache_num = 0;
#define MAX_CACHE_SIZE 10
+static void __object_put(struct object *obj)
+{
+ if (--obj->refcnt == 0)
+ kfree(obj);
+}
+
+static void __object_get(struct object *obj)
+{
+ obj->refcnt++;
+}
+
+void object_put(struct object *obj)
+{
+ unsigned long flags;
+
+ spin_lock_irqsave(&cache_lock, flags);
+ __object_put(obj);
+ spin_unlock_irqrestore(&cache_lock, flags);
+}
+
+void object_get(struct object *obj)
+{
+ unsigned long flags;
+
+ spin_lock_irqsave(&cache_lock, flags);
+ __object_get(obj);
+ spin_unlock_irqrestore(&cache_lock, flags);
+}
+
/* Must be holding cache_lock */
static struct object *__cache_find(int id)
{
@@ -35,6 +65,7 @@
{
BUG_ON(!obj);
list_del(&obj->list);
+ __object_put(obj);
cache_num--;
}
@@ -63,6 +94,7 @@
strscpy(obj->name, name, sizeof(obj->name));
obj->id = id;
obj->popularity = 0;
+ obj->refcnt = 1; /* The cache holds a reference */
spin_lock_irqsave(&cache_lock, flags);
__cache_add(obj);
@@ -79,18 +111,15 @@
spin_unlock_irqrestore(&cache_lock, flags);
}
-int cache_find(int id, char *name)
+struct object *cache_find(int id)
{
struct object *obj;
- int ret = -ENOENT;
unsigned long flags;
spin_lock_irqsave(&cache_lock, flags);
obj = __cache_find(id);
- if (obj) {
- ret = 0;
- strcpy(name, obj->name);
- }
+ if (obj)
+ __object_get(obj);
spin_unlock_irqrestore(&cache_lock, flags);
- return ret;
+ return obj;
}
We encapsulate the reference counting in the standard 'get' and 'put'
functions. Now we can return the object itself from
cache_find() which has the advantage that the user can
now sleep holding the object (eg. to copy_to_user() to
name to userspace).
The other point to note is that I said a reference should be held for
every pointer to the object: thus the reference count is 1 when first
inserted into the cache. In some versions the framework does not hold a
reference count, but they are more complicated.
Using Atomic Operations For The Reference Count
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In practice, :c:type:`atomic_t` would usually be used for refcnt. There are a
number of atomic operations defined in ``include/asm/atomic.h``: these
are guaranteed to be seen atomically from all CPUs in the system, so no
lock is required. In this case, it is simpler than using spinlocks,
although for anything non-trivial using spinlocks is clearer. The
atomic_inc() and atomic_dec_and_test()
are used instead of the standard increment and decrement operators, and
the lock is no longer used to protect the reference count itself.
::
--- cache.c.refcnt 2003-12-09 15:00:35.000000000 +1100
+++ cache.c.refcnt-atomic 2003-12-11 15:49:42.000000000 +1100
@@ -7,7 +7,7 @@
struct object
{
struct list_head list;
- unsigned int refcnt;
+ atomic_t refcnt;
int id;
char name[32];
int popularity;
@@ -18,33 +18,15 @@
static unsigned int cache_num = 0;
#define MAX_CACHE_SIZE 10
-static void __object_put(struct object *obj)
-{
- if (--obj->refcnt == 0)
- kfree(obj);
-}
-
-static void __object_get(struct object *obj)
-{
- obj->refcnt++;
-}
-
void object_put(struct object *obj)
{
- unsigned long flags;
-
- spin_lock_irqsave(&cache_lock, flags);
- __object_put(obj);
- spin_unlock_irqrestore(&cache_lock, flags);
+ if (atomic_dec_and_test(&obj->refcnt))
+ kfree(obj);
}
void object_get(struct object *obj)
{
- unsigned long flags;
-
- spin_lock_irqsave(&cache_lock, flags);
- __object_get(obj);
- spin_unlock_irqrestore(&cache_lock, flags);
+ atomic_inc(&obj->refcnt);
}
/* Must be holding cache_lock */
@@ -65,7 +47,7 @@
{
BUG_ON(!obj);
list_del(&obj->list);
- __object_put(obj);
+ object_put(obj);
cache_num--;
}
@@ -94,7 +76,7 @@
strscpy(obj->name, name, sizeof(obj->name));
obj->id = id;
obj->popularity = 0;
- obj->refcnt = 1; /* The cache holds a reference */
+ atomic_set(&obj->refcnt, 1); /* The cache holds a reference */
spin_lock_irqsave(&cache_lock, flags);
__cache_add(obj);
@@ -119,7 +101,7 @@
spin_lock_irqsave(&cache_lock, flags);
obj = __cache_find(id);
if (obj)
- __object_get(obj);
+ object_get(obj);
spin_unlock_irqrestore(&cache_lock, flags);
return obj;
}
Protecting The Objects Themselves
---------------------------------
In these examples, we assumed that the objects (except the reference
counts) never changed once they are created. If we wanted to allow the
name to change, there are three possibilities:
- You can make ``cache_lock`` non-static, and tell people to grab that
lock before changing the name in any object.
- You can provide a cache_obj_rename() which grabs this
lock and changes the name for the caller, and tell everyone to use
that function.
- You can make the ``cache_lock`` protect only the cache itself, and
use another lock to protect the name.
Theoretically, you can make the locks as fine-grained as one lock for
every field, for every object. In practice, the most common variants
are:
- One lock which protects the infrastructure (the ``cache`` list in
this example) and all the objects. This is what we have done so far.
- One lock which protects the infrastructure (including the list
pointers inside the objects), and one lock inside the object which
protects the rest of that object.
- Multiple locks to protect the infrastructure (eg. one lock per hash
chain), possibly with a separate per-object lock.
Here is the "lock-per-object" implementation:
::
--- cache.c.refcnt-atomic 2003-12-11 15:50:54.000000000 +1100
+++ cache.c.perobjectlock 2003-12-11 17:15:03.000000000 +1100
@@ -6,11 +6,17 @@
struct object
{
+ /* These two protected by cache_lock. */
struct list_head list;
+ int popularity;
+
atomic_t refcnt;
+
+ /* Doesn't change once created. */
int id;
+
+ spinlock_t lock; /* Protects the name */
char name[32];
- int popularity;
};
static DEFINE_SPINLOCK(cache_lock);
@@ -77,6 +84,7 @@
obj->id = id;
obj->popularity = 0;
atomic_set(&obj->refcnt, 1); /* The cache holds a reference */
+ spin_lock_init(&obj->lock);
spin_lock_irqsave(&cache_lock, flags);
__cache_add(obj);
Note that I decide that the popularity count should be protected by the
``cache_lock`` rather than the per-object lock: this is because it (like
the :c:type:`struct list_head <list_head>` inside the object)
is logically part of the infrastructure. This way, I don't need to grab
the lock of every object in __cache_add() when seeking
the least popular.
I also decided that the id member is unchangeable, so I don't need to
grab each object lock in __cache_find() to examine the
id: the object lock is only used by a caller who wants to read or write
the name field.
Note also that I added a comment describing what data was protected by
which locks. This is extremely important, as it describes the runtime
behavior of the code, and can be hard to gain from just reading. And as
Alan Cox says, “Lock data, not code”.
Common Problems
===============
Deadlock: Simple and Advanced
-----------------------------
There is a coding bug where a piece of code tries to grab a spinlock
twice: it will spin forever, waiting for the lock to be released
(spinlocks, rwlocks and mutexes are not recursive in Linux). This is
trivial to diagnose: not a
stay-up-five-nights-talk-to-fluffy-code-bunnies kind of problem.
For a slightly more complex case, imagine you have a region shared by a
softirq and user context. If you use a spin_lock() call
to protect it, it is possible that the user context will be interrupted
by the softirq while it holds the lock, and the softirq will then spin
forever trying to get the same lock.
Both of these are called deadlock, and as shown above, it can occur even
with a single CPU (although not on UP compiles, since spinlocks vanish
on kernel compiles with ``CONFIG_SMP``\ =n. You'll still get data
corruption in the second example).
This complete lockup is easy to diagnose: on SMP boxes the watchdog
timer or compiling with ``DEBUG_SPINLOCK`` set
(``include/linux/spinlock.h``) will show this up immediately when it
happens.
A more complex problem is the so-called 'deadly embrace', involving two
or more locks. Say you have a hash table: each entry in the table is a
spinlock, and a chain of hashed objects. Inside a softirq handler, you
sometimes want to alter an object from one place in the hash to another:
you grab the spinlock of the old hash chain and the spinlock of the new
hash chain, and delete the object from the old one, and insert it in the
new one.
There are two problems here. First, if your code ever tries to move the
object to the same chain, it will deadlock with itself as it tries to
lock it twice. Secondly, if the same softirq on another CPU is trying to
move another object in the reverse direction, the following could
happen:
+-----------------------+-----------------------+
| CPU 1 | CPU 2 |
+=======================+=======================+
| Grab lock A -> OK | Grab lock B -> OK |
+-----------------------+-----------------------+
| Grab lock B -> spin | Grab lock A -> spin |
+-----------------------+-----------------------+
Table: Consequences
The two CPUs will spin forever, waiting for the other to give up their
lock. It will look, smell, and feel like a crash.
Preventing Deadlock
-------------------
Textbooks will tell you that if you always lock in the same order, you
will never get this kind of deadlock. Practice will tell you that this
approach doesn't scale: when I create a new lock, I don't understand
enough of the kernel to figure out where in the 5000 lock hierarchy it
will fit.
The best locks are encapsulated: they never get exposed in headers, and
are never held around calls to non-trivial functions outside the same
file. You can read through this code and see that it will never
deadlock, because it never tries to grab another lock while it has that
one. People using your code don't even need to know you are using a
lock.
A classic problem here is when you provide callbacks or hooks: if you
call these with the lock held, you risk simple deadlock, or a deadly
embrace (who knows what the callback will do?).
Overzealous Prevention Of Deadlocks
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Deadlocks are problematic, but not as bad as data corruption. Code which
grabs a read lock, searches a list, fails to find what it wants, drops
the read lock, grabs a write lock and inserts the object has a race
condition.
Racing Timers: A Kernel Pastime
-------------------------------
Timers can produce their own special problems with races. Consider a
collection of objects (list, hash, etc) where each object has a timer
which is due to destroy it.
If you want to destroy the entire collection (say on module removal),
you might do the following::
/* THIS CODE BAD BAD BAD BAD: IF IT WAS ANY WORSE IT WOULD USE
HUNGARIAN NOTATION */
spin_lock_bh(&list_lock);
while (list) {
struct foo *next = list->next;
timer_delete(&list->timer);
kfree(list);
list = next;
}
spin_unlock_bh(&list_lock);
Sooner or later, this will crash on SMP, because a timer can have just
gone off before the spin_lock_bh(), and it will only get
the lock after we spin_unlock_bh(), and then try to free
the element (which has already been freed!).
This can be avoided by checking the result of
timer_delete(): if it returns 1, the timer has been deleted.
If 0, it means (in this case) that it is currently running, so we can
do::
retry:
spin_lock_bh(&list_lock);
while (list) {
struct foo *next = list->next;
if (!timer_delete(&list->timer)) {
/* Give timer a chance to delete this */
spin_unlock_bh(&list_lock);
goto retry;
}
kfree(list);
list = next;
}
spin_unlock_bh(&list_lock);
Another common problem is deleting timers which restart themselves (by
calling add_timer() at the end of their timer function).
Because this is a fairly common case which is prone to races, you should
use timer_delete_sync() (``include/linux/timer.h``) to handle this case.
Before freeing a timer, timer_shutdown() or timer_shutdown_sync() should be
called which will keep it from being rearmed. Any subsequent attempt to
rearm the timer will be silently ignored by the core code.
Locking Speed
=============
There are three main things to worry about when considering speed of
some code which does locking. First is concurrency: how many things are
going to be waiting while someone else is holding a lock. Second is the
time taken to actually acquire and release an uncontended lock. Third is
using fewer, or smarter locks. I'm assuming that the lock is used fairly
often: otherwise, you wouldn't be concerned about efficiency.
Concurrency depends on how long the lock is usually held: you should
hold the lock for as long as needed, but no longer. In the cache
example, we always create the object without the lock held, and then
grab the lock only when we are ready to insert it in the list.
Acquisition times depend on how much damage the lock operations do to
the pipeline (pipeline stalls) and how likely it is that this CPU was
the last one to grab the lock (ie. is the lock cache-hot for this CPU):
on a machine with more CPUs, this likelihood drops fast. Consider a
700MHz Intel Pentium III: an instruction takes about 0.7ns, an atomic
increment takes about 58ns, a lock which is cache-hot on this CPU takes
160ns, and a cacheline transfer from another CPU takes an additional 170
to 360ns. (These figures from Paul McKenney's `Linux Journal RCU
article <http://www.linuxjournal.com/article.php?sid=6993>`__).
These two aims conflict: holding a lock for a short time might be done
by splitting locks into parts (such as in our final per-object-lock
example), but this increases the number of lock acquisitions, and the
results are often slower than having a single lock. This is another
reason to advocate locking simplicity.
The third concern is addressed below: there are some methods to reduce
the amount of locking which needs to be done.
Read/Write Lock Variants
------------------------
Both spinlocks and mutexes have read/write variants: ``rwlock_t`` and
:c:type:`struct rw_semaphore <rw_semaphore>`. These divide
users into two classes: the readers and the writers. If you are only
reading the data, you can get a read lock, but to write to the data you
need the write lock. Many people can hold a read lock, but a writer must
be sole holder.
If your code divides neatly along reader/writer lines (as our cache code
does), and the lock is held by readers for significant lengths of time,
using these locks can help. They are slightly slower than the normal
locks though, so in practice ``rwlock_t`` is not usually worthwhile.
Avoiding Locks: Read Copy Update
--------------------------------
There is a special method of read/write locking called Read Copy Update.
Using RCU, the readers can avoid taking a lock altogether: as we expect
our cache to be read more often than updated (otherwise the cache is a
waste of time), it is a candidate for this optimization.
How do we get rid of read locks? Getting rid of read locks means that
writers may be changing the list underneath the readers. That is
actually quite simple: we can read a linked list while an element is
being added if the writer adds the element very carefully. For example,
adding ``new`` to a single linked list called ``list``::
new->next = list->next;
wmb();
list->next = new;
The wmb() is a write memory barrier. It ensures that the
first operation (setting the new element's ``next`` pointer) is complete
and will be seen by all CPUs, before the second operation is (putting
the new element into the list). This is important, since modern
compilers and modern CPUs can both reorder instructions unless told
otherwise: we want a reader to either not see the new element at all, or
see the new element with the ``next`` pointer correctly pointing at the
rest of the list.
Fortunately, there is a function to do this for standard
:c:type:`struct list_head <list_head>` lists:
list_add_rcu() (``include/linux/list.h``).
Removing an element from the list is even simpler: we replace the
pointer to the old element with a pointer to its successor, and readers
will either see it, or skip over it.
::
list->next = old->next;
There is list_del_rcu() (``include/linux/list.h``) which
does this (the normal version poisons the old object, which we don't
want).
The reader must also be careful: some CPUs can look through the ``next``
pointer to start reading the contents of the next element early, but
don't realize that the pre-fetched contents is wrong when the ``next``
pointer changes underneath them. Once again, there is a
list_for_each_entry_rcu() (``include/linux/list.h``)
to help you. Of course, writers can just use
list_for_each_entry(), since there cannot be two
simultaneous writers.
Our final dilemma is this: when can we actually destroy the removed
element? Remember, a reader might be stepping through this element in
the list right now: if we free this element and the ``next`` pointer
changes, the reader will jump off into garbage and crash. We need to
wait until we know that all the readers who were traversing the list
when we deleted the element are finished. We use
call_rcu() to register a callback which will actually
destroy the object once all pre-existing readers are finished.
Alternatively, synchronize_rcu() may be used to block
until all pre-existing are finished.
But how does Read Copy Update know when the readers are finished? The
method is this: firstly, the readers always traverse the list inside
rcu_read_lock()/rcu_read_unlock() pairs:
these simply disable preemption so the reader won't go to sleep while
reading the list.
RCU then waits until every other CPU has slept at least once: since
readers cannot sleep, we know that any readers which were traversing the
list during the deletion are finished, and the callback is triggered.
The real Read Copy Update code is a little more optimized than this, but
this is the fundamental idea.
::
--- cache.c.perobjectlock 2003-12-11 17:15:03.000000000 +1100
+++ cache.c.rcupdate 2003-12-11 17:55:14.000000000 +1100
@@ -1,15 +1,18 @@
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/string.h>
+#include <linux/rcupdate.h>
#include <linux/mutex.h>
#include <asm/errno.h>
struct object
{
- /* These two protected by cache_lock. */
+ /* This is protected by RCU */
struct list_head list;
int popularity;
+ struct rcu_head rcu;
+
atomic_t refcnt;
/* Doesn't change once created. */
@@ -40,7 +43,7 @@
{
struct object *i;
- list_for_each_entry(i, &cache, list) {
+ list_for_each_entry_rcu(i, &cache, list) {
if (i->id == id) {
i->popularity++;
return i;
@@ -49,19 +52,25 @@
return NULL;
}
+/* Final discard done once we know no readers are looking. */
+static void cache_delete_rcu(void *arg)
+{
+ object_put(arg);
+}
+
/* Must be holding cache_lock */
static void __cache_delete(struct object *obj)
{
BUG_ON(!obj);
- list_del(&obj->list);
- object_put(obj);
+ list_del_rcu(&obj->list);
cache_num--;
+ call_rcu(&obj->rcu, cache_delete_rcu);
}
/* Must be holding cache_lock */
static void __cache_add(struct object *obj)
{
- list_add(&obj->list, &cache);
+ list_add_rcu(&obj->list, &cache);
if (++cache_num > MAX_CACHE_SIZE) {
struct object *i, *outcast = NULL;
list_for_each_entry(i, &cache, list) {
@@ -104,12 +114,11 @@
struct object *cache_find(int id)
{
struct object *obj;
- unsigned long flags;
- spin_lock_irqsave(&cache_lock, flags);
+ rcu_read_lock();
obj = __cache_find(id);
if (obj)
object_get(obj);
- spin_unlock_irqrestore(&cache_lock, flags);
+ rcu_read_unlock();
return obj;
}
Note that the reader will alter the popularity member in
__cache_find(), and now it doesn't hold a lock. One
solution would be to make it an ``atomic_t``, but for this usage, we
don't really care about races: an approximate result is good enough, so
I didn't change it.
The result is that cache_find() requires no
synchronization with any other functions, so is almost as fast on SMP as
it would be on UP.
There is a further optimization possible here: remember our original
cache code, where there were no reference counts and the caller simply
held the lock whenever using the object? This is still possible: if you
hold the lock, no one can delete the object, so you don't need to get
and put the reference count.
Now, because the 'read lock' in RCU is simply disabling preemption, a
caller which always has preemption disabled between calling
cache_find() and object_put() does not
need to actually get and put the reference count: we could expose
__cache_find() by making it non-static, and such
callers could simply call that.
The benefit here is that the reference count is not written to: the
object is not altered in any way, which is much faster on SMP machines
due to caching.
Per-CPU Data
------------
Another technique for avoiding locking which is used fairly widely is to
duplicate information for each CPU. For example, if you wanted to keep a
count of a common condition, you could use a spin lock and a single
counter. Nice and simple.
If that was too slow (it's usually not, but if you've got a really big
machine to test on and can show that it is), you could instead use a
counter for each CPU, then none of them need an exclusive lock. See
DEFINE_PER_CPU(), get_cpu_var() and
put_cpu_var() (``include/linux/percpu.h``).
Of particular use for simple per-cpu counters is the ``local_t`` type,
and the cpu_local_inc() and related functions, which are
more efficient than simple code on some architectures
(``include/asm/local.h``).
Note that there is no simple, reliable way of getting an exact value of
such a counter, without introducing more locks. This is not a problem
for some uses.
Data Which Mostly Used By An IRQ Handler
----------------------------------------
If data is always accessed from within the same IRQ handler, you don't
need a lock at all: the kernel already guarantees that the irq handler
will not run simultaneously on multiple CPUs.
Manfred Spraul points out that you can still do this, even if the data
is very occasionally accessed in user context or softirqs/tasklets. The
irq handler doesn't use a lock, and all other accesses are done as so::
mutex_lock(&lock);
disable_irq(irq);
...
enable_irq(irq);
mutex_unlock(&lock);
The disable_irq() prevents the irq handler from running
(and waits for it to finish if it's currently running on other CPUs).
The spinlock prevents any other accesses happening at the same time.
Naturally, this is slower than just a spin_lock_irq()
call, so it only makes sense if this type of access happens extremely
rarely.
What Functions Are Safe To Call From Interrupts?
================================================
Many functions in the kernel sleep (ie. call schedule()) directly or
indirectly: you can never call them while holding a spinlock, or with
preemption disabled. This also means you need to be in user context:
calling them from an interrupt is illegal.
Some Functions Which Sleep
--------------------------
The most common ones are listed below, but you usually have to read the
code to find out if other calls are safe. If everyone else who calls it
can sleep, you probably need to be able to sleep, too. In particular,
registration and deregistration functions usually expect to be called
from user context, and can sleep.
- Accesses to userspace:
- copy_from_user()
- copy_to_user()
- get_user()
- put_user()
- kmalloc(GP_KERNEL) <kmalloc>`
- mutex_lock_interruptible() and
mutex_lock()
There is a mutex_trylock() which does not sleep.
Still, it must not be used inside interrupt context since its
implementation is not safe for that. mutex_unlock()
will also never sleep. It cannot be used in interrupt context either
since a mutex must be released by the same task that acquired it.
Some Functions Which Don't Sleep
--------------------------------
Some functions are safe to call from any context, or holding almost any
lock.
- printk()
- kfree()
- add_timer() and timer_delete()
Mutex API reference
===================
.. kernel-doc:: include/linux/mutex.h
:internal:
.. kernel-doc:: kernel/locking/mutex.c
:export:
Futex API reference
===================
.. kernel-doc:: kernel/futex/core.c
:internal:
.. kernel-doc:: kernel/futex/futex.h
:internal:
.. kernel-doc:: kernel/futex/pi.c
:internal:
.. kernel-doc:: kernel/futex/requeue.c
:internal:
.. kernel-doc:: kernel/futex/waitwake.c
:internal:
Further reading
===============
- ``Documentation/locking/spinlocks.rst``: Linus Torvalds' spinlocking
tutorial in the kernel sources.
- Unix Systems for Modern Architectures: Symmetric Multiprocessing and
Caching for Kernel Programmers:
Curt Schimmel's very good introduction to kernel level locking (not
written for Linux, but nearly everything applies). The book is
expensive, but really worth every penny to understand SMP locking.
[ISBN: 0201633388]
Thanks
======
Thanks to Telsa Gwynne for DocBooking, neatening and adding style.
Thanks to Martin Pool, Philipp Rumpf, Stephen Rothwell, Paul Mackerras,
Ruedi Aschwanden, Alan Cox, Manfred Spraul, Tim Waugh, Pete Zaitcev,
James Morris, Robert Love, Paul McKenney, John Ashby for proofreading,
correcting, flaming, commenting.
Thanks to the cabal for having no influence on this document.
Glossary
========
preemption
Prior to 2.5, or when ``CONFIG_PREEMPT`` is unset, processes in user
context inside the kernel would not preempt each other (ie. you had that
CPU until you gave it up, except for interrupts). With the addition of
``CONFIG_PREEMPT`` in 2.5.4, this changed: when in user context, higher
priority tasks can "cut in": spinlocks were changed to disable
preemption, even on UP.
bh
Bottom Half: for historical reasons, functions with '_bh' in them often
now refer to any software interrupt, e.g. spin_lock_bh()
blocks any software interrupt on the current CPU. Bottom halves are
deprecated, and will eventually be replaced by tasklets. Only one bottom
half will be running at any time.
Hardware Interrupt / Hardware IRQ
Hardware interrupt request. in_hardirq() returns true in a
hardware interrupt handler.
Interrupt Context
Not user context: processing a hardware irq or software irq. Indicated
by the in_interrupt() macro returning true.
SMP
Symmetric Multi-Processor: kernels compiled for multiple-CPU machines.
(``CONFIG_SMP=y``).
Software Interrupt / softirq
Software interrupt handler. in_hardirq() returns false;
in_softirq() returns true. Tasklets and softirqs both
fall into the category of 'software interrupts'.
Strictly speaking a softirq is one of up to 32 enumerated software
interrupts which can run on multiple CPUs at once. Sometimes used to
refer to tasklets as well (ie. all software interrupts).
tasklet
A dynamically-registrable software interrupt, which is guaranteed to
only run on one CPU at a time.
timer
A dynamically-registrable software interrupt, which is run at (or close
to) a given time. When running, it is just like a tasklet (in fact, they
are called from the ``TIMER_SOFTIRQ``).
UP
Uni-Processor: Non-SMP. (``CONFIG_SMP=n``).
User Context
The kernel executing on behalf of a particular process (ie. a system
call or trap) or kernel thread. You can tell which process with the
``current`` macro.) Not to be confused with userspace. Can be
interrupted by software or hardware interrupts.
Userspace
A process executing its own code outside the kernel.
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
동시 실행과 race condition
1-93이 문서는 Linux 커널 locking의 기초를 설명한다. HyperThreading, SMP와 kernel preemption이 일반화되면서 커널 코드를 수정하는 모든 개발자는 동시 실행과 lock의 기본 원리를 이해해야 한다.
very_important_count++;
C의 증가 연산은 하나의 source statement지만 실제로는 값을 읽고, 1을 더하고, 결과를 쓰는 여러 단계다. 두 실행 주체가 순서대로 수행하면 5를 읽은 첫 실행이 6을 쓰고, 두 번째 실행이 6을 읽어 7을 쓴다.
그러나 두 실행이 모두 5를 읽은 뒤 각각 6을 계산해 쓰면 증가 한 번이 사라져 최종 값은 6이 된다. 여러 task의 상대적인 실행 시점에 따라 결과가 달라지는 현상이 race condition이고, 동시에 실행되면 안 되는 코드와 자료의 범위가 critical region이다.
CPU가 하나여도 preemption이 critical region 중간에 현재 task를 멈추고 같은 코드를 실행하는 다른 task로 바꾸면 동일한 race가 발생한다. 동시 접근이 가능한 경로를 식별하고 lock으로 한 번에 하나의 실행만 critical region에 들어가게 해야 한다.
두 CPU가 같은 초기 값을 읽으면 두 번의 증가가 한 번으로 관측된다.
spinlock, mutex와 UP 커널
94-140locking에서 가장 중요한 원칙은 단순하게 유지하는 것이다. 새 lock을 추가하기 전에 정말 필요한지 확인한다.
spinlock은 한 실행 주체만 보유할 수 있는 기본 lock이다. 획득하지 못하면 해제될 때까지 CPU에서 반복 확인한다. 작고 빠르며 sleep할 수 없는 문맥에서도 사용할 수 있다.
mutex는 획득하지 못한 task를 재우고 lock이 풀릴 때 깨운다. 기다리는 동안 CPU가 다른 일을 할 수 있지만 mutex를 보유한 상태에서 block할 수 있다는 전제는 process context에서만 성립한다. interrupt처럼 sleep할 수 없는 문맥에서는 spinlock을 써야 한다. 두 lock 모두 recursive하지 않으므로 같은 실행 주체가 두 번 획득하면 deadlock이다.
| 빌드 설정 | spinlock의 실질 동작 | mutex |
|---|---|---|
| CONFIG_SMP=n, CONFIG_PREEMPT=n | 동시 실행이 없어 제거됨 | user context 동기화를 위해 존재 |
| CONFIG_SMP=n, CONFIG_PREEMPT=y | preemption disable/enable로 변환 | 존재 |
| CONFIG_SMP=y | CPU 사이 배타 lock | 존재 |
실제 test 장비가 단일 CPU여도 CONFIG_SMP와 CONFIG_PREEMPT를 켠 빌드로 locking 코드를 시험해야 한다. 이 설정이 일부 lock misuse와 preemption 문제를 드러낸다.
user context, softirq, tasklet과 timer
141-241자료 구조가 user context에서만 접근되고 모든 호출자가 sleep할 수 있다면 mutex가 가장 단순하다. mutex_lock_interruptible()은 signal을 받으면 반환할 수 있어 권장되며, mutex_lock()은 signal이 와도 반환하지 않는다. net/netfilter/nf_sockopt.c의 nf_sockopt_mutex는 module load/unload 때 등록 목록을 바꾸고 setsockopt/getsockopt 경로에서 조회하는 자료를 보호하는 예다.
user context와 softirq가 자료를 공유하면 현재 task가 같은 CPU의 softirq에 interrupt될 수 있고, 다른 CPU의 softirq가 동시에 critical region에 들어올 수도 있다. user 쪽은 spin_lock_bh()로 현재 CPU의 softirq를 막은 뒤 lock을 잡고 spin_unlock_bh()로 역순 복구한다. bh는 예전 Bottom Half라는 이름의 흔적이다.
더 강한 spin_lock_irq() 또는 spin_lock_irqsave()를 써 hardware interrupt까지 막아도 된다. UP non-SMP 빌드에서는 실제 spinlock이 사라지고 local_bh_disable()이 남아 같은 CPU의 softirq 재진입을 막는다.
tasklet과 timer는 softirq에서 실행되므로 user context와의 locking 규칙은 softirq와 같다. 같은 tasklet은 동시에 두 CPU에서 실행되지 않으므로 자기 자신에 대한 reentrancy lock은 필요 없다. 다른 tasklet이나 timer와 자료를 공유하면 서로 다른 CPU에서 실행될 수 있으므로 양쪽에서 spin_lock()/spin_unlock()을 사용한다. 이미 tasklet 문맥에서는 같은 CPU의 tasklet이 겹쳐 실행되지 않아 _bh 변형이 필요 없다.
같은 softirq는 여러 CPU에서 동시에 실행될 수 있다. 성능이 중요하면 per-CPU data를 고려하고, 단일 공유 자료라면 spinlock을 사용한다. 다른 softirq, tasklet, timer 사이의 공유도 모두 다른 CPU 동시 실행 가능성이 있으므로 spin_lock이 필요하다.
hard IRQ 문맥의 locking
242-290hardware IRQ handler는 보통 작업을 queue에 넣고 softirq나 tasklet이 꺼내 처리한다. IRQ handler와 softirq가 자료를 공유하면 softirq 실행 중 같은 CPU의 hardware interrupt가 끼어들 수 있고, 다른 CPU의 IRQ handler도 동시에 접근할 수 있다.
softirq 쪽에서는 spin_lock_irq()로 현재 CPU interrupt를 끈 뒤 lock을 잡는다. IRQ handler 안에서는 softirq가 현재 IRQ를 선점하지 못하므로 보통 spin_lock()이면 충분하다. 단, 같은 lock을 쓰는 다른 hardware IRQ가 이 handler를 interrupt할 수 있다면 IRQ 쪽도 interrupt disable이 필요하다.
UP 빌드에서 spin_lock_irq()는 local_irq_disable()에 해당하는 효과를 남겨 softirq/tasklet/BH 실행을 막는다. spin_lock_irqsave()는 진입 전 interrupt enable 상태를 flags에 저장하고 spin_unlock_irqrestore()가 정확히 복원한다. 따라서 interrupt가 이미 꺼진 hardirq와 interrupt를 꺼야 하는 softirq에서 같은 코드를 사용할 수 있다.
softirq, tasklet과 timer는 hardware interrupt 복귀 경로에서 실행되므로 interrupt를 막는 lock은 이들도 함께 막는다. 두 hardware IRQ handler 사이에서 자료를 공유한다면 아키텍처마다 handler 진입 시 전체 interrupt disable 여부가 다르므로 spin_lock_irqsave()를 사용한다.
문맥별 최소 locking 요구
291-350- system call 같은 process context끼리만 배제하고 sleep 가능한 함수도 호출해야 하면 mutex를 사용한다.
- interrupt가 자료를 만질 수 있다면 가장 일반적인 spin_lock_irqsave()/spin_unlock_irqrestore()를 사용한다.
- spinlock 보유 구간은 가능하면 5줄 이내로 유지하고 readb() 같은 단순 accessor를 제외한 함수 호출을 가로질러 보유하지 않는다.
| 공유하는 문맥 | 최소 primitive | 이유 |
|---|---|---|
| IRQ handler A ↔ IRQ handler B | SLIS: spin_lock_irqsave | handler의 interrupt 상태가 아키텍처별로 다름 |
| IRQ handler ↔ softirq/tasklet/timer | SLI: spin_lock_irq | local hard IRQ 재진입 차단 |
| softirq/tasklet/timer 상호 간 | SL: spin_lock | 다른 CPU 동시 실행 배제 |
| user context ↔ softirq/tasklet/timer | SLBH: spin_lock_bh | local softirq와 다른 CPU 접근 배제 |
| user context A ↔ user context B | MLI: mutex_lock_interruptible | sleep 가능한 task 동기화 |
| 동일한 특정 tasklet 또는 timer | None | 동일 instance는 한 CPU에서만 실행 |
표는 최소 요구사항이다. spin_lock_irqsave()는 다른 spinlock 변형의 보호 범위를 포함하므로 문맥이 복잡할 때 사용할 수 있지만, 불필요하게 interrupt를 오래 막지 않도록 critical section을 줄여야 한다.
trylock 함수
351-370trylock은 lock을 한 번만 시도하고 즉시 성공 여부를 반환한다. 다른 thread가 lock을 보유한 동안 보호 자료가 꼭 필요하지 않은 경로에 사용할 수 있으며, 나중에 자료가 필요해지면 정식으로 lock을 획득해야 한다.
spin_trylock()은 spin하지 않고 첫 시도에 성공하면 0이 아닌 값, 실패하면 0을 반환한다. spin_lock과 같은 문맥에서 사용할 수 있지만 자신을 interrupt해 같은 lock을 잡을 수 있는 문맥은 호출 전에 이미 disable해야 한다.
mutex_trylock()은 task를 재우지 않고 첫 시도 결과를 반환한다. 그러나 구현 자체가 hardware 또는 software interrupt context에 안전한 것은 아니므로, sleep하지 않는다는 이유만으로 interrupt에서 사용할 수 없다.
예제 1: user context 전용 cache
371-490예제는 숫자 id와 이름을 연결하는 cache다. object마다 사용 횟수 popularity를 세고, MAX_CACHE_SIZE를 넘으면 가장 적게 사용한 object를 제거한다. 모든 operation이 system call의 user context에서 실행되므로 cache list, cache_num과 object 내용을 하나의 mutex로 보호한다.
struct object {
struct list_head list;
int id;
char name[32];
int popularity;
};
/* cache, cache_num과 그 안의 object를 보호 */
static DEFINE_MUTEX(cache_lock);
static LIST_HEAD(cache);
static unsigned int cache_num;
#define MAX_CACHE_SIZE 10
/* cache_lock을 보유해야 함 */
static struct object *__cache_find(int id)
{
struct object *i;
list_for_each_entry(i, &cache, list)
if (i->id == id) {
i->popularity++;
return i;
}
return NULL;
}
/* cache_lock을 보유해야 함 */
static void __cache_delete(struct object *obj)
{
BUG_ON(!obj);
list_del(&obj->list);
kfree(obj);
cache_num--;
}
__cache_add()는 list에 object를 넣고 개수가 제한을 넘으면 popularity가 가장 낮은 object를 찾아 __cache_delete()한다. 이름 앞의 __와 주석은 외부 lock을 이미 보유해야 하는 내부 helper라는 계약을 나타낸다.
int cache_add(int id, const char *name)
{
struct object *obj;
obj = kmalloc(sizeof(*obj), GFP_KERNEL);
if (!obj)
return -ENOMEM;
strscpy(obj->name, name, sizeof(obj->name));
obj->id = id;
obj->popularity = 0;
mutex_lock(&cache_lock);
__cache_add(obj);
mutex_unlock(&cache_lock);
return 0;
}
int cache_find(int id, char *name)
{
struct object *obj;
int ret = -ENOENT;
mutex_lock(&cache_lock);
obj = __cache_find(id);
if (obj) {
ret = 0;
strcpy(name, obj->name);
}
mutex_unlock(&cache_lock);
return ret;
}
cache 추가, 삭제와 조회 때 항상 cache_lock을 보유하므로 list 구조와 object 내용이 함께 보호된다. 호출자에게 object pointer를 노출하지 않고 이름을 복사해 주기 때문에 lock 밖 object lifetime 문제가 없다. cache_add()가 lock 전에 새 object field를 초기화하는 것은 list에 넣기 전에는 다른 실행 주체가 그 object를 찾을 수 없기 때문에 안전하며, lock 보유 시간을 줄이는 일반적인 최적화다.
예제 2: interrupt에서 cache 접근
491-573cache_find()나 삭제 경로가 hardware IRQ 또는 softirq에서도 호출될 수 있다면 mutex를 사용할 수 없다. cache_lock을 spinlock으로 바꾸고 모든 public operation이 spin_lock_irqsave()로 interrupt 상태를 저장한 뒤 lock을 잡게 한다.
-static DEFINE_MUTEX(cache_lock);
+static DEFINE_SPINLOCK(cache_lock);
int cache_add(int id, const char *name)
{
struct object *obj;
+ unsigned long flags;
...
- mutex_lock(&cache_lock);
+ spin_lock_irqsave(&cache_lock, flags);
__cache_add(obj);
- mutex_unlock(&cache_lock);
+ spin_unlock_irqrestore(&cache_lock, flags);
}
void cache_delete(int id)
{
+ unsigned long flags;
+ spin_lock_irqsave(&cache_lock, flags);
__cache_delete(__cache_find(id));
+ spin_unlock_irqrestore(&cache_lock, flags);
}
spin_lock_irqsave()는 interrupt가 켜져 있으면 끄고, 이미 IRQ handler라 꺼져 있으면 그 상태를 그대로 저장한다. 따라서 같은 함수가 여러 문맥에서 호출되어도 복귀 때 원래 상태를 복원한다.
cache_add()의 kmalloc(..., GFP_KERNEL)은 sleep할 수 있으므로 여전히 user context에서만 호출할 수 있다. interrupt에서도 추가가 필요하다면 allocation flag 또는 사전 할당 방식을 호출 문맥에 맞게 설계해야 한다. lock을 spinlock으로 바꿨다고 함수 안의 모든 operation이 interrupt-safe가 되는 것은 아니다.
예제 3: 외부 pointer와 reference count
574-698다른 파일이 cache object pointer를 보관하게 되면 두 문제가 생긴다. object 내용을 보호하는 cache_lock을 외부에 공개하면 locking 규칙이 여러 파일로 흩어진다. 더 심각하게는 lock을 놓은 뒤 cache_delete()가 object를 해제하고 같은 주소에 새 object가 할당될 수 있어 pointer lifetime이 보장되지 않는다.
pointer를 가진 각 사용자가 reference를 하나 얻고 사용을 마치면 put한다. 마지막 reference를 0으로 만든 실행 주체만 실제 memory를 해제한다. cache 자체도 list에 object를 보관하는 동안 reference 하나를 소유한다.
static void __object_put(struct object *obj)
{
if (--obj->refcnt == 0)
kfree(obj);
}
static void __object_get(struct object *obj)
{
obj->refcnt++;
}
void object_put(struct object *obj)
{
unsigned long flags;
spin_lock_irqsave(&cache_lock, flags);
__object_put(obj);
spin_unlock_irqrestore(&cache_lock, flags);
}
object 생성 때 refcnt=1로 cache 소유권을 기록하고, list에서 제거할 때 cache reference를 put한다. cache_find()는 cache_lock 아래에서 object를 찾고 reference를 증가시킨 뒤 pointer를 반환한다. 호출자는 object_put() 전까지 lock 없이 object lifetime을 유지할 수 있고, 그 사이 copy_to_user()처럼 sleep 가능한 operation도 수행할 수 있다.
struct object *cache_find(int id)
{
struct object *obj;
unsigned long flags;
spin_lock_irqsave(&cache_lock, flags);
obj = __cache_find(id);
if (obj)
__object_get(obj);
spin_unlock_irqrestore(&cache_lock, flags);
return obj;
}
예제 4: atomic reference operation
699-788실제 reference count에는 보통 atomic_t를 사용한다. atomic operation은 모든 CPU에서 하나의 분할 불가능한 갱신으로 관측되므로 단순 증가·감소를 위해 cache_lock을 잡을 필요가 없다. 복잡한 상태 변경까지 atomic 연산으로 억지로 표현하기보다 spinlock으로 불변식을 명시하는 편이 낫다.
struct object {
struct list_head list;
atomic_t refcnt;
int id;
char name[32];
int popularity;
};
void object_put(struct object *obj)
{
if (atomic_dec_and_test(&obj->refcnt))
kfree(obj);
}
void object_get(struct object *obj)
{
atomic_inc(&obj->refcnt);
}
/* cache가 첫 reference를 소유 */
atomic_set(&obj->refcnt, 1);
list에서 삭제할 때 object_put(), lookup 성공 때 object_get()을 호출한다. reference count 자체는 lock 없이 갱신되지만, 0에서 다시 reference를 얻는 일을 막으려면 object를 찾고 최초 reference를 획득하는 동안 cache_lock 또는 다른 lifetime protocol이 여전히 필요하다.
예제 5: infrastructure lock과 object lock
789-870object의 name도 변경 가능하게 만들려면 세 방식이 있다. cache_lock을 외부에 공개해 변경자가 잡게 하거나, cache_obj_rename() 같은 API가 내부에서 lock을 잡게 하거나, cache 구조와 object field를 서로 다른 lock으로 보호할 수 있다.
field마다 lock을 하나씩 둘 수도 있지만 일반적인 설계는 하나의 lock으로 infrastructure와 모든 object를 보호하거나, list pointer 같은 infrastructure field는 전역 lock으로 보호하고 각 object의 나머지 field는 object 내부 lock으로 보호하거나, hash chain별 infrastructure lock과 선택적인 per-object lock을 두는 형태다.
struct object {
/* cache_lock이 보호 */
struct list_head list;
int popularity;
atomic_t refcnt;
/* 생성 뒤 변경되지 않음 */
int id;
spinlock_t lock; /* name 보호 */
char name[32];
};
popularity는 list와 함께 eviction 정책을 구성하므로 cache_lock이 보호한다. 그러면 가장 낮은 popularity를 찾을 때 모든 object lock을 차례로 잡을 필요가 없다. id는 생성 뒤 불변이므로 __cache_find()에서 object lock 없이 읽을 수 있다. name을 읽거나 바꾸는 호출자만 object lock을 사용한다.
어떤 lock이 어떤 data를 보호하는지 구조체 가까이에 주석으로 기록한다. runtime locking 규칙은 코드만 읽어 추론하기 어렵다. 핵심은 code block이 아니라 data invariant를 잠그는 것이다.
deadlock과 lock ordering
871-953Linux의 spinlock, rwlock과 mutex는 recursive하지 않다. 같은 실행 주체가 같은 lock을 두 번 잡으면 두 번째 획득이 영원히 기다린다. user context가 spin_lock을 보유한 채 같은 lock을 잡는 softirq에 interrupt되어도 단일 CPU에서 deadlock이 발생한다. UP non-SMP 빌드에서는 spinlock이 제거되어 lockup 대신 data corruption으로 나타날 수 있다.
SMP에서는 watchdog 또는 DEBUG_SPINLOCK 빌드가 이런 완전 정지를 빠르게 드러낼 수 있다. 두 개 이상의 lock이 관련된 ABBA deadlock은 더 복잡하다. hash chain A에서 B로 object를 옮기는 CPU 0이 A를 잡고 B를 기다리는 동안, CPU 1이 반대 이동을 위해 B를 잡고 A를 기다리면 둘 다 진행하지 못한다. 같은 chain으로 이동하면서 같은 lock을 두 번 잡는 경우도 먼저 막아야 한다.
두 CPU가 서로 반대 순서로 lock을 획득하면 상대가 놓아야 할 lock을 영원히 기다린다.
모든 lock에 전역 순서를 부여하면 이론적으로 ABBA를 막을 수 있지만 거대한 kernel lock hierarchy에서 새 lock의 위치를 판단하기 어렵다. 가장 좋은 lock은 한 파일 안에 캡슐화되어 header로 노출되지 않고, 보유한 채 같은 파일 밖의 복잡한 함수를 호출하지 않는 lock이다.
callback과 hook을 lock 보유 상태에서 호출하면 callback이 어떤 lock을 잡을지 알 수 없어 simple recursion과 ABBA 위험이 생긴다. 반대로 deadlock을 피하겠다고 read lock으로 list를 검색한 뒤 lock을 놓고 write lock을 다시 잡아 삽입하면, 그 사이 다른 실행이 같은 object를 삽입하는 race가 생긴다. deadlock 회피가 data integrity보다 우선해서는 안 된다.
timer 삭제 race
954-1013각 object가 자신을 삭제하는 timer를 가진 collection을 module unload 때 모두 해제한다고 가정한다. list_lock을 잡고 timer_delete()한 뒤 즉시 kfree()하는 코드는 SMP에서 안전하지 않다. lock을 잡기 직전에 timer callback이 시작되어 lock을 기다리고 있었다면, collection 경로가 object를 해제한 뒤 callback이 lock을 얻어 같은 object를 다시 해제한다.
/* 안전하지 않은 형태 */
spin_lock_bh(&list_lock);
while (list) {
struct foo *next = list->next;
timer_delete(&list->timer);
kfree(list);
list = next;
}
spin_unlock_bh(&list_lock);
timer_delete()가 1이면 pending timer를 삭제한 것이고, 0이면 이 상황에서는 callback이 이미 실행 중일 수 있다. 원문 예제는 0일 때 lock을 놓고 retry해 callback이 삭제를 마칠 기회를 준다.
retry:
spin_lock_bh(&list_lock);
while (list) {
struct foo *next = list->next;
if (!timer_delete(&list->timer)) {
spin_unlock_bh(&list_lock);
goto retry;
}
kfree(list);
list = next;
}
spin_unlock_bh(&list_lock);
callback 끝에서 add_timer()로 자신을 다시 arm하는 timer는 흔하고 race가 많으므로 timer_delete_sync()를 사용한다. timer가 든 memory를 해제하기 전에는 timer_shutdown() 또는 timer_shutdown_sync()를 호출해 재무장을 영구 차단한다. shutdown 뒤의 재arm 요청은 timer core가 조용히 무시한다.
locking 비용과 read/write lock
1015-1063locking 성능에는 lock 보유자를 기다리는 동시 실행 수, 경쟁 없는 lock 획득·해제 자체의 비용, lock 개수와 배치가 영향을 준다. lock은 필요한 만큼만 보유한다. cache 예제처럼 새 object는 lock 밖에서 초기화하고 list에 publish할 순간에만 lock을 잡는다.
lock operation은 pipeline stall과 cache line 이동을 일으킨다. 원문이 인용한 700MHz Pentium III 수치는 일반 instruction 약 0.7ns, atomic increment 약 58ns, 같은 CPU cache에 뜨거운 lock 약 160ns, 다른 CPU에서 cache line을 가져오는 추가 비용 170~360ns다. 절대 수치는 오래되었지만 shared cache line ownership 이동이 비싸다는 원리는 남는다.
lock을 잘게 나누면 각 critical section은 짧아지지만 획득 횟수와 ordering 복잡도가 늘어 단일 lock보다 느릴 수 있다. 측정 없이 fine-grained locking을 추가하지 말아야 하는 이유다.
spinlock과 mutex에는 각각 rwlock_t와 struct rw_semaphore라는 read/write 변형이 있다. 여러 reader는 동시에 read lock을 가질 수 있지만 writer는 단독으로 write lock을 가져야 한다. reader와 writer가 명확히 분리되고 reader가 lock을 오래 보유할 때 도움이 될 수 있으나 기본 lock보다 operation이 느려 rwlock_t는 실제로 이득이 없는 경우가 많다.
RCU로 read-side lock 제거
1064-1245Read-Copy Update는 read가 update보다 훨씬 많은 자료 구조에서 reader의 lock 획득을 없애는 방식이다. writer가 새 node의 next를 먼저 완성하고 memory barrier 뒤 list에 publish하면 reader는 새 node를 전혀 보지 않거나, 완전히 초기화된 node와 올바른 next를 본다.
new->next = list->next;
wmb();
list->next = new;
compiler와 CPU는 명시적 제약이 없으면 store 순서를 바꿀 수 있다. wmb()는 next 초기화가 모든 CPU에 보인 뒤 publish pointer가 갱신되게 한다. struct list_head에는 이 protocol을 구현한 list_add_rcu()가 있다.
삭제는 predecessor의 next를 old->next로 바꾸어 reader가 old를 보거나 건너뛰게 한다. list_del_rcu()는 일반 list_del처럼 old link를 poison하지 않아 이미 old를 읽은 reader가 traversal을 계속할 수 있다. reader는 speculative prefetch와 pointer 변경을 안전하게 처리하는 list_for_each_entry_rcu()를 사용한다. writer는 동시에 하나만 실행되도록 별도 lock을 보유하므로 일반 list_for_each_entry()를 사용할 수 있다.
list에서 분리한 object를 즉시 free할 수는 없다. 삭제 전에 old를 읽은 reader가 아직 next를 따라가고 있을 수 있다. call_rcu()에 callback을 등록해 모든 기존 reader가 끝난 grace period 뒤 object를 해제하거나, synchronize_rcu()로 그 시점까지 동기적으로 기다린다.
reader는 rcu_read_lock()/rcu_read_unlock() 사이에서 traversal한다. 이 기본 설명에서는 read section이 preemption을 막아 sleep하지 못하게 하고, RCU는 모든 CPU가 quiescent state를 통과할 때 삭제 당시 reader가 끝났다고 판단한다. 실제 RCU 구현은 더 정교하지만 핵심은 publish ordering과 delayed reclamation이다.
rcu_read_lock();
obj = __cache_find(id); /* list_for_each_entry_rcu() */
if (obj)
object_get(obj);
rcu_read_unlock();
/* writer: cache_lock 보유 */
list_del_rcu(&obj->list);
call_rcu(&obj->rcu, cache_delete_rcu);
이 예제에서 popularity는 reader가 lock 없이 증가시켜 정확한 값에 race가 남는다. eviction에 근사치면 충분하다는 명시적 설계 선택이며, 정확성이 필요하면 atomic_t나 다른 동기화가 필요하다. RCU 적용 뒤 cache_find()는 다른 함수와 read-side lock 경쟁을 하지 않아 SMP에서도 UP에 가까운 lookup 비용을 낸다.
RCU read-side critical section 전체에서 object가 제거되어도 memory는 살아 있으므로, preemption이 계속 disable된 호출자는 별도 reference get/put 없이 pointer를 사용할 수 있다. reference count cache line을 쓰지 않는다는 점은 SMP에서 큰 이점이다. 그러나 pointer를 RCU read section 밖으로 가져가면 반드시 reference나 다른 lifetime 보장이 필요하다.
list에서 node를 즉시 분리해 새 reader에게 숨기되, 기존 reader가 끝날 때까지 memory 해제를 미룬다.
per-CPU data와 IRQ 중심 자료
1246-1291lock을 피하는 또 다른 방법은 CPU마다 자료를 복제하는 것이다. 자주 증가하는 하나의 counter에 spinlock을 두는 방식이 실제로 병목임을 큰 SMP 장비에서 측정했다면 per-CPU counter로 바꿀 수 있다. DEFINE_PER_CPU(), get_cpu_var(), put_cpu_var()와 단순 counter용 local_t 계열을 사용한다.
per-CPU 값은 갱신 경쟁을 없애지만 모든 CPU의 값을 동시에 정확히 읽으려면 다시 동기화가 필요하다. 통계처럼 근사 snapshot으로 충분한 용도에 적합하다.
자료를 항상 같은 IRQ handler만 접근하면 커널이 같은 handler를 여러 CPU에서 동시에 실행하지 않게 보장하므로 lock이 필요 없다. user context나 softirq가 매우 드물게 접근한다면 IRQ handler는 lock 없이 두고, 다른 경로가 mutex를 잡은 뒤 disable_irq(irq)로 handler 시작을 막고 현재 다른 CPU에서 실행 중인 handler가 끝날 때까지 기다릴 수 있다.
mutex_lock(&lock);
disable_irq(irq);
...
enable_irq(irq);
mutex_unlock(&lock);
이 방식은 일반 spin_lock_irq()보다 느리므로 IRQ 이외 접근이 극히 드물 때만 의미가 있다. 원문 일부에는 spinlock이라고 적혀 있지만 예제는 mutex를 사용하며, 핵심은 다른 비-IRQ 접근끼리의 배제와 disable_irq의 handler 동기화다.
interrupt에서 호출 가능한 함수
1293-1342kernel 함수 가운데 많은 수가 직접 또는 간접으로 schedule()을 호출한다. spinlock을 보유했거나 preemption을 disable한 상태에서는 절대 sleep 함수로 들어가면 안 되며, interrupt context에서도 호출할 수 없다.
다른 호출자들이 모두 sleep 가능한 문맥에서 쓰는 함수라면 새 호출자도 sleep 가능해야 할 가능성이 높다. 특히 등록과 해제 함수는 보통 user context를 전제로 하고 내부에서 memory allocation과 subsystem 동기화를 수행한다.
| 분류 | 함수 | 제약 |
|---|---|---|
| sleep 가능 | copy_from_user, copy_to_user, get_user, put_user | user memory fault로 sleep 가능 |
| sleep 가능 | kmalloc(..., GFP_KERNEL) | reclaim 등으로 sleep 가능 |
| sleep 가능 | mutex_lock_interruptible, mutex_lock | task를 wait queue에 재움 |
| interrupt 사용 금지 | mutex_trylock, mutex_unlock | trylock이 sleep하지 않아도 mutex owner/task semantics가 interrupt-safe하지 않음 |
| 어느 문맥에서도 대체로 안전 | printk, kfree | 문서가 열거한 비-sleep 예 |
| 어느 문맥에서도 대체로 안전 | add_timer, timer_delete | 문서가 열거한 비-sleep 예 |
API 문서와 추가 읽을거리
1343-1394mutex 내부 API는 include/linux/mutex.h와 kernel/locking/mutex.c의 kernel-doc에서 생성된다. futex 내부 API는 kernel/futex/core.c, futex.h, pi.c, requeue.c, waitwake.c의 kernel-doc을 함께 읽어야 한다.
.. kernel-doc:: include/linux/mutex.h
:internal:
.. kernel-doc:: kernel/locking/mutex.c
:export:
.. kernel-doc:: kernel/futex/core.c
:internal:
.. kernel-doc:: kernel/futex/futex.h
:internal:
.. kernel-doc:: kernel/futex/pi.c
:internal:
.. kernel-doc:: kernel/futex/requeue.c
:internal:
.. kernel-doc:: kernel/futex/waitwake.c
:internal:
추가 자료로 Documentation/locking/spinlocks.rst의 Linus Torvalds spinlock tutorial과 Curt Schimmel의 Unix Systems for Modern Architectures가 제시된다. 후자는 Linux 전용 책은 아니지만 SMP locking과 cache 동작의 대부분이 적용된다.
문서 형식과 내용의 교정에는 Telsa Gwynne, Martin Pool, Philipp Rumpf, Stephen Rothwell, Paul Mackerras, Ruedi Aschwanden, Alan Cox, Manfred Spraul, Tim Waugh, Pete Zaitcev, James Morris, Robert Love, Paul McKenney와 John Ashby가 기여했다.
용어 정리
1396-1454| 용어 | 의미 |
|---|---|
| preemption | CONFIG_PREEMPT에서 kernel user context의 더 높은 priority task가 현재 task를 선점할 수 있는 동작. spinlock은 UP에서도 preemption을 disable한다. |
| bh | 역사적 Bottom Half. 오늘날 _bh 함수는 보통 현재 CPU의 모든 software interrupt를 막는다. |
| Hardware IRQ | hardware interrupt request. handler 안에서 in_hardirq()가 true다. |
| Interrupt Context | user context가 아닌 hardware 또는 software IRQ 처리 상태. in_interrupt()로 판별한다. |
| SMP | CONFIG_SMP=y인 symmetric multi-processor kernel. |
| softirq | in_hardirq()는 false, in_softirq()는 true인 software interrupt. 최대 32개 열거형이며 같은 softirq가 여러 CPU에서 동시에 실행될 수 있다. |
| tasklet | 동적으로 등록하며 동일 tasklet instance는 한 번에 한 CPU에서만 실행되는 software interrupt. |
| timer | 지정 시각 근처에 실행되는 동적 software interrupt. TIMER_SOFTIRQ에서 호출되어 실행 문맥은 tasklet과 유사하다. |
| UP | CONFIG_SMP=n인 uni-processor kernel. |
| User Context | 특정 process를 대신해 system call·trap을 처리하거나 kernel thread가 실행되는 kernel 문맥. current로 task를 알 수 있으며 IRQ에 interrupt될 수 있다. |
| Userspace | process가 kernel 밖에서 자신의 code를 실행하는 상태. |
Race condition과 critical region
locking.rst:9-100very_important_count++는 하나의 C expression이지만 실제로는 load, add, store입니다. 두 CPU가 같은 old value를 읽고 각각 store하면 증가 하나가 사라집니다. 결과가 access timing에 따라 달라지는 영역이 race condition이고 그 code 구간이 critical region입니다.
Single CPU도 preemptible kernel이면 한 task가 critical region 중단점에서 선점되고 다른 task가 같은 region에 들어가 동일한 race가 생깁니다. Lock을 추가하기 전에 어떤 state를 하나의 invariant로 유지해야 하는지와 모든 access path를 먼저 목록화합니다.
Lock 수를 늘리는 것보다 보호 범위와 호출 계약을 단순하게 만드는 편이 낫습니다. 새 lock은 ordering edge와 object lifetime rule을 함께 추가합니다.