Linux啓動流程_LK流程(源碼層面)_作廢

此博客是剛剛開始學習LK的時候寫的,現在看來十分粗糙,重新寫了一個LK系列(大多數參考了網上資料),故此篇作廢。

此篇博客有很多參考其他文章的內容,由於參考內容繁雜,不一一標註角標了,在末尾會貼上所有參考博客的link,如有侵權,請聯繫本人處理,謝謝。

深入,並且廣泛
					 -沉默犀牛

step1 從哪裏開始執行,目前還不清楚,不作分析了。
step2 Bootloader(LK)

LK的代碼在bootable/bootloader/lk目錄下

在 bootable/bootloadler/lk/arch/arm/ssystem-onesegment.ld 連接文件中ENTRY(_start)指定 LK 從_start 函數開始,_start 在 lk/arch/crt0.S中,下面我們來看一下這個文件中的內容:

    .globl _start

    _start:  //這裏就是ENTRY(_start)中的_start

    ...

    /*啓動CPU*/

    這裏的指令都是有關CPU初始化的一些指令,不展開了

    /* we are relocated, jump to the right address */

    ldrr0, =.Lstack_setup

    ...

    .Lstack_setup:

    /*爲irq、fiq、abort、undefined、system/user和last supervisor模式設置堆棧*/

    /* 清除BSS *

    bl    kmain  //注意這裏!

上文說過bootloader分爲stage1和stage2,從這個彙編文件來看,應該已經包含了stage1,和stage2。只是stage2還沒有結束,kmain也算是stage2裏面的一部分。如果這裏理解有誤,請留言告知,感激不盡。

彙編中的最後一個有註釋的指令bl kmain,跳轉到了如下的代碼中,代碼路徑爲 lk/kernel/main.c

 void kmain(void) __NO_RETURN __EXTERNALLY_VISIBLE;

    void kmain(void) {

    thread_t *thr;

    thread_init_early();   //初始化thread(lk 中的簡單進程)相關結構體。

    arch_early_init();     //做一些如 關閉 cache,使能 mmu 的 arm 相關工作。

    platform_early_init();  // 相關平臺的早期初始化

    target_early_init();   // 現在就一個函數跳轉,初始化UART(板子相關)

    dprintf(INFO, "welcome to lk\n\n");

    bs_set_timestamp(BS_BL_START);

    dprintf(SPEW, "calling constructors\n"); 

    call_constructors();

    dprintf(SPEW, "initializing heap\n");

    heap_init();       // lk系統相關的堆棧初始化

    __stack_chk_guard_setup();

    dprintf(SPEW, "initializing threads\n");

    thread_init();   // 線程初始化

    dprintf(SPEW, "initializing dpc\n");

    dpc_init();   // lk系統控制器初始化(相關事件初始化)

    dprintf(SPEW, "initializing timers\n");

    timer_init();   // 初始化lk中的定時器

    #if (!ENABLE_NANDWRITE)

    dprintf(SPEW, "creating bootstrap completion thread\n");

    thr = thread_create("bootstrap2",&bootstrap2, NULL, DEFAULT_PRIORITY, DEFAULT_STACK_SIZE);   // 新建線程入口函數

    if (!thr) {

    panic("failed to create thread bootstrap2\n");

    }thread_resume(thr);

    exit_critical_section();   // 使能中斷

    thread_become_idle();  // 使自己成爲idle進程

    #else    //對應上面的#if (!ENABLE_NANDWRITE) ,我們一般走if,不會走else

            bootstrap_nandwrite();

    #endif

    }

這裏可以看到,kmain主要做了兩件事:1.本身lk的初始化 2.boot啓動初始化

以上與 boot 啓動初始化相關函數是arch_early_init、platform_early_init 、bootstrap2,這些是啓動的重點,我們下面慢慢來看。

arch_early_init

void arch_early_init(void)
{
	/* turn off the cache */
	arch_disable_cache(UCACHE);    // 關閉 cache 

	/* set the vector base to our exception vectors so we dont need to double map at 0 */
#if ARM_CPU_CORTEX_A8
	set_vector_base(MEMBASE);     //設置異常向量基地址
#endif

#if ARM_WITH_MMU
	arm_mmu_init();     //初始化MMU

#endif

	/* turn the cache back on */
	arch_enable_cache(UCACHE);   /*開啓cache */

#if ARM_WITH_NEON
	/* enable cp10 and cp11 */
	/* 使能 cp10 和 cp11*/
	uint32_t val;
	__asm__ volatile("mrc	p15, 0, %0, c1, c0, 2" : "=r" (val));
	val |= (3<<22)|(3<<20);
	__asm__ volatile("mcr	p15, 0, %0, c1, c0, 2" :: "r" (val));

	isb();

	/* set enable bit in fpexc */
	/*設置使能 fpexc 位(中斷相關)*/
	__asm__ volatile("mrc  p10, 7, %0, c8, c0, 0" : "=r" (val));
	val |= (1<<30);
	__asm__ volatile("mcr  p10, 7, %0, c8, c0, 0" :: "r" (val));
