转自:https://www.cnblogs.com/arnoldlu/p/8659988.html

目录:

Linux中断管理

Linux中断管理 (1)Linux中断管理机制

Linux中断管理 (2)软中断和tasklet

Linux中断管理 (3)workqueue工作队列

关键词:

工作队列的原理是把work(需要推迟执行的函数)交由一个内核线程来执行,它总是在进程上下文中执行。

工作队列的优点是利用进程上下文来执行中断下半部操作,因此工作队列允许重新调度和睡眠,是异步执行的进程上下文,它还能解决软中断和tasklet执行时间过长导致系统实时性下降等问题。

当驱动程序或者内核子系统在进程上下文中有异步执行的工作任务时,可以使用work item来描述工作任务,包括该工作任务的执行回调函数,把work item添加到一个队列中,然后一个内核线程回去执行这个工作任务的回调函数。

这里work item被称为工作,队列被称为workqueue,即工作队列,内核线程被称为worker。

CMWQ(Concurrency Managed Workqueues)

执行work item任务的线程被称为worker或者工作线程。工作线程会串行化地执行挂入到队列中所有的work item。如果队列中没有work,那么该工作线程就会变成idle态。

为了管理众多工作线程,CMWQ提出了工作线程池(worker-pool)概念,worker-pool有两种:

一是bound型,可以理解为Per-CPU类型,每个CPU都有worker-pool;

另一种是unbound型,即不和具体CPU绑定。

这两种worker-pool都会定义两个线程池,一个给普通优先级的work使用,另一个给高优先级的work使用。

1. 初始化工作队列

1.1 工作、工作队列、工作线程池、工作线程数据结构

workqueue机制最小的调度单元是work_struct,即工作任务。

  1. struct work_struct {
  2. atomic_long_t data;---------------低比特位部分是work的标志位,剩余比特位通常用于存放上一次运行的worker_pool IDpool_workqueue的指针。存放的内容有WORK_STRUCT_PWQ标志位来决定
  3. struct list_head entry;-----------用于把work挂到其他队列上。
  4. work_func_t func;-----------------工作任务的处理函数
  5. #ifdef CONFIG_LOCKDEP
  6. struct lockdep_map lockdep_map;
  7. #endif
  8. }

工作队列由struct workqueue_struct数据结构描述:

  1. struct workqueue_struct {
  2. struct list_head pwqs; /* WR: all pwqs of this wq */--------------------该workqueue所在的所有pool_workqueue链表
  3. struct list_head list; /* PL: list of all workqueues */-----------------系统所有workqueue_struct的全局链表
  4.  
  5. struct mutex mutex; /* protects this wq */
  6. int work_color; /* WQ: current work color */
  7. int flush_color; /* WQ: current flush color */
  8. atomic_t nr_pwqs_to_flush; /* flush in progress */
  9. struct wq_flusher *first_flusher; /* WQ: first flusher */
  10. struct list_head flusher_queue; /* WQ: flush waiters */
  11. struct list_head flusher_overflow; /* WQ: flush overflow list */
  12.  
  13. struct list_head maydays; /* MD: pwqs requesting rescue */-------------------所有rescue状态下的pool_workqueue数据结构链表
  14. struct worker *rescuer; /* I: rescue worker */---------------------------rescue内核线程,内存紧张时创建新的工作线程可能会失败,如果创建workqueue是设置了WQ_MEM_RECLAIM,那么rescuer线程会接管这种情况。
  15.  
  16. int nr_drainers; /* WQ: drain in progress */
  17. int saved_max_active; /* WQ: saved pwq max_active */
  18.  
  19. struct workqueue_attrs *unbound_attrs; /* WQ: only for unbound wqs */---------UNBOUND类型属性
  20. struct pool_workqueue *dfl_pwq; /* WQ: only for unbound wqs */----------------unbound类型的pool_workqueue
  21.  
  22. #ifdef CONFIG_SYSFS
  23. struct wq_device *wq_dev; /* I: for sysfs interface */
  24. #endif
  25. #ifdef CONFIG_LOCKDEP
  26. struct lockdep_map lockdep_map;
  27. #endif
  28. char name[WQ_NAME_LEN]; /* I: workqueue name */--------------------------该workqueue的名字
  29.  
  30. /* hot fields used during command issue, aligned to cacheline */
  31. unsigned int flags ____cacheline_aligned; /* WQ: WQ_* flags */---------------经常被不同CUP访问,因此要和cache line对齐。
  32. struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */---------------------指向per-cpu类型的pool_workqueue
  33. struct pool_workqueue __rcu *numa_pwq_tbl[]; /* FR: unbound pwqs indexed by node */
  34. }

运行work_struct的内核线程被称为worker,即工作线程。

  1. /*
  2. * The poor guys doing the actual heavy lifting. All on-duty workers are
  3. * either serving the manager role, on idle list or on busy hash. For
  4. * details on the locking annotation (L, I, X...), refer to workqueue.c.
  5. *
  6. * Only to be used in workqueue and async.
  7. */
  8. struct worker {
  9. /* on idle list while idle, on busy hash table while busy */
  10. union {
  11. struct list_head entry; /* L: while idle */
  12. struct hlist_node hentry; /* L: while busy */
  13. };
  14.  
  15. struct work_struct *current_work; /* L: work being processed */----当前正在处理的work
  16. work_func_t current_func; /* L: current_work's fn */-----------当前正在执行的work回调函数
  17. struct pool_workqueue *current_pwq; /* L: current_work's pwq */-------当前work所属的pool_workqueue
  18. bool desc_valid; /* ->desc is valid */
  19. struct list_head scheduled; /* L: scheduled works */---------------所有被调度并正准备执行的work_struct都挂入该链表中
  20.  
  21. /* 64 bytes boundary on 64bit, 32 on 32bit */
  22.  
  23. struct task_struct *task; /* I: worker task */-----------------该工作线程的task_struct数据结构
  24. struct worker_pool *pool; /* I: the associated pool */---------该工作线程所属的worker_pool
  25. /* L: for rescuers */
  26. struct list_head node; /* A: anchored at pool->workers */------可以把该worker挂入到worker_pool->workers链表中
  27. /* A: runs through worker->node */
  28.  
  29. unsigned long last_active; /* L: last active timestamp */
  30. unsigned int flags; /* X: flags */
  31. int id; /* I: worker id */
  32.  
  33. /*
  34. * Opaque string set with work_set_desc(). Printed out with task
  35. * dump for debugging - WARN, BUG, panic or sysrq.
  36. */
  37. char desc[WORKER_DESC_LEN];
  38.  
  39. /* used only by rescuers to point to the target workqueue */
  40. struct workqueue_struct *rescue_wq; /* I: the workqueue to rescue */
  41. }

CMWQ提出了工作线程池的概念,struct worker_pool数据结构用于描述工作线程池。

worker_pool是per-cpu变量,每个CPU都有worker_pool,而且有两个worker_pool。

一个用于普通优先级工作线程,另一个用于高优先级工作线程。

  1. struct worker_pool {
  2. spinlock_t lock; /* the pool lock */-----------------------用于保护worker_pool的自旋锁
  3. int cpu; /* I: the associated cpu */-------------------对于unbound类型为-1;对于bound类型workqueue表示绑定的CPU ID
  4. int node; /* I: the associated node ID */
  5. int id; /* I: pool ID */-------------------------------该worker_poolID
  6. unsigned int flags; /* X: flags */
  7.  
  8. struct list_head worklist; /* L: list of pending works */----------挂入pending状态的work_struct
  9. int nr_workers; /* L: total number of workers */-----------工作线程的数量
  10.  
  11. /* nr_idle includes the ones off idle_list for rebinding */
  12. int nr_idle; /* L: currently idle ones */------------------处于idle状态的工作线程的数量
  13.  
  14. struct list_head idle_list; /* X: list of idle workers */----------处于idle状态的工作线程链表
  15. struct timer_list idle_timer; /* L: worker idle timeout */
  16. struct timer_list mayday_timer; /* L: SOS timer for workers */
  17.  
  18. /* a workers is either on busy_hash or idle_list, or the manager */
  19. DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
  20. /* L: hash of busy workers */
  21.  
  22. /* see manage_workers() for details on the two manager mutexes */
  23. struct mutex manager_arb; /* manager arbitration */
  24. struct mutex attach_mutex; /* attach/detach exclusion */
  25. struct list_head workers; /* A: attached workers */---------------该worker_pool管理的工作线程链表
  26. struct completion *detach_completion; /* all workers detached */
  27.  
  28. struct ida worker_ida; /* worker IDs for task name */
  29.  
  30. struct workqueue_attrs *attrs; /* I: worker attributes */-----工作线程属性
  31. struct hlist_node hash_node; /* PL: unbound_pool_hash node */
  32. int refcnt; /* PL: refcnt for unbound pools */
  33.  
  34. /*
  35. * The current concurrency level. As it's likely to be accessed
  36. * from other CPUs during try_to_wake_up(), put it in a separate
  37. * cacheline.
  38. */
  39. atomic_t nr_running ____cacheline_aligned_in_smp;----------------用于管理worker的创建和销毁的统计计数,表示运行中的worker数量。该变量可能被多CPU同时访问,因此独占一个缓存行,避免多核读写造成“颠簸”现象。
  40.  
  41. /*
  42. * Destruction of pool is sched-RCU protected to allow dereferences
  43. * from get_work_pool().
  44. */
  45. struct rcu_head rcu;---------------------------------------------RCU
  46. }

struct pool_workqueue用于链接workqueue和worker_pool。

  1. struct pool_workqueue {
  2. struct worker_pool *pool; /* I: the associated pool */-----------指向worker_pool结构
  3. struct workqueue_struct *wq; /* I: the owning workqueue */----------指向workqueue_struct结构
  4. int work_color; /* L: current color */
  5. int flush_color; /* L: flushing color */
  6. int refcnt; /* L: reference count */
  7. int nr_in_flight[WORK_NR_COLORS];
  8. /* L: nr of in_flight works */
  9. int nr_active; /* L: nr of active works */------------------活跃的work_strcut数量
  10. int max_active; /* L: max active works */-------------------最大活跃work_struct数量
  11. struct list_head delayed_works; /* L: delayed works */--------------延迟执行work_struct链表
  12. struct list_head pwqs_node; /* WR: node on wq->pwqs */
  13. struct list_head mayday_node; /* MD: node on wq->maydays */
  14.  
  15. /*
  16. * Release of unbound pwq is punted to system_wq. See put_pwq()
  17. * and pwq_unbound_release_workfn() for details. pool_workqueue
  18. * itself is also sched-RCU protected so that the first pwq can be
  19. * determined without grabbing wq->mutex.
  20. */
  21. struct work_struct unbound_release_work;
  22. struct rcu_head rcu;------------------------------------------------RCU
  23. }

 上面几个数据结构的关系图?

1.2 初始化工作队列

