内核工作队列workqueue

    workqueue作为内核的重要基础组件,在内核中被广泛的使用,通过工作队列,可以很方便的把我们要执行的某个任务(即函数+上下文参数)交代给内核,由内核替我们执行。本文主要是介绍工作队列的使用,及其内部实现的逻辑。

    因为内核在系统初始化的时候,已为我们创建好了默认的工作队列,所以我们在使用的时候,可以不需要再创建工作队列,只需要创建工作,并将工作添加到工作队列上即可。当然,我们也可以创建自己的工作队列,而不使用内核创建好的工作队列。

    简单的理解,工作队列是由内核线程+链表+等待队列来实现的,即由一个内核线程不断的从链表中读取工作,然后执行工作的工作函数!

    一、工作的表示: struct work_struct

typedef void (*work_func_t)(struct work_struct *work);
struct work_struct {
    atomic_long_t data; /* 内核内部使用 */
    struct list_head entry; /* 用于链接到工作队列中*/
    work_func_t func; /* 工作函数*/
#ifdef CONFIG_LOCKDEP
    struct lockdep_map lockdep_map;
#endif
};

        从这个结构体可以看出,一个工作,就是一个待执行的工作函数,那如果我们要给工作函数传递参数,怎么解决呢?

    仔细观察工作函数的格式:参数是work_struct,所以在实际使用的时候,经常会在创建我们自己工作的时候,将此结构体嵌套在内部。然后在work_func函数内部通过container_of来得到我们自定义的工作,这样子就完成参数的传递了。

二、工作队列的常用接口: 在linux/kernel/workqueue.h

  1. 初始化工作:

#define __DELAYED_WORK_INITIALIZER(n, f) {          \
    .work = __WORK_INITIALIZER((n).work, (f)),      \
    .timer = TIMER_INITIALIZER(NULL, 0, 0),         \
    }

#define DECLARE_WORK(n, f)                  \
    struct work_struct n = __WORK_INITIALIZER(n, f)
    
// 也可以使用INIT_WORK宏:
#define INIT_WORK(_work, _func)                     \
    do {                                \
        (_work)->data = (atomic_long_t) WORK_DATA_INIT();   \
        INIT_LIST_HEAD(&(_work)->entry);            \
        PREPARE_WORK((_work), (_func));             \
    } while (0)

    主要是完成func成员的赋值。

    2. 工作入队: 添加到内核工作队列

int schedule_work(struct work_struct *work);

    3. 工作撤销: 从内核工作队列中删除

int cancel_work_sync(struct work_struct *work);

    4. 创建工作队列:

#ifdef CONFIG_LOCKDEP
#define __create_workqueue(name, singlethread, freezeable, rt)  \
({                              \
    static struct lock_class_key __key;         \
    const char *__lock_name;                \
                                \
    if (__builtin_constant_p(name))             \
        __lock_name = (name);               \
    else                            \
        __lock_name = #name;                \
                                \
    __create_workqueue_key((name), (singlethread),      \
                   (freezeable), (rt), &__key,  \
                   __lock_name);            \
})
#else
#define __create_workqueue(name, singlethread, freezeable, rt)  \
    __create_workqueue_key((name), (singlethread), (freezeable), (rt), \
                   NULL, NULL)
#endif

#define create_workqueue(name) __create_workqueue((name), 0, 0, 0)
#define create_rt_workqueue(name) __create_workqueue((name), 0, 0, 1)
#define create_freezeable_workqueue(name) __create_workqueue((name), 1, 1, 0)
#define create_singlethread_workqueue(name) __create_workqueue((name), 1, 0, 0)

    创建工作队列,最终调用的都是__create_workqueue_key()函数来完成,此函数返回的是struct workqueue_struct *,用于表示一个工作队列。

    5. 销毁工作队列:

void destroy_workqueue(struct workqueue_struct *wq);


    在介绍了上面的接口后,看一个简单的使用例子,这个例子使用的是内核已创建好的工作队列,要使用自己创建的工作队列,也是很简单的,看了后面的实现源码分析就清楚了。

#include <linux/module.h>
#include <linux/delay.h>
#include <linux/workqueue.h>

#define ENTER() printk(KERN_DEBUG "%s() Enter", __func__)
#define EXIT() printk(KERN_DEBUG "%s() Exit", __func__)
#define ERR(fmt, args...) printk(KERN_ERR "%s()-%d: " fmt "\n", __func__, __LINE__, ##args)
#define DBG(fmt, args...) printk(KERN_DEBUG "%s()-%d: " fmt "\n", __func__, __LINE__, ##args)

