Lk启动流程分析

9 篇文章 1 订阅
5 篇文章 1 订阅

1 Lk概述

LK是(L)ittle(K)ernel的缩写。目前android平台普遍采用lk作为其bootloader,LK是一个开源项目。但是,LK只是整个系统的引导部分,所以它不是独立存在。LK是一个功能及其强大的bootloader,但现在只支持arm和x86平台。
LK的一个显著的特点就是它实现了一个简单的线程机制(thread),和对高通处理器的深度定制和使用。

2 源代码目录

app //主函数启动app执行的目录,第一个app在app/aboot/aboot.c中
arch //体系代码包含x86和arm
dev //设备目录,包含显示器,键盘,net,usb等设备的初始化代码
include //头文件
kernel //kernel/main.c主函数以及kernel/thread.c线程函数
lib //库文件
make //编译规则
platform //不同平台代码mdmxxx,msmxxx,apqxxx,qsdxxx,还有共享的目录msm_shared
project //整个工程的编译规则
target //通用init.c,具体目标板的初始化(主要为板子设备资源init.c代码中)

3 Lk入口

3.1 bootable\bootloader\lk\arch\arm\rule.mk文件下相关部分:

# potentially generated files that should be cleaned out with clean make rule
GENERATED += \
    $(BUILDDIR)/system-onesegment.ld \
    $(BUILDDIR)/system-twosegment.ld

# rules for generating the linker scripts

$(BUILDDIR)/trustzone-test-system-onesegment.ld: $(LOCAL_DIR)/trustzone-test-system-onesegment.ld $(LK_TOP_DIR)/target/$(TARGET)/rules.mk .FORCE
    @echo generating $@
    @$(MKDIR)
    $(NOECHO)sed "s/%MEMBASE%/$(MEMBASE)/;s/%MEMSIZE%/$(MEMSIZE)/;s/%ROMLITE_PREFLASHED_DATA%/$(ROMLITE_PREFLASHED_DATA)/" < $< > $@

$(BUILDDIR)/trustzone-system-onesegment.ld: $(LOCAL_DIR)/trustzone-system-onesegment.ld $(LK_TOP_DIR)/target/$(TARGET)/rules.mk .FORCE
    @echo generating $@
    @$(MKDIR)
    $(NOECHO)sed "s/%MEMBASE%/$(MEMBASE)/;s/%MEMSIZE%/$(MEMSIZE)/" < $< > $@

$(BUILDDIR)/system-onesegment.ld: $(LOCAL_DIR)/system-onesegment.ld $(LK_TOP_DIR)/target/$(TARGET)/rules.mk .FORCE
    @echo generating $@
    @$(MKDIR)
    $(NOECHO)sed "s/%MEMBASE%/$(MEMBASE)/;s/%MEMSIZE%/$(MEMSIZE)/" < $< > $@

$(BUILDDIR)/system-twosegment.ld: $(LOCAL_DIR)/system-twosegment.ld $(LK_TOP_DIR)/target/$(TARGET)/rules.mk .FORCE
    @echo generating $@
    @$(MKDIR)
    $(NOECHO)sed "s/%ROMBASE%/$(ROMBASE)/;s/%MEMBASE%/$(MEMBASE)/;s/%MEMSIZE%/$(MEMSIZE)/" < $< > $@

3.2 arch/arm/system-onesegment.ld

OUTPUT_FORMAT("elf32-littlearm", "elf32-littlearm", "elf32-littlearm")
OUTPUT_ARCH(arm)

ENTRY(_start)   /*跳入crt0.S文件执行代码*/
3.3 arch/arm/crt0.S
.section ".text.boot"
.globl _start
_start:
    b   reset
    b   arm_undefined
    b   arm_syscall
    b   arm_prefetch_abort
    b   arm_data_abort
    b   arm_reserved
    b   arm_irq
    b   arm_fiq

reset:
……

    bl      kmain
    b       
……

4 kmain函数

bootable/bootloader/lk/kernel/main.c

