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