Khorina · 2月7日 · 黑龙江

【系统启动】ARM Trusted Firmware分析——启动、PSCI、OP-TEE接口(下)

5. BL31 PSCI

参考文档:《POWER STATE COORDINATION INTERFACE (PSCI) System Software on ARM® Systems》

PSCI功能作为Standard service一部分,由std_svc_smc_handler()处理。

DECLARE_RT_SVC(
        std_svc,

        OEN_STD_START,
        OEN_STD_END,
        SMC_TYPE_FAST,
        std_svc_setup,
        std_svc_smc_handler-----------------------------对于Fast类型Standard服务调用,主要是进行PSCI处理。
);

uintptr_t std_svc_smc_handler(uint32_t smc_fid,
                 u_register_t x1,
                 u_register_t x2,
                 u_register_t x3,
                 u_register_t x4,
                 void *cookie,
                 void *handle,
                 u_register_t flags)
{
    /*
     * Dispatch PSCI calls to PSCI SMC handler and return its return
     * value
     */
    if (is_psci_fid(smc_fid)) {
        uint64_t ret;
...

        ret = psci_smc_handler(smc_fid, x1, x2, x3, x4,
            cookie, handle, flags);---------------------首先判断是否是Fast类型,然后交给psci_smc_handler()进行处理。
...
        SMC_RET1(handle, ret);
    }
...
}

u_register_t psci_smc_handler(uint32_t smc_fid,
              u_register_t x1,
              u_register_t x2,
              u_register_t x3,
              u_register_t x4,
              void *cookie,
              void *handle,
              u_register_t flags)
{
    if (is_caller_secure(flags))
        return SMC_UNK;

    /* Check the fid against the capabilities */
    if (!(psci_caps & define_psci_cap(smc_fid)))
        return SMC_UNK;

    if (((smc_fid >> FUNCID_CC_SHIFT) & FUNCID_CC_MASK) == SMC_32) {
...
    } else {---------------------------------------------这里以64系统为例。
        /* 64-bit PSCI function */

        switch (smc_fid) {
        case PSCI_CPU_SUSPEND_AARCH64:
            return psci_cpu_suspend(x1, x2, x3);

        case PSCI_CPU_ON_AARCH64:-----------------------PSCI_CPU_ON_AARCH64为0xc4000003,bit[31]=1:Fast Call、bit[30]=1:SMC64、bits[29:24]=000100:Starndard service、bits[15:0]=0000 0011:内部定义序号。
            return psci_cpu_on(x1, x2, x3);

          case PSCI_AFFINITY_INFO_AARCH64:                 return psci_affinity_info(x1, x2);
                  case PSCI_MIG_AARCH64:             return psci_migrate(x1);
                  case PSCI_MIG_INFO_UP_CPU_AARCH64:                 return psci_migrate_info_up_cpu();
                  case PSCI_NODE_HW_STATE_AARCH64:                 return psci_node_hw_state(x1, x2);
                  case PSCI_SYSTEM_SUSPEND_AARCH64:                 return psci_system_suspend(x1, x2);
  #if ENABLE_PSCI_STAT            case PSCI_STAT_RESIDENCY_AARCH64:                 return psci_stat_residency(x1, x2);
                  case PSCI_STAT_COUNT_AARCH64:                 return psci_stat_count(x1, x2);  #endif
        default:
            break;
        }
    }

    WARN("Unimplemented PSCI Call: 0x%x \n", smc_fid);
    return SMC_UNK;
}

5.1 PSCI_VERSION

unsigned int psci_version(void)
{
    return PSCI_MAJOR_VER | PSCI_MINOR_VER;
}

#define PSCI_MAJOR_VER        (1 << 16)
#define PSCI_MINOR_VER        0x0

5.2 PSCI_CPU_SUSPEND

