kern_sleepq.c revision 1.85 1 /* $NetBSD: kern_sleepq.c,v 1.85 2023/10/15 10:27:11 riastradh Exp $ */
2
3 /*-
4 * Copyright (c) 2006, 2007, 2008, 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 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 * Sleep queue implementation, used by turnstiles and general sleep/wakeup
35 * interfaces.
36 */
37
38 #include <sys/cdefs.h>
39 __KERNEL_RCSID(0, "$NetBSD: kern_sleepq.c,v 1.85 2023/10/15 10:27:11 riastradh Exp $");
40
41 #include <sys/param.h>
42 #include <sys/kernel.h>
43 #include <sys/cpu.h>
44 #include <sys/intr.h>
45 #include <sys/pool.h>
46 #include <sys/proc.h>
47 #include <sys/resourcevar.h>
48 #include <sys/sched.h>
49 #include <sys/systm.h>
50 #include <sys/sleepq.h>
51 #include <sys/ktrace.h>
52 #include <sys/syncobj.h>
53
54 /*
55 * for sleepq_abort:
56 * During autoconfiguration or after a panic, a sleep will simply lower the
57 * priority briefly to allow interrupts, then return. The priority to be
58 * used (IPL_SAFEPRI) is machine-dependent, thus this value is initialized and
59 * maintained in the machine-dependent layers. This priority will typically
60 * be 0, or the lowest priority that is safe for use on the interrupt stack;
61 * it can be made higher to block network software interrupts after panics.
62 */
63 #ifndef IPL_SAFEPRI
64 #define IPL_SAFEPRI 0
65 #endif
66
67 static int sleepq_sigtoerror(lwp_t *, int);
68
69 /* General purpose sleep table, used by mtsleep() and condition variables. */
70 sleeptab_t sleeptab __cacheline_aligned;
71 sleepqlock_t sleepq_locks[SLEEPTAB_HASH_SIZE] __cacheline_aligned;
72
73 /*
74 * sleeptab_init:
75 *
76 * Initialize a sleep table.
77 */
78 void
79 sleeptab_init(sleeptab_t *st)
80 {
81 static bool again;
82 int i;
83
84 for (i = 0; i < SLEEPTAB_HASH_SIZE; i++) {
85 if (!again) {
86 mutex_init(&sleepq_locks[i].lock, MUTEX_DEFAULT,
87 IPL_SCHED);
88 }
89 sleepq_init(&st->st_queue[i]);
90 }
91 again = true;
92 }
93
94 /*
95 * sleepq_init:
96 *
97 * Prepare a sleep queue for use.
98 */
99 void
100 sleepq_init(sleepq_t *sq)
101 {
102
103 LIST_INIT(sq);
104 }
105
106 /*
107 * sleepq_remove:
108 *
109 * Remove an LWP from a sleep queue and wake it up. Distinguish
110 * between deliberate wakeups (which are a valuable information) and
111 * "unsleep" (an out-of-band action must be taken).
112 *
113 * For wakeup, convert any interruptable wait into non-interruptable
114 * one before waking the LWP. Otherwise, if only one LWP is awoken it
115 * could fail to do something useful with the wakeup due to an error
116 * return and the caller of e.g. cv_signal() may not expect this.
117 */
118 void
119 sleepq_remove(sleepq_t *sq, lwp_t *l, bool wakeup)
120 {
121 struct schedstate_percpu *spc;
122 struct cpu_info *ci;
123
124 KASSERT(lwp_locked(l, NULL));
125
126 if ((l->l_syncobj->sobj_flag & SOBJ_SLEEPQ_NULL) == 0) {
127 KASSERT(sq != NULL);
128 LIST_REMOVE(l, l_sleepchain);
129 } else {
130 KASSERT(sq == NULL);
131 }
132
133 l->l_syncobj = &sched_syncobj;
134 l->l_wchan = NULL;
135 l->l_sleepq = NULL;
136 l->l_flag &= wakeup ? ~(LW_SINTR|LW_CATCHINTR|LW_STIMO) : ~LW_SINTR;
137
138 ci = l->l_cpu;
139 spc = &ci->ci_schedstate;
140
141 /*
142 * If not sleeping, the LWP must have been suspended. Let whoever
143 * holds it stopped set it running again.
144 */
145 if (l->l_stat != LSSLEEP) {
146 KASSERT(l->l_stat == LSSTOP || l->l_stat == LSSUSPENDED);
147 lwp_setlock(l, spc->spc_lwplock);
148 return;
149 }
150
151 /*
152 * If the LWP is still on the CPU, mark it as LSONPROC. It may be
153 * about to call mi_switch(), in which case it will yield.
154 */
155 if ((l->l_pflag & LP_RUNNING) != 0) {
156 l->l_stat = LSONPROC;
157 l->l_slptime = 0;
158 lwp_setlock(l, spc->spc_lwplock);
159 return;
160 }
161
162 /* Update sleep time delta, call the wake-up handler of scheduler */
163 l->l_slpticksum += (getticks() - l->l_slpticks);
164 sched_wakeup(l);
165
166 /* Look for a CPU to wake up */
167 l->l_cpu = sched_takecpu(l);
168 ci = l->l_cpu;
169 spc = &ci->ci_schedstate;
170
171 /*
172 * Set it running.
173 */
174 spc_lock(ci);
175 lwp_setlock(l, spc->spc_mutex);
176 sched_setrunnable(l);
177 l->l_stat = LSRUN;
178 l->l_slptime = 0;
179 sched_enqueue(l);
180 sched_resched_lwp(l, true);
181 /* LWP & SPC now unlocked, but we still hold sleep queue lock. */
182 }
183
184 /*
185 * sleepq_insert:
186 *
187 * Insert an LWP into the sleep queue, optionally sorting by priority.
188 */
189 static void
190 sleepq_insert(sleepq_t *sq, lwp_t *l, syncobj_t *sobj)
191 {
192
193 if ((sobj->sobj_flag & SOBJ_SLEEPQ_NULL) != 0) {
194 KASSERT(sq == NULL);
195 return;
196 }
197 KASSERT(sq != NULL);
198
199 if ((sobj->sobj_flag & SOBJ_SLEEPQ_SORTED) != 0) {
200 lwp_t *l2, *l_last = NULL;
201 const pri_t pri = lwp_eprio(l);
202
203 LIST_FOREACH(l2, sq, l_sleepchain) {
204 l_last = l2;
205 if (lwp_eprio(l2) < pri) {
206 LIST_INSERT_BEFORE(l2, l, l_sleepchain);
207 return;
208 }
209 }
210 /*
211 * Ensure FIFO ordering if no waiters are of lower priority.
212 */
213 if (l_last != NULL) {
214 LIST_INSERT_AFTER(l_last, l, l_sleepchain);
215 return;
216 }
217 }
218
219 LIST_INSERT_HEAD(sq, l, l_sleepchain);
220 }
221
222 /*
223 * sleepq_enter:
224 *
225 * Prepare to block on a sleep queue, after which any interlock can be
226 * safely released.
227 */
228 int
229 sleepq_enter(sleepq_t *sq, lwp_t *l, kmutex_t *mp)
230 {
231 int nlocks;
232
233 KASSERT((sq != NULL) == (mp != NULL));
234
235 /*
236 * Acquire the per-LWP mutex and lend it our sleep queue lock.
237 * Once interlocked, we can release the kernel lock.
238 */
239 lwp_lock(l);
240 if (mp != NULL) {
241 lwp_unlock_to(l, mp);
242 }
243 if (__predict_false((nlocks = l->l_blcnt) != 0)) {
244 KERNEL_UNLOCK_ALL(NULL, NULL);
245 }
246 return nlocks;
247 }
248
249 /*
250 * sleepq_enqueue:
251 *
252 * Enter an LWP into the sleep queue and prepare for sleep. The sleep
253 * queue must already be locked, and any interlock (such as the kernel
254 * lock) must have be released (see sleeptab_lookup(), sleepq_enter()).
255 */
256 void
257 sleepq_enqueue(sleepq_t *sq, wchan_t wchan, const char *wmesg, syncobj_t *sobj,
258 bool catch_p)
259 {
260 lwp_t *l = curlwp;
261
262 KASSERT(lwp_locked(l, NULL));
263 KASSERT(l->l_stat == LSONPROC);
264 KASSERT(l->l_wchan == NULL);
265 KASSERT(l->l_sleepq == NULL);
266 KASSERT((l->l_flag & LW_SINTR) == 0);
267
268 l->l_syncobj = sobj;
269 l->l_wchan = wchan;
270 l->l_sleepq = sq;
271 l->l_wmesg = wmesg;
272 l->l_slptime = 0;
273 l->l_stat = LSSLEEP;
274 if (catch_p)
275 l->l_flag |= LW_SINTR;
276
277 sleepq_insert(sq, l, sobj);
278
279 /* Save the time when thread has slept */
280 l->l_slpticks = getticks();
281 sched_slept(l);
282 }
283
284 /*
285 * sleepq_transfer:
286 *
287 * Move an LWP from one sleep queue to another. Both sleep queues
288 * must already be locked.
289 *
290 * The LWP will be updated with the new sleepq, wchan, wmesg,
291 * sobj, and mutex. The interruptible flag will also be updated.
292 */
293 void
294 sleepq_transfer(lwp_t *l, sleepq_t *from_sq, sleepq_t *sq, wchan_t wchan,
295 const char *wmesg, syncobj_t *sobj, kmutex_t *mp, bool catch_p)
296 {
297
298 KASSERT(l->l_sleepq == from_sq);
299
300 LIST_REMOVE(l, l_sleepchain);
301 l->l_syncobj = sobj;
302 l->l_wchan = wchan;
303 l->l_sleepq = sq;
304 l->l_wmesg = wmesg;
305
306 if (catch_p)
307 l->l_flag = LW_SINTR | LW_CATCHINTR;
308 else
309 l->l_flag = ~(LW_SINTR | LW_CATCHINTR);
310
311 /*
312 * This allows the transfer from one sleepq to another where
313 * it is known that they're both protected by the same lock.
314 */
315 if (mp != NULL)
316 lwp_setlock(l, mp);
317
318 sleepq_insert(sq, l, sobj);
319 }
320
321 /*
322 * sleepq_uncatch:
323 *
324 * Mark the LWP as no longer sleeping interruptibly.
325 */
326 void
327 sleepq_uncatch(lwp_t *l)
328 {
329
330 l->l_flag &= ~(LW_SINTR | LW_CATCHINTR | LW_STIMO);
331 }
332
333 /*
334 * sleepq_block:
335 *
336 * After any intermediate step such as releasing an interlock, switch.
337 * sleepq_block() may return early under exceptional conditions, for
338 * example if the LWP's containing process is exiting.
339 *
340 * timo is a timeout in ticks. timo = 0 specifies an infinite timeout.
341 */
342 int
343 sleepq_block(int timo, bool catch_p, syncobj_t *syncobj, int nlocks)
344 {
345 const int mask = LW_CANCELLED|LW_WEXIT|LW_WCORE|LW_PENDSIG|LW_RESTART;
346 int error = 0, sig, flag;
347 struct proc *p;
348 lwp_t *l = curlwp;
349 bool early = false;
350
351 ktrcsw(1, 0, syncobj);
352
353 /*
354 * If sleeping interruptably, check for pending signals, exits or
355 * core dump events.
356 *
357 * Note the usage of LW_CATCHINTR. This expresses our intent
358 * to catch or not catch sleep interruptions, which might change
359 * while we are sleeping. It is independent from LW_SINTR because
360 * we don't want to leave LW_SINTR set when the LWP is not asleep.
361 */
362 flag = l->l_flag;
363 if (catch_p) {
364 if ((flag & mask) != 0) {
365 if ((flag & (LW_CANCELLED|LW_WEXIT|LW_WCORE)) != 0) {
366 l->l_flag = flag & ~LW_CANCELLED;
367 error = EINTR;
368 early = true;
369 } else if ((flag & LW_PENDSIG) != 0 &&
370 sigispending(l, 0))
371 early = true;
372 }
373 l->l_flag = (flag | LW_CATCHINTR) & ~LW_RESTART;
374 } else
375 l->l_flag = flag & ~(LW_CATCHINTR | LW_RESTART);
376
377 if (early) {
378 /* lwp_unsleep() will release the lock */
379 lwp_unsleep(l, true);
380 } else {
381 /*
382 * The LWP may have already been awoken if the caller
383 * dropped the sleep queue lock between sleepq_enqueue() and
384 * sleepq_block(). If that happens l_stat will be LSONPROC
385 * and mi_switch() will treat this as a preemption. No need
386 * to do anything special here.
387 */
388 if (timo) {
389 l->l_flag &= ~LW_STIMO;
390 callout_schedule(&l->l_timeout_ch, timo);
391 }
392 l->l_boostpri = l->l_syncobj->sobj_boostpri;
393 spc_lock(l->l_cpu);
394 mi_switch(l);
395
396 /* The LWP and sleep queue are now unlocked. */
397 if (timo) {
398 /*
399 * Even if the callout appears to have fired, we
400 * need to stop it in order to synchronise with
401 * other CPUs. It's important that we do this in
402 * this LWP's context, and not during wakeup, in
403 * order to keep the callout & its cache lines
404 * co-located on the CPU with the LWP.
405 */
406 (void)callout_halt(&l->l_timeout_ch, NULL);
407 error = (l->l_flag & LW_STIMO) ? EWOULDBLOCK : 0;
408 }
409 }
410
411 /*
412 * LW_CATCHINTR is only modified in this function OR when we
413 * are asleep (with the sleepq locked). We can therefore safely
414 * test it unlocked here as it is guaranteed to be stable by
415 * virtue of us running.
416 *
417 * We do not bother clearing it if set; that would require us
418 * to take the LWP lock, and it doesn't seem worth the hassle
419 * considering it is only meaningful here inside this function,
420 * and is set to reflect intent upon entry.
421 */
422 flag = atomic_load_relaxed(&l->l_flag);
423 if (__predict_false((flag & mask) != 0)) {
424 if ((flag & LW_CATCHINTR) == 0 || error != 0)
425 /* nothing */;
426 else if ((flag & (LW_CANCELLED | LW_WEXIT | LW_WCORE)) != 0)
427 error = EINTR;
428 else if ((flag & LW_PENDSIG) != 0) {
429 /*
430 * Acquiring p_lock may cause us to recurse
431 * through the sleep path and back into this
432 * routine, but is safe because LWPs sleeping
433 * on locks are non-interruptable and we will
434 * not recurse again.
435 */
436 p = l->l_proc;
437 mutex_enter(p->p_lock);
438 if (((sig = sigispending(l, 0)) != 0 &&
439 (sigprop[sig] & SA_STOP) == 0) ||
440 (sig = issignal(l)) != 0)
441 error = sleepq_sigtoerror(l, sig);
442 mutex_exit(p->p_lock);
443 } else if ((flag & LW_RESTART) != 0)
444 error = ERESTART;
445 }
446
447 ktrcsw(0, 0, syncobj);
448 if (__predict_false(nlocks != 0)) {
449 KERNEL_LOCK(nlocks, NULL);
450 }
451 return error;
452 }
453
454 /*
455 * sleepq_wake:
456 *
457 * Wake zero or more LWPs blocked on a single wait channel.
458 */
459 void
460 sleepq_wake(sleepq_t *sq, wchan_t wchan, u_int expected, kmutex_t *mp)
461 {
462 lwp_t *l, *next;
463
464 KASSERT(mutex_owned(mp));
465
466 for (l = LIST_FIRST(sq); l != NULL; l = next) {
467 KASSERT(l->l_sleepq == sq);
468 KASSERT(l->l_mutex == mp);
469 next = LIST_NEXT(l, l_sleepchain);
470 if (l->l_wchan != wchan)
471 continue;
472 sleepq_remove(sq, l, true);
473 if (--expected == 0)
474 break;
475 }
476
477 mutex_spin_exit(mp);
478 }
479
480 /*
481 * sleepq_unsleep:
482 *
483 * Remove an LWP from its sleep queue and set it runnable again.
484 * sleepq_unsleep() is called with the LWP's mutex held, and will
485 * release it if "unlock" is true.
486 */
487 void
488 sleepq_unsleep(lwp_t *l, bool unlock)
489 {
490 sleepq_t *sq = l->l_sleepq;
491 kmutex_t *mp = l->l_mutex;
492
493 KASSERT(lwp_locked(l, mp));
494 KASSERT(l->l_wchan != NULL);
495
496 sleepq_remove(sq, l, false);
497 if (unlock) {
498 mutex_spin_exit(mp);
499 }
500 }
501
502 /*
503 * sleepq_timeout:
504 *
505 * Entered via the callout(9) subsystem to time out an LWP that is on a
506 * sleep queue.
507 */
508 void
509 sleepq_timeout(void *arg)
510 {
511 lwp_t *l = arg;
512
513 /*
514 * Lock the LWP. Assuming it's still on the sleep queue, its
515 * current mutex will also be the sleep queue mutex.
516 */
517 lwp_lock(l);
518
519 if (l->l_wchan == NULL || l->l_syncobj == &callout_syncobj) {
520 /*
521 * Somebody beat us to it, or the LWP is blocked in
522 * callout_halt() waiting for us to finish here. In
523 * neither case should the LWP produce EWOULDBLOCK.
524 */
525 lwp_unlock(l);
526 return;
527 }
528
529 l->l_flag |= LW_STIMO;
530 lwp_unsleep(l, true);
531 }
532
533 /*
534 * sleepq_sigtoerror:
535 *
536 * Given a signal number, interpret and return an error code.
537 */
538 static int
539 sleepq_sigtoerror(lwp_t *l, int sig)
540 {
541 struct proc *p = l->l_proc;
542 int error;
543
544 KASSERT(mutex_owned(p->p_lock));
545
546 /*
547 * If this sleep was canceled, don't let the syscall restart.
548 */
549 if ((SIGACTION(p, sig).sa_flags & SA_RESTART) == 0)
550 error = EINTR;
551 else
552 error = ERESTART;
553
554 return error;
555 }
556
557 /*
558 * sleepq_abort:
559 *
560 * After a panic or during autoconfiguration, lower the interrupt
561 * priority level to give pending interrupts a chance to run, and
562 * then return. Called if sleepq_dontsleep() returns non-zero, and
563 * always returns zero.
564 */
565 int
566 sleepq_abort(kmutex_t *mtx, int unlock)
567 {
568 int s;
569
570 s = splhigh();
571 splx(IPL_SAFEPRI);
572 splx(s);
573 if (mtx != NULL && unlock != 0)
574 mutex_exit(mtx);
575
576 return 0;
577 }
578
579 /*
580 * sleepq_reinsert:
581 *
582 * Move the position of the lwp in the sleep queue after a possible
583 * change of the lwp's effective priority.
584 */
585 static void
586 sleepq_reinsert(sleepq_t *sq, lwp_t *l)
587 {
588
589 KASSERT(l->l_sleepq == sq);
590 if ((l->l_syncobj->sobj_flag & SOBJ_SLEEPQ_SORTED) == 0) {
591 return;
592 }
593
594 /*
595 * Don't let the sleep queue become empty, even briefly.
596 * cv_signal() and cv_broadcast() inspect it without the
597 * sleep queue lock held and need to see a non-empty queue
598 * head if there are waiters.
599 */
600 if (LIST_FIRST(sq) == l && LIST_NEXT(l, l_sleepchain) == NULL) {
601 return;
602 }
603 LIST_REMOVE(l, l_sleepchain);
604 sleepq_insert(sq, l, l->l_syncobj);
605 }
606
607 /*
608 * sleepq_changepri:
609 *
610 * Adjust the priority of an LWP residing on a sleepq.
611 */
612 void
613 sleepq_changepri(lwp_t *l, pri_t pri)
614 {
615 sleepq_t *sq = l->l_sleepq;
616
617 KASSERT(lwp_locked(l, NULL));
618
619 l->l_priority = pri;
620 sleepq_reinsert(sq, l);
621 }
622
623 /*
624 * sleepq_changepri:
625 *
626 * Adjust the lended priority of an LWP residing on a sleepq.
627 */
628 void
629 sleepq_lendpri(lwp_t *l, pri_t pri)
630 {
631 sleepq_t *sq = l->l_sleepq;
632
633 KASSERT(lwp_locked(l, NULL));
634
635 l->l_inheritedprio = pri;
636 l->l_auxprio = MAX(l->l_inheritedprio, l->l_protectprio);
637 sleepq_reinsert(sq, l);
638 }
639