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