U-Boot · source analysis

booti에서 ARM64 Linux로 handoff

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

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 인자로 쓰는 규약이 아닙니다.

양쪽 코드를 이어서 읽기

raw Image의 주소가 언제 Linux entry로 확정되는가?

booti는 Image를 검사·배치하고 ramdisk/FDT를 찾은 뒤, 선택된 bootm 상태만 실행한다. ARM64 Linux의 최종 점프는 cmd/booti.c가 아니라 arch/arm/lib/bootm.c의 OS_GO 경로에서 일어난다.

이 페이지는 CONFIG_ARM64와 FDT로 직접 부팅하는 경로를 다룬다. 압축 Image, initrd, relocation, trace용 OS_FAKE_GO는 각각 조건부다. 성공한 실제 점프는 명령행으로 돌아오는 단계가 아니다.

세 payload의 주소와 소유 관계

그림 1. Image·ramdisk·FDT는 같은 LMB 지도를 쓰지만 각기 다른 시점에 확정된다
Image명령 인자 또는 image_load_addr
booti_setup()magic·size·text_offset·flags를 읽어 목적 주소 계산
필요 시 memmoveimages.ep/os.start/end 설정, LMB에 Image 예약
실행 주소images.ep → ARM64 분기
ramdisk두 번째 인자; FDT만 주면 -
bootm_find_images()이미지 검증과 Image 겹침 검사
조건부 RAMDISK stateboot_ramdisk_high()가 copy 또는 in-place 예약
최종 구간initrd_start/end → FDT /chosen
FDT세 번째 인자
bootm_find_images()FDT 유효성·Image 겹침 검사
OS_PREPimage_setup_linux()에서 예약·relocation·fixup
working DTBimages.ft_addr → x0
Image의 images.ep는 C 함수 반환값이 아니라 CPU가 실행할 주소다. LMB는 뒤의 배치가 앞서 예약한 구간을 침범하지 않게 하는 공유 메모리 지도다.

근거: booti.c L77–109, bootm.c L470–520, image-board.c L907–940.

booti에서 ARM64 분기까지

그림 2. booti_start()와 두 번째 bootm_run_states()의 경계
  1. 01 · STARTdo_booti() → booti_start()BOOTM_STATE_START가 images를 초기화한다. Image 주소는 인자 또는 기본값.
  2. 02 · OPTIONAL압축 해제 뒤 booti_setup()압축이면 별도 목적 주소·크기 환경변수가 필요하다. ARM64 Image magic과 header를 검사한다.
  3. 03 · IMAGE + OTHERSImage 이동·예약 → 다른 이미지 탐색images.ep 기록, LMB 예약, bootm_find_images()로 initrd/FDT를 찾고 겹침을 거른다.
  4. 04 · CONDITIONALinterrupt off → RAMDISKbootm_disable_interrupts(). CONFIG_SYS_BOOT_RAMDISK_HIGH이면 boot_ramdisk_high().
  5. 05 · OS_PREPboot_prep_linux() → image_setup_linux()FDT reserved ranges, relocation, /chosen·initrd 속성 등 fixup. OS_FAKE_GO는 trace 빌드에서만.
  6. 06 · OS_GOboot_jump_linux() → EL switch → Imagecleanup과 cache/CPU 전환 뒤 images.ep로 비복귀 점프. x0=최종 DTB, x1–x3=0.
do_booti()의 상태 비트에는 BOOTM_STATE_FDT와 BOOTM_STATE_LOADOS가 없다. Image load는 booti_start()가, 이 ARM64 FDT 준비는 OS_PREP가 담당한다.

근거: booti.c L112–154, bootm.c L982–1116, ARM bootm.c L257–295.

상태 비트와 실제 생산자

