kern_sleepq.c revision 1.84 1 /* $NetBSD: kern_sleepq.c,v 1.84 2023/10/13 18:48:56 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.84 2023/10/13 18:48:56 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|LW_RESTART;
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 flag = l->l_flag;
362 if (catch_p) {
363 if ((flag & mask) != 0) {
364 if ((flag & (LW_CANCELLED|LW_WEXIT|LW_WCORE)) != 0) {
365 l->l_flag = flag & ~LW_CANCELLED;
366 error = EINTR;
367 early = true;
368 } else if ((flag & LW_PENDSIG) != 0 &&
369 sigispending(l, 0))
370 early = true;
371 }
372 l->l_flag = (flag | LW_CATCHINTR) & ~LW_RESTART;
373 } else
374 l->l_flag = flag & ~(LW_CATCHINTR | LW_RESTART);
375
376 if (early) {
377 /* lwp_unsleep() will release the lock */
378 lwp_unsleep(l, true);
379 } else {
380 /*
381 * The LWP may have already been awoken if the caller
382 * dropped the sleep queue lock between sleepq_enqueue() and
383 * sleepq_block(). If that happens l_stat will be LSONPROC
384 * and mi_switch() will treat this as a preemption. No need
385 * to do anything special here.
386 */
387 if (timo) {
388 l->l_flag &= ~LW_STIMO;
389 callout_schedule(&l->l_timeout_ch, timo);
390 }
391 l->l_boostpri = l->l_syncobj->sobj_boostpri;
392 spc_lock(l->l_cpu);
393 mi_switch(l);
394
395 /* The LWP and sleep queue are now unlocked. */
396 if (timo) {
397 /*
398 * Even if the callout appears to have fired, we
399 * need to stop it in order to synchronise with
400 * other CPUs. It's important that we do this in
401 * this LWP's context, and not during wakeup, in
402 * order to keep the callout & its cache lines
403 * co-located on the CPU with the LWP.
404 */
405 (void)callout_halt(&l->l_timeout_ch, NULL);
406 error = (l->l_flag & LW_STIMO) ? EWOULDBLOCK : 0;
407 }
408 }
409
410 /*
411 * LW_CATCHINTR is only modified in this function OR when we
412 * are asleep (with the sleepq locked). We can therefore safely
413 * test it unlocked here as it is guaranteed to be stable by
414 * virtue of us running.
415 *
416 * We do not bother clearing it if set; that would require us
417 * to take the LWP lock, and it doesn't seem worth the hassle
418 * considering it is only meaningful here inside this function,
419 * and is set to reflect intent upon entry.
420 */
421 flag = atomic_load_relaxed(&l->l_flag);
422 if (__predict_false((flag & mask) != 0)) {
423 if ((flag & LW_CATCHINTR) == 0 || error != 0)
424 /* nothing */;
425 else if ((flag & (LW_CANCELLED | LW_WEXIT | LW_WCORE)) != 0)
426 error = EINTR;
427 else if ((flag & LW_PENDSIG) != 0) {
428 /*
429 * Acquiring p_lock may cause us to recurse
430 * through the sleep path and back into this
431 * routine, but is safe because LWPs sleeping
432 * on locks are non-interruptable and we will
433 * not recurse again.
434 */
435 p = l->l_proc;
436 mutex_enter(p->p_lock);
437 if (((sig = sigispending(l, 0)) != 0 &&
438 (sigprop[sig] & SA_STOP) == 0) ||
439 (sig = issignal(l)) != 0)
440 error = sleepq_sigtoerror(l, sig);
441 mutex_exit(p->p_lock);
442 } else if ((flag & LW_RESTART) != 0)
443 error = ERESTART;
444 }
445
446 ktrcsw(0, 0, syncobj);
447 if (__predict_false(nlocks != 0)) {
448 KERNEL_LOCK(nlocks, NULL);
449 }
450 return error;
451 }
452
453 /*
454 * sleepq_wake:
455 *
456 * Wake zero or more LWPs blocked on a single wait channel.
457 */
458 void
459 sleepq_wake(sleepq_t *sq, wchan_t wchan, u_int expected, kmutex_t *mp)
460 {
461 lwp_t *l, *next;
462
463 KASSERT(mutex_owned(mp));
464
465 for (l = LIST_FIRST(sq); l != NULL; l = next) {
466 KASSERT(l->l_sleepq == sq);
467 KASSERT(l->l_mutex == mp);
468 next = LIST_NEXT(l, l_sleepchain);
469 if (l->l_wchan != wchan)
470 continue;
471 sleepq_remove(sq, l, true);
472 if (--expected == 0)
473 break;
474 }
475
476 mutex_spin_exit(mp);
477 }
478
479 /*
480 * sleepq_unsleep:
481 *
482 * Remove an LWP from its sleep queue and set it runnable again.
483 * sleepq_unsleep() is called with the LWP's mutex held, and will
484 * release it if "unlock" is true.
485 */
486 void
487 sleepq_unsleep(lwp_t *l, bool unlock)
488 {
489 sleepq_t *sq = l->l_sleepq;
490 kmutex_t *mp = l->l_mutex;
491
492 KASSERT(lwp_locked(l, mp));
493 KASSERT(l->l_wchan != NULL);
494
495 sleepq_remove(sq, l, false);
496 if (unlock) {
497 mutex_spin_exit(mp);
498 }
499 }
500
501 /*
502 * sleepq_timeout:
503 *
504 * Entered via the callout(9) subsystem to time out an LWP that is on a
505 * sleep queue.
506 */
507 void
508 sleepq_timeout(void *arg)
509 {
510 lwp_t *l = arg;
511
512 /*
513 * Lock the LWP. Assuming it's still on the sleep queue, its
514 * current mutex will also be the sleep queue mutex.
515 */
516 lwp_lock(l);
517
518 if (l->l_wchan == NULL || l->l_syncobj == &callout_syncobj) {
519 /*
520 * Somebody beat us to it, or the LWP is blocked in
521 * callout_halt() waiting for us to finish here. In
522 * neither case should the LWP produce EWOULDBLOCK.
523 */
524 lwp_unlock(l);
525 return;
526 }
527
528 l->l_flag |= LW_STIMO;
529 lwp_unsleep(l, true);
530 }
531
532 /*
533 * sleepq_sigtoerror:
534 *
535 * Given a signal number, interpret and return an error code.
536 */
537 static int
538 sleepq_sigtoerror(lwp_t *l, int sig)
539 {
540 struct proc *p = l->l_proc;
541 int error;
542
543 KASSERT(mutex_owned(p->p_lock));
544
545 /*
546 * If this sleep was canceled, don't let the syscall restart.
547 */
548 if ((SIGACTION(p, sig).sa_flags & SA_RESTART) == 0)
549 error = EINTR;
550 else
551 error = ERESTART;
552
553 return error;
554 }
555
556 /*
557 * sleepq_abort:
558 *
559 * After a panic or during autoconfiguration, lower the interrupt
560 * priority level to give pending interrupts a chance to run, and
561 * then return. Called if sleepq_dontsleep() returns non-zero, and
562 * always returns zero.
563 */
564 int
565 sleepq_abort(kmutex_t *mtx, int unlock)
566 {
567 int s;
568
569 s = splhigh();
570 splx(IPL_SAFEPRI);
571 splx(s);
572 if (mtx != NULL && unlock != 0)
573 mutex_exit(mtx);
574
575 return 0;
576 }
577
578 /*
579 * sleepq_reinsert:
580 *
581 * Move the position of the lwp in the sleep queue after a possible
582 * change of the lwp's effective priority.
583 */
584 static void
585 sleepq_reinsert(sleepq_t *sq, lwp_t *l)
586 {
587
588 KASSERT(l->l_sleepq == sq);
589 if ((l->l_syncobj->sobj_flag & SOBJ_SLEEPQ_SORTED) == 0) {
590 return;
591 }
592
593 /*
594 * Don't let the sleep queue become empty, even briefly.
595 * cv_signal() and cv_broadcast() inspect it without the
596 * sleep queue lock held and need to see a non-empty queue
597 * head if there are waiters.
598 */
599 if (LIST_FIRST(sq) == l && LIST_NEXT(l, l_sleepchain) == NULL) {
600 return;
601 }
602 LIST_REMOVE(l, l_sleepchain);
603 sleepq_insert(sq, l, l->l_syncobj);
604 }
605
606 /*
607 * sleepq_changepri:
608 *
609 * Adjust the priority of an LWP residing on a sleepq.
610 */
611 void
612 sleepq_changepri(lwp_t *l, pri_t pri)
613 {
614 sleepq_t *sq = l->l_sleepq;
615
616 KASSERT(lwp_locked(l, NULL));
617
618 l->l_priority = pri;
619 sleepq_reinsert(sq, l);
620 }
621
622 /*
623 * sleepq_changepri:
624 *
625 * Adjust the lended priority of an LWP residing on a sleepq.
626 */
627 void
628 sleepq_lendpri(lwp_t *l, pri_t pri)
629 {
630 sleepq_t *sq = l->l_sleepq;
631
632 KASSERT(lwp_locked(l, NULL));
633
634 l->l_inheritedprio = pri;
635 l->l_auxprio = MAX(l->l_inheritedprio, l->l_protectprio);
636 sleepq_reinsert(sq, l);
637 }
638