/* called from crt0.S */
void kmain(void) __NO_RETURN __EXTERNALLY_VISIBLE;
void kmain(void)
{
    // get us into some sort of thread context
    thread_init_early();        //初始化线程上下文

    // early arch stuff
    arch_early_init();      //架构初始化,如关闭cache,使能mmu

    // do any super early platform initialization
    platform_early_init();  //平台早期初始化

    // do any super early target initialization
    target_early_init();        //目标设备早期初始化,初始化串口

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

    // deal with any static constructors
    dprintf(SPEW, "calling constructors\n");
    call_constructors();

    // bring up the kernel heap
    dprintf(SPEW, "initializing heap\n");
    heap_init();            //堆初始化

    __stack_chk_guard_setup();

    // initialize the threading system
    dprintf(SPEW, "initializing threads\n");
    thread_init();          //线程初始化

    // initialize the dpc system
    dprintf(SPEW, "initializing dpc\n");
    dpc_init();         //lk系统控制器初始化

    // initialize kernel timers
    dprintf(SPEW, "initializing timers\n");
    timer_init();           //kernel时钟初始化

#if (!ENABLE_NANDWRITE)
    // create a thread to complete system initialization
    dprintf(SPEW, "creating bootstrap completion thread\n");
    thread_resume(thread_create("bootstrap2", &bootstrap2, NULL, DEFAULT_PRIORITY, DEFAULT_STACK_SIZE));        //创建一个线程初始化系统

    // enable interrupts
    exit_critical_section();        //使能中断

    // become the idle thread
    thread_become_idle();       //本线程切换成idle线程,idle为空闲线程,当没有更高优先级的线程时才执行
#else
        bootstrap_nandwrite();
#endif
}

4.1 arch_early_init函数

bootable/bootloader/lk/arch/arm/arch.c

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 */
    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 */
    __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); /* cycle count every cycle */
    en |= 1; /* enable all performance counters */
    __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
}

4.2 platform_early_init函数

bootable/bootloader/lk/platform/msm8953/platform.c

void platform_early_init(void)
{
    board_init();   //主板初始化
    platform_clock_init();  //平台时钟初始化
    qgic_init();    //中断控制器初始化
    qtimer_init();  //定时器初始化
    scm_init(); //
}

4.3 target_early_init函数

bootable/bootloader/lk/ target/msm8953/init.c

void target_early_init(void)
{
#if WITH_DEBUG_UART
     uart_dm_init(1, 0, BLSP1_UART0_BASE);  //串口初始化
#endif
}
5. timer_init函数
bootable/bootloader/lk/ kernel/timer.c
void timer_init(void)
{
    list_initialize(&timer_queue);

    /* register for a periodic timer tick */
    platform_set_periodic_timer(timer_tick, NULL, 10); /* 10ms */
}

4.4 bootstrap2函数分析

bootable/bootloader/lk/kernel/main.c

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();      //目标设备初始化,见1.1

    dprintf(SPEW, "calling apps_init()\n");
    apps_init();        //lk应用初始化,见1.2

    return 0;
}
4.4.1 target_init函数

bootable/bootloader/lk/target/msm8953/init.c

void target_init(void)
{
#if VERIFIED_BOOT
#if !VBOOT_MOTA
    int ret = 0;
#endif
#endif
    dprintf(INFO, "target_init()\n");

    spmi_init(PMIC_ARB_CHANNEL_NUM, PMIC_ARB_OWNER_ID); //初始化spmi 控制器

    target_keystatus();

    target_sdc_init();      //sd card 初始化,内部包含了mmc的初始化
    if (partition_read_table())     //读取分区表
    {
        dprintf(CRITICAL, "Error reading the partition table info\n");
        ASSERT(0);
    }

#if LONG_PRESS_POWER_ON
    shutdown_detect();
#endif

#if PON_VIB_SUPPORT
    vib_timed_turn_on(VIBRATE_TIME);
#endif


    if (target_use_signed_kernel())
        target_crypto_init_params();

#if VERIFIED_BOOT
#if !VBOOT_MOTA
    clock_ce_enable(CE1_INSTANCE);

    /* Initialize Qseecom */
    ret = qseecom_init();   //qse 初始化

    if (ret < 0)
    {
        dprintf(CRITICAL, "Failed to initialize qseecom, error: %d\n", ret);
        ASSERT(0);
    }

    /* Start Qseecom */
    ret = qseecom_tz_init(); //qse tz初始化

    if (ret < 0)
    {
        dprintf(CRITICAL, "Failed to start qseecom, error: %d\n", ret);
        ASSERT(0);
    }

    if (rpmb_init() < 0)  //rpmb 初始化(Replay Protected Memory Block,emmc中的一个分区,总共五个分区:BOOT Area Partition 1,BOOT Area Partition 2,RPMB,User Data Area,Vender private area)
    {
        dprintf(CRITICAL, "RPMB init failed\n");
        ASSERT(0);
    }

    /*
     * Load the sec app for first time
     */
    if (load_sec_app() < 0)         //加载安全app
    {
        dprintf(CRITICAL, "Failed to load App for verified\n");
        ASSERT(0);
    }
#endif
#endif

#if SMD_SUPPORT
    rpm_smd_init(); //smd 初始化
#endif
}
4.4.2 apps_init函数

