kernel - Fix GCC reordering problem with td_critcount
[dragonfly.git] / sys / kern / kern_spinlock.c
1 /*
2  * Copyright (c) 2005 Jeffrey M. Hsu.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Jeffrey M. Hsu. and Matthew Dillon
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of The DragonFly Project nor the names of its
16  *    contributors may be used to endorse or promote products derived
17  *    from this software without specific, prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
22  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
23  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
25  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
27  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
29  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 /*
34  * The implementation is designed to avoid looping when compatible operations
35  * are executed.
36  *
37  * To acquire a spinlock we first increment counta.  Then we check if counta
38  * meets our requirements.  For an exclusive spinlock it must be 1, of a
39  * shared spinlock it must either be 1 or the SHARED_SPINLOCK bit must be set.
40  *
41  * Shared spinlock failure case: Decrement the count, loop until we can
42  * transition from 0 to SHARED_SPINLOCK|1, or until we find SHARED_SPINLOCK
43  * is set and increment the count.
44  *
45  * Exclusive spinlock failure case: While maintaining the count, clear the
46  * SHARED_SPINLOCK flag unconditionally.  Then use an atomic add to transfer
47  * the count from the low bits to the high bits of counta.  Then loop until
48  * all low bits are 0.  Once the low bits drop to 0 we can transfer the
49  * count back with an atomic_cmpset_int(), atomically, and return.
50  */
51 #include <sys/param.h>
52 #include <sys/systm.h>
53 #include <sys/types.h>
54 #include <sys/kernel.h>
55 #include <sys/sysctl.h>
56 #ifdef INVARIANTS
57 #include <sys/proc.h>
58 #endif
59 #include <sys/priv.h>
60 #include <machine/atomic.h>
61 #include <machine/cpu.h>
62 #include <machine/cpufunc.h>
63 #include <machine/specialreg.h>
64 #include <machine/clock.h>
65 #include <sys/spinlock.h>
66 #include <sys/spinlock2.h>
67 #include <sys/ktr.h>
68
69 #ifdef _KERNEL_VIRTUAL
70 #include <pthread.h>
71 #endif
72
73 struct spinlock pmap_spin = SPINLOCK_INITIALIZER(pmap_spin, "pmap_spin");
74
75 struct indefinite_info {
76         sysclock_t      base;
77         int             secs;
78         const char      *ident;
79 };
80
81 /*
82  * Kernal Trace
83  */
84 #if !defined(KTR_SPIN_CONTENTION)
85 #define KTR_SPIN_CONTENTION     KTR_ALL
86 #endif
87 #define SPIN_STRING     "spin=%p type=%c"
88 #define SPIN_ARG_SIZE   (sizeof(void *) + sizeof(int))
89
90 KTR_INFO_MASTER(spin);
91 #if 0
92 KTR_INFO(KTR_SPIN_CONTENTION, spin, beg, 0, SPIN_STRING, SPIN_ARG_SIZE);
93 KTR_INFO(KTR_SPIN_CONTENTION, spin, end, 1, SPIN_STRING, SPIN_ARG_SIZE);
94 #endif
95
96 #define logspin(name, spin, type)                       \
97         KTR_LOG(spin_ ## name, spin, type)
98
99 #ifdef INVARIANTS
100 static int spin_lock_test_mode;
101 #endif
102
103 #ifdef DEBUG_LOCKS_LATENCY
104
105 static long spinlocks_add_latency;
106 SYSCTL_LONG(_debug, OID_AUTO, spinlocks_add_latency, CTLFLAG_RW,
107     &spinlocks_add_latency, 0,
108     "Add spinlock latency");
109
110 #endif
111
112 static int spin_indefinite_check(struct spinlock *spin,
113                                   struct indefinite_info *info);
114
115 /*
116  * We contested due to another exclusive lock holder.  We lose.
117  *
118  * We have to unwind the attempt and may acquire the spinlock
119  * anyway while doing so.
120  */
121 int
122 spin_trylock_contested(struct spinlock *spin)
123 {
124         globaldata_t gd = mycpu;
125
126         /*
127          * Handle degenerate case, else fail.
128          */
129         if (atomic_cmpset_int(&spin->counta, SPINLOCK_SHARED|0, 1))
130                 return TRUE;
131         /*atomic_add_int(&spin->counta, -1);*/
132         --gd->gd_spinlocks;
133         crit_exit_raw(gd->gd_curthread);
134
135         return (FALSE);
136 }
137
138 /*
139  * The spin_lock() inline was unable to acquire the lock and calls this
140  * function with spin->counta already incremented, passing (spin->counta - 1)
141  * to the function (the result of the inline's fetchadd).
142  *
143  * atomic_swap_int() is the absolute fastest spinlock instruction, at
144  * least on multi-socket systems.  All instructions seem to be about
145  * the same on single-socket multi-core systems.  However, atomic_swap_int()
146  * does not result in an even distribution of successful acquisitions.
147  *
148  * UNFORTUNATELY we cannot really use atomic_swap_int() when also implementing
149  * shared spin locks, so as we do a better job removing contention we've
150  * moved to atomic_cmpset_int() to be able handle multiple states.
151  *
152  * Another problem we have is that (at least on the 48-core opteron we test
153  * with) having all 48 cores contesting the same spin lock reduces
154  * performance to around 600,000 ops/sec, verses millions when fewer cores
155  * are going after the same lock.
156  *
157  * Backoff algorithms can create even worse starvation problems, and don't
158  * really improve performance when a lot of cores are contending.
159  *
160  * Our solution is to allow the data cache to lazy-update by reading it
161  * non-atomically and only attempting to acquire the lock if the lazy read
162  * looks good.  This effectively limits cache bus bandwidth.  A cpu_pause()
163  * (for intel/amd anyhow) is not strictly needed as cache bus resource use
164  * is governed by the lazy update.
165  *
166  * WARNING!!!!  Performance matters here, by a huge margin.
167  *
168  *      48-core test with pre-read / -j 48 no-modules kernel compile
169  *      with fanned-out inactive and active queues came in at 55 seconds.
170  *
171  *      48-core test with pre-read / -j 48 no-modules kernel compile
172  *      came in at 75 seconds.  Without pre-read it came in at 170 seconds.
173  *
174  *      4-core test with pre-read / -j 48 no-modules kernel compile
175  *      came in at 83 seconds.  Without pre-read it came in at 83 seconds
176  *      as well (no difference).
177  */
178 void
179 _spin_lock_contested(struct spinlock *spin, const char *ident, int value)
180 {
181         struct indefinite_info info = { 0, 0, ident };
182         int i;
183
184         /*
185          * WARNING! Caller has already incremented the lock.  We must
186          *          increment the count value (from the inline's fetch-add)
187          *          to match.
188          *
189          * Handle the degenerate case where the spinlock is flagged SHARED
190          * with only our reference.  We can convert it to EXCLUSIVE.
191          */
192         ++value;
193         if (value == (SPINLOCK_SHARED | 1)) {
194                 if (atomic_cmpset_int(&spin->counta, SPINLOCK_SHARED | 1, 1))
195                         return;
196         }
197
198         /*
199          * Transfer our exclusive request to the high bits and clear the
200          * SPINLOCK_SHARED bit if it was set.  This makes the spinlock
201          * appear exclusive, preventing any NEW shared or exclusive
202          * spinlocks from being obtained while we wait for existing
203          * shared or exclusive holders to unlock.
204          *
205          * Don't tread on earlier exclusive waiters by stealing the lock
206          * away early if the low bits happen to now be 1.
207          *
208          * The shared unlock understands that this may occur.
209          */
210         atomic_add_int(&spin->counta, SPINLOCK_EXCLWAIT - 1);
211         if (value & SPINLOCK_SHARED)
212                 atomic_clear_int(&spin->counta, SPINLOCK_SHARED);
213
214 #ifdef DEBUG_LOCKS_LATENCY
215         long j;
216         for (j = spinlocks_add_latency; j > 0; --j)
217                 cpu_ccfence();
218 #endif
219         /*
220          * Spin until we can acquire a low-count of 1.
221          */
222         i = 0;
223         /*logspin(beg, spin, 'w');*/
224         for (;;) {
225                 /*
226                  * If the low bits are zero, try to acquire the exclusive lock
227                  * by transfering our high bit reservation to the low bits.
228                  *
229                  * NOTE: Reading spin->counta prior to the swap is extremely
230                  *       important on multi-chip/many-core boxes.  On 48-core
231                  *       this one change improves fully concurrent all-cores
232                  *       compiles by 100% or better.
233                  *
234                  *       I can't emphasize enough how important the pre-read
235                  *       is in preventing hw cache bus armageddon on
236                  *       multi-chip systems.  And on single-chip/multi-core
237                  *       systems it just doesn't hurt.
238                  */
239                 uint32_t ovalue = spin->counta;
240                 cpu_ccfence();
241                 if ((ovalue & (SPINLOCK_EXCLWAIT - 1)) == 0 &&
242                     atomic_cmpset_int(&spin->counta, ovalue,
243                                       (ovalue - SPINLOCK_EXCLWAIT) | 1)) {
244                         break;
245                 }
246                 if ((++i & 0x7F) == 0x7F) {
247                         mycpu->gd_cnt.v_lock_name[0] = 'X';
248                         strncpy(mycpu->gd_cnt.v_lock_name + 1,
249                                 ident,
250                                 sizeof(mycpu->gd_cnt.v_lock_name) - 2);
251                         ++mycpu->gd_cnt.v_lock_colls;
252                         if (spin_indefinite_check(spin, &info))
253                                 break;
254                 }
255 #ifdef _KERNEL_VIRTUAL
256                 pthread_yield();
257 #endif
258         }
259         /*logspin(end, spin, 'w');*/
260 }
261
262 /*
263  * The spin_lock_shared() inline was unable to acquire the lock and calls
264  * this function with spin->counta already incremented.
265  *
266  * This is not in the critical path unless there is contention between
267  * shared and exclusive holders.
268  */
269 void
270 _spin_lock_shared_contested(struct spinlock *spin, const char *ident)
271 {
272         struct indefinite_info info = { 0, 0, ident };
273         int i;
274
275         /*
276          * Undo the inline's increment.
277          */
278         atomic_add_int(&spin->counta, -1);
279
280 #ifdef DEBUG_LOCKS_LATENCY
281         long j;
282         for (j = spinlocks_add_latency; j > 0; --j)
283                 cpu_ccfence();
284 #endif
285
286         /*logspin(beg, spin, 'w');*/
287         i = 0;
288         for (;;) {
289                 /*
290                  * Loop until we can acquire the shared spinlock.  Note that
291                  * the low bits can be zero while the high EXCLWAIT bits are
292                  * non-zero.  In this situation exclusive requesters have
293                  * priority (otherwise shared users on multiple cpus can hog
294                  * the spinlnock).
295                  *
296                  * NOTE: Reading spin->counta prior to the swap is extremely
297                  *       important on multi-chip/many-core boxes.  On 48-core
298                  *       this one change improves fully concurrent all-cores
299                  *       compiles by 100% or better.
300                  *
301                  *       I can't emphasize enough how important the pre-read
302                  *       is in preventing hw cache bus armageddon on
303                  *       multi-chip systems.  And on single-chip/multi-core
304                  *       systems it just doesn't hurt.
305                  */
306                 uint32_t ovalue = spin->counta;
307
308                 cpu_ccfence();
309                 if (ovalue == 0) {
310                         if (atomic_cmpset_int(&spin->counta, 0,
311                                               SPINLOCK_SHARED | 1))
312                                 break;
313                 } else if (ovalue & SPINLOCK_SHARED) {
314                         if (atomic_cmpset_int(&spin->counta, ovalue,
315                                               ovalue + 1))
316                                 break;
317                 }
318                 if ((++i & 0x7F) == 0x7F) {
319                         mycpu->gd_cnt.v_lock_name[0] = 'S';
320                         strncpy(mycpu->gd_cnt.v_lock_name + 1,
321                                 ident,
322                                 sizeof(mycpu->gd_cnt.v_lock_name) - 2);
323                         ++mycpu->gd_cnt.v_lock_colls;
324                         if (spin_indefinite_check(spin, &info))
325                                 break;
326                 }
327 #ifdef _KERNEL_VIRTUAL
328                 pthread_yield();
329 #endif
330         }
331         /*logspin(end, spin, 'w');*/
332 }
333
334 static
335 int
336 spin_indefinite_check(struct spinlock *spin, struct indefinite_info *info)
337 {
338         sysclock_t count;
339
340         cpu_spinlock_contested();
341
342         count = sys_cputimer->count();
343         if (info->secs == 0) {
344                 info->base = count;
345                 ++info->secs;
346         } else if (count - info->base > sys_cputimer->freq) {
347                 kprintf("spin_lock: %s(%p), indefinite wait (%d secs)!\n",
348                         info->ident, spin, info->secs);
349                 info->base = count;
350                 ++info->secs;
351                 if (panicstr)
352                         return (TRUE);
353 #if defined(INVARIANTS)
354                 if (spin_lock_test_mode) {
355                         print_backtrace(-1);
356                         return (TRUE);
357                 }
358 #endif
359 #if defined(INVARIANTS)
360                 if (info->secs == 11)
361                         print_backtrace(-1);
362 #endif
363                 if (info->secs == 60)
364                         panic("spin_lock: %s(%p), indefinite wait!",
365                               info->ident, spin);
366         }
367         return (FALSE);
368 }
369
370 /*
371  * If INVARIANTS is enabled various spinlock timing tests can be run
372  * by setting debug.spin_lock_test:
373  *
374  *      1       Test the indefinite wait code
375  *      2       Time the best-case exclusive lock overhead (spin_test_count)
376  *      3       Time the best-case shared lock overhead (spin_test_count)
377  */
378
379 #ifdef INVARIANTS
380
381 static int spin_test_count = 10000000;
382 SYSCTL_INT(_debug, OID_AUTO, spin_test_count, CTLFLAG_RW, &spin_test_count, 0,
383     "Number of iterations to use for spinlock wait code test");
384
385 static int
386 sysctl_spin_lock_test(SYSCTL_HANDLER_ARGS)
387 {
388         struct spinlock spin;
389         int error;
390         int value = 0;
391         int i;
392
393         if ((error = priv_check(curthread, PRIV_ROOT)) != 0)
394                 return (error);
395         if ((error = SYSCTL_IN(req, &value, sizeof(value))) != 0)
396                 return (error);
397
398         /*
399          * Indefinite wait test
400          */
401         if (value == 1) {
402                 spin_init(&spin, "sysctllock");
403                 spin_lock(&spin);       /* force an indefinite wait */
404                 spin_lock_test_mode = 1;
405                 spin_lock(&spin);
406                 spin_unlock(&spin);     /* Clean up the spinlock count */
407                 spin_unlock(&spin);
408                 spin_lock_test_mode = 0;
409         }
410
411         /*
412          * Time best-case exclusive spinlocks
413          */
414         if (value == 2) {
415                 globaldata_t gd = mycpu;
416
417                 spin_init(&spin, "sysctllocktest");
418                 for (i = spin_test_count; i > 0; --i) {
419                     _spin_lock_quick(gd, &spin, "test");
420                     spin_unlock_quick(gd, &spin);
421                 }
422         }
423
424         return (0);
425 }
426
427 SYSCTL_PROC(_debug, KERN_PROC_ALL, spin_lock_test, CTLFLAG_RW|CTLTYPE_INT,
428         0, 0, sysctl_spin_lock_test, "I", "Test spinlock wait code");
429
430 #endif  /* INVARIANTS */