LK · source analysis

lk_main의 kernel 초기화 순서

heap, thread, dpc, timer와 platform early init이 bootstrap thread 생성 전 어떤 순서로 준비되는지 읽습니다.

표의 버전은 소스 분석 기준이며 최신 보안 버전 권고가 아닙니다. TF-A LTS 2.14.3 이후에는 보안 수정이 있습니다. 제품 적용 시 공식 변경 기록과 사용 플랫폼의 errata를 확인하세요.

Series
03 / 20
Baseline
upstream 1eb9917
Commit
1eb99171efae
Source
top/main.c:35-123 (발췌 범위)

lk_main의 kernel 초기화 순서 단계에서 실제로 바뀌는 상태는 무엇인가?

초기화 순서에 따라 잠금, 메모리 할당, 인터럽트를 사용할 수 있는 시점이 달라진다. 각 함수를 호출하기 전에 필요한 기능이 준비되었는지 확인한다.

scheduler를 시작하기 전 idle/bootstrap thread와 필수 queue가 완전히 초기화되어야 한다. 이 문장을 기준으로 코드를 위에서 아래로 읽으면, 함수 이름을 외우는 대신 어느 시점에 어떤 상태를 신뢰할 수 있는지 판단할 수 있다.

객체와 주소가 놓이는 구조

그림 1. lk_main의 kernel 초기화 순서에서 입력, 내부 상태, 출력의 경계
입력과 전제내부 상태외부로 공개되는 결과
01early hooks
02heap and threads
03timer/DPC
04bootstrap2

global kernel services / bootstrap thread를 중심에 놓고 왼쪽의 입력이 어떤 검사를 거쳐 오른쪽 결과로 공개되는지 표시했다. 실제 디버깅에서는 각 블록의 주소와 크기를 로그에 대입한다.

실행 흐름

그림 2. 정상 경로의 주요 호출과 상태 전달
arch early init
platform early init
kernel services
bootstrap thread
scheduler

화살표는 단순 호출 순서만 뜻하지 않는다. 각 단계가 성공을 반환할 때 다음 단계가 읽을 수 있는 상태가 무엇인지 함께 확인한다. 오류 반환이 발생하면 바로 다음 화살표로 진행하지 않고 해당 단계의 정리 경로를 따라간다.

단계별 입력과 출력

각 단계의 입력과 처리 후 바뀌는 상태를 정리한 표다. 사용 중인 소스 버전에서 다른 필드를 변경한다면 그에 맞춰 표도 수정한다.

#단계진입 시 신뢰할 상태성공 뒤 남아야 할 상태다음 소비자
01arch early init부트 CPU의 동기 실행 문맥early hooksplatform early init
02platform early initarch early init 완료 상태heap and threadskernel services
03kernel servicesplatform early init 완료 상태timer/DPCbootstrap thread
04bootstrap threadkernel services 완료 상태bootstrap2scheduler
05schedulerbootstrap thread 완료 상태bootstrap2이 단계의 처리 결과를 사용하는 코드

분석 범위의 전제와 비교해, 다음 단계에 잘못된 입력을 넘긴 부분부터 조사한다.

주소와 객체의 이동을 그림으로 읽기

아래 그림은 주소, 객체를 사용하는 기간, 제어권을 넘기는 시점을 중심으로 정리했다. 실제 주소와 크기는 사용 중인 보드의 bdinfo, 맵 파일과 링커 심벌로 확인한다.

그림 3. lk_main이 scheduler를 열기 전 준비하는 순서

호출 이름만 나열하지 않고, 각 단계가 다음 단계에 넘기는 상태를 기준으로 실행 순서를 표시한다.

01arch early init
02platform early init
03heap 초기화
04thread·DPC·timer 초기화
05bootstrap thread 생성
06scheduler 진입
그림 4. kernel service의 생산자와 첫 소비자

왼쪽 생산자가 가운데 상태를 완성하고, 오른쪽 소비자가 그 상태를 처음 사용하는 관계다.

01heap_initallocation 가능thread_create
02thread_init_earlybootstrap thread 구조thread_resume
03timer_inittimer queuesleep·timeout
04platform_init_timerclock eventscheduler tick
05bootstrap2thread contextapps_init

