Barebox · source analysis

start_barebox와 초기 runtime

initcall 배열을 순회한 뒤 RUNNING 상태와 조건부 run_init·shell 경로로 넘어가는 순서를 읽습니다.

이 글은 Barebox v2026.06.1 소스의 제어 흐름을 분석합니다. 사용 보드의 Kconfig와 linker map에 따라 실제 포함된 callback은 달라집니다.

Series
03 / 19
Baseline
v2026.06.1
Commit
314c679eea2d
Source
common/startup.c:424-511 (발췌 범위)

start_barebox()는 언제 무엇을 실행하는가?

v2026.06.1의 start_barebox()는 이미 준비된 실행 환경에서 linker가 모은 initcall 함수 포인터를 순회한다. 순회를 마친 다음에야 barebox_system_state를 BAREBOX_RUNNING으로 바꾸고, 조건부 selftest와 barebox_main을 실행한다.

barebox_main이 기본 설정의 run_init()을 가리키는 조건과, CONFIG_SHELL_NONE에서 전원 종료로 가는 조건을 구분한다. 이 함수가 BSS·heap·DT root를 직접 만들거나 run_init()이 initcall을 실행한다고 읽으면 순서가 뒤집힌다.

근거: common/startup.c:444–479 · include/init.h의 level 정의

linker 배열, 실행 상태, main 함수 포인터

그림 1. 서로 다른 세 상태의 소유자
linker의 initcall 배열__barebox_initcalls_start부터 __barebox_initcalls_end까지 함수 포인터가 level 순서로 놓인다.
start_barebox()배열을 호출하며 각 반환값을 기록한다. 전체 순회 뒤 BAREBOX_RUNNING을 설정한다.
barebox_main설정에 따라 기본 run_init 또는 NULL이다. 스크립트·autoboot·shell 정책은 여기서 이어진다.

배열은 빌드 시 linker가 보존한 정적 포인터다. 런타임의 root device나 heap arena 자체가 아니다.

initcall 전체 순회 뒤 run_init()

그림 2. common/startup.c의 제어 흐름
  1. 1
    start_barebox() 진입선행 진입점이 넘겨준 환경에서 initcall 범위의 첫 포인터를 잡는다. 이 함수의 첫 동작은 별도 memory registration이 아니다.
  2. 2
    포인터마다 호출·오류 기록(*initcall)()이 0이 아니면 pr_err를 남기고 다음 포인터로 진행한다. 모든 callback에 공통 rollback은 없다.
  3. 3
    순회 완료 → RUNNINGbarebox_system_state = BAREBOX_RUNNING, 설정 시 selftest 실행.
  4. 4
    조건부 barebox_main()기본 포인터가 run_init이면 환경 스크립트·autoboot·shell 경로로 들어간다. NULL이면 생략한다.
  5. 5
    복귀 후 fallbackCONFIG_SHELL_NONE이면 poweroff, 아니면 while (1) run_shell(). 실제 boot 명령은 run_init() 안의 선택 분기다.

실행 전후에 관찰할 상태

이 표의 순서는 start_barebox() 본문 순서이며 보드별 초기 진입·메모리 준비 과정을 섞지 않았다.

지점읽는 것바꾸는 것다음 분기
initcall 반복linker 함수 포인터 배열각 callback 자체의 상태; 비0 반환은 오류 로그오류 여부와 무관하게 다음 포인터
반복 직후initcall 범위 끝BAREBOX_RUNNING조건부 selftest
main 선택barebox_main 포인터기본 run_init() 실행 시 PATH·스크립트·autoboot 정책포인터 NULL이면 건너뜀
main 반환CONFIG_SHELL_NONEpoweroff 또는 지속 shell 호출별도 반환값 검사 없음

초기화 완료와 사용자 명령 진입의 경계

그림 3. level 순회가 끝나야 run_init() 후보에 도달한다
initcall section 0…16linker 순서대로 callback 실행
BAREBOX_RUNNING순회 완료 뒤 한 번 설정
selftest → barebox_main각각 설정·포인터 조건부

console·memory·DT 관련 초기화가 이 배열의 어느 level에 실렸는지는 각 callback 등록을 보아야 한다. 함수 본문에 고정된 단계로 그려 넣지 않는다.

그림 4. run_init()의 boot/shell 분기와 반환 뒤 fallback

