QUESTION
부트 스택에서 thread 문맥으로 언제 넘어가는가?
lk_main()은 arch 코드가 만든 부트 CPU 실행 흐름에서 시작한다. thread_init_early()가 이 현재 흐름을 bootstrap thread 객체로 감싸지만 새 stack으로 전환하지는 않는다 (top/main.c:66, kernel/thread.c:775).
early init hook과 arch/platform/target early 함수, heap, constructors, kernel_init()은 이 흐름에서 순서대로 호출된다. 그 뒤 새 bootstrap2 thread를 만들고 READY로 둔 다음, 원래 bootstrap 흐름이 idle이 되어 인터럽트를 켜고 yield한다. 이때 scheduler가 새 thread를 실행한다 (top/main.c:104, kernel/thread.c:853).
STRUCTURE
부트 스택과 새 thread의 경계
두 갈래는 같은 함수의 연속 호출이 아니다. thread_resume()은 READY queue에 넣고, 실제 실행 전환은 thread_become_idle() 안의 interrupt enable·yield 이후다. 부트 stack의 물리적 회수 여부는 이 파일만으로 단정하지 않는다.
CALL PATH
init hook 구간과 직접 호출을 구분하기
화살표 하나는 “왼쪽 level 범위의 hook → 오른쪽 직접 함수”를 뜻한다. 후반 다섯 행은 별도 bootstrap2() thread에서 실행된다. hook은 LK_INIT_FLAG_PRIMARY_CPU와 level에 맞는 등록 항목을 순회한다 (top/include/lk/init.h:49, top/init.c:31).
STATE LEDGER
함수·문맥·다음 사용 가능 상태
전환 전까지 thread_init_early()가 만든 current-thread 객체와 실제 새 thread의 stack을 구분한다.
| 순서 | 실행 문맥 | 수행 내용 | 다음에 신뢰할 상태 |
|---|---|---|---|
| 01 | 부트 CPU의 현재 stack | 부트 인자 보존 → thread_init_early() (top/main.c:59) | 현재 실행을 대표하는 bootstrap thread 객체·run queue 기초 |
| 02 | 동일 bootstrap 흐름 | EARLIEST/ARCH_EARLY/PLATFORM_EARLY hook 구간과 arch/platform/target early 직접 호출 (top/main.c:70) | 각 early hook과 callback이 제공한 보드별 상태만 |
| 03 | 동일 bootstrap 흐름 | TARGET_EARLY→HEAP−1 hook, heap_init(), constructors (top/main.c:90) | heap 사용과 constructor 효과 |
| 04 | 동일 bootstrap 흐름 | HEAP→KERNEL−1 hook, kernel_init() (top/main.c:99) | MP·thread·timer·port 초기화 (kernel/init.c) |
| 05 | 동일 bootstrap 흐름 | KERNEL→THREADING−1 hook, bootstrap2 생성·pin·detach·resume (top/main.c:102) | 새 thread는 READY; 아직 bootstrap2 본문 실행을 뜻하지 않음 |
| 06 | 원래 흐름이 idle로 변함 | thread_become_idle() → interrupt enable → yield (kernel/thread.c:853) | scheduler가 READY thread를 실행할 수 있음 |
| 07 | 새 bootstrap2 stack | THREADING→ARCH→PLATFORM→TARGET→APPS→LAST hook 구간과 arch/platform/target/apps 직접 호출 (top/main.c:115) | app init 후 bootstrap2 반환 |
각 level 구간의 hook과 바로 뒤 직접 함수는 동의어가 아니다. kernel_init() 내부 호출 순서는 kernel/init.c:18을 기준으로 본다.
VISUAL WALKTHROUGH
준비된 상태와 첫 사용자를 연결하기
현재 부트 흐름과 새 bootstrap2 thread가 언제 각 서비스를 사용할 수 있는지 구분한다. bdinfo는 U-Boot 명령이므로 LK 주소 확인 지침에 사용하지 않는다. LK 빌드의 linker map과 ELF symbol을 확인한다.
현재 bootstrap 흐름의 초기화와 새 bootstrap2의 실행 사이에는 READY queue와 scheduler 선택이 있다.
각 초기화 함수가 준비한 상태를 후속 함수가 사용한다.
thread_init_early→현재 bootstrap 객체→get_current_threadheap_init→동적 할당 가능→thread_createkernel_init→MP·thread·timer·port→thread_resumethread_resume→bootstrap2 READY→thread_become_idlebootstrap2→ARCH→APPS hook 구간→apps_initUPSTREAM SOURCE
원본 코드
아래 코드는 LK upstream 1eb9917의 top/main.c에서 35-123줄을 그대로 가져온 것이다.
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);
107 thread_set_pinned_cpu(t, 0);
108 thread_detach(t);
109 thread_resume(t);
110
111 // become the idle thread and enable interrupts to start the scheduler
112 thread_become_idle();
113}
114
115static int bootstrap2(void *arg) {
116 dprintf(SPEW, "top of bootstrap2()\n");
117
118 lk_primary_cpu_init_level(LK_INIT_LEVEL_THREADING, LK_INIT_LEVEL_ARCH - 1);
119 arch_init();
120
121 // initialize the rest of the platform
122 dprintf(SPEW, "initializing platform\n");
123 lk_primary_cpu_init_level(LK_INIT_LEVEL_ARCH, LK_INIT_LEVEL_PLATFORM - 1);
READING CONTRACT
발췌 범위와 해석
보존한 첫 발췌는 고정 top/main.c의 35–123행이다. lk_main() 정의는 59행이며 35행부터가 함수 시작은 아니다. 115행부터 시작한 bootstrap2()의 나머지 본문과 secondary CPU 경로는 이어지는 관련 원본 발췌에 있다.
같은 파일의 lk_primary_cpu_init_level(A,B−1)는 A 이상 B 미만의 primary CPU hook을 먼저 수행한다. hook 이후의 직접 함수는 별도 호출이다 (top/include/lk/init.h:49, top/init.c:31).
thread_init_early()의 “thread context”는 현재 부트 흐름을 나타내는 객체를 뜻한다. 별도 bootstrap2 stack에서 실행되는 시점은 thread_become_idle() 이후다 (kernel/thread.c:775, kernel/thread.c:853).
RELATED SOURCE
함께 읽어야 하는 원본 코드
첫 코드 조각만으로 동작이 완성되지 않는 경우 호출 매크로, 객체 정의와 실제 실행 목록을 같은 페이지에 묶었다. 각 조각은 같은 기준 commit에서 가져왔다.
01. 첫 커널 스레드에서 나머지 초기화를 넘겨받는 bootstrap2
top/main.c 105-181줄이다.
105 dprintf(SPEW, "creating bootstrap completion thread\n");
106 thread_t *t = thread_create("bootstrap2", &bootstrap2, NULL, DEFAULT_PRIORITY, DEFAULT_STACK_SIZE);
107 thread_set_pinned_cpu(t, 0);
108 thread_detach(t);
109 thread_resume(t);
110
111 // become the idle thread and enable interrupts to start the scheduler
112 thread_become_idle();
113}
114
115static int bootstrap2(void *arg) {
116 dprintf(SPEW, "top of bootstrap2()\n");
117
118 lk_primary_cpu_init_level(LK_INIT_LEVEL_THREADING, LK_INIT_LEVEL_ARCH - 1);
119 arch_init();
120
121 // initialize the rest of the platform
122 dprintf(SPEW, "initializing platform\n");
123 lk_primary_cpu_init_level(LK_INIT_LEVEL_ARCH, LK_INIT_LEVEL_PLATFORM - 1);
124 platform_init();
125
126 // initialize the target
127 dprintf(SPEW, "initializing target\n");
128 lk_primary_cpu_init_level(LK_INIT_LEVEL_PLATFORM, LK_INIT_LEVEL_TARGET - 1);
129 target_init();
130
131 dprintf(SPEW, "initializing apps\n");
132 lk_primary_cpu_init_level(LK_INIT_LEVEL_TARGET, LK_INIT_LEVEL_APPS - 1);
133 apps_init();
134
135 lk_primary_cpu_init_level(LK_INIT_LEVEL_APPS, LK_INIT_LEVEL_LAST);
136
137 return 0;
138}
139
140#if WITH_SMP
141void lk_secondary_cpu_entry(void) {
142 uint cpu = arch_curr_cpu_num();
143
144 if (cpu > secondary_bootstrap_thread_count) {
145 dprintf(CRITICAL, "Invalid secondary cpu num %d, SMP_MAX_CPUS %d, secondary_bootstrap_thread_count %d\n",
146 cpu, SMP_MAX_CPUS, secondary_bootstrap_thread_count);
147 return;
148 }
149
150 thread_secondary_cpu_init_early();
151 thread_resume(secondary_bootstrap_threads[cpu - 1]);
152
153 dprintf(SPEW, "entering scheduler on cpu %d\n", cpu);
154 thread_secondary_cpu_entry();
155}
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
DETAILS
코드 경계를 따라 읽는 내부 동작
초기 current thread는 별도 할당된 bootstrap2가 아니다
thread_init_early()는 run queue와 thread list를 초기화하고 정적 idle-thread 객체를 bootstrap 이름으로 현재 thread에 연결한다. 부트 stack에서 흐름이 계속된다 (kernel/thread.c:775).
hook 구간과 직접 함수가 교대로 놓인다
lk_primary_cpu_init_level()은 범위·flag에 맞는 hook을 level 순으로 호출한다. 예를 들어 HEAP 직전 hook을 수행한 다음 heap_init()을 직접 호출한다. 등록 hook의 구체 목록은 선택한 빌드 구성에 따라 다르다 (top/main.c:90, top/init.c:31).
kernel_init의 실제 네 서비스
이 고정 commit의 kernel_init()은 event log 선택 초기화 뒤 mp_init(), thread_init(), timer_init(), port_init()을 호출한다. DPC는 이 함수의 직접 호출 목록에 없다 (kernel/init.c:18).
READY와 RUNNING 사이의 전환
thread_create()가 새 stack과 초기 frame을 준비한다. thread_resume()은 SUSPENDED를 READY로 바꾸고 run queue에 넣는다. 이 호출 시 인터럽트가 비활성인 bootstrap 경로에서는 즉시 재스케줄하지 않는다. thread_become_idle()이 현재 흐름을 idle로 바꾸고 interrupt enable·yield를 호출한다 (kernel/thread.c:146, kernel/thread.c:275, kernel/thread.c:853).
secondary CPU는 별도 경로
secondary_cpu_bootstrap2()는 primary의 bootstrap2()와 다른 함수다. secondary CPU에서는 lk_secondary_cpu_entry()가 자기 bootstrap thread를 resume하고 LK_INIT_FLAG_SECONDARY_CPUS hook을 THREADING–LAST 범위에서 실행한다 (top/main.c:141, top/main.c:157).
IMPLEMENTATION NOTES
구현에서 헷갈리기 쉬운 경계
EARLY와 일반 init을 같은 문맥으로 뭉치지 않기
hook level은 순서와 primary/secondary flag를 함께 가진다. 특정 platform callback이 heap이나 timer를 사용할 수 있는지는 그 callback의 정확한 위치와 보드 구현을 대조해야 한다 (top/include/lk/init.h:21).
새 thread를 만드는 것과 실행하는 것은 다르다
새 bootstrap2의 stack은 thread_create()에서 확보하고, thread_resume() 뒤 READY가 된다. 원래 bootstrap 객체는 thread_become_idle()에서 idle 역할로 전환된다 (kernel/thread.c:146, kernel/thread.c:853).
timer queue와 hardware tick을 구분하기
timer_init()은 CPU별 queue를 준비하고, 동적 timer가 아닌 구성에서 periodic timer를 등록한다. platform_init_timer()라는 고정 호출을 이 글의 경로에 끼워 넣지 않는다 (kernel/timer.c:283).
OBJECT LIFETIME
객체와 stack의 수명
| 대상 | 만드는 함수 | 언제 쓰는가 | 주의 |
|---|---|---|---|
현재 bootstrap thread 객체 | thread_init_early() (kernel/thread.c:775) | early init 동안 current thread로 사용, 이후 idle로 전환 | 정적 idle-thread 객체를 반쯤 구성한다. 새 stack 할당과 구분 |
| heap | heap_init() (top/main.c:92) | constructors와 thread_create() 이전에 준비 | 일찍 호출한 hook의 allocator 사용 가능성은 별도 점검 |
새 bootstrap2 객체·stack | thread_create() (top/main.c:106) | resume 뒤 READY, scheduler 선택 후 RUNNING | top/main.c는 반환값 NULL을 검사하지 않고 pin·detach 호출 |
| timer queue | timer_init() (kernel/timer.c:283) | timer 등록·sleep/timeout 경로 | hardware tick 등록은 timer 구성에 따라 다름 |
| secondary CPU bootstrap thread | lk_init_secondary_cpus() (top/main.c:164) | secondary entry가 해당 thread를 resume | primary bootstrap2와 함수·hook flag가 다름 |
FAILURE PATH
조건별 점검 지점
| 조건 | 관찰 가능한 문제 | 소스에서 확인할 점 |
|---|---|---|
| heap 이전에 동적 할당 요구 | 선행 hook의 전제 위반 또는 할당 실패 | 해당 hook level과 heap_init() 위치 (top/main.c:90) |
thread_create()가 NULL 반환 | 뒤따르는 pin·detach에서 유효하지 않은 포인터 사용 가능 | 반환 규약과 바로 다음 호출 (kernel/thread.c:137, top/main.c:106) |
| READY를 RUNNING으로 오인 | bootstrap2의 log가 resume 전후 기대와 다름 | thread_resume()의 queue 삽입과 thread_become_idle()의 yield (kernel/thread.c:269, kernel/thread.c:853) |
| timer 기능을 너무 이르게 사용 | queue 또는 platform tick 준비 전에 사용 | timer_init() 내부 구성 분기 (kernel/timer.c:283) |
이 글의 lk_main()은 일반적인 오류 코드 반환·단계별 unwind 함수가 아니다. 실패마다 자동 복구가 있다고 추정하지 말고 보드 설정과 호출자의 처리 경로를 확인한다.
EVIDENCE
ELF와 초기화 로그로 확인하기
먼저 해당 project의 실제 ELF·map 경로를 찾는다. 아래 <ELF>는 확인한 파일로 치환한다. nm은 C 선언문이 아니라 symbol 이름을 출력한다.
| 목적 | 명령 또는 계측 | 판정 기준 |
|---|---|---|
| symbol 존재 | nm -n <ELF> | grep -E '[[:space:]]lk_main$' | 출력 끝의 lk_main symbol과 주소 확인 |
| 호출 전환 | objdump -drS <ELF> | lk_main의 resume·idle 호출과 bootstrap2 진입 주소를 대조 |
| hook 순서 | 소스의 lk_init_level() 및 초기화 log (top/init.c:29) | 같은 level·flag의 실제 등록 hook과 실행 순서 확인 |
| thread 문맥 | get_current_thread() 이름과 stack pointer를 전환 전후에 기록 | bootstrap → idle, 새 bootstrap2의 문맥 구별 |
bdinfo나 U-Boot 전용 명령은 이 LK 코드의 관찰 명령으로 제시하지 않는다.
LAB
보드에서 검증할 세 지점
- 01early 문맥 기록
thread_init_early()전후 current thread 이름과 stack pointer를 기록해 같은 부트 흐름을 객체로 감싼 시점을 확인한다. - 02READY와 switch 분리
thread_resume()직후 bootstrap2 상태와thread_become_idle()직후 첫 bootstrap2 log를 대조한다. - 03init level 순서 기록
선택한 빌드의 primary hook 이름·level과 직접 arch/platform/target/apps init 시점을 나란히 남긴다. secondary CPU log는 별도 열로 기록한다.
PRIMARY REFERENCES