Home | History | Annotate | Line # | Download | only in kern
sched_m2.c revision 1.20
      1 /*	$NetBSD: sched_m2.c,v 1.20 2008/02/14 14:26:57 ad Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2007, 2008 Mindaugas Rasiukevicius <rmind at NetBSD org>
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     26  * SUCH DAMAGE.
     27  */
     28 
     29 /*
     30  * TODO:
     31  *  - Implementation of fair share queue;
     32  *  - Support for NUMA;
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 __KERNEL_RCSID(0, "$NetBSD: sched_m2.c,v 1.20 2008/02/14 14:26:57 ad Exp $");
     37 
     38 #include <sys/param.h>
     39 
     40 #include <sys/bitops.h>
     41 #include <sys/cpu.h>
     42 #include <sys/callout.h>
     43 #include <sys/errno.h>
     44 #include <sys/kernel.h>
     45 #include <sys/kmem.h>
     46 #include <sys/lwp.h>
     47 #include <sys/mutex.h>
     48 #include <sys/pool.h>
     49 #include <sys/proc.h>
     50 #include <sys/pset.h>
     51 #include <sys/resource.h>
     52 #include <sys/resourcevar.h>
     53 #include <sys/sched.h>
     54 #include <sys/syscallargs.h>
     55 #include <sys/sysctl.h>
     56 #include <sys/types.h>
     57 
     58 /*
     59  * Priority related defintions.
     60  */
     61 #define	PRI_TS_COUNT	(NPRI_USER)
     62 #define	PRI_RT_COUNT	(PRI_COUNT - PRI_TS_COUNT)
     63 #define	PRI_HTS_RANGE	(PRI_TS_COUNT / 10)
     64 
     65 #define	PRI_HIGHEST_TS	(MAXPRI_USER)
     66 
     67 const int schedppq = 1;
     68 
     69 /*
     70  * Bits per map.
     71  */
     72 #define	BITMAP_BITS	(32)
     73 #define	BITMAP_SHIFT	(5)
     74 #define	BITMAP_MSB	(0x80000000U)
     75 #define	BITMAP_MASK	(BITMAP_BITS - 1)
     76 
     77 /*
     78  * Time-slices and priorities.
     79  */
     80 static u_int	min_ts;			/* Minimal time-slice */
     81 static u_int	max_ts;			/* Maximal time-slice */
     82 static u_int	rt_ts;			/* Real-time time-slice */
     83 static u_int	ts_map[PRI_COUNT];	/* Map of time-slices */
     84 static pri_t	high_pri[PRI_COUNT];	/* Map for priority increase */
     85 
     86 /*
     87  * Migration and balancing.
     88  */
     89 #ifdef MULTIPROCESSOR
     90 
     91 static u_int	cacheht_time;		/* Cache hotness time */
     92 static u_int	min_catch;		/* Minimal LWP count for catching */
     93 
     94 static u_int		balance_period;	/* Balance period */
     95 static struct callout	balance_ch;	/* Callout of balancer */
     96 
     97 static struct cpu_info * volatile worker_ci;
     98 
     99 #endif
    100 
    101 /*
    102  * Structures, runqueue.
    103  */
    104 
    105 typedef struct {
    106 	TAILQ_HEAD(, lwp) q_head;
    107 } queue_t;
    108 
    109 typedef struct {
    110 	/* Lock and bitmap */
    111 	uint32_t	r_bitmap[PRI_COUNT >> BITMAP_SHIFT];
    112 	/* Counters */
    113 	u_int		r_count;	/* Count of the threads */
    114 	pri_t		r_highest_pri;	/* Highest priority */
    115 	u_int		r_avgcount;	/* Average count of threads */
    116 	u_int		r_mcount;	/* Count of migratable threads */
    117 	/* Runqueues */
    118 	queue_t		r_rt_queue[PRI_RT_COUNT];
    119 	queue_t		r_ts_queue[PRI_TS_COUNT];
    120 } runqueue_t;
    121 
    122 typedef struct {
    123 	u_int		sl_flags;
    124 	u_int		sl_timeslice;	/* Time-slice of thread */
    125 	u_int		sl_slept;	/* Saved sleep time for sleep sum */
    126 	u_int		sl_slpsum;	/* Sum of sleep time */
    127 	u_int		sl_rtime;	/* Saved start time of run */
    128 	u_int		sl_rtsum;	/* Sum of the run time */
    129 	u_int		sl_lrtime;	/* Last run time */
    130 } sched_info_lwp_t;
    131 
    132 /* Flags */
    133 #define	SL_BATCH	0x01
    134 
    135 /* Pool of the scheduler-specific structures for threads */
    136 static pool_cache_t	sil_pool;
    137 
    138 /*
    139  * Prototypes.
    140  */
    141 
    142 static inline void *	sched_getrq(runqueue_t *, const pri_t);
    143 static inline void	sched_newts(struct lwp *);
    144 static void		sched_precalcts(void);
    145 
    146 #ifdef MULTIPROCESSOR
    147 static struct lwp *	sched_catchlwp(void);
    148 static void		sched_balance(void *);
    149 #endif
    150 
    151 /*
    152  * Initialization and setup.
    153  */
    154 
    155 void
    156 sched_rqinit(void)
    157 {
    158 	struct cpu_info *ci = curcpu();
    159 
    160 	if (hz < 100) {
    161 		panic("sched_rqinit: value of HZ is too low\n");
    162 	}
    163 
    164 	/* Default timing ranges */
    165 	min_ts = mstohz(50);			/* ~50ms  */
    166 	max_ts = mstohz(150);			/* ~150ms */
    167 	rt_ts = mstohz(100);			/* ~100ms */
    168 	sched_precalcts();
    169 
    170 #ifdef MULTIPROCESSOR
    171 	/* Balancing */
    172 	worker_ci = ci;
    173 	cacheht_time = mstohz(5);		/* ~5 ms  */
    174 	balance_period = mstohz(300);		/* ~300ms */
    175 	min_catch = ~0;
    176 #endif
    177 
    178 	/* Pool of the scheduler-specific structures */
    179 	sil_pool = pool_cache_init(sizeof(sched_info_lwp_t), CACHE_LINE_SIZE,
    180 	    0, 0, "lwpsd", NULL, IPL_NONE, NULL, NULL, NULL);
    181 
    182 	/* Attach the primary CPU here */
    183 	sched_cpuattach(ci);
    184 
    185 	sched_lwp_fork(NULL, &lwp0);
    186 	sched_newts(&lwp0);
    187 }
    188 
    189 void
    190 sched_setup(void)
    191 {
    192 
    193 #ifdef MULTIPROCESSOR
    194 	/* Minimal count of LWPs for catching: log2(count of CPUs) */
    195 	min_catch = min(ilog2(ncpu), 4);
    196 
    197 	/* Initialize balancing callout and run it */
    198 	callout_init(&balance_ch, CALLOUT_MPSAFE);
    199 	callout_setfunc(&balance_ch, sched_balance, NULL);
    200 	callout_schedule(&balance_ch, balance_period);
    201 #endif
    202 }
    203 
    204 void
    205 sched_cpuattach(struct cpu_info *ci)
    206 {
    207 	runqueue_t *ci_rq;
    208 	void *rq_ptr;
    209 	u_int i, size;
    210 
    211 	if (ci == lwp0.l_cpu) {
    212 		/* Initialize the scheduler structure of the primary LWP */
    213 		lwp0.l_mutex = ci->ci_schedstate.spc_lwplock;
    214 	}
    215 
    216 	if (ci->ci_schedstate.spc_mutex != NULL) {
    217 		/* Already initialized. */
    218 		return;
    219 	}
    220 
    221 	/* Allocate the run queue */
    222 	size = roundup2(sizeof(runqueue_t), CACHE_LINE_SIZE) + CACHE_LINE_SIZE;
    223 	rq_ptr = kmem_zalloc(size, KM_SLEEP);
    224 	if (rq_ptr == NULL) {
    225 		panic("sched_cpuattach: could not allocate the runqueue");
    226 	}
    227 	ci_rq = (void *)(roundup2((uintptr_t)(rq_ptr), CACHE_LINE_SIZE));
    228 
    229 	/* Initialize run queues */
    230 	KASSERT(sizeof(kmutex_t) <= CACHE_LINE_SIZE);
    231 	ci->ci_schedstate.spc_mutex = kmem_alloc(CACHE_LINE_SIZE, KM_SLEEP);
    232 	mutex_init(ci->ci_schedstate.spc_mutex, MUTEX_DEFAULT, IPL_SCHED);
    233 	for (i = 0; i < PRI_RT_COUNT; i++)
    234 		TAILQ_INIT(&ci_rq->r_rt_queue[i].q_head);
    235 	for (i = 0; i < PRI_TS_COUNT; i++)
    236 		TAILQ_INIT(&ci_rq->r_ts_queue[i].q_head);
    237 	ci_rq->r_highest_pri = 0;
    238 
    239 	ci->ci_schedstate.spc_sched_info = ci_rq;
    240 }
    241 
    242 /* Pre-calculate the time-slices for the priorities */
    243 static void
    244 sched_precalcts(void)
    245 {
    246 	pri_t p;
    247 
    248 	/* Time-sharing range */
    249 	for (p = 0; p <= PRI_HIGHEST_TS; p++) {
    250 		ts_map[p] = max_ts -
    251 		    (p * 100 / (PRI_TS_COUNT - 1) * (max_ts - min_ts) / 100);
    252 		high_pri[p] = (PRI_HIGHEST_TS - PRI_HTS_RANGE) +
    253 		    ((p * PRI_HTS_RANGE) / (PRI_TS_COUNT - 1));
    254 	}
    255 
    256 	/* Real-time range */
    257 	for (p = (PRI_HIGHEST_TS + 1); p < PRI_COUNT; p++) {
    258 		ts_map[p] = rt_ts;
    259 		high_pri[p] = p;
    260 	}
    261 }
    262 
    263 /*
    264  * Hooks.
    265  */
    266 
    267 void
    268 sched_proc_fork(struct proc *parent, struct proc *child)
    269 {
    270 	struct lwp *l;
    271 
    272 	LIST_FOREACH(l, &child->p_lwps, l_sibling) {
    273 		lwp_lock(l);
    274 		sched_newts(l);
    275 		lwp_unlock(l);
    276 	}
    277 }
    278 
    279 void
    280 sched_proc_exit(struct proc *child, struct proc *parent)
    281 {
    282 
    283 	/* Dummy */
    284 }
    285 
    286 void
    287 sched_lwp_fork(struct lwp *l1, struct lwp *l2)
    288 {
    289 
    290 	KASSERT(l2->l_sched_info == NULL);
    291 	l2->l_sched_info = pool_cache_get(sil_pool, PR_WAITOK);
    292 	memset(l2->l_sched_info, 0, sizeof(sched_info_lwp_t));
    293 }
    294 
    295 void
    296 sched_lwp_exit(struct lwp *l)
    297 {
    298 
    299 	KASSERT(l->l_sched_info != NULL);
    300 	pool_cache_put(sil_pool, l->l_sched_info);
    301 	l->l_sched_info = NULL;
    302 }
    303 
    304 void
    305 sched_lwp_collect(struct lwp *l)
    306 {
    307 
    308 }
    309 
    310 void
    311 sched_setrunnable(struct lwp *l)
    312 {
    313 
    314 	/* Dummy */
    315 }
    316 
    317 void
    318 sched_schedclock(struct lwp *l)
    319 {
    320 
    321 	/* Dummy */
    322 }
    323 
    324 /*
    325  * Priorities and time-slice.
    326  */
    327 
    328 void
    329 sched_nice(struct proc *p, int prio)
    330 {
    331 
    332 	/* TODO: implement as SCHED_IA */
    333 }
    334 
    335 /* Recalculate the time-slice */
    336 static inline void
    337 sched_newts(struct lwp *l)
    338 {
    339 	sched_info_lwp_t *sil = l->l_sched_info;
    340 
    341 	sil->sl_timeslice = ts_map[lwp_eprio(l)];
    342 }
    343 
    344 /*
    345  * Control of the runqueue.
    346  */
    347 
    348 static inline void *
    349 sched_getrq(runqueue_t *ci_rq, const pri_t prio)
    350 {
    351 
    352 	KASSERT(prio < PRI_COUNT);
    353 	return (prio <= PRI_HIGHEST_TS) ?
    354 	    &ci_rq->r_ts_queue[prio].q_head :
    355 	    &ci_rq->r_rt_queue[prio - PRI_HIGHEST_TS - 1].q_head;
    356 }
    357 
    358 void
    359 sched_enqueue(struct lwp *l, bool swtch)
    360 {
    361 	runqueue_t *ci_rq;
    362 	sched_info_lwp_t *sil = l->l_sched_info;
    363 	TAILQ_HEAD(, lwp) *q_head;
    364 	const pri_t eprio = lwp_eprio(l);
    365 
    366 	ci_rq = l->l_cpu->ci_schedstate.spc_sched_info;
    367 	KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
    368 
    369 	/* Update the last run time on switch */
    370 	if (__predict_true(swtch == true)) {
    371 		sil->sl_lrtime = hardclock_ticks;
    372 		sil->sl_rtsum += (hardclock_ticks - sil->sl_rtime);
    373 	} else if (sil->sl_lrtime == 0)
    374 		sil->sl_lrtime = hardclock_ticks;
    375 
    376 	/* Enqueue the thread */
    377 	q_head = sched_getrq(ci_rq, eprio);
    378 	if (TAILQ_EMPTY(q_head)) {
    379 		u_int i;
    380 		uint32_t q;
    381 
    382 		/* Mark bit */
    383 		i = eprio >> BITMAP_SHIFT;
    384 		q = BITMAP_MSB >> (eprio & BITMAP_MASK);
    385 		KASSERT((ci_rq->r_bitmap[i] & q) == 0);
    386 		ci_rq->r_bitmap[i] |= q;
    387 	}
    388 	TAILQ_INSERT_TAIL(q_head, l, l_runq);
    389 	ci_rq->r_count++;
    390 	if ((l->l_flag & LW_BOUND) == 0)
    391 		ci_rq->r_mcount++;
    392 
    393 	/*
    394 	 * Update the value of highest priority in the runqueue,
    395 	 * if priority of this thread is higher.
    396 	 */
    397 	if (eprio > ci_rq->r_highest_pri)
    398 		ci_rq->r_highest_pri = eprio;
    399 
    400 	sched_newts(l);
    401 }
    402 
    403 void
    404 sched_dequeue(struct lwp *l)
    405 {
    406 	runqueue_t *ci_rq;
    407 	TAILQ_HEAD(, lwp) *q_head;
    408 	const pri_t eprio = lwp_eprio(l);
    409 
    410 	ci_rq = l->l_cpu->ci_schedstate.spc_sched_info;
    411 	KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
    412 
    413 	KASSERT(eprio <= ci_rq->r_highest_pri);
    414 	KASSERT(ci_rq->r_bitmap[eprio >> BITMAP_SHIFT] != 0);
    415 	KASSERT(ci_rq->r_count > 0);
    416 
    417 	ci_rq->r_count--;
    418 	if ((l->l_flag & LW_BOUND) == 0)
    419 		ci_rq->r_mcount--;
    420 
    421 	q_head = sched_getrq(ci_rq, eprio);
    422 	TAILQ_REMOVE(q_head, l, l_runq);
    423 	if (TAILQ_EMPTY(q_head)) {
    424 		u_int i;
    425 		uint32_t q;
    426 
    427 		/* Unmark bit */
    428 		i = eprio >> BITMAP_SHIFT;
    429 		q = BITMAP_MSB >> (eprio & BITMAP_MASK);
    430 		KASSERT((ci_rq->r_bitmap[i] & q) != 0);
    431 		ci_rq->r_bitmap[i] &= ~q;
    432 
    433 		/*
    434 		 * Update the value of highest priority in the runqueue, in a
    435 		 * case it was a last thread in the queue of highest priority.
    436 		 */
    437 		if (eprio != ci_rq->r_highest_pri)
    438 			return;
    439 
    440 		do {
    441 			q = ffs(ci_rq->r_bitmap[i]);
    442 			if (q) {
    443 				ci_rq->r_highest_pri =
    444 				    (i << BITMAP_SHIFT) + (BITMAP_BITS - q);
    445 				return;
    446 			}
    447 		} while (i--);
    448 
    449 		/* If not found - set the lowest value */
    450 		ci_rq->r_highest_pri = 0;
    451 	}
    452 }
    453 
    454 void
    455 sched_slept(struct lwp *l)
    456 {
    457 	sched_info_lwp_t *sil = l->l_sched_info;
    458 
    459 	/* Save the time when thread has slept */
    460 	sil->sl_slept = hardclock_ticks;
    461 
    462 	/*
    463 	 * If thread is in time-sharing queue and batch flag is not marked,
    464 	 * increase the the priority, and run with the lower time-quantum.
    465 	 */
    466 	if (l->l_priority < PRI_HIGHEST_TS &&
    467 	    (sil->sl_flags & SL_BATCH) == 0) {
    468 		KASSERT(l->l_class == SCHED_OTHER);
    469 		l->l_priority++;
    470 	}
    471 }
    472 
    473 void
    474 sched_wakeup(struct lwp *l)
    475 {
    476 	sched_info_lwp_t *sil = l->l_sched_info;
    477 
    478 	/* Update sleep time delta */
    479 	sil->sl_slpsum += (l->l_slptime == 0) ?
    480 	    (hardclock_ticks - sil->sl_slept) : hz;
    481 
    482 	/* If thread was sleeping a second or more - set a high priority */
    483 	if (l->l_slptime > 1 || (hardclock_ticks - sil->sl_slept) >= hz)
    484 		l->l_priority = high_pri[l->l_priority];
    485 
    486 	/* Also, consider looking for a better CPU to wake up */
    487 	if ((l->l_flag & (LW_BOUND | LW_SYSTEM)) == 0)
    488 		l->l_cpu = sched_takecpu(l);
    489 }
    490 
    491 void
    492 sched_pstats_hook(struct lwp *l)
    493 {
    494 	sched_info_lwp_t *sil = l->l_sched_info;
    495 	pri_t prio;
    496 	bool batch;
    497 
    498 	if (l->l_stat == LSSLEEP || l->l_stat == LSSTOP ||
    499 	    l->l_stat == LSSUSPENDED)
    500 		l->l_slptime++;
    501 
    502 	/*
    503 	 * Set that thread is more CPU-bound, if sum of run time exceeds the
    504 	 * sum of sleep time.  Check if thread is CPU-bound a first time.
    505 	 */
    506 	batch = (sil->sl_rtsum > sil->sl_slpsum);
    507 	if (batch) {
    508 		if ((sil->sl_flags & SL_BATCH) == 0)
    509 			batch = false;
    510 		sil->sl_flags |= SL_BATCH;
    511 	} else
    512 		sil->sl_flags &= ~SL_BATCH;
    513 
    514 	/* Reset the time sums */
    515 	sil->sl_slpsum = 0;
    516 	sil->sl_rtsum = 0;
    517 
    518 	/* Estimate threads on time-sharing queue only */
    519 	if (l->l_priority >= PRI_HIGHEST_TS)
    520 		return;
    521 	KASSERT(l->l_class == SCHED_OTHER);
    522 
    523 	/* If it is CPU-bound not a first time - decrease the priority */
    524 	prio = l->l_priority;
    525 	if (batch && prio != 0)
    526 		prio--;
    527 
    528 	/* If thread was not ran a second or more - set a high priority */
    529 	if (l->l_stat == LSRUN) {
    530 		if (sil->sl_lrtime && (hardclock_ticks - sil->sl_lrtime >= hz))
    531 			prio = high_pri[prio];
    532 		/* Re-enqueue the thread if priority has changed */
    533 		if (prio != l->l_priority)
    534 			lwp_changepri(l, prio);
    535 	} else {
    536 		/* In other states, change the priority directly */
    537 		l->l_priority = prio;
    538 	}
    539 }
    540 
    541 /*
    542  * Migration and balancing.
    543  */
    544 
    545 #ifdef MULTIPROCESSOR
    546 
    547 /* Estimate if LWP is cache-hot */
    548 static inline bool
    549 lwp_cache_hot(const struct lwp *l)
    550 {
    551 	const sched_info_lwp_t *sil = l->l_sched_info;
    552 
    553 	if (l->l_slptime || sil->sl_lrtime == 0)
    554 		return false;
    555 
    556 	return (hardclock_ticks - sil->sl_lrtime < cacheht_time);
    557 }
    558 
    559 /* Check if LWP can migrate to the chosen CPU */
    560 static inline bool
    561 sched_migratable(const struct lwp *l, struct cpu_info *ci)
    562 {
    563 	const struct schedstate_percpu *spc = &ci->ci_schedstate;
    564 
    565 	/* CPU is offline */
    566 	if (__predict_false(spc->spc_flags & SPCF_OFFLINE))
    567 		return false;
    568 
    569 	/* Affinity bind */
    570 	if (__predict_false(l->l_flag & LW_AFFINITY))
    571 		return CPU_ISSET(cpu_index(ci), &l->l_affinity);
    572 
    573 	/* Processor-set */
    574 	return (spc->spc_psid == l->l_psid);
    575 }
    576 
    577 /*
    578  * Estimate the migration of LWP to the other CPU.
    579  * Take and return the CPU, if migration is needed.
    580  */
    581 struct cpu_info *
    582 sched_takecpu(struct lwp *l)
    583 {
    584 	struct cpu_info *ci, *tci;
    585 	struct schedstate_percpu *spc;
    586 	runqueue_t *ci_rq;
    587 	CPU_INFO_ITERATOR cii;
    588 	pri_t eprio, lpri;
    589 
    590 	KASSERT(lwp_locked(l, NULL));
    591 
    592 	ci = l->l_cpu;
    593 	spc = &ci->ci_schedstate;
    594 	ci_rq = spc->spc_sched_info;
    595 
    596 	/* If thread is strictly bound, do not estimate other CPUs */
    597 	if (l->l_flag & LW_BOUND)
    598 		return ci;
    599 
    600 	/* CPU of this thread is idling - run there */
    601 	if (ci_rq->r_count == 0)
    602 		return ci;
    603 
    604 	eprio = lwp_eprio(l);
    605 
    606 	/* Stay if thread is cache-hot */
    607 	if (__predict_true(l->l_stat != LSIDL) &&
    608 	    lwp_cache_hot(l) && eprio >= spc->spc_curpriority)
    609 		return ci;
    610 
    611 	/* Run on current CPU if priority of thread is higher */
    612 	ci = curcpu();
    613 	spc = &ci->ci_schedstate;
    614 	if (eprio > spc->spc_curpriority && sched_migratable(l, ci))
    615 		return ci;
    616 
    617 	/*
    618 	 * Look for the CPU with the lowest priority thread.  In case of
    619 	 * equal the priority - check the lower count of the threads.
    620 	 */
    621 	tci = l->l_cpu;
    622 	lpri = PRI_COUNT;
    623 	for (CPU_INFO_FOREACH(cii, ci)) {
    624 		runqueue_t *ici_rq;
    625 		pri_t pri;
    626 
    627 		spc = &ci->ci_schedstate;
    628 		ici_rq = spc->spc_sched_info;
    629 		pri = max(spc->spc_curpriority, ici_rq->r_highest_pri);
    630 		if (pri > lpri)
    631 			continue;
    632 
    633 		if (pri == lpri && ci_rq->r_count < ici_rq->r_count)
    634 			continue;
    635 
    636 		if (!sched_migratable(l, ci))
    637 			continue;
    638 
    639 		lpri = pri;
    640 		tci = ci;
    641 		ci_rq = ici_rq;
    642 	}
    643 	return tci;
    644 }
    645 
    646 /*
    647  * Tries to catch an LWP from the runqueue of other CPU.
    648  */
    649 static struct lwp *
    650 sched_catchlwp(void)
    651 {
    652 	struct cpu_info *curci = curcpu(), *ci = worker_ci;
    653 	TAILQ_HEAD(, lwp) *q_head;
    654 	runqueue_t *ci_rq;
    655 	struct lwp *l;
    656 
    657 	if (curci == ci)
    658 		return NULL;
    659 
    660 	/* Lockless check */
    661 	ci_rq = ci->ci_schedstate.spc_sched_info;
    662 	if (ci_rq->r_count < min_catch)
    663 		return NULL;
    664 
    665 	/*
    666 	 * Double-lock the runqueues.
    667 	 */
    668 	if (curci < ci) {
    669 		spc_lock(ci);
    670 	} else if (!mutex_tryenter(ci->ci_schedstate.spc_mutex)) {
    671 		const runqueue_t *cur_rq = curci->ci_schedstate.spc_sched_info;
    672 
    673 		spc_unlock(curci);
    674 		spc_lock(ci);
    675 		spc_lock(curci);
    676 
    677 		if (cur_rq->r_count) {
    678 			spc_unlock(ci);
    679 			return NULL;
    680 		}
    681 	}
    682 
    683 	if (ci_rq->r_count < min_catch) {
    684 		spc_unlock(ci);
    685 		return NULL;
    686 	}
    687 
    688 	/* Take the highest priority thread */
    689 	q_head = sched_getrq(ci_rq, ci_rq->r_highest_pri);
    690 	l = TAILQ_FIRST(q_head);
    691 
    692 	for (;;) {
    693 		/* Check the first and next result from the queue */
    694 		if (l == NULL)
    695 			break;
    696 
    697 		/* Look for threads, whose are allowed to migrate */
    698 		if ((l->l_flag & LW_SYSTEM) || lwp_cache_hot(l) ||
    699 		    !sched_migratable(l, curci)) {
    700 			l = TAILQ_NEXT(l, l_runq);
    701 			continue;
    702 		}
    703 		/* Recheck if chosen thread is still on the runqueue */
    704 		if (l->l_stat == LSRUN && (l->l_flag & LW_INMEM)) {
    705 			sched_dequeue(l);
    706 			l->l_cpu = curci;
    707 			lwp_setlock(l, curci->ci_schedstate.spc_mutex);
    708 			sched_enqueue(l, false);
    709 			break;
    710 		}
    711 		l = TAILQ_NEXT(l, l_runq);
    712 	}
    713 	spc_unlock(ci);
    714 
    715 	return l;
    716 }
    717 
    718 /*
    719  * Periodical calculations for balancing.
    720  */
    721 static void
    722 sched_balance(void *nocallout)
    723 {
    724 	struct cpu_info *ci, *hci;
    725 	runqueue_t *ci_rq;
    726 	CPU_INFO_ITERATOR cii;
    727 	u_int highest;
    728 
    729 	hci = curcpu();
    730 	highest = 0;
    731 
    732 	/* Make lockless countings */
    733 	for (CPU_INFO_FOREACH(cii, ci)) {
    734 		ci_rq = ci->ci_schedstate.spc_sched_info;
    735 
    736 		/* Average count of the threads */
    737 		ci_rq->r_avgcount = (ci_rq->r_avgcount + ci_rq->r_mcount) >> 1;
    738 
    739 		/* Look for CPU with the highest average */
    740 		if (ci_rq->r_avgcount > highest) {
    741 			hci = ci;
    742 			highest = ci_rq->r_avgcount;
    743 		}
    744 	}
    745 
    746 	/* Update the worker */
    747 	worker_ci = hci;
    748 
    749 	if (nocallout == NULL)
    750 		callout_schedule(&balance_ch, balance_period);
    751 }
    752 
    753 #else
    754 
    755 struct cpu_info *
    756 sched_takecpu(struct lwp *l)
    757 {
    758 
    759 	return l->l_cpu;
    760 }
    761 
    762 #endif	/* MULTIPROCESSOR */
    763 
    764 /*
    765  * Scheduler mill.
    766  */
    767 struct lwp *
    768 sched_nextlwp(void)
    769 {
    770 	struct cpu_info *ci = curcpu();
    771 	struct schedstate_percpu *spc;
    772 	TAILQ_HEAD(, lwp) *q_head;
    773 	sched_info_lwp_t *sil;
    774 	runqueue_t *ci_rq;
    775 	struct lwp *l;
    776 
    777 	spc = &ci->ci_schedstate;
    778 	ci_rq = ci->ci_schedstate.spc_sched_info;
    779 
    780 #ifdef MULTIPROCESSOR
    781 	/* If runqueue is empty, try to catch some thread from other CPU */
    782 	if (__predict_false(spc->spc_flags & SPCF_OFFLINE)) {
    783 		if ((ci_rq->r_count - ci_rq->r_mcount) == 0)
    784 			return NULL;
    785 	} else if (ci_rq->r_count == 0) {
    786 		/* Reset the counter, and call the balancer */
    787 		ci_rq->r_avgcount = 0;
    788 		sched_balance(ci);
    789 
    790 		/* The re-locking will be done inside */
    791 		return sched_catchlwp();
    792 	}
    793 #else
    794 	if (ci_rq->r_count == 0)
    795 		return NULL;
    796 #endif
    797 
    798 	/* Take the highest priority thread */
    799 	KASSERT(ci_rq->r_bitmap[ci_rq->r_highest_pri >> BITMAP_SHIFT]);
    800 	q_head = sched_getrq(ci_rq, ci_rq->r_highest_pri);
    801 	l = TAILQ_FIRST(q_head);
    802 	KASSERT(l != NULL);
    803 
    804 	/* Update the counters */
    805 	sil = l->l_sched_info;
    806 	KASSERT(sil->sl_timeslice >= min_ts);
    807 	KASSERT(sil->sl_timeslice <= max_ts);
    808 	spc->spc_ticks = sil->sl_timeslice;
    809 	sil->sl_rtime = hardclock_ticks;
    810 
    811 	return l;
    812 }
    813 
    814 bool
    815 sched_curcpu_runnable_p(void)
    816 {
    817 	const struct cpu_info *ci = curcpu();
    818 	const runqueue_t *ci_rq = ci->ci_schedstate.spc_sched_info;
    819 
    820 #ifndef __HAVE_FAST_SOFTINTS
    821 	if (ci->ci_data.cpu_softints)
    822 		return true;
    823 #endif
    824 
    825 	if (ci->ci_schedstate.spc_flags & SPCF_OFFLINE)
    826 		return (ci_rq->r_count - ci_rq->r_mcount);
    827 
    828 	return ci_rq->r_count;
    829 }
    830 
    831 /*
    832  * Time-driven events.
    833  */
    834 
    835 /*
    836  * Called once per time-quantum.  This routine is CPU-local and runs at
    837  * IPL_SCHED, thus the locking is not needed.
    838  */
    839 void
    840 sched_tick(struct cpu_info *ci)
    841 {
    842 	const runqueue_t *ci_rq = ci->ci_schedstate.spc_sched_info;
    843 	struct schedstate_percpu *spc = &ci->ci_schedstate;
    844 	struct lwp *l = curlwp;
    845 	const sched_info_lwp_t *sil = l->l_sched_info;
    846 
    847 	if (CURCPU_IDLE_P())
    848 		return;
    849 
    850 	switch (l->l_class) {
    851 	case SCHED_FIFO:
    852 		/*
    853 		 * Update the time-quantum, and continue running,
    854 		 * if thread runs on FIFO real-time policy.
    855 		 */
    856 		KASSERT(l->l_priority > PRI_HIGHEST_TS);
    857 		spc->spc_ticks = sil->sl_timeslice;
    858 		return;
    859 	case SCHED_OTHER:
    860 		/*
    861 		 * If thread is in time-sharing queue, decrease the priority,
    862 		 * and run with a higher time-quantum.
    863 		 */
    864 		KASSERT(l->l_priority <= PRI_HIGHEST_TS);
    865 		if (l->l_priority != 0)
    866 			l->l_priority--;
    867 		break;
    868 	}
    869 
    870 	/*
    871 	 * If there are higher priority threads or threads in the same queue,
    872 	 * mark that thread should yield, otherwise, continue running.
    873 	 */
    874 	if (lwp_eprio(l) <= ci_rq->r_highest_pri || l->l_target_cpu) {
    875 		spc->spc_flags |= SPCF_SHOULDYIELD;
    876 		cpu_need_resched(ci, 0);
    877 	} else
    878 		spc->spc_ticks = sil->sl_timeslice;
    879 }
    880 
    881 /*
    882  * Sysctl nodes and initialization.
    883  */
    884 
    885 static int
    886 sysctl_sched_rtts(SYSCTLFN_ARGS)
    887 {
    888 	struct sysctlnode node;
    889 	int rttsms = hztoms(rt_ts);
    890 
    891 	node = *rnode;
    892 	node.sysctl_data = &rttsms;
    893 	return sysctl_lookup(SYSCTLFN_CALL(&node));
    894 }
    895 
    896 static int
    897 sysctl_sched_mints(SYSCTLFN_ARGS)
    898 {
    899 	struct sysctlnode node;
    900 	struct cpu_info *ci;
    901 	int error, newsize;
    902 	CPU_INFO_ITERATOR cii;
    903 
    904 	node = *rnode;
    905 	node.sysctl_data = &newsize;
    906 
    907 	newsize = hztoms(min_ts);
    908 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    909 	if (error || newp == NULL)
    910 		return error;
    911 
    912 	newsize = mstohz(newsize);
    913 	if (newsize < 1 || newsize > hz || newsize >= max_ts)
    914 		return EINVAL;
    915 
    916 	/* It is safe to do this in such order */
    917 	for (CPU_INFO_FOREACH(cii, ci))
    918 		spc_lock(ci);
    919 
    920 	min_ts = newsize;
    921 	sched_precalcts();
    922 
    923 	for (CPU_INFO_FOREACH(cii, ci))
    924 		spc_unlock(ci);
    925 
    926 	return 0;
    927 }
    928 
    929 static int
    930 sysctl_sched_maxts(SYSCTLFN_ARGS)
    931 {
    932 	struct sysctlnode node;
    933 	struct cpu_info *ci;
    934 	int error, newsize;
    935 	CPU_INFO_ITERATOR cii;
    936 
    937 	node = *rnode;
    938 	node.sysctl_data = &newsize;
    939 
    940 	newsize = hztoms(max_ts);
    941 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    942 	if (error || newp == NULL)
    943 		return error;
    944 
    945 	newsize = mstohz(newsize);
    946 	if (newsize < 10 || newsize > hz || newsize <= min_ts)
    947 		return EINVAL;
    948 
    949 	/* It is safe to do this in such order */
    950 	for (CPU_INFO_FOREACH(cii, ci))
    951 		spc_lock(ci);
    952 
    953 	max_ts = newsize;
    954 	sched_precalcts();
    955 
    956 	for (CPU_INFO_FOREACH(cii, ci))
    957 		spc_unlock(ci);
    958 
    959 	return 0;
    960 }
    961 
    962 SYSCTL_SETUP(sysctl_sched_setup, "sysctl kern.sched subtree setup")
    963 {
    964 	const struct sysctlnode *node = NULL;
    965 
    966 	sysctl_createv(clog, 0, NULL, NULL,
    967 		CTLFLAG_PERMANENT,
    968 		CTLTYPE_NODE, "kern", NULL,
    969 		NULL, 0, NULL, 0,
    970 		CTL_KERN, CTL_EOL);
    971 	sysctl_createv(clog, 0, NULL, &node,
    972 		CTLFLAG_PERMANENT,
    973 		CTLTYPE_NODE, "sched",
    974 		SYSCTL_DESCR("Scheduler options"),
    975 		NULL, 0, NULL, 0,
    976 		CTL_KERN, CTL_CREATE, CTL_EOL);
    977 
    978 	if (node == NULL)
    979 		return;
    980 
    981 	sysctl_createv(clog, 0, &node, NULL,
    982 		CTLFLAG_PERMANENT,
    983 		CTLTYPE_STRING, "name", NULL,
    984 		NULL, 0, __UNCONST("M2"), 0,
    985 		CTL_CREATE, CTL_EOL);
    986 	sysctl_createv(clog, 0, &node, NULL,
    987 		CTLFLAG_PERMANENT,
    988 		CTLTYPE_INT, "rtts",
    989 		SYSCTL_DESCR("Round-robin time quantum (in miliseconds)"),
    990 		sysctl_sched_rtts, 0, NULL, 0,
    991 		CTL_CREATE, CTL_EOL);
    992 	sysctl_createv(clog, 0, &node, NULL,
    993 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
    994 		CTLTYPE_INT, "maxts",
    995 		SYSCTL_DESCR("Maximal time quantum (in miliseconds)"),
    996 		sysctl_sched_maxts, 0, &max_ts, 0,
    997 		CTL_CREATE, CTL_EOL);
    998 	sysctl_createv(clog, 0, &node, NULL,
    999 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   1000 		CTLTYPE_INT, "mints",
   1001 		SYSCTL_DESCR("Minimal time quantum (in miliseconds)"),
   1002 		sysctl_sched_mints, 0, &min_ts, 0,
   1003 		CTL_CREATE, CTL_EOL);
   1004 
   1005 #ifdef MULTIPROCESSOR
   1006 	sysctl_createv(clog, 0, &node, NULL,
   1007 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   1008 		CTLTYPE_INT, "cacheht_time",
   1009 		SYSCTL_DESCR("Cache hotness time (in ticks)"),
   1010 		NULL, 0, &cacheht_time, 0,
   1011 		CTL_CREATE, CTL_EOL);
   1012 	sysctl_createv(clog, 0, &node, NULL,
   1013 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   1014 		CTLTYPE_INT, "balance_period",
   1015 		SYSCTL_DESCR("Balance period (in ticks)"),
   1016 		NULL, 0, &balance_period, 0,
   1017 		CTL_CREATE, CTL_EOL);
   1018 	sysctl_createv(clog, 0, &node, NULL,
   1019 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   1020 		CTLTYPE_INT, "min_catch",
   1021 		SYSCTL_DESCR("Minimal count of the threads for catching"),
   1022 		NULL, 0, &min_catch, 0,
   1023 		CTL_CREATE, CTL_EOL);
   1024 #endif
   1025 }
   1026 
   1027 /*
   1028  * Debugging.
   1029  */
   1030 
   1031 #ifdef DDB
   1032 
   1033 void
   1034 sched_print_runqueue(void (*pr)(const char *, ...))
   1035 {
   1036 	runqueue_t *ci_rq;
   1037 	sched_info_lwp_t *sil;
   1038 	struct lwp *l;
   1039 	struct proc *p;
   1040 	int i;
   1041 
   1042 	struct cpu_info *ci;
   1043 	CPU_INFO_ITERATOR cii;
   1044 
   1045 	for (CPU_INFO_FOREACH(cii, ci)) {
   1046 		ci_rq = ci->ci_schedstate.spc_sched_info;
   1047 
   1048 		(*pr)("Run-queue (CPU = %d):\n", ci->ci_cpuid);
   1049 		(*pr)(" pid.lid = %d.%d, threads count = %u, "
   1050 		    "avgcount = %u, highest pri = %d\n",
   1051 		    ci->ci_curlwp->l_proc->p_pid, ci->ci_curlwp->l_lid,
   1052 		    ci_rq->r_count, ci_rq->r_avgcount, ci_rq->r_highest_pri);
   1053 		i = (PRI_COUNT >> BITMAP_SHIFT) - 1;
   1054 		do {
   1055 			uint32_t q;
   1056 			q = ci_rq->r_bitmap[i];
   1057 			(*pr)(" bitmap[%d] => [ %d (0x%x) ]\n", i, ffs(q), q);
   1058 		} while (i--);
   1059 	}
   1060 
   1061 	(*pr)("   %5s %4s %4s %10s %3s %4s %11s %3s %s\n",
   1062 	    "LID", "PRI", "EPRI", "FL", "ST", "TS", "LWP", "CPU", "LRTIME");
   1063 
   1064 	PROCLIST_FOREACH(p, &allproc) {
   1065 		(*pr)(" /- %d (%s)\n", (int)p->p_pid, p->p_comm);
   1066 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
   1067 			sil = l->l_sched_info;
   1068 			ci = l->l_cpu;
   1069 			(*pr)(" | %5d %4u %4u 0x%8.8x %3s %4u %11p %3d "
   1070 			    "%u ST=%d RT=%d %d\n",
   1071 			    (int)l->l_lid, l->l_priority, lwp_eprio(l),
   1072 			    l->l_flag, l->l_stat == LSRUN ? "RQ" :
   1073 			    (l->l_stat == LSSLEEP ? "SQ" : "-"),
   1074 			    sil->sl_timeslice, l, ci->ci_cpuid,
   1075 			    (u_int)(hardclock_ticks - sil->sl_lrtime),
   1076 			    sil->sl_slpsum, sil->sl_rtsum, sil->sl_flags);
   1077 		}
   1078 	}
   1079 }
   1080 
   1081 #endif
   1082