1 /*-------------------------------------------------------------------------
4 * Hardware-dependent implementation of spinlocks.
7 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
12 * src/backend/storage/lmgr/s_lock.c
14 *-------------------------------------------------------------------------
21 #include "storage/s_lock.h"
24 static int spins_per_delay = DEFAULT_SPINS_PER_DELAY;
28 * s_lock_stuck() - complain about a stuck spinlock
31 s_lock_stuck(volatile slock_t *lock, const char *file, int line)
33 #if defined(S_LOCK_TEST)
35 "\nStuck spinlock (%p) detected at %s:%d.\n",
39 elog(PANIC, "stuck spinlock (%p) detected at %s:%d",
46 * s_lock(lock) - platform-independent portion of waiting for a spinlock.
49 s_lock(volatile slock_t *lock, const char *file, int line)
52 * We loop tightly for awhile, then delay using pg_usleep() and try again.
53 * Preferably, "awhile" should be a small multiple of the maximum time we
54 * expect a spinlock to be held. 100 iterations seems about right as an
55 * initial guess. However, on a uniprocessor the loop is a waste of
56 * cycles, while in a multi-CPU scenario it's usually better to spin a bit
57 * longer than to call the kernel, so we try to adapt the spin loop count
58 * depending on whether we seem to be in a uniprocessor or multiprocessor.
60 * Note: you might think MIN_SPINS_PER_DELAY should be just 1, but you'd
61 * be wrong; there are platforms where that can result in a "stuck
62 * spinlock" failure. This has been seen particularly on Alphas; it seems
63 * that the first TAS after returning from kernel space will always fail
66 * Once we do decide to block, we use randomly increasing pg_usleep()
67 * delays. The first delay is 1 msec, then the delay randomly increases to
68 * about one second, after which we reset to 1 msec and start again. The
69 * idea here is that in the presence of heavy contention we need to
70 * increase the delay, else the spinlock holder may never get to run and
71 * release the lock. (Consider situation where spinlock holder has been
72 * nice'd down in priority by the scheduler --- it will not get scheduled
73 * until all would-be acquirers are sleeping, so if we always use a 1-msec
74 * sleep, there is a real possibility of starvation.) But we can't just
75 * clamp the delay to an upper bound, else it would take a long time to
76 * make a reasonable number of tries.
78 * We time out and declare error after NUM_DELAYS delays (thus, exactly
79 * that many tries). With the given settings, this will usually take 2 or
80 * so minutes. It seems better to fix the total number of tries (and thus
81 * the probability of unintended failure) than to fix the total time
84 * The pg_usleep() delays are measured in milliseconds because 1 msec is a
85 * common resolution limit at the OS level for newer platforms. On older
86 * platforms the resolution limit is usually 10 msec, in which case the
87 * total delay before timeout will be a bit more.
89 #define MIN_SPINS_PER_DELAY 10
90 #define MAX_SPINS_PER_DELAY 1000
91 #define NUM_DELAYS 1000
92 #define MIN_DELAY_MSEC 1
93 #define MAX_DELAY_MSEC 1000
101 /* CPU-specific delay each time through the loop */
104 /* Block the process every spins_per_delay tries */
105 if (++spins >= spins_per_delay)
107 if (++delays > NUM_DELAYS)
108 s_lock_stuck(lock, file, line);
110 if (cur_delay == 0) /* first time to delay? */
111 cur_delay = MIN_DELAY_MSEC;
113 pg_usleep(cur_delay * 1000L);
115 #if defined(S_LOCK_TEST)
116 fprintf(stdout, "*");
120 /* increase delay by a random fraction between 1X and 2X */
121 cur_delay += (int) (cur_delay *
122 ((double) random() / (double) MAX_RANDOM_VALUE) + 0.5);
123 /* wrap back to minimum delay when max is exceeded */
124 if (cur_delay > MAX_DELAY_MSEC)
125 cur_delay = MIN_DELAY_MSEC;
132 * If we were able to acquire the lock without delaying, it's a good
133 * indication we are in a multiprocessor. If we had to delay, it's a sign
134 * (but not a sure thing) that we are in a uniprocessor. Hence, we
135 * decrement spins_per_delay slowly when we had to delay, and increase it
136 * rapidly when we didn't. It's expected that spins_per_delay will
137 * converge to the minimum value on a uniprocessor and to the maximum
138 * value on a multiprocessor.
140 * Note: spins_per_delay is local within our current process. We want to
141 * average these observations across multiple backends, since it's
142 * relatively rare for this function to even get entered, and so a single
143 * backend might not live long enough to converge on a good value. That
144 * is handled by the two routines below.
148 /* we never had to delay */
149 if (spins_per_delay < MAX_SPINS_PER_DELAY)
150 spins_per_delay = Min(spins_per_delay + 100, MAX_SPINS_PER_DELAY);
154 if (spins_per_delay > MIN_SPINS_PER_DELAY)
155 spins_per_delay = Max(spins_per_delay - 1, MIN_SPINS_PER_DELAY);
161 * Set local copy of spins_per_delay during backend startup.
163 * NB: this has to be pretty fast as it is called while holding a spinlock
166 set_spins_per_delay(int shared_spins_per_delay)
168 spins_per_delay = shared_spins_per_delay;
172 * Update shared estimate of spins_per_delay during backend exit.
174 * NB: this has to be pretty fast as it is called while holding a spinlock
177 update_spins_per_delay(int shared_spins_per_delay)
180 * We use an exponential moving average with a relatively slow adaption
181 * rate, so that noise in any one backend's result won't affect the shared
182 * value too much. As long as both inputs are within the allowed range,
183 * the result must be too, so we need not worry about clamping the result.
185 * We deliberately truncate rather than rounding; this is so that single
186 * adjustments inside a backend can affect the shared estimate (see the
187 * asymmetric adjustment rules above).
189 return (shared_spins_per_delay * 15 + spins_per_delay) / 16;
194 * Various TAS implementations that cannot live in s_lock.h as no inline
195 * definition exists (yet).
196 * In the future, get rid of tas.[cso] and fold it into this file.
198 * If you change something here, you will likely need to modify s_lock.h too,
199 * because the definitions for these are split between this file and s_lock.h.
203 #ifdef HAVE_SPINLOCKS /* skip spinlocks if requested */
206 #if defined(__GNUC__)
209 * All the gcc flavors that are not inlined
214 * Note: all the if-tests here probably ought to be testing gcc version
215 * rather than platform, but I don't have adequate info to know what to
216 * write. Ideally we'd flush all this in favor of the inline version.
218 #if defined(__m68k__) && !defined(__linux__)
219 /* really means: extern int tas(slock_t* **lock); */
223 __asm__ __volatile__(
224 #if defined(__NetBSD__) && defined(__ELF__)
225 /* no underscore for label and % for registers */
229 movel %sp@(0x4),%a0 \n\
241 movel sp@(0x4),a0 \n\
249 #endif /* __NetBSD__ && __ELF__ */
252 #endif /* __m68k__ && !__linux__ */
253 #else /* not __GNUC__ */
262 tas_dummy() /* really means: extern int tas(slock_t
271 asm("|#PROLOGUE# 1");
272 asm(" movel sp@(0x4),a0");
275 asm(" moveq #-128,d0");
283 #endif /* not __GNUC__ */
284 #endif /* HAVE_SPINLOCKS */
288 /*****************************************************************************/
289 #if defined(S_LOCK_TEST)
292 * test program for verifying a port's spinlock support.
295 struct test_lock_struct
302 volatile struct test_lock_struct test_lock;
307 srandom((unsigned int) time(NULL));
309 test_lock.pad1 = test_lock.pad2 = 0x44;
311 S_INIT_LOCK(&test_lock.lock);
313 if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
315 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
319 if (!S_LOCK_FREE(&test_lock.lock))
321 printf("S_LOCK_TEST: failed, lock not initialized\n");
325 S_LOCK(&test_lock.lock);
327 if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
329 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
333 if (S_LOCK_FREE(&test_lock.lock))
335 printf("S_LOCK_TEST: failed, lock not locked\n");
339 S_UNLOCK(&test_lock.lock);
341 if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
343 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
347 if (!S_LOCK_FREE(&test_lock.lock))
349 printf("S_LOCK_TEST: failed, lock not unlocked\n");
353 S_LOCK(&test_lock.lock);
355 if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
357 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
361 if (S_LOCK_FREE(&test_lock.lock))
363 printf("S_LOCK_TEST: failed, lock not re-locked\n");
367 printf("S_LOCK_TEST: this will print %d stars and then\n", NUM_DELAYS);
368 printf(" exit with a 'stuck spinlock' message\n");
369 printf(" if S_LOCK() and TAS() are working.\n");
372 s_lock(&test_lock.lock, __FILE__, __LINE__);
374 printf("S_LOCK_TEST: failed, lock not locked\n");
378 #endif /* S_LOCK_TEST */