Barebox · source analysis

initcall level과 run_init

linker section의 전체 initcall level을 start_barebox가 실행한 뒤 run_init이 시작되는 경계를 읽습니다.

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

Series
04 / 19
Baseline
v2026.06.1
Commit
314c679eea2d
Source
common/startup.c:313-401 (발췌 범위)

initcall level은 누가 실행하고 run_init()은 언제 시작하는가?

v2026.06.1의 pure_initcall부터 postenvironment_initcall까지는 linker section .initcall.0…16에 함수 포인터를 둔다. start_barebox()가 그 연속 범위를 순회한다. run_init()은 이 순회를 끝낸 뒤 조건부로 호출되는 사용자 환경·autoboot 함수다.

level 안의 callback 순서는 이 글에서 독립적인 의존성 계약으로 취급하지 않는다. 실패한 callback은 로그를 남기고 다음 callback을 실행하며, 모든 level이 끝난 뒤에도 실패가 자동으로 전체 부팅을 차단하지 않는다.

근거: init.h:54–71 · barebox.lds.h:17–40 · startup.c:448–479

등록 macro에서 실행 포인터까지

그림 1. compile/link/runtime의 세 경계
등록: *_initcall(fn)include/init.h가 정적 함수 포인터를 숫자 .initcall.N section에 배치한다.
linker: KEEPBAREBOX_INITCALLS가 .initcall.0에서 .initcall.16까지 고정 순서로 연결한다.
실행: start_barebox()start/end 사이 포인터를 하나씩 호출한다. run_init()은 배열에 속한 level 이름이 아니다.

section에 들어간 포인터의 수는 구성과 link 결과에 따른다. level 이름은 함수의 실제 성공이나 등록된 장치 수를 뜻하지 않는다.

level 0–16을 끝낸 뒤 사용자 init

그림 2. linker의 정렬과 start_barebox()의 반복
  1. 1
    link 단계KEEP(*(.initcall.0)) … KEEP(*(.initcall.16))이 하나의 포인터 범위를 만든다.
  2. 2
    runtime: initcall 반복start_barebox()가 범위 끝까지 각 포인터를 호출한다. callback 비0 반환 시 오류를 기록하고 계속한다.
  3. 3
    순회 완료BAREBOX_RUNNING 설정 → 설정 시 selftest 실행.
  4. 4
    조건부 mainbarebox_main이 있으면 호출한다. 기본 구성에서는 run_init()이 PATH·환경 script·autoboot를 처리한다.
  5. 5
    main 복귀shell-none이면 poweroff, 아니면 지속 shell 루프다.

level과 script 초기화는 서로 다른 단계

단계입력동작오류·다음 단계
등록·link__define_initcall(fn,id).initcall.N 포인터를 0–16 순서로 보존실제 포함 여부는 map에서 확인
initcall 실행start/end pointer range각 callback 호출비0이면 로그, 그래도 다음 포인터
순회 종료end 도달BAREBOX_RUNNING, 조건부 selftest실패 callback의 복구를 의미하지 않음
사용자 init조건부 barebox_mainrun_init()의 script/boot/menu/shellNULL 또는 조기 반환이면 최종 fallback

숫자 section 순서와 오류의 진행 방향

그림 3. include/init.h의 전체 level 0–16
0pure
1core
2postcore
3console
4postconsole
5mem
6postmem
7mmu
8postmmu
9coredevice
10fs
11device
12crypto
13of_populate
14late
15environment
16postenvironment
이후BAREBOX_RUNNING
조건부run_init

읽기 방향은 왼쪽에서 오른쪽, 다음 줄이다. run_init은 level 17이 아니다. 같은 숫자 section 안의 callback 사이에는 별도의 안정적 순서를 약속하지 않는다.

그림 4. 실패 callback도 순회를 멈추지 않는 경로
callback 호출result = (*initcall)()
비0이면 pr_err반환값은 이 callback에만 기록
다음 pointer범위 끝까지 반복 → RUNNING

오류 뒤 등록한 자원의 정리는 해당 callback·subsystem의 계약을 확인해야 한다. start_barebox()에는 공통 rollback이나 필수 level 실패 시 panic 경로가 없다.

원본 코드

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

commit314c679eea2d0ca847c64d1b646a1cf91225c0ecanchor · L337static int run_init(void)
313				   NULL);
314	globalvar_add_simple_int("autoboot_timeout",
315				 &global_autoboot_timeout, "%u");
316	globalvar_add_simple_enum("autoboot",
317				  &global_autoboot_state,
318				  global_autoboot_states,
319				  ARRAY_SIZE(global_autoboot_states));
320
321	return 0;
322}
323postcore_initcall(register_autoboot_vars);
324
325static enum autoboot_state current_autoboot = AUTOBOOT_UNKNOWN;
326
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();

발췌 범위와 읽기 기준

원문 313–401줄은 run_init()의 앞부분이다. L337은 함수 시작이며, 이 함수 안에는 initcall 포인터 순회가 없다. 이어지는 관련 원본의 start_barebox() L453–460이 전체 level 실행자다.

