Home | History | Annotate | Line # | Download | only in kern
kern_synch.c revision 1.186.2.20
      1 /*	$NetBSD: kern_synch.c,v 1.186.2.20 2007/10/23 20:17:12 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999, 2000, 2004, 2006, 2007 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
      9  * NASA Ames Research Center, by Charles M. Hannum, Andrew Doran and
     10  * Daniel Sieger.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. All advertising materials mentioning features or use of this software
     21  *    must display the following acknowledgement:
     22  *	This product includes software developed by the NetBSD
     23  *	Foundation, Inc. and its contributors.
     24  * 4. Neither the name of The NetBSD Foundation nor the names of its
     25  *    contributors may be used to endorse or promote products derived
     26  *    from this software without specific prior written permission.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     29  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     30  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     31  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     32  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     34  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     36  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     37  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     38  * POSSIBILITY OF SUCH DAMAGE.
     39  */
     40 
     41 /*-
     42  * Copyright (c) 1982, 1986, 1990, 1991, 1993
     43  *	The Regents of the University of California.  All rights reserved.
     44  * (c) UNIX System Laboratories, Inc.
     45  * All or some portions of this file are derived from material licensed
     46  * to the University of California by American Telephone and Telegraph
     47  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     48  * the permission of UNIX System Laboratories, Inc.
     49  *
     50  * Redistribution and use in source and binary forms, with or without
     51  * modification, are permitted provided that the following conditions
     52  * are met:
     53  * 1. Redistributions of source code must retain the above copyright
     54  *    notice, this list of conditions and the following disclaimer.
     55  * 2. Redistributions in binary form must reproduce the above copyright
     56  *    notice, this list of conditions and the following disclaimer in the
     57  *    documentation and/or other materials provided with the distribution.
     58  * 3. Neither the name of the University nor the names of its contributors
     59  *    may be used to endorse or promote products derived from this software
     60  *    without specific prior written permission.
     61  *
     62  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     63  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     64  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     65  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     66  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     67  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     68  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     69  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     70  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     71  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     72  * SUCH DAMAGE.
     73  *
     74  *	@(#)kern_synch.c	8.9 (Berkeley) 5/19/95
     75  */
     76 
     77 #include <sys/cdefs.h>
     78 __KERNEL_RCSID(0, "$NetBSD: kern_synch.c,v 1.186.2.20 2007/10/23 20:17:12 ad Exp $");
     79 
     80 #include "opt_kstack.h"
     81 #include "opt_lockdebug.h"
     82 #include "opt_multiprocessor.h"
     83 #include "opt_perfctrs.h"
     84 
     85 #define	__MUTEX_PRIVATE
     86 
     87 #include <sys/param.h>
     88 #include <sys/systm.h>
     89 #include <sys/proc.h>
     90 #include <sys/kernel.h>
     91 #if defined(PERFCTRS)
     92 #include <sys/pmc.h>
     93 #endif
     94 #include <sys/cpu.h>
     95 #include <sys/resourcevar.h>
     96 #include <sys/sched.h>
     97 #include <sys/syscall_stats.h>
     98 #include <sys/sleepq.h>
     99 #include <sys/lockdebug.h>
    100 #include <sys/evcnt.h>
    101 #include <sys/intr.h>
    102 
    103 #include <uvm/uvm_extern.h>
    104 
    105 callout_t sched_pstats_ch;
    106 unsigned int sched_pstats_ticks;
    107 
    108 kcondvar_t	lbolt;			/* once a second sleep address */
    109 
    110 static void	sched_unsleep(struct lwp *);
    111 static void	sched_changepri(struct lwp *, pri_t);
    112 static void	sched_lendpri(struct lwp *, pri_t);
    113 
    114 syncobj_t sleep_syncobj = {
    115 	SOBJ_SLEEPQ_SORTED,
    116 	sleepq_unsleep,
    117 	sleepq_changepri,
    118 	sleepq_lendpri,
    119 	syncobj_noowner,
    120 };
    121 
    122 syncobj_t sched_syncobj = {
    123 	SOBJ_SLEEPQ_SORTED,
    124 	sched_unsleep,
    125 	sched_changepri,
    126 	sched_lendpri,
    127 	syncobj_noowner,
    128 };
    129 
    130 /*
    131  * During autoconfiguration or after a panic, a sleep will simply lower the
    132  * priority briefly to allow interrupts, then return.  The priority to be
    133  * used (safepri) is machine-dependent, thus this value is initialized and
    134  * maintained in the machine-dependent layers.  This priority will typically
    135  * be 0, or the lowest priority that is safe for use on the interrupt stack;
    136  * it can be made higher to block network software interrupts after panics.
    137  */
    138 int	safepri;
    139 
    140 /*
    141  * OBSOLETE INTERFACE
    142  *
    143  * General sleep call.  Suspends the current process until a wakeup is
    144  * performed on the specified identifier.  The process will then be made
    145  * runnable with the specified priority.  Sleeps at most timo/hz seconds (0
    146  * means no timeout).  If pri includes PCATCH flag, signals are checked
    147  * before and after sleeping, else signals are not checked.  Returns 0 if
    148  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
    149  * signal needs to be delivered, ERESTART is returned if the current system
    150  * call should be restarted if possible, and EINTR is returned if the system
    151  * call should be interrupted by the signal (return EINTR).
    152  *
    153  * The interlock is held until we are on a sleep queue. The interlock will
    154  * be locked before returning back to the caller unless the PNORELOCK flag
    155  * is specified, in which case the interlock will always be unlocked upon
    156  * return.
    157  */
    158 int
    159 ltsleep(wchan_t ident, pri_t priority, const char *wmesg, int timo,
    160 	volatile struct simplelock *interlock)
    161 {
    162 	struct lwp *l = curlwp;
    163 	sleepq_t *sq;
    164 	int error;
    165 
    166 	KASSERT((l->l_pflag & LP_INTR) == 0);
    167 
    168 	if (sleepq_dontsleep(l)) {
    169 		(void)sleepq_abort(NULL, 0);
    170 		if ((priority & PNORELOCK) != 0)
    171 			simple_unlock(interlock);
    172 		return 0;
    173 	}
    174 
    175 	sq = sleeptab_lookup(&sleeptab, ident);
    176 	sleepq_enter(sq, l);
    177 	sleepq_enqueue(sq, sched_kpri(l), ident, wmesg, &sleep_syncobj);
    178 
    179 	if (interlock != NULL) {
    180 		KASSERT(simple_lock_held(interlock));
    181 		simple_unlock(interlock);
    182 	}
    183 
    184 	error = sleepq_block(timo, priority & PCATCH);
    185 
    186 	if (interlock != NULL && (priority & PNORELOCK) == 0)
    187 		simple_lock(interlock);
    188 
    189 	return error;
    190 }
    191 
    192 int
    193 mtsleep(wchan_t ident, pri_t priority, const char *wmesg, int timo,
    194 	kmutex_t *mtx)
    195 {
    196 	struct lwp *l = curlwp;
    197 	sleepq_t *sq;
    198 	int error;
    199 
    200 	KASSERT((l->l_pflag & LP_INTR) == 0);
    201 
    202 	if (sleepq_dontsleep(l)) {
    203 		(void)sleepq_abort(mtx, (priority & PNORELOCK) != 0);
    204 		return 0;
    205 	}
    206 
    207 	sq = sleeptab_lookup(&sleeptab, ident);
    208 	sleepq_enter(sq, l);
    209 	sleepq_enqueue(sq, sched_kpri(l), ident, wmesg, &sleep_syncobj);
    210 	mutex_exit(mtx);
    211 	error = sleepq_block(timo, priority & PCATCH);
    212 
    213 	if ((priority & PNORELOCK) == 0)
    214 		mutex_enter(mtx);
    215 
    216 	return error;
    217 }
    218 
    219 /*
    220  * General sleep call for situations where a wake-up is not expected.
    221  */
    222 int
    223 kpause(const char *wmesg, bool intr, int timo, kmutex_t *mtx)
    224 {
    225 	struct lwp *l = curlwp;
    226 	sleepq_t *sq;
    227 	int error;
    228 
    229 	if (sleepq_dontsleep(l))
    230 		return sleepq_abort(NULL, 0);
    231 
    232 	if (mtx != NULL)
    233 		mutex_exit(mtx);
    234 	sq = sleeptab_lookup(&sleeptab, l);
    235 	sleepq_enter(sq, l);
    236 	sleepq_enqueue(sq, sched_kpri(l), l, wmesg, &sleep_syncobj);
    237 	error = sleepq_block(timo, intr);
    238 	if (mtx != NULL)
    239 		mutex_enter(mtx);
    240 
    241 	return error;
    242 }
    243 
    244 /*
    245  * OBSOLETE INTERFACE
    246  *
    247  * Make all processes sleeping on the specified identifier runnable.
    248  */
    249 void
    250 wakeup(wchan_t ident)
    251 {
    252 	sleepq_t *sq;
    253 
    254 	if (cold)
    255 		return;
    256 
    257 	sq = sleeptab_lookup(&sleeptab, ident);
    258 	sleepq_wake(sq, ident, (u_int)-1);
    259 }
    260 
    261 /*
    262  * OBSOLETE INTERFACE
    263  *
    264  * Make the highest priority process first in line on the specified
    265  * identifier runnable.
    266  */
    267 void
    268 wakeup_one(wchan_t ident)
    269 {
    270 	sleepq_t *sq;
    271 
    272 	if (cold)
    273 		return;
    274 
    275 	sq = sleeptab_lookup(&sleeptab, ident);
    276 	sleepq_wake(sq, ident, 1);
    277 }
    278 
    279 
    280 /*
    281  * General yield call.  Puts the current process back on its run queue and
    282  * performs a voluntary context switch.  Should only be called when the
    283  * current process explicitly requests it (eg sched_yield(2)).
    284  */
    285 void
    286 yield(void)
    287 {
    288 	struct lwp *l = curlwp;
    289 
    290 	KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
    291 	lwp_lock(l);
    292 	KASSERT(lwp_locked(l, &l->l_cpu->ci_schedstate.spc_lwplock));
    293 	KASSERT(l->l_stat == LSONPROC);
    294 	/* XXX Only do this for timeshared threads. */
    295 	l->l_priority = 0;
    296 	(void)mi_switch(l);
    297 	KERNEL_LOCK(l->l_biglocks, l);
    298 }
    299 
    300 /*
    301  * General preemption call.  Puts the current process back on its run queue
    302  * and performs an involuntary context switch.
    303  */
    304 void
    305 preempt(void)
    306 {
    307 	struct lwp *l = curlwp;
    308 
    309 	KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
    310 	lwp_lock(l);
    311 	KASSERT(lwp_locked(l, &l->l_cpu->ci_schedstate.spc_lwplock));
    312 	KASSERT(l->l_stat == LSONPROC);
    313 	l->l_priority = l->l_usrpri;
    314 	l->l_nivcsw++;
    315 	(void)mi_switch(l);
    316 	KERNEL_LOCK(l->l_biglocks, l);
    317 }
    318 
    319 /*
    320  * Compute the amount of time during which the current lwp was running.
    321  *
    322  * - update l_rtime unless it's an idle lwp.
    323  */
    324 
    325 void
    326 updatertime(lwp_t *l, const struct timeval *tv)
    327 {
    328 	long s, u;
    329 
    330 	if ((l->l_flag & LW_IDLE) != 0)
    331 		return;
    332 
    333 	u = l->l_rtime.tv_usec + (tv->tv_usec - l->l_stime.tv_usec);
    334 	s = l->l_rtime.tv_sec + (tv->tv_sec - l->l_stime.tv_sec);
    335 	if (u < 0) {
    336 		u += 1000000;
    337 		s--;
    338 	} else if (u >= 1000000) {
    339 		u -= 1000000;
    340 		s++;
    341 	}
    342 	l->l_rtime.tv_usec = u;
    343 	l->l_rtime.tv_sec = s;
    344 }
    345 
    346 /*
    347  * The machine independent parts of context switch.
    348  *
    349  * Returns 1 if another LWP was actually run.
    350  */
    351 int
    352 mi_switch(lwp_t *l)
    353 {
    354 	struct schedstate_percpu *spc;
    355 	struct lwp *newl;
    356 	int retval, oldspl;
    357 	struct cpu_info *ci;
    358 	struct timeval tv;
    359 	bool returning;
    360 
    361 	KASSERT(lwp_locked(l, NULL));
    362 	LOCKDEBUG_BARRIER(l->l_mutex, 1);
    363 
    364 #ifdef KSTACK_CHECK_MAGIC
    365 	kstack_check_magic(l);
    366 #endif
    367 
    368 	microtime(&tv);
    369 
    370 	/*
    371 	 * It's safe to read the per CPU schedstate unlocked here, as all we
    372 	 * are after is the run time and that's guarenteed to have been last
    373 	 * updated by this CPU.
    374 	 */
    375 	ci = l->l_cpu;
    376 	KDASSERT(ci == curcpu());
    377 
    378 	/*
    379 	 * Process is about to yield the CPU; clear the appropriate
    380 	 * scheduling flags.
    381 	 */
    382 	spc = &ci->ci_schedstate;
    383 	returning = false;
    384 	newl = NULL;
    385 
    386 	/*
    387 	 * If we have been asked to switch to a specific LWP, then there
    388 	 * is no need to inspect the run queues.  If a soft interrupt is
    389 	 * blocking, then return to the interrupted thread without adjusting
    390 	 * VM context or its start time: neither have been changed in order
    391 	 * to take the interrupt.
    392 	 */
    393 	if (l->l_switchto != NULL) {
    394 		if ((l->l_pflag & LP_INTR) != 0) {
    395 			returning = true;
    396 			softint_block(l);
    397 			if ((l->l_flag & LW_TIMEINTR) != 0)
    398 				updatertime(l, &tv);
    399 		}
    400 		newl = l->l_switchto;
    401 		l->l_switchto = NULL;
    402 	}
    403 #ifndef __HAVE_FAST_SOFTINTS
    404 	else if (ci->ci_data.cpu_softints != 0) {
    405 		/* There are pending soft interrupts, so pick one. */
    406 		newl = softint_picklwp();
    407 		newl->l_stat = LSONPROC;
    408 		newl->l_flag |= LW_RUNNING;
    409 	}
    410 #endif	/* !__HAVE_FAST_SOFTINTS */
    411 
    412 	/* Count time spent in current system call */
    413 	if (!returning) {
    414 		SYSCALL_TIME_SLEEP(l);
    415 
    416 		/*
    417 		 * XXXSMP If we are using h/w performance counters,
    418 		 * save context.
    419 		 */
    420 #if PERFCTRS
    421 		if (PMC_ENABLED(l->l_proc)) {
    422 			pmc_save_context(l->l_proc);
    423 		}
    424 #endif
    425 		updatertime(l, &tv);
    426 	}
    427 
    428 	/*
    429 	 * If on the CPU and we have gotten this far, then we must yield.
    430 	 */
    431 	mutex_spin_enter(spc->spc_mutex);
    432 	KASSERT(l->l_stat != LSRUN);
    433 	if (l->l_stat == LSONPROC && l != newl) {
    434 		KASSERT(lwp_locked(l, &spc->spc_lwplock));
    435 		if ((l->l_flag & LW_IDLE) == 0) {
    436 			l->l_stat = LSRUN;
    437 			lwp_setlock(l, spc->spc_mutex);
    438 			sched_enqueue(l, true);
    439 		} else
    440 			l->l_stat = LSIDL;
    441 	}
    442 
    443 	/*
    444 	 * Let sched_nextlwp() select the LWP to run the CPU next.
    445 	 * If no LWP is runnable, switch to the idle LWP.
    446 	 * Note that spc_lwplock might not necessary be held.
    447 	 */
    448 	if (newl == NULL) {
    449 		newl = sched_nextlwp();
    450 		if (newl != NULL) {
    451 			sched_dequeue(newl);
    452 			KASSERT(lwp_locked(newl, spc->spc_mutex));
    453 			newl->l_stat = LSONPROC;
    454 			newl->l_cpu = ci;
    455 			newl->l_flag |= LW_RUNNING;
    456 			lwp_setlock(newl, &spc->spc_lwplock);
    457 		} else {
    458 			newl = ci->ci_data.cpu_idlelwp;
    459 			newl->l_stat = LSONPROC;
    460 			newl->l_flag |= LW_RUNNING;
    461 		}
    462 		/*
    463 		 * Only clear want_resched if there are no
    464 		 * pending (slow) software interrupts.
    465 		 */
    466 		ci->ci_want_resched = ci->ci_data.cpu_softints;
    467 		spc->spc_flags &= ~SPCF_SWITCHCLEAR;
    468 	}
    469 
    470 	/* Update the new LWP's start time while it is still locked. */
    471 	if (!returning) {
    472 		newl->l_stime = tv;
    473 		/*
    474 		 * XXX The following may be done unlocked if newl != NULL
    475 		 * above.
    476 		 */
    477 		newl->l_priority = newl->l_usrpri;
    478 	}
    479 
    480 	spc->spc_curpriority = newl->l_usrpri;
    481 
    482 	if (l != newl) {
    483 		struct lwp *prevlwp;
    484 
    485 		/*
    486 		 * If the old LWP has been moved to a run queue above,
    487 		 * drop the general purpose LWP lock: it's now locked
    488 		 * by the scheduler lock.
    489 		 *
    490 		 * Otherwise, drop the scheduler lock.  We're done with
    491 		 * the run queues for now.
    492 		 */
    493 		if (l->l_mutex == spc->spc_mutex) {
    494 			mutex_spin_exit(&spc->spc_lwplock);
    495 		} else {
    496 			mutex_spin_exit(spc->spc_mutex);
    497 		}
    498 
    499 		/* Unlocked, but for statistics only. */
    500 		uvmexp.swtch++;
    501 
    502 		/*
    503 		 * Save old VM context, unless a soft interrupt
    504 		 * handler is blocking.
    505 		 */
    506 		if (!returning)
    507 			pmap_deactivate(l);
    508 
    509 		/* Switch to the new LWP.. */
    510 		l->l_ncsw++;
    511 		l->l_flag &= ~LW_RUNNING;
    512 		oldspl = MUTEX_SPIN_OLDSPL(ci);
    513 		prevlwp = cpu_switchto(l, newl, returning);
    514 
    515 		/*
    516 		 * .. we have switched away and are now back so we must
    517 		 * be the new curlwp.  prevlwp is who we replaced.
    518 		 */
    519 		if (prevlwp != NULL) {
    520 			curcpu()->ci_mtx_oldspl = oldspl;
    521 			lwp_unlock(prevlwp);
    522 		} else {
    523 			splx(oldspl);
    524 		}
    525 
    526 		/* Restore VM context. */
    527 		pmap_activate(l);
    528 		retval = 1;
    529 	} else {
    530 		/* Nothing to do - just unlock and return. */
    531 		mutex_spin_exit(spc->spc_mutex);
    532 		lwp_unlock(l);
    533 		retval = 0;
    534 	}
    535 
    536 	KASSERT(l == curlwp);
    537 	KASSERT(l->l_stat == LSONPROC);
    538 	KASSERT(l->l_cpu == curcpu());
    539 
    540 	/*
    541 	 * XXXSMP If we are using h/w performance counters, restore context.
    542 	 */
    543 #if PERFCTRS
    544 	if (PMC_ENABLED(l->l_proc)) {
    545 		pmc_restore_context(l->l_proc);
    546 	}
    547 #endif
    548 
    549 	/*
    550 	 * We're running again; record our new start time.  We might
    551 	 * be running on a new CPU now, so don't use the cached
    552 	 * schedstate_percpu pointer.
    553 	 */
    554 	SYSCALL_TIME_WAKEUP(l);
    555 	KASSERT(curlwp == l);
    556 	KDASSERT(l->l_cpu == curcpu());
    557 	LOCKDEBUG_BARRIER(NULL, 1);
    558 
    559 	return retval;
    560 }
    561 
    562 /*
    563  * Change process state to be runnable, placing it on the run queue if it is
    564  * in memory, and awakening the swapper if it isn't in memory.
    565  *
    566  * Call with the process and LWP locked.  Will return with the LWP unlocked.
    567  */
    568 void
    569 setrunnable(struct lwp *l)
    570 {
    571 	struct proc *p = l->l_proc;
    572 	sigset_t *ss;
    573 
    574 	KASSERT((l->l_flag & LW_IDLE) == 0);
    575 	KASSERT(mutex_owned(&p->p_smutex));
    576 	KASSERT(lwp_locked(l, NULL));
    577 
    578 	switch (l->l_stat) {
    579 	case LSSTOP:
    580 		/*
    581 		 * If we're being traced (possibly because someone attached us
    582 		 * while we were stopped), check for a signal from the debugger.
    583 		 */
    584 		if ((p->p_slflag & PSL_TRACED) != 0 && p->p_xstat != 0) {
    585 			if ((sigprop[p->p_xstat] & SA_TOLWP) != 0)
    586 				ss = &l->l_sigpend.sp_set;
    587 			else
    588 				ss = &p->p_sigpend.sp_set;
    589 			sigaddset(ss, p->p_xstat);
    590 			signotify(l);
    591 		}
    592 		p->p_nrlwps++;
    593 		break;
    594 	case LSSUSPENDED:
    595 		l->l_flag &= ~LW_WSUSPEND;
    596 		p->p_nrlwps++;
    597 		cv_broadcast(&p->p_lwpcv);
    598 		break;
    599 	case LSSLEEP:
    600 		KASSERT(l->l_wchan != NULL);
    601 		break;
    602 	default:
    603 		panic("setrunnable: lwp %p state was %d", l, l->l_stat);
    604 	}
    605 
    606 	/*
    607 	 * If the LWP was sleeping interruptably, then it's OK to start it
    608 	 * again.  If not, mark it as still sleeping.
    609 	 */
    610 	if (l->l_wchan != NULL) {
    611 		l->l_stat = LSSLEEP;
    612 		/* lwp_unsleep() will release the lock. */
    613 		lwp_unsleep(l);
    614 		return;
    615 	}
    616 
    617 	/*
    618 	 * If the LWP is still on the CPU, mark it as LSONPROC.  It may be
    619 	 * about to call mi_switch(), in which case it will yield.
    620 	 */
    621 	if ((l->l_flag & LW_RUNNING) != 0) {
    622 		l->l_stat = LSONPROC;
    623 		l->l_slptime = 0;
    624 		lwp_unlock(l);
    625 		return;
    626 	}
    627 
    628 	/*
    629 	 * Set the LWP runnable.  If it's swapped out, we need to wake the swapper
    630 	 * to bring it back in.  Otherwise, enter it into a run queue.
    631 	 */
    632 	if (l->l_mutex != l->l_cpu->ci_schedstate.spc_mutex) {
    633 		spc_lock(l->l_cpu);
    634 		lwp_unlock_to(l, l->l_cpu->ci_schedstate.spc_mutex);
    635 	}
    636 
    637 	sched_setrunnable(l);
    638 	l->l_stat = LSRUN;
    639 	l->l_slptime = 0;
    640 
    641 	if (l->l_flag & LW_INMEM) {
    642 		sched_enqueue(l, false);
    643 		resched_cpu(l);
    644 		lwp_unlock(l);
    645 	} else {
    646 		lwp_unlock(l);
    647 		uvm_kick_scheduler();
    648 	}
    649 }
    650 
    651 /*
    652  * suspendsched:
    653  *
    654  *	Convert all non-L_SYSTEM LSSLEEP or LSRUN LWPs to LSSUSPENDED.
    655  */
    656 void
    657 suspendsched(void)
    658 {
    659 	CPU_INFO_ITERATOR cii;
    660 	struct cpu_info *ci;
    661 	struct lwp *l;
    662 	struct proc *p;
    663 
    664 	/*
    665 	 * We do this by process in order not to violate the locking rules.
    666 	 */
    667 	mutex_enter(&proclist_lock);
    668 	PROCLIST_FOREACH(p, &allproc) {
    669 		mutex_enter(&p->p_smutex);
    670 
    671 		if ((p->p_flag & PK_SYSTEM) != 0) {
    672 			mutex_exit(&p->p_smutex);
    673 			continue;
    674 		}
    675 
    676 		p->p_stat = SSTOP;
    677 
    678 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    679 			if (l == curlwp)
    680 				continue;
    681 
    682 			lwp_lock(l);
    683 
    684 			/*
    685 			 * Set L_WREBOOT so that the LWP will suspend itself
    686 			 * when it tries to return to user mode.  We want to
    687 			 * try and get to get as many LWPs as possible to
    688 			 * the user / kernel boundary, so that they will
    689 			 * release any locks that they hold.
    690 			 */
    691 			l->l_flag |= (LW_WREBOOT | LW_WSUSPEND);
    692 
    693 			if (l->l_stat == LSSLEEP &&
    694 			    (l->l_flag & LW_SINTR) != 0) {
    695 				/* setrunnable() will release the lock. */
    696 				setrunnable(l);
    697 				continue;
    698 			}
    699 
    700 			lwp_unlock(l);
    701 		}
    702 
    703 		mutex_exit(&p->p_smutex);
    704 	}
    705 	mutex_exit(&proclist_lock);
    706 
    707 	/*
    708 	 * Kick all CPUs to make them preempt any LWPs running in user mode.
    709 	 * They'll trap into the kernel and suspend themselves in userret().
    710 	 */
    711 	for (CPU_INFO_FOREACH(cii, ci)) {
    712 		spc_lock(ci);
    713 		cpu_need_resched(ci, RESCHED_IMMED);
    714 		spc_unlock(ci);
    715 	}
    716 }
    717 
    718 /*
    719  * sched_kpri:
    720  *
    721  *	Scale a priority level to a kernel priority level, usually
    722  *	for an LWP that is about to sleep.
    723  */
    724 pri_t
    725 sched_kpri(struct lwp *l)
    726 {
    727 	pri_t pri;
    728 
    729 #ifndef __HAVE_FAST_SOFTINTS
    730 	/*
    731 	 * Hack: if a user thread is being used to run a soft
    732 	 * interrupt, we need to boost the priority here.
    733 	 */
    734 	if ((l->l_pflag & LP_INTR) != 0 && l->l_priority < PRI_KERNEL_RT)
    735 		return softint_kpri(l);
    736 #endif
    737 
    738 	/*
    739 	 * Scale user priorities (0 -> 63) up to kernel priorities
    740 	 * in the range (64 -> 95).  This makes assumptions about
    741 	 * the priority space and so should be kept in sync with
    742 	 * param.h.
    743 	 */
    744 	if ((pri = l->l_usrpri) >= PRI_KERNEL)
    745 		return pri;
    746 
    747 	return (pri >> 1) + PRI_KERNEL;
    748 }
    749 
    750 /*
    751  * sched_unsleep:
    752  *
    753  *	The is called when the LWP has not been awoken normally but instead
    754  *	interrupted: for example, if the sleep timed out.  Because of this,
    755  *	it's not a valid action for running or idle LWPs.
    756  */
    757 static void
    758 sched_unsleep(struct lwp *l)
    759 {
    760 
    761 	lwp_unlock(l);
    762 	panic("sched_unsleep");
    763 }
    764 
    765 inline void
    766 resched_cpu(struct lwp *l)
    767 {
    768 	struct cpu_info *ci;
    769 	const pri_t pri = lwp_eprio(l);
    770 
    771 	/*
    772 	 * XXXSMP
    773 	 * Since l->l_cpu persists across a context switch,
    774 	 * this gives us *very weak* processor affinity, in
    775 	 * that we notify the CPU on which the process last
    776 	 * ran that it should try to switch.
    777 	 *
    778 	 * This does not guarantee that the process will run on
    779 	 * that processor next, because another processor might
    780 	 * grab it the next time it performs a context switch.
    781 	 *
    782 	 * This also does not handle the case where its last
    783 	 * CPU is running a higher-priority process, but every
    784 	 * other CPU is running a lower-priority process.  There
    785 	 * are ways to handle this situation, but they're not
    786 	 * currently very pretty, and we also need to weigh the
    787 	 * cost of moving a process from one CPU to another.
    788 	 */
    789 	ci = l->l_cpu;
    790 	if (pri > ci->ci_schedstate.spc_curpriority)
    791 		cpu_need_resched(ci, 0);
    792 }
    793 
    794 static void
    795 sched_changepri(struct lwp *l, pri_t pri)
    796 {
    797 
    798 	KASSERT(lwp_locked(l, NULL));
    799 
    800 	l->l_usrpri = pri;
    801 	if (l->l_priority >= PRI_KERNEL)
    802 		return;
    803 
    804 	if (l->l_stat != LSRUN || (l->l_flag & LW_INMEM) == 0) {
    805 		l->l_priority = pri;
    806 		return;
    807 	}
    808 
    809 	KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
    810 
    811 	sched_dequeue(l);
    812 	l->l_priority = pri;
    813 	sched_enqueue(l, false);
    814 	resched_cpu(l);
    815 }
    816 
    817 static void
    818 sched_lendpri(struct lwp *l, pri_t pri)
    819 {
    820 
    821 	KASSERT(lwp_locked(l, NULL));
    822 
    823 	if (l->l_stat != LSRUN || (l->l_flag & LW_INMEM) == 0) {
    824 		l->l_inheritedprio = pri;
    825 		return;
    826 	}
    827 
    828 	KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
    829 
    830 	sched_dequeue(l);
    831 	l->l_inheritedprio = pri;
    832 	sched_enqueue(l, false);
    833 	resched_cpu(l);
    834 }
    835 
    836 struct lwp *
    837 syncobj_noowner(wchan_t wchan)
    838 {
    839 
    840 	return NULL;
    841 }
    842 
    843 
    844 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
    845 fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;		/* exp(-1/20) */
    846 
    847 /*
    848  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
    849  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
    850  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
    851  *
    852  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
    853  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
    854  *
    855  * If you dont want to bother with the faster/more-accurate formula, you
    856  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
    857  * (more general) method of calculating the %age of CPU used by a process.
    858  */
    859 #define	CCPU_SHIFT	(FSHIFT + 1)
    860 
    861 /*
    862  * sched_pstats:
    863  *
    864  * Update process statistics and check CPU resource allocation.
    865  * Call scheduler-specific hook to eventually adjust process/LWP
    866  * priorities.
    867  */
    868 /* ARGSUSED */
    869 void
    870 sched_pstats(void *arg)
    871 {
    872 	struct rlimit *rlim;
    873 	struct lwp *l;
    874 	struct proc *p;
    875 	int minslp, sig, clkhz;
    876 	long runtm;
    877 
    878 	sched_pstats_ticks++;
    879 
    880 	mutex_enter(&proclist_lock);
    881 	PROCLIST_FOREACH(p, &allproc) {
    882 		/*
    883 		 * Increment time in/out of memory and sleep time (if
    884 		 * sleeping).  We ignore overflow; with 16-bit int's
    885 		 * (remember them?) overflow takes 45 days.
    886 		 */
    887 		minslp = 2;
    888 		mutex_enter(&p->p_smutex);
    889 		mutex_spin_enter(&p->p_stmutex);
    890 		runtm = p->p_rtime.tv_sec;
    891 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    892 			if ((l->l_flag & LW_IDLE) != 0)
    893 				continue;
    894 			lwp_lock(l);
    895 			runtm += l->l_rtime.tv_sec;
    896 			l->l_swtime++;
    897 			if (l->l_stat == LSSLEEP || l->l_stat == LSSTOP ||
    898 			    l->l_stat == LSSUSPENDED) {
    899 				l->l_slptime++;
    900 				minslp = min(minslp, l->l_slptime);
    901 			} else
    902 				minslp = 0;
    903 			sched_pstats_hook(l);
    904 			lwp_unlock(l);
    905 
    906 			/*
    907 			 * p_pctcpu is only for ps.
    908 			 */
    909 			l->l_pctcpu = (l->l_pctcpu * ccpu) >> FSHIFT;
    910 			if (l->l_slptime < 1) {
    911 				clkhz = stathz != 0 ? stathz : hz;
    912 #if	(FSHIFT >= CCPU_SHIFT)
    913 				l->l_pctcpu += (clkhz == 100) ?
    914 				    ((fixpt_t)l->l_cpticks) <<
    915 				        (FSHIFT - CCPU_SHIFT) :
    916 				    100 * (((fixpt_t) p->p_cpticks)
    917 				        << (FSHIFT - CCPU_SHIFT)) / clkhz;
    918 #else
    919 				l->l_pctcpu += ((FSCALE - ccpu) *
    920 				    (l->l_cpticks * FSCALE / clkhz)) >> FSHIFT;
    921 #endif
    922 				l->l_cpticks = 0;
    923 			}
    924 		}
    925 
    926 		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
    927 #ifdef SCHED_4BSD
    928 		/*
    929 		 * XXX: Workaround - belongs to sched_4bsd.c
    930 		 * If the process has slept the entire second,
    931 		 * stop recalculating its priority until it wakes up.
    932 		 */
    933 		if (minslp <= 1) {
    934 			extern fixpt_t decay_cpu(fixpt_t, fixpt_t);
    935 
    936 			fixpt_t loadfac = 2 * (averunnable.ldavg[0]);
    937 			p->p_estcpu = decay_cpu(loadfac, p->p_estcpu);
    938 		}
    939 #endif
    940 		mutex_spin_exit(&p->p_stmutex);
    941 
    942 		/*
    943 		 * Check if the process exceeds its CPU resource allocation.
    944 		 * If over max, kill it.
    945 		 */
    946 		rlim = &p->p_rlimit[RLIMIT_CPU];
    947 		sig = 0;
    948 		if (runtm >= rlim->rlim_cur) {
    949 			if (runtm >= rlim->rlim_max)
    950 				sig = SIGKILL;
    951 			else {
    952 				sig = SIGXCPU;
    953 				if (rlim->rlim_cur < rlim->rlim_max)
    954 					rlim->rlim_cur += 5;
    955 			}
    956 		}
    957 		mutex_exit(&p->p_smutex);
    958 		if (sig) {
    959 			/* XXXAD */
    960 			mutex_enter(&proclist_mutex);
    961 			psignal(p, sig);
    962 			mutex_enter(&proclist_mutex);
    963 		}
    964 	}
    965 	mutex_exit(&proclist_lock);
    966 	uvm_meter();
    967 	cv_wakeup(&lbolt);
    968 	callout_schedule(&sched_pstats_ch, hz);
    969 }
    970 
    971 void
    972 sched_init(void)
    973 {
    974 
    975 	callout_init(&sched_pstats_ch, CALLOUT_MPSAFE);
    976 	callout_setfunc(&sched_pstats_ch, sched_pstats, NULL);
    977 	sched_setup();
    978 	sched_pstats(NULL);
    979 }
    980