읽는 지도
scheduler는 runnable entity를 시간, priority, capacity, energy, isolation constraint에 매핑하는 정책 기계다. 한 함수가 맞는지만 보면 안 되고, enqueue/dequeue/update/pick/migrate 사이의 conservation law를 봐야 한다.
함수 이름보다 입력 객체와 출력 객체를 먼저 본다. 이 토픽에서 어떤 구조체가 생성, 연결, publish, retire되는지 표시한다.
정상 경로와 실패 경로를 같은 무게로 본다. kernel code의 품질은 성공 path보다 error unwind, hotplug, teardown에서 더 잘 드러난다.
왼쪽은 입력 또는 상위 계층이고, 오른쪽으로 갈수록 실제 상태 변경이 커진다. 문C식으로 읽을 때는 이 그림을 먼저 머리에 놓고 코드 조각을 끼워 넣는다.
원본 코드 좌표
Linux 6.18.37 LTS에서 열 파일
Linux 6.18.37 LTS: kernel/sched/fair.c
Linux 6.18.37 LTS: kernel/sched/topology.c
Linux 6.18.37 LTS: kernel/sched/sched.h
설명: 첫 파일은 보통 진입 함수가 있는 곳이고, 나머지는 구조체 정의, architecture glue, callback 구현을 확인할 때 같이 연다. 파일을 여러 개 놓고 봐야 이 토픽의 boundary가 보인다.
대표 코드
load_balance
hrtick_update(rq);
}
#ifdef CONFIG_SMP
/* Working cpumask for: load_balance, load_balance_newidle. */
static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask);
static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask);
#ifdef CONFIG_NO_HZ_COMMON
static struct {
cpumask_var_t idle_cpus_mask;
atomic_t nr_cpus;
int has_blocked; /* Idle CPUS has blocked load */
int needs_update; /* Newly idle CPUs need their next_balance collated */
unsigned long next_balance; /* in jiffy units */
unsigned long next_blocked; /* Next update of blocked load in jiffies */
} nohz ____cacheline_aligned;
#endif /* CONFIG_NO_HZ_COMMON */
static unsigned long cpu_load(struct rq *rq)
{
return cfs_rq_load_avg(&rq->cfs);
}
/*
* cpu_load_without - compute CPU load without any contributions from *p
* @cpu: the CPU which load is requested
* @p: the task which load should be discounted
*
* The load of a CPU is defined by the load of tasks currently enqueued on that
* CPU as well as tasks which are currently sleeping after an execution on that
* CPU.
*
* This method returns the load of the specified CPU by discounting the load of
* the specified task, whenever the task is currently contributing to the CPU
* load.
읽는 법: 이 절편에서 먼저 볼 것은 return 값이 아니라 상태 변경이다. 어떤 lock을 잡은 뒤 어떤 필드를 바꾸는지, 실패하면 어느 label로 빠지는지, 그리고 바뀐 상태를 다음 호출자가 어떤 전제로 소비하는지 표시한다.
find_busiest_group
if (decayed)
cpufreq_update_util(rq, 0);
rq_unlock_irqrestore(rq, &rf);
}
/********** Helpers for find_busiest_group ************************/
/*
* sg_lb_stats - stats of a sched_group required for load_balancing
*/
struct sg_lb_stats {
unsigned long avg_load; /*Avg load across the CPUs of the group */
unsigned long group_load; /* Total load over the CPUs of the group */
unsigned long group_capacity;
unsigned long group_util; /* Total utilization over the CPUs of the group */
unsigned long group_runnable; /* Total runnable time over the CPUs of the group */
unsigned int sum_nr_running; /* Nr of tasks running in the group */
unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */
unsigned int idle_cpus;
unsigned int group_weight;
enum group_type group_type;
unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */
unsigned int group_smt_balance; /* Task on busy SMT be moved */
unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */
#ifdef CONFIG_NUMA_BALANCING
unsigned int nr_numa_running;
unsigned int nr_preferred_running;
#endif
};
/*
* sd_lb_stats - Structure to store the statistics of a sched_domain
* during load balancing.
*/
struct sd_lb_stats {
struct sched_group *busiest; /* Busiest group in this sd */
struct sched_group *local; /* Local group in this sd */
unsigned long total_load; /* Total load of all groups in sd */
unsigned long total_capacity; /* Total capacity of all groups in sd */
unsigned long avg_load; /* Average load across all groups in sd */
읽는 법: 이 절편에서 먼저 볼 것은 return 값이 아니라 상태 변경이다. 어떤 lock을 잡은 뒤 어떤 필드를 바꾸는지, 실패하면 어느 label로 빠지는지, 그리고 바뀐 상태를 다음 호출자가 어떤 전제로 소비하는지 표시한다.
함수별 독해
CPU 간 runnable load와 capacity 차이를 보고 task migration을 결정하는 scheduler topology 알고리즘이다.
이 섹션은 원본 코드 발췌를 함수 이름 단위로 끊어, 각 함수가 어떤 전제 조건을 만들고 다음 함수가 무엇을 소비하는지 추적한다.
각 노드는 독립 함수가 아니라 전제 조건을 생산하고 소비하는 연결점이다. 코드를 읽을 때는 노드 사이에서 어떤 필드가 바뀌는지 표시한다.
1. load_balance
load_balance 주변에서는 sched_domain를 중심으로 본다. 이 필드는 balance 범위와 flag 역할을 하므로, 함수가 끝날 때 balance triggered 상태가 실제로 성립했는지 확인해야 한다.
원본 코드에서 볼 순서는 입력 범위 검증, 중심 필드 갱신, 다른 계층에 보이는 publish 지점, 실패 시 되돌림 순서다. 이 네 칸이 맞아야 다음 함수가 tick/nohz/idle에서 시작을 전제로 삼을 수 있다.
자주 틀리는 해석: 평균 load만 보고 capacity를 무시함
2. find_busiest_group
find_busiest_group 주변에서는 sched_domain를 중심으로 본다. 이 필드는 balance 범위와 flag 역할을 하므로, 함수가 끝날 때 busiest group found 상태가 실제로 성립했는지 확인해야 한다.
원본 코드에서 볼 순서는 입력 범위 검증, 중심 필드 갱신, 다른 계층에 보이는 publish 지점, 실패 시 되돌림 순서다. 이 네 칸이 맞아야 다음 함수가 imbalance 계산을 전제로 삼을 수 있다.
자주 틀리는 해석: task affinity와 cpuset 제약을 늦게 확인함
| 함수 | 입력 | 상태 변경 | 검증 질문 |
|---|---|---|---|
| load_balance | sched_domain, caller context, subsystem 전제 조건 | balance triggered: tick/nohz/idle에서 시작 | 평균 load만 보고 capacity를 무시함 문제를 코드상 어느 조건문 또는 error label에서 분리하는가 |
| find_busiest_group | sched_domain, caller context, subsystem 전제 조건 | busiest group found: imbalance 계산 | task affinity와 cpuset 제약을 늦게 확인함 문제를 코드상 어느 조건문 또는 error label에서 분리하는가 |
구조체 / 필드 해설
여기서는 “어떤 구조체가 있다”가 아니라 그 필드가 어느 단계에서 쓰기 가능하고 어느 단계부터 관찰 가능한지를 본다. 박사급 리뷰에서는 필드의 뜻보다 보호 규칙이 먼저다.
필드는 구조체 안에 흩어져 있지만, 실제 실행에서는 위 순서로 의미가 이어진다.
| 필드 | 읽는 법 | 확인 |
|---|---|---|
| sched_domain | balance 범위와 flag | 누가 쓰고, 누가 보호하고, 언제 lifetime이 끝나는지 원본 코드에서 확인 |
| sched_group_capacity | CPU capacity 모델 | 누가 쓰고, 누가 보호하고, 언제 lifetime이 끝나는지 원본 코드에서 확인 |
| env | detach/attach migration context | 누가 쓰고, 누가 보호하고, 언제 lifetime이 끝나는지 원본 코드에서 확인 |
| misfit task | capacity 불일치 후보 | 누가 쓰고, 누가 보호하고, 언제 lifetime이 끝나는지 원본 코드에서 확인 |
상태 전이 그림
상태 전이를 따로 그리는 이유는 정상 path와 실패 path를 같은 표에서 보기 위해서다. 커널 regression은 흔히 마지막 상태가 아니라 중간 상태를 외부에 publish한 뒤 rollback하지 못해서 생긴다.
상태 전이는 단방향처럼 그렸지만, 실패 경로에서는 대부분 역순 rollback이 붙는다.
| 상태 | 의미 | 진입 조건 | 깨지는 지점 |
|---|---|---|---|
| balance triggered | tick/nohz/idle에서 시작 | 앞 단계 함수가 전제 조건을 만들고 error path가 정리된 뒤 | 다음 단계가 이 상태를 너무 일찍 소비하거나 늦게 정리할 때 |
| busiest group found | imbalance 계산 | 앞 단계 함수가 전제 조건을 만들고 error path가 정리된 뒤 | 다음 단계가 이 상태를 너무 일찍 소비하거나 늦게 정리할 때 |
| tasks detached | affinity와 load 기준 선택 | 앞 단계 함수가 전제 조건을 만들고 error path가 정리된 뒤 | 다음 단계가 이 상태를 너무 일찍 소비하거나 늦게 정리할 때 |
| tasks attached | target rq로 이동 | 앞 단계 함수가 전제 조건을 만들고 error path가 정리된 뒤 | 다음 단계가 이 상태를 너무 일찍 소비하거나 늦게 정리할 때 |
불변조건 / 실패 케이스
load balancing 의 중심 객체가 publish된 뒤에는 마지막 참조가 사라지기 전까지 teardown path가 모든 callback, timer, IRQ, worker와 경합하지 않아야 한다.
상태 필드를 바꾼 뒤 다른 CPU나 하위 계층이 관찰할 수 있다면 lock, barrier, refcount, RCU 중 어느 장치가 visibility를 보장하는지 확인한다.
중간 단계 실패는 성공 단계의 역순으로 되돌아가야 한다. goto label이 많은 코드는 label 이름보다 어느 resource가 이미 획득됐는지를 표로 적는다.
embedded bring-up에서는 panic보다 silence, timeout, deferred probe, interrupt flood처럼 간접 증상으로 드러나는 경우가 많다.
평균 load만 보고 capacity를 무시함
task affinity와 cpuset 제약을 늦게 확인함
migration cost/cache hotness를 모델 밖으로 밀어냄
계측 / 검증
계측은 printk 위치 경쟁이 아니라 가설 검증이다. 먼저 위 상태표에서 멈춘 state를 정하고, 그 state를 바꾸는 함수와 그 결과를 소비하는 함수를 동시에 본다.
| 도구 | 보는 것 | 해석 |
|---|---|---|
| sched_migrate_task | load balancing 의 상태 전이가 어느 지점에서 멈추는지 확인 | 로그가 찍힌 위치를 완료 시점으로 단정하지 말고, 바로 앞뒤 필드 변경을 원본에서 확인 |
| perf sched map | load balancing 의 상태 전이가 어느 지점에서 멈추는지 확인 | 로그가 찍힌 위치를 완료 시점으로 단정하지 말고, 바로 앞뒤 필드 변경을 원본에서 확인 |
| /proc/sched_debug | load balancing 의 상태 전이가 어느 지점에서 멈추는지 확인 | 로그가 찍힌 위치를 완료 시점으로 단정하지 말고, 바로 앞뒤 필드 변경을 원본에서 확인 |
| trace_sched_load_balance | load balancing 의 상태 전이가 어느 지점에서 멈추는지 확인 | 로그가 찍힌 위치를 완료 시점으로 단정하지 말고, 바로 앞뒤 필드 변경을 원본에서 확인 |
# 예시: 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
연구 질문
- load balancing 의 state machine을 네 단계로 줄였을 때, 실제 코드에서 빠지는 intermediate state는 무엇인가?
- load balancing 의 fast path가 생략한 검사는 어느 init path 또는 slow path에서 보증되는가?
- 실험으로 확인한다면 '평균 load만 보고 capacity를 무시함' 문제를 어떤 tracepoint와 counter로 분리할 수 있는가?
- 실험으로 확인한다면 'task affinity와 cpuset 제약을 늦게 확인함' 문제를 어떤 tracepoint와 counter로 분리할 수 있는가?