Home | History | Annotate | Line # | Download | only in kern
kern_synch.c revision 1.215
      1 /*	$NetBSD: kern_synch.c,v 1.215 2008/01/04 21:18:10 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999, 2000, 2004, 2006, 2007 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
      9  * NASA Ames Research Center, by Charles M. Hannum, Andrew Doran and
     10  * Daniel Sieger.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. All advertising materials mentioning features or use of this software
     21  *    must display the following acknowledgement:
     22  *	This product includes software developed by the NetBSD
     23  *	Foundation, Inc. and its contributors.
     24  * 4. Neither the name of The NetBSD Foundation nor the names of its
     25  *    contributors may be used to endorse or promote products derived
     26  *    from this software without specific prior written permission.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     29  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     30  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     31  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     32  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     34  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     36  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     37  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     38  * POSSIBILITY OF SUCH DAMAGE.
     39  */
     40 
     41 /*-
     42  * Copyright (c) 1982, 1986, 1990, 1991, 1993
     43  *	The Regents of the University of California.  All rights reserved.
     44  * (c) UNIX System Laboratories, Inc.
     45  * All or some portions of this file are derived from material licensed
     46  * to the University of California by American Telephone and Telegraph
     47  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     48  * the permission of UNIX System Laboratories, Inc.
     49  *
     50  * Redistribution and use in source and binary forms, with or without
     51  * modification, are permitted provided that the following conditions
     52  * are met:
     53  * 1. Redistributions of source code must retain the above copyright
     54  *    notice, this list of conditions and the following disclaimer.
     55  * 2. Redistributions in binary form must reproduce the above copyright
     56  *    notice, this list of conditions and the following disclaimer in the
     57  *    documentation and/or other materials provided with the distribution.
     58  * 3. Neither the name of the University nor the names of its contributors
     59  *    may be used to endorse or promote products derived from this software
     60  *    without specific prior written permission.
     61  *
     62  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     63  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     64  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     65  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     66  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     67  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     68  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     69  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     70  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     71  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     72  * SUCH DAMAGE.
     73  *
     74  *	@(#)kern_synch.c	8.9 (Berkeley) 5/19/95
     75  */
     76 
     77 #include <sys/cdefs.h>
     78 __KERNEL_RCSID(0, "$NetBSD: kern_synch.c,v 1.215 2008/01/04 21:18:10 ad Exp $");
     79 
     80 #include "opt_kstack.h"
     81 #include "opt_lockdebug.h"
     82 #include "opt_multiprocessor.h"
     83 #include "opt_perfctrs.h"
     84 
     85 #define	__MUTEX_PRIVATE
     86 
     87 #include <sys/param.h>
     88 #include <sys/systm.h>
     89 #include <sys/proc.h>
     90 #include <sys/kernel.h>
     91 #if defined(PERFCTRS)
     92 #include <sys/pmc.h>
     93 #endif
     94 #include <sys/cpu.h>
     95 #include <sys/resourcevar.h>
     96 #include <sys/sched.h>
     97 #include <sys/syscall_stats.h>
     98 #include <sys/sleepq.h>
     99 #include <sys/lockdebug.h>
    100 #include <sys/evcnt.h>
    101 #include <sys/intr.h>
    102 #include <sys/lwpctl.h>
    103 #include <sys/atomic.h>
    104 #include <sys/simplelock.h>
    105 
    106 #include <uvm/uvm_extern.h>
    107 
    108 callout_t sched_pstats_ch;
    109 unsigned int sched_pstats_ticks;
    110 
    111 kcondvar_t	lbolt;			/* once a second sleep address */
    112 
    113 static void	sched_unsleep(struct lwp *);
    114 static void	sched_changepri(struct lwp *, pri_t);
    115 static void	sched_lendpri(struct lwp *, pri_t);
    116 
    117 syncobj_t sleep_syncobj = {
    118 	SOBJ_SLEEPQ_SORTED,
    119 	sleepq_unsleep,
    120 	sleepq_changepri,
    121 	sleepq_lendpri,
    122 	syncobj_noowner,
    123 };
    124 
    125 syncobj_t sched_syncobj = {
    126 	SOBJ_SLEEPQ_SORTED,
    127 	sched_unsleep,
    128 	sched_changepri,
    129 	sched_lendpri,
    130 	syncobj_noowner,
    131 };
    132 
    133 /*
    134  * During autoconfiguration or after a panic, a sleep will simply lower the
    135  * priority briefly to allow interrupts, then return.  The priority to be
    136  * used (safepri) is machine-dependent, thus this value is initialized and
    137  * maintained in the machine-dependent layers.  This priority will typically
    138  * be 0, or the lowest priority that is safe for use on the interrupt stack;
    139  * it can be made higher to block network software interrupts after panics.
    140  */
    141 int	safepri;
    142 
    143 /*
    144  * OBSOLETE INTERFACE
    145  *
    146  * General sleep call.  Suspends the current process until a wakeup is
    147  * performed on the specified identifier.  The process will then be made
    148  * runnable with the specified priority.  Sleeps at most timo/hz seconds (0
    149  * means no timeout).  If pri includes PCATCH flag, signals are checked
    150  * before and after sleeping, else signals are not checked.  Returns 0 if
    151  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
    152  * signal needs to be delivered, ERESTART is returned if the current system
    153  * call should be restarted if possible, and EINTR is returned if the system
    154  * call should be interrupted by the signal (return EINTR).
    155  *
    156  * The interlock is held until we are on a sleep queue. The interlock will
    157  * be locked before returning back to the caller unless the PNORELOCK flag
    158  * is specified, in which case the interlock will always be unlocked upon
    159  * return.
    160  */
    161 int
    162 ltsleep(wchan_t ident, pri_t priority, const char *wmesg, int timo,
    163 	volatile struct simplelock *interlock)
    164 {
    165 	struct lwp *l = curlwp;
    166 	sleepq_t *sq;
    167 	int error;
    168 
    169 	KASSERT((l->l_pflag & LP_INTR) == 0);
    170 
    171 	if (sleepq_dontsleep(l)) {
    172 		(void)sleepq_abort(NULL, 0);
    173 		if ((priority & PNORELOCK) != 0)
    174 			simple_unlock(interlock);
    175 		return 0;
    176 	}
    177 
    178 	l->l_kpriority = true;
    179 	sq = sleeptab_lookup(&sleeptab, ident);
    180 	sleepq_enter(sq, l);
    181 	sleepq_enqueue(sq, ident, wmesg, &sleep_syncobj);
    182 
    183 	if (interlock != NULL) {
    184 		KASSERT(simple_lock_held(interlock));
    185 		simple_unlock(interlock);
    186 	}
    187 
    188 	error = sleepq_block(timo, priority & PCATCH);
    189 
    190 	if (interlock != NULL && (priority & PNORELOCK) == 0)
    191 		simple_lock(interlock);
    192 
    193 	return error;
    194 }
    195 
    196 int
    197 mtsleep(wchan_t ident, pri_t priority, const char *wmesg, int timo,
    198 	kmutex_t *mtx)
    199 {
    200 	struct lwp *l = curlwp;
    201 	sleepq_t *sq;
    202 	int error;
    203 
    204 	KASSERT((l->l_pflag & LP_INTR) == 0);
    205 
    206 	if (sleepq_dontsleep(l)) {
    207 		(void)sleepq_abort(mtx, (priority & PNORELOCK) != 0);
    208 		return 0;
    209 	}
    210 
    211 	l->l_kpriority = true;
    212 	sq = sleeptab_lookup(&sleeptab, ident);
    213 	sleepq_enter(sq, l);
    214 	sleepq_enqueue(sq, ident, wmesg, &sleep_syncobj);
    215 	mutex_exit(mtx);
    216 	error = sleepq_block(timo, priority & PCATCH);
    217 
    218 	if ((priority & PNORELOCK) == 0)
    219 		mutex_enter(mtx);
    220 
    221 	return error;
    222 }
    223 
    224 /*
    225  * General sleep call for situations where a wake-up is not expected.
    226  */
    227 int
    228 kpause(const char *wmesg, bool intr, int timo, kmutex_t *mtx)
    229 {
    230 	struct lwp *l = curlwp;
    231 	sleepq_t *sq;
    232 	int error;
    233 
    234 	if (sleepq_dontsleep(l))
    235 		return sleepq_abort(NULL, 0);
    236 
    237 	if (mtx != NULL)
    238 		mutex_exit(mtx);
    239 	l->l_kpriority = true;
    240 	sq = sleeptab_lookup(&sleeptab, l);
    241 	sleepq_enter(sq, l);
    242 	sleepq_enqueue(sq, l, wmesg, &sleep_syncobj);
    243 	error = sleepq_block(timo, intr);
    244 	if (mtx != NULL)
    245 		mutex_enter(mtx);
    246 
    247 	return error;
    248 }
    249 
    250 /*
    251  * OBSOLETE INTERFACE
    252  *
    253  * Make all processes sleeping on the specified identifier runnable.
    254  */
    255 void
    256 wakeup(wchan_t ident)
    257 {
    258 	sleepq_t *sq;
    259 
    260 	if (cold)
    261 		return;
    262 
    263 	sq = sleeptab_lookup(&sleeptab, ident);
    264 	sleepq_wake(sq, ident, (u_int)-1);
    265 }
    266 
    267 /*
    268  * OBSOLETE INTERFACE
    269  *
    270  * Make the highest priority process first in line on the specified
    271  * identifier runnable.
    272  */
    273 void
    274 wakeup_one(wchan_t ident)
    275 {
    276 	sleepq_t *sq;
    277 
    278 	if (cold)
    279 		return;
    280 
    281 	sq = sleeptab_lookup(&sleeptab, ident);
    282 	sleepq_wake(sq, ident, 1);
    283 }
    284 
    285 
    286 /*
    287  * General yield call.  Puts the current process back on its run queue and
    288  * performs a voluntary context switch.  Should only be called when the
    289  * current process explicitly requests it (eg sched_yield(2)).
    290  */
    291 void
    292 yield(void)
    293 {
    294 	struct lwp *l = curlwp;
    295 
    296 	KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
    297 	lwp_lock(l);
    298 	KASSERT(lwp_locked(l, &l->l_cpu->ci_schedstate.spc_lwplock));
    299 	KASSERT(l->l_stat == LSONPROC);
    300 	l->l_kpriority = false;
    301 	if (l->l_class == SCHED_OTHER) {
    302 		/*
    303 		 * Only for timeshared threads.  It will be reset
    304 		 * by the scheduler in due course.
    305 		 */
    306 		l->l_priority = 0;
    307 	}
    308 	(void)mi_switch(l);
    309 	KERNEL_LOCK(l->l_biglocks, l);
    310 }
    311 
    312 /*
    313  * General preemption call.  Puts the current process back on its run queue
    314  * and performs an involuntary context switch.
    315  */
    316 void
    317 preempt(void)
    318 {
    319 	struct lwp *l = curlwp;
    320 
    321 	KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
    322 	lwp_lock(l);
    323 	KASSERT(lwp_locked(l, &l->l_cpu->ci_schedstate.spc_lwplock));
    324 	KASSERT(l->l_stat == LSONPROC);
    325 	l->l_kpriority = false;
    326 	l->l_nivcsw++;
    327 	(void)mi_switch(l);
    328 	KERNEL_LOCK(l->l_biglocks, l);
    329 }
    330 
    331 /*
    332  * Compute the amount of time during which the current lwp was running.
    333  *
    334  * - update l_rtime unless it's an idle lwp.
    335  */
    336 
    337 void
    338 updatertime(lwp_t *l, const struct bintime *now)
    339 {
    340 
    341 	if ((l->l_flag & LW_IDLE) != 0)
    342 		return;
    343 
    344 	/* rtime += now - stime */
    345 	bintime_add(&l->l_rtime, now);
    346 	bintime_sub(&l->l_rtime, &l->l_stime);
    347 }
    348 
    349 /*
    350  * The machine independent parts of context switch.
    351  *
    352  * Returns 1 if another LWP was actually run.
    353  */
    354 int
    355 mi_switch(lwp_t *l)
    356 {
    357 	struct schedstate_percpu *spc;
    358 	struct lwp *newl;
    359 	int retval, oldspl;
    360 	struct cpu_info *ci;
    361 	struct bintime bt;
    362 	bool returning;
    363 
    364 	KASSERT(lwp_locked(l, NULL));
    365 	LOCKDEBUG_BARRIER(l->l_mutex, 1);
    366 
    367 #ifdef KSTACK_CHECK_MAGIC
    368 	kstack_check_magic(l);
    369 #endif
    370 
    371 	binuptime(&bt);
    372 
    373 	KDASSERT(l->l_cpu == curcpu());
    374 	ci = l->l_cpu;
    375 	spc = &ci->ci_schedstate;
    376 	returning = false;
    377 	newl = NULL;
    378 
    379 	/*
    380 	 * If we have been asked to switch to a specific LWP, then there
    381 	 * is no need to inspect the run queues.  If a soft interrupt is
    382 	 * blocking, then return to the interrupted thread without adjusting
    383 	 * VM context or its start time: neither have been changed in order
    384 	 * to take the interrupt.
    385 	 */
    386 	if (l->l_switchto != NULL) {
    387 		if ((l->l_pflag & LP_INTR) != 0) {
    388 			returning = true;
    389 			softint_block(l);
    390 			if ((l->l_flag & LW_TIMEINTR) != 0)
    391 				updatertime(l, &bt);
    392 		}
    393 		newl = l->l_switchto;
    394 		l->l_switchto = NULL;
    395 	}
    396 #ifndef __HAVE_FAST_SOFTINTS
    397 	else if (ci->ci_data.cpu_softints != 0) {
    398 		/* There are pending soft interrupts, so pick one. */
    399 		newl = softint_picklwp();
    400 		newl->l_stat = LSONPROC;
    401 		newl->l_flag |= LW_RUNNING;
    402 	}
    403 #endif	/* !__HAVE_FAST_SOFTINTS */
    404 
    405 	/* Count time spent in current system call */
    406 	if (!returning) {
    407 		SYSCALL_TIME_SLEEP(l);
    408 
    409 		/*
    410 		 * XXXSMP If we are using h/w performance counters,
    411 		 * save context.
    412 		 */
    413 #if PERFCTRS
    414 		if (PMC_ENABLED(l->l_proc)) {
    415 			pmc_save_context(l->l_proc);
    416 		}
    417 #endif
    418 		updatertime(l, &bt);
    419 	}
    420 
    421 	/*
    422 	 * If on the CPU and we have gotten this far, then we must yield.
    423 	 */
    424 	mutex_spin_enter(spc->spc_mutex);
    425 	KASSERT(l->l_stat != LSRUN);
    426 	if (l->l_stat == LSONPROC && l != newl) {
    427 		KASSERT(lwp_locked(l, &spc->spc_lwplock));
    428 		if ((l->l_flag & LW_IDLE) == 0) {
    429 			l->l_stat = LSRUN;
    430 			lwp_setlock(l, spc->spc_mutex);
    431 			sched_enqueue(l, true);
    432 		} else
    433 			l->l_stat = LSIDL;
    434 	}
    435 
    436 	/*
    437 	 * Let sched_nextlwp() select the LWP to run the CPU next.
    438 	 * If no LWP is runnable, select the idle LWP.
    439 	 *
    440 	 * Note that spc_lwplock might not necessary be held, and
    441 	 * new thread would be unlocked after setting the LWP-lock.
    442 	 */
    443 	if (newl == NULL) {
    444 		newl = sched_nextlwp();
    445 		if (newl != NULL) {
    446 			sched_dequeue(newl);
    447 			KASSERT(lwp_locked(newl, spc->spc_mutex));
    448 			newl->l_stat = LSONPROC;
    449 			newl->l_cpu = ci;
    450 			newl->l_flag |= LW_RUNNING;
    451 			lwp_setlock(newl, &spc->spc_lwplock);
    452 		} else {
    453 			newl = ci->ci_data.cpu_idlelwp;
    454 			newl->l_stat = LSONPROC;
    455 			newl->l_flag |= LW_RUNNING;
    456 		}
    457 		/*
    458 		 * Only clear want_resched if there are no
    459 		 * pending (slow) software interrupts.
    460 		 */
    461 		ci->ci_want_resched = ci->ci_data.cpu_softints;
    462 		spc->spc_flags &= ~SPCF_SWITCHCLEAR;
    463 		spc->spc_curpriority = lwp_eprio(newl);
    464 	}
    465 
    466 	/* Items that must be updated with the CPU locked. */
    467 	if (!returning) {
    468 		/* Update the new LWP's start time. */
    469 		newl->l_stime = bt;
    470 
    471 		/*
    472 		 * ci_curlwp changes when a fast soft interrupt occurs.
    473 		 * We use cpu_onproc to keep track of which kernel or
    474 		 * user thread is running 'underneath' the software
    475 		 * interrupt.  This is important for time accounting,
    476 		 * itimers and forcing user threads to preempt (aston).
    477 		 */
    478 		ci->ci_data.cpu_onproc = newl;
    479 	}
    480 
    481 	if (l != newl) {
    482 		struct lwp *prevlwp;
    483 
    484 		/* Release all locks, but leave the current LWP locked */
    485 		if (l->l_mutex == spc->spc_mutex) {
    486 			/*
    487 			 * Drop spc_lwplock, if the current LWP has been moved
    488 			 * to the run queue (it is now locked by spc_mutex).
    489 			 */
    490 			mutex_spin_exit(&spc->spc_lwplock);
    491 		} else {
    492 			/*
    493 			 * Otherwise, drop the spc_mutex, we are done with the
    494 			 * run queues.
    495 			 */
    496 			mutex_spin_exit(spc->spc_mutex);
    497 		}
    498 
    499 		/*
    500 		 * Mark that context switch is going to be perfomed
    501 		 * for this LWP, to protect it from being switched
    502 		 * to on another CPU.
    503 		 */
    504 		KASSERT(l->l_ctxswtch == 0);
    505 		l->l_ctxswtch = 1;
    506 		l->l_ncsw++;
    507 		l->l_flag &= ~LW_RUNNING;
    508 
    509 		/*
    510 		 * Increase the count of spin-mutexes before the release
    511 		 * of the last lock - we must remain at IPL_SCHED during
    512 		 * the context switch.
    513 		 */
    514 		oldspl = MUTEX_SPIN_OLDSPL(ci);
    515 		ci->ci_mtx_count--;
    516 		lwp_unlock(l);
    517 
    518 		/* Unlocked, but for statistics only. */
    519 		uvmexp.swtch++;
    520 
    521 		/* Update status for lwpctl, if present. */
    522 		if (l->l_lwpctl != NULL)
    523 			l->l_lwpctl->lc_curcpu = LWPCTL_CPU_NONE;
    524 
    525 		/*
    526 		 * Save old VM context, unless a soft interrupt
    527 		 * handler is blocking.
    528 		 */
    529 		if (!returning)
    530 			pmap_deactivate(l);
    531 
    532 		/*
    533 		 * We may need to spin-wait for if 'newl' is still
    534 		 * context switching on another CPU.
    535 		 */
    536 		if (newl->l_ctxswtch != 0) {
    537 			u_int count;
    538 			count = SPINLOCK_BACKOFF_MIN;
    539 			while (newl->l_ctxswtch)
    540 				SPINLOCK_BACKOFF(count);
    541 		}
    542 
    543 		/* Switch to the new LWP.. */
    544 		prevlwp = cpu_switchto(l, newl, returning);
    545 		ci = curcpu();
    546 
    547 		/*
    548 		 * Switched away - we have new curlwp.
    549 		 * Restore VM context and IPL.
    550 		 */
    551 		pmap_activate(l);
    552 		if (prevlwp != NULL) {
    553 			/* Normalize the count of the spin-mutexes */
    554 			ci->ci_mtx_count++;
    555 			/* Unmark the state of context switch */
    556 			membar_exit();
    557 			prevlwp->l_ctxswtch = 0;
    558 		}
    559 		splx(oldspl);
    560 
    561 		/* Update status for lwpctl, if present. */
    562 		if (l->l_lwpctl != NULL)
    563 			l->l_lwpctl->lc_curcpu = (int)cpu_index(ci);
    564 
    565 		retval = 1;
    566 	} else {
    567 		/* Nothing to do - just unlock and return. */
    568 		mutex_spin_exit(spc->spc_mutex);
    569 		lwp_unlock(l);
    570 		retval = 0;
    571 	}
    572 
    573 	KASSERT(l == curlwp);
    574 	KASSERT(l->l_stat == LSONPROC);
    575 	KASSERT(l->l_cpu == ci);
    576 
    577 	/*
    578 	 * XXXSMP If we are using h/w performance counters, restore context.
    579 	 */
    580 #if PERFCTRS
    581 	if (PMC_ENABLED(l->l_proc)) {
    582 		pmc_restore_context(l->l_proc);
    583 	}
    584 #endif
    585 	SYSCALL_TIME_WAKEUP(l);
    586 	LOCKDEBUG_BARRIER(NULL, 1);
    587 
    588 	return retval;
    589 }
    590 
    591 /*
    592  * Change process state to be runnable, placing it on the run queue if it is
    593  * in memory, and awakening the swapper if it isn't in memory.
    594  *
    595  * Call with the process and LWP locked.  Will return with the LWP unlocked.
    596  */
    597 void
    598 setrunnable(struct lwp *l)
    599 {
    600 	struct proc *p = l->l_proc;
    601 	struct cpu_info *ci;
    602 	sigset_t *ss;
    603 
    604 	KASSERT((l->l_flag & LW_IDLE) == 0);
    605 	KASSERT(mutex_owned(&p->p_smutex));
    606 	KASSERT(lwp_locked(l, NULL));
    607 	KASSERT(l->l_mutex != l->l_cpu->ci_schedstate.spc_mutex);
    608 
    609 	switch (l->l_stat) {
    610 	case LSSTOP:
    611 		/*
    612 		 * If we're being traced (possibly because someone attached us
    613 		 * while we were stopped), check for a signal from the debugger.
    614 		 */
    615 		if ((p->p_slflag & PSL_TRACED) != 0 && p->p_xstat != 0) {
    616 			if ((sigprop[p->p_xstat] & SA_TOLWP) != 0)
    617 				ss = &l->l_sigpend.sp_set;
    618 			else
    619 				ss = &p->p_sigpend.sp_set;
    620 			sigaddset(ss, p->p_xstat);
    621 			signotify(l);
    622 		}
    623 		p->p_nrlwps++;
    624 		break;
    625 	case LSSUSPENDED:
    626 		l->l_flag &= ~LW_WSUSPEND;
    627 		p->p_nrlwps++;
    628 		cv_broadcast(&p->p_lwpcv);
    629 		break;
    630 	case LSSLEEP:
    631 		KASSERT(l->l_wchan != NULL);
    632 		break;
    633 	default:
    634 		panic("setrunnable: lwp %p state was %d", l, l->l_stat);
    635 	}
    636 
    637 	/*
    638 	 * If the LWP was sleeping interruptably, then it's OK to start it
    639 	 * again.  If not, mark it as still sleeping.
    640 	 */
    641 	if (l->l_wchan != NULL) {
    642 		l->l_stat = LSSLEEP;
    643 		/* lwp_unsleep() will release the lock. */
    644 		lwp_unsleep(l);
    645 		return;
    646 	}
    647 
    648 	/*
    649 	 * If the LWP is still on the CPU, mark it as LSONPROC.  It may be
    650 	 * about to call mi_switch(), in which case it will yield.
    651 	 */
    652 	if ((l->l_flag & LW_RUNNING) != 0) {
    653 		l->l_stat = LSONPROC;
    654 		l->l_slptime = 0;
    655 		lwp_unlock(l);
    656 		return;
    657 	}
    658 
    659 	/*
    660 	 * Look for a CPU to run.
    661 	 * Set the LWP runnable.
    662 	 */
    663 	ci = sched_takecpu(l);
    664 	l->l_cpu = ci;
    665 	if (l->l_mutex != l->l_cpu->ci_schedstate.spc_mutex) {
    666 		lwp_unlock_to(l, ci->ci_schedstate.spc_mutex);
    667 		lwp_lock(l);
    668 	}
    669 	sched_setrunnable(l);
    670 	l->l_stat = LSRUN;
    671 	l->l_slptime = 0;
    672 
    673 	/*
    674 	 * If thread is swapped out - wake the swapper to bring it back in.
    675 	 * Otherwise, enter it into a run queue.
    676 	 */
    677 	if (l->l_flag & LW_INMEM) {
    678 		sched_enqueue(l, false);
    679 		resched_cpu(l);
    680 		lwp_unlock(l);
    681 	} else {
    682 		lwp_unlock(l);
    683 		uvm_kick_scheduler();
    684 	}
    685 }
    686 
    687 /*
    688  * suspendsched:
    689  *
    690  *	Convert all non-L_SYSTEM LSSLEEP or LSRUN LWPs to LSSUSPENDED.
    691  */
    692 void
    693 suspendsched(void)
    694 {
    695 	CPU_INFO_ITERATOR cii;
    696 	struct cpu_info *ci;
    697 	struct lwp *l;
    698 	struct proc *p;
    699 
    700 	/*
    701 	 * We do this by process in order not to violate the locking rules.
    702 	 */
    703 	mutex_enter(&proclist_lock);
    704 	PROCLIST_FOREACH(p, &allproc) {
    705 		mutex_enter(&p->p_smutex);
    706 
    707 		if ((p->p_flag & PK_SYSTEM) != 0) {
    708 			mutex_exit(&p->p_smutex);
    709 			continue;
    710 		}
    711 
    712 		p->p_stat = SSTOP;
    713 
    714 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    715 			if (l == curlwp)
    716 				continue;
    717 
    718 			lwp_lock(l);
    719 
    720 			/*
    721 			 * Set L_WREBOOT so that the LWP will suspend itself
    722 			 * when it tries to return to user mode.  We want to
    723 			 * try and get to get as many LWPs as possible to
    724 			 * the user / kernel boundary, so that they will
    725 			 * release any locks that they hold.
    726 			 */
    727 			l->l_flag |= (LW_WREBOOT | LW_WSUSPEND);
    728 
    729 			if (l->l_stat == LSSLEEP &&
    730 			    (l->l_flag & LW_SINTR) != 0) {
    731 				/* setrunnable() will release the lock. */
    732 				setrunnable(l);
    733 				continue;
    734 			}
    735 
    736 			lwp_unlock(l);
    737 		}
    738 
    739 		mutex_exit(&p->p_smutex);
    740 	}
    741 	mutex_exit(&proclist_lock);
    742 
    743 	/*
    744 	 * Kick all CPUs to make them preempt any LWPs running in user mode.
    745 	 * They'll trap into the kernel and suspend themselves in userret().
    746 	 */
    747 	for (CPU_INFO_FOREACH(cii, ci)) {
    748 		spc_lock(ci);
    749 		cpu_need_resched(ci, RESCHED_IMMED);
    750 		spc_unlock(ci);
    751 	}
    752 }
    753 
    754 /*
    755  * sched_unsleep:
    756  *
    757  *	The is called when the LWP has not been awoken normally but instead
    758  *	interrupted: for example, if the sleep timed out.  Because of this,
    759  *	it's not a valid action for running or idle LWPs.
    760  */
    761 static void
    762 sched_unsleep(struct lwp *l)
    763 {
    764 
    765 	lwp_unlock(l);
    766 	panic("sched_unsleep");
    767 }
    768 
    769 void
    770 resched_cpu(struct lwp *l)
    771 {
    772 	struct cpu_info *ci;
    773 
    774 	/*
    775 	 * XXXSMP
    776 	 * Since l->l_cpu persists across a context switch,
    777 	 * this gives us *very weak* processor affinity, in
    778 	 * that we notify the CPU on which the process last
    779 	 * ran that it should try to switch.
    780 	 *
    781 	 * This does not guarantee that the process will run on
    782 	 * that processor next, because another processor might
    783 	 * grab it the next time it performs a context switch.
    784 	 *
    785 	 * This also does not handle the case where its last
    786 	 * CPU is running a higher-priority process, but every
    787 	 * other CPU is running a lower-priority process.  There
    788 	 * are ways to handle this situation, but they're not
    789 	 * currently very pretty, and we also need to weigh the
    790 	 * cost of moving a process from one CPU to another.
    791 	 */
    792 	ci = l->l_cpu;
    793 	if (lwp_eprio(l) > ci->ci_schedstate.spc_curpriority)
    794 		cpu_need_resched(ci, 0);
    795 }
    796 
    797 static void
    798 sched_changepri(struct lwp *l, pri_t pri)
    799 {
    800 
    801 	KASSERT(lwp_locked(l, NULL));
    802 
    803 	if (l->l_stat == LSRUN && (l->l_flag & LW_INMEM) != 0) {
    804 		KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
    805 		sched_dequeue(l);
    806 		l->l_priority = pri;
    807 		sched_enqueue(l, false);
    808 	} else {
    809 		l->l_priority = pri;
    810 	}
    811 	resched_cpu(l);
    812 }
    813 
    814 static void
    815 sched_lendpri(struct lwp *l, pri_t pri)
    816 {
    817 
    818 	KASSERT(lwp_locked(l, NULL));
    819 
    820 	if (l->l_stat == LSRUN && (l->l_flag & LW_INMEM) != 0) {
    821 		KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
    822 		sched_dequeue(l);
    823 		l->l_inheritedprio = pri;
    824 		sched_enqueue(l, false);
    825 	} else {
    826 		l->l_inheritedprio = pri;
    827 	}
    828 	resched_cpu(l);
    829 }
    830 
    831 struct lwp *
    832 syncobj_noowner(wchan_t wchan)
    833 {
    834 
    835 	return NULL;
    836 }
    837 
    838 
    839 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
    840 fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;		/* exp(-1/20) */
    841 
    842 /*
    843  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
    844  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
    845  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
    846  *
    847  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
    848  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
    849  *
    850  * If you dont want to bother with the faster/more-accurate formula, you
    851  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
    852  * (more general) method of calculating the %age of CPU used by a process.
    853  */
    854 #define	CCPU_SHIFT	(FSHIFT + 1)
    855 
    856 /*
    857  * sched_pstats:
    858  *
    859  * Update process statistics and check CPU resource allocation.
    860  * Call scheduler-specific hook to eventually adjust process/LWP
    861  * priorities.
    862  */
    863 /* ARGSUSED */
    864 void
    865 sched_pstats(void *arg)
    866 {
    867 	struct rlimit *rlim;
    868 	struct lwp *l;
    869 	struct proc *p;
    870 	int sig, clkhz;
    871 	long runtm;
    872 
    873 	sched_pstats_ticks++;
    874 
    875 	mutex_enter(&proclist_lock);
    876 	PROCLIST_FOREACH(p, &allproc) {
    877 		/*
    878 		 * Increment time in/out of memory and sleep time (if
    879 		 * sleeping).  We ignore overflow; with 16-bit int's
    880 		 * (remember them?) overflow takes 45 days.
    881 		 */
    882 		mutex_enter(&p->p_smutex);
    883 		mutex_spin_enter(&p->p_stmutex);
    884 		runtm = p->p_rtime.sec;
    885 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    886 			if ((l->l_flag & LW_IDLE) != 0)
    887 				continue;
    888 			lwp_lock(l);
    889 			runtm += l->l_rtime.sec;
    890 			l->l_swtime++;
    891 			sched_pstats_hook(l);
    892 			lwp_unlock(l);
    893 
    894 			/*
    895 			 * p_pctcpu is only for ps.
    896 			 */
    897 			l->l_pctcpu = (l->l_pctcpu * ccpu) >> FSHIFT;
    898 			if (l->l_slptime < 1) {
    899 				clkhz = stathz != 0 ? stathz : hz;
    900 #if	(FSHIFT >= CCPU_SHIFT)
    901 				l->l_pctcpu += (clkhz == 100) ?
    902 				    ((fixpt_t)l->l_cpticks) <<
    903 				        (FSHIFT - CCPU_SHIFT) :
    904 				    100 * (((fixpt_t) p->p_cpticks)
    905 				        << (FSHIFT - CCPU_SHIFT)) / clkhz;
    906 #else
    907 				l->l_pctcpu += ((FSCALE - ccpu) *
    908 				    (l->l_cpticks * FSCALE / clkhz)) >> FSHIFT;
    909 #endif
    910 				l->l_cpticks = 0;
    911 			}
    912 		}
    913 		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
    914 		mutex_spin_exit(&p->p_stmutex);
    915 
    916 		/*
    917 		 * Check if the process exceeds its CPU resource allocation.
    918 		 * If over max, kill it.
    919 		 */
    920 		rlim = &p->p_rlimit[RLIMIT_CPU];
    921 		sig = 0;
    922 		if (runtm >= rlim->rlim_cur) {
    923 			if (runtm >= rlim->rlim_max)
    924 				sig = SIGKILL;
    925 			else {
    926 				sig = SIGXCPU;
    927 				if (rlim->rlim_cur < rlim->rlim_max)
    928 					rlim->rlim_cur += 5;
    929 			}
    930 		}
    931 		mutex_exit(&p->p_smutex);
    932 		if (sig) {
    933 			mutex_enter(&proclist_mutex);
    934 			psignal(p, sig);
    935 			mutex_exit(&proclist_mutex);
    936 		}
    937 	}
    938 	mutex_exit(&proclist_lock);
    939 	uvm_meter();
    940 	cv_wakeup(&lbolt);
    941 	callout_schedule(&sched_pstats_ch, hz);
    942 }
    943 
    944 void
    945 sched_init(void)
    946 {
    947 
    948 	cv_init(&lbolt, "lbolt");
    949 	callout_init(&sched_pstats_ch, CALLOUT_MPSAFE);
    950 	callout_setfunc(&sched_pstats_ch, sched_pstats, NULL);
    951 	sched_setup();
    952 	sched_pstats(NULL);
    953 }
    954