Linux内核启动流程-迅为IMX6ULL开发板(二)

基于迅为-IMX6ULL开发板 Linux内核启动(三):内核初始化

start_kernel是所有Linux平台进入系统内核初始化后的入口函数,它主要完成剩余的与 硬件平台相关的初始化工作,在进行一系列与内核相关的初始化后,调用第一个用户进程- init 进程并等待用户进程的执行,这样整个 Linux内核便启动完毕。

30.3.1 start_kernel 函数

start_kernel 通过调用众多的子函数来完成 Linux 启动之前的一些初始化工作,由于start_kernel 函数里面调用的子函数太多,而这些子函数又很复杂,因此我们简单介绍一下一些重要的子函数。start_kernel 函数定义在文件 init/main.c中。精简并添加注释后的 start_kernel 函数内容如下:
asmlinkage __visible void __init start_kernel(void)
{
char *command_line;
char *after_dashes;
lockdep_init(); /* lockdep 是死锁检测模块,此函数会初始化
两个 hash 表。此函数要求尽可能早的执行!
*/
set_task_stack_end_magic(&init_task);        /* 设置任务栈结束魔术数,
*用于栈溢出检测
*/
smp_setup_processor_id();   /* 跟 SMP 有关(多核处理器),设置处理器 ID
有很多资料说 ARM 架构下此函数为空函数,那是因
为他们用的老版本 Linux,而那时候 ARM 还没有多
核处理器。
*/
debug_objects_early_init(); /* 做一些和 debug 有关的初始化 */
boot_init_stack_canary();          /* 栈溢出检测初始化 */
cgroup_init_early();                  /* cgroup 初始化,cgroup 用于控制 Linux 系统资源*/
local_irq_disable();                  /* 关闭当前 CPU 中断 */
early_boot_irqs_disabled = true;
/*
中断关闭期间做一些重要的操作,然后打开中断
*/
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(); /* 如果只是 SMP(多核 CPU)的话,此函数用于获取
* CPU 核心数量,CPU 数量保存在变量
* nr_cpu_ids 中。
*/
setup_per_cpu_areas(); /* 在 SMP 系统中有用,设置每个 CPU 的 per-cpu 数据 */
smp_prepare_boot_cpu();
build_all_zonelists(NULL, NULL); /* 建立系统内存页区(zone)链表 */
page_alloc_init();                           /* 处理用于热插拔 CPU 的页 */
/* 打印命令行信息 */
pr_notice("Kernel command line: %s ", 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();
setup_log_buf(0);                          /* 设置 log 使用的缓冲区*/
pidhash_init();                          /* 构建 PID 哈希表,Linux 中每个进程都有一个 ID,
这个 ID 叫做 PID。通过构建哈希表可以快速搜索进程
信息结构体。
*/
vfs_caches_init_early();         /* 预先初始化 vfs(虚拟文件系统)的目录项和
索引节点缓存
*/
sort_main_extable();                  /* 定义内核异常列表 */
trap_init();                                  /* 完成对系统保留中断向量的初始化 */
mm_init();                                  /* 内存管理初始化 */
sched_init();                          /* 初始化调度器,主要是初始化一些结构体 */
preempt_disable();                         /* 关闭优先级抢占 */
if (WARN(!irqs_disabled(),  /* 检查中断是否关闭,如果没有的话就关闭中断 */
"Interrupts were enabled *very* early, fixing it "))
local_irq_disable();
idr_init_cache();                          /* IDR 初始化,IDR 是 Linux 内核的整数管理机
制,也就是将一个整数 ID 与一个指针关联起来。
*/
rcu_init();                 /* 初始化 RCURCU 全称为 Read Copy Update(-拷贝修改) */
trace_init();          /* 跟踪调试相关初始化 */
context_tracking_init();
radix_tree_init();                  /* 基数树相关数据结构初始化 */
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 ");
early_boot_irqs_disabled = false;
local_irq_enable();                         /* 使能中断 */
kmem_cache_init_late();                 /* slab 初始化,slab 是 Linux 内存分配器 */
console_init();                                 /* 初始化控制台,之前 printk 打印的信息都存放
缓冲区中,并没有打印出来。只有调用此函数
初始化控制台以后才能在控制台上打印信息。
*/
if (panic_later)
panic("Too many boot %s vars at `%s'", panic_later,
panic_param);
lockdep_info();                /* 如果定义了宏 CONFIG_LOCKDEP,那么此函数打印一些信息。*/
locking_selftest()                 /* 锁自测 */
......
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();
......
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();                         /* 初始化信号*/
page_writeback_init();         /* 页回写初始化*/
proc_root_init();                         /* 注册并挂载 proc 文件系统 */
nsfs_init();
cpuset_init();                 /* 初始化 cpusetcpuset 是将 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();
rest_init();                         /* rest_init 函数 */
}
start_kernel 里面调用了大量的函数,每一个函数都是一个庞大的知识点,如果想要学习Linux 内核,那么这些函数就需要去详细的研究。本教程注重于嵌入式 Linux 入门,因此不会去讲太多关于 Linux 内核的知识。start_kernel 函数最后调用了 rest_init,接下来简单看一下rest_init函数。

30.3.2 rest_init 函数

rest_init 函数定义在文件 init/main.c 中,函数内容如下:
383 static noinline void __init_refok rest_init(void)
384 {
385                 int pid;
386
387                 rcu_scheduler_starting();
388                 smpboot_thread_init();
389                 /*
390                 * We need to spawn init first so that it obtains pid 1, however
391                 * the init task will end up wanting to create kthreads, which,
392                 * if we schedule it before we create kthreadd, will OOPS.
393                 */
394                 kernel_thread(kernel_init, NULL, CLONE_FS);
395                 numa_default_policy();
396                 pid = kernel_thread(kthreadd, NULL, CLONE_FS | CLONE_FILES);
397                 rcu_read_lock();
398                 kthreadd_task = find_task_by_pid_ns(pid, &init_pid_ns);
399                 rcu_read_unlock();
400                 complete(&kthreadd_done);
401
402                 /*
403                 * The boot idle thread must execute schedule()
404                 * at least once to get things moving:
405                 */
406                 init_idle_bootup_task(current);
407                 schedule_preempt_disabled();
408                 /* Call into cpu_idle with preempt disabled */
409                 cpu_startup_entry(CPUHP_ONLINE);
410 }
 387 行,调用函数 rcu_scheduler_starting,启动 RCU 锁调度器。
 394 行,调用函数 kernel_thread 创建 kernel_init 线程,也就是大名鼎鼎的 init 内核进程。init 进程的 PID  1。init 进程一开始是内核进程(也就是运行在内核态),后面 init 进程会在根文件系统中查找名为“init”这个程序,这个“init”程序处于用户态,通过运行这个“init”程序,init 进程就会实现从内核态到用户态的转变。
 396 行,调用函数 kernel_thread 创建 kthreadd 内核进程,此内核进程的 PID  2。kthreadd进程负责所有内核进程的调度和管理。
 409 行,最后调用函数 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 函数来创建,因为它是有主进程演变而来的。

30.3.3 init 进程

kernel_init 函数就是 init 进程具体做的工作,定义在文件 init/main.c 中,函数内容如下:
928 static int __ref kernel_init(void *unused)
929 {
930                 int ret;
931
932                 kernel_init_freeable();         /* init 进程的一些其他初始化工作 */
933         /* need to finish all async __init code before freeing the memory */
934                 async_synchronize_full();         /* 等待所有的异步调用执行完成 */
935                 free_initmem();                         /* 释放 init 段内存*/
936                 mark_rodata_ro();
937                 system_state = SYSTEM_RUNNING; /* 标记系统正在运行*/
938                 numa_default_policy();
939
940                 flush_delayed_fput();
941
942                 if (ramdisk_execute_command) {
943                 ret = run_init_process(ramdisk_execute_command);
944                 if (!ret)
945                 return 0;
946                 pr_err("Failed to execute %s (error %d) ",
947                 ramdisk_execute_command, ret);
948 }
949
950 /*
951 * We try each of these until one succeeds.
952 *
953 * The Bourne shell can be used instead of init if we are
954 * trying to recover a really broken machine.
955 */
956                 if (execute_command) {
957                         ret = run_init_process(execute_command);
958                         if (!ret)
959                                 return 0;
960                         panic("Requested init %s failed (error %d).",
961                         execute_command, ret);
962                 }
963                 if (!try_to_run_init_process("/sbin/init") ||
964                         !try_to_run_init_process("/etc/init") ||
965                         !try_to_run_init_process("/bin/init") ||
966                         !try_to_run_init_process("/bin/sh"))
967                         return 0;
968
969                 panic("No working init found. Try passing init= option to
kernel. "
970                 "See Linux Documentation/init.txt for guidance.");
971 }
 932 行,kernel_init_freeable 函数用于完成 init 进程的一些其他初始化工作,稍后再来具体看一下此函数。
 940 行,ramdisk_execute_command 是一个全局的 char 指针变量,此变量值“/init”,也就是根目录下的 init 程序。ramdisk_execute_command 也可以通过 uboot 传递,在bootargs 中使用“rdinit=xxx”即可,xxx 为具体的 init 程序名字。
 943 行,如果存在“/init”程序的话就通过函数 run_init_process 来运行此程序。
 956 行,如果 ramdisk_execute_command 为空的话就看 execute_command 是否为空,反正不管如何一定要在根文件系统中找到一个可运行的 init 程序。execute_command 的值是通过uboot 传递,在 bootargs 中使用“init=xxxx”就可以了,比如“init=/linuxrc”表示根文件系统中的 linuxrc 就是要执行的用户空间 init 程序。
 963~966 行,如果 ramdisk_execute_command  execute_command 都为空,那么就依次查找“/sbin/init”、“/etc/init”、“/bin/init”和“/bin/sh”,这四个相当于备用 init 程序,如果这四个也不存在,那么 Linux 启动失败!
 969 行,如果以上步骤都没有找到用户空间的 init 程序,那么就提示错误发生!
最后来简单看一下 kernel_init_freeable 函数,前面说了,kernel_init 会调用此函数来做一些init 进程初始化工作。kernel_init_freeable 定义在文件 init/main.c 中,缩减后的函数内容如下:
973 static noinline void __init kernel_init_freeable(void)
974 {
975                 /*
976                 * Wait until kthreadd is all set-up.
977                 */
978                 wait_for_completion(&kthreadd_done);/* 等待 kthreadd 进程准备就绪 */
......
998
999                 smp_init();                         /* SMP 初始化 */
1000         sched_init_smp();         /* 多核(SMP)调度初始化 */
1001
1002         do_basic_setup();         /* 设备初始化都在此函数中完成 */
1003
1004         /* Open the /dev/console on the rootfs, this should never fail */
1005         if (sys_open((const char __user *) "/dev/console", O_RDWR, 0) < 0)
1006         pr_err("Warning: unable to open an initial console. ");
1007
1008         (void) sys_dup(0);
1009         (void) sys_dup(0);
1010         /*
1011         * check if there is an early userspace init. If yes, let it do
1012         * all the work
1013                 */
1014
1015         if (!ramdisk_execute_command)
1016                 ramdisk_execute_command = "/init";
1017
1018         if (sys_access((const char __user *) ramdisk_execute_command, 0) != 0) {
1019                 ramdisk_execute_command = NULL;
1020                 prepare_namespace();
1021         }
1022
1023         /*
1024         * Ok, we have completed the initial bootup, and
1025         * we're essentially up and running. Get rid of the
1026         * initmem segments and start the user-mode stuff..
1027         *
1028         * rootfs is available now, try loading the public keys
1029         * and default modules
1030         */
1031
1032         integrity_load_keys();
1033         load_default_modules();
1034 }
 1002 行,do_basic_setup 函数用于完成 Linux 下设备驱动初始化工作!非常重要。 do_basic_setup 会调用 driver_init 函数完成 Linux 下驱动模型子系统的初始化。
 1005 行,打开设备“/dev/console”,在 Linux 中一切皆为文件!因此“/dev/console”也是一个文件,此文件为控制台设备。每个文件都有一个文件描述符,此处打开的“/dev/console”文件描述符为 0,作为标准输入(0)。
 1008  1009 行,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 屏幕上看到系统的提示信息。
 1020 行,调用函数 prepare_namespace 来挂载根文件系统。跟文件系统也是由命令行参数指定的,也就是 uboot  bootargs 环境变量。比如“root=/dev/mmcblk1p2 rootwait rw”就表示根文件系统在/dev/mmcblk1p2 中,也就是 EMMC 的分区 2 中。
Linux 内核启动流程就分析到这里,Linux 内核最终是需要和根文件系统打交道的,需要挂载根文件系统,并且执行根文件系统中的 init 程序,以此来进去用户态。这里就正式引出了根文件系统,根文件系统也是我们系统移植的最后一片拼图。Linux 移植三巨头:uboot、Linux kernel、rootfs(根文件系统)。关于根文件系统后面章节会详细的讲解,这里我们只需要知道 Linux内核移植完成以后还需要构建根文件系统即可。
原文地址:https://www.cnblogs.com/liyue3/p/13343757.html