Barebox · source analysis

register_device와 device tree 객체

device 등록 중 전역·버스·부모 목록 연결과 동기 driver match의 순서를 읽습니다.

Series
06 / 19
Baseline
v2026.06.1
Commit
314c679eea2d
Source
drivers/base/driver.c:220-308 (발췌 범위)

등록은 언제 공개되고 언제 probe를 시도하는가?

register_device()는 이름 충돌을 검사한 뒤 전역 device 목록에 객체를 넣는다. bus가 있으면 버스 목록에 넣고 기존 드라이버마다 match()를 호출한다. 등록 과정 안에서 device_probe()가 바로 실행될 수 있다.

probe 실패가 등록 실패는 아니다. match()는 실패 시 driver 포인터를 비우지만 register_device()는 이후 부모 children 목록에 연결하고 0을 반환한다. 다음 글에서 callback과 defer 분기를 읽는다.

한 객체가 들어가는 세 목록

그림 1. device 객체의 목록 관계
호출자가 준비한 struct devicename/id와 선택적인 bus·parent·of_node·resource. 이 함수는 객체 본체를 할당하지 않는다.
device_list←이름 확인 뒤 연결 · L265
bus 목록←bus가 있을 때 연결 · L276–280
parent children←parent가 있을 때, 매칭 시도 뒤 연결 · L288–289

bus가 있지만 parent가 없으면 bus device가 parent가 된다(L276–278). bus가 없으면 match 루프가 생략된다.

register_device 내부의 실행 순서

그림 2. 전역 공개와 동기 probe
이름·id 확인동적 id 할당 또는 중복 검사 · L248–256
전역 목록 연결unique_name·내부 목록·bobject 초기화 · L258–274
bus가 있으면bus 목록 → 기존 driver별 match → probe · L276–286
parent가 있으면children 연결 → 등록 함수 0 반환 · L288–291

DT population과 device allocation은 호출자에 따라 다르며 register_device 내부의 필수 선행 단계가 아니다.

단계별 상태와 반환값

단계고정 소스상태 변화 / 반환
이름 검사L248–261중복이면 목록 변경 전 -EINVAL. 필요 시 unique_name 생성.
전역 공개L265–274device_list 연결, 내부 목록 초기화, bobject·pinctrl 소비자 등록.
버스 분기L276–286 · 조건부bus 목록 연결, 기존 driver 순회. match 성공은 probe 성공을 포함.
부모 분기L288–291 · 조건부children 연결. probe 결과와 별개로 등록 함수는 0 반환.

조건부 매칭과 객체 수명

그림 3. match 결과와 등록 결과는 다르다
NO BUS전역 목록만bus가 없으면 driver match를 시도하지 않는다.
NO MATCH등록 유지후보 driver가 맞지 않으면 다음 후보를 본다.
PROBE ERROR등록 유지match는 dev->driver를 NULL로 되돌리고 -1을 반환한다.
PROBE SUCCESSdriver 결합성공 후보에서 순회를 멈춘다. parent 연결은 그 뒤다.

등록 반환값 0은 probe 성공의 증거가 아니다. driver가 나중에 등록되면 register_driver()가 기존 bus device를 순회한다(L430–447).

그림 4. 등록과 해제의 소유권 경계
REGISTER객체는 호출자 소유register_device는 전달된 포인터를 목록에 연결한다.
UNREGISTER연결 해제bound device면 remove, children 재귀 해제 뒤 목록을 분리한다(L295–343).
FREE MEMBERSfree_device_resdevinfo, unique_name, deferred 이유를 정리한다(L354–361).
FREE OBJECTfree_devicefree_device_res 뒤 객체 본체를 free한다(L371–375).

unregister_device가 임의 resource 배열 또는 device 본체까지 자동으로 free한다고 가정하지 않는다.

원본 코드

아래 코드는 Barebox v2026.06.1의 drivers/base/driver.c에서 220-308줄을 그대로 가져온 것이다.

