]> granicus.if.org Git - postgresql/blob - src/backend/storage/lmgr/s_lock.c
Update copyrights for 2013
[postgresql] / src / backend / storage / lmgr / s_lock.c
1 /*-------------------------------------------------------------------------
2  *
3  * s_lock.c
4  *         Hardware-dependent implementation of spinlocks.
5  *
6  *
7  * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  *
11  * IDENTIFICATION
12  *        src/backend/storage/lmgr/s_lock.c
13  *
14  *-------------------------------------------------------------------------
15  */
16 #include "postgres.h"
17
18 #include <time.h>
19 #include <unistd.h>
20
21 #include "storage/s_lock.h"
22
23 slock_t         dummy_spinlock;
24
25 static int      spins_per_delay = DEFAULT_SPINS_PER_DELAY;
26
27
28 /*
29  * s_lock_stuck() - complain about a stuck spinlock
30  */
31 static void
32 s_lock_stuck(volatile slock_t *lock, const char *file, int line)
33 {
34 #if defined(S_LOCK_TEST)
35         fprintf(stderr,
36                         "\nStuck spinlock (%p) detected at %s:%d.\n",
37                         lock, file, line);
38         exit(1);
39 #else
40         elog(PANIC, "stuck spinlock (%p) detected at %s:%d",
41                  lock, file, line);
42 #endif
43 }
44
45
46 /*
47  * s_lock(lock) - platform-independent portion of waiting for a spinlock.
48  */
49 int
50 s_lock(volatile slock_t *lock, const char *file, int line)
51 {
52         /*
53          * We loop tightly for awhile, then delay using pg_usleep() and try again.
54          * Preferably, "awhile" should be a small multiple of the maximum time we
55          * expect a spinlock to be held.  100 iterations seems about right as an
56          * initial guess.  However, on a uniprocessor the loop is a waste of
57          * cycles, while in a multi-CPU scenario it's usually better to spin a bit
58          * longer than to call the kernel, so we try to adapt the spin loop count
59          * depending on whether we seem to be in a uniprocessor or multiprocessor.
60          *
61          * Note: you might think MIN_SPINS_PER_DELAY should be just 1, but you'd
62          * be wrong; there are platforms where that can result in a "stuck
63          * spinlock" failure.  This has been seen particularly on Alphas; it seems
64          * that the first TAS after returning from kernel space will always fail
65          * on that hardware.
66          *
67          * Once we do decide to block, we use randomly increasing pg_usleep()
68          * delays. The first delay is 1 msec, then the delay randomly increases to
69          * about one second, after which we reset to 1 msec and start again.  The
70          * idea here is that in the presence of heavy contention we need to
71          * increase the delay, else the spinlock holder may never get to run and
72          * release the lock.  (Consider situation where spinlock holder has been
73          * nice'd down in priority by the scheduler --- it will not get scheduled
74          * until all would-be acquirers are sleeping, so if we always use a 1-msec
75          * sleep, there is a real possibility of starvation.)  But we can't just
76          * clamp the delay to an upper bound, else it would take a long time to
77          * make a reasonable number of tries.
78          *
79          * We time out and declare error after NUM_DELAYS delays (thus, exactly
80          * that many tries).  With the given settings, this will usually take 2 or
81          * so minutes.  It seems better to fix the total number of tries (and thus
82          * the probability of unintended failure) than to fix the total time
83          * spent.
84          *
85          * The pg_usleep() delays are measured in milliseconds because 1 msec is a
86          * common resolution limit at the OS level for newer platforms. On older
87          * platforms the resolution limit is usually 10 msec, in which case the
88          * total delay before timeout will be a bit more.
89          */
90 #define MIN_SPINS_PER_DELAY 10
91 #define MAX_SPINS_PER_DELAY 1000
92 #define NUM_DELAYS                      1000
93 #define MIN_DELAY_MSEC          1
94 #define MAX_DELAY_MSEC          1000
95
96         int                     spins = 0;
97         int                     delays = 0;
98         int                     cur_delay = 0;
99
100         while (TAS_SPIN(lock))
101         {
102                 /* CPU-specific delay each time through the loop */
103                 SPIN_DELAY();
104
105                 /* Block the process every spins_per_delay tries */
106                 if (++spins >= spins_per_delay)
107                 {
108                         if (++delays > NUM_DELAYS)
109                                 s_lock_stuck(lock, file, line);
110
111                         if (cur_delay == 0) /* first time to delay? */
112                                 cur_delay = MIN_DELAY_MSEC;
113
114                         pg_usleep(cur_delay * 1000L);
115
116 #if defined(S_LOCK_TEST)
117                         fprintf(stdout, "*");
118                         fflush(stdout);
119 #endif
120
121                         /* increase delay by a random fraction between 1X and 2X */
122                         cur_delay += (int) (cur_delay *
123                                           ((double) random() / (double) MAX_RANDOM_VALUE) + 0.5);
124                         /* wrap back to minimum delay when max is exceeded */
125                         if (cur_delay > MAX_DELAY_MSEC)
126                                 cur_delay = MIN_DELAY_MSEC;
127
128                         spins = 0;
129                 }
130         }
131
132         /*
133          * If we were able to acquire the lock without delaying, it's a good
134          * indication we are in a multiprocessor.  If we had to delay, it's a sign
135          * (but not a sure thing) that we are in a uniprocessor. Hence, we
136          * decrement spins_per_delay slowly when we had to delay, and increase it
137          * rapidly when we didn't.  It's expected that spins_per_delay will
138          * converge to the minimum value on a uniprocessor and to the maximum
139          * value on a multiprocessor.
140          *
141          * Note: spins_per_delay is local within our current process. We want to
142          * average these observations across multiple backends, since it's
143          * relatively rare for this function to even get entered, and so a single
144          * backend might not live long enough to converge on a good value.      That
145          * is handled by the two routines below.
146          */
147         if (cur_delay == 0)
148         {
149                 /* we never had to delay */
150                 if (spins_per_delay < MAX_SPINS_PER_DELAY)
151                         spins_per_delay = Min(spins_per_delay + 100, MAX_SPINS_PER_DELAY);
152         }
153         else
154         {
155                 if (spins_per_delay > MIN_SPINS_PER_DELAY)
156                         spins_per_delay = Max(spins_per_delay - 1, MIN_SPINS_PER_DELAY);
157         }
158         return delays;
159 }
160
161
162 /*
163  * Set local copy of spins_per_delay during backend startup.
164  *
165  * NB: this has to be pretty fast as it is called while holding a spinlock
166  */
167 void
168 set_spins_per_delay(int shared_spins_per_delay)
169 {
170         spins_per_delay = shared_spins_per_delay;
171 }
172
173 /*
174  * Update shared estimate of spins_per_delay during backend exit.
175  *
176  * NB: this has to be pretty fast as it is called while holding a spinlock
177  */
178 int
179 update_spins_per_delay(int shared_spins_per_delay)
180 {
181         /*
182          * We use an exponential moving average with a relatively slow adaption
183          * rate, so that noise in any one backend's result won't affect the shared
184          * value too much.      As long as both inputs are within the allowed range,
185          * the result must be too, so we need not worry about clamping the result.
186          *
187          * We deliberately truncate rather than rounding; this is so that single
188          * adjustments inside a backend can affect the shared estimate (see the
189          * asymmetric adjustment rules above).
190          */
191         return (shared_spins_per_delay * 15 + spins_per_delay) / 16;
192 }
193
194
195 /*
196  * Various TAS implementations that cannot live in s_lock.h as no inline
197  * definition exists (yet).
198  * In the future, get rid of tas.[cso] and fold it into this file.
199  *
200  * If you change something here, you will likely need to modify s_lock.h too,
201  * because the definitions for these are split between this file and s_lock.h.
202  */
203
204
205 #ifdef HAVE_SPINLOCKS                   /* skip spinlocks if requested */
206
207
208 #if defined(__GNUC__)
209
210 /*
211  * All the gcc flavors that are not inlined
212  */
213
214
215 /*
216  * Note: all the if-tests here probably ought to be testing gcc version
217  * rather than platform, but I don't have adequate info to know what to
218  * write.  Ideally we'd flush all this in favor of the inline version.
219  */
220 #if defined(__m68k__) && !defined(__linux__)
221 /* really means: extern int tas(slock_t* **lock); */
222 static void
223 tas_dummy()
224 {
225         __asm__         __volatile__(
226 #if defined(__NetBSD__) && defined(__ELF__)
227 /* no underscore for label and % for registers */
228                                                                                  "\
229 .global         tas                             \n\
230 tas:                                                    \n\
231                         movel   %sp@(0x4),%a0   \n\
232                         tas     %a0@            \n\
233                         beq     _success        \n\
234                         moveq   #-128,%d0       \n\
235                         rts                             \n\
236 _success:                                               \n\
237                         moveq   #0,%d0          \n\
238                         rts                             \n"
239 #else
240                                                                                  "\
241 .global         _tas                            \n\
242 _tas:                                                   \n\
243                         movel   sp@(0x4),a0     \n\
244                         tas     a0@                     \n\
245                         beq     _success        \n\
246                         moveq   #-128,d0        \n\
247                         rts                                     \n\
248 _success:                                               \n\
249                         moveq   #0,d0           \n\
250                         rts                                     \n"
251 #endif   /* __NetBSD__ && __ELF__ */
252         );
253 }
254 #endif   /* __m68k__ && !__linux__ */
255 #else                                                   /* not __GNUC__ */
256
257 /*
258  * All non gcc
259  */
260
261
262 #if defined(sun3)
263 static void
264 tas_dummy()                                             /* really means: extern int tas(slock_t
265                                                                  * *lock); */
266 {
267         asm("LLA0:");
268         asm("   .data");
269         asm("   .text");
270         asm("|#PROC# 04");
271         asm("   .globl  _tas");
272         asm("_tas:");
273         asm("|#PROLOGUE# 1");
274         asm("   movel   sp@(0x4),a0");
275         asm("   tas a0@");
276         asm("   beq LLA1");
277         asm("   moveq   #-128,d0");
278         asm("   rts");
279         asm("LLA1:");
280         asm("   moveq   #0,d0");
281         asm("   rts");
282         asm("   .data");
283 }
284 #endif   /* sun3 */
285 #endif   /* not __GNUC__ */
286 #endif   /* HAVE_SPINLOCKS */
287
288
289
290 /*****************************************************************************/
291 #if defined(S_LOCK_TEST)
292
293 /*
294  * test program for verifying a port's spinlock support.
295  */
296
297 struct test_lock_struct
298 {
299         char            pad1;
300         slock_t         lock;
301         char            pad2;
302 };
303
304 volatile struct test_lock_struct test_lock;
305
306 int
307 main()
308 {
309         srandom((unsigned int) time(NULL));
310
311         test_lock.pad1 = test_lock.pad2 = 0x44;
312
313         S_INIT_LOCK(&test_lock.lock);
314
315         if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
316         {
317                 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
318                 return 1;
319         }
320
321         if (!S_LOCK_FREE(&test_lock.lock))
322         {
323                 printf("S_LOCK_TEST: failed, lock not initialized\n");
324                 return 1;
325         }
326
327         S_LOCK(&test_lock.lock);
328
329         if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
330         {
331                 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
332                 return 1;
333         }
334
335         if (S_LOCK_FREE(&test_lock.lock))
336         {
337                 printf("S_LOCK_TEST: failed, lock not locked\n");
338                 return 1;
339         }
340
341         S_UNLOCK(&test_lock.lock);
342
343         if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
344         {
345                 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
346                 return 1;
347         }
348
349         if (!S_LOCK_FREE(&test_lock.lock))
350         {
351                 printf("S_LOCK_TEST: failed, lock not unlocked\n");
352                 return 1;
353         }
354
355         S_LOCK(&test_lock.lock);
356
357         if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
358         {
359                 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
360                 return 1;
361         }
362
363         if (S_LOCK_FREE(&test_lock.lock))
364         {
365                 printf("S_LOCK_TEST: failed, lock not re-locked\n");
366                 return 1;
367         }
368
369         printf("S_LOCK_TEST: this will print %d stars and then\n", NUM_DELAYS);
370         printf("             exit with a 'stuck spinlock' message\n");
371         printf("             if S_LOCK() and TAS() are working.\n");
372         fflush(stdout);
373
374         s_lock(&test_lock.lock, __FILE__, __LINE__);
375
376         printf("S_LOCK_TEST: failed, lock not locked\n");
377         return 1;
378 }
379
380 #endif   /* S_LOCK_TEST */