LK · source analysis

platform과 target 초기화 경계

SoC 공통 platform 코드와 보드 정책인 target 코드가 어디서 나뉘는지 QEMU ARM 예로 읽습니다.

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

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

platform과 target 초기화 경계 단계에서 실제로 바뀌는 상태는 무엇인가?

platform은 재사용 가능한 SoC/IP 초기화를, target은 보드 wiring과 제품 정책을 담는 것이 기본이다. 서로의 전역 심볼을 직접 침범하는 곳을 찾는다.

early init에서 사용하는 UART, interrupt controller와 timer의 물리 주소는 target memory map과 일치해야 한다. 이 문장을 기준으로 코드를 위에서 아래로 읽으면, 함수 이름을 외우는 대신 어느 시점에 어떤 상태를 신뢰할 수 있는지 판단할 수 있다.

객체와 주소가 놓이는 구조

그림 1. platform과 target 초기화 경계에서 입력, 내부 상태, 출력의 경계
입력과 전제내부 상태외부로 공개되는 결과
01architecture layer
02SoC platform
03board target
04app policy

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

실행 흐름

그림 2. 정상 경로의 주요 호출과 상태 전달
arch init
platform_early_init
GIC/timer/UART
target_init
applications

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

단계별 입력과 출력

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

#단계진입 시 신뢰할 상태성공 뒤 남아야 할 상태다음 소비자
01arch init부트 CPU의 동기 실행 문맥architecture layerplatform_early_init
02platform_early_initarch init 완료 상태SoC platformGIC/timer/UART
03GIC/timer/UARTplatform_early_init 완료 상태board targettarget_init
04target_initGIC/timer/UART 완료 상태app policyapplications
05applicationstarget_init 완료 상태app policy이 단계의 처리 결과를 사용하는 코드

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

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

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

그림 3. architecture·platform·target 초기화 책임의 연결

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

01arch generic
02platform SoC
03target board
04driver/resource 등록
05app policy
06runtime service
그림 4. 각 계층이 제공하고 소비하는 정보

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

01archexception·MMU primitiveplatform
02platformtimer·interrupt·UARTkernel services
03targetboard GPIO·storageapps
04projectmodule selectionlink graph
05device tree/configresource addressdrivers

원본 코드

아래 코드는 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에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.

platform은 재사용 가능한 SoC/IP 초기화를, target은 보드 wiring과 제품 정책을 담는 것이 기본이다. 서로의 전역 심볼을 직접 침범하는 곳을 찾는다.

함께 읽어야 하는 원본 코드

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

01. early 단계 이후 device와 interrupt를 여는 platform_init

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    }

내부 동작을 더 깊게 읽기

01

진입 조건을 먼저 고정한다

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

platform은 재사용 가능한 SoC/IP 초기화를, target은 보드 wiring과 제품 정책을 담는 것이 기본이다. 서로의 전역 심볼을 직접 침범하는 곳을 찾는다.

02

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

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

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

03

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

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

04

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

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

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

05

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

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

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

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

01

platform은 SoC, target은 제품 조립을 담당한다

platform layer는 timer, interrupt controller, UART, MMU 같은 SoC 공통 hardware를 초기화하고 target은 board pin, storage layout와 제품 정책을 연결한다. target code가 다른 platform private symbol을 직접 참조하면 재사용 경계가 무너진다.

동일 SoC 여러 board의 차이가 target에 머무는지 build dependency로 확인한다.

02

early와 normal callback의 허용 기능이 다르다

early callback은 heap, scheduler, interrupt가 없을 수 있어 polling과 static storage만 사용해야 한다. normal callback은 core subsystem 준비 뒤 실행되지만 app보다 앞서야 하는 provider를 공개한다.

각 callback 진입에서 available-service bitmap이나 assertion을 두면 잘못된 API 사용을 빠르게 찾을 수 있다.

03

초기화 실패 전달 방식을 제품 정책으로 정한다

platform callback이 void이고 hardware failure를 log만 남기면 target과 app이 없는 장치를 계속 사용한다. 필수 장치는 panic, optional 장치는 capability flag를 내려 consumer가 건너뛰게 해야 한다.

board variant별 probe 결과와 target 선택값을 boot log 첫 부분에 고정해 잘못된 image 배포를 구분한다.

객체와 수명

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

실패 지점과 증상

#조건관찰되는 증상먼저 볼 단계
01platform/target 조합 오류잘못된 MMIOplatform_early_init
02timer 이전 IRQ enableinterrupt stormGIC/timer/UART
03UART clock 오류로그 해석 불가target_init

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

소스 밖에서 확인할 증거

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

#목적명령 또는 계측판정 기준
01빌드 구성make <project> -j1platform, target, app 선택과 linker 입력을 로그로 남긴다.
02symbol과 주소nm -n build-*/lk.elf | grep 'void platform_early_init'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
    QEMU device tree와 platform MMIO 상수 비교

    platform_early_init 진입 전후에 architecture layer의 주소·크기·반환값과 timestamp를 함께 남긴다.

  2. 02
    target만 바꾼 build의 module diff

    GIC/timer/UART 진입 전후에 SoC platform의 주소·크기·반환값과 timestamp를 함께 남긴다.

  3. 03
    각 init 뒤 MMIO readback 기록

    target_init 진입 전후에 board target의 주소·크기·반환값과 timestamp를 함께 남긴다.

원문과 다음 글