int psci_cpu_suspend(unsigned int power_state,
             uintptr_t entrypoint,
             u_register_t context_id)
{
    int rc;
    unsigned int target_pwrlvl, is_power_down_state;
    entry_point_info_t ep;
    psci_power_state_t state_info = { {PSCI_LOCAL_STATE_RUN} };
    plat_local_state_t cpu_pd_state;

    /* Validate the power_state parameter */
    rc = psci_validate_power_state(power_state, &state_info);
    if (rc != PSCI_E_SUCCESS) {
        assert(rc == PSCI_E_INVALID_PARAMS);
        return rc;
    }

    /*
     * Get the value of the state type bit from the power state parameter.
     */
    is_power_down_state = psci_get_pstate_type(power_state);

    /* Sanity check the requested suspend levels */
    assert(psci_validate_suspend_req(&state_info, is_power_down_state)
            == PSCI_E_SUCCESS);

    target_pwrlvl = psci_find_target_suspend_lvl(&state_info);
    if (target_pwrlvl == PSCI_INVALID_PWR_LVL) {
        ERROR("Invalid target power level for suspend operation\n");
        panic();
    }

    /* Fast path for CPU standby.*/
    if (is_cpu_standby_req(is_power_down_state, target_pwrlvl)) {
        if  (!psci_plat_pm_ops->cpu_standby)
            return PSCI_E_INVALID_PARAMS;

        /*
         * Set the state of the CPU power domain to the platform
         * specific retention state and enter the standby state.
         */
        cpu_pd_state = state_info.pwr_domain_state[PSCI_CPU_PWR_LVL];
        psci_set_cpu_local_state(cpu_pd_state);

#if ENABLE_PSCI_STAT
        /*
         * Capture time-stamp before CPU standby
         * No cache maintenance is needed as caches
         * are ON through out the CPU standby operation.
         */
        PMF_CAPTURE_TIMESTAMP(psci_svc, PSCI_STAT_ID_ENTER_LOW_PWR,
            PMF_NO_CACHE_MAINT);
#endif

#if ENABLE_RUNTIME_INSTRUMENTATION
        PMF_CAPTURE_TIMESTAMP(rt_instr_svc,
            RT_INSTR_ENTER_HW_LOW_PWR,
            PMF_NO_CACHE_MAINT);
#endif

        psci_plat_pm_ops->cpu_standby(cpu_pd_state);

        /* Upon exit from standby, set the state back to RUN. */
        psci_set_cpu_local_state(PSCI_LOCAL_STATE_RUN);

#if ENABLE_RUNTIME_INSTRUMENTATION
        PMF_CAPTURE_TIMESTAMP(rt_instr_svc,
            RT_INSTR_EXIT_HW_LOW_PWR,
            PMF_NO_CACHE_MAINT);
#endif

#if ENABLE_PSCI_STAT
        /* Capture time-stamp after CPU standby */
        PMF_CAPTURE_TIMESTAMP(psci_svc, PSCI_STAT_ID_EXIT_LOW_PWR,
            PMF_NO_CACHE_MAINT);

        /* Update PSCI stats */
        psci_stats_update_pwr_up(PSCI_CPU_PWR_LVL, &state_info,
            PMF_NO_CACHE_MAINT);
#endif

        return PSCI_E_SUCCESS;
    }

    /*
     * If a power down state has been requested, we need to verify entry
     * point and program entry information.
     */
    if (is_power_down_state) {
        rc = psci_validate_entry_point(&ep, entrypoint, context_id);
        if (rc != PSCI_E_SUCCESS)
            return rc;
    }

    /*
     * Do what is needed to enter the power down state. Upon success,
     * enter the final wfi which will power down this CPU. This function
     * might return if the power down was abandoned for any reason, e.g.
     * arrival of an interrupt
     */
    psci_cpu_suspend_start(&ep,
                target_pwrlvl,
                &state_info,
                is_power_down_state);

    return PSCI_E_SUCCESS;
}

5.3 PSCI_CPU_OFF

