Linux內核啟動流程(簡介)


1. vmlinux.lds

首先分析 Linux 內核的連接腳本文件 arch/arm/kernel/vmlinux.lds,通過鏈接腳本可以找到 Linux 內核的第一行程序是從哪里執行的:
image
第 493 行的 ENTRY 指明了了 Linux 內核入口,入口為 stext,stext 定義在文件arch/arm/kernel/head.S 中 , 因 此 要 分 析 Linux 內核的啟動流程,就得先從文件arch/arm/kernel/head.S 的 stext 處開始分析

2. 內核啟動流程分析

2.1 內核入口stext

stext 是 Linux 內核的入口地址,在文件 arch/arm/kernel/head.S 中有如下所示提示內容
image
如圖可知:如果要啟動Linux,啟動要求如下:

  • 關閉 MMU。
  • 關閉 D-cache。
  • I-Cache 無所謂。
  • r0=0。
  • r1=machine nr(也就是機器 ID)。
  • r2=atags 或者設備樹(dtb)首地址。
    Linux 內核的入口點 stext 其實相當於內核的入口函數,stext 函數內容如下:
    image
    proc_info_list 在文件arch/arm/include/asm/procinfo.h 中的定義如下:
struct proc_info_list {
 unsigned int cpu_val;
 unsigned int cpu_mask;
 unsigned long __cpu_mm_mmu_flags; /* used by head.S */
 unsigned long __cpu_io_mmu_flags; /* used by head.S */
 unsigned long __cpu_flush; /* used by head.S */
 const char *arch_name;
 const char *elf_name;
 unsigned int elf_hwcap;
 const char *cpu_name;
 struct processor *proc;
 struct cpu_tlb_fns *tlb;
 struct cpu_user_fns *user;
 struct cpu_cache_fns *cache;
};

Linux 內核將每種處理器都抽象為一個 proc_info_list 結構體,每種處理器都對應一個procinfo。因此可以通過處理器 ID 來找到對應的 procinfo 結構__lookup_processor_type 函數找到對應處理器的 procinfo 以后會將其保存到 r5 寄存器中
繼續回到源代碼:
image
image

2.2 __mmap_switched函數

image

2.3 start_kernel函數

start_kernel 通過調用眾多的子函數來完成 Linux 啟動之前的一些初始化工作,由於start_kernel 函數里面調用的子函數太多,而這些子函數又很復雜,因此我們簡單的來看一些重要的子函數。精簡並添加注釋后的 start_kernel 函數內容如下:

