1 /*- 2 * Copyright (c) 2002-2007, 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 /* 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. 31 * 32 * etymology: 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. 36 */ 37 38 #include <sys/cdefs.h> 39 __FBSDID("$FreeBSD$"); 40 41 #include "opt_hwpmc_hooks.h" 42 #include "opt_sched.h" 43 44 #include <sys/param.h> 45 #include <sys/systm.h> 46 #include <sys/kdb.h> 47 #include <sys/kernel.h> 48 #include <sys/ktr.h> 49 #include <sys/lock.h> 50 #include <sys/mutex.h> 51 #include <sys/proc.h> 52 #include <sys/resource.h> 53 #include <sys/resourcevar.h> 54 #include <sys/sched.h> 55 #include <sys/smp.h> 56 #include <sys/sx.h> 57 #include <sys/sysctl.h> 58 #include <sys/sysproto.h> 59 #include <sys/turnstile.h> 60 #include <sys/umtx.h> 61 #include <sys/vmmeter.h> 62 #include <sys/cpuset.h> 63 #ifdef KTRACE 64 #include <sys/uio.h> 65 #include <sys/ktrace.h> 66 #endif 67 68 #ifdef HWPMC_HOOKS 69 #include <sys/pmckern.h> 70 #endif 71 72 #include <machine/cpu.h> 73 #include <machine/smp.h> 74 75 #if !defined(__i386__) && !defined(__amd64__) && !defined(__powerpc__) && !defined(__arm__) 76 #error "This architecture is not currently compatible with ULE" 77 #endif 78 79 #define KTR_ULE 0 80 81 /* 82 * Thread scheduler specific section. All fields are protected 83 * by the thread lock. 84 */ 85 struct td_sched { 86 TAILQ_ENTRY(td_sched) ts_procq; /* Run queue. */ 87 struct thread *ts_thread; /* Active associated thread. */ 88 struct runq *ts_runq; /* Run-queue we're queued on. */ 89 short ts_flags; /* TSF_* flags. */ 90 u_char ts_rqindex; /* Run queue index. */ 91 u_char ts_cpu; /* CPU that we have affinity for. */ 92 int ts_rltick; /* Real last tick, for affinity. */ 93 int ts_slice; /* Ticks of slice remaining. */ 94 u_int ts_slptime; /* Number of ticks we vol. slept */ 95 u_int ts_runtime; /* Number of ticks we were running */ 96 int ts_ltick; /* Last tick that we were running on */ 97 int ts_ftick; /* First tick that we were running on */ 98 int ts_ticks; /* Tick count */ 99 }; 100 /* flags kept in ts_flags */ 101 #define TSF_BOUND 0x0001 /* Thread can not migrate. */ 102 #define TSF_XFERABLE 0x0002 /* Thread was added as transferable. */ 103 104 static struct td_sched td_sched0; 105 106 #define THREAD_CAN_MIGRATE(td) ((td)->td_pinned == 0) 107 #define THREAD_CAN_SCHED(td, cpu) \ 108 CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask) 109 110 /* 111 * Cpu percentage computation macros and defines. 112 * 113 * SCHED_TICK_SECS: Number of seconds to average the cpu usage across. 114 * SCHED_TICK_TARG: Number of hz ticks to average the cpu usage across. 115 * SCHED_TICK_MAX: Maximum number of ticks before scaling back. 116 * SCHED_TICK_SHIFT: Shift factor to avoid rounding away results. 117 * SCHED_TICK_HZ: Compute the number of hz ticks for a given ticks count. 118 * SCHED_TICK_TOTAL: Gives the amount of time we've been recording ticks. 119 */ 120 #define SCHED_TICK_SECS 10 121 #define SCHED_TICK_TARG (hz * SCHED_TICK_SECS) 122 #define SCHED_TICK_MAX (SCHED_TICK_TARG + hz) 123 #define SCHED_TICK_SHIFT 10 124 #define SCHED_TICK_HZ(ts) ((ts)->ts_ticks >> SCHED_TICK_SHIFT) 125 #define SCHED_TICK_TOTAL(ts) (max((ts)->ts_ltick - (ts)->ts_ftick, hz)) 126 127 /* 128 * These macros determine priorities for non-interactive threads. They are 129 * assigned a priority based on their recent cpu utilization as expressed 130 * by the ratio of ticks to the tick total. NHALF priorities at the start 131 * and end of the MIN to MAX timeshare range are only reachable with negative 132 * or positive nice respectively. 133 * 134 * PRI_RANGE: Priority range for utilization dependent priorities. 135 * PRI_NRESV: Number of nice values. 136 * PRI_TICKS: Compute a priority in PRI_RANGE from the ticks count and total. 137 * PRI_NICE: Determines the part of the priority inherited from nice. 138 */ 139 #define SCHED_PRI_NRESV (PRIO_MAX - PRIO_MIN) 140 #define SCHED_PRI_NHALF (SCHED_PRI_NRESV / 2) 141 #define SCHED_PRI_MIN (PRI_MIN_TIMESHARE + SCHED_PRI_NHALF) 142 #define SCHED_PRI_MAX (PRI_MAX_TIMESHARE - SCHED_PRI_NHALF) 143 #define SCHED_PRI_RANGE (SCHED_PRI_MAX - SCHED_PRI_MIN) 144 #define SCHED_PRI_TICKS(ts) \ 145 (SCHED_TICK_HZ((ts)) / \ 146 (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE)) 147 #define SCHED_PRI_NICE(nice) (nice) 148 149 /* 150 * These determine the interactivity of a process. Interactivity differs from 151 * cpu utilization in that it expresses the voluntary time slept vs time ran 152 * while cpu utilization includes all time not running. This more accurately 153 * models the intent of the thread. 154 * 155 * SLP_RUN_MAX: Maximum amount of sleep time + run time we'll accumulate 156 * before throttling back. 157 * SLP_RUN_FORK: Maximum slp+run time to inherit at fork time. 158 * INTERACT_MAX: Maximum interactivity value. Smaller is better. 159 * INTERACT_THRESH: Threshhold for placement on the current runq. 160 */ 161 #define SCHED_SLP_RUN_MAX ((hz * 5) << SCHED_TICK_SHIFT) 162 #define SCHED_SLP_RUN_FORK ((hz / 2) << SCHED_TICK_SHIFT) 163 #define SCHED_INTERACT_MAX (100) 164 #define SCHED_INTERACT_HALF (SCHED_INTERACT_MAX / 2) 165 #define SCHED_INTERACT_THRESH (30) 166 167 /* 168 * tickincr: Converts a stathz tick into a hz domain scaled by 169 * the shift factor. Without the shift the error rate 170 * due to rounding would be unacceptably high. 171 * realstathz: stathz is sometimes 0 and run off of hz. 172 * sched_slice: Runtime of each thread before rescheduling. 173 * preempt_thresh: Priority threshold for preemption and remote IPIs. 174 */ 175 static int sched_interact = SCHED_INTERACT_THRESH; 176 static int realstathz; 177 static int tickincr; 178 static int sched_slice = 1; 179 #ifdef PREEMPTION 180 #ifdef FULL_PREEMPTION 181 static int preempt_thresh = PRI_MAX_IDLE; 182 #else 183 static int preempt_thresh = PRI_MIN_KERN; 184 #endif 185 #else 186 static int preempt_thresh = 0; 187 #endif 188 static int static_boost = 1; 189 190 /* 191 * tdq - per processor runqs and statistics. All fields are protected by the 192 * tdq_lock. The load and lowpri may be accessed without to avoid excess 193 * locking in sched_pickcpu(); 194 */ 195 struct tdq { 196 /* Ordered to improve efficiency of cpu_search() and switch(). */ 197 struct mtx tdq_lock; /* run queue lock. */ 198 struct cpu_group *tdq_cg; /* Pointer to cpu topology. */ 199 int tdq_load; /* Aggregate load. */ 200 int tdq_sysload; /* For loadavg, !ITHD load. */ 201 int tdq_transferable; /* Transferable thread count. */ 202 u_char tdq_lowpri; /* Lowest priority thread. */ 203 u_char tdq_ipipending; /* IPI pending. */ 204 u_char tdq_idx; /* Current insert index. */ 205 u_char tdq_ridx; /* Current removal index. */ 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 char tdq_name[sizeof("sched lock") + 6]; 210 } __aligned(64); 211 212 213 #ifdef SMP 214 struct cpu_group *cpu_top; 215 216 #define SCHED_AFFINITY_DEFAULT (max(1, hz / 1000)) 217 #define SCHED_AFFINITY(ts, t) ((ts)->ts_rltick > ticks - ((t) * affinity)) 218 219 /* 220 * Run-time tunables. 221 */ 222 static int rebalance = 1; 223 static int balance_interval = 128; /* Default set in sched_initticks(). */ 224 static int affinity; 225 static int steal_htt = 1; 226 static int steal_idle = 1; 227 static int steal_thresh = 2; 228 229 /* 230 * One thread queue per processor. 231 */ 232 static struct tdq tdq_cpu[MAXCPU]; 233 static struct tdq *balance_tdq; 234 static int balance_ticks; 235 236 #define TDQ_SELF() (&tdq_cpu[PCPU_GET(cpuid)]) 237 #define TDQ_CPU(x) (&tdq_cpu[(x)]) 238 #define TDQ_ID(x) ((int)((x) - tdq_cpu)) 239 #else /* !SMP */ 240 static struct tdq tdq_cpu; 241 242 #define TDQ_ID(x) (0) 243 #define TDQ_SELF() (&tdq_cpu) 244 #define TDQ_CPU(x) (&tdq_cpu) 245 #endif 246 247 #define TDQ_LOCK_ASSERT(t, type) mtx_assert(TDQ_LOCKPTR((t)), (type)) 248 #define TDQ_LOCK(t) mtx_lock_spin(TDQ_LOCKPTR((t))) 249 #define TDQ_LOCK_FLAGS(t, f) mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f)) 250 #define TDQ_UNLOCK(t) mtx_unlock_spin(TDQ_LOCKPTR((t))) 251 #define TDQ_LOCKPTR(t) (&(t)->tdq_lock) 252 253 static void sched_priority(struct thread *); 254 static void sched_thread_priority(struct thread *, u_char); 255 static int sched_interact_score(struct thread *); 256 static void sched_interact_update(struct thread *); 257 static void sched_interact_fork(struct thread *); 258 static void sched_pctcpu_update(struct td_sched *); 259 260 /* Operations on per processor queues */ 261 static struct td_sched * tdq_choose(struct tdq *); 262 static void tdq_setup(struct tdq *); 263 static void tdq_load_add(struct tdq *, struct td_sched *); 264 static void tdq_load_rem(struct tdq *, struct td_sched *); 265 static __inline void tdq_runq_add(struct tdq *, struct td_sched *, int); 266 static __inline void tdq_runq_rem(struct tdq *, struct td_sched *); 267 static inline int sched_shouldpreempt(int, int, int); 268 void tdq_print(int cpu); 269 static void runq_print(struct runq *rq); 270 static void tdq_add(struct tdq *, struct thread *, int); 271 #ifdef SMP 272 static int tdq_move(struct tdq *, struct tdq *); 273 static int tdq_idled(struct tdq *); 274 static void tdq_notify(struct tdq *, struct td_sched *); 275 static struct td_sched *tdq_steal(struct tdq *, int); 276 static struct td_sched *runq_steal(struct runq *, int); 277 static int sched_pickcpu(struct td_sched *, int); 278 static void sched_balance(void); 279 static int sched_balance_pair(struct tdq *, struct tdq *); 280 static inline struct tdq *sched_setcpu(struct td_sched *, int, int); 281 static inline struct mtx *thread_block_switch(struct thread *); 282 static inline void thread_unblock_switch(struct thread *, struct mtx *); 283 static struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int); 284 #endif 285 286 static void sched_setup(void *dummy); 287 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL); 288 289 static void sched_initticks(void *dummy); 290 SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks, 291 NULL); 292 293 /* 294 * Print the threads waiting on a run-queue. 295 */ 296 static void 297 runq_print(struct runq *rq) 298 { 299 struct rqhead *rqh; 300 struct td_sched *ts; 301 int pri; 302 int j; 303 int i; 304 305 for (i = 0; i < RQB_LEN; i++) { 306 printf("\t\trunq bits %d 0x%zx\n", 307 i, rq->rq_status.rqb_bits[i]); 308 for (j = 0; j < RQB_BPW; j++) 309 if (rq->rq_status.rqb_bits[i] & (1ul << j)) { 310 pri = j + (i << RQB_L2BPW); 311 rqh = &rq->rq_queues[pri]; 312 TAILQ_FOREACH(ts, rqh, ts_procq) { 313 printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n", 314 ts->ts_thread, ts->ts_thread->td_name, ts->ts_thread->td_priority, ts->ts_rqindex, pri); 315 } 316 } 317 } 318 } 319 320 /* 321 * Print the status of a per-cpu thread queue. Should be a ddb show cmd. 322 */ 323 void 324 tdq_print(int cpu) 325 { 326 struct tdq *tdq; 327 328 tdq = TDQ_CPU(cpu); 329 330 printf("tdq %d:\n", TDQ_ID(tdq)); 331 printf("\tlock %p\n", TDQ_LOCKPTR(tdq)); 332 printf("\tLock name: %s\n", tdq->tdq_name); 333 printf("\tload: %d\n", tdq->tdq_load); 334 printf("\ttimeshare idx: %d\n", tdq->tdq_idx); 335 printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx); 336 printf("\trealtime runq:\n"); 337 runq_print(&tdq->tdq_realtime); 338 printf("\ttimeshare runq:\n"); 339 runq_print(&tdq->tdq_timeshare); 340 printf("\tidle runq:\n"); 341 runq_print(&tdq->tdq_idle); 342 printf("\tload transferable: %d\n", tdq->tdq_transferable); 343 printf("\tlowest priority: %d\n", tdq->tdq_lowpri); 344 } 345 346 static inline int 347 sched_shouldpreempt(int pri, int cpri, int remote) 348 { 349 /* 350 * If the new priority is not better than the current priority there is 351 * nothing to do. 352 */ 353 if (pri >= cpri) 354 return (0); 355 /* 356 * Always preempt idle. 357 */ 358 if (cpri >= PRI_MIN_IDLE) 359 return (1); 360 /* 361 * If preemption is disabled don't preempt others. 362 */ 363 if (preempt_thresh == 0) 364 return (0); 365 /* 366 * Preempt if we exceed the threshold. 367 */ 368 if (pri <= preempt_thresh) 369 return (1); 370 /* 371 * If we're realtime or better and there is timeshare or worse running 372 * preempt only remote processors. 373 */ 374 if (remote && pri <= PRI_MAX_REALTIME && cpri > PRI_MAX_REALTIME) 375 return (1); 376 return (0); 377 } 378 379 #define TS_RQ_PPQ (((PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE) + 1) / RQ_NQS) 380 /* 381 * Add a thread to the actual run-queue. Keeps transferable counts up to 382 * date with what is actually on the run-queue. Selects the correct 383 * queue position for timeshare threads. 384 */ 385 static __inline void 386 tdq_runq_add(struct tdq *tdq, struct td_sched *ts, int flags) 387 { 388 u_char pri; 389 390 TDQ_LOCK_ASSERT(tdq, MA_OWNED); 391 THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED); 392 393 TD_SET_RUNQ(ts->ts_thread); 394 if (THREAD_CAN_MIGRATE(ts->ts_thread)) { 395 tdq->tdq_transferable++; 396 ts->ts_flags |= TSF_XFERABLE; 397 } 398 pri = ts->ts_thread->td_priority; 399 if (pri <= PRI_MAX_REALTIME) { 400 ts->ts_runq = &tdq->tdq_realtime; 401 } else if (pri <= PRI_MAX_TIMESHARE) { 402 ts->ts_runq = &tdq->tdq_timeshare; 403 KASSERT(pri <= PRI_MAX_TIMESHARE && pri >= PRI_MIN_TIMESHARE, 404 ("Invalid priority %d on timeshare runq", pri)); 405 /* 406 * This queue contains only priorities between MIN and MAX 407 * realtime. Use the whole queue to represent these values. 408 */ 409 if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) { 410 pri = (pri - PRI_MIN_TIMESHARE) / TS_RQ_PPQ; 411 pri = (pri + tdq->tdq_idx) % RQ_NQS; 412 /* 413 * This effectively shortens the queue by one so we 414 * can have a one slot difference between idx and 415 * ridx while we wait for threads to drain. 416 */ 417 if (tdq->tdq_ridx != tdq->tdq_idx && 418 pri == tdq->tdq_ridx) 419 pri = (unsigned char)(pri - 1) % RQ_NQS; 420 } else 421 pri = tdq->tdq_ridx; 422 runq_add_pri(ts->ts_runq, ts, pri, flags); 423 return; 424 } else 425 ts->ts_runq = &tdq->tdq_idle; 426 runq_add(ts->ts_runq, ts, flags); 427 } 428 429 /* 430 * Remove a thread from a run-queue. This typically happens when a thread 431 * is selected to run. Running threads are not on the queue and the 432 * transferable count does not reflect them. 433 */ 434 static __inline void 435 tdq_runq_rem(struct tdq *tdq, struct td_sched *ts) 436 { 437 TDQ_LOCK_ASSERT(tdq, MA_OWNED); 438 KASSERT(ts->ts_runq != NULL, 439 ("tdq_runq_remove: thread %p null ts_runq", ts->ts_thread)); 440 if (ts->ts_flags & TSF_XFERABLE) { 441 tdq->tdq_transferable--; 442 ts->ts_flags &= ~TSF_XFERABLE; 443 } 444 if (ts->ts_runq == &tdq->tdq_timeshare) { 445 if (tdq->tdq_idx != tdq->tdq_ridx) 446 runq_remove_idx(ts->ts_runq, ts, &tdq->tdq_ridx); 447 else 448 runq_remove_idx(ts->ts_runq, ts, NULL); 449 } else 450 runq_remove(ts->ts_runq, ts); 451 } 452 453 /* 454 * Load is maintained for all threads RUNNING and ON_RUNQ. Add the load 455 * for this thread to the referenced thread queue. 456 */ 457 static void 458 tdq_load_add(struct tdq *tdq, struct td_sched *ts) 459 { 460 int class; 461 462 TDQ_LOCK_ASSERT(tdq, MA_OWNED); 463 THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED); 464 class = PRI_BASE(ts->ts_thread->td_pri_class); 465 tdq->tdq_load++; 466 CTR2(KTR_SCHED, "cpu %d load: %d", TDQ_ID(tdq), tdq->tdq_load); 467 if (class != PRI_ITHD && 468 (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0) 469 tdq->tdq_sysload++; 470 } 471 472 /* 473 * Remove the load from a thread that is transitioning to a sleep state or 474 * exiting. 475 */ 476 static void 477 tdq_load_rem(struct tdq *tdq, struct td_sched *ts) 478 { 479 int class; 480 481 THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED); 482 TDQ_LOCK_ASSERT(tdq, MA_OWNED); 483 class = PRI_BASE(ts->ts_thread->td_pri_class); 484 if (class != PRI_ITHD && 485 (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0) 486 tdq->tdq_sysload--; 487 KASSERT(tdq->tdq_load != 0, 488 ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq))); 489 tdq->tdq_load--; 490 CTR1(KTR_SCHED, "load: %d", tdq->tdq_load); 491 } 492 493 /* 494 * Set lowpri to its exact value by searching the run-queue and 495 * evaluating curthread. curthread may be passed as an optimization. 496 */ 497 static void 498 tdq_setlowpri(struct tdq *tdq, struct thread *ctd) 499 { 500 struct td_sched *ts; 501 struct thread *td; 502 503 TDQ_LOCK_ASSERT(tdq, MA_OWNED); 504 if (ctd == NULL) 505 ctd = pcpu_find(TDQ_ID(tdq))->pc_curthread; 506 ts = tdq_choose(tdq); 507 if (ts) 508 td = ts->ts_thread; 509 if (ts == NULL || td->td_priority > ctd->td_priority) 510 tdq->tdq_lowpri = ctd->td_priority; 511 else 512 tdq->tdq_lowpri = td->td_priority; 513 } 514 515 #ifdef SMP 516 struct cpu_search { 517 cpumask_t cs_mask; /* Mask of valid cpus. */ 518 u_int cs_load; 519 u_int cs_cpu; 520 int cs_limit; /* Min priority for low min load for high. */ 521 }; 522 523 #define CPU_SEARCH_LOWEST 0x1 524 #define CPU_SEARCH_HIGHEST 0x2 525 #define CPU_SEARCH_BOTH (CPU_SEARCH_LOWEST|CPU_SEARCH_HIGHEST) 526 527 #define CPUMASK_FOREACH(cpu, mask) \ 528 for ((cpu) = 0; (cpu) < sizeof((mask)) * 8; (cpu)++) \ 529 if ((mask) & 1 << (cpu)) 530 531 static __inline int cpu_search(struct cpu_group *cg, struct cpu_search *low, 532 struct cpu_search *high, const int match); 533 int cpu_search_lowest(struct cpu_group *cg, struct cpu_search *low); 534 int cpu_search_highest(struct cpu_group *cg, struct cpu_search *high); 535 int cpu_search_both(struct cpu_group *cg, struct cpu_search *low, 536 struct cpu_search *high); 537 538 /* 539 * This routine compares according to the match argument and should be 540 * reduced in actual instantiations via constant propagation and dead code 541 * elimination. 542 */ 543 static __inline int 544 cpu_compare(int cpu, struct cpu_search *low, struct cpu_search *high, 545 const int match) 546 { 547 struct tdq *tdq; 548 549 tdq = TDQ_CPU(cpu); 550 if (match & CPU_SEARCH_LOWEST) 551 if (low->cs_mask & (1 << cpu) && 552 tdq->tdq_load < low->cs_load && 553 tdq->tdq_lowpri > low->cs_limit) { 554 low->cs_cpu = cpu; 555 low->cs_load = tdq->tdq_load; 556 } 557 if (match & CPU_SEARCH_HIGHEST) 558 if (high->cs_mask & (1 << cpu) && 559 tdq->tdq_load >= high->cs_limit && 560 tdq->tdq_load > high->cs_load && 561 tdq->tdq_transferable) { 562 high->cs_cpu = cpu; 563 high->cs_load = tdq->tdq_load; 564 } 565 return (tdq->tdq_load); 566 } 567 568 /* 569 * Search the tree of cpu_groups for the lowest or highest loaded cpu 570 * according to the match argument. This routine actually compares the 571 * load on all paths through the tree and finds the least loaded cpu on 572 * the least loaded path, which may differ from the least loaded cpu in 573 * the system. This balances work among caches and busses. 574 * 575 * This inline is instantiated in three forms below using constants for the 576 * match argument. It is reduced to the minimum set for each case. It is 577 * also recursive to the depth of the tree. 578 */ 579 static __inline int 580 cpu_search(struct cpu_group *cg, struct cpu_search *low, 581 struct cpu_search *high, const int match) 582 { 583 int total; 584 585 total = 0; 586 if (cg->cg_children) { 587 struct cpu_search lgroup; 588 struct cpu_search hgroup; 589 struct cpu_group *child; 590 u_int lload; 591 int hload; 592 int load; 593 int i; 594 595 lload = -1; 596 hload = -1; 597 for (i = 0; i < cg->cg_children; i++) { 598 child = &cg->cg_child[i]; 599 if (match & CPU_SEARCH_LOWEST) { 600 lgroup = *low; 601 lgroup.cs_load = -1; 602 } 603 if (match & CPU_SEARCH_HIGHEST) { 604 hgroup = *high; 605 lgroup.cs_load = 0; 606 } 607 switch (match) { 608 case CPU_SEARCH_LOWEST: 609 load = cpu_search_lowest(child, &lgroup); 610 break; 611 case CPU_SEARCH_HIGHEST: 612 load = cpu_search_highest(child, &hgroup); 613 break; 614 case CPU_SEARCH_BOTH: 615 load = cpu_search_both(child, &lgroup, &hgroup); 616 break; 617 } 618 total += load; 619 if (match & CPU_SEARCH_LOWEST) 620 if (load < lload || low->cs_cpu == -1) { 621 *low = lgroup; 622 lload = load; 623 } 624 if (match & CPU_SEARCH_HIGHEST) 625 if (load > hload || high->cs_cpu == -1) { 626 hload = load; 627 *high = hgroup; 628 } 629 } 630 } else { 631 int cpu; 632 633 CPUMASK_FOREACH(cpu, cg->cg_mask) 634 total += cpu_compare(cpu, low, high, match); 635 } 636 return (total); 637 } 638 639 /* 640 * cpu_search instantiations must pass constants to maintain the inline 641 * optimization. 642 */ 643 int 644 cpu_search_lowest(struct cpu_group *cg, struct cpu_search *low) 645 { 646 return cpu_search(cg, low, NULL, CPU_SEARCH_LOWEST); 647 } 648 649 int 650 cpu_search_highest(struct cpu_group *cg, struct cpu_search *high) 651 { 652 return cpu_search(cg, NULL, high, CPU_SEARCH_HIGHEST); 653 } 654 655 int 656 cpu_search_both(struct cpu_group *cg, struct cpu_search *low, 657 struct cpu_search *high) 658 { 659 return cpu_search(cg, low, high, CPU_SEARCH_BOTH); 660 } 661 662 /* 663 * Find the cpu with the least load via the least loaded path that has a 664 * lowpri greater than pri pri. A pri of -1 indicates any priority is 665 * acceptable. 666 */ 667 static inline int 668 sched_lowest(struct cpu_group *cg, cpumask_t mask, int pri) 669 { 670 struct cpu_search low; 671 672 low.cs_cpu = -1; 673 low.cs_load = -1; 674 low.cs_mask = mask; 675 low.cs_limit = pri; 676 cpu_search_lowest(cg, &low); 677 return low.cs_cpu; 678 } 679 680 /* 681 * Find the cpu with the highest load via the highest loaded path. 682 */ 683 static inline int 684 sched_highest(struct cpu_group *cg, cpumask_t mask, int minload) 685 { 686 struct cpu_search high; 687 688 high.cs_cpu = -1; 689 high.cs_load = 0; 690 high.cs_mask = mask; 691 high.cs_limit = minload; 692 cpu_search_highest(cg, &high); 693 return high.cs_cpu; 694 } 695 696 /* 697 * Simultaneously find the highest and lowest loaded cpu reachable via 698 * cg. 699 */ 700 static inline void 701 sched_both(struct cpu_group *cg, cpumask_t mask, int *lowcpu, int *highcpu) 702 { 703 struct cpu_search high; 704 struct cpu_search low; 705 706 low.cs_cpu = -1; 707 low.cs_limit = -1; 708 low.cs_load = -1; 709 low.cs_mask = mask; 710 high.cs_load = 0; 711 high.cs_cpu = -1; 712 high.cs_limit = -1; 713 high.cs_mask = mask; 714 cpu_search_both(cg, &low, &high); 715 *lowcpu = low.cs_cpu; 716 *highcpu = high.cs_cpu; 717 return; 718 } 719 720 static void 721 sched_balance_group(struct cpu_group *cg) 722 { 723 cpumask_t mask; 724 int high; 725 int low; 726 int i; 727 728 mask = -1; 729 for (;;) { 730 sched_both(cg, mask, &low, &high); 731 if (low == high || low == -1 || high == -1) 732 break; 733 if (sched_balance_pair(TDQ_CPU(high), TDQ_CPU(low))) 734 break; 735 /* 736 * If we failed to move any threads determine which cpu 737 * to kick out of the set and try again. 738 */ 739 if (TDQ_CPU(high)->tdq_transferable == 0) 740 mask &= ~(1 << high); 741 else 742 mask &= ~(1 << low); 743 } 744 745 for (i = 0; i < cg->cg_children; i++) 746 sched_balance_group(&cg->cg_child[i]); 747 } 748 749 static void 750 sched_balance() 751 { 752 struct tdq *tdq; 753 754 /* 755 * Select a random time between .5 * balance_interval and 756 * 1.5 * balance_interval. 757 */ 758 balance_ticks = max(balance_interval / 2, 1); 759 balance_ticks += random() % balance_interval; 760 if (smp_started == 0 || rebalance == 0) 761 return; 762 tdq = TDQ_SELF(); 763 TDQ_UNLOCK(tdq); 764 sched_balance_group(cpu_top); 765 TDQ_LOCK(tdq); 766 } 767 768 /* 769 * Lock two thread queues using their address to maintain lock order. 770 */ 771 static void 772 tdq_lock_pair(struct tdq *one, struct tdq *two) 773 { 774 if (one < two) { 775 TDQ_LOCK(one); 776 TDQ_LOCK_FLAGS(two, MTX_DUPOK); 777 } else { 778 TDQ_LOCK(two); 779 TDQ_LOCK_FLAGS(one, MTX_DUPOK); 780 } 781 } 782 783 /* 784 * Unlock two thread queues. Order is not important here. 785 */ 786 static void 787 tdq_unlock_pair(struct tdq *one, struct tdq *two) 788 { 789 TDQ_UNLOCK(one); 790 TDQ_UNLOCK(two); 791 } 792 793 /* 794 * Transfer load between two imbalanced thread queues. 795 */ 796 static int 797 sched_balance_pair(struct tdq *high, struct tdq *low) 798 { 799 int transferable; 800 int high_load; 801 int low_load; 802 int moved; 803 int move; 804 int diff; 805 int i; 806 807 tdq_lock_pair(high, low); 808 transferable = high->tdq_transferable; 809 high_load = high->tdq_load; 810 low_load = low->tdq_load; 811 moved = 0; 812 /* 813 * Determine what the imbalance is and then adjust that to how many 814 * threads we actually have to give up (transferable). 815 */ 816 if (transferable != 0) { 817 diff = high_load - low_load; 818 move = diff / 2; 819 if (diff & 0x1) 820 move++; 821 move = min(move, transferable); 822 for (i = 0; i < move; i++) 823 moved += tdq_move(high, low); 824 /* 825 * IPI the target cpu to force it to reschedule with the new 826 * workload. 827 */ 828 ipi_selected(1 << TDQ_ID(low), IPI_PREEMPT); 829 } 830 tdq_unlock_pair(high, low); 831 return (moved); 832 } 833 834 /* 835 * Move a thread from one thread queue to another. 836 */ 837 static int 838 tdq_move(struct tdq *from, struct tdq *to) 839 { 840 struct td_sched *ts; 841 struct thread *td; 842 struct tdq *tdq; 843 int cpu; 844 845 TDQ_LOCK_ASSERT(from, MA_OWNED); 846 TDQ_LOCK_ASSERT(to, MA_OWNED); 847 848 tdq = from; 849 cpu = TDQ_ID(to); 850 ts = tdq_steal(tdq, cpu); 851 if (ts == NULL) 852 return (0); 853 td = ts->ts_thread; 854 /* 855 * Although the run queue is locked the thread may be blocked. Lock 856 * it to clear this and acquire the run-queue lock. 857 */ 858 thread_lock(td); 859 /* Drop recursive lock on from acquired via thread_lock(). */ 860 TDQ_UNLOCK(from); 861 sched_rem(td); 862 ts->ts_cpu = cpu; 863 td->td_lock = TDQ_LOCKPTR(to); 864 tdq_add(to, td, SRQ_YIELDING); 865 return (1); 866 } 867 868 /* 869 * This tdq has idled. Try to steal a thread from another cpu and switch 870 * to it. 871 */ 872 static int 873 tdq_idled(struct tdq *tdq) 874 { 875 struct cpu_group *cg; 876 struct tdq *steal; 877 cpumask_t mask; 878 int thresh; 879 int cpu; 880 881 if (smp_started == 0 || steal_idle == 0) 882 return (1); 883 mask = -1; 884 mask &= ~PCPU_GET(cpumask); 885 /* We don't want to be preempted while we're iterating. */ 886 spinlock_enter(); 887 for (cg = tdq->tdq_cg; cg != NULL; ) { 888 if ((cg->cg_flags & (CG_FLAG_HTT | CG_FLAG_THREAD)) == 0) 889 thresh = steal_thresh; 890 else 891 thresh = 1; 892 cpu = sched_highest(cg, mask, thresh); 893 if (cpu == -1) { 894 cg = cg->cg_parent; 895 continue; 896 } 897 steal = TDQ_CPU(cpu); 898 mask &= ~(1 << cpu); 899 tdq_lock_pair(tdq, steal); 900 if (steal->tdq_load < thresh || steal->tdq_transferable == 0) { 901 tdq_unlock_pair(tdq, steal); 902 continue; 903 } 904 /* 905 * If a thread was added while interrupts were disabled don't 906 * steal one here. If we fail to acquire one due to affinity 907 * restrictions loop again with this cpu removed from the 908 * set. 909 */ 910 if (tdq->tdq_load == 0 && tdq_move(steal, tdq) == 0) { 911 tdq_unlock_pair(tdq, steal); 912 continue; 913 } 914 spinlock_exit(); 915 TDQ_UNLOCK(steal); 916 mi_switch(SW_VOL, NULL); 917 thread_unlock(curthread); 918 919 return (0); 920 } 921 spinlock_exit(); 922 return (1); 923 } 924 925 /* 926 * Notify a remote cpu of new work. Sends an IPI if criteria are met. 927 */ 928 static void 929 tdq_notify(struct tdq *tdq, struct td_sched *ts) 930 { 931 int cpri; 932 int pri; 933 int cpu; 934 935 if (tdq->tdq_ipipending) 936 return; 937 cpu = ts->ts_cpu; 938 pri = ts->ts_thread->td_priority; 939 cpri = pcpu_find(cpu)->pc_curthread->td_priority; 940 if (!sched_shouldpreempt(pri, cpri, 1)) 941 return; 942 tdq->tdq_ipipending = 1; 943 ipi_selected(1 << cpu, IPI_PREEMPT); 944 } 945 946 /* 947 * Steals load from a timeshare queue. Honors the rotating queue head 948 * index. 949 */ 950 static struct td_sched * 951 runq_steal_from(struct runq *rq, int cpu, u_char start) 952 { 953 struct td_sched *ts; 954 struct rqbits *rqb; 955 struct rqhead *rqh; 956 int first; 957 int bit; 958 int pri; 959 int i; 960 961 rqb = &rq->rq_status; 962 bit = start & (RQB_BPW -1); 963 pri = 0; 964 first = 0; 965 again: 966 for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) { 967 if (rqb->rqb_bits[i] == 0) 968 continue; 969 if (bit != 0) { 970 for (pri = bit; pri < RQB_BPW; pri++) 971 if (rqb->rqb_bits[i] & (1ul << pri)) 972 break; 973 if (pri >= RQB_BPW) 974 continue; 975 } else 976 pri = RQB_FFS(rqb->rqb_bits[i]); 977 pri += (i << RQB_L2BPW); 978 rqh = &rq->rq_queues[pri]; 979 TAILQ_FOREACH(ts, rqh, ts_procq) { 980 if (first && THREAD_CAN_MIGRATE(ts->ts_thread) && 981 THREAD_CAN_SCHED(ts->ts_thread, cpu)) 982 return (ts); 983 first = 1; 984 } 985 } 986 if (start != 0) { 987 start = 0; 988 goto again; 989 } 990 991 return (NULL); 992 } 993 994 /* 995 * Steals load from a standard linear queue. 996 */ 997 static struct td_sched * 998 runq_steal(struct runq *rq, int cpu) 999 { 1000 struct rqhead *rqh; 1001 struct rqbits *rqb; 1002 struct td_sched *ts; 1003 int word; 1004 int bit; 1005 1006 rqb = &rq->rq_status; 1007 for (word = 0; word < RQB_LEN; word++) { 1008 if (rqb->rqb_bits[word] == 0) 1009 continue; 1010 for (bit = 0; bit < RQB_BPW; bit++) { 1011 if ((rqb->rqb_bits[word] & (1ul << bit)) == 0) 1012 continue; 1013 rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)]; 1014 TAILQ_FOREACH(ts, rqh, ts_procq) 1015 if (THREAD_CAN_MIGRATE(ts->ts_thread) && 1016 THREAD_CAN_SCHED(ts->ts_thread, cpu)) 1017 return (ts); 1018 } 1019 } 1020 return (NULL); 1021 } 1022 1023 /* 1024 * Attempt to steal a thread in priority order from a thread queue. 1025 */ 1026 static struct td_sched * 1027 tdq_steal(struct tdq *tdq, int cpu) 1028 { 1029 struct td_sched *ts; 1030 1031 TDQ_LOCK_ASSERT(tdq, MA_OWNED); 1032 if ((ts = runq_steal(&tdq->tdq_realtime, cpu)) != NULL) 1033 return (ts); 1034 if ((ts = runq_steal_from(&tdq->tdq_timeshare, cpu, tdq->tdq_ridx)) 1035 != NULL) 1036 return (ts); 1037 return (runq_steal(&tdq->tdq_idle, cpu)); 1038 } 1039 1040 /* 1041 * Sets the thread lock and ts_cpu to match the requested cpu. Unlocks the 1042 * current lock and returns with the assigned queue locked. 1043 */ 1044 static inline struct tdq * 1045 sched_setcpu(struct td_sched *ts, int cpu, int flags) 1046 { 1047 struct thread *td; 1048 struct tdq *tdq; 1049 1050 THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED); 1051 1052 tdq = TDQ_CPU(cpu); 1053 td = ts->ts_thread; 1054 ts->ts_cpu = cpu; 1055 1056 /* If the lock matches just return the queue. */ 1057 if (td->td_lock == TDQ_LOCKPTR(tdq)) 1058 return (tdq); 1059 #ifdef notyet 1060 /* 1061 * If the thread isn't running its lockptr is a 1062 * turnstile or a sleepqueue. We can just lock_set without 1063 * blocking. 1064 */ 1065 if (TD_CAN_RUN(td)) { 1066 TDQ_LOCK(tdq); 1067 thread_lock_set(td, TDQ_LOCKPTR(tdq)); 1068 return (tdq); 1069 } 1070 #endif 1071 /* 1072 * The hard case, migration, we need to block the thread first to 1073 * prevent order reversals with other cpus locks. 1074 */ 1075 thread_lock_block(td); 1076 TDQ_LOCK(tdq); 1077 thread_lock_unblock(td, TDQ_LOCKPTR(tdq)); 1078 return (tdq); 1079 } 1080 1081 static int 1082 sched_pickcpu(struct td_sched *ts, int flags) 1083 { 1084 struct cpu_group *cg; 1085 struct thread *td; 1086 struct tdq *tdq; 1087 cpumask_t mask; 1088 int self; 1089 int pri; 1090 int cpu; 1091 1092 self = PCPU_GET(cpuid); 1093 td = ts->ts_thread; 1094 if (smp_started == 0) 1095 return (self); 1096 /* 1097 * Don't migrate a running thread from sched_switch(). 1098 */ 1099 if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td)) 1100 return (ts->ts_cpu); 1101 /* 1102 * Prefer to run interrupt threads on the processors that generate 1103 * the interrupt. 1104 */ 1105 if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) && 1106 curthread->td_intr_nesting_level) 1107 ts->ts_cpu = self; 1108 /* 1109 * If the thread can run on the last cpu and the affinity has not 1110 * expired or it is idle run it there. 1111 */ 1112 pri = td->td_priority; 1113 tdq = TDQ_CPU(ts->ts_cpu); 1114 if (THREAD_CAN_SCHED(td, ts->ts_cpu)) { 1115 if (tdq->tdq_lowpri > PRI_MIN_IDLE) 1116 return (ts->ts_cpu); 1117 if (SCHED_AFFINITY(ts, CG_SHARE_L2) && tdq->tdq_lowpri > pri) 1118 return (ts->ts_cpu); 1119 } 1120 /* 1121 * Search for the highest level in the tree that still has affinity. 1122 */ 1123 cg = NULL; 1124 for (cg = tdq->tdq_cg; cg != NULL; cg = cg->cg_parent) 1125 if (SCHED_AFFINITY(ts, cg->cg_level)) 1126 break; 1127 cpu = -1; 1128 mask = td->td_cpuset->cs_mask.__bits[0]; 1129 if (cg) 1130 cpu = sched_lowest(cg, mask, pri); 1131 if (cpu == -1) 1132 cpu = sched_lowest(cpu_top, mask, -1); 1133 /* 1134 * Compare the lowest loaded cpu to current cpu. 1135 */ 1136 if (THREAD_CAN_SCHED(td, self) && TDQ_CPU(self)->tdq_lowpri > pri && 1137 TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE) 1138 cpu = self; 1139 KASSERT(cpu != -1, ("sched_pickcpu: Failed to find a cpu.")); 1140 return (cpu); 1141 } 1142 #endif 1143 1144 /* 1145 * Pick the highest priority task we have and return it. 1146 */ 1147 static struct td_sched * 1148 tdq_choose(struct tdq *tdq) 1149 { 1150 struct td_sched *ts; 1151 1152 TDQ_LOCK_ASSERT(tdq, MA_OWNED); 1153 ts = runq_choose(&tdq->tdq_realtime); 1154 if (ts != NULL) 1155 return (ts); 1156 ts = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx); 1157 if (ts != NULL) { 1158 KASSERT(ts->ts_thread->td_priority >= PRI_MIN_TIMESHARE, 1159 ("tdq_choose: Invalid priority on timeshare queue %d", 1160 ts->ts_thread->td_priority)); 1161 return (ts); 1162 } 1163 1164 ts = runq_choose(&tdq->tdq_idle); 1165 if (ts != NULL) { 1166 KASSERT(ts->ts_thread->td_priority >= PRI_MIN_IDLE, 1167 ("tdq_choose: Invalid priority on idle queue %d", 1168 ts->ts_thread->td_priority)); 1169 return (ts); 1170 } 1171 1172 return (NULL); 1173 } 1174 1175 /* 1176 * Initialize a thread queue. 1177 */ 1178 static void 1179 tdq_setup(struct tdq *tdq) 1180 { 1181 1182 if (bootverbose) 1183 printf("ULE: setup cpu %d\n", TDQ_ID(tdq)); 1184 runq_init(&tdq->tdq_realtime); 1185 runq_init(&tdq->tdq_timeshare); 1186 runq_init(&tdq->tdq_idle); 1187 snprintf(tdq->tdq_name, sizeof(tdq->tdq_name), 1188 "sched lock %d", (int)TDQ_ID(tdq)); 1189 mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock", 1190 MTX_SPIN | MTX_RECURSE); 1191 } 1192 1193 #ifdef SMP 1194 static void 1195 sched_setup_smp(void) 1196 { 1197 struct tdq *tdq; 1198 int i; 1199 1200 cpu_top = smp_topo(); 1201 for (i = 0; i < MAXCPU; i++) { 1202 if (CPU_ABSENT(i)) 1203 continue; 1204 tdq = TDQ_CPU(i); 1205 tdq_setup(tdq); 1206 tdq->tdq_cg = smp_topo_find(cpu_top, i); 1207 if (tdq->tdq_cg == NULL) 1208 panic("Can't find cpu group for %d\n", i); 1209 } 1210 balance_tdq = TDQ_SELF(); 1211 sched_balance(); 1212 } 1213 #endif 1214 1215 /* 1216 * Setup the thread queues and initialize the topology based on MD 1217 * information. 1218 */ 1219 static void 1220 sched_setup(void *dummy) 1221 { 1222 struct tdq *tdq; 1223 1224 tdq = TDQ_SELF(); 1225 #ifdef SMP 1226 sched_setup_smp(); 1227 #else 1228 tdq_setup(tdq); 1229 #endif 1230 /* 1231 * To avoid divide-by-zero, we set realstathz a dummy value 1232 * in case which sched_clock() called before sched_initticks(). 1233 */ 1234 realstathz = hz; 1235 sched_slice = (realstathz/10); /* ~100ms */ 1236 tickincr = 1 << SCHED_TICK_SHIFT; 1237 1238 /* Add thread0's load since it's running. */ 1239 TDQ_LOCK(tdq); 1240 thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF()); 1241 tdq_load_add(tdq, &td_sched0); 1242 tdq->tdq_lowpri = thread0.td_priority; 1243 TDQ_UNLOCK(tdq); 1244 } 1245 1246 /* 1247 * This routine determines the tickincr after stathz and hz are setup. 1248 */ 1249 /* ARGSUSED */ 1250 static void 1251 sched_initticks(void *dummy) 1252 { 1253 int incr; 1254 1255 realstathz = stathz ? stathz : hz; 1256 sched_slice = (realstathz/10); /* ~100ms */ 1257 1258 /* 1259 * tickincr is shifted out by 10 to avoid rounding errors due to 1260 * hz not being evenly divisible by stathz on all platforms. 1261 */ 1262 incr = (hz << SCHED_TICK_SHIFT) / realstathz; 1263 /* 1264 * This does not work for values of stathz that are more than 1265 * 1 << SCHED_TICK_SHIFT * hz. In practice this does not happen. 1266 */ 1267 if (incr == 0) 1268 incr = 1; 1269 tickincr = incr; 1270 #ifdef SMP 1271 /* 1272 * Set the default balance interval now that we know 1273 * what realstathz is. 1274 */ 1275 balance_interval = realstathz; 1276 /* 1277 * Set steal thresh to log2(mp_ncpu) but no greater than 4. This 1278 * prevents excess thrashing on large machines and excess idle on 1279 * smaller machines. 1280 */ 1281 steal_thresh = min(ffs(mp_ncpus) - 1, 3); 1282 affinity = SCHED_AFFINITY_DEFAULT; 1283 #endif 1284 } 1285 1286 1287 /* 1288 * This is the core of the interactivity algorithm. Determines a score based 1289 * on past behavior. It is the ratio of sleep time to run time scaled to 1290 * a [0, 100] integer. This is the voluntary sleep time of a process, which 1291 * differs from the cpu usage because it does not account for time spent 1292 * waiting on a run-queue. Would be prettier if we had floating point. 1293 */ 1294 static int 1295 sched_interact_score(struct thread *td) 1296 { 1297 struct td_sched *ts; 1298 int div; 1299 1300 ts = td->td_sched; 1301 /* 1302 * The score is only needed if this is likely to be an interactive 1303 * task. Don't go through the expense of computing it if there's 1304 * no chance. 1305 */ 1306 if (sched_interact <= SCHED_INTERACT_HALF && 1307 ts->ts_runtime >= ts->ts_slptime) 1308 return (SCHED_INTERACT_HALF); 1309 1310 if (ts->ts_runtime > ts->ts_slptime) { 1311 div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF); 1312 return (SCHED_INTERACT_HALF + 1313 (SCHED_INTERACT_HALF - (ts->ts_slptime / div))); 1314 } 1315 if (ts->ts_slptime > ts->ts_runtime) { 1316 div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF); 1317 return (ts->ts_runtime / div); 1318 } 1319 /* runtime == slptime */ 1320 if (ts->ts_runtime) 1321 return (SCHED_INTERACT_HALF); 1322 1323 /* 1324 * This can happen if slptime and runtime are 0. 1325 */ 1326 return (0); 1327 1328 } 1329 1330 /* 1331 * Scale the scheduling priority according to the "interactivity" of this 1332 * process. 1333 */ 1334 static void 1335 sched_priority(struct thread *td) 1336 { 1337 int score; 1338 int pri; 1339 1340 if (td->td_pri_class != PRI_TIMESHARE) 1341 return; 1342 /* 1343 * If the score is interactive we place the thread in the realtime 1344 * queue with a priority that is less than kernel and interrupt 1345 * priorities. These threads are not subject to nice restrictions. 1346 * 1347 * Scores greater than this are placed on the normal timeshare queue 1348 * where the priority is partially decided by the most recent cpu 1349 * utilization and the rest is decided by nice value. 1350 * 1351 * The nice value of the process has a linear effect on the calculated 1352 * score. Negative nice values make it easier for a thread to be 1353 * considered interactive. 1354 */ 1355 score = imax(0, sched_interact_score(td) - td->td_proc->p_nice); 1356 if (score < sched_interact) { 1357 pri = PRI_MIN_REALTIME; 1358 pri += ((PRI_MAX_REALTIME - PRI_MIN_REALTIME) / sched_interact) 1359 * score; 1360 KASSERT(pri >= PRI_MIN_REALTIME && pri <= PRI_MAX_REALTIME, 1361 ("sched_priority: invalid interactive priority %d score %d", 1362 pri, score)); 1363 } else { 1364 pri = SCHED_PRI_MIN; 1365 if (td->td_sched->ts_ticks) 1366 pri += SCHED_PRI_TICKS(td->td_sched); 1367 pri += SCHED_PRI_NICE(td->td_proc->p_nice); 1368 KASSERT(pri >= PRI_MIN_TIMESHARE && pri <= PRI_MAX_TIMESHARE, 1369 ("sched_priority: invalid priority %d: nice %d, " 1370 "ticks %d ftick %d ltick %d tick pri %d", 1371 pri, td->td_proc->p_nice, td->td_sched->ts_ticks, 1372 td->td_sched->ts_ftick, td->td_sched->ts_ltick, 1373 SCHED_PRI_TICKS(td->td_sched))); 1374 } 1375 sched_user_prio(td, pri); 1376 1377 return; 1378 } 1379 1380 /* 1381 * This routine enforces a maximum limit on the amount of scheduling history 1382 * kept. It is called after either the slptime or runtime is adjusted. This 1383 * function is ugly due to integer math. 1384 */ 1385 static void 1386 sched_interact_update(struct thread *td) 1387 { 1388 struct td_sched *ts; 1389 u_int sum; 1390 1391 ts = td->td_sched; 1392 sum = ts->ts_runtime + ts->ts_slptime; 1393 if (sum < SCHED_SLP_RUN_MAX) 1394 return; 1395 /* 1396 * This only happens from two places: 1397 * 1) We have added an unusual amount of run time from fork_exit. 1398 * 2) We have added an unusual amount of sleep time from sched_sleep(). 1399 */ 1400 if (sum > SCHED_SLP_RUN_MAX * 2) { 1401 if (ts->ts_runtime > ts->ts_slptime) { 1402 ts->ts_runtime = SCHED_SLP_RUN_MAX; 1403 ts->ts_slptime = 1; 1404 } else { 1405 ts->ts_slptime = SCHED_SLP_RUN_MAX; 1406 ts->ts_runtime = 1; 1407 } 1408 return; 1409 } 1410 /* 1411 * If we have exceeded by more than 1/5th then the algorithm below 1412 * will not bring us back into range. Dividing by two here forces 1413 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX] 1414 */ 1415 if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) { 1416 ts->ts_runtime /= 2; 1417 ts->ts_slptime /= 2; 1418 return; 1419 } 1420 ts->ts_runtime = (ts->ts_runtime / 5) * 4; 1421 ts->ts_slptime = (ts->ts_slptime / 5) * 4; 1422 } 1423 1424 /* 1425 * Scale back the interactivity history when a child thread is created. The 1426 * history is inherited from the parent but the thread may behave totally 1427 * differently. For example, a shell spawning a compiler process. We want 1428 * to learn that the compiler is behaving badly very quickly. 1429 */ 1430 static void 1431 sched_interact_fork(struct thread *td) 1432 { 1433 int ratio; 1434 int sum; 1435 1436 sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime; 1437 if (sum > SCHED_SLP_RUN_FORK) { 1438 ratio = sum / SCHED_SLP_RUN_FORK; 1439 td->td_sched->ts_runtime /= ratio; 1440 td->td_sched->ts_slptime /= ratio; 1441 } 1442 } 1443 1444 /* 1445 * Called from proc0_init() to setup the scheduler fields. 1446 */ 1447 void 1448 schedinit(void) 1449 { 1450 1451 /* 1452 * Set up the scheduler specific parts of proc0. 1453 */ 1454 proc0.p_sched = NULL; /* XXX */ 1455 thread0.td_sched = &td_sched0; 1456 td_sched0.ts_ltick = ticks; 1457 td_sched0.ts_ftick = ticks; 1458 td_sched0.ts_thread = &thread0; 1459 td_sched0.ts_slice = sched_slice; 1460 } 1461 1462 /* 1463 * This is only somewhat accurate since given many processes of the same 1464 * priority they will switch when their slices run out, which will be 1465 * at most sched_slice stathz ticks. 1466 */ 1467 int 1468 sched_rr_interval(void) 1469 { 1470 1471 /* Convert sched_slice to hz */ 1472 return (hz/(realstathz/sched_slice)); 1473 } 1474 1475 /* 1476 * Update the percent cpu tracking information when it is requested or 1477 * the total history exceeds the maximum. We keep a sliding history of 1478 * tick counts that slowly decays. This is less precise than the 4BSD 1479 * mechanism since it happens with less regular and frequent events. 1480 */ 1481 static void 1482 sched_pctcpu_update(struct td_sched *ts) 1483 { 1484 1485 if (ts->ts_ticks == 0) 1486 return; 1487 if (ticks - (hz / 10) < ts->ts_ltick && 1488 SCHED_TICK_TOTAL(ts) < SCHED_TICK_MAX) 1489 return; 1490 /* 1491 * Adjust counters and watermark for pctcpu calc. 1492 */ 1493 if (ts->ts_ltick > ticks - SCHED_TICK_TARG) 1494 ts->ts_ticks = (ts->ts_ticks / (ticks - ts->ts_ftick)) * 1495 SCHED_TICK_TARG; 1496 else 1497 ts->ts_ticks = 0; 1498 ts->ts_ltick = ticks; 1499 ts->ts_ftick = ts->ts_ltick - SCHED_TICK_TARG; 1500 } 1501 1502 /* 1503 * Adjust the priority of a thread. Move it to the appropriate run-queue 1504 * if necessary. This is the back-end for several priority related 1505 * functions. 1506 */ 1507 static void 1508 sched_thread_priority(struct thread *td, u_char prio) 1509 { 1510 struct td_sched *ts; 1511 struct tdq *tdq; 1512 int oldpri; 1513 1514 CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)", 1515 td, td->td_name, td->td_priority, prio, curthread, 1516 curthread->td_name); 1517 ts = td->td_sched; 1518 THREAD_LOCK_ASSERT(td, MA_OWNED); 1519 if (td->td_priority == prio) 1520 return; 1521 /* 1522 * If the priority has been elevated due to priority 1523 * propagation, we may have to move ourselves to a new 1524 * queue. This could be optimized to not re-add in some 1525 * cases. 1526 */ 1527 if (TD_ON_RUNQ(td) && prio < td->td_priority) { 1528 sched_rem(td); 1529 td->td_priority = prio; 1530 sched_add(td, SRQ_BORROWING); 1531 return; 1532 } 1533 /* 1534 * If the thread is currently running we may have to adjust the lowpri 1535 * information so other cpus are aware of our current priority. 1536 */ 1537 if (TD_IS_RUNNING(td)) { 1538 tdq = TDQ_CPU(ts->ts_cpu); 1539 oldpri = td->td_priority; 1540 td->td_priority = prio; 1541 if (prio < tdq->tdq_lowpri) 1542 tdq->tdq_lowpri = prio; 1543 else if (tdq->tdq_lowpri == oldpri) 1544 tdq_setlowpri(tdq, td); 1545 return; 1546 } 1547 td->td_priority = prio; 1548 } 1549 1550 /* 1551 * Update a thread's priority when it is lent another thread's 1552 * priority. 1553 */ 1554 void 1555 sched_lend_prio(struct thread *td, u_char prio) 1556 { 1557 1558 td->td_flags |= TDF_BORROWING; 1559 sched_thread_priority(td, prio); 1560 } 1561 1562 /* 1563 * Restore a thread's priority when priority propagation is 1564 * over. The prio argument is the minimum priority the thread 1565 * needs to have to satisfy other possible priority lending 1566 * requests. If the thread's regular priority is less 1567 * important than prio, the thread will keep a priority boost 1568 * of prio. 1569 */ 1570 void 1571 sched_unlend_prio(struct thread *td, u_char prio) 1572 { 1573 u_char base_pri; 1574 1575 if (td->td_base_pri >= PRI_MIN_TIMESHARE && 1576 td->td_base_pri <= PRI_MAX_TIMESHARE) 1577 base_pri = td->td_user_pri; 1578 else 1579 base_pri = td->td_base_pri; 1580 if (prio >= base_pri) { 1581 td->td_flags &= ~TDF_BORROWING; 1582 sched_thread_priority(td, base_pri); 1583 } else 1584 sched_lend_prio(td, prio); 1585 } 1586 1587 /* 1588 * Standard entry for setting the priority to an absolute value. 1589 */ 1590 void 1591 sched_prio(struct thread *td, u_char prio) 1592 { 1593 u_char oldprio; 1594 1595 /* First, update the base priority. */ 1596 td->td_base_pri = prio; 1597 1598 /* 1599 * If the thread is borrowing another thread's priority, don't 1600 * ever lower the priority. 1601 */ 1602 if (td->td_flags & TDF_BORROWING && td->td_priority < prio) 1603 return; 1604 1605 /* Change the real priority. */ 1606 oldprio = td->td_priority; 1607 sched_thread_priority(td, prio); 1608 1609 /* 1610 * If the thread is on a turnstile, then let the turnstile update 1611 * its state. 1612 */ 1613 if (TD_ON_LOCK(td) && oldprio != prio) 1614 turnstile_adjust(td, oldprio); 1615 } 1616 1617 /* 1618 * Set the base user priority, does not effect current running priority. 1619 */ 1620 void 1621 sched_user_prio(struct thread *td, u_char prio) 1622 { 1623 u_char oldprio; 1624 1625 td->td_base_user_pri = prio; 1626 if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio) 1627 return; 1628 oldprio = td->td_user_pri; 1629 td->td_user_pri = prio; 1630 } 1631 1632 void 1633 sched_lend_user_prio(struct thread *td, u_char prio) 1634 { 1635 u_char oldprio; 1636 1637 THREAD_LOCK_ASSERT(td, MA_OWNED); 1638 td->td_flags |= TDF_UBORROWING; 1639 oldprio = td->td_user_pri; 1640 td->td_user_pri = prio; 1641 } 1642 1643 void 1644 sched_unlend_user_prio(struct thread *td, u_char prio) 1645 { 1646 u_char base_pri; 1647 1648 THREAD_LOCK_ASSERT(td, MA_OWNED); 1649 base_pri = td->td_base_user_pri; 1650 if (prio >= base_pri) { 1651 td->td_flags &= ~TDF_UBORROWING; 1652 sched_user_prio(td, base_pri); 1653 } else { 1654 sched_lend_user_prio(td, prio); 1655 } 1656 } 1657 1658 /* 1659 * Block a thread for switching. Similar to thread_block() but does not 1660 * bump the spin count. 1661 */ 1662 static inline struct mtx * 1663 thread_block_switch(struct thread *td) 1664 { 1665 struct mtx *lock; 1666 1667 THREAD_LOCK_ASSERT(td, MA_OWNED); 1668 lock = td->td_lock; 1669 td->td_lock = &blocked_lock; 1670 mtx_unlock_spin(lock); 1671 1672 return (lock); 1673 } 1674 1675 /* 1676 * Handle migration from sched_switch(). This happens only for 1677 * cpu binding. 1678 */ 1679 static struct mtx * 1680 sched_switch_migrate(struct tdq *tdq, struct thread *td, int flags) 1681 { 1682 struct tdq *tdn; 1683 1684 tdn = TDQ_CPU(td->td_sched->ts_cpu); 1685 #ifdef SMP 1686 tdq_load_rem(tdq, td->td_sched); 1687 /* 1688 * Do the lock dance required to avoid LOR. We grab an extra 1689 * spinlock nesting to prevent preemption while we're 1690 * not holding either run-queue lock. 1691 */ 1692 spinlock_enter(); 1693 thread_block_switch(td); /* This releases the lock on tdq. */ 1694 TDQ_LOCK(tdn); 1695 tdq_add(tdn, td, flags); 1696 tdq_notify(tdn, td->td_sched); 1697 /* 1698 * After we unlock tdn the new cpu still can't switch into this 1699 * thread until we've unblocked it in cpu_switch(). The lock 1700 * pointers may match in the case of HTT cores. Don't unlock here 1701 * or we can deadlock when the other CPU runs the IPI handler. 1702 */ 1703 if (TDQ_LOCKPTR(tdn) != TDQ_LOCKPTR(tdq)) { 1704 TDQ_UNLOCK(tdn); 1705 TDQ_LOCK(tdq); 1706 } 1707 spinlock_exit(); 1708 #endif 1709 return (TDQ_LOCKPTR(tdn)); 1710 } 1711 1712 /* 1713 * Release a thread that was blocked with thread_block_switch(). 1714 */ 1715 static inline void 1716 thread_unblock_switch(struct thread *td, struct mtx *mtx) 1717 { 1718 atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock, 1719 (uintptr_t)mtx); 1720 } 1721 1722 /* 1723 * Switch threads. This function has to handle threads coming in while 1724 * blocked for some reason, running, or idle. It also must deal with 1725 * migrating a thread from one queue to another as running threads may 1726 * be assigned elsewhere via binding. 1727 */ 1728 void 1729 sched_switch(struct thread *td, struct thread *newtd, int flags) 1730 { 1731 struct tdq *tdq; 1732 struct td_sched *ts; 1733 struct mtx *mtx; 1734 int srqflag; 1735 int cpuid; 1736 1737 THREAD_LOCK_ASSERT(td, MA_OWNED); 1738 KASSERT(newtd == NULL, ("sched_switch: Unsupported newtd argument")); 1739 1740 cpuid = PCPU_GET(cpuid); 1741 tdq = TDQ_CPU(cpuid); 1742 ts = td->td_sched; 1743 mtx = td->td_lock; 1744 ts->ts_rltick = ticks; 1745 td->td_lastcpu = td->td_oncpu; 1746 td->td_oncpu = NOCPU; 1747 td->td_flags &= ~TDF_NEEDRESCHED; 1748 td->td_owepreempt = 0; 1749 /* 1750 * The lock pointer in an idle thread should never change. Reset it 1751 * to CAN_RUN as well. 1752 */ 1753 if (TD_IS_IDLETHREAD(td)) { 1754 MPASS(td->td_lock == TDQ_LOCKPTR(tdq)); 1755 TD_SET_CAN_RUN(td); 1756 } else if (TD_IS_RUNNING(td)) { 1757 MPASS(td->td_lock == TDQ_LOCKPTR(tdq)); 1758 srqflag = (flags & SW_PREEMPT) ? 1759 SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED : 1760 SRQ_OURSELF|SRQ_YIELDING; 1761 if (ts->ts_cpu == cpuid) 1762 tdq_runq_add(tdq, ts, srqflag); 1763 else 1764 mtx = sched_switch_migrate(tdq, td, srqflag); 1765 } else { 1766 /* This thread must be going to sleep. */ 1767 TDQ_LOCK(tdq); 1768 mtx = thread_block_switch(td); 1769 tdq_load_rem(tdq, ts); 1770 } 1771 /* 1772 * We enter here with the thread blocked and assigned to the 1773 * appropriate cpu run-queue or sleep-queue and with the current 1774 * thread-queue locked. 1775 */ 1776 TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED); 1777 newtd = choosethread(); 1778 /* 1779 * Call the MD code to switch contexts if necessary. 1780 */ 1781 if (td != newtd) { 1782 #ifdef HWPMC_HOOKS 1783 if (PMC_PROC_IS_USING_PMCS(td->td_proc)) 1784 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT); 1785 #endif 1786 lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object); 1787 TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd; 1788 cpu_switch(td, newtd, mtx); 1789 /* 1790 * We may return from cpu_switch on a different cpu. However, 1791 * we always return with td_lock pointing to the current cpu's 1792 * run queue lock. 1793 */ 1794 cpuid = PCPU_GET(cpuid); 1795 tdq = TDQ_CPU(cpuid); 1796 lock_profile_obtain_lock_success( 1797 &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__); 1798 #ifdef HWPMC_HOOKS 1799 if (PMC_PROC_IS_USING_PMCS(td->td_proc)) 1800 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN); 1801 #endif 1802 } else 1803 thread_unblock_switch(td, mtx); 1804 /* 1805 * Assert that all went well and return. 1806 */ 1807 TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED); 1808 MPASS(td->td_lock == TDQ_LOCKPTR(tdq)); 1809 td->td_oncpu = cpuid; 1810 } 1811 1812 /* 1813 * Adjust thread priorities as a result of a nice request. 1814 */ 1815 void 1816 sched_nice(struct proc *p, int nice) 1817 { 1818 struct thread *td; 1819 1820 PROC_LOCK_ASSERT(p, MA_OWNED); 1821 1822 p->p_nice = nice; 1823 FOREACH_THREAD_IN_PROC(p, td) { 1824 thread_lock(td); 1825 sched_priority(td); 1826 sched_prio(td, td->td_base_user_pri); 1827 thread_unlock(td); 1828 } 1829 } 1830 1831 /* 1832 * Record the sleep time for the interactivity scorer. 1833 */ 1834 void 1835 sched_sleep(struct thread *td, int prio) 1836 { 1837 1838 THREAD_LOCK_ASSERT(td, MA_OWNED); 1839 1840 td->td_slptick = ticks; 1841 if (TD_IS_SUSPENDED(td) || prio <= PSOCK) 1842 td->td_flags |= TDF_CANSWAP; 1843 if (static_boost && prio) 1844 sched_prio(td, prio); 1845 } 1846 1847 /* 1848 * Schedule a thread to resume execution and record how long it voluntarily 1849 * slept. We also update the pctcpu, interactivity, and priority. 1850 */ 1851 void 1852 sched_wakeup(struct thread *td) 1853 { 1854 struct td_sched *ts; 1855 int slptick; 1856 1857 THREAD_LOCK_ASSERT(td, MA_OWNED); 1858 ts = td->td_sched; 1859 td->td_flags &= ~TDF_CANSWAP; 1860 /* 1861 * If we slept for more than a tick update our interactivity and 1862 * priority. 1863 */ 1864 slptick = td->td_slptick; 1865 td->td_slptick = 0; 1866 if (slptick && slptick != ticks) { 1867 u_int hzticks; 1868 1869 hzticks = (ticks - slptick) << SCHED_TICK_SHIFT; 1870 ts->ts_slptime += hzticks; 1871 sched_interact_update(td); 1872 sched_pctcpu_update(ts); 1873 } 1874 /* Reset the slice value after we sleep. */ 1875 ts->ts_slice = sched_slice; 1876 sched_add(td, SRQ_BORING); 1877 } 1878 1879 /* 1880 * Penalize the parent for creating a new child and initialize the child's 1881 * priority. 1882 */ 1883 void 1884 sched_fork(struct thread *td, struct thread *child) 1885 { 1886 THREAD_LOCK_ASSERT(td, MA_OWNED); 1887 sched_fork_thread(td, child); 1888 /* 1889 * Penalize the parent and child for forking. 1890 */ 1891 sched_interact_fork(child); 1892 sched_priority(child); 1893 td->td_sched->ts_runtime += tickincr; 1894 sched_interact_update(td); 1895 sched_priority(td); 1896 } 1897 1898 /* 1899 * Fork a new thread, may be within the same process. 1900 */ 1901 void 1902 sched_fork_thread(struct thread *td, struct thread *child) 1903 { 1904 struct td_sched *ts; 1905 struct td_sched *ts2; 1906 1907 THREAD_LOCK_ASSERT(td, MA_OWNED); 1908 /* 1909 * Initialize child. 1910 */ 1911 ts = td->td_sched; 1912 ts2 = child->td_sched; 1913 child->td_lock = TDQ_LOCKPTR(TDQ_SELF()); 1914 child->td_cpuset = cpuset_ref(td->td_cpuset); 1915 ts2->ts_thread = child; 1916 ts2->ts_cpu = ts->ts_cpu; 1917 ts2->ts_flags = 0; 1918 /* 1919 * Grab our parents cpu estimation information and priority. 1920 */ 1921 ts2->ts_ticks = ts->ts_ticks; 1922 ts2->ts_ltick = ts->ts_ltick; 1923 ts2->ts_ftick = ts->ts_ftick; 1924 child->td_user_pri = td->td_user_pri; 1925 child->td_base_user_pri = td->td_base_user_pri; 1926 /* 1927 * And update interactivity score. 1928 */ 1929 ts2->ts_slptime = ts->ts_slptime; 1930 ts2->ts_runtime = ts->ts_runtime; 1931 ts2->ts_slice = 1; /* Attempt to quickly learn interactivity. */ 1932 } 1933 1934 /* 1935 * Adjust the priority class of a thread. 1936 */ 1937 void 1938 sched_class(struct thread *td, int class) 1939 { 1940 1941 THREAD_LOCK_ASSERT(td, MA_OWNED); 1942 if (td->td_pri_class == class) 1943 return; 1944 td->td_pri_class = class; 1945 } 1946 1947 /* 1948 * Return some of the child's priority and interactivity to the parent. 1949 */ 1950 void 1951 sched_exit(struct proc *p, struct thread *child) 1952 { 1953 struct thread *td; 1954 1955 CTR3(KTR_SCHED, "sched_exit: %p(%s) prio %d", 1956 child, child->td_name, child->td_priority); 1957 1958 PROC_LOCK_ASSERT(p, MA_OWNED); 1959 td = FIRST_THREAD_IN_PROC(p); 1960 sched_exit_thread(td, child); 1961 } 1962 1963 /* 1964 * Penalize another thread for the time spent on this one. This helps to 1965 * worsen the priority and interactivity of processes which schedule batch 1966 * jobs such as make. This has little effect on the make process itself but 1967 * causes new processes spawned by it to receive worse scores immediately. 1968 */ 1969 void 1970 sched_exit_thread(struct thread *td, struct thread *child) 1971 { 1972 1973 CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d", 1974 child, child->td_name, child->td_priority); 1975 1976 /* 1977 * Give the child's runtime to the parent without returning the 1978 * sleep time as a penalty to the parent. This causes shells that 1979 * launch expensive things to mark their children as expensive. 1980 */ 1981 thread_lock(td); 1982 td->td_sched->ts_runtime += child->td_sched->ts_runtime; 1983 sched_interact_update(td); 1984 sched_priority(td); 1985 thread_unlock(td); 1986 } 1987 1988 void 1989 sched_preempt(struct thread *td) 1990 { 1991 struct tdq *tdq; 1992 1993 thread_lock(td); 1994 tdq = TDQ_SELF(); 1995 TDQ_LOCK_ASSERT(tdq, MA_OWNED); 1996 tdq->tdq_ipipending = 0; 1997 if (td->td_priority > tdq->tdq_lowpri) { 1998 if (td->td_critnest > 1) 1999 td->td_owepreempt = 1; 2000 else 2001 mi_switch(SW_INVOL | SW_PREEMPT, NULL); 2002 } 2003 thread_unlock(td); 2004 } 2005 2006 /* 2007 * Fix priorities on return to user-space. Priorities may be elevated due 2008 * to static priorities in msleep() or similar. 2009 */ 2010 void 2011 sched_userret(struct thread *td) 2012 { 2013 /* 2014 * XXX we cheat slightly on the locking here to avoid locking in 2015 * the usual case. Setting td_priority here is essentially an 2016 * incomplete workaround for not setting it properly elsewhere. 2017 * Now that some interrupt handlers are threads, not setting it 2018 * properly elsewhere can clobber it in the window between setting 2019 * it here and returning to user mode, so don't waste time setting 2020 * it perfectly here. 2021 */ 2022 KASSERT((td->td_flags & TDF_BORROWING) == 0, 2023 ("thread with borrowed priority returning to userland")); 2024 if (td->td_priority != td->td_user_pri) { 2025 thread_lock(td); 2026 td->td_priority = td->td_user_pri; 2027 td->td_base_pri = td->td_user_pri; 2028 tdq_setlowpri(TDQ_SELF(), td); 2029 thread_unlock(td); 2030 } 2031 } 2032 2033 /* 2034 * Handle a stathz tick. This is really only relevant for timeshare 2035 * threads. 2036 */ 2037 void 2038 sched_clock(struct thread *td) 2039 { 2040 struct tdq *tdq; 2041 struct td_sched *ts; 2042 2043 THREAD_LOCK_ASSERT(td, MA_OWNED); 2044 tdq = TDQ_SELF(); 2045 #ifdef SMP 2046 /* 2047 * We run the long term load balancer infrequently on the first cpu. 2048 */ 2049 if (balance_tdq == tdq) { 2050 if (balance_ticks && --balance_ticks == 0) 2051 sched_balance(); 2052 } 2053 #endif 2054 /* 2055 * Advance the insert index once for each tick to ensure that all 2056 * threads get a chance to run. 2057 */ 2058 if (tdq->tdq_idx == tdq->tdq_ridx) { 2059 tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS; 2060 if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx])) 2061 tdq->tdq_ridx = tdq->tdq_idx; 2062 } 2063 ts = td->td_sched; 2064 if (td->td_pri_class & PRI_FIFO_BIT) 2065 return; 2066 if (td->td_pri_class == PRI_TIMESHARE) { 2067 /* 2068 * We used a tick; charge it to the thread so 2069 * that we can compute our interactivity. 2070 */ 2071 td->td_sched->ts_runtime += tickincr; 2072 sched_interact_update(td); 2073 sched_priority(td); 2074 } 2075 /* 2076 * We used up one time slice. 2077 */ 2078 if (--ts->ts_slice > 0) 2079 return; 2080 /* 2081 * We're out of time, force a requeue at userret(). 2082 */ 2083 ts->ts_slice = sched_slice; 2084 td->td_flags |= TDF_NEEDRESCHED; 2085 } 2086 2087 /* 2088 * Called once per hz tick. Used for cpu utilization information. This 2089 * is easier than trying to scale based on stathz. 2090 */ 2091 void 2092 sched_tick(void) 2093 { 2094 struct td_sched *ts; 2095 2096 ts = curthread->td_sched; 2097 /* Adjust ticks for pctcpu */ 2098 ts->ts_ticks += 1 << SCHED_TICK_SHIFT; 2099 ts->ts_ltick = ticks; 2100 /* 2101 * Update if we've exceeded our desired tick threshhold by over one 2102 * second. 2103 */ 2104 if (ts->ts_ftick + SCHED_TICK_MAX < ts->ts_ltick) 2105 sched_pctcpu_update(ts); 2106 } 2107 2108 /* 2109 * Return whether the current CPU has runnable tasks. Used for in-kernel 2110 * cooperative idle threads. 2111 */ 2112 int 2113 sched_runnable(void) 2114 { 2115 struct tdq *tdq; 2116 int load; 2117 2118 load = 1; 2119 2120 tdq = TDQ_SELF(); 2121 if ((curthread->td_flags & TDF_IDLETD) != 0) { 2122 if (tdq->tdq_load > 0) 2123 goto out; 2124 } else 2125 if (tdq->tdq_load - 1 > 0) 2126 goto out; 2127 load = 0; 2128 out: 2129 return (load); 2130 } 2131 2132 /* 2133 * Choose the highest priority thread to run. The thread is removed from 2134 * the run-queue while running however the load remains. For SMP we set 2135 * the tdq in the global idle bitmask if it idles here. 2136 */ 2137 struct thread * 2138 sched_choose(void) 2139 { 2140 struct td_sched *ts; 2141 struct tdq *tdq; 2142 2143 tdq = TDQ_SELF(); 2144 TDQ_LOCK_ASSERT(tdq, MA_OWNED); 2145 ts = tdq_choose(tdq); 2146 if (ts) { 2147 ts->ts_ltick = ticks; 2148 tdq_runq_rem(tdq, ts); 2149 return (ts->ts_thread); 2150 } 2151 return (PCPU_GET(idlethread)); 2152 } 2153 2154 /* 2155 * Set owepreempt if necessary. Preemption never happens directly in ULE, 2156 * we always request it once we exit a critical section. 2157 */ 2158 static inline void 2159 sched_setpreempt(struct thread *td) 2160 { 2161 struct thread *ctd; 2162 int cpri; 2163 int pri; 2164 2165 THREAD_LOCK_ASSERT(curthread, MA_OWNED); 2166 2167 ctd = curthread; 2168 pri = td->td_priority; 2169 cpri = ctd->td_priority; 2170 if (pri < cpri) 2171 ctd->td_flags |= TDF_NEEDRESCHED; 2172 if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd)) 2173 return; 2174 if (!sched_shouldpreempt(pri, cpri, 0)) 2175 return; 2176 ctd->td_owepreempt = 1; 2177 } 2178 2179 /* 2180 * Add a thread to a thread queue. Select the appropriate runq and add the 2181 * thread to it. This is the internal function called when the tdq is 2182 * predetermined. 2183 */ 2184 void 2185 tdq_add(struct tdq *tdq, struct thread *td, int flags) 2186 { 2187 struct td_sched *ts; 2188 2189 TDQ_LOCK_ASSERT(tdq, MA_OWNED); 2190 KASSERT((td->td_inhibitors == 0), 2191 ("sched_add: trying to run inhibited thread")); 2192 KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)), 2193 ("sched_add: bad thread state")); 2194 KASSERT(td->td_flags & TDF_INMEM, 2195 ("sched_add: thread swapped out")); 2196 2197 ts = td->td_sched; 2198 if (td->td_priority < tdq->tdq_lowpri) 2199 tdq->tdq_lowpri = td->td_priority; 2200 tdq_runq_add(tdq, ts, flags); 2201 tdq_load_add(tdq, ts); 2202 } 2203 2204 /* 2205 * Select the target thread queue and add a thread to it. Request 2206 * preemption or IPI a remote processor if required. 2207 */ 2208 void 2209 sched_add(struct thread *td, int flags) 2210 { 2211 struct tdq *tdq; 2212 #ifdef SMP 2213 struct td_sched *ts; 2214 int cpu; 2215 #endif 2216 CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)", 2217 td, td->td_name, td->td_priority, curthread, 2218 curthread->td_name); 2219 THREAD_LOCK_ASSERT(td, MA_OWNED); 2220 /* 2221 * Recalculate the priority before we select the target cpu or 2222 * run-queue. 2223 */ 2224 if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE) 2225 sched_priority(td); 2226 #ifdef SMP 2227 /* 2228 * Pick the destination cpu and if it isn't ours transfer to the 2229 * target cpu. 2230 */ 2231 ts = td->td_sched; 2232 cpu = sched_pickcpu(ts, flags); 2233 tdq = sched_setcpu(ts, cpu, flags); 2234 tdq_add(tdq, td, flags); 2235 if (cpu != PCPU_GET(cpuid)) { 2236 tdq_notify(tdq, ts); 2237 return; 2238 } 2239 #else 2240 tdq = TDQ_SELF(); 2241 TDQ_LOCK(tdq); 2242 /* 2243 * Now that the thread is moving to the run-queue, set the lock 2244 * to the scheduler's lock. 2245 */ 2246 thread_lock_set(td, TDQ_LOCKPTR(tdq)); 2247 tdq_add(tdq, td, flags); 2248 #endif 2249 if (!(flags & SRQ_YIELDING)) 2250 sched_setpreempt(td); 2251 } 2252 2253 /* 2254 * Remove a thread from a run-queue without running it. This is used 2255 * when we're stealing a thread from a remote queue. Otherwise all threads 2256 * exit by calling sched_exit_thread() and sched_throw() themselves. 2257 */ 2258 void 2259 sched_rem(struct thread *td) 2260 { 2261 struct tdq *tdq; 2262 struct td_sched *ts; 2263 2264 CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)", 2265 td, td->td_name, td->td_priority, curthread, 2266 curthread->td_name); 2267 ts = td->td_sched; 2268 tdq = TDQ_CPU(ts->ts_cpu); 2269 TDQ_LOCK_ASSERT(tdq, MA_OWNED); 2270 MPASS(td->td_lock == TDQ_LOCKPTR(tdq)); 2271 KASSERT(TD_ON_RUNQ(td), 2272 ("sched_rem: thread not on run queue")); 2273 tdq_runq_rem(tdq, ts); 2274 tdq_load_rem(tdq, ts); 2275 TD_SET_CAN_RUN(td); 2276 if (td->td_priority == tdq->tdq_lowpri) 2277 tdq_setlowpri(tdq, NULL); 2278 } 2279 2280 /* 2281 * Fetch cpu utilization information. Updates on demand. 2282 */ 2283 fixpt_t 2284 sched_pctcpu(struct thread *td) 2285 { 2286 fixpt_t pctcpu; 2287 struct td_sched *ts; 2288 2289 pctcpu = 0; 2290 ts = td->td_sched; 2291 if (ts == NULL) 2292 return (0); 2293 2294 thread_lock(td); 2295 if (ts->ts_ticks) { 2296 int rtick; 2297 2298 sched_pctcpu_update(ts); 2299 /* How many rtick per second ? */ 2300 rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz); 2301 pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT; 2302 } 2303 thread_unlock(td); 2304 2305 return (pctcpu); 2306 } 2307 2308 /* 2309 * Enforce affinity settings for a thread. Called after adjustments to 2310 * cpumask. 2311 */ 2312 void 2313 sched_affinity(struct thread *td) 2314 { 2315 #ifdef SMP 2316 struct td_sched *ts; 2317 int cpu; 2318 2319 THREAD_LOCK_ASSERT(td, MA_OWNED); 2320 ts = td->td_sched; 2321 if (THREAD_CAN_SCHED(td, ts->ts_cpu)) 2322 return; 2323 if (!TD_IS_RUNNING(td)) 2324 return; 2325 td->td_flags |= TDF_NEEDRESCHED; 2326 if (!THREAD_CAN_MIGRATE(td)) 2327 return; 2328 /* 2329 * Assign the new cpu and force a switch before returning to 2330 * userspace. If the target thread is not running locally send 2331 * an ipi to force the issue. 2332 */ 2333 cpu = ts->ts_cpu; 2334 ts->ts_cpu = sched_pickcpu(ts, 0); 2335 if (cpu != PCPU_GET(cpuid)) 2336 ipi_selected(1 << cpu, IPI_PREEMPT); 2337 #endif 2338 } 2339 2340 /* 2341 * Bind a thread to a target cpu. 2342 */ 2343 void 2344 sched_bind(struct thread *td, int cpu) 2345 { 2346 struct td_sched *ts; 2347 2348 THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED); 2349 ts = td->td_sched; 2350 if (ts->ts_flags & TSF_BOUND) 2351 sched_unbind(td); 2352 ts->ts_flags |= TSF_BOUND; 2353 sched_pin(); 2354 if (PCPU_GET(cpuid) == cpu) 2355 return; 2356 ts->ts_cpu = cpu; 2357 /* When we return from mi_switch we'll be on the correct cpu. */ 2358 mi_switch(SW_VOL, NULL); 2359 } 2360 2361 /* 2362 * Release a bound thread. 2363 */ 2364 void 2365 sched_unbind(struct thread *td) 2366 { 2367 struct td_sched *ts; 2368 2369 THREAD_LOCK_ASSERT(td, MA_OWNED); 2370 ts = td->td_sched; 2371 if ((ts->ts_flags & TSF_BOUND) == 0) 2372 return; 2373 ts->ts_flags &= ~TSF_BOUND; 2374 sched_unpin(); 2375 } 2376 2377 int 2378 sched_is_bound(struct thread *td) 2379 { 2380 THREAD_LOCK_ASSERT(td, MA_OWNED); 2381 return (td->td_sched->ts_flags & TSF_BOUND); 2382 } 2383 2384 /* 2385 * Basic yield call. 2386 */ 2387 void 2388 sched_relinquish(struct thread *td) 2389 { 2390 thread_lock(td); 2391 SCHED_STAT_INC(switch_relinquish); 2392 mi_switch(SW_VOL, NULL); 2393 thread_unlock(td); 2394 } 2395 2396 /* 2397 * Return the total system load. 2398 */ 2399 int 2400 sched_load(void) 2401 { 2402 #ifdef SMP 2403 int total; 2404 int i; 2405 2406 total = 0; 2407 for (i = 0; i <= mp_maxid; i++) 2408 total += TDQ_CPU(i)->tdq_sysload; 2409 return (total); 2410 #else 2411 return (TDQ_SELF()->tdq_sysload); 2412 #endif 2413 } 2414 2415 int 2416 sched_sizeof_proc(void) 2417 { 2418 return (sizeof(struct proc)); 2419 } 2420 2421 int 2422 sched_sizeof_thread(void) 2423 { 2424 return (sizeof(struct thread) + sizeof(struct td_sched)); 2425 } 2426 2427 /* 2428 * The actual idle process. 2429 */ 2430 void 2431 sched_idletd(void *dummy) 2432 { 2433 struct thread *td; 2434 struct tdq *tdq; 2435 2436 td = curthread; 2437 tdq = TDQ_SELF(); 2438 mtx_assert(&Giant, MA_NOTOWNED); 2439 /* ULE relies on preemption for idle interruption. */ 2440 for (;;) { 2441 #ifdef SMP 2442 if (tdq_idled(tdq)) 2443 cpu_idle(); 2444 #else 2445 cpu_idle(); 2446 #endif 2447 } 2448 } 2449 2450 /* 2451 * A CPU is entering for the first time or a thread is exiting. 2452 */ 2453 void 2454 sched_throw(struct thread *td) 2455 { 2456 struct thread *newtd; 2457 struct tdq *tdq; 2458 2459 tdq = TDQ_SELF(); 2460 if (td == NULL) { 2461 /* Correct spinlock nesting and acquire the correct lock. */ 2462 TDQ_LOCK(tdq); 2463 spinlock_exit(); 2464 } else { 2465 MPASS(td->td_lock == TDQ_LOCKPTR(tdq)); 2466 tdq_load_rem(tdq, td->td_sched); 2467 lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object); 2468 } 2469 KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count")); 2470 newtd = choosethread(); 2471 TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd; 2472 PCPU_SET(switchtime, cpu_ticks()); 2473 PCPU_SET(switchticks, ticks); 2474 cpu_throw(td, newtd); /* doesn't return */ 2475 } 2476 2477 /* 2478 * This is called from fork_exit(). Just acquire the correct locks and 2479 * let fork do the rest of the work. 2480 */ 2481 void 2482 sched_fork_exit(struct thread *td) 2483 { 2484 struct td_sched *ts; 2485 struct tdq *tdq; 2486 int cpuid; 2487 2488 /* 2489 * Finish setting up thread glue so that it begins execution in a 2490 * non-nested critical section with the scheduler lock held. 2491 */ 2492 cpuid = PCPU_GET(cpuid); 2493 tdq = TDQ_CPU(cpuid); 2494 ts = td->td_sched; 2495 if (TD_IS_IDLETHREAD(td)) 2496 td->td_lock = TDQ_LOCKPTR(tdq); 2497 MPASS(td->td_lock == TDQ_LOCKPTR(tdq)); 2498 td->td_oncpu = cpuid; 2499 TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED); 2500 lock_profile_obtain_lock_success( 2501 &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__); 2502 } 2503 2504 static SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, 2505 "Scheduler"); 2506 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0, 2507 "Scheduler name"); 2508 SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0, 2509 "Slice size for timeshare threads"); 2510 SYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0, 2511 "Interactivity score threshold"); 2512 SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh, 2513 0,"Min priority for preemption, lower priorities have greater precedence"); 2514 SYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost, 2515 0,"Controls whether static kernel priorities are assigned to sleeping threads."); 2516 #ifdef SMP 2517 SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0, 2518 "Number of hz ticks to keep thread affinity for"); 2519 SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0, 2520 "Enables the long-term load balancer"); 2521 SYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW, 2522 &balance_interval, 0, 2523 "Average frequency in stathz ticks to run the long-term balancer"); 2524 SYSCTL_INT(_kern_sched, OID_AUTO, steal_htt, CTLFLAG_RW, &steal_htt, 0, 2525 "Steals work from another hyper-threaded core on idle"); 2526 SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0, 2527 "Attempts to steal work from other cores before idling"); 2528 SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0, 2529 "Minimum load on remote cpu before we'll steal"); 2530 #endif 2531 2532 /* ps compat. All cpu percentages from ULE are weighted. */ 2533 static int ccpu = 0; 2534 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, ""); 2535 2536 2537 #define KERN_SWITCH_INCLUDE 1 2538 #include "kern/kern_switch.c" 2539