bootable/bootloader/lk/ app/app.c

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);
    }

    /* 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);
        }
    }
}
代码段:
for (app = &__apps_start; app != &__apps_end; app++) {
        if (app->init)
            app->init(app);
    }
表示进入各自的app init函数,通过下面的代码段可以分析出具体有哪些app init函数。
bootable/bootloader/lk/ arch/arm/system-onesegment.ld
.rodata : {
       ……..
        __apps_start = .;
        KEEP (*(.apps))
        __apps_end = .;
       ……..
}
bootable/bootloader/lk/ include/app.h
struct app_descriptor {
    const char *name;
    app_init  init;
    app_entry entry;
    unsigned int flags;
};
#define APP_START(appname) struct app_descriptor _app_##appname __SECTION(".apps") = { .name = #appname,
#define APP_END };
bootable/bootloader/lk/app/aboot/aboot.c
APP_START(aboot)
    .init = aboot_init,
APP_END
上面的过程表示了如何将aboot模块的aboot_init函数加入到.apps代码段。这种方式也用在clocktests 、shell、pcitests、stringtests、tests模块中,请参见一下文件:
bootable/bootloader/lk/app/clocktests/clock_tests.c:APP_START(clocktests)
bootable/bootloader/lk/app/aboot/aboot.c:APP_START(aboot)
bootable/bootloader/lk/app/shell/shell.c:APP_START(shell)
bootable/bootloader/lk/app/pcitests/pci_tests.c:APP_START(pcitests)
bootable/bootloader/lk/app/stringtests/string_tests.c:APP_START(stringtests)
bootable/bootloader/lk/app/tests/tests.c:APP_START(tests)

5 aboot_init函数分析

/bootable/bootloader/lk/app/aboot/aboot.c

void aboot_init(const struct app_descriptor *app)
{
    unsigned reboot_mode = 0;

    /* 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);          //读取device info分区的信息到device结构体中
    read_allow_oem_unlock(&device); //devinfo分区里记录了unlock状态,从device中读取此信息

    /* 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 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);
        else
            display_image_on_screen();
#else
        target_display_init(device.display_panel);  //显示splash,Splash也就是应用程序启动之前先启动一个画面,上面简单的介绍应用程序的厂商,厂商的LOGO,名称和版本等信息,多为一张图片
#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())      //判断是否是用户设置的重启
        goto normal_boot;

/* Check if we should do something other than booting up */
//判断是否进入各种模式
    if (keys_get_state(KEY_VOLUMEUP) && keys_get_state(KEY_VOLUMEDOWN))
    {
        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))
            boot_into_recovery = 1;
        if (!boot_into_recovery &&
            (keys_get_state(KEY_BACK) || keys_get_state(KEY_VOLUMEDOWN)))
            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
#if !VBOOT_MOTA
    else if (reboot_mode == DM_VERITY_ENFORCING)
    {
        device.verity_mode = 1;
        write_device_info(&device);
    }
    else if (reboot_mode == DM_VERITY_LOGGING)
    {
        device.verity_mode = 0;
        write_device_info(&device);
    }
    else if (reboot_mode == DM_VERITY_KEYSCLEAR)
    {
        if(send_delete_keys_to_tz())
            ASSERT(0);
    }
#endif
#endif

