1 /*- 2 * Copyright (c) 2000, All rights reserved. See /usr/src/COPYRIGHT 3 * 4 * $FreeBSD$ 5 */ 6 7 #include "opt_ktrace.h" 8 9 #include <sys/param.h> 10 #include <sys/systm.h> 11 #include <sys/kernel.h> 12 #include <sys/ktr.h> 13 #include <sys/kthread.h> 14 #include <sys/lock.h> 15 #include <sys/mutex.h> 16 #include <sys/pcpu.h> 17 #include <sys/proc.h> 18 #include <sys/resourcevar.h> 19 #include <sys/sched.h> 20 #include <sys/smp.h> 21 #include <sys/unistd.h> 22 #ifdef KTRACE 23 #include <sys/uio.h> 24 #include <sys/ktrace.h> 25 #endif 26 27 static void idle_setup(void *dummy); 28 SYSINIT(idle_setup, SI_SUB_SCHED_IDLE, SI_ORDER_FIRST, idle_setup, NULL) 29 30 static void idle_proc(void *dummy); 31 32 /* 33 * Setup per-cpu idle process contexts. The AP's shouldn't be running or 34 * accessing their idle processes at this point, so don't bother with 35 * locking. 36 */ 37 static void 38 idle_setup(void *dummy) 39 { 40 #ifdef SMP 41 struct pcpu *pc; 42 #endif 43 struct proc *p; 44 struct thread *td; 45 int error; 46 47 #ifdef SMP 48 SLIST_FOREACH(pc, &cpuhead, pc_allcpu) { 49 error = kthread_create(idle_proc, NULL, &p, 50 RFSTOPPED | RFHIGHPID, 0, "idle: cpu%d", pc->pc_cpuid); 51 pc->pc_idlethread = FIRST_THREAD_IN_PROC(p); 52 if (pc->pc_curthread == NULL) { 53 pc->pc_curthread = pc->pc_idlethread; 54 pc->pc_idlethread->td_critnest = 0; 55 } 56 #else 57 error = kthread_create(idle_proc, NULL, &p, 58 RFSTOPPED | RFHIGHPID, 0, "idle"); 59 PCPU_SET(idlethread, FIRST_THREAD_IN_PROC(p)); 60 #endif 61 if (error) 62 panic("idle_setup: kthread_create error %d\n", error); 63 64 p->p_flag |= P_NOLOAD; 65 p->p_state = PRS_NORMAL; 66 td = FIRST_THREAD_IN_PROC(p); 67 td->td_state = TDS_CAN_RUN; 68 td->td_kse->ke_flags |= KEF_IDLEKSE; 69 #ifdef SMP 70 } 71 #endif 72 } 73 74 /* 75 * idle process context 76 */ 77 static void 78 idle_proc(void *dummy) 79 { 80 #ifdef DIAGNOSTIC 81 int count; 82 #endif 83 struct thread *td; 84 struct proc *p; 85 86 td = curthread; 87 p = td->td_proc; 88 for (;;) { 89 mtx_assert(&Giant, MA_NOTOWNED); 90 91 #ifdef DIAGNOSTIC 92 count = 0; 93 94 while (count >= 0 && sched_runnable() == 0) { 95 #else 96 while (sched_runnable() == 0) { 97 #endif 98 /* 99 * This is a good place to put things to be done in 100 * the background, including sanity checks. 101 */ 102 103 #ifdef DIAGNOSTIC 104 if (count++ < 0) 105 CTR0(KTR_PROC, "idle_proc: timed out waiting" 106 " for a process"); 107 #endif 108 109 #ifdef __i386__ 110 cpu_idle(); 111 #endif 112 } 113 114 mtx_lock_spin(&sched_lock); 115 p->p_stats->p_ru.ru_nvcsw++; 116 td->td_state = TDS_CAN_RUN; 117 mi_switch(); 118 mtx_unlock_spin(&sched_lock); 119 } 120 } 121