Linux中的通知链技术

    技术2025-09-27  82

    Linux中的通知链技术

    Linux 内核中,各个子系统之间 有很强的相互关系,某些子系统可能对其它子系统产生的事件感兴趣。为了让某个子系统在发生某个事件时通知感兴趣的子系统, Linux 内核引入了通知链技术。通知链只能够在内核的子系统之间使用,而不能够在内核和用户空间进行 事件的通知。

    数据结构:

    通 知链有四种类型

    · 原子通知链( Atomic notifier chains  ):通知链元素的回调函数(当事件发生时要执行的函数)只能在中断上下文中运行,不允许阻塞 。对应的链表头结构:

    struct atomic_notifier_head {

    spinlock_t lock;

    struct notifier_block *head;

    };

    · 可阻塞通知链( Blocking notifier chains  ):通知链元素的回调函数在进程上下文中运行,允许阻塞 。对应的链表头:

    struct blocking_notifier_head {

    struct rw_semaphore rwsem;

    struct notifier_block *head;

    };

    · 原始通知链( Raw notifier chains  ):对通知链元素的回调函数没有任何限制,所有锁和保护机制都由调用者维护 。对应的链表头:

    struct raw_notifier_head {

    struct notifier_block *head;

    };

    · SRCU 通知链(  SRCU notifier chains  ):可阻 塞通知链的一种变体 。对应的链表头:

    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 是这个通知的优先级,同一条链上的 notifier_block{} 是按优先级排列的。内核代码中一般把通知链命名为 xxx_chain, xxx_nofitier_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  函数通知事件的到达,这个函数会遍历通知链中所有的元素,然后依次调用每一个的回调函数(即完成通 知动作)

    /**

     * notifier_call_chain - Informs the registered notifiers about an event.

     * @nl: Pointer to head of the blocking notifier chain

     * @val: Value passed unmodified to notifier function

     * @v: Pointer passed unmodified to notifier function

     * @nr_to_call: Number of notifier functions to be called. Don't care

     * value of this parameter is -1.

     * @nr_calls: Records the number of notifications sent. Don't care

     * value of this field is NULL.

     * @returns: notifier_call_chain returns the value returned by the

     * last notifier function called.

     */

    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);

     

    #ifdef CONFIG_DEBUG_NOTIFIERS

    if (unlikely(!func_ptr_is_kernel_text(nb->notifier_call))) {

    WARN(1, "Invalid notifier called!");

    nb = next_nb;

    continue;

    }

    #endif

    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 用来指向通知链上的函数执行时需要用到的参 数,一般不同的通知链,参数类型也不一样,例如当通知一个网卡被注册时, v 就指向 net_device 结构, nr_to_call 表示准备最多通知几个, -1 表示整条链都通知, nr_calls 非空的话,返回通知了多少 个。

    每个被执行的notifier_block 回调函数的返回值可能取值为以下几个:

    ·NOTIFY_DONE :表示对相关的事件类型不关心

    ·NOTIFY_OK :顺利执行

    ·NOTIFY_BAD :执行有错

    ·NOTIFY_STOP :停止执行后面的回调函数

    ·NOTIFY_STOP_MASK :停止执行的掩码

    Notifier_call_chain()把最后一个被调用的回调函数的返回值作为它的返回值。

     

    内核网络代码中对通知链的使用

    内核网络部分使用的一些通知 链:

    ·inetaddr_chain ipv4 地址变动时的通知链

    ·netdev_chain :网络设备状态变动时的通知链

    网络代码中对通知链的调用一般 都有一个包装函数,例如对netdev_chain 的注册就是由 register_netdevice_notifier() 函数完成的:

    int register_netdevice_notifier(struct notifier_block *nb)

    {

    struct net_device *dev;

    struct net_device *last;

    struct net *net;

    int err;

     

    rtnl_lock();

    err = raw_notifier_chain_register(&netdev_chain, nb);

    if (err)

    goto unlock;

    if (dev_boot_phase)

    goto unlock;

    for_each_net(net) {

    for_each_netdev(net, dev) {

    err = nb->notifier_call(nb, NETDEV_REGISTER, dev);

    err = notifier_to_errno(err);

    if (err)

    goto rollback;

     

    if (!(dev->flags & IFF_UP))

    continue;

     

    nb->notifier_call(nb, NETDEV_UP, dev);

    }

    }

     

    unlock:

    rtnl_unlock();

    return err;

     

    rollback:

    last = dev;

    for_each_net(net) {

    for_each_netdev(net, dev) {

    if (dev == last)

    break;

     

    if (dev->flags & IFF_UP) {

    nb->notifier_call(nb, NETDEV_GOING_DOWN, dev);

    nb->notifier_call(nb, NETDEV_DOWN, dev);

    }

    nb->notifier_call(nb, NETDEV_UNREGISTER, dev);

    }

    }

     

    raw_notifier_chain_unregister(&netdev_chain, nb);

    goto unlock;

    }

     

    这个函数主要完成两件事情:

    1) 把参数struct notifier_block *nb 注册到 netdev_chain 通知链上;

    2) 系统中所有已经被注册过的或者激活的网络设备的事件都 要被新增的这个通知的回调函数重新调用一遍,使设备更新到一个完整的状态。

    dev_boot_phase定义如下,表示在启动阶段。

    static int dev_boot_phase = 1;

    例如,在启动阶段的网络模块初 始化过程中,有一个调用过程inet_init()-->ip_init()-->ip_rt_init()-->devinet_init() ,会注册一个 ip_netdev_notifier 通知链:

    register_netdevice_notifier(&ip_netdev_notifier);

    ip_netdev_notifier 定义为:

    static struct notifier_block ip_netdev_notifier = {

    .notifier_call = inetdev_event,

    };

    inetdev_event()实现为:

    static int inetdev_event(struct notifier_block *this, unsigned long event,

     void *ptr)

    {

    struct net_device *dev = ptr;

    struct in_device *in_dev = __in_dev_get_rtnl(dev);

     

    ASSERT_RTNL();

     

    if (!in_dev) {

    if (event == NETDEV_REGISTER) {

    in_dev = inetdev_init(dev);

    if (!in_dev)

    return notifier_from_errno(-ENOMEM);

    if (dev->flags & IFF_LOOPBACK) {

    IN_DEV_CONF_SET(in_dev, NOXFRM, 1);

    IN_DEV_CONF_SET(in_dev, NOPOLICY, 1);

    }

    } else if (event == NETDEV_CHANGEMTU) {

    /* Re-enabling IP */

    if (inetdev_valid_mtu(dev->mtu))

    in_dev = inetdev_init(dev);

    }

    goto out;

    }

     

    switch (event) {

    case NETDEV_REGISTER:

    printk(KERN_DEBUG "inetdev_event: bug/n");

    dev->ip_ptr = NULL;

    break;

    case NETDEV_UP:

    if (!inetdev_valid_mtu(dev->mtu))

    break;

    if (dev->flags & IFF_LOOPBACK) {

    struct in_ifaddr *ifa;

    if ((ifa = inet_alloc_ifa()) != NULL) {

    ifa->ifa_local =

      ifa->ifa_address = htonl(INADDR_LOOPBACK);

    ifa->ifa_prefixlen = 8;

    ifa->ifa_mask = inet_make_mask(8);

    in_dev_hold(in_dev);

    ifa->ifa_dev = in_dev;

    ifa->ifa_scope = RT_SCOPE_HOST;

    memcpy(ifa->ifa_label, dev->name, IFNAMSIZ);

    inet_insert_ifa(ifa);

    }

    }

    ip_mc_up(in_dev);

    /* fall through */

    case NETDEV_CHANGEADDR:

    if (IN_DEV_ARP_NOTIFY(in_dev))

    arp_send(ARPOP_REQUEST, ETH_P_ARP,

     in_dev->ifa_list->ifa_address,

     dev,

     in_dev->ifa_list->ifa_address,

     NULL, dev->dev_addr, NULL);

    break;

    case NETDEV_DOWN:

    ip_mc_down(in_dev);

    break;

    case NETDEV_CHANGEMTU:

    if (inetdev_valid_mtu(dev->mtu))

    break;

    /* disable IP when MTU is not enough */

    case NETDEV_UNREGISTER:

    inetdev_destroy(in_dev);

    break;

    case NETDEV_CHANGENAME:

    /* Do not notify about label change, this event is

     * not interesting to applications using netlink.

     */

    inetdev_changename(dev, in_dev);

     

    devinet_sysctl_unregister(in_dev);

    devinet_sysctl_register(in_dev);

    break;

    }

    out:

    return NOTIFY_DONE;

    }

    在注册的时候传递的是 NETDEV_REGISTER 事件,所以在in_dev 不为空时,只做 switch 语句中的一个动作: dev->ip_ptr = NULL ;在 in_dev 为空时,调用 inetdev_init() 函数分配一个 struct in_device ,此时如果是 Loopback 设备才有动作了。

     

    举例 

    这个例子由参考文章二给出。

       在这里,写了一个简单的通 知链表的代码。   实际上,整个通知链的编写也就两个过程:     首先是定义自己的 通知链的头节点,并将要执行的函数注册到自己的通知链中。     其次则是由另外的子系统来通知这个链,让其上面注册的函数运行。     这里将第一个过程 分成了两步来写,第一步是定义了头节点和一些自定义的注册函数(针对该头节点的),第二步则是使用自定义的注册函数注册了一些通知链节点。分别在代码buildchain.c regchain.c 中。     发送通知信息的代 码为notify.c 代码1 buildchain.c     它的作用是自定义 一个通知链表test_chain ,然后再自定义两个函数分别向这个通知链中加入或删除节点,最后再定义一个函数通知这个 test_chain 链。

    #include <asm/uaccess.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/notifier.h> #include <linux/init.h> #include <linux/types.h> #include <linux/module.h> MODULE_LICENSE("GPL"); /* 定义自己的通知链头结点以及注册和卸载通知链的外包函数 */ /* * RAW_NOTIFIER_HEAD是定义一个通知链的头部结点, 通过这个头部结点可以找到这个链中的其它所有的 notifier_block */ static RAW_NOTIFIER_HEAD(test_chain); /* 自定义的注册函数,将 notifier_block 节点 加到刚刚定义的 test_chain 这个链表中来 * raw_notifier_chain_register会调用 notifier_chain_register */ 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); /* 自定义的通知链表的函数,即通知 test_chain 指向的链表 中的所有节点执行相应的函数 */ 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); /* * init and exit  */ 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);

     

    代码2 regchain.c     该代码的作用是将test_notifier1 test_notifier2 test_notifier3 这三个节点加到之前定义的 test_chain 这个通知链表 上,同时每个节点都注册了一个函数。

    #include <asm/uaccess.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/notifier.h> #include <linux/init.h> #include <linux/types.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;  } /* 事件 1 ,该节点执行的函数为 test_event1 */ static struct notifier_block test_notifier1 = {         .notifier_call = test_event1, }; /* 事件 2 ,该节点执行的函数为 test_event1 */ static struct notifier_block test_notifier2 = {         .notifier_call = test_event2, }; /* 事件 3 ,该节点执行的函数为 test_event1 */ 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)         {                 printk("register test_notifier1 error/n");                 return -1;          }         printk("register test_notifier1 completed/n");         err = register_test_notifier(&test_notifier2);         if (err)         {                 printk("register test_notifier2 error/n");                 return -1;          }         printk("register test_notifier2 completed/n");         err = register_test_notifier(&test_notifier3);         if (err)         {                 printk("register test_notifier3 error/n");                 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);

     

    代码3 notify.c     该代码的作用就是 向test_chain 通知链中发送消息,让链中的函数运行。

    #include <asm/uaccess.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/notifier.h> #include <linux/init.h> #include <linux/types.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"); /* 调用自定义的函数,向 test_chain 链发送消息 */         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文件(我修改了)

    注意,记得先检查有没有安装 当前linux 版本的内核头文件:

    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

     

    这样就可以看到通知链运行的 效果了 下面是我在自己的机器上面运行得到的结果(dmesg 命令) :

    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 ==============================

    参考文章:

    http://hi.baidu.com/mczyh/blog/item/80f4200098588c087bec2ce8.html

    http://www.yuanma.org/data/2009/0427/article_3645.htm

    http://blog.chinaunix.net/u2/67414/showart_1993495.html

    最新回复(0)