Home | History | Annotate | Line # | Download | only in kern
kern_synch.c revision 1.186.2.19
      1 /*	$NetBSD: kern_synch.c,v 1.186.2.19 2007/10/18 15:47:33 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.19 2007/10/18 15:47:33 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 	 */
    447 	if (newl == NULL) {
    448 		newl = sched_nextlwp();
    449 		if (newl != NULL) {
    450 			sched_dequeue(newl);
    451 			KASSERT(lwp_locked(newl, spc->spc_mutex));
    452 			newl->l_stat = LSONPROC;
    453 			newl->l_cpu = ci;
    454 			newl->l_flag |= LW_RUNNING;
    455 			lwp_setlock(newl, &spc->spc_lwplock);
    456 		} else {
    457 			newl = ci->ci_data.cpu_idlelwp;
    458 			newl->l_stat = LSONPROC;
    459 			newl->l_flag |= LW_RUNNING;
    460 		}
    461 		/*
    462 		 * Only clear want_resched if there are no
    463 		 * pending (slow) software interrupts.
    464 		 */
    465 		ci->ci_want_resched = ci->ci_data.cpu_softints;
    466 		spc->spc_flags &= ~SPCF_SWITCHCLEAR;
    467 	}
    468 
    469 	/* Update the new LWP's start time while it is still locked. */
    470 	if (!returning) {
    471 		newl->l_stime = tv;
    472 		/*
    473 		 * XXX The following may be done unlocked if newl != NULL
    474 		 * above.
    475 		 */
    476 		newl->l_priority = newl->l_usrpri;
    477 	}
    478 
    479 	spc->spc_curpriority = newl->l_usrpri;
    480 
    481 	if (l != newl) {
    482 		struct lwp *prevlwp;
    483 
    484 		/*
    485 		 * If the old LWP has been moved to a run queue above,
    486 		 * drop the general purpose LWP lock: it's now locked
    487 		 * by the scheduler lock.
    488 		 *
    489 		 * Otherwise, drop the scheduler lock.  We're done with
    490 		 * the run queues for now.
    491 		 */
    492 		if (l->l_mutex == spc->spc_mutex) {
    493 			mutex_spin_exit(&spc->spc_lwplock);
    494 		} else {
    495 			mutex_spin_exit(spc->spc_mutex);
    496 		}
    497 
    498 		/* Unlocked, but for statistics only. */
    499 		uvmexp.swtch++;
    500 
    501 		/*
    502 		 * Save old VM context, unless a soft interrupt
    503 		 * handler is blocking.
    504 		 */
    505 		if (!returning)
    506 			pmap_deactivate(l);
    507 
    508 		/* Switch to the new LWP.. */
    509 		l->l_ncsw++;
    510 		l->l_flag &= ~LW_RUNNING;
    511 		oldspl = MUTEX_SPIN_OLDSPL(ci);
    512 		prevlwp = cpu_switchto(l, newl, returning);
    513 
    514 		/*
    515 		 * .. we have switched away and are now back so we must
    516 		 * be the new curlwp.  prevlwp is who we replaced.
    517 		 */
    518 		if (prevlwp != NULL) {
    519 			curcpu()->ci_mtx_oldspl = oldspl;
    520 			lwp_unlock(prevlwp);
    521 		} else {
    522 			splx(oldspl);
    523 		}
    524 
    525 		/* Restore VM context. */
    526 		pmap_activate(l);
    527 		retval = 1;
    528 	} else {
    529 		/* Nothing to do - just unlock and return. */
    530 		mutex_spin_exit(spc->spc_mutex);
    531 		lwp_unlock(l);
    532 		retval = 0;
    533 	}
    534 
    535 	KASSERT(l == curlwp);
    536 	KASSERT(l->l_stat == LSONPROC);
    537 	KASSERT(l->l_cpu == curcpu());
    538 
    539 	/*
    540 	 * XXXSMP If we are using h/w performance counters, restore context.
    541 	 */
    542 #if PERFCTRS
    543 	if (PMC_ENABLED(l->l_proc)) {
    544 		pmc_restore_context(l->l_proc);
    545 	}
    546 #endif
    547 
    548 	/*
    549 	 * We're running again; record our new start time.  We might
    550 	 * be running on a new CPU now, so don't use the cached
    551 	 * schedstate_percpu pointer.
    552 	 */
    553 	SYSCALL_TIME_WAKEUP(l);
    554 	KASSERT(curlwp == l);
    555 	KDASSERT(l->l_cpu == curcpu());
    556 	LOCKDEBUG_BARRIER(NULL, 1);
    557 
    558 	return retval;
    559 }
    560 
    561 /*
    562  * Change process state to be runnable, placing it on the run queue if it is
    563  * in memory, and awakening the swapper if it isn't in memory.
    564  *
    565  * Call with the process and LWP locked.  Will return with the LWP unlocked.
    566  */
    567 void
    568 setrunnable(struct lwp *l)
    569 {
    570 	struct proc *p = l->l_proc;
    571 	sigset_t *ss;
    572 
    573 	KASSERT((l->l_flag & LW_IDLE) == 0);
    574 	KASSERT(mutex_owned(&p->p_smutex));
    575 	KASSERT(lwp_locked(l, NULL));
    576 
    577 	switch (l->l_stat) {
    578 	case LSSTOP:
    579 		/*
    580 		 * If we're being traced (possibly because someone attached us
    581 		 * while we were stopped), check for a signal from the debugger.
    582 		 */
    583 		if ((p->p_slflag & PSL_TRACED) != 0 && p->p_xstat != 0) {
    584 			if ((sigprop[p->p_xstat] & SA_TOLWP) != 0)
    585 				ss = &l->l_sigpend.sp_set;
    586 			else
    587 				ss = &p->p_sigpend.sp_set;
    588 			sigaddset(ss, p->p_xstat);
    589 			signotify(l);
    590 		}
    591 		p->p_nrlwps++;
    592 		break;
    593 	case LSSUSPENDED:
    594 		l->l_flag &= ~LW_WSUSPEND;
    595 		p->p_nrlwps++;
    596 		cv_broadcast(&p->p_lwpcv);
    597 		break;
    598 	case LSSLEEP:
    599 		KASSERT(l->l_wchan != NULL);
    600 		break;
    601 	default:
    602 		panic("setrunnable: lwp %p state was %d", l, l->l_stat);
    603 	}
    604 
    605 	/*
    606 	 * If the LWP was sleeping interruptably, then it's OK to start it
    607 	 * again.  If not, mark it as still sleeping.
    608 	 */
    609 	if (l->l_wchan != NULL) {
    610 		l->l_stat = LSSLEEP;
    611 		/* lwp_unsleep() will release the lock. */
    612 		lwp_unsleep(l);
    613 		return;
    614 	}
    615 
    616 	/*
    617 	 * If the LWP is still on the CPU, mark it as LSONPROC.  It may be
    618 	 * about to call mi_switch(), in which case it will yield.
    619 	 */
    620 	if ((l->l_flag & LW_RUNNING) != 0) {
    621 		l->l_stat = LSONPROC;
    622 		l->l_slptime = 0;
    623 		lwp_unlock(l);
    624 		return;
    625 	}
    626 
    627 	/*
    628 	 * Set the LWP runnable.  If it's swapped out, we need to wake the swapper
    629 	 * to bring it back in.  Otherwise, enter it into a run queue.
    630 	 */
    631 	if (l->l_mutex != l->l_cpu->ci_schedstate.spc_mutex) {
    632 		spc_lock(l->l_cpu);
    633 		lwp_unlock_to(l, l->l_cpu->ci_schedstate.spc_mutex);
    634 	}
    635 
    636 	sched_setrunnable(l);
    637 	l->l_stat = LSRUN;
    638 	l->l_slptime = 0;
    639 
    640 	if (l->l_flag & LW_INMEM) {
    641 		sched_enqueue(l, false);
    642 		resched_cpu(l);
    643 		lwp_unlock(l);
    644 	} else {
    645 		lwp_unlock(l);
    646 		uvm_kick_scheduler();
    647 	}
    648 }
    649 
    650 /*
    651  * suspendsched:
    652  *
    653  *	Convert all non-L_SYSTEM LSSLEEP or LSRUN LWPs to LSSUSPENDED.
    654  */
    655 void
    656 suspendsched(void)
    657 {
    658 	CPU_INFO_ITERATOR cii;
    659 	struct cpu_info *ci;
    660 	struct lwp *l;
    661 	struct proc *p;
    662 
    663 	/*
    664 	 * We do this by process in order not to violate the locking rules.
    665 	 */
    666 	mutex_enter(&proclist_lock);
    667 	PROCLIST_FOREACH(p, &allproc) {
    668 		mutex_enter(&p->p_smutex);
    669 
    670 		if ((p->p_flag & PK_SYSTEM) != 0) {
    671 			mutex_exit(&p->p_smutex);
    672 			continue;
    673 		}
    674 
    675 		p->p_stat = SSTOP;
    676 
    677 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    678 			if (l == curlwp)
    679 				continue;
    680 
    681 			lwp_lock(l);
    682 
    683 			/*
    684 			 * Set L_WREBOOT so that the LWP will suspend itself
    685 			 * when it tries to return to user mode.  We want to
    686 			 * try and get to get as many LWPs as possible to
    687 			 * the user / kernel boundary, so that they will
    688 			 * release any locks that they hold.
    689 			 */
    690 			l->l_flag |= (LW_WREBOOT | LW_WSUSPEND);
    691 
    692 			if (l->l_stat == LSSLEEP &&
    693 			    (l->l_flag & LW_SINTR) != 0) {
    694 				/* setrunnable() will release the lock. */
    695 				setrunnable(l);
    696 				continue;
    697 			}
    698 
    699 			lwp_unlock(l);
    700 		}
    701 
    702 		mutex_exit(&p->p_smutex);
    703 	}
    704 	mutex_exit(&proclist_lock);
    705 
    706 	/*
    707 	 * Kick all CPUs to make them preempt any LWPs running in user mode.
    708 	 * They'll trap into the kernel and suspend themselves in userret().
    709 	 */
    710 	for (CPU_INFO_FOREACH(cii, ci)) {
    711 		spc_lock(ci);
    712 		cpu_need_resched(ci, RESCHED_IMMED);
    713 		spc_unlock(ci);
    714 	}
    715 }
    716 
    717 /*
    718  * sched_kpri:
    719  *
    720  *	Scale a priority level to a kernel priority level, usually
    721  *	for an LWP that is about to sleep.
    722  */
    723 pri_t
    724 sched_kpri(struct lwp *l)
    725 {
    726 	pri_t pri;
    727 
    728 #ifndef __HAVE_FAST_SOFTINTS
    729 	/*
    730 	 * Hack: if a user thread is being used to run a soft
    731 	 * interrupt, we need to boost the priority here.
    732 	 */
    733 	if ((l->l_pflag & LP_INTR) != 0 && l->l_priority < PRI_KERNEL_RT)
    734 		return softint_kpri(l);
    735 #endif
    736 
    737 	/*
    738 	 * Scale user priorities (0 -> 63) up to kernel priorities
    739 	 * in the range (64 -> 95).  This makes assumptions about
    740 	 * the priority space and so should be kept in sync with
    741 	 * param.h.
    742 	 */
    743 	if ((pri = l->l_usrpri) >= PRI_KERNEL)
    744 		return pri;
    745 
    746 	return (pri >> 1) + PRI_KERNEL;
    747 }
    748 
    749 /*
    750  * sched_unsleep:
    751  *
    752  *	The is called when the LWP has not been awoken normally but instead
    753  *	interrupted: for example, if the sleep timed out.  Because of this,
    754  *	it's not a valid action for running or idle LWPs.
    755  */
    756 static void
    757 sched_unsleep(struct lwp *l)
    758 {
    759 
    760 	lwp_unlock(l);
    761 	panic("sched_unsleep");
    762 }
    763 
    764 inline void
    765 resched_cpu(struct lwp *l)
    766 {
    767 	struct cpu_info *ci;
    768 	const pri_t pri = lwp_eprio(l);
    769 
    770 	/*
    771 	 * XXXSMP
    772 	 * Since l->l_cpu persists across a context switch,
    773 	 * this gives us *very weak* processor affinity, in
    774 	 * that we notify the CPU on which the process last
    775 	 * ran that it should try to switch.
    776 	 *
    777 	 * This does not guarantee that the process will run on
    778 	 * that processor next, because another processor might
    779 	 * grab it the next time it performs a context switch.
    780 	 *
    781 	 * This also does not handle the case where its last
    782 	 * CPU is running a higher-priority process, but every
    783 	 * other CPU is running a lower-priority process.  There
    784 	 * are ways to handle this situation, but they're not
    785 	 * currently very pretty, and we also need to weigh the
    786 	 * cost of moving a process from one CPU to another.
    787 	 */
    788 	ci = l->l_cpu;
    789 	if (pri > ci->ci_schedstate.spc_curpriority)
    790 		cpu_need_resched(ci, 0);
    791 }
    792 
    793 static void
    794 sched_changepri(struct lwp *l, pri_t pri)
    795 {
    796 
    797 	KASSERT(lwp_locked(l, NULL));
    798 
    799 	l->l_usrpri = pri;
    800 	if (l->l_priority >= PRI_KERNEL)
    801 		return;
    802 
    803 	if (l->l_stat != LSRUN || (l->l_flag & LW_INMEM) == 0) {
    804 		l->l_priority = pri;
    805 		return;
    806 	}
    807 
    808 	KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
    809 
    810 	sched_dequeue(l);
    811 	l->l_priority = pri;
    812 	sched_enqueue(l, false);
    813 	resched_cpu(l);
    814 }
    815 
    816 static void
    817 sched_lendpri(struct lwp *l, pri_t pri)
    818 {
    819 
    820 	KASSERT(lwp_locked(l, NULL));
    821 
    822 	if (l->l_stat != LSRUN || (l->l_flag & LW_INMEM) == 0) {
    823 		l->l_inheritedprio = pri;
    824 		return;
    825 	}
    826 
    827 	KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
    828 
    829 	sched_dequeue(l);
    830 	l->l_inheritedprio = pri;
    831 	sched_enqueue(l, false);
    832 	resched_cpu(l);
    833 }
    834 
    835 struct lwp *
    836 syncobj_noowner(wchan_t wchan)
    837 {
    838 
    839 	return NULL;
    840 }
    841 
    842 
    843 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
    844 fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;		/* exp(-1/20) */
    845 
    846 /*
    847  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
    848  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
    849  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
    850  *
    851  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
    852  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
    853  *
    854  * If you dont want to bother with the faster/more-accurate formula, you
    855  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
    856  * (more general) method of calculating the %age of CPU used by a process.
    857  */
    858 #define	CCPU_SHIFT	(FSHIFT + 1)
    859 
    860 /*
    861  * sched_pstats:
    862  *
    863  * Update process statistics and check CPU resource allocation.
    864  * Call scheduler-specific hook to eventually adjust process/LWP
    865  * priorities.
    866  */
    867 /* ARGSUSED */
    868 void
    869 sched_pstats(void *arg)
    870 {
    871 	struct rlimit *rlim;
    872 	struct lwp *l;
    873 	struct proc *p;
    874 	int minslp, sig, clkhz;
    875 	long runtm;
    876 
    877 	sched_pstats_ticks++;
    878 
    879 	mutex_enter(&proclist_lock);
    880 	PROCLIST_FOREACH(p, &allproc) {
    881 		/*
    882 		 * Increment time in/out of memory and sleep time (if
    883 		 * sleeping).  We ignore overflow; with 16-bit int's
    884 		 * (remember them?) overflow takes 45 days.
    885 		 */
    886 		minslp = 2;
    887 		mutex_enter(&p->p_smutex);
    888 		mutex_spin_enter(&p->p_stmutex);
    889 		runtm = p->p_rtime.tv_sec;
    890 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    891 			if ((l->l_flag & LW_IDLE) != 0)
    892 				continue;
    893 			lwp_lock(l);
    894 			runtm += l->l_rtime.tv_sec;
    895 			l->l_swtime++;
    896 			if (l->l_stat == LSSLEEP || l->l_stat == LSSTOP ||
    897 			    l->l_stat == LSSUSPENDED) {
    898 				l->l_slptime++;
    899 				minslp = min(minslp, l->l_slptime);
    900 			} else
    901 				minslp = 0;
    902 			sched_pstats_hook(l);
    903 			lwp_unlock(l);
    904 
    905 			/*
    906 			 * p_pctcpu is only for ps.
    907 			 */
    908 			l->l_pctcpu = (l->l_pctcpu * ccpu) >> FSHIFT;
    909 			if (l->l_slptime < 1) {
    910 				clkhz = stathz != 0 ? stathz : hz;
    911 #if	(FSHIFT >= CCPU_SHIFT)
    912 				l->l_pctcpu += (clkhz == 100) ?
    913 				    ((fixpt_t)l->l_cpticks) <<
    914 				        (FSHIFT - CCPU_SHIFT) :
    915 				    100 * (((fixpt_t) p->p_cpticks)
    916 				        << (FSHIFT - CCPU_SHIFT)) / clkhz;
    917 #else
    918 				l->l_pctcpu += ((FSCALE - ccpu) *
    919 				    (l->l_cpticks * FSCALE / clkhz)) >> FSHIFT;
    920 #endif
    921 				l->l_cpticks = 0;
    922 			}
    923 		}
    924 
    925 		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
    926 #ifdef SCHED_4BSD
    927 		/*
    928 		 * XXX: Workaround - belongs to sched_4bsd.c
    929 		 * If the process has slept the entire second,
    930 		 * stop recalculating its priority until it wakes up.
    931 		 */
    932 		if (minslp <= 1) {
    933 			extern fixpt_t decay_cpu(fixpt_t, fixpt_t);
    934 
    935 			fixpt_t loadfac = 2 * (averunnable.ldavg[0]);
    936 			p->p_estcpu = decay_cpu(loadfac, p->p_estcpu);
    937 		}
    938 #endif
    939 		mutex_spin_exit(&p->p_stmutex);
    940 
    941 		/*
    942 		 * Check if the process exceeds its CPU resource allocation.
    943 		 * If over max, kill it.
    944 		 */
    945 		rlim = &p->p_rlimit[RLIMIT_CPU];
    946 		sig = 0;
    947 		if (runtm >= rlim->rlim_cur) {
    948 			if (runtm >= rlim->rlim_max)
    949 				sig = SIGKILL;
    950 			else {
    951 				sig = SIGXCPU;
    952 				if (rlim->rlim_cur < rlim->rlim_max)
    953 					rlim->rlim_cur += 5;
    954 			}
    955 		}
    956 		mutex_exit(&p->p_smutex);
    957 		if (sig) {
    958 			/* XXXAD */
    959 			mutex_enter(&proclist_mutex);
    960 			psignal(p, sig);
    961 			mutex_enter(&proclist_mutex);
    962 		}
    963 	}
    964 	mutex_exit(&proclist_lock);
    965 	uvm_meter();
    966 	cv_wakeup(&lbolt);
    967 	callout_schedule(&sched_pstats_ch, hz);
    968 }
    969 
    970 void
    971 sched_init(void)
    972 {
    973 
    974 	callout_init(&sched_pstats_ch, CALLOUT_MPSAFE);
    975 	callout_setfunc(&sched_pstats_ch, sched_pstats, NULL);
    976 	sched_setup();
    977 	sched_pstats(NULL);
    978 }
    979