#endif

#if ARM_CPU_CORTEX_A8
	/* enable the cycle count register */
	/* 使能循環計數寄存器 */
	uint32_t en;
	__asm__ volatile("mrc	p15, 0, %0, c9, c12, 0" : "=r" (en));
	en &= ~(1<<3);   /*循環計算每個週期*/
	en |= 1; /* 啓動所有的 performance 計數器  */
	__asm__ volatile("mcr	p15, 0, %0, c9, c12, 0" :: "r" (en));

	/* enable cycle counter */
	en = (1<<31);
	__asm__ volatile("mcr	p15, 0, %0, c9, c12, 1" :: "r" (en));
#endif
}

platform_early_init

void platform_early_init(void)
{
	/* initialize the interrupt controller */
	/*1.初始化中斷*/
	platform_init_interrupts();

	/* initialize the timer block */
	/*初始化定時器*/
	platform_init_timer();
}

bootstrap2

static int bootstrap2(void *arg)
{
	dprintf(SPEW, "top of bootstrap2()\n");

	arch_init();  //此函數爲空

	// XXX put this somewhere else
#if WITH_LIB_BIO
	bio_init();
#endif
#if WITH_LIB_FS
	fs_init();
#endif

	// initialize the rest of the platform
	dprintf(SPEW, "initializing platform\n");
	platform_init();  // 平臺初始化,不同的平臺要做的事情不一樣,可以是初始化系統時鐘,超頻等

	// initialize the target
	dprintf(SPEW, "initializing target\n");
	target_init();   //目標設備初始化,主要初始化Flash,整合分區表等

	dprintf(SPEW, "calling apps_init()\n");
	apps_init();//應用功能初始化,主要調用aboot_init,啓動kernel,加載boot/recovery鏡像等

	return 0;
}

platform_init 中主要是函數 acpu_clock_init,在 acpu_clock_init 對 arm11 進行系統時鐘設置,超頻 。

target_init 針對硬件平臺進行設置。主要對 arm9 和 arm11 的分區表進行整合,初始化flash和讀取FLASH信息。

apps_init 是關鍵,對 LK 中所有 app 初始化並運行起來,而 aboot_init 就將在這裏開始被運行,android linux 內核的加載工作就在 aboot_init 中完成的 。

void apps_init(void)
{
	const struct app_descriptor *app;

	/* call all the init routines */
	for (app = &__apps_start; app != &__apps_end; app++) {
		if (app->init)   //如果app有init成員,就執行app->init
			app->init(app);
	}

	/* start any that want to start on boot */
	for (app = &__apps_start; app != &__apps_end; app++) {
		if (app->entry && (app->flags & APP_FLAG_DONT_START_ON_BOOT) == 0) { 
			start_app(app);
		}
	}
}

apps_init()的邏輯很簡單,可以猜測aboot_init一定是aboot->init,for循環輪到aboot的時候,就自然調用了aboot_init。

以下代碼也證實了我們的猜測:

APP_START(aboot)           // 增加一個name爲aboot的app
	.init = aboot_init,    //該app的ini賦值爲aboot_init
APP_END

接下來是真正的重頭戲:aboot_init()

