日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > linux >内容正文

linux

(连载)Android 8.0 : 系统启动流程之Linux内核

發布時間:2024/1/8 linux 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 (连载)Android 8.0 : 系统启动流程之Linux内核 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

這是一個連載的博文系列,我將持續為大家提供盡可能透徹的Android源碼分析 github連載地址

前言

Android本質上就是一個基于Linux內核的操作系統,與Ubuntu Linux、Fedora Linux類似,我們要講Android,必定先要了解一些Linux內核的知識。

Linux內核的東西特別多,我也不可能全部講完,由于本文主要講解Android系統啟動流程,所以這里主要講一些內核啟動相關的知識。

Linux內核啟動主要涉及3個特殊的進程,idle進程(PID = 0), init進程(PID = 1)和kthreadd進程(PID = 2),這三個進程是內核的基礎。

  • idle進程是Linux系統第一個進程,是init進程和kthreadd進程的父進程
  • init進程是Linux系統第一個用戶進程,是Android系統應用程序的始祖,我們的app都是直接或間接以它為父進程
  • kthreadd進程是Linux系統內核管家,所有的內核線程都是直接或間接以它為父進程

本文將以這三個進程為線索,主要講解以下內容:

  • idle進程啟動
  • kthreadd進程啟動
  • init進程啟動

本文涉及到的文件

msm/arch/arm64/kernel/head.S msm/init/main.c msm/kernel/rcutree.c msm/kernel/fork.c msm/mm/mempolicy.c msm/kernel/kthread.c msm/include/linux/kthread.h msm/include/linux/rcupdate.h msm/kernel/rcupdate.c msm/kernel/pid.c msm/include/linux/sched.h msm/kernel/sched/core.c msm/kernel/cpu/idle.c msm/drivers/base/init.c 復制代碼

一、idle進程啟動

很多文章講Android都從init進程講起,它的進程號是1,既然進程號是1,那么有沒有進程號是0的進程呢,其實是有的。

這個進程名字叫init_task,后期會退化為idle,它是Linux系統的第一個進程(init進程是第一個用戶進程),也是唯一一個沒有通過fork或者kernel_thread產生的進程,它在完成初始化操作后,主要負責進程調度、交換。

idle進程的啟動是用匯編語言寫的,對應文件是msm/arch/arm64/kernel/head.S,因為都是用匯編語言寫的,我就不多介紹了,具體可參考 kernel 啟動流程之head.S ,這里面有一句比較重要

340 str x22, [x4] // Save processor ID 341 str x21, [x5] // Save FDT pointer 342 str x24, [x6] // Save PHYS_OFFSET 343 mov x29, #0 344 b start_kernel //跳轉start_kernel函數 復制代碼

第344行,b start_kernel,b 就是跳轉的意思,跳轉到start_kernel.h,這個頭文件對應的實現在msm/init/main.c,start_kernel函數在最后會調用rest_init函數,這個函數開啟了init進程和kthreadd進程,我們著重分析下rest_init函數。