struct test_work {
	struct work_struct w;
	unsigned long data;
};

static struct test_work my_work;

static void my_work_func(struct work_struct *work)
{
	struct test_work *p_work;
	ENTER();
	p_work = container_of(work, struct test_work, w);
	while (p_work->data) {
		DBG("data: %lu", p_work->data--);
		msleep_interruptible(1000);
	}

	EXIT();
}

static int __init wq_demo_init(void)
{
	INIT_WORK(&my_work.w, my_work_func);
	my_work.data = 30;

	msleep_interruptible(1000);
	DBG("schedule work begin:");
	if (schedule_work(&my_work.w) == 0) {
		ERR("schedule work fail");
		return -1;
	}

	DBG("success");
	return 0;
}

static void __exit wq_demo_exit(void)
{
	ENTER();
	while (my_work.data) {
		DBG("waiting exit");
		msleep_interruptible(2000);
	}
	EXIT();
}

MODULE_LICENSE("GPL");
module_init(wq_demo_init);
module_exit(wq_demo_exit);

    

    下面就分析workqueue组件的源码实现,先从work_queue模块的初始化开始,然后再分析工作的注册过程,最后是工作如何被执行的。

三、workqueu的初始化:在kernel/workqueue.c

static DEFINE_SPINLOCK(workqueue_lock);  //全局的自旋锁,用于保证对全局链表workqueues的原子操作
static LIST_HEAD(workqueues); // 全局链表,用于链接所有的工作队列
static struct workqueue_struct *keventd_wq;

void __init init_workqueues(void)
{
    alloc_cpumask_var(&cpu_populated_map, GFP_KERNEL);

    cpumask_copy(cpu_populated_map, cpu_online_mask);
    singlethread_cpu = cpumask_first(cpu_possible_mask);
    cpu_singlethread_map = cpumask_of(singlethread_cpu);
    hotcpu_notifier(workqueue_cpu_callback, 0);
    keventd_wq = create_workqueue("events");                                                                                              
    BUG_ON(!keventd_wq);
}

    调用create_workqueue()函数创建了一个工作队列,名字为events。那就再看看工作队列是如何创建的:

    上面在介绍创建工作队列的接口时,有看到最终调用的都是__create_workqueue_key()函数的,在介绍这个函数之前,先看看struct workqueue_struct结构体的定义:在kernel/workqueue.c

struct workqueue_struct {                                                                                                                 
    struct cpu_workqueue_struct *cpu_wq;
    struct list_head list; // 用于链接到全局链表workqueues
    const char *name; //工作队列的名字,即内核线程的名字
    int singlethread;
    int freezeable;     /* Freeze threads during suspend */
    int rt;
#ifdef CONFIG_LOCKDEP
    struct lockdep_map lockdep_map;
#endif
};

struct cpu_workqueue_struct {

    spinlock_t lock; // 用于保证worklist链表的原子操作

    struct list_head worklist;  //用于保存添加的工作
    wait_queue_head_t more_work; // 等待队列,当worklist为空时,则会将内核线程挂起,存放与此链表中
    struct work_struct *current_work;  //保存内核线程当前正在执行的工作

    struct workqueue_struct *wq;
    struct task_struct *thread; // 内核线程
} ____cacheline_aligned;

    下面看一下创建函数的内部实现,这里要注意我们传递的参数:singlethread = 0, freezeable =0, rt = 0

