Home | History | Annotate | Line # | Download | only in kern
kern_synch.c revision 1.186.2.11
      1 /*	$NetBSD: kern_synch.c,v 1.186.2.11 2007/07/14 22:09:45 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.11 2007/07/14 22:09:45 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 	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  * - update l_runtime for the next lwp.
    319  */
    320 
    321 void
    322 updatertime(lwp_t *l, struct timeval *tv)
    323 {
    324 	long s, u;
    325 
    326 	if ((l->l_flag & LW_IDLE) != 0)
    327 		return;
    328 
    329 	u = l->l_rtime.tv_usec + (tv->tv_usec - l->l_stime.tv_usec);
    330 	s = l->l_rtime.tv_sec + (tv->tv_sec - l->l_stime.tv_sec);
    331 	if (u < 0) {
    332 		u += 1000000;
    333 		s--;
    334 	} else if (u >= 1000000) {
    335 		u -= 1000000;
    336 		s++;
    337 	}
    338 	l->l_rtime.tv_usec = u;
    339 	l->l_rtime.tv_sec = s;
    340 }
    341 
    342 /*
    343  * The machine independent parts of context switch.
    344  *
    345  * Returns 1 if another LWP was actually run.
    346  */
    347 int
    348 mi_switch(lwp_t *l)
    349 {
    350 	struct schedstate_percpu *spc;
    351 	struct lwp *newl;
    352 	int retval, oldspl;
    353 	struct timeval tv;
    354 	bool returning;
    355 
    356 	KASSERT(lwp_locked(l, NULL));
    357 	LOCKDEBUG_BARRIER(l->l_mutex, 1);
    358 
    359 #ifdef KSTACK_CHECK_MAGIC
    360 	kstack_check_magic(l);
    361 #endif
    362 
    363 	microtime(&tv);
    364 
    365 	/*
    366 	 * It's safe to read the per CPU schedstate unlocked here, as all we
    367 	 * are after is the run time and that's guarenteed to have been last
    368 	 * updated by this CPU.
    369 	 */
    370 	KDASSERT(l->l_cpu == curcpu());
    371 
    372 	/*
    373 	 * Process is about to yield the CPU; clear the appropriate
    374 	 * scheduling flags.
    375 	 */
    376 	spc = &l->l_cpu->ci_schedstate;
    377 	returning = false;
    378 	newl = NULL;
    379 
    380 	/*
    381 	 * If we have been asked to switch to a specific LWP, then there
    382 	 * is no need to inspect the run queues.  If a soft interrupt is
    383 	 * blocking, then return to the interrupted thread without adjusting
    384 	 * VM context or its start time: neither have been changed in order
    385 	 * to take the interrupt.
    386 	 */
    387 	if (l->l_switchto != NULL) {
    388 		if ((l->l_flag & LW_INTR) != 0) {
    389 			returning = true;
    390 			softint_block.ev_count++;
    391 			if ((l->l_flag & LW_TIMEINTR) != 0)
    392 				updatertime(l, &tv);
    393 		}
    394 		newl = l->l_switchto;
    395 		l->l_switchto = NULL;
    396 	}
    397 
    398 	if (!returning) {
    399 		/* Count time spent in current system call */
    400 		SYSCALL_TIME_SLEEP(l);
    401 
    402 		/*
    403 		 * XXXSMP If we are using h/w performance counters,
    404 		 * save context.
    405 		 */
    406 #if PERFCTRS
    407 		if (PMC_ENABLED(l->l_proc)) {
    408 			pmc_save_context(l->l_proc);
    409 		}
    410 #endif
    411 		spc->spc_flags &= ~SPCF_SWITCHCLEAR;
    412 		updatertime(l, &tv);
    413 	}
    414 
    415 	/*
    416 	 * If on the CPU and we have gotten this far, then we must yield.
    417 	 */
    418 	mutex_spin_enter(spc->spc_mutex);
    419 	KASSERT(l->l_stat != LSRUN);
    420 	if (l->l_stat == LSONPROC) {
    421 		KASSERT(lwp_locked(l, &spc->spc_lwplock));
    422 		if ((l->l_flag & LW_IDLE) == 0) {
    423 			l->l_stat = LSRUN;
    424 			lwp_setlock(l, spc->spc_mutex);
    425 			sched_enqueue(l, true);
    426 		} else
    427 			l->l_stat = LSIDL;
    428 	}
    429 
    430 	/*
    431 	 * Let sched_nextlwp() select the LWP to run the CPU next.
    432 	 * If no LWP is runnable, switch to the idle LWP.
    433 	 */
    434 	if (newl == NULL) {
    435 		newl = sched_nextlwp();
    436 		if (newl != NULL) {
    437 			sched_dequeue(newl);
    438 			KASSERT(lwp_locked(newl, spc->spc_mutex));
    439 			newl->l_stat = LSONPROC;
    440 			newl->l_cpu = l->l_cpu;
    441 			newl->l_flag |= LW_RUNNING;
    442 			lwp_setlock(newl, &spc->spc_lwplock);
    443 		} else {
    444 			newl = l->l_cpu->ci_data.cpu_idlelwp;
    445 			newl->l_stat = LSONPROC;
    446 			newl->l_flag |= LW_RUNNING;
    447 		}
    448 		spc->spc_curpriority = newl->l_usrpri;
    449 		newl->l_priority = newl->l_usrpri;
    450 		cpu_did_resched();
    451 	}
    452 
    453 	/* Update the new LWP's start time while it is still locked. */
    454 	if (!returning)
    455 		newl->l_stime = tv;
    456 
    457 	if (l != newl) {
    458 		struct lwp *prevlwp;
    459 
    460 		/*
    461 		 * If the old LWP has been moved to a run queue above,
    462 		 * drop the general purpose LWP lock: it's now locked
    463 		 * by the scheduler lock.
    464 		 *
    465 		 * Otherwise, drop the scheduler lock.  We're done with
    466 		 * the run queues for now.
    467 		 */
    468 		if (l->l_mutex == spc->spc_mutex) {
    469 			mutex_spin_exit(&spc->spc_lwplock);
    470 		} else {
    471 			mutex_spin_exit(spc->spc_mutex);
    472 		}
    473 
    474 		/* Unlocked, but for statistics only. */
    475 		uvmexp.swtch++;
    476 
    477 		/*
    478 		 * Save old VM context, unless a soft interrupt
    479 		 * handler is blocking.
    480 		 */
    481 		if (!returning)
    482 			pmap_deactivate(l);
    483 
    484 		/* Switch to the new LWP.. */
    485 		l->l_ncsw++;
    486 		l->l_flag &= ~LW_RUNNING;
    487 		oldspl = MUTEX_SPIN_OLDSPL(l->l_cpu);
    488 		prevlwp = cpu_switchto(l, newl, returning);
    489 
    490 		/*
    491 		 * .. we have switched away and are now back so we must
    492 		 * be the new curlwp.  prevlwp is who we replaced.
    493 		 */
    494 		curlwp = l;
    495 		if (prevlwp != NULL) {
    496 			curcpu()->ci_mtx_oldspl = oldspl;
    497 			lwp_unlock(prevlwp);
    498 		} else {
    499 			splx(oldspl);
    500 		}
    501 
    502 		/* Restore VM context. */
    503 		pmap_activate(l);
    504 		retval = 1;
    505 	} else {
    506 		/* Nothing to do - just unlock and return. */
    507 		mutex_spin_exit(spc->spc_mutex);
    508 		lwp_unlock(l);
    509 		retval = 0;
    510 	}
    511 
    512 	KASSERT(l == curlwp);
    513 	KASSERT(l->l_stat == LSONPROC);
    514 	KASSERT(l->l_cpu == curcpu());
    515 
    516 	/*
    517 	 * XXXSMP If we are using h/w performance counters, restore context.
    518 	 */
    519 #if PERFCTRS
    520 	if (PMC_ENABLED(l->l_proc)) {
    521 		pmc_restore_context(l->l_proc);
    522 	}
    523 #endif
    524 
    525 	SYSCALL_TIME_WAKEUP(l);
    526 	LOCKDEBUG_BARRIER(NULL, 1);
    527 
    528 	return retval;
    529 }
    530 
    531 /*
    532  * Change process state to be runnable, placing it on the run queue if it is
    533  * in memory, and awakening the swapper if it isn't in memory.
    534  *
    535  * Call with the process and LWP locked.  Will return with the LWP unlocked.
    536  */
    537 void
    538 setrunnable(struct lwp *l)
    539 {
    540 	struct proc *p = l->l_proc;
    541 	sigset_t *ss;
    542 
    543 	KASSERT((l->l_flag & LW_IDLE) == 0);
    544 	KASSERT(mutex_owned(&p->p_smutex));
    545 	KASSERT(lwp_locked(l, NULL));
    546 
    547 	switch (l->l_stat) {
    548 	case LSSTOP:
    549 		/*
    550 		 * If we're being traced (possibly because someone attached us
    551 		 * while we were stopped), check for a signal from the debugger.
    552 		 */
    553 		if ((p->p_slflag & PSL_TRACED) != 0 && p->p_xstat != 0) {
    554 			if ((sigprop[p->p_xstat] & SA_TOLWP) != 0)
    555 				ss = &l->l_sigpend.sp_set;
    556 			else
    557 				ss = &p->p_sigpend.sp_set;
    558 			sigaddset(ss, p->p_xstat);
    559 			signotify(l);
    560 		}
    561 		p->p_nrlwps++;
    562 		break;
    563 	case LSSUSPENDED:
    564 		l->l_flag &= ~LW_WSUSPEND;
    565 		p->p_nrlwps++;
    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 #ifdef MULTIPROCESSOR
    628 	CPU_INFO_ITERATOR cii;
    629 	struct cpu_info *ci;
    630 #endif
    631 	struct lwp *l;
    632 	struct proc *p;
    633 
    634 	/*
    635 	 * We do this by process in order not to violate the locking rules.
    636 	 */
    637 	mutex_enter(&proclist_lock);
    638 	PROCLIST_FOREACH(p, &allproc) {
    639 		mutex_enter(&p->p_smutex);
    640 
    641 		if ((p->p_flag & PK_SYSTEM) != 0) {
    642 			mutex_exit(&p->p_smutex);
    643 			continue;
    644 		}
    645 
    646 		p->p_stat = SSTOP;
    647 
    648 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    649 			if (l == curlwp)
    650 				continue;
    651 
    652 			lwp_lock(l);
    653 
    654 			/*
    655 			 * Set L_WREBOOT so that the LWP will suspend itself
    656 			 * when it tries to return to user mode.  We want to
    657 			 * try and get to get as many LWPs as possible to
    658 			 * the user / kernel boundary, so that they will
    659 			 * release any locks that they hold.
    660 			 */
    661 			l->l_flag |= (LW_WREBOOT | LW_WSUSPEND);
    662 
    663 			if (l->l_stat == LSSLEEP &&
    664 			    (l->l_flag & LW_SINTR) != 0) {
    665 				/* setrunnable() will release the lock. */
    666 				setrunnable(l);
    667 				continue;
    668 			}
    669 
    670 			lwp_unlock(l);
    671 		}
    672 
    673 		mutex_exit(&p->p_smutex);
    674 	}
    675 	mutex_exit(&proclist_lock);
    676 
    677 	/*
    678 	 * Kick all CPUs to make them preempt any LWPs running in user mode.
    679 	 * They'll trap into the kernel and suspend themselves in userret().
    680 	 */
    681 #ifdef MULTIPROCESSOR
    682 	for (CPU_INFO_FOREACH(cii, ci))
    683 		cpu_need_resched(ci, 0);
    684 #else
    685 	cpu_need_resched(curcpu(), 0);
    686 #endif
    687 }
    688 
    689 /*
    690  * sched_kpri:
    691  *
    692  *	Scale a priority level to a kernel priority level, usually
    693  *	for an LWP that is about to sleep.
    694  */
    695 pri_t
    696 sched_kpri(struct lwp *l)
    697 {
    698 	pri_t pri;
    699 
    700 	/*
    701 	 * Scale user priorities (0 -> 63) up to kernel priorities
    702 	 * in the range (64 -> 95).  This makes assumptions about
    703 	 * the priority space and so should be kept in sync with
    704 	 * param.h.
    705 	 */
    706 	if ((pri = l->l_usrpri) >= PRI_KERNEL)
    707 		return pri;
    708 
    709 	return (pri >> 1) + PRI_KERNEL;
    710 }
    711 
    712 /*
    713  * sched_unsleep:
    714  *
    715  *	The is called when the LWP has not been awoken normally but instead
    716  *	interrupted: for example, if the sleep timed out.  Because of this,
    717  *	it's not a valid action for running or idle LWPs.
    718  */
    719 static void
    720 sched_unsleep(struct lwp *l)
    721 {
    722 
    723 	lwp_unlock(l);
    724 	panic("sched_unsleep");
    725 }
    726 
    727 inline void
    728 resched_cpu(struct lwp *l)
    729 {
    730 	struct cpu_info *ci;
    731 	const pri_t pri = lwp_eprio(l);
    732 
    733 	/*
    734 	 * XXXSMP
    735 	 * Since l->l_cpu persists across a context switch,
    736 	 * this gives us *very weak* processor affinity, in
    737 	 * that we notify the CPU on which the process last
    738 	 * ran that it should try to switch.
    739 	 *
    740 	 * This does not guarantee that the process will run on
    741 	 * that processor next, because another processor might
    742 	 * grab it the next time it performs a context switch.
    743 	 *
    744 	 * This also does not handle the case where its last
    745 	 * CPU is running a higher-priority process, but every
    746 	 * other CPU is running a lower-priority process.  There
    747 	 * are ways to handle this situation, but they're not
    748 	 * currently very pretty, and we also need to weigh the
    749 	 * cost of moving a process from one CPU to another.
    750 	 */
    751 	ci = (l->l_cpu != NULL) ? l->l_cpu : curcpu();
    752 	if (pri < ci->ci_schedstate.spc_curpriority)
    753 		cpu_need_resched(ci, 0);
    754 }
    755 
    756 static void
    757 sched_changepri(struct lwp *l, pri_t pri)
    758 {
    759 
    760 	KASSERT(lwp_locked(l, NULL));
    761 
    762 	l->l_usrpri = pri;
    763 	if (l->l_priority >= PRI_KERNEL)
    764 		return;
    765 
    766 	if (l->l_stat != LSRUN || (l->l_flag & LW_INMEM) == 0) {
    767 		l->l_priority = pri;
    768 		return;
    769 	}
    770 
    771 	KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
    772 
    773 	sched_dequeue(l);
    774 	l->l_priority = pri;
    775 	sched_enqueue(l, false);
    776 	resched_cpu(l);
    777 }
    778 
    779 static void
    780 sched_lendpri(struct lwp *l, pri_t pri)
    781 {
    782 
    783 	KASSERT(lwp_locked(l, NULL));
    784 
    785 	if (l->l_stat != LSRUN || (l->l_flag & LW_INMEM) == 0) {
    786 		l->l_inheritedprio = pri;
    787 		return;
    788 	}
    789 
    790 	KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
    791 
    792 	sched_dequeue(l);
    793 	l->l_inheritedprio = pri;
    794 	sched_enqueue(l, false);
    795 	resched_cpu(l);
    796 }
    797 
    798 struct lwp *
    799 syncobj_noowner(wchan_t wchan)
    800 {
    801 
    802 	return NULL;
    803 }
    804 
    805 
    806 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
    807 fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;		/* exp(-1/20) */
    808 
    809 /*
    810  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
    811  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
    812  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
    813  *
    814  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
    815  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
    816  *
    817  * If you dont want to bother with the faster/more-accurate formula, you
    818  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
    819  * (more general) method of calculating the %age of CPU used by a process.
    820  */
    821 #define	CCPU_SHIFT	(FSHIFT + 1)
    822 
    823 /*
    824  * sched_pstats:
    825  *
    826  * Update process statistics and check CPU resource allocation.
    827  * Call scheduler-specific hook to eventually adjust process/LWP
    828  * priorities.
    829  */
    830 /* ARGSUSED */
    831 void
    832 sched_pstats(void *arg)
    833 {
    834 	struct rlimit *rlim;
    835 	struct lwp *l;
    836 	struct proc *p;
    837 	int minslp, sig, clkhz;
    838 	long runtm;
    839 
    840 	sched_pstats_ticks++;
    841 
    842 	mutex_enter(&proclist_lock);
    843 	PROCLIST_FOREACH(p, &allproc) {
    844 		/*
    845 		 * Increment time in/out of memory and sleep time (if
    846 		 * sleeping).  We ignore overflow; with 16-bit int's
    847 		 * (remember them?) overflow takes 45 days.
    848 		 */
    849 		minslp = 2;
    850 		mutex_enter(&p->p_smutex);
    851 		mutex_spin_enter(&p->p_stmutex);
    852 		runtm = p->p_rtime.tv_sec;
    853 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    854 			if ((l->l_flag & LW_IDLE) != 0)
    855 				continue;
    856 			lwp_lock(l);
    857 			runtm += l->l_rtime.tv_sec;
    858 			l->l_swtime++;
    859 			if (l->l_stat == LSSLEEP || l->l_stat == LSSTOP ||
    860 			    l->l_stat == LSSUSPENDED) {
    861 				l->l_slptime++;
    862 				minslp = min(minslp, l->l_slptime);
    863 			} else
    864 				minslp = 0;
    865 			lwp_unlock(l);
    866 
    867 			/*
    868 			 * p_pctcpu is only for ps.
    869 			 */
    870 			l->l_pctcpu = (l->l_pctcpu * ccpu) >> FSHIFT;
    871 			if (l->l_slptime < 1) {
    872 				clkhz = stathz != 0 ? stathz : hz;
    873 #if	(FSHIFT >= CCPU_SHIFT)
    874 				l->l_pctcpu += (clkhz == 100) ?
    875 				    ((fixpt_t)l->l_cpticks) <<
    876 				        (FSHIFT - CCPU_SHIFT) :
    877 				    100 * (((fixpt_t) p->p_cpticks)
    878 				        << (FSHIFT - CCPU_SHIFT)) / clkhz;
    879 #else
    880 				l->l_pctcpu += ((FSCALE - ccpu) *
    881 				    (l->l_cpticks * FSCALE / clkhz)) >> FSHIFT;
    882 #endif
    883 				l->l_cpticks = 0;
    884 			}
    885 		}
    886 		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
    887 		sched_pstats_hook(p, minslp);
    888 		mutex_spin_exit(&p->p_stmutex);
    889 
    890 		/*
    891 		 * Check if the process exceeds its CPU resource allocation.
    892 		 * If over max, kill it.
    893 		 */
    894 		rlim = &p->p_rlimit[RLIMIT_CPU];
    895 		sig = 0;
    896 		if (runtm >= rlim->rlim_cur) {
    897 			if (runtm >= rlim->rlim_max)
    898 				sig = SIGKILL;
    899 			else {
    900 				sig = SIGXCPU;
    901 				if (rlim->rlim_cur < rlim->rlim_max)
    902 					rlim->rlim_cur += 5;
    903 			}
    904 		}
    905 		mutex_exit(&p->p_smutex);
    906 		if (sig) {
    907 			/* XXXAD */
    908 			mutex_enter(&proclist_mutex);
    909 			psignal(p, sig);
    910 			mutex_enter(&proclist_mutex);
    911 		}
    912 	}
    913 	mutex_exit(&proclist_lock);
    914 	uvm_meter();
    915 	cv_broadcast(&lbolt);
    916 	callout_schedule(&sched_pstats_ch, hz);
    917 }
    918 
    919 void
    920 sched_init(void)
    921 {
    922 
    923 	callout_init(&sched_pstats_ch, CALLOUT_MPSAFE);
    924 	callout_setfunc(&sched_pstats_ch, sched_pstats, NULL);
    925 	sched_setup();
    926 	sched_pstats(NULL);
    927 }
    928