OSDN Git Service

locking/qspinlock: Re-order code
[android-x86/kernel.git] / kernel / locking / qspinlock.c
1 /*
2  * Queued spinlock
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * (C) Copyright 2013-2015 Hewlett-Packard Development Company, L.P.
15  * (C) Copyright 2013-2014 Red Hat, Inc.
16  * (C) Copyright 2015 Intel Corp.
17  * (C) Copyright 2015 Hewlett-Packard Enterprise Development LP
18  *
19  * Authors: Waiman Long <waiman.long@hpe.com>
20  *          Peter Zijlstra <peterz@infradead.org>
21  */
22
23 #ifndef _GEN_PV_LOCK_SLOWPATH
24
25 #include <linux/smp.h>
26 #include <linux/bug.h>
27 #include <linux/cpumask.h>
28 #include <linux/percpu.h>
29 #include <linux/hardirq.h>
30 #include <linux/mutex.h>
31 #include <asm/byteorder.h>
32 #include <asm/qspinlock.h>
33
34 /*
35  * The basic principle of a queue-based spinlock can best be understood
36  * by studying a classic queue-based spinlock implementation called the
37  * MCS lock. The paper below provides a good description for this kind
38  * of lock.
39  *
40  * http://www.cise.ufl.edu/tr/DOC/REP-1992-71.pdf
41  *
42  * This queued spinlock implementation is based on the MCS lock, however to make
43  * it fit the 4 bytes we assume spinlock_t to be, and preserve its existing
44  * API, we must modify it somehow.
45  *
46  * In particular; where the traditional MCS lock consists of a tail pointer
47  * (8 bytes) and needs the next pointer (another 8 bytes) of its own node to
48  * unlock the next pending (next->locked), we compress both these: {tail,
49  * next->locked} into a single u32 value.
50  *
51  * Since a spinlock disables recursion of its own context and there is a limit
52  * to the contexts that can nest; namely: task, softirq, hardirq, nmi. As there
53  * are at most 4 nesting levels, it can be encoded by a 2-bit number. Now
54  * we can encode the tail by combining the 2-bit nesting level with the cpu
55  * number. With one byte for the lock value and 3 bytes for the tail, only a
56  * 32-bit word is now needed. Even though we only need 1 bit for the lock,
57  * we extend it to a full byte to achieve better performance for architectures
58  * that support atomic byte write.
59  *
60  * We also change the first spinner to spin on the lock bit instead of its
61  * node; whereby avoiding the need to carry a node from lock to unlock, and
62  * preserving existing lock API. This also makes the unlock code simpler and
63  * faster.
64  *
65  * N.B. The current implementation only supports architectures that allow
66  *      atomic operations on smaller 8-bit and 16-bit data types.
67  *
68  */
69
70 #include "mcs_spinlock.h"
71
72 #ifdef CONFIG_PARAVIRT_SPINLOCKS
73 #define MAX_NODES       8
74 #else
75 #define MAX_NODES       4
76 #endif
77
78 /*
79  * The pending bit spinning loop count.
80  * This heuristic is used to limit the number of lockword accesses
81  * made by atomic_cond_read_relaxed when waiting for the lock to
82  * transition out of the "== _Q_PENDING_VAL" state. We don't spin
83  * indefinitely because there's no guarantee that we'll make forward
84  * progress.
85  */
86 #ifndef _Q_PENDING_LOOPS
87 #define _Q_PENDING_LOOPS        1
88 #endif
89
90 /*
91  * Per-CPU queue node structures; we can never have more than 4 nested
92  * contexts: task, softirq, hardirq, nmi.
93  *
94  * Exactly fits one 64-byte cacheline on a 64-bit architecture.
95  *
96  * PV doubles the storage and uses the second cacheline for PV state.
97  */
98 static DEFINE_PER_CPU_ALIGNED(struct mcs_spinlock, mcs_nodes[MAX_NODES]);
99
100 /*
101  * We must be able to distinguish between no-tail and the tail at 0:0,
102  * therefore increment the cpu number by one.
103  */
104
105 static inline __pure u32 encode_tail(int cpu, int idx)
106 {
107         u32 tail;
108
109 #ifdef CONFIG_DEBUG_SPINLOCK
110         BUG_ON(idx > 3);
111 #endif
112         tail  = (cpu + 1) << _Q_TAIL_CPU_OFFSET;
113         tail |= idx << _Q_TAIL_IDX_OFFSET; /* assume < 4 */
114
115         return tail;
116 }
117
118 static inline __pure struct mcs_spinlock *decode_tail(u32 tail)
119 {
120         int cpu = (tail >> _Q_TAIL_CPU_OFFSET) - 1;
121         int idx = (tail &  _Q_TAIL_IDX_MASK) >> _Q_TAIL_IDX_OFFSET;
122
123         return per_cpu_ptr(&mcs_nodes[idx], cpu);
124 }
125
126 #define _Q_LOCKED_PENDING_MASK (_Q_LOCKED_MASK | _Q_PENDING_MASK)
127
128 #if _Q_PENDING_BITS == 8
129 /**
130  * clear_pending - clear the pending bit.
131  * @lock: Pointer to queued spinlock structure
132  *
133  * *,1,* -> *,0,*
134  */
135 static __always_inline void clear_pending(struct qspinlock *lock)
136 {
137         WRITE_ONCE(lock->pending, 0);
138 }
139
140 /**
141  * clear_pending_set_locked - take ownership and clear the pending bit.
142  * @lock: Pointer to queued spinlock structure
143  *
144  * *,1,0 -> *,0,1
145  *
146  * Lock stealing is not allowed if this function is used.
147  */
148 static __always_inline void clear_pending_set_locked(struct qspinlock *lock)
149 {
150         WRITE_ONCE(lock->locked_pending, _Q_LOCKED_VAL);
151 }
152
153 /*
154  * xchg_tail - Put in the new queue tail code word & retrieve previous one
155  * @lock : Pointer to queued spinlock structure
156  * @tail : The new queue tail code word
157  * Return: The previous queue tail code word
158  *
159  * xchg(lock, tail), which heads an address dependency
160  *
161  * p,*,* -> n,*,* ; prev = xchg(lock, node)
162  */
163 static __always_inline u32 xchg_tail(struct qspinlock *lock, u32 tail)
164 {
165         /*
166          * Use release semantics to make sure that the MCS node is properly
167          * initialized before changing the tail code.
168          */
169         return (u32)xchg_release(&lock->tail,
170                                  tail >> _Q_TAIL_OFFSET) << _Q_TAIL_OFFSET;
171 }
172
173 #else /* _Q_PENDING_BITS == 8 */
174
175 /**
176  * clear_pending - clear the pending bit.
177  * @lock: Pointer to queued spinlock structure
178  *
179  * *,1,* -> *,0,*
180  */
181 static __always_inline void clear_pending(struct qspinlock *lock)
182 {
183         atomic_andnot(_Q_PENDING_VAL, &lock->val);
184 }
185
186 /**
187  * clear_pending_set_locked - take ownership and clear the pending bit.
188  * @lock: Pointer to queued spinlock structure
189  *
190  * *,1,0 -> *,0,1
191  */
192 static __always_inline void clear_pending_set_locked(struct qspinlock *lock)
193 {
194         atomic_add(-_Q_PENDING_VAL + _Q_LOCKED_VAL, &lock->val);
195 }
196
197 /**
198  * xchg_tail - Put in the new queue tail code word & retrieve previous one
199  * @lock : Pointer to queued spinlock structure
200  * @tail : The new queue tail code word
201  * Return: The previous queue tail code word
202  *
203  * xchg(lock, tail)
204  *
205  * p,*,* -> n,*,* ; prev = xchg(lock, node)
206  */
207 static __always_inline u32 xchg_tail(struct qspinlock *lock, u32 tail)
208 {
209         u32 old, new, val = atomic_read(&lock->val);
210
211         for (;;) {
212                 new = (val & _Q_LOCKED_PENDING_MASK) | tail;
213                 /*
214                  * Use release semantics to make sure that the MCS node is
215                  * properly initialized before changing the tail code.
216                  */
217                 old = atomic_cmpxchg_release(&lock->val, val, new);
218                 if (old == val)
219                         break;
220
221                 val = old;
222         }
223         return old;
224 }
225 #endif /* _Q_PENDING_BITS == 8 */
226
227 /**
228  * set_locked - Set the lock bit and own the lock
229  * @lock: Pointer to queued spinlock structure
230  *
231  * *,*,0 -> *,0,1
232  */
233 static __always_inline void set_locked(struct qspinlock *lock)
234 {
235         WRITE_ONCE(lock->locked, _Q_LOCKED_VAL);
236 }
237
238
239 /*
240  * Generate the native code for queued_spin_unlock_slowpath(); provide NOPs for
241  * all the PV callbacks.
242  */
243
244 static __always_inline void __pv_init_node(struct mcs_spinlock *node) { }
245 static __always_inline void __pv_wait_node(struct mcs_spinlock *node,
246                                            struct mcs_spinlock *prev) { }
247 static __always_inline void __pv_kick_node(struct qspinlock *lock,
248                                            struct mcs_spinlock *node) { }
249 static __always_inline u32  __pv_wait_head_or_lock(struct qspinlock *lock,
250                                                    struct mcs_spinlock *node)
251                                                    { return 0; }
252
253 #define pv_enabled()            false
254
255 #define pv_init_node            __pv_init_node
256 #define pv_wait_node            __pv_wait_node
257 #define pv_kick_node            __pv_kick_node
258 #define pv_wait_head_or_lock    __pv_wait_head_or_lock
259
260 #ifdef CONFIG_PARAVIRT_SPINLOCKS
261 #define queued_spin_lock_slowpath       native_queued_spin_lock_slowpath
262 #endif
263
264 /*
265  * Various notes on spin_is_locked() and spin_unlock_wait(), which are
266  * 'interesting' functions:
267  *
268  * PROBLEM: some architectures have an interesting issue with atomic ACQUIRE
269  * operations in that the ACQUIRE applies to the LOAD _not_ the STORE (ARM64,
270  * PPC). Also qspinlock has a similar issue per construction, the setting of
271  * the locked byte can be unordered acquiring the lock proper.
272  *
273  * This gets to be 'interesting' in the following cases, where the /should/s
274  * end up false because of this issue.
275  *
276  *
277  * CASE 1:
278  *
279  * So the spin_is_locked() correctness issue comes from something like:
280  *
281  *   CPU0                               CPU1
282  *
283  *   global_lock();                     local_lock(i)
284  *     spin_lock(&G)                      spin_lock(&L[i])
285  *     for (i)                            if (!spin_is_locked(&G)) {
286  *       spin_unlock_wait(&L[i]);           smp_acquire__after_ctrl_dep();
287  *                                          return;
288  *                                        }
289  *                                        // deal with fail
290  *
291  * Where it is important CPU1 sees G locked or CPU0 sees L[i] locked such
292  * that there is exclusion between the two critical sections.
293  *
294  * The load from spin_is_locked(&G) /should/ be constrained by the ACQUIRE from
295  * spin_lock(&L[i]), and similarly the load(s) from spin_unlock_wait(&L[i])
296  * /should/ be constrained by the ACQUIRE from spin_lock(&G).
297  *
298  * Similarly, later stuff is constrained by the ACQUIRE from CTRL+RMB.
299  *
300  *
301  * CASE 2:
302  *
303  * For spin_unlock_wait() there is a second correctness issue, namely:
304  *
305  *   CPU0                               CPU1
306  *
307  *   flag = set;
308  *   smp_mb();                          spin_lock(&l)
309  *   spin_unlock_wait(&l);              if (!flag)
310  *                                        // add to lockless list
311  *                                      spin_unlock(&l);
312  *   // iterate lockless list
313  *
314  * Which wants to ensure that CPU1 will stop adding bits to the list and CPU0
315  * will observe the last entry on the list (if spin_unlock_wait() had ACQUIRE
316  * semantics etc..)
317  *
318  * Where flag /should/ be ordered against the locked store of l.
319  */
320
321 /*
322  * queued_spin_lock_slowpath() can (load-)ACQUIRE the lock before
323  * issuing an _unordered_ store to set _Q_LOCKED_VAL.
324  *
325  * This means that the store can be delayed, but no later than the
326  * store-release from the unlock. This means that simply observing
327  * _Q_LOCKED_VAL is not sufficient to determine if the lock is acquired.
328  *
329  * There are two paths that can issue the unordered store:
330  *
331  *  (1) clear_pending_set_locked():     *,1,0 -> *,0,1
332  *
333  *  (2) set_locked():                   t,0,0 -> t,0,1 ; t != 0
334  *      atomic_cmpxchg_relaxed():       t,0,0 -> 0,0,1
335  *
336  * However, in both cases we have other !0 state we've set before to queue
337  * ourseves:
338  *
339  * For (1) we have the atomic_cmpxchg_acquire() that set _Q_PENDING_VAL, our
340  * load is constrained by that ACQUIRE to not pass before that, and thus must
341  * observe the store.
342  *
343  * For (2) we have a more intersting scenario. We enqueue ourselves using
344  * xchg_tail(), which ends up being a RELEASE. This in itself is not
345  * sufficient, however that is followed by an smp_cond_acquire() on the same
346  * word, giving a RELEASE->ACQUIRE ordering. This again constrains our load and
347  * guarantees we must observe that store.
348  *
349  * Therefore both cases have other !0 state that is observable before the
350  * unordered locked byte store comes through. This means we can use that to
351  * wait for the lock store, and then wait for an unlock.
352  */
353 #ifndef queued_spin_unlock_wait
354 void queued_spin_unlock_wait(struct qspinlock *lock)
355 {
356         u32 val;
357
358         for (;;) {
359                 val = atomic_read(&lock->val);
360
361                 if (!val) /* not locked, we're done */
362                         goto done;
363
364                 if (val & _Q_LOCKED_MASK) /* locked, go wait for unlock */
365                         break;
366
367                 /* not locked, but pending, wait until we observe the lock */
368                 cpu_relax();
369         }
370
371         /* any unlock is good */
372         while (atomic_read(&lock->val) & _Q_LOCKED_MASK)
373                 cpu_relax();
374
375 done:
376         smp_acquire__after_ctrl_dep();
377 }
378 EXPORT_SYMBOL(queued_spin_unlock_wait);
379 #endif
380
381 #endif /* _GEN_PV_LOCK_SLOWPATH */
382
383 /**
384  * queued_spin_lock_slowpath - acquire the queued spinlock
385  * @lock: Pointer to queued spinlock structure
386  * @val: Current value of the queued spinlock 32-bit word
387  *
388  * (queue tail, pending bit, lock value)
389  *
390  *              fast     :    slow                                  :    unlock
391  *                       :                                          :
392  * uncontended  (0,0,0) -:--> (0,0,1) ------------------------------:--> (*,*,0)
393  *                       :       | ^--------.------.             /  :
394  *                       :       v           \      \            |  :
395  * pending               :    (0,1,1) +--> (0,1,0)   \           |  :
396  *                       :       | ^--'              |           |  :
397  *                       :       v                   |           |  :
398  * uncontended           :    (n,x,y) +--> (n,0,0) --'           |  :
399  *   queue               :       | ^--'                          |  :
400  *                       :       v                               |  :
401  * contended             :    (*,x,y) +--> (*,0,0) ---> (*,0,1) -'  :
402  *   queue               :         ^--'                             :
403  */
404 void queued_spin_lock_slowpath(struct qspinlock *lock, u32 val)
405 {
406         struct mcs_spinlock *prev, *next, *node;
407         u32 old, tail;
408         int idx;
409
410         BUILD_BUG_ON(CONFIG_NR_CPUS >= (1U << _Q_TAIL_CPU_BITS));
411
412         if (pv_enabled())
413                 goto queue;
414
415         if (virt_spin_lock(lock))
416                 return;
417
418         /*
419          * Wait for in-progress pending->locked hand-overs with a bounded
420          * number of spins so that we guarantee forward progress.
421          *
422          * 0,1,0 -> 0,0,1
423          */
424         if (val == _Q_PENDING_VAL) {
425                 int cnt = _Q_PENDING_LOOPS;
426                 val = smp_cond_load_acquire(&lock->val.counter,
427                                                (VAL != _Q_PENDING_VAL) || !cnt--);
428         }
429
430         /*
431          * If we observe any contention; queue.
432          */
433         if (val & ~_Q_LOCKED_MASK)
434                 goto queue;
435
436         /*
437          * trylock || pending
438          *
439          * 0,0,0 -> 0,0,1 ; trylock
440          * 0,0,1 -> 0,1,1 ; pending
441          */
442         val = atomic_fetch_or_acquire(_Q_PENDING_VAL, &lock->val);
443         /*
444          * If we observe any contention; undo and queue.
445          */
446         if (unlikely(val & ~_Q_LOCKED_MASK)) {
447                 if (!(val & _Q_PENDING_MASK))
448                         clear_pending(lock);
449                 goto queue;
450         }
451
452         /*
453          * We're pending, wait for the owner to go away.
454          *
455          * 0,1,1 -> 0,1,0
456          *
457          * this wait loop must be a load-acquire such that we match the
458          * store-release that clears the locked bit and create lock
459          * sequentiality; this is because not all
460          * clear_pending_set_locked() implementations imply full
461          * barriers.
462          */
463         if (val & _Q_LOCKED_MASK)
464                 smp_cond_load_acquire(&lock->val.counter, !(VAL & _Q_LOCKED_MASK));
465
466         /*
467          * take ownership and clear the pending bit.
468          *
469          * 0,1,0 -> 0,0,1
470          */
471         clear_pending_set_locked(lock);
472         return;
473
474         /*
475          * End of pending bit optimistic spinning and beginning of MCS
476          * queuing.
477          */
478 queue:
479         node = this_cpu_ptr(&mcs_nodes[0]);
480         idx = node->count++;
481         tail = encode_tail(smp_processor_id(), idx);
482
483         node += idx;
484
485         /*
486          * Ensure that we increment the head node->count before initialising
487          * the actual node. If the compiler is kind enough to reorder these
488          * stores, then an IRQ could overwrite our assignments.
489          */
490         barrier();
491
492         node->locked = 0;
493         node->next = NULL;
494         pv_init_node(node);
495
496         /*
497          * We touched a (possibly) cold cacheline in the per-cpu queue node;
498          * attempt the trylock once more in the hope someone let go while we
499          * weren't watching.
500          */
501         if (queued_spin_trylock(lock))
502                 goto release;
503
504         /*
505          * We have already touched the queueing cacheline; don't bother with
506          * pending stuff.
507          *
508          * p,*,* -> n,*,*
509          *
510          * RELEASE, such that the stores to @node must be complete.
511          */
512         old = xchg_tail(lock, tail);
513         next = NULL;
514
515         /*
516          * if there was a previous node; link it and wait until reaching the
517          * head of the waitqueue.
518          */
519         if (old & _Q_TAIL_MASK) {
520                 prev = decode_tail(old);
521
522                 /*
523                  * We must ensure that the stores to @node are observed before
524                  * the write to prev->next. The address dependency from
525                  * xchg_tail is not sufficient to ensure this because the read
526                  * component of xchg_tail is unordered with respect to the
527                  * initialisation of @node.
528                  */
529                 smp_store_release(&prev->next, node);
530
531                 pv_wait_node(node, prev);
532                 arch_mcs_spin_lock_contended(&node->locked);
533
534                 /*
535                  * While waiting for the MCS lock, the next pointer may have
536                  * been set by another lock waiter. We optimistically load
537                  * the next pointer & prefetch the cacheline for writing
538                  * to reduce latency in the upcoming MCS unlock operation.
539                  */
540                 next = READ_ONCE(node->next);
541                 if (next)
542                         prefetchw(next);
543         }
544
545         /*
546          * we're at the head of the waitqueue, wait for the owner & pending to
547          * go away.
548          *
549          * *,x,y -> *,0,0
550          *
551          * this wait loop must use a load-acquire such that we match the
552          * store-release that clears the locked bit and create lock
553          * sequentiality; this is because the set_locked() function below
554          * does not imply a full barrier.
555          *
556          * The PV pv_wait_head_or_lock function, if active, will acquire
557          * the lock and return a non-zero value. So we have to skip the
558          * smp_cond_load_acquire() call. As the next PV queue head hasn't been
559          * designated yet, there is no way for the locked value to become
560          * _Q_SLOW_VAL. So both the set_locked() and the
561          * atomic_cmpxchg_relaxed() calls will be safe.
562          *
563          * If PV isn't active, 0 will be returned instead.
564          *
565          */
566         if ((val = pv_wait_head_or_lock(lock, node)))
567                 goto locked;
568
569         val = smp_cond_load_acquire(&lock->val.counter, !(VAL & _Q_LOCKED_PENDING_MASK));
570
571 locked:
572         /*
573          * claim the lock:
574          *
575          * n,0,0 -> 0,0,1 : lock, uncontended
576          * *,*,0 -> *,*,1 : lock, contended
577          *
578          * If the queue head is the only one in the queue (lock value == tail)
579          * and nobody is pending, clear the tail code and grab the lock.
580          * Otherwise, we only need to grab the lock.
581          */
582
583         /* In the PV case we might already have _Q_LOCKED_VAL set */
584         if ((val & _Q_TAIL_MASK) == tail) {
585                 /*
586                  * The smp_cond_load_acquire() call above has provided the
587                  * necessary acquire semantics required for locking.
588                  */
589                 old = atomic_cmpxchg_relaxed(&lock->val, val, _Q_LOCKED_VAL);
590                 if (old == val)
591                         goto release; /* No contention */
592         }
593
594         /* Either somebody is queued behind us or _Q_PENDING_VAL is set */
595         set_locked(lock);
596
597         /*
598          * contended path; wait for next if not observed yet, release.
599          */
600         if (!next) {
601                 while (!(next = READ_ONCE(node->next)))
602                         cpu_relax();
603         }
604
605         arch_mcs_spin_unlock_contended(&next->locked);
606         pv_kick_node(lock, next);
607
608 release:
609         /*
610          * release the node
611          */
612         __this_cpu_dec(mcs_nodes[0].count);
613 }
614 EXPORT_SYMBOL(queued_spin_lock_slowpath);
615
616 /*
617  * Generate the paravirt code for queued_spin_unlock_slowpath().
618  */
619 #if !defined(_GEN_PV_LOCK_SLOWPATH) && defined(CONFIG_PARAVIRT_SPINLOCKS)
620 #define _GEN_PV_LOCK_SLOWPATH
621
622 #undef  pv_enabled
623 #define pv_enabled()    true
624
625 #undef pv_init_node
626 #undef pv_wait_node
627 #undef pv_kick_node
628 #undef pv_wait_head_or_lock
629
630 #undef  queued_spin_lock_slowpath
631 #define queued_spin_lock_slowpath       __pv_queued_spin_lock_slowpath
632
633 #include "qspinlock_paravirt.h"
634 #include "qspinlock.c"
635
636 #endif