run_init()의 조기 반환(L350–364)과 외부 DT를 파일로 저장하는 L396–398을 본래 의미대로 읽는다. 외부 DT 파일 기록은 이 지점에서 root node를 등록한다는 뜻이 아니다.

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

함께 읽어야 하는 원본 코드

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

01. initcall을 마친 뒤 main loop로 진입하는 start_barebox

common/startup.c 438-502줄이다.

filecommon/startup.canchor · L448void __noreturn start_barebox(void)
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

등록에서 사용자 init까지

01

macro는 함수 포인터를 놓는다

__define_initcall(fn,id)는 함수 정의를 호출하지 않고 static const pointer를 .initcall.id에 배치한다. 숫자 0–16의 대응은 include/init.h에 고정돼 있다.

02

linker는 level을 순서대로 보존한다

BAREBOX_INITCALLS의 KEEP 연쇄가 범위의 순서를 정한다. source 파일명이나 C 선언 순서가 전체 실행 순서를 정하지 않는다. 같은 level 내부의 의존성은 별도 계약이 필요하다.

03

실행자는 start_barebox()다

포인터를 끝까지 순회하면서 각 결과를 검사한다. 비0은 pr_err로 보고하지만 break하지 않는다. 따라서 실패한 provider 뒤에도 consumer가 호출될 수 있다.

04

run_init()은 뒤에 온다

initcall 순회와 RUNNING 전환 뒤 barebox_main이 설정돼 있을 때만 run_init()이 시작된다. PATH, legacy init, /env/init/*, cmdline, autoboot와 shell이 그 범위다.

05

조기 반환은 최종 fallback으로 연결된다

legacy init을 찾거나 사용자가 abort하면 run_init()이 조기 반환한다. start_barebox()는 main 반환값을 판정하지 않고 shell-none poweroff 또는 무한 shell 루프를 따른다.

level 경계에서 확인할 세 가지

01

0–16 전체 목록을 보아야 한다

mem·postmem·mmu·postmmu·coredevice·fs·crypto·of_populate·postenvironment는 축약 그림에서 빠지기 쉽다. 실제 빌드의 linker map은 빈 level과 포함된 callback을 보여 준다.

02

동일 level의 우연한 배치에 기대지 않는다

linker macro가 보장하는 것은 숫자 section들의 순서다. 특정 provider가 같은 section의 consumer보다 먼저 올 것이라고 가정하면 빌드 구성 변경에 취약하다. 필요하면 level을 분리하거나 명시적 의존성을 둔다.

03

오류 정책은 callback과 caller를 나눠 본다

callback 내부가 부분 등록을 해제하는지는 해당 구현을 읽어야 한다. 공통 caller는 실패를 로그로 남길 뿐 반복을 계속한다. run_init()의 script 실패·abort 정책과도 별도다.

link-time 포인터와 runtime 상태

대상생성·배치사용주의
__initcall_##fn##idcompile/link 때 .initcall.Nruntime의 함수 포인터callback 자체가 생성한 자원과 다름
start/end 심벌linker scriptstart_barebox() 반복 범위종료 주소는 포함되지 않음
result각 callback 반환비0일 때 오류 로그다음 callback 실행을 막지 않음
barebox_main설정별 포인터전체 initcall 이후 조건부 호출기본 run_init 또는 NULL

실패가 보이는 지점과 실제 결과

상황caller 동작확인할 증거
callback 미포함호출 대상 자체가 없음build config, map의 .initcall.N 및 심벌
callback 비0오류 로그 후 다음 pointer실패 심벌·errno·뒤이은 callback 로그
같은 level 의존성caller는 의존성을 검사하지 않음실제 map 순서와 provider readiness
run_init() 조기 반환initcall 재실행 없음legacy init, abort, /cmdline 파일 쓰기 결과

linker 배열과 runtime 로그를 대조한다

보드 설정·toolchain과 동일한 산출물에서 읽기 전용으로 확인한다.

목적확인 방법판정 기준
level 배치빌드 linker map의 .initcall.0…16숫자 section 순서와 callback 포함 여부
경계 심벌${CROSS_COMPILE}nm -n barebox | grep '__barebox_initcalls_'start/end 주소와 배열 범위
실행자${CROSS_COMPILE}nm -n barebox | grep ' start_barebox$'C 선언문이 아닌 심벌명으로 검색
callback 결과CONFIG_DEBUG_INITCALLS와 serial loginitcall-> 뒤 비0 오류·다음 실행 여부

level 순서를 검증하는 실험

  1. 01
    map과 선언 macro 맞추기

    테스트 빌드에서 몇 개의 core_initcall·device_initcall을 선택해 map section과 함수 포인터 주소를 대조한다.

  2. 02
    비0 반환 callback 추적

    테스트 보드에서 실패를 주입하고 callback 로그, 다음 callback 실행, RUNNING 전환을 순서대로 기록한다.

  3. 03
    run_init() 경계 기록

    마지막 initcall과 run_init() 첫 로그의 시간을 비교하고 legacy init 또는 abort 후 shell fallback을 관찰한다.

원문과 다음 글