Barebox · source analysis

bootm image handler와 실행 단계

입력 형식을 열어 실제 kernel type을 찾고 OS별 handler에 적재와 실행을 맡기는 bootm 경로를 읽습니다.

Series
17 / 19
Baseline
v2026.06.1
Commit
314c679eea2d
Source
common/bootm.c:796-884 (발췌 범위)

컨테이너를 연 뒤 어떤 커널 handler가 실행되는가?

bootm_boot()은 bootm_boot_prep()로 입력을 준비하고, bootm_boot_handler()로 등록된 handler를 골라 호출한다. FIT·uImage·압축 파일의 바깥 형식과 그 안의 kernel_type을 구별해야 실제 선택 이유를 알 수 있다.

공통 코드는 모든 OS의 적재 순서를 직접 실행하지 않는다. 선택된 handler가 필요한 kernel·initrd·FDT를 배치하고 제어권을 넘긴다. handler가 반환한 경우에는 성공·오류·dry-run에 관계없이 bootm_boot_cleanup()이 실행된다.

입력 데이터와 handler 목록은 서로 다른 수명

그림 1. per-boot 상태와 미리 등록된 callback의 교차점

부팅 시마다 생기는 image_data

  • bootm_data의 파일명·주소·verify·dryrun을 복사
  • 헤더를 읽어 image_type 감지
  • FIT/uImage/압축 형식을 열어 kernel_type과 loadable 준비

이미 등록된 image_handler 목록

  • register_image_handler()가 handler를 전역 목록에 연결
  • 각 check_image()가 준비된 kernel_type을 검사
  • 첫 일치 handler의 bootm(data) 호출

handler 목록은 파일 검출 단계에서 새로 만들어지지 않는다. 기본 비교는 filetype이며, uImage는 OS 헤더의 ih_os도 확인하고 EFI handler는 별도 check_image를 쓸 수 있다.

공통 경로는 준비·선택·호출·반환 후 정리

그림 2. 공통 bootm 호출 순서
01 PREPbootm_boot_prep()os_file 검사 → 헤더 판별 → 형식별 loadable 준비 · 실패 시 내부 cleanup
02 SELECTbootm_boot_handler()kernel_type 정리 → check_image 순회 · 없으면 -ENODEV
03 CALLBACKhandler->bootm(data)OS/아키텍처별 적재·FDT·handoff · dryrun 판단도 handler 책임
04 IF RETURNbootm_boot_cleanup()callback이 돌아왔을 때 resource·loadable·임시 bootargs·파일명 해제

정상적인 비복귀 OS 진입에는 마지막 반환·cleanup 화살표가 실행되지 않는다. callback이 돌아온 경로만 공통 cleanup으로 이어진다.

바깥 형식, 커널 형식, callback을 따로 기록

단계핵심 상태다음 단계가 읽는 것
입력 복사bootm_data → image_dataos_file·선택적 initrd/FDT/TEE·주소 힌트·verify·dryrun
헤더 검출image_type파일 자체의 FIT/uImage/압축/일반 형식; 불명 형식은 force가 없으면 거부
형식별 준비kernel_type 및 loadableFIT 구성의 kernel, uImage 안의 OS, 압축 해제 후 kernel의 실제 형식
handler 선택check_image(data, kernel_type)첫 매치의 bootm callback; 매치 없음은 -ENODEV
callback 반환ret 및 resource반환하면 공통 cleanup 후 ret 전달; 비복귀 handoff는 반환하지 않음

컨테이너 분기와 반환 경계

그림 3. 겉포장과 실제 커널 형식의 차이
FITconfiguration을 열어 loadable 생성kernel·선택적 ramdisk/FDT/TEE를 연결하고 내부 kernel 헤더에서 kernel_type을 갱신한다.
uImageuImage parser 경유내부 OS 정보가 handler 매칭에 쓰인다. 단순한 파일 확장자 선택이 아니다.
COMPRESSED압축 loadable로 감쌈해제한 헤더를 읽어 kernel_type을 다시 감지한다.
OTHER파일 loadable을 엶image_type을 kernel_type 초기값으로 두고 handler 검사에 넘긴다.