在講源碼前,我先說明下我分析源碼的寫作風格:

  • 一般我會在函數下面寫明該函數所在的位置,比如定義在msm/init/main.c中,這樣大家就可以去項目里找到源文件
  • 我會把源碼相應的英文注釋也一并copy進來,這樣方便英文好的人可以看到原作者的注釋
  • 我會盡可能將函數中每一行代碼的作用注釋下(一般以//的形式注釋在代碼結尾),大家在看源碼的同時就可以理解這段代碼作用,這也是我花時間最多的,請大家務必認真看。我也想過在源碼外部統一通過行號來解釋,但是感覺這樣需要大家一會兒看源碼,一會兒看解釋,上下來回看不方便,所以干脆寫在一起了
  • 為了大家更好地閱讀注釋,我會手動做換行處理,//形式注釋可能會換行到句首,也就是可能會出現在代碼下方
  • 在函數結尾我盡可能總結下這個函數做了些什么,以及這個函數涉及到的一些知識
  • 對于重要的函數,我會將函數中每一個調用的子函數再單獨拿出來講解
  • 考慮到大家都是開發Android的比較多,對C/C++不太了解,在注釋中我也會講一些C/C++的知識,方便大家理解,C語言注釋我一般用/** */的形式注釋在代碼頂頭
  • 為了更好的閱讀體驗,希望大家可以下載一下Source Insight同步看代碼,使用教程 ,可以直接將項目中app/src/main/cpp作為目錄加入到Source Insight中

1.1 rest_init

定義在msm/init/main.c中

/** 1.C語言oninline與inline是一對意義相反的關鍵字,inline的作用是編譯期間直接替換代碼塊,也就是說編譯后就沒有這個方法了,* 而是直接把代碼塊替換調用這個函數的地方,oninline就相反,強制不替換,保持原有的函數* 2.__init_refok是__init的擴展,__init 定義的初始化函數會放入名叫.init.text的輸入段,當內核啟動完畢后,* 這個段中的內存會被釋放掉,在本文中有講,關注3.5 free_initmem* 3.不帶參數的方法會加一個void參數*/ static noinline void __init_refok rest_init(void) {int pid;/** 1.C語言中const相當于Java中的final static, 表示常量* 2.struct是結構體,相當于Java中定義了一個實體類,里面只有一些成員變量,{.sched_priority =1 }相當于new,* 然后將成員變量sched_priority的值賦為1*/const struct sched_param param = { .sched_priority = 1 }; //初始化優先級為1的進程調度策略,//取值1~99,1為最小rcu_scheduler_starting(); //啟動RCU機制,這個與后面的rcu_read_lock和rcu_read_unlock是配套的,用于多核同步/** 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.*//** 1.C語言中支持方法傳參,kernel_thread是函數,kernel_init也是函數,但是kernel_init卻作為參數傳遞了過去,* 其實傳遞過去的是一個函數指針,參考[函數指針](http://www.cnblogs.com/haore147/p/3647262.html)* 2.CLONE_FS這種大寫的一般就是常量了,跟Java差不多*/kernel_thread(kernel_init, NULL, CLONE_FS | CLONE_SIGHAND); //用kernel_thread方式創建init進程,//CLONE_FS 子進程與父進程共享相同的文件系統,包括root、當前目錄、umask,//CLONE_SIGHAND 子進程與父進程共享相同的信號處理(signal handler)表numa_default_policy(); // 設定NUMA系統的默認內存訪問策略pid = kernel_thread(kthreadd, NULL, CLONE_FS | CLONE_FILES);//用kernel_thread方式創建kthreadd進程,//CLONE_FILES 子進程與父進程共享相同的文件描述符(file descriptor)表rcu_read_lock(); //打開RCU讀取鎖,在此期間無法進行進程切換/** C語言中&的作用是獲得變量的內存地址,參考[C指針](http://www.runoob.com/cprogramming/c-pointers.html)*/kthreadd_task = find_task_by_pid_ns(pid, &init_pid_ns);// 獲取kthreadd的進程描述符,//期間需要檢索進程pid的使用鏈表,所以要加鎖rcu_read_unlock(); //關閉RCU讀取鎖sched_setscheduler_nocheck(kthreadd_task, SCHED_FIFO, &param); //設置kthreadd的進程調度策略,//SCHED_FIFO 實時調度策略,即馬上調用,先到先服務,param的優先級之前定義為1complete(&kthreadd_done); // complete和wait_for_completion是配套的同步機制,跟java的notify和wait差不多,//之前kernel_init函數調用了wait_for_completion(&kthreadd_done),//這里調用complete就是通知kernel_init進程kthreadd進程已創建完成,可以繼續執行/** The boot idle thread must execute schedule()* at least once to get things moving:*/init_idle_bootup_task(current);//current表示當前進程,當前0號進程init_task設置為idle進程schedule_preempt_disabled(); //0號進程主動請求調度,讓出cpu,1號進程kernel_init將會運行,并且禁止搶占/* Call into cpu_idle with preempt disabled */cpu_startup_entry(CPUHP_ONLINE);// 這個函數會調用cpu_idle_loop()使得idle進程進入自己的事件處理循環 } 復制代碼

rest_init的字面意思是剩余的初始化,但是它卻一點都不剩余,它創建了Linux系統中兩個重要的進程init和kthreadd,并且將init_task進程變為idle進程,接下來我將把rest_init中的方法逐個解析,方便大家理解。

1.2 rcu_scheduler_starting

定義在msm/kernel/rcutree.c

/** This function is invoked towards the end of the scheduler's initialization* process. Before this is called, the idle task might contain* RCU read-side critical sections (during which time, this idle* task is booting the system). After this function is called, the* idle tasks are prohibited from containing RCU read-side critical* sections. This function also enables RCU lockdep checking.*/ void rcu_scheduler_starting(void) {WARN_ON(num_online_cpus() != 1); //WARN_ON相當于警告,會打印出當前棧信息,不會重啟, //num_online_cpus表示當前啟動的cpu數WARN_ON(nr_context_switches() > 0); // nr_context_switches 進行進程切換的次數rcu_scheduler_active = 1; //啟用rcu機制 } 復制代碼

1.3 kernel_thread

定義在msm/kernel/fork.c

/** Create a kernel thread.*//** 1.C語言中 int (*fn)(void *)表示函數指針的定義,int是返回值,void是函數的參數,fn是名字* 2.C語言中 * 表示指針,這個用法很多* 3.unsigned表示無符號,一般與long,int,char等結合使用,表示范圍只有正數,* 比如init表示范圍-2147483648~2147483647 ,那unsigned表示范圍0~4294967295,足足多了一倍*/ pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags) {return do_fork(flags|CLONE_VM|CLONE_UNTRACED, (unsigned long)fn,(unsigned long)arg, NULL, NULL); } 復制代碼

do_fork函數用于創建進程,它首先調用copy_process()創建新進程,然后調用wake_up_new_task()將進程放入運行隊列中并啟動新進程。 kernel_thread的第一個參數是一個函數引用,它相當于Java中的構造函數,會在創建進程后執行,第三個參數是創建進程的方式,具體如下:

參數名作用
CLONE_PARENT創建的子進程的父進程是調用者的父進程,新進程與創建它的進程成了“兄弟”而不是“父子”
CLONE_FS子進程與父進程共享相同的文件系統,包括root、當前目錄、umask
CLONE_FILES子進程與父進程共享相同的文件描述符(file descriptor)表
CLONE_NEWNS在新的namespace啟動子進程,namespace描述了進程的文件hierarchy
CLONE_SIGHAND子進程與父進程共享相同的信號處理(signal handler)表
CLONE_PTRACE若父進程被trace,子進程也被trace
CLONE_UNTRACED若父進程被trace,子進程不被trace
CLONE_VFORK父進程被掛起,直至子進程釋放虛擬內存資源
CLONE_VM子進程與父進程運行于相同的內存空間
CLONE_PID子進程在創建時PID與父進程一致
CLONE_THREADLinux 2.4中增加以支持POSIX線程標準,子進程與父進程共享相同的線程群

1.4 kernel_init

定義在msm/init/main.c

這個函數比較重要,負責init進程的啟動,我將放在第三節重點講,這個函數首先調用kernel_init_freeable函數

static noinline void __init kernel_init_freeable(void) {/** Wait until kthreadd is all set-up.*/wait_for_completion(&kthreadd_done);... }復制代碼

wait_for_completion之前講了,與complete是配套的同步機制,這里就是等待&kthreadd_done這個值complete,然后就可以繼續執行

1.5 numa_default_policy

定義在msm/mm/mempolicy.c

/* Reset policy of current process to default */ void numa_default_policy(void) {do_set_mempolicy(MPOL_DEFAULT, 0, NULL); //設定NUMA系統的內存訪問策略為MPOL_DEFAULT } 復制代碼

1.6 kthreadd

定義在msm/kernel/kthread.c中

kthreadd進程我將在第二節中重點講,它是內核中重要的進程,負責內核線程的調度和管理,內核線程基本都是以它為父進程的

1.7 rcu_read_lock & rcu_read_unlock

定義在msm/include/linux/rcupdate.h和msm/kernel/rcupdate.c中

RCU(Read-Copy Update)是數據同步的一種方式,在當前的Linux內核中發揮著重要的作用。RCU主要針對的數據對象是鏈表,目的是提高遍歷讀取數據的效率,為了達到目的使用RCU機制讀取數據的時候不對鏈表進行耗時的加鎖操作。這樣在同一時間可以有多個線程同時讀取該鏈表,并且允許一個線程對鏈表進行修改(修改的時候,需要加鎖)

static inline void rcu_read_lock(void) {__rcu_read_lock();__acquire(RCU);rcu_lock_acquire(&rcu_lock_map);rcu_lockdep_assert(!rcu_is_cpu_idle(),"rcu_read_lock() used illegally while idle"); }static inline void rcu_read_unlock(void) {rcu_lockdep_assert(!rcu_is_cpu_idle(),"rcu_read_unlock() used illegally while idle");rcu_lock_release(&rcu_lock_map);__release(RCU);__rcu_read_unlock(); } 復制代碼

1.8 find_task_by_pid_ns

定義在msm/kernel/pid.c中

task_struct叫進程描述符,這個結構體包含了一個進程所需的所有信息,它定義在msm/include/linux/sched.h文件中。

它的結構十分復雜,本文就不重點講了,可以參考Linux進程描述符task_struct結構體詳解

/** Must be called under rcu_read_lock().*/ struct task_struct *find_task_by_pid_ns(pid_t nr, struct pid_namespace *ns) {rcu_lockdep_assert(rcu_read_lock_held(),"find_task_by_pid_ns() needs rcu_read_lock()"" protection"); //必須進行RCU加鎖return pid_task(find_pid_ns(nr, ns), PIDTYPE_PID); }struct pid *find_pid_ns(int nr, struct pid_namespace *ns) {struct upid *pnr;hlist_for_each_entry_rcu(pnr,&pid_hash[pid_hashfn(nr, ns)], pid_chain)/** C語言中 -> 用于指向結構體 struct 中的數據*/if (pnr->nr == nr && pnr->ns == ns)return container_of(pnr, struct pid,numbers[ns->level]); //遍歷hash表,找到struct pidreturn NULL; }struct task_struct *pid_task(struct pid *pid, enum pid_type type) {struct task_struct *result = NULL;if (pid) {struct hlist_node *first;first = rcu_dereference_check(hlist_first_rcu(&pid->tasks[type]),lockdep_tasklist_lock_is_held());if (first)result = hlist_entry(first, struct task_struct, pids[(type)].node); //從hash表中找出struct task_struct}return result; } 復制代碼

find_task_by_pid_ns的作用就是根據pid,在hash表中獲得對應pid的task_struct

1.9 sched_setscheduler_nocheck

定義在msm/kernel/sched/core.c中

int sched_setscheduler_nocheck(struct task_struct *p, int policy,const struct sched_param *param) {struct sched_attr attr = {.sched_policy = policy,.sched_priority = param->sched_priority};return __sched_setscheduler(p, &attr, false); //設置進程調度策略 } 復制代碼

linux內核目前實現了6種調度策略(即調度算法), 用于對不同類型的進程進行調度, 或者支持某些特殊的功能

  • SCHED_FIFO和SCHED_RR和SCHED_DEADLINE則采用不同的調度策略調度實時進程,優先級最高

  • SCHED_NORMAL和SCHED_BATCH調度普通的非實時進程,優先級普通

  • SCHED_IDLE則在系統空閑時調用idle進程,優先級最低

1.10 init_idle_bootup_task

定義在msm/kernel/sched/core.c中

void __cpuinit init_idle_bootup_task(struct task_struct *idle) {idle->sched_class = &idle_sched_class; //設置進程的調度器類為idle_sched_class } 復制代碼

Linux依據其調度策略的不同實現了5個調度器類, 一個調度器類可以用一種種或者多種調度策略調度某一類進程, 也可以用于特殊情況或者調度特殊功能的進程.

其所屬進程的優先級順序為

stop_sched_class -> dl_sched_class -> rt_sched_class -> fair_sched_class -> idle_sched_class 復制代碼

可見idle_sched_class的優先級最低,只有系統空閑時才調用idle進程

1.11 schedule_preempt_disabled

定義在msm/kernel/sched/core.c中

/*** schedule_preempt_disabled - called with preemption disabled** Returns with preemption disabled. Note: preempt_count must be 1*/ void __sched schedule_preempt_disabled(void) {sched_preempt_enable_no_resched(); //開啟內核搶占schedule(); // 并主動請求調度,讓出cpupreempt_disable(); // 關閉內核搶占 } 復制代碼

1.9到1.11都涉及到Linux的進程調度問題,可以參考 Linux用戶搶占和內核搶占詳解

1.12 cpu_startup_entry

定義在msm/kernel/cpu/idle.c中

void cpu_startup_entry(enum cpuhp_state state) {/** This #ifdef needs to die, but it's too late in the cycle to* make this generic (arm and sh have never invoked the canary* init for the non boot cpus!). Will be fixed in 3.11*//** 1.C語言中#ifdef和#else、#endif是條件編譯語句,也就是說在滿足某些條件的時候,* 夾在這幾個關鍵字中間的代碼才編譯,不滿足就不編譯* 2.下面這句話的意思就是如果定義了CONFIG_X86這個宏,就把boot_init_stack_canary這個代碼編譯進去*/ #ifdef CONFIG_X86/** If we're the non-boot CPU, nothing set the stack canary up* for us. The boot CPU already has it initialized but no harm* in doing it again. This is a good place for updating it, as* we wont ever return from this function (so the invalid* canaries already on the stack wont ever trigger).*/boot_init_stack_canary();//只有在x86這種non-boot CPU機器上執行,該函數主要用于初始化stack_canary的值,用于防止棧溢出 #endif__current_set_polling(); //設置本架構下面有標示輪詢poll的bit位,保證cpu進行重新調度。arch_cpu_idle_prepare(); //進行idle前的準備工作,ARM64中沒有實現per_cpu(idle_force_poll, smp_processor_id()) = 0;cpu_idle_loop(); //進入idle進程的事件循環 }復制代碼

1.13 cpu_idle_loop

定義在msm/kernel/cpu/idle.c中

/** Generic idle loop implementation*/ static void cpu_idle_loop(void) {while (1) { //開啟無限循環,進行進程調度tick_nohz_idle_enter(); //停止周期時鐘while (!need_resched()) { //判斷是否有設置TIF_NEED_RESCHED,只有系統沒有進程需要調度時才執行while里面操作check_pgt_cache();rmb();local_irq_disable(); //關閉irq中斷arch_cpu_idle_enter();/** In poll mode we reenable interrupts and spin.** Also if we detected in the wakeup from idle* path that the tick broadcast device expired* for us, we don't want to go deep idle as we* know that the IPI is going to arrive right* away*/if (cpu_idle_force_poll ||tick_check_broadcast_expired() ||__get_cpu_var(idle_force_poll)) {cpu_idle_poll(); //進入 CPU 的poll mode模式,避免進入深度睡眠,可以處理 處理器間中斷} else {if (!current_clr_polling_and_test()) {stop_critical_timings();rcu_idle_enter();arch_cpu_idle(); //進入 CPU 的 idle 模式,省電WARN_ON_ONCE(irqs_disabled());rcu_idle_exit();start_critical_timings();} else {local_irq_enable();}__current_set_polling();}arch_cpu_idle_exit();}tick_nohz_idle_exit(); //如果有進程需要調度,則先開啟周期時鐘schedule_preempt_disabled(); //讓出cpu,執行調度if (cpu_is_offline(smp_processor_id())) //如果當前cpu處理offline狀態,關閉idle進程arch_cpu_idle_dead();} } 復制代碼

idle進程并不執行什么復雜的工作,只有在系統沒有其他進程調度的時候才進入idle進程,而在idle進程中盡可能讓cpu空閑下來,連周期時鐘也關掉了,達到省電目的。當有其他進程需要調度的時候,馬上開啟周期時鐘,然后讓出cpu。

小結

idle進程是Linux系統的第一個進程,進程號是0,在完成系統環境初始化工作之后,開啟了兩個重要的進程,init進程和kthreadd進程,執行完創建工作之后,開啟一個無限循環,負責進程的調度。

二、kthreadd進程啟動

之前在rest_init函數中啟動了kthreadd進程

pid = kernel_thread(kthreadd, NULL, CLONE_FS | CLONE_FILES); 復制代碼

進程創建成功后會執行kthreadd函數

2.1 kthreadd

定義在msm/kernel/kthread.c中

int kthreadd(void *unused) {struct task_struct *tsk = current;/* Setup a clean context for our children to inherit. */set_task_comm(tsk, "kthreadd");ignore_signals(tsk);set_cpus_allowed_ptr(tsk, cpu_all_mask); // 允許kthreadd在任意CPU上運行set_mems_allowed(node_states[N_MEMORY]);current->flags |= PF_NOFREEZE;for (;;) {set_current_state(TASK_INTERRUPTIBLE); //首先將線程狀態設置為 TASK_INTERRUPTIBLE, //如果當前沒有要創建的線程則主動放棄 CPU 完成調度.此進程變為阻塞態if (list_empty(&kthread_create_list)) // 沒有需要創建的內核線程schedule(); // 執行一次調度, 讓出CPU__set_current_state(TASK_RUNNING);// 運行到此表示 kthreadd 線程被喚醒(就是我們當前),設置進程運行狀態為 TASK_RUNNINGspin_lock(&kthread_create_lock); //spin_lock和spin_unlock是配套的加鎖機制,spin_lock是加鎖while (!list_empty(&kthread_create_list)) {struct kthread_create_info *create;create = list_entry(kthread_create_list.next,struct kthread_create_info, list); //kthread_create_list是一個鏈表,//從鏈表中取出下一個要創建的kthread_create_info,即線程創建信息list_del_init(&create->list); //刪除create中的listspin_unlock(&kthread_create_lock); //解鎖create_kthread(create); //創建線程spin_lock(&kthread_create_lock); }spin_unlock(&kthread_create_lock);}return 0; } 復制代碼

kthreadd函數的作用就是循環地從kthread_create_list鏈表中取出要創建的線程,然后執行create_kthread函數,直到kthread_create_list為空,讓出CPU,進入睡眠,我們來看下create_kthread函數

2.2 create_kthread

定義在msm/kernel/kthread.c中

static void create_kthread(struct kthread_create_info *create) {int pid;#ifdef CONFIG_NUMAcurrent->pref_node_fork = create->node; #endif/* We want our own signal handler (we take no signals by default). */pid = kernel_thread(kthread, create, CLONE_FS | CLONE_FILES | SIGCHLD);if (pid < 0) {create->result = ERR_PTR(pid);complete(&create->done);} } 復制代碼

其實這里面就是調用kernel_thread函數創建進程,然后執行kthread函數,注意不要搞混了,之前那個函數叫kthreadd,接下來看看kthread函數

2.3 kthread

定義在msm/kernel/kthread.c中

static int kthread(void *_create) {/* Copy data: it's on kthread's stack */struct kthread_create_info *create = _create; // create 就是之前kthreadd函數循環取出的 kthread_create_infoint (*threadfn)(void *data) = create->threadfn; //新線程工作函數void *data = create->data;struct kthread self;int ret;self.flags = 0;self.data = data;init_completion(&self.exited);init_completion(&self.parked);current->vfork_done = &self.exited;/* OK, tell user we're spawned, wait for stop or wakeup */__set_current_state(TASK_UNINTERRUPTIBLE);create->result = current;complete(&create->done); //表示線程創建完畢schedule(); //讓出CPU,注意這里并沒有執行新線程的threadfn函數就直接進入睡眠了,然后等待線程被手動喚醒,然后才執行threadfnret = -EINTR;if (!test_bit(KTHREAD_SHOULD_STOP, &self.flags)) {__kthread_parkme(&self);ret = threadfn(data);}/* we can't just return, we must preserve "self" on stack */do_exit(ret); } 復制代碼

2.4 kthread_create & kthread_run

定義在msm/include/linux/kthread.h

kthreadd創建線程是遍歷kthread_create_list列表,那kthread_create_list列表中的值是哪兒來的呢?我們知道Linux創建內核線程有兩種方式,kthread_create和kthread_run

#define kthread_create(threadfn, data, namefmt, arg...) \kthread_create_on_node(threadfn, data, -1, namefmt, ##arg)#define kthread_run(threadfn, data, namefmt, ...) \ ({ \struct task_struct *__k \= kthread_create(threadfn, data, namefmt, ## __VA_ARGS__); \if (!IS_ERR(__k)) \wake_up_process(__k); //手動喚醒新線程 \__k; \ }) 復制代碼

kthread_create和kthread_run并不是函數,而是宏,宏相當于Java中的final static定義,在編譯時會替換對應代碼,宏的參數沒有類型定義,多行宏的定義會在行末尾加上\

這兩個宏最終都是調用kthread_create_on_node函數,只是kthread_run在線程創建完成后會手動喚醒,我們來看看kthread_create_on_node函數

2.5 kthread_create_on_node

定義在msm/kernel/kthread.c中

/*** kthread_create_on_node - create a kthread.* @threadfn: the function to run until signal_pending(current).* @data: data ptr for @threadfn.* @node: memory node number.* @namefmt: printf-style name for the thread.** Description: This helper function creates and names a kernel* thread. The thread will be stopped: use wake_up_process() to start* it. See also kthread_run().** If thread is going to be bound on a particular cpu, give its node* in @node, to get NUMA affinity for kthread stack, or else give -1.* When woken, the thread will run @threadfn() with @data as its* argument. @threadfn() can either call do_exit() directly if it is a* standalone thread for which no one will call kthread_stop(), or* return when 'kthread_should_stop()' is true (which means* kthread_stop() has been called). The return value should be zero* or a negative error number; it will be passed to kthread_stop().** Returns a task_struct or ERR_PTR(-ENOMEM).*/ struct task_struct *kthread_create_on_node(int (*threadfn)(void *data),void *data, int node,const char namefmt[],...) {struct kthread_create_info create;create.threadfn = threadfn;create.data = data;create.node = node;init_completion(&create.done); //初始化&create.done,之前講過completion和wait_for_completion同步spin_lock(&kthread_create_lock); //加鎖,之前也講過list_add_tail(&create.list, &kthread_create_list); //將要創建的線程加到kthread_create_list鏈表尾部spin_unlock(&kthread_create_lock);wake_up_process(kthreadd_task); //喚醒kthreadd進程,開啟列表循環創建線程wait_for_completion(&create.done); //當&create.done complete時,會繼續往下執行if (!IS_ERR(create.result)) {static const struct sched_param param = { .sched_priority = 0 };va_list args; //不定參數定義,相當于Java中的... ,定義多個數量不定的參數va_start(args, namefmt);vsnprintf(create.result->comm, sizeof(create.result->comm),namefmt, args);va_end(args);/** root may have changed our (kthreadd's) priority or CPU mask.* The kernel thread should not inherit these properties.*/sched_setscheduler_nocheck(create.result, SCHED_NORMAL, &param); //create.result類型為task_struct,//該函數作用是設置新線程調度策略,SCHED_NORMAL 普通調度策略,非實時,//優先級低于實時調度策略SCHED_FIFO和SCHED_RR,param的優先級上面定義為0set_cpus_allowed_ptr(create.result, cpu_all_mask); //允許新線程在任意CPU上運行}return create.result; } 復制代碼

kthread_create_on_node主要作用就是在kthread_create_list鏈表尾部加上要創建的線程,然后喚醒kthreadd進程進行具體創建工作

小結

kthreadd進程由idle通過kernel_thread創建,并始終運行在內核空間, 負責所有內核線程的調度和管理,所有的內核線程都是直接或者間接的以kthreadd為父進程。

  • kthreadd進程會執行一個kthreadd的函數,該函數的作用就是遍歷kthread_create_list鏈表,從鏈表中取出需要創建的內核線程進行創建, 創建成功后會執行kthread函數。

  • kthread函數完成一些初始賦值后就讓出CPU,并沒有執行新線程的工作函數,因此需要手工 wake up被喚醒后,新線程才執行自己的真正工作函數。

  • 當我們調用kthread_create和kthread_run創建的內核線程會被加入到kthread_create_list鏈表,kthread_create不會手動wake up新線程,kthread_run會手動wake up新線程。

其實這就是一個典型的生產者消費者模式,kthread_create和kthread_run負責生產各種內核線程創建需求,kthreadd開啟循環去消費各種內核線程創建需求。

三、init進程啟動

init進程分為前后兩部分,前一部分是在內核啟動的,主要是完成創建和內核初始化工作,內容都是跟Linux內核相關的;后一部分是在用戶空間啟動的,主要完成Android系統的初始化工作。

我這里要講的是前一部分,后一部分將在下一篇文章中講述。

之前在rest_init函數中啟動了init進程

kernel_thread(kernel_init, NULL, CLONE_FS | CLONE_SIGHAND); 復制代碼

在創建完init進程后,會調用kernel_init函數

3.1 kernel_init

定義在msm/init/main.c中

/** __ref 這個跟之前講的__init作用一樣*/ static int __ref kernel_init(void *unused) {kernel_init_freeable(); //進行init進程的一些初始化操作/* need to finish all async __init code before freeing the memory */async_synchronize_full();// 等待所有異步調用執行完成,,在釋放內存前,必須完成所有的異步 __init 代碼free_initmem();// 釋放所有init.* 段中的內存mark_rodata_ro(); //arm64空實現system_state = SYSTEM_RUNNING;// 設置系統狀態為運行狀態numa_default_policy(); // 設定NUMA系統的默認內存訪問策略flush_delayed_fput(); // 釋放所有延時的struct file結構體if (ramdisk_execute_command) { //ramdisk_execute_command的值為"/init"if (!run_init_process(ramdisk_execute_command)) //運行根目錄下的init程序return 0;pr_err("Failed to execute %s\n", ramdisk_execute_command);}/** 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.*/if (execute_command) { //execute_command的值如果有定義就去根目錄下找對應的應用程序,然后啟動if (!run_init_process(execute_command))return 0;pr_err("Failed to execute %s. Attempting defaults...\n",execute_command);}if (!run_init_process("/sbin/init") || //如果ramdisk_execute_command和execute_command定義的應用程序都沒有找到,//就到根目錄下找 /sbin/init,/etc/init,/bin/init,/bin/sh 這四個應用程序進行啟動!run_init_process("/etc/init") ||!run_init_process("/bin/init") ||!run_init_process("/bin/sh"))return 0;panic("No init found. Try passing init= option to kernel. ""See Linux Documentation/init.txt for guidance."); } 復制代碼

kernel_init主要工作是完成一些init的初始化操作,然后去系統根目錄下依次找ramdisk_execute_command和execute_command設置的應用程序,如果這兩個目錄都找不到,就依次去根目錄下找 /sbin/init,/etc/init,/bin/init,/bin/sh 這四個應用程序進行啟動,只要這些應用程序有一個啟動了,其他就不啟動了

ramdisk_execute_command和execute_command的值是通過bootloader傳遞過來的參數設置的,ramdisk_execute_command通過"rdinit"參數賦值,execute_command通過"init"參數賦值

ramdisk_execute_command如果沒有被賦值,kernel_init_freeable函數會賦一個初始值"/init"

3.2 kernel_init_freeable

定義在msm/init/main.c中

static noinline void __init kernel_init_freeable(void) {/** Wait until kthreadd is all set-up.*/wait_for_completion(&kthreadd_done); //等待&kthreadd_done這個值complete,這個在rest_init方法中有寫,在ktreadd進程啟動完成后設置為complete/* 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進程可以分配物理頁面/** init can run on any cpu.*/set_cpus_allowed_ptr(current, cpu_all_mask); //init進程可以在任意cpu上執行cad_pid = task_pid(current); //設置到init進程的pid號給cad_pid,cad就是ctrl-alt-del,設置init進程來處理ctrl-alt-del信號smp_prepare_cpus(setup_max_cpus);//設置smp初始化時的最大CPU數量,然后將對應數量的CPU狀態設置為presentdo_pre_smp_initcalls();//調用__initcall_start到__initcall0_start之間的initcall_t函數指針lockup_detector_init(); //開啟watchdog_threads,watchdog主要用來監控、管理CPU的運行狀態smp_init();//啟動cpu0外的其他cpu核sched_init_smp(); //進程調度域初始化do_basic_setup();//初始化設備,驅動等,這個方法比較重要,將在下面單獨講/* Open the /dev/console on the rootfs, this should never fail */if (sys_open((const char __user *) "/dev/console", O_RDWR, 0) < 0) // 打開/dev/console,//文件號0,作為init進程標準輸入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*/if (!ramdisk_execute_command) //如果 ramdisk_execute_command 沒有賦值,則賦值為"/init",之前有講到ramdisk_execute_command = "/init";if (sys_access((const char __user *) ramdisk_execute_command, 0) != 0) { // 嘗試進入ramdisk_execute_command指向的文件,如果失敗則重新掛載根文件系統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 default modules */load_default_modules(); // 加載I/O調度的電梯算法 }復制代碼

kernel_init_freeable函數做了很多重要的事情

  • 啟動了smp,smp全稱是Symmetrical Multi-Processing,即對稱多處理,是指在一個計算機上匯集了一組處理器(多CPU),各CPU之間共享內存子系統以及總線結構。
  • 初始化設備和驅動程序
  • 打開標準輸入和輸出
  • 初始化文件系統

3.3 do_basic_setup

定義在msm/init/main.c中

/** 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子系統。usermodehelper_init();// 創建khelper單線程工作隊列,用于協助新建和運行用戶空間程序shmem_init();// 初始化共享內存driver_init();// 初始化設備驅動,比較重要下面單獨講init_irq_proc();//創建/proc/irq目錄, 并初始化系統中所有中斷對應的子目錄do_ctors();// 執行內核的構造函數usermodehelper_enable();// 啟用usermodehelperdo_initcalls();//遍歷initcall_levels數組,調用里面的initcall函數,這里主要是對設備、驅動、文件系統進行初始化,//之所有將函數封裝到數組進行遍歷,主要是為了好擴展random_int_secret_init();//初始化隨機數生成池 } 復制代碼

3.4 driver_init

定義在msm/drivers/base/init.c中

/*** 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_init();// 注冊devtmpfs文件系統,啟動kdevtmpfs進程devices_init();// 初始化驅動模型中的部分子系統,kset:devices 和 kobject:dev、 dev/block、 dev/charbuses_init();// 初始化驅動模型中的bus子系統,kset:bus、devices/systemclasses_init();// 初始化驅動模型中的class子系統,kset:classfirmware_init();// 初始化驅動模型中的firmware子系統 ,kobject:firmwarehypervisor_init();// 初始化驅動模型中的hypervisor子系統,kobject:hypervisor/* These are also core pieces, but must come after the* core core pieces.*/platform_bus_init();// 初始化驅動模型中的bus/platform子系統,這個節點是所有platform設備和驅動的總線類型,//即所有platform設備和驅動都會掛載到這個總線上cpu_dev_init(); // 初始化驅動模型中的devices/system/cpu子系統,該節點包含CPU相關的屬性memory_dev_init();//初始化驅動模型中的/devices/system/memory子系統,該節點包含了內存相關的屬性,如塊大小等 }復制代碼

這個函數完成驅動子系統的構建,實現了Linux設備驅動的一個整體框架,但是它只是建立了目錄結構,具體驅動的裝載是在do_initcalls函數,之前有講

kernel_init_freeable函數告一段落了,我們接著講kernel_init中剩余的函數

3.5 free_initmem

定義在msm/arch/arm64/mm/init.c中中

void free_initmem(void) {poison_init_mem(__init_begin, __init_end - __init_begin);free_initmem_default(0); } 復制代碼

所有使用__init標記過的函數和使用__initdata標記過的數據,在free_initmem函數執行后,都不能使用,它們曾經獲得的內存現在可以重新用于其他目的。

3.6 flush_delayed_fput

定義在msm/arch/arm64/mm/init.c中,它執行的是delayed_fput(NULL)

static void delayed_fput(struct work_struct *unused) {LIST_HEAD(head);spin_lock_irq(&delayed_fput_lock);list_splice_init(&delayed_fput_list, &head);spin_unlock_irq(&delayed_fput_lock);while (!list_empty(&head)) {struct file *f = list_first_entry(&head, struct file, f_u.fu_list);list_del_init(&f->f_u.fu_list); //刪除fu_list__fput(f); //釋放struct file} } 復制代碼

這個函數主要用于釋放&delayed_fput_list這個鏈表中的struct file,struct file即文件結構體,代表一個打開的文件,系統中的每個打開的文件在內核空間都有一個關聯的 struct file。

3.7 run_init_process

定義在msm/init/main.c中

static int run_init_process(const char *init_filename) {argv_init[0] = init_filename;return do_execve(init_filename,(const char __user *const __user *)argv_init,(const char __user *const __user *)envp_init); //do_execve就是執行一個可執行文件 } 復制代碼

run_init_process就是運行可執行文件了,從kernel_init函數中可知,系統會依次去找根目錄下的init,execute_command,/sbin/init,/etc/init,/bin/init,/bin/sh這六個可執行文件,只要找到其中一個,其他就不執行。

Android系統一般會在根目錄下放一個init的可執行文件,也就是說Linux系統的init進程在內核初始化完成后,就直接執行init這個文件,這個文件的源代碼在platform/system/core/init/init.cpp,下一篇文章中我將從這個文件為入口,講解Android系統的init進程。

關于我

  • foxleezh
  • 我的博客
  • github
  • 郵箱-foxleezh@gmail.com

總結

以上是生活随笔為你收集整理的(连载)Android 8.0 : 系统启动流程之Linux内核的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。