normal_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();
                #endif
                #if USE_PCOM_SECBOOT
                    set_tamper_flag(device.is_tampered);
                #endif
                }
            }

            boot_linux_from_mmc();  //跳入linux kernel启动,后面深入分析
        }
        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();    //跳入linux kernel启动,后面深入分析
        }
        dprintf(CRITICAL, "ERROR: Could not do normal boot. Reverting "
            "to fastboot mode.\n");
    }

    /* We are here means regular boot did not happen. Start fastboot. */

    /* register aboot specific fastboot commands */
    aboot_fastboot_register_commands();

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

    /* initialize and start fastboot */
    fastboot_init(target_get_scratch_address(), target_get_max_flash_size());
#if FBCON_DISPLAY_MSG
    display_fastboot_menu();    //显示fastboot菜单
#endif
}

5.1 read_device_info函数分析

  1. device_info结构体
    bootable/bootloader/lk/ app/aboot/devinfo.h
struct device_info
{
    unsigned char magic[DEVICE_MAGIC_SIZE];
    bool is_unlocked;
    bool is_tampered;
    bool is_unlock_critical;
    bool charger_screen_enabled;
    char display_panel[MAX_PANEL_ID_LEN];
    char bootloader_version[MAX_VERSION_LEN];
    char radio_version[MAX_VERSION_LEN];
};

2 read_device_info函数
bootable/bootloader/lk/ app/aboot/aboot.c

void read_device_info(device_info *dev)
{
    if(target_is_emmc_boot())
    {
        struct device_info *info = memalign(PAGE_SIZE, ROUNDUP(BOOT_IMG_MAX_PAGE_SIZE, PAGE_SIZE));     //开辟一片内存,其大小是对齐的倍数,必须是2的幂
        if(info == NULL)
        {
            dprintf(CRITICAL, "Failed to allocate memory for device info struct\n");
            ASSERT(0);
        }
        info_buf = info;

#if USE_RPMB_FOR_DEVINFO            //从rpmb中读取devinfo
        if (is_secure_boot_enable()) {
            if((read_device_info_rpmb((void*) info, PAGE_SIZE)) < 0)
                ASSERT(0);
        }
        else
            read_device_info_mmc(info);
#else
        read_device_info_mmc(info);     //从mmc中读取devinfo
#endif

        if (memcmp(info->magic, DEVICE_MAGIC, DEVICE_MAGIC_SIZE))
        {
            memcpy(info->magic, DEVICE_MAGIC, DEVICE_MAGIC_SIZE);
            if (is_secure_boot_enable()) {  //是否为安全启动
                info->is_unlocked = 0;
#if !VBOOT_MOTA
                info->is_unlock_critical = 0;
#endif
            } else {
                info->is_unlocked = 1;
#if !VBOOT_MOTA
                info->is_unlock_critical = 1;
#endif
            }
            info->is_tampered = 0;
            info->charger_screen_enabled = 0;
#if !VBOOT_MOTA
            info->verity_mode = 1; //enforcing by default
#endif
            write_device_info(info);
        }
        memcpy(dev, info, sizeof(device_info)); //回写devinfo
        free(info);
    }
    else
    {
        read_device_info_flash(dev);        //从flash中读取devinfo
    }
}

5.2 boot_linux_from_mmc分析

/bootable/bootloader/lk/app/aboot/aboot.c

int boot_linux_from_mmc(void)
{
// buf由前面BUF_DMA_ALIGN(buf, BOOT_IMG_MAX_PAGE_SIZE); 表示声明一个buf数组,并将boot img copy到其中
    //Equal to max-supported pagesize
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;
    int rc;

#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;

    if (check_format_bit()) //查找bootselect分区,并判断其是否存在相应的标志位,否则返回false
        boot_into_recovery = 1;

    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的位置
    uhdr = (struct boot_img_hdr *)EMMC_BOOT_IMG_HEADER_ADDR;
    if (!memcmp(uhdr->magic, BOOT_MAGIC, BOOT_MAGIC_SIZE)) {//校验magic是否为"ANDROID! "
        dprintf(INFO, "Unified boot method!\n");
        hdr = uhdr; //将uhdr的值赋给hdr,即buf
        goto unified_boot;
    }
    if (!boot_into_recovery) {  //正常启动
        index = partition_get_index("boot");
        ptn = partition_get_offset(index);
        if(ptn == 0) {
            dprintf(CRITICAL, "ERROR: No boot partition found\n");
                    return -1;
        }
    }
    else {
        index = partition_get_index("recovery");//进入recovery模式
        ptn = partition_get_offset(index);
        if(ptn == 0) {
            dprintf(CRITICAL, "ERROR: No recovery partition found\n");
                    return -1;
        }
    }
    /* Set Lun for boot & recovery partitions */
    mmc_set_lun(partition_get_lun(index));

    if (mmc_read(ptn + offset, (uint32_t *) buf, page_size)) {  //将bootimg读取到buf中
        dprintf(CRITICAL, "ERROR: Cannot read boot image header\n");
                return -1;
    }

    if (memcmp(hdr->magic, BOOT_MAGIC, BOOT_MAGIC_SIZE)) {//校验
        dprintf(CRITICAL, "ERROR: Invalid boot image header\n");
                return -1;
    }

    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;
    }

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

    kernel_actual  = ROUND_TO_PAGE(hdr->kernel_size,  page_mask);   //kernel所占页的总大小
    ramdisk_actual = ROUND_TO_PAGE(hdr->ramdisk_size, page_mask);   //ramdisk所占页的总大小

    image_addr = (unsigned char *)target_get_scratch_address();