시점실행 조건생산/소비 상태오류 또는 결과
STARTbooti_start() 안의 첫 bootm_run_states()images 초기화뒤의 상태 비트와 다른 호출
Image압축이면 먼저 해제; booti_setup(..., false)ep/os.start/os.end와 Image LMB 예약magic·주소·할당 실패 시 시작 중단
다른 payloadbootm_find_images()rd_start/end, ft_addr/leninitrd/FDT 오류·Image 겹침이면 중단
RAMDISKCONFIG_SYS_BOOT_RAMDISK_HIGHinitrd_start/end; copy 또는 in-place 예약할당 실패면 상태 실행 중단
OS_PREPARM64 Linux + FDT/LMB 경로image_setup_linux()가 FDT 이동·fixupFDT 생성 실패는 ARM 코드의 panic()
OS_GO앞 단계 성공최종 DTB를 x0, ep를 실행 PC로실제 ARM64 점프는 정상 반환하지 않음

OS_FAKE_GO는 CONFIG_TRACE 빌드의 계측 경로다. 실제 Linux 진입을 뜻하는 OS_GO와 구분한다.

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

아래 그림은 initrd가 제공된 경우를 예로 들어 주소, 객체 수명과 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_rimage_decomp() 조건부 → booti_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

LMB로 예약한 최종 보존 구간

Linux가 해석할 RAMDT·커널 예약을 별도 적용

U-Boot의 LMB 지도와 같은 객체가 아님

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를 RAM에 load
02압축이면 image_decomp() 뒤 raw Image 확보
03Image 목적 주소를 header로 계산
04필요 시 Image 이동·LMB 예약
05initrd가 있으면 최종 range·copy 결정
06OS_PREP에서 FDT 예약·이동·/chosen 수정
07cache clean·MMU/interrupt 상태 정리
08x0=DTB, PC=kernel entry로 분기
그림 5. 처음 읽은 주소를 그대로 사용하지 않는 이유

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

01

kernel 실행 위치 계약

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

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

flags bit 3, 2 MiB base + text_offset, image_size 확인
02

Image와 다른 payload 충돌 검사

문제가 되는 상태ramdisk 또는 FDT가 Image 목적 구간과 겹침

실패 결과bootm_find_images()가 handoff를 중단

bootm_find_images()의 RD/FDT overlap 검사
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줄은 booti_start()의 마지막 부분부터 시작한다. int do_booti(...)는 L112이고, 이 함수의 선택 상태 비트는 L147–150이다. 부팅 준비의 출발점은 위에 표시되지 않은 booti_start() L23–87도 함께 보아야 한다.

관련 원본 네 상자는 Image 목적 주소, ramdisk 배치, FDT relocation, /chosen의 initrd 기록을 각각 보여 준다. 실제 점프와 CPU 레지스터는 ARM64 boot_jump_linux()에서 확인한다. do_booti()의 일반 반환문을 성공적인 Linux handoff로 해석하지 않는다.

함께 읽어야 하는 원본 코드

첫 코드 조각만으로 동작이 완성되지 않는 경우 호출 매크로, 객체 정의와 실제 실행 목록을 같은 페이지에 묶었다. 각 조각은 같은 기준 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

Image 입력과 압축 분기

booti_start()는 명령 인자 또는 image_load_addr를 읽는다. 압축 형식이 감지되면 kernel_comp_addr_r와 kernel_comp_size가 필요하며, 압축 해제 후 raw Image를 원래 load 주소로 옮긴다. 그 다음에야 booti_setup()이 ARM64 Image magic을 검사한다.

02

Image 목적 주소와 LMB 예약

booti_setup(..., false)는 flags bit 3에 따라 image - text_offset 또는 첫 DRAM bank 시작을 고른 뒤 2 MiB 경계로 올림 정렬하고 text_offset를 더한다. 주소가 다르면 memmove() 후 images.ep/os.start/os.end를 설정한다. lmb_alloc_mem(LMB_MEM_ALLOC_ADDR)가 Image 범위를 예약한다.

03

ramdisk와 FDT는 Image와 별개로 발견된다

