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