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