보조 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
OP-TEE dispatcher와 BL32 최초 진입 단계에서 실제로 바뀌는 상태는 무엇인가?
OP-TEE는 BL31과 같은 EL에서 실행되지 않는다. EL3 dispatcher가 S-EL1 context를 소유하고 Normal World SMC마다 어느 context를 복원하는지 본다.
BL32 entry, SPSR, pageable/DT arguments와 secure stack이 유효해야 하며 초기 진입이 반환된 뒤에만 OP-TEE service를 runtime에 공개해야 한다. 이 문장을 기준으로 코드를 위에서 아래로 읽으면, 함수 이름을 외우는 대신 어느 시점에 어떤 상태를 신뢰할 수 있는지 판단할 수 있다.
STRUCTURE
객체와 주소가 놓이는 구조
optee_context_t / opteed_sp_context를 중심에 놓고 왼쪽의 입력이 어떤 검사를 거쳐 오른쪽 결과로 공개되는지 표시했다. 실제 디버깅에서는 각 블록의 주소와 크기를 로그에 대입한다.
CALL PATH
실행 흐름
화살표는 단순 호출 순서만 뜻하지 않는다. 각 단계가 성공을 반환할 때 다음 단계가 읽을 수 있는 상태가 무엇인지 함께 확인한다. 오류 반환이 발생하면 바로 다음 화살표로 진행하지 않고 해당 단계의 정리 경로를 따라간다.
STATE LEDGER
단계별 입력과 출력
호출 순서를 함수 이름으로만 외우지 않고, 각 단계가 무엇을 받아 무엇을 공개하는지 적은 표다. 실제 소스에서 생산 필드가 다르면 표를 고치는 방식으로 사용한다.
| # | 단계 | 진입 시 신뢰할 상태 | 성공 뒤 남아야 할 상태 | 다음 소비자 |
|---|---|---|---|---|
| 01 | BL32 image info | EL3 SPD initialization context | optee_context_t | opteed_setup |
| 02 | opteed_setup | BL32 image info 완료 상태 | BL32 entry_point_info | secure context init |
| 03 | secure context init | opteed_setup 완료 상태 | secure stack/context | synchronous BL32 entry |
| 04 | synchronous BL32 entry | secure context init 완료 상태 | SPD service | OP-TEE init return |
| 05 | OP-TEE init return | synchronous BL32 entry 완료 상태 | SPD service | 최종 최종 부트로더 이미지 또는 다음 stage |
분석 범위의 전제와 비교해, 다음 단계의 입력 조건을 처음 어긴 생산 단계부터 조사한다.
VISUAL WALKTHROUGH
주소와 객체의 이동을 그림으로 읽기
아래 그림은 호출 이름보다 주소, 객체 수명과 handoff 경계를 먼저 볼 수 있도록 구성했다. 실제 주소와 크기는 사용 중인 보드의 bdinfo, map과 linker symbol을 대입한다.
각 칸은 제어권이 다음 단계로 넘어가기 전에 확정되어야 하는 상태를 나타낸다.
왼쪽에서 만든 상태를 오른쪽 단계가 처음 사용하는 관계를 표시한다.
BL32 ep_info→entry·SPSR→optee_contextBL31 stack→synchronous entry→OP-TEE _startOP-TEE init SMC→return protocol→SPD initializedper-CPU state→secondary init→runtime SMCUPSTREAM 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줄에는 앞뒤 문맥이 포함됩니다. 기준 구문 static int32_t opteed_setup(void)은 L150에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.
OP-TEE는 BL31과 같은 EL에서 실행되지 않는다. EL3 dispatcher가 S-EL1 context를 소유하고 Normal World SMC마다 어느 context를 복원하는지 본다.
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
내부 동작을 더 깊게 읽기
진입 조건을 먼저 고정한다
BL32 image info에서 들어온 실행은 EL3 SPD initialization context에 놓여 있다. 이때 interrupt, MMU/cache, stack, heap 중 무엇이 이미 준비되었는지 소스의 호출자까지 올라가 확인한다. 같은 함수라도 SPL, relocation 전후, app thread처럼 호출 문맥이 달라지면 허용되는 API와 지연 시간이 달라진다.
OP-TEE는 BL31과 같은 EL에서 실행되지 않는다. EL3 dispatcher가 S-EL1 context를 소유하고 Normal World SMC마다 어느 context를 복원하는지 본다.
중심 객체의 생성과 공개를 나눈다
이 글의 중심 객체는 optee_context_t / opteed_sp_context다. 메모리를 확보한 시점, 필드를 채운 시점, 전역 list나 다른 subsystem에 공개한 시점을 구분한다. 공개 뒤 오류가 발생한다면 목록에서 제거하고 child, buffer, reference를 역순으로 정리하는지 확인한다.
빌드 산출물 관점에서는 최종 부트로더 이미지 안에 해당 symbol과 section이 실제로 포함되었는지도 map과 objdump로 검증한다.
주소, 크기와 정렬을 계산한다
부트 코드의 오류는 논리보다 주소 계산에서 먼저 드러나는 경우가 많다. source range, destination range, header가 말하는 payload size, block 또는 page 단위를 표로 적고 각 구간의 끝 주소를 직접 계산한다. 끝 주소는 start + size - 1인지 exclusive end인지 API 계약을 확인한다.
성공 flag와 실제 완료 시점을 맞춘다
opteed_setup → secure context init → synchronous BL32 entry 구간에서는 부분 초기화 상태가 생길 수 있다. flag, list insertion, callback 등록, storage write 완료 중 무엇이 성공의 기준인지 찾는다. hardware write나 DMA가 포함되면 함수 반환과 장치 완료가 같은 시점인지도 확인한다.
다른 CPU, interrupt handler, USB completion 또는 shell command가 상태를 관찰할 수 있다면 memory ordering과 lock 범위도 함께 읽는다.
마지막 handoff의 계약을 적는다
정상 경로는 OP-TEE init return에서 끝난다. 이 단계가 함수 반환인지, scheduler 전환인지, 다른 image로의 비복귀 분기인지 구분한다. 비복귀 handoff라면 cache clean/invalidate, interrupt disable, 장치 quiesce, argument register와 FDT 또는 image address가 최종 점검 항목이다.
반환하는 경로라면 caller가 오류와 부분 성공을 구분하고 다음 후보 또는 복구 경로를 선택하는지 확인한다.
IMPLEMENTATION NOTES
구현을 읽을 때 놓치기 쉬운 부분
BL32 image info에서 OP-TEE init return까지 제어권이 이동하는 조건
BL32 entry parameter로 secure context를 만들고 OP-TEE의 초기 SMC return을 받아 dispatcher state를 완성하는 경로를 읽습니다. 이 경로는 함수 호출 목록만 외워서는 연결되지 않는다. BL32 image info → opteed_setup → secure context init → synchronous BL32 entry → OP-TEE init return 순서에서 각 단계가 읽는 입력, 새로 확정하는 상태, 다음 단계에 넘기는 값을 구분해야 한다. 특히 EL3 SPD initialization context에서는 이전 단계가 남긴 register와 memory attribute가 C 코드의 전제 조건이 된다.
OP-TEE는 BL31과 같은 EL에서 실행되지 않는다. EL3 dispatcher가 S-EL1 context를 소유하고 Normal World SMC마다 어느 context를 복원하는지 본다. 따라서 첫 지점에서 optee_context_t / opteed_sp_context의 주소와 owner를 기록하고, 마지막 지점에서 같은 값이 그대로 유지되는지 아니면 새 객체로 교체되는지를 확인한다. 중간 함수가 성공을 반환해도 BL32 entry, SPSR, pageable/DT arguments와 secure stack이 유효해야 하며 초기 진입이 반환된 뒤에만 OP-TEE service를 runtime에 공개해야 한다.
optee_context_t와 SPD service의 생성 시점과 수명
이 글에서 함께 나타나는 객체는 optee_context_t, BL32 entry_point_info, secure stack/context, SPD service이다. 이름이 비슷해도 저장 위치와 수명은 다르다. build-time descriptor인지, boot 단계의 임시 객체인지, world switch 뒤에도 남는 runtime 객체인지 나눠야 pointer를 따라가다 다른 단계의 구조체를 같은 것으로 오해하지 않는다.
optee_context_t / opteed_sp_context을 기준으로 allocation 또는 정적 배치 위치, list/table에 공개되는 시점, 참조가 끊기는 시점을 적는다. 그 다음 source와 destination 범위, per-CPU 여부, secure/non-secure 접근 권한을 map과 runtime log로 대조한다. 이 절차를 거치면 단순한 호출 순서가 아니라 실제 소유권 이동이 보인다.
성공 로그만으로 놓치기 쉬운 실패 경계
대표적인 실패 조건은 BL32 SPSR 오류: 최초 ERET fault; 초기 SMC protocol 불일치: dispatcher hang; per-CPU context 미생성: secondary SMC fault이다. 이 문제들은 대개 fault가 발생한 함수보다 앞에서 만들어진 잘못된 주소, size, security state 또는 refcount 때문에 생긴다. 마지막 출력만 보지 말고 각 경계 직전의 상태를 한 줄씩 남겨 최초 불일치 지점을 찾는다.
재현에는 BL32 entry와 OP-TEE _start 주소 대조; init return SMC ID 기록; primary/secondary OP-TEE context 주소 비교를 사용한다. 정상 경로와 실패 경로에서 같은 필드를 같은 위치에 출력하고, 실패가 검증 단계에서 차단되는지 아니면 다음 context까지 전파되는지 비교한다. firmware와 secure world에서는 실패 뒤의 cleanup 또는 reset 경로도 정상 경로만큼 중요하다.
DEEP ANALYSIS
레지스터에서 오류 판정까지 상세 분석
opteed는 OP-TEE 자체가 아니라 BL31 안에서 S-EL1 OP-TEE context를 관리하는 Secure Payload Dispatcher다. 최초 BL32 진입은 runtime SMC forwarding과 다르게 동기 호출로 이루어지며, OP-TEE가 초기화를 마쳤다는 특별한 SMC를 돌려줘야 BL31 초기화 흐름이 계속된다.
분석할 때 BL32 entry_point_info에서 만든 EL3 return state, optee_context_t에 저장되는 secure general/system register, OP-TEE가 사용하는 secure stack, Normal World context를 각각 분리한다. 초기화 반환을 일반 client SMC return과 섞으면 dispatcher state machine이 잘못된다.
OP-TEE _start의 실제 load address와 일치해야 한다.
S-EL1h/AArch64와 mask 상태가 OP-TEE entry 요구와 맞아야 한다.
OP-TEE pager/DT/boot-info ABI에 맞는 값이어야 한다.
현재 CPU의 secure cpu_context_t와 optee_context_t가 연결돼야 한다.
dispatcher가 기다리는 function ID와 calling convention이어야 한다.
각 계약은 앞 단계가 생산하고 현재 단계가 검증한 뒤 다음 소비자에게 넘기는 상태다. 한 항목이라도 확인되지 않으면 뒤 단계의 fault를 그 지점의 문제로 단정하지 않는다.
진입 레지스터와 메모리 계약
함수 첫 줄에 도달했을 때 이미 참이라고 가정하는 값과, 그 값이 틀렸을 때 영향을 받는 범위를 함께 적었다.
| # | 입력 상태 | 생산자 | 정상 조건 | 확인 이유 |
|---|---|---|---|---|
| 01 | BL32 ep_info.pc | BL2 image descriptor | OP-TEE _start의 실제 load address와 일치해야 한다. | 최초 secure ERET의 ELR_EL3가 된다. |
| 02 | BL32 ep_info.spsr | platform post-load hook | S-EL1h/AArch64와 mask 상태가 OP-TEE entry 요구와 맞아야 한다. | 첫 instruction의 execution mode와 stack 선택을 결정한다. |
| 03 | x0-x3 boot args | BL32 ep_info args | OP-TEE pager/DT/boot-info ABI에 맞는 값이어야 한다. | _start가 x19-x22에 보존해 C init에 전달한다. |
| 04 | secure context slot | opteed_init_optee_ep_state | 현재 CPU의 secure cpu_context_t와 optee_context_t가 연결돼야 한다. | 초기 진입과 이후 SMC에서 재사용한다. |
| 05 | init return SMC | OP-TEE 초기화 끝 | dispatcher가 기다리는 function ID와 calling convention이어야 한다. | BL31의 synchronous entry frame을 복귀시킨다. |
핵심 구조체 필드의 생산자, 소비자와 수명
구조체 이름만 나열하지 않고 어떤 코드가 값을 쓰고, 어느 코드가 처음 읽으며, 언제까지 주소와 내용이 유지되어야 하는지 구분했다.
| # | 객체 또는 필드 | 생산자 | 소비자 | 수명과 불변 조건 |
|---|---|---|---|---|
| 01 | optee_context_t | opteed context init | SMC/interrupt world switch | CPU별 secure payload context로 BL31 runtime 동안 유지된다. |
| 02 | opteed_sp_context | dispatcher global/per-CPU storage | setup와 handler | primary/secondary context 초기화 상태를 구분한다. |
| 03 | BL32 entry_point_info | BL2 | opteed_setup | 최초 entry state를 secure context에 옮길 때까지 유효하다. |
| 04 | synchronous entry frame | opteed_synchronous_sp_entry | init return handler | BL32가 초기화 SMC로 돌아올 때까지 EL3 stack에 유지된다. |
| 05 | secure cpu_context_t | context management | ERET/SMC | 현재 CPU의 S-EL1 system register와 gp_regs를 보존한다. |
| 06 | OP-TEE boot arguments | BL2/platform | OP-TEE _start/init_primary | 초기 C runtime이 복사하거나 소비할 때까지 주소와 backing memory가 유효해야 한다. |
함수 내부 실행 순서
소스의 큰 분기와 side effect를 실행 순서대로 다시 펼쳤다. breakpoint는 이 목록의 경계에 두고, 다음 번호로 넘어갈 때 새로 유효해진 객체를 기록한다.
- 01
BL31이 BL2 parameter에서 BL32 image_info와 entry_point_info를 찾고 존재 여부를 판정한다.
- 02
opteed_setup이 SPD runtime service와 BL32 init callback을 등록한다.
- 03
opteed_init_optee_ep_state가 SPSR, SCR, PC, x0-x3를 secure context에 설치한다.
- 04
현재 CPU의 optee_context_t와 generic context management slot을 연결한다.
- 05
opteed_synchronous_sp_entry가 EL3의 복귀 지점을 저장하고 secure context를 restore한다.
- 06
ERET로 OP-TEE _start에 진입해 relocation, MMU, pager, thread와 service를 초기화한다.
- 07
OP-TEE가 초기화 완료 SMC를 실행하면 EL3 vector가 opteed handler로 dispatch한다.
- 08
handler가 init return ID와 현재 dispatcher state를 확인하고 synchronous frame으로 돌아간다.
- 09
BL31은 BL32를 initialized 상태로 표시하고 BL33 non-secure context 준비를 계속한다.
빌드 설정이 바꾸는 실제 코드 경로
동일한 함수 이름이라도 아래 설정에 따라 포함되는 source, 구조체 크기, 인자 의미와 failure path가 달라진다.
| # | 설정 | 바뀌는 동작 | 확인 방법 |
|---|---|---|---|
| 01 | SPD=opteed | BL31에 OP-TEE 전용 dispatcher와 service descriptor를 포함한다. | bl31 map에서 opteed_setup/handler symbol을 확인한다. |
| 02 | BL32 | FIP에 넣을 OP-TEE image path와 ep_info source를 정한다. | FIP UUID, image base/size, OP-TEE _start 주소를 비교한다. |
| 03 | OPTEE_PAGED_IMAGE | x0 또는 boot info의 pageable payload 인자 의미가 달라질 수 있다. | TF-A platform post-load hook과 OP-TEE build mode를 맞춘다. |
| 04 | CTX_INCLUDE_* | secure context에 저장할 architecture state가 늘어난다. | OP-TEE가 사용하는 FP/PAUTH feature와 TF-A context option을 맞춘다. |
증상에서 최초 불일치 지점까지 추적하기
마지막 panic 메시지가 아니라 어디에서 멈추고 무엇을 읽어 어떤 결론을 내릴지 정리했다. 정상값과 실패값은 같은 build와 같은 위치에서 비교한다.
| # | 관찰 증상 | 중단 위치 | 기록할 값 | 판정 |
|---|---|---|---|---|
| 01 | BL32 ERET 즉시 synchronous abort | opteed entry 직전과 OP-TEE _start | ELR/SPSR/SCR, x0-x3, first opcode | load 주소, target EL, boot arg 중 어느 계약이 틀렸는지 분리한다. |
| 02 | OP-TEE banner 뒤 BL31이 멈춤 | OP-TEE init return SMC와 opteed handler | SMC FID, dispatcher state, sync frame | 초기화 완료 protocol 불일치를 확인한다. |
| 03 | 첫 client SMC에서 secure context 없음 | opteed_smc_handler | CPU index, optee_context pointer, initialized flag | primary init state가 runtime context에 공개됐는지 본다. |
| 04 | secondary CPU SMC만 실패 | secondary context init | per-CPU optee_context와 secure stack | secondary entry/initialization 경로 누락을 찾는다. |
OBJECT LIFETIME
객체와 수명
| 대상 | 만들어지는 시점 | 유효 범위 | 확인할 조건 |
|---|---|---|---|
optee_context_t / opteed_sp_context | opteed_setup | OP-TEE init return 또는 오류 정리 완료까지 | 진입 전제와 상태 계약 |
| 입력 buffer / metadata | BL32 image info | parse와 검증이 끝날 때까지 | 길이, 정렬, 소유권, 변조 가능성 |
| 등록된 list / descriptor | secure context init | subsystem 종료 또는 image handoff까지 | 이중 등록, dangling pointer, 오류 unwind |
| hardware 또는 persistent state | 실제 write/probe가 완료된 뒤 | reset 또는 명시적 해제·갱신까지 | flush, timeout, 전원 차단, rollback |
최종 부트로더 이미지 | link/image 생성 시점 | 다음 stage가 새 image로 교체할 때까지 | load address, entry, section과 header 일치 |
FAILURE PATH
실패 지점과 증상
| # | 조건 | 관찰되는 증상 | 먼저 볼 단계 |
|---|---|---|---|
| 01 | BL32 SPSR 오류 | 최초 ERET fault | opteed_setup |
| 02 | 초기 SMC protocol 불일치 | dispatcher hang | secure context init |
| 03 | per-CPU context 미생성 | secondary SMC fault | synchronous BL32 entry |
로그가 끊긴 마지막 함수만 고치지 않는다. 그 함수가 받은 주소, size, flag가 만들어진 앞 단계까지 올라가고, 오류 뒤 등록 객체와 hardware 상태가 남았는지도 확인한다.
EVIDENCE
소스 밖에서 확인할 증거
소스 해석은 실제 빌드 산출물과 target 로그로 닫아야 한다. 아래 명령의 보드 이름과 toolchain prefix는 사용 중인 빌드 환경에 맞게 바꾼다.
| # | 목적 | 명령 또는 계측 | 판정 기준 |
|---|---|---|---|
| 01 | 빌드 산출물 | make PLAT=<platform> DEBUG=1 all fip | BL1, BL2, BL31과 FIP가 같은 설정으로 만들어졌는지 전체 빌드 명령부터 기록한다. |
| 02 | FIP 구성 | tools/fiptool/fiptool info build/<platform>/debug/fip.bin | FIP 안의 BL31, BL32, BL33 UUID와 offset, 크기를 확인해 실제 적재 입력을 고정한다. |
| 03 | 심볼과 주소 | ${CROSS_COMPILE}nm -n build/<platform>/debug/bl31/bl31.elf | grep 'static int32_t opteed_setup' | 대상 함수가 BL31의 어느 주소와 섹션에 놓였는지 확인한다. |
| 04 | EL3 명령 추적 | ${CROSS_COMPILE}objdump -drS build/<platform>/debug/bl31/bl31.elf | C 코드가 EL3 system register 접근과 eret 경로로 어떻게 번역됐는지 대조한다. |
| 05 | 실행 시점 증거 | TF-A DEBUG log + CurrentEL/SCR_EL3/SPSR_EL3/x0-x3 기록 | 어느 exception level에서 어떤 security state와 인자를 다음 이미지에 넘겼는지 serial log로 남긴다. |
LAB
직접 확인할 실험
- 01BL32 entry와 OP-TEE _start 주소 대조
opteed_setup진입 전후에 optee_context_t의 주소·크기·반환값과 timestamp를 함께 남긴다. - 02init return SMC ID 기록
secure context init진입 전후에 BL32 entry_point_info의 주소·크기·반환값과 timestamp를 함께 남긴다. - 03primary/secondary OP-TEE context 주소 비교
synchronous BL32 entry진입 전후에 secure stack/context의 주소·크기·반환값과 timestamp를 함께 남긴다.
PRIMARY REFERENCES