asmlinkage __visible void __init start_kernel(void)
{
	char *command_line;
	char *after_dashes;

	/*
	 * Need to run as early as possible, to initialize the
	 * lockdep hash:
	 */
	lockdep_init(); //死鎖檢測模塊,兩個Hash表,此函數要盡早執行
	set_task_stack_end_magic(&init_task); //任務棧結束魔術數,用於檢測棧溢出
	smp_setup_processor_id();//跟 SMP 有關(多核處理器),設置處理器 ID
	debug_objects_early_init(); //debug初始化

	/*
	 * Set up the the initial canary ASAP:
	 */
	boot_init_stack_canary(); //棧溢出檢測初始化

	cgroup_init_early(); // cgroup初始化,cgroup用於檢測linux系統資源

	local_irq_disable(); // 關閉當前cpu中斷
	early_boot_irqs_disabled = true; // 

/*
 * Interrupts are still disabled. Do necessary setups, then
 * enable them
 */
	boot_cpu_init(); // CPU有關初始化
	page_address_init(); // 頁地址初始化
	pr_notice("%s", linux_banner); // 打印linux版本號和編譯時間等信息
	setup_arch(&command_line); /* 架構相關的初始化,此函數會解析傳遞進來的
								* ATAGS 或者設備樹(DTB)文件。會根據設備樹里面
								* 的 model 和 compatible 這兩個屬性值來查找
								* Linux 是否支持這個單板。此函數也會獲取設備樹
								* 中 chosen 節點下的 bootargs 屬性值來得到命令
								* 行參數,也就是 uboot 中的 bootargs 環境變量的
								* 值,獲取到的命令行參數會保存到
								*command_line 中。
								*/
	mm_init_cpumask(&init_mm); // 內存相關初始化
	setup_command_line(command_line); // 存儲命令行參數
	setup_nr_cpu_ids(); // 如果是多核,此函數用於獲取CPU核心數量
	setup_per_cpu_areas(); // 設置每個CPU的pre-cpu數據
	smp_prepare_boot_cpu();	 // 

	build_all_zonelists(NULL, NULL); // 建立系統內存頁區鏈表
	page_alloc_init(); // 處理用於CPU熱插拔的頁

	/* 打印命令行信息 */
	pr_notice("Kernel command line: %s\n", boot_command_line); // 
	parse_early_param(); //  解釋命令行中console參數
	after_dashes = parse_args("Booting kernel", // 
				  static_command_line, __start___param,
				  __stop___param - __start___param,
				  -1, -1, &unknown_bootoption);
	if (!IS_ERR_OR_NULL(after_dashes)) // 
		parse_args("Setting init args", after_dashes, NULL, 0, -1, -1,
			   set_init_arg); // 

	jump_label_init(); // 

	/*
	 * These use large bootmem allocations and must precede
	 * kmem_cache_init()
	 */
	setup_log_buf(0); // 設置log使用的緩沖區
	pidhash_init(); // 構建PID哈希表
	vfs_caches_init_early(); // 預先初始化 vfs(虛擬文件系統)的目錄項和索引節點緩存
	sort_main_extable(); // 定義內核異常列表
	trap_init(); // 完成對系統保留中斷向量的初始化
	mm_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(); // 沒關閉就關閉中斷
	idr_init_cache(); // IDR 初始化,IDR 是 Linux 內核的整數管理機制,也就是將一個整數 ID 與一個指針關聯起來
	rcu_init(); //  初始化 RCU,RCU 全稱為 Read Copy Update(讀-拷貝修改

	/* trace_printk() and trace points may be used after this */
	trace_init(); // 跟蹤調試相關初始化

	context_tracking_init(); // 
	radix_tree_init(); //  基數樹相關數據結構初始化
	/* init some links before init_ISA_irqs() */
	early_irq_init(); // 初始中斷相關初始化,主要是注冊 irq_desc 結構體變量,因為 Linux 內核使用 irq_desc 來描述一個中斷。
	init_IRQ(); // 中斷初始化
	tick_init(); //  tick 初始化
	rcu_init_nohz(); // 
	init_timers(); // 初始化定時器
	hrtimers_init(); // 初始化高精度定時器
	softirq_init(); // 初始化軟中端
	timekeeping_init(); // 
	time_init(); // 初始化系統時間
	sched_clock_postinit(); // 
	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(); // slab 初始化,slab 是 Linux 內存分配器

	/*
	 * 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 打印的信息都存放
 						* 緩沖區中,並沒有打印出來。只有調用此函數
 						* 初始化控制台以后才能在控制台上打印信息。
						*/
	if (panic_later)
		panic("Too many boot %s vars at `%s'", panic_later,
		      panic_param); // 

	lockdep_info(); //  如果定義了宏 CONFIG_LOCKDEP,那么此函數打印一些信息。

	/*
	 * 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(); // 鎖自測

#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(); // 
	debug_objects_mem_init(); // 
	kmemleak_init(); //  kmemleak 初始化,kmemleak 用於檢查內存泄漏
	setup_per_cpu_pageset(); // 
	numa_policy_init(); // 
	if (late_time_init)
		late_time_init(); // 
	sched_clock_init(); // 
	calibrate_delay(); // 測定 BogoMIPS 值,可以通過 BogoMIPS 來判斷 CPU 的性能 BogoMIPS 設置越大,說明 CPU 性能越好。
	pidmap_init(); // PID 位圖初始化
	anon_vma_init(); // 生成 anon_vma slab 緩存
	acpi_early_init(); // 
#ifdef CONFIG_X86
	if (efi_enabled(EFI_RUNTIME_SERVICES))
		efi_enter_virtual_mode();
#endif
#ifdef CONFIG_X86_ESPFIX64
	/* Should be run before the first non-init thread is created */
	init_espfix_bsp();
#endif
	thread_info_cache_init(); // 
	cred_init(); // 為對象的每個用於賦予資格(憑證)
	fork_init(); // 初始化一些結構體以使用 fork 函數
	proc_caches_init(); // 給各種資源管理結構分配緩存
	buffer_init(); //  初始化緩沖緩存
	key_init(); // 初始化秘鑰
	security_init(); // 安全相關初始化
	dbg_late_init(); // 
	vfs_caches_init(totalram_pages); // 為 VFS 創建緩存
	signals_init(); // 初始化信號
	/* rootfs populating might need page-writeback */
	page_writeback_init(); // 頁回寫初始化
	proc_root_init(); // 注冊並掛載proc文件系統
	nsfs_init(); // 
	cpuset_init(); //  初始化 cpuset,cpuset 是將 CPU 和內存資源以邏輯性和層次性集成的一種機制,是 cgroup 使用的子系統之一
	cgroup_init(); // 初始化 cgroup
	taskstats_init_early(); // 進程狀態初始化
	delayacct_init(); // 

	check_bugs(); //  檢查寫緩沖一致性

	acpi_subsystem_init(); // 
	sfi_init_late(); // 

	if (efi_enabled(EFI_RUNTIME_SERVICES)) {
		efi_late_init(); // 
		efi_free_boot_services(); // 
	}

	ftrace_init(); // 

	/* Do the rest non-__init'ed, we're now alive */
	rest_init(); // 
}