void aboot_init(const struct app_descriptor *app)
{
	unsigned reboot_mode = 0;
	int boot_err_type = 0;
	int boot_slot = INVALID;

	/* Initialise wdog to catch early lk crashes */
#if WDOG_SUPPORT
	msm_wdog_init();
#endif

	/* Setup page size information for nv storage */
	if (target_is_emmc_boot())  //檢測是emmc還是flash存儲,並設置頁大小,一般是2048
	{
		page_size = mmc_page_size();
		page_mask = page_size - 1;
		mmc_blocksize = mmc_get_device_blocksize();
		mmc_blocksize_mask = mmc_blocksize - 1;
	}
	else
	{
		page_size = flash_page_size();
		page_mask = page_size - 1;
	}
	ASSERT((MEMBASE + MEMSIZE) > MEMBASE);    //斷言,如果內存基地址+內存大小小於內存基地址,則直接終止錯誤

	read_device_info(&device);           //從devinfo分區表read data到device結構體  
	read_allow_oem_unlock(&device);       //devinfo分區裏記錄了unlock狀態,從device中讀取此信息

	/* Detect multi-slot support */
	if (partition_multislot_is_supported())
	{
		boot_slot = partition_find_active_slot();
		if (boot_slot == INVALID)
		{
			boot_into_fastboot = true;
			dprintf(INFO, "Active Slot: (INVALID)\n");
		}
		else
		{
			/* Setting the state of system to boot active slot */
			partition_mark_active_slot(boot_slot);
			dprintf(INFO, "Active Slot: (%s)\n", SUFFIX_SLOT(boot_slot));
		}
	}

	/* Display splash screen if enabled */
#if DISPLAY_SPLASH_SCREEN
#if NO_ALARM_DISPLAY
	if (!check_alarm_boot()) {
#endif
		dprintf(SPEW, "Display Init: Start\n");
#if DISPLAY_HDMI_PRIMARY
	if (!strlen(device.display_panel))
		strlcpy(device.display_panel, DISPLAY_PANEL_HDMI,
			sizeof(device.display_panel));
#endif
#if ENABLE_WBC
		/* Wait if the display shutdown is in progress */
		while(pm_app_display_shutdown_in_prgs());
		if (!pm_appsbl_display_init_done())
			target_display_init(device.display_panel);//顯示splash,Splash也就是應用程序啓動之前先啓動一個畫面,上面簡單的介紹應用程序的廠商,廠商的LOGO,名稱和版本等信息,多爲一張圖片     
		else
			display_image_on_screen();
#else
		target_display_init(device.display_panel);
#endif
		dprintf(SPEW, "Display Init: Done\n");
#if NO_ALARM_DISPLAY
	}
#endif
#endif

	target_serialno((unsigned char *) sn_buf);
	dprintf(SPEW,"serial number: %s\n",sn_buf);

	memset(display_panel_buf, '\0', MAX_PANEL_BUF_SIZE);

	/*
	 * Check power off reason if user force reset,
	 * if yes phone will do normal boot.
	 */
	if (is_user_force_reset())     //如果強制重啓,直接進入normal_boot
		goto normal_boot;

	/* Check if we should do something other than booting up */
	if (keys_get_state(KEY_VOLUMEUP) && keys_get_state(KEY_VOLUMEDOWN))  //如果按下音量上下鍵,boot_init_fastboot = ture
	{
		dprintf(ALWAYS,"dload mode key sequence detected\n");
		reboot_device(EMERGENCY_DLOAD);
		dprintf(CRITICAL,"Failed to reboot into dload mode\n");

		boot_into_fastboot = true;
	}
	if (!boot_into_fastboot) 
	{
		if (keys_get_state(KEY_HOME) || keys_get_state(KEY_VOLUMEUP))  //按下home+音量上 boot_into_recovery = 1
			boot_into_recovery = 1;
		if (!boot_into_recovery &&
			(keys_get_state(KEY_BACK) || keys_get_state(KEY_VOLUMEDOWN)))  //按下back+音量下,boot_into_fastboot = true
			boot_into_fastboot = true;
	}
	#if NO_KEYPAD_DRIVER
	if (fastboot_trigger())
		boot_into_fastboot = true;
	#endif

#if USE_PON_REBOOT_REG
	reboot_mode = check_hard_reboot_mode();
#else
	reboot_mode = check_reboot_mode();   //檢測開機原因,修改相應的標誌位
#endif
	if (reboot_mode == RECOVERY_MODE)
	{
		boot_into_recovery = 1;
	}
	else if(reboot_mode == FASTBOOT_MODE)
	{
		boot_into_fastboot = true;
	}
	else if(reboot_mode == ALARM_BOOT)
	{
		boot_reason_alarm = true;
	}
#if VERIFIED_BOOT
	else if (VB_M <= target_get_vb_version())
	{
		if (reboot_mode == DM_VERITY_ENFORCING)
		{
			device.verity_mode = 1;
			write_device_info(&device);
		}
#if ENABLE_VB_ATTEST
		else if (reboot_mode == DM_VERITY_EIO)
#else
		else if (reboot_mode == DM_VERITY_LOGGING)
#endif
		{
			device.verity_mode = 0;
			write_device_info(&device);
		}
		else if (reboot_mode == DM_VERITY_KEYSCLEAR)
		{
			if(send_delete_keys_to_tz())
				ASSERT(0);
		}
	}
#endif

normal_boot:    //正常boot
	if (!boot_into_fastboot)
	{
		if (target_is_emmc_boot())
		{
			if(emmc_recovery_init())
				dprintf(ALWAYS,"error in emmc_recovery_init\n");
			if(target_use_signed_kernel())
			{
				if((device.is_unlocked) || (device.is_tampered))
				{
				#ifdef TZ_TAMPER_FUSE
					set_tamper_fuse_cmd(HLOS_IMG_TAMPER_FUSE);
				#endif
				#if USE_PCOM_SECBOOT
					set_tamper_flag(device.is_tampered);
				#endif
				}
			}

retry_boot:  
			/* Trying to boot active partition */
			if (partition_multislot_is_supported())
			{
				boot_slot = partition_find_boot_slot();
				partition_mark_active_slot(boot_slot);
				if (boot_slot == INVALID)
					goto fastboot;
			}

			boot_err_type = boot_linux_from_mmc();  //單獨分析這個函數,很重要
			switch (boot_err_type)
			{
				case ERR_INVALID_PAGE_SIZE:
				case ERR_DT_PARSE:
				case ERR_ABOOT_ADDR_OVERLAP:
				case ERR_INVALID_BOOT_MAGIC:
					if(partition_multislot_is_supported())
					{
						/*
						 * Deactivate current slot, as it failed to
						 * boot, and retry next slot.
						 */
						partition_deactivate_slot(boot_slot);
						goto retry_boot;
					}
					else
						break;
				default:
					break;
				/* going to fastboot menu */
			}
		}
		else
		{
			recovery_init();
	#if USE_PCOM_SECBOOT
		if((device.is_unlocked) || (device.is_tampered))
			set_tamper_flag(device.is_tampered);
	#endif
			boot_linux_from_flash();
		}
		dprintf(CRITICAL, "ERROR: Could not do normal boot. Reverting "
			"to fastboot mode.\n");
	}

fastboot:  //下面的代碼是fastboot的準備工作,從中可以看出,進入fastboot模式是不啓動kernel的
	/* We are here means regular boot did not happen. Start fastboot. */

	/* register aboot specific fastboot commands */
	aboot_fastboot_register_commands();  //此函數是fastboot支持的命令,如flash、erase等等

	/* dump partition table for debug info */
	partition_dump();

	/* initialize and start fastboot */
	fastboot_init(target_get_scratch_address(), target_get_max_flash_size());  //初始化fastboot
#if FBCON_DISPLAY_MSG
	display_fastboot_menu();   //顯示fastboot界面
#endif
}

