U-Boot · source analysis

board_init_f 초기화 배열

console 이전의 CPU, timer, DRAM, FDT, reservation 작업이 순서가 고정된 initcall 목록으로 실행되는 방식을 읽습니다.

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

Series
04 / 22
Baseline
v2026.07
Commit
ece349ade297
Source
common/board_f.c:1007-1095 (발췌 범위)

board_init_f 초기화 배열 단계에서 실제로 바뀌는 상태는 무엇인가?

initcall_run_f()의 순서는 단순한 목록이 아니라 의존성 그래프를 일렬로 편 것이다. 한 호출을 옮길 때 그 함수가 읽는 gd 필드와 driver model, timer, console의 준비 여부를 먼저 확인한다.

각 initcall은 다음 호출이 읽을 상태를 성공 시 완전히 게시해야 하며, 실패를 반환하면 INITCALL이 즉시 hang()으로 진입한다. 이 문장을 기준으로 코드를 위에서 아래로 읽으면, 함수 이름을 외우는 대신 어느 시점에 어떤 상태를 신뢰할 수 있는지 판단할 수 있다.

객체와 주소가 놓이는 구조

그림 1. board_init_f 초기화 배열에서 입력, 내부 상태, 출력의 경계
입력과 전제내부 상태외부로 공개되는 결과
01boot flags와 임시 board_f
02CPU·timer·console 준비
03DRAM 발견과 상단 예약
04relocation 인자

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

실행 흐름

그림 2. 정상 경로의 주요 호출과 상태 전달
_main
board_init_f
initcall_run_f
DRAM discovery
top-down reservation
relocation return

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

단계별 입력과 출력

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

#단계진입 시 신뢰할 상태성공 뒤 남아야 할 상태다음 소비자
01_main부트 CPU의 동기 실행 문맥boot flags와 임시 board_fboard_init_f
02board_init_f_main 완료 상태CPU·timer·console 준비initcall_run_f
03initcall_run_fboard_init_f 완료 상태DRAM 발견과 상단 예약DRAM discovery
04DRAM discoveryinitcall_run_f 완료 상태relocation 인자top-down reservation
05top-down reservationDRAM discovery 완료 상태relocation 인자relocation return
06relocation returntop-down reservation 완료 상태relocation 인자최종 relocation 전 U-Boot text와 global data 또는 다음 stage

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

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

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

그림 3. initcall_run_f를 여섯 구간으로 나눠 읽기

긴 호출 목록은 함수 이름이 아니라 다음 구간이 요구하는 상태를 생산하는 순서로 읽는다.

01image 길이·early malloc
02CPU·SoC·driver model
03timer·environment·console
04DRAM 크기 발견
05DRAM 상단 예약
06relocation metadata·정리
그림 4. 앞 단계가 생산하고 뒤 단계가 소비하는 대표 gd 필드

화살표 왼쪽 함수가 값을 채우고 오른쪽 함수가 그 값을 사용한다.

01setup_mon_lengd->mon_lenreserve_uboot
02dram_initgd->ram_sizesetup_dest_addr
03setup_dest_addrgd->start_addr_spreserve_*
04reserve_global_datanew gd 주소relocate_code
05reserve_fdtboardf.new_fdtreloc_fdt
06setup_relocgd->reloc_offrelocation fixup

원본 코드

아래 코드는 U-Boot v2026.07의 common/board_f.c에서 1007-1095줄을 그대로 가져온 것이다. 설명을 위해 실제 코드를 가짜 의사 코드로 바꾸지 않았다.

