Home | History | Annotate | Line # | Download | only in kern
kern_synch.c revision 1.101.2.29
      1 /*	$NetBSD: kern_synch.c,v 1.101.2.29 2002/12/31 01:03:52 thorpej Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999, 2000 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.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  * 3. All advertising materials mentioning features or use of this software
     20  *    must display the following acknowledgement:
     21  *	This product includes software developed by the NetBSD
     22  *	Foundation, Inc. and its contributors.
     23  * 4. Neither the name of The NetBSD Foundation nor the names of its
     24  *    contributors may be used to endorse or promote products derived
     25  *    from this software without specific prior written permission.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     37  * POSSIBILITY OF SUCH DAMAGE.
     38  */
     39 
     40 /*-
     41  * Copyright (c) 1982, 1986, 1990, 1991, 1993
     42  *	The Regents of the University of California.  All rights reserved.
     43  * (c) UNIX System Laboratories, Inc.
     44  * All or some portions of this file are derived from material licensed
     45  * to the University of California by American Telephone and Telegraph
     46  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     47  * the permission of UNIX System Laboratories, Inc.
     48  *
     49  * Redistribution and use in source and binary forms, with or without
     50  * modification, are permitted provided that the following conditions
     51  * are met:
     52  * 1. Redistributions of source code must retain the above copyright
     53  *    notice, this list of conditions and the following disclaimer.
     54  * 2. Redistributions in binary form must reproduce the above copyright
     55  *    notice, this list of conditions and the following disclaimer in the
     56  *    documentation and/or other materials provided with the distribution.
     57  * 3. All advertising materials mentioning features or use of this software
     58  *    must display the following acknowledgement:
     59  *	This product includes software developed by the University of
     60  *	California, Berkeley and its contributors.
     61  * 4. Neither the name of the University nor the names of its contributors
     62  *    may be used to endorse or promote products derived from this software
     63  *    without specific prior written permission.
     64  *
     65  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     66  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     67  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     68  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     69  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     70  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     71  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     72  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     73  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     74  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     75  * SUCH DAMAGE.
     76  *
     77  *	@(#)kern_synch.c	8.9 (Berkeley) 5/19/95
     78  */
     79 
     80 #include <sys/cdefs.h>
     81 __KERNEL_RCSID(0, "$NetBSD: kern_synch.c,v 1.101.2.29 2002/12/31 01:03:52 thorpej Exp $");
     82 
     83 #include "opt_ddb.h"
     84 #include "opt_ktrace.h"
     85 #include "opt_kstack.h"
     86 #include "opt_lockdebug.h"
     87 #include "opt_multiprocessor.h"
     88 #include "opt_perfctrs.h"
     89 
     90 #include <sys/param.h>
     91 #include <sys/systm.h>
     92 #include <sys/callout.h>
     93 #include <sys/proc.h>
     94 #include <sys/kernel.h>
     95 #include <sys/buf.h>
     96 #if defined(PERFCTRS)
     97 #include <sys/pmc.h>
     98 #endif
     99 #include <sys/signalvar.h>
    100 #include <sys/resourcevar.h>
    101 #include <sys/sched.h>
    102 #include <sys/sa.h>
    103 #include <sys/savar.h>
    104 
    105 #include <uvm/uvm_extern.h>
    106 
    107 #ifdef KTRACE
    108 #include <sys/ktrace.h>
    109 #endif
    110 
    111 #include <machine/cpu.h>
    112 
    113 int	lbolt;			/* once a second sleep address */
    114 int	rrticks;		/* number of hardclock ticks per roundrobin() */
    115 
    116 /*
    117  * The global scheduler state.
    118  */
    119 struct prochd sched_qs[RUNQUE_NQS];	/* run queues */
    120 __volatile u_int32_t sched_whichqs;	/* bitmap of non-empty queues */
    121 struct slpque sched_slpque[SLPQUE_TABLESIZE]; /* sleep queues */
    122 
    123 struct simplelock sched_lock = SIMPLELOCK_INITIALIZER;
    124 
    125 void schedcpu(void *);
    126 void updatepri(struct lwp *);
    127 void endtsleep(void *);
    128 
    129 __inline void awaken(struct lwp *);
    130 
    131 struct callout schedcpu_ch = CALLOUT_INITIALIZER;
    132 
    133 
    134 
    135 /*
    136  * Force switch among equal priority processes every 100ms.
    137  * Called from hardclock every hz/10 == rrticks hardclock ticks.
    138  */
    139 /* ARGSUSED */
    140 void
    141 roundrobin(struct cpu_info *ci)
    142 {
    143 	struct schedstate_percpu *spc = &ci->ci_schedstate;
    144 
    145 	spc->spc_rrticks = rrticks;
    146 
    147 	if (curlwp != NULL) {
    148 		if (spc->spc_flags & SPCF_SEENRR) {
    149 			/*
    150 			 * The process has already been through a roundrobin
    151 			 * without switching and may be hogging the CPU.
    152 			 * Indicate that the process should yield.
    153 			 */
    154 			spc->spc_flags |= SPCF_SHOULDYIELD;
    155 		} else
    156 			spc->spc_flags |= SPCF_SEENRR;
    157 	}
    158 	need_resched(curcpu());
    159 }
    160 
    161 /*
    162  * Constants for digital decay and forget:
    163  *	90% of (p_estcpu) usage in 5 * loadav time
    164  *	95% of (p_pctcpu) usage in 60 seconds (load insensitive)
    165  *          Note that, as ps(1) mentions, this can let percentages
    166  *          total over 100% (I've seen 137.9% for 3 processes).
    167  *
    168  * Note that hardclock updates p_estcpu and p_cpticks independently.
    169  *
    170  * We wish to decay away 90% of p_estcpu in (5 * loadavg) seconds.
    171  * That is, the system wants to compute a value of decay such
    172  * that the following for loop:
    173  * 	for (i = 0; i < (5 * loadavg); i++)
    174  * 		p_estcpu *= decay;
    175  * will compute
    176  * 	p_estcpu *= 0.1;
    177  * for all values of loadavg:
    178  *
    179  * Mathematically this loop can be expressed by saying:
    180  * 	decay ** (5 * loadavg) ~= .1
    181  *
    182  * The system computes decay as:
    183  * 	decay = (2 * loadavg) / (2 * loadavg + 1)
    184  *
    185  * We wish to prove that the system's computation of decay
    186  * will always fulfill the equation:
    187  * 	decay ** (5 * loadavg) ~= .1
    188  *
    189  * If we compute b as:
    190  * 	b = 2 * loadavg
    191  * then
    192  * 	decay = b / (b + 1)
    193  *
    194  * We now need to prove two things:
    195  *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
    196  *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
    197  *
    198  * Facts:
    199  *         For x close to zero, exp(x) =~ 1 + x, since
    200  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
    201  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
    202  *         For x close to zero, ln(1+x) =~ x, since
    203  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
    204  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
    205  *         ln(.1) =~ -2.30
    206  *
    207  * Proof of (1):
    208  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
    209  *	solving for factor,
    210  *      ln(factor) =~ (-2.30/5*loadav), or
    211  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
    212  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
    213  *
    214  * Proof of (2):
    215  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
    216  *	solving for power,
    217  *      power*ln(b/(b+1)) =~ -2.30, or
    218  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
    219  *
    220  * Actual power values for the implemented algorithm are as follows:
    221  *      loadav: 1       2       3       4
    222  *      power:  5.68    10.32   14.94   19.55
    223  */
    224 
    225 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
    226 #define	loadfactor(loadav)	(2 * (loadav))
    227 #define	decay_cpu(loadfac, cpu)	(((loadfac) * (cpu)) / ((loadfac) + FSCALE))
    228 
    229 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
    230 fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;		/* exp(-1/20) */
    231 
    232 /*
    233  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
    234  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
    235  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
    236  *
    237  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
    238  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
    239  *
    240  * If you dont want to bother with the faster/more-accurate formula, you
    241  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
    242  * (more general) method of calculating the %age of CPU used by a process.
    243  */
    244 #define	CCPU_SHIFT	11
    245 
    246 /*
    247  * Recompute process priorities, every hz ticks.
    248  */
    249 /* ARGSUSED */
    250 void
    251 schedcpu(void *arg)
    252 {
    253 	fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
    254 	struct lwp *l;
    255 	struct proc *p;
    256 	int s, s1;
    257 	unsigned int newcpu;
    258 	int clkhz;
    259 
    260 	proclist_lock_read();
    261 	LIST_FOREACH(l, &alllwp, l_list) {
    262 		/*
    263 		 * Increment time in/out of memory and sleep time
    264 		 * (if sleeping).  We ignore overflow; with 16-bit int's
    265 		 * (remember them?) overflow takes 45 days.
    266 		 */
    267 		p = l->l_proc;
    268 		l->l_swtime++;
    269 		if (l->l_stat == LSSLEEP || l->l_stat == LSSTOP ||
    270 		    l->l_stat == LSSUSPENDED)
    271 			l->l_slptime++;
    272 		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
    273 		/*
    274 		 * If the process has slept the entire second,
    275 		 * stop recalculating its priority until it wakes up.
    276 		 */
    277 		if (l->l_slptime > 1)
    278 			continue;
    279 		s = splstatclock();	/* prevent state changes */
    280 		/*
    281 		 * p_pctcpu is only for ps.
    282 		 */
    283 		clkhz = stathz != 0 ? stathz : hz;
    284 #if	(FSHIFT >= CCPU_SHIFT)
    285 		p->p_pctcpu += (clkhz == 100)?
    286 			((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT):
    287                 	100 * (((fixpt_t) p->p_cpticks)
    288 				<< (FSHIFT - CCPU_SHIFT)) / clkhz;
    289 #else
    290 		l->l_pctcpu += ((FSCALE - ccpu) *
    291 			(p->p_cpticks * FSCALE / clkhz)) >> FSHIFT;
    292 #endif
    293 		p->p_cpticks = 0;
    294 		newcpu = (u_int)decay_cpu(loadfac, p->p_estcpu);
    295 		p->p_estcpu = newcpu;
    296 		SCHED_LOCK(s1);
    297 		resetpriority(l);
    298 		if (l->l_priority >= PUSER) {
    299 			if (l->l_stat == LSRUN &&
    300 			    (l->l_flag & L_INMEM) &&
    301 			    (l->l_priority / PPQ) != (l->l_usrpri / PPQ)) {
    302 				remrunqueue(l);
    303 				l->l_priority = l->l_usrpri;
    304 				setrunqueue(l);
    305 			} else
    306 				l->l_priority = l->l_usrpri;
    307 		}
    308 		SCHED_UNLOCK(s1);
    309 		splx(s);
    310 	}
    311 	proclist_unlock_read();
    312 	uvm_meter();
    313 	wakeup((caddr_t)&lbolt);
    314 	callout_reset(&schedcpu_ch, hz, schedcpu, NULL);
    315 }
    316 
    317 /*
    318  * Recalculate the priority of a process after it has slept for a while.
    319  * For all load averages >= 1 and max p_estcpu of 255, sleeping for at
    320  * least six times the loadfactor will decay p_estcpu to zero.
    321  */
    322 void
    323 updatepri(struct lwp *l)
    324 {
    325 	struct proc *p = l->l_proc;
    326 	unsigned int newcpu;
    327 	fixpt_t loadfac;
    328 
    329 	SCHED_ASSERT_LOCKED();
    330 
    331 	newcpu = p->p_estcpu;
    332 	loadfac = loadfactor(averunnable.ldavg[0]);
    333 
    334 	if (l->l_slptime > 5 * loadfac)
    335 		p->p_estcpu = 0; /* XXX NJWLWP */
    336 	else {
    337 		l->l_slptime--;	/* the first time was done in schedcpu */
    338 		while (newcpu && --l->l_slptime)
    339 			newcpu = (int) decay_cpu(loadfac, newcpu);
    340 		p->p_estcpu = newcpu;
    341 	}
    342 	resetpriority(l);
    343 }
    344 
    345 /*
    346  * During autoconfiguration or after a panic, a sleep will simply
    347  * lower the priority briefly to allow interrupts, then return.
    348  * The priority to be used (safepri) is machine-dependent, thus this
    349  * value is initialized and maintained in the machine-dependent layers.
    350  * This priority will typically be 0, or the lowest priority
    351  * that is safe for use on the interrupt stack; it can be made
    352  * higher to block network software interrupts after panics.
    353  */
    354 int safepri;
    355 
    356 /*
    357  * General sleep call.  Suspends the current process until a wakeup is
    358  * performed on the specified identifier.  The process will then be made
    359  * runnable with the specified priority.  Sleeps at most timo/hz seconds
    360  * (0 means no timeout).  If pri includes PCATCH flag, signals are checked
    361  * before and after sleeping, else signals are not checked.  Returns 0 if
    362  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
    363  * signal needs to be delivered, ERESTART is returned if the current system
    364  * call should be restarted if possible, and EINTR is returned if the system
    365  * call should be interrupted by the signal (return EINTR).
    366  *
    367  * The interlock is held until the scheduler_slock is acquired.  The
    368  * interlock will be locked before returning back to the caller
    369  * unless the PNORELOCK flag is specified, in which case the
    370  * interlock will always be unlocked upon return.
    371  */
    372 int
    373 ltsleep(void *ident, int priority, const char *wmesg, int timo,
    374     __volatile struct simplelock *interlock)
    375 {
    376 	struct lwp *l = curlwp;
    377 	struct proc *p = l->l_proc;
    378 	struct slpque *qp;
    379 	int sig, s;
    380 	int catch = priority & PCATCH;
    381 	int relock = (priority & PNORELOCK) == 0;
    382 	int exiterr = (priority & PNOEXITERR) == 0;
    383 
    384 	/*
    385 	 * XXXSMP
    386 	 * This is probably bogus.  Figure out what the right
    387 	 * thing to do here really is.
    388 	 * Note that not sleeping if ltsleep is called with curlwp == NULL
    389 	 * in the shutdown case is disgusting but partly necessary given
    390 	 * how shutdown (barely) works.
    391 	 */
    392 	if (cold || (doing_shutdown && (panicstr || (l == NULL)))) {
    393 		/*
    394 		 * After a panic, or during autoconfiguration,
    395 		 * just give interrupts a chance, then just return;
    396 		 * don't run any other procs or panic below,
    397 		 * in case this is the idle process and already asleep.
    398 		 */
    399 		s = splhigh();
    400 		splx(safepri);
    401 		splx(s);
    402 		if (interlock != NULL && relock == 0)
    403 			simple_unlock(interlock);
    404 		return (0);
    405 	}
    406 
    407 	KASSERT(p != NULL);
    408 	LOCK_ASSERT(interlock == NULL || simple_lock_held(interlock));
    409 
    410 #ifdef KTRACE
    411 	if (KTRPOINT(p, KTR_CSW))
    412 		ktrcsw(p, 1, 0);
    413 #endif
    414 
    415 	SCHED_LOCK(s);
    416 
    417 #ifdef DIAGNOSTIC
    418 	if (ident == NULL)
    419 		panic("ltsleep: ident == NULL");
    420 	if (l->l_stat != LSONPROC)
    421 		panic("ltsleep: l_stat %d != LSONPROC", l->l_stat);
    422 	if (l->l_back != NULL)
    423 		panic("ltsleep: p_back != NULL");
    424 #endif
    425 
    426 	l->l_wchan = ident;
    427 	l->l_wmesg = wmesg;
    428 	l->l_slptime = 0;
    429 	l->l_priority = priority & PRIMASK;
    430 
    431 	qp = SLPQUE(ident);
    432 	if (qp->sq_head == 0)
    433 		qp->sq_head = l;
    434 	else {
    435 		*qp->sq_tailp = l;
    436 	}
    437 	*(qp->sq_tailp = &l->l_forw) = 0;
    438 
    439 	if (timo)
    440 		callout_reset(&l->l_tsleep_ch, timo, endtsleep, l);
    441 
    442 	/*
    443 	 * We can now release the interlock; the scheduler_slock
    444 	 * is held, so a thread can't get in to do wakeup() before
    445 	 * we do the switch.
    446 	 *
    447 	 * XXX We leave the code block here, after inserting ourselves
    448 	 * on the sleep queue, because we might want a more clever
    449 	 * data structure for the sleep queues at some point.
    450 	 */
    451 	if (interlock != NULL)
    452 		simple_unlock(interlock);
    453 
    454 	/*
    455 	 * We put ourselves on the sleep queue and start our timeout
    456 	 * before calling CURSIG, as we could stop there, and a wakeup
    457 	 * or a SIGCONT (or both) could occur while we were stopped.
    458 	 * A SIGCONT would cause us to be marked as SSLEEP
    459 	 * without resuming us, thus we must be ready for sleep
    460 	 * when CURSIG is called.  If the wakeup happens while we're
    461 	 * stopped, p->p_wchan will be 0 upon return from CURSIG.
    462 	 */
    463 	if (catch) {
    464 		l->l_flag |= L_SINTR;
    465 		if ((sig = CURSIG(l)) != 0) {
    466 			if (l->l_wchan != NULL)
    467 				unsleep(l);
    468 			l->l_stat = LSONPROC;
    469 			SCHED_UNLOCK(s);
    470 			goto resume;
    471 		}
    472 		if (l->l_wchan == NULL) {
    473 			catch = 0;
    474 			SCHED_UNLOCK(s);
    475 			goto resume;
    476 		}
    477 	} else
    478 		sig = 0;
    479 	l->l_stat = LSSLEEP;
    480 	p->p_nrlwps--;
    481 	p->p_stats->p_ru.ru_nvcsw++;
    482 	SCHED_ASSERT_LOCKED();
    483 	if (l->l_flag & L_SA)
    484 		sa_switch(l, SA_UPCALL_BLOCKED);
    485 	else
    486 		mi_switch(l, NULL);
    487 
    488 #if	defined(DDB) && !defined(GPROF)
    489 	/* handy breakpoint location after process "wakes" */
    490 	__asm(".globl bpendtsleep ; bpendtsleep:");
    491 #endif
    492 	/*
    493 	 * p->p_nrlwps is incremented by whoever made us runnable again,
    494 	 * either setrunnable() or awaken().
    495 	 */
    496 
    497 	SCHED_ASSERT_UNLOCKED();
    498 	splx(s);
    499 
    500  resume:
    501 	KDASSERT(l->l_cpu != NULL);
    502 	KDASSERT(l->l_cpu == curcpu());
    503 	l->l_cpu->ci_schedstate.spc_curpriority = l->l_usrpri;
    504 
    505 	l->l_flag &= ~L_SINTR;
    506 	if (l->l_flag & L_TIMEOUT) {
    507 		l->l_flag &= ~L_TIMEOUT;
    508 		if (sig == 0) {
    509 #ifdef KTRACE
    510 			if (KTRPOINT(p, KTR_CSW))
    511 				ktrcsw(p, 0, 0);
    512 #endif
    513 			if (relock && interlock != NULL)
    514 				simple_lock(interlock);
    515 			return (EWOULDBLOCK);
    516 		}
    517 	} else if (timo)
    518 		callout_stop(&l->l_tsleep_ch);
    519 	if (catch && (sig != 0 || (sig = CURSIG(l)) != 0)) {
    520 #ifdef KTRACE
    521 		if (KTRPOINT(p, KTR_CSW))
    522 			ktrcsw(p, 0, 0);
    523 #endif
    524 		if (relock && interlock != NULL)
    525 			simple_lock(interlock);
    526 		if ((SIGACTION(p, sig).sa_flags & SA_RESTART) == 0)
    527 			return (EINTR);
    528 		return (ERESTART);
    529 	}
    530 	/* XXXNJW this is very much a kluge.
    531 	 * revisit. a better way of preventing looping/hanging syscalls like
    532 	 * wait4() and _lwp_wait() from wedging an exiting process
    533 	 * would be preferred.
    534 	 */
    535 	if (catch && ((p->p_flag & P_WEXIT) && exiterr))
    536 		return (EINTR);
    537 #ifdef KTRACE
    538 	if (KTRPOINT(p, KTR_CSW))
    539 		ktrcsw(p, 0, 0);
    540 #endif
    541 	if (relock && interlock != NULL)
    542 		simple_lock(interlock);
    543 	return (0);
    544 }
    545 
    546 /*
    547  * Implement timeout for tsleep.
    548  * If process hasn't been awakened (wchan non-zero),
    549  * set timeout flag and undo the sleep.  If proc
    550  * is stopped, just unsleep so it will remain stopped.
    551  */
    552 void
    553 endtsleep(void *arg)
    554 {
    555 	struct lwp *l;
    556 	int s;
    557 
    558 	l = (struct lwp *)arg;
    559 	SCHED_LOCK(s);
    560 	if (l->l_wchan) {
    561 		if (l->l_stat == LSSLEEP)
    562 			setrunnable(l);
    563 		else
    564 			unsleep(l);
    565 		l->l_flag |= L_TIMEOUT;
    566 	}
    567 	SCHED_UNLOCK(s);
    568 }
    569 
    570 /*
    571  * Remove a process from its wait queue
    572  */
    573 void
    574 unsleep(struct lwp *l)
    575 {
    576 	struct slpque *qp;
    577 	struct lwp **hp;
    578 
    579 	SCHED_ASSERT_LOCKED();
    580 
    581 	if (l->l_wchan) {
    582 		hp = &(qp = SLPQUE(l->l_wchan))->sq_head;
    583 		while (*hp != l)
    584 			hp = &(*hp)->l_forw;
    585 		*hp = l->l_forw;
    586 		if (qp->sq_tailp == &l->l_forw)
    587 			qp->sq_tailp = hp;
    588 		l->l_wchan = 0;
    589 	}
    590 }
    591 
    592 /*
    593  * Optimized-for-wakeup() version of setrunnable().
    594  */
    595 __inline void
    596 awaken(struct lwp *l)
    597 {
    598 
    599 	SCHED_ASSERT_LOCKED();
    600 
    601 	if (l->l_slptime > 1)
    602 		updatepri(l);
    603 	l->l_slptime = 0;
    604 	l->l_stat = LSRUN;
    605 	l->l_proc->p_nrlwps++;
    606 	/*
    607 	 * Since curpriority is a user priority, p->p_priority
    608 	 * is always better than curpriority on the last CPU on
    609 	 * which it ran.
    610 	 *
    611 	 * XXXSMP See affinity comment in resched_proc().
    612 	 */
    613 	if (l->l_flag & L_INMEM) {
    614 		setrunqueue(l);
    615 		if (l->l_flag & L_SA)
    616 			l->l_proc->p_sa->sa_woken = l;
    617 		KASSERT(l->l_cpu != NULL);
    618 		need_resched(l->l_cpu);
    619 	} else
    620 		sched_wakeup(&proc0);
    621 }
    622 
    623 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
    624 void
    625 sched_unlock_idle(void)
    626 {
    627 
    628 	simple_unlock(&sched_lock);
    629 }
    630 
    631 void
    632 sched_lock_idle(void)
    633 {
    634 
    635 	simple_lock(&sched_lock);
    636 }
    637 #endif /* MULTIPROCESSOR || LOCKDEBUG */
    638 
    639 /*
    640  * Make all processes sleeping on the specified identifier runnable.
    641  */
    642 
    643 void
    644 wakeup(void *ident)
    645 {
    646 	int s;
    647 
    648 	SCHED_ASSERT_UNLOCKED();
    649 
    650 	SCHED_LOCK(s);
    651 	sched_wakeup(ident);
    652 	SCHED_UNLOCK(s);
    653 }
    654 
    655 void
    656 sched_wakeup(void *ident)
    657 {
    658 	struct slpque *qp;
    659 	struct lwp *l, **q;
    660 
    661 	SCHED_ASSERT_LOCKED();
    662 
    663 	qp = SLPQUE(ident);
    664  restart:
    665 	for (q = &qp->sq_head; (l = *q) != NULL; ) {
    666 #ifdef DIAGNOSTIC
    667 		if (l->l_back || (l->l_stat != LSSLEEP &&
    668 		    l->l_stat != LSSTOP && l->l_stat != LSSUSPENDED))
    669 			panic("wakeup");
    670 #endif
    671 		if (l->l_wchan == ident) {
    672 			l->l_wchan = 0;
    673 			*q = l->l_forw;
    674 			if (qp->sq_tailp == &l->l_forw)
    675 				qp->sq_tailp = q;
    676 			if (l->l_stat == LSSLEEP) {
    677 				awaken(l);
    678 				goto restart;
    679 			}
    680 		} else
    681 			q = &l->l_forw;
    682 	}
    683 }
    684 
    685 /*
    686  * Make the highest priority process first in line on the specified
    687  * identifier runnable.
    688  */
    689 void
    690 wakeup_one(void *ident)
    691 {
    692 	struct slpque *qp;
    693 	struct lwp *l, **q;
    694 	struct lwp *best_sleepp, **best_sleepq;
    695 	struct lwp *best_stopp, **best_stopq;
    696 	int s;
    697 
    698 	best_sleepp = best_stopp = NULL;
    699 	best_sleepq = best_stopq = NULL;
    700 
    701 	SCHED_LOCK(s);
    702 
    703 	qp = SLPQUE(ident);
    704 
    705 	for (q = &qp->sq_head; (l = *q) != NULL; q = &l->l_forw) {
    706 #ifdef DIAGNOSTIC
    707 		if (l->l_back || (l->l_stat != LSSLEEP &&
    708 		    l->l_stat != LSSTOP && l->l_stat != LSSUSPENDED))
    709 			panic("wakeup_one");
    710 #endif
    711 		if (l->l_wchan == ident) {
    712 			if (l->l_stat == LSSLEEP) {
    713 				if (best_sleepp == NULL ||
    714 				    l->l_priority < best_sleepp->l_priority) {
    715 					best_sleepp = l;
    716 					best_sleepq = q;
    717 				}
    718 			} else {
    719 				if (best_stopp == NULL ||
    720 				    l->l_priority < best_stopp->l_priority) {
    721 				    	best_stopp = l;
    722 					best_stopq = q;
    723 				}
    724 			}
    725 		}
    726 	}
    727 
    728 	/*
    729 	 * Consider any SSLEEP process higher than the highest priority SSTOP
    730 	 * process.
    731 	 */
    732 	if (best_sleepp != NULL) {
    733 		l = best_sleepp;
    734 		q = best_sleepq;
    735 	} else {
    736 		l = best_stopp;
    737 		q = best_stopq;
    738 	}
    739 
    740 	if (l != NULL) {
    741 		l->l_wchan = NULL;
    742 		*q = l->l_forw;
    743 		if (qp->sq_tailp == &l->l_forw)
    744 			qp->sq_tailp = q;
    745 		if (l->l_stat == LSSLEEP)
    746 			awaken(l);
    747 	}
    748 	SCHED_UNLOCK(s);
    749 }
    750 
    751 /*
    752  * General yield call.  Puts the current process back on its run queue and
    753  * performs a voluntary context switch.  Should only be called when the
    754  * current process explicitly requests it (eg sched_yield(2) in compat code).
    755  */
    756 void
    757 yield(void)
    758 {
    759 	struct lwp *l = curlwp;
    760 	int s;
    761 
    762 	SCHED_LOCK(s);
    763 	l->l_priority = l->l_usrpri;
    764 	l->l_stat = LSRUN;
    765 	setrunqueue(l);
    766 	l->l_proc->p_stats->p_ru.ru_nvcsw++;
    767 	mi_switch(l, NULL);
    768 	SCHED_ASSERT_UNLOCKED();
    769 	splx(s);
    770 }
    771 
    772 /*
    773  * General preemption call.  Puts the current process back on its run queue
    774  * and performs an involuntary context switch.  If a process is supplied,
    775  * we switch to that process.  Otherwise, we use the normal process selection
    776  * criteria.
    777  */
    778 
    779 void
    780 preempt(struct lwp *newl)
    781 {
    782 	struct lwp *l = curlwp;
    783 	int r, s;
    784 
    785 	if (l->l_flag & L_SA) {
    786 		SCHED_LOCK(s);
    787 		l->l_priority = l->l_usrpri;
    788 		l->l_stat = LSRUN;
    789 		setrunqueue(l);
    790 		l->l_proc->p_stats->p_ru.ru_nivcsw++;
    791 		r = mi_switch(l, newl);
    792 		SCHED_ASSERT_UNLOCKED();
    793 		splx(s);
    794 		if (r != 0)
    795 			sa_preempt(l);
    796 	} else {
    797 		SCHED_LOCK(s);
    798 		l->l_priority = l->l_usrpri;
    799 		l->l_stat = LSRUN;
    800 		setrunqueue(l);
    801 		l->l_proc->p_stats->p_ru.ru_nivcsw++;
    802 		mi_switch(l, newl);
    803 		SCHED_ASSERT_UNLOCKED();
    804 		splx(s);
    805 	}
    806 
    807 }
    808 
    809 /*
    810  * The machine independent parts of context switch.
    811  * Must be called at splsched() (no higher!) and with
    812  * the sched_lock held.
    813  * Switch to "new" if non-NULL, otherwise let cpu_switch choose
    814  * the next lwp.
    815  *
    816  * Returns 1 if another process was actually run.
    817  */
    818 int
    819 mi_switch(struct lwp *l, struct lwp *newl)
    820 {
    821 	struct schedstate_percpu *spc;
    822 	struct rlimit *rlim;
    823 	long s, u;
    824 	struct timeval tv;
    825 #if defined(MULTIPROCESSOR)
    826 	int hold_count;
    827 #endif
    828 	struct proc *p = l->l_proc;
    829 	int retval;
    830 
    831 	SCHED_ASSERT_LOCKED();
    832 
    833 #if defined(MULTIPROCESSOR)
    834 	/*
    835 	 * Release the kernel_lock, as we are about to yield the CPU.
    836 	 * The scheduler lock is still held until cpu_switch()
    837 	 * selects a new process and removes it from the run queue.
    838 	 */
    839 	if (l->l_flag & L_BIGLOCK)
    840 		hold_count = spinlock_release_all(&kernel_lock);
    841 #endif
    842 
    843 	KDASSERT(l->l_cpu != NULL);
    844 	KDASSERT(l->l_cpu == curcpu());
    845 
    846 	spc = &l->l_cpu->ci_schedstate;
    847 
    848 #if defined(LOCKDEBUG) || defined(DIAGNOSTIC)
    849 	spinlock_switchcheck();
    850 #endif
    851 #ifdef LOCKDEBUG
    852 	simple_lock_switchcheck();
    853 #endif
    854 
    855 	/*
    856 	 * Compute the amount of time during which the current
    857 	 * process was running.
    858 	 */
    859 	microtime(&tv);
    860 	u = p->p_rtime.tv_usec +
    861 	    (tv.tv_usec - spc->spc_runtime.tv_usec);
    862 	s = p->p_rtime.tv_sec + (tv.tv_sec - spc->spc_runtime.tv_sec);
    863 	if (u < 0) {
    864 		u += 1000000;
    865 		s--;
    866 	} else if (u >= 1000000) {
    867 		u -= 1000000;
    868 		s++;
    869 	}
    870 	p->p_rtime.tv_usec = u;
    871 	p->p_rtime.tv_sec = s;
    872 
    873 	/*
    874 	 * Check if the process exceeds its cpu resource allocation.
    875 	 * If over max, kill it.  In any case, if it has run for more
    876 	 * than 10 minutes, reduce priority to give others a chance.
    877 	 */
    878 	rlim = &p->p_rlimit[RLIMIT_CPU];
    879 	if (s >= rlim->rlim_cur) {
    880 		/*
    881 		 * XXXSMP: we're inside the scheduler lock perimeter;
    882 		 * use sched_psignal.
    883 		 */
    884 		if (s >= rlim->rlim_max)
    885 			sched_psignal(p, SIGKILL);
    886 		else {
    887 			sched_psignal(p, SIGXCPU);
    888 			if (rlim->rlim_cur < rlim->rlim_max)
    889 				rlim->rlim_cur += 5;
    890 		}
    891 	}
    892 	if (autonicetime && s > autonicetime && p->p_ucred->cr_uid &&
    893 	    p->p_nice == NZERO) {
    894 		p->p_nice = autoniceval + NZERO;
    895 		resetpriority(l);
    896 	}
    897 
    898 	/*
    899 	 * Process is about to yield the CPU; clear the appropriate
    900 	 * scheduling flags.
    901 	 */
    902 	spc->spc_flags &= ~SPCF_SWITCHCLEAR;
    903 
    904 #ifdef KSTACK_CHECK_MAGIC
    905 	kstack_check_magic(p);
    906 #endif
    907 
    908 	/*
    909 	 * If we are using h/w performance counters, save context.
    910 	 */
    911 #if PERFCTRS
    912 	if (PMC_ENABLED(p))
    913 		pmc_save_context(p);
    914 #endif
    915 
    916 	/*
    917 	 * Switch to the new current process.  When we
    918 	 * run again, we'll return back here.
    919 	 */
    920 	uvmexp.swtch++;
    921 	if (newl == NULL) {
    922 		retval = cpu_switch(l, NULL);
    923 	} else {
    924 		remrunqueue(newl);
    925 		cpu_switchto(l, newl);
    926 		retval = 0;
    927 	}
    928 
    929 	/*
    930 	 * If we are using h/w performance counters, restore context.
    931 	 */
    932 #if PERFCTRS
    933 	if (PMC_ENABLED(p))
    934 		pmc_restore_context(p);
    935 #endif
    936 
    937 	/*
    938 	 * Make sure that MD code released the scheduler lock before
    939 	 * resuming us.
    940 	 */
    941 	SCHED_ASSERT_UNLOCKED();
    942 
    943 	/*
    944 	 * We're running again; record our new start time.  We might
    945 	 * be running on a new CPU now, so don't use the cache'd
    946 	 * schedstate_percpu pointer.
    947 	 */
    948 	KDASSERT(l->l_cpu != NULL);
    949 	KDASSERT(l->l_cpu == curcpu());
    950 	microtime(&l->l_cpu->ci_schedstate.spc_runtime);
    951 
    952 #if defined(MULTIPROCESSOR)
    953 	/*
    954 	 * Reacquire the kernel_lock now.  We do this after we've
    955 	 * released the scheduler lock to avoid deadlock, and before
    956 	 * we reacquire the interlock.
    957 	 */
    958 	if (l->l_flag & L_BIGLOCK)
    959 		spinlock_acquire_count(&kernel_lock, hold_count);
    960 #endif
    961 
    962 	return retval;
    963 }
    964 
    965 /*
    966  * Initialize the (doubly-linked) run queues
    967  * to be empty.
    968  */
    969 void
    970 rqinit()
    971 {
    972 	int i;
    973 
    974 	for (i = 0; i < RUNQUE_NQS; i++)
    975 		sched_qs[i].ph_link = sched_qs[i].ph_rlink =
    976 		    (struct lwp *)&sched_qs[i];
    977 }
    978 
    979 static __inline void
    980 resched_proc(struct lwp *l)
    981 {
    982 	struct cpu_info *ci;
    983 
    984 	/*
    985 	 * XXXSMP
    986 	 * Since l->l_cpu persists across a context switch,
    987 	 * this gives us *very weak* processor affinity, in
    988 	 * that we notify the CPU on which the process last
    989 	 * ran that it should try to switch.
    990 	 *
    991 	 * This does not guarantee that the process will run on
    992 	 * that processor next, because another processor might
    993 	 * grab it the next time it performs a context switch.
    994 	 *
    995 	 * This also does not handle the case where its last
    996 	 * CPU is running a higher-priority process, but every
    997 	 * other CPU is running a lower-priority process.  There
    998 	 * are ways to handle this situation, but they're not
    999 	 * currently very pretty, and we also need to weigh the
   1000 	 * cost of moving a process from one CPU to another.
   1001 	 *
   1002 	 * XXXSMP
   1003 	 * There is also the issue of locking the other CPU's
   1004 	 * sched state, which we currently do not do.
   1005 	 */
   1006 	ci = (l->l_cpu != NULL) ? l->l_cpu : curcpu();
   1007 	if (l->l_priority < ci->ci_schedstate.spc_curpriority)
   1008 		need_resched(ci);
   1009 }
   1010 
   1011 /*
   1012  * Change process state to be runnable,
   1013  * placing it on the run queue if it is in memory,
   1014  * and awakening the swapper if it isn't in memory.
   1015  */
   1016 void
   1017 setrunnable(struct lwp *l)
   1018 {
   1019 	struct proc *p = l->l_proc;
   1020 
   1021 	SCHED_ASSERT_LOCKED();
   1022 
   1023 	switch (l->l_stat) {
   1024 	case 0:
   1025 	case LSRUN:
   1026 	case LSONPROC:
   1027 	case LSZOMB:
   1028 	case LSDEAD:
   1029 	default:
   1030 		panic("setrunnable");
   1031 	case LSSTOP:
   1032 		/*
   1033 		 * If we're being traced (possibly because someone attached us
   1034 		 * while we were stopped), check for a signal from the debugger.
   1035 		 */
   1036 		if ((p->p_flag & P_TRACED) != 0 && p->p_xstat != 0) {
   1037 			sigaddset(&p->p_sigctx.ps_siglist, p->p_xstat);
   1038 			CHECKSIGS(p);
   1039 		}
   1040 	case LSSLEEP:
   1041 		unsleep(l);		/* e.g. when sending signals */
   1042 		break;
   1043 
   1044 	case LSIDL:
   1045 		break;
   1046 	case LSSUSPENDED:
   1047 		break;
   1048 	}
   1049 	l->l_stat = LSRUN;
   1050 	p->p_nrlwps++;
   1051 
   1052 	if (l->l_flag & L_INMEM)
   1053 		setrunqueue(l);
   1054 
   1055 	if (l->l_slptime > 1)
   1056 		updatepri(l);
   1057 	l->l_slptime = 0;
   1058 	if ((l->l_flag & L_INMEM) == 0)
   1059 		sched_wakeup((caddr_t)&proc0);
   1060 	else
   1061 		resched_proc(l);
   1062 }
   1063 
   1064 /*
   1065  * Compute the priority of a process when running in user mode.
   1066  * Arrange to reschedule if the resulting priority is better
   1067  * than that of the current process.
   1068  */
   1069 void
   1070 resetpriority(struct lwp *l)
   1071 {
   1072 	unsigned int newpriority;
   1073 	struct proc *p = l->l_proc;
   1074 
   1075 	SCHED_ASSERT_LOCKED();
   1076 
   1077 	newpriority = PUSER + p->p_estcpu +
   1078 			NICE_WEIGHT * (p->p_nice - NZERO);
   1079 	newpriority = min(newpriority, MAXPRI);
   1080 	l->l_usrpri = newpriority;
   1081 	resched_proc(l);
   1082 }
   1083 
   1084 /*
   1085  * Recompute priority for all LWPs in a process.
   1086  */
   1087 void
   1088 resetprocpriority(struct proc *p)
   1089 {
   1090 	struct lwp *l;
   1091 
   1092 	LIST_FOREACH(l, &p->p_lwps, l_sibling)
   1093 	    resetpriority(l);
   1094 }
   1095 
   1096 /*
   1097  * We adjust the priority of the current process.  The priority of a process
   1098  * gets worse as it accumulates CPU time.  The cpu usage estimator (p_estcpu)
   1099  * is increased here.  The formula for computing priorities (in kern_synch.c)
   1100  * will compute a different value each time p_estcpu increases. This can
   1101  * cause a switch, but unless the priority crosses a PPQ boundary the actual
   1102  * queue will not change.  The cpu usage estimator ramps up quite quickly
   1103  * when the process is running (linearly), and decays away exponentially, at
   1104  * a rate which is proportionally slower when the system is busy.  The basic
   1105  * principle is that the system will 90% forget that the process used a lot
   1106  * of CPU time in 5 * loadav seconds.  This causes the system to favor
   1107  * processes which haven't run much recently, and to round-robin among other
   1108  * processes.
   1109  */
   1110 
   1111 void
   1112 schedclock(struct lwp *l)
   1113 {
   1114 	struct proc *p = l->l_proc;
   1115 	int s;
   1116 
   1117 	p->p_estcpu = ESTCPULIM(p->p_estcpu + 1);
   1118 	SCHED_LOCK(s);
   1119 	resetpriority(l);
   1120 	SCHED_UNLOCK(s);
   1121 
   1122 	if (l->l_priority >= PUSER)
   1123 		l->l_priority = l->l_usrpri;
   1124 }
   1125 
   1126 void
   1127 suspendsched()
   1128 {
   1129 	struct lwp *l;
   1130 	int s;
   1131 
   1132 	/*
   1133 	 * Convert all non-P_SYSTEM LSSLEEP or LSRUN processes to
   1134 	 * LSSUSPENDED.
   1135 	 */
   1136 	proclist_lock_read();
   1137 	SCHED_LOCK(s);
   1138 	LIST_FOREACH(l, &alllwp, l_list) {
   1139 		if ((l->l_proc->p_flag & P_SYSTEM) != 0)
   1140 			continue;
   1141 
   1142 		switch (l->l_stat) {
   1143 		case LSRUN:
   1144 			l->l_proc->p_nrlwps--;
   1145 			if ((l->l_flag & L_INMEM) != 0)
   1146 				remrunqueue(l);
   1147 			/* FALLTHROUGH */
   1148 		case LSSLEEP:
   1149 			l->l_stat = LSSUSPENDED;
   1150 			break;
   1151 		case LSONPROC:
   1152 			/*
   1153 			 * XXX SMP: we need to deal with processes on
   1154 			 * others CPU !
   1155 			 */
   1156 			break;
   1157 		default:
   1158 			break;
   1159 		}
   1160 	}
   1161 	SCHED_UNLOCK(s);
   1162 	proclist_unlock_read();
   1163 }
   1164 
   1165 /*
   1166  * Low-level routines to access the run queue.  Optimised assembler
   1167  * routines can override these.
   1168  */
   1169 
   1170 #ifndef __HAVE_MD_RUNQUEUE
   1171 
   1172 /*
   1173  * The primitives that manipulate the run queues.  whichqs tells which
   1174  * of the 32 queues qs have processes in them.  Setrunqueue puts processes
   1175  * into queues, remrunqueue removes them from queues.  The running process is
   1176  * on no queue, other processes are on a queue related to p->p_priority,
   1177  * divided by 4 actually to shrink the 0-127 range of priorities into the 32
   1178  * available queues.
   1179  */
   1180 
   1181 void
   1182 setrunqueue(struct lwp *l)
   1183 {
   1184 	struct prochd *rq;
   1185 	struct lwp *prev;
   1186 	int whichq;
   1187 
   1188 #ifdef DIAGNOSTIC
   1189 	if (l->l_back != NULL || l->l_wchan != NULL || l->l_stat != LSRUN)
   1190 		panic("setrunqueue");
   1191 #endif
   1192 	whichq = l->l_priority / 4;
   1193 	sched_whichqs |= (1<<whichq);
   1194 	rq = &sched_qs[whichq];
   1195 	prev = rq->ph_rlink;
   1196 	l->l_forw = (struct lwp *)rq;
   1197 	rq->ph_rlink = l;
   1198 	prev->l_forw = l;
   1199 	l->l_back = prev;
   1200 }
   1201 
   1202 void
   1203 remrunqueue(struct lwp *l)
   1204 {
   1205 	struct lwp *prev, *next;
   1206 	int whichq;
   1207 
   1208 	whichq = l->l_priority / 4;
   1209 #ifdef DIAGNOSTIC
   1210 	if (((sched_whichqs & (1<<whichq)) == 0))
   1211 		panic("remrunqueue");
   1212 #endif
   1213 	prev = l->l_back;
   1214 	l->l_back = NULL;
   1215 	next = l->l_forw;
   1216 	prev->l_forw = next;
   1217 	next->l_back = prev;
   1218 	if (prev == next)
   1219 		sched_whichqs &= ~(1<<whichq);
   1220 }
   1221 
   1222 #endif
   1223