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