函數的最后調用了reset_init

2.4 reset_init函數

這個函數里面介紹了面試常問的PID 0 1 2進程(到現在還只是不太明白)

static noinline void __init_refok rest_init(void)
{
	int pid;

	rcu_scheduler_starting(); //啟動RCU鎖調度器
	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 進程,也就是大名鼎鼎的 init 內核進程。
// init 進程的 PID 為 1。init 進程一開始是內核進程(也就是運行在內核態),后面 init 進程會在根
// 文件系統中查找名為“init”這個程序,這個“init”程序處於用戶態,通過運行這個“init”程
// 序,init 進程就會實現從內核態到用戶態的轉變。
	kernel_thread(kernel_init, NULL, CLONE_FS);
	numa_default_policy();
// 	調用函數 kernel_thread 創建 kthreadd 內核進程,此內核進程的 PID 為 2。kthreadd
// 進程負責所有內核進程的調度和管理
	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 來進入 idle 進程,cpu_startup_entry 會調用
// cpu_idle_loop,cpu_idle_loop 是個 while 循環,也就是 idle 進程代碼。idle 進程的 PID 為 0,idle
// 進程叫做空閑進程,如果學過 FreeRTOS 或者 UCOS 的話應該聽說過空閑任務。idle 空閑進程
// 就和空閑任務一樣,當 CPU 沒有事情做的時候就在 idle 空閑進程里面“瞎逛游”,反正就是給
// CPU 找點事做。當其他進程要工作的時候就會搶占 idle 進程,從而奪取 CPU 使用權。其實大
// 家應該可以看到 idle 進程並沒有使用 kernel_thread 或者 fork 函數來創建,因為它是有主進程演
// 變而來的, idle 進程是內核進程
	cpu_startup_entry(CPUHP_ONLINE);
}

2.5 init進程

static int __ref kernel_init(void *unused)
{
	int ret;

	kernel_init_freeable(); /* init 進程的一些其他初始化工作 */
	/* need to finish all async __init code before freeing the memory */
	async_synchronize_full();/* 等待所有的異步調用執行完成 */
	free_initmem();/* 釋放 init 段內存 */
	mark_rodata_ro();
	system_state = SYSTEM_RUNNING;/* 標記系統正在運行 */
	numa_default_policy();

	flush_delayed_fput();

// 	ramdisk_execute_command 是一個全局的 char 指針變量,此變量值為“/init”,
// 也就是根目錄下的 init 程序。ramdisk_execute_command 也可以通過 uboot 傳遞,在 bootargs 中
// 使用“rdinit=xxx”即可,xxx 為具體的 init 程序名字
	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.
	 */
// 	如果 ramdisk_execute_command 為空的話就看 execute_command 是否為空,反
// 正不管如何一定要在根文件系統中找到一個可運行的 init 程序。execute_command 的值是通過
// uboot 傳遞,在 bootargs 中使用“init=xxxx”就可以了,比如“init=/linuxrc”表示根文件系統中
// 的 linuxrc 就是要執行的用戶空間 init 程序
	if (execute_command) {
		ret = run_init_process(execute_command);
		if (!ret)
			return 0;
		panic("Requested init %s failed (error %d).",
		      execute_command, ret);
	}
// 	如果 ramdisk_execute_command 和 execute_command 都為空,那么就依次
// 查找“/sbin/init”、“/etc/init”、“/bin/init”和“/bin/sh”,這四個相當於備用 init 程序,如果這四
// 個也不存在,那么 Linux 啟動失敗!
// 如果以上步驟都沒有找到用戶空間的 init 程序,那么就提示錯誤發生
	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"))
		return 0;

	panic("No working init found.  Try passing init= option to kernel. "
	      "See Linux Documentation/init.txt for guidance.");
}