int psci_cpu_off(void)
{
    int rc;
    unsigned int target_pwrlvl = PLAT_MAX_PWR_LVL;

    /*
     * Do what is needed to power off this CPU and possible higher power
     * levels if it able to do so. Upon success, enter the final wfi
     * which will power down this CPU.
     */
    rc = psci_do_cpu_off(target_pwrlvl);

    /*
     * The only error cpu_off can return is E_DENIED. So check if that's
     * indeed the case.
     */
    assert(rc == PSCI_E_DENIED);

    return rc;
}

5.4 PSCI_CPU_ON

/*******************************************************************************
 * PSCI frontend api for servicing SMCs. Described in the PSCI spec.
 ******************************************************************************/
int psci_cpu_on(u_register_t target_cpu,
        uintptr_t entrypoint,
        u_register_t context_id)

{
    int rc;
    entry_point_info_t ep;

    /* Determine if the cpu exists of not */
    rc = psci_validate_mpidr(target_cpu);
    if (rc != PSCI_E_SUCCESS)
        return PSCI_E_INVALID_PARAMS;

    /* Validate the entry point and get the entry_point_info */
    rc = psci_validate_entry_point(&ep, entrypoint, context_id);
    if (rc != PSCI_E_SUCCESS)
        return rc;

    /*
     * To turn this cpu on, specify which power
     * levels need to be turned on
     */
    return psci_cpu_on_start(target_cpu, &ep);
}

5.5 PSCI_AFFINITY_INFO

int psci_affinity_info(u_register_t target_affinity,
               unsigned int lowest_affinity_level)
{
    unsigned int target_idx;

    /* We dont support level higher than PSCI_CPU_PWR_LVL */
    if (lowest_affinity_level > PSCI_CPU_PWR_LVL)
        return PSCI_E_INVALID_PARAMS;

    /* Calculate the cpu index of the target */
    target_idx = plat_core_pos_by_mpidr(target_affinity);
    if (target_idx == -1)
        return PSCI_E_INVALID_PARAMS;

    return psci_get_aff_info_state_by_idx(target_idx);
}

5.6 PSCI_MIG

int psci_migrate(u_register_t target_cpu)
{
    int rc;
    u_register_t resident_cpu_mpidr;

    rc = psci_spd_migrate_info(&resident_cpu_mpidr);
    if (rc != PSCI_TOS_UP_MIG_CAP)
        return (rc == PSCI_TOS_NOT_UP_MIG_CAP) ?
              PSCI_E_DENIED : PSCI_E_NOT_SUPPORTED;

    /*
     * Migrate should only be invoked on the CPU where
     * the Secure OS is resident.
     */
    if (resident_cpu_mpidr != read_mpidr_el1())
        return PSCI_E_NOT_PRESENT;

    /* Check the validity of the specified target cpu */
    rc = psci_validate_mpidr(target_cpu);
    if (rc != PSCI_E_SUCCESS)
        return PSCI_E_INVALID_PARAMS;

    assert(psci_spd_pm && psci_spd_pm->svc_migrate);

    rc = psci_spd_pm->svc_migrate(read_mpidr_el1(), target_cpu);
    assert(rc == PSCI_E_SUCCESS || rc == PSCI_E_INTERN_FAIL);

    return rc;
}

5.7 PSCI_MIG_INFO_TYPE

int psci_migrate_info_type(void)
{
    u_register_t resident_cpu_mpidr;

    return psci_spd_migrate_info(&resident_cpu_mpidr);
}

/*******************************************************************************
 * This function invokes the migrate info hook in the spd_pm_ops. It performs
 * the necessary return value validation. If the Secure Payload is UP and
 * migrate capable, it returns the mpidr of the CPU on which the Secure payload
 * is resident through the mpidr parameter. Else the value of the parameter on
 * return is undefined.
 ******************************************************************************/
