kernel - Add wakeup() probe sysctl
[dragonfly.git] / sys / kern / kern_synch.c
blob4a0bb2a6e6237b732d85f26424db72ea51029dc8
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.
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. 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.
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.
34 * @(#)kern_synch.c 8.9 (Berkeley) 5/19/95
35 * $FreeBSD: src/sys/kern/kern_synch.c,v 1.87.2.6 2002/10/13 07:29:53 kbyanc Exp $
38 #include "opt_ktrace.h"
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/proc.h>
43 #include <sys/kernel.h>
44 #include <sys/signalvar.h>
45 #include <sys/resourcevar.h>
46 #include <sys/vmmeter.h>
47 #include <sys/sysctl.h>
48 #include <sys/priv.h>
49 #include <sys/lock.h>
50 #include <sys/uio.h>
51 #include <sys/kcollect.h>
52 #ifdef KTRACE
53 #include <sys/ktrace.h>
54 #endif
55 #include <sys/ktr.h>
56 #include <sys/serialize.h>
58 #include <sys/signal2.h>
59 #include <sys/thread2.h>
60 #include <sys/spinlock2.h>
61 #include <sys/mutex2.h>
63 #include <machine/cpu.h>
64 #include <machine/smp.h>
66 #include <vm/vm_extern.h>
68 struct tslpque {
69 TAILQ_HEAD(, thread) queue;
70 const volatile void *ident0;
71 const volatile void *ident1;
72 const volatile void *ident2;
73 const volatile void *ident3;
76 static void sched_setup (void *dummy);
77 SYSINIT(sched_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, sched_setup, NULL);
78 static void sched_dyninit (void *dummy);
79 SYSINIT(sched_dyninit, SI_BOOT1_DYNALLOC, SI_ORDER_FIRST, sched_dyninit, NULL);
81 int lbolt;
82 void *lbolt_syncer;
83 int ncpus;
84 int ncpus_fit, ncpus_fit_mask; /* note: mask not cpumask_t */
85 int safepri;
86 int tsleep_now_works;
87 int tsleep_crypto_dump = 0;
89 MALLOC_DEFINE(M_TSLEEP, "tslpque", "tsleep queues");
91 #define __DEALL(ident) __DEQUALIFY(void *, ident)
93 #if !defined(KTR_TSLEEP)
94 #define KTR_TSLEEP KTR_ALL
95 #endif
96 KTR_INFO_MASTER(tsleep);
97 KTR_INFO(KTR_TSLEEP, tsleep, tsleep_beg, 0, "tsleep enter %p", const volatile void *ident);
98 KTR_INFO(KTR_TSLEEP, tsleep, tsleep_end, 1, "tsleep exit");
99 KTR_INFO(KTR_TSLEEP, tsleep, wakeup_beg, 2, "wakeup enter %p", const volatile void *ident);
100 KTR_INFO(KTR_TSLEEP, tsleep, wakeup_end, 3, "wakeup exit");
101 KTR_INFO(KTR_TSLEEP, tsleep, ilockfail, 4, "interlock failed %p", const volatile void *ident);
103 #define logtsleep1(name) KTR_LOG(tsleep_ ## name)
104 #define logtsleep2(name, val) KTR_LOG(tsleep_ ## name, val)
106 struct loadavg averunnable =
107 { {0, 0, 0}, FSCALE }; /* load average, of runnable procs */
109 * Constants for averages over 1, 5, and 15 minutes
110 * when sampling at 5 second intervals.
112 static fixpt_t cexp[3] = {
113 0.9200444146293232 * FSCALE, /* exp(-1/12) */
114 0.9834714538216174 * FSCALE, /* exp(-1/60) */
115 0.9944598480048967 * FSCALE, /* exp(-1/180) */
118 static void endtsleep (void *);
119 static void loadav (void *arg);
120 static void schedcpu (void *arg);
122 static int pctcpu_decay = 10;
123 SYSCTL_INT(_kern, OID_AUTO, pctcpu_decay, CTLFLAG_RW,
124 &pctcpu_decay, 0, "");
127 * kernel uses `FSCALE', userland (SHOULD) use kern.fscale
129 int fscale __unused = FSCALE; /* exported to systat */
130 SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, "");
133 * Issue a wakeup() from userland (debugging)
135 static int
136 sysctl_wakeup(SYSCTL_HANDLER_ARGS)
138 uint64_t ident = 1;
139 int error = 0;
141 if (req->newptr != NULL) {
142 if (priv_check(curthread, PRIV_ROOT))
143 return (EPERM);
144 error = SYSCTL_IN(req, &ident, sizeof(ident));
145 if (error)
146 return error;
147 kprintf("issue wakeup %016jx\n", ident);
148 wakeup((void *)(intptr_t)ident);
150 if (req->oldptr != NULL) {
151 error = SYSCTL_OUT(req, &ident, sizeof(ident));
153 return error;
156 SYSCTL_PROC(_debug, OID_AUTO, wakeup, CTLTYPE_UQUAD|CTLFLAG_RW, 0, 0,
157 sysctl_wakeup, "Q", "issue wakeup(addr)");
160 * Recompute process priorities, once a second.
162 * Since the userland schedulers are typically event oriented, if the
163 * estcpu calculation at wakeup() time is not sufficient to make a
164 * process runnable relative to other processes in the system we have
165 * a 1-second recalc to help out.
167 * This code also allows us to store sysclock_t data in the process structure
168 * without fear of an overrun, since sysclock_t are guarenteed to hold
169 * several seconds worth of count.
171 * WARNING! callouts can preempt normal threads. However, they will not
172 * preempt a thread holding a spinlock so we *can* safely use spinlocks.
174 static int schedcpu_stats(struct proc *p, void *data __unused);
175 static int schedcpu_resource(struct proc *p, void *data __unused);
177 static void
178 schedcpu(void *arg)
180 allproc_scan(schedcpu_stats, NULL, 1);
181 allproc_scan(schedcpu_resource, NULL, 1);
182 if (mycpu->gd_cpuid == 0) {
183 wakeup((caddr_t)&lbolt);
184 wakeup(lbolt_syncer);
186 callout_reset(&mycpu->gd_schedcpu_callout, hz, schedcpu, NULL);
190 * General process statistics once a second
192 static int
193 schedcpu_stats(struct proc *p, void *data __unused)
195 struct lwp *lp;
198 * Threads may not be completely set up if process in SIDL state.
200 if (p->p_stat == SIDL)
201 return(0);
203 PHOLD(p);
204 if (lwkt_trytoken(&p->p_token) == FALSE) {
205 PRELE(p);
206 return(0);
209 p->p_swtime++;
210 FOREACH_LWP_IN_PROC(lp, p) {
211 if (lp->lwp_stat == LSSLEEP) {
212 ++lp->lwp_slptime;
213 if (lp->lwp_slptime == 1)
214 p->p_usched->uload_update(lp);
218 * Only recalculate processes that are active or have slept
219 * less then 2 seconds. The schedulers understand this.
220 * Otherwise decay by 50% per second.
222 if (lp->lwp_slptime <= 1) {
223 p->p_usched->recalculate(lp);
224 } else {
225 int decay;
227 decay = pctcpu_decay;
228 cpu_ccfence();
229 if (decay <= 1)
230 decay = 1;
231 if (decay > 100)
232 decay = 100;
233 lp->lwp_pctcpu = (lp->lwp_pctcpu * (decay - 1)) / decay;
236 lwkt_reltoken(&p->p_token);
237 lwkt_yield();
238 PRELE(p);
239 return(0);
243 * Resource checks. XXX break out since ksignal/killproc can block,
244 * limiting us to one process killed per second. There is probably
245 * a better way.
247 static int
248 schedcpu_resource(struct proc *p, void *data __unused)
250 u_int64_t ttime;
251 struct lwp *lp;
253 if (p->p_stat == SIDL)
254 return(0);
256 PHOLD(p);
257 if (lwkt_trytoken(&p->p_token) == FALSE) {
258 PRELE(p);
259 return(0);
262 if (p->p_stat == SZOMB || p->p_limit == NULL) {
263 lwkt_reltoken(&p->p_token);
264 PRELE(p);
265 return(0);
268 ttime = 0;
269 FOREACH_LWP_IN_PROC(lp, p) {
271 * We may have caught an lp in the middle of being
272 * created, lwp_thread can be NULL.
274 if (lp->lwp_thread) {
275 ttime += lp->lwp_thread->td_sticks;
276 ttime += lp->lwp_thread->td_uticks;
280 switch(plimit_testcpulimit(p->p_limit, ttime)) {
281 case PLIMIT_TESTCPU_KILL:
282 killproc(p, "exceeded maximum CPU limit");
283 break;
284 case PLIMIT_TESTCPU_XCPU:
285 if ((p->p_flags & P_XCPU) == 0) {
286 p->p_flags |= P_XCPU;
287 ksignal(p, SIGXCPU);
289 break;
290 default:
291 break;
293 lwkt_reltoken(&p->p_token);
294 lwkt_yield();
295 PRELE(p);
296 return(0);
300 * This is only used by ps. Generate a cpu percentage use over
301 * a period of one second.
303 void
304 updatepcpu(struct lwp *lp, int cpticks, int ttlticks)
306 fixpt_t acc;
307 int remticks;
309 acc = (cpticks << FSHIFT) / ttlticks;
310 if (ttlticks >= ESTCPUFREQ) {
311 lp->lwp_pctcpu = acc;
312 } else {
313 remticks = ESTCPUFREQ - ttlticks;
314 lp->lwp_pctcpu = (acc * ttlticks + lp->lwp_pctcpu * remticks) /
315 ESTCPUFREQ;
320 * Handy macros to calculate hash indices. LOOKUP() calculates the
321 * global cpumask hash index, TCHASHSHIFT() converts that into the
322 * pcpu hash index.
324 * By making the pcpu hash arrays smaller we save a significant amount
325 * of memory at very low cost. The real cost is in IPIs, which are handled
326 * by the much larger global cpumask hash table.
328 #define LOOKUP_PRIME 66555444443333333ULL
329 #define LOOKUP(x) ((((uintptr_t)(x) + ((uintptr_t)(x) >> 18)) ^ \
330 LOOKUP_PRIME) % slpque_tablesize)
331 #define TCHASHSHIFT(x) ((x) >> 4)
333 static uint32_t slpque_tablesize;
334 static cpumask_t *slpque_cpumasks;
336 SYSCTL_UINT(_kern, OID_AUTO, slpque_tablesize, CTLFLAG_RD, &slpque_tablesize,
337 0, "");
340 * This is a dandy function that allows us to interlock tsleep/wakeup
341 * operations with unspecified upper level locks, such as lockmgr locks,
342 * simply by holding a critical section. The sequence is:
344 * (acquire upper level lock)
345 * tsleep_interlock(blah)
346 * (release upper level lock)
347 * tsleep(blah, ...)
349 * Basically this functions queues us on the tsleep queue without actually
350 * descheduling us. When tsleep() is later called with PINTERLOCK it
351 * assumes the thread was already queued, otherwise it queues it there.
353 * Thus it is possible to receive the wakeup prior to going to sleep and
354 * the race conditions are covered.
356 static __inline void
357 _tsleep_interlock(globaldata_t gd, const volatile void *ident, int flags)
359 thread_t td = gd->gd_curthread;
360 struct tslpque *qp;
361 uint32_t cid;
362 uint32_t gid;
364 if (ident == NULL) {
365 kprintf("tsleep_interlock: NULL ident %s\n", td->td_comm);
366 print_backtrace(5);
369 crit_enter_quick(td);
370 if (td->td_flags & TDF_TSLEEPQ) {
371 cid = LOOKUP(td->td_wchan);
372 gid = TCHASHSHIFT(cid);
373 qp = &gd->gd_tsleep_hash[gid];
374 TAILQ_REMOVE(&qp->queue, td, td_sleepq);
375 if (TAILQ_FIRST(&qp->queue) == NULL) {
376 qp->ident0 = NULL;
377 qp->ident1 = NULL;
378 qp->ident2 = NULL;
379 qp->ident3 = NULL;
380 ATOMIC_CPUMASK_NANDBIT(slpque_cpumasks[cid],
381 gd->gd_cpuid);
383 } else {
384 td->td_flags |= TDF_TSLEEPQ;
386 cid = LOOKUP(ident);
387 gid = TCHASHSHIFT(cid);
388 qp = &gd->gd_tsleep_hash[gid];
389 TAILQ_INSERT_TAIL(&qp->queue, td, td_sleepq);
390 if (qp->ident0 != ident && qp->ident1 != ident &&
391 qp->ident2 != ident && qp->ident3 != ident) {
392 if (qp->ident0 == NULL)
393 qp->ident0 = ident;
394 else if (qp->ident1 == NULL)
395 qp->ident1 = ident;
396 else if (qp->ident2 == NULL)
397 qp->ident2 = ident;
398 else if (qp->ident3 == NULL)
399 qp->ident3 = ident;
400 else
401 qp->ident0 = (void *)(intptr_t)-1;
403 ATOMIC_CPUMASK_ORBIT(slpque_cpumasks[cid], gd->gd_cpuid);
404 td->td_wchan = ident;
405 td->td_wdomain = flags & PDOMAIN_MASK;
406 crit_exit_quick(td);
409 void
410 tsleep_interlock(const volatile void *ident, int flags)
412 _tsleep_interlock(mycpu, ident, flags);
416 * Remove thread from sleepq. Must be called with a critical section held.
417 * The thread must not be migrating.
419 static __inline void
420 _tsleep_remove(thread_t td)
422 globaldata_t gd = mycpu;
423 struct tslpque *qp;
424 uint32_t cid;
425 uint32_t gid;
427 KKASSERT(td->td_gd == gd && IN_CRITICAL_SECT(td));
428 KKASSERT((td->td_flags & TDF_MIGRATING) == 0);
429 if (td->td_flags & TDF_TSLEEPQ) {
430 td->td_flags &= ~TDF_TSLEEPQ;
431 cid = LOOKUP(td->td_wchan);
432 gid = TCHASHSHIFT(cid);
433 qp = &gd->gd_tsleep_hash[gid];
434 TAILQ_REMOVE(&qp->queue, td, td_sleepq);
435 if (TAILQ_FIRST(&qp->queue) == NULL) {
436 ATOMIC_CPUMASK_NANDBIT(slpque_cpumasks[cid],
437 gd->gd_cpuid);
439 td->td_wchan = NULL;
440 td->td_wdomain = 0;
444 void
445 tsleep_remove(thread_t td)
447 _tsleep_remove(td);
451 * General sleep call. Suspends the current process until a wakeup is
452 * performed on the specified identifier. The process will then be made
453 * runnable with the specified priority. Sleeps at most timo/hz seconds
454 * (0 means no timeout). If flags includes PCATCH flag, signals are checked
455 * before and after sleeping, else signals are not checked. Returns 0 if
456 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a
457 * signal needs to be delivered, ERESTART is returned if the current system
458 * call should be restarted if possible, and EINTR is returned if the system
459 * call should be interrupted by the signal (return EINTR).
461 * Note that if we are a process, we release_curproc() before messing with
462 * the LWKT scheduler.
464 * During autoconfiguration or after a panic, a sleep will simply
465 * lower the priority briefly to allow interrupts, then return.
467 * WARNING! This code can't block (short of switching away), or bad things
468 * will happen. No getting tokens, no blocking locks, etc.
471 tsleep(const volatile void *ident, int flags, const char *wmesg, int timo)
473 struct thread *td = curthread;
474 struct lwp *lp = td->td_lwp;
475 struct proc *p = td->td_proc; /* may be NULL */
476 globaldata_t gd;
477 int sig;
478 int catch;
479 int error;
480 int oldpri;
481 struct callout thandle;
484 * Currently a severe hack. Make sure any delayed wakeups
485 * are flushed before we sleep or we might deadlock on whatever
486 * event we are sleeping on.
488 if (td->td_flags & TDF_DELAYED_WAKEUP)
489 wakeup_end_delayed();
492 * NOTE: removed KTRPOINT, it could cause races due to blocking
493 * even in stable. Just scrap it for now.
495 if (!tsleep_crypto_dump && (tsleep_now_works == 0 || panicstr)) {
497 * After a panic, or before we actually have an operational
498 * softclock, just give interrupts a chance, then just return;
500 * don't run any other procs or panic below,
501 * in case this is the idle process and already asleep.
503 splz();
504 oldpri = td->td_pri;
505 lwkt_setpri_self(safepri);
506 lwkt_switch();
507 lwkt_setpri_self(oldpri);
508 return (0);
510 logtsleep2(tsleep_beg, ident);
511 gd = td->td_gd;
512 KKASSERT(td != &gd->gd_idlethread); /* you must be kidding! */
513 td->td_wakefromcpu = -1; /* overwritten by _wakeup */
516 * NOTE: all of this occurs on the current cpu, including any
517 * callout-based wakeups, so a critical section is a sufficient
518 * interlock.
520 * The entire sequence through to where we actually sleep must
521 * run without breaking the critical section.
523 catch = flags & PCATCH;
524 error = 0;
525 sig = 0;
527 crit_enter_quick(td);
529 KASSERT(ident != NULL, ("tsleep: no ident"));
530 KASSERT(lp == NULL ||
531 lp->lwp_stat == LSRUN || /* Obvious */
532 lp->lwp_stat == LSSTOP, /* Set in tstop */
533 ("tsleep %p %s %d",
534 ident, wmesg, lp->lwp_stat));
537 * We interlock the sleep queue if the caller has not already done
538 * it for us. This must be done before we potentially acquire any
539 * tokens or we can loose the wakeup.
541 if ((flags & PINTERLOCKED) == 0) {
542 _tsleep_interlock(gd, ident, flags);
546 * Setup for the current process (if this is a process). We must
547 * interlock with lwp_token to avoid remote wakeup races via
548 * setrunnable()
550 if (lp) {
551 lwkt_gettoken(&lp->lwp_token);
554 * If the umbrella process is in the SCORE state then
555 * make sure that the thread is flagged going into a
556 * normal sleep to allow the core dump to proceed, otherwise
557 * the coredump can end up waiting forever. If the normal
558 * sleep is woken up, the thread will enter a stopped state
559 * upon return to userland.
561 * We do not want to interrupt or cause a thread exist at
562 * this juncture because that will mess-up the state the
563 * coredump is trying to save.
565 if (p->p_stat == SCORE &&
566 (lp->lwp_mpflags & LWP_MP_WSTOP) == 0) {
567 atomic_set_int(&lp->lwp_mpflags, LWP_MP_WSTOP);
568 ++p->p_nstopped;
572 * PCATCH requested.
574 if (catch) {
576 * Early termination if PCATCH was set and a
577 * signal is pending, interlocked with the
578 * critical section.
580 * Early termination only occurs when tsleep() is
581 * entered while in a normal LSRUN state.
583 if ((sig = CURSIG(lp)) != 0)
584 goto resume;
587 * Causes ksignal to wake us up if a signal is
588 * received (interlocked with lp->lwp_token).
590 lp->lwp_flags |= LWP_SINTR;
592 } else {
593 KKASSERT(p == NULL);
597 * Make sure the current process has been untangled from
598 * the userland scheduler and initialize slptime to start
599 * counting.
601 * NOTE: td->td_wakefromcpu is pre-set by the release function
602 * for the dfly scheduler, and then adjusted by _wakeup()
604 if (lp) {
605 p->p_usched->release_curproc(lp);
606 lp->lwp_slptime = 0;
610 * If the interlocked flag is set but our cpu bit in the slpqueue
611 * is no longer set, then a wakeup was processed inbetween the
612 * tsleep_interlock() (ours or the callers), and here. This can
613 * occur under numerous circumstances including when we release the
614 * current process.
616 * Extreme loads can cause the sending of an IPI (e.g. wakeup()'s)
617 * to process incoming IPIs, thus draining incoming wakeups.
619 if ((td->td_flags & TDF_TSLEEPQ) == 0) {
620 logtsleep2(ilockfail, ident);
621 goto resume;
625 * scheduling is blocked while in a critical section. Coincide
626 * the descheduled-by-tsleep flag with the descheduling of the
627 * lwkt.
629 * The timer callout is localized on our cpu and interlocked by
630 * our critical section.
632 lwkt_deschedule_self(td);
633 td->td_flags |= TDF_TSLEEP_DESCHEDULED;
634 td->td_wmesg = wmesg;
637 * Setup the timeout, if any. The timeout is only operable while
638 * the thread is flagged descheduled.
640 KKASSERT((td->td_flags & TDF_TIMEOUT) == 0);
641 if (timo) {
642 callout_init_mp(&thandle);
643 callout_reset(&thandle, timo, endtsleep, td);
647 * Beddy bye bye.
649 if (lp) {
651 * Ok, we are sleeping. Place us in the SSLEEP state.
653 KKASSERT((lp->lwp_mpflags & LWP_MP_ONRUNQ) == 0);
656 * tstop() sets LSSTOP, so don't fiddle with that.
658 if (lp->lwp_stat != LSSTOP)
659 lp->lwp_stat = LSSLEEP;
660 lp->lwp_ru.ru_nvcsw++;
661 p->p_usched->uload_update(lp);
662 lwkt_switch();
665 * And when we are woken up, put us back in LSRUN. If we
666 * slept for over a second, recalculate our estcpu.
668 lp->lwp_stat = LSRUN;
669 if (lp->lwp_slptime) {
670 p->p_usched->uload_update(lp);
671 p->p_usched->recalculate(lp);
673 lp->lwp_slptime = 0;
674 } else {
675 lwkt_switch();
679 * Make sure we haven't switched cpus while we were asleep. It's
680 * not supposed to happen. Cleanup our temporary flags.
682 KKASSERT(gd == td->td_gd);
685 * Cleanup the timeout. If the timeout has already occured thandle
686 * has already been stopped, otherwise stop thandle. If the timeout
687 * is running (the callout thread must be blocked trying to get
688 * lwp_token) then wait for us to get scheduled.
690 if (timo) {
691 while (td->td_flags & TDF_TIMEOUT_RUNNING) {
692 /* else we won't get rescheduled! */
693 if (lp->lwp_stat != LSSTOP)
694 lp->lwp_stat = LSSLEEP;
695 lwkt_deschedule_self(td);
696 td->td_wmesg = "tsrace";
697 lwkt_switch();
698 kprintf("td %p %s: timeout race\n", td, td->td_comm);
700 if (td->td_flags & TDF_TIMEOUT) {
701 td->td_flags &= ~TDF_TIMEOUT;
702 error = EWOULDBLOCK;
703 } else {
704 /* does not block when on same cpu */
705 callout_stop(&thandle);
708 td->td_flags &= ~TDF_TSLEEP_DESCHEDULED;
711 * Make sure we have been removed from the sleepq. In most
712 * cases this will have been done for us already but it is
713 * possible for a scheduling IPI to be in-flight from a
714 * previous tsleep/tsleep_interlock() or due to a straight-out
715 * call to lwkt_schedule() (in the case of an interrupt thread),
716 * causing a spurious wakeup.
718 _tsleep_remove(td);
719 td->td_wmesg = NULL;
722 * Figure out the correct error return. If interrupted by a
723 * signal we want to return EINTR or ERESTART.
725 resume:
726 if (lp) {
727 if (catch && error == 0) {
728 if (sig != 0 || (sig = CURSIG(lp))) {
729 if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
730 error = EINTR;
731 else
732 error = ERESTART;
736 lp->lwp_flags &= ~LWP_SINTR;
739 * Unconditionally set us to LSRUN on resume. lwp_stat could
740 * be in a weird state due to the goto resume, particularly
741 * when tsleep() is called from tstop().
743 lp->lwp_stat = LSRUN;
744 lwkt_reltoken(&lp->lwp_token);
746 logtsleep1(tsleep_end);
747 crit_exit_quick(td);
748 return (error);
752 * Interlocked spinlock sleep. An exclusively held spinlock must
753 * be passed to ssleep(). The function will atomically release the
754 * spinlock and tsleep on the ident, then reacquire the spinlock and
755 * return.
757 * This routine is fairly important along the critical path, so optimize it
758 * heavily.
761 ssleep(const volatile void *ident, struct spinlock *spin, int flags,
762 const char *wmesg, int timo)
764 globaldata_t gd = mycpu;
765 int error;
767 _tsleep_interlock(gd, ident, flags);
768 spin_unlock_quick(gd, spin);
769 error = tsleep(ident, flags | PINTERLOCKED, wmesg, timo);
770 KKASSERT(gd == mycpu);
771 _spin_lock_quick(gd, spin, wmesg);
773 return (error);
777 lksleep(const volatile void *ident, struct lock *lock, int flags,
778 const char *wmesg, int timo)
780 globaldata_t gd = mycpu;
781 int error;
783 _tsleep_interlock(gd, ident, flags);
784 lockmgr(lock, LK_RELEASE);
785 error = tsleep(ident, flags | PINTERLOCKED, wmesg, timo);
786 lockmgr(lock, LK_EXCLUSIVE);
788 return (error);
792 * Interlocked mutex sleep. An exclusively held mutex must be passed
793 * to mtxsleep(). The function will atomically release the mutex
794 * and tsleep on the ident, then reacquire the mutex and return.
797 mtxsleep(const volatile void *ident, struct mtx *mtx, int flags,
798 const char *wmesg, int timo)
800 globaldata_t gd = mycpu;
801 int error;
803 _tsleep_interlock(gd, ident, flags);
804 mtx_unlock(mtx);
805 error = tsleep(ident, flags | PINTERLOCKED, wmesg, timo);
806 mtx_lock_ex_quick(mtx);
808 return (error);
812 * Interlocked serializer sleep. An exclusively held serializer must
813 * be passed to zsleep(). The function will atomically release
814 * the serializer and tsleep on the ident, then reacquire the serializer
815 * and return.
818 zsleep(const volatile void *ident, struct lwkt_serialize *slz, int flags,
819 const char *wmesg, int timo)
821 globaldata_t gd = mycpu;
822 int ret;
824 ASSERT_SERIALIZED(slz);
826 _tsleep_interlock(gd, ident, flags);
827 lwkt_serialize_exit(slz);
828 ret = tsleep(ident, flags | PINTERLOCKED, wmesg, timo);
829 lwkt_serialize_enter(slz);
831 return ret;
835 * Directly block on the LWKT thread by descheduling it. This
836 * is much faster then tsleep(), but the only legal way to wake
837 * us up is to directly schedule the thread.
839 * Setting TDF_SINTR will cause new signals to directly schedule us.
841 * This routine must be called while in a critical section.
844 lwkt_sleep(const char *wmesg, int flags)
846 thread_t td = curthread;
847 int sig;
849 if ((flags & PCATCH) == 0 || td->td_lwp == NULL) {
850 td->td_flags |= TDF_BLOCKED;
851 td->td_wmesg = wmesg;
852 lwkt_deschedule_self(td);
853 lwkt_switch();
854 td->td_wmesg = NULL;
855 td->td_flags &= ~TDF_BLOCKED;
856 return(0);
858 if ((sig = CURSIG(td->td_lwp)) != 0) {
859 if (SIGISMEMBER(td->td_proc->p_sigacts->ps_sigintr, sig))
860 return(EINTR);
861 else
862 return(ERESTART);
865 td->td_flags |= TDF_BLOCKED | TDF_SINTR;
866 td->td_wmesg = wmesg;
867 lwkt_deschedule_self(td);
868 lwkt_switch();
869 td->td_flags &= ~(TDF_BLOCKED | TDF_SINTR);
870 td->td_wmesg = NULL;
871 return(0);
875 * Implement the timeout for tsleep.
877 * This type of callout timeout is scheduled on the same cpu the process
878 * is sleeping on. Also, at the moment, the MP lock is held.
880 static void
881 endtsleep(void *arg)
883 thread_t td = arg;
884 struct lwp *lp;
887 * We are going to have to get the lwp_token, which means we might
888 * block. This can race a tsleep getting woken up by other means
889 * so set TDF_TIMEOUT_RUNNING to force the tsleep to wait for our
890 * processing to complete (sorry tsleep!).
892 * We can safely set td_flags because td MUST be on the same cpu
893 * as we are.
895 KKASSERT(td->td_gd == mycpu);
896 crit_enter();
897 td->td_flags |= TDF_TIMEOUT_RUNNING | TDF_TIMEOUT;
900 * This can block but TDF_TIMEOUT_RUNNING will prevent the thread
901 * from exiting the tsleep on us. The flag is interlocked by virtue
902 * of lp being on the same cpu as we are.
904 if ((lp = td->td_lwp) != NULL)
905 lwkt_gettoken(&lp->lwp_token);
907 KKASSERT(td->td_flags & TDF_TSLEEP_DESCHEDULED);
909 if (lp) {
911 * callout timer should normally never be set in tstop()
912 * because it passes a timeout of 0. However, there is a
913 * case during thread exit (which SSTOP's all the threads)
914 * for which tstop() must break out and can (properly) leave
915 * the thread in LSSTOP.
917 KKASSERT(lp->lwp_stat != LSSTOP ||
918 (lp->lwp_mpflags & LWP_MP_WEXIT));
919 setrunnable(lp);
920 lwkt_reltoken(&lp->lwp_token);
921 } else {
922 _tsleep_remove(td);
923 lwkt_schedule(td);
925 KKASSERT(td->td_gd == mycpu);
926 td->td_flags &= ~TDF_TIMEOUT_RUNNING;
927 crit_exit();
931 * Make all processes sleeping on the specified identifier runnable.
932 * count may be zero or one only.
934 * The domain encodes the sleep/wakeup domain, flags, plus the originating
935 * cpu.
937 * This call may run without the MP lock held. We can only manipulate thread
938 * state on the cpu owning the thread. We CANNOT manipulate process state
939 * at all.
941 * _wakeup() can be passed to an IPI so we can't use (const volatile
942 * void *ident).
944 static void
945 _wakeup(void *ident, int domain)
947 struct tslpque *qp;
948 struct thread *td;
949 struct thread *ntd;
950 globaldata_t gd;
951 cpumask_t mask;
952 uint32_t cid;
953 uint32_t gid;
954 int wids = 0;
956 crit_enter();
957 logtsleep2(wakeup_beg, ident);
958 gd = mycpu;
959 cid = LOOKUP(ident);
960 gid = TCHASHSHIFT(cid);
961 qp = &gd->gd_tsleep_hash[gid];
962 restart:
963 for (td = TAILQ_FIRST(&qp->queue); td != NULL; td = ntd) {
964 ntd = TAILQ_NEXT(td, td_sleepq);
965 if (td->td_wchan == ident &&
966 td->td_wdomain == (domain & PDOMAIN_MASK)
968 KKASSERT(td->td_gd == gd);
969 _tsleep_remove(td);
970 td->td_wakefromcpu = PWAKEUP_DECODE(domain);
971 if (td->td_flags & TDF_TSLEEP_DESCHEDULED) {
972 lwkt_schedule(td);
973 if (domain & PWAKEUP_ONE)
974 goto done;
976 goto restart;
978 if (td->td_wchan == qp->ident0)
979 wids |= 1;
980 else if (td->td_wchan == qp->ident1)
981 wids |= 2;
982 else if (td->td_wchan == qp->ident2)
983 wids |= 4;
984 else if (td->td_wchan == qp->ident3)
985 wids |= 8;
986 else
987 wids |= 16; /* force ident0 to be retained (-1) */
991 * Because a bunch of cpumask array entries cover the same queue, it
992 * is possible for our bit to remain set in some of them and cause
993 * spurious wakeup IPIs later on. Make sure that the bit is cleared
994 * when a spurious IPI occurs to prevent further spurious IPIs.
996 if (TAILQ_FIRST(&qp->queue) == NULL) {
997 ATOMIC_CPUMASK_NANDBIT(slpque_cpumasks[cid], gd->gd_cpuid);
998 qp->ident0 = NULL;
999 qp->ident1 = NULL;
1000 qp->ident2 = NULL;
1001 qp->ident3 = NULL;
1002 } else {
1003 if ((wids & 1) == 0) {
1004 if ((wids & 16) == 0) {
1005 qp->ident0 = NULL;
1006 } else {
1007 KKASSERT(qp->ident0 == (void *)(intptr_t)-1);
1010 if ((wids & 2) == 0)
1011 qp->ident1 = NULL;
1012 if ((wids & 4) == 0)
1013 qp->ident2 = NULL;
1014 if ((wids & 8) == 0)
1015 qp->ident3 = NULL;
1019 * We finished checking the current cpu but there still may be
1020 * more work to do. Either wakeup_one was requested and no matching
1021 * thread was found, or a normal wakeup was requested and we have
1022 * to continue checking cpus.
1024 * It should be noted that this scheme is actually less expensive then
1025 * the old scheme when waking up multiple threads, since we send
1026 * only one IPI message per target candidate which may then schedule
1027 * multiple threads. Before we could have wound up sending an IPI
1028 * message for each thread on the target cpu (!= current cpu) that
1029 * needed to be woken up.
1031 * NOTE: Wakeups occuring on remote cpus are asynchronous. This
1032 * should be ok since we are passing idents in the IPI rather
1033 * then thread pointers.
1035 * NOTE: We MUST mfence (or use an atomic op) prior to reading
1036 * the cpumask, as another cpu may have written to it in
1037 * a fashion interlocked with whatever the caller did before
1038 * calling wakeup(). Otherwise we might miss the interaction
1039 * (kern_mutex.c can cause this problem).
1041 * lfence is insufficient as it may allow a written state to
1042 * reorder around the cpumask load.
1044 if ((domain & PWAKEUP_MYCPU) == 0) {
1045 globaldata_t tgd;
1046 const volatile void *id0;
1047 int n;
1049 cpu_mfence();
1050 /* cpu_lfence(); */
1051 mask = slpque_cpumasks[cid];
1052 CPUMASK_ANDMASK(mask, gd->gd_other_cpus);
1053 while (CPUMASK_TESTNZERO(mask)) {
1054 n = BSRCPUMASK(mask);
1055 CPUMASK_NANDBIT(mask, n);
1056 tgd = globaldata_find(n);
1059 * Both ident0 compares must from a single load
1060 * to avoid ident0 update races crossing the two
1061 * compares.
1063 qp = &tgd->gd_tsleep_hash[gid];
1064 id0 = qp->ident0;
1065 cpu_ccfence();
1066 if (id0 == (void *)(intptr_t)-1) {
1067 lwkt_send_ipiq2(tgd, _wakeup, ident,
1068 domain | PWAKEUP_MYCPU);
1069 ++tgd->gd_cnt.v_wakeup_colls;
1070 } else if (id0 == ident ||
1071 qp->ident1 == ident ||
1072 qp->ident2 == ident ||
1073 qp->ident3 == ident) {
1074 lwkt_send_ipiq2(tgd, _wakeup, ident,
1075 domain | PWAKEUP_MYCPU);
1078 #if 0
1079 if (CPUMASK_TESTNZERO(mask)) {
1080 lwkt_send_ipiq2_mask(mask, _wakeup, ident,
1081 domain | PWAKEUP_MYCPU);
1083 #endif
1085 done:
1086 logtsleep1(wakeup_end);
1087 crit_exit();
1091 * Wakeup all threads tsleep()ing on the specified ident, on all cpus
1093 void
1094 wakeup(const volatile void *ident)
1096 globaldata_t gd = mycpu;
1097 thread_t td = gd->gd_curthread;
1099 if (td && (td->td_flags & TDF_DELAYED_WAKEUP)) {
1101 * If we are in a delayed wakeup section, record up to two wakeups in
1102 * a per-CPU queue and issue them when we block or exit the delayed
1103 * wakeup section.
1105 if (atomic_cmpset_ptr(&gd->gd_delayed_wakeup[0], NULL, ident))
1106 return;
1107 if (atomic_cmpset_ptr(&gd->gd_delayed_wakeup[1], NULL, ident))
1108 return;
1110 ident = atomic_swap_ptr(__DEQUALIFY(volatile void **, &gd->gd_delayed_wakeup[1]),
1111 __DEALL(ident));
1112 ident = atomic_swap_ptr(__DEQUALIFY(volatile void **, &gd->gd_delayed_wakeup[0]),
1113 __DEALL(ident));
1116 _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, gd->gd_cpuid));
1120 * Wakeup one thread tsleep()ing on the specified ident, on any cpu.
1122 void
1123 wakeup_one(const volatile void *ident)
1125 /* XXX potentially round-robin the first responding cpu */
1126 _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, mycpu->gd_cpuid) |
1127 PWAKEUP_ONE);
1131 * Wakeup threads tsleep()ing on the specified ident on the current cpu
1132 * only.
1134 void
1135 wakeup_mycpu(const volatile void *ident)
1137 _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, mycpu->gd_cpuid) |
1138 PWAKEUP_MYCPU);
1142 * Wakeup one thread tsleep()ing on the specified ident on the current cpu
1143 * only.
1145 void
1146 wakeup_mycpu_one(const volatile void *ident)
1148 /* XXX potentially round-robin the first responding cpu */
1149 _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, mycpu->gd_cpuid) |
1150 PWAKEUP_MYCPU | PWAKEUP_ONE);
1154 * Wakeup all thread tsleep()ing on the specified ident on the specified cpu
1155 * only.
1157 void
1158 wakeup_oncpu(globaldata_t gd, const volatile void *ident)
1160 globaldata_t mygd = mycpu;
1161 if (gd == mycpu) {
1162 _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, mygd->gd_cpuid) |
1163 PWAKEUP_MYCPU);
1164 } else {
1165 lwkt_send_ipiq2(gd, _wakeup, __DEALL(ident),
1166 PWAKEUP_ENCODE(0, mygd->gd_cpuid) |
1167 PWAKEUP_MYCPU);
1172 * Wakeup one thread tsleep()ing on the specified ident on the specified cpu
1173 * only.
1175 void
1176 wakeup_oncpu_one(globaldata_t gd, const volatile void *ident)
1178 globaldata_t mygd = mycpu;
1179 if (gd == mygd) {
1180 _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, mygd->gd_cpuid) |
1181 PWAKEUP_MYCPU | PWAKEUP_ONE);
1182 } else {
1183 lwkt_send_ipiq2(gd, _wakeup, __DEALL(ident),
1184 PWAKEUP_ENCODE(0, mygd->gd_cpuid) |
1185 PWAKEUP_MYCPU | PWAKEUP_ONE);
1190 * Wakeup all threads waiting on the specified ident that slept using
1191 * the specified domain, on all cpus.
1193 void
1194 wakeup_domain(const volatile void *ident, int domain)
1196 _wakeup(__DEALL(ident), PWAKEUP_ENCODE(domain, mycpu->gd_cpuid));
1200 * Wakeup one thread waiting on the specified ident that slept using
1201 * the specified domain, on any cpu.
1203 void
1204 wakeup_domain_one(const volatile void *ident, int domain)
1206 /* XXX potentially round-robin the first responding cpu */
1207 _wakeup(__DEALL(ident),
1208 PWAKEUP_ENCODE(domain, mycpu->gd_cpuid) | PWAKEUP_ONE);
1211 void
1212 wakeup_start_delayed(void)
1214 globaldata_t gd = mycpu;
1216 crit_enter();
1217 gd->gd_curthread->td_flags |= TDF_DELAYED_WAKEUP;
1218 crit_exit();
1221 void
1222 wakeup_end_delayed(void)
1224 globaldata_t gd = mycpu;
1226 if (gd->gd_curthread->td_flags & TDF_DELAYED_WAKEUP) {
1227 crit_enter();
1228 gd->gd_curthread->td_flags &= ~TDF_DELAYED_WAKEUP;
1229 if (gd->gd_delayed_wakeup[0] || gd->gd_delayed_wakeup[1]) {
1230 if (gd->gd_delayed_wakeup[0]) {
1231 wakeup(gd->gd_delayed_wakeup[0]);
1232 gd->gd_delayed_wakeup[0] = NULL;
1234 if (gd->gd_delayed_wakeup[1]) {
1235 wakeup(gd->gd_delayed_wakeup[1]);
1236 gd->gd_delayed_wakeup[1] = NULL;
1239 crit_exit();
1244 * setrunnable()
1246 * Make a process runnable. lp->lwp_token must be held on call and this
1247 * function must be called from the cpu owning lp.
1249 * This only has an effect if we are in LSSTOP or LSSLEEP.
1251 void
1252 setrunnable(struct lwp *lp)
1254 thread_t td = lp->lwp_thread;
1256 ASSERT_LWKT_TOKEN_HELD(&lp->lwp_token);
1257 KKASSERT(td->td_gd == mycpu);
1258 crit_enter();
1259 if (lp->lwp_stat == LSSTOP)
1260 lp->lwp_stat = LSSLEEP;
1261 if (lp->lwp_stat == LSSLEEP) {
1262 _tsleep_remove(td);
1263 lwkt_schedule(td);
1264 } else if (td->td_flags & TDF_SINTR) {
1265 lwkt_schedule(td);
1267 crit_exit();
1271 * The process is stopped due to some condition, usually because p_stat is
1272 * set to SSTOP, but also possibly due to being traced.
1274 * Caller must hold p->p_token
1276 * NOTE! If the caller sets SSTOP, the caller must also clear P_WAITED
1277 * because the parent may check the child's status before the child actually
1278 * gets to this routine.
1280 * This routine is called with the current lwp only, typically just
1281 * before returning to userland if the process state is detected as
1282 * possibly being in a stopped state.
1284 void
1285 tstop(void)
1287 struct lwp *lp = curthread->td_lwp;
1288 struct proc *p = lp->lwp_proc;
1289 struct proc *q;
1291 lwkt_gettoken(&lp->lwp_token);
1292 crit_enter();
1295 * If LWP_MP_WSTOP is set, we were sleeping
1296 * while our process was stopped. At this point
1297 * we were already counted as stopped.
1299 if ((lp->lwp_mpflags & LWP_MP_WSTOP) == 0) {
1301 * If we're the last thread to stop, signal
1302 * our parent.
1304 p->p_nstopped++;
1305 atomic_set_int(&lp->lwp_mpflags, LWP_MP_WSTOP);
1306 wakeup(&p->p_nstopped);
1307 if (p->p_nstopped == p->p_nthreads) {
1309 * Token required to interlock kern_wait()
1311 q = p->p_pptr;
1312 PHOLD(q);
1313 lwkt_gettoken(&q->p_token);
1314 p->p_flags &= ~P_WAITED;
1315 wakeup(p->p_pptr);
1316 if ((q->p_sigacts->ps_flag & PS_NOCLDSTOP) == 0)
1317 ksignal(q, SIGCHLD);
1318 lwkt_reltoken(&q->p_token);
1319 PRELE(q);
1324 * Wait here while in a stopped state, interlocked with lwp_token.
1325 * We must break-out if the whole process is trying to exit.
1327 while (STOPLWP(p, lp)) {
1328 lp->lwp_stat = LSSTOP;
1329 tsleep(p, 0, "stop", 0);
1331 p->p_nstopped--;
1332 atomic_clear_int(&lp->lwp_mpflags, LWP_MP_WSTOP);
1333 crit_exit();
1334 lwkt_reltoken(&lp->lwp_token);
1338 * Compute a tenex style load average of a quantity on
1339 * 1, 5 and 15 minute intervals. This is a pcpu callout.
1341 * We segment the lwp scan on a pcpu basis. This does NOT
1342 * mean the associated lwps are on this cpu, it is done
1343 * just to break the work up.
1345 * The callout on cpu0 rolls up the stats from the other
1346 * cpus.
1348 static int loadav_count_runnable(struct lwp *p, void *data);
1350 static void
1351 loadav(void *arg)
1353 globaldata_t gd = mycpu;
1354 struct loadavg *avg;
1355 int i, nrun;
1357 nrun = 0;
1358 alllwp_scan(loadav_count_runnable, &nrun, 1);
1359 gd->gd_loadav_nrunnable = nrun;
1360 if (gd->gd_cpuid == 0) {
1361 avg = &averunnable;
1362 nrun = 0;
1363 for (i = 0; i < ncpus; ++i)
1364 nrun += globaldata_find(i)->gd_loadav_nrunnable;
1365 for (i = 0; i < 3; i++) {
1366 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
1367 (long)nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
1372 * Schedule the next update to occur after 5 seconds, but add a
1373 * random variation to avoid synchronisation with processes that
1374 * run at regular intervals.
1376 callout_reset(&gd->gd_loadav_callout,
1377 hz * 4 + (int)(krandom() % (hz * 2 + 1)),
1378 loadav, NULL);
1381 static int
1382 loadav_count_runnable(struct lwp *lp, void *data)
1384 int *nrunp = data;
1385 thread_t td;
1387 switch (lp->lwp_stat) {
1388 case LSRUN:
1389 if ((td = lp->lwp_thread) == NULL)
1390 break;
1391 if (td->td_flags & TDF_BLOCKED)
1392 break;
1393 ++*nrunp;
1394 break;
1395 default:
1396 break;
1398 lwkt_yield();
1399 return(0);
1403 * Regular data collection
1405 static uint64_t
1406 collect_load_callback(int n)
1408 int fscale = averunnable.fscale;
1410 return ((averunnable.ldavg[0] * 100 + (fscale >> 1)) / fscale);
1413 static void
1414 sched_setup(void *dummy __unused)
1416 globaldata_t save_gd = mycpu;
1417 globaldata_t gd;
1418 int n;
1420 kcollect_register(KCOLLECT_LOAD, "load", collect_load_callback,
1421 KCOLLECT_SCALE(KCOLLECT_LOAD_FORMAT, 0));
1424 * Kick off timeout driven events by calling first time. We
1425 * split the work across available cpus to help scale it,
1426 * it can eat a lot of cpu when there are a lot of processes
1427 * on the system.
1429 for (n = 0; n < ncpus; ++n) {
1430 gd = globaldata_find(n);
1431 lwkt_setcpu_self(gd);
1432 callout_init_mp(&gd->gd_loadav_callout);
1433 callout_init_mp(&gd->gd_schedcpu_callout);
1434 schedcpu(NULL);
1435 loadav(NULL);
1437 lwkt_setcpu_self(save_gd);
1441 * Extremely early initialization, dummy-up the tables so we don't have
1442 * to conditionalize for NULL in _wakeup() and tsleep_interlock(). Even
1443 * though the system isn't blocking this early, these functions still
1444 * try to access the hash table.
1446 * This setup will be overridden once sched_dyninit() -> sleep_gdinit()
1447 * is called.
1449 void
1450 sleep_early_gdinit(globaldata_t gd)
1452 static struct tslpque dummy_slpque;
1453 static cpumask_t dummy_cpumasks;
1455 slpque_tablesize = 1;
1456 gd->gd_tsleep_hash = &dummy_slpque;
1457 slpque_cpumasks = &dummy_cpumasks;
1458 TAILQ_INIT(&dummy_slpque.queue);
1462 * PCPU initialization. Called after KMALLOC is operational, by
1463 * sched_dyninit() for cpu 0, and by mi_gdinit() for other cpus later.
1465 * WARNING! The pcpu hash table is smaller than the global cpumask
1466 * hash table, which can save us a lot of memory when maxproc
1467 * is set high.
1469 void
1470 sleep_gdinit(globaldata_t gd)
1472 struct thread *td;
1473 size_t hash_size;
1474 uint32_t n;
1475 uint32_t i;
1478 * This shouldn't happen, that is there shouldn't be any threads
1479 * waiting on the dummy tsleep queue this early in the boot.
1481 if (gd->gd_cpuid == 0) {
1482 struct tslpque *qp = &gd->gd_tsleep_hash[0];
1483 TAILQ_FOREACH(td, &qp->queue, td_sleepq) {
1484 kprintf("SLEEP_GDINIT SWITCH %s\n", td->td_comm);
1489 * Note that we have to allocate one extra slot because we are
1490 * shifting a modulo value. TCHASHSHIFT(slpque_tablesize - 1) can
1491 * return the same value as TCHASHSHIFT(slpque_tablesize).
1493 n = TCHASHSHIFT(slpque_tablesize) + 1;
1495 hash_size = sizeof(struct tslpque) * n;
1496 gd->gd_tsleep_hash = (void *)kmem_alloc3(&kernel_map, hash_size,
1497 VM_SUBSYS_GD,
1498 KM_CPU(gd->gd_cpuid));
1499 memset(gd->gd_tsleep_hash, 0, hash_size);
1500 for (i = 0; i < n; ++i)
1501 TAILQ_INIT(&gd->gd_tsleep_hash[i].queue);
1505 * Dynamic initialization after the memory system is operational.
1507 static void
1508 sched_dyninit(void *dummy __unused)
1510 int tblsize;
1511 int tblsize2;
1512 int n;
1515 * Calculate table size for slpque hash. We want a prime number
1516 * large enough to avoid overloading slpque_cpumasks when the
1517 * system has a large number of sleeping processes, which will
1518 * spam IPIs on wakeup().
1520 * While it is true this is really a per-lwp factor, generally
1521 * speaking the maxproc limit is a good metric to go by.
1523 for (tblsize = maxproc | 1; ; tblsize += 2) {
1524 if (tblsize % 3 == 0)
1525 continue;
1526 if (tblsize % 5 == 0)
1527 continue;
1528 tblsize2 = (tblsize / 2) | 1;
1529 for (n = 7; n < tblsize2; n += 2) {
1530 if (tblsize % n == 0)
1531 break;
1533 if (n == tblsize2)
1534 break;
1538 * PIDs are currently limited to 6 digits. Cap the table size
1539 * at double this.
1541 if (tblsize > 2000003)
1542 tblsize = 2000003;
1544 slpque_tablesize = tblsize;
1545 slpque_cpumasks = kmalloc(sizeof(*slpque_cpumasks) * slpque_tablesize,
1546 M_TSLEEP, M_WAITOK | M_ZERO);
1547 sleep_gdinit(mycpu);