1 /* 2 * Copyright (c) 1999 Peter Wemm <peter@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, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 24 * SUCH DAMAGE. 25 * 26 * $DragonFly: src/sys/kern/usched_bsd4.c,v 1.26 2008/11/01 23:31:19 dillon Exp $ 27 */ 28 29 #include <sys/param.h> 30 #include <sys/systm.h> 31 #include <sys/kernel.h> 32 #include <sys/lock.h> 33 #include <sys/queue.h> 34 #include <sys/proc.h> 35 #include <sys/rtprio.h> 36 #include <sys/uio.h> 37 #include <sys/sysctl.h> 38 #include <sys/resourcevar.h> 39 #include <sys/spinlock.h> 40 #include <machine/cpu.h> 41 #include <machine/smp.h> 42 43 #include <sys/thread2.h> 44 #include <sys/spinlock2.h> 45 46 /* 47 * Priorities. Note that with 32 run queues per scheduler each queue 48 * represents four priority levels. 49 */ 50 51 #define MAXPRI 128 52 #define PRIMASK (MAXPRI - 1) 53 #define PRIBASE_REALTIME 0 54 #define PRIBASE_NORMAL MAXPRI 55 #define PRIBASE_IDLE (MAXPRI * 2) 56 #define PRIBASE_THREAD (MAXPRI * 3) 57 #define PRIBASE_NULL (MAXPRI * 4) 58 59 #define NQS 32 /* 32 run queues. */ 60 #define PPQ (MAXPRI / NQS) /* priorities per queue */ 61 #define PPQMASK (PPQ - 1) 62 63 /* 64 * NICEPPQ - number of nice units per priority queue 65 * ESTCPURAMP - number of scheduler ticks for estcpu to switch queues 66 * 67 * ESTCPUPPQ - number of estcpu units per priority queue 68 * ESTCPUMAX - number of estcpu units 69 * ESTCPUINCR - amount we have to increment p_estcpu per scheduling tick at 70 * 100% cpu. 71 */ 72 #define NICEPPQ 2 73 #define ESTCPURAMP 4 74 #define ESTCPUPPQ 512 75 #define ESTCPUMAX (ESTCPUPPQ * NQS) 76 #define ESTCPUINCR (ESTCPUPPQ / ESTCPURAMP) 77 #define PRIO_RANGE (PRIO_MAX - PRIO_MIN + 1) 78 79 #define ESTCPULIM(v) min((v), ESTCPUMAX) 80 81 TAILQ_HEAD(rq, lwp); 82 83 #define lwp_priority lwp_usdata.bsd4.priority 84 #define lwp_rqindex lwp_usdata.bsd4.rqindex 85 #define lwp_origcpu lwp_usdata.bsd4.origcpu 86 #define lwp_estcpu lwp_usdata.bsd4.estcpu 87 #define lwp_rqtype lwp_usdata.bsd4.rqtype 88 89 static void bsd4_acquire_curproc(struct lwp *lp); 90 static void bsd4_release_curproc(struct lwp *lp); 91 static void bsd4_select_curproc(globaldata_t gd); 92 static void bsd4_setrunqueue(struct lwp *lp); 93 static void bsd4_schedulerclock(struct lwp *lp, sysclock_t period, 94 sysclock_t cpstamp); 95 static void bsd4_recalculate_estcpu(struct lwp *lp); 96 static void bsd4_resetpriority(struct lwp *lp); 97 static void bsd4_forking(struct lwp *plp, struct lwp *lp); 98 static void bsd4_exiting(struct lwp *plp, struct lwp *lp); 99 static void bsd4_yield(struct lwp *lp); 100 101 #ifdef SMP 102 static void need_user_resched_remote(void *dummy); 103 #endif 104 static struct lwp *chooseproc_locked(struct lwp *chklp); 105 static void bsd4_remrunqueue_locked(struct lwp *lp); 106 static void bsd4_setrunqueue_locked(struct lwp *lp); 107 108 struct usched usched_bsd4 = { 109 { NULL }, 110 "bsd4", "Original DragonFly Scheduler", 111 NULL, /* default registration */ 112 NULL, /* default deregistration */ 113 bsd4_acquire_curproc, 114 bsd4_release_curproc, 115 bsd4_setrunqueue, 116 bsd4_schedulerclock, 117 bsd4_recalculate_estcpu, 118 bsd4_resetpriority, 119 bsd4_forking, 120 bsd4_exiting, 121 NULL, /* setcpumask not supported */ 122 bsd4_yield 123 }; 124 125 struct usched_bsd4_pcpu { 126 struct thread helper_thread; 127 short rrcount; 128 short upri; 129 struct lwp *uschedcp; 130 }; 131 132 typedef struct usched_bsd4_pcpu *bsd4_pcpu_t; 133 134 /* 135 * We have NQS (32) run queues per scheduling class. For the normal 136 * class, there are 128 priorities scaled onto these 32 queues. New 137 * processes are added to the last entry in each queue, and processes 138 * are selected for running by taking them from the head and maintaining 139 * a simple FIFO arrangement. Realtime and Idle priority processes have 140 * and explicit 0-31 priority which maps directly onto their class queue 141 * index. When a queue has something in it, the corresponding bit is 142 * set in the queuebits variable, allowing a single read to determine 143 * the state of all 32 queues and then a ffs() to find the first busy 144 * queue. 145 */ 146 static struct rq bsd4_queues[NQS]; 147 static struct rq bsd4_rtqueues[NQS]; 148 static struct rq bsd4_idqueues[NQS]; 149 static u_int32_t bsd4_queuebits; 150 static u_int32_t bsd4_rtqueuebits; 151 static u_int32_t bsd4_idqueuebits; 152 static cpumask_t bsd4_curprocmask = -1; /* currently running a user process */ 153 static cpumask_t bsd4_rdyprocmask; /* ready to accept a user process */ 154 static int bsd4_runqcount; 155 #ifdef SMP 156 static volatile int bsd4_scancpu; 157 #endif 158 static struct spinlock bsd4_spin; 159 static struct usched_bsd4_pcpu bsd4_pcpu[MAXCPU]; 160 161 SYSCTL_INT(_debug, OID_AUTO, bsd4_runqcount, CTLFLAG_RD, &bsd4_runqcount, 0, ""); 162 #ifdef INVARIANTS 163 static int usched_nonoptimal; 164 SYSCTL_INT(_debug, OID_AUTO, usched_nonoptimal, CTLFLAG_RW, 165 &usched_nonoptimal, 0, "acquire_curproc() was not optimal"); 166 static int usched_optimal; 167 SYSCTL_INT(_debug, OID_AUTO, usched_optimal, CTLFLAG_RW, 168 &usched_optimal, 0, "acquire_curproc() was optimal"); 169 #endif 170 static int usched_debug = -1; 171 SYSCTL_INT(_debug, OID_AUTO, scdebug, CTLFLAG_RW, &usched_debug, 0, ""); 172 #ifdef SMP 173 static int remote_resched_nonaffinity; 174 static int remote_resched_affinity; 175 static int choose_affinity; 176 SYSCTL_INT(_debug, OID_AUTO, remote_resched_nonaffinity, CTLFLAG_RD, 177 &remote_resched_nonaffinity, 0, "Number of remote rescheds"); 178 SYSCTL_INT(_debug, OID_AUTO, remote_resched_affinity, CTLFLAG_RD, 179 &remote_resched_affinity, 0, "Number of remote rescheds"); 180 SYSCTL_INT(_debug, OID_AUTO, choose_affinity, CTLFLAG_RD, 181 &choose_affinity, 0, "chooseproc() was smart"); 182 #endif 183 184 static int usched_bsd4_rrinterval = (ESTCPUFREQ + 9) / 10; 185 SYSCTL_INT(_kern, OID_AUTO, usched_bsd4_rrinterval, CTLFLAG_RW, 186 &usched_bsd4_rrinterval, 0, ""); 187 static int usched_bsd4_decay = ESTCPUINCR / 2; 188 SYSCTL_INT(_kern, OID_AUTO, usched_bsd4_decay, CTLFLAG_RW, 189 &usched_bsd4_decay, 0, ""); 190 191 /* 192 * Initialize the run queues at boot time. 193 */ 194 static void 195 rqinit(void *dummy) 196 { 197 int i; 198 199 spin_init(&bsd4_spin); 200 for (i = 0; i < NQS; i++) { 201 TAILQ_INIT(&bsd4_queues[i]); 202 TAILQ_INIT(&bsd4_rtqueues[i]); 203 TAILQ_INIT(&bsd4_idqueues[i]); 204 } 205 atomic_clear_int(&bsd4_curprocmask, 1); 206 } 207 SYSINIT(runqueue, SI_BOOT2_USCHED, SI_ORDER_FIRST, rqinit, NULL) 208 209 /* 210 * BSD4_ACQUIRE_CURPROC 211 * 212 * This function is called when the kernel intends to return to userland. 213 * It is responsible for making the thread the current designated userland 214 * thread for this cpu, blocking if necessary. 215 * 216 * The kernel has already depressed our LWKT priority so we must not switch 217 * until we have either assigned or disposed of the thread. 218 * 219 * WARNING! THIS FUNCTION IS ALLOWED TO CAUSE THE CURRENT THREAD TO MIGRATE 220 * TO ANOTHER CPU! Because most of the kernel assumes that no migration will 221 * occur, this function is called only under very controlled circumstances. 222 * 223 * MPSAFE 224 */ 225 static void 226 bsd4_acquire_curproc(struct lwp *lp) 227 { 228 globaldata_t gd; 229 bsd4_pcpu_t dd; 230 struct lwp *olp; 231 232 crit_enter(); 233 bsd4_recalculate_estcpu(lp); 234 235 /* 236 * If a reschedule was requested give another thread the 237 * driver's seat. 238 */ 239 if (user_resched_wanted()) { 240 clear_user_resched(); 241 bsd4_release_curproc(lp); 242 } 243 244 /* 245 * Loop until we are the current user thread 246 */ 247 do { 248 /* 249 * Reload after a switch or setrunqueue/switch possibly 250 * moved us to another cpu. 251 */ 252 clear_lwkt_resched(); 253 gd = mycpu; 254 dd = &bsd4_pcpu[gd->gd_cpuid]; 255 256 /* 257 * Become the currently scheduled user thread for this cpu 258 * if we can do so trivially. 259 * 260 * We can steal another thread's current thread designation 261 * on this cpu since if we are running that other thread 262 * must not be, so we can safely deschedule it. 263 */ 264 if (dd->uschedcp == lp) { 265 dd->upri = lp->lwp_priority; 266 } else if (dd->uschedcp == NULL) { 267 atomic_set_int(&bsd4_curprocmask, gd->gd_cpumask); 268 dd->uschedcp = lp; 269 dd->upri = lp->lwp_priority; 270 } else if (dd->upri > lp->lwp_priority) { 271 olp = dd->uschedcp; 272 dd->uschedcp = lp; 273 dd->upri = lp->lwp_priority; 274 lwkt_deschedule(olp->lwp_thread); 275 bsd4_setrunqueue(olp); 276 } else { 277 lwkt_deschedule(lp->lwp_thread); 278 bsd4_setrunqueue(lp); 279 lwkt_switch(); 280 } 281 282 /* 283 * Other threads at our current user priority have already 284 * put in their bids, but we must run any kernel threads 285 * at higher priorities, and we could lose our bid to 286 * another thread trying to return to user mode in the 287 * process. 288 * 289 * If we lose our bid we will be descheduled and put on 290 * the run queue. When we are reactivated we will have 291 * another chance. 292 */ 293 if (lwkt_check_resched(lp->lwp_thread) > 1) { 294 lwkt_switch(); 295 continue; 296 } 297 } while (dd->uschedcp != lp); 298 299 crit_exit(); 300 KKASSERT((lp->lwp_flag & LWP_ONRUNQ) == 0); 301 } 302 303 /* 304 * BSD4_RELEASE_CURPROC 305 * 306 * This routine detaches the current thread from the userland scheduler, 307 * usually because the thread needs to run or block in the kernel (at 308 * kernel priority) for a while. 309 * 310 * This routine is also responsible for selecting a new thread to 311 * make the current thread. 312 * 313 * NOTE: This implementation differs from the dummy example in that 314 * bsd4_select_curproc() is able to select the current process, whereas 315 * dummy_select_curproc() is not able to select the current process. 316 * This means we have to NULL out uschedcp. 317 * 318 * Additionally, note that we may already be on a run queue if releasing 319 * via the lwkt_switch() in bsd4_setrunqueue(). 320 * 321 * WARNING! The MP lock may be in an unsynchronized state due to the 322 * way get_mplock() works and the fact that this function may be called 323 * from a passive release during a lwkt_switch(). try_mplock() will deal 324 * with this for us but you should be aware that td_mpcount may not be 325 * useable. 326 * 327 * MPSAFE 328 */ 329 static void 330 bsd4_release_curproc(struct lwp *lp) 331 { 332 globaldata_t gd = mycpu; 333 bsd4_pcpu_t dd = &bsd4_pcpu[gd->gd_cpuid]; 334 335 if (dd->uschedcp == lp) { 336 crit_enter(); 337 KKASSERT((lp->lwp_flag & LWP_ONRUNQ) == 0); 338 dd->uschedcp = NULL; /* don't let lp be selected */ 339 dd->upri = PRIBASE_NULL; 340 atomic_clear_int(&bsd4_curprocmask, gd->gd_cpumask); 341 bsd4_select_curproc(gd); 342 crit_exit(); 343 } 344 } 345 346 /* 347 * BSD4_SELECT_CURPROC 348 * 349 * Select a new current process for this cpu and clear any pending user 350 * reschedule request. The cpu currently has no current process. 351 * 352 * This routine is also responsible for equal-priority round-robining, 353 * typically triggered from bsd4_schedulerclock(). In our dummy example 354 * all the 'user' threads are LWKT scheduled all at once and we just 355 * call lwkt_switch(). 356 * 357 * The calling process is not on the queue and cannot be selected. 358 * 359 * MPSAFE 360 */ 361 static 362 void 363 bsd4_select_curproc(globaldata_t gd) 364 { 365 bsd4_pcpu_t dd = &bsd4_pcpu[gd->gd_cpuid]; 366 struct lwp *nlp; 367 int cpuid = gd->gd_cpuid; 368 369 crit_enter_gd(gd); 370 371 spin_lock_wr(&bsd4_spin); 372 if ((nlp = chooseproc_locked(dd->uschedcp)) != NULL) { 373 atomic_set_int(&bsd4_curprocmask, 1 << cpuid); 374 dd->upri = nlp->lwp_priority; 375 dd->uschedcp = nlp; 376 spin_unlock_wr(&bsd4_spin); 377 #ifdef SMP 378 lwkt_acquire(nlp->lwp_thread); 379 #endif 380 lwkt_schedule(nlp->lwp_thread); 381 } else if (bsd4_runqcount && (bsd4_rdyprocmask & (1 << cpuid))) { 382 atomic_clear_int(&bsd4_rdyprocmask, 1 << cpuid); 383 spin_unlock_wr(&bsd4_spin); 384 lwkt_schedule(&dd->helper_thread); 385 } else { 386 spin_unlock_wr(&bsd4_spin); 387 } 388 crit_exit_gd(gd); 389 } 390 391 /* 392 * BSD4_SETRUNQUEUE 393 * 394 * Place the specified lwp on the user scheduler's run queue. This routine 395 * must be called with the thread descheduled. The lwp must be runnable. 396 * 397 * The thread may be the current thread as a special case. 398 * 399 * MPSAFE 400 */ 401 static void 402 bsd4_setrunqueue(struct lwp *lp) 403 { 404 globaldata_t gd; 405 bsd4_pcpu_t dd; 406 #ifdef SMP 407 int cpuid; 408 cpumask_t mask; 409 cpumask_t tmpmask; 410 #endif 411 412 /* 413 * First validate the process state relative to the current cpu. 414 * We don't need the spinlock for this, just a critical section. 415 * We are in control of the process. 416 */ 417 crit_enter(); 418 KASSERT(lp->lwp_stat == LSRUN, ("setrunqueue: lwp not LSRUN")); 419 KASSERT((lp->lwp_flag & LWP_ONRUNQ) == 0, 420 ("lwp %d/%d already on runq! flag %08x/%08x", lp->lwp_proc->p_pid, 421 lp->lwp_tid, lp->lwp_proc->p_flag, lp->lwp_flag)); 422 KKASSERT((lp->lwp_thread->td_flags & TDF_RUNQ) == 0); 423 424 /* 425 * Note: gd and dd are relative to the target thread's last cpu, 426 * NOT our current cpu. 427 */ 428 gd = lp->lwp_thread->td_gd; 429 dd = &bsd4_pcpu[gd->gd_cpuid]; 430 431 /* 432 * This process is not supposed to be scheduled anywhere or assigned 433 * as the current process anywhere. Assert the condition. 434 */ 435 KKASSERT(dd->uschedcp != lp); 436 437 #ifndef SMP 438 /* 439 * If we are not SMP we do not have a scheduler helper to kick 440 * and must directly activate the process if none are scheduled. 441 * 442 * This is really only an issue when bootstrapping init since 443 * the caller in all other cases will be a user process, and 444 * even if released (dd->uschedcp == NULL), that process will 445 * kickstart the scheduler when it returns to user mode from 446 * the kernel. 447 */ 448 if (dd->uschedcp == NULL) { 449 atomic_set_int(&bsd4_curprocmask, gd->gd_cpumask); 450 dd->uschedcp = lp; 451 dd->upri = lp->lwp_priority; 452 lwkt_schedule(lp->lwp_thread); 453 crit_exit(); 454 return; 455 } 456 #endif 457 458 #ifdef SMP 459 /* 460 * XXX fixme. Could be part of a remrunqueue/setrunqueue 461 * operation when the priority is recalculated, so TDF_MIGRATING 462 * may already be set. 463 */ 464 if ((lp->lwp_thread->td_flags & TDF_MIGRATING) == 0) 465 lwkt_giveaway(lp->lwp_thread); 466 #endif 467 468 /* 469 * We lose control of lp the moment we release the spinlock after 470 * having placed lp on the queue. i.e. another cpu could pick it 471 * up and it could exit, or its priority could be further adjusted, 472 * or something like that. 473 */ 474 spin_lock_wr(&bsd4_spin); 475 bsd4_setrunqueue_locked(lp); 476 477 #ifdef SMP 478 /* 479 * Kick the scheduler helper on one of the other cpu's 480 * and request a reschedule if appropriate. 481 */ 482 cpuid = (bsd4_scancpu & 0xFFFF) % ncpus; 483 ++bsd4_scancpu; 484 mask = ~bsd4_curprocmask & bsd4_rdyprocmask & 485 lp->lwp_cpumask & smp_active_mask; 486 spin_unlock_wr(&bsd4_spin); 487 488 while (mask) { 489 tmpmask = ~((1 << cpuid) - 1); 490 if (mask & tmpmask) 491 cpuid = bsfl(mask & tmpmask); 492 else 493 cpuid = bsfl(mask); 494 gd = globaldata_find(cpuid); 495 dd = &bsd4_pcpu[cpuid]; 496 497 if ((dd->upri & ~PPQMASK) > (lp->lwp_priority & ~PPQMASK)) { 498 if (gd == mycpu) 499 need_user_resched_remote(NULL); 500 else 501 lwkt_send_ipiq(gd, need_user_resched_remote, NULL); 502 break; 503 } 504 mask &= ~(1 << cpuid); 505 } 506 #else 507 /* 508 * Request a reschedule if appropriate. 509 */ 510 spin_unlock_wr(&bsd4_spin); 511 if ((dd->upri & ~PPQMASK) > (lp->lwp_priority & ~PPQMASK)) { 512 need_user_resched(); 513 } 514 #endif 515 crit_exit(); 516 } 517 518 /* 519 * This routine is called from a systimer IPI. It MUST be MP-safe and 520 * the BGL IS NOT HELD ON ENTRY. This routine is called at ESTCPUFREQ on 521 * each cpu. 522 * 523 * Because this is effectively a 'fast' interrupt, we cannot safely 524 * use spinlocks unless gd_spinlock_rd is NULL and gd_spinlocks_wr is 0, 525 * even if the spinlocks are 'non conflicting'. This is due to the way 526 * spinlock conflicts against cached read locks are handled. 527 * 528 * MPSAFE 529 */ 530 static 531 void 532 bsd4_schedulerclock(struct lwp *lp, sysclock_t period, sysclock_t cpstamp) 533 { 534 globaldata_t gd = mycpu; 535 bsd4_pcpu_t dd = &bsd4_pcpu[gd->gd_cpuid]; 536 537 /* 538 * Do we need to round-robin? We round-robin 10 times a second. 539 * This should only occur for cpu-bound batch processes. 540 */ 541 if (++dd->rrcount >= usched_bsd4_rrinterval) { 542 dd->rrcount = 0; 543 need_user_resched(); 544 } 545 546 /* 547 * As the process accumulates cpu time p_estcpu is bumped and may 548 * push the process into another scheduling queue. It typically 549 * takes 4 ticks to bump the queue. 550 */ 551 lp->lwp_estcpu = ESTCPULIM(lp->lwp_estcpu + ESTCPUINCR); 552 553 /* 554 * Reducing p_origcpu over time causes more of our estcpu to be 555 * returned to the parent when we exit. This is a small tweak 556 * for the batch detection heuristic. 557 */ 558 if (lp->lwp_origcpu) 559 --lp->lwp_origcpu; 560 561 /* 562 * We can only safely call bsd4_resetpriority(), which uses spinlocks, 563 * if we aren't interrupting a thread that is using spinlocks. 564 * Otherwise we can deadlock with another cpu waiting for our read 565 * spinlocks to clear. 566 */ 567 if (gd->gd_spinlock_rd == NULL && gd->gd_spinlocks_wr == 0) 568 bsd4_resetpriority(lp); 569 else 570 need_user_resched(); 571 } 572 573 /* 574 * Called from acquire and from kern_synch's one-second timer (one of the 575 * callout helper threads) with a critical section held. 576 * 577 * Decay p_estcpu based on the number of ticks we haven't been running 578 * and our p_nice. As the load increases each process observes a larger 579 * number of idle ticks (because other processes are running in them). 580 * This observation leads to a larger correction which tends to make the 581 * system more 'batchy'. 582 * 583 * Note that no recalculation occurs for a process which sleeps and wakes 584 * up in the same tick. That is, a system doing thousands of context 585 * switches per second will still only do serious estcpu calculations 586 * ESTCPUFREQ times per second. 587 * 588 * MPSAFE 589 */ 590 static 591 void 592 bsd4_recalculate_estcpu(struct lwp *lp) 593 { 594 globaldata_t gd = mycpu; 595 sysclock_t cpbase; 596 int loadfac; 597 int ndecay; 598 int nticks; 599 int nleft; 600 601 /* 602 * We have to subtract periodic to get the last schedclock 603 * timeout time, otherwise we would get the upcoming timeout. 604 * Keep in mind that a process can migrate between cpus and 605 * while the scheduler clock should be very close, boundary 606 * conditions could lead to a small negative delta. 607 */ 608 cpbase = gd->gd_schedclock.time - gd->gd_schedclock.periodic; 609 610 if (lp->lwp_slptime > 1) { 611 /* 612 * Too much time has passed, do a coarse correction. 613 */ 614 lp->lwp_estcpu = lp->lwp_estcpu >> 1; 615 bsd4_resetpriority(lp); 616 lp->lwp_cpbase = cpbase; 617 lp->lwp_cpticks = 0; 618 } else if (lp->lwp_cpbase != cpbase) { 619 /* 620 * Adjust estcpu if we are in a different tick. Don't waste 621 * time if we are in the same tick. 622 * 623 * First calculate the number of ticks in the measurement 624 * interval. The nticks calculation can wind up 0 due to 625 * a bug in the handling of lwp_slptime (as yet not found), 626 * so make sure we do not get a divide by 0 panic. 627 */ 628 nticks = (cpbase - lp->lwp_cpbase) / gd->gd_schedclock.periodic; 629 if (nticks <= 0) 630 nticks = 1; 631 updatepcpu(lp, lp->lwp_cpticks, nticks); 632 633 if ((nleft = nticks - lp->lwp_cpticks) < 0) 634 nleft = 0; 635 if (usched_debug == lp->lwp_proc->p_pid) { 636 kprintf("pid %d tid %d estcpu %d cpticks %d nticks %d nleft %d", 637 lp->lwp_proc->p_pid, lp->lwp_tid, lp->lwp_estcpu, 638 lp->lwp_cpticks, nticks, nleft); 639 } 640 641 /* 642 * Calculate a decay value based on ticks remaining scaled 643 * down by the instantanious load and p_nice. 644 */ 645 if ((loadfac = bsd4_runqcount) < 2) 646 loadfac = 2; 647 ndecay = nleft * usched_bsd4_decay * 2 * 648 (PRIO_MAX * 2 - lp->lwp_proc->p_nice) / (loadfac * PRIO_MAX * 2); 649 650 /* 651 * Adjust p_estcpu. Handle a border case where batch jobs 652 * can get stalled long enough to decay to zero when they 653 * shouldn't. 654 */ 655 if (lp->lwp_estcpu > ndecay * 2) 656 lp->lwp_estcpu -= ndecay; 657 else 658 lp->lwp_estcpu >>= 1; 659 660 if (usched_debug == lp->lwp_proc->p_pid) 661 kprintf(" ndecay %d estcpu %d\n", ndecay, lp->lwp_estcpu); 662 bsd4_resetpriority(lp); 663 lp->lwp_cpbase = cpbase; 664 lp->lwp_cpticks = 0; 665 } 666 } 667 668 /* 669 * Compute the priority of a process when running in user mode. 670 * Arrange to reschedule if the resulting priority is better 671 * than that of the current process. 672 * 673 * This routine may be called with any process. 674 * 675 * This routine is called by fork1() for initial setup with the process 676 * of the run queue, and also may be called normally with the process on or 677 * off the run queue. 678 * 679 * MPSAFE 680 */ 681 static void 682 bsd4_resetpriority(struct lwp *lp) 683 { 684 bsd4_pcpu_t dd; 685 int newpriority; 686 u_short newrqtype; 687 int reschedcpu; 688 689 /* 690 * Calculate the new priority and queue type 691 */ 692 crit_enter(); 693 spin_lock_wr(&bsd4_spin); 694 695 newrqtype = lp->lwp_rtprio.type; 696 697 switch(newrqtype) { 698 case RTP_PRIO_REALTIME: 699 case RTP_PRIO_FIFO: 700 newpriority = PRIBASE_REALTIME + 701 (lp->lwp_rtprio.prio & PRIMASK); 702 break; 703 case RTP_PRIO_NORMAL: 704 newpriority = (lp->lwp_proc->p_nice - PRIO_MIN) * PPQ / NICEPPQ; 705 newpriority += lp->lwp_estcpu * PPQ / ESTCPUPPQ; 706 newpriority = newpriority * MAXPRI / (PRIO_RANGE * PPQ / 707 NICEPPQ + ESTCPUMAX * PPQ / ESTCPUPPQ); 708 newpriority = PRIBASE_NORMAL + (newpriority & PRIMASK); 709 break; 710 case RTP_PRIO_IDLE: 711 newpriority = PRIBASE_IDLE + (lp->lwp_rtprio.prio & PRIMASK); 712 break; 713 case RTP_PRIO_THREAD: 714 newpriority = PRIBASE_THREAD + (lp->lwp_rtprio.prio & PRIMASK); 715 break; 716 default: 717 panic("Bad RTP_PRIO %d", newrqtype); 718 /* NOT REACHED */ 719 } 720 721 /* 722 * The newpriority incorporates the queue type so do a simple masked 723 * check to determine if the process has moved to another queue. If 724 * it has, and it is currently on a run queue, then move it. 725 */ 726 if ((lp->lwp_priority ^ newpriority) & ~PPQMASK) { 727 lp->lwp_priority = newpriority; 728 if (lp->lwp_flag & LWP_ONRUNQ) { 729 bsd4_remrunqueue_locked(lp); 730 lp->lwp_rqtype = newrqtype; 731 lp->lwp_rqindex = (newpriority & PRIMASK) / PPQ; 732 bsd4_setrunqueue_locked(lp); 733 reschedcpu = lp->lwp_thread->td_gd->gd_cpuid; 734 } else { 735 lp->lwp_rqtype = newrqtype; 736 lp->lwp_rqindex = (newpriority & PRIMASK) / PPQ; 737 reschedcpu = -1; 738 } 739 } else { 740 lp->lwp_priority = newpriority; 741 reschedcpu = -1; 742 } 743 spin_unlock_wr(&bsd4_spin); 744 745 /* 746 * Determine if we need to reschedule the target cpu. This only 747 * occurs if the LWP is already on a scheduler queue, which means 748 * that idle cpu notification has already occured. At most we 749 * need only issue a need_user_resched() on the appropriate cpu. 750 * 751 * The LWP may be owned by a CPU different from the current one, 752 * in which case dd->uschedcp may be modified without an MP lock 753 * or a spinlock held. The worst that happens is that the code 754 * below causes a spurious need_user_resched() on the target CPU 755 * and dd->pri to be wrong for a short period of time, both of 756 * which are harmless. 757 */ 758 if (reschedcpu >= 0) { 759 dd = &bsd4_pcpu[reschedcpu]; 760 if ((dd->upri & ~PRIMASK) > (lp->lwp_priority & ~PRIMASK)) { 761 dd->upri = lp->lwp_priority; 762 #ifdef SMP 763 if (reschedcpu == mycpu->gd_cpuid) { 764 need_user_resched(); 765 } else { 766 lwkt_send_ipiq(lp->lwp_thread->td_gd, 767 need_user_resched_remote, NULL); 768 } 769 #else 770 need_user_resched(); 771 #endif 772 } 773 } 774 crit_exit(); 775 } 776 777 /* 778 * MPSAFE 779 */ 780 static 781 void 782 bsd4_yield(struct lwp *lp) 783 { 784 #if 0 785 /* FUTURE (or something similar) */ 786 switch(lp->lwp_rqtype) { 787 case RTP_PRIO_NORMAL: 788 lp->lwp_estcpu = ESTCPULIM(lp->lwp_estcpu + ESTCPUINCR); 789 break; 790 default: 791 break; 792 } 793 #endif 794 need_user_resched(); 795 } 796 797 /* 798 * Called from fork1() when a new child process is being created. 799 * 800 * Give the child process an initial estcpu that is more batch then 801 * its parent and dock the parent for the fork (but do not 802 * reschedule the parent). This comprises the main part of our batch 803 * detection heuristic for both parallel forking and sequential execs. 804 * 805 * Interactive processes will decay the boosted estcpu quickly while batch 806 * processes will tend to compound it. 807 * XXX lwp should be "spawning" instead of "forking" 808 * 809 * MPSAFE 810 */ 811 static void 812 bsd4_forking(struct lwp *plp, struct lwp *lp) 813 { 814 lp->lwp_estcpu = ESTCPULIM(plp->lwp_estcpu + ESTCPUPPQ); 815 lp->lwp_origcpu = lp->lwp_estcpu; 816 plp->lwp_estcpu = ESTCPULIM(plp->lwp_estcpu + ESTCPUPPQ); 817 } 818 819 /* 820 * Called when the parent reaps a child. Propogate cpu use by the child 821 * back to the parent. 822 * 823 * MPSAFE 824 */ 825 static void 826 bsd4_exiting(struct lwp *plp, struct lwp *lp) 827 { 828 int delta; 829 830 if (plp->lwp_proc->p_pid != 1) { 831 delta = lp->lwp_estcpu - lp->lwp_origcpu; 832 if (delta > 0) 833 plp->lwp_estcpu = ESTCPULIM(plp->lwp_estcpu + delta); 834 } 835 } 836 837 838 /* 839 * chooseproc() is called when a cpu needs a user process to LWKT schedule, 840 * it selects a user process and returns it. If chklp is non-NULL and chklp 841 * has a better or equal priority then the process that would otherwise be 842 * chosen, NULL is returned. 843 * 844 * Until we fix the RUNQ code the chklp test has to be strict or we may 845 * bounce between processes trying to acquire the current process designation. 846 * 847 * MPSAFE - must be called with bsd4_spin exclusive held. The spinlock is 848 * left intact through the entire routine. 849 */ 850 static 851 struct lwp * 852 chooseproc_locked(struct lwp *chklp) 853 { 854 struct lwp *lp; 855 struct rq *q; 856 u_int32_t *which, *which2; 857 u_int32_t pri; 858 u_int32_t rtqbits; 859 u_int32_t tsqbits; 860 u_int32_t idqbits; 861 cpumask_t cpumask; 862 863 rtqbits = bsd4_rtqueuebits; 864 tsqbits = bsd4_queuebits; 865 idqbits = bsd4_idqueuebits; 866 cpumask = mycpu->gd_cpumask; 867 868 #ifdef SMP 869 again: 870 #endif 871 if (rtqbits) { 872 pri = bsfl(rtqbits); 873 q = &bsd4_rtqueues[pri]; 874 which = &bsd4_rtqueuebits; 875 which2 = &rtqbits; 876 } else if (tsqbits) { 877 pri = bsfl(tsqbits); 878 q = &bsd4_queues[pri]; 879 which = &bsd4_queuebits; 880 which2 = &tsqbits; 881 } else if (idqbits) { 882 pri = bsfl(idqbits); 883 q = &bsd4_idqueues[pri]; 884 which = &bsd4_idqueuebits; 885 which2 = &idqbits; 886 } else { 887 return NULL; 888 } 889 lp = TAILQ_FIRST(q); 890 KASSERT(lp, ("chooseproc: no lwp on busy queue")); 891 892 #ifdef SMP 893 while ((lp->lwp_cpumask & cpumask) == 0) { 894 lp = TAILQ_NEXT(lp, lwp_procq); 895 if (lp == NULL) { 896 *which2 &= ~(1 << pri); 897 goto again; 898 } 899 } 900 #endif 901 902 /* 903 * If the passed lwp <chklp> is reasonably close to the selected 904 * lwp <lp>, return NULL (indicating that <chklp> should be kept). 905 * 906 * Note that we must error on the side of <chklp> to avoid bouncing 907 * between threads in the acquire code. 908 */ 909 if (chklp) { 910 if (chklp->lwp_priority < lp->lwp_priority + PPQ) 911 return(NULL); 912 } 913 914 #ifdef SMP 915 /* 916 * If the chosen lwp does not reside on this cpu spend a few 917 * cycles looking for a better candidate at the same priority level. 918 * This is a fallback check, setrunqueue() tries to wakeup the 919 * correct cpu and is our front-line affinity. 920 */ 921 if (lp->lwp_thread->td_gd != mycpu && 922 (chklp = TAILQ_NEXT(lp, lwp_procq)) != NULL 923 ) { 924 if (chklp->lwp_thread->td_gd == mycpu) { 925 ++choose_affinity; 926 lp = chklp; 927 } 928 } 929 #endif 930 931 TAILQ_REMOVE(q, lp, lwp_procq); 932 --bsd4_runqcount; 933 if (TAILQ_EMPTY(q)) 934 *which &= ~(1 << pri); 935 KASSERT((lp->lwp_flag & LWP_ONRUNQ) != 0, ("not on runq6!")); 936 lp->lwp_flag &= ~LWP_ONRUNQ; 937 return lp; 938 } 939 940 #ifdef SMP 941 942 /* 943 * Called via an ipi message to reschedule on another cpu. If no 944 * user thread is active on the target cpu we wake the scheduler 945 * helper thread up to help schedule one. 946 * 947 * MPSAFE 948 */ 949 static 950 void 951 need_user_resched_remote(void *dummy) 952 { 953 globaldata_t gd = mycpu; 954 bsd4_pcpu_t dd = &bsd4_pcpu[gd->gd_cpuid]; 955 956 if (dd->uschedcp == NULL && (bsd4_rdyprocmask & gd->gd_cpumask)) { 957 atomic_clear_int(&bsd4_rdyprocmask, gd->gd_cpumask); 958 lwkt_schedule(&dd->helper_thread); 959 } else { 960 need_user_resched(); 961 } 962 } 963 964 #endif 965 966 /* 967 * bsd4_remrunqueue_locked() removes a given process from the run queue 968 * that it is on, clearing the queue busy bit if it becomes empty. 969 * 970 * Note that user process scheduler is different from the LWKT schedule. 971 * The user process scheduler only manages user processes but it uses LWKT 972 * underneath, and a user process operating in the kernel will often be 973 * 'released' from our management. 974 * 975 * MPSAFE - bsd4_spin must be held exclusively on call 976 */ 977 static void 978 bsd4_remrunqueue_locked(struct lwp *lp) 979 { 980 struct rq *q; 981 u_int32_t *which; 982 u_int8_t pri; 983 984 KKASSERT(lp->lwp_flag & LWP_ONRUNQ); 985 lp->lwp_flag &= ~LWP_ONRUNQ; 986 --bsd4_runqcount; 987 KKASSERT(bsd4_runqcount >= 0); 988 989 pri = lp->lwp_rqindex; 990 switch(lp->lwp_rqtype) { 991 case RTP_PRIO_NORMAL: 992 q = &bsd4_queues[pri]; 993 which = &bsd4_queuebits; 994 break; 995 case RTP_PRIO_REALTIME: 996 case RTP_PRIO_FIFO: 997 q = &bsd4_rtqueues[pri]; 998 which = &bsd4_rtqueuebits; 999 break; 1000 case RTP_PRIO_IDLE: 1001 q = &bsd4_idqueues[pri]; 1002 which = &bsd4_idqueuebits; 1003 break; 1004 default: 1005 panic("remrunqueue: invalid rtprio type"); 1006 /* NOT REACHED */ 1007 } 1008 TAILQ_REMOVE(q, lp, lwp_procq); 1009 if (TAILQ_EMPTY(q)) { 1010 KASSERT((*which & (1 << pri)) != 0, 1011 ("remrunqueue: remove from empty queue")); 1012 *which &= ~(1 << pri); 1013 } 1014 } 1015 1016 /* 1017 * bsd4_setrunqueue_locked() 1018 * 1019 * Add a process whos rqtype and rqindex had previously been calculated 1020 * onto the appropriate run queue. Determine if the addition requires 1021 * a reschedule on a cpu and return the cpuid or -1. 1022 * 1023 * NOTE: Lower priorities are better priorities. 1024 * 1025 * MPSAFE - bsd4_spin must be held exclusively on call 1026 */ 1027 static void 1028 bsd4_setrunqueue_locked(struct lwp *lp) 1029 { 1030 struct rq *q; 1031 u_int32_t *which; 1032 int pri; 1033 1034 KKASSERT((lp->lwp_flag & LWP_ONRUNQ) == 0); 1035 lp->lwp_flag |= LWP_ONRUNQ; 1036 ++bsd4_runqcount; 1037 1038 pri = lp->lwp_rqindex; 1039 1040 switch(lp->lwp_rqtype) { 1041 case RTP_PRIO_NORMAL: 1042 q = &bsd4_queues[pri]; 1043 which = &bsd4_queuebits; 1044 break; 1045 case RTP_PRIO_REALTIME: 1046 case RTP_PRIO_FIFO: 1047 q = &bsd4_rtqueues[pri]; 1048 which = &bsd4_rtqueuebits; 1049 break; 1050 case RTP_PRIO_IDLE: 1051 q = &bsd4_idqueues[pri]; 1052 which = &bsd4_idqueuebits; 1053 break; 1054 default: 1055 panic("remrunqueue: invalid rtprio type"); 1056 /* NOT REACHED */ 1057 } 1058 1059 /* 1060 * Add to the correct queue and set the appropriate bit. If no 1061 * lower priority (i.e. better) processes are in the queue then 1062 * we want a reschedule, calculate the best cpu for the job. 1063 * 1064 * Always run reschedules on the LWPs original cpu. 1065 */ 1066 TAILQ_INSERT_TAIL(q, lp, lwp_procq); 1067 *which |= 1 << pri; 1068 } 1069 1070 #ifdef SMP 1071 1072 /* 1073 * For SMP systems a user scheduler helper thread is created for each 1074 * cpu and is used to allow one cpu to wakeup another for the purposes of 1075 * scheduling userland threads from setrunqueue(). UP systems do not 1076 * need the helper since there is only one cpu. We can't use the idle 1077 * thread for this because we need to hold the MP lock. Additionally, 1078 * doing things this way allows us to HLT idle cpus on MP systems. 1079 * 1080 * MPSAFE 1081 */ 1082 static void 1083 sched_thread(void *dummy) 1084 { 1085 globaldata_t gd; 1086 bsd4_pcpu_t dd; 1087 struct lwp *nlp; 1088 cpumask_t cpumask; 1089 int cpuid; 1090 #if 0 1091 cpumask_t tmpmask; 1092 int tmpid; 1093 #endif 1094 1095 gd = mycpu; 1096 cpuid = gd->gd_cpuid; /* doesn't change */ 1097 cpumask = gd->gd_cpumask; /* doesn't change */ 1098 dd = &bsd4_pcpu[cpuid]; 1099 1100 /* 1101 * The scheduler thread does not need to hold the MP lock. Since we 1102 * are woken up only when no user processes are scheduled on a cpu, we 1103 * can run at an ultra low priority. 1104 */ 1105 rel_mplock(); 1106 lwkt_setpri_self(TDPRI_USER_SCHEDULER); 1107 1108 for (;;) { 1109 /* 1110 * We use the LWKT deschedule-interlock trick to avoid racing 1111 * bsd4_rdyprocmask. This means we cannot block through to the 1112 * manual lwkt_switch() call we make below. 1113 */ 1114 crit_enter_gd(gd); 1115 lwkt_deschedule_self(gd->gd_curthread); 1116 spin_lock_wr(&bsd4_spin); 1117 atomic_set_int(&bsd4_rdyprocmask, cpumask); 1118 1119 clear_user_resched(); /* This satisfied the reschedule request */ 1120 dd->rrcount = 0; /* Reset the round-robin counter */ 1121 1122 if ((bsd4_curprocmask & cpumask) == 0) { 1123 /* 1124 * No thread is currently scheduled. 1125 */ 1126 KKASSERT(dd->uschedcp == NULL); 1127 if ((nlp = chooseproc_locked(NULL)) != NULL) { 1128 atomic_set_int(&bsd4_curprocmask, cpumask); 1129 dd->upri = nlp->lwp_priority; 1130 dd->uschedcp = nlp; 1131 spin_unlock_wr(&bsd4_spin); 1132 lwkt_acquire(nlp->lwp_thread); 1133 lwkt_schedule(nlp->lwp_thread); 1134 } else { 1135 spin_unlock_wr(&bsd4_spin); 1136 } 1137 #if 0 1138 /* 1139 * Disabled for now, this can create an infinite loop. 1140 */ 1141 } else if (bsd4_runqcount) { 1142 /* 1143 * Someone scheduled us but raced. In order to not lose 1144 * track of the fact that there may be a LWP ready to go, 1145 * forward the request to another cpu if available. 1146 * 1147 * Rotate through cpus starting with cpuid + 1. Since cpuid 1148 * is already masked out by gd_other_cpus, just use ~cpumask. 1149 */ 1150 tmpmask = bsd4_rdyprocmask & mycpu->gd_other_cpus & 1151 ~bsd4_curprocmask; 1152 if (tmpmask) { 1153 if (tmpmask & ~(cpumask - 1)) 1154 tmpid = bsfl(tmpmask & ~(cpumask - 1)); 1155 else 1156 tmpid = bsfl(tmpmask); 1157 bsd4_scancpu = tmpid; 1158 atomic_clear_int(&bsd4_rdyprocmask, 1 << tmpid); 1159 spin_unlock_wr(&bsd4_spin); 1160 lwkt_schedule(&bsd4_pcpu[tmpid].helper_thread); 1161 } else { 1162 spin_unlock_wr(&bsd4_spin); 1163 } 1164 #endif 1165 } else { 1166 /* 1167 * The runq is empty. 1168 */ 1169 spin_unlock_wr(&bsd4_spin); 1170 } 1171 crit_exit_gd(gd); 1172 lwkt_switch(); 1173 } 1174 } 1175 1176 /* 1177 * Setup our scheduler helpers. Note that curprocmask bit 0 has already 1178 * been cleared by rqinit() and we should not mess with it further. 1179 */ 1180 static void 1181 sched_thread_cpu_init(void) 1182 { 1183 int i; 1184 1185 if (bootverbose) 1186 kprintf("start scheduler helpers on cpus:"); 1187 1188 for (i = 0; i < ncpus; ++i) { 1189 bsd4_pcpu_t dd = &bsd4_pcpu[i]; 1190 cpumask_t mask = 1 << i; 1191 1192 if ((mask & smp_active_mask) == 0) 1193 continue; 1194 1195 if (bootverbose) 1196 kprintf(" %d", i); 1197 1198 lwkt_create(sched_thread, NULL, NULL, &dd->helper_thread, 1199 TDF_STOPREQ, i, "usched %d", i); 1200 1201 /* 1202 * Allow user scheduling on the target cpu. cpu #0 has already 1203 * been enabled in rqinit(). 1204 */ 1205 if (i) 1206 atomic_clear_int(&bsd4_curprocmask, mask); 1207 atomic_set_int(&bsd4_rdyprocmask, mask); 1208 dd->upri = PRIBASE_NULL; 1209 } 1210 if (bootverbose) 1211 kprintf("\n"); 1212 } 1213 SYSINIT(uschedtd, SI_BOOT2_USCHED, SI_ORDER_SECOND, 1214 sched_thread_cpu_init, NULL) 1215 1216 #endif 1217 1218