Home | History | Annotate | Line # | Download | only in kern
kern_sleepq.c revision 1.63.2.1
      1 /*	$NetBSD: kern_sleepq.c,v 1.63.2.1 2020/04/20 11:29:10 bouyer Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2006, 2007, 2008, 2009, 2019, 2020 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by 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  * Sleep queue implementation, used by turnstiles and general sleep/wakeup
     34  * interfaces.
     35  */
     36 
     37 #include <sys/cdefs.h>
     38 __KERNEL_RCSID(0, "$NetBSD: kern_sleepq.c,v 1.63.2.1 2020/04/20 11:29:10 bouyer Exp $");
     39 
     40 #include <sys/param.h>
     41 #include <sys/kernel.h>
     42 #include <sys/cpu.h>
     43 #include <sys/intr.h>
     44 #include <sys/pool.h>
     45 #include <sys/proc.h>
     46 #include <sys/resourcevar.h>
     47 #include <sys/sched.h>
     48 #include <sys/systm.h>
     49 #include <sys/sleepq.h>
     50 #include <sys/ktrace.h>
     51 
     52 /*
     53  * for sleepq_abort:
     54  * During autoconfiguration or after a panic, a sleep will simply lower the
     55  * priority briefly to allow interrupts, then return.  The priority to be
     56  * used (IPL_SAFEPRI) is machine-dependent, thus this value is initialized and
     57  * maintained in the machine-dependent layers.  This priority will typically
     58  * be 0, or the lowest priority that is safe for use on the interrupt stack;
     59  * it can be made higher to block network software interrupts after panics.
     60  */
     61 #ifndef	IPL_SAFEPRI
     62 #define	IPL_SAFEPRI	0
     63 #endif
     64 
     65 static int	sleepq_sigtoerror(lwp_t *, int);
     66 
     67 /* General purpose sleep table, used by mtsleep() and condition variables. */
     68 sleeptab_t	sleeptab __cacheline_aligned;
     69 sleepqlock_t	sleepq_locks[SLEEPTAB_HASH_SIZE] __cacheline_aligned;
     70 
     71 /*
     72  * sleeptab_init:
     73  *
     74  *	Initialize a sleep table.
     75  */
     76 void
     77 sleeptab_init(sleeptab_t *st)
     78 {
     79 	static bool again;
     80 	int i;
     81 
     82 	for (i = 0; i < SLEEPTAB_HASH_SIZE; i++) {
     83 		if (!again) {
     84 			mutex_init(&sleepq_locks[i].lock, MUTEX_DEFAULT,
     85 			    IPL_SCHED);
     86 		}
     87 		sleepq_init(&st->st_queue[i]);
     88 	}
     89 	again = true;
     90 }
     91 
     92 /*
     93  * sleepq_init:
     94  *
     95  *	Prepare a sleep queue for use.
     96  */
     97 void
     98 sleepq_init(sleepq_t *sq)
     99 {
    100 
    101 	LIST_INIT(sq);
    102 }
    103 
    104 /*
    105  * sleepq_remove:
    106  *
    107  *	Remove an LWP from a sleep queue and wake it up.
    108  */
    109 void
    110 sleepq_remove(sleepq_t *sq, lwp_t *l)
    111 {
    112 	struct schedstate_percpu *spc;
    113 	struct cpu_info *ci;
    114 
    115 	KASSERT(lwp_locked(l, NULL));
    116 
    117 	if ((l->l_syncobj->sobj_flag & SOBJ_SLEEPQ_NULL) == 0) {
    118 		KASSERT(sq != NULL);
    119 		LIST_REMOVE(l, l_sleepchain);
    120 	} else {
    121 		KASSERT(sq == NULL);
    122 	}
    123 
    124 	l->l_syncobj = &sched_syncobj;
    125 	l->l_wchan = NULL;
    126 	l->l_sleepq = NULL;
    127 	l->l_flag &= ~LW_SINTR;
    128 
    129 	ci = l->l_cpu;
    130 	spc = &ci->ci_schedstate;
    131 
    132 	/*
    133 	 * If not sleeping, the LWP must have been suspended.  Let whoever
    134 	 * holds it stopped set it running again.
    135 	 */
    136 	if (l->l_stat != LSSLEEP) {
    137 		KASSERT(l->l_stat == LSSTOP || l->l_stat == LSSUSPENDED);
    138 		lwp_setlock(l, spc->spc_lwplock);
    139 		return;
    140 	}
    141 
    142 	/*
    143 	 * If the LWP is still on the CPU, mark it as LSONPROC.  It may be
    144 	 * about to call mi_switch(), in which case it will yield.
    145 	 */
    146 	if ((l->l_pflag & LP_RUNNING) != 0) {
    147 		l->l_stat = LSONPROC;
    148 		l->l_slptime = 0;
    149 		lwp_setlock(l, spc->spc_lwplock);
    150 		return;
    151 	}
    152 
    153 	/* Update sleep time delta, call the wake-up handler of scheduler */
    154 	l->l_slpticksum += (getticks() - l->l_slpticks);
    155 	sched_wakeup(l);
    156 
    157 	/* Look for a CPU to wake up */
    158 	l->l_cpu = sched_takecpu(l);
    159 	ci = l->l_cpu;
    160 	spc = &ci->ci_schedstate;
    161 
    162 	/*
    163 	 * Set it running.
    164 	 */
    165 	spc_lock(ci);
    166 	lwp_setlock(l, spc->spc_mutex);
    167 	sched_setrunnable(l);
    168 	l->l_stat = LSRUN;
    169 	l->l_slptime = 0;
    170 	sched_enqueue(l);
    171 	sched_resched_lwp(l, true);
    172 	/* LWP & SPC now unlocked, but we still hold sleep queue lock. */
    173 }
    174 
    175 /*
    176  * sleepq_insert:
    177  *
    178  *	Insert an LWP into the sleep queue, optionally sorting by priority.
    179  */
    180 static void
    181 sleepq_insert(sleepq_t *sq, lwp_t *l, syncobj_t *sobj)
    182 {
    183 
    184 	if ((sobj->sobj_flag & SOBJ_SLEEPQ_NULL) != 0) {
    185 		KASSERT(sq == NULL);
    186 		return;
    187 	}
    188 	KASSERT(sq != NULL);
    189 
    190 	if ((sobj->sobj_flag & SOBJ_SLEEPQ_SORTED) != 0) {
    191 		lwp_t *l2;
    192 		const pri_t pri = lwp_eprio(l);
    193 
    194 		LIST_FOREACH(l2, sq, l_sleepchain) {
    195 			if (lwp_eprio(l2) < pri) {
    196 				LIST_INSERT_BEFORE(l2, l, l_sleepchain);
    197 				return;
    198 			}
    199 		}
    200 	}
    201 
    202 	LIST_INSERT_HEAD(sq, l, l_sleepchain);
    203 }
    204 
    205 /*
    206  * sleepq_enqueue:
    207  *
    208  *	Enter an LWP into the sleep queue and prepare for sleep.  The sleep
    209  *	queue must already be locked, and any interlock (such as the kernel
    210  *	lock) must have be released (see sleeptab_lookup(), sleepq_enter()).
    211  */
    212 void
    213 sleepq_enqueue(sleepq_t *sq, wchan_t wchan, const char *wmesg, syncobj_t *sobj,
    214     bool catch_p)
    215 {
    216 	lwp_t *l = curlwp;
    217 
    218 	KASSERT(lwp_locked(l, NULL));
    219 	KASSERT(l->l_stat == LSONPROC);
    220 	KASSERT(l->l_wchan == NULL && l->l_sleepq == NULL);
    221 	KASSERT((l->l_flag & LW_SINTR) == 0);
    222 
    223 	l->l_syncobj = sobj;
    224 	l->l_wchan = wchan;
    225 	l->l_sleepq = sq;
    226 	l->l_wmesg = wmesg;
    227 	l->l_slptime = 0;
    228 	l->l_stat = LSSLEEP;
    229 	if (catch_p)
    230 		l->l_flag |= LW_SINTR;
    231 
    232 	sleepq_insert(sq, l, sobj);
    233 
    234 	/* Save the time when thread has slept */
    235 	l->l_slpticks = getticks();
    236 	sched_slept(l);
    237 }
    238 
    239 /*
    240  * sleepq_block:
    241  *
    242  *	After any intermediate step such as releasing an interlock, switch.
    243  * 	sleepq_block() may return early under exceptional conditions, for
    244  * 	example if the LWP's containing process is exiting.
    245  *
    246  *	timo is a timeout in ticks.  timo = 0 specifies an infinite timeout.
    247  */
    248 int
    249 sleepq_block(int timo, bool catch_p)
    250 {
    251 	int error = 0, sig;
    252 	struct proc *p;
    253 	lwp_t *l = curlwp;
    254 	bool early = false;
    255 	int biglocks = l->l_biglocks;
    256 
    257 	ktrcsw(1, 0);
    258 
    259 	/*
    260 	 * If sleeping interruptably, check for pending signals, exits or
    261 	 * core dump events.
    262 	 */
    263 	if (catch_p) {
    264 		if ((l->l_flag & (LW_CANCELLED|LW_WEXIT|LW_WCORE)) != 0) {
    265 			l->l_flag &= ~LW_CANCELLED;
    266 			error = EINTR;
    267 			early = true;
    268 		} else if ((l->l_flag & LW_PENDSIG) != 0 && sigispending(l, 0))
    269 			early = true;
    270 	}
    271 
    272 	if (early) {
    273 		/* lwp_unsleep() will release the lock */
    274 		lwp_unsleep(l, true);
    275 	} else {
    276 		/*
    277 		 * The LWP may have already been awoken if the caller
    278 		 * dropped the sleep queue lock between sleepq_enqueue() and
    279 		 * sleepq_block().  If that happends l_stat will be LSONPROC
    280 		 * and mi_switch() will treat this as a preemption.  No need
    281 		 * to do anything special here.
    282 		 */
    283 		if (timo) {
    284 			l->l_flag &= ~LW_STIMO;
    285 			callout_schedule(&l->l_timeout_ch, timo);
    286 		}
    287 		spc_lock(l->l_cpu);
    288 		mi_switch(l);
    289 
    290 		/* The LWP and sleep queue are now unlocked. */
    291 		if (timo) {
    292 			/*
    293 			 * Even if the callout appears to have fired, we
    294 			 * need to stop it in order to synchronise with
    295 			 * other CPUs.  It's important that we do this in
    296 			 * this LWP's context, and not during wakeup, in
    297 			 * order to keep the callout & its cache lines
    298 			 * co-located on the CPU with the LWP.
    299 			 */
    300 			(void)callout_halt(&l->l_timeout_ch, NULL);
    301 			error = (l->l_flag & LW_STIMO) ? EWOULDBLOCK : 0;
    302 		}
    303 	}
    304 
    305 	if (catch_p && error == 0) {
    306 		p = l->l_proc;
    307 		if ((l->l_flag & (LW_CANCELLED | LW_WEXIT | LW_WCORE)) != 0)
    308 			error = EINTR;
    309 		else if ((l->l_flag & LW_PENDSIG) != 0) {
    310 			/*
    311 			 * Acquiring p_lock may cause us to recurse
    312 			 * through the sleep path and back into this
    313 			 * routine, but is safe because LWPs sleeping
    314 			 * on locks are non-interruptable and we will
    315 			 * not recurse again.
    316 			 */
    317 			mutex_enter(p->p_lock);
    318 			if (((sig = sigispending(l, 0)) != 0 &&
    319 			    (sigprop[sig] & SA_STOP) == 0) ||
    320 			    (sig = issignal(l)) != 0)
    321 				error = sleepq_sigtoerror(l, sig);
    322 			mutex_exit(p->p_lock);
    323 		}
    324 	}
    325 
    326 	ktrcsw(0, 0);
    327 	if (__predict_false(biglocks != 0)) {
    328 		KERNEL_LOCK(biglocks, NULL);
    329 	}
    330 	return error;
    331 }
    332 
    333 /*
    334  * sleepq_wake:
    335  *
    336  *	Wake zero or more LWPs blocked on a single wait channel.
    337  */
    338 void
    339 sleepq_wake(sleepq_t *sq, wchan_t wchan, u_int expected, kmutex_t *mp)
    340 {
    341 	lwp_t *l, *next;
    342 
    343 	KASSERT(mutex_owned(mp));
    344 
    345 	for (l = LIST_FIRST(sq); l != NULL; l = next) {
    346 		KASSERT(l->l_sleepq == sq);
    347 		KASSERT(l->l_mutex == mp);
    348 		next = LIST_NEXT(l, l_sleepchain);
    349 		if (l->l_wchan != wchan)
    350 			continue;
    351 		sleepq_remove(sq, l);
    352 		if (--expected == 0)
    353 			break;
    354 	}
    355 
    356 	mutex_spin_exit(mp);
    357 }
    358 
    359 /*
    360  * sleepq_unsleep:
    361  *
    362  *	Remove an LWP from its sleep queue and set it runnable again.
    363  *	sleepq_unsleep() is called with the LWP's mutex held, and will
    364  *	release it if "unlock" is true.
    365  */
    366 void
    367 sleepq_unsleep(lwp_t *l, bool unlock)
    368 {
    369 	sleepq_t *sq = l->l_sleepq;
    370 	kmutex_t *mp = l->l_mutex;
    371 
    372 	KASSERT(lwp_locked(l, mp));
    373 	KASSERT(l->l_wchan != NULL);
    374 
    375 	sleepq_remove(sq, l);
    376 	if (unlock) {
    377 		mutex_spin_exit(mp);
    378 	}
    379 }
    380 
    381 /*
    382  * sleepq_timeout:
    383  *
    384  *	Entered via the callout(9) subsystem to time out an LWP that is on a
    385  *	sleep queue.
    386  */
    387 void
    388 sleepq_timeout(void *arg)
    389 {
    390 	lwp_t *l = arg;
    391 
    392 	/*
    393 	 * Lock the LWP.  Assuming it's still on the sleep queue, its
    394 	 * current mutex will also be the sleep queue mutex.
    395 	 */
    396 	lwp_lock(l);
    397 
    398 	if (l->l_wchan == NULL) {
    399 		/* Somebody beat us to it. */
    400 		lwp_unlock(l);
    401 		return;
    402 	}
    403 
    404 	l->l_flag |= LW_STIMO;
    405 	lwp_unsleep(l, true);
    406 }
    407 
    408 /*
    409  * sleepq_sigtoerror:
    410  *
    411  *	Given a signal number, interpret and return an error code.
    412  */
    413 static int
    414 sleepq_sigtoerror(lwp_t *l, int sig)
    415 {
    416 	struct proc *p = l->l_proc;
    417 	int error;
    418 
    419 	KASSERT(mutex_owned(p->p_lock));
    420 
    421 	/*
    422 	 * If this sleep was canceled, don't let the syscall restart.
    423 	 */
    424 	if ((SIGACTION(p, sig).sa_flags & SA_RESTART) == 0)
    425 		error = EINTR;
    426 	else
    427 		error = ERESTART;
    428 
    429 	return error;
    430 }
    431 
    432 /*
    433  * sleepq_abort:
    434  *
    435  *	After a panic or during autoconfiguration, lower the interrupt
    436  *	priority level to give pending interrupts a chance to run, and
    437  *	then return.  Called if sleepq_dontsleep() returns non-zero, and
    438  *	always returns zero.
    439  */
    440 int
    441 sleepq_abort(kmutex_t *mtx, int unlock)
    442 {
    443 	int s;
    444 
    445 	s = splhigh();
    446 	splx(IPL_SAFEPRI);
    447 	splx(s);
    448 	if (mtx != NULL && unlock != 0)
    449 		mutex_exit(mtx);
    450 
    451 	return 0;
    452 }
    453 
    454 /*
    455  * sleepq_reinsert:
    456  *
    457  *	Move the possition of the lwp in the sleep queue after a possible
    458  *	change of the lwp's effective priority.
    459  */
    460 static void
    461 sleepq_reinsert(sleepq_t *sq, lwp_t *l)
    462 {
    463 
    464 	KASSERT(l->l_sleepq == sq);
    465 	if ((l->l_syncobj->sobj_flag & SOBJ_SLEEPQ_SORTED) == 0) {
    466 		return;
    467 	}
    468 
    469 	/*
    470 	 * Don't let the sleep queue become empty, even briefly.
    471 	 * cv_signal() and cv_broadcast() inspect it without the
    472 	 * sleep queue lock held and need to see a non-empty queue
    473 	 * head if there are waiters.
    474 	 */
    475 	if (LIST_FIRST(sq) == l && LIST_NEXT(l, l_sleepchain) == NULL) {
    476 		return;
    477 	}
    478 	LIST_REMOVE(l, l_sleepchain);
    479 	sleepq_insert(sq, l, l->l_syncobj);
    480 }
    481 
    482 /*
    483  * sleepq_changepri:
    484  *
    485  *	Adjust the priority of an LWP residing on a sleepq.
    486  */
    487 void
    488 sleepq_changepri(lwp_t *l, pri_t pri)
    489 {
    490 	sleepq_t *sq = l->l_sleepq;
    491 
    492 	KASSERT(lwp_locked(l, NULL));
    493 
    494 	l->l_priority = pri;
    495 	sleepq_reinsert(sq, l);
    496 }
    497 
    498 /*
    499  * sleepq_changepri:
    500  *
    501  *	Adjust the lended priority of an LWP residing on a sleepq.
    502  */
    503 void
    504 sleepq_lendpri(lwp_t *l, pri_t pri)
    505 {
    506 	sleepq_t *sq = l->l_sleepq;
    507 
    508 	KASSERT(lwp_locked(l, NULL));
    509 
    510 	l->l_inheritedprio = pri;
    511 	l->l_auxprio = MAX(l->l_inheritedprio, l->l_protectprio);
    512 	sleepq_reinsert(sq, l);
    513 }
    514