sched_ule.c revision 126326
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: head/sys/kern/sched_ule.c 126326 2004-02-27 18:52:44Z jhb $");
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/resourcevar.h>
39#include <sys/sched.h>
40#include <sys/smp.h>
41#include <sys/sx.h>
42#include <sys/sysctl.h>
43#include <sys/sysproto.h>
44#include <sys/vmmeter.h>
45#ifdef DDB
46#include <ddb/ddb.h>
47#endif
48#ifdef KTRACE
49#include <sys/uio.h>
50#include <sys/ktrace.h>
51#endif
52
53#include <machine/cpu.h>
54#include <machine/smp.h>
55
56#define KTR_ULE         KTR_NFS
57
58/* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
59/* XXX This is bogus compatability crap for ps */
60static fixpt_t  ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
61SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
62
63static void sched_setup(void *dummy);
64SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL)
65
66static SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "SCHED");
67
68static int slice_min = 1;
69SYSCTL_INT(_kern_sched, OID_AUTO, slice_min, CTLFLAG_RW, &slice_min, 0, "");
70
71static int slice_max = 10;
72SYSCTL_INT(_kern_sched, OID_AUTO, slice_max, CTLFLAG_RW, &slice_max, 0, "");
73
74int realstathz;
75int tickincr = 1;
76
77#ifdef SMP
78/* Callouts to handle load balancing SMP systems. */
79static struct callout kseq_lb_callout;
80static struct callout kseq_group_callout;
81#endif
82
83/*
84 * These datastructures are allocated within their parent datastructure but
85 * are scheduler specific.
86 */
87
88struct 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#define	ke_assign	ke_procq.tqe_next
105
106#define	KEF_ASSIGNED	KEF_SCHED0	/* KSE is being migrated. */
107#define	KEF_BOUND	KEF_SCHED1	/* KSE can not migrate. */
108
109struct kg_sched {
110	int	skg_slptime;		/* Number of ticks we vol. slept */
111	int	skg_runtime;		/* Number of ticks we were running */
112};
113#define	kg_slptime	kg_sched->skg_slptime
114#define	kg_runtime	kg_sched->skg_runtime
115
116struct td_sched {
117	int	std_slptime;
118};
119#define	td_slptime	td_sched->std_slptime
120
121struct td_sched td_sched;
122struct ke_sched ke_sched;
123struct kg_sched kg_sched;
124
125struct ke_sched *kse0_sched = &ke_sched;
126struct kg_sched *ksegrp0_sched = &kg_sched;
127struct p_sched *proc0_sched = NULL;
128struct td_sched *thread0_sched = &td_sched;
129
130/*
131 * The priority is primarily determined by the interactivity score.  Thus, we
132 * give lower(better) priorities to kse groups that use less CPU.  The nice
133 * value is then directly added to this to allow nice to have some effect
134 * on latency.
135 *
136 * PRI_RANGE:	Total priority range for timeshare threads.
137 * PRI_NRESV:	Number of nice values.
138 * PRI_BASE:	The start of the dynamic range.
139 */
140#define	SCHED_PRI_RANGE		(PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE + 1)
141#define	SCHED_PRI_NRESV		((PRIO_MAX - PRIO_MIN) + 1)
142#define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
143#define	SCHED_PRI_BASE		(PRI_MIN_TIMESHARE)
144#define	SCHED_PRI_INTERACT(score)					\
145    ((score) * SCHED_PRI_RANGE / SCHED_INTERACT_MAX)
146
147/*
148 * These determine the interactivity of a process.
149 *
150 * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
151 *		before throttling back.
152 * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
153 * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
154 * INTERACT_THRESH:	Threshhold for placement on the current runq.
155 */
156#define	SCHED_SLP_RUN_MAX	((hz * 5) << 10)
157#define	SCHED_SLP_RUN_FORK	((hz / 2) << 10)
158#define	SCHED_INTERACT_MAX	(100)
159#define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
160#define	SCHED_INTERACT_THRESH	(30)
161
162/*
163 * These parameters and macros determine the size of the time slice that is
164 * granted to each thread.
165 *
166 * SLICE_MIN:	Minimum time slice granted, in units of ticks.
167 * SLICE_MAX:	Maximum time slice granted.
168 * SLICE_RANGE:	Range of available time slices scaled by hz.
169 * SLICE_SCALE:	The number slices granted per val in the range of [0, max].
170 * SLICE_NICE:  Determine the amount of slice granted to a scaled nice.
171 * SLICE_NTHRESH:	The nice cutoff point for slice assignment.
172 */
173#define	SCHED_SLICE_MIN			(slice_min)
174#define	SCHED_SLICE_MAX			(slice_max)
175#define	SCHED_SLICE_INTERACTIVE		(slice_max)
176#define	SCHED_SLICE_NTHRESH	(SCHED_PRI_NHALF - 1)
177#define	SCHED_SLICE_RANGE		(SCHED_SLICE_MAX - SCHED_SLICE_MIN + 1)
178#define	SCHED_SLICE_SCALE(val, max)	(((val) * SCHED_SLICE_RANGE) / (max))
179#define	SCHED_SLICE_NICE(nice)						\
180    (SCHED_SLICE_MAX - SCHED_SLICE_SCALE((nice), SCHED_SLICE_NTHRESH))
181
182/*
183 * This macro determines whether or not the kse belongs on the current or
184 * next run queue.
185 */
186#define	SCHED_INTERACTIVE(kg)						\
187    (sched_interact_score(kg) < SCHED_INTERACT_THRESH)
188#define	SCHED_CURR(kg, ke)						\
189    (ke->ke_thread->td_priority != kg->kg_user_pri ||			\
190    SCHED_INTERACTIVE(kg))
191
192/*
193 * Cpu percentage computation macros and defines.
194 *
195 * SCHED_CPU_TIME:	Number of seconds to average the cpu usage across.
196 * SCHED_CPU_TICKS:	Number of hz ticks to average the cpu usage across.
197 */
198
199#define	SCHED_CPU_TIME	10
200#define	SCHED_CPU_TICKS	(hz * SCHED_CPU_TIME)
201
202/*
203 * kseq - per processor runqs and statistics.
204 */
205struct kseq {
206	struct runq	ksq_idle;		/* Queue of IDLE threads. */
207	struct runq	ksq_timeshare[2];	/* Run queues for !IDLE. */
208	struct runq	*ksq_next;		/* Next timeshare queue. */
209	struct runq	*ksq_curr;		/* Current queue. */
210	int		ksq_load_timeshare;	/* Load for timeshare. */
211	int		ksq_load;		/* Aggregate load. */
212	short		ksq_nice[SCHED_PRI_NRESV]; /* KSEs in each nice bin. */
213	short		ksq_nicemin;		/* Least nice. */
214#ifdef SMP
215	int			ksq_transferable;
216	LIST_ENTRY(kseq)	ksq_siblings;	/* Next in kseq group. */
217	struct kseq_group	*ksq_group;	/* Our processor group. */
218	volatile struct kse	*ksq_assigned;	/* assigned by another CPU. */
219#else
220	int		ksq_sysload;		/* For loadavg, !ITHD load. */
221#endif
222};
223
224#ifdef SMP
225/*
226 * kseq groups are groups of processors which can cheaply share threads.  When
227 * one processor in the group goes idle it will check the runqs of the other
228 * processors in its group prior to halting and waiting for an interrupt.
229 * These groups are suitable for SMT (Symetric Multi-Threading) and not NUMA.
230 * In a numa environment we'd want an idle bitmap per group and a two tiered
231 * load balancer.
232 */
233struct kseq_group {
234	int	ksg_cpus;		/* Count of CPUs in this kseq group. */
235	int	ksg_cpumask;		/* Mask of cpus in this group. */
236	int	ksg_idlemask;		/* Idle cpus in this group. */
237	int	ksg_mask;		/* Bit mask for first cpu. */
238	int	ksg_load;		/* Total load of this group. */
239	int	ksg_transferable;	/* Transferable load of this group. */
240	LIST_HEAD(, kseq)	ksg_members; /* Linked list of all members. */
241};
242#endif
243
244/*
245 * One kse queue per processor.
246 */
247#ifdef SMP
248static int kseq_idle;
249static int ksg_maxid;
250static struct kseq	kseq_cpu[MAXCPU];
251static struct kseq_group kseq_groups[MAXCPU];
252#define	KSEQ_SELF()	(&kseq_cpu[PCPU_GET(cpuid)])
253#define	KSEQ_CPU(x)	(&kseq_cpu[(x)])
254#define	KSEQ_ID(x)	((x) - kseq_cpu)
255#define	KSEQ_GROUP(x)	(&kseq_groups[(x)])
256#else	/* !SMP */
257static struct kseq	kseq_cpu;
258#define	KSEQ_SELF()	(&kseq_cpu)
259#define	KSEQ_CPU(x)	(&kseq_cpu)
260#endif
261
262static void sched_slice(struct kse *ke);
263static void sched_priority(struct ksegrp *kg);
264static int sched_interact_score(struct ksegrp *kg);
265static void sched_interact_update(struct ksegrp *kg);
266static void sched_interact_fork(struct ksegrp *kg);
267static void sched_pctcpu_update(struct kse *ke);
268
269/* Operations on per processor queues */
270static struct kse * kseq_choose(struct kseq *kseq);
271static void kseq_setup(struct kseq *kseq);
272static void kseq_load_add(struct kseq *kseq, struct kse *ke);
273static void kseq_load_rem(struct kseq *kseq, struct kse *ke);
274static __inline void kseq_runq_add(struct kseq *kseq, struct kse *ke);
275static __inline void kseq_runq_rem(struct kseq *kseq, struct kse *ke);
276static void kseq_nice_add(struct kseq *kseq, int nice);
277static void kseq_nice_rem(struct kseq *kseq, int nice);
278void kseq_print(int cpu);
279#ifdef SMP
280static int kseq_transfer(struct kseq *ksq, struct kse *ke, int class);
281static struct kse *runq_steal(struct runq *rq);
282static void sched_balance(void *arg);
283static void sched_balance_group(struct kseq_group *ksg);
284static void sched_balance_pair(struct kseq *high, struct kseq *low);
285static void kseq_move(struct kseq *from, int cpu);
286static int kseq_idled(struct kseq *kseq);
287static void kseq_notify(struct kse *ke, int cpu);
288static void kseq_assign(struct kseq *);
289static struct kse *kseq_steal(struct kseq *kseq, int stealidle);
290/*
291 * On P4 Xeons the round-robin interrupt delivery is broken.  As a result of
292 * this, we can't pin interrupts to the cpu that they were delivered to,
293 * otherwise all ithreads only run on CPU 0.
294 */
295#ifdef __i386__
296#define	KSE_CAN_MIGRATE(ke, class)					\
297    ((ke)->ke_thread->td_pinned == 0 && ((ke)->ke_flags & KEF_BOUND) == 0)
298#else /* !__i386__ */
299#define	KSE_CAN_MIGRATE(ke, class)					\
300    ((class) != PRI_ITHD && (ke)->ke_thread->td_pinned == 0 &&		\
301    ((ke)->ke_flags & KEF_BOUND) == 0)
302#endif /* !__i386__ */
303#endif
304
305void
306kseq_print(int cpu)
307{
308	struct kseq *kseq;
309	int i;
310
311	kseq = KSEQ_CPU(cpu);
312
313	printf("kseq:\n");
314	printf("\tload:           %d\n", kseq->ksq_load);
315	printf("\tload TIMESHARE: %d\n", kseq->ksq_load_timeshare);
316#ifdef SMP
317	printf("\tload transferable: %d\n", kseq->ksq_transferable);
318#endif
319	printf("\tnicemin:\t%d\n", kseq->ksq_nicemin);
320	printf("\tnice counts:\n");
321	for (i = 0; i < SCHED_PRI_NRESV; i++)
322		if (kseq->ksq_nice[i])
323			printf("\t\t%d = %d\n",
324			    i - SCHED_PRI_NHALF, kseq->ksq_nice[i]);
325}
326
327static __inline void
328kseq_runq_add(struct kseq *kseq, struct kse *ke)
329{
330#ifdef SMP
331	if (KSE_CAN_MIGRATE(ke, PRI_BASE(ke->ke_ksegrp->kg_pri_class))) {
332		kseq->ksq_transferable++;
333		kseq->ksq_group->ksg_transferable++;
334	}
335#endif
336	runq_add(ke->ke_runq, ke);
337}
338
339static __inline void
340kseq_runq_rem(struct kseq *kseq, struct kse *ke)
341{
342#ifdef SMP
343	if (KSE_CAN_MIGRATE(ke, PRI_BASE(ke->ke_ksegrp->kg_pri_class))) {
344		kseq->ksq_transferable--;
345		kseq->ksq_group->ksg_transferable--;
346	}
347#endif
348	runq_remove(ke->ke_runq, ke);
349}
350
351static void
352kseq_load_add(struct kseq *kseq, struct kse *ke)
353{
354	int class;
355	mtx_assert(&sched_lock, MA_OWNED);
356	class = PRI_BASE(ke->ke_ksegrp->kg_pri_class);
357	if (class == PRI_TIMESHARE)
358		kseq->ksq_load_timeshare++;
359	kseq->ksq_load++;
360	if (class != PRI_ITHD)
361#ifdef SMP
362		kseq->ksq_group->ksg_load++;
363#else
364		kseq->ksq_sysload++;
365#endif
366	if (ke->ke_ksegrp->kg_pri_class == PRI_TIMESHARE)
367		CTR6(KTR_ULE,
368		    "Add kse %p to %p (slice: %d, pri: %d, nice: %d(%d))",
369		    ke, ke->ke_runq, ke->ke_slice, ke->ke_thread->td_priority,
370		    ke->ke_ksegrp->kg_nice, kseq->ksq_nicemin);
371	if (ke->ke_ksegrp->kg_pri_class == PRI_TIMESHARE)
372		kseq_nice_add(kseq, ke->ke_ksegrp->kg_nice);
373}
374
375static void
376kseq_load_rem(struct kseq *kseq, struct kse *ke)
377{
378	int class;
379	mtx_assert(&sched_lock, MA_OWNED);
380	class = PRI_BASE(ke->ke_ksegrp->kg_pri_class);
381	if (class == PRI_TIMESHARE)
382		kseq->ksq_load_timeshare--;
383	if (class != PRI_ITHD)
384#ifdef SMP
385		kseq->ksq_group->ksg_load--;
386#else
387		kseq->ksq_sysload--;
388#endif
389	kseq->ksq_load--;
390	ke->ke_runq = NULL;
391	if (ke->ke_ksegrp->kg_pri_class == PRI_TIMESHARE)
392		kseq_nice_rem(kseq, ke->ke_ksegrp->kg_nice);
393}
394
395static void
396kseq_nice_add(struct kseq *kseq, int nice)
397{
398	mtx_assert(&sched_lock, MA_OWNED);
399	/* Normalize to zero. */
400	kseq->ksq_nice[nice + SCHED_PRI_NHALF]++;
401	if (nice < kseq->ksq_nicemin || kseq->ksq_load_timeshare == 1)
402		kseq->ksq_nicemin = nice;
403}
404
405static void
406kseq_nice_rem(struct kseq *kseq, int nice)
407{
408	int n;
409
410	mtx_assert(&sched_lock, MA_OWNED);
411	/* Normalize to zero. */
412	n = nice + SCHED_PRI_NHALF;
413	kseq->ksq_nice[n]--;
414	KASSERT(kseq->ksq_nice[n] >= 0, ("Negative nice count."));
415
416	/*
417	 * If this wasn't the smallest nice value or there are more in
418	 * this bucket we can just return.  Otherwise we have to recalculate
419	 * the smallest nice.
420	 */
421	if (nice != kseq->ksq_nicemin ||
422	    kseq->ksq_nice[n] != 0 ||
423	    kseq->ksq_load_timeshare == 0)
424		return;
425
426	for (; n < SCHED_PRI_NRESV; n++)
427		if (kseq->ksq_nice[n]) {
428			kseq->ksq_nicemin = n - SCHED_PRI_NHALF;
429			return;
430		}
431}
432
433#ifdef SMP
434/*
435 * sched_balance is a simple CPU load balancing algorithm.  It operates by
436 * finding the least loaded and most loaded cpu and equalizing their load
437 * by migrating some processes.
438 *
439 * Dealing only with two CPUs at a time has two advantages.  Firstly, most
440 * installations will only have 2 cpus.  Secondly, load balancing too much at
441 * once can have an unpleasant effect on the system.  The scheduler rarely has
442 * enough information to make perfect decisions.  So this algorithm chooses
443 * algorithm simplicity and more gradual effects on load in larger systems.
444 *
445 * It could be improved by considering the priorities and slices assigned to
446 * each task prior to balancing them.  There are many pathological cases with
447 * any approach and so the semi random algorithm below may work as well as any.
448 *
449 */
450static void
451sched_balance(void *arg)
452{
453	struct kseq_group *high;
454	struct kseq_group *low;
455	struct kseq_group *ksg;
456	int timo;
457	int cnt;
458	int i;
459
460	mtx_lock_spin(&sched_lock);
461	if (smp_started == 0)
462		goto out;
463	low = high = NULL;
464	i = random() % (ksg_maxid + 1);
465	for (cnt = 0; cnt <= ksg_maxid; cnt++) {
466		ksg = KSEQ_GROUP(i);
467		/*
468		 * Find the CPU with the highest load that has some
469		 * threads to transfer.
470		 */
471		if ((high == NULL || ksg->ksg_load > high->ksg_load)
472		    && ksg->ksg_transferable)
473			high = ksg;
474		if (low == NULL || ksg->ksg_load < low->ksg_load)
475			low = ksg;
476		if (++i > ksg_maxid)
477			i = 0;
478	}
479	if (low != NULL && high != NULL && high != low)
480		sched_balance_pair(LIST_FIRST(&high->ksg_members),
481		    LIST_FIRST(&low->ksg_members));
482out:
483	mtx_unlock_spin(&sched_lock);
484	timo = random() % (hz * 2);
485	callout_reset(&kseq_lb_callout, timo, sched_balance, NULL);
486}
487
488static void
489sched_balance_groups(void *arg)
490{
491	int timo;
492	int i;
493
494	mtx_lock_spin(&sched_lock);
495	if (smp_started)
496		for (i = 0; i <= ksg_maxid; i++)
497			sched_balance_group(KSEQ_GROUP(i));
498	mtx_unlock_spin(&sched_lock);
499	timo = random() % (hz * 2);
500	callout_reset(&kseq_group_callout, timo, sched_balance_groups, NULL);
501}
502
503static void
504sched_balance_group(struct kseq_group *ksg)
505{
506	struct kseq *kseq;
507	struct kseq *high;
508	struct kseq *low;
509	int load;
510
511	if (ksg->ksg_transferable == 0)
512		return;
513	low = NULL;
514	high = NULL;
515	LIST_FOREACH(kseq, &ksg->ksg_members, ksq_siblings) {
516		load = kseq->ksq_load;
517		if (kseq == KSEQ_CPU(0))
518			load--;
519		if (high == NULL || load > high->ksq_load)
520			high = kseq;
521		if (low == NULL || load < low->ksq_load)
522			low = kseq;
523	}
524	if (high != NULL && low != NULL && high != low)
525		sched_balance_pair(high, low);
526}
527
528static void
529sched_balance_pair(struct kseq *high, struct kseq *low)
530{
531	int transferable;
532	int high_load;
533	int low_load;
534	int move;
535	int diff;
536	int i;
537
538	/*
539	 * If we're transfering within a group we have to use this specific
540	 * kseq's transferable count, otherwise we can steal from other members
541	 * of the group.
542	 */
543	if (high->ksq_group == low->ksq_group) {
544		transferable = high->ksq_transferable;
545		high_load = high->ksq_load;
546		low_load = low->ksq_load;
547		/*
548		 * XXX If we encounter cpu 0 we must remember to reduce it's
549		 * load by 1 to reflect the swi that is running the callout.
550		 * At some point we should really fix load balancing of the
551		 * swi and then this wont matter.
552		 */
553		if (high == KSEQ_CPU(0))
554			high_load--;
555		if (low == KSEQ_CPU(0))
556			low_load--;
557	} else {
558		transferable = high->ksq_group->ksg_transferable;
559		high_load = high->ksq_group->ksg_load;
560		low_load = low->ksq_group->ksg_load;
561	}
562	if (transferable == 0)
563		return;
564	/*
565	 * Determine what the imbalance is and then adjust that to how many
566	 * kses we actually have to give up (transferable).
567	 */
568	diff = high_load - low_load;
569	move = diff / 2;
570	if (diff & 0x1)
571		move++;
572	move = min(move, transferable);
573	for (i = 0; i < move; i++)
574		kseq_move(high, KSEQ_ID(low));
575	return;
576}
577
578static void
579kseq_move(struct kseq *from, int cpu)
580{
581	struct kseq *kseq;
582	struct kseq *to;
583	struct kse *ke;
584
585	kseq = from;
586	to = KSEQ_CPU(cpu);
587	ke = kseq_steal(kseq, 1);
588	if (ke == NULL) {
589		struct kseq_group *ksg;
590
591		ksg = kseq->ksq_group;
592		LIST_FOREACH(kseq, &ksg->ksg_members, ksq_siblings) {
593			if (kseq == from || kseq->ksq_transferable == 0)
594				continue;
595			ke = kseq_steal(kseq, 1);
596			break;
597		}
598		if (ke == NULL)
599			panic("kseq_move: No KSEs available with a "
600			    "transferable count of %d\n",
601			    ksg->ksg_transferable);
602	}
603	if (kseq == to)
604		return;
605	ke->ke_state = KES_THREAD;
606	kseq_runq_rem(kseq, ke);
607	kseq_load_rem(kseq, ke);
608	kseq_notify(ke, cpu);
609}
610
611static int
612kseq_idled(struct kseq *kseq)
613{
614	struct kseq_group *ksg;
615	struct kseq *steal;
616	struct kse *ke;
617
618	ksg = kseq->ksq_group;
619	/*
620	 * If we're in a cpu group, try and steal kses from another cpu in
621	 * the group before idling.
622	 */
623	if (ksg->ksg_cpus > 1 && ksg->ksg_transferable) {
624		LIST_FOREACH(steal, &ksg->ksg_members, ksq_siblings) {
625			if (steal == kseq || steal->ksq_transferable == 0)
626				continue;
627			ke = kseq_steal(steal, 0);
628			if (ke == NULL)
629				continue;
630			ke->ke_state = KES_THREAD;
631			kseq_runq_rem(steal, ke);
632			kseq_load_rem(steal, ke);
633			ke->ke_cpu = PCPU_GET(cpuid);
634			sched_add(ke->ke_thread);
635			return (0);
636		}
637	}
638	/*
639	 * We only set the idled bit when all of the cpus in the group are
640	 * idle.  Otherwise we could get into a situation where a KSE bounces
641	 * back and forth between two idle cores on seperate physical CPUs.
642	 */
643	ksg->ksg_idlemask |= PCPU_GET(cpumask);
644	if (ksg->ksg_idlemask != ksg->ksg_cpumask)
645		return (1);
646	atomic_set_int(&kseq_idle, ksg->ksg_mask);
647	return (1);
648}
649
650static void
651kseq_assign(struct kseq *kseq)
652{
653	struct kse *nke;
654	struct kse *ke;
655
656	do {
657		(volatile struct kse *)ke = kseq->ksq_assigned;
658	} while(!atomic_cmpset_ptr(&kseq->ksq_assigned, ke, NULL));
659	for (; ke != NULL; ke = nke) {
660		nke = ke->ke_assign;
661		ke->ke_flags &= ~KEF_ASSIGNED;
662		sched_add(ke->ke_thread);
663	}
664}
665
666static void
667kseq_notify(struct kse *ke, int cpu)
668{
669	struct kseq *kseq;
670	struct thread *td;
671	struct pcpu *pcpu;
672
673	ke->ke_cpu = cpu;
674	ke->ke_flags |= KEF_ASSIGNED;
675
676	kseq = KSEQ_CPU(cpu);
677
678	/*
679	 * Place a KSE on another cpu's queue and force a resched.
680	 */
681	do {
682		(volatile struct kse *)ke->ke_assign = kseq->ksq_assigned;
683	} while(!atomic_cmpset_ptr(&kseq->ksq_assigned, ke->ke_assign, ke));
684	pcpu = pcpu_find(cpu);
685	td = pcpu->pc_curthread;
686	if (ke->ke_thread->td_priority < td->td_priority ||
687	    td == pcpu->pc_idlethread) {
688		td->td_flags |= TDF_NEEDRESCHED;
689		ipi_selected(1 << cpu, IPI_AST);
690	}
691}
692
693static struct kse *
694runq_steal(struct runq *rq)
695{
696	struct rqhead *rqh;
697	struct rqbits *rqb;
698	struct kse *ke;
699	int word;
700	int bit;
701
702	mtx_assert(&sched_lock, MA_OWNED);
703	rqb = &rq->rq_status;
704	for (word = 0; word < RQB_LEN; word++) {
705		if (rqb->rqb_bits[word] == 0)
706			continue;
707		for (bit = 0; bit < RQB_BPW; bit++) {
708			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
709				continue;
710			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
711			TAILQ_FOREACH(ke, rqh, ke_procq) {
712				if (KSE_CAN_MIGRATE(ke,
713				    PRI_BASE(ke->ke_ksegrp->kg_pri_class)))
714					return (ke);
715			}
716		}
717	}
718	return (NULL);
719}
720
721static struct kse *
722kseq_steal(struct kseq *kseq, int stealidle)
723{
724	struct kse *ke;
725
726	/*
727	 * Steal from next first to try to get a non-interactive task that
728	 * may not have run for a while.
729	 */
730	if ((ke = runq_steal(kseq->ksq_next)) != NULL)
731		return (ke);
732	if ((ke = runq_steal(kseq->ksq_curr)) != NULL)
733		return (ke);
734	if (stealidle)
735		return (runq_steal(&kseq->ksq_idle));
736	return (NULL);
737}
738
739int
740kseq_transfer(struct kseq *kseq, struct kse *ke, int class)
741{
742	struct kseq_group *ksg;
743	int cpu;
744
745	if (smp_started == 0)
746		return (0);
747	cpu = 0;
748	ksg = kseq->ksq_group;
749
750	/*
751	 * If there are any idle groups, give them our extra load.  The
752	 * threshold at which we start to reassign kses has a large impact
753	 * on the overall performance of the system.  Tuned too high and
754	 * some CPUs may idle.  Too low and there will be excess migration
755	 * and context swiches.
756	 */
757	if (ksg->ksg_load > (ksg->ksg_cpus * 2) && kseq_idle) {
758		/*
759		 * Multiple cpus could find this bit simultaneously
760		 * but the race shouldn't be terrible.
761		 */
762		cpu = ffs(kseq_idle);
763		if (cpu)
764			atomic_clear_int(&kseq_idle, 1 << (cpu - 1));
765	}
766	/*
767	 * If another cpu in this group has idled, assign a thread over
768	 * to them after checking to see if there are idled groups.
769	 */
770	if (cpu == 0 && kseq->ksq_load > 1 && ksg->ksg_idlemask) {
771		cpu = ffs(ksg->ksg_idlemask);
772		if (cpu)
773			ksg->ksg_idlemask &= ~(1 << (cpu - 1));
774	}
775	/*
776	 * Now that we've found an idle CPU, migrate the thread.
777	 */
778	if (cpu) {
779		cpu--;
780		ke->ke_runq = NULL;
781		kseq_notify(ke, cpu);
782		return (1);
783	}
784	return (0);
785}
786
787#endif	/* SMP */
788
789/*
790 * Pick the highest priority task we have and return it.
791 */
792
793static struct kse *
794kseq_choose(struct kseq *kseq)
795{
796	struct kse *ke;
797	struct runq *swap;
798
799	mtx_assert(&sched_lock, MA_OWNED);
800	swap = NULL;
801
802	for (;;) {
803		ke = runq_choose(kseq->ksq_curr);
804		if (ke == NULL) {
805			/*
806			 * We already swaped once and didn't get anywhere.
807			 */
808			if (swap)
809				break;
810			swap = kseq->ksq_curr;
811			kseq->ksq_curr = kseq->ksq_next;
812			kseq->ksq_next = swap;
813			continue;
814		}
815		/*
816		 * If we encounter a slice of 0 the kse is in a
817		 * TIMESHARE kse group and its nice was too far out
818		 * of the range that receives slices.
819		 */
820		if (ke->ke_slice == 0) {
821			runq_remove(ke->ke_runq, ke);
822			sched_slice(ke);
823			ke->ke_runq = kseq->ksq_next;
824			runq_add(ke->ke_runq, ke);
825			continue;
826		}
827		return (ke);
828	}
829
830	return (runq_choose(&kseq->ksq_idle));
831}
832
833static void
834kseq_setup(struct kseq *kseq)
835{
836	runq_init(&kseq->ksq_timeshare[0]);
837	runq_init(&kseq->ksq_timeshare[1]);
838	runq_init(&kseq->ksq_idle);
839	kseq->ksq_curr = &kseq->ksq_timeshare[0];
840	kseq->ksq_next = &kseq->ksq_timeshare[1];
841	kseq->ksq_load = 0;
842	kseq->ksq_load_timeshare = 0;
843}
844
845static void
846sched_setup(void *dummy)
847{
848#ifdef SMP
849	int balance_groups;
850	int i;
851#endif
852
853	slice_min = (hz/100);	/* 10ms */
854	slice_max = (hz/7);	/* ~140ms */
855
856#ifdef SMP
857	balance_groups = 0;
858	/*
859	 * Initialize the kseqs.
860	 */
861	for (i = 0; i < MAXCPU; i++) {
862		struct kseq *ksq;
863
864		ksq = &kseq_cpu[i];
865		ksq->ksq_assigned = NULL;
866		kseq_setup(&kseq_cpu[i]);
867	}
868	if (smp_topology == NULL) {
869		struct kseq_group *ksg;
870		struct kseq *ksq;
871
872		for (i = 0; i < MAXCPU; i++) {
873			ksq = &kseq_cpu[i];
874			ksg = &kseq_groups[i];
875			/*
876			 * Setup a kse group with one member.
877			 */
878			ksq->ksq_transferable = 0;
879			ksq->ksq_group = ksg;
880			ksg->ksg_cpus = 1;
881			ksg->ksg_idlemask = 0;
882			ksg->ksg_cpumask = ksg->ksg_mask = 1 << i;
883			ksg->ksg_load = 0;
884			ksg->ksg_transferable = 0;
885			LIST_INIT(&ksg->ksg_members);
886			LIST_INSERT_HEAD(&ksg->ksg_members, ksq, ksq_siblings);
887		}
888	} else {
889		struct kseq_group *ksg;
890		struct cpu_group *cg;
891		int j;
892
893		for (i = 0; i < smp_topology->ct_count; i++) {
894			cg = &smp_topology->ct_group[i];
895			ksg = &kseq_groups[i];
896			/*
897			 * Initialize the group.
898			 */
899			ksg->ksg_idlemask = 0;
900			ksg->ksg_load = 0;
901			ksg->ksg_transferable = 0;
902			ksg->ksg_cpus = cg->cg_count;
903			ksg->ksg_cpumask = cg->cg_mask;
904			LIST_INIT(&ksg->ksg_members);
905			/*
906			 * Find all of the group members and add them.
907			 */
908			for (j = 0; j < MAXCPU; j++) {
909				if ((cg->cg_mask & (1 << j)) != 0) {
910					if (ksg->ksg_mask == 0)
911						ksg->ksg_mask = 1 << j;
912					kseq_cpu[j].ksq_transferable = 0;
913					kseq_cpu[j].ksq_group = ksg;
914					LIST_INSERT_HEAD(&ksg->ksg_members,
915					    &kseq_cpu[j], ksq_siblings);
916				}
917			}
918			if (ksg->ksg_cpus > 1)
919				balance_groups = 1;
920		}
921		ksg_maxid = smp_topology->ct_count - 1;
922	}
923	callout_init(&kseq_lb_callout, CALLOUT_MPSAFE);
924	callout_init(&kseq_group_callout, CALLOUT_MPSAFE);
925	sched_balance(NULL);
926	/*
927	 * Stagger the group and global load balancer so they do not
928	 * interfere with each other.
929	 */
930	if (balance_groups)
931		callout_reset(&kseq_group_callout, hz / 2,
932		    sched_balance_groups, NULL);
933#else
934	kseq_setup(KSEQ_SELF());
935#endif
936	mtx_lock_spin(&sched_lock);
937	kseq_load_add(KSEQ_SELF(), &kse0);
938	mtx_unlock_spin(&sched_lock);
939}
940
941/*
942 * Scale the scheduling priority according to the "interactivity" of this
943 * process.
944 */
945static void
946sched_priority(struct ksegrp *kg)
947{
948	int pri;
949
950	if (kg->kg_pri_class != PRI_TIMESHARE)
951		return;
952
953	pri = SCHED_PRI_INTERACT(sched_interact_score(kg));
954	pri += SCHED_PRI_BASE;
955	pri += kg->kg_nice;
956
957	if (pri > PRI_MAX_TIMESHARE)
958		pri = PRI_MAX_TIMESHARE;
959	else if (pri < PRI_MIN_TIMESHARE)
960		pri = PRI_MIN_TIMESHARE;
961
962	kg->kg_user_pri = pri;
963
964	return;
965}
966
967/*
968 * Calculate a time slice based on the properties of the kseg and the runq
969 * that we're on.  This is only for PRI_TIMESHARE ksegrps.
970 */
971static void
972sched_slice(struct kse *ke)
973{
974	struct kseq *kseq;
975	struct ksegrp *kg;
976
977	kg = ke->ke_ksegrp;
978	kseq = KSEQ_CPU(ke->ke_cpu);
979
980	/*
981	 * Rationale:
982	 * KSEs in interactive ksegs get the minimum slice so that we
983	 * quickly notice if it abuses its advantage.
984	 *
985	 * KSEs in non-interactive ksegs are assigned a slice that is
986	 * based on the ksegs nice value relative to the least nice kseg
987	 * on the run queue for this cpu.
988	 *
989	 * If the KSE is less nice than all others it gets the maximum
990	 * slice and other KSEs will adjust their slice relative to
991	 * this when they first expire.
992	 *
993	 * There is 20 point window that starts relative to the least
994	 * nice kse on the run queue.  Slice size is determined by
995	 * the kse distance from the last nice ksegrp.
996	 *
997	 * If the kse is outside of the window it will get no slice
998	 * and will be reevaluated each time it is selected on the
999	 * run queue.  The exception to this is nice 0 ksegs when
1000	 * a nice -20 is running.  They are always granted a minimum
1001	 * slice.
1002	 */
1003	if (!SCHED_INTERACTIVE(kg)) {
1004		int nice;
1005
1006		nice = kg->kg_nice + (0 - kseq->ksq_nicemin);
1007		if (kseq->ksq_load_timeshare == 0 ||
1008		    kg->kg_nice < kseq->ksq_nicemin)
1009			ke->ke_slice = SCHED_SLICE_MAX;
1010		else if (nice <= SCHED_SLICE_NTHRESH)
1011			ke->ke_slice = SCHED_SLICE_NICE(nice);
1012		else if (kg->kg_nice == 0)
1013			ke->ke_slice = SCHED_SLICE_MIN;
1014		else
1015			ke->ke_slice = 0;
1016	} else
1017		ke->ke_slice = SCHED_SLICE_INTERACTIVE;
1018
1019	CTR6(KTR_ULE,
1020	    "Sliced %p(%d) (nice: %d, nicemin: %d, load: %d, interactive: %d)",
1021	    ke, ke->ke_slice, kg->kg_nice, kseq->ksq_nicemin,
1022	    kseq->ksq_load_timeshare, SCHED_INTERACTIVE(kg));
1023
1024	return;
1025}
1026
1027/*
1028 * This routine enforces a maximum limit on the amount of scheduling history
1029 * kept.  It is called after either the slptime or runtime is adjusted.
1030 * This routine will not operate correctly when slp or run times have been
1031 * adjusted to more than double their maximum.
1032 */
1033static void
1034sched_interact_update(struct ksegrp *kg)
1035{
1036	int sum;
1037
1038	sum = kg->kg_runtime + kg->kg_slptime;
1039	if (sum < SCHED_SLP_RUN_MAX)
1040		return;
1041	/*
1042	 * If we have exceeded by more than 1/5th then the algorithm below
1043	 * will not bring us back into range.  Dividing by two here forces
1044	 * us into the range of [3/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1045	 */
1046	if (sum > (SCHED_INTERACT_MAX / 5) * 6) {
1047		kg->kg_runtime /= 2;
1048		kg->kg_slptime /= 2;
1049		return;
1050	}
1051	kg->kg_runtime = (kg->kg_runtime / 5) * 4;
1052	kg->kg_slptime = (kg->kg_slptime / 5) * 4;
1053}
1054
1055static void
1056sched_interact_fork(struct ksegrp *kg)
1057{
1058	int ratio;
1059	int sum;
1060
1061	sum = kg->kg_runtime + kg->kg_slptime;
1062	if (sum > SCHED_SLP_RUN_FORK) {
1063		ratio = sum / SCHED_SLP_RUN_FORK;
1064		kg->kg_runtime /= ratio;
1065		kg->kg_slptime /= ratio;
1066	}
1067}
1068
1069static int
1070sched_interact_score(struct ksegrp *kg)
1071{
1072	int div;
1073
1074	if (kg->kg_runtime > kg->kg_slptime) {
1075		div = max(1, kg->kg_runtime / SCHED_INTERACT_HALF);
1076		return (SCHED_INTERACT_HALF +
1077		    (SCHED_INTERACT_HALF - (kg->kg_slptime / div)));
1078	} if (kg->kg_slptime > kg->kg_runtime) {
1079		div = max(1, kg->kg_slptime / SCHED_INTERACT_HALF);
1080		return (kg->kg_runtime / div);
1081	}
1082
1083	/*
1084	 * This can happen if slptime and runtime are 0.
1085	 */
1086	return (0);
1087
1088}
1089
1090/*
1091 * This is only somewhat accurate since given many processes of the same
1092 * priority they will switch when their slices run out, which will be
1093 * at most SCHED_SLICE_MAX.
1094 */
1095int
1096sched_rr_interval(void)
1097{
1098	return (SCHED_SLICE_MAX);
1099}
1100
1101static void
1102sched_pctcpu_update(struct kse *ke)
1103{
1104	/*
1105	 * Adjust counters and watermark for pctcpu calc.
1106	 */
1107	if (ke->ke_ltick > ticks - SCHED_CPU_TICKS) {
1108		/*
1109		 * Shift the tick count out so that the divide doesn't
1110		 * round away our results.
1111		 */
1112		ke->ke_ticks <<= 10;
1113		ke->ke_ticks = (ke->ke_ticks / (ticks - ke->ke_ftick)) *
1114			    SCHED_CPU_TICKS;
1115		ke->ke_ticks >>= 10;
1116	} else
1117		ke->ke_ticks = 0;
1118	ke->ke_ltick = ticks;
1119	ke->ke_ftick = ke->ke_ltick - SCHED_CPU_TICKS;
1120}
1121
1122void
1123sched_prio(struct thread *td, u_char prio)
1124{
1125	struct kse *ke;
1126
1127	ke = td->td_kse;
1128	mtx_assert(&sched_lock, MA_OWNED);
1129	if (TD_ON_RUNQ(td)) {
1130		/*
1131		 * If the priority has been elevated due to priority
1132		 * propagation, we may have to move ourselves to a new
1133		 * queue.  We still call adjustrunqueue below in case kse
1134		 * needs to fix things up.
1135		 */
1136		if (prio < td->td_priority && ke &&
1137		    (ke->ke_flags & KEF_ASSIGNED) == 0 &&
1138		    ke->ke_runq != KSEQ_CPU(ke->ke_cpu)->ksq_curr) {
1139			runq_remove(ke->ke_runq, ke);
1140			ke->ke_runq = KSEQ_CPU(ke->ke_cpu)->ksq_curr;
1141			runq_add(ke->ke_runq, ke);
1142		}
1143		adjustrunqueue(td, prio);
1144	} else
1145		td->td_priority = prio;
1146}
1147
1148void
1149sched_switch(struct thread *td)
1150{
1151	struct thread *newtd;
1152	struct kse *ke;
1153
1154	mtx_assert(&sched_lock, MA_OWNED);
1155
1156	ke = td->td_kse;
1157
1158	td->td_last_kse = ke;
1159        td->td_lastcpu = td->td_oncpu;
1160	td->td_oncpu = NOCPU;
1161        td->td_flags &= ~TDF_NEEDRESCHED;
1162
1163	/*
1164	 * If the KSE has been assigned it may be in the process of switching
1165	 * to the new cpu.  This is the case in sched_bind().
1166	 */
1167	if ((ke->ke_flags & KEF_ASSIGNED) == 0) {
1168		if (TD_IS_RUNNING(td)) {
1169			if (td->td_proc->p_flag & P_SA) {
1170				kseq_load_rem(KSEQ_CPU(ke->ke_cpu), ke);
1171				setrunqueue(td);
1172			} else
1173				kseq_runq_add(KSEQ_SELF(), ke);
1174		} else {
1175			if (ke->ke_runq) {
1176				kseq_load_rem(KSEQ_CPU(ke->ke_cpu), ke);
1177			} else if ((td->td_flags & TDF_IDLETD) == 0)
1178				backtrace();
1179			/*
1180			 * We will not be on the run queue. So we must be
1181			 * sleeping or similar.
1182			 */
1183			if (td->td_proc->p_flag & P_SA)
1184				kse_reassign(ke);
1185		}
1186	}
1187	newtd = choosethread();
1188	if (td != newtd)
1189		cpu_switch(td, newtd);
1190	sched_lock.mtx_lock = (uintptr_t)td;
1191
1192	td->td_oncpu = PCPU_GET(cpuid);
1193}
1194
1195void
1196sched_nice(struct ksegrp *kg, int nice)
1197{
1198	struct kse *ke;
1199	struct thread *td;
1200	struct kseq *kseq;
1201
1202	PROC_LOCK_ASSERT(kg->kg_proc, MA_OWNED);
1203	mtx_assert(&sched_lock, MA_OWNED);
1204	/*
1205	 * We need to adjust the nice counts for running KSEs.
1206	 */
1207	if (kg->kg_pri_class == PRI_TIMESHARE)
1208		FOREACH_KSE_IN_GROUP(kg, ke) {
1209			if (ke->ke_runq == NULL)
1210				continue;
1211			kseq = KSEQ_CPU(ke->ke_cpu);
1212			kseq_nice_rem(kseq, kg->kg_nice);
1213			kseq_nice_add(kseq, nice);
1214		}
1215	kg->kg_nice = nice;
1216	sched_priority(kg);
1217	FOREACH_THREAD_IN_GROUP(kg, td)
1218		td->td_flags |= TDF_NEEDRESCHED;
1219}
1220
1221void
1222sched_sleep(struct thread *td)
1223{
1224	mtx_assert(&sched_lock, MA_OWNED);
1225
1226	td->td_slptime = ticks;
1227	td->td_base_pri = td->td_priority;
1228
1229	CTR2(KTR_ULE, "sleep kse %p (tick: %d)",
1230	    td->td_kse, td->td_slptime);
1231}
1232
1233void
1234sched_wakeup(struct thread *td)
1235{
1236	mtx_assert(&sched_lock, MA_OWNED);
1237
1238	/*
1239	 * Let the kseg know how long we slept for.  This is because process
1240	 * interactivity behavior is modeled in the kseg.
1241	 */
1242	if (td->td_slptime) {
1243		struct ksegrp *kg;
1244		int hzticks;
1245
1246		kg = td->td_ksegrp;
1247		hzticks = (ticks - td->td_slptime) << 10;
1248		if (hzticks >= SCHED_SLP_RUN_MAX) {
1249			kg->kg_slptime = SCHED_SLP_RUN_MAX;
1250			kg->kg_runtime = 1;
1251		} else {
1252			kg->kg_slptime += hzticks;
1253			sched_interact_update(kg);
1254		}
1255		sched_priority(kg);
1256		if (td->td_kse)
1257			sched_slice(td->td_kse);
1258		CTR2(KTR_ULE, "wakeup kse %p (%d ticks)",
1259		    td->td_kse, hzticks);
1260		td->td_slptime = 0;
1261	}
1262	setrunqueue(td);
1263}
1264
1265/*
1266 * Penalize the parent for creating a new child and initialize the child's
1267 * priority.
1268 */
1269void
1270sched_fork(struct proc *p, struct proc *p1)
1271{
1272
1273	mtx_assert(&sched_lock, MA_OWNED);
1274
1275	sched_fork_ksegrp(FIRST_KSEGRP_IN_PROC(p), FIRST_KSEGRP_IN_PROC(p1));
1276	sched_fork_kse(FIRST_KSE_IN_PROC(p), FIRST_KSE_IN_PROC(p1));
1277	sched_fork_thread(FIRST_THREAD_IN_PROC(p), FIRST_THREAD_IN_PROC(p1));
1278}
1279
1280void
1281sched_fork_kse(struct kse *ke, struct kse *child)
1282{
1283
1284	child->ke_slice = 1;	/* Attempt to quickly learn interactivity. */
1285	child->ke_cpu = ke->ke_cpu;
1286	child->ke_runq = NULL;
1287
1288	/* Grab our parents cpu estimation information. */
1289	child->ke_ticks = ke->ke_ticks;
1290	child->ke_ltick = ke->ke_ltick;
1291	child->ke_ftick = ke->ke_ftick;
1292}
1293
1294void
1295sched_fork_ksegrp(struct ksegrp *kg, struct ksegrp *child)
1296{
1297	PROC_LOCK_ASSERT(child->kg_proc, MA_OWNED);
1298
1299	child->kg_slptime = kg->kg_slptime;
1300	child->kg_runtime = kg->kg_runtime;
1301	child->kg_user_pri = kg->kg_user_pri;
1302	child->kg_nice = kg->kg_nice;
1303	sched_interact_fork(child);
1304	kg->kg_runtime += tickincr << 10;
1305	sched_interact_update(kg);
1306
1307	CTR6(KTR_ULE, "sched_fork_ksegrp: %d(%d, %d) - %d(%d, %d)",
1308	    kg->kg_proc->p_pid, kg->kg_slptime, kg->kg_runtime,
1309	    child->kg_proc->p_pid, child->kg_slptime, child->kg_runtime);
1310}
1311
1312void
1313sched_fork_thread(struct thread *td, struct thread *child)
1314{
1315}
1316
1317void
1318sched_class(struct ksegrp *kg, int class)
1319{
1320	struct kseq *kseq;
1321	struct kse *ke;
1322	int nclass;
1323	int oclass;
1324
1325	mtx_assert(&sched_lock, MA_OWNED);
1326	if (kg->kg_pri_class == class)
1327		return;
1328
1329	nclass = PRI_BASE(class);
1330	oclass = PRI_BASE(kg->kg_pri_class);
1331	FOREACH_KSE_IN_GROUP(kg, ke) {
1332		if (ke->ke_state != KES_ONRUNQ &&
1333		    ke->ke_state != KES_THREAD)
1334			continue;
1335		kseq = KSEQ_CPU(ke->ke_cpu);
1336
1337#ifdef SMP
1338		/*
1339		 * On SMP if we're on the RUNQ we must adjust the transferable
1340		 * count because could be changing to or from an interrupt
1341		 * class.
1342		 */
1343		if (ke->ke_state == KES_ONRUNQ) {
1344			if (KSE_CAN_MIGRATE(ke, oclass)) {
1345				kseq->ksq_transferable--;
1346				kseq->ksq_group->ksg_transferable--;
1347			}
1348			if (KSE_CAN_MIGRATE(ke, nclass)) {
1349				kseq->ksq_transferable++;
1350				kseq->ksq_group->ksg_transferable++;
1351			}
1352		}
1353#endif
1354		if (oclass == PRI_TIMESHARE) {
1355			kseq->ksq_load_timeshare--;
1356			kseq_nice_rem(kseq, kg->kg_nice);
1357		}
1358		if (nclass == PRI_TIMESHARE) {
1359			kseq->ksq_load_timeshare++;
1360			kseq_nice_add(kseq, kg->kg_nice);
1361		}
1362	}
1363
1364	kg->kg_pri_class = class;
1365}
1366
1367/*
1368 * Return some of the child's priority and interactivity to the parent.
1369 */
1370void
1371sched_exit(struct proc *p, struct proc *child)
1372{
1373	mtx_assert(&sched_lock, MA_OWNED);
1374	sched_exit_kse(FIRST_KSE_IN_PROC(p), FIRST_KSE_IN_PROC(child));
1375	sched_exit_ksegrp(FIRST_KSEGRP_IN_PROC(p), FIRST_KSEGRP_IN_PROC(child));
1376}
1377
1378void
1379sched_exit_kse(struct kse *ke, struct kse *child)
1380{
1381	kseq_load_rem(KSEQ_CPU(child->ke_cpu), child);
1382}
1383
1384void
1385sched_exit_ksegrp(struct ksegrp *kg, struct ksegrp *child)
1386{
1387	/* kg->kg_slptime += child->kg_slptime; */
1388	kg->kg_runtime += child->kg_runtime;
1389	sched_interact_update(kg);
1390}
1391
1392void
1393sched_exit_thread(struct thread *td, struct thread *child)
1394{
1395}
1396
1397void
1398sched_clock(struct thread *td)
1399{
1400	struct kseq *kseq;
1401	struct ksegrp *kg;
1402	struct kse *ke;
1403
1404	/*
1405	 * sched_setup() apparently happens prior to stathz being set.  We
1406	 * need to resolve the timers earlier in the boot so we can avoid
1407	 * calculating this here.
1408	 */
1409	if (realstathz == 0) {
1410		realstathz = stathz ? stathz : hz;
1411		tickincr = hz / realstathz;
1412		/*
1413		 * XXX This does not work for values of stathz that are much
1414		 * larger than hz.
1415		 */
1416		if (tickincr == 0)
1417			tickincr = 1;
1418	}
1419
1420	ke = td->td_kse;
1421	kg = ke->ke_ksegrp;
1422
1423	mtx_assert(&sched_lock, MA_OWNED);
1424	/* Adjust ticks for pctcpu */
1425	ke->ke_ticks++;
1426	ke->ke_ltick = ticks;
1427
1428	/* Go up to one second beyond our max and then trim back down */
1429	if (ke->ke_ftick + SCHED_CPU_TICKS + hz < ke->ke_ltick)
1430		sched_pctcpu_update(ke);
1431
1432	if (td->td_flags & TDF_IDLETD)
1433		return;
1434
1435	CTR4(KTR_ULE, "Tick kse %p (slice: %d, slptime: %d, runtime: %d)",
1436	    ke, ke->ke_slice, kg->kg_slptime >> 10, kg->kg_runtime >> 10);
1437	/*
1438	 * We only do slicing code for TIMESHARE ksegrps.
1439	 */
1440	if (kg->kg_pri_class != PRI_TIMESHARE)
1441		return;
1442	/*
1443	 * We used a tick charge it to the ksegrp so that we can compute our
1444	 * interactivity.
1445	 */
1446	kg->kg_runtime += tickincr << 10;
1447	sched_interact_update(kg);
1448
1449	/*
1450	 * We used up one time slice.
1451	 */
1452	if (--ke->ke_slice > 0)
1453		return;
1454	/*
1455	 * We're out of time, recompute priorities and requeue.
1456	 */
1457	kseq = KSEQ_SELF();
1458	kseq_load_rem(kseq, ke);
1459	sched_priority(kg);
1460	sched_slice(ke);
1461	if (SCHED_CURR(kg, ke))
1462		ke->ke_runq = kseq->ksq_curr;
1463	else
1464		ke->ke_runq = kseq->ksq_next;
1465	kseq_load_add(kseq, ke);
1466	td->td_flags |= TDF_NEEDRESCHED;
1467}
1468
1469int
1470sched_runnable(void)
1471{
1472	struct kseq *kseq;
1473	int load;
1474
1475	load = 1;
1476
1477	kseq = KSEQ_SELF();
1478#ifdef SMP
1479	if (kseq->ksq_assigned) {
1480		mtx_lock_spin(&sched_lock);
1481		kseq_assign(kseq);
1482		mtx_unlock_spin(&sched_lock);
1483	}
1484#endif
1485	if ((curthread->td_flags & TDF_IDLETD) != 0) {
1486		if (kseq->ksq_load > 0)
1487			goto out;
1488	} else
1489		if (kseq->ksq_load - 1 > 0)
1490			goto out;
1491	load = 0;
1492out:
1493	return (load);
1494}
1495
1496void
1497sched_userret(struct thread *td)
1498{
1499	struct ksegrp *kg;
1500
1501	kg = td->td_ksegrp;
1502
1503	if (td->td_priority != kg->kg_user_pri) {
1504		mtx_lock_spin(&sched_lock);
1505		td->td_priority = kg->kg_user_pri;
1506		mtx_unlock_spin(&sched_lock);
1507	}
1508}
1509
1510struct kse *
1511sched_choose(void)
1512{
1513	struct kseq *kseq;
1514	struct kse *ke;
1515
1516	mtx_assert(&sched_lock, MA_OWNED);
1517	kseq = KSEQ_SELF();
1518#ifdef SMP
1519restart:
1520	if (kseq->ksq_assigned)
1521		kseq_assign(kseq);
1522#endif
1523	ke = kseq_choose(kseq);
1524	if (ke) {
1525#ifdef SMP
1526		if (ke->ke_ksegrp->kg_pri_class == PRI_IDLE)
1527			if (kseq_idled(kseq) == 0)
1528				goto restart;
1529#endif
1530		kseq_runq_rem(kseq, ke);
1531		ke->ke_state = KES_THREAD;
1532
1533		if (ke->ke_ksegrp->kg_pri_class == PRI_TIMESHARE) {
1534			CTR4(KTR_ULE, "Run kse %p from %p (slice: %d, pri: %d)",
1535			    ke, ke->ke_runq, ke->ke_slice,
1536			    ke->ke_thread->td_priority);
1537		}
1538		return (ke);
1539	}
1540#ifdef SMP
1541	if (kseq_idled(kseq) == 0)
1542		goto restart;
1543#endif
1544	return (NULL);
1545}
1546
1547void
1548sched_add(struct thread *td)
1549{
1550	struct kseq *kseq;
1551	struct ksegrp *kg;
1552	struct kse *ke;
1553	int class;
1554
1555	mtx_assert(&sched_lock, MA_OWNED);
1556	ke = td->td_kse;
1557	kg = td->td_ksegrp;
1558	if (ke->ke_flags & KEF_ASSIGNED)
1559		return;
1560	kseq = KSEQ_SELF();
1561	KASSERT((ke->ke_thread != NULL),
1562	    ("sched_add: No thread on KSE"));
1563	KASSERT((ke->ke_thread->td_kse != NULL),
1564	    ("sched_add: No KSE on thread"));
1565	KASSERT(ke->ke_state != KES_ONRUNQ,
1566	    ("sched_add: kse %p (%s) already in run queue", ke,
1567	    ke->ke_proc->p_comm));
1568	KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
1569	    ("sched_add: process swapped out"));
1570	KASSERT(ke->ke_runq == NULL,
1571	    ("sched_add: KSE %p is still assigned to a run queue", ke));
1572
1573	class = PRI_BASE(kg->kg_pri_class);
1574	switch (class) {
1575	case PRI_ITHD:
1576	case PRI_REALTIME:
1577		ke->ke_runq = kseq->ksq_curr;
1578		ke->ke_slice = SCHED_SLICE_MAX;
1579		ke->ke_cpu = PCPU_GET(cpuid);
1580		break;
1581	case PRI_TIMESHARE:
1582		if (SCHED_CURR(kg, ke))
1583			ke->ke_runq = kseq->ksq_curr;
1584		else
1585			ke->ke_runq = kseq->ksq_next;
1586		break;
1587	case PRI_IDLE:
1588		/*
1589		 * This is for priority prop.
1590		 */
1591		if (ke->ke_thread->td_priority < PRI_MIN_IDLE)
1592			ke->ke_runq = kseq->ksq_curr;
1593		else
1594			ke->ke_runq = &kseq->ksq_idle;
1595		ke->ke_slice = SCHED_SLICE_MIN;
1596		break;
1597	default:
1598		panic("Unknown pri class.");
1599		break;
1600	}
1601#ifdef SMP
1602	if (ke->ke_cpu != PCPU_GET(cpuid)) {
1603		ke->ke_runq = NULL;
1604		kseq_notify(ke, ke->ke_cpu);
1605		return;
1606	}
1607	/*
1608	 * If we had been idle, clear our bit in the group and potentially
1609	 * the global bitmap.  If not, see if we should transfer this thread.
1610	 */
1611	if ((class == PRI_TIMESHARE || class == PRI_REALTIME) &&
1612	    (kseq->ksq_group->ksg_idlemask & PCPU_GET(cpumask)) != 0) {
1613		/*
1614		 * Check to see if our group is unidling, and if so, remove it
1615		 * from the global idle mask.
1616		 */
1617		if (kseq->ksq_group->ksg_idlemask ==
1618		    kseq->ksq_group->ksg_cpumask)
1619			atomic_clear_int(&kseq_idle, kseq->ksq_group->ksg_mask);
1620		/*
1621		 * Now remove ourselves from the group specific idle mask.
1622		 */
1623		kseq->ksq_group->ksg_idlemask &= ~PCPU_GET(cpumask);
1624	} else if (kseq->ksq_load > 1 && KSE_CAN_MIGRATE(ke, class))
1625		if (kseq_transfer(kseq, ke, class))
1626			return;
1627#endif
1628        if (td->td_priority < curthread->td_priority)
1629                curthread->td_flags |= TDF_NEEDRESCHED;
1630
1631	ke->ke_ksegrp->kg_runq_kses++;
1632	ke->ke_state = KES_ONRUNQ;
1633
1634	kseq_runq_add(kseq, ke);
1635	kseq_load_add(kseq, ke);
1636}
1637
1638void
1639sched_rem(struct thread *td)
1640{
1641	struct kseq *kseq;
1642	struct kse *ke;
1643
1644	ke = td->td_kse;
1645	/*
1646	 * It is safe to just return here because sched_rem() is only ever
1647	 * used in places where we're immediately going to add the
1648	 * kse back on again.  In that case it'll be added with the correct
1649	 * thread and priority when the caller drops the sched_lock.
1650	 */
1651	if (ke->ke_flags & KEF_ASSIGNED)
1652		return;
1653	mtx_assert(&sched_lock, MA_OWNED);
1654	KASSERT((ke->ke_state == KES_ONRUNQ),
1655	    ("sched_rem: KSE not on run queue"));
1656
1657	ke->ke_state = KES_THREAD;
1658	ke->ke_ksegrp->kg_runq_kses--;
1659	kseq = KSEQ_CPU(ke->ke_cpu);
1660	kseq_runq_rem(kseq, ke);
1661	kseq_load_rem(kseq, ke);
1662}
1663
1664fixpt_t
1665sched_pctcpu(struct thread *td)
1666{
1667	fixpt_t pctcpu;
1668	struct kse *ke;
1669
1670	pctcpu = 0;
1671	ke = td->td_kse;
1672	if (ke == NULL)
1673		return (0);
1674
1675	mtx_lock_spin(&sched_lock);
1676	if (ke->ke_ticks) {
1677		int rtick;
1678
1679		/*
1680		 * Don't update more frequently than twice a second.  Allowing
1681		 * this causes the cpu usage to decay away too quickly due to
1682		 * rounding errors.
1683		 */
1684		if (ke->ke_ftick + SCHED_CPU_TICKS < ke->ke_ltick ||
1685		    ke->ke_ltick < (ticks - (hz / 2)))
1686			sched_pctcpu_update(ke);
1687		/* How many rtick per second ? */
1688		rtick = min(ke->ke_ticks / SCHED_CPU_TIME, SCHED_CPU_TICKS);
1689		pctcpu = (FSCALE * ((FSCALE * rtick)/realstathz)) >> FSHIFT;
1690	}
1691
1692	ke->ke_proc->p_swtime = ke->ke_ltick - ke->ke_ftick;
1693	mtx_unlock_spin(&sched_lock);
1694
1695	return (pctcpu);
1696}
1697
1698void
1699sched_bind(struct thread *td, int cpu)
1700{
1701	struct kse *ke;
1702
1703	mtx_assert(&sched_lock, MA_OWNED);
1704	ke = td->td_kse;
1705	ke->ke_flags |= KEF_BOUND;
1706#ifdef SMP
1707	if (PCPU_GET(cpuid) == cpu)
1708		return;
1709	/* sched_rem without the runq_remove */
1710	ke->ke_state = KES_THREAD;
1711	ke->ke_ksegrp->kg_runq_kses--;
1712	kseq_load_rem(KSEQ_CPU(ke->ke_cpu), ke);
1713	kseq_notify(ke, cpu);
1714	/* When we return from mi_switch we'll be on the correct cpu. */
1715	mi_switch(SW_VOL);
1716#endif
1717}
1718
1719void
1720sched_unbind(struct thread *td)
1721{
1722	mtx_assert(&sched_lock, MA_OWNED);
1723	td->td_kse->ke_flags &= ~KEF_BOUND;
1724}
1725
1726int
1727sched_load(void)
1728{
1729#ifdef SMP
1730	int total;
1731	int i;
1732
1733	total = 0;
1734	for (i = 0; i <= ksg_maxid; i++)
1735		total += KSEQ_GROUP(i)->ksg_load;
1736	return (total);
1737#else
1738	return (KSEQ_SELF()->ksq_sysload);
1739#endif
1740}
1741
1742int
1743sched_sizeof_kse(void)
1744{
1745	return (sizeof(struct kse) + sizeof(struct ke_sched));
1746}
1747
1748int
1749sched_sizeof_ksegrp(void)
1750{
1751	return (sizeof(struct ksegrp) + sizeof(struct kg_sched));
1752}
1753
1754int
1755sched_sizeof_proc(void)
1756{
1757	return (sizeof(struct proc));
1758}
1759
1760int
1761sched_sizeof_thread(void)
1762{
1763	return (sizeof(struct thread) + sizeof(struct td_sched));
1764}
1765