Trusted Firmware-A · source analysis

BL31 초기화와 EL3 runtime 상주

BL31이 플랫폼, 실행 상태 관리, 런타임 서비스, 인터럽트 처리를 초기화하고 BL32 또는 BL33을 선택하는 과정을 살펴봅니다.

표의 버전은 소스 분석 기준이며 최신 보안 버전 권고가 아닙니다. TF-A LTS 2.14.3 이후에는 보안 수정이 있습니다. 제품 적용 시 공식 변경 기록과 사용 플랫폼의 errata를 확인하세요.

Series
06 / 12
Baseline
LTS 2.14.3
Commit
f5e765a3443f
Source
bl31/bl31_main.c:81-169 (발췌 범위)

CPU를 새로 켤 때는 BL31의 warm boot 경로를 봅니다

부팅을 마친 BL31은 EL3에 남아 요청을 처리합니다. CPU_ON으로 새 CPU를 시작할 때에는 각 CPU가 BL31 최초 초기화 전체를 다시 수행하는 것이 아니라 플랫폼의 warm boot 경로를 거칩니다. Linux가 넘긴 비보안 entrypoint와 context_id를 새 CPU의 context로 구성한 뒤 커널로 진입합니다.

양쪽 코드를 이어서 읽기

BL31 초기화와 EL3 runtime 상주 단계에서 실제로 바뀌는 상태는 무엇인가?

BL31은 부팅 후 사라지는 loader가 아니라 EL3에 남아 SMC, PSCI와 world switch를 처리한다. init memory와 runtime memory의 수명을 구분한다.

BL31 runtime code/data와 per-CPU context는 BL33 실행 후에도 secure하게 보존되고 모든 service가 context management 초기화 뒤 공개되어야 한다. 이 문장을 기준으로 코드를 위에서 아래로 읽으면, 함수 이름을 외우는 대신 어느 시점에 어떤 상태를 신뢰할 수 있는지 판단할 수 있다.

객체와 주소가 놓이는 구조

그림 1. BL31 초기화와 EL3 runtime 상주에서 입력, 내부 상태, 출력의 경계
입력과 전제내부 상태외부로 공개되는 결과
01BL31 image
02secure/non-secure contexts
03runtime service table
04next image info

BL31 runtime / entry_point_info_t를 중심에 놓고 왼쪽의 입력이 어떤 검사를 거쳐 오른쪽 결과로 공개되는지 표시했다. 실제 디버깅에서는 각 블록의 주소와 크기를 로그에 대입한다.

실행 흐름

그림 2. 정상 경로의 주요 호출과 상태 전달
BL2 parameters
BL31 early platform
runtime services
BL32 init
BL33 prepare

화살표는 단순 호출 순서만 뜻하지 않는다. 각 단계가 성공을 반환할 때 다음 단계가 읽을 수 있는 상태가 무엇인지 함께 확인한다. 오류 반환이 발생하면 바로 다음 화살표로 진행하지 않고 해당 단계의 정리 경로를 따라간다.

단계별 입력과 출력

각 단계의 입력과 처리 후 바뀌는 상태를 정리한 표다. 사용 중인 소스 버전에서 다른 필드를 변경한다면 그에 맞춰 표도 수정한다.

#단계진입 시 신뢰할 상태성공 뒤 남아야 할 상태다음 소비자
01BL2 parametersEL3 initialization contextBL31 imageBL31 early platform
02BL31 early platformBL2 parameters 완료 상태secure/non-secure contextsruntime services
03runtime servicesBL31 early platform 완료 상태runtime service tableBL32 init
04BL32 initruntime services 완료 상태next image infoBL33 prepare
05BL33 prepareBL32 init 완료 상태next image info최종 resident BL31 runtime firmware 또는 다음 stage

분석 범위의 전제와 비교해, 다음 단계에 잘못된 입력을 넘긴 부분부터 조사한다.

주소와 객체의 이동을 그림으로 읽기

