Kernel rest_init相关

时间:2023-03-09 19:20:25
Kernel rest_init相关

Linux系统里,有些进程只有kernel部分的代码,即由一个kernel函数进入,在sched的时候,将其与用户进程同等对待。

PID为0的叫swapper或sched进程,对应函数为rest_init

init进程PID为1,

kthreadd进程PID为2,

0号进程,即rest_init主体如下

 static noinline void __init_refok rest_init(void)
{
int pid; rcu_scheduler_starting();
smpboot_thread_init();
/*
* We need to spawn init first so that it obtains pid 1, however
* the init task will end up wanting to create kthreads, which, if
* we schedule it before we create kthreadd, will OOPS.
*/
kernel_thread(kernel_init, NULL, CLONE_FS);
numa_default_policy();
pid = kernel_thread(kthreadd, NULL, CLONE_FS | CLONE_FILES);
rcu_read_lock();
kthreadd_task = find_task_by_pid_ns(pid, &init_pid_ns);
rcu_read_unlock();
complete(&kthreadd_done); /*
* The boot idle thread must execute schedule()
* at least once to get things moving:
*/
init_idle_bootup_task(current);
schedule_preempt_disabled();
/* Call into cpu_idle with preempt disabled */
cpu_startup_entry(CPUHP_ONLINE);

先是rcu_scheduler_starting函数,这个函数的作用是

再是smpboot_thread_init函数,这个函数注册smpboot时候的notifier,响应CPU动作

 static struct notifier_block smpboot_thread_notifier = {
.notifier_call = smpboot_thread_call,
.priority = CPU_PRI_SMPBOOT,
}; void __cpuinit smpboot_thread_init(void)
{
register_cpu_notifier(&smpboot_thread_notifier);
}

然后调用kernel_thread函数fork init进程

 /*
* Create a kernel thread.
*/
pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
{
return do_fork(flags|CLONE_VM|CLONE_UNTRACED, (unsigned long)fn,
(unsigned long)arg, NULL, NULL);
}

do_fork函数被调用

这里有一点要注意,init进程执行的时候要等kerneladd进程执行后才被complete(&kthreadd_done)唤醒,然后真正执行,不然直接调度到init的话会OOPs

numa_default_policy被调用设置内存numa默认策略

然后调用kernel_thread函数fork kthreadd进程

然后用find_task_by_pid_ns(pid, &init_pid_ns)获取kthreadd的task_struct

最后唤醒complete(&kthreadd_done)进程

最后,0号进程,即空闲进程,要让一切跑起来,调用一次schedule