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