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