2 * kernel/workqueue.c - generic async execution with shared worker pool
4 * Copyright (C) 2002 Ingo Molnar
6 * Derived from the taskqueue/keventd code by:
7 * David Woodhouse <dwmw2@infradead.org>
9 * Kai Petzke <wpp@marie.physik.tu-berlin.de>
10 * Theodore Ts'o <tytso@mit.edu>
12 * Made to use alloc_percpu by Christoph Lameter.
14 * Copyright (C) 2010 SUSE Linux Products GmbH
15 * Copyright (C) 2010 Tejun Heo <tj@kernel.org>
17 * This is the generic async execution mechanism. Work items as are
18 * executed in process context. The worker pool is shared and
19 * automatically managed. There are two worker pools for each CPU (one for
20 * normal work items and the other for high priority ones) and some extra
21 * pools for workqueues which are not bound to any specific CPU - the
22 * number of these backing pools is dynamic.
24 * Please read Documentation/workqueue.txt for details.
27 #include <linux/export.h>
28 #include <linux/kernel.h>
29 #include <linux/sched.h>
30 #include <linux/init.h>
31 #include <linux/signal.h>
32 #include <linux/completion.h>
33 #include <linux/workqueue.h>
34 #include <linux/slab.h>
35 #include <linux/cpu.h>
36 #include <linux/notifier.h>
37 #include <linux/kthread.h>
38 #include <linux/hardirq.h>
39 #include <linux/mempolicy.h>
40 #include <linux/freezer.h>
41 #include <linux/kallsyms.h>
42 #include <linux/debug_locks.h>
43 #include <linux/lockdep.h>
44 #include <linux/idr.h>
45 #include <linux/jhash.h>
46 #include <linux/hashtable.h>
47 #include <linux/rculist.h>
48 #include <linux/nodemask.h>
49 #include <linux/moduleparam.h>
50 #include <linux/uaccess.h>
52 #include "workqueue_internal.h"
58 * A bound pool is either associated or disassociated with its CPU.
59 * While associated (!DISASSOCIATED), all workers are bound to the
60 * CPU and none has %WORKER_UNBOUND set and concurrency management
63 * While DISASSOCIATED, the cpu may be offline and all workers have
64 * %WORKER_UNBOUND set and concurrency management disabled, and may
65 * be executing on any CPU. The pool behaves as an unbound one.
67 * Note that DISASSOCIATED should be flipped only while holding
68 * attach_mutex to avoid changing binding state while
69 * worker_attach_to_pool() is in progress.
71 POOL_MANAGER_ACTIVE = 1 << 0, /* being managed */
72 POOL_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
75 WORKER_DIE = 1 << 1, /* die die die */
76 WORKER_IDLE = 1 << 2, /* is idle */
77 WORKER_PREP = 1 << 3, /* preparing to run works */
78 WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
79 WORKER_UNBOUND = 1 << 7, /* worker is unbound */
80 WORKER_REBOUND = 1 << 8, /* worker was rebound */
82 WORKER_NOT_RUNNING = WORKER_PREP | WORKER_CPU_INTENSIVE |
83 WORKER_UNBOUND | WORKER_REBOUND,
85 NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */
87 UNBOUND_POOL_HASH_ORDER = 6, /* hashed by pool->attrs */
88 BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
90 MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
91 IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
93 MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
94 /* call for help after 10ms
96 MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
97 CREATE_COOLDOWN = HZ, /* time to breath after fail */
100 * Rescue workers are used only on emergencies and shared by
101 * all cpus. Give MIN_NICE.
103 RESCUER_NICE_LEVEL = MIN_NICE,
104 HIGHPRI_NICE_LEVEL = MIN_NICE,
110 * Structure fields follow one of the following exclusion rules.
112 * I: Modifiable by initialization/destruction paths and read-only for
115 * P: Preemption protected. Disabling preemption is enough and should
116 * only be modified and accessed from the local cpu.
118 * L: pool->lock protected. Access with pool->lock held.
120 * X: During normal operation, modification requires pool->lock and should
121 * be done only from local cpu. Either disabling preemption on local
122 * cpu or grabbing pool->lock is enough for read access. If
123 * POOL_DISASSOCIATED is set, it's identical to L.
125 * A: pool->attach_mutex protected.
127 * PL: wq_pool_mutex protected.
129 * PR: wq_pool_mutex protected for writes. Sched-RCU protected for reads.
131 * PW: wq_pool_mutex and wq->mutex protected for writes. Either for reads.
133 * PWR: wq_pool_mutex and wq->mutex protected for writes. Either or
134 * sched-RCU for reads.
136 * WQ: wq->mutex protected.
138 * WR: wq->mutex protected for writes. Sched-RCU protected for reads.
140 * MD: wq_mayday_lock protected.
143 /* struct worker is defined in workqueue_internal.h */
146 spinlock_t lock; /* the pool lock */
147 int cpu; /* I: the associated cpu */
148 int node; /* I: the associated node ID */
149 int id; /* I: pool ID */
150 unsigned int flags; /* X: flags */
152 struct list_head worklist; /* L: list of pending works */
153 int nr_workers; /* L: total number of workers */
155 /* nr_idle includes the ones off idle_list for rebinding */
156 int nr_idle; /* L: currently idle ones */
158 struct list_head idle_list; /* X: list of idle workers */
159 struct timer_list idle_timer; /* L: worker idle timeout */
160 struct timer_list mayday_timer; /* L: SOS timer for workers */
162 /* a workers is either on busy_hash or idle_list, or the manager */
163 DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
164 /* L: hash of busy workers */
166 /* see manage_workers() for details on the two manager mutexes */
167 struct worker *manager; /* L: purely informational */
168 struct mutex attach_mutex; /* attach/detach exclusion */
169 struct list_head workers; /* A: attached workers */
170 struct completion *detach_completion; /* all workers detached */
172 struct ida worker_ida; /* worker IDs for task name */
174 struct workqueue_attrs *attrs; /* I: worker attributes */
175 struct hlist_node hash_node; /* PL: unbound_pool_hash node */
176 int refcnt; /* PL: refcnt for unbound pools */
179 * The current concurrency level. As it's likely to be accessed
180 * from other CPUs during try_to_wake_up(), put it in a separate
183 atomic_t nr_running ____cacheline_aligned_in_smp;
186 * Destruction of pool is sched-RCU protected to allow dereferences
187 * from get_work_pool().
190 } ____cacheline_aligned_in_smp;
193 * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
194 * of work_struct->data are used for flags and the remaining high bits
195 * point to the pwq; thus, pwqs need to be aligned at two's power of the
196 * number of flag bits.
198 struct pool_workqueue {
199 struct worker_pool *pool; /* I: the associated pool */
200 struct workqueue_struct *wq; /* I: the owning workqueue */
201 int work_color; /* L: current color */
202 int flush_color; /* L: flushing color */
203 int refcnt; /* L: reference count */
204 int nr_in_flight[WORK_NR_COLORS];
205 /* L: nr of in_flight works */
206 int nr_active; /* L: nr of active works */
207 int max_active; /* L: max active works */
208 struct list_head delayed_works; /* L: delayed works */
209 struct list_head pwqs_node; /* WR: node on wq->pwqs */
210 struct list_head mayday_node; /* MD: node on wq->maydays */
213 * Release of unbound pwq is punted to system_wq. See put_pwq()
214 * and pwq_unbound_release_workfn() for details. pool_workqueue
215 * itself is also sched-RCU protected so that the first pwq can be
216 * determined without grabbing wq->mutex.
218 struct work_struct unbound_release_work;
220 } __aligned(1 << WORK_STRUCT_FLAG_BITS);
223 * Structure used to wait for workqueue flush.
226 struct list_head list; /* WQ: list of flushers */
227 int flush_color; /* WQ: flush color waiting for */
228 struct completion done; /* flush completion */
234 * The externally visible workqueue. It relays the issued work items to
235 * the appropriate worker_pool through its pool_workqueues.
237 struct workqueue_struct {
238 struct list_head pwqs; /* WR: all pwqs of this wq */
239 struct list_head list; /* PR: list of all workqueues */
241 struct mutex mutex; /* protects this wq */
242 int work_color; /* WQ: current work color */
243 int flush_color; /* WQ: current flush color */
244 atomic_t nr_pwqs_to_flush; /* flush in progress */
245 struct wq_flusher *first_flusher; /* WQ: first flusher */
246 struct list_head flusher_queue; /* WQ: flush waiters */
247 struct list_head flusher_overflow; /* WQ: flush overflow list */
249 struct list_head maydays; /* MD: pwqs requesting rescue */
250 struct worker *rescuer; /* I: rescue worker */
252 int nr_drainers; /* WQ: drain in progress */
253 int saved_max_active; /* WQ: saved pwq max_active */
255 struct workqueue_attrs *unbound_attrs; /* PW: only for unbound wqs */
256 struct pool_workqueue *dfl_pwq; /* PW: only for unbound wqs */
259 struct wq_device *wq_dev; /* I: for sysfs interface */
261 #ifdef CONFIG_LOCKDEP
262 struct lockdep_map lockdep_map;
264 char name[WQ_NAME_LEN]; /* I: workqueue name */
267 * Destruction of workqueue_struct is sched-RCU protected to allow
268 * walking the workqueues list without grabbing wq_pool_mutex.
269 * This is used to dump all workqueues from sysrq.
273 /* hot fields used during command issue, aligned to cacheline */
274 unsigned int flags ____cacheline_aligned; /* WQ: WQ_* flags */
275 struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */
276 struct pool_workqueue __rcu *numa_pwq_tbl[]; /* PWR: unbound pwqs indexed by node */
279 static struct kmem_cache *pwq_cache;
281 static cpumask_var_t *wq_numa_possible_cpumask;
282 /* possible CPUs of each node */
284 static bool wq_disable_numa;
285 module_param_named(disable_numa, wq_disable_numa, bool, 0444);
287 /* see the comment above the definition of WQ_POWER_EFFICIENT */
288 static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
289 module_param_named(power_efficient, wq_power_efficient, bool, 0444);
291 static bool wq_numa_enabled; /* unbound NUMA affinity enabled */
293 /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
294 static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf;
296 static DEFINE_MUTEX(wq_pool_mutex); /* protects pools and workqueues list */
297 static DEFINE_SPINLOCK(wq_mayday_lock); /* protects wq->maydays list */
298 static DECLARE_WAIT_QUEUE_HEAD(wq_manager_wait); /* wait for manager to go away */
300 static LIST_HEAD(workqueues); /* PR: list of all workqueues */
301 static bool workqueue_freezing; /* PL: have wqs started freezing? */
303 static cpumask_var_t wq_unbound_cpumask; /* PL: low level cpumask for all unbound wqs */
305 /* the per-cpu worker pools */
306 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
309 static DEFINE_IDR(worker_pool_idr); /* PR: idr of all pools */
311 /* PL: hash of all unbound pools keyed by pool->attrs */
312 static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
314 /* I: attributes used when instantiating standard unbound pools on demand */
315 static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
317 /* I: attributes used when instantiating ordered pools on demand */
318 static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
320 struct workqueue_struct *system_wq __read_mostly;
321 EXPORT_SYMBOL(system_wq);
322 struct workqueue_struct *system_highpri_wq __read_mostly;
323 EXPORT_SYMBOL_GPL(system_highpri_wq);
324 struct workqueue_struct *system_long_wq __read_mostly;
325 EXPORT_SYMBOL_GPL(system_long_wq);
326 struct workqueue_struct *system_unbound_wq __read_mostly;
327 EXPORT_SYMBOL_GPL(system_unbound_wq);
328 struct workqueue_struct *system_freezable_wq __read_mostly;
329 EXPORT_SYMBOL_GPL(system_freezable_wq);
330 struct workqueue_struct *system_power_efficient_wq __read_mostly;
331 EXPORT_SYMBOL_GPL(system_power_efficient_wq);
332 struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
333 EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
335 static int worker_thread(void *__worker);
336 static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
338 #define CREATE_TRACE_POINTS
339 #include <trace/events/workqueue.h>
341 #define assert_rcu_or_pool_mutex() \
342 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() && \
343 !lockdep_is_held(&wq_pool_mutex), \
344 "sched RCU or wq_pool_mutex should be held")
346 #define assert_rcu_or_wq_mutex(wq) \
347 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() && \
348 !lockdep_is_held(&wq->mutex), \
349 "sched RCU or wq->mutex should be held")
351 #define assert_rcu_or_wq_mutex_or_pool_mutex(wq) \
352 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() && \
353 !lockdep_is_held(&wq->mutex) && \
354 !lockdep_is_held(&wq_pool_mutex), \
355 "sched RCU, wq->mutex or wq_pool_mutex should be held")
357 #define for_each_cpu_worker_pool(pool, cpu) \
358 for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
359 (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
363 * for_each_pool - iterate through all worker_pools in the system
364 * @pool: iteration cursor
365 * @pi: integer used for iteration
367 * This must be called either with wq_pool_mutex held or sched RCU read
368 * locked. If the pool needs to be used beyond the locking in effect, the
369 * caller is responsible for guaranteeing that the pool stays online.
371 * The if/else clause exists only for the lockdep assertion and can be
374 #define for_each_pool(pool, pi) \
375 idr_for_each_entry(&worker_pool_idr, pool, pi) \
376 if (({ assert_rcu_or_pool_mutex(); false; })) { } \
380 * for_each_pool_worker - iterate through all workers of a worker_pool
381 * @worker: iteration cursor
382 * @pool: worker_pool to iterate workers of
384 * This must be called with @pool->attach_mutex.
386 * The if/else clause exists only for the lockdep assertion and can be
389 #define for_each_pool_worker(worker, pool) \
390 list_for_each_entry((worker), &(pool)->workers, node) \
391 if (({ lockdep_assert_held(&pool->attach_mutex); false; })) { } \
395 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
396 * @pwq: iteration cursor
397 * @wq: the target workqueue
399 * This must be called either with wq->mutex held or sched RCU read locked.
400 * If the pwq needs to be used beyond the locking in effect, the caller is
401 * responsible for guaranteeing that the pwq stays online.
403 * The if/else clause exists only for the lockdep assertion and can be
406 #define for_each_pwq(pwq, wq) \
407 list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node) \
408 if (({ assert_rcu_or_wq_mutex(wq); false; })) { } \
411 #ifdef CONFIG_DEBUG_OBJECTS_WORK
413 static struct debug_obj_descr work_debug_descr;
415 static void *work_debug_hint(void *addr)
417 return ((struct work_struct *) addr)->func;
421 * fixup_init is called when:
422 * - an active object is initialized
424 static int work_fixup_init(void *addr, enum debug_obj_state state)
426 struct work_struct *work = addr;
429 case ODEBUG_STATE_ACTIVE:
430 cancel_work_sync(work);
431 debug_object_init(work, &work_debug_descr);
439 * fixup_activate is called when:
440 * - an active object is activated
441 * - an unknown object is activated (might be a statically initialized object)
443 static int work_fixup_activate(void *addr, enum debug_obj_state state)
445 struct work_struct *work = addr;
449 case ODEBUG_STATE_NOTAVAILABLE:
451 * This is not really a fixup. The work struct was
452 * statically initialized. We just make sure that it
453 * is tracked in the object tracker.
455 if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
456 debug_object_init(work, &work_debug_descr);
457 debug_object_activate(work, &work_debug_descr);
463 case ODEBUG_STATE_ACTIVE:
472 * fixup_free is called when:
473 * - an active object is freed
475 static int work_fixup_free(void *addr, enum debug_obj_state state)
477 struct work_struct *work = addr;
480 case ODEBUG_STATE_ACTIVE:
481 cancel_work_sync(work);
482 debug_object_free(work, &work_debug_descr);
489 static struct debug_obj_descr work_debug_descr = {
490 .name = "work_struct",
491 .debug_hint = work_debug_hint,
492 .fixup_init = work_fixup_init,
493 .fixup_activate = work_fixup_activate,
494 .fixup_free = work_fixup_free,
497 static inline void debug_work_activate(struct work_struct *work)
499 debug_object_activate(work, &work_debug_descr);
502 static inline void debug_work_deactivate(struct work_struct *work)
504 debug_object_deactivate(work, &work_debug_descr);
507 void __init_work(struct work_struct *work, int onstack)
510 debug_object_init_on_stack(work, &work_debug_descr);
512 debug_object_init(work, &work_debug_descr);
514 EXPORT_SYMBOL_GPL(__init_work);
516 void destroy_work_on_stack(struct work_struct *work)
518 debug_object_free(work, &work_debug_descr);
520 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
522 void destroy_delayed_work_on_stack(struct delayed_work *work)
524 destroy_timer_on_stack(&work->timer);
525 debug_object_free(&work->work, &work_debug_descr);
527 EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
530 static inline void debug_work_activate(struct work_struct *work) { }
531 static inline void debug_work_deactivate(struct work_struct *work) { }
535 * worker_pool_assign_id - allocate ID and assing it to @pool
536 * @pool: the pool pointer of interest
538 * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
539 * successfully, -errno on failure.
541 static int worker_pool_assign_id(struct worker_pool *pool)
545 lockdep_assert_held(&wq_pool_mutex);
547 ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
557 * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
558 * @wq: the target workqueue
561 * This must be called with any of wq_pool_mutex, wq->mutex or sched RCU
563 * If the pwq needs to be used beyond the locking in effect, the caller is
564 * responsible for guaranteeing that the pwq stays online.
566 * Return: The unbound pool_workqueue for @node.
568 static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
571 assert_rcu_or_wq_mutex_or_pool_mutex(wq);
574 * XXX: @node can be NUMA_NO_NODE if CPU goes offline while a
575 * delayed item is pending. The plan is to keep CPU -> NODE
576 * mapping valid and stable across CPU on/offlines. Once that
577 * happens, this workaround can be removed.
579 if (unlikely(node == NUMA_NO_NODE))
582 return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
585 static unsigned int work_color_to_flags(int color)
587 return color << WORK_STRUCT_COLOR_SHIFT;
590 static int get_work_color(struct work_struct *work)
592 return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
593 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
596 static int work_next_color(int color)
598 return (color + 1) % WORK_NR_COLORS;
602 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
603 * contain the pointer to the queued pwq. Once execution starts, the flag
604 * is cleared and the high bits contain OFFQ flags and pool ID.
606 * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
607 * and clear_work_data() can be used to set the pwq, pool or clear
608 * work->data. These functions should only be called while the work is
609 * owned - ie. while the PENDING bit is set.
611 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
612 * corresponding to a work. Pool is available once the work has been
613 * queued anywhere after initialization until it is sync canceled. pwq is
614 * available only while the work item is queued.
616 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
617 * canceled. While being canceled, a work item may have its PENDING set
618 * but stay off timer and worklist for arbitrarily long and nobody should
619 * try to steal the PENDING bit.
621 static inline void set_work_data(struct work_struct *work, unsigned long data,
624 WARN_ON_ONCE(!work_pending(work));
625 atomic_long_set(&work->data, data | flags | work_static(work));
628 static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
629 unsigned long extra_flags)
631 set_work_data(work, (unsigned long)pwq,
632 WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
635 static void set_work_pool_and_keep_pending(struct work_struct *work,
638 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
639 WORK_STRUCT_PENDING);
642 static void set_work_pool_and_clear_pending(struct work_struct *work,
646 * The following wmb is paired with the implied mb in
647 * test_and_set_bit(PENDING) and ensures all updates to @work made
648 * here are visible to and precede any updates by the next PENDING
652 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
654 * The following mb guarantees that previous clear of a PENDING bit
655 * will not be reordered with any speculative LOADS or STORES from
656 * work->current_func, which is executed afterwards. This possible
657 * reordering can lead to a missed execution on attempt to qeueue
658 * the same @work. E.g. consider this case:
661 * ---------------------------- --------------------------------
663 * 1 STORE event_indicated
664 * 2 queue_work_on() {
665 * 3 test_and_set_bit(PENDING)
666 * 4 } set_..._and_clear_pending() {
667 * 5 set_work_data() # clear bit
669 * 7 work->current_func() {
670 * 8 LOAD event_indicated
673 * Without an explicit full barrier speculative LOAD on line 8 can
674 * be executed before CPU#0 does STORE on line 1. If that happens,
675 * CPU#0 observes the PENDING bit is still set and new execution of
676 * a @work is not queued in a hope, that CPU#1 will eventually
677 * finish the queued @work. Meanwhile CPU#1 does not see
678 * event_indicated is set, because speculative LOAD was executed
679 * before actual STORE.
684 static void clear_work_data(struct work_struct *work)
686 smp_wmb(); /* see set_work_pool_and_clear_pending() */
687 set_work_data(work, WORK_STRUCT_NO_POOL, 0);
690 static struct pool_workqueue *get_work_pwq(struct work_struct *work)
692 unsigned long data = atomic_long_read(&work->data);
694 if (data & WORK_STRUCT_PWQ)
695 return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
701 * get_work_pool - return the worker_pool a given work was associated with
702 * @work: the work item of interest
704 * Pools are created and destroyed under wq_pool_mutex, and allows read
705 * access under sched-RCU read lock. As such, this function should be
706 * called under wq_pool_mutex or with preemption disabled.
708 * All fields of the returned pool are accessible as long as the above
709 * mentioned locking is in effect. If the returned pool needs to be used
710 * beyond the critical section, the caller is responsible for ensuring the
711 * returned pool is and stays online.
713 * Return: The worker_pool @work was last associated with. %NULL if none.
715 static struct worker_pool *get_work_pool(struct work_struct *work)
717 unsigned long data = atomic_long_read(&work->data);
720 assert_rcu_or_pool_mutex();
722 if (data & WORK_STRUCT_PWQ)
723 return ((struct pool_workqueue *)
724 (data & WORK_STRUCT_WQ_DATA_MASK))->pool;
726 pool_id = data >> WORK_OFFQ_POOL_SHIFT;
727 if (pool_id == WORK_OFFQ_POOL_NONE)
730 return idr_find(&worker_pool_idr, pool_id);
734 * get_work_pool_id - return the worker pool ID a given work is associated with
735 * @work: the work item of interest
737 * Return: The worker_pool ID @work was last associated with.
738 * %WORK_OFFQ_POOL_NONE if none.
740 static int get_work_pool_id(struct work_struct *work)
742 unsigned long data = atomic_long_read(&work->data);
744 if (data & WORK_STRUCT_PWQ)
745 return ((struct pool_workqueue *)
746 (data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
748 return data >> WORK_OFFQ_POOL_SHIFT;
751 static void mark_work_canceling(struct work_struct *work)
753 unsigned long pool_id = get_work_pool_id(work);
755 pool_id <<= WORK_OFFQ_POOL_SHIFT;
756 set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
759 static bool work_is_canceling(struct work_struct *work)
761 unsigned long data = atomic_long_read(&work->data);
763 return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
767 * Policy functions. These define the policies on how the global worker
768 * pools are managed. Unless noted otherwise, these functions assume that
769 * they're being called with pool->lock held.
772 static bool __need_more_worker(struct worker_pool *pool)
774 return !atomic_read(&pool->nr_running);
778 * Need to wake up a worker? Called from anything but currently
781 * Note that, because unbound workers never contribute to nr_running, this
782 * function will always return %true for unbound pools as long as the
783 * worklist isn't empty.
785 static bool need_more_worker(struct worker_pool *pool)
787 return !list_empty(&pool->worklist) && __need_more_worker(pool);
790 /* Can I start working? Called from busy but !running workers. */
791 static bool may_start_working(struct worker_pool *pool)
793 return pool->nr_idle;
796 /* Do I need to keep working? Called from currently running workers. */
797 static bool keep_working(struct worker_pool *pool)
799 return !list_empty(&pool->worklist) &&
800 atomic_read(&pool->nr_running) <= 1;
803 /* Do we need a new worker? Called from manager. */
804 static bool need_to_create_worker(struct worker_pool *pool)
806 return need_more_worker(pool) && !may_start_working(pool);
809 /* Do we have too many workers and should some go away? */
810 static bool too_many_workers(struct worker_pool *pool)
812 bool managing = pool->flags & POOL_MANAGER_ACTIVE;
813 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
814 int nr_busy = pool->nr_workers - nr_idle;
816 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
823 /* Return the first idle worker. Safe with preemption disabled */
824 static struct worker *first_idle_worker(struct worker_pool *pool)
826 if (unlikely(list_empty(&pool->idle_list)))
829 return list_first_entry(&pool->idle_list, struct worker, entry);
833 * wake_up_worker - wake up an idle worker
834 * @pool: worker pool to wake worker from
836 * Wake up the first idle worker of @pool.
839 * spin_lock_irq(pool->lock).
841 static void wake_up_worker(struct worker_pool *pool)
843 struct worker *worker = first_idle_worker(pool);
846 wake_up_process(worker->task);
850 * wq_worker_waking_up - a worker is waking up
851 * @task: task waking up
852 * @cpu: CPU @task is waking up to
854 * This function is called during try_to_wake_up() when a worker is
858 * spin_lock_irq(rq->lock)
860 void wq_worker_waking_up(struct task_struct *task, int cpu)
862 struct worker *worker = kthread_data(task);
864 if (!(worker->flags & WORKER_NOT_RUNNING)) {
865 WARN_ON_ONCE(worker->pool->cpu != cpu);
866 atomic_inc(&worker->pool->nr_running);
871 * wq_worker_sleeping - a worker is going to sleep
872 * @task: task going to sleep
873 * @cpu: CPU in question, must be the current CPU number
875 * This function is called during schedule() when a busy worker is
876 * going to sleep. Worker on the same cpu can be woken up by
877 * returning pointer to its task.
880 * spin_lock_irq(rq->lock)
883 * Worker task on @cpu to wake up, %NULL if none.
885 struct task_struct *wq_worker_sleeping(struct task_struct *task, int cpu)
887 struct worker *worker = kthread_data(task), *to_wakeup = NULL;
888 struct worker_pool *pool;
891 * Rescuers, which may not have all the fields set up like normal
892 * workers, also reach here, let's not access anything before
893 * checking NOT_RUNNING.
895 if (worker->flags & WORKER_NOT_RUNNING)
900 /* this can only happen on the local cpu */
901 if (WARN_ON_ONCE(cpu != raw_smp_processor_id() || pool->cpu != cpu))
905 * The counterpart of the following dec_and_test, implied mb,
906 * worklist not empty test sequence is in insert_work().
907 * Please read comment there.
909 * NOT_RUNNING is clear. This means that we're bound to and
910 * running on the local cpu w/ rq lock held and preemption
911 * disabled, which in turn means that none else could be
912 * manipulating idle_list, so dereferencing idle_list without pool
915 if (atomic_dec_and_test(&pool->nr_running) &&
916 !list_empty(&pool->worklist))
917 to_wakeup = first_idle_worker(pool);
918 return to_wakeup ? to_wakeup->task : NULL;
922 * worker_set_flags - set worker flags and adjust nr_running accordingly
924 * @flags: flags to set
926 * Set @flags in @worker->flags and adjust nr_running accordingly.
929 * spin_lock_irq(pool->lock)
931 static inline void worker_set_flags(struct worker *worker, unsigned int flags)
933 struct worker_pool *pool = worker->pool;
935 WARN_ON_ONCE(worker->task != current);
937 /* If transitioning into NOT_RUNNING, adjust nr_running. */
938 if ((flags & WORKER_NOT_RUNNING) &&
939 !(worker->flags & WORKER_NOT_RUNNING)) {
940 atomic_dec(&pool->nr_running);
943 worker->flags |= flags;
947 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
949 * @flags: flags to clear
951 * Clear @flags in @worker->flags and adjust nr_running accordingly.
954 * spin_lock_irq(pool->lock)
956 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
958 struct worker_pool *pool = worker->pool;
959 unsigned int oflags = worker->flags;
961 WARN_ON_ONCE(worker->task != current);
963 worker->flags &= ~flags;
966 * If transitioning out of NOT_RUNNING, increment nr_running. Note
967 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
968 * of multiple flags, not a single flag.
970 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
971 if (!(worker->flags & WORKER_NOT_RUNNING))
972 atomic_inc(&pool->nr_running);
976 * find_worker_executing_work - find worker which is executing a work
977 * @pool: pool of interest
978 * @work: work to find worker for
980 * Find a worker which is executing @work on @pool by searching
981 * @pool->busy_hash which is keyed by the address of @work. For a worker
982 * to match, its current execution should match the address of @work and
983 * its work function. This is to avoid unwanted dependency between
984 * unrelated work executions through a work item being recycled while still
987 * This is a bit tricky. A work item may be freed once its execution
988 * starts and nothing prevents the freed area from being recycled for
989 * another work item. If the same work item address ends up being reused
990 * before the original execution finishes, workqueue will identify the
991 * recycled work item as currently executing and make it wait until the
992 * current execution finishes, introducing an unwanted dependency.
994 * This function checks the work item address and work function to avoid
995 * false positives. Note that this isn't complete as one may construct a
996 * work function which can introduce dependency onto itself through a
997 * recycled work item. Well, if somebody wants to shoot oneself in the
998 * foot that badly, there's only so much we can do, and if such deadlock
999 * actually occurs, it should be easy to locate the culprit work function.
1002 * spin_lock_irq(pool->lock).
1005 * Pointer to worker which is executing @work if found, %NULL
1008 static struct worker *find_worker_executing_work(struct worker_pool *pool,
1009 struct work_struct *work)
1011 struct worker *worker;
1013 hash_for_each_possible(pool->busy_hash, worker, hentry,
1014 (unsigned long)work)
1015 if (worker->current_work == work &&
1016 worker->current_func == work->func)
1023 * move_linked_works - move linked works to a list
1024 * @work: start of series of works to be scheduled
1025 * @head: target list to append @work to
1026 * @nextp: out parameter for nested worklist walking
1028 * Schedule linked works starting from @work to @head. Work series to
1029 * be scheduled starts at @work and includes any consecutive work with
1030 * WORK_STRUCT_LINKED set in its predecessor.
1032 * If @nextp is not NULL, it's updated to point to the next work of
1033 * the last scheduled work. This allows move_linked_works() to be
1034 * nested inside outer list_for_each_entry_safe().
1037 * spin_lock_irq(pool->lock).
1039 static void move_linked_works(struct work_struct *work, struct list_head *head,
1040 struct work_struct **nextp)
1042 struct work_struct *n;
1045 * Linked worklist will always end before the end of the list,
1046 * use NULL for list head.
1048 list_for_each_entry_safe_from(work, n, NULL, entry) {
1049 list_move_tail(&work->entry, head);
1050 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1055 * If we're already inside safe list traversal and have moved
1056 * multiple works to the scheduled queue, the next position
1057 * needs to be updated.
1064 * get_pwq - get an extra reference on the specified pool_workqueue
1065 * @pwq: pool_workqueue to get
1067 * Obtain an extra reference on @pwq. The caller should guarantee that
1068 * @pwq has positive refcnt and be holding the matching pool->lock.
1070 static void get_pwq(struct pool_workqueue *pwq)
1072 lockdep_assert_held(&pwq->pool->lock);
1073 WARN_ON_ONCE(pwq->refcnt <= 0);
1078 * put_pwq - put a pool_workqueue reference
1079 * @pwq: pool_workqueue to put
1081 * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
1082 * destruction. The caller should be holding the matching pool->lock.
1084 static void put_pwq(struct pool_workqueue *pwq)
1086 lockdep_assert_held(&pwq->pool->lock);
1087 if (likely(--pwq->refcnt))
1089 if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
1092 * @pwq can't be released under pool->lock, bounce to
1093 * pwq_unbound_release_workfn(). This never recurses on the same
1094 * pool->lock as this path is taken only for unbound workqueues and
1095 * the release work item is scheduled on a per-cpu workqueue. To
1096 * avoid lockdep warning, unbound pool->locks are given lockdep
1097 * subclass of 1 in get_unbound_pool().
1099 schedule_work(&pwq->unbound_release_work);
1103 * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1104 * @pwq: pool_workqueue to put (can be %NULL)
1106 * put_pwq() with locking. This function also allows %NULL @pwq.
1108 static void put_pwq_unlocked(struct pool_workqueue *pwq)
1112 * As both pwqs and pools are sched-RCU protected, the
1113 * following lock operations are safe.
1115 spin_lock_irq(&pwq->pool->lock);
1117 spin_unlock_irq(&pwq->pool->lock);
1121 static void pwq_activate_delayed_work(struct work_struct *work)
1123 struct pool_workqueue *pwq = get_work_pwq(work);
1125 trace_workqueue_activate_work(work);
1126 move_linked_works(work, &pwq->pool->worklist, NULL);
1127 __clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
1131 static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
1133 struct work_struct *work = list_first_entry(&pwq->delayed_works,
1134 struct work_struct, entry);
1136 pwq_activate_delayed_work(work);
1140 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1141 * @pwq: pwq of interest
1142 * @color: color of work which left the queue
1144 * A work either has completed or is removed from pending queue,
1145 * decrement nr_in_flight of its pwq and handle workqueue flushing.
1148 * spin_lock_irq(pool->lock).
1150 static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
1152 /* uncolored work items don't participate in flushing or nr_active */
1153 if (color == WORK_NO_COLOR)
1156 pwq->nr_in_flight[color]--;
1159 if (!list_empty(&pwq->delayed_works)) {
1160 /* one down, submit a delayed one */
1161 if (pwq->nr_active < pwq->max_active)
1162 pwq_activate_first_delayed(pwq);
1165 /* is flush in progress and are we at the flushing tip? */
1166 if (likely(pwq->flush_color != color))
1169 /* are there still in-flight works? */
1170 if (pwq->nr_in_flight[color])
1173 /* this pwq is done, clear flush_color */
1174 pwq->flush_color = -1;
1177 * If this was the last pwq, wake up the first flusher. It
1178 * will handle the rest.
1180 if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1181 complete(&pwq->wq->first_flusher->done);
1187 * try_to_grab_pending - steal work item from worklist and disable irq
1188 * @work: work item to steal
1189 * @is_dwork: @work is a delayed_work
1190 * @flags: place to store irq state
1192 * Try to grab PENDING bit of @work. This function can handle @work in any
1193 * stable state - idle, on timer or on worklist.
1196 * 1 if @work was pending and we successfully stole PENDING
1197 * 0 if @work was idle and we claimed PENDING
1198 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1199 * -ENOENT if someone else is canceling @work, this state may persist
1200 * for arbitrarily long
1203 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1204 * interrupted while holding PENDING and @work off queue, irq must be
1205 * disabled on entry. This, combined with delayed_work->timer being
1206 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1208 * On successful return, >= 0, irq is disabled and the caller is
1209 * responsible for releasing it using local_irq_restore(*@flags).
1211 * This function is safe to call from any context including IRQ handler.
1213 static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1214 unsigned long *flags)
1216 struct worker_pool *pool;
1217 struct pool_workqueue *pwq;
1219 local_irq_save(*flags);
1221 /* try to steal the timer if it exists */
1223 struct delayed_work *dwork = to_delayed_work(work);
1226 * dwork->timer is irqsafe. If del_timer() fails, it's
1227 * guaranteed that the timer is not queued anywhere and not
1228 * running on the local CPU.
1230 if (likely(del_timer(&dwork->timer)))
1234 /* try to claim PENDING the normal way */
1235 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1239 * The queueing is in progress, or it is already queued. Try to
1240 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1242 pool = get_work_pool(work);
1246 spin_lock(&pool->lock);
1248 * work->data is guaranteed to point to pwq only while the work
1249 * item is queued on pwq->wq, and both updating work->data to point
1250 * to pwq on queueing and to pool on dequeueing are done under
1251 * pwq->pool->lock. This in turn guarantees that, if work->data
1252 * points to pwq which is associated with a locked pool, the work
1253 * item is currently queued on that pool.
1255 pwq = get_work_pwq(work);
1256 if (pwq && pwq->pool == pool) {
1257 debug_work_deactivate(work);
1260 * A delayed work item cannot be grabbed directly because
1261 * it might have linked NO_COLOR work items which, if left
1262 * on the delayed_list, will confuse pwq->nr_active
1263 * management later on and cause stall. Make sure the work
1264 * item is activated before grabbing.
1266 if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1267 pwq_activate_delayed_work(work);
1269 list_del_init(&work->entry);
1270 pwq_dec_nr_in_flight(pwq, get_work_color(work));
1272 /* work->data points to pwq iff queued, point to pool */
1273 set_work_pool_and_keep_pending(work, pool->id);
1275 spin_unlock(&pool->lock);
1278 spin_unlock(&pool->lock);
1280 local_irq_restore(*flags);
1281 if (work_is_canceling(work))
1288 * insert_work - insert a work into a pool
1289 * @pwq: pwq @work belongs to
1290 * @work: work to insert
1291 * @head: insertion point
1292 * @extra_flags: extra WORK_STRUCT_* flags to set
1294 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
1295 * work_struct flags.
1298 * spin_lock_irq(pool->lock).
1300 static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1301 struct list_head *head, unsigned int extra_flags)
1303 struct worker_pool *pool = pwq->pool;
1305 /* we own @work, set data and link */
1306 set_work_pwq(work, pwq, extra_flags);
1307 list_add_tail(&work->entry, head);
1311 * Ensure either wq_worker_sleeping() sees the above
1312 * list_add_tail() or we see zero nr_running to avoid workers lying
1313 * around lazily while there are works to be processed.
1317 if (__need_more_worker(pool))
1318 wake_up_worker(pool);
1322 * Test whether @work is being queued from another work executing on the
1325 static bool is_chained_work(struct workqueue_struct *wq)
1327 struct worker *worker;
1329 worker = current_wq_worker();
1331 * Return %true iff I'm a worker execuing a work item on @wq. If
1332 * I'm @worker, it's safe to dereference it without locking.
1334 return worker && worker->current_pwq->wq == wq;
1337 static void __queue_work(int cpu, struct workqueue_struct *wq,
1338 struct work_struct *work)
1340 struct pool_workqueue *pwq;
1341 struct worker_pool *last_pool;
1342 struct list_head *worklist;
1343 unsigned int work_flags;
1344 unsigned int req_cpu = cpu;
1347 * While a work item is PENDING && off queue, a task trying to
1348 * steal the PENDING will busy-loop waiting for it to either get
1349 * queued or lose PENDING. Grabbing PENDING and queueing should
1350 * happen with IRQ disabled.
1352 WARN_ON_ONCE(!irqs_disabled());
1355 /* if draining, only works from the same workqueue are allowed */
1356 if (unlikely(wq->flags & __WQ_DRAINING) &&
1357 WARN_ON_ONCE(!is_chained_work(wq)))
1360 if (req_cpu == WORK_CPU_UNBOUND)
1361 cpu = raw_smp_processor_id();
1363 /* pwq which will be used unless @work is executing elsewhere */
1364 if (!(wq->flags & WQ_UNBOUND))
1365 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1367 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1370 * If @work was previously on a different pool, it might still be
1371 * running there, in which case the work needs to be queued on that
1372 * pool to guarantee non-reentrancy.
1374 last_pool = get_work_pool(work);
1375 if (last_pool && last_pool != pwq->pool) {
1376 struct worker *worker;
1378 spin_lock(&last_pool->lock);
1380 worker = find_worker_executing_work(last_pool, work);
1382 if (worker && worker->current_pwq->wq == wq) {
1383 pwq = worker->current_pwq;
1385 /* meh... not running there, queue here */
1386 spin_unlock(&last_pool->lock);
1387 spin_lock(&pwq->pool->lock);
1390 spin_lock(&pwq->pool->lock);
1394 * pwq is determined and locked. For unbound pools, we could have
1395 * raced with pwq release and it could already be dead. If its
1396 * refcnt is zero, repeat pwq selection. Note that pwqs never die
1397 * without another pwq replacing it in the numa_pwq_tbl or while
1398 * work items are executing on it, so the retrying is guaranteed to
1399 * make forward-progress.
1401 if (unlikely(!pwq->refcnt)) {
1402 if (wq->flags & WQ_UNBOUND) {
1403 spin_unlock(&pwq->pool->lock);
1408 WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
1412 /* pwq determined, queue */
1413 trace_workqueue_queue_work(req_cpu, pwq, work);
1415 if (WARN_ON(!list_empty(&work->entry))) {
1416 spin_unlock(&pwq->pool->lock);
1420 pwq->nr_in_flight[pwq->work_color]++;
1421 work_flags = work_color_to_flags(pwq->work_color);
1423 if (likely(pwq->nr_active < pwq->max_active)) {
1424 trace_workqueue_activate_work(work);
1426 worklist = &pwq->pool->worklist;
1428 work_flags |= WORK_STRUCT_DELAYED;
1429 worklist = &pwq->delayed_works;
1432 debug_work_activate(work);
1433 insert_work(pwq, work, worklist, work_flags);
1435 spin_unlock(&pwq->pool->lock);
1439 * queue_work_on - queue work on specific cpu
1440 * @cpu: CPU number to execute work on
1441 * @wq: workqueue to use
1442 * @work: work to queue
1444 * We queue the work to a specific CPU, the caller must ensure it
1447 * Return: %false if @work was already on a queue, %true otherwise.
1449 bool queue_work_on(int cpu, struct workqueue_struct *wq,
1450 struct work_struct *work)
1453 unsigned long flags;
1455 local_irq_save(flags);
1457 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1458 __queue_work(cpu, wq, work);
1462 local_irq_restore(flags);
1465 EXPORT_SYMBOL(queue_work_on);
1467 void delayed_work_timer_fn(unsigned long __data)
1469 struct delayed_work *dwork = (struct delayed_work *)__data;
1471 /* should have been called from irqsafe timer with irq already off */
1472 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
1474 EXPORT_SYMBOL(delayed_work_timer_fn);
1476 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
1477 struct delayed_work *dwork, unsigned long delay)
1479 struct timer_list *timer = &dwork->timer;
1480 struct work_struct *work = &dwork->work;
1483 WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
1484 timer->data != (unsigned long)dwork);
1485 WARN_ON_ONCE(timer_pending(timer));
1486 WARN_ON_ONCE(!list_empty(&work->entry));
1489 * If @delay is 0, queue @dwork->work immediately. This is for
1490 * both optimization and correctness. The earliest @timer can
1491 * expire is on the closest next tick and delayed_work users depend
1492 * on that there's no such delay when @delay is 0.
1495 __queue_work(cpu, wq, &dwork->work);
1499 timer_stats_timer_set_start_info(&dwork->timer);
1503 timer->expires = jiffies + delay;
1505 if (unlikely(cpu != WORK_CPU_UNBOUND))
1506 add_timer_on(timer, cpu);
1512 * queue_delayed_work_on - queue work on specific CPU after delay
1513 * @cpu: CPU number to execute work on
1514 * @wq: workqueue to use
1515 * @dwork: work to queue
1516 * @delay: number of jiffies to wait before queueing
1518 * Return: %false if @work was already on a queue, %true otherwise. If
1519 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1522 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1523 struct delayed_work *dwork, unsigned long delay)
1525 struct work_struct *work = &dwork->work;
1527 unsigned long flags;
1529 /* read the comment in __queue_work() */
1530 local_irq_save(flags);
1532 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1533 __queue_delayed_work(cpu, wq, dwork, delay);
1537 local_irq_restore(flags);
1540 EXPORT_SYMBOL(queue_delayed_work_on);
1543 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1544 * @cpu: CPU number to execute work on
1545 * @wq: workqueue to use
1546 * @dwork: work to queue
1547 * @delay: number of jiffies to wait before queueing
1549 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1550 * modify @dwork's timer so that it expires after @delay. If @delay is
1551 * zero, @work is guaranteed to be scheduled immediately regardless of its
1554 * Return: %false if @dwork was idle and queued, %true if @dwork was
1555 * pending and its timer was modified.
1557 * This function is safe to call from any context including IRQ handler.
1558 * See try_to_grab_pending() for details.
1560 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
1561 struct delayed_work *dwork, unsigned long delay)
1563 unsigned long flags;
1567 ret = try_to_grab_pending(&dwork->work, true, &flags);
1568 } while (unlikely(ret == -EAGAIN));
1570 if (likely(ret >= 0)) {
1571 __queue_delayed_work(cpu, wq, dwork, delay);
1572 local_irq_restore(flags);
1575 /* -ENOENT from try_to_grab_pending() becomes %true */
1578 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
1581 * worker_enter_idle - enter idle state
1582 * @worker: worker which is entering idle state
1584 * @worker is entering idle state. Update stats and idle timer if
1588 * spin_lock_irq(pool->lock).
1590 static void worker_enter_idle(struct worker *worker)
1592 struct worker_pool *pool = worker->pool;
1594 if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
1595 WARN_ON_ONCE(!list_empty(&worker->entry) &&
1596 (worker->hentry.next || worker->hentry.pprev)))
1599 /* can't use worker_set_flags(), also called from create_worker() */
1600 worker->flags |= WORKER_IDLE;
1602 worker->last_active = jiffies;
1604 /* idle_list is LIFO */
1605 list_add(&worker->entry, &pool->idle_list);
1607 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1608 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1611 * Sanity check nr_running. Because wq_unbind_fn() releases
1612 * pool->lock between setting %WORKER_UNBOUND and zapping
1613 * nr_running, the warning may trigger spuriously. Check iff
1614 * unbind is not in progress.
1616 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1617 pool->nr_workers == pool->nr_idle &&
1618 atomic_read(&pool->nr_running));
1622 * worker_leave_idle - leave idle state
1623 * @worker: worker which is leaving idle state
1625 * @worker is leaving idle state. Update stats.
1628 * spin_lock_irq(pool->lock).
1630 static void worker_leave_idle(struct worker *worker)
1632 struct worker_pool *pool = worker->pool;
1634 if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
1636 worker_clr_flags(worker, WORKER_IDLE);
1638 list_del_init(&worker->entry);
1641 static struct worker *alloc_worker(int node)
1643 struct worker *worker;
1645 worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
1647 INIT_LIST_HEAD(&worker->entry);
1648 INIT_LIST_HEAD(&worker->scheduled);
1649 INIT_LIST_HEAD(&worker->node);
1650 /* on creation a worker is in !idle && prep state */
1651 worker->flags = WORKER_PREP;
1657 * worker_attach_to_pool() - attach a worker to a pool
1658 * @worker: worker to be attached
1659 * @pool: the target pool
1661 * Attach @worker to @pool. Once attached, the %WORKER_UNBOUND flag and
1662 * cpu-binding of @worker are kept coordinated with the pool across
1665 static void worker_attach_to_pool(struct worker *worker,
1666 struct worker_pool *pool)
1668 mutex_lock(&pool->attach_mutex);
1671 * set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
1672 * online CPUs. It'll be re-applied when any of the CPUs come up.
1674 set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
1677 * The pool->attach_mutex ensures %POOL_DISASSOCIATED remains
1678 * stable across this function. See the comments above the
1679 * flag definition for details.
1681 if (pool->flags & POOL_DISASSOCIATED)
1682 worker->flags |= WORKER_UNBOUND;
1684 list_add_tail(&worker->node, &pool->workers);
1686 mutex_unlock(&pool->attach_mutex);
1690 * worker_detach_from_pool() - detach a worker from its pool
1691 * @worker: worker which is attached to its pool
1692 * @pool: the pool @worker is attached to
1694 * Undo the attaching which had been done in worker_attach_to_pool(). The
1695 * caller worker shouldn't access to the pool after detached except it has
1696 * other reference to the pool.
1698 static void worker_detach_from_pool(struct worker *worker,
1699 struct worker_pool *pool)
1701 struct completion *detach_completion = NULL;
1703 mutex_lock(&pool->attach_mutex);
1704 list_del(&worker->node);
1705 if (list_empty(&pool->workers))
1706 detach_completion = pool->detach_completion;
1707 mutex_unlock(&pool->attach_mutex);
1709 /* clear leftover flags without pool->lock after it is detached */
1710 worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
1712 if (detach_completion)
1713 complete(detach_completion);
1717 * create_worker - create a new workqueue worker
1718 * @pool: pool the new worker will belong to
1720 * Create and start a new worker which is attached to @pool.
1723 * Might sleep. Does GFP_KERNEL allocations.
1726 * Pointer to the newly created worker.
1728 static struct worker *create_worker(struct worker_pool *pool)
1730 struct worker *worker = NULL;
1734 /* ID is needed to determine kthread name */
1735 id = ida_simple_get(&pool->worker_ida, 0, 0, GFP_KERNEL);
1739 worker = alloc_worker(pool->node);
1743 worker->pool = pool;
1747 snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
1748 pool->attrs->nice < 0 ? "H" : "");
1750 snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
1752 worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
1753 "kworker/%s", id_buf);
1754 if (IS_ERR(worker->task))
1757 set_user_nice(worker->task, pool->attrs->nice);
1758 kthread_bind_mask(worker->task, pool->attrs->cpumask);
1760 /* successful, attach the worker to the pool */
1761 worker_attach_to_pool(worker, pool);
1763 /* start the newly created worker */
1764 spin_lock_irq(&pool->lock);
1765 worker->pool->nr_workers++;
1766 worker_enter_idle(worker);
1767 wake_up_process(worker->task);
1768 spin_unlock_irq(&pool->lock);
1774 ida_simple_remove(&pool->worker_ida, id);
1780 * destroy_worker - destroy a workqueue worker
1781 * @worker: worker to be destroyed
1783 * Destroy @worker and adjust @pool stats accordingly. The worker should
1787 * spin_lock_irq(pool->lock).
1789 static void destroy_worker(struct worker *worker)
1791 struct worker_pool *pool = worker->pool;
1793 lockdep_assert_held(&pool->lock);
1795 /* sanity check frenzy */
1796 if (WARN_ON(worker->current_work) ||
1797 WARN_ON(!list_empty(&worker->scheduled)) ||
1798 WARN_ON(!(worker->flags & WORKER_IDLE)))
1804 list_del_init(&worker->entry);
1805 worker->flags |= WORKER_DIE;
1806 wake_up_process(worker->task);
1809 static void idle_worker_timeout(unsigned long __pool)
1811 struct worker_pool *pool = (void *)__pool;
1813 spin_lock_irq(&pool->lock);
1815 while (too_many_workers(pool)) {
1816 struct worker *worker;
1817 unsigned long expires;
1819 /* idle_list is kept in LIFO order, check the last one */
1820 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1821 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1823 if (time_before(jiffies, expires)) {
1824 mod_timer(&pool->idle_timer, expires);
1828 destroy_worker(worker);
1831 spin_unlock_irq(&pool->lock);
1834 static void send_mayday(struct work_struct *work)
1836 struct pool_workqueue *pwq = get_work_pwq(work);
1837 struct workqueue_struct *wq = pwq->wq;
1839 lockdep_assert_held(&wq_mayday_lock);
1844 /* mayday mayday mayday */
1845 if (list_empty(&pwq->mayday_node)) {
1847 * If @pwq is for an unbound wq, its base ref may be put at
1848 * any time due to an attribute change. Pin @pwq until the
1849 * rescuer is done with it.
1852 list_add_tail(&pwq->mayday_node, &wq->maydays);
1853 wake_up_process(wq->rescuer->task);
1857 static void pool_mayday_timeout(unsigned long __pool)
1859 struct worker_pool *pool = (void *)__pool;
1860 struct work_struct *work;
1862 spin_lock_irq(&pool->lock);
1863 spin_lock(&wq_mayday_lock); /* for wq->maydays */
1865 if (need_to_create_worker(pool)) {
1867 * We've been trying to create a new worker but
1868 * haven't been successful. We might be hitting an
1869 * allocation deadlock. Send distress signals to
1872 list_for_each_entry(work, &pool->worklist, entry)
1876 spin_unlock(&wq_mayday_lock);
1877 spin_unlock_irq(&pool->lock);
1879 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1883 * maybe_create_worker - create a new worker if necessary
1884 * @pool: pool to create a new worker for
1886 * Create a new worker for @pool if necessary. @pool is guaranteed to
1887 * have at least one idle worker on return from this function. If
1888 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1889 * sent to all rescuers with works scheduled on @pool to resolve
1890 * possible allocation deadlock.
1892 * On return, need_to_create_worker() is guaranteed to be %false and
1893 * may_start_working() %true.
1896 * spin_lock_irq(pool->lock) which may be released and regrabbed
1897 * multiple times. Does GFP_KERNEL allocations. Called only from
1900 static void maybe_create_worker(struct worker_pool *pool)
1901 __releases(&pool->lock)
1902 __acquires(&pool->lock)
1905 spin_unlock_irq(&pool->lock);
1907 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1908 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1911 if (create_worker(pool) || !need_to_create_worker(pool))
1914 schedule_timeout_interruptible(CREATE_COOLDOWN);
1916 if (!need_to_create_worker(pool))
1920 del_timer_sync(&pool->mayday_timer);
1921 spin_lock_irq(&pool->lock);
1923 * This is necessary even after a new worker was just successfully
1924 * created as @pool->lock was dropped and the new worker might have
1925 * already become busy.
1927 if (need_to_create_worker(pool))
1932 * manage_workers - manage worker pool
1935 * Assume the manager role and manage the worker pool @worker belongs
1936 * to. At any given time, there can be only zero or one manager per
1937 * pool. The exclusion is handled automatically by this function.
1939 * The caller can safely start processing works on false return. On
1940 * true return, it's guaranteed that need_to_create_worker() is false
1941 * and may_start_working() is true.
1944 * spin_lock_irq(pool->lock) which may be released and regrabbed
1945 * multiple times. Does GFP_KERNEL allocations.
1948 * %false if the pool doesn't need management and the caller can safely
1949 * start processing works, %true if management function was performed and
1950 * the conditions that the caller verified before calling the function may
1951 * no longer be true.
1953 static bool manage_workers(struct worker *worker)
1955 struct worker_pool *pool = worker->pool;
1957 if (pool->flags & POOL_MANAGER_ACTIVE)
1960 pool->flags |= POOL_MANAGER_ACTIVE;
1961 pool->manager = worker;
1963 maybe_create_worker(pool);
1965 pool->manager = NULL;
1966 pool->flags &= ~POOL_MANAGER_ACTIVE;
1967 wake_up(&wq_manager_wait);
1972 * process_one_work - process single work
1974 * @work: work to process
1976 * Process @work. This function contains all the logics necessary to
1977 * process a single work including synchronization against and
1978 * interaction with other workers on the same cpu, queueing and
1979 * flushing. As long as context requirement is met, any worker can
1980 * call this function to process a work.
1983 * spin_lock_irq(pool->lock) which is released and regrabbed.
1985 static void process_one_work(struct worker *worker, struct work_struct *work)
1986 __releases(&pool->lock)
1987 __acquires(&pool->lock)
1989 struct pool_workqueue *pwq = get_work_pwq(work);
1990 struct worker_pool *pool = worker->pool;
1991 bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
1993 struct worker *collision;
1994 #ifdef CONFIG_LOCKDEP
1996 * It is permissible to free the struct work_struct from
1997 * inside the function that is called from it, this we need to
1998 * take into account for lockdep too. To avoid bogus "held
1999 * lock freed" warnings as well as problems when looking into
2000 * work->lockdep_map, make a copy and use that here.
2002 struct lockdep_map lockdep_map;
2004 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
2006 /* ensure we're on the correct CPU */
2007 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2008 raw_smp_processor_id() != pool->cpu);
2011 * A single work shouldn't be executed concurrently by
2012 * multiple workers on a single cpu. Check whether anyone is
2013 * already processing the work. If so, defer the work to the
2014 * currently executing one.
2016 collision = find_worker_executing_work(pool, work);
2017 if (unlikely(collision)) {
2018 move_linked_works(work, &collision->scheduled, NULL);
2022 /* claim and dequeue */
2023 debug_work_deactivate(work);
2024 hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2025 worker->current_work = work;
2026 worker->current_func = work->func;
2027 worker->current_pwq = pwq;
2028 work_color = get_work_color(work);
2030 list_del_init(&work->entry);
2033 * CPU intensive works don't participate in concurrency management.
2034 * They're the scheduler's responsibility. This takes @worker out
2035 * of concurrency management and the next code block will chain
2036 * execution of the pending work items.
2038 if (unlikely(cpu_intensive))
2039 worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2042 * Wake up another worker if necessary. The condition is always
2043 * false for normal per-cpu workers since nr_running would always
2044 * be >= 1 at this point. This is used to chain execution of the
2045 * pending work items for WORKER_NOT_RUNNING workers such as the
2046 * UNBOUND and CPU_INTENSIVE ones.
2048 if (need_more_worker(pool))
2049 wake_up_worker(pool);
2052 * Record the last pool and clear PENDING which should be the last
2053 * update to @work. Also, do this inside @pool->lock so that
2054 * PENDING and queued state changes happen together while IRQ is
2057 set_work_pool_and_clear_pending(work, pool->id);
2059 spin_unlock_irq(&pool->lock);
2061 lock_map_acquire_read(&pwq->wq->lockdep_map);
2062 lock_map_acquire(&lockdep_map);
2063 trace_workqueue_execute_start(work);
2064 worker->current_func(work);
2066 * While we must be careful to not use "work" after this, the trace
2067 * point will only record its address.
2069 trace_workqueue_execute_end(work);
2070 lock_map_release(&lockdep_map);
2071 lock_map_release(&pwq->wq->lockdep_map);
2073 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2074 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2075 " last function: %pf\n",
2076 current->comm, preempt_count(), task_pid_nr(current),
2077 worker->current_func);
2078 debug_show_held_locks(current);
2083 * The following prevents a kworker from hogging CPU on !PREEMPT
2084 * kernels, where a requeueing work item waiting for something to
2085 * happen could deadlock with stop_machine as such work item could
2086 * indefinitely requeue itself while all other CPUs are trapped in
2087 * stop_machine. At the same time, report a quiescent RCU state so
2088 * the same condition doesn't freeze RCU.
2090 cond_resched_rcu_qs();
2092 spin_lock_irq(&pool->lock);
2094 /* clear cpu intensive status */
2095 if (unlikely(cpu_intensive))
2096 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2098 /* we're done with it, release */
2099 hash_del(&worker->hentry);
2100 worker->current_work = NULL;
2101 worker->current_func = NULL;
2102 worker->current_pwq = NULL;
2103 worker->desc_valid = false;
2104 pwq_dec_nr_in_flight(pwq, work_color);
2108 * process_scheduled_works - process scheduled works
2111 * Process all scheduled works. Please note that the scheduled list
2112 * may change while processing a work, so this function repeatedly
2113 * fetches a work from the top and executes it.
2116 * spin_lock_irq(pool->lock) which may be released and regrabbed
2119 static void process_scheduled_works(struct worker *worker)
2121 while (!list_empty(&worker->scheduled)) {
2122 struct work_struct *work = list_first_entry(&worker->scheduled,
2123 struct work_struct, entry);
2124 process_one_work(worker, work);
2129 * worker_thread - the worker thread function
2132 * The worker thread function. All workers belong to a worker_pool -
2133 * either a per-cpu one or dynamic unbound one. These workers process all
2134 * work items regardless of their specific target workqueue. The only
2135 * exception is work items which belong to workqueues with a rescuer which
2136 * will be explained in rescuer_thread().
2140 static int worker_thread(void *__worker)
2142 struct worker *worker = __worker;
2143 struct worker_pool *pool = worker->pool;
2145 /* tell the scheduler that this is a workqueue worker */
2146 worker->task->flags |= PF_WQ_WORKER;
2148 spin_lock_irq(&pool->lock);
2150 /* am I supposed to die? */
2151 if (unlikely(worker->flags & WORKER_DIE)) {
2152 spin_unlock_irq(&pool->lock);
2153 WARN_ON_ONCE(!list_empty(&worker->entry));
2154 worker->task->flags &= ~PF_WQ_WORKER;
2156 set_task_comm(worker->task, "kworker/dying");
2157 ida_simple_remove(&pool->worker_ida, worker->id);
2158 worker_detach_from_pool(worker, pool);
2163 worker_leave_idle(worker);
2165 /* no more worker necessary? */
2166 if (!need_more_worker(pool))
2169 /* do we need to manage? */
2170 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2174 * ->scheduled list can only be filled while a worker is
2175 * preparing to process a work or actually processing it.
2176 * Make sure nobody diddled with it while I was sleeping.
2178 WARN_ON_ONCE(!list_empty(&worker->scheduled));
2181 * Finish PREP stage. We're guaranteed to have at least one idle
2182 * worker or that someone else has already assumed the manager
2183 * role. This is where @worker starts participating in concurrency
2184 * management if applicable and concurrency management is restored
2185 * after being rebound. See rebind_workers() for details.
2187 worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2190 struct work_struct *work =
2191 list_first_entry(&pool->worklist,
2192 struct work_struct, entry);
2194 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2195 /* optimization path, not strictly necessary */
2196 process_one_work(worker, work);
2197 if (unlikely(!list_empty(&worker->scheduled)))
2198 process_scheduled_works(worker);
2200 move_linked_works(work, &worker->scheduled, NULL);
2201 process_scheduled_works(worker);
2203 } while (keep_working(pool));
2205 worker_set_flags(worker, WORKER_PREP);
2208 * pool->lock is held and there's no work to process and no need to
2209 * manage, sleep. Workers are woken up only while holding
2210 * pool->lock or from local cpu, so setting the current state
2211 * before releasing pool->lock is enough to prevent losing any
2214 worker_enter_idle(worker);
2215 __set_current_state(TASK_INTERRUPTIBLE);
2216 spin_unlock_irq(&pool->lock);
2222 * rescuer_thread - the rescuer thread function
2225 * Workqueue rescuer thread function. There's one rescuer for each
2226 * workqueue which has WQ_MEM_RECLAIM set.
2228 * Regular work processing on a pool may block trying to create a new
2229 * worker which uses GFP_KERNEL allocation which has slight chance of
2230 * developing into deadlock if some works currently on the same queue
2231 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2232 * the problem rescuer solves.
2234 * When such condition is possible, the pool summons rescuers of all
2235 * workqueues which have works queued on the pool and let them process
2236 * those works so that forward progress can be guaranteed.
2238 * This should happen rarely.
2242 static int rescuer_thread(void *__rescuer)
2244 struct worker *rescuer = __rescuer;
2245 struct workqueue_struct *wq = rescuer->rescue_wq;
2246 struct list_head *scheduled = &rescuer->scheduled;
2249 set_user_nice(current, RESCUER_NICE_LEVEL);
2252 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2253 * doesn't participate in concurrency management.
2255 rescuer->task->flags |= PF_WQ_WORKER;
2257 set_current_state(TASK_INTERRUPTIBLE);
2260 * By the time the rescuer is requested to stop, the workqueue
2261 * shouldn't have any work pending, but @wq->maydays may still have
2262 * pwq(s) queued. This can happen by non-rescuer workers consuming
2263 * all the work items before the rescuer got to them. Go through
2264 * @wq->maydays processing before acting on should_stop so that the
2265 * list is always empty on exit.
2267 should_stop = kthread_should_stop();
2269 /* see whether any pwq is asking for help */
2270 spin_lock_irq(&wq_mayday_lock);
2272 while (!list_empty(&wq->maydays)) {
2273 struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2274 struct pool_workqueue, mayday_node);
2275 struct worker_pool *pool = pwq->pool;
2276 struct work_struct *work, *n;
2278 __set_current_state(TASK_RUNNING);
2279 list_del_init(&pwq->mayday_node);
2281 spin_unlock_irq(&wq_mayday_lock);
2283 worker_attach_to_pool(rescuer, pool);
2285 spin_lock_irq(&pool->lock);
2286 rescuer->pool = pool;
2289 * Slurp in all works issued via this workqueue and
2292 WARN_ON_ONCE(!list_empty(scheduled));
2293 list_for_each_entry_safe(work, n, &pool->worklist, entry)
2294 if (get_work_pwq(work) == pwq)
2295 move_linked_works(work, scheduled, &n);
2297 if (!list_empty(scheduled)) {
2298 process_scheduled_works(rescuer);
2301 * The above execution of rescued work items could
2302 * have created more to rescue through
2303 * pwq_activate_first_delayed() or chained
2304 * queueing. Let's put @pwq back on mayday list so
2305 * that such back-to-back work items, which may be
2306 * being used to relieve memory pressure, don't
2307 * incur MAYDAY_INTERVAL delay inbetween.
2309 if (need_to_create_worker(pool)) {
2310 spin_lock(&wq_mayday_lock);
2312 * Queue iff we aren't racing destruction
2313 * and somebody else hasn't queued it already.
2315 if (wq->rescuer && list_empty(&pwq->mayday_node)) {
2317 list_add_tail(&pwq->mayday_node, &wq->maydays);
2319 spin_unlock(&wq_mayday_lock);
2324 * Put the reference grabbed by send_mayday(). @pool won't
2325 * go away while we're still attached to it.
2330 * Leave this pool. If need_more_worker() is %true, notify a
2331 * regular worker; otherwise, we end up with 0 concurrency
2332 * and stalling the execution.
2334 if (need_more_worker(pool))
2335 wake_up_worker(pool);
2337 rescuer->pool = NULL;
2338 spin_unlock_irq(&pool->lock);
2340 worker_detach_from_pool(rescuer, pool);
2342 spin_lock_irq(&wq_mayday_lock);
2345 spin_unlock_irq(&wq_mayday_lock);
2348 __set_current_state(TASK_RUNNING);
2349 rescuer->task->flags &= ~PF_WQ_WORKER;
2353 /* rescuers should never participate in concurrency management */
2354 WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2360 struct work_struct work;
2361 struct completion done;
2362 struct task_struct *task; /* purely informational */
2365 static void wq_barrier_func(struct work_struct *work)
2367 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2368 complete(&barr->done);
2372 * insert_wq_barrier - insert a barrier work
2373 * @pwq: pwq to insert barrier into
2374 * @barr: wq_barrier to insert
2375 * @target: target work to attach @barr to
2376 * @worker: worker currently executing @target, NULL if @target is not executing
2378 * @barr is linked to @target such that @barr is completed only after
2379 * @target finishes execution. Please note that the ordering
2380 * guarantee is observed only with respect to @target and on the local
2383 * Currently, a queued barrier can't be canceled. This is because
2384 * try_to_grab_pending() can't determine whether the work to be
2385 * grabbed is at the head of the queue and thus can't clear LINKED
2386 * flag of the previous work while there must be a valid next work
2387 * after a work with LINKED flag set.
2389 * Note that when @worker is non-NULL, @target may be modified
2390 * underneath us, so we can't reliably determine pwq from @target.
2393 * spin_lock_irq(pool->lock).
2395 static void insert_wq_barrier(struct pool_workqueue *pwq,
2396 struct wq_barrier *barr,
2397 struct work_struct *target, struct worker *worker)
2399 struct list_head *head;
2400 unsigned int linked = 0;
2403 * debugobject calls are safe here even with pool->lock locked
2404 * as we know for sure that this will not trigger any of the
2405 * checks and call back into the fixup functions where we
2408 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2409 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2410 init_completion(&barr->done);
2411 barr->task = current;
2414 * If @target is currently being executed, schedule the
2415 * barrier to the worker; otherwise, put it after @target.
2418 head = worker->scheduled.next;
2420 unsigned long *bits = work_data_bits(target);
2422 head = target->entry.next;
2423 /* there can already be other linked works, inherit and set */
2424 linked = *bits & WORK_STRUCT_LINKED;
2425 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2428 debug_work_activate(&barr->work);
2429 insert_work(pwq, &barr->work, head,
2430 work_color_to_flags(WORK_NO_COLOR) | linked);
2434 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
2435 * @wq: workqueue being flushed
2436 * @flush_color: new flush color, < 0 for no-op
2437 * @work_color: new work color, < 0 for no-op
2439 * Prepare pwqs for workqueue flushing.
2441 * If @flush_color is non-negative, flush_color on all pwqs should be
2442 * -1. If no pwq has in-flight commands at the specified color, all
2443 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
2444 * has in flight commands, its pwq->flush_color is set to
2445 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
2446 * wakeup logic is armed and %true is returned.
2448 * The caller should have initialized @wq->first_flusher prior to
2449 * calling this function with non-negative @flush_color. If
2450 * @flush_color is negative, no flush color update is done and %false
2453 * If @work_color is non-negative, all pwqs should have the same
2454 * work_color which is previous to @work_color and all will be
2455 * advanced to @work_color.
2458 * mutex_lock(wq->mutex).
2461 * %true if @flush_color >= 0 and there's something to flush. %false
2464 static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
2465 int flush_color, int work_color)
2468 struct pool_workqueue *pwq;
2470 if (flush_color >= 0) {
2471 WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2472 atomic_set(&wq->nr_pwqs_to_flush, 1);
2475 for_each_pwq(pwq, wq) {
2476 struct worker_pool *pool = pwq->pool;
2478 spin_lock_irq(&pool->lock);
2480 if (flush_color >= 0) {
2481 WARN_ON_ONCE(pwq->flush_color != -1);
2483 if (pwq->nr_in_flight[flush_color]) {
2484 pwq->flush_color = flush_color;
2485 atomic_inc(&wq->nr_pwqs_to_flush);
2490 if (work_color >= 0) {
2491 WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2492 pwq->work_color = work_color;
2495 spin_unlock_irq(&pool->lock);
2498 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
2499 complete(&wq->first_flusher->done);
2505 * flush_workqueue - ensure that any scheduled work has run to completion.
2506 * @wq: workqueue to flush
2508 * This function sleeps until all work items which were queued on entry
2509 * have finished execution, but it is not livelocked by new incoming ones.
2511 void flush_workqueue(struct workqueue_struct *wq)
2513 struct wq_flusher this_flusher = {
2514 .list = LIST_HEAD_INIT(this_flusher.list),
2516 .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
2520 lock_map_acquire(&wq->lockdep_map);
2521 lock_map_release(&wq->lockdep_map);
2523 mutex_lock(&wq->mutex);
2526 * Start-to-wait phase
2528 next_color = work_next_color(wq->work_color);
2530 if (next_color != wq->flush_color) {
2532 * Color space is not full. The current work_color
2533 * becomes our flush_color and work_color is advanced
2536 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
2537 this_flusher.flush_color = wq->work_color;
2538 wq->work_color = next_color;
2540 if (!wq->first_flusher) {
2541 /* no flush in progress, become the first flusher */
2542 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2544 wq->first_flusher = &this_flusher;
2546 if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
2548 /* nothing to flush, done */
2549 wq->flush_color = next_color;
2550 wq->first_flusher = NULL;
2555 WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
2556 list_add_tail(&this_flusher.list, &wq->flusher_queue);
2557 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2561 * Oops, color space is full, wait on overflow queue.
2562 * The next flush completion will assign us
2563 * flush_color and transfer to flusher_queue.
2565 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2568 mutex_unlock(&wq->mutex);
2570 wait_for_completion(&this_flusher.done);
2573 * Wake-up-and-cascade phase
2575 * First flushers are responsible for cascading flushes and
2576 * handling overflow. Non-first flushers can simply return.
2578 if (wq->first_flusher != &this_flusher)
2581 mutex_lock(&wq->mutex);
2583 /* we might have raced, check again with mutex held */
2584 if (wq->first_flusher != &this_flusher)
2587 wq->first_flusher = NULL;
2589 WARN_ON_ONCE(!list_empty(&this_flusher.list));
2590 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2593 struct wq_flusher *next, *tmp;
2595 /* complete all the flushers sharing the current flush color */
2596 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2597 if (next->flush_color != wq->flush_color)
2599 list_del_init(&next->list);
2600 complete(&next->done);
2603 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
2604 wq->flush_color != work_next_color(wq->work_color));
2606 /* this flush_color is finished, advance by one */
2607 wq->flush_color = work_next_color(wq->flush_color);
2609 /* one color has been freed, handle overflow queue */
2610 if (!list_empty(&wq->flusher_overflow)) {
2612 * Assign the same color to all overflowed
2613 * flushers, advance work_color and append to
2614 * flusher_queue. This is the start-to-wait
2615 * phase for these overflowed flushers.
2617 list_for_each_entry(tmp, &wq->flusher_overflow, list)
2618 tmp->flush_color = wq->work_color;
2620 wq->work_color = work_next_color(wq->work_color);
2622 list_splice_tail_init(&wq->flusher_overflow,
2623 &wq->flusher_queue);
2624 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2627 if (list_empty(&wq->flusher_queue)) {
2628 WARN_ON_ONCE(wq->flush_color != wq->work_color);
2633 * Need to flush more colors. Make the next flusher
2634 * the new first flusher and arm pwqs.
2636 WARN_ON_ONCE(wq->flush_color == wq->work_color);
2637 WARN_ON_ONCE(wq->flush_color != next->flush_color);
2639 list_del_init(&next->list);
2640 wq->first_flusher = next;
2642 if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
2646 * Meh... this color is already done, clear first
2647 * flusher and repeat cascading.
2649 wq->first_flusher = NULL;
2653 mutex_unlock(&wq->mutex);
2655 EXPORT_SYMBOL(flush_workqueue);
2658 * drain_workqueue - drain a workqueue
2659 * @wq: workqueue to drain
2661 * Wait until the workqueue becomes empty. While draining is in progress,
2662 * only chain queueing is allowed. IOW, only currently pending or running
2663 * work items on @wq can queue further work items on it. @wq is flushed
2664 * repeatedly until it becomes empty. The number of flushing is determined
2665 * by the depth of chaining and should be relatively short. Whine if it
2668 void drain_workqueue(struct workqueue_struct *wq)
2670 unsigned int flush_cnt = 0;
2671 struct pool_workqueue *pwq;
2674 * __queue_work() needs to test whether there are drainers, is much
2675 * hotter than drain_workqueue() and already looks at @wq->flags.
2676 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
2678 mutex_lock(&wq->mutex);
2679 if (!wq->nr_drainers++)
2680 wq->flags |= __WQ_DRAINING;
2681 mutex_unlock(&wq->mutex);
2683 flush_workqueue(wq);
2685 mutex_lock(&wq->mutex);
2687 for_each_pwq(pwq, wq) {
2690 spin_lock_irq(&pwq->pool->lock);
2691 drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
2692 spin_unlock_irq(&pwq->pool->lock);
2697 if (++flush_cnt == 10 ||
2698 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2699 pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
2700 wq->name, flush_cnt);
2702 mutex_unlock(&wq->mutex);
2706 if (!--wq->nr_drainers)
2707 wq->flags &= ~__WQ_DRAINING;
2708 mutex_unlock(&wq->mutex);
2710 EXPORT_SYMBOL_GPL(drain_workqueue);
2712 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2714 struct worker *worker = NULL;
2715 struct worker_pool *pool;
2716 struct pool_workqueue *pwq;
2720 local_irq_disable();
2721 pool = get_work_pool(work);
2727 spin_lock(&pool->lock);
2728 /* see the comment in try_to_grab_pending() with the same code */
2729 pwq = get_work_pwq(work);
2731 if (unlikely(pwq->pool != pool))
2734 worker = find_worker_executing_work(pool, work);
2737 pwq = worker->current_pwq;
2740 insert_wq_barrier(pwq, barr, work, worker);
2741 spin_unlock_irq(&pool->lock);
2744 * If @max_active is 1 or rescuer is in use, flushing another work
2745 * item on the same workqueue may lead to deadlock. Make sure the
2746 * flusher is not running on the same workqueue by verifying write
2749 if (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)
2750 lock_map_acquire(&pwq->wq->lockdep_map);
2752 lock_map_acquire_read(&pwq->wq->lockdep_map);
2753 lock_map_release(&pwq->wq->lockdep_map);
2757 spin_unlock_irq(&pool->lock);
2762 * flush_work - wait for a work to finish executing the last queueing instance
2763 * @work: the work to flush
2765 * Wait until @work has finished execution. @work is guaranteed to be idle
2766 * on return if it hasn't been requeued since flush started.
2769 * %true if flush_work() waited for the work to finish execution,
2770 * %false if it was already idle.
2772 bool flush_work(struct work_struct *work)
2774 struct wq_barrier barr;
2776 lock_map_acquire(&work->lockdep_map);
2777 lock_map_release(&work->lockdep_map);
2779 if (start_flush_work(work, &barr)) {
2780 wait_for_completion(&barr.done);
2781 destroy_work_on_stack(&barr.work);
2787 EXPORT_SYMBOL_GPL(flush_work);
2791 struct work_struct *work;
2794 static int cwt_wakefn(wait_queue_t *wait, unsigned mode, int sync, void *key)
2796 struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
2798 if (cwait->work != key)
2800 return autoremove_wake_function(wait, mode, sync, key);
2803 static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2805 static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
2806 unsigned long flags;
2810 ret = try_to_grab_pending(work, is_dwork, &flags);
2812 * If someone else is already canceling, wait for it to
2813 * finish. flush_work() doesn't work for PREEMPT_NONE
2814 * because we may get scheduled between @work's completion
2815 * and the other canceling task resuming and clearing
2816 * CANCELING - flush_work() will return false immediately
2817 * as @work is no longer busy, try_to_grab_pending() will
2818 * return -ENOENT as @work is still being canceled and the
2819 * other canceling task won't be able to clear CANCELING as
2820 * we're hogging the CPU.
2822 * Let's wait for completion using a waitqueue. As this
2823 * may lead to the thundering herd problem, use a custom
2824 * wake function which matches @work along with exclusive
2827 if (unlikely(ret == -ENOENT)) {
2828 struct cwt_wait cwait;
2830 init_wait(&cwait.wait);
2831 cwait.wait.func = cwt_wakefn;
2834 prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
2835 TASK_UNINTERRUPTIBLE);
2836 if (work_is_canceling(work))
2838 finish_wait(&cancel_waitq, &cwait.wait);
2840 } while (unlikely(ret < 0));
2842 /* tell other tasks trying to grab @work to back off */
2843 mark_work_canceling(work);
2844 local_irq_restore(flags);
2847 clear_work_data(work);
2850 * Paired with prepare_to_wait() above so that either
2851 * waitqueue_active() is visible here or !work_is_canceling() is
2855 if (waitqueue_active(&cancel_waitq))
2856 __wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
2862 * cancel_work_sync - cancel a work and wait for it to finish
2863 * @work: the work to cancel
2865 * Cancel @work and wait for its execution to finish. This function
2866 * can be used even if the work re-queues itself or migrates to
2867 * another workqueue. On return from this function, @work is
2868 * guaranteed to be not pending or executing on any CPU.
2870 * cancel_work_sync(&delayed_work->work) must not be used for
2871 * delayed_work's. Use cancel_delayed_work_sync() instead.
2873 * The caller must ensure that the workqueue on which @work was last
2874 * queued can't be destroyed before this function returns.
2877 * %true if @work was pending, %false otherwise.
2879 bool cancel_work_sync(struct work_struct *work)
2881 return __cancel_work_timer(work, false);
2883 EXPORT_SYMBOL_GPL(cancel_work_sync);
2886 * flush_delayed_work - wait for a dwork to finish executing the last queueing
2887 * @dwork: the delayed work to flush
2889 * Delayed timer is cancelled and the pending work is queued for
2890 * immediate execution. Like flush_work(), this function only
2891 * considers the last queueing instance of @dwork.
2894 * %true if flush_work() waited for the work to finish execution,
2895 * %false if it was already idle.
2897 bool flush_delayed_work(struct delayed_work *dwork)
2899 local_irq_disable();
2900 if (del_timer_sync(&dwork->timer))
2901 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
2903 return flush_work(&dwork->work);
2905 EXPORT_SYMBOL(flush_delayed_work);
2908 * cancel_delayed_work - cancel a delayed work
2909 * @dwork: delayed_work to cancel
2911 * Kill off a pending delayed_work.
2913 * Return: %true if @dwork was pending and canceled; %false if it wasn't
2917 * The work callback function may still be running on return, unless
2918 * it returns %true and the work doesn't re-arm itself. Explicitly flush or
2919 * use cancel_delayed_work_sync() to wait on it.
2921 * This function is safe to call from any context including IRQ handler.
2923 bool cancel_delayed_work(struct delayed_work *dwork)
2925 unsigned long flags;
2929 ret = try_to_grab_pending(&dwork->work, true, &flags);
2930 } while (unlikely(ret == -EAGAIN));
2932 if (unlikely(ret < 0))
2935 set_work_pool_and_clear_pending(&dwork->work,
2936 get_work_pool_id(&dwork->work));
2937 local_irq_restore(flags);
2940 EXPORT_SYMBOL(cancel_delayed_work);
2943 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2944 * @dwork: the delayed work cancel
2946 * This is cancel_work_sync() for delayed works.
2949 * %true if @dwork was pending, %false otherwise.
2951 bool cancel_delayed_work_sync(struct delayed_work *dwork)
2953 return __cancel_work_timer(&dwork->work, true);
2955 EXPORT_SYMBOL(cancel_delayed_work_sync);
2958 * schedule_on_each_cpu - execute a function synchronously on each online CPU
2959 * @func: the function to call
2961 * schedule_on_each_cpu() executes @func on each online CPU using the
2962 * system workqueue and blocks until all CPUs have completed.
2963 * schedule_on_each_cpu() is very slow.
2966 * 0 on success, -errno on failure.
2968 int schedule_on_each_cpu(work_func_t func)
2971 struct work_struct __percpu *works;
2973 works = alloc_percpu(struct work_struct);
2979 for_each_online_cpu(cpu) {
2980 struct work_struct *work = per_cpu_ptr(works, cpu);
2982 INIT_WORK(work, func);
2983 schedule_work_on(cpu, work);
2986 for_each_online_cpu(cpu)
2987 flush_work(per_cpu_ptr(works, cpu));
2995 * execute_in_process_context - reliably execute the routine with user context
2996 * @fn: the function to execute
2997 * @ew: guaranteed storage for the execute work structure (must
2998 * be available when the work executes)
3000 * Executes the function immediately if process context is available,
3001 * otherwise schedules the function for delayed execution.
3003 * Return: 0 - function was executed
3004 * 1 - function was scheduled for execution
3006 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
3008 if (!in_interrupt()) {
3013 INIT_WORK(&ew->work, fn);
3014 schedule_work(&ew->work);
3018 EXPORT_SYMBOL_GPL(execute_in_process_context);
3021 * free_workqueue_attrs - free a workqueue_attrs
3022 * @attrs: workqueue_attrs to free
3024 * Undo alloc_workqueue_attrs().
3026 void free_workqueue_attrs(struct workqueue_attrs *attrs)
3029 free_cpumask_var(attrs->cpumask);
3035 * alloc_workqueue_attrs - allocate a workqueue_attrs
3036 * @gfp_mask: allocation mask to use
3038 * Allocate a new workqueue_attrs, initialize with default settings and
3041 * Return: The allocated new workqueue_attr on success. %NULL on failure.
3043 struct workqueue_attrs *alloc_workqueue_attrs(gfp_t gfp_mask)
3045 struct workqueue_attrs *attrs;
3047 attrs = kzalloc(sizeof(*attrs), gfp_mask);
3050 if (!alloc_cpumask_var(&attrs->cpumask, gfp_mask))
3053 cpumask_copy(attrs->cpumask, cpu_possible_mask);
3056 free_workqueue_attrs(attrs);
3060 static void copy_workqueue_attrs(struct workqueue_attrs *to,
3061 const struct workqueue_attrs *from)
3063 to->nice = from->nice;
3064 cpumask_copy(to->cpumask, from->cpumask);
3066 * Unlike hash and equality test, this function doesn't ignore
3067 * ->no_numa as it is used for both pool and wq attrs. Instead,
3068 * get_unbound_pool() explicitly clears ->no_numa after copying.
3070 to->no_numa = from->no_numa;
3073 /* hash value of the content of @attr */
3074 static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
3078 hash = jhash_1word(attrs->nice, hash);
3079 hash = jhash(cpumask_bits(attrs->cpumask),
3080 BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
3084 /* content equality test */
3085 static bool wqattrs_equal(const struct workqueue_attrs *a,
3086 const struct workqueue_attrs *b)
3088 if (a->nice != b->nice)
3090 if (!cpumask_equal(a->cpumask, b->cpumask))
3096 * init_worker_pool - initialize a newly zalloc'd worker_pool
3097 * @pool: worker_pool to initialize
3099 * Initialize a newly zalloc'd @pool. It also allocates @pool->attrs.
3101 * Return: 0 on success, -errno on failure. Even on failure, all fields
3102 * inside @pool proper are initialized and put_unbound_pool() can be called
3103 * on @pool safely to release it.
3105 static int init_worker_pool(struct worker_pool *pool)
3107 spin_lock_init(&pool->lock);
3110 pool->node = NUMA_NO_NODE;
3111 pool->flags |= POOL_DISASSOCIATED;
3112 INIT_LIST_HEAD(&pool->worklist);
3113 INIT_LIST_HEAD(&pool->idle_list);
3114 hash_init(pool->busy_hash);
3116 init_timer_deferrable(&pool->idle_timer);
3117 pool->idle_timer.function = idle_worker_timeout;
3118 pool->idle_timer.data = (unsigned long)pool;
3120 setup_timer(&pool->mayday_timer, pool_mayday_timeout,
3121 (unsigned long)pool);
3123 mutex_init(&pool->attach_mutex);
3124 INIT_LIST_HEAD(&pool->workers);
3126 ida_init(&pool->worker_ida);
3127 INIT_HLIST_NODE(&pool->hash_node);
3130 /* shouldn't fail above this point */
3131 pool->attrs = alloc_workqueue_attrs(GFP_KERNEL);
3137 static void rcu_free_wq(struct rcu_head *rcu)
3139 struct workqueue_struct *wq =
3140 container_of(rcu, struct workqueue_struct, rcu);
3142 if (!(wq->flags & WQ_UNBOUND))
3143 free_percpu(wq->cpu_pwqs);
3145 free_workqueue_attrs(wq->unbound_attrs);
3151 static void rcu_free_pool(struct rcu_head *rcu)
3153 struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
3155 ida_destroy(&pool->worker_ida);
3156 free_workqueue_attrs(pool->attrs);
3161 * put_unbound_pool - put a worker_pool
3162 * @pool: worker_pool to put
3164 * Put @pool. If its refcnt reaches zero, it gets destroyed in sched-RCU
3165 * safe manner. get_unbound_pool() calls this function on its failure path
3166 * and this function should be able to release pools which went through,
3167 * successfully or not, init_worker_pool().
3169 * Should be called with wq_pool_mutex held.
3171 static void put_unbound_pool(struct worker_pool *pool)
3173 DECLARE_COMPLETION_ONSTACK(detach_completion);
3174 struct worker *worker;
3176 lockdep_assert_held(&wq_pool_mutex);
3182 if (WARN_ON(!(pool->cpu < 0)) ||
3183 WARN_ON(!list_empty(&pool->worklist)))
3186 /* release id and unhash */
3188 idr_remove(&worker_pool_idr, pool->id);
3189 hash_del(&pool->hash_node);
3192 * Become the manager and destroy all workers. This prevents
3193 * @pool's workers from blocking on attach_mutex. We're the last
3194 * manager and @pool gets freed with the flag set.
3196 spin_lock_irq(&pool->lock);
3197 wait_event_lock_irq(wq_manager_wait,
3198 !(pool->flags & POOL_MANAGER_ACTIVE), pool->lock);
3199 pool->flags |= POOL_MANAGER_ACTIVE;
3201 while ((worker = first_idle_worker(pool)))
3202 destroy_worker(worker);
3203 WARN_ON(pool->nr_workers || pool->nr_idle);
3204 spin_unlock_irq(&pool->lock);
3206 mutex_lock(&pool->attach_mutex);
3207 if (!list_empty(&pool->workers))
3208 pool->detach_completion = &detach_completion;
3209 mutex_unlock(&pool->attach_mutex);
3211 if (pool->detach_completion)
3212 wait_for_completion(pool->detach_completion);
3214 /* shut down the timers */
3215 del_timer_sync(&pool->idle_timer);
3216 del_timer_sync(&pool->mayday_timer);
3218 /* sched-RCU protected to allow dereferences from get_work_pool() */
3219 call_rcu_sched(&pool->rcu, rcu_free_pool);
3223 * get_unbound_pool - get a worker_pool with the specified attributes
3224 * @attrs: the attributes of the worker_pool to get
3226 * Obtain a worker_pool which has the same attributes as @attrs, bump the
3227 * reference count and return it. If there already is a matching
3228 * worker_pool, it will be used; otherwise, this function attempts to
3231 * Should be called with wq_pool_mutex held.
3233 * Return: On success, a worker_pool with the same attributes as @attrs.
3234 * On failure, %NULL.
3236 static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
3238 u32 hash = wqattrs_hash(attrs);
3239 struct worker_pool *pool;
3241 int target_node = NUMA_NO_NODE;
3243 lockdep_assert_held(&wq_pool_mutex);
3245 /* do we already have a matching pool? */
3246 hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
3247 if (wqattrs_equal(pool->attrs, attrs)) {
3253 /* if cpumask is contained inside a NUMA node, we belong to that node */
3254 if (wq_numa_enabled) {
3255 for_each_node(node) {
3256 if (cpumask_subset(attrs->cpumask,
3257 wq_numa_possible_cpumask[node])) {
3264 /* nope, create a new one */
3265 pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, target_node);
3266 if (!pool || init_worker_pool(pool) < 0)
3269 lockdep_set_subclass(&pool->lock, 1); /* see put_pwq() */
3270 copy_workqueue_attrs(pool->attrs, attrs);
3271 pool->node = target_node;
3274 * no_numa isn't a worker_pool attribute, always clear it. See
3275 * 'struct workqueue_attrs' comments for detail.
3277 pool->attrs->no_numa = false;
3279 if (worker_pool_assign_id(pool) < 0)
3282 /* create and start the initial worker */
3283 if (!create_worker(pool))
3287 hash_add(unbound_pool_hash, &pool->hash_node, hash);
3292 put_unbound_pool(pool);
3296 static void rcu_free_pwq(struct rcu_head *rcu)
3298 kmem_cache_free(pwq_cache,
3299 container_of(rcu, struct pool_workqueue, rcu));
3303 * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
3304 * and needs to be destroyed.
3306 static void pwq_unbound_release_workfn(struct work_struct *work)
3308 struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
3309 unbound_release_work);
3310 struct workqueue_struct *wq = pwq->wq;
3311 struct worker_pool *pool = pwq->pool;
3312 bool is_last = false;
3315 * when @pwq is not linked, it doesn't hold any reference to the
3316 * @wq, and @wq is invalid to access.
3318 if (!list_empty(&pwq->pwqs_node)) {
3319 if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
3322 mutex_lock(&wq->mutex);
3323 list_del_rcu(&pwq->pwqs_node);
3324 is_last = list_empty(&wq->pwqs);
3325 mutex_unlock(&wq->mutex);
3328 mutex_lock(&wq_pool_mutex);
3329 put_unbound_pool(pool);
3330 mutex_unlock(&wq_pool_mutex);
3332 call_rcu_sched(&pwq->rcu, rcu_free_pwq);
3335 * If we're the last pwq going away, @wq is already dead and no one
3336 * is gonna access it anymore. Schedule RCU free.
3339 call_rcu_sched(&wq->rcu, rcu_free_wq);
3343 * pwq_adjust_max_active - update a pwq's max_active to the current setting
3344 * @pwq: target pool_workqueue
3346 * If @pwq isn't freezing, set @pwq->max_active to the associated
3347 * workqueue's saved_max_active and activate delayed work items
3348 * accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
3350 static void pwq_adjust_max_active(struct pool_workqueue *pwq)
3352 struct workqueue_struct *wq = pwq->wq;
3353 bool freezable = wq->flags & WQ_FREEZABLE;
3355 /* for @wq->saved_max_active */
3356 lockdep_assert_held(&wq->mutex);
3358 /* fast exit for non-freezable wqs */
3359 if (!freezable && pwq->max_active == wq->saved_max_active)
3362 spin_lock_irq(&pwq->pool->lock);
3365 * During [un]freezing, the caller is responsible for ensuring that
3366 * this function is called at least once after @workqueue_freezing
3367 * is updated and visible.
3369 if (!freezable || !workqueue_freezing) {
3372 pwq->max_active = wq->saved_max_active;
3374 while (!list_empty(&pwq->delayed_works) &&
3375 pwq->nr_active < pwq->max_active) {
3376 pwq_activate_first_delayed(pwq);
3381 * Need to kick a worker after thawed or an unbound wq's
3382 * max_active is bumped. In realtime scenarios, always kicking a
3383 * worker will cause interference on the isolated cpu cores, so
3384 * let's kick iff work items were activated.
3387 wake_up_worker(pwq->pool);
3389 pwq->max_active = 0;
3392 spin_unlock_irq(&pwq->pool->lock);
3395 /* initialize newly alloced @pwq which is associated with @wq and @pool */
3396 static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
3397 struct worker_pool *pool)
3399 BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3401 memset(pwq, 0, sizeof(*pwq));
3405 pwq->flush_color = -1;
3407 INIT_LIST_HEAD(&pwq->delayed_works);
3408 INIT_LIST_HEAD(&pwq->pwqs_node);
3409 INIT_LIST_HEAD(&pwq->mayday_node);
3410 INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
3413 /* sync @pwq with the current state of its associated wq and link it */
3414 static void link_pwq(struct pool_workqueue *pwq)
3416 struct workqueue_struct *wq = pwq->wq;
3418 lockdep_assert_held(&wq->mutex);
3420 /* may be called multiple times, ignore if already linked */
3421 if (!list_empty(&pwq->pwqs_node))
3424 /* set the matching work_color */
3425 pwq->work_color = wq->work_color;
3427 /* sync max_active to the current setting */
3428 pwq_adjust_max_active(pwq);
3431 list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
3434 /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
3435 static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
3436 const struct workqueue_attrs *attrs)
3438 struct worker_pool *pool;
3439 struct pool_workqueue *pwq;
3441 lockdep_assert_held(&wq_pool_mutex);
3443 pool = get_unbound_pool(attrs);
3447 pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
3449 put_unbound_pool(pool);
3453 init_pwq(pwq, wq, pool);
3458 * wq_calc_node_cpumask - calculate a wq_attrs' cpumask for the specified node
3459 * @attrs: the wq_attrs of the default pwq of the target workqueue
3460 * @node: the target NUMA node
3461 * @cpu_going_down: if >= 0, the CPU to consider as offline
3462 * @cpumask: outarg, the resulting cpumask
3464 * Calculate the cpumask a workqueue with @attrs should use on @node. If
3465 * @cpu_going_down is >= 0, that cpu is considered offline during
3466 * calculation. The result is stored in @cpumask.
3468 * If NUMA affinity is not enabled, @attrs->cpumask is always used. If
3469 * enabled and @node has online CPUs requested by @attrs, the returned
3470 * cpumask is the intersection of the possible CPUs of @node and
3473 * The caller is responsible for ensuring that the cpumask of @node stays
3476 * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
3479 static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
3480 int cpu_going_down, cpumask_t *cpumask)
3482 if (!wq_numa_enabled || attrs->no_numa)
3485 /* does @node have any online CPUs @attrs wants? */
3486 cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
3487 if (cpu_going_down >= 0)
3488 cpumask_clear_cpu(cpu_going_down, cpumask);
3490 if (cpumask_empty(cpumask))
3493 /* yeap, return possible CPUs in @node that @attrs wants */
3494 cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
3495 return !cpumask_equal(cpumask, attrs->cpumask);
3498 cpumask_copy(cpumask, attrs->cpumask);
3502 /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
3503 static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
3505 struct pool_workqueue *pwq)
3507 struct pool_workqueue *old_pwq;
3509 lockdep_assert_held(&wq_pool_mutex);
3510 lockdep_assert_held(&wq->mutex);
3512 /* link_pwq() can handle duplicate calls */
3515 old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
3516 rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
3520 /* context to store the prepared attrs & pwqs before applying */
3521 struct apply_wqattrs_ctx {
3522 struct workqueue_struct *wq; /* target workqueue */
3523 struct workqueue_attrs *attrs; /* attrs to apply */
3524 struct list_head list; /* queued for batching commit */
3525 struct pool_workqueue *dfl_pwq;
3526 struct pool_workqueue *pwq_tbl[];
3529 /* free the resources after success or abort */
3530 static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
3536 put_pwq_unlocked(ctx->pwq_tbl[node]);
3537 put_pwq_unlocked(ctx->dfl_pwq);
3539 free_workqueue_attrs(ctx->attrs);
3545 /* allocate the attrs and pwqs for later installation */
3546 static struct apply_wqattrs_ctx *
3547 apply_wqattrs_prepare(struct workqueue_struct *wq,
3548 const struct workqueue_attrs *attrs)
3550 struct apply_wqattrs_ctx *ctx;
3551 struct workqueue_attrs *new_attrs, *tmp_attrs;
3554 lockdep_assert_held(&wq_pool_mutex);
3556 ctx = kzalloc(sizeof(*ctx) + nr_node_ids * sizeof(ctx->pwq_tbl[0]),
3559 new_attrs = alloc_workqueue_attrs(GFP_KERNEL);
3560 tmp_attrs = alloc_workqueue_attrs(GFP_KERNEL);
3561 if (!ctx || !new_attrs || !tmp_attrs)
3565 * Calculate the attrs of the default pwq.
3566 * If the user configured cpumask doesn't overlap with the
3567 * wq_unbound_cpumask, we fallback to the wq_unbound_cpumask.
3569 copy_workqueue_attrs(new_attrs, attrs);
3570 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, wq_unbound_cpumask);
3571 if (unlikely(cpumask_empty(new_attrs->cpumask)))
3572 cpumask_copy(new_attrs->cpumask, wq_unbound_cpumask);
3575 * We may create multiple pwqs with differing cpumasks. Make a
3576 * copy of @new_attrs which will be modified and used to obtain
3579 copy_workqueue_attrs(tmp_attrs, new_attrs);
3582 * If something goes wrong during CPU up/down, we'll fall back to
3583 * the default pwq covering whole @attrs->cpumask. Always create
3584 * it even if we don't use it immediately.
3586 ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
3590 for_each_node(node) {
3591 if (wq_calc_node_cpumask(new_attrs, node, -1, tmp_attrs->cpumask)) {
3592 ctx->pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
3593 if (!ctx->pwq_tbl[node])
3596 ctx->dfl_pwq->refcnt++;
3597 ctx->pwq_tbl[node] = ctx->dfl_pwq;
3601 /* save the user configured attrs and sanitize it. */
3602 copy_workqueue_attrs(new_attrs, attrs);
3603 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
3604 ctx->attrs = new_attrs;
3607 free_workqueue_attrs(tmp_attrs);
3611 free_workqueue_attrs(tmp_attrs);
3612 free_workqueue_attrs(new_attrs);
3613 apply_wqattrs_cleanup(ctx);
3617 /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
3618 static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
3622 /* all pwqs have been created successfully, let's install'em */
3623 mutex_lock(&ctx->wq->mutex);
3625 copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
3627 /* save the previous pwq and install the new one */
3629 ctx->pwq_tbl[node] = numa_pwq_tbl_install(ctx->wq, node,
3630 ctx->pwq_tbl[node]);
3632 /* @dfl_pwq might not have been used, ensure it's linked */
3633 link_pwq(ctx->dfl_pwq);
3634 swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
3636 mutex_unlock(&ctx->wq->mutex);
3639 static void apply_wqattrs_lock(void)
3641 /* CPUs should stay stable across pwq creations and installations */
3643 mutex_lock(&wq_pool_mutex);
3646 static void apply_wqattrs_unlock(void)
3648 mutex_unlock(&wq_pool_mutex);
3652 static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
3653 const struct workqueue_attrs *attrs)
3655 struct apply_wqattrs_ctx *ctx;
3658 /* only unbound workqueues can change attributes */
3659 if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
3662 /* creating multiple pwqs breaks ordering guarantee */
3663 if (!list_empty(&wq->pwqs)) {
3664 if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
3667 wq->flags &= ~__WQ_ORDERED;
3670 ctx = apply_wqattrs_prepare(wq, attrs);
3672 /* the ctx has been prepared successfully, let's commit it */
3674 apply_wqattrs_commit(ctx);
3678 apply_wqattrs_cleanup(ctx);
3684 * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
3685 * @wq: the target workqueue
3686 * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
3688 * Apply @attrs to an unbound workqueue @wq. Unless disabled, on NUMA
3689 * machines, this function maps a separate pwq to each NUMA node with
3690 * possibles CPUs in @attrs->cpumask so that work items are affine to the
3691 * NUMA node it was issued on. Older pwqs are released as in-flight work
3692 * items finish. Note that a work item which repeatedly requeues itself
3693 * back-to-back will stay on its current pwq.
3695 * Performs GFP_KERNEL allocations.
3697 * Return: 0 on success and -errno on failure.
3699 int apply_workqueue_attrs(struct workqueue_struct *wq,
3700 const struct workqueue_attrs *attrs)
3704 apply_wqattrs_lock();
3705 ret = apply_workqueue_attrs_locked(wq, attrs);
3706 apply_wqattrs_unlock();
3712 * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
3713 * @wq: the target workqueue
3714 * @cpu: the CPU coming up or going down
3715 * @online: whether @cpu is coming up or going down
3717 * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
3718 * %CPU_DOWN_FAILED. @cpu is being hot[un]plugged, update NUMA affinity of
3721 * If NUMA affinity can't be adjusted due to memory allocation failure, it
3722 * falls back to @wq->dfl_pwq which may not be optimal but is always
3725 * Note that when the last allowed CPU of a NUMA node goes offline for a
3726 * workqueue with a cpumask spanning multiple nodes, the workers which were
3727 * already executing the work items for the workqueue will lose their CPU
3728 * affinity and may execute on any CPU. This is similar to how per-cpu
3729 * workqueues behave on CPU_DOWN. If a workqueue user wants strict
3730 * affinity, it's the user's responsibility to flush the work item from
3733 static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
3736 int node = cpu_to_node(cpu);
3737 int cpu_off = online ? -1 : cpu;
3738 struct pool_workqueue *old_pwq = NULL, *pwq;
3739 struct workqueue_attrs *target_attrs;
3742 lockdep_assert_held(&wq_pool_mutex);
3744 if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND) ||
3745 wq->unbound_attrs->no_numa)
3749 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
3750 * Let's use a preallocated one. The following buf is protected by
3751 * CPU hotplug exclusion.
3753 target_attrs = wq_update_unbound_numa_attrs_buf;
3754 cpumask = target_attrs->cpumask;
3756 copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
3757 pwq = unbound_pwq_by_node(wq, node);
3760 * Let's determine what needs to be done. If the target cpumask is
3761 * different from the default pwq's, we need to compare it to @pwq's
3762 * and create a new one if they don't match. If the target cpumask
3763 * equals the default pwq's, the default pwq should be used.
3765 if (wq_calc_node_cpumask(wq->dfl_pwq->pool->attrs, node, cpu_off, cpumask)) {
3766 if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
3772 /* create a new pwq */
3773 pwq = alloc_unbound_pwq(wq, target_attrs);
3775 pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
3780 /* Install the new pwq. */
3781 mutex_lock(&wq->mutex);
3782 old_pwq = numa_pwq_tbl_install(wq, node, pwq);
3786 mutex_lock(&wq->mutex);
3787 spin_lock_irq(&wq->dfl_pwq->pool->lock);
3788 get_pwq(wq->dfl_pwq);
3789 spin_unlock_irq(&wq->dfl_pwq->pool->lock);
3790 old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
3792 mutex_unlock(&wq->mutex);
3793 put_pwq_unlocked(old_pwq);
3796 static int alloc_and_link_pwqs(struct workqueue_struct *wq)
3798 bool highpri = wq->flags & WQ_HIGHPRI;
3801 if (!(wq->flags & WQ_UNBOUND)) {
3802 wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
3806 for_each_possible_cpu(cpu) {
3807 struct pool_workqueue *pwq =
3808 per_cpu_ptr(wq->cpu_pwqs, cpu);
3809 struct worker_pool *cpu_pools =
3810 per_cpu(cpu_worker_pools, cpu);
3812 init_pwq(pwq, wq, &cpu_pools[highpri]);
3814 mutex_lock(&wq->mutex);
3816 mutex_unlock(&wq->mutex);
3819 } else if (wq->flags & __WQ_ORDERED) {
3820 ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
3821 /* there should only be single pwq for ordering guarantee */
3822 WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
3823 wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
3824 "ordering guarantee broken for workqueue %s\n", wq->name);
3827 return apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
3831 static int wq_clamp_max_active(int max_active, unsigned int flags,
3834 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3836 if (max_active < 1 || max_active > lim)
3837 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3838 max_active, name, 1, lim);
3840 return clamp_val(max_active, 1, lim);
3843 struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
3846 struct lock_class_key *key,
3847 const char *lock_name, ...)
3849 size_t tbl_size = 0;
3851 struct workqueue_struct *wq;
3852 struct pool_workqueue *pwq;
3855 * Unbound && max_active == 1 used to imply ordered, which is no
3856 * longer the case on NUMA machines due to per-node pools. While
3857 * alloc_ordered_workqueue() is the right way to create an ordered
3858 * workqueue, keep the previous behavior to avoid subtle breakages
3861 if ((flags & WQ_UNBOUND) && max_active == 1)
3862 flags |= __WQ_ORDERED;
3864 /* see the comment above the definition of WQ_POWER_EFFICIENT */
3865 if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
3866 flags |= WQ_UNBOUND;
3868 /* allocate wq and format name */
3869 if (flags & WQ_UNBOUND)
3870 tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
3872 wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
3876 if (flags & WQ_UNBOUND) {
3877 wq->unbound_attrs = alloc_workqueue_attrs(GFP_KERNEL);
3878 if (!wq->unbound_attrs)
3882 va_start(args, lock_name);
3883 vsnprintf(wq->name, sizeof(wq->name), fmt, args);
3886 max_active = max_active ?: WQ_DFL_ACTIVE;
3887 max_active = wq_clamp_max_active(max_active, flags, wq->name);
3891 wq->saved_max_active = max_active;
3892 mutex_init(&wq->mutex);
3893 atomic_set(&wq->nr_pwqs_to_flush, 0);
3894 INIT_LIST_HEAD(&wq->pwqs);
3895 INIT_LIST_HEAD(&wq->flusher_queue);
3896 INIT_LIST_HEAD(&wq->flusher_overflow);
3897 INIT_LIST_HEAD(&wq->maydays);
3899 lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3900 INIT_LIST_HEAD(&wq->list);
3902 if (alloc_and_link_pwqs(wq) < 0)
3906 * Workqueues which may be used during memory reclaim should
3907 * have a rescuer to guarantee forward progress.
3909 if (flags & WQ_MEM_RECLAIM) {
3910 struct worker *rescuer;
3912 rescuer = alloc_worker(NUMA_NO_NODE);
3916 rescuer->rescue_wq = wq;
3917 rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
3919 if (IS_ERR(rescuer->task)) {
3924 wq->rescuer = rescuer;
3925 kthread_bind_mask(rescuer->task, cpu_possible_mask);
3926 wake_up_process(rescuer->task);
3929 if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
3933 * wq_pool_mutex protects global freeze state and workqueues list.
3934 * Grab it, adjust max_active and add the new @wq to workqueues
3937 mutex_lock(&wq_pool_mutex);
3939 mutex_lock(&wq->mutex);
3940 for_each_pwq(pwq, wq)
3941 pwq_adjust_max_active(pwq);
3942 mutex_unlock(&wq->mutex);
3944 list_add_tail_rcu(&wq->list, &workqueues);
3946 mutex_unlock(&wq_pool_mutex);
3951 free_workqueue_attrs(wq->unbound_attrs);
3955 destroy_workqueue(wq);
3958 EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
3961 * destroy_workqueue - safely terminate a workqueue
3962 * @wq: target workqueue
3964 * Safely destroy a workqueue. All work currently pending will be done first.
3966 void destroy_workqueue(struct workqueue_struct *wq)
3968 struct pool_workqueue *pwq;
3972 * Remove it from sysfs first so that sanity check failure doesn't
3973 * lead to sysfs name conflicts.
3975 workqueue_sysfs_unregister(wq);
3977 /* drain it before proceeding with destruction */
3978 drain_workqueue(wq);
3980 /* kill rescuer, if sanity checks fail, leave it w/o rescuer */
3982 struct worker *rescuer = wq->rescuer;
3984 /* this prevents new queueing */
3985 spin_lock_irq(&wq_mayday_lock);
3987 spin_unlock_irq(&wq_mayday_lock);
3989 /* rescuer will empty maydays list before exiting */
3990 kthread_stop(rescuer->task);
3995 mutex_lock(&wq->mutex);
3996 for_each_pwq(pwq, wq) {
3999 for (i = 0; i < WORK_NR_COLORS; i++) {
4000 if (WARN_ON(pwq->nr_in_flight[i])) {
4001 mutex_unlock(&wq->mutex);
4006 if (WARN_ON((pwq != wq->dfl_pwq) && (pwq->refcnt > 1)) ||
4007 WARN_ON(pwq->nr_active) ||
4008 WARN_ON(!list_empty(&pwq->delayed_works))) {
4009 mutex_unlock(&wq->mutex);
4013 mutex_unlock(&wq->mutex);
4016 * wq list is used to freeze wq, remove from list after
4017 * flushing is complete in case freeze races us.
4019 mutex_lock(&wq_pool_mutex);
4020 list_del_rcu(&wq->list);
4021 mutex_unlock(&wq_pool_mutex);
4023 if (!(wq->flags & WQ_UNBOUND)) {
4025 * The base ref is never dropped on per-cpu pwqs. Directly
4026 * schedule RCU free.
4028 call_rcu_sched(&wq->rcu, rcu_free_wq);
4031 * We're the sole accessor of @wq at this point. Directly
4032 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
4033 * @wq will be freed when the last pwq is released.
4035 for_each_node(node) {
4036 pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
4037 RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
4038 put_pwq_unlocked(pwq);
4042 * Put dfl_pwq. @wq may be freed any time after dfl_pwq is
4043 * put. Don't access it afterwards.
4047 put_pwq_unlocked(pwq);
4050 EXPORT_SYMBOL_GPL(destroy_workqueue);
4053 * workqueue_set_max_active - adjust max_active of a workqueue
4054 * @wq: target workqueue
4055 * @max_active: new max_active value.
4057 * Set max_active of @wq to @max_active.
4060 * Don't call from IRQ context.
4062 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4064 struct pool_workqueue *pwq;
4066 /* disallow meddling with max_active for ordered workqueues */
4067 if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
4070 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4072 mutex_lock(&wq->mutex);
4074 wq->flags &= ~__WQ_ORDERED;
4075 wq->saved_max_active = max_active;
4077 for_each_pwq(pwq, wq)
4078 pwq_adjust_max_active(pwq);
4080 mutex_unlock(&wq->mutex);
4082 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4085 * current_work - retrieve %current task's work struct
4087 * Determine if %current task is a workqueue worker and what it's working on.
4088 * Useful to find out the context that the %current task is running in.
4090 * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
4092 struct work_struct *current_work(void)
4094 struct worker *worker = current_wq_worker();
4096 return worker ? worker->current_work : NULL;
4098 EXPORT_SYMBOL(current_work);
4101 * current_is_workqueue_rescuer - is %current workqueue rescuer?
4103 * Determine whether %current is a workqueue rescuer. Can be used from
4104 * work functions to determine whether it's being run off the rescuer task.
4106 * Return: %true if %current is a workqueue rescuer. %false otherwise.
4108 bool current_is_workqueue_rescuer(void)
4110 struct worker *worker = current_wq_worker();
4112 return worker && worker->rescue_wq;
4116 * workqueue_congested - test whether a workqueue is congested
4117 * @cpu: CPU in question
4118 * @wq: target workqueue
4120 * Test whether @wq's cpu workqueue for @cpu is congested. There is
4121 * no synchronization around this function and the test result is
4122 * unreliable and only useful as advisory hints or for debugging.
4124 * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4125 * Note that both per-cpu and unbound workqueues may be associated with
4126 * multiple pool_workqueues which have separate congested states. A
4127 * workqueue being congested on one CPU doesn't mean the workqueue is also
4128 * contested on other CPUs / NUMA nodes.
4131 * %true if congested, %false otherwise.
4133 bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4135 struct pool_workqueue *pwq;
4138 rcu_read_lock_sched();
4140 if (cpu == WORK_CPU_UNBOUND)
4141 cpu = smp_processor_id();
4143 if (!(wq->flags & WQ_UNBOUND))
4144 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
4146 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4148 ret = !list_empty(&pwq->delayed_works);
4149 rcu_read_unlock_sched();
4153 EXPORT_SYMBOL_GPL(workqueue_congested);
4156 * work_busy - test whether a work is currently pending or running
4157 * @work: the work to be tested
4159 * Test whether @work is currently pending or running. There is no
4160 * synchronization around this function and the test result is
4161 * unreliable and only useful as advisory hints or for debugging.
4164 * OR'd bitmask of WORK_BUSY_* bits.
4166 unsigned int work_busy(struct work_struct *work)
4168 struct worker_pool *pool;
4169 unsigned long flags;
4170 unsigned int ret = 0;
4172 if (work_pending(work))
4173 ret |= WORK_BUSY_PENDING;
4175 local_irq_save(flags);
4176 pool = get_work_pool(work);
4178 spin_lock(&pool->lock);
4179 if (find_worker_executing_work(pool, work))
4180 ret |= WORK_BUSY_RUNNING;
4181 spin_unlock(&pool->lock);
4183 local_irq_restore(flags);
4187 EXPORT_SYMBOL_GPL(work_busy);
4190 * set_worker_desc - set description for the current work item
4191 * @fmt: printf-style format string
4192 * @...: arguments for the format string
4194 * This function can be called by a running work function to describe what
4195 * the work item is about. If the worker task gets dumped, this
4196 * information will be printed out together to help debugging. The
4197 * description can be at most WORKER_DESC_LEN including the trailing '\0'.
4199 void set_worker_desc(const char *fmt, ...)
4201 struct worker *worker = current_wq_worker();
4205 va_start(args, fmt);
4206 vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
4208 worker->desc_valid = true;
4213 * print_worker_info - print out worker information and description
4214 * @log_lvl: the log level to use when printing
4215 * @task: target task
4217 * If @task is a worker and currently executing a work item, print out the
4218 * name of the workqueue being serviced and worker description set with
4219 * set_worker_desc() by the currently executing work item.
4221 * This function can be safely called on any task as long as the
4222 * task_struct itself is accessible. While safe, this function isn't
4223 * synchronized and may print out mixups or garbages of limited length.
4225 void print_worker_info(const char *log_lvl, struct task_struct *task)
4227 work_func_t *fn = NULL;
4228 char name[WQ_NAME_LEN] = { };
4229 char desc[WORKER_DESC_LEN] = { };
4230 struct pool_workqueue *pwq = NULL;
4231 struct workqueue_struct *wq = NULL;
4232 bool desc_valid = false;
4233 struct worker *worker;
4235 if (!(task->flags & PF_WQ_WORKER))
4239 * This function is called without any synchronization and @task
4240 * could be in any state. Be careful with dereferences.
4242 worker = probe_kthread_data(task);
4245 * Carefully copy the associated workqueue's workfn and name. Keep
4246 * the original last '\0' in case the original contains garbage.
4248 probe_kernel_read(&fn, &worker->current_func, sizeof(fn));
4249 probe_kernel_read(&pwq, &worker->current_pwq, sizeof(pwq));
4250 probe_kernel_read(&wq, &pwq->wq, sizeof(wq));
4251 probe_kernel_read(name, wq->name, sizeof(name) - 1);
4253 /* copy worker description */
4254 probe_kernel_read(&desc_valid, &worker->desc_valid, sizeof(desc_valid));
4256 probe_kernel_read(desc, worker->desc, sizeof(desc) - 1);
4258 if (fn || name[0] || desc[0]) {
4259 printk("%sWorkqueue: %s %pf", log_lvl, name, fn);
4261 pr_cont(" (%s)", desc);
4266 static void pr_cont_pool_info(struct worker_pool *pool)
4268 pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
4269 if (pool->node != NUMA_NO_NODE)
4270 pr_cont(" node=%d", pool->node);
4271 pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
4274 static void pr_cont_work(bool comma, struct work_struct *work)
4276 if (work->func == wq_barrier_func) {
4277 struct wq_barrier *barr;
4279 barr = container_of(work, struct wq_barrier, work);
4281 pr_cont("%s BAR(%d)", comma ? "," : "",
4282 task_pid_nr(barr->task));
4284 pr_cont("%s %pf", comma ? "," : "", work->func);
4288 static void show_pwq(struct pool_workqueue *pwq)
4290 struct worker_pool *pool = pwq->pool;
4291 struct work_struct *work;
4292 struct worker *worker;
4293 bool has_in_flight = false, has_pending = false;
4296 pr_info(" pwq %d:", pool->id);
4297 pr_cont_pool_info(pool);
4299 pr_cont(" active=%d/%d refcnt=%d%s\n",
4300 pwq->nr_active, pwq->max_active, pwq->refcnt,
4301 !list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
4303 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
4304 if (worker->current_pwq == pwq) {
4305 has_in_flight = true;
4309 if (has_in_flight) {
4312 pr_info(" in-flight:");
4313 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
4314 if (worker->current_pwq != pwq)
4317 pr_cont("%s %d%s:%pf", comma ? "," : "",
4318 task_pid_nr(worker->task),
4319 worker == pwq->wq->rescuer ? "(RESCUER)" : "",
4320 worker->current_func);
4321 list_for_each_entry(work, &worker->scheduled, entry)
4322 pr_cont_work(false, work);
4328 list_for_each_entry(work, &pool->worklist, entry) {
4329 if (get_work_pwq(work) == pwq) {
4337 pr_info(" pending:");
4338 list_for_each_entry(work, &pool->worklist, entry) {
4339 if (get_work_pwq(work) != pwq)
4342 pr_cont_work(comma, work);
4343 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
4348 if (!list_empty(&pwq->delayed_works)) {
4351 pr_info(" delayed:");
4352 list_for_each_entry(work, &pwq->delayed_works, entry) {
4353 pr_cont_work(comma, work);
4354 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
4361 * show_workqueue_state - dump workqueue state
4363 * Called from a sysrq handler and prints out all busy workqueues and
4366 void show_workqueue_state(void)
4368 struct workqueue_struct *wq;
4369 struct worker_pool *pool;
4370 unsigned long flags;
4373 rcu_read_lock_sched();
4375 pr_info("Showing busy workqueues and worker pools:\n");
4377 list_for_each_entry_rcu(wq, &workqueues, list) {
4378 struct pool_workqueue *pwq;
4381 for_each_pwq(pwq, wq) {
4382 if (pwq->nr_active || !list_empty(&pwq->delayed_works)) {
4390 pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
4392 for_each_pwq(pwq, wq) {
4393 spin_lock_irqsave(&pwq->pool->lock, flags);
4394 if (pwq->nr_active || !list_empty(&pwq->delayed_works))
4396 spin_unlock_irqrestore(&pwq->pool->lock, flags);
4400 for_each_pool(pool, pi) {
4401 struct worker *worker;
4404 spin_lock_irqsave(&pool->lock, flags);
4405 if (pool->nr_workers == pool->nr_idle)
4408 pr_info("pool %d:", pool->id);
4409 pr_cont_pool_info(pool);
4410 pr_cont(" workers=%d", pool->nr_workers);
4412 pr_cont(" manager: %d",
4413 task_pid_nr(pool->manager->task));
4414 list_for_each_entry(worker, &pool->idle_list, entry) {
4415 pr_cont(" %s%d", first ? "idle: " : "",
4416 task_pid_nr(worker->task));
4421 spin_unlock_irqrestore(&pool->lock, flags);
4424 rcu_read_unlock_sched();
4430 * There are two challenges in supporting CPU hotplug. Firstly, there
4431 * are a lot of assumptions on strong associations among work, pwq and
4432 * pool which make migrating pending and scheduled works very
4433 * difficult to implement without impacting hot paths. Secondly,
4434 * worker pools serve mix of short, long and very long running works making
4435 * blocked draining impractical.
4437 * This is solved by allowing the pools to be disassociated from the CPU
4438 * running as an unbound one and allowing it to be reattached later if the
4439 * cpu comes back online.
4442 static void wq_unbind_fn(struct work_struct *work)
4444 int cpu = smp_processor_id();
4445 struct worker_pool *pool;
4446 struct worker *worker;
4448 for_each_cpu_worker_pool(pool, cpu) {
4449 mutex_lock(&pool->attach_mutex);
4450 spin_lock_irq(&pool->lock);
4453 * We've blocked all attach/detach operations. Make all workers
4454 * unbound and set DISASSOCIATED. Before this, all workers
4455 * except for the ones which are still executing works from
4456 * before the last CPU down must be on the cpu. After
4457 * this, they may become diasporas.
4459 for_each_pool_worker(worker, pool)
4460 worker->flags |= WORKER_UNBOUND;
4462 pool->flags |= POOL_DISASSOCIATED;
4464 spin_unlock_irq(&pool->lock);
4465 mutex_unlock(&pool->attach_mutex);
4468 * Call schedule() so that we cross rq->lock and thus can
4469 * guarantee sched callbacks see the %WORKER_UNBOUND flag.
4470 * This is necessary as scheduler callbacks may be invoked
4476 * Sched callbacks are disabled now. Zap nr_running.
4477 * After this, nr_running stays zero and need_more_worker()
4478 * and keep_working() are always true as long as the
4479 * worklist is not empty. This pool now behaves as an
4480 * unbound (in terms of concurrency management) pool which
4481 * are served by workers tied to the pool.
4483 atomic_set(&pool->nr_running, 0);
4486 * With concurrency management just turned off, a busy
4487 * worker blocking could lead to lengthy stalls. Kick off
4488 * unbound chain execution of currently pending work items.
4490 spin_lock_irq(&pool->lock);
4491 wake_up_worker(pool);
4492 spin_unlock_irq(&pool->lock);
4497 * rebind_workers - rebind all workers of a pool to the associated CPU
4498 * @pool: pool of interest
4500 * @pool->cpu is coming online. Rebind all workers to the CPU.
4502 static void rebind_workers(struct worker_pool *pool)
4504 struct worker *worker;
4506 lockdep_assert_held(&pool->attach_mutex);
4509 * Restore CPU affinity of all workers. As all idle workers should
4510 * be on the run-queue of the associated CPU before any local
4511 * wake-ups for concurrency management happen, restore CPU affinity
4512 * of all workers first and then clear UNBOUND. As we're called
4513 * from CPU_ONLINE, the following shouldn't fail.
4515 for_each_pool_worker(worker, pool)
4516 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4517 pool->attrs->cpumask) < 0);
4519 spin_lock_irq(&pool->lock);
4522 * XXX: CPU hotplug notifiers are weird and can call DOWN_FAILED
4523 * w/o preceding DOWN_PREPARE. Work around it. CPU hotplug is
4524 * being reworked and this can go away in time.
4526 if (!(pool->flags & POOL_DISASSOCIATED)) {
4527 spin_unlock_irq(&pool->lock);
4531 pool->flags &= ~POOL_DISASSOCIATED;
4533 for_each_pool_worker(worker, pool) {
4534 unsigned int worker_flags = worker->flags;
4537 * A bound idle worker should actually be on the runqueue
4538 * of the associated CPU for local wake-ups targeting it to
4539 * work. Kick all idle workers so that they migrate to the
4540 * associated CPU. Doing this in the same loop as
4541 * replacing UNBOUND with REBOUND is safe as no worker will
4542 * be bound before @pool->lock is released.
4544 if (worker_flags & WORKER_IDLE)
4545 wake_up_process(worker->task);
4548 * We want to clear UNBOUND but can't directly call
4549 * worker_clr_flags() or adjust nr_running. Atomically
4550 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
4551 * @worker will clear REBOUND using worker_clr_flags() when
4552 * it initiates the next execution cycle thus restoring
4553 * concurrency management. Note that when or whether
4554 * @worker clears REBOUND doesn't affect correctness.
4556 * ACCESS_ONCE() is necessary because @worker->flags may be
4557 * tested without holding any lock in
4558 * wq_worker_waking_up(). Without it, NOT_RUNNING test may
4559 * fail incorrectly leading to premature concurrency
4560 * management operations.
4562 WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
4563 worker_flags |= WORKER_REBOUND;
4564 worker_flags &= ~WORKER_UNBOUND;
4565 ACCESS_ONCE(worker->flags) = worker_flags;
4568 spin_unlock_irq(&pool->lock);
4572 * restore_unbound_workers_cpumask - restore cpumask of unbound workers
4573 * @pool: unbound pool of interest
4574 * @cpu: the CPU which is coming up
4576 * An unbound pool may end up with a cpumask which doesn't have any online
4577 * CPUs. When a worker of such pool get scheduled, the scheduler resets
4578 * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
4579 * online CPU before, cpus_allowed of all its workers should be restored.
4581 static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
4583 static cpumask_t cpumask;
4584 struct worker *worker;
4586 lockdep_assert_held(&pool->attach_mutex);
4588 /* is @cpu allowed for @pool? */
4589 if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
4592 /* is @cpu the only online CPU? */
4593 cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
4594 if (cpumask_weight(&cpumask) != 1)
4597 /* as we're called from CPU_ONLINE, the following shouldn't fail */
4598 for_each_pool_worker(worker, pool)
4599 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4600 pool->attrs->cpumask) < 0);
4604 * Workqueues should be brought up before normal priority CPU notifiers.
4605 * This will be registered high priority CPU notifier.
4607 static int workqueue_cpu_up_callback(struct notifier_block *nfb,
4608 unsigned long action,
4611 int cpu = (unsigned long)hcpu;
4612 struct worker_pool *pool;
4613 struct workqueue_struct *wq;
4616 switch (action & ~CPU_TASKS_FROZEN) {
4617 case CPU_UP_PREPARE:
4618 for_each_cpu_worker_pool(pool, cpu) {
4619 if (pool->nr_workers)
4621 if (!create_worker(pool))
4626 case CPU_DOWN_FAILED:
4628 mutex_lock(&wq_pool_mutex);
4630 for_each_pool(pool, pi) {
4631 mutex_lock(&pool->attach_mutex);
4633 if (pool->cpu == cpu)
4634 rebind_workers(pool);
4635 else if (pool->cpu < 0)
4636 restore_unbound_workers_cpumask(pool, cpu);
4638 mutex_unlock(&pool->attach_mutex);
4641 /* update NUMA affinity of unbound workqueues */
4642 list_for_each_entry(wq, &workqueues, list)
4643 wq_update_unbound_numa(wq, cpu, true);
4645 mutex_unlock(&wq_pool_mutex);
4652 * Workqueues should be brought down after normal priority CPU notifiers.
4653 * This will be registered as low priority CPU notifier.
4655 static int workqueue_cpu_down_callback(struct notifier_block *nfb,
4656 unsigned long action,
4659 int cpu = (unsigned long)hcpu;
4660 struct work_struct unbind_work;
4661 struct workqueue_struct *wq;
4663 switch (action & ~CPU_TASKS_FROZEN) {
4664 case CPU_DOWN_PREPARE:
4665 /* unbinding per-cpu workers should happen on the local CPU */
4666 INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
4667 queue_work_on(cpu, system_highpri_wq, &unbind_work);
4669 /* update NUMA affinity of unbound workqueues */
4670 mutex_lock(&wq_pool_mutex);
4671 list_for_each_entry(wq, &workqueues, list)
4672 wq_update_unbound_numa(wq, cpu, false);
4673 mutex_unlock(&wq_pool_mutex);
4675 /* wait for per-cpu unbinding to finish */
4676 flush_work(&unbind_work);
4677 destroy_work_on_stack(&unbind_work);
4685 struct work_for_cpu {
4686 struct work_struct work;
4692 static void work_for_cpu_fn(struct work_struct *work)
4694 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
4696 wfc->ret = wfc->fn(wfc->arg);
4700 * work_on_cpu - run a function in user context on a particular cpu
4701 * @cpu: the cpu to run on
4702 * @fn: the function to run
4703 * @arg: the function arg
4705 * It is up to the caller to ensure that the cpu doesn't go offline.
4706 * The caller must not hold any locks which would prevent @fn from completing.
4708 * Return: The value @fn returns.
4710 long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
4712 struct work_for_cpu wfc = { .fn = fn, .arg = arg };
4714 INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
4715 schedule_work_on(cpu, &wfc.work);
4716 flush_work(&wfc.work);
4717 destroy_work_on_stack(&wfc.work);
4720 EXPORT_SYMBOL_GPL(work_on_cpu);
4721 #endif /* CONFIG_SMP */
4723 #ifdef CONFIG_FREEZER
4726 * freeze_workqueues_begin - begin freezing workqueues
4728 * Start freezing workqueues. After this function returns, all freezable
4729 * workqueues will queue new works to their delayed_works list instead of
4733 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4735 void freeze_workqueues_begin(void)
4737 struct workqueue_struct *wq;
4738 struct pool_workqueue *pwq;
4740 mutex_lock(&wq_pool_mutex);
4742 WARN_ON_ONCE(workqueue_freezing);
4743 workqueue_freezing = true;
4745 list_for_each_entry(wq, &workqueues, list) {
4746 mutex_lock(&wq->mutex);
4747 for_each_pwq(pwq, wq)
4748 pwq_adjust_max_active(pwq);
4749 mutex_unlock(&wq->mutex);
4752 mutex_unlock(&wq_pool_mutex);
4756 * freeze_workqueues_busy - are freezable workqueues still busy?
4758 * Check whether freezing is complete. This function must be called
4759 * between freeze_workqueues_begin() and thaw_workqueues().
4762 * Grabs and releases wq_pool_mutex.
4765 * %true if some freezable workqueues are still busy. %false if freezing
4768 bool freeze_workqueues_busy(void)
4771 struct workqueue_struct *wq;
4772 struct pool_workqueue *pwq;
4774 mutex_lock(&wq_pool_mutex);
4776 WARN_ON_ONCE(!workqueue_freezing);
4778 list_for_each_entry(wq, &workqueues, list) {
4779 if (!(wq->flags & WQ_FREEZABLE))
4782 * nr_active is monotonically decreasing. It's safe
4783 * to peek without lock.
4785 rcu_read_lock_sched();
4786 for_each_pwq(pwq, wq) {
4787 WARN_ON_ONCE(pwq->nr_active < 0);
4788 if (pwq->nr_active) {
4790 rcu_read_unlock_sched();
4794 rcu_read_unlock_sched();
4797 mutex_unlock(&wq_pool_mutex);
4802 * thaw_workqueues - thaw workqueues
4804 * Thaw workqueues. Normal queueing is restored and all collected
4805 * frozen works are transferred to their respective pool worklists.
4808 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4810 void thaw_workqueues(void)
4812 struct workqueue_struct *wq;
4813 struct pool_workqueue *pwq;
4815 mutex_lock(&wq_pool_mutex);
4817 if (!workqueue_freezing)
4820 workqueue_freezing = false;
4822 /* restore max_active and repopulate worklist */
4823 list_for_each_entry(wq, &workqueues, list) {
4824 mutex_lock(&wq->mutex);
4825 for_each_pwq(pwq, wq)
4826 pwq_adjust_max_active(pwq);
4827 mutex_unlock(&wq->mutex);
4831 mutex_unlock(&wq_pool_mutex);
4833 #endif /* CONFIG_FREEZER */
4835 static int workqueue_apply_unbound_cpumask(void)
4839 struct workqueue_struct *wq;
4840 struct apply_wqattrs_ctx *ctx, *n;
4842 lockdep_assert_held(&wq_pool_mutex);
4844 list_for_each_entry(wq, &workqueues, list) {
4845 if (!(wq->flags & WQ_UNBOUND))
4847 /* creating multiple pwqs breaks ordering guarantee */
4848 if (wq->flags & __WQ_ORDERED)
4851 ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs);
4857 list_add_tail(&ctx->list, &ctxs);
4860 list_for_each_entry_safe(ctx, n, &ctxs, list) {
4862 apply_wqattrs_commit(ctx);
4863 apply_wqattrs_cleanup(ctx);
4870 * workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
4871 * @cpumask: the cpumask to set
4873 * The low-level workqueues cpumask is a global cpumask that limits
4874 * the affinity of all unbound workqueues. This function check the @cpumask
4875 * and apply it to all unbound workqueues and updates all pwqs of them.
4877 * Retun: 0 - Success
4878 * -EINVAL - Invalid @cpumask
4879 * -ENOMEM - Failed to allocate memory for attrs or pwqs.
4881 int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
4884 cpumask_var_t saved_cpumask;
4886 if (!zalloc_cpumask_var(&saved_cpumask, GFP_KERNEL))
4889 cpumask_and(cpumask, cpumask, cpu_possible_mask);
4890 if (!cpumask_empty(cpumask)) {
4891 apply_wqattrs_lock();
4893 /* save the old wq_unbound_cpumask. */
4894 cpumask_copy(saved_cpumask, wq_unbound_cpumask);
4896 /* update wq_unbound_cpumask at first and apply it to wqs. */
4897 cpumask_copy(wq_unbound_cpumask, cpumask);
4898 ret = workqueue_apply_unbound_cpumask();
4900 /* restore the wq_unbound_cpumask when failed. */
4902 cpumask_copy(wq_unbound_cpumask, saved_cpumask);
4904 apply_wqattrs_unlock();
4907 free_cpumask_var(saved_cpumask);
4913 * Workqueues with WQ_SYSFS flag set is visible to userland via
4914 * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
4915 * following attributes.
4917 * per_cpu RO bool : whether the workqueue is per-cpu or unbound
4918 * max_active RW int : maximum number of in-flight work items
4920 * Unbound workqueues have the following extra attributes.
4922 * id RO int : the associated pool ID
4923 * nice RW int : nice value of the workers
4924 * cpumask RW mask : bitmask of allowed CPUs for the workers
4927 struct workqueue_struct *wq;
4931 static struct workqueue_struct *dev_to_wq(struct device *dev)
4933 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
4938 static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
4941 struct workqueue_struct *wq = dev_to_wq(dev);
4943 return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
4945 static DEVICE_ATTR_RO(per_cpu);
4947 static ssize_t max_active_show(struct device *dev,
4948 struct device_attribute *attr, char *buf)
4950 struct workqueue_struct *wq = dev_to_wq(dev);
4952 return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
4955 static ssize_t max_active_store(struct device *dev,
4956 struct device_attribute *attr, const char *buf,
4959 struct workqueue_struct *wq = dev_to_wq(dev);
4962 if (sscanf(buf, "%d", &val) != 1 || val <= 0)
4965 workqueue_set_max_active(wq, val);
4968 static DEVICE_ATTR_RW(max_active);
4970 static struct attribute *wq_sysfs_attrs[] = {
4971 &dev_attr_per_cpu.attr,
4972 &dev_attr_max_active.attr,
4975 ATTRIBUTE_GROUPS(wq_sysfs);
4977 static ssize_t wq_pool_ids_show(struct device *dev,
4978 struct device_attribute *attr, char *buf)
4980 struct workqueue_struct *wq = dev_to_wq(dev);
4981 const char *delim = "";
4982 int node, written = 0;
4984 rcu_read_lock_sched();
4985 for_each_node(node) {
4986 written += scnprintf(buf + written, PAGE_SIZE - written,
4987 "%s%d:%d", delim, node,
4988 unbound_pwq_by_node(wq, node)->pool->id);
4991 written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
4992 rcu_read_unlock_sched();
4997 static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
5000 struct workqueue_struct *wq = dev_to_wq(dev);
5003 mutex_lock(&wq->mutex);
5004 written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
5005 mutex_unlock(&wq->mutex);
5010 /* prepare workqueue_attrs for sysfs store operations */
5011 static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
5013 struct workqueue_attrs *attrs;
5015 lockdep_assert_held(&wq_pool_mutex);
5017 attrs = alloc_workqueue_attrs(GFP_KERNEL);
5021 copy_workqueue_attrs(attrs, wq->unbound_attrs);
5025 static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
5026 const char *buf, size_t count)
5028 struct workqueue_struct *wq = dev_to_wq(dev);
5029 struct workqueue_attrs *attrs;
5032 apply_wqattrs_lock();
5034 attrs = wq_sysfs_prep_attrs(wq);
5038 if (sscanf(buf, "%d", &attrs->nice) == 1 &&
5039 attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
5040 ret = apply_workqueue_attrs_locked(wq, attrs);
5045 apply_wqattrs_unlock();
5046 free_workqueue_attrs(attrs);
5047 return ret ?: count;
5050 static ssize_t wq_cpumask_show(struct device *dev,
5051 struct device_attribute *attr, char *buf)
5053 struct workqueue_struct *wq = dev_to_wq(dev);
5056 mutex_lock(&wq->mutex);
5057 written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
5058 cpumask_pr_args(wq->unbound_attrs->cpumask));
5059 mutex_unlock(&wq->mutex);
5063 static ssize_t wq_cpumask_store(struct device *dev,
5064 struct device_attribute *attr,
5065 const char *buf, size_t count)
5067 struct workqueue_struct *wq = dev_to_wq(dev);
5068 struct workqueue_attrs *attrs;
5071 apply_wqattrs_lock();
5073 attrs = wq_sysfs_prep_attrs(wq);
5077 ret = cpumask_parse(buf, attrs->cpumask);
5079 ret = apply_workqueue_attrs_locked(wq, attrs);
5082 apply_wqattrs_unlock();
5083 free_workqueue_attrs(attrs);
5084 return ret ?: count;
5087 static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
5090 struct workqueue_struct *wq = dev_to_wq(dev);
5093 mutex_lock(&wq->mutex);
5094 written = scnprintf(buf, PAGE_SIZE, "%d\n",
5095 !wq->unbound_attrs->no_numa);
5096 mutex_unlock(&wq->mutex);
5101 static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
5102 const char *buf, size_t count)
5104 struct workqueue_struct *wq = dev_to_wq(dev);
5105 struct workqueue_attrs *attrs;
5106 int v, ret = -ENOMEM;
5108 apply_wqattrs_lock();
5110 attrs = wq_sysfs_prep_attrs(wq);
5115 if (sscanf(buf, "%d", &v) == 1) {
5116 attrs->no_numa = !v;
5117 ret = apply_workqueue_attrs_locked(wq, attrs);
5121 apply_wqattrs_unlock();
5122 free_workqueue_attrs(attrs);
5123 return ret ?: count;
5126 static struct device_attribute wq_sysfs_unbound_attrs[] = {
5127 __ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
5128 __ATTR(nice, 0644, wq_nice_show, wq_nice_store),
5129 __ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
5130 __ATTR(numa, 0644, wq_numa_show, wq_numa_store),
5134 static struct bus_type wq_subsys = {
5135 .name = "workqueue",
5136 .dev_groups = wq_sysfs_groups,
5139 static ssize_t wq_unbound_cpumask_show(struct device *dev,
5140 struct device_attribute *attr, char *buf)
5144 mutex_lock(&wq_pool_mutex);
5145 written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
5146 cpumask_pr_args(wq_unbound_cpumask));
5147 mutex_unlock(&wq_pool_mutex);
5152 static ssize_t wq_unbound_cpumask_store(struct device *dev,
5153 struct device_attribute *attr, const char *buf, size_t count)
5155 cpumask_var_t cpumask;
5158 if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
5161 ret = cpumask_parse(buf, cpumask);
5163 ret = workqueue_set_unbound_cpumask(cpumask);
5165 free_cpumask_var(cpumask);
5166 return ret ? ret : count;
5169 static struct device_attribute wq_sysfs_cpumask_attr =
5170 __ATTR(cpumask, 0644, wq_unbound_cpumask_show,
5171 wq_unbound_cpumask_store);
5173 static int __init wq_sysfs_init(void)
5177 err = subsys_virtual_register(&wq_subsys, NULL);
5181 return device_create_file(wq_subsys.dev_root, &wq_sysfs_cpumask_attr);
5183 core_initcall(wq_sysfs_init);
5185 static void wq_device_release(struct device *dev)
5187 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
5193 * workqueue_sysfs_register - make a workqueue visible in sysfs
5194 * @wq: the workqueue to register
5196 * Expose @wq in sysfs under /sys/bus/workqueue/devices.
5197 * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
5198 * which is the preferred method.
5200 * Workqueue user should use this function directly iff it wants to apply
5201 * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
5202 * apply_workqueue_attrs() may race against userland updating the
5205 * Return: 0 on success, -errno on failure.
5207 int workqueue_sysfs_register(struct workqueue_struct *wq)
5209 struct wq_device *wq_dev;
5213 * Adjusting max_active or creating new pwqs by applying
5214 * attributes breaks ordering guarantee. Disallow exposing ordered
5217 if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
5220 wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
5225 wq_dev->dev.bus = &wq_subsys;
5226 wq_dev->dev.init_name = wq->name;
5227 wq_dev->dev.release = wq_device_release;
5230 * unbound_attrs are created separately. Suppress uevent until
5231 * everything is ready.
5233 dev_set_uevent_suppress(&wq_dev->dev, true);
5235 ret = device_register(&wq_dev->dev);
5237 put_device(&wq_dev->dev);
5242 if (wq->flags & WQ_UNBOUND) {
5243 struct device_attribute *attr;
5245 for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
5246 ret = device_create_file(&wq_dev->dev, attr);
5248 device_unregister(&wq_dev->dev);
5255 dev_set_uevent_suppress(&wq_dev->dev, false);
5256 kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
5261 * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
5262 * @wq: the workqueue to unregister
5264 * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
5266 static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
5268 struct wq_device *wq_dev = wq->wq_dev;
5274 device_unregister(&wq_dev->dev);
5276 #else /* CONFIG_SYSFS */
5277 static void workqueue_sysfs_unregister(struct workqueue_struct *wq) { }
5278 #endif /* CONFIG_SYSFS */
5280 static void __init wq_numa_init(void)
5285 if (num_possible_nodes() <= 1)
5288 if (wq_disable_numa) {
5289 pr_info("workqueue: NUMA affinity support disabled\n");
5293 wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs(GFP_KERNEL);
5294 BUG_ON(!wq_update_unbound_numa_attrs_buf);
5297 * We want masks of possible CPUs of each node which isn't readily
5298 * available. Build one from cpu_to_node() which should have been
5299 * fully initialized by now.
5301 tbl = kzalloc(nr_node_ids * sizeof(tbl[0]), GFP_KERNEL);
5305 BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
5306 node_online(node) ? node : NUMA_NO_NODE));
5308 for_each_possible_cpu(cpu) {
5309 node = cpu_to_node(cpu);
5310 if (WARN_ON(node == NUMA_NO_NODE)) {
5311 pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
5312 /* happens iff arch is bonkers, let's just proceed */
5315 cpumask_set_cpu(cpu, tbl[node]);
5318 wq_numa_possible_cpumask = tbl;
5319 wq_numa_enabled = true;
5322 static int __init init_workqueues(void)
5324 int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
5327 WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
5329 BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
5330 cpumask_copy(wq_unbound_cpumask, cpu_possible_mask);
5332 pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
5334 cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
5335 hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
5339 /* initialize CPU pools */
5340 for_each_possible_cpu(cpu) {
5341 struct worker_pool *pool;
5344 for_each_cpu_worker_pool(pool, cpu) {
5345 BUG_ON(init_worker_pool(pool));
5347 cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
5348 pool->attrs->nice = std_nice[i++];
5349 pool->node = cpu_to_node(cpu);
5352 mutex_lock(&wq_pool_mutex);
5353 BUG_ON(worker_pool_assign_id(pool));
5354 mutex_unlock(&wq_pool_mutex);
5358 /* create the initial worker */
5359 for_each_online_cpu(cpu) {
5360 struct worker_pool *pool;
5362 for_each_cpu_worker_pool(pool, cpu) {
5363 pool->flags &= ~POOL_DISASSOCIATED;
5364 BUG_ON(!create_worker(pool));
5368 /* create default unbound and ordered wq attrs */
5369 for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
5370 struct workqueue_attrs *attrs;
5372 BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
5373 attrs->nice = std_nice[i];
5374 unbound_std_wq_attrs[i] = attrs;
5377 * An ordered wq should have only one pwq as ordering is
5378 * guaranteed by max_active which is enforced by pwqs.
5379 * Turn off NUMA so that dfl_pwq is used for all nodes.
5381 BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
5382 attrs->nice = std_nice[i];
5383 attrs->no_numa = true;
5384 ordered_wq_attrs[i] = attrs;
5387 system_wq = alloc_workqueue("events", 0, 0);
5388 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
5389 system_long_wq = alloc_workqueue("events_long", 0, 0);
5390 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
5391 WQ_UNBOUND_MAX_ACTIVE);
5392 system_freezable_wq = alloc_workqueue("events_freezable",
5394 system_power_efficient_wq = alloc_workqueue("events_power_efficient",
5395 WQ_POWER_EFFICIENT, 0);
5396 system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
5397 WQ_FREEZABLE | WQ_POWER_EFFICIENT,
5399 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
5400 !system_unbound_wq || !system_freezable_wq ||
5401 !system_power_efficient_wq ||
5402 !system_freezable_power_efficient_wq);
5405 early_initcall(init_workqueues);