2 * Copyright (c) 2005 Jeffrey M. Hsu. All rights reserved.
4 * This code is derived from software contributed to The DragonFly Project
5 * by Jeffrey M. Hsu. and Matthew Dillon
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
34 * The implementation is designed to avoid looping when compatible operations
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.
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.
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.
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>
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>
69 #ifdef _KERNEL_VIRTUAL
73 struct spinlock pmap_spin = SPINLOCK_INITIALIZER(pmap_spin, "pmap_spin");
75 struct indefinite_info {
84 #if !defined(KTR_SPIN_CONTENTION)
85 #define KTR_SPIN_CONTENTION KTR_ALL
87 #define SPIN_STRING "spin=%p type=%c"
88 #define SPIN_ARG_SIZE (sizeof(void *) + sizeof(int))
90 KTR_INFO_MASTER(spin);
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);
96 #define logspin(name, spin, type) \
97 KTR_LOG(spin_ ## name, spin, type)
100 static int spin_lock_test_mode;
103 #ifdef DEBUG_LOCKS_LATENCY
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");
112 static int spin_indefinite_check(struct spinlock *spin,
113 struct indefinite_info *info);
116 * We contested due to another exclusive lock holder. We lose.
118 * We have to unwind the attempt and may acquire the spinlock
119 * anyway while doing so.
122 spin_trylock_contested(struct spinlock *spin)
124 globaldata_t gd = mycpu;
127 * Handle degenerate case, else fail.
129 if (atomic_cmpset_int(&spin->counta, SPINLOCK_SHARED|0, 1))
131 /*atomic_add_int(&spin->counta, -1);*/
133 crit_exit_raw(gd->gd_curthread);
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).
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.
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.
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.
157 * Backoff algorithms can create even worse starvation problems, and don't
158 * really improve performance when a lot of cores are contending.
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.
166 * WARNING!!!! Performance matters here, by a huge margin.
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.
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.
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).
179 _spin_lock_contested(struct spinlock *spin, const char *ident, int value)
181 struct indefinite_info info = { 0, 0, ident };
185 * WARNING! Caller has already incremented the lock. We must
186 * increment the count value (from the inline's fetch-add)
189 * Handle the degenerate case where the spinlock is flagged SHARED
190 * with only our reference. We can convert it to EXCLUSIVE.
193 if (value == (SPINLOCK_SHARED | 1)) {
194 if (atomic_cmpset_int(&spin->counta, SPINLOCK_SHARED | 1, 1))
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.
205 * Don't tread on earlier exclusive waiters by stealing the lock
206 * away early if the low bits happen to now be 1.
208 * The shared unlock understands that this may occur.
210 atomic_add_int(&spin->counta, SPINLOCK_EXCLWAIT - 1);
211 if (value & SPINLOCK_SHARED)
212 atomic_clear_int(&spin->counta, SPINLOCK_SHARED);
214 #ifdef DEBUG_LOCKS_LATENCY
216 for (j = spinlocks_add_latency; j > 0; --j)
220 * Spin until we can acquire a low-count of 1.
223 /*logspin(beg, spin, 'w');*/
226 * If the low bits are zero, try to acquire the exclusive lock
227 * by transfering our high bit reservation to the low bits.
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.
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.
239 uint32_t ovalue = spin->counta;
241 if ((ovalue & (SPINLOCK_EXCLWAIT - 1)) == 0 &&
242 atomic_cmpset_int(&spin->counta, ovalue,
243 (ovalue - SPINLOCK_EXCLWAIT) | 1)) {
246 if ((++i & 0x7F) == 0x7F) {
247 mycpu->gd_cnt.v_lock_name[0] = 'X';
248 strncpy(mycpu->gd_cnt.v_lock_name + 1,
250 sizeof(mycpu->gd_cnt.v_lock_name) - 2);
251 ++mycpu->gd_cnt.v_lock_colls;
252 if (spin_indefinite_check(spin, &info))
255 #ifdef _KERNEL_VIRTUAL
259 /*logspin(end, spin, 'w');*/
263 * The spin_lock_shared() inline was unable to acquire the lock and calls
264 * this function with spin->counta already incremented.
266 * This is not in the critical path unless there is contention between
267 * shared and exclusive holders.
270 _spin_lock_shared_contested(struct spinlock *spin, const char *ident)
272 struct indefinite_info info = { 0, 0, ident };
276 * Undo the inline's increment.
278 atomic_add_int(&spin->counta, -1);
280 #ifdef DEBUG_LOCKS_LATENCY
282 for (j = spinlocks_add_latency; j > 0; --j)
286 /*logspin(beg, spin, 'w');*/
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
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.
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.
306 uint32_t ovalue = spin->counta;
310 if (atomic_cmpset_int(&spin->counta, 0,
311 SPINLOCK_SHARED | 1))
313 } else if (ovalue & SPINLOCK_SHARED) {
314 if (atomic_cmpset_int(&spin->counta, ovalue,
318 if ((++i & 0x7F) == 0x7F) {
319 mycpu->gd_cnt.v_lock_name[0] = 'S';
320 strncpy(mycpu->gd_cnt.v_lock_name + 1,
322 sizeof(mycpu->gd_cnt.v_lock_name) - 2);
323 ++mycpu->gd_cnt.v_lock_colls;
324 if (spin_indefinite_check(spin, &info))
327 #ifdef _KERNEL_VIRTUAL
331 /*logspin(end, spin, 'w');*/
336 spin_indefinite_check(struct spinlock *spin, struct indefinite_info *info)
340 cpu_spinlock_contested();
342 count = sys_cputimer->count();
343 if (info->secs == 0) {
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);
353 #if defined(INVARIANTS)
354 if (spin_lock_test_mode) {
359 #if defined(INVARIANTS)
360 if (info->secs == 11)
363 if (info->secs == 60)
364 panic("spin_lock: %s(%p), indefinite wait!",
371 * If INVARIANTS is enabled various spinlock timing tests can be run
372 * by setting debug.spin_lock_test:
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)
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");
386 sysctl_spin_lock_test(SYSCTL_HANDLER_ARGS)
388 struct spinlock spin;
393 if ((error = priv_check(curthread, PRIV_ROOT)) != 0)
395 if ((error = SYSCTL_IN(req, &value, sizeof(value))) != 0)
399 * Indefinite wait test
402 spin_init(&spin, "sysctllock");
403 spin_lock(&spin); /* force an indefinite wait */
404 spin_lock_test_mode = 1;
406 spin_unlock(&spin); /* Clean up the spinlock count */
408 spin_lock_test_mode = 0;
412 * Time best-case exclusive spinlocks
415 globaldata_t gd = mycpu;
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);
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");
430 #endif /* INVARIANTS */