struct workqueue_struct *__create_workqueue_key(const char *name,
                        int singlethread,
                        int freezeable,
                        int rt,
                        struct lock_class_key *key,
                        const char *lock_name)
{
    struct workqueue_struct *wq;
    struct cpu_workqueue_struct *cwq;
    int err = 0, cpu;

    wq = kzalloc(sizeof(*wq), GFP_KERNEL);
    if (!wq)
        return NULL;

    wq->cpu_wq = alloc_percpu(struct cpu_workqueue_struct);
    if (!wq->cpu_wq) {
        kfree(wq);
        return NULL;
    }

    wq->name = name;
    lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
    wq->singlethread = singlethread;
    wq->freezeable = freezeable;
    wq->rt = rt;
    INIT_LIST_HEAD(&wq->list);

    if (singlethread) {
        cwq = init_cpu_workqueue(wq, singlethread_cpu);
        err = create_workqueue_thread(cwq, singlethread_cpu); 
        start_workqueue_thread(cwq, -1);
    } else {
        cpu_maps_update_begin();
        /*
         * We must place this wq on list even if the code below fails.
         * cpu_down(cpu) can remove cpu from cpu_populated_map before
         * destroy_workqueue() takes the lock, in that case we leak
         * cwq[cpu]->thread.
         */
        spin_lock(&workqueue_lock);
        list_add(&wq->list, &workqueues);
        spin_unlock(&workqueue_lock);
        /*
         * We must initialize cwqs for each possible cpu even if we
         * are going to call destroy_workqueue() finally. Otherwise
         * cpu_up() can hit the uninitialized cwq once we drop the
         * lock.
         */
        for_each_possible_cpu(cpu) {
            cwq = init_cpu_workqueue(wq, cpu);
            if (err || !cpu_online(cpu))
                continue;
            err = create_workqueue_thread(cwq, cpu); /*创建内核线程*/
            start_workqueue_thread(cwq, cpu); /*启动内核线程*/
        }
        cpu_maps_update_done();
    }

    if (err) {
        destroy_workqueue(wq);
        wq = NULL;
    }
    return wq;
}

        主要的代码逻辑是创建一个struct workqueue_struct类型的对象,然后将此工作队列加入到workqueues链表中,最后是调用create_workqueue_thread()创建一个内核线程,并启动此线程。

    我们知道内核线程最主要的是它的线程函数,那么工作队列的线程函数时什么呢?

static int create_workqueue_thread(struct cpu_workqueue_struct *cwq, int cpu)
{
    struct sched_param param = { .sched_priority = MAX_RT_PRIO-1 };
    struct workqueue_struct *wq = cwq->wq;
    const char *fmt = is_wq_single_threaded(wq) ? "%s" : "%s/%d";
    struct task_struct *p;
    
    p = kthread_create(worker_thread, cwq, fmt, wq->name, cpu);
    /*
     * Nobody can add the work_struct to this cwq,
     *  if (caller is __create_workqueue)
     *      nobody should see this wq
     *  else // caller is CPU_UP_PREPARE
     *      cpu is not on cpu_online_map
     * so we can abort safely.
     */
    if (IS_ERR(p))
        return PTR_ERR(p);
    if (cwq->wq->rt)
        sched_setscheduler_nocheck(p, SCHED_FIFO, &param);
    cwq->thread = p;
    
    trace_workqueue_creation(cwq->thread, cpu);
    
    return 0;
}

static void start_workqueue_thread(struct cpu_workqueue_struct *cwq, int cpu)
{
    struct task_struct *p = cwq->thread;

    if (p != NULL) {
        if (cpu >= 0)
            kthread_bind(p, cpu);
        wake_up_process(p);
    }
}

        主要就是调用kthread_create()创建内核线程,线程函数为worker_thread,参数为cwq。start_workqueue_thread()函数就是调用wake_up_process()把内核线程加入到run queue中。

    下面就分析下线程函数worker_thread到底是怎么我们添加的工作的?

static int worker_thread(void *__cwq)
{
    struct cpu_workqueue_struct *cwq = __cwq;
    DEFINE_WAIT(wait);

    if (cwq->wq->freezeable)
        set_freezable();

    for (;;) {
        prepare_to_wait(&cwq->more_work, &wait, TASK_INTERRUPTIBLE);
        if (!freezing(current) &&
            !kthread_should_stop() &&
            list_empty(&cwq->worklist))
            schedule(); //若worklist链表为空,则进行调度
        finish_wait(&cwq->more_work, &wait);

        try_to_freeze();

        if (kthread_should_stop())
            break;

        run_workqueue(cwq);//执行队列中的工作
    }

    return 0;
}

        前面已经有文章分析了内核线程和等待队列waitqueue,了解这个的话,就很容易看懂这段代码,就是判断worklist队列是否为空,如果为空,则将当前内核线程挂起,否则就调用run_workqueue()去执行已添加注册的工作:

static void run_workqueue(struct cpu_workqueue_struct *cwq)
{
    spin_lock_irq(&cwq->lock);
    while (!list_empty(&cwq->worklist)) {
        struct work_struct *work = list_entry(cwq->worklist.next,
                        struct work_struct, entry);
        work_func_t f = work->func;
#ifdef CONFIG_LOCKDEP
        /*
         * It is permissible to free the struct work_struct
         * from inside the function that is called from it,
         * this we need to take into account for lockdep too.
         * To avoid bogus "held lock freed" warnings as well
         * as problems when looking into work->lockdep_map,
         * make a copy and use that here.
         */
        struct lockdep_map lockdep_map = work->lockdep_map;
#endif
        trace_workqueue_execution(cwq->thread, work);
        cwq->current_work = work; //保存当前工作到current_work
        list_del_init(cwq->worklist.next); // 将此工作从链表中移除
        spin_unlock_irq(&cwq->lock);

        BUG_ON(get_wq_data(work) != cwq);
        work_clear_pending(work);
        lock_map_acquire(&cwq->wq->lockdep_map);
        lock_map_acquire(&lockdep_map);
        f(work); //执行工作函数
        lock_map_release(&lockdep_map);
        lock_map_release(&cwq->wq->lockdep_map);

        if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
            printk(KERN_ERR "BUG: workqueue leaked lock or atomic: "
                    "%s/0x%08x/%d\n",
                    current->comm, preempt_count(),
                        task_pid_nr(current));
            printk(KERN_ERR "    last function: ");
            print_symbol("%s\n", (unsigned long)f);
            debug_show_held_locks(current);
            dump_stack();
        }

        spin_lock_irq(&cwq->lock);
        cwq->current_work = NULL;
    }
    spin_unlock_irq(&cwq->lock);
}

    上面的注释已经说明清楚代码的逻辑了,这里就不在解释了。

四、添加工作到内核工作队列中:

    上面提到了,当工作队列中的worklist链表为空,及没有需要执行的工作,怎会将工作队列所在的内核线程挂起,那么什么时候会将其唤醒呢?肯定就是当有工作添加到链表的时候,即调用schedule_work()的时候:

int schedule_work(struct work_struct *work)
{
    return queue_work(keventd_wq, work); // 将工作添加到内核提我们创建好的工作队列中
}

    前面在初始化的时候,就将内核创建的工作队列保存在keventd_wq变量中。

/**
 * queue_work - queue work on a workqueue
 * @wq: workqueue to use
 * @work: work to queue
 *
 * Returns 0 if @work was already on a queue, non-zero otherwise.
 *
 * We queue the work to the CPU on which it was submitted, but if the CPU dies
 * it can be processed by another CPU.
 */
int queue_work(struct workqueue_struct *wq, struct work_struct *work)                                                                     
{
    int ret;

    ret = queue_work_on(get_cpu(), wq, work);
    put_cpu();

    return ret;
}

int queue_work_on(int cpu, struct workqueue_struct *wq, struct work_struct *work)
{
    int ret = 0;

    if (!test_and_set_bit(WORK_STRUCT_PENDING, work_data_bits(work))) {
        BUG_ON(!list_empty(&work->entry));
        __queue_work(wq_per_cpu(wq, cpu), work);
        ret = 1;
    }
    return ret;
}

static void __queue_work(struct cpu_workqueue_struct *cwq, struct work_struct *work)
{
    unsigned long flags;

    spin_lock_irqsave(&cwq->lock, flags); //加锁,保证insert_work原子操作
    insert_work(cwq, work, &cwq->worklist);
    spin_unlock_irqrestore(&cwq->lock, flags); //解锁
}

static void insert_work(struct cpu_workqueue_struct *cwq, struct work_struct *work, struct list_head *head)
{
    trace_workqueue_insertion(cwq->thread, work);
    
    set_wq_data(work, cwq);
    /*
     * Ensure that we get the right work->data if we see the
     * result of list_add() below, see try_to_grab_pending().
     */
    smp_wmb();
    list_add_tail(&work->entry, head); //加入到worklist链表
    wake_up(&cwq->more_work); //唤醒在more_work等待链表上的任务,即工作队列线程
}

五、使用自定义工作队列:

    通过上面的分析,创建 工作队列最基本的接口时create_workqueue()。当我们要把工作放入到自定义的工作队列时,使用如下接口:

int queue_work(struct workqueue_struct *wq, struct work_struct *work);

    在上面的分析中,其实已经使用了此接口,只不过我们调用schedule_work()的时候,wq参数为内核已创建好的工作队列keventd_wq。





转载于:https://my.oschina.net/kaedehao/blog/631394

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值