首先看一下对创建工作队列有重要影响的flags。

  1. /*
  2. * Workqueue flags and constants. For details, please refer to
  3. * Documentation/workqueue.txt.
  4. */
  5. enum {
  6. WQ_UNBOUND = 1 << 1, /* not bound to any cpu */-----------------绑定到某一个CPU执行
  7. WQ_FREEZABLE = 1 << 2, /* freeze during suspend */--------------在suspend进行进程冻结的时候,需要让工作线程完成当前所有的work才完成进程冻结,并且这个过程不会再新开始一个work的执行,知道进程被解冻。
  8. WQ_MEM_RECLAIM = 1 << 3, /* may be used for memory reclaim */---在内存紧张导致创建新进程失败,系统通过rescuer内核线程去接管这种情况。
  9. WQ_HIGHPRI = 1 << 4, /* high priority */------------------------属于高于高优先级的worker_pool
  10. WQ_CPU_INTENSIVE = 1 << 5, /* cpu intensive workqueue */------------属于特别消耗CPU资源的一类work,这个work执行会得到调度器的监管,排在这类work后的non-CPU-intensive类型work可能会推迟执行
  11. WQ_SYSFS = 1 << 6, /* visible in sysfs, see wq_sysfs_register() */
  12.  
  13. WQ_POWER_EFFICIENT = 1 << 7,-----------------根据wq_power_efficient来决定此类型的工作队列是bound还是unbound类型,bound型可能导致处于idleCPU被唤醒,而unbound型则不会必然唤醒idleCPU
  14.  
  15. __WQ_DRAINING = 1 << 16, /* internal: workqueue is draining */
  16. __WQ_ORDERED = 1 << 17, /* internal: workqueue is ordered */----表示同一时间只能执行一个work_item
  17. __WQ_ORDERED_EXPLICIT = 1 << 19, /* internal: alloc_ordered_workqueue() */
  18.  
  19. WQ_MAX_ACTIVE = 512, /* I like 512, better ideas? */
  20. WQ_MAX_UNBOUND_PER_CPU = 4, /* 4 * #cpus for unbound wq */
  21. WQ_DFL_ACTIVE = WQ_MAX_ACTIVE / 2,
  22. };

内核启动的时候,调用init_workqueues()创建工作线程,同时创建了一些常用的工作队列。

init_workqueues()由early_initcall(init_workqueues)在early阶段调用。

1.2.1 谁?都创建了哪些工作线程?

对于4核SMP系统来说,必然创建的工作线程有:每个CPU的kworker/x:0、kworker/x:0H、以及unbound类型的kworker/u8:0。

init_workqueues()创建CPU0以及unbound工作线程

kworker/0:0和kworker/0:0H以及kworker/u8:0都是由init_workqueues创建的,调用轨迹如下。

kworker/0:0、kworker/0:0H:kernel_init()->kernel_init_freeable()->do_one_initcall()->init_workqueues()->create_worker()

kworker/u8:0:kernel_init()->kernel_init_freeable()->do_one_inicall->init_workqueues()->__alloc_workqueue_key()->apply_workqueue_attrs()->alloc_unbound_pwq()->create_worker()

对于unbound工作线程的创建是因为init_workqueues()中创建了一系列的workqueue,调用alloc_workqueue()->__allow_workqueue_key()->alloc_and_link_pwqs()->apply_workqueue_attrs()->alloc_unbound_pwq()导致的。

这里的init_workqueues()为什么不将CPU1~3的工作线程一起创建了?

虽然此处init_workqueues()是在do_one_initcall中执行,但是此处的do_one_initcall较特殊。

  1. static noinline void __init kernel_init_freeable(void)
  2. {
  3. ...
  4. smp_prepare_cpus(setup_max_cpus);
  5.  
  6. do_pre_smp_initcalls();-------------------------------------此处调用的initcall是在__initcall_start~__initcall0_start之间的函数,也即early_initcall()。所以init_workqueues()在smp_init之前被调用。
  7. lockup_detector_init();
  8.  
  9. smp_init();
  10. sched_init_smp();-------------------------------------------将剩余CPU1~3进行up操作。
  11.  
  12. do_basic_setup();-------------------------------------------执行__initcall_0start之后的initcall函数
  13. ...
  14. }

在初始化pool的时候,是按照possible的CPU来进行初始化的。而在创建工作线程的时候是按照online的CPU来创建的。

在init_workqueues()的时刻,CPU1~3还没有online。所以会先创建kworker/0:0、kworker/0:0H、kworker/u8:0三个工作线程。

unbound工作线程的pool->id为8也就不难理解了,因为前面4和分配个0~7。

workqueue_cpu_up_callback()创建了其他CPU工作线程

kernel_init()->kernel_init_freeable()->smp_init()->cpu_up()->_cpu_up()->__raw_notifier_call_chain()->workqueue_cpu_up_callback()->create_worker()

在init_workqueues()开头就注册了CPU_PRI_WORKQUEUE_UP处理函数,所以在smp_init()->cpu_up()将CPU启动之后就会为每个CPU创建两个工作线程

1.2.2 init_workqueues()初始化worker_pool、worker、workqueue

  1. static int __init init_workqueues(void)
  2. {
  3. int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };---------------这里HIGHPRI_NICE_LEVEL为-20,对应的prio100,是普通进程里面的最高优先级。
  4. int i, cpu;
  5.  
  6. WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
  7.  
  8. pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
  9.  
  10. cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);--------------跟随CPU_UP/CPU_DOWN动态创建工作线程的接口。
  11. hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
  12.  
  13. wq_numa_init();
  14.  
  15. /* initialize CPU pools */
  16. for_each_possible_cpu(cpu) {------------------------------------------------遍历每个possible状态的CPU
  17. struct worker_pool *pool;
  18.  
  19. i = 0;
  20. for_each_cpu_worker_pool(pool, cpu) {-----------------------------------每个CPU两个worker_poo,分别对应per-cpu变量cpu_worker_pool[0]和cpu_worker_pool[1]
  21. BUG_ON(init_worker_pool(pool));-------------------------------------初始化worker_pool
  22. pool->cpu = cpu;
  23. cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
  24. pool->attrs->nice = std_nice[i++];----------------------------------设置nice
  25. pool->node = cpu_to_node(cpu);
  26.  
  27. /* alloc pool ID */
  28. mutex_lock(&wq_pool_mutex);
  29. BUG_ON(worker_pool_assign_id(pool));
  30. mutex_unlock(&wq_pool_mutex);
  31. }
  32. }
  33.  
  34. /* create the initial worker */
  35. for_each_online_cpu(cpu) {--------------------------------------------------遍历所有online状态CPU,对于SMP多核CPU,支队boot cpu创建了工作线程。其他CPU工作线程稍后再cpu_up中创建。
  36. struct worker_pool *pool;
  37.  
  38. for_each_cpu_worker_pool(pool, cpu) {-----------------------------------使用create_worker对每个worker_pool创建两个内核线程对应cpu_worker_pool[0]和cpu_worker_pool[1]
  39. pool->flags &= ~POOL_DISASSOCIATED;
  40. BUG_ON(!create_worker(pool));
  41. }
  42. }
  43.  
  44. /* create default unbound and ordered wq attrs */
  45. for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
  46. struct workqueue_attrs *attrs;
  47.  
  48. BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
  49. attrs->nice = std_nice[i];
  50. unbound_std_wq_attrs[i] = attrs;---------------------------------------设置Unbound类型workqueue的属性
  51.  
  52. /*
  53. * An ordered wq should have only one pwq as ordering is
  54. * guaranteed by max_active which is enforced by pwqs.
  55. * Turn off NUMA so that dfl_pwq is used for all nodes.
  56. */
  57. BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
  58. attrs->nice = std_nice[i];
  59. attrs->no_numa = true;
  60. ordered_wq_attrs[i] = attrs;-------------------------------------------设置ordered类型workqueue的属性,ordered类型workqueue同一时刻只能有一个work item在运行。
  61. }
  62.  
  63. system_wq = alloc_workqueue("events", 0, 0);-------------------------------普通优先级bound类型工作队列system_wq
  64. system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);------高优先级bound类型工作队列system_highpri_wq
  65. system_long_wq = alloc_workqueue("events_long", 0, 0);---------------------
  66. system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,----------普通优先级unbound类型工作队列system_unbound_wq
  67. WQ_UNBOUND_MAX_ACTIVE);
  68. system_freezable_wq = alloc_workqueue("events_freezable",------------------freezable类型工作队列system_freezable_wq
  69. WQ_FREEZABLE, 0);
  70. system_power_efficient_wq = alloc_workqueue("events_power_efficient",------省电类型的工作队列system_power_efficient_wq
  71. WQ_POWER_EFFICIENT, 0);
  72. system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
  73. WQ_FREEZABLE | WQ_POWER_EFFICIENT,-------------------freezable并且省电类型的工作队列system_freezable_power_efficient_wq
  74. 0);
  75. BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
  76. !system_unbound_wq || !system_freezable_wq ||
  77. !system_power_efficient_wq ||
  78. !system_freezable_power_efficient_wq);
  79. return 0;
  80. }
  1. static int workqueue_cpu_up_callback(struct notifier_block *nfb,
  2. unsigned long action,
  3. void *hcpu)
  4. {
  5. int cpu = (unsigned long)hcpu;
  6. struct worker_pool *pool;
  7. struct workqueue_struct *wq;
  8. int pi;
  9.  
  10. switch (action & ~CPU_TASKS_FROZEN) {
  11. case CPU_UP_PREPARE:
  12. for_each_cpu_worker_pool(pool, cpu) {
  13. if (pool->nr_workers)
  14. continue;
  15. if (!create_worker(pool))
  16. return NOTIFY_BAD;
  17. }
  18. break;
  19.  
  20. case CPU_DOWN_FAILED:
  21. case CPU_ONLINE:
  22. mutex_lock(&wq_pool_mutex);
  23.  
  24. for_each_pool(pool, pi) {
  25. mutex_lock(&pool->attach_mutex);
  26.  
  27. if (pool->cpu == cpu)
  28. rebind_workers(pool);
  29. else if (pool->cpu < 0)
  30. restore_unbound_workers_cpumask(pool, cpu);
  31.  
  32. mutex_unlock(&pool->attach_mutex);
  33. }
  34.  
  35. /* update NUMA affinity of unbound workqueues */
  36. list_for_each_entry(wq, &workqueues, list)
  37. wq_update_unbound_numa(wq, cpu, true);
  38.  
  39. mutex_unlock(&wq_pool_mutex);
  40. break;
  41. }
  42. return NOTIFY_OK;
  43. }
  44.  
  45. static int workqueue_cpu_down_callback(struct notifier_block *nfb,
  46. unsigned long action,
  47. void *hcpu)
  48. {
  49. int cpu = (unsigned long)hcpu;
  50. struct work_struct unbind_work;
  51. struct workqueue_struct *wq;
  52.  
  53. switch (action & ~CPU_TASKS_FROZEN) {
  54. case CPU_DOWN_PREPARE:
  55. /* unbinding per-cpu workers should happen on the local CPU */
  56. INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
  57. queue_work_on(cpu, system_highpri_wq, &unbind_work);
  58.  
  59. /* update NUMA affinity of unbound workqueues */
  60. mutex_lock(&wq_pool_mutex);
  61. list_for_each_entry(wq, &workqueues, list)
  62. wq_update_unbound_numa(wq, cpu, false);
  63. mutex_unlock(&wq_pool_mutex);
  64.  
  65. /* wait for per-cpu unbinding to finish */
  66. flush_work(&unbind_work);
  67. destroy_work_on_stack(&unbind_work);
  68. break;
  69. }
  70. return NOTIFY_OK;
  71. }

