xref: /dragonfly/sys/kern/kern_spinlock.c (revision d4ef6694)
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 
113 /*
114  * We need a fairly large pool to avoid contention on large SMP systems,
115  * particularly multi-chip systems.
116  */
117 /*#define SPINLOCK_NUM_POOL	8101*/
118 #define SPINLOCK_NUM_POOL	8192
119 #define SPINLOCK_NUM_POOL_MASK	(SPINLOCK_NUM_POOL - 1)
120 
121 static __cachealign struct {
122 	struct spinlock	spin;
123 	char filler[32 - sizeof(struct spinlock)];
124 } pool_spinlocks[SPINLOCK_NUM_POOL];
125 
126 static int spin_indefinite_check(struct spinlock *spin,
127 				  struct indefinite_info *info);
128 
129 /*
130  * We contested due to another exclusive lock holder.  We lose.
131  *
132  * We have to unwind the attempt and may acquire the spinlock
133  * anyway while doing so.  countb was incremented on our behalf.
134  */
135 int
136 spin_trylock_contested(struct spinlock *spin)
137 {
138 	globaldata_t gd = mycpu;
139 
140 	/*atomic_add_int(&spin->counta, -1);*/
141 	--gd->gd_spinlocks;
142 	--gd->gd_curthread->td_critcount;
143 	return (FALSE);
144 }
145 
146 /*
147  * The spin_lock() inline was unable to acquire the lock.
148  *
149  * atomic_swap_int() is the absolute fastest spinlock instruction, at
150  * least on multi-socket systems.  All instructions seem to be about
151  * the same on single-socket multi-core systems.  However, atomic_swap_int()
152  * does not result in an even distribution of successful acquisitions.
153  *
154  * UNFORTUNATELY we cannot really use atomic_swap_int() when also implementing
155  * shared spin locks, so as we do a better job removing contention we've
156  * moved to atomic_cmpset_int() to be able handle multiple states.
157  *
158  * Another problem we have is that (at least on the 48-core opteron we test
159  * with) having all 48 cores contesting the same spin lock reduces
160  * performance to around 600,000 ops/sec, verses millions when fewer cores
161  * are going after the same lock.
162  *
163  * Backoff algorithms can create even worse starvation problems, and don't
164  * really improve performance when a lot of cores are contending.
165  *
166  * Our solution is to allow the data cache to lazy-update by reading it
167  * non-atomically and only attempting to acquire the lock if the lazy read
168  * looks good.  This effectively limits cache bus bandwidth.  A cpu_pause()
169  * (for intel/amd anyhow) is not strictly needed as cache bus resource use
170  * is governed by the lazy update.
171  *
172  * WARNING!!!!  Performance matters here, by a huge margin.
173  *
174  *	48-core test with pre-read / -j 48 no-modules kernel compile
175  *	with fanned-out inactive and active queues came in at 55 seconds.
176  *
177  *	48-core test with pre-read / -j 48 no-modules kernel compile
178  *	came in at 75 seconds.  Without pre-read it came in at 170 seconds.
179  *
180  *	4-core test with pre-read / -j 48 no-modules kernel compile
181  *	came in at 83 seconds.  Without pre-read it came in at 83 seconds
182  *	as well (no difference).
183  */
184 void
185 _spin_lock_contested(struct spinlock *spin, const char *ident)
186 {
187 	struct indefinite_info info = { 0, 0, ident };
188 	int i;
189 
190 	/*
191 	 * Transfer our count to the high bits, then loop until we can
192 	 * acquire the low counter (== 1).  No new shared lock can be
193 	 * acquired while we hold the EXCLWAIT bits.
194 	 *
195 	 * Force any existing shared locks to exclusive.  The shared unlock
196 	 * understands that this may occur.
197 	 */
198 	atomic_add_int(&spin->counta, SPINLOCK_EXCLWAIT - 1);
199 	atomic_clear_int(&spin->counta, SPINLOCK_SHARED);
200 
201 #ifdef DEBUG_LOCKS_LATENCY
202 	long j;
203 	for (j = spinlocks_add_latency; j > 0; --j)
204 		cpu_ccfence();
205 #endif
206 #if defined(INVARIANTS)
207 	if (spin_lock_test_mode > 10 &&
208 	    spin->countb > spin_lock_test_mode &&
209 	    (spin_lock_test_mode & 0xFF) == mycpu->gd_cpuid) {
210 		spin->countb = 0;
211 		print_backtrace(-1);
212 	}
213 	++spin->countb;
214 #endif
215 	i = 0;
216 
217 	/*logspin(beg, spin, 'w');*/
218 	for (;;) {
219 		/*
220 		 * If the low bits are zero, try to acquire the exclusive lock
221 		 * by transfering our high bit counter to the low bits.
222 		 *
223 		 * NOTE: Reading spin->counta prior to the swap is extremely
224 		 *	 important on multi-chip/many-core boxes.  On 48-core
225 		 *	 this one change improves fully concurrent all-cores
226 		 *	 compiles by 100% or better.
227 		 *
228 		 *	 I can't emphasize enough how important the pre-read
229 		 *	 is in preventing hw cache bus armageddon on
230 		 *	 multi-chip systems.  And on single-chip/multi-core
231 		 *	 systems it just doesn't hurt.
232 		 */
233 		uint32_t ovalue = spin->counta;
234 		cpu_ccfence();
235 		if ((ovalue & (SPINLOCK_EXCLWAIT - 1)) == 0 &&
236 		    atomic_cmpset_int(&spin->counta, ovalue,
237 				      (ovalue - SPINLOCK_EXCLWAIT) | 1)) {
238 			break;
239 		}
240 		if ((++i & 0x7F) == 0x7F) {
241 			mycpu->gd_cnt.v_lock_name[0] = 'X';
242 			strncpy(mycpu->gd_cnt.v_lock_name + 1,
243 				ident,
244 				sizeof(mycpu->gd_cnt.v_lock_name) - 2);
245 			++mycpu->gd_cnt.v_lock_colls;
246 #if defined(INVARIANTS)
247 			++spin->countb;
248 #endif
249 			if (spin_indefinite_check(spin, &info))
250 				break;
251 		}
252 #ifdef _KERNEL_VIRTUAL
253 		pthread_yield();
254 #endif
255 	}
256 	/*logspin(end, spin, 'w');*/
257 }
258 
259 /*
260  * Shared spinlock attempt was contested.
261  *
262  * The caller has not modified counta.
263  */
264 void
265 _spin_lock_shared_contested(struct spinlock *spin, const char *ident)
266 {
267 	struct indefinite_info info = { 0, 0, ident };
268 	int i;
269 
270 #ifdef DEBUG_LOCKS_LATENCY
271 	long j;
272 	for (j = spinlocks_add_latency; j > 0; --j)
273 		cpu_ccfence();
274 #endif
275 #if defined(INVARIANTS)
276 	if (spin_lock_test_mode > 10 &&
277 	    spin->countb > spin_lock_test_mode &&
278 	    (spin_lock_test_mode & 0xFF) == mycpu->gd_cpuid) {
279 		spin->countb = 0;
280 		print_backtrace(-1);
281 	}
282 	++spin->countb;
283 #endif
284 	i = 0;
285 
286 	/*logspin(beg, spin, 'w');*/
287 	for (;;) {
288 		/*
289 		 * Loop until we can acquire the shared spinlock.  Note that
290 		 * the low bits can be zero while the high EXCLWAIT bits are
291 		 * non-zero.  In this situation exclusive requesters have
292 		 * priority (otherwise shared users on multiple cpus can hog
293 		 * the spinlnock).
294 		 *
295 		 * NOTE: Reading spin->counta prior to the swap is extremely
296 		 *	 important on multi-chip/many-core boxes.  On 48-core
297 		 *	 this one change improves fully concurrent all-cores
298 		 *	 compiles by 100% or better.
299 		 *
300 		 *	 I can't emphasize enough how important the pre-read
301 		 *	 is in preventing hw cache bus armageddon on
302 		 *	 multi-chip systems.  And on single-chip/multi-core
303 		 *	 systems it just doesn't hurt.
304 		 */
305 		uint32_t ovalue = spin->counta;
306 
307 		cpu_ccfence();
308 		if (ovalue == 0) {
309 			if (atomic_cmpset_int(&spin->counta, 0,
310 					      SPINLOCK_SHARED | 1))
311 				break;
312 		} else if (ovalue & SPINLOCK_SHARED) {
313 			if (atomic_cmpset_int(&spin->counta, ovalue,
314 					      ovalue + 1))
315 				break;
316 		}
317 		if ((++i & 0x7F) == 0x7F) {
318 			mycpu->gd_cnt.v_lock_name[0] = 'S';
319 			strncpy(mycpu->gd_cnt.v_lock_name + 1,
320 				ident,
321 				sizeof(mycpu->gd_cnt.v_lock_name) - 2);
322 			++mycpu->gd_cnt.v_lock_colls;
323 #if defined(INVARIANTS)
324 			++spin->countb;
325 #endif
326 			if (spin_indefinite_check(spin, &info))
327 				break;
328 		}
329 #ifdef _KERNEL_VIRTUAL
330 		pthread_yield();
331 #endif
332 	}
333 	/*logspin(end, spin, 'w');*/
334 }
335 
336 /*
337  * Pool functions (SHARED SPINLOCKS NOT SUPPORTED)
338  */
339 static __inline int
340 _spin_pool_hash(void *ptr)
341 {
342 	int i;
343 
344 	i = ((int)(uintptr_t) ptr >> 5) ^ ((int)(uintptr_t)ptr >> 12);
345 	i &= SPINLOCK_NUM_POOL_MASK;
346 	return (i);
347 }
348 
349 void
350 _spin_pool_lock(void *chan, const char *ident)
351 {
352 	struct spinlock *sp;
353 
354 	sp = &pool_spinlocks[_spin_pool_hash(chan)].spin;
355 	_spin_lock(sp, ident);
356 }
357 
358 void
359 _spin_pool_unlock(void *chan)
360 {
361 	struct spinlock *sp;
362 
363 	sp = &pool_spinlocks[_spin_pool_hash(chan)].spin;
364 	spin_unlock(sp);
365 }
366 
367 
368 static
369 int
370 spin_indefinite_check(struct spinlock *spin, struct indefinite_info *info)
371 {
372 	sysclock_t count;
373 
374 	cpu_spinlock_contested();
375 
376 	count = sys_cputimer->count();
377 	if (info->secs == 0) {
378 		info->base = count;
379 		++info->secs;
380 	} else if (count - info->base > sys_cputimer->freq) {
381 		kprintf("spin_lock: %s(%p), indefinite wait (%d secs)!\n",
382 			info->ident, spin, info->secs);
383 		info->base = count;
384 		++info->secs;
385 		if (panicstr)
386 			return (TRUE);
387 #if defined(INVARIANTS)
388 		if (spin_lock_test_mode) {
389 			print_backtrace(-1);
390 			return (TRUE);
391 		}
392 #endif
393 #if defined(INVARIANTS)
394 		if (info->secs == 11)
395 			print_backtrace(-1);
396 #endif
397 		if (info->secs == 60)
398 			panic("spin_lock: %s(%p), indefinite wait!",
399 			      info->ident, spin);
400 	}
401 	return (FALSE);
402 }
403 
404 /*
405  * If INVARIANTS is enabled various spinlock timing tests can be run
406  * by setting debug.spin_lock_test:
407  *
408  *	1	Test the indefinite wait code
409  *	2	Time the best-case exclusive lock overhead (spin_test_count)
410  *	3	Time the best-case shared lock overhead (spin_test_count)
411  */
412 
413 #ifdef INVARIANTS
414 
415 static int spin_test_count = 10000000;
416 SYSCTL_INT(_debug, OID_AUTO, spin_test_count, CTLFLAG_RW, &spin_test_count, 0,
417     "Number of iterations to use for spinlock wait code test");
418 
419 static int
420 sysctl_spin_lock_test(SYSCTL_HANDLER_ARGS)
421 {
422         struct spinlock spin;
423 	int error;
424 	int value = 0;
425 	int i;
426 
427 	if ((error = priv_check(curthread, PRIV_ROOT)) != 0)
428 		return (error);
429 	if ((error = SYSCTL_IN(req, &value, sizeof(value))) != 0)
430 		return (error);
431 
432 	/*
433 	 * Indefinite wait test
434 	 */
435 	if (value == 1) {
436 		spin_init(&spin, "sysctllock");
437 		spin_lock(&spin);	/* force an indefinite wait */
438 		spin_lock_test_mode = 1;
439 		spin_lock(&spin);
440 		spin_unlock(&spin);	/* Clean up the spinlock count */
441 		spin_unlock(&spin);
442 		spin_lock_test_mode = 0;
443 	}
444 
445 	/*
446 	 * Time best-case exclusive spinlocks
447 	 */
448 	if (value == 2) {
449 		globaldata_t gd = mycpu;
450 
451 		spin_init(&spin, "sysctllocktest");
452 		for (i = spin_test_count; i > 0; --i) {
453 		    _spin_lock_quick(gd, &spin, "test");
454 		    spin_unlock_quick(gd, &spin);
455 		}
456 	}
457 
458         return (0);
459 }
460 
461 SYSCTL_PROC(_debug, KERN_PROC_ALL, spin_lock_test, CTLFLAG_RW|CTLTYPE_INT,
462         0, 0, sysctl_spin_lock_test, "I", "Test spinlock wait code");
463 
464 #endif	/* INVARIANTS */
465