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 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 ovalue = atomic_fetchadd_int(&spin->counta, SPINLOCK_EXCLWAIT - 1); 186 ovalue += SPINLOCK_EXCLWAIT - 1; 187 if (ovalue & SPINLOCK_SHARED) { 188 atomic_clear_int(&spin->counta, SPINLOCK_SHARED); 189 ovalue &= ~SPINLOCK_SHARED; 190 } 191 192 indefinite_init(&info, ident, 0, 'S'); 193 194 /* 195 * Spin until we can acquire a low-count of 1. 196 */ 197 for (;;) { 198 /* 199 * If the low bits are zero, try to acquire the exclusive lock 200 * by transfering our high bit reservation to the low bits. 201 * 202 * NOTE: Reading spin->counta prior to the swap is extremely 203 * important on multi-chip/many-core boxes. On 48-core 204 * this one change improves fully concurrent all-cores 205 * compiles by 100% or better. 206 * 207 * I can't emphasize enough how important the pre-read 208 * is in preventing hw cache bus armageddon on 209 * multi-chip systems. And on single-chip/multi-core 210 * systems it just doesn't hurt. 211 */ 212 cpu_ccfence(); 213 if ((ovalue & (SPINLOCK_EXCLWAIT - 1)) == 0) { 214 if (atomic_fcmpset_int(&spin->counta, &ovalue, 215 (ovalue - SPINLOCK_EXCLWAIT) | 1)) { 216 break; 217 } 218 continue; 219 } 220 221 /* 222 * Throw in extra cpu_pause()'s when we are waiting on 223 * multiple other shared lock holders to release (the 224 * indefinite_check() also throws one in). 225 * 226 * We know these are shared lock holders when the count 227 * is larger than 1, because an exclusive lock holder can 228 * only have one count. Do this optimization only when 229 * the number of shared lock holders is 3 or greater. 230 */ 231 ovalue &= SPINLOCK_EXCLWAIT - 1; 232 while (ovalue > 2) { 233 cpu_pause(); 234 cpu_pause(); 235 --ovalue; 236 } 237 238 if (indefinite_check(&info)) 239 break; 240 /* 241 * ovalue was wrong anyway, just reload 242 */ 243 ovalue = spin->counta; 244 } 245 indefinite_done(&info); 246 } 247 248 /* 249 * The spin_lock_shared() inline was unable to acquire the lock and calls 250 * this function with spin->counta already incremented. 251 * 252 * This is not in the critical path unless there is contention between 253 * shared and exclusive holders. 254 */ 255 void 256 _spin_lock_shared_contested(struct spinlock *spin, const char *ident) 257 { 258 indefinite_info_t info; 259 uint32_t ovalue; 260 261 /* 262 * Undo the inline's increment. 263 */ 264 ovalue = atomic_fetchadd_int(&spin->counta, -1) - 1; 265 266 indefinite_init(&info, ident, 0, 's'); 267 cpu_pause(); 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 302 /* 303 * Ignore the EXCLWAIT bits if we have waited too long. 304 * This would be a situation where most of the cpu cores 305 * are concurrently cycling both shared and exclusive use 306 * of the same spinlock, which can cause one or more cores 307 * to wait indefinitely on a shared spinlock. This can 308 * only occur in the most extreme testing environments. 309 */ 310 if (info.secs > 1 && (ovalue & (SPINLOCK_EXCLWAIT - 1)) == 0) { 311 if (atomic_fcmpset_int(&spin->counta, &ovalue, 312 ovalue | SPINLOCK_SHARED | 1)) { 313 break; 314 } 315 continue; 316 } 317 318 /* 319 * If SHARED is already set, go for the increment, improving 320 * the exclusive to multiple-readers transition. 321 */ 322 if (ovalue & SPINLOCK_SHARED) { 323 ovalue = atomic_fetchadd_int(&spin->counta, 1); 324 /* ovalue += 1; NOT NEEDED */ 325 if (ovalue & SPINLOCK_SHARED) 326 break; 327 ovalue = atomic_fetchadd_int(&spin->counta, -1); 328 ovalue += -1; 329 continue; 330 } 331 if (indefinite_check(&info)) 332 break; 333 /* 334 * ovalue was wrong anyway, just reload 335 */ 336 ovalue = spin->counta; 337 } 338 indefinite_done(&info); 339 } 340 341 /* 342 * If INVARIANTS is enabled various spinlock timing tests can be run 343 * by setting debug.spin_lock_test: 344 * 345 * 1 Test the indefinite wait code 346 * 2 Time the best-case exclusive lock overhead (spin_test_count) 347 * 3 Time the best-case shared lock overhead (spin_test_count) 348 */ 349 350 #ifdef INVARIANTS 351 352 static int spin_test_count = 10000000; 353 SYSCTL_INT(_debug, OID_AUTO, spin_test_count, CTLFLAG_RW, &spin_test_count, 0, 354 "Number of iterations to use for spinlock wait code test"); 355 356 static int 357 sysctl_spin_lock_test(SYSCTL_HANDLER_ARGS) 358 { 359 struct spinlock spin; 360 int error; 361 int value = 0; 362 int i; 363 364 if ((error = priv_check(curthread, PRIV_ROOT)) != 0) 365 return (error); 366 if ((error = SYSCTL_IN(req, &value, sizeof(value))) != 0) 367 return (error); 368 369 /* 370 * Indefinite wait test 371 */ 372 if (value == 1) { 373 spin_init(&spin, "sysctllock"); 374 spin_lock(&spin); /* force an indefinite wait */ 375 spin_lock_test_mode = 1; 376 spin_lock(&spin); 377 spin_unlock(&spin); /* Clean up the spinlock count */ 378 spin_unlock(&spin); 379 spin_lock_test_mode = 0; 380 } 381 382 /* 383 * Time best-case exclusive spinlocks 384 */ 385 if (value == 2) { 386 globaldata_t gd = mycpu; 387 388 spin_init(&spin, "sysctllocktest"); 389 for (i = spin_test_count; i > 0; --i) { 390 _spin_lock_quick(gd, &spin, "test"); 391 spin_unlock_quick(gd, &spin); 392 } 393 } 394 395 return (0); 396 } 397 398 SYSCTL_PROC(_debug, KERN_PROC_ALL, spin_lock_test, CTLFLAG_RW|CTLTYPE_INT, 399 0, 0, sysctl_spin_lock_test, "I", "Test spinlock wait code"); 400 401 #endif /* INVARIANTS */ 402