xref: /dragonfly/sys/kern/kern_spinlock.c (revision e6e77800)
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 
158 	/*
159 	 * WARNING! Caller has already incremented the lock.  We must
160 	 *	    increment the count value (from the inline's fetch-add)
161 	 *	    to match.
162 	 *
163 	 * Handle the degenerate case where the spinlock is flagged SHARED
164 	 * with only our reference.  We can convert it to EXCLUSIVE.
165 	 */
166 	++value;
167 	if (value == (SPINLOCK_SHARED | 1)) {
168 		if (atomic_cmpset_int(&spin->counta, SPINLOCK_SHARED | 1, 1))
169 			return;
170 	}
171 	indefinite_init(&info, ident, 0, 'S');
172 
173 	/*
174 	 * Transfer our exclusive request to the high bits and clear the
175 	 * SPINLOCK_SHARED bit if it was set.  This makes the spinlock
176 	 * appear exclusive, preventing any NEW shared or exclusive
177 	 * spinlocks from being obtained while we wait for existing
178 	 * shared or exclusive holders to unlock.
179 	 *
180 	 * Don't tread on earlier exclusive waiters by stealing the lock
181 	 * away early if the low bits happen to now be 1.
182 	 *
183 	 * The shared unlock understands that this may occur.
184 	 */
185 	atomic_add_int(&spin->counta, SPINLOCK_EXCLWAIT - 1);
186 	if (value & SPINLOCK_SHARED)
187 		atomic_clear_int(&spin->counta, SPINLOCK_SHARED);
188 
189 	/*
190 	 * Spin until we can acquire a low-count of 1.
191 	 */
192 	for (;;) {
193 		/*
194 		 * If the low bits are zero, try to acquire the exclusive lock
195 		 * by transfering our high bit reservation to the low bits.
196 		 *
197 		 * NOTE: Reading spin->counta prior to the swap is extremely
198 		 *	 important on multi-chip/many-core boxes.  On 48-core
199 		 *	 this one change improves fully concurrent all-cores
200 		 *	 compiles by 100% or better.
201 		 *
202 		 *	 I can't emphasize enough how important the pre-read
203 		 *	 is in preventing hw cache bus armageddon on
204 		 *	 multi-chip systems.  And on single-chip/multi-core
205 		 *	 systems it just doesn't hurt.
206 		 */
207 		uint32_t ovalue = spin->counta;
208 		cpu_ccfence();
209 		if ((ovalue & (SPINLOCK_EXCLWAIT - 1)) == 0 &&
210 		    atomic_cmpset_int(&spin->counta, ovalue,
211 				      (ovalue - SPINLOCK_EXCLWAIT) | 1)) {
212 			break;
213 		}
214 
215 		/*
216 		 * Throw in extra cpu_pause()'s when we are waiting on
217 		 * multiple other shared lock holders to release (the
218 		 * indefinite_check() also throws one in).
219 		 *
220 		 * We know these are shared lock holders when the count
221 		 * is larger than 1, because an exclusive lock holder can
222 		 * only have one count.  Do this optimization only when
223 		 * the number of shared lock holders is 3 or greater.
224 		 */
225 		ovalue &= SPINLOCK_EXCLWAIT - 1;
226 		while (ovalue > 2) {
227 			cpu_pause();
228 			cpu_pause();
229 			--ovalue;
230 		}
231 
232 		if (indefinite_check(&info))
233 			break;
234 	}
235 	indefinite_done(&info);
236 }
237 
238 /*
239  * The spin_lock_shared() inline was unable to acquire the lock and calls
240  * this function with spin->counta already incremented.
241  *
242  * This is not in the critical path unless there is contention between
243  * shared and exclusive holders.
244  */
245 void
246 _spin_lock_shared_contested(struct spinlock *spin, const char *ident)
247 {
248 	indefinite_info_t info;
249 
250 	indefinite_init(&info, ident, 0, 's');
251 
252 	/*
253 	 * Undo the inline's increment.
254 	 */
255 	atomic_add_int(&spin->counta, -1);
256 
257 #ifdef DEBUG_LOCKS_LATENCY
258 	long j;
259 	for (j = spinlocks_add_latency; j > 0; --j)
260 		cpu_ccfence();
261 #endif
262 
263 	for (;;) {
264 		/*
265 		 * Loop until we can acquire the shared spinlock.  Note that
266 		 * the low bits can be zero while the high EXCLWAIT bits are
267 		 * non-zero.  In this situation exclusive requesters have
268 		 * priority (otherwise shared users on multiple cpus can hog
269 		 * the spinlnock).
270 		 *
271 		 * NOTE: Reading spin->counta prior to the swap is extremely
272 		 *	 important on multi-chip/many-core boxes.  On 48-core
273 		 *	 this one change improves fully concurrent all-cores
274 		 *	 compiles by 100% or better.
275 		 *
276 		 *	 I can't emphasize enough how important the pre-read
277 		 *	 is in preventing hw cache bus armageddon on
278 		 *	 multi-chip systems.  And on single-chip/multi-core
279 		 *	 systems it just doesn't hurt.
280 		 */
281 		uint32_t ovalue = spin->counta;
282 
283 		cpu_ccfence();
284 		if (ovalue == 0) {
285 			if (atomic_cmpset_int(&spin->counta, 0,
286 					      SPINLOCK_SHARED | 1))
287 				break;
288 		} else if (ovalue & SPINLOCK_SHARED) {
289 			if (atomic_cmpset_int(&spin->counta, ovalue,
290 					      ovalue + 1))
291 				break;
292 		}
293 		if (indefinite_check(&info))
294 			break;
295 	}
296 	indefinite_done(&info);
297 }
298 
299 /*
300  * If INVARIANTS is enabled various spinlock timing tests can be run
301  * by setting debug.spin_lock_test:
302  *
303  *	1	Test the indefinite wait code
304  *	2	Time the best-case exclusive lock overhead (spin_test_count)
305  *	3	Time the best-case shared lock overhead (spin_test_count)
306  */
307 
308 #ifdef INVARIANTS
309 
310 static int spin_test_count = 10000000;
311 SYSCTL_INT(_debug, OID_AUTO, spin_test_count, CTLFLAG_RW, &spin_test_count, 0,
312     "Number of iterations to use for spinlock wait code test");
313 
314 static int
315 sysctl_spin_lock_test(SYSCTL_HANDLER_ARGS)
316 {
317         struct spinlock spin;
318 	int error;
319 	int value = 0;
320 	int i;
321 
322 	if ((error = priv_check(curthread, PRIV_ROOT)) != 0)
323 		return (error);
324 	if ((error = SYSCTL_IN(req, &value, sizeof(value))) != 0)
325 		return (error);
326 
327 	/*
328 	 * Indefinite wait test
329 	 */
330 	if (value == 1) {
331 		spin_init(&spin, "sysctllock");
332 		spin_lock(&spin);	/* force an indefinite wait */
333 		spin_lock_test_mode = 1;
334 		spin_lock(&spin);
335 		spin_unlock(&spin);	/* Clean up the spinlock count */
336 		spin_unlock(&spin);
337 		spin_lock_test_mode = 0;
338 	}
339 
340 	/*
341 	 * Time best-case exclusive spinlocks
342 	 */
343 	if (value == 2) {
344 		globaldata_t gd = mycpu;
345 
346 		spin_init(&spin, "sysctllocktest");
347 		for (i = spin_test_count; i > 0; --i) {
348 		    _spin_lock_quick(gd, &spin, "test");
349 		    spin_unlock_quick(gd, &spin);
350 		}
351 	}
352 
353         return (0);
354 }
355 
356 SYSCTL_PROC(_debug, KERN_PROC_ALL, spin_lock_test, CTLFLAG_RW|CTLTYPE_INT,
357         0, 0, sysctl_spin_lock_test, "I", "Test spinlock wait code");
358 
359 #endif	/* INVARIANTS */
360