아래 그림은 주소, 객체를 사용하는 기간, 제어권을 넘기는 시점을 중심으로 정리했다. 실제 주소와 크기는 사용 중인 보드의 bdinfo, 맵 파일과 링커 심벌로 확인한다.

그림 3. BL31 초기화와 EL3 runtime 상주의 실행 순서

각 칸은 제어권이 다음 단계로 넘어가기 전에 확정되어야 하는 상태를 나타낸다.

01BL2 parameters
02BL31 early platform
03runtime services
04BL32 init
05BL33 prepare
그림 4. BL31 init memory와 runtime memory

크기는 개념 비율이다. 실제 시작·끝 주소는 platform map과 linker symbol로 대조한다.

높은 주소↓ 주소 감소
BL31 runtime codeSMC·PSCI·context switch
runtime dataservice table·per-CPU context
BL31 stack각 CPU EL3 stack
init code/data부팅 뒤 재사용 가능
BL32 carveoutS-EL1 secure payload
BL33 / NS DRAMNormal World
낮은 주소예약 cursor 진행 방향

원본 코드

아래 코드는 Trusted Firmware-A LTS 2.14.3의 bl31/bl31_main.c에서 81-169줄을 그대로 가져온 것이다. 설명을 위해 실제 코드를 가짜 의사 코드로 바꾸지 않았다.