init_worker_pool()初始化一个worker_pool。

  1. static int init_worker_pool(struct worker_pool *pool)
  2. {
  3. spin_lock_init(&pool->lock);
  4. pool->id = -1;
  5. pool->cpu = -1;---------------------------------------------初始值-1表示当前worker_poolunbound型的
  6. pool->node = NUMA_NO_NODE;
  7. pool->flags |= POOL_DISASSOCIATED;
  8. INIT_LIST_HEAD(&pool->worklist);
  9. INIT_LIST_HEAD(&pool->idle_list);
  10. hash_init(pool->busy_hash);
  11.  
  12. init_timer_deferrable(&pool->idle_timer);
  13. pool->idle_timer.function = idle_worker_timeout;-------------销毁多余worker,每IDLE_WORKER_TIMEOUT(300秒)执行一次。
  14. pool->idle_timer.data = (unsigned long)pool;
  15.  
  16. setup_timer(&pool->mayday_timer, pool_mayday_timeout,
  17. (unsigned long)pool);--------------------------------设置mayday_timer,周期为MAYDAY_INTERVAL,即100ms
  18.  
  19. mutex_init(&pool->manager_arb);
  20. mutex_init(&pool->attach_mutex);
  21. INIT_LIST_HEAD(&pool->workers);
  22.  
  23. ida_init(&pool->worker_ida);
  24. INIT_HLIST_NODE(&pool->hash_node);
  25. pool->refcnt = 1;
  26.  
  27. /* shouldn't fail above this point */
  28. pool->attrs = alloc_workqueue_attrs(GFP_KERNEL);
  29. if (!pool->attrs)
  30. return -ENOMEM;
  31. return 0;
  32. }

create_worker()创建内核的工作线程。

  1. static struct worker *create_worker(struct worker_pool *pool)
  2. {
  3. struct worker *worker = NULL;
  4. int id = -1;
  5. char id_buf[16];
  6.  
  7. /* ID is needed to determine kthread name */
  8. id = ida_simple_get(&pool->worker_ida, 0, 0, GFP_KERNEL);----------------从当前worker_pool->worker_ida获取一个空闲id
  9. if (id < 0)
  10. goto fail;
  11.  
  12. worker = alloc_worker(pool->node);---------------------------------------分配一个woker结构体
  13. if (!worker)
  14. goto fail;
  15.  
  16. worker->pool = pool;-----------------------------------------------------woker_pool关联到worker
  17. worker->id = id;---------------------------------------------------------递增的id
  18.  
  19. if (pool->cpu >= 0)------------------------------------------------------初始值为-1表示unbound,当>=0的时候就指定了cpu,说明是bound型的。
  20. snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
  21. pool->attrs->nice < 0 ? "H" : "");-----------------------------nice0表示普通优先级,nice为-20是高优先级。
  22. else
  23. snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
  24.  
  25. worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
  26. "kworker/%s", id_buf);----------------------------woker和创建的内核工作线程关联上,线程处理函数是worker_thread
  27. if (IS_ERR(worker->task))
  28. goto fail;
  29.  
  30. set_user_nice(worker->task, pool->attrs->nice);-------------------------设置内核工作线程的优先级相关
  31.  
  32. /* prevent userland from meddling with cpumask of workqueue workers */
  33. worker->task->flags |= PF_NO_SETAFFINITY;-------------------------------阻止用户修改其CPU亲和性
  34.  
  35. /* successful, attach the worker to the pool */
  36. worker_attach_to_pool(worker, pool);------------------------------------将worker附着到worker_pool
  37.  
  38. /* start the newly created worker */
  39. spin_lock_irq(&pool->lock);
  40. worker->pool->nr_workers++;---------------------------------------------统计当前worker对应worker_pool中工作线程数目
  41. worker_enter_idle(worker);----------------------------------------------让该工作线程进入idle状态。
  42. wake_up_process(worker->task);------------------------------------------唤醒刚创建的工作线程
  43. spin_unlock_irq(&pool->lock);
  44.  
  45. return worker;
  46.  
  47. fail:
  48. if (id >= 0)
  49. ida_simple_remove(&pool->worker_ida, id);
  50. kfree(worker);
  51. return NULL;
  52. }

woker_attact_to_pool()主要是将worker工作线程加入到woker_pool->workers链表中。

  1. static void worker_attach_to_pool(struct worker *worker,
  2. struct worker_pool *pool)
  3. {
  4. mutex_lock(&pool->attach_mutex);
  5.  
  6. set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
  7. if (pool->flags & POOL_DISASSOCIATED)------------------表示worker_pool没有绑定到某个CPU上,所以worker也不会绑定到某个CPU
  8. worker->flags |= WORKER_UNBOUND;
  9.  
  10. list_add_tail(&worker->node, &pool->workers);----------将当前worker加入到worker_pool末尾。
  11.  
  12. mutex_unlock(&pool->attach_mutex);
  13. }

1.2.3 工作线程执行函数

worker_thread()是工作线程的处理函数,不管其所在worker_pool是bound还是unbound型。

worker_thread()处理了大部分work_item,除了属于rescuer的work_item由rescuer_thread()进行处理。

通过worker找到对应的worker_pool,然后遍历worker_pool中的work_struct。

  1. static int worker_thread(void *__worker)
  2. {
  3. struct worker *worker = __worker;
  4. struct worker_pool *pool = worker->pool;
  5.  
  6. /* tell the scheduler that this is a workqueue worker */
  7. worker->task->flags |= PF_WQ_WORKER;------------------PF_WQ_WORKER告诉调度器这是一个woker类型的线程。
  8. woke_up:
  9. spin_lock_irq(&pool->lock);
  10.  
  11. /* am I supposed to die? */
  12. if (unlikely(worker->flags & WORKER_DIE)) {-----------WORKER_DIE表示此工作线程将要被销毁。
  13. spin_unlock_irq(&pool->lock);
  14. WARN_ON_ONCE(!list_empty(&worker->entry));
  15. worker->task->flags &= ~PF_WQ_WORKER;
  16.  
  17. set_task_comm(worker->task, "kworker/dying");
  18. ida_simple_remove(&pool->worker_ida, worker->id);
  19. worker_detach_from_pool(worker, pool);
  20. kfree(worker);
  21. return 0;
  22. }
  23.  
  24. worker_leave_idle(worker);----------------------------清除WORKER_IDLE标志位,并退出idle状态链表
  25. recheck:
  26. /* no more worker necessary? */
  27. if (!need_more_worker(pool))--------------------------如果当前worker_pool->worklist中没有pending任务,并且当前pool中没有正在运行的线程,need_more_worker()返回true
  28. goto sleep;
  29.  
  30. /* do we need to manage? */
  31. if (unlikely(!may_start_working(pool)) &&manage_workers(worker))------may_start_working()判断pool中是否有idle状态工作线程。如果没有,那么manage_workers()创建一些工作线程。
  32. goto recheck;------------------------------------------------------manage_worker()创建新工作线程之后,还需要跳转到recheck标签处再检查一遍,有可能在创建工作线程过程中整个线程池发生了变化。
  33.  
  34. /*
  35. * ->scheduled list can only be filled while a worker is
  36. * preparing to process a work or actually processing it.
  37. * Make sure nobody diddled with it while I was sleeping.
  38. */
  39. WARN_ON_ONCE(!list_empty(&worker->scheduled));-------------------------scheduled链表表示工作线程准备处理一个work或者正在执行一个work时才会有work添加到该链表中。
  40.  
  41. /*
  42. * Finish PREP stage. We're guaranteed to have at least one idle
  43. * worker or that someone else has already assumed the manager
  44. * role. This is where @worker starts participating in concurrency
  45. * management if applicable and concurrency management is restored
  46. * after being rebound. See rebind_workers() for details.
  47. */
  48. worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);--------因为马上就要开始执行work的回调函数了,对于bound类型增加worker_pool->nr_running计数
  49.  
  50. do {-----------------------------------------------------------遍历当前worker_pool->worklist中的工作,调用process_one_work()进行处理。
  51. struct work_struct *work =
  52. list_first_entry(&pool->worklist,
  53. struct work_struct, entry);
  54.  
  55. if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
  56. /* optimization path, not strictly necessary */process_one_work(worker, work);------------------------单独处理一个work
  57. if (unlikely(!list_empty(&worker->scheduled)))
  58. process_scheduled_works(worker);-------------------处理worker_pool->scheduled链表上的work_struct
  59. } else {---------------------------------------------------如果当前work_struct置位WORK_STRUCT_LINKED表示work后面还串上其它work,把这些work迁移到woeker_pool->scheduled中,然后一并再用process_one_work()函数处理。
  60. move_linked_works(work, &worker->scheduled, NULL);
  61. process_scheduled_works(worker);
  62. }
  63. } while (keep_working(pool));----------------------------------判断当前worker_pool->worklist不为空,且工作线程池活跃线程小于等于1,那么保持当前工作线程继续工作,以防止工作线程泛滥。
  64.  
  65. worker_set_flags(worker, WORKER_PREP);
  66. sleep:
  67. /*
  68. * pool->lock is held and there's no work to process and no need to
  69. * manage, sleep. Workers are woken up only while holding
  70. * pool->lock or from local cpu, so setting the current state
  71. * before releasing pool->lock is enough to prevent losing any
  72. * event.
  73. */
  74. worker_enter_idle(worker);
  75. __set_current_state(TASK_INTERRUPTIBLE);
  76. spin_unlock_irq(&pool->lock);
  77. schedule();
  78. goto woke_up;
  79. }

manage_workers()函数动态管理创建工作线程的函数。

maybo_create_worker()函数中while首先调用create_worker()来创建新的工作线程。

  1. static bool manage_workers(struct worker *worker)
  2. {
  3. struct worker_pool *pool = worker->pool;
  4.  
  5. if (pool->flags & POOL_MANAGER_ACTIVE)
  6. return false;
  7.  
  8. pool->flags |= POOL_MANAGER_ACTIVE;
  9. pool->manager = worker;
  10.  
  11. maybe_create_worker(pool);
  12.  
  13. pool->manager = NULL;
  14. pool->flags &= ~POOL_MANAGER_ACTIVE;
  15. wake_up(&wq_manager_wait);
  16. return true;
  17. }
  18.  
  19. static void maybe_create_worker(struct worker_pool *pool)
  20. __releases(&pool->lock)
  21. __acquires(&pool->lock)
  22. {
  23. restart:
  24. spin_unlock_irq(&pool->lock);
  25.  
  26. /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
  27. mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
  28.  
  29. while (true) {
  30. if (create_worker(pool) || !need_to_create_worker(pool))-----------------create_worker()创建成功则退出while循环;或者通过need_to_create_worker()判断是否需要继续创建新线程。
  31. break;
  32.  
  33. schedule_timeout_interruptible(CREATE_COOLDOWN);
  34.  
  35. if (!need_to_create_worker(pool))----------------------------------------再次判断是否需要继续创建新线程。
  36. break;
  37. }
  38.  
  39. del_timer_sync(&pool->mayday_timer);
  40. spin_lock_irq(&pool->lock);
  41. /*
  42. * This is necessary even after a new worker was just successfully
  43. * created as @pool->lock was dropped and the new worker might have
  44. * already become busy.
  45. */
  46. if (need_to_create_worker(pool))
  47. goto restart;
  48. }