#if DEVICE_TREE
    dt_actual = ROUND_TO_PAGE(hdr->dt_size, page_mask); //dt所占页的总大小
    imagesize_actual = (page_size + kernel_actual + ramdisk_actual + dt_actual);    //image所占页的总大小
#else
    imagesize_actual = (page_size + kernel_actual + ramdisk_actual);
#endif

#if VERIFIED_BOOT
    boot_verifier_init();       //校验boot
#endif

    if (check_aboot_addr_range_overlap((uintptr_t) image_addr, imagesize_actual))   //aboot和bootimage地址是否重合
    {
        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.
     */

    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)//判断image能否完全放入ddr
    {
        dprintf(CRITICAL, "booimage  size is greater than DDR can hold\n");
      return -1;
    }

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

    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);

    /* 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())
    {
        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);//校验bootimg
        /* 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);   //second_size所占页的总大小
        #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 */
    }

#if VERIFIED_BOOT
    if(boot_verify_get_state() == ORANGE)
    {
#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 !VBOOT_MOTA
    // send root of trust
    if(!send_rot_command((uint32_t)device.is_unlocked))
        ASSERT(0);
#endif
#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 {
        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));    //更新kernel/ramdisk/tags地址

    /* Get virtual addresses since the hdr saves physical addresses. */
    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_aboot_addr_range_overlap(hdr->ramdisk_addr, ramdisk_actual))
{
        dprintf(CRITICAL, "kernel/ramdisk addresses overlap with aboot addresses.\n");
        return -1;
    }

#ifndef DEVICE_TREE
    if (check_aboot_addr_range_overlap(hdr->tags_addr, MAX_TAGS_SIZE))
    {
        dprintf(CRITICAL, "Tags addresses overlap with aboot addresses.\n");
        return -1;
    }