commitf5e765a3443fe21154aa908228e75ee2600085f6anchor · L105void __no_pauth bl31_main(
81	DEFINE_STATIC_PSCI_LIB_ARGS_V1(psci_args, bl31_warm_entrypoint);
82
83	/* PSCI is the only ARM Standard Service implemented */
84	assert(svc_mask == PSCI_FID_MASK);
85
86	return (uintptr_t)&psci_args;
87}
88
89/*******************************************************************************
90 * Simple function to initialise all BL31 helper libraries.
91 ******************************************************************************/
92static void __init bl31_lib_init(void)
93{
94	cm_init();
95}
96
97/*******************************************************************************
98 * BL31 is responsible for setting up the runtime services for the primary cpu
99 * before passing control to the bootloader or an Operating System. This
100 * function calls runtime_svc_init() which initializes all registered runtime
101 * services. The run time services would setup enough context for the core to
102 * switch to the next exception level. When this function returns, the core will
103 * switch to the programmed exception level via an ERET.
104 ******************************************************************************/
105void __no_pauth bl31_main(u_register_t arg0, u_register_t arg1, u_register_t arg2,
106		u_register_t arg3)
107{
108	unsigned int core_pos = plat_my_core_pos();
109
110	/* Enable early console if EARLY_CONSOLE flag is enabled */
111	plat_setup_early_console();
112
113	/* Perform early platform-specific setup */
114	bl31_early_platform_setup2(arg0, arg1, arg2, arg3);
115
116	/* Perform late platform-specific setup */
117	bl31_plat_arch_setup();
118
119#if FEATURE_DETECTION
120	/* Detect if features enabled during compilation are supported by PE. */
121	detect_arch_features(core_pos);
122#endif /* FEATURE_DETECTION */
123
124	/* Prints context_memory allocated for all the security states */
125	report_ctx_memory_usage();
126
127	/* Init registers that never change for the lifetime of the core. */
128	cm_manage_extensions_el3(core_pos);
129
130	/* Init per-world context registers */
131	cm_manage_extensions_per_world();
132
133	NOTICE("BL31: %s\n", build_version_string);
134	NOTICE("BL31: %s\n", build_message);
135
136#if ENABLE_RUNTIME_INSTRUMENTATION
137	PMF_CAPTURE_TIMESTAMP(bl_svc, BL31_ENTRY, PMF_CACHE_MAINT);
138#endif
139
140#ifdef SUPPORT_UNKNOWN_MPID
141	if (unsupported_mpid_flag == 0) {
142		NOTICE("Unsupported MPID detected!\n");
143	}
144#endif
145
146	/* Perform platform setup in BL31 */
147	bl31_platform_setup();
148
149#if USE_DSU_DRIVER
150	dsu_driver_init(&plat_dsu_data);
151#endif
152
153#if USE_GIC_DRIVER
154	/*
155	 * Initialize the GIC driver as well as per-cpu and global interfaces.
156	 * Platform has had an opportunity to initialise specifics.
157	 */
158	gic_init(core_pos);
159	gic_pcpu_init(core_pos);
160	gic_cpuif_enable(core_pos);
161#endif /* USE_GIC_DRIVER */
162
163	/* Initialise helper libraries */
164	bl31_lib_init();
165
166#if EL3_EXCEPTION_HANDLING
167	INFO("BL31: Initialising Exception Handling Framework\n");
168	ehf_init();
169#endif

발췌 범위와 읽기 기준

원문 81-169줄에는 앞뒤 문맥이 포함됩니다. 기준 구문 void __no_pauth bl31_main(은 L105에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.

BL31은 부팅 후 사라지는 loader가 아니라 EL3에 남아 SMC, PSCI와 world switch를 처리한다. init memory와 runtime memory의 수명을 구분한다.

함께 읽어야 하는 원본 코드

첫 코드 조각만으로 동작이 완성되지 않는 경우 호출 매크로, 객체 정의와 실제 실행 목록을 같은 페이지에 묶었다. 각 조각은 같은 기준 commit에서 가져왔다.

01. linker section의 EL3 runtime service를 초기화

common/runtime_svc.c 78-155줄이다.

filecommon/runtime_svc.canchor · L90void __init runtime_svc_init(void)
78		return -EINVAL;
79	}
80	return 0;
81}
82
83/*******************************************************************************
84 * This function calls the initialisation routine in the descriptor exported by
85 * a runtime service. Once a descriptor has been validated, its start & end
86 * owning entity numbers and the call type are combined to form a unique oen.
87 * The unique oen is used as an index into the 'rt_svc_descs_indices' array.
88 * The index of the runtime service descriptor is stored at this index.
89 ******************************************************************************/
90void __init runtime_svc_init(void)
91{
92	int rc = 0;
93	uint8_t index, start_idx, end_idx;
94	rt_svc_desc_t *rt_svc_descs;
95
96	/* Assert the number of descriptors detected are less than maximum indices */
97	assert((RT_SVC_DESCS_END >= RT_SVC_DESCS_START) &&
98			(RT_SVC_DECS_NUM < MAX_RT_SVCS));
99
100	/* If no runtime services are implemented then simply bail out */
101	if (RT_SVC_DECS_NUM == 0U) {
102		return;
103	}
104	/* Initialise internal variables to invalid state */
105	(void)memset(rt_svc_descs_indices, -1, sizeof(rt_svc_descs_indices));
106
107	rt_svc_descs = (rt_svc_desc_t *) RT_SVC_DESCS_START;
108	for (index = 0U; index < RT_SVC_DECS_NUM; index++) {
109		rt_svc_desc_t *service = &rt_svc_descs[index];
110
111		/*
112		 * An invalid descriptor is an error condition since it is
113		 * difficult to predict the system behaviour in the absence
114		 * of this service.
115		 */
116		rc = validate_rt_svc_desc(service);
117		if (rc != 0) {
118			ERROR("Invalid runtime service descriptor %p\n",
119				(void *) service);
120			panic();
121		}
122
123		/*
124		 * The runtime service may have separate rt_svc_desc_t
125		 * for its fast smc and yielding smc. Since the service itself
126		 * need to be initialized only once, only one of them will have
127		 * an initialisation routine defined. Call the initialisation
128		 * routine for this runtime service, if it is defined.
129		 */
130		if (service->init != NULL) {
131			rc = service->init();
132			if (rc != 0) {
133				ERROR("Error initializing runtime service %s\n",
134						service->name);
135				continue;
136			}
137		}
138
139		/*
140		 * Fill the indices corresponding to the start and end
141		 * owning entity numbers with the index of the
142		 * descriptor which will handle the SMCs for this owning
143		 * entity range.
144		 */
145		start_idx = (uint8_t)get_unique_oen(service->start_oen,
146						    service->call_type);
147		end_idx = (uint8_t)get_unique_oen(service->end_oen,
148						  service->call_type);
149		assert(start_idx <= end_idx);
150		assert(end_idx < MAX_RT_SVCS);
151		for (; start_idx <= end_idx; start_idx++) {
152			rt_svc_descs_indices[start_idx] = index;
153		}
154	}
155}

