Home | History | Annotate | Line # | Download | only in kern
kern_synch.c revision 1.257
      1 /*	$NetBSD: kern_synch.c,v 1.257 2008/12/20 23:06:14 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999, 2000, 2004, 2006, 2007, 2008 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  *
     21  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     23  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     24  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     25  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     31  * POSSIBILITY OF SUCH DAMAGE.
     32  */
     33 
     34 /*-
     35  * Copyright (c) 1982, 1986, 1990, 1991, 1993
     36  *	The Regents of the University of California.  All rights reserved.
     37  * (c) UNIX System Laboratories, Inc.
     38  * All or some portions of this file are derived from material licensed
     39  * to the University of California by American Telephone and Telegraph
     40  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     41  * the permission of UNIX System Laboratories, Inc.
     42  *
     43  * Redistribution and use in source and binary forms, with or without
     44  * modification, are permitted provided that the following conditions
     45  * are met:
     46  * 1. Redistributions of source code must retain the above copyright
     47  *    notice, this list of conditions and the following disclaimer.
     48  * 2. Redistributions in binary form must reproduce the above copyright
     49  *    notice, this list of conditions and the following disclaimer in the
     50  *    documentation and/or other materials provided with the distribution.
     51  * 3. Neither the name of the University nor the names of its contributors
     52  *    may be used to endorse or promote products derived from this software
     53  *    without specific prior written permission.
     54  *
     55  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     56  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     57  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     58  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     59  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     60  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     61  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     62  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     63  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     64  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     65  * SUCH DAMAGE.
     66  *
     67  *	@(#)kern_synch.c	8.9 (Berkeley) 5/19/95
     68  */
     69 
     70 #include <sys/cdefs.h>
     71 __KERNEL_RCSID(0, "$NetBSD: kern_synch.c,v 1.257 2008/12/20 23:06:14 ad Exp $");
     72 
     73 #include "opt_kstack.h"
     74 #include "opt_perfctrs.h"
     75 #include "opt_sa.h"
     76 
     77 #define	__MUTEX_PRIVATE
     78 
     79 #include <sys/param.h>
     80 #include <sys/systm.h>
     81 #include <sys/proc.h>
     82 #include <sys/kernel.h>
     83 #if defined(PERFCTRS)
     84 #include <sys/pmc.h>
     85 #endif
     86 #include <sys/cpu.h>
     87 #include <sys/resourcevar.h>
     88 #include <sys/sched.h>
     89 #include <sys/sa.h>
     90 #include <sys/savar.h>
     91 #include <sys/syscall_stats.h>
     92 #include <sys/sleepq.h>
     93 #include <sys/lockdebug.h>
     94 #include <sys/evcnt.h>
     95 #include <sys/intr.h>
     96 #include <sys/lwpctl.h>
     97 #include <sys/atomic.h>
     98 #include <sys/simplelock.h>
     99 
    100 #include <uvm/uvm_extern.h>
    101 
    102 #include <dev/lockstat.h>
    103 
    104 static u_int	sched_unsleep(struct lwp *, bool);
    105 static void	sched_changepri(struct lwp *, pri_t);
    106 static void	sched_lendpri(struct lwp *, pri_t);
    107 static void	resched_cpu(struct lwp *);
    108 
    109 syncobj_t sleep_syncobj = {
    110 	SOBJ_SLEEPQ_SORTED,
    111 	sleepq_unsleep,
    112 	sleepq_changepri,
    113 	sleepq_lendpri,
    114 	syncobj_noowner,
    115 };
    116 
    117 syncobj_t sched_syncobj = {
    118 	SOBJ_SLEEPQ_SORTED,
    119 	sched_unsleep,
    120 	sched_changepri,
    121 	sched_lendpri,
    122 	syncobj_noowner,
    123 };
    124 
    125 callout_t 	sched_pstats_ch;
    126 unsigned	sched_pstats_ticks;
    127 kcondvar_t	lbolt;			/* once a second sleep address */
    128 
    129 /* Preemption event counters */
    130 static struct evcnt kpreempt_ev_crit;
    131 static struct evcnt kpreempt_ev_klock;
    132 static struct evcnt kpreempt_ev_ipl;
    133 static struct evcnt kpreempt_ev_immed;
    134 
    135 /*
    136  * During autoconfiguration or after a panic, a sleep will simply lower the
    137  * priority briefly to allow interrupts, then return.  The priority to be
    138  * used (safepri) is machine-dependent, thus this value is initialized and
    139  * maintained in the machine-dependent layers.  This priority will typically
    140  * be 0, or the lowest priority that is safe for use on the interrupt stack;
    141  * it can be made higher to block network software interrupts after panics.
    142  */
    143 int	safepri;
    144 
    145 void
    146 sched_init(void)
    147 {
    148 
    149 	cv_init(&lbolt, "lbolt");
    150 	callout_init(&sched_pstats_ch, CALLOUT_MPSAFE);
    151 	callout_setfunc(&sched_pstats_ch, sched_pstats, NULL);
    152 
    153 	evcnt_attach_dynamic(&kpreempt_ev_crit, EVCNT_TYPE_MISC, NULL,
    154 	   "kpreempt", "defer: critical section");
    155 	evcnt_attach_dynamic(&kpreempt_ev_klock, EVCNT_TYPE_MISC, NULL,
    156 	   "kpreempt", "defer: kernel_lock");
    157 	evcnt_attach_dynamic(&kpreempt_ev_ipl, EVCNT_TYPE_MISC, NULL,
    158 	   "kpreempt", "defer: IPL");
    159 	evcnt_attach_dynamic(&kpreempt_ev_immed, EVCNT_TYPE_MISC, NULL,
    160 	   "kpreempt", "immediate");
    161 
    162 	sched_pstats(NULL);
    163 }
    164 
    165 /*
    166  * OBSOLETE INTERFACE
    167  *
    168  * General sleep call.  Suspends the current LWP until a wakeup is
    169  * performed on the specified identifier.  The LWP will then be made
    170  * runnable with the specified priority.  Sleeps at most timo/hz seconds (0
    171  * means no timeout).  If pri includes PCATCH flag, signals are checked
    172  * before and after sleeping, else signals are not checked.  Returns 0 if
    173  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
    174  * signal needs to be delivered, ERESTART is returned if the current system
    175  * call should be restarted if possible, and EINTR is returned if the system
    176  * call should be interrupted by the signal (return EINTR).
    177  *
    178  * The interlock is held until we are on a sleep queue. The interlock will
    179  * be locked before returning back to the caller unless the PNORELOCK flag
    180  * is specified, in which case the interlock will always be unlocked upon
    181  * return.
    182  */
    183 int
    184 ltsleep(wchan_t ident, pri_t priority, const char *wmesg, int timo,
    185 	volatile struct simplelock *interlock)
    186 {
    187 	struct lwp *l = curlwp;
    188 	sleepq_t *sq;
    189 	kmutex_t *mp;
    190 	int error;
    191 
    192 	KASSERT((l->l_pflag & LP_INTR) == 0);
    193 
    194 	if (sleepq_dontsleep(l)) {
    195 		(void)sleepq_abort(NULL, 0);
    196 		if ((priority & PNORELOCK) != 0)
    197 			simple_unlock(interlock);
    198 		return 0;
    199 	}
    200 
    201 	l->l_kpriority = true;
    202 	sq = sleeptab_lookup(&sleeptab, ident, &mp);
    203 	sleepq_enter(sq, l, mp);
    204 	sleepq_enqueue(sq, ident, wmesg, &sleep_syncobj);
    205 
    206 	if (interlock != NULL) {
    207 		KASSERT(simple_lock_held(interlock));
    208 		simple_unlock(interlock);
    209 	}
    210 
    211 	error = sleepq_block(timo, priority & PCATCH);
    212 
    213 	if (interlock != NULL && (priority & PNORELOCK) == 0)
    214 		simple_lock(interlock);
    215 
    216 	return error;
    217 }
    218 
    219 int
    220 mtsleep(wchan_t ident, pri_t priority, const char *wmesg, int timo,
    221 	kmutex_t *mtx)
    222 {
    223 	struct lwp *l = curlwp;
    224 	sleepq_t *sq;
    225 	kmutex_t *mp;
    226 	int error;
    227 
    228 	KASSERT((l->l_pflag & LP_INTR) == 0);
    229 
    230 	if (sleepq_dontsleep(l)) {
    231 		(void)sleepq_abort(mtx, (priority & PNORELOCK) != 0);
    232 		return 0;
    233 	}
    234 
    235 	l->l_kpriority = true;
    236 	sq = sleeptab_lookup(&sleeptab, ident, &mp);
    237 	sleepq_enter(sq, l, mp);
    238 	sleepq_enqueue(sq, ident, wmesg, &sleep_syncobj);
    239 	mutex_exit(mtx);
    240 	error = sleepq_block(timo, priority & PCATCH);
    241 
    242 	if ((priority & PNORELOCK) == 0)
    243 		mutex_enter(mtx);
    244 
    245 	return error;
    246 }
    247 
    248 /*
    249  * General sleep call for situations where a wake-up is not expected.
    250  */
    251 int
    252 kpause(const char *wmesg, bool intr, int timo, kmutex_t *mtx)
    253 {
    254 	struct lwp *l = curlwp;
    255 	kmutex_t *mp;
    256 	sleepq_t *sq;
    257 	int error;
    258 
    259 	if (sleepq_dontsleep(l))
    260 		return sleepq_abort(NULL, 0);
    261 
    262 	if (mtx != NULL)
    263 		mutex_exit(mtx);
    264 	l->l_kpriority = true;
    265 	sq = sleeptab_lookup(&sleeptab, l, &mp);
    266 	sleepq_enter(sq, l, mp);
    267 	sleepq_enqueue(sq, l, wmesg, &sleep_syncobj);
    268 	error = sleepq_block(timo, intr);
    269 	if (mtx != NULL)
    270 		mutex_enter(mtx);
    271 
    272 	return error;
    273 }
    274 
    275 #ifdef KERN_SA
    276 /*
    277  * sa_awaken:
    278  *
    279  *	We believe this lwp is an SA lwp. If it's yielding,
    280  * let it know it needs to wake up.
    281  *
    282  *	We are called and exit with the lwp locked. We are
    283  * called in the middle of wakeup operations, so we need
    284  * to not touch the locks at all.
    285  */
    286 void
    287 sa_awaken(struct lwp *l)
    288 {
    289 	/* LOCK_ASSERT(lwp_locked(l, NULL)); */
    290 
    291 	if (l == l->l_savp->savp_lwp && l->l_flag & LW_SA_YIELD)
    292 		l->l_flag &= ~LW_SA_IDLE;
    293 }
    294 #endif /* KERN_SA */
    295 
    296 /*
    297  * OBSOLETE INTERFACE
    298  *
    299  * Make all LWPs sleeping on the specified identifier runnable.
    300  */
    301 void
    302 wakeup(wchan_t ident)
    303 {
    304 	sleepq_t *sq;
    305 	kmutex_t *mp;
    306 
    307 	if (cold)
    308 		return;
    309 
    310 	sq = sleeptab_lookup(&sleeptab, ident, &mp);
    311 	sleepq_wake(sq, ident, (u_int)-1, mp);
    312 }
    313 
    314 /*
    315  * OBSOLETE INTERFACE
    316  *
    317  * Make the highest priority LWP first in line on the specified
    318  * identifier runnable.
    319  */
    320 void
    321 wakeup_one(wchan_t ident)
    322 {
    323 	sleepq_t *sq;
    324 	kmutex_t *mp;
    325 
    326 	if (cold)
    327 		return;
    328 
    329 	sq = sleeptab_lookup(&sleeptab, ident, &mp);
    330 	sleepq_wake(sq, ident, 1, mp);
    331 }
    332 
    333 
    334 /*
    335  * General yield call.  Puts the current LWP back on its run queue and
    336  * performs a voluntary context switch.  Should only be called when the
    337  * current LWP explicitly requests it (eg sched_yield(2)).
    338  */
    339 void
    340 yield(void)
    341 {
    342 	struct lwp *l = curlwp;
    343 
    344 	KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
    345 	lwp_lock(l);
    346 	KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_lwplock));
    347 	KASSERT(l->l_stat == LSONPROC);
    348 	l->l_kpriority = false;
    349 	(void)mi_switch(l);
    350 	KERNEL_LOCK(l->l_biglocks, l);
    351 }
    352 
    353 /*
    354  * General preemption call.  Puts the current LWP back on its run queue
    355  * and performs an involuntary context switch.
    356  */
    357 void
    358 preempt(void)
    359 {
    360 	struct lwp *l = curlwp;
    361 
    362 	KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
    363 	lwp_lock(l);
    364 	KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_lwplock));
    365 	KASSERT(l->l_stat == LSONPROC);
    366 	l->l_kpriority = false;
    367 	l->l_nivcsw++;
    368 	(void)mi_switch(l);
    369 	KERNEL_LOCK(l->l_biglocks, l);
    370 }
    371 
    372 /*
    373  * Handle a request made by another agent to preempt the current LWP
    374  * in-kernel.  Usually called when l_dopreempt may be non-zero.
    375  *
    376  * Character addresses for lockstat only.
    377  */
    378 static char	in_critical_section;
    379 static char	kernel_lock_held;
    380 static char	spl_raised;
    381 static char	is_softint;
    382 
    383 bool
    384 kpreempt(uintptr_t where)
    385 {
    386 	uintptr_t failed;
    387 	lwp_t *l;
    388 	int s, dop;
    389 
    390 	l = curlwp;
    391 	failed = 0;
    392 	while ((dop = l->l_dopreempt) != 0) {
    393 		if (l->l_stat != LSONPROC) {
    394 			/*
    395 			 * About to block (or die), let it happen.
    396 			 * Doesn't really count as "preemption has
    397 			 * been blocked", since we're going to
    398 			 * context switch.
    399 			 */
    400 			l->l_dopreempt = 0;
    401 			return true;
    402 		}
    403 		if (cpu_intr_p()) {
    404 			/*
    405 			 * Don't record a failure event if handling
    406 			 * a hardware interrupt.  We're probably
    407 			 * here from _kernel_unlock().  The
    408 			 * preemption will be processed at EOI.
    409 			 */
    410 			return true;
    411 		}
    412 		if (__predict_false((l->l_flag & LW_IDLE) != 0)) {
    413 			/* Can't preempt idle loop, don't count as failure. */
    414 		    	l->l_dopreempt = 0;
    415 		    	return true;
    416 		}
    417 		if (__predict_false(l->l_nopreempt != 0)) {
    418 			/* LWP holds preemption disabled, explicitly. */
    419 			if ((dop & DOPREEMPT_COUNTED) == 0) {
    420 				kpreempt_ev_crit.ev_count++;
    421 			}
    422 			failed = (uintptr_t)&in_critical_section;
    423 			break;
    424 		}
    425 		if (__predict_false((l->l_pflag & LP_INTR) != 0)) {
    426 		    	/* Can't preempt soft interrupts yet. */
    427 		    	l->l_dopreempt = 0;
    428 		    	failed = (uintptr_t)&is_softint;
    429 		    	break;
    430 		}
    431 		s = splsched();
    432 		if (__predict_false(l->l_blcnt != 0 ||
    433 		    curcpu()->ci_biglock_wanted != NULL)) {
    434 			/* Hold or want kernel_lock, code is not MT safe. */
    435 			splx(s);
    436 			if ((dop & DOPREEMPT_COUNTED) == 0) {
    437 				kpreempt_ev_klock.ev_count++;
    438 			}
    439 			failed = (uintptr_t)&kernel_lock_held;
    440 			break;
    441 		}
    442 		if (__predict_false(!cpu_kpreempt_enter(where, s))) {
    443 			/*
    444 			 * It may be that the IPL is too high.
    445 			 * kpreempt_enter() can schedule an
    446 			 * interrupt to retry later.
    447 			 */
    448 			splx(s);
    449 			if ((dop & DOPREEMPT_COUNTED) == 0) {
    450 				kpreempt_ev_ipl.ev_count++;
    451 			}
    452 			failed = (uintptr_t)&spl_raised;
    453 			break;
    454 		}
    455 		/* Do it! */
    456 		if (__predict_true((dop & DOPREEMPT_COUNTED) == 0)) {
    457 			kpreempt_ev_immed.ev_count++;
    458 		}
    459 		lwp_lock(l);
    460 		mi_switch(l);
    461 		l->l_nopreempt++;
    462 		splx(s);
    463 
    464 		/* Take care of any MD cleanup. */
    465 		cpu_kpreempt_exit(where);
    466 		l->l_nopreempt--;
    467 	}
    468 
    469 	/* Record preemption failure for reporting via lockstat. */
    470 	if (__predict_false(failed)) {
    471 		int lsflag = 0;
    472 		atomic_or_uint(&l->l_dopreempt, DOPREEMPT_COUNTED);
    473 		LOCKSTAT_ENTER(lsflag);
    474 		/* Might recurse, make it atomic. */
    475 		if (__predict_false(lsflag)) {
    476 			if (where == 0) {
    477 				where = (uintptr_t)__builtin_return_address(0);
    478 			}
    479 			if (atomic_cas_ptr_ni((void *)&l->l_pfailaddr,
    480 			    NULL, (void *)where) == NULL) {
    481 				LOCKSTAT_START_TIMER(lsflag, l->l_pfailtime);
    482 				l->l_pfaillock = failed;
    483 			}
    484 		}
    485 		LOCKSTAT_EXIT(lsflag);
    486 	}
    487 
    488 	return failed;
    489 }
    490 
    491 /*
    492  * Return true if preemption is explicitly disabled.
    493  */
    494 bool
    495 kpreempt_disabled(void)
    496 {
    497 	lwp_t *l;
    498 
    499 	l = curlwp;
    500 
    501 	return l->l_nopreempt != 0 || l->l_stat == LSZOMB ||
    502 	    (l->l_flag & LW_IDLE) != 0 || cpu_kpreempt_disabled();
    503 }
    504 
    505 /*
    506  * Disable kernel preemption.
    507  */
    508 void
    509 kpreempt_disable(void)
    510 {
    511 
    512 	KPREEMPT_DISABLE(curlwp);
    513 }
    514 
    515 /*
    516  * Reenable kernel preemption.
    517  */
    518 void
    519 kpreempt_enable(void)
    520 {
    521 
    522 	KPREEMPT_ENABLE(curlwp);
    523 }
    524 
    525 /*
    526  * Compute the amount of time during which the current lwp was running.
    527  *
    528  * - update l_rtime unless it's an idle lwp.
    529  */
    530 
    531 void
    532 updatertime(lwp_t *l, const struct bintime *now)
    533 {
    534 
    535 	if ((l->l_flag & LW_IDLE) != 0)
    536 		return;
    537 
    538 	/* rtime += now - stime */
    539 	bintime_add(&l->l_rtime, now);
    540 	bintime_sub(&l->l_rtime, &l->l_stime);
    541 }
    542 
    543 /*
    544  * Select next LWP from the current CPU to run..
    545  */
    546 static inline lwp_t *
    547 nextlwp(struct cpu_info *ci, struct schedstate_percpu *spc)
    548 {
    549 	lwp_t *newl;
    550 
    551 	/*
    552 	 * Let sched_nextlwp() select the LWP to run the CPU next.
    553 	 * If no LWP is runnable, select the idle LWP.
    554 	 *
    555 	 * Note that spc_lwplock might not necessary be held, and
    556 	 * new thread would be unlocked after setting the LWP-lock.
    557 	 */
    558 	newl = sched_nextlwp();
    559 	if (newl != NULL) {
    560 		sched_dequeue(newl);
    561 		KASSERT(lwp_locked(newl, spc->spc_mutex));
    562 		newl->l_stat = LSONPROC;
    563 		newl->l_cpu = ci;
    564 		newl->l_pflag |= LP_RUNNING;
    565 		lwp_setlock(newl, spc->spc_lwplock);
    566 	} else {
    567 		newl = ci->ci_data.cpu_idlelwp;
    568 		newl->l_stat = LSONPROC;
    569 		newl->l_pflag |= LP_RUNNING;
    570 	}
    571 
    572 	/*
    573 	 * Only clear want_resched if there are no pending (slow)
    574 	 * software interrupts.
    575 	 */
    576 	ci->ci_want_resched = ci->ci_data.cpu_softints;
    577 	spc->spc_flags &= ~SPCF_SWITCHCLEAR;
    578 	spc->spc_curpriority = lwp_eprio(newl);
    579 
    580 	return newl;
    581 }
    582 
    583 /*
    584  * The machine independent parts of context switch.
    585  *
    586  * Returns 1 if another LWP was actually run.
    587  */
    588 int
    589 mi_switch(lwp_t *l)
    590 {
    591 	struct cpu_info *ci;
    592 	struct schedstate_percpu *spc;
    593 	struct lwp *newl;
    594 	int retval, oldspl;
    595 	struct bintime bt;
    596 	bool returning;
    597 
    598 	KASSERT(lwp_locked(l, NULL));
    599 	KASSERT(kpreempt_disabled());
    600 	LOCKDEBUG_BARRIER(l->l_mutex, 1);
    601 
    602 #ifdef KSTACK_CHECK_MAGIC
    603 	kstack_check_magic(l);
    604 #endif
    605 
    606 	binuptime(&bt);
    607 
    608 	KASSERT(l->l_cpu == curcpu());
    609 	ci = l->l_cpu;
    610 	spc = &ci->ci_schedstate;
    611 	returning = false;
    612 	newl = NULL;
    613 
    614 	/*
    615 	 * If we have been asked to switch to a specific LWP, then there
    616 	 * is no need to inspect the run queues.  If a soft interrupt is
    617 	 * blocking, then return to the interrupted thread without adjusting
    618 	 * VM context or its start time: neither have been changed in order
    619 	 * to take the interrupt.
    620 	 */
    621 	if (l->l_switchto != NULL) {
    622 		if ((l->l_pflag & LP_INTR) != 0) {
    623 			returning = true;
    624 			softint_block(l);
    625 			if ((l->l_pflag & LP_TIMEINTR) != 0)
    626 				updatertime(l, &bt);
    627 		}
    628 		newl = l->l_switchto;
    629 		l->l_switchto = NULL;
    630 	}
    631 #ifndef __HAVE_FAST_SOFTINTS
    632 	else if (ci->ci_data.cpu_softints != 0) {
    633 		/* There are pending soft interrupts, so pick one. */
    634 		newl = softint_picklwp();
    635 		newl->l_stat = LSONPROC;
    636 		newl->l_pflag |= LP_RUNNING;
    637 	}
    638 #endif	/* !__HAVE_FAST_SOFTINTS */
    639 
    640 	/* Count time spent in current system call */
    641 	if (!returning) {
    642 		SYSCALL_TIME_SLEEP(l);
    643 
    644 		/*
    645 		 * XXXSMP If we are using h/w performance counters,
    646 		 * save context.
    647 		 */
    648 #if PERFCTRS
    649 		if (PMC_ENABLED(l->l_proc)) {
    650 			pmc_save_context(l->l_proc);
    651 		}
    652 #endif
    653 		updatertime(l, &bt);
    654 	}
    655 
    656 	/* Lock the runqueue */
    657 	KASSERT(l->l_stat != LSRUN);
    658 	mutex_spin_enter(spc->spc_mutex);
    659 
    660 	/*
    661 	 * If on the CPU and we have gotten this far, then we must yield.
    662 	 */
    663 	if (l->l_stat == LSONPROC && l != newl) {
    664 		KASSERT(lwp_locked(l, spc->spc_lwplock));
    665 		if ((l->l_flag & LW_IDLE) == 0) {
    666 			l->l_stat = LSRUN;
    667 			lwp_setlock(l, spc->spc_mutex);
    668 			sched_enqueue(l, true);
    669 			/* Handle migration case */
    670 			KASSERT(spc->spc_migrating == NULL);
    671 			if (l->l_target_cpu !=  NULL) {
    672 				spc->spc_migrating = l;
    673 			}
    674 		} else
    675 			l->l_stat = LSIDL;
    676 	}
    677 
    678 	/* Pick new LWP to run. */
    679 	if (newl == NULL) {
    680 		newl = nextlwp(ci, spc);
    681 	}
    682 
    683 	/* Items that must be updated with the CPU locked. */
    684 	if (!returning) {
    685 		/* Update the new LWP's start time. */
    686 		newl->l_stime = bt;
    687 
    688 		/*
    689 		 * ci_curlwp changes when a fast soft interrupt occurs.
    690 		 * We use cpu_onproc to keep track of which kernel or
    691 		 * user thread is running 'underneath' the software
    692 		 * interrupt.  This is important for time accounting,
    693 		 * itimers and forcing user threads to preempt (aston).
    694 		 */
    695 		ci->ci_data.cpu_onproc = newl;
    696 	}
    697 
    698 	/*
    699 	 * Preemption related tasks.  Must be done with the current
    700 	 * CPU locked.
    701 	 */
    702 	cpu_did_resched(l);
    703 	l->l_dopreempt = 0;
    704 	if (__predict_false(l->l_pfailaddr != 0)) {
    705 		LOCKSTAT_FLAG(lsflag);
    706 		LOCKSTAT_ENTER(lsflag);
    707 		LOCKSTAT_STOP_TIMER(lsflag, l->l_pfailtime);
    708 		LOCKSTAT_EVENT_RA(lsflag, l->l_pfaillock, LB_NOPREEMPT|LB_SPIN,
    709 		    1, l->l_pfailtime, l->l_pfailaddr);
    710 		LOCKSTAT_EXIT(lsflag);
    711 		l->l_pfailtime = 0;
    712 		l->l_pfaillock = 0;
    713 		l->l_pfailaddr = 0;
    714 	}
    715 
    716 	if (l != newl) {
    717 		struct lwp *prevlwp;
    718 
    719 		/* Release all locks, but leave the current LWP locked */
    720 		if (l->l_mutex == spc->spc_mutex) {
    721 			/*
    722 			 * Drop spc_lwplock, if the current LWP has been moved
    723 			 * to the run queue (it is now locked by spc_mutex).
    724 			 */
    725 			mutex_spin_exit(spc->spc_lwplock);
    726 		} else {
    727 			/*
    728 			 * Otherwise, drop the spc_mutex, we are done with the
    729 			 * run queues.
    730 			 */
    731 			mutex_spin_exit(spc->spc_mutex);
    732 		}
    733 
    734 		/*
    735 		 * Mark that context switch is going to be performed
    736 		 * for this LWP, to protect it from being switched
    737 		 * to on another CPU.
    738 		 */
    739 		KASSERT(l->l_ctxswtch == 0);
    740 		l->l_ctxswtch = 1;
    741 		l->l_ncsw++;
    742 		l->l_pflag &= ~LP_RUNNING;
    743 
    744 		/*
    745 		 * Increase the count of spin-mutexes before the release
    746 		 * of the last lock - we must remain at IPL_SCHED during
    747 		 * the context switch.
    748 		 */
    749 		oldspl = MUTEX_SPIN_OLDSPL(ci);
    750 		ci->ci_mtx_count--;
    751 		lwp_unlock(l);
    752 
    753 		/* Count the context switch on this CPU. */
    754 		ci->ci_data.cpu_nswtch++;
    755 
    756 		/* Update status for lwpctl, if present. */
    757 		if (l->l_lwpctl != NULL)
    758 			l->l_lwpctl->lc_curcpu = LWPCTL_CPU_NONE;
    759 
    760 		/*
    761 		 * Save old VM context, unless a soft interrupt
    762 		 * handler is blocking.
    763 		 */
    764 		if (!returning)
    765 			pmap_deactivate(l);
    766 
    767 		/*
    768 		 * We may need to spin-wait for if 'newl' is still
    769 		 * context switching on another CPU.
    770 		 */
    771 		if (newl->l_ctxswtch != 0) {
    772 			u_int count;
    773 			count = SPINLOCK_BACKOFF_MIN;
    774 			while (newl->l_ctxswtch)
    775 				SPINLOCK_BACKOFF(count);
    776 		}
    777 
    778 		/* Switch to the new LWP.. */
    779 		prevlwp = cpu_switchto(l, newl, returning);
    780 		ci = curcpu();
    781 
    782 		/*
    783 		 * Switched away - we have new curlwp.
    784 		 * Restore VM context and IPL.
    785 		 */
    786 		pmap_activate(l);
    787 		if (prevlwp != NULL) {
    788 			/* Normalize the count of the spin-mutexes */
    789 			ci->ci_mtx_count++;
    790 			/* Unmark the state of context switch */
    791 			membar_exit();
    792 			prevlwp->l_ctxswtch = 0;
    793 		}
    794 
    795 		/* Update status for lwpctl, if present. */
    796 		if (l->l_lwpctl != NULL) {
    797 			l->l_lwpctl->lc_curcpu = (int)cpu_index(ci);
    798 			l->l_lwpctl->lc_pctr++;
    799 		}
    800 
    801 		KASSERT(l->l_cpu == ci);
    802 		splx(oldspl);
    803 		retval = 1;
    804 	} else {
    805 		/* Nothing to do - just unlock and return. */
    806 		mutex_spin_exit(spc->spc_mutex);
    807 		lwp_unlock(l);
    808 		retval = 0;
    809 	}
    810 
    811 	KASSERT(l == curlwp);
    812 	KASSERT(l->l_stat == LSONPROC);
    813 
    814 	/*
    815 	 * XXXSMP If we are using h/w performance counters, restore context.
    816 	 * XXXSMP preemption problem.
    817 	 */
    818 #if PERFCTRS
    819 	if (PMC_ENABLED(l->l_proc)) {
    820 		pmc_restore_context(l->l_proc);
    821 	}
    822 #endif
    823 	SYSCALL_TIME_WAKEUP(l);
    824 	LOCKDEBUG_BARRIER(NULL, 1);
    825 
    826 	return retval;
    827 }
    828 
    829 /*
    830  * The machine independent parts of context switch to oblivion.
    831  * Does not return.  Call with the LWP unlocked.
    832  */
    833 void
    834 lwp_exit_switchaway(lwp_t *l)
    835 {
    836 	struct cpu_info *ci;
    837 	struct lwp *newl;
    838 	struct bintime bt;
    839 
    840 	ci = l->l_cpu;
    841 
    842 	KASSERT(kpreempt_disabled());
    843 	KASSERT(l->l_stat == LSZOMB || l->l_stat == LSIDL);
    844 	KASSERT(ci == curcpu());
    845 	LOCKDEBUG_BARRIER(NULL, 0);
    846 
    847 #ifdef KSTACK_CHECK_MAGIC
    848 	kstack_check_magic(l);
    849 #endif
    850 
    851 	/* Count time spent in current system call */
    852 	SYSCALL_TIME_SLEEP(l);
    853 	binuptime(&bt);
    854 	updatertime(l, &bt);
    855 
    856 	/* Must stay at IPL_SCHED even after releasing run queue lock. */
    857 	(void)splsched();
    858 
    859 	/*
    860 	 * Let sched_nextlwp() select the LWP to run the CPU next.
    861 	 * If no LWP is runnable, select the idle LWP.
    862 	 *
    863 	 * Note that spc_lwplock might not necessary be held, and
    864 	 * new thread would be unlocked after setting the LWP-lock.
    865 	 */
    866 	spc_lock(ci);
    867 #ifndef __HAVE_FAST_SOFTINTS
    868 	if (ci->ci_data.cpu_softints != 0) {
    869 		/* There are pending soft interrupts, so pick one. */
    870 		newl = softint_picklwp();
    871 		newl->l_stat = LSONPROC;
    872 		newl->l_pflag |= LP_RUNNING;
    873 	} else
    874 #endif	/* !__HAVE_FAST_SOFTINTS */
    875 	{
    876 		newl = nextlwp(ci, &ci->ci_schedstate);
    877 	}
    878 
    879 	/* Update the new LWP's start time. */
    880 	newl->l_stime = bt;
    881 	l->l_pflag &= ~LP_RUNNING;
    882 
    883 	/*
    884 	 * ci_curlwp changes when a fast soft interrupt occurs.
    885 	 * We use cpu_onproc to keep track of which kernel or
    886 	 * user thread is running 'underneath' the software
    887 	 * interrupt.  This is important for time accounting,
    888 	 * itimers and forcing user threads to preempt (aston).
    889 	 */
    890 	ci->ci_data.cpu_onproc = newl;
    891 
    892 	/*
    893 	 * Preemption related tasks.  Must be done with the current
    894 	 * CPU locked.
    895 	 */
    896 	cpu_did_resched(l);
    897 
    898 	/* Unlock the run queue. */
    899 	spc_unlock(ci);
    900 
    901 	/* Count the context switch on this CPU. */
    902 	ci->ci_data.cpu_nswtch++;
    903 
    904 	/* Update status for lwpctl, if present. */
    905 	if (l->l_lwpctl != NULL)
    906 		l->l_lwpctl->lc_curcpu = LWPCTL_CPU_EXITED;
    907 
    908 	/*
    909 	 * We may need to spin-wait for if 'newl' is still
    910 	 * context switching on another CPU.
    911 	 */
    912 	if (newl->l_ctxswtch != 0) {
    913 		u_int count;
    914 		count = SPINLOCK_BACKOFF_MIN;
    915 		while (newl->l_ctxswtch)
    916 			SPINLOCK_BACKOFF(count);
    917 	}
    918 
    919 	/* Switch to the new LWP.. */
    920 	(void)cpu_switchto(NULL, newl, false);
    921 
    922 	for (;;) continue;	/* XXX: convince gcc about "noreturn" */
    923 	/* NOTREACHED */
    924 }
    925 
    926 /*
    927  * Change LWP state to be runnable, placing it on the run queue if it is
    928  * in memory, and awakening the swapper if it isn't in memory.
    929  *
    930  * Call with the process and LWP locked.  Will return with the LWP unlocked.
    931  */
    932 void
    933 setrunnable(struct lwp *l)
    934 {
    935 	struct proc *p = l->l_proc;
    936 	struct cpu_info *ci;
    937 
    938 	KASSERT((l->l_flag & LW_IDLE) == 0);
    939 	KASSERT(mutex_owned(p->p_lock));
    940 	KASSERT(lwp_locked(l, NULL));
    941 	KASSERT(l->l_mutex != l->l_cpu->ci_schedstate.spc_mutex);
    942 
    943 	switch (l->l_stat) {
    944 	case LSSTOP:
    945 		/*
    946 		 * If we're being traced (possibly because someone attached us
    947 		 * while we were stopped), check for a signal from the debugger.
    948 		 */
    949 		if ((p->p_slflag & PSL_TRACED) != 0 && p->p_xstat != 0)
    950 			signotify(l);
    951 		p->p_nrlwps++;
    952 		break;
    953 	case LSSUSPENDED:
    954 		l->l_flag &= ~LW_WSUSPEND;
    955 		p->p_nrlwps++;
    956 		cv_broadcast(&p->p_lwpcv);
    957 		break;
    958 	case LSSLEEP:
    959 		KASSERT(l->l_wchan != NULL);
    960 		break;
    961 	default:
    962 		panic("setrunnable: lwp %p state was %d", l, l->l_stat);
    963 	}
    964 
    965 #ifdef KERN_SA
    966 	if (l->l_proc->p_sa)
    967 		sa_awaken(l);
    968 #endif /* KERN_SA */
    969 
    970 	/*
    971 	 * If the LWP was sleeping interruptably, then it's OK to start it
    972 	 * again.  If not, mark it as still sleeping.
    973 	 */
    974 	if (l->l_wchan != NULL) {
    975 		l->l_stat = LSSLEEP;
    976 		/* lwp_unsleep() will release the lock. */
    977 		lwp_unsleep(l, true);
    978 		return;
    979 	}
    980 
    981 	/*
    982 	 * If the LWP is still on the CPU, mark it as LSONPROC.  It may be
    983 	 * about to call mi_switch(), in which case it will yield.
    984 	 */
    985 	if ((l->l_pflag & LP_RUNNING) != 0) {
    986 		l->l_stat = LSONPROC;
    987 		l->l_slptime = 0;
    988 		lwp_unlock(l);
    989 		return;
    990 	}
    991 
    992 	/*
    993 	 * Look for a CPU to run.
    994 	 * Set the LWP runnable.
    995 	 */
    996 	ci = sched_takecpu(l);
    997 	l->l_cpu = ci;
    998 	spc_lock(ci);
    999 	lwp_unlock_to(l, ci->ci_schedstate.spc_mutex);
   1000 	sched_setrunnable(l);
   1001 	l->l_stat = LSRUN;
   1002 	l->l_slptime = 0;
   1003 
   1004 	/*
   1005 	 * If thread is swapped out - wake the swapper to bring it back in.
   1006 	 * Otherwise, enter it into a run queue.
   1007 	 */
   1008 	if (l->l_flag & LW_INMEM) {
   1009 		sched_enqueue(l, false);
   1010 		resched_cpu(l);
   1011 		lwp_unlock(l);
   1012 	} else {
   1013 		lwp_unlock(l);
   1014 		uvm_kick_scheduler();
   1015 	}
   1016 }
   1017 
   1018 /*
   1019  * suspendsched:
   1020  *
   1021  *	Convert all non-L_SYSTEM LSSLEEP or LSRUN LWPs to LSSUSPENDED.
   1022  */
   1023 void
   1024 suspendsched(void)
   1025 {
   1026 	CPU_INFO_ITERATOR cii;
   1027 	struct cpu_info *ci;
   1028 	struct lwp *l;
   1029 	struct proc *p;
   1030 
   1031 	/*
   1032 	 * We do this by process in order not to violate the locking rules.
   1033 	 */
   1034 	mutex_enter(proc_lock);
   1035 	PROCLIST_FOREACH(p, &allproc) {
   1036 		if ((p->p_flag & PK_MARKER) != 0)
   1037 			continue;
   1038 
   1039 		mutex_enter(p->p_lock);
   1040 		if ((p->p_flag & PK_SYSTEM) != 0) {
   1041 			mutex_exit(p->p_lock);
   1042 			continue;
   1043 		}
   1044 
   1045 		p->p_stat = SSTOP;
   1046 
   1047 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
   1048 			if (l == curlwp)
   1049 				continue;
   1050 
   1051 			lwp_lock(l);
   1052 
   1053 			/*
   1054 			 * Set L_WREBOOT so that the LWP will suspend itself
   1055 			 * when it tries to return to user mode.  We want to
   1056 			 * try and get to get as many LWPs as possible to
   1057 			 * the user / kernel boundary, so that they will
   1058 			 * release any locks that they hold.
   1059 			 */
   1060 			l->l_flag |= (LW_WREBOOT | LW_WSUSPEND);
   1061 
   1062 			if (l->l_stat == LSSLEEP &&
   1063 			    (l->l_flag & LW_SINTR) != 0) {
   1064 				/* setrunnable() will release the lock. */
   1065 				setrunnable(l);
   1066 				continue;
   1067 			}
   1068 
   1069 			lwp_unlock(l);
   1070 		}
   1071 
   1072 		mutex_exit(p->p_lock);
   1073 	}
   1074 	mutex_exit(proc_lock);
   1075 
   1076 	/*
   1077 	 * Kick all CPUs to make them preempt any LWPs running in user mode.
   1078 	 * They'll trap into the kernel and suspend themselves in userret().
   1079 	 */
   1080 	for (CPU_INFO_FOREACH(cii, ci)) {
   1081 		spc_lock(ci);
   1082 		cpu_need_resched(ci, RESCHED_IMMED);
   1083 		spc_unlock(ci);
   1084 	}
   1085 }
   1086 
   1087 /*
   1088  * sched_unsleep:
   1089  *
   1090  *	The is called when the LWP has not been awoken normally but instead
   1091  *	interrupted: for example, if the sleep timed out.  Because of this,
   1092  *	it's not a valid action for running or idle LWPs.
   1093  */
   1094 static u_int
   1095 sched_unsleep(struct lwp *l, bool cleanup)
   1096 {
   1097 
   1098 	lwp_unlock(l);
   1099 	panic("sched_unsleep");
   1100 }
   1101 
   1102 static void
   1103 resched_cpu(struct lwp *l)
   1104 {
   1105 	struct cpu_info *ci = ci = l->l_cpu;
   1106 
   1107 	KASSERT(lwp_locked(l, NULL));
   1108 	if (lwp_eprio(l) > ci->ci_schedstate.spc_curpriority)
   1109 		cpu_need_resched(ci, 0);
   1110 }
   1111 
   1112 static void
   1113 sched_changepri(struct lwp *l, pri_t pri)
   1114 {
   1115 
   1116 	KASSERT(lwp_locked(l, NULL));
   1117 
   1118 	if (l->l_stat == LSRUN && (l->l_flag & LW_INMEM) != 0) {
   1119 		KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
   1120 		sched_dequeue(l);
   1121 		l->l_priority = pri;
   1122 		sched_enqueue(l, false);
   1123 	} else {
   1124 		l->l_priority = pri;
   1125 	}
   1126 	resched_cpu(l);
   1127 }
   1128 
   1129 static void
   1130 sched_lendpri(struct lwp *l, pri_t pri)
   1131 {
   1132 
   1133 	KASSERT(lwp_locked(l, NULL));
   1134 
   1135 	if (l->l_stat == LSRUN && (l->l_flag & LW_INMEM) != 0) {
   1136 		KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
   1137 		sched_dequeue(l);
   1138 		l->l_inheritedprio = pri;
   1139 		sched_enqueue(l, false);
   1140 	} else {
   1141 		l->l_inheritedprio = pri;
   1142 	}
   1143 	resched_cpu(l);
   1144 }
   1145 
   1146 struct lwp *
   1147 syncobj_noowner(wchan_t wchan)
   1148 {
   1149 
   1150 	return NULL;
   1151 }
   1152 
   1153 /* Decay 95% of proc::p_pctcpu in 60 seconds, ccpu = exp(-1/20) */
   1154 const fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;
   1155 
   1156 /*
   1157  * sched_pstats:
   1158  *
   1159  * Update process statistics and check CPU resource allocation.
   1160  * Call scheduler-specific hook to eventually adjust process/LWP
   1161  * priorities.
   1162  */
   1163 /* ARGSUSED */
   1164 void
   1165 sched_pstats(void *arg)
   1166 {
   1167 	const int clkhz = (stathz != 0 ? stathz : hz);
   1168 	struct rlimit *rlim;
   1169 	struct lwp *l;
   1170 	struct proc *p;
   1171 	long runtm;
   1172 	fixpt_t lpctcpu;
   1173 	u_int lcpticks;
   1174 	int sig;
   1175 
   1176 	sched_pstats_ticks++;
   1177 
   1178 	mutex_enter(proc_lock);
   1179 	PROCLIST_FOREACH(p, &allproc) {
   1180 		if (__predict_false((p->p_flag & PK_MARKER) != 0))
   1181 			continue;
   1182 
   1183 		/*
   1184 		 * Increment time in/out of memory and sleep
   1185 		 * time (if sleeping), ignore overflow.
   1186 		 */
   1187 		mutex_enter(p->p_lock);
   1188 		runtm = p->p_rtime.sec;
   1189 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
   1190 			if (__predict_false((l->l_flag & LW_IDLE) != 0))
   1191 				continue;
   1192 			lwp_lock(l);
   1193 			runtm += l->l_rtime.sec;
   1194 			l->l_swtime++;
   1195 			sched_lwp_stats(l);
   1196 			lwp_unlock(l);
   1197 
   1198 			l->l_pctcpu = (l->l_pctcpu * ccpu) >> FSHIFT;
   1199 			if (l->l_slptime != 0)
   1200 				continue;
   1201 
   1202 			lpctcpu = l->l_pctcpu;
   1203 			lcpticks = atomic_swap_uint(&l->l_cpticks, 0);
   1204 			lpctcpu += ((FSCALE - ccpu) *
   1205 			    (lcpticks * FSCALE / clkhz)) >> FSHIFT;
   1206 			l->l_pctcpu = lpctcpu;
   1207 		}
   1208 		/* Calculating p_pctcpu only for ps(1) */
   1209 		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
   1210 
   1211 		/*
   1212 		 * Check if the process exceeds its CPU resource allocation.
   1213 		 * If over max, kill it.
   1214 		 */
   1215 		rlim = &p->p_rlimit[RLIMIT_CPU];
   1216 		sig = 0;
   1217 		if (__predict_false(runtm >= rlim->rlim_cur)) {
   1218 			if (runtm >= rlim->rlim_max)
   1219 				sig = SIGKILL;
   1220 			else {
   1221 				sig = SIGXCPU;
   1222 				if (rlim->rlim_cur < rlim->rlim_max)
   1223 					rlim->rlim_cur += 5;
   1224 			}
   1225 		}
   1226 		mutex_exit(p->p_lock);
   1227 		if (__predict_false(sig))
   1228 			psignal(p, sig);
   1229 	}
   1230 	mutex_exit(proc_lock);
   1231 	uvm_meter();
   1232 	cv_wakeup(&lbolt);
   1233 	callout_schedule(&sched_pstats_ch, hz);
   1234 }
   1235