簡單看一下 kernel_init_freeable 函數,前面說了,kernel_init 會調用此函數來做一些init 進程初始化工作。kernel_init_freeable 定義在文件 init/main.c 中,縮減后的函數內容如下:

static noinline void __init kernel_init_freeable(void)
{
	/*
	 * Wait until kthreadd is all set-up.
	 */
	wait_for_completion(&kthreadd_done);/* 等待 kthreadd 進程准備就緒 */

	/* Now the scheduler is fully set up and can do blocking allocations */
	gfp_allowed_mask = __GFP_BITS_MASK;

	/*
	 * init can allocate pages on any node
	 */
	set_mems_allowed(node_states[N_MEMORY]);
	/*
	 * init can run on any cpu.
	 */
	set_cpus_allowed_ptr(current, cpu_all_mask);

	cad_pid = task_pid(current);

	smp_prepare_cpus(setup_max_cpus);

	do_pre_smp_initcalls();
	lockup_detector_init();

	smp_init();/* SMP 初始化 */
	sched_init_smp();/* 多核(SMP)調度初始化 */

	do_basic_setup();/* 設備初始化都在此函數中完成 */
	//do_basic_setup 會調用 driver_init 函數完成 Linux 下驅動模型子系統的初始化

	/* Open the /dev/console on the rootfs, this should never fail */
// 	打開設備“/dev/console”,在 Linux 中一切皆為文件!因此“/dev/console”也
// 是一個文件,此文件為控制台設備。每個文件都有一個文件描述符,此處打開的“/dev/console”
// 文件描述符為 0,作為標准輸入(0)
	if (sys_open((const char __user *) "/dev/console", O_RDWR, 0) < 0)
		pr_err("Warning: unable to open an initial console.\n");

// 	sys_dup 函數將標准輸入(0)的文件描述符復制了 2 次,一個作為標准
// 輸出(1),一個作為標准錯誤(2)。這樣標准輸入、輸出、錯誤都是/dev/console 了。console 通過
// uboot 的 bootargs 環境變量設置,“console=ttymxc0,115200”表示將/dev/ttymxc0 設置為 console,
// 也就是 I.MX6U 的串口 1。當然,也可以設置其他的設備為 console,比如虛擬控制台 tty1,設
// 置 tty1 為 console 就可以在 LCD 屏幕上看到系統的提示信息
	(void) sys_dup(0);
	(void) sys_dup(0);
	/*
	 * check if there is an early userspace init.  If yes, let it do all
	 * the work
	 */

	if (!ramdisk_execute_command)
		ramdisk_execute_command = "/init";

	if (sys_access((const char __user *) ramdisk_execute_command, 0) != 0) {
		ramdisk_execute_command = NULL;
// 		調用函數 prepare_namespace 來掛載根文件系統。跟文件系統也是由命令行參
// 數指定的,也就是 uboot 的 bootargs 環境變量。比如“root=/dev/mmcblk1p2 rootwait rw”就表示
// 根文件系統在/dev/mmcblk1p2 中,也就是 EMMC 的分區 2 中
		prepare_namespace();
	}

	/*
	 * Ok, we have completed the initial bootup, and
	 * we're essentially up and running. Get rid of the
	 * initmem segments and start the user-mode stuff..
	 *
	 * rootfs is available now, try loading the public keys
	 * and default modules
	 */

	integrity_load_keys();
	load_default_modules();
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM