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