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