kern_synch.c revision 1.296.4.1 1 /* $NetBSD: kern_synch.c,v 1.296.4.1 2012/02/18 07:35:31 mrg Exp $ */
2
3 /*-
4 * Copyright (c) 1999, 2000, 2004, 2006, 2007, 2008, 2009
5 * The NetBSD Foundation, Inc.
6 * All rights reserved.
7 *
8 * This code is derived from software contributed to The NetBSD Foundation
9 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
10 * NASA Ames Research Center, by Charles M. Hannum, Andrew Doran and
11 * Daniel Sieger.
12 *
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
15 * are met:
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
23 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
24 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
26 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGE.
33 */
34
35 /*-
36 * Copyright (c) 1982, 1986, 1990, 1991, 1993
37 * The Regents of the University of California. All rights reserved.
38 * (c) UNIX System Laboratories, Inc.
39 * All or some portions of this file are derived from material licensed
40 * to the University of California by American Telephone and Telegraph
41 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
42 * the permission of UNIX System Laboratories, Inc.
43 *
44 * Redistribution and use in source and binary forms, with or without
45 * modification, are permitted provided that the following conditions
46 * are met:
47 * 1. Redistributions of source code must retain the above copyright
48 * notice, this list of conditions and the following disclaimer.
49 * 2. Redistributions in binary form must reproduce the above copyright
50 * notice, this list of conditions and the following disclaimer in the
51 * documentation and/or other materials provided with the distribution.
52 * 3. Neither the name of the University nor the names of its contributors
53 * may be used to endorse or promote products derived from this software
54 * without specific prior written permission.
55 *
56 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
57 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
58 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
59 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
60 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
61 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
62 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
63 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
64 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
65 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66 * SUCH DAMAGE.
67 *
68 * @(#)kern_synch.c 8.9 (Berkeley) 5/19/95
69 */
70
71 #include <sys/cdefs.h>
72 __KERNEL_RCSID(0, "$NetBSD: kern_synch.c,v 1.296.4.1 2012/02/18 07:35:31 mrg Exp $");
73
74 #include "opt_kstack.h"
75 #include "opt_perfctrs.h"
76 #include "opt_sa.h"
77 #include "opt_dtrace.h"
78
79 #define __MUTEX_PRIVATE
80
81 #include <sys/param.h>
82 #include <sys/systm.h>
83 #include <sys/proc.h>
84 #include <sys/kernel.h>
85 #if defined(PERFCTRS)
86 #include <sys/pmc.h>
87 #endif
88 #include <sys/cpu.h>
89 #include <sys/pserialize.h>
90 #include <sys/resourcevar.h>
91 #include <sys/sched.h>
92 #include <sys/sa.h>
93 #include <sys/savar.h>
94 #include <sys/syscall_stats.h>
95 #include <sys/sleepq.h>
96 #include <sys/lockdebug.h>
97 #include <sys/evcnt.h>
98 #include <sys/intr.h>
99 #include <sys/lwpctl.h>
100 #include <sys/atomic.h>
101 #include <sys/simplelock.h>
102 #include <sys/syslog.h>
103
104 #include <uvm/uvm_extern.h>
105
106 #include <dev/lockstat.h>
107
108 #include <sys/dtrace_bsd.h>
109 int dtrace_vtime_active=0;
110 dtrace_vtime_switch_func_t dtrace_vtime_switch_func;
111
112 static void sched_unsleep(struct lwp *, bool);
113 static void sched_changepri(struct lwp *, pri_t);
114 static void sched_lendpri(struct lwp *, pri_t);
115 static void resched_cpu(struct lwp *);
116
117 syncobj_t sleep_syncobj = {
118 SOBJ_SLEEPQ_SORTED,
119 sleepq_unsleep,
120 sleepq_changepri,
121 sleepq_lendpri,
122 syncobj_noowner,
123 };
124
125 syncobj_t sched_syncobj = {
126 SOBJ_SLEEPQ_SORTED,
127 sched_unsleep,
128 sched_changepri,
129 sched_lendpri,
130 syncobj_noowner,
131 };
132
133 /* "Lightning bolt": once a second sleep address. */
134 kcondvar_t lbolt __cacheline_aligned;
135
136 u_int sched_pstats_ticks __cacheline_aligned;
137
138 /* Preemption event counters. */
139 static struct evcnt kpreempt_ev_crit __cacheline_aligned;
140 static struct evcnt kpreempt_ev_klock __cacheline_aligned;
141 static struct evcnt kpreempt_ev_immed __cacheline_aligned;
142
143 /*
144 * During autoconfiguration or after a panic, a sleep will simply lower the
145 * priority briefly to allow interrupts, then return. The priority to be
146 * used (safepri) is machine-dependent, thus this value is initialized and
147 * maintained in the machine-dependent layers. This priority will typically
148 * be 0, or the lowest priority that is safe for use on the interrupt stack;
149 * it can be made higher to block network software interrupts after panics.
150 */
151 int safepri;
152
153 void
154 synch_init(void)
155 {
156
157 cv_init(&lbolt, "lbolt");
158
159 evcnt_attach_dynamic(&kpreempt_ev_crit, EVCNT_TYPE_MISC, NULL,
160 "kpreempt", "defer: critical section");
161 evcnt_attach_dynamic(&kpreempt_ev_klock, EVCNT_TYPE_MISC, NULL,
162 "kpreempt", "defer: kernel_lock");
163 evcnt_attach_dynamic(&kpreempt_ev_immed, EVCNT_TYPE_MISC, NULL,
164 "kpreempt", "immediate");
165 }
166
167 /*
168 * OBSOLETE INTERFACE
169 *
170 * General sleep call. Suspends the current LWP until a wakeup is
171 * performed on the specified identifier. The LWP will then be made
172 * runnable with the specified priority. Sleeps at most timo/hz seconds (0
173 * means no timeout). If pri includes PCATCH flag, signals are checked
174 * before and after sleeping, else signals are not checked. Returns 0 if
175 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a
176 * signal needs to be delivered, ERESTART is returned if the current system
177 * call should be restarted if possible, and EINTR is returned if the system
178 * call should be interrupted by the signal (return EINTR).
179 */
180 int
181 tsleep(wchan_t ident, pri_t priority, const char *wmesg, int timo)
182 {
183 struct lwp *l = curlwp;
184 sleepq_t *sq;
185 kmutex_t *mp;
186
187 KASSERT((l->l_pflag & LP_INTR) == 0);
188 KASSERT(ident != &lbolt);
189
190 if (sleepq_dontsleep(l)) {
191 (void)sleepq_abort(NULL, 0);
192 return 0;
193 }
194
195 l->l_kpriority = true;
196 sq = sleeptab_lookup(&sleeptab, ident, &mp);
197 sleepq_enter(sq, l, mp);
198 sleepq_enqueue(sq, ident, wmesg, &sleep_syncobj);
199 return sleepq_block(timo, priority & PCATCH);
200 }
201
202 int
203 mtsleep(wchan_t ident, pri_t priority, const char *wmesg, int timo,
204 kmutex_t *mtx)
205 {
206 struct lwp *l = curlwp;
207 sleepq_t *sq;
208 kmutex_t *mp;
209 int error;
210
211 KASSERT((l->l_pflag & LP_INTR) == 0);
212 KASSERT(ident != &lbolt);
213
214 if (sleepq_dontsleep(l)) {
215 (void)sleepq_abort(mtx, (priority & PNORELOCK) != 0);
216 return 0;
217 }
218
219 l->l_kpriority = true;
220 sq = sleeptab_lookup(&sleeptab, ident, &mp);
221 sleepq_enter(sq, l, mp);
222 sleepq_enqueue(sq, ident, wmesg, &sleep_syncobj);
223 mutex_exit(mtx);
224 error = sleepq_block(timo, priority & PCATCH);
225
226 if ((priority & PNORELOCK) == 0)
227 mutex_enter(mtx);
228
229 return error;
230 }
231
232 /*
233 * General sleep call for situations where a wake-up is not expected.
234 */
235 int
236 kpause(const char *wmesg, bool intr, int timo, kmutex_t *mtx)
237 {
238 struct lwp *l = curlwp;
239 kmutex_t *mp;
240 sleepq_t *sq;
241 int error;
242
243 KASSERT(!(timo == 0 && intr == false));
244
245 if (sleepq_dontsleep(l))
246 return sleepq_abort(NULL, 0);
247
248 if (mtx != NULL)
249 mutex_exit(mtx);
250 l->l_kpriority = true;
251 sq = sleeptab_lookup(&sleeptab, l, &mp);
252 sleepq_enter(sq, l, mp);
253 sleepq_enqueue(sq, l, wmesg, &sleep_syncobj);
254 error = sleepq_block(timo, intr);
255 if (mtx != NULL)
256 mutex_enter(mtx);
257
258 return error;
259 }
260
261 #ifdef KERN_SA
262 /*
263 * sa_awaken:
264 *
265 * We believe this lwp is an SA lwp. If it's yielding,
266 * let it know it needs to wake up.
267 *
268 * We are called and exit with the lwp locked. We are
269 * called in the middle of wakeup operations, so we need
270 * to not touch the locks at all.
271 */
272 void
273 sa_awaken(struct lwp *l)
274 {
275 /* LOCK_ASSERT(lwp_locked(l, NULL)); */
276
277 if (l == l->l_savp->savp_lwp && l->l_flag & LW_SA_YIELD)
278 l->l_flag &= ~LW_SA_IDLE;
279 }
280 #endif /* KERN_SA */
281
282 /*
283 * OBSOLETE INTERFACE
284 *
285 * Make all LWPs sleeping on the specified identifier runnable.
286 */
287 void
288 wakeup(wchan_t ident)
289 {
290 sleepq_t *sq;
291 kmutex_t *mp;
292
293 if (__predict_false(cold))
294 return;
295
296 sq = sleeptab_lookup(&sleeptab, ident, &mp);
297 sleepq_wake(sq, ident, (u_int)-1, mp);
298 }
299
300 /*
301 * General yield call. Puts the current LWP back on its run queue and
302 * performs a voluntary context switch. Should only be called when the
303 * current LWP explicitly requests it (eg sched_yield(2)).
304 */
305 void
306 yield(void)
307 {
308 struct lwp *l = curlwp;
309
310 KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
311 lwp_lock(l);
312 KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_lwplock));
313 KASSERT(l->l_stat == LSONPROC);
314 l->l_kpriority = false;
315 (void)mi_switch(l);
316 KERNEL_LOCK(l->l_biglocks, l);
317 }
318
319 /*
320 * General preemption call. Puts the current LWP back on its run queue
321 * and performs an involuntary context switch.
322 */
323 void
324 preempt(void)
325 {
326 struct lwp *l = curlwp;
327
328 KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
329 lwp_lock(l);
330 KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_lwplock));
331 KASSERT(l->l_stat == LSONPROC);
332 l->l_kpriority = false;
333 l->l_nivcsw++;
334 (void)mi_switch(l);
335 KERNEL_LOCK(l->l_biglocks, l);
336 }
337
338 /*
339 * Handle a request made by another agent to preempt the current LWP
340 * in-kernel. Usually called when l_dopreempt may be non-zero.
341 *
342 * Character addresses for lockstat only.
343 */
344 static char in_critical_section;
345 static char kernel_lock_held;
346 static char is_softint;
347 static char cpu_kpreempt_enter_fail;
348
349 bool
350 kpreempt(uintptr_t where)
351 {
352 uintptr_t failed;
353 lwp_t *l;
354 int s, dop, lsflag;
355
356 l = curlwp;
357 failed = 0;
358 while ((dop = l->l_dopreempt) != 0) {
359 if (l->l_stat != LSONPROC) {
360 /*
361 * About to block (or die), let it happen.
362 * Doesn't really count as "preemption has
363 * been blocked", since we're going to
364 * context switch.
365 */
366 l->l_dopreempt = 0;
367 return true;
368 }
369 if (__predict_false((l->l_flag & LW_IDLE) != 0)) {
370 /* Can't preempt idle loop, don't count as failure. */
371 l->l_dopreempt = 0;
372 return true;
373 }
374 if (__predict_false(l->l_nopreempt != 0)) {
375 /* LWP holds preemption disabled, explicitly. */
376 if ((dop & DOPREEMPT_COUNTED) == 0) {
377 kpreempt_ev_crit.ev_count++;
378 }
379 failed = (uintptr_t)&in_critical_section;
380 break;
381 }
382 if (__predict_false((l->l_pflag & LP_INTR) != 0)) {
383 /* Can't preempt soft interrupts yet. */
384 l->l_dopreempt = 0;
385 failed = (uintptr_t)&is_softint;
386 break;
387 }
388 s = splsched();
389 if (__predict_false(l->l_blcnt != 0 ||
390 curcpu()->ci_biglock_wanted != NULL)) {
391 /* Hold or want kernel_lock, code is not MT safe. */
392 splx(s);
393 if ((dop & DOPREEMPT_COUNTED) == 0) {
394 kpreempt_ev_klock.ev_count++;
395 }
396 failed = (uintptr_t)&kernel_lock_held;
397 break;
398 }
399 if (__predict_false(!cpu_kpreempt_enter(where, s))) {
400 /*
401 * It may be that the IPL is too high.
402 * kpreempt_enter() can schedule an
403 * interrupt to retry later.
404 */
405 splx(s);
406 failed = (uintptr_t)&cpu_kpreempt_enter_fail;
407 break;
408 }
409 /* Do it! */
410 if (__predict_true((dop & DOPREEMPT_COUNTED) == 0)) {
411 kpreempt_ev_immed.ev_count++;
412 }
413 lwp_lock(l);
414 mi_switch(l);
415 l->l_nopreempt++;
416 splx(s);
417
418 /* Take care of any MD cleanup. */
419 cpu_kpreempt_exit(where);
420 l->l_nopreempt--;
421 }
422
423 if (__predict_true(!failed)) {
424 return false;
425 }
426
427 /* Record preemption failure for reporting via lockstat. */
428 atomic_or_uint(&l->l_dopreempt, DOPREEMPT_COUNTED);
429 lsflag = 0;
430 LOCKSTAT_ENTER(lsflag);
431 if (__predict_false(lsflag)) {
432 if (where == 0) {
433 where = (uintptr_t)__builtin_return_address(0);
434 }
435 /* Preemption is on, might recurse, so make it atomic. */
436 if (atomic_cas_ptr_ni((void *)&l->l_pfailaddr, NULL,
437 (void *)where) == NULL) {
438 LOCKSTAT_START_TIMER(lsflag, l->l_pfailtime);
439 l->l_pfaillock = failed;
440 }
441 }
442 LOCKSTAT_EXIT(lsflag);
443 return true;
444 }
445
446 /*
447 * Return true if preemption is explicitly disabled.
448 */
449 bool
450 kpreempt_disabled(void)
451 {
452 const lwp_t *l = curlwp;
453
454 return l->l_nopreempt != 0 || l->l_stat == LSZOMB ||
455 (l->l_flag & LW_IDLE) != 0 || cpu_kpreempt_disabled();
456 }
457
458 /*
459 * Disable kernel preemption.
460 */
461 void
462 kpreempt_disable(void)
463 {
464
465 KPREEMPT_DISABLE(curlwp);
466 }
467
468 /*
469 * Reenable kernel preemption.
470 */
471 void
472 kpreempt_enable(void)
473 {
474
475 KPREEMPT_ENABLE(curlwp);
476 }
477
478 /*
479 * Compute the amount of time during which the current lwp was running.
480 *
481 * - update l_rtime unless it's an idle lwp.
482 */
483
484 void
485 updatertime(lwp_t *l, const struct bintime *now)
486 {
487
488 if (__predict_false(l->l_flag & LW_IDLE))
489 return;
490
491 /* rtime += now - stime */
492 bintime_add(&l->l_rtime, now);
493 bintime_sub(&l->l_rtime, &l->l_stime);
494 }
495
496 /*
497 * Select next LWP from the current CPU to run..
498 */
499 static inline lwp_t *
500 nextlwp(struct cpu_info *ci, struct schedstate_percpu *spc)
501 {
502 lwp_t *newl;
503
504 /*
505 * Let sched_nextlwp() select the LWP to run the CPU next.
506 * If no LWP is runnable, select the idle LWP.
507 *
508 * Note that spc_lwplock might not necessary be held, and
509 * new thread would be unlocked after setting the LWP-lock.
510 */
511 newl = sched_nextlwp();
512 if (newl != NULL) {
513 sched_dequeue(newl);
514 KASSERT(lwp_locked(newl, spc->spc_mutex));
515 KASSERT(newl->l_cpu == ci);
516 newl->l_stat = LSONPROC;
517 newl->l_pflag |= LP_RUNNING;
518 lwp_setlock(newl, spc->spc_lwplock);
519 } else {
520 newl = ci->ci_data.cpu_idlelwp;
521 newl->l_stat = LSONPROC;
522 newl->l_pflag |= LP_RUNNING;
523 }
524
525 /*
526 * Only clear want_resched if there are no pending (slow)
527 * software interrupts.
528 */
529 ci->ci_want_resched = ci->ci_data.cpu_softints;
530 spc->spc_flags &= ~SPCF_SWITCHCLEAR;
531 spc->spc_curpriority = lwp_eprio(newl);
532
533 return newl;
534 }
535
536 /*
537 * The machine independent parts of context switch.
538 *
539 * Returns 1 if another LWP was actually run.
540 */
541 int
542 mi_switch(lwp_t *l)
543 {
544 struct cpu_info *ci;
545 struct schedstate_percpu *spc;
546 struct lwp *newl;
547 int retval, oldspl;
548 struct bintime bt;
549 bool returning;
550
551 KASSERT(lwp_locked(l, NULL));
552 KASSERT(kpreempt_disabled());
553 LOCKDEBUG_BARRIER(l->l_mutex, 1);
554
555 kstack_check_magic(l);
556
557 binuptime(&bt);
558
559 KASSERT((l->l_pflag & LP_RUNNING) != 0);
560 KASSERT(l->l_cpu == curcpu());
561 ci = l->l_cpu;
562 spc = &ci->ci_schedstate;
563 returning = false;
564 newl = NULL;
565
566 /*
567 * If we have been asked to switch to a specific LWP, then there
568 * is no need to inspect the run queues. If a soft interrupt is
569 * blocking, then return to the interrupted thread without adjusting
570 * VM context or its start time: neither have been changed in order
571 * to take the interrupt.
572 */
573 if (l->l_switchto != NULL) {
574 if ((l->l_pflag & LP_INTR) != 0) {
575 returning = true;
576 softint_block(l);
577 if ((l->l_pflag & LP_TIMEINTR) != 0)
578 updatertime(l, &bt);
579 }
580 newl = l->l_switchto;
581 l->l_switchto = NULL;
582 }
583 #ifndef __HAVE_FAST_SOFTINTS
584 else if (ci->ci_data.cpu_softints != 0) {
585 /* There are pending soft interrupts, so pick one. */
586 newl = softint_picklwp();
587 newl->l_stat = LSONPROC;
588 newl->l_pflag |= LP_RUNNING;
589 }
590 #endif /* !__HAVE_FAST_SOFTINTS */
591
592 /* Count time spent in current system call */
593 if (!returning) {
594 SYSCALL_TIME_SLEEP(l);
595
596 /*
597 * XXXSMP If we are using h/w performance counters,
598 * save context.
599 */
600 #if PERFCTRS
601 if (PMC_ENABLED(l->l_proc)) {
602 pmc_save_context(l->l_proc);
603 }
604 #endif
605 updatertime(l, &bt);
606 }
607
608 /* Lock the runqueue */
609 KASSERT(l->l_stat != LSRUN);
610 mutex_spin_enter(spc->spc_mutex);
611
612 /*
613 * If on the CPU and we have gotten this far, then we must yield.
614 */
615 if (l->l_stat == LSONPROC && l != newl) {
616 KASSERT(lwp_locked(l, spc->spc_lwplock));
617 if ((l->l_flag & LW_IDLE) == 0) {
618 l->l_stat = LSRUN;
619 lwp_setlock(l, spc->spc_mutex);
620 sched_enqueue(l, true);
621 /*
622 * Handle migration. Note that "migrating LWP" may
623 * be reset here, if interrupt/preemption happens
624 * early in idle LWP.
625 */
626 if (l->l_target_cpu != NULL) {
627 KASSERT((l->l_pflag & LP_INTR) == 0);
628 spc->spc_migrating = l;
629 }
630 } else
631 l->l_stat = LSIDL;
632 }
633
634 /* Pick new LWP to run. */
635 if (newl == NULL) {
636 newl = nextlwp(ci, spc);
637 }
638
639 /* Items that must be updated with the CPU locked. */
640 if (!returning) {
641 /* Update the new LWP's start time. */
642 newl->l_stime = bt;
643
644 /*
645 * ci_curlwp changes when a fast soft interrupt occurs.
646 * We use cpu_onproc to keep track of which kernel or
647 * user thread is running 'underneath' the software
648 * interrupt. This is important for time accounting,
649 * itimers and forcing user threads to preempt (aston).
650 */
651 ci->ci_data.cpu_onproc = newl;
652 }
653
654 /*
655 * Preemption related tasks. Must be done with the current
656 * CPU locked.
657 */
658 cpu_did_resched(l);
659 l->l_dopreempt = 0;
660 if (__predict_false(l->l_pfailaddr != 0)) {
661 LOCKSTAT_FLAG(lsflag);
662 LOCKSTAT_ENTER(lsflag);
663 LOCKSTAT_STOP_TIMER(lsflag, l->l_pfailtime);
664 LOCKSTAT_EVENT_RA(lsflag, l->l_pfaillock, LB_NOPREEMPT|LB_SPIN,
665 1, l->l_pfailtime, l->l_pfailaddr);
666 LOCKSTAT_EXIT(lsflag);
667 l->l_pfailtime = 0;
668 l->l_pfaillock = 0;
669 l->l_pfailaddr = 0;
670 }
671
672 if (l != newl) {
673 struct lwp *prevlwp;
674
675 /* Release all locks, but leave the current LWP locked */
676 if (l->l_mutex == spc->spc_mutex) {
677 /*
678 * Drop spc_lwplock, if the current LWP has been moved
679 * to the run queue (it is now locked by spc_mutex).
680 */
681 mutex_spin_exit(spc->spc_lwplock);
682 } else {
683 /*
684 * Otherwise, drop the spc_mutex, we are done with the
685 * run queues.
686 */
687 mutex_spin_exit(spc->spc_mutex);
688 }
689
690 /*
691 * Mark that context switch is going to be performed
692 * for this LWP, to protect it from being switched
693 * to on another CPU.
694 */
695 KASSERT(l->l_ctxswtch == 0);
696 l->l_ctxswtch = 1;
697 l->l_ncsw++;
698 KASSERT((l->l_pflag & LP_RUNNING) != 0);
699 l->l_pflag &= ~LP_RUNNING;
700
701 /*
702 * Increase the count of spin-mutexes before the release
703 * of the last lock - we must remain at IPL_SCHED during
704 * the context switch.
705 */
706 KASSERTMSG(ci->ci_mtx_count == -1,
707 "%s: cpu%u: ci_mtx_count (%d) != -1",
708 __func__, cpu_index(ci), ci->ci_mtx_count);
709 oldspl = MUTEX_SPIN_OLDSPL(ci);
710 ci->ci_mtx_count--;
711 lwp_unlock(l);
712
713 /* Count the context switch on this CPU. */
714 ci->ci_data.cpu_nswtch++;
715
716 /* Update status for lwpctl, if present. */
717 if (l->l_lwpctl != NULL)
718 l->l_lwpctl->lc_curcpu = LWPCTL_CPU_NONE;
719
720 /*
721 * Save old VM context, unless a soft interrupt
722 * handler is blocking.
723 */
724 if (!returning)
725 pmap_deactivate(l);
726
727 /*
728 * We may need to spin-wait if 'newl' is still
729 * context switching on another CPU.
730 */
731 if (__predict_false(newl->l_ctxswtch != 0)) {
732 u_int count;
733 count = SPINLOCK_BACKOFF_MIN;
734 while (newl->l_ctxswtch)
735 SPINLOCK_BACKOFF(count);
736 }
737
738 /*
739 * If DTrace has set the active vtime enum to anything
740 * other than INACTIVE (0), then it should have set the
741 * function to call.
742 */
743 if (__predict_false(dtrace_vtime_active)) {
744 (*dtrace_vtime_switch_func)(newl);
745 }
746
747 /* Switch to the new LWP.. */
748 prevlwp = cpu_switchto(l, newl, returning);
749 ci = curcpu();
750
751 /*
752 * Switched away - we have new curlwp.
753 * Restore VM context and IPL.
754 */
755 pmap_activate(l);
756 uvm_emap_switch(l);
757 pcu_switchpoint(l);
758
759 if (prevlwp != NULL) {
760 /* Normalize the count of the spin-mutexes */
761 ci->ci_mtx_count++;
762 /* Unmark the state of context switch */
763 membar_exit();
764 prevlwp->l_ctxswtch = 0;
765 }
766
767 /* Update status for lwpctl, if present. */
768 if (l->l_lwpctl != NULL) {
769 l->l_lwpctl->lc_curcpu = (int)cpu_index(ci);
770 l->l_lwpctl->lc_pctr++;
771 }
772
773 /* Note trip through cpu_switchto(). */
774 pserialize_switchpoint();
775
776 KASSERT(l->l_cpu == ci);
777 splx(oldspl);
778 retval = 1;
779 } else {
780 /* Nothing to do - just unlock and return. */
781 mutex_spin_exit(spc->spc_mutex);
782 lwp_unlock(l);
783 retval = 0;
784 }
785
786 KASSERT(l == curlwp);
787 KASSERT(l->l_stat == LSONPROC);
788
789 /*
790 * XXXSMP If we are using h/w performance counters, restore context.
791 * XXXSMP preemption problem.
792 */
793 #if PERFCTRS
794 if (PMC_ENABLED(l->l_proc)) {
795 pmc_restore_context(l->l_proc);
796 }
797 #endif
798 SYSCALL_TIME_WAKEUP(l);
799 LOCKDEBUG_BARRIER(NULL, 1);
800
801 return retval;
802 }
803
804 /*
805 * The machine independent parts of context switch to oblivion.
806 * Does not return. Call with the LWP unlocked.
807 */
808 void
809 lwp_exit_switchaway(lwp_t *l)
810 {
811 struct cpu_info *ci;
812 struct lwp *newl;
813 struct bintime bt;
814
815 ci = l->l_cpu;
816
817 KASSERT(kpreempt_disabled());
818 KASSERT(l->l_stat == LSZOMB || l->l_stat == LSIDL);
819 KASSERT(ci == curcpu());
820 LOCKDEBUG_BARRIER(NULL, 0);
821
822 kstack_check_magic(l);
823
824 /* Count time spent in current system call */
825 SYSCALL_TIME_SLEEP(l);
826 binuptime(&bt);
827 updatertime(l, &bt);
828
829 /* Must stay at IPL_SCHED even after releasing run queue lock. */
830 (void)splsched();
831
832 /*
833 * Let sched_nextlwp() select the LWP to run the CPU next.
834 * If no LWP is runnable, select the idle LWP.
835 *
836 * Note that spc_lwplock might not necessary be held, and
837 * new thread would be unlocked after setting the LWP-lock.
838 */
839 spc_lock(ci);
840 #ifndef __HAVE_FAST_SOFTINTS
841 if (ci->ci_data.cpu_softints != 0) {
842 /* There are pending soft interrupts, so pick one. */
843 newl = softint_picklwp();
844 newl->l_stat = LSONPROC;
845 newl->l_pflag |= LP_RUNNING;
846 } else
847 #endif /* !__HAVE_FAST_SOFTINTS */
848 {
849 newl = nextlwp(ci, &ci->ci_schedstate);
850 }
851
852 /* Update the new LWP's start time. */
853 newl->l_stime = bt;
854 l->l_pflag &= ~LP_RUNNING;
855
856 /*
857 * ci_curlwp changes when a fast soft interrupt occurs.
858 * We use cpu_onproc to keep track of which kernel or
859 * user thread is running 'underneath' the software
860 * interrupt. This is important for time accounting,
861 * itimers and forcing user threads to preempt (aston).
862 */
863 ci->ci_data.cpu_onproc = newl;
864
865 /*
866 * Preemption related tasks. Must be done with the current
867 * CPU locked.
868 */
869 cpu_did_resched(l);
870
871 /* Unlock the run queue. */
872 spc_unlock(ci);
873
874 /* Count the context switch on this CPU. */
875 ci->ci_data.cpu_nswtch++;
876
877 /* Update status for lwpctl, if present. */
878 if (l->l_lwpctl != NULL)
879 l->l_lwpctl->lc_curcpu = LWPCTL_CPU_EXITED;
880
881 /*
882 * We may need to spin-wait if 'newl' is still
883 * context switching on another CPU.
884 */
885 if (__predict_false(newl->l_ctxswtch != 0)) {
886 u_int count;
887 count = SPINLOCK_BACKOFF_MIN;
888 while (newl->l_ctxswtch)
889 SPINLOCK_BACKOFF(count);
890 }
891
892 /*
893 * If DTrace has set the active vtime enum to anything
894 * other than INACTIVE (0), then it should have set the
895 * function to call.
896 */
897 if (__predict_false(dtrace_vtime_active)) {
898 (*dtrace_vtime_switch_func)(newl);
899 }
900
901 /* Switch to the new LWP.. */
902 (void)cpu_switchto(NULL, newl, false);
903
904 for (;;) continue; /* XXX: convince gcc about "noreturn" */
905 /* NOTREACHED */
906 }
907
908 /*
909 * setrunnable: change LWP state to be runnable, placing it on the run queue.
910 *
911 * Call with the process and LWP locked. Will return with the LWP unlocked.
912 */
913 void
914 setrunnable(struct lwp *l)
915 {
916 struct proc *p = l->l_proc;
917 struct cpu_info *ci;
918
919 KASSERT((l->l_flag & LW_IDLE) == 0);
920 KASSERT(mutex_owned(p->p_lock));
921 KASSERT(lwp_locked(l, NULL));
922 KASSERT(l->l_mutex != l->l_cpu->ci_schedstate.spc_mutex);
923
924 switch (l->l_stat) {
925 case LSSTOP:
926 /*
927 * If we're being traced (possibly because someone attached us
928 * while we were stopped), check for a signal from the debugger.
929 */
930 if ((p->p_slflag & PSL_TRACED) != 0 && p->p_xstat != 0)
931 signotify(l);
932 p->p_nrlwps++;
933 break;
934 case LSSUSPENDED:
935 l->l_flag &= ~LW_WSUSPEND;
936 p->p_nrlwps++;
937 cv_broadcast(&p->p_lwpcv);
938 break;
939 case LSSLEEP:
940 KASSERT(l->l_wchan != NULL);
941 break;
942 default:
943 panic("setrunnable: lwp %p state was %d", l, l->l_stat);
944 }
945
946 #ifdef KERN_SA
947 if (l->l_proc->p_sa)
948 sa_awaken(l);
949 #endif /* KERN_SA */
950
951 /*
952 * If the LWP was sleeping, start it again.
953 */
954 if (l->l_wchan != NULL) {
955 l->l_stat = LSSLEEP;
956 /* lwp_unsleep() will release the lock. */
957 lwp_unsleep(l, true);
958 return;
959 }
960
961 /*
962 * If the LWP is still on the CPU, mark it as LSONPROC. It may be
963 * about to call mi_switch(), in which case it will yield.
964 */
965 if ((l->l_pflag & LP_RUNNING) != 0) {
966 l->l_stat = LSONPROC;
967 l->l_slptime = 0;
968 lwp_unlock(l);
969 return;
970 }
971
972 /*
973 * Look for a CPU to run.
974 * Set the LWP runnable.
975 */
976 ci = sched_takecpu(l);
977 l->l_cpu = ci;
978 spc_lock(ci);
979 lwp_unlock_to(l, ci->ci_schedstate.spc_mutex);
980 sched_setrunnable(l);
981 l->l_stat = LSRUN;
982 l->l_slptime = 0;
983
984 sched_enqueue(l, false);
985 resched_cpu(l);
986 lwp_unlock(l);
987 }
988
989 /*
990 * suspendsched:
991 *
992 * Convert all non-LW_SYSTEM LSSLEEP or LSRUN LWPs to LSSUSPENDED.
993 */
994 void
995 suspendsched(void)
996 {
997 CPU_INFO_ITERATOR cii;
998 struct cpu_info *ci;
999 struct lwp *l;
1000 struct proc *p;
1001
1002 /*
1003 * We do this by process in order not to violate the locking rules.
1004 */
1005 mutex_enter(proc_lock);
1006 PROCLIST_FOREACH(p, &allproc) {
1007 mutex_enter(p->p_lock);
1008 if ((p->p_flag & PK_SYSTEM) != 0) {
1009 mutex_exit(p->p_lock);
1010 continue;
1011 }
1012
1013 p->p_stat = SSTOP;
1014
1015 LIST_FOREACH(l, &p->p_lwps, l_sibling) {
1016 if (l == curlwp)
1017 continue;
1018
1019 lwp_lock(l);
1020
1021 /*
1022 * Set L_WREBOOT so that the LWP will suspend itself
1023 * when it tries to return to user mode. We want to
1024 * try and get to get as many LWPs as possible to
1025 * the user / kernel boundary, so that they will
1026 * release any locks that they hold.
1027 */
1028 l->l_flag |= (LW_WREBOOT | LW_WSUSPEND);
1029
1030 if (l->l_stat == LSSLEEP &&
1031 (l->l_flag & LW_SINTR) != 0) {
1032 /* setrunnable() will release the lock. */
1033 setrunnable(l);
1034 continue;
1035 }
1036
1037 lwp_unlock(l);
1038 }
1039
1040 mutex_exit(p->p_lock);
1041 }
1042 mutex_exit(proc_lock);
1043
1044 /*
1045 * Kick all CPUs to make them preempt any LWPs running in user mode.
1046 * They'll trap into the kernel and suspend themselves in userret().
1047 */
1048 for (CPU_INFO_FOREACH(cii, ci)) {
1049 spc_lock(ci);
1050 cpu_need_resched(ci, RESCHED_IMMED);
1051 spc_unlock(ci);
1052 }
1053 }
1054
1055 /*
1056 * sched_unsleep:
1057 *
1058 * The is called when the LWP has not been awoken normally but instead
1059 * interrupted: for example, if the sleep timed out. Because of this,
1060 * it's not a valid action for running or idle LWPs.
1061 */
1062 static void
1063 sched_unsleep(struct lwp *l, bool cleanup)
1064 {
1065
1066 lwp_unlock(l);
1067 panic("sched_unsleep");
1068 }
1069
1070 static void
1071 resched_cpu(struct lwp *l)
1072 {
1073 struct cpu_info *ci = l->l_cpu;
1074
1075 KASSERT(lwp_locked(l, NULL));
1076 if (lwp_eprio(l) > ci->ci_schedstate.spc_curpriority)
1077 cpu_need_resched(ci, 0);
1078 }
1079
1080 static void
1081 sched_changepri(struct lwp *l, pri_t pri)
1082 {
1083
1084 KASSERT(lwp_locked(l, NULL));
1085
1086 if (l->l_stat == LSRUN) {
1087 KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
1088 sched_dequeue(l);
1089 l->l_priority = pri;
1090 sched_enqueue(l, false);
1091 } else {
1092 l->l_priority = pri;
1093 }
1094 resched_cpu(l);
1095 }
1096
1097 static void
1098 sched_lendpri(struct lwp *l, pri_t pri)
1099 {
1100
1101 KASSERT(lwp_locked(l, NULL));
1102
1103 if (l->l_stat == LSRUN) {
1104 KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
1105 sched_dequeue(l);
1106 l->l_inheritedprio = pri;
1107 sched_enqueue(l, false);
1108 } else {
1109 l->l_inheritedprio = pri;
1110 }
1111 resched_cpu(l);
1112 }
1113
1114 struct lwp *
1115 syncobj_noowner(wchan_t wchan)
1116 {
1117
1118 return NULL;
1119 }
1120
1121 /* Decay 95% of proc::p_pctcpu in 60 seconds, ccpu = exp(-1/20) */
1122 const fixpt_t ccpu = 0.95122942450071400909 * FSCALE;
1123
1124 /*
1125 * Constants for averages over 1, 5 and 15 minutes when sampling at
1126 * 5 second intervals.
1127 */
1128 static const fixpt_t cexp[ ] = {
1129 0.9200444146293232 * FSCALE, /* exp(-1/12) */
1130 0.9834714538216174 * FSCALE, /* exp(-1/60) */
1131 0.9944598480048967 * FSCALE, /* exp(-1/180) */
1132 };
1133
1134 /*
1135 * sched_pstats:
1136 *
1137 * => Update process statistics and check CPU resource allocation.
1138 * => Call scheduler-specific hook to eventually adjust LWP priorities.
1139 * => Compute load average of a quantity on 1, 5 and 15 minute intervals.
1140 */
1141 void
1142 sched_pstats(void)
1143 {
1144 extern struct loadavg averunnable;
1145 struct loadavg *avg = &averunnable;
1146 const int clkhz = (stathz != 0 ? stathz : hz);
1147 static bool backwards = false;
1148 static u_int lavg_count = 0;
1149 struct proc *p;
1150 int nrun;
1151
1152 sched_pstats_ticks++;
1153 if (++lavg_count >= 5) {
1154 lavg_count = 0;
1155 nrun = 0;
1156 }
1157 mutex_enter(proc_lock);
1158 PROCLIST_FOREACH(p, &allproc) {
1159 struct lwp *l;
1160 struct rlimit *rlim;
1161 time_t runtm;
1162 int sig;
1163
1164 /* Increment sleep time (if sleeping), ignore overflow. */
1165 mutex_enter(p->p_lock);
1166 runtm = p->p_rtime.sec;
1167 LIST_FOREACH(l, &p->p_lwps, l_sibling) {
1168 fixpt_t lpctcpu;
1169 u_int lcpticks;
1170
1171 if (__predict_false((l->l_flag & LW_IDLE) != 0))
1172 continue;
1173 lwp_lock(l);
1174 runtm += l->l_rtime.sec;
1175 l->l_swtime++;
1176 sched_lwp_stats(l);
1177
1178 /* For load average calculation. */
1179 if (__predict_false(lavg_count == 0) &&
1180 (l->l_flag & (LW_SINTR | LW_SYSTEM)) == 0) {
1181 switch (l->l_stat) {
1182 case LSSLEEP:
1183 if (l->l_slptime > 1) {
1184 break;
1185 }
1186 case LSRUN:
1187 case LSONPROC:
1188 case LSIDL:
1189 nrun++;
1190 }
1191 }
1192 lwp_unlock(l);
1193
1194 l->l_pctcpu = (l->l_pctcpu * ccpu) >> FSHIFT;
1195 if (l->l_slptime != 0)
1196 continue;
1197
1198 lpctcpu = l->l_pctcpu;
1199 lcpticks = atomic_swap_uint(&l->l_cpticks, 0);
1200 lpctcpu += ((FSCALE - ccpu) *
1201 (lcpticks * FSCALE / clkhz)) >> FSHIFT;
1202 l->l_pctcpu = lpctcpu;
1203 }
1204 /* Calculating p_pctcpu only for ps(1) */
1205 p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
1206
1207 /*
1208 * Check if the process exceeds its CPU resource allocation.
1209 * If over the hard limit, kill it with SIGKILL.
1210 * If over the soft limit, send SIGXCPU and raise
1211 * the soft limit a little.
1212 */
1213 rlim = &p->p_rlimit[RLIMIT_CPU];
1214 sig = 0;
1215 if (__predict_false(runtm >= rlim->rlim_cur)) {
1216 if (runtm >= rlim->rlim_max) {
1217 sig = SIGKILL;
1218 log(LOG_NOTICE, "pid %d is killed: %s\n",
1219 p->p_pid, "exceeded RLIMIT_CPU");
1220 uprintf("pid %d, command %s, is killed: %s\n",
1221 p->p_pid, p->p_comm,
1222 "exceeded RLIMIT_CPU");
1223 } else {
1224 sig = SIGXCPU;
1225 if (rlim->rlim_cur < rlim->rlim_max)
1226 rlim->rlim_cur += 5;
1227 }
1228 }
1229 mutex_exit(p->p_lock);
1230 if (__predict_false(runtm < 0)) {
1231 if (!backwards) {
1232 backwards = true;
1233 printf("WARNING: negative runtime; "
1234 "monotonic clock has gone backwards\n");
1235 }
1236 } else if (__predict_false(sig)) {
1237 KASSERT((p->p_flag & PK_SYSTEM) == 0);
1238 psignal(p, sig);
1239 }
1240 }
1241 mutex_exit(proc_lock);
1242
1243 /* Load average calculation. */
1244 if (__predict_false(lavg_count == 0)) {
1245 int i;
1246 CTASSERT(__arraycount(cexp) == __arraycount(avg->ldavg));
1247 for (i = 0; i < __arraycount(cexp); i++) {
1248 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
1249 nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
1250 }
1251 }
1252
1253 /* Lightning bolt. */
1254 cv_broadcast(&lbolt);
1255 }
1256