GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing www.kernel.org — Unreliable Guide To Locking — The Linux Kernel documentation
English
Unreliable Guide To Locking¶
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:
This is what might happen:
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 ( The second type is a mutex ( Neither type of lock is recursive: see Deadlock: Simple and Advanced. Locks and Uniprocessor Kernels¶For kernels compiled without If the kernel is compiled without You should always test your locking code with 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 ( Example: 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 Note that you can also use This works perfectly for UP as well: the spin lock vanishes, and this
macro simply becomes 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 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 Different Softirqs¶You’ll need to use 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
The irq handler does not need to use This works perfectly for UP as well: the spin lock vanishes, and this
macro simply becomes
Note that softirqs (and hence tasklets and timers) are run on return
from hardware interrupts, so Locking Between Two Hard IRQ Handlers¶It is rare to have to share data between two IRQ handlers, but if you
do, Cheat Sheet For Locking¶Pete Zaitcev gives the following summary:
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
Table: Table of Locking Requirements
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.
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_obj(*obj)) == 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;
strscpy(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
Accessing From Interrupt Context¶Now consider the case where The change is shown below, in standard patch format: the --- 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_obj(*obj)) == 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;
strscpy(name, obj->name);
}
- mutex_unlock(&cache_lock);
+ spin_unlock_irqrestore(&cache_lock, flags);
return ret;
}
Note that the Unfortunately, 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 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 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;
- strscpy(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
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, --- 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:
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:
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
I also decided that the id member is unchangeable, so I don’t need to
grab each object lock in 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 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 This complete lockup is easy to diagnose: on SMP boxes the watchdog
timer or compiling with 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:
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 This can be avoided by checking the result of
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 Before freeing a timer, 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). 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: 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 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->next = list->next; wmb(); list->next = new; The Fortunately, there is a function to do this for standard
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 The reader must also be careful: some CPUs can look through the 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 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 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
The result is that 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
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
Of particular use for simple per-cpu counters is the 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 What Functions Are Safe To Call From Interrupts?¶Many functions in the kernel sleep (ie. call 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.
Some Functions Which Don’t Sleep¶Some functions are safe to call from any context, or holding almost any lock. Mutex API reference¶
Parameters
Description Initialize the mutex to unlocked state. It is not allowed to initialize an already locked mutex.
Parameters
Description Initialize the mutex to the unlocked state. It is not allowed to initialize an already locked mutex.
Parameters
Description Returns true if the mutex is locked, false if unlocked.
Parameters
Description Lock the mutex exclusively for this task. If the mutex is not available right now, it will sleep until it can get it. The mutex must later on be released by the same task that
acquired it. Recursive locking is not allowed. The task
may not exit without first unlocking the mutex. Also, kernel
memory where the mutex resides must not be freed with
the mutex still locked. The mutex must first be initialized
(or statically defined) before it can be locked. (The CONFIG_DEBUG_MUTEXES .config option turns on debugging checks that will enforce the restrictions and will also do deadlock debugging) This function is similar to (but not equivalent to)
Parameters
Description Unlock a mutex that has been locked by this task previously. This function must not be used in interrupt context. Unlocking of a not locked mutex is not allowed. The caller must ensure that the mutex stays alive until this function has
returned - This function is similar to (but not equivalent to)
Parameters
Description Unlock a mutex that has been locked by this task previously with any of the ww_mutex_lock* functions (with or without an acquire context). It is forbidden to release the locks after releasing the acquire context. This function must not be used in interrupt context. Unlocking of a unlocked mutex is not allowed.
Parameters
Description Trylocks a mutex with the optional acquire context; no deadlock detection is possible. Returns 1 if the mutex has been acquired successfully, 0 otherwise. Unlike ww_mutex_lock, no deadlock handling is performed. However, if a ctx is specified, -EALREADY handling may happen in calls to ww_mutex_trylock. A mutex acquired with this function must be released with ww_mutex_unlock.
Parameters
Description Lock the mutex like Context Process context. Return 0 if the lock was successfully acquired or
Parameters
Description Lock the mutex like Context Process context. Return 0 if the lock was successfully acquired or
Parameters
Description Lock the mutex like Context Process context.
Parameters
Description Try to acquire the mutex atomically. Returns 1 if the mutex has been acquired successfully, and 0 on contention. NOTE this function follows the This function must not be used in interrupt context. The mutex must be released by the same task that acquired it.
Parameters
Description return true and hold lock if we dec to 0, return false otherwise Futex API reference¶
Parameters
Description We hash on the keys returned from get_futex_key (see below) and return the corresponding hash bucket. If the FUTEX is PROCESS_PRIVATE then a per-process hash bucket (from the private hash) is returned if existing. Otherwise a hash bucket from the global hash is returned.
Parameters
Return Initialized hrtimer_sleeper structure or NULL if no timeout value given
Parameters
Return a negative error code or 0 Description The key words are stored in key on success. For shared mappings (when fshared), the key is:
[ also see For private mappings (or when !fshared), the key is:
This allows (cross process, where applicable) identification of the futex without keeping the page pinned for the duration of the FUTEX_WAIT.
Parameters
Description Slow path to fixup the fault we just took in the atomic write access to uaddr. We have no generic implementation of a non-destructive write to the
user address. We know that we faulted in the atomic pagefault
disabled section so we can as well avoid the #PF overhead by
calling
Parameters
Description Must be called with the hb lock held.
Parameters
Description Caller must hold a refcount on exiting. Parameters
Description The q->lock_ptr must not be NULL and must be held by the caller. Parameters
Description The q->lock_ptr must not be held by the caller. A call to Return
Parameters
Description Set the futex exit state of the task lockless. The futex waiter code observes that state when a task is exiting and loops until the task has actually finished the futex cleanup. The worst case for this is that the waiter runs through the wait loop until the state becomes visible. This is called from the recursive fault handling path in This is best effort. Either the futex exit code has run already or not. If the OWNER_DIED bit has been set on the futex then the waiter can take it over. If not, the problem is pushed back to user space. If the futex exit code did not run yet, then an already queued waiter might block forever, but there is nothing which can be done about that.
Definition: struct futex_q {
struct plist_node list;
struct task_struct *task;
spinlock_t *lock_ptr;
futex_wake_fn *wake;
void *wake_data;
union futex_key key;
struct futex_pi_state *pi_state;
struct rt_mutex_waiter *rt_waiter;
union futex_key *requeue_pi_key;
u32 bitset;
atomic_t requeue_state;
struct futex_private_hash *drop_fph;
#ifdef CONFIG_PREEMPT_RT;
struct rcuwait requeue_wait;
#endif;
};
Members
Description We use this hashed waitqueue, instead of a normal wait_queue_entry_t, so we can wake only the relevant ones (hashed queues may be shared). A futex_q has a woken state, just like tasks have TASK_RUNNING.
It is considered woken when plist_node_empty( PI futexes are typically woken before they are removed from the hash list via
the rt_mutex code. See
Parameters
Description Return 1 if two futex_keys are equal, 0 otherwise.
Parameters
Description The hb->lock must be held by the caller, and is released here. A call to
Note that task may be NULL, for async usage of futexes.
Definition: struct futex_vector {
struct futex_waitv w;
struct futex_q q;
};
Members
Description Struct used to build an array with all data need for
Parameters
Return
Description The hb->lock must be held by the caller. exiting is only set when the return value is -EBUSY. If so, this holds a refcount on the exiting task on return and the caller needs to drop it after waiting for the exit to complete.
Parameters
Description After attempting to lock an rt_mutex, this function is called to cleanup the pi_state owner as well as handle race conditions that may allow us to acquire the lock. Must be called with the hb lock held. Return
Parameters
Parameters
Description During futex_requeue, with requeue_pi=1, it is possible to acquire the target futex if it is uncontended or via a lock steal.
Must be called with both q->lock_ptr and hb->lock held.
Parameters
Description Try and get the lock on behalf of the top waiter if we can do it atomically.
Wake the top waiter if we succeed. If the caller specified set_waiters,
then direct exiting is only set when the return value is -EBUSY. If so, this holds a refcount on the exiting task on return and the caller needs to drop it after waiting for the exit to complete. Return
Parameters
Description Requeue waiters on uaddr1 to uaddr2. In the requeue_pi case, try to acquire uaddr2 atomically on behalf of the top waiter. Return
Parameters
Description Determine the cause for the early wakeup. Return -EWOULDBLOCK or -ETIMEDOUT or -ERESTARTNOINTR
Parameters
Description The caller will wait on uaddr and will be requeued by We call schedule in If 3, cleanup and return -ERESTARTNOINTR. If 2, we may then block on trying to take the rt_mutex and return via: 5) successful lock 6) signal 7) timeout 8) other lock acquisition failure If 6, return -EWOULDBLOCK (restarting the syscall would do the same). If 4 or 7, we cleanup and return with -ETIMEDOUT. Return
Parameters
Parameters
Description Helper to unqueue a list of futexes. This can’t fail. Return
Parameters
Description Prepare multiple futexes in a single step and enqueue them. This may fail if the futex list is invalid or if any futex was already awoken. On success the task is ready to interruptible sleep. Return
Parameters
Description Sleep if and only if the timeout hasn’t expired and no futex on the list has been woken up.
Parameters
Description Entry point for the FUTEX_WAIT_MULTIPLE futex operation, this function sleeps on a group of futexes and returns on the first futex that is wake, or after the timeout has elapsed. Return
Parameters
Description Setup the futex_q and locate the hash_bucket. Get the futex value and compare it with the expected value. Handle atomic faults internally. Return with the hb lock held on success, and unlocked on failure. Return
Further reading¶
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¶
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |