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