Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Linux 內核通知鏈機制:原理、數據結構與實戰代碼

編輯:關於 Android 開發

為什麼內核需要通知鏈

大多數內核子系統彼此獨立,但某個子系統往往會關心另一個子系統發生的事件。為了解決這種「事件廣播」需求,Linux 內核提供了通知鏈(Notification Chain)機制。

需要強調的是,通知鏈只用於內核子系統之間的通訊,不能用來向用戶空間發送事件。

它的本質是一條函數鏈表:每個節點都注册了一個函數,事件發生時,鏈上所有節點的函數依次被調用。因此通知鏈必然存在通知方與接收方兩種角色,而具體執行哪些函數由接收方決定——接收方提前把自己的回調注册進鏈中,事件到來時這些函數便被執行。整體思路與用戶空間的信號(signal)機制頗為相似。

四種通知鏈與核心數據結構

內核提供了四種類型的通知鏈,主要差異在於回調函數的執行上下文與鎖保護策略:

1. 原子通知鏈(Atomic notifier chains)

回調只能在中斷上下文中運行,不允許阻塞。

struct atomic_notifier_head {
    spinlock_t lock;
    struct notifier_block *head;
};

2. 可阻塞通知鏈(Blocking notifier chains)

回調在進程上下文中運行,允許睡眠與阻塞。

struct blocking_notifier_head {
    struct rw_semaphore rwsem;
    struct notifier_block *head;
};

3. 原始通知鏈(Raw notifier chains)

對回調不作任何限制,鎖與保護機制由調用者自行維護。

struct raw_notifier_head {
    struct notifier_block *head;
};

4. SRCU 通知鏈(SRCU notifier chains)

可阻塞通知鏈的變體,借助 SRCU 機制延遲釋放。

struct srcu_notifier_head {
    struct mutex mutex;
    struct srcu_struct srcu;
    struct notifier_block *head;
};

而鏈上每個節點的核心結構始終是同一個:

struct notifier_block {
    int (*notifier_call)(struct notifier_block *, unsigned long, void *);
    struct notifier_block *next;
    int priority;
};

其中 notifier_call 是回調函數指針,next 串起下一個節點,priority 決定節點在鏈上的位置——同一條鏈按優先級排列。內核代碼中,這類鏈通常命名為 xxx_chain 或 xxx_notifier_chain。

運作機制

通知鏈的參與者只有兩類:

被通知者——對某事件感興趣的一方。它定義事件發生時的處理函數(回調),並事先注册到通知鏈中,也就是往鏈上插入一項。

通知者——事件的發布方。它定義通知鏈,鏈中保存所有感興趣方的回調;事件發生時遍歷整條鏈,逐一調用處理函數。

完整流程可概括為三步:通知者定義通知鏈;被通知者注册回調;事件發生時通知者觸發整條鏈。

注册與注銷

被通知者調用 notifier_chain_register 按優先級插入回調:

static int notifier_chain_register(struct notifier_block **nl,
                                   struct notifier_block *n)
{
    while ((*nl) != NULL) {
        if (n->priority > (*nl)->priority)
            break;
        nl = &((*nl)->next);
    }
    n->next = *nl;
    rcu_assign_pointer(*nl, n);
    return 0;
}

注銷則由 notifier_chain_unregister 把節點從鏈中摘除:

static int notifier_chain_unregister(struct notifier_block **nl,
                                     struct notifier_block *n)
{
    while ((*nl) != NULL) {
        if ((*nl) == n) {
            rcu_assign_pointer(*nl, n->next);
            return 0;
        }
        nl = &((*nl)->next);
    }
    return -ENOENT;
}

觸發通知

通知者調用 notifier_call_chain 遍歷鏈條並依次執行回調:

static int __kprobes 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(*nl);
    while (nb && nr_to_call) {
        next_nb = rcu_dereference(nb->next);
        ret = nb->notifier_call(nb, val, v);
        if (nr_calls)
            (*nr_calls)++;
        if ((ret & NOTIFY_STOP_MASK) == NOTIFY_STOP_MASK)
            break;
        nb = next_nb;
        nr_to_call--;
    }
    return ret;
}

參數含義:nl 是鏈頭,val 表示事件類型,v 指向回調所需的私有參數(例如通知網卡注册時指向 net_device 結構),nr_to_call 限定最多通知幾個(-1 表示整條鏈),nr_calls 非空時返回實際通知數量。

回調函數的返回值有以下幾種語義:NOTIFY_DONE 表示不關心此事件;NOTIFY_OK 表示執行成功;NOTIFY_BAD 表示執行出錯;NOTIFY_STOP 表示中止後續回調;NOTIFY_STOP_MASK 是中止判斷用的掩碼。notifier_call_chain() 最終返回最後一個被調用回調的返回值。

動手寫一個通知鏈

