locking/rwsem: Document barrier need when waking tasks
[linux-2.6-block.git] / kernel / locking / rwsem-xadd.c
CommitLineData
1da177e4
LT
1/* rwsem.c: R/W semaphores: contention handling functions
2 *
3 * Written by David Howells (dhowells@redhat.com).
4 * Derived from arch/i386/kernel/semaphore.c
ce6711f3
AS
5 *
6 * Writer lock-stealing by Alex Shi <alex.shi@intel.com>
fe6e674c 7 * and Michel Lespinasse <walken@google.com>
4fc828e2
DB
8 *
9 * Optimistic spinning by Tim Chen <tim.c.chen@intel.com>
10 * and Davidlohr Bueso <davidlohr@hp.com>. Based on mutexes.
1da177e4
LT
11 */
12#include <linux/rwsem.h>
13#include <linux/sched.h>
14#include <linux/init.h>
8bc3bcc9 15#include <linux/export.h>
4fc828e2
DB
16#include <linux/sched/rt.h>
17
18#include "mcs_spinlock.h"
1da177e4 19
3cf2f34e
TC
20/*
21 * Guide to the rw_semaphore's count field for common values.
22 * (32-bit case illustrated, similar for 64-bit)
23 *
24 * 0x0000000X (1) X readers active or attempting lock, no writer waiting
25 * X = #active_readers + #readers attempting to lock
26 * (X*ACTIVE_BIAS)
27 *
28 * 0x00000000 rwsem is unlocked, and no one is waiting for the lock or
29 * attempting to read lock or write lock.
30 *
31 * 0xffff000X (1) X readers active or attempting lock, with waiters for lock
32 * X = #active readers + # readers attempting lock
33 * (X*ACTIVE_BIAS + WAITING_BIAS)
34 * (2) 1 writer attempting lock, no waiters for lock
35 * X-1 = #active readers + #readers attempting lock
36 * ((X-1)*ACTIVE_BIAS + ACTIVE_WRITE_BIAS)
37 * (3) 1 writer active, no waiters for lock
38 * X-1 = #active readers + #readers attempting lock
39 * ((X-1)*ACTIVE_BIAS + ACTIVE_WRITE_BIAS)
40 *
41 * 0xffff0001 (1) 1 reader active or attempting lock, waiters for lock
42 * (WAITING_BIAS + ACTIVE_BIAS)
43 * (2) 1 writer active or attempting lock, no waiters for lock
44 * (ACTIVE_WRITE_BIAS)
45 *
46 * 0xffff0000 (1) There are writers or readers queued but none active
47 * or in the process of attempting lock.
48 * (WAITING_BIAS)
49 * Note: writer can attempt to steal lock for this count by adding
50 * ACTIVE_WRITE_BIAS in cmpxchg and checking the old count
51 *
52 * 0xfffe0001 (1) 1 writer active, or attempting lock. Waiters on queue.
53 * (ACTIVE_WRITE_BIAS + WAITING_BIAS)
54 *
55 * Note: Readers attempt to lock by adding ACTIVE_BIAS in down_read and checking
56 * the count becomes more than 0 for successful lock acquisition,
57 * i.e. the case where there are only readers or nobody has lock.
58 * (1st and 2nd case above).
59 *
60 * Writers attempt to lock by adding ACTIVE_WRITE_BIAS in down_write and
61 * checking the count becomes ACTIVE_WRITE_BIAS for successful lock
62 * acquisition (i.e. nobody else has lock or attempts lock). If
63 * unsuccessful, in rwsem_down_write_failed, we'll check to see if there
64 * are only waiters but none active (5th case above), and attempt to
65 * steal the lock.
66 *
67 */
68
4ea2176d
IM
69/*
70 * Initialize an rwsem:
71 */
72void __init_rwsem(struct rw_semaphore *sem, const char *name,
73 struct lock_class_key *key)
74{
75#ifdef CONFIG_DEBUG_LOCK_ALLOC
76 /*
77 * Make sure we are not reinitializing a held semaphore:
78 */
79 debug_check_no_locks_freed((void *)sem, sizeof(*sem));
4dfbb9d8 80 lockdep_init_map(&sem->dep_map, name, key, 0);
4ea2176d
IM
81#endif
82 sem->count = RWSEM_UNLOCKED_VALUE;
ddb6c9b5 83 raw_spin_lock_init(&sem->wait_lock);
4ea2176d 84 INIT_LIST_HEAD(&sem->wait_list);
5db6c6fe 85#ifdef CONFIG_RWSEM_SPIN_ON_OWNER
4fc828e2 86 sem->owner = NULL;
4d9d951e 87 osq_lock_init(&sem->osq);
4fc828e2 88#endif
4ea2176d
IM
89}
90
91EXPORT_SYMBOL(__init_rwsem);
92
e2d57f78
ML
93enum rwsem_waiter_type {
94 RWSEM_WAITING_FOR_WRITE,
95 RWSEM_WAITING_FOR_READ
96};
97
1da177e4
LT
98struct rwsem_waiter {
99 struct list_head list;
100 struct task_struct *task;
e2d57f78 101 enum rwsem_waiter_type type;
1da177e4
LT
102};
103
fe6e674c
ML
104enum rwsem_wake_type {
105 RWSEM_WAKE_ANY, /* Wake whatever's at head of wait list */
106 RWSEM_WAKE_READERS, /* Wake readers only */
107 RWSEM_WAKE_READ_OWNED /* Waker thread holds the read lock */
108};
70bdc6e0 109
1da177e4
LT
110/*
111 * handle the lock release when processes blocked on it that can now run
112 * - if we come here from up_xxxx(), then:
113 * - the 'active part' of count (&0x0000ffff) reached 0 (but may have changed)
114 * - the 'waiting part' of count (&0xffff0000) is -ve (and will still be so)
345af7bf 115 * - there must be someone on the queue
1da177e4
LT
116 * - the spinlock must be held by the caller
117 * - woken process blocks are discarded from the list after having task zeroed
118 * - writers are only woken if downgrading is false
119 */
70bdc6e0 120static struct rw_semaphore *
fe6e674c 121__rwsem_do_wake(struct rw_semaphore *sem, enum rwsem_wake_type wake_type)
1da177e4
LT
122{
123 struct rwsem_waiter *waiter;
124 struct task_struct *tsk;
125 struct list_head *next;
b5f54181 126 long oldcount, woken, loop, adjustment;
1da177e4 127
345af7bf 128 waiter = list_entry(sem->wait_list.next, struct rwsem_waiter, list);
8cf5322c 129 if (waiter->type == RWSEM_WAITING_FOR_WRITE) {
fe6e674c 130 if (wake_type == RWSEM_WAKE_ANY)
8cf5322c
ML
131 /* Wake writer at the front of the queue, but do not
132 * grant it the lock yet as we want other writers
133 * to be able to steal it. Readers, on the other hand,
134 * will block as they will notice the queued writer.
135 */
136 wake_up_process(waiter->task);
345af7bf 137 goto out;
8cf5322c 138 }
1da177e4 139
fe6e674c
ML
140 /* Writers might steal the lock before we grant it to the next reader.
141 * We prefer to do the first reader grant before counting readers
142 * so we can bail out early if a writer stole the lock.
70bdc6e0 143 */
fe6e674c
ML
144 adjustment = 0;
145 if (wake_type != RWSEM_WAKE_READ_OWNED) {
146 adjustment = RWSEM_ACTIVE_READ_BIAS;
147 try_reader_grant:
148 oldcount = rwsem_atomic_update(adjustment, sem) - adjustment;
149 if (unlikely(oldcount < RWSEM_WAITING_BIAS)) {
150 /* A writer stole the lock. Undo our reader grant. */
151 if (rwsem_atomic_update(-adjustment, sem) &
152 RWSEM_ACTIVE_MASK)
153 goto out;
154 /* Last active locker left. Retry waking readers. */
155 goto try_reader_grant;
156 }
157 }
1da177e4 158
345af7bf
ML
159 /* Grant an infinite number of read locks to the readers at the front
160 * of the queue. Note we increment the 'active part' of the count by
161 * the number of readers before waking any processes up.
1da177e4 162 */
1da177e4
LT
163 woken = 0;
164 do {
165 woken++;
166
167 if (waiter->list.next == &sem->wait_list)
168 break;
169
170 waiter = list_entry(waiter->list.next,
171 struct rwsem_waiter, list);
172
e2d57f78 173 } while (waiter->type != RWSEM_WAITING_FOR_WRITE);
1da177e4 174
fe6e674c 175 adjustment = woken * RWSEM_ACTIVE_READ_BIAS - adjustment;
e2d57f78 176 if (waiter->type != RWSEM_WAITING_FOR_WRITE)
fd41b334
ML
177 /* hit end of list above */
178 adjustment -= RWSEM_WAITING_BIAS;
1da177e4 179
fe6e674c
ML
180 if (adjustment)
181 rwsem_atomic_add(adjustment, sem);
1da177e4
LT
182
183 next = sem->wait_list.next;
8cf5322c
ML
184 loop = woken;
185 do {
1da177e4
LT
186 waiter = list_entry(next, struct rwsem_waiter, list);
187 next = waiter->list.next;
188 tsk = waiter->task;
49e4b2bc
DB
189 /*
190 * Make sure we do not wakeup the next reader before
191 * setting the nil condition to grant the next reader;
192 * otherwise we could miss the wakeup on the other
193 * side and end up sleeping again. See the pairing
194 * in rwsem_down_read_failed().
195 */
d59dd462 196 smp_mb();
1da177e4
LT
197 waiter->task = NULL;
198 wake_up_process(tsk);
199 put_task_struct(tsk);
8cf5322c 200 } while (--loop);
1da177e4
LT
201
202 sem->wait_list.next = next;
203 next->prev = &sem->wait_list;
204
205 out:
1da177e4 206 return sem;
ce6711f3
AS
207}
208
1da177e4 209/*
4fc828e2 210 * Wait for the read lock to be granted
1da177e4 211 */
3ebae4f3 212__visible
1e78277c 213struct rw_semaphore __sched *rwsem_down_read_failed(struct rw_semaphore *sem)
1da177e4 214{
b5f54181 215 long count, adjustment = -RWSEM_ACTIVE_READ_BIAS;
a8618a0e 216 struct rwsem_waiter waiter;
1da177e4 217 struct task_struct *tsk = current;
1da177e4 218
1da177e4 219 /* set up my own style of waitqueue */
a8618a0e 220 waiter.task = tsk;
da16922c 221 waiter.type = RWSEM_WAITING_FOR_READ;
1da177e4
LT
222 get_task_struct(tsk);
223
f7dd1cee 224 raw_spin_lock_irq(&sem->wait_lock);
fd41b334
ML
225 if (list_empty(&sem->wait_list))
226 adjustment += RWSEM_WAITING_BIAS;
a8618a0e 227 list_add_tail(&waiter.list, &sem->wait_list);
1da177e4 228
70bdc6e0 229 /* we're now waiting on the lock, but no longer actively locking */
1da177e4
LT
230 count = rwsem_atomic_update(adjustment, sem);
231
25c39325
ML
232 /* If there are no active locks, wake the front queued process(es).
233 *
234 * If there are no writers and we are first in the queue,
235 * wake our own waiter to join the existing active readers !
236 */
237 if (count == RWSEM_WAITING_BIAS ||
238 (count > RWSEM_WAITING_BIAS &&
239 adjustment != -RWSEM_ACTIVE_READ_BIAS))
fe6e674c 240 sem = __rwsem_do_wake(sem, RWSEM_WAKE_ANY);
1da177e4 241
ddb6c9b5 242 raw_spin_unlock_irq(&sem->wait_lock);
1da177e4
LT
243
244 /* wait to be given the lock */
f7dd1cee
ML
245 while (true) {
246 set_task_state(tsk, TASK_UNINTERRUPTIBLE);
a8618a0e 247 if (!waiter.task)
1da177e4
LT
248 break;
249 schedule();
1da177e4
LT
250 }
251
73105994 252 __set_task_state(tsk, TASK_RUNNING);
1da177e4
LT
253 return sem;
254}
db0e716a 255EXPORT_SYMBOL(rwsem_down_read_failed);
1da177e4 256
4fc828e2
DB
257static inline bool rwsem_try_write_lock(long count, struct rw_semaphore *sem)
258{
debfab74
JL
259 /*
260 * Try acquiring the write lock. Check count first in order
261 * to reduce unnecessary expensive cmpxchg() operations.
262 */
263 if (count == RWSEM_WAITING_BIAS &&
264 cmpxchg(&sem->count, RWSEM_WAITING_BIAS,
265 RWSEM_ACTIVE_WRITE_BIAS) == RWSEM_WAITING_BIAS) {
266 if (!list_is_singular(&sem->wait_list))
267 rwsem_atomic_update(RWSEM_WAITING_BIAS, sem);
268 return true;
4fc828e2 269 }
debfab74 270
4fc828e2
DB
271 return false;
272}
273
5db6c6fe 274#ifdef CONFIG_RWSEM_SPIN_ON_OWNER
1da177e4 275/*
4fc828e2
DB
276 * Try to acquire write lock before the writer has been put on wait queue.
277 */
278static inline bool rwsem_try_write_lock_unqueued(struct rw_semaphore *sem)
279{
280 long old, count = ACCESS_ONCE(sem->count);
281
282 while (true) {
283 if (!(count == 0 || count == RWSEM_WAITING_BIAS))
284 return false;
285
286 old = cmpxchg(&sem->count, count, count + RWSEM_ACTIVE_WRITE_BIAS);
287 if (old == count)
288 return true;
289
290 count = old;
291 }
292}
293
294static inline bool rwsem_can_spin_on_owner(struct rw_semaphore *sem)
295{
296 struct task_struct *owner;
37e95624 297 bool on_cpu = false;
4fc828e2
DB
298
299 if (need_resched())
37e95624 300 return false;
4fc828e2
DB
301
302 rcu_read_lock();
303 owner = ACCESS_ONCE(sem->owner);
304 if (owner)
305 on_cpu = owner->on_cpu;
306 rcu_read_unlock();
307
308 /*
37e95624
JL
309 * If sem->owner is not set, yet we have just recently entered the
310 * slowpath, then there is a possibility reader(s) may have the lock.
311 * To be safe, avoid spinning in these situations.
4fc828e2
DB
312 */
313 return on_cpu;
314}
315
316static inline bool owner_running(struct rw_semaphore *sem,
317 struct task_struct *owner)
318{
319 if (sem->owner != owner)
320 return false;
321
322 /*
323 * Ensure we emit the owner->on_cpu, dereference _after_ checking
324 * sem->owner still matches owner, if that fails, owner might
325 * point to free()d memory, if it still matches, the rcu_read_lock()
326 * ensures the memory stays valid.
327 */
328 barrier();
329
330 return owner->on_cpu;
331}
332
333static noinline
334bool rwsem_spin_on_owner(struct rw_semaphore *sem, struct task_struct *owner)
335{
336 rcu_read_lock();
337 while (owner_running(sem, owner)) {
338 if (need_resched())
339 break;
340
3a6bfbc9 341 cpu_relax_lowlatency();
4fc828e2
DB
342 }
343 rcu_read_unlock();
344
345 /*
346 * We break out the loop above on need_resched() or when the
347 * owner changed, which is a sign for heavy contention. Return
348 * success only when sem->owner is NULL.
349 */
350 return sem->owner == NULL;
351}
352
353static bool rwsem_optimistic_spin(struct rw_semaphore *sem)
354{
355 struct task_struct *owner;
356 bool taken = false;
357
358 preempt_disable();
359
360 /* sem->wait_lock should not be held when doing optimistic spinning */
361 if (!rwsem_can_spin_on_owner(sem))
362 goto done;
363
364 if (!osq_lock(&sem->osq))
365 goto done;
366
367 while (true) {
368 owner = ACCESS_ONCE(sem->owner);
369 if (owner && !rwsem_spin_on_owner(sem, owner))
370 break;
371
372 /* wait_lock will be acquired if write_lock is obtained */
373 if (rwsem_try_write_lock_unqueued(sem)) {
374 taken = true;
375 break;
376 }
377
378 /*
379 * When there's no owner, we might have preempted between the
380 * owner acquiring the lock and setting the owner field. If
381 * we're an RT task that will live-lock because we won't let
382 * the owner complete.
383 */
384 if (!owner && (need_resched() || rt_task(current)))
385 break;
386
387 /*
388 * The cpu_relax() call is a compiler barrier which forces
389 * everything in this loop to be re-loaded. We don't need
390 * memory barriers as we'll eventually observe the right
391 * values at the cost of a few extra spins.
392 */
3a6bfbc9 393 cpu_relax_lowlatency();
4fc828e2
DB
394 }
395 osq_unlock(&sem->osq);
396done:
397 preempt_enable();
398 return taken;
399}
400
401#else
402static bool rwsem_optimistic_spin(struct rw_semaphore *sem)
403{
404 return false;
405}
406#endif
407
408/*
409 * Wait until we successfully acquire the write lock
1da177e4 410 */
3ebae4f3 411__visible
d1233754 412struct rw_semaphore __sched *rwsem_down_write_failed(struct rw_semaphore *sem)
1da177e4 413{
4fc828e2
DB
414 long count;
415 bool waiting = true; /* any queued threads before us */
1e78277c 416 struct rwsem_waiter waiter;
1e78277c 417
4fc828e2
DB
418 /* undo write bias from down_write operation, stop active locking */
419 count = rwsem_atomic_update(-RWSEM_ACTIVE_WRITE_BIAS, sem);
420
421 /* do optimistic spinning and steal lock if possible */
422 if (rwsem_optimistic_spin(sem))
423 return sem;
424
425 /*
426 * Optimistic spinning failed, proceed to the slowpath
427 * and block until we can acquire the sem.
428 */
429 waiter.task = current;
023fe4f7 430 waiter.type = RWSEM_WAITING_FOR_WRITE;
1e78277c
ML
431
432 raw_spin_lock_irq(&sem->wait_lock);
4fc828e2
DB
433
434 /* account for this before adding a new element to the list */
1e78277c 435 if (list_empty(&sem->wait_list))
4fc828e2
DB
436 waiting = false;
437
1e78277c
ML
438 list_add_tail(&waiter.list, &sem->wait_list);
439
440 /* we're now waiting on the lock, but no longer actively locking */
4fc828e2
DB
441 if (waiting) {
442 count = ACCESS_ONCE(sem->count);
1e78277c 443
4fc828e2 444 /*
0cc3d011
AM
445 * If there were already threads queued before us and there are
446 * no active writers, the lock must be read owned; so we try to
447 * wake any read locks that were queued ahead of us.
4fc828e2
DB
448 */
449 if (count > RWSEM_WAITING_BIAS)
450 sem = __rwsem_do_wake(sem, RWSEM_WAKE_READERS);
451
452 } else
453 count = rwsem_atomic_update(RWSEM_WAITING_BIAS, sem);
1e78277c 454
023fe4f7 455 /* wait until we successfully acquire the lock */
4fc828e2 456 set_current_state(TASK_UNINTERRUPTIBLE);
1e78277c 457 while (true) {
4fc828e2
DB
458 if (rwsem_try_write_lock(count, sem))
459 break;
1e78277c 460 raw_spin_unlock_irq(&sem->wait_lock);
a7d2c573
ML
461
462 /* Block until there are no active lockers. */
463 do {
464 schedule();
4fc828e2 465 set_current_state(TASK_UNINTERRUPTIBLE);
9b0fc9c0 466 } while ((count = sem->count) & RWSEM_ACTIVE_MASK);
a7d2c573 467
023fe4f7 468 raw_spin_lock_irq(&sem->wait_lock);
1e78277c 469 }
4fc828e2 470 __set_current_state(TASK_RUNNING);
1e78277c 471
023fe4f7
ML
472 list_del(&waiter.list);
473 raw_spin_unlock_irq(&sem->wait_lock);
1e78277c
ML
474
475 return sem;
1da177e4 476}
db0e716a 477EXPORT_SYMBOL(rwsem_down_write_failed);
1da177e4
LT
478
479/*
480 * handle waking up a waiter on the semaphore
481 * - up_read/up_write has decremented the active part of count if we come here
482 */
3ebae4f3 483__visible
d1233754 484struct rw_semaphore *rwsem_wake(struct rw_semaphore *sem)
1da177e4
LT
485{
486 unsigned long flags;
487
ddb6c9b5 488 raw_spin_lock_irqsave(&sem->wait_lock, flags);
1da177e4
LT
489
490 /* do nothing if list empty */
491 if (!list_empty(&sem->wait_list))
70bdc6e0 492 sem = __rwsem_do_wake(sem, RWSEM_WAKE_ANY);
1da177e4 493
ddb6c9b5 494 raw_spin_unlock_irqrestore(&sem->wait_lock, flags);
1da177e4 495
1da177e4
LT
496 return sem;
497}
db0e716a 498EXPORT_SYMBOL(rwsem_wake);
1da177e4
LT
499
500/*
501 * downgrade a write lock into a read lock
502 * - caller incremented waiting part of count and discovered it still negative
503 * - just wake up any readers at the front of the queue
504 */
3ebae4f3 505__visible
d1233754 506struct rw_semaphore *rwsem_downgrade_wake(struct rw_semaphore *sem)
1da177e4
LT
507{
508 unsigned long flags;
509
ddb6c9b5 510 raw_spin_lock_irqsave(&sem->wait_lock, flags);
1da177e4
LT
511
512 /* do nothing if list empty */
513 if (!list_empty(&sem->wait_list))
70bdc6e0 514 sem = __rwsem_do_wake(sem, RWSEM_WAKE_READ_OWNED);
1da177e4 515
ddb6c9b5 516 raw_spin_unlock_irqrestore(&sem->wait_lock, flags);
1da177e4 517
1da177e4
LT
518 return sem;
519}
1da177e4 520EXPORT_SYMBOL(rwsem_downgrade_wake);