process_scheduled_works()专门处理worker->scheduled上面的工作,具体处理还是交给process_one_work()。

  1. static void process_scheduled_works(struct worker *worker)
  2. {
  3. while (!list_empty(&worker->scheduled)) {
  4. struct work_struct *work = list_first_entry(&worker->scheduled,
  5. struct work_struct, entry);
  6. process_one_work(worker, work);
  7. }
  8. }
  9.  
  10. static void process_one_work(struct worker *worker, struct work_struct *work)
  11. __releases(&pool->lock)
  12. __acquires(&pool->lock)
  13. {
  14. struct pool_workqueue *pwq = get_work_pwq(work);
  15. struct worker_pool *pool = worker->pool;
  16. bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;----------------判断当前的workqueue是否是CPU_INTENSIVE,会对其所在工作线程进行特殊设置。
  17. int work_color;
  18. struct worker *collision;
  19. #ifdef CONFIG_LOCKDEP
  20. /*
  21. * It is permissible to free the struct work_struct from
  22. * inside the function that is called from it, this we need to
  23. * take into account for lockdep too. To avoid bogus "held
  24. * lock freed" warnings as well as problems when looking into
  25. * work->lockdep_map, make a copy and use that here.
  26. */
  27. struct lockdep_map lockdep_map;
  28.  
  29. lockdep_copy_map(&lockdep_map, &work->lockdep_map);
  30. #endif
  31. /* ensure we're on the correct CPU */
  32. WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
  33. raw_smp_processor_id() != pool->cpu);
  34.  
  35. /*
  36. * A single work shouldn't be executed concurrently by
  37. * multiple workers on a single cpu. Check whether anyone is
  38. * already processing the work. If so, defer the work to the
  39. * currently executing one.
  40. */
  41. collision = find_worker_executing_work(pool, work);--------------------查询当前work是否在worker_pool->busy_hash表中正在运行,如果在就移到当前work正在执行的worker->scheduled并退出当前处理。
  42. if (unlikely(collision)) {
  43. move_linked_works(work, &collision->scheduled, NULL);
  44. return;
  45. }
  46.  
  47. /* claim and dequeue */
  48. debug_work_deactivate(work);
  49. hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
  50. worker->current_work = work;
  51. worker->current_func = work->func;
  52. worker->current_pwq = pwq;
  53. work_color = get_work_color(work);
  54.  
  55. list_del_init(&work->entry);
  56.  
  57. /*
  58. * CPU intensive works don't participate in concurrency management.
  59. * They're the scheduler's responsibility. This takes @worker out
  60. * of concurrency management and the next code block will chain
  61. * execution of the pending work items.
  62. */
  63. if (unlikely(cpu_intensive))
  64. worker_set_flags(worker, WORKER_CPU_INTENSIVE);--------------------设置当前工作线程flags,调度器就知道内核线程属性了,但实际上调度器暂时并没有做特殊处理。
  65.  
  66. /*
  67. * Wake up another worker if necessary. The condition is always
  68. * false for normal per-cpu workers since nr_running would always
  69. * be >= 1 at this point. This is used to chain execution of the
  70. * pending work items for WORKER_NOT_RUNNING workers such as the
  71. * UNBOUND and CPU_INTENSIVE ones.
  72. */
  73. if (need_more_worker(pool))-----------------------判断是否需要唤醒更多工作线程,wake_up_worker()去唤醒worker_pool中第一个idle线程。对于boundworker_pool此时一般nr_running>=1,所以条件不成立。
  74. wake_up_worker(pool);
  75.  
  76. /*
  77. * Record the last pool and clear PENDING which should be the last
  78. * update to @work. Also, do this inside @pool->lock so that
  79. * PENDING and queued state changes happen together while IRQ is
  80. * disabled.
  81. */
  82. set_work_pool_and_clear_pending(work, pool->id);---------------清除struct workerdata成员pending标志位,里面使用了smp_wmb保证了pending之前的写操作完成之后才清除pending
  83.  
  84. spin_unlock_irq(&pool->lock);
  85.  
  86. lock_map_acquire_read(&pwq->wq->lockdep_map);
  87. lock_map_acquire(&lockdep_map);
  88. trace_workqueue_execute_start(work);
  89. worker->current_func(work);------------------------------------真正执行work的回调函数
  90. /*
  91. * While we must be careful to not use "work" after this, the trace
  92. * point will only record its address.
  93. */
  94. trace_workqueue_execute_end(work);
  95. lock_map_release(&lockdep_map);
  96. lock_map_release(&pwq->wq->lockdep_map);
  97.  
  98. if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
  99. pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
  100. " last function: %pf\n",
  101. current->comm, preempt_count(), task_pid_nr(current),
  102. worker->current_func);
  103. debug_show_held_locks(current);
  104. dump_stack();
  105. }
  106.  
  107. /*
  108. * The following prevents a kworker from hogging CPU on !PREEMPT
  109. * kernels, where a requeueing work item waiting for something to
  110. * happen could deadlock with stop_machine as such work item could
  111. * indefinitely requeue itself while all other CPUs are trapped in
  112. * stop_machine. At the same time, report a quiescent RCU state so
  113. * the same condition doesn't freeze RCU.
  114. */
  115. cond_resched_rcu_qs();
  116.  
  117. spin_lock_irq(&pool->lock);
  118.  
  119. /* clear cpu intensive status */
  120. if (unlikely(cpu_intensive))
  121. worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
  122.  
  123. /* we're done with it, release */
  124. hash_del(&worker->hentry);-----------------------------------work回调函数执行完成后的清理工作
  125. worker->current_work = NULL;
  126. worker->current_func = NULL;
  127. worker->current_pwq = NULL;
  128. worker->desc_valid = false;
  129. pwq_dec_nr_in_flight(pwq, work_color);
  130. }

2 创建工作队列

2.1 各种创建工作队列API和flags

创建工作队列的API有很多,但最终都通过__alloc_workqueue_key()去实现。不同API之间的主要区别在于使用了不同的flag。

所以看一下这些flag,同时max_active决定每个CPU最多可有多少个work挂入一个工作队列。

如果bound类型工作队列,max_active最大可以是512;如果max_active为0,表示指定为256。

如果需要严格串行执行工作队列,使用max_active=1和WQ_UNBOUND组合。

  1. /*
  2. * Workqueue flags and constants. For details, please refer to
  3. * Documentation/workqueue.txt.
  4. */
  5. enum {
  6. WQ_NON_REENTRANT = 1 << 0, /* guarantee non-reentrance */-----------确保工作在多个CPU上是不可重入的。
  7. WQ_UNBOUND = 1 << 1, /* not bound to any cpu */-----------------工作任务会加入unbound工作队列中,unbound类型work不需要额外的同步管理,unbound工作线程池会尝试尽快执行它的work
  8. WQ_FREEZABLE = 1 << 2, /* freeze during suspend */--------------此标记工作队列会参与到系统suspend过程中,会让工作线程处理完成所有的work才完成进程冻结,并且这个过程不会再新开始一个work执行,直到进程被解冻。
  9. WQ_MEM_RECLAIM = 1 << 3, /* may be used for memory reclaim */---当内存紧张时,创建新的工作线程可能会失败,系统还有一个recuer内核线程会去接管这种情况。
  10. WQ_HIGHPRI = 1 << 4, /* high priority */------------------------工作队列的任务对应高优先级的worker_pool,即较低nice值。
  11. WQ_CPU_INTENSIVE = 1 << 5, /* cpu instensive workqueue */-----------属于特别消耗CPU资源一类work,这类work会得到系统进程调度器的监管,排在这类work后面的non-cpu intensive类型work可能会推迟执行。

WQ_SYSFS = 1 << 6, /* visible in sysfs, see wq_sysfs_register() */

  1. WQ_RESCUER = 1 << 7, /* internal: workqueue has rescuer */

__WQ_DRAINING = 1 << 16, /* internal: workqueue is draining */
      __WQ_ORDERED = 1 << 17, /* internal: workqueue is ordered */-----------同一时间只能执行一个work item。

  1. WQ_MAX_ACTIVE = 512, /* I like 512, better ideas? */
  2. WQ_MAX_UNBOUND_PER_CPU = 4, /* 4 * #cpus for unbound wq */
  3. WQ_DFL_ACTIVE = WQ_MAX_ACTIVE / 2,
  4. };

