Kernel 启动流程梳理

Posted Li-Yongjun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Kernel 启动流程梳理相关的知识,希望对你有一定的参考价值。

内核生命周期

uboot 打印完 Starting kernel . . .,就完成了自己的使命,控制权便交给了 kernel 的第一条指令,也就是下面这个函数
init/main.c

asmlinkage __visible void __init start_kernel(void)

	...
	rest_init();

start_kernel 相当于内核的 main 函数,内核的生命周期就是从执行这个函数的第一条语句开始的,直到最后一个函数 reset_init(),内核将不再从这个函数中返回,而是陷入这个函数里面的一个 while(1) 死循环,这个死循环被作为 idle 进程,也就是 0 号进程

所以,内核的生命周期,就是一个完整的 start_kernel 函数。始于 start_kernel 函数的第一条语句,停留在最后的死循环。

init 进程

kernel 会创建众多内核线程,来持续致力于内存、磁盘、CPU 的管理,其中有两个内核线程比较重要,需要我们重点讲解,那就是 1 号内核线程 kernel_init 和 2 号内核线程 kthreadd。1 号内核线程最终会被用户的第一个进程 init 代替,也就成了 1 号进程。如下:

# ps
PID   USER     COMMAND
    1 root     init
    2 root     [kthreadd]
    3 root     [rcu_gp]
    4 root     [rcu_par_gp]
    7 root     [kworker/u4:0-ev]
    8 root     [mm_percpu_wq]
    9 root     [ksoftirqd/0]
...

COMMAND 这一列,带中括号的是内核线程,不带中括号的是用户进程。从 PID 统一编址就可以看出,它俩地位是一样的。
下面我们深入分析一下从 start_kernel 到最终运行 init 进程,kernel 都经历了什么

打印

添加打印,是分析流程的好方法。

asmlinkage __visible void __init start_kernel(void)

	char *command_line;
	char *after_dashes;

	set_task_stack_end_magic(&init_task);
	smp_setup_processor_id();
	debug_objects_early_init();

	cgroup_init_early();

	local_irq_disable();
	early_boot_irqs_disabled = true;

	/*
	 * Interrupts are still disabled. Do necessary setups, then
	 * enable them.
	 */
	boot_cpu_init();
	page_address_init();
	pr_notice("%s", linux_banner);
	setup_arch(&command_line);
	/*
	 * Set up the the initial canary and entropy after arch
	 * and after adding latent and command line entropy.
	 */
	add_latent_entropy();
	add_device_randomness(command_line, strlen(command_line));
	boot_init_stack_canary();
	mm_init_cpumask(&init_mm);
	setup_command_line(command_line);
	setup_nr_cpu_ids();
	setup_per_cpu_areas();
	smp_prepare_boot_cpu();	/* arch-specific boot-cpu hooks */
	boot_cpu_hotplug_init();

	build_all_zonelists(NULL);
	page_alloc_init();

	pr_notice("Kernel command line: %s\\n", boot_command_line);
	parse_early_param();
	after_dashes = parse_args("Booting kernel",
				  static_command_line, __start___param,
				  __stop___param - __start___param,
				  -1, -1, NULL, &unknown_bootoption);
	if (!IS_ERR_OR_NULL(after_dashes))
		parse_args("Setting init args", after_dashes, NULL, 0, -1, -1,
			   NULL, set_init_arg);

	jump_label_init();

	/*
	 * These use large bootmem allocations and must precede
	 * kmem_cache_init()
	 */
	setup_log_buf(0);
	vfs_caches_init_early();
	sort_main_extable();
	trap_init();
	mm_init();

	ftrace_init();

	/* trace_printk can be enabled here */
	early_trace_init();

	/*
	 * Set up the scheduler prior starting any interrupts (such as the
	 * timer interrupt). Full topology setup happens at smp_init()
	 * time - but meanwhile we still have a functioning scheduler.
	 */
	sched_init();
	/*
	 * Disable preemption - early bootup scheduling is extremely
	 * fragile until we cpu_idle() for the first time.
	 */
	preempt_disable();
	if (WARN(!irqs_disabled(),
		 "Interrupts were enabled *very* early, fixing it\\n"))
		local_irq_disable();
	radix_tree_init();

	/*
	 * Set up housekeeping before setting up workqueues to allow the unbound
	 * workqueue to take non-housekeeping into account.
	 */
	housekeeping_init();

	/*
	 * Allow workqueue creation and work item queueing/cancelling
	 * early.  Work item execution depends on kthreads and starts after
	 * workqueue_init().
	 */
	workqueue_init_early();

	rcu_init();

	/* Trace events are available after this */
	trace_init();

	if (initcall_debug)
		initcall_debug_enable();

	context_tracking_init();
	/* init some links before init_ISA_irqs() */
	early_irq_init();
	init_IRQ();
	tick_init();
	rcu_init_nohz();
	init_timers();
	hrtimers_init();
	softirq_init();
	timekeeping_init();
	time_init();
	sched_clock_postinit();
	printk_safe_init();
	perf_event_init();
	profile_init();
	call_function_init();
	WARN(!irqs_disabled(), "Interrupts were enabled early\\n");
	early_boot_irqs_disabled = false;
	local_irq_enable();

	kmem_cache_init_late();

	/*
	 * HACK ALERT! This is early. We're enabling the console before
	 * we've done PCI setups etc, and console_init() must be aware of
	 * this. But we do want output early, in case something goes wrong.
	 */
	console_init();
