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>
51 #include <linux/locallock.h>
52 #include <linux/delay.h>
54 #include "workqueue_internal.h"
60 * A bound pool is either associated or disassociated with its CPU.
61 * While associated (!DISASSOCIATED), all workers are bound to the
62 * CPU and none has %WORKER_UNBOUND set and concurrency management
65 * While DISASSOCIATED, the cpu may be offline and all workers have
66 * %WORKER_UNBOUND set and concurrency management disabled, and may
67 * be executing on any CPU. The pool behaves as an unbound one.
69 * Note that DISASSOCIATED should be flipped only while holding
70 * attach_mutex to avoid changing binding state while
71 * worker_attach_to_pool() is in progress.
73 POOL_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
76 WORKER_DIE = 1 << 1, /* die die die */
77 WORKER_IDLE = 1 << 2, /* is idle */
78 WORKER_PREP = 1 << 3, /* preparing to run works */
79 WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
80 WORKER_UNBOUND = 1 << 7, /* worker is unbound */
81 WORKER_REBOUND = 1 << 8, /* worker was rebound */
83 WORKER_NOT_RUNNING = WORKER_PREP | WORKER_CPU_INTENSIVE |
84 WORKER_UNBOUND | WORKER_REBOUND,
86 NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */
88 UNBOUND_POOL_HASH_ORDER = 6, /* hashed by pool->attrs */
89 BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
91 MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
92 IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
94 MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
95 /* call for help after 10ms
97 MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
98 CREATE_COOLDOWN = HZ, /* time to breath after fail */
101 * Rescue workers are used only on emergencies and shared by
102 * all cpus. Give MIN_NICE.
104 RESCUER_NICE_LEVEL = MIN_NICE,
105 HIGHPRI_NICE_LEVEL = MIN_NICE,
111 * Structure fields follow one of the following exclusion rules.
113 * I: Modifiable by initialization/destruction paths and read-only for
116 * P: Preemption protected. Disabling preemption is enough and should
117 * only be modified and accessed from the local cpu.
119 * L: pool->lock protected. Access with pool->lock held.
121 * X: During normal operation, modification requires pool->lock and should
122 * be done only from local cpu. Either disabling preemption on local
123 * cpu or grabbing pool->lock is enough for read access. If
124 * POOL_DISASSOCIATED is set, it's identical to L.
126 * On RT we need the extra protection via rt_lock_idle_list() for
127 * the list manipulations against read access from
128 * wq_worker_sleeping(). All other places are nicely serialized via
131 * A: pool->attach_mutex protected.
133 * PL: wq_pool_mutex protected.
135 * PR: wq_pool_mutex protected for writes. RCU protected for reads.
137 * PW: wq_pool_mutex and wq->mutex protected for writes. Either for reads.
139 * PWR: wq_pool_mutex and wq->mutex protected for writes. Either or
140 * sched-RCU for reads.
142 * WQ: wq->mutex protected.
144 * WR: wq->mutex protected for writes. RCU protected for reads.
146 * MD: wq_mayday_lock protected.
149 /* struct worker is defined in workqueue_internal.h */
152 spinlock_t lock; /* the pool lock */
153 int cpu; /* I: the associated cpu */
154 int node; /* I: the associated node ID */
155 int id; /* I: pool ID */
156 unsigned int flags; /* X: flags */
158 struct list_head worklist; /* L: list of pending works */
159 int nr_workers; /* L: total number of workers */
161 /* nr_idle includes the ones off idle_list for rebinding */
162 int nr_idle; /* L: currently idle ones */
164 struct list_head idle_list; /* X: list of idle workers */
165 struct timer_list idle_timer; /* L: worker idle timeout */
166 struct timer_list mayday_timer; /* L: SOS timer for workers */
168 /* a workers is either on busy_hash or idle_list, or the manager */
169 DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
170 /* L: hash of busy workers */
172 /* see manage_workers() for details on the two manager mutexes */
173 struct mutex manager_arb; /* manager arbitration */
174 struct worker *manager; /* L: purely informational */
175 struct mutex attach_mutex; /* attach/detach exclusion */
176 struct list_head workers; /* A: attached workers */
177 struct completion *detach_completion; /* all workers detached */
179 struct ida worker_ida; /* worker IDs for task name */
181 struct workqueue_attrs *attrs; /* I: worker attributes */
182 struct hlist_node hash_node; /* PL: unbound_pool_hash node */
183 int refcnt; /* PL: refcnt for unbound pools */
186 * The current concurrency level. As it's likely to be accessed
187 * from other CPUs during try_to_wake_up(), put it in a separate
190 atomic_t nr_running ____cacheline_aligned_in_smp;
193 * Destruction of pool is RCU protected to allow dereferences
194 * from get_work_pool().
197 } ____cacheline_aligned_in_smp;
200 * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
201 * of work_struct->data are used for flags and the remaining high bits
202 * point to the pwq; thus, pwqs need to be aligned at two's power of the
203 * number of flag bits.
205 struct pool_workqueue {
206 struct worker_pool *pool; /* I: the associated pool */
207 struct workqueue_struct *wq; /* I: the owning workqueue */
208 int work_color; /* L: current color */
209 int flush_color; /* L: flushing color */
210 int refcnt; /* L: reference count */
211 int nr_in_flight[WORK_NR_COLORS];
212 /* L: nr of in_flight works */
213 int nr_active; /* L: nr of active works */
214 int max_active; /* L: max active works */
215 struct list_head delayed_works; /* L: delayed works */
216 struct list_head pwqs_node; /* WR: node on wq->pwqs */
217 struct list_head mayday_node; /* MD: node on wq->maydays */
220 * Release of unbound pwq is punted to system_wq. See put_pwq()
221 * and pwq_unbound_release_workfn() for details. pool_workqueue
222 * itself is also RCU protected so that the first pwq can be
223 * determined without grabbing wq->mutex.
225 struct work_struct unbound_release_work;
227 } __aligned(1 << WORK_STRUCT_FLAG_BITS);
230 * Structure used to wait for workqueue flush.
233 struct list_head list; /* WQ: list of flushers */
234 int flush_color; /* WQ: flush color waiting for */
235 struct completion done; /* flush completion */
241 * The externally visible workqueue. It relays the issued work items to
242 * the appropriate worker_pool through its pool_workqueues.
244 struct workqueue_struct {
245 struct list_head pwqs; /* WR: all pwqs of this wq */
246 struct list_head list; /* PR: list of all workqueues */
248 struct mutex mutex; /* protects this wq */
249 int work_color; /* WQ: current work color */
250 int flush_color; /* WQ: current flush color */
251 atomic_t nr_pwqs_to_flush; /* flush in progress */
252 struct wq_flusher *first_flusher; /* WQ: first flusher */
253 struct list_head flusher_queue; /* WQ: flush waiters */
254 struct list_head flusher_overflow; /* WQ: flush overflow list */
256 struct list_head maydays; /* MD: pwqs requesting rescue */
257 struct worker *rescuer; /* I: rescue worker */
259 int nr_drainers; /* WQ: drain in progress */
260 int saved_max_active; /* WQ: saved pwq max_active */
262 struct workqueue_attrs *unbound_attrs; /* PW: only for unbound wqs */
263 struct pool_workqueue *dfl_pwq; /* PW: only for unbound wqs */
266 struct wq_device *wq_dev; /* I: for sysfs interface */
268 #ifdef CONFIG_LOCKDEP
269 struct lockdep_map lockdep_map;
271 char name[WQ_NAME_LEN]; /* I: workqueue name */
274 * Destruction of workqueue_struct is sched-RCU protected to allow
275 * walking the workqueues list without grabbing wq_pool_mutex.
276 * This is used to dump all workqueues from sysrq.
280 /* hot fields used during command issue, aligned to cacheline */
281 unsigned int flags ____cacheline_aligned; /* WQ: WQ_* flags */
282 struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */
283 struct pool_workqueue __rcu *numa_pwq_tbl[]; /* PWR: unbound pwqs indexed by node */
286 static struct kmem_cache *pwq_cache;
288 static cpumask_var_t *wq_numa_possible_cpumask;
289 /* possible CPUs of each node */
291 static bool wq_disable_numa;
292 module_param_named(disable_numa, wq_disable_numa, bool, 0444);
294 /* see the comment above the definition of WQ_POWER_EFFICIENT */
295 static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
296 module_param_named(power_efficient, wq_power_efficient, bool, 0444);
298 static bool wq_numa_enabled; /* unbound NUMA affinity enabled */
300 /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
301 static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf;
303 static DEFINE_MUTEX(wq_pool_mutex); /* protects pools and workqueues list */
304 static DEFINE_SPINLOCK(wq_mayday_lock); /* protects wq->maydays list */
306 static LIST_HEAD(workqueues); /* PR: list of all workqueues */
307 static bool workqueue_freezing; /* PL: have wqs started freezing? */
309 static cpumask_var_t wq_unbound_cpumask; /* PL: low level cpumask for all unbound wqs */
311 /* the per-cpu worker pools */
312 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
315 static DEFINE_IDR(worker_pool_idr); /* PR: idr of all pools */
317 /* PL: hash of all unbound pools keyed by pool->attrs */
318 static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
320 /* I: attributes used when instantiating standard unbound pools on demand */
321 static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
323 /* I: attributes used when instantiating ordered pools on demand */
324 static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
326 struct workqueue_struct *system_wq __read_mostly;
327 EXPORT_SYMBOL(system_wq);
328 struct workqueue_struct *system_highpri_wq __read_mostly;
329 EXPORT_SYMBOL_GPL(system_highpri_wq);
330 struct workqueue_struct *system_long_wq __read_mostly;
331 EXPORT_SYMBOL_GPL(system_long_wq);
332 struct workqueue_struct *system_unbound_wq __read_mostly;
333 EXPORT_SYMBOL_GPL(system_unbound_wq);
334 struct workqueue_struct *system_freezable_wq __read_mostly;
335 EXPORT_SYMBOL_GPL(system_freezable_wq);
336 struct workqueue_struct *system_power_efficient_wq __read_mostly;
337 EXPORT_SYMBOL_GPL(system_power_efficient_wq);
338 struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
339 EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
341 static DEFINE_LOCAL_IRQ_LOCK(pendingb_lock);
343 static int worker_thread(void *__worker);
344 static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
346 #define CREATE_TRACE_POINTS
347 #include <trace/events/workqueue.h>
349 #define assert_rcu_or_pool_mutex() \
350 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
351 !lockdep_is_held(&wq_pool_mutex), \
352 "RCU or wq_pool_mutex should be held")
354 #define assert_rcu_or_wq_mutex(wq) \
355 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
356 !lockdep_is_held(&wq->mutex), \
357 "RCU or wq->mutex should be held")
359 #define assert_rcu_or_wq_mutex_or_pool_mutex(wq) \
360 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
361 !lockdep_is_held(&wq->mutex) && \
362 !lockdep_is_held(&wq_pool_mutex), \
363 "RCU, wq->mutex or wq_pool_mutex should be held")
365 #define for_each_cpu_worker_pool(pool, cpu) \
366 for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
367 (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
371 * for_each_pool - iterate through all worker_pools in the system
372 * @pool: iteration cursor
373 * @pi: integer used for iteration
375 * This must be called either with wq_pool_mutex held or RCU read
376 * locked. If the pool needs to be used beyond the locking in effect, the
377 * caller is responsible for guaranteeing that the pool stays online.
379 * The if/else clause exists only for the lockdep assertion and can be
382 #define for_each_pool(pool, pi) \
383 idr_for_each_entry(&worker_pool_idr, pool, pi) \
384 if (({ assert_rcu_or_pool_mutex(); false; })) { } \
388 * for_each_pool_worker - iterate through all workers of a worker_pool
389 * @worker: iteration cursor
390 * @pool: worker_pool to iterate workers of
392 * This must be called with @pool->attach_mutex.
394 * The if/else clause exists only for the lockdep assertion and can be
397 #define for_each_pool_worker(worker, pool) \
398 list_for_each_entry((worker), &(pool)->workers, node) \
399 if (({ lockdep_assert_held(&pool->attach_mutex); false; })) { } \
403 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
404 * @pwq: iteration cursor
405 * @wq: the target workqueue
407 * This must be called either with wq->mutex held or RCU read locked.
408 * If the pwq needs to be used beyond the locking in effect, the caller is
409 * responsible for guaranteeing that the pwq stays online.
411 * The if/else clause exists only for the lockdep assertion and can be
414 #define for_each_pwq(pwq, wq) \
415 list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node) \
416 if (({ assert_rcu_or_wq_mutex(wq); false; })) { } \
419 #ifdef CONFIG_PREEMPT_RT_BASE
420 static inline void rt_lock_idle_list(struct worker_pool *pool)
424 static inline void rt_unlock_idle_list(struct worker_pool *pool)
428 static inline void sched_lock_idle_list(struct worker_pool *pool) { }
429 static inline void sched_unlock_idle_list(struct worker_pool *pool) { }
431 static inline void rt_lock_idle_list(struct worker_pool *pool) { }
432 static inline void rt_unlock_idle_list(struct worker_pool *pool) { }
433 static inline void sched_lock_idle_list(struct worker_pool *pool)
435 spin_lock_irq(&pool->lock);
437 static inline void sched_unlock_idle_list(struct worker_pool *pool)
439 spin_unlock_irq(&pool->lock);
444 #ifdef CONFIG_DEBUG_OBJECTS_WORK
446 static struct debug_obj_descr work_debug_descr;
448 static void *work_debug_hint(void *addr)
450 return ((struct work_struct *) addr)->func;
454 * fixup_init is called when:
455 * - an active object is initialized
457 static int work_fixup_init(void *addr, enum debug_obj_state state)
459 struct work_struct *work = addr;
462 case ODEBUG_STATE_ACTIVE:
463 cancel_work_sync(work);
464 debug_object_init(work, &work_debug_descr);
472 * fixup_activate is called when:
473 * - an active object is activated
474 * - an unknown object is activated (might be a statically initialized object)
476 static int work_fixup_activate(void *addr, enum debug_obj_state state)
478 struct work_struct *work = addr;
482 case ODEBUG_STATE_NOTAVAILABLE:
484 * This is not really a fixup. The work struct was
485 * statically initialized. We just make sure that it
486 * is tracked in the object tracker.
488 if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
489 debug_object_init(work, &work_debug_descr);
490 debug_object_activate(work, &work_debug_descr);
496 case ODEBUG_STATE_ACTIVE:
505 * fixup_free is called when:
506 * - an active object is freed
508 static int work_fixup_free(void *addr, enum debug_obj_state state)
510 struct work_struct *work = addr;
513 case ODEBUG_STATE_ACTIVE:
514 cancel_work_sync(work);
515 debug_object_free(work, &work_debug_descr);
522 static struct debug_obj_descr work_debug_descr = {
523 .name = "work_struct",
524 .debug_hint = work_debug_hint,
525 .fixup_init = work_fixup_init,
526 .fixup_activate = work_fixup_activate,
527 .fixup_free = work_fixup_free,
530 static inline void debug_work_activate(struct work_struct *work)
532 debug_object_activate(work, &work_debug_descr);
535 static inline void debug_work_deactivate(struct work_struct *work)
537 debug_object_deactivate(work, &work_debug_descr);
540 void __init_work(struct work_struct *work, int onstack)
543 debug_object_init_on_stack(work, &work_debug_descr);
545 debug_object_init(work, &work_debug_descr);
547 EXPORT_SYMBOL_GPL(__init_work);
549 void destroy_work_on_stack(struct work_struct *work)
551 debug_object_free(work, &work_debug_descr);
553 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
555 void destroy_delayed_work_on_stack(struct delayed_work *work)
557 destroy_timer_on_stack(&work->timer);
558 debug_object_free(&work->work, &work_debug_descr);
560 EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
563 static inline void debug_work_activate(struct work_struct *work) { }
564 static inline void debug_work_deactivate(struct work_struct *work) { }
568 * worker_pool_assign_id - allocate ID and assing it to @pool
569 * @pool: the pool pointer of interest
571 * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
572 * successfully, -errno on failure.
574 static int worker_pool_assign_id(struct worker_pool *pool)
578 lockdep_assert_held(&wq_pool_mutex);
580 ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
590 * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
591 * @wq: the target workqueue
594 * This must be called with any of wq_pool_mutex, wq->mutex or RCU
596 * If the pwq needs to be used beyond the locking in effect, the caller is
597 * responsible for guaranteeing that the pwq stays online.
599 * Return: The unbound pool_workqueue for @node.
601 static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
604 assert_rcu_or_wq_mutex_or_pool_mutex(wq);
607 * XXX: @node can be NUMA_NO_NODE if CPU goes offline while a
608 * delayed item is pending. The plan is to keep CPU -> NODE
609 * mapping valid and stable across CPU on/offlines. Once that
610 * happens, this workaround can be removed.
612 if (unlikely(node == NUMA_NO_NODE))
615 return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
618 static unsigned int work_color_to_flags(int color)
620 return color << WORK_STRUCT_COLOR_SHIFT;
623 static int get_work_color(struct work_struct *work)
625 return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
626 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
629 static int work_next_color(int color)
631 return (color + 1) % WORK_NR_COLORS;
635 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
636 * contain the pointer to the queued pwq. Once execution starts, the flag
637 * is cleared and the high bits contain OFFQ flags and pool ID.
639 * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
640 * and clear_work_data() can be used to set the pwq, pool or clear
641 * work->data. These functions should only be called while the work is
642 * owned - ie. while the PENDING bit is set.
644 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
645 * corresponding to a work. Pool is available once the work has been
646 * queued anywhere after initialization until it is sync canceled. pwq is
647 * available only while the work item is queued.
649 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
650 * canceled. While being canceled, a work item may have its PENDING set
651 * but stay off timer and worklist for arbitrarily long and nobody should
652 * try to steal the PENDING bit.
654 static inline void set_work_data(struct work_struct *work, unsigned long data,
657 WARN_ON_ONCE(!work_pending(work));
658 atomic_long_set(&work->data, data | flags | work_static(work));
661 static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
662 unsigned long extra_flags)
664 set_work_data(work, (unsigned long)pwq,
665 WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
668 static void set_work_pool_and_keep_pending(struct work_struct *work,
671 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
672 WORK_STRUCT_PENDING);
675 static void set_work_pool_and_clear_pending(struct work_struct *work,
679 * The following wmb is paired with the implied mb in
680 * test_and_set_bit(PENDING) and ensures all updates to @work made
681 * here are visible to and precede any updates by the next PENDING
685 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
687 * The following mb guarantees that previous clear of a PENDING bit
688 * will not be reordered with any speculative LOADS or STORES from
689 * work->current_func, which is executed afterwards. This possible
690 * reordering can lead to a missed execution on attempt to qeueue
691 * the same @work. E.g. consider this case:
694 * ---------------------------- --------------------------------
696 * 1 STORE event_indicated
697 * 2 queue_work_on() {
698 * 3 test_and_set_bit(PENDING)
699 * 4 } set_..._and_clear_pending() {
700 * 5 set_work_data() # clear bit
702 * 7 work->current_func() {
703 * 8 LOAD event_indicated
706 * Without an explicit full barrier speculative LOAD on line 8 can
707 * be executed before CPU#0 does STORE on line 1. If that happens,
708 * CPU#0 observes the PENDING bit is still set and new execution of
709 * a @work is not queued in a hope, that CPU#1 will eventually
710 * finish the queued @work. Meanwhile CPU#1 does not see
711 * event_indicated is set, because speculative LOAD was executed
712 * before actual STORE.
717 static void clear_work_data(struct work_struct *work)
719 smp_wmb(); /* see set_work_pool_and_clear_pending() */
720 set_work_data(work, WORK_STRUCT_NO_POOL, 0);
723 static struct pool_workqueue *get_work_pwq(struct work_struct *work)
725 unsigned long data = atomic_long_read(&work->data);
727 if (data & WORK_STRUCT_PWQ)
728 return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
734 * get_work_pool - return the worker_pool a given work was associated with
735 * @work: the work item of interest
737 * Pools are created and destroyed under wq_pool_mutex, and allows read
738 * access under RCU read lock. As such, this function should be
739 * called under wq_pool_mutex or inside of a rcu_read_lock() region.
741 * All fields of the returned pool are accessible as long as the above
742 * mentioned locking is in effect. If the returned pool needs to be used
743 * beyond the critical section, the caller is responsible for ensuring the
744 * returned pool is and stays online.
746 * Return: The worker_pool @work was last associated with. %NULL if none.
748 static struct worker_pool *get_work_pool(struct work_struct *work)
750 unsigned long data = atomic_long_read(&work->data);
753 assert_rcu_or_pool_mutex();
755 if (data & WORK_STRUCT_PWQ)
756 return ((struct pool_workqueue *)
757 (data & WORK_STRUCT_WQ_DATA_MASK))->pool;
759 pool_id = data >> WORK_OFFQ_POOL_SHIFT;
760 if (pool_id == WORK_OFFQ_POOL_NONE)
763 return idr_find(&worker_pool_idr, pool_id);
767 * get_work_pool_id - return the worker pool ID a given work is associated with
768 * @work: the work item of interest
770 * Return: The worker_pool ID @work was last associated with.
771 * %WORK_OFFQ_POOL_NONE if none.
773 static int get_work_pool_id(struct work_struct *work)
775 unsigned long data = atomic_long_read(&work->data);
777 if (data & WORK_STRUCT_PWQ)
778 return ((struct pool_workqueue *)
779 (data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
781 return data >> WORK_OFFQ_POOL_SHIFT;
784 static void mark_work_canceling(struct work_struct *work)
786 unsigned long pool_id = get_work_pool_id(work);
788 pool_id <<= WORK_OFFQ_POOL_SHIFT;
789 set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
792 static bool work_is_canceling(struct work_struct *work)
794 unsigned long data = atomic_long_read(&work->data);
796 return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
800 * Policy functions. These define the policies on how the global worker
801 * pools are managed. Unless noted otherwise, these functions assume that
802 * they're being called with pool->lock held.
805 static bool __need_more_worker(struct worker_pool *pool)
807 return !atomic_read(&pool->nr_running);
811 * Need to wake up a worker? Called from anything but currently
814 * Note that, because unbound workers never contribute to nr_running, this
815 * function will always return %true for unbound pools as long as the
816 * worklist isn't empty.
818 static bool need_more_worker(struct worker_pool *pool)
820 return !list_empty(&pool->worklist) && __need_more_worker(pool);
823 /* Can I start working? Called from busy but !running workers. */
824 static bool may_start_working(struct worker_pool *pool)
826 return pool->nr_idle;
829 /* Do I need to keep working? Called from currently running workers. */
830 static bool keep_working(struct worker_pool *pool)
832 return !list_empty(&pool->worklist) &&
833 atomic_read(&pool->nr_running) <= 1;
836 /* Do we need a new worker? Called from manager. */
837 static bool need_to_create_worker(struct worker_pool *pool)
839 return need_more_worker(pool) && !may_start_working(pool);
842 /* Do we have too many workers and should some go away? */
843 static bool too_many_workers(struct worker_pool *pool)
845 bool managing = mutex_is_locked(&pool->manager_arb);
846 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
847 int nr_busy = pool->nr_workers - nr_idle;
849 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
856 /* Return the first idle worker. Safe with preemption disabled */
857 static struct worker *first_idle_worker(struct worker_pool *pool)
859 if (unlikely(list_empty(&pool->idle_list)))
862 return list_first_entry(&pool->idle_list, struct worker, entry);
866 * wake_up_worker - wake up an idle worker
867 * @pool: worker pool to wake worker from
869 * Wake up the first idle worker of @pool.
872 * spin_lock_irq(pool->lock).
874 static void wake_up_worker(struct worker_pool *pool)
876 struct worker *worker;
878 rt_lock_idle_list(pool);
880 worker = first_idle_worker(pool);
883 wake_up_process(worker->task);
885 rt_unlock_idle_list(pool);
889 * wq_worker_running - a worker is running again
890 * @task: task returning from sleep
892 * This function is called when a worker returns from schedule()
894 void wq_worker_running(struct task_struct *task)
896 struct worker *worker = kthread_data(task);
898 if (!worker->sleeping)
900 if (!(worker->flags & WORKER_NOT_RUNNING))
901 atomic_inc(&worker->pool->nr_running);
902 worker->sleeping = 0;
906 * wq_worker_sleeping - a worker is going to sleep
907 * @task: task going to sleep
908 * This function is called from schedule() when a busy worker is
911 void wq_worker_sleeping(struct task_struct *task)
913 struct worker *worker = kthread_data(task);
914 struct worker_pool *pool;
917 * Rescuers, which may not have all the fields set up like normal
918 * workers, also reach here, let's not access anything before
919 * checking NOT_RUNNING.
921 if (worker->flags & WORKER_NOT_RUNNING)
926 if (WARN_ON_ONCE(worker->sleeping))
929 worker->sleeping = 1;
932 * The counterpart of the following dec_and_test, implied mb,
933 * worklist not empty test sequence is in insert_work().
934 * Please read comment there.
936 if (atomic_dec_and_test(&pool->nr_running) &&
937 !list_empty(&pool->worklist)) {
938 sched_lock_idle_list(pool);
939 wake_up_worker(pool);
940 sched_unlock_idle_list(pool);
945 * worker_set_flags - set worker flags and adjust nr_running accordingly
947 * @flags: flags to set
949 * Set @flags in @worker->flags and adjust nr_running accordingly.
952 * spin_lock_irq(pool->lock)
954 static inline void worker_set_flags(struct worker *worker, unsigned int flags)
956 struct worker_pool *pool = worker->pool;
958 WARN_ON_ONCE(worker->task != current);
960 /* If transitioning into NOT_RUNNING, adjust nr_running. */
961 if ((flags & WORKER_NOT_RUNNING) &&
962 !(worker->flags & WORKER_NOT_RUNNING)) {
963 atomic_dec(&pool->nr_running);
966 worker->flags |= flags;
970 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
972 * @flags: flags to clear
974 * Clear @flags in @worker->flags and adjust nr_running accordingly.
977 * spin_lock_irq(pool->lock)
979 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
981 struct worker_pool *pool = worker->pool;
982 unsigned int oflags = worker->flags;
984 WARN_ON_ONCE(worker->task != current);
986 worker->flags &= ~flags;
989 * If transitioning out of NOT_RUNNING, increment nr_running. Note
990 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
991 * of multiple flags, not a single flag.
993 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
994 if (!(worker->flags & WORKER_NOT_RUNNING))
995 atomic_inc(&pool->nr_running);
999 * find_worker_executing_work - find worker which is executing a work
1000 * @pool: pool of interest
1001 * @work: work to find worker for
1003 * Find a worker which is executing @work on @pool by searching
1004 * @pool->busy_hash which is keyed by the address of @work. For a worker
1005 * to match, its current execution should match the address of @work and
1006 * its work function. This is to avoid unwanted dependency between
1007 * unrelated work executions through a work item being recycled while still
1010 * This is a bit tricky. A work item may be freed once its execution
1011 * starts and nothing prevents the freed area from being recycled for
1012 * another work item. If the same work item address ends up being reused
1013 * before the original execution finishes, workqueue will identify the
1014 * recycled work item as currently executing and make it wait until the
1015 * current execution finishes, introducing an unwanted dependency.
1017 * This function checks the work item address and work function to avoid
1018 * false positives. Note that this isn't complete as one may construct a
1019 * work function which can introduce dependency onto itself through a
1020 * recycled work item. Well, if somebody wants to shoot oneself in the
1021 * foot that badly, there's only so much we can do, and if such deadlock
1022 * actually occurs, it should be easy to locate the culprit work function.
1025 * spin_lock_irq(pool->lock).
1028 * Pointer to worker which is executing @work if found, %NULL
1031 static struct worker *find_worker_executing_work(struct worker_pool *pool,
1032 struct work_struct *work)
1034 struct worker *worker;
1036 hash_for_each_possible(pool->busy_hash, worker, hentry,
1037 (unsigned long)work)
1038 if (worker->current_work == work &&
1039 worker->current_func == work->func)
1046 * move_linked_works - move linked works to a list
1047 * @work: start of series of works to be scheduled
1048 * @head: target list to append @work to
1049 * @nextp: out parameter for nested worklist walking
1051 * Schedule linked works starting from @work to @head. Work series to
1052 * be scheduled starts at @work and includes any consecutive work with
1053 * WORK_STRUCT_LINKED set in its predecessor.
1055 * If @nextp is not NULL, it's updated to point to the next work of
1056 * the last scheduled work. This allows move_linked_works() to be
1057 * nested inside outer list_for_each_entry_safe().
1060 * spin_lock_irq(pool->lock).
1062 static void move_linked_works(struct work_struct *work, struct list_head *head,
1063 struct work_struct **nextp)
1065 struct work_struct *n;
1068 * Linked worklist will always end before the end of the list,
1069 * use NULL for list head.
1071 list_for_each_entry_safe_from(work, n, NULL, entry) {
1072 list_move_tail(&work->entry, head);
1073 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1078 * If we're already inside safe list traversal and have moved
1079 * multiple works to the scheduled queue, the next position
1080 * needs to be updated.
1087 * get_pwq - get an extra reference on the specified pool_workqueue
1088 * @pwq: pool_workqueue to get
1090 * Obtain an extra reference on @pwq. The caller should guarantee that
1091 * @pwq has positive refcnt and be holding the matching pool->lock.
1093 static void get_pwq(struct pool_workqueue *pwq)
1095 lockdep_assert_held(&pwq->pool->lock);
1096 WARN_ON_ONCE(pwq->refcnt <= 0);
1101 * put_pwq - put a pool_workqueue reference
1102 * @pwq: pool_workqueue to put
1104 * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
1105 * destruction. The caller should be holding the matching pool->lock.
1107 static void put_pwq(struct pool_workqueue *pwq)
1109 lockdep_assert_held(&pwq->pool->lock);
1110 if (likely(--pwq->refcnt))
1112 if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
1115 * @pwq can't be released under pool->lock, bounce to
1116 * pwq_unbound_release_workfn(). This never recurses on the same
1117 * pool->lock as this path is taken only for unbound workqueues and
1118 * the release work item is scheduled on a per-cpu workqueue. To
1119 * avoid lockdep warning, unbound pool->locks are given lockdep
1120 * subclass of 1 in get_unbound_pool().
1122 schedule_work(&pwq->unbound_release_work);
1126 * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1127 * @pwq: pool_workqueue to put (can be %NULL)
1129 * put_pwq() with locking. This function also allows %NULL @pwq.
1131 static void put_pwq_unlocked(struct pool_workqueue *pwq)
1135 * As both pwqs and pools are RCU protected, the
1136 * following lock operations are safe.
1139 local_spin_lock_irq(pendingb_lock, &pwq->pool->lock);
1141 local_spin_unlock_irq(pendingb_lock, &pwq->pool->lock);
1146 static void pwq_activate_delayed_work(struct work_struct *work)
1148 struct pool_workqueue *pwq = get_work_pwq(work);
1150 trace_workqueue_activate_work(work);
1151 move_linked_works(work, &pwq->pool->worklist, NULL);
1152 __clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
1156 static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
1158 struct work_struct *work = list_first_entry(&pwq->delayed_works,
1159 struct work_struct, entry);
1161 pwq_activate_delayed_work(work);
1165 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1166 * @pwq: pwq of interest
1167 * @color: color of work which left the queue
1169 * A work either has completed or is removed from pending queue,
1170 * decrement nr_in_flight of its pwq and handle workqueue flushing.
1173 * spin_lock_irq(pool->lock).
1175 static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
1177 /* uncolored work items don't participate in flushing or nr_active */
1178 if (color == WORK_NO_COLOR)
1181 pwq->nr_in_flight[color]--;
1184 if (!list_empty(&pwq->delayed_works)) {
1185 /* one down, submit a delayed one */
1186 if (pwq->nr_active < pwq->max_active)
1187 pwq_activate_first_delayed(pwq);
1190 /* is flush in progress and are we at the flushing tip? */
1191 if (likely(pwq->flush_color != color))
1194 /* are there still in-flight works? */
1195 if (pwq->nr_in_flight[color])
1198 /* this pwq is done, clear flush_color */
1199 pwq->flush_color = -1;
1202 * If this was the last pwq, wake up the first flusher. It
1203 * will handle the rest.
1205 if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1206 complete(&pwq->wq->first_flusher->done);
1212 * try_to_grab_pending - steal work item from worklist and disable irq
1213 * @work: work item to steal
1214 * @is_dwork: @work is a delayed_work
1215 * @flags: place to store irq state
1217 * Try to grab PENDING bit of @work. This function can handle @work in any
1218 * stable state - idle, on timer or on worklist.
1221 * 1 if @work was pending and we successfully stole PENDING
1222 * 0 if @work was idle and we claimed PENDING
1223 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1224 * -ENOENT if someone else is canceling @work, this state may persist
1225 * for arbitrarily long
1228 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1229 * interrupted while holding PENDING and @work off queue, irq must be
1230 * disabled on entry. This, combined with delayed_work->timer being
1231 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1233 * On successful return, >= 0, irq is disabled and the caller is
1234 * responsible for releasing it using local_irq_restore(*@flags).
1236 * This function is safe to call from any context including IRQ handler.
1238 static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1239 unsigned long *flags)
1241 struct worker_pool *pool;
1242 struct pool_workqueue *pwq;
1244 local_lock_irqsave(pendingb_lock, *flags);
1246 /* try to steal the timer if it exists */
1248 struct delayed_work *dwork = to_delayed_work(work);
1251 * dwork->timer is irqsafe. If del_timer() fails, it's
1252 * guaranteed that the timer is not queued anywhere and not
1253 * running on the local CPU.
1255 if (likely(del_timer(&dwork->timer)))
1259 /* try to claim PENDING the normal way */
1260 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1265 * The queueing is in progress, or it is already queued. Try to
1266 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1268 pool = get_work_pool(work);
1272 spin_lock(&pool->lock);
1274 * work->data is guaranteed to point to pwq only while the work
1275 * item is queued on pwq->wq, and both updating work->data to point
1276 * to pwq on queueing and to pool on dequeueing are done under
1277 * pwq->pool->lock. This in turn guarantees that, if work->data
1278 * points to pwq which is associated with a locked pool, the work
1279 * item is currently queued on that pool.
1281 pwq = get_work_pwq(work);
1282 if (pwq && pwq->pool == pool) {
1283 debug_work_deactivate(work);
1286 * A delayed work item cannot be grabbed directly because
1287 * it might have linked NO_COLOR work items which, if left
1288 * on the delayed_list, will confuse pwq->nr_active
1289 * management later on and cause stall. Make sure the work
1290 * item is activated before grabbing.
1292 if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1293 pwq_activate_delayed_work(work);
1295 list_del_init(&work->entry);
1296 pwq_dec_nr_in_flight(pwq, get_work_color(work));
1298 /* work->data points to pwq iff queued, point to pool */
1299 set_work_pool_and_keep_pending(work, pool->id);
1301 spin_unlock(&pool->lock);
1305 spin_unlock(&pool->lock);
1308 local_unlock_irqrestore(pendingb_lock, *flags);
1309 if (work_is_canceling(work))
1316 * insert_work - insert a work into a pool
1317 * @pwq: pwq @work belongs to
1318 * @work: work to insert
1319 * @head: insertion point
1320 * @extra_flags: extra WORK_STRUCT_* flags to set
1322 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
1323 * work_struct flags.
1326 * spin_lock_irq(pool->lock).
1328 static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1329 struct list_head *head, unsigned int extra_flags)
1331 struct worker_pool *pool = pwq->pool;
1333 /* we own @work, set data and link */
1334 set_work_pwq(work, pwq, extra_flags);
1335 list_add_tail(&work->entry, head);
1339 * Ensure either wq_worker_sleeping() sees the above
1340 * list_add_tail() or we see zero nr_running to avoid workers lying
1341 * around lazily while there are works to be processed.
1345 if (__need_more_worker(pool))
1346 wake_up_worker(pool);
1350 * Test whether @work is being queued from another work executing on the
1353 static bool is_chained_work(struct workqueue_struct *wq)
1355 struct worker *worker;
1357 worker = current_wq_worker();
1359 * Return %true iff I'm a worker execuing a work item on @wq. If
1360 * I'm @worker, it's safe to dereference it without locking.
1362 return worker && worker->current_pwq->wq == wq;
1365 static void __queue_work(int cpu, struct workqueue_struct *wq,
1366 struct work_struct *work)
1368 struct pool_workqueue *pwq;
1369 struct worker_pool *last_pool;
1370 struct list_head *worklist;
1371 unsigned int work_flags;
1372 unsigned int req_cpu = cpu;
1375 * While a work item is PENDING && off queue, a task trying to
1376 * steal the PENDING will busy-loop waiting for it to either get
1377 * queued or lose PENDING. Grabbing PENDING and queueing should
1378 * happen with IRQ disabled.
1380 WARN_ON_ONCE_NONRT(!irqs_disabled());
1382 debug_work_activate(work);
1384 /* if draining, only works from the same workqueue are allowed */
1385 if (unlikely(wq->flags & __WQ_DRAINING) &&
1386 WARN_ON_ONCE(!is_chained_work(wq)))
1391 if (req_cpu == WORK_CPU_UNBOUND)
1392 cpu = raw_smp_processor_id();
1394 /* pwq which will be used unless @work is executing elsewhere */
1395 if (!(wq->flags & WQ_UNBOUND))
1396 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1398 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1401 * If @work was previously on a different pool, it might still be
1402 * running there, in which case the work needs to be queued on that
1403 * pool to guarantee non-reentrancy.
1405 last_pool = get_work_pool(work);
1406 if (last_pool && last_pool != pwq->pool) {
1407 struct worker *worker;
1409 spin_lock(&last_pool->lock);
1411 worker = find_worker_executing_work(last_pool, work);
1413 if (worker && worker->current_pwq->wq == wq) {
1414 pwq = worker->current_pwq;
1416 /* meh... not running there, queue here */
1417 spin_unlock(&last_pool->lock);
1418 spin_lock(&pwq->pool->lock);
1421 spin_lock(&pwq->pool->lock);
1425 * pwq is determined and locked. For unbound pools, we could have
1426 * raced with pwq release and it could already be dead. If its
1427 * refcnt is zero, repeat pwq selection. Note that pwqs never die
1428 * without another pwq replacing it in the numa_pwq_tbl or while
1429 * work items are executing on it, so the retrying is guaranteed to
1430 * make forward-progress.
1432 if (unlikely(!pwq->refcnt)) {
1433 if (wq->flags & WQ_UNBOUND) {
1434 spin_unlock(&pwq->pool->lock);
1439 WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
1443 /* pwq determined, queue */
1444 trace_workqueue_queue_work(req_cpu, pwq, work);
1446 if (WARN_ON(!list_empty(&work->entry)))
1449 pwq->nr_in_flight[pwq->work_color]++;
1450 work_flags = work_color_to_flags(pwq->work_color);
1452 if (likely(pwq->nr_active < pwq->max_active)) {
1453 trace_workqueue_activate_work(work);
1455 worklist = &pwq->pool->worklist;
1457 work_flags |= WORK_STRUCT_DELAYED;
1458 worklist = &pwq->delayed_works;
1461 insert_work(pwq, work, worklist, work_flags);
1464 spin_unlock(&pwq->pool->lock);
1469 * queue_work_on - queue work on specific cpu
1470 * @cpu: CPU number to execute work on
1471 * @wq: workqueue to use
1472 * @work: work to queue
1474 * We queue the work to a specific CPU, the caller must ensure it
1477 * Return: %false if @work was already on a queue, %true otherwise.
1479 bool queue_work_on(int cpu, struct workqueue_struct *wq,
1480 struct work_struct *work)
1483 unsigned long flags;
1485 local_lock_irqsave(pendingb_lock,flags);
1487 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1488 __queue_work(cpu, wq, work);
1492 local_unlock_irqrestore(pendingb_lock, flags);
1495 EXPORT_SYMBOL(queue_work_on);
1497 void delayed_work_timer_fn(unsigned long __data)
1499 struct delayed_work *dwork = (struct delayed_work *)__data;
1501 /* should have been called from irqsafe timer with irq already off */
1502 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
1504 EXPORT_SYMBOL(delayed_work_timer_fn);
1506 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
1507 struct delayed_work *dwork, unsigned long delay)
1509 struct timer_list *timer = &dwork->timer;
1510 struct work_struct *work = &dwork->work;
1512 WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
1513 timer->data != (unsigned long)dwork);
1514 WARN_ON_ONCE(timer_pending(timer));
1515 WARN_ON_ONCE(!list_empty(&work->entry));
1518 * If @delay is 0, queue @dwork->work immediately. This is for
1519 * both optimization and correctness. The earliest @timer can
1520 * expire is on the closest next tick and delayed_work users depend
1521 * on that there's no such delay when @delay is 0.
1524 __queue_work(cpu, wq, &dwork->work);
1528 timer_stats_timer_set_start_info(&dwork->timer);
1532 timer->expires = jiffies + delay;
1534 if (unlikely(cpu != WORK_CPU_UNBOUND))
1535 add_timer_on(timer, cpu);
1541 * queue_delayed_work_on - queue work on specific CPU after delay
1542 * @cpu: CPU number to execute work on
1543 * @wq: workqueue to use
1544 * @dwork: work to queue
1545 * @delay: number of jiffies to wait before queueing
1547 * Return: %false if @work was already on a queue, %true otherwise. If
1548 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1551 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1552 struct delayed_work *dwork, unsigned long delay)
1554 struct work_struct *work = &dwork->work;
1556 unsigned long flags;
1558 /* read the comment in __queue_work() */
1559 local_lock_irqsave(pendingb_lock, flags);
1561 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1562 __queue_delayed_work(cpu, wq, dwork, delay);
1566 local_unlock_irqrestore(pendingb_lock, flags);
1569 EXPORT_SYMBOL(queue_delayed_work_on);
1572 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1573 * @cpu: CPU number to execute work on
1574 * @wq: workqueue to use
1575 * @dwork: work to queue
1576 * @delay: number of jiffies to wait before queueing
1578 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1579 * modify @dwork's timer so that it expires after @delay. If @delay is
1580 * zero, @work is guaranteed to be scheduled immediately regardless of its
1583 * Return: %false if @dwork was idle and queued, %true if @dwork was
1584 * pending and its timer was modified.
1586 * This function is safe to call from any context including IRQ handler.
1587 * See try_to_grab_pending() for details.
1589 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
1590 struct delayed_work *dwork, unsigned long delay)
1592 unsigned long flags;
1596 ret = try_to_grab_pending(&dwork->work, true, &flags);
1597 } while (unlikely(ret == -EAGAIN));
1599 if (likely(ret >= 0)) {
1600 __queue_delayed_work(cpu, wq, dwork, delay);
1601 local_unlock_irqrestore(pendingb_lock, flags);
1604 /* -ENOENT from try_to_grab_pending() becomes %true */
1607 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
1610 * worker_enter_idle - enter idle state
1611 * @worker: worker which is entering idle state
1613 * @worker is entering idle state. Update stats and idle timer if
1617 * spin_lock_irq(pool->lock).
1619 static void worker_enter_idle(struct worker *worker)
1621 struct worker_pool *pool = worker->pool;
1623 if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
1624 WARN_ON_ONCE(!list_empty(&worker->entry) &&
1625 (worker->hentry.next || worker->hentry.pprev)))
1628 /* can't use worker_set_flags(), also called from create_worker() */
1629 worker->flags |= WORKER_IDLE;
1631 worker->last_active = jiffies;
1633 /* idle_list is LIFO */
1634 rt_lock_idle_list(pool);
1635 list_add(&worker->entry, &pool->idle_list);
1636 rt_unlock_idle_list(pool);
1638 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1639 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1642 * Sanity check nr_running. Because wq_unbind_fn() releases
1643 * pool->lock between setting %WORKER_UNBOUND and zapping
1644 * nr_running, the warning may trigger spuriously. Check iff
1645 * unbind is not in progress.
1647 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1648 pool->nr_workers == pool->nr_idle &&
1649 atomic_read(&pool->nr_running));
1653 * worker_leave_idle - leave idle state
1654 * @worker: worker which is leaving idle state
1656 * @worker is leaving idle state. Update stats.
1659 * spin_lock_irq(pool->lock).
1661 static void worker_leave_idle(struct worker *worker)
1663 struct worker_pool *pool = worker->pool;
1665 if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
1667 worker_clr_flags(worker, WORKER_IDLE);
1669 rt_lock_idle_list(pool);
1670 list_del_init(&worker->entry);
1671 rt_unlock_idle_list(pool);
1674 static struct worker *alloc_worker(int node)
1676 struct worker *worker;
1678 worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
1680 INIT_LIST_HEAD(&worker->entry);
1681 INIT_LIST_HEAD(&worker->scheduled);
1682 INIT_LIST_HEAD(&worker->node);
1683 /* on creation a worker is in !idle && prep state */
1684 worker->flags = WORKER_PREP;
1690 * worker_attach_to_pool() - attach a worker to a pool
1691 * @worker: worker to be attached
1692 * @pool: the target pool
1694 * Attach @worker to @pool. Once attached, the %WORKER_UNBOUND flag and
1695 * cpu-binding of @worker are kept coordinated with the pool across
1698 static void worker_attach_to_pool(struct worker *worker,
1699 struct worker_pool *pool)
1701 mutex_lock(&pool->attach_mutex);
1704 * set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
1705 * online CPUs. It'll be re-applied when any of the CPUs come up.
1707 set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
1710 * The pool->attach_mutex ensures %POOL_DISASSOCIATED remains
1711 * stable across this function. See the comments above the
1712 * flag definition for details.
1714 if (pool->flags & POOL_DISASSOCIATED)
1715 worker->flags |= WORKER_UNBOUND;
1717 list_add_tail(&worker->node, &pool->workers);
1719 mutex_unlock(&pool->attach_mutex);
1723 * worker_detach_from_pool() - detach a worker from its pool
1724 * @worker: worker which is attached to its pool
1725 * @pool: the pool @worker is attached to
1727 * Undo the attaching which had been done in worker_attach_to_pool(). The
1728 * caller worker shouldn't access to the pool after detached except it has
1729 * other reference to the pool.
1731 static void worker_detach_from_pool(struct worker *worker,
1732 struct worker_pool *pool)
1734 struct completion *detach_completion = NULL;
1736 mutex_lock(&pool->attach_mutex);
1737 list_del(&worker->node);
1738 if (list_empty(&pool->workers))
1739 detach_completion = pool->detach_completion;
1740 mutex_unlock(&pool->attach_mutex);
1742 /* clear leftover flags without pool->lock after it is detached */
1743 worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
1745 if (detach_completion)
1746 complete(detach_completion);
1750 * create_worker - create a new workqueue worker
1751 * @pool: pool the new worker will belong to
1753 * Create and start a new worker which is attached to @pool.
1756 * Might sleep. Does GFP_KERNEL allocations.
1759 * Pointer to the newly created worker.
1761 static struct worker *create_worker(struct worker_pool *pool)
1763 struct worker *worker = NULL;
1767 /* ID is needed to determine kthread name */
1768 id = ida_simple_get(&pool->worker_ida, 0, 0, GFP_KERNEL);
1772 worker = alloc_worker(pool->node);
1776 worker->pool = pool;
1780 snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
1781 pool->attrs->nice < 0 ? "H" : "");
1783 snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
1785 worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
1786 "kworker/%s", id_buf);
1787 if (IS_ERR(worker->task))
1790 set_user_nice(worker->task, pool->attrs->nice);
1791 kthread_bind_mask(worker->task, pool->attrs->cpumask);
1793 /* successful, attach the worker to the pool */
1794 worker_attach_to_pool(worker, pool);
1796 /* start the newly created worker */
1797 spin_lock_irq(&pool->lock);
1798 worker->pool->nr_workers++;
1799 worker_enter_idle(worker);
1800 wake_up_process(worker->task);
1801 spin_unlock_irq(&pool->lock);
1807 ida_simple_remove(&pool->worker_ida, id);
1813 * destroy_worker - destroy a workqueue worker
1814 * @worker: worker to be destroyed
1816 * Destroy @worker and adjust @pool stats accordingly. The worker should
1820 * spin_lock_irq(pool->lock).
1822 static void destroy_worker(struct worker *worker)
1824 struct worker_pool *pool = worker->pool;
1826 lockdep_assert_held(&pool->lock);
1828 /* sanity check frenzy */
1829 if (WARN_ON(worker->current_work) ||
1830 WARN_ON(!list_empty(&worker->scheduled)) ||
1831 WARN_ON(!(worker->flags & WORKER_IDLE)))
1837 rt_lock_idle_list(pool);
1838 list_del_init(&worker->entry);
1839 rt_unlock_idle_list(pool);
1840 worker->flags |= WORKER_DIE;
1841 wake_up_process(worker->task);
1844 static void idle_worker_timeout(unsigned long __pool)
1846 struct worker_pool *pool = (void *)__pool;
1848 spin_lock_irq(&pool->lock);
1850 while (too_many_workers(pool)) {
1851 struct worker *worker;
1852 unsigned long expires;
1854 /* idle_list is kept in LIFO order, check the last one */
1855 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1856 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1858 if (time_before(jiffies, expires)) {
1859 mod_timer(&pool->idle_timer, expires);
1863 destroy_worker(worker);
1866 spin_unlock_irq(&pool->lock);
1869 static void send_mayday(struct work_struct *work)
1871 struct pool_workqueue *pwq = get_work_pwq(work);
1872 struct workqueue_struct *wq = pwq->wq;
1874 lockdep_assert_held(&wq_mayday_lock);
1879 /* mayday mayday mayday */
1880 if (list_empty(&pwq->mayday_node)) {
1882 * If @pwq is for an unbound wq, its base ref may be put at
1883 * any time due to an attribute change. Pin @pwq until the
1884 * rescuer is done with it.
1887 list_add_tail(&pwq->mayday_node, &wq->maydays);
1888 wake_up_process(wq->rescuer->task);
1892 static void pool_mayday_timeout(unsigned long __pool)
1894 struct worker_pool *pool = (void *)__pool;
1895 struct work_struct *work;
1897 spin_lock_irq(&pool->lock);
1898 spin_lock(&wq_mayday_lock); /* for wq->maydays */
1900 if (need_to_create_worker(pool)) {
1902 * We've been trying to create a new worker but
1903 * haven't been successful. We might be hitting an
1904 * allocation deadlock. Send distress signals to
1907 list_for_each_entry(work, &pool->worklist, entry)
1911 spin_unlock(&wq_mayday_lock);
1912 spin_unlock_irq(&pool->lock);
1914 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1918 * maybe_create_worker - create a new worker if necessary
1919 * @pool: pool to create a new worker for
1921 * Create a new worker for @pool if necessary. @pool is guaranteed to
1922 * have at least one idle worker on return from this function. If
1923 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1924 * sent to all rescuers with works scheduled on @pool to resolve
1925 * possible allocation deadlock.
1927 * On return, need_to_create_worker() is guaranteed to be %false and
1928 * may_start_working() %true.
1931 * spin_lock_irq(pool->lock) which may be released and regrabbed
1932 * multiple times. Does GFP_KERNEL allocations. Called only from
1935 static void maybe_create_worker(struct worker_pool *pool)
1936 __releases(&pool->lock)
1937 __acquires(&pool->lock)
1940 spin_unlock_irq(&pool->lock);
1942 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1943 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1946 if (create_worker(pool) || !need_to_create_worker(pool))
1949 schedule_timeout_interruptible(CREATE_COOLDOWN);
1951 if (!need_to_create_worker(pool))
1955 del_timer_sync(&pool->mayday_timer);
1956 spin_lock_irq(&pool->lock);
1958 * This is necessary even after a new worker was just successfully
1959 * created as @pool->lock was dropped and the new worker might have
1960 * already become busy.
1962 if (need_to_create_worker(pool))
1967 * manage_workers - manage worker pool
1970 * Assume the manager role and manage the worker pool @worker belongs
1971 * to. At any given time, there can be only zero or one manager per
1972 * pool. The exclusion is handled automatically by this function.
1974 * The caller can safely start processing works on false return. On
1975 * true return, it's guaranteed that need_to_create_worker() is false
1976 * and may_start_working() is true.
1979 * spin_lock_irq(pool->lock) which may be released and regrabbed
1980 * multiple times. Does GFP_KERNEL allocations.
1983 * %false if the pool doesn't need management and the caller can safely
1984 * start processing works, %true if management function was performed and
1985 * the conditions that the caller verified before calling the function may
1986 * no longer be true.
1988 static bool manage_workers(struct worker *worker)
1990 struct worker_pool *pool = worker->pool;
1993 * Anyone who successfully grabs manager_arb wins the arbitration
1994 * and becomes the manager. mutex_trylock() on pool->manager_arb
1995 * failure while holding pool->lock reliably indicates that someone
1996 * else is managing the pool and the worker which failed trylock
1997 * can proceed to executing work items. This means that anyone
1998 * grabbing manager_arb is responsible for actually performing
1999 * manager duties. If manager_arb is grabbed and released without
2000 * actual management, the pool may stall indefinitely.
2002 if (!mutex_trylock(&pool->manager_arb))
2004 pool->manager = worker;
2006 maybe_create_worker(pool);
2008 pool->manager = NULL;
2009 mutex_unlock(&pool->manager_arb);
2014 * process_one_work - process single work
2016 * @work: work to process
2018 * Process @work. This function contains all the logics necessary to
2019 * process a single work including synchronization against and
2020 * interaction with other workers on the same cpu, queueing and
2021 * flushing. As long as context requirement is met, any worker can
2022 * call this function to process a work.
2025 * spin_lock_irq(pool->lock) which is released and regrabbed.
2027 static void process_one_work(struct worker *worker, struct work_struct *work)
2028 __releases(&pool->lock)
2029 __acquires(&pool->lock)
2031 struct pool_workqueue *pwq = get_work_pwq(work);
2032 struct worker_pool *pool = worker->pool;
2033 bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
2035 struct worker *collision;
2036 #ifdef CONFIG_LOCKDEP
2038 * It is permissible to free the struct work_struct from
2039 * inside the function that is called from it, this we need to
2040 * take into account for lockdep too. To avoid bogus "held
2041 * lock freed" warnings as well as problems when looking into
2042 * work->lockdep_map, make a copy and use that here.
2044 struct lockdep_map lockdep_map;
2046 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
2048 /* ensure we're on the correct CPU */
2049 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2050 raw_smp_processor_id() != pool->cpu);
2053 * A single work shouldn't be executed concurrently by
2054 * multiple workers on a single cpu. Check whether anyone is
2055 * already processing the work. If so, defer the work to the
2056 * currently executing one.
2058 collision = find_worker_executing_work(pool, work);
2059 if (unlikely(collision)) {
2060 move_linked_works(work, &collision->scheduled, NULL);
2064 /* claim and dequeue */
2065 debug_work_deactivate(work);
2066 hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2067 worker->current_work = work;
2068 worker->current_func = work->func;
2069 worker->current_pwq = pwq;
2070 work_color = get_work_color(work);
2072 list_del_init(&work->entry);
2075 * CPU intensive works don't participate in concurrency management.
2076 * They're the scheduler's responsibility. This takes @worker out
2077 * of concurrency management and the next code block will chain
2078 * execution of the pending work items.
2080 if (unlikely(cpu_intensive))
2081 worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2084 * Wake up another worker if necessary. The condition is always
2085 * false for normal per-cpu workers since nr_running would always
2086 * be >= 1 at this point. This is used to chain execution of the
2087 * pending work items for WORKER_NOT_RUNNING workers such as the
2088 * UNBOUND and CPU_INTENSIVE ones.
2090 if (need_more_worker(pool))
2091 wake_up_worker(pool);
2094 * Record the last pool and clear PENDING which should be the last
2095 * update to @work. Also, do this inside @pool->lock so that
2096 * PENDING and queued state changes happen together while IRQ is
2099 set_work_pool_and_clear_pending(work, pool->id);
2101 spin_unlock_irq(&pool->lock);
2103 lock_map_acquire_read(&pwq->wq->lockdep_map);
2104 lock_map_acquire(&lockdep_map);
2105 trace_workqueue_execute_start(work);
2106 worker->current_func(work);
2108 * While we must be careful to not use "work" after this, the trace
2109 * point will only record its address.
2111 trace_workqueue_execute_end(work);
2112 lock_map_release(&lockdep_map);
2113 lock_map_release(&pwq->wq->lockdep_map);
2115 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2116 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2117 " last function: %pf\n",
2118 current->comm, preempt_count(), task_pid_nr(current),
2119 worker->current_func);
2120 debug_show_held_locks(current);
2125 * The following prevents a kworker from hogging CPU on !PREEMPT
2126 * kernels, where a requeueing work item waiting for something to
2127 * happen could deadlock with stop_machine as such work item could
2128 * indefinitely requeue itself while all other CPUs are trapped in
2129 * stop_machine. At the same time, report a quiescent RCU state so
2130 * the same condition doesn't freeze RCU.
2132 cond_resched_rcu_qs();
2134 spin_lock_irq(&pool->lock);
2136 /* clear cpu intensive status */
2137 if (unlikely(cpu_intensive))
2138 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2140 /* we're done with it, release */
2141 hash_del(&worker->hentry);
2142 worker->current_work = NULL;
2143 worker->current_func = NULL;
2144 worker->current_pwq = NULL;
2145 worker->desc_valid = false;
2146 pwq_dec_nr_in_flight(pwq, work_color);
2150 * process_scheduled_works - process scheduled works
2153 * Process all scheduled works. Please note that the scheduled list
2154 * may change while processing a work, so this function repeatedly
2155 * fetches a work from the top and executes it.
2158 * spin_lock_irq(pool->lock) which may be released and regrabbed
2161 static void process_scheduled_works(struct worker *worker)
2163 while (!list_empty(&worker->scheduled)) {
2164 struct work_struct *work = list_first_entry(&worker->scheduled,
2165 struct work_struct, entry);
2166 process_one_work(worker, work);
2171 * worker_thread - the worker thread function
2174 * The worker thread function. All workers belong to a worker_pool -
2175 * either a per-cpu one or dynamic unbound one. These workers process all
2176 * work items regardless of their specific target workqueue. The only
2177 * exception is work items which belong to workqueues with a rescuer which
2178 * will be explained in rescuer_thread().
2182 static int worker_thread(void *__worker)
2184 struct worker *worker = __worker;
2185 struct worker_pool *pool = worker->pool;
2187 /* tell the scheduler that this is a workqueue worker */
2188 worker->task->flags |= PF_WQ_WORKER;
2190 spin_lock_irq(&pool->lock);
2192 /* am I supposed to die? */
2193 if (unlikely(worker->flags & WORKER_DIE)) {
2194 spin_unlock_irq(&pool->lock);
2195 WARN_ON_ONCE(!list_empty(&worker->entry));
2196 worker->task->flags &= ~PF_WQ_WORKER;
2198 set_task_comm(worker->task, "kworker/dying");
2199 ida_simple_remove(&pool->worker_ida, worker->id);
2200 worker_detach_from_pool(worker, pool);
2205 worker_leave_idle(worker);
2207 /* no more worker necessary? */
2208 if (!need_more_worker(pool))
2211 /* do we need to manage? */
2212 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2216 * ->scheduled list can only be filled while a worker is
2217 * preparing to process a work or actually processing it.
2218 * Make sure nobody diddled with it while I was sleeping.
2220 WARN_ON_ONCE(!list_empty(&worker->scheduled));
2223 * Finish PREP stage. We're guaranteed to have at least one idle
2224 * worker or that someone else has already assumed the manager
2225 * role. This is where @worker starts participating in concurrency
2226 * management if applicable and concurrency management is restored
2227 * after being rebound. See rebind_workers() for details.
2229 worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2232 struct work_struct *work =
2233 list_first_entry(&pool->worklist,
2234 struct work_struct, entry);
2236 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2237 /* optimization path, not strictly necessary */
2238 process_one_work(worker, work);
2239 if (unlikely(!list_empty(&worker->scheduled)))
2240 process_scheduled_works(worker);
2242 move_linked_works(work, &worker->scheduled, NULL);
2243 process_scheduled_works(worker);
2245 } while (keep_working(pool));
2247 worker_set_flags(worker, WORKER_PREP);
2250 * pool->lock is held and there's no work to process and no need to
2251 * manage, sleep. Workers are woken up only while holding
2252 * pool->lock or from local cpu, so setting the current state
2253 * before releasing pool->lock is enough to prevent losing any
2256 worker_enter_idle(worker);
2257 __set_current_state(TASK_INTERRUPTIBLE);
2258 spin_unlock_irq(&pool->lock);
2264 * rescuer_thread - the rescuer thread function
2267 * Workqueue rescuer thread function. There's one rescuer for each
2268 * workqueue which has WQ_MEM_RECLAIM set.
2270 * Regular work processing on a pool may block trying to create a new
2271 * worker which uses GFP_KERNEL allocation which has slight chance of
2272 * developing into deadlock if some works currently on the same queue
2273 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2274 * the problem rescuer solves.
2276 * When such condition is possible, the pool summons rescuers of all
2277 * workqueues which have works queued on the pool and let them process
2278 * those works so that forward progress can be guaranteed.
2280 * This should happen rarely.
2284 static int rescuer_thread(void *__rescuer)
2286 struct worker *rescuer = __rescuer;
2287 struct workqueue_struct *wq = rescuer->rescue_wq;
2288 struct list_head *scheduled = &rescuer->scheduled;
2291 set_user_nice(current, RESCUER_NICE_LEVEL);
2294 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2295 * doesn't participate in concurrency management.
2297 rescuer->task->flags |= PF_WQ_WORKER;
2299 set_current_state(TASK_INTERRUPTIBLE);
2302 * By the time the rescuer is requested to stop, the workqueue
2303 * shouldn't have any work pending, but @wq->maydays may still have
2304 * pwq(s) queued. This can happen by non-rescuer workers consuming
2305 * all the work items before the rescuer got to them. Go through
2306 * @wq->maydays processing before acting on should_stop so that the
2307 * list is always empty on exit.
2309 should_stop = kthread_should_stop();
2311 /* see whether any pwq is asking for help */
2312 spin_lock_irq(&wq_mayday_lock);
2314 while (!list_empty(&wq->maydays)) {
2315 struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2316 struct pool_workqueue, mayday_node);
2317 struct worker_pool *pool = pwq->pool;
2318 struct work_struct *work, *n;
2320 __set_current_state(TASK_RUNNING);
2321 list_del_init(&pwq->mayday_node);
2323 spin_unlock_irq(&wq_mayday_lock);
2325 worker_attach_to_pool(rescuer, pool);
2327 spin_lock_irq(&pool->lock);
2328 rescuer->pool = pool;
2331 * Slurp in all works issued via this workqueue and
2334 WARN_ON_ONCE(!list_empty(scheduled));
2335 list_for_each_entry_safe(work, n, &pool->worklist, entry)
2336 if (get_work_pwq(work) == pwq)
2337 move_linked_works(work, scheduled, &n);
2339 if (!list_empty(scheduled)) {
2340 process_scheduled_works(rescuer);
2343 * The above execution of rescued work items could
2344 * have created more to rescue through
2345 * pwq_activate_first_delayed() or chained
2346 * queueing. Let's put @pwq back on mayday list so
2347 * that such back-to-back work items, which may be
2348 * being used to relieve memory pressure, don't
2349 * incur MAYDAY_INTERVAL delay inbetween.
2351 if (need_to_create_worker(pool)) {
2352 spin_lock(&wq_mayday_lock);
2354 list_move_tail(&pwq->mayday_node, &wq->maydays);
2355 spin_unlock(&wq_mayday_lock);
2360 * Put the reference grabbed by send_mayday(). @pool won't
2361 * go away while we're still attached to it.
2366 * Leave this pool. If need_more_worker() is %true, notify a
2367 * regular worker; otherwise, we end up with 0 concurrency
2368 * and stalling the execution.
2370 if (need_more_worker(pool))
2371 wake_up_worker(pool);
2373 rescuer->pool = NULL;
2374 spin_unlock_irq(&pool->lock);
2376 worker_detach_from_pool(rescuer, pool);
2378 spin_lock_irq(&wq_mayday_lock);
2381 spin_unlock_irq(&wq_mayday_lock);
2384 __set_current_state(TASK_RUNNING);
2385 rescuer->task->flags &= ~PF_WQ_WORKER;
2389 /* rescuers should never participate in concurrency management */
2390 WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2396 struct work_struct work;
2397 struct completion done;
2398 struct task_struct *task; /* purely informational */
2401 static void wq_barrier_func(struct work_struct *work)
2403 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2404 complete(&barr->done);
2408 * insert_wq_barrier - insert a barrier work
2409 * @pwq: pwq to insert barrier into
2410 * @barr: wq_barrier to insert
2411 * @target: target work to attach @barr to
2412 * @worker: worker currently executing @target, NULL if @target is not executing
2414 * @barr is linked to @target such that @barr is completed only after
2415 * @target finishes execution. Please note that the ordering
2416 * guarantee is observed only with respect to @target and on the local
2419 * Currently, a queued barrier can't be canceled. This is because
2420 * try_to_grab_pending() can't determine whether the work to be
2421 * grabbed is at the head of the queue and thus can't clear LINKED
2422 * flag of the previous work while there must be a valid next work
2423 * after a work with LINKED flag set.
2425 * Note that when @worker is non-NULL, @target may be modified
2426 * underneath us, so we can't reliably determine pwq from @target.
2429 * spin_lock_irq(pool->lock).
2431 static void insert_wq_barrier(struct pool_workqueue *pwq,
2432 struct wq_barrier *barr,
2433 struct work_struct *target, struct worker *worker)
2435 struct list_head *head;
2436 unsigned int linked = 0;
2439 * debugobject calls are safe here even with pool->lock locked
2440 * as we know for sure that this will not trigger any of the
2441 * checks and call back into the fixup functions where we
2444 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2445 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2446 init_completion(&barr->done);
2447 barr->task = current;
2450 * If @target is currently being executed, schedule the
2451 * barrier to the worker; otherwise, put it after @target.
2454 head = worker->scheduled.next;
2456 unsigned long *bits = work_data_bits(target);
2458 head = target->entry.next;
2459 /* there can already be other linked works, inherit and set */
2460 linked = *bits & WORK_STRUCT_LINKED;
2461 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2464 debug_work_activate(&barr->work);
2465 insert_work(pwq, &barr->work, head,
2466 work_color_to_flags(WORK_NO_COLOR) | linked);
2470 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
2471 * @wq: workqueue being flushed
2472 * @flush_color: new flush color, < 0 for no-op
2473 * @work_color: new work color, < 0 for no-op
2475 * Prepare pwqs for workqueue flushing.
2477 * If @flush_color is non-negative, flush_color on all pwqs should be
2478 * -1. If no pwq has in-flight commands at the specified color, all
2479 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
2480 * has in flight commands, its pwq->flush_color is set to
2481 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
2482 * wakeup logic is armed and %true is returned.
2484 * The caller should have initialized @wq->first_flusher prior to
2485 * calling this function with non-negative @flush_color. If
2486 * @flush_color is negative, no flush color update is done and %false
2489 * If @work_color is non-negative, all pwqs should have the same
2490 * work_color which is previous to @work_color and all will be
2491 * advanced to @work_color.
2494 * mutex_lock(wq->mutex).
2497 * %true if @flush_color >= 0 and there's something to flush. %false
2500 static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
2501 int flush_color, int work_color)
2504 struct pool_workqueue *pwq;
2506 if (flush_color >= 0) {
2507 WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2508 atomic_set(&wq->nr_pwqs_to_flush, 1);
2511 for_each_pwq(pwq, wq) {
2512 struct worker_pool *pool = pwq->pool;
2514 spin_lock_irq(&pool->lock);
2516 if (flush_color >= 0) {
2517 WARN_ON_ONCE(pwq->flush_color != -1);
2519 if (pwq->nr_in_flight[flush_color]) {
2520 pwq->flush_color = flush_color;
2521 atomic_inc(&wq->nr_pwqs_to_flush);
2526 if (work_color >= 0) {
2527 WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2528 pwq->work_color = work_color;
2531 spin_unlock_irq(&pool->lock);
2534 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
2535 complete(&wq->first_flusher->done);
2541 * flush_workqueue - ensure that any scheduled work has run to completion.
2542 * @wq: workqueue to flush
2544 * This function sleeps until all work items which were queued on entry
2545 * have finished execution, but it is not livelocked by new incoming ones.
2547 void flush_workqueue(struct workqueue_struct *wq)
2549 struct wq_flusher this_flusher = {
2550 .list = LIST_HEAD_INIT(this_flusher.list),
2552 .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
2556 lock_map_acquire(&wq->lockdep_map);
2557 lock_map_release(&wq->lockdep_map);
2559 mutex_lock(&wq->mutex);
2562 * Start-to-wait phase
2564 next_color = work_next_color(wq->work_color);
2566 if (next_color != wq->flush_color) {
2568 * Color space is not full. The current work_color
2569 * becomes our flush_color and work_color is advanced
2572 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
2573 this_flusher.flush_color = wq->work_color;
2574 wq->work_color = next_color;
2576 if (!wq->first_flusher) {
2577 /* no flush in progress, become the first flusher */
2578 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2580 wq->first_flusher = &this_flusher;
2582 if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
2584 /* nothing to flush, done */
2585 wq->flush_color = next_color;
2586 wq->first_flusher = NULL;
2591 WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
2592 list_add_tail(&this_flusher.list, &wq->flusher_queue);
2593 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2597 * Oops, color space is full, wait on overflow queue.
2598 * The next flush completion will assign us
2599 * flush_color and transfer to flusher_queue.
2601 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2604 mutex_unlock(&wq->mutex);
2606 wait_for_completion(&this_flusher.done);
2609 * Wake-up-and-cascade phase
2611 * First flushers are responsible for cascading flushes and
2612 * handling overflow. Non-first flushers can simply return.
2614 if (wq->first_flusher != &this_flusher)
2617 mutex_lock(&wq->mutex);
2619 /* we might have raced, check again with mutex held */
2620 if (wq->first_flusher != &this_flusher)
2623 wq->first_flusher = NULL;
2625 WARN_ON_ONCE(!list_empty(&this_flusher.list));
2626 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2629 struct wq_flusher *next, *tmp;
2631 /* complete all the flushers sharing the current flush color */
2632 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2633 if (next->flush_color != wq->flush_color)
2635 list_del_init(&next->list);
2636 complete(&next->done);
2639 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
2640 wq->flush_color != work_next_color(wq->work_color));
2642 /* this flush_color is finished, advance by one */
2643 wq->flush_color = work_next_color(wq->flush_color);
2645 /* one color has been freed, handle overflow queue */
2646 if (!list_empty(&wq->flusher_overflow)) {
2648 * Assign the same color to all overflowed
2649 * flushers, advance work_color and append to
2650 * flusher_queue. This is the start-to-wait
2651 * phase for these overflowed flushers.
2653 list_for_each_entry(tmp, &wq->flusher_overflow, list)
2654 tmp->flush_color = wq->work_color;
2656 wq->work_color = work_next_color(wq->work_color);
2658 list_splice_tail_init(&wq->flusher_overflow,
2659 &wq->flusher_queue);
2660 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2663 if (list_empty(&wq->flusher_queue)) {
2664 WARN_ON_ONCE(wq->flush_color != wq->work_color);
2669 * Need to flush more colors. Make the next flusher
2670 * the new first flusher and arm pwqs.
2672 WARN_ON_ONCE(wq->flush_color == wq->work_color);
2673 WARN_ON_ONCE(wq->flush_color != next->flush_color);
2675 list_del_init(&next->list);
2676 wq->first_flusher = next;
2678 if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
2682 * Meh... this color is already done, clear first
2683 * flusher and repeat cascading.
2685 wq->first_flusher = NULL;
2689 mutex_unlock(&wq->mutex);
2691 EXPORT_SYMBOL(flush_workqueue);
2694 * drain_workqueue - drain a workqueue
2695 * @wq: workqueue to drain
2697 * Wait until the workqueue becomes empty. While draining is in progress,
2698 * only chain queueing is allowed. IOW, only currently pending or running
2699 * work items on @wq can queue further work items on it. @wq is flushed
2700 * repeatedly until it becomes empty. The number of flushing is determined
2701 * by the depth of chaining and should be relatively short. Whine if it
2704 void drain_workqueue(struct workqueue_struct *wq)
2706 unsigned int flush_cnt = 0;
2707 struct pool_workqueue *pwq;
2710 * __queue_work() needs to test whether there are drainers, is much
2711 * hotter than drain_workqueue() and already looks at @wq->flags.
2712 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
2714 mutex_lock(&wq->mutex);
2715 if (!wq->nr_drainers++)
2716 wq->flags |= __WQ_DRAINING;
2717 mutex_unlock(&wq->mutex);
2719 flush_workqueue(wq);
2721 mutex_lock(&wq->mutex);
2723 for_each_pwq(pwq, wq) {
2726 spin_lock_irq(&pwq->pool->lock);
2727 drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
2728 spin_unlock_irq(&pwq->pool->lock);
2733 if (++flush_cnt == 10 ||
2734 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2735 pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
2736 wq->name, flush_cnt);
2738 mutex_unlock(&wq->mutex);
2742 if (!--wq->nr_drainers)
2743 wq->flags &= ~__WQ_DRAINING;
2744 mutex_unlock(&wq->mutex);
2746 EXPORT_SYMBOL_GPL(drain_workqueue);
2748 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2750 struct worker *worker = NULL;
2751 struct worker_pool *pool;
2752 struct pool_workqueue *pwq;
2757 pool = get_work_pool(work);
2763 spin_lock_irq(&pool->lock);
2764 /* see the comment in try_to_grab_pending() with the same code */
2765 pwq = get_work_pwq(work);
2767 if (unlikely(pwq->pool != pool))
2770 worker = find_worker_executing_work(pool, work);
2773 pwq = worker->current_pwq;
2776 insert_wq_barrier(pwq, barr, work, worker);
2777 spin_unlock_irq(&pool->lock);
2780 * If @max_active is 1 or rescuer is in use, flushing another work
2781 * item on the same workqueue may lead to deadlock. Make sure the
2782 * flusher is not running on the same workqueue by verifying write
2785 if (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)
2786 lock_map_acquire(&pwq->wq->lockdep_map);
2788 lock_map_acquire_read(&pwq->wq->lockdep_map);
2789 lock_map_release(&pwq->wq->lockdep_map);
2793 spin_unlock_irq(&pool->lock);
2799 * flush_work - wait for a work to finish executing the last queueing instance
2800 * @work: the work to flush
2802 * Wait until @work has finished execution. @work is guaranteed to be idle
2803 * on return if it hasn't been requeued since flush started.
2806 * %true if flush_work() waited for the work to finish execution,
2807 * %false if it was already idle.
2809 bool flush_work(struct work_struct *work)
2811 struct wq_barrier barr;
2813 lock_map_acquire(&work->lockdep_map);
2814 lock_map_release(&work->lockdep_map);
2816 if (start_flush_work(work, &barr)) {
2817 wait_for_completion(&barr.done);
2818 destroy_work_on_stack(&barr.work);
2824 EXPORT_SYMBOL_GPL(flush_work);
2828 struct work_struct *work;
2831 static int cwt_wakefn(wait_queue_t *wait, unsigned mode, int sync, void *key)
2833 struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
2835 if (cwait->work != key)
2837 return autoremove_wake_function(wait, mode, sync, key);
2840 static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2842 static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
2843 unsigned long flags;
2847 ret = try_to_grab_pending(work, is_dwork, &flags);
2849 * If someone else is already canceling, wait for it to
2850 * finish. flush_work() doesn't work for PREEMPT_NONE
2851 * because we may get scheduled between @work's completion
2852 * and the other canceling task resuming and clearing
2853 * CANCELING - flush_work() will return false immediately
2854 * as @work is no longer busy, try_to_grab_pending() will
2855 * return -ENOENT as @work is still being canceled and the
2856 * other canceling task won't be able to clear CANCELING as
2857 * we're hogging the CPU.
2859 * Let's wait for completion using a waitqueue. As this
2860 * may lead to the thundering herd problem, use a custom
2861 * wake function which matches @work along with exclusive
2864 if (unlikely(ret == -ENOENT)) {
2865 struct cwt_wait cwait;
2867 init_wait(&cwait.wait);
2868 cwait.wait.func = cwt_wakefn;
2871 prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
2872 TASK_UNINTERRUPTIBLE);
2873 if (work_is_canceling(work))
2875 finish_wait(&cancel_waitq, &cwait.wait);
2877 } while (unlikely(ret < 0));
2879 /* tell other tasks trying to grab @work to back off */
2880 mark_work_canceling(work);
2881 local_unlock_irqrestore(pendingb_lock, flags);
2884 clear_work_data(work);
2887 * Paired with prepare_to_wait() above so that either
2888 * waitqueue_active() is visible here or !work_is_canceling() is
2892 if (waitqueue_active(&cancel_waitq))
2893 __wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
2899 * cancel_work_sync - cancel a work and wait for it to finish
2900 * @work: the work to cancel
2902 * Cancel @work and wait for its execution to finish. This function
2903 * can be used even if the work re-queues itself or migrates to
2904 * another workqueue. On return from this function, @work is
2905 * guaranteed to be not pending or executing on any CPU.
2907 * cancel_work_sync(&delayed_work->work) must not be used for
2908 * delayed_work's. Use cancel_delayed_work_sync() instead.
2910 * The caller must ensure that the workqueue on which @work was last
2911 * queued can't be destroyed before this function returns.
2914 * %true if @work was pending, %false otherwise.
2916 bool cancel_work_sync(struct work_struct *work)
2918 return __cancel_work_timer(work, false);
2920 EXPORT_SYMBOL_GPL(cancel_work_sync);
2923 * flush_delayed_work - wait for a dwork to finish executing the last queueing
2924 * @dwork: the delayed work to flush
2926 * Delayed timer is cancelled and the pending work is queued for
2927 * immediate execution. Like flush_work(), this function only
2928 * considers the last queueing instance of @dwork.
2931 * %true if flush_work() waited for the work to finish execution,
2932 * %false if it was already idle.
2934 bool flush_delayed_work(struct delayed_work *dwork)
2936 local_lock_irq(pendingb_lock);
2937 if (del_timer_sync(&dwork->timer))
2938 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
2939 local_unlock_irq(pendingb_lock);
2940 return flush_work(&dwork->work);
2942 EXPORT_SYMBOL(flush_delayed_work);
2945 * cancel_delayed_work - cancel a delayed work
2946 * @dwork: delayed_work to cancel
2948 * Kill off a pending delayed_work.
2950 * Return: %true if @dwork was pending and canceled; %false if it wasn't
2954 * The work callback function may still be running on return, unless
2955 * it returns %true and the work doesn't re-arm itself. Explicitly flush or
2956 * use cancel_delayed_work_sync() to wait on it.
2958 * This function is safe to call from any context including IRQ handler.
2960 bool cancel_delayed_work(struct delayed_work *dwork)
2962 unsigned long flags;
2966 ret = try_to_grab_pending(&dwork->work, true, &flags);
2967 } while (unlikely(ret == -EAGAIN));
2969 if (unlikely(ret < 0))
2972 set_work_pool_and_clear_pending(&dwork->work,
2973 get_work_pool_id(&dwork->work));
2974 local_unlock_irqrestore(pendingb_lock, flags);
2977 EXPORT_SYMBOL(cancel_delayed_work);
2980 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2981 * @dwork: the delayed work cancel
2983 * This is cancel_work_sync() for delayed works.
2986 * %true if @dwork was pending, %false otherwise.
2988 bool cancel_delayed_work_sync(struct delayed_work *dwork)
2990 return __cancel_work_timer(&dwork->work, true);
2992 EXPORT_SYMBOL(cancel_delayed_work_sync);
2995 * schedule_on_each_cpu - execute a function synchronously on each online CPU
2996 * @func: the function to call
2998 * schedule_on_each_cpu() executes @func on each online CPU using the
2999 * system workqueue and blocks until all CPUs have completed.
3000 * schedule_on_each_cpu() is very slow.
3003 * 0 on success, -errno on failure.
3005 int schedule_on_each_cpu(work_func_t func)
3008 struct work_struct __percpu *works;
3010 works = alloc_percpu(struct work_struct);
3016 for_each_online_cpu(cpu) {
3017 struct work_struct *work = per_cpu_ptr(works, cpu);
3019 INIT_WORK(work, func);
3020 schedule_work_on(cpu, work);
3023 for_each_online_cpu(cpu)
3024 flush_work(per_cpu_ptr(works, cpu));
3032 * execute_in_process_context - reliably execute the routine with user context
3033 * @fn: the function to execute
3034 * @ew: guaranteed storage for the execute work structure (must
3035 * be available when the work executes)
3037 * Executes the function immediately if process context is available,
3038 * otherwise schedules the function for delayed execution.
3040 * Return: 0 - function was executed
3041 * 1 - function was scheduled for execution
3043 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
3045 if (!in_interrupt()) {
3050 INIT_WORK(&ew->work, fn);
3051 schedule_work(&ew->work);
3055 EXPORT_SYMBOL_GPL(execute_in_process_context);
3058 * free_workqueue_attrs - free a workqueue_attrs
3059 * @attrs: workqueue_attrs to free
3061 * Undo alloc_workqueue_attrs().
3063 void free_workqueue_attrs(struct workqueue_attrs *attrs)
3066 free_cpumask_var(attrs->cpumask);
3072 * alloc_workqueue_attrs - allocate a workqueue_attrs
3073 * @gfp_mask: allocation mask to use
3075 * Allocate a new workqueue_attrs, initialize with default settings and
3078 * Return: The allocated new workqueue_attr on success. %NULL on failure.
3080 struct workqueue_attrs *alloc_workqueue_attrs(gfp_t gfp_mask)
3082 struct workqueue_attrs *attrs;
3084 attrs = kzalloc(sizeof(*attrs), gfp_mask);
3087 if (!alloc_cpumask_var(&attrs->cpumask, gfp_mask))
3090 cpumask_copy(attrs->cpumask, cpu_possible_mask);
3093 free_workqueue_attrs(attrs);
3097 static void copy_workqueue_attrs(struct workqueue_attrs *to,
3098 const struct workqueue_attrs *from)
3100 to->nice = from->nice;
3101 cpumask_copy(to->cpumask, from->cpumask);
3103 * Unlike hash and equality test, this function doesn't ignore
3104 * ->no_numa as it is used for both pool and wq attrs. Instead,
3105 * get_unbound_pool() explicitly clears ->no_numa after copying.
3107 to->no_numa = from->no_numa;
3110 /* hash value of the content of @attr */
3111 static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
3115 hash = jhash_1word(attrs->nice, hash);
3116 hash = jhash(cpumask_bits(attrs->cpumask),
3117 BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
3121 /* content equality test */
3122 static bool wqattrs_equal(const struct workqueue_attrs *a,
3123 const struct workqueue_attrs *b)
3125 if (a->nice != b->nice)
3127 if (!cpumask_equal(a->cpumask, b->cpumask))
3133 * init_worker_pool - initialize a newly zalloc'd worker_pool
3134 * @pool: worker_pool to initialize
3136 * Initialize a newly zalloc'd @pool. It also allocates @pool->attrs.
3138 * Return: 0 on success, -errno on failure. Even on failure, all fields
3139 * inside @pool proper are initialized and put_unbound_pool() can be called
3140 * on @pool safely to release it.
3142 static int init_worker_pool(struct worker_pool *pool)
3144 spin_lock_init(&pool->lock);
3147 pool->node = NUMA_NO_NODE;
3148 pool->flags |= POOL_DISASSOCIATED;
3149 INIT_LIST_HEAD(&pool->worklist);
3150 INIT_LIST_HEAD(&pool->idle_list);
3151 hash_init(pool->busy_hash);
3153 init_timer_deferrable(&pool->idle_timer);
3154 pool->idle_timer.function = idle_worker_timeout;
3155 pool->idle_timer.data = (unsigned long)pool;
3157 setup_timer(&pool->mayday_timer, pool_mayday_timeout,
3158 (unsigned long)pool);
3160 mutex_init(&pool->manager_arb);
3161 mutex_init(&pool->attach_mutex);
3162 INIT_LIST_HEAD(&pool->workers);
3164 ida_init(&pool->worker_ida);
3165 INIT_HLIST_NODE(&pool->hash_node);
3168 /* shouldn't fail above this point */
3169 pool->attrs = alloc_workqueue_attrs(GFP_KERNEL);
3175 static void rcu_free_wq(struct rcu_head *rcu)
3177 struct workqueue_struct *wq =
3178 container_of(rcu, struct workqueue_struct, rcu);
3180 if (!(wq->flags & WQ_UNBOUND))
3181 free_percpu(wq->cpu_pwqs);
3183 free_workqueue_attrs(wq->unbound_attrs);
3189 static void rcu_free_pool(struct rcu_head *rcu)
3191 struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
3193 ida_destroy(&pool->worker_ida);
3194 free_workqueue_attrs(pool->attrs);
3199 * put_unbound_pool - put a worker_pool
3200 * @pool: worker_pool to put
3202 * Put @pool. If its refcnt reaches zero, it gets destroyed in RCU
3203 * safe manner. get_unbound_pool() calls this function on its failure path
3204 * and this function should be able to release pools which went through,
3205 * successfully or not, init_worker_pool().
3207 * Should be called with wq_pool_mutex held.
3209 static void put_unbound_pool(struct worker_pool *pool)
3211 DECLARE_COMPLETION_ONSTACK(detach_completion);
3212 struct worker *worker;
3214 lockdep_assert_held(&wq_pool_mutex);
3220 if (WARN_ON(!(pool->cpu < 0)) ||
3221 WARN_ON(!list_empty(&pool->worklist)))
3224 /* release id and unhash */
3226 idr_remove(&worker_pool_idr, pool->id);
3227 hash_del(&pool->hash_node);
3230 * Become the manager and destroy all workers. Grabbing
3231 * manager_arb prevents @pool's workers from blocking on
3234 mutex_lock(&pool->manager_arb);
3236 spin_lock_irq(&pool->lock);
3237 while ((worker = first_idle_worker(pool)))
3238 destroy_worker(worker);
3239 WARN_ON(pool->nr_workers || pool->nr_idle);
3240 spin_unlock_irq(&pool->lock);
3242 mutex_lock(&pool->attach_mutex);
3243 if (!list_empty(&pool->workers))
3244 pool->detach_completion = &detach_completion;
3245 mutex_unlock(&pool->attach_mutex);
3247 if (pool->detach_completion)
3248 wait_for_completion(pool->detach_completion);
3250 mutex_unlock(&pool->manager_arb);
3252 /* shut down the timers */
3253 del_timer_sync(&pool->idle_timer);
3254 del_timer_sync(&pool->mayday_timer);
3256 /* RCU protected to allow dereferences from get_work_pool() */
3257 call_rcu(&pool->rcu, rcu_free_pool);
3261 * get_unbound_pool - get a worker_pool with the specified attributes
3262 * @attrs: the attributes of the worker_pool to get
3264 * Obtain a worker_pool which has the same attributes as @attrs, bump the
3265 * reference count and return it. If there already is a matching
3266 * worker_pool, it will be used; otherwise, this function attempts to
3269 * Should be called with wq_pool_mutex held.
3271 * Return: On success, a worker_pool with the same attributes as @attrs.
3272 * On failure, %NULL.
3274 static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
3276 u32 hash = wqattrs_hash(attrs);
3277 struct worker_pool *pool;
3279 int target_node = NUMA_NO_NODE;
3281 lockdep_assert_held(&wq_pool_mutex);
3283 /* do we already have a matching pool? */
3284 hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
3285 if (wqattrs_equal(pool->attrs, attrs)) {
3291 /* if cpumask is contained inside a NUMA node, we belong to that node */
3292 if (wq_numa_enabled) {
3293 for_each_node(node) {
3294 if (cpumask_subset(attrs->cpumask,
3295 wq_numa_possible_cpumask[node])) {
3302 /* nope, create a new one */
3303 pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, target_node);
3304 if (!pool || init_worker_pool(pool) < 0)
3307 lockdep_set_subclass(&pool->lock, 1); /* see put_pwq() */
3308 copy_workqueue_attrs(pool->attrs, attrs);
3309 pool->node = target_node;
3312 * no_numa isn't a worker_pool attribute, always clear it. See
3313 * 'struct workqueue_attrs' comments for detail.
3315 pool->attrs->no_numa = false;
3317 if (worker_pool_assign_id(pool) < 0)
3320 /* create and start the initial worker */
3321 if (!create_worker(pool))
3325 hash_add(unbound_pool_hash, &pool->hash_node, hash);
3330 put_unbound_pool(pool);
3334 static void rcu_free_pwq(struct rcu_head *rcu)
3336 kmem_cache_free(pwq_cache,
3337 container_of(rcu, struct pool_workqueue, rcu));
3341 * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
3342 * and needs to be destroyed.
3344 static void pwq_unbound_release_workfn(struct work_struct *work)
3346 struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
3347 unbound_release_work);
3348 struct workqueue_struct *wq = pwq->wq;
3349 struct worker_pool *pool = pwq->pool;
3352 if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
3355 mutex_lock(&wq->mutex);
3356 list_del_rcu(&pwq->pwqs_node);
3357 is_last = list_empty(&wq->pwqs);
3358 mutex_unlock(&wq->mutex);
3360 mutex_lock(&wq_pool_mutex);
3361 put_unbound_pool(pool);
3362 mutex_unlock(&wq_pool_mutex);
3364 call_rcu(&pwq->rcu, rcu_free_pwq);
3367 * If we're the last pwq going away, @wq is already dead and no one
3368 * is gonna access it anymore. Schedule RCU free.
3371 call_rcu(&wq->rcu, rcu_free_wq);
3375 * pwq_adjust_max_active - update a pwq's max_active to the current setting
3376 * @pwq: target pool_workqueue
3378 * If @pwq isn't freezing, set @pwq->max_active to the associated
3379 * workqueue's saved_max_active and activate delayed work items
3380 * accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
3382 static void pwq_adjust_max_active(struct pool_workqueue *pwq)
3384 struct workqueue_struct *wq = pwq->wq;
3385 bool freezable = wq->flags & WQ_FREEZABLE;
3387 /* for @wq->saved_max_active */
3388 lockdep_assert_held(&wq->mutex);
3390 /* fast exit for non-freezable wqs */
3391 if (!freezable && pwq->max_active == wq->saved_max_active)
3394 spin_lock_irq(&pwq->pool->lock);
3397 * During [un]freezing, the caller is responsible for ensuring that
3398 * this function is called at least once after @workqueue_freezing
3399 * is updated and visible.
3401 if (!freezable || !workqueue_freezing) {
3402 pwq->max_active = wq->saved_max_active;
3404 while (!list_empty(&pwq->delayed_works) &&
3405 pwq->nr_active < pwq->max_active)
3406 pwq_activate_first_delayed(pwq);
3409 * Need to kick a worker after thawed or an unbound wq's
3410 * max_active is bumped. It's a slow path. Do it always.
3412 wake_up_worker(pwq->pool);
3414 pwq->max_active = 0;
3417 spin_unlock_irq(&pwq->pool->lock);
3420 /* initialize newly alloced @pwq which is associated with @wq and @pool */
3421 static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
3422 struct worker_pool *pool)
3424 BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3426 memset(pwq, 0, sizeof(*pwq));
3430 pwq->flush_color = -1;
3432 INIT_LIST_HEAD(&pwq->delayed_works);
3433 INIT_LIST_HEAD(&pwq->pwqs_node);
3434 INIT_LIST_HEAD(&pwq->mayday_node);
3435 INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
3438 /* sync @pwq with the current state of its associated wq and link it */
3439 static void link_pwq(struct pool_workqueue *pwq)
3441 struct workqueue_struct *wq = pwq->wq;
3443 lockdep_assert_held(&wq->mutex);
3445 /* may be called multiple times, ignore if already linked */
3446 if (!list_empty(&pwq->pwqs_node))
3449 /* set the matching work_color */
3450 pwq->work_color = wq->work_color;
3452 /* sync max_active to the current setting */
3453 pwq_adjust_max_active(pwq);
3456 list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
3459 /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
3460 static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
3461 const struct workqueue_attrs *attrs)
3463 struct worker_pool *pool;
3464 struct pool_workqueue *pwq;
3466 lockdep_assert_held(&wq_pool_mutex);
3468 pool = get_unbound_pool(attrs);
3472 pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
3474 put_unbound_pool(pool);
3478 init_pwq(pwq, wq, pool);
3483 * wq_calc_node_cpumask - calculate a wq_attrs' cpumask for the specified node
3484 * @attrs: the wq_attrs of the default pwq of the target workqueue
3485 * @node: the target NUMA node
3486 * @cpu_going_down: if >= 0, the CPU to consider as offline
3487 * @cpumask: outarg, the resulting cpumask
3489 * Calculate the cpumask a workqueue with @attrs should use on @node. If
3490 * @cpu_going_down is >= 0, that cpu is considered offline during
3491 * calculation. The result is stored in @cpumask.
3493 * If NUMA affinity is not enabled, @attrs->cpumask is always used. If
3494 * enabled and @node has online CPUs requested by @attrs, the returned
3495 * cpumask is the intersection of the possible CPUs of @node and
3498 * The caller is responsible for ensuring that the cpumask of @node stays
3501 * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
3504 static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
3505 int cpu_going_down, cpumask_t *cpumask)
3507 if (!wq_numa_enabled || attrs->no_numa)
3510 /* does @node have any online CPUs @attrs wants? */
3511 cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
3512 if (cpu_going_down >= 0)
3513 cpumask_clear_cpu(cpu_going_down, cpumask);
3515 if (cpumask_empty(cpumask))
3518 /* yeap, return possible CPUs in @node that @attrs wants */
3519 cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
3520 return !cpumask_equal(cpumask, attrs->cpumask);
3523 cpumask_copy(cpumask, attrs->cpumask);
3527 /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
3528 static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
3530 struct pool_workqueue *pwq)
3532 struct pool_workqueue *old_pwq;
3534 lockdep_assert_held(&wq_pool_mutex);
3535 lockdep_assert_held(&wq->mutex);
3537 /* link_pwq() can handle duplicate calls */
3540 old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
3541 rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
3545 /* context to store the prepared attrs & pwqs before applying */
3546 struct apply_wqattrs_ctx {
3547 struct workqueue_struct *wq; /* target workqueue */
3548 struct workqueue_attrs *attrs; /* attrs to apply */
3549 struct list_head list; /* queued for batching commit */
3550 struct pool_workqueue *dfl_pwq;
3551 struct pool_workqueue *pwq_tbl[];
3554 /* free the resources after success or abort */
3555 static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
3561 put_pwq_unlocked(ctx->pwq_tbl[node]);
3562 put_pwq_unlocked(ctx->dfl_pwq);
3564 free_workqueue_attrs(ctx->attrs);
3570 /* allocate the attrs and pwqs for later installation */
3571 static struct apply_wqattrs_ctx *
3572 apply_wqattrs_prepare(struct workqueue_struct *wq,
3573 const struct workqueue_attrs *attrs)
3575 struct apply_wqattrs_ctx *ctx;
3576 struct workqueue_attrs *new_attrs, *tmp_attrs;
3579 lockdep_assert_held(&wq_pool_mutex);
3581 ctx = kzalloc(sizeof(*ctx) + nr_node_ids * sizeof(ctx->pwq_tbl[0]),
3584 new_attrs = alloc_workqueue_attrs(GFP_KERNEL);
3585 tmp_attrs = alloc_workqueue_attrs(GFP_KERNEL);
3586 if (!ctx || !new_attrs || !tmp_attrs)
3590 * Calculate the attrs of the default pwq.
3591 * If the user configured cpumask doesn't overlap with the
3592 * wq_unbound_cpumask, we fallback to the wq_unbound_cpumask.
3594 copy_workqueue_attrs(new_attrs, attrs);
3595 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, wq_unbound_cpumask);
3596 if (unlikely(cpumask_empty(new_attrs->cpumask)))
3597 cpumask_copy(new_attrs->cpumask, wq_unbound_cpumask);
3600 * We may create multiple pwqs with differing cpumasks. Make a
3601 * copy of @new_attrs which will be modified and used to obtain
3604 copy_workqueue_attrs(tmp_attrs, new_attrs);
3607 * If something goes wrong during CPU up/down, we'll fall back to
3608 * the default pwq covering whole @attrs->cpumask. Always create
3609 * it even if we don't use it immediately.
3611 ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
3615 for_each_node(node) {
3616 if (wq_calc_node_cpumask(new_attrs, node, -1, tmp_attrs->cpumask)) {
3617 ctx->pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
3618 if (!ctx->pwq_tbl[node])
3621 ctx->dfl_pwq->refcnt++;
3622 ctx->pwq_tbl[node] = ctx->dfl_pwq;
3626 /* save the user configured attrs and sanitize it. */
3627 copy_workqueue_attrs(new_attrs, attrs);
3628 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
3629 ctx->attrs = new_attrs;
3632 free_workqueue_attrs(tmp_attrs);
3636 free_workqueue_attrs(tmp_attrs);
3637 free_workqueue_attrs(new_attrs);
3638 apply_wqattrs_cleanup(ctx);
3642 /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
3643 static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
3647 /* all pwqs have been created successfully, let's install'em */
3648 mutex_lock(&ctx->wq->mutex);
3650 copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
3652 /* save the previous pwq and install the new one */
3654 ctx->pwq_tbl[node] = numa_pwq_tbl_install(ctx->wq, node,
3655 ctx->pwq_tbl[node]);
3657 /* @dfl_pwq might not have been used, ensure it's linked */
3658 link_pwq(ctx->dfl_pwq);
3659 swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
3661 mutex_unlock(&ctx->wq->mutex);
3664 static void apply_wqattrs_lock(void)
3666 /* CPUs should stay stable across pwq creations and installations */
3668 mutex_lock(&wq_pool_mutex);
3671 static void apply_wqattrs_unlock(void)
3673 mutex_unlock(&wq_pool_mutex);
3677 static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
3678 const struct workqueue_attrs *attrs)
3680 struct apply_wqattrs_ctx *ctx;
3683 /* only unbound workqueues can change attributes */
3684 if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
3687 /* creating multiple pwqs breaks ordering guarantee */
3688 if (WARN_ON((wq->flags & __WQ_ORDERED) && !list_empty(&wq->pwqs)))
3691 ctx = apply_wqattrs_prepare(wq, attrs);
3693 /* the ctx has been prepared successfully, let's commit it */
3695 apply_wqattrs_commit(ctx);
3699 apply_wqattrs_cleanup(ctx);
3705 * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
3706 * @wq: the target workqueue
3707 * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
3709 * Apply @attrs to an unbound workqueue @wq. Unless disabled, on NUMA
3710 * machines, this function maps a separate pwq to each NUMA node with
3711 * possibles CPUs in @attrs->cpumask so that work items are affine to the
3712 * NUMA node it was issued on. Older pwqs are released as in-flight work
3713 * items finish. Note that a work item which repeatedly requeues itself
3714 * back-to-back will stay on its current pwq.
3716 * Performs GFP_KERNEL allocations.
3718 * Return: 0 on success and -errno on failure.
3720 int apply_workqueue_attrs(struct workqueue_struct *wq,
3721 const struct workqueue_attrs *attrs)
3725 apply_wqattrs_lock();
3726 ret = apply_workqueue_attrs_locked(wq, attrs);
3727 apply_wqattrs_unlock();
3733 * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
3734 * @wq: the target workqueue
3735 * @cpu: the CPU coming up or going down
3736 * @online: whether @cpu is coming up or going down
3738 * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
3739 * %CPU_DOWN_FAILED. @cpu is being hot[un]plugged, update NUMA affinity of
3742 * If NUMA affinity can't be adjusted due to memory allocation failure, it
3743 * falls back to @wq->dfl_pwq which may not be optimal but is always
3746 * Note that when the last allowed CPU of a NUMA node goes offline for a
3747 * workqueue with a cpumask spanning multiple nodes, the workers which were
3748 * already executing the work items for the workqueue will lose their CPU
3749 * affinity and may execute on any CPU. This is similar to how per-cpu
3750 * workqueues behave on CPU_DOWN. If a workqueue user wants strict
3751 * affinity, it's the user's responsibility to flush the work item from
3754 static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
3757 int node = cpu_to_node(cpu);
3758 int cpu_off = online ? -1 : cpu;
3759 struct pool_workqueue *old_pwq = NULL, *pwq;
3760 struct workqueue_attrs *target_attrs;
3763 lockdep_assert_held(&wq_pool_mutex);
3765 if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND) ||
3766 wq->unbound_attrs->no_numa)
3770 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
3771 * Let's use a preallocated one. The following buf is protected by
3772 * CPU hotplug exclusion.
3774 target_attrs = wq_update_unbound_numa_attrs_buf;
3775 cpumask = target_attrs->cpumask;
3777 copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
3778 pwq = unbound_pwq_by_node(wq, node);
3781 * Let's determine what needs to be done. If the target cpumask is
3782 * different from the default pwq's, we need to compare it to @pwq's
3783 * and create a new one if they don't match. If the target cpumask
3784 * equals the default pwq's, the default pwq should be used.
3786 if (wq_calc_node_cpumask(wq->dfl_pwq->pool->attrs, node, cpu_off, cpumask)) {
3787 if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
3793 /* create a new pwq */
3794 pwq = alloc_unbound_pwq(wq, target_attrs);
3796 pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
3801 /* Install the new pwq. */
3802 mutex_lock(&wq->mutex);
3803 old_pwq = numa_pwq_tbl_install(wq, node, pwq);
3807 mutex_lock(&wq->mutex);
3808 spin_lock_irq(&wq->dfl_pwq->pool->lock);
3809 get_pwq(wq->dfl_pwq);
3810 spin_unlock_irq(&wq->dfl_pwq->pool->lock);
3811 old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
3813 mutex_unlock(&wq->mutex);
3814 put_pwq_unlocked(old_pwq);
3817 static int alloc_and_link_pwqs(struct workqueue_struct *wq)
3819 bool highpri = wq->flags & WQ_HIGHPRI;
3822 if (!(wq->flags & WQ_UNBOUND)) {
3823 wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
3827 for_each_possible_cpu(cpu) {
3828 struct pool_workqueue *pwq =
3829 per_cpu_ptr(wq->cpu_pwqs, cpu);
3830 struct worker_pool *cpu_pools =
3831 per_cpu(cpu_worker_pools, cpu);
3833 init_pwq(pwq, wq, &cpu_pools[highpri]);
3835 mutex_lock(&wq->mutex);
3837 mutex_unlock(&wq->mutex);
3840 } else if (wq->flags & __WQ_ORDERED) {
3841 ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
3842 /* there should only be single pwq for ordering guarantee */
3843 WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
3844 wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
3845 "ordering guarantee broken for workqueue %s\n", wq->name);
3848 return apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
3852 static int wq_clamp_max_active(int max_active, unsigned int flags,
3855 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3857 if (max_active < 1 || max_active > lim)
3858 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3859 max_active, name, 1, lim);
3861 return clamp_val(max_active, 1, lim);
3864 struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
3867 struct lock_class_key *key,
3868 const char *lock_name, ...)
3870 size_t tbl_size = 0;
3872 struct workqueue_struct *wq;
3873 struct pool_workqueue *pwq;
3875 /* see the comment above the definition of WQ_POWER_EFFICIENT */
3876 if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
3877 flags |= WQ_UNBOUND;
3879 /* allocate wq and format name */
3880 if (flags & WQ_UNBOUND)
3881 tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
3883 wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
3887 if (flags & WQ_UNBOUND) {
3888 wq->unbound_attrs = alloc_workqueue_attrs(GFP_KERNEL);
3889 if (!wq->unbound_attrs)
3893 va_start(args, lock_name);
3894 vsnprintf(wq->name, sizeof(wq->name), fmt, args);
3897 max_active = max_active ?: WQ_DFL_ACTIVE;
3898 max_active = wq_clamp_max_active(max_active, flags, wq->name);
3902 wq->saved_max_active = max_active;
3903 mutex_init(&wq->mutex);
3904 atomic_set(&wq->nr_pwqs_to_flush, 0);
3905 INIT_LIST_HEAD(&wq->pwqs);
3906 INIT_LIST_HEAD(&wq->flusher_queue);
3907 INIT_LIST_HEAD(&wq->flusher_overflow);
3908 INIT_LIST_HEAD(&wq->maydays);
3910 lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3911 INIT_LIST_HEAD(&wq->list);
3913 if (alloc_and_link_pwqs(wq) < 0)
3917 * Workqueues which may be used during memory reclaim should
3918 * have a rescuer to guarantee forward progress.
3920 if (flags & WQ_MEM_RECLAIM) {
3921 struct worker *rescuer;
3923 rescuer = alloc_worker(NUMA_NO_NODE);
3927 rescuer->rescue_wq = wq;
3928 rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
3930 if (IS_ERR(rescuer->task)) {
3935 wq->rescuer = rescuer;
3936 kthread_bind_mask(rescuer->task, cpu_possible_mask);
3937 wake_up_process(rescuer->task);
3940 if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
3944 * wq_pool_mutex protects global freeze state and workqueues list.
3945 * Grab it, adjust max_active and add the new @wq to workqueues
3948 mutex_lock(&wq_pool_mutex);
3950 mutex_lock(&wq->mutex);
3951 for_each_pwq(pwq, wq)
3952 pwq_adjust_max_active(pwq);
3953 mutex_unlock(&wq->mutex);
3955 list_add_tail_rcu(&wq->list, &workqueues);
3957 mutex_unlock(&wq_pool_mutex);
3962 free_workqueue_attrs(wq->unbound_attrs);
3966 destroy_workqueue(wq);
3969 EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
3972 * destroy_workqueue - safely terminate a workqueue
3973 * @wq: target workqueue
3975 * Safely destroy a workqueue. All work currently pending will be done first.
3977 void destroy_workqueue(struct workqueue_struct *wq)
3979 struct pool_workqueue *pwq;
3982 /* drain it before proceeding with destruction */
3983 drain_workqueue(wq);
3986 mutex_lock(&wq->mutex);
3987 for_each_pwq(pwq, wq) {
3990 for (i = 0; i < WORK_NR_COLORS; i++) {
3991 if (WARN_ON(pwq->nr_in_flight[i])) {
3992 mutex_unlock(&wq->mutex);
3997 if (WARN_ON((pwq != wq->dfl_pwq) && (pwq->refcnt > 1)) ||
3998 WARN_ON(pwq->nr_active) ||
3999 WARN_ON(!list_empty(&pwq->delayed_works))) {
4000 mutex_unlock(&wq->mutex);
4004 mutex_unlock(&wq->mutex);
4007 * wq list is used to freeze wq, remove from list after
4008 * flushing is complete in case freeze races us.
4010 mutex_lock(&wq_pool_mutex);
4011 list_del_rcu(&wq->list);
4012 mutex_unlock(&wq_pool_mutex);
4014 workqueue_sysfs_unregister(wq);
4017 kthread_stop(wq->rescuer->task);
4019 if (!(wq->flags & WQ_UNBOUND)) {
4021 * The base ref is never dropped on per-cpu pwqs. Directly
4022 * schedule RCU free.
4024 call_rcu(&wq->rcu, rcu_free_wq);
4027 * We're the sole accessor of @wq at this point. Directly
4028 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
4029 * @wq will be freed when the last pwq is released.
4031 for_each_node(node) {
4032 pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
4033 RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
4034 put_pwq_unlocked(pwq);
4038 * Put dfl_pwq. @wq may be freed any time after dfl_pwq is
4039 * put. Don't access it afterwards.
4043 put_pwq_unlocked(pwq);
4046 EXPORT_SYMBOL_GPL(destroy_workqueue);
4049 * workqueue_set_max_active - adjust max_active of a workqueue
4050 * @wq: target workqueue
4051 * @max_active: new max_active value.
4053 * Set max_active of @wq to @max_active.
4056 * Don't call from IRQ context.
4058 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4060 struct pool_workqueue *pwq;
4062 /* disallow meddling with max_active for ordered workqueues */
4063 if (WARN_ON(wq->flags & __WQ_ORDERED))
4066 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4068 mutex_lock(&wq->mutex);
4070 wq->saved_max_active = max_active;
4072 for_each_pwq(pwq, wq)
4073 pwq_adjust_max_active(pwq);
4075 mutex_unlock(&wq->mutex);
4077 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4080 * current_is_workqueue_rescuer - is %current workqueue rescuer?
4082 * Determine whether %current is a workqueue rescuer. Can be used from
4083 * work functions to determine whether it's being run off the rescuer task.
4085 * Return: %true if %current is a workqueue rescuer. %false otherwise.
4087 bool current_is_workqueue_rescuer(void)
4089 struct worker *worker = current_wq_worker();
4091 return worker && worker->rescue_wq;
4095 * workqueue_congested - test whether a workqueue is congested
4096 * @cpu: CPU in question
4097 * @wq: target workqueue
4099 * Test whether @wq's cpu workqueue for @cpu is congested. There is
4100 * no synchronization around this function and the test result is
4101 * unreliable and only useful as advisory hints or for debugging.
4103 * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4104 * Note that both per-cpu and unbound workqueues may be associated with
4105 * multiple pool_workqueues which have separate congested states. A
4106 * workqueue being congested on one CPU doesn't mean the workqueue is also
4107 * contested on other CPUs / NUMA nodes.
4110 * %true if congested, %false otherwise.
4112 bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4114 struct pool_workqueue *pwq;
4120 if (cpu == WORK_CPU_UNBOUND)
4121 cpu = smp_processor_id();
4123 if (!(wq->flags & WQ_UNBOUND))
4124 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
4126 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4128 ret = !list_empty(&pwq->delayed_works);
4134 EXPORT_SYMBOL_GPL(workqueue_congested);
4137 * work_busy - test whether a work is currently pending or running
4138 * @work: the work to be tested
4140 * Test whether @work is currently pending or running. There is no
4141 * synchronization around this function and the test result is
4142 * unreliable and only useful as advisory hints or for debugging.
4145 * OR'd bitmask of WORK_BUSY_* bits.
4147 unsigned int work_busy(struct work_struct *work)
4149 struct worker_pool *pool;
4150 unsigned long flags;
4151 unsigned int ret = 0;
4153 if (work_pending(work))
4154 ret |= WORK_BUSY_PENDING;
4157 pool = get_work_pool(work);
4159 spin_lock_irqsave(&pool->lock, flags);
4160 if (find_worker_executing_work(pool, work))
4161 ret |= WORK_BUSY_RUNNING;
4162 spin_unlock_irqrestore(&pool->lock, flags);
4168 EXPORT_SYMBOL_GPL(work_busy);
4171 * set_worker_desc - set description for the current work item
4172 * @fmt: printf-style format string
4173 * @...: arguments for the format string
4175 * This function can be called by a running work function to describe what
4176 * the work item is about. If the worker task gets dumped, this
4177 * information will be printed out together to help debugging. The
4178 * description can be at most WORKER_DESC_LEN including the trailing '\0'.
4180 void set_worker_desc(const char *fmt, ...)
4182 struct worker *worker = current_wq_worker();
4186 va_start(args, fmt);
4187 vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
4189 worker->desc_valid = true;
4194 * print_worker_info - print out worker information and description
4195 * @log_lvl: the log level to use when printing
4196 * @task: target task
4198 * If @task is a worker and currently executing a work item, print out the
4199 * name of the workqueue being serviced and worker description set with
4200 * set_worker_desc() by the currently executing work item.
4202 * This function can be safely called on any task as long as the
4203 * task_struct itself is accessible. While safe, this function isn't
4204 * synchronized and may print out mixups or garbages of limited length.
4206 void print_worker_info(const char *log_lvl, struct task_struct *task)
4208 work_func_t *fn = NULL;
4209 char name[WQ_NAME_LEN] = { };
4210 char desc[WORKER_DESC_LEN] = { };
4211 struct pool_workqueue *pwq = NULL;
4212 struct workqueue_struct *wq = NULL;
4213 bool desc_valid = false;
4214 struct worker *worker;
4216 if (!(task->flags & PF_WQ_WORKER))
4220 * This function is called without any synchronization and @task
4221 * could be in any state. Be careful with dereferences.
4223 worker = probe_kthread_data(task);
4226 * Carefully copy the associated workqueue's workfn and name. Keep
4227 * the original last '\0' in case the original contains garbage.
4229 probe_kernel_read(&fn, &worker->current_func, sizeof(fn));
4230 probe_kernel_read(&pwq, &worker->current_pwq, sizeof(pwq));
4231 probe_kernel_read(&wq, &pwq->wq, sizeof(wq));
4232 probe_kernel_read(name, wq->name, sizeof(name) - 1);
4234 /* copy worker description */
4235 probe_kernel_read(&desc_valid, &worker->desc_valid, sizeof(desc_valid));
4237 probe_kernel_read(desc, worker->desc, sizeof(desc) - 1);
4239 if (fn || name[0] || desc[0]) {
4240 printk("%sWorkqueue: %s %pf", log_lvl, name, fn);
4242 pr_cont(" (%s)", desc);
4247 static void pr_cont_pool_info(struct worker_pool *pool)
4249 pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
4250 if (pool->node != NUMA_NO_NODE)
4251 pr_cont(" node=%d", pool->node);
4252 pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
4255 static void pr_cont_work(bool comma, struct work_struct *work)
4257 if (work->func == wq_barrier_func) {
4258 struct wq_barrier *barr;
4260 barr = container_of(work, struct wq_barrier, work);
4262 pr_cont("%s BAR(%d)", comma ? "," : "",
4263 task_pid_nr(barr->task));
4265 pr_cont("%s %pf", comma ? "," : "", work->func);
4269 static void show_pwq(struct pool_workqueue *pwq)
4271 struct worker_pool *pool = pwq->pool;
4272 struct work_struct *work;
4273 struct worker *worker;
4274 bool has_in_flight = false, has_pending = false;
4277 pr_info(" pwq %d:", pool->id);
4278 pr_cont_pool_info(pool);
4280 pr_cont(" active=%d/%d%s\n", pwq->nr_active, pwq->max_active,
4281 !list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
4283 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
4284 if (worker->current_pwq == pwq) {
4285 has_in_flight = true;
4289 if (has_in_flight) {
4292 pr_info(" in-flight:");
4293 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
4294 if (worker->current_pwq != pwq)
4297 pr_cont("%s %d%s:%pf", comma ? "," : "",
4298 task_pid_nr(worker->task),
4299 worker == pwq->wq->rescuer ? "(RESCUER)" : "",
4300 worker->current_func);
4301 list_for_each_entry(work, &worker->scheduled, entry)
4302 pr_cont_work(false, work);
4308 list_for_each_entry(work, &pool->worklist, entry) {
4309 if (get_work_pwq(work) == pwq) {
4317 pr_info(" pending:");
4318 list_for_each_entry(work, &pool->worklist, entry) {
4319 if (get_work_pwq(work) != pwq)
4322 pr_cont_work(comma, work);
4323 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
4328 if (!list_empty(&pwq->delayed_works)) {
4331 pr_info(" delayed:");
4332 list_for_each_entry(work, &pwq->delayed_works, entry) {
4333 pr_cont_work(comma, work);
4334 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
4341 * show_workqueue_state - dump workqueue state
4343 * Called from a sysrq handler and prints out all busy workqueues and
4346 void show_workqueue_state(void)
4348 struct workqueue_struct *wq;
4349 struct worker_pool *pool;
4350 unsigned long flags;
4355 pr_info("Showing busy workqueues and worker pools:\n");
4357 list_for_each_entry_rcu(wq, &workqueues, list) {
4358 struct pool_workqueue *pwq;
4361 for_each_pwq(pwq, wq) {
4362 if (pwq->nr_active || !list_empty(&pwq->delayed_works)) {
4370 pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
4372 for_each_pwq(pwq, wq) {
4373 spin_lock_irqsave(&pwq->pool->lock, flags);
4374 if (pwq->nr_active || !list_empty(&pwq->delayed_works))
4376 spin_unlock_irqrestore(&pwq->pool->lock, flags);
4380 for_each_pool(pool, pi) {
4381 struct worker *worker;
4384 spin_lock_irqsave(&pool->lock, flags);
4385 if (pool->nr_workers == pool->nr_idle)
4388 pr_info("pool %d:", pool->id);
4389 pr_cont_pool_info(pool);
4390 pr_cont(" workers=%d", pool->nr_workers);
4392 pr_cont(" manager: %d",
4393 task_pid_nr(pool->manager->task));
4394 list_for_each_entry(worker, &pool->idle_list, entry) {
4395 pr_cont(" %s%d", first ? "idle: " : "",
4396 task_pid_nr(worker->task));
4401 spin_unlock_irqrestore(&pool->lock, flags);
4410 * There are two challenges in supporting CPU hotplug. Firstly, there
4411 * are a lot of assumptions on strong associations among work, pwq and
4412 * pool which make migrating pending and scheduled works very
4413 * difficult to implement without impacting hot paths. Secondly,
4414 * worker pools serve mix of short, long and very long running works making
4415 * blocked draining impractical.
4417 * This is solved by allowing the pools to be disassociated from the CPU
4418 * running as an unbound one and allowing it to be reattached later if the
4419 * cpu comes back online.
4422 static void wq_unbind_fn(struct work_struct *work)
4424 int cpu = smp_processor_id();
4425 struct worker_pool *pool;
4426 struct worker *worker;
4428 for_each_cpu_worker_pool(pool, cpu) {
4429 mutex_lock(&pool->attach_mutex);
4430 spin_lock_irq(&pool->lock);
4433 * We've blocked all attach/detach operations. Make all workers
4434 * unbound and set DISASSOCIATED. Before this, all workers
4435 * except for the ones which are still executing works from
4436 * before the last CPU down must be on the cpu. After
4437 * this, they may become diasporas.
4439 for_each_pool_worker(worker, pool)
4440 worker->flags |= WORKER_UNBOUND;
4442 pool->flags |= POOL_DISASSOCIATED;
4444 spin_unlock_irq(&pool->lock);
4445 mutex_unlock(&pool->attach_mutex);
4448 * Call schedule() so that we cross rq->lock and thus can
4449 * guarantee sched callbacks see the %WORKER_UNBOUND flag.
4450 * This is necessary as scheduler callbacks may be invoked
4456 * Sched callbacks are disabled now. Zap nr_running.
4457 * After this, nr_running stays zero and need_more_worker()
4458 * and keep_working() are always true as long as the
4459 * worklist is not empty. This pool now behaves as an
4460 * unbound (in terms of concurrency management) pool which
4461 * are served by workers tied to the pool.
4463 atomic_set(&pool->nr_running, 0);
4466 * With concurrency management just turned off, a busy
4467 * worker blocking could lead to lengthy stalls. Kick off
4468 * unbound chain execution of currently pending work items.
4470 spin_lock_irq(&pool->lock);
4471 wake_up_worker(pool);
4472 spin_unlock_irq(&pool->lock);
4477 * rebind_workers - rebind all workers of a pool to the associated CPU
4478 * @pool: pool of interest
4480 * @pool->cpu is coming online. Rebind all workers to the CPU.
4482 static void rebind_workers(struct worker_pool *pool)
4484 struct worker *worker;
4486 lockdep_assert_held(&pool->attach_mutex);
4489 * Restore CPU affinity of all workers. As all idle workers should
4490 * be on the run-queue of the associated CPU before any local
4491 * wake-ups for concurrency management happen, restore CPU affinity
4492 * of all workers first and then clear UNBOUND. As we're called
4493 * from CPU_ONLINE, the following shouldn't fail.
4495 for_each_pool_worker(worker, pool)
4496 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4497 pool->attrs->cpumask) < 0);
4499 spin_lock_irq(&pool->lock);
4502 * XXX: CPU hotplug notifiers are weird and can call DOWN_FAILED
4503 * w/o preceding DOWN_PREPARE. Work around it. CPU hotplug is
4504 * being reworked and this can go away in time.
4506 if (!(pool->flags & POOL_DISASSOCIATED)) {
4507 spin_unlock_irq(&pool->lock);
4511 pool->flags &= ~POOL_DISASSOCIATED;
4513 for_each_pool_worker(worker, pool) {
4514 unsigned int worker_flags = worker->flags;
4517 * A bound idle worker should actually be on the runqueue
4518 * of the associated CPU for local wake-ups targeting it to
4519 * work. Kick all idle workers so that they migrate to the
4520 * associated CPU. Doing this in the same loop as
4521 * replacing UNBOUND with REBOUND is safe as no worker will
4522 * be bound before @pool->lock is released.
4524 if (worker_flags & WORKER_IDLE)
4525 wake_up_process(worker->task);
4528 * We want to clear UNBOUND but can't directly call
4529 * worker_clr_flags() or adjust nr_running. Atomically
4530 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
4531 * @worker will clear REBOUND using worker_clr_flags() when
4532 * it initiates the next execution cycle thus restoring
4533 * concurrency management. Note that when or whether
4534 * @worker clears REBOUND doesn't affect correctness.
4536 * ACCESS_ONCE() is necessary because @worker->flags may be
4537 * tested without holding any lock in
4538 * wq_worker_waking_up(). Without it, NOT_RUNNING test may
4539 * fail incorrectly leading to premature concurrency
4540 * management operations.
4542 WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
4543 worker_flags |= WORKER_REBOUND;
4544 worker_flags &= ~WORKER_UNBOUND;
4545 ACCESS_ONCE(worker->flags) = worker_flags;
4548 spin_unlock_irq(&pool->lock);
4552 * restore_unbound_workers_cpumask - restore cpumask of unbound workers
4553 * @pool: unbound pool of interest
4554 * @cpu: the CPU which is coming up
4556 * An unbound pool may end up with a cpumask which doesn't have any online
4557 * CPUs. When a worker of such pool get scheduled, the scheduler resets
4558 * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
4559 * online CPU before, cpus_allowed of all its workers should be restored.
4561 static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
4563 static cpumask_t cpumask;
4564 struct worker *worker;
4566 lockdep_assert_held(&pool->attach_mutex);
4568 /* is @cpu allowed for @pool? */
4569 if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
4572 /* is @cpu the only online CPU? */
4573 cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
4574 if (cpumask_weight(&cpumask) != 1)
4577 /* as we're called from CPU_ONLINE, the following shouldn't fail */
4578 for_each_pool_worker(worker, pool)
4579 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4580 pool->attrs->cpumask) < 0);
4584 * Workqueues should be brought up before normal priority CPU notifiers.
4585 * This will be registered high priority CPU notifier.
4587 static int workqueue_cpu_up_callback(struct notifier_block *nfb,
4588 unsigned long action,
4591 int cpu = (unsigned long)hcpu;
4592 struct worker_pool *pool;
4593 struct workqueue_struct *wq;
4596 switch (action & ~CPU_TASKS_FROZEN) {
4597 case CPU_UP_PREPARE:
4598 for_each_cpu_worker_pool(pool, cpu) {
4599 if (pool->nr_workers)
4601 if (!create_worker(pool))
4606 case CPU_DOWN_FAILED:
4608 mutex_lock(&wq_pool_mutex);
4610 for_each_pool(pool, pi) {
4611 mutex_lock(&pool->attach_mutex);
4613 if (pool->cpu == cpu)
4614 rebind_workers(pool);
4615 else if (pool->cpu < 0)
4616 restore_unbound_workers_cpumask(pool, cpu);
4618 mutex_unlock(&pool->attach_mutex);
4621 /* update NUMA affinity of unbound workqueues */
4622 list_for_each_entry(wq, &workqueues, list)
4623 wq_update_unbound_numa(wq, cpu, true);
4625 mutex_unlock(&wq_pool_mutex);
4632 * Workqueues should be brought down after normal priority CPU notifiers.
4633 * This will be registered as low priority CPU notifier.
4635 static int workqueue_cpu_down_callback(struct notifier_block *nfb,
4636 unsigned long action,
4639 int cpu = (unsigned long)hcpu;
4640 struct work_struct unbind_work;
4641 struct workqueue_struct *wq;
4643 switch (action & ~CPU_TASKS_FROZEN) {
4644 case CPU_DOWN_PREPARE:
4645 /* unbinding per-cpu workers should happen on the local CPU */
4646 INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
4647 queue_work_on(cpu, system_highpri_wq, &unbind_work);
4649 /* update NUMA affinity of unbound workqueues */
4650 mutex_lock(&wq_pool_mutex);
4651 list_for_each_entry(wq, &workqueues, list)
4652 wq_update_unbound_numa(wq, cpu, false);
4653 mutex_unlock(&wq_pool_mutex);
4655 /* wait for per-cpu unbinding to finish */
4656 flush_work(&unbind_work);
4657 destroy_work_on_stack(&unbind_work);
4665 struct work_for_cpu {
4666 struct work_struct work;
4672 static void work_for_cpu_fn(struct work_struct *work)
4674 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
4676 wfc->ret = wfc->fn(wfc->arg);
4680 * work_on_cpu - run a function in user context on a particular cpu
4681 * @cpu: the cpu to run on
4682 * @fn: the function to run
4683 * @arg: the function arg
4685 * It is up to the caller to ensure that the cpu doesn't go offline.
4686 * The caller must not hold any locks which would prevent @fn from completing.
4688 * Return: The value @fn returns.
4690 long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
4692 struct work_for_cpu wfc = { .fn = fn, .arg = arg };
4694 INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
4695 schedule_work_on(cpu, &wfc.work);
4696 flush_work(&wfc.work);
4697 destroy_work_on_stack(&wfc.work);
4700 EXPORT_SYMBOL_GPL(work_on_cpu);
4701 #endif /* CONFIG_SMP */
4703 #ifdef CONFIG_FREEZER
4706 * freeze_workqueues_begin - begin freezing workqueues
4708 * Start freezing workqueues. After this function returns, all freezable
4709 * workqueues will queue new works to their delayed_works list instead of
4713 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4715 void freeze_workqueues_begin(void)
4717 struct workqueue_struct *wq;
4718 struct pool_workqueue *pwq;
4720 mutex_lock(&wq_pool_mutex);
4722 WARN_ON_ONCE(workqueue_freezing);
4723 workqueue_freezing = true;
4725 list_for_each_entry(wq, &workqueues, list) {
4726 mutex_lock(&wq->mutex);
4727 for_each_pwq(pwq, wq)
4728 pwq_adjust_max_active(pwq);
4729 mutex_unlock(&wq->mutex);
4732 mutex_unlock(&wq_pool_mutex);
4736 * freeze_workqueues_busy - are freezable workqueues still busy?
4738 * Check whether freezing is complete. This function must be called
4739 * between freeze_workqueues_begin() and thaw_workqueues().
4742 * Grabs and releases wq_pool_mutex.
4745 * %true if some freezable workqueues are still busy. %false if freezing
4748 bool freeze_workqueues_busy(void)
4751 struct workqueue_struct *wq;
4752 struct pool_workqueue *pwq;
4754 mutex_lock(&wq_pool_mutex);
4756 WARN_ON_ONCE(!workqueue_freezing);
4758 list_for_each_entry(wq, &workqueues, list) {
4759 if (!(wq->flags & WQ_FREEZABLE))
4762 * nr_active is monotonically decreasing. It's safe
4763 * to peek without lock.
4766 for_each_pwq(pwq, wq) {
4767 WARN_ON_ONCE(pwq->nr_active < 0);
4768 if (pwq->nr_active) {
4777 mutex_unlock(&wq_pool_mutex);
4782 * thaw_workqueues - thaw workqueues
4784 * Thaw workqueues. Normal queueing is restored and all collected
4785 * frozen works are transferred to their respective pool worklists.
4788 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4790 void thaw_workqueues(void)
4792 struct workqueue_struct *wq;
4793 struct pool_workqueue *pwq;
4795 mutex_lock(&wq_pool_mutex);
4797 if (!workqueue_freezing)
4800 workqueue_freezing = false;
4802 /* restore max_active and repopulate worklist */
4803 list_for_each_entry(wq, &workqueues, list) {
4804 mutex_lock(&wq->mutex);
4805 for_each_pwq(pwq, wq)
4806 pwq_adjust_max_active(pwq);
4807 mutex_unlock(&wq->mutex);
4811 mutex_unlock(&wq_pool_mutex);
4813 #endif /* CONFIG_FREEZER */
4815 static int workqueue_apply_unbound_cpumask(void)
4819 struct workqueue_struct *wq;
4820 struct apply_wqattrs_ctx *ctx, *n;
4822 lockdep_assert_held(&wq_pool_mutex);
4824 list_for_each_entry(wq, &workqueues, list) {
4825 if (!(wq->flags & WQ_UNBOUND))
4827 /* creating multiple pwqs breaks ordering guarantee */
4828 if (wq->flags & __WQ_ORDERED)
4831 ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs);
4837 list_add_tail(&ctx->list, &ctxs);
4840 list_for_each_entry_safe(ctx, n, &ctxs, list) {
4842 apply_wqattrs_commit(ctx);
4843 apply_wqattrs_cleanup(ctx);
4850 * workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
4851 * @cpumask: the cpumask to set
4853 * The low-level workqueues cpumask is a global cpumask that limits
4854 * the affinity of all unbound workqueues. This function check the @cpumask
4855 * and apply it to all unbound workqueues and updates all pwqs of them.
4857 * Retun: 0 - Success
4858 * -EINVAL - Invalid @cpumask
4859 * -ENOMEM - Failed to allocate memory for attrs or pwqs.
4861 int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
4864 cpumask_var_t saved_cpumask;
4866 if (!zalloc_cpumask_var(&saved_cpumask, GFP_KERNEL))
4869 cpumask_and(cpumask, cpumask, cpu_possible_mask);
4870 if (!cpumask_empty(cpumask)) {
4871 apply_wqattrs_lock();
4873 /* save the old wq_unbound_cpumask. */
4874 cpumask_copy(saved_cpumask, wq_unbound_cpumask);
4876 /* update wq_unbound_cpumask at first and apply it to wqs. */
4877 cpumask_copy(wq_unbound_cpumask, cpumask);
4878 ret = workqueue_apply_unbound_cpumask();
4880 /* restore the wq_unbound_cpumask when failed. */
4882 cpumask_copy(wq_unbound_cpumask, saved_cpumask);
4884 apply_wqattrs_unlock();
4887 free_cpumask_var(saved_cpumask);
4893 * Workqueues with WQ_SYSFS flag set is visible to userland via
4894 * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
4895 * following attributes.
4897 * per_cpu RO bool : whether the workqueue is per-cpu or unbound
4898 * max_active RW int : maximum number of in-flight work items
4900 * Unbound workqueues have the following extra attributes.
4902 * id RO int : the associated pool ID
4903 * nice RW int : nice value of the workers
4904 * cpumask RW mask : bitmask of allowed CPUs for the workers
4907 struct workqueue_struct *wq;
4911 static struct workqueue_struct *dev_to_wq(struct device *dev)
4913 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
4918 static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
4921 struct workqueue_struct *wq = dev_to_wq(dev);
4923 return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
4925 static DEVICE_ATTR_RO(per_cpu);
4927 static ssize_t max_active_show(struct device *dev,
4928 struct device_attribute *attr, char *buf)
4930 struct workqueue_struct *wq = dev_to_wq(dev);
4932 return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
4935 static ssize_t max_active_store(struct device *dev,
4936 struct device_attribute *attr, const char *buf,
4939 struct workqueue_struct *wq = dev_to_wq(dev);
4942 if (sscanf(buf, "%d", &val) != 1 || val <= 0)
4945 workqueue_set_max_active(wq, val);
4948 static DEVICE_ATTR_RW(max_active);
4950 static struct attribute *wq_sysfs_attrs[] = {
4951 &dev_attr_per_cpu.attr,
4952 &dev_attr_max_active.attr,
4955 ATTRIBUTE_GROUPS(wq_sysfs);
4957 static ssize_t wq_pool_ids_show(struct device *dev,
4958 struct device_attribute *attr, char *buf)
4960 struct workqueue_struct *wq = dev_to_wq(dev);
4961 const char *delim = "";
4962 int node, written = 0;
4966 for_each_node(node) {
4967 written += scnprintf(buf + written, PAGE_SIZE - written,
4968 "%s%d:%d", delim, node,
4969 unbound_pwq_by_node(wq, node)->pool->id);
4972 written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
4979 static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
4982 struct workqueue_struct *wq = dev_to_wq(dev);
4985 mutex_lock(&wq->mutex);
4986 written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
4987 mutex_unlock(&wq->mutex);
4992 /* prepare workqueue_attrs for sysfs store operations */
4993 static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
4995 struct workqueue_attrs *attrs;
4997 lockdep_assert_held(&wq_pool_mutex);
4999 attrs = alloc_workqueue_attrs(GFP_KERNEL);
5003 copy_workqueue_attrs(attrs, wq->unbound_attrs);
5007 static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
5008 const char *buf, size_t count)
5010 struct workqueue_struct *wq = dev_to_wq(dev);
5011 struct workqueue_attrs *attrs;
5014 apply_wqattrs_lock();
5016 attrs = wq_sysfs_prep_attrs(wq);
5020 if (sscanf(buf, "%d", &attrs->nice) == 1 &&
5021 attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
5022 ret = apply_workqueue_attrs_locked(wq, attrs);
5027 apply_wqattrs_unlock();
5028 free_workqueue_attrs(attrs);
5029 return ret ?: count;
5032 static ssize_t wq_cpumask_show(struct device *dev,
5033 struct device_attribute *attr, char *buf)
5035 struct workqueue_struct *wq = dev_to_wq(dev);
5038 mutex_lock(&wq->mutex);
5039 written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
5040 cpumask_pr_args(wq->unbound_attrs->cpumask));
5041 mutex_unlock(&wq->mutex);
5045 static ssize_t wq_cpumask_store(struct device *dev,
5046 struct device_attribute *attr,
5047 const char *buf, size_t count)
5049 struct workqueue_struct *wq = dev_to_wq(dev);
5050 struct workqueue_attrs *attrs;
5053 apply_wqattrs_lock();
5055 attrs = wq_sysfs_prep_attrs(wq);
5059 ret = cpumask_parse(buf, attrs->cpumask);
5061 ret = apply_workqueue_attrs_locked(wq, attrs);
5064 apply_wqattrs_unlock();
5065 free_workqueue_attrs(attrs);
5066 return ret ?: count;
5069 static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
5072 struct workqueue_struct *wq = dev_to_wq(dev);
5075 mutex_lock(&wq->mutex);
5076 written = scnprintf(buf, PAGE_SIZE, "%d\n",
5077 !wq->unbound_attrs->no_numa);
5078 mutex_unlock(&wq->mutex);
5083 static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
5084 const char *buf, size_t count)
5086 struct workqueue_struct *wq = dev_to_wq(dev);
5087 struct workqueue_attrs *attrs;
5088 int v, ret = -ENOMEM;
5090 apply_wqattrs_lock();
5092 attrs = wq_sysfs_prep_attrs(wq);
5097 if (sscanf(buf, "%d", &v) == 1) {
5098 attrs->no_numa = !v;
5099 ret = apply_workqueue_attrs_locked(wq, attrs);
5103 apply_wqattrs_unlock();
5104 free_workqueue_attrs(attrs);
5105 return ret ?: count;
5108 static struct device_attribute wq_sysfs_unbound_attrs[] = {
5109 __ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
5110 __ATTR(nice, 0644, wq_nice_show, wq_nice_store),
5111 __ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
5112 __ATTR(numa, 0644, wq_numa_show, wq_numa_store),
5116 static struct bus_type wq_subsys = {
5117 .name = "workqueue",
5118 .dev_groups = wq_sysfs_groups,
5121 static ssize_t wq_unbound_cpumask_show(struct device *dev,
5122 struct device_attribute *attr, char *buf)
5126 mutex_lock(&wq_pool_mutex);
5127 written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
5128 cpumask_pr_args(wq_unbound_cpumask));
5129 mutex_unlock(&wq_pool_mutex);
5134 static ssize_t wq_unbound_cpumask_store(struct device *dev,
5135 struct device_attribute *attr, const char *buf, size_t count)
5137 cpumask_var_t cpumask;
5140 if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
5143 ret = cpumask_parse(buf, cpumask);
5145 ret = workqueue_set_unbound_cpumask(cpumask);
5147 free_cpumask_var(cpumask);
5148 return ret ? ret : count;
5151 static struct device_attribute wq_sysfs_cpumask_attr =
5152 __ATTR(cpumask, 0644, wq_unbound_cpumask_show,
5153 wq_unbound_cpumask_store);
5155 static int __init wq_sysfs_init(void)
5159 err = subsys_virtual_register(&wq_subsys, NULL);
5163 return device_create_file(wq_subsys.dev_root, &wq_sysfs_cpumask_attr);
5165 core_initcall(wq_sysfs_init);
5167 static void wq_device_release(struct device *dev)
5169 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
5175 * workqueue_sysfs_register - make a workqueue visible in sysfs
5176 * @wq: the workqueue to register
5178 * Expose @wq in sysfs under /sys/bus/workqueue/devices.
5179 * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
5180 * which is the preferred method.
5182 * Workqueue user should use this function directly iff it wants to apply
5183 * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
5184 * apply_workqueue_attrs() may race against userland updating the
5187 * Return: 0 on success, -errno on failure.
5189 int workqueue_sysfs_register(struct workqueue_struct *wq)
5191 struct wq_device *wq_dev;
5195 * Adjusting max_active or creating new pwqs by applying
5196 * attributes breaks ordering guarantee. Disallow exposing ordered
5199 if (WARN_ON(wq->flags & __WQ_ORDERED))
5202 wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
5207 wq_dev->dev.bus = &wq_subsys;
5208 wq_dev->dev.init_name = wq->name;
5209 wq_dev->dev.release = wq_device_release;
5212 * unbound_attrs are created separately. Suppress uevent until
5213 * everything is ready.
5215 dev_set_uevent_suppress(&wq_dev->dev, true);
5217 ret = device_register(&wq_dev->dev);
5224 if (wq->flags & WQ_UNBOUND) {
5225 struct device_attribute *attr;
5227 for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
5228 ret = device_create_file(&wq_dev->dev, attr);
5230 device_unregister(&wq_dev->dev);
5237 dev_set_uevent_suppress(&wq_dev->dev, false);
5238 kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
5243 * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
5244 * @wq: the workqueue to unregister
5246 * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
5248 static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
5250 struct wq_device *wq_dev = wq->wq_dev;
5256 device_unregister(&wq_dev->dev);
5258 #else /* CONFIG_SYSFS */
5259 static void workqueue_sysfs_unregister(struct workqueue_struct *wq) { }
5260 #endif /* CONFIG_SYSFS */
5262 static void __init wq_numa_init(void)
5267 if (num_possible_nodes() <= 1)
5270 if (wq_disable_numa) {
5271 pr_info("workqueue: NUMA affinity support disabled\n");
5275 wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs(GFP_KERNEL);
5276 BUG_ON(!wq_update_unbound_numa_attrs_buf);
5279 * We want masks of possible CPUs of each node which isn't readily
5280 * available. Build one from cpu_to_node() which should have been
5281 * fully initialized by now.
5283 tbl = kzalloc(nr_node_ids * sizeof(tbl[0]), GFP_KERNEL);
5287 BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
5288 node_online(node) ? node : NUMA_NO_NODE));
5290 for_each_possible_cpu(cpu) {
5291 node = cpu_to_node(cpu);
5292 if (WARN_ON(node == NUMA_NO_NODE)) {
5293 pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
5294 /* happens iff arch is bonkers, let's just proceed */
5297 cpumask_set_cpu(cpu, tbl[node]);
5300 wq_numa_possible_cpumask = tbl;
5301 wq_numa_enabled = true;
5304 static int __init init_workqueues(void)
5306 int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
5309 WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
5311 BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
5312 cpumask_copy(wq_unbound_cpumask, cpu_possible_mask);
5314 pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
5316 cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
5317 hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
5321 /* initialize CPU pools */
5322 for_each_possible_cpu(cpu) {
5323 struct worker_pool *pool;
5326 for_each_cpu_worker_pool(pool, cpu) {
5327 BUG_ON(init_worker_pool(pool));
5329 cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
5330 pool->attrs->nice = std_nice[i++];
5331 pool->node = cpu_to_node(cpu);
5334 mutex_lock(&wq_pool_mutex);
5335 BUG_ON(worker_pool_assign_id(pool));
5336 mutex_unlock(&wq_pool_mutex);
5340 /* create the initial worker */
5341 for_each_online_cpu(cpu) {
5342 struct worker_pool *pool;
5344 for_each_cpu_worker_pool(pool, cpu) {
5345 pool->flags &= ~POOL_DISASSOCIATED;
5346 BUG_ON(!create_worker(pool));
5350 /* create default unbound and ordered wq attrs */
5351 for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
5352 struct workqueue_attrs *attrs;
5354 BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
5355 attrs->nice = std_nice[i];
5356 unbound_std_wq_attrs[i] = attrs;
5359 * An ordered wq should have only one pwq as ordering is
5360 * guaranteed by max_active which is enforced by pwqs.
5361 * Turn off NUMA so that dfl_pwq is used for all nodes.
5363 BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
5364 attrs->nice = std_nice[i];
5365 attrs->no_numa = true;
5366 ordered_wq_attrs[i] = attrs;
5369 system_wq = alloc_workqueue("events", 0, 0);
5370 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
5371 system_long_wq = alloc_workqueue("events_long", 0, 0);
5372 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
5373 WQ_UNBOUND_MAX_ACTIVE);
5374 system_freezable_wq = alloc_workqueue("events_freezable",
5376 system_power_efficient_wq = alloc_workqueue("events_power_efficient",
5377 WQ_POWER_EFFICIENT, 0);
5378 system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
5379 WQ_FREEZABLE | WQ_POWER_EFFICIENT,
5381 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
5382 !system_unbound_wq || !system_freezable_wq ||
5383 !system_power_efficient_wq ||
5384 !system_freezable_power_efficient_wq);
5387 early_initcall(init_workqueues);