xref: /freebsd/sys/kern/sched_ule.c (revision d086ded32300bc0f33fb1574d0bcfccfbc60881d)
1 /*-
2  * Copyright (c) 2002-2003, Jeffrey Roberson <jeff@freebsd.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice unmodified, this list of conditions, and the following
10  *    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 AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/kernel.h>
33 #include <sys/ktr.h>
34 #include <sys/lock.h>
35 #include <sys/mutex.h>
36 #include <sys/proc.h>
37 #include <sys/resource.h>
38 #include <sys/sched.h>
39 #include <sys/smp.h>
40 #include <sys/sx.h>
41 #include <sys/sysctl.h>
42 #include <sys/sysproto.h>
43 #include <sys/vmmeter.h>
44 #ifdef DDB
45 #include <ddb/ddb.h>
46 #endif
47 #ifdef KTRACE
48 #include <sys/uio.h>
49 #include <sys/ktrace.h>
50 #endif
51 
52 #include <machine/cpu.h>
53 
54 #define KTR_ULE         KTR_NFS
55 
56 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
57 /* XXX This is bogus compatability crap for ps */
58 static fixpt_t  ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
59 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
60 
61 static void sched_setup(void *dummy);
62 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL)
63 
64 static SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "SCHED");
65 
66 static int sched_strict;
67 SYSCTL_INT(_kern_sched, OID_AUTO, strict, CTLFLAG_RD, &sched_strict, 0, "");
68 
69 static int slice_min = 1;
70 SYSCTL_INT(_kern_sched, OID_AUTO, slice_min, CTLFLAG_RW, &slice_min, 0, "");
71 
72 static int slice_max = 10;
73 SYSCTL_INT(_kern_sched, OID_AUTO, slice_max, CTLFLAG_RW, &slice_max, 0, "");
74 
75 int realstathz;
76 int tickincr = 1;
77 
78 #ifdef SMP
79 /* Callout to handle load balancing SMP systems. */
80 static struct callout kseq_lb_callout;
81 #endif
82 
83 /*
84  * These datastructures are allocated within their parent datastructure but
85  * are scheduler specific.
86  */
87 
88 struct ke_sched {
89 	int		ske_slice;
90 	struct runq	*ske_runq;
91 	/* The following variables are only used for pctcpu calculation */
92 	int		ske_ltick;	/* Last tick that we were running on */
93 	int		ske_ftick;	/* First tick that we were running on */
94 	int		ske_ticks;	/* Tick count */
95 	/* CPU that we have affinity for. */
96 	u_char		ske_cpu;
97 };
98 #define	ke_slice	ke_sched->ske_slice
99 #define	ke_runq		ke_sched->ske_runq
100 #define	ke_ltick	ke_sched->ske_ltick
101 #define	ke_ftick	ke_sched->ske_ftick
102 #define	ke_ticks	ke_sched->ske_ticks
103 #define	ke_cpu		ke_sched->ske_cpu
104 
105 struct kg_sched {
106 	int	skg_slptime;		/* Number of ticks we vol. slept */
107 	int	skg_runtime;		/* Number of ticks we were running */
108 };
109 #define	kg_slptime	kg_sched->skg_slptime
110 #define	kg_runtime	kg_sched->skg_runtime
111 
112 struct td_sched {
113 	int	std_slptime;
114 };
115 #define	td_slptime	td_sched->std_slptime
116 
117 struct td_sched td_sched;
118 struct ke_sched ke_sched;
119 struct kg_sched kg_sched;
120 
121 struct ke_sched *kse0_sched = &ke_sched;
122 struct kg_sched *ksegrp0_sched = &kg_sched;
123 struct p_sched *proc0_sched = NULL;
124 struct td_sched *thread0_sched = &td_sched;
125 
126 /*
127  * The priority is primarily determined by the interactivity score.  Thus, we
128  * give lower(better) priorities to kse groups that use less CPU.  The nice
129  * value is then directly added to this to allow nice to have some effect
130  * on latency.
131  *
132  * PRI_RANGE:	Total priority range for timeshare threads.
133  * PRI_NRESV:	Number of nice values.
134  * PRI_BASE:	The start of the dynamic range.
135  */
136 #define	SCHED_PRI_RANGE		(PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE + 1)
137 #define	SCHED_PRI_NRESV		PRIO_TOTAL
138 #define	SCHED_PRI_NHALF		(PRIO_TOTAL / 2)
139 #define	SCHED_PRI_NTHRESH	(SCHED_PRI_NHALF - 1)
140 #define	SCHED_PRI_BASE		(PRI_MIN_TIMESHARE)
141 #define	SCHED_PRI_INTERACT(score)					\
142     ((score) * SCHED_PRI_RANGE / SCHED_INTERACT_MAX)
143 
144 /*
145  * These determine the interactivity of a process.
146  *
147  * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
148  *		before throttling back.
149  * SLP_RUN_THROTTLE:	Divisor for reducing slp/run time.
150  * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
151  * INTERACT_THRESH:	Threshhold for placement on the current runq.
152  */
153 #define	SCHED_SLP_RUN_MAX	((hz * 2) << 10)
154 #define	SCHED_SLP_RUN_THROTTLE	(2)
155 #define	SCHED_INTERACT_MAX	(100)
156 #define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
157 #define	SCHED_INTERACT_THRESH	(20)
158 
159 /*
160  * These parameters and macros determine the size of the time slice that is
161  * granted to each thread.
162  *
163  * SLICE_MIN:	Minimum time slice granted, in units of ticks.
164  * SLICE_MAX:	Maximum time slice granted.
165  * SLICE_RANGE:	Range of available time slices scaled by hz.
166  * SLICE_SCALE:	The number slices granted per val in the range of [0, max].
167  * SLICE_NICE:  Determine the amount of slice granted to a scaled nice.
168  */
169 #define	SCHED_SLICE_MIN			(slice_min)
170 #define	SCHED_SLICE_MAX			(slice_max)
171 #define	SCHED_SLICE_RANGE		(SCHED_SLICE_MAX - SCHED_SLICE_MIN + 1)
172 #define	SCHED_SLICE_SCALE(val, max)	(((val) * SCHED_SLICE_RANGE) / (max))
173 #define	SCHED_SLICE_NICE(nice)						\
174     (SCHED_SLICE_MAX - SCHED_SLICE_SCALE((nice), SCHED_PRI_NTHRESH))
175 
176 /*
177  * This macro determines whether or not the kse belongs on the current or
178  * next run queue.
179  *
180  * XXX nice value should effect how interactive a kg is.
181  */
182 #define	SCHED_INTERACTIVE(kg)						\
183     (sched_interact_score(kg) < SCHED_INTERACT_THRESH)
184 #define	SCHED_CURR(kg, ke)						\
185     (ke->ke_thread->td_priority < PRI_MIN_TIMESHARE || SCHED_INTERACTIVE(kg))
186 
187 /*
188  * Cpu percentage computation macros and defines.
189  *
190  * SCHED_CPU_TIME:	Number of seconds to average the cpu usage across.
191  * SCHED_CPU_TICKS:	Number of hz ticks to average the cpu usage across.
192  */
193 
194 #define	SCHED_CPU_TIME	10
195 #define	SCHED_CPU_TICKS	(hz * SCHED_CPU_TIME)
196 
197 /*
198  * kseq - per processor runqs and statistics.
199  */
200 
201 #define	KSEQ_NCLASS	(PRI_IDLE + 1)	/* Number of run classes. */
202 
203 struct kseq {
204 	struct runq	ksq_idle;		/* Queue of IDLE threads. */
205 	struct runq	ksq_timeshare[2];	/* Run queues for !IDLE. */
206 	struct runq	*ksq_next;		/* Next timeshare queue. */
207 	struct runq	*ksq_curr;		/* Current queue. */
208 	int		ksq_loads[KSEQ_NCLASS];	/* Load for each class */
209 	int		ksq_load;		/* Aggregate load. */
210 	short		ksq_nice[PRIO_TOTAL + 1]; /* KSEs in each nice bin. */
211 	short		ksq_nicemin;		/* Least nice. */
212 #ifdef SMP
213 	unsigned int	ksq_rslices;	/* Slices on run queue */
214 #endif
215 };
216 
217 /*
218  * One kse queue per processor.
219  */
220 #ifdef SMP
221 struct kseq	kseq_cpu[MAXCPU];
222 #define	KSEQ_SELF()	(&kseq_cpu[PCPU_GET(cpuid)])
223 #define	KSEQ_CPU(x)	(&kseq_cpu[(x)])
224 #else
225 struct kseq	kseq_cpu;
226 #define	KSEQ_SELF()	(&kseq_cpu)
227 #define	KSEQ_CPU(x)	(&kseq_cpu)
228 #endif
229 
230 static void sched_slice(struct kse *ke);
231 static void sched_priority(struct ksegrp *kg);
232 static int sched_interact_score(struct ksegrp *kg);
233 static void sched_interact_update(struct ksegrp *kg);
234 void sched_pctcpu_update(struct kse *ke);
235 int sched_pickcpu(void);
236 
237 /* Operations on per processor queues */
238 static struct kse * kseq_choose(struct kseq *kseq);
239 static void kseq_setup(struct kseq *kseq);
240 static void kseq_add(struct kseq *kseq, struct kse *ke);
241 static void kseq_rem(struct kseq *kseq, struct kse *ke);
242 static void kseq_nice_add(struct kseq *kseq, int nice);
243 static void kseq_nice_rem(struct kseq *kseq, int nice);
244 void kseq_print(int cpu);
245 #ifdef SMP
246 struct kseq * kseq_load_highest(void);
247 void kseq_balance(void *arg);
248 void kseq_move(struct kseq *from, int cpu);
249 #endif
250 
251 void
252 kseq_print(int cpu)
253 {
254 	struct kseq *kseq;
255 	int i;
256 
257 	kseq = KSEQ_CPU(cpu);
258 
259 	printf("kseq:\n");
260 	printf("\tload:           %d\n", kseq->ksq_load);
261 	printf("\tload ITHD:      %d\n", kseq->ksq_loads[PRI_ITHD]);
262 	printf("\tload REALTIME:  %d\n", kseq->ksq_loads[PRI_REALTIME]);
263 	printf("\tload TIMESHARE: %d\n", kseq->ksq_loads[PRI_TIMESHARE]);
264 	printf("\tload IDLE:      %d\n", kseq->ksq_loads[PRI_IDLE]);
265 	printf("\tnicemin:\t%d\n", kseq->ksq_nicemin);
266 	printf("\tnice counts:\n");
267 	for (i = 0; i < PRIO_TOTAL + 1; i++)
268 		if (kseq->ksq_nice[i])
269 			printf("\t\t%d = %d\n",
270 			    i - SCHED_PRI_NHALF, kseq->ksq_nice[i]);
271 }
272 
273 static void
274 kseq_add(struct kseq *kseq, struct kse *ke)
275 {
276 	mtx_assert(&sched_lock, MA_OWNED);
277 	kseq->ksq_loads[PRI_BASE(ke->ke_ksegrp->kg_pri_class)]++;
278 	kseq->ksq_load++;
279 	if (ke->ke_ksegrp->kg_pri_class == PRI_TIMESHARE)
280 	CTR6(KTR_ULE, "Add kse %p to %p (slice: %d, pri: %d, nice: %d(%d))",
281 	    ke, ke->ke_runq, ke->ke_slice, ke->ke_thread->td_priority,
282 	    ke->ke_ksegrp->kg_nice, kseq->ksq_nicemin);
283 	if (ke->ke_ksegrp->kg_pri_class == PRI_TIMESHARE)
284 		kseq_nice_add(kseq, ke->ke_ksegrp->kg_nice);
285 #ifdef SMP
286 	kseq->ksq_rslices += ke->ke_slice;
287 #endif
288 }
289 
290 static void
291 kseq_rem(struct kseq *kseq, struct kse *ke)
292 {
293 	mtx_assert(&sched_lock, MA_OWNED);
294 	kseq->ksq_loads[PRI_BASE(ke->ke_ksegrp->kg_pri_class)]--;
295 	kseq->ksq_load--;
296 	ke->ke_runq = NULL;
297 	if (ke->ke_ksegrp->kg_pri_class == PRI_TIMESHARE)
298 		kseq_nice_rem(kseq, ke->ke_ksegrp->kg_nice);
299 #ifdef SMP
300 	kseq->ksq_rslices -= ke->ke_slice;
301 #endif
302 }
303 
304 static void
305 kseq_nice_add(struct kseq *kseq, int nice)
306 {
307 	mtx_assert(&sched_lock, MA_OWNED);
308 	/* Normalize to zero. */
309 	kseq->ksq_nice[nice + SCHED_PRI_NHALF]++;
310 	if (nice < kseq->ksq_nicemin || kseq->ksq_loads[PRI_TIMESHARE] == 1)
311 		kseq->ksq_nicemin = nice;
312 }
313 
314 static void
315 kseq_nice_rem(struct kseq *kseq, int nice)
316 {
317 	int n;
318 
319 	mtx_assert(&sched_lock, MA_OWNED);
320 	/* Normalize to zero. */
321 	n = nice + SCHED_PRI_NHALF;
322 	kseq->ksq_nice[n]--;
323 	KASSERT(kseq->ksq_nice[n] >= 0, ("Negative nice count."));
324 
325 	/*
326 	 * If this wasn't the smallest nice value or there are more in
327 	 * this bucket we can just return.  Otherwise we have to recalculate
328 	 * the smallest nice.
329 	 */
330 	if (nice != kseq->ksq_nicemin ||
331 	    kseq->ksq_nice[n] != 0 ||
332 	    kseq->ksq_loads[PRI_TIMESHARE] == 0)
333 		return;
334 
335 	for (; n < SCHED_PRI_NRESV + 1; n++)
336 		if (kseq->ksq_nice[n]) {
337 			kseq->ksq_nicemin = n - SCHED_PRI_NHALF;
338 			return;
339 		}
340 }
341 
342 #ifdef SMP
343 /*
344  * kseq_balance is a simple CPU load balancing algorithm.  It operates by
345  * finding the least loaded and most loaded cpu and equalizing their load
346  * by migrating some processes.
347  *
348  * Dealing only with two CPUs at a time has two advantages.  Firstly, most
349  * installations will only have 2 cpus.  Secondly, load balancing too much at
350  * once can have an unpleasant effect on the system.  The scheduler rarely has
351  * enough information to make perfect decisions.  So this algorithm chooses
352  * algorithm simplicity and more gradual effects on load in larger systems.
353  *
354  * It could be improved by considering the priorities and slices assigned to
355  * each task prior to balancing them.  There are many pathological cases with
356  * any approach and so the semi random algorithm below may work as well as any.
357  *
358  */
359 void
360 kseq_balance(void *arg)
361 {
362 	struct kseq *kseq;
363 	int high_load;
364 	int low_load;
365 	int high_cpu;
366 	int low_cpu;
367 	int move;
368 	int diff;
369 	int i;
370 
371 	high_cpu = 0;
372 	low_cpu = 0;
373 	high_load = 0;
374 	low_load = -1;
375 
376 	mtx_lock_spin(&sched_lock);
377 	for (i = 0; i < mp_maxid; i++) {
378 		if (CPU_ABSENT(i))
379 			continue;
380 		kseq = KSEQ_CPU(i);
381 		if (kseq->ksq_load > high_load) {
382 			high_load = kseq->ksq_load;
383 			high_cpu = i;
384 		}
385 		if (low_load == -1 || kseq->ksq_load < low_load) {
386 			low_load = kseq->ksq_load;
387 			low_cpu = i;
388 		}
389 	}
390 
391 	/*
392 	 * Nothing to do.
393 	 */
394 	if (high_load < 2 || low_load == high_load)
395 		goto out;
396 
397 	diff = high_load - low_load;
398 	move = diff / 2;
399 	if (diff & 0x1)
400 		move++;
401 
402 	for (i = 0; i < move; i++)
403 		kseq_move(KSEQ_CPU(high_cpu), low_cpu);
404 
405 out:
406 	mtx_unlock_spin(&sched_lock);
407 	callout_reset(&kseq_lb_callout, hz, kseq_balance, NULL);
408 
409 	return;
410 }
411 
412 struct kseq *
413 kseq_load_highest(void)
414 {
415 	struct kseq *kseq;
416 	int load;
417 	int cpu;
418 	int i;
419 
420 	mtx_assert(&sched_lock, MA_OWNED);
421 	cpu = 0;
422 	load = 0;
423 
424 	for (i = 0; i < mp_maxid; i++) {
425 		if (CPU_ABSENT(i))
426 			continue;
427 		kseq = KSEQ_CPU(i);
428 		if (kseq->ksq_load > load) {
429 			load = kseq->ksq_load;
430 			cpu = i;
431 		}
432 	}
433 	if (load > 1)
434 		return (KSEQ_CPU(cpu));
435 
436 	return (NULL);
437 }
438 
439 void
440 kseq_move(struct kseq *from, int cpu)
441 {
442 	struct kse *ke;
443 
444 	ke = kseq_choose(from);
445 	runq_remove(ke->ke_runq, ke);
446 	ke->ke_state = KES_THREAD;
447 	kseq_rem(from, ke);
448 
449 	ke->ke_cpu = cpu;
450 	sched_add(ke);
451 }
452 #endif
453 
454 struct kse *
455 kseq_choose(struct kseq *kseq)
456 {
457 	struct kse *ke;
458 	struct runq *swap;
459 
460 	mtx_assert(&sched_lock, MA_OWNED);
461 	swap = NULL;
462 
463 	for (;;) {
464 		ke = runq_choose(kseq->ksq_curr);
465 		if (ke == NULL) {
466 			/*
467 			 * We already swaped once and didn't get anywhere.
468 			 */
469 			if (swap)
470 				break;
471 			swap = kseq->ksq_curr;
472 			kseq->ksq_curr = kseq->ksq_next;
473 			kseq->ksq_next = swap;
474 			continue;
475 		}
476 		/*
477 		 * If we encounter a slice of 0 the kse is in a
478 		 * TIMESHARE kse group and its nice was too far out
479 		 * of the range that receives slices.
480 		 */
481 		if (ke->ke_slice == 0) {
482 			runq_remove(ke->ke_runq, ke);
483 			sched_slice(ke);
484 			ke->ke_runq = kseq->ksq_next;
485 			runq_add(ke->ke_runq, ke);
486 			continue;
487 		}
488 		return (ke);
489 	}
490 
491 	return (runq_choose(&kseq->ksq_idle));
492 }
493 
494 static void
495 kseq_setup(struct kseq *kseq)
496 {
497 	runq_init(&kseq->ksq_timeshare[0]);
498 	runq_init(&kseq->ksq_timeshare[1]);
499 	runq_init(&kseq->ksq_idle);
500 
501 	kseq->ksq_curr = &kseq->ksq_timeshare[0];
502 	kseq->ksq_next = &kseq->ksq_timeshare[1];
503 
504 	kseq->ksq_loads[PRI_ITHD] = 0;
505 	kseq->ksq_loads[PRI_REALTIME] = 0;
506 	kseq->ksq_loads[PRI_TIMESHARE] = 0;
507 	kseq->ksq_loads[PRI_IDLE] = 0;
508 	kseq->ksq_load = 0;
509 #ifdef SMP
510 	kseq->ksq_rslices = 0;
511 #endif
512 }
513 
514 static void
515 sched_setup(void *dummy)
516 {
517 	int i;
518 
519 	slice_min = (hz/100);
520 	slice_max = (hz/10);
521 
522 	mtx_lock_spin(&sched_lock);
523 	/* init kseqs */
524 	for (i = 0; i < MAXCPU; i++)
525 		kseq_setup(KSEQ_CPU(i));
526 
527 	kseq_add(KSEQ_SELF(), &kse0);
528 	mtx_unlock_spin(&sched_lock);
529 #ifdef SMP
530 	callout_init(&kseq_lb_callout, 1);
531 	kseq_balance(NULL);
532 #endif
533 }
534 
535 /*
536  * Scale the scheduling priority according to the "interactivity" of this
537  * process.
538  */
539 static void
540 sched_priority(struct ksegrp *kg)
541 {
542 	int pri;
543 
544 	if (kg->kg_pri_class != PRI_TIMESHARE)
545 		return;
546 
547 	pri = SCHED_PRI_INTERACT(sched_interact_score(kg));
548 	pri += SCHED_PRI_BASE;
549 	pri += kg->kg_nice;
550 
551 	if (pri > PRI_MAX_TIMESHARE)
552 		pri = PRI_MAX_TIMESHARE;
553 	else if (pri < PRI_MIN_TIMESHARE)
554 		pri = PRI_MIN_TIMESHARE;
555 
556 	kg->kg_user_pri = pri;
557 
558 	return;
559 }
560 
561 /*
562  * Calculate a time slice based on the properties of the kseg and the runq
563  * that we're on.  This is only for PRI_TIMESHARE ksegrps.
564  */
565 static void
566 sched_slice(struct kse *ke)
567 {
568 	struct kseq *kseq;
569 	struct ksegrp *kg;
570 
571 	kg = ke->ke_ksegrp;
572 	kseq = KSEQ_CPU(ke->ke_cpu);
573 
574 	/*
575 	 * Rationale:
576 	 * KSEs in interactive ksegs get the minimum slice so that we
577 	 * quickly notice if it abuses its advantage.
578 	 *
579 	 * KSEs in non-interactive ksegs are assigned a slice that is
580 	 * based on the ksegs nice value relative to the least nice kseg
581 	 * on the run queue for this cpu.
582 	 *
583 	 * If the KSE is less nice than all others it gets the maximum
584 	 * slice and other KSEs will adjust their slice relative to
585 	 * this when they first expire.
586 	 *
587 	 * There is 20 point window that starts relative to the least
588 	 * nice kse on the run queue.  Slice size is determined by
589 	 * the kse distance from the last nice ksegrp.
590 	 *
591 	 * If you are outside of the window you will get no slice and
592 	 * you will be reevaluated each time you are selected on the
593 	 * run queue.
594 	 *
595 	 */
596 
597 	if (!SCHED_INTERACTIVE(kg)) {
598 		int nice;
599 
600 		nice = kg->kg_nice + (0 - kseq->ksq_nicemin);
601 		if (kseq->ksq_loads[PRI_TIMESHARE] == 0 ||
602 		    kg->kg_nice < kseq->ksq_nicemin)
603 			ke->ke_slice = SCHED_SLICE_MAX;
604 		else if (nice <= SCHED_PRI_NTHRESH)
605 			ke->ke_slice = SCHED_SLICE_NICE(nice);
606 		else
607 			ke->ke_slice = 0;
608 	} else
609 		ke->ke_slice = SCHED_SLICE_MIN;
610 
611 	CTR6(KTR_ULE,
612 	    "Sliced %p(%d) (nice: %d, nicemin: %d, load: %d, interactive: %d)",
613 	    ke, ke->ke_slice, kg->kg_nice, kseq->ksq_nicemin,
614 	    kseq->ksq_loads[PRI_TIMESHARE], SCHED_INTERACTIVE(kg));
615 
616 	/*
617 	 * Check to see if we need to scale back the slp and run time
618 	 * in the kg.  This will cause us to forget old interactivity
619 	 * while maintaining the current ratio.
620 	 */
621 	sched_interact_update(kg);
622 
623 	return;
624 }
625 
626 static void
627 sched_interact_update(struct ksegrp *kg)
628 {
629 	/* XXX Fixme, use a linear algorithm and not a while loop. */
630 	while ((kg->kg_runtime + kg->kg_slptime) >  SCHED_SLP_RUN_MAX) {
631 		kg->kg_runtime = (kg->kg_runtime / 5) * 4;
632 		kg->kg_slptime = (kg->kg_slptime / 5) * 4;
633 	}
634 }
635 
636 static int
637 sched_interact_score(struct ksegrp *kg)
638 {
639 	int div;
640 
641 	if (kg->kg_runtime > kg->kg_slptime) {
642 		div = max(1, kg->kg_runtime / SCHED_INTERACT_HALF);
643 		return (SCHED_INTERACT_HALF +
644 		    (SCHED_INTERACT_HALF - (kg->kg_slptime / div)));
645 	} if (kg->kg_slptime > kg->kg_runtime) {
646 		div = max(1, kg->kg_slptime / SCHED_INTERACT_HALF);
647 		return (kg->kg_runtime / div);
648 	}
649 
650 	/*
651 	 * This can happen if slptime and runtime are 0.
652 	 */
653 	return (0);
654 
655 }
656 
657 /*
658  * This is only somewhat accurate since given many processes of the same
659  * priority they will switch when their slices run out, which will be
660  * at most SCHED_SLICE_MAX.
661  */
662 int
663 sched_rr_interval(void)
664 {
665 	return (SCHED_SLICE_MAX);
666 }
667 
668 void
669 sched_pctcpu_update(struct kse *ke)
670 {
671 	/*
672 	 * Adjust counters and watermark for pctcpu calc.
673 	 */
674 
675 	/*
676 	 * Shift the tick count out so that the divide doesn't round away
677 	 * our results.
678 	 */
679 	ke->ke_ticks <<= 10;
680 	ke->ke_ticks = (ke->ke_ticks / (ke->ke_ltick - ke->ke_ftick)) *
681 		    SCHED_CPU_TICKS;
682 	ke->ke_ticks >>= 10;
683 	ke->ke_ltick = ticks;
684 	ke->ke_ftick = ke->ke_ltick - SCHED_CPU_TICKS;
685 }
686 
687 #ifdef SMP
688 /* XXX Should be changed to kseq_load_lowest() */
689 int
690 sched_pickcpu(void)
691 {
692 	struct kseq *kseq;
693 	int load;
694 	int cpu;
695 	int i;
696 
697 	mtx_assert(&sched_lock, MA_OWNED);
698 	if (!smp_started)
699 		return (0);
700 
701 	load = 0;
702 	cpu = 0;
703 
704 	for (i = 0; i < mp_maxid; i++) {
705 		if (CPU_ABSENT(i))
706 			continue;
707 		kseq = KSEQ_CPU(i);
708 		if (kseq->ksq_load < load) {
709 			cpu = i;
710 			load = kseq->ksq_load;
711 		}
712 	}
713 
714 	CTR1(KTR_RUNQ, "sched_pickcpu: %d", cpu);
715 	return (cpu);
716 }
717 #else
718 int
719 sched_pickcpu(void)
720 {
721 	return (0);
722 }
723 #endif
724 
725 void
726 sched_prio(struct thread *td, u_char prio)
727 {
728 	struct kse *ke;
729 	struct runq *rq;
730 
731 	mtx_assert(&sched_lock, MA_OWNED);
732 	ke = td->td_kse;
733 	td->td_priority = prio;
734 
735 	if (TD_ON_RUNQ(td)) {
736 		rq = ke->ke_runq;
737 
738 		runq_remove(rq, ke);
739 		runq_add(rq, ke);
740 	}
741 }
742 
743 void
744 sched_switchout(struct thread *td)
745 {
746 	struct kse *ke;
747 
748 	mtx_assert(&sched_lock, MA_OWNED);
749 
750 	ke = td->td_kse;
751 
752 	td->td_last_kse = ke;
753         td->td_lastcpu = td->td_oncpu;
754 	td->td_oncpu = NOCPU;
755         td->td_flags &= ~TDF_NEEDRESCHED;
756 
757 	if (TD_IS_RUNNING(td)) {
758 		/*
759 		 * This queue is always correct except for idle threads which
760 		 * have a higher priority due to priority propagation.
761 		 */
762 		if (ke->ke_ksegrp->kg_pri_class == PRI_IDLE &&
763 		    ke->ke_thread->td_priority > PRI_MIN_IDLE)
764 			ke->ke_runq = KSEQ_SELF()->ksq_curr;
765 		runq_add(ke->ke_runq, ke);
766 		/* setrunqueue(td); */
767 		return;
768 	}
769 	if (ke->ke_runq)
770 		kseq_rem(KSEQ_CPU(ke->ke_cpu), ke);
771 	/*
772 	 * We will not be on the run queue. So we must be
773 	 * sleeping or similar.
774 	 */
775 	if (td->td_proc->p_flag & P_SA)
776 		kse_reassign(ke);
777 }
778 
779 void
780 sched_switchin(struct thread *td)
781 {
782 	/* struct kse *ke = td->td_kse; */
783 	mtx_assert(&sched_lock, MA_OWNED);
784 
785 	td->td_oncpu = PCPU_GET(cpuid);
786 }
787 
788 void
789 sched_nice(struct ksegrp *kg, int nice)
790 {
791 	struct kse *ke;
792 	struct thread *td;
793 	struct kseq *kseq;
794 
795 	PROC_LOCK_ASSERT(kg->kg_proc, MA_OWNED);
796 	mtx_assert(&sched_lock, MA_OWNED);
797 	/*
798 	 * We need to adjust the nice counts for running KSEs.
799 	 */
800 	if (kg->kg_pri_class == PRI_TIMESHARE)
801 		FOREACH_KSE_IN_GROUP(kg, ke) {
802 			if (ke->ke_runq == NULL)
803 				continue;
804 			kseq = KSEQ_CPU(ke->ke_cpu);
805 			kseq_nice_rem(kseq, kg->kg_nice);
806 			kseq_nice_add(kseq, nice);
807 		}
808 	kg->kg_nice = nice;
809 	sched_priority(kg);
810 	FOREACH_THREAD_IN_GROUP(kg, td)
811 		td->td_flags |= TDF_NEEDRESCHED;
812 }
813 
814 void
815 sched_sleep(struct thread *td, u_char prio)
816 {
817 	mtx_assert(&sched_lock, MA_OWNED);
818 
819 	td->td_slptime = ticks;
820 	td->td_priority = prio;
821 
822 	CTR2(KTR_ULE, "sleep kse %p (tick: %d)",
823 	    td->td_kse, td->td_slptime);
824 }
825 
826 void
827 sched_wakeup(struct thread *td)
828 {
829 	mtx_assert(&sched_lock, MA_OWNED);
830 
831 	/*
832 	 * Let the kseg know how long we slept for.  This is because process
833 	 * interactivity behavior is modeled in the kseg.
834 	 */
835 	if (td->td_slptime) {
836 		struct ksegrp *kg;
837 		int hzticks;
838 
839 		kg = td->td_ksegrp;
840 		hzticks = ticks - td->td_slptime;
841 		kg->kg_slptime += hzticks << 10;
842 		sched_interact_update(kg);
843 		sched_priority(kg);
844 		if (td->td_kse)
845 			sched_slice(td->td_kse);
846 		CTR2(KTR_ULE, "wakeup kse %p (%d ticks)",
847 		    td->td_kse, hzticks);
848 		td->td_slptime = 0;
849 	}
850 	setrunqueue(td);
851         if (td->td_priority < curthread->td_priority)
852                 curthread->td_flags |= TDF_NEEDRESCHED;
853 }
854 
855 /*
856  * Penalize the parent for creating a new child and initialize the child's
857  * priority.
858  */
859 void
860 sched_fork(struct proc *p, struct proc *p1)
861 {
862 
863 	mtx_assert(&sched_lock, MA_OWNED);
864 
865 	sched_fork_ksegrp(FIRST_KSEGRP_IN_PROC(p), FIRST_KSEGRP_IN_PROC(p1));
866 	sched_fork_kse(FIRST_KSE_IN_PROC(p), FIRST_KSE_IN_PROC(p1));
867 	sched_fork_thread(FIRST_THREAD_IN_PROC(p), FIRST_THREAD_IN_PROC(p1));
868 }
869 
870 void
871 sched_fork_kse(struct kse *ke, struct kse *child)
872 {
873 
874 	child->ke_slice = 1;	/* Attempt to quickly learn interactivity. */
875 	child->ke_cpu = ke->ke_cpu; /* sched_pickcpu(); */
876 	child->ke_runq = NULL;
877 
878 	/*
879 	 * Claim that we've been running for one second for statistical
880 	 * purposes.
881 	 */
882 	child->ke_ticks = 0;
883 	child->ke_ltick = ticks;
884 	child->ke_ftick = ticks - hz;
885 }
886 
887 void
888 sched_fork_ksegrp(struct ksegrp *kg, struct ksegrp *child)
889 {
890 
891 	PROC_LOCK_ASSERT(child->kg_proc, MA_OWNED);
892 	/* XXX Need something better here */
893 
894 	child->kg_slptime = kg->kg_slptime;
895 	child->kg_runtime = kg->kg_runtime;
896 	kg->kg_runtime += tickincr << 10;
897 	sched_interact_update(kg);
898 
899 	child->kg_user_pri = kg->kg_user_pri;
900 	child->kg_nice = kg->kg_nice;
901 }
902 
903 void
904 sched_fork_thread(struct thread *td, struct thread *child)
905 {
906 }
907 
908 void
909 sched_class(struct ksegrp *kg, int class)
910 {
911 	struct kseq *kseq;
912 	struct kse *ke;
913 
914 	mtx_assert(&sched_lock, MA_OWNED);
915 	if (kg->kg_pri_class == class)
916 		return;
917 
918 	FOREACH_KSE_IN_GROUP(kg, ke) {
919 		if (ke->ke_state != KES_ONRUNQ &&
920 		    ke->ke_state != KES_THREAD)
921 			continue;
922 		kseq = KSEQ_CPU(ke->ke_cpu);
923 
924 		kseq->ksq_loads[PRI_BASE(kg->kg_pri_class)]--;
925 		kseq->ksq_loads[PRI_BASE(class)]++;
926 
927 		if (kg->kg_pri_class == PRI_TIMESHARE)
928 			kseq_nice_rem(kseq, kg->kg_nice);
929 		else if (class == PRI_TIMESHARE)
930 			kseq_nice_add(kseq, kg->kg_nice);
931 	}
932 
933 	kg->kg_pri_class = class;
934 }
935 
936 /*
937  * Return some of the child's priority and interactivity to the parent.
938  */
939 void
940 sched_exit(struct proc *p, struct proc *child)
941 {
942 	/* XXX Need something better here */
943 	mtx_assert(&sched_lock, MA_OWNED);
944 	sched_exit_kse(FIRST_KSE_IN_PROC(p), FIRST_KSE_IN_PROC(child));
945 	sched_exit_ksegrp(FIRST_KSEGRP_IN_PROC(p), FIRST_KSEGRP_IN_PROC(child));
946 }
947 
948 void
949 sched_exit_kse(struct kse *ke, struct kse *child)
950 {
951 	kseq_rem(KSEQ_CPU(child->ke_cpu), child);
952 }
953 
954 void
955 sched_exit_ksegrp(struct ksegrp *kg, struct ksegrp *child)
956 {
957 	/* kg->kg_slptime += child->kg_slptime; */
958 	kg->kg_runtime += child->kg_runtime;
959 	sched_interact_update(kg);
960 }
961 
962 void
963 sched_exit_thread(struct thread *td, struct thread *child)
964 {
965 }
966 
967 void
968 sched_clock(struct kse *ke)
969 {
970 	struct kseq *kseq;
971 	struct ksegrp *kg;
972 	struct thread *td;
973 #if 0
974 	struct kse *nke;
975 #endif
976 
977 	/*
978 	 * sched_setup() apparently happens prior to stathz being set.  We
979 	 * need to resolve the timers earlier in the boot so we can avoid
980 	 * calculating this here.
981 	 */
982 	if (realstathz == 0) {
983 		realstathz = stathz ? stathz : hz;
984 		tickincr = hz / realstathz;
985 		/*
986 		 * XXX This does not work for values of stathz that are much
987 		 * larger than hz.
988 		 */
989 		if (tickincr == 0)
990 			tickincr = 1;
991 	}
992 
993 	td = ke->ke_thread;
994 	kg = ke->ke_ksegrp;
995 
996 	mtx_assert(&sched_lock, MA_OWNED);
997 	KASSERT((td != NULL), ("schedclock: null thread pointer"));
998 
999 	/* Adjust ticks for pctcpu */
1000 	ke->ke_ticks++;
1001 	ke->ke_ltick = ticks;
1002 
1003 	/* Go up to one second beyond our max and then trim back down */
1004 	if (ke->ke_ftick + SCHED_CPU_TICKS + hz < ke->ke_ltick)
1005 		sched_pctcpu_update(ke);
1006 
1007 	if (td->td_flags & TDF_IDLETD)
1008 		return;
1009 
1010 	CTR4(KTR_ULE, "Tick kse %p (slice: %d, slptime: %d, runtime: %d)",
1011 	    ke, ke->ke_slice, kg->kg_slptime >> 10, kg->kg_runtime >> 10);
1012 
1013 	/*
1014 	 * We only do slicing code for TIMESHARE ksegrps.
1015 	 */
1016 	if (kg->kg_pri_class != PRI_TIMESHARE)
1017 		return;
1018 	/*
1019 	 * Check for a higher priority task on the run queue.  This can happen
1020 	 * on SMP if another processor woke up a process on our runq.
1021 	 */
1022 	kseq = KSEQ_SELF();
1023 #if 0
1024 	if (kseq->ksq_load > 1 && (nke = kseq_choose(kseq)) != NULL) {
1025 		if (sched_strict &&
1026 		    nke->ke_thread->td_priority < td->td_priority)
1027 			td->td_flags |= TDF_NEEDRESCHED;
1028 		else if (nke->ke_thread->td_priority <
1029 		    td->td_priority SCHED_PRIO_SLOP)
1030 
1031 		if (nke->ke_thread->td_priority < td->td_priority)
1032 			td->td_flags |= TDF_NEEDRESCHED;
1033 	}
1034 #endif
1035 	/*
1036 	 * We used a tick charge it to the ksegrp so that we can compute our
1037 	 * interactivity.
1038 	 */
1039 	kg->kg_runtime += tickincr << 10;
1040 	sched_interact_update(kg);
1041 
1042 	/*
1043 	 * We used up one time slice.
1044 	 */
1045 	ke->ke_slice--;
1046 #ifdef SMP
1047 	kseq->ksq_rslices--;
1048 #endif
1049 
1050 	if (ke->ke_slice > 0)
1051 		return;
1052 	/*
1053 	 * We're out of time, recompute priorities and requeue.
1054 	 */
1055 	kseq_rem(kseq, ke);
1056 	sched_priority(kg);
1057 	sched_slice(ke);
1058 	if (SCHED_CURR(kg, ke))
1059 		ke->ke_runq = kseq->ksq_curr;
1060 	else
1061 		ke->ke_runq = kseq->ksq_next;
1062 	kseq_add(kseq, ke);
1063 	td->td_flags |= TDF_NEEDRESCHED;
1064 }
1065 
1066 int
1067 sched_runnable(void)
1068 {
1069 	struct kseq *kseq;
1070 	int load;
1071 
1072 	load = 1;
1073 
1074 	mtx_lock_spin(&sched_lock);
1075 	kseq = KSEQ_SELF();
1076 
1077 	if (kseq->ksq_load)
1078 		goto out;
1079 #ifdef SMP
1080 	/*
1081 	 * For SMP we may steal other processor's KSEs.  Just search until we
1082 	 * verify that at least on other cpu has a runnable task.
1083 	 */
1084 	if (smp_started) {
1085 		int i;
1086 
1087 		for (i = 0; i < mp_maxid; i++) {
1088 			if (CPU_ABSENT(i))
1089 				continue;
1090 			kseq = KSEQ_CPU(i);
1091 			if (kseq->ksq_load > 1)
1092 				goto out;
1093 		}
1094 	}
1095 #endif
1096 	load = 0;
1097 out:
1098 	mtx_unlock_spin(&sched_lock);
1099 	return (load);
1100 }
1101 
1102 void
1103 sched_userret(struct thread *td)
1104 {
1105 	struct ksegrp *kg;
1106 	struct kseq *kseq;
1107 	struct kse *ke;
1108 
1109 	kg = td->td_ksegrp;
1110 
1111 	if (td->td_priority != kg->kg_user_pri) {
1112 		mtx_lock_spin(&sched_lock);
1113 		td->td_priority = kg->kg_user_pri;
1114 		kseq = KSEQ_SELF();
1115 		if (td->td_ksegrp->kg_pri_class == PRI_TIMESHARE &&
1116 		    kseq->ksq_load > 1 &&
1117 		    (ke = kseq_choose(kseq)) != NULL &&
1118 		    ke->ke_thread->td_priority < td->td_priority)
1119 			curthread->td_flags |= TDF_NEEDRESCHED;
1120 		mtx_unlock_spin(&sched_lock);
1121 	}
1122 }
1123 
1124 struct kse *
1125 sched_choose(void)
1126 {
1127 	struct kseq *kseq;
1128 	struct kse *ke;
1129 
1130 	mtx_assert(&sched_lock, MA_OWNED);
1131 #ifdef SMP
1132 retry:
1133 #endif
1134 	kseq = KSEQ_SELF();
1135 	ke = kseq_choose(kseq);
1136 	if (ke) {
1137 		runq_remove(ke->ke_runq, ke);
1138 		ke->ke_state = KES_THREAD;
1139 
1140 		if (ke->ke_ksegrp->kg_pri_class == PRI_TIMESHARE) {
1141 			CTR4(KTR_ULE, "Run kse %p from %p (slice: %d, pri: %d)",
1142 			    ke, ke->ke_runq, ke->ke_slice,
1143 			    ke->ke_thread->td_priority);
1144 		}
1145 		return (ke);
1146 	}
1147 
1148 #ifdef SMP
1149 	if (smp_started) {
1150 		/*
1151 		 * Find the cpu with the highest load and steal one proc.
1152 		 */
1153 		if ((kseq = kseq_load_highest()) == NULL)
1154 			return (NULL);
1155 
1156 		/*
1157 		 * Remove this kse from this kseq and runq and then requeue
1158 		 * on the current processor.  Then we will dequeue it
1159 		 * normally above.
1160 		 */
1161 		kseq_move(kseq, PCPU_GET(cpuid));
1162 		goto retry;
1163 	}
1164 #endif
1165 
1166 	return (NULL);
1167 }
1168 
1169 void
1170 sched_add(struct kse *ke)
1171 {
1172 	struct kseq *kseq;
1173 	struct ksegrp *kg;
1174 
1175 	mtx_assert(&sched_lock, MA_OWNED);
1176 	KASSERT((ke->ke_thread != NULL), ("sched_add: No thread on KSE"));
1177 	KASSERT((ke->ke_thread->td_kse != NULL),
1178 	    ("sched_add: No KSE on thread"));
1179 	KASSERT(ke->ke_state != KES_ONRUNQ,
1180 	    ("sched_add: kse %p (%s) already in run queue", ke,
1181 	    ke->ke_proc->p_comm));
1182 	KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
1183 	    ("sched_add: process swapped out"));
1184 	KASSERT(ke->ke_runq == NULL,
1185 	    ("sched_add: KSE %p is still assigned to a run queue", ke));
1186 
1187 	kg = ke->ke_ksegrp;
1188 
1189 	switch (PRI_BASE(kg->kg_pri_class)) {
1190 	case PRI_ITHD:
1191 	case PRI_REALTIME:
1192 		kseq = KSEQ_SELF();
1193 		ke->ke_runq = kseq->ksq_curr;
1194 		ke->ke_slice = SCHED_SLICE_MAX;
1195 		ke->ke_cpu = PCPU_GET(cpuid);
1196 		break;
1197 	case PRI_TIMESHARE:
1198 		kseq = KSEQ_CPU(ke->ke_cpu);
1199 		if (SCHED_CURR(kg, ke))
1200 			ke->ke_runq = kseq->ksq_curr;
1201 		else
1202 			ke->ke_runq = kseq->ksq_next;
1203 		break;
1204 	case PRI_IDLE:
1205 		kseq = KSEQ_CPU(ke->ke_cpu);
1206 		/*
1207 		 * This is for priority prop.
1208 		 */
1209 		if (ke->ke_thread->td_priority > PRI_MIN_IDLE)
1210 			ke->ke_runq = kseq->ksq_curr;
1211 		else
1212 			ke->ke_runq = &kseq->ksq_idle;
1213 		ke->ke_slice = SCHED_SLICE_MIN;
1214 		break;
1215 	default:
1216 		panic("Unknown pri class.\n");
1217 		break;
1218 	}
1219 
1220 	ke->ke_ksegrp->kg_runq_kses++;
1221 	ke->ke_state = KES_ONRUNQ;
1222 
1223 	runq_add(ke->ke_runq, ke);
1224 	kseq_add(kseq, ke);
1225 }
1226 
1227 void
1228 sched_rem(struct kse *ke)
1229 {
1230 	struct kseq *kseq;
1231 
1232 	mtx_assert(&sched_lock, MA_OWNED);
1233 	KASSERT((ke->ke_state == KES_ONRUNQ), ("KSE not on run queue"));
1234 
1235 	ke->ke_state = KES_THREAD;
1236 	ke->ke_ksegrp->kg_runq_kses--;
1237 	kseq = KSEQ_CPU(ke->ke_cpu);
1238 	runq_remove(ke->ke_runq, ke);
1239 	kseq_rem(kseq, ke);
1240 }
1241 
1242 fixpt_t
1243 sched_pctcpu(struct kse *ke)
1244 {
1245 	fixpt_t pctcpu;
1246 
1247 	pctcpu = 0;
1248 
1249 	mtx_lock_spin(&sched_lock);
1250 	if (ke->ke_ticks) {
1251 		int rtick;
1252 
1253 		/*
1254 		 * Don't update more frequently than twice a second.  Allowing
1255 		 * this causes the cpu usage to decay away too quickly due to
1256 		 * rounding errors.
1257 		 */
1258 		if (ke->ke_ltick < (ticks - (hz / 2)))
1259 			sched_pctcpu_update(ke);
1260 
1261 		/* How many rtick per second ? */
1262 		rtick = min(ke->ke_ticks / SCHED_CPU_TIME, SCHED_CPU_TICKS);
1263 		pctcpu = (FSCALE * ((FSCALE * rtick)/realstathz)) >> FSHIFT;
1264 	}
1265 
1266 	ke->ke_proc->p_swtime = ke->ke_ltick - ke->ke_ftick;
1267 	mtx_unlock_spin(&sched_lock);
1268 
1269 	return (pctcpu);
1270 }
1271 
1272 int
1273 sched_sizeof_kse(void)
1274 {
1275 	return (sizeof(struct kse) + sizeof(struct ke_sched));
1276 }
1277 
1278 int
1279 sched_sizeof_ksegrp(void)
1280 {
1281 	return (sizeof(struct ksegrp) + sizeof(struct kg_sched));
1282 }
1283 
1284 int
1285 sched_sizeof_proc(void)
1286 {
1287 	return (sizeof(struct proc));
1288 }
1289 
1290 int
1291 sched_sizeof_thread(void)
1292 {
1293 	return (sizeof(struct thread) + sizeof(struct td_sched));
1294 }
1295