← Kernel Series DUJINLABS.COM

IRQ / Time · Linux 6.18.37 LTS · source + diagram note

hrtimer

최신 LTS 기준: kernel.org longterm 6.18.37 기준으로 파일 위치와 링크를 맞춘 원본 코드 분석 노트입니다. high-resolution timer와 clockevent.

전체 흐름

interrupt/time 코드는 비동기 사건을 bounded latency의 kernel execution으로 변환한다. hardirq, softirq, timer callback, kthread가 같은 상태를 만지므로 context별 허용 동작을 먼저 나눠야 한다.

핵심 확인 사항

함수 이름보다 입력 객체와 출력 객체를 먼저 본다. 이 토픽에서 어떤 구조체가 생성, 연결, publish, retire되는지 표시한다.

오류 처리 확인

정상 경로와 실패 경로를 함께 확인한다. 성공 경로뿐 아니라 오류 복구, hotplug, 해제 과정에서 상태가 올바르게 정리되는지 점검한다.

그림 1. hrtimer 이 kernel 안에서 놓이는 위치
device / timerexternal event or clockevent
irqchip / irq_descdomain mapping, masking, flow handler
top halfhardirq handler, no sleep
bottom halfsoftirq, tasklet, threaded IRQ, ksoftirqd

왼쪽에서 오른쪽으로 갈수록 실제 상태 변경이 커진다. 각 코드 조각이 어느 단계에 해당하는지 대조한다.

소스 코드 위치

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

원본 코드:
Linux 6.18.37 LTS: kernel/time/hrtimer.c
Linux 6.18.37 LTS: kernel/time/timer.c
Linux 6.18.37 LTS: include/linux/hrtimer.h

설명: 첫 파일은 보통 진입 함수가 있는 곳이고, 나머지는 구조체 정의, architecture glue, callback 구현을 확인할 때 같이 연다. 파일을 여러 개 놓고 봐야 이 토픽의 boundary가 보인다.

대표 코드

hrtimer_start_range_ns

원본 코드: kernel/time/hrtimer.c, 1210행 부근
	 * cpu_base->*expires_next is only set by hrtimer_reprogram()
	 */
	hrtimer_reprogram(cpu_base->softirq_next_timer, reprogram);
}

static int __hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
				    u64 delta_ns, const enum hrtimer_mode mode,
				    struct hrtimer_clock_base *base)
{
	struct hrtimer_clock_base *new_base;
	bool force_local, first;

	/*
	 * If the timer is on the local cpu base and is the first expiring
	 * timer then this might end up reprogramming the hardware twice
	 * (on removal and on enqueue). To avoid that by prevent the
	 * reprogram on removal, keep the timer local to the current CPU
	 * and enforce reprogramming after it is queued no matter whether
	 * it is the new first expiring timer again or not.
	 */
	force_local = base->cpu_base == this_cpu_ptr(&hrtimer_bases);
	force_local &= base->cpu_base->next_timer == timer;

	/*
	 * Remove an active timer from the queue. In case it is not queued
	 * on the current CPU, make sure that remove_hrtimer() updates the
	 * remote data correctly.
	 *
	 * If it's on the current CPU and the first expiring timer, then
	 * skip reprogramming, keep the timer local and enforce
	 * reprogramming later if it was the first expiring timer.  This
	 * avoids programming the underlying clock event twice (once at
	 * removal and once after enqueue).
	 */
	remove_hrtimer(timer, base, true, force_local);

	if (mode & HRTIMER_MODE_REL)
		tim = ktime_add_safe(tim, base->get_time());

	tim = hrtimer_update_lowres(timer, tim, mode);

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

__hrtimer_run_queues

원본 코드: kernel/time/hrtimer.c, 1715행 부근

	WARN_ON_ONCE(base->running != timer);
	base->running = NULL;
}

