Notifier Chain (알림 체인(Notifier Chain))
Notifier Chain은 Linux 커널의 이벤트 알림 메커니즘입니다. 발행자(publisher)가 이벤트를 발생시키면 등록된 구독자(subscriber) 콜백(Callback)들이 순서대로 호출됩니다. 잠금(Lock) 컨텍스트에 따라 4가지 변형(blocking, atomic, raw, srcu)을 제공하며, CPU 핫플러그(Hotplug)·전원관리·네트워크 디바이스 이벤트 등 커널 전반에서 사용됩니다.
이 문서에서는 각 변형의 API 나열에 그치지 않고 "콜백이 실행되는 잠금 문맥"과 "콜백 내부에서 허용되는 동작"을 중심으로 설계 기준을 정리합니다. registration/unregistration의 수명 주기 규칙, 우선순위(Priority) 체인의 부작용, NOTIFY_STOP 사용 시 전파 차단 영향, SRCU 비용 모델과 읽기 경로 이점까지 분석해 모듈 간 결합도를 낮추면서도 장애 전파를 제어할 수 있는 이벤트 설계 방법을 제공합니다.
핵심 요약
- notifier_block — 구독자 콜백을 담는 기본 구조체 (priority 필드로 호출 순서 결정)
- blocking_notifier_head — rwsem 보호, 슬립(Sleep) 가능 컨텍스트 (가장 일반적)
- atomic_notifier_head — 스핀락 보호, 인터럽트(Interrupt) 핸들러(Handler) 내 사용 가능
- raw_notifier_head — 잠금 없음, 호출자가 직접 동기화 책임
- srcu_notifier_head — SRCU 보호, 콜백 내에서 체인 수정 허용
단계별 이해
- notifier_block 작성
콜백 함수와 우선순위를 담은struct notifier_block을 정의합니다. 우선순위가 높을수록 먼저 호출됩니다. - 체인에 등록
register_*_notifier()함수로 관심 체인에 등록합니다. 반환값을 확인하여 중복 등록을 방지해야 합니다. - 이벤트 수신
체인 발행자가*_notifier_call_chain()을 호출하면 등록된 모든 콜백이 순서대로 실행됩니다. - 콜백 반환값
NOTIFY_OK: 정상 처리,NOTIFY_STOP: 체인 순회 중단,NOTIFY_BAD: 오류(중단 없음),NOTIFY_DONE: 이벤트 무관. - 등록 해제
모듈 언로드 시 반드시unregister_*_notifier()를 호출해야 합니다. 미해제 시 댕글링 포인터 패닉이 발생합니다.
개요
Notifier Chain의 핵심은 struct notifier_block의 단방향 연결 리스트(Linked List)입니다. 발행자는 이벤트 번호와 데이터를 인자로 체인을 순회하며 각 콜백을 호출합니다.
발행-구독 아키텍처
Notifier Chain은 발행-구독(Publish-Subscribe) 패턴을 커널 내부에서 구현한 것입니다. 이벤트 소스(발행자)가 체인 헤드를 통해 이벤트를 발행하면, 등록된 모든 구독자 콜백이 우선순위 순서대로 호출됩니다. 각 체인 헤드는 서로 다른 잠금 메커니즘을 사용하여 동시성을 제어합니다. 아래 다이어그램은 커널 전반의 주요 이벤트 소스가 어떻게 체인 헤드를 거쳐 구독자에게 전달되는지를 보여줍니다.
struct notifier_block
/* include/linux/notifier.h */
struct notifier_block {
notifier_fn_t notifier_call; /* 콜백 함수 포인터 */
struct notifier_block __rcu *next; /* 다음 구독자 (RCU protected) */
int priority; /* 호출 우선순위 (높을수록 먼저) */
};
/* 콜백 함수 시그니처 */
typedef int (*notifier_fn_t)(struct notifier_block *nb,
unsigned long action,
void *data);
콜백 반환값
| 반환값 | 의미 | 체인 순회 |
|---|---|---|
NOTIFY_DONE | 이 이벤트에 관심 없음 | 계속 |
NOTIFY_OK | 정상 처리 완료 | 계속 |
NOTIFY_BAD | 처리 실패 (에러 신호) | 계속 |
NOTIFY_STOP | 처리 완료, 이후 콜백 불필요 | 중단 |
NOTIFY_STOP_MASK | NOTIFY_STOP에 포함된 비트 마스크 | 중단 |
4가지 Notifier Chain 변형
Blocking Notifier Chain
가장 일반적인 변형으로, rwsem(읽기-쓰기 세마포어(Semaphore))으로 보호됩니다. 콜백에서 슬립이 허용되며, 프로세스(Process) 컨텍스트에서만 사용 가능합니다.
Blocking API
/* 선언 및 초기화 */
static BLOCKING_NOTIFIER_HEAD(my_chain); /* 정적 초기화 */
/* 또는 동적 초기화 */
struct blocking_notifier_head my_chain;
BLOCKING_INIT_NOTIFIER_HEAD(&my_chain);
/* 구독자 등록/해제 */
int blocking_notifier_chain_register(struct blocking_notifier_head *nh,
struct notifier_block *nb);
int blocking_notifier_chain_unregister(struct blocking_notifier_head *nh,
struct notifier_block *nb);
/* 이벤트 발행 */
int blocking_notifier_call_chain(struct blocking_notifier_head *nh,
unsigned long val, void *v);
Blocking Notifier 실전 예제
/* === 발행자(publisher) 측 === */
static BLOCKING_NOTIFIER_HEAD(voltage_change_chain);
/* 외부에서 등록/해제할 수 있도록 함수 공개 */
int register_voltage_notifier(struct notifier_block *nb)
{
return blocking_notifier_chain_register(&voltage_change_chain, nb);
}
EXPORT_SYMBOL(register_voltage_notifier);
int unregister_voltage_notifier(struct notifier_block *nb)
{
return blocking_notifier_chain_unregister(&voltage_change_chain, nb);
}
EXPORT_SYMBOL(unregister_voltage_notifier);
/* 이벤트 정의 */
#define VOLTAGE_CHANGE_PRE 0x01
#define VOLTAGE_CHANGE_POST 0x02
static void notify_voltage_change(unsigned long event, int mv)
{
blocking_notifier_call_chain(&voltage_change_chain, event, (void *)(long)mv);
}
/* === 구독자(subscriber) 측 === */
static int my_voltage_cb(struct notifier_block *nb,
unsigned long event, void *data)
{
int mv = (int)(long)data;
if (event == VOLTAGE_CHANGE_PRE)
pr_info("Voltage will change to %dmV\n", mv);
return NOTIFY_OK;
}
static struct notifier_block my_nb = {
.notifier_call = my_voltage_cb,
.priority = 100, /* 높을수록 먼저 호출 */
};
static int __init my_init(void)
{
return register_voltage_notifier(&my_nb);
}
static void __exit my_exit(void)
{
unregister_voltage_notifier(&my_nb); /* 반드시 해제! */
}
rwsem 잠금 동작 상세
Blocking notifier는 내부적으로 rw_semaphore(읽기-쓰기 세마포어)를 사용합니다. 이벤트 발행 시 down_read()로 읽기 잠금을 획득하고 체인을 순회합니다. 구독자 등록/해제 시에는 down_write()로 쓰기 잠금을 획득합니다. 읽기 잠금은 여러 CPU에서 동시에 획득할 수 있어 이벤트 발행의 병렬성이 보장됩니다. 그러나 쓰기 잠금은 모든 읽기 잠금이 해제될 때까지 대기해야 하므로, 콜백 실행 중 등록/해제가 지연될 수 있습니다.
Atomic Notifier Chain
스핀락으로 보호되어 인터럽트 핸들러에서도 호출 가능합니다. 콜백 내에서 슬립을 유발하는 어떠한 연산도 허용되지 않습니다.
/* 초기화 */
static ATOMIC_NOTIFIER_HEAD(netdev_chain);
/* API */
int atomic_notifier_chain_register(struct atomic_notifier_head *nh,
struct notifier_block *nb);
int atomic_notifier_chain_unregister(struct atomic_notifier_head *nh,
struct notifier_block *nb);
int atomic_notifier_call_chain(struct atomic_notifier_head *nh,
unsigned long val, void *v);
mutex_lock(), kmalloc(GFP_KERNEL), schedule() 등 슬립을 유발하는 함수를 호출하면 커널 패닉(Kernel Panic)이 발생합니다.
RCU 기반 내부 구현
Atomic notifier의 핵심은 읽기 경로(call_chain)와 쓰기 경로(register/unregister)가 서로 다른 동기화를 사용한다는 점입니다. 읽기 경로는 rcu_read_lock()으로 보호되어 스핀락 없이 체인을 순회합니다. 쓰기 경로만 spin_lock_irqsave()로 리스트를 수정합니다. 이 설계 덕분에 여러 CPU가 동시에 이벤트를 발행해도 스핀락 경합이 발생하지 않습니다. notifier_block의 next 포인터에 __rcu 어노테이션이 붙는 이유도 RCU로 보호되기 때문입니다.
내부 구현 코드
/* kernel/notifier.c — atomic notifier 내부 구현 (간략화) */
int atomic_notifier_chain_register(struct atomic_notifier_head *nh,
struct notifier_block *n)
{
unsigned long flags;
int ret;
spin_lock_irqsave(&nh->lock, flags);
ret = notifier_chain_register(&nh->head, n); /* rcu_assign_pointer 사용 */
spin_unlock_irqrestore(&nh->lock, flags);
return ret;
}
int atomic_notifier_call_chain(struct atomic_notifier_head *nh,
unsigned long val, void *v)
{
int ret;
rcu_read_lock(); /* 스핀락 없이 RCU만 사용 */
ret = notifier_call_chain(&nh->head, val, v, -1, NULL);
rcu_read_unlock();
return ret;
}
/* notifier_call_chain 내부 순회 */
static int notifier_call_chain(struct notifier_block **nl,
unsigned long val, void *v, ...)
{
struct notifier_block *nb, *next_nb;
nb = rcu_dereference_raw(*nl); /* __rcu 포인터 역참조 */
while (nb) {
next_nb = rcu_dereference_raw(nb->next);
ret = nb->notifier_call(nb, val, v);
if (ret & NOTIFY_STOP_MASK)
break;
nb = next_nb;
}
return ret;
}
SRCU Notifier Chain
SRCU(Sleepable RCU)로 보호되어 콜백 내에서 슬립이 허용되면서도, 콜백 실행 중 체인에서 등록/해제가 가능합니다. CPU 핫플러그 이벤트에 사용됩니다.
/* SRCU Notifier는 동적 초기화가 필수 */
struct srcu_notifier_head cpu_chain;
static int __init init_cpu_notifier(void)
{
srcu_init_notifier_head(&cpu_chain); /* SRCU struct 초기화 포함 */
return 0;
}
/* 정리 시 반드시 호출 */
srcu_cleanup_notifier_head(&cpu_chain);
/* API */
int srcu_notifier_chain_register(struct srcu_notifier_head *nh,
struct notifier_block *nb);
int srcu_notifier_chain_unregister(struct srcu_notifier_head *nh,
struct notifier_block *nb);
int srcu_notifier_call_chain(struct srcu_notifier_head *nh,
unsigned long val, void *v);
SRCU vs RCU: 설계 차이와 비용
일반 RCU에서 rcu_read_lock()은 선점을 비활성화(Preemption Disable)합니다. 이 때문에 RCU 읽기 구간 내에서는 슬립이 불가능합니다. SRCU는 이 제약을 해결하기 위해 Per-CPU 카운터 기반의 참조 추적을 사용합니다. srcu_read_lock()은 현재 CPU의 Per-CPU 카운터를 증가시키고 인덱스를 반환합니다. srcu_read_unlock()은 해당 카운터를 감소시킵니다. 선점을 비활성화하지 않으므로 콜백에서 슬립이 가능합니다.
SRCU의 비용은 일반 RCU보다 큽니다. srcu_struct는 Per-CPU 카운터 배열을 포함하여 약 200바이트(Byte) 이상의 메모리를 사용합니다. 반면 atomic notifier의 spinlock_t는 4바이트에 불과합니다. 따라서 SRCU notifier는 콜백에서 슬립이 반드시 필요하고, 콜백 내에서 체인 수정이 요구되는 경우에만 사용해야 합니다.
Raw Notifier Chain
잠금이 전혀 없는 최저수준 변형입니다. 동기화는 전적으로 호출자의 책임입니다. 시스템 초기화 단계나 이미 잠금이 보장된 특수 경로에서만 사용합니다.
/* 초기화 */
static RAW_NOTIFIER_HEAD(my_raw_chain);
/* API: 호출자가 적절한 잠금을 보유해야 함 */
int raw_notifier_chain_register(struct raw_notifier_head *nh,
struct notifier_block *nb);
int raw_notifier_chain_unregister(struct raw_notifier_head *nh,
struct notifier_block *nb);
int raw_notifier_call_chain(struct raw_notifier_head *nh,
unsigned long val, void *v);
Raw Notifier 실전 예제 — Reboot 알림
/* kernel/reboot.c: 시스템 재부팅/종료 알림 (Raw Notifier 사용)
* 재부팅 경로는 이미 잠금 보유 상태이고 특수 컨텍스트이므로 raw 사용 */
/* 구독자 측 */
static int my_reboot_cb(struct notifier_block *nb,
unsigned long code, void *data)
{
switch (code) {
case SYS_RESTART:
pr_info("System restarting\n");
my_flush_all(); /* 데이터 플러시 */
break;
case SYS_HALT:
case SYS_POWER_OFF:
pr_info("System halting\n");
my_hw_shutdown(); /* 하드웨어 안전 종료 */
break;
}
return NOTIFY_DONE;
}
static struct notifier_block my_reboot_nb = {
.notifier_call = my_reboot_cb,
.priority = 128, /* 0 = 기본, 양수 = 앞서 호출, 음수 = 나중 호출 */
};
static int __init my_init(void)
{
return register_reboot_notifier(&my_reboot_nb);
}
static void __exit my_exit(void)
{
unregister_reboot_notifier(&my_reboot_nb);
}
raw_notifier_call_chain()은 어떤 잠금도 획득하지 않습니다. 등록/해제와 호출이 동시에 일어날 수 있는 환경에서는 use-after-free 문제가 발생합니다. 반드시 호출자가 적절한 직렬화(Serialization)를 보장해야 합니다.
4종 비교
| 항목 | blocking | atomic | raw | srcu |
|---|---|---|---|---|
| 잠금 구조체 | struct rw_semaphore | spinlock_t | 없음 | struct srcu_struct |
| 콜백 내 sleep | 가능 | 불가 | 호출자 결정 | 가능 |
| IRQ 컨텍스트 | 불가 | 가능 | 호출자 결정 | 불가 |
| 콜백 중 등록 | 불가 (데드락) | 불가 (데드락) | 가능 (주의) | 가능 |
| 초기화 매크로(Macro) | BLOCKING_NOTIFIER_HEAD | ATOMIC_NOTIFIER_HEAD | RAW_NOTIFIER_HEAD | srcu_init_notifier_head() |
| 주 사용처 | 전원관리, 클럭, 규제기 | 네트워크, 디바이스 | 부팅 초기, 특수 | CPU 핫플러그 |
| 등록 시 잠금 | rwsem write | spin_lock_irqsave | 없음 | mutex |
| 호출 시 잠금 | rwsem read | spin_lock_irqsave + RCU read | 없음 | srcu_read_lock |
| PREEMPT_RT 호환 | 가능 | 제한적 | 호출자 결정 | 가능 |
| grace period 필요 | 아니오 | 예 (RCU) | 아니오 | 예 (SRCU) |
| 메모리 오버헤드(Overhead) | rw_semaphore (40B) | spinlock_t (4B) | 포인터 (8B) | srcu_struct (~200B) |
4종 잠금 메커니즘 비교 다이어그램
내부 동작 메커니즘
notifier_call_chain 내부 구조
모든 변형의 핵심은 notifier_call_chain()으로, 우선순위 정렬된 연결 리스트를 순회하며 콜백을 호출합니다.
/* kernel/notifier.c: 실제 순회 로직 (단순화) */
static int notifier_call_chain(struct notifier_block **nl,
unsigned long val, void *v,
int nr_to_call, int *nr_calls)
{
int ret = NOTIFY_DONE;
struct notifier_block *nb, *next_nb;
nb = rcu_dereference_raw(*nl);
while (nb && nr_to_call) {
next_nb = rcu_dereference_raw(nb->next);
if (nr_calls)
(*nr_calls)++;
ret = nb->notifier_call(nb, val, v);
if (ret & NOTIFY_STOP_MASK) /* NOTIFY_STOP or NOTIFY_BAD with stop */
break;
nb = next_nb;
nr_to_call--;
}
return ret;
}
notifier_call_chain 실행 흐름 다이어그램
notifier_call_chain 상세 코드 분석
notifier_call_chain()은 4종 모든 변형의 핵심 순회 함수입니다. 각 변형은 이 함수를 잠금으로 감싸서 호출합니다. 핵심 매개변수인 nr_to_call은 최대 호출 횟수를 제한하며, nr_calls는 실제 호출된 횟수를 돌려줍니다.
/* kernel/notifier.c — 전체 구현 (Linux 6.x) */
static int notifier_call_chain(
struct notifier_block **nl,
unsigned long val, void *v,
int nr_to_call, int *nr_calls)
{
int ret = NOTIFY_DONE;
struct notifier_block *nb, *next_nb;
nb = rcu_dereference_raw(*nl);
while (nb && nr_to_call) {
/* 콜백 실행 전에 next를 미리 저장 —
* 콜백이 자기 자신을 해제해도 안전하게 순회 가능 (SRCU/raw) */
next_nb = rcu_dereference_raw(nb->next);
if (nr_calls)
(*nr_calls)++;
/* 핵심: 콜백 호출 */
ret = nb->notifier_call(nb, val, v);
if (notifier_to_errno(ret)) {
/* ret에 NOTIFY_STOP_MASK 비트가 설정됨
* → NOTIFY_STOP 또는 NOTIFY_BAD */
break;
}
nb = next_nb;
nr_to_call--;
}
return ret;
}
/* blocking 변형: rwsem read lock으로 감싸기 */
int blocking_notifier_call_chain(
struct blocking_notifier_head *nh,
unsigned long val, void *v)
{
int ret = NOTIFY_DONE;
if (rcu_access_pointer(nh->head)) {
down_read(&nh->rwsem); /* 읽기 잠금 획득 */
ret = notifier_call_chain(&nh->head, val, v,
-1, NULL);
up_read(&nh->rwsem); /* 읽기 잠금 해제 */
}
return ret;
}
/* atomic 변형: RCU read-side critical section */
int atomic_notifier_call_chain(
struct atomic_notifier_head *nh,
unsigned long val, void *v)
{
int ret;
rcu_read_lock(); /* RCU 읽기 진입 */
ret = notifier_call_chain(&nh->head, val, v,
-1, NULL);
rcu_read_unlock(); /* RCU 읽기 종료 */
return ret;
}
콜백 반환값 처리 로직
콜백 반환값은 비트 마스크로 처리됩니다. NOTIFY_STOP_MASK (0x8000) 비트가 설정되면 체인 순회가 중단됩니다.
/* include/linux/notifier.h — 반환값 정의 */
#define NOTIFY_DONE 0x0000 /* 관심 없음, 계속 */
#define NOTIFY_OK 0x0001 /* 처리 완료, 계속 */
#define NOTIFY_STOP_MASK 0x8000 /* 중단 비트 */
#define NOTIFY_BAD (NOTIFY_STOP_MASK|0x0002)
/* 0x8002: 에러 + 중단 */
#define NOTIFY_STOP (NOTIFY_STOP_MASK|0x0001)
/* 0x8001: 성공 + 중단 */
/* 변환 함수: 반환값에서 에러 코드 추출 */
static inline int notifier_from_errno(int err)
{
if (err)
return NOTIFY_STOP_MASK | (NOTIFY_OK - err);
return NOTIFY_OK;
}
static inline int notifier_to_errno(int ret)
{
return -(ret & ~NOTIFY_STOP_MASK); /* STOP_MASK 제거 후 부호 반전 */
}
NOTIFY_STOP은 "이벤트를 성공적으로 처리했으니 더 이상 전파할 필요 없음"이고,
NOTIFY_BAD는 "에러가 발생했으며 발행자가 이벤트를 취소해야 함"입니다.
blocking_notifier_call_chain()의 반환값에 notifier_to_errno()를 적용하면 에러 코드를 추출할 수 있습니다.
등록 시 우선순위 정렬
/* 등록 시 우선순위 내림차순으로 연결 리스트에 삽입 */
static int notifier_chain_register(struct notifier_block **nl,
struct notifier_block *n)
{
while ((*nl) != NULL) {
if ((*nl)->priority < n->priority)
break; /* 삽입 위치 발견 */
nl = &((*nl)->next);
}
n->next = *nl;
rcu_assign_pointer(*nl, n);
return 0;
}
/* → 등록 시마다 O(n) 탐색, 호출 시 순서 보장 */
우선순위 정렬 구조 다이어그램
등록/해제 생명주기 다이어그램
커널 주요 Notifier Chain 목록
전원 관리 (Blocking)
/* kernel/power/main.c: PM 상태 전환 알림 */
int register_pm_notifier(struct notifier_block *nb);
int unregister_pm_notifier(struct notifier_block *nb);
/* PM 이벤트 값 */
// PM_HIBERNATION_PREPARE : 하이버네이션 준비
// PM_POST_HIBERNATION : 하이버네이션 복구 후
// PM_SUSPEND_PREPARE : 서스펜드 진입 전
// PM_POST_SUSPEND : 서스펜드 복구 후
static int my_pm_cb(struct notifier_block *nb,
unsigned long event, void *data)
{
if (event == PM_SUSPEND_PREPARE)
flush_my_work(); /* 서스펜드 전 작업 정리 */
return NOTIFY_OK;
}
네트워크 디바이스 (Atomic)
/* net/core/dev.c: 네트워크 디바이스 이벤트 */
int register_netdevice_notifier(struct notifier_block *nb);
int unregister_netdevice_notifier(struct notifier_block *nb);
/* 이벤트: NETDEV_UP, NETDEV_DOWN, NETDEV_REGISTER, NETDEV_UNREGISTER, */
/* NETDEV_CHANGE, NETDEV_CHANGEMTU, NETDEV_CHANGEADDR 등 */
static int my_netdev_cb(struct notifier_block *nb,
unsigned long event, void *ptr)
{
struct net_device *dev = netdev_notifier_info_to_dev(ptr);
if (event == NETDEV_UP)
pr_info("%s is up\n", dev->name);
return NOTIFY_DONE;
}
CPU 핫플러그 (SRCU 기반 state machine)
/* Linux 4.10+: cpuhp state machine으로 교체됨 */
/* 직접 notifier 대신 cpuhp_setup_state() 사용 권장 */
int cpuhp_setup_state(enum cpuhp_state state,
const char *name,
int (*startup)(unsigned int cpu),
int (*teardown)(unsigned int cpu));
/* 예제 */
static int my_cpu_online(unsigned int cpu)
{
pr_info("CPU %u online\n", cpu);
return 0;
}
static int __init my_init(void)
{
return cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "my:online",
my_cpu_online, NULL);
}
register_cpu_notifier()는 deprecated되었고, cpuhp_setup_state() 기반 state machine으로 전환되었습니다. 내부적으로 여전히 SRCU Notifier를 사용합니다.
CPU Hotplug Notifier 실행 시퀀스
CPU Hotplug 실전 코드
/* 완전한 CPU Hotplug 드라이버 예제 */
#include <linux/cpuhotplug.h>
#include <linux/percpu.h>
static DEFINE_PER_CPU(struct my_cpu_data, cpu_data);
static enum cpuhp_state hp_state;
static int my_cpu_online(unsigned int cpu)
{
struct my_cpu_data *data = per_cpu_ptr(&cpu_data, cpu);
pr_info("CPU %u online: 리소스 초기화\n", cpu);
data->active = true;
data->counter = 0;
return 0; /* 0: 성공, 음수: 실패 → CPU online 중단 */
}
static int my_cpu_offline(unsigned int cpu)
{
struct my_cpu_data *data = per_cpu_ptr(&cpu_data, cpu);
pr_info("CPU %u offline: 리소스 정리\n", cpu);
data->active = false;
flush_my_cpu_work(cpu); /* CPU별 작업 완료 */
return 0;
}
static int __init my_init(void)
{
int ret;
/* CPUHP_AP_ONLINE_DYN: 동적 state 번호 할당
* 등록 즉시 모든 온라인 CPU에 startup 콜백 실행 */
ret = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN,
"mydrv:online",
my_cpu_online,
my_cpu_offline);
if (ret < 0)
return ret;
hp_state = ret; /* 해제 시 필요한 state 번호 저장 */
return 0;
}
static void __exit my_exit(void)
{
/* 모든 온라인 CPU에 teardown 콜백 실행 후 등록 해제 */
cpuhp_remove_state(hp_state);
}
Netdevice Notifier 실전 사용 흐름
Netdevice Notifier 완전한 예제
/* 네트워크 디바이스 이벤트 전체 처리 예제 */
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/notifier.h>
static int my_netdev_event(struct notifier_block *nb,
unsigned long event, void *ptr)
{
struct net_device *dev = netdev_notifier_info_to_dev(ptr);
/* 특정 디바이스만 필터링 */
if (!(dev->flags & IFF_UP) && event != NETDEV_UP)
return NOTIFY_DONE;
switch (event) {
case NETDEV_REGISTER:
pr_info("[%s] 디바이스 등록됨\n", dev->name);
break;
case NETDEV_UP:
pr_info("[%s] 인터페이스 UP (MTU=%d)\n",
dev->name, dev->mtu);
/* 필터 규칙 설치 등 */
break;
case NETDEV_DOWN:
pr_info("[%s] 인터페이스 DOWN\n", dev->name);
/* 필터 규칙 제거 등 */
break;
case NETDEV_CHANGEMTU:
pr_info("[%s] MTU 변경: %d\n", dev->name, dev->mtu);
break;
case NETDEV_UNREGISTER:
pr_info("[%s] 디바이스 해제 중\n", dev->name);
break;
}
return NOTIFY_DONE;
}
static struct notifier_block my_netdev_nb = {
.notifier_call = my_netdev_event,
.priority = 0, /* 기본 우선순위 */
};
static int __init my_init(void)
{
return register_netdevice_notifier(&my_netdev_nb);
}
static void __exit my_exit(void)
{
unregister_netdevice_notifier(&my_netdev_nb);
}
module_init(my_init);
module_exit(my_exit);
NETDEV_REGISTER + NETDEV_UP 이벤트를 즉시 재생(replay)합니다. 이를 통해 등록 시점에 이미 존재하는 디바이스도 빠짐없이 처리할 수 있습니다.
PM Notifier 실전 상세 예제
/* 전원 관리 Notifier — 서스펜드/하이버네이션 전후 처리 */
#include <linux/suspend.h>
#include <linux/notifier.h>
static int my_pm_notifier(struct notifier_block *nb,
unsigned long action, void *data)
{
switch (action) {
case PM_HIBERNATION_PREPARE:
pr_info("하이버네이션 준비 중\n");
my_save_state();
break;
case PM_SUSPEND_PREPARE:
pr_info("서스펜드 준비 중\n");
my_flush_buffers();
my_disable_polling();
break;
case PM_POST_SUSPEND:
pr_info("서스펜드 복귀\n");
my_enable_polling();
my_restore_state();
break;
case PM_POST_HIBERNATION:
pr_info("하이버네이션 복귀\n");
my_restore_state();
break;
case PM_RESTORE_PREPARE:
/* 하이버네이션 이미지 복원 직전 */
break;
case PM_POST_RESTORE:
/* 하이버네이션 이미지 복원 실패 시 */
break;
}
return NOTIFY_OK;
}
static struct notifier_block my_pm_nb = {
.notifier_call = my_pm_notifier,
.priority = 0,
};
/* 등록/해제 */
register_pm_notifier(&my_pm_nb);
unregister_pm_notifier(&my_pm_nb);
Reboot Notifier 실전 상세 예제
/* Reboot Notifier — 시스템 재부팅/종료/halt 처리
* kernel/reboot.c에서 restart_handler_list 관리
* 이 체인은 blocking_notifier_head (restart_handler) 또는
* raw_notifier_head (reboot_notifier_list) 사용 */
#include <linux/reboot.h>
static int my_reboot_handler(struct notifier_block *nb,
unsigned long action, void *data)
{
switch (action) {
case SYS_RESTART:
pr_emerg("시스템 재시작 — 하드웨어 안전 종료\n");
my_hw_safe_shutdown();
my_flush_nvram(); /* 비휘발 메모리 플러시 */
break;
case SYS_HALT:
pr_emerg("시스템 정지\n");
my_hw_safe_shutdown();
break;
case SYS_POWER_OFF:
pr_emerg("시스템 전원 끄기\n");
my_hw_power_down_sequence();
break;
}
return NOTIFY_DONE;
}
static struct notifier_block my_reboot_nb = {
.notifier_call = my_reboot_handler,
.priority = 200, /* 높은 우선순위 — 먼저 실행 */
};
/* register_reboot_notifier()는 내부적으로
* blocking_notifier_chain_register(&reboot_notifier_list, nb) 호출 */
register_reboot_notifier(&my_reboot_nb);
unregister_reboot_notifier(&my_reboot_nb);
기타 주요 Notifier Chain
| 체인 | 등록 함수 | 이벤트 예시 | 변형 |
|---|---|---|---|
| Reboot | register_reboot_notifier() | SYS_RESTART, SYS_HALT | raw |
| inet 주소 변경 | register_inetaddr_notifier() | NETDEV_UP, NETDEV_DOWN | blocking |
| inet6 주소 변경 | register_inet6addr_notifier() | NETDEV_UP, NETDEV_DOWN | blocking |
| 클럭 변경 | clk_notifier_register() | PRE_RATE_CHANGE, POST_RATE_CHANGE | blocking |
| Regulator 변경 | regulator_register_notifier() | REGULATOR_EVENT_ENABLE | blocking |
| 디스플레이 패널 | 드라이버별 register_notifier | PANEL_EVENT_BLANK, UNBLANK | blocking |
| PANIC | atomic_notifier_chain_register(&panic_notifier_list, nb) | 0 (단일 이벤트) | atomic |
| FB (Framebuffer) | fb_register_client() | FB_EVENT_BLANK, SUSPEND | blocking |
inet 주소 변경 알림 예제
/* 네트워크 인터페이스 IP 주소 변경 감지 */
#include <linux/inetdevice.h>
static int my_inetaddr_cb(struct notifier_block *nb,
unsigned long event, void *ptr)
{
struct in_ifaddr *ifa = ptr;
struct net_device *dev = ifa->ifa_dev->dev;
switch (event) {
case NETDEV_UP:
pr_info("%s: IP %pI4 added\n", dev->name, &ifa->ifa_address);
break;
case NETDEV_DOWN:
pr_info("%s: IP %pI4 removed\n", dev->name, &ifa->ifa_address);
break;
}
return NOTIFY_OK;
}
static struct notifier_block my_inetaddr_nb = {
.notifier_call = my_inetaddr_cb,
};
register_inetaddr_notifier(&my_inetaddr_nb);
PANIC Notifier 예제
/* 커널 패닉 직전에 호출 — atomic 컨텍스트 */
static int my_panic_cb(struct notifier_block *nb,
unsigned long val, void *data)
{
const char *msg = data; /* 패닉 메시지 문자열 */
/* 하드웨어 상태 레지스터 덤프 등 긴급 처리 */
my_hw_emergency_dump();
return NOTIFY_DONE; /* NOTIFY_STOP 금지: 패닉을 막을 수 없음 */
}
static struct notifier_block my_panic_nb = {
.notifier_call = my_panic_cb,
.priority = 200, /* 높은 우선순위로 먼저 실행 */
};
/* panic_notifier_list는 atomic_notifier_head */
atomic_notifier_chain_register(&panic_notifier_list, &my_panic_nb);
성능 고려사항
| 항목 | 내용 |
|---|---|
| 등록 비용 | O(n) — 우선순위 정렬 삽입, 등록은 드물게 발생하므로 무시 가능 |
| 호출 비용 | O(n) 콜백 수 — 콜백이 많을수록 지연(Latency) 증가 |
| Blocking 오버헤드 | rwsem 읽기 획득/해제 (경합(Contention) 없을 때 매우 빠름) |
| Atomic 오버헤드 | 스핀락 획득/해제 (IRQ 비활성화 포함) |
| SRCU 오버헤드 | srcu_read_lock/unlock — 빠른 경로지만 grace period 비용 |
디버깅(Debugging)
ftrace로 Notifier Chain 추적
ftrace의 function 트레이서와 function_graph 트레이서를 사용하면 notifier chain 콜백의 호출 순서와 소요 시간을 정밀하게 추적할 수 있습니다.
# 1. notifier_call_chain 함수 추적
echo 'notifier_call_chain' > /sys/kernel/debug/tracing/set_ftrace_filter
echo function > /sys/kernel/debug/tracing/current_tracer
echo 1 > /sys/kernel/debug/tracing/tracing_on
cat /sys/kernel/debug/tracing/trace
# 2. function_graph로 콜백 호출 계층 확인
echo function_graph > /sys/kernel/debug/tracing/current_tracer
echo 'blocking_notifier_call_chain' > /sys/kernel/debug/tracing/set_graph_function
echo 1 > /sys/kernel/debug/tracing/tracing_on
# 이벤트 발생 후 확인
cat /sys/kernel/debug/tracing/trace
# 출력 예시:
# | blocking_notifier_call_chain() {
# | down_read() { ... }
# | notifier_call_chain() {
# | my_pm_notifier() { ... } ← 콜백 1
# | driver_xyz_notifier() { ... } ← 콜백 2
# }
# | up_read() { ... }
# }
# 3. 특정 notifier chain만 필터링 (예: PM)
echo 'pm_notifier_call_chain' > /sys/kernel/debug/tracing/set_ftrace_filter
echo funcgraph-duration > /sys/kernel/debug/tracing/trace_options
echo funcgraph-proc > /sys/kernel/debug/tracing/trace_options
# 4. 추적 종료 및 정리
echo 0 > /sys/kernel/debug/tracing/tracing_on
echo nop > /sys/kernel/debug/tracing/current_tracer
lockdep을 이용한 잠금 순서 검증
# 커널 빌드 옵션 (디버그 커널에서 활성화)
CONFIG_DEBUG_LOCK_ALLOC=y
CONFIG_PROVE_LOCKING=y
CONFIG_LOCKDEP=y
# lockdep이 검출하는 Notifier Chain 관련 문제:
# 1. blocking_notifier 콜백에서 같은 체인의 register/unregister → 데드락
# 2. atomic_notifier 콜백에서 sleep 함수 호출 → BUG: scheduling while atomic
# 3. 중첩된 notifier chain 호출의 잠금 역순 → lockdep 경고
# lockdep 통계 확인
cat /proc/lockdep_stats
# lock_stat으로 경합 분석
cat /proc/lock_stat | grep notifier
printk를 이용한 콜백 디버깅
/* 콜백 진입/종료 추적 패턴 */
static int my_debug_cb(struct notifier_block *nb,
unsigned long event, void *data)
{
pr_debug("[%s] event=%lu data=%p\n", __func__, event, data);
/* 콜백 소요 시간 측정 */
ktime_t start = ktime_get();
/* ... 실제 처리 ... */
pr_debug("[%s] took %lld ns\n", __func__,
ktime_to_ns(ktime_sub(ktime_get(), start)));
return NOTIFY_OK;
}
/* dynamic debug로 런타임에 활성화/비활성화 */
/* echo 'func my_debug_cb +p' > /sys/kernel/debug/dynamic_debug/control */
변형 선택 가이드
주의사항 및 흔한 실수
unregister_*_notifier()를 호출하지 않으면, 해제된 메모리의 콜백 포인터가 남아 있어 이후 이벤트 발생 시 커널 패닉이 발생합니다. 이는 가장 흔하면서도 치명적인 버그입니다.
atomic_notifier_call_chain()은 RCU read-side critical section에서 실행됩니다. 콜백 내에서 mutex_lock(), kmalloc(GFP_KERNEL), msleep(), schedule() 등 슬립을 유발하는 함수를 호출하면 BUG: scheduling while atomic 패닉이 발생합니다.
/* 잘못된 예: atomic notifier 콜백에서 sleep */
static int bad_atomic_cb(struct notifier_block *nb,
unsigned long event, void *data)
{
struct my_data *d = kmalloc(sizeof(*d), GFP_KERNEL); /* BUG! sleep 가능 */
mutex_lock(&my_mutex); /* BUG! sleep 가능 */
return NOTIFY_OK;
}
/* 올바른 예: atomic 안전한 할당 사용 */
static int good_atomic_cb(struct notifier_block *nb,
unsigned long event, void *data)
{
struct my_data *d = kmalloc(sizeof(*d), GFP_ATOMIC); /* OK: 비수면 */
spin_lock(&my_lock); /* OK: 비수면 */
/* 또는: 무거운 작업은 workqueue로 위임 */
schedule_work(&my_work); /* OK: 작업 예약만 함 */
return NOTIFY_OK;
}
blocking_notifier_call_chain()은 내부적으로 rwsem 읽기 잠금을 획득합니다. 콜백 내에서 같은 체인에 register/unregister를 시도하면 쓰기 잠금을 요청하게 되어 데드락이 발생합니다. 이 경우 SRCU Notifier를 사용해야 합니다.
dev_change_flags()를 호출하면 NETDEV_CHANGE 이벤트가 다시 발생하여 순환 호출이 됩니다.
/* 잘못된 예: 콜백에서 같은 체인 이벤트 재발생 */
static int bad_recursive_cb(struct notifier_block *nb,
unsigned long event, void *data)
{
struct net_device *dev = netdev_notifier_info_to_dev(data);
if (event == NETDEV_UP) {
/* 위험! 이 호출이 NETDEV_CHANGE를 발생시킬 수 있음 */
dev_change_flags(dev, dev->flags | IFF_PROMISC, NULL);
}
return NOTIFY_DONE;
}
/* 올바른 예: workqueue로 위임 */
static int good_deferred_cb(struct notifier_block *nb,
unsigned long event, void *data)
{
if (event == NETDEV_UP) {
/* 비동기로 처리하여 재귀 회피 */
schedule_work(&my_promisc_work);
}
return NOTIFY_DONE;
}
NOTIFY_STOP을 반환하면 이후 콜백은 호출되지 않습니다. 이는 우선순위가 높은 핸들러가 이벤트를 독점적으로 처리할 때 유용하지만, 다른 모듈의 정상적인 이벤트 수신을 방해할 수 있습니다. NOTIFY_STOP은 정확한 의미를 이해한 경우에만 사용하세요.
priority 필드를 명시적으로 설정하세요. 동일 우선순위의 등록 순서는 LIFO이므로 모듈 로드 순서에 따라 결과가 달라질 수 있습니다.
흔한 실수 요약
| 실수 | 증상 | 해결 방법 |
|---|---|---|
| unregister 누락 | 모듈 언로드 후 커널 패닉 (UAF) | module_exit에서 반드시 unregister |
| atomic 콜백에서 sleep | BUG: scheduling while atomic | GFP_ATOMIC / workqueue 위임 |
| blocking 콜백에서 재등록 | 데드락 (rwsem R→W) | SRCU notifier 사용 |
| 콜백에서 같은 체인 이벤트 발생 | 무한 재귀 / 스택 오버플로(Stack Overflow)우 | workqueue로 비동기 처리 |
| NOTIFY_STOP 남용 | 다른 구독자 이벤트 수신 불가 | NOTIFY_OK / NOTIFY_DONE 사용 |
| priority 미지정 | 모듈 로드 순서에 의존적 동작 | 명시적 priority 값 설정 |
| 스택 변수에 nb 선언 | 함수 반환 후 댕글링 포인터 | static 또는 동적 할당 |
| 콜백 소요시간 과다 | 이벤트 경로 지연, 시스템 지연 | 최소한의 처리, 나머지 위임 |
die_chain / panic_notifier 상세
커널이 치명적 오류를 만나면 두 가지 알림 체인이 순서대로 동작합니다. die_chain은 oops/die 경로에서 호출되며, panic_notifier_list는 커널 패닉 직전 최후 정리 기회를 제공합니다. 두 체인 모두 Atomic Notifier이므로 콜백 내에서 슬립이 절대 허용되지 않습니다.
die_chain 구조
die_chain은 arch/x86/kernel/dumpstack.c(또는 아키텍처별 해당 파일)에서 notify_die()를 통해 호출됩니다. 이 함수는 트랩 핸들러, 페이지 폴트(Page Fault) 핸들러, MCE(Machine Check Exception) 경로 등에서 불립니다.
/* include/linux/kdebug.h */
enum die_val {
DIE_OOPS = 1,
DIE_INT3, /* breakpoint */
DIE_DEBUG, /* debug exception */
DIE_PANIC, /* panic 직전 */
DIE_NMI, /* NMI */
DIE_DIE, /* 커널 die() 진입 */
DIE_NMIUNKNOWN, /* 출처 불명 NMI */
DIE_NMIWATCHDOG, /* NMI watchdog */
DIE_KERNELDEBUG, /* 커널 디버거 */
DIE_TRAP, /* 일반 트랩 */
DIE_GPF, /* General Protection Fault */
DIE_CALL, /* 소프트웨어 호출 */
DIE_PAGE_FAULT, /* 페이지 폴트 */
};
/* kernel/notifier.c */
static ATOMIC_NOTIFIER_HEAD(die_chain);
int register_die_notifier(struct notifier_block *nb)
{
return atomic_notifier_chain_register(&die_chain, nb);
}
/* notify_die() — 아키텍처 트랩 핸들러에서 호출 */
int notify_die(enum die_val val, const char *str,
struct pt_regs *regs, long err,
int trap, int sig)
{
struct die_args args = {
.regs = regs,
.str = str,
.err = err,
.trapnr = trap,
.signr = sig,
};
return atomic_notifier_call_chain(&die_chain, val, &args);
}
panic_notifier_list
panic_notifier_list는 kernel/panic.c의 panic() 함수에서 호출됩니다. 시스템이 더 이상 복구 불가능한 상태에서 최후의 정리를 수행합니다.
/* kernel/panic.c */
ATOMIC_NOTIFIER_HEAD(panic_notifier_list);
EXPORT_SYMBOL(panic_notifier_list);
void panic(const char *fmt, ...)
{
/* ... 초기 설정 ... */
atomic_notifier_call_chain(&panic_notifier_list,
PANIC_NOTIFIER, buf);
/* ... kmsg dump, kdump, reboot ... */
}
spin_lock()조차 안전하지 않을 수 있으며, printk()도 NMI-safe 경로만 사용해야 합니다. 가능한 최소한의 작업(레지스터(Register) 덤프(Dump), LED 점멸, 하드웨어 리셋 트리거)만 수행하세요.
실제 사용 예
| 서브시스템 | 등록 함수 | 용도 |
|---|---|---|
| kgdb | register_die_notifier() | breakpoint/single-step 이벤트를 가로채 디버거로 전달 |
| MCE | register_die_notifier() | Machine Check Exception 처리 및 로깅 |
| KVM | register_die_notifier() | 게스트 VM 내부 예외를 호스트에서 처리 |
| perf | register_die_notifier() | 하드웨어 브레이크포인트 및 watchpoint 처리 |
| kdump/kexec | atomic_notifier_chain_register() | 패닉 시 크래시 덤프 커널 부팅 |
| panic_blink | atomic_notifier_chain_register() | 패닉 시 키보드 LED 점멸 |
Reboot Notifier Chain
시스템이 재부팅, 종료(halt), 전원 차단(power off)될 때 드라이버와 서브시스템에 정리 기회를 제공하는 Blocking Notifier Chain입니다. kernel/reboot.c에 정의되어 있으며, sys_reboot() 시스템 콜(System Call) 경로에서 호출됩니다.
Reboot 이벤트 종류
| 이벤트 | 값 | 설명 |
|---|---|---|
SYS_RESTART | 0x0001 | 시스템 재시작 (warm reboot) |
SYS_HALT | 0x0002 | 시스템 정지 (CPU halt) |
SYS_POWER_OFF | 0x0003 | 전원 완전 차단 |
API 및 등록
/* kernel/reboot.c */
static BLOCKING_NOTIFIER_HEAD(reboot_notifier_list);
int register_reboot_notifier(struct notifier_block *nb);
int unregister_reboot_notifier(struct notifier_block *nb);
/* devm 래퍼: device 수명과 자동 연결 */
int devm_register_reboot_notifier(struct device *dev,
struct notifier_block *nb);
콜백 우선순위와 순서
reboot notifier는 우선순위가 높은 콜백부터 실행됩니다. 일반적으로 하드웨어 드라이버는 낮은 우선순위(먼저 호출되어 하드웨어 상태 저장), 파일시스템(Filesystem)은 높은 우선순위(나중에 호출되어 최종 플러시)로 등록합니다.
/* 예제: 커스텀 reboot notifier */
static int my_reboot_handler(struct notifier_block *nb,
unsigned long action, void *data)
{
switch (action) {
case SYS_RESTART:
pr_info("my_driver: saving state before restart\n");
my_hw_save_state();
break;
case SYS_HALT:
case SYS_POWER_OFF:
pr_info("my_driver: shutting down hardware\n");
my_hw_shutdown();
break;
}
return NOTIFY_DONE;
}
static struct notifier_block my_reboot_nb = {
.notifier_call = my_reboot_handler,
.priority = 0, /* 기본 우선순위 */
};
static int __init my_init(void)
{
return register_reboot_notifier(&my_reboot_nb);
}
static void __exit my_exit(void)
{
unregister_reboot_notifier(&my_reboot_nb);
}
restart_handler_list: SoC별 리셋 핸들러
restart_handler_list는 실제 하드웨어 리셋을 수행하는 별도의 체인입니다. SoC 드라이버가 아키텍처별 리셋 메커니즘(watchdog 리셋, PMIC 리셋 등)을 등록하며, 우선순위가 가장 높은 핸들러 하나만 실행됩니다.
/* kernel/reboot.c */
void do_kernel_restart(char *cmd)
{
atomic_notifier_call_chain(&restart_handler_list,
reboot_mode, cmd);
}
/* 드라이버 등록 예: watchdog 기반 리셋 */
static int wdt_restart(struct notifier_block *nb,
unsigned long action, void *data)
{
writel(0x1, wdt_base + WDT_RESET_REG);
mdelay(100);
return NOTIFY_DONE;
}
static struct notifier_block wdt_restart_nb = {
.notifier_call = wdt_restart,
.priority = 128, /* 높은 우선순위: 선호 리셋 방법 */
};
reboot_notifier_list는 셧다운 직전 정리를 위한 Blocking 체인이고, restart_handler_list는 실제 하드웨어 리셋을 수행하는 Atomic 체인입니다. 전자는 여러 콜백이 모두 실행되지만, 후자는 NOTIFY_STOP을 반환하는 첫 핸들러에서 멈춥니다.
네트워크 Notifier Chain
리눅스 네트워크 스택(Network Stack)은 다양한 이벤트를 notifier chain으로 전파합니다. NIC 상태 변경, IP 주소 할당, 라우팅 테이블(Routing Table) 갱신 등 모든 네트워크 상태 변화가 구독자에게 알림됩니다.
netdev_chain 이벤트 목록
| 이벤트 | 발생 시점 | 콜백 데이터 |
|---|---|---|
NETDEV_REGISTER | 네트워크 디바이스 등록 | struct net_device * |
NETDEV_UNREGISTER | 디바이스 등록 해제 | struct net_device * |
NETDEV_UP | 인터페이스 활성화 (ifconfig up) | struct net_device * |
NETDEV_DOWN | 인터페이스 비활성화 | struct net_device * |
NETDEV_CHANGE | 링크 상태/플래그 변경 | struct net_device * |
NETDEV_CHANGEMTU | MTU 변경 | struct net_device * |
NETDEV_CHANGEADDR | MAC 주소 변경 | struct net_device * |
NETDEV_CHANGENAME | 인터페이스 이름 변경 | struct net_device * |
NETDEV_PRE_UP | 인터페이스 활성화 직전 | struct net_device * |
NETDEV_FEAT_CHANGE | features 변경 (offload 등) | struct net_device * |
call_netdevice_notifiers() 호출 경로
/* net/core/dev.c */
static RAW_NOTIFIER_HEAD(netdev_chain);
int call_netdevice_notifiers(unsigned long val,
struct net_device *dev)
{
struct netdev_notifier_info info = {
.dev = dev,
};
return call_netdevice_notifiers_info(val, &info);
}
/* 내부적으로 rtnl_lock()으로 보호 — raw이지만 사실상 blocking처럼 동작 */
static int call_netdevice_notifiers_info(unsigned long val,
struct netdev_notifier_info *info)
{
ASSERT_RTNL(); /* rtnl_lock 보유 확인 */
return raw_notifier_call_chain(&netdev_chain, val, info);
}
netdev_chain은 raw_notifier이지만, 모든 등록/해제와 호출이 rtnl_lock()(뮤텍스) 보호 하에 이루어지므로 별도의 내부 잠금이 필요 없습니다. 이는 네트워크 서브시스템 고유의 Big Kernel Lock 스타일 동기화입니다.
netevent_notifier: 이웃 서브시스템 이벤트
/* net/core/netevent.c */
static ATOMIC_NOTIFIER_HEAD(netevent_notif_chain);
/* 이벤트 종류 */
enum netevent_notif_type {
NETEVENT_NEIGH_UPDATE, /* ARP/NDP 엔트리 갱신 */
NETEVENT_REDIRECT, /* ICMP 리다이렉트 수신 */
NETEVENT_DELAY_PROBE_TIME_UPDATE, /* 탐사 간격 변경 */
NETEVENT_IPV4_MPATH_HASH_UPDATE, /* 멀티패스 해시 정책 변경 */
NETEVENT_IPV6_MPATH_HASH_UPDATE,
};
inet/inet6addr_chain: IP 주소 변경 알림
/* net/ipv4/devinet.c */
BLOCKING_NOTIFIER_HEAD(inetaddr_chain); /* IPv4 주소 변경 */
int register_inetaddr_notifier(struct notifier_block *nb);
/* net/ipv6/addrconf.c */
BLOCKING_NOTIFIER_HEAD(inet6addr_chain); /* IPv6 주소 변경 */
int register_inet6addr_notifier(struct notifier_block *nb);
/* 이벤트: NETDEV_UP, NETDEV_DOWN (주소 추가/삭제 시) */
/* 콜백 데이터: struct in_ifaddr * (IPv4) / struct inet6_ifaddr * (IPv6) */
fib_chain: 라우팅 테이블 변경
/* net/ipv4/fib_trie.c */
static ATOMIC_NOTIFIER_HEAD(fib_chain);
/* 이벤트 */
#define FIB_EVENT_ENTRY_REPLACE 0
#define FIB_EVENT_ENTRY_APPEND 1
#define FIB_EVENT_ENTRY_ADD 2
#define FIB_EVENT_ENTRY_DEL 3
#define FIB_EVENT_RULE_ADD 4
#define FIB_EVENT_RULE_DEL 5
/* switchdev 드라이버가 이를 구독하여 HW FIB 오프로드 수행 */
int register_fib_notifier(struct net *net,
struct notifier_block *nb,
void (*cb)(struct notifier_block *nb,
unsigned long event, void *ptr),
struct netlink_ext_ack *extack);
CPU 핫플러그 Notifier
Linux 4.10에서 기존 register_cpu_notifier() API는 deprecated되고, 상태 머신 기반의 cpuhp_setup_state()로 전환되었습니다. 새 API는 각 상태 전이마다 startup/teardown 콜백 쌍을 등록하여 대칭적 초기화/정리를 보장합니다.
핫플러그 상태 머신
CPU가 온라인/오프라인될 때 여러 단계(state)를 거칩니다. 각 단계마다 등록된 콜백이 호출되며, 실패 시 자동 롤백(Rollback)됩니다.
| 구간 | 상태 범위 | 실행 CPU | 슬립 가능 | 용도 |
|---|---|---|---|---|
| PREPARE | CPUHP_OFFLINE ~ CPUHP_BRINGUP_CPU | 부팅 CPU | 가능 | 메모리 할당, 자료구조 준비 |
| STARTING | CPUHP_BRINGUP_CPU ~ CPUHP_AP_ONLINE | 대상 CPU | 불가 (IRQ off) | per-CPU 초기화, 타이머(Timer) 설정 |
| ONLINE | CPUHP_AP_ONLINE ~ CPUHP_ONLINE | 대상 CPU | 가능 | 고수준 서비스 시작 |
cpuhp_setup_state() API
/* include/linux/cpuhotplug.h */
/* 정적 상태: 미리 정의된 슬롯에 등록 */
int cpuhp_setup_state(enum cpuhp_state state,
const char *name,
int (*startup)(unsigned int cpu),
int (*teardown)(unsigned int cpu));
/* 동적 상태: CPUHP_AP_ONLINE_DYN에서 자동 할당 */
/* 반환값이 양수이면 할당된 state 번호 */
int cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "my:online",
my_cpu_online, my_cpu_offline);
/* no-call 변형: 기존 온라인 CPU에 대해 콜백 미호출 */
int cpuhp_setup_state_nocalls(enum cpuhp_state state,
const char *name,
int (*startup)(unsigned int cpu),
int (*teardown)(unsigned int cpu));
/* 인스턴스 기반: 여러 인스턴스가 같은 state 공유 */
int cpuhp_setup_state_multi(enum cpuhp_state state,
const char *name,
int (*startup)(unsigned int cpu,
struct hlist_node *node),
int (*teardown)(unsigned int cpu,
struct hlist_node *node));
인스턴스 기반 vs 싱글턴 콜백
cpuhp_setup_state()는 서브시스템 전체에 대한 단일 콜백입니다. 타이머 서브시스템, RCU, 워크큐 등 시스템당 하나만 필요한 초기화에 적합합니다.
cpuhp_setup_state_multi()는 같은 상태에 여러 인스턴스를 등록할 수 있습니다. 예를 들어, 여러 블록 디바이스가 각각 per-CPU 완료 큐를 관리해야 할 때 사용합니다. 각 인스턴스는 cpuhp_state_add_instance()/cpuhp_state_remove_instance()로 동적 추가/제거됩니다.
/* 인스턴스 기반 예제: 블록 디바이스 per-CPU 큐 */
static enum cpuhp_state blk_mq_hp_state;
static int blk_mq_hctx_notify_online(unsigned int cpu,
struct hlist_node *node)
{
struct blk_mq_hw_ctx *hctx =
hlist_entry_safe(node, struct blk_mq_hw_ctx, cpuhp_online);
/* CPU가 온라인되면 해당 CPU의 하드웨어 큐 활성화 */
blk_mq_tag_wakeup_all(hctx->tags, true);
return 0;
}
PM (Power Management) Notifier
전원 관리(PM) notifier는 시스템 서스펜드/하이버네이션 전후에 드라이버와 서브시스템에 알림을 보내는 Blocking Notifier Chain입니다. 콜백에서 NOTIFY_BAD를 반환하면 서스펜드를 거부할 수 있습니다.
PM 이벤트 종류
| 이벤트 | 시점 | 거부 가능 | 용도 |
|---|---|---|---|
PM_HIBERNATION_PREPARE | 하이버네이션 진입 전 | 가능 | 디스크 공간 확보, 캐시(Cache) 플러시(Flush) |
PM_POST_HIBERNATION | 하이버네이션 복구 후 | 불가 | 리소스 재초기화 |
PM_SUSPEND_PREPARE | 서스펜드 진입 전 | 가능 | 작업 플러시, 하드웨어 상태 저장 |
PM_POST_SUSPEND | 서스펜드 복구 후 | 불가 | 하드웨어 재초기화 |
PM_RESTORE_PREPARE | 하이버네이션 이미지 복원 전 | 가능 | 복원 준비 |
PM_POST_RESTORE | 복원 실패 후 | 불가 | 정리 |
API 및 콜백 패턴
/* kernel/power/main.c */
static BLOCKING_NOTIFIER_HEAD(pm_chain_head);
int register_pm_notifier(struct notifier_block *nb);
int unregister_pm_notifier(struct notifier_block *nb);
/* 서스펜드 거부 예제 */
static int my_pm_handler(struct notifier_block *nb,
unsigned long event, void *data)
{
switch (event) {
case PM_SUSPEND_PREPARE:
if (critical_operation_in_progress()) {
pr_warn("my_driver: blocking suspend — critical op\n");
return NOTIFY_BAD; /* 서스펜드 거부! */
}
flush_all_pending_work();
save_hardware_state();
break;
case PM_POST_SUSPEND:
restore_hardware_state();
break;
}
return NOTIFY_OK;
}
static struct notifier_block my_pm_nb = {
.notifier_call = my_pm_handler,
.priority = 0,
};
PM_SUSPEND_PREPARE에서 NOTIFY_BAD를 반환하면 서스펜드가 거부됩니다. 하지만 이 시점에서 이미 호출된 다른 콜백들은 PM_POST_SUSPEND를 받아 rollback해야 합니다. PM 프레임워크가 이를 자동으로 처리하지만, 콜백 순서에 주의해야 합니다.
콜백 순서 의존성
PM notifier의 호출 순서는 우선순위에 의해 결정됩니다. 일반적으로 서브시스템 수준 콜백이 먼저 실행되고 개별 드라이버 콜백이 나중에 실행됩니다. 디바이스 수준의 서스펜드/리줌은 별도의 dev_pm_ops 프레임워크가 담당하며, PM notifier는 그 이전 단계입니다.
/* 서스펜드 진행 순서:
* 1. pm_notifier_call_chain(PM_SUSPEND_PREPARE) ← PM notifier
* 2. suspend_freeze_processes() ← 프로세스 동결
* 3. dpm_suspend_start() ← dev_pm_ops.prepare
* 4. dpm_suspend() ← dev_pm_ops.suspend
* 5. platform_suspend() ← 아키텍처별 진입
*
* 리줌은 역순:
* 5. platform_resume()
* 4. dpm_resume()
* 3. dpm_resume_end()
* 2. suspend_thaw_processes()
* 1. pm_notifier_call_chain(PM_POST_SUSPEND) ← PM notifier
*/
서스펜드/리줌 전체 시퀀스
아래 다이어그램은 시스템 서스펜드(Suspend)와 리줌(Resume) 과정에서 PM notifier가 호출되는 시점과 NOTIFY_BAD 롤백 경로를 보여줍니다.
메모리 Notifier Chain
메모리 핫플러그와 메모리 압박 상황에서 서브시스템에 알림을 전달하는 notifier chain 그룹입니다.
memory_chain: 메모리 핫플러그
/* mm/memory_hotplug.c */
static BLOCKING_NOTIFIER_HEAD(memory_chain);
int register_memory_notifier(struct notifier_block *nb);
int unregister_memory_notifier(struct notifier_block *nb);
메모리 핫플러그 이벤트
| 이벤트 | 시점 | 거부 | 설명 |
|---|---|---|---|
MEM_GOING_ONLINE | 메모리 블록 온라인 전 | 가능 | 자료구조 확장 준비 |
MEM_ONLINE | 온라인 완료 후 | 불가 | 새 메모리 사용 시작 |
MEM_GOING_OFFLINE | 메모리 블록 오프라인 전 | 가능 | 페이지(Page) 마이그레이션 준비 |
MEM_OFFLINE | 오프라인 완료 후 | 불가 | 자료구조 축소 |
MEM_CANCEL_ONLINE | 온라인 취소됨 | 불가 | MEM_GOING_ONLINE 롤백 |
MEM_CANCEL_OFFLINE | 오프라인 취소됨 | 불가 | MEM_GOING_OFFLINE 롤백 |
/* 메모리 핫플러그 notifier 예제 */
static int my_memory_cb(struct notifier_block *nb,
unsigned long action, void *data)
{
struct memory_notify *mn = data;
switch (action) {
case MEM_GOING_ONLINE:
pr_info("memory block %lu going online (start_pfn=%lu, nr=%lu)\n",
mn->start_pfn >> 15, mn->start_pfn, mn->nr_pages);
/* 페이지 범위에 대한 자료구조 사전 할당 */
if (expand_my_page_table(mn->start_pfn, mn->nr_pages))
return NOTIFY_BAD; /* 메모리 부족: 온라인 거부 */
break;
case MEM_CANCEL_ONLINE:
shrink_my_page_table(mn->start_pfn, mn->nr_pages);
break;
case MEM_OFFLINE:
shrink_my_page_table(mn->start_pfn, mn->nr_pages);
break;
}
return NOTIFY_OK;
}
vmpressure notifier: 메모리 압박 알림
/* mm/vmpressure.c */
/* vmpressure는 memcg별 이벤트로, eventfd 기반 */
/* cgroup v2의 memory.pressure 인터페이스와 연동 */
/* 압박 수준 */
enum vmpressure_levels {
VMPRESSURE_LOW, /* 경미한 압박 (캐시 회수 시작) */
VMPRESSURE_MEDIUM, /* 중간 압박 (스왑 활발) */
VMPRESSURE_CRITICAL, /* 위험 (OOM 임박) */
};
/* 사용자 공간에서 모니터링:
* /sys/fs/cgroup//memory.pressure
* PSI(Pressure Stall Information) 인터페이스
*/
OOM notifier
/* mm/oom_kill.c */
static BLOCKING_NOTIFIER_HEAD(oom_notify_list);
int register_oom_notifier(struct notifier_block *nb);
int unregister_oom_notifier(struct notifier_block *nb);
/* OOM notifier는 OOM killer 발동 전에 호출됨 */
/* 콜백이 메모리를 확보하면 NOTIFY_OK 반환 → OOM kill 회피 가능 */
static int my_oom_handler(struct notifier_block *nb,
unsigned long action, void *data)
{
unsigned long freed = release_my_caches();
if (freed > 0) {
pr_info("my_driver: freed %lu pages, avoiding OOM\n", freed);
return NOTIFY_OK; /* OOM killer 호출 억제 시도 */
}
return NOTIFY_DONE; /* 관심 없음 */
}
메모리 Notifier 이벤트 흐름
아래 다이어그램은 메모리 핫플러그 체인의 이벤트 상태 전이, vmpressure 알림 수준, OOM notifier의 동작을 한눈에 보여줍니다.
반환값 프로토콜
Notifier 콜백의 반환값은 체인 전파 동작을 제어하는 핵심 메커니즘입니다. 반환값은 단순 정수가 아니라 비트마스크 기반 프로토콜을 따릅니다.
반환값 정의
/* include/linux/notifier.h */
#define NOTIFY_DONE 0x0000 /* 관심 없음, 다음 콜백 계속 */
#define NOTIFY_OK 0x0001 /* 성공 처리, 다음 콜백 계속 */
#define NOTIFY_BAD (NOTIFY_STOP_MASK | 0x0002)
/* 에러/거부 + 즉시 중단 */
#define NOTIFY_STOP (NOTIFY_STOP_MASK | NOTIFY_OK)
/* 성공 + 즉시 중단 */
#define NOTIFY_STOP_MASK 0x8000 /* 이 비트가 설정되면 체인 중단 */
반환값 의미 비교
| 반환값 | 비트 | 체인 계속 | 의미 | 사용 시나리오 |
|---|---|---|---|---|
NOTIFY_DONE | 0x0000 | 계속 | 이 이벤트에 관심 없음 | 대부분의 경우 기본 반환값 |
NOTIFY_OK | 0x0001 | 계속 | 성공적으로 처리함 | 이벤트를 인지하고 처리한 경우 |
NOTIFY_BAD | 0x8002 | 중단 | 에러/거부 | PM_SUSPEND_PREPARE 거부, MEM_GOING_ONLINE 거부 |
NOTIFY_STOP | 0x8001 | 중단 | 성공 + 독점 처리 | die_notifier에서 kgdb가 이벤트를 처리한 경우 |
notifier_to_errno / errno_to_notifier 변환
/* include/linux/notifier.h */
static inline int notifier_from_errno(int err)
{
if (err)
return NOTIFY_STOP_MASK | (NOTIFY_OK - err);
return NOTIFY_OK;
}
static inline int notifier_to_errno(int ret)
{
ret &= ~NOTIFY_STOP_MASK;
return ret > NOTIFY_OK ? NOTIFY_OK - ret : 0;
}
/* 사용 예: 호출자 측 */
ret = blocking_notifier_call_chain(&my_chain, EVENT, data);
ret = notifier_to_errno(ret);
if (ret) {
pr_err("notifier returned error: %d\n", ret);
goto rollback;
}
NOTIFY_BAD는 PM 서스펜드 거부, 메모리 온라인 거부 등 "작업 취소"가 가능한 체인에서만 의미가 있습니다. 예를 들어, die_chain에서 NOTIFY_BAD를 반환해도 oops 자체를 되돌릴 수는 없습니다. 반면 NOTIFY_STOP은 "이 이벤트를 내가 완전히 처리했으니 다른 콜백은 볼 필요 없다"는 의미입니다 (kgdb의 breakpoint 처리가 대표적 예).
우선순위와 순서 제어
struct notifier_block의 priority 필드는 체인 내 콜백 실행 순서를 결정합니다. 높은 값이 먼저 실행되며, 같은 우선순위에서는 나중에 등록된 콜백이 먼저 실행됩니다(LIFO).
우선순위 메커니즘
/* kernel/notifier.c: 등록 시 정렬 삽입 */
static int notifier_chain_register(
struct notifier_block **nl,
struct notifier_block *n)
{
while ((*nl) != NULL) {
/* priority가 높은 것이 리스트 앞쪽 */
if (n->priority > (*nl)->priority)
break;
if (n->priority == (*nl)->priority &&
n == *nl) /* 중복 등록 방지 */
return -EEXIST;
nl = &((*nl)->next);
}
n->next = *nl;
rcu_assign_pointer(*nl, n);
return 0;
}
커널 서브시스템별 우선순위 관례
| 우선순위 범위 | 용도 | 예 |
|---|---|---|
INT_MAX | 최우선 처리 (디버거) | kgdb die notifier |
200~255 | 하드웨어 리셋 핸들러 | watchdog restart_handler |
100~199 | 핵심 서브시스템 | KPTI, perf |
1~99 | 일반 서브시스템 | 네트워크 필터, 브릿지 |
0 (기본값) | 일반 드라이버/모듈 | 대부분의 콜백 |
-1 ~ -INT_MAX | 정리/최후 처리 | 로깅, 통계 수집 |
우선순위 관련 문제
/* 안티패턴: 우선순위에 의존하는 취약한 설계 */
/* 모듈 A: 이벤트를 변환하여 전달 */
static struct notifier_block transformer_nb = {
.notifier_call = transform_event,
.priority = 10, /* 모듈 B보다 먼저 실행 의도 */
};
/* 모듈 B: 변환된 이벤트 소비 */
static struct notifier_block consumer_nb = {
.notifier_call = consume_event,
.priority = 0, /* 모듈 A 이후 실행 의도 */
};
/* 문제: 모듈 A가 로드되지 않으면 모듈 B는 원본 이벤트를 수신함
* 해결: 모듈 간 직접 의존성이 있으면 notifier 대신 직접 함수 호출 사용
*/
디버깅과 트레이싱
Notifier chain 콜백의 지연, 오류, 충돌을 진단하기 위한 다양한 커널 디버깅 기법을 소개합니다.
ftrace를 이용한 notifier 추적
# notifier_call_chain 함수 진입/종료 추적
cd /sys/kernel/debug/tracing
echo 'notifier_call_chain' > set_ftrace_filter
echo 'function_graph' > current_tracer
echo 1 > tracing_on
# 특정 notifier chain 호출 추적
echo 'blocking_notifier_call_chain raw_notifier_call_chain atomic_notifier_call_chain' > set_ftrace_filter
# 결과 확인
cat trace
# 출력 예:
# 1) | blocking_notifier_call_chain() {
# 1) | notifier_call_chain() {
# 1) 0.892 us | my_pm_handler();
# 1) 0.341 us | driver_suspend_cb();
# 1) 2.104 us | }
# 1) 2.561 us | }
Notifier 트레이스포인트
# 사용 가능한 notifier 관련 트레이스포인트 확인
ls /sys/kernel/debug/tracing/events/notifier/
# notifier 등록/해제 이벤트 활성화 (커널 빌드 옵션 의존)
echo 1 > /sys/kernel/debug/tracing/events/notifier/enable
# CPU hotplug 관련 트레이스포인트
echo 1 > /sys/kernel/debug/tracing/events/cpuhp/enable
cat trace_pipe
BPF 기반 notifier 지연 분석
/* bpftrace 스크립트: notifier 콜백 지연 측정 */
/* bpftrace -e 아래 내용 */
/*
kprobe:notifier_call_chain
{
@start[tid] = nsecs;
}
kretprobe:notifier_call_chain
/@start[tid]/
{
$dur = nsecs - @start[tid];
@latency = hist($dur);
if ($dur > 1000000) { // 1ms 이상
printf("slow notifier chain: %d ns, comm=%s\n",
$dur, comm);
}
delete(@start[tid]);
}
*/
# bpftrace로 느린 notifier 콜백 탐지
bpftrace -e '
kprobe:notifier_call_chain { @start[tid] = nsecs; }
kretprobe:notifier_call_chain /@start[tid]/ {
$d = nsecs - @start[tid];
@us = hist($d / 1000);
if ($d > 1000000) {
printf("SLOW %d us comm=%s\n", $d/1000, comm);
}
delete(@start[tid]);
}
'
콜백 내 크래시 디버깅
unregister 없이 모듈이 언로드되어 콜백 함수 포인터가 댕글링 포인터가 되는 경우입니다. 이 크래시는 모듈 언로드 직후가 아니라 다음 이벤트 발생 시 나타나므로 원인 추적이 어렵습니다.
/* 크래시 진단을 위한 디버그 래퍼 */
static int debug_notifier_call_chain(
struct notifier_block **nl,
unsigned long val, void *v)
{
struct notifier_block *nb;
int ret;
for (nb = rcu_dereference(*nl); nb; nb = rcu_dereference(nb->next)) {
/* 콜백 주소가 유효한 커널 텍스트인지 검증 */
if (!kernel_text_address((unsigned long)nb->notifier_call)) {
WARN(1, "invalid notifier callback %px\n",
nb->notifier_call);
continue;
}
ret = nb->notifier_call(nb, val, v);
if (ret & NOTIFY_STOP_MASK)
break;
}
return ret;
}
일반적 디버깅 시나리오
| 증상 | 원인 | 진단 방법 | 해결 |
|---|---|---|---|
| 모듈 언로드 후 패닉 | unregister 누락 | ftrace로 등록/해제 쌍 확인 | module_exit에 unregister 추가 |
| 서스펜드 실패 | 콜백에서 NOTIFY_BAD | pm_debug_messages=1 부트 파라미터 | 거부하는 콜백 수정 |
| 데드락 | 콜백 내 재등록 | lockdep 경고 메시지 | SRCU notifier 사용 또는 workqueue 위임 |
| 높은 지연 | 콜백 과도한 작업 | bpftrace 지연 측정 | 최소 작업 + workqueue 위임 |
| 이벤트 누락 | 다른 콜백의 NOTIFY_STOP | ftrace function_graph로 체인 추적 | NOTIFY_STOP 사용 콜백 검토 |
설계 패턴과 모범 사례
Notifier chain을 올바르게 설계하고 사용하기 위한 패턴과 안티패턴을 정리합니다.
언제 Notifier Chain을 사용해야 하는가
| 적합한 경우 | 부적합한 경우 |
|---|---|
| 구독자가 컴파일 시점에 알 수 없음 | 구독자가 고정(1~2개) |
| 이벤트 소스와 구독자 간 느슨한 결합 필요 | 구독자 간 순서 의존성 있음 |
| 다수의 독립 모듈이 같은 이벤트 관심 | 양방향 통신 필요 |
| 모듈이 동적으로 로드/언로드됨 | 고성능 핫패스(per-packet 등) |
| 커널 내부 서브시스템 간 이벤트 전달 | 사용자 공간(User Space)과의 이벤트 전달 |
대안 메커니즘 비교
| 메커니즘 | 결합도 | 성능 | 용도 |
|---|---|---|---|
| Notifier Chain | 느슨 | 보통 | 커널 서브시스템 간 이벤트 |
| 직접 콜백 | 강함 | 높음 | 1:1 관계, 고성능 필요 |
| Workqueue | 느슨 | 보통 | 비동기 작업 위임 |
| Netlink | 느슨 | 낮음 | 커널-사용자 공간 이벤트 |
| Tracepoint | 느슨 | 높음 | 관찰/진단 목적 |
| eventfd | 보통 | 높음 | 사용자 공간 이벤트 알림 |
모듈 언로드 시 안전한 해제 패턴
/* 패턴 1: 기본 — module_exit에서 해제 */
static struct notifier_block my_nb = {
.notifier_call = my_callback,
};
static int __init my_init(void)
{
return register_netdevice_notifier(&my_nb);
}
static void __exit my_exit(void)
{
unregister_netdevice_notifier(&my_nb);
/* unregister 이후에만 모듈 리소스 해제 */
kfree(my_data);
}
/* 패턴 2: devm — device 수명 자동 관리 */
static int my_probe(struct platform_device *pdev)
{
return devm_register_reboot_notifier(&pdev->dev, &my_nb);
/* 디바이스 제거 시 자동 unregister */
}
/* 패턴 3: 에러 경로 안전 — goto 패턴 */
static int __init my_init(void)
{
int ret;
ret = register_pm_notifier(&my_pm_nb);
if (ret)
return ret;
ret = register_netdevice_notifier(&my_net_nb);
if (ret)
goto err_net;
ret = register_reboot_notifier(&my_reboot_nb);
if (ret)
goto err_reboot;
return 0;
err_reboot:
unregister_netdevice_notifier(&my_net_nb);
err_net:
unregister_pm_notifier(&my_pm_nb);
return ret;
}
SRCU vs Blocking: 트레이드오프
커널 모듈(Kernel Module) Notifier 사용 템플릿
/* 완전한 커널 모듈 템플릿: notifier chain 사용 */
#include <linux/module.h>
#include <linux/notifier.h>
#include <linux/netdevice.h>
#include <linux/reboot.h>
static int my_netdev_event(struct notifier_block *nb,
unsigned long event, void *ptr)
{
struct net_device *dev = netdev_notifier_info_to_dev(ptr);
switch (event) {
case NETDEV_UP:
pr_info("[my_mod] %s is up\n", dev->name);
break;
case NETDEV_DOWN:
pr_info("[my_mod] %s is down\n", dev->name);
break;
default:
break; /* 관심 없는 이벤트 무시 */
}
return NOTIFY_DONE;
}
static struct notifier_block my_netdev_nb = {
.notifier_call = my_netdev_event,
};
static int __init my_mod_init(void)
{
int ret;
ret = register_netdevice_notifier(&my_netdev_nb);
if (ret) {
pr_err("[my_mod] failed to register notifier: %d\n", ret);
return ret;
}
pr_info("[my_mod] loaded\n");
return 0;
}
static void __exit my_mod_exit(void)
{
unregister_netdevice_notifier(&my_netdev_nb);
pr_info("[my_mod] unloaded\n");
}
module_init(my_mod_init);
module_exit(my_mod_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Notifier Chain example module");
흔한 실수 요약
struct notifier_block을 로컬 변수로 선언하고 등록하면, 함수 반환 후 메모리가 해제되어 댕글링 포인터가 됩니다. 반드시 static 또는 kmalloc으로 할당하세요.
dev_set_mtu()를 호출하면 NETDEV_CHANGEMTU 이벤트가 발생하여 같은 콜백이 재진입됩니다. 재진입 가드(per-CPU 플래그)를 사용하거나 workqueue로 비동기 처리하세요.
/* 재진입 가드 패턴 */
static DEFINE_PER_CPU(int, in_notifier_cb);
static int my_netdev_cb(struct notifier_block *nb,
unsigned long event, void *ptr)
{
if (__this_cpu_read(in_notifier_cb))
return NOTIFY_DONE; /* 재진입 방지 */
__this_cpu_write(in_notifier_cb, 1);
/* ... 작업 수행 ... */
__this_cpu_write(in_notifier_cb, 0);
return NOTIFY_DONE;
}
PREEMPT_RT 환경에서의 Notifier Chain
PREEMPT_RT(실시간 선점 패치)는 스핀락 시맨틱(Semantics)을 근본적으로 변경합니다. 일반 커널에서 spinlock_t는 선점과 인터럽트를 비활성화하지만, PREEMPT_RT에서는 rt_mutex로 대체되어 슬립이 가능한 잠금이 됩니다. 이 변화는 각 Notifier Chain 변형의 동작에 직접적인 영향을 미칩니다.
Atomic notifier의 경우, PREEMPT_RT에서 스핀락이 슬리핑 잠금으로 바뀌므로 등록 경로에서 슬립이 가능해집니다. 다만 읽기 경로는 여전히 rcu_read_lock()을 사용하므로, PREEMPT_RT에서 RCU 읽기 구간이 선점 가능해지는 효과가 있습니다. 이는 콜백 실행 중 더 높은 우선순위 태스크에 의해 선점될 수 있음을 의미합니다.
Blocking notifier와 SRCU notifier는 원래 슬립이 가능한 잠금을 사용하므로, PREEMPT_RT에서도 동작이 크게 변하지 않습니다. 따라서 RT 시스템에서는 blocking이나 SRCU notifier를 선호하는 것이 안전합니다.
| Notifier 유형 | 일반 커널 | PREEMPT_RT | RT 영향 |
|---|---|---|---|
atomic |
spinlock + RCU (비선점) | rt_mutex + RCU (선점 가능) | 콜백 중 선점 가능, 지연 시간 변동 |
blocking |
rwsem (슬립 가능) | rwsem (변화 없음) | 영향 없음 (RT 안전) |
srcu |
SRCU + mutex (슬립 가능) | SRCU + mutex (변화 없음) | 영향 없음 (RT 안전) |
raw |
잠금 없음 | 잠금 없음 | 호출자 동기화에 따라 다름 |
커널 Notifier Chain 전체 맵
Linux 커널에는 수십 개의 Notifier Chain이 여러 서브시스템에 걸쳐 정의되어 있습니다. 아래 다이어그램은 주요 Notifier Chain을 서브시스템별로 분류하고, 각 체인의 유형과 대표 이벤트를 정리한 것입니다.
참고자료
공식 문서
- Notifier Error Injection — Linux Kernel Documentation — 알림 체인 오류 주입 테스트 프레임워크 공식 문서입니다
- Device Driver Infrastructure — Linux Kernel Documentation — 디바이스 드라이버 인프라에서 notifier 활용을 설명합니다
- CPU Hotplug in the Kernel — Linux Kernel Documentation — CPU 핫플러그 알림 체인 사용 방법을 다룹니다
- Suspend and CPU Hotplug — Linux Kernel Documentation — PM notifier와 CPU 핫플러그 간 상호작용을 설명합니다
LWN.net 및 주요 참고 글
- Notifier chains in the kernel (LWN, 2006) — Alan Stern의 notifier chain 타입 분리 패치 시리즈에 대한 기사로, blocking/atomic 분리 배경을 설명합니다
- Notifiers and blocking (LWN, 2006) — 기존 단일 notifier_head에서 blocking과 atomic을 분리한 이유와 설계 결정을 다룹니다
- SRCU-based notifier chains (LWN, 2008) — SRCU notifier chain 도입 배경과 성능 특성을 설명합니다
- LWN Kernel Index — Notifiers — LWN의 notifier 관련 기사 색인 페이지입니다
- Avoiding the OOM killer with notifiers (LWN, 2005) — 메모리 부족 상황에서 notifier chain 활용 사례를 설명합니다
커널 소스 경로
| 파일 | 역할 |
|---|---|
kernel/notifier.c |
알림 체인 핵심 구현 — register/unregister/call 함수 |
include/linux/notifier.h |
notifier_block, 4종 notifier_head 구조체 및 매크로 정의 |
kernel/cpu.c |
CPU 핫플러그 notifier 등록 및 호출 경로 |
kernel/power/main.c |
PM notifier chain — suspend/resume 이벤트 알림 |
net/core/dev.c |
netdev_chain — 네트워크 디바이스 이벤트(NETDEV_UP 등) 알림 |
kernel/panic.c |
panic_notifier_list — 커널 패닉 직전 atomic notifier 호출 |
kernel/reboot.c |
reboot_notifier_list — 시스템 재부팅/종료 알림 체인 |
lib/notifier-error-inject.c |
notifier 오류 주입 테스트 프레임워크 구현 |
서적 및 학습 자료
- Linux Kernel Development, 3rd Edition (Robert Love, 2010) — Chapter 4에서 커널 알림 메커니즘과 콜백 체인 패턴을 설명합니다
- Understanding the Linux Kernel, 3rd Edition (Bovet & Cesati, 2005) — 커널 내부 이벤트 전달 구조와 notifier chain 구현을 다룹니다
- Linux Device Drivers, 3rd Edition (Corbet, Rubini & Kroah-Hartman, 2005) — 디바이스 드라이버에서 notifier chain 활용 패턴을 설명합니다. 온라인 무료 공개판을 확인할 수 있습니다
- Professional Linux Kernel Architecture (Wolfgang Mauerer, 2008) — 네트워크 서브시스템의 netdev notifier chain 분석을 포함합니다
블로그 및 커뮤니티 자료
- Kernel Newbies — Notifiers FAQ — 초심자를 위한 notifier chain 기본 개념 정리입니다
- linux-insides — Notification Chains — 커널 내부 알림 체인 구현을 코드와 함께 상세히 분석합니다
- Bootlin Elixir — notifier_block 전체 사용처 — 커널 소스 내 notifier_block 참조를 확인할 수 있습니다
관련 문서
- 동기화 기법 — rwsem, spinlock 기초
- RCU — SRCU Notifier의 기반 메커니즘
- 디바이스 드라이버 — Notifier Chain을 활용한 Device Model
- 인터럽트 기초 — Atomic Notifier 사용 컨텍스트, IRQ/NMI 이해
- Bottom Half 선택 가이드 — Notifier 콜백에서 workqueue 위임 패턴