Driver / Device · Linux 6.18.37 LTS · source + diagram note

platform driver

기존 코드 발췌를 읽으실 때

기존 platform_get_resource 대표 발췌가 platform 버스 객체 초기화에서 시작해 함수 제목과 맞지 않습니다. 기존 글은 보존했으며, 새 개념 설명에는 버전과 범위를 대조한 원문을 실었습니다.

최신 LTS 기준: kernel.org longterm 6.18.37 기준으로 파일 위치와 링크를 맞춘 원본 코드 분석 노트입니다. probe, resource, irq, regmap.

전체 흐름

driver/device 코드는 abstract device model을 concrete register programming sequence로 연결한다. probe가 호출된다는 사실보다 probe가 호출될 수 있는 dependency graph를 먼저 읽어야 한다.

핵심 확인 사항

함수의 입력과 처리 결과를 먼저 확인한다. 구조체를 생성하고 연결하는 시점, 다른 코드에서 사용할 수 있게 하는 시점, 더 이상 사용하지 않아 회수하는 시점을 구분한다.

오류 처리 확인

정상 처리와 오류 처리를 함께 확인한다. 오류 복구, 장치의 실행 중 연결·분리(hotplug), 자원 해제 과정에서도 상태가 올바르게 정리되는지 점검한다.

그림 1. platform driver 이 kernel 안에서 놓이는 위치
firmware descriptionDT/ACPI node, resources, compatible
→
driver corebus, device, driver, match
→
probeclk/reset/regulator/irq/mmio
→
runtimePM, IRQ handler, remove/shutdown

왼쪽부터 처리 단계를 나열했다. 각 코드 조각에서 바뀌는 상태를 해당 단계와 대조한다.

소스 코드 위치

먼저 확인할 Linux 6.18.37 LTS 소스 파일

원본 코드:
Linux 6.18.37 LTS: drivers/base/platform.c
Linux 6.18.37 LTS: drivers/base/dd.c
Linux 6.18.37 LTS: include/linux/platform_device.h

설명: 진입 함수가 있는 파일과 구조체 정의, 아키텍처별 연결 코드, 콜백 구현을 함께 확인한다. 여러 파일을 대조해야 호출 관계와 각 코드의 역할을 알 수 있다.

대표 코드

platform_driver_probe

원본 코드: drivers/base/platform.c, 889행 부근
		return 1;
	return 0;
}

/**
 * __platform_driver_probe - register driver for non-hotpluggable device
 * @drv: platform driver structure
 * @probe: the driver probe routine, probably from an __init section
 * @module: module which will be the owner of the driver
 *
 * Use this instead of platform_driver_register() when you know the device
 * is not hotpluggable and has already been registered, and you want to
 * remove its run-once probe() infrastructure from memory after the driver
 * has bound to the device.
 *
 * One typical use for this would be with drivers for controllers integrated
 * into system-on-chip processors, where the controller devices have been
 * configured as part of board setup.
 *
 * Note that this is incompatible with deferred probing.
 *
 * Returns zero if the driver registered and bound to a device, else returns
 * a negative error code and with the driver not registered.
 */
int __init_or_module __platform_driver_probe(struct platform_driver *drv,
		int (*probe)(struct platform_device *), struct module *module)
{
	int retval;

	if (drv->driver.probe_type == PROBE_PREFER_ASYNCHRONOUS) {
		pr_err("%s: drivers registered with %s can not be probed asynchronously\n",
			 drv->driver.name, __func__);
		return -EINVAL;
	}

	/*
	 * We have to run our probes synchronously because we check if
	 * we find any devices to bind to and exit with error if there
	 * are any.
	 */

확인 사항: 이 코드에서는 반환값보다 상태 변경을 먼저 확인한다. 어느 잠금을 획득한 뒤 어떤 필드를 바꾸는지, 실패 시 어느 레이블로 분기하는지, 변경된 상태를 다음 호출자가 어떤 전제로 사용하는지 추적한다.

platform_get_resource

원본 코드: drivers/base/platform.c, 43행 부근
	.init_name	= "platform",
};
EXPORT_SYMBOL_GPL(platform_bus);

/**
 * platform_get_resource - get a resource for a device
 * @dev: platform device
 * @type: resource type
 * @num: resource index
 *
 * Return: a pointer to the resource or NULL on failure.
 */