int psci_spd_migrate_info(u_register_t *mpidr)
{
    int rc;

    if (!psci_spd_pm || !psci_spd_pm->svc_migrate_info)
        return PSCI_E_NOT_SUPPORTED;

    rc = psci_spd_pm->svc_migrate_info(mpidr);

    assert(rc == PSCI_TOS_UP_MIG_CAP || rc == PSCI_TOS_NOT_UP_MIG_CAP \
        || rc == PSCI_TOS_NOT_PRESENT_MP || rc == PSCI_E_NOT_SUPPORTED);

    return rc;
}

5.8 PSCI_MIG_INFO_UP_CPU

long psci_migrate_info_up_cpu(void)
{
    u_register_t resident_cpu_mpidr;
    int rc;

    /*
     * Return value of this depends upon what
     * psci_spd_migrate_info() returns.
     */
    rc = psci_spd_migrate_info(&resident_cpu_mpidr);
    if (rc != PSCI_TOS_NOT_UP_MIG_CAP && rc != PSCI_TOS_UP_MIG_CAP)
        return PSCI_E_INVALID_PARAMS;

    return resident_cpu_mpidr;
}

5.9 PSCI_SYSTEM_OFF

void psci_system_off(void)
{
    psci_print_power_domain_map();

    assert(psci_plat_pm_ops->system_off);

    /* Notify the Secure Payload Dispatcher */
    if (psci_spd_pm && psci_spd_pm->svc_system_off) {
        psci_spd_pm->svc_system_off();
    }

    /* Call the platform specific hook */
    psci_plat_pm_ops->system_off();

    /* This function does not return. We should never get here */
}

5.10 PSCI_SYSTEM_RESET

void psci_system_reset(void)
{
    psci_print_power_domain_map();

    assert(psci_plat_pm_ops->system_reset);

    /* Notify the Secure Payload Dispatcher */
    if (psci_spd_pm && psci_spd_pm->svc_system_reset) {
        psci_spd_pm->svc_system_reset();
    }

    /* Call the platform specific hook */
    psci_plat_pm_ops->system_reset();

    /* This function does not return. We should never get here */
}

5.11 PSCI_FEATURES

int psci_features(unsigned int psci_fid)
{
    unsigned int local_caps = psci_caps;

    /* Check if it is a 64 bit function */
    if (((psci_fid >> FUNCID_CC_SHIFT) & FUNCID_CC_MASK) == SMC_64)
        local_caps &= PSCI_CAP_64BIT_MASK;

    /* Check for invalid fid */
    if (!(is_std_svc_call(psci_fid) && is_valid_fast_smc(psci_fid)
            && is_psci_fid(psci_fid)))
        return PSCI_E_NOT_SUPPORTED;


    /* Check if the psci fid is supported or not */
    if (!(local_caps & define_psci_cap(psci_fid)))
        return PSCI_E_NOT_SUPPORTED;

    /* Format the feature flags */
    if (psci_fid == PSCI_CPU_SUSPEND_AARCH32 ||
            psci_fid == PSCI_CPU_SUSPEND_AARCH64) {
        /*
         * The trusted firmware does not support OS Initiated Mode.
         */
        return (FF_PSTATE << FF_PSTATE_SHIFT) |
            ((!FF_SUPPORTS_OS_INIT_MODE) << FF_MODE_SUPPORT_SHIFT);
    }

    /* Return 0 for all other fid's */
    return PSCI_E_SUCCESS;
}

5.12 PSCI_SYSTEM_SUSPEND