run_init()가 실행될 때

  1. PATH=/env/bin 설정
  2. legacy /env/bin/init이 있으면 source 후 조기 반환
  3. 그 밖에는 abort 검사, /env/init/* 및 cmdline/bmode 처리
  4. countdown이 AUTOBOOT_BOOT면 boot 명령; menu면 menu 루프, 아니면 shell

start_barebox()로 돌아오면

  1. barebox_main이 NULL이어도 같은 지점에 도달
  2. CONFIG_SHELL_NONE: critical 로그 후 poweroff
  3. 그 외: 무한 run_shell() 호출

legacy init과 abort는 run_init() 내부 조기 반환 경로다. initcall 순회를 되돌리거나 재실행하지 않는다.

원본 코드

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

commit314c679eea2d0ca847c64d1b646a1cf91225c0ecanchor · L448void __noreturn start_barebox(void)
424
425	if (current_autoboot != AUTOBOOT_MENU) {
426		if (current_autoboot == AUTOBOOT_ABORT &&
427		    current_autoboot == global_autoboot_state)
428			watchdog_inhibit_all();
429
430		run_shell();
431	}
432
433	do {
434		/*
435		 * Let's run the command once at least, so an error
436		 * message is printed if the file doesn't exist
437		 */
438		run_command(MENUFILE);
439	} while (stat(MENUFILE, &s) == 0);
440
441	hang();
442}
443
444int (*barebox_main)(void)
445	= !IS_ENABLED(CONFIG_SHELL_NONE) &&
446           IS_ENABLED(CONFIG_COMMAND_SUPPORT) ? run_init : NULL;
447
448void __noreturn start_barebox(void)
449{
450	initcall_t *initcall;
451	int result;
452
453	for (initcall = __barebox_initcalls_start;
454			initcall < __barebox_initcalls_end; initcall++) {
455		pr_debug("initcall-> %pS\n", *initcall);
456		result = (*initcall)();
457		if (result)
458			pr_err("initcall %pS failed: %pe\n", *initcall,
459					ERR_PTR(result));
460	}
461
462	barebox_system_state = BAREBOX_RUNNING;
463	pr_debug("initcalls done\n");
464
465
466	if (IS_ENABLED(CONFIG_SELFTEST_AUTORUN))
467		selftests_run();
468
469	if (barebox_main)
470		barebox_main();
471
472	if (IS_ENABLED(CONFIG_SHELL_NONE)) {
473		pr_crit("Nothing left to do\n");
474		poweroff_machine(0);
475	} else {
476		while (1)
477			run_shell();
478	}
479}
480
481void __noreturn hang (void)
482{
483	puts ("### ERROR ### Please RESET the board ###\n");
484	for (;;);
485}
486
487/* Everything needed to cleanly shutdown barebox.
488 * Should be called before starting an OS to get
489 * the devices into a clean state
490 */
491void shutdown_barebox(void)
492{
493	exitcall_t *exitcall;
494
495	barebox_system_state = BAREBOX_EXITING;
496
497	for (exitcall = __barebox_exitcalls_start;
498			exitcall < __barebox_exitcalls_end; exitcall++) {
499		pr_debug("exitcall-> %pS\n", *exitcall);
500		(*exitcall)();
501	}
502
503	console_flush();
504}
505
506BAREBOX_MAGICVAR(global.autoboot,
507                 "Autoboot state. Possible values: countdown (default), abort, halt, menu, boot");
508BAREBOX_MAGICVAR(global.autoboot_abort_key,
509                 "Which key allows to interrupt autoboot. Possible values: 'any', 'ctrl-c' or any other single ascii character.");
510BAREBOX_MAGICVAR(global.autoboot_timeout,
511                 "Timeout before autoboot starts in seconds");

발췌 범위와 읽기 기준

원문 424–511줄은 run_init()의 끝, barebox_main, start_barebox(), shutdown의 시작까지 포함한다. 기준 함수는 L448에 시작한다.

L453–460의 initcall 반복, L462의 RUNNING 전환, L469–477의 main/fallback을 순서대로 읽는다. run_init()의 앞부분은 아래 관련 원본에 있으며 이 반복보다 뒤에 호출된다.

run_init()의 일반 경로는 단순히 shell 또는 menu를 선택하고 반환하지 않는다. menu 모드가 아니면 먼저 run_shell()을 호출하고, 이것이 돌아오면 menu 파일을 최소 한 번 실행한 뒤 파일이 있는 동안 반복하고 마지막에 hang()에 도달한다(L425–441). 호출자 fallback에 도달하는 legacy init·abort·cmdline 쓰기 오류의 조기 반환과 구분한다.