device_info是一個用來存放某些信息的結構體:

struct device_info
{
    unsigned char magic[DEVICE_MAGIC_SIZE];
    bool is_unlocked;
    bool is_tampered;
    bool is_verified;
    bool charger_screen_enabled;
    char display_panel[MAX_PANEL_ID_LEN];
    char bootloader_version[MAX_VERSION_LEN];
    char radio_version[MAX_VERSION_LEN];
};

devinfo
Device information including:iis_unlocked, is_tampered, is_verified, charger_screen_enabled, display_panel, bootloader_version, radio_version, All these attirbutes are set based on some specific conditions and written on devinfo partition.


從以上的源碼分析中,aboot_init()所做的工作大致如下

1).確定page_size大小;

2).從devinfo分區獲取devinfo信息;

3).通過不同按鍵選擇設置對應標誌位boot_into_xxx;

4).如果進入fastboot模式,初始化fastboot命令等。

5).進入boot_linux_from_mmc()函數。


程序走到這,說明沒有進入fastboot模式,可能的情況有:正常啓動,進入recovery,開機鬧鐘啓動。

boot_linux_from_mmc()主要做下面的事情

1).程序會從boot分區或者recovery分區的header中讀取地址等信息,然後把kernel、ramdisk加載到內存中。

2).程序會從misc分區中讀取bootloader_message結構體,如果有boot-recovery,則進入recovery模式

3).更新cmdline,然後把cmdline寫到tags_addr地址,把參數傳給kernel,kernel起來以後會到這個地址讀取參數。

