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.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
38 * @(#)kern_synch.c 8.9 (Berkeley) 5/19/95
39 * $FreeBSD: src/sys/kern/kern_synch.c,v 1.87.2.6 2002/10/13 07:29:53 kbyanc Exp $
40 * $DragonFly: src/sys/kern/kern_synch.c,v 1.91 2008/09/09 04:06:13 dillon Exp $
43 #include "opt_ktrace.h"
45 #include <sys/param.h>
46 #include <sys/systm.h>
48 #include <sys/kernel.h>
49 #include <sys/signalvar.h>
50 #include <sys/resourcevar.h>
51 #include <sys/vmmeter.h>
52 #include <sys/sysctl.h>
56 #include <sys/ktrace.h>
58 #include <sys/xwait.h>
60 #include <sys/serialize.h>
62 #include <sys/signal2.h>
63 #include <sys/thread2.h>
64 #include <sys/spinlock2.h>
65 #include <sys/mutex2.h>
67 #include <machine/cpu.h>
68 #include <machine/smp.h>
70 TAILQ_HEAD(tslpque, thread);
72 static void sched_setup (void *dummy);
73 SYSINIT(sched_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, sched_setup, NULL)
78 int sched_quantum; /* Roundrobin scheduling quantum in ticks. */
80 int ncpus2, ncpus2_shift, ncpus2_mask; /* note: mask not cpumask_t */
81 int ncpus_fit, ncpus_fit_mask; /* note: mask not cpumask_t */
84 int tsleep_crypto_dump = 0;
86 static struct callout loadav_callout;
87 static struct callout schedcpu_callout;
88 MALLOC_DEFINE(M_TSLEEP, "tslpque", "tsleep queues");
90 #define __DEALL(ident) __DEQUALIFY(void *, ident)
92 #if !defined(KTR_TSLEEP)
93 #define KTR_TSLEEP KTR_ALL
95 KTR_INFO_MASTER(tsleep);
96 KTR_INFO(KTR_TSLEEP, tsleep, tsleep_beg, 0, "tsleep enter %p", const volatile void *ident);
97 KTR_INFO(KTR_TSLEEP, tsleep, tsleep_end, 1, "tsleep exit");
98 KTR_INFO(KTR_TSLEEP, tsleep, wakeup_beg, 2, "wakeup enter %p", const volatile void *ident);
99 KTR_INFO(KTR_TSLEEP, tsleep, wakeup_end, 3, "wakeup exit");
100 KTR_INFO(KTR_TSLEEP, tsleep, ilockfail, 4, "interlock failed %p", const volatile void *ident);
102 #define logtsleep1(name) KTR_LOG(tsleep_ ## name)
103 #define logtsleep2(name, val) KTR_LOG(tsleep_ ## name, val)
105 struct loadavg averunnable =
106 { {0, 0, 0}, FSCALE }; /* load average, of runnable procs */
108 * Constants for averages over 1, 5, and 15 minutes
109 * when sampling at 5 second intervals.
111 static fixpt_t cexp[3] = {
112 0.9200444146293232 * FSCALE, /* exp(-1/12) */
113 0.9834714538216174 * FSCALE, /* exp(-1/60) */
114 0.9944598480048967 * FSCALE, /* exp(-1/180) */
117 static void endtsleep (void *);
118 static void loadav (void *arg);
119 static void schedcpu (void *arg);
122 * Adjust the scheduler quantum. The quantum is specified in microseconds.
123 * Note that 'tick' is in microseconds per tick.
126 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
130 new_val = sched_quantum * ustick;
131 error = sysctl_handle_int(oidp, &new_val, 0, req);
132 if (error != 0 || req->newptr == NULL)
134 if (new_val < ustick)
136 sched_quantum = new_val / ustick;
137 hogticks = 2 * sched_quantum;
141 SYSCTL_PROC(_kern, OID_AUTO, quantum, CTLTYPE_INT|CTLFLAG_RW,
142 0, sizeof sched_quantum, sysctl_kern_quantum, "I", "");
144 static int pctcpu_decay = 10;
145 SYSCTL_INT(_kern, OID_AUTO, pctcpu_decay, CTLFLAG_RW, &pctcpu_decay, 0, "");
148 * kernel uses `FSCALE', userland (SHOULD) use kern.fscale
150 int fscale __unused = FSCALE; /* exported to systat */
151 SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, "");
154 * Recompute process priorities, once a second.
156 * Since the userland schedulers are typically event oriented, if the
157 * estcpu calculation at wakeup() time is not sufficient to make a
158 * process runnable relative to other processes in the system we have
159 * a 1-second recalc to help out.
161 * This code also allows us to store sysclock_t data in the process structure
162 * without fear of an overrun, since sysclock_t are guarenteed to hold
163 * several seconds worth of count.
165 * WARNING! callouts can preempt normal threads. However, they will not
166 * preempt a thread holding a spinlock so we *can* safely use spinlocks.
168 static int schedcpu_stats(struct proc *p, void *data __unused);
169 static int schedcpu_resource(struct proc *p, void *data __unused);
174 allproc_scan(schedcpu_stats, NULL);
175 allproc_scan(schedcpu_resource, NULL);
176 wakeup((caddr_t)&lbolt);
177 wakeup(lbolt_syncer);
178 callout_reset(&schedcpu_callout, hz, schedcpu, NULL);
182 * General process statistics once a second
185 schedcpu_stats(struct proc *p, void *data __unused)
190 * Threads may not be completely set up if process in SIDL state.
192 if (p->p_stat == SIDL)
196 if (lwkt_trytoken(&p->p_token) == FALSE) {
202 FOREACH_LWP_IN_PROC(lp, p) {
203 if (lp->lwp_stat == LSSLEEP) {
205 if (lp->lwp_slptime == 1)
206 p->p_usched->uload_update(lp);
210 * Only recalculate processes that are active or have slept
211 * less then 2 seconds. The schedulers understand this.
212 * Otherwise decay by 50% per second.
214 if (lp->lwp_slptime <= 1) {
215 p->p_usched->recalculate(lp);
219 decay = pctcpu_decay;
225 lp->lwp_pctcpu = (lp->lwp_pctcpu * (decay - 1)) / decay;
228 lwkt_reltoken(&p->p_token);
235 * Resource checks. XXX break out since ksignal/killproc can block,
236 * limiting us to one process killed per second. There is probably
240 schedcpu_resource(struct proc *p, void *data __unused)
245 if (p->p_stat == SIDL)
249 if (lwkt_trytoken(&p->p_token) == FALSE) {
254 if (p->p_stat == SZOMB || p->p_limit == NULL) {
255 lwkt_reltoken(&p->p_token);
261 FOREACH_LWP_IN_PROC(lp, p) {
263 * We may have caught an lp in the middle of being
264 * created, lwp_thread can be NULL.
266 if (lp->lwp_thread) {
267 ttime += lp->lwp_thread->td_sticks;
268 ttime += lp->lwp_thread->td_uticks;
272 switch(plimit_testcpulimit(p->p_limit, ttime)) {
273 case PLIMIT_TESTCPU_KILL:
274 killproc(p, "exceeded maximum CPU limit");
276 case PLIMIT_TESTCPU_XCPU:
277 if ((p->p_flags & P_XCPU) == 0) {
278 p->p_flags |= P_XCPU;
285 lwkt_reltoken(&p->p_token);
292 * This is only used by ps. Generate a cpu percentage use over
293 * a period of one second.
296 updatepcpu(struct lwp *lp, int cpticks, int ttlticks)
301 acc = (cpticks << FSHIFT) / ttlticks;
302 if (ttlticks >= ESTCPUFREQ) {
303 lp->lwp_pctcpu = acc;
305 remticks = ESTCPUFREQ - ttlticks;
306 lp->lwp_pctcpu = (acc * ttlticks + lp->lwp_pctcpu * remticks) /
312 * tsleep/wakeup hash table parameters. Try to find the sweet spot for
313 * like addresses being slept on.
315 #define TABLESIZE 4001
316 #define LOOKUP(x) (((u_int)(uintptr_t)(x)) % TABLESIZE)
318 static cpumask_t slpque_cpumasks[TABLESIZE];
321 * General scheduler initialization. We force a reschedule 25 times
322 * a second by default. Note that cpu0 is initialized in early boot and
323 * cannot make any high level calls.
325 * Each cpu has its own sleep queue.
328 sleep_gdinit(globaldata_t gd)
330 static struct tslpque slpque_cpu0[TABLESIZE];
333 if (gd->gd_cpuid == 0) {
334 sched_quantum = (hz + 24) / 25;
335 hogticks = 2 * sched_quantum;
337 gd->gd_tsleep_hash = slpque_cpu0;
339 gd->gd_tsleep_hash = kmalloc(sizeof(slpque_cpu0),
340 M_TSLEEP, M_WAITOK | M_ZERO);
342 for (i = 0; i < TABLESIZE; ++i)
343 TAILQ_INIT(&gd->gd_tsleep_hash[i]);
347 * This is a dandy function that allows us to interlock tsleep/wakeup
348 * operations with unspecified upper level locks, such as lockmgr locks,
349 * simply by holding a critical section. The sequence is:
351 * (acquire upper level lock)
352 * tsleep_interlock(blah)
353 * (release upper level lock)
356 * Basically this functions queues us on the tsleep queue without actually
357 * descheduling us. When tsleep() is later called with PINTERLOCK it
358 * assumes the thread was already queued, otherwise it queues it there.
360 * Thus it is possible to receive the wakeup prior to going to sleep and
361 * the race conditions are covered.
364 _tsleep_interlock(globaldata_t gd, const volatile void *ident, int flags)
366 thread_t td = gd->gd_curthread;
369 crit_enter_quick(td);
370 if (td->td_flags & TDF_TSLEEPQ) {
371 id = LOOKUP(td->td_wchan);
372 TAILQ_REMOVE(&gd->gd_tsleep_hash[id], td, td_sleepq);
373 if (TAILQ_FIRST(&gd->gd_tsleep_hash[id]) == NULL) {
374 atomic_clear_cpumask(&slpque_cpumasks[id],
378 td->td_flags |= TDF_TSLEEPQ;
381 TAILQ_INSERT_TAIL(&gd->gd_tsleep_hash[id], td, td_sleepq);
382 atomic_set_cpumask(&slpque_cpumasks[id], gd->gd_cpumask);
383 td->td_wchan = ident;
384 td->td_wdomain = flags & PDOMAIN_MASK;
389 tsleep_interlock(const volatile void *ident, int flags)
391 _tsleep_interlock(mycpu, ident, flags);
395 * Remove thread from sleepq. Must be called with a critical section held.
396 * The thread must not be migrating.
399 _tsleep_remove(thread_t td)
401 globaldata_t gd = mycpu;
404 KKASSERT(td->td_gd == gd && IN_CRITICAL_SECT(td));
405 KKASSERT((td->td_flags & TDF_MIGRATING) == 0);
406 if (td->td_flags & TDF_TSLEEPQ) {
407 td->td_flags &= ~TDF_TSLEEPQ;
408 id = LOOKUP(td->td_wchan);
409 TAILQ_REMOVE(&gd->gd_tsleep_hash[id], td, td_sleepq);
410 if (TAILQ_FIRST(&gd->gd_tsleep_hash[id]) == NULL)
411 atomic_clear_cpumask(&slpque_cpumasks[id], gd->gd_cpumask);
418 tsleep_remove(thread_t td)
424 * General sleep call. Suspends the current process until a wakeup is
425 * performed on the specified identifier. The process will then be made
426 * runnable with the specified priority. Sleeps at most timo/hz seconds
427 * (0 means no timeout). If flags includes PCATCH flag, signals are checked
428 * before and after sleeping, else signals are not checked. Returns 0 if
429 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a
430 * signal needs to be delivered, ERESTART is returned if the current system
431 * call should be restarted if possible, and EINTR is returned if the system
432 * call should be interrupted by the signal (return EINTR).
434 * Note that if we are a process, we release_curproc() before messing with
435 * the LWKT scheduler.
437 * During autoconfiguration or after a panic, a sleep will simply
438 * lower the priority briefly to allow interrupts, then return.
440 * WARNING! This code can't block (short of switching away), or bad things
441 * will happen. No getting tokens, no blocking locks, etc.
444 tsleep(const volatile void *ident, int flags, const char *wmesg, int timo)
446 struct thread *td = curthread;
447 struct lwp *lp = td->td_lwp;
448 struct proc *p = td->td_proc; /* may be NULL */
454 struct callout thandle;
457 * Currently a severe hack. Make sure any delayed wakeups
458 * are flushed before we sleep or we might deadlock on whatever
459 * event we are sleeping on.
461 if (td->td_flags & TDF_DELAYED_WAKEUP)
462 wakeup_end_delayed();
465 * NOTE: removed KTRPOINT, it could cause races due to blocking
466 * even in stable. Just scrap it for now.
468 if (!tsleep_crypto_dump && (tsleep_now_works == 0 || panicstr)) {
470 * After a panic, or before we actually have an operational
471 * softclock, just give interrupts a chance, then just return;
473 * don't run any other procs or panic below,
474 * in case this is the idle process and already asleep.
478 lwkt_setpri_self(safepri);
480 lwkt_setpri_self(oldpri);
483 logtsleep2(tsleep_beg, ident);
485 KKASSERT(td != &gd->gd_idlethread); /* you must be kidding! */
486 td->td_wakefromcpu = -1; /* overwritten by _wakeup */
489 * NOTE: all of this occurs on the current cpu, including any
490 * callout-based wakeups, so a critical section is a sufficient
493 * The entire sequence through to where we actually sleep must
494 * run without breaking the critical section.
496 catch = flags & PCATCH;
500 crit_enter_quick(td);
502 KASSERT(ident != NULL, ("tsleep: no ident"));
503 KASSERT(lp == NULL ||
504 lp->lwp_stat == LSRUN || /* Obvious */
505 lp->lwp_stat == LSSTOP, /* Set in tstop */
507 ident, wmesg, lp->lwp_stat));
510 * We interlock the sleep queue if the caller has not already done
511 * it for us. This must be done before we potentially acquire any
512 * tokens or we can loose the wakeup.
514 if ((flags & PINTERLOCKED) == 0) {
515 _tsleep_interlock(gd, ident, flags);
519 * Setup for the current process (if this is a process). We must
520 * interlock with lwp_token to avoid remote wakeup races via
524 lwkt_gettoken(&lp->lwp_token);
527 * Early termination if PCATCH was set and a
528 * signal is pending, interlocked with the
531 * Early termination only occurs when tsleep() is
532 * entered while in a normal LSRUN state.
534 if ((sig = CURSIG(lp)) != 0)
538 * Causes ksignal to wake us up if a signal is
539 * received (interlocked with p->p_token).
541 lp->lwp_flags |= LWP_SINTR;
548 * Make sure the current process has been untangled from
549 * the userland scheduler and initialize slptime to start
552 * NOTE: td->td_wakefromcpu is pre-set by the release function
553 * for the dfly scheduler, and then adjusted by _wakeup()
556 p->p_usched->release_curproc(lp);
561 * If the interlocked flag is set but our cpu bit in the slpqueue
562 * is no longer set, then a wakeup was processed inbetween the
563 * tsleep_interlock() (ours or the callers), and here. This can
564 * occur under numerous circumstances including when we release the
567 * Extreme loads can cause the sending of an IPI (e.g. wakeup()'s)
568 * to process incoming IPIs, thus draining incoming wakeups.
570 if ((td->td_flags & TDF_TSLEEPQ) == 0) {
571 logtsleep2(ilockfail, ident);
576 * scheduling is blocked while in a critical section. Coincide
577 * the descheduled-by-tsleep flag with the descheduling of the
580 * The timer callout is localized on our cpu and interlocked by
581 * our critical section.
583 lwkt_deschedule_self(td);
584 td->td_flags |= TDF_TSLEEP_DESCHEDULED;
585 td->td_wmesg = wmesg;
588 * Setup the timeout, if any. The timeout is only operable while
589 * the thread is flagged descheduled.
591 KKASSERT((td->td_flags & TDF_TIMEOUT) == 0);
593 callout_init_mp(&thandle);
594 callout_reset(&thandle, timo, endtsleep, td);
602 * Ok, we are sleeping. Place us in the SSLEEP state.
604 KKASSERT((lp->lwp_mpflags & LWP_MP_ONRUNQ) == 0);
607 * tstop() sets LSSTOP, so don't fiddle with that.
609 if (lp->lwp_stat != LSSTOP)
610 lp->lwp_stat = LSSLEEP;
611 lp->lwp_ru.ru_nvcsw++;
612 p->p_usched->uload_update(lp);
616 * And when we are woken up, put us back in LSRUN. If we
617 * slept for over a second, recalculate our estcpu.
619 lp->lwp_stat = LSRUN;
620 if (lp->lwp_slptime) {
621 p->p_usched->uload_update(lp);
622 p->p_usched->recalculate(lp);
630 * Make sure we haven't switched cpus while we were asleep. It's
631 * not supposed to happen. Cleanup our temporary flags.
633 KKASSERT(gd == td->td_gd);
636 * Cleanup the timeout. If the timeout has already occured thandle
637 * has already been stopped, otherwise stop thandle. If the timeout
638 * is running (the callout thread must be blocked trying to get
639 * lwp_token) then wait for us to get scheduled.
642 while (td->td_flags & TDF_TIMEOUT_RUNNING) {
643 lwkt_deschedule_self(td);
644 td->td_wmesg = "tsrace";
646 kprintf("td %p %s: timeout race\n", td, td->td_comm);
648 if (td->td_flags & TDF_TIMEOUT) {
649 td->td_flags &= ~TDF_TIMEOUT;
652 /* does not block when on same cpu */
653 callout_stop(&thandle);
656 td->td_flags &= ~TDF_TSLEEP_DESCHEDULED;
659 * Make sure we have been removed from the sleepq. In most
660 * cases this will have been done for us already but it is
661 * possible for a scheduling IPI to be in-flight from a
662 * previous tsleep/tsleep_interlock() or due to a straight-out
663 * call to lwkt_schedule() (in the case of an interrupt thread),
664 * causing a spurious wakeup.
670 * Figure out the correct error return. If interrupted by a
671 * signal we want to return EINTR or ERESTART.
675 if (catch && error == 0) {
676 if (sig != 0 || (sig = CURSIG(lp))) {
677 if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
683 lp->lwp_flags &= ~LWP_SINTR;
684 lwkt_reltoken(&lp->lwp_token);
686 logtsleep1(tsleep_end);
692 * Interlocked spinlock sleep. An exclusively held spinlock must
693 * be passed to ssleep(). The function will atomically release the
694 * spinlock and tsleep on the ident, then reacquire the spinlock and
697 * This routine is fairly important along the critical path, so optimize it
701 ssleep(const volatile void *ident, struct spinlock *spin, int flags,
702 const char *wmesg, int timo)
704 globaldata_t gd = mycpu;
707 _tsleep_interlock(gd, ident, flags);
708 spin_unlock_quick(gd, spin);
709 error = tsleep(ident, flags | PINTERLOCKED, wmesg, timo);
710 spin_lock_quick(gd, spin);
716 lksleep(const volatile void *ident, struct lock *lock, int flags,
717 const char *wmesg, int timo)
719 globaldata_t gd = mycpu;
722 _tsleep_interlock(gd, ident, flags);
723 lockmgr(lock, LK_RELEASE);
724 error = tsleep(ident, flags | PINTERLOCKED, wmesg, timo);
725 lockmgr(lock, LK_EXCLUSIVE);
731 * Interlocked mutex sleep. An exclusively held mutex must be passed
732 * to mtxsleep(). The function will atomically release the mutex
733 * and tsleep on the ident, then reacquire the mutex and return.
736 mtxsleep(const volatile void *ident, struct mtx *mtx, int flags,
737 const char *wmesg, int timo)
739 globaldata_t gd = mycpu;
742 _tsleep_interlock(gd, ident, flags);
744 error = tsleep(ident, flags | PINTERLOCKED, wmesg, timo);
745 mtx_lock_ex_quick(mtx, wmesg);
751 * Interlocked serializer sleep. An exclusively held serializer must
752 * be passed to zsleep(). The function will atomically release
753 * the serializer and tsleep on the ident, then reacquire the serializer
757 zsleep(const volatile void *ident, struct lwkt_serialize *slz, int flags,
758 const char *wmesg, int timo)
760 globaldata_t gd = mycpu;
763 ASSERT_SERIALIZED(slz);
765 _tsleep_interlock(gd, ident, flags);
766 lwkt_serialize_exit(slz);
767 ret = tsleep(ident, flags | PINTERLOCKED, wmesg, timo);
768 lwkt_serialize_enter(slz);
774 * Directly block on the LWKT thread by descheduling it. This
775 * is much faster then tsleep(), but the only legal way to wake
776 * us up is to directly schedule the thread.
778 * Setting TDF_SINTR will cause new signals to directly schedule us.
780 * This routine must be called while in a critical section.
783 lwkt_sleep(const char *wmesg, int flags)
785 thread_t td = curthread;
788 if ((flags & PCATCH) == 0 || td->td_lwp == NULL) {
789 td->td_flags |= TDF_BLOCKED;
790 td->td_wmesg = wmesg;
791 lwkt_deschedule_self(td);
794 td->td_flags &= ~TDF_BLOCKED;
797 if ((sig = CURSIG(td->td_lwp)) != 0) {
798 if (SIGISMEMBER(td->td_proc->p_sigacts->ps_sigintr, sig))
804 td->td_flags |= TDF_BLOCKED | TDF_SINTR;
805 td->td_wmesg = wmesg;
806 lwkt_deschedule_self(td);
808 td->td_flags &= ~(TDF_BLOCKED | TDF_SINTR);
814 * Implement the timeout for tsleep.
816 * This type of callout timeout is scheduled on the same cpu the process
817 * is sleeping on. Also, at the moment, the MP lock is held.
826 * We are going to have to get the lwp_token, which means we might
827 * block. This can race a tsleep getting woken up by other means
828 * so set TDF_TIMEOUT_RUNNING to force the tsleep to wait for our
829 * processing to complete (sorry tsleep!).
831 * We can safely set td_flags because td MUST be on the same cpu
834 KKASSERT(td->td_gd == mycpu);
836 td->td_flags |= TDF_TIMEOUT_RUNNING | TDF_TIMEOUT;
839 * This can block but TDF_TIMEOUT_RUNNING will prevent the thread
840 * from exiting the tsleep on us. The flag is interlocked by virtue
841 * of lp being on the same cpu as we are.
843 if ((lp = td->td_lwp) != NULL)
844 lwkt_gettoken(&lp->lwp_token);
846 KKASSERT(td->td_flags & TDF_TSLEEP_DESCHEDULED);
849 if (lp->lwp_proc->p_stat != SSTOP)
851 lwkt_reltoken(&lp->lwp_token);
856 KKASSERT(td->td_gd == mycpu);
857 td->td_flags &= ~TDF_TIMEOUT_RUNNING;
862 * Make all processes sleeping on the specified identifier runnable.
863 * count may be zero or one only.
865 * The domain encodes the sleep/wakeup domain, flags, plus the originating
868 * This call may run without the MP lock held. We can only manipulate thread
869 * state on the cpu owning the thread. We CANNOT manipulate process state
872 * _wakeup() can be passed to an IPI so we can't use (const volatile
876 _wakeup(void *ident, int domain)
888 logtsleep2(wakeup_beg, ident);
891 qp = &gd->gd_tsleep_hash[id];
893 for (td = TAILQ_FIRST(qp); td != NULL; td = ntd) {
894 ntd = TAILQ_NEXT(td, td_sleepq);
895 if (td->td_wchan == ident &&
896 td->td_wdomain == (domain & PDOMAIN_MASK)
898 KKASSERT(td->td_gd == gd);
900 td->td_wakefromcpu = PWAKEUP_DECODE(domain);
901 if (td->td_flags & TDF_TSLEEP_DESCHEDULED) {
903 if (domain & PWAKEUP_ONE)
912 * We finished checking the current cpu but there still may be
913 * more work to do. Either wakeup_one was requested and no matching
914 * thread was found, or a normal wakeup was requested and we have
915 * to continue checking cpus.
917 * It should be noted that this scheme is actually less expensive then
918 * the old scheme when waking up multiple threads, since we send
919 * only one IPI message per target candidate which may then schedule
920 * multiple threads. Before we could have wound up sending an IPI
921 * message for each thread on the target cpu (!= current cpu) that
922 * needed to be woken up.
924 * NOTE: Wakeups occuring on remote cpus are asynchronous. This
925 * should be ok since we are passing idents in the IPI rather then
928 if ((domain & PWAKEUP_MYCPU) == 0 &&
929 (mask = slpque_cpumasks[id] & gd->gd_other_cpus) != 0) {
930 lwkt_send_ipiq2_mask(mask, _wakeup, ident,
931 domain | PWAKEUP_MYCPU);
935 logtsleep1(wakeup_end);
940 * Wakeup all threads tsleep()ing on the specified ident, on all cpus
943 wakeup(const volatile void *ident)
945 globaldata_t gd = mycpu;
946 thread_t td = gd->gd_curthread;
948 if (td && (td->td_flags & TDF_DELAYED_WAKEUP)) {
949 if (!atomic_cmpset_ptr(&gd->gd_delayed_wakeup[0], NULL, ident)) {
950 if (!atomic_cmpset_ptr(&gd->gd_delayed_wakeup[1], NULL, ident))
951 _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, gd->gd_cpuid));
955 _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, gd->gd_cpuid));
959 * Wakeup one thread tsleep()ing on the specified ident, on any cpu.
962 wakeup_one(const volatile void *ident)
964 /* XXX potentially round-robin the first responding cpu */
965 _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, mycpu->gd_cpuid) |
970 * Wakeup threads tsleep()ing on the specified ident on the current cpu
974 wakeup_mycpu(const volatile void *ident)
976 _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, mycpu->gd_cpuid) |
981 * Wakeup one thread tsleep()ing on the specified ident on the current cpu
985 wakeup_mycpu_one(const volatile void *ident)
987 /* XXX potentially round-robin the first responding cpu */
988 _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, mycpu->gd_cpuid) |
989 PWAKEUP_MYCPU | PWAKEUP_ONE);
993 * Wakeup all thread tsleep()ing on the specified ident on the specified cpu
997 wakeup_oncpu(globaldata_t gd, const volatile void *ident)
1000 globaldata_t mygd = mycpu;
1002 _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, mygd->gd_cpuid) |
1005 lwkt_send_ipiq2(gd, _wakeup, __DEALL(ident),
1006 PWAKEUP_ENCODE(0, mygd->gd_cpuid) |
1010 _wakeup(__DEALL(ident), PWAKEUP_MYCPU);
1015 * Wakeup one thread tsleep()ing on the specified ident on the specified cpu
1019 wakeup_oncpu_one(globaldata_t gd, const volatile void *ident)
1022 globaldata_t mygd = mycpu;
1024 _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, mygd->gd_cpuid) |
1025 PWAKEUP_MYCPU | PWAKEUP_ONE);
1027 lwkt_send_ipiq2(gd, _wakeup, __DEALL(ident),
1028 PWAKEUP_ENCODE(0, mygd->gd_cpuid) |
1029 PWAKEUP_MYCPU | PWAKEUP_ONE);
1032 _wakeup(__DEALL(ident), PWAKEUP_MYCPU | PWAKEUP_ONE);
1037 * Wakeup all threads waiting on the specified ident that slept using
1038 * the specified domain, on all cpus.
1041 wakeup_domain(const volatile void *ident, int domain)
1043 _wakeup(__DEALL(ident), PWAKEUP_ENCODE(domain, mycpu->gd_cpuid));
1047 * Wakeup one thread waiting on the specified ident that slept using
1048 * the specified domain, on any cpu.
1051 wakeup_domain_one(const volatile void *ident, int domain)
1053 /* XXX potentially round-robin the first responding cpu */
1054 _wakeup(__DEALL(ident),
1055 PWAKEUP_ENCODE(domain, mycpu->gd_cpuid) | PWAKEUP_ONE);
1059 wakeup_start_delayed(void)
1061 globaldata_t gd = mycpu;
1064 gd->gd_curthread->td_flags |= TDF_DELAYED_WAKEUP;
1069 wakeup_end_delayed(void)
1071 globaldata_t gd = mycpu;
1073 if (gd->gd_curthread->td_flags & TDF_DELAYED_WAKEUP) {
1075 gd->gd_curthread->td_flags &= ~TDF_DELAYED_WAKEUP;
1076 if (gd->gd_delayed_wakeup[0] || gd->gd_delayed_wakeup[1]) {
1077 if (gd->gd_delayed_wakeup[0]) {
1078 wakeup(gd->gd_delayed_wakeup[0]);
1079 gd->gd_delayed_wakeup[0] = NULL;
1081 if (gd->gd_delayed_wakeup[1]) {
1082 wakeup(gd->gd_delayed_wakeup[1]);
1083 gd->gd_delayed_wakeup[1] = NULL;
1093 * Make a process runnable. lp->lwp_token must be held on call and this
1094 * function must be called from the cpu owning lp.
1096 * This only has an effect if we are in LSSTOP or LSSLEEP.
1099 setrunnable(struct lwp *lp)
1101 thread_t td = lp->lwp_thread;
1103 ASSERT_LWKT_TOKEN_HELD(&lp->lwp_token);
1104 KKASSERT(td->td_gd == mycpu);
1106 if (lp->lwp_stat == LSSTOP)
1107 lp->lwp_stat = LSSLEEP;
1108 if (lp->lwp_stat == LSSLEEP) {
1111 } else if (td->td_flags & TDF_SINTR) {
1118 * The process is stopped due to some condition, usually because p_stat is
1119 * set to SSTOP, but also possibly due to being traced.
1121 * Caller must hold p->p_token
1123 * NOTE! If the caller sets SSTOP, the caller must also clear P_WAITED
1124 * because the parent may check the child's status before the child actually
1125 * gets to this routine.
1127 * This routine is called with the current lwp only, typically just
1128 * before returning to userland if the process state is detected as
1129 * possibly being in a stopped state.
1134 struct lwp *lp = curthread->td_lwp;
1135 struct proc *p = lp->lwp_proc;
1138 lwkt_gettoken(&lp->lwp_token);
1142 * If LWP_MP_WSTOP is set, we were sleeping
1143 * while our process was stopped. At this point
1144 * we were already counted as stopped.
1146 if ((lp->lwp_mpflags & LWP_MP_WSTOP) == 0) {
1148 * If we're the last thread to stop, signal
1152 atomic_set_int(&lp->lwp_mpflags, LWP_MP_WSTOP);
1153 wakeup(&p->p_nstopped);
1154 if (p->p_nstopped == p->p_nthreads) {
1156 * Token required to interlock kern_wait()
1160 lwkt_gettoken(&q->p_token);
1161 p->p_flags &= ~P_WAITED;
1163 if ((q->p_sigacts->ps_flag & PS_NOCLDSTOP) == 0)
1164 ksignal(q, SIGCHLD);
1165 lwkt_reltoken(&q->p_token);
1169 while (p->p_stat == SSTOP) {
1170 lp->lwp_stat = LSSTOP;
1171 tsleep(p, 0, "stop", 0);
1174 atomic_clear_int(&lp->lwp_mpflags, LWP_MP_WSTOP);
1176 lwkt_reltoken(&lp->lwp_token);
1180 * Compute a tenex style load average of a quantity on
1181 * 1, 5 and 15 minute intervals.
1183 static int loadav_count_runnable(struct lwp *p, void *data);
1188 struct loadavg *avg;
1192 alllwp_scan(loadav_count_runnable, &nrun);
1194 for (i = 0; i < 3; i++) {
1195 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
1196 nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
1200 * Schedule the next update to occur after 5 seconds, but add a
1201 * random variation to avoid synchronisation with processes that
1202 * run at regular intervals.
1204 callout_reset(&loadav_callout, hz * 4 + (int)(krandom() % (hz * 2 + 1)),
1209 loadav_count_runnable(struct lwp *lp, void *data)
1214 switch (lp->lwp_stat) {
1216 if ((td = lp->lwp_thread) == NULL)
1218 if (td->td_flags & TDF_BLOCKED)
1231 sched_setup(void *dummy)
1233 callout_init_mp(&loadav_callout);
1234 callout_init_mp(&schedcpu_callout);
1236 /* Kick off timeout driven events by calling first time. */