02. BL32 또는 BL33을 다음 ERET 대상으로 선택하는 준비 함수

bl31/bl31_main.c 283-354줄이다.

filebl31/bl31_main.canchor · L295void __init bl31_prepare_next_image_entry(void)
283	next_image_type = security_state;
284}
285
286static uint32_t bl31_get_next_image_type(void)
287{
288	return next_image_type;
289}
290
291/*******************************************************************************
292 * This function programs EL3 registers and performs other setup to enable entry
293 * into the next image after BL31 at the next ERET.
294 ******************************************************************************/
295void __init bl31_prepare_next_image_entry(void)
296{
297	const entry_point_info_t *next_image_info;
298	uint32_t image_type;
299
300#if CTX_INCLUDE_AARCH32_REGS
301	/*
302	 * Ensure that the build flag to save AArch32 system registers in CPU
303	 * context is not set for AArch64-only platforms.
304	 */
305	if (el_implemented(1) == EL_IMPL_A64ONLY) {
306		ERROR("EL1 supports AArch64-only. Please set build flag "
307				"CTX_INCLUDE_AARCH32_REGS = 0\n");
308		panic();
309	}
310#endif
311
312	/* Determine which image to execute next */
313	image_type = bl31_get_next_image_type();
314
315	/* Program EL3 registers to enable entry into the next EL */
316	next_image_info = bl31_plat_get_next_image_ep_info(image_type);
317	assert(next_image_info != NULL);
318	assert(image_type == GET_SECURITY_STATE(next_image_info->h.attr));
319
320	INFO("BL31: Preparing for EL3 exit to %s world\n",
321		(image_type == SECURE) ? "secure" : "normal");
322	print_entry_point_info(next_image_info);
323	cm_init_my_context(next_image_info);
324
325	/*
326	* If we are entering the Non-secure world, use
327	* 'cm_prepare_el3_exit_ns' to exit.
328	*/
329	if (image_type == NON_SECURE) {
330		cm_prepare_el3_exit_ns();
331	} else {
332		cm_prepare_el3_exit(image_type);
333	}
334}
335
336/*******************************************************************************
337 * This function initializes the pointer to BL32 init function. This is expected
338 * to be called by the SPD after it finishes all its initialization
339 ******************************************************************************/
340void bl31_register_bl32_init(int32_t (*func)(void))
341{
342	bl32_init = func;
343}
344
345#if ENABLE_RME
346/*******************************************************************************
347 * This function initializes the pointer to RMM init function. This is expected
348 * to be called by the RMMD after it finishes all its initialization
349 ******************************************************************************/
350void bl31_register_rmm_init(int32_t (*func)(void))
351{
352	rmm_init = func;
353}
354#endif

내부 동작을 더 깊게 읽기

01

진입 조건을 먼저 고정한다

BL2 parameters에서 들어온 실행은 EL3 initialization context에 놓여 있다. 이때 interrupt, MMU/cache, stack, heap 중 무엇이 이미 준비되었는지 소스의 호출자까지 올라가 확인한다. 같은 함수라도 SPL, relocation 전후, app thread처럼 호출 문맥이 달라지면 허용되는 API와 지연 시간이 달라진다.

BL31은 부팅 후 사라지는 loader가 아니라 EL3에 남아 SMC, PSCI와 world switch를 처리한다. init memory와 runtime memory의 수명을 구분한다.

02

중심 객체의 생성과 공개를 나눈다

이 글의 중심 객체는 BL31 runtime / entry_point_info_t다. 메모리를 확보한 시점, 필드를 채운 시점, 전역 list나 다른 subsystem에 공개한 시점을 구분한다. 공개 뒤 오류가 발생한다면 목록에서 제거하고 child, buffer, reference를 역순으로 정리하는지 확인한다.

