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