int psci_system_suspend(uintptr_t entrypoint, u_register_t context_id)
{
    int rc;
    psci_power_state_t state_info;
    entry_point_info_t ep;

    /* Check if the current CPU is the last ON CPU in the system */
    if (!psci_is_last_on_cpu())
        return PSCI_E_DENIED;

    /* Validate the entry point and get the entry_point_info */
    rc = psci_validate_entry_point(&ep, entrypoint, context_id);
    if (rc != PSCI_E_SUCCESS)
        return rc;

    /* Query the psci_power_state for system suspend */
    psci_query_sys_suspend_pwrstate(&state_info);

    /* Ensure that the psci_power_state makes sense */
    assert(psci_find_target_suspend_lvl(&state_info) == PLAT_MAX_PWR_LVL);
    assert(psci_validate_suspend_req(&state_info, PSTATE_TYPE_POWERDOWN)
                        == PSCI_E_SUCCESS);
    assert(is_local_state_off(state_info.pwr_domain_state[PLAT_MAX_PWR_LVL]));

    /*
     * Do what is needed to enter the system suspend state. This function
     * might return if the power down was abandoned for any reason, e.g.
     * arrival of an interrupt
     */
    psci_cpu_suspend_start(&ep,
                PLAT_MAX_PWR_LVL,
                &state_info,
                PSTATE_TYPE_POWERDOWN);

    return PSCI_E_SUCCESS;
}

6. BL31 OPTEE接口

optee注册了Fast和Standard两种调用类型,Fast类型需要使用opteed_setup()进行初始化。两种类型共用opteed_smc_handler()进行smc处理。

/* Define an OPTEED runtime service descriptor for fast SMC calls */
DECLARE_RT_SVC(
    opteed_fast,

    OEN_TOS_START,
    OEN_TOS_END,
    SMC_TYPE_FAST,
    opteed_setup,
    opteed_smc_handler
);

/* Define an OPTEED runtime service descriptor for standard SMC calls */
DECLARE_RT_SVC(
    opteed_std,

    OEN_TOS_START,
    OEN_TOS_END,
    SMC_TYPE_STD,
    NULL,
    opteed_smc_handler
);

6.1 optee启动

在ATF BL31启动过程中,runtime_svc_init()会调用opteed_setup()来完成optee的启动

/*******************************************************************************
 * OPTEE Dispatcher setup. The OPTEED finds out the OPTEE entrypoint and type
 * (aarch32/aarch64) if not already known and initialises the context for entry
 * into OPTEE for its initialization.
 ******************************************************************************/
int32_t opteed_setup(void)
{
    entry_point_info_t *optee_ep_info;
    uint32_t linear_id;

    linear_id = plat_my_core_pos();

    optee_ep_info = bl31_plat_get_next_image_ep_info(SECURE);-----------------获取BL32即optee os镜像信息。
    if (!optee_ep_info) {
        WARN("No OPTEE provided by BL2 boot loader, Booting device"
            " without OPTEE initialization. SMC`s destined for OPTEE"
            " will return SMC_UNK\n");
        return 1;
    }

    if (!optee_ep_info->pc)
        return 1;

    /*
     * We could inspect the SP image and determine it's execution
     * state i.e whether AArch32 or AArch64. Assuming it's AArch32
     * for the time being.
     */
    opteed_rw = OPTEE_AARCH64;
    opteed_init_optee_ep_state(optee_ep_info,
                opteed_rw,
                optee_ep_info->pc,
                &opteed_sp_context[linear_id]);------------------------------初始化安全CPU的smc上下文,存放于opteed_sp_context[]中。

    /*
     * All OPTEED initialization done. Now register our init function with
     * BL31 for deferred invocation
     */
    bl31_register_bl32_init(&opteed_init);-----------------------------------bl32_init指向opteed_init(),在bl31_main()中被调用。

    return 0;
}

opteed_init()从镜像中获取optee os的入口点,并初始化好ATF和optee切换的上下文,然后进入optee并等待返回结果。

/*******************************************************************************
 * This function passes control to the OPTEE image (BL32) for the first time
 * on the primary cpu after a cold boot. It assumes that a valid secure
 * context has already been created by opteed_setup() which can be directly
 * used.  It also assumes that a valid non-secure context has been
 * initialised by PSCI so it does not need to save and restore any
 * non-secure state. This function performs a synchronous entry into
 * OPTEE. OPTEE passes control back to this routine through a SMC.
 ******************************************************************************/
