QUESTION
어떤 reset 경로가 실제로 BL2까지 가는가?
이 글은 TF-A LTS 2.14.3 AArch64 BL1을 기준으로 한다. bl1_entrypoint의 공통 매크로가 warm reset과 secondary cold boot를 먼저 가른다. bl1_main()은 primary CPU의 cold boot에서만 호출된다.
BL2 경로에서도 인증은 무조건 실행되지 않는다. TRUSTED_BOARD_BOOT와 동적 인증 비활성화 여부를 구분하고, 마지막 인계는 ENABLE_RME에 따라 다른 코드를 따른다.
RESET BRANCHES
BL1 C 진입 전에 갈라지는 세 경로
bl1_entrypoint의 reset 분기plat_get_my_entrypoint()가 주소 반환PROGRAMMABLE_RESET_ADDRESS=0이면 해당 주소로 br. 아래 BL1 C 초기화를 다시 실행하지 않는다.
plat_is_my_cpu_primary()가 거짓COLD_BOOT_SINGLE_CPU=0이면 플랫폼의 plat_secondary_cold_boot_setup()으로 간다. 정상적으로 되돌아오지 않는다.
platform_mem_init, BSS zero, BL1 data 복사, SP_EL0 선택·plat_set_my_stack() 뒤 bl1_main() 호출.
옵션은 분기 사용 여부를 바꾼다. 실제 reset EL·ROM 계약과 플랫폼 hook은 보드 설정으로 확인한다. 공통 매크로 원문
PRIMARY COLD BOOT
bl1_main()의 상태와 분기
- 01 · early
plat_setup_early_console(),bl1_early_platform_setup(),bl1_plat_arch_setup() - 02 · EL3 contextextensions 초기화, 조건부 per-world context,
bl1_arch_setup() - 03 · 검증 준비
crypto_mod_init(),auth_mod_init(), measured boot init - 04 · platform
bl1_platform_setup()에서 플랫폼 I/O·descriptor 등을 준비 - 05 · image 선택다음 image ID가 BL2면
bl1_load_bl2(); 그 외는 FWU 진입 표시 - 06 · 인계 준비measured boot/crypto 종료 →
bl1_prepare_next_image()→ console flush → C 반환
bl1_main()이 직접 BL2로 branch하지 않는다. C 반환 후 assembly가 ENABLE_RME에 따라 EL3 출구를 고른다. FWU의 다른 image ID는 BL2 적재·인증 경로와 동일하게 그리지 않는다.
STATE LEDGER
다음 단계가 읽는 값과 조건
| 경계 | 생산자 | 소비자 | 조건·주의점 |
|---|---|---|---|
| primary cold | mailbox·primary 분기 | bl1_main() | warm/secondary는 다른 경로 |
| C runtime | BSS zero, data 복사, SP_EL0 stack | platform·crypto/auth init | 초기 stack은 SP_EL3가 아님 |
| BL2 descriptor | bl1_plat_get_image_desc() | pre hook·loader | 생성·주소는 플랫폼 계약 |
| BL2 bytes | I/O, 조건부 인증·측정, flush | post hook·인계 | 모든 빌드가 서명 검증하는 것은 아님 |
| next entry | bl1_prepare_next_image() | el3_exit 또는 Root/EL3 반환 | RME와 비 RME의 context 준비는 다름 |
VISUAL WALKTHROUGH
BL2 적재·인증과 메모리 경계
bl1_load_bl2()의 성공/오류 관문플랫폼 pre/post hook과 공통 loader의 실제 호출 순서다.
- 01descriptor 참조
bl1_plat_get_image_desc(BL2_IMAGE_ID)에서image_info를 얻는다. - 02pre hook
bl1_plat_handle_pre_image_load()실패는plat_error_handler()로 보낸다. - 03load/auth
load_auth_image()는 I/O size·maximum·read 길이를 검사한다. 신뢰 부트가 활성화되고 인증이 비활성화되지 않았다면 parent chain과 현재 image를 검증한다. - 04성공 후 효과공통 함수는 성공 뒤 플랫폼 측정을 호출하고 image 범위를 flush한다. 측정 실패도 오류다.
- 05post hook실패는 플랫폼 오류 처리. 모두 성공하면
BL1: Booting BL2.
주소 크기나 상하 관계는 플랫폼마다 달라 임의의 비율로 그리지 않았다.
- BL1 code/RO와 RW/BSS
plat_set_my_stack()가 지정한 C stack- crypto/auth용 플랫폼 작업 공간
- platform descriptor의
image_base - 상한
image_max_size - 읽은 뒤
image_size
UPSTREAM SOURCE
원본 코드
아래 코드는 Trusted Firmware-A LTS 2.14.3의 bl1/bl1_main.c에서 26-114줄을 그대로 가져온 것이다.
26#include <lib/utils.h>
27#include <plat/common/platform.h>
28#include <smccc_helpers.h>
29#include <tools_share/uuid.h>
30
31#include "bl1_private.h"
32
33static void bl1_load_bl2(void);
34
35#if ENABLE_PAUTH
36uint64_t bl1_apiakey[2];
37#endif
38
39#if ENABLE_RUNTIME_INSTRUMENTATION
40 PMF_REGISTER_SERVICE(bl_svc, PMF_RT_INSTR_SVC_ID,
41 BL_TOTAL_IDS, PMF_DUMP_ENABLE)
42#endif
43
44/*******************************************************************************
45 * Setup function for BL1.
46 * Also perform late architectural and platform specific initialization.
47 * It also queries the platform to load and run next BL image. Only called
48 * by the primary cpu after a cold boot.
49 ******************************************************************************/
50void __no_pauth bl1_main(void)
51{
52 unsigned int image_id;
53
54 /* Enable early console if EARLY_CONSOLE flag is enabled */
55 plat_setup_early_console();
56
57 /* Perform early platform-specific setup */
58 bl1_early_platform_setup();
59
60 /* Perform late platform-specific setup */
61 bl1_plat_arch_setup();
62
63 /* Init registers that don't get contexted */
64 cm_manage_extensions_el3(plat_my_core_pos());
65
66 /* When BL2 runs in Secure world, it needs a coherent context. */
67#if !BL2_RUNS_AT_EL3
68 /* Init per-world context registers. */
69 cm_manage_extensions_per_world();
70#endif
71
72#if ENABLE_RUNTIME_INSTRUMENTATION
73 PMF_CAPTURE_TIMESTAMP(bl_svc, BL1_ENTRY, PMF_CACHE_MAINT);
74#endif
75
76 /* Announce our arrival */
77 NOTICE(FIRMWARE_WELCOME_STR);
78 NOTICE("BL1: %s\n", build_version_string);
79 NOTICE("BL1: %s\n", build_message);
80
81 INFO("BL1: RAM %p - %p\n", (void *)BL1_RAM_BASE, (void *)BL1_RAM_LIMIT);
82
83 print_errata_status();
84
85#if ENABLE_ASSERTIONS
86 u_register_t val;
87 /*
88 * Ensure that MMU/Caches and coherency are turned on
89 */
90#ifdef __aarch64__
91 val = read_sctlr_el3();
92#else
93 val = read_sctlr();
94#endif
95 assert((val & SCTLR_M_BIT) != 0);
96 assert((val & SCTLR_C_BIT) != 0);
97 assert((val & SCTLR_I_BIT) != 0);
98 /*
99 * Check that Cache Writeback Granule (CWG) in CTR_EL0 matches the
100 * provided platform value
101 */
102 val = (read_ctr_el0() >> CTR_CWG_SHIFT) & CTR_CWG_MASK;
103 /*
104 * If CWG is zero, then no CWG information is available but we can
105 * at least check the platform value is less than the architectural
106 * maximum.
107 */
108 if (val != 0)
109 assert(CACHE_WRITEBACK_GRANULE == SIZE_FROM_LOG2_WORDS(val));
110 else
111 assert(CACHE_WRITEBACK_GRANULE <= MAX_CACHE_LINE_SIZE);
112#endif /* ENABLE_ASSERTIONS */
113
114 /* Perform remaining generic architectural setup from EL3 */
READING CONTRACT
발췌 범위와 읽기 기준
원문 26-114줄에는 앞뒤 문맥이 포함됩니다. 기준 구문 void __no_pauth bl1_main(void)은 L50에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.
이 발췌는 bl1_main()의 준비 단계까지만 보인다. reset 분기는 assembly와 공통 매크로, BL2 적재는 같은 파일 뒤쪽, 인계 context는 별도 파일에서 확인한다.
RELATED SOURCE
함께 읽어야 하는 원본 코드
첫 코드 조각만으로 동작이 완성되지 않는 경우 호출 매크로, 객체 정의와 실제 실행 목록을 같은 페이지에 묶었다. 각 조각은 같은 기준 commit에서 가져왔다.
01. BL1 main 시작과 BL2 loader 선언
bl1/bl1_main.c 23-91줄이다. 여기에는 bl1_load_bl2() 선언만 있고, 구현은 같은 파일의 156줄 이후에 있다.
23#include <lib/el3_runtime/context_mgmt.h>
24#include <lib/extensions/pauth.h>
25#include <lib/pmf/pmf.h>
26#include <lib/utils.h>
27#include <plat/common/platform.h>
28#include <smccc_helpers.h>
29#include <tools_share/uuid.h>
30
31#include "bl1_private.h"
32
33static void bl1_load_bl2(void);
34
35#if ENABLE_PAUTH
36uint64_t bl1_apiakey[2];
37#endif
38
39#if ENABLE_RUNTIME_INSTRUMENTATION
40 PMF_REGISTER_SERVICE(bl_svc, PMF_RT_INSTR_SVC_ID,
41 BL_TOTAL_IDS, PMF_DUMP_ENABLE)
42#endif
43
44/*******************************************************************************
45 * Setup function for BL1.
46 * Also perform late architectural and platform specific initialization.
47 * It also queries the platform to load and run next BL image. Only called
48 * by the primary cpu after a cold boot.
49 ******************************************************************************/
50void __no_pauth bl1_main(void)
51{
52 unsigned int image_id;
53
54 /* Enable early console if EARLY_CONSOLE flag is enabled */
55 plat_setup_early_console();
56
57 /* Perform early platform-specific setup */
58 bl1_early_platform_setup();
59
60 /* Perform late platform-specific setup */
61 bl1_plat_arch_setup();
62
63 /* Init registers that don't get contexted */
64 cm_manage_extensions_el3(plat_my_core_pos());
65
66 /* When BL2 runs in Secure world, it needs a coherent context. */
67#if !BL2_RUNS_AT_EL3
68 /* Init per-world context registers. */
69 cm_manage_extensions_per_world();
70#endif
71
72#if ENABLE_RUNTIME_INSTRUMENTATION
73 PMF_CAPTURE_TIMESTAMP(bl_svc, BL1_ENTRY, PMF_CACHE_MAINT);
74#endif
75
76 /* Announce our arrival */
77 NOTICE(FIRMWARE_WELCOME_STR);
78 NOTICE("BL1: %s\n", build_version_string);
79 NOTICE("BL1: %s\n", build_message);
80
81 INFO("BL1: RAM %p - %p\n", (void *)BL1_RAM_BASE, (void *)BL1_RAM_LIMIT);
82
83 print_errata_status();
84
85#if ENABLE_ASSERTIONS
86 u_register_t val;
87 /*
88 * Ensure that MMU/Caches and coherency are turned on
89 */
90#ifdef __aarch64__
91 val = read_sctlr_el3();
02. storage에서 image를 읽고 실제 크기를 확정하는 공통 loader
common/bl_common.c 63-159줄이다.
63}
64
65/*******************************************************************************
66 * Internal function to load an image at a specific address given
67 * an image ID and extents of free memory.
68 *
69 * If the load is successful then the image information is updated.
70 *
71 * Returns 0 on success, a negative error code otherwise.
72 ******************************************************************************/
73static int load_image(unsigned int image_id, image_info_t *image_data)
74{
75 uintptr_t dev_handle = 0ULL;
76 uintptr_t image_handle = 0ULL;
77 uintptr_t image_spec = 0ULL;
78 uintptr_t image_base;
79 size_t image_size = 0ULL;
80 size_t bytes_read = 0ULL;
81 int io_result;
82
83 assert(image_data != NULL);
84 assert(image_data->h.version >= VERSION_2);
85
86 image_base = image_data->image_base;
87
88 /* Obtain a reference to the image by querying the platform layer */
89 io_result = plat_get_image_source(image_id, &dev_handle, &image_spec);
90 if (io_result != 0) {
91 WARN("Failed to obtain reference to image id=%u (%i)\n",
92 image_id, io_result);
93 return io_result;
94 }
95
96 /* Attempt to access the image */
97 io_result = io_open(dev_handle, image_spec, &image_handle);
98 if (io_result != 0) {
99 WARN("Failed to access image id=%u (%i)\n",
100 image_id, io_result);
101 return io_result;
102 }
103
104 INFO("Loading image id=%u at address 0x%lx\n", image_id, image_base);
105
106 /* Find the size of the image */
107 io_result = io_size(image_handle, &image_size);
108 if (io_result != 0) {
109 WARN("Failed to determine the size of the image id=%u (%i)\n",
110 image_id, io_result);
111 goto exit_load_image;
112 }
113
114 if (image_size == 0U) {
115 WARN("image id=%u size is zero\n", image_id);
116 io_result = -EIO;
117 goto exit_load_image;
118 }
119
120 /* Check that the image size to load is within limit */
121 if (image_size > image_data->image_max_size) {
122 WARN("Image id=%u size out of bounds\n", image_id);
123 io_result = -EFBIG;
124 goto exit_load_image;
125 }
126
127 /*
128 * image_data->image_max_size is a uint32_t so image_size will always
129 * fit in image_data->image_size.
130 */
131 image_data->image_size = (uint32_t)image_size;
132
133 /* We have enough space so load the image now */
134 /* TODO: Consider whether to try to recover/retry a partially successful read */
135 io_result = io_read(image_handle, image_base, image_size, &bytes_read);
136 if ((io_result != 0) || (bytes_read < image_size)) {
137 WARN("Failed to load image id=%u (%i)\n", image_id, io_result);
138 goto exit_load_image;
139 }
140
141 INFO("Image id=%u loaded: 0x%lx - 0x%lx\n", image_id, image_base,
142 (uintptr_t)(image_base + image_size));
143
144exit_load_image:
145 (void)io_close(image_handle);
146 /* Ignore improbable/unrecoverable error in 'close' */
147
148 /* TODO: Consider maintaining open device connection from this bootloader stage */
149 (void)io_dev_close(dev_handle);
150 /* Ignore improbable/unrecoverable error in 'dev_close' */
151
152 return io_result;
153}
154
155#if TRUSTED_BOARD_BOOT
156/*
157 * This function uses recursion to authenticate the parent images up to the root
158 * of trust.
159 */
IMPLEMENTATION
함수 경계별로 읽는 실제 상태
reset과 C runtime은 별개다
공통 매크로는 warm mailbox가 켜졌을 때 플랫폼 주소로 빠지고, 필요하면 secondary cold boot도 플랫폼 대기 경로로 보낸다. primary cold boot만 memory init, BSS zero/data copy, SP_EL0 stack 지정 뒤 bl1_main()을 호출한다.
platform setup은 고정 image 배치를 가정하지 않는다
bl1_platform_setup()과 image descriptor·I/O source는 플랫폼 hook의 영역이다. Arm 공통 플랫폼 예시는 I/O 설정, FWU 판정, FW_CONFIG/transfer list 등을 다루지만 다른 보드의 주소·저장장치·descriptor 배치까지 보장하지 않는다.
적재 성공과 인증 성공을 분리한다
load_image()는 크기·최대치·실제 read 길이를 확인한다. 신뢰 부트 빌드에서는 필요 시 parent image를 재귀 로드·검증한 뒤 현재 BL2를 검증한다. 개발용 동적 인증 비활성화가 켜진 경우와 비신뢰 부트 빌드는 이 검증 경로를 밟지 않는다.
entry 정보는 인계 준비에서 소비된다
비 RME 경로는 descriptor의 ep_info에서 보안 상태를 읽고 SPSR·context를 준비한다. RME 경로는 BL2용 EL3 SPSR와 pointer를 준비해 cache flush한다. 어느 쪽도 bl1_load_bl2() 반환만으로 실행 상태가 완성되지는 않는다.
FAILURE BOUNDARIES
로그가 끊긴 위치로 경계를 좁히기
BL1 NOTICE 이전
reset EL, warm mailbox, secondary CPU 판정, BSS/data/stack 준비를 먼저 대조한다. 이 구간은 bl1_main() 발췌만으로는 보이지 않는다.
Loading BL2 이후 오류
pre hook·I/O source·zero/oversize/short read·조건부 인증과 측정·post hook 중 최초 오류를 기록한다. plat_error_handler() 호출을 임의의 재시도나 안전한 복귀로 해석하지 않는다.
Booting BL2 이후 fault
descriptor의 PC·SPSR·security attribute와 빌드의 RME 분기를 확인한다. image 검증과 CPU 실행 context는 서로 다른 관문이다.
HANDOFF PATHS
BL1 C 반환 뒤 EL3 출구가 달라진다
bl1_prepare_next_image(image_id)는 C 반환 전에 호출된다. 아래 비교는 정상적인 BL2 선택 경로에 한정한다. 이 버전의 RME 구현은 image ID가 BL2라고 assert하므로 일반 FWU 경로까지 같은 인계라고 해석하지 않는다.
ENABLE_RME에 따른 BL2 인계bl1_main() → bl1_prepare_next_image() → console flush·PAuth 비활성화 → assembly로 반환el3_exitep_info.h.attr에서 security state를 읽는다.- NS+EL2 지원이면 EL2, 아니면 EL1 SPSR를 준비한다.
- 플랫폼 ep hook →
cm_init_my_context()→cm_prepare_el3_exit(). - descriptor를 EXECUTED로 표시한 뒤 assembly의
el3_exit로 간다.
- BL2 descriptor의
ep_info를 가리킨다. - EL3 SPSR를 만들고
ep_info를 flush한다. - assembly에서 EL3 MMU/I-cache를 끄고 TLB를 무효화한다.
- ELR_EL3·SPSR_EL3·x0-x7을 채운 뒤 exception return.
BL1 context 원문과 entrypoint assembly를 같은 tag에서 대조한다.
빌드 옵션이 바꾸는 분기
| 옵션/조건 | 이 글에서 달라지는 동작 | 확인할 원문 |
|---|---|---|
PROGRAMMABLE_RESET_ADDRESS | 설정되면 BL1 warm mailbox 검사를 생략 | bl1_entrypoint.S |
COLD_BOOT_SINGLE_CPU | 설정되면 secondary cold boot 검사 분기를 생략 | bl1_entrypoint.S |
TRUSTED_BOARD_BOOT와 DYN_DISABLE_AUTH | 인증 체인 포함 및 개발용 동적 비활성화 여부 결정 | common/bl_common.c |
ENABLE_RME | Root/EL3 BL2 직접 인계와 context 기반 el3_exit를 나눔 | bl1_context_mgmt.c, bl1_entrypoint.S |
OBJECT LIFETIME
BL1이 읽고 넘기는 객체
| 객체 | 생산/참조 지점 | 검증해야 하는 범위 |
|---|---|---|
| BL1 RW/BSS와 C stack | reset 매크로의 data copy/BSS zero·plat_set_my_stack() | RAM map과 linker 배치; BL2 destination과 겹치지 않는지 |
image_desc_t.image_info | bl1_plat_get_image_desc(BL2_IMAGE_ID) | image_base, image_max_size, 읽은 뒤 image_size |
image_desc_t.ep_info | 플랫폼 descriptor와 bl1_prepare_next_image() | PC·SPSR·보안 상태·인자의 실제 next-image 계약 |
| CPU context | 비 RME의 cm_init_my_context()·cm_prepare_el3_exit() | RME Root/EL3 경로에 동일 객체 사용을 가정하지 않기 |
짧은 read 감지와 반환 오류는 같지 않습니다
LTS 2.14.3의 load_image()는 bytes_read < image_size이면 경고를 남기고 정리 경로로 갑니다. 그러나 그 분기에서 io_result를 별도 오류 값으로 바꾸지 않고 그대로 반환합니다. 따라서 I/O backend가 0을 반환하면서 읽은 길이만 짧게 보고하면 공통 loader도 0을 반환할 수 있습니다. 크기 0의 -EIO, 최대 크기 초과의 -EFBIG와 이 경우를 구분해야 합니다.
인증 활성 경로의 후속 검증과 별개로, 이 버전의 길이 비교만으로 모든 짧은 읽기가 오류 반환된다고 보증하지 않습니다. 실제 backend의 반환 코드·읽은 길이와 사용 버전의 수정 상태를 함께 대조합니다. 고정 버전의 읽기·정리·반환 코드
FAILURE PATH
다음 image로 넘어가지 못하는 지점
| 관찰 | 먼저 확인할 코드/조건 | 판정 |
|---|---|---|
| BL1 NOTICE가 없다 | warm mailbox, secondary cold boot, C stack 초기화 | BL2 인증 오류라고 단정하지 않는다. |
Failure in pre image load | 플랫폼 pre hook과 image source | 공통 loader 호출 전 오류다. |
Failed to load BL2 firmware | I/O size/read, 조건부 인증, 측정 | load_auth_image() 반환 오류를 분해한다. |
Failure in post image load | 플랫폼 post hook | bytes 적재 뒤 인계 준비 전 오류다. |
Booting BL2 뒤 fault | PC/SPSR/EL·보안 상태와 RME 분기 | 적재 성공과 실행 context 성공을 분리한다. |
EVIDENCE
빌드 산출물과 보드에서 확인할 값
아래는 이미 생성된 산출물을 읽는 예시다. <platform>과 도구 접두사는 보드 빌드에 맞춘다. 이 작업에서 실행한 명령은 아니다.
| 대상 | 읽기 전용 예시 | 비교할 값 |
|---|---|---|
| BL1 심볼 | ${CROSS_COMPILE}nm -n build/<platform>/debug/bl1/bl1.elf | grep ' bl1_main$' | BL1 ELF symbol 주소와 linker map |
| BL1 명령 | ${CROSS_COMPILE}objdump -dr build/<platform>/debug/bl1/bl1.elf | reset entry·bl1_main·EL3 exit branch |
| FIP 사용 플랫폼 | tools/fiptool/fiptool info build/<platform>/debug/fip.bin | FIP를 I/O source로 쓰는 경우에만 BL2 항목 확인 |
| 로그·레지스터 | BL1 serial log와 debugger의 PC·SPSR_EL3·SCR_EL3 | 첫 오류 위치와 보안/EL 계약 |
LAB
보드별로 확인할 실험
- 01cold/warm/secondary 경로 구별
reset 설정과 CPU 번호를 기록하고
bl1_main()진입 로그가 primary cold boot에서만 나오는지 대조한다. - 02BL2 적재 범위 확인
BL1 map의 RW/BSS/stack과 descriptor의
image_base·image_max_size·실제 크기를 같은 주소계로 비교한다. - 03인증과 인계 분리
신뢰 부트가 켜진 시험 빌드에서만 변조 image가 검증 단계에서 차단되는지 확인한다. 정상 image는 다음 PC/SPSR/EL을 RME 옵션별 원문과 대조한다.
PRIMARY REFERENCES