最常见的形式是alloc_workqueue(),其它都是对某些flag的封装。

  1. #define alloc_workqueue(fmt, flags, max_active, args...) \
  2. __alloc_workqueue_key((fmt), (flags), (max_active), \
  3. NULL, NULL, ##args)
  4. #define alloc_ordered_workqueue(fmt, flags, args...) \
  5. alloc_workqueue(fmt, WQ_UNBOUND | __WQ_ORDERED | (flags), 1, ##args)
  6.  
  7. #define create_workqueue(name) \
  8. alloc_workqueue("%s", WQ_MEM_RECLAIM, 1, (name))
  9. #define create_freezable_workqueue(name) \
  10. alloc_workqueue("%s", WQ_FREEZABLE | WQ_UNBOUND | WQ_MEM_RECLAIM, \
  11. 1, (name))
  12. #define create_singlethread_workqueue(name) \
  13. alloc_ordered_workqueue("%s", WQ_MEM_RECLAIM, name)

2.2 __alloc_workqueue_key()

__alloc_workqueue_key分配一个workqueue_struct数据结构并进行初始化,和pool_workqueue进行关联等操作。

  1. struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
  2. unsigned int flags,
  3. int max_active,
  4. struct lock_class_key *key,
  5. const char *lock_name, ...)
  6. {
  7. size_t tbl_size = 0;
  8. va_list args;
  9. struct workqueue_struct *wq;
  10. struct pool_workqueue *pwq;
  11.  
  12. /* see the comment above the definition of WQ_POWER_EFFICIENT */
  13. if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)----------设置unbound类型workqueue后,究竟选择哪个cpu上唤醒交由进程调度器决定。如果是bound类型就会让idle状态的CPUidle状态唤醒,从而增加了功耗。
  14. flags |= WQ_UNBOUND;
  15.  
  16. /* allocate wq and format name */
  17. if (flags & WQ_UNBOUND)
  18. tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
  19.  
  20. wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
  21. if (!wq)
  22. return NULL;
  23.  
  24. if (flags & WQ_UNBOUND) {
  25. wq->unbound_attrs = alloc_workqueue_attrs(GFP_KERNEL);
  26. if (!wq->unbound_attrs)
  27. goto err_free_wq;
  28. }
  29.  
  30. va_start(args, lock_name);
  31. vsnprintf(wq->name, sizeof(wq->name), fmt, args);
  32. va_end(args);
  33.  
  34. max_active = max_active ?: WQ_DFL_ACTIVE;
  35. max_active = wq_clamp_max_active(max_active, flags, wq->name);
  36.  
  37. /* init wq */
  38. wq->flags = flags;
  39. wq->saved_max_active = max_active;
  40. mutex_init(&wq->mutex);
  41. atomic_set(&wq->nr_pwqs_to_flush, 0);
  42. INIT_LIST_HEAD(&wq->pwqs);
  43. INIT_LIST_HEAD(&wq->flusher_queue);
  44. INIT_LIST_HEAD(&wq->flusher_overflow);
  45. INIT_LIST_HEAD(&wq->maydays);
  46.  
  47. lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
  48. INIT_LIST_HEAD(&wq->list);
  49.  
  50. if (alloc_and_link_pwqs(wq) < 0)---------------------分配一个workqueue_struct数据结构并初始化
  51. goto err_free_wq;
  52.  
  53. /*
  54. * Workqueues which may be used during memory reclaim should
  55. * have a rescuer to guarantee forward progress.
  56. */
  57. if (flags & WQ_MEM_RECLAIM) {
  58. struct worker *rescuer;
  59.  
  60. rescuer = alloc_worker(NUMA_NO_NODE);
  61. if (!rescuer)
  62. goto err_destroy;
  63.  
  64. rescuer->rescue_wq = wq;
  65. rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
  66. wq->name);
  67. if (IS_ERR(rescuer->task)) {
  68. kfree(rescuer);
  69. goto err_destroy;
  70. }
  71.  
  72. wq->rescuer = rescuer;
  73. rescuer->task->flags |= PF_NO_SETAFFINITY;
  74. wake_up_process(rescuer->task);
  75. }
  76.  
  77. if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
  78. goto err_destroy;
  79.  
  80. /*
  81. * wq_pool_mutex protects global freeze state and workqueues list.
  82. * Grab it, adjust max_active and add the new @wq to workqueues
  83. * list.
  84. */
  85. mutex_lock(&wq_pool_mutex);
  86.  
  87. mutex_lock(&wq->mutex);
  88. for_each_pwq(pwq, wq)
  89. pwq_adjust_max_active(pwq);
  90. mutex_unlock(&wq->mutex);
  91.  
  92. list_add(&wq->list, &workqueues);
  93.  
  94. mutex_unlock(&wq_pool_mutex);
  95.  
  96. return wq;
  97.  
  98. err_free_wq:
  99. free_workqueue_attrs(wq->unbound_attrs);
  100. kfree(wq);
  101. return NULL;
  102. err_destroy:
  103. destroy_workqueue(wq);
  104. return NULL;
  105. }
  1. static int alloc_and_link_pwqs(struct workqueue_struct *wq)
  2. {
  3. bool highpri = wq->flags & WQ_HIGHPRI;
  4. int cpu, ret;
  5.  
  6. if (!(wq->flags & WQ_UNBOUND)) {------------------------处理bound类型workqueue
  7. wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);-cpu_pwqs是一个per-cpu类型,为每个cpu分配一个pool_workqueue数据结构,是动态分配的。cpu_worker_pools是静态定义的per-cpu类型worker_pool数据结构。
  8. if (!wq->cpu_pwqs)
  9. return -ENOMEM;
  10.  
  11. for_each_possible_cpu(cpu) {
  12. struct pool_workqueue *pwq =
  13. per_cpu_ptr(wq->cpu_pwqs, cpu);
  14. struct worker_pool *cpu_pools =
  15. per_cpu(cpu_worker_pools, cpu);
  16.  
  17. init_pwq(pwq, wq, &cpu_pools[highpri]);--------init_pwq()将动态分配的cpu_pwqs和静态定义的cpu_worker_pools关联起来。
  18.  
  19. mutex_lock(&wq->mutex);
  20. link_pwq(pwq);---------------------------------把pool_workqueue添加到workqueue_struct->pwqs链表中。
  21. mutex_unlock(&wq->mutex);
  22. }
  23. return 0;
  24. } else if (wq->flags & __WQ_ORDERED) {-----------------处理ordered类型workqueue
  25. ret =apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
  26. /* there should only be single pwq for ordering guarantee */
  27. WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
  28. wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
  29. "ordering guarantee broken for workqueue %s\n", wq->name);
  30. return ret;
  31. } else {-----------------------------------------------处理unbound类型workqueue
  32. returnapply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
  33. }
  34. }
  1. int apply_workqueue_attrs(struct workqueue_struct *wq,
  2. const struct workqueue_attrs *attrs)
  3. {
  4. struct workqueue_attrs *new_attrs, *tmp_attrs;
  5. struct pool_workqueue **pwq_tbl, *dfl_pwq;
  6. int node, ret;
  7.  
  8. /* only unbound workqueues can change attributes */
  9. if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
  10. return -EINVAL;
  11.  
  12. /* creating multiple pwqs breaks ordering guarantee */
  13. if (WARN_ON((wq->flags & __WQ_ORDERED) && !list_empty(&wq->pwqs)))
  14. return -EINVAL;
  15.  
  16. pwq_tbl = kzalloc(nr_node_ids * sizeof(pwq_tbl[0]), GFP_KERNEL);
  17. new_attrs = alloc_workqueue_attrs(GFP_KERNEL);
  18. tmp_attrs = alloc_workqueue_attrs(GFP_KERNEL);
  19. if (!pwq_tbl || !new_attrs || !tmp_attrs)
  20. goto enomem;
  21.  
  22. /* make a copy of @attrs and sanitize it */
  23. copy_workqueue_attrs(new_attrs, attrs);
  24. cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
  25.  
  26. /*
  27. * We may create multiple pwqs with differing cpumasks. Make a
  28. * copy of @new_attrs which will be modified and used to obtain
  29. * pools.
  30. */
  31. copy_workqueue_attrs(tmp_attrs, new_attrs);
  32.  
  33. /*
  34. * CPUs should stay stable across pwq creations and installations.
  35. * Pin CPUs, determine the target cpumask for each node and create
  36. * pwqs accordingly.
  37. */
  38. get_online_cpus();
  39.  
  40. mutex_lock(&wq_pool_mutex);
  41.  
  42. /*
  43. * If something goes wrong during CPU up/down, we'll fall back to
  44. * the default pwq covering whole @attrs->cpumask. Always create
  45. * it even if we don't use it immediately.
  46. */
  47. dfl_pwq =alloc_unbound_pwq(wq, new_attrs);---------------------分配一个pool_workqueue数据结构
  48. if (!dfl_pwq)
  49. goto enomem_pwq;
  50.  
  51. for_each_node(node) {
  52. if (wq_calc_node_cpumask(attrs, node, -1, tmp_attrs->cpumask)) {
  53. pwq_tbl[node] =alloc_unbound_pwq(wq, tmp_attrs);-------查找或者新建一个pool_workqueue
  54. if (!pwq_tbl[node])
  55. goto enomem_pwq;
  56. } else {
  57. dfl_pwq->refcnt++;
  58. pwq_tbl[node] = dfl_pwq;
  59. }
  60. }
  61.  
  62. mutex_unlock(&wq_pool_mutex);
  63.  
  64. /* all pwqs have been created successfully, let's install'em */
  65. mutex_lock(&wq->mutex);
  66.  
  67. copy_workqueue_attrs(wq->unbound_attrs, new_attrs);
  68.  
  69. /* save the previous pwq and install the new one */
  70. for_each_node(node)
  71. pwq_tbl[node] = numa_pwq_tbl_install(wq, node, pwq_tbl[node]);
  72.  
  73. /* @dfl_pwq might not have been used, ensure it's linked */
  74. link_pwq(dfl_pwq);
  75. swap(wq->dfl_pwq, dfl_pwq);
  76.  
  77. mutex_unlock(&wq->mutex);
  78.  
  79. /* put the old pwqs */
  80. for_each_node(node)
  81. put_pwq_unlocked(pwq_tbl[node]);
  82. put_pwq_unlocked(dfl_pwq);
  83.  
  84. put_online_cpus();
  85. ret = 0;
  86. /* fall through */
  87. out_free:
  88. free_workqueue_attrs(tmp_attrs);
  89. free_workqueue_attrs(new_attrs);
  90. kfree(pwq_tbl);
  91. return ret;
  92.  
  93. enomem_pwq:
  94. free_unbound_pwq(dfl_pwq);
  95. for_each_node(node)
  96. if (pwq_tbl && pwq_tbl[node] != dfl_pwq)
  97. free_unbound_pwq(pwq_tbl[node]);
  98. mutex_unlock(&wq_pool_mutex);
  99. put_online_cpus();
  100. enomem:
  101. ret = -ENOMEM;
  102. goto out_free;
  103. }
  104.  
  105. static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
  106. const struct workqueue_attrs *attrs)
  107. {
  108. struct worker_pool *pool;
  109. struct pool_workqueue *pwq;
  110.  
  111. lockdep_assert_held(&wq_pool_mutex);
  112.  
  113. pool =get_unbound_pool(attrs);----------------------------首先查找一个worker_pool,如果没有则创建一个新的worker_pool
  114. if (!pool)
  115. return NULL;
  116.  
  117. pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);-----分配一个pool_workqueue数据结构
  118. if (!pwq) {
  119. put_unbound_pool(pool);
  120. return NULL;
  121. }
  122.  
  123. init_pwq(pwq, wq, pool);
  124. return pwq;
  125. }
  126.  
  127. static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
  128. {
  129. u32 hash = wqattrs_hash(attrs);
  130. struct worker_pool *pool;
  131. int node;
  132.  
  133. lockdep_assert_held(&wq_pool_mutex);
  134.  
  135. /* do we already have a matching pool? */
  136. hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {------系统定义了一个哈希表unbound_pool_hash,用于管理所有的unbound类型worker_pool
  137. if (wqattrs_equal(pool->attrs, attrs)) {----------------------------通过wqattrs_equal()判断系统中是否已经有个类型相关worker_pool
  138. pool->refcnt++;
  139. return pool;
  140. }
  141. }
  142.  
  143. /* nope, create a new one */
  144. pool = kzalloc(sizeof(*pool), GFP_KERNEL);------------------------------如果没有找到,重新分配和初始化一个worker_pool
  145. if (!pool || init_worker_pool(pool) < 0)
  146. goto fail;
  147. ...
  148. /* create and start the initial worker */
  149. if (!create_worker(pool))
  150. goto fail;
  151.  
  152. /* install */
  153. hash_add(unbound_pool_hash, &pool->hash_node, hash);
  154.  
  155. return pool;
  156. ...
  157. }
  158.  
  159. static void put_pwq(struct pool_workqueue *pwq)
  160. {
  161. lockdep_assert_held(&pwq->pool->lock);
  162. if (likely(--pwq->refcnt))
  163. return;
  164. if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
  165. return;
  166. schedule_work(&pwq->unbound_release_work);
  167. }
  168.  
  169. static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
  170. struct worker_pool *pool)
  171. {
  172. BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
  173.  
  174. memset(pwq, 0, sizeof(*pwq));
  175.  
  176. pwq->pool = pool;-------------------------------------------pwq->pool指向worker_pool
  177. pwq->wq = wq;-----------------------------------------------pwq->wq指向workqueue_struct
  178. pwq->flush_color = -1;
  179. pwq->refcnt = 1;
  180. INIT_LIST_HEAD(&pwq->delayed_works);
  181. INIT_LIST_HEAD(&pwq->pwqs_node);
  182. INIT_LIST_HEAD(&pwq->mayday_node);
  183. INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);------------用于释放pool_workqueue
  184. }
  185.  
  186. static void pwq_unbound_release_workfn(struct work_struct *work)
  187. {
  188. struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
  189. unbound_release_work);-----------从work找到pool_workqueue数据结构指针pwq
  190. struct workqueue_struct *wq = pwq->wq;
  191. struct worker_pool *pool = pwq->pool;
  192. bool is_last;
  193.  
  194. if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
  195. return;
  196.  
  197. mutex_lock(&wq->mutex);
  198. list_del_rcu(&pwq->pwqs_node);
  199. is_last = list_empty(&wq->pwqs);
  200. mutex_unlock(&wq->mutex);
  201.  
  202. mutex_lock(&wq_pool_mutex);
  203. put_unbound_pool(pool);
  204. mutex_unlock(&wq_pool_mutex);
  205.  
  206. call_rcu_sched(&pwq->rcu, rcu_free_pwq);
  207.  
  208. /*
  209. * If we're the last pwq going away, @wq is already dead and no one
  210. * is gonna access it anymore. Free it.
  211. */
  212. if (is_last) {
  213. free_workqueue_attrs(wq->unbound_attrs);
  214. kfree(wq);
  215. }
  216. }

