xref: /netbsd-src/sys/kern/kern_synch.c (revision 33881f779a77dce6440bdc44610d94de75bebefe)
1 /*	$NetBSD: kern_synch.c,v 1.344 2020/03/14 20:23:51 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.344 2020/03/14 20:23:51 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 		if (__predict_false((l->l_flag & LW_IDLE) != 0)) {
391 			/* Can't preempt idle loop, don't count as failure. */
392 			atomic_swap_uint(&l->l_dopreempt, 0);
393 			return true;
394 		}
395 		if (__predict_false(l->l_nopreempt != 0)) {
396 			/* LWP holds preemption disabled, explicitly. */
397 			if ((dop & DOPREEMPT_COUNTED) == 0) {
398 				kpreempt_ev_crit.ev_count++;
399 			}
400 			failed = (uintptr_t)&kpreempt_is_disabled;
401 			break;
402 		}
403 		if (__predict_false((l->l_pflag & LP_INTR) != 0)) {
404 			/* Can't preempt soft interrupts yet. */
405 			atomic_swap_uint(&l->l_dopreempt, 0);
406 			failed = (uintptr_t)&is_softint_lwp;
407 			break;
408 		}
409 		s = splsched();
410 		if (__predict_false(l->l_blcnt != 0 ||
411 		    curcpu()->ci_biglock_wanted != NULL)) {
412 			/* Hold or want kernel_lock, code is not MT safe. */
413 			splx(s);
414 			if ((dop & DOPREEMPT_COUNTED) == 0) {
415 				kpreempt_ev_klock.ev_count++;
416 			}
417 			failed = (uintptr_t)&kernel_lock_held;
418 			break;
419 		}
420 		if (__predict_false(!cpu_kpreempt_enter(where, s))) {
421 			/*
422 			 * It may be that the IPL is too high.
423 			 * kpreempt_enter() can schedule an
424 			 * interrupt to retry later.
425 			 */
426 			splx(s);
427 			failed = (uintptr_t)&spl_is_raised;
428 			break;
429 		}
430 		/* Do it! */
431 		if (__predict_true((dop & DOPREEMPT_COUNTED) == 0)) {
432 			kpreempt_ev_immed.ev_count++;
433 		}
434 		lwp_lock(l);
435 		/* Involuntary - keep kpriority boost. */
436 		l->l_pflag |= LP_PREEMPTING;
437 		spc_lock(l->l_cpu);
438 		mi_switch(l);
439 		l->l_nopreempt++;
440 		splx(s);
441 
442 		/* Take care of any MD cleanup. */
443 		cpu_kpreempt_exit(where);
444 		l->l_nopreempt--;
445 	}
446 
447 	if (__predict_true(!failed)) {
448 		return false;
449 	}
450 
451 	/* Record preemption failure for reporting via lockstat. */
452 	atomic_or_uint(&l->l_dopreempt, DOPREEMPT_COUNTED);
453 	lsflag = 0;
454 	LOCKSTAT_ENTER(lsflag);
455 	if (__predict_false(lsflag)) {
456 		if (where == 0) {
457 			where = (uintptr_t)__builtin_return_address(0);
458 		}
459 		/* Preemption is on, might recurse, so make it atomic. */
460 		if (atomic_cas_ptr_ni((void *)&l->l_pfailaddr, NULL,
461 		    (void *)where) == NULL) {
462 			LOCKSTAT_START_TIMER(lsflag, l->l_pfailtime);
463 			l->l_pfaillock = failed;
464 		}
465 	}
466 	LOCKSTAT_EXIT(lsflag);
467 	return true;
468 }
469 
470 /*
471  * Return true if preemption is explicitly disabled.
472  */
473 bool
474 kpreempt_disabled(void)
475 {
476 	const lwp_t *l = curlwp;
477 
478 	return l->l_nopreempt != 0 || l->l_stat == LSZOMB ||
479 	    (l->l_flag & LW_IDLE) != 0 || (l->l_pflag & LP_INTR) != 0 ||
480 	    cpu_kpreempt_disabled();
481 }
482 
483 /*
484  * Disable kernel preemption.
485  */
486 void
487 kpreempt_disable(void)
488 {
489 
490 	KPREEMPT_DISABLE(curlwp);
491 }
492 
493 /*
494  * Reenable kernel preemption.
495  */
496 void
497 kpreempt_enable(void)
498 {
499 
500 	KPREEMPT_ENABLE(curlwp);
501 }
502 
503 /*
504  * Compute the amount of time during which the current lwp was running.
505  *
506  * - update l_rtime unless it's an idle lwp.
507  */
508 
509 void
510 updatertime(lwp_t *l, const struct bintime *now)
511 {
512 
513 	if (__predict_false(l->l_flag & LW_IDLE))
514 		return;
515 
516 	/* rtime += now - stime */
517 	bintime_add(&l->l_rtime, now);
518 	bintime_sub(&l->l_rtime, &l->l_stime);
519 }
520 
521 /*
522  * Select next LWP from the current CPU to run..
523  */
524 static inline lwp_t *
525 nextlwp(struct cpu_info *ci, struct schedstate_percpu *spc)
526 {
527 	lwp_t *newl;
528 
529 	/*
530 	 * Let sched_nextlwp() select the LWP to run the CPU next.
531 	 * If no LWP is runnable, select the idle LWP.
532 	 *
533 	 * On arrival here LWPs on a run queue are locked by spc_mutex which
534 	 * is currently held.  Idle LWPs are always locked by spc_lwplock,
535 	 * which may or may not be held here.  On exit from this code block,
536 	 * in all cases newl is locked by spc_lwplock.
537 	 */
538 	newl = sched_nextlwp();
539 	if (newl != NULL) {
540 		sched_dequeue(newl);
541 		KASSERT(lwp_locked(newl, spc->spc_mutex));
542 		KASSERT(newl->l_cpu == ci);
543 		newl->l_stat = LSONPROC;
544 		newl->l_pflag |= LP_RUNNING;
545 		spc->spc_curpriority = lwp_eprio(newl);
546 		spc->spc_flags &= ~(SPCF_SWITCHCLEAR | SPCF_IDLE);
547 		lwp_setlock(newl, spc->spc_lwplock);
548 	} else {
549 		/*
550 		 * Updates to newl here are unlocked, but newl is the idle
551 		 * LWP and thus sheltered from outside interference, so no
552 		 * harm is going to come of it.
553 		 */
554 		newl = ci->ci_data.cpu_idlelwp;
555 		newl->l_stat = LSONPROC;
556 		newl->l_pflag |= LP_RUNNING;
557 		spc->spc_curpriority = PRI_IDLE;
558 		spc->spc_flags = (spc->spc_flags & ~SPCF_SWITCHCLEAR) |
559 		    SPCF_IDLE;
560 	}
561 
562 	/*
563 	 * Only clear want_resched if there are no pending (slow) software
564 	 * interrupts.  We can do this without an atomic, because no new
565 	 * LWPs can appear in the queue due to our hold on spc_mutex, and
566 	 * the update to ci_want_resched will become globally visible before
567 	 * the release of spc_mutex becomes globally visible.
568 	 */
569 	ci->ci_want_resched = ci->ci_data.cpu_softints;
570 
571 	return newl;
572 }
573 
574 /*
575  * The machine independent parts of context switch.
576  *
577  * NOTE: l->l_cpu is not changed in this routine, because an LWP never
578  * changes its own l_cpu (that would screw up curcpu on many ports and could
579  * cause all kinds of other evil stuff).  l_cpu is always changed by some
580  * other actor, when it's known the LWP is not running (the LP_RUNNING flag
581  * is checked under lock).
582  */
583 void
584 mi_switch(lwp_t *l)
585 {
586 	struct cpu_info *ci;
587 	struct schedstate_percpu *spc;
588 	struct lwp *newl;
589 	kmutex_t *lock;
590 	int oldspl;
591 	struct bintime bt;
592 	bool returning;
593 
594 	KASSERT(lwp_locked(l, NULL));
595 	KASSERT(kpreempt_disabled());
596 	KASSERT(mutex_owned(curcpu()->ci_schedstate.spc_mutex));
597 	KASSERTMSG(l->l_blcnt == 0, "kernel_lock leaked");
598 
599 	kstack_check_magic(l);
600 
601 	binuptime(&bt);
602 
603 	KASSERTMSG(l == curlwp, "l %p curlwp %p", l, curlwp);
604 	KASSERT((l->l_pflag & LP_RUNNING) != 0);
605 	KASSERT(l->l_cpu == curcpu() || l->l_stat == LSRUN);
606 	ci = curcpu();
607 	spc = &ci->ci_schedstate;
608 	returning = false;
609 	newl = NULL;
610 
611 	/*
612 	 * If we have been asked to switch to a specific LWP, then there
613 	 * is no need to inspect the run queues.  If a soft interrupt is
614 	 * blocking, then return to the interrupted thread without adjusting
615 	 * VM context or its start time: neither have been changed in order
616 	 * to take the interrupt.
617 	 */
618 	if (l->l_switchto != NULL) {
619 		if ((l->l_pflag & LP_INTR) != 0) {
620 			returning = true;
621 			softint_block(l);
622 			if ((l->l_pflag & LP_TIMEINTR) != 0)
623 				updatertime(l, &bt);
624 		}
625 		newl = l->l_switchto;
626 		l->l_switchto = NULL;
627 	}
628 #ifndef __HAVE_FAST_SOFTINTS
629 	else if (ci->ci_data.cpu_softints != 0) {
630 		/* There are pending soft interrupts, so pick one. */
631 		newl = softint_picklwp();
632 		newl->l_stat = LSONPROC;
633 		newl->l_pflag |= LP_RUNNING;
634 	}
635 #endif	/* !__HAVE_FAST_SOFTINTS */
636 
637 	/*
638 	 * If on the CPU and we have gotten this far, then we must yield.
639 	 */
640 	if (l->l_stat == LSONPROC && l != newl) {
641 		KASSERT(lwp_locked(l, spc->spc_lwplock));
642 		KASSERT((l->l_flag & LW_IDLE) == 0);
643 		l->l_stat = LSRUN;
644 		lwp_setlock(l, spc->spc_mutex);
645 		sched_enqueue(l);
646 		sched_preempted(l);
647 
648 		/*
649 		 * Handle migration.  Note that "migrating LWP" may
650 		 * be reset here, if interrupt/preemption happens
651 		 * early in idle LWP.
652 		 */
653 		if (l->l_target_cpu != NULL && (l->l_pflag & LP_BOUND) == 0) {
654 			KASSERT((l->l_pflag & LP_INTR) == 0);
655 			spc->spc_migrating = l;
656 		}
657 	}
658 
659 	/* Pick new LWP to run. */
660 	if (newl == NULL) {
661 		newl = nextlwp(ci, spc);
662 	}
663 
664 	/* Items that must be updated with the CPU locked. */
665 	if (!returning) {
666 		/* Count time spent in current system call */
667 		SYSCALL_TIME_SLEEP(l);
668 
669 		updatertime(l, &bt);
670 
671 		/* Update the new LWP's start time. */
672 		newl->l_stime = bt;
673 
674 		/*
675 		 * ci_curlwp changes when a fast soft interrupt occurs.
676 		 * We use ci_onproc to keep track of which kernel or
677 		 * user thread is running 'underneath' the software
678 		 * interrupt.  This is important for time accounting,
679 		 * itimers and forcing user threads to preempt (aston).
680 		 */
681 		ci->ci_onproc = newl;
682 	}
683 
684 	/*
685 	 * Preemption related tasks.  Must be done holding spc_mutex.  Clear
686 	 * l_dopreempt without an atomic - it's only ever set non-zero by
687 	 * sched_resched_cpu() which also holds spc_mutex, and only ever
688 	 * cleared by the LWP itself (us) with atomics when not under lock.
689 	 */
690 	l->l_dopreempt = 0;
691 	if (__predict_false(l->l_pfailaddr != 0)) {
692 		LOCKSTAT_FLAG(lsflag);
693 		LOCKSTAT_ENTER(lsflag);
694 		LOCKSTAT_STOP_TIMER(lsflag, l->l_pfailtime);
695 		LOCKSTAT_EVENT_RA(lsflag, l->l_pfaillock, LB_NOPREEMPT|LB_SPIN,
696 		    1, l->l_pfailtime, l->l_pfailaddr);
697 		LOCKSTAT_EXIT(lsflag);
698 		l->l_pfailtime = 0;
699 		l->l_pfaillock = 0;
700 		l->l_pfailaddr = 0;
701 	}
702 
703 	if (l != newl) {
704 		struct lwp *prevlwp;
705 
706 		/* Release all locks, but leave the current LWP locked */
707 		if (l->l_mutex == spc->spc_mutex) {
708 			/*
709 			 * Drop spc_lwplock, if the current LWP has been moved
710 			 * to the run queue (it is now locked by spc_mutex).
711 			 */
712 			mutex_spin_exit(spc->spc_lwplock);
713 		} else {
714 			/*
715 			 * Otherwise, drop the spc_mutex, we are done with the
716 			 * run queues.
717 			 */
718 			mutex_spin_exit(spc->spc_mutex);
719 		}
720 
721 		/* We're down to only one lock, so do debug checks. */
722 		LOCKDEBUG_BARRIER(l->l_mutex, 1);
723 
724 		/* Count the context switch. */
725 		CPU_COUNT(CPU_COUNT_NSWTCH, 1);
726 		l->l_ncsw++;
727 		if ((l->l_pflag & LP_PREEMPTING) != 0) {
728 			l->l_nivcsw++;
729 			l->l_pflag &= ~LP_PREEMPTING;
730 		}
731 
732 		/*
733 		 * Increase the count of spin-mutexes before the release
734 		 * of the last lock - we must remain at IPL_SCHED after
735 		 * releasing the lock.
736 		 */
737 		KASSERTMSG(ci->ci_mtx_count == -1,
738 		    "%s: cpu%u: ci_mtx_count (%d) != -1 "
739 		    "(block with spin-mutex held)",
740 		     __func__, cpu_index(ci), ci->ci_mtx_count);
741 		oldspl = MUTEX_SPIN_OLDSPL(ci);
742 		ci->ci_mtx_count = -2;
743 
744 		/* Update status for lwpctl, if present. */
745 		if (l->l_lwpctl != NULL) {
746 			l->l_lwpctl->lc_curcpu = (l->l_stat == LSZOMB ?
747 			    LWPCTL_CPU_EXITED : LWPCTL_CPU_NONE);
748 		}
749 
750 		/*
751 		 * If curlwp is a soft interrupt LWP, there's nobody on the
752 		 * other side to unlock - we're returning into an assembly
753 		 * trampoline.  Unlock now.  This is safe because this is a
754 		 * kernel LWP and is bound to current CPU: the worst anyone
755 		 * else will do to it, is to put it back onto this CPU's run
756 		 * queue (and the CPU is busy here right now!).
757 		 */
758 		if (returning) {
759 			/* Keep IPL_SCHED after this; MD code will fix up. */
760 			l->l_pflag &= ~LP_RUNNING;
761 			lwp_unlock(l);
762 		} else {
763 			/* A normal LWP: save old VM context. */
764 			pmap_deactivate(l);
765 		}
766 
767 		/*
768 		 * If DTrace has set the active vtime enum to anything
769 		 * other than INACTIVE (0), then it should have set the
770 		 * function to call.
771 		 */
772 		if (__predict_false(dtrace_vtime_active)) {
773 			(*dtrace_vtime_switch_func)(newl);
774 		}
775 
776 		/*
777 		 * We must ensure not to come here from inside a read section.
778 		 */
779 		KASSERT(pserialize_not_in_read_section());
780 
781 		/* Switch to the new LWP.. */
782 #ifdef MULTIPROCESSOR
783 		KASSERT(curlwp == ci->ci_curlwp);
784 #endif
785 		KASSERTMSG(l == curlwp, "l %p curlwp %p", l, curlwp);
786 		prevlwp = cpu_switchto(l, newl, returning);
787 		ci = curcpu();
788 #ifdef MULTIPROCESSOR
789 		KASSERT(curlwp == ci->ci_curlwp);
790 #endif
791 		KASSERTMSG(l == curlwp, "l %p curlwp %p prevlwp %p",
792 		    l, curlwp, prevlwp);
793 		KASSERT(prevlwp != NULL);
794 		KASSERT(l->l_cpu == ci);
795 		KASSERT(ci->ci_mtx_count == -2);
796 
797 		/*
798 		 * Immediately mark the previous LWP as no longer running
799 		 * and unlock (to keep lock wait times short as possible).
800 		 * We'll still be at IPL_SCHED afterwards.  If a zombie,
801 		 * don't touch after clearing LP_RUNNING as it could be
802 		 * reaped by another CPU.  Issue a memory barrier to ensure
803 		 * this.
804 		 */
805 		KASSERT((prevlwp->l_pflag & LP_RUNNING) != 0);
806 		lock = prevlwp->l_mutex;
807 		if (__predict_false(prevlwp->l_stat == LSZOMB)) {
808 			membar_sync();
809 		}
810 		prevlwp->l_pflag &= ~LP_RUNNING;
811 		mutex_spin_exit(lock);
812 
813 		/*
814 		 * Switched away - we have new curlwp.
815 		 * Restore VM context and IPL.
816 		 */
817 		pmap_activate(l);
818 		pcu_switchpoint(l);
819 
820 		/* Update status for lwpctl, if present. */
821 		if (l->l_lwpctl != NULL) {
822 			l->l_lwpctl->lc_curcpu = (int)cpu_index(ci);
823 			l->l_lwpctl->lc_pctr++;
824 		}
825 
826 		/*
827 		 * Normalize the spin mutex count and restore the previous
828 		 * SPL.  Note that, unless the caller disabled preemption,
829 		 * we can be preempted at any time after this splx().
830 		 */
831 		KASSERT(l->l_cpu == ci);
832 		KASSERT(ci->ci_mtx_count == -1);
833 		ci->ci_mtx_count = 0;
834 		splx(oldspl);
835 	} else {
836 		/* Nothing to do - just unlock and return. */
837 		mutex_spin_exit(spc->spc_mutex);
838 		l->l_pflag &= ~LP_PREEMPTING;
839 		lwp_unlock(l);
840 	}
841 
842 	KASSERT(l == curlwp);
843 	KASSERT(l->l_stat == LSONPROC);
844 
845 	SYSCALL_TIME_WAKEUP(l);
846 	LOCKDEBUG_BARRIER(NULL, 1);
847 }
848 
849 /*
850  * setrunnable: change LWP state to be runnable, placing it on the run queue.
851  *
852  * Call with the process and LWP locked.  Will return with the LWP unlocked.
853  */
854 void
855 setrunnable(struct lwp *l)
856 {
857 	struct proc *p = l->l_proc;
858 	struct cpu_info *ci;
859 	kmutex_t *oldlock;
860 
861 	KASSERT((l->l_flag & LW_IDLE) == 0);
862 	KASSERT((l->l_flag & LW_DBGSUSPEND) == 0);
863 	KASSERT(mutex_owned(p->p_lock));
864 	KASSERT(lwp_locked(l, NULL));
865 	KASSERT(l->l_mutex != l->l_cpu->ci_schedstate.spc_mutex);
866 
867 	switch (l->l_stat) {
868 	case LSSTOP:
869 		/*
870 		 * If we're being traced (possibly because someone attached us
871 		 * while we were stopped), check for a signal from the debugger.
872 		 */
873 		if ((p->p_slflag & PSL_TRACED) != 0 && p->p_xsig != 0)
874 			signotify(l);
875 		p->p_nrlwps++;
876 		break;
877 	case LSSUSPENDED:
878 		KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_lwplock));
879 		l->l_flag &= ~LW_WSUSPEND;
880 		p->p_nrlwps++;
881 		cv_broadcast(&p->p_lwpcv);
882 		break;
883 	case LSSLEEP:
884 		KASSERT(l->l_wchan != NULL);
885 		break;
886 	case LSIDL:
887 		KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_lwplock));
888 		break;
889 	default:
890 		panic("setrunnable: lwp %p state was %d", l, l->l_stat);
891 	}
892 
893 	/*
894 	 * If the LWP was sleeping, start it again.
895 	 */
896 	if (l->l_wchan != NULL) {
897 		l->l_stat = LSSLEEP;
898 		/* lwp_unsleep() will release the lock. */
899 		lwp_unsleep(l, true);
900 		return;
901 	}
902 
903 	/*
904 	 * If the LWP is still on the CPU, mark it as LSONPROC.  It may be
905 	 * about to call mi_switch(), in which case it will yield.
906 	 */
907 	if ((l->l_pflag & LP_RUNNING) != 0) {
908 		l->l_stat = LSONPROC;
909 		l->l_slptime = 0;
910 		lwp_unlock(l);
911 		return;
912 	}
913 
914 	/*
915 	 * Look for a CPU to run.
916 	 * Set the LWP runnable.
917 	 */
918 	ci = sched_takecpu(l);
919 	l->l_cpu = ci;
920 	spc_lock(ci);
921 	oldlock = lwp_setlock(l, l->l_cpu->ci_schedstate.spc_mutex);
922 	sched_setrunnable(l);
923 	l->l_stat = LSRUN;
924 	l->l_slptime = 0;
925 	sched_enqueue(l);
926 	sched_resched_lwp(l, true);
927 	/* SPC & LWP now unlocked. */
928 	mutex_spin_exit(oldlock);
929 }
930 
931 /*
932  * suspendsched:
933  *
934  *	Convert all non-LW_SYSTEM LSSLEEP or LSRUN LWPs to LSSUSPENDED.
935  */
936 void
937 suspendsched(void)
938 {
939 	CPU_INFO_ITERATOR cii;
940 	struct cpu_info *ci;
941 	struct lwp *l;
942 	struct proc *p;
943 
944 	/*
945 	 * We do this by process in order not to violate the locking rules.
946 	 */
947 	mutex_enter(proc_lock);
948 	PROCLIST_FOREACH(p, &allproc) {
949 		mutex_enter(p->p_lock);
950 		if ((p->p_flag & PK_SYSTEM) != 0) {
951 			mutex_exit(p->p_lock);
952 			continue;
953 		}
954 
955 		if (p->p_stat != SSTOP) {
956 			if (p->p_stat != SZOMB && p->p_stat != SDEAD) {
957 				p->p_pptr->p_nstopchild++;
958 				p->p_waited = 0;
959 			}
960 			p->p_stat = SSTOP;
961 		}
962 
963 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
964 			if (l == curlwp)
965 				continue;
966 
967 			lwp_lock(l);
968 
969 			/*
970 			 * Set L_WREBOOT so that the LWP will suspend itself
971 			 * when it tries to return to user mode.  We want to
972 			 * try and get to get as many LWPs as possible to
973 			 * the user / kernel boundary, so that they will
974 			 * release any locks that they hold.
975 			 */
976 			l->l_flag |= (LW_WREBOOT | LW_WSUSPEND);
977 
978 			if (l->l_stat == LSSLEEP &&
979 			    (l->l_flag & LW_SINTR) != 0) {
980 				/* setrunnable() will release the lock. */
981 				setrunnable(l);
982 				continue;
983 			}
984 
985 			lwp_unlock(l);
986 		}
987 
988 		mutex_exit(p->p_lock);
989 	}
990 	mutex_exit(proc_lock);
991 
992 	/*
993 	 * Kick all CPUs to make them preempt any LWPs running in user mode.
994 	 * They'll trap into the kernel and suspend themselves in userret().
995 	 *
996 	 * Unusually, we don't hold any other scheduler object locked, which
997 	 * would keep preemption off for sched_resched_cpu(), so disable it
998 	 * explicitly.
999 	 */
1000 	kpreempt_disable();
1001 	for (CPU_INFO_FOREACH(cii, ci)) {
1002 		spc_lock(ci);
1003 		sched_resched_cpu(ci, PRI_KERNEL, true);
1004 		/* spc now unlocked */
1005 	}
1006 	kpreempt_enable();
1007 }
1008 
1009 /*
1010  * sched_unsleep:
1011  *
1012  *	The is called when the LWP has not been awoken normally but instead
1013  *	interrupted: for example, if the sleep timed out.  Because of this,
1014  *	it's not a valid action for running or idle LWPs.
1015  */
1016 static void
1017 sched_unsleep(struct lwp *l, bool cleanup)
1018 {
1019 
1020 	lwp_unlock(l);
1021 	panic("sched_unsleep");
1022 }
1023 
1024 static void
1025 sched_changepri(struct lwp *l, pri_t pri)
1026 {
1027 	struct schedstate_percpu *spc;
1028 	struct cpu_info *ci;
1029 
1030 	KASSERT(lwp_locked(l, NULL));
1031 
1032 	ci = l->l_cpu;
1033 	spc = &ci->ci_schedstate;
1034 
1035 	if (l->l_stat == LSRUN) {
1036 		KASSERT(lwp_locked(l, spc->spc_mutex));
1037 		sched_dequeue(l);
1038 		l->l_priority = pri;
1039 		sched_enqueue(l);
1040 		sched_resched_lwp(l, false);
1041 	} else if (l->l_stat == LSONPROC && l->l_class != SCHED_OTHER) {
1042 		/* On priority drop, only evict realtime LWPs. */
1043 		KASSERT(lwp_locked(l, spc->spc_lwplock));
1044 		l->l_priority = pri;
1045 		spc_lock(ci);
1046 		sched_resched_cpu(ci, spc->spc_maxpriority, true);
1047 		/* spc now unlocked */
1048 	} else {
1049 		l->l_priority = pri;
1050 	}
1051 }
1052 
1053 static void
1054 sched_lendpri(struct lwp *l, pri_t pri)
1055 {
1056 	struct schedstate_percpu *spc;
1057 	struct cpu_info *ci;
1058 
1059 	KASSERT(lwp_locked(l, NULL));
1060 
1061 	ci = l->l_cpu;
1062 	spc = &ci->ci_schedstate;
1063 
1064 	if (l->l_stat == LSRUN) {
1065 		KASSERT(lwp_locked(l, spc->spc_mutex));
1066 		sched_dequeue(l);
1067 		l->l_inheritedprio = pri;
1068 		l->l_auxprio = MAX(l->l_inheritedprio, l->l_protectprio);
1069 		sched_enqueue(l);
1070 		sched_resched_lwp(l, false);
1071 	} else if (l->l_stat == LSONPROC && l->l_class != SCHED_OTHER) {
1072 		/* On priority drop, only evict realtime LWPs. */
1073 		KASSERT(lwp_locked(l, spc->spc_lwplock));
1074 		l->l_inheritedprio = pri;
1075 		l->l_auxprio = MAX(l->l_inheritedprio, l->l_protectprio);
1076 		spc_lock(ci);
1077 		sched_resched_cpu(ci, spc->spc_maxpriority, true);
1078 		/* spc now unlocked */
1079 	} else {
1080 		l->l_inheritedprio = pri;
1081 		l->l_auxprio = MAX(l->l_inheritedprio, l->l_protectprio);
1082 	}
1083 }
1084 
1085 struct lwp *
1086 syncobj_noowner(wchan_t wchan)
1087 {
1088 
1089 	return NULL;
1090 }
1091 
1092 /* Decay 95% of proc::p_pctcpu in 60 seconds, ccpu = exp(-1/20) */
1093 const fixpt_t ccpu = 0.95122942450071400909 * FSCALE;
1094 
1095 /*
1096  * Constants for averages over 1, 5 and 15 minutes when sampling at
1097  * 5 second intervals.
1098  */
1099 static const fixpt_t cexp[ ] = {
1100 	0.9200444146293232 * FSCALE,	/* exp(-1/12) */
1101 	0.9834714538216174 * FSCALE,	/* exp(-1/60) */
1102 	0.9944598480048967 * FSCALE,	/* exp(-1/180) */
1103 };
1104 
1105 /*
1106  * sched_pstats:
1107  *
1108  * => Update process statistics and check CPU resource allocation.
1109  * => Call scheduler-specific hook to eventually adjust LWP priorities.
1110  * => Compute load average of a quantity on 1, 5 and 15 minute intervals.
1111  */
1112 void
1113 sched_pstats(void)
1114 {
1115 	extern struct loadavg averunnable;
1116 	struct loadavg *avg = &averunnable;
1117 	const int clkhz = (stathz != 0 ? stathz : hz);
1118 	static bool backwards = false;
1119 	static u_int lavg_count = 0;
1120 	struct proc *p;
1121 	int nrun;
1122 
1123 	sched_pstats_ticks++;
1124 	if (++lavg_count >= 5) {
1125 		lavg_count = 0;
1126 		nrun = 0;
1127 	}
1128 	mutex_enter(proc_lock);
1129 	PROCLIST_FOREACH(p, &allproc) {
1130 		struct lwp *l;
1131 		struct rlimit *rlim;
1132 		time_t runtm;
1133 		int sig;
1134 
1135 		/* Increment sleep time (if sleeping), ignore overflow. */
1136 		mutex_enter(p->p_lock);
1137 		runtm = p->p_rtime.sec;
1138 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
1139 			fixpt_t lpctcpu;
1140 			u_int lcpticks;
1141 
1142 			if (__predict_false((l->l_flag & LW_IDLE) != 0))
1143 				continue;
1144 			lwp_lock(l);
1145 			runtm += l->l_rtime.sec;
1146 			l->l_swtime++;
1147 			sched_lwp_stats(l);
1148 
1149 			/* For load average calculation. */
1150 			if (__predict_false(lavg_count == 0) &&
1151 			    (l->l_flag & (LW_SINTR | LW_SYSTEM)) == 0) {
1152 				switch (l->l_stat) {
1153 				case LSSLEEP:
1154 					if (l->l_slptime > 1) {
1155 						break;
1156 					}
1157 					/* FALLTHROUGH */
1158 				case LSRUN:
1159 				case LSONPROC:
1160 				case LSIDL:
1161 					nrun++;
1162 				}
1163 			}
1164 			lwp_unlock(l);
1165 
1166 			l->l_pctcpu = (l->l_pctcpu * ccpu) >> FSHIFT;
1167 			if (l->l_slptime != 0)
1168 				continue;
1169 
1170 			lpctcpu = l->l_pctcpu;
1171 			lcpticks = atomic_swap_uint(&l->l_cpticks, 0);
1172 			lpctcpu += ((FSCALE - ccpu) *
1173 			    (lcpticks * FSCALE / clkhz)) >> FSHIFT;
1174 			l->l_pctcpu = lpctcpu;
1175 		}
1176 		/* Calculating p_pctcpu only for ps(1) */
1177 		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
1178 
1179 		if (__predict_false(runtm < 0)) {
1180 			if (!backwards) {
1181 				backwards = true;
1182 				printf("WARNING: negative runtime; "
1183 				    "monotonic clock has gone backwards\n");
1184 			}
1185 			mutex_exit(p->p_lock);
1186 			continue;
1187 		}
1188 
1189 		/*
1190 		 * Check if the process exceeds its CPU resource allocation.
1191 		 * If over the hard limit, kill it with SIGKILL.
1192 		 * If over the soft limit, send SIGXCPU and raise
1193 		 * the soft limit a little.
1194 		 */
1195 		rlim = &p->p_rlimit[RLIMIT_CPU];
1196 		sig = 0;
1197 		if (__predict_false(runtm >= rlim->rlim_cur)) {
1198 			if (runtm >= rlim->rlim_max) {
1199 				sig = SIGKILL;
1200 				log(LOG_NOTICE,
1201 				    "pid %d, command %s, is killed: %s\n",
1202 				    p->p_pid, p->p_comm, "exceeded RLIMIT_CPU");
1203 				uprintf("pid %d, command %s, is killed: %s\n",
1204 				    p->p_pid, p->p_comm, "exceeded RLIMIT_CPU");
1205 			} else {
1206 				sig = SIGXCPU;
1207 				if (rlim->rlim_cur < rlim->rlim_max)
1208 					rlim->rlim_cur += 5;
1209 			}
1210 		}
1211 		mutex_exit(p->p_lock);
1212 		if (__predict_false(sig)) {
1213 			KASSERT((p->p_flag & PK_SYSTEM) == 0);
1214 			psignal(p, sig);
1215 		}
1216 	}
1217 
1218 	/* Load average calculation. */
1219 	if (__predict_false(lavg_count == 0)) {
1220 		int i;
1221 		CTASSERT(__arraycount(cexp) == __arraycount(avg->ldavg));
1222 		for (i = 0; i < __arraycount(cexp); i++) {
1223 			avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
1224 			    nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
1225 		}
1226 	}
1227 
1228 	/* Lightning bolt. */
1229 	cv_broadcast(&lbolt);
1230 
1231 	mutex_exit(proc_lock);
1232 }
1233