U-Boot · source analysis

booti에서 ARM64 Linux로 handoff

raw ARM64 Image header를 검사하고 initrd/FDT를 배치한 뒤 kernel entry로 분기하는 경로를 읽습니다.

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

Series
17 / 22
Baseline
v2026.07
Commit
ece349ade297
Source
cmd/booti.c:88-176 (발췌 범위)

U-Boot가 넘긴 값을 커널에서 받는 위치

ARM64 직접 부팅에서 최종 DTB의 물리 주소는 x0로, x1~x3은 0으로 전달합니다. Linux head.S는 DTB 주소를 x21과 boot_args에 보존합니다. 이후 fixmap으로 읽을 주소를 준비하고 FDT의 chosen·메모리 정보를 해석합니다. initramfs 위치는 chosen 속성으로 전달하며 x1·x2를 initramfs 인자로 쓰는 규약이 아닙니다.

양쪽 코드를 이어서 읽기

booti에서 ARM64 Linux로 handoff 단계에서 실제로 바뀌는 상태는 무엇인가?

분기 직전에는 bootloader의 편의 기능보다 Linux boot protocol을 우선한다. x0의 FDT 주소, EL, MMU/cache 상태, reserved memory 반영을 체크한다.

kernel entry가 보는 Image, FDT, initrd는 서로 겹치지 않고 ARM64 boot protocol의 register와 CPU 상태를 만족해야 한다. 이 문장을 기준으로 코드를 위에서 아래로 읽으면, 함수 이름을 외우는 대신 어느 시점에 어떤 상태를 신뢰할 수 있는지 판단할 수 있다.

객체와 주소가 놓이는 구조

그림 1. booti에서 ARM64 Linux로 handoff에서 입력, 내부 상태, 출력의 경계
입력과 전제내부 상태외부로 공개되는 결과
01ARM64 Image
02bootm_headers
03working FDT
04EL and register contract

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

실행 흐름

그림 2. 정상 경로의 주요 호출과 상태 전달
booti command
Image header
bootm states
FDT/initrd setup
kernel entry

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

단계별 입력과 출력

호출 순서를 함수 이름으로만 외우지 않고, 각 단계가 무엇을 받아 무엇을 공개하는지 적은 표다. 실제 소스에서 생산 필드가 다르면 표를 고치는 방식으로 사용한다.

#단계진입 시 신뢰할 상태성공 뒤 남아야 할 상태다음 소비자
01booti command부트 CPU의 동기 실행 문맥ARM64 ImageImage header
02Image headerbooti command 완료 상태bootm_headersbootm states
03bootm statesImage header 완료 상태working FDTFDT/initrd setup
04FDT/initrd setupbootm states 완료 상태EL and register contractkernel entry
05kernel entryFDT/initrd setup 완료 상태EL and register contract최종 최종 부트로더 이미지 또는 다음 stage

분석 범위의 전제와 비교해, 다음 단계의 입력 조건을 처음 어긴 생산 단계부터 조사한다.

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

아래 그림은 호출 이름보다 주소, 객체 수명과 handoff 경계를 먼저 볼 수 있도록 구성했다. 실제 주소와 크기는 사용 중인 보드의 bdinfo, map과 linker symbol을 대입한다.

그림 3. kernel Image, initrd, DTB가 임시 적재 주소에서 최종 주소로 이동하는 과정

왼쪽은 storage나 network에서 읽은 직후의 staging 주소이고, 오른쪽은 Linux로 분기하기 직전의 최종 배치다. 주소는 개념도이며 실제 값은 보드의 DRAM map과 environment에 따라 달라진다.

01 · LOAD

임시 적재 주소

파일을 읽기 편한 빈 RAM에 우선 올린 상태

HIGHLOW
U-Boot runtimerelocaddr · malloc · stack

booti가 끝날 때까지 덮으면 안 되는 영역

