LK · source analysis

platform과 target 초기화 경계

QEMU ARM의 early platform 작업과 target hook, bootstrap2 thread의 후반 초기화 순서를 원본 코드로 구분합니다.

Series
11 / 20
Baseline
upstream 1eb9917
Commit
1eb99171efae
Source
platform/qemu-virt-arm/platform.c:89-177 (발췌 범위)

GIC·timer·early UART는 언제 초기화되고, target과 app은 언제 호출되는가?

고정 platform/qemu-virt-arm/platform.c에서는 platform_early_init() 내부에서 arm_gic_init → arm_generic_timer_init → uart_init_early가 실행된다. 이 셋은 platform_early_init 뒤에 따로 이어지는 단계가 아니다.

top/main.c의 lk_main은 그다음 target_early_init, heap·constructor·kernel 준비, bootstrap2 thread 생성과 idle 전환을 수행한다. 이후 그 thread의 bootstrap2에서 arch_init → platform_init → target_init → apps_init가 실행된다. 호출자 · platform 구현.

호출자와 구현을 분리해 읽기

그림 1. top/main.c가 단계 경계를 정하고 QEMU platform 코드가 내부 작업을 정의한다
CALL ORDERtop/main.c

lk_main은 early hook과 heap/thread 전환을 배치한다. bootstrap2는 별도 thread에서 normal hook과 app init을 배치한다.

QEMU PLATFORM WORKplatform/qemu-virt-arm/platform.c

early 함수 안에서 GIC·physical timer·early UART와 FDT/PMM/PSCI 처리를 한다. normal platform_init은 나중에 UART·PCI·virtio를 다룬다.

target_early_init과 target_init은 top/main.c의 서로 다른 call site다. 이 두 원본 파일만으로 target 구현의 GPIO·storage 정책을 단정하지 않는다.

동기 early 경로와 bootstrap2 thread

그림 2. lk_main의 early 호출과 별도 bootstrap2 thread의 후속 순서
LK_MAIN · EARLY

early 호출과 thread 준비

  1. thread_init_early → init level → arch_early_init.
  2. platform_early_init 안에서 GIC → physical timer → early UART → FDT/PMM/PSCI.
  3. target_early_init → heap_init → constructors → kernel_init.
  4. bootstrap2 thread 생성·CPU 0 고정·detach·resume → thread_become_idle.

top/main.c L59–113.

BOOTSTRAP2 · THREAD

normal hook과 apps

  1. thread의 bootstrap2에서 init level → arch_init.
  2. 다음 level → platform_init (QEMU 구현은 normal UART, 조건부 PCI, virtio).
  3. 다음 level → target_init.
  4. 다음 level → apps_init, 마지막 init level까지 진행.

top/main.c L115–137.

thread_resume은 bootstrap2의 실행을 예약하며 동기 호출하지 않는다. 각 hook 사이의 lk_primary_cpu_init_level도 순서의 일부다. 두 QEMU platform hook은 void이며, top/main.c의 이 call site는 hook의 오류 반환을 검사하지 않는다.

호출 위치와 다음 경계

GIC·timer·early UART는 아래 02행의 함수 내부다. 05행부터는 별도 bootstrap2 thread가 담당한다.

#문맥호출과 내부 작업다음 경계근거
01lk_mainthread_init_early, init level, arch_early_initearly platformmain L59–75
02platform_early_init 내부GIC → physical timer → early UART → FDT walk·PMM·PSCItarget_early_initplatform L113–166
03lk_maintarget_early_init, 그다음 heap·constructors·kernel 준비thread 생성main L77–102
04lk_mainthread_create → CPU 0 고정 → detach → resumethread_become_idlemain L104–113
05bootstrap2 threadinit level → arch_init → platform_initnormal targetmain L115–124
06bootstrap2 threadinit level → target_init → init level → apps_initlast init levelmain L126–137

QEMU platform_init의 normal UART·PCI·virtio는 early UART/GIC/timer와 다른 시점이다. target 함수의 내부 구현은 별도 target 소스로 확인해야 한다.

