kern_turnstile.c revision 1.53 1 /* $NetBSD: kern_turnstile.c,v 1.53 2023/10/08 13:23:05 ad Exp $ */
2
3 /*-
4 * Copyright (c) 2002, 2006, 2007, 2009, 2019, 2020, 2023
5 * The NetBSD Foundation, Inc.
6 * All rights reserved.
7 *
8 * This code is derived from software contributed to The NetBSD Foundation
9 * by Jason R. Thorpe and Andrew Doran.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
31 */
32
33 /*
34 * Turnstiles are described in detail in:
35 *
36 * Solaris Internals: Core Kernel Architecture, Jim Mauro and
37 * Richard McDougall.
38 *
39 * Turnstiles are kept in a hash table. There are likely to be many more
40 * synchronisation objects than there are threads. Since a thread can block
41 * on only one lock at a time, we only need one turnstile per thread, and
42 * so they are allocated at thread creation time.
43 *
44 * When a thread decides it needs to block on a lock, it looks up the
45 * active turnstile for that lock. If no active turnstile exists, then
46 * the process lends its turnstile to the lock. If there is already an
47 * active turnstile for the lock, the thread places its turnstile on a
48 * list of free turnstiles, and references the active one instead.
49 *
50 * The act of looking up the turnstile acquires an interlock on the sleep
51 * queue. If a thread decides it doesn't need to block after all, then this
52 * interlock must be released by explicitly aborting the turnstile
53 * operation.
54 *
55 * When a thread is awakened, it needs to get its turnstile back. If there
56 * are still other threads waiting in the active turnstile, the thread
57 * grabs a free turnstile off the free list. Otherwise, it can take back
58 * the active turnstile from the lock (thus deactivating the turnstile).
59 *
60 * Turnstiles are where we do priority inheritence.
61 */
62
63 #include <sys/cdefs.h>
64 __KERNEL_RCSID(0, "$NetBSD: kern_turnstile.c,v 1.53 2023/10/08 13:23:05 ad Exp $");
65
66 #include <sys/param.h>
67 #include <sys/lockdebug.h>
68 #include <sys/proc.h>
69 #include <sys/sleepq.h>
70 #include <sys/sleeptab.h>
71 #include <sys/systm.h>
72
73 /*
74 * Shift of 6 aligns to typical cache line size of 64 bytes; there's no
75 * point having two turnstile locks to back two lock objects that share one
76 * cache line.
77 */
78 #define TS_HASH_SIZE 128
79 #define TS_HASH_MASK (TS_HASH_SIZE - 1)
80 #define TS_HASH(obj) (((uintptr_t)(obj) >> 6) & TS_HASH_MASK)
81
82 static tschain_t turnstile_chains[TS_HASH_SIZE] __cacheline_aligned;
83
84 static union {
85 kmutex_t lock;
86 uint8_t pad[COHERENCY_UNIT];
87 } turnstile_locks[TS_HASH_SIZE] __cacheline_aligned;
88
89 /*
90 * turnstile_init:
91 *
92 * Initialize the turnstile mechanism.
93 */
94 void
95 turnstile_init(void)
96 {
97 int i;
98
99 for (i = 0; i < TS_HASH_SIZE; i++) {
100 LIST_INIT(&turnstile_chains[i]);
101 mutex_init(&turnstile_locks[i].lock, MUTEX_DEFAULT, IPL_SCHED);
102 }
103
104 turnstile_ctor(&turnstile0);
105 }
106
107 /*
108 * turnstile_ctor:
109 *
110 * Constructor for turnstiles.
111 */
112 void
113 turnstile_ctor(turnstile_t *ts)
114 {
115
116 memset(ts, 0, sizeof(*ts));
117 sleepq_init(&ts->ts_sleepq[TS_READER_Q]);
118 sleepq_init(&ts->ts_sleepq[TS_WRITER_Q]);
119 }
120
121 /*
122 * turnstile_remove:
123 *
124 * Remove an LWP from a turnstile sleep queue and wake it.
125 */
126 static inline void
127 turnstile_remove(turnstile_t *ts, lwp_t *l, int q)
128 {
129 turnstile_t *nts;
130
131 KASSERT(l->l_ts == ts);
132
133 /*
134 * This process is no longer using the active turnstile.
135 * Find an inactive one on the free list to give to it.
136 */
137 if ((nts = ts->ts_free) != NULL) {
138 KASSERT(TS_ALL_WAITERS(ts) > 1);
139 l->l_ts = nts;
140 ts->ts_free = nts->ts_free;
141 nts->ts_free = NULL;
142 } else {
143 /*
144 * If the free list is empty, this is the last
145 * waiter.
146 */
147 KASSERT(TS_ALL_WAITERS(ts) == 1);
148 LIST_REMOVE(ts, ts_chain);
149 }
150
151 ts->ts_waiters[q]--;
152 sleepq_remove(&ts->ts_sleepq[q], l, true);
153 }
154
155 /*
156 * turnstile_lookup:
157 *
158 * Look up the turnstile for the specified lock. This acquires and
159 * holds the turnstile chain lock (sleep queue interlock).
160 */
161 turnstile_t *
162 turnstile_lookup(wchan_t obj)
163 {
164 turnstile_t *ts;
165 tschain_t *tc;
166 u_int hash;
167
168 hash = TS_HASH(obj);
169 tc = &turnstile_chains[hash];
170 mutex_spin_enter(&turnstile_locks[hash].lock);
171
172 LIST_FOREACH(ts, tc, ts_chain)
173 if (ts->ts_obj == obj)
174 return (ts);
175
176 /*
177 * No turnstile yet for this lock. No problem, turnstile_block()
178 * handles this by fetching the turnstile from the blocking thread.
179 */
180 return (NULL);
181 }
182
183 /*
184 * turnstile_exit:
185 *
186 * Abort a turnstile operation.
187 */
188 void
189 turnstile_exit(wchan_t obj)
190 {
191
192 mutex_spin_exit(&turnstile_locks[TS_HASH(obj)].lock);
193 }
194
195 /*
196 * turnstile_lendpri:
197 *
198 * Lend our priority to lwps on the blocking chain.
199 *
200 * If the current owner of the lock (l->l_wchan, set by sleepq_enqueue)
201 * has a priority lower than ours (lwp_eprio(l)), lend our priority to
202 * him to avoid priority inversions.
203 */
204
205 static void
206 turnstile_lendpri(lwp_t *cur)
207 {
208 lwp_t * l = cur;
209 pri_t prio;
210
211 /*
212 * NOTE: if you get a panic in this code block, it is likely that
213 * a lock has been destroyed or corrupted while still in use. Try
214 * compiling a kernel with LOCKDEBUG to pinpoint the problem.
215 */
216
217 LOCKDEBUG_BARRIER(l->l_mutex, 1);
218 KASSERT(l == curlwp);
219 prio = lwp_eprio(l);
220 for (;;) {
221 lwp_t *owner;
222 turnstile_t *ts;
223 bool dolock;
224
225 if (l->l_wchan == NULL)
226 break;
227
228 /*
229 * Ask syncobj the owner of the lock.
230 */
231 owner = (*l->l_syncobj->sobj_owner)(l->l_wchan);
232 if (owner == NULL)
233 break;
234
235 /*
236 * The owner may have changed as we have dropped the tc lock.
237 */
238 if (cur == owner) {
239 /*
240 * We own the lock: stop here, sleepq_block()
241 * should wake up immediately.
242 */
243 break;
244 }
245 /*
246 * Acquire owner->l_mutex if we don't have it yet.
247 * Because we already have another LWP lock (l->l_mutex) held,
248 * we need to play a try lock dance to avoid deadlock.
249 */
250 dolock = l->l_mutex != atomic_load_relaxed(&owner->l_mutex);
251 if (l == owner || (dolock && !lwp_trylock(owner))) {
252 /*
253 * The owner was changed behind us or trylock failed.
254 * Restart from curlwp.
255 *
256 * Note that there may be a livelock here:
257 * the owner may try grabbing cur's lock (which is the
258 * tc lock) while we're trying to grab the owner's lock.
259 */
260 lwp_unlock(l);
261 l = cur;
262 lwp_lock(l);
263 prio = lwp_eprio(l);
264 continue;
265 }
266 /*
267 * If the owner's priority is already higher than ours,
268 * there's nothing to do anymore.
269 */
270 if (prio <= lwp_eprio(owner)) {
271 if (dolock)
272 lwp_unlock(owner);
273 break;
274 }
275 /*
276 * Lend our priority to the 'owner' LWP.
277 *
278 * Update lenders info for turnstile_unlendpri.
279 */
280 ts = l->l_ts;
281 KASSERT(ts->ts_inheritor == owner || ts->ts_inheritor == NULL);
282 if (ts->ts_inheritor == NULL) {
283 ts->ts_inheritor = owner;
284 ts->ts_eprio = prio;
285 SLIST_INSERT_HEAD(&owner->l_pi_lenders, ts, ts_pichain);
286 lwp_lendpri(owner, prio);
287 } else if (prio > ts->ts_eprio) {
288 ts->ts_eprio = prio;
289 lwp_lendpri(owner, prio);
290 }
291 if (dolock)
292 lwp_unlock(l);
293 LOCKDEBUG_BARRIER(owner->l_mutex, 1);
294 l = owner;
295 }
296 LOCKDEBUG_BARRIER(l->l_mutex, 1);
297 if (cur->l_mutex != atomic_load_relaxed(&l->l_mutex)) {
298 lwp_unlock(l);
299 lwp_lock(cur);
300 }
301 LOCKDEBUG_BARRIER(cur->l_mutex, 1);
302 }
303
304 /*
305 * turnstile_unlendpri: undo turnstile_lendpri
306 */
307
308 static void
309 turnstile_unlendpri(turnstile_t *ts)
310 {
311 lwp_t * const l = curlwp;
312 turnstile_t *iter;
313 turnstile_t *next;
314 turnstile_t *prev = NULL;
315 pri_t prio;
316 bool dolock;
317
318 KASSERT(ts->ts_inheritor != NULL);
319 ts->ts_inheritor = NULL;
320 dolock = (atomic_load_relaxed(&l->l_mutex) ==
321 l->l_cpu->ci_schedstate.spc_lwplock);
322 if (dolock) {
323 lwp_lock(l);
324 }
325
326 /*
327 * the following loop does two things.
328 *
329 * - remove ts from the list.
330 *
331 * - from the rest of the list, find the highest priority.
332 */
333
334 prio = -1;
335 KASSERT(!SLIST_EMPTY(&l->l_pi_lenders));
336 for (iter = SLIST_FIRST(&l->l_pi_lenders);
337 iter != NULL; iter = next) {
338 KASSERT(lwp_eprio(l) >= ts->ts_eprio);
339 next = SLIST_NEXT(iter, ts_pichain);
340 if (iter == ts) {
341 if (prev == NULL) {
342 SLIST_REMOVE_HEAD(&l->l_pi_lenders,
343 ts_pichain);
344 } else {
345 SLIST_REMOVE_AFTER(prev, ts_pichain);
346 }
347 } else if (prio < iter->ts_eprio) {
348 prio = iter->ts_eprio;
349 }
350 prev = iter;
351 }
352
353 lwp_lendpri(l, prio);
354
355 if (dolock) {
356 lwp_unlock(l);
357 }
358 }
359
360 /*
361 * turnstile_block:
362 *
363 * Enter an object into the turnstile chain and prepare the current
364 * LWP for sleep.
365 */
366 void
367 turnstile_block(turnstile_t *ts, int q, wchan_t obj, syncobj_t *sobj)
368 {
369 lwp_t * const l = curlwp; /* cached curlwp */
370 turnstile_t *ots;
371 tschain_t *tc;
372 kmutex_t *lock;
373 sleepq_t *sq;
374 u_int hash;
375 int nlocks;
376
377 hash = TS_HASH(obj);
378 tc = &turnstile_chains[hash];
379 lock = &turnstile_locks[hash].lock;
380
381 KASSERT(q == TS_READER_Q || q == TS_WRITER_Q);
382 KASSERT(mutex_owned(lock));
383 KASSERT(l != NULL);
384 KASSERT(l->l_ts != NULL);
385
386 if (ts == NULL) {
387 /*
388 * We are the first thread to wait for this object;
389 * lend our turnstile to it.
390 */
391 ts = l->l_ts;
392 KASSERT(TS_ALL_WAITERS(ts) == 0);
393 KASSERT(LIST_EMPTY(&ts->ts_sleepq[TS_READER_Q]));
394 KASSERT(LIST_EMPTY(&ts->ts_sleepq[TS_WRITER_Q]));
395 ts->ts_obj = obj;
396 ts->ts_inheritor = NULL;
397 LIST_INSERT_HEAD(tc, ts, ts_chain);
398 } else {
399 /*
400 * Object already has a turnstile. Put our turnstile
401 * onto the free list, and reference the existing
402 * turnstile instead.
403 */
404 ots = l->l_ts;
405 KASSERT(ots->ts_free == NULL);
406 ots->ts_free = ts->ts_free;
407 ts->ts_free = ots;
408 l->l_ts = ts;
409
410 KASSERT(ts->ts_obj == obj);
411 KASSERT(TS_ALL_WAITERS(ts) != 0);
412 KASSERT(!LIST_EMPTY(&ts->ts_sleepq[TS_READER_Q]) ||
413 !LIST_EMPTY(&ts->ts_sleepq[TS_WRITER_Q]));
414 }
415
416 sq = &ts->ts_sleepq[q];
417 ts->ts_waiters[q]++;
418 nlocks = sleepq_enter(sq, l, lock);
419 LOCKDEBUG_BARRIER(lock, 1);
420 sleepq_enqueue(sq, obj, sobj->sobj_name, sobj, false);
421
422 /*
423 * Disable preemption across this entire block, as we may drop
424 * scheduler locks (allowing preemption), and would prefer not
425 * to be interrupted while in a state of flux.
426 */
427 KPREEMPT_DISABLE(l);
428 KASSERT(lock == l->l_mutex);
429 turnstile_lendpri(l);
430 sleepq_block(0, false, sobj, nlocks);
431 KPREEMPT_ENABLE(l);
432 }
433
434 /*
435 * turnstile_wakeup:
436 *
437 * Wake up the specified number of threads that are blocked
438 * in a turnstile.
439 */
440 void
441 turnstile_wakeup(turnstile_t *ts, int q, int count, lwp_t *nl)
442 {
443 sleepq_t *sq;
444 kmutex_t *lock;
445 u_int hash;
446 lwp_t *l;
447
448 hash = TS_HASH(ts->ts_obj);
449 lock = &turnstile_locks[hash].lock;
450 sq = &ts->ts_sleepq[q];
451
452 KASSERT(q == TS_READER_Q || q == TS_WRITER_Q);
453 KASSERT(count > 0);
454 KASSERT(count <= TS_WAITERS(ts, q));
455 KASSERT(mutex_owned(lock));
456 KASSERT(ts->ts_inheritor == curlwp || ts->ts_inheritor == NULL);
457
458 /*
459 * restore inherited priority if necessary.
460 */
461
462 if (ts->ts_inheritor != NULL) {
463 turnstile_unlendpri(ts);
464 }
465
466 if (nl != NULL) {
467 #if defined(DEBUG) || defined(LOCKDEBUG)
468 LIST_FOREACH(l, sq, l_sleepchain) {
469 if (l == nl)
470 break;
471 }
472 if (l == NULL)
473 panic("turnstile_wakeup: nl not on sleepq");
474 #endif
475 turnstile_remove(ts, nl, q);
476 } else {
477 while (count-- > 0) {
478 l = LIST_FIRST(sq);
479 KASSERT(l != NULL);
480 turnstile_remove(ts, l, q);
481 }
482 }
483 mutex_spin_exit(lock);
484 }
485
486 /*
487 * turnstile_unsleep:
488 *
489 * Remove an LWP from the turnstile. This is called when the LWP has
490 * not been awoken normally but instead interrupted: for example, if it
491 * has received a signal. It's not a valid action for turnstiles,
492 * since LWPs blocking on a turnstile are not interruptable.
493 */
494 void
495 turnstile_unsleep(lwp_t *l, bool cleanup)
496 {
497
498 lwp_unlock(l);
499 panic("turnstile_unsleep");
500 }
501
502 /*
503 * turnstile_changepri:
504 *
505 * Adjust the priority of an LWP residing on a turnstile.
506 */
507 void
508 turnstile_changepri(lwp_t *l, pri_t pri)
509 {
510
511 /* XXX priority inheritance */
512 sleepq_changepri(l, pri);
513 }
514
515 #if defined(LOCKDEBUG)
516 /*
517 * turnstile_print:
518 *
519 * Given the address of a lock object, print the contents of a
520 * turnstile.
521 */
522 void
523 turnstile_print(volatile void *obj, void (*pr)(const char *, ...))
524 {
525 turnstile_t *ts;
526 tschain_t *tc;
527 sleepq_t *rsq, *wsq;
528 u_int hash;
529 lwp_t *l;
530
531 hash = TS_HASH(obj);
532 tc = &turnstile_chains[hash];
533
534 LIST_FOREACH(ts, tc, ts_chain)
535 if (ts->ts_obj == obj)
536 break;
537
538 if (ts == NULL) {
539 (*pr)("Turnstile: no active turnstile for this lock.\n");
540 return;
541 }
542
543 rsq = &ts->ts_sleepq[TS_READER_Q];
544 wsq = &ts->ts_sleepq[TS_WRITER_Q];
545
546 (*pr)("Turnstile:\n");
547 (*pr)("=> %d waiting readers:", TS_WAITERS(ts, TS_READER_Q));
548 LIST_FOREACH(l, rsq, l_sleepchain) {
549 (*pr)(" %p", l);
550 }
551 (*pr)("\n");
552
553 (*pr)("=> %d waiting writers:", TS_WAITERS(ts, TS_WRITER_Q));
554 LIST_FOREACH(l, wsq, l_sleepchain) {
555 (*pr)(" %p", l);
556 }
557 (*pr)("\n");
558 }
559 #endif /* LOCKDEBUG */
560