Linux启动流程_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

猜你喜欢

转载自blog.csdn.net/qq_35065875/article/details/82502273
今日推荐