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