kern_synch.c revision 1.361 1 /* $NetBSD: kern_synch.c,v 1.361 2023/10/04 20:28:06 ad Exp $ */
2
3 /*-
4 * Copyright (c) 1999, 2000, 2004, 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 Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
10 * NASA Ames Research Center, by Charles M. Hannum, Andrew Doran and
11 * Daniel Sieger.
12 *
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
15 * are met:
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
23 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
24 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
26 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGE.
33 */
34
35 /*-
36 * Copyright (c) 1982, 1986, 1990, 1991, 1993
37 * The Regents of the University of California. All rights reserved.
38 * (c) UNIX System Laboratories, Inc.
39 * All or some portions of this file are derived from material licensed
40 * to the University of California by American Telephone and Telegraph
41 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
42 * the permission of UNIX System Laboratories, Inc.
43 *
44 * Redistribution and use in source and binary forms, with or without
45 * modification, are permitted provided that the following conditions
46 * are met:
47 * 1. Redistributions of source code must retain the above copyright
48 * notice, this list of conditions and the following disclaimer.
49 * 2. Redistributions in binary form must reproduce the above copyright
50 * notice, this list of conditions and the following disclaimer in the
51 * documentation and/or other materials provided with the distribution.
52 * 3. Neither the name of the University nor the names of its contributors
53 * may be used to endorse or promote products derived from this software
54 * without specific prior written permission.
55 *
56 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
57 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
58 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
59 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
60 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
61 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
62 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
63 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
64 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
65 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66 * SUCH DAMAGE.
67 *
68 * @(#)kern_synch.c 8.9 (Berkeley) 5/19/95
69 */
70
71 #include <sys/cdefs.h>
72 __KERNEL_RCSID(0, "$NetBSD: kern_synch.c,v 1.361 2023/10/04 20:28:06 ad Exp $");
73
74 #include "opt_kstack.h"
75 #include "opt_ddb.h"
76 #include "opt_dtrace.h"
77
78 #define __MUTEX_PRIVATE
79
80 #include <sys/param.h>
81 #include <sys/systm.h>
82 #include <sys/proc.h>
83 #include <sys/kernel.h>
84 #include <sys/cpu.h>
85 #include <sys/pserialize.h>
86 #include <sys/resource.h>
87 #include <sys/resourcevar.h>
88 #include <sys/rwlock.h>
89 #include <sys/sched.h>
90 #include <sys/syscall_stats.h>
91 #include <sys/sleepq.h>
92 #include <sys/lockdebug.h>
93 #include <sys/evcnt.h>
94 #include <sys/intr.h>
95 #include <sys/lwpctl.h>
96 #include <sys/atomic.h>
97 #include <sys/syslog.h>
98
99 #include <uvm/uvm_extern.h>
100
101 #include <dev/lockstat.h>
102
103 #include <sys/dtrace_bsd.h>
104 int dtrace_vtime_active=0;
105 dtrace_vtime_switch_func_t dtrace_vtime_switch_func;
106
107 #ifdef DDB
108 #include <ddb/ddb.h>
109 #endif
110
111 static void sched_unsleep(struct lwp *, bool);
112 static void sched_changepri(struct lwp *, pri_t);
113 static void sched_lendpri(struct lwp *, pri_t);
114
115 syncobj_t sleep_syncobj = {
116 .sobj_name = "sleep",
117 .sobj_flag = SOBJ_SLEEPQ_SORTED,
118 .sobj_boostpri = PRI_KERNEL,
119 .sobj_unsleep = sleepq_unsleep,
120 .sobj_changepri = sleepq_changepri,
121 .sobj_lendpri = sleepq_lendpri,
122 .sobj_owner = syncobj_noowner,
123 };
124
125 syncobj_t sched_syncobj = {
126 .sobj_name = "sched",
127 .sobj_flag = SOBJ_SLEEPQ_SORTED,
128 .sobj_boostpri = PRI_USER,
129 .sobj_unsleep = sched_unsleep,
130 .sobj_changepri = sched_changepri,
131 .sobj_lendpri = sched_lendpri,
132 .sobj_owner = syncobj_noowner,
133 };
134
135 syncobj_t kpause_syncobj = {
136 .sobj_name = "kpause",
137 .sobj_flag = SOBJ_SLEEPQ_NULL,
138 .sobj_boostpri = PRI_KERNEL,
139 .sobj_unsleep = sleepq_unsleep,
140 .sobj_changepri = sleepq_changepri,
141 .sobj_lendpri = sleepq_lendpri,
142 .sobj_owner = syncobj_noowner,
143 };
144
145 /* "Lightning bolt": once a second sleep address. */
146 kcondvar_t lbolt __cacheline_aligned;
147
148 u_int sched_pstats_ticks __cacheline_aligned;
149
150 /* Preemption event counters. */
151 static struct evcnt kpreempt_ev_crit __cacheline_aligned;
152 static struct evcnt kpreempt_ev_klock __cacheline_aligned;
153 static struct evcnt kpreempt_ev_immed __cacheline_aligned;
154
155 void
156 synch_init(void)
157 {
158
159 cv_init(&lbolt, "lbolt");
160
161 evcnt_attach_dynamic(&kpreempt_ev_crit, EVCNT_TYPE_MISC, NULL,
162 "kpreempt", "defer: critical section");
163 evcnt_attach_dynamic(&kpreempt_ev_klock, EVCNT_TYPE_MISC, NULL,
164 "kpreempt", "defer: kernel_lock");
165 evcnt_attach_dynamic(&kpreempt_ev_immed, EVCNT_TYPE_MISC, NULL,
166 "kpreempt", "immediate");
167 }
168
169 /*
170 * OBSOLETE INTERFACE
171 *
172 * General sleep call. Suspends the current LWP until a wakeup is
173 * performed on the specified identifier. The LWP will then be made
174 * runnable with the specified priority. Sleeps at most timo/hz seconds (0
175 * means no timeout). If pri includes PCATCH flag, signals are checked
176 * before and after sleeping, else signals are not checked. Returns 0 if
177 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a
178 * signal needs to be delivered, ERESTART is returned if the current system
179 * call should be restarted if possible, and EINTR is returned if the system
180 * call should be interrupted by the signal (return EINTR).
181 */
182 int
183 tsleep(wchan_t ident, pri_t priority, const char *wmesg, int timo)
184 {
185 struct lwp *l = curlwp;
186 sleepq_t *sq;
187 kmutex_t *mp;
188 bool catch_p;
189
190 KASSERT((l->l_pflag & LP_INTR) == 0);
191 KASSERT(ident != &lbolt);
192 //KASSERT(KERNEL_LOCKED_P());
193
194 if (sleepq_dontsleep(l)) {
195 (void)sleepq_abort(NULL, 0);
196 return 0;
197 }
198
199 catch_p = priority & PCATCH;
200 sq = sleeptab_lookup(&sleeptab, ident, &mp);
201 sleepq_enter(sq, l, mp);
202 sleepq_enqueue(sq, ident, wmesg, &sleep_syncobj, catch_p);
203 return sleepq_block(timo, catch_p, &sleep_syncobj);
204 }
205
206 int
207 mtsleep(wchan_t ident, pri_t priority, const char *wmesg, int timo,
208 kmutex_t *mtx)
209 {
210 struct lwp *l = curlwp;
211 sleepq_t *sq;
212 kmutex_t *mp;
213 bool catch_p;
214 int error;
215
216 KASSERT((l->l_pflag & LP_INTR) == 0);
217 KASSERT(ident != &lbolt);
218
219 if (sleepq_dontsleep(l)) {
220 (void)sleepq_abort(mtx, (priority & PNORELOCK) != 0);
221 return 0;
222 }
223
224 catch_p = priority & PCATCH;
225 sq = sleeptab_lookup(&sleeptab, ident, &mp);
226 sleepq_enter(sq, l, mp);
227 sleepq_enqueue(sq, ident, wmesg, &sleep_syncobj, catch_p);
228 mutex_exit(mtx);
229 error = sleepq_block(timo, catch_p, &sleep_syncobj);
230
231 if ((priority & PNORELOCK) == 0)
232 mutex_enter(mtx);
233
234 return error;
235 }
236
237 /*
238 * General sleep call for situations where a wake-up is not expected.
239 */
240 int
241 kpause(const char *wmesg, bool intr, int timo, kmutex_t *mtx)
242 {
243 struct lwp *l = curlwp;
244 int error;
245
246 KASSERT(timo != 0 || intr);
247
248 if (sleepq_dontsleep(l))
249 return sleepq_abort(NULL, 0);
250
251 if (mtx != NULL)
252 mutex_exit(mtx);
253 lwp_lock(l);
254 KERNEL_UNLOCK_ALL(NULL, &l->l_biglocks);
255 sleepq_enqueue(NULL, l, wmesg, &kpause_syncobj, intr);
256 error = sleepq_block(timo, intr, &kpause_syncobj);
257 if (mtx != NULL)
258 mutex_enter(mtx);
259
260 return error;
261 }
262
263 /*
264 * OBSOLETE INTERFACE
265 *
266 * Make all LWPs sleeping on the specified identifier runnable.
267 */
268 void
269 wakeup(wchan_t ident)
270 {
271 sleepq_t *sq;
272 kmutex_t *mp;
273
274 if (__predict_false(cold))
275 return;
276
277 sq = sleeptab_lookup(&sleeptab, ident, &mp);
278 sleepq_wake(sq, ident, (u_int)-1, mp);
279 }
280
281 /*
282 * General yield call. Puts the current LWP back on its run queue and
283 * performs a context switch.
284 */
285 void
286 yield(void)
287 {
288 struct lwp *l = curlwp;
289
290 KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
291 lwp_lock(l);
292
293 KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_lwplock));
294 KASSERT(l->l_stat == LSONPROC);
295
296 spc_lock(l->l_cpu);
297 mi_switch(l);
298 KERNEL_LOCK(l->l_biglocks, l);
299 }
300
301 /*
302 * General preemption call. Puts the current LWP back on its run queue
303 * and performs an involuntary context switch. Different from yield()
304 * in that:
305 *
306 * - It's counted differently (involuntary vs. voluntary).
307 * - Realtime threads go to the head of their runqueue vs. tail for yield().
308 */
309 void
310 preempt(void)
311 {
312 struct lwp *l = curlwp;
313
314 KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
315 lwp_lock(l);
316
317 KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_lwplock));
318 KASSERT(l->l_stat == LSONPROC);
319
320 spc_lock(l->l_cpu);
321 l->l_pflag |= LP_PREEMPTING;
322 mi_switch(l);
323 KERNEL_LOCK(l->l_biglocks, l);
324 }
325
326 /*
327 * Return true if the current LWP should yield the processor. Intended to
328 * be used by long-running code in kernel.
329 */
330 inline bool
331 preempt_needed(void)
332 {
333 lwp_t *l = curlwp;
334 int needed;
335
336 KPREEMPT_DISABLE(l);
337 needed = l->l_cpu->ci_want_resched;
338 KPREEMPT_ENABLE(l);
339
340 return (needed != 0);
341 }
342
343 /*
344 * A breathing point for long running code in kernel.
345 */
346 void
347 preempt_point(void)
348 {
349
350 if (__predict_false(preempt_needed())) {
351 preempt();
352 }
353 }
354
355 /*
356 * Handle a request made by another agent to preempt the current LWP
357 * in-kernel. Usually called when l_dopreempt may be non-zero.
358 *
359 * Character addresses for lockstat only.
360 */
361 static char kpreempt_is_disabled;
362 static char kernel_lock_held;
363 static char is_softint_lwp;
364 static char spl_is_raised;
365
366 bool
367 kpreempt(uintptr_t where)
368 {
369 uintptr_t failed;
370 lwp_t *l;
371 int s, dop, lsflag;
372
373 l = curlwp;
374 failed = 0;
375 while ((dop = l->l_dopreempt) != 0) {
376 if (l->l_stat != LSONPROC) {
377 /*
378 * About to block (or die), let it happen.
379 * Doesn't really count as "preemption has
380 * been blocked", since we're going to
381 * context switch.
382 */
383 atomic_swap_uint(&l->l_dopreempt, 0);
384 return true;
385 }
386 KASSERT((l->l_flag & LW_IDLE) == 0);
387 if (__predict_false(l->l_nopreempt != 0)) {
388 /* LWP holds preemption disabled, explicitly. */
389 if ((dop & DOPREEMPT_COUNTED) == 0) {
390 kpreempt_ev_crit.ev_count++;
391 }
392 failed = (uintptr_t)&kpreempt_is_disabled;
393 break;
394 }
395 if (__predict_false((l->l_pflag & LP_INTR) != 0)) {
396 /* Can't preempt soft interrupts yet. */
397 atomic_swap_uint(&l->l_dopreempt, 0);
398 failed = (uintptr_t)&is_softint_lwp;
399 break;
400 }
401 s = splsched();
402 if (__predict_false(l->l_blcnt != 0 ||
403 curcpu()->ci_biglock_wanted != NULL)) {
404 /* Hold or want kernel_lock, code is not MT safe. */
405 splx(s);
406 if ((dop & DOPREEMPT_COUNTED) == 0) {
407 kpreempt_ev_klock.ev_count++;
408 }
409 failed = (uintptr_t)&kernel_lock_held;
410 break;
411 }
412 if (__predict_false(!cpu_kpreempt_enter(where, s))) {
413 /*
414 * It may be that the IPL is too high.
415 * kpreempt_enter() can schedule an
416 * interrupt to retry later.
417 */
418 splx(s);
419 failed = (uintptr_t)&spl_is_raised;
420 break;
421 }
422 /* Do it! */
423 if (__predict_true((dop & DOPREEMPT_COUNTED) == 0)) {
424 kpreempt_ev_immed.ev_count++;
425 }
426 lwp_lock(l);
427 l->l_pflag |= LP_PREEMPTING;
428 spc_lock(l->l_cpu);
429 mi_switch(l);
430 l->l_nopreempt++;
431 splx(s);
432
433 /* Take care of any MD cleanup. */
434 cpu_kpreempt_exit(where);
435 l->l_nopreempt--;
436 }
437
438 if (__predict_true(!failed)) {
439 return false;
440 }
441
442 /* Record preemption failure for reporting via lockstat. */
443 atomic_or_uint(&l->l_dopreempt, DOPREEMPT_COUNTED);
444 lsflag = 0;
445 LOCKSTAT_ENTER(lsflag);
446 if (__predict_false(lsflag)) {
447 if (where == 0) {
448 where = (uintptr_t)__builtin_return_address(0);
449 }
450 /* Preemption is on, might recurse, so make it atomic. */
451 if (atomic_cas_ptr_ni((void *)&l->l_pfailaddr, NULL,
452 (void *)where) == NULL) {
453 LOCKSTAT_START_TIMER(lsflag, l->l_pfailtime);
454 l->l_pfaillock = failed;
455 }
456 }
457 LOCKSTAT_EXIT(lsflag);
458 return true;
459 }
460
461 /*
462 * Return true if preemption is explicitly disabled.
463 */
464 bool
465 kpreempt_disabled(void)
466 {
467 const lwp_t *l = curlwp;
468
469 return l->l_nopreempt != 0 || l->l_stat == LSZOMB ||
470 (l->l_flag & LW_IDLE) != 0 || (l->l_pflag & LP_INTR) != 0 ||
471 cpu_kpreempt_disabled();
472 }
473
474 /*
475 * Disable kernel preemption.
476 */
477 void
478 kpreempt_disable(void)
479 {
480
481 KPREEMPT_DISABLE(curlwp);
482 }
483
484 /*
485 * Reenable kernel preemption.
486 */
487 void
488 kpreempt_enable(void)
489 {
490
491 KPREEMPT_ENABLE(curlwp);
492 }
493
494 /*
495 * Compute the amount of time during which the current lwp was running.
496 *
497 * - update l_rtime unless it's an idle lwp.
498 */
499
500 void
501 updatertime(lwp_t *l, const struct bintime *now)
502 {
503 static bool backwards = false;
504
505 if (__predict_false(l->l_flag & LW_IDLE))
506 return;
507
508 if (__predict_false(bintimecmp(now, &l->l_stime, <)) && !backwards) {
509 char caller[128];
510
511 #ifdef DDB
512 db_symstr(caller, sizeof(caller),
513 (db_expr_t)(intptr_t)__builtin_return_address(0),
514 DB_STGY_PROC);
515 #else
516 snprintf(caller, sizeof(caller), "%p",
517 __builtin_return_address(0));
518 #endif
519 backwards = true;
520 printf("WARNING: lwp %ld (%s%s%s) flags 0x%x:"
521 " timecounter went backwards"
522 " from (%jd + 0x%016"PRIx64"/2^64) sec"
523 " to (%jd + 0x%016"PRIx64"/2^64) sec"
524 " in %s\n",
525 (long)l->l_lid,
526 l->l_proc->p_comm,
527 l->l_name ? " " : "",
528 l->l_name ? l->l_name : "",
529 l->l_pflag,
530 (intmax_t)l->l_stime.sec, l->l_stime.frac,
531 (intmax_t)now->sec, now->frac,
532 caller);
533 }
534
535 /* rtime += now - stime */
536 bintime_add(&l->l_rtime, now);
537 bintime_sub(&l->l_rtime, &l->l_stime);
538 }
539
540 /*
541 * Select next LWP from the current CPU to run..
542 */
543 static inline lwp_t *
544 nextlwp(struct cpu_info *ci, struct schedstate_percpu *spc)
545 {
546 lwp_t *newl;
547
548 /*
549 * Let sched_nextlwp() select the LWP to run the CPU next.
550 * If no LWP is runnable, select the idle LWP.
551 *
552 * On arrival here LWPs on a run queue are locked by spc_mutex which
553 * is currently held. Idle LWPs are always locked by spc_lwplock,
554 * which may or may not be held here. On exit from this code block,
555 * in all cases newl is locked by spc_lwplock.
556 */
557 newl = sched_nextlwp();
558 if (newl != NULL) {
559 sched_dequeue(newl);
560 KASSERT(lwp_locked(newl, spc->spc_mutex));
561 KASSERT(newl->l_cpu == ci);
562 newl->l_stat = LSONPROC;
563 newl->l_pflag |= LP_RUNNING;
564 newl->l_boostpri = PRI_NONE;
565 spc->spc_curpriority = lwp_eprio(newl);
566 spc->spc_flags &= ~(SPCF_SWITCHCLEAR | SPCF_IDLE);
567 lwp_setlock(newl, spc->spc_lwplock);
568 } else {
569 /*
570 * The idle LWP does not get set to LSONPROC, because
571 * otherwise it screws up the output from top(1) etc.
572 */
573 newl = ci->ci_data.cpu_idlelwp;
574 newl->l_pflag |= LP_RUNNING;
575 spc->spc_curpriority = PRI_IDLE;
576 spc->spc_flags = (spc->spc_flags & ~SPCF_SWITCHCLEAR) |
577 SPCF_IDLE;
578 }
579
580 /*
581 * Only clear want_resched if there are no pending (slow) software
582 * interrupts. We can do this without an atomic, because no new
583 * LWPs can appear in the queue due to our hold on spc_mutex, and
584 * the update to ci_want_resched will become globally visible before
585 * the release of spc_mutex becomes globally visible.
586 */
587 if (ci->ci_data.cpu_softints == 0)
588 ci->ci_want_resched = 0;
589
590 return newl;
591 }
592
593 /*
594 * The machine independent parts of context switch.
595 *
596 * NOTE: l->l_cpu is not changed in this routine, because an LWP never
597 * changes its own l_cpu (that would screw up curcpu on many ports and could
598 * cause all kinds of other evil stuff). l_cpu is always changed by some
599 * other actor, when it's known the LWP is not running (the LP_RUNNING flag
600 * is checked under lock).
601 */
602 void
603 mi_switch(lwp_t *l)
604 {
605 struct cpu_info *ci;
606 struct schedstate_percpu *spc;
607 struct lwp *newl;
608 kmutex_t *lock;
609 int oldspl;
610 struct bintime bt;
611 bool returning;
612
613 KASSERT(lwp_locked(l, NULL));
614 KASSERT(kpreempt_disabled());
615 KASSERT(mutex_owned(curcpu()->ci_schedstate.spc_mutex));
616 KASSERTMSG(l->l_blcnt == 0, "kernel_lock leaked");
617
618 kstack_check_magic(l);
619
620 binuptime(&bt);
621
622 KASSERTMSG(l == curlwp, "l %p curlwp %p", l, curlwp);
623 KASSERT((l->l_pflag & LP_RUNNING) != 0);
624 KASSERT(l->l_cpu == curcpu() || l->l_stat == LSRUN);
625 ci = curcpu();
626 spc = &ci->ci_schedstate;
627 returning = false;
628 newl = NULL;
629
630 /*
631 * If we have been asked to switch to a specific LWP, then there
632 * is no need to inspect the run queues. If a soft interrupt is
633 * blocking, then return to the interrupted thread without adjusting
634 * VM context or its start time: neither have been changed in order
635 * to take the interrupt.
636 */
637 if (l->l_switchto != NULL) {
638 if ((l->l_pflag & LP_INTR) != 0) {
639 returning = true;
640 softint_block(l);
641 if ((l->l_pflag & LP_TIMEINTR) != 0)
642 updatertime(l, &bt);
643 }
644 newl = l->l_switchto;
645 l->l_switchto = NULL;
646 }
647 #ifndef __HAVE_FAST_SOFTINTS
648 else if (ci->ci_data.cpu_softints != 0) {
649 /* There are pending soft interrupts, so pick one. */
650 newl = softint_picklwp();
651 newl->l_stat = LSONPROC;
652 newl->l_pflag |= LP_RUNNING;
653 }
654 #endif /* !__HAVE_FAST_SOFTINTS */
655
656 /*
657 * If on the CPU and we have gotten this far, then we must yield.
658 */
659 if (l->l_stat == LSONPROC && l != newl) {
660 KASSERT(lwp_locked(l, spc->spc_lwplock));
661 KASSERT((l->l_flag & LW_IDLE) == 0);
662 l->l_stat = LSRUN;
663 lwp_setlock(l, spc->spc_mutex);
664 sched_enqueue(l);
665 sched_preempted(l);
666
667 /*
668 * Handle migration. Note that "migrating LWP" may
669 * be reset here, if interrupt/preemption happens
670 * early in idle LWP.
671 */
672 if (l->l_target_cpu != NULL && (l->l_pflag & LP_BOUND) == 0) {
673 KASSERT((l->l_pflag & LP_INTR) == 0);
674 spc->spc_migrating = l;
675 }
676 }
677
678 /* Pick new LWP to run. */
679 if (newl == NULL) {
680 newl = nextlwp(ci, spc);
681 }
682
683 /* Items that must be updated with the CPU locked. */
684 if (!returning) {
685 /* Count time spent in current system call */
686 SYSCALL_TIME_SLEEP(l);
687
688 updatertime(l, &bt);
689
690 /* Update the new LWP's start time. */
691 newl->l_stime = bt;
692
693 /*
694 * ci_curlwp changes when a fast soft interrupt occurs.
695 * We use ci_onproc to keep track of which kernel or
696 * user thread is running 'underneath' the software
697 * interrupt. This is important for time accounting,
698 * itimers and forcing user threads to preempt (aston).
699 */
700 ci->ci_onproc = newl;
701 }
702
703 /*
704 * Preemption related tasks. Must be done holding spc_mutex. Clear
705 * l_dopreempt without an atomic - it's only ever set non-zero by
706 * sched_resched_cpu() which also holds spc_mutex, and only ever
707 * cleared by the LWP itself (us) with atomics when not under lock.
708 */
709 l->l_dopreempt = 0;
710 if (__predict_false(l->l_pfailaddr != 0)) {
711 LOCKSTAT_FLAG(lsflag);
712 LOCKSTAT_ENTER(lsflag);
713 LOCKSTAT_STOP_TIMER(lsflag, l->l_pfailtime);
714 LOCKSTAT_EVENT_RA(lsflag, l->l_pfaillock, LB_NOPREEMPT|LB_SPIN,
715 1, l->l_pfailtime, l->l_pfailaddr);
716 LOCKSTAT_EXIT(lsflag);
717 l->l_pfailtime = 0;
718 l->l_pfaillock = 0;
719 l->l_pfailaddr = 0;
720 }
721
722 if (l != newl) {
723 struct lwp *prevlwp;
724
725 /* Release all locks, but leave the current LWP locked */
726 if (l->l_mutex == spc->spc_mutex) {
727 /*
728 * Drop spc_lwplock, if the current LWP has been moved
729 * to the run queue (it is now locked by spc_mutex).
730 */
731 mutex_spin_exit(spc->spc_lwplock);
732 } else {
733 /*
734 * Otherwise, drop the spc_mutex, we are done with the
735 * run queues.
736 */
737 mutex_spin_exit(spc->spc_mutex);
738 }
739
740 /* We're down to only one lock, so do debug checks. */
741 LOCKDEBUG_BARRIER(l->l_mutex, 1);
742
743 /* Count the context switch. */
744 CPU_COUNT(CPU_COUNT_NSWTCH, 1);
745 if ((l->l_pflag & LP_PREEMPTING) != 0) {
746 l->l_ru.ru_nivcsw++;
747 l->l_pflag &= ~LP_PREEMPTING;
748 } else {
749 l->l_ru.ru_nvcsw++;
750 }
751
752 /*
753 * Increase the count of spin-mutexes before the release
754 * of the last lock - we must remain at IPL_SCHED after
755 * releasing the lock.
756 */
757 KASSERTMSG(ci->ci_mtx_count == -1,
758 "%s: cpu%u: ci_mtx_count (%d) != -1 "
759 "(block with spin-mutex held)",
760 __func__, cpu_index(ci), ci->ci_mtx_count);
761 oldspl = MUTEX_SPIN_OLDSPL(ci);
762 ci->ci_mtx_count = -2;
763
764 /* Update status for lwpctl, if present. */
765 if (l->l_lwpctl != NULL) {
766 l->l_lwpctl->lc_curcpu = (l->l_stat == LSZOMB ?
767 LWPCTL_CPU_EXITED : LWPCTL_CPU_NONE);
768 }
769
770 /*
771 * If curlwp is a soft interrupt LWP, there's nobody on the
772 * other side to unlock - we're returning into an assembly
773 * trampoline. Unlock now. This is safe because this is a
774 * kernel LWP and is bound to current CPU: the worst anyone
775 * else will do to it, is to put it back onto this CPU's run
776 * queue (and the CPU is busy here right now!).
777 */
778 if (returning) {
779 /* Keep IPL_SCHED after this; MD code will fix up. */
780 l->l_pflag &= ~LP_RUNNING;
781 lwp_unlock(l);
782 } else {
783 /* A normal LWP: save old VM context. */
784 pmap_deactivate(l);
785 }
786
787 /*
788 * If DTrace has set the active vtime enum to anything
789 * other than INACTIVE (0), then it should have set the
790 * function to call.
791 */
792 if (__predict_false(dtrace_vtime_active)) {
793 (*dtrace_vtime_switch_func)(newl);
794 }
795
796 /*
797 * We must ensure not to come here from inside a read section.
798 */
799 KASSERT(pserialize_not_in_read_section());
800
801 /* Switch to the new LWP.. */
802 #ifdef MULTIPROCESSOR
803 KASSERT(curlwp == ci->ci_curlwp);
804 #endif
805 KASSERTMSG(l == curlwp, "l %p curlwp %p", l, curlwp);
806 prevlwp = cpu_switchto(l, newl, returning);
807 ci = curcpu();
808 #ifdef MULTIPROCESSOR
809 KASSERT(curlwp == ci->ci_curlwp);
810 #endif
811 KASSERTMSG(l == curlwp, "l %p curlwp %p prevlwp %p",
812 l, curlwp, prevlwp);
813 KASSERT(prevlwp != NULL);
814 KASSERT(l->l_cpu == ci);
815 KASSERT(ci->ci_mtx_count == -2);
816
817 /*
818 * Immediately mark the previous LWP as no longer running
819 * and unlock (to keep lock wait times short as possible).
820 * We'll still be at IPL_SCHED afterwards. If a zombie,
821 * don't touch after clearing LP_RUNNING as it could be
822 * reaped by another CPU. Issue a memory barrier to ensure
823 * this.
824 *
825 * atomic_store_release matches atomic_load_acquire in
826 * lwp_free.
827 */
828 KASSERT((prevlwp->l_pflag & LP_RUNNING) != 0);
829 lock = prevlwp->l_mutex;
830 if (__predict_false(prevlwp->l_stat == LSZOMB)) {
831 atomic_store_release(&prevlwp->l_pflag,
832 prevlwp->l_pflag & ~LP_RUNNING);
833 } else {
834 prevlwp->l_pflag &= ~LP_RUNNING;
835 }
836 mutex_spin_exit(lock);
837
838 /*
839 * Switched away - we have new curlwp.
840 * Restore VM context and IPL.
841 */
842 pmap_activate(l);
843 pcu_switchpoint(l);
844
845 /* Update status for lwpctl, if present. */
846 if (l->l_lwpctl != NULL) {
847 l->l_lwpctl->lc_curcpu = (int)cpu_index(ci);
848 l->l_lwpctl->lc_pctr++;
849 }
850
851 /*
852 * Normalize the spin mutex count and restore the previous
853 * SPL. Note that, unless the caller disabled preemption,
854 * we can be preempted at any time after this splx().
855 */
856 KASSERT(l->l_cpu == ci);
857 KASSERT(ci->ci_mtx_count == -1);
858 ci->ci_mtx_count = 0;
859 splx(oldspl);
860 } else {
861 /* Nothing to do - just unlock and return. */
862 mutex_spin_exit(spc->spc_mutex);
863 l->l_pflag &= ~LP_PREEMPTING;
864 lwp_unlock(l);
865 }
866
867 KASSERT(l == curlwp);
868 KASSERT(l->l_stat == LSONPROC || (l->l_flag & LW_IDLE) != 0);
869
870 SYSCALL_TIME_WAKEUP(l);
871 LOCKDEBUG_BARRIER(NULL, 1);
872 }
873
874 /*
875 * setrunnable: change LWP state to be runnable, placing it on the run queue.
876 *
877 * Call with the process and LWP locked. Will return with the LWP unlocked.
878 */
879 void
880 setrunnable(struct lwp *l)
881 {
882 struct proc *p = l->l_proc;
883 struct cpu_info *ci;
884 kmutex_t *oldlock;
885
886 KASSERT((l->l_flag & LW_IDLE) == 0);
887 KASSERT((l->l_flag & LW_DBGSUSPEND) == 0);
888 KASSERT(mutex_owned(p->p_lock));
889 KASSERT(lwp_locked(l, NULL));
890 KASSERT(l->l_mutex != l->l_cpu->ci_schedstate.spc_mutex);
891
892 switch (l->l_stat) {
893 case LSSTOP:
894 /*
895 * If we're being traced (possibly because someone attached us
896 * while we were stopped), check for a signal from the debugger.
897 */
898 if ((p->p_slflag & PSL_TRACED) != 0 && p->p_xsig != 0)
899 signotify(l);
900 p->p_nrlwps++;
901 break;
902 case LSSUSPENDED:
903 KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_lwplock));
904 l->l_flag &= ~LW_WSUSPEND;
905 p->p_nrlwps++;
906 cv_broadcast(&p->p_lwpcv);
907 break;
908 case LSSLEEP:
909 KASSERT(l->l_wchan != NULL);
910 break;
911 case LSIDL:
912 KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_lwplock));
913 break;
914 default:
915 panic("setrunnable: lwp %p state was %d", l, l->l_stat);
916 }
917
918 /*
919 * If the LWP was sleeping, start it again.
920 */
921 if (l->l_wchan != NULL) {
922 l->l_stat = LSSLEEP;
923 /* lwp_unsleep() will release the lock. */
924 lwp_unsleep(l, true);
925 return;
926 }
927
928 /*
929 * If the LWP is still on the CPU, mark it as LSONPROC. It may be
930 * about to call mi_switch(), in which case it will yield.
931 */
932 if ((l->l_pflag & LP_RUNNING) != 0) {
933 l->l_stat = LSONPROC;
934 l->l_slptime = 0;
935 lwp_unlock(l);
936 return;
937 }
938
939 /*
940 * Look for a CPU to run.
941 * Set the LWP runnable.
942 */
943 ci = sched_takecpu(l);
944 l->l_cpu = ci;
945 spc_lock(ci);
946 oldlock = lwp_setlock(l, l->l_cpu->ci_schedstate.spc_mutex);
947 sched_setrunnable(l);
948 l->l_stat = LSRUN;
949 l->l_slptime = 0;
950 sched_enqueue(l);
951 sched_resched_lwp(l, true);
952 /* SPC & LWP now unlocked. */
953 mutex_spin_exit(oldlock);
954 }
955
956 /*
957 * suspendsched:
958 *
959 * Convert all non-LW_SYSTEM LSSLEEP or LSRUN LWPs to LSSUSPENDED.
960 */
961 void
962 suspendsched(void)
963 {
964 CPU_INFO_ITERATOR cii;
965 struct cpu_info *ci;
966 struct lwp *l;
967 struct proc *p;
968
969 /*
970 * We do this by process in order not to violate the locking rules.
971 */
972 mutex_enter(&proc_lock);
973 PROCLIST_FOREACH(p, &allproc) {
974 mutex_enter(p->p_lock);
975 if ((p->p_flag & PK_SYSTEM) != 0) {
976 mutex_exit(p->p_lock);
977 continue;
978 }
979
980 if (p->p_stat != SSTOP) {
981 if (p->p_stat != SZOMB && p->p_stat != SDEAD) {
982 p->p_pptr->p_nstopchild++;
983 p->p_waited = 0;
984 }
985 p->p_stat = SSTOP;
986 }
987
988 LIST_FOREACH(l, &p->p_lwps, l_sibling) {
989 if (l == curlwp)
990 continue;
991
992 lwp_lock(l);
993
994 /*
995 * Set L_WREBOOT so that the LWP will suspend itself
996 * when it tries to return to user mode. We want to
997 * try and get to get as many LWPs as possible to
998 * the user / kernel boundary, so that they will
999 * release any locks that they hold.
1000 */
1001 l->l_flag |= (LW_WREBOOT | LW_WSUSPEND);
1002
1003 if (l->l_stat == LSSLEEP &&
1004 (l->l_flag & LW_SINTR) != 0) {
1005 /* setrunnable() will release the lock. */
1006 setrunnable(l);
1007 continue;
1008 }
1009
1010 lwp_unlock(l);
1011 }
1012
1013 mutex_exit(p->p_lock);
1014 }
1015 mutex_exit(&proc_lock);
1016
1017 /*
1018 * Kick all CPUs to make them preempt any LWPs running in user mode.
1019 * They'll trap into the kernel and suspend themselves in userret().
1020 *
1021 * Unusually, we don't hold any other scheduler object locked, which
1022 * would keep preemption off for sched_resched_cpu(), so disable it
1023 * explicitly.
1024 */
1025 kpreempt_disable();
1026 for (CPU_INFO_FOREACH(cii, ci)) {
1027 spc_lock(ci);
1028 sched_resched_cpu(ci, PRI_KERNEL, true);
1029 /* spc now unlocked */
1030 }
1031 kpreempt_enable();
1032 }
1033
1034 /*
1035 * sched_unsleep:
1036 *
1037 * The is called when the LWP has not been awoken normally but instead
1038 * interrupted: for example, if the sleep timed out. Because of this,
1039 * it's not a valid action for running or idle LWPs.
1040 */
1041 static void
1042 sched_unsleep(struct lwp *l, bool cleanup)
1043 {
1044
1045 lwp_unlock(l);
1046 panic("sched_unsleep");
1047 }
1048
1049 static void
1050 sched_changepri(struct lwp *l, pri_t pri)
1051 {
1052 struct schedstate_percpu *spc;
1053 struct cpu_info *ci;
1054
1055 KASSERT(lwp_locked(l, NULL));
1056
1057 ci = l->l_cpu;
1058 spc = &ci->ci_schedstate;
1059
1060 if (l->l_stat == LSRUN) {
1061 KASSERT(lwp_locked(l, spc->spc_mutex));
1062 sched_dequeue(l);
1063 l->l_priority = pri;
1064 sched_enqueue(l);
1065 sched_resched_lwp(l, false);
1066 } else if (l->l_stat == LSONPROC && l->l_class != SCHED_OTHER) {
1067 /* On priority drop, only evict realtime LWPs. */
1068 KASSERT(lwp_locked(l, spc->spc_lwplock));
1069 l->l_priority = pri;
1070 spc_lock(ci);
1071 sched_resched_cpu(ci, spc->spc_maxpriority, true);
1072 /* spc now unlocked */
1073 } else {
1074 l->l_priority = pri;
1075 }
1076 }
1077
1078 static void
1079 sched_lendpri(struct lwp *l, pri_t pri)
1080 {
1081 struct schedstate_percpu *spc;
1082 struct cpu_info *ci;
1083
1084 KASSERT(lwp_locked(l, NULL));
1085
1086 ci = l->l_cpu;
1087 spc = &ci->ci_schedstate;
1088
1089 if (l->l_stat == LSRUN) {
1090 KASSERT(lwp_locked(l, spc->spc_mutex));
1091 sched_dequeue(l);
1092 l->l_inheritedprio = pri;
1093 l->l_auxprio = MAX(l->l_inheritedprio, l->l_protectprio);
1094 sched_enqueue(l);
1095 sched_resched_lwp(l, false);
1096 } else if (l->l_stat == LSONPROC && l->l_class != SCHED_OTHER) {
1097 /* On priority drop, only evict realtime LWPs. */
1098 KASSERT(lwp_locked(l, spc->spc_lwplock));
1099 l->l_inheritedprio = pri;
1100 l->l_auxprio = MAX(l->l_inheritedprio, l->l_protectprio);
1101 spc_lock(ci);
1102 sched_resched_cpu(ci, spc->spc_maxpriority, true);
1103 /* spc now unlocked */
1104 } else {
1105 l->l_inheritedprio = pri;
1106 l->l_auxprio = MAX(l->l_inheritedprio, l->l_protectprio);
1107 }
1108 }
1109
1110 struct lwp *
1111 syncobj_noowner(wchan_t wchan)
1112 {
1113
1114 return NULL;
1115 }
1116
1117 /* Decay 95% of proc::p_pctcpu in 60 seconds, ccpu = exp(-1/20) */
1118 const fixpt_t ccpu = 0.95122942450071400909 * FSCALE;
1119
1120 /*
1121 * Constants for averages over 1, 5 and 15 minutes when sampling at
1122 * 5 second intervals.
1123 */
1124 static const fixpt_t cexp[ ] = {
1125 0.9200444146293232 * FSCALE, /* exp(-1/12) */
1126 0.9834714538216174 * FSCALE, /* exp(-1/60) */
1127 0.9944598480048967 * FSCALE, /* exp(-1/180) */
1128 };
1129
1130 /*
1131 * sched_pstats:
1132 *
1133 * => Update process statistics and check CPU resource allocation.
1134 * => Call scheduler-specific hook to eventually adjust LWP priorities.
1135 * => Compute load average of a quantity on 1, 5 and 15 minute intervals.
1136 */
1137 void
1138 sched_pstats(void)
1139 {
1140 struct loadavg *avg = &averunnable;
1141 const int clkhz = (stathz != 0 ? stathz : hz);
1142 static bool backwardslwp = false;
1143 static bool backwardsproc = false;
1144 static u_int lavg_count = 0;
1145 struct proc *p;
1146 int nrun;
1147
1148 sched_pstats_ticks++;
1149 if (++lavg_count >= 5) {
1150 lavg_count = 0;
1151 nrun = 0;
1152 }
1153 mutex_enter(&proc_lock);
1154 PROCLIST_FOREACH(p, &allproc) {
1155 struct lwp *l;
1156 struct rlimit *rlim;
1157 time_t runtm;
1158 int sig;
1159
1160 /* Increment sleep time (if sleeping), ignore overflow. */
1161 mutex_enter(p->p_lock);
1162 runtm = p->p_rtime.sec;
1163 LIST_FOREACH(l, &p->p_lwps, l_sibling) {
1164 fixpt_t lpctcpu;
1165 u_int lcpticks;
1166
1167 if (__predict_false((l->l_flag & LW_IDLE) != 0))
1168 continue;
1169 lwp_lock(l);
1170 if (__predict_false(l->l_rtime.sec < 0) &&
1171 !backwardslwp) {
1172 backwardslwp = true;
1173 printf("WARNING: lwp %ld (%s%s%s): "
1174 "negative runtime: "
1175 "(%jd + 0x%016"PRIx64"/2^64) sec\n",
1176 (long)l->l_lid,
1177 l->l_proc->p_comm,
1178 l->l_name ? " " : "",
1179 l->l_name ? l->l_name : "",
1180 (intmax_t)l->l_rtime.sec,
1181 l->l_rtime.frac);
1182 }
1183 runtm += l->l_rtime.sec;
1184 l->l_swtime++;
1185 sched_lwp_stats(l);
1186
1187 /* For load average calculation. */
1188 if (__predict_false(lavg_count == 0) &&
1189 (l->l_flag & (LW_SINTR | LW_SYSTEM)) == 0) {
1190 switch (l->l_stat) {
1191 case LSSLEEP:
1192 if (l->l_slptime > 1) {
1193 break;
1194 }
1195 /* FALLTHROUGH */
1196 case LSRUN:
1197 case LSONPROC:
1198 case LSIDL:
1199 nrun++;
1200 }
1201 }
1202 lwp_unlock(l);
1203
1204 l->l_pctcpu = (l->l_pctcpu * ccpu) >> FSHIFT;
1205 if (l->l_slptime != 0)
1206 continue;
1207
1208 lpctcpu = l->l_pctcpu;
1209 lcpticks = atomic_swap_uint(&l->l_cpticks, 0);
1210 lpctcpu += ((FSCALE - ccpu) *
1211 (lcpticks * FSCALE / clkhz)) >> FSHIFT;
1212 l->l_pctcpu = lpctcpu;
1213 }
1214 /* Calculating p_pctcpu only for ps(1) */
1215 p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
1216
1217 if (__predict_false(runtm < 0)) {
1218 if (!backwardsproc) {
1219 backwardsproc = true;
1220 printf("WARNING: pid %ld (%s): "
1221 "negative runtime; "
1222 "monotonic clock has gone backwards\n",
1223 (long)p->p_pid, p->p_comm);
1224 }
1225 mutex_exit(p->p_lock);
1226 continue;
1227 }
1228
1229 /*
1230 * Check if the process exceeds its CPU resource allocation.
1231 * If over the hard limit, kill it with SIGKILL.
1232 * If over the soft limit, send SIGXCPU and raise
1233 * the soft limit a little.
1234 */
1235 rlim = &p->p_rlimit[RLIMIT_CPU];
1236 sig = 0;
1237 if (__predict_false(runtm >= rlim->rlim_cur)) {
1238 if (runtm >= rlim->rlim_max) {
1239 sig = SIGKILL;
1240 log(LOG_NOTICE,
1241 "pid %d, command %s, is killed: %s\n",
1242 p->p_pid, p->p_comm, "exceeded RLIMIT_CPU");
1243 uprintf("pid %d, command %s, is killed: %s\n",
1244 p->p_pid, p->p_comm, "exceeded RLIMIT_CPU");
1245 } else {
1246 sig = SIGXCPU;
1247 if (rlim->rlim_cur < rlim->rlim_max)
1248 rlim->rlim_cur += 5;
1249 }
1250 }
1251 mutex_exit(p->p_lock);
1252 if (__predict_false(sig)) {
1253 KASSERT((p->p_flag & PK_SYSTEM) == 0);
1254 psignal(p, sig);
1255 }
1256 }
1257
1258 /* Load average calculation. */
1259 if (__predict_false(lavg_count == 0)) {
1260 int i;
1261 CTASSERT(__arraycount(cexp) == __arraycount(avg->ldavg));
1262 for (i = 0; i < __arraycount(cexp); i++) {
1263 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
1264 nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
1265 }
1266 }
1267
1268 /* Lightning bolt. */
1269 cv_broadcast(&lbolt);
1270
1271 mutex_exit(&proc_lock);
1272 }
1273