kernel - Rewrite the callout_*() API
[dragonfly.git] / sys / kern / kern_synch.c
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. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      @(#)kern_synch.c        8.9 (Berkeley) 5/19/95
35  * $FreeBSD: src/sys/kern/kern_synch.c,v 1.87.2.6 2002/10/13 07:29:53 kbyanc Exp $
36  */
37
38 #include "opt_ktrace.h"
39
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/lock.h>
49 #include <sys/uio.h>
50 #include <sys/priv.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>
57
58 #include <sys/signal2.h>
59 #include <sys/thread2.h>
60 #include <sys/spinlock2.h>
61 #include <sys/mutex2.h>
62
63 #include <machine/cpu.h>
64 #include <machine/smp.h>
65
66 #include <vm/vm_extern.h>
67
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;
74 };
75
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);
80
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;
88
89 MALLOC_DEFINE(M_TSLEEP, "tslpque", "tsleep queues");
90
91 #define __DEALL(ident)  __DEQUALIFY(void *, ident)
92
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);
102
103 #define logtsleep1(name)        KTR_LOG(tsleep_ ## name)
104 #define logtsleep2(name, val)   KTR_LOG(tsleep_ ## name, val)
105
106 struct loadavg averunnable =
107         { {0, 0, 0}, FSCALE };  /* load average, of runnable procs */
108 /*
109  * Constants for averages over 1, 5, and 15 minutes
110  * when sampling at 5 second intervals.
111  */
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) */
116 };
117
118 static void     endtsleep (void *);
119 static void     loadav (void *arg);
120 static void     schedcpu (void *arg);
121
122 static int pctcpu_decay = 10;
123 SYSCTL_INT(_kern, OID_AUTO, pctcpu_decay, CTLFLAG_RW,
124            &pctcpu_decay, 0, "");
125
126 /*
127  * kernel uses `FSCALE', userland (SHOULD) use kern.fscale 
128  */
129 int     fscale __unused = FSCALE;       /* exported to systat */
130 SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, "");
131
132 /*
133  * Issue a wakeup() from userland (debugging)
134  */
135 static int
136 sysctl_wakeup(SYSCTL_HANDLER_ARGS)
137 {
138         uint64_t ident = 1;
139         int error = 0;
140
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);
149         }
150         if (req->oldptr != NULL) {
151                 error = SYSCTL_OUT(req, &ident, sizeof(ident));
152         }
153         return error;
154 }
155
156 static int
157 sysctl_wakeup_umtx(SYSCTL_HANDLER_ARGS)
158 {
159         uint64_t ident = 1;
160         int error = 0;
161
162         if (req->newptr != NULL) {
163                 if (priv_check(curthread, PRIV_ROOT))
164                         return (EPERM);
165                 error = SYSCTL_IN(req, &ident, sizeof(ident));
166                 if (error)
167                         return error;
168                 kprintf("issue wakeup %016jx, PDOMAIN_UMTX\n", ident);
169                 wakeup_domain((void *)(intptr_t)ident, PDOMAIN_UMTX);
170         }
171         if (req->oldptr != NULL) {
172                 error = SYSCTL_OUT(req, &ident, sizeof(ident));
173         }
174         return error;
175 }
176
177 SYSCTL_PROC(_debug, OID_AUTO, wakeup, CTLTYPE_UQUAD|CTLFLAG_RW, 0, 0,
178             sysctl_wakeup, "Q", "issue wakeup(addr)");
179 SYSCTL_PROC(_debug, OID_AUTO, wakeup_umtx, CTLTYPE_UQUAD|CTLFLAG_RW, 0, 0,
180             sysctl_wakeup_umtx, "Q", "issue wakeup(addr, PDOMAIN_UMTX)");
181
182 /*
183  * Recompute process priorities, once a second.
184  *
185  * Since the userland schedulers are typically event oriented, if the
186  * estcpu calculation at wakeup() time is not sufficient to make a
187  * process runnable relative to other processes in the system we have
188  * a 1-second recalc to help out.
189  *
190  * This code also allows us to store sysclock_t data in the process structure
191  * without fear of an overrun, since sysclock_t are guarenteed to hold 
192  * several seconds worth of count.
193  *
194  * WARNING!  callouts can preempt normal threads.  However, they will not
195  * preempt a thread holding a spinlock so we *can* safely use spinlocks.
196  */
197 static int schedcpu_stats(struct proc *p, void *data __unused);
198 static int schedcpu_resource(struct proc *p, void *data __unused);
199
200 static void
201 schedcpu(void *arg)
202 {
203         allproc_scan(schedcpu_stats, NULL, 1);
204         allproc_scan(schedcpu_resource, NULL, 1);
205         if (mycpu->gd_cpuid == 0) {
206                 wakeup((caddr_t)&lbolt);
207                 wakeup(lbolt_syncer);
208         }
209         callout_reset(&mycpu->gd_schedcpu_callout, hz, schedcpu, NULL);
210 }
211
212 /*
213  * General process statistics once a second
214  */
215 static int
216 schedcpu_stats(struct proc *p, void *data __unused)
217 {
218         struct lwp *lp;
219
220         /*
221          * Threads may not be completely set up if process in SIDL state.
222          */
223         if (p->p_stat == SIDL)
224                 return(0);
225
226         PHOLD(p);
227         if (lwkt_trytoken(&p->p_token) == FALSE) {
228                 PRELE(p);
229                 return(0);
230         }
231
232         p->p_swtime++;
233         FOREACH_LWP_IN_PROC(lp, p) {
234                 if (lp->lwp_stat == LSSLEEP) {
235                         ++lp->lwp_slptime;
236                         if (lp->lwp_slptime == 1)
237                                 p->p_usched->uload_update(lp);
238                 }
239
240                 /*
241                  * Only recalculate processes that are active or have slept
242                  * less then 2 seconds.  The schedulers understand this.
243                  * Otherwise decay by 50% per second.
244                  */
245                 if (lp->lwp_slptime <= 1) {
246                         p->p_usched->recalculate(lp);
247                 } else {
248                         int decay;
249
250                         decay = pctcpu_decay;
251                         cpu_ccfence();
252                         if (decay <= 1)
253                                 decay = 1;
254                         if (decay > 100)
255                                 decay = 100;
256                         lp->lwp_pctcpu = (lp->lwp_pctcpu * (decay - 1)) / decay;
257                 }
258         }
259         lwkt_reltoken(&p->p_token);
260         lwkt_yield();
261         PRELE(p);
262         return(0);
263 }
264
265 /*
266  * Resource checks.  XXX break out since ksignal/killproc can block,
267  * limiting us to one process killed per second.  There is probably
268  * a better way.
269  */
270 static int
271 schedcpu_resource(struct proc *p, void *data __unused)
272 {
273         u_int64_t ttime;
274         struct lwp *lp;
275
276         if (p->p_stat == SIDL)
277                 return(0);
278
279         PHOLD(p);
280         if (lwkt_trytoken(&p->p_token) == FALSE) {
281                 PRELE(p);
282                 return(0);
283         }
284
285         if (p->p_stat == SZOMB || p->p_limit == NULL) {
286                 lwkt_reltoken(&p->p_token);
287                 PRELE(p);
288                 return(0);
289         }
290
291         ttime = 0;
292         FOREACH_LWP_IN_PROC(lp, p) {
293                 /*
294                  * We may have caught an lp in the middle of being
295                  * created, lwp_thread can be NULL.
296                  */
297                 if (lp->lwp_thread) {
298                         ttime += lp->lwp_thread->td_sticks;
299                         ttime += lp->lwp_thread->td_uticks;
300                 }
301         }
302
303         switch(plimit_testcpulimit(p, ttime)) {
304         case PLIMIT_TESTCPU_KILL:
305                 killproc(p, "exceeded maximum CPU limit");
306                 break;
307         case PLIMIT_TESTCPU_XCPU:
308                 if ((p->p_flags & P_XCPU) == 0) {
309                         p->p_flags |= P_XCPU;
310                         ksignal(p, SIGXCPU);
311                 }
312                 break;
313         default:
314                 break;
315         }
316         lwkt_reltoken(&p->p_token);
317         lwkt_yield();
318         PRELE(p);
319         return(0);
320 }
321
322 /*
323  * This is only used by ps.  Generate a cpu percentage use over
324  * a period of one second.
325  */
326 void
327 updatepcpu(struct lwp *lp, int cpticks, int ttlticks)
328 {
329         fixpt_t acc;
330         int remticks;
331
332         acc = (cpticks << FSHIFT) / ttlticks;
333         if (ttlticks >= ESTCPUFREQ) {
334                 lp->lwp_pctcpu = acc;
335         } else {
336                 remticks = ESTCPUFREQ - ttlticks;
337                 lp->lwp_pctcpu = (acc * ttlticks + lp->lwp_pctcpu * remticks) /
338                                 ESTCPUFREQ;
339         }
340 }
341
342 /*
343  * Handy macros to calculate hash indices.  LOOKUP() calculates the
344  * global cpumask hash index, TCHASHSHIFT() converts that into the
345  * pcpu hash index.
346  *
347  * By making the pcpu hash arrays smaller we save a significant amount
348  * of memory at very low cost.  The real cost is in IPIs, which are handled
349  * by the much larger global cpumask hash table.
350  */
351 #define LOOKUP_PRIME    66555444443333333ULL
352 #define LOOKUP(x)       ((((uintptr_t)(x) + ((uintptr_t)(x) >> 18)) ^   \
353                           LOOKUP_PRIME) % slpque_tablesize)
354 #define TCHASHSHIFT(x)  ((x) >> 4)
355
356 static uint32_t slpque_tablesize;
357 static cpumask_t *slpque_cpumasks;
358
359 SYSCTL_UINT(_kern, OID_AUTO, slpque_tablesize, CTLFLAG_RD, &slpque_tablesize,
360     0, "");
361
362 /*
363  * This is a dandy function that allows us to interlock tsleep/wakeup
364  * operations with unspecified upper level locks, such as lockmgr locks,
365  * simply by holding a critical section.  The sequence is:
366  *
367  *      (acquire upper level lock)
368  *      tsleep_interlock(blah)
369  *      (release upper level lock)
370  *      tsleep(blah, ...)
371  *
372  * Basically this functions queues us on the tsleep queue without actually
373  * descheduling us.  When tsleep() is later called with PINTERLOCK it
374  * assumes the thread was already queued, otherwise it queues it there.
375  *
376  * Thus it is possible to receive the wakeup prior to going to sleep and
377  * the race conditions are covered.
378  */
379 static __inline void
380 _tsleep_interlock(globaldata_t gd, const volatile void *ident, int flags)
381 {
382         thread_t td = gd->gd_curthread;
383         struct tslpque *qp;
384         uint32_t cid;
385         uint32_t gid;
386
387         if (ident == NULL) {
388                 kprintf("tsleep_interlock: NULL ident %s\n", td->td_comm);
389                 print_backtrace(5);
390         }
391
392         crit_enter_quick(td);
393         if (td->td_flags & TDF_TSLEEPQ) {
394                 /*
395                  * Shortcut if unchanged
396                  */
397                 if (td->td_wchan == ident &&
398                     td->td_wdomain == (flags & PDOMAIN_MASK)) {
399                         crit_exit_quick(td);
400                         return;
401                 }
402
403                 /*
404                  * Remove current sleepq
405                  */
406                 cid = LOOKUP(td->td_wchan);
407                 gid = TCHASHSHIFT(cid);
408                 qp = &gd->gd_tsleep_hash[gid];
409                 TAILQ_REMOVE(&qp->queue, td, td_sleepq);
410                 if (TAILQ_FIRST(&qp->queue) == NULL) {
411                         qp->ident0 = NULL;
412                         qp->ident1 = NULL;
413                         qp->ident2 = NULL;
414                         qp->ident3 = NULL;
415                         ATOMIC_CPUMASK_NANDBIT(slpque_cpumasks[cid],
416                                                gd->gd_cpuid);
417                 }
418         } else {
419                 td->td_flags |= TDF_TSLEEPQ;
420         }
421         cid = LOOKUP(ident);
422         gid = TCHASHSHIFT(cid);
423         qp = &gd->gd_tsleep_hash[gid];
424         TAILQ_INSERT_TAIL(&qp->queue, td, td_sleepq);
425         if (qp->ident0 != ident && qp->ident1 != ident &&
426             qp->ident2 != ident && qp->ident3 != ident) {
427                 if (qp->ident0 == NULL)
428                         qp->ident0 = ident;
429                 else if (qp->ident1 == NULL)
430                         qp->ident1 = ident;
431                 else if (qp->ident2 == NULL)
432                         qp->ident2 = ident;
433                 else if (qp->ident3 == NULL)
434                         qp->ident3 = ident;
435                 else
436                         qp->ident0 = (void *)(intptr_t)-1;
437         }
438         ATOMIC_CPUMASK_ORBIT(slpque_cpumasks[cid], gd->gd_cpuid);
439         td->td_wchan = ident;
440         td->td_wdomain = flags & PDOMAIN_MASK;
441         crit_exit_quick(td);
442 }
443
444 void
445 tsleep_interlock(const volatile void *ident, int flags)
446 {
447         _tsleep_interlock(mycpu, ident, flags);
448 }
449
450 /*
451  * Remove thread from sleepq.  Must be called with a critical section held.
452  * The thread must not be migrating.
453  */
454 static __inline void
455 _tsleep_remove(thread_t td)
456 {
457         globaldata_t gd = mycpu;
458         struct tslpque *qp;
459         uint32_t cid;
460         uint32_t gid;
461
462         KKASSERT(td->td_gd == gd && IN_CRITICAL_SECT(td));
463         KKASSERT((td->td_flags & TDF_MIGRATING) == 0);
464         if (td->td_flags & TDF_TSLEEPQ) {
465                 td->td_flags &= ~TDF_TSLEEPQ;
466                 cid = LOOKUP(td->td_wchan);
467                 gid = TCHASHSHIFT(cid);
468                 qp = &gd->gd_tsleep_hash[gid];
469                 TAILQ_REMOVE(&qp->queue, td, td_sleepq);
470                 if (TAILQ_FIRST(&qp->queue) == NULL) {
471                         ATOMIC_CPUMASK_NANDBIT(slpque_cpumasks[cid],
472                                                gd->gd_cpuid);
473                 }
474                 td->td_wchan = NULL;
475                 td->td_wdomain = 0;
476         }
477 }
478
479 void
480 tsleep_remove(thread_t td)
481 {
482         _tsleep_remove(td);
483 }
484
485 /*
486  * General sleep call.  Suspends the current process until a wakeup is
487  * performed on the specified identifier.  The process will then be made
488  * runnable with the specified priority.  Sleeps at most timo/hz seconds
489  * (0 means no timeout).  If flags includes PCATCH flag, signals are checked
490  * before and after sleeping, else signals are not checked.  Returns 0 if
491  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
492  * signal needs to be delivered, ERESTART is returned if the current system
493  * call should be restarted if possible, and EINTR is returned if the system
494  * call should be interrupted by the signal (return EINTR).
495  *
496  * Note that if we are a process, we release_curproc() before messing with
497  * the LWKT scheduler.
498  *
499  * During autoconfiguration or after a panic, a sleep will simply
500  * lower the priority briefly to allow interrupts, then return.
501  *
502  * WARNING!  This code can't block (short of switching away), or bad things
503  *           will happen.  No getting tokens, no blocking locks, etc.
504  */
505 int
506 tsleep(const volatile void *ident, int flags, const char *wmesg, int timo)
507 {
508         struct thread *td = curthread;
509         struct lwp *lp = td->td_lwp;
510         struct proc *p = td->td_proc;           /* may be NULL */
511         globaldata_t gd;
512         int sig;
513         int catch;
514         int error;
515         int oldpri;
516         struct callout thandle;
517
518         /*
519          * Currently a severe hack.  Make sure any delayed wakeups
520          * are flushed before we sleep or we might deadlock on whatever
521          * event we are sleeping on.
522          */
523         if (td->td_flags & TDF_DELAYED_WAKEUP)
524                 wakeup_end_delayed();
525
526         /*
527          * NOTE: removed KTRPOINT, it could cause races due to blocking
528          * even in stable.  Just scrap it for now.
529          */
530         if (!tsleep_crypto_dump && (tsleep_now_works == 0 || panicstr)) {
531                 /*
532                  * After a panic, or before we actually have an operational
533                  * softclock, just give interrupts a chance, then just return;
534                  *
535                  * don't run any other procs or panic below,
536                  * in case this is the idle process and already asleep.
537                  */
538                 splz();
539                 oldpri = td->td_pri;
540                 lwkt_setpri_self(safepri);
541                 lwkt_switch();
542                 lwkt_setpri_self(oldpri);
543                 return (0);
544         }
545         logtsleep2(tsleep_beg, ident);
546         gd = td->td_gd;
547         KKASSERT(td != &gd->gd_idlethread);     /* you must be kidding! */
548         td->td_wakefromcpu = -1;                /* overwritten by _wakeup */
549
550         /*
551          * NOTE: all of this occurs on the current cpu, including any
552          * callout-based wakeups, so a critical section is a sufficient
553          * interlock.
554          *
555          * The entire sequence through to where we actually sleep must
556          * run without breaking the critical section.
557          */
558         catch = flags & PCATCH;
559         error = 0;
560         sig = 0;
561
562         crit_enter_quick(td);
563
564         KASSERT(ident != NULL, ("tsleep: no ident"));
565         KASSERT(lp == NULL ||
566                 lp->lwp_stat == LSRUN ||        /* Obvious */
567                 lp->lwp_stat == LSSTOP,         /* Set in tstop */
568                 ("tsleep %p %s %d",
569                         ident, wmesg, lp->lwp_stat));
570
571         /*
572          * We interlock the sleep queue if the caller has not already done
573          * it for us.  This must be done before we potentially acquire any
574          * tokens or we can loose the wakeup.
575          */
576         if ((flags & PINTERLOCKED) == 0) {
577                 _tsleep_interlock(gd, ident, flags);
578         }
579
580         /*
581          * Setup for the current process (if this is a process).  We must
582          * interlock with lwp_token to avoid remote wakeup races via
583          * setrunnable()
584          */
585         if (lp) {
586                 lwkt_gettoken(&lp->lwp_token);
587
588                 /*
589                  * If the umbrella process is in the SCORE state then
590                  * make sure that the thread is flagged going into a
591                  * normal sleep to allow the core dump to proceed, otherwise
592                  * the coredump can end up waiting forever.  If the normal
593                  * sleep is woken up, the thread will enter a stopped state
594                  * upon return to userland.
595                  *
596                  * We do not want to interrupt or cause a thread exist at
597                  * this juncture because that will mess-up the state the
598                  * coredump is trying to save.
599                  */
600                 if (p->p_stat == SCORE) {
601                         lwkt_gettoken(&p->p_token);
602                         if ((lp->lwp_mpflags & LWP_MP_WSTOP) == 0) {
603                                 atomic_set_int(&lp->lwp_mpflags, LWP_MP_WSTOP);
604                                 ++p->p_nstopped;
605                         }
606                         lwkt_reltoken(&p->p_token);
607                 }
608
609                 /*
610                  * PCATCH requested.
611                  */
612                 if (catch) {
613                         /*
614                          * Early termination if PCATCH was set and a
615                          * signal is pending, interlocked with the
616                          * critical section.
617                          *
618                          * Early termination only occurs when tsleep() is
619                          * entered while in a normal LSRUN state.
620                          */
621                         if ((sig = CURSIG(lp)) != 0)
622                                 goto resume;
623
624                         /*
625                          * Causes ksignal to wake us up if a signal is
626                          * received (interlocked with lp->lwp_token).
627                          */
628                         lp->lwp_flags |= LWP_SINTR;
629                 }
630         } else {
631                 KKASSERT(p == NULL);
632         }
633
634         /*
635          * Make sure the current process has been untangled from
636          * the userland scheduler and initialize slptime to start
637          * counting.
638          *
639          * NOTE: td->td_wakefromcpu is pre-set by the release function
640          *       for the dfly scheduler, and then adjusted by _wakeup()
641          */
642         if (lp) {
643                 p->p_usched->release_curproc(lp);
644                 lp->lwp_slptime = 0;
645         }
646
647         /*
648          * For PINTERLOCKED operation, TDF_TSLEEPQ might not be set if
649          * a wakeup() was processed before the thread could go to sleep.
650          *
651          * If TDF_TSLEEPQ is set, make sure the ident matches the recorded
652          * ident.  If it does not then the thread slept inbetween the
653          * caller's initial tsleep_interlock() call and the caller's tsleep()
654          * call.
655          *
656          * Extreme loads can cause the sending of an IPI (e.g. wakeup()'s)
657          * to process incoming IPIs, thus draining incoming wakeups.
658          */
659         if ((td->td_flags & TDF_TSLEEPQ) == 0) {
660                 logtsleep2(ilockfail, ident);
661                 goto resume;
662         } else if (td->td_wchan != ident ||
663                    td->td_wdomain != (flags & PDOMAIN_MASK)) {
664                 logtsleep2(ilockfail, ident);
665                 goto resume;
666         }
667
668         /*
669          * scheduling is blocked while in a critical section.  Coincide
670          * the descheduled-by-tsleep flag with the descheduling of the
671          * lwkt.
672          *
673          * The timer callout is localized on our cpu and interlocked by
674          * our critical section.
675          */
676         lwkt_deschedule_self(td);
677         td->td_flags |= TDF_TSLEEP_DESCHEDULED;
678         td->td_wmesg = wmesg;
679
680         /*
681          * Setup the timeout, if any.  The timeout is only operable while
682          * the thread is flagged descheduled.
683          */
684         KKASSERT((td->td_flags & TDF_TIMEOUT) == 0);
685         if (timo) {
686                 callout_init_mp(&thandle);
687                 callout_reset(&thandle, timo, endtsleep, td);
688         }
689
690         /*
691          * Beddy bye bye.
692          */
693         if (lp) {
694                 /*
695                  * Ok, we are sleeping.  Place us in the SSLEEP state.
696                  */
697                 KKASSERT((lp->lwp_mpflags & LWP_MP_ONRUNQ) == 0);
698
699                 /*
700                  * tstop() sets LSSTOP, so don't fiddle with that.
701                  */
702                 if (lp->lwp_stat != LSSTOP)
703                         lp->lwp_stat = LSSLEEP;
704                 lp->lwp_ru.ru_nvcsw++;
705                 p->p_usched->uload_update(lp);
706                 lwkt_switch();
707
708                 /*
709                  * And when we are woken up, put us back in LSRUN.  If we
710                  * slept for over a second, recalculate our estcpu.
711                  */
712                 lp->lwp_stat = LSRUN;
713                 if (lp->lwp_slptime) {
714                         p->p_usched->uload_update(lp);
715                         p->p_usched->recalculate(lp);
716                 }
717                 lp->lwp_slptime = 0;
718         } else {
719                 lwkt_switch();
720         }
721
722         /* 
723          * Make sure we haven't switched cpus while we were asleep.  It's
724          * not supposed to happen.  Cleanup our temporary flags.
725          */
726         KKASSERT(gd == td->td_gd);
727
728         /*
729          * Cleanup the timeout.  If the timeout has already occured thandle
730          * has already been stopped, otherwise stop thandle.  If the timeout
731          * is running (the callout thread must be blocked trying to get
732          * lwp_token) then wait for us to get scheduled.
733          */
734         if (timo) {
735                 while (td->td_flags & TDF_TIMEOUT_RUNNING) {
736                         /* else we won't get rescheduled! */
737                         if (lp->lwp_stat != LSSTOP)
738                                 lp->lwp_stat = LSSLEEP;
739                         lwkt_deschedule_self(td);
740                         td->td_wmesg = "tsrace";
741                         lwkt_switch();
742                         kprintf("td %p %s: timeout race\n", td, td->td_comm);
743                 }
744                 if (td->td_flags & TDF_TIMEOUT) {
745                         td->td_flags &= ~TDF_TIMEOUT;
746                         error = EWOULDBLOCK;
747                 } else {
748                         /* does not block when on same cpu */
749                         callout_cancel(&thandle);
750                 }
751         }
752         td->td_flags &= ~TDF_TSLEEP_DESCHEDULED;
753
754         /*
755          * Make sure we have been removed from the sleepq.  In most
756          * cases this will have been done for us already but it is
757          * possible for a scheduling IPI to be in-flight from a
758          * previous tsleep/tsleep_interlock() or due to a straight-out
759          * call to lwkt_schedule() (in the case of an interrupt thread),
760          * causing a spurious wakeup.
761          */
762         _tsleep_remove(td);
763         td->td_wmesg = NULL;
764
765         /*
766          * Figure out the correct error return.  If interrupted by a
767          * signal we want to return EINTR or ERESTART.  
768          */
769 resume:
770         if (lp) {
771                 if (catch && error == 0) {
772                         if (sig != 0 || (sig = CURSIG(lp))) {
773                                 if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
774                                         error = EINTR;
775                                 else
776                                         error = ERESTART;
777                         }
778                 }
779
780                 lp->lwp_flags &= ~LWP_SINTR;
781
782                 /*
783                  * Unconditionally set us to LSRUN on resume.  lwp_stat could
784                  * be in a weird state due to the goto resume, particularly
785                  * when tsleep() is called from tstop().
786                  */
787                 lp->lwp_stat = LSRUN;
788                 lwkt_reltoken(&lp->lwp_token);
789         }
790         logtsleep1(tsleep_end);
791         crit_exit_quick(td);
792
793         return (error);
794 }
795
796 /*
797  * Interlocked spinlock sleep.  An exclusively held spinlock must
798  * be passed to ssleep().  The function will atomically release the
799  * spinlock and tsleep on the ident, then reacquire the spinlock and
800  * return.
801  *
802  * This routine is fairly important along the critical path, so optimize it
803  * heavily.
804  */
805 int
806 ssleep(const volatile void *ident, struct spinlock *spin, int flags,
807        const char *wmesg, int timo)
808 {
809         globaldata_t gd = mycpu;
810         int error;
811
812         _tsleep_interlock(gd, ident, flags);
813         spin_unlock_quick(gd, spin);
814         error = tsleep(ident, flags | PINTERLOCKED, wmesg, timo);
815         KKASSERT(gd == mycpu);
816         _spin_lock_quick(gd, spin, wmesg);
817
818         return (error);
819 }
820
821 int
822 lksleep(const volatile void *ident, struct lock *lock, int flags,
823         const char *wmesg, int timo)
824 {
825         globaldata_t gd = mycpu;
826         int error;
827
828         _tsleep_interlock(gd, ident, flags);
829         lockmgr(lock, LK_RELEASE);
830         error = tsleep(ident, flags | PINTERLOCKED, wmesg, timo);
831         lockmgr(lock, LK_EXCLUSIVE);
832
833         return (error);
834 }
835
836 /*
837  * Interlocked mutex sleep.  An exclusively held mutex must be passed
838  * to mtxsleep().  The function will atomically release the mutex
839  * and tsleep on the ident, then reacquire the mutex and return.
840  */
841 int
842 mtxsleep(const volatile void *ident, struct mtx *mtx, int flags,
843          const char *wmesg, int timo)
844 {
845         globaldata_t gd = mycpu;
846         int error;
847
848         _tsleep_interlock(gd, ident, flags);
849         mtx_unlock(mtx);
850         error = tsleep(ident, flags | PINTERLOCKED, wmesg, timo);
851         mtx_lock_ex_quick(mtx);
852
853         return (error);
854 }
855
856 /*
857  * Interlocked serializer sleep.  An exclusively held serializer must
858  * be passed to zsleep().  The function will atomically release
859  * the serializer and tsleep on the ident, then reacquire the serializer
860  * and return.
861  */
862 int
863 zsleep(const volatile void *ident, struct lwkt_serialize *slz, int flags,
864        const char *wmesg, int timo)
865 {
866         globaldata_t gd = mycpu;
867         int ret;
868
869         ASSERT_SERIALIZED(slz);
870
871         _tsleep_interlock(gd, ident, flags);
872         lwkt_serialize_exit(slz);
873         ret = tsleep(ident, flags | PINTERLOCKED, wmesg, timo);
874         lwkt_serialize_enter(slz);
875
876         return ret;
877 }
878
879 /*
880  * Directly block on the LWKT thread by descheduling it.  This
881  * is much faster then tsleep(), but the only legal way to wake
882  * us up is to directly schedule the thread.
883  *
884  * Setting TDF_SINTR will cause new signals to directly schedule us.
885  *
886  * This routine must be called while in a critical section.
887  */
888 int
889 lwkt_sleep(const char *wmesg, int flags)
890 {
891         thread_t td = curthread;
892         int sig;
893
894         if ((flags & PCATCH) == 0 || td->td_lwp == NULL) {
895                 td->td_flags |= TDF_BLOCKED;
896                 td->td_wmesg = wmesg;
897                 lwkt_deschedule_self(td);
898                 lwkt_switch();
899                 td->td_wmesg = NULL;
900                 td->td_flags &= ~TDF_BLOCKED;
901                 return(0);
902         }
903         if ((sig = CURSIG(td->td_lwp)) != 0) {
904                 if (SIGISMEMBER(td->td_proc->p_sigacts->ps_sigintr, sig))
905                         return(EINTR);
906                 else
907                         return(ERESTART);
908                         
909         }
910         td->td_flags |= TDF_BLOCKED | TDF_SINTR;
911         td->td_wmesg = wmesg;
912         lwkt_deschedule_self(td);
913         lwkt_switch();
914         td->td_flags &= ~(TDF_BLOCKED | TDF_SINTR);
915         td->td_wmesg = NULL;
916         return(0);
917 }
918
919 /*
920  * Implement the timeout for tsleep.
921  *
922  * This type of callout timeout is scheduled on the same cpu the process
923  * is sleeping on.  Also, at the moment, the MP lock is held.
924  */
925 static void
926 endtsleep(void *arg)
927 {
928         thread_t td = arg;
929         struct lwp *lp;
930
931         /*
932          * We are going to have to get the lwp_token, which means we might
933          * block.  This can race a tsleep getting woken up by other means
934          * so set TDF_TIMEOUT_RUNNING to force the tsleep to wait for our
935          * processing to complete (sorry tsleep!).
936          *
937          * We can safely set td_flags because td MUST be on the same cpu
938          * as we are.
939          */
940         KKASSERT(td->td_gd == mycpu);
941         crit_enter();
942         td->td_flags |= TDF_TIMEOUT_RUNNING | TDF_TIMEOUT;
943
944         /*
945          * This can block but TDF_TIMEOUT_RUNNING will prevent the thread
946          * from exiting the tsleep on us.  The flag is interlocked by virtue
947          * of lp being on the same cpu as we are.
948          */
949         if ((lp = td->td_lwp) != NULL)
950                 lwkt_gettoken(&lp->lwp_token);
951
952         KKASSERT(td->td_flags & TDF_TSLEEP_DESCHEDULED);
953
954         if (lp) {
955                 /*
956                  * callout timer should normally never be set in tstop()
957                  * because it passes a timeout of 0.  However, there is a
958                  * case during thread exit (which SSTOP's all the threads)
959                  * for which tstop() must break out and can (properly) leave
960                  * the thread in LSSTOP.
961                  */
962                 KKASSERT(lp->lwp_stat != LSSTOP ||
963                          (lp->lwp_mpflags & LWP_MP_WEXIT));
964                 setrunnable(lp);
965                 lwkt_reltoken(&lp->lwp_token);
966         } else {
967                 _tsleep_remove(td);
968                 lwkt_schedule(td);
969         }
970         KKASSERT(td->td_gd == mycpu);
971         td->td_flags &= ~TDF_TIMEOUT_RUNNING;
972         crit_exit();
973 }
974
975 /*
976  * Make all processes sleeping on the specified identifier runnable.
977  * count may be zero or one only.
978  *
979  * The domain encodes the sleep/wakeup domain, flags, plus the originating
980  * cpu.
981  *
982  * This call may run without the MP lock held.  We can only manipulate thread
983  * state on the cpu owning the thread.  We CANNOT manipulate process state
984  * at all.
985  *
986  * _wakeup() can be passed to an IPI so we can't use (const volatile
987  * void *ident).
988  */
989 static void
990 _wakeup(void *ident, int domain)
991 {
992         struct tslpque *qp;
993         struct thread *td;
994         struct thread *ntd;
995         globaldata_t gd;
996         cpumask_t mask;
997         uint32_t cid;
998         uint32_t gid;
999         int wids = 0;
1000
1001         crit_enter();
1002         logtsleep2(wakeup_beg, ident);
1003         gd = mycpu;
1004         cid = LOOKUP(ident);
1005         gid = TCHASHSHIFT(cid);
1006         qp = &gd->gd_tsleep_hash[gid];
1007 restart:
1008         for (td = TAILQ_FIRST(&qp->queue); td != NULL; td = ntd) {
1009                 ntd = TAILQ_NEXT(td, td_sleepq);
1010                 if (td->td_wchan == ident && 
1011                     td->td_wdomain == (domain & PDOMAIN_MASK)
1012                 ) {
1013                         KKASSERT(td->td_gd == gd);
1014                         _tsleep_remove(td);
1015                         td->td_wakefromcpu = PWAKEUP_DECODE(domain);
1016                         if (td->td_flags & TDF_TSLEEP_DESCHEDULED) {
1017                                 lwkt_schedule(td);
1018                                 if (domain & PWAKEUP_ONE)
1019                                         goto done;
1020                         }
1021                         goto restart;
1022                 }
1023                 if (td->td_wchan == qp->ident0)
1024                         wids |= 1;
1025                 else if (td->td_wchan == qp->ident1)
1026                         wids |= 2;
1027                 else if (td->td_wchan == qp->ident2)
1028                         wids |= 4;
1029                 else if (td->td_wchan == qp->ident3)
1030                         wids |= 8;
1031                 else
1032                         wids |= 16;     /* force ident0 to be retained (-1) */
1033         }
1034
1035         /*
1036          * Because a bunch of cpumask array entries cover the same queue, it
1037          * is possible for our bit to remain set in some of them and cause
1038          * spurious wakeup IPIs later on.  Make sure that the bit is cleared
1039          * when a spurious IPI occurs to prevent further spurious IPIs.
1040          */
1041         if (TAILQ_FIRST(&qp->queue) == NULL) {
1042                 ATOMIC_CPUMASK_NANDBIT(slpque_cpumasks[cid], gd->gd_cpuid);
1043                 qp->ident0 = NULL;
1044                 qp->ident1 = NULL;
1045                 qp->ident2 = NULL;
1046                 qp->ident3 = NULL;
1047         } else {
1048                 if ((wids & 1) == 0) {
1049                         if ((wids & 16) == 0) {
1050                                 qp->ident0 = NULL;
1051                         } else {
1052                                 KKASSERT(qp->ident0 == (void *)(intptr_t)-1);
1053                         }
1054                 }
1055                 if ((wids & 2) == 0)
1056                         qp->ident1 = NULL;
1057                 if ((wids & 4) == 0)
1058                         qp->ident2 = NULL;
1059                 if ((wids & 8) == 0)
1060                         qp->ident3 = NULL;
1061         }
1062
1063         /*
1064          * We finished checking the current cpu but there still may be
1065          * more work to do.  Either wakeup_one was requested and no matching
1066          * thread was found, or a normal wakeup was requested and we have
1067          * to continue checking cpus.
1068          *
1069          * It should be noted that this scheme is actually less expensive then
1070          * the old scheme when waking up multiple threads, since we send 
1071          * only one IPI message per target candidate which may then schedule
1072          * multiple threads.  Before we could have wound up sending an IPI
1073          * message for each thread on the target cpu (!= current cpu) that
1074          * needed to be woken up.
1075          *
1076          * NOTE: Wakeups occuring on remote cpus are asynchronous.  This
1077          *       should be ok since we are passing idents in the IPI rather
1078          *       then thread pointers.
1079          *
1080          * NOTE: We MUST mfence (or use an atomic op) prior to reading
1081          *       the cpumask, as another cpu may have written to it in
1082          *       a fashion interlocked with whatever the caller did before
1083          *       calling wakeup().  Otherwise we might miss the interaction
1084          *       (kern_mutex.c can cause this problem).
1085          *
1086          *       lfence is insufficient as it may allow a written state to
1087          *       reorder around the cpumask load.
1088          */
1089         if ((domain & PWAKEUP_MYCPU) == 0) {
1090                 globaldata_t tgd;
1091                 const volatile void *id0;
1092                 int n;
1093
1094                 cpu_mfence();
1095                 /* cpu_lfence(); */
1096                 mask = slpque_cpumasks[cid];
1097                 CPUMASK_ANDMASK(mask, gd->gd_other_cpus);
1098                 while (CPUMASK_TESTNZERO(mask)) {
1099                         n = BSRCPUMASK(mask);
1100                         CPUMASK_NANDBIT(mask, n);
1101                         tgd = globaldata_find(n);
1102
1103                         /*
1104                          * Both ident0 compares must from a single load
1105                          * to avoid ident0 update races crossing the two
1106                          * compares.
1107                          */
1108                         qp = &tgd->gd_tsleep_hash[gid];
1109                         id0 = qp->ident0;
1110                         cpu_ccfence();
1111                         if (id0 == (void *)(intptr_t)-1) {
1112                                 lwkt_send_ipiq2(tgd, _wakeup, ident,
1113                                                 domain | PWAKEUP_MYCPU);
1114                                 ++tgd->gd_cnt.v_wakeup_colls;
1115                         } else if (id0 == ident ||
1116                                    qp->ident1 == ident ||
1117                                    qp->ident2 == ident ||
1118                                    qp->ident3 == ident) {
1119                                 lwkt_send_ipiq2(tgd, _wakeup, ident,
1120                                                 domain | PWAKEUP_MYCPU);
1121                         }
1122                 }
1123 #if 0
1124                 if (CPUMASK_TESTNZERO(mask)) {
1125                         lwkt_send_ipiq2_mask(mask, _wakeup, ident,
1126                                              domain | PWAKEUP_MYCPU);
1127                 }
1128 #endif
1129         }
1130 done:
1131         logtsleep1(wakeup_end);
1132         crit_exit();
1133 }
1134
1135 /*
1136  * Wakeup all threads tsleep()ing on the specified ident, on all cpus
1137  */
1138 void
1139 wakeup(const volatile void *ident)
1140 {
1141     globaldata_t gd = mycpu;
1142     thread_t td = gd->gd_curthread;
1143
1144     if (td && (td->td_flags & TDF_DELAYED_WAKEUP)) {
1145         /*
1146          * If we are in a delayed wakeup section, record up to two wakeups in
1147          * a per-CPU queue and issue them when we block or exit the delayed
1148          * wakeup section.
1149          */
1150         if (atomic_cmpset_ptr(&gd->gd_delayed_wakeup[0], NULL, ident))
1151                 return;
1152         if (atomic_cmpset_ptr(&gd->gd_delayed_wakeup[1], NULL, ident))
1153                 return;
1154
1155         ident = atomic_swap_ptr(__DEQUALIFY(volatile void **, &gd->gd_delayed_wakeup[1]),
1156                                 __DEALL(ident));
1157         ident = atomic_swap_ptr(__DEQUALIFY(volatile void **, &gd->gd_delayed_wakeup[0]),
1158                                 __DEALL(ident));
1159     }
1160
1161     _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, gd->gd_cpuid));
1162 }
1163
1164 /*
1165  * Wakeup one thread tsleep()ing on the specified ident, on any cpu.
1166  */
1167 void
1168 wakeup_one(const volatile void *ident)
1169 {
1170     /* XXX potentially round-robin the first responding cpu */
1171     _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, mycpu->gd_cpuid) |
1172                             PWAKEUP_ONE);
1173 }
1174
1175 /*
1176  * Wakeup threads tsleep()ing on the specified ident on the current cpu
1177  * only.
1178  */
1179 void
1180 wakeup_mycpu(const volatile void *ident)
1181 {
1182     _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, mycpu->gd_cpuid) |
1183                             PWAKEUP_MYCPU);
1184 }
1185
1186 /*
1187  * Wakeup one thread tsleep()ing on the specified ident on the current cpu
1188  * only.
1189  */
1190 void
1191 wakeup_mycpu_one(const volatile void *ident)
1192 {
1193     /* XXX potentially round-robin the first responding cpu */
1194     _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, mycpu->gd_cpuid) |
1195                             PWAKEUP_MYCPU | PWAKEUP_ONE);
1196 }
1197
1198 /*
1199  * Wakeup all thread tsleep()ing on the specified ident on the specified cpu
1200  * only.
1201  */
1202 void
1203 wakeup_oncpu(globaldata_t gd, const volatile void *ident)
1204 {
1205     globaldata_t mygd = mycpu;
1206     if (gd == mycpu) {
1207         _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, mygd->gd_cpuid) |
1208                                 PWAKEUP_MYCPU);
1209     } else {
1210         lwkt_send_ipiq2(gd, _wakeup, __DEALL(ident),
1211                         PWAKEUP_ENCODE(0, mygd->gd_cpuid) |
1212                         PWAKEUP_MYCPU);
1213     }
1214 }
1215
1216 /*
1217  * Wakeup one thread tsleep()ing on the specified ident on the specified cpu
1218  * only.
1219  */
1220 void
1221 wakeup_oncpu_one(globaldata_t gd, const volatile void *ident)
1222 {
1223     globaldata_t mygd = mycpu;
1224     if (gd == mygd) {
1225         _wakeup(__DEALL(ident), PWAKEUP_ENCODE(0, mygd->gd_cpuid) |
1226                                 PWAKEUP_MYCPU | PWAKEUP_ONE);
1227     } else {
1228         lwkt_send_ipiq2(gd, _wakeup, __DEALL(ident),
1229                         PWAKEUP_ENCODE(0, mygd->gd_cpuid) |
1230                         PWAKEUP_MYCPU | PWAKEUP_ONE);
1231     }
1232 }
1233
1234 /*
1235  * Wakeup all threads waiting on the specified ident that slept using
1236  * the specified domain, on all cpus.
1237  */
1238 void
1239 wakeup_domain(const volatile void *ident, int domain)
1240 {
1241     _wakeup(__DEALL(ident), PWAKEUP_ENCODE(domain, mycpu->gd_cpuid));
1242 }
1243
1244 /*
1245  * Wakeup one thread waiting on the specified ident that slept using
1246  * the specified  domain, on any cpu.
1247  */
1248 void
1249 wakeup_domain_one(const volatile void *ident, int domain)
1250 {
1251     /* XXX potentially round-robin the first responding cpu */
1252     _wakeup(__DEALL(ident),
1253             PWAKEUP_ENCODE(domain, mycpu->gd_cpuid) | PWAKEUP_ONE);
1254 }
1255
1256 void
1257 wakeup_start_delayed(void)
1258 {
1259     globaldata_t gd = mycpu;
1260
1261     crit_enter();
1262     gd->gd_curthread->td_flags |= TDF_DELAYED_WAKEUP;
1263     crit_exit();
1264 }
1265
1266 void
1267 wakeup_end_delayed(void)
1268 {
1269     globaldata_t gd = mycpu;
1270
1271     if (gd->gd_curthread->td_flags & TDF_DELAYED_WAKEUP) {
1272         crit_enter();
1273         gd->gd_curthread->td_flags &= ~TDF_DELAYED_WAKEUP;
1274         if (gd->gd_delayed_wakeup[0] || gd->gd_delayed_wakeup[1]) {
1275             if (gd->gd_delayed_wakeup[0]) {
1276                     wakeup(gd->gd_delayed_wakeup[0]);
1277                     gd->gd_delayed_wakeup[0] = NULL;
1278             }
1279             if (gd->gd_delayed_wakeup[1]) {
1280                     wakeup(gd->gd_delayed_wakeup[1]);
1281                     gd->gd_delayed_wakeup[1] = NULL;
1282             }
1283         }
1284         crit_exit();
1285     }
1286 }
1287
1288 /*
1289  * setrunnable()
1290  *
1291  * Make a process runnable.  lp->lwp_token must be held on call and this
1292  * function must be called from the cpu owning lp.
1293  *
1294  * This only has an effect if we are in LSSTOP or LSSLEEP.
1295  */
1296 void
1297 setrunnable(struct lwp *lp)
1298 {
1299         thread_t td = lp->lwp_thread;
1300
1301         ASSERT_LWKT_TOKEN_HELD(&lp->lwp_token);
1302         KKASSERT(td->td_gd == mycpu);
1303         crit_enter();
1304         if (lp->lwp_stat == LSSTOP)
1305                 lp->lwp_stat = LSSLEEP;
1306         if (lp->lwp_stat == LSSLEEP) {
1307                 _tsleep_remove(td);
1308                 lwkt_schedule(td);
1309         } else if (td->td_flags & TDF_SINTR) {
1310                 lwkt_schedule(td);
1311         }
1312         crit_exit();
1313 }
1314
1315 /*
1316  * The process is stopped due to some condition, usually because p_stat is
1317  * set to SSTOP, but also possibly due to being traced.  
1318  *
1319  * Caller must hold p->p_token
1320  *
1321  * NOTE!  If the caller sets SSTOP, the caller must also clear P_WAITED
1322  * because the parent may check the child's status before the child actually
1323  * gets to this routine.
1324  *
1325  * This routine is called with the current lwp only, typically just
1326  * before returning to userland if the process state is detected as
1327  * possibly being in a stopped state.
1328  */
1329 void
1330 tstop(void)
1331 {
1332         struct lwp *lp = curthread->td_lwp;
1333         struct proc *p = lp->lwp_proc;
1334         struct proc *q;
1335
1336         lwkt_gettoken(&lp->lwp_token);
1337         crit_enter();
1338
1339         /*
1340          * If LWP_MP_WSTOP is set, we were sleeping
1341          * while our process was stopped.  At this point
1342          * we were already counted as stopped.
1343          */
1344         if ((lp->lwp_mpflags & LWP_MP_WSTOP) == 0) {
1345                 /*
1346                  * If we're the last thread to stop, signal
1347                  * our parent.
1348                  */
1349                 p->p_nstopped++;
1350                 atomic_set_int(&lp->lwp_mpflags, LWP_MP_WSTOP);
1351                 wakeup(&p->p_nstopped);
1352                 if (p->p_nstopped == p->p_nthreads) {
1353                         /*
1354                          * Token required to interlock kern_wait()
1355                          */
1356                         q = p->p_pptr;
1357                         PHOLD(q);
1358                         lwkt_gettoken(&q->p_token);
1359                         p->p_flags &= ~P_WAITED;
1360                         wakeup(p->p_pptr);
1361                         if ((q->p_sigacts->ps_flag & PS_NOCLDSTOP) == 0)
1362                                 ksignal(q, SIGCHLD);
1363                         lwkt_reltoken(&q->p_token);
1364                         PRELE(q);
1365                 }
1366         }
1367
1368         /*
1369          * Wait here while in a stopped state, interlocked with lwp_token.
1370          * We must break-out if the whole process is trying to exit.
1371          */
1372         while (STOPLWP(p, lp)) {
1373                 lp->lwp_stat = LSSTOP;
1374                 tsleep(p, 0, "stop", 0);
1375         }
1376         p->p_nstopped--;
1377         atomic_clear_int(&lp->lwp_mpflags, LWP_MP_WSTOP);
1378         crit_exit();
1379         lwkt_reltoken(&lp->lwp_token);
1380 }
1381
1382 /*
1383  * Compute a tenex style load average of a quantity on
1384  * 1, 5 and 15 minute intervals.  This is a pcpu callout.
1385  *
1386  * We segment the lwp scan on a pcpu basis.  This does NOT
1387  * mean the associated lwps are on this cpu, it is done
1388  * just to break the work up.
1389  *
1390  * The callout on cpu0 rolls up the stats from the other
1391  * cpus.
1392  */
1393 static int loadav_count_runnable(struct lwp *p, void *data);
1394
1395 static void
1396 loadav(void *arg)
1397 {
1398         globaldata_t gd = mycpu;
1399         struct loadavg *avg;
1400         int i, nrun;
1401
1402         nrun = 0;
1403         alllwp_scan(loadav_count_runnable, &nrun, 1);
1404         gd->gd_loadav_nrunnable = nrun;
1405         if (gd->gd_cpuid == 0) {
1406                 avg = &averunnable;
1407                 nrun = 0;
1408                 for (i = 0; i < ncpus; ++i)
1409                         nrun += globaldata_find(i)->gd_loadav_nrunnable;
1410                 for (i = 0; i < 3; i++) {
1411                         avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
1412                             (long)nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
1413                 }
1414         }
1415
1416         /*
1417          * Schedule the next update to occur after 5 seconds, but add a
1418          * random variation to avoid synchronisation with processes that
1419          * run at regular intervals.
1420          */
1421         callout_reset(&gd->gd_loadav_callout,
1422                       hz * 4 + (int)(krandom() % (hz * 2 + 1)),
1423                       loadav, NULL);
1424 }
1425
1426 static int
1427 loadav_count_runnable(struct lwp *lp, void *data)
1428 {
1429         int *nrunp = data;
1430         thread_t td;
1431
1432         switch (lp->lwp_stat) {
1433         case LSRUN:
1434                 if ((td = lp->lwp_thread) == NULL)
1435                         break;
1436                 if (td->td_flags & TDF_BLOCKED)
1437                         break;
1438                 ++*nrunp;
1439                 break;
1440         default:
1441                 break;
1442         }
1443         lwkt_yield();
1444         return(0);
1445 }
1446
1447 /*
1448  * Regular data collection
1449  */
1450 static uint64_t
1451 collect_load_callback(int n)
1452 {
1453         int fscale = averunnable.fscale;
1454
1455         return ((averunnable.ldavg[0] * 100 + (fscale >> 1)) / fscale);
1456 }
1457
1458 static void
1459 sched_setup(void *dummy __unused)
1460 {
1461         globaldata_t save_gd = mycpu;
1462         globaldata_t gd;
1463         int n;
1464
1465         kcollect_register(KCOLLECT_LOAD, "load", collect_load_callback,
1466                           KCOLLECT_SCALE(KCOLLECT_LOAD_FORMAT, 0));
1467
1468         /*
1469          * Kick off timeout driven events by calling first time.  We
1470          * split the work across available cpus to help scale it,
1471          * it can eat a lot of cpu when there are a lot of processes
1472          * on the system.
1473          */
1474         for (n = 0; n < ncpus; ++n) {
1475                 gd = globaldata_find(n);
1476                 lwkt_setcpu_self(gd);
1477                 callout_init_mp(&gd->gd_loadav_callout);
1478                 callout_init_mp(&gd->gd_schedcpu_callout);
1479                 schedcpu(NULL);
1480                 loadav(NULL);
1481         }
1482         lwkt_setcpu_self(save_gd);
1483 }
1484
1485 /*
1486  * Extremely early initialization, dummy-up the tables so we don't have
1487  * to conditionalize for NULL in _wakeup() and tsleep_interlock().  Even
1488  * though the system isn't blocking this early, these functions still
1489  * try to access the hash table.
1490  *
1491  * This setup will be overridden once sched_dyninit() -> sleep_gdinit()
1492  * is called.
1493  */
1494 void
1495 sleep_early_gdinit(globaldata_t gd)
1496 {
1497         static struct tslpque   dummy_slpque;
1498         static cpumask_t dummy_cpumasks;
1499
1500         slpque_tablesize = 1;
1501         gd->gd_tsleep_hash = &dummy_slpque;
1502         slpque_cpumasks = &dummy_cpumasks;
1503         TAILQ_INIT(&dummy_slpque.queue);
1504 }
1505
1506 /*
1507  * PCPU initialization.  Called after KMALLOC is operational, by
1508  * sched_dyninit() for cpu 0, and by mi_gdinit() for other cpus later.
1509  *
1510  * WARNING! The pcpu hash table is smaller than the global cpumask
1511  *          hash table, which can save us a lot of memory when maxproc
1512  *          is set high.
1513  */
1514 void
1515 sleep_gdinit(globaldata_t gd)
1516 {
1517         struct thread *td;
1518         size_t hash_size;
1519         uint32_t n;
1520         uint32_t i;
1521
1522         /*
1523          * This shouldn't happen, that is there shouldn't be any threads
1524          * waiting on the dummy tsleep queue this early in the boot.
1525          */
1526         if (gd->gd_cpuid == 0) {
1527                 struct tslpque *qp = &gd->gd_tsleep_hash[0];
1528                 TAILQ_FOREACH(td, &qp->queue, td_sleepq) {
1529                         kprintf("SLEEP_GDINIT SWITCH %s\n", td->td_comm);
1530                 }
1531         }
1532
1533         /*
1534          * Note that we have to allocate one extra slot because we are
1535          * shifting a modulo value.  TCHASHSHIFT(slpque_tablesize - 1) can
1536          * return the same value as TCHASHSHIFT(slpque_tablesize).
1537          */
1538         n = TCHASHSHIFT(slpque_tablesize) + 1;
1539
1540         hash_size = sizeof(struct tslpque) * n;
1541         gd->gd_tsleep_hash = (void *)kmem_alloc3(&kernel_map, hash_size,
1542                                                  VM_SUBSYS_GD,
1543                                                  KM_CPU(gd->gd_cpuid));
1544         memset(gd->gd_tsleep_hash, 0, hash_size);
1545         for (i = 0; i < n; ++i)
1546                 TAILQ_INIT(&gd->gd_tsleep_hash[i].queue);
1547 }
1548
1549 /*
1550  * Dynamic initialization after the memory system is operational.
1551  */
1552 static void
1553 sched_dyninit(void *dummy __unused)
1554 {
1555         int tblsize;
1556         int tblsize2;
1557         int n;
1558
1559         /*
1560          * Calculate table size for slpque hash.  We want a prime number
1561          * large enough to avoid overloading slpque_cpumasks when the
1562          * system has a large number of sleeping processes, which will
1563          * spam IPIs on wakeup().
1564          *
1565          * While it is true this is really a per-lwp factor, generally
1566          * speaking the maxproc limit is a good metric to go by.
1567          */
1568         for (tblsize = maxproc | 1; ; tblsize += 2) {
1569                 if (tblsize % 3 == 0)
1570                         continue;
1571                 if (tblsize % 5 == 0)
1572                         continue;
1573                 tblsize2 = (tblsize / 2) | 1;
1574                 for (n = 7; n < tblsize2; n += 2) {
1575                         if (tblsize % n == 0)
1576                                 break;
1577                 }
1578                 if (n == tblsize2)
1579                         break;
1580         }
1581
1582         /*
1583          * PIDs are currently limited to 6 digits.  Cap the table size
1584          * at double this.
1585          */
1586         if (tblsize > 2000003)
1587                 tblsize = 2000003;
1588
1589         slpque_tablesize = tblsize;
1590         slpque_cpumasks = kmalloc(sizeof(*slpque_cpumasks) * slpque_tablesize,
1591                                   M_TSLEEP, M_WAITOK | M_ZERO);
1592         sleep_gdinit(mycpu);
1593 }