빌드 산출물 관점에서는 resident BL31 runtime firmware 안에 해당 symbol과 section이 실제로 포함되었는지도 map과 objdump로 검증한다.

03

주소, 크기와 정렬을 계산한다

부트 코드에서는 주소 계산 오류를 주의해야 한다. 원본과 목적지의 주소 범위, 헤더에 기록된 데이터 크기, 블록·페이지 단위를 표로 정리하고 각 구간의 끝 주소를 계산한다. 끝 주소가 start + size - 1처럼 마지막 바이트를 가리키는지, 구간 바로 다음 주소를 가리키는지는 API 규약에서 확인한다.

04

성공 flag와 실제 완료 시점을 맞춘다

BL31 early platform → runtime services → BL32 init 구간에서는 부분 초기화 상태가 생길 수 있다. flag, list insertion, callback 등록, storage write 완료 중 무엇이 성공의 기준인지 찾는다. hardware write나 DMA가 포함되면 함수 반환과 장치 완료가 같은 시점인지도 확인한다.

다른 CPU, 인터럽트 처리기, USB 완료 콜백, 셸 명령에서도 이 상태를 읽는다면 메모리 접근 순서와 잠금 범위를 함께 확인한다.

05

제어권을 넘기기 전에 확인할 조건을 정리한다

정상 경로는 BL33 prepare에서 끝난다. 이 단계가 함수 반환인지, scheduler 전환인지, 다른 image로의 비복귀 분기인지 구분한다. 비복귀 handoff라면 cache clean/invalidate, interrupt disable, 장치 quiesce, argument register와 FDT 또는 image address가 최종 점검 항목이다.

호출한 함수로 돌아오는 경로라면 오류와 일부 처리만 완료된 상태를 구분하는지 확인한다. 이어서 다음 후보를 시도할지, 복구 절차를 실행할지 살펴본다.

구현을 읽을 때 놓치기 쉬운 부분

01

BL2 parameters에서 BL33 prepare까지 제어권이 이동하는 조건

BL31이 플랫폼, 실행 상태 관리, 런타임 서비스, 인터럽트 처리를 초기화하고 BL32 또는 BL33을 선택하는 과정을 살펴봅니다. 이 경로는 함수 호출 목록만 외워서는 연결되지 않는다. BL2 parameters → BL31 early platform → runtime services → BL32 init → BL33 prepare 순서에서 각 단계가 읽는 입력, 새로 확정하는 상태, 다음 단계에 넘기는 값을 구분해야 한다. 특히 EL3 initialization context에서는 이전 단계가 남긴 register와 memory attribute가 C 코드의 전제 조건이 된다.

BL31은 부팅 후 사라지는 loader가 아니라 EL3에 남아 SMC, PSCI와 world switch를 처리한다. init memory와 runtime memory의 수명을 구분한다. 따라서 첫 지점에서 BL31 runtime / entry_point_info_t의 주소와 owner를 기록하고, 마지막 지점에서 같은 값이 그대로 유지되는지 아니면 새 객체로 교체되는지를 확인한다. 중간 함수가 성공을 반환해도 BL31 runtime code/data와 per-CPU context는 BL33 실행 후에도 secure하게 보존되고 모든 service가 context management 초기화 뒤 공개되어야 한다.

02

BL31 image와 next image info의 생성 시점과 수명

이 글에서 함께 나타나는 객체는 BL31 image, secure/non-secure contexts, runtime service table, next image info이다. 이름이 비슷해도 저장 위치와 수명은 다르다. build-time descriptor인지, boot 단계의 임시 객체인지, world switch 뒤에도 남는 runtime 객체인지 나눠야 pointer를 따라가다 다른 단계의 구조체를 같은 것으로 오해하지 않는다.

BL31 runtime / entry_point_info_t을 기준으로 allocation 또는 정적 배치 위치, list/table에 공개되는 시점, 참조가 끊기는 시점을 적는다. 그 다음 source와 destination 범위, per-CPU 여부, secure/non-secure 접근 권한을 map과 runtime log로 대조한다. 이 절차를 거치면 단순한 호출 순서가 아니라 실제 소유권 이동이 보인다.