printk("## start_kernel() --> console_init()\\n");
	if (panic_later)
		panic("Too many boot %s vars at `%s'", panic_later,
		      panic_param);

	lockdep_info();

	/*
	 * Need to run this when irqs are enabled, because it wants
	 * to self-test [hard/soft]-irqs on/off lock inversion bugs
	 * too:
	 */
	locking_selftest();

	/*
	 * This needs to be called before any devices perform DMA
	 * operations that might use the SWIOTLB bounce buffers. It will
	 * mark the bounce buffers as decrypted so that their usage will
	 * not cause "plain-text" data to be decrypted when accessed.
	 */
	mem_encrypt_init();

#ifdef CONFIG_BLK_DEV_INITRD
	if (initrd_start && !initrd_below_start_ok &&
	    page_to_pfn(virt_to_page((void *)initrd_start)) < min_low_pfn) 
		pr_crit("initrd overwritten (0x%08lx < 0x%08lx) - disabling it.\\n",
		    page_to_pfn(virt_to_page((void *)initrd_start)),
		    min_low_pfn);
		initrd_start = 0;
	
#endif
	page_ext_init();
	kmemleak_init();
	debug_objects_mem_init();
	setup_per_cpu_pageset();
	numa_policy_init();
	acpi_early_init();
	if (late_time_init)
		late_time_init();
	calibrate_delay();
	pid_idr_init();
	anon_vma_init();
#ifdef CONFIG_X86
	if (efi_enabled(EFI_RUNTIME_SERVICES))
		efi_enter_virtual_mode();
#endif
	thread_stack_cache_init();
	cred_init();
	fork_init();
	proc_caches_init();
	uts_ns_init();
	buffer_init();
	key_init();
	security_init();
	dbg_late_init();
	vfs_caches_init();
	pagecache_init();
	signals_init();
	seq_file_init();
	proc_root_init();
	nsfs_init();
	cpuset_init();
	cgroup_init();
	taskstats_init_early();
	delayacct_init();

	check_bugs();

	acpi_subsystem_init();
	arch_post_acpi_subsys_init();
	sfi_init_late();

	if (efi_enabled(EFI_RUNTIME_SERVICES)) 
		efi_free_boot_services();
	
printk("## run rest_init()\\n");
	/* Do the rest non-__init'ed, we're now alive */
	rest_init();
printk("## after rest_init()\\n");

一开始尝试在函数刚开始就添加 printk 打印,结果发现添加完 printk 后内核起不来,最后保守起见,在 131 行 console_init(); 后才开始添加打印。


Starting kernel ...