#endif

    /* Move kernel, ramdisk and device tree to correct address */
    memmove((void*) hdr->kernel_addr, kernel_start_addr, kernel_size); //移动kernel, ramdisk and device tree到相应的地址
    memmove((void*) hdr->ramdisk_addr, (char *)(image_addr + page_size + kernel_actual), hdr->ramdisk_size);

    #if DEVICE_TREE
    if(hdr->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(hdr->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) > hdr->dt_size) {
            dprintf(CRITICAL, "ERROR: Device tree contents are Invalid\n");
            return -1;
        }

        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 */
        if (check_aboot_addr_range_overlap(hdr->tags_addr, dtb_size))
        {
            dprintf(CRITICAL, "Device tree addresses overlap with aboot addresses.\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))
        {
            dprintf(CRITICAL, "Device tree addresses overlap with aboot addresses.\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),
                    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((void *)hdr->kernel_addr, (void *)hdr->tags_addr,
           (const char *)hdr->cmdline, board_machtype(),
           (void *)hdr->ramdisk_addr, hdr->ramdisk_size);

    return 0;
}

主要完成的工作:
1.将uhdr存入hdr/buf
2.读取bootimg到内存buf/hdr中
3.判断内核是否为gzip格式,如果是则解压
4.boot linux并通过boot_linux函数传递内核的地址,tags的地址,命令行参数,ramdisk地址和大小

5.2.1 boot_img_hdr结构分析

boot_img_hdr主要存储了bootimg、ramdisk、dt的地址
bootable/bootloader/lk /app/aboot/bootimg.h

#ifndef _BOOT_IMAGE_H_
#define _BOOT_IMAGE_H_

typedef struct boot_img_hdr boot_img_hdr;

#define BOOT_MAGIC "ANDROID!"
#define BOOT_MAGIC_SIZE 8
#define BOOT_NAME_SIZE  16
#define BOOT_ARGS_SIZE  512
#define BOOT_IMG_MAX_PAGE_SIZE 4096
struct boot_img_hdr
{
    unsigned char magic[BOOT_MAGIC_SIZE];

    unsigned kernel_size;  /* size in bytes */
    unsigned kernel_addr;  /* physical load addr */

    unsigned ramdisk_size; /* size in bytes */
    unsigned ramdisk_addr; /* physical load addr */

    unsigned second_size;  /* size in bytes */
    unsigned second_addr;  /* physical load addr */

    unsigned tags_addr;    /* physical addr for kernel tags */
    unsigned page_size;    /* flash page size we assume */
    unsigned dt_size;      /* device_tree in bytes */
    unsigned unused;    /* future expansion: should be 0 */

    unsigned char name[BOOT_NAME_SIZE]; /* asciiz product name */

    unsigned char cmdline[BOOT_ARGS_SIZE];

    unsigned id[8]; /* timestamp / checksum / sha1 / etc */
};

/*
** +-----------------+
** | boot header     | 1 page
** +-----------------+
** | kernel          | n pages
** +-----------------+
** | ramdisk         | m pages
** +-----------------+
** | second stage    | o pages
** +-----------------+
** | device tree     | p pages
** +-----------------+
**
** n = (kernel_size + page_size - 1) / page_size
** m = (ramdisk_size + page_size - 1) / page_size
** o = (second_size + page_size - 1) / page_size
** p = (dt_size + page_size - 1) / page_size
** 0. all entities are page_size aligned in flash
** 1. kernel and ramdisk are required (size != 0)
** 2. second is optional (second_size == 0 -> no second)
** 3. load each element (kernel, ramdisk, second) at
**    the specified physical address (kernel_addr, etc)
** 4. prepare tags at tag_addr.  kernel_args[] is
**    appended to the kernel commandline in the tags.
** 5. r0 = 0, r1 = MACHINE_TYPE, r2 = tags_addr
** 6. if second_size != 0: jump to second_addr
**    else: jump to kernel_addr
*/

boot_img_hdr *mkbootimg(void *kernel, unsigned kernel_size,
                        void *ramdisk, unsigned ramdisk_size,
                        void *second, unsigned second_size,
                        unsigned page_size,
                        unsigned *bootimg_size);

void bootimg_set_cmdline(boot_img_hdr *hdr, const char *cmdline);

#define KERNEL64_HDR_MAGIC 0x644D5241 /* ARM64 */

struct kernel64_hdr
{
    uint32_t insn;
    uint32_t res1;
    uint64_t text_offset;
    uint64_t res2;
    uint64_t res3;
    uint64_t res4;
    uint64_t res5;
    uint64_t res6;
    uint32_t magic_64;
    uint32_t res7;
};
5.2.2 boot_linux函数分析
void boot_linux(void *kernel, unsigned *tags,
        const char *cmdline, unsigned machtype,
        void *ramdisk, unsigned ramdisk_size)
{
    unsigned char *final_cmdline;
#if DEVICE_TREE
    int ret = 0;
#endif

    void (*entry)(unsigned, unsigned, unsigned*) = (entry_func_ptr*)(PA((addr_t)kernel));//获取kernel的入口地址
    uint32_t tags_phys = PA((addr_t)tags);
    struct kernel64_hdr *kptr = ((struct kernel64_hdr*)(PA((addr_t)kernel)));//获取hdr

    ramdisk = (void *)PA((addr_t)ramdisk);

    final_cmdline = update_cmdline((const char*)cmdline);//更新cmdline,返回的final_cmdline是各个cmdline的字符数组

#if DEVICE_TREE
    dprintf(INFO, "Updating device tree: start\n");

    /* Update the Device Tree */
    ret = update_device_tree((void *)tags,(const char *)final_cmdline, ramdisk, ramdisk_size);//将更新的cmdline存入dt
    if(ret)
    {
        dprintf(CRITICAL, "ERROR: Updating Device Tree Failed \n");
        ASSERT(0);
    }
    dprintf(INFO, "Updating device tree: done\n");
#else
    /* Generating the Atags */
    generate_atags(tags, final_cmdline, ramdisk, ramdisk_size);//将更新的cmdline、ramdisk存入tags对应的地址
#endif

    free(final_cmdline);//释放在update_cmdline中申请的内存空间

#if VERIFIED_BOOT
#if !VBOOT_MOTA
    if (device.verity_mode == 0) {
#if FBCON_DISPLAY_MSG
        display_bootverify_menu(DISPLAY_MENU_LOGGING);
        wait_for_users_action();
#else
        dprintf(CRITICAL,
            "The dm-verity is not started in enforcing mode.\nWait for 5 seconds before proceeding\n");
        mdelay(5000);
#endif
    }

#endif
#endif

#if VERIFIED_BOOT
    /* Write protect the device info */
    if (!boot_into_recovery && target_build_variant_user() && devinfo_present && mmc_write_protect("devinfo", 1))
    {
        dprintf(INFO, "Failed to write protect dev info\n");
        ASSERT(0);
    }
#endif

    /* Turn off splash screen if enabled */
#if DISPLAY_SPLASH_SCREEN
    target_display_shutdown();  //显示关机图像
#endif

    /* Perform target specific cleanup */
    target_uninit();    //执行目标特定清除

    dprintf(INFO, "booting linux @ %p, ramdisk @ %p (%d), tags/device tree @ %p\n",
        entry, ramdisk, ramdisk_size, (void *)tags_phys);

    enter_critical_section(); //进入临界区

    /* do any platform specific cleanup before kernel entry */
    platform_uninit();  //执行平台特定清除

    arch_disable_cache(UCACHE);

#if ARM_WITH_MMU
    arch_disable_mmu();//禁止mmu
#endif
    bs_set_timestamp(BS_KERNEL_ENTRY);

    if (IS_ARM64(kptr))//判断是否是64位的内核
        /* Jump to a 64bit kernel */
        scm_elexec_call((paddr_t)kernel, tags_phys);//执行内核启动
    else
        /* Jump to a 32bit kernel */
        entry(0, machtype, (unsigned*)tags_phys);
}

主要功能:
1. 获取kernel、ramdisk的地址
2. 更新cmdline,并存储在dt/tags分区中
3. 回收平台特定资源
4. 进入kernel

5.2.3 ffbm分析

如果boot_linux_from_xxx函数中check_format_bit()=0,且misc分区的0地址为”ffbm-“,则boot_into_ffbm=true。该过程通过get_ffbm函数实现。

int get_ffbm(char *ffbm, unsigned size)
{
    const char *ffbm_cmd = "ffbm-";
    uint32_t page_size = get_page_size();
    char *ffbm_page_buffer = NULL;
    int retval = 0;
    if (size < FFBM_MODE_BUF_SIZE || size >= page_size)
    {
        dprintf(CRITICAL, "Invalid size argument passed to get_ffbm\n");
        retval = -1;
        goto cleanup;
    }
    ffbm_page_buffer = (char*)malloc(page_size);
    if (!ffbm_page_buffer)
    {
        dprintf(CRITICAL, "Failed to alloc buffer for ffbm cookie\n");
        retval = -1;
        goto cleanup;
    }
    if (read_misc(0, ffbm_page_buffer, page_size))
    {
        dprintf(CRITICAL, "Error reading MISC partition\n");
        retval = -1;
        goto cleanup;
    }
    ffbm_page_buffer[size] = '\0';
    if (strncmp(ffbm_cmd, ffbm_page_buffer, strlen(ffbm_cmd)))
    {
        retval = 0;
        goto cleanup;
    }
    else
    {
        if (strlcpy(ffbm, ffbm_page_buffer, size) <
                FFBM_MODE_BUF_SIZE -1)
        {
            dprintf(CRITICAL, "Invalid string in misc partition\n");
            retval = -1;
        }
        else
            retval = 1;
    }
cleanup:
if(ffbm_page_buffer)
        free(ffbm_page_buffer);
    return retval;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值