Home | History | Annotate | Line # | Download | only in kern
sched_m2.c revision 1.3.2.4
      1 /*	$NetBSD: sched_m2.c,v 1.3.2.4 2007/10/13 08:46:58 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.4 2007/10/13 08:46:58 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 	bool batch;
    500 
    501 	/*
    502 	 * Set that thread is more CPU-bound, if sum of run time exceeds the
    503 	 * sum of sleep time.  Check if thread is CPU-bound a first time.
    504 	 */
    505 	batch = (sil->sl_rtsum > sil->sl_slpsum);
    506 	if (batch) {
    507 		if ((sil->sl_flags & SL_BATCH) == 0)
    508 			batch = false;
    509 		sil->sl_flags |= SL_BATCH;
    510 	} else
    511 		sil->sl_flags &= ~SL_BATCH;
    512 
    513 	/* Reset the time sums */
    514 	sil->sl_slpsum = 0;
    515 	sil->sl_rtsum = 0;
    516 
    517 	/* Estimate threads on time-sharing queue only */
    518 	if (l->l_usrpri >= PRI_HIGHEST_TS)
    519 		return;
    520 
    521 	/* If it is CPU-bound not a first time - decrease the priority */
    522 	if (batch && l->l_usrpri != 0)
    523 		l->l_usrpri--;
    524 
    525 	/* If thread was not ran a second or more - set a high priority */
    526 	if (l->l_stat == LSRUN && sil->sl_lrtime &&
    527 	    (hardclock_ticks - sil->sl_lrtime >= hz))
    528 		lwp_changepri(l, high_pri[l->l_usrpri]);
    529 }
    530 
    531 /*
    532  * Migration and balancing.
    533  */
    534 
    535 #ifdef MULTIPROCESSOR
    536 
    537 /* Check if LWP can migrate to the chosen CPU */
    538 static inline bool
    539 sched_migratable(const struct lwp *l, const struct cpu_info *ci)
    540 {
    541 
    542 	if (ci->ci_schedstate.spc_flags & SPCF_OFFLINE)
    543 		return false;
    544 
    545 	if ((l->l_flag & LW_BOUND) == 0)
    546 		return true;
    547 #if 0
    548 	return cpu_in_pset(ci, l->l_psid);
    549 #else
    550 	return false;
    551 #endif
    552 }
    553 
    554 /*
    555  * Estimate the migration of LWP to the other CPU.
    556  * Take and return the CPU, if migration is needed.
    557  */
    558 struct cpu_info *
    559 sched_takecpu(struct lwp *l)
    560 {
    561 	struct cpu_info *ci, *tci = NULL;
    562 	struct schedstate_percpu *spc;
    563 	runqueue_t *ci_rq;
    564 	sched_info_lwp_t *sil;
    565 	CPU_INFO_ITERATOR cii;
    566 	pri_t eprio, lpri;
    567 
    568 	ci = l->l_cpu;
    569 	spc = &ci->ci_schedstate;
    570 	ci_rq = spc->spc_sched_info;
    571 
    572 	/* CPU of this thread is idling - run there */
    573 	if (ci_rq->r_count == 0)
    574 		return ci;
    575 
    576 	eprio = lwp_eprio(l);
    577 	sil = l->l_sched_info;
    578 
    579 	/* Stay if thread is cache-hot */
    580 	if (l->l_stat == LSSLEEP && l->l_slptime <= 1 &&
    581 	    CACHE_HOT(sil) && eprio >= spc->spc_curpriority)
    582 		return ci;
    583 
    584 	/* Run on current CPU if priority of thread is higher */
    585 	ci = curcpu();
    586 	spc = &ci->ci_schedstate;
    587 	if (eprio > spc->spc_curpriority && sched_migratable(l, ci))
    588 		return ci;
    589 
    590 	/*
    591 	 * Look for the CPU with the lowest priority thread.  In case of
    592 	 * equal the priority - check the lower count of the threads.
    593 	 */
    594 	lpri = PRI_COUNT;
    595 	for (CPU_INFO_FOREACH(cii, ci)) {
    596 		runqueue_t *ici_rq;
    597 		pri_t pri;
    598 
    599 		spc = &ci->ci_schedstate;
    600 		ici_rq = spc->spc_sched_info;
    601 		pri = max(spc->spc_curpriority, ici_rq->r_highest_pri);
    602 		if (pri > lpri)
    603 			continue;
    604 
    605 		if (pri == lpri && tci && ci_rq->r_count < ici_rq->r_count)
    606 			continue;
    607 
    608 		if (sched_migratable(l, ci) == false)
    609 			continue;
    610 
    611 		lpri = pri;
    612 		tci = ci;
    613 		ci_rq = ici_rq;
    614 	}
    615 
    616 	KASSERT(tci != NULL);
    617 	return tci;
    618 }
    619 
    620 /*
    621  * Tries to catch an LWP from the runqueue of other CPU.
    622  */
    623 static struct lwp *
    624 sched_catchlwp(void)
    625 {
    626 	struct cpu_info *curci = curcpu(), *ci = worker_ci;
    627 	TAILQ_HEAD(, lwp) *q_head;
    628 	runqueue_t *ci_rq;
    629 	struct lwp *l;
    630 
    631 	if (curci == ci)
    632 		return NULL;
    633 
    634 	/* Lockless check */
    635 	ci_rq = ci->ci_schedstate.spc_sched_info;
    636 	if (ci_rq->r_count < min_catch)
    637 		return NULL;
    638 
    639 	/*
    640 	 * Double-lock the runqueues.
    641 	 */
    642 	if (curci < ci) {
    643 		spc_lock(ci);
    644 	} else if (!mutex_tryenter(ci->ci_schedstate.spc_mutex)) {
    645 		const runqueue_t *cur_rq = curci->ci_schedstate.spc_sched_info;
    646 
    647 		spc_unlock(curci);
    648 		spc_lock(ci);
    649 		spc_lock(curci);
    650 
    651 		if (cur_rq->r_count) {
    652 			spc_unlock(ci);
    653 			return NULL;
    654 		}
    655 	}
    656 
    657 	if (ci_rq->r_count < min_catch) {
    658 		spc_unlock(ci);
    659 		return NULL;
    660 	}
    661 
    662 	/* Take the highest priority thread */
    663 	q_head = sched_getrq(ci_rq, ci_rq->r_highest_pri);
    664 	l = TAILQ_FIRST(q_head);
    665 
    666 	for (;;) {
    667 		sched_info_lwp_t *sil;
    668 
    669 		/* Check the first and next result from the queue */
    670 		if (l == NULL)
    671 			break;
    672 
    673 		/* Look for threads, whose are allowed to migrate */
    674 		sil = l->l_sched_info;
    675 		if ((l->l_flag & LW_SYSTEM) || CACHE_HOT(sil) ||
    676 		    sched_migratable(l, curci) == false) {
    677 			l = TAILQ_NEXT(l, l_runq);
    678 			continue;
    679 		}
    680 		/* Recheck if chosen thread is still on the runqueue */
    681 		if (l->l_stat == LSRUN && (l->l_flag & LW_INMEM)) {
    682 			sched_dequeue(l);
    683 			l->l_cpu = curci;
    684 			lwp_setlock(l, curci->ci_schedstate.spc_mutex);
    685 			sched_enqueue(l, false);
    686 			break;
    687 		}
    688 		l = TAILQ_NEXT(l, l_runq);
    689 	}
    690 	spc_unlock(ci);
    691 
    692 	return l;
    693 }
    694 
    695 /*
    696  * Periodical calculations for balancing.
    697  */
    698 static void
    699 sched_balance(void *nocallout)
    700 {
    701 	struct cpu_info *ci, *hci;
    702 	runqueue_t *ci_rq;
    703 	CPU_INFO_ITERATOR cii;
    704 	u_int highest;
    705 
    706 	hci = curcpu();
    707 	highest = 0;
    708 
    709 	/* Make lockless countings */
    710 	for (CPU_INFO_FOREACH(cii, ci)) {
    711 		ci_rq = ci->ci_schedstate.spc_sched_info;
    712 
    713 		/* Average count of the threads */
    714 		ci_rq->r_avgcount = (ci_rq->r_avgcount + ci_rq->r_mcount) >> 1;
    715 
    716 		/* Look for CPU with the highest average */
    717 		if (ci_rq->r_avgcount > highest) {
    718 			hci = ci;
    719 			highest = ci_rq->r_avgcount;
    720 		}
    721 	}
    722 
    723 	/* Update the worker */
    724 	worker_ci = hci;
    725 
    726 	if (nocallout == NULL)
    727 		callout_schedule(&balance_ch, balance_period);
    728 }
    729 
    730 #else
    731 
    732 struct cpu_info *
    733 sched_takecpu(struct lwp *l)
    734 {
    735 
    736 	return l->l_cpu;
    737 }
    738 
    739 #endif	/* MULTIPROCESSOR */
    740 
    741 /*
    742  * Scheduler mill.
    743  */
    744 struct lwp *
    745 sched_nextlwp(void)
    746 {
    747 	struct cpu_info *ci = curcpu();
    748 	struct schedstate_percpu *spc;
    749 	TAILQ_HEAD(, lwp) *q_head;
    750 	sched_info_lwp_t *sil;
    751 	runqueue_t *ci_rq;
    752 	struct lwp *l;
    753 
    754 	spc = &ci->ci_schedstate;
    755 	ci_rq = ci->ci_schedstate.spc_sched_info;
    756 
    757 #ifdef MULTIPROCESSOR
    758 	/* If runqueue is empty, try to catch some thread from other CPU */
    759 	if (spc->spc_flags & SPCF_OFFLINE) {
    760 		if (ci_rq->r_mcount == 0)
    761 			return NULL;
    762 	} else if (ci_rq->r_count == 0) {
    763 		/* Reset the counter, and call the balancer */
    764 		ci_rq->r_avgcount = 0;
    765 		sched_balance(ci);
    766 
    767 		/* The re-locking will be done inside */
    768 		return sched_catchlwp();
    769 	}
    770 #else
    771 	if (ci_rq->r_count == 0)
    772 		return NULL;
    773 #endif
    774 
    775 	/* Take the highest priority thread */
    776 	KASSERT(ci_rq->r_bitmap[ci_rq->r_highest_pri >> BITMAP_SHIFT]);
    777 	q_head = sched_getrq(ci_rq, ci_rq->r_highest_pri);
    778 	l = TAILQ_FIRST(q_head);
    779 	KASSERT(l != NULL);
    780 
    781 	/* Update the counters */
    782 	sil = l->l_sched_info;
    783 	KASSERT(sil->sl_timeslice >= min_ts);
    784 	KASSERT(sil->sl_timeslice <= max_ts);
    785 	spc->spc_ticks = sil->sl_timeslice;
    786 	sil->sl_rtime = hardclock_ticks;
    787 
    788 	return l;
    789 }
    790 
    791 bool
    792 sched_curcpu_runnable_p(void)
    793 {
    794 	const struct cpu_info *ci = curcpu();
    795 	const runqueue_t *ci_rq = ci->ci_schedstate.spc_sched_info;
    796 
    797 	if (ci->ci_schedstate.spc_flags & SPCF_OFFLINE)
    798 		return ci_rq->r_mcount;
    799 
    800 	return ci_rq->r_count;
    801 }
    802 
    803 /*
    804  * Time-driven events.
    805  */
    806 
    807 /*
    808  * Called once per time-quantum.  This routine is CPU-local and runs at
    809  * IPL_SCHED, thus the locking is not needed.
    810  */
    811 void
    812 sched_tick(struct cpu_info *ci)
    813 {
    814 	const runqueue_t *ci_rq = ci->ci_schedstate.spc_sched_info;
    815 	struct schedstate_percpu *spc = &ci->ci_schedstate;
    816 	struct lwp *l = curlwp;
    817 	sched_info_lwp_t *sil = l->l_sched_info;
    818 
    819 	if (CURCPU_IDLE_P())
    820 		return;
    821 
    822 	switch (l->l_policy) {
    823 	case SCHED_FIFO:
    824 		/*
    825 		 * Update the time-quantum, and continue running,
    826 		 * if thread runs on FIFO real-time policy.
    827 		 */
    828 		spc->spc_ticks = sil->sl_timeslice;
    829 		return;
    830 	case SCHED_OTHER:
    831 		/*
    832 		 * If thread is in time-sharing queue, decrease the priority,
    833 		 * and run with a higher time-quantum.
    834 		 */
    835 		if (l->l_usrpri > PRI_HIGHEST_TS)
    836 			break;
    837 		if (l->l_usrpri != 0)
    838 			l->l_usrpri--;
    839 		l->l_priority = l->l_usrpri;
    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", "UPRI", "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, l->l_usrpri,
   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