xref: /dflybsd-src/sys/kern/kern_spinlock.c (revision b276d6fe06e6cb191f75486f1608f0dbc5822485)
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/indefinite2.h>
66 #include <sys/spinlock.h>
67 #include <sys/spinlock2.h>
68 #include <sys/ktr.h>
69 
70 #ifdef _KERNEL_VIRTUAL
71 #include <pthread.h>
72 #endif
73 
74 struct spinlock pmap_spin = SPINLOCK_INITIALIZER(pmap_spin, "pmap_spin");
75 
76 /*
77  * Kernal Trace
78  */
79 #if !defined(KTR_SPIN_CONTENTION)
80 #define KTR_SPIN_CONTENTION	KTR_ALL
81 #endif
82 #define SPIN_STRING	"spin=%p type=%c"
83 #define SPIN_ARG_SIZE	(sizeof(void *) + sizeof(int))
84 
85 KTR_INFO_MASTER(spin);
86 #if 0
87 KTR_INFO(KTR_SPIN_CONTENTION, spin, beg, 0, SPIN_STRING, SPIN_ARG_SIZE);
88 KTR_INFO(KTR_SPIN_CONTENTION, spin, end, 1, SPIN_STRING, SPIN_ARG_SIZE);
89 #endif
90 
91 #define logspin(name, spin, type)			\
92 	KTR_LOG(spin_ ## name, spin, type)
93 
94 #ifdef INVARIANTS
95 static int spin_lock_test_mode;
96 #endif
97 
98 #ifdef DEBUG_LOCKS_LATENCY
99 
100 static long spinlocks_add_latency;
101 SYSCTL_LONG(_debug, OID_AUTO, spinlocks_add_latency, CTLFLAG_RW,
102     &spinlocks_add_latency, 0,
103     "Add spinlock latency");
104 
105 #endif
106 
107 /*
108  * We contested due to another exclusive lock holder.  We lose.
109  *
110  * We have to unwind the attempt and may acquire the spinlock
111  * anyway while doing so.
112  */
113 int
114 spin_trylock_contested(struct spinlock *spin)
115 {
116 	globaldata_t gd = mycpu;
117 
118 	/*
119 	 * Handle degenerate case, else fail.
120 	 */
121 	if (atomic_cmpset_int(&spin->counta, SPINLOCK_SHARED|0, 1))
122 		return TRUE;
123 	/*atomic_add_int(&spin->counta, -1);*/
124 	--gd->gd_spinlocks;
125 	crit_exit_raw(gd->gd_curthread);
126 
127 	return (FALSE);
128 }
129 
130 /*
131  * The spin_lock() inline was unable to acquire the lock and calls this
132  * function with spin->counta already incremented, passing (spin->counta - 1)
133  * to the function (the result of the inline's fetchadd).
134  *
135  * Note that we implement both exclusive and shared spinlocks, so we cannot
136  * use atomic_swap_int().  Instead, we try to use atomic_fetchadd_int()
137  * to put most of the burden on the cpu.  Atomic_cmpset_int() (cmpxchg)
138  * can cause a lot of unnecessary looping in situations where it is just
139  * trying to increment the count.
140  *
141  * Similarly, we leave the SHARED flag intact and incur slightly more
142  * overhead when switching from shared to exclusive.  This allows us to
143  * use atomic_fetchadd_int() for both spinlock types in the critical
144  * path.
145  *
146  * Backoff algorithms can create even worse starvation problems, particularly
147  * on multi-socket cpus, and don't really improve performance when a lot
148  * of cores are contending.  However, if we are contested on an exclusive
149  * lock due to a large number of shared locks being present, we throw in
150  * extra cpu_pause()'s to account for the necessary time it will take other
151  * cores to contend among themselves and release their shared locks.
152  */
153 void
154 _spin_lock_contested(struct spinlock *spin, const char *ident, int value)
155 {
156 	indefinite_info_t info;
157 	uint32_t ovalue;
158 
159 	/*
160 	 * WARNING! Caller has already incremented the lock.  We must
161 	 *	    increment the count value (from the inline's fetch-add)
162 	 *	    to match.
163 	 *
164 	 * Handle the degenerate case where the spinlock is flagged SHARED
165 	 * with only our reference.  We can convert it to EXCLUSIVE.
166 	 */
167 	++value;
168 	if (value == (SPINLOCK_SHARED | 1)) {
169 		if (atomic_cmpset_int(&spin->counta, SPINLOCK_SHARED | 1, 1))
170 			return;
171 	}
172 	indefinite_init(&info, ident, 0, 'S');
173 
174 	/*
175 	 * Transfer our exclusive request to the high bits and clear the
176 	 * SPINLOCK_SHARED bit if it was set.  This makes the spinlock
177 	 * appear exclusive, preventing any NEW shared or exclusive
178 	 * spinlocks from being obtained while we wait for existing
179 	 * shared or exclusive holders to unlock.
180 	 *
181 	 * Don't tread on earlier exclusive waiters by stealing the lock
182 	 * away early if the low bits happen to now be 1.
183 	 *
184 	 * The shared unlock understands that this may occur.
185 	 */
186 	ovalue = atomic_fetchadd_int(&spin->counta, SPINLOCK_EXCLWAIT - 1);
187 	ovalue += SPINLOCK_EXCLWAIT - 1;
188 	if (value & SPINLOCK_SHARED) {
189 		atomic_clear_int(&spin->counta, SPINLOCK_SHARED);
190 		ovalue &= ~SPINLOCK_SHARED;
191 	}
192 
193 	/*
194 	 * Spin until we can acquire a low-count of 1.
195 	 */
196 	for (;;) {
197 		/*
198 		 * If the low bits are zero, try to acquire the exclusive lock
199 		 * by transfering our high bit reservation to the low bits.
200 		 *
201 		 * NOTE: Reading spin->counta prior to the swap is extremely
202 		 *	 important on multi-chip/many-core boxes.  On 48-core
203 		 *	 this one change improves fully concurrent all-cores
204 		 *	 compiles by 100% or better.
205 		 *
206 		 *	 I can't emphasize enough how important the pre-read
207 		 *	 is in preventing hw cache bus armageddon on
208 		 *	 multi-chip systems.  And on single-chip/multi-core
209 		 *	 systems it just doesn't hurt.
210 		 */
211 		cpu_ccfence();
212 		if ((ovalue & (SPINLOCK_EXCLWAIT - 1)) == 0) {
213 			if (atomic_fcmpset_int(&spin->counta, &ovalue,
214 				      (ovalue - SPINLOCK_EXCLWAIT) | 1)) {
215 				break;
216 			}
217 			continue;
218 		}
219 
220 		/*
221 		 * Throw in extra cpu_pause()'s when we are waiting on
222 		 * multiple other shared lock holders to release (the
223 		 * indefinite_check() also throws one in).
224 		 *
225 		 * We know these are shared lock holders when the count
226 		 * is larger than 1, because an exclusive lock holder can
227 		 * only have one count.  Do this optimization only when
228 		 * the number of shared lock holders is 3 or greater.
229 		 */
230 		ovalue &= SPINLOCK_EXCLWAIT - 1;
231 		while (ovalue > 2) {
232 			cpu_pause();
233 			cpu_pause();
234 			--ovalue;
235 		}
236 
237 		if (indefinite_check(&info))
238 			break;
239 		/*
240 		 * ovalue was wrong anyway, just reload
241 		 */
242 		ovalue = spin->counta;
243 	}
244 	indefinite_done(&info);
245 }
246 
247 /*
248  * The spin_lock_shared() inline was unable to acquire the lock and calls
249  * this function with spin->counta already incremented.
250  *
251  * This is not in the critical path unless there is contention between
252  * shared and exclusive holders.
253  */
254 void
255 _spin_lock_shared_contested(struct spinlock *spin, const char *ident)
256 {
257 	indefinite_info_t info;
258 	uint32_t ovalue;
259 
260 	indefinite_init(&info, ident, 0, 's');
261 
262 	/*
263 	 * Undo the inline's increment.
264 	 */
265 	cpu_pause();
266 	ovalue = atomic_fetchadd_int(&spin->counta, -1);
267 	ovalue += -1;
268 
269 #ifdef DEBUG_LOCKS_LATENCY
270 	long j;
271 	for (j = spinlocks_add_latency; j > 0; --j)
272 		cpu_ccfence();
273 #endif
274 
275 	for (;;) {
276 		/*
277 		 * Loop until we can acquire the shared spinlock.  Note that
278 		 * the low bits can be zero while the high EXCLWAIT bits are
279 		 * non-zero.  In this situation exclusive requesters have
280 		 * priority (otherwise shared users on multiple cpus can hog
281 		 * the spinlnock).
282 		 *
283 		 * NOTE: Reading spin->counta prior to the swap is extremely
284 		 *	 important on multi-chip/many-core boxes.  On 48-core
285 		 *	 this one change improves fully concurrent all-cores
286 		 *	 compiles by 100% or better.
287 		 *
288 		 *	 I can't emphasize enough how important the pre-read
289 		 *	 is in preventing hw cache bus armageddon on
290 		 *	 multi-chip systems.  And on single-chip/multi-core
291 		 *	 systems it just doesn't hurt.
292 		 */
293 		cpu_ccfence();
294 		if (ovalue == 0) {
295 			if (atomic_fcmpset_int(&spin->counta, &ovalue,
296 					      SPINLOCK_SHARED | 1)) {
297 				break;
298 			}
299 			continue;
300 		}
301 		if (ovalue & SPINLOCK_SHARED) {
302 			/*
303 			 * Go for the increment, improving the exclusive
304 			 * to multiple-readers transition.
305 			 */
306 			ovalue = atomic_fetchadd_int(&spin->counta, 1);
307 			/* ovalue += 1; NOT NEEDED */
308 			if (ovalue & SPINLOCK_SHARED)
309 				break;
310 			ovalue = atomic_fetchadd_int(&spin->counta, -1);
311 			ovalue += -1;
312 			continue;
313 		}
314 		if (indefinite_check(&info))
315 			break;
316 		/*
317 		 * ovalue was wrong anyway, just reload
318 		 */
319 		ovalue = spin->counta;
320 	}
321 	indefinite_done(&info);
322 }
323 
324 /*
325  * If INVARIANTS is enabled various spinlock timing tests can be run
326  * by setting debug.spin_lock_test:
327  *
328  *	1	Test the indefinite wait code
329  *	2	Time the best-case exclusive lock overhead (spin_test_count)
330  *	3	Time the best-case shared lock overhead (spin_test_count)
331  */
332 
333 #ifdef INVARIANTS
334 
335 static int spin_test_count = 10000000;
336 SYSCTL_INT(_debug, OID_AUTO, spin_test_count, CTLFLAG_RW, &spin_test_count, 0,
337     "Number of iterations to use for spinlock wait code test");
338 
339 static int
340 sysctl_spin_lock_test(SYSCTL_HANDLER_ARGS)
341 {
342         struct spinlock spin;
343 	int error;
344 	int value = 0;
345 	int i;
346 
347 	if ((error = priv_check(curthread, PRIV_ROOT)) != 0)
348 		return (error);
349 	if ((error = SYSCTL_IN(req, &value, sizeof(value))) != 0)
350 		return (error);
351 
352 	/*
353 	 * Indefinite wait test
354 	 */
355 	if (value == 1) {
356 		spin_init(&spin, "sysctllock");
357 		spin_lock(&spin);	/* force an indefinite wait */
358 		spin_lock_test_mode = 1;
359 		spin_lock(&spin);
360 		spin_unlock(&spin);	/* Clean up the spinlock count */
361 		spin_unlock(&spin);
362 		spin_lock_test_mode = 0;
363 	}
364 
365 	/*
366 	 * Time best-case exclusive spinlocks
367 	 */
368 	if (value == 2) {
369 		globaldata_t gd = mycpu;
370 
371 		spin_init(&spin, "sysctllocktest");
372 		for (i = spin_test_count; i > 0; --i) {
373 		    _spin_lock_quick(gd, &spin, "test");
374 		    spin_unlock_quick(gd, &spin);
375 		}
376 	}
377 
378         return (0);
379 }
380 
381 SYSCTL_PROC(_debug, KERN_PROC_ALL, spin_lock_test, CTLFLAG_RW|CTLTYPE_INT,
382         0, 0, sysctl_spin_lock_test, "I", "Test spinlock wait code");
383 
384 #endif	/* INVARIANTS */
385