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