전체 흐름
락, RCU, 원자 연산은 여러 실행 흐름이 함께 사용하는 상태의 접근 순서와 객체 수명을 관리한다. lock API를 외우는 것이 아니라 context, memory model, object lifetime을 하나의 그래프로 읽어야 한다.
함수의 입력과 처리 결과를 먼저 확인한다. 구조체를 생성하고 연결하는 시점, 다른 코드에서 사용할 수 있게 하는 시점, 더 이상 사용하지 않아 회수하는 시점을 구분한다.
정상 처리와 오류 처리를 함께 확인한다. 오류 복구, 장치의 실행 중 연결·분리(hotplug), 자원 해제 과정에서도 상태가 올바르게 정리되는지 점검한다.
왼쪽부터 처리 단계를 나열했다. 각 코드 조각에서 바뀌는 상태를 해당 단계와 대조한다.
소스 코드 위치
먼저 확인할 Linux 6.18.37 LTS 소스 파일
Linux 6.18.37 LTS: kernel/locking/lockdep.c
Linux 6.18.37 LTS: include/linux/lockdep.h
Linux 6.18.37 LTS: kernel/locking/lockdep_proc.c
설명: 진입 함수가 있는 파일과 구조체 정의, 아키텍처별 연결 코드, 콜백 구현을 함께 확인한다. 여러 파일을 대조해야 호출 관계와 각 코드의 역할을 알 수 있다.
대표 코드
lockdep_init
void __init lockdep_init(void)
{
pr_info("Lock dependency validator: Copyright (c) 2006 Red Hat, Inc., Ingo Molnar\n");
pr_info("... MAX_LOCKDEP_SUBCLASSES: %lu\n", MAX_LOCKDEP_SUBCLASSES);
pr_info("... MAX_LOCK_DEPTH: %lu\n", MAX_LOCK_DEPTH);
pr_info("... MAX_LOCKDEP_KEYS: %lu\n", MAX_LOCKDEP_KEYS);
pr_info("... CLASSHASH_SIZE: %lu\n", CLASSHASH_SIZE);
pr_info("... MAX_LOCKDEP_ENTRIES: %lu\n", MAX_LOCKDEP_ENTRIES);
pr_info("... MAX_LOCKDEP_CHAINS: %lu\n", MAX_LOCKDEP_CHAINS);
pr_info("... CHAINHASH_SIZE: %lu\n", CHAINHASH_SIZE);
pr_info(" memory used by lock dependency info: %zu kB\n",
(sizeof(lock_classes) +
sizeof(lock_classes_in_use) +
sizeof(classhash_table) +
sizeof(list_entries) +
sizeof(list_entries_in_use) +
sizeof(chainhash_table) +
sizeof(delayed_free)
#ifdef CONFIG_PROVE_LOCKING
+ sizeof(lock_cq)
+ sizeof(lock_chains)
+ sizeof(lock_chains_in_use)
+ sizeof(chain_hlocks)
#endif
) / 1024
);
#if defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING)
pr_info(" memory used for stack traces: %zu kB\n",
(sizeof(stack_trace) + sizeof(stack_trace_hash)) / 1024
);
#endif
pr_info(" per task-struct memory footprint: %zu bytes\n",
sizeof(((struct task_struct *)NULL)->held_locks));
}
lockdep_init_task()와 lockdep_init()은 다른 함수다. 아래는 전역 초기화 진입점의 실제 본문이며, 이 버전에서 출력하는 크기·설정 정보를 볼 수 있다. task별 held_locks 초기화나 전체 의존성 그래프 구축을 이 발췌가 수행한다고 해석하지 않는다.
__lock_acquire
__lock_acquire 함수 전체 (194줄)
static int __lock_acquire(struct lockdep_map *lock, unsigned int subclass,
int trylock, int read, int check, int hardirqs_off,
struct lockdep_map *nest_lock, unsigned long ip,
int references, int pin_count, int sync)
{
struct task_struct *curr = current;
struct lock_class *class = NULL;
struct held_lock *hlock;
unsigned int depth;
int chain_head = 0;
int class_idx;
u64 chain_key;
if (unlikely(!debug_locks))
return 0;
if (unlikely(lock->key == &__lockdep_no_track__))
return 0;
lockevent_inc(lockdep_acquire);
if (!prove_locking || lock->key == &__lockdep_no_validate__) {
check = 0;
lockevent_inc(lockdep_nocheck);
}
if (DEBUG_LOCKS_WARN_ON(subclass >= MAX_LOCKDEP_SUBCLASSES))
return 0;
if (subclass < NR_LOCKDEP_CACHING_CLASSES)
class = lock->class_cache[subclass];
/*
* Not cached?
*/
if (unlikely(!class)) {
class = register_lock_class(lock, subclass, 0);
if (!class)
return 0;
}
debug_class_ops_inc(class);
if (very_verbose(class)) {
nbcon_cpu_emergency_enter();
printk("\nacquire class [%px] %s", class->key, class->name);
if (class->name_version > 1)
printk(KERN_CONT "#%d", class->name_version);
printk(KERN_CONT "\n");
dump_stack();
nbcon_cpu_emergency_exit();
}
/*
* Add the lock to the list of currently held locks.
* (we dont increase the depth just yet, up until the
* dependency checks are done)
*/
depth = curr->lockdep_depth;
/*
* Ran out of static storage for our per-task lock stack again have we?
*/
if (DEBUG_LOCKS_WARN_ON(depth >= MAX_LOCK_DEPTH))
return 0;
class_idx = class - lock_classes;
if (depth && !sync) {
/* we're holding locks and the new held lock is not a sync */
hlock = curr->held_locks + depth - 1;
if (hlock->class_idx == class_idx && nest_lock) {
if (!references)
references++;
if (!hlock->references)
hlock->references++;
hlock->references += references;
/* Overflow */
if (DEBUG_LOCKS_WARN_ON(hlock->references < references))
return 0;
return 2;
}
}
hlock = curr->held_locks + depth;
/*
* Plain impossible, we just registered it and checked it weren't no
* NULL like.. I bet this mushroom I ate was good!
*/
if (DEBUG_LOCKS_WARN_ON(!class))
return 0;
hlock->class_idx = class_idx;
hlock->acquire_ip = ip;
hlock->instance = lock;
hlock->nest_lock = nest_lock;
hlock->irq_context = task_irq_context(curr);
hlock->trylock = trylock;
hlock->read = read;
hlock->check = check;
hlock->sync = !!sync;
hlock->hardirqs_off = !!hardirqs_off;
hlock->references = references;
#ifdef CONFIG_LOCK_STAT
hlock->waittime_stamp = 0;
hlock->holdtime_stamp = lockstat_clock();
#endif
hlock->pin_count = pin_count;
if (check_wait_context(curr, hlock))
return 0;
/* Initialize the lock usage bit */
if (!mark_usage(curr, hlock, check))
return 0;
/*
* Calculate the chain hash: it's the combined hash of all the
* lock keys along the dependency chain. We save the hash value
* at every step so that we can get the current hash easily
* after unlock. The chain hash is then used to cache dependency
* results.
*
* The 'key ID' is what is the most compact key value to drive
* the hash, not class->key.
*/
/*
* Whoops, we did it again.. class_idx is invalid.
*/
if (DEBUG_LOCKS_WARN_ON(!test_bit(class_idx, lock_classes_in_use)))
return 0;
chain_key = curr->curr_chain_key;
if (!depth) {
/*
* How can we have a chain hash when we ain't got no keys?!
*/
if (DEBUG_LOCKS_WARN_ON(chain_key != INITIAL_CHAIN_KEY))
return 0;
chain_head = 1;
}
hlock->prev_chain_key = chain_key;
if (separate_irq_context(curr, hlock)) {
chain_key = INITIAL_CHAIN_KEY;
chain_head = 1;
}
chain_key = iterate_chain_key(chain_key, hlock_id(hlock));
if (nest_lock && !__lock_is_held(nest_lock, -1)) {
print_lock_nested_lock_not_held(curr, hlock);
return 0;
}
if (!debug_locks_silent) {
WARN_ON_ONCE(depth && !hlock_class(hlock - 1)->key);
WARN_ON_ONCE(!hlock_class(hlock)->key);
}
if (!validate_chain(curr, hlock, chain_head, chain_key))
return 0;
/* For lock_sync(), we are done here since no actual critical section */
if (hlock->sync)
return 1;
curr->curr_chain_key = chain_key;
curr->lockdep_depth++;
check_chain_key(curr);
#ifdef CONFIG_DEBUG_LOCKDEP
if (unlikely(!debug_locks))
return 0;
#endif
if (unlikely(curr->lockdep_depth >= MAX_LOCK_DEPTH)) {
debug_locks_off();
nbcon_cpu_emergency_enter();
print_lockdep_off("BUG: MAX_LOCK_DEPTH too low!");
printk(KERN_DEBUG "depth: %i max: %lu!\n",
curr->lockdep_depth, MAX_LOCK_DEPTH);
lockdep_print_held_locks(current);
debug_show_all_locks();
dump_stack();
nbcon_cpu_emergency_exit();
return 0;
}
if (unlikely(curr->lockdep_depth > max_lockdep_depth))
max_lockdep_depth = curr->lockdep_depth;
return 1;
}확인 사항: 이 코드에서는 반환값보다 상태 변경을 먼저 확인한다. 어느 잠금을 획득한 뒤 어떤 필드를 바꾸는지, 실패 시 어느 레이블로 분기하는지, 변경된 상태를 다음 호출자가 어떤 전제로 사용하는지 추적한다.
함수별 분석
lock class dependency graph를 runtime에 구축해 deadlock 가능 cycle과 context misuse를 잡는 검증기다.
원본 코드를 함수별로 나누어 살펴본다. 각 함수가 준비하는 값과 다음 함수가 그 값을 사용하는 방식을 확인한다.
각 단계의 입력과 처리 결과를 연결해 본다. 다음 단계로 넘어가기 전에 바뀌는 필드를 코드에서 확인한다.
1. lockdep_init
lockdep_init 주변에서는 lock_class_key를 중심으로 본다. 이 필드는 static lock identity 역할을 하므로, 함수가 끝날 때 lock acquired 상태가 실제로 성립했는지 확인해야 한다.
원본 코드에서 입력 범위 검사, 주요 필드 변경, 다른 계층에서 사용할 수 있게 하는 시점, 실패 시 복구 순서를 확인한다. 이 조건을 만족해야 다음 함수가 edge 후보 기록을 전제로 삼을 수 있다.
자주 틀리는 해석: lock instance와 lock class를 구분하지 않음
2. __lock_acquire
__lock_acquire 주변에서는 held_locks를 중심으로 본다. 이 필드는 task held stack 역할을 하므로, 함수가 끝날 때 context checked 상태가 실제로 성립했는지 확인해야 한다.
원본 코드에서 입력 범위 검사, 주요 필드 변경, 다른 계층에서 사용할 수 있게 하는 시점, 실패 시 복구 순서를 확인한다. 이 조건을 만족해야 다음 함수가 irq-safe/sleep rules 확인을 전제로 삼을 수 있다.
자주 틀리는 해석: lockdep warning을 실제 deadlock 발생으로만 해석함
| 함수 | 입력 | 상태 변경 | 확인할 사항 |
|---|---|---|---|
| lockdep_init | lock_class_key, 호출 시 실행 문맥, 하위 시스템의 준비 조건 | lock acquired: edge 후보 기록 | lock instance와 lock class를 구분하지 않음 문제를 코드상 어느 조건문 또는 error label에서 분리하는가 |
| __lock_acquire | held_locks, 호출 시 실행 문맥, 하위 시스템의 준비 조건 | context checked: irq-safe/sleep rules 확인 | lockdep warning을 실제 deadlock 발생으로만 해석함 문제를 코드상 어느 조건문 또는 error label에서 분리하는가 |
구조체와 필드
구조체의 필드를 언제 바꿀 수 있고 다른 코드가 언제 읽을 수 있는지 확인한다. 필드의 의미와 함께 잠금 등 접근을 보호하는 규칙을 살펴본다.
각 단계에서 읽고 쓰는 필드를 구조체 정의와 대조한다.
어떤 코드가 필드를 변경하고 어떤 방식으로 접근을 보호하는지, 객체를 언제 해제하는지 원본 코드에서 확인한다.
| 필드 | 읽는 법 |
|---|---|
| lock_class_key | static lock identity |
| held_locks | task held stack |
| dependency graph | class ordering edges |
| irq context bits | hardirq/softirq safety |
실행 단계와 상태 변화
실행 단계를 따로 정리하면 정상 경로와 실패 경로를 나란히 비교할 수 있다. 커널 문제는 최종 결과보다 준비가 덜 된 중간 상태를 다른 코드에 공개한 뒤, 실패 시 제대로 정리하지 못할 때 자주 발생한다.
화살표는 정상 진행 방향을 나타낸다. 중간 단계에서 실패하면 각 단계의 오류 처리 또는 대체 경로로 이동한다.
| 상태 | 의미 | 진입 조건 | 깨지는 지점 |
|---|---|---|---|
| lock acquired | edge 후보 기록 | 앞 단계의 준비와 오류 처리가 끝난 뒤 | 다음 단계가 준비되지 않은 상태를 사용하거나 필요한 정리를 늦출 때 |
| context checked | irq-safe/sleep rules 확인 | 앞 단계의 준비와 오류 처리가 끝난 뒤 | 다음 단계가 준비되지 않은 상태를 사용하거나 필요한 정리를 늦출 때 |
| cycle found | warning emit | 앞 단계의 준비와 오류 처리가 끝난 뒤 | 다음 단계가 준비되지 않은 상태를 사용하거나 필요한 정리를 늦출 때 |
| release | held stack pop | 앞 단계의 준비와 오류 처리가 끝난 뒤 | 다음 단계가 준비되지 않은 상태를 사용하거나 필요한 정리를 늦출 때 |
불변 조건과 실패 사례
lockdep의 핵심 객체가 외부에 공개된 뒤에는 마지막 참조가 사라질 때까지 해제 경로가 callback, timer, IRQ, worker와 경합하지 않아야 한다.
다른 CPU나 하위 계층이 변경된 필드를 읽는다면 잠금과 메모리 배리어가 접근 순서를 어떻게 보장하는지 확인한다. 참조 횟수와 RCU로 관리하는 객체 수명도 별도로 확인한다.
중간 단계에서 실패하면 이미 확보한 자원을 의존 관계에 맞춰 해제해야 한다. goto 레이블이 많다면 각 분기에 도달했을 때 확보한 자원을 표로 정리한다.
임베디드 보드를 처음 구동할 때는 패닉 대신 로그 중단, 시간 초과, 장치 초기화 지연, 과도한 인터럽트 같은 증상으로 문제가 드러날 수 있다.
lock instance와 lock class를 구분하지 않음
lockdep warning을 실제 deadlock 발생으로만 해석함
disable path에서 검증 공백을 놓침
계측과 검증
로그를 무작정 추가하지 말고 확인할 가설을 먼저 세운다. 상태표에서 처리가 멈춘 단계를 찾은 뒤, 상태를 바꾸는 함수와 그 결과를 사용하는 함수를 함께 살펴본다.
로그가 출력되었다고 처리가 끝난 것으로 판단하지 않는다. 원본 코드에서 로그 앞뒤의 필드 변경을 확인한다.
| 도구 | 보는 것 |
|---|---|
| CONFIG_PROVE_LOCKING | lockdep 실행이 어느 단계에서 멈추는지 확인 |
| cat /proc/lockdep | lockdep 실행이 어느 단계에서 멈추는지 확인 |
| dmesg lockdep | lockdep 실행이 어느 단계에서 멈추는지 확인 |
| perf lock | lockdep 실행이 어느 단계에서 멈추는지 확인 |
# 예시: 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
추가 확인 사항
- lockdep 의 state machine을 네 단계로 줄였을 때, 실제 코드에서 빠지는 intermediate state는 무엇인가?
- lockdep 의 fast path가 생략한 검사는 어느 init path 또는 slow path에서 보증되는가?
- 실험으로 확인한다면 'lock instance와 lock class를 구분하지 않음' 문제를 어떤 tracepoint와 counter로 분리할 수 있는가?
- 실험으로 확인한다면 'lockdep warning을 실제 deadlock 발생으로만 해석함' 문제를 어떤 tracepoint와 counter로 분리할 수 있는가?