3. 调度一个work

一般情况下使用默认的workqueue,首先需要初始化一个work,然后使用schedule_work()把work挂入默认的workqueue中。

3.1 初始化一个work

初始化一个work的API有各种不同形式,但最终都调用__INIT_WORK()。

  1.  

#define TIMER_DEFERRABLE 0x1LU
  #define TIMER_IRQSAFE 0x2LU

  1. #define __INIT_WORK(_work, _func, _onstack) \
  2. do { \
  3. __init_work((_work), _onstack); \
  4. (_work)->data = (atomic_long_t) WORK_DATA_INIT(); \
  5. INIT_LIST_HEAD(&(_work)->entry); \
  6. (_work)->func = (_func); \
  7. } while (0)
  8.  
  9. #define INIT_WORK(_work, _func) \
  10. __INIT_WORK((_work), (_func), 0)
  11.  
  12. #define INIT_WORK_ONSTACK(_work, _func) \
  13. __INIT_WORK((_work), (_func), 1)
  14.  
  15. #define __INIT_DELAYED_WORK(_work, _func, _tflags) \
  16. do { \
  17. INIT_WORK(&(_work)->work, (_func)); \
  18. __setup_timer(&(_work)->timer, delayed_work_timer_fn, \
  19. (unsigned long)(_work), \
  20. (_tflags) | TIMER_IRQSAFE); \
  21. } while (0)
  22.  
  23. #define __INIT_DELAYED_WORK_ONSTACK(_work, _func, _tflags) \
  24. do { \
  25. INIT_WORK_ONSTACK(&(_work)->work, (_func)); \
  26. __setup_timer_on_stack(&(_work)->timer, \
  27. delayed_work_timer_fn, \
  28. (unsigned long)(_work), \
  29. (_tflags) | TIMER_IRQSAFE); \
  30. } while (0)
  31.  
  32. #define INIT_DELAYED_WORK(_work, _func) \
  33. __INIT_DELAYED_WORK(_work, _func, 0)
  34.  
  35. #define INIT_DELAYED_WORK_ONSTACK(_work, _func) \
  36. __INIT_DELAYED_WORK_ONSTACK(_work, _func, 0)
  37.  
  38. #define INIT_DEFERRABLE_WORK(_work, _func) \
  39. __INIT_DELAYED_WORK(_work, _func, TIMER_DEFERRABLE)
  40.  
  41. #define INIT_DEFERRABLE_WORK_ONSTACK(_work, _func) \
  42. __INIT_DELAYED_WORK_ONSTACK(_work, _func, TIMER_DEFERRABLE)

当data字段包含WORK_STRUCT_PWQ_BIT标志位时,高位存放上一次pool_workqueue指针,低8位存放标志位;没有包含时,包比特位存放上次worker_pool的ID号,低5位存放标志位。

常见标志位如下:

  1. enum {
  2. WORK_STRUCT_PENDING_BIT = 0, /* work item is pending execution */----表示该work正在pending执行。
  3. WORK_STRUCT_DELAYED_BIT = 1, /* work item is delayed */--------------表示该work被延迟执行了。
  4. WORK_STRUCT_PWQ_BIT = 2, /* data points to pwq */
  5. WORK_STRUCT_LINKED_BIT = 3, /* next work is linked to this one */----表示一个work连接到该work上。
  6. #ifdef CONFIG_DEBUG_OBJECTS_WORK
  7. WORK_STRUCT_STATIC_BIT = 4, /* static initializer (debugobjects) */
  8. WORK_STRUCT_COLOR_SHIFT = 5, /* color for workqueue flushing */
  9. #else
  10. WORK_STRUCT_COLOR_SHIFT = 4, /* color for workqueue flushing */
  11. #endif
  12. WORK_STRUCT_COLOR_BITS = 4,
  13. ...
  14. }

3.2 schedule_work

在初始化完work之后,调用schedule_work()函数把work挂入系统默认workqueue中。

schedule_work()的默认的工作队列是system_wq,最终将工作交给__queue_work()。

  1. static inline bool schedule_work(struct work_struct *work)
  2. {
  3. returnqueue_work(system_wq, work);
  4. }
  5.  
  6. static inline bool queue_work(struct workqueue_struct *wq,
  7. struct work_struct *work)
  8. {
  9. returnqueue_work_on(WORK_CPU_UNBOUND, wq, work);------------WORK_CPU_UNBOUND不是表示unbound类型,而是CPU
  10. }
  11.  
  12. bool queue_work_on(int cpu, struct workqueue_struct *wq,
  13. struct work_struct *work)
  14. {
  15. bool ret = false;
  16. unsigned long flags;
  17.  
  18. local_irq_save(flags);---------------------------------------把work加入工作队列是在关本地中断下运行的。
  19.  
  20. if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {------------设置WORK_STRUCT_PENDING_BIT并返回旧值。
  21. __queue_work(cpu, wq, work);
  22. ret = true;
  23. }
  24.  
  25. local_irq_restore(flags);
  26. return ret;
  27. }
  28.  
  29. static void __queue_work(int cpu, struct workqueue_struct *wq,
  30. struct work_struct *work)
  31. {
  32. struct pool_workqueue *pwq;
  33. struct worker_pool *last_pool;
  34. struct list_head *worklist;
  35. unsigned int work_flags;
  36. unsigned int req_cpu = cpu;
  37.  
  38. WARN_ON_ONCE(!irqs_disabled());----------------------------是否处于关中断状态
  39.  
  40. debug_work_activate(work);
  41.  
  42. /* if draining, only works from the same workqueue are allowed */
  43. if (unlikely(wq->flags & __WQ_DRAINING) &&
  44. WARN_ON_ONCE(!is_chained_work(wq)))--------------------__WQ_DRAINING表示要销毁workqueue,那么挂入workqueue中所有的work都要处理完毕才能把这个workqueue销毁。在销毁过程中,一般不允许再有新的work加入队列中。有一种特殊例外是正在清空work时触发了一个queue work操作,这种情况被称为chained work
  45. return;
  46. retry:
  47. if (req_cpu == WORK_CPU_UNBOUND)
  48. cpu = raw_smp_processor_id();
  49.  
  50. /* pwq which will be used unless @work is executing elsewhere */
  51. if (!(wq->flags & WQ_UNBOUND))
  52. pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);-----------------对于bound型的workqueue,直接使用本地CPU对应pool_workqueue
  53. else
  54. pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));------对于unbound型,调用unbound_pwq_by_node()寻找本地node节点对应的unbound类型的pool_workqueue
  55.  
  56. /*
  57. * If @work was previously on a different pool, it might still be
  58. * running there, in which case the work needs to be queued on that
  59. * pool to guarantee non-reentrancy.
  60. */
  61. last_pool =get_work_pool(work);--------------------------通过work_struct的成员data查询该work上一次是在哪个worker_pool中运行的。
  62. if (last_pool && last_pool != pwq->pool) {----------------如果上次运行的worker_pool和本次不一致
  63. struct worker *worker;
  64.  
  65. spin_lock(&last_pool->lock);
  66.  
  67. worker = find_worker_executing_work(last_pool, work);--判断一个work是否正在last_pool上运行,也即不在当前worker_pool运行,如果是返回这个正在执行的工作线程worker
  68.  
  69. if (worker && worker->current_pwq->wq == wq) {
  70. pwq = worker->current_pwq;-------------------------利用当前work正在执行的pool_workqueue,利用缓存热度,不进行调度。
  71. } else {
  72. /* meh... not running there, queue here */
  73. spin_unlock(&last_pool->lock);
  74. spin_lock(&pwq->pool->lock);
  75. }
  76. } else {
  77. spin_lock(&pwq->pool->lock);
  78. }
  79.  
  80. if (unlikely(!pwq->refcnt)) {
  81. if (wq->flags & WQ_UNBOUND) {-------------------对unbound类型pool_workqueue释放是异步的,当refcnt减少到0时,说明该pool_workqueue已经被释放,那么需要跳转到retry出重新选择pool_workqueue
  82. spin_unlock(&pwq->pool->lock);
  83. cpu_relax();
  84. goto retry;
  85. }
  86. /* oops */
  87. WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
  88. wq->name, cpu);
  89. }
  90.  
  91. /* pwq determined, queue */
  92. trace_workqueue_queue_work(req_cpu, pwq, work);
  93.  
  94. if (WARN_ON(!list_empty(&work->entry))) {
  95. spin_unlock(&pwq->pool->lock);
  96. return;
  97. }
  98.  
  99. pwq->nr_in_flight[pwq->work_color]++;
  100. work_flags = work_color_to_flags(pwq->work_color);
  101.  
  102. if (likely(pwq->nr_active < pwq->max_active)) {-------判断当前pool_workqueuework活跃数量,如果少于最高限值,就加入pending状态链表worker_pool->worklist,否则加入delayed_works链表中。
  103. trace_workqueue_activate_work(work);
  104. pwq->nr_active++;
  105. worklist = &pwq->pool->worklist;
  106. } else {
  107. work_flags |= WORK_STRUCT_DELAYED;
  108. worklist = &pwq->delayed_works;
  109. }
  110.  
  111. insert_work(pwq, work, worklist, work_flags);---------将当前work加入到pool_workqueue->worklist尾部。
  112.  
  113. spin_unlock(&pwq->pool->lock);
  114. }

get_work_pool()通过work_struct找到该work上一次在哪个worker_pool中运行。

  1. static struct worker_pool *get_work_pool(struct work_struct *work)
  2. {
  3. unsigned long data = atomic_long_read(&work->data);
  4. int pool_id;
  5.  
  6. assert_rcu_or_pool_mutex();
  7.  
  8. if (data & WORK_STRUCT_PWQ)----------------------------如果定义了WORK_STRUCT_PWQ,那么直接得到pool_workqueue地址,进而找到worker_pool
  9. return ((struct pool_workqueue *)
  10. (data & WORK_STRUCT_WQ_DATA_MASK))->pool;
  11.  
  12. pool_id = data >> WORK_OFFQ_POOL_SHIFT;----------------如果没定义WORK_STRUCT_PWQ,那么可以得到对应的pool_id
  13. if (pool_id == WORK_OFFQ_POOL_NONE)
  14. return NULL;
  15.  
  16. return idr_find(&worker_pool_idr, pool_id);------------根据pool_idworker_pool_idr中找到对应的worker_pool
  17. }

