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