自己實現通知鏈,本質上只有兩件事:先定義鏈頭並把回調注册進去,再由另一個子系統觸發這條鏈。下面把定義與注册拆成兩個模塊,觸發單獨一個模塊。

buildchain.c:定義鏈頭與外匯函數

#include <linux/notifier.h>
#include <linux/module.h>
MODULE_LICENSE("GPL");

/* 定義通知鏈頭結點 */
static RAW_NOTIFIER_HEAD(test_chain);

int register_test_notifier(struct notifier_block *nb)
{
    return raw_notifier_chain_register(&test_chain, nb);
}
EXPORT_SYMBOL(register_test_notifier);

int unregister_test_notifier(struct notifier_block *nb)
{
    return raw_notifier_chain_unregister(&test_chain, nb);
}
EXPORT_SYMBOL(unregister_test_notifier);

/* 通知整條鏈上的節點 */
int test_notifier_call_chain(unsigned long val, void *v)
{
    return raw_notifier_call_chain(&test_chain, val, v);
}
EXPORT_SYMBOL(test_notifier_call_chain);

static int __init init_notifier(void)
{
    printk("init_notifier\n");
    return 0;
}

static void __exit exit_notifier(void)
{
    printk("exit_notifier\n");
}

module_init(init_notifier);
module_exit(exit_notifier);

regchain.c:注册三個節點

#include <linux/notifier.h>
#include <linux/module.h>
MODULE_LICENSE("GPL");

extern int register_test_notifier(struct notifier_block *);
extern int unregister_test_notifier(struct notifier_block *);

static int test_event1(struct notifier_block *this, unsigned long event, void *ptr)
{
    printk("In Event 1: Event Number is %d\n", event);
    return 0;
}

static int test_event2(struct notifier_block *this, unsigned long event, void *ptr)
{
    printk("In Event 2: Event Number is %d\n", event);
    return 0;
}

static int test_event3(struct notifier_block *this, unsigned long event, void *ptr)
{
    printk("In Event 3: Event Number is %d\n", event);
    return 0;
}

static struct notifier_block test_notifier1 = { .notifier_call = test_event1, };
static struct notifier_block test_notifier2 = { .notifier_call = test_event2, };
static struct notifier_block test_notifier3 = { .notifier_call = test_event3, };

static int __init reg_notifier(void)
{
    int err;
    printk("Begin to register:\n");

    err = register_test_notifier(&test_notifier1);
    if (err) return -1;
    printk("register test_notifier1 completed\n");

    err = register_test_notifier(&test_notifier2);
    if (err) return -1;
    printk("register test_notifier2 completed\n");

    err = register_test_notifier(&test_notifier3);
    if (err) return -1;
    printk("register test_notifier3 completed\n");

    return err;
}

static void __exit unreg_notifier(void)
{
    printk("Begin to unregister\n");
    unregister_test_notifier(&test_notifier1);
    unregister_test_notifier(&test_notifier2);
    unregister_test_notifier(&test_notifier3);
    printk("Unregister finished\n");
}

module_init(reg_notifier);
module_exit(unreg_notifier);

notify.c:觸發通知

#include <linux/notifier.h>
#include <linux/module.h>
MODULE_LICENSE("GPL");

extern int test_notifier_call_chain(unsigned long val, void *v);

static int __init call_notifier(void)
{
    int err;
    printk("Begin to notify:\n");
    printk("==============================\n");
    err = test_notifier_call_chain(1, NULL);
    printk("==============================\n");
    if (err)
        printk("notifier_call_chain error\n");
    return err;
}

static void __exit uncall_notifier(void)
{
    printk("End notify\n");
}

module_init(call_notifier);
module_exit(uncall_notifier);

Makefile

obj-m := buildchain.o regchain.o notify.o
CURRENT_PATH := $(shell pwd)
LINUX_KERNEL := $(shell uname -r)
KERNELDIR := /usr/src/linux-headers-$(LINUX_KERNEL)

all:
    make -C $(KERNELDIR) M=$(CURRENT_PATH) modules

clean:
    make -C $(KERNELDIR) M=$(CURRENT_PATH) clean

編譯與加載

注意 insmod 需要 root 權限:

make
insmod buildchain.ko
insmod regchain.ko
insmod notify.ko

加載完成後,內核日誌中可以看到通知鏈的完整運行過程:

init_notifier
Begin to register:
register test_notifier1 completed
register test_notifier2 completed
register test_notifier3 completed
Begin to notify:
==============================
In Event 1: Event Number is 1
In Event 2: Event Number is 1
In Event 3: Event Number is 1
==============================

三個節點按注册順序被依次調用,通知鏈的閉環由此完成。理解了這套機制,再去看內核裡的 netdev_chain、cpufreq 通知等實際用例,就會清晰很多。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved