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