LK · source analysis

bootstrap2와 init hook 단계

새 bootstrap2 thread에서 어떤 hook이 선택되고, arch·platform·target·app 초기화와 어떻게 교대하는지 읽습니다.

이 글은 LK upstream 고정 commit 1eb9917의 init hook 구현을 설명한다. 보드별 callback 효과는 선택한 project 소스에서 확인한다.

Series
04 / 20
Baseline
upstream 1eb9917
Commit
1eb99171efae
Source
top/main.c:18-106 (발췌 범위)

어떤 hook이 어느 CPU·level에서 호출되는가?

primary CPU의 bootstrap2()는 새 thread stack에서 시작해 THREADING→ARCH→PLATFORM→TARGET→APPS→LAST 구간의 init hook을 차례로 호출한다. 각 구간의 hook 뒤에 arch_init(), platform_init(), target_init(), apps_init()가 별도 호출된다 (top/main.c:115).

LK_INIT_HOOK_FLAGS는 정적 descriptor의 level·CPU flag를 lk_init section에 놓는다. lk_init_level()은 범위와 flag에 맞는 hook을 골라 동기 호출한다. flag 자체가 별도 thread·비동기 실행·완료 대기를 뜻하지 않는다 (top/include/lk/init.h:64, top/init.c:31).

등록 descriptor와 실행 경로

그림 1. init hook 등록과 CPU별 소비 경로
LK_INIT_HOOK_FLAGSname, function, level, CPU flags를 정적 descriptor로 등록
lk_init section__start_lk_init … __stop_lk_init 범위
lk_init_level()호출자가 정한 CPU flag·level 범위로 순회
primary: bootstrap2()LK_INIT_FLAG_PRIMARY_CPU, 각 구간 hook 뒤 직접 init 호출
secondary: secondary_cpu_bootstrap2()LK_INIT_FLAG_SECONDARY_CPUS, THREADING–LAST hook; primary 직접 init 반복 아님

descriptor는 link 시점에 section에 들어간다. primary와 secondary는 같은 등록 집합에서 서로 다른 flag를 요구한다. LK_INIT_HOOK 기본형은 primary flag를 쓴다 (top/include/lk/init.h:72).

flag·범위 필터와 동기 호출

그림 2. lk_init_level()이 hook 하나를 고르는 루프
호출 구간required_flag + start_level..stop_level
선별(entry.flags & required_flag) ≠ 0, level 범위 포함
순서아직 안 부른 가장 낮은 level의 descriptor 선택
선택한 found->hook(found->level)을 동기 호출 → 마지막 level/descriptor 갱신 → 다음 후보 탐색. 같은 level의 상대 순서는 section 순회에 좌우되므로 소스 파일 순서로 의존성을 설계하지 않는다.

lk_init_hook은 void (*)(uint level) 형식이다. framework 자체에는 hook 반환 오류·timeout·rollback 전달 경로가 없다 (top/include/lk/init.h:19, top/init.c:85).

primary bootstrap2의 정확한 순서

아래 다섯 hook 범위는 새 bootstrap2 thread에서 실행된다. 괄호 속 끝 level은 포함하지 않는다.

구간hook 범위직후 직접 호출근거
01THREADING ≤ level < ARCHarch_init()top/main.c:118
02ARCH ≤ level < PLATFORMplatform_init()top/main.c:123
03PLATFORM ≤ level < TARGETtarget_init()top/main.c:128
04TARGET ≤ level < APPSapps_init()top/main.c:132
05APPS ≤ level ≤ LASTbootstrap2()가 0 반환top/main.c:135

직접 호출 함수의 내부 장치 상태·blocking 정책은 이 표만으로 확정할 수 없다. 해당 platform·target·app 구현과 선택한 빌드 구성을 확인한다.

hook 구간과 실행 문맥을 함께 읽기

그림의 주소와 등록 descriptor는 선택한 LK 빌드의 ELF와 linker map에서 확인한다.

그림 3. 새 bootstrap2 thread가 처리하는 hook·직접 init 교대

각 hook 범위가 끝난 뒤 직접 init 함수를 호출한다. HEAP·VM 초기화는 이 thread보다 앞선 단계다.

01scheduler가 bootstrap2 실행
02THREADING..ARCH−1 hook → arch_init
03ARCH..PLATFORM−1 hook → platform_init
04PLATFORM..TARGET−1 hook → target_init
05TARGET..APPS−1 hook → apps_init
06APPS..LAST hook → return 0
그림 4. scheduler 이전 bootstrap 흐름과 새 bootstrap2 thread

새 thread가 존재한다는 것과 대기 대상 서비스가 준비됐다는 것은 별개의 조건이다.

thread_become_idle 이전

01부트 흐름의 현재 stack