사용 가능한 RAMstaging 사이의 빈 공간

아직 최종 배치가 확정되지 않은 공간

DTB sourcefdt_addr_r

storage에서 읽은 원본 DTB

initrd sourceramdisk_addr_r

initramfs archive와 size

kernel Image sourcekernel_addr_r / loadaddr

raw Image 또는 압축 Image의 입력 buffer

DRAM base사용 가능한 RAM의 시작

보드가 Linux에 공개할 물리 메모리

kernel Imagekernel_addr_rbooti_setup() + memmove images->ep
initrdramdisk_addr_rLMB + boot_ramdisk_high() final initrd range
DTBfdt_addr_rLMB + boot_relocate_fdt() working FDT
02 · HANDOFF

Linux 진입 직전의 최종 주소

실행 조건과 reserved range를 만족하도록 다시 배치

HIGHLOW
U-Boot runtimehandoff 전까지 유지

자기 stack·heap과 payload가 겹치지 않아야 함

working DTBfinal_fdt · 8-byte aligned

여유 공간을 확보하고 /chosen을 수정한 사본

final initrdinitrd_start .. initrd_end

kernel Image와 같은 허용 window 안의 보존 구간

kernel이 사용할 RAMLMB reservation 제외

부팅 뒤 page allocator에 넘길 수 있는 공간

final kernel Image2 MiB aligned base + text_offset

image_size 전체가 안전한 실행 위치

DRAM baseusable system RAM

가능하면 낮은 주소 쪽에 kernel을 배치

ARM64 Linux entry contract
PCfinal kernel entryCPU가 Image 첫 instruction으로 분기
x0final DTB addressLinux가 hardware와 bootargs를 읽는 물리 주소
/chosenlinux,initrd-start / linux,initrd-endinitrd 위치는 DTB property로 전달
x1-x30ARM64 Linux boot protocol의 reserved register
그림 4. booti가 세 payload의 최종 주소를 확정하는 순서

load 명령의 주소는 출발점일 뿐이다. Image header와 LMB reservation을 읽은 뒤에야 Linux가 실제로 볼 주소가 확정된다.

01kernel·initrd·DTB를 staging RAM에 load
02Image header의 text_offset·image_size 확인
03U-Boot·reserved-memory를 LMB에 예약
04kernel destination 계산과 copy/decompress
05initrd 최종 range 선택과 필요 시 copy
06DTB 확장·copy 후 /chosen 수정
07cache clean·MMU/interrupt 상태 정리
08x0=DTB, PC=kernel entry로 분기
그림 5. 처음 읽은 주소를 그대로 사용하지 않는 이유

staging 주소는 입출력 편의를 위한 위치이고, final 주소는 Linux boot protocol과 메모리 안전성을 만족해야 하는 위치다.

01

kernel 실행 위치 계약

문제가 되는 상태Image가 잘못된 base에서 시작

실패 결과초기 page table 또는 linear map 전제 불일치

2 MiB aligned base + text_offset, image_size 범위 확보
02

source와 destination 충돌 방지

문제가 되는 상태copy/decompress 출력이 입력 buffer를 덮음

실패 결과Image 후반부가 손상되어 early boot fault

두 반개구간 [start, end)의 교차 여부를 먼저 검사
03

DTB를 수정할 작업 공간

문제가 되는 상태원본 DTB 뒤에 여유 공간이 없음

실패 결과/chosen, memory, reserved-memory fixup 실패

writable buffer와 padding을 확보한 working FDT 사용
04

initrd 수명 보장

문제가 되는 상태kernel이 풀기 전에 다른 buffer가 initrd를 덮음

실패 결과invalid compressed data 또는 rootfs mount 실패

final range를 LMB로 예약하고 DTB /chosen에 기록

원본 코드

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

