Rename serialize_sleep() to zsleep()
[dragonfly.git] / sys / kern / kern_synch.c
CommitLineData
984263bc
MD
1/*-
2 * Copyright (c) 1982, 1986, 1990, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the University of
21 * California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * SUCH DAMAGE.
37 *
38 * @(#)kern_synch.c 8.9 (Berkeley) 5/19/95
39 * $FreeBSD: src/sys/kern/kern_synch.c,v 1.87.2.6 2002/10/13 07:29:53 kbyanc Exp $
c730be20 40 * $DragonFly: src/sys/kern/kern_synch.c,v 1.91 2008/09/09 04:06:13 dillon Exp $
984263bc
MD
41 */
42
43#include "opt_ktrace.h"
44
45#include <sys/param.h>
46#include <sys/systm.h>
47#include <sys/proc.h>
48#include <sys/kernel.h>
49#include <sys/signalvar.h>
b1b4e5a6 50#include <sys/signal2.h>
984263bc
MD
51#include <sys/resourcevar.h>
52#include <sys/vmmeter.h>
53#include <sys/sysctl.h>
344ad853 54#include <sys/lock.h>
984263bc
MD
55#ifdef KTRACE
56#include <sys/uio.h>
57#include <sys/ktrace.h>
58#endif
f1d1c3fa 59#include <sys/xwait.h>
9afb0ffd 60#include <sys/ktr.h>
984263bc 61
bf765287
MD
62#include <sys/thread2.h>
63#include <sys/spinlock2.h>
7f6220a9 64#include <sys/mutex2.h>
362e59be 65#include <sys/serialize.h>
bf765287 66
984263bc 67#include <machine/cpu.h>
984263bc
MD
68#include <machine/smp.h>
69
fc17ad60
MD
70TAILQ_HEAD(tslpque, thread);
71
402ed7e1 72static void sched_setup (void *dummy);
984263bc
MD
73SYSINIT(sched_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, sched_setup, NULL)
74
984263bc
MD
75int hogticks;
76int lbolt;
344ad853 77int lbolt_syncer;
984263bc 78int sched_quantum; /* Roundrobin scheduling quantum in ticks. */
17a9f566 79int ncpus;
90100055 80int ncpus2, ncpus2_shift, ncpus2_mask;
b45759e1 81int ncpus_fit, ncpus_fit_mask;
e43a034f 82int safepri;
dbcd0c9b 83int tsleep_now_works;
984263bc
MD
84
85static struct callout loadav_callout;
35f9d051 86static struct callout schedcpu_callout;
fc17ad60 87MALLOC_DEFINE(M_TSLEEP, "tslpque", "tsleep queues");
984263bc 88
9afb0ffd
MD
89#if !defined(KTR_TSLEEP)
90#define KTR_TSLEEP KTR_ALL
91#endif
92KTR_INFO_MASTER(tsleep);
8aa3430c
MD
93KTR_INFO(KTR_TSLEEP, tsleep, tsleep_beg, 0, "tsleep enter %p", sizeof(void *));
94KTR_INFO(KTR_TSLEEP, tsleep, tsleep_end, 1, "tsleep exit", 0);
95KTR_INFO(KTR_TSLEEP, tsleep, wakeup_beg, 2, "wakeup enter %p", sizeof(void *));
96KTR_INFO(KTR_TSLEEP, tsleep, wakeup_end, 3, "wakeup exit", 0);
d9345d3a 97KTR_INFO(KTR_TSLEEP, tsleep, ilockfail, 4, "interlock failed %p", sizeof(void *));
8aa3430c
MD
98
99#define logtsleep1(name) KTR_LOG(tsleep_ ## name)
100#define logtsleep2(name, val) KTR_LOG(tsleep_ ## name, val)
9afb0ffd 101
984263bc
MD
102struct loadavg averunnable =
103 { {0, 0, 0}, FSCALE }; /* load average, of runnable procs */
104/*
105 * Constants for averages over 1, 5, and 15 minutes
106 * when sampling at 5 second intervals.
107 */
108static fixpt_t cexp[3] = {
109 0.9200444146293232 * FSCALE, /* exp(-1/12) */
110 0.9834714538216174 * FSCALE, /* exp(-1/60) */
111 0.9944598480048967 * FSCALE, /* exp(-1/180) */
112};
113
402ed7e1 114static void endtsleep (void *);
ae8e83e6 115static void tsleep_wakeup(struct thread *td);
402ed7e1 116static void loadav (void *arg);
402ed7e1 117static void schedcpu (void *arg);
984263bc 118
a46fac56
MD
119/*
120 * Adjust the scheduler quantum. The quantum is specified in microseconds.
121 * Note that 'tick' is in microseconds per tick.
122 */
984263bc
MD
123static int
124sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
125{
126 int error, new_val;
127
128 new_val = sched_quantum * tick;
129 error = sysctl_handle_int(oidp, &new_val, 0, req);
130 if (error != 0 || req->newptr == NULL)
131 return (error);
132 if (new_val < tick)
133 return (EINVAL);
134 sched_quantum = new_val / tick;
135 hogticks = 2 * sched_quantum;
136 return (0);
137}
138
139SYSCTL_PROC(_kern, OID_AUTO, quantum, CTLTYPE_INT|CTLFLAG_RW,
140 0, sizeof sched_quantum, sysctl_kern_quantum, "I", "");
141
984263bc
MD
142/*
143 * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
144 * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
145 * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
146 *
147 * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
dcc99b62 148 * 1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
984263bc
MD
149 *
150 * If you don't want to bother with the faster/more-accurate formula, you
151 * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
152 * (more general) method of calculating the %age of CPU used by a process.
dcc99b62 153 *
08f2f1bb 154 * decay 95% of `lwp_pctcpu' in 60 seconds; see CCPU_SHIFT before changing
dcc99b62
MD
155 */
156#define CCPU_SHIFT 11
157
158static fixpt_t ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
159SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
160
161/*
162 * kernel uses `FSCALE', userland (SHOULD) use kern.fscale
984263bc 163 */
460426e6 164int fscale __unused = FSCALE; /* exported to systat */
dcc99b62 165SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, "");
984263bc
MD
166
167/*
0a3f9b47 168 * Recompute process priorities, once a second.
dcc99b62
MD
169 *
170 * Since the userland schedulers are typically event oriented, if the
171 * estcpu calculation at wakeup() time is not sufficient to make a
172 * process runnable relative to other processes in the system we have
173 * a 1-second recalc to help out.
174 *
175 * This code also allows us to store sysclock_t data in the process structure
176 * without fear of an overrun, since sysclock_t are guarenteed to hold
177 * several seconds worth of count.
8fa76237
MD
178 *
179 * WARNING! callouts can preempt normal threads. However, they will not
180 * preempt a thread holding a spinlock so we *can* safely use spinlocks.
984263bc 181 */
8fa76237
MD
182static int schedcpu_stats(struct proc *p, void *data __unused);
183static int schedcpu_resource(struct proc *p, void *data __unused);
184
984263bc 185static void
26a0694b 186schedcpu(void *arg)
984263bc 187{
8fa76237
MD
188 allproc_scan(schedcpu_stats, NULL);
189 allproc_scan(schedcpu_resource, NULL);
190 wakeup((caddr_t)&lbolt);
191 wakeup((caddr_t)&lbolt_syncer);
192 callout_reset(&schedcpu_callout, hz, schedcpu, NULL);
193}
194
195/*
196 * General process statistics once a second
197 */
198static int
199schedcpu_stats(struct proc *p, void *data __unused)
200{
08f2f1bb
SS
201 struct lwp *lp;
202
8fa76237
MD
203 crit_enter();
204 p->p_swtime++;
c7e98b2f
SS
205 FOREACH_LWP_IN_PROC(lp, p) {
206 if (lp->lwp_stat == LSSLEEP)
207 lp->lwp_slptime++;
4b5f931b 208
c7e98b2f
SS
209 /*
210 * Only recalculate processes that are active or have slept
211 * less then 2 seconds. The schedulers understand this.
212 */
213 if (lp->lwp_slptime <= 1) {
214 p->p_usched->recalculate(lp);
215 } else {
216 lp->lwp_pctcpu = (lp->lwp_pctcpu * ccpu) >> FSHIFT;
217 }
8fa76237
MD
218 }
219 crit_exit();
220 return(0);
221}
a46fac56 222
8fa76237 223/*
84204577 224 * Resource checks. XXX break out since ksignal/killproc can block,
8fa76237
MD
225 * limiting us to one process killed per second. There is probably
226 * a better way.
227 */
228static int
229schedcpu_resource(struct proc *p, void *data __unused)
230{
231 u_int64_t ttime;
08f2f1bb 232 struct lwp *lp;
8fa76237
MD
233
234 crit_enter();
235 if (p->p_stat == SIDL ||
416d05d7 236 p->p_stat == SZOMB ||
c7e98b2f 237 p->p_limit == NULL
8fa76237 238 ) {
e43a034f 239 crit_exit();
8fa76237 240 return(0);
984263bc 241 }
344ad853 242
c7e98b2f
SS
243 ttime = 0;
244 FOREACH_LWP_IN_PROC(lp, p) {
e595c6cd
MD
245 /*
246 * We may have caught an lp in the middle of being
247 * created, lwp_thread can be NULL.
248 */
249 if (lp->lwp_thread) {
250 ttime += lp->lwp_thread->td_sticks;
251 ttime += lp->lwp_thread->td_uticks;
252 }
c7e98b2f 253 }
8fa76237
MD
254
255 switch(plimit_testcpulimit(p->p_limit, ttime)) {
256 case PLIMIT_TESTCPU_KILL:
257 killproc(p, "exceeded maximum CPU limit");
258 break;
259 case PLIMIT_TESTCPU_XCPU:
260 if ((p->p_flag & P_XCPU) == 0) {
261 p->p_flag |= P_XCPU;
84204577 262 ksignal(p, SIGXCPU);
344ad853 263 }
8fa76237
MD
264 break;
265 default:
c0b8a06d 266 break;
344ad853 267 }
8fa76237
MD
268 crit_exit();
269 return(0);
984263bc
MD
270}
271
272/*
dcc99b62
MD
273 * This is only used by ps. Generate a cpu percentage use over
274 * a period of one second.
52eedfb5
MD
275 *
276 * MPSAFE
984263bc 277 */
dcc99b62 278void
553ea3c8 279updatepcpu(struct lwp *lp, int cpticks, int ttlticks)
984263bc 280{
dcc99b62
MD
281 fixpt_t acc;
282 int remticks;
283
284 acc = (cpticks << FSHIFT) / ttlticks;
285 if (ttlticks >= ESTCPUFREQ) {
553ea3c8 286 lp->lwp_pctcpu = acc;
dcc99b62
MD
287 } else {
288 remticks = ESTCPUFREQ - ttlticks;
553ea3c8 289 lp->lwp_pctcpu = (acc * ttlticks + lp->lwp_pctcpu * remticks) /
dcc99b62 290 ESTCPUFREQ;
a46fac56 291 }
984263bc
MD
292}
293
294/*
8aa3430c
MD
295 * tsleep/wakeup hash table parameters. Try to find the sweet spot for
296 * like addresses being slept on.
984263bc 297 */
8aa3430c
MD
298#define TABLESIZE 1024
299#define LOOKUP(x) (((intptr_t)(x) >> 6) & (TABLESIZE - 1))
984263bc 300
fc17ad60
MD
301static cpumask_t slpque_cpumasks[TABLESIZE];
302
984263bc 303/*
a46fac56 304 * General scheduler initialization. We force a reschedule 25 times
fc17ad60
MD
305 * a second by default. Note that cpu0 is initialized in early boot and
306 * cannot make any high level calls.
307 *
308 * Each cpu has its own sleep queue.
984263bc 309 */
984263bc 310void
fc17ad60 311sleep_gdinit(globaldata_t gd)
984263bc 312{
fc17ad60 313 static struct tslpque slpque_cpu0[TABLESIZE];
9c1fad94 314 int i;
984263bc 315
fc17ad60
MD
316 if (gd->gd_cpuid == 0) {
317 sched_quantum = (hz + 24) / 25;
318 hogticks = 2 * sched_quantum;
319
320 gd->gd_tsleep_hash = slpque_cpu0;
321 } else {
77652cad 322 gd->gd_tsleep_hash = kmalloc(sizeof(slpque_cpu0),
fc17ad60
MD
323 M_TSLEEP, M_WAITOK | M_ZERO);
324 }
325 for (i = 0; i < TABLESIZE; ++i)
326 TAILQ_INIT(&gd->gd_tsleep_hash[i]);
984263bc
MD
327}
328
329/*
ae8e83e6
MD
330 * This is a dandy function that allows us to interlock tsleep/wakeup
331 * operations with unspecified upper level locks, such as lockmgr locks,
332 * simply by holding a critical section. The sequence is:
333 *
334 * (acquire upper level lock)
335 * tsleep_interlock(blah)
336 * (release upper level lock)
337 * tsleep(blah, ...)
338 *
339 * Basically this functions queues us on the tsleep queue without actually
340 * descheduling us. When tsleep() is later called with PINTERLOCK it
341 * assumes the thread was already queued, otherwise it queues it there.
342 *
343 * Thus it is possible to receive the wakeup prior to going to sleep and
344 * the race conditions are covered.
345 */
346static __inline void
347_tsleep_interlock(globaldata_t gd, void *ident, int flags)
348{
349 thread_t td = gd->gd_curthread;
350 int id;
351
352 crit_enter_quick(td);
353 if (td->td_flags & TDF_TSLEEPQ) {
354 id = LOOKUP(td->td_wchan);
355 TAILQ_REMOVE(&gd->gd_tsleep_hash[id], td, td_sleepq);
356 if (TAILQ_FIRST(&gd->gd_tsleep_hash[id]) == NULL)
357 atomic_clear_int(&slpque_cpumasks[id], gd->gd_cpumask);
358 } else {
359 td->td_flags |= TDF_TSLEEPQ;
360 }
361 id = LOOKUP(ident);
362 TAILQ_INSERT_TAIL(&gd->gd_tsleep_hash[id], td, td_sleepq);
363 atomic_set_int(&slpque_cpumasks[id], gd->gd_cpumask);
364 td->td_wchan = ident;
365 td->td_wdomain = flags & PDOMAIN_MASK;
ae8e83e6
MD
366 crit_exit_quick(td);
367}
368
369void
370tsleep_interlock(void *ident, int flags)
371{
372 _tsleep_interlock(mycpu, ident, flags);
373}
374
375/*
376 * Remove thread from sleepq. Must be called with a critical section held.
377 */
378static __inline void
379_tsleep_remove(thread_t td)
380{
381 globaldata_t gd = mycpu;
382 int id;
383
384 KKASSERT(td->td_gd == gd);
385 if (td->td_flags & TDF_TSLEEPQ) {
386 td->td_flags &= ~TDF_TSLEEPQ;
387 id = LOOKUP(td->td_wchan);
388 TAILQ_REMOVE(&gd->gd_tsleep_hash[id], td, td_sleepq);
389 if (TAILQ_FIRST(&gd->gd_tsleep_hash[id]) == NULL)
390 atomic_clear_int(&slpque_cpumasks[id], gd->gd_cpumask);
391 td->td_wchan = NULL;
392 td->td_wdomain = 0;
393 }
394}
395
396void
397tsleep_remove(thread_t td)
398{
399 _tsleep_remove(td);
400}
401
402/*
403 * This function removes a thread from the tsleep queue and schedules
404 * it. This function may act asynchronously. The target thread may be
405 * sleeping on a different cpu.
406 *
407 * This function mus be called while in a critical section but if the
408 * target thread is sleeping on a different cpu we cannot safely probe
409 * td_flags.
410 */
411static __inline
412void
413_tsleep_wakeup(struct thread *td)
414{
c4e34360 415#ifdef SMP
ae8e83e6
MD
416 globaldata_t gd = mycpu;
417
ae8e83e6
MD
418 if (td->td_gd != gd) {
419 lwkt_send_ipiq(td->td_gd, (ipifunc1_t)tsleep_wakeup, td);
420 return;
421 }
422#endif
423 _tsleep_remove(td);
424 if (td->td_flags & TDF_TSLEEP_DESCHEDULED) {
425 td->td_flags &= ~TDF_TSLEEP_DESCHEDULED;
426 lwkt_schedule(td);
427 }
428}
429
430static
431void
432tsleep_wakeup(struct thread *td)
433{
434 _tsleep_wakeup(td);
435}
436
437
438/*
984263bc
MD
439 * General sleep call. Suspends the current process until a wakeup is
440 * performed on the specified identifier. The process will then be made
441 * runnable with the specified priority. Sleeps at most timo/hz seconds
377d4740 442 * (0 means no timeout). If flags includes PCATCH flag, signals are checked
984263bc
MD
443 * before and after sleeping, else signals are not checked. Returns 0 if
444 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a
445 * signal needs to be delivered, ERESTART is returned if the current system
446 * call should be restarted if possible, and EINTR is returned if the system
447 * call should be interrupted by the signal (return EINTR).
26a0694b 448 *
0a3f9b47
MD
449 * Note that if we are a process, we release_curproc() before messing with
450 * the LWKT scheduler.
a46fac56
MD
451 *
452 * During autoconfiguration or after a panic, a sleep will simply
453 * lower the priority briefly to allow interrupts, then return.
984263bc
MD
454 */
455int
6656cd91 456tsleep(void *ident, int flags, const char *wmesg, int timo)
984263bc 457{
dadab5e9 458 struct thread *td = curthread;
08f2f1bb 459 struct lwp *lp = td->td_lwp;
0cfcada1 460 struct proc *p = td->td_proc; /* may be NULL */
fc17ad60 461 globaldata_t gd;
344ad853
MD
462 int sig;
463 int catch;
464 int id;
465 int error;
e43a034f 466 int oldpri;
076fecef 467 struct callout thandle;
984263bc 468
0cfcada1
MD
469 /*
470 * NOTE: removed KTRPOINT, it could cause races due to blocking
471 * even in stable. Just scrap it for now.
472 */
dbcd0c9b 473 if (tsleep_now_works == 0 || panicstr) {
984263bc 474 /*
dbcd0c9b
MD
475 * After a panic, or before we actually have an operational
476 * softclock, just give interrupts a chance, then just return;
477 *
984263bc
MD
478 * don't run any other procs or panic below,
479 * in case this is the idle process and already asleep.
480 */
e43a034f
MD
481 splz();
482 oldpri = td->td_pri & TDPRI_MASK;
483 lwkt_setpri_self(safepri);
484 lwkt_switch();
485 lwkt_setpri_self(oldpri);
984263bc
MD
486 return (0);
487 }
8aa3430c 488 logtsleep2(tsleep_beg, ident);
fc17ad60
MD
489 gd = td->td_gd;
490 KKASSERT(td != &gd->gd_idlethread); /* you must be kidding! */
344ad853
MD
491
492 /*
493 * NOTE: all of this occurs on the current cpu, including any
494 * callout-based wakeups, so a critical section is a sufficient
495 * interlock.
496 *
497 * The entire sequence through to where we actually sleep must
498 * run without breaking the critical section.
499 */
344ad853
MD
500 catch = flags & PCATCH;
501 error = 0;
502 sig = 0;
503
37af14fe 504 crit_enter_quick(td);
344ad853 505
0cfcada1 506 KASSERT(ident != NULL, ("tsleep: no ident"));
7278a846
SS
507 KASSERT(lp == NULL ||
508 lp->lwp_stat == LSRUN || /* Obvious */
509 lp->lwp_stat == LSSTOP, /* Set in tstop */
510 ("tsleep %p %s %d",
511 ident, wmesg, lp->lwp_stat));
0cfcada1 512
344ad853
MD
513 /*
514 * Setup for the current process (if this is a process).
515 */
08f2f1bb 516 if (lp) {
344ad853
MD
517 if (catch) {
518 /*
519 * Early termination if PCATCH was set and a
520 * signal is pending, interlocked with the
521 * critical section.
522 *
523 * Early termination only occurs when tsleep() is
164b8401 524 * entered while in a normal LSRUN state.
344ad853 525 */
08f2f1bb 526 if ((sig = CURSIG(lp)) != 0)
344ad853
MD
527 goto resume;
528
529 /*
7c1212ec
MD
530 * Early termination if PCATCH was set and a
531 * mailbox signal was possibly delivered prior to
532 * the system call even being made, in order to
533 * allow the user to interlock without having to
534 * make additional system calls.
535 */
536 if (p->p_flag & P_MAILBOX)
537 goto resume;
538
539 /*
84204577 540 * Causes ksignal to wake us up when.
344ad853 541 */
9a379a4a 542 lp->lwp_flag |= LWP_SINTR;
344ad853 543 }
4ecd8190 544 }
344ad853 545
4ecd8190
MD
546 /*
547 * We interlock the sleep queue if the caller has not already done
548 * it for us.
549 */
550 if ((flags & PINTERLOCKED) == 0) {
551 id = LOOKUP(ident);
552 _tsleep_interlock(gd, ident, flags);
553 }
554
555 /*
556 *
557 * If no interlock was set we do an integrated interlock here.
558 * Make sure the current process has been untangled from
559 * the userland scheduler and initialize slptime to start
560 * counting. We must interlock the sleep queue before doing
561 * this to avoid wakeup/process-ipi races which can occur under
562 * heavy loads.
563 */
564 if (lp) {
08f2f1bb
SS
565 p->p_usched->release_curproc(lp);
566 lp->lwp_slptime = 0;
0a3f9b47 567 }
fc17ad60
MD
568
569 /*
d9345d3a
MD
570 * If the interlocked flag is set but our cpu bit in the slpqueue
571 * is no longer set, then a wakeup was processed inbetween the
4ecd8190
MD
572 * tsleep_interlock() (ours or the callers), and here. This can
573 * occur under numerous circumstances including when we release the
574 * current process.
d9345d3a 575 *
4ecd8190
MD
576 * Extreme loads can cause the sending of an IPI (e.g. wakeup()'s)
577 * to process incoming IPIs, thus draining incoming wakeups.
d9345d3a 578 */
4ecd8190
MD
579 if ((td->td_flags & TDF_TSLEEPQ) == 0) {
580 logtsleep2(ilockfail, ident);
581 goto resume;
d9345d3a 582 }
4ecd8190
MD
583
584 /*
585 * scheduling is blocked while in a critical section. Coincide
586 * the descheduled-by-tsleep flag with the descheduling of the
587 * lwkt.
588 */
37af14fe 589 lwkt_deschedule_self(td);
ae8e83e6 590 td->td_flags |= TDF_TSLEEP_DESCHEDULED;
344ad853 591 td->td_wmesg = wmesg;
344ad853
MD
592
593 /*
594 * Setup the timeout, if any
595 */
076fecef
MD
596 if (timo) {
597 callout_init(&thandle);
598 callout_reset(&thandle, timo, endtsleep, td);
599 }
344ad853 600
984263bc 601 /*
344ad853 602 * Beddy bye bye.
984263bc 603 */
08f2f1bb 604 if (lp) {
26a0694b 605 /*
52eedfb5 606 * Ok, we are sleeping. Place us in the SSLEEP state.
26a0694b 607 */
9388413d 608 KKASSERT((lp->lwp_flag & LWP_ONRUNQ) == 0);
7278a846
SS
609 /*
610 * tstop() sets LSSTOP, so don't fiddle with that.
611 */
612 if (lp->lwp_stat != LSSTOP)
613 lp->lwp_stat = LSSLEEP;
08f2f1bb 614 lp->lwp_ru.ru_nvcsw++;
344ad853 615 lwkt_switch();
ab554892
MD
616
617 /*
164b8401 618 * And when we are woken up, put us back in LSRUN. If we
ab554892
MD
619 * slept for over a second, recalculate our estcpu.
620 */
164b8401 621 lp->lwp_stat = LSRUN;
08f2f1bb
SS
622 if (lp->lwp_slptime)
623 p->p_usched->recalculate(lp);
624 lp->lwp_slptime = 0;
0cfcada1
MD
625 } else {
626 lwkt_switch();
627 }
344ad853 628
fc17ad60
MD
629 /*
630 * Make sure we haven't switched cpus while we were asleep. It's
344ad853 631 * not supposed to happen. Cleanup our temporary flags.
fc17ad60
MD
632 */
633 KKASSERT(gd == td->td_gd);
344ad853
MD
634
635 /*
636 * Cleanup the timeout.
637 */
638 if (timo) {
639 if (td->td_flags & TDF_TIMEOUT) {
640 td->td_flags &= ~TDF_TIMEOUT;
a40da8f0 641 error = EWOULDBLOCK;
344ad853
MD
642 } else {
643 callout_stop(&thandle);
644 }
0cfcada1 645 }
344ad853
MD
646
647 /*
ae8e83e6
MD
648 * Make sure we have been removed from the sleepq. This should
649 * have been done for us already.
344ad853 650 */
ae8e83e6 651 _tsleep_remove(td);
344ad853 652 td->td_wmesg = NULL;
ae8e83e6
MD
653 if (td->td_flags & TDF_TSLEEP_DESCHEDULED) {
654 td->td_flags &= ~TDF_TSLEEP_DESCHEDULED;
655 kprintf("td %p (%s) unexpectedly rescheduled\n",
656 td, td->td_comm);
657 }
344ad853
MD
658
659 /*
7c1212ec
MD
660 * Figure out the correct error return. If interrupted by a
661 * signal we want to return EINTR or ERESTART.
662 *
663 * If P_MAILBOX is set no automatic system call restart occurs
664 * and we return EINTR. P_MAILBOX is meant to be used as an
665 * interlock, the user must poll it prior to any system call
666 * that it wishes to interlock a mailbox signal against since
667 * the flag is cleared on *any* system call that sleeps.
344ad853
MD
668 */
669resume:
0cfcada1 670 if (p) {
7c1212ec
MD
671 if (catch && error == 0) {
672 if ((p->p_flag & P_MAILBOX) && sig == 0) {
344ad853 673 error = EINTR;
08f2f1bb 674 } else if (sig != 0 || (sig = CURSIG(lp))) {
7c1212ec
MD
675 if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
676 error = EINTR;
677 else
678 error = ERESTART;
679 }
984263bc 680 }
9a379a4a
SS
681 lp->lwp_flag &= ~(LWP_BREAKTSLEEP | LWP_SINTR);
682 p->p_flag &= ~P_MAILBOX;
984263bc 683 }
8aa3430c 684 logtsleep1(tsleep_end);
344ad853
MD
685 crit_exit_quick(td);
686 return (error);
984263bc
MD
687}
688
984263bc 689/*
bf765287
MD
690 * Interlocked spinlock sleep. An exclusively held spinlock must
691 * be passed to msleep(). The function will atomically release the
692 * spinlock and tsleep on the ident, then reacquire the spinlock and
693 * return.
694 *
695 * This routine is fairly important along the critical path, so optimize it
696 * heavily.
697 */
698int
699msleep(void *ident, struct spinlock *spin, int flags,
700 const char *wmesg, int timo)
701{
702 globaldata_t gd = mycpu;
703 int error;
16523a43 704
ae8e83e6 705 _tsleep_interlock(gd, ident, flags);
bf765287 706 spin_unlock_wr_quick(gd, spin);
ef48be0d 707 error = tsleep(ident, flags | PINTERLOCKED, wmesg, timo);
bf765287 708 spin_lock_wr_quick(gd, spin);
bf765287
MD
709
710 return (error);
16523a43
MD
711}
712
713/*
7f6220a9
MD
714 * Interlocked mutex sleep. An exclusively held mutex must be passed
715 * to mtxsleep(). The function will atomically release the mutex
716 * and tsleep on the ident, then reacquire the mutex and return.
717 */
718int
719mtxsleep(void *ident, struct mtx *mtx, int flags,
720 const char *wmesg, int timo)
721{
722 globaldata_t gd = mycpu;
723 int error;
724
725 _tsleep_interlock(gd, ident, flags);
726 mtx_unlock(mtx);
727 error = tsleep(ident, flags | PINTERLOCKED, wmesg, timo);
728 mtx_lock_ex_quick(mtx, wmesg);
729
730 return (error);
731}
732
733/*
362e59be 734 * Interlocked serializer sleep. An exclusively held serializer must
ed3f6624 735 * be passed to zsleep(). The function will atomically release
362e59be
SZ
736 * the serializer and tsleep on the ident, then reacquire the serializer
737 * and return.
738 */
739int
ed3f6624
MD
740zsleep(void *ident, struct lwkt_serialize *slz, int flags,
741 const char *wmesg, int timo)
362e59be 742{
ae8e83e6 743 globaldata_t gd = mycpu;
362e59be
SZ
744 int ret;
745
746 ASSERT_SERIALIZED(slz);
747
ae8e83e6 748 _tsleep_interlock(gd, ident, flags);
362e59be 749 lwkt_serialize_exit(slz);
ef48be0d 750 ret = tsleep(ident, flags | PINTERLOCKED, wmesg, timo);
362e59be 751 lwkt_serialize_enter(slz);
362e59be
SZ
752
753 return ret;
754}
755
756/*
a22c590e
MD
757 * Directly block on the LWKT thread by descheduling it. This
758 * is much faster then tsleep(), but the only legal way to wake
759 * us up is to directly schedule the thread.
760 *
761 * Setting TDF_SINTR will cause new signals to directly schedule us.
762 *
ae8e83e6 763 * This routine must be called while in a critical section.
a22c590e
MD
764 */
765int
766lwkt_sleep(const char *wmesg, int flags)
767{
768 thread_t td = curthread;
769 int sig;
770
771 if ((flags & PCATCH) == 0 || td->td_lwp == NULL) {
772 td->td_flags |= TDF_BLOCKED;
773 td->td_wmesg = wmesg;
774 lwkt_deschedule_self(td);
775 lwkt_switch();
776 td->td_wmesg = NULL;
777 td->td_flags &= ~TDF_BLOCKED;
778 return(0);
779 }
780 if ((sig = CURSIG(td->td_lwp)) != 0) {
781 if (SIGISMEMBER(td->td_proc->p_sigacts->ps_sigintr, sig))
782 return(EINTR);
783 else
784 return(ERESTART);
785
786 }
787 td->td_flags |= TDF_BLOCKED | TDF_SINTR;
788 td->td_wmesg = wmesg;
789 lwkt_deschedule_self(td);
790 lwkt_switch();
791 td->td_flags &= ~(TDF_BLOCKED | TDF_SINTR);
792 td->td_wmesg = NULL;
793 return(0);
794}
795
796/*
344ad853 797 * Implement the timeout for tsleep.
fc17ad60 798 *
9a379a4a 799 * We set LWP_BREAKTSLEEP to indicate that an event has occured, but
344ad853
MD
800 * we only call setrunnable if the process is not stopped.
801 *
802 * This type of callout timeout is scheduled on the same cpu the process
803 * is sleeping on. Also, at the moment, the MP lock is held.
984263bc
MD
804 */
805static void
0cfcada1 806endtsleep(void *arg)
984263bc 807{
0cfcada1 808 thread_t td = arg;
9a379a4a 809 struct lwp *lp;
984263bc 810
344ad853 811 ASSERT_MP_LOCK_HELD(curthread);
37af14fe 812 crit_enter();
344ad853
MD
813
814 /*
815 * cpu interlock. Thread flags are only manipulated on
816 * the cpu owning the thread. proc flags are only manipulated
817 * by the older of the MP lock. We have both.
818 */
ae8e83e6 819 if (td->td_flags & TDF_TSLEEP_DESCHEDULED) {
0cfcada1 820 td->td_flags |= TDF_TIMEOUT;
344ad853 821
9a379a4a
SS
822 if ((lp = td->td_lwp) != NULL) {
823 lp->lwp_flag |= LWP_BREAKTSLEEP;
824 if (lp->lwp_proc->p_stat != SSTOP)
825 setrunnable(lp);
0cfcada1 826 } else {
ae8e83e6 827 _tsleep_wakeup(td);
0cfcada1 828 }
984263bc 829 }
37af14fe 830 crit_exit();
984263bc
MD
831}
832
984263bc 833/*
8fb8bca6 834 * Make all processes sleeping on the specified identifier runnable.
fc17ad60
MD
835 * count may be zero or one only.
836 *
837 * The domain encodes the sleep/wakeup domain AND the first cpu to check
838 * (which is always the current cpu). As we iterate across cpus
344ad853
MD
839 *
840 * This call may run without the MP lock held. We can only manipulate thread
841 * state on the cpu owning the thread. We CANNOT manipulate process state
842 * at all.
8fb8bca6
EN
843 */
844static void
fc17ad60 845_wakeup(void *ident, int domain)
8fb8bca6 846{
fc17ad60 847 struct tslpque *qp;
0cfcada1
MD
848 struct thread *td;
849 struct thread *ntd;
fc17ad60 850 globaldata_t gd;
fc17ad60
MD
851#ifdef SMP
852 cpumask_t mask;
fc17ad60
MD
853#endif
854 int id;
984263bc 855
37af14fe 856 crit_enter();
8aa3430c 857 logtsleep2(wakeup_beg, ident);
fc17ad60
MD
858 gd = mycpu;
859 id = LOOKUP(ident);
860 qp = &gd->gd_tsleep_hash[id];
984263bc 861restart:
0cfcada1 862 for (td = TAILQ_FIRST(qp); td != NULL; td = ntd) {
ae8e83e6 863 ntd = TAILQ_NEXT(td, td_sleepq);
fc17ad60
MD
864 if (td->td_wchan == ident &&
865 td->td_wdomain == (domain & PDOMAIN_MASK)
866 ) {
ae8e83e6
MD
867 KKASSERT(td->td_gd == gd);
868 _tsleep_remove(td);
869 if (td->td_flags & TDF_TSLEEP_DESCHEDULED) {
870 td->td_flags &= ~TDF_TSLEEP_DESCHEDULED;
871 lwkt_schedule(td);
872 if (domain & PWAKEUP_ONE)
873 goto done;
fc17ad60 874 }
0cfcada1 875 goto restart;
984263bc
MD
876 }
877 }
fc17ad60
MD
878
879#ifdef SMP
880 /*
881 * We finished checking the current cpu but there still may be
882 * more work to do. Either wakeup_one was requested and no matching
883 * thread was found, or a normal wakeup was requested and we have
884 * to continue checking cpus.
885 *
fc17ad60
MD
886 * It should be noted that this scheme is actually less expensive then
887 * the old scheme when waking up multiple threads, since we send
888 * only one IPI message per target candidate which may then schedule
889 * multiple threads. Before we could have wound up sending an IPI
890 * message for each thread on the target cpu (!= current cpu) that
891 * needed to be woken up.
892 *
893 * NOTE: Wakeups occuring on remote cpus are asynchronous. This
894 * should be ok since we are passing idents in the IPI rather then
895 * thread pointers.
896 */
1f4f6e0b
MD
897 if ((domain & PWAKEUP_MYCPU) == 0 &&
898 (mask = slpque_cpumasks[id] & gd->gd_other_cpus) != 0) {
899 lwkt_send_ipiq2_mask(mask, _wakeup, ident,
900 domain | PWAKEUP_MYCPU);
fc17ad60
MD
901 }
902#endif
903done:
8aa3430c 904 logtsleep1(wakeup_end);
37af14fe 905 crit_exit();
984263bc
MD
906}
907
b336a9b1
MD
908/*
909 * Wakeup all threads tsleep()ing on the specified ident, on all cpus
910 */
984263bc 911void
0cfcada1 912wakeup(void *ident)
984263bc 913{
fc17ad60 914 _wakeup(ident, PWAKEUP_ENCODE(0, mycpu->gd_cpuid));
0cfcada1 915}
984263bc 916
b336a9b1
MD
917/*
918 * Wakeup one thread tsleep()ing on the specified ident, on any cpu.
919 */
0cfcada1
MD
920void
921wakeup_one(void *ident)
922{
fc17ad60
MD
923 /* XXX potentially round-robin the first responding cpu */
924 _wakeup(ident, PWAKEUP_ENCODE(0, mycpu->gd_cpuid) | PWAKEUP_ONE);
da5fb9ef
MD
925}
926
b336a9b1
MD
927/*
928 * Wakeup threads tsleep()ing on the specified ident on the current cpu
929 * only.
930 */
931void
932wakeup_mycpu(void *ident)
933{
934 _wakeup(ident, PWAKEUP_MYCPU);
935}
936
937/*
938 * Wakeup one thread tsleep()ing on the specified ident on the current cpu
939 * only.
940 */
941void
942wakeup_mycpu_one(void *ident)
943{
944 /* XXX potentially round-robin the first responding cpu */
945 _wakeup(ident, PWAKEUP_MYCPU|PWAKEUP_ONE);
946}
947
948/*
949 * Wakeup all thread tsleep()ing on the specified ident on the specified cpu
950 * only.
951 */
952void
953wakeup_oncpu(globaldata_t gd, void *ident)
954{
1699d292 955#ifdef SMP
b336a9b1
MD
956 if (gd == mycpu) {
957 _wakeup(ident, PWAKEUP_MYCPU);
958 } else {
959 lwkt_send_ipiq2(gd, _wakeup, ident, PWAKEUP_MYCPU);
960 }
1699d292
MD
961#else
962 _wakeup(ident, PWAKEUP_MYCPU);
963#endif
b336a9b1
MD
964}
965
966/*
967 * Wakeup one thread tsleep()ing on the specified ident on the specified cpu
968 * only.
969 */
970void
971wakeup_oncpu_one(globaldata_t gd, void *ident)
972{
1699d292 973#ifdef SMP
b336a9b1
MD
974 if (gd == mycpu) {
975 _wakeup(ident, PWAKEUP_MYCPU | PWAKEUP_ONE);
976 } else {
977 lwkt_send_ipiq2(gd, _wakeup, ident, PWAKEUP_MYCPU | PWAKEUP_ONE);
978 }
1699d292
MD
979#else
980 _wakeup(ident, PWAKEUP_MYCPU | PWAKEUP_ONE);
981#endif
b336a9b1
MD
982}
983
984/*
985 * Wakeup all threads waiting on the specified ident that slept using
986 * the specified domain, on all cpus.
987 */
da5fb9ef
MD
988void
989wakeup_domain(void *ident, int domain)
990{
fc17ad60 991 _wakeup(ident, PWAKEUP_ENCODE(domain, mycpu->gd_cpuid));
da5fb9ef
MD
992}
993
b336a9b1
MD
994/*
995 * Wakeup one thread waiting on the specified ident that slept using
996 * the specified domain, on any cpu.
997 */
da5fb9ef
MD
998void
999wakeup_domain_one(void *ident, int domain)
1000{
fc17ad60
MD
1001 /* XXX potentially round-robin the first responding cpu */
1002 _wakeup(ident, PWAKEUP_ENCODE(domain, mycpu->gd_cpuid) | PWAKEUP_ONE);
984263bc
MD
1003}
1004
1005/*
344ad853
MD
1006 * setrunnable()
1007 *
1008 * Make a process runnable. The MP lock must be held on call. This only
1009 * has an effect if we are in SSLEEP. We only break out of the
9a379a4a 1010 * tsleep if LWP_BREAKTSLEEP is set, otherwise we just fix-up the state.
37af14fe 1011 *
344ad853
MD
1012 * NOTE: With the MP lock held we can only safely manipulate the process
1013 * structure. We cannot safely manipulate the thread structure.
984263bc
MD
1014 */
1015void
9a379a4a 1016setrunnable(struct lwp *lp)
984263bc 1017{
344ad853
MD
1018 crit_enter();
1019 ASSERT_MP_LOCK_HELD(curthread);
2daf83b0
SS
1020 if (lp->lwp_stat == LSSTOP)
1021 lp->lwp_stat = LSSLEEP;
1022 if (lp->lwp_stat == LSSLEEP && (lp->lwp_flag & LWP_BREAKTSLEEP))
ae8e83e6 1023 _tsleep_wakeup(lp->lwp_thread);
344ad853 1024 crit_exit();
984263bc
MD
1025}
1026
1027/*
164b8401
SS
1028 * The process is stopped due to some condition, usually because p_stat is
1029 * set to SSTOP, but also possibly due to being traced.
fc17ad60 1030 *
164b8401 1031 * NOTE! If the caller sets SSTOP, the caller must also clear P_WAITED
344ad853
MD
1032 * because the parent may check the child's status before the child actually
1033 * gets to this routine.
1034 *
9a379a4a 1035 * This routine is called with the current lwp only, typically just
344ad853
MD
1036 * before returning to userland.
1037 *
9a379a4a 1038 * Setting LWP_BREAKTSLEEP before entering the tsleep will cause a passive
344ad853 1039 * SIGCONT to break out of the tsleep.
984263bc
MD
1040 */
1041void
9a379a4a 1042tstop(void)
984263bc 1043{
9a379a4a 1044 struct lwp *lp = curthread->td_lwp;
7278a846 1045 struct proc *p = lp->lwp_proc;
9a379a4a 1046
7278a846 1047 crit_enter();
f33e8653
SS
1048 /*
1049 * If LWP_WSTOP is set, we were sleeping
1050 * while our process was stopped. At this point
1051 * we were already counted as stopped.
1052 */
1053 if ((lp->lwp_flag & LWP_WSTOP) == 0) {
1054 /*
1055 * If we're the last thread to stop, signal
1056 * our parent.
1057 */
1058 p->p_nstopped++;
1059 lp->lwp_flag |= LWP_WSTOP;
ea59a697 1060 wakeup(&p->p_nstopped);
f33e8653
SS
1061 if (p->p_nstopped == p->p_nthreads) {
1062 p->p_flag &= ~P_WAITED;
1063 wakeup(p->p_pptr);
1064 if ((p->p_pptr->p_sigacts->ps_flag & PS_NOCLDSTOP) == 0)
1065 ksignal(p->p_pptr, SIGCHLD);
1066 }
1067 }
ea59a697
SS
1068 while (p->p_stat == SSTOP) {
1069 lp->lwp_flag |= LWP_BREAKTSLEEP;
1070 lp->lwp_stat = LSSTOP;
1071 tsleep(p, 0, "stop", 0);
1072 }
7278a846 1073 p->p_nstopped--;
a5ff9d37 1074 lp->lwp_flag &= ~LWP_WSTOP;
7278a846 1075 crit_exit();
26a0694b
MD
1076}
1077
1078/*
a77ac49d
MD
1079 * Yield / synchronous reschedule. This is a bit tricky because the trap
1080 * code might have set a lazy release on the switch function. Setting
1081 * P_PASSIVE_ACQ will ensure that the lazy release executes when we call
1082 * switch, and that we are given a greater chance of affinity with our
1083 * current cpu.
1084 *
1085 * We call lwkt_setpri_self() to rotate our thread to the end of the lwkt
1086 * run queue. lwkt_switch() will also execute any assigned passive release
1087 * (which usually calls release_curproc()), allowing a same/higher priority
1088 * process to be designated as the current process.
1089 *
1090 * While it is possible for a lower priority process to be designated,
1091 * it's call to lwkt_maybe_switch() in acquire_curproc() will likely
1092 * round-robin back to us and we will be able to re-acquire the current
1093 * process designation.
1094 */
1095void
1096uio_yield(void)
1097{
1098 struct thread *td = curthread;
1099 struct proc *p = td->td_proc;
1100
1101 lwkt_setpri_self(td->td_pri & TDPRI_MASK);
1102 if (p) {
1103 p->p_flag |= P_PASSIVE_ACQ;
1104 lwkt_switch();
1105 p->p_flag &= ~P_PASSIVE_ACQ;
1106 } else {
1107 lwkt_switch();
1108 }
1109}
1110
1111/*
984263bc
MD
1112 * Compute a tenex style load average of a quantity on
1113 * 1, 5 and 15 minute intervals.
1114 */
c7e98b2f 1115static int loadav_count_runnable(struct lwp *p, void *data);
8fa76237 1116
984263bc
MD
1117static void
1118loadav(void *arg)
1119{
984263bc 1120 struct loadavg *avg;
8fa76237 1121 int i, nrun;
984263bc 1122
984263bc 1123 nrun = 0;
c7e98b2f 1124 alllwp_scan(loadav_count_runnable, &nrun);
8fa76237
MD
1125 avg = &averunnable;
1126 for (i = 0; i < 3; i++) {
984263bc
MD
1127 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
1128 nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
8fa76237 1129 }
984263bc
MD
1130
1131 /*
1132 * Schedule the next update to occur after 5 seconds, but add a
1133 * random variation to avoid synchronisation with processes that
1134 * run at regular intervals.
1135 */
cddfb7bb 1136 callout_reset(&loadav_callout, hz * 4 + (int)(krandom() % (hz * 2 + 1)),
8fa76237
MD
1137 loadav, NULL);
1138}
1139
1140static int
c7e98b2f 1141loadav_count_runnable(struct lwp *lp, void *data)
8fa76237
MD
1142{
1143 int *nrunp = data;
1144 thread_t td;
1145
164b8401
SS
1146 switch (lp->lwp_stat) {
1147 case LSRUN:
08f2f1bb 1148 if ((td = lp->lwp_thread) == NULL)
8fa76237
MD
1149 break;
1150 if (td->td_flags & TDF_BLOCKED)
1151 break;
8fa76237
MD
1152 ++*nrunp;
1153 break;
1154 default:
1155 break;
1156 }
1157 return(0);
984263bc
MD
1158}
1159
1160/* ARGSUSED */
1161static void
6656cd91 1162sched_setup(void *dummy)
984263bc 1163{
984263bc 1164 callout_init(&loadav_callout);
35f9d051 1165 callout_init(&schedcpu_callout);
984263bc
MD
1166
1167 /* Kick off timeout driven events by calling first time. */
984263bc
MD
1168 schedcpu(NULL);
1169 loadav(NULL);
1170}
1171