02thread_init_early가 current 객체 부여

03early/heap/kernel hook 구간 수행

04bootstrap2는 생성·READY까지만

05idle 전환 때 interrupt enable·yield

새 bootstrap2 문맥

01scheduler가 새 stack에서 선택

02primary CPU flag hook 실행

03ARCH→APPS 직접 init과 교대

04heap·timer 등 선행 서비스는 존재

05blocking은 각 의존 서비스 확인 뒤 판단

원본 코드

아래 코드는 LK upstream 1eb9917의 top/main.c에서 18-106줄을 그대로 가져온 것이다.

commit1eb99171efae98867d4be4a5bd6479ea03f43ac9anchor · L42static int bootstrap2(void *arg)
18#include <kernel/mutex.h>
19#include <kernel/novm.h>
20#include <kernel/thread.h>
21#include <lib/heap.h>
22#include <lk/compiler.h>
23#include <lk/debug.h>
24#include <lk/init.h>
25#include <platform.h>
26#include <string.h>
27#include <target.h>
28
29/* saved boot arguments from whoever loaded the system */
30ulong lk_boot_args[4];
31
32extern void (*__ctor_list[])(void);
33extern void (*__ctor_end[])(void);
34extern int __bss_start;
35extern int _end;
36
37#if WITH_SMP
38static thread_t *secondary_bootstrap_threads[SMP_MAX_CPUS - 1];
39static uint secondary_bootstrap_thread_count;
40#endif
41
42static int bootstrap2(void *arg);
43
44static void call_constructors(void) {
45    void (**ctor)(void);
46
47    ctor = __ctor_list;
48    while (ctor != __ctor_end) {
49        void (*func)(void);
50
51        func = *ctor;
52
53        func();
54        ctor++;
55    }
56}
57
58/* called from arch code */
59void lk_main(ulong arg0, ulong arg1, ulong arg2, ulong arg3) {
60    // save the boot args
61    lk_boot_args[0] = arg0;
62    lk_boot_args[1] = arg1;
63    lk_boot_args[2] = arg2;
64    lk_boot_args[3] = arg3;
65
66    // get us into some sort of thread context
67    thread_init_early();
68
69    // early arch stuff
70    lk_primary_cpu_init_level(LK_INIT_LEVEL_EARLIEST, LK_INIT_LEVEL_ARCH_EARLY - 1);
71    arch_early_init();
72
73    // do any super early platform initialization
74    lk_primary_cpu_init_level(LK_INIT_LEVEL_ARCH_EARLY, LK_INIT_LEVEL_PLATFORM_EARLY - 1);
75    platform_early_init();
76
77    // do any super early target initialization
78    lk_primary_cpu_init_level(LK_INIT_LEVEL_PLATFORM_EARLY, LK_INIT_LEVEL_TARGET_EARLY - 1);
79    target_early_init();
80
81#if WITH_SMP
82    dprintf(INFO, "\nwelcome to lk/MP\n\n");
83#else
84    dprintf(INFO, "\nwelcome to lk\n\n");
85#endif
86    dprintf(INFO, "boot args 0x%lx 0x%lx 0x%lx 0x%lx\n",
87            lk_boot_args[0], lk_boot_args[1], lk_boot_args[2], lk_boot_args[3]);
88
89    // bring up the kernel heap
90    lk_primary_cpu_init_level(LK_INIT_LEVEL_TARGET_EARLY, LK_INIT_LEVEL_HEAP - 1);
91    dprintf(SPEW, "initializing heap\n");
92    heap_init();
93
94    // deal with any static constructors
95    dprintf(SPEW, "calling constructors\n");
96    call_constructors();
97
98    // initialize the kernel
99    lk_primary_cpu_init_level(LK_INIT_LEVEL_HEAP, LK_INIT_LEVEL_KERNEL - 1);
100    kernel_init();
101
102    lk_primary_cpu_init_level(LK_INIT_LEVEL_KERNEL, LK_INIT_LEVEL_THREADING - 1);
103
104    // create a thread to complete system initialization
105    dprintf(SPEW, "creating bootstrap completion thread\n");
106    thread_t *t = thread_create("bootstrap2", &bootstrap2, NULL, DEFAULT_PRIORITY, DEFAULT_STACK_SIZE);

원본 발췌와 빠진 중간 구간

기존 원본 18–106행은 그대로 보존했다. 42행의 static int bootstrap2(void *arg);는 선언이고, 구현은 115행에서 시작한다. 기존 보충 원본 156–181행은 secondary CPU 경로다. 두 발췌 사이의 실제 primary 실행은 아래 107–138행이다 (top/main.c:107).

filetop/main.clines107–138
    thread_set_pinned_cpu(t, 0);
    thread_detach(t);
    thread_resume(t);

    // become the idle thread and enable interrupts to start the scheduler
    thread_become_idle();
}

