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