int boot_linux_from_mmc(void)
{
	//首先創建一個用來保存boot.img文件頭信息的變量hdr,buf是一個4096byte的數組,hdr和hdr指向了同一個內存地址
	struct boot_img_hdr *hdr = (void*) buf;
	struct boot_img_hdr *uhdr;
	unsigned offset = 0;
	int rcode;
	unsigned long long ptn = 0;
	int index = INVALID_PTN;

	unsigned char *image_addr = 0;
	unsigned kernel_actual;
	unsigned ramdisk_actual;
	unsigned imagesize_actual;
	unsigned second_actual = 0;

	unsigned int dtb_size = 0;
	unsigned int out_len = 0;
	unsigned int out_avai_len = 0;
	unsigned char *out_addr = NULL;
	uint32_t dtb_offset = 0;
	unsigned char *kernel_start_addr = NULL;
	unsigned int kernel_size = 0;
	unsigned int patched_kernel_hdr_size = 0;
	int rc;
#if VERIFIED_BOOT_2
	int status;
#endif
	char *ptn_name = NULL;
#if DEVICE_TREE
	struct dt_table *table;
	struct dt_entry dt_entry;
	unsigned dt_table_offset;
	uint32_t dt_actual;
	uint32_t dt_hdr_size;
	unsigned char *best_match_dt_addr = NULL;
#endif
	struct kernel64_hdr *kptr = NULL;
	int current_active_slot = INVALID;
	
	if (check_format_bit()) //執行check_format_bit,根據bootselect分區信息判斷是否進入recovery模式
		boot_into_recovery = 1;
		
	//此時有兩種可能,正常開機/進入ffbm(工廠測試)模式,進入ffbm模式是正行啓動,但是向kernel傳參會多一個字符
	//串"androidboot.mode='ffbm_mode_string'" 
	
	if (!boot_into_recovery) { 
		memset(ffbm_mode_string, '\0', sizeof(ffbm_mode_string));
		rcode = get_ffbm(ffbm_mode_string, sizeof(ffbm_mode_string));
		if (rcode <= 0) {
			boot_into_ffbm = false;
			if (rcode < 0)
				dprintf(CRITICAL,"failed to get ffbm cookie");
		} else
			boot_into_ffbm = true;
	} else
		boot_into_ffbm = false;
		
	uhdr = (struct boot_img_hdr *)EMMC_BOOT_IMG_HEADER_ADDR; //uhdr指向boot分區header地址
	if (!memcmp(uhdr->magic, BOOT_MAGIC, BOOT_MAGIC_SIZE)) { // //檢查uhdr->magic 是否等於 "ANDROID!"
		dprintf(INFO, "Unified boot method!\n");
		hdr = uhdr;
		goto unified_boot;
	}

	if (boot_into_recovery &&
		(!partition_multislot_is_supported()))
			ptn_name = "recovery";   支持recovery分區
	else
			ptn_name = "boot";   //支持boot分區

	index = partition_get_index(ptn_name); //讀取對應分區
	ptn = partition_get_offset(index);     //讀取對應分區的偏移量
	if(ptn == 0) {
		dprintf(CRITICAL, "ERROR: No %s partition found\n", ptn_name);
		return -1;
	}

	/* Set Lun for boot & recovery partitions */
	mmc_set_lun(partition_get_lun(index));   //調用mmc_set_lun設置boot或recovery分區的lun號
	
	//調用mmc_read,從boot或者recovery分區讀取1字節的內容到buf(hdr)中
	//我們知道在boot/recovery中開始的1字節存放的是hdr的內容
	if (mmc_read(ptn + offset, (uint32_t *) buf, page_size)) {
		dprintf(CRITICAL, "ERROR: Cannot read boot image header\n");
                return -1;
	}
	//上面已經從boot/recovery分區讀取了header到hdr,這裏對比magic是否等於"ANDROID!"
	//如果不是,則表明讀取的header是錯誤的,也算是校驗吧
	if (memcmp(hdr->magic, BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
		dprintf(CRITICAL, "ERROR: Invalid boot image header\n");
                return ERR_INVALID_BOOT_MAGIC;
	}
	
	 //比較也的大小是否相同(應該都是相同的2048字節),判斷是否需要更新頁大小。
	if (hdr->page_size && (hdr->page_size != page_size)) {

		if (hdr->page_size > BOOT_IMG_MAX_PAGE_SIZE) {
			dprintf(CRITICAL, "ERROR: Invalid page size\n");
			return -1;
		}
		page_size = hdr->page_size;
		page_mask = page_size - 1;
	}
	
	//kernel、ramdisk,second大小向上頁對齊
	kernel_actual  = ROUND_TO_PAGE(hdr->kernel_size,  page_mask);
	ramdisk_actual = ROUND_TO_PAGE(hdr->ramdisk_size, page_mask);
	second_actual  = ROUND_TO_PAGE(hdr->second_size, page_mask);

	image_addr = (unsigned char *)target_get_scratch_address();
	memcpy(image_addr, (void *)buf, page_size);

	/* ensure commandline is terminated */
        hdr->cmdline[BOOT_ARGS_SIZE-1] = 0;

#if DEVICE_TREE   //如果有DEVICE_TREE
#ifndef OSVERSION_IN_BOOTIMAGE
	dt_size = hdr->dt_size;
#endif
	dt_actual = ROUND_TO_PAGE(dt_size, page_mask); //計算出dt所佔的頁的大小
	if (UINT_MAX < ((uint64_t)kernel_actual + (uint64_t)ramdisk_actual+ (uint64_t)second_actual + (uint64_t)dt_actual + page_size)) {
		dprintf(CRITICAL, "Integer overflow detected in bootimage header fields at %u in %s\n",__LINE__,__FILE__);
		return -1;
	}
	// image佔的頁的總大小
	imagesize_actual = (page_size + kernel_actual + ramdisk_actual + second_actual + dt_actual);
#else
	if (UINT_MAX < ((uint64_t)kernel_actual + (uint64_t)ramdisk_actual + (uint64_t)second_actual + page_size)) {
		dprintf(CRITICAL, "Integer overflow detected in bootimage header fields at %u in %s\n",__LINE__,__FILE__);
		return -1;
	}
	imagesize_actual = (page_size + kernel_actual + ramdisk_actual + second_actual);
#endif

#if VERIFIED_BOOT
	boot_verifier_init(); //初始化boot.img的鑑權,讀取OEM 和User Keystore(即校驗boot)
#endif
	//檢查boot.img是否與aboot的內存空間有重疊
	if (check_aboot_addr_range_overlap((uintptr_t) image_addr, imagesize_actual))
	{
		dprintf(CRITICAL, "Boot image buffer address overlaps with aboot addresses.\n");
		return -1;
	}

	/*
	 * Update loading flow of bootimage to support compressed/uncompressed
	 * bootimage on both 64bit and 32bit platform.
	 * 1. Load bootimage from emmc partition onto DDR.
	 * 2. Check if bootimage is gzip format. If yes, decompress compressed kernel
	 * 3. Check kernel header and update kernel load addr for 64bit and 32bit
	 *    platform accordingly.
	 * 4. Sanity Check on kernel_addr and ramdisk_addr and copy data.
	 */
	if (partition_multislot_is_supported())
	{
		current_active_slot = partition_find_active_slot();
		dprintf(INFO, "Loading boot image (%d) active_slot(%s): start\n",
				imagesize_actual, SUFFIX_SLOT(current_active_slot));
	}
	else
	{
		dprintf(INFO, "Loading (%s) image (%d): start\n",
				(!boot_into_recovery ? "boot" : "recovery"),imagesize_actual);
	}
	bs_set_timestamp(BS_KERNEL_LOAD_START);

	if ((target_get_max_flash_size() - page_size) < imagesize_actual)
	{
		dprintf(CRITICAL, "booimage  size is greater than DDR can hold\n");
		return -1;
	}
	offset = page_size;
	/* Read image without signature and header*/
	if (mmc_read(ptn + offset, (void *)(image_addr + offset), imagesize_actual - page_size))
	{
		dprintf(CRITICAL, "ERROR: Cannot read boot image\n");
		return -1;
	}

	if (partition_multislot_is_supported())
	{
		dprintf(INFO, "Loading boot image (%d) active_slot(%s): done\n",
				imagesize_actual, SUFFIX_SLOT(current_active_slot));
	}
	else
	{
		dprintf(INFO, "Loading (%s) image (%d): done\n",
			(!boot_into_recovery ? "boot" : "recovery"),imagesize_actual);

	}
	bs_set_timestamp(BS_KERNEL_LOAD_DONE);

	/* Authenticate Kernel */
	dprintf(INFO, "use_signed_kernel=%d, is_unlocked=%d, is_tampered=%d.\n",
		(int) target_use_signed_kernel(),
		device.is_unlocked,
		device.is_tampered);
#if VERIFIED_BOOT_2
	offset = imagesize_actual;
	if (check_aboot_addr_range_overlap((uintptr_t)image_addr + offset, page_size))
	{
		dprintf(CRITICAL, "Signature read buffer address overlaps with aboot addresses.\n");
		return -1;
	}

	/* Read signature */
	if(mmc_read(ptn + offset, (void *)(image_addr + offset), page_size))
	{
		dprintf(CRITICAL, "ERROR: Cannot read boot image signature\n");
		return -1;
	}

	memset(&info, 0, sizeof(bootinfo));
	info.images[0].image_buffer = image_addr;
	info.images[0].imgsize = imagesize_actual;
	info.images[0].name = "boot";
	info.num_loaded_images = 0;
	info.multi_slot_boot = partition_multislot_is_supported();
	info.bootreason_alarm = boot_reason_alarm;
	info.bootinto_recovery = boot_into_recovery;
	status = load_image_and_auth(&info);
	if(status)
		return -1;

	vbcmdline = info.vbcmdline;
#else
	/* Change the condition a little bit to include the test framework support.
	 * We would never reach this point if device is in fastboot mode, even if we did
	 * that means we are in test mode, so execute kernel authentication part for the
	 * tests */
	if((target_use_signed_kernel() && (!device.is_unlocked)) || is_test_mode_enabled()) //這裏是false
	{
		offset = imagesize_actual;
		if (check_aboot_addr_range_overlap((uintptr_t)image_addr + offset, page_size))
		{
			dprintf(CRITICAL, "Signature read buffer address overlaps with aboot addresses.\n");
			return -1;
		}

		/* Read signature */
		if(mmc_read(ptn + offset, (void *)(image_addr + offset), page_size))
		{
			dprintf(CRITICAL, "ERROR: Cannot read boot image signature\n");
			return -1;
		}

		verify_signed_bootimg((uint32_t)image_addr, imagesize_actual);
		/* The purpose of our test is done here */
		if(is_test_mode_enabled() && auth_kernel_img)
			return 0;
	} else {
		second_actual  = ROUND_TO_PAGE(hdr->second_size,  page_mask);
		#ifdef TZ_SAVE_KERNEL_HASH
		aboot_save_boot_hash_mmc((uint32_t) image_addr, imagesize_actual);
		#endif /* TZ_SAVE_KERNEL_HASH */

#ifdef MDTP_SUPPORT
		{
			/* Verify MDTP lock.
			 * For boot & recovery partitions, MDTP will use boot_verifier APIs,
			 * since verification was skipped in aboot. The signature is not part of the loaded image.
			 */
			mdtp_ext_partition_verification_t ext_partition;
			ext_partition.partition = boot_into_recovery ? MDTP_PARTITION_RECOVERY : MDTP_PARTITION_BOOT;
			ext_partition.integrity_state = MDTP_PARTITION_STATE_UNSET;
			ext_partition.page_size = page_size;
			ext_partition.image_addr = (uint32)image_addr;
			ext_partition.image_size = imagesize_actual;
			ext_partition.sig_avail = FALSE;
			mdtp_fwlock_verify_lock(&ext_partition);
		}
#endif /* MDTP_SUPPORT */
	}
#endif

#if VERIFIED_BOOT
	if((boot_verify_get_state() == ORANGE) && (!boot_into_ffbm))  //校驗boot
	{
#if FBCON_DISPLAY_MSG
		display_bootverify_menu(DISPLAY_MENU_ORANGE);
		wait_for_users_action();
#else
		//dprintf(CRITICAL,
		//	"Your device has been unlocked and can't be trusted.\nWait for 5 seconds before proceeding\n");
		//mdelay(5000);
#endif
	}
#endif

#if VERIFIED_BOOT
	if (VB_M == target_get_vb_version())
	{
		/* set boot and system versions. */
		set_os_version((unsigned char *)image_addr);
		// send root of trust
		if(!send_rot_command((uint32_t)device.is_unlocked))
			ASSERT(0);
	}
#endif
	/*
	 * Check if the kernel image is a gzip package. If yes, need to decompress it.
	 * If not, continue booting.
	 */
	if (is_gzip_package((unsigned char *)(image_addr + page_size), hdr->kernel_size))
	{
		out_addr = (unsigned char *)(image_addr + imagesize_actual + page_size);
		out_avai_len = target_get_max_flash_size() - imagesize_actual - page_size;
		dprintf(INFO, "decompressing kernel image: start\n");
		rc = decompress((unsigned char *)(image_addr + page_size),
				hdr->kernel_size, out_addr, out_avai_len,
				&dtb_offset, &out_len);
		if (rc)
		{
			dprintf(CRITICAL, "decompressing kernel image failed!!!\n");
			ASSERT(0);
		}

		dprintf(INFO, "decompressing kernel image: done\n");
		kptr = (struct kernel64_hdr *)out_addr;
		kernel_start_addr = out_addr;
		kernel_size = out_len;
	} else {
		dprintf(INFO, "Uncpmpressed kernel in use\n");
		if (!strncmp((char*)(image_addr + page_size),
					PATCHED_KERNEL_MAGIC,
					sizeof(PATCHED_KERNEL_MAGIC) - 1)) {
			dprintf(INFO, "Patched kernel detected\n");
			kptr = (struct kernel64_hdr *)(image_addr + page_size +
					PATCHED_KERNEL_HEADER_SIZE);
			//The size of the kernel is stored at start of kernel image + 16
			//The dtb would start just after the kernel
			dtb_offset = *((uint32_t*)((unsigned char*)
						(image_addr + page_size +
						 sizeof(PATCHED_KERNEL_MAGIC) -
						 1)));
			//The actual kernel starts after the 20 byte header.
			kernel_start_addr = (unsigned char*)(image_addr +
					page_size + PATCHED_KERNEL_HEADER_SIZE);
			kernel_size = hdr->kernel_size;
			patched_kernel_hdr_size = PATCHED_KERNEL_HEADER_SIZE;
		} else {
			dprintf(INFO, "Kernel image not patched..Unable to locate dt offset\n");
			kptr = (struct kernel64_hdr *)(image_addr + page_size);
			kernel_start_addr = (unsigned char *)(image_addr + page_size);
			kernel_size = hdr->kernel_size;
		}
	}

	/*
	 * Update the kernel/ramdisk/tags address if the boot image header
	 * has default values, these default values come from mkbootimg when
	 * the boot image is flashed using fastboot flash:raw
	 */
	update_ker_tags_rdisk_addr(hdr, IS_ARM64(kptr));

	/* Get virtual addresses since the hdr saves physical addresses. */
	//將hdr中保存的物理地址轉化爲虛擬地址
	hdr->kernel_addr = VA((addr_t)(hdr->kernel_addr));
	hdr->ramdisk_addr = VA((addr_t)(hdr->ramdisk_addr));
	hdr->tags_addr = VA((addr_t)(hdr->tags_addr));

	kernel_size = ROUND_TO_PAGE(kernel_size,  page_mask);
	/* Check if the addresses in the header are valid. */
	if (check_aboot_addr_range_overlap(hdr->kernel_addr, kernel_size) ||
		check_ddr_addr_range_bound(hdr->kernel_addr, kernel_size) ||
		check_aboot_addr_range_overlap(hdr->ramdisk_addr, ramdisk_actual) ||
		check_ddr_addr_range_bound(hdr->ramdisk_addr, ramdisk_actual))
	{
		dprintf(CRITICAL, "kernel/ramdisk addresses are not valid.\n");
		return -1;
	}

#ifndef DEVICE_TREE
	if (check_aboot_addr_range_overlap(hdr->tags_addr, MAX_TAGS_SIZE) ||
		check_ddr_addr_range_bound(hdr->tags_addr, MAX_TAGS_SIZE))
	{
		dprintf(CRITICAL, "Tags addresses are not valid.\n");
		return -1;
	}
#endif

	/* Move kernel, ramdisk and device tree to correct address */
	memmove((void*) hdr->kernel_addr, kernel_start_addr, kernel_size);
	memmove((void*) hdr->ramdisk_addr, (char *)(image_addr + page_size + kernel_actual), hdr->ramdisk_size);

	#if DEVICE_TREE
	if(dt_size) {
		dt_table_offset = ((uint32_t)image_addr + page_size + kernel_actual + ramdisk_actual + second_actual);
		table = (struct dt_table*) dt_table_offset;

		if (dev_tree_validate(table, hdr->page_size, &dt_hdr_size) != 0) {
			dprintf(CRITICAL, "ERROR: Cannot validate Device Tree Table \n");
			return -1;
		}

		/* Its Error if, dt_hdr_size (table->num_entries * dt_entry size + Dev_Tree Header)
		goes beyound hdr->dt_size*/
		if (dt_hdr_size > ROUND_TO_PAGE(dt_size,hdr->page_size)) {
			dprintf(CRITICAL, "ERROR: Invalid Device Tree size \n");
			return -1;
		}

		/* Find index of device tree within device tree table */
		if(dev_tree_get_entry_info(table, &dt_entry) != 0){
			dprintf(CRITICAL, "ERROR: Getting device tree address failed\n");
			return -1;
		}

		if(dt_entry.offset > (UINT_MAX - dt_entry.size)) {
			dprintf(CRITICAL, "ERROR: Device tree contents are Invalid\n");
			return -1;
		}

		/* Ensure we are not overshooting dt_size with the dt_entry selected */
		if ((dt_entry.offset + dt_entry.size) > dt_size) {
			dprintf(CRITICAL, "ERROR: Device tree contents are Invalid\n");
			return -1;
		}
		//檢測kernel image是否是gzip的包,如果是,解壓,如果不是,繼續boot。得到kernel的起始地址和大小
		if (is_gzip_package((unsigned char *)dt_table_offset + dt_entry.offset, dt_entry.size))
		{
			unsigned int compressed_size = 0;
			out_addr += out_len;
			out_avai_len -= out_len;
			dprintf(INFO, "decompressing dtb: start\n");
			rc = decompress((unsigned char *)dt_table_offset + dt_entry.offset,
					dt_entry.size, out_addr, out_avai_len,
					&compressed_size, &dtb_size);
			if (rc)
			{
				dprintf(CRITICAL, "decompressing dtb failed!!!\n");
				ASSERT(0);
			}

			dprintf(INFO, "decompressing dtb: done\n");
			best_match_dt_addr = out_addr;
		} else {
			best_match_dt_addr = (unsigned char *)dt_table_offset + dt_entry.offset;
			dtb_size = dt_entry.size;
		}

		/* Validate and Read device device tree in the tags_addr */
		//檢測kernel/ramdisk/tags地址是否超出emmc地址
		if (check_aboot_addr_range_overlap(hdr->tags_addr, dtb_size) || 
			check_ddr_addr_range_bound(hdr->tags_addr, dtb_size))
		{
			dprintf(CRITICAL, "Device tree addresses are not valid\n");
			return -1;
		}

		memmove((void *)hdr->tags_addr, (char *)best_match_dt_addr, dtb_size);
	} else {
		/* Validate the tags_addr */
		if (check_aboot_addr_range_overlap(hdr->tags_addr, kernel_actual) ||
			check_ddr_addr_range_bound(hdr->tags_addr, kernel_actual))
		{
			dprintf(CRITICAL, "Device tree addresses are not valid.\n");
			return -1;
		}
		/*
		 * If appended dev tree is found, update the atags with
		 * memory address to the DTB appended location on RAM.
		 * Else update with the atags address in the kernel header
		 */
		void *dtb;
		dtb = dev_tree_appended(
				(void*)(image_addr + page_size +
					patched_kernel_hdr_size),
				hdr->kernel_size, dtb_offset,
				(void *)hdr->tags_addr);
		if (!dtb) {
			dprintf(CRITICAL, "ERROR: Appended Device Tree Blob not found\n");
			return -1;
		}
	}
	#endif

	if (boot_into_recovery && !device.is_unlocked && !device.is_tampered)
		target_load_ssd_keystore();

unified_boot:

	//最後在函數返回前,將會執行到boot_linux,在boot_linux中將會完成跳轉到內核的操作。
	boot_linux((void *)hdr->kernel_addr, (void *)hdr->tags_addr,
		   (const char *)hdr->cmdline, board_machtype(),
		   (void *)hdr->ramdisk_addr, hdr->ramdisk_size);

	return 0;
}

至此LK的源碼分析完畢。還需要補充emmc,boot.img , recovery.img 和各種分區部分的知識。

參考文章:
Android 開發之 ---- bootloader (LK)https://blog.csdn.net/jmq_0000/article/details/7378348
Android啓動流程分析之二:內核的引導 https://blog.csdn.net/ffmxnjm/article/details/70598711
MSM8909+Android5.1.1啓動流程(7)—boot_linux_from_mmc() https://www.2cto.com/kf/201608/543311.html
lk啓動流程詳細分析 https://www.cnblogs.com/xiaolei-kaiyuan/p/5458145.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章