03

성공 로그만으로 놓치기 쉬운 오류

대표적인 실패 조건은 init section 조기 해제: runtime fault; BL32 callback 순서 오류: secure payload 미초기화; next image 누락: EL3 panic이다. 이 문제들은 대개 fault가 발생한 함수보다 앞에서 만들어진 잘못된 주소, size, security state 또는 refcount 때문에 생긴다. 마지막 출력만 보지 말고 각 경계 직전의 상태를 한 줄씩 남겨 최초 불일치 지점을 찾는다.

재현에는 BL31 map에서 init/runtime section 구분; runtime_svc descriptor 개수 출력; BL32 유무에 따른 next image 선택 비교를 사용한다. 정상 경로와 실패 경로에서 같은 필드를 같은 위치에 출력하고, 실패가 검증 단계에서 차단되는지 아니면 다음 context까지 전파되는지 비교한다. firmware와 secure world에서는 실패 뒤의 cleanup 또는 reset 경로도 정상 경로만큼 중요하다.

레지스터에서 오류 판정까지 상세 분석

BL31은 BL32와 BL33을 호출하고 사라지는 loader가 아니라 EL3에 계속 상주하는 runtime firmware다. 초기화 시점에는 BL2 parameter, platform console, MMU mapping을 사용하지만 정상 world 실행 뒤에는 SMC, PSCI, interrupt와 context switch를 처리할 최소 runtime 영역만 남아야 한다.

읽을 때는 init-only code/data와 resident code/data를 구분하고, runtime service descriptor가 언제 등록되는지, secure/non-secure per-CPU context가 언제 유효해지는지, BL32 초기화가 반환된 뒤 BL33을 어떤 state로 준비하는지를 한 흐름으로 연결한다.

그림 5. 이 경로를 통과하는 다섯 개의 진입 계약
01BL2 params

BL31/BL32/BL33 image_info와 ep_info를 가리켜야 한다.

02CurrentEL/SCR_EL3

BL31이 EL3 secure state에서 시작하도록 설정돼야 한다.

03BL31 stack/per-CPU data

현재 core의 runtime stack과 cpu_data가 겹치지 않아야 한다.

04runtime descriptors

OEN/call type 범위가 겹치지 않고 init callback이 성공해야 한다.

05next image

security state, target EL, PC, SPSR, args가 모두 확정돼야 한다.

각 계약은 앞 단계가 생산하고 현재 단계가 검증한 뒤 다음 소비자에게 넘기는 상태다. 한 항목이라도 확인되지 않으면 뒤 단계의 fault를 그 지점의 문제로 단정하지 않는다.

진입 레지스터와 메모리 계약

함수 첫 줄에 도달했을 때 이미 참이라고 가정하는 값과, 그 값이 틀렸을 때 영향을 받는 범위를 함께 적었다.

#입력 상태생산자정상 조건확인 이유
01BL2 paramsBL2 handoffBL31/BL32/BL33 image_info와 ep_info를 가리켜야 한다.다음 image와 runtime memory 초기화의 입력이다.
02CurrentEL/SCR_EL3BL2 contextBL31이 EL3 secure state에서 시작하도록 설정돼야 한다.EL3 register와 context management를 초기화한다.
03BL31 stack/per-CPU dataassembly entry현재 core의 runtime stack과 cpu_data가 겹치지 않아야 한다.C 초기화와 이후 SMC handler가 재사용한다.
04runtime descriptorslinker sectionOEN/call type 범위가 겹치지 않고 init callback이 성공해야 한다.SMC dispatch table의 근거다.
05next imageBL32 init 결과와 BL33 ep_infosecurity state, target EL, PC, SPSR, args가 모두 확정돼야 한다.최종 ERET의 입력이다.

핵심 구조체 필드의 생산자, 소비자와 수명

구조체 이름만 나열하지 않고 어떤 코드가 값을 쓰고, 어느 코드가 처음 읽으며, 언제까지 주소와 내용이 유지되어야 하는지 구분했다.

