Barebox · source analysis

Device Tree population과 deep probe

root DT의 node를 platform device로 만들고 필요 시점까지 probe를 늦추는 Barebox 방식을 읽습니다.

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

Series
08 / 19
Baseline
v2026.06.1
Commit
314c679eea2d
Source
drivers/of/platform.c:397-485 (발췌 범위)

Device Tree population과 deep probe 단계에서 실제로 바뀌는 상태는 무엇인가?

node가 존재하는 것, device가 등록된 것, driver probe가 끝난 것을 세 단계로 구분한다. deep-probe 설정은 부팅 시간과 dependency 발견 순서를 바꾼다.

각 device는 원래 DT node와 resource translation 결과를 안정적으로 참조해야 한다. 이 문장을 기준으로 코드를 위에서 아래로 읽으면, 함수 이름을 외우는 대신 어느 시점에 어떤 상태를 신뢰할 수 있는지 판단할 수 있다.

객체와 주소가 놓이는 구조

그림 1. Device Tree population과 deep probe에서 입력, 내부 상태, 출력의 경계
입력과 전제내부 상태외부로 공개되는 결과
01device_node tree
02platform devices
03aliases/resources
04probe policy

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

실행 흐름

그림 2. 정상 경로의 주요 호출과 상태 전달
root DT
node walk
of_device allocation
register_device
deep probe

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

단계별 입력과 출력

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

#단계진입 시 신뢰할 상태성공 뒤 남아야 할 상태다음 소비자
01root DT부트 CPU의 동기 실행 문맥device_node treenode walk
02node walkroot DT 완료 상태platform devicesof_device allocation
03of_device allocationnode walk 완료 상태aliases/resourcesregister_device
04register_deviceof_device allocation 완료 상태probe policydeep probe
05deep proberegister_device 완료 상태probe policy이 단계의 처리 결과를 사용하는 코드

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

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

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

그림 3. DT node가 platform device가 되는 순서

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

01root node
02status 확인
03compatible·bus 판단
04resource translate
05device allocation
06register_device
07deep probe 시점
그림 4. 일반 population과 deep probe

두 열의 객체는 이름이 비슷해도 생성 시점, 사용 가능한 API와 해제 책임이 다르다.

Population

01node를 device로 생성

02driver 미probe 가능

03전체 topology 확보

04초기 비용 발생

05provider 순서 미확정

Deep probe

01필요한 path에서 probe

02dependency를 따라 활성화

03초기 시간 절약

04첫 접근 latency

05compatible 정책 영향

원본 코드

아래 코드는 Barebox v2026.06.1의 drivers/of/platform.c에서 397-485줄을 그대로 가져온 것이다. 설명을 위해 실제 코드를 가짜 의사 코드로 바꾸지 않았다.