[    0.000000] Booting Linux on physical CPU 0x0
[    0.000000] Linux version 4.18.12 (liyongjun@Box) (gcc version 9.3.0 (Buildroot 2021.05)) #14 SMP Thu Nov 25 00:37:30 CST 2021
[    0.000000] CPU: ARMv7 Processor [410fc074] revision 4 (ARMv7), cr=10c5387d
[    0.000000] CPU: div instructions available: patching division code
[    0.000000] CPU: PIPT / VIPT nonaliasing data cache, VIPT aliasing instruction cache
[    0.000000] OF: fdt: Machine model: LeMaker Banana Pi
[    0.000000] Memory policy: Data cache writealloc
[    0.000000] cma: Reserved 16 MiB at 0x7ec00000
[    0.000000] psci: probing for conduit method from DT.
[    0.000000] psci: Using PSCI v0.1 Function IDs from DT
[    0.000000] random: get_random_bytes called from start_kernel+0xa0/0x430 with crng_init=0
[    0.000000] percpu: Embedded 16 pages/cpu @(ptrval) s34444 r8192 d22900 u65536
[    0.000000] Built 1 zonelists, mobility grouping on.  Total pages: 260202
[    0.000000] Kernel command line: console=ttyS0,57600 earlyprintk root=/dev/mmcblk0p2 rootwait
[    0.000000] Dentry cache hash table entries: 131072 (order: 7, 524288 bytes)
[    0.000000] Inode-cache hash table entries: 65536 (order: 6, 262144 bytes)
[    0.000000] Memory: 1011460K/1046952K available (6144K kernel code, 418K rwdata, 1524K rodata, 1024K init, 240K bss, 19108K reserved, 16384K cma-reserved, 244136K highmem)
[    0.000000] Virtual kernel memory layout:
[    0.000000]     vector  : 0xffff0000 - 0xffff1000   (   4 kB)
[    0.000000]     fixmap  : 0xffc00000 - 0xfff00000   (3072 kB)
[    0.000000]     vmalloc : 0xf0800000 - 0xff800000   ( 240 MB)
[    0.000000]     lowmem  : 0xc0000000 - 0xf0000000   ( 768 MB)
[    0.000000]     pkmap   : 0xbfe00000 - 0xc0000000   (   2 MB)
[    0.000000]     modules : 0xbf000000 - 0xbfe00000   (  14 MB)
[    0.000000]       .text : 0x(ptrval) - 0x(ptrval)   (7136 kB)
[    0.000000]       .init : 0x(ptrval) - 0x(ptrval)   (1024 kB)
[    0.000000]       .data : 0x(ptrval) - 0x(ptrval)   ( 419 kB)
[    0.000000]        .bss : 0x(ptrval) - 0x(ptrval)   ( 241 kB)
[    0.000000] SLUB: HWalign=64, Order=0-3, MinObjects=0, CPUs=2, Nodes=1
[    0.000000] Hierarchical RCU implementation.
[    0.000000]  RCU restricting CPUs from NR_CPUS=8 to nr_cpu_ids=2.
[    0.000000] RCU: Adjusting geometry for rcu_fanout_leaf=16, nr_cpu_ids=2
[    0.000000] NR_IRQS: 16, nr_irqs: 16, preallocated irqs: 16
[    0.000000] GIC: Using split EOI/Deactivate mode
[    0.000000] arch_timer: cp15 timer(s) running at 24.00MHz (phys).
[    0.000000] clocksource: arch_sys_counter: mask: 0xffffffffffffff max_cycles: 0x588fe9dc0, max_idle_ns: 440795202592 ns
[    0.000007] sched_clock: 56 bits at 24MHz, resolution 41ns, wraps every 4398046511097ns
[    0.000021] Switching to timer-based delay loop, resolution 41ns
[    0.000334] clocksource: timer: mask: 0xffffffff max_cycles: 0xffffffff, max_idle_ns: 79635851949 ns
[    0.000586] clocksource: hstimer: mask: 0xffffffff max_cycles: 0xffffffff, max_idle_ns: 6370868154 ns
[    0.000822] Console: colour dummy device 80x30
[    0.000844] ## start_kernel() --> console_init()	// 132 行的打印

可是,发现在 console_init() 之前就有不少打印了,这个地方还是有些不解。猜测要么是在 console_init() 之前就已经可以打印了;要么是在 console_init() 之前先将打印缓存着,等初始化之后再打印。这点以后再研究吧。先插个眼👁。

接着看打印

[    0.000844] ## start_kernel() --> console_init()
[    0.000872] Calibrating delay loop (skipped), value calculated using timer frequency.. 48.00 BogoMIPS (lpj=240000)
[    0.000886] pid_max: default: 32768 minimum: 301
[    0.001054] Mount-cache hash table entries: 2048 (order: 1, 8192 bytes)
[    0.001070] Mountpoint-cache hash table entries: 2048 (order: 1, 8192 bytes)
[    0.001727] CPU: Testing write buffer coherency: ok
[    0.001779] ## run rest_init()

从 133 行到 206 行,代码不少,打印却只有寥寥 5 行。少就说明不重要,那就不分析了,哈哈😁。
看下面的代码,乖乖,就剩一句了:rest_init();,并且第 210 行的 printk 等到系统完全起来都没有打印,说明 rest_init() 就没返回。看来是个扛把子。