static int32_t opteed_init(void)
{
    uint32_t linear_id = plat_my_core_pos();
    optee_context_t *optee_ctx = &opteed_sp_context[linear_id];
    entry_point_info_t *optee_entry_point;
    uint64_t rc;

    /*
     * Get information about the OPTEE (BL32) image. Its
     * absence is a critical failure.
     */
    optee_entry_point = bl31_plat_get_next_image_ep_info(SECURE);-----------------------------获取optee os镜像信息。
    assert(optee_entry_point);

    cm_init_my_context(optee_entry_point);----------------------------------------------------设置当前CPU进入安全状态的上下文。

    /*
     * Arrange for an entry into OPTEE. It will be returned via
     * OPTEE_ENTRY_DONE case
     */
    rc = opteed_synchronous_sp_entry(optee_ctx);----------------------------------------------启动optee os,并等待OPTEE_ENTRY_DONE返回结果。
    assert(rc != 0);

    return rc;
}

/*******************************************************************************
 * This function takes an OPTEE context pointer and:
 * 1. Applies the S-EL1 system register context from optee_ctx->cpu_ctx.
 * 2. Saves the current C runtime state (callee saved registers) on the stack
 *    frame and saves a reference to this state.
 * 3. Calls el3_exit() so that the EL3 system and general purpose registers
 *    from the optee_ctx->cpu_ctx are used to enter the OPTEE image.
 ******************************************************************************/
