Home | History | Annotate | Line # | Download | only in kern
kern_synch.c revision 1.186.2.15
      1 /*	$NetBSD: kern_synch.c,v 1.186.2.15 2007/08/31 15:18:12 yamt 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.15 2007/08/31 15:18:12 yamt 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 	if (sleepq_dontsleep(l)) {
    167 		(void)sleepq_abort(NULL, 0);
    168 		if ((priority & PNORELOCK) != 0)
    169 			simple_unlock(interlock);
    170 		return 0;
    171 	}
    172 
    173 	sq = sleeptab_lookup(&sleeptab, ident);
    174 	sleepq_enter(sq, l);
    175 	sleepq_enqueue(sq, sched_kpri(l), ident, wmesg, &sleep_syncobj);
    176 
    177 	if (interlock != NULL) {
    178 		KASSERT(simple_lock_held(interlock));
    179 		simple_unlock(interlock);
    180 	}
    181 
    182 	error = sleepq_block(timo, priority & PCATCH);
    183 
    184 	if (interlock != NULL && (priority & PNORELOCK) == 0)
    185 		simple_lock(interlock);
    186 
    187 	return error;
    188 }
    189 
    190 int
    191 mtsleep(wchan_t ident, pri_t priority, const char *wmesg, int timo,
    192 	kmutex_t *mtx)
    193 {
    194 	struct lwp *l = curlwp;
    195 	sleepq_t *sq;
    196 	int error;
    197 
    198 	if (sleepq_dontsleep(l)) {
    199 		(void)sleepq_abort(mtx, (priority & PNORELOCK) != 0);
    200 		return 0;
    201 	}
    202 
    203 	sq = sleeptab_lookup(&sleeptab, ident);
    204 	sleepq_enter(sq, l);
    205 	sleepq_enqueue(sq, sched_kpri(l), ident, wmesg, &sleep_syncobj);
    206 	mutex_exit(mtx);
    207 	error = sleepq_block(timo, priority & PCATCH);
    208 
    209 	if ((priority & PNORELOCK) == 0)
    210 		mutex_enter(mtx);
    211 
    212 	return error;
    213 }
    214 
    215 /*
    216  * General sleep call for situations where a wake-up is not expected.
    217  */
    218 int
    219 kpause(const char *wmesg, bool intr, int timo, kmutex_t *mtx)
    220 {
    221 	struct lwp *l = curlwp;
    222 	sleepq_t *sq;
    223 	int error;
    224 
    225 	if (sleepq_dontsleep(l))
    226 		return sleepq_abort(NULL, 0);
    227 
    228 	if (mtx != NULL)
    229 		mutex_exit(mtx);
    230 	sq = sleeptab_lookup(&sleeptab, l);
    231 	sleepq_enter(sq, l);
    232 	sleepq_enqueue(sq, sched_kpri(l), l, wmesg, &sleep_syncobj);
    233 	error = sleepq_block(timo, intr);
    234 	if (mtx != NULL)
    235 		mutex_enter(mtx);
    236 
    237 	return error;
    238 }
    239 
    240 /*
    241  * OBSOLETE INTERFACE
    242  *
    243  * Make all processes sleeping on the specified identifier runnable.
    244  */
    245 void
    246 wakeup(wchan_t ident)
    247 {
    248 	sleepq_t *sq;
    249 
    250 	if (cold)
    251 		return;
    252 
    253 	sq = sleeptab_lookup(&sleeptab, ident);
    254 	sleepq_wake(sq, ident, (u_int)-1);
    255 }
    256 
    257 /*
    258  * OBSOLETE INTERFACE
    259  *
    260  * Make the highest priority process first in line on the specified
    261  * identifier runnable.
    262  */
    263 void
    264 wakeup_one(wchan_t ident)
    265 {
    266 	sleepq_t *sq;
    267 
    268 	if (cold)
    269 		return;
    270 
    271 	sq = sleeptab_lookup(&sleeptab, ident);
    272 	sleepq_wake(sq, ident, 1);
    273 }
    274 
    275 
    276 /*
    277  * General yield call.  Puts the current process back on its run queue and
    278  * performs a voluntary context switch.  Should only be called when the
    279  * current process explicitly requests it (eg sched_yield(2) in compat code).
    280  */
    281 void
    282 yield(void)
    283 {
    284 	struct lwp *l = curlwp;
    285 
    286 	KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
    287 	lwp_lock(l);
    288 	KASSERT(lwp_locked(l, &l->l_cpu->ci_schedstate.spc_lwplock));
    289 	KASSERT(l->l_stat == LSONPROC);
    290 	l->l_priority = l->l_usrpri;
    291 	(void)mi_switch(l);
    292 	KERNEL_LOCK(l->l_biglocks, l);
    293 }
    294 
    295 /*
    296  * General preemption call.  Puts the current process back on its run queue
    297  * and performs an involuntary context switch.
    298  */
    299 void
    300 preempt(void)
    301 {
    302 	struct lwp *l = curlwp;
    303 
    304 	KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
    305 	lwp_lock(l);
    306 	KASSERT(lwp_locked(l, &l->l_cpu->ci_schedstate.spc_lwplock));
    307 	KASSERT(l->l_stat == LSONPROC);
    308 	l->l_priority = l->l_usrpri;
    309 	l->l_nivcsw++;
    310 	(void)mi_switch(l);
    311 	KERNEL_LOCK(l->l_biglocks, l);
    312 }
    313 
    314 /*
    315  * Compute the amount of time during which the current lwp was running.
    316  *
    317  * - update l_rtime unless it's an idle lwp.
    318  */
    319 
    320 void
    321 updatertime(lwp_t *l, const struct timeval *tv)
    322 {
    323 	long s, u;
    324 
    325 	if ((l->l_flag & LW_IDLE) != 0)
    326 		return;
    327 
    328 	u = l->l_rtime.tv_usec + (tv->tv_usec - l->l_stime.tv_usec);
    329 	s = l->l_rtime.tv_sec + (tv->tv_sec - l->l_stime.tv_sec);
    330 	if (u < 0) {
    331 		u += 1000000;
    332 		s--;
    333 	} else if (u >= 1000000) {
    334 		u -= 1000000;
    335 		s++;
    336 	}
    337 	l->l_rtime.tv_usec = u;
    338 	l->l_rtime.tv_sec = s;
    339 }
    340 
    341 /*
    342  * The machine independent parts of context switch.
    343  *
    344  * Returns 1 if another LWP was actually run.
    345  */
    346 int
    347 mi_switch(lwp_t *l)
    348 {
    349 	struct schedstate_percpu *spc;
    350 	struct lwp *newl;
    351 	int retval, oldspl;
    352 	struct timeval tv;
    353 	bool returning;
    354 
    355 	KASSERT(lwp_locked(l, NULL));
    356 	LOCKDEBUG_BARRIER(l->l_mutex, 1);
    357 
    358 #ifdef KSTACK_CHECK_MAGIC
    359 	kstack_check_magic(l);
    360 #endif
    361 
    362 	microtime(&tv);
    363 
    364 	/*
    365 	 * It's safe to read the per CPU schedstate unlocked here, as all we
    366 	 * are after is the run time and that's guarenteed to have been last
    367 	 * updated by this CPU.
    368 	 */
    369 	KDASSERT(l->l_cpu == curcpu());
    370 
    371 	/*
    372 	 * Process is about to yield the CPU; clear the appropriate
    373 	 * scheduling flags.
    374 	 */
    375 	spc = &l->l_cpu->ci_schedstate;
    376 	returning = false;
    377 	newl = NULL;
    378 
    379 	/*
    380 	 * If we have been asked to switch to a specific LWP, then there
    381 	 * is no need to inspect the run queues.  If a soft interrupt is
    382 	 * blocking, then return to the interrupted thread without adjusting
    383 	 * VM context or its start time: neither have been changed in order
    384 	 * to take the interrupt.
    385 	 */
    386 	if (l->l_switchto != NULL) {
    387 		if ((l->l_flag & LW_INTR) != 0) {
    388 			returning = true;
    389 			softint_block.ev_count++;
    390 			if ((l->l_flag & LW_TIMEINTR) != 0)
    391 				updatertime(l, &tv);
    392 		}
    393 		newl = l->l_switchto;
    394 		l->l_switchto = NULL;
    395 	}
    396 
    397 	if (!returning) {
    398 		/* Count time spent in current system call */
    399 		SYSCALL_TIME_SLEEP(l);
    400 
    401 		/*
    402 		 * XXXSMP If we are using h/w performance counters,
    403 		 * save context.
    404 		 */
    405 #if PERFCTRS
    406 		if (PMC_ENABLED(l->l_proc)) {
    407 			pmc_save_context(l->l_proc);
    408 		}
    409 #endif
    410 		updatertime(l, &tv);
    411 	}
    412 
    413 	/*
    414 	 * If on the CPU and we have gotten this far, then we must yield.
    415 	 */
    416 	mutex_spin_enter(spc->spc_mutex);
    417 	KASSERT(l->l_stat != LSRUN);
    418 	if (l->l_stat == LSONPROC) {
    419 		KASSERT(lwp_locked(l, &spc->spc_lwplock));
    420 		if ((l->l_flag & LW_IDLE) == 0) {
    421 			l->l_stat = LSRUN;
    422 			lwp_setlock(l, spc->spc_mutex);
    423 			sched_enqueue(l, true);
    424 		} else
    425 			l->l_stat = LSIDL;
    426 	}
    427 
    428 	/*
    429 	 * Let sched_nextlwp() select the LWP to run the CPU next.
    430 	 * If no LWP is runnable, switch to the idle LWP.
    431 	 */
    432 	if (newl == NULL) {
    433 		newl = sched_nextlwp();
    434 		if (newl != NULL) {
    435 			sched_dequeue(newl);
    436 			KASSERT(lwp_locked(newl, spc->spc_mutex));
    437 			newl->l_stat = LSONPROC;
    438 			newl->l_cpu = l->l_cpu;
    439 			newl->l_flag |= LW_RUNNING;
    440 			lwp_setlock(newl, &spc->spc_lwplock);
    441 		} else {
    442 			newl = l->l_cpu->ci_data.cpu_idlelwp;
    443 			newl->l_stat = LSONPROC;
    444 			newl->l_flag |= LW_RUNNING;
    445 		}
    446 		spc->spc_curpriority = newl->l_usrpri;
    447 		newl->l_priority = newl->l_usrpri;
    448 		cpu_did_resched();
    449 		spc->spc_flags &= ~SPCF_SWITCHCLEAR;
    450 	}
    451 
    452 	/* Update the new LWP's start time while it is still locked. */
    453 	if (!returning)
    454 		newl->l_stime = tv;
    455 
    456 	if (l != newl) {
    457 		struct lwp *prevlwp;
    458 
    459 		/*
    460 		 * If the old LWP has been moved to a run queue above,
    461 		 * drop the general purpose LWP lock: it's now locked
    462 		 * by the scheduler lock.
    463 		 *
    464 		 * Otherwise, drop the scheduler lock.  We're done with
    465 		 * the run queues for now.
    466 		 */
    467 		if (l->l_mutex == spc->spc_mutex) {
    468 			mutex_spin_exit(&spc->spc_lwplock);
    469 		} else {
    470 			mutex_spin_exit(spc->spc_mutex);
    471 		}
    472 
    473 		/* Unlocked, but for statistics only. */
    474 		uvmexp.swtch++;
    475 
    476 		/*
    477 		 * Save old VM context, unless a soft interrupt
    478 		 * handler is blocking.
    479 		 */
    480 		if (!returning)
    481 			pmap_deactivate(l);
    482 
    483 		/* Switch to the new LWP.. */
    484 		l->l_ncsw++;
    485 		l->l_flag &= ~LW_RUNNING;
    486 		oldspl = MUTEX_SPIN_OLDSPL(l->l_cpu);
    487 		prevlwp = cpu_switchto(l, newl, returning);
    488 
    489 		/*
    490 		 * .. we have switched away and are now back so we must
    491 		 * be the new curlwp.  prevlwp is who we replaced.
    492 		 */
    493 		curlwp = l;
    494 		if (prevlwp != NULL) {
    495 			curcpu()->ci_mtx_oldspl = oldspl;
    496 			lwp_unlock(prevlwp);
    497 		} else {
    498 			splx(oldspl);
    499 		}
    500 
    501 		/* Restore VM context. */
    502 		pmap_activate(l);
    503 		retval = 1;
    504 	} else {
    505 		/* Nothing to do - just unlock and return. */
    506 		mutex_spin_exit(spc->spc_mutex);
    507 		lwp_unlock(l);
    508 		retval = 0;
    509 	}
    510 
    511 	KASSERT(l == curlwp);
    512 	KASSERT(l->l_stat == LSONPROC);
    513 	KASSERT(l->l_cpu == curcpu());
    514 
    515 	/*
    516 	 * XXXSMP If we are using h/w performance counters, restore context.
    517 	 */
    518 #if PERFCTRS
    519 	if (PMC_ENABLED(l->l_proc)) {
    520 		pmc_restore_context(l->l_proc);
    521 	}
    522 #endif
    523 
    524 	SYSCALL_TIME_WAKEUP(l);
    525 	LOCKDEBUG_BARRIER(NULL, 1);
    526 
    527 	return retval;
    528 }
    529 
    530 /*
    531  * Change process state to be runnable, placing it on the run queue if it is
    532  * in memory, and awakening the swapper if it isn't in memory.
    533  *
    534  * Call with the process and LWP locked.  Will return with the LWP unlocked.
    535  */
    536 void
    537 setrunnable(struct lwp *l)
    538 {
    539 	struct proc *p = l->l_proc;
    540 	sigset_t *ss;
    541 
    542 	KASSERT((l->l_flag & LW_IDLE) == 0);
    543 	KASSERT(mutex_owned(&p->p_smutex));
    544 	KASSERT(lwp_locked(l, NULL));
    545 
    546 	switch (l->l_stat) {
    547 	case LSSTOP:
    548 		/*
    549 		 * If we're being traced (possibly because someone attached us
    550 		 * while we were stopped), check for a signal from the debugger.
    551 		 */
    552 		if ((p->p_slflag & PSL_TRACED) != 0 && p->p_xstat != 0) {
    553 			if ((sigprop[p->p_xstat] & SA_TOLWP) != 0)
    554 				ss = &l->l_sigpend.sp_set;
    555 			else
    556 				ss = &p->p_sigpend.sp_set;
    557 			sigaddset(ss, p->p_xstat);
    558 			signotify(l);
    559 		}
    560 		p->p_nrlwps++;
    561 		break;
    562 	case LSSUSPENDED:
    563 		l->l_flag &= ~LW_WSUSPEND;
    564 		p->p_nrlwps++;
    565 		cv_broadcast(&p->p_lwpcv);
    566 		break;
    567 	case LSSLEEP:
    568 		KASSERT(l->l_wchan != NULL);
    569 		break;
    570 	default:
    571 		panic("setrunnable: lwp %p state was %d", l, l->l_stat);
    572 	}
    573 
    574 	/*
    575 	 * If the LWP was sleeping interruptably, then it's OK to start it
    576 	 * again.  If not, mark it as still sleeping.
    577 	 */
    578 	if (l->l_wchan != NULL) {
    579 		l->l_stat = LSSLEEP;
    580 		/* lwp_unsleep() will release the lock. */
    581 		lwp_unsleep(l);
    582 		return;
    583 	}
    584 
    585 	/*
    586 	 * If the LWP is still on the CPU, mark it as LSONPROC.  It may be
    587 	 * about to call mi_switch(), in which case it will yield.
    588 	 */
    589 	if ((l->l_flag & LW_RUNNING) != 0) {
    590 		l->l_stat = LSONPROC;
    591 		l->l_slptime = 0;
    592 		lwp_unlock(l);
    593 		return;
    594 	}
    595 
    596 	/*
    597 	 * Set the LWP runnable.  If it's swapped out, we need to wake the swapper
    598 	 * to bring it back in.  Otherwise, enter it into a run queue.
    599 	 */
    600 	if (l->l_mutex != l->l_cpu->ci_schedstate.spc_mutex) {
    601 		spc_lock(l->l_cpu);
    602 		lwp_unlock_to(l, l->l_cpu->ci_schedstate.spc_mutex);
    603 	}
    604 
    605 	sched_setrunnable(l);
    606 	l->l_stat = LSRUN;
    607 	l->l_slptime = 0;
    608 
    609 	if (l->l_flag & LW_INMEM) {
    610 		sched_enqueue(l, false);
    611 		resched_cpu(l);
    612 		lwp_unlock(l);
    613 	} else {
    614 		lwp_unlock(l);
    615 		uvm_kick_scheduler();
    616 	}
    617 }
    618 
    619 /*
    620  * suspendsched:
    621  *
    622  *	Convert all non-L_SYSTEM LSSLEEP or LSRUN LWPs to LSSUSPENDED.
    623  */
    624 void
    625 suspendsched(void)
    626 {
    627 	CPU_INFO_ITERATOR cii;
    628 	struct cpu_info *ci;
    629 	struct lwp *l;
    630 	struct proc *p;
    631 
    632 	/*
    633 	 * We do this by process in order not to violate the locking rules.
    634 	 */
    635 	mutex_enter(&proclist_lock);
    636 	PROCLIST_FOREACH(p, &allproc) {
    637 		mutex_enter(&p->p_smutex);
    638 
    639 		if ((p->p_flag & PK_SYSTEM) != 0) {
    640 			mutex_exit(&p->p_smutex);
    641 			continue;
    642 		}
    643 
    644 		p->p_stat = SSTOP;
    645 
    646 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    647 			if (l == curlwp)
    648 				continue;
    649 
    650 			lwp_lock(l);
    651 
    652 			/*
    653 			 * Set L_WREBOOT so that the LWP will suspend itself
    654 			 * when it tries to return to user mode.  We want to
    655 			 * try and get to get as many LWPs as possible to
    656 			 * the user / kernel boundary, so that they will
    657 			 * release any locks that they hold.
    658 			 */
    659 			l->l_flag |= (LW_WREBOOT | LW_WSUSPEND);
    660 
    661 			if (l->l_stat == LSSLEEP &&
    662 			    (l->l_flag & LW_SINTR) != 0) {
    663 				/* setrunnable() will release the lock. */
    664 				setrunnable(l);
    665 				continue;
    666 			}
    667 
    668 			lwp_unlock(l);
    669 		}
    670 
    671 		mutex_exit(&p->p_smutex);
    672 	}
    673 	mutex_exit(&proclist_lock);
    674 
    675 	/*
    676 	 * Kick all CPUs to make them preempt any LWPs running in user mode.
    677 	 * They'll trap into the kernel and suspend themselves in userret().
    678 	 */
    679 	for (CPU_INFO_FOREACH(cii, ci)) {
    680 		spc_lock(ci);
    681 		cpu_need_resched(ci, RESCHED_IMMED);
    682 		spc_unlock(ci);
    683 	}
    684 }
    685 
    686 /*
    687  * sched_kpri:
    688  *
    689  *	Scale a priority level to a kernel priority level, usually
    690  *	for an LWP that is about to sleep.
    691  */
    692 pri_t
    693 sched_kpri(struct lwp *l)
    694 {
    695 	pri_t pri;
    696 
    697 	/*
    698 	 * Scale user priorities (0 -> 63) up to kernel priorities
    699 	 * in the range (64 -> 95).  This makes assumptions about
    700 	 * the priority space and so should be kept in sync with
    701 	 * param.h.
    702 	 */
    703 	if ((pri = l->l_usrpri) >= PRI_KERNEL)
    704 		return pri;
    705 
    706 	return (pri >> 1) + PRI_KERNEL;
    707 }
    708 
    709 /*
    710  * sched_unsleep:
    711  *
    712  *	The is called when the LWP has not been awoken normally but instead
    713  *	interrupted: for example, if the sleep timed out.  Because of this,
    714  *	it's not a valid action for running or idle LWPs.
    715  */
    716 static void
    717 sched_unsleep(struct lwp *l)
    718 {
    719 
    720 	lwp_unlock(l);
    721 	panic("sched_unsleep");
    722 }
    723 
    724 inline void
    725 resched_cpu(struct lwp *l)
    726 {
    727 	struct cpu_info *ci;
    728 	const pri_t pri = lwp_eprio(l);
    729 
    730 	/*
    731 	 * XXXSMP
    732 	 * Since l->l_cpu persists across a context switch,
    733 	 * this gives us *very weak* processor affinity, in
    734 	 * that we notify the CPU on which the process last
    735 	 * ran that it should try to switch.
    736 	 *
    737 	 * This does not guarantee that the process will run on
    738 	 * that processor next, because another processor might
    739 	 * grab it the next time it performs a context switch.
    740 	 *
    741 	 * This also does not handle the case where its last
    742 	 * CPU is running a higher-priority process, but every
    743 	 * other CPU is running a lower-priority process.  There
    744 	 * are ways to handle this situation, but they're not
    745 	 * currently very pretty, and we also need to weigh the
    746 	 * cost of moving a process from one CPU to another.
    747 	 */
    748 	ci = l->l_cpu;
    749 	if (pri > ci->ci_schedstate.spc_curpriority)
    750 		cpu_need_resched(ci, 0);
    751 }
    752 
    753 static void
    754 sched_changepri(struct lwp *l, pri_t pri)
    755 {
    756 
    757 	KASSERT(lwp_locked(l, NULL));
    758 
    759 	l->l_usrpri = pri;
    760 	if (l->l_priority >= PRI_KERNEL)
    761 		return;
    762 
    763 	if (l->l_stat != LSRUN || (l->l_flag & LW_INMEM) == 0) {
    764 		l->l_priority = pri;
    765 		return;
    766 	}
    767 
    768 	KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
    769 
    770 	sched_dequeue(l);
    771 	l->l_priority = pri;
    772 	sched_enqueue(l, false);
    773 	resched_cpu(l);
    774 }
    775 
    776 static void
    777 sched_lendpri(struct lwp *l, pri_t pri)
    778 {
    779 
    780 	KASSERT(lwp_locked(l, NULL));
    781 
    782 	if (l->l_stat != LSRUN || (l->l_flag & LW_INMEM) == 0) {
    783 		l->l_inheritedprio = pri;
    784 		return;
    785 	}
    786 
    787 	KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
    788 
    789 	sched_dequeue(l);
    790 	l->l_inheritedprio = pri;
    791 	sched_enqueue(l, false);
    792 	resched_cpu(l);
    793 }
    794 
    795 struct lwp *
    796 syncobj_noowner(wchan_t wchan)
    797 {
    798 
    799 	return NULL;
    800 }
    801 
    802 
    803 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
    804 fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;		/* exp(-1/20) */
    805 
    806 /*
    807  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
    808  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
    809  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
    810  *
    811  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
    812  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
    813  *
    814  * If you dont want to bother with the faster/more-accurate formula, you
    815  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
    816  * (more general) method of calculating the %age of CPU used by a process.
    817  */
    818 #define	CCPU_SHIFT	(FSHIFT + 1)
    819 
    820 /*
    821  * sched_pstats:
    822  *
    823  * Update process statistics and check CPU resource allocation.
    824  * Call scheduler-specific hook to eventually adjust process/LWP
    825  * priorities.
    826  */
    827 /* ARGSUSED */
    828 void
    829 sched_pstats(void *arg)
    830 {
    831 	struct rlimit *rlim;
    832 	struct lwp *l;
    833 	struct proc *p;
    834 	int minslp, sig, clkhz;
    835 	long runtm;
    836 
    837 	sched_pstats_ticks++;
    838 
    839 	mutex_enter(&proclist_lock);
    840 	PROCLIST_FOREACH(p, &allproc) {
    841 		/*
    842 		 * Increment time in/out of memory and sleep time (if
    843 		 * sleeping).  We ignore overflow; with 16-bit int's
    844 		 * (remember them?) overflow takes 45 days.
    845 		 */
    846 		minslp = 2;
    847 		mutex_enter(&p->p_smutex);
    848 		mutex_spin_enter(&p->p_stmutex);
    849 		runtm = p->p_rtime.tv_sec;
    850 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    851 			if ((l->l_flag & LW_IDLE) != 0)
    852 				continue;
    853 			lwp_lock(l);
    854 			runtm += l->l_rtime.tv_sec;
    855 			l->l_swtime++;
    856 			if (l->l_stat == LSSLEEP || l->l_stat == LSSTOP ||
    857 			    l->l_stat == LSSUSPENDED) {
    858 				l->l_slptime++;
    859 				minslp = min(minslp, l->l_slptime);
    860 			} else
    861 				minslp = 0;
    862 			lwp_unlock(l);
    863 
    864 			/*
    865 			 * p_pctcpu is only for ps.
    866 			 */
    867 			l->l_pctcpu = (l->l_pctcpu * ccpu) >> FSHIFT;
    868 			if (l->l_slptime < 1) {
    869 				clkhz = stathz != 0 ? stathz : hz;
    870 #if	(FSHIFT >= CCPU_SHIFT)
    871 				l->l_pctcpu += (clkhz == 100) ?
    872 				    ((fixpt_t)l->l_cpticks) <<
    873 				        (FSHIFT - CCPU_SHIFT) :
    874 				    100 * (((fixpt_t) p->p_cpticks)
    875 				        << (FSHIFT - CCPU_SHIFT)) / clkhz;
    876 #else
    877 				l->l_pctcpu += ((FSCALE - ccpu) *
    878 				    (l->l_cpticks * FSCALE / clkhz)) >> FSHIFT;
    879 #endif
    880 				l->l_cpticks = 0;
    881 			}
    882 		}
    883 		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
    884 		sched_pstats_hook(p, minslp);
    885 		mutex_spin_exit(&p->p_stmutex);
    886 
    887 		/*
    888 		 * Check if the process exceeds its CPU resource allocation.
    889 		 * If over max, kill it.
    890 		 */
    891 		rlim = &p->p_rlimit[RLIMIT_CPU];
    892 		sig = 0;
    893 		if (runtm >= rlim->rlim_cur) {
    894 			if (runtm >= rlim->rlim_max)
    895 				sig = SIGKILL;
    896 			else {
    897 				sig = SIGXCPU;
    898 				if (rlim->rlim_cur < rlim->rlim_max)
    899 					rlim->rlim_cur += 5;
    900 			}
    901 		}
    902 		mutex_exit(&p->p_smutex);
    903 		if (sig) {
    904 			/* XXXAD */
    905 			mutex_enter(&proclist_mutex);
    906 			psignal(p, sig);
    907 			mutex_enter(&proclist_mutex);
    908 		}
    909 	}
    910 	mutex_exit(&proclist_lock);
    911 	uvm_meter();
    912 	cv_wakeup(&lbolt);
    913 	callout_schedule(&sched_pstats_ch, hz);
    914 }
    915 
    916 void
    917 sched_init(void)
    918 {
    919 
    920 	callout_init(&sched_pstats_ch, CALLOUT_MPSAFE);
    921 	callout_setfunc(&sched_pstats_ch, sched_pstats, NULL);
    922 	sched_setup();
    923 	sched_pstats(NULL);
    924 }
    925