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 * WQ: wq->mutex protected.
139 * WR: wq->mutex protected for writes. RCU protected for reads.
141 * MD: wq_mayday_lock protected.
144 /* struct worker is defined in workqueue_internal.h */
147 spinlock_t lock; /* the pool lock */
148 int cpu; /* I: the associated cpu */
149 int node; /* I: the associated node ID */
150 int id; /* I: pool ID */
151 unsigned int flags; /* X: flags */
153 struct list_head worklist; /* L: list of pending works */
154 int nr_workers; /* L: total number of workers */
156 /* nr_idle includes the ones off idle_list for rebinding */
157 int nr_idle; /* L: currently idle ones */
159 struct list_head idle_list; /* X: list of idle workers */
160 struct timer_list idle_timer; /* L: worker idle timeout */
161 struct timer_list mayday_timer; /* L: SOS timer for workers */
163 /* a workers is either on busy_hash or idle_list, or the manager */
164 DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
165 /* L: hash of busy workers */
167 /* see manage_workers() for details on the two manager mutexes */
168 struct mutex manager_arb; /* manager arbitration */
169 struct worker *manager; /* L: purely informational */
170 struct mutex attach_mutex; /* attach/detach exclusion */
171 struct list_head workers; /* A: attached workers */
172 struct completion *detach_completion; /* all workers detached */
174 struct ida worker_ida; /* worker IDs for task name */
176 struct workqueue_attrs *attrs; /* I: worker attributes */
177 struct hlist_node hash_node; /* PL: unbound_pool_hash node */
178 int refcnt; /* PL: refcnt for unbound pools */
181 * The current concurrency level. As it's likely to be accessed
182 * from other CPUs during try_to_wake_up(), put it in a separate
185 atomic_t nr_running ____cacheline_aligned_in_smp;
188 * Destruction of pool is RCU protected to allow dereferences
189 * from get_work_pool().
192 } ____cacheline_aligned_in_smp;
195 * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
196 * of work_struct->data are used for flags and the remaining high bits
197 * point to the pwq; thus, pwqs need to be aligned at two's power of the
198 * number of flag bits.
200 struct pool_workqueue {
201 struct worker_pool *pool; /* I: the associated pool */
202 struct workqueue_struct *wq; /* I: the owning workqueue */
203 int work_color; /* L: current color */
204 int flush_color; /* L: flushing color */
205 int refcnt; /* L: reference count */
206 int nr_in_flight[WORK_NR_COLORS];
207 /* L: nr of in_flight works */
208 int nr_active; /* L: nr of active works */
209 int max_active; /* L: max active works */
210 struct list_head delayed_works; /* L: delayed works */
211 struct list_head pwqs_node; /* WR: node on wq->pwqs */
212 struct list_head mayday_node; /* MD: node on wq->maydays */
215 * Release of unbound pwq is punted to system_wq. See put_pwq()
216 * and pwq_unbound_release_workfn() for details. pool_workqueue
217 * itself is also RCU protected so that the first pwq can be
218 * determined without grabbing wq->mutex.
220 struct work_struct unbound_release_work;
222 } __aligned(1 << WORK_STRUCT_FLAG_BITS);
225 * Structure used to wait for workqueue flush.
228 struct list_head list; /* WQ: list of flushers */
229 int flush_color; /* WQ: flush color waiting for */
230 struct completion done; /* flush completion */
236 * The externally visible workqueue. It relays the issued work items to
237 * the appropriate worker_pool through its pool_workqueues.
239 struct workqueue_struct {
240 struct list_head pwqs; /* WR: all pwqs of this wq */
241 struct list_head list; /* PR: list of all workqueues */
243 struct mutex mutex; /* protects this wq */
244 int work_color; /* WQ: current work color */
245 int flush_color; /* WQ: current flush color */
246 atomic_t nr_pwqs_to_flush; /* flush in progress */
247 struct wq_flusher *first_flusher; /* WQ: first flusher */
248 struct list_head flusher_queue; /* WQ: flush waiters */
249 struct list_head flusher_overflow; /* WQ: flush overflow list */
251 struct list_head maydays; /* MD: pwqs requesting rescue */
252 struct worker *rescuer; /* I: rescue worker */
254 int nr_drainers; /* WQ: drain in progress */
255 int saved_max_active; /* WQ: saved pwq max_active */
257 struct workqueue_attrs *unbound_attrs; /* WQ: only for unbound wqs */
258 struct pool_workqueue *dfl_pwq; /* WQ: only for unbound wqs */
261 struct wq_device *wq_dev; /* I: for sysfs interface */
263 #ifdef CONFIG_LOCKDEP
264 struct lockdep_map lockdep_map;
266 char name[WQ_NAME_LEN]; /* I: workqueue name */
269 * Destruction of workqueue_struct is sched-RCU protected to allow
270 * walking the workqueues list without grabbing wq_pool_mutex.
271 * This is used to dump all workqueues from sysrq.
275 /* hot fields used during command issue, aligned to cacheline */
276 unsigned int flags ____cacheline_aligned; /* WQ: WQ_* flags */
277 struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */
278 struct pool_workqueue __rcu *numa_pwq_tbl[]; /* FR: unbound pwqs indexed by node */
281 static struct kmem_cache *pwq_cache;
283 static cpumask_var_t *wq_numa_possible_cpumask;
284 /* possible CPUs of each node */
286 static bool wq_disable_numa;
287 module_param_named(disable_numa, wq_disable_numa, bool, 0444);
289 /* see the comment above the definition of WQ_POWER_EFFICIENT */
290 #ifdef CONFIG_WQ_POWER_EFFICIENT_DEFAULT
291 static bool wq_power_efficient = true;
293 static bool wq_power_efficient;
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 /* the per-cpu worker pools */
310 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
313 static DEFINE_IDR(worker_pool_idr); /* PR: idr of all pools */
315 /* PL: hash of all unbound pools keyed by pool->attrs */
316 static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
318 /* I: attributes used when instantiating standard unbound pools on demand */
319 static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
321 /* I: attributes used when instantiating ordered pools on demand */
322 static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
324 struct workqueue_struct *system_wq __read_mostly;
325 EXPORT_SYMBOL(system_wq);
326 struct workqueue_struct *system_highpri_wq __read_mostly;
327 EXPORT_SYMBOL_GPL(system_highpri_wq);
328 struct workqueue_struct *system_long_wq __read_mostly;
329 EXPORT_SYMBOL_GPL(system_long_wq);
330 struct workqueue_struct *system_unbound_wq __read_mostly;
331 EXPORT_SYMBOL_GPL(system_unbound_wq);
332 struct workqueue_struct *system_freezable_wq __read_mostly;
333 EXPORT_SYMBOL_GPL(system_freezable_wq);
334 struct workqueue_struct *system_power_efficient_wq __read_mostly;
335 EXPORT_SYMBOL_GPL(system_power_efficient_wq);
336 struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
337 EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
339 static DEFINE_LOCAL_IRQ_LOCK(pendingb_lock);
341 static int worker_thread(void *__worker);
342 static void copy_workqueue_attrs(struct workqueue_attrs *to,
343 const struct workqueue_attrs *from);
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_assert(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_assert(rcu_read_lock_held() || \
356 lockdep_is_held(&wq->mutex), \
357 "RCU or wq->mutex should be held")
359 #define for_each_cpu_worker_pool(pool, cpu) \
360 for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
361 (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
365 * for_each_pool - iterate through all worker_pools in the system
366 * @pool: iteration cursor
367 * @pi: integer used for iteration
369 * This must be called either with wq_pool_mutex held or RCU read
370 * locked. If the pool needs to be used beyond the locking in effect, the
371 * caller is responsible for guaranteeing that the pool stays online.
373 * The if/else clause exists only for the lockdep assertion and can be
376 #define for_each_pool(pool, pi) \
377 idr_for_each_entry(&worker_pool_idr, pool, pi) \
378 if (({ assert_rcu_or_pool_mutex(); false; })) { } \
382 * for_each_pool_worker - iterate through all workers of a worker_pool
383 * @worker: iteration cursor
384 * @pool: worker_pool to iterate workers of
386 * This must be called with @pool->attach_mutex.
388 * The if/else clause exists only for the lockdep assertion and can be
391 #define for_each_pool_worker(worker, pool) \
392 list_for_each_entry((worker), &(pool)->workers, node) \
393 if (({ lockdep_assert_held(&pool->attach_mutex); false; })) { } \
397 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
398 * @pwq: iteration cursor
399 * @wq: the target workqueue
401 * This must be called either with wq->mutex held or RCU read locked.
402 * If the pwq needs to be used beyond the locking in effect, the caller is
403 * responsible for guaranteeing that the pwq stays online.
405 * The if/else clause exists only for the lockdep assertion and can be
408 #define for_each_pwq(pwq, wq) \
409 list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node) \
410 if (({ assert_rcu_or_wq_mutex(wq); false; })) { } \
413 #ifdef CONFIG_PREEMPT_RT_BASE
414 static inline void rt_lock_idle_list(struct worker_pool *pool)
418 static inline void rt_unlock_idle_list(struct worker_pool *pool)
422 static inline void sched_lock_idle_list(struct worker_pool *pool) { }
423 static inline void sched_unlock_idle_list(struct worker_pool *pool) { }
425 static inline void rt_lock_idle_list(struct worker_pool *pool) { }
426 static inline void rt_unlock_idle_list(struct worker_pool *pool) { }
427 static inline void sched_lock_idle_list(struct worker_pool *pool)
429 spin_lock_irq(&pool->lock);
431 static inline void sched_unlock_idle_list(struct worker_pool *pool)
433 spin_unlock_irq(&pool->lock);
438 #ifdef CONFIG_DEBUG_OBJECTS_WORK
440 static struct debug_obj_descr work_debug_descr;
442 static void *work_debug_hint(void *addr)
444 return ((struct work_struct *) addr)->func;
448 * fixup_init is called when:
449 * - an active object is initialized
451 static int work_fixup_init(void *addr, enum debug_obj_state state)
453 struct work_struct *work = addr;
456 case ODEBUG_STATE_ACTIVE:
457 cancel_work_sync(work);
458 debug_object_init(work, &work_debug_descr);
466 * fixup_activate is called when:
467 * - an active object is activated
468 * - an unknown object is activated (might be a statically initialized object)
470 static int work_fixup_activate(void *addr, enum debug_obj_state state)
472 struct work_struct *work = addr;
476 case ODEBUG_STATE_NOTAVAILABLE:
478 * This is not really a fixup. The work struct was
479 * statically initialized. We just make sure that it
480 * is tracked in the object tracker.
482 if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
483 debug_object_init(work, &work_debug_descr);
484 debug_object_activate(work, &work_debug_descr);
490 case ODEBUG_STATE_ACTIVE:
499 * fixup_free is called when:
500 * - an active object is freed
502 static int work_fixup_free(void *addr, enum debug_obj_state state)
504 struct work_struct *work = addr;
507 case ODEBUG_STATE_ACTIVE:
508 cancel_work_sync(work);
509 debug_object_free(work, &work_debug_descr);
516 static struct debug_obj_descr work_debug_descr = {
517 .name = "work_struct",
518 .debug_hint = work_debug_hint,
519 .fixup_init = work_fixup_init,
520 .fixup_activate = work_fixup_activate,
521 .fixup_free = work_fixup_free,
524 static inline void debug_work_activate(struct work_struct *work)
526 debug_object_activate(work, &work_debug_descr);
529 static inline void debug_work_deactivate(struct work_struct *work)
531 debug_object_deactivate(work, &work_debug_descr);
534 void __init_work(struct work_struct *work, int onstack)
537 debug_object_init_on_stack(work, &work_debug_descr);
539 debug_object_init(work, &work_debug_descr);
541 EXPORT_SYMBOL_GPL(__init_work);
543 void destroy_work_on_stack(struct work_struct *work)
545 debug_object_free(work, &work_debug_descr);
547 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
549 void destroy_delayed_work_on_stack(struct delayed_work *work)
551 destroy_timer_on_stack(&work->timer);
552 debug_object_free(&work->work, &work_debug_descr);
554 EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
557 static inline void debug_work_activate(struct work_struct *work) { }
558 static inline void debug_work_deactivate(struct work_struct *work) { }
562 * worker_pool_assign_id - allocate ID and assing it to @pool
563 * @pool: the pool pointer of interest
565 * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
566 * successfully, -errno on failure.
568 static int worker_pool_assign_id(struct worker_pool *pool)
572 lockdep_assert_held(&wq_pool_mutex);
574 ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
584 * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
585 * @wq: the target workqueue
588 * This must be called either with pwq_lock held or RCU read locked.
589 * If the pwq needs to be used beyond the locking in effect, the caller is
590 * responsible for guaranteeing that the pwq stays online.
592 * Return: The unbound pool_workqueue for @node.
594 static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
597 assert_rcu_or_wq_mutex(wq);
598 return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
601 static unsigned int work_color_to_flags(int color)
603 return color << WORK_STRUCT_COLOR_SHIFT;
606 static int get_work_color(struct work_struct *work)
608 return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
609 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
612 static int work_next_color(int color)
614 return (color + 1) % WORK_NR_COLORS;
618 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
619 * contain the pointer to the queued pwq. Once execution starts, the flag
620 * is cleared and the high bits contain OFFQ flags and pool ID.
622 * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
623 * and clear_work_data() can be used to set the pwq, pool or clear
624 * work->data. These functions should only be called while the work is
625 * owned - ie. while the PENDING bit is set.
627 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
628 * corresponding to a work. Pool is available once the work has been
629 * queued anywhere after initialization until it is sync canceled. pwq is
630 * available only while the work item is queued.
632 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
633 * canceled. While being canceled, a work item may have its PENDING set
634 * but stay off timer and worklist for arbitrarily long and nobody should
635 * try to steal the PENDING bit.
637 static inline void set_work_data(struct work_struct *work, unsigned long data,
640 WARN_ON_ONCE(!work_pending(work));
641 atomic_long_set(&work->data, data | flags | work_static(work));
644 static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
645 unsigned long extra_flags)
647 set_work_data(work, (unsigned long)pwq,
648 WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
651 static void set_work_pool_and_keep_pending(struct work_struct *work,
654 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
655 WORK_STRUCT_PENDING);
658 static void set_work_pool_and_clear_pending(struct work_struct *work,
662 * The following wmb is paired with the implied mb in
663 * test_and_set_bit(PENDING) and ensures all updates to @work made
664 * here are visible to and precede any updates by the next PENDING
668 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
671 static void clear_work_data(struct work_struct *work)
673 smp_wmb(); /* see set_work_pool_and_clear_pending() */
674 set_work_data(work, WORK_STRUCT_NO_POOL, 0);
677 static struct pool_workqueue *get_work_pwq(struct work_struct *work)
679 unsigned long data = atomic_long_read(&work->data);
681 if (data & WORK_STRUCT_PWQ)
682 return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
688 * get_work_pool - return the worker_pool a given work was associated with
689 * @work: the work item of interest
691 * Pools are created and destroyed under wq_pool_mutex, and allows read
692 * access under RCU read lock. As such, this function should be
693 * called under wq_pool_mutex or inside of a rcu_read_lock() region.
695 * All fields of the returned pool are accessible as long as the above
696 * mentioned locking is in effect. If the returned pool needs to be used
697 * beyond the critical section, the caller is responsible for ensuring the
698 * returned pool is and stays online.
700 * Return: The worker_pool @work was last associated with. %NULL if none.
702 static struct worker_pool *get_work_pool(struct work_struct *work)
704 unsigned long data = atomic_long_read(&work->data);
707 assert_rcu_or_pool_mutex();
709 if (data & WORK_STRUCT_PWQ)
710 return ((struct pool_workqueue *)
711 (data & WORK_STRUCT_WQ_DATA_MASK))->pool;
713 pool_id = data >> WORK_OFFQ_POOL_SHIFT;
714 if (pool_id == WORK_OFFQ_POOL_NONE)
717 return idr_find(&worker_pool_idr, pool_id);
721 * get_work_pool_id - return the worker pool ID a given work is associated with
722 * @work: the work item of interest
724 * Return: The worker_pool ID @work was last associated with.
725 * %WORK_OFFQ_POOL_NONE if none.
727 static int get_work_pool_id(struct work_struct *work)
729 unsigned long data = atomic_long_read(&work->data);
731 if (data & WORK_STRUCT_PWQ)
732 return ((struct pool_workqueue *)
733 (data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
735 return data >> WORK_OFFQ_POOL_SHIFT;
738 static void mark_work_canceling(struct work_struct *work)
740 unsigned long pool_id = get_work_pool_id(work);
742 pool_id <<= WORK_OFFQ_POOL_SHIFT;
743 set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
746 static bool work_is_canceling(struct work_struct *work)
748 unsigned long data = atomic_long_read(&work->data);
750 return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
754 * Policy functions. These define the policies on how the global worker
755 * pools are managed. Unless noted otherwise, these functions assume that
756 * they're being called with pool->lock held.
759 static bool __need_more_worker(struct worker_pool *pool)
761 return !atomic_read(&pool->nr_running);
765 * Need to wake up a worker? Called from anything but currently
768 * Note that, because unbound workers never contribute to nr_running, this
769 * function will always return %true for unbound pools as long as the
770 * worklist isn't empty.
772 static bool need_more_worker(struct worker_pool *pool)
774 return !list_empty(&pool->worklist) && __need_more_worker(pool);
777 /* Can I start working? Called from busy but !running workers. */
778 static bool may_start_working(struct worker_pool *pool)
780 return pool->nr_idle;
783 /* Do I need to keep working? Called from currently running workers. */
784 static bool keep_working(struct worker_pool *pool)
786 return !list_empty(&pool->worklist) &&
787 atomic_read(&pool->nr_running) <= 1;
790 /* Do we need a new worker? Called from manager. */
791 static bool need_to_create_worker(struct worker_pool *pool)
793 return need_more_worker(pool) && !may_start_working(pool);
796 /* Do we have too many workers and should some go away? */
797 static bool too_many_workers(struct worker_pool *pool)
799 bool managing = mutex_is_locked(&pool->manager_arb);
800 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
801 int nr_busy = pool->nr_workers - nr_idle;
803 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
810 /* Return the first idle worker. Safe with preemption disabled */
811 static struct worker *first_idle_worker(struct worker_pool *pool)
813 if (unlikely(list_empty(&pool->idle_list)))
816 return list_first_entry(&pool->idle_list, struct worker, entry);
820 * wake_up_worker - wake up an idle worker
821 * @pool: worker pool to wake worker from
823 * Wake up the first idle worker of @pool.
826 * spin_lock_irq(pool->lock).
828 static void wake_up_worker(struct worker_pool *pool)
830 struct worker *worker;
832 rt_lock_idle_list(pool);
834 worker = first_idle_worker(pool);
837 wake_up_process(worker->task);
839 rt_unlock_idle_list(pool);
843 * wq_worker_running - a worker is running again
844 * @task: task returning from sleep
846 * This function is called when a worker returns from schedule()
848 void wq_worker_running(struct task_struct *task)
850 struct worker *worker = kthread_data(task);
852 if (!worker->sleeping)
854 if (!(worker->flags & WORKER_NOT_RUNNING))
855 atomic_inc(&worker->pool->nr_running);
856 worker->sleeping = 0;
860 * wq_worker_sleeping - a worker is going to sleep
861 * @task: task going to sleep
862 * This function is called from schedule() when a busy worker is
865 void wq_worker_sleeping(struct task_struct *task)
867 struct worker *worker = kthread_data(task);
868 struct worker_pool *pool;
871 * Rescuers, which may not have all the fields set up like normal
872 * workers, also reach here, let's not access anything before
873 * checking NOT_RUNNING.
875 if (worker->flags & WORKER_NOT_RUNNING)
880 if (WARN_ON_ONCE(worker->sleeping))
883 worker->sleeping = 1;
886 * The counterpart of the following dec_and_test, implied mb,
887 * worklist not empty test sequence is in insert_work().
888 * Please read comment there.
890 if (atomic_dec_and_test(&pool->nr_running) &&
891 !list_empty(&pool->worklist)) {
892 sched_lock_idle_list(pool);
893 wake_up_worker(pool);
894 sched_unlock_idle_list(pool);
899 * worker_set_flags - set worker flags and adjust nr_running accordingly
901 * @flags: flags to set
903 * Set @flags in @worker->flags and adjust nr_running accordingly.
906 * spin_lock_irq(pool->lock)
908 static inline void worker_set_flags(struct worker *worker, unsigned int flags)
910 struct worker_pool *pool = worker->pool;
912 WARN_ON_ONCE(worker->task != current);
914 /* If transitioning into NOT_RUNNING, adjust nr_running. */
915 if ((flags & WORKER_NOT_RUNNING) &&
916 !(worker->flags & WORKER_NOT_RUNNING)) {
917 atomic_dec(&pool->nr_running);
920 worker->flags |= flags;
924 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
926 * @flags: flags to clear
928 * Clear @flags in @worker->flags and adjust nr_running accordingly.
931 * spin_lock_irq(pool->lock)
933 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
935 struct worker_pool *pool = worker->pool;
936 unsigned int oflags = worker->flags;
938 WARN_ON_ONCE(worker->task != current);
940 worker->flags &= ~flags;
943 * If transitioning out of NOT_RUNNING, increment nr_running. Note
944 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
945 * of multiple flags, not a single flag.
947 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
948 if (!(worker->flags & WORKER_NOT_RUNNING))
949 atomic_inc(&pool->nr_running);
953 * find_worker_executing_work - find worker which is executing a work
954 * @pool: pool of interest
955 * @work: work to find worker for
957 * Find a worker which is executing @work on @pool by searching
958 * @pool->busy_hash which is keyed by the address of @work. For a worker
959 * to match, its current execution should match the address of @work and
960 * its work function. This is to avoid unwanted dependency between
961 * unrelated work executions through a work item being recycled while still
964 * This is a bit tricky. A work item may be freed once its execution
965 * starts and nothing prevents the freed area from being recycled for
966 * another work item. If the same work item address ends up being reused
967 * before the original execution finishes, workqueue will identify the
968 * recycled work item as currently executing and make it wait until the
969 * current execution finishes, introducing an unwanted dependency.
971 * This function checks the work item address and work function to avoid
972 * false positives. Note that this isn't complete as one may construct a
973 * work function which can introduce dependency onto itself through a
974 * recycled work item. Well, if somebody wants to shoot oneself in the
975 * foot that badly, there's only so much we can do, and if such deadlock
976 * actually occurs, it should be easy to locate the culprit work function.
979 * spin_lock_irq(pool->lock).
982 * Pointer to worker which is executing @work if found, %NULL
985 static struct worker *find_worker_executing_work(struct worker_pool *pool,
986 struct work_struct *work)
988 struct worker *worker;
990 hash_for_each_possible(pool->busy_hash, worker, hentry,
992 if (worker->current_work == work &&
993 worker->current_func == work->func)
1000 * move_linked_works - move linked works to a list
1001 * @work: start of series of works to be scheduled
1002 * @head: target list to append @work to
1003 * @nextp: out paramter for nested worklist walking
1005 * Schedule linked works starting from @work to @head. Work series to
1006 * be scheduled starts at @work and includes any consecutive work with
1007 * WORK_STRUCT_LINKED set in its predecessor.
1009 * If @nextp is not NULL, it's updated to point to the next work of
1010 * the last scheduled work. This allows move_linked_works() to be
1011 * nested inside outer list_for_each_entry_safe().
1014 * spin_lock_irq(pool->lock).
1016 static void move_linked_works(struct work_struct *work, struct list_head *head,
1017 struct work_struct **nextp)
1019 struct work_struct *n;
1022 * Linked worklist will always end before the end of the list,
1023 * use NULL for list head.
1025 list_for_each_entry_safe_from(work, n, NULL, entry) {
1026 list_move_tail(&work->entry, head);
1027 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1032 * If we're already inside safe list traversal and have moved
1033 * multiple works to the scheduled queue, the next position
1034 * needs to be updated.
1041 * get_pwq - get an extra reference on the specified pool_workqueue
1042 * @pwq: pool_workqueue to get
1044 * Obtain an extra reference on @pwq. The caller should guarantee that
1045 * @pwq has positive refcnt and be holding the matching pool->lock.
1047 static void get_pwq(struct pool_workqueue *pwq)
1049 lockdep_assert_held(&pwq->pool->lock);
1050 WARN_ON_ONCE(pwq->refcnt <= 0);
1055 * put_pwq - put a pool_workqueue reference
1056 * @pwq: pool_workqueue to put
1058 * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
1059 * destruction. The caller should be holding the matching pool->lock.
1061 static void put_pwq(struct pool_workqueue *pwq)
1063 lockdep_assert_held(&pwq->pool->lock);
1064 if (likely(--pwq->refcnt))
1066 if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
1069 * @pwq can't be released under pool->lock, bounce to
1070 * pwq_unbound_release_workfn(). This never recurses on the same
1071 * pool->lock as this path is taken only for unbound workqueues and
1072 * the release work item is scheduled on a per-cpu workqueue. To
1073 * avoid lockdep warning, unbound pool->locks are given lockdep
1074 * subclass of 1 in get_unbound_pool().
1076 schedule_work(&pwq->unbound_release_work);
1080 * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1081 * @pwq: pool_workqueue to put (can be %NULL)
1083 * put_pwq() with locking. This function also allows %NULL @pwq.
1085 static void put_pwq_unlocked(struct pool_workqueue *pwq)
1089 * As both pwqs and pools are RCU protected, the
1090 * following lock operations are safe.
1092 local_spin_lock_irq(pendingb_lock, &pwq->pool->lock);
1094 local_spin_unlock_irq(pendingb_lock, &pwq->pool->lock);
1098 static void pwq_activate_delayed_work(struct work_struct *work)
1100 struct pool_workqueue *pwq = get_work_pwq(work);
1102 trace_workqueue_activate_work(work);
1103 move_linked_works(work, &pwq->pool->worklist, NULL);
1104 __clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
1108 static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
1110 struct work_struct *work = list_first_entry(&pwq->delayed_works,
1111 struct work_struct, entry);
1113 pwq_activate_delayed_work(work);
1117 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1118 * @pwq: pwq of interest
1119 * @color: color of work which left the queue
1121 * A work either has completed or is removed from pending queue,
1122 * decrement nr_in_flight of its pwq and handle workqueue flushing.
1125 * spin_lock_irq(pool->lock).
1127 static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
1129 /* uncolored work items don't participate in flushing or nr_active */
1130 if (color == WORK_NO_COLOR)
1133 pwq->nr_in_flight[color]--;
1136 if (!list_empty(&pwq->delayed_works)) {
1137 /* one down, submit a delayed one */
1138 if (pwq->nr_active < pwq->max_active)
1139 pwq_activate_first_delayed(pwq);
1142 /* is flush in progress and are we at the flushing tip? */
1143 if (likely(pwq->flush_color != color))
1146 /* are there still in-flight works? */
1147 if (pwq->nr_in_flight[color])
1150 /* this pwq is done, clear flush_color */
1151 pwq->flush_color = -1;
1154 * If this was the last pwq, wake up the first flusher. It
1155 * will handle the rest.
1157 if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1158 complete(&pwq->wq->first_flusher->done);
1164 * try_to_grab_pending - steal work item from worklist and disable irq
1165 * @work: work item to steal
1166 * @is_dwork: @work is a delayed_work
1167 * @flags: place to store irq state
1169 * Try to grab PENDING bit of @work. This function can handle @work in any
1170 * stable state - idle, on timer or on worklist.
1173 * 1 if @work was pending and we successfully stole PENDING
1174 * 0 if @work was idle and we claimed PENDING
1175 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1176 * -ENOENT if someone else is canceling @work, this state may persist
1177 * for arbitrarily long
1180 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1181 * interrupted while holding PENDING and @work off queue, irq must be
1182 * disabled on entry. This, combined with delayed_work->timer being
1183 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1185 * On successful return, >= 0, irq is disabled and the caller is
1186 * responsible for releasing it using local_irq_restore(*@flags).
1188 * This function is safe to call from any context including IRQ handler.
1190 static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1191 unsigned long *flags)
1193 struct worker_pool *pool;
1194 struct pool_workqueue *pwq;
1196 local_lock_irqsave(pendingb_lock, *flags);
1198 /* try to steal the timer if it exists */
1200 struct delayed_work *dwork = to_delayed_work(work);
1203 * dwork->timer is irqsafe. If del_timer() fails, it's
1204 * guaranteed that the timer is not queued anywhere and not
1205 * running on the local CPU.
1207 if (likely(del_timer(&dwork->timer)))
1211 /* try to claim PENDING the normal way */
1212 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1217 * The queueing is in progress, or it is already queued. Try to
1218 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1220 pool = get_work_pool(work);
1224 spin_lock(&pool->lock);
1226 * work->data is guaranteed to point to pwq only while the work
1227 * item is queued on pwq->wq, and both updating work->data to point
1228 * to pwq on queueing and to pool on dequeueing are done under
1229 * pwq->pool->lock. This in turn guarantees that, if work->data
1230 * points to pwq which is associated with a locked pool, the work
1231 * item is currently queued on that pool.
1233 pwq = get_work_pwq(work);
1234 if (pwq && pwq->pool == pool) {
1235 debug_work_deactivate(work);
1238 * A delayed work item cannot be grabbed directly because
1239 * it might have linked NO_COLOR work items which, if left
1240 * on the delayed_list, will confuse pwq->nr_active
1241 * management later on and cause stall. Make sure the work
1242 * item is activated before grabbing.
1244 if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1245 pwq_activate_delayed_work(work);
1247 list_del_init(&work->entry);
1248 pwq_dec_nr_in_flight(pwq, get_work_color(work));
1250 /* work->data points to pwq iff queued, point to pool */
1251 set_work_pool_and_keep_pending(work, pool->id);
1253 spin_unlock(&pool->lock);
1257 spin_unlock(&pool->lock);
1260 local_unlock_irqrestore(pendingb_lock, *flags);
1261 if (work_is_canceling(work))
1268 * insert_work - insert a work into a pool
1269 * @pwq: pwq @work belongs to
1270 * @work: work to insert
1271 * @head: insertion point
1272 * @extra_flags: extra WORK_STRUCT_* flags to set
1274 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
1275 * work_struct flags.
1278 * spin_lock_irq(pool->lock).
1280 static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1281 struct list_head *head, unsigned int extra_flags)
1283 struct worker_pool *pool = pwq->pool;
1285 /* we own @work, set data and link */
1286 set_work_pwq(work, pwq, extra_flags);
1287 list_add_tail(&work->entry, head);
1291 * Ensure either wq_worker_sleeping() sees the above
1292 * list_add_tail() or we see zero nr_running to avoid workers lying
1293 * around lazily while there are works to be processed.
1297 if (__need_more_worker(pool))
1298 wake_up_worker(pool);
1302 * Test whether @work is being queued from another work executing on the
1305 static bool is_chained_work(struct workqueue_struct *wq)
1307 struct worker *worker;
1309 worker = current_wq_worker();
1311 * Return %true iff I'm a worker execuing a work item on @wq. If
1312 * I'm @worker, it's safe to dereference it without locking.
1314 return worker && worker->current_pwq->wq == wq;
1317 static void __queue_work(int cpu, struct workqueue_struct *wq,
1318 struct work_struct *work)
1320 struct pool_workqueue *pwq;
1321 struct worker_pool *last_pool;
1322 struct list_head *worklist;
1323 unsigned int work_flags;
1324 unsigned int req_cpu = cpu;
1327 * While a work item is PENDING && off queue, a task trying to
1328 * steal the PENDING will busy-loop waiting for it to either get
1329 * queued or lose PENDING. Grabbing PENDING and queueing should
1330 * happen with IRQ disabled.
1332 WARN_ON_ONCE_NONRT(!irqs_disabled());
1334 debug_work_activate(work);
1336 /* if draining, only works from the same workqueue are allowed */
1337 if (unlikely(wq->flags & __WQ_DRAINING) &&
1338 WARN_ON_ONCE(!is_chained_work(wq)))
1343 if (req_cpu == WORK_CPU_UNBOUND)
1344 cpu = raw_smp_processor_id();
1346 /* pwq which will be used unless @work is executing elsewhere */
1347 if (!(wq->flags & WQ_UNBOUND))
1348 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1350 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1353 * If @work was previously on a different pool, it might still be
1354 * running there, in which case the work needs to be queued on that
1355 * pool to guarantee non-reentrancy.
1357 last_pool = get_work_pool(work);
1358 if (last_pool && last_pool != pwq->pool) {
1359 struct worker *worker;
1361 spin_lock(&last_pool->lock);
1363 worker = find_worker_executing_work(last_pool, work);
1365 if (worker && worker->current_pwq->wq == wq) {
1366 pwq = worker->current_pwq;
1368 /* meh... not running there, queue here */
1369 spin_unlock(&last_pool->lock);
1370 spin_lock(&pwq->pool->lock);
1373 spin_lock(&pwq->pool->lock);
1377 * pwq is determined and locked. For unbound pools, we could have
1378 * raced with pwq release and it could already be dead. If its
1379 * refcnt is zero, repeat pwq selection. Note that pwqs never die
1380 * without another pwq replacing it in the numa_pwq_tbl or while
1381 * work items are executing on it, so the retrying is guaranteed to
1382 * make forward-progress.
1384 if (unlikely(!pwq->refcnt)) {
1385 if (wq->flags & WQ_UNBOUND) {
1386 spin_unlock(&pwq->pool->lock);
1391 WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
1395 /* pwq determined, queue */
1396 trace_workqueue_queue_work(req_cpu, pwq, work);
1398 if (WARN_ON(!list_empty(&work->entry)))
1401 pwq->nr_in_flight[pwq->work_color]++;
1402 work_flags = work_color_to_flags(pwq->work_color);
1404 if (likely(pwq->nr_active < pwq->max_active)) {
1405 trace_workqueue_activate_work(work);
1407 worklist = &pwq->pool->worklist;
1409 work_flags |= WORK_STRUCT_DELAYED;
1410 worklist = &pwq->delayed_works;
1413 insert_work(pwq, work, worklist, work_flags);
1416 spin_unlock(&pwq->pool->lock);
1421 * queue_work_on - queue work on specific cpu
1422 * @cpu: CPU number to execute work on
1423 * @wq: workqueue to use
1424 * @work: work to queue
1426 * We queue the work to a specific CPU, the caller must ensure it
1429 * Return: %false if @work was already on a queue, %true otherwise.
1431 bool queue_work_on(int cpu, struct workqueue_struct *wq,
1432 struct work_struct *work)
1435 unsigned long flags;
1437 local_lock_irqsave(pendingb_lock,flags);
1439 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1440 __queue_work(cpu, wq, work);
1444 local_unlock_irqrestore(pendingb_lock, flags);
1447 EXPORT_SYMBOL(queue_work_on);
1449 void delayed_work_timer_fn(unsigned long __data)
1451 struct delayed_work *dwork = (struct delayed_work *)__data;
1453 /* should have been called from irqsafe timer with irq already off */
1454 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
1456 EXPORT_SYMBOL(delayed_work_timer_fn);
1458 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
1459 struct delayed_work *dwork, unsigned long delay)
1461 struct timer_list *timer = &dwork->timer;
1462 struct work_struct *work = &dwork->work;
1464 WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
1465 timer->data != (unsigned long)dwork);
1466 WARN_ON_ONCE(timer_pending(timer));
1467 WARN_ON_ONCE(!list_empty(&work->entry));
1470 * If @delay is 0, queue @dwork->work immediately. This is for
1471 * both optimization and correctness. The earliest @timer can
1472 * expire is on the closest next tick and delayed_work users depend
1473 * on that there's no such delay when @delay is 0.
1476 __queue_work(cpu, wq, &dwork->work);
1480 timer_stats_timer_set_start_info(&dwork->timer);
1484 timer->expires = jiffies + delay;
1486 if (unlikely(cpu != WORK_CPU_UNBOUND))
1487 add_timer_on(timer, cpu);
1493 * queue_delayed_work_on - queue work on specific CPU after delay
1494 * @cpu: CPU number to execute work on
1495 * @wq: workqueue to use
1496 * @dwork: work to queue
1497 * @delay: number of jiffies to wait before queueing
1499 * Return: %false if @work was already on a queue, %true otherwise. If
1500 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1503 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1504 struct delayed_work *dwork, unsigned long delay)
1506 struct work_struct *work = &dwork->work;
1508 unsigned long flags;
1510 /* read the comment in __queue_work() */
1511 local_lock_irqsave(pendingb_lock, flags);
1513 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1514 __queue_delayed_work(cpu, wq, dwork, delay);
1518 local_unlock_irqrestore(pendingb_lock, flags);
1521 EXPORT_SYMBOL(queue_delayed_work_on);
1524 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1525 * @cpu: CPU number to execute work on
1526 * @wq: workqueue to use
1527 * @dwork: work to queue
1528 * @delay: number of jiffies to wait before queueing
1530 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1531 * modify @dwork's timer so that it expires after @delay. If @delay is
1532 * zero, @work is guaranteed to be scheduled immediately regardless of its
1535 * Return: %false if @dwork was idle and queued, %true if @dwork was
1536 * pending and its timer was modified.
1538 * This function is safe to call from any context including IRQ handler.
1539 * See try_to_grab_pending() for details.
1541 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
1542 struct delayed_work *dwork, unsigned long delay)
1544 unsigned long flags;
1548 ret = try_to_grab_pending(&dwork->work, true, &flags);
1549 } while (unlikely(ret == -EAGAIN));
1551 if (likely(ret >= 0)) {
1552 __queue_delayed_work(cpu, wq, dwork, delay);
1553 local_unlock_irqrestore(pendingb_lock, flags);
1556 /* -ENOENT from try_to_grab_pending() becomes %true */
1559 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
1562 * worker_enter_idle - enter idle state
1563 * @worker: worker which is entering idle state
1565 * @worker is entering idle state. Update stats and idle timer if
1569 * spin_lock_irq(pool->lock).
1571 static void worker_enter_idle(struct worker *worker)
1573 struct worker_pool *pool = worker->pool;
1575 if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
1576 WARN_ON_ONCE(!list_empty(&worker->entry) &&
1577 (worker->hentry.next || worker->hentry.pprev)))
1580 /* can't use worker_set_flags(), also called from create_worker() */
1581 worker->flags |= WORKER_IDLE;
1583 worker->last_active = jiffies;
1585 /* idle_list is LIFO */
1586 rt_lock_idle_list(pool);
1587 list_add(&worker->entry, &pool->idle_list);
1588 rt_unlock_idle_list(pool);
1590 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1591 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1594 * Sanity check nr_running. Because wq_unbind_fn() releases
1595 * pool->lock between setting %WORKER_UNBOUND and zapping
1596 * nr_running, the warning may trigger spuriously. Check iff
1597 * unbind is not in progress.
1599 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1600 pool->nr_workers == pool->nr_idle &&
1601 atomic_read(&pool->nr_running));
1605 * worker_leave_idle - leave idle state
1606 * @worker: worker which is leaving idle state
1608 * @worker is leaving idle state. Update stats.
1611 * spin_lock_irq(pool->lock).
1613 static void worker_leave_idle(struct worker *worker)
1615 struct worker_pool *pool = worker->pool;
1617 if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
1619 worker_clr_flags(worker, WORKER_IDLE);
1621 rt_lock_idle_list(pool);
1622 list_del_init(&worker->entry);
1623 rt_unlock_idle_list(pool);
1626 static struct worker *alloc_worker(int node)
1628 struct worker *worker;
1630 worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
1632 INIT_LIST_HEAD(&worker->entry);
1633 INIT_LIST_HEAD(&worker->scheduled);
1634 INIT_LIST_HEAD(&worker->node);
1635 /* on creation a worker is in !idle && prep state */
1636 worker->flags = WORKER_PREP;
1642 * worker_attach_to_pool() - attach a worker to a pool
1643 * @worker: worker to be attached
1644 * @pool: the target pool
1646 * Attach @worker to @pool. Once attached, the %WORKER_UNBOUND flag and
1647 * cpu-binding of @worker are kept coordinated with the pool across
1650 static void worker_attach_to_pool(struct worker *worker,
1651 struct worker_pool *pool)
1653 mutex_lock(&pool->attach_mutex);
1656 * set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
1657 * online CPUs. It'll be re-applied when any of the CPUs come up.
1659 set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
1662 * The pool->attach_mutex ensures %POOL_DISASSOCIATED remains
1663 * stable across this function. See the comments above the
1664 * flag definition for details.
1666 if (pool->flags & POOL_DISASSOCIATED)
1667 worker->flags |= WORKER_UNBOUND;
1669 list_add_tail(&worker->node, &pool->workers);
1671 mutex_unlock(&pool->attach_mutex);
1675 * worker_detach_from_pool() - detach a worker from its pool
1676 * @worker: worker which is attached to its pool
1677 * @pool: the pool @worker is attached to
1679 * Undo the attaching which had been done in worker_attach_to_pool(). The
1680 * caller worker shouldn't access to the pool after detached except it has
1681 * other reference to the pool.
1683 static void worker_detach_from_pool(struct worker *worker,
1684 struct worker_pool *pool)
1686 struct completion *detach_completion = NULL;
1688 mutex_lock(&pool->attach_mutex);
1689 list_del(&worker->node);
1690 if (list_empty(&pool->workers))
1691 detach_completion = pool->detach_completion;
1692 mutex_unlock(&pool->attach_mutex);
1694 /* clear leftover flags without pool->lock after it is detached */
1695 worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
1697 if (detach_completion)
1698 complete(detach_completion);
1702 * create_worker - create a new workqueue worker
1703 * @pool: pool the new worker will belong to
1705 * Create and start a new worker which is attached to @pool.
1708 * Might sleep. Does GFP_KERNEL allocations.
1711 * Pointer to the newly created worker.
1713 static struct worker *create_worker(struct worker_pool *pool)
1715 struct worker *worker = NULL;
1719 /* ID is needed to determine kthread name */
1720 id = ida_simple_get(&pool->worker_ida, 0, 0, GFP_KERNEL);
1724 worker = alloc_worker(pool->node);
1728 worker->pool = pool;
1732 snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
1733 pool->attrs->nice < 0 ? "H" : "");
1735 snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
1737 worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
1738 "kworker/%s", id_buf);
1739 if (IS_ERR(worker->task))
1742 set_user_nice(worker->task, pool->attrs->nice);
1744 /* prevent userland from meddling with cpumask of workqueue workers */
1745 worker->task->flags |= PF_NO_SETAFFINITY;
1747 /* successful, attach the worker to the pool */
1748 worker_attach_to_pool(worker, pool);
1750 /* start the newly created worker */
1751 spin_lock_irq(&pool->lock);
1752 worker->pool->nr_workers++;
1753 worker_enter_idle(worker);
1754 wake_up_process(worker->task);
1755 spin_unlock_irq(&pool->lock);
1761 ida_simple_remove(&pool->worker_ida, id);
1767 * destroy_worker - destroy a workqueue worker
1768 * @worker: worker to be destroyed
1770 * Destroy @worker and adjust @pool stats accordingly. The worker should
1774 * spin_lock_irq(pool->lock).
1776 static void destroy_worker(struct worker *worker)
1778 struct worker_pool *pool = worker->pool;
1780 lockdep_assert_held(&pool->lock);
1782 /* sanity check frenzy */
1783 if (WARN_ON(worker->current_work) ||
1784 WARN_ON(!list_empty(&worker->scheduled)) ||
1785 WARN_ON(!(worker->flags & WORKER_IDLE)))
1791 rt_lock_idle_list(pool);
1792 list_del_init(&worker->entry);
1793 rt_unlock_idle_list(pool);
1794 worker->flags |= WORKER_DIE;
1795 wake_up_process(worker->task);
1798 static void idle_worker_timeout(unsigned long __pool)
1800 struct worker_pool *pool = (void *)__pool;
1802 spin_lock_irq(&pool->lock);
1804 while (too_many_workers(pool)) {
1805 struct worker *worker;
1806 unsigned long expires;
1808 /* idle_list is kept in LIFO order, check the last one */
1809 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1810 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1812 if (time_before(jiffies, expires)) {
1813 mod_timer(&pool->idle_timer, expires);
1817 destroy_worker(worker);
1820 spin_unlock_irq(&pool->lock);
1823 static void send_mayday(struct work_struct *work)
1825 struct pool_workqueue *pwq = get_work_pwq(work);
1826 struct workqueue_struct *wq = pwq->wq;
1828 lockdep_assert_held(&wq_mayday_lock);
1833 /* mayday mayday mayday */
1834 if (list_empty(&pwq->mayday_node)) {
1836 * If @pwq is for an unbound wq, its base ref may be put at
1837 * any time due to an attribute change. Pin @pwq until the
1838 * rescuer is done with it.
1841 list_add_tail(&pwq->mayday_node, &wq->maydays);
1842 wake_up_process(wq->rescuer->task);
1846 static void pool_mayday_timeout(unsigned long __pool)
1848 struct worker_pool *pool = (void *)__pool;
1849 struct work_struct *work;
1851 spin_lock_irq(&pool->lock);
1852 spin_lock(&wq_mayday_lock); /* for wq->maydays */
1854 if (need_to_create_worker(pool)) {
1856 * We've been trying to create a new worker but
1857 * haven't been successful. We might be hitting an
1858 * allocation deadlock. Send distress signals to
1861 list_for_each_entry(work, &pool->worklist, entry)
1865 spin_unlock(&wq_mayday_lock);
1866 spin_unlock_irq(&pool->lock);
1868 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1872 * maybe_create_worker - create a new worker if necessary
1873 * @pool: pool to create a new worker for
1875 * Create a new worker for @pool if necessary. @pool is guaranteed to
1876 * have at least one idle worker on return from this function. If
1877 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1878 * sent to all rescuers with works scheduled on @pool to resolve
1879 * possible allocation deadlock.
1881 * On return, need_to_create_worker() is guaranteed to be %false and
1882 * may_start_working() %true.
1885 * spin_lock_irq(pool->lock) which may be released and regrabbed
1886 * multiple times. Does GFP_KERNEL allocations. Called only from
1889 static void maybe_create_worker(struct worker_pool *pool)
1890 __releases(&pool->lock)
1891 __acquires(&pool->lock)
1894 spin_unlock_irq(&pool->lock);
1896 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1897 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1900 if (create_worker(pool) || !need_to_create_worker(pool))
1903 schedule_timeout_interruptible(CREATE_COOLDOWN);
1905 if (!need_to_create_worker(pool))
1909 del_timer_sync(&pool->mayday_timer);
1910 spin_lock_irq(&pool->lock);
1912 * This is necessary even after a new worker was just successfully
1913 * created as @pool->lock was dropped and the new worker might have
1914 * already become busy.
1916 if (need_to_create_worker(pool))
1921 * manage_workers - manage worker pool
1924 * Assume the manager role and manage the worker pool @worker belongs
1925 * to. At any given time, there can be only zero or one manager per
1926 * pool. The exclusion is handled automatically by this function.
1928 * The caller can safely start processing works on false return. On
1929 * true return, it's guaranteed that need_to_create_worker() is false
1930 * and may_start_working() is true.
1933 * spin_lock_irq(pool->lock) which may be released and regrabbed
1934 * multiple times. Does GFP_KERNEL allocations.
1937 * %false if the pool doesn't need management and the caller can safely
1938 * start processing works, %true if management function was performed and
1939 * the conditions that the caller verified before calling the function may
1940 * no longer be true.
1942 static bool manage_workers(struct worker *worker)
1944 struct worker_pool *pool = worker->pool;
1947 * Anyone who successfully grabs manager_arb wins the arbitration
1948 * and becomes the manager. mutex_trylock() on pool->manager_arb
1949 * failure while holding pool->lock reliably indicates that someone
1950 * else is managing the pool and the worker which failed trylock
1951 * can proceed to executing work items. This means that anyone
1952 * grabbing manager_arb is responsible for actually performing
1953 * manager duties. If manager_arb is grabbed and released without
1954 * actual management, the pool may stall indefinitely.
1956 if (!mutex_trylock(&pool->manager_arb))
1958 pool->manager = worker;
1960 maybe_create_worker(pool);
1962 pool->manager = NULL;
1963 mutex_unlock(&pool->manager_arb);
1968 * process_one_work - process single work
1970 * @work: work to process
1972 * Process @work. This function contains all the logics necessary to
1973 * process a single work including synchronization against and
1974 * interaction with other workers on the same cpu, queueing and
1975 * flushing. As long as context requirement is met, any worker can
1976 * call this function to process a work.
1979 * spin_lock_irq(pool->lock) which is released and regrabbed.
1981 static void process_one_work(struct worker *worker, struct work_struct *work)
1982 __releases(&pool->lock)
1983 __acquires(&pool->lock)
1985 struct pool_workqueue *pwq = get_work_pwq(work);
1986 struct worker_pool *pool = worker->pool;
1987 bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
1989 struct worker *collision;
1990 #ifdef CONFIG_LOCKDEP
1992 * It is permissible to free the struct work_struct from
1993 * inside the function that is called from it, this we need to
1994 * take into account for lockdep too. To avoid bogus "held
1995 * lock freed" warnings as well as problems when looking into
1996 * work->lockdep_map, make a copy and use that here.
1998 struct lockdep_map lockdep_map;
2000 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
2002 /* ensure we're on the correct CPU */
2003 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2004 raw_smp_processor_id() != pool->cpu);
2007 * A single work shouldn't be executed concurrently by
2008 * multiple workers on a single cpu. Check whether anyone is
2009 * already processing the work. If so, defer the work to the
2010 * currently executing one.
2012 collision = find_worker_executing_work(pool, work);
2013 if (unlikely(collision)) {
2014 move_linked_works(work, &collision->scheduled, NULL);
2018 /* claim and dequeue */
2019 debug_work_deactivate(work);
2020 hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2021 worker->current_work = work;
2022 worker->current_func = work->func;
2023 worker->current_pwq = pwq;
2024 work_color = get_work_color(work);
2026 list_del_init(&work->entry);
2029 * CPU intensive works don't participate in concurrency management.
2030 * They're the scheduler's responsibility. This takes @worker out
2031 * of concurrency management and the next code block will chain
2032 * execution of the pending work items.
2034 if (unlikely(cpu_intensive))
2035 worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2038 * Wake up another worker if necessary. The condition is always
2039 * false for normal per-cpu workers since nr_running would always
2040 * be >= 1 at this point. This is used to chain execution of the
2041 * pending work items for WORKER_NOT_RUNNING workers such as the
2042 * UNBOUND and CPU_INTENSIVE ones.
2044 if (need_more_worker(pool))
2045 wake_up_worker(pool);
2048 * Record the last pool and clear PENDING which should be the last
2049 * update to @work. Also, do this inside @pool->lock so that
2050 * PENDING and queued state changes happen together while IRQ is
2053 set_work_pool_and_clear_pending(work, pool->id);
2055 spin_unlock_irq(&pool->lock);
2057 lock_map_acquire_read(&pwq->wq->lockdep_map);
2058 lock_map_acquire(&lockdep_map);
2059 trace_workqueue_execute_start(work);
2060 worker->current_func(work);
2062 * While we must be careful to not use "work" after this, the trace
2063 * point will only record its address.
2065 trace_workqueue_execute_end(work);
2066 lock_map_release(&lockdep_map);
2067 lock_map_release(&pwq->wq->lockdep_map);
2069 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2070 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2071 " last function: %pf\n",
2072 current->comm, preempt_count(), task_pid_nr(current),
2073 worker->current_func);
2074 debug_show_held_locks(current);
2079 * The following prevents a kworker from hogging CPU on !PREEMPT
2080 * kernels, where a requeueing work item waiting for something to
2081 * happen could deadlock with stop_machine as such work item could
2082 * indefinitely requeue itself while all other CPUs are trapped in
2083 * stop_machine. At the same time, report a quiescent RCU state so
2084 * the same condition doesn't freeze RCU.
2086 cond_resched_rcu_qs();
2088 spin_lock_irq(&pool->lock);
2090 /* clear cpu intensive status */
2091 if (unlikely(cpu_intensive))
2092 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2094 /* we're done with it, release */
2095 hash_del(&worker->hentry);
2096 worker->current_work = NULL;
2097 worker->current_func = NULL;
2098 worker->current_pwq = NULL;
2099 worker->desc_valid = false;
2100 pwq_dec_nr_in_flight(pwq, work_color);
2104 * process_scheduled_works - process scheduled works
2107 * Process all scheduled works. Please note that the scheduled list
2108 * may change while processing a work, so this function repeatedly
2109 * fetches a work from the top and executes it.
2112 * spin_lock_irq(pool->lock) which may be released and regrabbed
2115 static void process_scheduled_works(struct worker *worker)
2117 while (!list_empty(&worker->scheduled)) {
2118 struct work_struct *work = list_first_entry(&worker->scheduled,
2119 struct work_struct, entry);
2120 process_one_work(worker, work);
2125 * worker_thread - the worker thread function
2128 * The worker thread function. All workers belong to a worker_pool -
2129 * either a per-cpu one or dynamic unbound one. These workers process all
2130 * work items regardless of their specific target workqueue. The only
2131 * exception is work items which belong to workqueues with a rescuer which
2132 * will be explained in rescuer_thread().
2136 static int worker_thread(void *__worker)
2138 struct worker *worker = __worker;
2139 struct worker_pool *pool = worker->pool;
2141 /* tell the scheduler that this is a workqueue worker */
2142 worker->task->flags |= PF_WQ_WORKER;
2144 spin_lock_irq(&pool->lock);
2146 /* am I supposed to die? */
2147 if (unlikely(worker->flags & WORKER_DIE)) {
2148 spin_unlock_irq(&pool->lock);
2149 WARN_ON_ONCE(!list_empty(&worker->entry));
2150 worker->task->flags &= ~PF_WQ_WORKER;
2152 set_task_comm(worker->task, "kworker/dying");
2153 ida_simple_remove(&pool->worker_ida, worker->id);
2154 worker_detach_from_pool(worker, pool);
2159 worker_leave_idle(worker);
2161 /* no more worker necessary? */
2162 if (!need_more_worker(pool))
2165 /* do we need to manage? */
2166 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2170 * ->scheduled list can only be filled while a worker is
2171 * preparing to process a work or actually processing it.
2172 * Make sure nobody diddled with it while I was sleeping.
2174 WARN_ON_ONCE(!list_empty(&worker->scheduled));
2177 * Finish PREP stage. We're guaranteed to have at least one idle
2178 * worker or that someone else has already assumed the manager
2179 * role. This is where @worker starts participating in concurrency
2180 * management if applicable and concurrency management is restored
2181 * after being rebound. See rebind_workers() for details.
2183 worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2186 struct work_struct *work =
2187 list_first_entry(&pool->worklist,
2188 struct work_struct, entry);
2190 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2191 /* optimization path, not strictly necessary */
2192 process_one_work(worker, work);
2193 if (unlikely(!list_empty(&worker->scheduled)))
2194 process_scheduled_works(worker);
2196 move_linked_works(work, &worker->scheduled, NULL);
2197 process_scheduled_works(worker);
2199 } while (keep_working(pool));
2201 worker_set_flags(worker, WORKER_PREP);
2204 * pool->lock is held and there's no work to process and no need to
2205 * manage, sleep. Workers are woken up only while holding
2206 * pool->lock or from local cpu, so setting the current state
2207 * before releasing pool->lock is enough to prevent losing any
2210 worker_enter_idle(worker);
2211 __set_current_state(TASK_INTERRUPTIBLE);
2212 spin_unlock_irq(&pool->lock);
2218 * rescuer_thread - the rescuer thread function
2221 * Workqueue rescuer thread function. There's one rescuer for each
2222 * workqueue which has WQ_MEM_RECLAIM set.
2224 * Regular work processing on a pool may block trying to create a new
2225 * worker which uses GFP_KERNEL allocation which has slight chance of
2226 * developing into deadlock if some works currently on the same queue
2227 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2228 * the problem rescuer solves.
2230 * When such condition is possible, the pool summons rescuers of all
2231 * workqueues which have works queued on the pool and let them process
2232 * those works so that forward progress can be guaranteed.
2234 * This should happen rarely.
2238 static int rescuer_thread(void *__rescuer)
2240 struct worker *rescuer = __rescuer;
2241 struct workqueue_struct *wq = rescuer->rescue_wq;
2242 struct list_head *scheduled = &rescuer->scheduled;
2245 set_user_nice(current, RESCUER_NICE_LEVEL);
2248 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2249 * doesn't participate in concurrency management.
2251 rescuer->task->flags |= PF_WQ_WORKER;
2253 set_current_state(TASK_INTERRUPTIBLE);
2256 * By the time the rescuer is requested to stop, the workqueue
2257 * shouldn't have any work pending, but @wq->maydays may still have
2258 * pwq(s) queued. This can happen by non-rescuer workers consuming
2259 * all the work items before the rescuer got to them. Go through
2260 * @wq->maydays processing before acting on should_stop so that the
2261 * list is always empty on exit.
2263 should_stop = kthread_should_stop();
2265 /* see whether any pwq is asking for help */
2266 spin_lock_irq(&wq_mayday_lock);
2268 while (!list_empty(&wq->maydays)) {
2269 struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2270 struct pool_workqueue, mayday_node);
2271 struct worker_pool *pool = pwq->pool;
2272 struct work_struct *work, *n;
2274 __set_current_state(TASK_RUNNING);
2275 list_del_init(&pwq->mayday_node);
2277 spin_unlock_irq(&wq_mayday_lock);
2279 worker_attach_to_pool(rescuer, pool);
2281 spin_lock_irq(&pool->lock);
2282 rescuer->pool = pool;
2285 * Slurp in all works issued via this workqueue and
2288 WARN_ON_ONCE(!list_empty(scheduled));
2289 list_for_each_entry_safe(work, n, &pool->worklist, entry)
2290 if (get_work_pwq(work) == pwq)
2291 move_linked_works(work, scheduled, &n);
2293 if (!list_empty(scheduled)) {
2294 process_scheduled_works(rescuer);
2297 * The above execution of rescued work items could
2298 * have created more to rescue through
2299 * pwq_activate_first_delayed() or chained
2300 * queueing. Let's put @pwq back on mayday list so
2301 * that such back-to-back work items, which may be
2302 * being used to relieve memory pressure, don't
2303 * incur MAYDAY_INTERVAL delay inbetween.
2305 if (need_to_create_worker(pool)) {
2306 spin_lock(&wq_mayday_lock);
2308 list_move_tail(&pwq->mayday_node, &wq->maydays);
2309 spin_unlock(&wq_mayday_lock);
2314 * Put the reference grabbed by send_mayday(). @pool won't
2315 * go away while we're still attached to it.
2320 * Leave this pool. If need_more_worker() is %true, notify a
2321 * regular worker; otherwise, we end up with 0 concurrency
2322 * and stalling the execution.
2324 if (need_more_worker(pool))
2325 wake_up_worker(pool);
2327 rescuer->pool = NULL;
2328 spin_unlock_irq(&pool->lock);
2330 worker_detach_from_pool(rescuer, pool);
2332 spin_lock_irq(&wq_mayday_lock);
2335 spin_unlock_irq(&wq_mayday_lock);
2338 __set_current_state(TASK_RUNNING);
2339 rescuer->task->flags &= ~PF_WQ_WORKER;
2343 /* rescuers should never participate in concurrency management */
2344 WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2350 struct work_struct work;
2351 struct completion done;
2352 struct task_struct *task; /* purely informational */
2355 static void wq_barrier_func(struct work_struct *work)
2357 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2358 complete(&barr->done);
2362 * insert_wq_barrier - insert a barrier work
2363 * @pwq: pwq to insert barrier into
2364 * @barr: wq_barrier to insert
2365 * @target: target work to attach @barr to
2366 * @worker: worker currently executing @target, NULL if @target is not executing
2368 * @barr is linked to @target such that @barr is completed only after
2369 * @target finishes execution. Please note that the ordering
2370 * guarantee is observed only with respect to @target and on the local
2373 * Currently, a queued barrier can't be canceled. This is because
2374 * try_to_grab_pending() can't determine whether the work to be
2375 * grabbed is at the head of the queue and thus can't clear LINKED
2376 * flag of the previous work while there must be a valid next work
2377 * after a work with LINKED flag set.
2379 * Note that when @worker is non-NULL, @target may be modified
2380 * underneath us, so we can't reliably determine pwq from @target.
2383 * spin_lock_irq(pool->lock).
2385 static void insert_wq_barrier(struct pool_workqueue *pwq,
2386 struct wq_barrier *barr,
2387 struct work_struct *target, struct worker *worker)
2389 struct list_head *head;
2390 unsigned int linked = 0;
2393 * debugobject calls are safe here even with pool->lock locked
2394 * as we know for sure that this will not trigger any of the
2395 * checks and call back into the fixup functions where we
2398 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2399 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2400 init_completion(&barr->done);
2401 barr->task = current;
2404 * If @target is currently being executed, schedule the
2405 * barrier to the worker; otherwise, put it after @target.
2408 head = worker->scheduled.next;
2410 unsigned long *bits = work_data_bits(target);
2412 head = target->entry.next;
2413 /* there can already be other linked works, inherit and set */
2414 linked = *bits & WORK_STRUCT_LINKED;
2415 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2418 debug_work_activate(&barr->work);
2419 insert_work(pwq, &barr->work, head,
2420 work_color_to_flags(WORK_NO_COLOR) | linked);
2424 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
2425 * @wq: workqueue being flushed
2426 * @flush_color: new flush color, < 0 for no-op
2427 * @work_color: new work color, < 0 for no-op
2429 * Prepare pwqs for workqueue flushing.
2431 * If @flush_color is non-negative, flush_color on all pwqs should be
2432 * -1. If no pwq has in-flight commands at the specified color, all
2433 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
2434 * has in flight commands, its pwq->flush_color is set to
2435 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
2436 * wakeup logic is armed and %true is returned.
2438 * The caller should have initialized @wq->first_flusher prior to
2439 * calling this function with non-negative @flush_color. If
2440 * @flush_color is negative, no flush color update is done and %false
2443 * If @work_color is non-negative, all pwqs should have the same
2444 * work_color which is previous to @work_color and all will be
2445 * advanced to @work_color.
2448 * mutex_lock(wq->mutex).
2451 * %true if @flush_color >= 0 and there's something to flush. %false
2454 static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
2455 int flush_color, int work_color)
2458 struct pool_workqueue *pwq;
2460 if (flush_color >= 0) {
2461 WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2462 atomic_set(&wq->nr_pwqs_to_flush, 1);
2465 for_each_pwq(pwq, wq) {
2466 struct worker_pool *pool = pwq->pool;
2468 spin_lock_irq(&pool->lock);
2470 if (flush_color >= 0) {
2471 WARN_ON_ONCE(pwq->flush_color != -1);
2473 if (pwq->nr_in_flight[flush_color]) {
2474 pwq->flush_color = flush_color;
2475 atomic_inc(&wq->nr_pwqs_to_flush);
2480 if (work_color >= 0) {
2481 WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2482 pwq->work_color = work_color;
2485 spin_unlock_irq(&pool->lock);
2488 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
2489 complete(&wq->first_flusher->done);
2495 * flush_workqueue - ensure that any scheduled work has run to completion.
2496 * @wq: workqueue to flush
2498 * This function sleeps until all work items which were queued on entry
2499 * have finished execution, but it is not livelocked by new incoming ones.
2501 void flush_workqueue(struct workqueue_struct *wq)
2503 struct wq_flusher this_flusher = {
2504 .list = LIST_HEAD_INIT(this_flusher.list),
2506 .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
2510 lock_map_acquire(&wq->lockdep_map);
2511 lock_map_release(&wq->lockdep_map);
2513 mutex_lock(&wq->mutex);
2516 * Start-to-wait phase
2518 next_color = work_next_color(wq->work_color);
2520 if (next_color != wq->flush_color) {
2522 * Color space is not full. The current work_color
2523 * becomes our flush_color and work_color is advanced
2526 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
2527 this_flusher.flush_color = wq->work_color;
2528 wq->work_color = next_color;
2530 if (!wq->first_flusher) {
2531 /* no flush in progress, become the first flusher */
2532 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2534 wq->first_flusher = &this_flusher;
2536 if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
2538 /* nothing to flush, done */
2539 wq->flush_color = next_color;
2540 wq->first_flusher = NULL;
2545 WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
2546 list_add_tail(&this_flusher.list, &wq->flusher_queue);
2547 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2551 * Oops, color space is full, wait on overflow queue.
2552 * The next flush completion will assign us
2553 * flush_color and transfer to flusher_queue.
2555 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2558 mutex_unlock(&wq->mutex);
2560 wait_for_completion(&this_flusher.done);
2563 * Wake-up-and-cascade phase
2565 * First flushers are responsible for cascading flushes and
2566 * handling overflow. Non-first flushers can simply return.
2568 if (wq->first_flusher != &this_flusher)
2571 mutex_lock(&wq->mutex);
2573 /* we might have raced, check again with mutex held */
2574 if (wq->first_flusher != &this_flusher)
2577 wq->first_flusher = NULL;
2579 WARN_ON_ONCE(!list_empty(&this_flusher.list));
2580 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2583 struct wq_flusher *next, *tmp;
2585 /* complete all the flushers sharing the current flush color */
2586 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2587 if (next->flush_color != wq->flush_color)
2589 list_del_init(&next->list);
2590 complete(&next->done);
2593 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
2594 wq->flush_color != work_next_color(wq->work_color));
2596 /* this flush_color is finished, advance by one */
2597 wq->flush_color = work_next_color(wq->flush_color);
2599 /* one color has been freed, handle overflow queue */
2600 if (!list_empty(&wq->flusher_overflow)) {
2602 * Assign the same color to all overflowed
2603 * flushers, advance work_color and append to
2604 * flusher_queue. This is the start-to-wait
2605 * phase for these overflowed flushers.
2607 list_for_each_entry(tmp, &wq->flusher_overflow, list)
2608 tmp->flush_color = wq->work_color;
2610 wq->work_color = work_next_color(wq->work_color);
2612 list_splice_tail_init(&wq->flusher_overflow,
2613 &wq->flusher_queue);
2614 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2617 if (list_empty(&wq->flusher_queue)) {
2618 WARN_ON_ONCE(wq->flush_color != wq->work_color);
2623 * Need to flush more colors. Make the next flusher
2624 * the new first flusher and arm pwqs.
2626 WARN_ON_ONCE(wq->flush_color == wq->work_color);
2627 WARN_ON_ONCE(wq->flush_color != next->flush_color);
2629 list_del_init(&next->list);
2630 wq->first_flusher = next;
2632 if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
2636 * Meh... this color is already done, clear first
2637 * flusher and repeat cascading.
2639 wq->first_flusher = NULL;
2643 mutex_unlock(&wq->mutex);
2645 EXPORT_SYMBOL_GPL(flush_workqueue);
2648 * drain_workqueue - drain a workqueue
2649 * @wq: workqueue to drain
2651 * Wait until the workqueue becomes empty. While draining is in progress,
2652 * only chain queueing is allowed. IOW, only currently pending or running
2653 * work items on @wq can queue further work items on it. @wq is flushed
2654 * repeatedly until it becomes empty. The number of flushing is detemined
2655 * by the depth of chaining and should be relatively short. Whine if it
2658 void drain_workqueue(struct workqueue_struct *wq)
2660 unsigned int flush_cnt = 0;
2661 struct pool_workqueue *pwq;
2664 * __queue_work() needs to test whether there are drainers, is much
2665 * hotter than drain_workqueue() and already looks at @wq->flags.
2666 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
2668 mutex_lock(&wq->mutex);
2669 if (!wq->nr_drainers++)
2670 wq->flags |= __WQ_DRAINING;
2671 mutex_unlock(&wq->mutex);
2673 flush_workqueue(wq);
2675 mutex_lock(&wq->mutex);
2677 for_each_pwq(pwq, wq) {
2680 spin_lock_irq(&pwq->pool->lock);
2681 drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
2682 spin_unlock_irq(&pwq->pool->lock);
2687 if (++flush_cnt == 10 ||
2688 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2689 pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
2690 wq->name, flush_cnt);
2692 mutex_unlock(&wq->mutex);
2696 if (!--wq->nr_drainers)
2697 wq->flags &= ~__WQ_DRAINING;
2698 mutex_unlock(&wq->mutex);
2700 EXPORT_SYMBOL_GPL(drain_workqueue);
2702 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2704 struct worker *worker = NULL;
2705 struct worker_pool *pool;
2706 struct pool_workqueue *pwq;
2711 pool = get_work_pool(work);
2717 spin_lock_irq(&pool->lock);
2718 /* see the comment in try_to_grab_pending() with the same code */
2719 pwq = get_work_pwq(work);
2721 if (unlikely(pwq->pool != pool))
2724 worker = find_worker_executing_work(pool, work);
2727 pwq = worker->current_pwq;
2730 insert_wq_barrier(pwq, barr, work, worker);
2731 spin_unlock_irq(&pool->lock);
2734 * If @max_active is 1 or rescuer is in use, flushing another work
2735 * item on the same workqueue may lead to deadlock. Make sure the
2736 * flusher is not running on the same workqueue by verifying write
2739 if (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)
2740 lock_map_acquire(&pwq->wq->lockdep_map);
2742 lock_map_acquire_read(&pwq->wq->lockdep_map);
2743 lock_map_release(&pwq->wq->lockdep_map);
2747 spin_unlock_irq(&pool->lock);
2753 * flush_work - wait for a work to finish executing the last queueing instance
2754 * @work: the work to flush
2756 * Wait until @work has finished execution. @work is guaranteed to be idle
2757 * on return if it hasn't been requeued since flush started.
2760 * %true if flush_work() waited for the work to finish execution,
2761 * %false if it was already idle.
2763 bool flush_work(struct work_struct *work)
2765 struct wq_barrier barr;
2767 lock_map_acquire(&work->lockdep_map);
2768 lock_map_release(&work->lockdep_map);
2770 if (start_flush_work(work, &barr)) {
2771 wait_for_completion(&barr.done);
2772 destroy_work_on_stack(&barr.work);
2778 EXPORT_SYMBOL_GPL(flush_work);
2782 struct work_struct *work;
2785 static int cwt_wakefn(wait_queue_t *wait, unsigned mode, int sync, void *key)
2787 struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
2789 if (cwait->work != key)
2791 return autoremove_wake_function(wait, mode, sync, key);
2794 static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2796 static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
2797 unsigned long flags;
2801 ret = try_to_grab_pending(work, is_dwork, &flags);
2803 * If someone else is already canceling, wait for it to
2804 * finish. flush_work() doesn't work for PREEMPT_NONE
2805 * because we may get scheduled between @work's completion
2806 * and the other canceling task resuming and clearing
2807 * CANCELING - flush_work() will return false immediately
2808 * as @work is no longer busy, try_to_grab_pending() will
2809 * return -ENOENT as @work is still being canceled and the
2810 * other canceling task won't be able to clear CANCELING as
2811 * we're hogging the CPU.
2813 * Let's wait for completion using a waitqueue. As this
2814 * may lead to the thundering herd problem, use a custom
2815 * wake function which matches @work along with exclusive
2818 if (unlikely(ret == -ENOENT)) {
2819 struct cwt_wait cwait;
2821 init_wait(&cwait.wait);
2822 cwait.wait.func = cwt_wakefn;
2825 prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
2826 TASK_UNINTERRUPTIBLE);
2827 if (work_is_canceling(work))
2829 finish_wait(&cancel_waitq, &cwait.wait);
2831 } while (unlikely(ret < 0));
2833 /* tell other tasks trying to grab @work to back off */
2834 mark_work_canceling(work);
2835 local_unlock_irqrestore(pendingb_lock, flags);
2838 clear_work_data(work);
2841 * Paired with prepare_to_wait() above so that either
2842 * waitqueue_active() is visible here or !work_is_canceling() is
2846 if (waitqueue_active(&cancel_waitq))
2847 __wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
2853 * cancel_work_sync - cancel a work and wait for it to finish
2854 * @work: the work to cancel
2856 * Cancel @work and wait for its execution to finish. This function
2857 * can be used even if the work re-queues itself or migrates to
2858 * another workqueue. On return from this function, @work is
2859 * guaranteed to be not pending or executing on any CPU.
2861 * cancel_work_sync(&delayed_work->work) must not be used for
2862 * delayed_work's. Use cancel_delayed_work_sync() instead.
2864 * The caller must ensure that the workqueue on which @work was last
2865 * queued can't be destroyed before this function returns.
2868 * %true if @work was pending, %false otherwise.
2870 bool cancel_work_sync(struct work_struct *work)
2872 return __cancel_work_timer(work, false);
2874 EXPORT_SYMBOL_GPL(cancel_work_sync);
2877 * flush_delayed_work - wait for a dwork to finish executing the last queueing
2878 * @dwork: the delayed work to flush
2880 * Delayed timer is cancelled and the pending work is queued for
2881 * immediate execution. Like flush_work(), this function only
2882 * considers the last queueing instance of @dwork.
2885 * %true if flush_work() waited for the work to finish execution,
2886 * %false if it was already idle.
2888 bool flush_delayed_work(struct delayed_work *dwork)
2890 local_lock_irq(pendingb_lock);
2891 if (del_timer_sync(&dwork->timer))
2892 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
2893 local_unlock_irq(pendingb_lock);
2894 return flush_work(&dwork->work);
2896 EXPORT_SYMBOL(flush_delayed_work);
2899 * cancel_delayed_work - cancel a delayed work
2900 * @dwork: delayed_work to cancel
2902 * Kill off a pending delayed_work.
2904 * Return: %true if @dwork was pending and canceled; %false if it wasn't
2908 * The work callback function may still be running on return, unless
2909 * it returns %true and the work doesn't re-arm itself. Explicitly flush or
2910 * use cancel_delayed_work_sync() to wait on it.
2912 * This function is safe to call from any context including IRQ handler.
2914 bool cancel_delayed_work(struct delayed_work *dwork)
2916 unsigned long flags;
2920 ret = try_to_grab_pending(&dwork->work, true, &flags);
2921 } while (unlikely(ret == -EAGAIN));
2923 if (unlikely(ret < 0))
2926 set_work_pool_and_clear_pending(&dwork->work,
2927 get_work_pool_id(&dwork->work));
2928 local_unlock_irqrestore(pendingb_lock, flags);
2931 EXPORT_SYMBOL(cancel_delayed_work);
2934 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2935 * @dwork: the delayed work cancel
2937 * This is cancel_work_sync() for delayed works.
2940 * %true if @dwork was pending, %false otherwise.
2942 bool cancel_delayed_work_sync(struct delayed_work *dwork)
2944 return __cancel_work_timer(&dwork->work, true);
2946 EXPORT_SYMBOL(cancel_delayed_work_sync);
2949 * schedule_on_each_cpu - execute a function synchronously on each online CPU
2950 * @func: the function to call
2952 * schedule_on_each_cpu() executes @func on each online CPU using the
2953 * system workqueue and blocks until all CPUs have completed.
2954 * schedule_on_each_cpu() is very slow.
2957 * 0 on success, -errno on failure.
2959 int schedule_on_each_cpu(work_func_t func)
2962 struct work_struct __percpu *works;
2964 works = alloc_percpu(struct work_struct);
2970 for_each_online_cpu(cpu) {
2971 struct work_struct *work = per_cpu_ptr(works, cpu);
2973 INIT_WORK(work, func);
2974 schedule_work_on(cpu, work);
2977 for_each_online_cpu(cpu)
2978 flush_work(per_cpu_ptr(works, cpu));
2986 * flush_scheduled_work - ensure that any scheduled work has run to completion.
2988 * Forces execution of the kernel-global workqueue and blocks until its
2991 * Think twice before calling this function! It's very easy to get into
2992 * trouble if you don't take great care. Either of the following situations
2993 * will lead to deadlock:
2995 * One of the work items currently on the workqueue needs to acquire
2996 * a lock held by your code or its caller.
2998 * Your code is running in the context of a work routine.
3000 * They will be detected by lockdep when they occur, but the first might not
3001 * occur very often. It depends on what work items are on the workqueue and
3002 * what locks they need, which you have no control over.
3004 * In most situations flushing the entire workqueue is overkill; you merely
3005 * need to know that a particular work item isn't queued and isn't running.
3006 * In such cases you should use cancel_delayed_work_sync() or
3007 * cancel_work_sync() instead.
3009 void flush_scheduled_work(void)
3011 flush_workqueue(system_wq);
3013 EXPORT_SYMBOL(flush_scheduled_work);
3016 * execute_in_process_context - reliably execute the routine with user context
3017 * @fn: the function to execute
3018 * @ew: guaranteed storage for the execute work structure (must
3019 * be available when the work executes)
3021 * Executes the function immediately if process context is available,
3022 * otherwise schedules the function for delayed execution.
3024 * Return: 0 - function was executed
3025 * 1 - function was scheduled for execution
3027 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
3029 if (!in_interrupt()) {
3034 INIT_WORK(&ew->work, fn);
3035 schedule_work(&ew->work);
3039 EXPORT_SYMBOL_GPL(execute_in_process_context);
3042 * free_workqueue_attrs - free a workqueue_attrs
3043 * @attrs: workqueue_attrs to free
3045 * Undo alloc_workqueue_attrs().
3047 void free_workqueue_attrs(struct workqueue_attrs *attrs)
3050 free_cpumask_var(attrs->cpumask);
3056 * alloc_workqueue_attrs - allocate a workqueue_attrs
3057 * @gfp_mask: allocation mask to use
3059 * Allocate a new workqueue_attrs, initialize with default settings and
3062 * Return: The allocated new workqueue_attr on success. %NULL on failure.
3064 struct workqueue_attrs *alloc_workqueue_attrs(gfp_t gfp_mask)
3066 struct workqueue_attrs *attrs;
3068 attrs = kzalloc(sizeof(*attrs), gfp_mask);
3071 if (!alloc_cpumask_var(&attrs->cpumask, gfp_mask))
3074 cpumask_copy(attrs->cpumask, cpu_possible_mask);
3077 free_workqueue_attrs(attrs);
3081 static void copy_workqueue_attrs(struct workqueue_attrs *to,
3082 const struct workqueue_attrs *from)
3084 to->nice = from->nice;
3085 cpumask_copy(to->cpumask, from->cpumask);
3087 * Unlike hash and equality test, this function doesn't ignore
3088 * ->no_numa as it is used for both pool and wq attrs. Instead,
3089 * get_unbound_pool() explicitly clears ->no_numa after copying.
3091 to->no_numa = from->no_numa;
3094 /* hash value of the content of @attr */
3095 static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
3099 hash = jhash_1word(attrs->nice, hash);
3100 hash = jhash(cpumask_bits(attrs->cpumask),
3101 BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
3105 /* content equality test */
3106 static bool wqattrs_equal(const struct workqueue_attrs *a,
3107 const struct workqueue_attrs *b)
3109 if (a->nice != b->nice)
3111 if (!cpumask_equal(a->cpumask, b->cpumask))
3117 * init_worker_pool - initialize a newly zalloc'd worker_pool
3118 * @pool: worker_pool to initialize
3120 * Initiailize a newly zalloc'd @pool. It also allocates @pool->attrs.
3122 * Return: 0 on success, -errno on failure. Even on failure, all fields
3123 * inside @pool proper are initialized and put_unbound_pool() can be called
3124 * on @pool safely to release it.
3126 static int init_worker_pool(struct worker_pool *pool)
3128 spin_lock_init(&pool->lock);
3131 pool->node = NUMA_NO_NODE;
3132 pool->flags |= POOL_DISASSOCIATED;
3133 INIT_LIST_HEAD(&pool->worklist);
3134 INIT_LIST_HEAD(&pool->idle_list);
3135 hash_init(pool->busy_hash);
3137 init_timer_deferrable(&pool->idle_timer);
3138 pool->idle_timer.function = idle_worker_timeout;
3139 pool->idle_timer.data = (unsigned long)pool;
3141 setup_timer(&pool->mayday_timer, pool_mayday_timeout,
3142 (unsigned long)pool);
3144 mutex_init(&pool->manager_arb);
3145 mutex_init(&pool->attach_mutex);
3146 INIT_LIST_HEAD(&pool->workers);
3148 ida_init(&pool->worker_ida);
3149 INIT_HLIST_NODE(&pool->hash_node);
3152 /* shouldn't fail above this point */
3153 pool->attrs = alloc_workqueue_attrs(GFP_KERNEL);
3159 static void rcu_free_wq(struct rcu_head *rcu)
3161 struct workqueue_struct *wq =
3162 container_of(rcu, struct workqueue_struct, rcu);
3164 if (!(wq->flags & WQ_UNBOUND))
3165 free_percpu(wq->cpu_pwqs);
3167 free_workqueue_attrs(wq->unbound_attrs);
3173 static void rcu_free_pool(struct rcu_head *rcu)
3175 struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
3177 ida_destroy(&pool->worker_ida);
3178 free_workqueue_attrs(pool->attrs);
3183 * put_unbound_pool - put a worker_pool
3184 * @pool: worker_pool to put
3186 * Put @pool. If its refcnt reaches zero, it gets destroyed in RCU
3187 * safe manner. get_unbound_pool() calls this function on its failure path
3188 * and this function should be able to release pools which went through,
3189 * successfully or not, init_worker_pool().
3191 * Should be called with wq_pool_mutex held.
3193 static void put_unbound_pool(struct worker_pool *pool)
3195 DECLARE_COMPLETION_ONSTACK(detach_completion);
3196 struct worker *worker;
3198 lockdep_assert_held(&wq_pool_mutex);
3204 if (WARN_ON(!(pool->cpu < 0)) ||
3205 WARN_ON(!list_empty(&pool->worklist)))
3208 /* release id and unhash */
3210 idr_remove(&worker_pool_idr, pool->id);
3211 hash_del(&pool->hash_node);
3214 * Become the manager and destroy all workers. Grabbing
3215 * manager_arb prevents @pool's workers from blocking on
3218 mutex_lock(&pool->manager_arb);
3220 spin_lock_irq(&pool->lock);
3221 while ((worker = first_idle_worker(pool)))
3222 destroy_worker(worker);
3223 WARN_ON(pool->nr_workers || pool->nr_idle);
3224 spin_unlock_irq(&pool->lock);
3226 mutex_lock(&pool->attach_mutex);
3227 if (!list_empty(&pool->workers))
3228 pool->detach_completion = &detach_completion;
3229 mutex_unlock(&pool->attach_mutex);
3231 if (pool->detach_completion)
3232 wait_for_completion(pool->detach_completion);
3234 mutex_unlock(&pool->manager_arb);
3236 /* shut down the timers */
3237 del_timer_sync(&pool->idle_timer);
3238 del_timer_sync(&pool->mayday_timer);
3240 /* RCU protected to allow dereferences from get_work_pool() */
3241 call_rcu(&pool->rcu, rcu_free_pool);
3245 * get_unbound_pool - get a worker_pool with the specified attributes
3246 * @attrs: the attributes of the worker_pool to get
3248 * Obtain a worker_pool which has the same attributes as @attrs, bump the
3249 * reference count and return it. If there already is a matching
3250 * worker_pool, it will be used; otherwise, this function attempts to
3253 * Should be called with wq_pool_mutex held.
3255 * Return: On success, a worker_pool with the same attributes as @attrs.
3256 * On failure, %NULL.
3258 static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
3260 u32 hash = wqattrs_hash(attrs);
3261 struct worker_pool *pool;
3264 lockdep_assert_held(&wq_pool_mutex);
3266 /* do we already have a matching pool? */
3267 hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
3268 if (wqattrs_equal(pool->attrs, attrs)) {
3274 /* nope, create a new one */
3275 pool = kzalloc(sizeof(*pool), GFP_KERNEL);
3276 if (!pool || init_worker_pool(pool) < 0)
3279 lockdep_set_subclass(&pool->lock, 1); /* see put_pwq() */
3280 copy_workqueue_attrs(pool->attrs, attrs);
3283 * no_numa isn't a worker_pool attribute, always clear it. See
3284 * 'struct workqueue_attrs' comments for detail.
3286 pool->attrs->no_numa = false;
3288 /* if cpumask is contained inside a NUMA node, we belong to that node */
3289 if (wq_numa_enabled) {
3290 for_each_node(node) {
3291 if (cpumask_subset(pool->attrs->cpumask,
3292 wq_numa_possible_cpumask[node])) {
3299 if (worker_pool_assign_id(pool) < 0)
3302 /* create and start the initial worker */
3303 if (!create_worker(pool))
3307 hash_add(unbound_pool_hash, &pool->hash_node, hash);
3312 put_unbound_pool(pool);
3316 static void rcu_free_pwq(struct rcu_head *rcu)
3318 kmem_cache_free(pwq_cache,
3319 container_of(rcu, struct pool_workqueue, rcu));
3323 * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
3324 * and needs to be destroyed.
3326 static void pwq_unbound_release_workfn(struct work_struct *work)
3328 struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
3329 unbound_release_work);
3330 struct workqueue_struct *wq = pwq->wq;
3331 struct worker_pool *pool = pwq->pool;
3334 if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
3337 mutex_lock(&wq->mutex);
3338 list_del_rcu(&pwq->pwqs_node);
3339 is_last = list_empty(&wq->pwqs);
3340 mutex_unlock(&wq->mutex);
3342 mutex_lock(&wq_pool_mutex);
3343 put_unbound_pool(pool);
3344 mutex_unlock(&wq_pool_mutex);
3346 call_rcu(&pwq->rcu, rcu_free_pwq);
3349 * If we're the last pwq going away, @wq is already dead and no one
3350 * is gonna access it anymore. Schedule RCU free.
3353 call_rcu(&wq->rcu, rcu_free_wq);
3357 * pwq_adjust_max_active - update a pwq's max_active to the current setting
3358 * @pwq: target pool_workqueue
3360 * If @pwq isn't freezing, set @pwq->max_active to the associated
3361 * workqueue's saved_max_active and activate delayed work items
3362 * accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
3364 static void pwq_adjust_max_active(struct pool_workqueue *pwq)
3366 struct workqueue_struct *wq = pwq->wq;
3367 bool freezable = wq->flags & WQ_FREEZABLE;
3369 /* for @wq->saved_max_active */
3370 lockdep_assert_held(&wq->mutex);
3372 /* fast exit for non-freezable wqs */
3373 if (!freezable && pwq->max_active == wq->saved_max_active)
3376 spin_lock_irq(&pwq->pool->lock);
3379 * During [un]freezing, the caller is responsible for ensuring that
3380 * this function is called at least once after @workqueue_freezing
3381 * is updated and visible.
3383 if (!freezable || !workqueue_freezing) {
3384 pwq->max_active = wq->saved_max_active;
3386 while (!list_empty(&pwq->delayed_works) &&
3387 pwq->nr_active < pwq->max_active)
3388 pwq_activate_first_delayed(pwq);
3391 * Need to kick a worker after thawed or an unbound wq's
3392 * max_active is bumped. It's a slow path. Do it always.
3394 wake_up_worker(pwq->pool);
3396 pwq->max_active = 0;
3399 spin_unlock_irq(&pwq->pool->lock);
3402 /* initialize newly alloced @pwq which is associated with @wq and @pool */
3403 static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
3404 struct worker_pool *pool)
3406 BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3408 memset(pwq, 0, sizeof(*pwq));
3412 pwq->flush_color = -1;
3414 INIT_LIST_HEAD(&pwq->delayed_works);
3415 INIT_LIST_HEAD(&pwq->pwqs_node);
3416 INIT_LIST_HEAD(&pwq->mayday_node);
3417 INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
3420 /* sync @pwq with the current state of its associated wq and link it */
3421 static void link_pwq(struct pool_workqueue *pwq)
3423 struct workqueue_struct *wq = pwq->wq;
3425 lockdep_assert_held(&wq->mutex);
3427 /* may be called multiple times, ignore if already linked */
3428 if (!list_empty(&pwq->pwqs_node))
3431 /* set the matching work_color */
3432 pwq->work_color = wq->work_color;
3434 /* sync max_active to the current setting */
3435 pwq_adjust_max_active(pwq);
3438 list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
3441 /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
3442 static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
3443 const struct workqueue_attrs *attrs)
3445 struct worker_pool *pool;
3446 struct pool_workqueue *pwq;
3448 lockdep_assert_held(&wq_pool_mutex);
3450 pool = get_unbound_pool(attrs);
3454 pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
3456 put_unbound_pool(pool);
3460 init_pwq(pwq, wq, pool);
3464 /* undo alloc_unbound_pwq(), used only in the error path */
3465 static void free_unbound_pwq(struct pool_workqueue *pwq)
3467 lockdep_assert_held(&wq_pool_mutex);
3470 put_unbound_pool(pwq->pool);
3471 kmem_cache_free(pwq_cache, pwq);
3476 * wq_calc_node_mask - calculate a wq_attrs' cpumask for the specified node
3477 * @attrs: the wq_attrs of interest
3478 * @node: the target NUMA node
3479 * @cpu_going_down: if >= 0, the CPU to consider as offline
3480 * @cpumask: outarg, the resulting cpumask
3482 * Calculate the cpumask a workqueue with @attrs should use on @node. If
3483 * @cpu_going_down is >= 0, that cpu is considered offline during
3484 * calculation. The result is stored in @cpumask.
3486 * If NUMA affinity is not enabled, @attrs->cpumask is always used. If
3487 * enabled and @node has online CPUs requested by @attrs, the returned
3488 * cpumask is the intersection of the possible CPUs of @node and
3491 * The caller is responsible for ensuring that the cpumask of @node stays
3494 * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
3497 static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
3498 int cpu_going_down, cpumask_t *cpumask)
3500 if (!wq_numa_enabled || attrs->no_numa)
3503 /* does @node have any online CPUs @attrs wants? */
3504 cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
3505 if (cpu_going_down >= 0)
3506 cpumask_clear_cpu(cpu_going_down, cpumask);
3508 if (cpumask_empty(cpumask))
3511 /* yeap, return possible CPUs in @node that @attrs wants */
3512 cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
3513 return !cpumask_equal(cpumask, attrs->cpumask);
3516 cpumask_copy(cpumask, attrs->cpumask);
3520 /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
3521 static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
3523 struct pool_workqueue *pwq)
3525 struct pool_workqueue *old_pwq;
3527 lockdep_assert_held(&wq->mutex);
3529 /* link_pwq() can handle duplicate calls */
3532 old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
3533 rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
3538 * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
3539 * @wq: the target workqueue
3540 * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
3542 * Apply @attrs to an unbound workqueue @wq. Unless disabled, on NUMA
3543 * machines, this function maps a separate pwq to each NUMA node with
3544 * possibles CPUs in @attrs->cpumask so that work items are affine to the
3545 * NUMA node it was issued on. Older pwqs are released as in-flight work
3546 * items finish. Note that a work item which repeatedly requeues itself
3547 * back-to-back will stay on its current pwq.
3549 * Performs GFP_KERNEL allocations.
3551 * Return: 0 on success and -errno on failure.
3553 int apply_workqueue_attrs(struct workqueue_struct *wq,
3554 const struct workqueue_attrs *attrs)
3556 struct workqueue_attrs *new_attrs, *tmp_attrs;
3557 struct pool_workqueue **pwq_tbl, *dfl_pwq;
3560 /* only unbound workqueues can change attributes */
3561 if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
3564 /* creating multiple pwqs breaks ordering guarantee */
3565 if (WARN_ON((wq->flags & __WQ_ORDERED) && !list_empty(&wq->pwqs)))
3568 pwq_tbl = kzalloc(nr_node_ids * sizeof(pwq_tbl[0]), GFP_KERNEL);
3569 new_attrs = alloc_workqueue_attrs(GFP_KERNEL);
3570 tmp_attrs = alloc_workqueue_attrs(GFP_KERNEL);
3571 if (!pwq_tbl || !new_attrs || !tmp_attrs)
3574 /* make a copy of @attrs and sanitize it */
3575 copy_workqueue_attrs(new_attrs, attrs);
3576 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
3579 * We may create multiple pwqs with differing cpumasks. Make a
3580 * copy of @new_attrs which will be modified and used to obtain
3583 copy_workqueue_attrs(tmp_attrs, new_attrs);
3586 * CPUs should stay stable across pwq creations and installations.
3587 * Pin CPUs, determine the target cpumask for each node and create
3592 mutex_lock(&wq_pool_mutex);
3595 * If something goes wrong during CPU up/down, we'll fall back to
3596 * the default pwq covering whole @attrs->cpumask. Always create
3597 * it even if we don't use it immediately.
3599 dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
3603 for_each_node(node) {
3604 if (wq_calc_node_cpumask(attrs, node, -1, tmp_attrs->cpumask)) {
3605 pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
3610 pwq_tbl[node] = dfl_pwq;
3614 mutex_unlock(&wq_pool_mutex);
3616 /* all pwqs have been created successfully, let's install'em */
3617 mutex_lock(&wq->mutex);
3619 copy_workqueue_attrs(wq->unbound_attrs, new_attrs);
3621 /* save the previous pwq and install the new one */
3623 pwq_tbl[node] = numa_pwq_tbl_install(wq, node, pwq_tbl[node]);
3625 /* @dfl_pwq might not have been used, ensure it's linked */
3627 swap(wq->dfl_pwq, dfl_pwq);
3629 mutex_unlock(&wq->mutex);
3631 /* put the old pwqs */
3633 put_pwq_unlocked(pwq_tbl[node]);
3634 put_pwq_unlocked(dfl_pwq);
3640 free_workqueue_attrs(tmp_attrs);
3641 free_workqueue_attrs(new_attrs);
3646 free_unbound_pwq(dfl_pwq);
3648 if (pwq_tbl && pwq_tbl[node] != dfl_pwq)
3649 free_unbound_pwq(pwq_tbl[node]);
3650 mutex_unlock(&wq_pool_mutex);
3658 * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
3659 * @wq: the target workqueue
3660 * @cpu: the CPU coming up or going down
3661 * @online: whether @cpu is coming up or going down
3663 * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
3664 * %CPU_DOWN_FAILED. @cpu is being hot[un]plugged, update NUMA affinity of
3667 * If NUMA affinity can't be adjusted due to memory allocation failure, it
3668 * falls back to @wq->dfl_pwq which may not be optimal but is always
3671 * Note that when the last allowed CPU of a NUMA node goes offline for a
3672 * workqueue with a cpumask spanning multiple nodes, the workers which were
3673 * already executing the work items for the workqueue will lose their CPU
3674 * affinity and may execute on any CPU. This is similar to how per-cpu
3675 * workqueues behave on CPU_DOWN. If a workqueue user wants strict
3676 * affinity, it's the user's responsibility to flush the work item from
3679 static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
3682 int node = cpu_to_node(cpu);
3683 int cpu_off = online ? -1 : cpu;
3684 struct pool_workqueue *old_pwq = NULL, *pwq;
3685 struct workqueue_attrs *target_attrs;
3688 lockdep_assert_held(&wq_pool_mutex);
3690 if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND))
3694 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
3695 * Let's use a preallocated one. The following buf is protected by
3696 * CPU hotplug exclusion.
3698 target_attrs = wq_update_unbound_numa_attrs_buf;
3699 cpumask = target_attrs->cpumask;
3701 mutex_lock(&wq->mutex);
3702 if (wq->unbound_attrs->no_numa)
3705 copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
3706 pwq = unbound_pwq_by_node(wq, node);
3709 * Let's determine what needs to be done. If the target cpumask is
3710 * different from wq's, we need to compare it to @pwq's and create
3711 * a new one if they don't match. If the target cpumask equals
3712 * wq's, the default pwq should be used.
3714 if (wq_calc_node_cpumask(wq->unbound_attrs, node, cpu_off, cpumask)) {
3715 if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
3721 mutex_unlock(&wq->mutex);
3723 /* create a new pwq */
3724 pwq = alloc_unbound_pwq(wq, target_attrs);
3726 pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
3728 mutex_lock(&wq->mutex);
3733 * Install the new pwq. As this function is called only from CPU
3734 * hotplug callbacks and applying a new attrs is wrapped with
3735 * get/put_online_cpus(), @wq->unbound_attrs couldn't have changed
3738 mutex_lock(&wq->mutex);
3739 old_pwq = numa_pwq_tbl_install(wq, node, pwq);
3743 spin_lock_irq(&wq->dfl_pwq->pool->lock);
3744 get_pwq(wq->dfl_pwq);
3745 spin_unlock_irq(&wq->dfl_pwq->pool->lock);
3746 old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
3748 mutex_unlock(&wq->mutex);
3749 put_pwq_unlocked(old_pwq);
3752 static int alloc_and_link_pwqs(struct workqueue_struct *wq)
3754 bool highpri = wq->flags & WQ_HIGHPRI;
3757 if (!(wq->flags & WQ_UNBOUND)) {
3758 wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
3762 for_each_possible_cpu(cpu) {
3763 struct pool_workqueue *pwq =
3764 per_cpu_ptr(wq->cpu_pwqs, cpu);
3765 struct worker_pool *cpu_pools =
3766 per_cpu(cpu_worker_pools, cpu);
3768 init_pwq(pwq, wq, &cpu_pools[highpri]);
3770 mutex_lock(&wq->mutex);
3772 mutex_unlock(&wq->mutex);
3775 } else if (wq->flags & __WQ_ORDERED) {
3776 ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
3777 /* there should only be single pwq for ordering guarantee */
3778 WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
3779 wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
3780 "ordering guarantee broken for workqueue %s\n", wq->name);
3783 return apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
3787 static int wq_clamp_max_active(int max_active, unsigned int flags,
3790 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3792 if (max_active < 1 || max_active > lim)
3793 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3794 max_active, name, 1, lim);
3796 return clamp_val(max_active, 1, lim);
3799 struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
3802 struct lock_class_key *key,
3803 const char *lock_name, ...)
3805 size_t tbl_size = 0;
3807 struct workqueue_struct *wq;
3808 struct pool_workqueue *pwq;
3810 /* see the comment above the definition of WQ_POWER_EFFICIENT */
3811 if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
3812 flags |= WQ_UNBOUND;
3814 /* allocate wq and format name */
3815 if (flags & WQ_UNBOUND)
3816 tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
3818 wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
3822 if (flags & WQ_UNBOUND) {
3823 wq->unbound_attrs = alloc_workqueue_attrs(GFP_KERNEL);
3824 if (!wq->unbound_attrs)
3828 va_start(args, lock_name);
3829 vsnprintf(wq->name, sizeof(wq->name), fmt, args);
3832 max_active = max_active ?: WQ_DFL_ACTIVE;
3833 max_active = wq_clamp_max_active(max_active, flags, wq->name);
3837 wq->saved_max_active = max_active;
3838 mutex_init(&wq->mutex);
3839 atomic_set(&wq->nr_pwqs_to_flush, 0);
3840 INIT_LIST_HEAD(&wq->pwqs);
3841 INIT_LIST_HEAD(&wq->flusher_queue);
3842 INIT_LIST_HEAD(&wq->flusher_overflow);
3843 INIT_LIST_HEAD(&wq->maydays);
3845 lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3846 INIT_LIST_HEAD(&wq->list);
3848 if (alloc_and_link_pwqs(wq) < 0)
3852 * Workqueues which may be used during memory reclaim should
3853 * have a rescuer to guarantee forward progress.
3855 if (flags & WQ_MEM_RECLAIM) {
3856 struct worker *rescuer;
3858 rescuer = alloc_worker(NUMA_NO_NODE);
3862 rescuer->rescue_wq = wq;
3863 rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
3865 if (IS_ERR(rescuer->task)) {
3870 wq->rescuer = rescuer;
3871 rescuer->task->flags |= PF_NO_SETAFFINITY;
3872 wake_up_process(rescuer->task);
3875 if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
3879 * wq_pool_mutex protects global freeze state and workqueues list.
3880 * Grab it, adjust max_active and add the new @wq to workqueues
3883 mutex_lock(&wq_pool_mutex);
3885 mutex_lock(&wq->mutex);
3886 for_each_pwq(pwq, wq)
3887 pwq_adjust_max_active(pwq);
3888 mutex_unlock(&wq->mutex);
3890 list_add_tail_rcu(&wq->list, &workqueues);
3892 mutex_unlock(&wq_pool_mutex);
3897 free_workqueue_attrs(wq->unbound_attrs);
3901 destroy_workqueue(wq);
3904 EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
3907 * destroy_workqueue - safely terminate a workqueue
3908 * @wq: target workqueue
3910 * Safely destroy a workqueue. All work currently pending will be done first.
3912 void destroy_workqueue(struct workqueue_struct *wq)
3914 struct pool_workqueue *pwq;
3917 /* drain it before proceeding with destruction */
3918 drain_workqueue(wq);
3921 mutex_lock(&wq->mutex);
3922 for_each_pwq(pwq, wq) {
3925 for (i = 0; i < WORK_NR_COLORS; i++) {
3926 if (WARN_ON(pwq->nr_in_flight[i])) {
3927 mutex_unlock(&wq->mutex);
3932 if (WARN_ON((pwq != wq->dfl_pwq) && (pwq->refcnt > 1)) ||
3933 WARN_ON(pwq->nr_active) ||
3934 WARN_ON(!list_empty(&pwq->delayed_works))) {
3935 mutex_unlock(&wq->mutex);
3939 mutex_unlock(&wq->mutex);
3942 * wq list is used to freeze wq, remove from list after
3943 * flushing is complete in case freeze races us.
3945 mutex_lock(&wq_pool_mutex);
3946 list_del_rcu(&wq->list);
3947 mutex_unlock(&wq_pool_mutex);
3949 workqueue_sysfs_unregister(wq);
3952 kthread_stop(wq->rescuer->task);
3954 if (!(wq->flags & WQ_UNBOUND)) {
3956 * The base ref is never dropped on per-cpu pwqs. Directly
3957 * schedule RCU free.
3959 call_rcu(&wq->rcu, rcu_free_wq);
3962 * We're the sole accessor of @wq at this point. Directly
3963 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
3964 * @wq will be freed when the last pwq is released.
3966 for_each_node(node) {
3967 pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
3968 RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
3969 put_pwq_unlocked(pwq);
3973 * Put dfl_pwq. @wq may be freed any time after dfl_pwq is
3974 * put. Don't access it afterwards.
3978 put_pwq_unlocked(pwq);
3981 EXPORT_SYMBOL_GPL(destroy_workqueue);
3984 * workqueue_set_max_active - adjust max_active of a workqueue
3985 * @wq: target workqueue
3986 * @max_active: new max_active value.
3988 * Set max_active of @wq to @max_active.
3991 * Don't call from IRQ context.
3993 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
3995 struct pool_workqueue *pwq;
3997 /* disallow meddling with max_active for ordered workqueues */
3998 if (WARN_ON(wq->flags & __WQ_ORDERED))
4001 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4003 mutex_lock(&wq->mutex);
4005 wq->saved_max_active = max_active;
4007 for_each_pwq(pwq, wq)
4008 pwq_adjust_max_active(pwq);
4010 mutex_unlock(&wq->mutex);
4012 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4015 * current_is_workqueue_rescuer - is %current workqueue rescuer?
4017 * Determine whether %current is a workqueue rescuer. Can be used from
4018 * work functions to determine whether it's being run off the rescuer task.
4020 * Return: %true if %current is a workqueue rescuer. %false otherwise.
4022 bool current_is_workqueue_rescuer(void)
4024 struct worker *worker = current_wq_worker();
4026 return worker && worker->rescue_wq;
4030 * workqueue_congested - test whether a workqueue is congested
4031 * @cpu: CPU in question
4032 * @wq: target workqueue
4034 * Test whether @wq's cpu workqueue for @cpu is congested. There is
4035 * no synchronization around this function and the test result is
4036 * unreliable and only useful as advisory hints or for debugging.
4038 * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4039 * Note that both per-cpu and unbound workqueues may be associated with
4040 * multiple pool_workqueues which have separate congested states. A
4041 * workqueue being congested on one CPU doesn't mean the workqueue is also
4042 * contested on other CPUs / NUMA nodes.
4045 * %true if congested, %false otherwise.
4047 bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4049 struct pool_workqueue *pwq;
4055 if (cpu == WORK_CPU_UNBOUND)
4056 cpu = smp_processor_id();
4058 if (!(wq->flags & WQ_UNBOUND))
4059 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
4061 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4063 ret = !list_empty(&pwq->delayed_works);
4069 EXPORT_SYMBOL_GPL(workqueue_congested);
4072 * work_busy - test whether a work is currently pending or running
4073 * @work: the work to be tested
4075 * Test whether @work is currently pending or running. There is no
4076 * synchronization around this function and the test result is
4077 * unreliable and only useful as advisory hints or for debugging.
4080 * OR'd bitmask of WORK_BUSY_* bits.
4082 unsigned int work_busy(struct work_struct *work)
4084 struct worker_pool *pool;
4085 unsigned long flags;
4086 unsigned int ret = 0;
4088 if (work_pending(work))
4089 ret |= WORK_BUSY_PENDING;
4092 pool = get_work_pool(work);
4094 spin_lock_irqsave(&pool->lock, flags);
4095 if (find_worker_executing_work(pool, work))
4096 ret |= WORK_BUSY_RUNNING;
4097 spin_unlock_irqrestore(&pool->lock, flags);
4103 EXPORT_SYMBOL_GPL(work_busy);
4106 * set_worker_desc - set description for the current work item
4107 * @fmt: printf-style format string
4108 * @...: arguments for the format string
4110 * This function can be called by a running work function to describe what
4111 * the work item is about. If the worker task gets dumped, this
4112 * information will be printed out together to help debugging. The
4113 * description can be at most WORKER_DESC_LEN including the trailing '\0'.
4115 void set_worker_desc(const char *fmt, ...)
4117 struct worker *worker = current_wq_worker();
4121 va_start(args, fmt);
4122 vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
4124 worker->desc_valid = true;
4129 * print_worker_info - print out worker information and description
4130 * @log_lvl: the log level to use when printing
4131 * @task: target task
4133 * If @task is a worker and currently executing a work item, print out the
4134 * name of the workqueue being serviced and worker description set with
4135 * set_worker_desc() by the currently executing work item.
4137 * This function can be safely called on any task as long as the
4138 * task_struct itself is accessible. While safe, this function isn't
4139 * synchronized and may print out mixups or garbages of limited length.
4141 void print_worker_info(const char *log_lvl, struct task_struct *task)
4143 work_func_t *fn = NULL;
4144 char name[WQ_NAME_LEN] = { };
4145 char desc[WORKER_DESC_LEN] = { };
4146 struct pool_workqueue *pwq = NULL;
4147 struct workqueue_struct *wq = NULL;
4148 bool desc_valid = false;
4149 struct worker *worker;
4151 if (!(task->flags & PF_WQ_WORKER))
4155 * This function is called without any synchronization and @task
4156 * could be in any state. Be careful with dereferences.
4158 worker = probe_kthread_data(task);
4161 * Carefully copy the associated workqueue's workfn and name. Keep
4162 * the original last '\0' in case the original contains garbage.
4164 probe_kernel_read(&fn, &worker->current_func, sizeof(fn));
4165 probe_kernel_read(&pwq, &worker->current_pwq, sizeof(pwq));
4166 probe_kernel_read(&wq, &pwq->wq, sizeof(wq));
4167 probe_kernel_read(name, wq->name, sizeof(name) - 1);
4169 /* copy worker description */
4170 probe_kernel_read(&desc_valid, &worker->desc_valid, sizeof(desc_valid));
4172 probe_kernel_read(desc, worker->desc, sizeof(desc) - 1);
4174 if (fn || name[0] || desc[0]) {
4175 printk("%sWorkqueue: %s %pf", log_lvl, name, fn);
4177 pr_cont(" (%s)", desc);
4182 static void pr_cont_pool_info(struct worker_pool *pool)
4184 pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
4185 if (pool->node != NUMA_NO_NODE)
4186 pr_cont(" node=%d", pool->node);
4187 pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
4190 static void pr_cont_work(bool comma, struct work_struct *work)
4192 if (work->func == wq_barrier_func) {
4193 struct wq_barrier *barr;
4195 barr = container_of(work, struct wq_barrier, work);
4197 pr_cont("%s BAR(%d)", comma ? "," : "",
4198 task_pid_nr(barr->task));
4200 pr_cont("%s %pf", comma ? "," : "", work->func);
4204 static void show_pwq(struct pool_workqueue *pwq)
4206 struct worker_pool *pool = pwq->pool;
4207 struct work_struct *work;
4208 struct worker *worker;
4209 bool has_in_flight = false, has_pending = false;
4212 pr_info(" pwq %d:", pool->id);
4213 pr_cont_pool_info(pool);
4215 pr_cont(" active=%d/%d%s\n", pwq->nr_active, pwq->max_active,
4216 !list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
4218 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
4219 if (worker->current_pwq == pwq) {
4220 has_in_flight = true;
4224 if (has_in_flight) {
4227 pr_info(" in-flight:");
4228 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
4229 if (worker->current_pwq != pwq)
4232 pr_cont("%s %d%s:%pf", comma ? "," : "",
4233 task_pid_nr(worker->task),
4234 worker == pwq->wq->rescuer ? "(RESCUER)" : "",
4235 worker->current_func);
4236 list_for_each_entry(work, &worker->scheduled, entry)
4237 pr_cont_work(false, work);
4243 list_for_each_entry(work, &pool->worklist, entry) {
4244 if (get_work_pwq(work) == pwq) {
4252 pr_info(" pending:");
4253 list_for_each_entry(work, &pool->worklist, entry) {
4254 if (get_work_pwq(work) != pwq)
4257 pr_cont_work(comma, work);
4258 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
4263 if (!list_empty(&pwq->delayed_works)) {
4266 pr_info(" delayed:");
4267 list_for_each_entry(work, &pwq->delayed_works, entry) {
4268 pr_cont_work(comma, work);
4269 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
4276 * show_workqueue_state - dump workqueue state
4278 * Called from a sysrq handler and prints out all busy workqueues and
4281 void show_workqueue_state(void)
4283 struct workqueue_struct *wq;
4284 struct worker_pool *pool;
4285 unsigned long flags;
4290 pr_info("Showing busy workqueues and worker pools:\n");
4292 list_for_each_entry_rcu(wq, &workqueues, list) {
4293 struct pool_workqueue *pwq;
4296 for_each_pwq(pwq, wq) {
4297 if (pwq->nr_active || !list_empty(&pwq->delayed_works)) {
4305 pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
4307 for_each_pwq(pwq, wq) {
4308 spin_lock_irqsave(&pwq->pool->lock, flags);
4309 if (pwq->nr_active || !list_empty(&pwq->delayed_works))
4311 spin_unlock_irqrestore(&pwq->pool->lock, flags);
4315 for_each_pool(pool, pi) {
4316 struct worker *worker;
4319 spin_lock_irqsave(&pool->lock, flags);
4320 if (pool->nr_workers == pool->nr_idle)
4323 pr_info("pool %d:", pool->id);
4324 pr_cont_pool_info(pool);
4325 pr_cont(" workers=%d", pool->nr_workers);
4327 pr_cont(" manager: %d",
4328 task_pid_nr(pool->manager->task));
4329 list_for_each_entry(worker, &pool->idle_list, entry) {
4330 pr_cont(" %s%d", first ? "idle: " : "",
4331 task_pid_nr(worker->task));
4336 spin_unlock_irqrestore(&pool->lock, flags);
4345 * There are two challenges in supporting CPU hotplug. Firstly, there
4346 * are a lot of assumptions on strong associations among work, pwq and
4347 * pool which make migrating pending and scheduled works very
4348 * difficult to implement without impacting hot paths. Secondly,
4349 * worker pools serve mix of short, long and very long running works making
4350 * blocked draining impractical.
4352 * This is solved by allowing the pools to be disassociated from the CPU
4353 * running as an unbound one and allowing it to be reattached later if the
4354 * cpu comes back online.
4357 static void wq_unbind_fn(struct work_struct *work)
4359 int cpu = smp_processor_id();
4360 struct worker_pool *pool;
4361 struct worker *worker;
4363 for_each_cpu_worker_pool(pool, cpu) {
4364 mutex_lock(&pool->attach_mutex);
4365 spin_lock_irq(&pool->lock);
4368 * We've blocked all attach/detach operations. Make all workers
4369 * unbound and set DISASSOCIATED. Before this, all workers
4370 * except for the ones which are still executing works from
4371 * before the last CPU down must be on the cpu. After
4372 * this, they may become diasporas.
4374 for_each_pool_worker(worker, pool)
4375 worker->flags |= WORKER_UNBOUND;
4377 pool->flags |= POOL_DISASSOCIATED;
4379 spin_unlock_irq(&pool->lock);
4380 mutex_unlock(&pool->attach_mutex);
4383 * Call schedule() so that we cross rq->lock and thus can
4384 * guarantee sched callbacks see the %WORKER_UNBOUND flag.
4385 * This is necessary as scheduler callbacks may be invoked
4391 * Sched callbacks are disabled now. Zap nr_running.
4392 * After this, nr_running stays zero and need_more_worker()
4393 * and keep_working() are always true as long as the
4394 * worklist is not empty. This pool now behaves as an
4395 * unbound (in terms of concurrency management) pool which
4396 * are served by workers tied to the pool.
4398 atomic_set(&pool->nr_running, 0);
4401 * With concurrency management just turned off, a busy
4402 * worker blocking could lead to lengthy stalls. Kick off
4403 * unbound chain execution of currently pending work items.
4405 spin_lock_irq(&pool->lock);
4406 wake_up_worker(pool);
4407 spin_unlock_irq(&pool->lock);
4412 * rebind_workers - rebind all workers of a pool to the associated CPU
4413 * @pool: pool of interest
4415 * @pool->cpu is coming online. Rebind all workers to the CPU.
4417 static void rebind_workers(struct worker_pool *pool)
4419 struct worker *worker;
4421 lockdep_assert_held(&pool->attach_mutex);
4424 * Restore CPU affinity of all workers. As all idle workers should
4425 * be on the run-queue of the associated CPU before any local
4426 * wake-ups for concurrency management happen, restore CPU affinty
4427 * of all workers first and then clear UNBOUND. As we're called
4428 * from CPU_ONLINE, the following shouldn't fail.
4430 for_each_pool_worker(worker, pool)
4431 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4432 pool->attrs->cpumask) < 0);
4434 spin_lock_irq(&pool->lock);
4435 pool->flags &= ~POOL_DISASSOCIATED;
4437 for_each_pool_worker(worker, pool) {
4438 unsigned int worker_flags = worker->flags;
4441 * A bound idle worker should actually be on the runqueue
4442 * of the associated CPU for local wake-ups targeting it to
4443 * work. Kick all idle workers so that they migrate to the
4444 * associated CPU. Doing this in the same loop as
4445 * replacing UNBOUND with REBOUND is safe as no worker will
4446 * be bound before @pool->lock is released.
4448 if (worker_flags & WORKER_IDLE)
4449 wake_up_process(worker->task);
4452 * We want to clear UNBOUND but can't directly call
4453 * worker_clr_flags() or adjust nr_running. Atomically
4454 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
4455 * @worker will clear REBOUND using worker_clr_flags() when
4456 * it initiates the next execution cycle thus restoring
4457 * concurrency management. Note that when or whether
4458 * @worker clears REBOUND doesn't affect correctness.
4460 * ACCESS_ONCE() is necessary because @worker->flags may be
4461 * tested without holding any lock in
4462 * wq_worker_waking_up(). Without it, NOT_RUNNING test may
4463 * fail incorrectly leading to premature concurrency
4464 * management operations.
4466 WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
4467 worker_flags |= WORKER_REBOUND;
4468 worker_flags &= ~WORKER_UNBOUND;
4469 ACCESS_ONCE(worker->flags) = worker_flags;
4472 spin_unlock_irq(&pool->lock);
4476 * restore_unbound_workers_cpumask - restore cpumask of unbound workers
4477 * @pool: unbound pool of interest
4478 * @cpu: the CPU which is coming up
4480 * An unbound pool may end up with a cpumask which doesn't have any online
4481 * CPUs. When a worker of such pool get scheduled, the scheduler resets
4482 * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
4483 * online CPU before, cpus_allowed of all its workers should be restored.
4485 static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
4487 static cpumask_t cpumask;
4488 struct worker *worker;
4490 lockdep_assert_held(&pool->attach_mutex);
4492 /* is @cpu allowed for @pool? */
4493 if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
4496 /* is @cpu the only online CPU? */
4497 cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
4498 if (cpumask_weight(&cpumask) != 1)
4501 /* as we're called from CPU_ONLINE, the following shouldn't fail */
4502 for_each_pool_worker(worker, pool)
4503 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4504 pool->attrs->cpumask) < 0);
4508 * Workqueues should be brought up before normal priority CPU notifiers.
4509 * This will be registered high priority CPU notifier.
4511 static int workqueue_cpu_up_callback(struct notifier_block *nfb,
4512 unsigned long action,
4515 int cpu = (unsigned long)hcpu;
4516 struct worker_pool *pool;
4517 struct workqueue_struct *wq;
4520 switch (action & ~CPU_TASKS_FROZEN) {
4521 case CPU_UP_PREPARE:
4522 for_each_cpu_worker_pool(pool, cpu) {
4523 if (pool->nr_workers)
4525 if (!create_worker(pool))
4530 case CPU_DOWN_FAILED:
4532 mutex_lock(&wq_pool_mutex);
4534 for_each_pool(pool, pi) {
4535 mutex_lock(&pool->attach_mutex);
4537 if (pool->cpu == cpu)
4538 rebind_workers(pool);
4539 else if (pool->cpu < 0)
4540 restore_unbound_workers_cpumask(pool, cpu);
4542 mutex_unlock(&pool->attach_mutex);
4545 /* update NUMA affinity of unbound workqueues */
4546 list_for_each_entry(wq, &workqueues, list)
4547 wq_update_unbound_numa(wq, cpu, true);
4549 mutex_unlock(&wq_pool_mutex);
4556 * Workqueues should be brought down after normal priority CPU notifiers.
4557 * This will be registered as low priority CPU notifier.
4559 static int workqueue_cpu_down_callback(struct notifier_block *nfb,
4560 unsigned long action,
4563 int cpu = (unsigned long)hcpu;
4564 struct work_struct unbind_work;
4565 struct workqueue_struct *wq;
4567 switch (action & ~CPU_TASKS_FROZEN) {
4568 case CPU_DOWN_PREPARE:
4569 /* unbinding per-cpu workers should happen on the local CPU */
4570 INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
4571 queue_work_on(cpu, system_highpri_wq, &unbind_work);
4573 /* update NUMA affinity of unbound workqueues */
4574 mutex_lock(&wq_pool_mutex);
4575 list_for_each_entry(wq, &workqueues, list)
4576 wq_update_unbound_numa(wq, cpu, false);
4577 mutex_unlock(&wq_pool_mutex);
4579 /* wait for per-cpu unbinding to finish */
4580 flush_work(&unbind_work);
4581 destroy_work_on_stack(&unbind_work);
4589 struct work_for_cpu {
4590 struct work_struct work;
4596 static void work_for_cpu_fn(struct work_struct *work)
4598 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
4600 wfc->ret = wfc->fn(wfc->arg);
4604 * work_on_cpu - run a function in user context on a particular cpu
4605 * @cpu: the cpu to run on
4606 * @fn: the function to run
4607 * @arg: the function arg
4609 * It is up to the caller to ensure that the cpu doesn't go offline.
4610 * The caller must not hold any locks which would prevent @fn from completing.
4612 * Return: The value @fn returns.
4614 long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
4616 struct work_for_cpu wfc = { .fn = fn, .arg = arg };
4618 INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
4619 schedule_work_on(cpu, &wfc.work);
4620 flush_work(&wfc.work);
4621 destroy_work_on_stack(&wfc.work);
4624 EXPORT_SYMBOL_GPL(work_on_cpu);
4625 #endif /* CONFIG_SMP */
4627 #ifdef CONFIG_FREEZER
4630 * freeze_workqueues_begin - begin freezing workqueues
4632 * Start freezing workqueues. After this function returns, all freezable
4633 * workqueues will queue new works to their delayed_works list instead of
4637 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4639 void freeze_workqueues_begin(void)
4641 struct workqueue_struct *wq;
4642 struct pool_workqueue *pwq;
4644 mutex_lock(&wq_pool_mutex);
4646 WARN_ON_ONCE(workqueue_freezing);
4647 workqueue_freezing = true;
4649 list_for_each_entry(wq, &workqueues, list) {
4650 mutex_lock(&wq->mutex);
4651 for_each_pwq(pwq, wq)
4652 pwq_adjust_max_active(pwq);
4653 mutex_unlock(&wq->mutex);
4656 mutex_unlock(&wq_pool_mutex);
4660 * freeze_workqueues_busy - are freezable workqueues still busy?
4662 * Check whether freezing is complete. This function must be called
4663 * between freeze_workqueues_begin() and thaw_workqueues().
4666 * Grabs and releases wq_pool_mutex.
4669 * %true if some freezable workqueues are still busy. %false if freezing
4672 bool freeze_workqueues_busy(void)
4675 struct workqueue_struct *wq;
4676 struct pool_workqueue *pwq;
4678 mutex_lock(&wq_pool_mutex);
4680 WARN_ON_ONCE(!workqueue_freezing);
4682 list_for_each_entry(wq, &workqueues, list) {
4683 if (!(wq->flags & WQ_FREEZABLE))
4686 * nr_active is monotonically decreasing. It's safe
4687 * to peek without lock.
4690 for_each_pwq(pwq, wq) {
4691 WARN_ON_ONCE(pwq->nr_active < 0);
4692 if (pwq->nr_active) {
4701 mutex_unlock(&wq_pool_mutex);
4706 * thaw_workqueues - thaw workqueues
4708 * Thaw workqueues. Normal queueing is restored and all collected
4709 * frozen works are transferred to their respective pool worklists.
4712 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4714 void thaw_workqueues(void)
4716 struct workqueue_struct *wq;
4717 struct pool_workqueue *pwq;
4719 mutex_lock(&wq_pool_mutex);
4721 if (!workqueue_freezing)
4724 workqueue_freezing = false;
4726 /* restore max_active and repopulate worklist */
4727 list_for_each_entry(wq, &workqueues, list) {
4728 mutex_lock(&wq->mutex);
4729 for_each_pwq(pwq, wq)
4730 pwq_adjust_max_active(pwq);
4731 mutex_unlock(&wq->mutex);
4735 mutex_unlock(&wq_pool_mutex);
4737 #endif /* CONFIG_FREEZER */
4741 * Workqueues with WQ_SYSFS flag set is visible to userland via
4742 * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
4743 * following attributes.
4745 * per_cpu RO bool : whether the workqueue is per-cpu or unbound
4746 * max_active RW int : maximum number of in-flight work items
4748 * Unbound workqueues have the following extra attributes.
4750 * id RO int : the associated pool ID
4751 * nice RW int : nice value of the workers
4752 * cpumask RW mask : bitmask of allowed CPUs for the workers
4755 struct workqueue_struct *wq;
4759 static struct workqueue_struct *dev_to_wq(struct device *dev)
4761 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
4766 static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
4769 struct workqueue_struct *wq = dev_to_wq(dev);
4771 return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
4773 static DEVICE_ATTR_RO(per_cpu);
4775 static ssize_t max_active_show(struct device *dev,
4776 struct device_attribute *attr, char *buf)
4778 struct workqueue_struct *wq = dev_to_wq(dev);
4780 return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
4783 static ssize_t max_active_store(struct device *dev,
4784 struct device_attribute *attr, const char *buf,
4787 struct workqueue_struct *wq = dev_to_wq(dev);
4790 if (sscanf(buf, "%d", &val) != 1 || val <= 0)
4793 workqueue_set_max_active(wq, val);
4796 static DEVICE_ATTR_RW(max_active);
4798 static struct attribute *wq_sysfs_attrs[] = {
4799 &dev_attr_per_cpu.attr,
4800 &dev_attr_max_active.attr,
4803 ATTRIBUTE_GROUPS(wq_sysfs);
4805 static ssize_t wq_pool_ids_show(struct device *dev,
4806 struct device_attribute *attr, char *buf)
4808 struct workqueue_struct *wq = dev_to_wq(dev);
4809 const char *delim = "";
4810 int node, written = 0;
4814 for_each_node(node) {
4815 written += scnprintf(buf + written, PAGE_SIZE - written,
4816 "%s%d:%d", delim, node,
4817 unbound_pwq_by_node(wq, node)->pool->id);
4820 written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
4827 static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
4830 struct workqueue_struct *wq = dev_to_wq(dev);
4833 mutex_lock(&wq->mutex);
4834 written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
4835 mutex_unlock(&wq->mutex);
4840 /* prepare workqueue_attrs for sysfs store operations */
4841 static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
4843 struct workqueue_attrs *attrs;
4845 attrs = alloc_workqueue_attrs(GFP_KERNEL);
4849 mutex_lock(&wq->mutex);
4850 copy_workqueue_attrs(attrs, wq->unbound_attrs);
4851 mutex_unlock(&wq->mutex);
4855 static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
4856 const char *buf, size_t count)
4858 struct workqueue_struct *wq = dev_to_wq(dev);
4859 struct workqueue_attrs *attrs;
4862 attrs = wq_sysfs_prep_attrs(wq);
4866 if (sscanf(buf, "%d", &attrs->nice) == 1 &&
4867 attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
4868 ret = apply_workqueue_attrs(wq, attrs);
4872 free_workqueue_attrs(attrs);
4873 return ret ?: count;
4876 static ssize_t wq_cpumask_show(struct device *dev,
4877 struct device_attribute *attr, char *buf)
4879 struct workqueue_struct *wq = dev_to_wq(dev);
4882 mutex_lock(&wq->mutex);
4883 written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
4884 cpumask_pr_args(wq->unbound_attrs->cpumask));
4885 mutex_unlock(&wq->mutex);
4889 static ssize_t wq_cpumask_store(struct device *dev,
4890 struct device_attribute *attr,
4891 const char *buf, size_t count)
4893 struct workqueue_struct *wq = dev_to_wq(dev);
4894 struct workqueue_attrs *attrs;
4897 attrs = wq_sysfs_prep_attrs(wq);
4901 ret = cpumask_parse(buf, attrs->cpumask);
4903 ret = apply_workqueue_attrs(wq, attrs);
4905 free_workqueue_attrs(attrs);
4906 return ret ?: count;
4909 static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
4912 struct workqueue_struct *wq = dev_to_wq(dev);
4915 mutex_lock(&wq->mutex);
4916 written = scnprintf(buf, PAGE_SIZE, "%d\n",
4917 !wq->unbound_attrs->no_numa);
4918 mutex_unlock(&wq->mutex);
4923 static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
4924 const char *buf, size_t count)
4926 struct workqueue_struct *wq = dev_to_wq(dev);
4927 struct workqueue_attrs *attrs;
4930 attrs = wq_sysfs_prep_attrs(wq);
4935 if (sscanf(buf, "%d", &v) == 1) {
4936 attrs->no_numa = !v;
4937 ret = apply_workqueue_attrs(wq, attrs);
4940 free_workqueue_attrs(attrs);
4941 return ret ?: count;
4944 static struct device_attribute wq_sysfs_unbound_attrs[] = {
4945 __ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
4946 __ATTR(nice, 0644, wq_nice_show, wq_nice_store),
4947 __ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
4948 __ATTR(numa, 0644, wq_numa_show, wq_numa_store),
4952 static struct bus_type wq_subsys = {
4953 .name = "workqueue",
4954 .dev_groups = wq_sysfs_groups,
4957 static int __init wq_sysfs_init(void)
4959 return subsys_virtual_register(&wq_subsys, NULL);
4961 core_initcall(wq_sysfs_init);
4963 static void wq_device_release(struct device *dev)
4965 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
4971 * workqueue_sysfs_register - make a workqueue visible in sysfs
4972 * @wq: the workqueue to register
4974 * Expose @wq in sysfs under /sys/bus/workqueue/devices.
4975 * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
4976 * which is the preferred method.
4978 * Workqueue user should use this function directly iff it wants to apply
4979 * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
4980 * apply_workqueue_attrs() may race against userland updating the
4983 * Return: 0 on success, -errno on failure.
4985 int workqueue_sysfs_register(struct workqueue_struct *wq)
4987 struct wq_device *wq_dev;
4991 * Adjusting max_active or creating new pwqs by applyting
4992 * attributes breaks ordering guarantee. Disallow exposing ordered
4995 if (WARN_ON(wq->flags & __WQ_ORDERED))
4998 wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
5003 wq_dev->dev.bus = &wq_subsys;
5004 wq_dev->dev.init_name = wq->name;
5005 wq_dev->dev.release = wq_device_release;
5008 * unbound_attrs are created separately. Suppress uevent until
5009 * everything is ready.
5011 dev_set_uevent_suppress(&wq_dev->dev, true);
5013 ret = device_register(&wq_dev->dev);
5020 if (wq->flags & WQ_UNBOUND) {
5021 struct device_attribute *attr;
5023 for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
5024 ret = device_create_file(&wq_dev->dev, attr);
5026 device_unregister(&wq_dev->dev);
5033 dev_set_uevent_suppress(&wq_dev->dev, false);
5034 kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
5039 * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
5040 * @wq: the workqueue to unregister
5042 * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
5044 static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
5046 struct wq_device *wq_dev = wq->wq_dev;
5052 device_unregister(&wq_dev->dev);
5054 #else /* CONFIG_SYSFS */
5055 static void workqueue_sysfs_unregister(struct workqueue_struct *wq) { }
5056 #endif /* CONFIG_SYSFS */
5058 static void __init wq_numa_init(void)
5063 if (num_possible_nodes() <= 1)
5066 if (wq_disable_numa) {
5067 pr_info("workqueue: NUMA affinity support disabled\n");
5071 wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs(GFP_KERNEL);
5072 BUG_ON(!wq_update_unbound_numa_attrs_buf);
5075 * We want masks of possible CPUs of each node which isn't readily
5076 * available. Build one from cpu_to_node() which should have been
5077 * fully initialized by now.
5079 tbl = kzalloc(nr_node_ids * sizeof(tbl[0]), GFP_KERNEL);
5083 BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
5084 node_online(node) ? node : NUMA_NO_NODE));
5086 for_each_possible_cpu(cpu) {
5087 node = cpu_to_node(cpu);
5088 if (WARN_ON(node == NUMA_NO_NODE)) {
5089 pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
5090 /* happens iff arch is bonkers, let's just proceed */
5093 cpumask_set_cpu(cpu, tbl[node]);
5096 wq_numa_possible_cpumask = tbl;
5097 wq_numa_enabled = true;
5100 static int __init init_workqueues(void)
5102 int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
5105 WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
5107 pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
5109 cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
5110 hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
5114 /* initialize CPU pools */
5115 for_each_possible_cpu(cpu) {
5116 struct worker_pool *pool;
5119 for_each_cpu_worker_pool(pool, cpu) {
5120 BUG_ON(init_worker_pool(pool));
5122 cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
5123 pool->attrs->nice = std_nice[i++];
5124 pool->node = cpu_to_node(cpu);
5127 mutex_lock(&wq_pool_mutex);
5128 BUG_ON(worker_pool_assign_id(pool));
5129 mutex_unlock(&wq_pool_mutex);
5133 /* create the initial worker */
5134 for_each_online_cpu(cpu) {
5135 struct worker_pool *pool;
5137 for_each_cpu_worker_pool(pool, cpu) {
5138 pool->flags &= ~POOL_DISASSOCIATED;
5139 BUG_ON(!create_worker(pool));
5143 /* create default unbound and ordered wq attrs */
5144 for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
5145 struct workqueue_attrs *attrs;
5147 BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
5148 attrs->nice = std_nice[i];
5149 unbound_std_wq_attrs[i] = attrs;
5152 * An ordered wq should have only one pwq as ordering is
5153 * guaranteed by max_active which is enforced by pwqs.
5154 * Turn off NUMA so that dfl_pwq is used for all nodes.
5156 BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
5157 attrs->nice = std_nice[i];
5158 attrs->no_numa = true;
5159 ordered_wq_attrs[i] = attrs;
5162 system_wq = alloc_workqueue("events", 0, 0);
5163 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
5164 system_long_wq = alloc_workqueue("events_long", 0, 0);
5165 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
5166 WQ_UNBOUND_MAX_ACTIVE);
5167 system_freezable_wq = alloc_workqueue("events_freezable",
5169 system_power_efficient_wq = alloc_workqueue("events_power_efficient",
5170 WQ_POWER_EFFICIENT, 0);
5171 system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
5172 WQ_FREEZABLE | WQ_POWER_EFFICIENT,
5174 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
5175 !system_unbound_wq || !system_freezable_wq ||
5176 !system_power_efficient_wq ||
5177 !system_freezable_power_efficient_wq);
5180 early_initcall(init_workqueues);