insert_work()将work加入到worker_pool的列表中,

  1. static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
  2. struct list_head *head, unsigned int extra_flags)
  3. {
  4. struct worker_pool *pool = pwq->pool;
  5.  
  6. /* we own @work, set data and link */
  7. set_work_pwq(work, pwq, extra_flags);------------把pool_workqueue指针的值和一些flag设置到data成员中,方便下次调用queue_work()知道本次使用哪个pool_workqueue()。
  8. list_add_tail(&work->entry, head);---------------将work加入到worker_pool->worklist尾部。
  9. get_pwq(pwq);------------------------------------增加pool_workqueue->refcnt成员引用计数。
  10.  
  11. /*
  12. * Ensure either wq_worker_sleeping() sees the above
  13. * list_add_tail() or we see zero nr_running to avoid workers lying
  14. * around lazily while there are works to be processed.
  15. */
  16. smp_mb();----------------------------------------保证wake_up_worker()唤醒worker时,在__schedule()->wq_worker_sleeping()时,这里的list_add_tail()已经完成。同时保证下面__need_more_worker()读取nr_runninglist_add_tail()链表已经完成。
  17.  
  18. if (__need_more_worker(pool))--------------------如果当前nr_running0,表示当前worker可能并没有处于运行状态。那么需要wake_up_worker()强行唤醒一次。
  19. wake_up_worker(pool);
  20. }
  21.  
  22. static void wake_up_worker(struct worker_pool *pool)
  23. {
  24. struct worker *worker = first_idle_worker(pool);
  25.  
  26. if (likely(worker))
  27. wake_up_process(worker->task);
  28. }

调用schedule_work()只是把work加入到workqueue中,,但并没有开始实质的调度工作。

  • 加入workqueue的pending链表是关中断环境下进行的
  • 设置work->data成员的WORK_STRUCT_PENDING_BIT标志位
  • 寻找合适的pool_workqueue,优先选择本地CPU对应的pool_workqueue;如果该work正在另一个CPU工作线程池中运行,则优先选择此工作线程池。
  • 找到pool_workqueue,就找到了对应的worker_pool和对应的pending链表

那么work真正执行的地方在哪里呢?参见worker_thread()。

其它基于system_wq的变种还包括如下系列,_on表示指定某个CPU,_delayed表示延时工作。

  1. int schedule_work_on(int cpu, struct work_struct *work)
  2. {
  3. return queue_work_on(cpu, system_wq, work);
  4. }
  5.  
  6. int schedule_delayed_work(struct delayed_work *dwork,
  7. unsigned long delay)
  8. {
  9. return queue_delayed_work(system_wq, dwork, delay);
  10. }
  11.  
  12. int schedule_delayed_work_on(int cpu,
  13. struct delayed_work *dwork, unsigned long delay)
  14. {
  15. return queue_delayed_work_on(cpu, system_wq, dwork, delay);
  16. }

3.3 其它系统默认workqueue

上面介绍了schedule_work(),其默认将work放入system_wq上。

系统还有其它很多默认workqueue,这些workqueue也都是通过queue_work()将work放入其上。

下面介绍一些其它系统全局workqueue的使用。

system_highpri_wq 和system_wq的区别在于WQ_HIGHPRI,这些work对应的工作线程位于cpu_worker_pool[1]中。工作线程的nice为-20,要比system_wq对应的工作线程优先级要高。

system_long_wq和system_wq类似,但是一般system_long_wq用于执行时间较长的work,而system_wq放执行较短的work。

这两个workqueue没有明显的区别,更多的是靠使用者自觉。

system_nrt_wq相对于system_wq使用了WQ_NON_REENTRANT。默认情况下工作队列只是确保在同一CPU不可重入,即工作在同一CPU上不会被多个工作线程并发执行,但容许在多个CPU上并发执行。

该标志表明在多个CPU上也是不可重入的,工作将在不可重入workqueue上,并确保至多在一个系统范围内的工作线程上执行。

system_unbound_wq相对于system_wq的区别是被设置为WQ_UNBOUND,没有并发管理,且work最大活跃数不超过WQ_UNBOUND_MAX_ACTIVE,一般为WQ_MAX_ACTIVE=512。

system_unbound_wq对应的工作线程不会被绑定到特定CPU,所有排队的work会被立即执行,只要资源足够并且不超过最大活跃数。

system_freezable_wq 相对于system_wq多了WQ_FREEZABLE标志,表示可以冻结workqueue参与系统的暂停操作,该workqueue的工作将被暂停,除非被唤醒,否者没有新的work被执行。

system_power_efficient_wq相对于system_wq多了WQ_POWER_EFFICIENT标志,将工作队列表示为unbound已达到节省功耗的目的,并且还需要wq_power_efficient打开。否则和system_wq没啥区别。

system_freezable_power_efficient_wq兼具system_freezable_wq的freezable和system_power_efficient_wq的power efficient两个特性。

4. 取消一个work

取消一个work的接口是cancel_work_sync(),该函数通常会取消一个work,但会等待该work执行完毕。

  1. bool cancel_work_sync(struct work_struct *work)
  2. {
  3. return __cancel_work_timer(work, false);
  4. }
  5.  
  6. static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
  7. {
  8. static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);---------------------等待队列cancel_waitq
  9. unsigned long flags;
  10. int ret;
  11.  
  12. do {
  13. ret = try_to_grab_pending(work, is_dwork, &flags);------------判断当前work的状态,需要特殊处理-ENOENT情况。
  14.  
  15. if (unlikely(ret == -ENOENT)) {
  16. struct cwt_wait cwait;
  17.  
  18. init_wait(&cwait.wait);
  19. cwait.wait.func = cwt_wakefn;
  20. cwait.work = work;
  21.  
  22. prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
  23. TASK_UNINTERRUPTIBLE);
  24. if (work_is_canceling(work))
  25. schedule();
  26. finish_wait(&cancel_waitq, &cwait.wait);
  27. }
  28. } while (unlikely(ret < 0));
  29.  
  30. /* tell other tasks trying to grab @work to back off */
  31. mark_work_canceling(work);
  32. local_irq_restore(flags);
  33.  
  34. flush_work(work);-------------------------------------------------会去等待work执行完成
  35. clear_work_data(work);--------------------------------------------清除work标志位
  36.  
  37. /*
  38. * Paired with prepare_to_wait() above so that either
  39. * waitqueue_active() is visible here or !work_is_canceling() is
  40. * visible there.
  41. */
  42. smp_mb();
  43. if (waitqueue_active(&cancel_waitq))
  44. __wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
  45.  
  46. return ret;
  47. }

try_to_grab_pending()判断当前的work可否被取消,返回不同状态。__cancel_work_timer()根据不同状态采取不同操作。

  1. static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
  2. unsigned long *flags)
  3. {
  4. struct worker_pool *pool;
  5. struct pool_workqueue *pwq;
  6.  
  7. local_irq_save(*flags);-----------------------------------------------关本地中断,主要工作都在关中断下进行。
  8.  
  9. /* try to steal the timer if it exists */
  10. if (is_dwork) {
  11. struct delayed_work *dwork = to_delayed_work(work);
  12.  
  13. if (likely(del_timer(&dwork->timer)))
  14. return 1;
  15. }
  16.  
  17. /* try to claim PENDING the normal way */
  18. if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))----如果PENDING_BIT0,说明该work处于idle状态,那么可以轻松的把work取出来。此处重新设置PENDING_BIT位,后续还需要等待该work执行完成。
  19. return 0;
  20.  
  21. /*
  22. * The queueing is in progress, or it is already queued. Try to
  23. * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
  24. */----------------------------------------------------------------------下面的情况说明work正在被执行或者已经在worklist链表中,那么尝试去工作池中把work偷出来,成功后返回1.
  25. pool = get_work_pool(work);
  26. if (!pool)
  27. goto fail;
  28.  
  29. spin_lock(&pool->lock);
  30.  
  31. pwq = get_work_pwq(work);
  32. if (pwq && pwq->pool == pool) {
  33. debug_work_deactivate(work);
  34.  
  35. if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
  36. pwq_activate_delayed_work(work);
  37.  
  38. list_del_init(&work->entry);-----------------------------------------将当前workworker_pool->worklist中移除
  39. pwq_dec_nr_in_flight(pwq, get_work_color(work));
  40.  
  41. /* work->data points to pwq iff queued, point to pool */
  42. set_work_pool_and_keep_pending(work, pool->id);
  43.  
  44. spin_unlock(&pool->lock);
  45. return 1;
  46. }
  47. spin_unlock(&pool->lock);
  48. fail:
  49. local_irq_restore(*flags);
  50. if (work_is_canceling(work))--------------------------通过该work->data判断该work正在被取消,返回-ENOENT__cancel_work_timer()会睡眠等待并继续完成。
  51. return -ENOENT;
  52. cpu_relax();
  53. return -EAGAIN;---------------------------------------返回__cancel_work_timer()重试
  54. }

flush_work()等待work执行完成,返回false表示当前work并没有处于执行状态;返回true表示等到work执行完成。

  1. bool flush_work(struct work_struct *work)
  2. {
  3. struct wq_barrier barr;
  4.  
  5. lock_map_acquire(&work->lockdep_map);
  6. lock_map_release(&work->lockdep_map);
  7.  
  8. if (start_flush_work(work, &barr)) {
  9. wait_for_completion(&barr.done);
  10. destroy_work_on_stack(&barr.work);
  11. return true;
  12. } else {
  13. return false;
  14. }
  15. }
  16.  
  17. static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
  18. {
  19. struct worker *worker = NULL;
  20. struct worker_pool *pool;
  21. struct pool_workqueue *pwq;
  22.  
  23. might_sleep();
  24.  
  25. local_irq_disable();
  26. pool = get_work_pool(work);-----------------由work_struct找到worker_pool
  27. if (!pool) {
  28. local_irq_enable();
  29. return false;
  30. }
  31.  
  32. spin_lock(&pool->lock);
  33. /* see the comment in try_to_grab_pending() with the same code */
  34. pwq = get_work_pwq(work);-------------------由work_struct找到pool_workqueue
  35. if (pwq) {
  36. if (unlikely(pwq->pool != pool))--------表示当前work已经被执行完
  37. goto already_gone;
  38. } else {
  39. worker = find_worker_executing_work(pool, work);-----------返回正在执行workworker,如果没有则返回NULL,表示已经被执行完毕。
  40. if (!worker)
  41. goto already_gone;
  42. pwq = worker->current_pwq;
  43. }
  44.  
  45. insert_wq_barrier(pwq, barr, work, worker);
  46. spin_unlock_irq(&pool->lock);
  47.  
  48. /*
  49. * If @max_active is 1 or rescuer is in use, flushing another work
  50. * item on the same workqueue may lead to deadlock. Make sure the
  51. * flusher is not running on the same workqueue by verifying write
  52. * access.
  53. */
  54. if (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)
  55. lock_map_acquire(&pwq->wq->lockdep_map);
  56. else
  57. lock_map_acquire_read(&pwq->wq->lockdep_map);
  58. lock_map_release(&pwq->wq->lockdep_map);
  59.  
  60. return true;
  61. already_gone:
  62. spin_unlock_irq(&pool->lock);
  63. return false;
  64. }
  65.  
  66. static void insert_wq_barrier(struct pool_workqueue *pwq,
  67. struct wq_barrier *barr,
  68. struct work_struct *target, struct worker *worker)
  69. {
  70. struct list_head *head;
  71. unsigned int linked = 0;
  72.  
  73. /*
  74. * debugobject calls are safe here even with pool->lock locked
  75. * as we know for sure that this will not trigger any of the
  76. * checks and call back into the fixup functions where we
  77. * might deadlock.
  78. */
  79. INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);-----------------初始化一个新的barr->work,执行函数是wq_barrier_func,里面complete完成量barr->done
  80. __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
  81. init_completion(&barr->done);------------------------------------初始化barr->done完成量
  82.  
  83. /*
  84. * If @target is currently being executed, schedule the
  85. * barrier to the worker; otherwise, put it after @target.
  86. */
  87. if (worker)------------------------------------------------------当前work正在被执行,放在worker->scheduled.next之后
  88. head = worker->scheduled.next;
  89. else {
  90. unsigned long *bits = work_data_bits(target);----------------否则放在target->entry.next
  91.  
  92. head = target->entry.next;
  93. /* there can already be other linked works, inherit and set */
  94. linked = *bits & WORK_STRUCT_LINKED;
  95. __set_bit(WORK_STRUCT_LINKED_BIT, bits);
  96. }
  97.  
  98. debug_work_activate(&barr->work);
  99. insert_work(pwq, &barr->work, head,
  100. work_color_to_flags(WORK_NO_COLOR) | linked);------------将barr->work加入到head
  101. }

