Home | History | Annotate | Line # | Download | only in kern
sched_m2.c revision 1.6.4.8
      1 /*	$NetBSD: sched_m2.c,v 1.6.4.8 2008/03/17 09:15:34 yamt 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.6.4.8 2008/03/17 09:15:34 yamt 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 	const u_int slptime = hardclock_ticks - sil->sl_slept;
    478 
    479 	/* Update sleep time delta */
    480 	sil->sl_slpsum += (l->l_slptime == 0) ? slptime : hz;
    481 
    482 	/* If thread was sleeping a second or more - set a high priority */
    483 	if (l->l_slptime > 1 || slptime >= hz)
    484 		l->l_priority = high_pri[l->l_priority];
    485 
    486 	/* Also, consider looking for a better CPU to wake up */
    487 	l->l_cpu = sched_takecpu(l);
    488 }
    489 
    490 void
    491 sched_pstats_hook(struct lwp *l)
    492 {
    493 	sched_info_lwp_t *sil = l->l_sched_info;
    494 	pri_t prio;
    495 	bool batch;
    496 
    497 	if (l->l_stat == LSSLEEP || l->l_stat == LSSTOP ||
    498 	    l->l_stat == LSSUSPENDED)
    499 		l->l_slptime++;
    500 
    501 	/*
    502 	 * Set that thread is more CPU-bound, if sum of run time exceeds the
    503 	 * sum of sleep time.  Check if thread is CPU-bound a first time.
    504 	 */
    505 	batch = (sil->sl_rtsum > sil->sl_slpsum);
    506 	if (batch) {
    507 		if ((sil->sl_flags & SL_BATCH) == 0)
    508 			batch = false;
    509 		sil->sl_flags |= SL_BATCH;
    510 	} else
    511 		sil->sl_flags &= ~SL_BATCH;
    512 
    513 	/*
    514 	 * If thread is CPU-bound and never sleeps, it would occupy the CPU.
    515 	 * In such case reset the value of last sleep, and check it later, if
    516 	 * it is still zero - perform the migration, unmark the batch flag.
    517 	 */
    518 	if (batch && (l->l_slptime + sil->sl_slpsum) == 0) {
    519 		if (l->l_stat != LSONPROC && sil->sl_slept == 0) {
    520 			struct cpu_info *ci = sched_takecpu(l);
    521 
    522 			if (l->l_cpu != ci)
    523 				l->l_target_cpu = ci;
    524 			sil->sl_flags &= ~SL_BATCH;
    525 		} else {
    526 			sil->sl_slept = 0;
    527 		}
    528 	}
    529 
    530 	/* Reset the time sums */
    531 	sil->sl_slpsum = 0;
    532 	sil->sl_rtsum = 0;
    533 
    534 	/*
    535 	 * Estimate threads on time-sharing queue only, however,
    536 	 * exclude the highest priority for performance purposes.
    537 	 */
    538 	if (l->l_priority >= PRI_HIGHEST_TS)
    539 		return;
    540 	KASSERT(l->l_class == SCHED_OTHER);
    541 
    542 	/* If it is CPU-bound not a first time - decrease the priority */
    543 	prio = l->l_priority;
    544 	if (batch && prio != 0)
    545 		prio--;
    546 
    547 	/* If thread was not ran a second or more - set a high priority */
    548 	if (l->l_stat == LSRUN) {
    549 		if (sil->sl_lrtime && (hardclock_ticks - sil->sl_lrtime >= hz))
    550 			prio = high_pri[prio];
    551 		/* Re-enqueue the thread if priority has changed */
    552 		if (prio != l->l_priority)
    553 			lwp_changepri(l, prio);
    554 	} else {
    555 		/* In other states, change the priority directly */
    556 		l->l_priority = prio;
    557 	}
    558 }
    559 
    560 /*
    561  * Migration and balancing.
    562  */
    563 
    564 #ifdef MULTIPROCESSOR
    565 
    566 /* Estimate if LWP is cache-hot */
    567 static inline bool
    568 lwp_cache_hot(const struct lwp *l)
    569 {
    570 	const sched_info_lwp_t *sil = l->l_sched_info;
    571 
    572 	if (l->l_slptime || sil->sl_lrtime == 0)
    573 		return false;
    574 
    575 	return (hardclock_ticks - sil->sl_lrtime <= cacheht_time);
    576 }
    577 
    578 /* Check if LWP can migrate to the chosen CPU */
    579 static inline bool
    580 sched_migratable(const struct lwp *l, struct cpu_info *ci)
    581 {
    582 	const struct schedstate_percpu *spc = &ci->ci_schedstate;
    583 
    584 	/* CPU is offline */
    585 	if (__predict_false(spc->spc_flags & SPCF_OFFLINE))
    586 		return false;
    587 
    588 	/* Affinity bind */
    589 	if (__predict_false(l->l_flag & LW_AFFINITY))
    590 		return CPU_ISSET(cpu_index(ci), &l->l_affinity);
    591 
    592 	/* Processor-set */
    593 	return (spc->spc_psid == l->l_psid);
    594 }
    595 
    596 /*
    597  * Estimate the migration of LWP to the other CPU.
    598  * Take and return the CPU, if migration is needed.
    599  */
    600 struct cpu_info *
    601 sched_takecpu(struct lwp *l)
    602 {
    603 	struct cpu_info *ci, *tci;
    604 	struct schedstate_percpu *spc;
    605 	runqueue_t *ci_rq;
    606 	CPU_INFO_ITERATOR cii;
    607 	pri_t eprio, lpri;
    608 
    609 	KASSERT(lwp_locked(l, NULL));
    610 
    611 	ci = l->l_cpu;
    612 	spc = &ci->ci_schedstate;
    613 	ci_rq = spc->spc_sched_info;
    614 
    615 	/* If thread is strictly bound, do not estimate other CPUs */
    616 	if (l->l_flag & LW_BOUND)
    617 		return ci;
    618 
    619 	/* CPU of this thread is idling - run there */
    620 	if (ci_rq->r_count == 0)
    621 		return ci;
    622 
    623 	eprio = lwp_eprio(l);
    624 
    625 	/* Stay if thread is cache-hot */
    626 	if (__predict_true(l->l_stat != LSIDL) &&
    627 	    lwp_cache_hot(l) && eprio >= spc->spc_curpriority)
    628 		return ci;
    629 
    630 	/* Run on current CPU if priority of thread is higher */
    631 	ci = curcpu();
    632 	spc = &ci->ci_schedstate;
    633 	if (eprio > spc->spc_curpriority && sched_migratable(l, ci))
    634 		return ci;
    635 
    636 	/*
    637 	 * Look for the CPU with the lowest priority thread.  In case of
    638 	 * equal the priority - check the lower count of the threads.
    639 	 */
    640 	tci = l->l_cpu;
    641 	lpri = PRI_COUNT;
    642 	for (CPU_INFO_FOREACH(cii, ci)) {
    643 		runqueue_t *ici_rq;
    644 		pri_t pri;
    645 
    646 		spc = &ci->ci_schedstate;
    647 		ici_rq = spc->spc_sched_info;
    648 		pri = max(spc->spc_curpriority, ici_rq->r_highest_pri);
    649 		if (pri > lpri)
    650 			continue;
    651 
    652 		if (pri == lpri && ci_rq->r_count < ici_rq->r_count)
    653 			continue;
    654 
    655 		if (!sched_migratable(l, ci))
    656 			continue;
    657 
    658 		lpri = pri;
    659 		tci = ci;
    660 		ci_rq = ici_rq;
    661 	}
    662 	return tci;
    663 }
    664 
    665 /*
    666  * Tries to catch an LWP from the runqueue of other CPU.
    667  */
    668 static struct lwp *
    669 sched_catchlwp(void)
    670 {
    671 	struct cpu_info *curci = curcpu(), *ci = worker_ci;
    672 	TAILQ_HEAD(, lwp) *q_head;
    673 	runqueue_t *ci_rq;
    674 	struct lwp *l;
    675 
    676 	if (curci == ci)
    677 		return NULL;
    678 
    679 	/* Lockless check */
    680 	ci_rq = ci->ci_schedstate.spc_sched_info;
    681 	if (ci_rq->r_mcount < min_catch)
    682 		return NULL;
    683 
    684 	/*
    685 	 * Double-lock the runqueues.
    686 	 */
    687 	if (curci < ci) {
    688 		spc_lock(ci);
    689 	} else if (!mutex_tryenter(ci->ci_schedstate.spc_mutex)) {
    690 		const runqueue_t *cur_rq = curci->ci_schedstate.spc_sched_info;
    691 
    692 		spc_unlock(curci);
    693 		spc_lock(ci);
    694 		spc_lock(curci);
    695 
    696 		if (cur_rq->r_count) {
    697 			spc_unlock(ci);
    698 			return NULL;
    699 		}
    700 	}
    701 
    702 	if (ci_rq->r_mcount < min_catch) {
    703 		spc_unlock(ci);
    704 		return NULL;
    705 	}
    706 
    707 	/* Take the highest priority thread */
    708 	q_head = sched_getrq(ci_rq, ci_rq->r_highest_pri);
    709 	l = TAILQ_FIRST(q_head);
    710 
    711 	for (;;) {
    712 		/* Check the first and next result from the queue */
    713 		if (l == NULL)
    714 			break;
    715 		KASSERT(l->l_stat == LSRUN);
    716 		KASSERT(l->l_flag & LW_INMEM);
    717 
    718 		/* Look for threads, whose are allowed to migrate */
    719 		if ((l->l_flag & LW_BOUND) || lwp_cache_hot(l) ||
    720 		    !sched_migratable(l, curci)) {
    721 			l = TAILQ_NEXT(l, l_runq);
    722 			continue;
    723 		}
    724 
    725 		/* Grab the thread, and move to the local run queue */
    726 		sched_dequeue(l);
    727 		l->l_cpu = curci;
    728 		lwp_unlock_to(l, curci->ci_schedstate.spc_mutex);
    729 		sched_enqueue(l, false);
    730 		return l;
    731 	}
    732 	spc_unlock(ci);
    733 
    734 	return l;
    735 }
    736 
    737 /*
    738  * Periodical calculations for balancing.
    739  */
    740 static void
    741 sched_balance(void *nocallout)
    742 {
    743 	struct cpu_info *ci, *hci;
    744 	runqueue_t *ci_rq;
    745 	CPU_INFO_ITERATOR cii;
    746 	u_int highest;
    747 
    748 	hci = curcpu();
    749 	highest = 0;
    750 
    751 	/* Make lockless countings */
    752 	for (CPU_INFO_FOREACH(cii, ci)) {
    753 		ci_rq = ci->ci_schedstate.spc_sched_info;
    754 
    755 		/* Average count of the threads */
    756 		ci_rq->r_avgcount = (ci_rq->r_avgcount + ci_rq->r_mcount) >> 1;
    757 
    758 		/* Look for CPU with the highest average */
    759 		if (ci_rq->r_avgcount > highest) {
    760 			hci = ci;
    761 			highest = ci_rq->r_avgcount;
    762 		}
    763 	}
    764 
    765 	/* Update the worker */
    766 	worker_ci = hci;
    767 
    768 	if (nocallout == NULL)
    769 		callout_schedule(&balance_ch, balance_period);
    770 }
    771 
    772 #else
    773 
    774 struct cpu_info *
    775 sched_takecpu(struct lwp *l)
    776 {
    777 
    778 	return l->l_cpu;
    779 }
    780 
    781 #endif	/* MULTIPROCESSOR */
    782 
    783 /*
    784  * Scheduler mill.
    785  */
    786 struct lwp *
    787 sched_nextlwp(void)
    788 {
    789 	struct cpu_info *ci = curcpu();
    790 	struct schedstate_percpu *spc;
    791 	TAILQ_HEAD(, lwp) *q_head;
    792 	sched_info_lwp_t *sil;
    793 	runqueue_t *ci_rq;
    794 	struct lwp *l;
    795 
    796 	spc = &ci->ci_schedstate;
    797 	ci_rq = ci->ci_schedstate.spc_sched_info;
    798 
    799 #ifdef MULTIPROCESSOR
    800 	/* If runqueue is empty, try to catch some thread from other CPU */
    801 	if (__predict_false(spc->spc_flags & SPCF_OFFLINE)) {
    802 		if ((ci_rq->r_count - ci_rq->r_mcount) == 0)
    803 			return NULL;
    804 	} else if (ci_rq->r_count == 0) {
    805 		/* Reset the counter, and call the balancer */
    806 		ci_rq->r_avgcount = 0;
    807 		sched_balance(ci);
    808 
    809 		/* The re-locking will be done inside */
    810 		return sched_catchlwp();
    811 	}
    812 #else
    813 	if (ci_rq->r_count == 0)
    814 		return NULL;
    815 #endif
    816 
    817 	/* Take the highest priority thread */
    818 	KASSERT(ci_rq->r_bitmap[ci_rq->r_highest_pri >> BITMAP_SHIFT]);
    819 	q_head = sched_getrq(ci_rq, ci_rq->r_highest_pri);
    820 	l = TAILQ_FIRST(q_head);
    821 	KASSERT(l != NULL);
    822 
    823 	/* Update the counters */
    824 	sil = l->l_sched_info;
    825 	KASSERT(sil->sl_timeslice >= min_ts);
    826 	KASSERT(sil->sl_timeslice <= max_ts);
    827 	spc->spc_ticks = sil->sl_timeslice;
    828 	sil->sl_rtime = hardclock_ticks;
    829 
    830 	return l;
    831 }
    832 
    833 bool
    834 sched_curcpu_runnable_p(void)
    835 {
    836 	const struct cpu_info *ci = curcpu();
    837 	const runqueue_t *ci_rq = ci->ci_schedstate.spc_sched_info;
    838 
    839 #ifndef __HAVE_FAST_SOFTINTS
    840 	if (ci->ci_data.cpu_softints)
    841 		return true;
    842 #endif
    843 
    844 	if (ci->ci_schedstate.spc_flags & SPCF_OFFLINE)
    845 		return (ci_rq->r_count - ci_rq->r_mcount);
    846 
    847 	return ci_rq->r_count;
    848 }
    849 
    850 /*
    851  * Time-driven events.
    852  */
    853 
    854 /*
    855  * Called once per time-quantum.  This routine is CPU-local and runs at
    856  * IPL_SCHED, thus the locking is not needed.
    857  */
    858 void
    859 sched_tick(struct cpu_info *ci)
    860 {
    861 	const runqueue_t *ci_rq = ci->ci_schedstate.spc_sched_info;
    862 	struct schedstate_percpu *spc = &ci->ci_schedstate;
    863 	struct lwp *l = curlwp;
    864 	const sched_info_lwp_t *sil = l->l_sched_info;
    865 
    866 	if (CURCPU_IDLE_P())
    867 		return;
    868 
    869 	switch (l->l_class) {
    870 	case SCHED_FIFO:
    871 		/*
    872 		 * Update the time-quantum, and continue running,
    873 		 * if thread runs on FIFO real-time policy.
    874 		 */
    875 		KASSERT(l->l_priority > PRI_HIGHEST_TS);
    876 		spc->spc_ticks = sil->sl_timeslice;
    877 		return;
    878 	case SCHED_OTHER:
    879 		/*
    880 		 * If thread is in time-sharing queue, decrease the priority,
    881 		 * and run with a higher time-quantum.
    882 		 */
    883 		KASSERT(l->l_priority <= PRI_HIGHEST_TS);
    884 		if (l->l_priority != 0)
    885 			l->l_priority--;
    886 		break;
    887 	}
    888 
    889 	/*
    890 	 * If there are higher priority threads or threads in the same queue,
    891 	 * mark that thread should yield, otherwise, continue running.
    892 	 */
    893 	if (lwp_eprio(l) <= ci_rq->r_highest_pri || l->l_target_cpu) {
    894 		spc->spc_flags |= SPCF_SHOULDYIELD;
    895 		cpu_need_resched(ci, 0);
    896 	} else
    897 		spc->spc_ticks = sil->sl_timeslice;
    898 }
    899 
    900 /*
    901  * Sysctl nodes and initialization.
    902  */
    903 
    904 static int
    905 sysctl_sched_rtts(SYSCTLFN_ARGS)
    906 {
    907 	struct sysctlnode node;
    908 	int rttsms = hztoms(rt_ts);
    909 
    910 	node = *rnode;
    911 	node.sysctl_data = &rttsms;
    912 	return sysctl_lookup(SYSCTLFN_CALL(&node));
    913 }
    914 
    915 static int
    916 sysctl_sched_mints(SYSCTLFN_ARGS)
    917 {
    918 	struct sysctlnode node;
    919 	struct cpu_info *ci;
    920 	int error, newsize;
    921 	CPU_INFO_ITERATOR cii;
    922 
    923 	node = *rnode;
    924 	node.sysctl_data = &newsize;
    925 
    926 	newsize = hztoms(min_ts);
    927 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    928 	if (error || newp == NULL)
    929 		return error;
    930 
    931 	newsize = mstohz(newsize);
    932 	if (newsize < 1 || newsize > hz || newsize >= max_ts)
    933 		return EINVAL;
    934 
    935 	/* It is safe to do this in such order */
    936 	for (CPU_INFO_FOREACH(cii, ci))
    937 		spc_lock(ci);
    938 
    939 	min_ts = newsize;
    940 	sched_precalcts();
    941 
    942 	for (CPU_INFO_FOREACH(cii, ci))
    943 		spc_unlock(ci);
    944 
    945 	return 0;
    946 }
    947 
    948 static int
    949 sysctl_sched_maxts(SYSCTLFN_ARGS)
    950 {
    951 	struct sysctlnode node;
    952 	struct cpu_info *ci;
    953 	int error, newsize;
    954 	CPU_INFO_ITERATOR cii;
    955 
    956 	node = *rnode;
    957 	node.sysctl_data = &newsize;
    958 
    959 	newsize = hztoms(max_ts);
    960 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    961 	if (error || newp == NULL)
    962 		return error;
    963 
    964 	newsize = mstohz(newsize);
    965 	if (newsize < 10 || newsize > hz || newsize <= min_ts)
    966 		return EINVAL;
    967 
    968 	/* It is safe to do this in such order */
    969 	for (CPU_INFO_FOREACH(cii, ci))
    970 		spc_lock(ci);
    971 
    972 	max_ts = newsize;
    973 	sched_precalcts();
    974 
    975 	for (CPU_INFO_FOREACH(cii, ci))
    976 		spc_unlock(ci);
    977 
    978 	return 0;
    979 }
    980 
    981 SYSCTL_SETUP(sysctl_sched_setup, "sysctl kern.sched subtree setup")
    982 {
    983 	const struct sysctlnode *node = NULL;
    984 
    985 	sysctl_createv(clog, 0, NULL, NULL,
    986 		CTLFLAG_PERMANENT,
    987 		CTLTYPE_NODE, "kern", NULL,
    988 		NULL, 0, NULL, 0,
    989 		CTL_KERN, CTL_EOL);
    990 	sysctl_createv(clog, 0, NULL, &node,
    991 		CTLFLAG_PERMANENT,
    992 		CTLTYPE_NODE, "sched",
    993 		SYSCTL_DESCR("Scheduler options"),
    994 		NULL, 0, NULL, 0,
    995 		CTL_KERN, CTL_CREATE, CTL_EOL);
    996 
    997 	if (node == NULL)
    998 		return;
    999 
   1000 	sysctl_createv(clog, 0, &node, NULL,
   1001 		CTLFLAG_PERMANENT,
   1002 		CTLTYPE_STRING, "name", NULL,
   1003 		NULL, 0, __UNCONST("M2"), 0,
   1004 		CTL_CREATE, CTL_EOL);
   1005 	sysctl_createv(clog, 0, &node, NULL,
   1006 		CTLFLAG_PERMANENT,
   1007 		CTLTYPE_INT, "rtts",
   1008 		SYSCTL_DESCR("Round-robin time quantum (in miliseconds)"),
   1009 		sysctl_sched_rtts, 0, NULL, 0,
   1010 		CTL_CREATE, CTL_EOL);
   1011 	sysctl_createv(clog, 0, &node, NULL,
   1012 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   1013 		CTLTYPE_INT, "maxts",
   1014 		SYSCTL_DESCR("Maximal time quantum (in miliseconds)"),
   1015 		sysctl_sched_maxts, 0, &max_ts, 0,
   1016 		CTL_CREATE, CTL_EOL);
   1017 	sysctl_createv(clog, 0, &node, NULL,
   1018 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   1019 		CTLTYPE_INT, "mints",
   1020 		SYSCTL_DESCR("Minimal time quantum (in miliseconds)"),
   1021 		sysctl_sched_mints, 0, &min_ts, 0,
   1022 		CTL_CREATE, CTL_EOL);
   1023 
   1024 #ifdef MULTIPROCESSOR
   1025 	sysctl_createv(clog, 0, &node, NULL,
   1026 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   1027 		CTLTYPE_INT, "cacheht_time",
   1028 		SYSCTL_DESCR("Cache hotness time (in ticks)"),
   1029 		NULL, 0, &cacheht_time, 0,
   1030 		CTL_CREATE, CTL_EOL);
   1031 	sysctl_createv(clog, 0, &node, NULL,
   1032 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   1033 		CTLTYPE_INT, "balance_period",
   1034 		SYSCTL_DESCR("Balance period (in ticks)"),
   1035 		NULL, 0, &balance_period, 0,
   1036 		CTL_CREATE, CTL_EOL);
   1037 	sysctl_createv(clog, 0, &node, NULL,
   1038 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   1039 		CTLTYPE_INT, "min_catch",
   1040 		SYSCTL_DESCR("Minimal count of the threads for catching"),
   1041 		NULL, 0, &min_catch, 0,
   1042 		CTL_CREATE, CTL_EOL);
   1043 #endif
   1044 }
   1045 
   1046 /*
   1047  * Debugging.
   1048  */
   1049 
   1050 #ifdef DDB
   1051 
   1052 void
   1053 sched_print_runqueue(void (*pr)(const char *, ...))
   1054 {
   1055 	runqueue_t *ci_rq;
   1056 	sched_info_lwp_t *sil;
   1057 	struct lwp *l;
   1058 	struct proc *p;
   1059 	int i;
   1060 
   1061 	struct cpu_info *ci;
   1062 	CPU_INFO_ITERATOR cii;
   1063 
   1064 	for (CPU_INFO_FOREACH(cii, ci)) {
   1065 		ci_rq = ci->ci_schedstate.spc_sched_info;
   1066 
   1067 		(*pr)("Run-queue (CPU = %u):\n", ci->ci_index);
   1068 		(*pr)(" pid.lid = %d.%d, threads count = %u, "
   1069 		    "avgcount = %u, highest pri = %d\n",
   1070 		    ci->ci_curlwp->l_proc->p_pid, ci->ci_curlwp->l_lid,
   1071 		    ci_rq->r_count, ci_rq->r_avgcount, ci_rq->r_highest_pri);
   1072 		i = (PRI_COUNT >> BITMAP_SHIFT) - 1;
   1073 		do {
   1074 			uint32_t q;
   1075 			q = ci_rq->r_bitmap[i];
   1076 			(*pr)(" bitmap[%d] => [ %d (0x%x) ]\n", i, ffs(q), q);
   1077 		} while (i--);
   1078 	}
   1079 
   1080 	(*pr)("   %5s %4s %4s %10s %3s %4s %11s %3s %s\n",
   1081 	    "LID", "PRI", "EPRI", "FL", "ST", "TS", "LWP", "CPU", "LRTIME");
   1082 
   1083 	PROCLIST_FOREACH(p, &allproc) {
   1084 		(*pr)(" /- %d (%s)\n", (int)p->p_pid, p->p_comm);
   1085 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
   1086 			sil = l->l_sched_info;
   1087 			ci = l->l_cpu;
   1088 			(*pr)(" | %5d %4u %4u 0x%8.8x %3s %4u %11p %3u "
   1089 			    "%u ST=%d RT=%d %d\n",
   1090 			    (int)l->l_lid, l->l_priority, lwp_eprio(l),
   1091 			    l->l_flag, l->l_stat == LSRUN ? "RQ" :
   1092 			    (l->l_stat == LSSLEEP ? "SQ" : "-"),
   1093 			    sil->sl_timeslice, l, ci->ci_index,
   1094 			    (u_int)(hardclock_ticks - sil->sl_lrtime),
   1095 			    sil->sl_slpsum, sil->sl_rtsum, sil->sl_flags);
   1096 		}
   1097 	}
   1098 }
   1099 
   1100 #endif
   1101