手把手教你分析 Linux 啟動流程
下載 Linux 內核網址:
https://www.kernel.org/
最新 Linux 內核是 5.15 版本。現在常用 Linux 內核源碼為4.14、4.19、4.9 等版本,其中 4.14 版本源碼壓縮包大概 90+M,解壓后 700+M,合計 61350 個文件。如此眾多的文件,用 source insight 或者 VSCode 查看都會比較卡,所以可以采用在線查看的方式。
在線查看 Linux 內核源碼網址:
https://elixir.bootlin.com/linux/latest/source
在線查看 Android 源碼:
http://androidxref.com/
Android系統是基于Linux 內核的,最底層為Linux內核,源碼量翻很多倍。所以用軟件看安卓源碼更卡,可以使用在線網址看源碼。
我們知道,Linux 系統的啟動,前面有一個啟動引導程序 bootloader,比如常用的 uboot,本文不分析 uboot 的啟動,只放一張流程圖:
本文主要講解當從 bootloader 跳轉到 Linux 系統的啟動函數 start_kernel 后,此函數對系統初始化的流程。
在 linux4.14/arch/arm/kernel/head.S 文件中,是最后匯編階段的初始化,而后會跳轉到 main.c 文件的 start_kernel 函數,在此做 Linux 啟動初始化,在這個函數中會調用將近100個函數去完成 Linux 系統的初始化,調用函數如下(不同內核版本,順序和細節有變化):
linux4.14/init/main.c,start_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);
- /* parameters may set static keys */
- jump_label_init();
- 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);
- /*
- * These use large bootmem allocations and must precede
- * kmem_cache_init()
- */
- setup_log_buf(0);
- pidhash_init();
- 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();
- /*
- * 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();
- 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();
- 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
- kmemleak_init();
- debug_objects_mem_init();
- setup_per_cpu_pageset();
- numa_policy_init();
- if (late_time_init)
- late_time_init();
- calibrate_delay();
- pidmap_init();
- anon_vma_init();
- acpi_early_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();
- buffer_init();
- key_init();
- security_init();
- dbg_late_init();
- vfs_caches_init();
- pagecache_init();
- signals_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();
- }
- /* Do the rest non-__init'ed, we're now alive */
- rest_init();
- prevent_tail_call_optimization();
- }
其中有七個函數較為重要,分別為:
- setup_arch(&command_line);
- mm_init();
- sched_init();
- init_IRQ();
- console_init();
- vfs_caches_init();
- rest_init();
1、setup_arch(&command_line)
此函數是系統架構初始化函數,處理 uboot 傳遞進來的參數,不同的架構進行不同的初始化,也就是說每個架構都會有一個 setup_arch 函數。
linux4.14/arch/arm/kernel/setup.c
2、mm_init
內存初始化函數
linux4.14/init/main.c
3、sched_init
核心進程調度器初始化。Linux 內核實現了四種調度方式,一般是采用 CFS 調度方式。作為一個普適性的操作系統,必須考慮各種需求,我們不能只按照中斷優先級或者時間輪轉片來規定進程運行的時間。作為一個多用戶操作系統,必須考慮到每個用戶的公平性。不能因為一個用戶沒有高級權限,就限制他的進程的運行時間,要考慮每個用戶擁有公平的時間。
linux4.14/kernel/sched/core.c
4、init_IRQ
中斷初始化函數,這個很好理解,大家都用過中斷。
linux4.14/arch/arm/kernel/irq.c
5、console_init
在這個函數初始化之前,你所有寫的內核打印函數 printk 都打印不出東西。在這個函數初始化之前,所有打印都會存在 buf 里,此函數初始化以后,會將 buf里面的數據打印出來,你才能在終端看到 printk 打印的東西。
tty 是 Linux 中的終端, _con_initcall_start 和_con_initcall_end 這兩句的意思是執行所有兩者之間的 initcall 函數。
linux4.14/kernel/printk/printk.c
6、vfs_caches_init
虛擬文件系統初始化,比如 sysfs,根文件系統等,就是在這一步進行掛載,proc 是內核虛擬的,用來輸出內核數據結構信息,不算在這里。
vfs虛擬文件系統,屏蔽了底層硬件的不同,提供了統一了接口,方便系統的移植和使用。使用戶在不用更改應用代碼的情況下直接移植代碼到其他平臺。
linux4.14/fs/dcache.c
這里的掛載主要在mnt_init()函數中:
linux4.14/fs/namespace.c
7、rest_init
這個函數可以算是 start_kernel函數調用的最后一個函數,在這里產生了最重要的兩個內核進程 kernel_init 和 kthreadd,kernel_init后面會從內核空間跳轉到用戶空間,變成用戶空間的 init 進程,PID=1,而 kthreadd ,PID=2,是內核進程,專門用來監聽創建內核進程的請求,它維護了一個鏈表,如果有創建內核進程的需求,就會在鏈表上創建。
至此,用戶空間最重要的 init 進程已經出來,后面用戶空間的進程都由 init進程來 fork。如果是安卓系統,init 進程會 fork 出一個 zygote 進程,他是所有安卓系統進程的父進程。
linux4.14/init.main.c
上圖,400 行創建了 kernel_init 進程,412 行創建了 kthreadd 進程,這兩個都是內核進程。426 行通知 kernel_init 進程 kthreadd 已經創建完畢。也就是說,實際上是 kthreadd 先運行,kernel_init 再運行。
其余的函數大家可以參照下面的文章去理解:
https://www.cnblogs.com/andyfly/p/9410441.html
https://www.cnblogs.com/lifexy/p/7366782.html
https://www.cnblogs.com/yanzs/p/13910344.html#radix_tree:init
本文轉載自微信公眾號「嵌入式Linux系統開發」