关于PENDING_BIT何时被设置以及被清0:

  • 当一个work已经加入到workqueue队列中,schedule_work()->queue_work()->queue_work_on()时被设置。
  • 当一个work在工作线程里马上要执行,worker_thread()->process_on_work()->set_work_pool_and_clear_pend是清0。
  • 上述设置和清0都是在关闭本地中断情况下执行的。

5. 和调度器的交互

假设某个work回调函数执行了睡眠操作,在wait_event_interruptible()中设置当前进程state为TASK_INTERRUPTIBLE,然后执行schedule()进行进程切换,调用轨迹是schedule()->__schedule()。

  1. static void __sched __schedule(void)
  2. {
  3. struct task_struct *prev, *next;
  4. unsigned long *switch_count;
  5. struct rq *rq;
  6. int cpu;
  7.  
  8. preempt_disable();
  9. cpu = smp_processor_id();
  10. rq = cpu_rq(cpu);
  11. rcu_note_context_switch();
  12. prev = rq->curr;------------------------------------------------prev指当前进程,即执行work的工作线程,state状态为TASK_INTERRUPTIBLE
  13. ...
  14. if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {-------work回调函数中调度不是中断返回前抢占调度,preempt_count也没有设置PREEMPT_ACTIVE
  15. if (unlikely(signal_pending_state(prev->state, prev))) {
  16. prev->state = TASK_RUNNING;
  17. } else {
  18. deactivate_task(rq, prev, DEQUEUE_SLEEP);
  19. prev->on_rq = 0;
  20.  
  21. /*
  22. * If a worker went to sleep, notify and ask workqueue
  23. * whether it wants to wake up a task to maintain
  24. * concurrency.
  25. */
  26. if (prev->flags & PF_WQ_WORKER) {
  27. struct task_struct *to_wakeup;
  28.  
  29. to_wakeup =wq_worker_sleeping(prev, cpu);---------当一个工作线程要被调度器换出时,调用wq_worker_sleeping()看看是否需要唤醒同一个线程池中的其它内核线程。
  30. if (to_wakeup)
  31. try_to_wake_up_local(to_wakeup);---------------去唤醒to_wakeup线程
  32. }
  33. }
  34. switch_count = &prev->nvcsw;
  35. }
  36. ...
  37. }

wq_worker_sleeping()检查当前工作线程池中是否有内核线程正准备睡眠。如果有则返回task_struct,否则返回NULL。

在wq_worker_sleeping()返回不为NULL的情况下,调用try_to_wake_up_local()。

try_to_wake_up_local()是执行唤醒进程的操作。

  1. struct task_struct *wq_worker_sleeping(struct task_struct *task, int cpu)
  2. {
  3. struct worker *worker = kthread_data(task), *to_wakeup = NULL;
  4. struct worker_pool *pool;
  5.  
  6. /*
  7. * Rescuers, which may not have all the fields set up like normal
  8. * workers, also reach here, let's not access anything before
  9. * checking NOT_RUNNING.
  10. */
  11. if (worker->flags & WORKER_NOT_RUNNING)
  12. return NULL;
  13.  
  14. pool = worker->pool;
  15.  
  16. /* this can only happen on the local cpu */
  17. if (WARN_ON_ONCE(cpu != raw_smp_processor_id() || pool->cpu != cpu))
  18. return NULL;
  19.  
  20. /*
  21. * The counterpart of the following dec_and_test, implied mb,
  22. * worklist not empty test sequence is in insert_work().
  23. * Please read comment there.
  24. *
  25. * NOT_RUNNING is clear. This means that we're bound to and
  26. * running on the local cpu w/ rq lock held and preemption
  27. * disabled, which in turn means that none else could be
  28. * manipulating idle_list, so dereferencing idle_list without pool
  29. * lock is safe.
  30. */
  31. if (atomic_dec_and_test(&pool->nr_running) &&
  32. !list_empty(&pool->worklist))
  33. to_wakeup =first_idle_worker(pool);-------------------从worker_pool->idle_list中找到第一个worker工作线程。
  34. return to_wakeup ? to_wakeup->task : NULL;
  35. }
  36.  
  37. static struct worker *first_idle_worker(struct worker_pool *pool)
  38. {
  39. if (unlikely(list_empty(&pool->idle_list)))
  40. return NULL;
  41.  
  42. return list_first_entry(&pool->idle_list, struct worker, entry);
  43. }
  44.  
  45. static void try_to_wake_up_local(struct task_struct *p)
  46. {
  47. struct rq *rq = task_rq(p);
  48.  
  49. if (WARN_ON_ONCE(rq != this_rq()) ||
  50. WARN_ON_ONCE(p == current))
  51. return;
  52.  
  53. lockdep_assert_held(&rq->lock);
  54.  
  55. if (!raw_spin_trylock(&p->pi_lock)) {
  56. raw_spin_unlock(&rq->lock);
  57. raw_spin_lock(&p->pi_lock);
  58. raw_spin_lock(&rq->lock);
  59. }
  60.  
  61. if (!(p->state & TASK_NORMAL))
  62. goto out;
  63.  
  64. if (!task_on_rq_queued(p))
  65. ttwu_activate(rq, p, ENQUEUE_WAKEUP);
  66.  
  67. ttwu_do_wakeup(rq, p, 0);------------------------设置进程转改为TASK_RUNNING,并且调用sched_class->task_woken执行进程唤醒抢占操作。
  68. ttwu_stat(p, smp_processor_id(), 0);
  69. out:
  70. raw_spin_unlock(&p->pi_lock);
  71. }
  72.  
  73. static void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
  74. {
  75. activate_task(rq, p, en_flags);
  76. p->on_rq = TASK_ON_RQ_QUEUED;
  77.  
  78. /* if a worker is waking up, notify workqueue */
  79. if (p->flags & PF_WQ_WORKER)
  80. wq_worker_waking_up(p, cpu_of(rq));---------------增加nr_running技术,表示有一个工作线程马上就会被唤醒。
  81. }

6. 小结

联系方式:arnoldlu@qq.com

Linux中断管理 (3)workqueue工作队列【转】的更多相关文章

  1. Linux中断管理 (3)workqueue工作队列

    目录: <Linux中断管理> <Linux中断管理 (1)Linux中断管理机制> <Linux中断管理 (2)软中断和tasklet> <Linux中断管 ...

  2. Linux中断管理

    CPU和外设之间的交互,或CPU通过轮询机制查询,或外设通过中断机制主动上报. 对大部分外设中断比轮询效率高,但比如网卡驱动采取轮询比中断效率高. 这里重点关注ARM+Linux组合下中断管理,从底层 ...

  3. Linux中断管理 (1)Linux中断管理机制

    目录: <Linux中断管理> <Linux中断管理 (1)Linux中断管理机制> <Linux中断管理 (2)软中断和tasklet> <Linux中断管 ...

  4. Linux中断管理 (2)软中断和tasklet

    目录: <Linux中断管理> <Linux中断管理 (1)Linux中断管理机制> <Linux中断管理 (2)软中断和tasklet> <Linux中断管 ...

  5. Linux中断管理 (1)Linux中断管理机制【转】

    转自:https://www.cnblogs.com/arnoldlu/p/8659981.html 目录: <Linux中断管理> <Linux中断管理 (1)Linux中断管理机 ...

  6. Linux进程管理 (篇外)内核线程简要介绍

    关键词:kthread.irq.ksoftirqd.kworker.workqueues 在使用ps查看线程的时候,会有不少[...]名称的线程,这些有别于其它线程,都是内核线程. 其中多数内核线程从 ...

  7. Linux进程管理 (篇外)内核线程简要介绍【转】

    转自:https://www.cnblogs.com/arnoldlu/p/8336998.html 关键词:kthread.irq.ksoftirqd.kworker.workqueues 在使用p ...

  8. 【原创】Linux中断子系统(四)-Workqueue

    背景 Read the fucking source code! --By 鲁迅 A picture is worth a thousand words. --By 高尔基 说明: Kernel版本: ...

  9. 驱动: 中断【1】linux中断流程

    通常情况下,当一个给定的中断处理程序正在执行时,所有其他的中断都是打开的,所以这些不同中断线上的其他中断都能被处理,但当前中断总是被禁止的. 将中断处理切为两个部分或两半.中断处理程序上半部(top ...

随机推荐

  1. 微软发布Visual Studio Online公共预览版和ML.NET 1.4

    在今天的Ignite 2019上,Microsoft启动了 Visual Studio Online 公共预览版.Visual Studio Online将Visual Studio,云托管的开发人员 ...

  2. postman---postman自动发博客

    前面写了一篇如何通过Cookies值去登录博客园,今天我们来通过登录博客园之后,我们进行通过Postman自动写博客 自动写博客 1.打开Postman.填写博客园对应的Cookies: 2.抓取编写 ...

  3. web前端学习路线(干货)

  4. 【洛谷P2494】 [SDOI2011]保密(分数规划+最小割)

    洛谷 题意: 题意好绕好绕...不想写了. 思路: 首先类似于分数规划做法,二分答案得到到每个点的最小危险度. 然后就是在一个二分图中,两边撤掉最少的点(相应代价为上面算出的危险度)及相应边,使得中间 ...

  5. Hive 读书札记

    把数据从一个关系型数据库直接导入 Hive,使用 Sqoop.

  6. docker 创建mysql容器并且绑定到本地navicat

    docker pull mysql docker run --name mysql -itd -p 3306:3306 -e MYSQL_ROOT_PASSWORD=root1234 mysql do ...

  7. webrtc笔记(4): kurento 部署

    kurento是一个开源的webrtc mcu服务器,按官方的文档,建议在ubtntu上安装,过程如下: 注:建议先切换到root身份,如果不是root身份登录的,下列命令,请自行加上sudo . 另 ...

  8. MMM的又一周计划[2019 7.1→2019.7.7]

    发现今天是7.1然后又是星期一 来一发吧 本周目标: 1.二分图最佳匹配 2.网络流 3.HH的项链 4.洛谷rk前1000(目前1.1k) (upd:469) 5.AC260(35题,上周A了34, ...

  9. iOS Workflow 分享 - Debug Action

    有时候我们想要知道别人的 app 在调用 Share Extension 时提供了什么类型的数据以及具体数据是什么,我们可以自己在 Xcode 里面写个 app 去接收别人 app 的数据,但我们也可 ...

  10. 大话设计模式Python实现-模板方法模式

    模板方法模式(Template Method Pattern):定义一个操作中的算法骨架,将一些步骤延迟至子类中.模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤. 下面是一个模 ...