static int bootstrap2(void *arg) {
    dprintf(SPEW, "top of bootstrap2()\n");

    lk_primary_cpu_init_level(LK_INIT_LEVEL_THREADING, LK_INIT_LEVEL_ARCH - 1);
    arch_init();

    // initialize the rest of the platform
    dprintf(SPEW, "initializing platform\n");
    lk_primary_cpu_init_level(LK_INIT_LEVEL_ARCH, LK_INIT_LEVEL_PLATFORM - 1);
    platform_init();

    // initialize the target
    dprintf(SPEW, "initializing target\n");
    lk_primary_cpu_init_level(LK_INIT_LEVEL_PLATFORM, LK_INIT_LEVEL_TARGET - 1);
    target_init();

    dprintf(SPEW, "initializing apps\n");
    lk_primary_cpu_init_level(LK_INIT_LEVEL_TARGET, LK_INIT_LEVEL_APPS - 1);
    apps_init();

    lk_primary_cpu_init_level(LK_INIT_LEVEL_APPS, LK_INIT_LEVEL_LAST);

    return 0;
}

lk_primary_cpu_init_level(A,B−1)는 primary flag를 전달한다. LK_INIT_HOOK_FLAGS의 다른 flag는 scheduler thread 선택 옵션이 아니다 (top/include/lk/init.h:49, top/include/lk/init.h:64).

함께 읽어야 하는 원본 코드

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

01. 보조 CPU를 scheduler에 참여시키는 초기화

top/main.c 156-181줄이다.

filetop/main.canchor · L164void lk_init_secondary_cpus
156
157static int secondary_cpu_bootstrap2(void *arg) {
158    /* secondary cpu initialize from threading level up. 0 to threading was handled in arch */
159    lk_init_level(LK_INIT_FLAG_SECONDARY_CPUS, LK_INIT_LEVEL_THREADING, LK_INIT_LEVEL_LAST);
160
161    return 0;
162}
163
164void lk_init_secondary_cpus(uint secondary_cpu_count) {
165    if (secondary_cpu_count >= SMP_MAX_CPUS) {
166        dprintf(CRITICAL, "Invalid secondary_cpu_count %d, SMP_MAX_CPUS %d\n",
167                secondary_cpu_count, SMP_MAX_CPUS);
168        secondary_cpu_count = SMP_MAX_CPUS - 1;
169    }
170    for (uint i = 0; i < secondary_cpu_count; i++) {
171        dprintf(SPEW, "creating bootstrap completion thread for cpu %d\n", i + 1);
172        thread_t *t = thread_create("secondarybootstrap2",
173                                    &secondary_cpu_bootstrap2, NULL,
174                                    DEFAULT_PRIORITY, DEFAULT_STACK_SIZE);
175        t->pinned_cpu = i + 1;
176        thread_detach(t);
177        secondary_bootstrap_threads[i] = t;
178    }
179    secondary_bootstrap_thread_count = secondary_cpu_count;
180}
181#endif

등록·선별·호출의 경계

01

정적 descriptor와 runtime 호출을 나눈다

LK_INIT_HOOK_FLAGS는 struct lk_init_struct에 level, flags, hook, name을 채워 lk_init section에 둔다. bootstrap2()가 실행되기 전 이미 등록되어 있다 (top/include/lk/init.h:57, top/include/lk/init.h:64).

02

required_flag는 CPU 종류 선택이다

primary wrapper는 LK_INIT_FLAG_PRIMARY_CPU를 넘긴다. secondary 경로는 LK_INIT_FLAG_SECONDARY_CPUS를 사용한다. bitmask에 양쪽을 둔 descriptor는 두 경로에서 후보가 될 수 있다 (top/include/lk/init.h:40, top/main.c:157).

03

같은 level의 순서를 소스 순서로 가정하지 않는다

lk_init_level()은 가장 낮은 미호출 level을 반복 탐색하고, 같은 level에서는 section descriptor 순회 위치를 기준으로 다음 대상을 찾는다. 의존 관계가 있다면 서로 다른 level이나 명시적 동기화로 표현해야 한다 (top/init.c:39).

04

hook과 직접 init은 별개다

각 구간의 hook 호출 뒤 arch_init(), platform_init(), target_init(), apps_init()을 직접 호출한다. 이 함수들이 준비하는 실제 device·policy·app 상태는 선택한 보드 소스에 따라 다르다 (top/main.c:118).

05

void hook의 실패 처리 위치