같은 이름의 early와 normal 단계를 나눠 보기

그림 3. QEMU ARM platform_early_init() 안의 실제 실행 순서
FIRST · L113–119GIC → physical timer → early UART

arm_gic_init, arm_generic_timer_init, uart_init_early는 모두 platform_early_init() 본문 안에서 호출된다.

THEN · L121–166FDT → PMM → CPU count → PSCI

fdt_walk 뒤 memory arena와 첫 64 KiB를 처리한다. CPU count를 정한 뒤 각 secondary CPU에 psci_cpu_on을 시도한다. FDT walk 오류는 로그를 남기고 뒤로 진행한다.

그림 4. target hook은 early와 bootstrap2에서 한 번씩 다른 경계에 있다
EARLY · LK_MAINtarget_early_init

platform_early_init 반환 다음 호출된다. heap·constructors·kernel_init과 bootstrap2 thread 생성은 그 뒤다.

NORMAL · BOOTSTRAP2target_init → apps_init

arch_init와 platform_init 이후 별도 thread에서 실행된다. normal platform_init에는 uart_init과 조건부 PCI, virtio 탐지가 있다.

원본 코드

아래 코드는 LK upstream 1eb9917의 platform/qemu-virt-arm/platform.c에서 89-177줄을 그대로 가져온 것이다.