prep에서 발견한 컨테이너 열기·검증 오류는 handler 선택 전에 반환한다. 그러나 FIT loadable은 구성 요소를 나중에 열거나 추출할 수도 있으므로, 모든 구성 요소의 접근·검증 오류가 prep에서 끝난다는 뜻은 아니다. 서명 강제 정책은 FIT만 허용하고 별도 initrd/FDT/TEE 파일은 사용하지 않는다.

그림 4. handler가 돌아오느냐가 cleanup 경계
PREP ERRORprep 내부 정리헤더 읽기·정책·형식별 열기 중 실패하면 준비 함수가 정리하고 오류 포인터를 돌려준다.
NO HANDLER공통 정리매치가 없으면 -ENODEV. bootm_boot()은 image_data를 cleanup한 뒤 오류를 전달한다.
HANDLER RETURNS공통 정리callback의 ret를 보존하고 예약 영역·loadable·임시 bootargs 등을 해제한다.
OS HANDOFF비복귀 진입handler가 OS로 제어권을 넘기고 돌아오지 않으면 공통 cleanup은 실행되지 않는다.

dryrun은 공통 handler 함수에서 callback 뒤 메시지를 출력할 뿐이다. 실제 점프 억제와 부작용 범위는 선택된 handler 구현을 확인해야 한다.

원본 코드

아래 코드는 Barebox v2026.06.1의 common/bootm.c에서 796-884줄을 그대로 가져온 것이다.