#객체 또는 필드생산자소비자수명과 불변 조건
01BL31 init sectionslinkerbl31_main초기화 완료 뒤 재사용·unmap될 수 있으므로 runtime callback이 참조하면 안 된다.
02per_cpu_dataBL31 early setupSMC/interrupt/PSCI각 physical CPU가 EL3에 진입할 때마다 계속 유효하다.
03runtime_svc_descs_indicesruntime_svc_inithandle_runtime_svc초기화 뒤 read-mostly table로 resident해야 한다.
04secure/non-secure cpu_contextcontext managementworld switchCPU별·security state별로 분리되어 suspend/reset 정책까지 유지된다.
05BL32 entry_point_infoBL2/post-loadSPD setupBL32 최초 init이 완료될 때까지 필요하며 이후 SPD context로 전환된다.
06BL33 entry_point_infoBL2/post-loadbl31_prepare_next_image_entry첫 non-secure ERET까지 유효하고 target context에 복사돼야 한다.

함수 내부 실행 순서

소스의 큰 분기와 side effect를 실행 순서대로 다시 펼쳤다. breakpoint는 이 목록의 경계에 두고, 다음 번호로 넘어갈 때 새로 유효해진 객체를 기록한다.

  1. 01

    assembly entry가 stack, exception vector, per-CPU pointer를 준비하고 BL2 parameter를 보존한다.

  2. 02

    early platform setup이 console과 필수 register base를 제공하되 runtime dependency와 구분한다.

  3. 03

    architecture setup이 BL31 text/rodata/RW, device, coherent memory의 EL3 translation을 만든다.

  4. 04

    platform setup이 GIC, power controller, topology와 다음 image 정보를 확정한다.

  5. 05

    runtime_svc_init이 linker section descriptor를 검증하고 OEN/call-type index table을 구축한다.

  6. 06

    context management가 secure와 non-secure context slot, EL1/EL2 system register state를 초기화한다.

  7. 07

    SPD가 있으면 BL32 entry를 설치해 synchronous init을 실행하고 초기화 완료 SMC를 받는다.

  8. 08

    BL33 ep_info를 NON_SECURE context에 복사하고 SCR_EL3/SPSR_EL3/ELR_EL3를 준비한다.

  9. 09

    init memory 의존을 끊고 cache·console 정책을 정리한 뒤 최초 BL33 ERET를 수행한다.

빌드 설정이 바꾸는 실제 코드 경로

동일한 함수 이름이라도 아래 설정에 따라 포함되는 source, 구조체 크기, 인자 의미와 failure path가 달라진다.

#설정바뀌는 동작확인 방법
01RESET_TO_BL31BL31이 reset entry와 BL2 역할 일부를 직접 처리한다.BL2 parameter가 없는 대체 경로와 next image source를 확인한다.
02SPD=opteed / SPMDBL32 초기화와 runtime SMC routing 방식이 달라진다.동시에 두 dispatcher가 활성화되지 않는지 build define을 본다.
03EL3_EXCEPTION_HANDLINGEL3 interrupt/exception framework 범위가 늘어난다.vector와 interrupt routing, stack budget을 확인한다.
04ENABLE_PAUTHBL31 return address와 context에 pointer authentication 상태가 추가된다.key init과 world switch save/restore 경로를 확인한다.
05SEPARATE_CODE_AND_RODATAresident mapping permission과 init section 배치가 달라진다.BL31 map과 translation table permission을 비교한다.

증상에서 최초 불일치 지점까지 추적하기

마지막 panic 메시지가 아니라 어디에서 멈추고 무엇을 읽어 어떤 결론을 내릴지 정리했다. 정상값과 실패값은 같은 build와 같은 위치에서 비교한다.

