New PHP5 APC - version 3.0.19, using PHP5 5.2.0-8+etch11,
[php5-apc.git] / pgsql_s_lock.c
1 /*
2   +----------------------------------------------------------------------+
3   | APC                                                                  |
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   +----------------------------------------------------------------------+
19
20  */
21
22 /* $Id: pgsql_s_lock.c,v 3.2.2.1 2008/05/11 18:57:00 rasmus Exp $ */
23
24 /*-------------------------------------------------------------------------
25  *
26  * s_lock.c
27  *         Hardware-dependent implementation of spinlocks.
28  *
29  *
30  * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
31  * Portions Copyright (c) 1994, Regents of the University of California
32  *
33  *
34  * IDENTIFICATION
35  *        $PostgreSQL: pgsql/src/backend/storage/lmgr/s_lock.c,v 1.47 2006/10/04 00:29:58 momjian Exp $
36  *
37  *-------------------------------------------------------------------------
38  */
39 /* #include "postgres.h"  -- Removed for APC */
40
41 /* -- Added for APC -- */
42 #include "apc.h"
43 #ifdef APC_SPIN_LOCKS
44
45 #ifdef S_LOCK_TEST
46 #include <stdio.h>
47 #endif
48 #ifndef WIN32
49 #include <sys/select.h>
50 #endif
51 /* ---- */
52
53 #include <time.h>
54 #include <unistd.h>
55
56 /* #include "storage/s_lock.h" -- Removed for APC */
57 #include "pgsql_s_lock.h"
58
59 static int      spins_per_delay = DEFAULT_SPINS_PER_DELAY;
60
61
62 /* -- APC specific additions ------------------------------*/
63 /* The following dependencies have been copied from 
64  * other pgsql source files.  The original locations 
65  * have been noted.
66  */
67
68 /* -- from include/c.h -- */
69 #ifndef TRUE
70 #define TRUE  1
71 #endif
72
73 #ifndef FALSE
74 #define FALSE 0
75 #endif
76
77 /* -- from include/pg_config_manual.h -- */
78 #define MAX_RANDOM_VALUE (0x7FFFFFFF) 
79
80 /*
81  * Max
82  *    Return the maximum of two numbers.
83  */
84 #define Max(x, y)   ((x) > (y) ? (x) : (y))
85
86 /* -- from include/c.h -- */
87 /*
88  * Min
89  *    Return the minimum of two numbers.
90  */
91 #define Min(x, y)   ((x) < (y) ? (x) : (y))
92
93
94 /* -- from backend/port/win32/signal.c -- */
95 /*
96  * pg_usleep --- delay the specified number of microseconds.
97  *
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.
101  *
102  * On machines where "long" is 32 bits, the maximum delay is ~2000 seconds.
103  */
104 void
105 pg_usleep(long microsec)
106 {
107         if (microsec > 0)
108         {
109 #ifndef WIN32
110                 struct timeval delay;
111
112                 delay.tv_sec = microsec / 1000000L;
113                 delay.tv_usec = microsec % 1000000L;
114                 (void) select(0, NULL, NULL, NULL, &delay);
115 #else
116                 SleepEx((microsec < 500 ? 1 : (microsec + 500) / 1000), FALSE);
117 #endif
118         }
119 }
120
121 /* -- End APC specific additions ------------------------------*/
122
123
124 /*
125  * s_lock_stuck() - complain about a stuck spinlock
126  */
127 static void
128 s_lock_stuck(volatile slock_t *lock, const char *file, int line)
129 {
130 #if defined(S_LOCK_TEST)
131         fprintf(stderr,
132                         "\nStuck spinlock (%p) detected at %s:%d.\n",
133                         lock, file, line);
134         exit(1);
135 #else
136   /* -- Removed for APC
137         elog(PANIC, "stuck spinlock (%p) detected at %s:%d",
138                  lock, file, line);
139   */
140   apc_eprint("Stuck spinlock (%p) detected", lock);
141 #endif
142 }
143
144
145 /*
146  * s_lock(lock) - platform-independent portion of waiting for a spinlock.
147  */
148 void
149 s_lock(volatile slock_t *lock, const char *file, int line)
150 {
151         /*
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.
159          *
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
164          * on that hardware.
165          *
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.
177          *
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
182          * spent.
183          *
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.
188          */
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
194
195         int                     spins = 0;
196         int                     delays = 0;
197         int                     cur_delay = 0;
198   
199         while (TAS(lock))
200         {
201                 /* CPU-specific delay each time through the loop */
202                 SPIN_DELAY();
203
204                 /* Block the process every spins_per_delay tries */
205                 if (++spins >= spins_per_delay)
206                 {
207                         if (++delays > NUM_DELAYS)
208                                 s_lock_stuck(lock, file, line);
209
210                         if (cur_delay == 0) /* first time to delay? */
211                                 cur_delay = MIN_DELAY_MSEC;
212
213                         pg_usleep(cur_delay * 1000L);
214
215 #if defined(S_LOCK_TEST)
216                         fprintf(stdout, "*");
217                         fflush(stdout);
218 #endif
219
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;
226
227                         spins = 0;
228                 }
229         }
230
231         /*
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.
239          *
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.
245          */
246         if (cur_delay == 0)
247         {
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);
251         }
252         else
253         {
254                 if (spins_per_delay > MIN_SPINS_PER_DELAY)
255                         spins_per_delay = Max(spins_per_delay - 1, MIN_SPINS_PER_DELAY);
256         }
257 }
258
259
260 #if 0  /* -- APC doesn't use the set_spins_per_delay or update_spins_per_delay -- */
261 /*
262  * Set local copy of spins_per_delay during backend startup.
263  *
264  * NB: this has to be pretty fast as it is called while holding a spinlock
265  */
266 void
267 set_spins_per_delay(int shared_spins_per_delay)
268 {
269         spins_per_delay = shared_spins_per_delay;
270 }
271
272 /*
273  * Update shared estimate of spins_per_delay during backend exit.
274  *
275  * NB: this has to be pretty fast as it is called while holding a spinlock
276  */
277 int
278 update_spins_per_delay(int shared_spins_per_delay)
279 {
280         /*
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.
285          *
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).
289          */
290         return (shared_spins_per_delay * 15 + spins_per_delay) / 16;
291 }
292 #endif
293
294 /*
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.
298  *
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.
301  */
302
303
304 #ifdef HAVE_SPINLOCKS                   /* skip spinlocks if requested */
305
306
307 #if defined(__GNUC__)
308
309 /*
310  * All the gcc flavors that are not inlined
311  */
312
313
314 /*
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.
318  */
319 #if defined(__m68k__) && !defined(__linux__)
320 /* really means: extern int tas(slock_t* **lock); */
321 static void
322 tas_dummy()
323 {
324         __asm__         __volatile__(
325 #if defined(__NetBSD__) && defined(__ELF__)
326 /* no underscore for label and % for registers */
327                                                                                  "\
328 .global         tas                             \n\
329 tas:                                                    \n\
330                         movel   %sp@(0x4),%a0   \n\
331                         tas     %a0@            \n\
332                         beq     _success        \n\
333                         moveq   #-128,%d0       \n\
334                         rts                             \n\
335 _success:                                               \n\
336                         moveq   #0,%d0          \n\
337                         rts                             \n"
338 #else
339                                                                                  "\
340 .global         _tas                            \n\
341 _tas:                                                   \n\
342                         movel   sp@(0x4),a0     \n\
343                         tas     a0@                     \n\
344                         beq     _success        \n\
345                         moveq   #-128,d0        \n\
346                         rts                                     \n\
347 _success:                                               \n\
348                         moveq   #0,d0           \n\
349                         rts                                     \n"
350 #endif   /* __NetBSD__ && __ELF__ */
351         );
352 }
353 #endif   /* __m68k__ && !__linux__ */
354 #else                                                   /* not __GNUC__ */
355
356 /*
357  * All non gcc
358  */
359
360
361 #if defined(sun3)
362 static void
363 tas_dummy()                                             /* really means: extern int tas(slock_t
364                                                                  * *lock); */
365 {
366         asm("LLA0:");
367         asm("   .data");
368         asm("   .text");
369         asm("|#PROC# 04");
370         asm("   .globl  _tas");
371         asm("_tas:");
372         asm("|#PROLOGUE# 1");
373         asm("   movel   sp@(0x4),a0");
374         asm("   tas a0@");
375         asm("   beq LLA1");
376         asm("   moveq   #-128,d0");
377         asm("   rts");
378         asm("LLA1:");
379         asm("   moveq   #0,d0");
380         asm("   rts");
381         asm("   .data");
382 }
383 #endif   /* sun3 */
384 #endif   /* not __GNUC__ */
385 #endif   /* HAVE_SPINLOCKS */
386
387
388
389 /*****************************************************************************/
390 #if defined(S_LOCK_TEST)
391
392 /*
393  * test program for verifying a port's spinlock support.
394  */
395
396 struct test_lock_struct
397 {
398         char            pad1;
399         slock_t         lock;
400         char            pad2;
401 };
402
403 volatile struct test_lock_struct test_lock;
404
405 int
406 main()
407 {
408         srandom((unsigned int) time(NULL));
409
410         test_lock.pad1 = test_lock.pad2 = 0x44;
411
412         S_INIT_LOCK(&test_lock.lock);
413
414         if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
415         {
416                 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
417                 return 1;
418         }
419
420         if (!S_LOCK_FREE(&test_lock.lock))
421         {
422                 printf("S_LOCK_TEST: failed, lock not initialized\n");
423                 return 1;
424         }
425
426         S_LOCK(&test_lock.lock);
427
428         if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
429         {
430                 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
431                 return 1;
432         }
433
434         if (S_LOCK_FREE(&test_lock.lock))
435         {
436                 printf("S_LOCK_TEST: failed, lock not locked\n");
437                 return 1;
438         }
439
440         S_UNLOCK(&test_lock.lock);
441
442         if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
443         {
444                 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
445                 return 1;
446         }
447
448         if (!S_LOCK_FREE(&test_lock.lock))
449         {
450                 printf("S_LOCK_TEST: failed, lock not unlocked\n");
451                 return 1;
452         }
453
454         S_LOCK(&test_lock.lock);
455
456         if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
457         {
458                 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
459                 return 1;
460         }
461
462         if (S_LOCK_FREE(&test_lock.lock))
463         {
464                 printf("S_LOCK_TEST: failed, lock not re-locked\n");
465                 return 1;
466         }
467
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");
471         fflush(stdout);
472
473         s_lock(&test_lock.lock, __FILE__, __LINE__);
474
475         printf("S_LOCK_TEST: failed, lock not locked\n");
476         return 1;
477 }
478
479 #endif   /* S_LOCK_TEST */
480
481 #endif /* APC_SPIN_LOCKS */