1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Linux内核4.14版本:ARM64的内核启动过程(二)——start_kernel

Linux内核4.14版本:ARM64的内核启动过程(二)——start_kernel

时间:2020-07-04 22:09:56

相关推荐

Linux内核4.14版本:ARM64的内核启动过程(二)——start_kernel

目录

1. rest_init

2. init 进程(kernel_init)

2.1kernel_init_freeable

2.1.1do_basic_setup

2.1.2prepare_namespace(挂载根文件系统)

2.2run_init_process

start_kernel 里面调用了大量的函数,每一个函数都是一个庞大的知识点,如果想要学习Linux 内核,那么这些函数就需要去详细的研究。本篇文章只是简单介绍 Linux内核启动流程,因此不会去讲太多关于 Linux 内核的知识。 start_kernel 函数最后调用了 rest_init。

asmlinkage __visible void __init start_kernel(void){char *command_line;char *after_dashes;set_task_stack_end_magic(&init_task);/* 设置任务栈结束魔术数,*用于栈溢出检测*/smp_setup_processor_id();/* 跟 SMP 有关(多核处理器),设置处理器 ID。* 有很多资料说 ARM 架构下此函数为空函数,那是因* 为他们用的老版本 Linux,而那时候 ARM 还没有多* 核处理器。*/debug_objects_early_init();/* 做一些和 debug 有关的初始化 */cgroup_init_early();/* cgroup 初始化, cgroup 用于控制 Linux 系统资源*/local_irq_disable(); //关闭当前CUP中断 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 中。*//** 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();/* 如果只是 SMP(多核 CPU)的话,此函数用于获取* CPU 核心数量, CPU 数量保存在变量* nr_cpu_ids 中。*/setup_per_cpu_areas();/* 在 SMP 系统中有用,设置每个 CPU 的 per-cpu 数据 */smp_prepare_boot_cpu();/* arch-specific boot-cpu hooks */boot_cpu_hotplug_init();build_all_zonelists(NULL);/* 建立系统内存页区(zone)链表 */page_alloc_init();/* 处理用于热插拔 CPU 的页 *//* 打印命令行信息 */pr_notice("Kernel command line: %s\n", boot_command_line);/* parameters may set static keys */jump_label_init();parse_early_param();/* 解析命令行中的 console 参数 */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);/* 设置 log 使用的缓冲区*/pidhash_init();/* 构建 PID 哈希表, Linux 中每个进程都有一个 ID,* 这个 ID 叫做 PID。通过构建哈希表可以快速搜索进程* 信息结构体。*/vfs_caches_init_early();/* 预先初始化 vfs(虚拟文件系统)的目录项和* 索引节点缓存*/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();/* 初始化 RCU, RCU 全称为 Read Copy Update(读-拷贝修改) *//* Trace events are available after this */trace_init();/* 跟踪调试相关初始化 */context_tracking_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();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(); /* 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(); /* 锁自测 *//** 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_INITRDif (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;}#endifkmemleak_init(); /* kmemleak 初始化, kmemleak 用于检查内存泄漏 */debug_objects_mem_init();setup_per_cpu_pageset();numa_policy_init();if (late_time_init)late_time_init();calibrate_delay(); /* 测定 BogoMIPS 值,可以通过 BogoMIPS 来判断 CPU 的性能* BogoMIPS 设置越大,说明 CPU 性能越好。*/pidmap_init();/* PID 位图初始化 */anon_vma_init();/* 生成 anon_vma slab 缓存 */acpi_early_init();#ifdef CONFIG_X86if (efi_enabled(EFI_RUNTIME_SERVICES))efi_enter_virtual_mode();#endifthread_stack_cache_init();cred_init();/* 为对象的每个用于赋予资格(凭证) */fork_init();/* 初始化一些结构体以使用 fork 函数 */proc_caches_init(); /* 给各种资源管理结构分配缓存 */buffer_init();/* 初始化缓冲缓存 */key_init();/* 初始化密钥 */security_init();/* 安全相关初始化 */dbg_late_init();vfs_caches_init(); /* 为 VFS 创建缓存 */pagecache_init();signals_init();/* 初始化信号 */proc_root_init();nsfs_init();cpuset_init(); /* 初始化 cpuset, cpuset 是将 CPU 和内存资源以逻辑性* 和层次性集成的一种机制,是 cgroup 使用的子系统之一*/cgroup_init();/* 初始化 cgroup */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();/* rest_init 函数 */prevent_tail_call_optimization();}

1. rest_init

rest_init 函数定义在文件 init/main.c 中,函数内容如下:

static noinline void __ref rest_init(void){struct task_struct *tsk;int pid;rcu_scheduler_starting();/* 启动 RCU 锁调度器 *//** 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();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();/** Enable might_sleep() and smp_processor_id() checks.* They cannot be enabled earlier because with CONFIG_PRREMPT=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;complete(&kthreadd_done);/** The boot idle thread must execute schedule()* at least once to get things moving:*/schedule_preempt_disabled();/* Call into cpu_idle with preempt disabled */cpu_startup_entry(CPUHP_ONLINE);}

在第六行,通过调用函数rcu_scheduler_starting,来启动 RCU 锁调度器。

第十二行,调用函数 kernel_thread 创建 kernel_init 线程,也就是大名鼎鼎的 init 内核进程。init 进程的 PID 为 1。 init 进程一开始是内核进程(也就是运行在内核态),后面 init 进程会在根文件系统中查找名为“init”这个程序,这个“init”程序处于用户态,通过运行这个“init”程序, init 进程就会实现从内核态到用户态的转变。

第二十四行,调用函数 kernel_thread 创建 kthreadd 内核进程,此内核进程的 PID 为 2。kthreadd进程负责所有内核进程的调度和管理。

第四十六行,调用函数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 函数来创建,因为它是有主进程演变而来的。

在 Linux 终端中输入ps -A就可以打印出当前系统中的所有进程,其中就能看到 init 进程和kthreadd 进程。

2. init 进程(kernel_init)

kernel_init 函数就是 init 进程具体做的工作,定义在文件 init/main.c 中,函数内容如下:

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();/* 等待所有的异步调用执行完成 */ftrace_free_init_mem();free_initmem();/* 释放 init 段内存 */mark_readonly();system_state = SYSTEM_RUNNING;/* 标记系统正在运行 */numa_default_policy(); // 设定NUMA系统的默认内存访问策略rcu_end_inkernel_boot();if (ramdisk_execute_command) { //ramdisk_execute_command的值为"/init"ret = run_init_process(ramdisk_execute_command); //运行根目录下的init程序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.*///execute_command的值如果有定义就去根目录下找对应的应用程序,然后启动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 这四个应用程序进行启动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/admin-guide/init.rst for guidance.");}

第五行,kernel_init_freeable 函数用于完成 init 进程的一些其他初始化工作。

第十六行,ramdisk_execute_command 是一个全局的 char 指针变量,此变量值为“/init”,

也就是根目录下的 init 程序。 ramdisk_execute_command 也可以通过 uboot 传递,在 bootargs 中使用“rdinit=xxx”即可, xxx 为具体的 init 程序名字。

第十六行,如果存在“/init”程序的话就通过函数 run_init_process 来运行此程序。

第三十行,如果 ramdisk_execute_command 为空的话就看 execute_command 是否为空,反正不管如何一定要在根文件系统中找到一个可运行的 init 程序。 execute_command 的值是通过uboot 传递,在 bootargs 中使用“init=xxxx”就可以了,比如“init=/linuxrc”表示根文件系统中的 linuxrc 就是要执行的用户空间 init 程序。

第三十七行,如果 ramdisk_execute_command 和 execute_command 都为空,那么就依次查找“/sbin/init”、“/etc/init”、“/bin/init”和“/bin/sh”,这四个相当于备用 init 程序,如果这四个也不存在,那么 Linux 启动失败!

第四十三行,如果以上步骤都没有找到用户空间的 init 程序,那么就提示错误发生!

Linux 内核最终是需要和根文件系统打交道的,需要挂载根文件系统,并且执行根文件系统中的 init 程序,以此来进去用户态。这里就正式引出了根文件系统,根文件系统也是我们系统移植的最后一片拼图。 Linux 移植三巨头: uboot、 Linux kernel、 rootfs(根文件系统)。

2.1kernel_init_freeable

init\main.c

static noinline void __init kernel_init_freeable(void){/** Wait until kthreadd is all set-up.*///等待&kthreadd_done这个值complete,这个在rest_init方法中有写,在ktreadd进程启动完成后设置为completewait_for_completion(&kthreadd_done);/* Now the scheduler is fully set up and can do blocking allocations */gfp_allowed_mask = __GFP_BITS_MASK;//设置bitmask, 使得init进程可以使用PM并且允许I/O阻塞操作/** init can allocate pages on any node*/set_mems_allowed(node_states[N_MEMORY]); //init进程可以分配物理页面cad_pid = get_pid(task_pid(current));smp_prepare_cpus(setup_max_cpus);//设置smp初始化时的最大CPU数量,然后将对应数量的CPU状态设置为presentworkqueue_init();init_mm_internals();do_pre_smp_initcalls();//调用__initcall_start到__initcall0_start之间的initcall_t函数指针lockup_detector_init(); //开启watchdog_threads,watchdog主要用来监控、管理CPU的运行状态smp_init();//启动cpu0外的其他cpu核sched_init_smp();//进程调度域初始化page_alloc_init_late();/* Initialize page ext after all struct pages are initialized. */page_ext_init();do_basic_setup();//初始化设备,驱动等,这个方法比较重要,将在下面单独讲/* Open the /dev/console on the rootfs, this should never fail */// 打开/dev/console,文件号0,作为init进程标准输入if (sys_open((const char __user *) "/dev/console", O_RDWR, 0) < 0)pr_err("Warning: unable to open an initial console.\n");(void) sys_dup(0);// 标准输入(void) sys_dup(0);// 标准输出/** check if there is an early userspace init. If yes, let it do all* the work*///如果 ramdisk_execute_command 没有赋值,则赋值为"/init"if (!ramdisk_execute_command)ramdisk_execute_command = "/init";// 尝试进入ramdisk_execute_command指向的文件,如果失败则重新挂载根文件系统if (sys_access((const char __user *) ramdisk_execute_command, 0) != 0) {ramdisk_execute_command = NULL;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(); // 加载I/O调度的电梯算法}

kernel_init_freeable函数做了很多重要的事情,启动了smp,smp全称是Symmetrical Multi-Processing,即对称多处理,是指在一个计算机上汇集了一组处理器(多CPU),各CPU之间共享内存子系统以及总线结构。初始化设备和驱动程序、打开标准输入和输出、初始化文件系统(挂载根文件系统)等等。

2.1.1do_basic_setup

/** Ok, the machine is now initialized. None of the devices* have been touched yet, but the CPU subsystem is up and* running, and memory and process management works.** Now we can finally start doing some real work..*/static void __init do_basic_setup(void){cpuset_init_smp();/**针对SMP系统,初始化内核control group的cpuset子系统。如果非SMP,此函数为空。*cpuset是在用户空间中操作cgroup文件系统来执行进程与cpu和进程与内存结点之间的绑定。*本函数将cpus_allowed和mems_allwed更新为在线的cpu和在线的内存结点,并为内存热插拨注册了钩子函数,最后创建一个单线程工作队列cpuset。*/shmem_init();driver_init();//初始化驱动模型中的各子系统,可见的现象是在/sys中出现的目录和文件init_irq_proc();//在proc文件系统中创建irq目录,并在其中初始化系统中所有中断对应的目录。do_ctors();//调用链接到内核中的所有构造函数,也就是链接进.ctors段中的所有函数。usermodehelper_enable();do_initcalls();// 调用所有编译内核的驱动模块中的初始化函数。}

2.1.1.1driver_init

/*** driver_init - initialize driver model.** Call the driver model init functions to initialize their* subsystems. Called early from init/main.c.*/void __init driver_init(void){/* These are the core pieces *//* 初始化devtmpfs文件系统,驱动核心设备将在这个文件系统中添加它们的设备节点。这个文件系统可以由内核在挂载根文件系统之后自动挂载到/dev下,也可以在文件系统的启动脚本中手动挂载。 */devtmpfs_init();/* 初始化驱动模型中的部分子系统和kobject:devicesdevdev/blockdev/char */devices_init();buses_init();//初始化驱动模型中的bus子系统classes_init();//初始化驱动模型中的class子系统firmware_init();//初始化驱动模型中的firmware子系统hypervisor_init();//初始化驱动模型中的hypervisor子系统/* These are also core pieces, but must come after the* core core pieces.*/platform_bus_init();//初始化驱动模型中的bus/platform子系统cpu_dev_init();//初始化驱动模型中的devices/system/cpu子系统//初始化驱动模型中的devices/system/memory子系统虽然从代码上看这样,但是我在实际的系统中并没有找到/sys/devices/system/memory这个目录。memory_dev_init();container_dev_init();of_core_init();}

2.1.1.2do_initcalls()

主要通过核心函数do_initcalls()调用所有编译内核的驱动模块中的初始化函数。完成外设及其驱动程序的加载和初始化 ;

do_initcalls()这里就是驱动程序员需要关心的步骤,其中按照各个内核模块初始化函数所自定义的启动级别(1~7),按顺序调用器初始化函数。对于同一级别的初始化函数,安装编译是链接的顺序调用,也就是和内核Makefile的编写有关。在编写内核模块的时候需要知道这方面的知识,比如你编写的模块使用的是I2C的API,那你的模块的初始化函数的级别必须低于I2C子系统初始化函数的级别(也就是级别数(1~7)要大于I2C子系统)。如果编写的模块必须和依赖的模块在同一级,那就必须注意内核Makefile的修改了。

Linux内核4.14版本:ARM64的内核启动过程(四)——do_initcalls_yangguoyu8023的博客-CSDN博客

2.1.2prepare_namespace(挂载根文件系统)

prepare_namespace这个函数负责挂载根文件系统

如果内核挂载根文件系统成功,则会打印出:VFS: Mounted root (xxxx filesystem) on device xxxx.

如果挂载根文件系统失败,则会打印:No filesystem could mount root, tried: xxxx

一般来说,挂载根文件系统失败的原因有:1.U-boot的环境变量bootargs设置不对,导致传递了错误的参数给kernel;2.还有一定几率是烧录根文件系统的时候出错,这个纯粹是运气问题;3.根文件系统本身制作有问题

Linux内核4.14版本:ARM64的内核启动过程——prepare_namespace()挂载根文件系统_yangguoyu8023的博客-CSDN博客

2.2run_init_process

static int run_init_process(const char *init_filename){argv_init[0] = init_filename;return do_execve(getname_kernel(init_filename),(const char __user *const __user *)argv_init,(const char __user *const __user *)envp_init);}

run_init_process就是运行可执行文件了,从kernel_init函数中可知,系统会依次去找根目录下的init,execute_command,/sbin/init,/etc/init,/bin/init,/bin/sh这六个可执行文件,只要找到其中一个,其他就不执行。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。