2 +----------------------------------------------------------------------+
4 +----------------------------------------------------------------------+
5 | Copyright (c) 2008 The PHP Group |
6 +----------------------------------------------------------------------+
7 | This source file is subject to version 3.01 of the PHP license, |
8 | that is bundled with this package in the file LICENSE, and is |
9 | available through the world-wide-web at the following url: |
10 | http://www.php.net/license/3_01.txt |
11 | If you did not receive a copy of the PHP license and are unable to |
12 | obtain it through the world-wide-web, please send a note to |
13 | license@php.net so we can mail you a copy immediately. |
14 +----------------------------------------------------------------------+
15 | The following code was ported from the PostgreSQL project, please |
16 | see appropriate copyright notices that follow. |
17 | Initial conversion by Brian Shire <shire@php.net> |
18 +----------------------------------------------------------------------+
22 /* $Id: pgsql_s_lock.c,v 3.2.2.1 2008/05/11 18:57:00 rasmus Exp $ */
24 /*-------------------------------------------------------------------------
27 * Hardware-dependent implementation of spinlocks.
30 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
31 * Portions Copyright (c) 1994, Regents of the University of California
35 * $PostgreSQL: pgsql/src/backend/storage/lmgr/s_lock.c,v 1.47 2006/10/04 00:29:58 momjian Exp $
37 *-------------------------------------------------------------------------
39 /* #include "postgres.h" -- Removed for APC */
41 /* -- Added for APC -- */
49 #include <sys/select.h>
56 /* #include "storage/s_lock.h" -- Removed for APC */
57 #include "pgsql_s_lock.h"
59 static int spins_per_delay = DEFAULT_SPINS_PER_DELAY;
62 /* -- APC specific additions ------------------------------*/
63 /* The following dependencies have been copied from
64 * other pgsql source files. The original locations
68 /* -- from include/c.h -- */
77 /* -- from include/pg_config_manual.h -- */
78 #define MAX_RANDOM_VALUE (0x7FFFFFFF)
82 * Return the maximum of two numbers.
84 #define Max(x, y) ((x) > (y) ? (x) : (y))
86 /* -- from include/c.h -- */
89 * Return the minimum of two numbers.
91 #define Min(x, y) ((x) < (y) ? (x) : (y))
94 /* -- from backend/port/win32/signal.c -- */
96 * pg_usleep --- delay the specified number of microseconds.
98 * NOTE: although the delay is specified in microseconds, the effective
99 * resolution is only 1/HZ, or 10 milliseconds, on most Unixen. Expect
100 * the requested delay to be rounded up to the next resolution boundary.
102 * On machines where "long" is 32 bits, the maximum delay is ~2000 seconds.
105 pg_usleep(long microsec)
110 struct timeval delay;
112 delay.tv_sec = microsec / 1000000L;
113 delay.tv_usec = microsec % 1000000L;
114 (void) select(0, NULL, NULL, NULL, &delay);
116 SleepEx((microsec < 500 ? 1 : (microsec + 500) / 1000), FALSE);
121 /* -- End APC specific additions ------------------------------*/
125 * s_lock_stuck() - complain about a stuck spinlock
128 s_lock_stuck(volatile slock_t *lock, const char *file, int line)
130 #if defined(S_LOCK_TEST)
132 "\nStuck spinlock (%p) detected at %s:%d.\n",
136 /* -- Removed for APC
137 elog(PANIC, "stuck spinlock (%p) detected at %s:%d",
140 apc_eprint("Stuck spinlock (%p) detected", lock);
146 * s_lock(lock) - platform-independent portion of waiting for a spinlock.
149 s_lock(volatile slock_t *lock, const char *file, int line)
152 * We loop tightly for awhile, then delay using pg_usleep() and try again.
153 * Preferably, "awhile" should be a small multiple of the maximum time we
154 * expect a spinlock to be held. 100 iterations seems about right as an
155 * initial guess. However, on a uniprocessor the loop is a waste of
156 * cycles, while in a multi-CPU scenario it's usually better to spin a bit
157 * longer than to call the kernel, so we try to adapt the spin loop count
158 * depending on whether we seem to be in a uniprocessor or multiprocessor.
160 * Note: you might think MIN_SPINS_PER_DELAY should be just 1, but you'd
161 * be wrong; there are platforms where that can result in a "stuck
162 * spinlock" failure. This has been seen particularly on Alphas; it seems
163 * that the first TAS after returning from kernel space will always fail
166 * Once we do decide to block, we use randomly increasing pg_usleep()
167 * delays. The first delay is 1 msec, then the delay randomly increases to
168 * about one second, after which we reset to 1 msec and start again. The
169 * idea here is that in the presence of heavy contention we need to
170 * increase the delay, else the spinlock holder may never get to run and
171 * release the lock. (Consider situation where spinlock holder has been
172 * nice'd down in priority by the scheduler --- it will not get scheduled
173 * until all would-be acquirers are sleeping, so if we always use a 1-msec
174 * sleep, there is a real possibility of starvation.) But we can't just
175 * clamp the delay to an upper bound, else it would take a long time to
176 * make a reasonable number of tries.
178 * We time out and declare error after NUM_DELAYS delays (thus, exactly
179 * that many tries). With the given settings, this will usually take 2 or
180 * so minutes. It seems better to fix the total number of tries (and thus
181 * the probability of unintended failure) than to fix the total time
184 * The pg_usleep() delays are measured in milliseconds because 1 msec is a
185 * common resolution limit at the OS level for newer platforms. On older
186 * platforms the resolution limit is usually 10 msec, in which case the
187 * total delay before timeout will be a bit more.
189 #define MIN_SPINS_PER_DELAY 10
190 #define MAX_SPINS_PER_DELAY 1000
191 #define NUM_DELAYS 1000
192 #define MIN_DELAY_MSEC 1
193 #define MAX_DELAY_MSEC 1000
201 /* CPU-specific delay each time through the loop */
204 /* Block the process every spins_per_delay tries */
205 if (++spins >= spins_per_delay)
207 if (++delays > NUM_DELAYS)
208 s_lock_stuck(lock, file, line);
210 if (cur_delay == 0) /* first time to delay? */
211 cur_delay = MIN_DELAY_MSEC;
213 pg_usleep(cur_delay * 1000L);
215 #if defined(S_LOCK_TEST)
216 fprintf(stdout, "*");
220 /* increase delay by a random fraction between 1X and 2X */
221 cur_delay += (int) (cur_delay *
222 ((double) random() / (double) MAX_RANDOM_VALUE) + 0.5);
223 /* wrap back to minimum delay when max is exceeded */
224 if (cur_delay > MAX_DELAY_MSEC)
225 cur_delay = MIN_DELAY_MSEC;
232 * If we were able to acquire the lock without delaying, it's a good
233 * indication we are in a multiprocessor. If we had to delay, it's a sign
234 * (but not a sure thing) that we are in a uniprocessor. Hence, we
235 * decrement spins_per_delay slowly when we had to delay, and increase it
236 * rapidly when we didn't. It's expected that spins_per_delay will
237 * converge to the minimum value on a uniprocessor and to the maximum
238 * value on a multiprocessor.
240 * Note: spins_per_delay is local within our current process. We want to
241 * average these observations across multiple backends, since it's
242 * relatively rare for this function to even get entered, and so a single
243 * backend might not live long enough to converge on a good value. That
244 * is handled by the two routines below.
248 /* we never had to delay */
249 if (spins_per_delay < MAX_SPINS_PER_DELAY)
250 spins_per_delay = Min(spins_per_delay + 100, MAX_SPINS_PER_DELAY);
254 if (spins_per_delay > MIN_SPINS_PER_DELAY)
255 spins_per_delay = Max(spins_per_delay - 1, MIN_SPINS_PER_DELAY);
260 #if 0 /* -- APC doesn't use the set_spins_per_delay or update_spins_per_delay -- */
262 * Set local copy of spins_per_delay during backend startup.
264 * NB: this has to be pretty fast as it is called while holding a spinlock
267 set_spins_per_delay(int shared_spins_per_delay)
269 spins_per_delay = shared_spins_per_delay;
273 * Update shared estimate of spins_per_delay during backend exit.
275 * NB: this has to be pretty fast as it is called while holding a spinlock
278 update_spins_per_delay(int shared_spins_per_delay)
281 * We use an exponential moving average with a relatively slow adaption
282 * rate, so that noise in any one backend's result won't affect the shared
283 * value too much. As long as both inputs are within the allowed range,
284 * the result must be too, so we need not worry about clamping the result.
286 * We deliberately truncate rather than rounding; this is so that single
287 * adjustments inside a backend can affect the shared estimate (see the
288 * asymmetric adjustment rules above).
290 return (shared_spins_per_delay * 15 + spins_per_delay) / 16;
295 * Various TAS implementations that cannot live in s_lock.h as no inline
296 * definition exists (yet).
297 * In the future, get rid of tas.[cso] and fold it into this file.
299 * If you change something here, you will likely need to modify s_lock.h too,
300 * because the definitions for these are split between this file and s_lock.h.
304 #ifdef HAVE_SPINLOCKS /* skip spinlocks if requested */
307 #if defined(__GNUC__)
310 * All the gcc flavors that are not inlined
315 * Note: all the if-tests here probably ought to be testing gcc version
316 * rather than platform, but I don't have adequate info to know what to
317 * write. Ideally we'd flush all this in favor of the inline version.
319 #if defined(__m68k__) && !defined(__linux__)
320 /* really means: extern int tas(slock_t* **lock); */
324 __asm__ __volatile__(
325 #if defined(__NetBSD__) && defined(__ELF__)
326 /* no underscore for label and % for registers */
330 movel %sp@(0x4),%a0 \n\
342 movel sp@(0x4),a0 \n\
350 #endif /* __NetBSD__ && __ELF__ */
353 #endif /* __m68k__ && !__linux__ */
354 #else /* not __GNUC__ */
363 tas_dummy() /* really means: extern int tas(slock_t
372 asm("|#PROLOGUE# 1");
373 asm(" movel sp@(0x4),a0");
376 asm(" moveq #-128,d0");
384 #endif /* not __GNUC__ */
385 #endif /* HAVE_SPINLOCKS */
389 /*****************************************************************************/
390 #if defined(S_LOCK_TEST)
393 * test program for verifying a port's spinlock support.
396 struct test_lock_struct
403 volatile struct test_lock_struct test_lock;
408 srandom((unsigned int) time(NULL));
410 test_lock.pad1 = test_lock.pad2 = 0x44;
412 S_INIT_LOCK(&test_lock.lock);
414 if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
416 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
420 if (!S_LOCK_FREE(&test_lock.lock))
422 printf("S_LOCK_TEST: failed, lock not initialized\n");
426 S_LOCK(&test_lock.lock);
428 if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
430 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
434 if (S_LOCK_FREE(&test_lock.lock))
436 printf("S_LOCK_TEST: failed, lock not locked\n");
440 S_UNLOCK(&test_lock.lock);
442 if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
444 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
448 if (!S_LOCK_FREE(&test_lock.lock))
450 printf("S_LOCK_TEST: failed, lock not unlocked\n");
454 S_LOCK(&test_lock.lock);
456 if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
458 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
462 if (S_LOCK_FREE(&test_lock.lock))
464 printf("S_LOCK_TEST: failed, lock not re-locked\n");
468 printf("S_LOCK_TEST: this will print %d stars and then\n", NUM_DELAYS);
469 printf(" exit with a 'stuck spinlock' message\n");
470 printf(" if S_LOCK() and TAS() are working.\n");
473 s_lock(&test_lock.lock, __FILE__, __LINE__);
475 printf("S_LOCK_TEST: failed, lock not locked\n");
479 #endif /* S_LOCK_TEST */
481 #endif /* APC_SPIN_LOCKS */