Home | History | Annotate | Line # | Download | only in kern
kern_synch.c revision 1.227
      1 /*	$NetBSD: kern_synch.c,v 1.227 2008/04/13 22:54:19 yamt 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  * 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) 2007, 2008 Mindaugas Rasiukevicius <rmind at NetBSD org>
     43  * All rights reserved.
     44  *
     45  * Redistribution and use in source and binary forms, with or without
     46  * modification, are permitted provided that the following conditions
     47  * are met:
     48  * 1. Redistributions of source code must retain the above copyright
     49  *    notice, this list of conditions and the following disclaimer.
     50  * 2. Redistributions in binary form must reproduce the above copyright
     51  *    notice, this list of conditions and the following disclaimer in the
     52  *    documentation and/or other materials provided with the distribution.
     53  *
     54  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     64  * SUCH DAMAGE.
     65  */
     66 
     67 /*-
     68  * Copyright (c) 1982, 1986, 1990, 1991, 1993
     69  *	The Regents of the University of California.  All rights reserved.
     70  * (c) UNIX System Laboratories, Inc.
     71  * All or some portions of this file are derived from material licensed
     72  * to the University of California by American Telephone and Telegraph
     73  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     74  * the permission of UNIX System Laboratories, Inc.
     75  *
     76  * Redistribution and use in source and binary forms, with or without
     77  * modification, are permitted provided that the following conditions
     78  * are met:
     79  * 1. Redistributions of source code must retain the above copyright
     80  *    notice, this list of conditions and the following disclaimer.
     81  * 2. Redistributions in binary form must reproduce the above copyright
     82  *    notice, this list of conditions and the following disclaimer in the
     83  *    documentation and/or other materials provided with the distribution.
     84  * 3. Neither the name of the University nor the names of its contributors
     85  *    may be used to endorse or promote products derived from this software
     86  *    without specific prior written permission.
     87  *
     88  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     89  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     90  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     91  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     92  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     93  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     94  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     95  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     96  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     97  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     98  * SUCH DAMAGE.
     99  *
    100  *	@(#)kern_synch.c	8.9 (Berkeley) 5/19/95
    101  */
    102 
    103 #include <sys/cdefs.h>
    104 __KERNEL_RCSID(0, "$NetBSD: kern_synch.c,v 1.227 2008/04/13 22:54:19 yamt Exp $");
    105 
    106 #include "opt_kstack.h"
    107 #include "opt_lockdebug.h"
    108 #include "opt_multiprocessor.h"
    109 #include "opt_perfctrs.h"
    110 
    111 #define	__MUTEX_PRIVATE
    112 
    113 #include <sys/param.h>
    114 #include <sys/systm.h>
    115 #include <sys/proc.h>
    116 #include <sys/kernel.h>
    117 #if defined(PERFCTRS)
    118 #include <sys/pmc.h>
    119 #endif
    120 #include <sys/cpu.h>
    121 #include <sys/resourcevar.h>
    122 #include <sys/sched.h>
    123 #include <sys/syscall_stats.h>
    124 #include <sys/sleepq.h>
    125 #include <sys/lockdebug.h>
    126 #include <sys/evcnt.h>
    127 #include <sys/intr.h>
    128 #include <sys/lwpctl.h>
    129 #include <sys/atomic.h>
    130 #include <sys/simplelock.h>
    131 #include <sys/bitops.h>
    132 #include <sys/kmem.h>
    133 #include <sys/sysctl.h>
    134 #include <sys/idle.h>
    135 
    136 #include <uvm/uvm_extern.h>
    137 
    138 /*
    139  * Priority related defintions.
    140  */
    141 #define	PRI_TS_COUNT	(NPRI_USER)
    142 #define	PRI_RT_COUNT	(PRI_COUNT - PRI_TS_COUNT)
    143 #define	PRI_HTS_RANGE	(PRI_TS_COUNT / 10)
    144 
    145 #define	PRI_HIGHEST_TS	(MAXPRI_USER)
    146 
    147 /*
    148  * Bits per map.
    149  */
    150 #define	BITMAP_BITS	(32)
    151 #define	BITMAP_SHIFT	(5)
    152 #define	BITMAP_MSB	(0x80000000U)
    153 #define	BITMAP_MASK	(BITMAP_BITS - 1)
    154 
    155 /*
    156  * Structures, runqueue.
    157  */
    158 
    159 typedef struct {
    160 	TAILQ_HEAD(, lwp) q_head;
    161 } queue_t;
    162 
    163 typedef struct {
    164 	/* Lock and bitmap */
    165 	uint32_t	r_bitmap[PRI_COUNT >> BITMAP_SHIFT];
    166 	/* Counters */
    167 	u_int		r_count;	/* Count of the threads */
    168 	u_int		r_avgcount;	/* Average count of threads */
    169 	u_int		r_mcount;	/* Count of migratable threads */
    170 	/* Runqueues */
    171 	queue_t		r_rt_queue[PRI_RT_COUNT];
    172 	queue_t		r_ts_queue[PRI_TS_COUNT];
    173 } runqueue_t;
    174 
    175 static u_int	sched_unsleep(struct lwp *, bool);
    176 static void	sched_changepri(struct lwp *, pri_t);
    177 static void	sched_lendpri(struct lwp *, pri_t);
    178 static void	*sched_getrq(runqueue_t *, const pri_t);
    179 #ifdef MULTIPROCESSOR
    180 static lwp_t	*sched_catchlwp(void);
    181 static void	sched_balance(void *);
    182 #endif
    183 
    184 syncobj_t sleep_syncobj = {
    185 	SOBJ_SLEEPQ_SORTED,
    186 	sleepq_unsleep,
    187 	sleepq_changepri,
    188 	sleepq_lendpri,
    189 	syncobj_noowner,
    190 };
    191 
    192 syncobj_t sched_syncobj = {
    193 	SOBJ_SLEEPQ_SORTED,
    194 	sched_unsleep,
    195 	sched_changepri,
    196 	sched_lendpri,
    197 	syncobj_noowner,
    198 };
    199 
    200 const int 	schedppq = 1;
    201 callout_t 	sched_pstats_ch;
    202 unsigned	sched_pstats_ticks;
    203 kcondvar_t	lbolt;			/* once a second sleep address */
    204 
    205 /*
    206  * Migration and balancing.
    207  */
    208 static u_int	cacheht_time;		/* Cache hotness time */
    209 static u_int	min_catch;		/* Minimal LWP count for catching */
    210 static u_int	balance_period;		/* Balance period */
    211 static struct cpu_info *worker_ci;	/* Victim CPU */
    212 #ifdef MULTIPROCESSOR
    213 static struct callout balance_ch;	/* Callout of balancer */
    214 #endif
    215 
    216 /*
    217  * During autoconfiguration or after a panic, a sleep will simply lower the
    218  * priority briefly to allow interrupts, then return.  The priority to be
    219  * used (safepri) is machine-dependent, thus this value is initialized and
    220  * maintained in the machine-dependent layers.  This priority will typically
    221  * be 0, or the lowest priority that is safe for use on the interrupt stack;
    222  * it can be made higher to block network software interrupts after panics.
    223  */
    224 int	safepri;
    225 
    226 /*
    227  * OBSOLETE INTERFACE
    228  *
    229  * General sleep call.  Suspends the current process until a wakeup is
    230  * performed on the specified identifier.  The process will then be made
    231  * runnable with the specified priority.  Sleeps at most timo/hz seconds (0
    232  * means no timeout).  If pri includes PCATCH flag, signals are checked
    233  * before and after sleeping, else signals are not checked.  Returns 0 if
    234  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
    235  * signal needs to be delivered, ERESTART is returned if the current system
    236  * call should be restarted if possible, and EINTR is returned if the system
    237  * call should be interrupted by the signal (return EINTR).
    238  *
    239  * The interlock is held until we are on a sleep queue. The interlock will
    240  * be locked before returning back to the caller unless the PNORELOCK flag
    241  * is specified, in which case the interlock will always be unlocked upon
    242  * return.
    243  */
    244 int
    245 ltsleep(wchan_t ident, pri_t priority, const char *wmesg, int timo,
    246 	volatile struct simplelock *interlock)
    247 {
    248 	struct lwp *l = curlwp;
    249 	sleepq_t *sq;
    250 	int error;
    251 
    252 	KASSERT((l->l_pflag & LP_INTR) == 0);
    253 
    254 	if (sleepq_dontsleep(l)) {
    255 		(void)sleepq_abort(NULL, 0);
    256 		if ((priority & PNORELOCK) != 0)
    257 			simple_unlock(interlock);
    258 		return 0;
    259 	}
    260 
    261 	l->l_kpriority = true;
    262 	sq = sleeptab_lookup(&sleeptab, ident);
    263 	sleepq_enter(sq, l);
    264 	sleepq_enqueue(sq, ident, wmesg, &sleep_syncobj);
    265 
    266 	if (interlock != NULL) {
    267 		KASSERT(simple_lock_held(interlock));
    268 		simple_unlock(interlock);
    269 	}
    270 
    271 	error = sleepq_block(timo, priority & PCATCH);
    272 
    273 	if (interlock != NULL && (priority & PNORELOCK) == 0)
    274 		simple_lock(interlock);
    275 
    276 	return error;
    277 }
    278 
    279 int
    280 mtsleep(wchan_t ident, pri_t priority, const char *wmesg, int timo,
    281 	kmutex_t *mtx)
    282 {
    283 	struct lwp *l = curlwp;
    284 	sleepq_t *sq;
    285 	int error;
    286 
    287 	KASSERT((l->l_pflag & LP_INTR) == 0);
    288 
    289 	if (sleepq_dontsleep(l)) {
    290 		(void)sleepq_abort(mtx, (priority & PNORELOCK) != 0);
    291 		return 0;
    292 	}
    293 
    294 	l->l_kpriority = true;
    295 	sq = sleeptab_lookup(&sleeptab, ident);
    296 	sleepq_enter(sq, l);
    297 	sleepq_enqueue(sq, ident, wmesg, &sleep_syncobj);
    298 	mutex_exit(mtx);
    299 	error = sleepq_block(timo, priority & PCATCH);
    300 
    301 	if ((priority & PNORELOCK) == 0)
    302 		mutex_enter(mtx);
    303 
    304 	return error;
    305 }
    306 
    307 /*
    308  * General sleep call for situations where a wake-up is not expected.
    309  */
    310 int
    311 kpause(const char *wmesg, bool intr, int timo, kmutex_t *mtx)
    312 {
    313 	struct lwp *l = curlwp;
    314 	sleepq_t *sq;
    315 	int error;
    316 
    317 	if (sleepq_dontsleep(l))
    318 		return sleepq_abort(NULL, 0);
    319 
    320 	if (mtx != NULL)
    321 		mutex_exit(mtx);
    322 	l->l_kpriority = true;
    323 	sq = sleeptab_lookup(&sleeptab, l);
    324 	sleepq_enter(sq, l);
    325 	sleepq_enqueue(sq, l, wmesg, &sleep_syncobj);
    326 	error = sleepq_block(timo, intr);
    327 	if (mtx != NULL)
    328 		mutex_enter(mtx);
    329 
    330 	return error;
    331 }
    332 
    333 /*
    334  * OBSOLETE INTERFACE
    335  *
    336  * Make all processes sleeping on the specified identifier runnable.
    337  */
    338 void
    339 wakeup(wchan_t ident)
    340 {
    341 	sleepq_t *sq;
    342 
    343 	if (cold)
    344 		return;
    345 
    346 	sq = sleeptab_lookup(&sleeptab, ident);
    347 	sleepq_wake(sq, ident, (u_int)-1);
    348 }
    349 
    350 /*
    351  * OBSOLETE INTERFACE
    352  *
    353  * Make the highest priority process first in line on the specified
    354  * identifier runnable.
    355  */
    356 void
    357 wakeup_one(wchan_t ident)
    358 {
    359 	sleepq_t *sq;
    360 
    361 	if (cold)
    362 		return;
    363 
    364 	sq = sleeptab_lookup(&sleeptab, ident);
    365 	sleepq_wake(sq, ident, 1);
    366 }
    367 
    368 
    369 /*
    370  * General yield call.  Puts the current process back on its run queue and
    371  * performs a voluntary context switch.  Should only be called when the
    372  * current process explicitly requests it (eg sched_yield(2)).
    373  */
    374 void
    375 yield(void)
    376 {
    377 	struct lwp *l = curlwp;
    378 
    379 	KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
    380 	lwp_lock(l);
    381 	KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_lwplock));
    382 	KASSERT(l->l_stat == LSONPROC);
    383 	l->l_kpriority = false;
    384 	(void)mi_switch(l);
    385 	KERNEL_LOCK(l->l_biglocks, l);
    386 }
    387 
    388 /*
    389  * General preemption call.  Puts the current process back on its run queue
    390  * and performs an involuntary context switch.
    391  */
    392 void
    393 preempt(void)
    394 {
    395 	struct lwp *l = curlwp;
    396 
    397 	KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
    398 	lwp_lock(l);
    399 	KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_lwplock));
    400 	KASSERT(l->l_stat == LSONPROC);
    401 	l->l_kpriority = false;
    402 	l->l_nivcsw++;
    403 	(void)mi_switch(l);
    404 	KERNEL_LOCK(l->l_biglocks, l);
    405 }
    406 
    407 /*
    408  * Compute the amount of time during which the current lwp was running.
    409  *
    410  * - update l_rtime unless it's an idle lwp.
    411  */
    412 
    413 void
    414 updatertime(lwp_t *l, const struct bintime *now)
    415 {
    416 
    417 	if ((l->l_flag & LW_IDLE) != 0)
    418 		return;
    419 
    420 	/* rtime += now - stime */
    421 	bintime_add(&l->l_rtime, now);
    422 	bintime_sub(&l->l_rtime, &l->l_stime);
    423 }
    424 
    425 /*
    426  * The machine independent parts of context switch.
    427  *
    428  * Returns 1 if another LWP was actually run.
    429  */
    430 int
    431 mi_switch(lwp_t *l)
    432 {
    433 	struct cpu_info *ci, *tci = NULL;
    434 	struct schedstate_percpu *spc;
    435 	struct lwp *newl;
    436 	int retval, oldspl;
    437 	struct bintime bt;
    438 	bool returning;
    439 
    440 	KASSERT(lwp_locked(l, NULL));
    441 	LOCKDEBUG_BARRIER(l->l_mutex, 1);
    442 
    443 #ifdef KSTACK_CHECK_MAGIC
    444 	kstack_check_magic(l);
    445 #endif
    446 
    447 	binuptime(&bt);
    448 
    449 	KDASSERT(l->l_cpu == curcpu());
    450 	ci = l->l_cpu;
    451 	spc = &ci->ci_schedstate;
    452 	returning = false;
    453 	newl = NULL;
    454 
    455 	/*
    456 	 * If we have been asked to switch to a specific LWP, then there
    457 	 * is no need to inspect the run queues.  If a soft interrupt is
    458 	 * blocking, then return to the interrupted thread without adjusting
    459 	 * VM context or its start time: neither have been changed in order
    460 	 * to take the interrupt.
    461 	 */
    462 	if (l->l_switchto != NULL) {
    463 		if ((l->l_pflag & LP_INTR) != 0) {
    464 			returning = true;
    465 			softint_block(l);
    466 			if ((l->l_flag & LW_TIMEINTR) != 0)
    467 				updatertime(l, &bt);
    468 		}
    469 		newl = l->l_switchto;
    470 		l->l_switchto = NULL;
    471 	}
    472 #ifndef __HAVE_FAST_SOFTINTS
    473 	else if (ci->ci_data.cpu_softints != 0) {
    474 		/* There are pending soft interrupts, so pick one. */
    475 		newl = softint_picklwp();
    476 		newl->l_stat = LSONPROC;
    477 		newl->l_flag |= LW_RUNNING;
    478 	}
    479 #endif	/* !__HAVE_FAST_SOFTINTS */
    480 
    481 	/* Count time spent in current system call */
    482 	if (!returning) {
    483 		SYSCALL_TIME_SLEEP(l);
    484 
    485 		/*
    486 		 * XXXSMP If we are using h/w performance counters,
    487 		 * save context.
    488 		 */
    489 #if PERFCTRS
    490 		if (PMC_ENABLED(l->l_proc)) {
    491 			pmc_save_context(l->l_proc);
    492 		}
    493 #endif
    494 		updatertime(l, &bt);
    495 	}
    496 
    497 	/*
    498 	 * If on the CPU and we have gotten this far, then we must yield.
    499 	 */
    500 	KASSERT(l->l_stat != LSRUN);
    501 	if (l->l_stat == LSONPROC && (l->l_target_cpu || l != newl)) {
    502 		KASSERT(lwp_locked(l, spc->spc_lwplock));
    503 
    504 		if (l->l_target_cpu == l->l_cpu) {
    505 			l->l_target_cpu = NULL;
    506 		} else {
    507 			tci = l->l_target_cpu;
    508 		}
    509 
    510 		if (__predict_false(tci != NULL)) {
    511 			/* Double-lock the runqueues */
    512 			spc_dlock(ci, tci);
    513 		} else {
    514 			/* Lock the runqueue */
    515 			spc_lock(ci);
    516 		}
    517 
    518 		if ((l->l_flag & LW_IDLE) == 0) {
    519 			l->l_stat = LSRUN;
    520 			if (__predict_false(tci != NULL)) {
    521 				/*
    522 				 * Set the new CPU, lock and unset the
    523 				 * l_target_cpu - thread will be enqueued
    524 				 * to the runqueue of target CPU.
    525 				 */
    526 				l->l_cpu = tci;
    527 				lwp_setlock(l, tci->ci_schedstate.spc_mutex);
    528 				l->l_target_cpu = NULL;
    529 			} else {
    530 				lwp_setlock(l, spc->spc_mutex);
    531 			}
    532 			sched_enqueue(l, true);
    533 		} else {
    534 			KASSERT(tci == NULL);
    535 			l->l_stat = LSIDL;
    536 		}
    537 	} else {
    538 		/* Lock the runqueue */
    539 		spc_lock(ci);
    540 	}
    541 
    542 	/*
    543 	 * Let sched_nextlwp() select the LWP to run the CPU next.
    544 	 * If no LWP is runnable, select the idle LWP.
    545 	 *
    546 	 * Note that spc_lwplock might not necessary be held, and
    547 	 * new thread would be unlocked after setting the LWP-lock.
    548 	 */
    549 	if (newl == NULL) {
    550 		newl = sched_nextlwp();
    551 		if (newl != NULL) {
    552 			sched_dequeue(newl);
    553 			KASSERT(lwp_locked(newl, spc->spc_mutex));
    554 			newl->l_stat = LSONPROC;
    555 			newl->l_cpu = ci;
    556 			newl->l_flag |= LW_RUNNING;
    557 			lwp_setlock(newl, spc->spc_lwplock);
    558 		} else {
    559 			newl = ci->ci_data.cpu_idlelwp;
    560 			newl->l_stat = LSONPROC;
    561 			newl->l_flag |= LW_RUNNING;
    562 		}
    563 		/*
    564 		 * Only clear want_resched if there are no
    565 		 * pending (slow) software interrupts.
    566 		 */
    567 		ci->ci_want_resched = ci->ci_data.cpu_softints;
    568 		spc->spc_flags &= ~SPCF_SWITCHCLEAR;
    569 		spc->spc_curpriority = lwp_eprio(newl);
    570 	}
    571 
    572 	/* Items that must be updated with the CPU locked. */
    573 	if (!returning) {
    574 		/* Update the new LWP's start time. */
    575 		newl->l_stime = bt;
    576 
    577 		/*
    578 		 * ci_curlwp changes when a fast soft interrupt occurs.
    579 		 * We use cpu_onproc to keep track of which kernel or
    580 		 * user thread is running 'underneath' the software
    581 		 * interrupt.  This is important for time accounting,
    582 		 * itimers and forcing user threads to preempt (aston).
    583 		 */
    584 		ci->ci_data.cpu_onproc = newl;
    585 	}
    586 
    587 	if (l != newl) {
    588 		struct lwp *prevlwp;
    589 
    590 		/* Release all locks, but leave the current LWP locked */
    591 		if (l->l_mutex == l->l_cpu->ci_schedstate.spc_mutex) {
    592 			/*
    593 			 * In case of migration, drop the local runqueue
    594 			 * lock, thread is on other runqueue now.
    595 			 */
    596 			if (__predict_false(tci != NULL))
    597 				spc_unlock(ci);
    598 			/*
    599 			 * Drop spc_lwplock, if the current LWP has been moved
    600 			 * to the run queue (it is now locked by spc_mutex).
    601 			 */
    602 			mutex_spin_exit(spc->spc_lwplock);
    603 		} else {
    604 			/*
    605 			 * Otherwise, drop the spc_mutex, we are done with the
    606 			 * run queues.
    607 			 */
    608 			mutex_spin_exit(spc->spc_mutex);
    609 			KASSERT(tci == NULL);
    610 		}
    611 
    612 		/*
    613 		 * Mark that context switch is going to be perfomed
    614 		 * for this LWP, to protect it from being switched
    615 		 * to on another CPU.
    616 		 */
    617 		KASSERT(l->l_ctxswtch == 0);
    618 		l->l_ctxswtch = 1;
    619 		l->l_ncsw++;
    620 		l->l_flag &= ~LW_RUNNING;
    621 
    622 		/*
    623 		 * Increase the count of spin-mutexes before the release
    624 		 * of the last lock - we must remain at IPL_SCHED during
    625 		 * the context switch.
    626 		 */
    627 		oldspl = MUTEX_SPIN_OLDSPL(ci);
    628 		ci->ci_mtx_count--;
    629 		lwp_unlock(l);
    630 
    631 		/* Count the context switch on this CPU. */
    632 		ci->ci_data.cpu_nswtch++;
    633 
    634 		/* Update status for lwpctl, if present. */
    635 		if (l->l_lwpctl != NULL)
    636 			l->l_lwpctl->lc_curcpu = LWPCTL_CPU_NONE;
    637 
    638 		/*
    639 		 * Save old VM context, unless a soft interrupt
    640 		 * handler is blocking.
    641 		 */
    642 		if (!returning)
    643 			pmap_deactivate(l);
    644 
    645 		/*
    646 		 * We may need to spin-wait for if 'newl' is still
    647 		 * context switching on another CPU.
    648 		 */
    649 		if (newl->l_ctxswtch != 0) {
    650 			u_int count;
    651 			count = SPINLOCK_BACKOFF_MIN;
    652 			while (newl->l_ctxswtch)
    653 				SPINLOCK_BACKOFF(count);
    654 		}
    655 
    656 		/* Switch to the new LWP.. */
    657 		prevlwp = cpu_switchto(l, newl, returning);
    658 		ci = curcpu();
    659 
    660 		/*
    661 		 * Switched away - we have new curlwp.
    662 		 * Restore VM context and IPL.
    663 		 */
    664 		pmap_activate(l);
    665 		if (prevlwp != NULL) {
    666 			/* Normalize the count of the spin-mutexes */
    667 			ci->ci_mtx_count++;
    668 			/* Unmark the state of context switch */
    669 			membar_exit();
    670 			prevlwp->l_ctxswtch = 0;
    671 		}
    672 		splx(oldspl);
    673 
    674 		/* Update status for lwpctl, if present. */
    675 		if (l->l_lwpctl != NULL) {
    676 			l->l_lwpctl->lc_curcpu = (int)cpu_index(ci);
    677 			l->l_lwpctl->lc_pctr++;
    678 		}
    679 
    680 		retval = 1;
    681 	} else {
    682 		/* Nothing to do - just unlock and return. */
    683 		KASSERT(tci == NULL);
    684 		spc_unlock(ci);
    685 		lwp_unlock(l);
    686 		retval = 0;
    687 	}
    688 
    689 	KASSERT(l == curlwp);
    690 	KASSERT(l->l_stat == LSONPROC);
    691 	KASSERT(l->l_cpu == ci);
    692 
    693 	/*
    694 	 * XXXSMP If we are using h/w performance counters, restore context.
    695 	 */
    696 #if PERFCTRS
    697 	if (PMC_ENABLED(l->l_proc)) {
    698 		pmc_restore_context(l->l_proc);
    699 	}
    700 #endif
    701 	SYSCALL_TIME_WAKEUP(l);
    702 	LOCKDEBUG_BARRIER(NULL, 1);
    703 
    704 	return retval;
    705 }
    706 
    707 /*
    708  * Change process state to be runnable, placing it on the run queue if it is
    709  * in memory, and awakening the swapper if it isn't in memory.
    710  *
    711  * Call with the process and LWP locked.  Will return with the LWP unlocked.
    712  */
    713 void
    714 setrunnable(struct lwp *l)
    715 {
    716 	struct proc *p = l->l_proc;
    717 	struct cpu_info *ci;
    718 	sigset_t *ss;
    719 
    720 	KASSERT((l->l_flag & LW_IDLE) == 0);
    721 	KASSERT(mutex_owned(&p->p_smutex));
    722 	KASSERT(lwp_locked(l, NULL));
    723 	KASSERT(l->l_mutex != l->l_cpu->ci_schedstate.spc_mutex);
    724 
    725 	switch (l->l_stat) {
    726 	case LSSTOP:
    727 		/*
    728 		 * If we're being traced (possibly because someone attached us
    729 		 * while we were stopped), check for a signal from the debugger.
    730 		 */
    731 		if ((p->p_slflag & PSL_TRACED) != 0 && p->p_xstat != 0) {
    732 			if ((sigprop[p->p_xstat] & SA_TOLWP) != 0)
    733 				ss = &l->l_sigpend.sp_set;
    734 			else
    735 				ss = &p->p_sigpend.sp_set;
    736 			sigaddset(ss, p->p_xstat);
    737 			signotify(l);
    738 		}
    739 		p->p_nrlwps++;
    740 		break;
    741 	case LSSUSPENDED:
    742 		l->l_flag &= ~LW_WSUSPEND;
    743 		p->p_nrlwps++;
    744 		cv_broadcast(&p->p_lwpcv);
    745 		break;
    746 	case LSSLEEP:
    747 		KASSERT(l->l_wchan != NULL);
    748 		break;
    749 	default:
    750 		panic("setrunnable: lwp %p state was %d", l, l->l_stat);
    751 	}
    752 
    753 	/*
    754 	 * If the LWP was sleeping interruptably, then it's OK to start it
    755 	 * again.  If not, mark it as still sleeping.
    756 	 */
    757 	if (l->l_wchan != NULL) {
    758 		l->l_stat = LSSLEEP;
    759 		/* lwp_unsleep() will release the lock. */
    760 		lwp_unsleep(l, true);
    761 		return;
    762 	}
    763 
    764 	/*
    765 	 * If the LWP is still on the CPU, mark it as LSONPROC.  It may be
    766 	 * about to call mi_switch(), in which case it will yield.
    767 	 */
    768 	if ((l->l_flag & LW_RUNNING) != 0) {
    769 		l->l_stat = LSONPROC;
    770 		l->l_slptime = 0;
    771 		lwp_unlock(l);
    772 		return;
    773 	}
    774 
    775 	/*
    776 	 * Look for a CPU to run.
    777 	 * Set the LWP runnable.
    778 	 */
    779 	ci = sched_takecpu(l);
    780 	l->l_cpu = ci;
    781 	if (l->l_mutex != l->l_cpu->ci_schedstate.spc_mutex) {
    782 		lwp_unlock_to(l, ci->ci_schedstate.spc_mutex);
    783 		lwp_lock(l);
    784 	}
    785 	sched_setrunnable(l);
    786 	l->l_stat = LSRUN;
    787 	l->l_slptime = 0;
    788 
    789 	/*
    790 	 * If thread is swapped out - wake the swapper to bring it back in.
    791 	 * Otherwise, enter it into a run queue.
    792 	 */
    793 	if (l->l_flag & LW_INMEM) {
    794 		sched_enqueue(l, false);
    795 		resched_cpu(l);
    796 		lwp_unlock(l);
    797 	} else {
    798 		lwp_unlock(l);
    799 		uvm_kick_scheduler();
    800 	}
    801 }
    802 
    803 /*
    804  * suspendsched:
    805  *
    806  *	Convert all non-L_SYSTEM LSSLEEP or LSRUN LWPs to LSSUSPENDED.
    807  */
    808 void
    809 suspendsched(void)
    810 {
    811 	CPU_INFO_ITERATOR cii;
    812 	struct cpu_info *ci;
    813 	struct lwp *l;
    814 	struct proc *p;
    815 
    816 	/*
    817 	 * We do this by process in order not to violate the locking rules.
    818 	 */
    819 	mutex_enter(&proclist_lock);
    820 	PROCLIST_FOREACH(p, &allproc) {
    821 		mutex_enter(&p->p_smutex);
    822 
    823 		if ((p->p_flag & PK_SYSTEM) != 0) {
    824 			mutex_exit(&p->p_smutex);
    825 			continue;
    826 		}
    827 
    828 		p->p_stat = SSTOP;
    829 
    830 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    831 			if (l == curlwp)
    832 				continue;
    833 
    834 			lwp_lock(l);
    835 
    836 			/*
    837 			 * Set L_WREBOOT so that the LWP will suspend itself
    838 			 * when it tries to return to user mode.  We want to
    839 			 * try and get to get as many LWPs as possible to
    840 			 * the user / kernel boundary, so that they will
    841 			 * release any locks that they hold.
    842 			 */
    843 			l->l_flag |= (LW_WREBOOT | LW_WSUSPEND);
    844 
    845 			if (l->l_stat == LSSLEEP &&
    846 			    (l->l_flag & LW_SINTR) != 0) {
    847 				/* setrunnable() will release the lock. */
    848 				setrunnable(l);
    849 				continue;
    850 			}
    851 
    852 			lwp_unlock(l);
    853 		}
    854 
    855 		mutex_exit(&p->p_smutex);
    856 	}
    857 	mutex_exit(&proclist_lock);
    858 
    859 	/*
    860 	 * Kick all CPUs to make them preempt any LWPs running in user mode.
    861 	 * They'll trap into the kernel and suspend themselves in userret().
    862 	 */
    863 	for (CPU_INFO_FOREACH(cii, ci)) {
    864 		spc_lock(ci);
    865 		cpu_need_resched(ci, RESCHED_IMMED);
    866 		spc_unlock(ci);
    867 	}
    868 }
    869 
    870 /*
    871  * sched_unsleep:
    872  *
    873  *	The is called when the LWP has not been awoken normally but instead
    874  *	interrupted: for example, if the sleep timed out.  Because of this,
    875  *	it's not a valid action for running or idle LWPs.
    876  */
    877 static u_int
    878 sched_unsleep(struct lwp *l, bool cleanup)
    879 {
    880 
    881 	lwp_unlock(l);
    882 	panic("sched_unsleep");
    883 }
    884 
    885 void
    886 resched_cpu(struct lwp *l)
    887 {
    888 	struct cpu_info *ci;
    889 
    890 	/*
    891 	 * XXXSMP
    892 	 * Since l->l_cpu persists across a context switch,
    893 	 * this gives us *very weak* processor affinity, in
    894 	 * that we notify the CPU on which the process last
    895 	 * ran that it should try to switch.
    896 	 *
    897 	 * This does not guarantee that the process will run on
    898 	 * that processor next, because another processor might
    899 	 * grab it the next time it performs a context switch.
    900 	 *
    901 	 * This also does not handle the case where its last
    902 	 * CPU is running a higher-priority process, but every
    903 	 * other CPU is running a lower-priority process.  There
    904 	 * are ways to handle this situation, but they're not
    905 	 * currently very pretty, and we also need to weigh the
    906 	 * cost of moving a process from one CPU to another.
    907 	 */
    908 	ci = l->l_cpu;
    909 	if (lwp_eprio(l) > ci->ci_schedstate.spc_curpriority)
    910 		cpu_need_resched(ci, 0);
    911 }
    912 
    913 static void
    914 sched_changepri(struct lwp *l, pri_t pri)
    915 {
    916 
    917 	KASSERT(lwp_locked(l, NULL));
    918 
    919 	if (l->l_stat == LSRUN && (l->l_flag & LW_INMEM) != 0) {
    920 		KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
    921 		sched_dequeue(l);
    922 		l->l_priority = pri;
    923 		sched_enqueue(l, false);
    924 	} else {
    925 		l->l_priority = pri;
    926 	}
    927 	resched_cpu(l);
    928 }
    929 
    930 static void
    931 sched_lendpri(struct lwp *l, pri_t pri)
    932 {
    933 
    934 	KASSERT(lwp_locked(l, NULL));
    935 
    936 	if (l->l_stat == LSRUN && (l->l_flag & LW_INMEM) != 0) {
    937 		KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
    938 		sched_dequeue(l);
    939 		l->l_inheritedprio = pri;
    940 		sched_enqueue(l, false);
    941 	} else {
    942 		l->l_inheritedprio = pri;
    943 	}
    944 	resched_cpu(l);
    945 }
    946 
    947 struct lwp *
    948 syncobj_noowner(wchan_t wchan)
    949 {
    950 
    951 	return NULL;
    952 }
    953 
    954 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
    955 fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;		/* exp(-1/20) */
    956 
    957 /*
    958  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
    959  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
    960  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
    961  *
    962  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
    963  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
    964  *
    965  * If you dont want to bother with the faster/more-accurate formula, you
    966  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
    967  * (more general) method of calculating the %age of CPU used by a process.
    968  */
    969 #define	CCPU_SHIFT	(FSHIFT + 1)
    970 
    971 /*
    972  * sched_pstats:
    973  *
    974  * Update process statistics and check CPU resource allocation.
    975  * Call scheduler-specific hook to eventually adjust process/LWP
    976  * priorities.
    977  */
    978 /* ARGSUSED */
    979 void
    980 sched_pstats(void *arg)
    981 {
    982 	struct rlimit *rlim;
    983 	struct lwp *l;
    984 	struct proc *p;
    985 	int sig, clkhz;
    986 	long runtm;
    987 
    988 	sched_pstats_ticks++;
    989 
    990 	mutex_enter(&proclist_lock);
    991 	PROCLIST_FOREACH(p, &allproc) {
    992 		/*
    993 		 * Increment time in/out of memory and sleep time (if
    994 		 * sleeping).  We ignore overflow; with 16-bit int's
    995 		 * (remember them?) overflow takes 45 days.
    996 		 */
    997 		mutex_enter(&p->p_smutex);
    998 		mutex_spin_enter(&p->p_stmutex);
    999 		runtm = p->p_rtime.sec;
   1000 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
   1001 			if ((l->l_flag & LW_IDLE) != 0)
   1002 				continue;
   1003 			lwp_lock(l);
   1004 			runtm += l->l_rtime.sec;
   1005 			l->l_swtime++;
   1006 			sched_pstats_hook(l);
   1007 			lwp_unlock(l);
   1008 
   1009 			/*
   1010 			 * p_pctcpu is only for ps.
   1011 			 */
   1012 			l->l_pctcpu = (l->l_pctcpu * ccpu) >> FSHIFT;
   1013 			if (l->l_slptime < 1) {
   1014 				clkhz = stathz != 0 ? stathz : hz;
   1015 #if	(FSHIFT >= CCPU_SHIFT)
   1016 				l->l_pctcpu += (clkhz == 100) ?
   1017 				    ((fixpt_t)l->l_cpticks) <<
   1018 				        (FSHIFT - CCPU_SHIFT) :
   1019 				    100 * (((fixpt_t) p->p_cpticks)
   1020 				        << (FSHIFT - CCPU_SHIFT)) / clkhz;
   1021 #else
   1022 				l->l_pctcpu += ((FSCALE - ccpu) *
   1023 				    (l->l_cpticks * FSCALE / clkhz)) >> FSHIFT;
   1024 #endif
   1025 				l->l_cpticks = 0;
   1026 			}
   1027 		}
   1028 		p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
   1029 		mutex_spin_exit(&p->p_stmutex);
   1030 
   1031 		/*
   1032 		 * Check if the process exceeds its CPU resource allocation.
   1033 		 * If over max, kill it.
   1034 		 */
   1035 		rlim = &p->p_rlimit[RLIMIT_CPU];
   1036 		sig = 0;
   1037 		if (runtm >= rlim->rlim_cur) {
   1038 			if (runtm >= rlim->rlim_max)
   1039 				sig = SIGKILL;
   1040 			else {
   1041 				sig = SIGXCPU;
   1042 				if (rlim->rlim_cur < rlim->rlim_max)
   1043 					rlim->rlim_cur += 5;
   1044 			}
   1045 		}
   1046 		mutex_exit(&p->p_smutex);
   1047 		if (sig) {
   1048 			mutex_enter(&proclist_mutex);
   1049 			psignal(p, sig);
   1050 			mutex_exit(&proclist_mutex);
   1051 		}
   1052 	}
   1053 	mutex_exit(&proclist_lock);
   1054 	uvm_meter();
   1055 	cv_wakeup(&lbolt);
   1056 	callout_schedule(&sched_pstats_ch, hz);
   1057 }
   1058 
   1059 void
   1060 sched_init(void)
   1061 {
   1062 
   1063 	cv_init(&lbolt, "lbolt");
   1064 	callout_init(&sched_pstats_ch, CALLOUT_MPSAFE);
   1065 	callout_setfunc(&sched_pstats_ch, sched_pstats, NULL);
   1066 
   1067 	/* Balancing */
   1068 	worker_ci = curcpu();
   1069 	cacheht_time = mstohz(5);		/* ~5 ms  */
   1070 	balance_period = mstohz(300);		/* ~300ms */
   1071 
   1072 	/* Minimal count of LWPs for catching: log2(count of CPUs) */
   1073 	min_catch = min(ilog2(ncpu), 4);
   1074 
   1075 	/* Initialize balancing callout and run it */
   1076 #ifdef MULTIPROCESSOR
   1077 	callout_init(&balance_ch, CALLOUT_MPSAFE);
   1078 	callout_setfunc(&balance_ch, sched_balance, NULL);
   1079 	callout_schedule(&balance_ch, balance_period);
   1080 #endif
   1081 	sched_pstats(NULL);
   1082 }
   1083 
   1084 SYSCTL_SETUP(sysctl_sched_setup, "sysctl sched setup")
   1085 {
   1086 	const struct sysctlnode *node = NULL;
   1087 
   1088 	sysctl_createv(clog, 0, NULL, NULL,
   1089 		CTLFLAG_PERMANENT,
   1090 		CTLTYPE_NODE, "kern", NULL,
   1091 		NULL, 0, NULL, 0,
   1092 		CTL_KERN, CTL_EOL);
   1093 	sysctl_createv(clog, 0, NULL, &node,
   1094 		CTLFLAG_PERMANENT,
   1095 		CTLTYPE_NODE, "sched",
   1096 		SYSCTL_DESCR("Scheduler options"),
   1097 		NULL, 0, NULL, 0,
   1098 		CTL_KERN, CTL_CREATE, CTL_EOL);
   1099 
   1100 	if (node == NULL)
   1101 		return;
   1102 
   1103 	sysctl_createv(clog, 0, &node, NULL,
   1104 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   1105 		CTLTYPE_INT, "cacheht_time",
   1106 		SYSCTL_DESCR("Cache hotness time (in ticks)"),
   1107 		NULL, 0, &cacheht_time, 0,
   1108 		CTL_CREATE, CTL_EOL);
   1109 	sysctl_createv(clog, 0, &node, NULL,
   1110 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   1111 		CTLTYPE_INT, "balance_period",
   1112 		SYSCTL_DESCR("Balance period (in ticks)"),
   1113 		NULL, 0, &balance_period, 0,
   1114 		CTL_CREATE, CTL_EOL);
   1115 	sysctl_createv(clog, 0, &node, NULL,
   1116 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   1117 		CTLTYPE_INT, "min_catch",
   1118 		SYSCTL_DESCR("Minimal count of threads for catching"),
   1119 		NULL, 0, &min_catch, 0,
   1120 		CTL_CREATE, CTL_EOL);
   1121 	sysctl_createv(clog, 0, &node, NULL,
   1122 		CTLFLAG_READWRITE,
   1123 		CTLTYPE_INT, "timesoftints",
   1124 		SYSCTL_DESCR("Track CPU time for soft interrupts"),
   1125 		NULL, 0, &softint_timing, 0,
   1126 		CTL_CREATE, CTL_EOL);
   1127 }
   1128 
   1129 void
   1130 sched_cpuattach(struct cpu_info *ci)
   1131 {
   1132 	runqueue_t *ci_rq;
   1133 	void *rq_ptr;
   1134 	u_int i, size;
   1135 
   1136 	if (ci->ci_schedstate.spc_lwplock == NULL) {
   1137 		ci->ci_schedstate.spc_lwplock =
   1138 		    mutex_obj_alloc(MUTEX_DEFAULT, IPL_SCHED);
   1139 	}
   1140 	if (ci == lwp0.l_cpu) {
   1141 		/* Initialize the scheduler structure of the primary LWP */
   1142 		lwp0.l_mutex = ci->ci_schedstate.spc_lwplock;
   1143 	}
   1144 	if (ci->ci_schedstate.spc_mutex != NULL) {
   1145 		/* Already initialized. */
   1146 		return;
   1147 	}
   1148 
   1149 	/* Allocate the run queue */
   1150 	size = roundup2(sizeof(runqueue_t), coherency_unit) + coherency_unit;
   1151 	rq_ptr = kmem_zalloc(size, KM_SLEEP);
   1152 	if (rq_ptr == NULL) {
   1153 		panic("sched_cpuattach: could not allocate the runqueue");
   1154 	}
   1155 	ci_rq = (void *)(roundup2((uintptr_t)(rq_ptr), coherency_unit));
   1156 
   1157 	/* Initialize run queues */
   1158 	ci->ci_schedstate.spc_mutex =
   1159 	    mutex_obj_alloc(MUTEX_DEFAULT, IPL_SCHED);
   1160 	for (i = 0; i < PRI_RT_COUNT; i++)
   1161 		TAILQ_INIT(&ci_rq->r_rt_queue[i].q_head);
   1162 	for (i = 0; i < PRI_TS_COUNT; i++)
   1163 		TAILQ_INIT(&ci_rq->r_ts_queue[i].q_head);
   1164 
   1165 	ci->ci_schedstate.spc_sched_info = ci_rq;
   1166 }
   1167 
   1168 /*
   1169  * Control of the runqueue.
   1170  */
   1171 
   1172 static void *
   1173 sched_getrq(runqueue_t *ci_rq, const pri_t prio)
   1174 {
   1175 
   1176 	KASSERT(prio < PRI_COUNT);
   1177 	return (prio <= PRI_HIGHEST_TS) ?
   1178 	    &ci_rq->r_ts_queue[prio].q_head :
   1179 	    &ci_rq->r_rt_queue[prio - PRI_HIGHEST_TS - 1].q_head;
   1180 }
   1181 
   1182 void
   1183 sched_enqueue(struct lwp *l, bool swtch)
   1184 {
   1185 	runqueue_t *ci_rq;
   1186 	struct schedstate_percpu *spc;
   1187 	TAILQ_HEAD(, lwp) *q_head;
   1188 	const pri_t eprio = lwp_eprio(l);
   1189 	struct cpu_info *ci;
   1190 
   1191 	ci = l->l_cpu;
   1192 	spc = &ci->ci_schedstate;
   1193 	ci_rq = spc->spc_sched_info;
   1194 	KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
   1195 
   1196 	/* Update the last run time on switch */
   1197 	if (__predict_true(swtch == true)) {
   1198 		l->l_rticks = hardclock_ticks;
   1199 		l->l_rticksum += (hardclock_ticks - l->l_rticks);
   1200 	} else if (l->l_rticks == 0)
   1201 		l->l_rticks = hardclock_ticks;
   1202 
   1203 	/* Enqueue the thread */
   1204 	q_head = sched_getrq(ci_rq, eprio);
   1205 	if (TAILQ_EMPTY(q_head)) {
   1206 		u_int i;
   1207 		uint32_t q;
   1208 
   1209 		/* Mark bit */
   1210 		i = eprio >> BITMAP_SHIFT;
   1211 		q = BITMAP_MSB >> (eprio & BITMAP_MASK);
   1212 		KASSERT((ci_rq->r_bitmap[i] & q) == 0);
   1213 		ci_rq->r_bitmap[i] |= q;
   1214 	}
   1215 	TAILQ_INSERT_TAIL(q_head, l, l_runq);
   1216 	ci_rq->r_count++;
   1217 	if ((l->l_pflag & LP_BOUND) == 0)
   1218 		ci_rq->r_mcount++;
   1219 
   1220 	/*
   1221 	 * Update the value of highest priority in the runqueue,
   1222 	 * if priority of this thread is higher.
   1223 	 */
   1224 	if (eprio > spc->spc_maxpriority)
   1225 		spc->spc_maxpriority = eprio;
   1226 
   1227 	sched_newts(l);
   1228 
   1229 	/*
   1230 	 * Wake the chosen CPU or cause a preemption if the newly
   1231 	 * enqueued thread has higher priority.  Don't cause a
   1232 	 * preemption if the thread is yielding (swtch).
   1233 	 */
   1234 	if (!swtch && eprio > spc->spc_curpriority) {
   1235 		cpu_need_resched(ci,
   1236 		    (eprio >= PRI_KERNEL ? RESCHED_IMMED : 0));
   1237 	}
   1238 }
   1239 
   1240 void
   1241 sched_dequeue(struct lwp *l)
   1242 {
   1243 	runqueue_t *ci_rq;
   1244 	TAILQ_HEAD(, lwp) *q_head;
   1245 	struct schedstate_percpu *spc;
   1246 	const pri_t eprio = lwp_eprio(l);
   1247 
   1248 	spc = & l->l_cpu->ci_schedstate;
   1249 	ci_rq = spc->spc_sched_info;
   1250 	KASSERT(lwp_locked(l, spc->spc_mutex));
   1251 
   1252 	KASSERT(eprio <= spc->spc_maxpriority);
   1253 	KASSERT(ci_rq->r_bitmap[eprio >> BITMAP_SHIFT] != 0);
   1254 	KASSERT(ci_rq->r_count > 0);
   1255 
   1256 	ci_rq->r_count--;
   1257 	if ((l->l_pflag & LP_BOUND) == 0)
   1258 		ci_rq->r_mcount--;
   1259 
   1260 	q_head = sched_getrq(ci_rq, eprio);
   1261 	TAILQ_REMOVE(q_head, l, l_runq);
   1262 	if (TAILQ_EMPTY(q_head)) {
   1263 		u_int i;
   1264 		uint32_t q;
   1265 
   1266 		/* Unmark bit */
   1267 		i = eprio >> BITMAP_SHIFT;
   1268 		q = BITMAP_MSB >> (eprio & BITMAP_MASK);
   1269 		KASSERT((ci_rq->r_bitmap[i] & q) != 0);
   1270 		ci_rq->r_bitmap[i] &= ~q;
   1271 
   1272 		/*
   1273 		 * Update the value of highest priority in the runqueue, in a
   1274 		 * case it was a last thread in the queue of highest priority.
   1275 		 */
   1276 		if (eprio != spc->spc_maxpriority)
   1277 			return;
   1278 
   1279 		do {
   1280 			if (ci_rq->r_bitmap[i] != 0) {
   1281 				q = ffs(ci_rq->r_bitmap[i]);
   1282 				spc->spc_maxpriority =
   1283 				    (i << BITMAP_SHIFT) + (BITMAP_BITS - q);
   1284 				return;
   1285 			}
   1286 		} while (i--);
   1287 
   1288 		/* If not found - set the lowest value */
   1289 		spc->spc_maxpriority = 0;
   1290 	}
   1291 }
   1292 
   1293 /*
   1294  * Migration and balancing.
   1295  */
   1296 
   1297 #ifdef MULTIPROCESSOR
   1298 
   1299 /* Estimate if LWP is cache-hot */
   1300 static inline bool
   1301 lwp_cache_hot(const struct lwp *l)
   1302 {
   1303 
   1304 	if (l->l_slptime || l->l_rticks == 0)
   1305 		return false;
   1306 
   1307 	return (hardclock_ticks - l->l_rticks <= cacheht_time);
   1308 }
   1309 
   1310 /* Check if LWP can migrate to the chosen CPU */
   1311 static inline bool
   1312 sched_migratable(const struct lwp *l, struct cpu_info *ci)
   1313 {
   1314 	const struct schedstate_percpu *spc = &ci->ci_schedstate;
   1315 
   1316 	/* CPU is offline */
   1317 	if (__predict_false(spc->spc_flags & SPCF_OFFLINE))
   1318 		return false;
   1319 
   1320 	/* Affinity bind */
   1321 	if (__predict_false(l->l_flag & LW_AFFINITY))
   1322 		return CPU_ISSET(cpu_index(ci), &l->l_affinity);
   1323 
   1324 	/* Processor-set */
   1325 	return (spc->spc_psid == l->l_psid);
   1326 }
   1327 
   1328 /*
   1329  * Estimate the migration of LWP to the other CPU.
   1330  * Take and return the CPU, if migration is needed.
   1331  */
   1332 struct cpu_info *
   1333 sched_takecpu(struct lwp *l)
   1334 {
   1335 	struct cpu_info *ci, *tci, *first, *next;
   1336 	struct schedstate_percpu *spc;
   1337 	runqueue_t *ci_rq, *ici_rq;
   1338 	pri_t eprio, lpri, pri;
   1339 
   1340 	KASSERT(lwp_locked(l, NULL));
   1341 
   1342 	ci = l->l_cpu;
   1343 	spc = &ci->ci_schedstate;
   1344 	ci_rq = spc->spc_sched_info;
   1345 
   1346 	/* If thread is strictly bound, do not estimate other CPUs */
   1347 	if (l->l_pflag & LP_BOUND)
   1348 		return ci;
   1349 
   1350 	/* CPU of this thread is idling - run there */
   1351 	if (ci_rq->r_count == 0)
   1352 		return ci;
   1353 
   1354 	eprio = lwp_eprio(l);
   1355 
   1356 	/* Stay if thread is cache-hot */
   1357 	if (__predict_true(l->l_stat != LSIDL) &&
   1358 	    lwp_cache_hot(l) && eprio >= spc->spc_curpriority)
   1359 		return ci;
   1360 
   1361 	/* Run on current CPU if priority of thread is higher */
   1362 	ci = curcpu();
   1363 	spc = &ci->ci_schedstate;
   1364 	if (eprio > spc->spc_curpriority && sched_migratable(l, ci))
   1365 		return ci;
   1366 
   1367 	/*
   1368 	 * Look for the CPU with the lowest priority thread.  In case of
   1369 	 * equal priority, choose the CPU with the fewest of threads.
   1370 	 */
   1371 	first = l->l_cpu;
   1372 	ci = first;
   1373 	tci = first;
   1374 	lpri = PRI_COUNT;
   1375 	do {
   1376 		next = CIRCLEQ_LOOP_NEXT(&cpu_queue, ci, ci_data.cpu_qchain);
   1377 		spc = &ci->ci_schedstate;
   1378 		ici_rq = spc->spc_sched_info;
   1379 		pri = max(spc->spc_curpriority, spc->spc_maxpriority);
   1380 		if (pri > lpri)
   1381 			continue;
   1382 
   1383 		if (pri == lpri && ci_rq->r_count < ici_rq->r_count)
   1384 			continue;
   1385 
   1386 		if (!sched_migratable(l, ci))
   1387 			continue;
   1388 
   1389 		lpri = pri;
   1390 		tci = ci;
   1391 		ci_rq = ici_rq;
   1392 	} while (ci = next, ci != first);
   1393 
   1394 	return tci;
   1395 }
   1396 
   1397 /*
   1398  * Tries to catch an LWP from the runqueue of other CPU.
   1399  */
   1400 static struct lwp *
   1401 sched_catchlwp(void)
   1402 {
   1403 	struct cpu_info *curci = curcpu(), *ci = worker_ci;
   1404 	struct schedstate_percpu *spc;
   1405 	TAILQ_HEAD(, lwp) *q_head;
   1406 	runqueue_t *ci_rq;
   1407 	struct lwp *l;
   1408 
   1409 	if (curci == ci)
   1410 		return NULL;
   1411 
   1412 	/* Lockless check */
   1413 	spc = &ci->ci_schedstate;
   1414 	ci_rq = spc->spc_sched_info;
   1415 	if (ci_rq->r_mcount < min_catch)
   1416 		return NULL;
   1417 
   1418 	/*
   1419 	 * Double-lock the runqueues.
   1420 	 */
   1421 	if (curci < ci) {
   1422 		spc_lock(ci);
   1423 	} else if (!mutex_tryenter(ci->ci_schedstate.spc_mutex)) {
   1424 		const runqueue_t *cur_rq = curci->ci_schedstate.spc_sched_info;
   1425 
   1426 		spc_unlock(curci);
   1427 		spc_lock(ci);
   1428 		spc_lock(curci);
   1429 
   1430 		if (cur_rq->r_count) {
   1431 			spc_unlock(ci);
   1432 			return NULL;
   1433 		}
   1434 	}
   1435 
   1436 	if (ci_rq->r_mcount < min_catch) {
   1437 		spc_unlock(ci);
   1438 		return NULL;
   1439 	}
   1440 
   1441 	/* Take the highest priority thread */
   1442 	q_head = sched_getrq(ci_rq, spc->spc_maxpriority);
   1443 	l = TAILQ_FIRST(q_head);
   1444 
   1445 	for (;;) {
   1446 		/* Check the first and next result from the queue */
   1447 		if (l == NULL)
   1448 			break;
   1449 		KASSERT(l->l_stat == LSRUN);
   1450 		KASSERT(l->l_flag & LW_INMEM);
   1451 
   1452 		/* Look for threads, whose are allowed to migrate */
   1453 		if ((l->l_pflag & LP_BOUND) || lwp_cache_hot(l) ||
   1454 		    !sched_migratable(l, curci)) {
   1455 			l = TAILQ_NEXT(l, l_runq);
   1456 			continue;
   1457 		}
   1458 
   1459 		/* Grab the thread, and move to the local run queue */
   1460 		sched_dequeue(l);
   1461 		l->l_cpu = curci;
   1462 		lwp_unlock_to(l, curci->ci_schedstate.spc_mutex);
   1463 		sched_enqueue(l, false);
   1464 		return l;
   1465 	}
   1466 	spc_unlock(ci);
   1467 
   1468 	return l;
   1469 }
   1470 
   1471 /*
   1472  * Periodical calculations for balancing.
   1473  */
   1474 static void
   1475 sched_balance(void *nocallout)
   1476 {
   1477 	struct cpu_info *ci, *hci;
   1478 	runqueue_t *ci_rq;
   1479 	CPU_INFO_ITERATOR cii;
   1480 	u_int highest;
   1481 
   1482 	hci = curcpu();
   1483 	highest = 0;
   1484 
   1485 	/* Make lockless countings */
   1486 	for (CPU_INFO_FOREACH(cii, ci)) {
   1487 		ci_rq = ci->ci_schedstate.spc_sched_info;
   1488 
   1489 		/* Average count of the threads */
   1490 		ci_rq->r_avgcount = (ci_rq->r_avgcount + ci_rq->r_mcount) >> 1;
   1491 
   1492 		/* Look for CPU with the highest average */
   1493 		if (ci_rq->r_avgcount > highest) {
   1494 			hci = ci;
   1495 			highest = ci_rq->r_avgcount;
   1496 		}
   1497 	}
   1498 
   1499 	/* Update the worker */
   1500 	worker_ci = hci;
   1501 
   1502 	if (nocallout == NULL)
   1503 		callout_schedule(&balance_ch, balance_period);
   1504 }
   1505 
   1506 #else
   1507 
   1508 struct cpu_info *
   1509 sched_takecpu(struct lwp *l)
   1510 {
   1511 
   1512 	return l->l_cpu;
   1513 }
   1514 
   1515 #endif	/* MULTIPROCESSOR */
   1516 
   1517 /*
   1518  * Scheduler mill.
   1519  */
   1520 struct lwp *
   1521 sched_nextlwp(void)
   1522 {
   1523 	struct cpu_info *ci = curcpu();
   1524 	struct schedstate_percpu *spc;
   1525 	TAILQ_HEAD(, lwp) *q_head;
   1526 	runqueue_t *ci_rq;
   1527 	struct lwp *l;
   1528 
   1529 	spc = &ci->ci_schedstate;
   1530 	ci_rq = spc->spc_sched_info;
   1531 
   1532 #ifdef MULTIPROCESSOR
   1533 	/* If runqueue is empty, try to catch some thread from other CPU */
   1534 	if (__predict_false(spc->spc_flags & SPCF_OFFLINE)) {
   1535 		if ((ci_rq->r_count - ci_rq->r_mcount) == 0)
   1536 			return NULL;
   1537 	} else if (ci_rq->r_count == 0) {
   1538 		/* Reset the counter, and call the balancer */
   1539 		ci_rq->r_avgcount = 0;
   1540 		sched_balance(ci);
   1541 
   1542 		/* The re-locking will be done inside */
   1543 		return sched_catchlwp();
   1544 	}
   1545 #else
   1546 	if (ci_rq->r_count == 0)
   1547 		return NULL;
   1548 #endif
   1549 
   1550 	/* Take the highest priority thread */
   1551 	KASSERT(ci_rq->r_bitmap[spc->spc_maxpriority >> BITMAP_SHIFT]);
   1552 	q_head = sched_getrq(ci_rq, spc->spc_maxpriority);
   1553 	l = TAILQ_FIRST(q_head);
   1554 	KASSERT(l != NULL);
   1555 
   1556 	sched_oncpu(l);
   1557 	l->l_rticks = hardclock_ticks;
   1558 
   1559 	return l;
   1560 }
   1561 
   1562 bool
   1563 sched_curcpu_runnable_p(void)
   1564 {
   1565 	const struct cpu_info *ci = curcpu();
   1566 	const runqueue_t *ci_rq = ci->ci_schedstate.spc_sched_info;
   1567 
   1568 #ifndef __HAVE_FAST_SOFTINTS
   1569 	if (ci->ci_data.cpu_softints)
   1570 		return true;
   1571 #endif
   1572 
   1573 	if (ci->ci_schedstate.spc_flags & SPCF_OFFLINE)
   1574 		return (ci_rq->r_count - ci_rq->r_mcount);
   1575 
   1576 	return ci_rq->r_count;
   1577 }
   1578 
   1579 /*
   1580  * Debugging.
   1581  */
   1582 
   1583 #ifdef DDB
   1584 
   1585 void
   1586 sched_print_runqueue(void (*pr)(const char *, ...)
   1587     __attribute__((__format__(__printf__,1,2))))
   1588 {
   1589 	runqueue_t *ci_rq;
   1590 	struct schedstate_percpu *spc;
   1591 	struct lwp *l;
   1592 	struct proc *p;
   1593 	int i;
   1594 	struct cpu_info *ci;
   1595 	CPU_INFO_ITERATOR cii;
   1596 
   1597 	for (CPU_INFO_FOREACH(cii, ci)) {
   1598 		spc = &ci->ci_schedstate;
   1599 		ci_rq = spc->spc_sched_info;
   1600 
   1601 		(*pr)("Run-queue (CPU = %u):\n", ci->ci_index);
   1602 		(*pr)(" pid.lid = %d.%d, threads count = %u, "
   1603 		    "avgcount = %u, highest pri = %d\n",
   1604 #ifdef MULTIPROCESSOR
   1605 		    ci->ci_curlwp->l_proc->p_pid, ci->ci_curlwp->l_lid,
   1606 #else
   1607 		    curlwp->l_proc->p_pid, curlwp->l_lid,
   1608 #endif
   1609 		    ci_rq->r_count, ci_rq->r_avgcount, spc->spc_maxpriority);
   1610 		i = (PRI_COUNT >> BITMAP_SHIFT) - 1;
   1611 		do {
   1612 			uint32_t q;
   1613 			q = ci_rq->r_bitmap[i];
   1614 			(*pr)(" bitmap[%d] => [ %d (0x%x) ]\n", i, ffs(q), q);
   1615 		} while (i--);
   1616 	}
   1617 
   1618 	(*pr)("   %5s %4s %4s %10s %3s %18s %4s %s\n",
   1619 	    "LID", "PRI", "EPRI", "FL", "ST", "LWP", "CPU", "LRTIME");
   1620 
   1621 	PROCLIST_FOREACH(p, &allproc) {
   1622 		(*pr)(" /- %d (%s)\n", (int)p->p_pid, p->p_comm);
   1623 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
   1624 			ci = l->l_cpu;
   1625 			(*pr)(" | %5d %4u %4u 0x%8.8x %3s %18p %4u %u\n",
   1626 			    (int)l->l_lid, l->l_priority, lwp_eprio(l),
   1627 			    l->l_flag, l->l_stat == LSRUN ? "RQ" :
   1628 			    (l->l_stat == LSSLEEP ? "SQ" : "-"),
   1629 			    l, ci->ci_index,
   1630 			    (u_int)(hardclock_ticks - l->l_rticks));
   1631 		}
   1632 	}
   1633 }
   1634 
   1635 #endif
   1636