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