commit1eb99171efae98867d4be4a5bd6479ea03f43ac9anchor · L113void platform_early_init(void)
89
90        *found_mem = true; // stop searching after the first one
91    }
92}
93
94static void cpucallback(uint64_t id, void *cookie) {
95    int *cpu_count = (int *)cookie;
96
97    LTRACEF("id %#llx cookie %p\n", id, cookie);
98
99    (*cpu_count)++;
100}
101
102struct pcie_detect_state {
103    struct fdt_walk_pcie_info info;
104} pcie_state;
105
106static void pciecallback(const struct fdt_walk_pcie_info *info, void *cookie) {
107    struct pcie_detect_state *state = cookie;
108
109    LTRACEF("ecam base %#llx, len %#llx, bus_start %hhu, bus_end %hhu\n", info->ecam_base, info->ecam_len, info->bus_start, info->bus_end);
110    state->info = *info;
111}
112
113void platform_early_init(void) {
114    /* initialize the interrupt controller */
115    arm_gic_init();
116
117    arm_generic_timer_init(ARM_GENERIC_TIMER_PHYSICAL_INT, 0);
118
119    uart_init_early();
120
121    int cpu_count = 0;
122    bool found_mem = false;
123    struct fdt_walk_callbacks cb = {
124        .mem = memcallback,
125        .memcookie = &found_mem,
126        .cpu = cpucallback,
127        .cpucookie = &cpu_count,
128        .pcie = pciecallback,
129        .pciecookie = &pcie_state,
130    };
131
132    const void *fdt = (void *)KERNEL_BASE;
133    status_t err = fdt_walk(fdt, &cb);
134    LTRACEF("fdt_walk returns %d\n", err);
135
136    if (err != 0) {
137        printf("FDT: error finding FDT at %p, using default memory & cpu count\n", fdt);
138    }
139
140    /* add the main memory arena */
141    pmm_add_arena(&arena);
142
143    /* reserve the first 64k of ram, which should be holding the fdt */
144    struct list_node list = LIST_INITIAL_VALUE(list);
145    pmm_alloc_range(MEMBASE, 0x10000 / PAGE_SIZE, &list);
146
147    /* count the number of secondary cpus */
148    if (cpu_count == 0) {
149        /* if we didn't find any in the FDT, assume max number */
150        cpu_count = SMP_MAX_CPUS;
151    } else if (cpu_count > 0) {
152        printf("FDT: found %d cpus\n", cpu_count);
153        cpu_count = MIN(cpu_count, SMP_MAX_CPUS);
154    }
155
156    LTRACEF("booting %d cpus\n", cpu_count);
157
158    /* boot the secondary cpus using the Power State Coordintion Interface */
159    for (int cpuid = 1; cpuid < cpu_count; cpuid++) {
160        /* note: assumes cpuids are numbered like MPIDR 0:0:0:N */
161        int ret = psci_cpu_on(cpuid, MEMBASE + KERNEL_LOAD_OFFSET);
162        if (ret != 0) {
163            printf("ERROR: psci CPU_ON returns %d\n", ret);
164        }
165    }
166}
167
168void platform_init(void) {
169    status_t err;
170
171    uart_init();
172
173    /* detect pci */
174#if ARCH_ARM
175    if (pcie_state.info.ecam_base > (1ULL << 32)) {
176        // dont try to configure this since we dont have LPAE support
177        printf("PCIE: skipping pci initialization due to high memory ECAM\n");

발췌 범위와 호출자

원문 89–177줄에는 앞뒤 문맥이 포함됩니다. 기준 구문 void platform_early_init(void)은 L113에 있습니다. GIC·timer·early UART는 L115–119의 함수 내부 호출입니다.

이 코드 조각만으로 target_early_init이나 bootstrap2의 위치는 알 수 없습니다. 같은 고정 commit의 top/main.c L59–137을 호출 순서의 근거로 함께 읽습니다. platform_init의 uart_init은 early UART와 별도입니다.

함께 읽어야 하는 원본 코드

아래 원본 코드는 early 함수가 끝난 뒤에도 즉시 실행되지 않습니다. top/main.c의 bootstrap2에서 arch_init 다음 platform_init이 호출됩니다.

01. bootstrap2에서 호출되는 normal platform_init의 UART·PCI·virtio

platform/qemu-virt-arm/platform.c 158-234줄이다.

fileplatform/qemu-virt-arm/platform.canchor · L168void platform_init(void)
158    /* boot the secondary cpus using the Power State Coordintion Interface */
159    for (int cpuid = 1; cpuid < cpu_count; cpuid++) {
160        /* note: assumes cpuids are numbered like MPIDR 0:0:0:N */
161        int ret = psci_cpu_on(cpuid, MEMBASE + KERNEL_LOAD_OFFSET);
162        if (ret != 0) {
163            printf("ERROR: psci CPU_ON returns %d\n", ret);
164        }
165    }
166}
167
168void platform_init(void) {
169    status_t err;
170
171    uart_init();
172
173    /* detect pci */
174#if ARCH_ARM
175    if (pcie_state.info.ecam_base > (1ULL << 32)) {
176        // dont try to configure this since we dont have LPAE support
177        printf("PCIE: skipping pci initialization due to high memory ECAM\n");
178        pcie_state.info.ecam_len = 0;
179    }
180#endif
181    if (pcie_state.info.ecam_len > 0) {
182        printf("PCIE: initializing pcie with ecam at %#" PRIx64 " found in FDT\n", pcie_state.info.ecam_base);
183        err = pci_init_ecam(pcie_state.info.ecam_base, pcie_state.info.ecam_len, pcie_state.info.bus_start, pcie_state.info.bus_end);
184        if (err == NO_ERROR) {
185            // add some additional resources to the pci bus manager in case it needs to configure
186            if (pcie_state.info.io_len > 0) {
187                // we can only deal with a mapping of io base 0 to the mmio base
188                DEBUG_ASSERT(pcie_state.info.io_base == 0);
189                pci_bus_mgr_add_resource(PCI_RESOURCE_IO_RANGE, pcie_state.info.io_base, pcie_state.info.io_len);
190
191                // TODO: set the mmio base somehow so pci knows what to do with it
192            }
193            if (pcie_state.info.mmio_len > 0) {
194                pci_bus_mgr_add_resource(PCI_RESOURCE_MMIO_RANGE, pcie_state.info.mmio_base, pcie_state.info.mmio_len);
195            }
196            if (pcie_state.info.mmio64_len > 0) {
197                pci_bus_mgr_add_resource(PCI_RESOURCE_MMIO64_RANGE, pcie_state.info.mmio64_base, pcie_state.info.mmio64_len);
198            }
199
200            // start the bus manager
201            pci_bus_mgr_init();
202
203            pci_bus_mgr_assign_resources();
204        }
205    }
206
207    /* detect any virtio devices */
208    uint virtio_irqs[NUM_VIRTIO_TRANSPORTS];
209    for (int i = 0; i < NUM_VIRTIO_TRANSPORTS; i++) {
210        virtio_irqs[i] = VIRTIO0_INT_BASE + i;
211    }
212
213    virtio_mmio_detect((void *)VIRTIO_BASE, NUM_VIRTIO_TRANSPORTS, virtio_irqs, 0x200);
214
215#if WITH_LIB_MINIP
216    if (virtio_net_found() > 0) {
217        uint8_t mac_addr[6];
218
219        virtio_net_get_mac_addr(mac_addr);
220
221        TRACEF("found virtio networking interface\n");
222
223        /* start minip */
224        minip_set_eth(virtio_net_send_minip_pkt, NULL, mac_addr);
225
226        __UNUSED uint32_t ip_addr = IPV4(192, 168, 0, 99);
227        __UNUSED uint32_t ip_mask = IPV4(255, 255, 255, 0);
228        __UNUSED uint32_t ip_gateway = IPV4_NONE;
229
230        virtio_net_start();
231
232        //minip_start_static(ip_addr, ip_mask, ip_gateway);
233        minip_start_dhcp();
234    }

고정 QEMU ARM 구현에서 구분할 상태

01

early thread 문맥은 먼저 만든다

lk_main은 thread_init_early 후 init level과 arch_early_init을 지나 platform_early_init에 들어간다. “thread가 전혀 없다”거나 이미 bootstrap2가 실행 중이라고 읽지 않는다. main L59–79.

02

GIC·timer·early UART는 platform 함수 내부다

QEMU 구현은 세 호출 뒤 FDT walk, PMM arena 등록, 첫 64 KiB 예약, CPU count/PSCI 시도를 한다. FDT walk 오류는 로그만 남기고 이 함수의 나머지 경로로 진행한다. platform L113–166.

03

target early 뒤 heap·kernel·thread가 온다

target_early_init 반환 다음 init level, heap_init, constructors, kernel_init을 거친다. 그다음 bootstrap2 thread를 CPU 0에 고정하고 resume한 뒤 thread_become_idle로 간다. main L77–113.

04

normal platform은 별도의 나중 호출이다

bootstrap2에서 arch_init 다음 platform_init을 호출한다. QEMU 구현은 uart_init으로 시작해 조건부 PCI ECAM 설정과 virtio transport 탐지를 수행한다. 이 normal UART는 early UART 호출과 합치지 않는다. main L115–124 · platform L168–234.

05

apps는 target normal 뒤 init된다

bootstrap2는 platform_init 뒤 target_init, 이어 apps_init과 마지막 init level을 실행한 뒤 반환한다. 여기에는 다른 image로의 비복귀 handoff가 없다. main L126–139.

두 파일에서 확정할 수 있는 경계

01

init level과 hook은 한 쌍으로 읽는다

top/main.c는 각 early/normal hook 전에 lk_primary_cpu_init_level 범위를 호출한다. “arch → platform → target”이라는 이름만으로 init level 경계를 생략하지 않는다. main L66–137.

02

target의 내부 정책은 이 호출자에 없다

lk_main과 bootstrap2는 target_early_init/target_init의 호출 위치를 보여준다. GPIO·storage 구현 또는 성공 flag는 여기서 정의하지 않으므로 target 별 소스를 따로 대조한다.

03

FDT 오류와 PSCI 오류는 여기서 즉시 중단하지 않는다

QEMU early platform은 fdt_walk 오류를 출력한 뒤 memory arena와 CPU 처리로 계속 간다. psci_cpu_on 실패도 로그를 남긴다. 함수 반환형이 void이므로 단계 표에 가상의 오류 반환 화살표를 넣지 않는다. platform L132–166.

04

normal platform의 선택 작업은 조건부다

platform_init은 normal UART 뒤 PCI ECAM 탐지 결과를 확인하고, ARM의 high ECAM은 LPAE 부재로 생략한다. virtio transport 탐지는 별도 호출이다. 모든 target에서 PCI/network가 항상 올라온다고 그리지 않는다. platform L168–234.

단계가 사용하는 구체적 상태

상태QEMU ARM 코드의 생산/사용경계에서 확인할 점근거
GIC·physical timer·early UARTplatform_early_init 시작에서 순서대로 호출target early보다 앞; normal UART와 구분platform
FDT·PMM arenaFDT walk 후 arena 등록, 첫 64 KiB 예약 시도FDT 오류 로그 뒤에도 함수가 진행platform
CPU count·PSCIFDT callback의 count 또는 SMP_MAX_CPUS fallback, secondary CPU_ON 반복각 실패는 출력하며 반복 계속platform
bootstrap2 threadkernel_init 이후 생성, CPU 0 고정·detach·resumelk_main은 idle로 전환; 재개된 thread에서 normal hook 실행main
normal platform/target/appsbootstrap2에서 arch_init 뒤 차례로 호출early hook과 다른 thread·init levelmain

로그를 단계 실패로 잘못 읽지 않기

#조건고정 소스의 동작확인할 위치
01FDT walk 오류오류를 출력하지만 PMM와 CPU-count 경로로 진행platform L132–150
02CPU count를 FDT에서 못 얻음SMP_MAX_CPUS를 가정한 뒤 secondary CPU_ON 반복platform L147–165
03psci_cpu_on 오류오류를 출력; loop의 다음 CPU를 계속 시도platform L158–165
04ARM high ECAMnormal platform_init의 PCI 설정을 건너뛰도록 길이를 0으로 설정platform L173–181

QEMU platform_early_init과 platform_init은 void 함수다. top/main.c는 표시한 target call site에서도 오류 반환을 검사하지 않는다. 원본에 없는 성공 flag·rollback 계약을 표에 만들지 않는다.

고정 소스와 실제 로그의 대조 지점

실제 보드·QEMU build에서는 project 구성과 로그를 함께 고정한다. 아래 계측은 재현 절차이며 실제 보드 실행 결과가 아니다.

#목적소스/로그에서 볼 값판정 기준
01early call ordertop/main.c L66–79와 platform.c L113–119GIC·timer·early UART가 platform 함수 안에 있는지 확인
02heap/thread boundarytop/main.c L89–113target early 뒤 heap·kernel, bootstrap2 생성과 idle 전환 순서
03normal call ordertop/main.c L115–137bootstrap2의 arch/platform/target/apps와 init level
04QEMU 조건부 작업FDT·PSCI 로그, PCI ECAM/virtio 탐지 로그로그 경고를 곧바로 hook 반환 실패로 해석하지 않음
05실행 문맥hook 이름·current thread·CPU 번호·timestampearly lk_main과 bootstrap2를 구별

한 보드에서 순서를 검증하는 방법

  1. 01
    early 내부 호출을 찍는다

    platform_early_init 진입과 GIC·timer·early UART 직후를 계측해 세 작업이 함수 반환 전인지 본다.

  2. 02
    target early와 heap 경계를 찍는다

    target_early_init, heap_init, constructors, kernel_init, thread create/resume 순서를 같은 로그 축에 둔다.

  3. 03
    bootstrap2의 thread·CPU를 확인한다

    CPU 0에 고정해 resume한 thread에서 arch_init → platform_init → target_init → apps_init 순서를 기록하고 lk_main의 idle 전환과 구분한다.

  4. 04
    조건부 로그를 분리한다

    FDT walk/PSCI 오류와 PCI ECAM 분기를 기록해, hook 자체의 반환과 내부 fallback·log 동작을 혼동하지 않는다.

원문과 다음 글