#관찰 증상중단 위치기록할 값판정
01BL31 banner 전 faultassembly entry와 bl31_main 첫 줄SP, x0 parameter, VBAR_EL3, SCTLR_EL3BL2 handoff와 BL31 C runtime 문제를 분리한다.
02runtime_svc_init panicdescriptor validation loopstart/end OEN, call_type, init returnlinker descriptor 중복 또는 service init 실패를 찾는다.
03BL32 init 뒤 BL33으로 못 감SPD init return과 next image selectionsecure context state, BL33 ep_infoBL32 protocol hang과 BL33 parameter 누락을 구분한다.
04Linux 실행 뒤 첫 SMC에서 crashEL3 vector와 handler dispatchper_cpu_data, runtime table, current contextinit-only memory를 runtime이 참조하는지 확인한다.

객체와 수명

대상만들어지는 시점유효 범위확인할 조건
BL31 runtime / entry_point_info_tBL31 early platformBL33 prepare 또는 오류 정리 완료까지진입 전제와 상태 계약
입력 buffer / metadataBL2 parametersparse와 검증이 끝날 때까지길이, 정렬, 소유권, 변조 가능성
등록된 list / descriptorruntime services하위 시스템을 종료하거나 다음 이미지에 제어권을 넘길 때까지중복 등록, 해제된 객체를 가리키는 포인터, 오류 후 자원 정리
hardware 또는 persistent state실제 write/probe가 완료된 뒤reset 또는 명시적 해제·갱신까지쓰기 완료, 시간 초과, 전원 차단, 이전 상태 복원
resident BL31 runtime firmwarelink/image 생성 시점다음 stage가 새 image로 교체할 때까지적재 주소, 진입점, 섹션, 헤더의 일치 여부

실패 지점과 증상

#조건관찰되는 증상먼저 볼 단계
01init section 조기 해제runtime faultBL31 early platform
02BL32 callback 순서 오류secure payload 미초기화runtime services
03next image 누락EL3 panicBL32 init

로그가 끊긴 함수뿐 아니라 그 함수에 주소, 크기, 플래그를 전달한 앞 단계도 조사한다. 오류 처리 후 등록된 객체나 하드웨어 설정이 그대로 남아 있는지도 확인한다.

소스 밖에서 확인할 증거

소스에서 파악한 동작을 실제 빌드 결과와 대상 보드의 로그로 확인한다. 아래 명령의 보드 이름과 툴체인 접두사는 사용 중인 빌드 환경에 맞게 바꾼다.

#목적명령 또는 계측판정 기준
01빌드 산출물make PLAT=<platform> DEBUG=1 all fipBL1, BL2, BL31과 FIP가 같은 설정으로 만들어졌는지 전체 빌드 명령부터 기록한다.
02FIP 구성tools/fiptool/fiptool info build/<platform>/debug/fip.binFIP 안의 BL31, BL32, BL33 UUID와 offset, 크기를 확인해 실제 적재 입력을 고정한다.
03심볼과 주소${CROSS_COMPILE}nm -n build/<platform>/debug/bl31/bl31.elf | grep 'void __no_pauth bl31_main'대상 함수가 BL31의 어느 주소와 섹션에 놓였는지 확인한다.
04EL3 명령 추적${CROSS_COMPILE}objdump -drS build/<platform>/debug/bl31/bl31.elfC 코드가 EL3 system register 접근과 eret 경로로 어떻게 번역됐는지 대조한다.
05실행 시점 증거TF-A DEBUG log + CurrentEL/SCR_EL3/SPSR_EL3/x0-x3 기록어느 exception level에서 어떤 security state와 인자를 다음 이미지에 넘겼는지 serial log로 남긴다.

직접 확인할 실험

  1. 01
    BL31 map에서 init/runtime section 구분

    BL31 early platform 진입 전후에 BL31 image의 주소·크기·반환값과 timestamp를 함께 남긴다.

  2. 02
    runtime_svc descriptor 개수 출력

    runtime services 진입 전후에 secure/non-secure contexts의 주소·크기·반환값과 timestamp를 함께 남긴다.

  3. 03
    BL32 유무에 따른 next image 선택 비교

    BL32 init 진입 전후에 runtime service table의 주소·크기·반환값과 timestamp를 함께 남긴다.

원문과 다음 글