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);
688 static void clear_work_data(struct work_struct *work)
690 smp_wmb(); /* see set_work_pool_and_clear_pending() */
691 set_work_data(work, WORK_STRUCT_NO_POOL, 0);
694 static struct pool_workqueue *get_work_pwq(struct work_struct *work)
696 unsigned long data = atomic_long_read(&work->data);
698 if (data & WORK_STRUCT_PWQ)
699 return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
705 * get_work_pool - return the worker_pool a given work was associated with
706 * @work: the work item of interest
708 * Pools are created and destroyed under wq_pool_mutex, and allows read
709 * access under RCU read lock. As such, this function should be
710 * called under wq_pool_mutex or inside of a rcu_read_lock() region.
712 * All fields of the returned pool are accessible as long as the above
713 * mentioned locking is in effect. If the returned pool needs to be used
714 * beyond the critical section, the caller is responsible for ensuring the
715 * returned pool is and stays online.
717 * Return: The worker_pool @work was last associated with. %NULL if none.
719 static struct worker_pool *get_work_pool(struct work_struct *work)
721 unsigned long data = atomic_long_read(&work->data);
724 assert_rcu_or_pool_mutex();
726 if (data & WORK_STRUCT_PWQ)
727 return ((struct pool_workqueue *)
728 (data & WORK_STRUCT_WQ_DATA_MASK))->pool;
730 pool_id = data >> WORK_OFFQ_POOL_SHIFT;
731 if (pool_id == WORK_OFFQ_POOL_NONE)
734 return idr_find(&worker_pool_idr, pool_id);
738 * get_work_pool_id - return the worker pool ID a given work is associated with
739 * @work: the work item of interest
741 * Return: The worker_pool ID @work was last associated with.
742 * %WORK_OFFQ_POOL_NONE if none.
744 static int get_work_pool_id(struct work_struct *work)
746 unsigned long data = atomic_long_read(&work->data);
748 if (data & WORK_STRUCT_PWQ)
749 return ((struct pool_workqueue *)
750 (data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
752 return data >> WORK_OFFQ_POOL_SHIFT;
755 static void mark_work_canceling(struct work_struct *work)
757 unsigned long pool_id = get_work_pool_id(work);
759 pool_id <<= WORK_OFFQ_POOL_SHIFT;
760 set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
763 static bool work_is_canceling(struct work_struct *work)
765 unsigned long data = atomic_long_read(&work->data);
767 return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
771 * Policy functions. These define the policies on how the global worker
772 * pools are managed. Unless noted otherwise, these functions assume that
773 * they're being called with pool->lock held.
776 static bool __need_more_worker(struct worker_pool *pool)
778 return !atomic_read(&pool->nr_running);
782 * Need to wake up a worker? Called from anything but currently
785 * Note that, because unbound workers never contribute to nr_running, this
786 * function will always return %true for unbound pools as long as the
787 * worklist isn't empty.
789 static bool need_more_worker(struct worker_pool *pool)
791 return !list_empty(&pool->worklist) && __need_more_worker(pool);
794 /* Can I start working? Called from busy but !running workers. */
795 static bool may_start_working(struct worker_pool *pool)
797 return pool->nr_idle;
800 /* Do I need to keep working? Called from currently running workers. */
801 static bool keep_working(struct worker_pool *pool)
803 return !list_empty(&pool->worklist) &&
804 atomic_read(&pool->nr_running) <= 1;
807 /* Do we need a new worker? Called from manager. */
808 static bool need_to_create_worker(struct worker_pool *pool)
810 return need_more_worker(pool) && !may_start_working(pool);
813 /* Do we have too many workers and should some go away? */
814 static bool too_many_workers(struct worker_pool *pool)
816 bool managing = mutex_is_locked(&pool->manager_arb);
817 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
818 int nr_busy = pool->nr_workers - nr_idle;
820 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
827 /* Return the first idle worker. Safe with preemption disabled */
828 static struct worker *first_idle_worker(struct worker_pool *pool)
830 if (unlikely(list_empty(&pool->idle_list)))
833 return list_first_entry(&pool->idle_list, struct worker, entry);
837 * wake_up_worker - wake up an idle worker
838 * @pool: worker pool to wake worker from
840 * Wake up the first idle worker of @pool.
843 * spin_lock_irq(pool->lock).
845 static void wake_up_worker(struct worker_pool *pool)
847 struct worker *worker;
849 rt_lock_idle_list(pool);
851 worker = first_idle_worker(pool);
854 wake_up_process(worker->task);
856 rt_unlock_idle_list(pool);
860 * wq_worker_running - a worker is running again
861 * @task: task returning from sleep
863 * This function is called when a worker returns from schedule()
865 void wq_worker_running(struct task_struct *task)
867 struct worker *worker = kthread_data(task);
869 if (!worker->sleeping)
871 if (!(worker->flags & WORKER_NOT_RUNNING))
872 atomic_inc(&worker->pool->nr_running);
873 worker->sleeping = 0;
877 * wq_worker_sleeping - a worker is going to sleep
878 * @task: task going to sleep
879 * This function is called from schedule() when a busy worker is
882 void wq_worker_sleeping(struct task_struct *task)
884 struct worker *worker = kthread_data(task);
885 struct worker_pool *pool;
888 * Rescuers, which may not have all the fields set up like normal
889 * workers, also reach here, let's not access anything before
890 * checking NOT_RUNNING.
892 if (worker->flags & WORKER_NOT_RUNNING)
897 if (WARN_ON_ONCE(worker->sleeping))
900 worker->sleeping = 1;
903 * The counterpart of the following dec_and_test, implied mb,
904 * worklist not empty test sequence is in insert_work().
905 * Please read comment there.
907 if (atomic_dec_and_test(&pool->nr_running) &&
908 !list_empty(&pool->worklist)) {
909 sched_lock_idle_list(pool);
910 wake_up_worker(pool);
911 sched_unlock_idle_list(pool);
916 * worker_set_flags - set worker flags and adjust nr_running accordingly
918 * @flags: flags to set
920 * Set @flags in @worker->flags and adjust nr_running accordingly.
923 * spin_lock_irq(pool->lock)
925 static inline void worker_set_flags(struct worker *worker, unsigned int flags)
927 struct worker_pool *pool = worker->pool;
929 WARN_ON_ONCE(worker->task != current);
931 /* If transitioning into NOT_RUNNING, adjust nr_running. */
932 if ((flags & WORKER_NOT_RUNNING) &&
933 !(worker->flags & WORKER_NOT_RUNNING)) {
934 atomic_dec(&pool->nr_running);
937 worker->flags |= flags;
941 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
943 * @flags: flags to clear
945 * Clear @flags in @worker->flags and adjust nr_running accordingly.
948 * spin_lock_irq(pool->lock)
950 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
952 struct worker_pool *pool = worker->pool;
953 unsigned int oflags = worker->flags;
955 WARN_ON_ONCE(worker->task != current);
957 worker->flags &= ~flags;
960 * If transitioning out of NOT_RUNNING, increment nr_running. Note
961 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
962 * of multiple flags, not a single flag.
964 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
965 if (!(worker->flags & WORKER_NOT_RUNNING))
966 atomic_inc(&pool->nr_running);
970 * find_worker_executing_work - find worker which is executing a work
971 * @pool: pool of interest
972 * @work: work to find worker for
974 * Find a worker which is executing @work on @pool by searching
975 * @pool->busy_hash which is keyed by the address of @work. For a worker
976 * to match, its current execution should match the address of @work and
977 * its work function. This is to avoid unwanted dependency between
978 * unrelated work executions through a work item being recycled while still
981 * This is a bit tricky. A work item may be freed once its execution
982 * starts and nothing prevents the freed area from being recycled for
983 * another work item. If the same work item address ends up being reused
984 * before the original execution finishes, workqueue will identify the
985 * recycled work item as currently executing and make it wait until the
986 * current execution finishes, introducing an unwanted dependency.
988 * This function checks the work item address and work function to avoid
989 * false positives. Note that this isn't complete as one may construct a
990 * work function which can introduce dependency onto itself through a
991 * recycled work item. Well, if somebody wants to shoot oneself in the
992 * foot that badly, there's only so much we can do, and if such deadlock
993 * actually occurs, it should be easy to locate the culprit work function.
996 * spin_lock_irq(pool->lock).
999 * Pointer to worker which is executing @work if found, %NULL
1002 static struct worker *find_worker_executing_work(struct worker_pool *pool,
1003 struct work_struct *work)
1005 struct worker *worker;
1007 hash_for_each_possible(pool->busy_hash, worker, hentry,
1008 (unsigned long)work)
1009 if (worker->current_work == work &&
1010 worker->current_func == work->func)
1017 * move_linked_works - move linked works to a list
1018 * @work: start of series of works to be scheduled
1019 * @head: target list to append @work to
1020 * @nextp: out parameter for nested worklist walking
1022 * Schedule linked works starting from @work to @head. Work series to
1023 * be scheduled starts at @work and includes any consecutive work with
1024 * WORK_STRUCT_LINKED set in its predecessor.
1026 * If @nextp is not NULL, it's updated to point to the next work of
1027 * the last scheduled work. This allows move_linked_works() to be
1028 * nested inside outer list_for_each_entry_safe().
1031 * spin_lock_irq(pool->lock).
1033 static void move_linked_works(struct work_struct *work, struct list_head *head,
1034 struct work_struct **nextp)
1036 struct work_struct *n;
1039 * Linked worklist will always end before the end of the list,
1040 * use NULL for list head.
1042 list_for_each_entry_safe_from(work, n, NULL, entry) {
1043 list_move_tail(&work->entry, head);
1044 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1049 * If we're already inside safe list traversal and have moved
1050 * multiple works to the scheduled queue, the next position
1051 * needs to be updated.
1058 * get_pwq - get an extra reference on the specified pool_workqueue
1059 * @pwq: pool_workqueue to get
1061 * Obtain an extra reference on @pwq. The caller should guarantee that
1062 * @pwq has positive refcnt and be holding the matching pool->lock.
1064 static void get_pwq(struct pool_workqueue *pwq)
1066 lockdep_assert_held(&pwq->pool->lock);
1067 WARN_ON_ONCE(pwq->refcnt <= 0);
1072 * put_pwq - put a pool_workqueue reference
1073 * @pwq: pool_workqueue to put
1075 * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
1076 * destruction. The caller should be holding the matching pool->lock.
1078 static void put_pwq(struct pool_workqueue *pwq)
1080 lockdep_assert_held(&pwq->pool->lock);
1081 if (likely(--pwq->refcnt))
1083 if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
1086 * @pwq can't be released under pool->lock, bounce to
1087 * pwq_unbound_release_workfn(). This never recurses on the same
1088 * pool->lock as this path is taken only for unbound workqueues and
1089 * the release work item is scheduled on a per-cpu workqueue. To
1090 * avoid lockdep warning, unbound pool->locks are given lockdep
1091 * subclass of 1 in get_unbound_pool().
1093 schedule_work(&pwq->unbound_release_work);
1097 * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1098 * @pwq: pool_workqueue to put (can be %NULL)
1100 * put_pwq() with locking. This function also allows %NULL @pwq.
1102 static void put_pwq_unlocked(struct pool_workqueue *pwq)
1106 * As both pwqs and pools are RCU protected, the
1107 * following lock operations are safe.
1109 local_spin_lock_irq(pendingb_lock, &pwq->pool->lock);
1111 local_spin_unlock_irq(pendingb_lock, &pwq->pool->lock);
1115 static void pwq_activate_delayed_work(struct work_struct *work)
1117 struct pool_workqueue *pwq = get_work_pwq(work);
1119 trace_workqueue_activate_work(work);
1120 move_linked_works(work, &pwq->pool->worklist, NULL);
1121 __clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
1125 static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
1127 struct work_struct *work = list_first_entry(&pwq->delayed_works,
1128 struct work_struct, entry);
1130 pwq_activate_delayed_work(work);
1134 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1135 * @pwq: pwq of interest
1136 * @color: color of work which left the queue
1138 * A work either has completed or is removed from pending queue,
1139 * decrement nr_in_flight of its pwq and handle workqueue flushing.
1142 * spin_lock_irq(pool->lock).
1144 static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
1146 /* uncolored work items don't participate in flushing or nr_active */
1147 if (color == WORK_NO_COLOR)
1150 pwq->nr_in_flight[color]--;
1153 if (!list_empty(&pwq->delayed_works)) {
1154 /* one down, submit a delayed one */
1155 if (pwq->nr_active < pwq->max_active)
1156 pwq_activate_first_delayed(pwq);
1159 /* is flush in progress and are we at the flushing tip? */
1160 if (likely(pwq->flush_color != color))
1163 /* are there still in-flight works? */
1164 if (pwq->nr_in_flight[color])
1167 /* this pwq is done, clear flush_color */
1168 pwq->flush_color = -1;
1171 * If this was the last pwq, wake up the first flusher. It
1172 * will handle the rest.
1174 if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1175 complete(&pwq->wq->first_flusher->done);
1181 * try_to_grab_pending - steal work item from worklist and disable irq
1182 * @work: work item to steal
1183 * @is_dwork: @work is a delayed_work
1184 * @flags: place to store irq state
1186 * Try to grab PENDING bit of @work. This function can handle @work in any
1187 * stable state - idle, on timer or on worklist.
1190 * 1 if @work was pending and we successfully stole PENDING
1191 * 0 if @work was idle and we claimed PENDING
1192 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1193 * -ENOENT if someone else is canceling @work, this state may persist
1194 * for arbitrarily long
1197 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1198 * interrupted while holding PENDING and @work off queue, irq must be
1199 * disabled on entry. This, combined with delayed_work->timer being
1200 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1202 * On successful return, >= 0, irq is disabled and the caller is
1203 * responsible for releasing it using local_irq_restore(*@flags).
1205 * This function is safe to call from any context including IRQ handler.
1207 static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1208 unsigned long *flags)
1210 struct worker_pool *pool;
1211 struct pool_workqueue *pwq;
1213 local_lock_irqsave(pendingb_lock, *flags);
1215 /* try to steal the timer if it exists */
1217 struct delayed_work *dwork = to_delayed_work(work);
1220 * dwork->timer is irqsafe. If del_timer() fails, it's
1221 * guaranteed that the timer is not queued anywhere and not
1222 * running on the local CPU.
1224 if (likely(del_timer(&dwork->timer)))
1228 /* try to claim PENDING the normal way */
1229 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1234 * The queueing is in progress, or it is already queued. Try to
1235 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1237 pool = get_work_pool(work);
1241 spin_lock(&pool->lock);
1243 * work->data is guaranteed to point to pwq only while the work
1244 * item is queued on pwq->wq, and both updating work->data to point
1245 * to pwq on queueing and to pool on dequeueing are done under
1246 * pwq->pool->lock. This in turn guarantees that, if work->data
1247 * points to pwq which is associated with a locked pool, the work
1248 * item is currently queued on that pool.
1250 pwq = get_work_pwq(work);
1251 if (pwq && pwq->pool == pool) {
1252 debug_work_deactivate(work);
1255 * A delayed work item cannot be grabbed directly because
1256 * it might have linked NO_COLOR work items which, if left
1257 * on the delayed_list, will confuse pwq->nr_active
1258 * management later on and cause stall. Make sure the work
1259 * item is activated before grabbing.
1261 if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1262 pwq_activate_delayed_work(work);
1264 list_del_init(&work->entry);
1265 pwq_dec_nr_in_flight(pwq, get_work_color(work));
1267 /* work->data points to pwq iff queued, point to pool */
1268 set_work_pool_and_keep_pending(work, pool->id);
1270 spin_unlock(&pool->lock);
1274 spin_unlock(&pool->lock);
1277 local_unlock_irqrestore(pendingb_lock, *flags);
1278 if (work_is_canceling(work))
1285 * insert_work - insert a work into a pool
1286 * @pwq: pwq @work belongs to
1287 * @work: work to insert
1288 * @head: insertion point
1289 * @extra_flags: extra WORK_STRUCT_* flags to set
1291 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
1292 * work_struct flags.
1295 * spin_lock_irq(pool->lock).
1297 static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1298 struct list_head *head, unsigned int extra_flags)
1300 struct worker_pool *pool = pwq->pool;
1302 /* we own @work, set data and link */
1303 set_work_pwq(work, pwq, extra_flags);
1304 list_add_tail(&work->entry, head);
1308 * Ensure either wq_worker_sleeping() sees the above
1309 * list_add_tail() or we see zero nr_running to avoid workers lying
1310 * around lazily while there are works to be processed.
1314 if (__need_more_worker(pool))
1315 wake_up_worker(pool);
1319 * Test whether @work is being queued from another work executing on the
1322 static bool is_chained_work(struct workqueue_struct *wq)
1324 struct worker *worker;
1326 worker = current_wq_worker();
1328 * Return %true iff I'm a worker execuing a work item on @wq. If
1329 * I'm @worker, it's safe to dereference it without locking.
1331 return worker && worker->current_pwq->wq == wq;
1334 static void __queue_work(int cpu, struct workqueue_struct *wq,
1335 struct work_struct *work)
1337 struct pool_workqueue *pwq;
1338 struct worker_pool *last_pool;
1339 struct list_head *worklist;
1340 unsigned int work_flags;
1341 unsigned int req_cpu = cpu;
1344 * While a work item is PENDING && off queue, a task trying to
1345 * steal the PENDING will busy-loop waiting for it to either get
1346 * queued or lose PENDING. Grabbing PENDING and queueing should
1347 * happen with IRQ disabled.
1349 WARN_ON_ONCE_NONRT(!irqs_disabled());
1351 debug_work_activate(work);
1353 /* if draining, only works from the same workqueue are allowed */
1354 if (unlikely(wq->flags & __WQ_DRAINING) &&
1355 WARN_ON_ONCE(!is_chained_work(wq)))
1360 if (req_cpu == WORK_CPU_UNBOUND)
1361 cpu = raw_smp_processor_id();
1363 /* pwq which will be used unless @work is executing elsewhere */
1364 if (!(wq->flags & WQ_UNBOUND))
1365 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1367 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1370 * If @work was previously on a different pool, it might still be
1371 * running there, in which case the work needs to be queued on that
1372 * pool to guarantee non-reentrancy.
1374 last_pool = get_work_pool(work);
1375 if (last_pool && last_pool != pwq->pool) {
1376 struct worker *worker;
1378 spin_lock(&last_pool->lock);
1380 worker = find_worker_executing_work(last_pool, work);
1382 if (worker && worker->current_pwq->wq == wq) {
1383 pwq = worker->current_pwq;
1385 /* meh... not running there, queue here */
1386 spin_unlock(&last_pool->lock);
1387 spin_lock(&pwq->pool->lock);
1390 spin_lock(&pwq->pool->lock);
1394 * pwq is determined and locked. For unbound pools, we could have
1395 * raced with pwq release and it could already be dead. If its
1396 * refcnt is zero, repeat pwq selection. Note that pwqs never die
1397 * without another pwq replacing it in the numa_pwq_tbl or while
1398 * work items are executing on it, so the retrying is guaranteed to
1399 * make forward-progress.
1401 if (unlikely(!pwq->refcnt)) {
1402 if (wq->flags & WQ_UNBOUND) {
1403 spin_unlock(&pwq->pool->lock);
1408 WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
1412 /* pwq determined, queue */
1413 trace_workqueue_queue_work(req_cpu, pwq, work);
1415 if (WARN_ON(!list_empty(&work->entry)))
1418 pwq->nr_in_flight[pwq->work_color]++;
1419 work_flags = work_color_to_flags(pwq->work_color);
1421 if (likely(pwq->nr_active < pwq->max_active)) {
1422 trace_workqueue_activate_work(work);
1424 worklist = &pwq->pool->worklist;
1426 work_flags |= WORK_STRUCT_DELAYED;
1427 worklist = &pwq->delayed_works;
1430 insert_work(pwq, work, worklist, work_flags);
1433 spin_unlock(&pwq->pool->lock);
1438 * queue_work_on - queue work on specific cpu
1439 * @cpu: CPU number to execute work on
1440 * @wq: workqueue to use
1441 * @work: work to queue
1443 * We queue the work to a specific CPU, the caller must ensure it
1446 * Return: %false if @work was already on a queue, %true otherwise.
1448 bool queue_work_on(int cpu, struct workqueue_struct *wq,
1449 struct work_struct *work)
1452 unsigned long flags;
1454 local_lock_irqsave(pendingb_lock,flags);
1456 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1457 __queue_work(cpu, wq, work);
1461 local_unlock_irqrestore(pendingb_lock, flags);
1464 EXPORT_SYMBOL(queue_work_on);
1466 void delayed_work_timer_fn(unsigned long __data)
1468 struct delayed_work *dwork = (struct delayed_work *)__data;
1470 /* should have been called from irqsafe timer with irq already off */
1471 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
1473 EXPORT_SYMBOL(delayed_work_timer_fn);
1475 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
1476 struct delayed_work *dwork, unsigned long delay)
1478 struct timer_list *timer = &dwork->timer;
1479 struct work_struct *work = &dwork->work;
1481 WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
1482 timer->data != (unsigned long)dwork);
1483 WARN_ON_ONCE(timer_pending(timer));
1484 WARN_ON_ONCE(!list_empty(&work->entry));
1487 * If @delay is 0, queue @dwork->work immediately. This is for
1488 * both optimization and correctness. The earliest @timer can
1489 * expire is on the closest next tick and delayed_work users depend
1490 * on that there's no such delay when @delay is 0.
1493 __queue_work(cpu, wq, &dwork->work);
1497 timer_stats_timer_set_start_info(&dwork->timer);
1501 timer->expires = jiffies + delay;
1503 if (unlikely(cpu != WORK_CPU_UNBOUND))
1504 add_timer_on(timer, cpu);
1510 * queue_delayed_work_on - queue work on specific CPU after delay
1511 * @cpu: CPU number to execute work on
1512 * @wq: workqueue to use
1513 * @dwork: work to queue
1514 * @delay: number of jiffies to wait before queueing
1516 * Return: %false if @work was already on a queue, %true otherwise. If
1517 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1520 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1521 struct delayed_work *dwork, unsigned long delay)
1523 struct work_struct *work = &dwork->work;
1525 unsigned long flags;
1527 /* read the comment in __queue_work() */
1528 local_lock_irqsave(pendingb_lock, flags);
1530 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1531 __queue_delayed_work(cpu, wq, dwork, delay);
1535 local_unlock_irqrestore(pendingb_lock, flags);
1538 EXPORT_SYMBOL(queue_delayed_work_on);
1541 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
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 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1548 * modify @dwork's timer so that it expires after @delay. If @delay is
1549 * zero, @work is guaranteed to be scheduled immediately regardless of its
1552 * Return: %false if @dwork was idle and queued, %true if @dwork was
1553 * pending and its timer was modified.
1555 * This function is safe to call from any context including IRQ handler.
1556 * See try_to_grab_pending() for details.
1558 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
1559 struct delayed_work *dwork, unsigned long delay)
1561 unsigned long flags;
1565 ret = try_to_grab_pending(&dwork->work, true, &flags);
1566 } while (unlikely(ret == -EAGAIN));
1568 if (likely(ret >= 0)) {
1569 __queue_delayed_work(cpu, wq, dwork, delay);
1570 local_unlock_irqrestore(pendingb_lock, flags);
1573 /* -ENOENT from try_to_grab_pending() becomes %true */
1576 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
1579 * worker_enter_idle - enter idle state
1580 * @worker: worker which is entering idle state
1582 * @worker is entering idle state. Update stats and idle timer if
1586 * spin_lock_irq(pool->lock).
1588 static void worker_enter_idle(struct worker *worker)
1590 struct worker_pool *pool = worker->pool;
1592 if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
1593 WARN_ON_ONCE(!list_empty(&worker->entry) &&
1594 (worker->hentry.next || worker->hentry.pprev)))
1597 /* can't use worker_set_flags(), also called from create_worker() */
1598 worker->flags |= WORKER_IDLE;
1600 worker->last_active = jiffies;
1602 /* idle_list is LIFO */
1603 rt_lock_idle_list(pool);
1604 list_add(&worker->entry, &pool->idle_list);
1605 rt_unlock_idle_list(pool);
1607 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1608 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1611 * Sanity check nr_running. Because wq_unbind_fn() releases
1612 * pool->lock between setting %WORKER_UNBOUND and zapping
1613 * nr_running, the warning may trigger spuriously. Check iff
1614 * unbind is not in progress.
1616 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1617 pool->nr_workers == pool->nr_idle &&
1618 atomic_read(&pool->nr_running));
1622 * worker_leave_idle - leave idle state
1623 * @worker: worker which is leaving idle state
1625 * @worker is leaving idle state. Update stats.
1628 * spin_lock_irq(pool->lock).
1630 static void worker_leave_idle(struct worker *worker)
1632 struct worker_pool *pool = worker->pool;
1634 if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
1636 worker_clr_flags(worker, WORKER_IDLE);
1638 rt_lock_idle_list(pool);
1639 list_del_init(&worker->entry);
1640 rt_unlock_idle_list(pool);
1643 static struct worker *alloc_worker(int node)
1645 struct worker *worker;
1647 worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
1649 INIT_LIST_HEAD(&worker->entry);
1650 INIT_LIST_HEAD(&worker->scheduled);
1651 INIT_LIST_HEAD(&worker->node);
1652 /* on creation a worker is in !idle && prep state */
1653 worker->flags = WORKER_PREP;
1659 * worker_attach_to_pool() - attach a worker to a pool
1660 * @worker: worker to be attached
1661 * @pool: the target pool
1663 * Attach @worker to @pool. Once attached, the %WORKER_UNBOUND flag and
1664 * cpu-binding of @worker are kept coordinated with the pool across
1667 static void worker_attach_to_pool(struct worker *worker,
1668 struct worker_pool *pool)
1670 mutex_lock(&pool->attach_mutex);
1673 * set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
1674 * online CPUs. It'll be re-applied when any of the CPUs come up.
1676 set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
1679 * The pool->attach_mutex ensures %POOL_DISASSOCIATED remains
1680 * stable across this function. See the comments above the
1681 * flag definition for details.
1683 if (pool->flags & POOL_DISASSOCIATED)
1684 worker->flags |= WORKER_UNBOUND;
1686 list_add_tail(&worker->node, &pool->workers);
1688 mutex_unlock(&pool->attach_mutex);
1692 * worker_detach_from_pool() - detach a worker from its pool
1693 * @worker: worker which is attached to its pool
1694 * @pool: the pool @worker is attached to
1696 * Undo the attaching which had been done in worker_attach_to_pool(). The
1697 * caller worker shouldn't access to the pool after detached except it has
1698 * other reference to the pool.
1700 static void worker_detach_from_pool(struct worker *worker,
1701 struct worker_pool *pool)
1703 struct completion *detach_completion = NULL;
1705 mutex_lock(&pool->attach_mutex);
1706 list_del(&worker->node);
1707 if (list_empty(&pool->workers))
1708 detach_completion = pool->detach_completion;
1709 mutex_unlock(&pool->attach_mutex);
1711 /* clear leftover flags without pool->lock after it is detached */
1712 worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
1714 if (detach_completion)
1715 complete(detach_completion);
1719 * create_worker - create a new workqueue worker
1720 * @pool: pool the new worker will belong to
1722 * Create and start a new worker which is attached to @pool.
1725 * Might sleep. Does GFP_KERNEL allocations.
1728 * Pointer to the newly created worker.
1730 static struct worker *create_worker(struct worker_pool *pool)
1732 struct worker *worker = NULL;
1736 /* ID is needed to determine kthread name */
1737 id = ida_simple_get(&pool->worker_ida, 0, 0, GFP_KERNEL);
1741 worker = alloc_worker(pool->node);
1745 worker->pool = pool;
1749 snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
1750 pool->attrs->nice < 0 ? "H" : "");
1752 snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
1754 worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
1755 "kworker/%s", id_buf);
1756 if (IS_ERR(worker->task))
1759 set_user_nice(worker->task, pool->attrs->nice);
1760 kthread_bind_mask(worker->task, pool->attrs->cpumask);
1762 /* successful, attach the worker to the pool */
1763 worker_attach_to_pool(worker, pool);
1765 /* start the newly created worker */
1766 spin_lock_irq(&pool->lock);
1767 worker->pool->nr_workers++;
1768 worker_enter_idle(worker);
1769 wake_up_process(worker->task);
1770 spin_unlock_irq(&pool->lock);
1776 ida_simple_remove(&pool->worker_ida, id);
1782 * destroy_worker - destroy a workqueue worker
1783 * @worker: worker to be destroyed
1785 * Destroy @worker and adjust @pool stats accordingly. The worker should
1789 * spin_lock_irq(pool->lock).
1791 static void destroy_worker(struct worker *worker)
1793 struct worker_pool *pool = worker->pool;
1795 lockdep_assert_held(&pool->lock);
1797 /* sanity check frenzy */
1798 if (WARN_ON(worker->current_work) ||
1799 WARN_ON(!list_empty(&worker->scheduled)) ||
1800 WARN_ON(!(worker->flags & WORKER_IDLE)))
1806 rt_lock_idle_list(pool);
1807 list_del_init(&worker->entry);
1808 rt_unlock_idle_list(pool);
1809 worker->flags |= WORKER_DIE;
1810 wake_up_process(worker->task);
1813 static void idle_worker_timeout(unsigned long __pool)
1815 struct worker_pool *pool = (void *)__pool;
1817 spin_lock_irq(&pool->lock);
1819 while (too_many_workers(pool)) {
1820 struct worker *worker;
1821 unsigned long expires;
1823 /* idle_list is kept in LIFO order, check the last one */
1824 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1825 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1827 if (time_before(jiffies, expires)) {
1828 mod_timer(&pool->idle_timer, expires);
1832 destroy_worker(worker);
1835 spin_unlock_irq(&pool->lock);
1838 static void send_mayday(struct work_struct *work)
1840 struct pool_workqueue *pwq = get_work_pwq(work);
1841 struct workqueue_struct *wq = pwq->wq;
1843 lockdep_assert_held(&wq_mayday_lock);
1848 /* mayday mayday mayday */
1849 if (list_empty(&pwq->mayday_node)) {
1851 * If @pwq is for an unbound wq, its base ref may be put at
1852 * any time due to an attribute change. Pin @pwq until the
1853 * rescuer is done with it.
1856 list_add_tail(&pwq->mayday_node, &wq->maydays);
1857 wake_up_process(wq->rescuer->task);
1861 static void pool_mayday_timeout(unsigned long __pool)
1863 struct worker_pool *pool = (void *)__pool;
1864 struct work_struct *work;
1866 spin_lock_irq(&pool->lock);
1867 spin_lock(&wq_mayday_lock); /* for wq->maydays */
1869 if (need_to_create_worker(pool)) {
1871 * We've been trying to create a new worker but
1872 * haven't been successful. We might be hitting an
1873 * allocation deadlock. Send distress signals to
1876 list_for_each_entry(work, &pool->worklist, entry)
1880 spin_unlock(&wq_mayday_lock);
1881 spin_unlock_irq(&pool->lock);
1883 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1887 * maybe_create_worker - create a new worker if necessary
1888 * @pool: pool to create a new worker for
1890 * Create a new worker for @pool if necessary. @pool is guaranteed to
1891 * have at least one idle worker on return from this function. If
1892 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1893 * sent to all rescuers with works scheduled on @pool to resolve
1894 * possible allocation deadlock.
1896 * On return, need_to_create_worker() is guaranteed to be %false and
1897 * may_start_working() %true.
1900 * spin_lock_irq(pool->lock) which may be released and regrabbed
1901 * multiple times. Does GFP_KERNEL allocations. Called only from
1904 static void maybe_create_worker(struct worker_pool *pool)
1905 __releases(&pool->lock)
1906 __acquires(&pool->lock)
1909 spin_unlock_irq(&pool->lock);
1911 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1912 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1915 if (create_worker(pool) || !need_to_create_worker(pool))
1918 schedule_timeout_interruptible(CREATE_COOLDOWN);
1920 if (!need_to_create_worker(pool))
1924 del_timer_sync(&pool->mayday_timer);
1925 spin_lock_irq(&pool->lock);
1927 * This is necessary even after a new worker was just successfully
1928 * created as @pool->lock was dropped and the new worker might have
1929 * already become busy.
1931 if (need_to_create_worker(pool))
1936 * manage_workers - manage worker pool
1939 * Assume the manager role and manage the worker pool @worker belongs
1940 * to. At any given time, there can be only zero or one manager per
1941 * pool. The exclusion is handled automatically by this function.
1943 * The caller can safely start processing works on false return. On
1944 * true return, it's guaranteed that need_to_create_worker() is false
1945 * and may_start_working() is true.
1948 * spin_lock_irq(pool->lock) which may be released and regrabbed
1949 * multiple times. Does GFP_KERNEL allocations.
1952 * %false if the pool doesn't need management and the caller can safely
1953 * start processing works, %true if management function was performed and
1954 * the conditions that the caller verified before calling the function may
1955 * no longer be true.
1957 static bool manage_workers(struct worker *worker)
1959 struct worker_pool *pool = worker->pool;
1962 * Anyone who successfully grabs manager_arb wins the arbitration
1963 * and becomes the manager. mutex_trylock() on pool->manager_arb
1964 * failure while holding pool->lock reliably indicates that someone
1965 * else is managing the pool and the worker which failed trylock
1966 * can proceed to executing work items. This means that anyone
1967 * grabbing manager_arb is responsible for actually performing
1968 * manager duties. If manager_arb is grabbed and released without
1969 * actual management, the pool may stall indefinitely.
1971 if (!mutex_trylock(&pool->manager_arb))
1973 pool->manager = worker;
1975 maybe_create_worker(pool);
1977 pool->manager = NULL;
1978 mutex_unlock(&pool->manager_arb);
1983 * process_one_work - process single work
1985 * @work: work to process
1987 * Process @work. This function contains all the logics necessary to
1988 * process a single work including synchronization against and
1989 * interaction with other workers on the same cpu, queueing and
1990 * flushing. As long as context requirement is met, any worker can
1991 * call this function to process a work.
1994 * spin_lock_irq(pool->lock) which is released and regrabbed.
1996 static void process_one_work(struct worker *worker, struct work_struct *work)
1997 __releases(&pool->lock)
1998 __acquires(&pool->lock)
2000 struct pool_workqueue *pwq = get_work_pwq(work);
2001 struct worker_pool *pool = worker->pool;
2002 bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
2004 struct worker *collision;
2005 #ifdef CONFIG_LOCKDEP
2007 * It is permissible to free the struct work_struct from
2008 * inside the function that is called from it, this we need to
2009 * take into account for lockdep too. To avoid bogus "held
2010 * lock freed" warnings as well as problems when looking into
2011 * work->lockdep_map, make a copy and use that here.
2013 struct lockdep_map lockdep_map;
2015 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
2017 /* ensure we're on the correct CPU */
2018 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2019 raw_smp_processor_id() != pool->cpu);
2022 * A single work shouldn't be executed concurrently by
2023 * multiple workers on a single cpu. Check whether anyone is
2024 * already processing the work. If so, defer the work to the
2025 * currently executing one.
2027 collision = find_worker_executing_work(pool, work);
2028 if (unlikely(collision)) {
2029 move_linked_works(work, &collision->scheduled, NULL);
2033 /* claim and dequeue */
2034 debug_work_deactivate(work);
2035 hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2036 worker->current_work = work;
2037 worker->current_func = work->func;
2038 worker->current_pwq = pwq;
2039 work_color = get_work_color(work);
2041 list_del_init(&work->entry);
2044 * CPU intensive works don't participate in concurrency management.
2045 * They're the scheduler's responsibility. This takes @worker out
2046 * of concurrency management and the next code block will chain
2047 * execution of the pending work items.
2049 if (unlikely(cpu_intensive))
2050 worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2053 * Wake up another worker if necessary. The condition is always
2054 * false for normal per-cpu workers since nr_running would always
2055 * be >= 1 at this point. This is used to chain execution of the
2056 * pending work items for WORKER_NOT_RUNNING workers such as the
2057 * UNBOUND and CPU_INTENSIVE ones.
2059 if (need_more_worker(pool))
2060 wake_up_worker(pool);
2063 * Record the last pool and clear PENDING which should be the last
2064 * update to @work. Also, do this inside @pool->lock so that
2065 * PENDING and queued state changes happen together while IRQ is
2068 set_work_pool_and_clear_pending(work, pool->id);
2070 spin_unlock_irq(&pool->lock);
2072 lock_map_acquire_read(&pwq->wq->lockdep_map);
2073 lock_map_acquire(&lockdep_map);
2074 trace_workqueue_execute_start(work);
2075 worker->current_func(work);
2077 * While we must be careful to not use "work" after this, the trace
2078 * point will only record its address.
2080 trace_workqueue_execute_end(work);
2081 lock_map_release(&lockdep_map);
2082 lock_map_release(&pwq->wq->lockdep_map);
2084 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2085 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2086 " last function: %pf\n",
2087 current->comm, preempt_count(), task_pid_nr(current),
2088 worker->current_func);
2089 debug_show_held_locks(current);
2094 * The following prevents a kworker from hogging CPU on !PREEMPT
2095 * kernels, where a requeueing work item waiting for something to
2096 * happen could deadlock with stop_machine as such work item could
2097 * indefinitely requeue itself while all other CPUs are trapped in
2098 * stop_machine. At the same time, report a quiescent RCU state so
2099 * the same condition doesn't freeze RCU.
2101 cond_resched_rcu_qs();
2103 spin_lock_irq(&pool->lock);
2105 /* clear cpu intensive status */
2106 if (unlikely(cpu_intensive))
2107 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2109 /* we're done with it, release */
2110 hash_del(&worker->hentry);
2111 worker->current_work = NULL;
2112 worker->current_func = NULL;
2113 worker->current_pwq = NULL;
2114 worker->desc_valid = false;
2115 pwq_dec_nr_in_flight(pwq, work_color);
2119 * process_scheduled_works - process scheduled works
2122 * Process all scheduled works. Please note that the scheduled list
2123 * may change while processing a work, so this function repeatedly
2124 * fetches a work from the top and executes it.
2127 * spin_lock_irq(pool->lock) which may be released and regrabbed
2130 static void process_scheduled_works(struct worker *worker)
2132 while (!list_empty(&worker->scheduled)) {
2133 struct work_struct *work = list_first_entry(&worker->scheduled,
2134 struct work_struct, entry);
2135 process_one_work(worker, work);
2140 * worker_thread - the worker thread function
2143 * The worker thread function. All workers belong to a worker_pool -
2144 * either a per-cpu one or dynamic unbound one. These workers process all
2145 * work items regardless of their specific target workqueue. The only
2146 * exception is work items which belong to workqueues with a rescuer which
2147 * will be explained in rescuer_thread().
2151 static int worker_thread(void *__worker)
2153 struct worker *worker = __worker;
2154 struct worker_pool *pool = worker->pool;
2156 /* tell the scheduler that this is a workqueue worker */
2157 worker->task->flags |= PF_WQ_WORKER;
2159 spin_lock_irq(&pool->lock);
2161 /* am I supposed to die? */
2162 if (unlikely(worker->flags & WORKER_DIE)) {
2163 spin_unlock_irq(&pool->lock);
2164 WARN_ON_ONCE(!list_empty(&worker->entry));
2165 worker->task->flags &= ~PF_WQ_WORKER;
2167 set_task_comm(worker->task, "kworker/dying");
2168 ida_simple_remove(&pool->worker_ida, worker->id);
2169 worker_detach_from_pool(worker, pool);
2174 worker_leave_idle(worker);
2176 /* no more worker necessary? */
2177 if (!need_more_worker(pool))
2180 /* do we need to manage? */
2181 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2185 * ->scheduled list can only be filled while a worker is
2186 * preparing to process a work or actually processing it.
2187 * Make sure nobody diddled with it while I was sleeping.
2189 WARN_ON_ONCE(!list_empty(&worker->scheduled));
2192 * Finish PREP stage. We're guaranteed to have at least one idle
2193 * worker or that someone else has already assumed the manager
2194 * role. This is where @worker starts participating in concurrency
2195 * management if applicable and concurrency management is restored
2196 * after being rebound. See rebind_workers() for details.
2198 worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2201 struct work_struct *work =
2202 list_first_entry(&pool->worklist,
2203 struct work_struct, entry);
2205 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2206 /* optimization path, not strictly necessary */
2207 process_one_work(worker, work);
2208 if (unlikely(!list_empty(&worker->scheduled)))
2209 process_scheduled_works(worker);
2211 move_linked_works(work, &worker->scheduled, NULL);
2212 process_scheduled_works(worker);
2214 } while (keep_working(pool));
2216 worker_set_flags(worker, WORKER_PREP);
2219 * pool->lock is held and there's no work to process and no need to
2220 * manage, sleep. Workers are woken up only while holding
2221 * pool->lock or from local cpu, so setting the current state
2222 * before releasing pool->lock is enough to prevent losing any
2225 worker_enter_idle(worker);
2226 __set_current_state(TASK_INTERRUPTIBLE);
2227 spin_unlock_irq(&pool->lock);
2233 * rescuer_thread - the rescuer thread function
2236 * Workqueue rescuer thread function. There's one rescuer for each
2237 * workqueue which has WQ_MEM_RECLAIM set.
2239 * Regular work processing on a pool may block trying to create a new
2240 * worker which uses GFP_KERNEL allocation which has slight chance of
2241 * developing into deadlock if some works currently on the same queue
2242 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2243 * the problem rescuer solves.
2245 * When such condition is possible, the pool summons rescuers of all
2246 * workqueues which have works queued on the pool and let them process
2247 * those works so that forward progress can be guaranteed.
2249 * This should happen rarely.
2253 static int rescuer_thread(void *__rescuer)
2255 struct worker *rescuer = __rescuer;
2256 struct workqueue_struct *wq = rescuer->rescue_wq;
2257 struct list_head *scheduled = &rescuer->scheduled;
2260 set_user_nice(current, RESCUER_NICE_LEVEL);
2263 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2264 * doesn't participate in concurrency management.
2266 rescuer->task->flags |= PF_WQ_WORKER;
2268 set_current_state(TASK_INTERRUPTIBLE);
2271 * By the time the rescuer is requested to stop, the workqueue
2272 * shouldn't have any work pending, but @wq->maydays may still have
2273 * pwq(s) queued. This can happen by non-rescuer workers consuming
2274 * all the work items before the rescuer got to them. Go through
2275 * @wq->maydays processing before acting on should_stop so that the
2276 * list is always empty on exit.
2278 should_stop = kthread_should_stop();
2280 /* see whether any pwq is asking for help */
2281 spin_lock_irq(&wq_mayday_lock);
2283 while (!list_empty(&wq->maydays)) {
2284 struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2285 struct pool_workqueue, mayday_node);
2286 struct worker_pool *pool = pwq->pool;
2287 struct work_struct *work, *n;
2289 __set_current_state(TASK_RUNNING);
2290 list_del_init(&pwq->mayday_node);
2292 spin_unlock_irq(&wq_mayday_lock);
2294 worker_attach_to_pool(rescuer, pool);
2296 spin_lock_irq(&pool->lock);
2297 rescuer->pool = pool;
2300 * Slurp in all works issued via this workqueue and
2303 WARN_ON_ONCE(!list_empty(scheduled));
2304 list_for_each_entry_safe(work, n, &pool->worklist, entry)
2305 if (get_work_pwq(work) == pwq)
2306 move_linked_works(work, scheduled, &n);
2308 if (!list_empty(scheduled)) {
2309 process_scheduled_works(rescuer);
2312 * The above execution of rescued work items could
2313 * have created more to rescue through
2314 * pwq_activate_first_delayed() or chained
2315 * queueing. Let's put @pwq back on mayday list so
2316 * that such back-to-back work items, which may be
2317 * being used to relieve memory pressure, don't
2318 * incur MAYDAY_INTERVAL delay inbetween.
2320 if (need_to_create_worker(pool)) {
2321 spin_lock(&wq_mayday_lock);
2323 list_move_tail(&pwq->mayday_node, &wq->maydays);
2324 spin_unlock(&wq_mayday_lock);
2329 * Put the reference grabbed by send_mayday(). @pool won't
2330 * go away while we're still attached to it.
2335 * Leave this pool. If need_more_worker() is %true, notify a
2336 * regular worker; otherwise, we end up with 0 concurrency
2337 * and stalling the execution.
2339 if (need_more_worker(pool))
2340 wake_up_worker(pool);
2342 rescuer->pool = NULL;
2343 spin_unlock_irq(&pool->lock);
2345 worker_detach_from_pool(rescuer, pool);
2347 spin_lock_irq(&wq_mayday_lock);
2350 spin_unlock_irq(&wq_mayday_lock);
2353 __set_current_state(TASK_RUNNING);
2354 rescuer->task->flags &= ~PF_WQ_WORKER;
2358 /* rescuers should never participate in concurrency management */
2359 WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2365 struct work_struct work;
2366 struct completion done;
2367 struct task_struct *task; /* purely informational */
2370 static void wq_barrier_func(struct work_struct *work)
2372 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2373 complete(&barr->done);
2377 * insert_wq_barrier - insert a barrier work
2378 * @pwq: pwq to insert barrier into
2379 * @barr: wq_barrier to insert
2380 * @target: target work to attach @barr to
2381 * @worker: worker currently executing @target, NULL if @target is not executing
2383 * @barr is linked to @target such that @barr is completed only after
2384 * @target finishes execution. Please note that the ordering
2385 * guarantee is observed only with respect to @target and on the local
2388 * Currently, a queued barrier can't be canceled. This is because
2389 * try_to_grab_pending() can't determine whether the work to be
2390 * grabbed is at the head of the queue and thus can't clear LINKED
2391 * flag of the previous work while there must be a valid next work
2392 * after a work with LINKED flag set.
2394 * Note that when @worker is non-NULL, @target may be modified
2395 * underneath us, so we can't reliably determine pwq from @target.
2398 * spin_lock_irq(pool->lock).
2400 static void insert_wq_barrier(struct pool_workqueue *pwq,
2401 struct wq_barrier *barr,
2402 struct work_struct *target, struct worker *worker)
2404 struct list_head *head;
2405 unsigned int linked = 0;
2408 * debugobject calls are safe here even with pool->lock locked
2409 * as we know for sure that this will not trigger any of the
2410 * checks and call back into the fixup functions where we
2413 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2414 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2415 init_completion(&barr->done);
2416 barr->task = current;
2419 * If @target is currently being executed, schedule the
2420 * barrier to the worker; otherwise, put it after @target.
2423 head = worker->scheduled.next;
2425 unsigned long *bits = work_data_bits(target);
2427 head = target->entry.next;
2428 /* there can already be other linked works, inherit and set */
2429 linked = *bits & WORK_STRUCT_LINKED;
2430 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2433 debug_work_activate(&barr->work);
2434 insert_work(pwq, &barr->work, head,
2435 work_color_to_flags(WORK_NO_COLOR) | linked);
2439 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
2440 * @wq: workqueue being flushed
2441 * @flush_color: new flush color, < 0 for no-op
2442 * @work_color: new work color, < 0 for no-op
2444 * Prepare pwqs for workqueue flushing.
2446 * If @flush_color is non-negative, flush_color on all pwqs should be
2447 * -1. If no pwq has in-flight commands at the specified color, all
2448 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
2449 * has in flight commands, its pwq->flush_color is set to
2450 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
2451 * wakeup logic is armed and %true is returned.
2453 * The caller should have initialized @wq->first_flusher prior to
2454 * calling this function with non-negative @flush_color. If
2455 * @flush_color is negative, no flush color update is done and %false
2458 * If @work_color is non-negative, all pwqs should have the same
2459 * work_color which is previous to @work_color and all will be
2460 * advanced to @work_color.
2463 * mutex_lock(wq->mutex).
2466 * %true if @flush_color >= 0 and there's something to flush. %false
2469 static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
2470 int flush_color, int work_color)
2473 struct pool_workqueue *pwq;
2475 if (flush_color >= 0) {
2476 WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2477 atomic_set(&wq->nr_pwqs_to_flush, 1);
2480 for_each_pwq(pwq, wq) {
2481 struct worker_pool *pool = pwq->pool;
2483 spin_lock_irq(&pool->lock);
2485 if (flush_color >= 0) {
2486 WARN_ON_ONCE(pwq->flush_color != -1);
2488 if (pwq->nr_in_flight[flush_color]) {
2489 pwq->flush_color = flush_color;
2490 atomic_inc(&wq->nr_pwqs_to_flush);
2495 if (work_color >= 0) {
2496 WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2497 pwq->work_color = work_color;
2500 spin_unlock_irq(&pool->lock);
2503 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
2504 complete(&wq->first_flusher->done);
2510 * flush_workqueue - ensure that any scheduled work has run to completion.
2511 * @wq: workqueue to flush
2513 * This function sleeps until all work items which were queued on entry
2514 * have finished execution, but it is not livelocked by new incoming ones.
2516 void flush_workqueue(struct workqueue_struct *wq)
2518 struct wq_flusher this_flusher = {
2519 .list = LIST_HEAD_INIT(this_flusher.list),
2521 .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
2525 lock_map_acquire(&wq->lockdep_map);
2526 lock_map_release(&wq->lockdep_map);
2528 mutex_lock(&wq->mutex);
2531 * Start-to-wait phase
2533 next_color = work_next_color(wq->work_color);
2535 if (next_color != wq->flush_color) {
2537 * Color space is not full. The current work_color
2538 * becomes our flush_color and work_color is advanced
2541 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
2542 this_flusher.flush_color = wq->work_color;
2543 wq->work_color = next_color;
2545 if (!wq->first_flusher) {
2546 /* no flush in progress, become the first flusher */
2547 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2549 wq->first_flusher = &this_flusher;
2551 if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
2553 /* nothing to flush, done */
2554 wq->flush_color = next_color;
2555 wq->first_flusher = NULL;
2560 WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
2561 list_add_tail(&this_flusher.list, &wq->flusher_queue);
2562 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2566 * Oops, color space is full, wait on overflow queue.
2567 * The next flush completion will assign us
2568 * flush_color and transfer to flusher_queue.
2570 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2573 mutex_unlock(&wq->mutex);
2575 wait_for_completion(&this_flusher.done);
2578 * Wake-up-and-cascade phase
2580 * First flushers are responsible for cascading flushes and
2581 * handling overflow. Non-first flushers can simply return.
2583 if (wq->first_flusher != &this_flusher)
2586 mutex_lock(&wq->mutex);
2588 /* we might have raced, check again with mutex held */
2589 if (wq->first_flusher != &this_flusher)
2592 wq->first_flusher = NULL;
2594 WARN_ON_ONCE(!list_empty(&this_flusher.list));
2595 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2598 struct wq_flusher *next, *tmp;
2600 /* complete all the flushers sharing the current flush color */
2601 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2602 if (next->flush_color != wq->flush_color)
2604 list_del_init(&next->list);
2605 complete(&next->done);
2608 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
2609 wq->flush_color != work_next_color(wq->work_color));
2611 /* this flush_color is finished, advance by one */
2612 wq->flush_color = work_next_color(wq->flush_color);
2614 /* one color has been freed, handle overflow queue */
2615 if (!list_empty(&wq->flusher_overflow)) {
2617 * Assign the same color to all overflowed
2618 * flushers, advance work_color and append to
2619 * flusher_queue. This is the start-to-wait
2620 * phase for these overflowed flushers.
2622 list_for_each_entry(tmp, &wq->flusher_overflow, list)
2623 tmp->flush_color = wq->work_color;
2625 wq->work_color = work_next_color(wq->work_color);
2627 list_splice_tail_init(&wq->flusher_overflow,
2628 &wq->flusher_queue);
2629 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2632 if (list_empty(&wq->flusher_queue)) {
2633 WARN_ON_ONCE(wq->flush_color != wq->work_color);
2638 * Need to flush more colors. Make the next flusher
2639 * the new first flusher and arm pwqs.
2641 WARN_ON_ONCE(wq->flush_color == wq->work_color);
2642 WARN_ON_ONCE(wq->flush_color != next->flush_color);
2644 list_del_init(&next->list);
2645 wq->first_flusher = next;
2647 if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
2651 * Meh... this color is already done, clear first
2652 * flusher and repeat cascading.
2654 wq->first_flusher = NULL;
2658 mutex_unlock(&wq->mutex);
2660 EXPORT_SYMBOL(flush_workqueue);
2663 * drain_workqueue - drain a workqueue
2664 * @wq: workqueue to drain
2666 * Wait until the workqueue becomes empty. While draining is in progress,
2667 * only chain queueing is allowed. IOW, only currently pending or running
2668 * work items on @wq can queue further work items on it. @wq is flushed
2669 * repeatedly until it becomes empty. The number of flushing is determined
2670 * by the depth of chaining and should be relatively short. Whine if it
2673 void drain_workqueue(struct workqueue_struct *wq)
2675 unsigned int flush_cnt = 0;
2676 struct pool_workqueue *pwq;
2679 * __queue_work() needs to test whether there are drainers, is much
2680 * hotter than drain_workqueue() and already looks at @wq->flags.
2681 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
2683 mutex_lock(&wq->mutex);
2684 if (!wq->nr_drainers++)
2685 wq->flags |= __WQ_DRAINING;
2686 mutex_unlock(&wq->mutex);
2688 flush_workqueue(wq);
2690 mutex_lock(&wq->mutex);
2692 for_each_pwq(pwq, wq) {
2695 spin_lock_irq(&pwq->pool->lock);
2696 drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
2697 spin_unlock_irq(&pwq->pool->lock);
2702 if (++flush_cnt == 10 ||
2703 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2704 pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
2705 wq->name, flush_cnt);
2707 mutex_unlock(&wq->mutex);
2711 if (!--wq->nr_drainers)
2712 wq->flags &= ~__WQ_DRAINING;
2713 mutex_unlock(&wq->mutex);
2715 EXPORT_SYMBOL_GPL(drain_workqueue);
2717 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2719 struct worker *worker = NULL;
2720 struct worker_pool *pool;
2721 struct pool_workqueue *pwq;
2726 pool = get_work_pool(work);
2732 spin_lock_irq(&pool->lock);
2733 /* see the comment in try_to_grab_pending() with the same code */
2734 pwq = get_work_pwq(work);
2736 if (unlikely(pwq->pool != pool))
2739 worker = find_worker_executing_work(pool, work);
2742 pwq = worker->current_pwq;
2745 insert_wq_barrier(pwq, barr, work, worker);
2746 spin_unlock_irq(&pool->lock);
2749 * If @max_active is 1 or rescuer is in use, flushing another work
2750 * item on the same workqueue may lead to deadlock. Make sure the
2751 * flusher is not running on the same workqueue by verifying write
2754 if (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)
2755 lock_map_acquire(&pwq->wq->lockdep_map);
2757 lock_map_acquire_read(&pwq->wq->lockdep_map);
2758 lock_map_release(&pwq->wq->lockdep_map);
2762 spin_unlock_irq(&pool->lock);
2768 * flush_work - wait for a work to finish executing the last queueing instance
2769 * @work: the work to flush
2771 * Wait until @work has finished execution. @work is guaranteed to be idle
2772 * on return if it hasn't been requeued since flush started.
2775 * %true if flush_work() waited for the work to finish execution,
2776 * %false if it was already idle.
2778 bool flush_work(struct work_struct *work)
2780 struct wq_barrier barr;
2782 lock_map_acquire(&work->lockdep_map);
2783 lock_map_release(&work->lockdep_map);
2785 if (start_flush_work(work, &barr)) {
2786 wait_for_completion(&barr.done);
2787 destroy_work_on_stack(&barr.work);
2793 EXPORT_SYMBOL_GPL(flush_work);
2797 struct work_struct *work;
2800 static int cwt_wakefn(wait_queue_t *wait, unsigned mode, int sync, void *key)
2802 struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
2804 if (cwait->work != key)
2806 return autoremove_wake_function(wait, mode, sync, key);
2809 static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2811 static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
2812 unsigned long flags;
2816 ret = try_to_grab_pending(work, is_dwork, &flags);
2818 * If someone else is already canceling, wait for it to
2819 * finish. flush_work() doesn't work for PREEMPT_NONE
2820 * because we may get scheduled between @work's completion
2821 * and the other canceling task resuming and clearing
2822 * CANCELING - flush_work() will return false immediately
2823 * as @work is no longer busy, try_to_grab_pending() will
2824 * return -ENOENT as @work is still being canceled and the
2825 * other canceling task won't be able to clear CANCELING as
2826 * we're hogging the CPU.
2828 * Let's wait for completion using a waitqueue. As this
2829 * may lead to the thundering herd problem, use a custom
2830 * wake function which matches @work along with exclusive
2833 if (unlikely(ret == -ENOENT)) {
2834 struct cwt_wait cwait;
2836 init_wait(&cwait.wait);
2837 cwait.wait.func = cwt_wakefn;
2840 prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
2841 TASK_UNINTERRUPTIBLE);
2842 if (work_is_canceling(work))
2844 finish_wait(&cancel_waitq, &cwait.wait);
2846 } while (unlikely(ret < 0));
2848 /* tell other tasks trying to grab @work to back off */
2849 mark_work_canceling(work);
2850 local_unlock_irqrestore(pendingb_lock, flags);
2853 clear_work_data(work);
2856 * Paired with prepare_to_wait() above so that either
2857 * waitqueue_active() is visible here or !work_is_canceling() is
2861 if (waitqueue_active(&cancel_waitq))
2862 __wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
2868 * cancel_work_sync - cancel a work and wait for it to finish
2869 * @work: the work to cancel
2871 * Cancel @work and wait for its execution to finish. This function
2872 * can be used even if the work re-queues itself or migrates to
2873 * another workqueue. On return from this function, @work is
2874 * guaranteed to be not pending or executing on any CPU.
2876 * cancel_work_sync(&delayed_work->work) must not be used for
2877 * delayed_work's. Use cancel_delayed_work_sync() instead.
2879 * The caller must ensure that the workqueue on which @work was last
2880 * queued can't be destroyed before this function returns.
2883 * %true if @work was pending, %false otherwise.
2885 bool cancel_work_sync(struct work_struct *work)
2887 return __cancel_work_timer(work, false);
2889 EXPORT_SYMBOL_GPL(cancel_work_sync);
2892 * flush_delayed_work - wait for a dwork to finish executing the last queueing
2893 * @dwork: the delayed work to flush
2895 * Delayed timer is cancelled and the pending work is queued for
2896 * immediate execution. Like flush_work(), this function only
2897 * considers the last queueing instance of @dwork.
2900 * %true if flush_work() waited for the work to finish execution,
2901 * %false if it was already idle.
2903 bool flush_delayed_work(struct delayed_work *dwork)
2905 local_lock_irq(pendingb_lock);
2906 if (del_timer_sync(&dwork->timer))
2907 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
2908 local_unlock_irq(pendingb_lock);
2909 return flush_work(&dwork->work);
2911 EXPORT_SYMBOL(flush_delayed_work);
2914 * cancel_delayed_work - cancel a delayed work
2915 * @dwork: delayed_work to cancel
2917 * Kill off a pending delayed_work.
2919 * Return: %true if @dwork was pending and canceled; %false if it wasn't
2923 * The work callback function may still be running on return, unless
2924 * it returns %true and the work doesn't re-arm itself. Explicitly flush or
2925 * use cancel_delayed_work_sync() to wait on it.
2927 * This function is safe to call from any context including IRQ handler.
2929 bool cancel_delayed_work(struct delayed_work *dwork)
2931 unsigned long flags;
2935 ret = try_to_grab_pending(&dwork->work, true, &flags);
2936 } while (unlikely(ret == -EAGAIN));
2938 if (unlikely(ret < 0))
2941 set_work_pool_and_clear_pending(&dwork->work,
2942 get_work_pool_id(&dwork->work));
2943 local_unlock_irqrestore(pendingb_lock, flags);
2946 EXPORT_SYMBOL(cancel_delayed_work);
2949 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2950 * @dwork: the delayed work cancel
2952 * This is cancel_work_sync() for delayed works.
2955 * %true if @dwork was pending, %false otherwise.
2957 bool cancel_delayed_work_sync(struct delayed_work *dwork)
2959 return __cancel_work_timer(&dwork->work, true);
2961 EXPORT_SYMBOL(cancel_delayed_work_sync);
2964 * schedule_on_each_cpu - execute a function synchronously on each online CPU
2965 * @func: the function to call
2967 * schedule_on_each_cpu() executes @func on each online CPU using the
2968 * system workqueue and blocks until all CPUs have completed.
2969 * schedule_on_each_cpu() is very slow.
2972 * 0 on success, -errno on failure.
2974 int schedule_on_each_cpu(work_func_t func)
2977 struct work_struct __percpu *works;
2979 works = alloc_percpu(struct work_struct);
2985 for_each_online_cpu(cpu) {
2986 struct work_struct *work = per_cpu_ptr(works, cpu);
2988 INIT_WORK(work, func);
2989 schedule_work_on(cpu, work);
2992 for_each_online_cpu(cpu)
2993 flush_work(per_cpu_ptr(works, cpu));
3001 * execute_in_process_context - reliably execute the routine with user context
3002 * @fn: the function to execute
3003 * @ew: guaranteed storage for the execute work structure (must
3004 * be available when the work executes)
3006 * Executes the function immediately if process context is available,
3007 * otherwise schedules the function for delayed execution.
3009 * Return: 0 - function was executed
3010 * 1 - function was scheduled for execution
3012 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
3014 if (!in_interrupt()) {
3019 INIT_WORK(&ew->work, fn);
3020 schedule_work(&ew->work);
3024 EXPORT_SYMBOL_GPL(execute_in_process_context);
3027 * free_workqueue_attrs - free a workqueue_attrs
3028 * @attrs: workqueue_attrs to free
3030 * Undo alloc_workqueue_attrs().
3032 void free_workqueue_attrs(struct workqueue_attrs *attrs)
3035 free_cpumask_var(attrs->cpumask);
3041 * alloc_workqueue_attrs - allocate a workqueue_attrs
3042 * @gfp_mask: allocation mask to use
3044 * Allocate a new workqueue_attrs, initialize with default settings and
3047 * Return: The allocated new workqueue_attr on success. %NULL on failure.
3049 struct workqueue_attrs *alloc_workqueue_attrs(gfp_t gfp_mask)
3051 struct workqueue_attrs *attrs;
3053 attrs = kzalloc(sizeof(*attrs), gfp_mask);
3056 if (!alloc_cpumask_var(&attrs->cpumask, gfp_mask))
3059 cpumask_copy(attrs->cpumask, cpu_possible_mask);
3062 free_workqueue_attrs(attrs);
3066 static void copy_workqueue_attrs(struct workqueue_attrs *to,
3067 const struct workqueue_attrs *from)
3069 to->nice = from->nice;
3070 cpumask_copy(to->cpumask, from->cpumask);
3072 * Unlike hash and equality test, this function doesn't ignore
3073 * ->no_numa as it is used for both pool and wq attrs. Instead,
3074 * get_unbound_pool() explicitly clears ->no_numa after copying.
3076 to->no_numa = from->no_numa;
3079 /* hash value of the content of @attr */
3080 static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
3084 hash = jhash_1word(attrs->nice, hash);
3085 hash = jhash(cpumask_bits(attrs->cpumask),
3086 BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
3090 /* content equality test */
3091 static bool wqattrs_equal(const struct workqueue_attrs *a,
3092 const struct workqueue_attrs *b)
3094 if (a->nice != b->nice)
3096 if (!cpumask_equal(a->cpumask, b->cpumask))
3102 * init_worker_pool - initialize a newly zalloc'd worker_pool
3103 * @pool: worker_pool to initialize
3105 * Initialize a newly zalloc'd @pool. It also allocates @pool->attrs.
3107 * Return: 0 on success, -errno on failure. Even on failure, all fields
3108 * inside @pool proper are initialized and put_unbound_pool() can be called
3109 * on @pool safely to release it.
3111 static int init_worker_pool(struct worker_pool *pool)
3113 spin_lock_init(&pool->lock);
3116 pool->node = NUMA_NO_NODE;
3117 pool->flags |= POOL_DISASSOCIATED;
3118 INIT_LIST_HEAD(&pool->worklist);
3119 INIT_LIST_HEAD(&pool->idle_list);
3120 hash_init(pool->busy_hash);
3122 init_timer_deferrable(&pool->idle_timer);
3123 pool->idle_timer.function = idle_worker_timeout;
3124 pool->idle_timer.data = (unsigned long)pool;
3126 setup_timer(&pool->mayday_timer, pool_mayday_timeout,
3127 (unsigned long)pool);
3129 mutex_init(&pool->manager_arb);
3130 mutex_init(&pool->attach_mutex);
3131 INIT_LIST_HEAD(&pool->workers);
3133 ida_init(&pool->worker_ida);
3134 INIT_HLIST_NODE(&pool->hash_node);
3137 /* shouldn't fail above this point */
3138 pool->attrs = alloc_workqueue_attrs(GFP_KERNEL);
3144 static void rcu_free_wq(struct rcu_head *rcu)
3146 struct workqueue_struct *wq =
3147 container_of(rcu, struct workqueue_struct, rcu);
3149 if (!(wq->flags & WQ_UNBOUND))
3150 free_percpu(wq->cpu_pwqs);
3152 free_workqueue_attrs(wq->unbound_attrs);
3158 static void rcu_free_pool(struct rcu_head *rcu)
3160 struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
3162 ida_destroy(&pool->worker_ida);
3163 free_workqueue_attrs(pool->attrs);
3168 * put_unbound_pool - put a worker_pool
3169 * @pool: worker_pool to put
3171 * Put @pool. If its refcnt reaches zero, it gets destroyed in RCU
3172 * safe manner. get_unbound_pool() calls this function on its failure path
3173 * and this function should be able to release pools which went through,
3174 * successfully or not, init_worker_pool().
3176 * Should be called with wq_pool_mutex held.
3178 static void put_unbound_pool(struct worker_pool *pool)
3180 DECLARE_COMPLETION_ONSTACK(detach_completion);
3181 struct worker *worker;
3183 lockdep_assert_held(&wq_pool_mutex);
3189 if (WARN_ON(!(pool->cpu < 0)) ||
3190 WARN_ON(!list_empty(&pool->worklist)))
3193 /* release id and unhash */
3195 idr_remove(&worker_pool_idr, pool->id);
3196 hash_del(&pool->hash_node);
3199 * Become the manager and destroy all workers. Grabbing
3200 * manager_arb prevents @pool's workers from blocking on
3203 mutex_lock(&pool->manager_arb);
3205 spin_lock_irq(&pool->lock);
3206 while ((worker = first_idle_worker(pool)))
3207 destroy_worker(worker);
3208 WARN_ON(pool->nr_workers || pool->nr_idle);
3209 spin_unlock_irq(&pool->lock);
3211 mutex_lock(&pool->attach_mutex);
3212 if (!list_empty(&pool->workers))
3213 pool->detach_completion = &detach_completion;
3214 mutex_unlock(&pool->attach_mutex);
3216 if (pool->detach_completion)
3217 wait_for_completion(pool->detach_completion);
3219 mutex_unlock(&pool->manager_arb);
3221 /* shut down the timers */
3222 del_timer_sync(&pool->idle_timer);
3223 del_timer_sync(&pool->mayday_timer);
3225 /* RCU protected to allow dereferences from get_work_pool() */
3226 call_rcu(&pool->rcu, rcu_free_pool);
3230 * get_unbound_pool - get a worker_pool with the specified attributes
3231 * @attrs: the attributes of the worker_pool to get
3233 * Obtain a worker_pool which has the same attributes as @attrs, bump the
3234 * reference count and return it. If there already is a matching
3235 * worker_pool, it will be used; otherwise, this function attempts to
3238 * Should be called with wq_pool_mutex held.
3240 * Return: On success, a worker_pool with the same attributes as @attrs.
3241 * On failure, %NULL.
3243 static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
3245 u32 hash = wqattrs_hash(attrs);
3246 struct worker_pool *pool;
3248 int target_node = NUMA_NO_NODE;
3250 lockdep_assert_held(&wq_pool_mutex);
3252 /* do we already have a matching pool? */
3253 hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
3254 if (wqattrs_equal(pool->attrs, attrs)) {
3260 /* if cpumask is contained inside a NUMA node, we belong to that node */
3261 if (wq_numa_enabled) {
3262 for_each_node(node) {
3263 if (cpumask_subset(attrs->cpumask,
3264 wq_numa_possible_cpumask[node])) {
3271 /* nope, create a new one */
3272 pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, target_node);
3273 if (!pool || init_worker_pool(pool) < 0)
3276 lockdep_set_subclass(&pool->lock, 1); /* see put_pwq() */
3277 copy_workqueue_attrs(pool->attrs, attrs);
3278 pool->node = target_node;
3281 * no_numa isn't a worker_pool attribute, always clear it. See
3282 * 'struct workqueue_attrs' comments for detail.
3284 pool->attrs->no_numa = false;
3286 if (worker_pool_assign_id(pool) < 0)
3289 /* create and start the initial worker */
3290 if (!create_worker(pool))
3294 hash_add(unbound_pool_hash, &pool->hash_node, hash);
3299 put_unbound_pool(pool);
3303 static void rcu_free_pwq(struct rcu_head *rcu)
3305 kmem_cache_free(pwq_cache,
3306 container_of(rcu, struct pool_workqueue, rcu));
3310 * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
3311 * and needs to be destroyed.
3313 static void pwq_unbound_release_workfn(struct work_struct *work)
3315 struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
3316 unbound_release_work);
3317 struct workqueue_struct *wq = pwq->wq;
3318 struct worker_pool *pool = pwq->pool;
3321 if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
3324 mutex_lock(&wq->mutex);
3325 list_del_rcu(&pwq->pwqs_node);
3326 is_last = list_empty(&wq->pwqs);
3327 mutex_unlock(&wq->mutex);
3329 mutex_lock(&wq_pool_mutex);
3330 put_unbound_pool(pool);
3331 mutex_unlock(&wq_pool_mutex);
3333 call_rcu(&pwq->rcu, rcu_free_pwq);
3336 * If we're the last pwq going away, @wq is already dead and no one
3337 * is gonna access it anymore. Schedule RCU free.
3340 call_rcu(&wq->rcu, rcu_free_wq);
3344 * pwq_adjust_max_active - update a pwq's max_active to the current setting
3345 * @pwq: target pool_workqueue
3347 * If @pwq isn't freezing, set @pwq->max_active to the associated
3348 * workqueue's saved_max_active and activate delayed work items
3349 * accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
3351 static void pwq_adjust_max_active(struct pool_workqueue *pwq)
3353 struct workqueue_struct *wq = pwq->wq;
3354 bool freezable = wq->flags & WQ_FREEZABLE;
3356 /* for @wq->saved_max_active */
3357 lockdep_assert_held(&wq->mutex);
3359 /* fast exit for non-freezable wqs */
3360 if (!freezable && pwq->max_active == wq->saved_max_active)
3363 spin_lock_irq(&pwq->pool->lock);
3366 * During [un]freezing, the caller is responsible for ensuring that
3367 * this function is called at least once after @workqueue_freezing
3368 * is updated and visible.
3370 if (!freezable || !workqueue_freezing) {
3371 pwq->max_active = wq->saved_max_active;
3373 while (!list_empty(&pwq->delayed_works) &&
3374 pwq->nr_active < pwq->max_active)
3375 pwq_activate_first_delayed(pwq);
3378 * Need to kick a worker after thawed or an unbound wq's
3379 * max_active is bumped. It's a slow path. Do it always.
3381 wake_up_worker(pwq->pool);
3383 pwq->max_active = 0;
3386 spin_unlock_irq(&pwq->pool->lock);
3389 /* initialize newly alloced @pwq which is associated with @wq and @pool */
3390 static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
3391 struct worker_pool *pool)
3393 BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3395 memset(pwq, 0, sizeof(*pwq));
3399 pwq->flush_color = -1;
3401 INIT_LIST_HEAD(&pwq->delayed_works);
3402 INIT_LIST_HEAD(&pwq->pwqs_node);
3403 INIT_LIST_HEAD(&pwq->mayday_node);
3404 INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
3407 /* sync @pwq with the current state of its associated wq and link it */
3408 static void link_pwq(struct pool_workqueue *pwq)
3410 struct workqueue_struct *wq = pwq->wq;
3412 lockdep_assert_held(&wq->mutex);
3414 /* may be called multiple times, ignore if already linked */
3415 if (!list_empty(&pwq->pwqs_node))
3418 /* set the matching work_color */
3419 pwq->work_color = wq->work_color;
3421 /* sync max_active to the current setting */
3422 pwq_adjust_max_active(pwq);
3425 list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
3428 /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
3429 static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
3430 const struct workqueue_attrs *attrs)
3432 struct worker_pool *pool;
3433 struct pool_workqueue *pwq;
3435 lockdep_assert_held(&wq_pool_mutex);
3437 pool = get_unbound_pool(attrs);
3441 pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
3443 put_unbound_pool(pool);
3447 init_pwq(pwq, wq, pool);
3452 * wq_calc_node_cpumask - calculate a wq_attrs' cpumask for the specified node
3453 * @attrs: the wq_attrs of the default pwq of the target workqueue
3454 * @node: the target NUMA node
3455 * @cpu_going_down: if >= 0, the CPU to consider as offline
3456 * @cpumask: outarg, the resulting cpumask
3458 * Calculate the cpumask a workqueue with @attrs should use on @node. If
3459 * @cpu_going_down is >= 0, that cpu is considered offline during
3460 * calculation. The result is stored in @cpumask.
3462 * If NUMA affinity is not enabled, @attrs->cpumask is always used. If
3463 * enabled and @node has online CPUs requested by @attrs, the returned
3464 * cpumask is the intersection of the possible CPUs of @node and
3467 * The caller is responsible for ensuring that the cpumask of @node stays
3470 * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
3473 static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
3474 int cpu_going_down, cpumask_t *cpumask)
3476 if (!wq_numa_enabled || attrs->no_numa)
3479 /* does @node have any online CPUs @attrs wants? */
3480 cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
3481 if (cpu_going_down >= 0)
3482 cpumask_clear_cpu(cpu_going_down, cpumask);
3484 if (cpumask_empty(cpumask))
3487 /* yeap, return possible CPUs in @node that @attrs wants */
3488 cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
3489 return !cpumask_equal(cpumask, attrs->cpumask);
3492 cpumask_copy(cpumask, attrs->cpumask);
3496 /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
3497 static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
3499 struct pool_workqueue *pwq)
3501 struct pool_workqueue *old_pwq;
3503 lockdep_assert_held(&wq_pool_mutex);
3504 lockdep_assert_held(&wq->mutex);
3506 /* link_pwq() can handle duplicate calls */
3509 old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
3510 rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
3514 /* context to store the prepared attrs & pwqs before applying */
3515 struct apply_wqattrs_ctx {
3516 struct workqueue_struct *wq; /* target workqueue */
3517 struct workqueue_attrs *attrs; /* attrs to apply */
3518 struct list_head list; /* queued for batching commit */
3519 struct pool_workqueue *dfl_pwq;
3520 struct pool_workqueue *pwq_tbl[];
3523 /* free the resources after success or abort */
3524 static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
3530 put_pwq_unlocked(ctx->pwq_tbl[node]);
3531 put_pwq_unlocked(ctx->dfl_pwq);
3533 free_workqueue_attrs(ctx->attrs);
3539 /* allocate the attrs and pwqs for later installation */
3540 static struct apply_wqattrs_ctx *
3541 apply_wqattrs_prepare(struct workqueue_struct *wq,
3542 const struct workqueue_attrs *attrs)
3544 struct apply_wqattrs_ctx *ctx;
3545 struct workqueue_attrs *new_attrs, *tmp_attrs;
3548 lockdep_assert_held(&wq_pool_mutex);
3550 ctx = kzalloc(sizeof(*ctx) + nr_node_ids * sizeof(ctx->pwq_tbl[0]),
3553 new_attrs = alloc_workqueue_attrs(GFP_KERNEL);
3554 tmp_attrs = alloc_workqueue_attrs(GFP_KERNEL);
3555 if (!ctx || !new_attrs || !tmp_attrs)
3559 * Calculate the attrs of the default pwq.
3560 * If the user configured cpumask doesn't overlap with the
3561 * wq_unbound_cpumask, we fallback to the wq_unbound_cpumask.
3563 copy_workqueue_attrs(new_attrs, attrs);
3564 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, wq_unbound_cpumask);
3565 if (unlikely(cpumask_empty(new_attrs->cpumask)))
3566 cpumask_copy(new_attrs->cpumask, wq_unbound_cpumask);
3569 * We may create multiple pwqs with differing cpumasks. Make a
3570 * copy of @new_attrs which will be modified and used to obtain
3573 copy_workqueue_attrs(tmp_attrs, new_attrs);
3576 * If something goes wrong during CPU up/down, we'll fall back to
3577 * the default pwq covering whole @attrs->cpumask. Always create
3578 * it even if we don't use it immediately.
3580 ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
3584 for_each_node(node) {
3585 if (wq_calc_node_cpumask(new_attrs, node, -1, tmp_attrs->cpumask)) {
3586 ctx->pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
3587 if (!ctx->pwq_tbl[node])
3590 ctx->dfl_pwq->refcnt++;
3591 ctx->pwq_tbl[node] = ctx->dfl_pwq;
3595 /* save the user configured attrs and sanitize it. */
3596 copy_workqueue_attrs(new_attrs, attrs);
3597 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
3598 ctx->attrs = new_attrs;
3601 free_workqueue_attrs(tmp_attrs);
3605 free_workqueue_attrs(tmp_attrs);
3606 free_workqueue_attrs(new_attrs);
3607 apply_wqattrs_cleanup(ctx);
3611 /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
3612 static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
3616 /* all pwqs have been created successfully, let's install'em */
3617 mutex_lock(&ctx->wq->mutex);
3619 copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
3621 /* save the previous pwq and install the new one */
3623 ctx->pwq_tbl[node] = numa_pwq_tbl_install(ctx->wq, node,
3624 ctx->pwq_tbl[node]);
3626 /* @dfl_pwq might not have been used, ensure it's linked */
3627 link_pwq(ctx->dfl_pwq);
3628 swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
3630 mutex_unlock(&ctx->wq->mutex);
3633 static void apply_wqattrs_lock(void)
3635 /* CPUs should stay stable across pwq creations and installations */
3637 mutex_lock(&wq_pool_mutex);
3640 static void apply_wqattrs_unlock(void)
3642 mutex_unlock(&wq_pool_mutex);
3646 static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
3647 const struct workqueue_attrs *attrs)
3649 struct apply_wqattrs_ctx *ctx;
3652 /* only unbound workqueues can change attributes */
3653 if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
3656 /* creating multiple pwqs breaks ordering guarantee */
3657 if (WARN_ON((wq->flags & __WQ_ORDERED) && !list_empty(&wq->pwqs)))
3660 ctx = apply_wqattrs_prepare(wq, attrs);
3662 /* the ctx has been prepared successfully, let's commit it */
3664 apply_wqattrs_commit(ctx);
3668 apply_wqattrs_cleanup(ctx);
3674 * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
3675 * @wq: the target workqueue
3676 * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
3678 * Apply @attrs to an unbound workqueue @wq. Unless disabled, on NUMA
3679 * machines, this function maps a separate pwq to each NUMA node with
3680 * possibles CPUs in @attrs->cpumask so that work items are affine to the
3681 * NUMA node it was issued on. Older pwqs are released as in-flight work
3682 * items finish. Note that a work item which repeatedly requeues itself
3683 * back-to-back will stay on its current pwq.
3685 * Performs GFP_KERNEL allocations.
3687 * Return: 0 on success and -errno on failure.
3689 int apply_workqueue_attrs(struct workqueue_struct *wq,
3690 const struct workqueue_attrs *attrs)
3694 apply_wqattrs_lock();
3695 ret = apply_workqueue_attrs_locked(wq, attrs);
3696 apply_wqattrs_unlock();
3702 * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
3703 * @wq: the target workqueue
3704 * @cpu: the CPU coming up or going down
3705 * @online: whether @cpu is coming up or going down
3707 * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
3708 * %CPU_DOWN_FAILED. @cpu is being hot[un]plugged, update NUMA affinity of
3711 * If NUMA affinity can't be adjusted due to memory allocation failure, it
3712 * falls back to @wq->dfl_pwq which may not be optimal but is always
3715 * Note that when the last allowed CPU of a NUMA node goes offline for a
3716 * workqueue with a cpumask spanning multiple nodes, the workers which were
3717 * already executing the work items for the workqueue will lose their CPU
3718 * affinity and may execute on any CPU. This is similar to how per-cpu
3719 * workqueues behave on CPU_DOWN. If a workqueue user wants strict
3720 * affinity, it's the user's responsibility to flush the work item from
3723 static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
3726 int node = cpu_to_node(cpu);
3727 int cpu_off = online ? -1 : cpu;
3728 struct pool_workqueue *old_pwq = NULL, *pwq;
3729 struct workqueue_attrs *target_attrs;
3732 lockdep_assert_held(&wq_pool_mutex);
3734 if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND) ||
3735 wq->unbound_attrs->no_numa)
3739 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
3740 * Let's use a preallocated one. The following buf is protected by
3741 * CPU hotplug exclusion.
3743 target_attrs = wq_update_unbound_numa_attrs_buf;
3744 cpumask = target_attrs->cpumask;
3746 copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
3747 pwq = unbound_pwq_by_node(wq, node);
3750 * Let's determine what needs to be done. If the target cpumask is
3751 * different from the default pwq's, we need to compare it to @pwq's
3752 * and create a new one if they don't match. If the target cpumask
3753 * equals the default pwq's, the default pwq should be used.
3755 if (wq_calc_node_cpumask(wq->dfl_pwq->pool->attrs, node, cpu_off, cpumask)) {
3756 if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
3762 /* create a new pwq */
3763 pwq = alloc_unbound_pwq(wq, target_attrs);
3765 pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
3770 /* Install the new pwq. */
3771 mutex_lock(&wq->mutex);
3772 old_pwq = numa_pwq_tbl_install(wq, node, pwq);
3776 mutex_lock(&wq->mutex);
3777 spin_lock_irq(&wq->dfl_pwq->pool->lock);
3778 get_pwq(wq->dfl_pwq);
3779 spin_unlock_irq(&wq->dfl_pwq->pool->lock);
3780 old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
3782 mutex_unlock(&wq->mutex);
3783 put_pwq_unlocked(old_pwq);
3786 static int alloc_and_link_pwqs(struct workqueue_struct *wq)
3788 bool highpri = wq->flags & WQ_HIGHPRI;
3791 if (!(wq->flags & WQ_UNBOUND)) {
3792 wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
3796 for_each_possible_cpu(cpu) {
3797 struct pool_workqueue *pwq =
3798 per_cpu_ptr(wq->cpu_pwqs, cpu);
3799 struct worker_pool *cpu_pools =
3800 per_cpu(cpu_worker_pools, cpu);
3802 init_pwq(pwq, wq, &cpu_pools[highpri]);
3804 mutex_lock(&wq->mutex);
3806 mutex_unlock(&wq->mutex);
3809 } else if (wq->flags & __WQ_ORDERED) {
3810 ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
3811 /* there should only be single pwq for ordering guarantee */
3812 WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
3813 wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
3814 "ordering guarantee broken for workqueue %s\n", wq->name);
3817 return apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
3821 static int wq_clamp_max_active(int max_active, unsigned int flags,
3824 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3826 if (max_active < 1 || max_active > lim)
3827 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3828 max_active, name, 1, lim);
3830 return clamp_val(max_active, 1, lim);
3833 struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
3836 struct lock_class_key *key,
3837 const char *lock_name, ...)
3839 size_t tbl_size = 0;
3841 struct workqueue_struct *wq;
3842 struct pool_workqueue *pwq;
3844 /* see the comment above the definition of WQ_POWER_EFFICIENT */
3845 if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
3846 flags |= WQ_UNBOUND;
3848 /* allocate wq and format name */
3849 if (flags & WQ_UNBOUND)
3850 tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
3852 wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
3856 if (flags & WQ_UNBOUND) {
3857 wq->unbound_attrs = alloc_workqueue_attrs(GFP_KERNEL);
3858 if (!wq->unbound_attrs)
3862 va_start(args, lock_name);
3863 vsnprintf(wq->name, sizeof(wq->name), fmt, args);
3866 max_active = max_active ?: WQ_DFL_ACTIVE;
3867 max_active = wq_clamp_max_active(max_active, flags, wq->name);
3871 wq->saved_max_active = max_active;
3872 mutex_init(&wq->mutex);
3873 atomic_set(&wq->nr_pwqs_to_flush, 0);
3874 INIT_LIST_HEAD(&wq->pwqs);
3875 INIT_LIST_HEAD(&wq->flusher_queue);
3876 INIT_LIST_HEAD(&wq->flusher_overflow);
3877 INIT_LIST_HEAD(&wq->maydays);
3879 lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3880 INIT_LIST_HEAD(&wq->list);
3882 if (alloc_and_link_pwqs(wq) < 0)
3886 * Workqueues which may be used during memory reclaim should
3887 * have a rescuer to guarantee forward progress.
3889 if (flags & WQ_MEM_RECLAIM) {
3890 struct worker *rescuer;
3892 rescuer = alloc_worker(NUMA_NO_NODE);
3896 rescuer->rescue_wq = wq;
3897 rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
3899 if (IS_ERR(rescuer->task)) {
3904 wq->rescuer = rescuer;
3905 kthread_bind_mask(rescuer->task, cpu_possible_mask);
3906 wake_up_process(rescuer->task);
3909 if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
3913 * wq_pool_mutex protects global freeze state and workqueues list.
3914 * Grab it, adjust max_active and add the new @wq to workqueues
3917 mutex_lock(&wq_pool_mutex);
3919 mutex_lock(&wq->mutex);
3920 for_each_pwq(pwq, wq)
3921 pwq_adjust_max_active(pwq);
3922 mutex_unlock(&wq->mutex);
3924 list_add_tail_rcu(&wq->list, &workqueues);
3926 mutex_unlock(&wq_pool_mutex);
3931 free_workqueue_attrs(wq->unbound_attrs);
3935 destroy_workqueue(wq);
3938 EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
3941 * destroy_workqueue - safely terminate a workqueue
3942 * @wq: target workqueue
3944 * Safely destroy a workqueue. All work currently pending will be done first.
3946 void destroy_workqueue(struct workqueue_struct *wq)
3948 struct pool_workqueue *pwq;
3951 /* drain it before proceeding with destruction */
3952 drain_workqueue(wq);
3955 mutex_lock(&wq->mutex);
3956 for_each_pwq(pwq, wq) {
3959 for (i = 0; i < WORK_NR_COLORS; i++) {
3960 if (WARN_ON(pwq->nr_in_flight[i])) {
3961 mutex_unlock(&wq->mutex);
3966 if (WARN_ON((pwq != wq->dfl_pwq) && (pwq->refcnt > 1)) ||
3967 WARN_ON(pwq->nr_active) ||
3968 WARN_ON(!list_empty(&pwq->delayed_works))) {
3969 mutex_unlock(&wq->mutex);
3973 mutex_unlock(&wq->mutex);
3976 * wq list is used to freeze wq, remove from list after
3977 * flushing is complete in case freeze races us.
3979 mutex_lock(&wq_pool_mutex);
3980 list_del_rcu(&wq->list);
3981 mutex_unlock(&wq_pool_mutex);
3983 workqueue_sysfs_unregister(wq);
3986 kthread_stop(wq->rescuer->task);
3988 if (!(wq->flags & WQ_UNBOUND)) {
3990 * The base ref is never dropped on per-cpu pwqs. Directly
3991 * schedule RCU free.
3993 call_rcu(&wq->rcu, rcu_free_wq);
3996 * We're the sole accessor of @wq at this point. Directly
3997 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
3998 * @wq will be freed when the last pwq is released.
4000 for_each_node(node) {
4001 pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
4002 RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
4003 put_pwq_unlocked(pwq);
4007 * Put dfl_pwq. @wq may be freed any time after dfl_pwq is
4008 * put. Don't access it afterwards.
4012 put_pwq_unlocked(pwq);
4015 EXPORT_SYMBOL_GPL(destroy_workqueue);
4018 * workqueue_set_max_active - adjust max_active of a workqueue
4019 * @wq: target workqueue
4020 * @max_active: new max_active value.
4022 * Set max_active of @wq to @max_active.
4025 * Don't call from IRQ context.
4027 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4029 struct pool_workqueue *pwq;
4031 /* disallow meddling with max_active for ordered workqueues */
4032 if (WARN_ON(wq->flags & __WQ_ORDERED))
4035 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4037 mutex_lock(&wq->mutex);
4039 wq->saved_max_active = max_active;
4041 for_each_pwq(pwq, wq)
4042 pwq_adjust_max_active(pwq);
4044 mutex_unlock(&wq->mutex);
4046 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4049 * current_is_workqueue_rescuer - is %current workqueue rescuer?
4051 * Determine whether %current is a workqueue rescuer. Can be used from
4052 * work functions to determine whether it's being run off the rescuer task.
4054 * Return: %true if %current is a workqueue rescuer. %false otherwise.
4056 bool current_is_workqueue_rescuer(void)
4058 struct worker *worker = current_wq_worker();
4060 return worker && worker->rescue_wq;
4064 * workqueue_congested - test whether a workqueue is congested
4065 * @cpu: CPU in question
4066 * @wq: target workqueue
4068 * Test whether @wq's cpu workqueue for @cpu is congested. There is
4069 * no synchronization around this function and the test result is
4070 * unreliable and only useful as advisory hints or for debugging.
4072 * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4073 * Note that both per-cpu and unbound workqueues may be associated with
4074 * multiple pool_workqueues which have separate congested states. A
4075 * workqueue being congested on one CPU doesn't mean the workqueue is also
4076 * contested on other CPUs / NUMA nodes.
4079 * %true if congested, %false otherwise.
4081 bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4083 struct pool_workqueue *pwq;
4089 if (cpu == WORK_CPU_UNBOUND)
4090 cpu = smp_processor_id();
4092 if (!(wq->flags & WQ_UNBOUND))
4093 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
4095 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4097 ret = !list_empty(&pwq->delayed_works);
4103 EXPORT_SYMBOL_GPL(workqueue_congested);
4106 * work_busy - test whether a work is currently pending or running
4107 * @work: the work to be tested
4109 * Test whether @work is currently pending or running. There is no
4110 * synchronization around this function and the test result is
4111 * unreliable and only useful as advisory hints or for debugging.
4114 * OR'd bitmask of WORK_BUSY_* bits.
4116 unsigned int work_busy(struct work_struct *work)
4118 struct worker_pool *pool;
4119 unsigned long flags;
4120 unsigned int ret = 0;
4122 if (work_pending(work))
4123 ret |= WORK_BUSY_PENDING;
4126 pool = get_work_pool(work);
4128 spin_lock_irqsave(&pool->lock, flags);
4129 if (find_worker_executing_work(pool, work))
4130 ret |= WORK_BUSY_RUNNING;
4131 spin_unlock_irqrestore(&pool->lock, flags);
4137 EXPORT_SYMBOL_GPL(work_busy);
4140 * set_worker_desc - set description for the current work item
4141 * @fmt: printf-style format string
4142 * @...: arguments for the format string
4144 * This function can be called by a running work function to describe what
4145 * the work item is about. If the worker task gets dumped, this
4146 * information will be printed out together to help debugging. The
4147 * description can be at most WORKER_DESC_LEN including the trailing '\0'.
4149 void set_worker_desc(const char *fmt, ...)
4151 struct worker *worker = current_wq_worker();
4155 va_start(args, fmt);
4156 vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
4158 worker->desc_valid = true;
4163 * print_worker_info - print out worker information and description
4164 * @log_lvl: the log level to use when printing
4165 * @task: target task
4167 * If @task is a worker and currently executing a work item, print out the
4168 * name of the workqueue being serviced and worker description set with
4169 * set_worker_desc() by the currently executing work item.
4171 * This function can be safely called on any task as long as the
4172 * task_struct itself is accessible. While safe, this function isn't
4173 * synchronized and may print out mixups or garbages of limited length.
4175 void print_worker_info(const char *log_lvl, struct task_struct *task)
4177 work_func_t *fn = NULL;
4178 char name[WQ_NAME_LEN] = { };
4179 char desc[WORKER_DESC_LEN] = { };
4180 struct pool_workqueue *pwq = NULL;
4181 struct workqueue_struct *wq = NULL;
4182 bool desc_valid = false;
4183 struct worker *worker;
4185 if (!(task->flags & PF_WQ_WORKER))
4189 * This function is called without any synchronization and @task
4190 * could be in any state. Be careful with dereferences.
4192 worker = probe_kthread_data(task);
4195 * Carefully copy the associated workqueue's workfn and name. Keep
4196 * the original last '\0' in case the original contains garbage.
4198 probe_kernel_read(&fn, &worker->current_func, sizeof(fn));
4199 probe_kernel_read(&pwq, &worker->current_pwq, sizeof(pwq));
4200 probe_kernel_read(&wq, &pwq->wq, sizeof(wq));
4201 probe_kernel_read(name, wq->name, sizeof(name) - 1);
4203 /* copy worker description */
4204 probe_kernel_read(&desc_valid, &worker->desc_valid, sizeof(desc_valid));
4206 probe_kernel_read(desc, worker->desc, sizeof(desc) - 1);
4208 if (fn || name[0] || desc[0]) {
4209 printk("%sWorkqueue: %s %pf", log_lvl, name, fn);
4211 pr_cont(" (%s)", desc);
4216 static void pr_cont_pool_info(struct worker_pool *pool)
4218 pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
4219 if (pool->node != NUMA_NO_NODE)
4220 pr_cont(" node=%d", pool->node);
4221 pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
4224 static void pr_cont_work(bool comma, struct work_struct *work)
4226 if (work->func == wq_barrier_func) {
4227 struct wq_barrier *barr;
4229 barr = container_of(work, struct wq_barrier, work);
4231 pr_cont("%s BAR(%d)", comma ? "," : "",
4232 task_pid_nr(barr->task));
4234 pr_cont("%s %pf", comma ? "," : "", work->func);
4238 static void show_pwq(struct pool_workqueue *pwq)
4240 struct worker_pool *pool = pwq->pool;
4241 struct work_struct *work;
4242 struct worker *worker;
4243 bool has_in_flight = false, has_pending = false;
4246 pr_info(" pwq %d:", pool->id);
4247 pr_cont_pool_info(pool);
4249 pr_cont(" active=%d/%d%s\n", pwq->nr_active, pwq->max_active,
4250 !list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
4252 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
4253 if (worker->current_pwq == pwq) {
4254 has_in_flight = true;
4258 if (has_in_flight) {
4261 pr_info(" in-flight:");
4262 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
4263 if (worker->current_pwq != pwq)
4266 pr_cont("%s %d%s:%pf", comma ? "," : "",
4267 task_pid_nr(worker->task),
4268 worker == pwq->wq->rescuer ? "(RESCUER)" : "",
4269 worker->current_func);
4270 list_for_each_entry(work, &worker->scheduled, entry)
4271 pr_cont_work(false, work);
4277 list_for_each_entry(work, &pool->worklist, entry) {
4278 if (get_work_pwq(work) == pwq) {
4286 pr_info(" pending:");
4287 list_for_each_entry(work, &pool->worklist, entry) {
4288 if (get_work_pwq(work) != pwq)
4291 pr_cont_work(comma, work);
4292 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
4297 if (!list_empty(&pwq->delayed_works)) {
4300 pr_info(" delayed:");
4301 list_for_each_entry(work, &pwq->delayed_works, entry) {
4302 pr_cont_work(comma, work);
4303 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
4310 * show_workqueue_state - dump workqueue state
4312 * Called from a sysrq handler and prints out all busy workqueues and
4315 void show_workqueue_state(void)
4317 struct workqueue_struct *wq;
4318 struct worker_pool *pool;
4319 unsigned long flags;
4324 pr_info("Showing busy workqueues and worker pools:\n");
4326 list_for_each_entry_rcu(wq, &workqueues, list) {
4327 struct pool_workqueue *pwq;
4330 for_each_pwq(pwq, wq) {
4331 if (pwq->nr_active || !list_empty(&pwq->delayed_works)) {
4339 pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
4341 for_each_pwq(pwq, wq) {
4342 spin_lock_irqsave(&pwq->pool->lock, flags);
4343 if (pwq->nr_active || !list_empty(&pwq->delayed_works))
4345 spin_unlock_irqrestore(&pwq->pool->lock, flags);
4349 for_each_pool(pool, pi) {
4350 struct worker *worker;
4353 spin_lock_irqsave(&pool->lock, flags);
4354 if (pool->nr_workers == pool->nr_idle)
4357 pr_info("pool %d:", pool->id);
4358 pr_cont_pool_info(pool);
4359 pr_cont(" workers=%d", pool->nr_workers);
4361 pr_cont(" manager: %d",
4362 task_pid_nr(pool->manager->task));
4363 list_for_each_entry(worker, &pool->idle_list, entry) {
4364 pr_cont(" %s%d", first ? "idle: " : "",
4365 task_pid_nr(worker->task));
4370 spin_unlock_irqrestore(&pool->lock, flags);
4379 * There are two challenges in supporting CPU hotplug. Firstly, there
4380 * are a lot of assumptions on strong associations among work, pwq and
4381 * pool which make migrating pending and scheduled works very
4382 * difficult to implement without impacting hot paths. Secondly,
4383 * worker pools serve mix of short, long and very long running works making
4384 * blocked draining impractical.
4386 * This is solved by allowing the pools to be disassociated from the CPU
4387 * running as an unbound one and allowing it to be reattached later if the
4388 * cpu comes back online.
4391 static void wq_unbind_fn(struct work_struct *work)
4393 int cpu = smp_processor_id();
4394 struct worker_pool *pool;
4395 struct worker *worker;
4397 for_each_cpu_worker_pool(pool, cpu) {
4398 mutex_lock(&pool->attach_mutex);
4399 spin_lock_irq(&pool->lock);
4402 * We've blocked all attach/detach operations. Make all workers
4403 * unbound and set DISASSOCIATED. Before this, all workers
4404 * except for the ones which are still executing works from
4405 * before the last CPU down must be on the cpu. After
4406 * this, they may become diasporas.
4408 for_each_pool_worker(worker, pool)
4409 worker->flags |= WORKER_UNBOUND;
4411 pool->flags |= POOL_DISASSOCIATED;
4413 spin_unlock_irq(&pool->lock);
4414 mutex_unlock(&pool->attach_mutex);
4417 * Call schedule() so that we cross rq->lock and thus can
4418 * guarantee sched callbacks see the %WORKER_UNBOUND flag.
4419 * This is necessary as scheduler callbacks may be invoked
4425 * Sched callbacks are disabled now. Zap nr_running.
4426 * After this, nr_running stays zero and need_more_worker()
4427 * and keep_working() are always true as long as the
4428 * worklist is not empty. This pool now behaves as an
4429 * unbound (in terms of concurrency management) pool which
4430 * are served by workers tied to the pool.
4432 atomic_set(&pool->nr_running, 0);
4435 * With concurrency management just turned off, a busy
4436 * worker blocking could lead to lengthy stalls. Kick off
4437 * unbound chain execution of currently pending work items.
4439 spin_lock_irq(&pool->lock);
4440 wake_up_worker(pool);
4441 spin_unlock_irq(&pool->lock);
4446 * rebind_workers - rebind all workers of a pool to the associated CPU
4447 * @pool: pool of interest
4449 * @pool->cpu is coming online. Rebind all workers to the CPU.
4451 static void rebind_workers(struct worker_pool *pool)
4453 struct worker *worker;
4455 lockdep_assert_held(&pool->attach_mutex);
4458 * Restore CPU affinity of all workers. As all idle workers should
4459 * be on the run-queue of the associated CPU before any local
4460 * wake-ups for concurrency management happen, restore CPU affinity
4461 * of all workers first and then clear UNBOUND. As we're called
4462 * from CPU_ONLINE, the following shouldn't fail.
4464 for_each_pool_worker(worker, pool)
4465 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4466 pool->attrs->cpumask) < 0);
4468 spin_lock_irq(&pool->lock);
4469 pool->flags &= ~POOL_DISASSOCIATED;
4471 for_each_pool_worker(worker, pool) {
4472 unsigned int worker_flags = worker->flags;
4475 * A bound idle worker should actually be on the runqueue
4476 * of the associated CPU for local wake-ups targeting it to
4477 * work. Kick all idle workers so that they migrate to the
4478 * associated CPU. Doing this in the same loop as
4479 * replacing UNBOUND with REBOUND is safe as no worker will
4480 * be bound before @pool->lock is released.
4482 if (worker_flags & WORKER_IDLE)
4483 wake_up_process(worker->task);
4486 * We want to clear UNBOUND but can't directly call
4487 * worker_clr_flags() or adjust nr_running. Atomically
4488 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
4489 * @worker will clear REBOUND using worker_clr_flags() when
4490 * it initiates the next execution cycle thus restoring
4491 * concurrency management. Note that when or whether
4492 * @worker clears REBOUND doesn't affect correctness.
4494 * ACCESS_ONCE() is necessary because @worker->flags may be
4495 * tested without holding any lock in
4496 * wq_worker_waking_up(). Without it, NOT_RUNNING test may
4497 * fail incorrectly leading to premature concurrency
4498 * management operations.
4500 WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
4501 worker_flags |= WORKER_REBOUND;
4502 worker_flags &= ~WORKER_UNBOUND;
4503 ACCESS_ONCE(worker->flags) = worker_flags;
4506 spin_unlock_irq(&pool->lock);
4510 * restore_unbound_workers_cpumask - restore cpumask of unbound workers
4511 * @pool: unbound pool of interest
4512 * @cpu: the CPU which is coming up
4514 * An unbound pool may end up with a cpumask which doesn't have any online
4515 * CPUs. When a worker of such pool get scheduled, the scheduler resets
4516 * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
4517 * online CPU before, cpus_allowed of all its workers should be restored.
4519 static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
4521 static cpumask_t cpumask;
4522 struct worker *worker;
4524 lockdep_assert_held(&pool->attach_mutex);
4526 /* is @cpu allowed for @pool? */
4527 if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
4530 /* is @cpu the only online CPU? */
4531 cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
4532 if (cpumask_weight(&cpumask) != 1)
4535 /* as we're called from CPU_ONLINE, the following shouldn't fail */
4536 for_each_pool_worker(worker, pool)
4537 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4538 pool->attrs->cpumask) < 0);
4542 * Workqueues should be brought up before normal priority CPU notifiers.
4543 * This will be registered high priority CPU notifier.
4545 static int workqueue_cpu_up_callback(struct notifier_block *nfb,
4546 unsigned long action,
4549 int cpu = (unsigned long)hcpu;
4550 struct worker_pool *pool;
4551 struct workqueue_struct *wq;
4554 switch (action & ~CPU_TASKS_FROZEN) {
4555 case CPU_UP_PREPARE:
4556 for_each_cpu_worker_pool(pool, cpu) {
4557 if (pool->nr_workers)
4559 if (!create_worker(pool))
4564 case CPU_DOWN_FAILED:
4566 mutex_lock(&wq_pool_mutex);
4568 for_each_pool(pool, pi) {
4569 mutex_lock(&pool->attach_mutex);
4571 if (pool->cpu == cpu)
4572 rebind_workers(pool);
4573 else if (pool->cpu < 0)
4574 restore_unbound_workers_cpumask(pool, cpu);
4576 mutex_unlock(&pool->attach_mutex);
4579 /* update NUMA affinity of unbound workqueues */
4580 list_for_each_entry(wq, &workqueues, list)
4581 wq_update_unbound_numa(wq, cpu, true);
4583 mutex_unlock(&wq_pool_mutex);
4590 * Workqueues should be brought down after normal priority CPU notifiers.
4591 * This will be registered as low priority CPU notifier.
4593 static int workqueue_cpu_down_callback(struct notifier_block *nfb,
4594 unsigned long action,
4597 int cpu = (unsigned long)hcpu;
4598 struct work_struct unbind_work;
4599 struct workqueue_struct *wq;
4601 switch (action & ~CPU_TASKS_FROZEN) {
4602 case CPU_DOWN_PREPARE:
4603 /* unbinding per-cpu workers should happen on the local CPU */
4604 INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
4605 queue_work_on(cpu, system_highpri_wq, &unbind_work);
4607 /* update NUMA affinity of unbound workqueues */
4608 mutex_lock(&wq_pool_mutex);
4609 list_for_each_entry(wq, &workqueues, list)
4610 wq_update_unbound_numa(wq, cpu, false);
4611 mutex_unlock(&wq_pool_mutex);
4613 /* wait for per-cpu unbinding to finish */
4614 flush_work(&unbind_work);
4615 destroy_work_on_stack(&unbind_work);
4623 struct work_for_cpu {
4624 struct work_struct work;
4630 static void work_for_cpu_fn(struct work_struct *work)
4632 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
4634 wfc->ret = wfc->fn(wfc->arg);
4638 * work_on_cpu - run a function in user context on a particular cpu
4639 * @cpu: the cpu to run on
4640 * @fn: the function to run
4641 * @arg: the function arg
4643 * It is up to the caller to ensure that the cpu doesn't go offline.
4644 * The caller must not hold any locks which would prevent @fn from completing.
4646 * Return: The value @fn returns.
4648 long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
4650 struct work_for_cpu wfc = { .fn = fn, .arg = arg };
4652 INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
4653 schedule_work_on(cpu, &wfc.work);
4654 flush_work(&wfc.work);
4655 destroy_work_on_stack(&wfc.work);
4658 EXPORT_SYMBOL_GPL(work_on_cpu);
4659 #endif /* CONFIG_SMP */
4661 #ifdef CONFIG_FREEZER
4664 * freeze_workqueues_begin - begin freezing workqueues
4666 * Start freezing workqueues. After this function returns, all freezable
4667 * workqueues will queue new works to their delayed_works list instead of
4671 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4673 void freeze_workqueues_begin(void)
4675 struct workqueue_struct *wq;
4676 struct pool_workqueue *pwq;
4678 mutex_lock(&wq_pool_mutex);
4680 WARN_ON_ONCE(workqueue_freezing);
4681 workqueue_freezing = true;
4683 list_for_each_entry(wq, &workqueues, list) {
4684 mutex_lock(&wq->mutex);
4685 for_each_pwq(pwq, wq)
4686 pwq_adjust_max_active(pwq);
4687 mutex_unlock(&wq->mutex);
4690 mutex_unlock(&wq_pool_mutex);
4694 * freeze_workqueues_busy - are freezable workqueues still busy?
4696 * Check whether freezing is complete. This function must be called
4697 * between freeze_workqueues_begin() and thaw_workqueues().
4700 * Grabs and releases wq_pool_mutex.
4703 * %true if some freezable workqueues are still busy. %false if freezing
4706 bool freeze_workqueues_busy(void)
4709 struct workqueue_struct *wq;
4710 struct pool_workqueue *pwq;
4712 mutex_lock(&wq_pool_mutex);
4714 WARN_ON_ONCE(!workqueue_freezing);
4716 list_for_each_entry(wq, &workqueues, list) {
4717 if (!(wq->flags & WQ_FREEZABLE))
4720 * nr_active is monotonically decreasing. It's safe
4721 * to peek without lock.
4724 for_each_pwq(pwq, wq) {
4725 WARN_ON_ONCE(pwq->nr_active < 0);
4726 if (pwq->nr_active) {
4735 mutex_unlock(&wq_pool_mutex);
4740 * thaw_workqueues - thaw workqueues
4742 * Thaw workqueues. Normal queueing is restored and all collected
4743 * frozen works are transferred to their respective pool worklists.
4746 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4748 void thaw_workqueues(void)
4750 struct workqueue_struct *wq;
4751 struct pool_workqueue *pwq;
4753 mutex_lock(&wq_pool_mutex);
4755 if (!workqueue_freezing)
4758 workqueue_freezing = false;
4760 /* restore max_active and repopulate worklist */
4761 list_for_each_entry(wq, &workqueues, list) {
4762 mutex_lock(&wq->mutex);
4763 for_each_pwq(pwq, wq)
4764 pwq_adjust_max_active(pwq);
4765 mutex_unlock(&wq->mutex);
4769 mutex_unlock(&wq_pool_mutex);
4771 #endif /* CONFIG_FREEZER */
4773 static int workqueue_apply_unbound_cpumask(void)
4777 struct workqueue_struct *wq;
4778 struct apply_wqattrs_ctx *ctx, *n;
4780 lockdep_assert_held(&wq_pool_mutex);
4782 list_for_each_entry(wq, &workqueues, list) {
4783 if (!(wq->flags & WQ_UNBOUND))
4785 /* creating multiple pwqs breaks ordering guarantee */
4786 if (wq->flags & __WQ_ORDERED)
4789 ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs);
4795 list_add_tail(&ctx->list, &ctxs);
4798 list_for_each_entry_safe(ctx, n, &ctxs, list) {
4800 apply_wqattrs_commit(ctx);
4801 apply_wqattrs_cleanup(ctx);
4808 * workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
4809 * @cpumask: the cpumask to set
4811 * The low-level workqueues cpumask is a global cpumask that limits
4812 * the affinity of all unbound workqueues. This function check the @cpumask
4813 * and apply it to all unbound workqueues and updates all pwqs of them.
4815 * Retun: 0 - Success
4816 * -EINVAL - Invalid @cpumask
4817 * -ENOMEM - Failed to allocate memory for attrs or pwqs.
4819 int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
4822 cpumask_var_t saved_cpumask;
4824 if (!zalloc_cpumask_var(&saved_cpumask, GFP_KERNEL))
4827 cpumask_and(cpumask, cpumask, cpu_possible_mask);
4828 if (!cpumask_empty(cpumask)) {
4829 apply_wqattrs_lock();
4831 /* save the old wq_unbound_cpumask. */
4832 cpumask_copy(saved_cpumask, wq_unbound_cpumask);
4834 /* update wq_unbound_cpumask at first and apply it to wqs. */
4835 cpumask_copy(wq_unbound_cpumask, cpumask);
4836 ret = workqueue_apply_unbound_cpumask();
4838 /* restore the wq_unbound_cpumask when failed. */
4840 cpumask_copy(wq_unbound_cpumask, saved_cpumask);
4842 apply_wqattrs_unlock();
4845 free_cpumask_var(saved_cpumask);
4851 * Workqueues with WQ_SYSFS flag set is visible to userland via
4852 * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
4853 * following attributes.
4855 * per_cpu RO bool : whether the workqueue is per-cpu or unbound
4856 * max_active RW int : maximum number of in-flight work items
4858 * Unbound workqueues have the following extra attributes.
4860 * id RO int : the associated pool ID
4861 * nice RW int : nice value of the workers
4862 * cpumask RW mask : bitmask of allowed CPUs for the workers
4865 struct workqueue_struct *wq;
4869 static struct workqueue_struct *dev_to_wq(struct device *dev)
4871 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
4876 static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
4879 struct workqueue_struct *wq = dev_to_wq(dev);
4881 return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
4883 static DEVICE_ATTR_RO(per_cpu);
4885 static ssize_t max_active_show(struct device *dev,
4886 struct device_attribute *attr, char *buf)
4888 struct workqueue_struct *wq = dev_to_wq(dev);
4890 return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
4893 static ssize_t max_active_store(struct device *dev,
4894 struct device_attribute *attr, const char *buf,
4897 struct workqueue_struct *wq = dev_to_wq(dev);
4900 if (sscanf(buf, "%d", &val) != 1 || val <= 0)
4903 workqueue_set_max_active(wq, val);
4906 static DEVICE_ATTR_RW(max_active);
4908 static struct attribute *wq_sysfs_attrs[] = {
4909 &dev_attr_per_cpu.attr,
4910 &dev_attr_max_active.attr,
4913 ATTRIBUTE_GROUPS(wq_sysfs);
4915 static ssize_t wq_pool_ids_show(struct device *dev,
4916 struct device_attribute *attr, char *buf)
4918 struct workqueue_struct *wq = dev_to_wq(dev);
4919 const char *delim = "";
4920 int node, written = 0;
4924 for_each_node(node) {
4925 written += scnprintf(buf + written, PAGE_SIZE - written,
4926 "%s%d:%d", delim, node,
4927 unbound_pwq_by_node(wq, node)->pool->id);
4930 written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
4937 static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
4940 struct workqueue_struct *wq = dev_to_wq(dev);
4943 mutex_lock(&wq->mutex);
4944 written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
4945 mutex_unlock(&wq->mutex);
4950 /* prepare workqueue_attrs for sysfs store operations */
4951 static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
4953 struct workqueue_attrs *attrs;
4955 lockdep_assert_held(&wq_pool_mutex);
4957 attrs = alloc_workqueue_attrs(GFP_KERNEL);
4961 copy_workqueue_attrs(attrs, wq->unbound_attrs);
4965 static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
4966 const char *buf, size_t count)
4968 struct workqueue_struct *wq = dev_to_wq(dev);
4969 struct workqueue_attrs *attrs;
4972 apply_wqattrs_lock();
4974 attrs = wq_sysfs_prep_attrs(wq);
4978 if (sscanf(buf, "%d", &attrs->nice) == 1 &&
4979 attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
4980 ret = apply_workqueue_attrs_locked(wq, attrs);
4985 apply_wqattrs_unlock();
4986 free_workqueue_attrs(attrs);
4987 return ret ?: count;
4990 static ssize_t wq_cpumask_show(struct device *dev,
4991 struct device_attribute *attr, char *buf)
4993 struct workqueue_struct *wq = dev_to_wq(dev);
4996 mutex_lock(&wq->mutex);
4997 written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
4998 cpumask_pr_args(wq->unbound_attrs->cpumask));
4999 mutex_unlock(&wq->mutex);
5003 static ssize_t wq_cpumask_store(struct device *dev,
5004 struct device_attribute *attr,
5005 const char *buf, size_t count)
5007 struct workqueue_struct *wq = dev_to_wq(dev);
5008 struct workqueue_attrs *attrs;
5011 apply_wqattrs_lock();
5013 attrs = wq_sysfs_prep_attrs(wq);
5017 ret = cpumask_parse(buf, attrs->cpumask);
5019 ret = apply_workqueue_attrs_locked(wq, attrs);
5022 apply_wqattrs_unlock();
5023 free_workqueue_attrs(attrs);
5024 return ret ?: count;
5027 static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
5030 struct workqueue_struct *wq = dev_to_wq(dev);
5033 mutex_lock(&wq->mutex);
5034 written = scnprintf(buf, PAGE_SIZE, "%d\n",
5035 !wq->unbound_attrs->no_numa);
5036 mutex_unlock(&wq->mutex);
5041 static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
5042 const char *buf, size_t count)
5044 struct workqueue_struct *wq = dev_to_wq(dev);
5045 struct workqueue_attrs *attrs;
5046 int v, ret = -ENOMEM;
5048 apply_wqattrs_lock();
5050 attrs = wq_sysfs_prep_attrs(wq);
5055 if (sscanf(buf, "%d", &v) == 1) {
5056 attrs->no_numa = !v;
5057 ret = apply_workqueue_attrs_locked(wq, attrs);
5061 apply_wqattrs_unlock();
5062 free_workqueue_attrs(attrs);
5063 return ret ?: count;
5066 static struct device_attribute wq_sysfs_unbound_attrs[] = {
5067 __ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
5068 __ATTR(nice, 0644, wq_nice_show, wq_nice_store),
5069 __ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
5070 __ATTR(numa, 0644, wq_numa_show, wq_numa_store),
5074 static struct bus_type wq_subsys = {
5075 .name = "workqueue",
5076 .dev_groups = wq_sysfs_groups,
5079 static ssize_t wq_unbound_cpumask_show(struct device *dev,
5080 struct device_attribute *attr, char *buf)
5084 mutex_lock(&wq_pool_mutex);
5085 written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
5086 cpumask_pr_args(wq_unbound_cpumask));
5087 mutex_unlock(&wq_pool_mutex);
5092 static ssize_t wq_unbound_cpumask_store(struct device *dev,
5093 struct device_attribute *attr, const char *buf, size_t count)
5095 cpumask_var_t cpumask;
5098 if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
5101 ret = cpumask_parse(buf, cpumask);
5103 ret = workqueue_set_unbound_cpumask(cpumask);
5105 free_cpumask_var(cpumask);
5106 return ret ? ret : count;
5109 static struct device_attribute wq_sysfs_cpumask_attr =
5110 __ATTR(cpumask, 0644, wq_unbound_cpumask_show,
5111 wq_unbound_cpumask_store);
5113 static int __init wq_sysfs_init(void)
5117 err = subsys_virtual_register(&wq_subsys, NULL);
5121 return device_create_file(wq_subsys.dev_root, &wq_sysfs_cpumask_attr);
5123 core_initcall(wq_sysfs_init);
5125 static void wq_device_release(struct device *dev)
5127 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
5133 * workqueue_sysfs_register - make a workqueue visible in sysfs
5134 * @wq: the workqueue to register
5136 * Expose @wq in sysfs under /sys/bus/workqueue/devices.
5137 * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
5138 * which is the preferred method.
5140 * Workqueue user should use this function directly iff it wants to apply
5141 * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
5142 * apply_workqueue_attrs() may race against userland updating the
5145 * Return: 0 on success, -errno on failure.
5147 int workqueue_sysfs_register(struct workqueue_struct *wq)
5149 struct wq_device *wq_dev;
5153 * Adjusting max_active or creating new pwqs by applying
5154 * attributes breaks ordering guarantee. Disallow exposing ordered
5157 if (WARN_ON(wq->flags & __WQ_ORDERED))
5160 wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
5165 wq_dev->dev.bus = &wq_subsys;
5166 wq_dev->dev.init_name = wq->name;
5167 wq_dev->dev.release = wq_device_release;
5170 * unbound_attrs are created separately. Suppress uevent until
5171 * everything is ready.
5173 dev_set_uevent_suppress(&wq_dev->dev, true);
5175 ret = device_register(&wq_dev->dev);
5182 if (wq->flags & WQ_UNBOUND) {
5183 struct device_attribute *attr;
5185 for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
5186 ret = device_create_file(&wq_dev->dev, attr);
5188 device_unregister(&wq_dev->dev);
5195 dev_set_uevent_suppress(&wq_dev->dev, false);
5196 kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
5201 * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
5202 * @wq: the workqueue to unregister
5204 * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
5206 static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
5208 struct wq_device *wq_dev = wq->wq_dev;
5214 device_unregister(&wq_dev->dev);
5216 #else /* CONFIG_SYSFS */
5217 static void workqueue_sysfs_unregister(struct workqueue_struct *wq) { }
5218 #endif /* CONFIG_SYSFS */
5220 static void __init wq_numa_init(void)
5225 if (num_possible_nodes() <= 1)
5228 if (wq_disable_numa) {
5229 pr_info("workqueue: NUMA affinity support disabled\n");
5233 wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs(GFP_KERNEL);
5234 BUG_ON(!wq_update_unbound_numa_attrs_buf);
5237 * We want masks of possible CPUs of each node which isn't readily
5238 * available. Build one from cpu_to_node() which should have been
5239 * fully initialized by now.
5241 tbl = kzalloc(nr_node_ids * sizeof(tbl[0]), GFP_KERNEL);
5245 BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
5246 node_online(node) ? node : NUMA_NO_NODE));
5248 for_each_possible_cpu(cpu) {
5249 node = cpu_to_node(cpu);
5250 if (WARN_ON(node == NUMA_NO_NODE)) {
5251 pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
5252 /* happens iff arch is bonkers, let's just proceed */
5255 cpumask_set_cpu(cpu, tbl[node]);
5258 wq_numa_possible_cpumask = tbl;
5259 wq_numa_enabled = true;
5262 static int __init init_workqueues(void)
5264 int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
5267 WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
5269 BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
5270 cpumask_copy(wq_unbound_cpumask, cpu_possible_mask);
5272 pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
5274 cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
5275 hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
5279 /* initialize CPU pools */
5280 for_each_possible_cpu(cpu) {
5281 struct worker_pool *pool;
5284 for_each_cpu_worker_pool(pool, cpu) {
5285 BUG_ON(init_worker_pool(pool));
5287 cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
5288 pool->attrs->nice = std_nice[i++];
5289 pool->node = cpu_to_node(cpu);
5292 mutex_lock(&wq_pool_mutex);
5293 BUG_ON(worker_pool_assign_id(pool));
5294 mutex_unlock(&wq_pool_mutex);
5298 /* create the initial worker */
5299 for_each_online_cpu(cpu) {
5300 struct worker_pool *pool;
5302 for_each_cpu_worker_pool(pool, cpu) {
5303 pool->flags &= ~POOL_DISASSOCIATED;
5304 BUG_ON(!create_worker(pool));
5308 /* create default unbound and ordered wq attrs */
5309 for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
5310 struct workqueue_attrs *attrs;
5312 BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
5313 attrs->nice = std_nice[i];
5314 unbound_std_wq_attrs[i] = attrs;
5317 * An ordered wq should have only one pwq as ordering is
5318 * guaranteed by max_active which is enforced by pwqs.
5319 * Turn off NUMA so that dfl_pwq is used for all nodes.
5321 BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
5322 attrs->nice = std_nice[i];
5323 attrs->no_numa = true;
5324 ordered_wq_attrs[i] = attrs;
5327 system_wq = alloc_workqueue("events", 0, 0);
5328 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
5329 system_long_wq = alloc_workqueue("events_long", 0, 0);
5330 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
5331 WQ_UNBOUND_MAX_ACTIVE);
5332 system_freezable_wq = alloc_workqueue("events_freezable",
5334 system_power_efficient_wq = alloc_workqueue("events_power_efficient",
5335 WQ_POWER_EFFICIENT, 0);
5336 system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
5337 WQ_FREEZABLE | WQ_POWER_EFFICIENT,
5339 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
5340 !system_unbound_wq || !system_freezable_wq ||
5341 !system_power_efficient_wq ||
5342 !system_freezable_power_efficient_wq);
5345 early_initcall(init_workqueues);