mfd: wm8350-i2c: Make sure the i2c regmap functions are compiled
[linux/fpc-iii.git] / kernel / workqueue.c
blob2bc1257e420f7aa9869d9bedf16f20eef0fd4619
1 /*
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>
8 * Andrew Morton
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"
54 enum {
56 * worker_pool flags
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
61 * is in effect.
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 * manager_mutex to avoid changing binding state while
69 * create_worker() is in progress.
71 POOL_MANAGE_WORKERS = 1 << 0, /* need to manage workers */
72 POOL_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
73 POOL_FREEZING = 1 << 3, /* freeze in progress */
75 /* worker flags */
76 WORKER_STARTED = 1 << 0, /* started */
77 WORKER_DIE = 1 << 1, /* die die die */
78 WORKER_IDLE = 1 << 2, /* is idle */
79 WORKER_PREP = 1 << 3, /* preparing to run works */
80 WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
81 WORKER_UNBOUND = 1 << 7, /* worker is unbound */
82 WORKER_REBOUND = 1 << 8, /* worker was rebound */
84 WORKER_NOT_RUNNING = WORKER_PREP | WORKER_CPU_INTENSIVE |
85 WORKER_UNBOUND | WORKER_REBOUND,
87 NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */
89 UNBOUND_POOL_HASH_ORDER = 6, /* hashed by pool->attrs */
90 BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
92 MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
93 IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
95 MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
96 /* call for help after 10ms
97 (min two ticks) */
98 MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
99 CREATE_COOLDOWN = HZ, /* time to breath after fail */
102 * Rescue workers are used only on emergencies and shared by
103 * all cpus. Give -20.
105 RESCUER_NICE_LEVEL = -20,
106 HIGHPRI_NICE_LEVEL = -20,
108 WQ_NAME_LEN = 24,
112 * Structure fields follow one of the following exclusion rules.
114 * I: Modifiable by initialization/destruction paths and read-only for
115 * everyone else.
117 * P: Preemption protected. Disabling preemption is enough and should
118 * only be modified and accessed from the local cpu.
120 * L: pool->lock protected. Access with pool->lock held.
122 * X: During normal operation, modification requires pool->lock and should
123 * be done only from local cpu. Either disabling preemption on local
124 * cpu or grabbing pool->lock is enough for read access. If
125 * POOL_DISASSOCIATED is set, it's identical to L.
127 * MG: pool->manager_mutex and pool->lock protected. Writes require both
128 * locks. Reads can happen under either lock.
130 * PL: wq_pool_mutex protected.
132 * PR: wq_pool_mutex protected for writes. Sched-RCU protected for reads.
134 * WQ: wq->mutex protected.
136 * WR: wq->mutex protected for writes. Sched-RCU protected for reads.
138 * MD: wq_mayday_lock protected.
141 /* struct worker is defined in workqueue_internal.h */
143 struct worker_pool {
144 spinlock_t lock; /* the pool lock */
145 int cpu; /* I: the associated cpu */
146 int node; /* I: the associated node ID */
147 int id; /* I: pool ID */
148 unsigned int flags; /* X: flags */
150 struct list_head worklist; /* L: list of pending works */
151 int nr_workers; /* L: total number of workers */
153 /* nr_idle includes the ones off idle_list for rebinding */
154 int nr_idle; /* L: currently idle ones */
156 struct list_head idle_list; /* X: list of idle workers */
157 struct timer_list idle_timer; /* L: worker idle timeout */
158 struct timer_list mayday_timer; /* L: SOS timer for workers */
160 /* a workers is either on busy_hash or idle_list, or the manager */
161 DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
162 /* L: hash of busy workers */
164 /* see manage_workers() for details on the two manager mutexes */
165 struct mutex manager_arb; /* manager arbitration */
166 struct mutex manager_mutex; /* manager exclusion */
167 struct idr worker_idr; /* MG: worker IDs and iteration */
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
176 * cacheline.
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().
184 struct rcu_head rcu;
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;
214 struct rcu_head rcu;
215 } __aligned(1 << WORK_STRUCT_FLAG_BITS);
218 * Structure used to wait for workqueue flush.
220 struct wq_flusher {
221 struct list_head list; /* WQ: list of flushers */
222 int flush_color; /* WQ: flush color waiting for */
223 struct completion done; /* flush completion */
226 struct wq_device;
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; /* PL: 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 */
253 #ifdef CONFIG_SYSFS
254 struct wq_device *wq_dev; /* I: for sysfs interface */
255 #endif
256 #ifdef CONFIG_LOCKDEP
257 struct lockdep_map lockdep_map;
258 #endif
259 char name[WQ_NAME_LEN]; /* I: workqueue name */
261 /* hot fields used during command issue, aligned to cacheline */
262 unsigned int flags ____cacheline_aligned; /* WQ: WQ_* flags */
263 struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */
264 struct pool_workqueue __rcu *numa_pwq_tbl[]; /* FR: unbound pwqs indexed by node */
267 static struct kmem_cache *pwq_cache;
269 static int wq_numa_tbl_len; /* highest possible NUMA node id + 1 */
270 static cpumask_var_t *wq_numa_possible_cpumask;
271 /* possible CPUs of each node */
273 static bool wq_disable_numa;
274 module_param_named(disable_numa, wq_disable_numa, bool, 0444);
276 /* see the comment above the definition of WQ_POWER_EFFICIENT */
277 #ifdef CONFIG_WQ_POWER_EFFICIENT_DEFAULT
278 static bool wq_power_efficient = true;
279 #else
280 static bool wq_power_efficient;
281 #endif
283 module_param_named(power_efficient, wq_power_efficient, bool, 0444);
285 static bool wq_numa_enabled; /* unbound NUMA affinity enabled */
287 /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
288 static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf;
290 static DEFINE_MUTEX(wq_pool_mutex); /* protects pools and workqueues list */
291 static DEFINE_SPINLOCK(wq_mayday_lock); /* protects wq->maydays list */
293 static LIST_HEAD(workqueues); /* PL: list of all workqueues */
294 static bool workqueue_freezing; /* PL: have wqs started freezing? */
296 /* the per-cpu worker pools */
297 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
298 cpu_worker_pools);
300 static DEFINE_IDR(worker_pool_idr); /* PR: idr of all pools */
302 /* PL: hash of all unbound pools keyed by pool->attrs */
303 static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
305 /* I: attributes used when instantiating standard unbound pools on demand */
306 static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
308 /* I: attributes used when instantiating ordered pools on demand */
309 static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
311 struct workqueue_struct *system_wq __read_mostly;
312 EXPORT_SYMBOL(system_wq);
313 struct workqueue_struct *system_highpri_wq __read_mostly;
314 EXPORT_SYMBOL_GPL(system_highpri_wq);
315 struct workqueue_struct *system_long_wq __read_mostly;
316 EXPORT_SYMBOL_GPL(system_long_wq);
317 struct workqueue_struct *system_unbound_wq __read_mostly;
318 EXPORT_SYMBOL_GPL(system_unbound_wq);
319 struct workqueue_struct *system_freezable_wq __read_mostly;
320 EXPORT_SYMBOL_GPL(system_freezable_wq);
321 struct workqueue_struct *system_power_efficient_wq __read_mostly;
322 EXPORT_SYMBOL_GPL(system_power_efficient_wq);
323 struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
324 EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
326 static int worker_thread(void *__worker);
327 static void copy_workqueue_attrs(struct workqueue_attrs *to,
328 const struct workqueue_attrs *from);
330 #define CREATE_TRACE_POINTS
331 #include <trace/events/workqueue.h>
333 #define assert_rcu_or_pool_mutex() \
334 rcu_lockdep_assert(rcu_read_lock_sched_held() || \
335 lockdep_is_held(&wq_pool_mutex), \
336 "sched RCU or wq_pool_mutex should be held")
338 #define assert_rcu_or_wq_mutex(wq) \
339 rcu_lockdep_assert(rcu_read_lock_sched_held() || \
340 lockdep_is_held(&wq->mutex), \
341 "sched RCU or wq->mutex should be held")
343 #ifdef CONFIG_LOCKDEP
344 #define assert_manager_or_pool_lock(pool) \
345 WARN_ONCE(debug_locks && \
346 !lockdep_is_held(&(pool)->manager_mutex) && \
347 !lockdep_is_held(&(pool)->lock), \
348 "pool->manager_mutex or ->lock should be held")
349 #else
350 #define assert_manager_or_pool_lock(pool) do { } while (0)
351 #endif
353 #define for_each_cpu_worker_pool(pool, cpu) \
354 for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
355 (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
356 (pool)++)
359 * for_each_pool - iterate through all worker_pools in the system
360 * @pool: iteration cursor
361 * @pi: integer used for iteration
363 * This must be called either with wq_pool_mutex held or sched RCU read
364 * locked. If the pool needs to be used beyond the locking in effect, the
365 * caller is responsible for guaranteeing that the pool stays online.
367 * The if/else clause exists only for the lockdep assertion and can be
368 * ignored.
370 #define for_each_pool(pool, pi) \
371 idr_for_each_entry(&worker_pool_idr, pool, pi) \
372 if (({ assert_rcu_or_pool_mutex(); false; })) { } \
373 else
376 * for_each_pool_worker - iterate through all workers of a worker_pool
377 * @worker: iteration cursor
378 * @wi: integer used for iteration
379 * @pool: worker_pool to iterate workers of
381 * This must be called with either @pool->manager_mutex or ->lock held.
383 * The if/else clause exists only for the lockdep assertion and can be
384 * ignored.
386 #define for_each_pool_worker(worker, wi, pool) \
387 idr_for_each_entry(&(pool)->worker_idr, (worker), (wi)) \
388 if (({ assert_manager_or_pool_lock((pool)); false; })) { } \
389 else
392 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
393 * @pwq: iteration cursor
394 * @wq: the target workqueue
396 * This must be called either with wq->mutex held or sched RCU read locked.
397 * If the pwq needs to be used beyond the locking in effect, the caller is
398 * responsible for guaranteeing that the pwq stays online.
400 * The if/else clause exists only for the lockdep assertion and can be
401 * ignored.
403 #define for_each_pwq(pwq, wq) \
404 list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node) \
405 if (({ assert_rcu_or_wq_mutex(wq); false; })) { } \
406 else
408 #ifdef CONFIG_DEBUG_OBJECTS_WORK
410 static struct debug_obj_descr work_debug_descr;
412 static void *work_debug_hint(void *addr)
414 return ((struct work_struct *) addr)->func;
418 * fixup_init is called when:
419 * - an active object is initialized
421 static int work_fixup_init(void *addr, enum debug_obj_state state)
423 struct work_struct *work = addr;
425 switch (state) {
426 case ODEBUG_STATE_ACTIVE:
427 cancel_work_sync(work);
428 debug_object_init(work, &work_debug_descr);
429 return 1;
430 default:
431 return 0;
436 * fixup_activate is called when:
437 * - an active object is activated
438 * - an unknown object is activated (might be a statically initialized object)
440 static int work_fixup_activate(void *addr, enum debug_obj_state state)
442 struct work_struct *work = addr;
444 switch (state) {
446 case ODEBUG_STATE_NOTAVAILABLE:
448 * This is not really a fixup. The work struct was
449 * statically initialized. We just make sure that it
450 * is tracked in the object tracker.
452 if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
453 debug_object_init(work, &work_debug_descr);
454 debug_object_activate(work, &work_debug_descr);
455 return 0;
457 WARN_ON_ONCE(1);
458 return 0;
460 case ODEBUG_STATE_ACTIVE:
461 WARN_ON(1);
463 default:
464 return 0;
469 * fixup_free is called when:
470 * - an active object is freed
472 static int work_fixup_free(void *addr, enum debug_obj_state state)
474 struct work_struct *work = addr;
476 switch (state) {
477 case ODEBUG_STATE_ACTIVE:
478 cancel_work_sync(work);
479 debug_object_free(work, &work_debug_descr);
480 return 1;
481 default:
482 return 0;
486 static struct debug_obj_descr work_debug_descr = {
487 .name = "work_struct",
488 .debug_hint = work_debug_hint,
489 .fixup_init = work_fixup_init,
490 .fixup_activate = work_fixup_activate,
491 .fixup_free = work_fixup_free,
494 static inline void debug_work_activate(struct work_struct *work)
496 debug_object_activate(work, &work_debug_descr);
499 static inline void debug_work_deactivate(struct work_struct *work)
501 debug_object_deactivate(work, &work_debug_descr);
504 void __init_work(struct work_struct *work, int onstack)
506 if (onstack)
507 debug_object_init_on_stack(work, &work_debug_descr);
508 else
509 debug_object_init(work, &work_debug_descr);
511 EXPORT_SYMBOL_GPL(__init_work);
513 void destroy_work_on_stack(struct work_struct *work)
515 debug_object_free(work, &work_debug_descr);
517 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
519 #else
520 static inline void debug_work_activate(struct work_struct *work) { }
521 static inline void debug_work_deactivate(struct work_struct *work) { }
522 #endif
524 /* allocate ID and assign it to @pool */
525 static int worker_pool_assign_id(struct worker_pool *pool)
527 int ret;
529 lockdep_assert_held(&wq_pool_mutex);
531 ret = idr_alloc(&worker_pool_idr, pool, 0, 0, GFP_KERNEL);
532 if (ret >= 0) {
533 pool->id = ret;
534 return 0;
536 return ret;
540 * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
541 * @wq: the target workqueue
542 * @node: the node ID
544 * This must be called either with pwq_lock held or sched RCU read locked.
545 * If the pwq needs to be used beyond the locking in effect, the caller is
546 * responsible for guaranteeing that the pwq stays online.
548 * Return: The unbound pool_workqueue for @node.
550 static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
551 int node)
553 assert_rcu_or_wq_mutex(wq);
554 return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
557 static unsigned int work_color_to_flags(int color)
559 return color << WORK_STRUCT_COLOR_SHIFT;
562 static int get_work_color(struct work_struct *work)
564 return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
565 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
568 static int work_next_color(int color)
570 return (color + 1) % WORK_NR_COLORS;
574 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
575 * contain the pointer to the queued pwq. Once execution starts, the flag
576 * is cleared and the high bits contain OFFQ flags and pool ID.
578 * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
579 * and clear_work_data() can be used to set the pwq, pool or clear
580 * work->data. These functions should only be called while the work is
581 * owned - ie. while the PENDING bit is set.
583 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
584 * corresponding to a work. Pool is available once the work has been
585 * queued anywhere after initialization until it is sync canceled. pwq is
586 * available only while the work item is queued.
588 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
589 * canceled. While being canceled, a work item may have its PENDING set
590 * but stay off timer and worklist for arbitrarily long and nobody should
591 * try to steal the PENDING bit.
593 static inline void set_work_data(struct work_struct *work, unsigned long data,
594 unsigned long flags)
596 WARN_ON_ONCE(!work_pending(work));
597 atomic_long_set(&work->data, data | flags | work_static(work));
600 static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
601 unsigned long extra_flags)
603 set_work_data(work, (unsigned long)pwq,
604 WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
607 static void set_work_pool_and_keep_pending(struct work_struct *work,
608 int pool_id)
610 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
611 WORK_STRUCT_PENDING);
614 static void set_work_pool_and_clear_pending(struct work_struct *work,
615 int pool_id)
618 * The following wmb is paired with the implied mb in
619 * test_and_set_bit(PENDING) and ensures all updates to @work made
620 * here are visible to and precede any updates by the next PENDING
621 * owner.
623 smp_wmb();
624 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
626 * The following mb guarantees that previous clear of a PENDING bit
627 * will not be reordered with any speculative LOADS or STORES from
628 * work->current_func, which is executed afterwards. This possible
629 * reordering can lead to a missed execution on attempt to qeueue
630 * the same @work. E.g. consider this case:
632 * CPU#0 CPU#1
633 * ---------------------------- --------------------------------
635 * 1 STORE event_indicated
636 * 2 queue_work_on() {
637 * 3 test_and_set_bit(PENDING)
638 * 4 } set_..._and_clear_pending() {
639 * 5 set_work_data() # clear bit
640 * 6 smp_mb()
641 * 7 work->current_func() {
642 * 8 LOAD event_indicated
645 * Without an explicit full barrier speculative LOAD on line 8 can
646 * be executed before CPU#0 does STORE on line 1. If that happens,
647 * CPU#0 observes the PENDING bit is still set and new execution of
648 * a @work is not queued in a hope, that CPU#1 will eventually
649 * finish the queued @work. Meanwhile CPU#1 does not see
650 * event_indicated is set, because speculative LOAD was executed
651 * before actual STORE.
653 smp_mb();
656 static void clear_work_data(struct work_struct *work)
658 smp_wmb(); /* see set_work_pool_and_clear_pending() */
659 set_work_data(work, WORK_STRUCT_NO_POOL, 0);
662 static struct pool_workqueue *get_work_pwq(struct work_struct *work)
664 unsigned long data = atomic_long_read(&work->data);
666 if (data & WORK_STRUCT_PWQ)
667 return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
668 else
669 return NULL;
673 * get_work_pool - return the worker_pool a given work was associated with
674 * @work: the work item of interest
676 * Pools are created and destroyed under wq_pool_mutex, and allows read
677 * access under sched-RCU read lock. As such, this function should be
678 * called under wq_pool_mutex or with preemption disabled.
680 * All fields of the returned pool are accessible as long as the above
681 * mentioned locking is in effect. If the returned pool needs to be used
682 * beyond the critical section, the caller is responsible for ensuring the
683 * returned pool is and stays online.
685 * Return: The worker_pool @work was last associated with. %NULL if none.
687 static struct worker_pool *get_work_pool(struct work_struct *work)
689 unsigned long data = atomic_long_read(&work->data);
690 int pool_id;
692 assert_rcu_or_pool_mutex();
694 if (data & WORK_STRUCT_PWQ)
695 return ((struct pool_workqueue *)
696 (data & WORK_STRUCT_WQ_DATA_MASK))->pool;
698 pool_id = data >> WORK_OFFQ_POOL_SHIFT;
699 if (pool_id == WORK_OFFQ_POOL_NONE)
700 return NULL;
702 return idr_find(&worker_pool_idr, pool_id);
706 * get_work_pool_id - return the worker pool ID a given work is associated with
707 * @work: the work item of interest
709 * Return: The worker_pool ID @work was last associated with.
710 * %WORK_OFFQ_POOL_NONE if none.
712 static int get_work_pool_id(struct work_struct *work)
714 unsigned long data = atomic_long_read(&work->data);
716 if (data & WORK_STRUCT_PWQ)
717 return ((struct pool_workqueue *)
718 (data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
720 return data >> WORK_OFFQ_POOL_SHIFT;
723 static void mark_work_canceling(struct work_struct *work)
725 unsigned long pool_id = get_work_pool_id(work);
727 pool_id <<= WORK_OFFQ_POOL_SHIFT;
728 set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
731 static bool work_is_canceling(struct work_struct *work)
733 unsigned long data = atomic_long_read(&work->data);
735 return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
739 * Policy functions. These define the policies on how the global worker
740 * pools are managed. Unless noted otherwise, these functions assume that
741 * they're being called with pool->lock held.
744 static bool __need_more_worker(struct worker_pool *pool)
746 return !atomic_read(&pool->nr_running);
750 * Need to wake up a worker? Called from anything but currently
751 * running workers.
753 * Note that, because unbound workers never contribute to nr_running, this
754 * function will always return %true for unbound pools as long as the
755 * worklist isn't empty.
757 static bool need_more_worker(struct worker_pool *pool)
759 return !list_empty(&pool->worklist) && __need_more_worker(pool);
762 /* Can I start working? Called from busy but !running workers. */
763 static bool may_start_working(struct worker_pool *pool)
765 return pool->nr_idle;
768 /* Do I need to keep working? Called from currently running workers. */
769 static bool keep_working(struct worker_pool *pool)
771 return !list_empty(&pool->worklist) &&
772 atomic_read(&pool->nr_running) <= 1;
775 /* Do we need a new worker? Called from manager. */
776 static bool need_to_create_worker(struct worker_pool *pool)
778 return need_more_worker(pool) && !may_start_working(pool);
781 /* Do I need to be the manager? */
782 static bool need_to_manage_workers(struct worker_pool *pool)
784 return need_to_create_worker(pool) ||
785 (pool->flags & POOL_MANAGE_WORKERS);
788 /* Do we have too many workers and should some go away? */
789 static bool too_many_workers(struct worker_pool *pool)
791 bool managing = mutex_is_locked(&pool->manager_arb);
792 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
793 int nr_busy = pool->nr_workers - nr_idle;
796 * nr_idle and idle_list may disagree if idle rebinding is in
797 * progress. Never return %true if idle_list is empty.
799 if (list_empty(&pool->idle_list))
800 return false;
802 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
806 * Wake up functions.
809 /* Return the first worker. Safe with preemption disabled */
810 static struct worker *first_worker(struct worker_pool *pool)
812 if (unlikely(list_empty(&pool->idle_list)))
813 return NULL;
815 return list_first_entry(&pool->idle_list, struct worker, entry);
819 * wake_up_worker - wake up an idle worker
820 * @pool: worker pool to wake worker from
822 * Wake up the first idle worker of @pool.
824 * CONTEXT:
825 * spin_lock_irq(pool->lock).
827 static void wake_up_worker(struct worker_pool *pool)
829 struct worker *worker = first_worker(pool);
831 if (likely(worker))
832 wake_up_process(worker->task);
836 * wq_worker_waking_up - a worker is waking up
837 * @task: task waking up
838 * @cpu: CPU @task is waking up to
840 * This function is called during try_to_wake_up() when a worker is
841 * being awoken.
843 * CONTEXT:
844 * spin_lock_irq(rq->lock)
846 void wq_worker_waking_up(struct task_struct *task, int cpu)
848 struct worker *worker = kthread_data(task);
850 if (!(worker->flags & WORKER_NOT_RUNNING)) {
851 WARN_ON_ONCE(worker->pool->cpu != cpu);
852 atomic_inc(&worker->pool->nr_running);
857 * wq_worker_sleeping - a worker is going to sleep
858 * @task: task going to sleep
859 * @cpu: CPU in question, must be the current CPU number
861 * This function is called during schedule() when a busy worker is
862 * going to sleep. Worker on the same cpu can be woken up by
863 * returning pointer to its task.
865 * CONTEXT:
866 * spin_lock_irq(rq->lock)
868 * Return:
869 * Worker task on @cpu to wake up, %NULL if none.
871 struct task_struct *wq_worker_sleeping(struct task_struct *task, int cpu)
873 struct worker *worker = kthread_data(task), *to_wakeup = NULL;
874 struct worker_pool *pool;
877 * Rescuers, which may not have all the fields set up like normal
878 * workers, also reach here, let's not access anything before
879 * checking NOT_RUNNING.
881 if (worker->flags & WORKER_NOT_RUNNING)
882 return NULL;
884 pool = worker->pool;
886 /* this can only happen on the local cpu */
887 if (WARN_ON_ONCE(cpu != raw_smp_processor_id()))
888 return NULL;
891 * The counterpart of the following dec_and_test, implied mb,
892 * worklist not empty test sequence is in insert_work().
893 * Please read comment there.
895 * NOT_RUNNING is clear. This means that we're bound to and
896 * running on the local cpu w/ rq lock held and preemption
897 * disabled, which in turn means that none else could be
898 * manipulating idle_list, so dereferencing idle_list without pool
899 * lock is safe.
901 if (atomic_dec_and_test(&pool->nr_running) &&
902 !list_empty(&pool->worklist))
903 to_wakeup = first_worker(pool);
904 return to_wakeup ? to_wakeup->task : NULL;
908 * worker_set_flags - set worker flags and adjust nr_running accordingly
909 * @worker: self
910 * @flags: flags to set
911 * @wakeup: wakeup an idle worker if necessary
913 * Set @flags in @worker->flags and adjust nr_running accordingly. If
914 * nr_running becomes zero and @wakeup is %true, an idle worker is
915 * woken up.
917 * CONTEXT:
918 * spin_lock_irq(pool->lock)
920 static inline void worker_set_flags(struct worker *worker, unsigned int flags,
921 bool wakeup)
923 struct worker_pool *pool = worker->pool;
925 WARN_ON_ONCE(worker->task != current);
928 * If transitioning into NOT_RUNNING, adjust nr_running and
929 * wake up an idle worker as necessary if requested by
930 * @wakeup.
932 if ((flags & WORKER_NOT_RUNNING) &&
933 !(worker->flags & WORKER_NOT_RUNNING)) {
934 if (wakeup) {
935 if (atomic_dec_and_test(&pool->nr_running) &&
936 !list_empty(&pool->worklist))
937 wake_up_worker(pool);
938 } else
939 atomic_dec(&pool->nr_running);
942 worker->flags |= flags;
946 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
947 * @worker: self
948 * @flags: flags to clear
950 * Clear @flags in @worker->flags and adjust nr_running accordingly.
952 * CONTEXT:
953 * spin_lock_irq(pool->lock)
955 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
957 struct worker_pool *pool = worker->pool;
958 unsigned int oflags = worker->flags;
960 WARN_ON_ONCE(worker->task != current);
962 worker->flags &= ~flags;
965 * If transitioning out of NOT_RUNNING, increment nr_running. Note
966 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
967 * of multiple flags, not a single flag.
969 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
970 if (!(worker->flags & WORKER_NOT_RUNNING))
971 atomic_inc(&pool->nr_running);
975 * find_worker_executing_work - find worker which is executing a work
976 * @pool: pool of interest
977 * @work: work to find worker for
979 * Find a worker which is executing @work on @pool by searching
980 * @pool->busy_hash which is keyed by the address of @work. For a worker
981 * to match, its current execution should match the address of @work and
982 * its work function. This is to avoid unwanted dependency between
983 * unrelated work executions through a work item being recycled while still
984 * being executed.
986 * This is a bit tricky. A work item may be freed once its execution
987 * starts and nothing prevents the freed area from being recycled for
988 * another work item. If the same work item address ends up being reused
989 * before the original execution finishes, workqueue will identify the
990 * recycled work item as currently executing and make it wait until the
991 * current execution finishes, introducing an unwanted dependency.
993 * This function checks the work item address and work function to avoid
994 * false positives. Note that this isn't complete as one may construct a
995 * work function which can introduce dependency onto itself through a
996 * recycled work item. Well, if somebody wants to shoot oneself in the
997 * foot that badly, there's only so much we can do, and if such deadlock
998 * actually occurs, it should be easy to locate the culprit work function.
1000 * CONTEXT:
1001 * spin_lock_irq(pool->lock).
1003 * Return:
1004 * Pointer to worker which is executing @work if found, %NULL
1005 * otherwise.
1007 static struct worker *find_worker_executing_work(struct worker_pool *pool,
1008 struct work_struct *work)
1010 struct worker *worker;
1012 hash_for_each_possible(pool->busy_hash, worker, hentry,
1013 (unsigned long)work)
1014 if (worker->current_work == work &&
1015 worker->current_func == work->func)
1016 return worker;
1018 return NULL;
1022 * move_linked_works - move linked works to a list
1023 * @work: start of series of works to be scheduled
1024 * @head: target list to append @work to
1025 * @nextp: out paramter for nested worklist walking
1027 * Schedule linked works starting from @work to @head. Work series to
1028 * be scheduled starts at @work and includes any consecutive work with
1029 * WORK_STRUCT_LINKED set in its predecessor.
1031 * If @nextp is not NULL, it's updated to point to the next work of
1032 * the last scheduled work. This allows move_linked_works() to be
1033 * nested inside outer list_for_each_entry_safe().
1035 * CONTEXT:
1036 * spin_lock_irq(pool->lock).
1038 static void move_linked_works(struct work_struct *work, struct list_head *head,
1039 struct work_struct **nextp)
1041 struct work_struct *n;
1044 * Linked worklist will always end before the end of the list,
1045 * use NULL for list head.
1047 list_for_each_entry_safe_from(work, n, NULL, entry) {
1048 list_move_tail(&work->entry, head);
1049 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1050 break;
1054 * If we're already inside safe list traversal and have moved
1055 * multiple works to the scheduled queue, the next position
1056 * needs to be updated.
1058 if (nextp)
1059 *nextp = n;
1063 * get_pwq - get an extra reference on the specified pool_workqueue
1064 * @pwq: pool_workqueue to get
1066 * Obtain an extra reference on @pwq. The caller should guarantee that
1067 * @pwq has positive refcnt and be holding the matching pool->lock.
1069 static void get_pwq(struct pool_workqueue *pwq)
1071 lockdep_assert_held(&pwq->pool->lock);
1072 WARN_ON_ONCE(pwq->refcnt <= 0);
1073 pwq->refcnt++;
1077 * put_pwq - put a pool_workqueue reference
1078 * @pwq: pool_workqueue to put
1080 * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
1081 * destruction. The caller should be holding the matching pool->lock.
1083 static void put_pwq(struct pool_workqueue *pwq)
1085 lockdep_assert_held(&pwq->pool->lock);
1086 if (likely(--pwq->refcnt))
1087 return;
1088 if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
1089 return;
1091 * @pwq can't be released under pool->lock, bounce to
1092 * pwq_unbound_release_workfn(). This never recurses on the same
1093 * pool->lock as this path is taken only for unbound workqueues and
1094 * the release work item is scheduled on a per-cpu workqueue. To
1095 * avoid lockdep warning, unbound pool->locks are given lockdep
1096 * subclass of 1 in get_unbound_pool().
1098 schedule_work(&pwq->unbound_release_work);
1102 * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1103 * @pwq: pool_workqueue to put (can be %NULL)
1105 * put_pwq() with locking. This function also allows %NULL @pwq.
1107 static void put_pwq_unlocked(struct pool_workqueue *pwq)
1109 if (pwq) {
1111 * As both pwqs and pools are sched-RCU protected, the
1112 * following lock operations are safe.
1114 spin_lock_irq(&pwq->pool->lock);
1115 put_pwq(pwq);
1116 spin_unlock_irq(&pwq->pool->lock);
1120 static void pwq_activate_delayed_work(struct work_struct *work)
1122 struct pool_workqueue *pwq = get_work_pwq(work);
1124 trace_workqueue_activate_work(work);
1125 move_linked_works(work, &pwq->pool->worklist, NULL);
1126 __clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
1127 pwq->nr_active++;
1130 static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
1132 struct work_struct *work = list_first_entry(&pwq->delayed_works,
1133 struct work_struct, entry);
1135 pwq_activate_delayed_work(work);
1139 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1140 * @pwq: pwq of interest
1141 * @color: color of work which left the queue
1143 * A work either has completed or is removed from pending queue,
1144 * decrement nr_in_flight of its pwq and handle workqueue flushing.
1146 * CONTEXT:
1147 * spin_lock_irq(pool->lock).
1149 static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
1151 /* uncolored work items don't participate in flushing or nr_active */
1152 if (color == WORK_NO_COLOR)
1153 goto out_put;
1155 pwq->nr_in_flight[color]--;
1157 pwq->nr_active--;
1158 if (!list_empty(&pwq->delayed_works)) {
1159 /* one down, submit a delayed one */
1160 if (pwq->nr_active < pwq->max_active)
1161 pwq_activate_first_delayed(pwq);
1164 /* is flush in progress and are we at the flushing tip? */
1165 if (likely(pwq->flush_color != color))
1166 goto out_put;
1168 /* are there still in-flight works? */
1169 if (pwq->nr_in_flight[color])
1170 goto out_put;
1172 /* this pwq is done, clear flush_color */
1173 pwq->flush_color = -1;
1176 * If this was the last pwq, wake up the first flusher. It
1177 * will handle the rest.
1179 if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1180 complete(&pwq->wq->first_flusher->done);
1181 out_put:
1182 put_pwq(pwq);
1186 * try_to_grab_pending - steal work item from worklist and disable irq
1187 * @work: work item to steal
1188 * @is_dwork: @work is a delayed_work
1189 * @flags: place to store irq state
1191 * Try to grab PENDING bit of @work. This function can handle @work in any
1192 * stable state - idle, on timer or on worklist.
1194 * Return:
1195 * 1 if @work was pending and we successfully stole PENDING
1196 * 0 if @work was idle and we claimed PENDING
1197 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1198 * -ENOENT if someone else is canceling @work, this state may persist
1199 * for arbitrarily long
1201 * Note:
1202 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1203 * interrupted while holding PENDING and @work off queue, irq must be
1204 * disabled on entry. This, combined with delayed_work->timer being
1205 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1207 * On successful return, >= 0, irq is disabled and the caller is
1208 * responsible for releasing it using local_irq_restore(*@flags).
1210 * This function is safe to call from any context including IRQ handler.
1212 static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1213 unsigned long *flags)
1215 struct worker_pool *pool;
1216 struct pool_workqueue *pwq;
1218 local_irq_save(*flags);
1220 /* try to steal the timer if it exists */
1221 if (is_dwork) {
1222 struct delayed_work *dwork = to_delayed_work(work);
1225 * dwork->timer is irqsafe. If del_timer() fails, it's
1226 * guaranteed that the timer is not queued anywhere and not
1227 * running on the local CPU.
1229 if (likely(del_timer(&dwork->timer)))
1230 return 1;
1233 /* try to claim PENDING the normal way */
1234 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1235 return 0;
1238 * The queueing is in progress, or it is already queued. Try to
1239 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1241 pool = get_work_pool(work);
1242 if (!pool)
1243 goto fail;
1245 spin_lock(&pool->lock);
1247 * work->data is guaranteed to point to pwq only while the work
1248 * item is queued on pwq->wq, and both updating work->data to point
1249 * to pwq on queueing and to pool on dequeueing are done under
1250 * pwq->pool->lock. This in turn guarantees that, if work->data
1251 * points to pwq which is associated with a locked pool, the work
1252 * item is currently queued on that pool.
1254 pwq = get_work_pwq(work);
1255 if (pwq && pwq->pool == pool) {
1256 debug_work_deactivate(work);
1259 * A delayed work item cannot be grabbed directly because
1260 * it might have linked NO_COLOR work items which, if left
1261 * on the delayed_list, will confuse pwq->nr_active
1262 * management later on and cause stall. Make sure the work
1263 * item is activated before grabbing.
1265 if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1266 pwq_activate_delayed_work(work);
1268 list_del_init(&work->entry);
1269 pwq_dec_nr_in_flight(get_work_pwq(work), get_work_color(work));
1271 /* work->data points to pwq iff queued, point to pool */
1272 set_work_pool_and_keep_pending(work, pool->id);
1274 spin_unlock(&pool->lock);
1275 return 1;
1277 spin_unlock(&pool->lock);
1278 fail:
1279 local_irq_restore(*flags);
1280 if (work_is_canceling(work))
1281 return -ENOENT;
1282 cpu_relax();
1283 return -EAGAIN;
1287 * insert_work - insert a work into a pool
1288 * @pwq: pwq @work belongs to
1289 * @work: work to insert
1290 * @head: insertion point
1291 * @extra_flags: extra WORK_STRUCT_* flags to set
1293 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
1294 * work_struct flags.
1296 * CONTEXT:
1297 * spin_lock_irq(pool->lock).
1299 static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1300 struct list_head *head, unsigned int extra_flags)
1302 struct worker_pool *pool = pwq->pool;
1304 /* we own @work, set data and link */
1305 set_work_pwq(work, pwq, extra_flags);
1306 list_add_tail(&work->entry, head);
1307 get_pwq(pwq);
1310 * Ensure either wq_worker_sleeping() sees the above
1311 * list_add_tail() or we see zero nr_running to avoid workers lying
1312 * around lazily while there are works to be processed.
1314 smp_mb();
1316 if (__need_more_worker(pool))
1317 wake_up_worker(pool);
1321 * Test whether @work is being queued from another work executing on the
1322 * same workqueue.
1324 static bool is_chained_work(struct workqueue_struct *wq)
1326 struct worker *worker;
1328 worker = current_wq_worker();
1330 * Return %true iff I'm a worker execuing a work item on @wq. If
1331 * I'm @worker, it's safe to dereference it without locking.
1333 return worker && worker->current_pwq->wq == wq;
1336 static void __queue_work(int cpu, struct workqueue_struct *wq,
1337 struct work_struct *work)
1339 struct pool_workqueue *pwq;
1340 struct worker_pool *last_pool;
1341 struct list_head *worklist;
1342 unsigned int work_flags;
1343 unsigned int req_cpu = cpu;
1346 * While a work item is PENDING && off queue, a task trying to
1347 * steal the PENDING will busy-loop waiting for it to either get
1348 * queued or lose PENDING. Grabbing PENDING and queueing should
1349 * happen with IRQ disabled.
1351 WARN_ON_ONCE(!irqs_disabled());
1353 debug_work_activate(work);
1355 /* if dying, only works from the same workqueue are allowed */
1356 if (unlikely(wq->flags & __WQ_DRAINING) &&
1357 WARN_ON_ONCE(!is_chained_work(wq)))
1358 return;
1359 retry:
1360 if (req_cpu == WORK_CPU_UNBOUND)
1361 cpu = raw_smp_processor_id();
1363 /* pwq which will be used unless @work is executing elsewhere */
1364 if (!(wq->flags & WQ_UNBOUND))
1365 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1366 else
1367 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1370 * If @work was previously on a different pool, it might still be
1371 * running there, in which case the work needs to be queued on that
1372 * pool to guarantee non-reentrancy.
1374 last_pool = get_work_pool(work);
1375 if (last_pool && last_pool != pwq->pool) {
1376 struct worker *worker;
1378 spin_lock(&last_pool->lock);
1380 worker = find_worker_executing_work(last_pool, work);
1382 if (worker && worker->current_pwq->wq == wq) {
1383 pwq = worker->current_pwq;
1384 } else {
1385 /* meh... not running there, queue here */
1386 spin_unlock(&last_pool->lock);
1387 spin_lock(&pwq->pool->lock);
1389 } else {
1390 spin_lock(&pwq->pool->lock);
1394 * pwq is determined and locked. For unbound pools, we could have
1395 * raced with pwq release and it could already be dead. If its
1396 * refcnt is zero, repeat pwq selection. Note that pwqs never die
1397 * without another pwq replacing it in the numa_pwq_tbl or while
1398 * work items are executing on it, so the retrying is guaranteed to
1399 * make forward-progress.
1401 if (unlikely(!pwq->refcnt)) {
1402 if (wq->flags & WQ_UNBOUND) {
1403 spin_unlock(&pwq->pool->lock);
1404 cpu_relax();
1405 goto retry;
1407 /* oops */
1408 WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
1409 wq->name, cpu);
1412 /* pwq determined, queue */
1413 trace_workqueue_queue_work(req_cpu, pwq, work);
1415 if (WARN_ON(!list_empty(&work->entry))) {
1416 spin_unlock(&pwq->pool->lock);
1417 return;
1420 pwq->nr_in_flight[pwq->work_color]++;
1421 work_flags = work_color_to_flags(pwq->work_color);
1423 if (likely(pwq->nr_active < pwq->max_active)) {
1424 trace_workqueue_activate_work(work);
1425 pwq->nr_active++;
1426 worklist = &pwq->pool->worklist;
1427 } else {
1428 work_flags |= WORK_STRUCT_DELAYED;
1429 worklist = &pwq->delayed_works;
1432 insert_work(pwq, work, worklist, work_flags);
1434 spin_unlock(&pwq->pool->lock);
1438 * queue_work_on - queue work on specific cpu
1439 * @cpu: CPU number to execute work on
1440 * @wq: workqueue to use
1441 * @work: work to queue
1443 * We queue the work to a specific CPU, the caller must ensure it
1444 * can't go away.
1446 * Return: %false if @work was already on a queue, %true otherwise.
1448 bool queue_work_on(int cpu, struct workqueue_struct *wq,
1449 struct work_struct *work)
1451 bool ret = false;
1452 unsigned long flags;
1454 local_irq_save(flags);
1456 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1457 __queue_work(cpu, wq, work);
1458 ret = true;
1461 local_irq_restore(flags);
1462 return ret;
1464 EXPORT_SYMBOL(queue_work_on);
1466 void delayed_work_timer_fn(unsigned long __data)
1468 struct delayed_work *dwork = (struct delayed_work *)__data;
1470 /* should have been called from irqsafe timer with irq already off */
1471 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
1473 EXPORT_SYMBOL(delayed_work_timer_fn);
1475 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
1476 struct delayed_work *dwork, unsigned long delay)
1478 struct timer_list *timer = &dwork->timer;
1479 struct work_struct *work = &dwork->work;
1481 WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
1482 timer->data != (unsigned long)dwork);
1483 WARN_ON_ONCE(timer_pending(timer));
1484 WARN_ON_ONCE(!list_empty(&work->entry));
1487 * If @delay is 0, queue @dwork->work immediately. This is for
1488 * both optimization and correctness. The earliest @timer can
1489 * expire is on the closest next tick and delayed_work users depend
1490 * on that there's no such delay when @delay is 0.
1492 if (!delay) {
1493 __queue_work(cpu, wq, &dwork->work);
1494 return;
1497 timer_stats_timer_set_start_info(&dwork->timer);
1499 dwork->wq = wq;
1500 dwork->cpu = cpu;
1501 timer->expires = jiffies + delay;
1503 if (unlikely(cpu != WORK_CPU_UNBOUND))
1504 add_timer_on(timer, cpu);
1505 else
1506 add_timer(timer);
1510 * queue_delayed_work_on - queue work on specific CPU after delay
1511 * @cpu: CPU number to execute work on
1512 * @wq: workqueue to use
1513 * @dwork: work to queue
1514 * @delay: number of jiffies to wait before queueing
1516 * Return: %false if @work was already on a queue, %true otherwise. If
1517 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1518 * execution.
1520 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1521 struct delayed_work *dwork, unsigned long delay)
1523 struct work_struct *work = &dwork->work;
1524 bool ret = false;
1525 unsigned long flags;
1527 /* read the comment in __queue_work() */
1528 local_irq_save(flags);
1530 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1531 __queue_delayed_work(cpu, wq, dwork, delay);
1532 ret = true;
1535 local_irq_restore(flags);
1536 return ret;
1538 EXPORT_SYMBOL(queue_delayed_work_on);
1541 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1542 * @cpu: CPU number to execute work on
1543 * @wq: workqueue to use
1544 * @dwork: work to queue
1545 * @delay: number of jiffies to wait before queueing
1547 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1548 * modify @dwork's timer so that it expires after @delay. If @delay is
1549 * zero, @work is guaranteed to be scheduled immediately regardless of its
1550 * current state.
1552 * Return: %false if @dwork was idle and queued, %true if @dwork was
1553 * pending and its timer was modified.
1555 * This function is safe to call from any context including IRQ handler.
1556 * See try_to_grab_pending() for details.
1558 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
1559 struct delayed_work *dwork, unsigned long delay)
1561 unsigned long flags;
1562 int ret;
1564 do {
1565 ret = try_to_grab_pending(&dwork->work, true, &flags);
1566 } while (unlikely(ret == -EAGAIN));
1568 if (likely(ret >= 0)) {
1569 __queue_delayed_work(cpu, wq, dwork, delay);
1570 local_irq_restore(flags);
1573 /* -ENOENT from try_to_grab_pending() becomes %true */
1574 return ret;
1576 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
1579 * worker_enter_idle - enter idle state
1580 * @worker: worker which is entering idle state
1582 * @worker is entering idle state. Update stats and idle timer if
1583 * necessary.
1585 * LOCKING:
1586 * spin_lock_irq(pool->lock).
1588 static void worker_enter_idle(struct worker *worker)
1590 struct worker_pool *pool = worker->pool;
1592 if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
1593 WARN_ON_ONCE(!list_empty(&worker->entry) &&
1594 (worker->hentry.next || worker->hentry.pprev)))
1595 return;
1597 /* can't use worker_set_flags(), also called from start_worker() */
1598 worker->flags |= WORKER_IDLE;
1599 pool->nr_idle++;
1600 worker->last_active = jiffies;
1602 /* idle_list is LIFO */
1603 list_add(&worker->entry, &pool->idle_list);
1605 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1606 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1609 * Sanity check nr_running. Because wq_unbind_fn() releases
1610 * pool->lock between setting %WORKER_UNBOUND and zapping
1611 * nr_running, the warning may trigger spuriously. Check iff
1612 * unbind is not in progress.
1614 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1615 pool->nr_workers == pool->nr_idle &&
1616 atomic_read(&pool->nr_running));
1620 * worker_leave_idle - leave idle state
1621 * @worker: worker which is leaving idle state
1623 * @worker is leaving idle state. Update stats.
1625 * LOCKING:
1626 * spin_lock_irq(pool->lock).
1628 static void worker_leave_idle(struct worker *worker)
1630 struct worker_pool *pool = worker->pool;
1632 if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
1633 return;
1634 worker_clr_flags(worker, WORKER_IDLE);
1635 pool->nr_idle--;
1636 list_del_init(&worker->entry);
1640 * worker_maybe_bind_and_lock - try to bind %current to worker_pool and lock it
1641 * @pool: target worker_pool
1643 * Bind %current to the cpu of @pool if it is associated and lock @pool.
1645 * Works which are scheduled while the cpu is online must at least be
1646 * scheduled to a worker which is bound to the cpu so that if they are
1647 * flushed from cpu callbacks while cpu is going down, they are
1648 * guaranteed to execute on the cpu.
1650 * This function is to be used by unbound workers and rescuers to bind
1651 * themselves to the target cpu and may race with cpu going down or
1652 * coming online. kthread_bind() can't be used because it may put the
1653 * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1654 * verbatim as it's best effort and blocking and pool may be
1655 * [dis]associated in the meantime.
1657 * This function tries set_cpus_allowed() and locks pool and verifies the
1658 * binding against %POOL_DISASSOCIATED which is set during
1659 * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
1660 * enters idle state or fetches works without dropping lock, it can
1661 * guarantee the scheduling requirement described in the first paragraph.
1663 * CONTEXT:
1664 * Might sleep. Called without any lock but returns with pool->lock
1665 * held.
1667 * Return:
1668 * %true if the associated pool is online (@worker is successfully
1669 * bound), %false if offline.
1671 static bool worker_maybe_bind_and_lock(struct worker_pool *pool)
1672 __acquires(&pool->lock)
1674 while (true) {
1676 * The following call may fail, succeed or succeed
1677 * without actually migrating the task to the cpu if
1678 * it races with cpu hotunplug operation. Verify
1679 * against POOL_DISASSOCIATED.
1681 if (!(pool->flags & POOL_DISASSOCIATED))
1682 set_cpus_allowed_ptr(current, pool->attrs->cpumask);
1684 spin_lock_irq(&pool->lock);
1685 if (pool->flags & POOL_DISASSOCIATED)
1686 return false;
1687 if (task_cpu(current) == pool->cpu &&
1688 cpumask_equal(&current->cpus_allowed, pool->attrs->cpumask))
1689 return true;
1690 spin_unlock_irq(&pool->lock);
1693 * We've raced with CPU hot[un]plug. Give it a breather
1694 * and retry migration. cond_resched() is required here;
1695 * otherwise, we might deadlock against cpu_stop trying to
1696 * bring down the CPU on non-preemptive kernel.
1698 cpu_relax();
1699 cond_resched();
1703 static struct worker *alloc_worker(void)
1705 struct worker *worker;
1707 worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1708 if (worker) {
1709 INIT_LIST_HEAD(&worker->entry);
1710 INIT_LIST_HEAD(&worker->scheduled);
1711 /* on creation a worker is in !idle && prep state */
1712 worker->flags = WORKER_PREP;
1714 return worker;
1718 * create_worker - create a new workqueue worker
1719 * @pool: pool the new worker will belong to
1721 * Create a new worker which is bound to @pool. The returned worker
1722 * can be started by calling start_worker() or destroyed using
1723 * destroy_worker().
1725 * CONTEXT:
1726 * Might sleep. Does GFP_KERNEL allocations.
1728 * Return:
1729 * Pointer to the newly created worker.
1731 static struct worker *create_worker(struct worker_pool *pool)
1733 struct worker *worker = NULL;
1734 int id = -1;
1735 char id_buf[16];
1737 lockdep_assert_held(&pool->manager_mutex);
1740 * ID is needed to determine kthread name. Allocate ID first
1741 * without installing the pointer.
1743 idr_preload(GFP_KERNEL);
1744 spin_lock_irq(&pool->lock);
1746 id = idr_alloc(&pool->worker_idr, NULL, 0, 0, GFP_NOWAIT);
1748 spin_unlock_irq(&pool->lock);
1749 idr_preload_end();
1750 if (id < 0)
1751 goto fail;
1753 worker = alloc_worker();
1754 if (!worker)
1755 goto fail;
1757 worker->pool = pool;
1758 worker->id = id;
1760 if (pool->cpu >= 0)
1761 snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
1762 pool->attrs->nice < 0 ? "H" : "");
1763 else
1764 snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
1766 worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
1767 "kworker/%s", id_buf);
1768 if (IS_ERR(worker->task))
1769 goto fail;
1772 * set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
1773 * online CPUs. It'll be re-applied when any of the CPUs come up.
1775 set_user_nice(worker->task, pool->attrs->nice);
1776 set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
1778 /* prevent userland from meddling with cpumask of workqueue workers */
1779 worker->task->flags |= PF_NO_SETAFFINITY;
1782 * The caller is responsible for ensuring %POOL_DISASSOCIATED
1783 * remains stable across this function. See the comments above the
1784 * flag definition for details.
1786 if (pool->flags & POOL_DISASSOCIATED)
1787 worker->flags |= WORKER_UNBOUND;
1789 /* successful, commit the pointer to idr */
1790 spin_lock_irq(&pool->lock);
1791 idr_replace(&pool->worker_idr, worker, worker->id);
1792 spin_unlock_irq(&pool->lock);
1794 return worker;
1796 fail:
1797 if (id >= 0) {
1798 spin_lock_irq(&pool->lock);
1799 idr_remove(&pool->worker_idr, id);
1800 spin_unlock_irq(&pool->lock);
1802 kfree(worker);
1803 return NULL;
1807 * start_worker - start a newly created worker
1808 * @worker: worker to start
1810 * Make the pool aware of @worker and start it.
1812 * CONTEXT:
1813 * spin_lock_irq(pool->lock).
1815 static void start_worker(struct worker *worker)
1817 worker->flags |= WORKER_STARTED;
1818 worker->pool->nr_workers++;
1819 worker_enter_idle(worker);
1820 wake_up_process(worker->task);
1824 * create_and_start_worker - create and start a worker for a pool
1825 * @pool: the target pool
1827 * Grab the managership of @pool and create and start a new worker for it.
1829 * Return: 0 on success. A negative error code otherwise.
1831 static int create_and_start_worker(struct worker_pool *pool)
1833 struct worker *worker;
1835 mutex_lock(&pool->manager_mutex);
1837 worker = create_worker(pool);
1838 if (worker) {
1839 spin_lock_irq(&pool->lock);
1840 start_worker(worker);
1841 spin_unlock_irq(&pool->lock);
1844 mutex_unlock(&pool->manager_mutex);
1846 return worker ? 0 : -ENOMEM;
1850 * destroy_worker - destroy a workqueue worker
1851 * @worker: worker to be destroyed
1853 * Destroy @worker and adjust @pool stats accordingly.
1855 * CONTEXT:
1856 * spin_lock_irq(pool->lock) which is released and regrabbed.
1858 static void destroy_worker(struct worker *worker)
1860 struct worker_pool *pool = worker->pool;
1862 lockdep_assert_held(&pool->manager_mutex);
1863 lockdep_assert_held(&pool->lock);
1865 /* sanity check frenzy */
1866 if (WARN_ON(worker->current_work) ||
1867 WARN_ON(!list_empty(&worker->scheduled)))
1868 return;
1870 if (worker->flags & WORKER_STARTED)
1871 pool->nr_workers--;
1872 if (worker->flags & WORKER_IDLE)
1873 pool->nr_idle--;
1876 * Once WORKER_DIE is set, the kworker may destroy itself at any
1877 * point. Pin to ensure the task stays until we're done with it.
1879 get_task_struct(worker->task);
1881 list_del_init(&worker->entry);
1882 worker->flags |= WORKER_DIE;
1884 idr_remove(&pool->worker_idr, worker->id);
1886 spin_unlock_irq(&pool->lock);
1888 kthread_stop(worker->task);
1889 put_task_struct(worker->task);
1890 kfree(worker);
1892 spin_lock_irq(&pool->lock);
1895 static void idle_worker_timeout(unsigned long __pool)
1897 struct worker_pool *pool = (void *)__pool;
1899 spin_lock_irq(&pool->lock);
1901 if (too_many_workers(pool)) {
1902 struct worker *worker;
1903 unsigned long expires;
1905 /* idle_list is kept in LIFO order, check the last one */
1906 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1907 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1909 if (time_before(jiffies, expires))
1910 mod_timer(&pool->idle_timer, expires);
1911 else {
1912 /* it's been idle for too long, wake up manager */
1913 pool->flags |= POOL_MANAGE_WORKERS;
1914 wake_up_worker(pool);
1918 spin_unlock_irq(&pool->lock);
1921 static void send_mayday(struct work_struct *work)
1923 struct pool_workqueue *pwq = get_work_pwq(work);
1924 struct workqueue_struct *wq = pwq->wq;
1926 lockdep_assert_held(&wq_mayday_lock);
1928 if (!wq->rescuer)
1929 return;
1931 /* mayday mayday mayday */
1932 if (list_empty(&pwq->mayday_node)) {
1934 * If @pwq is for an unbound wq, its base ref may be put at
1935 * any time due to an attribute change. Pin @pwq until the
1936 * rescuer is done with it.
1938 get_pwq(pwq);
1939 list_add_tail(&pwq->mayday_node, &wq->maydays);
1940 wake_up_process(wq->rescuer->task);
1944 static void pool_mayday_timeout(unsigned long __pool)
1946 struct worker_pool *pool = (void *)__pool;
1947 struct work_struct *work;
1949 spin_lock_irq(&wq_mayday_lock); /* for wq->maydays */
1950 spin_lock(&pool->lock);
1952 if (need_to_create_worker(pool)) {
1954 * We've been trying to create a new worker but
1955 * haven't been successful. We might be hitting an
1956 * allocation deadlock. Send distress signals to
1957 * rescuers.
1959 list_for_each_entry(work, &pool->worklist, entry)
1960 send_mayday(work);
1963 spin_unlock(&pool->lock);
1964 spin_unlock_irq(&wq_mayday_lock);
1966 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1970 * maybe_create_worker - create a new worker if necessary
1971 * @pool: pool to create a new worker for
1973 * Create a new worker for @pool if necessary. @pool is guaranteed to
1974 * have at least one idle worker on return from this function. If
1975 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1976 * sent to all rescuers with works scheduled on @pool to resolve
1977 * possible allocation deadlock.
1979 * On return, need_to_create_worker() is guaranteed to be %false and
1980 * may_start_working() %true.
1982 * LOCKING:
1983 * spin_lock_irq(pool->lock) which may be released and regrabbed
1984 * multiple times. Does GFP_KERNEL allocations. Called only from
1985 * manager.
1987 static void maybe_create_worker(struct worker_pool *pool)
1988 __releases(&pool->lock)
1989 __acquires(&pool->lock)
1991 if (!need_to_create_worker(pool))
1992 return;
1993 restart:
1994 spin_unlock_irq(&pool->lock);
1996 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1997 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1999 while (true) {
2000 struct worker *worker;
2002 worker = create_worker(pool);
2003 if (worker) {
2004 del_timer_sync(&pool->mayday_timer);
2005 spin_lock_irq(&pool->lock);
2006 start_worker(worker);
2007 if (WARN_ON_ONCE(need_to_create_worker(pool)))
2008 goto restart;
2009 return;
2012 if (!need_to_create_worker(pool))
2013 break;
2015 __set_current_state(TASK_INTERRUPTIBLE);
2016 schedule_timeout(CREATE_COOLDOWN);
2018 if (!need_to_create_worker(pool))
2019 break;
2022 del_timer_sync(&pool->mayday_timer);
2023 spin_lock_irq(&pool->lock);
2024 if (need_to_create_worker(pool))
2025 goto restart;
2026 return;
2030 * maybe_destroy_worker - destroy workers which have been idle for a while
2031 * @pool: pool to destroy workers for
2033 * Destroy @pool workers which have been idle for longer than
2034 * IDLE_WORKER_TIMEOUT.
2036 * LOCKING:
2037 * spin_lock_irq(pool->lock) which may be released and regrabbed
2038 * multiple times. Called only from manager.
2040 static void maybe_destroy_workers(struct worker_pool *pool)
2042 while (too_many_workers(pool)) {
2043 struct worker *worker;
2044 unsigned long expires;
2046 worker = list_entry(pool->idle_list.prev, struct worker, entry);
2047 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2049 if (time_before(jiffies, expires)) {
2050 mod_timer(&pool->idle_timer, expires);
2051 break;
2054 destroy_worker(worker);
2059 * manage_workers - manage worker pool
2060 * @worker: self
2062 * Assume the manager role and manage the worker pool @worker belongs
2063 * to. At any given time, there can be only zero or one manager per
2064 * pool. The exclusion is handled automatically by this function.
2066 * The caller can safely start processing works on false return. On
2067 * true return, it's guaranteed that need_to_create_worker() is false
2068 * and may_start_working() is true.
2070 * CONTEXT:
2071 * spin_lock_irq(pool->lock) which may be released and regrabbed
2072 * multiple times. Does GFP_KERNEL allocations.
2074 * Return:
2075 * %false if the pool doesn't need management and the caller can safely
2076 * start processing works, %true if management function was performed and
2077 * the conditions that the caller verified before calling the function may
2078 * no longer be true.
2080 static bool manage_workers(struct worker *worker)
2082 struct worker_pool *pool = worker->pool;
2085 * Managership is governed by two mutexes - manager_arb and
2086 * manager_mutex. manager_arb handles arbitration of manager role.
2087 * Anyone who successfully grabs manager_arb wins the arbitration
2088 * and becomes the manager. mutex_trylock() on pool->manager_arb
2089 * failure while holding pool->lock reliably indicates that someone
2090 * else is managing the pool and the worker which failed trylock
2091 * can proceed to executing work items. This means that anyone
2092 * grabbing manager_arb is responsible for actually performing
2093 * manager duties. If manager_arb is grabbed and released without
2094 * actual management, the pool may stall indefinitely.
2096 * manager_mutex is used for exclusion of actual management
2097 * operations. The holder of manager_mutex can be sure that none
2098 * of management operations, including creation and destruction of
2099 * workers, won't take place until the mutex is released. Because
2100 * manager_mutex doesn't interfere with manager role arbitration,
2101 * it is guaranteed that the pool's management, while may be
2102 * delayed, won't be disturbed by someone else grabbing
2103 * manager_mutex.
2105 if (!mutex_trylock(&pool->manager_arb))
2106 return false;
2109 * With manager arbitration won, manager_mutex would be free in
2110 * most cases. trylock first without dropping @pool->lock.
2112 if (unlikely(!mutex_trylock(&pool->manager_mutex))) {
2113 spin_unlock_irq(&pool->lock);
2114 mutex_lock(&pool->manager_mutex);
2115 spin_lock_irq(&pool->lock);
2118 pool->flags &= ~POOL_MANAGE_WORKERS;
2121 * Destroy and then create so that may_start_working() is true
2122 * on return.
2124 maybe_destroy_workers(pool);
2125 maybe_create_worker(pool);
2127 mutex_unlock(&pool->manager_mutex);
2128 mutex_unlock(&pool->manager_arb);
2129 return true;
2133 * process_one_work - process single work
2134 * @worker: self
2135 * @work: work to process
2137 * Process @work. This function contains all the logics necessary to
2138 * process a single work including synchronization against and
2139 * interaction with other workers on the same cpu, queueing and
2140 * flushing. As long as context requirement is met, any worker can
2141 * call this function to process a work.
2143 * CONTEXT:
2144 * spin_lock_irq(pool->lock) which is released and regrabbed.
2146 static void process_one_work(struct worker *worker, struct work_struct *work)
2147 __releases(&pool->lock)
2148 __acquires(&pool->lock)
2150 struct pool_workqueue *pwq = get_work_pwq(work);
2151 struct worker_pool *pool = worker->pool;
2152 bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
2153 int work_color;
2154 struct worker *collision;
2155 #ifdef CONFIG_LOCKDEP
2157 * It is permissible to free the struct work_struct from
2158 * inside the function that is called from it, this we need to
2159 * take into account for lockdep too. To avoid bogus "held
2160 * lock freed" warnings as well as problems when looking into
2161 * work->lockdep_map, make a copy and use that here.
2163 struct lockdep_map lockdep_map;
2165 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
2166 #endif
2168 * Ensure we're on the correct CPU. DISASSOCIATED test is
2169 * necessary to avoid spurious warnings from rescuers servicing the
2170 * unbound or a disassociated pool.
2172 WARN_ON_ONCE(!(worker->flags & WORKER_UNBOUND) &&
2173 !(pool->flags & POOL_DISASSOCIATED) &&
2174 raw_smp_processor_id() != pool->cpu);
2177 * A single work shouldn't be executed concurrently by
2178 * multiple workers on a single cpu. Check whether anyone is
2179 * already processing the work. If so, defer the work to the
2180 * currently executing one.
2182 collision = find_worker_executing_work(pool, work);
2183 if (unlikely(collision)) {
2184 move_linked_works(work, &collision->scheduled, NULL);
2185 return;
2188 /* claim and dequeue */
2189 debug_work_deactivate(work);
2190 hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2191 worker->current_work = work;
2192 worker->current_func = work->func;
2193 worker->current_pwq = pwq;
2194 work_color = get_work_color(work);
2196 list_del_init(&work->entry);
2199 * CPU intensive works don't participate in concurrency
2200 * management. They're the scheduler's responsibility.
2202 if (unlikely(cpu_intensive))
2203 worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
2206 * Unbound pool isn't concurrency managed and work items should be
2207 * executed ASAP. Wake up another worker if necessary.
2209 if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
2210 wake_up_worker(pool);
2213 * Record the last pool and clear PENDING which should be the last
2214 * update to @work. Also, do this inside @pool->lock so that
2215 * PENDING and queued state changes happen together while IRQ is
2216 * disabled.
2218 set_work_pool_and_clear_pending(work, pool->id);
2220 spin_unlock_irq(&pool->lock);
2222 lock_map_acquire_read(&pwq->wq->lockdep_map);
2223 lock_map_acquire(&lockdep_map);
2224 trace_workqueue_execute_start(work);
2225 worker->current_func(work);
2227 * While we must be careful to not use "work" after this, the trace
2228 * point will only record its address.
2230 trace_workqueue_execute_end(work);
2231 lock_map_release(&lockdep_map);
2232 lock_map_release(&pwq->wq->lockdep_map);
2234 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2235 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2236 " last function: %pf\n",
2237 current->comm, preempt_count(), task_pid_nr(current),
2238 worker->current_func);
2239 debug_show_held_locks(current);
2240 dump_stack();
2244 * The following prevents a kworker from hogging CPU on !PREEMPT
2245 * kernels, where a requeueing work item waiting for something to
2246 * happen could deadlock with stop_machine as such work item could
2247 * indefinitely requeue itself while all other CPUs are trapped in
2248 * stop_machine.
2250 cond_resched();
2252 spin_lock_irq(&pool->lock);
2254 /* clear cpu intensive status */
2255 if (unlikely(cpu_intensive))
2256 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2258 /* we're done with it, release */
2259 hash_del(&worker->hentry);
2260 worker->current_work = NULL;
2261 worker->current_func = NULL;
2262 worker->current_pwq = NULL;
2263 worker->desc_valid = false;
2264 pwq_dec_nr_in_flight(pwq, work_color);
2268 * process_scheduled_works - process scheduled works
2269 * @worker: self
2271 * Process all scheduled works. Please note that the scheduled list
2272 * may change while processing a work, so this function repeatedly
2273 * fetches a work from the top and executes it.
2275 * CONTEXT:
2276 * spin_lock_irq(pool->lock) which may be released and regrabbed
2277 * multiple times.
2279 static void process_scheduled_works(struct worker *worker)
2281 while (!list_empty(&worker->scheduled)) {
2282 struct work_struct *work = list_first_entry(&worker->scheduled,
2283 struct work_struct, entry);
2284 process_one_work(worker, work);
2289 * worker_thread - the worker thread function
2290 * @__worker: self
2292 * The worker thread function. All workers belong to a worker_pool -
2293 * either a per-cpu one or dynamic unbound one. These workers process all
2294 * work items regardless of their specific target workqueue. The only
2295 * exception is work items which belong to workqueues with a rescuer which
2296 * will be explained in rescuer_thread().
2298 * Return: 0
2300 static int worker_thread(void *__worker)
2302 struct worker *worker = __worker;
2303 struct worker_pool *pool = worker->pool;
2305 /* tell the scheduler that this is a workqueue worker */
2306 worker->task->flags |= PF_WQ_WORKER;
2307 woke_up:
2308 spin_lock_irq(&pool->lock);
2310 /* am I supposed to die? */
2311 if (unlikely(worker->flags & WORKER_DIE)) {
2312 spin_unlock_irq(&pool->lock);
2313 WARN_ON_ONCE(!list_empty(&worker->entry));
2314 worker->task->flags &= ~PF_WQ_WORKER;
2315 return 0;
2318 worker_leave_idle(worker);
2319 recheck:
2320 /* no more worker necessary? */
2321 if (!need_more_worker(pool))
2322 goto sleep;
2324 /* do we need to manage? */
2325 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2326 goto recheck;
2329 * ->scheduled list can only be filled while a worker is
2330 * preparing to process a work or actually processing it.
2331 * Make sure nobody diddled with it while I was sleeping.
2333 WARN_ON_ONCE(!list_empty(&worker->scheduled));
2336 * Finish PREP stage. We're guaranteed to have at least one idle
2337 * worker or that someone else has already assumed the manager
2338 * role. This is where @worker starts participating in concurrency
2339 * management if applicable and concurrency management is restored
2340 * after being rebound. See rebind_workers() for details.
2342 worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2344 do {
2345 struct work_struct *work =
2346 list_first_entry(&pool->worklist,
2347 struct work_struct, entry);
2349 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2350 /* optimization path, not strictly necessary */
2351 process_one_work(worker, work);
2352 if (unlikely(!list_empty(&worker->scheduled)))
2353 process_scheduled_works(worker);
2354 } else {
2355 move_linked_works(work, &worker->scheduled, NULL);
2356 process_scheduled_works(worker);
2358 } while (keep_working(pool));
2360 worker_set_flags(worker, WORKER_PREP, false);
2361 sleep:
2362 if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
2363 goto recheck;
2366 * pool->lock is held and there's no work to process and no need to
2367 * manage, sleep. Workers are woken up only while holding
2368 * pool->lock or from local cpu, so setting the current state
2369 * before releasing pool->lock is enough to prevent losing any
2370 * event.
2372 worker_enter_idle(worker);
2373 __set_current_state(TASK_INTERRUPTIBLE);
2374 spin_unlock_irq(&pool->lock);
2375 schedule();
2376 goto woke_up;
2380 * rescuer_thread - the rescuer thread function
2381 * @__rescuer: self
2383 * Workqueue rescuer thread function. There's one rescuer for each
2384 * workqueue which has WQ_MEM_RECLAIM set.
2386 * Regular work processing on a pool may block trying to create a new
2387 * worker which uses GFP_KERNEL allocation which has slight chance of
2388 * developing into deadlock if some works currently on the same queue
2389 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2390 * the problem rescuer solves.
2392 * When such condition is possible, the pool summons rescuers of all
2393 * workqueues which have works queued on the pool and let them process
2394 * those works so that forward progress can be guaranteed.
2396 * This should happen rarely.
2398 * Return: 0
2400 static int rescuer_thread(void *__rescuer)
2402 struct worker *rescuer = __rescuer;
2403 struct workqueue_struct *wq = rescuer->rescue_wq;
2404 struct list_head *scheduled = &rescuer->scheduled;
2405 bool should_stop;
2407 set_user_nice(current, RESCUER_NICE_LEVEL);
2410 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2411 * doesn't participate in concurrency management.
2413 rescuer->task->flags |= PF_WQ_WORKER;
2414 repeat:
2415 set_current_state(TASK_INTERRUPTIBLE);
2418 * By the time the rescuer is requested to stop, the workqueue
2419 * shouldn't have any work pending, but @wq->maydays may still have
2420 * pwq(s) queued. This can happen by non-rescuer workers consuming
2421 * all the work items before the rescuer got to them. Go through
2422 * @wq->maydays processing before acting on should_stop so that the
2423 * list is always empty on exit.
2425 should_stop = kthread_should_stop();
2427 /* see whether any pwq is asking for help */
2428 spin_lock_irq(&wq_mayday_lock);
2430 while (!list_empty(&wq->maydays)) {
2431 struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2432 struct pool_workqueue, mayday_node);
2433 struct worker_pool *pool = pwq->pool;
2434 struct work_struct *work, *n;
2436 __set_current_state(TASK_RUNNING);
2437 list_del_init(&pwq->mayday_node);
2439 spin_unlock_irq(&wq_mayday_lock);
2441 /* migrate to the target cpu if possible */
2442 worker_maybe_bind_and_lock(pool);
2443 rescuer->pool = pool;
2446 * Slurp in all works issued via this workqueue and
2447 * process'em.
2449 WARN_ON_ONCE(!list_empty(&rescuer->scheduled));
2450 list_for_each_entry_safe(work, n, &pool->worklist, entry)
2451 if (get_work_pwq(work) == pwq)
2452 move_linked_works(work, scheduled, &n);
2454 process_scheduled_works(rescuer);
2457 * Put the reference grabbed by send_mayday(). @pool won't
2458 * go away while we're holding its lock.
2460 put_pwq(pwq);
2463 * Leave this pool. If keep_working() is %true, notify a
2464 * regular worker; otherwise, we end up with 0 concurrency
2465 * and stalling the execution.
2467 if (keep_working(pool))
2468 wake_up_worker(pool);
2470 rescuer->pool = NULL;
2471 spin_unlock(&pool->lock);
2472 spin_lock(&wq_mayday_lock);
2475 spin_unlock_irq(&wq_mayday_lock);
2477 if (should_stop) {
2478 __set_current_state(TASK_RUNNING);
2479 rescuer->task->flags &= ~PF_WQ_WORKER;
2480 return 0;
2483 /* rescuers should never participate in concurrency management */
2484 WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2485 schedule();
2486 goto repeat;
2489 struct wq_barrier {
2490 struct work_struct work;
2491 struct completion done;
2494 static void wq_barrier_func(struct work_struct *work)
2496 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2497 complete(&barr->done);
2501 * insert_wq_barrier - insert a barrier work
2502 * @pwq: pwq to insert barrier into
2503 * @barr: wq_barrier to insert
2504 * @target: target work to attach @barr to
2505 * @worker: worker currently executing @target, NULL if @target is not executing
2507 * @barr is linked to @target such that @barr is completed only after
2508 * @target finishes execution. Please note that the ordering
2509 * guarantee is observed only with respect to @target and on the local
2510 * cpu.
2512 * Currently, a queued barrier can't be canceled. This is because
2513 * try_to_grab_pending() can't determine whether the work to be
2514 * grabbed is at the head of the queue and thus can't clear LINKED
2515 * flag of the previous work while there must be a valid next work
2516 * after a work with LINKED flag set.
2518 * Note that when @worker is non-NULL, @target may be modified
2519 * underneath us, so we can't reliably determine pwq from @target.
2521 * CONTEXT:
2522 * spin_lock_irq(pool->lock).
2524 static void insert_wq_barrier(struct pool_workqueue *pwq,
2525 struct wq_barrier *barr,
2526 struct work_struct *target, struct worker *worker)
2528 struct list_head *head;
2529 unsigned int linked = 0;
2532 * debugobject calls are safe here even with pool->lock locked
2533 * as we know for sure that this will not trigger any of the
2534 * checks and call back into the fixup functions where we
2535 * might deadlock.
2537 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2538 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2539 init_completion(&barr->done);
2542 * If @target is currently being executed, schedule the
2543 * barrier to the worker; otherwise, put it after @target.
2545 if (worker)
2546 head = worker->scheduled.next;
2547 else {
2548 unsigned long *bits = work_data_bits(target);
2550 head = target->entry.next;
2551 /* there can already be other linked works, inherit and set */
2552 linked = *bits & WORK_STRUCT_LINKED;
2553 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2556 debug_work_activate(&barr->work);
2557 insert_work(pwq, &barr->work, head,
2558 work_color_to_flags(WORK_NO_COLOR) | linked);
2562 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
2563 * @wq: workqueue being flushed
2564 * @flush_color: new flush color, < 0 for no-op
2565 * @work_color: new work color, < 0 for no-op
2567 * Prepare pwqs for workqueue flushing.
2569 * If @flush_color is non-negative, flush_color on all pwqs should be
2570 * -1. If no pwq has in-flight commands at the specified color, all
2571 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
2572 * has in flight commands, its pwq->flush_color is set to
2573 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
2574 * wakeup logic is armed and %true is returned.
2576 * The caller should have initialized @wq->first_flusher prior to
2577 * calling this function with non-negative @flush_color. If
2578 * @flush_color is negative, no flush color update is done and %false
2579 * is returned.
2581 * If @work_color is non-negative, all pwqs should have the same
2582 * work_color which is previous to @work_color and all will be
2583 * advanced to @work_color.
2585 * CONTEXT:
2586 * mutex_lock(wq->mutex).
2588 * Return:
2589 * %true if @flush_color >= 0 and there's something to flush. %false
2590 * otherwise.
2592 static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
2593 int flush_color, int work_color)
2595 bool wait = false;
2596 struct pool_workqueue *pwq;
2598 if (flush_color >= 0) {
2599 WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2600 atomic_set(&wq->nr_pwqs_to_flush, 1);
2603 for_each_pwq(pwq, wq) {
2604 struct worker_pool *pool = pwq->pool;
2606 spin_lock_irq(&pool->lock);
2608 if (flush_color >= 0) {
2609 WARN_ON_ONCE(pwq->flush_color != -1);
2611 if (pwq->nr_in_flight[flush_color]) {
2612 pwq->flush_color = flush_color;
2613 atomic_inc(&wq->nr_pwqs_to_flush);
2614 wait = true;
2618 if (work_color >= 0) {
2619 WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2620 pwq->work_color = work_color;
2623 spin_unlock_irq(&pool->lock);
2626 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
2627 complete(&wq->first_flusher->done);
2629 return wait;
2633 * flush_workqueue - ensure that any scheduled work has run to completion.
2634 * @wq: workqueue to flush
2636 * This function sleeps until all work items which were queued on entry
2637 * have finished execution, but it is not livelocked by new incoming ones.
2639 void flush_workqueue(struct workqueue_struct *wq)
2641 struct wq_flusher this_flusher = {
2642 .list = LIST_HEAD_INIT(this_flusher.list),
2643 .flush_color = -1,
2644 .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
2646 int next_color;
2648 lock_map_acquire(&wq->lockdep_map);
2649 lock_map_release(&wq->lockdep_map);
2651 mutex_lock(&wq->mutex);
2654 * Start-to-wait phase
2656 next_color = work_next_color(wq->work_color);
2658 if (next_color != wq->flush_color) {
2660 * Color space is not full. The current work_color
2661 * becomes our flush_color and work_color is advanced
2662 * by one.
2664 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
2665 this_flusher.flush_color = wq->work_color;
2666 wq->work_color = next_color;
2668 if (!wq->first_flusher) {
2669 /* no flush in progress, become the first flusher */
2670 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2672 wq->first_flusher = &this_flusher;
2674 if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
2675 wq->work_color)) {
2676 /* nothing to flush, done */
2677 wq->flush_color = next_color;
2678 wq->first_flusher = NULL;
2679 goto out_unlock;
2681 } else {
2682 /* wait in queue */
2683 WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
2684 list_add_tail(&this_flusher.list, &wq->flusher_queue);
2685 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2687 } else {
2689 * Oops, color space is full, wait on overflow queue.
2690 * The next flush completion will assign us
2691 * flush_color and transfer to flusher_queue.
2693 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2696 mutex_unlock(&wq->mutex);
2698 wait_for_completion(&this_flusher.done);
2701 * Wake-up-and-cascade phase
2703 * First flushers are responsible for cascading flushes and
2704 * handling overflow. Non-first flushers can simply return.
2706 if (wq->first_flusher != &this_flusher)
2707 return;
2709 mutex_lock(&wq->mutex);
2711 /* we might have raced, check again with mutex held */
2712 if (wq->first_flusher != &this_flusher)
2713 goto out_unlock;
2715 wq->first_flusher = NULL;
2717 WARN_ON_ONCE(!list_empty(&this_flusher.list));
2718 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2720 while (true) {
2721 struct wq_flusher *next, *tmp;
2723 /* complete all the flushers sharing the current flush color */
2724 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2725 if (next->flush_color != wq->flush_color)
2726 break;
2727 list_del_init(&next->list);
2728 complete(&next->done);
2731 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
2732 wq->flush_color != work_next_color(wq->work_color));
2734 /* this flush_color is finished, advance by one */
2735 wq->flush_color = work_next_color(wq->flush_color);
2737 /* one color has been freed, handle overflow queue */
2738 if (!list_empty(&wq->flusher_overflow)) {
2740 * Assign the same color to all overflowed
2741 * flushers, advance work_color and append to
2742 * flusher_queue. This is the start-to-wait
2743 * phase for these overflowed flushers.
2745 list_for_each_entry(tmp, &wq->flusher_overflow, list)
2746 tmp->flush_color = wq->work_color;
2748 wq->work_color = work_next_color(wq->work_color);
2750 list_splice_tail_init(&wq->flusher_overflow,
2751 &wq->flusher_queue);
2752 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2755 if (list_empty(&wq->flusher_queue)) {
2756 WARN_ON_ONCE(wq->flush_color != wq->work_color);
2757 break;
2761 * Need to flush more colors. Make the next flusher
2762 * the new first flusher and arm pwqs.
2764 WARN_ON_ONCE(wq->flush_color == wq->work_color);
2765 WARN_ON_ONCE(wq->flush_color != next->flush_color);
2767 list_del_init(&next->list);
2768 wq->first_flusher = next;
2770 if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
2771 break;
2774 * Meh... this color is already done, clear first
2775 * flusher and repeat cascading.
2777 wq->first_flusher = NULL;
2780 out_unlock:
2781 mutex_unlock(&wq->mutex);
2783 EXPORT_SYMBOL_GPL(flush_workqueue);
2786 * drain_workqueue - drain a workqueue
2787 * @wq: workqueue to drain
2789 * Wait until the workqueue becomes empty. While draining is in progress,
2790 * only chain queueing is allowed. IOW, only currently pending or running
2791 * work items on @wq can queue further work items on it. @wq is flushed
2792 * repeatedly until it becomes empty. The number of flushing is detemined
2793 * by the depth of chaining and should be relatively short. Whine if it
2794 * takes too long.
2796 void drain_workqueue(struct workqueue_struct *wq)
2798 unsigned int flush_cnt = 0;
2799 struct pool_workqueue *pwq;
2802 * __queue_work() needs to test whether there are drainers, is much
2803 * hotter than drain_workqueue() and already looks at @wq->flags.
2804 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
2806 mutex_lock(&wq->mutex);
2807 if (!wq->nr_drainers++)
2808 wq->flags |= __WQ_DRAINING;
2809 mutex_unlock(&wq->mutex);
2810 reflush:
2811 flush_workqueue(wq);
2813 mutex_lock(&wq->mutex);
2815 for_each_pwq(pwq, wq) {
2816 bool drained;
2818 spin_lock_irq(&pwq->pool->lock);
2819 drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
2820 spin_unlock_irq(&pwq->pool->lock);
2822 if (drained)
2823 continue;
2825 if (++flush_cnt == 10 ||
2826 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2827 pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
2828 wq->name, flush_cnt);
2830 mutex_unlock(&wq->mutex);
2831 goto reflush;
2834 if (!--wq->nr_drainers)
2835 wq->flags &= ~__WQ_DRAINING;
2836 mutex_unlock(&wq->mutex);
2838 EXPORT_SYMBOL_GPL(drain_workqueue);
2840 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2842 struct worker *worker = NULL;
2843 struct worker_pool *pool;
2844 struct pool_workqueue *pwq;
2846 might_sleep();
2848 local_irq_disable();
2849 pool = get_work_pool(work);
2850 if (!pool) {
2851 local_irq_enable();
2852 return false;
2855 spin_lock(&pool->lock);
2856 /* see the comment in try_to_grab_pending() with the same code */
2857 pwq = get_work_pwq(work);
2858 if (pwq) {
2859 if (unlikely(pwq->pool != pool))
2860 goto already_gone;
2861 } else {
2862 worker = find_worker_executing_work(pool, work);
2863 if (!worker)
2864 goto already_gone;
2865 pwq = worker->current_pwq;
2868 insert_wq_barrier(pwq, barr, work, worker);
2869 spin_unlock_irq(&pool->lock);
2872 * If @max_active is 1 or rescuer is in use, flushing another work
2873 * item on the same workqueue may lead to deadlock. Make sure the
2874 * flusher is not running on the same workqueue by verifying write
2875 * access.
2877 if (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)
2878 lock_map_acquire(&pwq->wq->lockdep_map);
2879 else
2880 lock_map_acquire_read(&pwq->wq->lockdep_map);
2881 lock_map_release(&pwq->wq->lockdep_map);
2883 return true;
2884 already_gone:
2885 spin_unlock_irq(&pool->lock);
2886 return false;
2889 static bool __flush_work(struct work_struct *work)
2891 struct wq_barrier barr;
2893 if (start_flush_work(work, &barr)) {
2894 wait_for_completion(&barr.done);
2895 destroy_work_on_stack(&barr.work);
2896 return true;
2897 } else {
2898 return false;
2903 * flush_work - wait for a work to finish executing the last queueing instance
2904 * @work: the work to flush
2906 * Wait until @work has finished execution. @work is guaranteed to be idle
2907 * on return if it hasn't been requeued since flush started.
2909 * Return:
2910 * %true if flush_work() waited for the work to finish execution,
2911 * %false if it was already idle.
2913 bool flush_work(struct work_struct *work)
2915 lock_map_acquire(&work->lockdep_map);
2916 lock_map_release(&work->lockdep_map);
2918 return __flush_work(work);
2920 EXPORT_SYMBOL_GPL(flush_work);
2922 struct cwt_wait {
2923 wait_queue_t wait;
2924 struct work_struct *work;
2927 static int cwt_wakefn(wait_queue_t *wait, unsigned mode, int sync, void *key)
2929 struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
2931 if (cwait->work != key)
2932 return 0;
2933 return autoremove_wake_function(wait, mode, sync, key);
2936 static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2938 static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
2939 unsigned long flags;
2940 int ret;
2942 do {
2943 ret = try_to_grab_pending(work, is_dwork, &flags);
2945 * If someone else is already canceling, wait for it to
2946 * finish. flush_work() doesn't work for PREEMPT_NONE
2947 * because we may get scheduled between @work's completion
2948 * and the other canceling task resuming and clearing
2949 * CANCELING - flush_work() will return false immediately
2950 * as @work is no longer busy, try_to_grab_pending() will
2951 * return -ENOENT as @work is still being canceled and the
2952 * other canceling task won't be able to clear CANCELING as
2953 * we're hogging the CPU.
2955 * Let's wait for completion using a waitqueue. As this
2956 * may lead to the thundering herd problem, use a custom
2957 * wake function which matches @work along with exclusive
2958 * wait and wakeup.
2960 if (unlikely(ret == -ENOENT)) {
2961 struct cwt_wait cwait;
2963 init_wait(&cwait.wait);
2964 cwait.wait.func = cwt_wakefn;
2965 cwait.work = work;
2967 prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
2968 TASK_UNINTERRUPTIBLE);
2969 if (work_is_canceling(work))
2970 schedule();
2971 finish_wait(&cancel_waitq, &cwait.wait);
2973 } while (unlikely(ret < 0));
2975 /* tell other tasks trying to grab @work to back off */
2976 mark_work_canceling(work);
2977 local_irq_restore(flags);
2979 flush_work(work);
2980 clear_work_data(work);
2983 * Paired with prepare_to_wait() above so that either
2984 * waitqueue_active() is visible here or !work_is_canceling() is
2985 * visible there.
2987 smp_mb();
2988 if (waitqueue_active(&cancel_waitq))
2989 __wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
2991 return ret;
2995 * cancel_work_sync - cancel a work and wait for it to finish
2996 * @work: the work to cancel
2998 * Cancel @work and wait for its execution to finish. This function
2999 * can be used even if the work re-queues itself or migrates to
3000 * another workqueue. On return from this function, @work is
3001 * guaranteed to be not pending or executing on any CPU.
3003 * cancel_work_sync(&delayed_work->work) must not be used for
3004 * delayed_work's. Use cancel_delayed_work_sync() instead.
3006 * The caller must ensure that the workqueue on which @work was last
3007 * queued can't be destroyed before this function returns.
3009 * Return:
3010 * %true if @work was pending, %false otherwise.
3012 bool cancel_work_sync(struct work_struct *work)
3014 return __cancel_work_timer(work, false);
3016 EXPORT_SYMBOL_GPL(cancel_work_sync);
3019 * flush_delayed_work - wait for a dwork to finish executing the last queueing
3020 * @dwork: the delayed work to flush
3022 * Delayed timer is cancelled and the pending work is queued for
3023 * immediate execution. Like flush_work(), this function only
3024 * considers the last queueing instance of @dwork.
3026 * Return:
3027 * %true if flush_work() waited for the work to finish execution,
3028 * %false if it was already idle.
3030 bool flush_delayed_work(struct delayed_work *dwork)
3032 local_irq_disable();
3033 if (del_timer_sync(&dwork->timer))
3034 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
3035 local_irq_enable();
3036 return flush_work(&dwork->work);
3038 EXPORT_SYMBOL(flush_delayed_work);
3041 * cancel_delayed_work - cancel a delayed work
3042 * @dwork: delayed_work to cancel
3044 * Kill off a pending delayed_work.
3046 * Return: %true if @dwork was pending and canceled; %false if it wasn't
3047 * pending.
3049 * Note:
3050 * The work callback function may still be running on return, unless
3051 * it returns %true and the work doesn't re-arm itself. Explicitly flush or
3052 * use cancel_delayed_work_sync() to wait on it.
3054 * This function is safe to call from any context including IRQ handler.
3056 bool cancel_delayed_work(struct delayed_work *dwork)
3058 unsigned long flags;
3059 int ret;
3061 do {
3062 ret = try_to_grab_pending(&dwork->work, true, &flags);
3063 } while (unlikely(ret == -EAGAIN));
3065 if (unlikely(ret < 0))
3066 return false;
3068 set_work_pool_and_clear_pending(&dwork->work,
3069 get_work_pool_id(&dwork->work));
3070 local_irq_restore(flags);
3071 return ret;
3073 EXPORT_SYMBOL(cancel_delayed_work);
3076 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3077 * @dwork: the delayed work cancel
3079 * This is cancel_work_sync() for delayed works.
3081 * Return:
3082 * %true if @dwork was pending, %false otherwise.
3084 bool cancel_delayed_work_sync(struct delayed_work *dwork)
3086 return __cancel_work_timer(&dwork->work, true);
3088 EXPORT_SYMBOL(cancel_delayed_work_sync);
3091 * schedule_on_each_cpu - execute a function synchronously on each online CPU
3092 * @func: the function to call
3094 * schedule_on_each_cpu() executes @func on each online CPU using the
3095 * system workqueue and blocks until all CPUs have completed.
3096 * schedule_on_each_cpu() is very slow.
3098 * Return:
3099 * 0 on success, -errno on failure.
3101 int schedule_on_each_cpu(work_func_t func)
3103 int cpu;
3104 struct work_struct __percpu *works;
3106 works = alloc_percpu(struct work_struct);
3107 if (!works)
3108 return -ENOMEM;
3110 get_online_cpus();
3112 for_each_online_cpu(cpu) {
3113 struct work_struct *work = per_cpu_ptr(works, cpu);
3115 INIT_WORK(work, func);
3116 schedule_work_on(cpu, work);
3119 for_each_online_cpu(cpu)
3120 flush_work(per_cpu_ptr(works, cpu));
3122 put_online_cpus();
3123 free_percpu(works);
3124 return 0;
3128 * flush_scheduled_work - ensure that any scheduled work has run to completion.
3130 * Forces execution of the kernel-global workqueue and blocks until its
3131 * completion.
3133 * Think twice before calling this function! It's very easy to get into
3134 * trouble if you don't take great care. Either of the following situations
3135 * will lead to deadlock:
3137 * One of the work items currently on the workqueue needs to acquire
3138 * a lock held by your code or its caller.
3140 * Your code is running in the context of a work routine.
3142 * They will be detected by lockdep when they occur, but the first might not
3143 * occur very often. It depends on what work items are on the workqueue and
3144 * what locks they need, which you have no control over.
3146 * In most situations flushing the entire workqueue is overkill; you merely
3147 * need to know that a particular work item isn't queued and isn't running.
3148 * In such cases you should use cancel_delayed_work_sync() or
3149 * cancel_work_sync() instead.
3151 void flush_scheduled_work(void)
3153 flush_workqueue(system_wq);
3155 EXPORT_SYMBOL(flush_scheduled_work);
3158 * execute_in_process_context - reliably execute the routine with user context
3159 * @fn: the function to execute
3160 * @ew: guaranteed storage for the execute work structure (must
3161 * be available when the work executes)
3163 * Executes the function immediately if process context is available,
3164 * otherwise schedules the function for delayed execution.
3166 * Return: 0 - function was executed
3167 * 1 - function was scheduled for execution
3169 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
3171 if (!in_interrupt()) {
3172 fn(&ew->work);
3173 return 0;
3176 INIT_WORK(&ew->work, fn);
3177 schedule_work(&ew->work);
3179 return 1;
3181 EXPORT_SYMBOL_GPL(execute_in_process_context);
3183 #ifdef CONFIG_SYSFS
3185 * Workqueues with WQ_SYSFS flag set is visible to userland via
3186 * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
3187 * following attributes.
3189 * per_cpu RO bool : whether the workqueue is per-cpu or unbound
3190 * max_active RW int : maximum number of in-flight work items
3192 * Unbound workqueues have the following extra attributes.
3194 * id RO int : the associated pool ID
3195 * nice RW int : nice value of the workers
3196 * cpumask RW mask : bitmask of allowed CPUs for the workers
3198 struct wq_device {
3199 struct workqueue_struct *wq;
3200 struct device dev;
3203 static struct workqueue_struct *dev_to_wq(struct device *dev)
3205 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
3207 return wq_dev->wq;
3210 static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
3211 char *buf)
3213 struct workqueue_struct *wq = dev_to_wq(dev);
3215 return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
3217 static DEVICE_ATTR_RO(per_cpu);
3219 static ssize_t max_active_show(struct device *dev,
3220 struct device_attribute *attr, char *buf)
3222 struct workqueue_struct *wq = dev_to_wq(dev);
3224 return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
3227 static ssize_t max_active_store(struct device *dev,
3228 struct device_attribute *attr, const char *buf,
3229 size_t count)
3231 struct workqueue_struct *wq = dev_to_wq(dev);
3232 int val;
3234 if (sscanf(buf, "%d", &val) != 1 || val <= 0)
3235 return -EINVAL;
3237 workqueue_set_max_active(wq, val);
3238 return count;
3240 static DEVICE_ATTR_RW(max_active);
3242 static struct attribute *wq_sysfs_attrs[] = {
3243 &dev_attr_per_cpu.attr,
3244 &dev_attr_max_active.attr,
3245 NULL,
3247 ATTRIBUTE_GROUPS(wq_sysfs);
3249 static ssize_t wq_pool_ids_show(struct device *dev,
3250 struct device_attribute *attr, char *buf)
3252 struct workqueue_struct *wq = dev_to_wq(dev);
3253 const char *delim = "";
3254 int node, written = 0;
3256 rcu_read_lock_sched();
3257 for_each_node(node) {
3258 written += scnprintf(buf + written, PAGE_SIZE - written,
3259 "%s%d:%d", delim, node,
3260 unbound_pwq_by_node(wq, node)->pool->id);
3261 delim = " ";
3263 written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
3264 rcu_read_unlock_sched();
3266 return written;
3269 static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
3270 char *buf)
3272 struct workqueue_struct *wq = dev_to_wq(dev);
3273 int written;
3275 mutex_lock(&wq->mutex);
3276 written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
3277 mutex_unlock(&wq->mutex);
3279 return written;
3282 /* prepare workqueue_attrs for sysfs store operations */
3283 static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
3285 struct workqueue_attrs *attrs;
3287 attrs = alloc_workqueue_attrs(GFP_KERNEL);
3288 if (!attrs)
3289 return NULL;
3291 mutex_lock(&wq->mutex);
3292 copy_workqueue_attrs(attrs, wq->unbound_attrs);
3293 mutex_unlock(&wq->mutex);
3294 return attrs;
3297 static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
3298 const char *buf, size_t count)
3300 struct workqueue_struct *wq = dev_to_wq(dev);
3301 struct workqueue_attrs *attrs;
3302 int ret;
3304 attrs = wq_sysfs_prep_attrs(wq);
3305 if (!attrs)
3306 return -ENOMEM;
3308 if (sscanf(buf, "%d", &attrs->nice) == 1 &&
3309 attrs->nice >= -20 && attrs->nice <= 19)
3310 ret = apply_workqueue_attrs(wq, attrs);
3311 else
3312 ret = -EINVAL;
3314 free_workqueue_attrs(attrs);
3315 return ret ?: count;
3318 static ssize_t wq_cpumask_show(struct device *dev,
3319 struct device_attribute *attr, char *buf)
3321 struct workqueue_struct *wq = dev_to_wq(dev);
3322 int written;
3324 mutex_lock(&wq->mutex);
3325 written = cpumask_scnprintf(buf, PAGE_SIZE, wq->unbound_attrs->cpumask);
3326 mutex_unlock(&wq->mutex);
3328 written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
3329 return written;
3332 static ssize_t wq_cpumask_store(struct device *dev,
3333 struct device_attribute *attr,
3334 const char *buf, size_t count)
3336 struct workqueue_struct *wq = dev_to_wq(dev);
3337 struct workqueue_attrs *attrs;
3338 int ret;
3340 attrs = wq_sysfs_prep_attrs(wq);
3341 if (!attrs)
3342 return -ENOMEM;
3344 ret = cpumask_parse(buf, attrs->cpumask);
3345 if (!ret)
3346 ret = apply_workqueue_attrs(wq, attrs);
3348 free_workqueue_attrs(attrs);
3349 return ret ?: count;
3352 static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
3353 char *buf)
3355 struct workqueue_struct *wq = dev_to_wq(dev);
3356 int written;
3358 mutex_lock(&wq->mutex);
3359 written = scnprintf(buf, PAGE_SIZE, "%d\n",
3360 !wq->unbound_attrs->no_numa);
3361 mutex_unlock(&wq->mutex);
3363 return written;
3366 static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
3367 const char *buf, size_t count)
3369 struct workqueue_struct *wq = dev_to_wq(dev);
3370 struct workqueue_attrs *attrs;
3371 int v, ret;
3373 attrs = wq_sysfs_prep_attrs(wq);
3374 if (!attrs)
3375 return -ENOMEM;
3377 ret = -EINVAL;
3378 if (sscanf(buf, "%d", &v) == 1) {
3379 attrs->no_numa = !v;
3380 ret = apply_workqueue_attrs(wq, attrs);
3383 free_workqueue_attrs(attrs);
3384 return ret ?: count;
3387 static struct device_attribute wq_sysfs_unbound_attrs[] = {
3388 __ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
3389 __ATTR(nice, 0644, wq_nice_show, wq_nice_store),
3390 __ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
3391 __ATTR(numa, 0644, wq_numa_show, wq_numa_store),
3392 __ATTR_NULL,
3395 static struct bus_type wq_subsys = {
3396 .name = "workqueue",
3397 .dev_groups = wq_sysfs_groups,
3400 static int __init wq_sysfs_init(void)
3402 return subsys_virtual_register(&wq_subsys, NULL);
3404 core_initcall(wq_sysfs_init);
3406 static void wq_device_release(struct device *dev)
3408 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
3410 kfree(wq_dev);
3414 * workqueue_sysfs_register - make a workqueue visible in sysfs
3415 * @wq: the workqueue to register
3417 * Expose @wq in sysfs under /sys/bus/workqueue/devices.
3418 * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
3419 * which is the preferred method.
3421 * Workqueue user should use this function directly iff it wants to apply
3422 * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
3423 * apply_workqueue_attrs() may race against userland updating the
3424 * attributes.
3426 * Return: 0 on success, -errno on failure.
3428 int workqueue_sysfs_register(struct workqueue_struct *wq)
3430 struct wq_device *wq_dev;
3431 int ret;
3434 * Adjusting max_active or creating new pwqs by applyting
3435 * attributes breaks ordering guarantee. Disallow exposing ordered
3436 * workqueues.
3438 if (WARN_ON(wq->flags & __WQ_ORDERED))
3439 return -EINVAL;
3441 wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
3442 if (!wq_dev)
3443 return -ENOMEM;
3445 wq_dev->wq = wq;
3446 wq_dev->dev.bus = &wq_subsys;
3447 wq_dev->dev.init_name = wq->name;
3448 wq_dev->dev.release = wq_device_release;
3451 * unbound_attrs are created separately. Suppress uevent until
3452 * everything is ready.
3454 dev_set_uevent_suppress(&wq_dev->dev, true);
3456 ret = device_register(&wq_dev->dev);
3457 if (ret) {
3458 kfree(wq_dev);
3459 wq->wq_dev = NULL;
3460 return ret;
3463 if (wq->flags & WQ_UNBOUND) {
3464 struct device_attribute *attr;
3466 for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
3467 ret = device_create_file(&wq_dev->dev, attr);
3468 if (ret) {
3469 device_unregister(&wq_dev->dev);
3470 wq->wq_dev = NULL;
3471 return ret;
3476 dev_set_uevent_suppress(&wq_dev->dev, false);
3477 kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
3478 return 0;
3482 * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
3483 * @wq: the workqueue to unregister
3485 * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
3487 static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
3489 struct wq_device *wq_dev = wq->wq_dev;
3491 if (!wq->wq_dev)
3492 return;
3494 wq->wq_dev = NULL;
3495 device_unregister(&wq_dev->dev);
3497 #else /* CONFIG_SYSFS */
3498 static void workqueue_sysfs_unregister(struct workqueue_struct *wq) { }
3499 #endif /* CONFIG_SYSFS */
3502 * free_workqueue_attrs - free a workqueue_attrs
3503 * @attrs: workqueue_attrs to free
3505 * Undo alloc_workqueue_attrs().
3507 void free_workqueue_attrs(struct workqueue_attrs *attrs)
3509 if (attrs) {
3510 free_cpumask_var(attrs->cpumask);
3511 kfree(attrs);
3516 * alloc_workqueue_attrs - allocate a workqueue_attrs
3517 * @gfp_mask: allocation mask to use
3519 * Allocate a new workqueue_attrs, initialize with default settings and
3520 * return it.
3522 * Return: The allocated new workqueue_attr on success. %NULL on failure.
3524 struct workqueue_attrs *alloc_workqueue_attrs(gfp_t gfp_mask)
3526 struct workqueue_attrs *attrs;
3528 attrs = kzalloc(sizeof(*attrs), gfp_mask);
3529 if (!attrs)
3530 goto fail;
3531 if (!alloc_cpumask_var(&attrs->cpumask, gfp_mask))
3532 goto fail;
3534 cpumask_copy(attrs->cpumask, cpu_possible_mask);
3535 return attrs;
3536 fail:
3537 free_workqueue_attrs(attrs);
3538 return NULL;
3541 static void copy_workqueue_attrs(struct workqueue_attrs *to,
3542 const struct workqueue_attrs *from)
3544 to->nice = from->nice;
3545 cpumask_copy(to->cpumask, from->cpumask);
3547 * Unlike hash and equality test, this function doesn't ignore
3548 * ->no_numa as it is used for both pool and wq attrs. Instead,
3549 * get_unbound_pool() explicitly clears ->no_numa after copying.
3551 to->no_numa = from->no_numa;
3554 /* hash value of the content of @attr */
3555 static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
3557 u32 hash = 0;
3559 hash = jhash_1word(attrs->nice, hash);
3560 hash = jhash(cpumask_bits(attrs->cpumask),
3561 BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
3562 return hash;
3565 /* content equality test */
3566 static bool wqattrs_equal(const struct workqueue_attrs *a,
3567 const struct workqueue_attrs *b)
3569 if (a->nice != b->nice)
3570 return false;
3571 if (!cpumask_equal(a->cpumask, b->cpumask))
3572 return false;
3573 return true;
3577 * init_worker_pool - initialize a newly zalloc'd worker_pool
3578 * @pool: worker_pool to initialize
3580 * Initiailize a newly zalloc'd @pool. It also allocates @pool->attrs.
3582 * Return: 0 on success, -errno on failure. Even on failure, all fields
3583 * inside @pool proper are initialized and put_unbound_pool() can be called
3584 * on @pool safely to release it.
3586 static int init_worker_pool(struct worker_pool *pool)
3588 spin_lock_init(&pool->lock);
3589 pool->id = -1;
3590 pool->cpu = -1;
3591 pool->node = NUMA_NO_NODE;
3592 pool->flags |= POOL_DISASSOCIATED;
3593 INIT_LIST_HEAD(&pool->worklist);
3594 INIT_LIST_HEAD(&pool->idle_list);
3595 hash_init(pool->busy_hash);
3597 init_timer_deferrable(&pool->idle_timer);
3598 pool->idle_timer.function = idle_worker_timeout;
3599 pool->idle_timer.data = (unsigned long)pool;
3601 setup_timer(&pool->mayday_timer, pool_mayday_timeout,
3602 (unsigned long)pool);
3604 mutex_init(&pool->manager_arb);
3605 mutex_init(&pool->manager_mutex);
3606 idr_init(&pool->worker_idr);
3608 INIT_HLIST_NODE(&pool->hash_node);
3609 pool->refcnt = 1;
3611 /* shouldn't fail above this point */
3612 pool->attrs = alloc_workqueue_attrs(GFP_KERNEL);
3613 if (!pool->attrs)
3614 return -ENOMEM;
3615 return 0;
3618 static void rcu_free_pool(struct rcu_head *rcu)
3620 struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
3622 idr_destroy(&pool->worker_idr);
3623 free_workqueue_attrs(pool->attrs);
3624 kfree(pool);
3628 * put_unbound_pool - put a worker_pool
3629 * @pool: worker_pool to put
3631 * Put @pool. If its refcnt reaches zero, it gets destroyed in sched-RCU
3632 * safe manner. get_unbound_pool() calls this function on its failure path
3633 * and this function should be able to release pools which went through,
3634 * successfully or not, init_worker_pool().
3636 * Should be called with wq_pool_mutex held.
3638 static void put_unbound_pool(struct worker_pool *pool)
3640 struct worker *worker;
3642 lockdep_assert_held(&wq_pool_mutex);
3644 if (--pool->refcnt)
3645 return;
3647 /* sanity checks */
3648 if (WARN_ON(!(pool->flags & POOL_DISASSOCIATED)) ||
3649 WARN_ON(!list_empty(&pool->worklist)))
3650 return;
3652 /* release id and unhash */
3653 if (pool->id >= 0)
3654 idr_remove(&worker_pool_idr, pool->id);
3655 hash_del(&pool->hash_node);
3658 * Become the manager and destroy all workers. Grabbing
3659 * manager_arb prevents @pool's workers from blocking on
3660 * manager_mutex.
3662 mutex_lock(&pool->manager_arb);
3663 mutex_lock(&pool->manager_mutex);
3664 spin_lock_irq(&pool->lock);
3666 while ((worker = first_worker(pool)))
3667 destroy_worker(worker);
3668 WARN_ON(pool->nr_workers || pool->nr_idle);
3670 spin_unlock_irq(&pool->lock);
3671 mutex_unlock(&pool->manager_mutex);
3672 mutex_unlock(&pool->manager_arb);
3674 /* shut down the timers */
3675 del_timer_sync(&pool->idle_timer);
3676 del_timer_sync(&pool->mayday_timer);
3678 /* sched-RCU protected to allow dereferences from get_work_pool() */
3679 call_rcu_sched(&pool->rcu, rcu_free_pool);
3683 * get_unbound_pool - get a worker_pool with the specified attributes
3684 * @attrs: the attributes of the worker_pool to get
3686 * Obtain a worker_pool which has the same attributes as @attrs, bump the
3687 * reference count and return it. If there already is a matching
3688 * worker_pool, it will be used; otherwise, this function attempts to
3689 * create a new one.
3691 * Should be called with wq_pool_mutex held.
3693 * Return: On success, a worker_pool with the same attributes as @attrs.
3694 * On failure, %NULL.
3696 static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
3698 u32 hash = wqattrs_hash(attrs);
3699 struct worker_pool *pool;
3700 int node;
3702 lockdep_assert_held(&wq_pool_mutex);
3704 /* do we already have a matching pool? */
3705 hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
3706 if (wqattrs_equal(pool->attrs, attrs)) {
3707 pool->refcnt++;
3708 goto out_unlock;
3712 /* nope, create a new one */
3713 pool = kzalloc(sizeof(*pool), GFP_KERNEL);
3714 if (!pool || init_worker_pool(pool) < 0)
3715 goto fail;
3717 if (workqueue_freezing)
3718 pool->flags |= POOL_FREEZING;
3720 lockdep_set_subclass(&pool->lock, 1); /* see put_pwq() */
3721 copy_workqueue_attrs(pool->attrs, attrs);
3724 * no_numa isn't a worker_pool attribute, always clear it. See
3725 * 'struct workqueue_attrs' comments for detail.
3727 pool->attrs->no_numa = false;
3729 /* if cpumask is contained inside a NUMA node, we belong to that node */
3730 if (wq_numa_enabled) {
3731 for_each_node(node) {
3732 if (cpumask_subset(pool->attrs->cpumask,
3733 wq_numa_possible_cpumask[node])) {
3734 pool->node = node;
3735 break;
3740 if (worker_pool_assign_id(pool) < 0)
3741 goto fail;
3743 /* create and start the initial worker */
3744 if (create_and_start_worker(pool) < 0)
3745 goto fail;
3747 /* install */
3748 hash_add(unbound_pool_hash, &pool->hash_node, hash);
3749 out_unlock:
3750 return pool;
3751 fail:
3752 if (pool)
3753 put_unbound_pool(pool);
3754 return NULL;
3757 static void rcu_free_pwq(struct rcu_head *rcu)
3759 kmem_cache_free(pwq_cache,
3760 container_of(rcu, struct pool_workqueue, rcu));
3764 * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
3765 * and needs to be destroyed.
3767 static void pwq_unbound_release_workfn(struct work_struct *work)
3769 struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
3770 unbound_release_work);
3771 struct workqueue_struct *wq = pwq->wq;
3772 struct worker_pool *pool = pwq->pool;
3773 bool is_last;
3775 if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
3776 return;
3779 * Unlink @pwq. Synchronization against wq->mutex isn't strictly
3780 * necessary on release but do it anyway. It's easier to verify
3781 * and consistent with the linking path.
3783 mutex_lock(&wq->mutex);
3784 list_del_rcu(&pwq->pwqs_node);
3785 is_last = list_empty(&wq->pwqs);
3786 mutex_unlock(&wq->mutex);
3788 mutex_lock(&wq_pool_mutex);
3789 put_unbound_pool(pool);
3790 mutex_unlock(&wq_pool_mutex);
3792 call_rcu_sched(&pwq->rcu, rcu_free_pwq);
3795 * If we're the last pwq going away, @wq is already dead and no one
3796 * is gonna access it anymore. Free it.
3798 if (is_last) {
3799 free_workqueue_attrs(wq->unbound_attrs);
3800 kfree(wq);
3805 * pwq_adjust_max_active - update a pwq's max_active to the current setting
3806 * @pwq: target pool_workqueue
3808 * If @pwq isn't freezing, set @pwq->max_active to the associated
3809 * workqueue's saved_max_active and activate delayed work items
3810 * accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
3812 static void pwq_adjust_max_active(struct pool_workqueue *pwq)
3814 struct workqueue_struct *wq = pwq->wq;
3815 bool freezable = wq->flags & WQ_FREEZABLE;
3817 /* for @wq->saved_max_active */
3818 lockdep_assert_held(&wq->mutex);
3820 /* fast exit for non-freezable wqs */
3821 if (!freezable && pwq->max_active == wq->saved_max_active)
3822 return;
3824 spin_lock_irq(&pwq->pool->lock);
3826 if (!freezable || !(pwq->pool->flags & POOL_FREEZING)) {
3827 pwq->max_active = wq->saved_max_active;
3829 while (!list_empty(&pwq->delayed_works) &&
3830 pwq->nr_active < pwq->max_active)
3831 pwq_activate_first_delayed(pwq);
3834 * Need to kick a worker after thawed or an unbound wq's
3835 * max_active is bumped. It's a slow path. Do it always.
3837 wake_up_worker(pwq->pool);
3838 } else {
3839 pwq->max_active = 0;
3842 spin_unlock_irq(&pwq->pool->lock);
3845 /* initialize newly alloced @pwq which is associated with @wq and @pool */
3846 static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
3847 struct worker_pool *pool)
3849 BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3851 memset(pwq, 0, sizeof(*pwq));
3853 pwq->pool = pool;
3854 pwq->wq = wq;
3855 pwq->flush_color = -1;
3856 pwq->refcnt = 1;
3857 INIT_LIST_HEAD(&pwq->delayed_works);
3858 INIT_LIST_HEAD(&pwq->pwqs_node);
3859 INIT_LIST_HEAD(&pwq->mayday_node);
3860 INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
3863 /* sync @pwq with the current state of its associated wq and link it */
3864 static void link_pwq(struct pool_workqueue *pwq)
3866 struct workqueue_struct *wq = pwq->wq;
3868 lockdep_assert_held(&wq->mutex);
3870 /* may be called multiple times, ignore if already linked */
3871 if (!list_empty(&pwq->pwqs_node))
3872 return;
3875 * Set the matching work_color. This is synchronized with
3876 * wq->mutex to avoid confusing flush_workqueue().
3878 pwq->work_color = wq->work_color;
3880 /* sync max_active to the current setting */
3881 pwq_adjust_max_active(pwq);
3883 /* link in @pwq */
3884 list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
3887 /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
3888 static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
3889 const struct workqueue_attrs *attrs)
3891 struct worker_pool *pool;
3892 struct pool_workqueue *pwq;
3894 lockdep_assert_held(&wq_pool_mutex);
3896 pool = get_unbound_pool(attrs);
3897 if (!pool)
3898 return NULL;
3900 pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
3901 if (!pwq) {
3902 put_unbound_pool(pool);
3903 return NULL;
3906 init_pwq(pwq, wq, pool);
3907 return pwq;
3910 /* undo alloc_unbound_pwq(), used only in the error path */
3911 static void free_unbound_pwq(struct pool_workqueue *pwq)
3913 lockdep_assert_held(&wq_pool_mutex);
3915 if (pwq) {
3916 put_unbound_pool(pwq->pool);
3917 kmem_cache_free(pwq_cache, pwq);
3922 * wq_calc_node_mask - calculate a wq_attrs' cpumask for the specified node
3923 * @attrs: the wq_attrs of interest
3924 * @node: the target NUMA node
3925 * @cpu_going_down: if >= 0, the CPU to consider as offline
3926 * @cpumask: outarg, the resulting cpumask
3928 * Calculate the cpumask a workqueue with @attrs should use on @node. If
3929 * @cpu_going_down is >= 0, that cpu is considered offline during
3930 * calculation. The result is stored in @cpumask.
3932 * If NUMA affinity is not enabled, @attrs->cpumask is always used. If
3933 * enabled and @node has online CPUs requested by @attrs, the returned
3934 * cpumask is the intersection of the possible CPUs of @node and
3935 * @attrs->cpumask.
3937 * The caller is responsible for ensuring that the cpumask of @node stays
3938 * stable.
3940 * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
3941 * %false if equal.
3943 static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
3944 int cpu_going_down, cpumask_t *cpumask)
3946 if (!wq_numa_enabled || attrs->no_numa)
3947 goto use_dfl;
3949 /* does @node have any online CPUs @attrs wants? */
3950 cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
3951 if (cpu_going_down >= 0)
3952 cpumask_clear_cpu(cpu_going_down, cpumask);
3954 if (cpumask_empty(cpumask))
3955 goto use_dfl;
3957 /* yeap, return possible CPUs in @node that @attrs wants */
3958 cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
3959 return !cpumask_equal(cpumask, attrs->cpumask);
3961 use_dfl:
3962 cpumask_copy(cpumask, attrs->cpumask);
3963 return false;
3966 /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
3967 static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
3968 int node,
3969 struct pool_workqueue *pwq)
3971 struct pool_workqueue *old_pwq;
3973 lockdep_assert_held(&wq->mutex);
3975 /* link_pwq() can handle duplicate calls */
3976 link_pwq(pwq);
3978 old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
3979 rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
3980 return old_pwq;
3984 * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
3985 * @wq: the target workqueue
3986 * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
3988 * Apply @attrs to an unbound workqueue @wq. Unless disabled, on NUMA
3989 * machines, this function maps a separate pwq to each NUMA node with
3990 * possibles CPUs in @attrs->cpumask so that work items are affine to the
3991 * NUMA node it was issued on. Older pwqs are released as in-flight work
3992 * items finish. Note that a work item which repeatedly requeues itself
3993 * back-to-back will stay on its current pwq.
3995 * Performs GFP_KERNEL allocations.
3997 * Return: 0 on success and -errno on failure.
3999 int apply_workqueue_attrs(struct workqueue_struct *wq,
4000 const struct workqueue_attrs *attrs)
4002 struct workqueue_attrs *new_attrs, *tmp_attrs;
4003 struct pool_workqueue **pwq_tbl, *dfl_pwq;
4004 int node, ret;
4006 /* only unbound workqueues can change attributes */
4007 if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
4008 return -EINVAL;
4010 /* creating multiple pwqs breaks ordering guarantee */
4011 if (WARN_ON((wq->flags & __WQ_ORDERED) && !list_empty(&wq->pwqs)))
4012 return -EINVAL;
4014 pwq_tbl = kzalloc(wq_numa_tbl_len * sizeof(pwq_tbl[0]), GFP_KERNEL);
4015 new_attrs = alloc_workqueue_attrs(GFP_KERNEL);
4016 tmp_attrs = alloc_workqueue_attrs(GFP_KERNEL);
4017 if (!pwq_tbl || !new_attrs || !tmp_attrs)
4018 goto enomem;
4020 /* make a copy of @attrs and sanitize it */
4021 copy_workqueue_attrs(new_attrs, attrs);
4022 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
4025 * We may create multiple pwqs with differing cpumasks. Make a
4026 * copy of @new_attrs which will be modified and used to obtain
4027 * pools.
4029 copy_workqueue_attrs(tmp_attrs, new_attrs);
4032 * CPUs should stay stable across pwq creations and installations.
4033 * Pin CPUs, determine the target cpumask for each node and create
4034 * pwqs accordingly.
4036 get_online_cpus();
4038 mutex_lock(&wq_pool_mutex);
4041 * If something goes wrong during CPU up/down, we'll fall back to
4042 * the default pwq covering whole @attrs->cpumask. Always create
4043 * it even if we don't use it immediately.
4045 dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
4046 if (!dfl_pwq)
4047 goto enomem_pwq;
4049 for_each_node(node) {
4050 if (wq_calc_node_cpumask(attrs, node, -1, tmp_attrs->cpumask)) {
4051 pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
4052 if (!pwq_tbl[node])
4053 goto enomem_pwq;
4054 } else {
4055 dfl_pwq->refcnt++;
4056 pwq_tbl[node] = dfl_pwq;
4060 mutex_unlock(&wq_pool_mutex);
4062 /* all pwqs have been created successfully, let's install'em */
4063 mutex_lock(&wq->mutex);
4065 copy_workqueue_attrs(wq->unbound_attrs, new_attrs);
4067 /* save the previous pwq and install the new one */
4068 for_each_node(node)
4069 pwq_tbl[node] = numa_pwq_tbl_install(wq, node, pwq_tbl[node]);
4071 /* @dfl_pwq might not have been used, ensure it's linked */
4072 link_pwq(dfl_pwq);
4073 swap(wq->dfl_pwq, dfl_pwq);
4075 mutex_unlock(&wq->mutex);
4077 /* put the old pwqs */
4078 for_each_node(node)
4079 put_pwq_unlocked(pwq_tbl[node]);
4080 put_pwq_unlocked(dfl_pwq);
4082 put_online_cpus();
4083 ret = 0;
4084 /* fall through */
4085 out_free:
4086 free_workqueue_attrs(tmp_attrs);
4087 free_workqueue_attrs(new_attrs);
4088 kfree(pwq_tbl);
4089 return ret;
4091 enomem_pwq:
4092 free_unbound_pwq(dfl_pwq);
4093 for_each_node(node)
4094 if (pwq_tbl && pwq_tbl[node] != dfl_pwq)
4095 free_unbound_pwq(pwq_tbl[node]);
4096 mutex_unlock(&wq_pool_mutex);
4097 put_online_cpus();
4098 enomem:
4099 ret = -ENOMEM;
4100 goto out_free;
4104 * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
4105 * @wq: the target workqueue
4106 * @cpu: the CPU coming up or going down
4107 * @online: whether @cpu is coming up or going down
4109 * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
4110 * %CPU_DOWN_FAILED. @cpu is being hot[un]plugged, update NUMA affinity of
4111 * @wq accordingly.
4113 * If NUMA affinity can't be adjusted due to memory allocation failure, it
4114 * falls back to @wq->dfl_pwq which may not be optimal but is always
4115 * correct.
4117 * Note that when the last allowed CPU of a NUMA node goes offline for a
4118 * workqueue with a cpumask spanning multiple nodes, the workers which were
4119 * already executing the work items for the workqueue will lose their CPU
4120 * affinity and may execute on any CPU. This is similar to how per-cpu
4121 * workqueues behave on CPU_DOWN. If a workqueue user wants strict
4122 * affinity, it's the user's responsibility to flush the work item from
4123 * CPU_DOWN_PREPARE.
4125 static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
4126 bool online)
4128 int node = cpu_to_node(cpu);
4129 int cpu_off = online ? -1 : cpu;
4130 struct pool_workqueue *old_pwq = NULL, *pwq;
4131 struct workqueue_attrs *target_attrs;
4132 cpumask_t *cpumask;
4134 lockdep_assert_held(&wq_pool_mutex);
4136 if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND))
4137 return;
4140 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
4141 * Let's use a preallocated one. The following buf is protected by
4142 * CPU hotplug exclusion.
4144 target_attrs = wq_update_unbound_numa_attrs_buf;
4145 cpumask = target_attrs->cpumask;
4147 mutex_lock(&wq->mutex);
4148 if (wq->unbound_attrs->no_numa)
4149 goto out_unlock;
4151 copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
4152 pwq = unbound_pwq_by_node(wq, node);
4155 * Let's determine what needs to be done. If the target cpumask is
4156 * different from wq's, we need to compare it to @pwq's and create
4157 * a new one if they don't match. If the target cpumask equals
4158 * wq's, the default pwq should be used. If @pwq is already the
4159 * default one, nothing to do; otherwise, install the default one.
4161 if (wq_calc_node_cpumask(wq->unbound_attrs, node, cpu_off, cpumask)) {
4162 if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
4163 goto out_unlock;
4164 } else {
4165 if (pwq == wq->dfl_pwq)
4166 goto out_unlock;
4167 else
4168 goto use_dfl_pwq;
4171 mutex_unlock(&wq->mutex);
4173 /* create a new pwq */
4174 pwq = alloc_unbound_pwq(wq, target_attrs);
4175 if (!pwq) {
4176 pr_warning("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
4177 wq->name);
4178 mutex_lock(&wq->mutex);
4179 goto use_dfl_pwq;
4183 * Install the new pwq. As this function is called only from CPU
4184 * hotplug callbacks and applying a new attrs is wrapped with
4185 * get/put_online_cpus(), @wq->unbound_attrs couldn't have changed
4186 * inbetween.
4188 mutex_lock(&wq->mutex);
4189 old_pwq = numa_pwq_tbl_install(wq, node, pwq);
4190 goto out_unlock;
4192 use_dfl_pwq:
4193 spin_lock_irq(&wq->dfl_pwq->pool->lock);
4194 get_pwq(wq->dfl_pwq);
4195 spin_unlock_irq(&wq->dfl_pwq->pool->lock);
4196 old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
4197 out_unlock:
4198 mutex_unlock(&wq->mutex);
4199 put_pwq_unlocked(old_pwq);
4202 static int alloc_and_link_pwqs(struct workqueue_struct *wq)
4204 bool highpri = wq->flags & WQ_HIGHPRI;
4205 int cpu, ret;
4207 if (!(wq->flags & WQ_UNBOUND)) {
4208 wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
4209 if (!wq->cpu_pwqs)
4210 return -ENOMEM;
4212 for_each_possible_cpu(cpu) {
4213 struct pool_workqueue *pwq =
4214 per_cpu_ptr(wq->cpu_pwqs, cpu);
4215 struct worker_pool *cpu_pools =
4216 per_cpu(cpu_worker_pools, cpu);
4218 init_pwq(pwq, wq, &cpu_pools[highpri]);
4220 mutex_lock(&wq->mutex);
4221 link_pwq(pwq);
4222 mutex_unlock(&wq->mutex);
4224 return 0;
4225 } else if (wq->flags & __WQ_ORDERED) {
4226 ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
4227 /* there should only be single pwq for ordering guarantee */
4228 WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
4229 wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
4230 "ordering guarantee broken for workqueue %s\n", wq->name);
4231 return ret;
4232 } else {
4233 return apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
4237 static int wq_clamp_max_active(int max_active, unsigned int flags,
4238 const char *name)
4240 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
4242 if (max_active < 1 || max_active > lim)
4243 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
4244 max_active, name, 1, lim);
4246 return clamp_val(max_active, 1, lim);
4249 struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
4250 unsigned int flags,
4251 int max_active,
4252 struct lock_class_key *key,
4253 const char *lock_name, ...)
4255 size_t tbl_size = 0;
4256 va_list args;
4257 struct workqueue_struct *wq;
4258 struct pool_workqueue *pwq;
4260 /* see the comment above the definition of WQ_POWER_EFFICIENT */
4261 if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
4262 flags |= WQ_UNBOUND;
4264 /* allocate wq and format name */
4265 if (flags & WQ_UNBOUND)
4266 tbl_size = wq_numa_tbl_len * sizeof(wq->numa_pwq_tbl[0]);
4268 wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
4269 if (!wq)
4270 return NULL;
4272 if (flags & WQ_UNBOUND) {
4273 wq->unbound_attrs = alloc_workqueue_attrs(GFP_KERNEL);
4274 if (!wq->unbound_attrs)
4275 goto err_free_wq;
4278 va_start(args, lock_name);
4279 vsnprintf(wq->name, sizeof(wq->name), fmt, args);
4280 va_end(args);
4282 max_active = max_active ?: WQ_DFL_ACTIVE;
4283 max_active = wq_clamp_max_active(max_active, flags, wq->name);
4285 /* init wq */
4286 wq->flags = flags;
4287 wq->saved_max_active = max_active;
4288 mutex_init(&wq->mutex);
4289 atomic_set(&wq->nr_pwqs_to_flush, 0);
4290 INIT_LIST_HEAD(&wq->pwqs);
4291 INIT_LIST_HEAD(&wq->flusher_queue);
4292 INIT_LIST_HEAD(&wq->flusher_overflow);
4293 INIT_LIST_HEAD(&wq->maydays);
4295 lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
4296 INIT_LIST_HEAD(&wq->list);
4298 if (alloc_and_link_pwqs(wq) < 0)
4299 goto err_free_wq;
4302 * Workqueues which may be used during memory reclaim should
4303 * have a rescuer to guarantee forward progress.
4305 if (flags & WQ_MEM_RECLAIM) {
4306 struct worker *rescuer;
4308 rescuer = alloc_worker();
4309 if (!rescuer)
4310 goto err_destroy;
4312 rescuer->rescue_wq = wq;
4313 rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
4314 wq->name);
4315 if (IS_ERR(rescuer->task)) {
4316 kfree(rescuer);
4317 goto err_destroy;
4320 wq->rescuer = rescuer;
4321 rescuer->task->flags |= PF_NO_SETAFFINITY;
4322 wake_up_process(rescuer->task);
4325 if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
4326 goto err_destroy;
4329 * wq_pool_mutex protects global freeze state and workqueues list.
4330 * Grab it, adjust max_active and add the new @wq to workqueues
4331 * list.
4333 mutex_lock(&wq_pool_mutex);
4335 mutex_lock(&wq->mutex);
4336 for_each_pwq(pwq, wq)
4337 pwq_adjust_max_active(pwq);
4338 mutex_unlock(&wq->mutex);
4340 list_add(&wq->list, &workqueues);
4342 mutex_unlock(&wq_pool_mutex);
4344 return wq;
4346 err_free_wq:
4347 free_workqueue_attrs(wq->unbound_attrs);
4348 kfree(wq);
4349 return NULL;
4350 err_destroy:
4351 destroy_workqueue(wq);
4352 return NULL;
4354 EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
4357 * destroy_workqueue - safely terminate a workqueue
4358 * @wq: target workqueue
4360 * Safely destroy a workqueue. All work currently pending will be done first.
4362 void destroy_workqueue(struct workqueue_struct *wq)
4364 struct pool_workqueue *pwq;
4365 int node;
4367 /* drain it before proceeding with destruction */
4368 drain_workqueue(wq);
4370 /* sanity checks */
4371 mutex_lock(&wq->mutex);
4372 for_each_pwq(pwq, wq) {
4373 int i;
4375 for (i = 0; i < WORK_NR_COLORS; i++) {
4376 if (WARN_ON(pwq->nr_in_flight[i])) {
4377 mutex_unlock(&wq->mutex);
4378 return;
4382 if (WARN_ON((pwq != wq->dfl_pwq) && (pwq->refcnt > 1)) ||
4383 WARN_ON(pwq->nr_active) ||
4384 WARN_ON(!list_empty(&pwq->delayed_works))) {
4385 mutex_unlock(&wq->mutex);
4386 return;
4389 mutex_unlock(&wq->mutex);
4392 * wq list is used to freeze wq, remove from list after
4393 * flushing is complete in case freeze races us.
4395 mutex_lock(&wq_pool_mutex);
4396 list_del_init(&wq->list);
4397 mutex_unlock(&wq_pool_mutex);
4399 workqueue_sysfs_unregister(wq);
4401 if (wq->rescuer) {
4402 kthread_stop(wq->rescuer->task);
4403 kfree(wq->rescuer);
4404 wq->rescuer = NULL;
4407 if (!(wq->flags & WQ_UNBOUND)) {
4409 * The base ref is never dropped on per-cpu pwqs. Directly
4410 * free the pwqs and wq.
4412 free_percpu(wq->cpu_pwqs);
4413 kfree(wq);
4414 } else {
4416 * We're the sole accessor of @wq at this point. Directly
4417 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
4418 * @wq will be freed when the last pwq is released.
4420 for_each_node(node) {
4421 pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
4422 RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
4423 put_pwq_unlocked(pwq);
4427 * Put dfl_pwq. @wq may be freed any time after dfl_pwq is
4428 * put. Don't access it afterwards.
4430 pwq = wq->dfl_pwq;
4431 wq->dfl_pwq = NULL;
4432 put_pwq_unlocked(pwq);
4435 EXPORT_SYMBOL_GPL(destroy_workqueue);
4438 * workqueue_set_max_active - adjust max_active of a workqueue
4439 * @wq: target workqueue
4440 * @max_active: new max_active value.
4442 * Set max_active of @wq to @max_active.
4444 * CONTEXT:
4445 * Don't call from IRQ context.
4447 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4449 struct pool_workqueue *pwq;
4451 /* disallow meddling with max_active for ordered workqueues */
4452 if (WARN_ON(wq->flags & __WQ_ORDERED))
4453 return;
4455 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4457 mutex_lock(&wq->mutex);
4459 wq->saved_max_active = max_active;
4461 for_each_pwq(pwq, wq)
4462 pwq_adjust_max_active(pwq);
4464 mutex_unlock(&wq->mutex);
4466 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4469 * current_is_workqueue_rescuer - is %current workqueue rescuer?
4471 * Determine whether %current is a workqueue rescuer. Can be used from
4472 * work functions to determine whether it's being run off the rescuer task.
4474 * Return: %true if %current is a workqueue rescuer. %false otherwise.
4476 bool current_is_workqueue_rescuer(void)
4478 struct worker *worker = current_wq_worker();
4480 return worker && worker->rescue_wq;
4484 * workqueue_congested - test whether a workqueue is congested
4485 * @cpu: CPU in question
4486 * @wq: target workqueue
4488 * Test whether @wq's cpu workqueue for @cpu is congested. There is
4489 * no synchronization around this function and the test result is
4490 * unreliable and only useful as advisory hints or for debugging.
4492 * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4493 * Note that both per-cpu and unbound workqueues may be associated with
4494 * multiple pool_workqueues which have separate congested states. A
4495 * workqueue being congested on one CPU doesn't mean the workqueue is also
4496 * contested on other CPUs / NUMA nodes.
4498 * Return:
4499 * %true if congested, %false otherwise.
4501 bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4503 struct pool_workqueue *pwq;
4504 bool ret;
4506 rcu_read_lock_sched();
4508 if (cpu == WORK_CPU_UNBOUND)
4509 cpu = smp_processor_id();
4511 if (!(wq->flags & WQ_UNBOUND))
4512 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
4513 else
4514 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4516 ret = !list_empty(&pwq->delayed_works);
4517 rcu_read_unlock_sched();
4519 return ret;
4521 EXPORT_SYMBOL_GPL(workqueue_congested);
4524 * work_busy - test whether a work is currently pending or running
4525 * @work: the work to be tested
4527 * Test whether @work is currently pending or running. There is no
4528 * synchronization around this function and the test result is
4529 * unreliable and only useful as advisory hints or for debugging.
4531 * Return:
4532 * OR'd bitmask of WORK_BUSY_* bits.
4534 unsigned int work_busy(struct work_struct *work)
4536 struct worker_pool *pool;
4537 unsigned long flags;
4538 unsigned int ret = 0;
4540 if (work_pending(work))
4541 ret |= WORK_BUSY_PENDING;
4543 local_irq_save(flags);
4544 pool = get_work_pool(work);
4545 if (pool) {
4546 spin_lock(&pool->lock);
4547 if (find_worker_executing_work(pool, work))
4548 ret |= WORK_BUSY_RUNNING;
4549 spin_unlock(&pool->lock);
4551 local_irq_restore(flags);
4553 return ret;
4555 EXPORT_SYMBOL_GPL(work_busy);
4558 * set_worker_desc - set description for the current work item
4559 * @fmt: printf-style format string
4560 * @...: arguments for the format string
4562 * This function can be called by a running work function to describe what
4563 * the work item is about. If the worker task gets dumped, this
4564 * information will be printed out together to help debugging. The
4565 * description can be at most WORKER_DESC_LEN including the trailing '\0'.
4567 void set_worker_desc(const char *fmt, ...)
4569 struct worker *worker = current_wq_worker();
4570 va_list args;
4572 if (worker) {
4573 va_start(args, fmt);
4574 vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
4575 va_end(args);
4576 worker->desc_valid = true;
4581 * print_worker_info - print out worker information and description
4582 * @log_lvl: the log level to use when printing
4583 * @task: target task
4585 * If @task is a worker and currently executing a work item, print out the
4586 * name of the workqueue being serviced and worker description set with
4587 * set_worker_desc() by the currently executing work item.
4589 * This function can be safely called on any task as long as the
4590 * task_struct itself is accessible. While safe, this function isn't
4591 * synchronized and may print out mixups or garbages of limited length.
4593 void print_worker_info(const char *log_lvl, struct task_struct *task)
4595 work_func_t *fn = NULL;
4596 char name[WQ_NAME_LEN] = { };
4597 char desc[WORKER_DESC_LEN] = { };
4598 struct pool_workqueue *pwq = NULL;
4599 struct workqueue_struct *wq = NULL;
4600 bool desc_valid = false;
4601 struct worker *worker;
4603 if (!(task->flags & PF_WQ_WORKER))
4604 return;
4607 * This function is called without any synchronization and @task
4608 * could be in any state. Be careful with dereferences.
4610 worker = probe_kthread_data(task);
4613 * Carefully copy the associated workqueue's workfn and name. Keep
4614 * the original last '\0' in case the original contains garbage.
4616 probe_kernel_read(&fn, &worker->current_func, sizeof(fn));
4617 probe_kernel_read(&pwq, &worker->current_pwq, sizeof(pwq));
4618 probe_kernel_read(&wq, &pwq->wq, sizeof(wq));
4619 probe_kernel_read(name, wq->name, sizeof(name) - 1);
4621 /* copy worker description */
4622 probe_kernel_read(&desc_valid, &worker->desc_valid, sizeof(desc_valid));
4623 if (desc_valid)
4624 probe_kernel_read(desc, worker->desc, sizeof(desc) - 1);
4626 if (fn || name[0] || desc[0]) {
4627 printk("%sWorkqueue: %s %pf", log_lvl, name, fn);
4628 if (desc[0])
4629 pr_cont(" (%s)", desc);
4630 pr_cont("\n");
4635 * CPU hotplug.
4637 * There are two challenges in supporting CPU hotplug. Firstly, there
4638 * are a lot of assumptions on strong associations among work, pwq and
4639 * pool which make migrating pending and scheduled works very
4640 * difficult to implement without impacting hot paths. Secondly,
4641 * worker pools serve mix of short, long and very long running works making
4642 * blocked draining impractical.
4644 * This is solved by allowing the pools to be disassociated from the CPU
4645 * running as an unbound one and allowing it to be reattached later if the
4646 * cpu comes back online.
4649 static void wq_unbind_fn(struct work_struct *work)
4651 int cpu = smp_processor_id();
4652 struct worker_pool *pool;
4653 struct worker *worker;
4654 int wi;
4656 for_each_cpu_worker_pool(pool, cpu) {
4657 WARN_ON_ONCE(cpu != smp_processor_id());
4659 mutex_lock(&pool->manager_mutex);
4660 spin_lock_irq(&pool->lock);
4663 * We've blocked all manager operations. Make all workers
4664 * unbound and set DISASSOCIATED. Before this, all workers
4665 * except for the ones which are still executing works from
4666 * before the last CPU down must be on the cpu. After
4667 * this, they may become diasporas.
4669 for_each_pool_worker(worker, wi, pool)
4670 worker->flags |= WORKER_UNBOUND;
4672 pool->flags |= POOL_DISASSOCIATED;
4674 spin_unlock_irq(&pool->lock);
4675 mutex_unlock(&pool->manager_mutex);
4678 * Call schedule() so that we cross rq->lock and thus can
4679 * guarantee sched callbacks see the %WORKER_UNBOUND flag.
4680 * This is necessary as scheduler callbacks may be invoked
4681 * from other cpus.
4683 schedule();
4686 * Sched callbacks are disabled now. Zap nr_running.
4687 * After this, nr_running stays zero and need_more_worker()
4688 * and keep_working() are always true as long as the
4689 * worklist is not empty. This pool now behaves as an
4690 * unbound (in terms of concurrency management) pool which
4691 * are served by workers tied to the pool.
4693 atomic_set(&pool->nr_running, 0);
4696 * With concurrency management just turned off, a busy
4697 * worker blocking could lead to lengthy stalls. Kick off
4698 * unbound chain execution of currently pending work items.
4700 spin_lock_irq(&pool->lock);
4701 wake_up_worker(pool);
4702 spin_unlock_irq(&pool->lock);
4707 * rebind_workers - rebind all workers of a pool to the associated CPU
4708 * @pool: pool of interest
4710 * @pool->cpu is coming online. Rebind all workers to the CPU.
4712 static void rebind_workers(struct worker_pool *pool)
4714 struct worker *worker;
4715 int wi;
4717 lockdep_assert_held(&pool->manager_mutex);
4720 * Restore CPU affinity of all workers. As all idle workers should
4721 * be on the run-queue of the associated CPU before any local
4722 * wake-ups for concurrency management happen, restore CPU affinty
4723 * of all workers first and then clear UNBOUND. As we're called
4724 * from CPU_ONLINE, the following shouldn't fail.
4726 for_each_pool_worker(worker, wi, pool)
4727 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4728 pool->attrs->cpumask) < 0);
4730 spin_lock_irq(&pool->lock);
4732 for_each_pool_worker(worker, wi, pool) {
4733 unsigned int worker_flags = worker->flags;
4736 * A bound idle worker should actually be on the runqueue
4737 * of the associated CPU for local wake-ups targeting it to
4738 * work. Kick all idle workers so that they migrate to the
4739 * associated CPU. Doing this in the same loop as
4740 * replacing UNBOUND with REBOUND is safe as no worker will
4741 * be bound before @pool->lock is released.
4743 if (worker_flags & WORKER_IDLE)
4744 wake_up_process(worker->task);
4747 * We want to clear UNBOUND but can't directly call
4748 * worker_clr_flags() or adjust nr_running. Atomically
4749 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
4750 * @worker will clear REBOUND using worker_clr_flags() when
4751 * it initiates the next execution cycle thus restoring
4752 * concurrency management. Note that when or whether
4753 * @worker clears REBOUND doesn't affect correctness.
4755 * ACCESS_ONCE() is necessary because @worker->flags may be
4756 * tested without holding any lock in
4757 * wq_worker_waking_up(). Without it, NOT_RUNNING test may
4758 * fail incorrectly leading to premature concurrency
4759 * management operations.
4761 WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
4762 worker_flags |= WORKER_REBOUND;
4763 worker_flags &= ~WORKER_UNBOUND;
4764 ACCESS_ONCE(worker->flags) = worker_flags;
4767 spin_unlock_irq(&pool->lock);
4771 * restore_unbound_workers_cpumask - restore cpumask of unbound workers
4772 * @pool: unbound pool of interest
4773 * @cpu: the CPU which is coming up
4775 * An unbound pool may end up with a cpumask which doesn't have any online
4776 * CPUs. When a worker of such pool get scheduled, the scheduler resets
4777 * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
4778 * online CPU before, cpus_allowed of all its workers should be restored.
4780 static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
4782 static cpumask_t cpumask;
4783 struct worker *worker;
4784 int wi;
4786 lockdep_assert_held(&pool->manager_mutex);
4788 /* is @cpu allowed for @pool? */
4789 if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
4790 return;
4792 /* is @cpu the only online CPU? */
4793 cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
4794 if (cpumask_weight(&cpumask) != 1)
4795 return;
4797 /* as we're called from CPU_ONLINE, the following shouldn't fail */
4798 for_each_pool_worker(worker, wi, pool)
4799 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4800 pool->attrs->cpumask) < 0);
4804 * Workqueues should be brought up before normal priority CPU notifiers.
4805 * This will be registered high priority CPU notifier.
4807 static int workqueue_cpu_up_callback(struct notifier_block *nfb,
4808 unsigned long action,
4809 void *hcpu)
4811 int cpu = (unsigned long)hcpu;
4812 struct worker_pool *pool;
4813 struct workqueue_struct *wq;
4814 int pi;
4816 switch (action & ~CPU_TASKS_FROZEN) {
4817 case CPU_UP_PREPARE:
4818 for_each_cpu_worker_pool(pool, cpu) {
4819 if (pool->nr_workers)
4820 continue;
4821 if (create_and_start_worker(pool) < 0)
4822 return NOTIFY_BAD;
4824 break;
4826 case CPU_DOWN_FAILED:
4827 case CPU_ONLINE:
4828 mutex_lock(&wq_pool_mutex);
4830 for_each_pool(pool, pi) {
4831 mutex_lock(&pool->manager_mutex);
4833 if (pool->cpu == cpu) {
4834 spin_lock_irq(&pool->lock);
4835 pool->flags &= ~POOL_DISASSOCIATED;
4836 spin_unlock_irq(&pool->lock);
4838 rebind_workers(pool);
4839 } else if (pool->cpu < 0) {
4840 restore_unbound_workers_cpumask(pool, cpu);
4843 mutex_unlock(&pool->manager_mutex);
4846 /* update NUMA affinity of unbound workqueues */
4847 list_for_each_entry(wq, &workqueues, list)
4848 wq_update_unbound_numa(wq, cpu, true);
4850 mutex_unlock(&wq_pool_mutex);
4851 break;
4853 return NOTIFY_OK;
4857 * Workqueues should be brought down after normal priority CPU notifiers.
4858 * This will be registered as low priority CPU notifier.
4860 static int workqueue_cpu_down_callback(struct notifier_block *nfb,
4861 unsigned long action,
4862 void *hcpu)
4864 int cpu = (unsigned long)hcpu;
4865 struct work_struct unbind_work;
4866 struct workqueue_struct *wq;
4868 switch (action & ~CPU_TASKS_FROZEN) {
4869 case CPU_DOWN_PREPARE:
4870 /* unbinding per-cpu workers should happen on the local CPU */
4871 INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
4872 queue_work_on(cpu, system_highpri_wq, &unbind_work);
4874 /* update NUMA affinity of unbound workqueues */
4875 mutex_lock(&wq_pool_mutex);
4876 list_for_each_entry(wq, &workqueues, list)
4877 wq_update_unbound_numa(wq, cpu, false);
4878 mutex_unlock(&wq_pool_mutex);
4880 /* wait for per-cpu unbinding to finish */
4881 flush_work(&unbind_work);
4882 break;
4884 return NOTIFY_OK;
4887 #ifdef CONFIG_SMP
4889 struct work_for_cpu {
4890 struct work_struct work;
4891 long (*fn)(void *);
4892 void *arg;
4893 long ret;
4896 static void work_for_cpu_fn(struct work_struct *work)
4898 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
4900 wfc->ret = wfc->fn(wfc->arg);
4904 * work_on_cpu - run a function in user context on a particular cpu
4905 * @cpu: the cpu to run on
4906 * @fn: the function to run
4907 * @arg: the function arg
4909 * It is up to the caller to ensure that the cpu doesn't go offline.
4910 * The caller must not hold any locks which would prevent @fn from completing.
4912 * Return: The value @fn returns.
4914 long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
4916 struct work_for_cpu wfc = { .fn = fn, .arg = arg };
4918 INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
4919 schedule_work_on(cpu, &wfc.work);
4922 * The work item is on-stack and can't lead to deadlock through
4923 * flushing. Use __flush_work() to avoid spurious lockdep warnings
4924 * when work_on_cpu()s are nested.
4926 __flush_work(&wfc.work);
4928 return wfc.ret;
4930 EXPORT_SYMBOL_GPL(work_on_cpu);
4931 #endif /* CONFIG_SMP */
4933 #ifdef CONFIG_FREEZER
4936 * freeze_workqueues_begin - begin freezing workqueues
4938 * Start freezing workqueues. After this function returns, all freezable
4939 * workqueues will queue new works to their delayed_works list instead of
4940 * pool->worklist.
4942 * CONTEXT:
4943 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4945 void freeze_workqueues_begin(void)
4947 struct worker_pool *pool;
4948 struct workqueue_struct *wq;
4949 struct pool_workqueue *pwq;
4950 int pi;
4952 mutex_lock(&wq_pool_mutex);
4954 WARN_ON_ONCE(workqueue_freezing);
4955 workqueue_freezing = true;
4957 /* set FREEZING */
4958 for_each_pool(pool, pi) {
4959 spin_lock_irq(&pool->lock);
4960 WARN_ON_ONCE(pool->flags & POOL_FREEZING);
4961 pool->flags |= POOL_FREEZING;
4962 spin_unlock_irq(&pool->lock);
4965 list_for_each_entry(wq, &workqueues, list) {
4966 mutex_lock(&wq->mutex);
4967 for_each_pwq(pwq, wq)
4968 pwq_adjust_max_active(pwq);
4969 mutex_unlock(&wq->mutex);
4972 mutex_unlock(&wq_pool_mutex);
4976 * freeze_workqueues_busy - are freezable workqueues still busy?
4978 * Check whether freezing is complete. This function must be called
4979 * between freeze_workqueues_begin() and thaw_workqueues().
4981 * CONTEXT:
4982 * Grabs and releases wq_pool_mutex.
4984 * Return:
4985 * %true if some freezable workqueues are still busy. %false if freezing
4986 * is complete.
4988 bool freeze_workqueues_busy(void)
4990 bool busy = false;
4991 struct workqueue_struct *wq;
4992 struct pool_workqueue *pwq;
4994 mutex_lock(&wq_pool_mutex);
4996 WARN_ON_ONCE(!workqueue_freezing);
4998 list_for_each_entry(wq, &workqueues, list) {
4999 if (!(wq->flags & WQ_FREEZABLE))
5000 continue;
5002 * nr_active is monotonically decreasing. It's safe
5003 * to peek without lock.
5005 rcu_read_lock_sched();
5006 for_each_pwq(pwq, wq) {
5007 WARN_ON_ONCE(pwq->nr_active < 0);
5008 if (pwq->nr_active) {
5009 busy = true;
5010 rcu_read_unlock_sched();
5011 goto out_unlock;
5014 rcu_read_unlock_sched();
5016 out_unlock:
5017 mutex_unlock(&wq_pool_mutex);
5018 return busy;
5022 * thaw_workqueues - thaw workqueues
5024 * Thaw workqueues. Normal queueing is restored and all collected
5025 * frozen works are transferred to their respective pool worklists.
5027 * CONTEXT:
5028 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5030 void thaw_workqueues(void)
5032 struct workqueue_struct *wq;
5033 struct pool_workqueue *pwq;
5034 struct worker_pool *pool;
5035 int pi;
5037 mutex_lock(&wq_pool_mutex);
5039 if (!workqueue_freezing)
5040 goto out_unlock;
5042 /* clear FREEZING */
5043 for_each_pool(pool, pi) {
5044 spin_lock_irq(&pool->lock);
5045 WARN_ON_ONCE(!(pool->flags & POOL_FREEZING));
5046 pool->flags &= ~POOL_FREEZING;
5047 spin_unlock_irq(&pool->lock);
5050 /* restore max_active and repopulate worklist */
5051 list_for_each_entry(wq, &workqueues, list) {
5052 mutex_lock(&wq->mutex);
5053 for_each_pwq(pwq, wq)
5054 pwq_adjust_max_active(pwq);
5055 mutex_unlock(&wq->mutex);
5058 workqueue_freezing = false;
5059 out_unlock:
5060 mutex_unlock(&wq_pool_mutex);
5062 #endif /* CONFIG_FREEZER */
5064 static void __init wq_numa_init(void)
5066 cpumask_var_t *tbl;
5067 int node, cpu;
5069 /* determine NUMA pwq table len - highest node id + 1 */
5070 for_each_node(node)
5071 wq_numa_tbl_len = max(wq_numa_tbl_len, node + 1);
5073 if (num_possible_nodes() <= 1)
5074 return;
5076 if (wq_disable_numa) {
5077 pr_info("workqueue: NUMA affinity support disabled\n");
5078 return;
5081 wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs(GFP_KERNEL);
5082 BUG_ON(!wq_update_unbound_numa_attrs_buf);
5085 * We want masks of possible CPUs of each node which isn't readily
5086 * available. Build one from cpu_to_node() which should have been
5087 * fully initialized by now.
5089 tbl = kzalloc(wq_numa_tbl_len * sizeof(tbl[0]), GFP_KERNEL);
5090 BUG_ON(!tbl);
5092 for_each_node(node)
5093 BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
5094 node_online(node) ? node : NUMA_NO_NODE));
5096 for_each_possible_cpu(cpu) {
5097 node = cpu_to_node(cpu);
5098 if (WARN_ON(node == NUMA_NO_NODE)) {
5099 pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
5100 /* happens iff arch is bonkers, let's just proceed */
5101 return;
5103 cpumask_set_cpu(cpu, tbl[node]);
5106 wq_numa_possible_cpumask = tbl;
5107 wq_numa_enabled = true;
5110 static int __init init_workqueues(void)
5112 int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
5113 int i, cpu;
5115 /* make sure we have enough bits for OFFQ pool ID */
5116 BUILD_BUG_ON((1LU << (BITS_PER_LONG - WORK_OFFQ_POOL_SHIFT)) <
5117 WORK_CPU_END * NR_STD_WORKER_POOLS);
5119 WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
5121 pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
5123 cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
5124 hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
5126 wq_numa_init();
5128 /* initialize CPU pools */
5129 for_each_possible_cpu(cpu) {
5130 struct worker_pool *pool;
5132 i = 0;
5133 for_each_cpu_worker_pool(pool, cpu) {
5134 BUG_ON(init_worker_pool(pool));
5135 pool->cpu = cpu;
5136 cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
5137 pool->attrs->nice = std_nice[i++];
5138 pool->node = cpu_to_node(cpu);
5140 /* alloc pool ID */
5141 mutex_lock(&wq_pool_mutex);
5142 BUG_ON(worker_pool_assign_id(pool));
5143 mutex_unlock(&wq_pool_mutex);
5147 /* create the initial worker */
5148 for_each_online_cpu(cpu) {
5149 struct worker_pool *pool;
5151 for_each_cpu_worker_pool(pool, cpu) {
5152 pool->flags &= ~POOL_DISASSOCIATED;
5153 BUG_ON(create_and_start_worker(pool) < 0);
5157 /* create default unbound and ordered wq attrs */
5158 for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
5159 struct workqueue_attrs *attrs;
5161 BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
5162 attrs->nice = std_nice[i];
5163 unbound_std_wq_attrs[i] = attrs;
5166 * An ordered wq should have only one pwq as ordering is
5167 * guaranteed by max_active which is enforced by pwqs.
5168 * Turn off NUMA so that dfl_pwq is used for all nodes.
5170 BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
5171 attrs->nice = std_nice[i];
5172 attrs->no_numa = true;
5173 ordered_wq_attrs[i] = attrs;
5176 system_wq = alloc_workqueue("events", 0, 0);
5177 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
5178 system_long_wq = alloc_workqueue("events_long", 0, 0);
5179 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
5180 WQ_UNBOUND_MAX_ACTIVE);
5181 system_freezable_wq = alloc_workqueue("events_freezable",
5182 WQ_FREEZABLE, 0);
5183 system_power_efficient_wq = alloc_workqueue("events_power_efficient",
5184 WQ_POWER_EFFICIENT, 0);
5185 system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
5186 WQ_FREEZABLE | WQ_POWER_EFFICIENT,
5188 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
5189 !system_unbound_wq || !system_freezable_wq ||
5190 !system_power_efficient_wq ||
5191 !system_freezable_power_efficient_wq);
5192 return 0;
5194 early_initcall(init_workqueues);