kern_synch.c revision 1.220 1 /* $NetBSD: kern_synch.c,v 1.220 2008/03/16 23:11:30 rmind 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 * 3. All advertising materials mentioning features or use of this software
21 * must display the following acknowledgement:
22 * This product includes software developed by the NetBSD
23 * Foundation, Inc. and its contributors.
24 * 4. Neither the name of The NetBSD Foundation nor the names of its
25 * contributors may be used to endorse or promote products derived
26 * from this software without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
29 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
30 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
31 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
32 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
34 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
35 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
36 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38 * POSSIBILITY OF SUCH DAMAGE.
39 */
40
41 /*-
42 * Copyright (c) 1982, 1986, 1990, 1991, 1993
43 * The Regents of the University of California. All rights reserved.
44 * (c) UNIX System Laboratories, Inc.
45 * All or some portions of this file are derived from material licensed
46 * to the University of California by American Telephone and Telegraph
47 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
48 * the permission of UNIX System Laboratories, Inc.
49 *
50 * Redistribution and use in source and binary forms, with or without
51 * modification, are permitted provided that the following conditions
52 * are met:
53 * 1. Redistributions of source code must retain the above copyright
54 * notice, this list of conditions and the following disclaimer.
55 * 2. Redistributions in binary form must reproduce the above copyright
56 * notice, this list of conditions and the following disclaimer in the
57 * documentation and/or other materials provided with the distribution.
58 * 3. Neither the name of the University nor the names of its contributors
59 * may be used to endorse or promote products derived from this software
60 * without specific prior written permission.
61 *
62 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
63 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
64 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
65 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
66 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
67 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
68 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
69 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
70 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
71 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
72 * SUCH DAMAGE.
73 *
74 * @(#)kern_synch.c 8.9 (Berkeley) 5/19/95
75 */
76
77 #include <sys/cdefs.h>
78 __KERNEL_RCSID(0, "$NetBSD: kern_synch.c,v 1.220 2008/03/16 23:11:30 rmind Exp $");
79
80 #include "opt_kstack.h"
81 #include "opt_lockdebug.h"
82 #include "opt_multiprocessor.h"
83 #include "opt_perfctrs.h"
84
85 #define __MUTEX_PRIVATE
86
87 #include <sys/param.h>
88 #include <sys/systm.h>
89 #include <sys/proc.h>
90 #include <sys/kernel.h>
91 #if defined(PERFCTRS)
92 #include <sys/pmc.h>
93 #endif
94 #include <sys/cpu.h>
95 #include <sys/resourcevar.h>
96 #include <sys/sched.h>
97 #include <sys/syscall_stats.h>
98 #include <sys/sleepq.h>
99 #include <sys/lockdebug.h>
100 #include <sys/evcnt.h>
101 #include <sys/intr.h>
102 #include <sys/lwpctl.h>
103 #include <sys/atomic.h>
104 #include <sys/simplelock.h>
105
106 #include <uvm/uvm_extern.h>
107
108 callout_t sched_pstats_ch;
109 unsigned int sched_pstats_ticks;
110
111 kcondvar_t lbolt; /* once a second sleep address */
112
113 static void sched_unsleep(struct lwp *);
114 static void sched_changepri(struct lwp *, pri_t);
115 static void sched_lendpri(struct lwp *, pri_t);
116
117 syncobj_t sleep_syncobj = {
118 SOBJ_SLEEPQ_SORTED,
119 sleepq_unsleep,
120 sleepq_changepri,
121 sleepq_lendpri,
122 syncobj_noowner,
123 };
124
125 syncobj_t sched_syncobj = {
126 SOBJ_SLEEPQ_SORTED,
127 sched_unsleep,
128 sched_changepri,
129 sched_lendpri,
130 syncobj_noowner,
131 };
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 /*
144 * OBSOLETE INTERFACE
145 *
146 * General sleep call. Suspends the current process until a wakeup is
147 * performed on the specified identifier. The process will then be made
148 * runnable with the specified priority. Sleeps at most timo/hz seconds (0
149 * means no timeout). If pri includes PCATCH flag, signals are checked
150 * before and after sleeping, else signals are not checked. Returns 0 if
151 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a
152 * signal needs to be delivered, ERESTART is returned if the current system
153 * call should be restarted if possible, and EINTR is returned if the system
154 * call should be interrupted by the signal (return EINTR).
155 *
156 * The interlock is held until we are on a sleep queue. The interlock will
157 * be locked before returning back to the caller unless the PNORELOCK flag
158 * is specified, in which case the interlock will always be unlocked upon
159 * return.
160 */
161 int
162 ltsleep(wchan_t ident, pri_t priority, const char *wmesg, int timo,
163 volatile struct simplelock *interlock)
164 {
165 struct lwp *l = curlwp;
166 sleepq_t *sq;
167 int error;
168
169 KASSERT((l->l_pflag & LP_INTR) == 0);
170
171 if (sleepq_dontsleep(l)) {
172 (void)sleepq_abort(NULL, 0);
173 if ((priority & PNORELOCK) != 0)
174 simple_unlock(interlock);
175 return 0;
176 }
177
178 l->l_kpriority = true;
179 sq = sleeptab_lookup(&sleeptab, ident);
180 sleepq_enter(sq, l);
181 sleepq_enqueue(sq, ident, wmesg, &sleep_syncobj);
182
183 if (interlock != NULL) {
184 KASSERT(simple_lock_held(interlock));
185 simple_unlock(interlock);
186 }
187
188 error = sleepq_block(timo, priority & PCATCH);
189
190 if (interlock != NULL && (priority & PNORELOCK) == 0)
191 simple_lock(interlock);
192
193 return error;
194 }
195
196 int
197 mtsleep(wchan_t ident, pri_t priority, const char *wmesg, int timo,
198 kmutex_t *mtx)
199 {
200 struct lwp *l = curlwp;
201 sleepq_t *sq;
202 int error;
203
204 KASSERT((l->l_pflag & LP_INTR) == 0);
205
206 if (sleepq_dontsleep(l)) {
207 (void)sleepq_abort(mtx, (priority & PNORELOCK) != 0);
208 return 0;
209 }
210
211 l->l_kpriority = true;
212 sq = sleeptab_lookup(&sleeptab, ident);
213 sleepq_enter(sq, l);
214 sleepq_enqueue(sq, ident, wmesg, &sleep_syncobj);
215 mutex_exit(mtx);
216 error = sleepq_block(timo, priority & PCATCH);
217
218 if ((priority & PNORELOCK) == 0)
219 mutex_enter(mtx);
220
221 return error;
222 }
223
224 /*
225 * General sleep call for situations where a wake-up is not expected.
226 */
227 int
228 kpause(const char *wmesg, bool intr, int timo, kmutex_t *mtx)
229 {
230 struct lwp *l = curlwp;
231 sleepq_t *sq;
232 int error;
233
234 if (sleepq_dontsleep(l))
235 return sleepq_abort(NULL, 0);
236
237 if (mtx != NULL)
238 mutex_exit(mtx);
239 l->l_kpriority = true;
240 sq = sleeptab_lookup(&sleeptab, l);
241 sleepq_enter(sq, l);
242 sleepq_enqueue(sq, l, wmesg, &sleep_syncobj);
243 error = sleepq_block(timo, intr);
244 if (mtx != NULL)
245 mutex_enter(mtx);
246
247 return error;
248 }
249
250 /*
251 * OBSOLETE INTERFACE
252 *
253 * Make all processes sleeping on the specified identifier runnable.
254 */
255 void
256 wakeup(wchan_t ident)
257 {
258 sleepq_t *sq;
259
260 if (cold)
261 return;
262
263 sq = sleeptab_lookup(&sleeptab, ident);
264 sleepq_wake(sq, ident, (u_int)-1);
265 }
266
267 /*
268 * OBSOLETE INTERFACE
269 *
270 * Make the highest priority process first in line on the specified
271 * identifier runnable.
272 */
273 void
274 wakeup_one(wchan_t ident)
275 {
276 sleepq_t *sq;
277
278 if (cold)
279 return;
280
281 sq = sleeptab_lookup(&sleeptab, ident);
282 sleepq_wake(sq, ident, 1);
283 }
284
285
286 /*
287 * General yield call. Puts the current process back on its run queue and
288 * performs a voluntary context switch. Should only be called when the
289 * current process explicitly requests it (eg sched_yield(2)).
290 */
291 void
292 yield(void)
293 {
294 struct lwp *l = curlwp;
295
296 KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
297 lwp_lock(l);
298 KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_lwplock));
299 KASSERT(l->l_stat == LSONPROC);
300 l->l_kpriority = false;
301 if (l->l_class == SCHED_OTHER) {
302 /*
303 * Only for timeshared threads. It will be reset
304 * by the scheduler in due course.
305 */
306 l->l_priority = 0;
307 }
308 (void)mi_switch(l);
309 KERNEL_LOCK(l->l_biglocks, l);
310 }
311
312 /*
313 * General preemption call. Puts the current process back on its run queue
314 * and performs an involuntary context switch.
315 */
316 void
317 preempt(void)
318 {
319 struct lwp *l = curlwp;
320
321 KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
322 lwp_lock(l);
323 KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_lwplock));
324 KASSERT(l->l_stat == LSONPROC);
325 l->l_kpriority = false;
326 l->l_nivcsw++;
327 (void)mi_switch(l);
328 KERNEL_LOCK(l->l_biglocks, l);
329 }
330
331 /*
332 * Compute the amount of time during which the current lwp was running.
333 *
334 * - update l_rtime unless it's an idle lwp.
335 */
336
337 void
338 updatertime(lwp_t *l, const struct bintime *now)
339 {
340
341 if ((l->l_flag & LW_IDLE) != 0)
342 return;
343
344 /* rtime += now - stime */
345 bintime_add(&l->l_rtime, now);
346 bintime_sub(&l->l_rtime, &l->l_stime);
347 }
348
349 /*
350 * The machine independent parts of context switch.
351 *
352 * Returns 1 if another LWP was actually run.
353 */
354 int
355 mi_switch(lwp_t *l)
356 {
357 struct cpu_info *ci, *tci = NULL;
358 struct schedstate_percpu *spc;
359 struct lwp *newl;
360 int retval, oldspl;
361 struct bintime bt;
362 bool returning;
363
364 KASSERT(lwp_locked(l, NULL));
365 LOCKDEBUG_BARRIER(l->l_mutex, 1);
366
367 #ifdef KSTACK_CHECK_MAGIC
368 kstack_check_magic(l);
369 #endif
370
371 binuptime(&bt);
372
373 KDASSERT(l->l_cpu == curcpu());
374 ci = l->l_cpu;
375 spc = &ci->ci_schedstate;
376 returning = false;
377 newl = NULL;
378
379 /*
380 * If we have been asked to switch to a specific LWP, then there
381 * is no need to inspect the run queues. If a soft interrupt is
382 * blocking, then return to the interrupted thread without adjusting
383 * VM context or its start time: neither have been changed in order
384 * to take the interrupt.
385 */
386 if (l->l_switchto != NULL) {
387 if ((l->l_pflag & LP_INTR) != 0) {
388 returning = true;
389 softint_block(l);
390 if ((l->l_flag & LW_TIMEINTR) != 0)
391 updatertime(l, &bt);
392 }
393 newl = l->l_switchto;
394 l->l_switchto = NULL;
395 }
396 #ifndef __HAVE_FAST_SOFTINTS
397 else if (ci->ci_data.cpu_softints != 0) {
398 /* There are pending soft interrupts, so pick one. */
399 newl = softint_picklwp();
400 newl->l_stat = LSONPROC;
401 newl->l_flag |= LW_RUNNING;
402 }
403 #endif /* !__HAVE_FAST_SOFTINTS */
404
405 /* Count time spent in current system call */
406 if (!returning) {
407 SYSCALL_TIME_SLEEP(l);
408
409 /*
410 * XXXSMP If we are using h/w performance counters,
411 * save context.
412 */
413 #if PERFCTRS
414 if (PMC_ENABLED(l->l_proc)) {
415 pmc_save_context(l->l_proc);
416 }
417 #endif
418 updatertime(l, &bt);
419 }
420
421 /*
422 * If on the CPU and we have gotten this far, then we must yield.
423 */
424 KASSERT(l->l_stat != LSRUN);
425 if (l->l_stat == LSONPROC && (l->l_target_cpu || l != newl)) {
426 KASSERT(lwp_locked(l, spc->spc_lwplock));
427
428 if (l->l_target_cpu == l->l_cpu) {
429 l->l_target_cpu = NULL;
430 } else {
431 tci = l->l_target_cpu;
432 }
433
434 if (__predict_false(tci != NULL)) {
435 /* Double-lock the runqueues */
436 spc_dlock(ci, tci);
437 } else {
438 /* Lock the runqueue */
439 spc_lock(ci);
440 }
441
442 if ((l->l_flag & LW_IDLE) == 0) {
443 l->l_stat = LSRUN;
444 if (__predict_false(tci != NULL)) {
445 /*
446 * Set the new CPU, lock and unset the
447 * l_target_cpu - thread will be enqueued
448 * to the runqueue of target CPU.
449 */
450 l->l_cpu = tci;
451 lwp_setlock(l, tci->ci_schedstate.spc_mutex);
452 l->l_target_cpu = NULL;
453 } else {
454 lwp_setlock(l, spc->spc_mutex);
455 }
456 sched_enqueue(l, true);
457 } else {
458 KASSERT(tci == NULL);
459 l->l_stat = LSIDL;
460 }
461 } else {
462 /* Lock the runqueue */
463 spc_lock(ci);
464 }
465
466 /*
467 * Let sched_nextlwp() select the LWP to run the CPU next.
468 * If no LWP is runnable, select the idle LWP.
469 *
470 * Note that spc_lwplock might not necessary be held, and
471 * new thread would be unlocked after setting the LWP-lock.
472 */
473 if (newl == NULL) {
474 newl = sched_nextlwp();
475 if (newl != NULL) {
476 sched_dequeue(newl);
477 KASSERT(lwp_locked(newl, spc->spc_mutex));
478 newl->l_stat = LSONPROC;
479 newl->l_cpu = ci;
480 newl->l_flag |= LW_RUNNING;
481 lwp_setlock(newl, spc->spc_lwplock);
482 } else {
483 newl = ci->ci_data.cpu_idlelwp;
484 newl->l_stat = LSONPROC;
485 newl->l_flag |= LW_RUNNING;
486 }
487 /*
488 * Only clear want_resched if there are no
489 * pending (slow) software interrupts.
490 */
491 ci->ci_want_resched = ci->ci_data.cpu_softints;
492 spc->spc_flags &= ~SPCF_SWITCHCLEAR;
493 spc->spc_curpriority = lwp_eprio(newl);
494 }
495
496 /* Items that must be updated with the CPU locked. */
497 if (!returning) {
498 /* Update the new LWP's start time. */
499 newl->l_stime = bt;
500
501 /*
502 * ci_curlwp changes when a fast soft interrupt occurs.
503 * We use cpu_onproc to keep track of which kernel or
504 * user thread is running 'underneath' the software
505 * interrupt. This is important for time accounting,
506 * itimers and forcing user threads to preempt (aston).
507 */
508 ci->ci_data.cpu_onproc = newl;
509 }
510
511 if (l != newl) {
512 struct lwp *prevlwp;
513
514 /* Release all locks, but leave the current LWP locked */
515 if (l->l_mutex == l->l_cpu->ci_schedstate.spc_mutex) {
516 /*
517 * In case of migration, drop the local runqueue
518 * lock, thread is on other runqueue now.
519 */
520 if (__predict_false(tci != NULL))
521 spc_unlock(ci);
522 /*
523 * Drop spc_lwplock, if the current LWP has been moved
524 * to the run queue (it is now locked by spc_mutex).
525 */
526 mutex_spin_exit(spc->spc_lwplock);
527 } else {
528 /*
529 * Otherwise, drop the spc_mutex, we are done with the
530 * run queues.
531 */
532 mutex_spin_exit(spc->spc_mutex);
533 KASSERT(tci == NULL);
534 }
535
536 /*
537 * Mark that context switch is going to be perfomed
538 * for this LWP, to protect it from being switched
539 * to on another CPU.
540 */
541 KASSERT(l->l_ctxswtch == 0);
542 l->l_ctxswtch = 1;
543 l->l_ncsw++;
544 l->l_flag &= ~LW_RUNNING;
545
546 /*
547 * Increase the count of spin-mutexes before the release
548 * of the last lock - we must remain at IPL_SCHED during
549 * the context switch.
550 */
551 oldspl = MUTEX_SPIN_OLDSPL(ci);
552 ci->ci_mtx_count--;
553 lwp_unlock(l);
554
555 /* Count the context switch on this CPU. */
556 ci->ci_data.cpu_nswtch++;
557
558 /* Update status for lwpctl, if present. */
559 if (l->l_lwpctl != NULL)
560 l->l_lwpctl->lc_curcpu = LWPCTL_CPU_NONE;
561
562 /*
563 * Save old VM context, unless a soft interrupt
564 * handler is blocking.
565 */
566 if (!returning)
567 pmap_deactivate(l);
568
569 /*
570 * We may need to spin-wait for if 'newl' is still
571 * context switching on another CPU.
572 */
573 if (newl->l_ctxswtch != 0) {
574 u_int count;
575 count = SPINLOCK_BACKOFF_MIN;
576 while (newl->l_ctxswtch)
577 SPINLOCK_BACKOFF(count);
578 }
579
580 /* Switch to the new LWP.. */
581 prevlwp = cpu_switchto(l, newl, returning);
582 ci = curcpu();
583
584 /*
585 * Switched away - we have new curlwp.
586 * Restore VM context and IPL.
587 */
588 pmap_activate(l);
589 if (prevlwp != NULL) {
590 /* Normalize the count of the spin-mutexes */
591 ci->ci_mtx_count++;
592 /* Unmark the state of context switch */
593 membar_exit();
594 prevlwp->l_ctxswtch = 0;
595 }
596 splx(oldspl);
597
598 /* Update status for lwpctl, if present. */
599 if (l->l_lwpctl != NULL) {
600 l->l_lwpctl->lc_curcpu = (int)cpu_index(ci);
601 l->l_lwpctl->lc_pctr++;
602 }
603
604 retval = 1;
605 } else {
606 /* Nothing to do - just unlock and return. */
607 KASSERT(tci == NULL);
608 spc_unlock(ci);
609 lwp_unlock(l);
610 retval = 0;
611 }
612
613 KASSERT(l == curlwp);
614 KASSERT(l->l_stat == LSONPROC);
615 KASSERT(l->l_cpu == ci);
616
617 /*
618 * XXXSMP If we are using h/w performance counters, restore context.
619 */
620 #if PERFCTRS
621 if (PMC_ENABLED(l->l_proc)) {
622 pmc_restore_context(l->l_proc);
623 }
624 #endif
625 SYSCALL_TIME_WAKEUP(l);
626 LOCKDEBUG_BARRIER(NULL, 1);
627
628 return retval;
629 }
630
631 /*
632 * Change process state to be runnable, placing it on the run queue if it is
633 * in memory, and awakening the swapper if it isn't in memory.
634 *
635 * Call with the process and LWP locked. Will return with the LWP unlocked.
636 */
637 void
638 setrunnable(struct lwp *l)
639 {
640 struct proc *p = l->l_proc;
641 struct cpu_info *ci;
642 sigset_t *ss;
643
644 KASSERT((l->l_flag & LW_IDLE) == 0);
645 KASSERT(mutex_owned(&p->p_smutex));
646 KASSERT(lwp_locked(l, NULL));
647 KASSERT(l->l_mutex != l->l_cpu->ci_schedstate.spc_mutex);
648
649 switch (l->l_stat) {
650 case LSSTOP:
651 /*
652 * If we're being traced (possibly because someone attached us
653 * while we were stopped), check for a signal from the debugger.
654 */
655 if ((p->p_slflag & PSL_TRACED) != 0 && p->p_xstat != 0) {
656 if ((sigprop[p->p_xstat] & SA_TOLWP) != 0)
657 ss = &l->l_sigpend.sp_set;
658 else
659 ss = &p->p_sigpend.sp_set;
660 sigaddset(ss, p->p_xstat);
661 signotify(l);
662 }
663 p->p_nrlwps++;
664 break;
665 case LSSUSPENDED:
666 l->l_flag &= ~LW_WSUSPEND;
667 p->p_nrlwps++;
668 cv_broadcast(&p->p_lwpcv);
669 break;
670 case LSSLEEP:
671 KASSERT(l->l_wchan != NULL);
672 break;
673 default:
674 panic("setrunnable: lwp %p state was %d", l, l->l_stat);
675 }
676
677 /*
678 * If the LWP was sleeping interruptably, then it's OK to start it
679 * again. If not, mark it as still sleeping.
680 */
681 if (l->l_wchan != NULL) {
682 l->l_stat = LSSLEEP;
683 /* lwp_unsleep() will release the lock. */
684 lwp_unsleep(l);
685 return;
686 }
687
688 /*
689 * If the LWP is still on the CPU, mark it as LSONPROC. It may be
690 * about to call mi_switch(), in which case it will yield.
691 */
692 if ((l->l_flag & LW_RUNNING) != 0) {
693 l->l_stat = LSONPROC;
694 l->l_slptime = 0;
695 lwp_unlock(l);
696 return;
697 }
698
699 /*
700 * Look for a CPU to run.
701 * Set the LWP runnable.
702 */
703 ci = sched_takecpu(l);
704 l->l_cpu = ci;
705 if (l->l_mutex != l->l_cpu->ci_schedstate.spc_mutex) {
706 lwp_unlock_to(l, ci->ci_schedstate.spc_mutex);
707 lwp_lock(l);
708 }
709 sched_setrunnable(l);
710 l->l_stat = LSRUN;
711 l->l_slptime = 0;
712
713 /*
714 * If thread is swapped out - wake the swapper to bring it back in.
715 * Otherwise, enter it into a run queue.
716 */
717 if (l->l_flag & LW_INMEM) {
718 sched_enqueue(l, false);
719 resched_cpu(l);
720 lwp_unlock(l);
721 } else {
722 lwp_unlock(l);
723 uvm_kick_scheduler();
724 }
725 }
726
727 /*
728 * suspendsched:
729 *
730 * Convert all non-L_SYSTEM LSSLEEP or LSRUN LWPs to LSSUSPENDED.
731 */
732 void
733 suspendsched(void)
734 {
735 CPU_INFO_ITERATOR cii;
736 struct cpu_info *ci;
737 struct lwp *l;
738 struct proc *p;
739
740 /*
741 * We do this by process in order not to violate the locking rules.
742 */
743 mutex_enter(&proclist_lock);
744 PROCLIST_FOREACH(p, &allproc) {
745 mutex_enter(&p->p_smutex);
746
747 if ((p->p_flag & PK_SYSTEM) != 0) {
748 mutex_exit(&p->p_smutex);
749 continue;
750 }
751
752 p->p_stat = SSTOP;
753
754 LIST_FOREACH(l, &p->p_lwps, l_sibling) {
755 if (l == curlwp)
756 continue;
757
758 lwp_lock(l);
759
760 /*
761 * Set L_WREBOOT so that the LWP will suspend itself
762 * when it tries to return to user mode. We want to
763 * try and get to get as many LWPs as possible to
764 * the user / kernel boundary, so that they will
765 * release any locks that they hold.
766 */
767 l->l_flag |= (LW_WREBOOT | LW_WSUSPEND);
768
769 if (l->l_stat == LSSLEEP &&
770 (l->l_flag & LW_SINTR) != 0) {
771 /* setrunnable() will release the lock. */
772 setrunnable(l);
773 continue;
774 }
775
776 lwp_unlock(l);
777 }
778
779 mutex_exit(&p->p_smutex);
780 }
781 mutex_exit(&proclist_lock);
782
783 /*
784 * Kick all CPUs to make them preempt any LWPs running in user mode.
785 * They'll trap into the kernel and suspend themselves in userret().
786 */
787 for (CPU_INFO_FOREACH(cii, ci)) {
788 spc_lock(ci);
789 cpu_need_resched(ci, RESCHED_IMMED);
790 spc_unlock(ci);
791 }
792 }
793
794 /*
795 * sched_unsleep:
796 *
797 * The is called when the LWP has not been awoken normally but instead
798 * interrupted: for example, if the sleep timed out. Because of this,
799 * it's not a valid action for running or idle LWPs.
800 */
801 static void
802 sched_unsleep(struct lwp *l)
803 {
804
805 lwp_unlock(l);
806 panic("sched_unsleep");
807 }
808
809 void
810 resched_cpu(struct lwp *l)
811 {
812 struct cpu_info *ci;
813
814 /*
815 * XXXSMP
816 * Since l->l_cpu persists across a context switch,
817 * this gives us *very weak* processor affinity, in
818 * that we notify the CPU on which the process last
819 * ran that it should try to switch.
820 *
821 * This does not guarantee that the process will run on
822 * that processor next, because another processor might
823 * grab it the next time it performs a context switch.
824 *
825 * This also does not handle the case where its last
826 * CPU is running a higher-priority process, but every
827 * other CPU is running a lower-priority process. There
828 * are ways to handle this situation, but they're not
829 * currently very pretty, and we also need to weigh the
830 * cost of moving a process from one CPU to another.
831 */
832 ci = l->l_cpu;
833 if (lwp_eprio(l) > ci->ci_schedstate.spc_curpriority)
834 cpu_need_resched(ci, 0);
835 }
836
837 static void
838 sched_changepri(struct lwp *l, pri_t pri)
839 {
840
841 KASSERT(lwp_locked(l, NULL));
842
843 if (l->l_stat == LSRUN && (l->l_flag & LW_INMEM) != 0) {
844 KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
845 sched_dequeue(l);
846 l->l_priority = pri;
847 sched_enqueue(l, false);
848 } else {
849 l->l_priority = pri;
850 }
851 resched_cpu(l);
852 }
853
854 static void
855 sched_lendpri(struct lwp *l, pri_t pri)
856 {
857
858 KASSERT(lwp_locked(l, NULL));
859
860 if (l->l_stat == LSRUN && (l->l_flag & LW_INMEM) != 0) {
861 KASSERT(lwp_locked(l, l->l_cpu->ci_schedstate.spc_mutex));
862 sched_dequeue(l);
863 l->l_inheritedprio = pri;
864 sched_enqueue(l, false);
865 } else {
866 l->l_inheritedprio = pri;
867 }
868 resched_cpu(l);
869 }
870
871 struct lwp *
872 syncobj_noowner(wchan_t wchan)
873 {
874
875 return NULL;
876 }
877
878
879 /* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
880 fixpt_t ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
881
882 /*
883 * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
884 * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
885 * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
886 *
887 * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
888 * 1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
889 *
890 * If you dont want to bother with the faster/more-accurate formula, you
891 * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
892 * (more general) method of calculating the %age of CPU used by a process.
893 */
894 #define CCPU_SHIFT (FSHIFT + 1)
895
896 /*
897 * sched_pstats:
898 *
899 * Update process statistics and check CPU resource allocation.
900 * Call scheduler-specific hook to eventually adjust process/LWP
901 * priorities.
902 */
903 /* ARGSUSED */
904 void
905 sched_pstats(void *arg)
906 {
907 struct rlimit *rlim;
908 struct lwp *l;
909 struct proc *p;
910 int sig, clkhz;
911 long runtm;
912
913 sched_pstats_ticks++;
914
915 mutex_enter(&proclist_lock);
916 PROCLIST_FOREACH(p, &allproc) {
917 /*
918 * Increment time in/out of memory and sleep time (if
919 * sleeping). We ignore overflow; with 16-bit int's
920 * (remember them?) overflow takes 45 days.
921 */
922 mutex_enter(&p->p_smutex);
923 mutex_spin_enter(&p->p_stmutex);
924 runtm = p->p_rtime.sec;
925 LIST_FOREACH(l, &p->p_lwps, l_sibling) {
926 if ((l->l_flag & LW_IDLE) != 0)
927 continue;
928 lwp_lock(l);
929 runtm += l->l_rtime.sec;
930 l->l_swtime++;
931 sched_pstats_hook(l);
932 lwp_unlock(l);
933
934 /*
935 * p_pctcpu is only for ps.
936 */
937 l->l_pctcpu = (l->l_pctcpu * ccpu) >> FSHIFT;
938 if (l->l_slptime < 1) {
939 clkhz = stathz != 0 ? stathz : hz;
940 #if (FSHIFT >= CCPU_SHIFT)
941 l->l_pctcpu += (clkhz == 100) ?
942 ((fixpt_t)l->l_cpticks) <<
943 (FSHIFT - CCPU_SHIFT) :
944 100 * (((fixpt_t) p->p_cpticks)
945 << (FSHIFT - CCPU_SHIFT)) / clkhz;
946 #else
947 l->l_pctcpu += ((FSCALE - ccpu) *
948 (l->l_cpticks * FSCALE / clkhz)) >> FSHIFT;
949 #endif
950 l->l_cpticks = 0;
951 }
952 }
953 p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
954 mutex_spin_exit(&p->p_stmutex);
955
956 /*
957 * Check if the process exceeds its CPU resource allocation.
958 * If over max, kill it.
959 */
960 rlim = &p->p_rlimit[RLIMIT_CPU];
961 sig = 0;
962 if (runtm >= rlim->rlim_cur) {
963 if (runtm >= rlim->rlim_max)
964 sig = SIGKILL;
965 else {
966 sig = SIGXCPU;
967 if (rlim->rlim_cur < rlim->rlim_max)
968 rlim->rlim_cur += 5;
969 }
970 }
971 mutex_exit(&p->p_smutex);
972 if (sig) {
973 mutex_enter(&proclist_mutex);
974 psignal(p, sig);
975 mutex_exit(&proclist_mutex);
976 }
977 }
978 mutex_exit(&proclist_lock);
979 uvm_meter();
980 cv_wakeup(&lbolt);
981 callout_schedule(&sched_pstats_ch, hz);
982 }
983
984 void
985 sched_init(void)
986 {
987
988 cv_init(&lbolt, "lbolt");
989 callout_init(&sched_pstats_ch, CALLOUT_MPSAFE);
990 callout_setfunc(&sched_pstats_ch, sched_pstats, NULL);
991 sched_setup();
992 sched_pstats(NULL);
993 }
994