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