bootm_find_images()가 ramdisk와 FDT를 고르고 각각 Image와의 겹침을 검사한다. ramdisk relocation은 선택된 BOOTM_STATE_RAMDISK에서, FDT relocation과 fixup은 ARM64 Linux OS_PREP에서 이뤄진다. 이 booti 상태 목록에는 독립 BOOTM_STATE_FDT가 없다.

04

FDT의 /chosen이 initrd를 전달한다

image_setup_linux()는 FDT reserved 영역을 LMB에 반영하고 boot_relocate_fdt()를 거쳐 image_setup_libfdt()를 호출한다. 이 함수의 fdt_initrd()가 최종 initrd_start/end를 /chosen에 기록한다. Linux가 받는 initrd 주소는 x1·x2가 아니다.

05

OS_GO와 반환 경계

do_bootm_linux(OS_PREP)는 준비 뒤 돌아오지만, 실제 OS_GO는 boot_jump_linux()로 이어진다. cleanup_before_linux(), 보드 설정에 따른 PSCI/EL 전환과 cache 정리 뒤 images.ep로 분기한다. 준비 오류는 반환 또는 panic 분기마다 다르므로 공통 rollback을 가정하지 않는다.

검사와 이동의 실제 순서: booti_start()는 Image를 먼저 memmove()한 뒤 LMB 예약과 ramdisk/FDT 겹침 검사를 한다. 그러므로 뒤의 검사 성공을 입력 staging 영역까지 미리 안전하게 검증한 것으로 해석할 수 없다. 압축 목적지 검사도 시작 주소 범위를 보는 것이며 전체 출력 구간의 안전성 증명은 아니다.

두 번째 상태 호출에는 BOOTM_STATE_MEASURE도 포함된다. CONFIG_MEASURED_BOOT이면 RAMDISK·OS_PREP보다 앞서 측정을 호출하지만, 이 고정 bootm_run_states()는 bootm_measure()의 반환값을 ret에 받지 않는다. 또한 booti_start()는 START 호출의 반환값을 즉시 검사하지 않는다. 상태 비트가 있다는 사실만으로 모든 앞 단계 오류가 전파된다고 단정하지 않는다.

image_size=0인 구형 Image header에는 16 MiB와 text_offset=0x80000 대체값을 쓴다. fdt_high=~0UL의 제자리 FDT는 뒤쪽 padding 공간을 전제하며 정렬 문제 경고도 출력한다. 이 경로를 자동 정렬·복사 보장으로 읽지 않는다. image_setup_libfdt()의 마지막 LMB 재예약 실패는 메시지만 출력하고 0으로 끝나므로, 모든 FDT 관련 오류가 panic으로 이어진다는 뜻도 아니다.

조건부 경로를 읽는 순서

01

relocation은 세 객체에 동일한 규칙이 아니다

Image는 ARM64 header의 flags, text_offset, image_size로 목적 주소를 계산한다. ramdisk는 initrd_high와 LMB 할당으로 copy 또는 in-place를 고른다. FDT는 fdt_high, padding, 유효한 FDT header와 LMB에 따라 working tree를 결정한다.

02

OS_PREP에서 FDT가 최종 수정된다

boot_prep_linux()는 FDT/LMB/길이 조건에서 image_setup_linux()를 호출하고 실패하면 panic한다. image_setup_libfdt()는 /chosen, 보드·시스템 fixup, initrd property 등을 설정한다. 보드별 hook과 CONFIG에 따라 수정 항목은 달라진다.

03

FAKE_GO와 실제 CPU 전환을 분리한다

BOOTM_STATE_OS_FAKE_GO는 CONFIG_TRACE일 때 실제 진입을 흉내 내고 돌아오는 계측 분기다. ARM64 boot_jump_linux()는 실제 GO에서 do_nonsec_virt_switch()와 EL switch를 진행한다. 마지막 x0에는 images.ft_addr, 나머지 argument register에는 0을 넘긴다.

