]> granicus.if.org Git - postgresql/blob - src/backend/storage/lmgr/s_lock.c
Stamp copyrights for year 2011.
[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-2011, 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
24 static int      spins_per_delay = DEFAULT_SPINS_PER_DELAY;
25
26
27 /*
28  * s_lock_stuck() - complain about a stuck spinlock
29  */
30 static void
31 s_lock_stuck(volatile slock_t *lock, const char *file, int line)
32 {
33 #if defined(S_LOCK_TEST)
34         fprintf(stderr,
35                         "\nStuck spinlock (%p) detected at %s:%d.\n",
36                         lock, file, line);
37         exit(1);
38 #else
39         elog(PANIC, "stuck spinlock (%p) detected at %s:%d",
40                  lock, file, line);
41 #endif
42 }
43
44
45 /*
46  * s_lock(lock) - platform-independent portion of waiting for a spinlock.
47  */
48 void
49 s_lock(volatile slock_t *lock, const char *file, int line)
50 {
51         /*
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.
59          *
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
64          * on that hardware.
65          *
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.
77          *
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
82          * spent.
83          *
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.
88          */
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
94
95         int                     spins = 0;
96         int                     delays = 0;
97         int                     cur_delay = 0;
98
99         while (TAS(lock))
100         {
101                 /* CPU-specific delay each time through the loop */
102                 SPIN_DELAY();
103
104                 /* Block the process every spins_per_delay tries */
105                 if (++spins >= spins_per_delay)
106                 {
107                         if (++delays > NUM_DELAYS)
108                                 s_lock_stuck(lock, file, line);
109
110                         if (cur_delay == 0) /* first time to delay? */
111                                 cur_delay = MIN_DELAY_MSEC;
112
113                         pg_usleep(cur_delay * 1000L);
114
115 #if defined(S_LOCK_TEST)
116                         fprintf(stdout, "*");
117                         fflush(stdout);
118 #endif
119
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;
126
127                         spins = 0;
128                 }
129         }
130
131         /*
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.
139          *
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.
145          */
146         if (cur_delay == 0)
147         {
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);
151         }
152         else
153         {
154                 if (spins_per_delay > MIN_SPINS_PER_DELAY)
155                         spins_per_delay = Max(spins_per_delay - 1, MIN_SPINS_PER_DELAY);
156         }
157 }
158
159
160 /*
161  * Set local copy of spins_per_delay during backend startup.
162  *
163  * NB: this has to be pretty fast as it is called while holding a spinlock
164  */
165 void
166 set_spins_per_delay(int shared_spins_per_delay)
167 {
168         spins_per_delay = shared_spins_per_delay;
169 }
170
171 /*
172  * Update shared estimate of spins_per_delay during backend exit.
173  *
174  * NB: this has to be pretty fast as it is called while holding a spinlock
175  */
176 int
177 update_spins_per_delay(int shared_spins_per_delay)
178 {
179         /*
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.
184          *
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).
188          */
189         return (shared_spins_per_delay * 15 + spins_per_delay) / 16;
190 }
191
192
193 /*
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.
197  *
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.
200  */
201
202
203 #ifdef HAVE_SPINLOCKS                   /* skip spinlocks if requested */
204
205
206 #if defined(__GNUC__)
207
208 /*
209  * All the gcc flavors that are not inlined
210  */
211
212
213 /*
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.
217  */
218 #if defined(__m68k__) && !defined(__linux__)
219 /* really means: extern int tas(slock_t* **lock); */
220 static void
221 tas_dummy()
222 {
223         __asm__         __volatile__(
224 #if defined(__NetBSD__) && defined(__ELF__)
225 /* no underscore for label and % for registers */
226                                                                                  "\
227 .global         tas                             \n\
228 tas:                                                    \n\
229                         movel   %sp@(0x4),%a0   \n\
230                         tas     %a0@            \n\
231                         beq     _success        \n\
232                         moveq   #-128,%d0       \n\
233                         rts                             \n\
234 _success:                                               \n\
235                         moveq   #0,%d0          \n\
236                         rts                             \n"
237 #else
238                                                                                  "\
239 .global         _tas                            \n\
240 _tas:                                                   \n\
241                         movel   sp@(0x4),a0     \n\
242                         tas     a0@                     \n\
243                         beq     _success        \n\
244                         moveq   #-128,d0        \n\
245                         rts                                     \n\
246 _success:                                               \n\
247                         moveq   #0,d0           \n\
248                         rts                                     \n"
249 #endif   /* __NetBSD__ && __ELF__ */
250         );
251 }
252 #endif   /* __m68k__ && !__linux__ */
253 #else                                                   /* not __GNUC__ */
254
255 /*
256  * All non gcc
257  */
258
259
260 #if defined(sun3)
261 static void
262 tas_dummy()                                             /* really means: extern int tas(slock_t
263                                                                  * *lock); */
264 {
265         asm("LLA0:");
266         asm("   .data");
267         asm("   .text");
268         asm("|#PROC# 04");
269         asm("   .globl  _tas");
270         asm("_tas:");
271         asm("|#PROLOGUE# 1");
272         asm("   movel   sp@(0x4),a0");
273         asm("   tas a0@");
274         asm("   beq LLA1");
275         asm("   moveq   #-128,d0");
276         asm("   rts");
277         asm("LLA1:");
278         asm("   moveq   #0,d0");
279         asm("   rts");
280         asm("   .data");
281 }
282 #endif   /* sun3 */
283 #endif   /* not __GNUC__ */
284 #endif   /* HAVE_SPINLOCKS */
285
286
287
288 /*****************************************************************************/
289 #if defined(S_LOCK_TEST)
290
291 /*
292  * test program for verifying a port's spinlock support.
293  */
294
295 struct test_lock_struct
296 {
297         char            pad1;
298         slock_t         lock;
299         char            pad2;
300 };
301
302 volatile struct test_lock_struct test_lock;
303
304 int
305 main()
306 {
307         srandom((unsigned int) time(NULL));
308
309         test_lock.pad1 = test_lock.pad2 = 0x44;
310
311         S_INIT_LOCK(&test_lock.lock);
312
313         if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
314         {
315                 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
316                 return 1;
317         }
318
319         if (!S_LOCK_FREE(&test_lock.lock))
320         {
321                 printf("S_LOCK_TEST: failed, lock not initialized\n");
322                 return 1;
323         }
324
325         S_LOCK(&test_lock.lock);
326
327         if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
328         {
329                 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
330                 return 1;
331         }
332
333         if (S_LOCK_FREE(&test_lock.lock))
334         {
335                 printf("S_LOCK_TEST: failed, lock not locked\n");
336                 return 1;
337         }
338
339         S_UNLOCK(&test_lock.lock);
340
341         if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
342         {
343                 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
344                 return 1;
345         }
346
347         if (!S_LOCK_FREE(&test_lock.lock))
348         {
349                 printf("S_LOCK_TEST: failed, lock not unlocked\n");
350                 return 1;
351         }
352
353         S_LOCK(&test_lock.lock);
354
355         if (test_lock.pad1 != 0x44 || test_lock.pad2 != 0x44)
356         {
357                 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
358                 return 1;
359         }
360
361         if (S_LOCK_FREE(&test_lock.lock))
362         {
363                 printf("S_LOCK_TEST: failed, lock not re-locked\n");
364                 return 1;
365         }
366
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");
370         fflush(stdout);
371
372         s_lock(&test_lock.lock, __FILE__, __LINE__);
373
374         printf("S_LOCK_TEST: failed, lock not locked\n");
375         return 1;
376 }
377
378 #endif   /* S_LOCK_TEST */