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