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