U-Boot의 LMB 예약 목록 전체가 그대로 Linux page allocator의 입력이 되는 것은 아니다. DT의 메모리·예약 정보와 kernel 자체 예약을 따로 해석한다. image_setup_linux()는 images.ft_addr를 갱신하지만 크기 계산에는 지역 변수 of_size를 사용하며 images.ft_len에 최종 크기를 다시 쓰지 않는다. 최종 DTB 크기는 그 header를 확인한다.

Image와 보조 payload의 수명

대상생산자소비자경계 조건
images.ep/os.start/endbooti_start()ARM64 boot_jump_linux()Image LMB 예약과 header 계산 주소 일치
images.rd_start/endboot_get_ramdisk()조건부 RAMDISK state입력 source이며 최종 주소와 다를 수 있음
images.initrd_start/endboot_ramdisk_high()fdt_initrd()최종 구간이 /chosen에 반영됨
images.ft_addr/ft_lenboot_get_fdt() → image_setup_linux()ARM64 entry의 x0relocation·fixup 이후 주소 사용

어느 단계에서 부팅을 멈추는가?

조건고정 소스의 분기먼저 확인할 값
압축 Image 입력 누락booti_start()의 -EINVAL → do_booti() 실패kernel_comp_addr_r, kernel_comp_size
ARM64 Image magic 불일치booti_setup() 실패 → 명령 중단load 주소의 실제 raw Image header
Image LMB 예약 실패booti_start()의 실패 반환목적 주소·size와 기존 LMB 구간
ramdisk/FDT가 Image와 겹침bootm_find_images()가 실패 반환rd_start/end, ft_addr/len
FDT 생성·fixup 실패ARM64 boot_prep_linux()에서 panic()FDT header·padding·LMB·fixup 반환값

interrupt를 끈 뒤의 오류를 일반적인 명령 실패와 같은 복구 상태로 취급하지 않는다. 정상 Linux entry 또한 shell로 돌아오는 결과가 아니다.

보드에서 확인할 증거

동일한 보드 설정과 U-Boot 빌드에서, boot 명령 전후에 주소를 기록한다. 실험용 변경은 별도 보드에서 수행한다.

목적읽기 명령·자료판정
입력 주소printenv kernel_addr_r ramdisk_addr_r fdt_addr_r initrd_high fdt_high kernel_comp_addr_r kernel_comp_size압축·copy·in-place 분기의 실제 입력
메모리 지도bdinfo, 보드 DRAM mapImage 목적지와 U-Boot runtime 및 세 payload의 겹침 여부
빌드 분기grep -E 'CONFIG_(ARM64|SYS_BOOT_RAMDISK_HIGH|OF_LIBFDT|TRACE)=' .config이 글의 ARM64/FDT/선택 경로가 빌드에 포함되는지
symbol 확인${CROSS_COMPILE}nm -an u-boot | grep -E 'do_booti|do_bootm_linux|boot_jump_linux'C 선언문이 아닌 symbol 이름으로 검색; static 함수는 최적화에 따라 안 보일 수 있음
최종 FDTLinux /proc/device-tree/chosen 및 early boot logbootargs·initrd 범위가 넘긴 값과 일치하는지

주소가 바뀌는 지점 계측

  1. 01
    Image 이동 결정 기록

    booti_setup() 직후 ld, relocated_addr, image_size를 기록해 memmove() 조건을 확인한다.

  2. 02
    initrd와 FDT의 최종 주소 대조

    RAMDISK state 뒤 initrd_start/end, OS_PREP 뒤 ft_addr/ft_len를 기록하고 Linux /chosen과 비교한다.

  3. 03
    실제 handoff 위치 확인

    boot_jump_linux()의 real GO에서 images.ep와 images.ft_addr를 확인한다. trace 빌드의 FAKE_GO 반환과 구별한다.

원문과 다음 글