1 /*- 2 * Copyright (c) 1982, 1986, 1990, 1991, 1993 3 * The Regents of the University of California. All rights reserved. 4 * (c) UNIX System Laboratories, Inc. 5 * All or some portions of this file are derived from material licensed 6 * to the University of California by American Telephone and Telegraph 7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with 8 * the permission of UNIX System Laboratories, Inc. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 4. Neither the name of the University nor the names of its contributors 19 * may be used to endorse or promote products derived from this software 20 * without specific prior written permission. 21 * 22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 32 * SUCH DAMAGE. 33 * 34 * @(#)kern_synch.c 8.9 (Berkeley) 5/19/95 35 */ 36 37 #include <sys/cdefs.h> 38 __FBSDID("$FreeBSD$"); 39 40 #include "opt_ktrace.h" 41 #include "opt_sched.h" 42 43 #include <sys/param.h> 44 #include <sys/systm.h> 45 #include <sys/condvar.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/resourcevar.h> 53 #include <sys/sched.h> 54 #include <sys/sdt.h> 55 #include <sys/signalvar.h> 56 #include <sys/sleepqueue.h> 57 #include <sys/smp.h> 58 #include <sys/sx.h> 59 #include <sys/sysctl.h> 60 #include <sys/sysproto.h> 61 #include <sys/vmmeter.h> 62 #ifdef KTRACE 63 #include <sys/uio.h> 64 #include <sys/ktrace.h> 65 #endif 66 67 #include <machine/cpu.h> 68 69 #define KTDSTATE(td) \ 70 (((td)->td_inhibitors & TDI_SLEEPING) != 0 ? "sleep" : \ 71 ((td)->td_inhibitors & TDI_SUSPENDED) != 0 ? "suspended" : \ 72 ((td)->td_inhibitors & TDI_SWAPPED) != 0 ? "swapped" : \ 73 ((td)->td_inhibitors & TDI_LOCK) != 0 ? "blocked" : \ 74 ((td)->td_inhibitors & TDI_IWAIT) != 0 ? "iwait" : "yielding") 75 76 static void synch_setup(void *dummy); 77 SYSINIT(synch_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, synch_setup, 78 NULL); 79 80 int hogticks; 81 static uint8_t pause_wchan[MAXCPU]; 82 83 static struct callout loadav_callout; 84 85 struct loadavg averunnable = 86 { {0, 0, 0}, FSCALE }; /* load average, of runnable procs */ 87 /* 88 * Constants for averages over 1, 5, and 15 minutes 89 * when sampling at 5 second intervals. 90 */ 91 static fixpt_t cexp[3] = { 92 0.9200444146293232 * FSCALE, /* exp(-1/12) */ 93 0.9834714538216174 * FSCALE, /* exp(-1/60) */ 94 0.9944598480048967 * FSCALE, /* exp(-1/180) */ 95 }; 96 97 /* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */ 98 SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, SYSCTL_NULL_INT_PTR, FSCALE, ""); 99 100 static void loadav(void *arg); 101 102 SDT_PROVIDER_DECLARE(sched); 103 SDT_PROBE_DEFINE(sched, , , preempt); 104 105 static void 106 sleepinit(void *unused) 107 { 108 109 hogticks = (hz / 10) * 2; /* Default only. */ 110 init_sleepqueues(); 111 } 112 113 /* 114 * vmem tries to lock the sleepq mutexes when free'ing kva, so make sure 115 * it is available. 116 */ 117 SYSINIT(sleepinit, SI_SUB_KMEM, SI_ORDER_ANY, sleepinit, 0); 118 119 /* 120 * General sleep call. Suspends the current thread until a wakeup is 121 * performed on the specified identifier. The thread will then be made 122 * runnable with the specified priority. Sleeps at most sbt units of time 123 * (0 means no timeout). If pri includes the PCATCH flag, let signals 124 * interrupt the sleep, otherwise ignore them while sleeping. Returns 0 if 125 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a 126 * signal becomes pending, ERESTART is returned if the current system 127 * call should be restarted if possible, and EINTR is returned if the system 128 * call should be interrupted by the signal (return EINTR). 129 * 130 * The lock argument is unlocked before the caller is suspended, and 131 * re-locked before _sleep() returns. If priority includes the PDROP 132 * flag the lock is not re-locked before returning. 133 */ 134 int 135 _sleep(void *ident, struct lock_object *lock, int priority, 136 const char *wmesg, sbintime_t sbt, sbintime_t pr, int flags) 137 { 138 struct thread *td; 139 struct proc *p; 140 struct lock_class *class; 141 uintptr_t lock_state; 142 int catch, pri, rval, sleepq_flags; 143 WITNESS_SAVE_DECL(lock_witness); 144 145 td = curthread; 146 p = td->td_proc; 147 #ifdef KTRACE 148 if (KTRPOINT(td, KTR_CSW)) 149 ktrcsw(1, 0, wmesg); 150 #endif 151 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, lock, 152 "Sleeping on \"%s\"", wmesg); 153 KASSERT(sbt != 0 || mtx_owned(&Giant) || lock != NULL, 154 ("sleeping without a lock")); 155 KASSERT(p != NULL, ("msleep1")); 156 KASSERT(ident != NULL && TD_IS_RUNNING(td), ("msleep")); 157 if (priority & PDROP) 158 KASSERT(lock != NULL && lock != &Giant.lock_object, 159 ("PDROP requires a non-Giant lock")); 160 if (lock != NULL) 161 class = LOCK_CLASS(lock); 162 else 163 class = NULL; 164 165 if (SCHEDULER_STOPPED()) { 166 if (lock != NULL && priority & PDROP) 167 class->lc_unlock(lock); 168 return (0); 169 } 170 catch = priority & PCATCH; 171 pri = priority & PRIMASK; 172 173 /* 174 * If we are already on a sleep queue, then remove us from that 175 * sleep queue first. We have to do this to handle recursive 176 * sleeps. 177 */ 178 if (TD_ON_SLEEPQ(td)) 179 sleepq_remove(td, td->td_wchan); 180 181 if ((uint8_t *)ident >= &pause_wchan[0] && 182 (uint8_t *)ident <= &pause_wchan[MAXCPU - 1]) 183 sleepq_flags = SLEEPQ_PAUSE; 184 else 185 sleepq_flags = SLEEPQ_SLEEP; 186 if (catch) 187 sleepq_flags |= SLEEPQ_INTERRUPTIBLE; 188 189 sleepq_lock(ident); 190 CTR5(KTR_PROC, "sleep: thread %ld (pid %ld, %s) on %s (%p)", 191 td->td_tid, p->p_pid, td->td_name, wmesg, ident); 192 193 if (lock == &Giant.lock_object) 194 mtx_assert(&Giant, MA_OWNED); 195 DROP_GIANT(); 196 if (lock != NULL && lock != &Giant.lock_object && 197 !(class->lc_flags & LC_SLEEPABLE)) { 198 WITNESS_SAVE(lock, lock_witness); 199 lock_state = class->lc_unlock(lock); 200 } else 201 /* GCC needs to follow the Yellow Brick Road */ 202 lock_state = -1; 203 204 /* 205 * We put ourselves on the sleep queue and start our timeout 206 * before calling thread_suspend_check, as we could stop there, 207 * and a wakeup or a SIGCONT (or both) could occur while we were 208 * stopped without resuming us. Thus, we must be ready for sleep 209 * when cursig() is called. If the wakeup happens while we're 210 * stopped, then td will no longer be on a sleep queue upon 211 * return from cursig(). 212 */ 213 sleepq_add(ident, lock, wmesg, sleepq_flags, 0); 214 if (sbt != 0) 215 sleepq_set_timeout_sbt(ident, sbt, pr, flags); 216 if (lock != NULL && class->lc_flags & LC_SLEEPABLE) { 217 sleepq_release(ident); 218 WITNESS_SAVE(lock, lock_witness); 219 lock_state = class->lc_unlock(lock); 220 sleepq_lock(ident); 221 } 222 if (sbt != 0 && catch) 223 rval = sleepq_timedwait_sig(ident, pri); 224 else if (sbt != 0) 225 rval = sleepq_timedwait(ident, pri); 226 else if (catch) 227 rval = sleepq_wait_sig(ident, pri); 228 else { 229 sleepq_wait(ident, pri); 230 rval = 0; 231 } 232 #ifdef KTRACE 233 if (KTRPOINT(td, KTR_CSW)) 234 ktrcsw(0, 0, wmesg); 235 #endif 236 PICKUP_GIANT(); 237 if (lock != NULL && lock != &Giant.lock_object && !(priority & PDROP)) { 238 class->lc_lock(lock, lock_state); 239 WITNESS_RESTORE(lock, lock_witness); 240 } 241 return (rval); 242 } 243 244 int 245 msleep_spin_sbt(void *ident, struct mtx *mtx, const char *wmesg, 246 sbintime_t sbt, sbintime_t pr, int flags) 247 { 248 struct thread *td; 249 struct proc *p; 250 int rval; 251 WITNESS_SAVE_DECL(mtx); 252 253 td = curthread; 254 p = td->td_proc; 255 KASSERT(mtx != NULL, ("sleeping without a mutex")); 256 KASSERT(p != NULL, ("msleep1")); 257 KASSERT(ident != NULL && TD_IS_RUNNING(td), ("msleep")); 258 259 if (SCHEDULER_STOPPED()) 260 return (0); 261 262 sleepq_lock(ident); 263 CTR5(KTR_PROC, "msleep_spin: thread %ld (pid %ld, %s) on %s (%p)", 264 td->td_tid, p->p_pid, td->td_name, wmesg, ident); 265 266 DROP_GIANT(); 267 mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED); 268 WITNESS_SAVE(&mtx->lock_object, mtx); 269 mtx_unlock_spin(mtx); 270 271 /* 272 * We put ourselves on the sleep queue and start our timeout. 273 */ 274 sleepq_add(ident, &mtx->lock_object, wmesg, SLEEPQ_SLEEP, 0); 275 if (sbt != 0) 276 sleepq_set_timeout_sbt(ident, sbt, pr, flags); 277 278 /* 279 * Can't call ktrace with any spin locks held so it can lock the 280 * ktrace_mtx lock, and WITNESS_WARN considers it an error to hold 281 * any spin lock. Thus, we have to drop the sleepq spin lock while 282 * we handle those requests. This is safe since we have placed our 283 * thread on the sleep queue already. 284 */ 285 #ifdef KTRACE 286 if (KTRPOINT(td, KTR_CSW)) { 287 sleepq_release(ident); 288 ktrcsw(1, 0, wmesg); 289 sleepq_lock(ident); 290 } 291 #endif 292 #ifdef WITNESS 293 sleepq_release(ident); 294 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, "Sleeping on \"%s\"", 295 wmesg); 296 sleepq_lock(ident); 297 #endif 298 if (sbt != 0) 299 rval = sleepq_timedwait(ident, 0); 300 else { 301 sleepq_wait(ident, 0); 302 rval = 0; 303 } 304 #ifdef KTRACE 305 if (KTRPOINT(td, KTR_CSW)) 306 ktrcsw(0, 0, wmesg); 307 #endif 308 PICKUP_GIANT(); 309 mtx_lock_spin(mtx); 310 WITNESS_RESTORE(&mtx->lock_object, mtx); 311 return (rval); 312 } 313 314 /* 315 * pause() delays the calling thread by the given number of system ticks. 316 * During cold bootup, pause() uses the DELAY() function instead of 317 * the tsleep() function to do the waiting. The "timo" argument must be 318 * greater than or equal to zero. A "timo" value of zero is equivalent 319 * to a "timo" value of one. 320 */ 321 int 322 pause_sbt(const char *wmesg, sbintime_t sbt, sbintime_t pr, int flags) 323 { 324 KASSERT(sbt >= 0, ("pause: timeout must be >= 0")); 325 326 /* silently convert invalid timeouts */ 327 if (sbt == 0) 328 sbt = tick_sbt; 329 330 if (cold || kdb_active || SCHEDULER_STOPPED()) { 331 /* 332 * We delay one second at a time to avoid overflowing the 333 * system specific DELAY() function(s): 334 */ 335 while (sbt >= SBT_1S) { 336 DELAY(1000000); 337 sbt -= SBT_1S; 338 } 339 /* Do the delay remainder, if any */ 340 sbt = howmany(sbt, SBT_1US); 341 if (sbt > 0) 342 DELAY(sbt); 343 return (0); 344 } 345 return (_sleep(&pause_wchan[curcpu], NULL, 0, wmesg, sbt, pr, flags)); 346 } 347 348 /* 349 * Make all threads sleeping on the specified identifier runnable. 350 */ 351 void 352 wakeup(void *ident) 353 { 354 int wakeup_swapper; 355 356 sleepq_lock(ident); 357 wakeup_swapper = sleepq_broadcast(ident, SLEEPQ_SLEEP, 0, 0); 358 sleepq_release(ident); 359 if (wakeup_swapper) { 360 KASSERT(ident != &proc0, 361 ("wakeup and wakeup_swapper and proc0")); 362 kick_proc0(); 363 } 364 } 365 366 /* 367 * Make a thread sleeping on the specified identifier runnable. 368 * May wake more than one thread if a target thread is currently 369 * swapped out. 370 */ 371 void 372 wakeup_one(void *ident) 373 { 374 int wakeup_swapper; 375 376 sleepq_lock(ident); 377 wakeup_swapper = sleepq_signal(ident, SLEEPQ_SLEEP, 0, 0); 378 sleepq_release(ident); 379 if (wakeup_swapper) 380 kick_proc0(); 381 } 382 383 static void 384 kdb_switch(void) 385 { 386 thread_unlock(curthread); 387 kdb_backtrace(); 388 kdb_reenter(); 389 panic("%s: did not reenter debugger", __func__); 390 } 391 392 /* 393 * The machine independent parts of context switching. 394 */ 395 void 396 mi_switch(int flags, struct thread *newtd) 397 { 398 uint64_t runtime, new_switchtime; 399 struct thread *td; 400 401 td = curthread; /* XXX */ 402 THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED); 403 KASSERT(!TD_ON_RUNQ(td), ("mi_switch: called by old code")); 404 #ifdef INVARIANTS 405 if (!TD_ON_LOCK(td) && !TD_IS_RUNNING(td)) 406 mtx_assert(&Giant, MA_NOTOWNED); 407 #endif 408 KASSERT(td->td_critnest == 1 || panicstr, 409 ("mi_switch: switch in a critical section")); 410 KASSERT((flags & (SW_INVOL | SW_VOL)) != 0, 411 ("mi_switch: switch must be voluntary or involuntary")); 412 KASSERT(newtd != curthread, ("mi_switch: preempting back to ourself")); 413 414 /* 415 * Don't perform context switches from the debugger. 416 */ 417 if (kdb_active) 418 kdb_switch(); 419 if (SCHEDULER_STOPPED()) 420 return; 421 if (flags & SW_VOL) { 422 td->td_ru.ru_nvcsw++; 423 td->td_swvoltick = ticks; 424 } else { 425 td->td_ru.ru_nivcsw++; 426 td->td_swinvoltick = ticks; 427 } 428 #ifdef SCHED_STATS 429 SCHED_STAT_INC(sched_switch_stats[flags & SW_TYPE_MASK]); 430 #endif 431 /* 432 * Compute the amount of time during which the current 433 * thread was running, and add that to its total so far. 434 */ 435 new_switchtime = cpu_ticks(); 436 runtime = new_switchtime - PCPU_GET(switchtime); 437 td->td_runtime += runtime; 438 td->td_incruntime += runtime; 439 PCPU_SET(switchtime, new_switchtime); 440 td->td_generation++; /* bump preempt-detect counter */ 441 PCPU_INC(cnt.v_swtch); 442 PCPU_SET(switchticks, ticks); 443 CTR4(KTR_PROC, "mi_switch: old thread %ld (td_sched %p, pid %ld, %s)", 444 td->td_tid, td_get_sched(td), td->td_proc->p_pid, td->td_name); 445 #if (KTR_COMPILE & KTR_SCHED) != 0 446 if (TD_IS_IDLETHREAD(td)) 447 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "idle", 448 "prio:%d", td->td_priority); 449 else 450 KTR_STATE3(KTR_SCHED, "thread", sched_tdname(td), KTDSTATE(td), 451 "prio:%d", td->td_priority, "wmesg:\"%s\"", td->td_wmesg, 452 "lockname:\"%s\"", td->td_lockname); 453 #endif 454 SDT_PROBE0(sched, , , preempt); 455 sched_switch(td, newtd, flags); 456 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running", 457 "prio:%d", td->td_priority); 458 459 CTR4(KTR_PROC, "mi_switch: new thread %ld (td_sched %p, pid %ld, %s)", 460 td->td_tid, td_get_sched(td), td->td_proc->p_pid, td->td_name); 461 462 /* 463 * If the last thread was exiting, finish cleaning it up. 464 */ 465 if ((td = PCPU_GET(deadthread))) { 466 PCPU_SET(deadthread, NULL); 467 thread_stash(td); 468 } 469 } 470 471 /* 472 * Change thread state to be runnable, placing it on the run queue if 473 * it is in memory. If it is swapped out, return true so our caller 474 * will know to awaken the swapper. 475 */ 476 int 477 setrunnable(struct thread *td) 478 { 479 480 THREAD_LOCK_ASSERT(td, MA_OWNED); 481 KASSERT(td->td_proc->p_state != PRS_ZOMBIE, 482 ("setrunnable: pid %d is a zombie", td->td_proc->p_pid)); 483 switch (td->td_state) { 484 case TDS_RUNNING: 485 case TDS_RUNQ: 486 return (0); 487 case TDS_INHIBITED: 488 /* 489 * If we are only inhibited because we are swapped out 490 * then arange to swap in this process. Otherwise just return. 491 */ 492 if (td->td_inhibitors != TDI_SWAPPED) 493 return (0); 494 /* FALLTHROUGH */ 495 case TDS_CAN_RUN: 496 break; 497 default: 498 printf("state is 0x%x", td->td_state); 499 panic("setrunnable(2)"); 500 } 501 if ((td->td_flags & TDF_INMEM) == 0) { 502 if ((td->td_flags & TDF_SWAPINREQ) == 0) { 503 td->td_flags |= TDF_SWAPINREQ; 504 return (1); 505 } 506 } else 507 sched_wakeup(td); 508 return (0); 509 } 510 511 /* 512 * Compute a tenex style load average of a quantity on 513 * 1, 5 and 15 minute intervals. 514 */ 515 static void 516 loadav(void *arg) 517 { 518 int i, nrun; 519 struct loadavg *avg; 520 521 nrun = sched_load(); 522 avg = &averunnable; 523 524 for (i = 0; i < 3; i++) 525 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] + 526 nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT; 527 528 /* 529 * Schedule the next update to occur after 5 seconds, but add a 530 * random variation to avoid synchronisation with processes that 531 * run at regular intervals. 532 */ 533 callout_reset_sbt(&loadav_callout, 534 SBT_1US * (4000000 + (int)(random() % 2000001)), SBT_1US, 535 loadav, NULL, C_DIRECT_EXEC | C_PREL(32)); 536 } 537 538 /* ARGSUSED */ 539 static void 540 synch_setup(void *dummy) 541 { 542 callout_init(&loadav_callout, 1); 543 544 /* Kick off timeout driven events by calling first time. */ 545 loadav(NULL); 546 } 547 548 int 549 should_yield(void) 550 { 551 552 return ((u_int)ticks - (u_int)curthread->td_swvoltick >= hogticks); 553 } 554 555 void 556 maybe_yield(void) 557 { 558 559 if (should_yield()) 560 kern_yield(PRI_USER); 561 } 562 563 void 564 kern_yield(int prio) 565 { 566 struct thread *td; 567 568 td = curthread; 569 DROP_GIANT(); 570 thread_lock(td); 571 if (prio == PRI_USER) 572 prio = td->td_user_pri; 573 if (prio >= 0) 574 sched_prio(td, prio); 575 mi_switch(SW_VOL | SWT_RELINQUISH, NULL); 576 thread_unlock(td); 577 PICKUP_GIANT(); 578 } 579 580 /* 581 * General purpose yield system call. 582 */ 583 int 584 sys_yield(struct thread *td, struct yield_args *uap) 585 { 586 587 thread_lock(td); 588 if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE) 589 sched_prio(td, PRI_MAX_TIMESHARE); 590 mi_switch(SW_VOL | SWT_RELINQUISH, NULL); 591 thread_unlock(td); 592 td->td_retval[0] = 0; 593 return (0); 594 } 595