struct resource *platform_get_resource(struct platform_device *dev,
				       unsigned int type, unsigned int num)
{
	u32 i;

	for (i = 0; i < dev->num_resources; i++) {
		struct resource *r = &dev->resource[i];

		if (type == resource_type(r) && num-- == 0)
			return r;
	}
	return NULL;
}
EXPORT_SYMBOL_GPL(platform_get_resource);

struct resource *platform_get_mem_or_io(struct platform_device *dev,
					unsigned int num)
{
	u32 i;

	for (i = 0; i < dev->num_resources; i++) {
		struct resource *r = &dev->resource[i];

		if ((resource_type(r) & (IORESOURCE_MEM|IORESOURCE_IO)) && num-- == 0)
			return r;
	}
	return NULL;
}

확인 사항: 이 코드에서는 반환값보다 상태 변경을 먼저 확인한다. 어느 잠금을 획득한 뒤 어떤 필드를 바꾸는지, 실패 시 어느 레이블로 분기하는지, 변경된 상태를 다음 호출자가 어떤 전제로 사용하는지 추적한다.

함수별 분석

SoC memory-mapped IP driver가 platform_device와 match되어 resource를 얻고 probe에서 hardware를 초기화하는 경로다.

원본 코드를 함수별로 나누어 살펴본다. 각 함수가 준비하는 값과 다음 함수가 그 값을 사용하는 방식을 확인한다.

그림 2. platform driver 함수 체인과 관찰 지점
entrycaller가 넘기는 객체와 context를 확정
→
platform_driver_proberesource 획득과 register programming
→
platform_get_resourcecompatible/name 매칭
→
observable statetracepoint, counter, sysfs/proc에서 확인되는 결과

각 단계의 입력과 처리 결과를 연결해 본다. 다음 단계로 넘어가기 전에 바뀌는 필드를 코드에서 확인한다.

1. platform_driver_probe

platform_driver_probe 주변에서는 platform_driver를 중심으로 본다. 이 필드는 probe/remove callbacks 역할을 하므로, 함수가 끝날 때 probe 상태가 실제로 성립했는지 확인해야 한다.

원본 코드에서 입력 범위 검사, 주요 필드 변경, 다른 계층에서 사용할 수 있게 하는 시점, 실패 시 복구 순서를 확인한다. 이 조건을 만족해야 다음 함수가 resource 획득과 register programming을 전제로 삼을 수 있다.

자주 틀리는 해석: probe가 안 불릴 때 driver 코드만 봄

2. platform_get_resource

platform_get_resource 주변에서는 platform_driver를 중심으로 본다. 이 필드는 probe/remove callbacks 역할을 하므로, 함수가 끝날 때 match 상태가 실제로 성립했는지 확인해야 한다.

원본 코드에서 입력 범위 검사, 주요 필드 변경, 다른 계층에서 사용할 수 있게 하는 시점, 실패 시 복구 순서를 확인한다. 이 조건을 만족해야 다음 함수가 compatible/name 매칭을 전제로 삼을 수 있다.

자주 틀리는 해석: devm을 모든 lifetime race 해결로 오해함

함수입력상태 변경확인할 사항
platform_driver_probeplatform_driver, 호출 시 실행 문맥, 하위 시스템의 준비 조건probe: resource 획득과 register programmingprobe가 안 불릴 때 driver 코드만 봄 문제를 코드상 어느 조건문 또는 error label에서 분리하는가
platform_get_resourceplatform_driver, 호출 시 실행 문맥, 하위 시스템의 준비 조건match: compatible/name 매칭devm을 모든 lifetime race 해결로 오해함 문제를 코드상 어느 조건문 또는 error label에서 분리하는가

구조체와 필드

구조체의 필드를 언제 바꿀 수 있고 다른 코드가 언제 읽을 수 있는지 확인한다. 필드의 의미와 함께 잠금 등 접근을 보호하는 규칙을 살펴본다.

그림 3. platform driver 핵심 필드 연결
platform_deviceresource container
→
platform_driverprobe/remove callbacks
→
struct resourceMMIO/IRQ ranges
→
devm resourcesdevice lifetime-managed allocations

각 단계에서 읽고 쓰는 필드를 구조체 정의와 대조한다.

어떤 코드가 필드를 변경하고 어떤 방식으로 접근을 보호하는지, 객체를 언제 해제하는지 원본 코드에서 확인한다.

필드읽는 법
platform_deviceresource container
platform_driverprobe/remove callbacks
struct resourceMMIO/IRQ ranges
devm resourcesdevice lifetime-managed allocations

실행 단계와 상태 변화

