locking/qspinlock: Optimize for smaller NR_CPUS
[linux-2.6-block.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  *
18  * Authors: Waiman Long <waiman.long@hp.com>
19  *          Peter Zijlstra <peterz@infradead.org>
20  */
21 #include <linux/smp.h>
22 #include <linux/bug.h>
23 #include <linux/cpumask.h>
24 #include <linux/percpu.h>
25 #include <linux/hardirq.h>
26 #include <linux/mutex.h>
27 #include <asm/byteorder.h>
28 #include <asm/qspinlock.h>
29
30 /*
31  * The basic principle of a queue-based spinlock can best be understood
32  * by studying a classic queue-based spinlock implementation called the
33  * MCS lock. The paper below provides a good description for this kind
34  * of lock.
35  *
36  * http://www.cise.ufl.edu/tr/DOC/REP-1992-71.pdf
37  *
38  * This queued spinlock implementation is based on the MCS lock, however to make
39  * it fit the 4 bytes we assume spinlock_t to be, and preserve its existing
40  * API, we must modify it somehow.
41  *
42  * In particular; where the traditional MCS lock consists of a tail pointer
43  * (8 bytes) and needs the next pointer (another 8 bytes) of its own node to
44  * unlock the next pending (next->locked), we compress both these: {tail,
45  * next->locked} into a single u32 value.
46  *
47  * Since a spinlock disables recursion of its own context and there is a limit
48  * to the contexts that can nest; namely: task, softirq, hardirq, nmi. As there
49  * are at most 4 nesting levels, it can be encoded by a 2-bit number. Now
50  * we can encode the tail by combining the 2-bit nesting level with the cpu
51  * number. With one byte for the lock value and 3 bytes for the tail, only a
52  * 32-bit word is now needed. Even though we only need 1 bit for the lock,
53  * we extend it to a full byte to achieve better performance for architectures
54  * that support atomic byte write.
55  *
56  * We also change the first spinner to spin on the lock bit instead of its
57  * node; whereby avoiding the need to carry a node from lock to unlock, and
58  * preserving existing lock API. This also makes the unlock code simpler and
59  * faster.
60  *
61  * N.B. The current implementation only supports architectures that allow
62  *      atomic operations on smaller 8-bit and 16-bit data types.
63  *
64  */
65
66 #include "mcs_spinlock.h"
67
68 /*
69  * Per-CPU queue node structures; we can never have more than 4 nested
70  * contexts: task, softirq, hardirq, nmi.
71  *
72  * Exactly fits one 64-byte cacheline on a 64-bit architecture.
73  */
74 static DEFINE_PER_CPU_ALIGNED(struct mcs_spinlock, mcs_nodes[4]);
75
76 /*
77  * We must be able to distinguish between no-tail and the tail at 0:0,
78  * therefore increment the cpu number by one.
79  */
80
81 static inline u32 encode_tail(int cpu, int idx)
82 {
83         u32 tail;
84
85 #ifdef CONFIG_DEBUG_SPINLOCK
86         BUG_ON(idx > 3);
87 #endif
88         tail  = (cpu + 1) << _Q_TAIL_CPU_OFFSET;
89         tail |= idx << _Q_TAIL_IDX_OFFSET; /* assume < 4 */
90
91         return tail;
92 }
93
94 static inline struct mcs_spinlock *decode_tail(u32 tail)
95 {
96         int cpu = (tail >> _Q_TAIL_CPU_OFFSET) - 1;
97         int idx = (tail &  _Q_TAIL_IDX_MASK) >> _Q_TAIL_IDX_OFFSET;
98
99         return per_cpu_ptr(&mcs_nodes[idx], cpu);
100 }
101
102 #define _Q_LOCKED_PENDING_MASK (_Q_LOCKED_MASK | _Q_PENDING_MASK)
103
104 /*
105  * By using the whole 2nd least significant byte for the pending bit, we
106  * can allow better optimization of the lock acquisition for the pending
107  * bit holder.
108  */
109 #if _Q_PENDING_BITS == 8
110
111 struct __qspinlock {
112         union {
113                 atomic_t val;
114                 struct {
115 #ifdef __LITTLE_ENDIAN
116                         u16     locked_pending;
117                         u16     tail;
118 #else
119                         u16     tail;
120                         u16     locked_pending;
121 #endif
122                 };
123         };
124 };
125
126 /**
127  * clear_pending_set_locked - take ownership and clear the pending bit.
128  * @lock: Pointer to queued spinlock structure
129  *
130  * *,1,0 -> *,0,1
131  *
132  * Lock stealing is not allowed if this function is used.
133  */
134 static __always_inline void clear_pending_set_locked(struct qspinlock *lock)
135 {
136         struct __qspinlock *l = (void *)lock;
137
138         WRITE_ONCE(l->locked_pending, _Q_LOCKED_VAL);
139 }
140
141 /*
142  * xchg_tail - Put in the new queue tail code word & retrieve previous one
143  * @lock : Pointer to queued spinlock structure
144  * @tail : The new queue tail code word
145  * Return: The previous queue tail code word
146  *
147  * xchg(lock, tail)
148  *
149  * p,*,* -> n,*,* ; prev = xchg(lock, node)
150  */
151 static __always_inline u32 xchg_tail(struct qspinlock *lock, u32 tail)
152 {
153         struct __qspinlock *l = (void *)lock;
154
155         return (u32)xchg(&l->tail, tail >> _Q_TAIL_OFFSET) << _Q_TAIL_OFFSET;
156 }
157
158 #else /* _Q_PENDING_BITS == 8 */
159
160 /**
161  * clear_pending_set_locked - take ownership and clear the pending bit.
162  * @lock: Pointer to queued spinlock structure
163  *
164  * *,1,0 -> *,0,1
165  */
166 static __always_inline void clear_pending_set_locked(struct qspinlock *lock)
167 {
168         atomic_add(-_Q_PENDING_VAL + _Q_LOCKED_VAL, &lock->val);
169 }
170
171 /**
172  * xchg_tail - Put in the new queue tail code word & retrieve previous one
173  * @lock : Pointer to queued spinlock structure
174  * @tail : The new queue tail code word
175  * Return: The previous queue tail code word
176  *
177  * xchg(lock, tail)
178  *
179  * p,*,* -> n,*,* ; prev = xchg(lock, node)
180  */
181 static __always_inline u32 xchg_tail(struct qspinlock *lock, u32 tail)
182 {
183         u32 old, new, val = atomic_read(&lock->val);
184
185         for (;;) {
186                 new = (val & _Q_LOCKED_PENDING_MASK) | tail;
187                 old = atomic_cmpxchg(&lock->val, val, new);
188                 if (old == val)
189                         break;
190
191                 val = old;
192         }
193         return old;
194 }
195 #endif /* _Q_PENDING_BITS == 8 */
196
197 /**
198  * queued_spin_lock_slowpath - acquire the queued spinlock
199  * @lock: Pointer to queued spinlock structure
200  * @val: Current value of the queued spinlock 32-bit word
201  *
202  * (queue tail, pending bit, lock value)
203  *
204  *              fast     :    slow                                  :    unlock
205  *                       :                                          :
206  * uncontended  (0,0,0) -:--> (0,0,1) ------------------------------:--> (*,*,0)
207  *                       :       | ^--------.------.             /  :
208  *                       :       v           \      \            |  :
209  * pending               :    (0,1,1) +--> (0,1,0)   \           |  :
210  *                       :       | ^--'              |           |  :
211  *                       :       v                   |           |  :
212  * uncontended           :    (n,x,y) +--> (n,0,0) --'           |  :
213  *   queue               :       | ^--'                          |  :
214  *                       :       v                               |  :
215  * contended             :    (*,x,y) +--> (*,0,0) ---> (*,0,1) -'  :
216  *   queue               :         ^--'                             :
217  */
218 void queued_spin_lock_slowpath(struct qspinlock *lock, u32 val)
219 {
220         struct mcs_spinlock *prev, *next, *node;
221         u32 new, old, tail;
222         int idx;
223
224         BUILD_BUG_ON(CONFIG_NR_CPUS >= (1U << _Q_TAIL_CPU_BITS));
225
226         /*
227          * wait for in-progress pending->locked hand-overs
228          *
229          * 0,1,0 -> 0,0,1
230          */
231         if (val == _Q_PENDING_VAL) {
232                 while ((val = atomic_read(&lock->val)) == _Q_PENDING_VAL)
233                         cpu_relax();
234         }
235
236         /*
237          * trylock || pending
238          *
239          * 0,0,0 -> 0,0,1 ; trylock
240          * 0,0,1 -> 0,1,1 ; pending
241          */
242         for (;;) {
243                 /*
244                  * If we observe any contention; queue.
245                  */
246                 if (val & ~_Q_LOCKED_MASK)
247                         goto queue;
248
249                 new = _Q_LOCKED_VAL;
250                 if (val == new)
251                         new |= _Q_PENDING_VAL;
252
253                 old = atomic_cmpxchg(&lock->val, val, new);
254                 if (old == val)
255                         break;
256
257                 val = old;
258         }
259
260         /*
261          * we won the trylock
262          */
263         if (new == _Q_LOCKED_VAL)
264                 return;
265
266         /*
267          * we're pending, wait for the owner to go away.
268          *
269          * *,1,1 -> *,1,0
270          *
271          * this wait loop must be a load-acquire such that we match the
272          * store-release that clears the locked bit and create lock
273          * sequentiality; this is because not all clear_pending_set_locked()
274          * implementations imply full barriers.
275          */
276         while ((val = smp_load_acquire(&lock->val.counter)) & _Q_LOCKED_MASK)
277                 cpu_relax();
278
279         /*
280          * take ownership and clear the pending bit.
281          *
282          * *,1,0 -> *,0,1
283          */
284         clear_pending_set_locked(lock);
285         return;
286
287         /*
288          * End of pending bit optimistic spinning and beginning of MCS
289          * queuing.
290          */
291 queue:
292         node = this_cpu_ptr(&mcs_nodes[0]);
293         idx = node->count++;
294         tail = encode_tail(smp_processor_id(), idx);
295
296         node += idx;
297         node->locked = 0;
298         node->next = NULL;
299
300         /*
301          * We touched a (possibly) cold cacheline in the per-cpu queue node;
302          * attempt the trylock once more in the hope someone let go while we
303          * weren't watching.
304          */
305         if (queued_spin_trylock(lock))
306                 goto release;
307
308         /*
309          * We have already touched the queueing cacheline; don't bother with
310          * pending stuff.
311          *
312          * p,*,* -> n,*,*
313          */
314         old = xchg_tail(lock, tail);
315
316         /*
317          * if there was a previous node; link it and wait until reaching the
318          * head of the waitqueue.
319          */
320         if (old & _Q_TAIL_MASK) {
321                 prev = decode_tail(old);
322                 WRITE_ONCE(prev->next, node);
323
324                 arch_mcs_spin_lock_contended(&node->locked);
325         }
326
327         /*
328          * we're at the head of the waitqueue, wait for the owner & pending to
329          * go away.
330          *
331          * *,x,y -> *,0,0
332          */
333         while ((val = atomic_read(&lock->val)) & _Q_LOCKED_PENDING_MASK)
334                 cpu_relax();
335
336         /*
337          * claim the lock:
338          *
339          * n,0,0 -> 0,0,1 : lock, uncontended
340          * *,0,0 -> *,0,1 : lock, contended
341          */
342         for (;;) {
343                 new = _Q_LOCKED_VAL;
344                 if (val != tail)
345                         new |= val;
346
347                 old = atomic_cmpxchg(&lock->val, val, new);
348                 if (old == val)
349                         break;
350
351                 val = old;
352         }
353
354         /*
355          * contended path; wait for next, release.
356          */
357         if (new != _Q_LOCKED_VAL) {
358                 while (!(next = READ_ONCE(node->next)))
359                         cpu_relax();
360
361                 arch_mcs_spin_unlock_contended(&next->locked);
362         }
363
364 release:
365         /*
366          * release the node
367          */
368         this_cpu_dec(mcs_nodes[0].count);
369 }
370 EXPORT_SYMBOL(queued_spin_lock_slowpath);