2 * Copyright (c) 2002-2007, Jeffrey Roberson <jeff@freebsd.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice unmodified, this list of conditions, and the following
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.
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.
28 * This file implements the ULE scheduler. ULE supports independent CPU
29 * run queues and fine grain locking. It has superior interactive
30 * performance under load even on uni-processor systems.
33 * ULE is the last three letters in schedule. It owes its name to a
34 * generic user created for a scheduling system by Paul Mikesell at
35 * Isilon Systems and a general lack of creativity on the part of the author.
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
41 #include "opt_hwpmc_hooks.h"
42 #include "opt_kdtrace.h"
43 #include "opt_sched.h"
45 #include <sys/param.h>
46 #include <sys/systm.h>
48 #include <sys/kernel.h>
51 #include <sys/mutex.h>
53 #include <sys/resource.h>
54 #include <sys/resourcevar.h>
55 #include <sys/sched.h>
58 #include <sys/sysctl.h>
59 #include <sys/sysproto.h>
60 #include <sys/turnstile.h>
62 #include <sys/vmmeter.h>
63 #include <sys/cpuset.h>
66 #include <sys/ktrace.h>
70 #include <sys/pmckern.h>
74 #include <sys/dtrace_bsd.h>
75 int dtrace_vtime_active;
76 dtrace_vtime_switch_func_t dtrace_vtime_switch_func;
79 #include <machine/cpu.h>
80 #include <machine/smp.h>
82 #if !defined(__i386__) && !defined(__amd64__) && !defined(__arm__)
83 #error "This architecture is not currently compatible with ULE"
89 * Thread scheduler specific section. All fields are protected
93 TAILQ_ENTRY(td_sched) ts_procq; /* Run queue. */
94 struct thread *ts_thread; /* Active associated thread. */
95 struct runq *ts_runq; /* Run-queue we're queued on. */
96 short ts_flags; /* TSF_* flags. */
97 u_char ts_rqindex; /* Run queue index. */
98 u_char ts_cpu; /* CPU that we have affinity for. */
99 int ts_slice; /* Ticks of slice remaining. */
100 u_int ts_slptime; /* Number of ticks we vol. slept */
101 u_int ts_runtime; /* Number of ticks we were running */
102 /* The following variables are only used for pctcpu calculation */
103 int ts_ltick; /* Last tick that we were running on */
104 int ts_ftick; /* First tick that we were running on */
105 int ts_ticks; /* Tick count */
107 int ts_rltick; /* Real last tick, for affinity. */
110 /* flags kept in ts_flags */
111 #define TSF_BOUND 0x0001 /* Thread can not migrate. */
112 #define TSF_XFERABLE 0x0002 /* Thread was added as transferable. */
114 static struct td_sched td_sched0;
116 #define THREAD_CAN_MIGRATE(td) ((td)->td_pinned == 0)
117 #define THREAD_CAN_SCHED(td, cpu) \
118 CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
121 * Cpu percentage computation macros and defines.
123 * SCHED_TICK_SECS: Number of seconds to average the cpu usage across.
124 * SCHED_TICK_TARG: Number of hz ticks to average the cpu usage across.
125 * SCHED_TICK_MAX: Maximum number of ticks before scaling back.
126 * SCHED_TICK_SHIFT: Shift factor to avoid rounding away results.
127 * SCHED_TICK_HZ: Compute the number of hz ticks for a given ticks count.
128 * SCHED_TICK_TOTAL: Gives the amount of time we've been recording ticks.
130 #define SCHED_TICK_SECS 10
131 #define SCHED_TICK_TARG (hz * SCHED_TICK_SECS)
132 #define SCHED_TICK_MAX (SCHED_TICK_TARG + hz)
133 #define SCHED_TICK_SHIFT 10
134 #define SCHED_TICK_HZ(ts) ((ts)->ts_ticks >> SCHED_TICK_SHIFT)
135 #define SCHED_TICK_TOTAL(ts) (max((ts)->ts_ltick - (ts)->ts_ftick, hz))
138 * These macros determine priorities for non-interactive threads. They are
139 * assigned a priority based on their recent cpu utilization as expressed
140 * by the ratio of ticks to the tick total. NHALF priorities at the start
141 * and end of the MIN to MAX timeshare range are only reachable with negative
142 * or positive nice respectively.
144 * PRI_RANGE: Priority range for utilization dependent priorities.
145 * PRI_NRESV: Number of nice values.
146 * PRI_TICKS: Compute a priority in PRI_RANGE from the ticks count and total.
147 * PRI_NICE: Determines the part of the priority inherited from nice.
149 #define SCHED_PRI_NRESV (PRIO_MAX - PRIO_MIN)
150 #define SCHED_PRI_NHALF (SCHED_PRI_NRESV / 2)
151 #define SCHED_PRI_MIN (PRI_MIN_TIMESHARE + SCHED_PRI_NHALF)
152 #define SCHED_PRI_MAX (PRI_MAX_TIMESHARE - SCHED_PRI_NHALF)
153 #define SCHED_PRI_RANGE (SCHED_PRI_MAX - SCHED_PRI_MIN)
154 #define SCHED_PRI_TICKS(ts) \
155 (SCHED_TICK_HZ((ts)) / \
156 (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
157 #define SCHED_PRI_NICE(nice) (nice)
160 * These determine the interactivity of a process. Interactivity differs from
161 * cpu utilization in that it expresses the voluntary time slept vs time ran
162 * while cpu utilization includes all time not running. This more accurately
163 * models the intent of the thread.
165 * SLP_RUN_MAX: Maximum amount of sleep time + run time we'll accumulate
166 * before throttling back.
167 * SLP_RUN_FORK: Maximum slp+run time to inherit at fork time.
168 * INTERACT_MAX: Maximum interactivity value. Smaller is better.
169 * INTERACT_THRESH: Threshhold for placement on the current runq.
171 #define SCHED_SLP_RUN_MAX ((hz * 5) << SCHED_TICK_SHIFT)
172 #define SCHED_SLP_RUN_FORK ((hz / 2) << SCHED_TICK_SHIFT)
173 #define SCHED_INTERACT_MAX (100)
174 #define SCHED_INTERACT_HALF (SCHED_INTERACT_MAX / 2)
175 #define SCHED_INTERACT_THRESH (30)
178 * tickincr: Converts a stathz tick into a hz domain scaled by
179 * the shift factor. Without the shift the error rate
180 * due to rounding would be unacceptably high.
181 * realstathz: stathz is sometimes 0 and run off of hz.
182 * sched_slice: Runtime of each thread before rescheduling.
183 * preempt_thresh: Priority threshold for preemption and remote IPIs.
185 static int sched_interact = SCHED_INTERACT_THRESH;
186 static int realstathz;
188 static int sched_slice;
190 #ifdef FULL_PREEMPTION
191 static int preempt_thresh = PRI_MAX_IDLE;
193 static int preempt_thresh = PRI_MIN_KERN;
196 static int preempt_thresh = 0;
200 * tdq - per processor runqs and statistics. All fields are protected by the
201 * tdq_lock. The load and lowpri may be accessed without to avoid excess
202 * locking in sched_pickcpu();
205 struct mtx *tdq_lock; /* Pointer to group lock. */
206 struct runq tdq_realtime; /* real-time run queue. */
207 struct runq tdq_timeshare; /* timeshare run queue. */
208 struct runq tdq_idle; /* Queue of IDLE threads. */
209 int tdq_load; /* Aggregate load. */
210 u_char tdq_idx; /* Current insert index. */
211 u_char tdq_ridx; /* Current removal index. */
213 u_char tdq_lowpri; /* Lowest priority thread. */
214 int tdq_transferable; /* Transferable thread count. */
215 LIST_ENTRY(tdq) tdq_siblings; /* Next in tdq group. */
216 struct tdq_group *tdq_group; /* Our processor group. */
218 int tdq_sysload; /* For loadavg, !ITHD load. */
225 * tdq groups are groups of processors which can cheaply share threads. When
226 * one processor in the group goes idle it will check the runqs of the other
227 * processors in its group prior to halting and waiting for an interrupt.
228 * These groups are suitable for SMT (Symetric Multi-Threading) and not NUMA.
229 * In a numa environment we'd want an idle bitmap per group and a two tiered
233 struct mtx tdg_lock; /* Protects all fields below. */
234 int tdg_cpus; /* Count of CPUs in this tdq group. */
235 cpumask_t tdg_cpumask; /* Mask of cpus in this group. */
236 cpumask_t tdg_idlemask; /* Idle cpus in this group. */
237 cpumask_t tdg_mask; /* Bit mask for first cpu. */
238 int tdg_load; /* Total load of this group. */
239 int tdg_transferable; /* Transferable load of this group. */
240 LIST_HEAD(, tdq) tdg_members; /* Linked list of all members. */
241 char tdg_name[16]; /* lock name. */
244 #define SCHED_AFFINITY_DEFAULT (max(1, hz / 300))
245 #define SCHED_AFFINITY(ts) ((ts)->ts_rltick > ticks - affinity)
250 static int rebalance = 1;
251 static int balance_interval = 128; /* Default set in sched_initticks(). */
252 static int pick_pri = 1;
254 static int tryself = 1;
255 static int steal_htt = 1;
256 static int steal_idle = 1;
257 static int steal_thresh = 2;
258 static int topology = 0;
261 * One thread queue per processor.
263 static volatile cpumask_t tdq_idle;
264 static int tdg_maxid;
265 static struct tdq tdq_cpu[MAXCPU];
266 static struct tdq_group tdq_groups[MAXCPU];
267 static struct tdq *balance_tdq;
268 static int balance_group_ticks;
269 static int balance_ticks;
271 #define TDQ_SELF() (&tdq_cpu[PCPU_GET(cpuid)])
272 #define TDQ_CPU(x) (&tdq_cpu[(x)])
273 #define TDQ_ID(x) ((int)((x) - tdq_cpu))
274 #define TDQ_GROUP(x) (&tdq_groups[(x)])
275 #define TDG_ID(x) ((int)((x) - tdq_groups))
277 static struct tdq tdq_cpu;
278 static struct mtx tdq_lock;
280 #define TDQ_ID(x) (0)
281 #define TDQ_SELF() (&tdq_cpu)
282 #define TDQ_CPU(x) (&tdq_cpu)
285 #define TDQ_LOCK_ASSERT(t, type) mtx_assert(TDQ_LOCKPTR((t)), (type))
286 #define TDQ_LOCK(t) mtx_lock_spin(TDQ_LOCKPTR((t)))
287 #define TDQ_LOCK_FLAGS(t, f) mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
288 #define TDQ_UNLOCK(t) mtx_unlock_spin(TDQ_LOCKPTR((t)))
289 #define TDQ_LOCKPTR(t) ((t)->tdq_lock)
291 static void sched_priority(struct thread *);
292 static void sched_thread_priority(struct thread *, u_char);
293 static int sched_interact_score(struct thread *);
294 static void sched_interact_update(struct thread *);
295 static void sched_interact_fork(struct thread *);
296 static void sched_pctcpu_update(struct td_sched *);
298 /* Operations on per processor queues */
299 static struct td_sched * tdq_choose(struct tdq *);
300 static void tdq_setup(struct tdq *);
301 static void tdq_load_add(struct tdq *, struct td_sched *);
302 static void tdq_load_rem(struct tdq *, struct td_sched *);
303 static __inline void tdq_runq_add(struct tdq *, struct td_sched *, int);
304 static __inline void tdq_runq_rem(struct tdq *, struct td_sched *);
305 void tdq_print(int cpu);
306 static void runq_print(struct runq *rq);
307 static void tdq_add(struct tdq *, struct thread *, int);
309 static void tdq_move(struct tdq *, struct tdq *);
310 static int tdq_idled(struct tdq *);
311 static void tdq_notify(struct td_sched *);
312 static struct td_sched *tdq_steal(struct tdq *, int);
313 static struct td_sched *runq_steal(struct runq *, int);
314 static int sched_pickcpu(struct thread *, int);
315 static void sched_balance(void);
316 static void sched_balance_groups(void);
317 static void sched_balance_group(struct tdq_group *);
318 static void sched_balance_pair(struct tdq *, struct tdq *);
319 static inline struct tdq *sched_setcpu(struct td_sched *, int, int);
320 static inline struct mtx *thread_block_switch(struct thread *);
321 static inline void thread_unblock_switch(struct thread *, struct mtx *);
322 static struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
325 static void sched_setup(void *dummy);
326 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
328 static void sched_initticks(void *dummy);
329 SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
333 * Print the threads waiting on a run-queue.
336 runq_print(struct runq *rq)
344 for (i = 0; i < RQB_LEN; i++) {
345 printf("\t\trunq bits %d 0x%zx\n",
346 i, rq->rq_status.rqb_bits[i]);
347 for (j = 0; j < RQB_BPW; j++)
348 if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
349 pri = j + (i << RQB_L2BPW);
350 rqh = &rq->rq_queues[pri];
351 TAILQ_FOREACH(ts, rqh, ts_procq) {
352 printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
353 ts->ts_thread, ts->ts_thread->td_proc->p_comm, ts->ts_thread->td_priority, ts->ts_rqindex, pri);
360 * Print the status of a per-cpu thread queue. Should be a ddb show cmd.
369 printf("tdq %d:\n", TDQ_ID(tdq));
370 printf("\tlockptr %p\n", TDQ_LOCKPTR(tdq));
371 printf("\tload: %d\n", tdq->tdq_load);
372 printf("\ttimeshare idx: %d\n", tdq->tdq_idx);
373 printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
374 printf("\trealtime runq:\n");
375 runq_print(&tdq->tdq_realtime);
376 printf("\ttimeshare runq:\n");
377 runq_print(&tdq->tdq_timeshare);
378 printf("\tidle runq:\n");
379 runq_print(&tdq->tdq_idle);
381 printf("\tload transferable: %d\n", tdq->tdq_transferable);
382 printf("\tlowest priority: %d\n", tdq->tdq_lowpri);
383 printf("\tgroup: %d\n", TDG_ID(tdq->tdq_group));
384 printf("\tLock name: %s\n", tdq->tdq_group->tdg_name);
388 #define TS_RQ_PPQ (((PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE) + 1) / RQ_NQS)
390 * Add a thread to the actual run-queue. Keeps transferable counts up to
391 * date with what is actually on the run-queue. Selects the correct
392 * queue position for timeshare threads.
395 tdq_runq_add(struct tdq *tdq, struct td_sched *ts, int flags)
397 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
398 THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
400 if (THREAD_CAN_MIGRATE(ts->ts_thread)) {
401 tdq->tdq_transferable++;
402 tdq->tdq_group->tdg_transferable++;
403 ts->ts_flags |= TSF_XFERABLE;
406 if (ts->ts_runq == &tdq->tdq_timeshare) {
409 pri = ts->ts_thread->td_priority;
410 KASSERT(pri <= PRI_MAX_TIMESHARE && pri >= PRI_MIN_TIMESHARE,
411 ("Invalid priority %d on timeshare runq", pri));
413 * This queue contains only priorities between MIN and MAX
414 * realtime. Use the whole queue to represent these values.
416 if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
417 pri = (pri - PRI_MIN_TIMESHARE) / TS_RQ_PPQ;
418 pri = (pri + tdq->tdq_idx) % RQ_NQS;
420 * This effectively shortens the queue by one so we
421 * can have a one slot difference between idx and
422 * ridx while we wait for threads to drain.
424 if (tdq->tdq_ridx != tdq->tdq_idx &&
425 pri == tdq->tdq_ridx)
426 pri = (unsigned char)(pri - 1) % RQ_NQS;
429 runq_add_pri(ts->ts_runq, ts, pri, flags);
431 runq_add(ts->ts_runq, ts, flags);
435 * Remove a thread from a run-queue. This typically happens when a thread
436 * is selected to run. Running threads are not on the queue and the
437 * transferable count does not reflect them.
440 tdq_runq_rem(struct tdq *tdq, struct td_sched *ts)
442 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
443 KASSERT(ts->ts_runq != NULL,
444 ("tdq_runq_remove: thread %p null ts_runq", ts->ts_thread));
446 if (ts->ts_flags & TSF_XFERABLE) {
447 tdq->tdq_transferable--;
448 tdq->tdq_group->tdg_transferable--;
449 ts->ts_flags &= ~TSF_XFERABLE;
452 if (ts->ts_runq == &tdq->tdq_timeshare) {
453 if (tdq->tdq_idx != tdq->tdq_ridx)
454 runq_remove_idx(ts->ts_runq, ts, &tdq->tdq_ridx);
456 runq_remove_idx(ts->ts_runq, ts, NULL);
458 * For timeshare threads we update the priority here so
459 * the priority reflects the time we've been sleeping.
461 ts->ts_ltick = ticks;
462 sched_pctcpu_update(ts);
463 sched_priority(ts->ts_thread);
465 runq_remove(ts->ts_runq, ts);
469 * Load is maintained for all threads RUNNING and ON_RUNQ. Add the load
470 * for this thread to the referenced thread queue.
473 tdq_load_add(struct tdq *tdq, struct td_sched *ts)
477 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
478 THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
479 class = PRI_BASE(ts->ts_thread->td_pri_class);
481 CTR2(KTR_SCHED, "cpu %d load: %d", TDQ_ID(tdq), tdq->tdq_load);
482 if (class != PRI_ITHD &&
483 (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0)
485 tdq->tdq_group->tdg_load++;
492 * Remove the load from a thread that is transitioning to a sleep state or
496 tdq_load_rem(struct tdq *tdq, struct td_sched *ts)
500 THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
501 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
502 class = PRI_BASE(ts->ts_thread->td_pri_class);
503 if (class != PRI_ITHD &&
504 (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0)
506 tdq->tdq_group->tdg_load--;
510 KASSERT(tdq->tdq_load != 0,
511 ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
513 CTR1(KTR_SCHED, "load: %d", tdq->tdq_load);
519 * sched_balance is a simple CPU load balancing algorithm. It operates by
520 * finding the least loaded and most loaded cpu and equalizing their load
521 * by migrating some processes.
523 * Dealing only with two CPUs at a time has two advantages. Firstly, most
524 * installations will only have 2 cpus. Secondly, load balancing too much at
525 * once can have an unpleasant effect on the system. The scheduler rarely has
526 * enough information to make perfect decisions. So this algorithm chooses
527 * simplicity and more gradual effects on load in larger systems.
533 struct tdq_group *high;
534 struct tdq_group *low;
535 struct tdq_group *tdg;
541 * Select a random time between .5 * balance_interval and
542 * 1.5 * balance_interval.
544 balance_ticks = max(balance_interval / 2, 1);
545 balance_ticks += random() % balance_interval;
546 if (smp_started == 0 || rebalance == 0)
551 i = random() % (tdg_maxid + 1);
552 for (cnt = 0; cnt <= tdg_maxid; cnt++) {
555 * Find the CPU with the highest load that has some
556 * threads to transfer.
558 if ((high == NULL || tdg->tdg_load > high->tdg_load)
559 && tdg->tdg_transferable)
561 if (low == NULL || tdg->tdg_load < low->tdg_load)
566 if (low != NULL && high != NULL && high != low)
567 sched_balance_pair(LIST_FIRST(&high->tdg_members),
568 LIST_FIRST(&low->tdg_members));
573 * Balance load between CPUs in a group. Will only migrate within the group.
576 sched_balance_groups()
582 * Select a random time between .5 * balance_interval and
583 * 1.5 * balance_interval.
585 balance_group_ticks = max(balance_interval / 2, 1);
586 balance_group_ticks += random() % balance_interval;
587 if (smp_started == 0 || rebalance == 0)
591 for (i = 0; i <= tdg_maxid; i++)
592 sched_balance_group(TDQ_GROUP(i));
597 * Finds the greatest imbalance between two tdqs in a group.
600 sched_balance_group(struct tdq_group *tdg)
607 if (tdg->tdg_transferable == 0)
611 LIST_FOREACH(tdq, &tdg->tdg_members, tdq_siblings) {
612 load = tdq->tdq_load;
613 if (high == NULL || load > high->tdq_load)
615 if (low == NULL || load < low->tdq_load)
618 if (high != NULL && low != NULL && high != low)
619 sched_balance_pair(high, low);
623 * Lock two thread queues using their address to maintain lock order.
626 tdq_lock_pair(struct tdq *one, struct tdq *two)
630 TDQ_LOCK_FLAGS(two, MTX_DUPOK);
633 TDQ_LOCK_FLAGS(one, MTX_DUPOK);
638 * Unlock two thread queues. Order is not important here.
641 tdq_unlock_pair(struct tdq *one, struct tdq *two)
648 * Transfer load between two imbalanced thread queues.
651 sched_balance_pair(struct tdq *high, struct tdq *low)
660 tdq_lock_pair(high, low);
662 * If we're transfering within a group we have to use this specific
663 * tdq's transferable count, otherwise we can steal from other members
666 if (high->tdq_group == low->tdq_group) {
667 transferable = high->tdq_transferable;
668 high_load = high->tdq_load;
669 low_load = low->tdq_load;
671 transferable = high->tdq_group->tdg_transferable;
672 high_load = high->tdq_group->tdg_load;
673 low_load = low->tdq_group->tdg_load;
676 * Determine what the imbalance is and then adjust that to how many
677 * threads we actually have to give up (transferable).
679 if (transferable != 0) {
680 diff = high_load - low_load;
684 move = min(move, transferable);
685 for (i = 0; i < move; i++)
688 * IPI the target cpu to force it to reschedule with the new
691 ipi_selected(1 << TDQ_ID(low), IPI_PREEMPT);
693 tdq_unlock_pair(high, low);
698 * Move a thread from one thread queue to another.
701 tdq_move(struct tdq *from, struct tdq *to)
708 TDQ_LOCK_ASSERT(from, MA_OWNED);
709 TDQ_LOCK_ASSERT(to, MA_OWNED);
713 ts = tdq_steal(tdq, cpu);
715 struct tdq_group *tdg;
717 tdg = tdq->tdq_group;
718 LIST_FOREACH(tdq, &tdg->tdg_members, tdq_siblings) {
719 if (tdq == from || tdq->tdq_transferable == 0)
721 ts = tdq_steal(tdq, cpu);
731 * Although the run queue is locked the thread may be blocked. Lock
732 * it to clear this and acquire the run-queue lock.
735 /* Drop recursive lock on from acquired via thread_lock(). */
739 td->td_lock = TDQ_LOCKPTR(to);
740 tdq_add(to, td, SRQ_YIELDING);
744 * This tdq has idled. Try to steal a thread from another cpu and switch
748 tdq_idled(struct tdq *tdq)
750 struct tdq_group *tdg;
756 if (smp_started == 0 || steal_idle == 0)
758 /* We don't want to be preempted while we're iterating over tdqs */
760 tdg = tdq->tdq_group;
762 * If we're in a cpu group, try and steal threads from another cpu in
763 * the group before idling. In a HTT group all cpus share the same
764 * run-queue lock, however, we still need a recursive lock to
767 if (steal_htt && tdg->tdg_cpus > 1 && tdg->tdg_transferable) {
769 LIST_FOREACH(steal, &tdg->tdg_members, tdq_siblings) {
770 if (steal == tdq || steal->tdq_transferable == 0)
778 * Find the least loaded CPU with a transferable thread and attempt
779 * to steal it. We make a lockless pass and then verify that the
780 * thread is still available after locking.
785 for (cpu = 0; cpu <= mp_maxid; cpu++) {
788 steal = TDQ_CPU(cpu);
789 if (steal->tdq_transferable == 0)
791 if (steal->tdq_load < highload)
793 highload = steal->tdq_load;
796 if (highload < steal_thresh)
798 steal = TDQ_CPU(highcpu);
801 tdq_lock_pair(tdq, steal);
802 if (steal->tdq_load >= steal_thresh && steal->tdq_transferable)
804 tdq_unlock_pair(tdq, steal);
810 tdq_move(steal, tdq);
812 mi_switch(SW_VOL, NULL);
813 thread_unlock(curthread);
819 * Notify a remote cpu of new work. Sends an IPI if criteria are met.
822 tdq_notify(struct td_sched *ts)
831 pri = ts->ts_thread->td_priority;
832 pcpu = pcpu_find(cpu);
833 ctd = pcpu->pc_curthread;
834 cpri = ctd->td_priority;
837 * If our priority is not better than the current priority there is
845 if (cpri > PRI_MIN_IDLE)
848 * If we're realtime or better and there is timeshare or worse running
851 if (pri < PRI_MAX_REALTIME && cpri > PRI_MAX_REALTIME)
854 * Otherwise only IPI if we exceed the threshold.
856 if (pri > preempt_thresh)
859 ipi_selected(1 << cpu, IPI_PREEMPT);
863 * Steals load from a timeshare queue. Honors the rotating queue head
866 static struct td_sched *
867 runq_steal_from(struct runq *rq, int cpu, u_char start)
877 rqb = &rq->rq_status;
878 bit = start & (RQB_BPW -1);
882 for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
883 if (rqb->rqb_bits[i] == 0)
886 for (pri = bit; pri < RQB_BPW; pri++)
887 if (rqb->rqb_bits[i] & (1ul << pri))
892 pri = RQB_FFS(rqb->rqb_bits[i]);
893 pri += (i << RQB_L2BPW);
894 rqh = &rq->rq_queues[pri];
895 TAILQ_FOREACH(ts, rqh, ts_procq) {
896 if (first && THREAD_CAN_MIGRATE(ts->ts_thread) &&
897 THREAD_CAN_SCHED(ts->ts_thread, cpu))
911 * Steals load from a standard linear queue.
913 static struct td_sched *
914 runq_steal(struct runq *rq, int cpu)
922 rqb = &rq->rq_status;
923 for (word = 0; word < RQB_LEN; word++) {
924 if (rqb->rqb_bits[word] == 0)
926 for (bit = 0; bit < RQB_BPW; bit++) {
927 if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
929 rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
930 TAILQ_FOREACH(ts, rqh, ts_procq)
931 if (THREAD_CAN_MIGRATE(ts->ts_thread) &&
932 THREAD_CAN_SCHED(ts->ts_thread, cpu))
940 * Attempt to steal a thread in priority order from a thread queue.
942 static struct td_sched *
943 tdq_steal(struct tdq *tdq, int cpu)
947 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
948 if ((ts = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
950 if ((ts = runq_steal_from(&tdq->tdq_timeshare,
951 cpu, tdq->tdq_ridx)) != NULL)
953 return (runq_steal(&tdq->tdq_idle, cpu));
957 * Sets the thread lock and ts_cpu to match the requested cpu. Unlocks the
958 * current lock and returns with the assigned queue locked.
960 static inline struct tdq *
961 sched_setcpu(struct td_sched *ts, int cpu, int flags)
966 THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
972 /* If the lock matches just return the queue. */
973 if (td->td_lock == TDQ_LOCKPTR(tdq))
977 * If the thread isn't running its lockptr is a
978 * turnstile or a sleepqueue. We can just lock_set without
981 if (TD_CAN_RUN(td)) {
983 thread_lock_set(td, TDQ_LOCKPTR(tdq));
988 * The hard case, migration, we need to block the thread first to
989 * prevent order reversals with other cpus locks.
991 thread_lock_block(td);
993 thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
998 * Find the thread queue running the lowest priority thread.
1001 tdq_lowestpri(struct thread *td)
1012 lowpri = lowcpu = 0;
1013 for (cpu = 0; cpu <= mp_maxid; cpu++) {
1014 if (CPU_ABSENT(cpu))
1016 if (!THREAD_CAN_SCHED(td, cpu))
1019 pri = tdq->tdq_lowpri;
1020 load = TDQ_CPU(cpu)->tdq_load;
1022 "cpu %d pri %d lowcpu %d lowpri %d",
1023 cpu, pri, lowcpu, lowpri);
1026 if (lowpri && lowpri == pri && load > lowload)
1037 * Find the thread queue with the least load.
1040 tdq_lowestload(struct thread *td)
1051 lowload = TDQ_CPU(0)->tdq_load;
1052 lowpri = TDQ_CPU(0)->tdq_lowpri;
1053 for (cpu = 1; cpu <= mp_maxid; cpu++) {
1054 if (CPU_ABSENT(cpu))
1056 if (!THREAD_CAN_SCHED(td, cpu))
1059 load = tdq->tdq_load;
1060 pri = tdq->tdq_lowpri;
1061 CTR4(KTR_ULE, "cpu %d load %d lowcpu %d lowload %d",
1062 cpu, load, lowcpu, lowload);
1065 if (load == lowload && pri < lowpri)
1076 * Pick the destination cpu for sched_add(). Respects affinity and makes
1077 * a determination based on load or priority of available processors.
1080 sched_pickcpu(struct thread *td, int flags)
1083 struct td_sched *ts;
1089 self = PCPU_GET(cpuid);
1091 if (smp_started == 0)
1094 * Don't migrate a running thread from sched_switch().
1096 if (flags & SRQ_OURSELF) {
1097 CTR1(KTR_ULE, "YIELDING %d",
1098 curthread->td_priority);
1101 pri = ts->ts_thread->td_priority;
1103 if (THREAD_CAN_SCHED(td, cpu)) {
1105 * Regardless of affinity, if the last cpu is idle
1109 if (tdq->tdq_lowpri > PRI_MIN_IDLE) {
1111 "ts_cpu %d idle, ltick %d ticks %d pri %d curthread %d",
1112 ts->ts_cpu, ts->ts_rltick, ticks, pri,
1114 return (ts->ts_cpu);
1117 * If we have affinity, try to place it on the cpu we
1120 if (SCHED_AFFINITY(ts) && tdq->tdq_lowpri > pri) {
1122 "affinity for %d, ltick %d ticks %d pri %d curthread %d",
1123 ts->ts_cpu, ts->ts_rltick, ticks, pri,
1125 return (ts->ts_cpu);
1130 * Look for an idle group.
1132 CTR1(KTR_ULE, "tdq_idle %X", tdq_idle);
1134 while ((cpu = ffs(mask)) != 0) {
1136 if (THREAD_CAN_SCHED(td, cpu))
1138 mask &= ~(1 << cpu);
1141 * If there are no idle cores see if we can run the thread locally.
1142 * This may improve locality among sleepers and wakers when there
1145 if (tryself && THREAD_CAN_SCHED(td, self) &&
1146 pri < curthread->td_priority) {
1147 CTR1(KTR_ULE, "tryself %d",
1148 curthread->td_priority);
1152 * Now search for the cpu running the lowest priority thread with
1156 cpu = tdq_lowestpri(td);
1158 cpu = tdq_lowestload(td);
1165 * Pick the highest priority task we have and return it.
1167 static struct td_sched *
1168 tdq_choose(struct tdq *tdq)
1170 struct td_sched *ts;
1172 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1173 ts = runq_choose(&tdq->tdq_realtime);
1176 ts = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1178 KASSERT(ts->ts_thread->td_priority >= PRI_MIN_TIMESHARE,
1179 ("tdq_choose: Invalid priority on timeshare queue %d",
1180 ts->ts_thread->td_priority));
1184 ts = runq_choose(&tdq->tdq_idle);
1186 KASSERT(ts->ts_thread->td_priority >= PRI_MIN_IDLE,
1187 ("tdq_choose: Invalid priority on idle queue %d",
1188 ts->ts_thread->td_priority));
1196 * Initialize a thread queue.
1199 tdq_setup(struct tdq *tdq)
1203 printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1204 runq_init(&tdq->tdq_realtime);
1205 runq_init(&tdq->tdq_timeshare);
1206 runq_init(&tdq->tdq_idle);
1212 tdg_setup(struct tdq_group *tdg)
1215 printf("ULE: setup cpu group %d\n", TDG_ID(tdg));
1216 snprintf(tdg->tdg_name, sizeof(tdg->tdg_name),
1217 "sched lock %d", (int)TDG_ID(tdg));
1218 mtx_init(&tdg->tdg_lock, tdg->tdg_name, "sched lock",
1219 MTX_SPIN | MTX_RECURSE);
1220 LIST_INIT(&tdg->tdg_members);
1222 tdg->tdg_transferable = 0;
1225 tdg->tdg_cpumask = 0;
1226 tdg->tdg_idlemask = 0;
1230 tdg_add(struct tdq_group *tdg, struct tdq *tdq)
1232 if (tdg->tdg_mask == 0)
1233 tdg->tdg_mask |= 1 << TDQ_ID(tdq);
1234 tdg->tdg_cpumask |= 1 << TDQ_ID(tdq);
1236 tdq->tdq_group = tdg;
1237 tdq->tdq_lock = &tdg->tdg_lock;
1238 LIST_INSERT_HEAD(&tdg->tdg_members, tdq, tdq_siblings);
1240 printf("ULE: adding cpu %d to group %d: cpus %d mask 0x%X\n",
1241 TDQ_ID(tdq), TDG_ID(tdg), tdg->tdg_cpus, tdg->tdg_cpumask);
1245 sched_setup_topology(void)
1247 struct tdq_group *tdg;
1248 struct cpu_group *cg;
1256 for (i = 0; i < smp_topology->ct_count; i++) {
1257 cg = &smp_topology->ct_group[i];
1258 tdg = &tdq_groups[i];
1260 * Initialize the group.
1264 * Find all of the group members and add them.
1266 for (j = 0; j < MAXCPU; j++) {
1267 if ((cg->cg_mask & (1 << j)) != 0) {
1273 if (tdg->tdg_cpus > 1)
1276 tdg_maxid = smp_topology->ct_count - 1;
1278 sched_balance_groups();
1282 sched_setup_smp(void)
1284 struct tdq_group *tdg;
1289 for (cpus = 0, i = 0; i < MAXCPU; i++) {
1293 tdg = &tdq_groups[i];
1295 * Setup a tdq group with one member.
1302 tdg_maxid = cpus - 1;
1306 * Fake a topology with one group containing all CPUs.
1309 sched_fake_topo(void)
1311 #ifdef SCHED_FAKE_TOPOLOGY
1312 static struct cpu_top top;
1313 static struct cpu_group group;
1316 top.ct_group = &group;
1317 group.cg_mask = all_cpus;
1318 group.cg_count = mp_ncpus;
1319 group.cg_children = 0;
1320 smp_topology = ⊤
1326 * Setup the thread queues and initialize the topology based on MD
1330 sched_setup(void *dummy)
1338 * Setup tdqs based on a topology configuration or vanilla SMP based
1341 if (smp_topology == NULL)
1344 sched_setup_topology();
1349 mtx_init(&tdq_lock, "sched lock", "sched lock", MTX_SPIN | MTX_RECURSE);
1350 tdq->tdq_lock = &tdq_lock;
1353 * To avoid divide-by-zero, we set realstathz a dummy value
1354 * in case which sched_clock() called before sched_initticks().
1357 sched_slice = (realstathz/10); /* ~100ms */
1358 tickincr = 1 << SCHED_TICK_SHIFT;
1360 /* Add thread0's load since it's running. */
1362 thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1363 tdq_load_add(tdq, &td_sched0);
1368 * This routine determines the tickincr after stathz and hz are setup.
1372 sched_initticks(void *dummy)
1376 realstathz = stathz ? stathz : hz;
1377 sched_slice = (realstathz/10); /* ~100ms */
1380 * tickincr is shifted out by 10 to avoid rounding errors due to
1381 * hz not being evenly divisible by stathz on all platforms.
1383 incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1385 * This does not work for values of stathz that are more than
1386 * 1 << SCHED_TICK_SHIFT * hz. In practice this does not happen.
1393 * Set the default balance interval now that we know
1394 * what realstathz is.
1396 balance_interval = realstathz;
1398 * Set steal thresh to roughly log2(mp_ncpu) but no greater than 4.
1399 * This prevents excess thrashing on large machines and excess idle
1400 * on smaller machines.
1402 steal_thresh = min(fls(mp_ncpus) - 1, 3);
1403 affinity = SCHED_AFFINITY_DEFAULT;
1409 * This is the core of the interactivity algorithm. Determines a score based
1410 * on past behavior. It is the ratio of sleep time to run time scaled to
1411 * a [0, 100] integer. This is the voluntary sleep time of a process, which
1412 * differs from the cpu usage because it does not account for time spent
1413 * waiting on a run-queue. Would be prettier if we had floating point.
1416 sched_interact_score(struct thread *td)
1418 struct td_sched *ts;
1423 * The score is only needed if this is likely to be an interactive
1424 * task. Don't go through the expense of computing it if there's
1427 if (sched_interact <= SCHED_INTERACT_HALF &&
1428 ts->ts_runtime >= ts->ts_slptime)
1429 return (SCHED_INTERACT_HALF);
1431 if (ts->ts_runtime > ts->ts_slptime) {
1432 div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1433 return (SCHED_INTERACT_HALF +
1434 (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1436 if (ts->ts_slptime > ts->ts_runtime) {
1437 div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1438 return (ts->ts_runtime / div);
1440 /* runtime == slptime */
1442 return (SCHED_INTERACT_HALF);
1445 * This can happen if slptime and runtime are 0.
1452 * Scale the scheduling priority according to the "interactivity" of this
1456 sched_priority(struct thread *td)
1461 if (td->td_pri_class != PRI_TIMESHARE)
1464 * If the score is interactive we place the thread in the realtime
1465 * queue with a priority that is less than kernel and interrupt
1466 * priorities. These threads are not subject to nice restrictions.
1468 * Scores greater than this are placed on the normal timeshare queue
1469 * where the priority is partially decided by the most recent cpu
1470 * utilization and the rest is decided by nice value.
1472 * The nice value of the process has a linear effect on the calculated
1473 * score. Negative nice values make it easier for a thread to be
1474 * considered interactive.
1476 score = imax(0, sched_interact_score(td) - td->td_proc->p_nice);
1477 if (score < sched_interact) {
1478 pri = PRI_MIN_REALTIME;
1479 pri += ((PRI_MAX_REALTIME - PRI_MIN_REALTIME) / sched_interact)
1481 KASSERT(pri >= PRI_MIN_REALTIME && pri <= PRI_MAX_REALTIME,
1482 ("sched_priority: invalid interactive priority %d score %d",
1485 pri = SCHED_PRI_MIN;
1486 if (td->td_sched->ts_ticks)
1487 pri += SCHED_PRI_TICKS(td->td_sched);
1488 pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1489 KASSERT(pri >= PRI_MIN_TIMESHARE && pri <= PRI_MAX_TIMESHARE,
1490 ("sched_priority: invalid priority %d: nice %d, "
1491 "ticks %d ftick %d ltick %d tick pri %d",
1492 pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1493 td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1494 SCHED_PRI_TICKS(td->td_sched)));
1496 sched_user_prio(td, pri);
1502 * This routine enforces a maximum limit on the amount of scheduling history
1503 * kept. It is called after either the slptime or runtime is adjusted. This
1504 * function is ugly due to integer math.
1507 sched_interact_update(struct thread *td)
1509 struct td_sched *ts;
1513 sum = ts->ts_runtime + ts->ts_slptime;
1514 if (sum < SCHED_SLP_RUN_MAX)
1517 * This only happens from two places:
1518 * 1) We have added an unusual amount of run time from fork_exit.
1519 * 2) We have added an unusual amount of sleep time from sched_sleep().
1521 if (sum > SCHED_SLP_RUN_MAX * 2) {
1522 if (ts->ts_runtime > ts->ts_slptime) {
1523 ts->ts_runtime = SCHED_SLP_RUN_MAX;
1526 ts->ts_slptime = SCHED_SLP_RUN_MAX;
1532 * If we have exceeded by more than 1/5th then the algorithm below
1533 * will not bring us back into range. Dividing by two here forces
1534 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1536 if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1537 ts->ts_runtime /= 2;
1538 ts->ts_slptime /= 2;
1541 ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1542 ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1546 * Scale back the interactivity history when a child thread is created. The
1547 * history is inherited from the parent but the thread may behave totally
1548 * differently. For example, a shell spawning a compiler process. We want
1549 * to learn that the compiler is behaving badly very quickly.
1552 sched_interact_fork(struct thread *td)
1557 sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1558 if (sum > SCHED_SLP_RUN_FORK) {
1559 ratio = sum / SCHED_SLP_RUN_FORK;
1560 td->td_sched->ts_runtime /= ratio;
1561 td->td_sched->ts_slptime /= ratio;
1566 * Called from proc0_init() to setup the scheduler fields.
1573 * Set up the scheduler specific parts of proc0.
1575 proc0.p_sched = NULL; /* XXX */
1576 thread0.td_sched = &td_sched0;
1577 td_sched0.ts_ltick = ticks;
1578 td_sched0.ts_ftick = ticks;
1579 td_sched0.ts_thread = &thread0;
1583 * This is only somewhat accurate since given many processes of the same
1584 * priority they will switch when their slices run out, which will be
1585 * at most sched_slice stathz ticks.
1588 sched_rr_interval(void)
1591 /* Convert sched_slice to hz */
1592 return (hz/(realstathz/sched_slice));
1596 * Update the percent cpu tracking information when it is requested or
1597 * the total history exceeds the maximum. We keep a sliding history of
1598 * tick counts that slowly decays. This is less precise than the 4BSD
1599 * mechanism since it happens with less regular and frequent events.
1602 sched_pctcpu_update(struct td_sched *ts)
1605 if (ts->ts_ticks == 0)
1607 if (ticks - (hz / 10) < ts->ts_ltick &&
1608 SCHED_TICK_TOTAL(ts) < SCHED_TICK_MAX)
1611 * Adjust counters and watermark for pctcpu calc.
1613 if (ts->ts_ltick > ticks - SCHED_TICK_TARG)
1614 ts->ts_ticks = (ts->ts_ticks / (ticks - ts->ts_ftick)) *
1618 ts->ts_ltick = ticks;
1619 ts->ts_ftick = ts->ts_ltick - SCHED_TICK_TARG;
1623 * Adjust the priority of a thread. Move it to the appropriate run-queue
1624 * if necessary. This is the back-end for several priority related
1628 sched_thread_priority(struct thread *td, u_char prio)
1630 struct td_sched *ts;
1632 CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
1633 td, td->td_proc->p_comm, td->td_priority, prio, curthread,
1634 curthread->td_proc->p_comm);
1636 THREAD_LOCK_ASSERT(td, MA_OWNED);
1637 if (td->td_priority == prio)
1640 if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1642 * If the priority has been elevated due to priority
1643 * propagation, we may have to move ourselves to a new
1644 * queue. This could be optimized to not re-add in some
1648 td->td_priority = prio;
1649 sched_add(td, SRQ_BORROWING);
1654 tdq = TDQ_CPU(ts->ts_cpu);
1655 if (prio < tdq->tdq_lowpri)
1656 tdq->tdq_lowpri = prio;
1658 td->td_priority = prio;
1663 * Update a thread's priority when it is lent another thread's
1667 sched_lend_prio(struct thread *td, u_char prio)
1670 td->td_flags |= TDF_BORROWING;
1671 sched_thread_priority(td, prio);
1675 * Restore a thread's priority when priority propagation is
1676 * over. The prio argument is the minimum priority the thread
1677 * needs to have to satisfy other possible priority lending
1678 * requests. If the thread's regular priority is less
1679 * important than prio, the thread will keep a priority boost
1683 sched_unlend_prio(struct thread *td, u_char prio)
1687 if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1688 td->td_base_pri <= PRI_MAX_TIMESHARE)
1689 base_pri = td->td_user_pri;
1691 base_pri = td->td_base_pri;
1692 if (prio >= base_pri) {
1693 td->td_flags &= ~TDF_BORROWING;
1694 sched_thread_priority(td, base_pri);
1696 sched_lend_prio(td, prio);
1700 * Standard entry for setting the priority to an absolute value.
1703 sched_prio(struct thread *td, u_char prio)
1707 /* First, update the base priority. */
1708 td->td_base_pri = prio;
1711 * If the thread is borrowing another thread's priority, don't
1712 * ever lower the priority.
1714 if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1717 /* Change the real priority. */
1718 oldprio = td->td_priority;
1719 sched_thread_priority(td, prio);
1722 * If the thread is on a turnstile, then let the turnstile update
1725 if (TD_ON_LOCK(td) && oldprio != prio)
1726 turnstile_adjust(td, oldprio);
1730 * Set the base user priority, does not effect current running priority.
1733 sched_user_prio(struct thread *td, u_char prio)
1737 td->td_base_user_pri = prio;
1738 if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio)
1740 oldprio = td->td_user_pri;
1741 td->td_user_pri = prio;
1745 sched_lend_user_prio(struct thread *td, u_char prio)
1749 THREAD_LOCK_ASSERT(td, MA_OWNED);
1750 td->td_flags |= TDF_UBORROWING;
1751 oldprio = td->td_user_pri;
1752 td->td_user_pri = prio;
1756 sched_unlend_user_prio(struct thread *td, u_char prio)
1760 THREAD_LOCK_ASSERT(td, MA_OWNED);
1761 base_pri = td->td_base_user_pri;
1762 if (prio >= base_pri) {
1763 td->td_flags &= ~TDF_UBORROWING;
1764 sched_user_prio(td, base_pri);
1766 sched_lend_user_prio(td, prio);
1771 * Add the thread passed as 'newtd' to the run queue before selecting
1772 * the next thread to run. This is only used for KSE.
1775 sched_switchin(struct tdq *tdq, struct thread *td)
1782 sched_setcpu(td->td_sched, TDQ_ID(tdq), SRQ_YIELDING);
1784 td->td_lock = TDQ_LOCKPTR(tdq);
1786 tdq_add(tdq, td, SRQ_YIELDING);
1787 MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1791 * Block a thread for switching. Similar to thread_block() but does not
1792 * bump the spin count.
1794 static inline struct mtx *
1795 thread_block_switch(struct thread *td)
1799 THREAD_LOCK_ASSERT(td, MA_OWNED);
1801 td->td_lock = &blocked_lock;
1802 mtx_unlock_spin(lock);
1808 * Handle migration from sched_switch(). This happens only for
1812 sched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1816 tdn = TDQ_CPU(td->td_sched->ts_cpu);
1819 * Do the lock dance required to avoid LOR. We grab an extra
1820 * spinlock nesting to prevent preemption while we're
1821 * not holding either run-queue lock.
1824 thread_block_switch(td); /* This releases the lock on tdq. */
1826 tdq_add(tdn, td, flags);
1827 tdq_notify(td->td_sched);
1829 * After we unlock tdn the new cpu still can't switch into this
1830 * thread until we've unblocked it in cpu_switch(). The lock
1831 * pointers may match in the case of HTT cores. Don't unlock here
1832 * or we can deadlock when the other CPU runs the IPI handler.
1834 if (TDQ_LOCKPTR(tdn) != TDQ_LOCKPTR(tdq)) {
1840 return (TDQ_LOCKPTR(tdn));
1844 * Release a thread that was blocked with thread_block_switch().
1847 thread_unblock_switch(struct thread *td, struct mtx *mtx)
1849 atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1854 * Switch threads. This function has to handle threads coming in while
1855 * blocked for some reason, running, or idle. It also must deal with
1856 * migrating a thread from one queue to another as running threads may
1857 * be assigned elsewhere via binding.
1860 sched_switch(struct thread *td, struct thread *newtd, int flags)
1863 struct td_sched *ts;
1868 THREAD_LOCK_ASSERT(td, MA_OWNED);
1870 cpuid = PCPU_GET(cpuid);
1871 tdq = TDQ_CPU(cpuid);
1875 ts->ts_rltick = ticks;
1876 if (newtd && newtd->td_priority < tdq->tdq_lowpri)
1877 tdq->tdq_lowpri = newtd->td_priority;
1879 td->td_lastcpu = td->td_oncpu;
1880 td->td_oncpu = NOCPU;
1881 td->td_flags &= ~TDF_NEEDRESCHED;
1882 td->td_owepreempt = 0;
1884 * The lock pointer in an idle thread should never change. Reset it
1885 * to CAN_RUN as well.
1887 if (TD_IS_IDLETHREAD(td)) {
1888 MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1890 } else if (TD_IS_RUNNING(td)) {
1891 MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1892 tdq_load_rem(tdq, ts);
1893 srqflag = (flags & SW_PREEMPT) ?
1894 SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1895 SRQ_OURSELF|SRQ_YIELDING;
1896 if (ts->ts_cpu == cpuid)
1897 tdq_add(tdq, td, srqflag);
1899 mtx = sched_switch_migrate(tdq, td, srqflag);
1901 /* This thread must be going to sleep. */
1903 mtx = thread_block_switch(td);
1904 tdq_load_rem(tdq, ts);
1907 * We enter here with the thread blocked and assigned to the
1908 * appropriate cpu run-queue or sleep-queue and with the current
1909 * thread-queue locked.
1911 TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1913 * If KSE assigned a new thread just add it here and let choosethread
1914 * select the best one.
1917 sched_switchin(tdq, newtd);
1918 newtd = choosethread();
1920 * Call the MD code to switch contexts if necessary.
1924 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1925 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1927 TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
1929 #ifdef KDTRACE_HOOKS
1931 * If DTrace has set the active vtime enum to anything
1932 * other than INACTIVE (0), then it should have set the
1935 if (dtrace_vtime_active)
1936 (*dtrace_vtime_switch_func)(newtd);
1938 cpu_switch(td, newtd, mtx);
1940 * We may return from cpu_switch on a different cpu. However,
1941 * we always return with td_lock pointing to the current cpu's
1944 cpuid = PCPU_GET(cpuid);
1945 tdq = TDQ_CPU(cpuid);
1947 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1948 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1951 thread_unblock_switch(td, mtx);
1953 * Assert that all went well and return.
1956 /* We should always get here with the lowest priority td possible */
1957 tdq->tdq_lowpri = td->td_priority;
1959 TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1960 MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1961 td->td_oncpu = cpuid;
1965 * Adjust thread priorities as a result of a nice request.
1968 sched_nice(struct proc *p, int nice)
1972 PROC_LOCK_ASSERT(p, MA_OWNED);
1973 PROC_SLOCK_ASSERT(p, MA_OWNED);
1976 FOREACH_THREAD_IN_PROC(p, td) {
1979 sched_prio(td, td->td_base_user_pri);
1985 * Record the sleep time for the interactivity scorer.
1988 sched_sleep(struct thread *td)
1991 THREAD_LOCK_ASSERT(td, MA_OWNED);
1993 td->td_slptick = ticks;
1997 * Schedule a thread to resume execution and record how long it voluntarily
1998 * slept. We also update the pctcpu, interactivity, and priority.
2001 sched_wakeup(struct thread *td)
2003 struct td_sched *ts;
2006 THREAD_LOCK_ASSERT(td, MA_OWNED);
2009 * If we slept for more than a tick update our interactivity and
2012 slptick = td->td_slptick;
2014 if (slptick && slptick != ticks) {
2017 hzticks = (ticks - slptick) << SCHED_TICK_SHIFT;
2018 ts->ts_slptime += hzticks;
2019 sched_interact_update(td);
2020 sched_pctcpu_update(ts);
2023 /* Reset the slice value after we sleep. */
2024 ts->ts_slice = sched_slice;
2025 sched_add(td, SRQ_BORING);
2029 * Penalize the parent for creating a new child and initialize the child's
2033 sched_fork(struct thread *td, struct thread *child)
2035 THREAD_LOCK_ASSERT(td, MA_OWNED);
2036 sched_fork_thread(td, child);
2038 * Penalize the parent and child for forking.
2040 sched_interact_fork(child);
2041 sched_priority(child);
2042 td->td_sched->ts_runtime += tickincr;
2043 sched_interact_update(td);
2048 * Fork a new thread, may be within the same process.
2051 sched_fork_thread(struct thread *td, struct thread *child)
2053 struct td_sched *ts;
2054 struct td_sched *ts2;
2059 THREAD_LOCK_ASSERT(td, MA_OWNED);
2060 sched_newthread(child);
2061 child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
2062 child->td_cpuset = cpuset_ref(td->td_cpuset);
2064 ts2 = child->td_sched;
2065 ts2->ts_cpu = ts->ts_cpu;
2066 ts2->ts_runq = NULL;
2068 * Grab our parents cpu estimation information and priority.
2070 ts2->ts_ticks = ts->ts_ticks;
2071 ts2->ts_ltick = ts->ts_ltick;
2072 ts2->ts_ftick = ts->ts_ftick;
2073 child->td_user_pri = td->td_user_pri;
2074 child->td_base_user_pri = td->td_base_user_pri;
2076 * And update interactivity score.
2078 ts2->ts_slptime = ts->ts_slptime;
2079 ts2->ts_runtime = ts->ts_runtime;
2080 ts2->ts_slice = 1; /* Attempt to quickly learn interactivity. */
2084 * Adjust the priority class of a thread.
2087 sched_class(struct thread *td, int class)
2090 THREAD_LOCK_ASSERT(td, MA_OWNED);
2091 if (td->td_pri_class == class)
2096 * On SMP if we're on the RUNQ we must adjust the transferable
2097 * count because could be changing to or from an interrupt
2100 if (TD_ON_RUNQ(td)) {
2103 tdq = TDQ_CPU(td->td_sched->ts_cpu);
2104 if (THREAD_CAN_MIGRATE(td)) {
2105 tdq->tdq_transferable--;
2106 tdq->tdq_group->tdg_transferable--;
2108 td->td_pri_class = class;
2109 if (THREAD_CAN_MIGRATE(td)) {
2110 tdq->tdq_transferable++;
2111 tdq->tdq_group->tdg_transferable++;
2115 td->td_pri_class = class;
2119 * Return some of the child's priority and interactivity to the parent.
2122 sched_exit(struct proc *p, struct thread *child)
2126 CTR3(KTR_SCHED, "sched_exit: %p(%s) prio %d",
2127 child, child->td_proc->p_comm, child->td_priority);
2129 PROC_SLOCK_ASSERT(p, MA_OWNED);
2130 td = FIRST_THREAD_IN_PROC(p);
2131 sched_exit_thread(td, child);
2135 * Penalize another thread for the time spent on this one. This helps to
2136 * worsen the priority and interactivity of processes which schedule batch
2137 * jobs such as make. This has little effect on the make process itself but
2138 * causes new processes spawned by it to receive worse scores immediately.
2141 sched_exit_thread(struct thread *td, struct thread *child)
2144 CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
2145 child, child->td_proc->p_comm, child->td_priority);
2149 * KSE forks and exits so often that this penalty causes short-lived
2150 * threads to always be non-interactive. This causes mozilla to
2153 if ((td->td_pflags & TDP_SA) && td->td_proc == child->td_proc)
2157 * Give the child's runtime to the parent without returning the
2158 * sleep time as a penalty to the parent. This causes shells that
2159 * launch expensive things to mark their children as expensive.
2162 td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2163 sched_interact_update(td);
2169 * Fix priorities on return to user-space. Priorities may be elevated due
2170 * to static priorities in msleep() or similar.
2173 sched_userret(struct thread *td)
2176 * XXX we cheat slightly on the locking here to avoid locking in
2177 * the usual case. Setting td_priority here is essentially an
2178 * incomplete workaround for not setting it properly elsewhere.
2179 * Now that some interrupt handlers are threads, not setting it
2180 * properly elsewhere can clobber it in the window between setting
2181 * it here and returning to user mode, so don't waste time setting
2182 * it perfectly here.
2184 KASSERT((td->td_flags & TDF_BORROWING) == 0,
2185 ("thread with borrowed priority returning to userland"));
2186 if (td->td_priority != td->td_user_pri) {
2188 td->td_priority = td->td_user_pri;
2189 td->td_base_pri = td->td_user_pri;
2195 * Handle a stathz tick. This is really only relevant for timeshare
2199 sched_clock(struct thread *td)
2202 struct td_sched *ts;
2204 THREAD_LOCK_ASSERT(td, MA_OWNED);
2208 * We run the long term load balancer infrequently on the first cpu.
2210 if (balance_tdq == tdq) {
2211 if (balance_ticks && --balance_ticks == 0)
2213 if (balance_group_ticks && --balance_group_ticks == 0)
2214 sched_balance_groups();
2218 * Advance the insert index once for each tick to ensure that all
2219 * threads get a chance to run.
2221 if (tdq->tdq_idx == tdq->tdq_ridx) {
2222 tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2223 if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2224 tdq->tdq_ridx = tdq->tdq_idx;
2227 if (td->td_pri_class & PRI_FIFO_BIT)
2229 if (td->td_pri_class == PRI_TIMESHARE) {
2231 * We used a tick; charge it to the thread so
2232 * that we can compute our interactivity.
2234 td->td_sched->ts_runtime += tickincr;
2235 sched_interact_update(td);
2238 * We used up one time slice.
2240 if (--ts->ts_slice > 0)
2243 * We're out of time, recompute priorities and requeue.
2246 td->td_flags |= TDF_NEEDRESCHED;
2250 * Called once per hz tick. Used for cpu utilization information. This
2251 * is easier than trying to scale based on stathz.
2256 struct td_sched *ts;
2258 ts = curthread->td_sched;
2260 * Ticks is updated asynchronously on a single cpu. Check here to
2261 * avoid incrementing ts_ticks multiple times in a single tick.
2263 if (ts->ts_ltick == ticks)
2265 /* Adjust ticks for pctcpu */
2266 ts->ts_ticks += 1 << SCHED_TICK_SHIFT;
2267 ts->ts_ltick = ticks;
2269 * Update if we've exceeded our desired tick threshhold by over one
2272 if (ts->ts_ftick + SCHED_TICK_MAX < ts->ts_ltick)
2273 sched_pctcpu_update(ts);
2277 * Return whether the current CPU has runnable tasks. Used for in-kernel
2278 * cooperative idle threads.
2281 sched_runnable(void)
2289 if ((curthread->td_flags & TDF_IDLETD) != 0) {
2290 if (tdq->tdq_load > 0)
2293 if (tdq->tdq_load - 1 > 0)
2301 * Choose the highest priority thread to run. The thread is removed from
2302 * the run-queue while running however the load remains. For SMP we set
2303 * the tdq in the global idle bitmask if it idles here.
2309 struct tdq_group *tdg;
2311 struct td_sched *ts;
2315 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2316 ts = tdq_choose(tdq);
2318 tdq_runq_rem(tdq, ts);
2319 return (ts->ts_thread);
2323 * We only set the idled bit when all of the cpus in the group are
2324 * idle. Otherwise we could get into a situation where a thread bounces
2325 * back and forth between two idle cores on seperate physical CPUs.
2327 tdg = tdq->tdq_group;
2328 tdg->tdg_idlemask |= PCPU_GET(cpumask);
2329 if (tdg->tdg_idlemask == tdg->tdg_cpumask)
2330 atomic_set_int(&tdq_idle, tdg->tdg_mask);
2331 tdq->tdq_lowpri = PRI_MAX_IDLE;
2333 return (PCPU_GET(idlethread));
2337 * Set owepreempt if necessary. Preemption never happens directly in ULE,
2338 * we always request it once we exit a critical section.
2341 sched_setpreempt(struct thread *td)
2348 pri = td->td_priority;
2349 cpri = ctd->td_priority;
2350 if (td->td_priority < ctd->td_priority)
2351 curthread->td_flags |= TDF_NEEDRESCHED;
2352 if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2355 * Always preempt IDLE threads. Otherwise only if the preempting
2356 * thread is an ithread.
2358 if (pri > preempt_thresh && cpri < PRI_MIN_IDLE)
2360 ctd->td_owepreempt = 1;
2365 * Add a thread to a thread queue. Initializes priority, slice, runq, and
2366 * add it to the appropriate queue. This is the internal function called
2367 * when the tdq is predetermined.
2370 tdq_add(struct tdq *tdq, struct thread *td, int flags)
2372 struct td_sched *ts;
2378 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2379 KASSERT((td->td_inhibitors == 0),
2380 ("sched_add: trying to run inhibited thread"));
2381 KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2382 ("sched_add: bad thread state"));
2383 KASSERT(td->td_flags & TDF_INMEM,
2384 ("sched_add: thread swapped out"));
2387 class = PRI_BASE(td->td_pri_class);
2389 if (ts->ts_slice == 0)
2390 ts->ts_slice = sched_slice;
2392 * Pick the run queue based on priority.
2394 if (td->td_priority <= PRI_MAX_REALTIME)
2395 ts->ts_runq = &tdq->tdq_realtime;
2396 else if (td->td_priority <= PRI_MAX_TIMESHARE)
2397 ts->ts_runq = &tdq->tdq_timeshare;
2399 ts->ts_runq = &tdq->tdq_idle;
2401 cpumask = 1 << ts->ts_cpu;
2403 * If we had been idle, clear our bit in the group and potentially
2404 * the global bitmap.
2406 if ((class != PRI_IDLE && class != PRI_ITHD) &&
2407 (tdq->tdq_group->tdg_idlemask & cpumask) != 0) {
2409 * Check to see if our group is unidling, and if so, remove it
2410 * from the global idle mask.
2412 if (tdq->tdq_group->tdg_idlemask ==
2413 tdq->tdq_group->tdg_cpumask)
2414 atomic_clear_int(&tdq_idle, tdq->tdq_group->tdg_mask);
2416 * Now remove ourselves from the group specific idle mask.
2418 tdq->tdq_group->tdg_idlemask &= ~cpumask;
2420 if (td->td_priority < tdq->tdq_lowpri)
2421 tdq->tdq_lowpri = td->td_priority;
2423 tdq_runq_add(tdq, ts, flags);
2424 tdq_load_add(tdq, ts);
2428 * Select the target thread queue and add a thread to it. Request
2429 * preemption or IPI a remote processor if required.
2432 sched_add(struct thread *td, int flags)
2434 struct td_sched *ts;
2440 CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
2441 td, td->td_proc->p_comm, td->td_priority, curthread,
2442 curthread->td_proc->p_comm);
2443 THREAD_LOCK_ASSERT(td, MA_OWNED);
2446 * Recalculate the priority before we select the target cpu or
2449 if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2452 cpuid = PCPU_GET(cpuid);
2454 * Pick the destination cpu and if it isn't ours transfer to the
2457 if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_MIGRATE(td) &&
2458 curthread->td_intr_nesting_level)
2460 if (!THREAD_CAN_MIGRATE(td))
2463 cpu = sched_pickcpu(td, flags);
2464 tdq = sched_setcpu(ts, cpu, flags);
2465 tdq_add(tdq, td, flags);
2474 * Now that the thread is moving to the run-queue, set the lock
2475 * to the scheduler's lock.
2477 thread_lock_set(td, TDQ_LOCKPTR(tdq));
2478 tdq_add(tdq, td, flags);
2480 if (!(flags & SRQ_YIELDING))
2481 sched_setpreempt(td);
2485 * Remove a thread from a run-queue without running it. This is used
2486 * when we're stealing a thread from a remote queue. Otherwise all threads
2487 * exit by calling sched_exit_thread() and sched_throw() themselves.
2490 sched_rem(struct thread *td)
2493 struct td_sched *ts;
2495 CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
2496 td, td->td_proc->p_comm, td->td_priority, curthread,
2497 curthread->td_proc->p_comm);
2499 tdq = TDQ_CPU(ts->ts_cpu);
2500 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2501 MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2502 KASSERT(TD_ON_RUNQ(td),
2503 ("sched_rem: thread not on run queue"));
2504 tdq_runq_rem(tdq, ts);
2505 tdq_load_rem(tdq, ts);
2510 * Fetch cpu utilization information. Updates on demand.
2513 sched_pctcpu(struct thread *td)
2516 struct td_sched *ts;
2527 sched_pctcpu_update(ts);
2528 /* How many rtick per second ? */
2529 rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2530 pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2538 * Enforce affinity settings for a thread. Called after adjustments to
2542 sched_affinity(struct thread *td)
2545 struct td_sched *ts;
2548 THREAD_LOCK_ASSERT(td, MA_OWNED);
2550 if (THREAD_CAN_SCHED(td, ts->ts_cpu))
2552 if (TD_ON_RUNQ(td)) {
2554 sched_add(td, SRQ_BORING);
2557 if (!TD_IS_RUNNING(td))
2559 td->td_flags |= TDF_NEEDRESCHED;
2560 if (!THREAD_CAN_MIGRATE(td))
2563 * Assign the new cpu and force a switch before returning to
2564 * userspace. If the target thread is not running locally send
2565 * an ipi to force the issue.
2568 ts->ts_cpu = sched_pickcpu(td, 0);
2569 if (cpu != PCPU_GET(cpuid))
2570 ipi_selected(1 << cpu, IPI_PREEMPT);
2575 * Bind a thread to a target cpu.
2578 sched_bind(struct thread *td, int cpu)
2580 struct td_sched *ts;
2582 THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2584 if (ts->ts_flags & TSF_BOUND)
2586 ts->ts_flags |= TSF_BOUND;
2589 if (PCPU_GET(cpuid) == cpu)
2592 /* When we return from mi_switch we'll be on the correct cpu. */
2593 mi_switch(SW_VOL, NULL);
2598 * Release a bound thread.
2601 sched_unbind(struct thread *td)
2603 struct td_sched *ts;
2605 THREAD_LOCK_ASSERT(td, MA_OWNED);
2607 if ((ts->ts_flags & TSF_BOUND) == 0)
2609 ts->ts_flags &= ~TSF_BOUND;
2616 sched_is_bound(struct thread *td)
2618 THREAD_LOCK_ASSERT(td, MA_OWNED);
2619 return (td->td_sched->ts_flags & TSF_BOUND);
2626 sched_relinquish(struct thread *td)
2629 SCHED_STAT_INC(switch_relinquish);
2630 mi_switch(SW_VOL, NULL);
2635 * Return the total system load.
2645 for (i = 0; i <= tdg_maxid; i++)
2646 total += TDQ_GROUP(i)->tdg_load;
2649 return (TDQ_SELF()->tdq_sysload);
2654 sched_sizeof_proc(void)
2656 return (sizeof(struct proc));
2660 sched_sizeof_thread(void)
2662 return (sizeof(struct thread) + sizeof(struct td_sched));
2666 * The actual idle process.
2669 sched_idletd(void *dummy)
2676 mtx_assert(&Giant, MA_NOTOWNED);
2677 /* ULE relies on preemption for idle interruption. */
2689 * A CPU is entering for the first time or a thread is exiting.
2692 sched_throw(struct thread *td)
2694 struct thread *newtd;
2699 /* Correct spinlock nesting and acquire the correct lock. */
2703 MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2704 tdq_load_rem(tdq, td->td_sched);
2706 KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2707 newtd = choosethread();
2708 TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
2709 PCPU_SET(switchtime, cpu_ticks());
2710 PCPU_SET(switchticks, ticks);
2711 cpu_throw(td, newtd); /* doesn't return */
2715 * This is called from fork_exit(). Just acquire the correct locks and
2716 * let fork do the rest of the work.
2719 sched_fork_exit(struct thread *td)
2721 struct td_sched *ts;
2726 * Finish setting up thread glue so that it begins execution in a
2727 * non-nested critical section with the scheduler lock held.
2729 cpuid = PCPU_GET(cpuid);
2730 tdq = TDQ_CPU(cpuid);
2732 if (TD_IS_IDLETHREAD(td))
2733 td->td_lock = TDQ_LOCKPTR(tdq);
2734 MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2735 td->td_oncpu = cpuid;
2736 TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2739 static SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0,
2741 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2743 SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2744 "Slice size for timeshare threads");
2745 SYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2746 "Interactivity score threshold");
2747 SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh,
2748 0,"Min priority for preemption, lower priorities have greater precedence");
2750 SYSCTL_INT(_kern_sched, OID_AUTO, pick_pri, CTLFLAG_RW, &pick_pri, 0,
2751 "Pick the target cpu based on priority rather than load.");
2752 SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2753 "Number of hz ticks to keep thread affinity for");
2754 SYSCTL_INT(_kern_sched, OID_AUTO, tryself, CTLFLAG_RW, &tryself, 0, "");
2755 SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2756 "Enables the long-term load balancer");
2757 SYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
2758 &balance_interval, 0,
2759 "Average frequency in stathz ticks to run the long-term balancer");
2760 SYSCTL_INT(_kern_sched, OID_AUTO, steal_htt, CTLFLAG_RW, &steal_htt, 0,
2761 "Steals work from another hyper-threaded core on idle");
2762 SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2763 "Attempts to steal work from other cores before idling");
2764 SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2765 "Minimum load on remote cpu before we'll steal");
2766 SYSCTL_INT(_kern_sched, OID_AUTO, topology, CTLFLAG_RD, &topology, 0,
2767 "True when a topology has been specified by the MD code.");
2770 /* ps compat. All cpu percentages from ULE are weighted. */
2771 static int ccpu = 0;
2772 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2775 #define KERN_SWITCH_INCLUDE 1
2776 #include "kern/kern_switch.c"