static void __hrtimer_run_queues(struct hrtimer_cpu_base *cpu_base, ktime_t now,
				 unsigned long flags, unsigned int active_mask)
{
	struct hrtimer_clock_base *base;
	unsigned int active = cpu_base->active_bases & active_mask;

	for_each_active_base(base, cpu_base, active) {
		struct timerqueue_node *node;
		ktime_t basenow;

		basenow = ktime_add(now, base->offset);

		while ((node = timerqueue_getnext(&base->active))) {
			struct hrtimer *timer;

			timer = container_of(node, struct hrtimer, node);

			/*
			 * The immediate goal for using the softexpires is
			 * minimizing wakeups, not running timers at the
			 * earliest interrupt after their soft expiration.
			 * This allows us to avoid using a Priority Search
			 * Tree, which can answer a stabbing query for
			 * overlapping intervals and instead use the simple
			 * BST we already have.
			 * We don't add extra wakeups by delaying timers that
			 * are right-of a not yet expired timer, because that
			 * timer will have to trigger a wakeup anyway.
			 */
			if (basenow < hrtimer_get_softexpires_tv64(timer))
				break;

			__run_hrtimer(cpu_base, base, timer, &basenow, flags);
			if (active_mask == HRTIMER_ACTIVE_SOFT)
				hrtimer_sync_wait_running(cpu_base, flags);

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

함수별 분석

high-resolution timer를 rb-tree/time ordered queue로 관리해 정확한 wakeup과 callback을 제공한다.

이 섹션은 원본 코드 발췌를 함수 이름 단위로 끊어, 각 함수가 어떤 전제 조건을 만들고 다음 함수가 무엇을 소비하는지 추적한다.

그림 2. hrtimer 함수 체인과 관찰 지점
entrycaller가 넘기는 객체와 context를 확정
hrtimer_start_range_nsqueue에 삽입
__hrtimer_run_queues다음 만료 시각 설정
observable statetracepoint, counter, sysfs/proc에서 확인되는 결과

각 노드는 독립 함수가 아니라 전제 조건을 생산하고 소비하는 연결점이다. 코드를 읽을 때는 노드 사이에서 어떤 필드가 바뀌는지 표시한다.

1. hrtimer_start_range_ns

hrtimer_start_range_ns 주변에서는 hrtimer_cpu_base를 중심으로 본다. 이 필드는 CPU별 timer queues 역할을 하므로, 함수가 끝날 때 timer started 상태가 실제로 성립했는지 확인해야 한다.

원본 코드에서 볼 순서는 입력 범위 검증, 중심 필드 갱신, 다른 계층에 보이는 publish 지점, 실패 시 되돌림 순서다. 이 네 칸이 맞아야 다음 함수가 queue에 삽입을 전제로 삼을 수 있다.

자주 틀리는 해석: timer callback context에서 sleep 가능하다고 봄

2. __hrtimer_run_queues

__hrtimer_run_queues 주변에서는 clock_base를 중심으로 본다. 이 필드는 monotonic/realtime 등 기준 역할을 하므로, 함수가 끝날 때 clockevent programmed 상태가 실제로 성립했는지 확인해야 한다.

원본 코드에서 볼 순서는 입력 범위 검증, 중심 필드 갱신, 다른 계층에 보이는 publish 지점, 실패 시 되돌림 순서다. 이 네 칸이 맞아야 다음 함수가 다음 만료 시각 설정을 전제로 삼을 수 있다.

자주 틀리는 해석: CLOCK_MONOTONIC과 REALTIME 조정 효과를 섞음

함수입력상태 변경검증 질문
hrtimer_start_range_nshrtimer_cpu_base, caller context, subsystem 전제 조건timer started: queue에 삽입timer callback context에서 sleep 가능하다고 봄 문제를 코드상 어느 조건문 또는 error label에서 분리하는가
__hrtimer_run_queuesclock_base, caller context, subsystem 전제 조건clockevent programmed: 다음 만료 시각 설정CLOCK_MONOTONIC과 REALTIME 조정 효과를 섞음 문제를 코드상 어느 조건문 또는 error label에서 분리하는가

구조체와 필드

여기서는 “어떤 구조체가 있다”가 아니라 그 필드가 어느 단계에서 쓰기 가능하고 어느 단계부터 관찰 가능한지를 본다. 필드의 뜻보다 보호 규칙이 먼저다.

그림 3. hrtimer 핵심 필드 연결
hrtimer_cpu_baseCPU별 timer queues
clock_basemonotonic/realtime 등 기준
expires만료 시각
functioncallback pointer

필드는 구조체 안에 흩어져 있지만, 실제 실행에서는 위 순서로 의미가 이어진다.

필드읽는 법확인
hrtimer_cpu_baseCPU별 timer queues누가 쓰고, 누가 보호하고, 언제 lifetime이 끝나는지 원본 코드에서 확인
clock_basemonotonic/realtime 등 기준누가 쓰고, 누가 보호하고, 언제 lifetime이 끝나는지 원본 코드에서 확인
expires만료 시각누가 쓰고, 누가 보호하고, 언제 lifetime이 끝나는지 원본 코드에서 확인
functioncallback pointer누가 쓰고, 누가 보호하고, 언제 lifetime이 끝나는지 원본 코드에서 확인

실행 단계와 상태 변화

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

그림 4. hrtimer 실행 단계
timer startedqueue에 삽입
clockevent programmed다음 만료 시각 설정
interrupt firedexpired timer 실행
callback resultrestart 또는 remove

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

상태의미진입 조건깨지는 지점
timer startedqueue에 삽입앞 단계 함수가 전제 조건을 만들고 error path가 정리된 뒤다음 단계가 이 상태를 너무 일찍 소비하거나 늦게 정리할 때
clockevent programmed다음 만료 시각 설정앞 단계 함수가 전제 조건을 만들고 error path가 정리된 뒤다음 단계가 이 상태를 너무 일찍 소비하거나 늦게 정리할 때
interrupt firedexpired timer 실행앞 단계 함수가 전제 조건을 만들고 error path가 정리된 뒤다음 단계가 이 상태를 너무 일찍 소비하거나 늦게 정리할 때
callback resultrestart 또는 remove앞 단계 함수가 전제 조건을 만들고 error path가 정리된 뒤다음 단계가 이 상태를 너무 일찍 소비하거나 늦게 정리할 때
hrtimer 검토 기준 = 상태 변화 + 소유권 변화 + 외부 공개 시점

불변 조건과 실패 사례

lifetime

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

ordering

상태 필드를 바꾼 뒤 다른 CPU나 하위 계층이 관찰할 수 있다면 lock, barrier, refcount, RCU 중 어느 장치가 visibility를 보장하는지 확인한다.

오류 복구

중간 단계 실패는 성공 단계의 역순으로 되돌아가야 한다. goto label이 많은 코드는 label 이름보다 어느 resource가 이미 획득됐는지를 표로 적는다.

bring-up symptom

embedded bring-up에서는 panic보다 silence, timeout, deferred probe, interrupt flood처럼 간접 증상으로 드러나는 경우가 많다.

주의

timer callback context에서 sleep 가능하다고 봄

주의

CLOCK_MONOTONIC과 REALTIME 조정 효과를 섞음

주의

timer migration과 CPU hotplug를 빼먹음

계측과 검증

계측은 printk 위치 경쟁이 아니라 가설 검증이다. 먼저 위 상태표에서 멈춘 state를 정하고, 그 state를 바꾸는 함수와 그 결과를 소비하는 함수를 동시에 본다.

도구보는 것해석
timer:hrtimer_starthrtimer 실행이 어느 단계에서 멈추는지 확인로그가 찍힌 위치를 완료 시점으로 단정하지 말고, 바로 앞뒤 필드 변경을 원본에서 확인
timer:hrtimer_expire_entryhrtimer 실행이 어느 단계에서 멈추는지 확인로그가 찍힌 위치를 완료 시점으로 단정하지 말고, 바로 앞뒤 필드 변경을 원본에서 확인
ftrace:hrtimer_interrupthrtimer 실행이 어느 단계에서 멈추는지 확인로그가 찍힌 위치를 완료 시점으로 단정하지 말고, 바로 앞뒤 필드 변경을 원본에서 확인
cyclictesthrtimer 실행이 어느 단계에서 멈추는지 확인로그가 찍힌 위치를 완료 시점으로 단정하지 말고, 바로 앞뒤 필드 변경을 원본에서 확인
기본 추적 경로:
# 예시: 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

추가 확인 사항

  • hrtimer 의 state machine을 네 단계로 줄였을 때, 실제 코드에서 빠지는 intermediate state는 무엇인가?
  • hrtimer 의 fast path가 생략한 검사는 어느 init path 또는 slow path에서 보증되는가?
  • 실험으로 확인한다면 'timer callback context에서 sleep 가능하다고 봄' 문제를 어떤 tracepoint와 counter로 분리할 수 있는가?
  • 실험으로 확인한다면 'CLOCK_MONOTONIC과 REALTIME 조정 효과를 섞음' 문제를 어떤 tracepoint와 counter로 분리할 수 있는가?