uint64_t opteed_synchronous_sp_entry(optee_context_t *optee_ctx)
{
    uint64_t rc;

    assert(optee_ctx != NULL);
    assert(optee_ctx->c_rt_ctx == 0);

    /* Apply the Secure EL1 system register context and switch to it */
    assert(cm_get_context(SECURE) == &optee_ctx->cpu_ctx);
    cm_el1_sysregs_context_restore(SECURE);---------------从optee_ctx->cpu_ctx中恢复S.EL1相关寄存器。
    cm_set_next_eret_context(SECURE);---------------------保存从S.EL1返回需要的上下文。

    rc = opteed_enter_sp(&optee_ctx->c_rt_ctx);-----------将安全CPU保存的状态恢复到optee_ctx->c_rt_ctx中,并跳转到opteed os执行。
#if DEBUG
    optee_ctx->c_rt_ctx = 0;
#endif

    return rc;
}
func opteed_enter_sp
    /* Make space for the registers that we're going to save */
    mov    x3, sp
    str    x3, [x0, #0]
    sub    sp, sp, #OPTEED_C_RT_CTX_SIZE

    /* Save callee-saved registers on to the stack */
    stp    x19, x20, [sp, #OPTEED_C_RT_CTX_X19]
    stp    x21, x22, [sp, #OPTEED_C_RT_CTX_X21]
    stp    x23, x24, [sp, #OPTEED_C_RT_CTX_X23]
    stp    x25, x26, [sp, #OPTEED_C_RT_CTX_X25]
    stp    x27, x28, [sp, #OPTEED_C_RT_CTX_X27]
    stp    x29, x30, [sp, #OPTEED_C_RT_CTX_X29]

    /* ---------------------------------------------
     * Everything is setup now. el3_exit() will
     * use the secure context to restore to the
     * general purpose and EL3 system registers to
     * ERET into OPTEE.
     * ---------------------------------------------
     */
    b    el3_exit--------------------------------------------------使用配置好的安全上下文,退出EL3进入OPTEE。
endfunc opteed_enter_sp

6.2 optee的SPD(Secure Payload Dispatcher)

BL31中处理OP-TEE安全请求分发入口函数是opteed_smc_handler()。

uint64_t opteed_smc_handler(uint32_t smc_fid,
             uint64_t x1,
             uint64_t x2,
             uint64_t x3,
             uint64_t x4,
             void *cookie,
             void *handle,
             uint64_t flags)
{
    cpu_context_t *ns_cpu_context;
    uint32_t linear_id = plat_my_core_pos();
    optee_context_t *optee_ctx = &opteed_sp_context[linear_id];---------------获取当前CPU保存的optee上下文。
    uint64_t rc;

    /*
     * Determine which security state this SMC originated from
     */

    if (is_caller_non_secure(flags)) {
        /*
         * This is a fresh request from the non-secure client.
         * The parameters are in x1 and x2. Figure out which
         * registers need to be preserved, save the non-secure
         * state and send the request to the secure payload.
         */
        assert(handle == cm_get_context(NON_SECURE));

        cm_el1_sysregs_context_save(NON_SECURE);

        /*
         * We are done stashing the non-secure context. Ask the
         * OPTEE to do the work now.
         */

        /*
         * Verify if there is a valid context to use, copy the
         * operation type and parameters to the secure context
         * and jump to the fast smc entry point in the secure
         * payload. Entry into S-EL1 will take place upon exit
         * from this function.
         */
        assert(&optee_ctx->cpu_ctx == cm_get_context(SECURE));

        /* Set appropriate entry for SMC.
         * We expect OPTEE to manage the PSTATE.I and PSTATE.F
         * flags as appropriate.
         */
        if (GET_SMC_TYPE(smc_fid) == SMC_TYPE_FAST) {
            cm_set_elr_el3(SECURE, (uint64_t)
                    &optee_vectors->fast_smc_entry);
        } else {
            cm_set_elr_el3(SECURE, (uint64_t)
                    &optee_vectors->std_smc_entry);
        }

        cm_el1_sysregs_context_restore(SECURE);
        cm_set_next_eret_context(SECURE);

        write_ctx_reg(get_gpregs_ctx(&optee_ctx->cpu_ctx),
                  CTX_GPREG_X4,
                  read_ctx_reg(get_gpregs_ctx(handle),
                       CTX_GPREG_X4));
        write_ctx_reg(get_gpregs_ctx(&optee_ctx->cpu_ctx),
                  CTX_GPREG_X5,
                  read_ctx_reg(get_gpregs_ctx(handle),
                       CTX_GPREG_X5));
        write_ctx_reg(get_gpregs_ctx(&optee_ctx->cpu_ctx),
                  CTX_GPREG_X6,
                  read_ctx_reg(get_gpregs_ctx(handle),
                       CTX_GPREG_X6));
        /* Propagate hypervisor client ID */
        write_ctx_reg(get_gpregs_ctx(&optee_ctx->cpu_ctx),
                  CTX_GPREG_X7,
                  read_ctx_reg(get_gpregs_ctx(handle),
                       CTX_GPREG_X7));

        SMC_RET4(&optee_ctx->cpu_ctx, smc_fid, x1, x2, x3);
    }

    /*
     * Returning from OPTEE
     */

    switch (smc_fid) {
    case TEESMC_OPTEED_RETURN_ENTRY_DONE:-------------------------------------optee冷启动初始化完成后返回。
        assert(optee_vectors == NULL);
        optee_vectors = (optee_vectors_t *) x1;

        if (optee_vectors) {
            set_optee_pstate(optee_ctx->state, OPTEE_PSTATE_ON);

            psci_register_spd_pm_hook(&opteed_pm);

            flags = 0;
            set_interrupt_rm_flag(flags, NON_SECURE);
            rc = register_interrupt_type_handler(INTR_TYPE_S_EL1,
                        opteed_sel1_interrupt_handler,
                        flags);
            if (rc)
                panic();
        }
        opteed_synchronous_sp_exit(optee_ctx, x1);-----------------------------从optee中返回。

    case TEESMC_OPTEED_RETURN_ON_DONE:-----------------------------------------表示optee由cpu_on导致的启动完成,0标识成功,其他失败。
    case TEESMC_OPTEED_RETURN_RESUME_DONE:-------------------------------------表示optee从cpu_suspend导致的休眠中唤醒完成;0表示成功,其他失败。
    case TEESMC_OPTEED_RETURN_OFF_DONE:----------------------------------------下面分表表示optee对cpu_off/cpu_suspend/system_off/system_reset的响应结果;0表示成功,其他表示失败。其中system_off和system_reset无返回参数。
    case TEESMC_OPTEED_RETURN_SUSPEND_DONE:
    case TEESMC_OPTEED_RETURN_SYSTEM_OFF_DONE:
    case TEESMC_OPTEED_RETURN_SYSTEM_RESET_DONE:
        opteed_synchronous_sp_exit(optee_ctx, x1);

    case TEESMC_OPTEED_RETURN_CALL_DONE:---------------------------------------optee处理完smc之后,需要返回普通世界,x1-x4返回参数。
        assert(handle == cm_get_context(SECURE));
        cm_el1_sysregs_context_save(SECURE);

        /* Get a reference to the non-secure context */
        ns_cpu_context = cm_get_context(NON_SECURE);
        assert(ns_cpu_context);

        /* Restore non-secure state */
        cm_el1_sysregs_context_restore(NON_SECURE);
        cm_set_next_eret_context(NON_SECURE);

        SMC_RET4(ns_cpu_context, x1, x2, x3, x4);

    case TEESMC_OPTEED_RETURN_FIQ_DONE:-----------------------------------------optee处理完fiq中断后,需要返回普通世界。
        ns_cpu_context = cm_get_context(NON_SECURE);
        assert(ns_cpu_context);

        cm_el1_sysregs_context_restore(NON_SECURE);
        cm_set_next_eret_context(NON_SECURE);

        SMC_RET0((uint64_t) ns_cpu_context);

    default:
        panic();
    }
}

void opteed_synchronous_sp_exit(optee_context_t *optee_ctx, uint64_t ret)
{
    assert(optee_ctx != NULL);
    /* Save the Secure EL1 system register context */
    assert(cm_get_context(SECURE) == &optee_ctx->cpu_ctx);
    cm_el1_sysregs_context_save(SECURE);------------------------保存S.EL1下optee系统寄存器保存到cpu_context[SECURE]中。

    assert(optee_ctx->c_rt_ctx != 0);
    opteed_exit_sp(optee_ctx->c_rt_ctx, ret);-------------------恢复optee_enter_sp()保存的C运行环境上下文。

    /* Should never reach here */
    assert(0);
}

参考文档

  • 《ARM Trusted Firmware Design》:介绍了ATF关键设计思想Cold boot、EL3运行时服务、PSCI、Secure-EL1系统和服务、BL镜像内存划分、FIP、Trusted Firmware内存一致性等等。
  • 《学习整理:arm-trusted-firmware》:基本上是对《ARM Trusted Firmware Design》的翻译。
  • 《ATF(ARM Trusted firmware)》专题:介绍了ATF启动流程以及各个阶段内容。
作者:ArnoldLu
文章来源:TrustZone

推荐阅读

更多物联网安全,PSA等技术干货请关注平台安全架构(PSA)专栏。欢迎添加极术小姐姐微信(id:aijishu20)加入PSA技术交流群,请备注研究方向。
推荐阅读
关注数
4540
内容数
125
Arm发布的PSA旨在为物联网安全提供一套全面的安全指导方针,使从芯片制造商到设备开发商等价值链中的每位成员都能成功实现安全运行。
目录
极术微信服务号
关注极术微信号
实时接收点赞提醒和评论通知
安谋科技学堂公众号
关注安谋科技学堂
实时获取安谋科技及 Arm 教学资源
安谋科技招聘公众号
关注安谋科技招聘
实时获取安谋科技中国职位信息