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