Adjust pamp_growkernel(), elf_brand_inuse(), and ktrace() to use
[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 $
c0b8a06d 40 * $DragonFly: src/sys/kern/kern_synch.c,v 1.60 2006/05/23 20:35:10 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>
50#include <sys/resourcevar.h>
51#include <sys/vmmeter.h>
52#include <sys/sysctl.h>
26a0694b 53#include <sys/thread2.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
MD
61
62#include <machine/cpu.h>
63#include <machine/ipl.h>
64#include <machine/smp.h>
65
fc17ad60
MD
66TAILQ_HEAD(tslpque, thread);
67
402ed7e1 68static void sched_setup (void *dummy);
984263bc
MD
69SYSINIT(sched_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, sched_setup, NULL)
70
984263bc
MD
71int hogticks;
72int lbolt;
344ad853 73int lbolt_syncer;
984263bc 74int sched_quantum; /* Roundrobin scheduling quantum in ticks. */
17a9f566 75int ncpus;
90100055 76int ncpus2, ncpus2_shift, ncpus2_mask;
e43a034f 77int safepri;
984263bc
MD
78
79static struct callout loadav_callout;
35f9d051 80static struct callout schedcpu_callout;
fc17ad60 81MALLOC_DEFINE(M_TSLEEP, "tslpque", "tsleep queues");
984263bc 82
9afb0ffd
MD
83#if !defined(KTR_TSLEEP)
84#define KTR_TSLEEP KTR_ALL
85#endif
86KTR_INFO_MASTER(tsleep);
87KTR_INFO(KTR_TSLEEP, tsleep, tsleep_beg, 0, "tsleep enter", 0);
88KTR_INFO(KTR_TSLEEP, tsleep, tsleep_end, 0, "tsleep exit", 0);
89KTR_INFO(KTR_TSLEEP, tsleep, wakeup_beg, 0, "wakeup enter", 0);
90KTR_INFO(KTR_TSLEEP, tsleep, wakeup_end, 0, "wakeup exit", 0);
91#define logtsleep(name) KTR_LOG(tsleep_ ## name)
92
984263bc
MD
93struct loadavg averunnable =
94 { {0, 0, 0}, FSCALE }; /* load average, of runnable procs */
95/*
96 * Constants for averages over 1, 5, and 15 minutes
97 * when sampling at 5 second intervals.
98 */
99static fixpt_t cexp[3] = {
100 0.9200444146293232 * FSCALE, /* exp(-1/12) */
101 0.9834714538216174 * FSCALE, /* exp(-1/60) */
102 0.9944598480048967 * FSCALE, /* exp(-1/180) */
103};
104
402ed7e1 105static void endtsleep (void *);
344ad853 106static void unsleep_and_wakeup_thread(struct thread *td);
402ed7e1 107static void loadav (void *arg);
402ed7e1 108static void schedcpu (void *arg);
984263bc 109
a46fac56
MD
110/*
111 * Adjust the scheduler quantum. The quantum is specified in microseconds.
112 * Note that 'tick' is in microseconds per tick.
113 */
984263bc
MD
114static int
115sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
116{
117 int error, new_val;
118
119 new_val = sched_quantum * tick;
120 error = sysctl_handle_int(oidp, &new_val, 0, req);
121 if (error != 0 || req->newptr == NULL)
122 return (error);
123 if (new_val < tick)
124 return (EINVAL);
125 sched_quantum = new_val / tick;
126 hogticks = 2 * sched_quantum;
127 return (0);
128}
129
130SYSCTL_PROC(_kern, OID_AUTO, quantum, CTLTYPE_INT|CTLFLAG_RW,
131 0, sizeof sched_quantum, sysctl_kern_quantum, "I", "");
132
984263bc
MD
133/*
134 * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
135 * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
136 * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
137 *
138 * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
dcc99b62 139 * 1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
984263bc
MD
140 *
141 * If you don't want to bother with the faster/more-accurate formula, you
142 * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
143 * (more general) method of calculating the %age of CPU used by a process.
dcc99b62
MD
144 *
145 * decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing
146 */
147#define CCPU_SHIFT 11
148
149static fixpt_t ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
150SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
151
152/*
153 * kernel uses `FSCALE', userland (SHOULD) use kern.fscale
984263bc 154 */
dcc99b62
MD
155static int fscale __unused = FSCALE;
156SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, "");
984263bc
MD
157
158/*
0a3f9b47 159 * Recompute process priorities, once a second.
dcc99b62
MD
160 *
161 * Since the userland schedulers are typically event oriented, if the
162 * estcpu calculation at wakeup() time is not sufficient to make a
163 * process runnable relative to other processes in the system we have
164 * a 1-second recalc to help out.
165 *
166 * This code also allows us to store sysclock_t data in the process structure
167 * without fear of an overrun, since sysclock_t are guarenteed to hold
168 * several seconds worth of count.
984263bc
MD
169 */
170/* ARGSUSED */
171static void
26a0694b 172schedcpu(void *arg)
984263bc 173{
4b5f931b 174 struct proc *p;
344ad853 175 u_int64_t ttime;
4b5f931b 176
344ad853
MD
177 /*
178 * General process statistics once a second
179 */
f62004ad 180 FOREACH_PROC_IN_SYSTEM(p) {
dcc99b62 181 crit_enter();
984263bc 182 p->p_swtime++;
344ad853 183 if (p->p_stat == SSLEEP)
984263bc 184 p->p_slptime++;
a46fac56
MD
185
186 /*
dcc99b62
MD
187 * Only recalculate processes that are active or have slept
188 * less then 2 seconds. The schedulers understand this.
a46fac56 189 */
dcc99b62 190 if (p->p_slptime <= 1) {
553ea3c8 191 p->p_usched->recalculate(&p->p_lwp);
dcc99b62
MD
192 } else {
193 p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
a46fac56 194 }
e43a034f 195 crit_exit();
984263bc 196 }
344ad853
MD
197
198 /*
199 * Resource checks. XXX break out since psignal/killproc can block,
200 * limiting us to one process killed per second. There is probably
201 * a better way.
202 */
203 FOREACH_PROC_IN_SYSTEM(p) {
204 crit_enter();
f026f3b0
MD
205 if (p->p_stat == SIDL ||
206 (p->p_flag & P_ZOMBIE) ||
344ad853
MD
207 p->p_limit == NULL ||
208 p->p_thread == NULL
209 ) {
210 crit_exit();
211 continue;
212 }
213 ttime = p->p_thread->td_sticks + p->p_thread->td_uticks;
c0b8a06d
MD
214 switch(plimit_testcpulimit(p->p_limit, ttime)) {
215 case PLIMIT_TESTCPU_KILL:
216 killproc(p, "exceeded maximum CPU limit");
217 break;
218 case PLIMIT_TESTCPU_XCPU:
219 if ((p->p_flag & P_XCPU) == 0) {
220 p->p_flag |= P_XCPU;
344ad853 221 psignal(p, SIGXCPU);
344ad853 222 }
344ad853 223 break;
c0b8a06d
MD
224 default:
225 crit_exit();
226 continue;
344ad853
MD
227 }
228 crit_exit();
c0b8a06d 229 break;
344ad853 230 }
984263bc 231 wakeup((caddr_t)&lbolt);
344ad853 232 wakeup((caddr_t)&lbolt_syncer);
35f9d051 233 callout_reset(&schedcpu_callout, hz, schedcpu, NULL);
984263bc
MD
234}
235
236/*
dcc99b62
MD
237 * This is only used by ps. Generate a cpu percentage use over
238 * a period of one second.
984263bc 239 */
dcc99b62 240void
553ea3c8 241updatepcpu(struct lwp *lp, int cpticks, int ttlticks)
984263bc 242{
dcc99b62
MD
243 fixpt_t acc;
244 int remticks;
245
246 acc = (cpticks << FSHIFT) / ttlticks;
247 if (ttlticks >= ESTCPUFREQ) {
553ea3c8 248 lp->lwp_pctcpu = acc;
dcc99b62
MD
249 } else {
250 remticks = ESTCPUFREQ - ttlticks;
553ea3c8 251 lp->lwp_pctcpu = (acc * ttlticks + lp->lwp_pctcpu * remticks) /
dcc99b62 252 ESTCPUFREQ;
a46fac56 253 }
984263bc
MD
254}
255
256/*
257 * We're only looking at 7 bits of the address; everything is
258 * aligned to 4, lots of things are aligned to greater powers
259 * of 2. Shift right by 8, i.e. drop the bottom 256 worth.
260 */
261#define TABLESIZE 128
984263bc
MD
262#define LOOKUP(x) (((intptr_t)(x) >> 8) & (TABLESIZE - 1))
263
fc17ad60
MD
264static cpumask_t slpque_cpumasks[TABLESIZE];
265
984263bc 266/*
a46fac56 267 * General scheduler initialization. We force a reschedule 25 times
fc17ad60
MD
268 * a second by default. Note that cpu0 is initialized in early boot and
269 * cannot make any high level calls.
270 *
271 * Each cpu has its own sleep queue.
984263bc 272 */
984263bc 273void
fc17ad60 274sleep_gdinit(globaldata_t gd)
984263bc 275{
fc17ad60 276 static struct tslpque slpque_cpu0[TABLESIZE];
9c1fad94 277 int i;
984263bc 278
fc17ad60
MD
279 if (gd->gd_cpuid == 0) {
280 sched_quantum = (hz + 24) / 25;
281 hogticks = 2 * sched_quantum;
282
283 gd->gd_tsleep_hash = slpque_cpu0;
284 } else {
285 gd->gd_tsleep_hash = malloc(sizeof(slpque_cpu0),
286 M_TSLEEP, M_WAITOK | M_ZERO);
287 }
288 for (i = 0; i < TABLESIZE; ++i)
289 TAILQ_INIT(&gd->gd_tsleep_hash[i]);
984263bc
MD
290}
291
292/*
293 * General sleep call. Suspends the current process until a wakeup is
294 * performed on the specified identifier. The process will then be made
295 * runnable with the specified priority. Sleeps at most timo/hz seconds
377d4740 296 * (0 means no timeout). If flags includes PCATCH flag, signals are checked
984263bc
MD
297 * before and after sleeping, else signals are not checked. Returns 0 if
298 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a
299 * signal needs to be delivered, ERESTART is returned if the current system
300 * call should be restarted if possible, and EINTR is returned if the system
301 * call should be interrupted by the signal (return EINTR).
26a0694b 302 *
0a3f9b47
MD
303 * Note that if we are a process, we release_curproc() before messing with
304 * the LWKT scheduler.
a46fac56
MD
305 *
306 * During autoconfiguration or after a panic, a sleep will simply
307 * lower the priority briefly to allow interrupts, then return.
984263bc
MD
308 */
309int
6656cd91 310tsleep(void *ident, int flags, const char *wmesg, int timo)
984263bc 311{
dadab5e9 312 struct thread *td = curthread;
0cfcada1 313 struct proc *p = td->td_proc; /* may be NULL */
fc17ad60 314 globaldata_t gd;
344ad853
MD
315 int sig;
316 int catch;
317 int id;
318 int error;
e43a034f 319 int oldpri;
076fecef 320 struct callout thandle;
984263bc 321
0cfcada1
MD
322 /*
323 * NOTE: removed KTRPOINT, it could cause races due to blocking
324 * even in stable. Just scrap it for now.
325 */
984263bc
MD
326 if (cold || panicstr) {
327 /*
328 * After a panic, or during autoconfiguration,
329 * just give interrupts a chance, then just return;
330 * don't run any other procs or panic below,
331 * in case this is the idle process and already asleep.
332 */
e43a034f
MD
333 splz();
334 oldpri = td->td_pri & TDPRI_MASK;
335 lwkt_setpri_self(safepri);
336 lwkt_switch();
337 lwkt_setpri_self(oldpri);
984263bc
MD
338 return (0);
339 }
9afb0ffd 340 logtsleep(tsleep_beg);
fc17ad60
MD
341 gd = td->td_gd;
342 KKASSERT(td != &gd->gd_idlethread); /* you must be kidding! */
344ad853
MD
343
344 /*
345 * NOTE: all of this occurs on the current cpu, including any
346 * callout-based wakeups, so a critical section is a sufficient
347 * interlock.
348 *
349 * The entire sequence through to where we actually sleep must
350 * run without breaking the critical section.
351 */
352 id = LOOKUP(ident);
353 catch = flags & PCATCH;
354 error = 0;
355 sig = 0;
356
37af14fe 357 crit_enter_quick(td);
344ad853 358
0cfcada1
MD
359 KASSERT(ident != NULL, ("tsleep: no ident"));
360 KASSERT(p == NULL || p->p_stat == SRUN, ("tsleep %p %s %d",
361 ident, wmesg, p->p_stat));
362
344ad853
MD
363 /*
364 * Setup for the current process (if this is a process).
365 */
0a3f9b47 366 if (p) {
344ad853
MD
367 if (catch) {
368 /*
369 * Early termination if PCATCH was set and a
370 * signal is pending, interlocked with the
371 * critical section.
372 *
373 * Early termination only occurs when tsleep() is
374 * entered while in a normal SRUN state.
375 */
376 if ((sig = CURSIG(p)) != 0)
377 goto resume;
378
379 /*
380 * Causes psignal to wake us up when.
381 */
382 p->p_flag |= P_SINTR;
383 }
384
385 /*
386 * Make sure the current process has been untangled from
387 * the userland scheduler and initialize slptime to start
388 * counting.
389 */
0a3f9b47
MD
390 if (flags & PNORESCHED)
391 td->td_flags |= TDF_NORESCHED;
553ea3c8 392 p->p_usched->release_curproc(&p->p_lwp);
0cfcada1 393 p->p_slptime = 0;
0a3f9b47 394 }
fc17ad60
MD
395
396 /*
344ad853 397 * Move our thread to the correct queue and setup our wchan, etc.
fc17ad60 398 */
37af14fe 399 lwkt_deschedule_self(td);
344ad853 400 td->td_flags |= TDF_TSLEEPQ;
fc17ad60
MD
401 TAILQ_INSERT_TAIL(&gd->gd_tsleep_hash[id], td, td_threadq);
402 atomic_set_int(&slpque_cpumasks[id], gd->gd_cpumask);
344ad853
MD
403
404 td->td_wchan = ident;
405 td->td_wmesg = wmesg;
406 td->td_wdomain = flags & PDOMAIN_MASK;
407
408 /*
409 * Setup the timeout, if any
410 */
076fecef
MD
411 if (timo) {
412 callout_init(&thandle);
413 callout_reset(&thandle, timo, endtsleep, td);
414 }
344ad853 415
984263bc 416 /*
344ad853 417 * Beddy bye bye.
984263bc 418 */
0cfcada1 419 if (p) {
26a0694b 420 /*
344ad853
MD
421 * Ok, we are sleeping. Remove us from the userland runq
422 * and place us in the SSLEEP state.
26a0694b 423 */
344ad853
MD
424 if (p->p_flag & P_ONRUNQ)
425 p->p_usched->remrunqueue(&p->p_lwp);
426 p->p_stat = SSLEEP;
0cfcada1 427 p->p_stats->p_ru.ru_nvcsw++;
344ad853
MD
428 lwkt_switch();
429 p->p_stat = SRUN;
0cfcada1
MD
430 } else {
431 lwkt_switch();
432 }
344ad853 433
fc17ad60
MD
434 /*
435 * Make sure we haven't switched cpus while we were asleep. It's
344ad853 436 * not supposed to happen. Cleanup our temporary flags.
fc17ad60
MD
437 */
438 KKASSERT(gd == td->td_gd);
0a3f9b47 439 td->td_flags &= ~TDF_NORESCHED;
344ad853
MD
440
441 /*
442 * Cleanup the timeout.
443 */
444 if (timo) {
445 if (td->td_flags & TDF_TIMEOUT) {
446 td->td_flags &= ~TDF_TIMEOUT;
447 if (sig == 0)
448 error = EWOULDBLOCK;
449 } else {
450 callout_stop(&thandle);
451 }
0cfcada1 452 }
344ad853
MD
453
454 /*
455 * Since td_threadq is used both for our run queue AND for the
456 * tsleep hash queue, we can't still be on it at this point because
457 * we've gotten cpu back.
458 */
afbfc034 459 KASSERT((td->td_flags & TDF_TSLEEPQ) == 0, ("tsleep: impossible thread flags %08x", td->td_flags));
344ad853
MD
460 td->td_wchan = NULL;
461 td->td_wmesg = NULL;
462 td->td_wdomain = 0;
463
464 /*
465 * Figure out the correct error return
466 */
467resume:
0cfcada1 468 if (p) {
344ad853
MD
469 p->p_flag &= ~(P_BREAKTSLEEP | P_SINTR);
470 if (catch && error == 0 && (sig != 0 || (sig = CURSIG(p)))) {
0cfcada1 471 if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
344ad853
MD
472 error = EINTR;
473 else
474 error = ERESTART;
984263bc 475 }
984263bc 476 }
9afb0ffd 477 logtsleep(tsleep_end);
344ad853
MD
478 crit_exit_quick(td);
479 return (error);
984263bc
MD
480}
481
16523a43
MD
482/*
483 * This is a dandy function that allows us to interlock tsleep/wakeup
484 * operations with unspecified upper level locks, such as lockmgr locks,
485 * simply by holding a critical section. The sequence is:
486 *
487 * (enter critical section)
488 * (acquire upper level lock)
489 * tsleep_interlock(blah)
490 * (release upper level lock)
491 * tsleep(blah, ...)
492 * (exit critical section)
493 *
494 * Basically this function sets our cpumask for the ident which informs
495 * other cpus that our cpu 'might' be waiting (or about to wait on) the
496 * hash index related to the ident. The critical section prevents another
497 * cpu's wakeup() from being processed on our cpu until we are actually
498 * able to enter the tsleep(). Thus, no race occurs between our attempt
499 * to release a resource and sleep, and another cpu's attempt to acquire
500 * a resource and call wakeup.
501 *
502 * There isn't much of a point to this function unless you call it while
503 * holding a critical section.
504 */
505void
506tsleep_interlock(void *ident)
507{
508 int id = LOOKUP(ident);
509
510 atomic_set_int(&slpque_cpumasks[id], mycpu->gd_cpumask);
511}
512
984263bc 513/*
344ad853 514 * Implement the timeout for tsleep.
fc17ad60 515 *
344ad853
MD
516 * We set P_BREAKTSLEEP to indicate that an event has occured, but
517 * we only call setrunnable if the process is not stopped.
518 *
519 * This type of callout timeout is scheduled on the same cpu the process
520 * is sleeping on. Also, at the moment, the MP lock is held.
984263bc
MD
521 */
522static void
0cfcada1 523endtsleep(void *arg)
984263bc 524{
0cfcada1
MD
525 thread_t td = arg;
526 struct proc *p;
984263bc 527
344ad853 528 ASSERT_MP_LOCK_HELD(curthread);
37af14fe 529 crit_enter();
344ad853
MD
530
531 /*
532 * cpu interlock. Thread flags are only manipulated on
533 * the cpu owning the thread. proc flags are only manipulated
534 * by the older of the MP lock. We have both.
535 */
536 if (td->td_flags & TDF_TSLEEPQ) {
0cfcada1 537 td->td_flags |= TDF_TIMEOUT;
344ad853 538
0cfcada1 539 if ((p = td->td_proc) != NULL) {
344ad853
MD
540 p->p_flag |= P_BREAKTSLEEP;
541 if ((p->p_flag & P_STOPPED) == 0)
0cfcada1 542 setrunnable(p);
0cfcada1 543 } else {
344ad853 544 unsleep_and_wakeup_thread(td);
0cfcada1 545 }
984263bc 546 }
37af14fe 547 crit_exit();
984263bc
MD
548}
549
984263bc 550/*
344ad853
MD
551 * Unsleep and wakeup a thread. This function runs without the MP lock
552 * which means that it can only manipulate thread state on the owning cpu,
553 * and cannot touch the process state at all.
984263bc 554 */
344ad853 555static
8fb8bca6 556void
344ad853 557unsleep_and_wakeup_thread(struct thread *td)
8fb8bca6 558{
344ad853 559 globaldata_t gd = mycpu;
fc17ad60
MD
560 int id;
561
344ad853
MD
562#ifdef SMP
563 if (td->td_gd != gd) {
564 lwkt_send_ipiq(td->td_gd, (ipifunc1_t)unsleep_and_wakeup_thread, td);
565 return;
566 }
567#endif
9c1fad94 568 crit_enter();
344ad853
MD
569 if (td->td_flags & TDF_TSLEEPQ) {
570 td->td_flags &= ~TDF_TSLEEPQ;
571 id = LOOKUP(td->td_wchan);
572 TAILQ_REMOVE(&gd->gd_tsleep_hash[id], td, td_threadq);
573 if (TAILQ_FIRST(&gd->gd_tsleep_hash[id]) == NULL)
574 atomic_clear_int(&slpque_cpumasks[id], gd->gd_cpumask);
575 lwkt_schedule(td);
8fb8bca6 576 }
9c1fad94 577 crit_exit();
8fb8bca6 578}
8fb8bca6
EN
579
580/*
581 * Make all processes sleeping on the specified identifier runnable.
fc17ad60
MD
582 * count may be zero or one only.
583 *
584 * The domain encodes the sleep/wakeup domain AND the first cpu to check
585 * (which is always the current cpu). As we iterate across cpus
344ad853
MD
586 *
587 * This call may run without the MP lock held. We can only manipulate thread
588 * state on the cpu owning the thread. We CANNOT manipulate process state
589 * at all.
8fb8bca6
EN
590 */
591static void
fc17ad60 592_wakeup(void *ident, int domain)
984263bc 593{
fc17ad60 594 struct tslpque *qp;
0cfcada1
MD
595 struct thread *td;
596 struct thread *ntd;
fc17ad60 597 globaldata_t gd;
fc17ad60
MD
598#ifdef SMP
599 cpumask_t mask;
600 cpumask_t tmask;
601 int startcpu;
602 int nextcpu;
603#endif
604 int id;
984263bc 605
37af14fe 606 crit_enter();
9afb0ffd 607 logtsleep(wakeup_beg);
fc17ad60
MD
608 gd = mycpu;
609 id = LOOKUP(ident);
610 qp = &gd->gd_tsleep_hash[id];
984263bc 611restart:
0cfcada1
MD
612 for (td = TAILQ_FIRST(qp); td != NULL; td = ntd) {
613 ntd = TAILQ_NEXT(td, td_threadq);
fc17ad60
MD
614 if (td->td_wchan == ident &&
615 td->td_wdomain == (domain & PDOMAIN_MASK)
616 ) {
344ad853
MD
617 KKASSERT(td->td_flags & TDF_TSLEEPQ);
618 td->td_flags &= ~TDF_TSLEEPQ;
0cfcada1 619 TAILQ_REMOVE(qp, td, td_threadq);
fc17ad60
MD
620 if (TAILQ_FIRST(qp) == NULL) {
621 atomic_clear_int(&slpque_cpumasks[id],
622 gd->gd_cpumask);
623 }
344ad853 624 lwkt_schedule(td);
fc17ad60
MD
625 if (domain & PWAKEUP_ONE)
626 goto done;
0cfcada1 627 goto restart;
984263bc
MD
628 }
629 }
fc17ad60
MD
630
631#ifdef SMP
632 /*
633 * We finished checking the current cpu but there still may be
634 * more work to do. Either wakeup_one was requested and no matching
635 * thread was found, or a normal wakeup was requested and we have
636 * to continue checking cpus.
637 *
638 * The cpu that started the wakeup sequence is encoded in the domain.
639 * We use this information to determine which cpus still need to be
640 * checked, locate a candidate cpu, and chain the wakeup
641 * asynchronously with an IPI message.
642 *
643 * It should be noted that this scheme is actually less expensive then
644 * the old scheme when waking up multiple threads, since we send
645 * only one IPI message per target candidate which may then schedule
646 * multiple threads. Before we could have wound up sending an IPI
647 * message for each thread on the target cpu (!= current cpu) that
648 * needed to be woken up.
649 *
650 * NOTE: Wakeups occuring on remote cpus are asynchronous. This
651 * should be ok since we are passing idents in the IPI rather then
652 * thread pointers.
653 */
b336a9b1
MD
654 if ((domain & PWAKEUP_MYCPU) == 0 &&
655 (mask = slpque_cpumasks[id]) != 0
656 ) {
fc17ad60
MD
657 /*
658 * Look for a cpu that might have work to do. Mask out cpus
659 * which have already been processed.
660 *
661 * 31xxxxxxxxxxxxxxxxxxxxxxxxxxxxx0
662 * ^ ^ ^
663 * start currentcpu start
664 * case2 case1
665 * * * *
666 * 11111111111111110000000000000111 case1
667 * 00000000111111110000000000000000 case2
668 *
669 * case1: We started at start_case1 and processed through
670 * to the current cpu. We have to check any bits
671 * after the current cpu, then check bits before
672 * the starting cpu.
673 *
674 * case2: We have already checked all the bits from
675 * start_case2 to the end, and from 0 to the current
676 * cpu. We just have the bits from the current cpu
677 * to start_case2 left to check.
678 */
679 startcpu = PWAKEUP_DECODE(domain);
680 if (gd->gd_cpuid >= startcpu) {
681 /*
682 * CASE1
683 */
684 tmask = mask & ~((gd->gd_cpumask << 1) - 1);
685 if (mask & tmask) {
686 nextcpu = bsfl(mask & tmask);
687 lwkt_send_ipiq2(globaldata_find(nextcpu),
688 _wakeup, ident, domain);
689 } else {
690 tmask = (1 << startcpu) - 1;
691 if (mask & tmask) {
692 nextcpu = bsfl(mask & tmask);
693 lwkt_send_ipiq2(
694 globaldata_find(nextcpu),
695 _wakeup, ident, domain);
696 }
697 }
698 } else {
699 /*
700 * CASE2
701 */
702 tmask = ~((gd->gd_cpumask << 1) - 1) &
703 ((1 << startcpu) - 1);
704 if (mask & tmask) {
705 nextcpu = bsfl(mask & tmask);
706 lwkt_send_ipiq2(globaldata_find(nextcpu),
707 _wakeup, ident, domain);
708 }
709 }
710 }
711#endif
712done:
9afb0ffd 713 logtsleep(wakeup_end);
37af14fe 714 crit_exit();
984263bc
MD
715}
716
b336a9b1
MD
717/*
718 * Wakeup all threads tsleep()ing on the specified ident, on all cpus
719 */
984263bc 720void
0cfcada1 721wakeup(void *ident)
984263bc 722{
fc17ad60 723 _wakeup(ident, PWAKEUP_ENCODE(0, mycpu->gd_cpuid));
0cfcada1 724}
984263bc 725
b336a9b1
MD
726/*
727 * Wakeup one thread tsleep()ing on the specified ident, on any cpu.
728 */
0cfcada1
MD
729void
730wakeup_one(void *ident)
731{
fc17ad60
MD
732 /* XXX potentially round-robin the first responding cpu */
733 _wakeup(ident, PWAKEUP_ENCODE(0, mycpu->gd_cpuid) | PWAKEUP_ONE);
da5fb9ef
MD
734}
735
b336a9b1
MD
736/*
737 * Wakeup threads tsleep()ing on the specified ident on the current cpu
738 * only.
739 */
740void
741wakeup_mycpu(void *ident)
742{
743 _wakeup(ident, PWAKEUP_MYCPU);
744}
745
746/*
747 * Wakeup one thread tsleep()ing on the specified ident on the current cpu
748 * only.
749 */
750void
751wakeup_mycpu_one(void *ident)
752{
753 /* XXX potentially round-robin the first responding cpu */
754 _wakeup(ident, PWAKEUP_MYCPU|PWAKEUP_ONE);
755}
756
757/*
758 * Wakeup all thread tsleep()ing on the specified ident on the specified cpu
759 * only.
760 */
761void
762wakeup_oncpu(globaldata_t gd, void *ident)
763{
1699d292 764#ifdef SMP
b336a9b1
MD
765 if (gd == mycpu) {
766 _wakeup(ident, PWAKEUP_MYCPU);
767 } else {
768 lwkt_send_ipiq2(gd, _wakeup, ident, PWAKEUP_MYCPU);
769 }
1699d292
MD
770#else
771 _wakeup(ident, PWAKEUP_MYCPU);
772#endif
b336a9b1
MD
773}
774
775/*
776 * Wakeup one thread tsleep()ing on the specified ident on the specified cpu
777 * only.
778 */
779void
780wakeup_oncpu_one(globaldata_t gd, void *ident)
781{
1699d292 782#ifdef SMP
b336a9b1
MD
783 if (gd == mycpu) {
784 _wakeup(ident, PWAKEUP_MYCPU | PWAKEUP_ONE);
785 } else {
786 lwkt_send_ipiq2(gd, _wakeup, ident, PWAKEUP_MYCPU | PWAKEUP_ONE);
787 }
1699d292
MD
788#else
789 _wakeup(ident, PWAKEUP_MYCPU | PWAKEUP_ONE);
790#endif
b336a9b1
MD
791}
792
793/*
794 * Wakeup all threads waiting on the specified ident that slept using
795 * the specified domain, on all cpus.
796 */
da5fb9ef
MD
797void
798wakeup_domain(void *ident, int domain)
799{
fc17ad60 800 _wakeup(ident, PWAKEUP_ENCODE(domain, mycpu->gd_cpuid));
da5fb9ef
MD
801}
802
b336a9b1
MD
803/*
804 * Wakeup one thread waiting on the specified ident that slept using
805 * the specified domain, on any cpu.
806 */
da5fb9ef
MD
807void
808wakeup_domain_one(void *ident, int domain)
809{
fc17ad60
MD
810 /* XXX potentially round-robin the first responding cpu */
811 _wakeup(ident, PWAKEUP_ENCODE(domain, mycpu->gd_cpuid) | PWAKEUP_ONE);
984263bc
MD
812}
813
814/*
344ad853
MD
815 * setrunnable()
816 *
817 * Make a process runnable. The MP lock must be held on call. This only
818 * has an effect if we are in SSLEEP. We only break out of the
819 * tsleep if P_BREAKTSLEEP is set, otherwise we just fix-up the state.
37af14fe 820 *
344ad853
MD
821 * NOTE: With the MP lock held we can only safely manipulate the process
822 * structure. We cannot safely manipulate the thread structure.
984263bc
MD
823 */
824void
344ad853 825setrunnable(struct proc *p)
984263bc 826{
344ad853
MD
827 crit_enter();
828 ASSERT_MP_LOCK_HELD(curthread);
829 p->p_flag &= ~P_STOPPED;
830 if (p->p_stat == SSLEEP && (p->p_flag & P_BREAKTSLEEP)) {
831 unsleep_and_wakeup_thread(p->p_thread);
984263bc 832 }
344ad853 833 crit_exit();
984263bc
MD
834}
835
836/*
344ad853
MD
837 * The process is stopped due to some condition, usually because P_STOPPED
838 * is set but also possibly due to being traced.
fc17ad60 839 *
344ad853
MD
840 * NOTE! If the caller sets P_STOPPED, the caller must also clear P_WAITED
841 * because the parent may check the child's status before the child actually
842 * gets to this routine.
843 *
844 * This routine is called with the current process only, typically just
845 * before returning to userland.
846 *
847 * Setting P_BREAKTSLEEP before entering the tsleep will cause a passive
848 * SIGCONT to break out of the tsleep.
984263bc
MD
849 */
850void
344ad853 851tstop(struct proc *p)
984263bc 852{
344ad853
MD
853 wakeup((caddr_t)p->p_pptr);
854 p->p_flag |= P_BREAKTSLEEP;
855 tsleep(p, 0, "stop", 0);
26a0694b
MD
856}
857
a77ac49d
MD
858/*
859 * Yield / synchronous reschedule. This is a bit tricky because the trap
860 * code might have set a lazy release on the switch function. Setting
861 * P_PASSIVE_ACQ will ensure that the lazy release executes when we call
862 * switch, and that we are given a greater chance of affinity with our
863 * current cpu.
864 *
865 * We call lwkt_setpri_self() to rotate our thread to the end of the lwkt
866 * run queue. lwkt_switch() will also execute any assigned passive release
867 * (which usually calls release_curproc()), allowing a same/higher priority
868 * process to be designated as the current process.
869 *
870 * While it is possible for a lower priority process to be designated,
871 * it's call to lwkt_maybe_switch() in acquire_curproc() will likely
872 * round-robin back to us and we will be able to re-acquire the current
873 * process designation.
874 */
875void
876uio_yield(void)
877{
878 struct thread *td = curthread;
879 struct proc *p = td->td_proc;
880
881 lwkt_setpri_self(td->td_pri & TDPRI_MASK);
882 if (p) {
883 p->p_flag |= P_PASSIVE_ACQ;
884 lwkt_switch();
885 p->p_flag &= ~P_PASSIVE_ACQ;
886 } else {
887 lwkt_switch();
888 }
889}
890
984263bc
MD
891/*
892 * Compute a tenex style load average of a quantity on
893 * 1, 5 and 15 minute intervals.
894 */
895static void
896loadav(void *arg)
897{
898 int i, nrun;
899 struct loadavg *avg;
900 struct proc *p;
8ec60c3f 901 thread_t td;
984263bc
MD
902
903 avg = &averunnable;
904 nrun = 0;
f62004ad 905 FOREACH_PROC_IN_SYSTEM(p) {
8ec60c3f
MD
906 switch (p->p_stat) {
907 case SRUN:
908 if ((td = p->p_thread) == NULL)
909 break;
910 if (td->td_flags & TDF_BLOCKED)
911 break;
912 /* fall through */
913 case SIDL:
914 nrun++;
915 break;
916 default:
917 break;
984263bc
MD
918 }
919 }
920 for (i = 0; i < 3; i++)
921 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
922 nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
923
924 /*
925 * Schedule the next update to occur after 5 seconds, but add a
926 * random variation to avoid synchronisation with processes that
927 * run at regular intervals.
928 */
929 callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)),
930 loadav, NULL);
931}
932
933/* ARGSUSED */
934static void
6656cd91 935sched_setup(void *dummy)
984263bc 936{
984263bc 937 callout_init(&loadav_callout);
35f9d051 938 callout_init(&schedcpu_callout);
984263bc
MD
939
940 /* Kick off timeout driven events by calling first time. */
984263bc
MD
941 schedcpu(NULL);
942 loadav(NULL);
943}
944