commitece349ade2973e220f524ce59e59711cc919263fanchor · L112int do_booti(struct cmd_tbl *cmdtp
88	images->ep = relocated_addr;
89	images->os.start = relocated_addr;
90	images->os.end = relocated_addr + image_size;
91
92	ep_addr = (phys_addr_t)images->ep;
93	ret = lmb_alloc_mem(LMB_MEM_ALLOC_ADDR, 0, &ep_addr,
94			    le32_to_cpu(image_size), LMB_NONE);
95	if (ret) {
96		printf("Failed to allocate memory for the image at %#llx\n",
97		       (unsigned long long)images->ep);
98		return 1;
99	}
100
101	/*
102	 * Handle the BOOTM_STATE_FINDOTHER state ourselves as we do not
103	 * have a header that provide this informaiton.
104	 */
105	if (bootm_find_images(image_load_addr, bmi->conf_ramdisk, bmi->conf_fdt,
106			      relocated_addr, image_size))
107		return 1;
108
109	return 0;
110}
111
112int do_booti(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[])
113{
114	struct bootm_info bmi;
115	int states;
116	int ret;
117
118	/* Consume 'booti' */
119	argc--; argv++;
120
121	bootm_init(&bmi);
122	if (argc)
123		bmi.addr_img = argv[0];
124	if (argc > 1)
125		bmi.conf_ramdisk = argv[1];
126	if (argc > 2)
127		bmi.conf_fdt = argv[2];
128	bmi.boot_progress = true;
129	bmi.cmd_name = "booti";
130	/* do not set up argc and argv[] since nothing uses them */
131
132	if (booti_start(&bmi))
133		return 1;
134
135	/*
136	 * We are doing the BOOTM_STATE_LOADOS state ourselves, so must
137	 * disable interrupts ourselves
138	 */
139	bootm_disable_interrupts();
140
141	images.os.os = IH_OS_LINUX;
142	if (IS_ENABLED(CONFIG_RISCV_SMODE))
143		images.os.arch = IH_ARCH_RISCV;
144	else if (IS_ENABLED(CONFIG_ARM64))
145		images.os.arch = IH_ARCH_ARM64;
146
147	states = BOOTM_STATE_MEASURE | BOOTM_STATE_OS_PREP |
148		BOOTM_STATE_OS_FAKE_GO | BOOTM_STATE_OS_GO;
149	if (IS_ENABLED(CONFIG_SYS_BOOT_RAMDISK_HIGH))
150		states |= BOOTM_STATE_RAMDISK;
151
152	ret = bootm_run_states(&bmi, states);
153
154	return ret;
155}
156
157U_BOOT_LONGHELP(booti,
158	"[addr [initrd[:size]] [fdt]]\n"
159	"    - boot Linux flat or compressed 'Image' stored at 'addr'\n"
160	"\tThe argument 'initrd' is optional and specifies the address\n"
161	"\tof an initrd in memory. The optional parameter ':size' allows\n"
162	"\tspecifying the size of a RAW initrd.\n"
163	"\tCurrently only booting from gz, bz2, lzma and lz4 compression\n"
164	"\ttypes are supported. In order to boot from any of these compressed\n"
165	"\timages, user have to set kernel_comp_addr_r and kernel_comp_size environment\n"
166	"\tvariables beforehand.\n"
167#if defined(CONFIG_OF_LIBFDT)
168	"\tSince booting a Linux kernel requires a flat device-tree, a\n"
169	"\tthird argument providing the address of the device-tree blob\n"
170	"\tis required. To boot a kernel with a device-tree blob but\n"
171	"\twithout an initrd image, use a '-' for the initrd argument.\n"
172#endif
173	);
174
175U_BOOT_CMD(
176	booti,	CONFIG_SYS_MAXARGS,	1,	do_booti,

발췌 범위와 읽기 기준

원문 88-176줄에는 앞뒤 문맥이 포함됩니다. 기준 구문 int do_booti(struct cmd_tbl *cmdtp은 L112에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.

분기 직전에는 bootloader의 편의 기능보다 Linux boot protocol을 우선한다. x0의 FDT 주소, EL, MMU/cache 상태, reserved memory 반영을 체크한다.

함께 읽어야 하는 원본 코드

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

01. ARM64 Image header에서 최종 kernel 주소를 계산하는 booti_setup

arch/arm/lib/image.c 21-79줄이다.

filearch/arm/lib/image.canchor · L31int booti_setup(ulong image
21	uint64_t	text_offset;	/* Image load offset, LE */
22	uint64_t	image_size;	/* Effective Image size, LE */
23	uint64_t	flags;		/* Kernel flags, LE */
24	uint64_t	res2;		/* reserved */
25	uint64_t	res3;		/* reserved */
26	uint64_t	res4;		/* reserved */
27	uint32_t	magic;		/* Magic number */
28	uint32_t	res5;
29};
30
31int booti_setup(ulong image, ulong *relocated_addr, ulong *size,
32		bool force_reloc)
33{
34	struct Image_header *ih;
35	uint64_t dst;
36	uint64_t image_size, text_offset;
37
38	*relocated_addr = image;
39
40	ih = (struct Image_header *)map_sysmem(image, 0);
41
42	if (ih->magic != le32_to_cpu(LINUX_ARM64_IMAGE_MAGIC)) {
43		puts("Bad Linux ARM64 Image magic!\n");
44		return 1;
45	}
46
47	/*
48	 * Prior to Linux commit a2c1d73b94ed, the text_offset field
49	 * is of unknown endianness.  In these cases, the image_size
50	 * field is zero, and we can assume a fixed value of 0x80000.
51	 */
52	if (ih->image_size == 0) {
53		puts("Image lacks image_size field, assuming 16MiB\n");
54		image_size = 16 << 20;
55		text_offset = 0x80000;
56	} else {
57		image_size = le64_to_cpu(ih->image_size);
58		text_offset = le64_to_cpu(ih->text_offset);
59	}
60
61	*size = image_size;
62
63	/*
64	 * If bit 3 of the flags field is set, the 2MB aligned base of the
65	 * kernel image can be anywhere in physical memory, so respect
66	 * images->ep.  Otherwise, relocate the image to the base of RAM
67	 * since memory below it is not accessible via the linear mapping.
68	 */
69	if (!force_reloc && (le64_to_cpu(ih->flags) & BIT(3)))
70		dst = image - text_offset;
71	else
72		dst = gd->bd->bi_dram[0].start;
73
74	*relocated_addr = ALIGN(dst, SZ_2M) + text_offset;
75
76	unmap_sysmem(ih);
77
78	return 0;
79}

02. initrd_high와 LMB로 initrd 최종 구간을 정하는 boot_ramdisk_high

boot/image-board.c 520-632줄이다.

fileboot/image-board.canchor · L539int boot_ramdisk_high(ulong rd_data
520 * boot_ramdisk_high - relocate init ramdisk
521 * @rd_data: ramdisk data start address
522 * @rd_len: ramdisk data length
523 * @initrd_start: pointer to a ulong variable, will hold final init ramdisk
524 *      start address (after possible relocation)
525 * @initrd_end: pointer to a ulong variable, will hold final init ramdisk
526 *      end address (after possible relocation)
527 *
528 * boot_ramdisk_high() takes a relocation hint from "initrd_high" environment
529 * variable and if requested ramdisk data is moved to a specified location.
530 *
531 * Initrd_start and initrd_end are set to final (after relocation) ramdisk
532 * start/end addresses if ramdisk image start and len were provided,
533 * otherwise set initrd_start and initrd_end set to zeros.
534 *
535 * returns:
536 *      0 - success
537 *     -1 - failure
538 */
539int boot_ramdisk_high(ulong rd_data, ulong rd_len, ulong *initrd_start,
540		      ulong *initrd_end)
541{
542	int err;
543	char	*s;
544	phys_addr_t initrd_high;
545	int	initrd_copy_to_ram = 1;
546
547	s = env_get("initrd_high");
548	if (s) {
549		/* a value of "no" or a similar string will act like 0,
550		 * turning the "load high" feature off. This is intentional.
551		 */
552		initrd_high = hextoul(s, NULL);
553		if (initrd_high == ~0)
554			initrd_copy_to_ram = 0;
555	} else {
556		initrd_high = env_get_bootm_mapsize() + env_get_bootm_low();
557	}
558
559	debug("## initrd_high = 0x%llx, copy_to_ram = %d\n",
560	      (u64)initrd_high, initrd_copy_to_ram);
561
562	if (rd_data) {
563		if (!initrd_copy_to_ram) {	/* zero-copy ramdisk support */
564			phys_addr_t initrd_addr;
565
566			debug("   in-place initrd\n");
567			*initrd_start = rd_data;
568			*initrd_end = rd_data + rd_len;
569			initrd_addr = (phys_addr_t)rd_data;
570			err = lmb_alloc_mem(LMB_MEM_ALLOC_ADDR, 0, &initrd_addr,
571					    rd_len, LMB_NONE);
572			if (err) {
573				puts("in-place initrd alloc failed\n");
574				goto error;
575			}
576		} else {
577			enum lmb_mem_type type = initrd_high ?
578				LMB_MEM_ALLOC_MAX : LMB_MEM_ALLOC_ANY;
579
580			err = lmb_alloc_mem(type, 0x1000, &initrd_high, rd_len,
581					    LMB_NONE);
582			if (err) {
583				puts("ramdisk - allocation error\n");
584				goto error;
585			}
586
587			*initrd_start = (ulong)initrd_high;
588			bootstage_mark(BOOTSTAGE_ID_COPY_RAMDISK);
589
590			*initrd_end = *initrd_start + rd_len;
591			printf("   Loading Ramdisk to %08lx, end %08lx ... ",
592			       *initrd_start, *initrd_end);
593
594			memmove_wd((void *)*initrd_start,
595				   (void *)rd_data, rd_len, CHUNKSZ);
596
597			/*
598			 * Ensure the image is flushed to memory to handle
599			 * AMP boot scenarios in which we might not be
600			 * HW cache coherent
601			 */
602			if (IS_ENABLED(CONFIG_MP)) {
603				flush_cache((unsigned long)*initrd_start,
604					    ALIGN(rd_len, ARCH_DMA_MINALIGN));
605			}
606			puts("OK\n");
607		}
608	} else {
609		*initrd_start = 0;
610		*initrd_end = 0;
611	}
612	debug("   ramdisk load start = 0x%08lx, ramdisk load end = 0x%08lx\n",
613	      *initrd_start, *initrd_end);
614
615	return 0;
616
617error:
618	return -1;
619}
620
621int boot_get_setup(struct bootm_headers *images, u8 arch,
622		   ulong *setup_start, ulong *setup_len)
623{
624	if (!CONFIG_IS_ENABLED(FIT))
625		return -ENOENT;
626
627	return boot_get_setup_fit(images, arch, setup_start, setup_len);
628}
629
630int boot_get_fpga(struct bootm_headers *images)
631{
632	ulong tmp_img_addr, img_data, img_len;

03. fdt_high와 padding을 반영해 working FDT를 만드는 boot_relocate_fdt

boot/image-fdt.c 141-261줄이다.

fileboot/image-fdt.canchor · L158int boot_relocate_fdt(char **of_flat_tree
141
142/**
143 * boot_relocate_fdt - relocate flat device tree
144 * @of_flat_tree: pointer to a char* variable, will hold fdt start address
145 * @of_size: pointer to a ulong variable, will hold fdt length
146 *
147 * boot_relocate_fdt() allocates a region of memory within the bootmap and
148 * relocates the of_flat_tree into that region, even if the fdt is already in
149 * the bootmap.  It also expands the size of the fdt by CONFIG_SYS_FDT_PAD
150 * bytes.
151 *
152 * of_flat_tree and of_size are set to final (after relocation) values
153 *
154 * returns:
155 *      0 - success
156 *      1 - failure
157 */
158int boot_relocate_fdt(char **of_flat_tree, ulong *of_size)
159{
160	u64	start, size, usable, low, mapsize;
161	void	*fdt_blob = *of_flat_tree;
162	void	*of_start = NULL;
163	char	*fdt_high;
164	ulong	of_len = 0;
165	int	bank;
166	int	err;
167	int	disable_relocation = 0;
168	phys_addr_t addr;
169
170	/* nothing to do */
171	if (*of_size == 0)
172		return 0;
173
174	if (fdt_check_header(fdt_blob) != 0) {
175		fdt_error("image is not a fdt");
176		goto error;
177	}
178
179	/* position on a 4K boundary before the alloc_current */
180	/* Pad the FDT by a specified amount */
181	of_len = *of_size + CONFIG_SYS_FDT_PAD;
182
183	/* If fdt_high is set use it to select the relocation address */
184	fdt_high = env_get("fdt_high");
185	if (fdt_high) {
186		ulong high_addr = hextoul(fdt_high, NULL);
187
188		if (high_addr == ~0UL) {
189			/* All ones means use fdt in place */
190			of_start = fdt_blob;
191			addr = map_to_sysmem(fdt_blob);
192			printf("WARNING:\n"
193			       "The 'fdt_high' environment variable is set to ~0. This is known to cause\n"
194			       "boot failures due to placement of DT at non-8-byte-aligned addresses.\n"
195			       "This system will likely fail to boot. Unset the 'fdt_high' environment\n"
196			       "variable and submit a fix upstream.\n");
197
198			err = lmb_alloc_mem(LMB_MEM_ALLOC_ADDR, 0, &addr,
199					    of_len, LMB_NONE);
200			if (err) {
201				printf("Failed to reserve memory for fdt at %#llx\n",
202				       (u64)addr);
203				goto error;
204			}
205
206			disable_relocation = 1;
207		} else {
208			enum lmb_mem_type type = high_addr ?
209				LMB_MEM_ALLOC_MAX : LMB_MEM_ALLOC_ANY;
210
211			addr = high_addr;
212			err = lmb_alloc_mem(type, 0x1000, &addr, of_len,
213					    LMB_NONE);
214			if (err) {
215				puts("Failed to allocate memory for Device Tree relocation\n");
216				goto error;
217			}
218			of_start = map_sysmem(addr, of_len);
219		}
220	} else {
221		mapsize = env_get_bootm_mapsize();
222		low = env_get_bootm_low();
223		of_start = NULL;
224
225		for (bank = 0; bank < CONFIG_NR_DRAM_BANKS; bank++) {
226			start = gd->bd->bi_dram[bank].start;
227			size = gd->bd->bi_dram[bank].size;
228
229			/* DRAM bank addresses are too low, skip it. */
230			if (start + size < low)
231				continue;
232
233			/*
234			 * At least part of this DRAM bank is usable, try
235			 * using the DRAM bank up to 'usable' address limit
236			 * for LMB allocation.
237			 */
238			usable = min(start + size, low + mapsize);
239			addr = usable;
240			err = lmb_alloc_mem(LMB_MEM_ALLOC_MAX, 0x1000,
241					    &addr, of_len, LMB_NONE);
242			if (!err) {
243				of_start = map_sysmem(addr, of_len);
244				/* Allocation succeeded, use this block. */
245				if (of_start)
246					break;
247			}
248
249			/*
250			 * Reduce the mapping size in the next bank
251			 * by the size of attempt in current bank.
252			 */
253			mapsize -= usable - max(start, low);
254			if (!mapsize)
255				break;
256		}
257	}
258
259	if (of_start == NULL) {
260		puts("device tree - allocation error\n");
261		goto error;

04. 최종 initrd 주소를 /chosen에 기록하는 fdt_initrd

boot/fdt_support.c 212-283줄이다.

fileboot/fdt_support.canchor · L221int fdt_initrd(void *fdt
212			printf("WARNING: could not set serial-number %s.\n",
213			       fdt_strerror(err));
214			return err;
215		}
216	}
217
218	return 0;
219}
220
221int fdt_initrd(void *fdt, ulong initrd_start, ulong initrd_end)
222{
223	int   nodeoffset;
224	int   err, j, total;
225	int is_u64;
226	uint64_t addr, size;
227
228	/* just return if the size of initrd is zero */
229	if (initrd_start == initrd_end)
230		return 0;
231
232	/* find or create "/chosen" node. */
233	nodeoffset = fdt_find_or_add_subnode(fdt, 0, "chosen");
234	if (nodeoffset < 0)
235		return nodeoffset;
236
237	total = fdt_num_mem_rsv(fdt);
238
239	/*
240	 * Look for an existing entry and update it.  If we don't find
241	 * the entry, we will j be the next available slot.
242	 */
243	for (j = 0; j < total; j++) {
244		err = fdt_get_mem_rsv(fdt, j, &addr, &size);
245		if (addr == initrd_start) {
246			fdt_del_mem_rsv(fdt, j);
247			break;
248		}
249	}
250
251	err = fdt_add_mem_rsv(fdt, initrd_start, initrd_end - initrd_start);
252	if (err < 0) {
253		printf("fdt_initrd: %s\n", fdt_strerror(err));
254		return err;
255	}
256
257	is_u64 = (fdt_address_cells(fdt, 0) == 2);
258
259	err = fdt_setprop_uxx(fdt, nodeoffset, "linux,initrd-start",
260			      (uint64_t)initrd_start, is_u64);
261
262	if (err < 0) {
263		printf("WARNING: could not set linux,initrd-start %s.\n",
264		       fdt_strerror(err));
265		return err;
266	}
267
268	err = fdt_setprop_uxx(fdt, nodeoffset, "linux,initrd-end",
269			      (uint64_t)initrd_end, is_u64);
270
271	if (err < 0) {
272		printf("WARNING: could not set linux,initrd-end %s.\n",
273		       fdt_strerror(err));
274
275		return err;
276	}
277
278	return 0;
279}
280
281int fdt_kaslrseed(void *fdt, bool overwrite)
282{
283	int len, err, nodeoffset;

내부 동작을 더 깊게 읽기

01

진입 조건을 먼저 고정한다

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

분기 직전에는 bootloader의 편의 기능보다 Linux boot protocol을 우선한다. x0의 FDT 주소, EL, MMU/cache 상태, reserved memory 반영을 체크한다.

02

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

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

빌드 산출물 관점에서는 최종 부트로더 이미지 안에 해당 symbol과 section이 실제로 포함되었는지도 map과 objdump로 검증한다.

03

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

부트 코드의 오류는 논리보다 주소 계산에서 먼저 드러나는 경우가 많다. source range, destination range, header가 말하는 payload size, block 또는 page 단위를 표로 적고 각 구간의 끝 주소를 직접 계산한다. 끝 주소는 start + size - 1인지 exclusive end인지 API 계약을 확인한다.

04

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

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

다른 CPU, interrupt handler, USB completion 또는 shell command가 상태를 관찰할 수 있다면 memory ordering과 lock 범위도 함께 읽는다.

05

마지막 handoff의 계약을 적는다

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

반환하는 경로라면 caller가 오류와 부분 성공을 구분하고 다음 후보 또는 복구 경로를 선택하는지 확인한다.

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

01

booti는 Image 배치와 bootm state machine을 연결한다

ARM64 Image header에서 text offset, image size와 flags를 읽고 현재 주소에서 실행 가능한지, 이동이나 압축 해제가 필요한지 계산한다. source와 destination이 겹칠 때 memmove 방향과 scratch 공간을 확인한다.

kernel, initrd, FDT 세 구간과 U-Boot runtime, reserved memory가 겹치지 않도록 LMB reservation을 대조한다.

02

FDT fixup은 Linux가 보는 hardware 계약을 마지막으로 바꾼다

memory node, chosen bootargs, initrd start/end, reserved-memory와 MAC address가 handoff 직전에 수정될 수 있다. 원본 DTB와 최종 DTB를 dump해 어떤 코드가 값을 바꿨는지 분리한다.

FDT 여유 공간이 부족한 실패를 무시하면 일부 property만 반영된 tree를 넘길 수 있다. 각 fixup return을 확인한다.

03

마지막 분기 전에 CPU와 device 상태를 닫는다

cache clean/invalidate, interrupt disable, secondary CPU와 DMA 정지, watchdog 정책을 architecture handoff 코드에서 확인한다. Linux entry register 계약상 x0는 FDT 주소이고 다른 argument register 조건도 지켜야 한다.

커널 첫 instruction fault는 image 자체뿐 아니라 잘못된 EL, MMU/cache 잔존 상태나 FDT 주소에서 올 수 있으므로 마지막 U-Boot PC와 첫 kernel PC를 연속으로 기록한다.

객체와 수명

대상만들어지는 시점유효 범위확인할 조건
struct bootm_headers / ARM64 Image headerImage headerkernel entry 또는 오류 정리 완료까지진입 전제와 상태 계약
입력 buffer / metadatabooti commandparse와 검증이 끝날 때까지길이, 정렬, 소유권, 변조 가능성
등록된 list / descriptorbootm statessubsystem 종료 또는 image handoff까지이중 등록, dangling pointer, 오류 unwind
hardware 또는 persistent state실제 write/probe가 완료된 뒤reset 또는 명시적 해제·갱신까지flush, timeout, 전원 차단, rollback
최종 부트로더 이미지link/image 생성 시점다음 stage가 새 image로 교체할 때까지load address, entry, section과 header 일치

실패 지점과 증상

#조건관찰되는 증상먼저 볼 단계
01Image magic 불일치명령 거부Image header
02FDT relocation 충돌early boot hangbootm states
03cache clean 누락kernel이 오래된 DT/코드 관찰FDT/initrd setup

로그가 끊긴 마지막 함수만 고치지 않는다. 그 함수가 받은 주소, size, flag가 만들어진 앞 단계까지 올라가고, 오류 뒤 등록 객체와 hardware 상태가 남았는지도 확인한다.

소스 밖에서 확인할 증거

소스 해석은 실제 빌드 산출물과 target 로그로 닫아야 한다. 아래 명령의 보드 이름과 toolchain prefix는 사용 중인 빌드 환경에 맞게 바꾼다.

#목적명령 또는 계측판정 기준
01전처리 결과make <board>_defconfig && make V=1선택된 CONFIG와 실제 compile/link 명령을 보관한다.
02symbol과 section${CROSS_COMPILE}nm -n u-boot | grep 'int do_booti'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
    booti 직전 booti_start/size 로그 추가

    Image header 진입 전후에 ARM64 Image의 주소·크기·반환값과 timestamp를 함께 남긴다.

  2. 02
    FDT chosen과 initrd 주소를 kernel early log와 대조

    bootm states 진입 전후에 bootm_headers의 주소·크기·반환값과 timestamp를 함께 남긴다.

  3. 03
    분기 직전 CurrentEL, SCTLR, x0 기록

    FDT/initrd setup 진입 전후에 working FDT의 주소·크기·반환값과 timestamp를 함께 남긴다.

원문과 다음 글