함께 읽어야 하는 원본 코드

관련 함수의 호출 순서를 확인할 수 있도록 같은 기준 commit의 원본 발췌를 함께 놓았다.

01. 환경 스크립트·autoboot·shell을 처리하는 run_init

common/startup.c 327-429줄이다.

filecommon/startup.canchor · L337static int run_init(void)
327/**
328 * get_autoboot_state - get the autoboot state
329 *
330 * This functions returns the autoboot state last used.
331 */
332enum autoboot_state get_autoboot_state(void)
333{
334	return current_autoboot;
335}
336
337static int run_init(void)
338{
339	const char *bmode, *cmdline;
340	bool env_bin_init_exists;
341	struct stat s;
342	glob_t g;
343	int i, ret;
344	size_t size;
345	void *ext_dtb;
346
347	setenv("PATH", "/env/bin");
348	export("PATH");
349
350	/* Run legacy /env/bin/init if it exists */
351	env_bin_init_exists = stat(INITFILE, &s) == 0;
352	if (env_bin_init_exists) {
353		pr_info("running legacy %s...\n", INITFILE);
354		run_command("source " INITFILE);
355		return 0;
356	}
357
358	/* Unblank console cursor */
359	printf("\e[?25h");
360
361	if (test_abort()) {
362		pr_info("Init sequence aborted\n");
363		return -EINTR;
364	}
365
366	/* Run scripts in /env/init/ */
367	ret = glob("/env/init/*", 0, NULL, &g);
368	if (!ret) {
369		for (i = 0; i < g.gl_pathc; i++) {
370			const char *path = g.gl_pathv[i];
371
372			ret = stat(path, &s);
373			if (ret)
374				continue;
375
376			if (!S_ISREG(s.st_mode))
377				continue;
378
379			pr_debug("Executing '%s'...\n", path);
380			run_command("source %s", path);
381		}
382
383		globfree(&g);
384	}
385
386	cmdline = barebox_cmdline_get();
387	if (cmdline) {
388		ret = write_file("/cmdline", cmdline, strlen(cmdline));
389		if (ret)
390			return ret;
391
392		console_ctrlc_allow();
393		run_command("source /cmdline");
394	}
395
396	ext_dtb = handoff_data_get_entry(HANDOFF_DATA_EXTERNAL_DT, &size);
397	if (ext_dtb)
398		write_file("/external-devicetree", ext_dtb, size);
399
400	/* source matching script in /env/bmode/ */
401	bmode = reboot_mode_get();
402	if (bmode) {
403		char *scr, *path;
404
405		scr = xasprintf("source /env/bmode/%s", bmode);
406		path = &scr[strlen("source ")];
407		if (stat(path, &s) == 0) {
408			pr_info("Invoking '%s'...\n", path);
409			run_command("%s", scr);
410		}
411		free(scr);
412	}
413
414	current_autoboot = do_autoboot_countdown();
415
416	console_ctrlc_allow();
417
418	if (current_autoboot == AUTOBOOT_BOOT)
419		run_command("boot");
420
421	if (IS_ENABLED(CONFIG_NET) && !IS_ENABLED(CONFIG_CONSOLE_DISABLE_INPUT) &&
422	    current_autoboot != AUTOBOOT_HALT)
423		eth_open_all();
424
425	if (current_autoboot != AUTOBOOT_MENU) {
426		if (current_autoboot == AUTOBOOT_ABORT &&
427		    current_autoboot == global_autoboot_state)
428			watchdog_inhibit_all();
429

함수 경계에서 실제로 하는 일

01

진입 범위를 좁힌다

start_barebox() 자체는 architecture별 entry, relocation, BSS 초기화나 allocator 배치를 설명하지 않는다. 이 글의 보장 범위는 common/startup.c L448 이후이며, 선행 조건은 사용 중인 보드의 진입 코드를 별도 확인한다.

02

initcall 오류는 기록하고 계속한다

각 callback의 result가 비0이면 함수 포인터와 errno를 출력하지만 반복을 중단하지 않는다. 일부 서비스가 실패한 채 다음 callback 또는 shell에 도달할 수 있다. 공통 등록 취소·자원 rollback은 이 함수에 없다.

03

RUNNING은 모든 성공을 뜻하지 않는다

BAREBOX_RUNNING은 전체 포인터 범위를 지났다는 제어 상태다. 앞서 실패한 callback의 자원이 유효하다는 보장은 아니다. 실패한 provider와 그것을 사용하는 후속 consumer를 로그로 대조한다.

04

main 포인터와 구성 조건을 구분한다

기본 barebox_main은 command support가 있고 shell-none이 아닐 때 run_init이다. run_init()은 initcall executor가 아니라 사용자 환경·autoboot·shell 정책을 담당한다. 보드가 포인터를 바꿨다면 실제 대상도 확인한다.

05

마지막 경로를 소스대로 읽는다

main이 돌아온 뒤 CONFIG_SHELL_NONE이면 poweroff, 그 외에는 shell 재호출 루프다. OS로의 handoff는 이 함수 끝에서 항상 일어나는 단계가 아니라 run_init()의 선택적 boot 명령 등 별도 경로다.

소스 대조에서 중요한 세 지점

01

주소 범위는 linker가 만든다

start_barebox()는 __barebox_initcalls_start에서 end 직전까지 함수 포인터를 증가시키며 호출한다. level 경계는 이 반복 안의 별도 switch가 아니라 include/asm-generic/barebox.lds.h의 KEEP(*(.initcall.N)) 배치다.

02

문서의 memory·DT·console 순서는 callback별로 확인한다

include/init.h는 각 등록 macro의 숫자 level을 정한다. 해당 보드에서 어떤 callback이 실제 들어왔는지 map·debug 로그와 대조한다. 이 파일 하나로 root device나 heap 생성 시점을 단정할 수 없다.

03

사용자 init의 조기 종료가 반복 루프를 바꾸지 않는다

legacy init script가 있거나 abort가 선택되면 run_init()이 일찍 돌아올 수 있다. 호출자는 반환값을 검사하지 않고 최종 poweroff 또는 shell 루프로 간다.

이 함수가 실제로 읽고 쓰는 객체

대상출처소비·변경주의
initcall pointer 범위linker의 정적 sectionL453–460에서 순차 호출callback 오류도 다음 pointer로 진행
barebox_system_state전역 상태L462에서 RUNNING 설정개별 subsystem 성공 표시는 아님
barebox_main설정별 함수 포인터L469에서 조건부 호출기본은 run_init 또는 NULL
current_autobootrun_init()의 countdownboot/menu/shell 분기조건부 main이 실행될 때만 갱신

실패가 어디까지 전파되는가?

조건소스의 처리관찰·후속 점검
initcall 비0 반환pr_err 후 다음 callback실패 callback과 후속 consumer를 함께 확인
barebox_main == NULL호출 생략shell-none 구성과 최종 분기 확인
run_init() 조기 반환호출자가 반환값을 검사하지 않음legacy init, abort, /cmdline 쓰기 실패를 구분
main 복귀poweroff 또는 shell 반복boot 성공 시 복귀하지 않는 별도 명령 경로와 혼동하지 않기

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

사용한 보드·Kconfig·toolchain을 고정하고, 실행 전에 읽기 전용으로 확인한다.

목적확인 방법판정 기준
함수 포함${CROSS_COMPILE}nm -n barebox | grep ' start_barebox$'심벌 이름을 검색한다. C 선언문은 nm 출력에 없음.
initcall 범위${CROSS_COMPILE}nm -n barebox | grep '__barebox_initcalls_'와 linker mapstart/end 및 .initcall.0…16의 배치를 대조
runtime 오류CONFIG_DEBUG_INITCALLS와 serial loginitcall-> 및 실패 로그 뒤 다음 callback이 진행하는지 확인
main 분기Kconfig와 barebox_main 포인터의 실제 값command support·shell-none 조건과 예상 main 일치

순서를 확인하는 작은 실험

  1. 01
    initcall 마지막과 RUNNING 전환을 계측

    함수 포인터 index, 반환값, barebox_system_state를 함께 기록해 비0 반환 뒤에도 반복이 계속되는지 확인한다.

  2. 02
    main 포인터와 진입을 계측

    barebox_main 값과 run_init()의 첫 로그를 비교해 initcall 순회 완료 이후에만 사용자 init이 시작하는지 확인한다.

  3. 03
    조기 반환 후 fallback 관찰

    테스트 보드에서 legacy init 또는 abort 경로를 선택하고 run_init() 복귀 뒤 shell/poweroff 분기를 확인한다.

원문과 다음 글