1 /*-------------------------------------------------------------------------
4 * Hardware-dependent implementation of spinlocks.
6 * When waiting for a contended spinlock we loop tightly for awhile, then
7 * delay using pg_usleep() and try again. Preferably, "awhile" should be a
8 * small multiple of the maximum time we expect a spinlock to be held. 100
9 * iterations seems about right as an initial guess. However, on a
10 * uniprocessor the loop is a waste of cycles, while in a multi-CPU scenario
11 * it's usually better to spin a bit longer than to call the kernel, so we try
12 * to adapt the spin loop count depending on whether we seem to be in a
13 * uniprocessor or multiprocessor.
15 * Note: you might think MIN_SPINS_PER_DELAY should be just 1, but you'd
16 * be wrong; there are platforms where that can result in a "stuck
17 * spinlock" failure. This has been seen particularly on Alphas; it seems
18 * that the first TAS after returning from kernel space will always fail
21 * Once we do decide to block, we use randomly increasing pg_usleep()
22 * delays. The first delay is 1 msec, then the delay randomly increases to
23 * about one second, after which we reset to 1 msec and start again. The
24 * idea here is that in the presence of heavy contention we need to
25 * increase the delay, else the spinlock holder may never get to run and
26 * release the lock. (Consider situation where spinlock holder has been
27 * nice'd down in priority by the scheduler --- it will not get scheduled
28 * until all would-be acquirers are sleeping, so if we always use a 1-msec
29 * sleep, there is a real possibility of starvation.) But we can't just
30 * clamp the delay to an upper bound, else it would take a long time to
31 * make a reasonable number of tries.
33 * We time out and declare error after NUM_DELAYS delays (thus, exactly
34 * that many tries). With the given settings, this will usually take 2 or
35 * so minutes. It seems better to fix the total number of tries (and thus
36 * the probability of unintended failure) than to fix the total time
39 * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
40 * Portions Copyright (c) 1994, Regents of the University of California
44 * src/backend/storage/lmgr/s_lock.c
46 *-------------------------------------------------------------------------
53 #include "storage/s_lock.h"
54 #include "storage/barrier.h"
57 #define MIN_SPINS_PER_DELAY 10
58 #define MAX_SPINS_PER_DELAY 1000
59 #define NUM_DELAYS 1000
60 #define MIN_DELAY_USEC 1000L
61 #define MAX_DELAY_USEC 1000000L
64 slock_t dummy_spinlock;
66 static int spins_per_delay = DEFAULT_SPINS_PER_DELAY;
70 * s_lock_stuck() - complain about a stuck spinlock
73 s_lock_stuck(const char *file, int line, const char *func)
77 #if defined(S_LOCK_TEST)
79 "\nStuck spinlock detected at %s, %s:%d.\n",
83 elog(PANIC, "stuck spinlock detected at %s, %s:%d",
89 * s_lock(lock) - platform-independent portion of waiting for a spinlock.
92 s_lock(volatile slock_t *lock, const char *file, int line, const char *func)
94 SpinDelayStatus delayStatus = init_spin_delay(file, line, func);
96 while (TAS_SPIN(lock))
98 perform_spin_delay(&delayStatus);
101 finish_spin_delay(&delayStatus);
103 return delayStatus.delays;
106 #ifdef USE_DEFAULT_S_UNLOCK
108 s_unlock(volatile slock_t *lock)
110 #ifdef TAS_ACTIVE_WORD
112 *TAS_ACTIVE_WORD(lock) = -1;
120 * Wait while spinning on a contended spinlock.
123 perform_spin_delay(SpinDelayStatus *status)
125 /* CPU-specific delay each time through the loop */
128 /* Block the process every spins_per_delay tries */
129 if (++(status->spins) >= spins_per_delay)
131 if (++(status->delays) > NUM_DELAYS)
132 s_lock_stuck(status->file, status->line, status->func);
134 if (status->cur_delay == 0) /* first time to delay? */
135 status->cur_delay = MIN_DELAY_USEC;
137 pg_usleep(status->cur_delay);
139 #if defined(S_LOCK_TEST)
140 fprintf(stdout, "*");
144 /* increase delay by a random fraction between 1X and 2X */
145 status->cur_delay += (int) (status->cur_delay *
146 ((double) random() / (double) MAX_RANDOM_VALUE) + 0.5);
147 /* wrap back to minimum delay when max is exceeded */
148 if (status->cur_delay > MAX_DELAY_USEC)
149 status->cur_delay = MIN_DELAY_USEC;
156 * After acquiring a spinlock, update estimates about how long to loop.
158 * If we were able to acquire the lock without delaying, it's a good
159 * indication we are in a multiprocessor. If we had to delay, it's a sign
160 * (but not a sure thing) that we are in a uniprocessor. Hence, we
161 * decrement spins_per_delay slowly when we had to delay, and increase it
162 * rapidly when we didn't. It's expected that spins_per_delay will
163 * converge to the minimum value on a uniprocessor and to the maximum
164 * value on a multiprocessor.
166 * Note: spins_per_delay is local within our current process. We want to
167 * average these observations across multiple backends, since it's
168 * relatively rare for this function to even get entered, and so a single
169 * backend might not live long enough to converge on a good value. That
170 * is handled by the two routines below.
173 finish_spin_delay(SpinDelayStatus *status)
175 if (status->cur_delay == 0)
177 /* we never had to delay */
178 if (spins_per_delay < MAX_SPINS_PER_DELAY)
179 spins_per_delay = Min(spins_per_delay + 100, MAX_SPINS_PER_DELAY);
183 if (spins_per_delay > MIN_SPINS_PER_DELAY)
184 spins_per_delay = Max(spins_per_delay - 1, MIN_SPINS_PER_DELAY);
189 * Set local copy of spins_per_delay during backend startup.
191 * NB: this has to be pretty fast as it is called while holding a spinlock
194 set_spins_per_delay(int shared_spins_per_delay)
196 spins_per_delay = shared_spins_per_delay;
200 * Update shared estimate of spins_per_delay during backend exit.
202 * NB: this has to be pretty fast as it is called while holding a spinlock
205 update_spins_per_delay(int shared_spins_per_delay)
208 * We use an exponential moving average with a relatively slow adaption
209 * rate, so that noise in any one backend's result won't affect the shared
210 * value too much. As long as both inputs are within the allowed range,
211 * the result must be too, so we need not worry about clamping the result.
213 * We deliberately truncate rather than rounding; this is so that single
214 * adjustments inside a backend can affect the shared estimate (see the
215 * asymmetric adjustment rules above).
217 return (shared_spins_per_delay * 15 + spins_per_delay) / 16;
222 * Various TAS implementations that cannot live in s_lock.h as no inline
223 * definition exists (yet).
224 * In the future, get rid of tas.[cso] and fold it into this file.
226 * If you change something here, you will likely need to modify s_lock.h too,
227 * because the definitions for these are split between this file and s_lock.h.
231 #ifdef HAVE_SPINLOCKS /* skip spinlocks if requested */
234 #if defined(__GNUC__)
237 * All the gcc flavors that are not inlined
242 * Note: all the if-tests here probably ought to be testing gcc version
243 * rather than platform, but I don't have adequate info to know what to
244 * write. Ideally we'd flush all this in favor of the inline version.
246 #if defined(__m68k__) && !defined(__linux__)
247 /* really means: extern int tas(slock_t* **lock); */
251 __asm__ __volatile__(
252 #if defined(__NetBSD__) && defined(__ELF__)
253 /* no underscore for label and % for registers */
257 movel %sp@(0x4),%a0 \n\
269 movel sp@(0x4),a0 \n\
277 #endif /* __NetBSD__ && __ELF__ */
280 #endif /* __m68k__ && !__linux__ */
281 #endif /* not __GNUC__ */
282 #endif /* HAVE_SPINLOCKS */
286 /*****************************************************************************/
287 #if defined(S_LOCK_TEST)
290 * test program for verifying a port's spinlock support.
293 struct test_lock_struct
300 volatile struct test_lock_struct test_lock;
305 srandom((unsigned int) time(NULL));
307 test_lock.pad1 = test_lock.pad2 = 0x44;
309 S_INIT_LOCK(&test_lock.lock);
311 if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
313 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
317 if (!S_LOCK_FREE(&test_lock.lock))
319 printf("S_LOCK_TEST: failed, lock not initialized\n");
323 S_LOCK(&test_lock.lock);
325 if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
327 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
331 if (S_LOCK_FREE(&test_lock.lock))
333 printf("S_LOCK_TEST: failed, lock not locked\n");
337 S_UNLOCK(&test_lock.lock);
339 if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
341 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
345 if (!S_LOCK_FREE(&test_lock.lock))
347 printf("S_LOCK_TEST: failed, lock not unlocked\n");
351 S_LOCK(&test_lock.lock);
353 if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
355 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
359 if (S_LOCK_FREE(&test_lock.lock))
361 printf("S_LOCK_TEST: failed, lock not re-locked\n");
365 printf("S_LOCK_TEST: this will print %d stars and then\n", NUM_DELAYS);
366 printf(" exit with a 'stuck spinlock' message\n");
367 printf(" if S_LOCK() and TAS() are working.\n");
370 s_lock(&test_lock.lock, __FILE__, __LINE__);
372 printf("S_LOCK_TEST: failed, lock not locked\n");
376 #endif /* S_LOCK_TEST */