Home | History | Annotate | Line # | Download | only in kern
kern_synch.c revision 1.74
      1 /*	$NetBSD: kern_synch.c,v 1.74 2000/05/27 00:40:46 sommerfeld 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 
     83 #include <sys/param.h>
     84 #include <sys/systm.h>
     85 #include <sys/callout.h>
     86 #include <sys/proc.h>
     87 #include <sys/kernel.h>
     88 #include <sys/buf.h>
     89 #include <sys/signalvar.h>
     90 #include <sys/resourcevar.h>
     91 #include <vm/vm.h>
     92 #include <sys/sched.h>
     93 
     94 #include <uvm/uvm_extern.h>
     95 
     96 #ifdef KTRACE
     97 #include <sys/ktrace.h>
     98 #endif
     99 
    100 #include <machine/cpu.h>
    101 
    102 int	lbolt;			/* once a second sleep address */
    103 
    104 /*
    105  * The global scheduler state.
    106  */
    107 struct prochd sched_qs[RUNQUE_NQS];	/* run queues */
    108 __volatile u_int32_t sched_whichqs;	/* bitmap of non-empty queues */
    109 struct slpque sched_slpque[SLPQUE_TABLESIZE]; /* sleep queues */
    110 
    111 void roundrobin __P((void *));
    112 void schedcpu __P((void *));
    113 void updatepri __P((struct proc *));
    114 void endtsleep __P((void *));
    115 
    116 __inline void awaken __P((struct proc *));
    117 
    118 struct callout roundrobin_ch = CALLOUT_INITIALIZER;
    119 struct callout schedcpu_ch = CALLOUT_INITIALIZER;
    120 
    121 /*
    122  * Force switch among equal priority processes every 100ms.
    123  */
    124 /* ARGSUSED */
    125 void
    126 roundrobin(arg)
    127 	void *arg;
    128 {
    129 	struct schedstate_percpu *spc = &curcpu()->ci_schedstate;
    130 	int s;
    131 
    132 	if (curproc != NULL) {
    133 		s = splstatclock();
    134 		if (spc->spc_flags & SPCF_SEENRR) {
    135 			/*
    136 			 * The process has already been through a roundrobin
    137 			 * without switching and may be hogging the CPU.
    138 			 * Indicate that the process should yield.
    139 			 */
    140 			spc->spc_flags |= SPCF_SHOULDYIELD;
    141 		} else
    142 			spc->spc_flags |= SPCF_SEENRR;
    143 		splx(s);
    144 	}
    145 	need_resched();
    146 	callout_reset(&roundrobin_ch, hz / 10, roundrobin, NULL);
    147 }
    148 
    149 /*
    150  * Constants for digital decay and forget:
    151  *	90% of (p_estcpu) usage in 5 * loadav time
    152  *	95% of (p_pctcpu) usage in 60 seconds (load insensitive)
    153  *          Note that, as ps(1) mentions, this can let percentages
    154  *          total over 100% (I've seen 137.9% for 3 processes).
    155  *
    156  * Note that hardclock updates p_estcpu and p_cpticks independently.
    157  *
    158  * We wish to decay away 90% of p_estcpu in (5 * loadavg) seconds.
    159  * That is, the system wants to compute a value of decay such
    160  * that the following for loop:
    161  * 	for (i = 0; i < (5 * loadavg); i++)
    162  * 		p_estcpu *= decay;
    163  * will compute
    164  * 	p_estcpu *= 0.1;
    165  * for all values of loadavg:
    166  *
    167  * Mathematically this loop can be expressed by saying:
    168  * 	decay ** (5 * loadavg) ~= .1
    169  *
    170  * The system computes decay as:
    171  * 	decay = (2 * loadavg) / (2 * loadavg + 1)
    172  *
    173  * We wish to prove that the system's computation of decay
    174  * will always fulfill the equation:
    175  * 	decay ** (5 * loadavg) ~= .1
    176  *
    177  * If we compute b as:
    178  * 	b = 2 * loadavg
    179  * then
    180  * 	decay = b / (b + 1)
    181  *
    182  * We now need to prove two things:
    183  *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
    184  *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
    185  *
    186  * Facts:
    187  *         For x close to zero, exp(x) =~ 1 + x, since
    188  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
    189  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
    190  *         For x close to zero, ln(1+x) =~ x, since
    191  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
    192  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
    193  *         ln(.1) =~ -2.30
    194  *
    195  * Proof of (1):
    196  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
    197  *	solving for factor,
    198  *      ln(factor) =~ (-2.30/5*loadav), or
    199  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
    200  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
    201  *
    202  * Proof of (2):
    203  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
    204  *	solving for power,
    205  *      power*ln(b/(b+1)) =~ -2.30, or
    206  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
    207  *
    208  * Actual power values for the implemented algorithm are as follows:
    209  *      loadav: 1       2       3       4
    210  *      power:  5.68    10.32   14.94   19.55
    211  */
    212 
    213 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
    214 #define	loadfactor(loadav)	(2 * (loadav))
    215 #define	decay_cpu(loadfac, cpu)	(((loadfac) * (cpu)) / ((loadfac) + FSCALE))
    216 
    217 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
    218 fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;		/* exp(-1/20) */
    219 
    220 /*
    221  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
    222  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
    223  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
    224  *
    225  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
    226  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
    227  *
    228  * If you dont want to bother with the faster/more-accurate formula, you
    229  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
    230  * (more general) method of calculating the %age of CPU used by a process.
    231  */
    232 #define	CCPU_SHIFT	11
    233 
    234 /*
    235  * Recompute process priorities, every hz ticks.
    236  */
    237 /* ARGSUSED */
    238 void
    239 schedcpu(arg)
    240 	void *arg;
    241 {
    242 	fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
    243 	struct proc *p;
    244 	int s;
    245 	unsigned int newcpu;
    246 	int clkhz;
    247 
    248 	proclist_lock_read();
    249 	for (p = allproc.lh_first; p != 0; p = p->p_list.le_next) {
    250 		/*
    251 		 * Increment time in/out of memory and sleep time
    252 		 * (if sleeping).  We ignore overflow; with 16-bit int's
    253 		 * (remember them?) overflow takes 45 days.
    254 		 */
    255 		p->p_swtime++;
    256 		if (p->p_stat == SSLEEP || p->p_stat == SSTOP)
    257 			p->p_slptime++;
    258 		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
    259 		/*
    260 		 * If the process has slept the entire second,
    261 		 * stop recalculating its priority until it wakes up.
    262 		 */
    263 		if (p->p_slptime > 1)
    264 			continue;
    265 		s = splstatclock();	/* prevent state changes */
    266 		/*
    267 		 * p_pctcpu is only for ps.
    268 		 */
    269 		clkhz = stathz != 0 ? stathz : hz;
    270 #if	(FSHIFT >= CCPU_SHIFT)
    271 		p->p_pctcpu += (clkhz == 100)?
    272 			((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT):
    273                 	100 * (((fixpt_t) p->p_cpticks)
    274 				<< (FSHIFT - CCPU_SHIFT)) / clkhz;
    275 #else
    276 		p->p_pctcpu += ((FSCALE - ccpu) *
    277 			(p->p_cpticks * FSCALE / clkhz)) >> FSHIFT;
    278 #endif
    279 		p->p_cpticks = 0;
    280 		newcpu = (u_int)decay_cpu(loadfac, p->p_estcpu);
    281 		p->p_estcpu = newcpu;
    282 		resetpriority(p);
    283 		if (p->p_priority >= PUSER) {
    284 			if (p->p_stat == SRUN &&
    285 			    (p->p_flag & P_INMEM) &&
    286 			    (p->p_priority / PPQ) != (p->p_usrpri / PPQ)) {
    287 				remrunqueue(p);
    288 				p->p_priority = p->p_usrpri;
    289 				setrunqueue(p);
    290 			} else
    291 				p->p_priority = p->p_usrpri;
    292 		}
    293 		splx(s);
    294 	}
    295 	proclist_unlock_read();
    296 	uvm_meter();
    297 	wakeup((caddr_t)&lbolt);
    298 	callout_reset(&schedcpu_ch, hz, schedcpu, NULL);
    299 }
    300 
    301 /*
    302  * Recalculate the priority of a process after it has slept for a while.
    303  * For all load averages >= 1 and max p_estcpu of 255, sleeping for at
    304  * least six times the loadfactor will decay p_estcpu to zero.
    305  */
    306 void
    307 updatepri(p)
    308 	struct proc *p;
    309 {
    310 	unsigned int newcpu = p->p_estcpu;
    311 	fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
    312 
    313 	if (p->p_slptime > 5 * loadfac)
    314 		p->p_estcpu = 0;
    315 	else {
    316 		p->p_slptime--;	/* the first time was done in schedcpu */
    317 		while (newcpu && --p->p_slptime)
    318 			newcpu = (int) decay_cpu(loadfac, newcpu);
    319 		p->p_estcpu = newcpu;
    320 	}
    321 	resetpriority(p);
    322 }
    323 
    324 /*
    325  * During autoconfiguration or after a panic, a sleep will simply
    326  * lower the priority briefly to allow interrupts, then return.
    327  * The priority to be used (safepri) is machine-dependent, thus this
    328  * value is initialized and maintained in the machine-dependent layers.
    329  * This priority will typically be 0, or the lowest priority
    330  * that is safe for use on the interrupt stack; it can be made
    331  * higher to block network software interrupts after panics.
    332  */
    333 int safepri;
    334 
    335 /*
    336  * General sleep call.  Suspends the current process until a wakeup is
    337  * performed on the specified identifier.  The process will then be made
    338  * runnable with the specified priority.  Sleeps at most timo/hz seconds
    339  * (0 means no timeout).  If pri includes PCATCH flag, signals are checked
    340  * before and after sleeping, else signals are not checked.  Returns 0 if
    341  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
    342  * signal needs to be delivered, ERESTART is returned if the current system
    343  * call should be restarted if possible, and EINTR is returned if the system
    344  * call should be interrupted by the signal (return EINTR).
    345  */
    346 int
    347 tsleep(ident, priority, wmesg, timo)
    348 	void *ident;
    349 	int priority, timo;
    350 	const char *wmesg;
    351 {
    352 	struct proc *p = curproc;
    353 	struct slpque *qp;
    354 	int s;
    355 	int sig, catch = priority & PCATCH;
    356 
    357 	if (cold || panicstr) {
    358 		/*
    359 		 * After a panic, or during autoconfiguration,
    360 		 * just give interrupts a chance, then just return;
    361 		 * don't run any other procs or panic below,
    362 		 * in case this is the idle process and already asleep.
    363 		 */
    364 		s = splhigh();
    365 		splx(safepri);
    366 		splx(s);
    367 		return (0);
    368 	}
    369 
    370 #ifdef KTRACE
    371 	if (KTRPOINT(p, KTR_CSW))
    372 		ktrcsw(p, 1, 0);
    373 #endif
    374 	s = splhigh();
    375 
    376 #ifdef DIAGNOSTIC
    377 	if (ident == NULL)
    378 		panic("tsleep: ident == NULL");
    379 	if (p->p_stat != SONPROC)
    380 		panic("tsleep: p_stat %d != SONPROC", p->p_stat);
    381 	if (p->p_back != NULL)
    382 		panic("tsleep: p_back != NULL");
    383 #endif
    384 	p->p_wchan = ident;
    385 	p->p_wmesg = wmesg;
    386 	p->p_slptime = 0;
    387 	p->p_priority = priority & PRIMASK;
    388 	qp = SLPQUE(ident);
    389 	if (qp->sq_head == 0)
    390 		qp->sq_head = p;
    391 	else
    392 		*qp->sq_tailp = p;
    393 	*(qp->sq_tailp = &p->p_forw) = 0;
    394 	if (timo)
    395 		callout_reset(&p->p_tsleep_ch, timo, endtsleep, p);
    396 	/*
    397 	 * We put ourselves on the sleep queue and start our timeout
    398 	 * before calling CURSIG, as we could stop there, and a wakeup
    399 	 * or a SIGCONT (or both) could occur while we were stopped.
    400 	 * A SIGCONT would cause us to be marked as SSLEEP
    401 	 * without resuming us, thus we must be ready for sleep
    402 	 * when CURSIG is called.  If the wakeup happens while we're
    403 	 * stopped, p->p_wchan will be 0 upon return from CURSIG.
    404 	 */
    405 	if (catch) {
    406 		p->p_flag |= P_SINTR;
    407 		if ((sig = CURSIG(p)) != 0) {
    408 			if (p->p_wchan)
    409 				unsleep(p);
    410 			p->p_stat = SONPROC;
    411 			goto resume;
    412 		}
    413 		if (p->p_wchan == 0) {
    414 			catch = 0;
    415 			goto resume;
    416 		}
    417 	} else
    418 		sig = 0;
    419 	p->p_stat = SSLEEP;
    420 	p->p_stats->p_ru.ru_nvcsw++;
    421 	mi_switch(p);
    422 #ifdef	DDB
    423 	/* handy breakpoint location after process "wakes" */
    424 	asm(".globl bpendtsleep ; bpendtsleep:");
    425 #endif
    426 resume:
    427 	curcpu()->ci_schedstate.spc_curpriority = p->p_usrpri;
    428 	splx(s);
    429 	p->p_flag &= ~P_SINTR;
    430 	if (p->p_flag & P_TIMEOUT) {
    431 		p->p_flag &= ~P_TIMEOUT;
    432 		if (sig == 0) {
    433 #ifdef KTRACE
    434 			if (KTRPOINT(p, KTR_CSW))
    435 				ktrcsw(p, 0, 0);
    436 #endif
    437 			return (EWOULDBLOCK);
    438 		}
    439 	} else if (timo)
    440 		callout_stop(&p->p_tsleep_ch);
    441 	if (catch && (sig != 0 || (sig = CURSIG(p)) != 0)) {
    442 #ifdef KTRACE
    443 		if (KTRPOINT(p, KTR_CSW))
    444 			ktrcsw(p, 0, 0);
    445 #endif
    446 		if ((p->p_sigacts->ps_sigact[sig].sa_flags & SA_RESTART) == 0)
    447 			return (EINTR);
    448 		return (ERESTART);
    449 	}
    450 #ifdef KTRACE
    451 	if (KTRPOINT(p, KTR_CSW))
    452 		ktrcsw(p, 0, 0);
    453 #endif
    454 	return (0);
    455 }
    456 
    457 /*
    458  * Implement timeout for tsleep.
    459  * If process hasn't been awakened (wchan non-zero),
    460  * set timeout flag and undo the sleep.  If proc
    461  * is stopped, just unsleep so it will remain stopped.
    462  */
    463 void
    464 endtsleep(arg)
    465 	void *arg;
    466 {
    467 	struct proc *p;
    468 	int s;
    469 
    470 	p = (struct proc *)arg;
    471 	s = splhigh();
    472 	if (p->p_wchan) {
    473 		if (p->p_stat == SSLEEP)
    474 			setrunnable(p);
    475 		else
    476 			unsleep(p);
    477 		p->p_flag |= P_TIMEOUT;
    478 	}
    479 	splx(s);
    480 }
    481 
    482 /*
    483  * Short-term, non-interruptable sleep.
    484  */
    485 void
    486 sleep(ident, priority)
    487 	void *ident;
    488 	int priority;
    489 {
    490 	struct proc *p = curproc;
    491 	struct slpque *qp;
    492 	int s;
    493 
    494 #ifdef DIAGNOSTIC
    495 	if (priority > PZERO) {
    496 		printf("sleep called with priority %d > PZERO, wchan: %p\n",
    497 		    priority, ident);
    498 		panic("old sleep");
    499 	}
    500 #endif
    501 	s = splhigh();
    502 	if (cold || panicstr) {
    503 		/*
    504 		 * After a panic, or during autoconfiguration,
    505 		 * just give interrupts a chance, then just return;
    506 		 * don't run any other procs or panic below,
    507 		 * in case this is the idle process and already asleep.
    508 		 */
    509 		splx(safepri);
    510 		splx(s);
    511 		return;
    512 	}
    513 #ifdef DIAGNOSTIC
    514 	if (ident == NULL || p->p_stat != SONPROC || p->p_back)
    515 		panic("sleep");
    516 #endif
    517 	p->p_wchan = ident;
    518 	p->p_wmesg = NULL;
    519 	p->p_slptime = 0;
    520 	p->p_priority = priority;
    521 	qp = SLPQUE(ident);
    522 	if (qp->sq_head == 0)
    523 		qp->sq_head = p;
    524 	else
    525 		*qp->sq_tailp = p;
    526 	*(qp->sq_tailp = &p->p_forw) = 0;
    527 	p->p_stat = SSLEEP;
    528 	p->p_stats->p_ru.ru_nvcsw++;
    529 #ifdef KTRACE
    530 	if (KTRPOINT(p, KTR_CSW))
    531 		ktrcsw(p, 1, 0);
    532 #endif
    533 	mi_switch(p);
    534 #ifdef	DDB
    535 	/* handy breakpoint location after process "wakes" */
    536 	asm(".globl bpendsleep ; bpendsleep:");
    537 #endif
    538 #ifdef KTRACE
    539 	if (KTRPOINT(p, KTR_CSW))
    540 		ktrcsw(p, 0, 0);
    541 #endif
    542 	curcpu()->ci_schedstate.spc_curpriority = p->p_usrpri;
    543 	splx(s);
    544 }
    545 
    546 /*
    547  * Remove a process from its wait queue
    548  */
    549 void
    550 unsleep(p)
    551 	struct proc *p;
    552 {
    553 	struct slpque *qp;
    554 	struct proc **hp;
    555 	int s;
    556 
    557 	s = splhigh();
    558 	if (p->p_wchan) {
    559 		hp = &(qp = SLPQUE(p->p_wchan))->sq_head;
    560 		while (*hp != p)
    561 			hp = &(*hp)->p_forw;
    562 		*hp = p->p_forw;
    563 		if (qp->sq_tailp == &p->p_forw)
    564 			qp->sq_tailp = hp;
    565 		p->p_wchan = 0;
    566 	}
    567 	splx(s);
    568 }
    569 
    570 /*
    571  * Optimized-for-wakeup() version of setrunnable().
    572  */
    573 __inline void
    574 awaken(p)
    575 	struct proc *p;
    576 {
    577 
    578 	if (p->p_slptime > 1)
    579 		updatepri(p);
    580 	p->p_slptime = 0;
    581 	p->p_stat = SRUN;
    582 	/*
    583 	 * Since curpriority is a user priority, p->p_priority
    584 	 * is always better than curpriority.
    585 	 */
    586 	if (p->p_flag & P_INMEM) {
    587 		setrunqueue(p);
    588 		need_resched();
    589 	} else
    590 		wakeup((caddr_t)&proc0);
    591 }
    592 
    593 /*
    594  * Make all processes sleeping on the specified identifier runnable.
    595  */
    596 void
    597 wakeup(ident)
    598 	void *ident;
    599 {
    600 	struct slpque *qp;
    601 	struct proc *p, **q;
    602 	int s;
    603 
    604 	s = splhigh();
    605 	qp = SLPQUE(ident);
    606 restart:
    607 	for (q = &qp->sq_head; (p = *q) != NULL; ) {
    608 #ifdef DIAGNOSTIC
    609 		if (p->p_back || (p->p_stat != SSLEEP && p->p_stat != SSTOP))
    610 			panic("wakeup");
    611 #endif
    612 		if (p->p_wchan == ident) {
    613 			p->p_wchan = 0;
    614 			*q = p->p_forw;
    615 			if (qp->sq_tailp == &p->p_forw)
    616 				qp->sq_tailp = q;
    617 			if (p->p_stat == SSLEEP) {
    618 				awaken(p);
    619 				goto restart;
    620 			}
    621 		} else
    622 			q = &p->p_forw;
    623 	}
    624 	splx(s);
    625 }
    626 
    627 /*
    628  * Make the highest priority process first in line on the specified
    629  * identifier runnable.
    630  */
    631 void
    632 wakeup_one(ident)
    633 	void *ident;
    634 {
    635 	struct slpque *qp;
    636 	struct proc *p, **q;
    637 	struct proc *best_sleepp, **best_sleepq;
    638 	struct proc *best_stopp, **best_stopq;
    639 	int s;
    640 
    641 	best_sleepp = best_stopp = NULL;
    642 	best_sleepq = best_stopq = NULL;
    643 
    644 	s = splhigh();
    645 	qp = SLPQUE(ident);
    646 	for (q = &qp->sq_head; (p = *q) != NULL; q = &p->p_forw) {
    647 #ifdef DIAGNOSTIC
    648 		if (p->p_back || (p->p_stat != SSLEEP && p->p_stat != SSTOP))
    649 			panic("wakeup_one");
    650 #endif
    651 		if (p->p_wchan == ident) {
    652 			if (p->p_stat == SSLEEP) {
    653 				if (best_sleepp == NULL ||
    654 				    p->p_priority < best_sleepp->p_priority) {
    655 					best_sleepp = p;
    656 					best_sleepq = q;
    657 				}
    658 			} else {
    659 				if (best_stopp == NULL ||
    660 				    p->p_priority < best_stopp->p_priority) {
    661 					best_stopp = p;
    662 					best_stopq = q;
    663 				}
    664 			}
    665 		}
    666 	}
    667 
    668 	/*
    669 	 * Consider any SSLEEP process higher than the highest priority SSTOP
    670 	 * process.
    671 	 */
    672 	if (best_sleepp != NULL) {
    673 		p = best_sleepp;
    674 		q = best_sleepq;
    675 	} else {
    676 		p = best_stopp;
    677 		q = best_stopq;
    678 	}
    679 
    680 	if (p != NULL) {
    681 		p->p_wchan = 0;
    682 		*q = p->p_forw;
    683 		if (qp->sq_tailp == &p->p_forw)
    684 			qp->sq_tailp = q;
    685 		if (p->p_stat == SSLEEP)
    686 			awaken(p);
    687 	}
    688 	splx(s);
    689 }
    690 
    691 /*
    692  * General yield call.  Puts the current process back on its run queue and
    693  * performs a voluntary context switch.
    694  */
    695 void
    696 yield()
    697 {
    698 	struct proc *p = curproc;
    699 	int s;
    700 
    701 	s = splstatclock();
    702 	p->p_priority = p->p_usrpri;
    703 	p->p_stat = SRUN;
    704 	setrunqueue(p);
    705 	p->p_stats->p_ru.ru_nvcsw++;
    706 	mi_switch(p);
    707 	splx(s);
    708 }
    709 
    710 /*
    711  * General preemption call.  Puts the current process back on its run queue
    712  * and performs an involuntary context switch.  If a process is supplied,
    713  * we switch to that process.  Otherwise, we use the normal process selection
    714  * criteria.
    715  */
    716 void
    717 preempt(newp)
    718 	struct proc *newp;
    719 {
    720 	struct proc *p = curproc;
    721 	int s;
    722 
    723 	/*
    724 	 * XXX Switching to a specific process is not supported yet.
    725 	 */
    726 	if (newp != NULL)
    727 		panic("preempt: cpu_preempt not yet implemented");
    728 
    729 	s = splstatclock();
    730 	p->p_priority = p->p_usrpri;
    731 	p->p_stat = SRUN;
    732 	setrunqueue(p);
    733 	p->p_stats->p_ru.ru_nivcsw++;
    734 	mi_switch(p);
    735 	splx(s);
    736 }
    737 
    738 /*
    739  * The machine independent parts of context switch.
    740  * Must be called at splstatclock() or higher.
    741  */
    742 void
    743 mi_switch(p)
    744 	struct proc *p;
    745 {
    746 	struct schedstate_percpu *spc = &curcpu()->ci_schedstate;
    747 	struct rlimit *rlim;
    748 	long s, u;
    749 	struct timeval tv;
    750 
    751 #ifdef DEBUG
    752 	if (p->p_simple_locks) {
    753 		printf("p->p_simple_locks %d\n", p->p_simple_locks);
    754 #ifdef LOCKDEBUG
    755 		simple_lock_dump();
    756 #endif
    757 		panic("sleep: holding simple lock");
    758 	}
    759 #endif
    760 	/*
    761 	 * Compute the amount of time during which the current
    762 	 * process was running, and add that to its total so far.
    763 	 */
    764 	microtime(&tv);
    765 	u = p->p_rtime.tv_usec + (tv.tv_usec - spc->spc_runtime.tv_usec);
    766 	s = p->p_rtime.tv_sec + (tv.tv_sec - spc->spc_runtime.tv_sec);
    767 	if (u < 0) {
    768 		u += 1000000;
    769 		s--;
    770 	} else if (u >= 1000000) {
    771 		u -= 1000000;
    772 		s++;
    773 	}
    774 	p->p_rtime.tv_usec = u;
    775 	p->p_rtime.tv_sec = s;
    776 
    777 	/*
    778 	 * Check if the process exceeds its cpu resource allocation.
    779 	 * If over max, kill it.  In any case, if it has run for more
    780 	 * than 10 minutes, reduce priority to give others a chance.
    781 	 */
    782 	rlim = &p->p_rlimit[RLIMIT_CPU];
    783 	if (s >= rlim->rlim_cur) {
    784 		if (s >= rlim->rlim_max)
    785 			psignal(p, SIGKILL);
    786 		else {
    787 			psignal(p, SIGXCPU);
    788 			if (rlim->rlim_cur < rlim->rlim_max)
    789 				rlim->rlim_cur += 5;
    790 		}
    791 	}
    792 	if (autonicetime && s > autonicetime && p->p_ucred->cr_uid && p->p_nice == NZERO) {
    793 		p->p_nice = autoniceval + NZERO;
    794 		resetpriority(p);
    795 	}
    796 
    797 	/*
    798 	 * Process is about to yield the CPU; clear the appropriate
    799 	 * scheduling flags.
    800 	 */
    801 	spc->spc_flags &= ~SPCF_SWITCHCLEAR;
    802 
    803 	/*
    804 	 * Pick a new current process and record its start time.
    805 	 */
    806 	uvmexp.swtch++;
    807 	cpu_switch(p);
    808 	microtime(&spc->spc_runtime);
    809 }
    810 
    811 /*
    812  * Initialize the (doubly-linked) run queues
    813  * to be empty.
    814  */
    815 void
    816 rqinit()
    817 {
    818 	int i;
    819 
    820 	for (i = 0; i < RUNQUE_NQS; i++)
    821 		sched_qs[i].ph_link = sched_qs[i].ph_rlink =
    822 		    (struct proc *)&sched_qs[i];
    823 }
    824 
    825 /*
    826  * Change process state to be runnable,
    827  * placing it on the run queue if it is in memory,
    828  * and awakening the swapper if it isn't in memory.
    829  */
    830 void
    831 setrunnable(p)
    832 	struct proc *p;
    833 {
    834 	int s;
    835 
    836 	s = splhigh();
    837 	switch (p->p_stat) {
    838 	case 0:
    839 	case SRUN:
    840 	case SONPROC:
    841 	case SZOMB:
    842 	case SDEAD:
    843 	default:
    844 		panic("setrunnable");
    845 	case SSTOP:
    846 		/*
    847 		 * If we're being traced (possibly because someone attached us
    848 		 * while we were stopped), check for a signal from the debugger.
    849 		 */
    850 		if ((p->p_flag & P_TRACED) != 0 && p->p_xstat != 0) {
    851 			sigaddset(&p->p_siglist, p->p_xstat);
    852 			p->p_sigcheck = 1;
    853 		}
    854 	case SSLEEP:
    855 		unsleep(p);		/* e.g. when sending signals */
    856 		break;
    857 
    858 	case SIDL:
    859 		break;
    860 	}
    861 	p->p_stat = SRUN;
    862 	if (p->p_flag & P_INMEM)
    863 		setrunqueue(p);
    864 	splx(s);
    865 	if (p->p_slptime > 1)
    866 		updatepri(p);
    867 	p->p_slptime = 0;
    868 	if ((p->p_flag & P_INMEM) == 0)
    869 		wakeup((caddr_t)&proc0);
    870 	else if (p->p_priority < curcpu()->ci_schedstate.spc_curpriority)
    871 		need_resched();
    872 }
    873 
    874 /*
    875  * Compute the priority of a process when running in user mode.
    876  * Arrange to reschedule if the resulting priority is better
    877  * than that of the current process.
    878  */
    879 void
    880 resetpriority(p)
    881 	struct proc *p;
    882 {
    883 	unsigned int newpriority;
    884 
    885 	newpriority = PUSER + p->p_estcpu + NICE_WEIGHT * (p->p_nice - NZERO);
    886 	newpriority = min(newpriority, MAXPRI);
    887 	p->p_usrpri = newpriority;
    888 	if (newpriority < curcpu()->ci_schedstate.spc_curpriority)
    889 		need_resched();
    890 }
    891 
    892 /*
    893  * We adjust the priority of the current process.  The priority of a process
    894  * gets worse as it accumulates CPU time.  The cpu usage estimator (p_estcpu)
    895  * is increased here.  The formula for computing priorities (in kern_synch.c)
    896  * will compute a different value each time p_estcpu increases. This can
    897  * cause a switch, but unless the priority crosses a PPQ boundary the actual
    898  * queue will not change.  The cpu usage estimator ramps up quite quickly
    899  * when the process is running (linearly), and decays away exponentially, at
    900  * a rate which is proportionally slower when the system is busy.  The basic
    901  * principal is that the system will 90% forget that the process used a lot
    902  * of CPU time in 5 * loadav seconds.  This causes the system to favor
    903  * processes which haven't run much recently, and to round-robin among other
    904  * processes.
    905  */
    906 
    907 void
    908 schedclock(p)
    909 	struct proc *p;
    910 {
    911 	p->p_estcpu = ESTCPULIM(p->p_estcpu + 1);
    912 	resetpriority(p);
    913 	if (p->p_priority >= PUSER)
    914 		p->p_priority = p->p_usrpri;
    915 }
    916