static noinline void __ref rest_init(void)

	struct task_struct *tsk;
	int pid;
printk("## rcu_scheduler_starting()\\n");
	rcu_scheduler_starting();
	/*
	 * 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.
	 */
	pid = kernel_thread(kernel_init, NULL, CLONE_FS);
	/*
	 * Pin init on the boot CPU. Task migration is not properly working
	 * until sched_init_smp() has been run. It will set the allowed
	 * CPUs for init to the non isolated CPUs.
	 */
	rcu_read_lock();
	tsk = find_task_by_pid_ns(pid, &init_pid_ns);
	set_cpus_allowed_ptr(tsk, cpumask_of(smp_processor_id()));
	rcu_read_unlock();
printk("## bb\\n");
	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();
printk("## cc\\n");
	/*
	 * Enable might_sleep() and smp_processor_id() checks.
	 * They cannot be enabled earlier because with CONFIG_PREEMPT=y
	 * kernel_thread() would trigger might_sleep() splats. With
	 * CONFIG_PREEMPT_VOLUNTARY=y the init task might have scheduled
	 * already, but it's stuck on the kthreadd_done completion.
	 */
	system_state = SYSTEM_SCHEDULING;
printk("## dd\\n");
	complete(&kthreadd_done);

	/*
	 * The boot idle thread must execute schedule()
	 * at least once to get things moving:
	 */
printk("## ee\\n");
	schedule_preempt_disabled();
printk("## ff\\n");
	/* Call into cpu_idle with preempt disabled */
	cpu_startup_entry(CPUHP_ONLINE);
// printk("## ff\\n");

对应打印如下:

[    0.001779] ## run rest_init()
[    0.001786] ## rcu_scheduler_starting()
[    0.002030] ## bb
[    0.002089] ## cc
[    0.002097] ## dd
[    0.002104] ## ee
[    0.002150] ## kernel_init()
[    0.002199] /cpus/cpu@0 missing clock-frequency property
[    0.002214] /cpus/cpu@1 missing clock-frequency property
[    0.002228] CPU0: thread -1, cpu 0, socket 0, mpidr 80000000
[    0.002799] Setting up static identity map for 0x40100000 - 0x40100060
[    0.002972] Hierarchical SRCU implementation.
[    0.003776] smp: Bringing up secondary CPUs ...
[    0.014335] ## ff

打印了 kernel_init(),是因为调用了 schedule_preempt_disabled(),其内部调用了 schedule() 执行进程切换,进入睡眠。当然,在当前进程被唤醒时,程序也是从这个断点开始运行。

void __sched schedule_preempt_disabled(void)

	sched_preempt_enable_no_resched();
	schedule();
	preempt_disable();

执行进程切换后,kernel_init() 才有机会运行

static int __ref kernel_init(void *unused)

	int ret;
printk("## kernel_init()\\n");
	kernel_init_freeable();
	/* need to finish all async __init code before freeing the memory */
	async_synchronize_full();

	ftrace_free_init_mem();

	jump_label_invalidate_initmem();
	free_initmem();
printk("## 2.\\n");
	mark_readonly();
printk("## 3.\\n");
	system_state = SYSTEM_RUNNING;
	numa_default_policy();

	rcu_end_inkernel_boot();
printk("## 4.\\n");
	if (ramdisk_execute_command) 
		ret = run_init_process(ramdisk_execute_command);
		if (!ret)
			return 0;
		pr_err("Failed to execute %s (error %d)\\n",
		       ramdisk_execute_command, ret);
	

	/*
	 * We try each of these until one succeeds.
	 *
	 * The Bourne shell can be used instead of init if we are
	 * trying to recover a really broken machine.
	 */
	if (execute_command) 
		ret = run_init_process(execute_command);
		if (!ret)
			return 0;
		panic("Requested init %s failed (error %d).",
		      execute_command, ret);
	
	if (!try_to_run_init_process("/sbin/init") ||
	    !try_to_run_init_process("/etc/init") ||
	    !try_to_run_init_process("/bin/init") ||
	    !try_to_run_init_process("/bin/sh")) 以上是关于Kernel 启动流程梳理的主要内容,如果未能解决你的问题,请参考以下文章

linux启动流程梳理

android 启动流程 相关2 init进程 属性服务

Linux系统移植:Kernel 启动流程

linux系统的启动过程简要分析

11 udp 发送数据的流程梳理

Linux内核启动流程 详解