commitece349ade2973e220f524ce59e59711cc919263fanchor · L1031void board_init_f(ulong boot_flags)
1007#endif
1008	INITCALL(reloc_bootstage);
1009	INITCALL(reloc_bloblist);
1010	INITCALL(setup_reloc);
1011#if CONFIG_IS_ENABLED(X86) || CONFIG_IS_ENABLED(ARC)
1012	INITCALL(copy_uboot_to_ram);
1013	INITCALL(do_elf_reloc_fixups);
1014#endif
1015	INITCALL(clear_bss);
1016	/*
1017	 * Deregister all cyclic functions before relocation, so that
1018	 * gd->cyclic_list does not contain any references to pre-relocation
1019	 * devices. Drivers will register their cyclic functions anew when the
1020	 * devices are probed again.
1021	 *
1022	 * This should happen as late as possible so that the window where a
1023	 * watchdog device is not serviced is as small as possible.
1024	 */
1025	INITCALL(cyclic_unregister_all);
1026#if !CONFIG_IS_ENABLED(ARM) && !CONFIG_IS_ENABLED(SANDBOX)
1027	INITCALL(jump_to_copy);
1028#endif
1029}
1030
1031void board_init_f(ulong boot_flags)
1032{
1033	struct board_f boardf;
1034
1035	gd->flags = boot_flags;
1036	gd->flags &= ~GD_FLG_HAVE_CONSOLE;
1037	gd->boardf = &boardf;
1038
1039	initcall_run_f();
1040
1041#if !defined(CONFIG_ARM) && !defined(CONFIG_SANDBOX) && \
1042		!defined(CONFIG_EFI_APP) && !CONFIG_IS_ENABLED(X86_64) && \
1043		!defined(CONFIG_ARC)
1044	/* NOTREACHED - jump_to_copy() does not return */
1045	hang();
1046#endif
1047}
1048
1049#if defined(CONFIG_X86) || defined(CONFIG_ARC)
1050/*
1051 * For now this code is only used on x86.
1052 *
1053 * Run init functions which are run when U-Boot is executing from Flash with a
1054 * semi-limited 'C' environment.
1055 * The following limitations must be considered when implementing an
1056 * '_f_r' function:
1057 *  - 'static' variables are read-only
1058 *  - Global Data (gd->xxx) is read/write
1059 *
1060 * The '_f_r' sequence must, as a minimum, copy U-Boot to RAM (if
1061 * supported).  It _should_, if possible, copy global data to RAM and
1062 * initialise the CPU caches (to speed up the relocation process)
1063 *
1064 * NOTE: At present only x86 uses this route, but it is intended that
1065 * all archs will move to this when generic relocation is implemented.
1066 */
1067static void initcall_run_f_r(void)
1068{
1069#if !CONFIG_IS_ENABLED(X86_64)
1070	INITCALL(init_cache_f_r);
1071#endif
1072}
1073
1074void board_init_f_r(void)
1075{
1076	initcall_run_f_r();
1077
1078	/*
1079	 * The pre-relocation drivers may be using memory that has now gone
1080	 * away. Mark serial as unavailable - this will fall back to the debug
1081	 * UART if available.
1082	 *
1083	 * Do the same with log drivers since the memory may not be available.
1084	 */
1085	gd->flags &= ~(GD_FLG_SERIAL_READY | GD_FLG_LOG_READY);
1086#ifdef CONFIG_TIMER
1087	gd->timer = NULL;
1088#endif
1089
1090	/*
1091	 * U-Boot has been copied into SDRAM, the BSS has been cleared etc.
1092	 * Transfer execution from Flash to RAM by calculating the address
1093	 * of the in-RAM copy of board_init_r() and calling it
1094	 */
1095	(board_init_r + gd->reloc_off)((gd_t *)gd, gd->relocaddr);

발췌 범위와 읽기 기준

원문 1007-1095줄에는 앞뒤 문맥이 포함됩니다. 기준 구문 void board_init_f(ulong boot_flags)은 L1031에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.

initcall_run_f()의 순서는 단순한 목록이 아니라 의존성 그래프를 일렬로 편 것이다. 한 호출을 옮길 때 그 함수가 읽는 gd 필드와 driver model, timer, console의 준비 여부를 먼저 확인한다.

1031void board_init_f(ulong boot_flags)

relocation 전 C 초기화 단계의 진입점이다. ARM64에서는 초기 stack과 gd가 준비된 뒤 _main이 호출하며, 이 함수가 반환하면 architecture assembly가 실제 relocation을 계속한다.

1033 struct board_f boardf;

relocation 계산에만 쓰는 지역 객체를 현재 stack에 만든다. new_fdt, fdt_size, new_bootstage, new_bloblist를 보관하며 board_init_f()가 끝난 뒤에는 수명이 끝난다.

1035 gd->flags = boot_flags;

이전 stage가 전달한 부트 상태를 global data에 복사한다. 이후 initcall들이 공통으로 읽기 때문에 다른 필드보다 먼저 게시한다.

1036 gd->flags &= ~GD_FLG_HAVE_CONSOLE;

console core가 아직 사용 가능하지 않음을 명시한다. serial hardware의 물리 상태와 별개이며 serial_init()과 console_init_f() 전의 잘못된 출력 경로를 막는다.

1037 gd->boardf = &boardf;

여러 reserve/relocation 함수가 같은 임시 장부를 쓰도록 주소를 gd에 연결한다. 지역 객체 주소이므로 relocation 이후까지 보존해서는 안 된다.

1039 initcall_run_f();

실제 초기화 정책으로 들어간다. 이 호출 안에서 CPU·timer·console·DRAM 초기화와 top-down 예약이 순서대로 실행되며, 어느 하나라도 0이 아닌 값을 반환하면 hang()으로 끝난다.

1044 /* NOTREACHED - jump_to_copy() does not return */

목록 안에서 jump_to_copy()를 실행하는 architecture는 정상 경로가 여기로 돌아오지 않는다는 설명이다. ARM과 sandbox 등은 별도의 반환·relocation 경로를 사용하므로 전처리 조건에서 제외된다.

1045 hang();

비복귀 relocation 함수가 예상과 달리 반환했을 때 더 진행하지 않도록 정지한다. 이 줄에 도달했다면 단순 initcall 실패가 아니라 architecture handoff 계약이 깨진 것이다.

함께 읽어야 하는 원본 코드

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

01. INITCALL과 INITCALL_EVT의 실제 실패 처리

include/initcall.h 15-41줄이다.

fileinclude/initcall.hanchor · L15#define INITCALL(_call)
15#define INITCALL(_call) \
16	do { \
17		if (_call()) { \
18			printf("%s(): initcall %s() failed\n", __func__, \
19			       #_call); \
20			hang(); \
21		} \
22	} while (0)
23
24#define INITCALL_EVT(_evt) \
25	do { \
26		if (event_notify_null(_evt)) { \
27			printf("%s(): event %d/%s failed\n", __func__, _evt, \
28			       event_type_name(_evt)) ; \
29			hang(); \
30		} \
31	} while (0)
32
33#if defined(CONFIG_WATCHDOG) || defined(CONFIG_HW_WATCHDOG)
34#define WATCHDOG_INIT() INITCALL(init_func_watchdog_init)
35#define WATCHDOG_RESET() INITCALL(init_func_watchdog_reset)
36#else
37#define WATCHDOG_INIT()
38#define WATCHDOG_RESET()
39#endif
40
41#endif

02. relocation 전용 struct board_f의 필드와 수명

include/board_f.h 8-35줄이다.

fileinclude/board_f.hanchor · L16struct board_f {
8#define __BOARD_F
9
10/**
11 * struct board_f: Information used only before relocation
12 *
13 * This struct is set up in board_init_f() and used to deal with relocation. It
14 * is not available after relocation.
15 */
16struct board_f {
17	/**
18	 * @new_fdt: relocated device tree
19	 */
20	void *new_fdt;
21	/**
22	 * @fdt_size: space reserved for relocated device space
23	 */
24	unsigned long fdt_size;
25	/**
26	 * @new_bootstage: relocated boot stage information
27	 */
28	struct bootstage_data *new_bootstage;
29	/**
30	 * @new_bloblist: relocated blob list information
31	 */
32	struct bloblist_hdr *new_bloblist;
33};
34
35#endif

03. initcall_run_f 전체 순서

common/board_f.c 879-1030줄이다.

filecommon/board_f.canchor · L879static void initcall_run_f(void)
879static void initcall_run_f(void)
880{
881	/*
882	 * Please do not add logic to this function (variables, if (), etc.).
883	 * For simplicity it should remain an ordered list of function calls.
884	 */
885	INITCALL(setup_mon_len);
886#if CONFIG_IS_ENABLED(OF_CONTROL)
887	INITCALL(fdtdec_setup);
888#endif
889#if CONFIG_IS_ENABLED(TRACE_EARLY)
890	INITCALL(trace_early_init);
891#endif
892	INITCALL(initf_malloc);
893	INITCALL(initf_upl);
894	INITCALL(log_init);
895	INITCALL(initf_bootstage); /* uses its own timer, so does not need DM */
896	INITCALL(event_init);
897	INITCALL(bloblist_maybe_init);
898	INITCALL(setup_spl_handoff);
899#if CONFIG_IS_ENABLED(CONSOLE_RECORD_INIT_F)
900	INITCALL(console_record_init);
901#endif
902	INITCALL_EVT(EVT_FSP_INIT_F);
903	INITCALL(arch_cpu_init);	/* basic arch cpu dependent setup */
904	INITCALL(mach_cpu_init);	/* SoC/machine dependent CPU setup */
905	INITCALL(initf_dm);
906#if CONFIG_IS_ENABLED(BOARD_EARLY_INIT_F)
907	INITCALL(board_early_init_f);
908#endif
909#if defined(CONFIG_PPC) || defined(CONFIG_SYS_FSL_CLK) || defined(CONFIG_M68K)
910	/* get CPU and bus clocks according to the environment variable */
911	INITCALL(get_clocks);		/* get CPU and bus clocks (etc.) */
912#endif
913#if !defined(CONFIG_M68K) || (defined(CONFIG_M68K) && !defined(CONFIG_MCFTMR))
914	INITCALL(timer_init);		/* initialize timer */
915#endif
916#if CONFIG_IS_ENABLED(BOARD_POSTCLK_INIT)
917	INITCALL(board_postclk_init);
918#endif
919	INITCALL(env_init);		/* initialize environment */
920	INITCALL(init_baud_rate);	/* initialze baudrate settings */
921	INITCALL(serial_init);		/* serial communications setup */
922	INITCALL(console_init_f);	/* stage 1 init of console */
923	INITCALL(display_options);	/* say that we are here */
924	INITCALL(display_text_info);	/* show debugging info if required */
925	INITCALL(checkcpu);
926#if CONFIG_IS_ENABLED(SYSRESET)
927	INITCALL(print_resetinfo);
928#endif
929	/* display cpu info (and speed) */
930#if CONFIG_IS_ENABLED(DISPLAY_CPUINFO)
931	INITCALL(print_cpuinfo);
932#endif
933#if CONFIG_IS_ENABLED(DTB_RESELECT)
934	INITCALL(embedded_dtb_select);
935#endif
936#if CONFIG_IS_ENABLED(DISPLAY_BOARDINFO)
937	INITCALL(show_board_info);
938#endif
939	WATCHDOG_INIT();
940	INITCALL_EVT(EVT_MISC_INIT_F);
941	WATCHDOG_RESET();
942#if CONFIG_IS_ENABLED(SYS_I2C_LEGACY)
943	INITCALL(init_func_i2c);
944#endif
945	INITCALL(announce_dram_init);
946	INITCALL(dram_init);		/* configure available RAM banks */
947#if CONFIG_IS_ENABLED(POST)
948	INITCALL(post_init_f);
949#endif
950	WATCHDOG_RESET();
951#if defined(CFG_SYS_DRAM_TEST)
952	INITCALL(testdram);
953#endif /* CFG_SYS_DRAM_TEST */
954	WATCHDOG_RESET();
955#if CONFIG_IS_ENABLED(POST)
956	INITCALL(init_post);
957#endif
958	WATCHDOG_RESET();
959	/*
960	 * Now that we have DRAM mapped and working, we can
961	 * relocate the code and continue running from DRAM.
962	 *
963	 * Reserve memory at end of RAM for (top down in that order):
964	 *  - area that won't get touched by U-Boot and Linux (optional)
965	 *  - kernel log buffer
966	 *  - protected RAM
967	 *  - LCD framebuffer
968	 *  - monitor code
969	 *  - board info struct
970	 */
971	INITCALL(setup_dest_addr);
972#if CONFIG_IS_ENABLED(OF_BOARD_FIXUP) && \
973    !CONFIG_IS_ENABLED(OF_INITIAL_DTB_READONLY)
974	INITCALL(fix_fdt);
975#endif
976#ifdef CFG_PRAM
977	INITCALL(reserve_pram);
978#endif
979	INITCALL(reserve_round_4k);
980	INITCALL(setup_relocaddr_from_bloblist);
981	INITCALL(arch_reserve_mmu);
982	INITCALL(reserve_video);
983	INITCALL(reserve_trace);
984	INITCALL(reserve_uboot);
985	INITCALL(reserve_malloc);
986	INITCALL(reserve_board);
987	INITCALL(reserve_global_data);
988	INITCALL(reserve_fdt);
989#if CONFIG_IS_ENABLED(OF_BOARD_FIXUP) && \
990    CONFIG_IS_ENABLED(OF_INITIAL_DTB_READONLY)
991	INITCALL(reloc_fdt);
992	INITCALL(fix_fdt);
993#endif
994	INITCALL(reserve_bootstage);
995	INITCALL(reserve_bloblist);
996	INITCALL(reserve_arch);
997	INITCALL(reserve_stacks);
998	INITCALL(dram_init_banksize);
999	INITCALL(show_dram_config);
1000	WATCHDOG_RESET();
1001	INITCALL(setup_bdinfo);
1002	INITCALL(display_new_sp);
1003	WATCHDOG_RESET();
1004#if !CONFIG_IS_ENABLED(OF_BOARD_FIXUP) || \
1005    !CONFIG_IS_ENABLED(INITIAL_DTB_READONLY)
1006	INITCALL(reloc_fdt);
1007#endif
1008	INITCALL(reloc_bootstage);
1009	INITCALL(reloc_bloblist);
1010	INITCALL(setup_reloc);
1011#if CONFIG_IS_ENABLED(X86) || CONFIG_IS_ENABLED(ARC)
1012	INITCALL(copy_uboot_to_ram);
1013	INITCALL(do_elf_reloc_fixups);
1014#endif
1015	INITCALL(clear_bss);
1016	/*
1017	 * Deregister all cyclic functions before relocation, so that
1018	 * gd->cyclic_list does not contain any references to pre-relocation
1019	 * devices. Drivers will register their cyclic functions anew when the
1020	 * devices are probed again.
1021	 *
1022	 * This should happen as late as possible so that the window where a
1023	 * watchdog device is not serviced is as small as possible.
1024	 */
1025	INITCALL(cyclic_unregister_all);
1026#if !CONFIG_IS_ENABLED(ARM) && !CONFIG_IS_ENABLED(SANDBOX)
1027	INITCALL(jump_to_copy);
1028#endif
1029}
1030

내부 동작을 더 깊게 읽기

01

진입 조건을 먼저 고정한다

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

initcall_run_f()의 순서는 단순한 목록이 아니라 의존성 그래프를 일렬로 편 것이다. 한 호출을 옮길 때 그 함수가 읽는 gd 필드와 driver model, timer, console의 준비 여부를 먼저 확인한다.

02

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

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

빌드 산출물 관점에서는 relocation 전 U-Boot text와 global data 안에 해당 symbol과 section이 실제로 포함되었는지도 map과 objdump로 검증한다.

03

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

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

04

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

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

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

05

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

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

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

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

01

board_init_f는 초기화 구현이 아니라 실행 순서를 여는 얇은 진입점이다

board_init_f() 자체에는 CPU clock, DRAM controller, serial driver를 직접 만지는 코드가 없다. 이 함수가 하는 일은 부트 플래그를 gd에 옮기고, 아직 console을 사용할 수 없음을 표시하고, relocation 전에만 필요한 struct board_f를 연결한 뒤 initcall_run_f()를 호출하는 것이다. 따라서 이 글을 함수 본문 19줄에서 끝내면 핵심을 놓친다. 실제 초기화 정책은 initcall_run_f()에 적힌 호출 순서에 있다.

호출 순서는 링크 시 수집되는 Linux initcall 표가 아니라 C 소스에 직접 나열된 목록이다. 전처리 결과에 따라 항목이 사라지므로 소스의 겉모양과 실제 binary의 순서는 다를 수 있다. 분석할 보드의 .config로 common/board_f.c를 전처리한 결과를 함께 봐야 한다.

02

boot_flags를 복사한 직후 console flag를 지우는 이유

gd->flags = boot_flags는 이전 stage가 넘긴 실행 조건을 보존한다. 바로 다음 줄의 gd->flags &= ~GD_FLG_HAVE_CONSOLE은 serial hardware가 반드시 꺼져 있다는 뜻이 아니라 U-Boot의 console 계층을 아직 호출 가능한 상태로 간주하지 않겠다는 선언이다. serial_init()과 console_init_f()가 끝나기 전에 이 비트를 남겨 두면 출력 함수가 준비되지 않은 console device를 따라갈 수 있다.

이 구간의 실패는 UART에 아무것도 남지 않을 수 있다. JTAG에서 PC를 보거나 GPIO 토글, SRAM trace buffer처럼 console에 의존하지 않는 관찰 수단이 필요하다. INITCALL의 오류 printf()도 console 초기화 전에는 화면에 보인다고 가정할 수 없다.

03

struct board_f는 relocation 전에만 유효한 임시 장부다

struct board_f boardf는 board_init_f()의 stack 지역 객체이고 gd->boardf가 그 주소를 가리킨다. 여기에는 새 FDT 주소와 예약 크기, 옮겨질 bootstage와 bloblist 주소가 들어간다. 이 정보는 DRAM 상단을 깎아 relocation 목적지를 계산하는 동안만 필요하다.

ARM 경로에서 board_init_f()가 반환하면 지역 객체의 C 수명은 끝난다. 이후 코드는 gd->boardf를 runtime 객체처럼 보관해서는 안 된다. 실제 runtime 상태는 relocation된 FDT, bootstage, bloblist와 새 gd로 넘어간다. 이 수명 경계를 어기면 relocation 전 stack 주소를 DRAM 실행 단계에서 다시 읽는 문제가 생긴다.

04

초기화 목록은 다섯 구간으로 나눠 읽어야 한다

첫 구간은 image 길이, early malloc, log, event, bloblist처럼 다른 초기화가 사용할 기반을 만든다. 둘째 구간은 architecture와 SoC CPU 설정, driver model, timer, environment, baud rate, serial과 console을 준비한다. 셋째 구간의 dram_init()이 사용 가능한 RAM 크기를 확정해야 비로소 relocation 주소 계산을 시작할 수 있다.

넷째 구간은 setup_dest_addr() 뒤에서 DRAM 상단 주소를 아래로 내리며 PRAM, MMU table, video, trace, U-Boot image, malloc, board info, global data, FDT, bootstage, bloblist, stack을 차례로 예약한다. 마지막 구간은 예약 결과를 실제 포인터와 relocation offset으로 바꾸고 BSS와 cyclic callback을 정리한 뒤 architecture별 relocation 경로로 넘긴다.

05

DRAM 발견과 DRAM 예약은 같은 단계가 아니다

dram_init()은 controller가 이미 사용할 수 있다는 전제에서 전체 RAM 크기 같은 topology 정보를 gd에 기록한다. 그 다음 setup_dest_addr()와 reserve_*() 함수들은 그 크기를 소비해 U-Boot가 차지할 구간을 계산한다. dram_init_banksize()는 더 뒤에서 bd->bi_dram[] 같은 bank별 정보를 채운다. 이름이 비슷해도 생산하는 필드와 호출 시점이 다르다.

예약 함수들은 allocator처럼 독립적으로 빈 공간을 찾지 않는다. 공통 cursor인 gd->start_addr_sp 또는 relocation 관련 주소를 위에서 아래로 줄인다. 한 함수의 정렬 반올림과 차감 크기가 틀리면 이후 모든 주소가 함께 밀리므로, 마지막 fault 주소만 보고 원인을 찾기 어렵다.

06

INITCALL의 실패 계약은 복구가 아니라 정지다

INITCALL(fn)은 fn()의 반환값이 0이 아니면 함수 이름을 출력하고 hang()을 호출한다. 여기에는 자동 rollback이나 다음 후보로 넘어가는 정책이 없다. 따라서 각 init 함수는 실패 전에 외부에 공개한 device, list, clock 상태를 스스로 정리하거나, 정리할 수 없는 상태라면 reset 전까지 안전하게 멈출 수 있어야 한다.

watchdog이 활성화된 보드에서는 hang()이 영구 정지로 관찰되지 않고 일정 시간 뒤 reset으로 보일 수 있다. console 준비 이전 실패, console 준비 이후 실패, watchdog reset 누락을 구분하려면 reset cause register와 마지막으로 완료된 initcall 번호를 함께 남기는 편이 낫다.

07

ARM과 x86/ARC의 relocation 경로를 한 문장으로 묶으면 안 된다

목록 끝의 copy_uboot_to_ram()과 do_elf_reloc_fixups()는 x86 또는 ARC에서만 포함된다. ARM은 board_init_f()가 반환한 뒤 crt0_64.S 같은 architecture 진입 코드가 relocate_code를 호출한다. 같은 board_init_f()를 읽더라도 비복귀 지점과 stack 전환 위치가 architecture마다 다르다.

디버거에서 initcall_run_f() 다음 PC를 예상할 때 현재 architecture의 전처리 결과를 기준으로 해야 한다. ARM에서 목록 안의 jump_to_copy()를 찾거나, x86에서 ARM assembly의 반환 경로를 대입하면 relocation 직전의 제어 흐름을 잘못 해석하게 된다.

객체와 수명

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

실패 지점과 증상

#조건관찰되는 증상먼저 볼 단계
01timer 이전 delay 호출watchdog 또는 polling loop가 끝나지 않음board_init_f
02DRAM 크기 미확정 상태의 reserve`gd->relocaddr`와 stack 주소가 실제 RAM 밖에 놓임initcall_run_f
03console 전 오류실패 메시지를 출력할 장치가 없어 무출력 reset처럼 보임DRAM discovery

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

소스 밖에서 확인할 증거

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

#목적명령 또는 계측판정 기준
01전처리 결과make <board>_defconfig && make V=1선택된 CONFIG와 실제 compile/link 명령을 보관한다.
02symbol과 section${CROSS_COMPILE}nm -n u-boot | grep 'void board_init_f'symbol 주소가 기대한 stage와 image에 들어갔는지 확인한다.
03어셈블리 대조${CROSS_COMPILE}objdump -drS u-bootC 한 줄이 실제 branch, relocation, memory access로 어떻게 바뀌었는지 본다.
04주소 배치bdinforelocaddr, malloc, FDT, stack과 DRAM bank 주소를 한 번에 기록한다.
05runtime 관찰dm tree; dm uclass; printenvdriver model과 환경이 이 단계에서 실제로 공개되었는지 확인한다.

직접 확인할 실험

  1. 01
    `INITCALL`에 임시 timestamp와 함수 이름 출력을 넣어 실제 순서 측정

    board_init_f 진입 전후에 boot flags와 임시 board_f의 주소·크기·반환값과 timestamp를 함께 남긴다.

  2. 02
    `dram_init`, `setup_dest_addr`, `reserve_uboot`, `setup_reloc` 전후의 gd 필드 비교

    initcall_run_f 진입 전후에 CPU·timer·console 준비의 주소·크기·반환값과 timestamp를 함께 남긴다.

  3. 03
    임의 initcall에 오류 반환을 주입하고 console 준비 전후의 관찰 차이 기록

    DRAM discovery 진입 전후에 DRAM 발견과 상단 예약의 주소·크기·반환값과 timestamp를 함께 남긴다.

원문과 다음 글