실행 단계를 따로 정리하면 정상 경로와 실패 경로를 나란히 비교할 수 있다. 커널 문제는 최종 결과보다 준비가 덜 된 중간 상태를 다른 코드에 공개한 뒤, 실패 시 제대로 정리하지 못할 때 자주 발생한다.

그림 4. platform driver 실행 단계
device existsDT/board code가 platform_device publish
→
matchcompatible/name 매칭
→
proberesource 획득과 register programming
→
removereverse teardown

화살표는 정상 진행 방향을 나타낸다. 중간 단계에서 실패하면 각 단계의 오류 처리 또는 대체 경로로 이동한다.

상태의미진입 조건깨지는 지점
device existsDT/board code가 platform_device publish앞 단계의 준비와 오류 처리가 끝난 뒤다음 단계가 준비되지 않은 상태를 사용하거나 필요한 정리를 늦출 때
matchcompatible/name 매칭앞 단계의 준비와 오류 처리가 끝난 뒤다음 단계가 준비되지 않은 상태를 사용하거나 필요한 정리를 늦출 때
proberesource 획득과 register programming앞 단계의 준비와 오류 처리가 끝난 뒤다음 단계가 준비되지 않은 상태를 사용하거나 필요한 정리를 늦출 때
removereverse teardown앞 단계의 준비와 오류 처리가 끝난 뒤다음 단계가 준비되지 않은 상태를 사용하거나 필요한 정리를 늦출 때
platform driver 검토 기준 = 상태 변화 + 소유권 변화 + 외부 공개 시점

불변 조건과 실패 사례

lifetime

platform driver의 핵심 객체가 외부에 공개된 뒤에는 마지막 참조가 사라질 때까지 해제 경로가 callback, timer, IRQ, worker와 경합하지 않아야 한다.

ordering

다른 CPU나 하위 계층이 변경된 필드를 읽는다면 잠금과 메모리 배리어가 접근 순서를 어떻게 보장하는지 확인한다. 참조 횟수와 RCU로 관리하는 객체 수명도 별도로 확인한다.

오류 복구

중간 단계에서 실패하면 이미 확보한 자원을 의존 관계에 맞춰 해제해야 한다. goto 레이블이 많다면 각 분기에 도달했을 때 확보한 자원을 표로 정리한다.

bring-up symptom

임베디드 보드를 처음 구동할 때는 패닉 대신 로그 중단, 시간 초과, 장치 초기화 지연, 과도한 인터럽트 같은 증상으로 문제가 드러날 수 있다.

주의

probe가 안 불릴 때 driver 코드만 봄

주의

devm을 모든 lifetime race 해결로 오해함

주의

IRQ enable과 hardware clear ordering을 놓침

계측과 검증

로그를 무작정 추가하지 말고 확인할 가설을 먼저 세운다. 상태표에서 처리가 멈춘 단계를 찾은 뒤, 상태를 바꾸는 함수와 그 결과를 사용하는 함수를 함께 살펴본다.

로그가 출력되었다고 처리가 끝난 것으로 판단하지 않는다. 원본 코드에서 로그 앞뒤의 필드 변경을 확인한다.

도구보는 것
ftrace:really_probeplatform driver 실행이 어느 단계에서 멈추는지 확인
devices_deferredplatform driver 실행이 어느 단계에서 멈추는지 확인
devres debugplatform driver 실행이 어느 단계에서 멈추는지 확인
cat /sys/bus/platform/devicesplatform driver 실행이 어느 단계에서 멈추는지 확인
기본 추적 경로:
# 예시: tracefs가 켜진 보드에서 토픽별 event를 좁혀 본다.
mount -t tracefs nodev /sys/kernel/tracing
echo function_graph > /sys/kernel/tracing/current_tracer
echo ':mod:*' > /sys/kernel/tracing/set_ftrace_filter
cat /sys/kernel/tracing/trace_pipe

추가 확인 사항

  • platform driver 의 state machine을 네 단계로 줄였을 때, 실제 코드에서 빠지는 intermediate state는 무엇인가?
  • platform driver 의 fast path가 생략한 검사는 어느 init path 또는 slow path에서 보증되는가?
  • 실험으로 확인한다면 'probe가 안 불릴 때 driver 코드만 봄' 문제를 어떤 tracepoint와 counter로 분리할 수 있는가?
  • 실험으로 확인한다면 'devm을 모든 lifetime race 해결로 오해함' 문제를 어떤 tracepoint와 counter로 분리할 수 있는가?