kern_synch.c revision 126885
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 126885 2004-03-12 19:06:18Z 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 102void 103sleepinit(void) 104{ 105 106 hogticks = (hz / 10) * 2; /* Default only. */ 107 init_sleepqueues(); 108} 109 110/* 111 * General sleep call. Suspends the current process until a wakeup is 112 * performed on the specified identifier. The process will then be made 113 * runnable with the specified priority. Sleeps at most timo/hz seconds 114 * (0 means no timeout). If pri includes PCATCH flag, signals are checked 115 * before and after sleeping, else signals are not checked. Returns 0 if 116 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a 117 * signal needs to be delivered, ERESTART is returned if the current system 118 * call should be restarted if possible, and EINTR is returned if the system 119 * call should be interrupted by the signal (return EINTR). 120 * 121 * The mutex argument is exited before the caller is suspended, and 122 * entered before msleep returns. If priority includes the PDROP 123 * flag the mutex is not entered before returning. 124 */ 125 126int 127msleep(ident, mtx, priority, wmesg, timo) 128 void *ident; 129 struct mtx *mtx; 130 int priority, timo; 131 const char *wmesg; 132{ 133 struct sleepqueue *sq; 134 struct thread *td; 135 struct proc *p; 136 int catch, rval, sig; 137 WITNESS_SAVE_DECL(mtx); 138 139 td = curthread; 140 p = td->td_proc; 141#ifdef KTRACE 142 if (KTRPOINT(td, KTR_CSW)) 143 ktrcsw(1, 0); 144#endif 145 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, mtx == NULL ? NULL : 146 &mtx->mtx_object, "Sleeping on \"%s\"", wmesg); 147 KASSERT(timo != 0 || mtx_owned(&Giant) || mtx != NULL, 148 ("sleeping without a mutex")); 149 KASSERT(p != NULL, ("msleep1")); 150 KASSERT(ident != NULL && TD_IS_RUNNING(td), ("msleep")); 151 152 if (cold) { 153 /* 154 * During autoconfiguration, just return; 155 * don't run any other procs or panic below, 156 * in case this is the idle process and already asleep. 157 * XXX: this used to do "s = splhigh(); splx(safepri); 158 * splx(s);" to give interrupts a chance, but there is 159 * no way to give interrupts a chance now. 160 */ 161 if (mtx != NULL && priority & PDROP) 162 mtx_unlock(mtx); 163 return (0); 164 } 165 catch = priority & PCATCH; 166 rval = 0; 167 168 /* 169 * If we are already on a sleep queue, then remove us from that 170 * sleep queue first. We have to do this to handle recursive 171 * sleeps. 172 */ 173 if (TD_ON_SLEEPQ(td)) 174 sleepq_remove(td, td->td_wchan); 175 176 sq = sleepq_lookup(ident); 177 mtx_lock_spin(&sched_lock); 178 179 /* 180 * If we are capable of async syscalls and there isn't already 181 * another one ready to return, start a new thread 182 * and queue it as ready to run. Note that there is danger here 183 * because we need to make sure that we don't sleep allocating 184 * the thread (recursion here might be bad). 185 */ 186 if (p->p_flag & P_SA || p->p_numthreads > 1) { 187 /* 188 * Just don't bother if we are exiting 189 * and not the exiting thread or thread was marked as 190 * interrupted. 191 */ 192 if (catch) { 193 if ((p->p_flag & P_WEXIT) && p->p_singlethread != td) { 194 mtx_unlock_spin(&sched_lock); 195 sleepq_release(ident); 196 return (EINTR); 197 } 198 if (td->td_flags & TDF_INTERRUPT) { 199 mtx_unlock_spin(&sched_lock); 200 sleepq_release(ident); 201 return (td->td_intrval); 202 } 203 } 204 } 205 mtx_unlock_spin(&sched_lock); 206 CTR5(KTR_PROC, "msleep: thread %p (pid %d, %s) on %s (%p)", 207 td, p->p_pid, p->p_comm, wmesg, ident); 208 209 DROP_GIANT(); 210 if (mtx != NULL) { 211 mtx_assert(mtx, MA_OWNED | MA_NOTRECURSED); 212 WITNESS_SAVE(&mtx->mtx_object, mtx); 213 mtx_unlock(mtx); 214 } 215 216 /* 217 * We put ourselves on the sleep queue and start our timeout 218 * before calling thread_suspend_check, as we could stop there, 219 * and a wakeup or a SIGCONT (or both) could occur while we were 220 * stopped without resuming us. Thus, we must be ready for sleep 221 * when cursig() is called. If the wakeup happens while we're 222 * stopped, then td will no longer be on a sleep queue upon 223 * return from cursig(). 224 */ 225 sleepq_add(sq, ident, mtx, wmesg, 0); 226 if (timo) 227 sleepq_set_timeout(ident, timo); 228 if (catch) { 229 sig = sleepq_catch_signals(ident); 230 if (sig == 0 && !TD_ON_SLEEPQ(td)) { 231 mtx_lock_spin(&sched_lock); 232 td->td_flags &= ~TDF_SINTR; 233 mtx_unlock_spin(&sched_lock); 234 catch = 0; 235 } 236 } else 237 sig = 0; 238 239 /* 240 * Adjust this threads priority. 241 * 242 * XXX: Do we need to save priority in td_base_pri? 243 */ 244 mtx_lock_spin(&sched_lock); 245 sched_prio(td, priority & PRIMASK); 246 mtx_unlock_spin(&sched_lock); 247 248 if (timo && catch) 249 rval = sleepq_timedwait_sig(ident, sig != 0); 250 else if (timo) 251 rval = sleepq_timedwait(ident, sig != 0); 252 else if (catch) 253 rval = sleepq_wait_sig(ident); 254 else { 255 sleepq_wait(ident); 256 rval = 0; 257 } 258 259 /* 260 * We're awake from voluntary sleep. 261 */ 262 if (rval == 0 && catch) 263 rval = sleepq_calc_signal_retval(sig); 264#ifdef KTRACE 265 if (KTRPOINT(td, KTR_CSW)) 266 ktrcsw(0, 0); 267#endif 268 PICKUP_GIANT(); 269 if (mtx != NULL && !(priority & PDROP)) { 270 mtx_lock(mtx); 271 WITNESS_RESTORE(&mtx->mtx_object, mtx); 272 } 273 return (rval); 274} 275 276/* 277 * Make all processes sleeping on the specified identifier runnable. 278 */ 279void 280wakeup(ident) 281 register void *ident; 282{ 283 284 sleepq_broadcast(ident, 0, -1); 285} 286 287/* 288 * Make a process sleeping on the specified identifier runnable. 289 * May wake more than one process if a target process is currently 290 * swapped out. 291 */ 292void 293wakeup_one(ident) 294 register void *ident; 295{ 296 297 sleepq_signal(ident, 0, -1); 298} 299 300/* 301 * The machine independent parts of mi_switch(). 302 */ 303void 304mi_switch(int flags) 305{ 306 struct bintime new_switchtime; 307 struct thread *td; 308 struct proc *p; 309 310 mtx_assert(&sched_lock, MA_OWNED | MA_NOTRECURSED); 311 td = curthread; /* XXX */ 312 p = td->td_proc; /* XXX */ 313 KASSERT(!TD_ON_RUNQ(td), ("mi_switch: called by old code")); 314#ifdef INVARIANTS 315 if (!TD_ON_LOCK(td) && !TD_IS_RUNNING(td)) 316 mtx_assert(&Giant, MA_NOTOWNED); 317#endif 318 KASSERT(td->td_critnest == 1, 319 ("mi_switch: switch in a critical section")); 320 KASSERT((flags & (SW_INVOL | SW_VOL)) != 0, 321 ("mi_switch: switch must be voluntary or involuntary")); 322 323 if (flags & SW_VOL) 324 p->p_stats->p_ru.ru_nvcsw++; 325 else 326 p->p_stats->p_ru.ru_nivcsw++; 327 /* 328 * Compute the amount of time during which the current 329 * process was running, and add that to its total so far. 330 */ 331 binuptime(&new_switchtime); 332 bintime_add(&p->p_runtime, &new_switchtime); 333 bintime_sub(&p->p_runtime, PCPU_PTR(switchtime)); 334 335 td->td_generation++; /* bump preempt-detect counter */ 336 337#ifdef DDB 338 /* 339 * Don't perform context switches from the debugger. 340 */ 341 if (db_active) { 342 mtx_unlock_spin(&sched_lock); 343 db_print_backtrace(); 344 db_error("Context switches not allowed in the debugger"); 345 } 346#endif 347 348 /* 349 * Check if the process exceeds its cpu resource allocation. If 350 * over max, arrange to kill the process in ast(). 351 */ 352 if (p->p_cpulimit != RLIM_INFINITY && 353 p->p_runtime.sec > p->p_cpulimit) { 354 p->p_sflag |= PS_XCPU; 355 td->td_flags |= TDF_ASTPENDING; 356 } 357 358 /* 359 * Finish up stats for outgoing thread. 360 */ 361 cnt.v_swtch++; 362 PCPU_SET(switchtime, new_switchtime); 363 PCPU_SET(switchticks, ticks); 364 CTR3(KTR_PROC, "mi_switch: old thread %p (pid %d, %s)", td, p->p_pid, 365 p->p_comm); 366 if (td->td_proc->p_flag & P_SA) 367 thread_switchout(td); 368 sched_switch(td); 369 370 CTR3(KTR_PROC, "mi_switch: new thread %p (pid %d, %s)", td, p->p_pid, 371 p->p_comm); 372 373 /* 374 * If the last thread was exiting, finish cleaning it up. 375 */ 376 if ((td = PCPU_GET(deadthread))) { 377 PCPU_SET(deadthread, NULL); 378 thread_stash(td); 379 } 380} 381 382/* 383 * Change process state to be runnable, 384 * placing it on the run queue if it is in memory, 385 * and awakening the swapper if it isn't in memory. 386 */ 387void 388setrunnable(struct thread *td) 389{ 390 struct proc *p; 391 392 p = td->td_proc; 393 mtx_assert(&sched_lock, MA_OWNED); 394 switch (p->p_state) { 395 case PRS_ZOMBIE: 396 panic("setrunnable(1)"); 397 default: 398 break; 399 } 400 switch (td->td_state) { 401 case TDS_RUNNING: 402 case TDS_RUNQ: 403 return; 404 case TDS_INHIBITED: 405 /* 406 * If we are only inhibited because we are swapped out 407 * then arange to swap in this process. Otherwise just return. 408 */ 409 if (td->td_inhibitors != TDI_SWAPPED) 410 return; 411 /* XXX: intentional fall-through ? */ 412 case TDS_CAN_RUN: 413 break; 414 default: 415 printf("state is 0x%x", td->td_state); 416 panic("setrunnable(2)"); 417 } 418 if ((p->p_sflag & PS_INMEM) == 0) { 419 if ((p->p_sflag & PS_SWAPPINGIN) == 0) { 420 p->p_sflag |= PS_SWAPINREQ; 421 wakeup(&proc0); 422 } 423 } else 424 sched_wakeup(td); 425} 426 427/* 428 * Compute a tenex style load average of a quantity on 429 * 1, 5 and 15 minute intervals. 430 * XXXKSE Needs complete rewrite when correct info is available. 431 * Completely Bogus.. only works with 1:1 (but compiles ok now :-) 432 */ 433static void 434loadav(void *arg) 435{ 436 int i, nrun; 437 struct loadavg *avg; 438 439 nrun = sched_load(); 440 avg = &averunnable; 441 442 for (i = 0; i < 3; i++) 443 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] + 444 nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT; 445 446 /* 447 * Schedule the next update to occur after 5 seconds, but add a 448 * random variation to avoid synchronisation with processes that 449 * run at regular intervals. 450 */ 451 callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)), 452 loadav, NULL); 453} 454 455static void 456lboltcb(void *arg) 457{ 458 wakeup(&lbolt); 459 callout_reset(&lbolt_callout, hz, lboltcb, NULL); 460} 461 462/* ARGSUSED */ 463static void 464synch_setup(dummy) 465 void *dummy; 466{ 467 callout_init(&loadav_callout, CALLOUT_MPSAFE); 468 callout_init(&lbolt_callout, CALLOUT_MPSAFE); 469 470 /* Kick off timeout driven events by calling first time. */ 471 loadav(NULL); 472 lboltcb(NULL); 473} 474 475/* 476 * General purpose yield system call 477 */ 478int 479yield(struct thread *td, struct yield_args *uap) 480{ 481 struct ksegrp *kg; 482 483 kg = td->td_ksegrp; 484 mtx_assert(&Giant, MA_NOTOWNED); 485 mtx_lock_spin(&sched_lock); 486 sched_prio(td, PRI_MAX_TIMESHARE); 487 mi_switch(SW_VOL); 488 mtx_unlock_spin(&sched_lock); 489 td->td_retval[0] = 0; 490 return (0); 491} 492