hook 형식은 void 반환이고 dispatcher는 found->hook(found->level)을 호출한 뒤 다음 후보로 간다. framework에 공통 오류 반환·rollback·timeout은 보이지 않는다. 실패를 어떻게 드러낼지는 개별 hook 구현에서 확인한다 (top/include/lk/init.h:19, top/init.c:85).

구현에서 과장하기 쉬운 세 가지

01

level은 숫자와 호출 문맥을 함께 가진다

같은 descriptor라도 호출자는 primary·secondary flag와 level 범위를 정한다. “HEAP 이상이면 모든 API가 가능”처럼 일반화하지 않고, 사용하는 서비스의 실제 초기화 지점을 확인한다.

02

flag는 async나 threaded-hook 설정이 아니다

이 고정 구현에서 dispatcher는 선택한 hook을 현재 호출 thread에서 동기 실행한다. 별도 비동기 작업은 개별 callback이 명시적으로 만들 때만 생긴다. 그 작업의 완료 대기·수명은 해당 callback 소스에서 확인해야 한다 (top/init.c:85).

03

source/link 순서에 숨은 dependency를 만들지 않는다

같은 level의 실행은 lk_init section 순회에 의해 결정된다. source file 이름만으로 provider-before-consumer를 약속하지 않는다. map과 runtime hook trace를 함께 대조한다 (top/init.c:42).

등록 정보와 runtime 객체

대상생성·등록호출 시 읽는 값주의
lk_init_struct descriptor컴파일·link 시 lk_init section (top/include/lk/init.h:64)level, flags, hook, nameruntime thread 객체가 아님
bootstrap2 threadlk_main()의 thread_create() (top/main.c:106)primary hook과 직접 init을 실행READY와 RUNNING을 구분
primary hook 순회 상태lk_init_level()의 last descriptor·level (top/init.c:31)다음 미호출 descriptor 선별같은 level 순서에 암묵적 의존 금지
secondary hook threadlk_init_secondary_cpus() (top/main.c:164)secondary flag, THREADING–LAST 범위primary의 arch/platform/target/apps 직접 호출을 반복하지 않음

가정이 깨지는 위치

조건소스상 결과검증할 지점
provider와 consumer가 같은 level에 의존section 순회 순서 변경 시 선행 조건 불명확각 descriptor의 level·flag와 top/init.c:59
CPU flag가 맞지 않음dispatcher가 해당 hook을 건너뜀ptr->flags & required_flag 검사 (top/init.c:51)
callback 내부 작업 실패void hook에서 framework로 오류 코드가 전파되지 않음해당 callback의 log·assert·복구 구현과 top/init.c:85
필요 서비스 전 blocking현재 thread는 있을 수 있어도 의존 서비스가 미완료면 대기 가능호출 level과 서비스 초기화 위치 (top/main.c:118)

이 dispatcher에는 공통 error label이나 자동 rollback이 없다. 특정 hook이 panic·retry·degraded mode를 택하는지는 해당 hook을 읽어야 알 수 있다.

선택한 LK 빌드에서 검증하기

실제 project의 심볼이 보존된 ELF와 linker map 경로를 먼저 확인한다. 아래 <ELF>는 그 파일로 바꿔 실행한다. nm은 C 선언문을 출력하지 않는다.

목적명령 또는 기록판정 기준
함수·section 경계nm -an <ELF> | grep -E '[[:space:]](bootstrap2|__start_lk_init|__stop_lk_init)$'존재하는 symbol 이름·주소 확인; strip/config에 따라 없을 수 있음
section 배치readelf -SW <ELF> | grep lk_init등록 descriptor section의 존재 확인
호출 순서기존 TRACE_INIT 및 platform log (top/init.c:21)level·CPU flag·hook 이름을 직접 호출 시점과 대조
secondary 구분CPU 번호와 secondary_cpu_bootstrap2 log (top/main.c:157)primary direct init과 secondary hook 경로 혼동 방지

TRACE_INIT은 LK_DEBUGLEVEL 조건과 EARLIEST_TRACE_LEVEL 하한의 영향을 받는다. early hook이 출력되지 않아도 실행이 없었다고 단정하지 않는다.

세 가지 검증 질문

  1. 01
    등록과 호출을 맞춰 보기

    실제 빌드의 lk_init descriptor level·flag 목록을 map에서 확인하고, primary hook log와 직접 arch_init() 등 호출 시점을 나란히 적는다.

  2. 02
    같은 level 의존성 확인

    provider·consumer hook이 같은 level인지 확인한다. 그렇다면 암묵적 link 순서 대신 명시적 level 분리 또는 의존 상태 검사 필요성을 검토한다.

  3. 03
    secondary 경로 구분

    secondary CPU의 flag와 THREADING–LAST hook 로그를 primary bootstrap2() 로그와 별도 열로 비교한다.

원문과 다음 글