kern_synch.c revision 126487
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 * 3. All advertising materials mentioning features or use of this software 19 * must display the following acknowledgement: 20 * This product includes software developed by the University of 21 * California, Berkeley and its contributors. 22 * 4. Neither the name of the University nor the names of its contributors 23 * may be used to endorse or promote products derived from this software 24 * without specific prior written permission. 25 * 26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 36 * SUCH DAMAGE. 37 * 38 * @(#)kern_synch.c 8.9 (Berkeley) 5/19/95 39 */ 40 41#include <sys/cdefs.h> 42__FBSDID("$FreeBSD: head/sys/kern/kern_synch.c 126487 2004-03-02 14:58:33Z jhb $"); 43 44#include "opt_ddb.h" 45#include "opt_ktrace.h" 46 47#include <sys/param.h> 48#include <sys/systm.h> 49#include <sys/condvar.h> 50#include <sys/kernel.h> 51#include <sys/ktr.h> 52#include <sys/lock.h> 53#include <sys/mutex.h> 54#include <sys/proc.h> 55#include <sys/resourcevar.h> 56#include <sys/sched.h> 57#include <sys/signalvar.h> 58#include <sys/sleepqueue.h> 59#include <sys/smp.h> 60#include <sys/sx.h> 61#include <sys/sysctl.h> 62#include <sys/sysproto.h> 63#include <sys/vmmeter.h> 64#ifdef DDB 65#include <ddb/ddb.h> 66#endif 67#ifdef KTRACE 68#include <sys/uio.h> 69#include <sys/ktrace.h> 70#endif 71 72#include <machine/cpu.h> 73 74static void synch_setup(void *dummy); 75SYSINIT(synch_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, synch_setup, NULL) 76 77int hogticks; 78int lbolt; 79 80static struct callout loadav_callout; 81static struct callout lbolt_callout; 82 83struct loadavg averunnable = 84 { {0, 0, 0}, FSCALE }; /* load average, of runnable procs */ 85/* 86 * Constants for averages over 1, 5, and 15 minutes 87 * when sampling at 5 second intervals. 88 */ 89static fixpt_t cexp[3] = { 90 0.9200444146293232 * FSCALE, /* exp(-1/12) */ 91 0.9834714538216174 * FSCALE, /* exp(-1/60) */ 92 0.9944598480048967 * FSCALE, /* exp(-1/180) */ 93}; 94 95/* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */ 96static int fscale __unused = FSCALE; 97SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, ""); 98 99static void loadav(void *arg); 100static void lboltcb(void *arg); 101 102/* 103 * We're only looking at 7 bits of the address; everything is 104 * aligned to 4, lots of things are aligned to greater powers 105 * of 2. Shift right by 8, i.e. drop the bottom 256 worth. 106 */ 107#define TABLESIZE 128 108static TAILQ_HEAD(slpquehead, thread) slpque[TABLESIZE]; 109#define LOOKUP(x) (((intptr_t)(x) >> 8) & (TABLESIZE - 1)) 110 111void 112sleepinit(void) 113{ 114 int i; 115 116 hogticks = (hz / 10) * 2; /* Default only. */ 117 for (i = 0; i < TABLESIZE; i++) 118 TAILQ_INIT(&slpque[i]); 119 init_sleepqueues(); 120} 121 122/* 123 * General sleep call. Suspends the current process until a wakeup is 124 * performed on the specified identifier. The process will then be made 125 * runnable with the specified priority. Sleeps at most timo/hz seconds 126 * (0 means no timeout). If pri includes PCATCH flag, signals are checked 127 * before and after sleeping, else signals are not checked. Returns 0 if 128 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a 129 * signal needs to be delivered, ERESTART is returned if the current system 130 * call should be restarted if possible, and EINTR is returned if the system 131 * call should be interrupted by the signal (return EINTR). 132 * 133 * The mutex argument is exited before the caller is suspended, and 134 * entered before msleep returns. If priority includes the PDROP 135 * flag the mutex is not entered before returning. 136 */ 137 138int 139msleep(ident, mtx, priority, wmesg, timo) 140 void *ident; 141 struct mtx *mtx; 142 int priority, timo; 143 const char *wmesg; 144{ 145 struct sleepqueue *sq; 146 struct thread *td; 147 struct proc *p; 148 int catch, rval, sig; 149 WITNESS_SAVE_DECL(mtx); 150 151 td = curthread; 152 p = td->td_proc; 153#ifdef KTRACE 154 if (KTRPOINT(td, KTR_CSW)) 155 ktrcsw(1, 0); 156#endif 157 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, mtx == NULL ? NULL : 158 &mtx->mtx_object, "Sleeping on \"%s\"", wmesg); 159 KASSERT(timo != 0 || mtx_owned(&Giant) || mtx != NULL, 160 ("sleeping without a mutex")); 161 KASSERT(p != NULL, ("msleep1")); 162 KASSERT(ident != NULL && TD_IS_RUNNING(td), ("msleep")); 163 164 if (cold) { 165 /* 166 * During autoconfiguration, just return; 167 * don't run any other procs or panic below, 168 * in case this is the idle process and already asleep. 169 * XXX: this used to do "s = splhigh(); splx(safepri); 170 * splx(s);" to give interrupts a chance, but there is 171 * no way to give interrupts a chance now. 172 */ 173 if (mtx != NULL && priority & PDROP) 174 mtx_unlock(mtx); 175 return (0); 176 } 177 catch = priority & PCATCH; 178 rval = 0; 179 180 /* 181 * If we are already on a sleep queue, then remove us from that 182 * sleep queue first. We have to do this to handle recursive 183 * sleeps. 184 */ 185 if (TD_ON_SLEEPQ(td)) 186 sleepq_remove(td, td->td_wchan); 187 188 sq = sleepq_lookup(ident); 189 mtx_lock_spin(&sched_lock); 190 191 /* 192 * If we are capable of async syscalls and there isn't already 193 * another one ready to return, start a new thread 194 * and queue it as ready to run. Note that there is danger here 195 * because we need to make sure that we don't sleep allocating 196 * the thread (recursion here might be bad). 197 */ 198 if (p->p_flag & P_SA || p->p_numthreads > 1) { 199 /* 200 * Just don't bother if we are exiting 201 * and not the exiting thread or thread was marked as 202 * interrupted. 203 */ 204 if (catch) { 205 if ((p->p_flag & P_WEXIT) && p->p_singlethread != td) { 206 mtx_unlock_spin(&sched_lock); 207 sleepq_release(ident); 208 return (EINTR); 209 } 210 if (td->td_flags & TDF_INTERRUPT) { 211 mtx_unlock_spin(&sched_lock); 212 sleepq_release(ident); 213 return (td->td_intrval); 214 } 215 } 216 } 217 mtx_unlock_spin(&sched_lock); 218 CTR5(KTR_PROC, "msleep: thread %p (pid %d, %s) on %s (%p)", 219 td, p->p_pid, p->p_comm, wmesg, ident); 220 221 DROP_GIANT(); 222 if (mtx != NULL) { 223 mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED); 224 WITNESS_SAVE(&mtx->mtx_object, mtx); 225 mtx_unlock(mtx); 226 } 227 228 /* 229 * We put ourselves on the sleep queue and start our timeout 230 * before calling thread_suspend_check, as we could stop there, 231 * and a wakeup or a SIGCONT (or both) could occur while we were 232 * stopped without resuming us. Thus, we must be ready for sleep 233 * when cursig() is called. If the wakeup happens while we're 234 * stopped, then td will no longer be on a sleep queue upon 235 * return from cursig(). 236 */ 237 sleepq_add(sq, ident, mtx, wmesg, 0); 238 if (timo) 239 sleepq_set_timeout(sq, ident, timo); 240 if (catch) { 241 sig = sleepq_catch_signals(ident); 242 if (sig == 0 && !TD_ON_SLEEPQ(td)) { 243 mtx_lock_spin(&sched_lock); 244 td->td_flags &= ~TDF_SINTR; 245 mtx_unlock_spin(&sched_lock); 246 catch = 0; 247 } 248 } else 249 sig = 0; 250 251 /* 252 * Adjust this threads priority. 253 * 254 * XXX: Do we need to save priority in td_base_pri? 255 */ 256 mtx_lock_spin(&sched_lock); 257 sched_prio(td, priority & PRIMASK); 258 mtx_unlock_spin(&sched_lock); 259 260 if (timo && catch) 261 rval = sleepq_timedwait_sig(ident, sig != 0); 262 else if (timo) 263 rval = sleepq_timedwait(ident, sig != 0); 264 else if (catch) 265 rval = sleepq_wait_sig(ident); 266 else { 267 sleepq_wait(ident); 268 rval = 0; 269 } 270 271 /* 272 * We're awake from voluntary sleep. 273 */ 274 if (rval == 0 && catch) 275 rval = sleepq_calc_signal_retval(sig); 276#ifdef KTRACE 277 if (KTRPOINT(td, KTR_CSW)) 278 ktrcsw(0, 0); 279#endif 280 PICKUP_GIANT(); 281 if (mtx != NULL && !(priority & PDROP)) { 282 mtx_lock(mtx); 283 WITNESS_RESTORE(&mtx->mtx_object, mtx); 284 } 285 return (rval); 286} 287 288/* 289 * Make all processes sleeping on the specified identifier runnable. 290 */ 291void 292wakeup(ident) 293 register void *ident; 294{ 295 296 sleepq_broadcast(ident, 0, -1); 297} 298 299/* 300 * Make a process sleeping on the specified identifier runnable. 301 * May wake more than one process if a target process is currently 302 * swapped out. 303 */ 304void 305wakeup_one(ident) 306 register void *ident; 307{ 308 309 sleepq_signal(ident, 0, -1); 310} 311 312/* 313 * The machine independent parts of mi_switch(). 314 */ 315void 316mi_switch(int flags) 317{ 318 struct bintime new_switchtime; 319 struct thread *td; 320 struct proc *p; 321 322 mtx_assert(&sched_lock, MA_OWNED | MA_NOTRECURSED); 323 td = curthread; /* XXX */ 324 p = td->td_proc; /* XXX */ 325 KASSERT(!TD_ON_RUNQ(td), ("mi_switch: called by old code")); 326#ifdef INVARIANTS 327 if (!TD_ON_LOCK(td) && !TD_IS_RUNNING(td)) 328 mtx_assert(&Giant, MA_NOTOWNED); 329#endif 330 KASSERT(td->td_critnest == 1, 331 ("mi_switch: switch in a critical section")); 332 KASSERT((flags & (SW_INVOL | SW_VOL)) != 0, 333 ("mi_switch: switch must be voluntary or involuntary")); 334 335 if (flags & SW_VOL) 336 p->p_stats->p_ru.ru_nvcsw++; 337 else 338 p->p_stats->p_ru.ru_nivcsw++; 339 /* 340 * Compute the amount of time during which the current 341 * process was running, and add that to its total so far. 342 */ 343 binuptime(&new_switchtime); 344 bintime_add(&p->p_runtime, &new_switchtime); 345 bintime_sub(&p->p_runtime, PCPU_PTR(switchtime)); 346 347 td->td_generation++; /* bump preempt-detect counter */ 348 349#ifdef DDB 350 /* 351 * Don't perform context switches from the debugger. 352 */ 353 if (db_active) { 354 mtx_unlock_spin(&sched_lock); 355 db_print_backtrace(); 356 db_error("Context switches not allowed in the debugger"); 357 } 358#endif 359 360 /* 361 * Check if the process exceeds its cpu resource allocation. If 362 * over max, arrange to kill the process in ast(). 363 */ 364 if (p->p_cpulimit != RLIM_INFINITY && 365 p->p_runtime.sec > p->p_cpulimit) { 366 p->p_sflag |= PS_XCPU; 367 td->td_flags |= TDF_ASTPENDING; 368 } 369 370 /* 371 * Finish up stats for outgoing thread. 372 */ 373 cnt.v_swtch++; 374 PCPU_SET(switchtime, new_switchtime); 375 PCPU_SET(switchticks, ticks); 376 CTR3(KTR_PROC, "mi_switch: old thread %p (pid %d, %s)", td, p->p_pid, 377 p->p_comm); 378 if (td->td_proc->p_flag & P_SA) 379 thread_switchout(td); 380 sched_switch(td); 381 382 CTR3(KTR_PROC, "mi_switch: new thread %p (pid %d, %s)", td, p->p_pid, 383 p->p_comm); 384 385 /* 386 * If the last thread was exiting, finish cleaning it up. 387 */ 388 if ((td = PCPU_GET(deadthread))) { 389 PCPU_SET(deadthread, NULL); 390 thread_stash(td); 391 } 392} 393 394/* 395 * Change process state to be runnable, 396 * placing it on the run queue if it is in memory, 397 * and awakening the swapper if it isn't in memory. 398 */ 399void 400setrunnable(struct thread *td) 401{ 402 struct proc *p; 403 404 p = td->td_proc; 405 mtx_assert(&sched_lock, MA_OWNED); 406 switch (p->p_state) { 407 case PRS_ZOMBIE: 408 panic("setrunnable(1)"); 409 default: 410 break; 411 } 412 switch (td->td_state) { 413 case TDS_RUNNING: 414 case TDS_RUNQ: 415 return; 416 case TDS_INHIBITED: 417 /* 418 * If we are only inhibited because we are swapped out 419 * then arange to swap in this process. Otherwise just return. 420 */ 421 if (td->td_inhibitors != TDI_SWAPPED) 422 return; 423 /* XXX: intentional fall-through ? */ 424 case TDS_CAN_RUN: 425 break; 426 default: 427 printf("state is 0x%x", td->td_state); 428 panic("setrunnable(2)"); 429 } 430 if ((p->p_sflag & PS_INMEM) == 0) { 431 if ((p->p_sflag & PS_SWAPPINGIN) == 0) { 432 p->p_sflag |= PS_SWAPINREQ; 433 wakeup(&proc0); 434 } 435 } else 436 sched_wakeup(td); 437} 438 439/* 440 * Compute a tenex style load average of a quantity on 441 * 1, 5 and 15 minute intervals. 442 * XXXKSE Needs complete rewrite when correct info is available. 443 * Completely Bogus.. only works with 1:1 (but compiles ok now :-) 444 */ 445static void 446loadav(void *arg) 447{ 448 int i, nrun; 449 struct loadavg *avg; 450 451 nrun = sched_load(); 452 avg = &averunnable; 453 454 for (i = 0; i < 3; i++) 455 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] + 456 nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT; 457 458 /* 459 * Schedule the next update to occur after 5 seconds, but add a 460 * random variation to avoid synchronisation with processes that 461 * run at regular intervals. 462 */ 463 callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)), 464 loadav, NULL); 465} 466 467static void 468lboltcb(void *arg) 469{ 470 wakeup(&lbolt); 471 callout_reset(&lbolt_callout, hz, lboltcb, NULL); 472} 473 474/* ARGSUSED */ 475static void 476synch_setup(dummy) 477 void *dummy; 478{ 479 callout_init(&loadav_callout, 0); 480 callout_init(&lbolt_callout, CALLOUT_MPSAFE); 481 482 /* Kick off timeout driven events by calling first time. */ 483 loadav(NULL); 484 lboltcb(NULL); 485} 486 487/* 488 * General purpose yield system call 489 */ 490int 491yield(struct thread *td, struct yield_args *uap) 492{ 493 struct ksegrp *kg; 494 495 kg = td->td_ksegrp; 496 mtx_assert(&Giant, MA_NOTOWNED); 497 mtx_lock_spin(&sched_lock); 498 sched_prio(td, PRI_MAX_TIMESHARE); 499 mi_switch(SW_VOL); 500 mtx_unlock_spin(&sched_lock); 501 td->td_retval[0] = 0; 502 return (0); 503} 504