kern_turnstile.c revision 1.50 1 /* $NetBSD: kern_turnstile.c,v 1.50 2023/09/23 18:48:04 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.50 2023/09/23 18:48:04 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);
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
376 hash = TS_HASH(obj);
377 tc = &turnstile_chains[hash];
378 lock = &turnstile_locks[hash].lock;
379
380 KASSERT(q == TS_READER_Q || q == TS_WRITER_Q);
381 KASSERT(mutex_owned(lock));
382 KASSERT(l != NULL);
383 KASSERT(l->l_ts != NULL);
384
385 if (ts == NULL) {
386 /*
387 * We are the first thread to wait for this object;
388 * lend our turnstile to it.
389 */
390 ts = l->l_ts;
391 KASSERT(TS_ALL_WAITERS(ts) == 0);
392 KASSERT(LIST_EMPTY(&ts->ts_sleepq[TS_READER_Q]));
393 KASSERT(LIST_EMPTY(&ts->ts_sleepq[TS_WRITER_Q]));
394 ts->ts_obj = obj;
395 ts->ts_inheritor = NULL;
396 LIST_INSERT_HEAD(tc, ts, ts_chain);
397 } else {
398 /*
399 * Object already has a turnstile. Put our turnstile
400 * onto the free list, and reference the existing
401 * turnstile instead.
402 */
403 ots = l->l_ts;
404 KASSERT(ots->ts_free == NULL);
405 ots->ts_free = ts->ts_free;
406 ts->ts_free = ots;
407 l->l_ts = ts;
408
409 KASSERT(ts->ts_obj == obj);
410 KASSERT(TS_ALL_WAITERS(ts) != 0);
411 KASSERT(!LIST_EMPTY(&ts->ts_sleepq[TS_READER_Q]) ||
412 !LIST_EMPTY(&ts->ts_sleepq[TS_WRITER_Q]));
413 }
414
415 sq = &ts->ts_sleepq[q];
416 ts->ts_waiters[q]++;
417 sleepq_enter(sq, l, lock);
418 LOCKDEBUG_BARRIER(lock, 1);
419 sleepq_enqueue(sq, obj, "tstile", sobj, false);
420
421 /*
422 * Disable preemption across this entire block, as we may drop
423 * scheduler locks (allowing preemption), and would prefer not
424 * to be interrupted while in a state of flux.
425 */
426 KPREEMPT_DISABLE(l);
427 KASSERT(lock == l->l_mutex);
428 turnstile_lendpri(l);
429 sleepq_block(0, false, sobj);
430 KPREEMPT_ENABLE(l);
431 }
432
433 /*
434 * turnstile_wakeup:
435 *
436 * Wake up the specified number of threads that are blocked
437 * in a turnstile.
438 */
439 void
440 turnstile_wakeup(turnstile_t *ts, int q, int count, lwp_t *nl)
441 {
442 sleepq_t *sq;
443 kmutex_t *lock;
444 u_int hash;
445 lwp_t *l;
446
447 hash = TS_HASH(ts->ts_obj);
448 lock = &turnstile_locks[hash].lock;
449 sq = &ts->ts_sleepq[q];
450
451 KASSERT(q == TS_READER_Q || q == TS_WRITER_Q);
452 KASSERT(count > 0);
453 KASSERT(count <= TS_WAITERS(ts, q));
454 KASSERT(mutex_owned(lock));
455 KASSERT(ts->ts_inheritor == curlwp || ts->ts_inheritor == NULL);
456
457 /*
458 * restore inherited priority if necessary.
459 */
460
461 if (ts->ts_inheritor != NULL) {
462 turnstile_unlendpri(ts);
463 }
464
465 if (nl != NULL) {
466 #if defined(DEBUG) || defined(LOCKDEBUG)
467 LIST_FOREACH(l, sq, l_sleepchain) {
468 if (l == nl)
469 break;
470 }
471 if (l == NULL)
472 panic("turnstile_wakeup: nl not on sleepq");
473 #endif
474 turnstile_remove(ts, nl, q);
475 } else {
476 while (count-- > 0) {
477 l = LIST_FIRST(sq);
478 KASSERT(l != NULL);
479 turnstile_remove(ts, l, q);
480 }
481 }
482 mutex_spin_exit(lock);
483 }
484
485 /*
486 * turnstile_unsleep:
487 *
488 * Remove an LWP from the turnstile. This is called when the LWP has
489 * not been awoken normally but instead interrupted: for example, if it
490 * has received a signal. It's not a valid action for turnstiles,
491 * since LWPs blocking on a turnstile are not interruptable.
492 */
493 void
494 turnstile_unsleep(lwp_t *l, bool cleanup)
495 {
496
497 lwp_unlock(l);
498 panic("turnstile_unsleep");
499 }
500
501 /*
502 * turnstile_changepri:
503 *
504 * Adjust the priority of an LWP residing on a turnstile.
505 */
506 void
507 turnstile_changepri(lwp_t *l, pri_t pri)
508 {
509
510 /* XXX priority inheritance */
511 sleepq_changepri(l, pri);
512 }
513
514 #if defined(LOCKDEBUG)
515 /*
516 * turnstile_print:
517 *
518 * Given the address of a lock object, print the contents of a
519 * turnstile.
520 */
521 void
522 turnstile_print(volatile void *obj, void (*pr)(const char *, ...))
523 {
524 turnstile_t *ts;
525 tschain_t *tc;
526 sleepq_t *rsq, *wsq;
527 u_int hash;
528 lwp_t *l;
529
530 hash = TS_HASH(obj);
531 tc = &turnstile_chains[hash];
532
533 LIST_FOREACH(ts, tc, ts_chain)
534 if (ts->ts_obj == obj)
535 break;
536
537 if (ts == NULL) {
538 (*pr)("Turnstile: no active turnstile for this lock.\n");
539 return;
540 }
541
542 rsq = &ts->ts_sleepq[TS_READER_Q];
543 wsq = &ts->ts_sleepq[TS_WRITER_Q];
544
545 (*pr)("Turnstile:\n");
546 (*pr)("=> %d waiting readers:", TS_WAITERS(ts, TS_READER_Q));
547 LIST_FOREACH(l, rsq, l_sleepchain) {
548 (*pr)(" %p", l);
549 }
550 (*pr)("\n");
551
552 (*pr)("=> %d waiting writers:", TS_WAITERS(ts, TS_WRITER_Q));
553 LIST_FOREACH(l, wsq, l_sleepchain) {
554 (*pr)(" %p", l);
555 }
556 (*pr)("\n");
557 }
558 #endif /* LOCKDEBUG */
559