2 * kernel/workqueue.c - generic async execution with shared worker pool
4 * Copyright (C) 2002 Ingo Molnar
6 * Derived from the taskqueue/keventd code by:
7 * David Woodhouse <dwmw2@infradead.org>
9 * Kai Petzke <wpp@marie.physik.tu-berlin.de>
10 * Theodore Ts'o <tytso@mit.edu>
12 * Made to use alloc_percpu by Christoph Lameter.
14 * Copyright (C) 2010 SUSE Linux Products GmbH
15 * Copyright (C) 2010 Tejun Heo <tj@kernel.org>
17 * This is the generic async execution mechanism. Work items as are
18 * executed in process context. The worker pool is shared and
19 * automatically managed. There are two worker pools for each CPU (one for
20 * normal work items and the other for high priority ones) and some extra
21 * pools for workqueues which are not bound to any specific CPU - the
22 * number of these backing pools is dynamic.
24 * Please read Documentation/workqueue.txt for details.
27 #include <linux/export.h>
28 #include <linux/kernel.h>
29 #include <linux/sched.h>
30 #include <linux/init.h>
31 #include <linux/signal.h>
32 #include <linux/completion.h>
33 #include <linux/workqueue.h>
34 #include <linux/slab.h>
35 #include <linux/cpu.h>
36 #include <linux/notifier.h>
37 #include <linux/kthread.h>
38 #include <linux/hardirq.h>
39 #include <linux/mempolicy.h>
40 #include <linux/freezer.h>
41 #include <linux/kallsyms.h>
42 #include <linux/debug_locks.h>
43 #include <linux/lockdep.h>
44 #include <linux/idr.h>
45 #include <linux/jhash.h>
46 #include <linux/hashtable.h>
47 #include <linux/rculist.h>
48 #include <linux/nodemask.h>
49 #include <linux/moduleparam.h>
50 #include <linux/uaccess.h>
52 #include "workqueue_internal.h"
58 * A bound pool is either associated or disassociated with its CPU.
59 * While associated (!DISASSOCIATED), all workers are bound to the
60 * CPU and none has %WORKER_UNBOUND set and concurrency management
63 * While DISASSOCIATED, the cpu may be offline and all workers have
64 * %WORKER_UNBOUND set and concurrency management disabled, and may
65 * be executing on any CPU. The pool behaves as an unbound one.
67 * Note that DISASSOCIATED should be flipped only while holding
68 * attach_mutex to avoid changing binding state while
69 * worker_attach_to_pool() is in progress.
71 POOL_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
74 WORKER_DIE = 1 << 1, /* die die die */
75 WORKER_IDLE = 1 << 2, /* is idle */
76 WORKER_PREP = 1 << 3, /* preparing to run works */
77 WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
78 WORKER_UNBOUND = 1 << 7, /* worker is unbound */
79 WORKER_REBOUND = 1 << 8, /* worker was rebound */
81 WORKER_NOT_RUNNING = WORKER_PREP | WORKER_CPU_INTENSIVE |
82 WORKER_UNBOUND | WORKER_REBOUND,
84 NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */
86 UNBOUND_POOL_HASH_ORDER = 6, /* hashed by pool->attrs */
87 BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
89 MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
90 IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
92 MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
93 /* call for help after 10ms
95 MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
96 CREATE_COOLDOWN = HZ, /* time to breath after fail */
99 * Rescue workers are used only on emergencies and shared by
100 * all cpus. Give MIN_NICE.
102 RESCUER_NICE_LEVEL = MIN_NICE,
103 HIGHPRI_NICE_LEVEL = MIN_NICE,
109 * Structure fields follow one of the following exclusion rules.
111 * I: Modifiable by initialization/destruction paths and read-only for
114 * P: Preemption protected. Disabling preemption is enough and should
115 * only be modified and accessed from the local cpu.
117 * L: pool->lock protected. Access with pool->lock held.
119 * X: During normal operation, modification requires pool->lock and should
120 * be done only from local cpu. Either disabling preemption on local
121 * cpu or grabbing pool->lock is enough for read access. If
122 * POOL_DISASSOCIATED is set, it's identical to L.
124 * A: pool->attach_mutex protected.
126 * PL: wq_pool_mutex protected.
128 * PR: wq_pool_mutex protected for writes. Sched-RCU protected for reads.
130 * WQ: wq->mutex protected.
132 * WR: wq->mutex protected for writes. Sched-RCU protected for reads.
134 * MD: wq_mayday_lock protected.
137 /* struct worker is defined in workqueue_internal.h */
140 spinlock_t lock; /* the pool lock */
141 int cpu; /* I: the associated cpu */
142 int node; /* I: the associated node ID */
143 int id; /* I: pool ID */
144 unsigned int flags; /* X: flags */
146 struct list_head worklist; /* L: list of pending works */
147 int nr_workers; /* L: total number of workers */
149 /* nr_idle includes the ones off idle_list for rebinding */
150 int nr_idle; /* L: currently idle ones */
152 struct list_head idle_list; /* X: list of idle workers */
153 struct timer_list idle_timer; /* L: worker idle timeout */
154 struct timer_list mayday_timer; /* L: SOS timer for workers */
156 /* a workers is either on busy_hash or idle_list, or the manager */
157 DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
158 /* L: hash of busy workers */
160 /* see manage_workers() for details on the two manager mutexes */
161 struct mutex manager_arb; /* manager arbitration */
162 struct worker *manager; /* L: purely informational */
163 struct mutex attach_mutex; /* attach/detach exclusion */
164 struct list_head workers; /* A: attached workers */
165 struct completion *detach_completion; /* all workers detached */
167 struct ida worker_ida; /* worker IDs for task name */
169 struct workqueue_attrs *attrs; /* I: worker attributes */
170 struct hlist_node hash_node; /* PL: unbound_pool_hash node */
171 int refcnt; /* PL: refcnt for unbound pools */
174 * The current concurrency level. As it's likely to be accessed
175 * from other CPUs during try_to_wake_up(), put it in a separate
178 atomic_t nr_running ____cacheline_aligned_in_smp;
181 * Destruction of pool is sched-RCU protected to allow dereferences
182 * from get_work_pool().
185 } ____cacheline_aligned_in_smp;
188 * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
189 * of work_struct->data are used for flags and the remaining high bits
190 * point to the pwq; thus, pwqs need to be aligned at two's power of the
191 * number of flag bits.
193 struct pool_workqueue {
194 struct worker_pool *pool; /* I: the associated pool */
195 struct workqueue_struct *wq; /* I: the owning workqueue */
196 int work_color; /* L: current color */
197 int flush_color; /* L: flushing color */
198 int refcnt; /* L: reference count */
199 int nr_in_flight[WORK_NR_COLORS];
200 /* L: nr of in_flight works */
201 int nr_active; /* L: nr of active works */
202 int max_active; /* L: max active works */
203 struct list_head delayed_works; /* L: delayed works */
204 struct list_head pwqs_node; /* WR: node on wq->pwqs */
205 struct list_head mayday_node; /* MD: node on wq->maydays */
208 * Release of unbound pwq is punted to system_wq. See put_pwq()
209 * and pwq_unbound_release_workfn() for details. pool_workqueue
210 * itself is also sched-RCU protected so that the first pwq can be
211 * determined without grabbing wq->mutex.
213 struct work_struct unbound_release_work;
215 } __aligned(1 << WORK_STRUCT_FLAG_BITS);
218 * Structure used to wait for workqueue flush.
221 struct list_head list; /* WQ: list of flushers */
222 int flush_color; /* WQ: flush color waiting for */
223 struct completion done; /* flush completion */
229 * The externally visible workqueue. It relays the issued work items to
230 * the appropriate worker_pool through its pool_workqueues.
232 struct workqueue_struct {
233 struct list_head pwqs; /* WR: all pwqs of this wq */
234 struct list_head list; /* PR: list of all workqueues */
236 struct mutex mutex; /* protects this wq */
237 int work_color; /* WQ: current work color */
238 int flush_color; /* WQ: current flush color */
239 atomic_t nr_pwqs_to_flush; /* flush in progress */
240 struct wq_flusher *first_flusher; /* WQ: first flusher */
241 struct list_head flusher_queue; /* WQ: flush waiters */
242 struct list_head flusher_overflow; /* WQ: flush overflow list */
244 struct list_head maydays; /* MD: pwqs requesting rescue */
245 struct worker *rescuer; /* I: rescue worker */
247 int nr_drainers; /* WQ: drain in progress */
248 int saved_max_active; /* WQ: saved pwq max_active */
250 struct workqueue_attrs *unbound_attrs; /* WQ: only for unbound wqs */
251 struct pool_workqueue *dfl_pwq; /* WQ: only for unbound wqs */
254 struct wq_device *wq_dev; /* I: for sysfs interface */
256 #ifdef CONFIG_LOCKDEP
257 struct lockdep_map lockdep_map;
259 char name[WQ_NAME_LEN]; /* I: workqueue name */
262 * Destruction of workqueue_struct is sched-RCU protected to allow
263 * walking the workqueues list without grabbing wq_pool_mutex.
264 * This is used to dump all workqueues from sysrq.
268 /* hot fields used during command issue, aligned to cacheline */
269 unsigned int flags ____cacheline_aligned; /* WQ: WQ_* flags */
270 struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */
271 struct pool_workqueue __rcu *numa_pwq_tbl[]; /* FR: unbound pwqs indexed by node */
274 static struct kmem_cache *pwq_cache;
276 static cpumask_var_t *wq_numa_possible_cpumask;
277 /* possible CPUs of each node */
279 static bool wq_disable_numa;
280 module_param_named(disable_numa, wq_disable_numa, bool, 0444);
282 /* see the comment above the definition of WQ_POWER_EFFICIENT */
283 #ifdef CONFIG_WQ_POWER_EFFICIENT_DEFAULT
284 static bool wq_power_efficient = true;
286 static bool wq_power_efficient;
289 module_param_named(power_efficient, wq_power_efficient, bool, 0444);
291 static bool wq_numa_enabled; /* unbound NUMA affinity enabled */
293 /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
294 static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf;
296 static DEFINE_MUTEX(wq_pool_mutex); /* protects pools and workqueues list */
297 static DEFINE_SPINLOCK(wq_mayday_lock); /* protects wq->maydays list */
299 static LIST_HEAD(workqueues); /* PR: list of all workqueues */
300 static bool workqueue_freezing; /* PL: have wqs started freezing? */
302 /* the per-cpu worker pools */
303 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
306 static DEFINE_IDR(worker_pool_idr); /* PR: idr of all pools */
308 /* PL: hash of all unbound pools keyed by pool->attrs */
309 static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
311 /* I: attributes used when instantiating standard unbound pools on demand */
312 static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
314 /* I: attributes used when instantiating ordered pools on demand */
315 static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
317 struct workqueue_struct *system_wq __read_mostly;
318 EXPORT_SYMBOL(system_wq);
319 struct workqueue_struct *system_highpri_wq __read_mostly;
320 EXPORT_SYMBOL_GPL(system_highpri_wq);
321 struct workqueue_struct *system_long_wq __read_mostly;
322 EXPORT_SYMBOL_GPL(system_long_wq);
323 struct workqueue_struct *system_unbound_wq __read_mostly;
324 EXPORT_SYMBOL_GPL(system_unbound_wq);
325 struct workqueue_struct *system_freezable_wq __read_mostly;
326 EXPORT_SYMBOL_GPL(system_freezable_wq);
327 struct workqueue_struct *system_power_efficient_wq __read_mostly;
328 EXPORT_SYMBOL_GPL(system_power_efficient_wq);
329 struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
330 EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
332 static int worker_thread(void *__worker);
333 static void copy_workqueue_attrs(struct workqueue_attrs *to,
334 const struct workqueue_attrs *from);
336 #define CREATE_TRACE_POINTS
337 #include <trace/events/workqueue.h>
339 #define assert_rcu_or_pool_mutex() \
340 rcu_lockdep_assert(rcu_read_lock_sched_held() || \
341 lockdep_is_held(&wq_pool_mutex), \
342 "sched RCU or wq_pool_mutex should be held")
344 #define assert_rcu_or_wq_mutex(wq) \
345 rcu_lockdep_assert(rcu_read_lock_sched_held() || \
346 lockdep_is_held(&wq->mutex), \
347 "sched RCU or wq->mutex should be held")
349 #define for_each_cpu_worker_pool(pool, cpu) \
350 for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
351 (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
355 * for_each_pool - iterate through all worker_pools in the system
356 * @pool: iteration cursor
357 * @pi: integer used for iteration
359 * This must be called either with wq_pool_mutex held or sched RCU read
360 * locked. If the pool needs to be used beyond the locking in effect, the
361 * caller is responsible for guaranteeing that the pool stays online.
363 * The if/else clause exists only for the lockdep assertion and can be
366 #define for_each_pool(pool, pi) \
367 idr_for_each_entry(&worker_pool_idr, pool, pi) \
368 if (({ assert_rcu_or_pool_mutex(); false; })) { } \
372 * for_each_pool_worker - iterate through all workers of a worker_pool
373 * @worker: iteration cursor
374 * @pool: worker_pool to iterate workers of
376 * This must be called with @pool->attach_mutex.
378 * The if/else clause exists only for the lockdep assertion and can be
381 #define for_each_pool_worker(worker, pool) \
382 list_for_each_entry((worker), &(pool)->workers, node) \
383 if (({ lockdep_assert_held(&pool->attach_mutex); false; })) { } \
387 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
388 * @pwq: iteration cursor
389 * @wq: the target workqueue
391 * This must be called either with wq->mutex held or sched RCU read locked.
392 * If the pwq needs to be used beyond the locking in effect, the caller is
393 * responsible for guaranteeing that the pwq stays online.
395 * The if/else clause exists only for the lockdep assertion and can be
398 #define for_each_pwq(pwq, wq) \
399 list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node) \
400 if (({ assert_rcu_or_wq_mutex(wq); false; })) { } \
403 #ifdef CONFIG_DEBUG_OBJECTS_WORK
405 static struct debug_obj_descr work_debug_descr;
407 static void *work_debug_hint(void *addr)
409 return ((struct work_struct *) addr)->func;
413 * fixup_init is called when:
414 * - an active object is initialized
416 static int work_fixup_init(void *addr, enum debug_obj_state state)
418 struct work_struct *work = addr;
421 case ODEBUG_STATE_ACTIVE:
422 cancel_work_sync(work);
423 debug_object_init(work, &work_debug_descr);
431 * fixup_activate is called when:
432 * - an active object is activated
433 * - an unknown object is activated (might be a statically initialized object)
435 static int work_fixup_activate(void *addr, enum debug_obj_state state)
437 struct work_struct *work = addr;
441 case ODEBUG_STATE_NOTAVAILABLE:
443 * This is not really a fixup. The work struct was
444 * statically initialized. We just make sure that it
445 * is tracked in the object tracker.
447 if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
448 debug_object_init(work, &work_debug_descr);
449 debug_object_activate(work, &work_debug_descr);
455 case ODEBUG_STATE_ACTIVE:
464 * fixup_free is called when:
465 * - an active object is freed
467 static int work_fixup_free(void *addr, enum debug_obj_state state)
469 struct work_struct *work = addr;
472 case ODEBUG_STATE_ACTIVE:
473 cancel_work_sync(work);
474 debug_object_free(work, &work_debug_descr);
481 static struct debug_obj_descr work_debug_descr = {
482 .name = "work_struct",
483 .debug_hint = work_debug_hint,
484 .fixup_init = work_fixup_init,
485 .fixup_activate = work_fixup_activate,
486 .fixup_free = work_fixup_free,
489 static inline void debug_work_activate(struct work_struct *work)
491 debug_object_activate(work, &work_debug_descr);
494 static inline void debug_work_deactivate(struct work_struct *work)
496 debug_object_deactivate(work, &work_debug_descr);
499 void __init_work(struct work_struct *work, int onstack)
502 debug_object_init_on_stack(work, &work_debug_descr);
504 debug_object_init(work, &work_debug_descr);
506 EXPORT_SYMBOL_GPL(__init_work);
508 void destroy_work_on_stack(struct work_struct *work)
510 debug_object_free(work, &work_debug_descr);
512 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
514 void destroy_delayed_work_on_stack(struct delayed_work *work)
516 destroy_timer_on_stack(&work->timer);
517 debug_object_free(&work->work, &work_debug_descr);
519 EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
522 static inline void debug_work_activate(struct work_struct *work) { }
523 static inline void debug_work_deactivate(struct work_struct *work) { }
527 * worker_pool_assign_id - allocate ID and assing it to @pool
528 * @pool: the pool pointer of interest
530 * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
531 * successfully, -errno on failure.
533 static int worker_pool_assign_id(struct worker_pool *pool)
537 lockdep_assert_held(&wq_pool_mutex);
539 ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
549 * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
550 * @wq: the target workqueue
553 * This must be called either with pwq_lock held or sched RCU read locked.
554 * If the pwq needs to be used beyond the locking in effect, the caller is
555 * responsible for guaranteeing that the pwq stays online.
557 * Return: The unbound pool_workqueue for @node.
559 static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
562 assert_rcu_or_wq_mutex(wq);
563 return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
566 static unsigned int work_color_to_flags(int color)
568 return color << WORK_STRUCT_COLOR_SHIFT;
571 static int get_work_color(struct work_struct *work)
573 return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
574 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
577 static int work_next_color(int color)
579 return (color + 1) % WORK_NR_COLORS;
583 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
584 * contain the pointer to the queued pwq. Once execution starts, the flag
585 * is cleared and the high bits contain OFFQ flags and pool ID.
587 * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
588 * and clear_work_data() can be used to set the pwq, pool or clear
589 * work->data. These functions should only be called while the work is
590 * owned - ie. while the PENDING bit is set.
592 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
593 * corresponding to a work. Pool is available once the work has been
594 * queued anywhere after initialization until it is sync canceled. pwq is
595 * available only while the work item is queued.
597 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
598 * canceled. While being canceled, a work item may have its PENDING set
599 * but stay off timer and worklist for arbitrarily long and nobody should
600 * try to steal the PENDING bit.
602 static inline void set_work_data(struct work_struct *work, unsigned long data,
605 WARN_ON_ONCE(!work_pending(work));
606 atomic_long_set(&work->data, data | flags | work_static(work));
609 static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
610 unsigned long extra_flags)
612 set_work_data(work, (unsigned long)pwq,
613 WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
616 static void set_work_pool_and_keep_pending(struct work_struct *work,
619 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
620 WORK_STRUCT_PENDING);
623 static void set_work_pool_and_clear_pending(struct work_struct *work,
627 * The following wmb is paired with the implied mb in
628 * test_and_set_bit(PENDING) and ensures all updates to @work made
629 * here are visible to and precede any updates by the next PENDING
633 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
636 static void clear_work_data(struct work_struct *work)
638 smp_wmb(); /* see set_work_pool_and_clear_pending() */
639 set_work_data(work, WORK_STRUCT_NO_POOL, 0);
642 static struct pool_workqueue *get_work_pwq(struct work_struct *work)
644 unsigned long data = atomic_long_read(&work->data);
646 if (data & WORK_STRUCT_PWQ)
647 return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
653 * get_work_pool - return the worker_pool a given work was associated with
654 * @work: the work item of interest
656 * Pools are created and destroyed under wq_pool_mutex, and allows read
657 * access under sched-RCU read lock. As such, this function should be
658 * called under wq_pool_mutex or with preemption disabled.
660 * All fields of the returned pool are accessible as long as the above
661 * mentioned locking is in effect. If the returned pool needs to be used
662 * beyond the critical section, the caller is responsible for ensuring the
663 * returned pool is and stays online.
665 * Return: The worker_pool @work was last associated with. %NULL if none.
667 static struct worker_pool *get_work_pool(struct work_struct *work)
669 unsigned long data = atomic_long_read(&work->data);
672 assert_rcu_or_pool_mutex();
674 if (data & WORK_STRUCT_PWQ)
675 return ((struct pool_workqueue *)
676 (data & WORK_STRUCT_WQ_DATA_MASK))->pool;
678 pool_id = data >> WORK_OFFQ_POOL_SHIFT;
679 if (pool_id == WORK_OFFQ_POOL_NONE)
682 return idr_find(&worker_pool_idr, pool_id);
686 * get_work_pool_id - return the worker pool ID a given work is associated with
687 * @work: the work item of interest
689 * Return: The worker_pool ID @work was last associated with.
690 * %WORK_OFFQ_POOL_NONE if none.
692 static int get_work_pool_id(struct work_struct *work)
694 unsigned long data = atomic_long_read(&work->data);
696 if (data & WORK_STRUCT_PWQ)
697 return ((struct pool_workqueue *)
698 (data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
700 return data >> WORK_OFFQ_POOL_SHIFT;
703 static void mark_work_canceling(struct work_struct *work)
705 unsigned long pool_id = get_work_pool_id(work);
707 pool_id <<= WORK_OFFQ_POOL_SHIFT;
708 set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
711 static bool work_is_canceling(struct work_struct *work)
713 unsigned long data = atomic_long_read(&work->data);
715 return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
719 * Policy functions. These define the policies on how the global worker
720 * pools are managed. Unless noted otherwise, these functions assume that
721 * they're being called with pool->lock held.
724 static bool __need_more_worker(struct worker_pool *pool)
726 return !atomic_read(&pool->nr_running);
730 * Need to wake up a worker? Called from anything but currently
733 * Note that, because unbound workers never contribute to nr_running, this
734 * function will always return %true for unbound pools as long as the
735 * worklist isn't empty.
737 static bool need_more_worker(struct worker_pool *pool)
739 return !list_empty(&pool->worklist) && __need_more_worker(pool);
742 /* Can I start working? Called from busy but !running workers. */
743 static bool may_start_working(struct worker_pool *pool)
745 return pool->nr_idle;
748 /* Do I need to keep working? Called from currently running workers. */
749 static bool keep_working(struct worker_pool *pool)
751 return !list_empty(&pool->worklist) &&
752 atomic_read(&pool->nr_running) <= 1;
755 /* Do we need a new worker? Called from manager. */
756 static bool need_to_create_worker(struct worker_pool *pool)
758 return need_more_worker(pool) && !may_start_working(pool);
761 /* Do we have too many workers and should some go away? */
762 static bool too_many_workers(struct worker_pool *pool)
764 bool managing = mutex_is_locked(&pool->manager_arb);
765 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
766 int nr_busy = pool->nr_workers - nr_idle;
768 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
775 /* Return the first idle worker. Safe with preemption disabled */
776 static struct worker *first_idle_worker(struct worker_pool *pool)
778 if (unlikely(list_empty(&pool->idle_list)))
781 return list_first_entry(&pool->idle_list, struct worker, entry);
785 * wake_up_worker - wake up an idle worker
786 * @pool: worker pool to wake worker from
788 * Wake up the first idle worker of @pool.
791 * spin_lock_irq(pool->lock).
793 static void wake_up_worker(struct worker_pool *pool)
795 struct worker *worker = first_idle_worker(pool);
798 wake_up_process(worker->task);
802 * wq_worker_waking_up - a worker is waking up
803 * @task: task waking up
804 * @cpu: CPU @task is waking up to
806 * This function is called during try_to_wake_up() when a worker is
810 * spin_lock_irq(rq->lock)
812 void wq_worker_waking_up(struct task_struct *task, int cpu)
814 struct worker *worker = kthread_data(task);
816 if (!(worker->flags & WORKER_NOT_RUNNING)) {
817 WARN_ON_ONCE(worker->pool->cpu != cpu);
818 atomic_inc(&worker->pool->nr_running);
823 * wq_worker_sleeping - a worker is going to sleep
824 * @task: task going to sleep
825 * @cpu: CPU in question, must be the current CPU number
827 * This function is called during schedule() when a busy worker is
828 * going to sleep. Worker on the same cpu can be woken up by
829 * returning pointer to its task.
832 * spin_lock_irq(rq->lock)
835 * Worker task on @cpu to wake up, %NULL if none.
837 struct task_struct *wq_worker_sleeping(struct task_struct *task, int cpu)
839 struct worker *worker = kthread_data(task), *to_wakeup = NULL;
840 struct worker_pool *pool;
843 * Rescuers, which may not have all the fields set up like normal
844 * workers, also reach here, let's not access anything before
845 * checking NOT_RUNNING.
847 if (worker->flags & WORKER_NOT_RUNNING)
852 /* this can only happen on the local cpu */
853 if (WARN_ON_ONCE(cpu != raw_smp_processor_id() || pool->cpu != cpu))
857 * The counterpart of the following dec_and_test, implied mb,
858 * worklist not empty test sequence is in insert_work().
859 * Please read comment there.
861 * NOT_RUNNING is clear. This means that we're bound to and
862 * running on the local cpu w/ rq lock held and preemption
863 * disabled, which in turn means that none else could be
864 * manipulating idle_list, so dereferencing idle_list without pool
867 if (atomic_dec_and_test(&pool->nr_running) &&
868 !list_empty(&pool->worklist))
869 to_wakeup = first_idle_worker(pool);
870 return to_wakeup ? to_wakeup->task : NULL;
874 * worker_set_flags - set worker flags and adjust nr_running accordingly
876 * @flags: flags to set
878 * Set @flags in @worker->flags and adjust nr_running accordingly.
881 * spin_lock_irq(pool->lock)
883 static inline void worker_set_flags(struct worker *worker, unsigned int flags)
885 struct worker_pool *pool = worker->pool;
887 WARN_ON_ONCE(worker->task != current);
889 /* If transitioning into NOT_RUNNING, adjust nr_running. */
890 if ((flags & WORKER_NOT_RUNNING) &&
891 !(worker->flags & WORKER_NOT_RUNNING)) {
892 atomic_dec(&pool->nr_running);
895 worker->flags |= flags;
899 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
901 * @flags: flags to clear
903 * Clear @flags in @worker->flags and adjust nr_running accordingly.
906 * spin_lock_irq(pool->lock)
908 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
910 struct worker_pool *pool = worker->pool;
911 unsigned int oflags = worker->flags;
913 WARN_ON_ONCE(worker->task != current);
915 worker->flags &= ~flags;
918 * If transitioning out of NOT_RUNNING, increment nr_running. Note
919 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
920 * of multiple flags, not a single flag.
922 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
923 if (!(worker->flags & WORKER_NOT_RUNNING))
924 atomic_inc(&pool->nr_running);
928 * find_worker_executing_work - find worker which is executing a work
929 * @pool: pool of interest
930 * @work: work to find worker for
932 * Find a worker which is executing @work on @pool by searching
933 * @pool->busy_hash which is keyed by the address of @work. For a worker
934 * to match, its current execution should match the address of @work and
935 * its work function. This is to avoid unwanted dependency between
936 * unrelated work executions through a work item being recycled while still
939 * This is a bit tricky. A work item may be freed once its execution
940 * starts and nothing prevents the freed area from being recycled for
941 * another work item. If the same work item address ends up being reused
942 * before the original execution finishes, workqueue will identify the
943 * recycled work item as currently executing and make it wait until the
944 * current execution finishes, introducing an unwanted dependency.
946 * This function checks the work item address and work function to avoid
947 * false positives. Note that this isn't complete as one may construct a
948 * work function which can introduce dependency onto itself through a
949 * recycled work item. Well, if somebody wants to shoot oneself in the
950 * foot that badly, there's only so much we can do, and if such deadlock
951 * actually occurs, it should be easy to locate the culprit work function.
954 * spin_lock_irq(pool->lock).
957 * Pointer to worker which is executing @work if found, %NULL
960 static struct worker *find_worker_executing_work(struct worker_pool *pool,
961 struct work_struct *work)
963 struct worker *worker;
965 hash_for_each_possible(pool->busy_hash, worker, hentry,
967 if (worker->current_work == work &&
968 worker->current_func == work->func)
975 * move_linked_works - move linked works to a list
976 * @work: start of series of works to be scheduled
977 * @head: target list to append @work to
978 * @nextp: out paramter for nested worklist walking
980 * Schedule linked works starting from @work to @head. Work series to
981 * be scheduled starts at @work and includes any consecutive work with
982 * WORK_STRUCT_LINKED set in its predecessor.
984 * If @nextp is not NULL, it's updated to point to the next work of
985 * the last scheduled work. This allows move_linked_works() to be
986 * nested inside outer list_for_each_entry_safe().
989 * spin_lock_irq(pool->lock).
991 static void move_linked_works(struct work_struct *work, struct list_head *head,
992 struct work_struct **nextp)
994 struct work_struct *n;
997 * Linked worklist will always end before the end of the list,
998 * use NULL for list head.
1000 list_for_each_entry_safe_from(work, n, NULL, entry) {
1001 list_move_tail(&work->entry, head);
1002 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1007 * If we're already inside safe list traversal and have moved
1008 * multiple works to the scheduled queue, the next position
1009 * needs to be updated.
1016 * get_pwq - get an extra reference on the specified pool_workqueue
1017 * @pwq: pool_workqueue to get
1019 * Obtain an extra reference on @pwq. The caller should guarantee that
1020 * @pwq has positive refcnt and be holding the matching pool->lock.
1022 static void get_pwq(struct pool_workqueue *pwq)
1024 lockdep_assert_held(&pwq->pool->lock);
1025 WARN_ON_ONCE(pwq->refcnt <= 0);
1030 * put_pwq - put a pool_workqueue reference
1031 * @pwq: pool_workqueue to put
1033 * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
1034 * destruction. The caller should be holding the matching pool->lock.
1036 static void put_pwq(struct pool_workqueue *pwq)
1038 lockdep_assert_held(&pwq->pool->lock);
1039 if (likely(--pwq->refcnt))
1041 if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
1044 * @pwq can't be released under pool->lock, bounce to
1045 * pwq_unbound_release_workfn(). This never recurses on the same
1046 * pool->lock as this path is taken only for unbound workqueues and
1047 * the release work item is scheduled on a per-cpu workqueue. To
1048 * avoid lockdep warning, unbound pool->locks are given lockdep
1049 * subclass of 1 in get_unbound_pool().
1051 schedule_work(&pwq->unbound_release_work);
1055 * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1056 * @pwq: pool_workqueue to put (can be %NULL)
1058 * put_pwq() with locking. This function also allows %NULL @pwq.
1060 static void put_pwq_unlocked(struct pool_workqueue *pwq)
1064 * As both pwqs and pools are sched-RCU protected, the
1065 * following lock operations are safe.
1067 spin_lock_irq(&pwq->pool->lock);
1069 spin_unlock_irq(&pwq->pool->lock);
1073 static void pwq_activate_delayed_work(struct work_struct *work)
1075 struct pool_workqueue *pwq = get_work_pwq(work);
1077 trace_workqueue_activate_work(work);
1078 move_linked_works(work, &pwq->pool->worklist, NULL);
1079 __clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
1083 static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
1085 struct work_struct *work = list_first_entry(&pwq->delayed_works,
1086 struct work_struct, entry);
1088 pwq_activate_delayed_work(work);
1092 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1093 * @pwq: pwq of interest
1094 * @color: color of work which left the queue
1096 * A work either has completed or is removed from pending queue,
1097 * decrement nr_in_flight of its pwq and handle workqueue flushing.
1100 * spin_lock_irq(pool->lock).
1102 static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
1104 /* uncolored work items don't participate in flushing or nr_active */
1105 if (color == WORK_NO_COLOR)
1108 pwq->nr_in_flight[color]--;
1111 if (!list_empty(&pwq->delayed_works)) {
1112 /* one down, submit a delayed one */
1113 if (pwq->nr_active < pwq->max_active)
1114 pwq_activate_first_delayed(pwq);
1117 /* is flush in progress and are we at the flushing tip? */
1118 if (likely(pwq->flush_color != color))
1121 /* are there still in-flight works? */
1122 if (pwq->nr_in_flight[color])
1125 /* this pwq is done, clear flush_color */
1126 pwq->flush_color = -1;
1129 * If this was the last pwq, wake up the first flusher. It
1130 * will handle the rest.
1132 if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1133 complete(&pwq->wq->first_flusher->done);
1139 * try_to_grab_pending - steal work item from worklist and disable irq
1140 * @work: work item to steal
1141 * @is_dwork: @work is a delayed_work
1142 * @flags: place to store irq state
1144 * Try to grab PENDING bit of @work. This function can handle @work in any
1145 * stable state - idle, on timer or on worklist.
1148 * 1 if @work was pending and we successfully stole PENDING
1149 * 0 if @work was idle and we claimed PENDING
1150 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1151 * -ENOENT if someone else is canceling @work, this state may persist
1152 * for arbitrarily long
1155 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1156 * interrupted while holding PENDING and @work off queue, irq must be
1157 * disabled on entry. This, combined with delayed_work->timer being
1158 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1160 * On successful return, >= 0, irq is disabled and the caller is
1161 * responsible for releasing it using local_irq_restore(*@flags).
1163 * This function is safe to call from any context including IRQ handler.
1165 static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1166 unsigned long *flags)
1168 struct worker_pool *pool;
1169 struct pool_workqueue *pwq;
1171 local_irq_save(*flags);
1173 /* try to steal the timer if it exists */
1175 struct delayed_work *dwork = to_delayed_work(work);
1178 * dwork->timer is irqsafe. If del_timer() fails, it's
1179 * guaranteed that the timer is not queued anywhere and not
1180 * running on the local CPU.
1182 if (likely(del_timer(&dwork->timer)))
1186 /* try to claim PENDING the normal way */
1187 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1191 * The queueing is in progress, or it is already queued. Try to
1192 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1194 pool = get_work_pool(work);
1198 spin_lock(&pool->lock);
1200 * work->data is guaranteed to point to pwq only while the work
1201 * item is queued on pwq->wq, and both updating work->data to point
1202 * to pwq on queueing and to pool on dequeueing are done under
1203 * pwq->pool->lock. This in turn guarantees that, if work->data
1204 * points to pwq which is associated with a locked pool, the work
1205 * item is currently queued on that pool.
1207 pwq = get_work_pwq(work);
1208 if (pwq && pwq->pool == pool) {
1209 debug_work_deactivate(work);
1212 * A delayed work item cannot be grabbed directly because
1213 * it might have linked NO_COLOR work items which, if left
1214 * on the delayed_list, will confuse pwq->nr_active
1215 * management later on and cause stall. Make sure the work
1216 * item is activated before grabbing.
1218 if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1219 pwq_activate_delayed_work(work);
1221 list_del_init(&work->entry);
1222 pwq_dec_nr_in_flight(pwq, get_work_color(work));
1224 /* work->data points to pwq iff queued, point to pool */
1225 set_work_pool_and_keep_pending(work, pool->id);
1227 spin_unlock(&pool->lock);
1230 spin_unlock(&pool->lock);
1232 local_irq_restore(*flags);
1233 if (work_is_canceling(work))
1240 * insert_work - insert a work into a pool
1241 * @pwq: pwq @work belongs to
1242 * @work: work to insert
1243 * @head: insertion point
1244 * @extra_flags: extra WORK_STRUCT_* flags to set
1246 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
1247 * work_struct flags.
1250 * spin_lock_irq(pool->lock).
1252 static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1253 struct list_head *head, unsigned int extra_flags)
1255 struct worker_pool *pool = pwq->pool;
1257 /* we own @work, set data and link */
1258 set_work_pwq(work, pwq, extra_flags);
1259 list_add_tail(&work->entry, head);
1263 * Ensure either wq_worker_sleeping() sees the above
1264 * list_add_tail() or we see zero nr_running to avoid workers lying
1265 * around lazily while there are works to be processed.
1269 if (__need_more_worker(pool))
1270 wake_up_worker(pool);
1274 * Test whether @work is being queued from another work executing on the
1277 static bool is_chained_work(struct workqueue_struct *wq)
1279 struct worker *worker;
1281 worker = current_wq_worker();
1283 * Return %true iff I'm a worker execuing a work item on @wq. If
1284 * I'm @worker, it's safe to dereference it without locking.
1286 return worker && worker->current_pwq->wq == wq;
1289 static void __queue_work(int cpu, struct workqueue_struct *wq,
1290 struct work_struct *work)
1292 struct pool_workqueue *pwq;
1293 struct worker_pool *last_pool;
1294 struct list_head *worklist;
1295 unsigned int work_flags;
1296 unsigned int req_cpu = cpu;
1299 * While a work item is PENDING && off queue, a task trying to
1300 * steal the PENDING will busy-loop waiting for it to either get
1301 * queued or lose PENDING. Grabbing PENDING and queueing should
1302 * happen with IRQ disabled.
1304 WARN_ON_ONCE(!irqs_disabled());
1306 debug_work_activate(work);
1308 /* if draining, only works from the same workqueue are allowed */
1309 if (unlikely(wq->flags & __WQ_DRAINING) &&
1310 WARN_ON_ONCE(!is_chained_work(wq)))
1313 if (req_cpu == WORK_CPU_UNBOUND)
1314 cpu = raw_smp_processor_id();
1316 /* pwq which will be used unless @work is executing elsewhere */
1317 if (!(wq->flags & WQ_UNBOUND))
1318 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1320 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1323 * If @work was previously on a different pool, it might still be
1324 * running there, in which case the work needs to be queued on that
1325 * pool to guarantee non-reentrancy.
1327 last_pool = get_work_pool(work);
1328 if (last_pool && last_pool != pwq->pool) {
1329 struct worker *worker;
1331 spin_lock(&last_pool->lock);
1333 worker = find_worker_executing_work(last_pool, work);
1335 if (worker && worker->current_pwq->wq == wq) {
1336 pwq = worker->current_pwq;
1338 /* meh... not running there, queue here */
1339 spin_unlock(&last_pool->lock);
1340 spin_lock(&pwq->pool->lock);
1343 spin_lock(&pwq->pool->lock);
1347 * pwq is determined and locked. For unbound pools, we could have
1348 * raced with pwq release and it could already be dead. If its
1349 * refcnt is zero, repeat pwq selection. Note that pwqs never die
1350 * without another pwq replacing it in the numa_pwq_tbl or while
1351 * work items are executing on it, so the retrying is guaranteed to
1352 * make forward-progress.
1354 if (unlikely(!pwq->refcnt)) {
1355 if (wq->flags & WQ_UNBOUND) {
1356 spin_unlock(&pwq->pool->lock);
1361 WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
1365 /* pwq determined, queue */
1366 trace_workqueue_queue_work(req_cpu, pwq, work);
1368 if (WARN_ON(!list_empty(&work->entry))) {
1369 spin_unlock(&pwq->pool->lock);
1373 pwq->nr_in_flight[pwq->work_color]++;
1374 work_flags = work_color_to_flags(pwq->work_color);
1376 if (likely(pwq->nr_active < pwq->max_active)) {
1377 trace_workqueue_activate_work(work);
1379 worklist = &pwq->pool->worklist;
1381 work_flags |= WORK_STRUCT_DELAYED;
1382 worklist = &pwq->delayed_works;
1385 insert_work(pwq, work, worklist, work_flags);
1387 spin_unlock(&pwq->pool->lock);
1391 * queue_work_on - queue work on specific cpu
1392 * @cpu: CPU number to execute work on
1393 * @wq: workqueue to use
1394 * @work: work to queue
1396 * We queue the work to a specific CPU, the caller must ensure it
1399 * Return: %false if @work was already on a queue, %true otherwise.
1401 bool queue_work_on(int cpu, struct workqueue_struct *wq,
1402 struct work_struct *work)
1405 unsigned long flags;
1407 local_irq_save(flags);
1409 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1410 __queue_work(cpu, wq, work);
1414 local_irq_restore(flags);
1417 EXPORT_SYMBOL(queue_work_on);
1419 void delayed_work_timer_fn(unsigned long __data)
1421 struct delayed_work *dwork = (struct delayed_work *)__data;
1423 /* should have been called from irqsafe timer with irq already off */
1424 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
1426 EXPORT_SYMBOL(delayed_work_timer_fn);
1428 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
1429 struct delayed_work *dwork, unsigned long delay)
1431 struct timer_list *timer = &dwork->timer;
1432 struct work_struct *work = &dwork->work;
1434 WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
1435 timer->data != (unsigned long)dwork);
1436 WARN_ON_ONCE(timer_pending(timer));
1437 WARN_ON_ONCE(!list_empty(&work->entry));
1440 * If @delay is 0, queue @dwork->work immediately. This is for
1441 * both optimization and correctness. The earliest @timer can
1442 * expire is on the closest next tick and delayed_work users depend
1443 * on that there's no such delay when @delay is 0.
1446 __queue_work(cpu, wq, &dwork->work);
1450 timer_stats_timer_set_start_info(&dwork->timer);
1454 timer->expires = jiffies + delay;
1456 if (unlikely(cpu != WORK_CPU_UNBOUND))
1457 add_timer_on(timer, cpu);
1463 * queue_delayed_work_on - queue work on specific CPU after delay
1464 * @cpu: CPU number to execute work on
1465 * @wq: workqueue to use
1466 * @dwork: work to queue
1467 * @delay: number of jiffies to wait before queueing
1469 * Return: %false if @work was already on a queue, %true otherwise. If
1470 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1473 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1474 struct delayed_work *dwork, unsigned long delay)
1476 struct work_struct *work = &dwork->work;
1478 unsigned long flags;
1480 /* read the comment in __queue_work() */
1481 local_irq_save(flags);
1483 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1484 __queue_delayed_work(cpu, wq, dwork, delay);
1488 local_irq_restore(flags);
1491 EXPORT_SYMBOL(queue_delayed_work_on);
1494 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1495 * @cpu: CPU number to execute work on
1496 * @wq: workqueue to use
1497 * @dwork: work to queue
1498 * @delay: number of jiffies to wait before queueing
1500 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1501 * modify @dwork's timer so that it expires after @delay. If @delay is
1502 * zero, @work is guaranteed to be scheduled immediately regardless of its
1505 * Return: %false if @dwork was idle and queued, %true if @dwork was
1506 * pending and its timer was modified.
1508 * This function is safe to call from any context including IRQ handler.
1509 * See try_to_grab_pending() for details.
1511 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
1512 struct delayed_work *dwork, unsigned long delay)
1514 unsigned long flags;
1518 ret = try_to_grab_pending(&dwork->work, true, &flags);
1519 } while (unlikely(ret == -EAGAIN));
1521 if (likely(ret >= 0)) {
1522 __queue_delayed_work(cpu, wq, dwork, delay);
1523 local_irq_restore(flags);
1526 /* -ENOENT from try_to_grab_pending() becomes %true */
1529 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
1532 * worker_enter_idle - enter idle state
1533 * @worker: worker which is entering idle state
1535 * @worker is entering idle state. Update stats and idle timer if
1539 * spin_lock_irq(pool->lock).
1541 static void worker_enter_idle(struct worker *worker)
1543 struct worker_pool *pool = worker->pool;
1545 if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
1546 WARN_ON_ONCE(!list_empty(&worker->entry) &&
1547 (worker->hentry.next || worker->hentry.pprev)))
1550 /* can't use worker_set_flags(), also called from create_worker() */
1551 worker->flags |= WORKER_IDLE;
1553 worker->last_active = jiffies;
1555 /* idle_list is LIFO */
1556 list_add(&worker->entry, &pool->idle_list);
1558 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1559 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1562 * Sanity check nr_running. Because wq_unbind_fn() releases
1563 * pool->lock between setting %WORKER_UNBOUND and zapping
1564 * nr_running, the warning may trigger spuriously. Check iff
1565 * unbind is not in progress.
1567 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1568 pool->nr_workers == pool->nr_idle &&
1569 atomic_read(&pool->nr_running));
1573 * worker_leave_idle - leave idle state
1574 * @worker: worker which is leaving idle state
1576 * @worker is leaving idle state. Update stats.
1579 * spin_lock_irq(pool->lock).
1581 static void worker_leave_idle(struct worker *worker)
1583 struct worker_pool *pool = worker->pool;
1585 if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
1587 worker_clr_flags(worker, WORKER_IDLE);
1589 list_del_init(&worker->entry);
1592 static struct worker *alloc_worker(int node)
1594 struct worker *worker;
1596 worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
1598 INIT_LIST_HEAD(&worker->entry);
1599 INIT_LIST_HEAD(&worker->scheduled);
1600 INIT_LIST_HEAD(&worker->node);
1601 /* on creation a worker is in !idle && prep state */
1602 worker->flags = WORKER_PREP;
1608 * worker_attach_to_pool() - attach a worker to a pool
1609 * @worker: worker to be attached
1610 * @pool: the target pool
1612 * Attach @worker to @pool. Once attached, the %WORKER_UNBOUND flag and
1613 * cpu-binding of @worker are kept coordinated with the pool across
1616 static void worker_attach_to_pool(struct worker *worker,
1617 struct worker_pool *pool)
1619 mutex_lock(&pool->attach_mutex);
1622 * set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
1623 * online CPUs. It'll be re-applied when any of the CPUs come up.
1625 set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
1628 * The pool->attach_mutex ensures %POOL_DISASSOCIATED remains
1629 * stable across this function. See the comments above the
1630 * flag definition for details.
1632 if (pool->flags & POOL_DISASSOCIATED)
1633 worker->flags |= WORKER_UNBOUND;
1635 list_add_tail(&worker->node, &pool->workers);
1637 mutex_unlock(&pool->attach_mutex);
1641 * worker_detach_from_pool() - detach a worker from its pool
1642 * @worker: worker which is attached to its pool
1643 * @pool: the pool @worker is attached to
1645 * Undo the attaching which had been done in worker_attach_to_pool(). The
1646 * caller worker shouldn't access to the pool after detached except it has
1647 * other reference to the pool.
1649 static void worker_detach_from_pool(struct worker *worker,
1650 struct worker_pool *pool)
1652 struct completion *detach_completion = NULL;
1654 mutex_lock(&pool->attach_mutex);
1655 list_del(&worker->node);
1656 if (list_empty(&pool->workers))
1657 detach_completion = pool->detach_completion;
1658 mutex_unlock(&pool->attach_mutex);
1660 /* clear leftover flags without pool->lock after it is detached */
1661 worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
1663 if (detach_completion)
1664 complete(detach_completion);
1668 * create_worker - create a new workqueue worker
1669 * @pool: pool the new worker will belong to
1671 * Create and start a new worker which is attached to @pool.
1674 * Might sleep. Does GFP_KERNEL allocations.
1677 * Pointer to the newly created worker.
1679 static struct worker *create_worker(struct worker_pool *pool)
1681 struct worker *worker = NULL;
1685 /* ID is needed to determine kthread name */
1686 id = ida_simple_get(&pool->worker_ida, 0, 0, GFP_KERNEL);
1690 worker = alloc_worker(pool->node);
1694 worker->pool = pool;
1698 snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
1699 pool->attrs->nice < 0 ? "H" : "");
1701 snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
1703 worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
1704 "kworker/%s", id_buf);
1705 if (IS_ERR(worker->task))
1708 set_user_nice(worker->task, pool->attrs->nice);
1710 /* prevent userland from meddling with cpumask of workqueue workers */
1711 worker->task->flags |= PF_NO_SETAFFINITY;
1713 /* successful, attach the worker to the pool */
1714 worker_attach_to_pool(worker, pool);
1716 /* start the newly created worker */
1717 spin_lock_irq(&pool->lock);
1718 worker->pool->nr_workers++;
1719 worker_enter_idle(worker);
1720 wake_up_process(worker->task);
1721 spin_unlock_irq(&pool->lock);
1727 ida_simple_remove(&pool->worker_ida, id);
1733 * destroy_worker - destroy a workqueue worker
1734 * @worker: worker to be destroyed
1736 * Destroy @worker and adjust @pool stats accordingly. The worker should
1740 * spin_lock_irq(pool->lock).
1742 static void destroy_worker(struct worker *worker)
1744 struct worker_pool *pool = worker->pool;
1746 lockdep_assert_held(&pool->lock);
1748 /* sanity check frenzy */
1749 if (WARN_ON(worker->current_work) ||
1750 WARN_ON(!list_empty(&worker->scheduled)) ||
1751 WARN_ON(!(worker->flags & WORKER_IDLE)))
1757 list_del_init(&worker->entry);
1758 worker->flags |= WORKER_DIE;
1759 wake_up_process(worker->task);
1762 static void idle_worker_timeout(unsigned long __pool)
1764 struct worker_pool *pool = (void *)__pool;
1766 spin_lock_irq(&pool->lock);
1768 while (too_many_workers(pool)) {
1769 struct worker *worker;
1770 unsigned long expires;
1772 /* idle_list is kept in LIFO order, check the last one */
1773 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1774 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1776 if (time_before(jiffies, expires)) {
1777 mod_timer(&pool->idle_timer, expires);
1781 destroy_worker(worker);
1784 spin_unlock_irq(&pool->lock);
1787 static void send_mayday(struct work_struct *work)
1789 struct pool_workqueue *pwq = get_work_pwq(work);
1790 struct workqueue_struct *wq = pwq->wq;
1792 lockdep_assert_held(&wq_mayday_lock);
1797 /* mayday mayday mayday */
1798 if (list_empty(&pwq->mayday_node)) {
1800 * If @pwq is for an unbound wq, its base ref may be put at
1801 * any time due to an attribute change. Pin @pwq until the
1802 * rescuer is done with it.
1805 list_add_tail(&pwq->mayday_node, &wq->maydays);
1806 wake_up_process(wq->rescuer->task);
1810 static void pool_mayday_timeout(unsigned long __pool)
1812 struct worker_pool *pool = (void *)__pool;
1813 struct work_struct *work;
1815 spin_lock_irq(&pool->lock);
1816 spin_lock(&wq_mayday_lock); /* for wq->maydays */
1818 if (need_to_create_worker(pool)) {
1820 * We've been trying to create a new worker but
1821 * haven't been successful. We might be hitting an
1822 * allocation deadlock. Send distress signals to
1825 list_for_each_entry(work, &pool->worklist, entry)
1829 spin_unlock(&wq_mayday_lock);
1830 spin_unlock_irq(&pool->lock);
1832 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1836 * maybe_create_worker - create a new worker if necessary
1837 * @pool: pool to create a new worker for
1839 * Create a new worker for @pool if necessary. @pool is guaranteed to
1840 * have at least one idle worker on return from this function. If
1841 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1842 * sent to all rescuers with works scheduled on @pool to resolve
1843 * possible allocation deadlock.
1845 * On return, need_to_create_worker() is guaranteed to be %false and
1846 * may_start_working() %true.
1849 * spin_lock_irq(pool->lock) which may be released and regrabbed
1850 * multiple times. Does GFP_KERNEL allocations. Called only from
1853 static void maybe_create_worker(struct worker_pool *pool)
1854 __releases(&pool->lock)
1855 __acquires(&pool->lock)
1858 spin_unlock_irq(&pool->lock);
1860 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1861 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1864 if (create_worker(pool) || !need_to_create_worker(pool))
1867 schedule_timeout_interruptible(CREATE_COOLDOWN);
1869 if (!need_to_create_worker(pool))
1873 del_timer_sync(&pool->mayday_timer);
1874 spin_lock_irq(&pool->lock);
1876 * This is necessary even after a new worker was just successfully
1877 * created as @pool->lock was dropped and the new worker might have
1878 * already become busy.
1880 if (need_to_create_worker(pool))
1885 * manage_workers - manage worker pool
1888 * Assume the manager role and manage the worker pool @worker belongs
1889 * to. At any given time, there can be only zero or one manager per
1890 * pool. The exclusion is handled automatically by this function.
1892 * The caller can safely start processing works on false return. On
1893 * true return, it's guaranteed that need_to_create_worker() is false
1894 * and may_start_working() is true.
1897 * spin_lock_irq(pool->lock) which may be released and regrabbed
1898 * multiple times. Does GFP_KERNEL allocations.
1901 * %false if the pool doesn't need management and the caller can safely
1902 * start processing works, %true if management function was performed and
1903 * the conditions that the caller verified before calling the function may
1904 * no longer be true.
1906 static bool manage_workers(struct worker *worker)
1908 struct worker_pool *pool = worker->pool;
1911 * Anyone who successfully grabs manager_arb wins the arbitration
1912 * and becomes the manager. mutex_trylock() on pool->manager_arb
1913 * failure while holding pool->lock reliably indicates that someone
1914 * else is managing the pool and the worker which failed trylock
1915 * can proceed to executing work items. This means that anyone
1916 * grabbing manager_arb is responsible for actually performing
1917 * manager duties. If manager_arb is grabbed and released without
1918 * actual management, the pool may stall indefinitely.
1920 if (!mutex_trylock(&pool->manager_arb))
1922 pool->manager = worker;
1924 maybe_create_worker(pool);
1926 pool->manager = NULL;
1927 mutex_unlock(&pool->manager_arb);
1932 * process_one_work - process single work
1934 * @work: work to process
1936 * Process @work. This function contains all the logics necessary to
1937 * process a single work including synchronization against and
1938 * interaction with other workers on the same cpu, queueing and
1939 * flushing. As long as context requirement is met, any worker can
1940 * call this function to process a work.
1943 * spin_lock_irq(pool->lock) which is released and regrabbed.
1945 static void process_one_work(struct worker *worker, struct work_struct *work)
1946 __releases(&pool->lock)
1947 __acquires(&pool->lock)
1949 struct pool_workqueue *pwq = get_work_pwq(work);
1950 struct worker_pool *pool = worker->pool;
1951 bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
1953 struct worker *collision;
1954 #ifdef CONFIG_LOCKDEP
1956 * It is permissible to free the struct work_struct from
1957 * inside the function that is called from it, this we need to
1958 * take into account for lockdep too. To avoid bogus "held
1959 * lock freed" warnings as well as problems when looking into
1960 * work->lockdep_map, make a copy and use that here.
1962 struct lockdep_map lockdep_map;
1964 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
1966 /* ensure we're on the correct CPU */
1967 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1968 raw_smp_processor_id() != pool->cpu);
1971 * A single work shouldn't be executed concurrently by
1972 * multiple workers on a single cpu. Check whether anyone is
1973 * already processing the work. If so, defer the work to the
1974 * currently executing one.
1976 collision = find_worker_executing_work(pool, work);
1977 if (unlikely(collision)) {
1978 move_linked_works(work, &collision->scheduled, NULL);
1982 /* claim and dequeue */
1983 debug_work_deactivate(work);
1984 hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
1985 worker->current_work = work;
1986 worker->current_func = work->func;
1987 worker->current_pwq = pwq;
1988 work_color = get_work_color(work);
1990 list_del_init(&work->entry);
1993 * CPU intensive works don't participate in concurrency management.
1994 * They're the scheduler's responsibility. This takes @worker out
1995 * of concurrency management and the next code block will chain
1996 * execution of the pending work items.
1998 if (unlikely(cpu_intensive))
1999 worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2002 * Wake up another worker if necessary. The condition is always
2003 * false for normal per-cpu workers since nr_running would always
2004 * be >= 1 at this point. This is used to chain execution of the
2005 * pending work items for WORKER_NOT_RUNNING workers such as the
2006 * UNBOUND and CPU_INTENSIVE ones.
2008 if (need_more_worker(pool))
2009 wake_up_worker(pool);
2012 * Record the last pool and clear PENDING which should be the last
2013 * update to @work. Also, do this inside @pool->lock so that
2014 * PENDING and queued state changes happen together while IRQ is
2017 set_work_pool_and_clear_pending(work, pool->id);
2019 spin_unlock_irq(&pool->lock);
2021 lock_map_acquire_read(&pwq->wq->lockdep_map);
2022 lock_map_acquire(&lockdep_map);
2023 trace_workqueue_execute_start(work);
2024 worker->current_func(work);
2026 * While we must be careful to not use "work" after this, the trace
2027 * point will only record its address.
2029 trace_workqueue_execute_end(work);
2030 lock_map_release(&lockdep_map);
2031 lock_map_release(&pwq->wq->lockdep_map);
2033 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2034 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2035 " last function: %pf\n",
2036 current->comm, preempt_count(), task_pid_nr(current),
2037 worker->current_func);
2038 debug_show_held_locks(current);
2043 * The following prevents a kworker from hogging CPU on !PREEMPT
2044 * kernels, where a requeueing work item waiting for something to
2045 * happen could deadlock with stop_machine as such work item could
2046 * indefinitely requeue itself while all other CPUs are trapped in
2047 * stop_machine. At the same time, report a quiescent RCU state so
2048 * the same condition doesn't freeze RCU.
2050 cond_resched_rcu_qs();
2052 spin_lock_irq(&pool->lock);
2054 /* clear cpu intensive status */
2055 if (unlikely(cpu_intensive))
2056 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2058 /* we're done with it, release */
2059 hash_del(&worker->hentry);
2060 worker->current_work = NULL;
2061 worker->current_func = NULL;
2062 worker->current_pwq = NULL;
2063 worker->desc_valid = false;
2064 pwq_dec_nr_in_flight(pwq, work_color);
2068 * process_scheduled_works - process scheduled works
2071 * Process all scheduled works. Please note that the scheduled list
2072 * may change while processing a work, so this function repeatedly
2073 * fetches a work from the top and executes it.
2076 * spin_lock_irq(pool->lock) which may be released and regrabbed
2079 static void process_scheduled_works(struct worker *worker)
2081 while (!list_empty(&worker->scheduled)) {
2082 struct work_struct *work = list_first_entry(&worker->scheduled,
2083 struct work_struct, entry);
2084 process_one_work(worker, work);
2089 * worker_thread - the worker thread function
2092 * The worker thread function. All workers belong to a worker_pool -
2093 * either a per-cpu one or dynamic unbound one. These workers process all
2094 * work items regardless of their specific target workqueue. The only
2095 * exception is work items which belong to workqueues with a rescuer which
2096 * will be explained in rescuer_thread().
2100 static int worker_thread(void *__worker)
2102 struct worker *worker = __worker;
2103 struct worker_pool *pool = worker->pool;
2105 /* tell the scheduler that this is a workqueue worker */
2106 worker->task->flags |= PF_WQ_WORKER;
2108 spin_lock_irq(&pool->lock);
2110 /* am I supposed to die? */
2111 if (unlikely(worker->flags & WORKER_DIE)) {
2112 spin_unlock_irq(&pool->lock);
2113 WARN_ON_ONCE(!list_empty(&worker->entry));
2114 worker->task->flags &= ~PF_WQ_WORKER;
2116 set_task_comm(worker->task, "kworker/dying");
2117 ida_simple_remove(&pool->worker_ida, worker->id);
2118 worker_detach_from_pool(worker, pool);
2123 worker_leave_idle(worker);
2125 /* no more worker necessary? */
2126 if (!need_more_worker(pool))
2129 /* do we need to manage? */
2130 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2134 * ->scheduled list can only be filled while a worker is
2135 * preparing to process a work or actually processing it.
2136 * Make sure nobody diddled with it while I was sleeping.
2138 WARN_ON_ONCE(!list_empty(&worker->scheduled));
2141 * Finish PREP stage. We're guaranteed to have at least one idle
2142 * worker or that someone else has already assumed the manager
2143 * role. This is where @worker starts participating in concurrency
2144 * management if applicable and concurrency management is restored
2145 * after being rebound. See rebind_workers() for details.
2147 worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2150 struct work_struct *work =
2151 list_first_entry(&pool->worklist,
2152 struct work_struct, entry);
2154 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2155 /* optimization path, not strictly necessary */
2156 process_one_work(worker, work);
2157 if (unlikely(!list_empty(&worker->scheduled)))
2158 process_scheduled_works(worker);
2160 move_linked_works(work, &worker->scheduled, NULL);
2161 process_scheduled_works(worker);
2163 } while (keep_working(pool));
2165 worker_set_flags(worker, WORKER_PREP);
2168 * pool->lock is held and there's no work to process and no need to
2169 * manage, sleep. Workers are woken up only while holding
2170 * pool->lock or from local cpu, so setting the current state
2171 * before releasing pool->lock is enough to prevent losing any
2174 worker_enter_idle(worker);
2175 __set_current_state(TASK_INTERRUPTIBLE);
2176 spin_unlock_irq(&pool->lock);
2182 * rescuer_thread - the rescuer thread function
2185 * Workqueue rescuer thread function. There's one rescuer for each
2186 * workqueue which has WQ_MEM_RECLAIM set.
2188 * Regular work processing on a pool may block trying to create a new
2189 * worker which uses GFP_KERNEL allocation which has slight chance of
2190 * developing into deadlock if some works currently on the same queue
2191 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2192 * the problem rescuer solves.
2194 * When such condition is possible, the pool summons rescuers of all
2195 * workqueues which have works queued on the pool and let them process
2196 * those works so that forward progress can be guaranteed.
2198 * This should happen rarely.
2202 static int rescuer_thread(void *__rescuer)
2204 struct worker *rescuer = __rescuer;
2205 struct workqueue_struct *wq = rescuer->rescue_wq;
2206 struct list_head *scheduled = &rescuer->scheduled;
2209 set_user_nice(current, RESCUER_NICE_LEVEL);
2212 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2213 * doesn't participate in concurrency management.
2215 rescuer->task->flags |= PF_WQ_WORKER;
2217 set_current_state(TASK_INTERRUPTIBLE);
2220 * By the time the rescuer is requested to stop, the workqueue
2221 * shouldn't have any work pending, but @wq->maydays may still have
2222 * pwq(s) queued. This can happen by non-rescuer workers consuming
2223 * all the work items before the rescuer got to them. Go through
2224 * @wq->maydays processing before acting on should_stop so that the
2225 * list is always empty on exit.
2227 should_stop = kthread_should_stop();
2229 /* see whether any pwq is asking for help */
2230 spin_lock_irq(&wq_mayday_lock);
2232 while (!list_empty(&wq->maydays)) {
2233 struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2234 struct pool_workqueue, mayday_node);
2235 struct worker_pool *pool = pwq->pool;
2236 struct work_struct *work, *n;
2238 __set_current_state(TASK_RUNNING);
2239 list_del_init(&pwq->mayday_node);
2241 spin_unlock_irq(&wq_mayday_lock);
2243 worker_attach_to_pool(rescuer, pool);
2245 spin_lock_irq(&pool->lock);
2246 rescuer->pool = pool;
2249 * Slurp in all works issued via this workqueue and
2252 WARN_ON_ONCE(!list_empty(scheduled));
2253 list_for_each_entry_safe(work, n, &pool->worklist, entry)
2254 if (get_work_pwq(work) == pwq)
2255 move_linked_works(work, scheduled, &n);
2257 if (!list_empty(scheduled)) {
2258 process_scheduled_works(rescuer);
2261 * The above execution of rescued work items could
2262 * have created more to rescue through
2263 * pwq_activate_first_delayed() or chained
2264 * queueing. Let's put @pwq back on mayday list so
2265 * that such back-to-back work items, which may be
2266 * being used to relieve memory pressure, don't
2267 * incur MAYDAY_INTERVAL delay inbetween.
2269 if (need_to_create_worker(pool)) {
2270 spin_lock(&wq_mayday_lock);
2272 list_move_tail(&pwq->mayday_node, &wq->maydays);
2273 spin_unlock(&wq_mayday_lock);
2278 * Put the reference grabbed by send_mayday(). @pool won't
2279 * go away while we're still attached to it.
2284 * Leave this pool. If need_more_worker() is %true, notify a
2285 * regular worker; otherwise, we end up with 0 concurrency
2286 * and stalling the execution.
2288 if (need_more_worker(pool))
2289 wake_up_worker(pool);
2291 rescuer->pool = NULL;
2292 spin_unlock_irq(&pool->lock);
2294 worker_detach_from_pool(rescuer, pool);
2296 spin_lock_irq(&wq_mayday_lock);
2299 spin_unlock_irq(&wq_mayday_lock);
2302 __set_current_state(TASK_RUNNING);
2303 rescuer->task->flags &= ~PF_WQ_WORKER;
2307 /* rescuers should never participate in concurrency management */
2308 WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2314 struct work_struct work;
2315 struct completion done;
2316 struct task_struct *task; /* purely informational */
2319 static void wq_barrier_func(struct work_struct *work)
2321 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2322 complete(&barr->done);
2326 * insert_wq_barrier - insert a barrier work
2327 * @pwq: pwq to insert barrier into
2328 * @barr: wq_barrier to insert
2329 * @target: target work to attach @barr to
2330 * @worker: worker currently executing @target, NULL if @target is not executing
2332 * @barr is linked to @target such that @barr is completed only after
2333 * @target finishes execution. Please note that the ordering
2334 * guarantee is observed only with respect to @target and on the local
2337 * Currently, a queued barrier can't be canceled. This is because
2338 * try_to_grab_pending() can't determine whether the work to be
2339 * grabbed is at the head of the queue and thus can't clear LINKED
2340 * flag of the previous work while there must be a valid next work
2341 * after a work with LINKED flag set.
2343 * Note that when @worker is non-NULL, @target may be modified
2344 * underneath us, so we can't reliably determine pwq from @target.
2347 * spin_lock_irq(pool->lock).
2349 static void insert_wq_barrier(struct pool_workqueue *pwq,
2350 struct wq_barrier *barr,
2351 struct work_struct *target, struct worker *worker)
2353 struct list_head *head;
2354 unsigned int linked = 0;
2357 * debugobject calls are safe here even with pool->lock locked
2358 * as we know for sure that this will not trigger any of the
2359 * checks and call back into the fixup functions where we
2362 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2363 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2364 init_completion(&barr->done);
2365 barr->task = current;
2368 * If @target is currently being executed, schedule the
2369 * barrier to the worker; otherwise, put it after @target.
2372 head = worker->scheduled.next;
2374 unsigned long *bits = work_data_bits(target);
2376 head = target->entry.next;
2377 /* there can already be other linked works, inherit and set */
2378 linked = *bits & WORK_STRUCT_LINKED;
2379 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2382 debug_work_activate(&barr->work);
2383 insert_work(pwq, &barr->work, head,
2384 work_color_to_flags(WORK_NO_COLOR) | linked);
2388 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
2389 * @wq: workqueue being flushed
2390 * @flush_color: new flush color, < 0 for no-op
2391 * @work_color: new work color, < 0 for no-op
2393 * Prepare pwqs for workqueue flushing.
2395 * If @flush_color is non-negative, flush_color on all pwqs should be
2396 * -1. If no pwq has in-flight commands at the specified color, all
2397 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
2398 * has in flight commands, its pwq->flush_color is set to
2399 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
2400 * wakeup logic is armed and %true is returned.
2402 * The caller should have initialized @wq->first_flusher prior to
2403 * calling this function with non-negative @flush_color. If
2404 * @flush_color is negative, no flush color update is done and %false
2407 * If @work_color is non-negative, all pwqs should have the same
2408 * work_color which is previous to @work_color and all will be
2409 * advanced to @work_color.
2412 * mutex_lock(wq->mutex).
2415 * %true if @flush_color >= 0 and there's something to flush. %false
2418 static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
2419 int flush_color, int work_color)
2422 struct pool_workqueue *pwq;
2424 if (flush_color >= 0) {
2425 WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2426 atomic_set(&wq->nr_pwqs_to_flush, 1);
2429 for_each_pwq(pwq, wq) {
2430 struct worker_pool *pool = pwq->pool;
2432 spin_lock_irq(&pool->lock);
2434 if (flush_color >= 0) {
2435 WARN_ON_ONCE(pwq->flush_color != -1);
2437 if (pwq->nr_in_flight[flush_color]) {
2438 pwq->flush_color = flush_color;
2439 atomic_inc(&wq->nr_pwqs_to_flush);
2444 if (work_color >= 0) {
2445 WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2446 pwq->work_color = work_color;
2449 spin_unlock_irq(&pool->lock);
2452 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
2453 complete(&wq->first_flusher->done);
2459 * flush_workqueue - ensure that any scheduled work has run to completion.
2460 * @wq: workqueue to flush
2462 * This function sleeps until all work items which were queued on entry
2463 * have finished execution, but it is not livelocked by new incoming ones.
2465 void flush_workqueue(struct workqueue_struct *wq)
2467 struct wq_flusher this_flusher = {
2468 .list = LIST_HEAD_INIT(this_flusher.list),
2470 .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
2474 lock_map_acquire(&wq->lockdep_map);
2475 lock_map_release(&wq->lockdep_map);
2477 mutex_lock(&wq->mutex);
2480 * Start-to-wait phase
2482 next_color = work_next_color(wq->work_color);
2484 if (next_color != wq->flush_color) {
2486 * Color space is not full. The current work_color
2487 * becomes our flush_color and work_color is advanced
2490 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
2491 this_flusher.flush_color = wq->work_color;
2492 wq->work_color = next_color;
2494 if (!wq->first_flusher) {
2495 /* no flush in progress, become the first flusher */
2496 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2498 wq->first_flusher = &this_flusher;
2500 if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
2502 /* nothing to flush, done */
2503 wq->flush_color = next_color;
2504 wq->first_flusher = NULL;
2509 WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
2510 list_add_tail(&this_flusher.list, &wq->flusher_queue);
2511 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2515 * Oops, color space is full, wait on overflow queue.
2516 * The next flush completion will assign us
2517 * flush_color and transfer to flusher_queue.
2519 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2522 mutex_unlock(&wq->mutex);
2524 wait_for_completion(&this_flusher.done);
2527 * Wake-up-and-cascade phase
2529 * First flushers are responsible for cascading flushes and
2530 * handling overflow. Non-first flushers can simply return.
2532 if (wq->first_flusher != &this_flusher)
2535 mutex_lock(&wq->mutex);
2537 /* we might have raced, check again with mutex held */
2538 if (wq->first_flusher != &this_flusher)
2541 wq->first_flusher = NULL;
2543 WARN_ON_ONCE(!list_empty(&this_flusher.list));
2544 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2547 struct wq_flusher *next, *tmp;
2549 /* complete all the flushers sharing the current flush color */
2550 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2551 if (next->flush_color != wq->flush_color)
2553 list_del_init(&next->list);
2554 complete(&next->done);
2557 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
2558 wq->flush_color != work_next_color(wq->work_color));
2560 /* this flush_color is finished, advance by one */
2561 wq->flush_color = work_next_color(wq->flush_color);
2563 /* one color has been freed, handle overflow queue */
2564 if (!list_empty(&wq->flusher_overflow)) {
2566 * Assign the same color to all overflowed
2567 * flushers, advance work_color and append to
2568 * flusher_queue. This is the start-to-wait
2569 * phase for these overflowed flushers.
2571 list_for_each_entry(tmp, &wq->flusher_overflow, list)
2572 tmp->flush_color = wq->work_color;
2574 wq->work_color = work_next_color(wq->work_color);
2576 list_splice_tail_init(&wq->flusher_overflow,
2577 &wq->flusher_queue);
2578 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2581 if (list_empty(&wq->flusher_queue)) {
2582 WARN_ON_ONCE(wq->flush_color != wq->work_color);
2587 * Need to flush more colors. Make the next flusher
2588 * the new first flusher and arm pwqs.
2590 WARN_ON_ONCE(wq->flush_color == wq->work_color);
2591 WARN_ON_ONCE(wq->flush_color != next->flush_color);
2593 list_del_init(&next->list);
2594 wq->first_flusher = next;
2596 if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
2600 * Meh... this color is already done, clear first
2601 * flusher and repeat cascading.
2603 wq->first_flusher = NULL;
2607 mutex_unlock(&wq->mutex);
2609 EXPORT_SYMBOL_GPL(flush_workqueue);
2612 * drain_workqueue - drain a workqueue
2613 * @wq: workqueue to drain
2615 * Wait until the workqueue becomes empty. While draining is in progress,
2616 * only chain queueing is allowed. IOW, only currently pending or running
2617 * work items on @wq can queue further work items on it. @wq is flushed
2618 * repeatedly until it becomes empty. The number of flushing is detemined
2619 * by the depth of chaining and should be relatively short. Whine if it
2622 void drain_workqueue(struct workqueue_struct *wq)
2624 unsigned int flush_cnt = 0;
2625 struct pool_workqueue *pwq;
2628 * __queue_work() needs to test whether there are drainers, is much
2629 * hotter than drain_workqueue() and already looks at @wq->flags.
2630 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
2632 mutex_lock(&wq->mutex);
2633 if (!wq->nr_drainers++)
2634 wq->flags |= __WQ_DRAINING;
2635 mutex_unlock(&wq->mutex);
2637 flush_workqueue(wq);
2639 mutex_lock(&wq->mutex);
2641 for_each_pwq(pwq, wq) {
2644 spin_lock_irq(&pwq->pool->lock);
2645 drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
2646 spin_unlock_irq(&pwq->pool->lock);
2651 if (++flush_cnt == 10 ||
2652 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2653 pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
2654 wq->name, flush_cnt);
2656 mutex_unlock(&wq->mutex);
2660 if (!--wq->nr_drainers)
2661 wq->flags &= ~__WQ_DRAINING;
2662 mutex_unlock(&wq->mutex);
2664 EXPORT_SYMBOL_GPL(drain_workqueue);
2666 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2668 struct worker *worker = NULL;
2669 struct worker_pool *pool;
2670 struct pool_workqueue *pwq;
2674 local_irq_disable();
2675 pool = get_work_pool(work);
2681 spin_lock(&pool->lock);
2682 /* see the comment in try_to_grab_pending() with the same code */
2683 pwq = get_work_pwq(work);
2685 if (unlikely(pwq->pool != pool))
2688 worker = find_worker_executing_work(pool, work);
2691 pwq = worker->current_pwq;
2694 insert_wq_barrier(pwq, barr, work, worker);
2695 spin_unlock_irq(&pool->lock);
2698 * If @max_active is 1 or rescuer is in use, flushing another work
2699 * item on the same workqueue may lead to deadlock. Make sure the
2700 * flusher is not running on the same workqueue by verifying write
2703 if (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)
2704 lock_map_acquire(&pwq->wq->lockdep_map);
2706 lock_map_acquire_read(&pwq->wq->lockdep_map);
2707 lock_map_release(&pwq->wq->lockdep_map);
2711 spin_unlock_irq(&pool->lock);
2716 * flush_work - wait for a work to finish executing the last queueing instance
2717 * @work: the work to flush
2719 * Wait until @work has finished execution. @work is guaranteed to be idle
2720 * on return if it hasn't been requeued since flush started.
2723 * %true if flush_work() waited for the work to finish execution,
2724 * %false if it was already idle.
2726 bool flush_work(struct work_struct *work)
2728 struct wq_barrier barr;
2730 lock_map_acquire(&work->lockdep_map);
2731 lock_map_release(&work->lockdep_map);
2733 if (start_flush_work(work, &barr)) {
2734 wait_for_completion(&barr.done);
2735 destroy_work_on_stack(&barr.work);
2741 EXPORT_SYMBOL_GPL(flush_work);
2745 struct work_struct *work;
2748 static int cwt_wakefn(wait_queue_t *wait, unsigned mode, int sync, void *key)
2750 struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
2752 if (cwait->work != key)
2754 return autoremove_wake_function(wait, mode, sync, key);
2757 static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2759 static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
2760 unsigned long flags;
2764 ret = try_to_grab_pending(work, is_dwork, &flags);
2766 * If someone else is already canceling, wait for it to
2767 * finish. flush_work() doesn't work for PREEMPT_NONE
2768 * because we may get scheduled between @work's completion
2769 * and the other canceling task resuming and clearing
2770 * CANCELING - flush_work() will return false immediately
2771 * as @work is no longer busy, try_to_grab_pending() will
2772 * return -ENOENT as @work is still being canceled and the
2773 * other canceling task won't be able to clear CANCELING as
2774 * we're hogging the CPU.
2776 * Let's wait for completion using a waitqueue. As this
2777 * may lead to the thundering herd problem, use a custom
2778 * wake function which matches @work along with exclusive
2781 if (unlikely(ret == -ENOENT)) {
2782 struct cwt_wait cwait;
2784 init_wait(&cwait.wait);
2785 cwait.wait.func = cwt_wakefn;
2788 prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
2789 TASK_UNINTERRUPTIBLE);
2790 if (work_is_canceling(work))
2792 finish_wait(&cancel_waitq, &cwait.wait);
2794 } while (unlikely(ret < 0));
2796 /* tell other tasks trying to grab @work to back off */
2797 mark_work_canceling(work);
2798 local_irq_restore(flags);
2801 clear_work_data(work);
2804 * Paired with prepare_to_wait() above so that either
2805 * waitqueue_active() is visible here or !work_is_canceling() is
2809 if (waitqueue_active(&cancel_waitq))
2810 __wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
2816 * cancel_work_sync - cancel a work and wait for it to finish
2817 * @work: the work to cancel
2819 * Cancel @work and wait for its execution to finish. This function
2820 * can be used even if the work re-queues itself or migrates to
2821 * another workqueue. On return from this function, @work is
2822 * guaranteed to be not pending or executing on any CPU.
2824 * cancel_work_sync(&delayed_work->work) must not be used for
2825 * delayed_work's. Use cancel_delayed_work_sync() instead.
2827 * The caller must ensure that the workqueue on which @work was last
2828 * queued can't be destroyed before this function returns.
2831 * %true if @work was pending, %false otherwise.
2833 bool cancel_work_sync(struct work_struct *work)
2835 return __cancel_work_timer(work, false);
2837 EXPORT_SYMBOL_GPL(cancel_work_sync);
2840 * flush_delayed_work - wait for a dwork to finish executing the last queueing
2841 * @dwork: the delayed work to flush
2843 * Delayed timer is cancelled and the pending work is queued for
2844 * immediate execution. Like flush_work(), this function only
2845 * considers the last queueing instance of @dwork.
2848 * %true if flush_work() waited for the work to finish execution,
2849 * %false if it was already idle.
2851 bool flush_delayed_work(struct delayed_work *dwork)
2853 local_irq_disable();
2854 if (del_timer_sync(&dwork->timer))
2855 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
2857 return flush_work(&dwork->work);
2859 EXPORT_SYMBOL(flush_delayed_work);
2862 * cancel_delayed_work - cancel a delayed work
2863 * @dwork: delayed_work to cancel
2865 * Kill off a pending delayed_work.
2867 * Return: %true if @dwork was pending and canceled; %false if it wasn't
2871 * The work callback function may still be running on return, unless
2872 * it returns %true and the work doesn't re-arm itself. Explicitly flush or
2873 * use cancel_delayed_work_sync() to wait on it.
2875 * This function is safe to call from any context including IRQ handler.
2877 bool cancel_delayed_work(struct delayed_work *dwork)
2879 unsigned long flags;
2883 ret = try_to_grab_pending(&dwork->work, true, &flags);
2884 } while (unlikely(ret == -EAGAIN));
2886 if (unlikely(ret < 0))
2889 set_work_pool_and_clear_pending(&dwork->work,
2890 get_work_pool_id(&dwork->work));
2891 local_irq_restore(flags);
2894 EXPORT_SYMBOL(cancel_delayed_work);
2897 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2898 * @dwork: the delayed work cancel
2900 * This is cancel_work_sync() for delayed works.
2903 * %true if @dwork was pending, %false otherwise.
2905 bool cancel_delayed_work_sync(struct delayed_work *dwork)
2907 return __cancel_work_timer(&dwork->work, true);
2909 EXPORT_SYMBOL(cancel_delayed_work_sync);
2912 * schedule_on_each_cpu - execute a function synchronously on each online CPU
2913 * @func: the function to call
2915 * schedule_on_each_cpu() executes @func on each online CPU using the
2916 * system workqueue and blocks until all CPUs have completed.
2917 * schedule_on_each_cpu() is very slow.
2920 * 0 on success, -errno on failure.
2922 int schedule_on_each_cpu(work_func_t func)
2925 struct work_struct __percpu *works;
2927 works = alloc_percpu(struct work_struct);
2933 for_each_online_cpu(cpu) {
2934 struct work_struct *work = per_cpu_ptr(works, cpu);
2936 INIT_WORK(work, func);
2937 schedule_work_on(cpu, work);
2940 for_each_online_cpu(cpu)
2941 flush_work(per_cpu_ptr(works, cpu));
2949 * flush_scheduled_work - ensure that any scheduled work has run to completion.
2951 * Forces execution of the kernel-global workqueue and blocks until its
2954 * Think twice before calling this function! It's very easy to get into
2955 * trouble if you don't take great care. Either of the following situations
2956 * will lead to deadlock:
2958 * One of the work items currently on the workqueue needs to acquire
2959 * a lock held by your code or its caller.
2961 * Your code is running in the context of a work routine.
2963 * They will be detected by lockdep when they occur, but the first might not
2964 * occur very often. It depends on what work items are on the workqueue and
2965 * what locks they need, which you have no control over.
2967 * In most situations flushing the entire workqueue is overkill; you merely
2968 * need to know that a particular work item isn't queued and isn't running.
2969 * In such cases you should use cancel_delayed_work_sync() or
2970 * cancel_work_sync() instead.
2972 void flush_scheduled_work(void)
2974 flush_workqueue(system_wq);
2976 EXPORT_SYMBOL(flush_scheduled_work);
2979 * execute_in_process_context - reliably execute the routine with user context
2980 * @fn: the function to execute
2981 * @ew: guaranteed storage for the execute work structure (must
2982 * be available when the work executes)
2984 * Executes the function immediately if process context is available,
2985 * otherwise schedules the function for delayed execution.
2987 * Return: 0 - function was executed
2988 * 1 - function was scheduled for execution
2990 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
2992 if (!in_interrupt()) {
2997 INIT_WORK(&ew->work, fn);
2998 schedule_work(&ew->work);
3002 EXPORT_SYMBOL_GPL(execute_in_process_context);
3006 * Workqueues with WQ_SYSFS flag set is visible to userland via
3007 * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
3008 * following attributes.
3010 * per_cpu RO bool : whether the workqueue is per-cpu or unbound
3011 * max_active RW int : maximum number of in-flight work items
3013 * Unbound workqueues have the following extra attributes.
3015 * id RO int : the associated pool ID
3016 * nice RW int : nice value of the workers
3017 * cpumask RW mask : bitmask of allowed CPUs for the workers
3020 struct workqueue_struct *wq;
3024 static struct workqueue_struct *dev_to_wq(struct device *dev)
3026 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
3031 static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
3034 struct workqueue_struct *wq = dev_to_wq(dev);
3036 return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
3038 static DEVICE_ATTR_RO(per_cpu);
3040 static ssize_t max_active_show(struct device *dev,
3041 struct device_attribute *attr, char *buf)
3043 struct workqueue_struct *wq = dev_to_wq(dev);
3045 return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
3048 static ssize_t max_active_store(struct device *dev,
3049 struct device_attribute *attr, const char *buf,
3052 struct workqueue_struct *wq = dev_to_wq(dev);
3055 if (sscanf(buf, "%d", &val) != 1 || val <= 0)
3058 workqueue_set_max_active(wq, val);
3061 static DEVICE_ATTR_RW(max_active);
3063 static struct attribute *wq_sysfs_attrs[] = {
3064 &dev_attr_per_cpu.attr,
3065 &dev_attr_max_active.attr,
3068 ATTRIBUTE_GROUPS(wq_sysfs);
3070 static ssize_t wq_pool_ids_show(struct device *dev,
3071 struct device_attribute *attr, char *buf)
3073 struct workqueue_struct *wq = dev_to_wq(dev);
3074 const char *delim = "";
3075 int node, written = 0;
3077 rcu_read_lock_sched();
3078 for_each_node(node) {
3079 written += scnprintf(buf + written, PAGE_SIZE - written,
3080 "%s%d:%d", delim, node,
3081 unbound_pwq_by_node(wq, node)->pool->id);
3084 written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
3085 rcu_read_unlock_sched();
3090 static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
3093 struct workqueue_struct *wq = dev_to_wq(dev);
3096 mutex_lock(&wq->mutex);
3097 written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
3098 mutex_unlock(&wq->mutex);
3103 /* prepare workqueue_attrs for sysfs store operations */
3104 static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
3106 struct workqueue_attrs *attrs;
3108 attrs = alloc_workqueue_attrs(GFP_KERNEL);
3112 mutex_lock(&wq->mutex);
3113 copy_workqueue_attrs(attrs, wq->unbound_attrs);
3114 mutex_unlock(&wq->mutex);
3118 static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
3119 const char *buf, size_t count)
3121 struct workqueue_struct *wq = dev_to_wq(dev);
3122 struct workqueue_attrs *attrs;
3125 attrs = wq_sysfs_prep_attrs(wq);
3129 if (sscanf(buf, "%d", &attrs->nice) == 1 &&
3130 attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
3131 ret = apply_workqueue_attrs(wq, attrs);
3135 free_workqueue_attrs(attrs);
3136 return ret ?: count;
3139 static ssize_t wq_cpumask_show(struct device *dev,
3140 struct device_attribute *attr, char *buf)
3142 struct workqueue_struct *wq = dev_to_wq(dev);
3145 mutex_lock(&wq->mutex);
3146 written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
3147 cpumask_pr_args(wq->unbound_attrs->cpumask));
3148 mutex_unlock(&wq->mutex);
3152 static ssize_t wq_cpumask_store(struct device *dev,
3153 struct device_attribute *attr,
3154 const char *buf, size_t count)
3156 struct workqueue_struct *wq = dev_to_wq(dev);
3157 struct workqueue_attrs *attrs;
3160 attrs = wq_sysfs_prep_attrs(wq);
3164 ret = cpumask_parse(buf, attrs->cpumask);
3166 ret = apply_workqueue_attrs(wq, attrs);
3168 free_workqueue_attrs(attrs);
3169 return ret ?: count;
3172 static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
3175 struct workqueue_struct *wq = dev_to_wq(dev);
3178 mutex_lock(&wq->mutex);
3179 written = scnprintf(buf, PAGE_SIZE, "%d\n",
3180 !wq->unbound_attrs->no_numa);
3181 mutex_unlock(&wq->mutex);
3186 static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
3187 const char *buf, size_t count)
3189 struct workqueue_struct *wq = dev_to_wq(dev);
3190 struct workqueue_attrs *attrs;
3193 attrs = wq_sysfs_prep_attrs(wq);
3198 if (sscanf(buf, "%d", &v) == 1) {
3199 attrs->no_numa = !v;
3200 ret = apply_workqueue_attrs(wq, attrs);
3203 free_workqueue_attrs(attrs);
3204 return ret ?: count;
3207 static struct device_attribute wq_sysfs_unbound_attrs[] = {
3208 __ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
3209 __ATTR(nice, 0644, wq_nice_show, wq_nice_store),
3210 __ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
3211 __ATTR(numa, 0644, wq_numa_show, wq_numa_store),
3215 static struct bus_type wq_subsys = {
3216 .name = "workqueue",
3217 .dev_groups = wq_sysfs_groups,
3220 static int __init wq_sysfs_init(void)
3222 return subsys_virtual_register(&wq_subsys, NULL);
3224 core_initcall(wq_sysfs_init);
3226 static void wq_device_release(struct device *dev)
3228 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
3234 * workqueue_sysfs_register - make a workqueue visible in sysfs
3235 * @wq: the workqueue to register
3237 * Expose @wq in sysfs under /sys/bus/workqueue/devices.
3238 * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
3239 * which is the preferred method.
3241 * Workqueue user should use this function directly iff it wants to apply
3242 * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
3243 * apply_workqueue_attrs() may race against userland updating the
3246 * Return: 0 on success, -errno on failure.
3248 int workqueue_sysfs_register(struct workqueue_struct *wq)
3250 struct wq_device *wq_dev;
3254 * Adjusting max_active or creating new pwqs by applyting
3255 * attributes breaks ordering guarantee. Disallow exposing ordered
3258 if (WARN_ON(wq->flags & __WQ_ORDERED))
3261 wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
3266 wq_dev->dev.bus = &wq_subsys;
3267 wq_dev->dev.init_name = wq->name;
3268 wq_dev->dev.release = wq_device_release;
3271 * unbound_attrs are created separately. Suppress uevent until
3272 * everything is ready.
3274 dev_set_uevent_suppress(&wq_dev->dev, true);
3276 ret = device_register(&wq_dev->dev);
3283 if (wq->flags & WQ_UNBOUND) {
3284 struct device_attribute *attr;
3286 for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
3287 ret = device_create_file(&wq_dev->dev, attr);
3289 device_unregister(&wq_dev->dev);
3296 dev_set_uevent_suppress(&wq_dev->dev, false);
3297 kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
3302 * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
3303 * @wq: the workqueue to unregister
3305 * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
3307 static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
3309 struct wq_device *wq_dev = wq->wq_dev;
3315 device_unregister(&wq_dev->dev);
3317 #else /* CONFIG_SYSFS */
3318 static void workqueue_sysfs_unregister(struct workqueue_struct *wq) { }
3319 #endif /* CONFIG_SYSFS */
3322 * free_workqueue_attrs - free a workqueue_attrs
3323 * @attrs: workqueue_attrs to free
3325 * Undo alloc_workqueue_attrs().
3327 void free_workqueue_attrs(struct workqueue_attrs *attrs)
3330 free_cpumask_var(attrs->cpumask);
3336 * alloc_workqueue_attrs - allocate a workqueue_attrs
3337 * @gfp_mask: allocation mask to use
3339 * Allocate a new workqueue_attrs, initialize with default settings and
3342 * Return: The allocated new workqueue_attr on success. %NULL on failure.
3344 struct workqueue_attrs *alloc_workqueue_attrs(gfp_t gfp_mask)
3346 struct workqueue_attrs *attrs;
3348 attrs = kzalloc(sizeof(*attrs), gfp_mask);
3351 if (!alloc_cpumask_var(&attrs->cpumask, gfp_mask))
3354 cpumask_copy(attrs->cpumask, cpu_possible_mask);
3357 free_workqueue_attrs(attrs);
3361 static void copy_workqueue_attrs(struct workqueue_attrs *to,
3362 const struct workqueue_attrs *from)
3364 to->nice = from->nice;
3365 cpumask_copy(to->cpumask, from->cpumask);
3367 * Unlike hash and equality test, this function doesn't ignore
3368 * ->no_numa as it is used for both pool and wq attrs. Instead,
3369 * get_unbound_pool() explicitly clears ->no_numa after copying.
3371 to->no_numa = from->no_numa;
3374 /* hash value of the content of @attr */
3375 static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
3379 hash = jhash_1word(attrs->nice, hash);
3380 hash = jhash(cpumask_bits(attrs->cpumask),
3381 BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
3385 /* content equality test */
3386 static bool wqattrs_equal(const struct workqueue_attrs *a,
3387 const struct workqueue_attrs *b)
3389 if (a->nice != b->nice)
3391 if (!cpumask_equal(a->cpumask, b->cpumask))
3397 * init_worker_pool - initialize a newly zalloc'd worker_pool
3398 * @pool: worker_pool to initialize
3400 * Initiailize a newly zalloc'd @pool. It also allocates @pool->attrs.
3402 * Return: 0 on success, -errno on failure. Even on failure, all fields
3403 * inside @pool proper are initialized and put_unbound_pool() can be called
3404 * on @pool safely to release it.
3406 static int init_worker_pool(struct worker_pool *pool)
3408 spin_lock_init(&pool->lock);
3411 pool->node = NUMA_NO_NODE;
3412 pool->flags |= POOL_DISASSOCIATED;
3413 INIT_LIST_HEAD(&pool->worklist);
3414 INIT_LIST_HEAD(&pool->idle_list);
3415 hash_init(pool->busy_hash);
3417 init_timer_deferrable(&pool->idle_timer);
3418 pool->idle_timer.function = idle_worker_timeout;
3419 pool->idle_timer.data = (unsigned long)pool;
3421 setup_timer(&pool->mayday_timer, pool_mayday_timeout,
3422 (unsigned long)pool);
3424 mutex_init(&pool->manager_arb);
3425 mutex_init(&pool->attach_mutex);
3426 INIT_LIST_HEAD(&pool->workers);
3428 ida_init(&pool->worker_ida);
3429 INIT_HLIST_NODE(&pool->hash_node);
3432 /* shouldn't fail above this point */
3433 pool->attrs = alloc_workqueue_attrs(GFP_KERNEL);
3439 static void rcu_free_wq(struct rcu_head *rcu)
3441 struct workqueue_struct *wq =
3442 container_of(rcu, struct workqueue_struct, rcu);
3444 if (!(wq->flags & WQ_UNBOUND))
3445 free_percpu(wq->cpu_pwqs);
3447 free_workqueue_attrs(wq->unbound_attrs);
3453 static void rcu_free_pool(struct rcu_head *rcu)
3455 struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
3457 ida_destroy(&pool->worker_ida);
3458 free_workqueue_attrs(pool->attrs);
3463 * put_unbound_pool - put a worker_pool
3464 * @pool: worker_pool to put
3466 * Put @pool. If its refcnt reaches zero, it gets destroyed in sched-RCU
3467 * safe manner. get_unbound_pool() calls this function on its failure path
3468 * and this function should be able to release pools which went through,
3469 * successfully or not, init_worker_pool().
3471 * Should be called with wq_pool_mutex held.
3473 static void put_unbound_pool(struct worker_pool *pool)
3475 DECLARE_COMPLETION_ONSTACK(detach_completion);
3476 struct worker *worker;
3478 lockdep_assert_held(&wq_pool_mutex);
3484 if (WARN_ON(!(pool->cpu < 0)) ||
3485 WARN_ON(!list_empty(&pool->worklist)))
3488 /* release id and unhash */
3490 idr_remove(&worker_pool_idr, pool->id);
3491 hash_del(&pool->hash_node);
3494 * Become the manager and destroy all workers. Grabbing
3495 * manager_arb prevents @pool's workers from blocking on
3498 mutex_lock(&pool->manager_arb);
3500 spin_lock_irq(&pool->lock);
3501 while ((worker = first_idle_worker(pool)))
3502 destroy_worker(worker);
3503 WARN_ON(pool->nr_workers || pool->nr_idle);
3504 spin_unlock_irq(&pool->lock);
3506 mutex_lock(&pool->attach_mutex);
3507 if (!list_empty(&pool->workers))
3508 pool->detach_completion = &detach_completion;
3509 mutex_unlock(&pool->attach_mutex);
3511 if (pool->detach_completion)
3512 wait_for_completion(pool->detach_completion);
3514 mutex_unlock(&pool->manager_arb);
3516 /* shut down the timers */
3517 del_timer_sync(&pool->idle_timer);
3518 del_timer_sync(&pool->mayday_timer);
3520 /* sched-RCU protected to allow dereferences from get_work_pool() */
3521 call_rcu_sched(&pool->rcu, rcu_free_pool);
3525 * get_unbound_pool - get a worker_pool with the specified attributes
3526 * @attrs: the attributes of the worker_pool to get
3528 * Obtain a worker_pool which has the same attributes as @attrs, bump the
3529 * reference count and return it. If there already is a matching
3530 * worker_pool, it will be used; otherwise, this function attempts to
3533 * Should be called with wq_pool_mutex held.
3535 * Return: On success, a worker_pool with the same attributes as @attrs.
3536 * On failure, %NULL.
3538 static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
3540 u32 hash = wqattrs_hash(attrs);
3541 struct worker_pool *pool;
3544 lockdep_assert_held(&wq_pool_mutex);
3546 /* do we already have a matching pool? */
3547 hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
3548 if (wqattrs_equal(pool->attrs, attrs)) {
3554 /* nope, create a new one */
3555 pool = kzalloc(sizeof(*pool), GFP_KERNEL);
3556 if (!pool || init_worker_pool(pool) < 0)
3559 lockdep_set_subclass(&pool->lock, 1); /* see put_pwq() */
3560 copy_workqueue_attrs(pool->attrs, attrs);
3563 * no_numa isn't a worker_pool attribute, always clear it. See
3564 * 'struct workqueue_attrs' comments for detail.
3566 pool->attrs->no_numa = false;
3568 /* if cpumask is contained inside a NUMA node, we belong to that node */
3569 if (wq_numa_enabled) {
3570 for_each_node(node) {
3571 if (cpumask_subset(pool->attrs->cpumask,
3572 wq_numa_possible_cpumask[node])) {
3579 if (worker_pool_assign_id(pool) < 0)
3582 /* create and start the initial worker */
3583 if (!create_worker(pool))
3587 hash_add(unbound_pool_hash, &pool->hash_node, hash);
3592 put_unbound_pool(pool);
3596 static void rcu_free_pwq(struct rcu_head *rcu)
3598 kmem_cache_free(pwq_cache,
3599 container_of(rcu, struct pool_workqueue, rcu));
3603 * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
3604 * and needs to be destroyed.
3606 static void pwq_unbound_release_workfn(struct work_struct *work)
3608 struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
3609 unbound_release_work);
3610 struct workqueue_struct *wq = pwq->wq;
3611 struct worker_pool *pool = pwq->pool;
3614 if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
3617 mutex_lock(&wq->mutex);
3618 list_del_rcu(&pwq->pwqs_node);
3619 is_last = list_empty(&wq->pwqs);
3620 mutex_unlock(&wq->mutex);
3622 mutex_lock(&wq_pool_mutex);
3623 put_unbound_pool(pool);
3624 mutex_unlock(&wq_pool_mutex);
3626 call_rcu_sched(&pwq->rcu, rcu_free_pwq);
3629 * If we're the last pwq going away, @wq is already dead and no one
3630 * is gonna access it anymore. Schedule RCU free.
3633 call_rcu_sched(&wq->rcu, rcu_free_wq);
3637 * pwq_adjust_max_active - update a pwq's max_active to the current setting
3638 * @pwq: target pool_workqueue
3640 * If @pwq isn't freezing, set @pwq->max_active to the associated
3641 * workqueue's saved_max_active and activate delayed work items
3642 * accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
3644 static void pwq_adjust_max_active(struct pool_workqueue *pwq)
3646 struct workqueue_struct *wq = pwq->wq;
3647 bool freezable = wq->flags & WQ_FREEZABLE;
3649 /* for @wq->saved_max_active */
3650 lockdep_assert_held(&wq->mutex);
3652 /* fast exit for non-freezable wqs */
3653 if (!freezable && pwq->max_active == wq->saved_max_active)
3656 spin_lock_irq(&pwq->pool->lock);
3659 * During [un]freezing, the caller is responsible for ensuring that
3660 * this function is called at least once after @workqueue_freezing
3661 * is updated and visible.
3663 if (!freezable || !workqueue_freezing) {
3664 pwq->max_active = wq->saved_max_active;
3666 while (!list_empty(&pwq->delayed_works) &&
3667 pwq->nr_active < pwq->max_active)
3668 pwq_activate_first_delayed(pwq);
3671 * Need to kick a worker after thawed or an unbound wq's
3672 * max_active is bumped. It's a slow path. Do it always.
3674 wake_up_worker(pwq->pool);
3676 pwq->max_active = 0;
3679 spin_unlock_irq(&pwq->pool->lock);
3682 /* initialize newly alloced @pwq which is associated with @wq and @pool */
3683 static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
3684 struct worker_pool *pool)
3686 BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3688 memset(pwq, 0, sizeof(*pwq));
3692 pwq->flush_color = -1;
3694 INIT_LIST_HEAD(&pwq->delayed_works);
3695 INIT_LIST_HEAD(&pwq->pwqs_node);
3696 INIT_LIST_HEAD(&pwq->mayday_node);
3697 INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
3700 /* sync @pwq with the current state of its associated wq and link it */
3701 static void link_pwq(struct pool_workqueue *pwq)
3703 struct workqueue_struct *wq = pwq->wq;
3705 lockdep_assert_held(&wq->mutex);
3707 /* may be called multiple times, ignore if already linked */
3708 if (!list_empty(&pwq->pwqs_node))
3711 /* set the matching work_color */
3712 pwq->work_color = wq->work_color;
3714 /* sync max_active to the current setting */
3715 pwq_adjust_max_active(pwq);
3718 list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
3721 /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
3722 static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
3723 const struct workqueue_attrs *attrs)
3725 struct worker_pool *pool;
3726 struct pool_workqueue *pwq;
3728 lockdep_assert_held(&wq_pool_mutex);
3730 pool = get_unbound_pool(attrs);
3734 pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
3736 put_unbound_pool(pool);
3740 init_pwq(pwq, wq, pool);
3744 /* undo alloc_unbound_pwq(), used only in the error path */
3745 static void free_unbound_pwq(struct pool_workqueue *pwq)
3747 lockdep_assert_held(&wq_pool_mutex);
3750 put_unbound_pool(pwq->pool);
3751 kmem_cache_free(pwq_cache, pwq);
3756 * wq_calc_node_mask - calculate a wq_attrs' cpumask for the specified node
3757 * @attrs: the wq_attrs of interest
3758 * @node: the target NUMA node
3759 * @cpu_going_down: if >= 0, the CPU to consider as offline
3760 * @cpumask: outarg, the resulting cpumask
3762 * Calculate the cpumask a workqueue with @attrs should use on @node. If
3763 * @cpu_going_down is >= 0, that cpu is considered offline during
3764 * calculation. The result is stored in @cpumask.
3766 * If NUMA affinity is not enabled, @attrs->cpumask is always used. If
3767 * enabled and @node has online CPUs requested by @attrs, the returned
3768 * cpumask is the intersection of the possible CPUs of @node and
3771 * The caller is responsible for ensuring that the cpumask of @node stays
3774 * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
3777 static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
3778 int cpu_going_down, cpumask_t *cpumask)
3780 if (!wq_numa_enabled || attrs->no_numa)
3783 /* does @node have any online CPUs @attrs wants? */
3784 cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
3785 if (cpu_going_down >= 0)
3786 cpumask_clear_cpu(cpu_going_down, cpumask);
3788 if (cpumask_empty(cpumask))
3791 /* yeap, return possible CPUs in @node that @attrs wants */
3792 cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
3793 return !cpumask_equal(cpumask, attrs->cpumask);
3796 cpumask_copy(cpumask, attrs->cpumask);
3800 /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
3801 static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
3803 struct pool_workqueue *pwq)
3805 struct pool_workqueue *old_pwq;
3807 lockdep_assert_held(&wq->mutex);
3809 /* link_pwq() can handle duplicate calls */
3812 old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
3813 rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
3818 * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
3819 * @wq: the target workqueue
3820 * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
3822 * Apply @attrs to an unbound workqueue @wq. Unless disabled, on NUMA
3823 * machines, this function maps a separate pwq to each NUMA node with
3824 * possibles CPUs in @attrs->cpumask so that work items are affine to the
3825 * NUMA node it was issued on. Older pwqs are released as in-flight work
3826 * items finish. Note that a work item which repeatedly requeues itself
3827 * back-to-back will stay on its current pwq.
3829 * Performs GFP_KERNEL allocations.
3831 * Return: 0 on success and -errno on failure.
3833 int apply_workqueue_attrs(struct workqueue_struct *wq,
3834 const struct workqueue_attrs *attrs)
3836 struct workqueue_attrs *new_attrs, *tmp_attrs;
3837 struct pool_workqueue **pwq_tbl, *dfl_pwq;
3840 /* only unbound workqueues can change attributes */
3841 if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
3844 /* creating multiple pwqs breaks ordering guarantee */
3845 if (WARN_ON((wq->flags & __WQ_ORDERED) && !list_empty(&wq->pwqs)))
3848 pwq_tbl = kzalloc(nr_node_ids * sizeof(pwq_tbl[0]), GFP_KERNEL);
3849 new_attrs = alloc_workqueue_attrs(GFP_KERNEL);
3850 tmp_attrs = alloc_workqueue_attrs(GFP_KERNEL);
3851 if (!pwq_tbl || !new_attrs || !tmp_attrs)
3854 /* make a copy of @attrs and sanitize it */
3855 copy_workqueue_attrs(new_attrs, attrs);
3856 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
3859 * We may create multiple pwqs with differing cpumasks. Make a
3860 * copy of @new_attrs which will be modified and used to obtain
3863 copy_workqueue_attrs(tmp_attrs, new_attrs);
3866 * CPUs should stay stable across pwq creations and installations.
3867 * Pin CPUs, determine the target cpumask for each node and create
3872 mutex_lock(&wq_pool_mutex);
3875 * If something goes wrong during CPU up/down, we'll fall back to
3876 * the default pwq covering whole @attrs->cpumask. Always create
3877 * it even if we don't use it immediately.
3879 dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
3883 for_each_node(node) {
3884 if (wq_calc_node_cpumask(attrs, node, -1, tmp_attrs->cpumask)) {
3885 pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
3890 pwq_tbl[node] = dfl_pwq;
3894 mutex_unlock(&wq_pool_mutex);
3896 /* all pwqs have been created successfully, let's install'em */
3897 mutex_lock(&wq->mutex);
3899 copy_workqueue_attrs(wq->unbound_attrs, new_attrs);
3901 /* save the previous pwq and install the new one */
3903 pwq_tbl[node] = numa_pwq_tbl_install(wq, node, pwq_tbl[node]);
3905 /* @dfl_pwq might not have been used, ensure it's linked */
3907 swap(wq->dfl_pwq, dfl_pwq);
3909 mutex_unlock(&wq->mutex);
3911 /* put the old pwqs */
3913 put_pwq_unlocked(pwq_tbl[node]);
3914 put_pwq_unlocked(dfl_pwq);
3920 free_workqueue_attrs(tmp_attrs);
3921 free_workqueue_attrs(new_attrs);
3926 free_unbound_pwq(dfl_pwq);
3928 if (pwq_tbl && pwq_tbl[node] != dfl_pwq)
3929 free_unbound_pwq(pwq_tbl[node]);
3930 mutex_unlock(&wq_pool_mutex);
3938 * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
3939 * @wq: the target workqueue
3940 * @cpu: the CPU coming up or going down
3941 * @online: whether @cpu is coming up or going down
3943 * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
3944 * %CPU_DOWN_FAILED. @cpu is being hot[un]plugged, update NUMA affinity of
3947 * If NUMA affinity can't be adjusted due to memory allocation failure, it
3948 * falls back to @wq->dfl_pwq which may not be optimal but is always
3951 * Note that when the last allowed CPU of a NUMA node goes offline for a
3952 * workqueue with a cpumask spanning multiple nodes, the workers which were
3953 * already executing the work items for the workqueue will lose their CPU
3954 * affinity and may execute on any CPU. This is similar to how per-cpu
3955 * workqueues behave on CPU_DOWN. If a workqueue user wants strict
3956 * affinity, it's the user's responsibility to flush the work item from
3959 static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
3962 int node = cpu_to_node(cpu);
3963 int cpu_off = online ? -1 : cpu;
3964 struct pool_workqueue *old_pwq = NULL, *pwq;
3965 struct workqueue_attrs *target_attrs;
3968 lockdep_assert_held(&wq_pool_mutex);
3970 if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND))
3974 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
3975 * Let's use a preallocated one. The following buf is protected by
3976 * CPU hotplug exclusion.
3978 target_attrs = wq_update_unbound_numa_attrs_buf;
3979 cpumask = target_attrs->cpumask;
3981 mutex_lock(&wq->mutex);
3982 if (wq->unbound_attrs->no_numa)
3985 copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
3986 pwq = unbound_pwq_by_node(wq, node);
3989 * Let's determine what needs to be done. If the target cpumask is
3990 * different from wq's, we need to compare it to @pwq's and create
3991 * a new one if they don't match. If the target cpumask equals
3992 * wq's, the default pwq should be used.
3994 if (wq_calc_node_cpumask(wq->unbound_attrs, node, cpu_off, cpumask)) {
3995 if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
4001 mutex_unlock(&wq->mutex);
4003 /* create a new pwq */
4004 pwq = alloc_unbound_pwq(wq, target_attrs);
4006 pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
4008 mutex_lock(&wq->mutex);
4013 * Install the new pwq. As this function is called only from CPU
4014 * hotplug callbacks and applying a new attrs is wrapped with
4015 * get/put_online_cpus(), @wq->unbound_attrs couldn't have changed
4018 mutex_lock(&wq->mutex);
4019 old_pwq = numa_pwq_tbl_install(wq, node, pwq);
4023 spin_lock_irq(&wq->dfl_pwq->pool->lock);
4024 get_pwq(wq->dfl_pwq);
4025 spin_unlock_irq(&wq->dfl_pwq->pool->lock);
4026 old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
4028 mutex_unlock(&wq->mutex);
4029 put_pwq_unlocked(old_pwq);
4032 static int alloc_and_link_pwqs(struct workqueue_struct *wq)
4034 bool highpri = wq->flags & WQ_HIGHPRI;
4037 if (!(wq->flags & WQ_UNBOUND)) {
4038 wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
4042 for_each_possible_cpu(cpu) {
4043 struct pool_workqueue *pwq =
4044 per_cpu_ptr(wq->cpu_pwqs, cpu);
4045 struct worker_pool *cpu_pools =
4046 per_cpu(cpu_worker_pools, cpu);
4048 init_pwq(pwq, wq, &cpu_pools[highpri]);
4050 mutex_lock(&wq->mutex);
4052 mutex_unlock(&wq->mutex);
4055 } else if (wq->flags & __WQ_ORDERED) {
4056 ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
4057 /* there should only be single pwq for ordering guarantee */
4058 WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
4059 wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
4060 "ordering guarantee broken for workqueue %s\n", wq->name);
4063 return apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
4067 static int wq_clamp_max_active(int max_active, unsigned int flags,
4070 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
4072 if (max_active < 1 || max_active > lim)
4073 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
4074 max_active, name, 1, lim);
4076 return clamp_val(max_active, 1, lim);
4079 struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
4082 struct lock_class_key *key,
4083 const char *lock_name, ...)
4085 size_t tbl_size = 0;
4087 struct workqueue_struct *wq;
4088 struct pool_workqueue *pwq;
4090 /* see the comment above the definition of WQ_POWER_EFFICIENT */
4091 if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
4092 flags |= WQ_UNBOUND;
4094 /* allocate wq and format name */
4095 if (flags & WQ_UNBOUND)
4096 tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
4098 wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
4102 if (flags & WQ_UNBOUND) {
4103 wq->unbound_attrs = alloc_workqueue_attrs(GFP_KERNEL);
4104 if (!wq->unbound_attrs)
4108 va_start(args, lock_name);
4109 vsnprintf(wq->name, sizeof(wq->name), fmt, args);
4112 max_active = max_active ?: WQ_DFL_ACTIVE;
4113 max_active = wq_clamp_max_active(max_active, flags, wq->name);
4117 wq->saved_max_active = max_active;
4118 mutex_init(&wq->mutex);
4119 atomic_set(&wq->nr_pwqs_to_flush, 0);
4120 INIT_LIST_HEAD(&wq->pwqs);
4121 INIT_LIST_HEAD(&wq->flusher_queue);
4122 INIT_LIST_HEAD(&wq->flusher_overflow);
4123 INIT_LIST_HEAD(&wq->maydays);
4125 lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
4126 INIT_LIST_HEAD(&wq->list);
4128 if (alloc_and_link_pwqs(wq) < 0)
4132 * Workqueues which may be used during memory reclaim should
4133 * have a rescuer to guarantee forward progress.
4135 if (flags & WQ_MEM_RECLAIM) {
4136 struct worker *rescuer;
4138 rescuer = alloc_worker(NUMA_NO_NODE);
4142 rescuer->rescue_wq = wq;
4143 rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
4145 if (IS_ERR(rescuer->task)) {
4150 wq->rescuer = rescuer;
4151 rescuer->task->flags |= PF_NO_SETAFFINITY;
4152 wake_up_process(rescuer->task);
4155 if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
4159 * wq_pool_mutex protects global freeze state and workqueues list.
4160 * Grab it, adjust max_active and add the new @wq to workqueues
4163 mutex_lock(&wq_pool_mutex);
4165 mutex_lock(&wq->mutex);
4166 for_each_pwq(pwq, wq)
4167 pwq_adjust_max_active(pwq);
4168 mutex_unlock(&wq->mutex);
4170 list_add_tail_rcu(&wq->list, &workqueues);
4172 mutex_unlock(&wq_pool_mutex);
4177 free_workqueue_attrs(wq->unbound_attrs);
4181 destroy_workqueue(wq);
4184 EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
4187 * destroy_workqueue - safely terminate a workqueue
4188 * @wq: target workqueue
4190 * Safely destroy a workqueue. All work currently pending will be done first.
4192 void destroy_workqueue(struct workqueue_struct *wq)
4194 struct pool_workqueue *pwq;
4197 /* drain it before proceeding with destruction */
4198 drain_workqueue(wq);
4201 mutex_lock(&wq->mutex);
4202 for_each_pwq(pwq, wq) {
4205 for (i = 0; i < WORK_NR_COLORS; i++) {
4206 if (WARN_ON(pwq->nr_in_flight[i])) {
4207 mutex_unlock(&wq->mutex);
4212 if (WARN_ON((pwq != wq->dfl_pwq) && (pwq->refcnt > 1)) ||
4213 WARN_ON(pwq->nr_active) ||
4214 WARN_ON(!list_empty(&pwq->delayed_works))) {
4215 mutex_unlock(&wq->mutex);
4219 mutex_unlock(&wq->mutex);
4222 * wq list is used to freeze wq, remove from list after
4223 * flushing is complete in case freeze races us.
4225 mutex_lock(&wq_pool_mutex);
4226 list_del_rcu(&wq->list);
4227 mutex_unlock(&wq_pool_mutex);
4229 workqueue_sysfs_unregister(wq);
4232 kthread_stop(wq->rescuer->task);
4234 if (!(wq->flags & WQ_UNBOUND)) {
4236 * The base ref is never dropped on per-cpu pwqs. Directly
4237 * schedule RCU free.
4239 call_rcu_sched(&wq->rcu, rcu_free_wq);
4242 * We're the sole accessor of @wq at this point. Directly
4243 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
4244 * @wq will be freed when the last pwq is released.
4246 for_each_node(node) {
4247 pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
4248 RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
4249 put_pwq_unlocked(pwq);
4253 * Put dfl_pwq. @wq may be freed any time after dfl_pwq is
4254 * put. Don't access it afterwards.
4258 put_pwq_unlocked(pwq);
4261 EXPORT_SYMBOL_GPL(destroy_workqueue);
4264 * workqueue_set_max_active - adjust max_active of a workqueue
4265 * @wq: target workqueue
4266 * @max_active: new max_active value.
4268 * Set max_active of @wq to @max_active.
4271 * Don't call from IRQ context.
4273 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4275 struct pool_workqueue *pwq;
4277 /* disallow meddling with max_active for ordered workqueues */
4278 if (WARN_ON(wq->flags & __WQ_ORDERED))
4281 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4283 mutex_lock(&wq->mutex);
4285 wq->saved_max_active = max_active;
4287 for_each_pwq(pwq, wq)
4288 pwq_adjust_max_active(pwq);
4290 mutex_unlock(&wq->mutex);
4292 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4295 * current_is_workqueue_rescuer - is %current workqueue rescuer?
4297 * Determine whether %current is a workqueue rescuer. Can be used from
4298 * work functions to determine whether it's being run off the rescuer task.
4300 * Return: %true if %current is a workqueue rescuer. %false otherwise.
4302 bool current_is_workqueue_rescuer(void)
4304 struct worker *worker = current_wq_worker();
4306 return worker && worker->rescue_wq;
4310 * workqueue_congested - test whether a workqueue is congested
4311 * @cpu: CPU in question
4312 * @wq: target workqueue
4314 * Test whether @wq's cpu workqueue for @cpu is congested. There is
4315 * no synchronization around this function and the test result is
4316 * unreliable and only useful as advisory hints or for debugging.
4318 * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4319 * Note that both per-cpu and unbound workqueues may be associated with
4320 * multiple pool_workqueues which have separate congested states. A
4321 * workqueue being congested on one CPU doesn't mean the workqueue is also
4322 * contested on other CPUs / NUMA nodes.
4325 * %true if congested, %false otherwise.
4327 bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4329 struct pool_workqueue *pwq;
4332 rcu_read_lock_sched();
4334 if (cpu == WORK_CPU_UNBOUND)
4335 cpu = smp_processor_id();
4337 if (!(wq->flags & WQ_UNBOUND))
4338 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
4340 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4342 ret = !list_empty(&pwq->delayed_works);
4343 rcu_read_unlock_sched();
4347 EXPORT_SYMBOL_GPL(workqueue_congested);
4350 * work_busy - test whether a work is currently pending or running
4351 * @work: the work to be tested
4353 * Test whether @work is currently pending or running. There is no
4354 * synchronization around this function and the test result is
4355 * unreliable and only useful as advisory hints or for debugging.
4358 * OR'd bitmask of WORK_BUSY_* bits.
4360 unsigned int work_busy(struct work_struct *work)
4362 struct worker_pool *pool;
4363 unsigned long flags;
4364 unsigned int ret = 0;
4366 if (work_pending(work))
4367 ret |= WORK_BUSY_PENDING;
4369 local_irq_save(flags);
4370 pool = get_work_pool(work);
4372 spin_lock(&pool->lock);
4373 if (find_worker_executing_work(pool, work))
4374 ret |= WORK_BUSY_RUNNING;
4375 spin_unlock(&pool->lock);
4377 local_irq_restore(flags);
4381 EXPORT_SYMBOL_GPL(work_busy);
4384 * set_worker_desc - set description for the current work item
4385 * @fmt: printf-style format string
4386 * @...: arguments for the format string
4388 * This function can be called by a running work function to describe what
4389 * the work item is about. If the worker task gets dumped, this
4390 * information will be printed out together to help debugging. The
4391 * description can be at most WORKER_DESC_LEN including the trailing '\0'.
4393 void set_worker_desc(const char *fmt, ...)
4395 struct worker *worker = current_wq_worker();
4399 va_start(args, fmt);
4400 vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
4402 worker->desc_valid = true;
4407 * print_worker_info - print out worker information and description
4408 * @log_lvl: the log level to use when printing
4409 * @task: target task
4411 * If @task is a worker and currently executing a work item, print out the
4412 * name of the workqueue being serviced and worker description set with
4413 * set_worker_desc() by the currently executing work item.
4415 * This function can be safely called on any task as long as the
4416 * task_struct itself is accessible. While safe, this function isn't
4417 * synchronized and may print out mixups or garbages of limited length.
4419 void print_worker_info(const char *log_lvl, struct task_struct *task)
4421 work_func_t *fn = NULL;
4422 char name[WQ_NAME_LEN] = { };
4423 char desc[WORKER_DESC_LEN] = { };
4424 struct pool_workqueue *pwq = NULL;
4425 struct workqueue_struct *wq = NULL;
4426 bool desc_valid = false;
4427 struct worker *worker;
4429 if (!(task->flags & PF_WQ_WORKER))
4433 * This function is called without any synchronization and @task
4434 * could be in any state. Be careful with dereferences.
4436 worker = probe_kthread_data(task);
4439 * Carefully copy the associated workqueue's workfn and name. Keep
4440 * the original last '\0' in case the original contains garbage.
4442 probe_kernel_read(&fn, &worker->current_func, sizeof(fn));
4443 probe_kernel_read(&pwq, &worker->current_pwq, sizeof(pwq));
4444 probe_kernel_read(&wq, &pwq->wq, sizeof(wq));
4445 probe_kernel_read(name, wq->name, sizeof(name) - 1);
4447 /* copy worker description */
4448 probe_kernel_read(&desc_valid, &worker->desc_valid, sizeof(desc_valid));
4450 probe_kernel_read(desc, worker->desc, sizeof(desc) - 1);
4452 if (fn || name[0] || desc[0]) {
4453 printk("%sWorkqueue: %s %pf", log_lvl, name, fn);
4455 pr_cont(" (%s)", desc);
4463 * There are two challenges in supporting CPU hotplug. Firstly, there
4464 * are a lot of assumptions on strong associations among work, pwq and
4465 * pool which make migrating pending and scheduled works very
4466 * difficult to implement without impacting hot paths. Secondly,
4467 * worker pools serve mix of short, long and very long running works making
4468 * blocked draining impractical.
4470 * This is solved by allowing the pools to be disassociated from the CPU
4471 * running as an unbound one and allowing it to be reattached later if the
4472 * cpu comes back online.
4475 static void wq_unbind_fn(struct work_struct *work)
4477 int cpu = smp_processor_id();
4478 struct worker_pool *pool;
4479 struct worker *worker;
4481 for_each_cpu_worker_pool(pool, cpu) {
4482 mutex_lock(&pool->attach_mutex);
4483 spin_lock_irq(&pool->lock);
4486 * We've blocked all attach/detach operations. Make all workers
4487 * unbound and set DISASSOCIATED. Before this, all workers
4488 * except for the ones which are still executing works from
4489 * before the last CPU down must be on the cpu. After
4490 * this, they may become diasporas.
4492 for_each_pool_worker(worker, pool)
4493 worker->flags |= WORKER_UNBOUND;
4495 pool->flags |= POOL_DISASSOCIATED;
4497 spin_unlock_irq(&pool->lock);
4498 mutex_unlock(&pool->attach_mutex);
4501 * Call schedule() so that we cross rq->lock and thus can
4502 * guarantee sched callbacks see the %WORKER_UNBOUND flag.
4503 * This is necessary as scheduler callbacks may be invoked
4509 * Sched callbacks are disabled now. Zap nr_running.
4510 * After this, nr_running stays zero and need_more_worker()
4511 * and keep_working() are always true as long as the
4512 * worklist is not empty. This pool now behaves as an
4513 * unbound (in terms of concurrency management) pool which
4514 * are served by workers tied to the pool.
4516 atomic_set(&pool->nr_running, 0);
4519 * With concurrency management just turned off, a busy
4520 * worker blocking could lead to lengthy stalls. Kick off
4521 * unbound chain execution of currently pending work items.
4523 spin_lock_irq(&pool->lock);
4524 wake_up_worker(pool);
4525 spin_unlock_irq(&pool->lock);
4530 * rebind_workers - rebind all workers of a pool to the associated CPU
4531 * @pool: pool of interest
4533 * @pool->cpu is coming online. Rebind all workers to the CPU.
4535 static void rebind_workers(struct worker_pool *pool)
4537 struct worker *worker;
4539 lockdep_assert_held(&pool->attach_mutex);
4542 * Restore CPU affinity of all workers. As all idle workers should
4543 * be on the run-queue of the associated CPU before any local
4544 * wake-ups for concurrency management happen, restore CPU affinty
4545 * of all workers first and then clear UNBOUND. As we're called
4546 * from CPU_ONLINE, the following shouldn't fail.
4548 for_each_pool_worker(worker, pool)
4549 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4550 pool->attrs->cpumask) < 0);
4552 spin_lock_irq(&pool->lock);
4553 pool->flags &= ~POOL_DISASSOCIATED;
4555 for_each_pool_worker(worker, pool) {
4556 unsigned int worker_flags = worker->flags;
4559 * A bound idle worker should actually be on the runqueue
4560 * of the associated CPU for local wake-ups targeting it to
4561 * work. Kick all idle workers so that they migrate to the
4562 * associated CPU. Doing this in the same loop as
4563 * replacing UNBOUND with REBOUND is safe as no worker will
4564 * be bound before @pool->lock is released.
4566 if (worker_flags & WORKER_IDLE)
4567 wake_up_process(worker->task);
4570 * We want to clear UNBOUND but can't directly call
4571 * worker_clr_flags() or adjust nr_running. Atomically
4572 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
4573 * @worker will clear REBOUND using worker_clr_flags() when
4574 * it initiates the next execution cycle thus restoring
4575 * concurrency management. Note that when or whether
4576 * @worker clears REBOUND doesn't affect correctness.
4578 * ACCESS_ONCE() is necessary because @worker->flags may be
4579 * tested without holding any lock in
4580 * wq_worker_waking_up(). Without it, NOT_RUNNING test may
4581 * fail incorrectly leading to premature concurrency
4582 * management operations.
4584 WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
4585 worker_flags |= WORKER_REBOUND;
4586 worker_flags &= ~WORKER_UNBOUND;
4587 ACCESS_ONCE(worker->flags) = worker_flags;
4590 spin_unlock_irq(&pool->lock);
4594 * restore_unbound_workers_cpumask - restore cpumask of unbound workers
4595 * @pool: unbound pool of interest
4596 * @cpu: the CPU which is coming up
4598 * An unbound pool may end up with a cpumask which doesn't have any online
4599 * CPUs. When a worker of such pool get scheduled, the scheduler resets
4600 * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
4601 * online CPU before, cpus_allowed of all its workers should be restored.
4603 static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
4605 static cpumask_t cpumask;
4606 struct worker *worker;
4608 lockdep_assert_held(&pool->attach_mutex);
4610 /* is @cpu allowed for @pool? */
4611 if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
4614 /* is @cpu the only online CPU? */
4615 cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
4616 if (cpumask_weight(&cpumask) != 1)
4619 /* as we're called from CPU_ONLINE, the following shouldn't fail */
4620 for_each_pool_worker(worker, pool)
4621 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4622 pool->attrs->cpumask) < 0);
4626 * Workqueues should be brought up before normal priority CPU notifiers.
4627 * This will be registered high priority CPU notifier.
4629 static int workqueue_cpu_up_callback(struct notifier_block *nfb,
4630 unsigned long action,
4633 int cpu = (unsigned long)hcpu;
4634 struct worker_pool *pool;
4635 struct workqueue_struct *wq;
4638 switch (action & ~CPU_TASKS_FROZEN) {
4639 case CPU_UP_PREPARE:
4640 for_each_cpu_worker_pool(pool, cpu) {
4641 if (pool->nr_workers)
4643 if (!create_worker(pool))
4648 case CPU_DOWN_FAILED:
4650 mutex_lock(&wq_pool_mutex);
4652 for_each_pool(pool, pi) {
4653 mutex_lock(&pool->attach_mutex);
4655 if (pool->cpu == cpu)
4656 rebind_workers(pool);
4657 else if (pool->cpu < 0)
4658 restore_unbound_workers_cpumask(pool, cpu);
4660 mutex_unlock(&pool->attach_mutex);
4663 /* update NUMA affinity of unbound workqueues */
4664 list_for_each_entry(wq, &workqueues, list)
4665 wq_update_unbound_numa(wq, cpu, true);
4667 mutex_unlock(&wq_pool_mutex);
4674 * Workqueues should be brought down after normal priority CPU notifiers.
4675 * This will be registered as low priority CPU notifier.
4677 static int workqueue_cpu_down_callback(struct notifier_block *nfb,
4678 unsigned long action,
4681 int cpu = (unsigned long)hcpu;
4682 struct work_struct unbind_work;
4683 struct workqueue_struct *wq;
4685 switch (action & ~CPU_TASKS_FROZEN) {
4686 case CPU_DOWN_PREPARE:
4687 /* unbinding per-cpu workers should happen on the local CPU */
4688 INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
4689 queue_work_on(cpu, system_highpri_wq, &unbind_work);
4691 /* update NUMA affinity of unbound workqueues */
4692 mutex_lock(&wq_pool_mutex);
4693 list_for_each_entry(wq, &workqueues, list)
4694 wq_update_unbound_numa(wq, cpu, false);
4695 mutex_unlock(&wq_pool_mutex);
4697 /* wait for per-cpu unbinding to finish */
4698 flush_work(&unbind_work);
4699 destroy_work_on_stack(&unbind_work);
4707 struct work_for_cpu {
4708 struct work_struct work;
4714 static void work_for_cpu_fn(struct work_struct *work)
4716 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
4718 wfc->ret = wfc->fn(wfc->arg);
4722 * work_on_cpu - run a function in user context on a particular cpu
4723 * @cpu: the cpu to run on
4724 * @fn: the function to run
4725 * @arg: the function arg
4727 * It is up to the caller to ensure that the cpu doesn't go offline.
4728 * The caller must not hold any locks which would prevent @fn from completing.
4730 * Return: The value @fn returns.
4732 long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
4734 struct work_for_cpu wfc = { .fn = fn, .arg = arg };
4736 INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
4737 schedule_work_on(cpu, &wfc.work);
4738 flush_work(&wfc.work);
4739 destroy_work_on_stack(&wfc.work);
4742 EXPORT_SYMBOL_GPL(work_on_cpu);
4743 #endif /* CONFIG_SMP */
4745 #ifdef CONFIG_FREEZER
4748 * freeze_workqueues_begin - begin freezing workqueues
4750 * Start freezing workqueues. After this function returns, all freezable
4751 * workqueues will queue new works to their delayed_works list instead of
4755 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4757 void freeze_workqueues_begin(void)
4759 struct workqueue_struct *wq;
4760 struct pool_workqueue *pwq;
4762 mutex_lock(&wq_pool_mutex);
4764 WARN_ON_ONCE(workqueue_freezing);
4765 workqueue_freezing = true;
4767 list_for_each_entry(wq, &workqueues, list) {
4768 mutex_lock(&wq->mutex);
4769 for_each_pwq(pwq, wq)
4770 pwq_adjust_max_active(pwq);
4771 mutex_unlock(&wq->mutex);
4774 mutex_unlock(&wq_pool_mutex);
4778 * freeze_workqueues_busy - are freezable workqueues still busy?
4780 * Check whether freezing is complete. This function must be called
4781 * between freeze_workqueues_begin() and thaw_workqueues().
4784 * Grabs and releases wq_pool_mutex.
4787 * %true if some freezable workqueues are still busy. %false if freezing
4790 bool freeze_workqueues_busy(void)
4793 struct workqueue_struct *wq;
4794 struct pool_workqueue *pwq;
4796 mutex_lock(&wq_pool_mutex);
4798 WARN_ON_ONCE(!workqueue_freezing);
4800 list_for_each_entry(wq, &workqueues, list) {
4801 if (!(wq->flags & WQ_FREEZABLE))
4804 * nr_active is monotonically decreasing. It's safe
4805 * to peek without lock.
4807 rcu_read_lock_sched();
4808 for_each_pwq(pwq, wq) {
4809 WARN_ON_ONCE(pwq->nr_active < 0);
4810 if (pwq->nr_active) {
4812 rcu_read_unlock_sched();
4816 rcu_read_unlock_sched();
4819 mutex_unlock(&wq_pool_mutex);
4824 * thaw_workqueues - thaw workqueues
4826 * Thaw workqueues. Normal queueing is restored and all collected
4827 * frozen works are transferred to their respective pool worklists.
4830 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4832 void thaw_workqueues(void)
4834 struct workqueue_struct *wq;
4835 struct pool_workqueue *pwq;
4837 mutex_lock(&wq_pool_mutex);
4839 if (!workqueue_freezing)
4842 workqueue_freezing = false;
4844 /* restore max_active and repopulate worklist */
4845 list_for_each_entry(wq, &workqueues, list) {
4846 mutex_lock(&wq->mutex);
4847 for_each_pwq(pwq, wq)
4848 pwq_adjust_max_active(pwq);
4849 mutex_unlock(&wq->mutex);
4853 mutex_unlock(&wq_pool_mutex);
4855 #endif /* CONFIG_FREEZER */
4857 static void __init wq_numa_init(void)
4862 if (num_possible_nodes() <= 1)
4865 if (wq_disable_numa) {
4866 pr_info("workqueue: NUMA affinity support disabled\n");
4870 wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs(GFP_KERNEL);
4871 BUG_ON(!wq_update_unbound_numa_attrs_buf);
4874 * We want masks of possible CPUs of each node which isn't readily
4875 * available. Build one from cpu_to_node() which should have been
4876 * fully initialized by now.
4878 tbl = kzalloc(nr_node_ids * sizeof(tbl[0]), GFP_KERNEL);
4882 BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
4883 node_online(node) ? node : NUMA_NO_NODE));
4885 for_each_possible_cpu(cpu) {
4886 node = cpu_to_node(cpu);
4887 if (WARN_ON(node == NUMA_NO_NODE)) {
4888 pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
4889 /* happens iff arch is bonkers, let's just proceed */
4892 cpumask_set_cpu(cpu, tbl[node]);
4895 wq_numa_possible_cpumask = tbl;
4896 wq_numa_enabled = true;
4899 static int __init init_workqueues(void)
4901 int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
4904 WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
4906 pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
4908 cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
4909 hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
4913 /* initialize CPU pools */
4914 for_each_possible_cpu(cpu) {
4915 struct worker_pool *pool;
4918 for_each_cpu_worker_pool(pool, cpu) {
4919 BUG_ON(init_worker_pool(pool));
4921 cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
4922 pool->attrs->nice = std_nice[i++];
4923 pool->node = cpu_to_node(cpu);
4926 mutex_lock(&wq_pool_mutex);
4927 BUG_ON(worker_pool_assign_id(pool));
4928 mutex_unlock(&wq_pool_mutex);
4932 /* create the initial worker */
4933 for_each_online_cpu(cpu) {
4934 struct worker_pool *pool;
4936 for_each_cpu_worker_pool(pool, cpu) {
4937 pool->flags &= ~POOL_DISASSOCIATED;
4938 BUG_ON(!create_worker(pool));
4942 /* create default unbound and ordered wq attrs */
4943 for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
4944 struct workqueue_attrs *attrs;
4946 BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
4947 attrs->nice = std_nice[i];
4948 unbound_std_wq_attrs[i] = attrs;
4951 * An ordered wq should have only one pwq as ordering is
4952 * guaranteed by max_active which is enforced by pwqs.
4953 * Turn off NUMA so that dfl_pwq is used for all nodes.
4955 BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
4956 attrs->nice = std_nice[i];
4957 attrs->no_numa = true;
4958 ordered_wq_attrs[i] = attrs;
4961 system_wq = alloc_workqueue("events", 0, 0);
4962 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
4963 system_long_wq = alloc_workqueue("events_long", 0, 0);
4964 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
4965 WQ_UNBOUND_MAX_ACTIVE);
4966 system_freezable_wq = alloc_workqueue("events_freezable",
4968 system_power_efficient_wq = alloc_workqueue("events_power_efficient",
4969 WQ_POWER_EFFICIENT, 0);
4970 system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
4971 WQ_FREEZABLE | WQ_POWER_EFFICIENT,
4973 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
4974 !system_unbound_wq || !system_freezable_wq ||
4975 !system_power_efficient_wq ||
4976 !system_freezable_power_efficient_wq);
4979 early_initcall(init_workqueues);