보조 CPU 시작 때에도 OP-TEE 초기화가 연결됩니다
전통적인 opteed 구성에서는 PSCI CPU 시작 마무리의 svc_on_finish 콜백이 opteed_cpu_on_finish_handler로 연결됩니다. 새 CPU에서 OP-TEE의 cpu_on_entry를 실행해 보안 상태를 준비한 뒤 TF-A로 돌아옵니다. 이후 비보안 Linux의 secondary_entry로 나갑니다. 최초 BL32 초기화와 각 CPU의 이 처리를 구분해야 합니다. FF-A/SPMC 구성은 같은 dispatcher 경로로 단정하지 않습니다.
QUESTION
BL32 최초 진입, 보조 CPU 준비, runtime SMC는 언제 갈라지는가?
일반 빌드에서 opteed_setup()은 유효한 BL32 entry 정보를 확인하고 현재 CPU의 Secure context를 준비한 뒤 opteed_init callback을 등록한다. 실제 BL32 최초 진입은 나중에 그 callback에서 동기적으로 수행된다. OP-TEE가 TEESMC_OPTEED_RETURN_ENTRY_DONE SMC로 돌아오면 vector table을 받는다.
OPTEE_ALLOW_SMC_LOAD 빌드는 설정 때 BL32 ep-info를 읽지 않고 SMC load를 기다린다. 보조 CPU의 PSCI svc_on_finish와 일반 runtime SMC도 각각 별도 경로다. 이미 선언된 runtime service descriptor와 OP-TEE vector가 준비되어 실제 전달 가능한 상태를 구분한다.
setup/init 150–289 · SMC/descriptor 608–869 · secondary 103–132
STRUCTURE
BL32 진입 정보를 만드는 두 경로
일반 BL32 적재
bl31_plat_get_next_image_ep_info(SECURE)ep-info 없음 또는 pc==0이면 setup 실패TRANSFER_LIST 조건부유효한 header이면 FDT 인자 재배치; 아니면 기본 args 사용opteed_init_optee_ep_state()현재 CPU의 opteed_sp_context[]에 Secure slot 연결bl31_register_bl32_init()실제 최초 진입은 별도 callback에서OPTEE_ALLOW_SMC_LOAD
두 열은 선택적 대안이다. opteed_sp_context[OPTEED_CORE_COUNT]는 고정 배열이며 plat_my_core_pos()로 현재 CPU 원소를 고른다.
정적 per-CPU storage 48–71 · setup 150–247 · load path 463–598
CALL PATH
primary·secondary·runtime의 세 시점
Primary cold init
cm_init_my_context → synchronous entrySecure EL1 복원·EL3 C runtime frame 보존ENTRY_DONE return SMCx1 vector가 있으면 ON state·PSCI hook 등록; sync frame 복귀이후의 별도 진입
svc_on_finish그 CPU의 cpu_on_entry context 설정·동기 진입CALL_DONE 반환Secure save → NS restore; FIQ_DONE은 별도 반환OP-TEE vector table이 없으면 일반 Normal World 요청은 -EINVAL로 돌아간다. secondary hook과 runtime 요청은 각각의 원인으로 진입한다.
STATE LEDGER
조건에 따라 달라지는 state
| 경계 | 조건 | 만드는/읽는 상태 | 다음 동작 |
|---|---|---|---|
| setup | OPTEE_ALLOW_SMC_LOAD | opteed_allow_load=true | 나중의 load SMC |
| 일반 setup | BL32 ep-info 및 pc 유효 | opteed_sp_context[linear_id] Secure slot·entry args | bl31_register_bl32_init |
| 최초 동기 entry | 등록된 init callback | c_rt_ctx frame과 Secure EL1 상태 | OP-TEE init return SMC |
ENTRY_DONE | x1 vector table 존재 | 현재 CPU ON; PSCI hook 등록 | 동기 frame 복귀 |
| secondary PSCI hook | ON/OFF 상태 조건 | 해당 CPU의 cpu_on_entry context | Secure 동기 entry 후 상태 ON |
| runtime NS SMC | vector table 유효 | fast/yield ELR 선택·Secure next context | OP-TEE handler |
이 표는 하나의 직선 호출열이 아니라 서로 다른 진입 조건을 한곳에 모은 것이다.
VISUAL WALKTHROUGH
첫 entry와 나중의 dispatch를 분리해 보기
cm_init_my_contextopteed_enter_spENTRY_DONEx1 vector → sync return이 그림은 !OPTEE_ALLOW_SMC_LOAD 경로다. SMC load 옵션에서는 entry 준비가 다른 시점에 일어난다. setup/init 원문 · init return.
PSCI secondary CPU
svc_on_finishopteed_cpu_on_finish_handlercpu_on_entry해당 CPU의 Secure context를 준비해 동기 진입Runtime Normal SMC
CALL_DONESecure save·NS restore 후 결과 반환두 열 모두 init return에서 받은 vector에 의존하지만 서로를 호출하지 않는다. FIQ_DONE은 Secure save를 생략하는 별도 반환이다. PSCI hook · runtime handler.
UPSTREAM SOURCE
원본 코드
아래 코드는 Trusted Firmware-A LTS 2.14.3의 services/spd/opteed/opteed_main.c에서 126-214줄을 그대로 가져온 것이다.
126
127/*
128 * Registers an interrupt handler for S-EL1 interrupts when generated during
129 * code executing in the non-secure state. Panics if it fails to do so.
130 */
131static void register_opteed_interrupt_handler(void)
132{
133 u_register_t flags;
134 uint64_t rc;
135
136 flags = 0;
137 set_interrupt_rm_flag(flags, NON_SECURE);
138 rc = register_interrupt_type_handler(INTR_TYPE_S_EL1,
139 opteed_sel1_interrupt_handler,
140 flags);
141 if (rc)
142 panic();
143}
144
145/*******************************************************************************
146 * OPTEE Dispatcher setup. The OPTEED finds out the OPTEE entrypoint and type
147 * (aarch32/aarch64) if not already known and initialises the context for entry
148 * into OPTEE for its initialization.
149 ******************************************************************************/
150static int32_t opteed_setup(void)
151{
152#if OPTEE_ALLOW_SMC_LOAD
153 opteed_allow_load = true;
154 INFO("Delaying OP-TEE setup until we receive an SMC call to load it\n");
155 /*
156 * We must register the interrupt handler now so that the interrupt
157 * priorities are not changed after starting the linux kernel.
158 */
159 register_opteed_interrupt_handler();
160 return 0;
161#else
162 entry_point_info_t *optee_ep_info;
163 uint32_t linear_id;
164 uint64_t arg0;
165 uint64_t arg1;
166 uint64_t arg2;
167 uint64_t arg3;
168 struct transfer_list_header __maybe_unused *tl = NULL;
169 struct transfer_list_entry __maybe_unused *te = NULL;
170 void __maybe_unused *dt = NULL;
171
172 linear_id = plat_my_core_pos();
173
174 /*
175 * Get information about the Secure Payload (BL32) image. Its
176 * absence is a critical failure. TODO: Add support to
177 * conditionally include the SPD service
178 */
179 optee_ep_info = bl31_plat_get_next_image_ep_info(SECURE);
180 if (!optee_ep_info) {
181 WARN("No OPTEE provided by BL2 boot loader, Booting device"
182 " without OPTEE initialization. SMC`s destined for OPTEE"
183 " will return SMC_UNK\n");
184 return 1;
185 }
186
187 /*
188 * If there's no valid entry point for SP, we return a non-zero value
189 * signalling failure initializing the service. We bail out without
190 * registering any handlers
191 */
192 if (!optee_ep_info->pc)
193 return 1;
194
195#if TRANSFER_LIST
196 tl = (void *)optee_ep_info->args.arg3;
197
198 if (transfer_list_check_header(tl)) {
199 te = transfer_list_find(tl, TL_TAG_FDT);
200 dt = transfer_list_entry_data(te);
201
202 opteed_rw = GET_RW(optee_ep_info->spsr);
203 if (opteed_rw == OPTEE_AARCH64) {
204 if (optee_ep_info->args.arg1 !=
205 TRANSFER_LIST_HANDOFF_X1_VALUE(
206 REGISTER_CONVENTION_VERSION))
207 return 1;
208
209 arg0 = (uint64_t)dt;
210 arg2 = 0;
211 } else {
212 if (optee_ep_info->args.arg1 !=
213 TRANSFER_LIST_HANDOFF_R1_VALUE(
214 REGISTER_CONVENTION_VERSION))
READING CONTRACT
발췌 범위와 읽기 기준
메인 발췌 126–214행은 opteed_setup()의 시작(150행)과 TRANSFER_LIST 분기 중간까지만 담는다. 함수 끝(247행), 실제 최초 entry(260–288행), init return case(736–763행)를 별도 원문과 함께 읽는다. 관련 코드 발췌 596–726행도 return switch 직전에서 끝난다.
OPTEE_ALLOW_SMC_LOAD의 두 빌드 경로, primary init, secondary PSCI hook, runtime SMC를 같은 호출 프레임으로 합치지 않는다.
RELATED SOURCE
함께 읽어야 하는 원본 코드
첫 코드 조각만으로 동작이 완성되지 않는 경우 호출 매크로, 객체 정의와 실제 실행 목록을 같은 페이지에 묶었다. 각 조각은 같은 기준 commit에서 가져왔다.
01. Normal World SMC와 OP-TEE return을 처리하는 dispatcher
services/spd/opteed/opteed_main.c 596-726줄이다.
596 return rc;
597}
598#endif /* OPTEE_ALLOW_SMC_LOAD */
599
600/*******************************************************************************
601 * This function is responsible for handling all SMCs in the Trusted OS/App
602 * range from the non-secure state as defined in the SMC Calling Convention
603 * Document. It is also responsible for communicating with the Secure
604 * payload to delegate work and return results back to the non-secure
605 * state. Lastly it will also return any information that OPTEE needs to do
606 * the work assigned to it.
607 ******************************************************************************/
608static uintptr_t opteed_smc_handler(uint32_t smc_fid,
609 u_register_t x1,
610 u_register_t x2,
611 u_register_t x3,
612 u_register_t x4,
613 void *cookie,
614 void *handle,
615 u_register_t flags)
616{
617 cpu_context_t *ns_cpu_context;
618 uint32_t linear_id = plat_my_core_pos();
619 optee_context_t *optee_ctx = &opteed_sp_context[linear_id];
620
621 /*
622 * Determine which security state this SMC originated from
623 */
624
625 if (is_caller_non_secure(flags)) {
626#if OPTEE_ALLOW_SMC_LOAD
627 if (opteed_allow_load && smc_fid == NSSMC_OPTEED_CALL_UID) {
628 /* Provide the UUID of the image loading service. */
629 SMC_UUID_RET(handle, optee_image_load_uuid);
630 }
631 if (smc_fid == NSSMC_OPTEED_CALL_LOAD_IMAGE) {
632 /*
633 * TODO: Consider wiping the code for SMC loading from
634 * memory after it has been invoked similar to what is
635 * done under RECLAIM_INIT, but extended to happen
636 * later.
637 */
638 if (!opteed_allow_load) {
639 SMC_RET1(handle, -EPERM);
640 }
641
642 opteed_allow_load = false;
643 uint64_t data_size = dual32to64(x1, x2);
644 uint64_t data_pa = dual32to64(x3, x4);
645 if (!data_size || !data_pa) {
646 /*
647 * This is invoked when the OP-TEE image didn't
648 * load correctly in the kernel but we want to
649 * block off loading of it later for security
650 * reasons.
651 */
652 SMC_RET1(handle, -EINVAL);
653 }
654 SMC_RET1(handle, opteed_handle_smc_load(
655 data_size, data_pa));
656 }
657#endif /* OPTEE_ALLOW_SMC_LOAD */
658 /*
659 * This is a fresh request from the non-secure client.
660 * The parameters are in x1 and x2. Figure out which
661 * registers need to be preserved, save the non-secure
662 * state and send the request to the secure payload.
663 */
664 assert(handle == cm_get_context(NON_SECURE));
665
666 cm_el1_sysregs_context_save(NON_SECURE);
667
668 /*
669 * We are done stashing the non-secure context. Ask the
670 * OP-TEE to do the work now. If we are loading vi an SMC,
671 * then we also need to init this CPU context if not done
672 * already.
673 */
674 if (optee_vector_table == NULL) {
675 SMC_RET1(handle, -EINVAL);
676 }
677
678 if (get_optee_pstate(optee_ctx->state) ==
679 OPTEE_PSTATE_UNKNOWN) {
680 opteed_cpu_on_finish_handler(0);
681 }
682
683 /*
684 * Verify if there is a valid context to use, copy the
685 * operation type and parameters to the secure context
686 * and jump to the fast smc entry point in the secure
687 * payload. Entry into S-EL1 will take place upon exit
688 * from this function.
689 */
690 assert(&optee_ctx->cpu_ctx == cm_get_context(SECURE));
691
692 /* Set appropriate entry for SMC.
693 * We expect OPTEE to manage the PSTATE.I and PSTATE.F
694 * flags as appropriate.
695 */
696 if (GET_SMC_TYPE(smc_fid) == SMC_TYPE_FAST) {
697 cm_set_elr_el3(SECURE, (uint64_t)
698 &optee_vector_table->fast_smc_entry);
699 } else {
700 cm_set_elr_el3(SECURE, (uint64_t)
701 &optee_vector_table->yield_smc_entry);
702 }
703
704 cm_el1_sysregs_context_restore(SECURE);
705 cm_set_next_eret_context(SECURE);
706
707 write_ctx_reg(get_gpregs_ctx(&optee_ctx->cpu_ctx),
708 CTX_GPREG_X4,
709 read_ctx_reg(get_gpregs_ctx(handle),
710 CTX_GPREG_X4));
711 write_ctx_reg(get_gpregs_ctx(&optee_ctx->cpu_ctx),
712 CTX_GPREG_X5,
713 read_ctx_reg(get_gpregs_ctx(handle),
714 CTX_GPREG_X5));
715 write_ctx_reg(get_gpregs_ctx(&optee_ctx->cpu_ctx),
716 CTX_GPREG_X6,
717 read_ctx_reg(get_gpregs_ctx(handle),
718 CTX_GPREG_X6));
719 /* Propagate hypervisor client ID */
720 write_ctx_reg(get_gpregs_ctx(&optee_ctx->cpu_ctx),
721 CTX_GPREG_X7,
722 read_ctx_reg(get_gpregs_ctx(handle),
723 CTX_GPREG_X7));
724
725 SMC_RET4(&optee_ctx->cpu_ctx, smc_fid, x1, x2, x3);
726 }
02. BL32 entry 정보를 secure OP-TEE context로 변환
services/spd/opteed/opteed_common.c 12-102줄이다.
12#include <lib/el3_runtime/context_mgmt.h>
13#include <lib/utils.h>
14
15#include "opteed_private.h"
16
17/*******************************************************************************
18 * Given a OPTEE entrypoint info pointer, entry point PC, register width,
19 * cpu id & pointer to a context data structure, this function will
20 * initialize OPTEE context and entry point info for OPTEE.
21 ******************************************************************************/
22void opteed_init_optee_ep_state(struct entry_point_info *optee_entry_point,
23 uint32_t rw, uint64_t pc, uint64_t arg0,
24 uint64_t arg1, uint64_t arg2, uint64_t arg3,
25 optee_context_t *optee_ctx)
26{
27 uint32_t ep_attr;
28
29 /* Passing a NULL context is a critical programming error */
30 assert(optee_ctx);
31 assert(optee_entry_point);
32 assert(pc);
33
34 /* Associate this context with the cpu specified */
35 optee_ctx->mpidr = read_mpidr_el1();
36 optee_ctx->state = 0;
37 set_optee_pstate(optee_ctx->state, OPTEE_PSTATE_OFF);
38
39 cm_set_context(&optee_ctx->cpu_ctx, SECURE);
40
41 /* initialise an entrypoint to set up the CPU context */
42 ep_attr = SECURE | EP_ST_ENABLE;
43 if (read_sctlr_el3() & SCTLR_EE_BIT)
44 ep_attr |= EP_EE_BIG;
45 SET_PARAM_HEAD(optee_entry_point, PARAM_EP, VERSION_1, ep_attr);
46 optee_entry_point->pc = pc;
47 if (rw == OPTEE_AARCH64)
48 optee_entry_point->spsr = SPSR_64(MODE_EL1, MODE_SP_ELX,
49 DISABLE_ALL_EXCEPTIONS);
50 else
51 optee_entry_point->spsr = SPSR_MODE32(MODE32_svc, SPSR_T_ARM,
52 SPSR_E_LITTLE,
53 DAIF_FIQ_BIT |
54 DAIF_IRQ_BIT |
55 DAIF_ABT_BIT);
56 zeromem(&optee_entry_point->args, sizeof(optee_entry_point->args));
57 optee_entry_point->args.arg0 = arg0;
58 optee_entry_point->args.arg1 = arg1;
59 optee_entry_point->args.arg2 = arg2;
60 optee_entry_point->args.arg3 = arg3;
61}
62
63/*******************************************************************************
64 * This function takes an OPTEE context pointer and:
65 * 1. Applies the S-EL1 system register context from optee_ctx->cpu_ctx.
66 * 2. Saves the current C runtime state (callee saved registers) on the stack
67 * frame and saves a reference to this state.
68 * 3. Calls el3_exit() so that the EL3 system and general purpose registers
69 * from the optee_ctx->cpu_ctx are used to enter the OPTEE image.
70 ******************************************************************************/
71uint64_t opteed_synchronous_sp_entry(optee_context_t *optee_ctx)
72{
73 uint64_t rc;
74
75 assert(optee_ctx != NULL);
76 assert(optee_ctx->c_rt_ctx == 0);
77
78 /* Apply the Secure EL1 system register context and switch to it */
79 assert(cm_get_context(SECURE) == &optee_ctx->cpu_ctx);
80 cm_el1_sysregs_context_restore(SECURE);
81 cm_set_next_eret_context(SECURE);
82
83 rc = opteed_enter_sp(&optee_ctx->c_rt_ctx);
84#if ENABLE_ASSERTIONS
85 optee_ctx->c_rt_ctx = 0;
86#endif
87
88 return rc;
89}
90
91
92/*******************************************************************************
93 * This function takes an OPTEE context pointer and:
94 * 1. Saves the S-EL1 system register context tp optee_ctx->cpu_ctx.
95 * 2. Restores the current C runtime state (callee saved registers) from the
96 * stack frame using the reference to this state saved in opteed_enter_sp().
97 * 3. It does not need to save any general purpose or EL3 system register state
98 * as the generic smc entry routine should have saved those.
99 ******************************************************************************/
100void opteed_synchronous_sp_exit(optee_context_t *optee_ctx, uint64_t ret)
101{
102 assert(optee_ctx != NULL);
DETAILS
최초 진입의 실제 완료 조건
setup은 최초 Secure 실행과 다르다
일반 setup은 BL32 ep-info/PC를 검사하고 transfer-list 또는 기본 args를 정한 뒤 entry state를 만들고 BL32 init callback을 등록한다. 동기 실행은 callback에서 나중에 일어난다.
EL3 stack의 synchronous frame
opteed_synchronous_sp_entry()는 Secure EL1 state를 복원하고 next context를 지정한 뒤 opteed_enter_sp()로 C runtime frame을 보관한다. ENTRY_DONE에서 opteed_synchronous_sp_exit()가 그 frame으로 돌아간다.
vector table이 실제 준비 신호다
init return x1이 유효한 vector일 때 현재 CPU를 ON으로 표시하고 PSCI hook을 등록한다(744–755행). 일반 runtime 요청은 vector table이 NULL이면 -EINVAL로 거절한다(674–676행).
IMPLEMENTATION NOTES
세 개의 독립 진입을 혼동하지 않기
SMC load 옵션
이 빌드에서는 setup 시점에 기존 BL32 ep-info 경로를 건너뛰고 interrupt handler를 등록한다. 나중의 Non-secure load SMC는 1회 허용 상태와 size/address를 검사한다. 일반 setup 경로와 둘 다 실행되지 않는다.
보조 CPU의 Secure context
PSCI svc_on_finish에서 그 CPU의 context를 cpu_on_entry용으로 만들고 동기적으로 OP-TEE에 들어간다. runtime SMC도 해당 CPU state가 UNKNOWN이면 이 handler를 부를 수 있다. Primary 최초 BL32 init의 반복이 아니다.
일반 요청과 두 반환
Normal caller는 NS EL1을 저장하고 fast/yield vector를 고른 뒤 Secure EL1을 복원한다. CALL_DONE은 Secure EL1 저장 후 NS로 돌아가지만 FIQ_DONE은 OP-TEE가 Secure state를 보존했다는 전제 아래 저장을 생략한다.
한 번의 load 시도: opteed_allow_load=false는 size/address가 0인지 검사하기 전에 기록된다. 따라서 0 인자로 거절되거나 뒤의 load가 실패해도 이 경로가 자동 재시도를 허용하지 않는다. 이 검사는 전체 입력 이미지의 안전성이나 신뢰성을 보증하지 않는다. 고정 원문 631–655행.
DEEP ANALYSIS
고정 원문의 조건별 결과
| 분기 | 고정 소스 결과 | 검토 지점 |
|---|---|---|
| setup: load 옵션 | opteed_allow_load=true, interrupt handler 등록, return | BL32 ep-info를 이때 읽지 않음 |
| setup: 일반 | ep-info/PC 검사, args 선택, context state 생성, init callback 등록 | TRANSFER_LIST는 옵션 |
ENTRY_DONE | x1 vector가 있으면 ON·PSCI hook 등록; sync exit | vector가 NULL이면 성공 상태로 취급하지 않음 |
| runtime: vector NULL | SMC_RET1(handle, -EINVAL) | descriptor 존재와 payload 준비를 구분 |
runtime: FIQ_DONE | NS restore 후 반환 | CALL_DONE의 Secure save와 다름 |
OBJECT LIFETIME
실제 보관되는 OP-TEE state
| 대상 | 생성·설정 | 이후 소비 |
|---|---|---|
opteed_sp_context[OPTEED_CORE_COUNT] | BL31의 정적 per-CPU 배열 | Primary/secondary/runtime handler가 현재 CPU index로 선택 |
entry_point_info_t | BL32/platform 정보로 PC·SPSR·args 설정 | cm_init_my_context의 최초 entry |
optee_ctx->c_rt_ctx | 동기 entry에서 EL3 C runtime frame 보관 | OP-TEE init/PM return의 synchronous exit |
optee_vector_table | Primary ENTRY_DONE x1 | PSCI와 fast/yield runtime entry |
FAILURE PATH
어느 경계가 먼저 거절하는가?
| 증상 | 고정 코드 조건 | 다음 확인 |
|---|---|---|
| 일반 setup 실패 | BL32 ep-info 없음 또는 pc==0 | main.c 179–193 |
| SMC load 거절 | 이미 사용했거나 size/address 0 | main.c 627–655 |
| 초기화 완료 뒤에도 호출 불가 | ENTRY_DONE x1 vector NULL | main.c 741–763 |
| Normal SMC 거절 | vector table NULL → -EINVAL | main.c 674–676 |
| 보조 CPU에서만 실패 | per-CPU state·cpu_on_entry | opteed_pm.c 103–132 |
EVIDENCE
빌드·보드에서 확인할 자료
아래는 대상 산출물이 있을 때의 읽기 중심 확인이다. 이 리뷰는 TF-A를 빌드하거나 보드에서 실행하지 않았다.
| 자료 | 예시 | 판정 |
|---|---|---|
| 빌드 설정 | SPD=opteed, OPTEE_ALLOW_SMC_LOAD, TRANSFER_LIST | 그림 1의 어느 열이 해당하는지 |
| BL31 symbol | ${CROSS_COMPILE}nm -n build/<platform>/debug/bl31/bl31.elf | grep opteed_setup | C 선언이 아닌 symbol 이름으로 검색 |
| EL3 debug log | SMC FID, CPU index, x1 vector, OP-TEE state | ENTRY_DONE·secondary·runtime 경계 구분 |
LAB
경로별로 독립 확인하기
- 01첫 BL32 entry
일반 빌드에서 BL32 ep-info PC, 선택된 args,
opteed_init()호출 시점을 각각 기록한다. - 02init return
ENTRY_DONEFID와 x1 vector, ON state, PSCI hook 등록 조건을 대조한다. - 03별도 후속 경로
secondary
svc_on_finish와 Normal runtime SMC의 CPU index/context를 분리해 기록한다.CALL_DONE과FIQ_DONE의 Secure save 차이를 함께 확인한다.
PRIMARY REFERENCES