commit314c679eea2d0ca847c64d1b646a1cf91225c0ecanchor · L820int bootm_boot(const struct bootm_data *bootm_data)
796	if (data->initrd_res)
797		of_del_reserve_entry(data->initrd_res->start, data->initrd_res->end);
798	release_sdram_region(data->initrd_res);
799	release_sdram_region(data->oftree_res);
800	release_sdram_region(data->tee_res);
801	loadable_release(&data->oftree);
802	loadable_release(&data->initrd);
803	loadable_release(&data->os);
804	loadable_release(&data->tee);
805	if (data->of_root_node)
806		of_delete_node(data->of_root_node);
807
808	globalvar_remove(LINUX_BOOTARGS_BOOTM_LATE  "*");
809	free(data->os_header);
810	free(data->os_file);
811	free(data->oftree_file);
812	free(data->initrd_file);
813	free(data->tee_file);
814	free(data);
815}
816
817/*
818 * bootm_boot - Boot an application image described by bootm_data
819 */
820int bootm_boot(const struct bootm_data *bootm_data)
821{
822	struct image_data *data;
823	int ret;
824
825	data = bootm_boot_prep(bootm_data);
826	if (IS_ERR(data))
827		return PTR_ERR(data);
828
829	ret = bootm_boot_handler(data);
830
831	bootm_boot_cleanup(data);
832	return ret;
833}
834
835bool bootm_efi_check_image(struct image_handler *handler,
836			   struct image_data *data,
837			   enum filetype detected_filetype)
838{
839	/* This is our default: Use EFI when support is compiled in,
840	 * and fallback to normal boot otherwise.
841	 */
842	if (data->efi_boot == BOOTM_EFI_AVAILABLE) {
843		if (IS_ENABLED(CONFIG_EFI_LOADER) || efi_is_payload())
844			data->efi_boot = BOOTM_EFI_REQUIRED;
845		else
846			data->efi_boot = BOOTM_EFI_DISABLED;
847	}
848
849	/* If EFI is disabled, we assume EFI-stubbed images are
850	 * just normal non-EFI stubbed ones
851	 */
852	if (data->efi_boot == BOOTM_EFI_DISABLED)
853		return handler->filetype == filetype_no_efistub(detected_filetype);
854
855	/* If EFI is required, we enforce handlers to match exactly */
856	return detected_filetype == handler->filetype;
857}
858
859int linux_rootwait_secs = 10;
860
861static const char * const bootm_efi_loader_mode_names[] = {
862	[BOOTM_EFI_DISABLED] = "disabled",
863	[BOOTM_EFI_AVAILABLE] = "available",
864	[BOOTM_EFI_REQUIRED] = "required",
865};
866
867static int bootm_init(void)
868{
869	globalvar_add_simple("bootm.image", NULL);
870	globalvar_add_simple("bootm.image.loadaddr", NULL);
871	globalvar_add_simple("bootm.oftree", NULL);
872	globalvar_add_simple("bootm.root_dev", NULL);
873	globalvar_add_simple("bootm.root_param", "root");
874	globalvar_add_simple("bootm.tee", NULL);
875	globalvar_add_simple_bool("bootm.appendroot", &bootm_appendroot);
876	globalvar_add_simple_bool("bootm.earlycon", &bootm_earlycon);
877	globalvar_add_simple_bool("bootm.provide_machine_id", &bootm_provide_machine_id);
878	globalvar_add_simple_bool("bootm.provide_hostname", &bootm_provide_hostname);
879	if (IS_ENABLED(CONFIG_SECURITY_POLICY))
880		globalvar_add_simple_bool("bootm.provide_policy", &bootm_provide_policy);
881	if (IS_ENABLED(CONFIG_BOOTM_INITRD)) {
882		globalvar_add_simple("bootm.initrd", NULL);
883		globalvar_add_simple("bootm.initrd.loadaddr", NULL);
884	}

발췌 범위와 읽기 기준

첫 코드 발췌는 bootm_boot()의 prep → handler → cleanup 연결, 앞의 정리 함수 일부, 뒤의 EFI match helper를 포함한다. 이 발췌만 보고 kernel·initrd·FDT의 적재 순서를 공통 코드의 고정 순서로 읽지 않는다.

보충 발췌에는 bootm_boot_prep() 앞부분만 있다. 뒤쪽 bootargs 추가와 handler lookup, loadable 적재 경계는 같은 태그의 common/bootm.c, FIT 내부 선택은 common/bootm-fit.c를 함께 확인한다.

loadable_from_fit()는 FIT 참조와 이미지 이름을 저장하는 객체를 만들며, 실제 구성 요소 읽기는 fit_loadable_get_info(), fit_loadable_mmap(), fit_loadable_extract_into_buf()의 fit_open_image() 호출에서도 발생한다. prep 성공을 모든 kernel·initrd·FDT·TEE의 최종 적재 성공으로 취급하지 않는다.

함께 읽어야 하는 원본 코드

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

01. image file을 열고 handler 실행 전 상태를 준비

common/bootm.c 521-635줄이다.

filecommon/bootm.canchor · L531struct image_data *bootm_boot_prep
521	/* Detect actual image type from decompressed content */
522	data->kernel_type = file_detect_boot_image_type(header, ret);
523
524	/* Replace the os_header with the decompressed header */
525	free(data->os_header);
526	data->os_header = header;
527
528	return 0;
529}
530
531struct image_data *bootm_boot_prep(const struct bootm_data *bootm_data)
532{
533	struct image_data *data;
534	int ret;
535	const char *image_type_str;
536
537	if (!bootm_data->os_file) {
538		pr_err("no image given\n");
539		return ERR_PTR(-ENOENT);
540	}
541
542	data = xzalloc(sizeof(*data));
543
544	bootm_image_name_and_part(bootm_data->os_file, &data->os_file, &data->os_part);
545	bootm_image_name_and_part(bootm_data->oftree_file, &data->oftree_file, &data->oftree_part);
546	bootm_image_name_and_part(bootm_data->initrd_file, &data->initrd_file, &data->initrd_part);
547	if (bootm_data->tee_file)
548		data->tee_file = xstrdup(bootm_data->tee_file);
549	data->verbose = bootm_data->verbose;
550	data->verify = bootm_data->verify;
551	data->force = bootm_data->force;
552	data->dryrun = bootm_data->dryrun;
553	data->initrd_address = bootm_data->initrd_address;
554	data->os_address = data->os_address_hint = bootm_data->os_address;
555	data->os_entry = data->os_entry_hint = bootm_data->os_entry;
556	data->efi_boot = bootm_data->efi_boot;
557
558	ret = file_read_and_detect_boot_image_type(data->os_file, &data->os_header);
559	if (ret < 0)
560		goto err_out;
561	data->image_type = ret;
562
563	if (!data->force && data->image_type == filetype_unknown) {
564		pr_err("Unknown OS filetype (try -f)\n");
565		ret = -EINVAL;
566		goto err_out;
567	}
568
569	if (bootm_signed_images_are_forced()) {
570		data->verify = BOOTM_VERIFY_SIGNATURE;
571
572		/*
573		 * When we only allow booting signed images make sure everything
574		 * we boot is in the OS image and not given separately.
575		 */
576		data->oftree_file = NULL;
577		data->initrd_file = NULL;
578		data->tee_file = NULL;
579		if (data->image_type != filetype_fit) {
580			pr_err("Signed boot and image is no FIT image, aborting\n");
581			ret = -EINVAL;
582			goto err_out;
583		}
584	}
585
586	image_type_str = file_type_to_short_string(data->image_type);
587
588	/* May be updated by below container-specific handlers */
589	data->kernel_type = data->image_type;
590
591	switch (data->image_type) {
592	case filetype_fit:
593		ret = bootm_open_fit(data, false);
594		break;
595	case filetype_uimage:
596		ret = bootm_open_uimage(data);
597		break;
598	case filetype_gzip:
599	case filetype_bzip2:
600	case filetype_lzo_compressed:
601	case filetype_lz4_compressed:
602	case filetype_xz_compressed:
603	case filetype_zstd_compressed:
604		ret = bootm_open_files(data);
605		if (!ret)
606			ret = bootm_open_os_compressed(data);
607		image_type_str = "compressed boot";
608		break;
609	default:
610		ret = bootm_open_files(data);
611		image_type_str = "boot";
612		break;
613	}
614
615	if (ret) {
616		pr_err("Loading %s image failed with: %pe\n", image_type_str, ERR_PTR(ret));
617		goto err_out;
618	}
619
620	if (IS_ENABLED(CONFIG_BOOTM_UIMAGE)) {
621		ret = bootm_collect_uimage_loadables(data);
622		if (ret)
623			goto err_out;
624	}
625
626	if (bootm_data->appendroot) {
627		const char *root = NULL;
628		const char *rootopts = NULL;
629
630		if (bootm_data->root_dev) {
631			const char *root_dev_name = devpath_to_name(bootm_data->root_dev);
632			struct cdev *root_cdev = cdev_open_by_name(root_dev_name, O_RDONLY);
633
634			ret = cdev_get_linux_root_and_opts(root_cdev, &root, &rootopts);
635

세 함수가 각각 보장하는 것

01

prep: 탐지와 정책

os_file이 없으면 -ENOENT. 헤더 검출 실패나 force 없는 unknown 형식은 handler 전 단계에서 끝난다. 서명 강제 정책은 verify를 signature로 고정하고 FIT만 허용한다.

02

prep: loadable 생성

FIT, uImage, 압축 파일과 그 밖의 파일이 서로 다른 open 경로를 지난다. kernel_type이 image_type과 달라질 수 있으므로 둘을 로그에서 분리한다.

03

handler: 선택과 위임

os_address·os_entry의 sentinel을 정리하고 check_image를 순회한다. 매치가 없으면 -ENODEV, 있으면 해당 handler의 bootm callback을 호출한다.

04

cleanup: 반환 뒤 자원 해제

callback이 반환하면 os/initrd/oftree/tee SDRAM resource와 loadable, DT 복제본, 일시 bootargs 변수 및 복사한 파일명을 정리한다.

공통 코드와 OS별 코드를 혼동하지 않는 법

01

load는 handler의 필요에 따라

공통 bootm_boot()은 모든 이미지의 목적 주소를 차례대로 예약하지 않는다. bootm_load_os(), bootm_load_initrd(), bootm_load_devicetree()를 해당 handler가 호출할 때 실제 적재와 resource 확보가 일어난다.

02

FDT는 선택적이며 fixup을 거침

bootm_get_devicetree()는 지정된 loadable 또는 내부 DT를 복제하고 initrd 범위를 반영한 뒤 fixup·flatten한다. 그 FDT를 SDRAM에 놓을지도 handler 호출 경로에 달려 있다.

03

dryrun은 공통 함수의 무부작용 보증이 아님

data->dryrun을 callback에 전달하고 돌아온 뒤 Dryrun 메시지를 출력한다. 공통 함수 자체가 모든 handler의 점프나 장치 변경을 막는다고 해석하지 않는다.

부팅 시 생기는 객체와 정리 소유자

대상생성 / 소비반환 시 정리
bootm_data명령/호출자가 전달하는 설정bootm_boot_cleanup()이 이 호출자 객체를 free하지 않음
image_dataprep이 할당하고 handler에 전달prep 오류 또는 handler 반환 뒤 bootm_boot_cleanup()
image_handler부팅 전에 전역 목록에 등록된 callback descriptorper-boot cleanup 대상이 아님
loadable / SDRAM resource형식별 prep와 handler helper에서 조건부 생성반환 경로에서 loadable_release와 release_sdram_region
임시 bootargs / DTprep과 handler가 조건부 생성반환 경로에서 일시 변수 제거·복제 DT 삭제

어느 단계에서 끊겼는지 먼저 구별

증상 / 조건위치고정 소스의 경계
OS 파일이 없음prep 입구-ENOENT; image_data 생성 전 반환
헤더 읽기·형식 실패prep오류 반환 또는 force 없는 unknown이면 -EINVAL; prep 내부 cleanup
강제 서명 정책에 맞지 않음prepFIT가 아니면 -EINVAL; 외부 initrd/FDT/TEE 경로 배제
일치하는 handler가 없음handler 선택-ENODEV; callback 호출 없이 bootm_boot() cleanup
주소·메모리·FDT 실패선택된 callback/helpercallback 반환값 확인; 돌아오면 공통 cleanup

로그의 Loading 문구는 OS로 제어권을 넘겼다는 뜻이 아니다. 선택된 handler가 어디까지 진행했는지는 callback 반환값과 뒤따르는 적재·FDT 로그를 대조한다.

코드와 보드에서 확인할 증거

목적관찰판정
빌드 포함 여부${CROSS_COMPILE}nm -n barebox | grep -E " (bootm_boot|bootm_boot_prep|bootm_boot_handler)$"심벌 이름으로 찾는다. 최적화·설정에 따라 부재할 수 있다.
handler 선택bootm -v <image>와 image type·handler 로그바깥 image_type과 실제 kernel_type, 선택 callback을 분리해 기록
예약 영역iomem을 handler 반환 전후에 관찰반환 경로에서 OS·initrd·FDT resource의 잔류 여부 비교
dry-runbootm -d -v <image> 및 대상 handler 추적OS 점프가 억제되는 지점과 상태 변경 범위를 handler에서 확인

같은 이미지로 분기를 재현

  1. 01
    형식과 handler를 함께 기록

    FIT·uImage·압축 커널 각각에서 prep의 image_type/kernel_type과 선택된 handler 이름을 기록한다.

  2. 02
    매치 실패 지점 고정

    지원하지 않는 커널 형식을 넣고 -ENODEV, handler callback 미호출, cleanup 뒤 iomem 상태를 확인한다.

  3. 03
    dry-run의 실제 경계 확인

    같은 handler에 일반 실행과 -d를 각각 적용하고 점프 직전 분기·반환값·예약 영역 정리를 비교한다.

원문과 다음 글