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