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