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