원본 코드

아래 코드는 LK upstream 1eb9917의 top/main.c에서 35-123줄을 그대로 가져온 것이다. 설명을 위해 실제 코드를 가짜 의사 코드로 바꾸지 않았다.

commit1eb99171efae98867d4be4a5bd6479ea03f43ac9anchor · L59void lk_main(ulong arg0
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);

발췌 범위와 읽기 기준

원문 35-123줄에는 앞뒤 문맥이 포함됩니다. 기준 구문 void lk_main(ulong arg0은 L59에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.

초기화 순서에 따라 잠금, 메모리 할당, 인터럽트를 사용할 수 있는 시점이 달라진다. 각 함수를 호출하기 전에 필요한 기능이 준비되었는지 확인한다.

함께 읽어야 하는 원본 코드

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

01. 첫 커널 스레드에서 나머지 초기화를 넘겨받는 bootstrap2

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

filetop/main.canchor · L115static int bootstrap2(void *arg) {
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

내부 동작을 더 깊게 읽기

01

진입 조건을 먼저 고정한다

arch early init에서 들어온 실행은 부트 CPU의 동기 실행 문맥에 놓여 있다. 이때 interrupt, MMU/cache, stack, heap 중 무엇이 이미 준비되었는지 소스의 호출자까지 올라가 확인한다. 같은 함수라도 SPL, relocation 전후, app thread처럼 호출 문맥이 달라지면 허용되는 API와 지연 시간이 달라진다.

초기화 순서에 따라 잠금, 메모리 할당, 인터럽트를 사용할 수 있는 시점이 달라진다. 각 함수를 호출하기 전에 필요한 기능이 준비되었는지 확인한다.

02

중심 객체의 생성과 공개를 나눈다

이 글의 중심 객체는 global kernel services / bootstrap thread다. 메모리를 확보한 시점, 필드를 채운 시점, 전역 list나 다른 subsystem에 공개한 시점을 구분한다. 공개 뒤 오류가 발생한다면 목록에서 제거하고 child, buffer, reference를 역순으로 정리하는지 확인한다.

빌드 산출물 관점에서는 최종 부트로더 이미지 안에 해당 symbol과 section이 실제로 포함되었는지도 map과 objdump로 검증한다.

03

주소, 크기와 정렬을 계산한다

부트 코드에서는 주소 계산 오류를 주의해야 한다. 원본과 목적지의 주소 범위, 헤더에 기록된 데이터 크기, 블록·페이지 단위를 표로 정리하고 각 구간의 끝 주소를 계산한다. 끝 주소가 start + size - 1처럼 마지막 바이트를 가리키는지, 구간 바로 다음 주소를 가리키는지는 API 규약에서 확인한다.

04

성공 flag와 실제 완료 시점을 맞춘다

platform early init → kernel services → bootstrap thread 구간에서는 부분 초기화 상태가 생길 수 있다. flag, list insertion, callback 등록, storage write 완료 중 무엇이 성공의 기준인지 찾는다. hardware write나 DMA가 포함되면 함수 반환과 장치 완료가 같은 시점인지도 확인한다.

다른 CPU, 인터럽트 처리기, USB 완료 콜백, 셸 명령에서도 이 상태를 읽는다면 메모리 접근 순서와 잠금 범위를 함께 확인한다.

05

제어권을 넘기기 전에 확인할 조건을 정리한다

정상 경로는 scheduler에서 끝난다. 이 단계가 함수 반환인지, scheduler 전환인지, 다른 image로의 비복귀 분기인지 구분한다. 비복귀 handoff라면 cache clean/invalidate, interrupt disable, 장치 quiesce, argument register와 FDT 또는 image address가 최종 점검 항목이다.

호출한 함수로 돌아오는 경로라면 오류와 일부 처리만 완료된 상태를 구분하는지 확인한다. 이어서 다음 후보를 시도할지, 복구 절차를 실행할지 살펴본다.

구현을 읽을 때 놓치기 쉬운 부분

01

lk_main은 kernel subsystem의 사용 가능 시점을 정의한다

heap, thread, timer, DPC, VM, platform과 target 초기화가 한 함수에 모여 있어 순서를 바꾸면 사용할 수 있는 API가 달라진다. 각 호출의 반환 직후 어떤 lock, allocator, interrupt와 scheduler 기능을 신뢰할 수 있는지 표로 고정한다.

초기 console 출력이 가능하더라도 heap이나 thread가 준비됐다는 뜻은 아니다. panic 경로가 일반 printf와 allocation을 요구하지 않는지도 확인한다.

02

bootstrap thread 생성은 실행 문맥을 바꾸는 경계다

초기화 일부는 현재 boot stack에서 실행되고 이후 작업은 생성된 bootstrap thread와 scheduler 문맥에서 계속된다. 함수 이름이 연속으로 보이더라도 current thread, interrupt 상태와 stack lifetime이 바뀐다.

boot stack을 재사용하거나 해제하는 platform이라면 마지막 참조가 사라지는 지점을 확인한다.

03

platform과 target callback은 core보다 강한 전제를 가질 수 없다

core init이 제공하기 전의 timer, heap, VM을 platform callback이 사용하면 특정 build에서만 우연히 동작한다. early와 normal callback의 허용 API를 문서화하고 assertion으로 검증한다.

각 단계 timestamp와 free heap을 남겨 초기화 지연과 memory 증가를 module별로 분리한다.

객체와 수명

대상만들어지는 시점유효 범위확인할 조건
global kernel services / bootstrap threadplatform early initscheduler 또는 오류 정리 완료까지진입 전제와 상태 계약
입력 buffer / metadataarch early initparse와 검증이 끝날 때까지길이, 정렬, 소유권, 변조 가능성
등록된 list / descriptorkernel services하위 시스템을 종료하거나 다음 이미지에 제어권을 넘길 때까지중복 등록, 해제된 객체를 가리키는 포인터, 오류 후 자원 정리
hardware 또는 persistent state실제 write/probe가 완료된 뒤reset 또는 명시적 해제·갱신까지쓰기 완료, 시간 초과, 전원 차단, 이전 상태 복원
최종 부트로더 이미지link/image 생성 시점다음 stage가 새 image로 교체할 때까지적재 주소, 진입점, 섹션, 헤더의 일치 여부

실패 지점과 증상

#조건관찰되는 증상먼저 볼 단계
01heap 이전 allocationcrashplatform early init
02timer 이전 timeout 사용영구 대기kernel services
03interrupt 조기 enable미등록 handler 실행bootstrap thread

로그가 끊긴 함수뿐 아니라 그 함수에 주소, 크기, 플래그를 전달한 앞 단계도 조사한다. 오류 처리 후 등록된 객체나 하드웨어 설정이 그대로 남아 있는지도 확인한다.

소스 밖에서 확인할 증거

소스에서 파악한 동작을 실제 빌드 결과와 대상 보드의 로그로 확인한다. 아래 명령의 보드 이름과 툴체인 접두사는 사용 중인 빌드 환경에 맞게 바꾼다.

#목적명령 또는 계측판정 기준
01빌드 구성make <project> -j1platform, target, app 선택과 linker 입력을 로그로 남긴다.
02symbol과 주소nm -n build-*/lk.elf | grep 'void lk_main'init hook, app descriptor와 함수가 어느 주소에 놓였는지 확인한다.
03어셈블리 대조objdump -drS build-*/lk.elfthread 전환과 interrupt disable 구간의 실제 명령을 확인한다.
04초기화 순서init level 전후에 current_time_hires()와 함수 이름 기록level 내부 순서와 지연을 serial log로 남긴다.
05문맥 확인current_thread, interrupt state, stack pointer 기록함수가 bootstrap thread인지 scheduler 이후 thread인지 구분한다.

직접 확인할 실험

  1. 01
    LK init log level을 높여 순서 기록

    platform early init 진입 전후에 early hooks의 주소·크기·반환값과 timestamp를 함께 남긴다.

  2. 02
    각 init 앞에서 interrupt 상태 확인

    kernel services 진입 전후에 heap and threads의 주소·크기·반환값과 timestamp를 함께 남긴다.

  3. 03
    heap 사용량과 첫 thread allocation 주소 기록

    bootstrap thread 진입 전후에 timer/DPC의 주소·크기·반환값과 timestamp를 함께 남긴다.

원문과 다음 글