commit314c679eea2d0ca847c64d1b646a1cf91225c0ecanchor · L421int of_platform_populate
397		return 0;
398
399	for_each_child_of_node(node, child) {
400		pr_debug("   create child: %pOF\n", child);
401		rc = of_platform_bus_create(child, matches, dev);
402		if (rc)
403			break;
404	}
405	return rc;
406}
407
408/**
409 * of_platform_populate() - Populate platform_devices from device tree data
410 * @root: parent of the first level to probe or NULL for the root of the tree
411 * @matches: match table, NULL to use the default
412 * @parent: parent to hook devices from, NULL for toplevel
413 *
414 * This function walks the device tree given by @root node and creates devices
415 * from nodes.  It requires all device nodes to have a 'compatible' property,
416 * and it is suitable for creating devices which are children of the root
417 * node.
418 *
419 * Returns 0 on success, < 0 on failure.
420 */
421int of_platform_populate(struct device_node *root,
422			const struct of_device_id *matches,
423			struct device *parent)
424{
425	struct device_node *child;
426	int rc = 0;
427
428	if (!root)
429		root = of_find_node_by_path("/");
430	if (!root)
431		return -EINVAL;
432
433	for_each_child_of_node(root, child) {
434		rc = of_platform_bus_create(child, matches, parent);
435		if (rc)
436			break;
437	}
438
439	return rc;
440}
441EXPORT_SYMBOL_GPL(of_platform_populate);
442
443static struct device *of_device_create_on_demand(struct device_node *np)
444{
445	struct device_node *parent;
446	struct device *parent_dev, *dev;
447
448	parent = of_get_parent(np);
449	if (!parent)
450		return NULL;
451
452	if (!np->dev && parent->dev)
453		device_rescan(parent->dev);
454
455	/* Create all parent devices needed for the requested device */
456	parent_dev = parent->dev ? : of_device_create_on_demand(parent);
457	if (IS_ERR(parent_dev))
458		return parent_dev;
459
460	/*
461	 * Parent devices like i2c/spi controllers are populating their own
462	 * devices. So it can be that the requested device already exists after
463	 * the parent device creation.
464	 */
465	if (np->dev)
466		return np->dev;
467
468	if (!of_property_present(np, "compatible"))
469		return NULL;
470
471	pr_debug("Creating device for %pOF\n", np);
472
473	if (of_device_is_compatible(np, "arm,primecell"))
474		dev = of_amba_device_create(np);
475	else
476		dev = of_platform_device_create(np, parent_dev);
477
478	return dev ? : ERR_PTR(-EPROBE_DEFER);
479}
480
481/**
482 * of_device_ensure_probed() - ensures that a device is probed
483 *
484 * @np: the device_node handle which should be probed
485 *

발췌 범위와 읽기 기준

원문 397-485줄에는 앞뒤 문맥이 포함됩니다. 기준 구문 int of_platform_populate은 L421에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.

node가 존재하는 것, device가 등록된 것, driver probe가 끝난 것을 세 단계로 구분한다. deep-probe 설정은 부팅 시간과 dependency 발견 순서를 바꾼다.

함께 읽어야 하는 원본 코드

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

01. DT node에서 resource를 읽어 device를 만드는 함수

drivers/of/platform.c 114-214줄이다.

filedrivers/of/platform.canchor · L124struct device *of_platform_device_create
114}
115
116/**
117 * of_platform_device_create - Alloc, initialize and register an of_device
118 * @np: pointer to node to create device for
119 * @parent: device model parent device.
120 *
121 * Returns pointer to created platform device, or NULL if a device was not
122 * registered. Unavailable devices will not get registered.
123 */
124struct device *of_platform_device_create(struct device_node *np,
125						struct device *parent)
126{
127	struct device *dev;
128	struct resource *res = NULL, temp_res;
129	resource_size_t resinval;
130	int i, ret, num_reg = 0;
131	u32 virt;
132
133	if (!of_device_is_available(np))
134		return NULL;
135
136	/*
137	 * Linux uses the OF_POPULATED flag to skip already populated/created
138	 * devices.
139	 */
140	if (np->dev) {
141		device_rescan(np->dev);
142		return np->dev;
143	}
144
145	/* count the io resources */
146	if (of_can_translate_address(np))
147		while (of_address_to_resource(np, num_reg, &temp_res) == 0)
148			num_reg++;
149
150	/* Populate the resource table */
151	if (num_reg) {
152		res = xzalloc(sizeof(*res) * num_reg);
153		for (i = 0; i < num_reg; i++) {
154			ret = of_address_to_resource(np, i, &res[i]);
155			if (ret) {
156				free(res);
157				return NULL;
158			}
159		}
160	}
161
162	/* setup generic device info */
163	dev = xzalloc(sizeof(*dev));
164	dev->id = DEVICE_ID_SINGLE;
165	dev->of_node = np;
166	dev->parent = parent;
167	dev->resource = res;
168	dev->num_resources = num_reg;
169	of_device_make_bus_id(dev);
170
171	of_dma_configure(dev, np);
172
173	if (num_reg && !of_property_read_u32(np, "virtual-reg", &virt)) {
174		resource_size_t remap_offset = virt - res[0].start;
175
176		for (i = 0; i < num_reg; i++) {
177			void *new_virt = (void *)res[i].start + remap_offset;
178			resource_size_t size = resource_size(&res[i]);
179
180			ret = arch_remap_range(new_virt, res[i].start, size, MAP_UNCACHED);
181			if (!ret) {
182				debug("%s: remap device %s resource %d: %pa -> 0x%p\n",
183				      __func__, dev_name(dev), i, &res[i].start, new_virt);
184
185				res[i].start = (resource_size_t)new_virt;
186				res[i].end = res[i].start + size - 1;
187			}
188		}
189	}
190
191	resinval = (-1);
192
193	debug("%s: register device %s, io=%pa\n",
194			__func__, dev_name(dev),
195		(num_reg) ? &dev->resource[0].start : &resinval);
196
197	BUG_ON(np->dev);
198	np->dev = dev;
199
200	ret = platform_device_register(dev);
201	if (ret) {
202		np->dev = NULL;
203		free_device(dev);
204		if (num_reg)
205			free(res);
206		return NULL;
207	}
208
209
210	return dev;
211}
212
213struct driver dummy_driver = {
214	.name = "dummy-driver",

내부 동작을 더 깊게 읽기

01

진입 조건을 먼저 고정한다

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

node가 존재하는 것, device가 등록된 것, driver probe가 끝난 것을 세 단계로 구분한다. deep-probe 설정은 부팅 시간과 dependency 발견 순서를 바꾼다.

02

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

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

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

03

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

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

04

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

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

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

05

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

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

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

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

01

DT node, device 등록, probe 완료는 서로 다른 상태다

population은 enabled node를 순회해 device와 resource를 만들지만 compatible driver가 없을 수 있고 deep probe가 활성화되면 실제 probe는 사용 시점까지 늦춰진다. of_dump, devinfo, drvinfo를 같은 node path로 대조한다.

node 수만 비교하지 말고 translated resource와 parent bus를 확인한다.

02

ranges와 cell 수가 child 주소의 의미를 바꾼다

각 bus의 #address-cells, #size-cells, ranges를 따라 physical resource를 계산한다. 중간 bus 하나의 cell 해석이 틀리면 child device는 존재해도 엉뚱한 MMIO를 접근한다.

대표 node의 raw cells와 최종 resource start/end를 손으로 계산한다.

03

deep probe는 boot time과 오류 시점을 바꾼다

필요 장치만 늦게 probe하면 부팅은 빨라지지만 dependency 오류가 boot entry 실행 시점에 나타난다. compatible allow-list와 provider chain이 충분한지 확인한다.

deep probe 설정 전후 전체 probe 수, boot target 접근 latency와 실패 위치를 기록한다.

객체와 수명

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

실패 지점과 증상

#조건관찰되는 증상먼저 볼 단계
01ranges 해석 오류잘못된 MMIOnode walk
02disabled node 등록불필요 probeof_device allocation
03deep probe 누락boot target 접근 시 device 없음register_device

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

소스 밖에서 확인할 증거

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

#목적명령 또는 계측판정 기준
01빌드 구성make <board>_defconfig && make V=1Kconfig, linker section과 최종 barebox image 생성 명령을 보관한다.
02symbol과 section${CROSS_COMPILE}nm -n barebox | grep 'int of_platform_populate'initcall, command, driver descriptor가 image에 남았는지 확인한다.
03주소와 resourceiomemimage, malloc, stack, device resource와 reserved 영역의 겹침을 확인한다.
04device 상태devinfo; drvinfo; of_dumpDT node 생성, device 등록, driver probe를 서로 구분한다.
05boot 정책boot -d -v; state -dentry 탐색 결과와 persistent state가 실제 선택에 미친 영향을 확인한다.

직접 확인할 실험

  1. 01
    of_dump와 devinfo node 수 비교

    node walk 진입 전후에 device_node tree의 주소·크기·반환값과 timestamp를 함께 남긴다.

  2. 02
    deep-probe compatible 목록 변경 전후 시간 측정

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

  3. 03
    ranges가 있는 bus의 translated resource 확인

    register_device 진입 전후에 aliases/resources의 주소·크기·반환값과 timestamp를 함께 남긴다.

원문과 다음 글