commit314c679eea2d0ca847c64d1b646a1cf91225c0ecanchor · L244int register_device(struct device *new_device)
220		device_detect(dev);
221}
222
223static int match(struct driver *drv, struct device *dev)
224{
225	int ret;
226
227	if (dev->driver)
228		return -1;
229
230	dev->driver = drv;
231
232	if (!driver_match_device(drv, dev))
233		goto err_out;
234	ret = device_probe(dev);
235	if (ret)
236		goto err_out;
237
238	return 0;
239err_out:
240	dev->driver = NULL;
241	return -1;
242}
243
244int register_device(struct device *new_device)
245{
246	struct driver *drv;
247
248	if (new_device->id == DEVICE_ID_DYNAMIC) {
249		new_device->id = get_free_deviceid(new_device->name);
250	} else {
251		if (get_device_by_name_id(new_device->name, new_device->id)) {
252			pr_err("register_device: already registered %s\n",
253				dev_name(new_device));
254			return -EINVAL;
255		}
256	}
257
258	if (new_device->id != DEVICE_ID_SINGLE)
259		new_device->unique_name = basprintf(FORMAT_DRIVER_NAME_ID,
260						    new_device->name,
261						    new_device->id);
262
263	debug ("register_device: %s\n", dev_name(new_device));
264
265	list_add_tail(&new_device->list, &device_list);
266	INIT_LIST_HEAD(&new_device->children);
267	INIT_LIST_HEAD(&new_device->cdevs);
268	INIT_LIST_HEAD(&new_device->active);
269	INIT_LIST_HEAD(&new_device->bus_list);
270	INIT_LIST_HEAD(&new_device->class_list);
271
272	bobject_init(&new_device->bobject);
273
274	of_pinctrl_register_consumer(new_device, new_device->device_node);
275
276	if (new_device->bus) {
277		if (!new_device->parent)
278			new_device->parent = &new_device->bus->dev;
279
280		list_add_tail(&new_device->bus_list, &new_device->bus->device_list);
281
282		bus_for_each_driver(new_device->bus, drv) {
283			if (!match(drv, new_device))
284				break;
285		}
286	}
287
288	if (new_device->parent)
289		list_add_tail(&new_device->sibling, &new_device->parent->children);
290
291	return 0;
292}
293EXPORT_SYMBOL(register_device);
294
295int unregister_device(struct device *old_dev)
296{
297	struct device_alias *alias, *at;
298	struct cdev *cdev, *ct;
299	struct device *child, *dt;
300	struct device_node *np;
301
302	dev_dbg(old_dev, "unregister\n");
303
304	bobject_del(&old_dev->bobject);
305
306	of_pinctrl_unregister_consumer(old_dev);
307
308	if (old_dev->driver)

발췌 범위와 읽기 기준

원본 코드 220–308줄에는 match() L223–242, register_device() L244–292와 unregister_device() 앞부분이 함께 있다. 보충 발췌 285–367줄에서 해제 경계를 확인한다.

driver_match_device()는 bus의 match callback이 있으면 호출하고 없으면 참을 반환한다(driver.h L344–348). 플랫폼 버스는 device_match를 쓴다(platform.c L40–44).

unregister_device()는 L341에서 free_device_res()를 호출한다. 목록만 분리하고 모든 동적 멤버를 그대로 두는 것은 아니다. 임의 resource 배열과 객체 본체의 소유권은 별도로 확인한다.

함께 읽어야 하는 원본 코드

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

01. device list와 child 관계를 풀어내는 unregister_device

drivers/base/driver.c 285-367줄이다.

filedrivers/base/driver.canchor · L295int unregister_device(struct device *old_dev)
285		}
286	}
287
288	if (new_device->parent)
289		list_add_tail(&new_device->sibling, &new_device->parent->children);
290
291	return 0;
292}
293EXPORT_SYMBOL(register_device);
294
295int unregister_device(struct device *old_dev)
296{
297	struct device_alias *alias, *at;
298	struct cdev *cdev, *ct;
299	struct device *child, *dt;
300	struct device_node *np;
301
302	dev_dbg(old_dev, "unregister\n");
303
304	bobject_del(&old_dev->bobject);
305
306	of_pinctrl_unregister_consumer(old_dev);
307
308	if (old_dev->driver)
309		device_remove(old_dev);
310
311	list_for_each_entry_safe(alias, at, &device_alias_list, list) {
312		if(alias->dev == old_dev)
313			list_del(&alias->list);
314	}
315
316	list_for_each_entry_safe(child, dt, &old_dev->children, sibling) {
317		dev_dbg(old_dev, "unregister child %s\n", dev_name(child));
318		unregister_device(child);
319	}
320
321	list_for_each_entry_safe(cdev, ct, &old_dev->cdevs, devices_list) {
322		if (cdev_is_partition(cdev)) {
323			dev_dbg(old_dev, "unregister part %s\n", cdev->name);
324			cdevfs_del_partition(cdev);
325		}
326	}
327
328	list_del(&old_dev->list);
329	list_del(&old_dev->bus_list);
330	list_del(&old_dev->class_list);
331	list_del(&old_dev->active);
332
333	/* remove device from parents child list */
334	if (old_dev->parent)
335		list_del(&old_dev->sibling);
336
337	np = dev_of_node(old_dev);
338	if (np && np->dev == old_dev)
339		np->dev = NULL;
340
341	free_device_res(old_dev);
342
343	return 0;
344}
345EXPORT_SYMBOL(unregister_device);
346
347/**
348 * free_device_res - free dynamically allocated device members
349 * @dev: The device
350 *
351 * This frees dynamically allocated resources allocated during device
352 * lifetime, but not the device itself.
353 */
354void free_device_res(struct device *dev)
355{
356	devinfo_del(dev, NULL);
357	free(dev->unique_name);
358	dev->unique_name = NULL;
359	free(dev->deferred_probe_reason);
360	dev->deferred_probe_reason = NULL;
361}
362EXPORT_SYMBOL(free_device_res);
363
364/**
365 * free_device - free a device
366 * @dev: The device
367 *

코드가 보장하는 등록 경계

01

중복 검사는 공개 전

DEVICE_ID_DYNAMIC은 빈 번호를 고르고, 그 외에는 동일 name/id를 찾으면 -EINVAL로 목록 연결 전에 끝낸다(L248–256).

02

전역 공개가 match보다 빠름

device_list 연결은 L265, bus driver 순회는 L282–285다. 매칭과 probe callback은 등록 호출 안에서 실행될 수 있다.

03

parent 연결은 match 뒤

parent가 없고 bus가 있으면 bus device를 parent로 지정한다. parent children 목록 연결은 매칭 루프 뒤 L288–289다.

등록·매칭·해제의 교차점

01

device/driver 등록 양쪽에서 match

device가 먼저 오면 register_device의 bus driver 루프가, driver가 나중에 오면 register_driver의 bus device 루프가 match를 호출한다(L282–285, L430–447).

02

match 실패는 driver 포인터를 되돌림

match는 후보를 dev->driver에 넣고 bus match와 probe를 시도한다. 실패하면 NULL로 되돌리고 -1을 반환한다(L230–241). 등록 객체를 자동 해제하지 않는다.

03

해제와 메모리 free는 별개

unregister_device는 remove·child 재귀 호출·목록 분리 뒤 free_device_res를 직접 호출한다(L295–343). unique_name과 deferred 이유는 이 경로에서 정리되지만 객체 본체는 해제하지 않는다. free_device는 free_device_res 뒤 본체까지 free하는 별도 함수다(L354–375).

객체와 목록의 수명

대상등록 중 변화해제 경계
struct device호출자가 전달; 본체를 할당하지 않음unregister 후 할당 방식에 따라 free_device 여부 결정
device_listL265에서 연결unregister_device L328에서 분리
bus / parent 목록bus가 있으면 L280, parent가 있으면 L289unregister_device L329 및 L334–335에서 분리
unique_namesingle id가 아니면 L258–261에서 할당free_device_res L357–358에서 해제

등록 오류와 probe 오류 구분

조건고정 소스 결과확인 지점
중복 name/idL251–255에서 -EINVAL; 목록 연결 전register_device 반환
bus match 불일치driver 포인터를 비우고 다음 후보; 등록 유지match L223–242
probe 오류 / defermatch에서 driver 포인터를 비움; 일반 defer는 별도 목록 가능device_probe L152–180
객체 수명 오류포인터만 목록에 연결하므로 stack 객체는 dangling 위험호출자 할당·해제

오류 뒤 callback에서 만든 child, cdev, enabled clock의 정리를 register_device가 일괄 보장하지 않는다. 해당 callback 실패 경로를 별도로 확인한다.

빌드와 기기에서 볼 증거

목적읽기 전용 확인판정
심벌${CROSS_COMPILE}nm -n barebox | grep -E ' (register_device|device_probe)$'nm은 C 선언문이 아니라 심벌 이름을 출력한다.
등록과 결합devinfo; drvinfo등록 device와 bound driver를 나누어 본다.
DT 관계of_dumpDT node와 실제 device 등록을 동일시하지 않는다.

재현 가능한 관찰

  1. 01
    이름 충돌과 목록 불변

    동일 name/id 등록의 -EINVAL 반환 전후 device 목록 항목 수를 비교한다.

  2. 02
    bus 유무에 따른 match

    등록 전후 dev->bus·dev->driver·버스 목록과 등록 반환값을 함께 기록한다.

  3. 03
    parent 연결 시점

    probe callback 안의 parent pointer와 parent children 목록을 각각 기록한다.

원문과 다음 글