1 /*-------------------------------------------------------------------------
4 * Hardware-dependent implementation of spinlocks.
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.
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
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.
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
39 * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
40 * Portions Copyright (c) 1994, Regents of the University of California
44 * src/backend/storage/lmgr/s_lock.c
46 *-------------------------------------------------------------------------
53 #include "common/pg_prng.h"
54 #include "port/atomics.h"
55 #include "storage/s_lock.h"
56 #include "utils/wait_event.h"
58 #define MIN_SPINS_PER_DELAY 10
59 #define MAX_SPINS_PER_DELAY 1000
60 #define NUM_DELAYS 1000
61 #define MIN_DELAY_USEC 1000L
62 #define MAX_DELAY_USEC 1000000L
66 * These are needed by pgstat_report_wait_start in the standalone compile of
69 static uint32 local_my_wait_event_info
;
70 uint32
*my_wait_event_info
= &local_my_wait_event_info
;
73 slock_t dummy_spinlock
;
75 static int spins_per_delay
= DEFAULT_SPINS_PER_DELAY
;
79 * s_lock_stuck() - complain about a stuck spinlock
82 s_lock_stuck(const char *file
, int line
, const char *func
)
86 #if defined(S_LOCK_TEST)
88 "\nStuck spinlock detected at %s, %s:%d.\n",
92 elog(PANIC
, "stuck spinlock detected at %s, %s:%d",
98 * s_lock(lock) - platform-independent portion of waiting for a spinlock.
101 s_lock(volatile slock_t
*lock
, const char *file
, int line
, const char *func
)
103 SpinDelayStatus delayStatus
;
105 init_spin_delay(&delayStatus
, file
, line
, func
);
107 while (TAS_SPIN(lock
))
109 perform_spin_delay(&delayStatus
);
112 finish_spin_delay(&delayStatus
);
114 return delayStatus
.delays
;
117 #ifdef USE_DEFAULT_S_UNLOCK
119 s_unlock(volatile slock_t
*lock
)
121 #ifdef TAS_ACTIVE_WORD
123 *TAS_ACTIVE_WORD(lock
) = -1;
131 * Wait while spinning on a contended spinlock.
134 perform_spin_delay(SpinDelayStatus
*status
)
136 /* CPU-specific delay each time through the loop */
139 /* Block the process every spins_per_delay tries */
140 if (++(status
->spins
) >= spins_per_delay
)
142 if (++(status
->delays
) > NUM_DELAYS
)
143 s_lock_stuck(status
->file
, status
->line
, status
->func
);
145 if (status
->cur_delay
== 0) /* first time to delay? */
146 status
->cur_delay
= MIN_DELAY_USEC
;
149 * Once we start sleeping, the overhead of reporting a wait event is
150 * justified. Actively spinning easily stands out in profilers, but
151 * sleeping with an exponential backoff is harder to spot...
153 * We might want to report something more granular at some point, but
154 * this is better than nothing.
156 pgstat_report_wait_start(WAIT_EVENT_SPIN_DELAY
);
157 pg_usleep(status
->cur_delay
);
158 pgstat_report_wait_end();
160 #if defined(S_LOCK_TEST)
161 fprintf(stdout
, "*");
165 /* increase delay by a random fraction between 1X and 2X */
166 status
->cur_delay
+= (int) (status
->cur_delay
*
167 pg_prng_double(&pg_global_prng_state
) + 0.5);
168 /* wrap back to minimum delay when max is exceeded */
169 if (status
->cur_delay
> MAX_DELAY_USEC
)
170 status
->cur_delay
= MIN_DELAY_USEC
;
177 * After acquiring a spinlock, update estimates about how long to loop.
179 * If we were able to acquire the lock without delaying, it's a good
180 * indication we are in a multiprocessor. If we had to delay, it's a sign
181 * (but not a sure thing) that we are in a uniprocessor. Hence, we
182 * decrement spins_per_delay slowly when we had to delay, and increase it
183 * rapidly when we didn't. It's expected that spins_per_delay will
184 * converge to the minimum value on a uniprocessor and to the maximum
185 * value on a multiprocessor.
187 * Note: spins_per_delay is local within our current process. We want to
188 * average these observations across multiple backends, since it's
189 * relatively rare for this function to even get entered, and so a single
190 * backend might not live long enough to converge on a good value. That
191 * is handled by the two routines below.
194 finish_spin_delay(SpinDelayStatus
*status
)
196 if (status
->cur_delay
== 0)
198 /* we never had to delay */
199 if (spins_per_delay
< MAX_SPINS_PER_DELAY
)
200 spins_per_delay
= Min(spins_per_delay
+ 100, MAX_SPINS_PER_DELAY
);
204 if (spins_per_delay
> MIN_SPINS_PER_DELAY
)
205 spins_per_delay
= Max(spins_per_delay
- 1, MIN_SPINS_PER_DELAY
);
210 * Set local copy of spins_per_delay during backend startup.
212 * NB: this has to be pretty fast as it is called while holding a spinlock
215 set_spins_per_delay(int shared_spins_per_delay
)
217 spins_per_delay
= shared_spins_per_delay
;
221 * Update shared estimate of spins_per_delay during backend exit.
223 * NB: this has to be pretty fast as it is called while holding a spinlock
226 update_spins_per_delay(int shared_spins_per_delay
)
229 * We use an exponential moving average with a relatively slow adaption
230 * rate, so that noise in any one backend's result won't affect the shared
231 * value too much. As long as both inputs are within the allowed range,
232 * the result must be too, so we need not worry about clamping the result.
234 * We deliberately truncate rather than rounding; this is so that single
235 * adjustments inside a backend can affect the shared estimate (see the
236 * asymmetric adjustment rules above).
238 return (shared_spins_per_delay
* 15 + spins_per_delay
) / 16;
242 /*****************************************************************************/
243 #if defined(S_LOCK_TEST)
246 * test program for verifying a port's spinlock support.
249 struct test_lock_struct
256 volatile struct test_lock_struct test_lock
;
261 pg_prng_seed(&pg_global_prng_state
, (uint64
) time(NULL
));
263 test_lock
.pad1
= test_lock
.pad2
= 0x44;
265 S_INIT_LOCK(&test_lock
.lock
);
267 if (test_lock
.pad1
!= 0x44 || test_lock
.pad2
!= 0x44)
269 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
273 if (!S_LOCK_FREE(&test_lock
.lock
))
275 printf("S_LOCK_TEST: failed, lock not initialized\n");
279 S_LOCK(&test_lock
.lock
);
281 if (test_lock
.pad1
!= 0x44 || test_lock
.pad2
!= 0x44)
283 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
287 if (S_LOCK_FREE(&test_lock
.lock
))
289 printf("S_LOCK_TEST: failed, lock not locked\n");
293 S_UNLOCK(&test_lock
.lock
);
295 if (test_lock
.pad1
!= 0x44 || test_lock
.pad2
!= 0x44)
297 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
301 if (!S_LOCK_FREE(&test_lock
.lock
))
303 printf("S_LOCK_TEST: failed, lock not unlocked\n");
307 S_LOCK(&test_lock
.lock
);
309 if (test_lock
.pad1
!= 0x44 || test_lock
.pad2
!= 0x44)
311 printf("S_LOCK_TEST: failed, declared datatype is wrong size\n");
315 if (S_LOCK_FREE(&test_lock
.lock
))
317 printf("S_LOCK_TEST: failed, lock not re-locked\n");
321 printf("S_LOCK_TEST: this will print %d stars and then\n", NUM_DELAYS
);
322 printf(" exit with a 'stuck spinlock' message\n");
323 printf(" if S_LOCK() and TAS() are working.\n");
326 s_lock(&test_lock
.lock
, __FILE__
, __LINE__
, __func__
);
328 printf("S_LOCK_TEST: failed, lock not locked\n");
332 #endif /* S_LOCK_TEST */