• 分析linux启动内核源码


    内核的启动时从main.c这个文件里面的start_kernel函数开始的,这个文件在linux源码里面的init文件夹下面

    下面我们来看看这个函数 这个函数很长,可以看个大概过去

    1. asmlinkage __visible void __init start_kernel(void)
    2. {
    3. char *command_line;
    4. char *after_dashes;
    5. set_task_stack_end_magic(&init_task);
    6. smp_setup_processor_id();
    7. debug_objects_early_init();
    8. cgroup_init_early();
    9. local_irq_disable();
    10. early_boot_irqs_disabled = true;
    11. /*
    12. * Interrupts are still disabled. Do necessary setups, then
    13. * enable them.
    14. */
    15. boot_cpu_init();
    16. page_address_init();
    17. pr_notice("%s", linux_banner);
    18. setup_arch(&command_line);
    19. /*
    20. * Set up the the initial canary and entropy after arch
    21. * and after adding latent and command line entropy.
    22. */
    23. add_latent_entropy();
    24. add_device_randomness(command_line, strlen(command_line));
    25. boot_init_stack_canary();
    26. mm_init_cpumask(&init_mm);
    27. setup_command_line(command_line);
    28. setup_nr_cpu_ids();
    29. setup_per_cpu_areas();
    30. smp_prepare_boot_cpu(); /* arch-specific boot-cpu hooks */
    31. boot_cpu_hotplug_init();
    32. build_all_zonelists(NULL);
    33. page_alloc_init();
    34. pr_notice("Kernel command line: %s\n", boot_command_line);
    35. parse_early_param();
    36. after_dashes = parse_args("Booting kernel",
    37. static_command_line, __start___param,
    38. __stop___param - __start___param,
    39. -1, -1, NULL, &unknown_bootoption);
    40. if (!IS_ERR_OR_NULL(after_dashes))
    41. parse_args("Setting init args", after_dashes, NULL, 0, -1, -1,
    42. NULL, set_init_arg);
    43. jump_label_init();
    44. /*
    45. * These use large bootmem allocations and must precede
    46. * kmem_cache_init()
    47. */
    48. setup_log_buf(0);
    49. vfs_caches_init_early();
    50. sort_main_extable();
    51. trap_init();
    52. mm_init();
    53. ftrace_init();
    54. /* trace_printk can be enabled here */
    55. early_trace_init();
    56. /*
    57. * Set up the scheduler prior starting any interrupts (such as the
    58. * timer interrupt). Full topology setup happens at smp_init()
    59. * time - but meanwhile we still have a functioning scheduler.
    60. */
    61. sched_init();
    62. /*
    63. * Disable preemption - early bootup scheduling is extremely
    64. * fragile until we cpu_idle() for the first time.
    65. */
    66. preempt_disable();
    67. if (WARN(!irqs_disabled(),
    68. "Interrupts were enabled *very* early, fixing it\n"))
    69. local_irq_disable();
    70. radix_tree_init();
    71. /*
    72. * Set up housekeeping before setting up workqueues to allow the unbound
    73. * workqueue to take non-housekeeping into account.
    74. */
    75. housekeeping_init();
    76. /*
    77. * Allow workqueue creation and work item queueing/cancelling
    78. * early. Work item execution depends on kthreads and starts after
    79. * workqueue_init().
    80. */
    81. workqueue_init_early();
    82. rcu_init();
    83. /* Trace events are available after this */
    84. trace_init();
    85. if (initcall_debug)
    86. initcall_debug_enable();
    87. context_tracking_init();
    88. /* init some links before init_ISA_irqs() */
    89. early_irq_init();
    90. init_IRQ();
    91. tick_init();
    92. rcu_init_nohz();
    93. init_timers();
    94. hrtimers_init();
    95. softirq_init();
    96. timekeeping_init();
    97. time_init();
    98. printk_safe_init();
    99. perf_event_init();
    100. profile_init();
    101. call_function_init();
    102. WARN(!irqs_disabled(), "Interrupts were enabled early\n");
    103. early_boot_irqs_disabled = false;
    104. local_irq_enable();
    105. kmem_cache_init_late();
    106. /*
    107. * HACK ALERT! This is early. We're enabling the console before
    108. * we've done PCI setups etc, and console_init() must be aware of
    109. * this. But we do want output early, in case something goes wrong.
    110. */
    111. console_init();
    112. if (panic_later)
    113. panic("Too many boot %s vars at `%s'", panic_later,
    114. panic_param);
    115. lockdep_init();
    116. /*
    117. * Need to run this when irqs are enabled, because it wants
    118. * to self-test [hard/soft]-irqs on/off lock inversion bugs
    119. * too:
    120. */
    121. locking_selftest();
    122. /*
    123. * This needs to be called before any devices perform DMA
    124. * operations that might use the SWIOTLB bounce buffers. It will
    125. * mark the bounce buffers as decrypted so that their usage will
    126. * not cause "plain-text" data to be decrypted when accessed.
    127. */
    128. mem_encrypt_init();
    129. #ifdef CONFIG_BLK_DEV_INITRD
    130. if (initrd_start && !initrd_below_start_ok &&
    131. page_to_pfn(virt_to_page((void *)initrd_start)) < min_low_pfn) {
    132. pr_crit("initrd overwritten (0x%08lx < 0x%08lx) - disabling it.\n",
    133. page_to_pfn(virt_to_page((void *)initrd_start)),
    134. min_low_pfn);
    135. initrd_start = 0;
    136. }
    137. #endif
    138. kmemleak_init();
    139. setup_per_cpu_pageset();
    140. numa_policy_init();
    141. acpi_early_init();
    142. if (late_time_init)
    143. late_time_init();
    144. sched_clock_init();
    145. calibrate_delay();
    146. pid_idr_init();
    147. anon_vma_init();
    148. #ifdef CONFIG_X86
    149. if (efi_enabled(EFI_RUNTIME_SERVICES))
    150. efi_enter_virtual_mode();
    151. #endif
    152. thread_stack_cache_init();
    153. cred_init();
    154. fork_init();
    155. proc_caches_init();
    156. uts_ns_init();
    157. buffer_init();
    158. key_init();
    159. security_init();
    160. dbg_late_init();
    161. vfs_caches_init();
    162. pagecache_init();
    163. signals_init();
    164. seq_file_init();
    165. proc_root_init();
    166. nsfs_init();
    167. cpuset_init();
    168. cgroup_init();
    169. taskstats_init_early();
    170. delayacct_init();
    171. check_bugs();
    172. acpi_subsystem_init();
    173. arch_post_acpi_subsys_init();
    174. sfi_init_late();
    175. /* Do the rest non-__init'ed, we're now alive */
    176. arch_call_rest_init();
    177. }
    【文章福利】小编推荐自己的Linux内核技术交流群: 【977878001】整理一些个人觉得比较好得学习书籍、视频资料共享在群文件里面,有需要的可以自行添加哦!!!前100进群领取,额外赠送一份 价值699的内核资料包(含视频教程、电子书、实战项目及代码)

    内核资料直通车:Linux内核源码技术学习路线+视频教程代码资料

    学习直通车:Linux内核源码/内存调优/文件系统/进程管理/设备驱动/网络协议栈

    这个函数里面我们会看到有很多的各种init,也就是初始化,我们只说几个重点操作

    首先来看下这个函数set_task_stack_end_magic(&init_task);

    在linux里面所有的进程都是由父进程创建而来,所以说在启动内核的时候需要有个祖先进程,这个进程是系统创建的

    第一个进程,我们称为0号进程,它是唯一一个没有通过fork或者kernel_thread的进程

    然后就是初始化系统调用,对应的函数就是trap_init();这里面设置了很多中断门,用于处理各种中断

    系统调用也是通过发送中断的方式进行的。

    接下来就是内存管理模块的初始化,对应的函数是mm_init();

    然后就是初始化任务调度,对应的函数就是sched_init();

    这个任务调度是干嘛用的呢?就是操作系统协调进程和cpu,比如说分配哪个进程在cpu上运行呀,

    在比如说你这个进程在cpu上运行时间过长了,然后操作系统就会把你踢下去,换另一个进程在cpu上运行。

    到了这个preempt_disable();函数,这个函数的意思就是在这个函数运行以后就禁止被中断

    也就是说在这个函数运行后面,如果没有主动让出cpu,那么其他进程是无法抢占他的。

    然后看下这个tick_init();这个函数是时钟初始化,这个时钟的概念是什么意思呢?

    计算机会每隔一段时间周期通知操作系统,就像时钟一样,滴答滴答,每滴答一下就是一个时间周期过去了,

    通知操作系统后,操作系统会看下当前在cpu上运行的进程运行时间是否过长,如果过长就标识该进程为可抢占

    然后在某些时机下会切掉该进程,换下一个进程。

    最后start_kernel()调用的是rest_init()用来初始化其他方面,这里面做了好多事情

    1. noinline void __ref rest_init(void)
    2. {
    3. struct task_struct *tsk;
    4. int pid;
    5. rcu_scheduler_starting();
    6. /*
    7. * We need to spawn init first so that it obtains pid 1, however
    8. * the init task will end up wanting to create kthreads, which, if
    9. * we schedule it before we create kthreadd, will OOPS.
    10. */
    11. pid = kernel_thread(kernel_init, NULL, CLONE_FS);
    12. /*
    13. * Pin init on the boot CPU. Task migration is not properly working
    14. * until sched_init_smp() has been run. It will set the allowed
    15. * CPUs for init to the non isolated CPUs.
    16. */
    17. rcu_read_lock();
    18. tsk = find_task_by_pid_ns(pid, &init_pid_ns);
    19. set_cpus_allowed_ptr(tsk, cpumask_of(smp_processor_id()));
    20. rcu_read_unlock();
    21. numa_default_policy();
    22. pid = kernel_thread(kthreadd, NULL, CLONE_FS | CLONE_FILES);
    23. rcu_read_lock();
    24. kthreadd_task = find_task_by_pid_ns(pid, &init_pid_ns);
    25. rcu_read_unlock();
    26. /*
    27. * Enable might_sleep() and smp_processor_id() checks.
    28. * They cannot be enabled earlier because with CONFIG_PREEMPT=y
    29. * kernel_thread() would trigger might_sleep() splats. With
    30. * CONFIG_PREEMPT_VOLUNTARY=y the init task might have scheduled
    31. * already, but it's stuck on the kthreadd_done completion.
    32. */
    33. system_state = SYSTEM_SCHEDULING;
    34. complete(&kthreadd_done);
    35. /*
    36. * The boot idle thread must execute schedule()
    37. * at least once to get things moving:
    38. */
    39. schedule_preempt_disabled();
    40. /* Call into cpu_idle with preempt disabled */
    41. cpu_startup_entry(CPUHP_ONLINE);
    42. }

    首先调用kernel_thread()函数,用来创建用户态的第一个进程,这个进程是所有用户态进程的祖先进程,我们称为1号进程

    这个一号进程进入用户态以后,开枝散叶,创建了很多子进程,子进程又创建子进程,就形成了一颗进程树。

    一旦有了用户进程,就需要划分资源了,比如说用户态的进程要想使用网卡发送数据,这个时候不能直接让用户态进程调用网卡

    而是通过操作系统提供的系统调用函数,给进程发送数据,发送成功以后在返回到用户态进程,通知进程处理结果,也就是封装了

    底层实现,用户态进程想要实现什么功能,直接调用系统调用就可以了,在用户态进程进行系统调用时,操作系统会把当前该进程的

    参数都保存到寄存器里面,如果有对寄存器不懂的,就把寄存器想象成变量,变量是编程语言存放数据的,那么寄存器就是cpu用来存放数据的东西,

    等到系统调用从内核态返回到用户态的时候,会恢复当时保存的寄存器里面的数据,继续运行。

    这个过程就是这样的,用户态-》系统调用-》保存寄存器-》内核态执行系统调用-》恢复寄存器-》返回用户态 接着运行

    然后接着说这个一号进程启动过程,现在这个进程还是在内核态的,那么要怎么把它搞到用户态里面的,

    一般都是从用户态到内核态在返回到用户态,很少见过直接从内核态开始然后到用户态的

    看下下面这个代码

    1. void
    2. start_thread(struct pt_regs *regs, unsigned long new_ip, unsigned long new_sp)
    3. {
    4. set_user_gs(regs, 0);
    5. regs->fs = 0;
    6. regs->ds = __USER_DS;
    7. regs->es = __USER_DS;
    8. regs->ss = __USER_DS;
    9. regs->cs = __USER_CS;
    10. regs->ip = new_ip;
    11. regs->sp = new_sp;
    12. regs->flags = X86_EFLAGS_IF;
    13. force_iret();
    14. }
    15. EXPORT_SYMBOL_GPL(start_thread);

    创建进程的这函数最后会有这么一个函数也就是start_thread(),这里面把各个寄存器都设置为了_USER,啥意思呢,里面将用户态的代码段CS设置为_USER_CS,将用户态的数据段DS设置为_USER_DS,

    以及指令指针寄存器IP,栈顶指针SP,最后的force_iret();是用来恢复寄存器的,按理来说应该恢复在系统调用的时候保存的寄存器,这里面恢复的其实就是上面设置的寄存器。CS和指令指针寄存器IP恢复了,

    指向用户态下一个要执行的语句,DS和函数栈指针SP也被恢复了,指向用户态函数栈的栈顶,所以,下一条指令就从用户态开始了。

    用户态的祖先进程创建完了,那么内核态有没有一个祖先进程呢?

    有的,rest_init第二大事情就是第三个进程,也就是2号进程。

  • 相关阅读:
    基于JAVA流浪猫狗救助网站计算机毕业设计源码+数据库+lw文档+系统+部署
    SpringCloud——什么是微服务
    SQL必需掌握的100个重要知识点:IN 操作符
    C++ IO流
    composer 安装如何彻底删除
    1003 我要通过!【PAT (Basic Level) Practice (中文)】
    Canny算子详解及例程
    【计算机网络】传输层协议——TCP(上)
    使用树莓派搭建文件共享服务器-samba服务器
    100张照片带你了解澳大利亚
  • 原文地址:https://blog.csdn.net/m0_74282605/article/details/128041991