target: Fix linux-4.1.y specific compile warning
[linux/fpc-iii.git] / kernel / workqueue.c
blob6d631161705c511c8050cf3c6887806a7ab03b6b
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 * attach_mutex to avoid changing binding state while
69 * worker_attach_to_pool() is in progress.
71 POOL_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
73 /* worker flags */
74 WORKER_DIE = 1 << 1, /* die die die */
75 WORKER_IDLE = 1 << 2, /* is idle */
76 WORKER_PREP = 1 << 3, /* preparing to run works */
77 WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
78 WORKER_UNBOUND = 1 << 7, /* worker is unbound */
79 WORKER_REBOUND = 1 << 8, /* worker was rebound */
81 WORKER_NOT_RUNNING = WORKER_PREP | WORKER_CPU_INTENSIVE |
82 WORKER_UNBOUND | WORKER_REBOUND,
84 NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */
86 UNBOUND_POOL_HASH_ORDER = 6, /* hashed by pool->attrs */
87 BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
89 MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
90 IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
92 MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
93 /* call for help after 10ms
94 (min two ticks) */
95 MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
96 CREATE_COOLDOWN = HZ, /* time to breath after fail */
99 * Rescue workers are used only on emergencies and shared by
100 * all cpus. Give MIN_NICE.
102 RESCUER_NICE_LEVEL = MIN_NICE,
103 HIGHPRI_NICE_LEVEL = MIN_NICE,
105 WQ_NAME_LEN = 24,
109 * Structure fields follow one of the following exclusion rules.
111 * I: Modifiable by initialization/destruction paths and read-only for
112 * everyone else.
114 * P: Preemption protected. Disabling preemption is enough and should
115 * only be modified and accessed from the local cpu.
117 * L: pool->lock protected. Access with pool->lock held.
119 * X: During normal operation, modification requires pool->lock and should
120 * be done only from local cpu. Either disabling preemption on local
121 * cpu or grabbing pool->lock is enough for read access. If
122 * POOL_DISASSOCIATED is set, it's identical to L.
124 * A: pool->attach_mutex protected.
126 * PL: wq_pool_mutex protected.
128 * PR: wq_pool_mutex protected for writes. Sched-RCU protected for reads.
130 * PW: wq_pool_mutex and wq->mutex protected for writes. Either for reads.
132 * PWR: wq_pool_mutex and wq->mutex protected for writes. Either or
133 * sched-RCU for reads.
135 * WQ: wq->mutex protected.
137 * WR: wq->mutex protected for writes. Sched-RCU protected for reads.
139 * MD: wq_mayday_lock protected.
142 /* struct worker is defined in workqueue_internal.h */
144 struct worker_pool {
145 spinlock_t lock; /* the pool lock */
146 int cpu; /* I: the associated cpu */
147 int node; /* I: the associated node ID */
148 int id; /* I: pool ID */
149 unsigned int flags; /* X: flags */
151 struct list_head worklist; /* L: list of pending works */
152 int nr_workers; /* L: total number of workers */
154 /* nr_idle includes the ones off idle_list for rebinding */
155 int nr_idle; /* L: currently idle ones */
157 struct list_head idle_list; /* X: list of idle workers */
158 struct timer_list idle_timer; /* L: worker idle timeout */
159 struct timer_list mayday_timer; /* L: SOS timer for workers */
161 /* a workers is either on busy_hash or idle_list, or the manager */
162 DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
163 /* L: hash of busy workers */
165 /* see manage_workers() for details on the two manager mutexes */
166 struct mutex manager_arb; /* manager arbitration */
167 struct worker *manager; /* L: purely informational */
168 struct mutex attach_mutex; /* attach/detach exclusion */
169 struct list_head workers; /* A: attached workers */
170 struct completion *detach_completion; /* all workers detached */
172 struct ida worker_ida; /* worker IDs for task name */
174 struct workqueue_attrs *attrs; /* I: worker attributes */
175 struct hlist_node hash_node; /* PL: unbound_pool_hash node */
176 int refcnt; /* PL: refcnt for unbound pools */
179 * The current concurrency level. As it's likely to be accessed
180 * from other CPUs during try_to_wake_up(), put it in a separate
181 * cacheline.
183 atomic_t nr_running ____cacheline_aligned_in_smp;
186 * Destruction of pool is sched-RCU protected to allow dereferences
187 * from get_work_pool().
189 struct rcu_head rcu;
190 } ____cacheline_aligned_in_smp;
193 * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
194 * of work_struct->data are used for flags and the remaining high bits
195 * point to the pwq; thus, pwqs need to be aligned at two's power of the
196 * number of flag bits.
198 struct pool_workqueue {
199 struct worker_pool *pool; /* I: the associated pool */
200 struct workqueue_struct *wq; /* I: the owning workqueue */
201 int work_color; /* L: current color */
202 int flush_color; /* L: flushing color */
203 int refcnt; /* L: reference count */
204 int nr_in_flight[WORK_NR_COLORS];
205 /* L: nr of in_flight works */
206 int nr_active; /* L: nr of active works */
207 int max_active; /* L: max active works */
208 struct list_head delayed_works; /* L: delayed works */
209 struct list_head pwqs_node; /* WR: node on wq->pwqs */
210 struct list_head mayday_node; /* MD: node on wq->maydays */
213 * Release of unbound pwq is punted to system_wq. See put_pwq()
214 * and pwq_unbound_release_workfn() for details. pool_workqueue
215 * itself is also sched-RCU protected so that the first pwq can be
216 * determined without grabbing wq->mutex.
218 struct work_struct unbound_release_work;
219 struct rcu_head rcu;
220 } __aligned(1 << WORK_STRUCT_FLAG_BITS);
223 * Structure used to wait for workqueue flush.
225 struct wq_flusher {
226 struct list_head list; /* WQ: list of flushers */
227 int flush_color; /* WQ: flush color waiting for */
228 struct completion done; /* flush completion */
231 struct wq_device;
234 * The externally visible workqueue. It relays the issued work items to
235 * the appropriate worker_pool through its pool_workqueues.
237 struct workqueue_struct {
238 struct list_head pwqs; /* WR: all pwqs of this wq */
239 struct list_head list; /* PR: list of all workqueues */
241 struct mutex mutex; /* protects this wq */
242 int work_color; /* WQ: current work color */
243 int flush_color; /* WQ: current flush color */
244 atomic_t nr_pwqs_to_flush; /* flush in progress */
245 struct wq_flusher *first_flusher; /* WQ: first flusher */
246 struct list_head flusher_queue; /* WQ: flush waiters */
247 struct list_head flusher_overflow; /* WQ: flush overflow list */
249 struct list_head maydays; /* MD: pwqs requesting rescue */
250 struct worker *rescuer; /* I: rescue worker */
252 int nr_drainers; /* WQ: drain in progress */
253 int saved_max_active; /* WQ: saved pwq max_active */
255 struct workqueue_attrs *unbound_attrs; /* PW: only for unbound wqs */
256 struct pool_workqueue *dfl_pwq; /* PW: only for unbound wqs */
258 #ifdef CONFIG_SYSFS
259 struct wq_device *wq_dev; /* I: for sysfs interface */
260 #endif
261 #ifdef CONFIG_LOCKDEP
262 struct lockdep_map lockdep_map;
263 #endif
264 char name[WQ_NAME_LEN]; /* I: workqueue name */
267 * Destruction of workqueue_struct is sched-RCU protected to allow
268 * walking the workqueues list without grabbing wq_pool_mutex.
269 * This is used to dump all workqueues from sysrq.
271 struct rcu_head rcu;
273 /* hot fields used during command issue, aligned to cacheline */
274 unsigned int flags ____cacheline_aligned; /* WQ: WQ_* flags */
275 struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */
276 struct pool_workqueue __rcu *numa_pwq_tbl[]; /* PWR: unbound pwqs indexed by node */
279 static struct kmem_cache *pwq_cache;
281 static cpumask_var_t *wq_numa_possible_cpumask;
282 /* possible CPUs of each node */
284 static bool wq_disable_numa;
285 module_param_named(disable_numa, wq_disable_numa, bool, 0444);
287 /* see the comment above the definition of WQ_POWER_EFFICIENT */
288 #ifdef CONFIG_WQ_POWER_EFFICIENT_DEFAULT
289 static bool wq_power_efficient = true;
290 #else
291 static bool wq_power_efficient;
292 #endif
294 module_param_named(power_efficient, wq_power_efficient, bool, 0444);
296 static bool wq_numa_enabled; /* unbound NUMA affinity enabled */
298 /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
299 static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf;
301 static DEFINE_MUTEX(wq_pool_mutex); /* protects pools and workqueues list */
302 static DEFINE_SPINLOCK(wq_mayday_lock); /* protects wq->maydays list */
304 static LIST_HEAD(workqueues); /* PR: list of all workqueues */
305 static bool workqueue_freezing; /* PL: have wqs started freezing? */
307 /* the per-cpu worker pools */
308 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
309 cpu_worker_pools);
311 static DEFINE_IDR(worker_pool_idr); /* PR: idr of all pools */
313 /* PL: hash of all unbound pools keyed by pool->attrs */
314 static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
316 /* I: attributes used when instantiating standard unbound pools on demand */
317 static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
319 /* I: attributes used when instantiating ordered pools on demand */
320 static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
322 struct workqueue_struct *system_wq __read_mostly;
323 EXPORT_SYMBOL(system_wq);
324 struct workqueue_struct *system_highpri_wq __read_mostly;
325 EXPORT_SYMBOL_GPL(system_highpri_wq);
326 struct workqueue_struct *system_long_wq __read_mostly;
327 EXPORT_SYMBOL_GPL(system_long_wq);
328 struct workqueue_struct *system_unbound_wq __read_mostly;
329 EXPORT_SYMBOL_GPL(system_unbound_wq);
330 struct workqueue_struct *system_freezable_wq __read_mostly;
331 EXPORT_SYMBOL_GPL(system_freezable_wq);
332 struct workqueue_struct *system_power_efficient_wq __read_mostly;
333 EXPORT_SYMBOL_GPL(system_power_efficient_wq);
334 struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
335 EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
337 static int worker_thread(void *__worker);
338 static void copy_workqueue_attrs(struct workqueue_attrs *to,
339 const struct workqueue_attrs *from);
340 static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
342 #define CREATE_TRACE_POINTS
343 #include <trace/events/workqueue.h>
345 #define assert_rcu_or_pool_mutex() \
346 rcu_lockdep_assert(rcu_read_lock_sched_held() || \
347 lockdep_is_held(&wq_pool_mutex), \
348 "sched RCU or wq_pool_mutex should be held")
350 #define assert_rcu_or_wq_mutex(wq) \
351 rcu_lockdep_assert(rcu_read_lock_sched_held() || \
352 lockdep_is_held(&wq->mutex), \
353 "sched RCU or wq->mutex should be held")
355 #define assert_rcu_or_wq_mutex_or_pool_mutex(wq) \
356 rcu_lockdep_assert(rcu_read_lock_sched_held() || \
357 lockdep_is_held(&wq->mutex) || \
358 lockdep_is_held(&wq_pool_mutex), \
359 "sched RCU, wq->mutex or wq_pool_mutex should be held")
361 #define for_each_cpu_worker_pool(pool, cpu) \
362 for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
363 (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
364 (pool)++)
367 * for_each_pool - iterate through all worker_pools in the system
368 * @pool: iteration cursor
369 * @pi: integer used for iteration
371 * This must be called either with wq_pool_mutex held or sched RCU read
372 * locked. If the pool needs to be used beyond the locking in effect, the
373 * caller is responsible for guaranteeing that the pool stays online.
375 * The if/else clause exists only for the lockdep assertion and can be
376 * ignored.
378 #define for_each_pool(pool, pi) \
379 idr_for_each_entry(&worker_pool_idr, pool, pi) \
380 if (({ assert_rcu_or_pool_mutex(); false; })) { } \
381 else
384 * for_each_pool_worker - iterate through all workers of a worker_pool
385 * @worker: iteration cursor
386 * @pool: worker_pool to iterate workers of
388 * This must be called with @pool->attach_mutex.
390 * The if/else clause exists only for the lockdep assertion and can be
391 * ignored.
393 #define for_each_pool_worker(worker, pool) \
394 list_for_each_entry((worker), &(pool)->workers, node) \
395 if (({ lockdep_assert_held(&pool->attach_mutex); false; })) { } \
396 else
399 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
400 * @pwq: iteration cursor
401 * @wq: the target workqueue
403 * This must be called either with wq->mutex held or sched RCU read locked.
404 * If the pwq needs to be used beyond the locking in effect, the caller is
405 * responsible for guaranteeing that the pwq stays online.
407 * The if/else clause exists only for the lockdep assertion and can be
408 * ignored.
410 #define for_each_pwq(pwq, wq) \
411 list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node) \
412 if (({ assert_rcu_or_wq_mutex(wq); false; })) { } \
413 else
415 #ifdef CONFIG_DEBUG_OBJECTS_WORK
417 static struct debug_obj_descr work_debug_descr;
419 static void *work_debug_hint(void *addr)
421 return ((struct work_struct *) addr)->func;
425 * fixup_init is called when:
426 * - an active object is initialized
428 static int work_fixup_init(void *addr, enum debug_obj_state state)
430 struct work_struct *work = addr;
432 switch (state) {
433 case ODEBUG_STATE_ACTIVE:
434 cancel_work_sync(work);
435 debug_object_init(work, &work_debug_descr);
436 return 1;
437 default:
438 return 0;
443 * fixup_activate is called when:
444 * - an active object is activated
445 * - an unknown object is activated (might be a statically initialized object)
447 static int work_fixup_activate(void *addr, enum debug_obj_state state)
449 struct work_struct *work = addr;
451 switch (state) {
453 case ODEBUG_STATE_NOTAVAILABLE:
455 * This is not really a fixup. The work struct was
456 * statically initialized. We just make sure that it
457 * is tracked in the object tracker.
459 if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
460 debug_object_init(work, &work_debug_descr);
461 debug_object_activate(work, &work_debug_descr);
462 return 0;
464 WARN_ON_ONCE(1);
465 return 0;
467 case ODEBUG_STATE_ACTIVE:
468 WARN_ON(1);
470 default:
471 return 0;
476 * fixup_free is called when:
477 * - an active object is freed
479 static int work_fixup_free(void *addr, enum debug_obj_state state)
481 struct work_struct *work = addr;
483 switch (state) {
484 case ODEBUG_STATE_ACTIVE:
485 cancel_work_sync(work);
486 debug_object_free(work, &work_debug_descr);
487 return 1;
488 default:
489 return 0;
493 static struct debug_obj_descr work_debug_descr = {
494 .name = "work_struct",
495 .debug_hint = work_debug_hint,
496 .fixup_init = work_fixup_init,
497 .fixup_activate = work_fixup_activate,
498 .fixup_free = work_fixup_free,
501 static inline void debug_work_activate(struct work_struct *work)
503 debug_object_activate(work, &work_debug_descr);
506 static inline void debug_work_deactivate(struct work_struct *work)
508 debug_object_deactivate(work, &work_debug_descr);
511 void __init_work(struct work_struct *work, int onstack)
513 if (onstack)
514 debug_object_init_on_stack(work, &work_debug_descr);
515 else
516 debug_object_init(work, &work_debug_descr);
518 EXPORT_SYMBOL_GPL(__init_work);
520 void destroy_work_on_stack(struct work_struct *work)
522 debug_object_free(work, &work_debug_descr);
524 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
526 void destroy_delayed_work_on_stack(struct delayed_work *work)
528 destroy_timer_on_stack(&work->timer);
529 debug_object_free(&work->work, &work_debug_descr);
531 EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
533 #else
534 static inline void debug_work_activate(struct work_struct *work) { }
535 static inline void debug_work_deactivate(struct work_struct *work) { }
536 #endif
539 * worker_pool_assign_id - allocate ID and assing it to @pool
540 * @pool: the pool pointer of interest
542 * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
543 * successfully, -errno on failure.
545 static int worker_pool_assign_id(struct worker_pool *pool)
547 int ret;
549 lockdep_assert_held(&wq_pool_mutex);
551 ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
552 GFP_KERNEL);
553 if (ret >= 0) {
554 pool->id = ret;
555 return 0;
557 return ret;
561 * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
562 * @wq: the target workqueue
563 * @node: the node ID
565 * This must be called with any of wq_pool_mutex, wq->mutex or sched RCU
566 * read locked.
567 * If the pwq needs to be used beyond the locking in effect, the caller is
568 * responsible for guaranteeing that the pwq stays online.
570 * Return: The unbound pool_workqueue for @node.
572 static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
573 int node)
575 assert_rcu_or_wq_mutex_or_pool_mutex(wq);
578 * XXX: @node can be NUMA_NO_NODE if CPU goes offline while a
579 * delayed item is pending. The plan is to keep CPU -> NODE
580 * mapping valid and stable across CPU on/offlines. Once that
581 * happens, this workaround can be removed.
583 if (unlikely(node == NUMA_NO_NODE))
584 return wq->dfl_pwq;
586 return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
589 static unsigned int work_color_to_flags(int color)
591 return color << WORK_STRUCT_COLOR_SHIFT;
594 static int get_work_color(struct work_struct *work)
596 return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
597 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
600 static int work_next_color(int color)
602 return (color + 1) % WORK_NR_COLORS;
606 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
607 * contain the pointer to the queued pwq. Once execution starts, the flag
608 * is cleared and the high bits contain OFFQ flags and pool ID.
610 * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
611 * and clear_work_data() can be used to set the pwq, pool or clear
612 * work->data. These functions should only be called while the work is
613 * owned - ie. while the PENDING bit is set.
615 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
616 * corresponding to a work. Pool is available once the work has been
617 * queued anywhere after initialization until it is sync canceled. pwq is
618 * available only while the work item is queued.
620 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
621 * canceled. While being canceled, a work item may have its PENDING set
622 * but stay off timer and worklist for arbitrarily long and nobody should
623 * try to steal the PENDING bit.
625 static inline void set_work_data(struct work_struct *work, unsigned long data,
626 unsigned long flags)
628 WARN_ON_ONCE(!work_pending(work));
629 atomic_long_set(&work->data, data | flags | work_static(work));
632 static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
633 unsigned long extra_flags)
635 set_work_data(work, (unsigned long)pwq,
636 WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
639 static void set_work_pool_and_keep_pending(struct work_struct *work,
640 int pool_id)
642 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
643 WORK_STRUCT_PENDING);
646 static void set_work_pool_and_clear_pending(struct work_struct *work,
647 int pool_id)
650 * The following wmb is paired with the implied mb in
651 * test_and_set_bit(PENDING) and ensures all updates to @work made
652 * here are visible to and precede any updates by the next PENDING
653 * owner.
655 smp_wmb();
656 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
659 static void clear_work_data(struct work_struct *work)
661 smp_wmb(); /* see set_work_pool_and_clear_pending() */
662 set_work_data(work, WORK_STRUCT_NO_POOL, 0);
665 static struct pool_workqueue *get_work_pwq(struct work_struct *work)
667 unsigned long data = atomic_long_read(&work->data);
669 if (data & WORK_STRUCT_PWQ)
670 return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
671 else
672 return NULL;
676 * get_work_pool - return the worker_pool a given work was associated with
677 * @work: the work item of interest
679 * Pools are created and destroyed under wq_pool_mutex, and allows read
680 * access under sched-RCU read lock. As such, this function should be
681 * called under wq_pool_mutex or with preemption disabled.
683 * All fields of the returned pool are accessible as long as the above
684 * mentioned locking is in effect. If the returned pool needs to be used
685 * beyond the critical section, the caller is responsible for ensuring the
686 * returned pool is and stays online.
688 * Return: The worker_pool @work was last associated with. %NULL if none.
690 static struct worker_pool *get_work_pool(struct work_struct *work)
692 unsigned long data = atomic_long_read(&work->data);
693 int pool_id;
695 assert_rcu_or_pool_mutex();
697 if (data & WORK_STRUCT_PWQ)
698 return ((struct pool_workqueue *)
699 (data & WORK_STRUCT_WQ_DATA_MASK))->pool;
701 pool_id = data >> WORK_OFFQ_POOL_SHIFT;
702 if (pool_id == WORK_OFFQ_POOL_NONE)
703 return NULL;
705 return idr_find(&worker_pool_idr, pool_id);
709 * get_work_pool_id - return the worker pool ID a given work is associated with
710 * @work: the work item of interest
712 * Return: The worker_pool ID @work was last associated with.
713 * %WORK_OFFQ_POOL_NONE if none.
715 static int get_work_pool_id(struct work_struct *work)
717 unsigned long data = atomic_long_read(&work->data);
719 if (data & WORK_STRUCT_PWQ)
720 return ((struct pool_workqueue *)
721 (data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
723 return data >> WORK_OFFQ_POOL_SHIFT;
726 static void mark_work_canceling(struct work_struct *work)
728 unsigned long pool_id = get_work_pool_id(work);
730 pool_id <<= WORK_OFFQ_POOL_SHIFT;
731 set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
734 static bool work_is_canceling(struct work_struct *work)
736 unsigned long data = atomic_long_read(&work->data);
738 return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
742 * Policy functions. These define the policies on how the global worker
743 * pools are managed. Unless noted otherwise, these functions assume that
744 * they're being called with pool->lock held.
747 static bool __need_more_worker(struct worker_pool *pool)
749 return !atomic_read(&pool->nr_running);
753 * Need to wake up a worker? Called from anything but currently
754 * running workers.
756 * Note that, because unbound workers never contribute to nr_running, this
757 * function will always return %true for unbound pools as long as the
758 * worklist isn't empty.
760 static bool need_more_worker(struct worker_pool *pool)
762 return !list_empty(&pool->worklist) && __need_more_worker(pool);
765 /* Can I start working? Called from busy but !running workers. */
766 static bool may_start_working(struct worker_pool *pool)
768 return pool->nr_idle;
771 /* Do I need to keep working? Called from currently running workers. */
772 static bool keep_working(struct worker_pool *pool)
774 return !list_empty(&pool->worklist) &&
775 atomic_read(&pool->nr_running) <= 1;
778 /* Do we need a new worker? Called from manager. */
779 static bool need_to_create_worker(struct worker_pool *pool)
781 return need_more_worker(pool) && !may_start_working(pool);
784 /* Do we have too many workers and should some go away? */
785 static bool too_many_workers(struct worker_pool *pool)
787 bool managing = mutex_is_locked(&pool->manager_arb);
788 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
789 int nr_busy = pool->nr_workers - nr_idle;
791 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
795 * Wake up functions.
798 /* Return the first idle worker. Safe with preemption disabled */
799 static struct worker *first_idle_worker(struct worker_pool *pool)
801 if (unlikely(list_empty(&pool->idle_list)))
802 return NULL;
804 return list_first_entry(&pool->idle_list, struct worker, entry);
808 * wake_up_worker - wake up an idle worker
809 * @pool: worker pool to wake worker from
811 * Wake up the first idle worker of @pool.
813 * CONTEXT:
814 * spin_lock_irq(pool->lock).
816 static void wake_up_worker(struct worker_pool *pool)
818 struct worker *worker = first_idle_worker(pool);
820 if (likely(worker))
821 wake_up_process(worker->task);
825 * wq_worker_waking_up - a worker is waking up
826 * @task: task waking up
827 * @cpu: CPU @task is waking up to
829 * This function is called during try_to_wake_up() when a worker is
830 * being awoken.
832 * CONTEXT:
833 * spin_lock_irq(rq->lock)
835 void wq_worker_waking_up(struct task_struct *task, int cpu)
837 struct worker *worker = kthread_data(task);
839 if (!(worker->flags & WORKER_NOT_RUNNING)) {
840 WARN_ON_ONCE(worker->pool->cpu != cpu);
841 atomic_inc(&worker->pool->nr_running);
846 * wq_worker_sleeping - a worker is going to sleep
847 * @task: task going to sleep
848 * @cpu: CPU in question, must be the current CPU number
850 * This function is called during schedule() when a busy worker is
851 * going to sleep. Worker on the same cpu can be woken up by
852 * returning pointer to its task.
854 * CONTEXT:
855 * spin_lock_irq(rq->lock)
857 * Return:
858 * Worker task on @cpu to wake up, %NULL if none.
860 struct task_struct *wq_worker_sleeping(struct task_struct *task, int cpu)
862 struct worker *worker = kthread_data(task), *to_wakeup = NULL;
863 struct worker_pool *pool;
866 * Rescuers, which may not have all the fields set up like normal
867 * workers, also reach here, let's not access anything before
868 * checking NOT_RUNNING.
870 if (worker->flags & WORKER_NOT_RUNNING)
871 return NULL;
873 pool = worker->pool;
875 /* this can only happen on the local cpu */
876 if (WARN_ON_ONCE(cpu != raw_smp_processor_id() || pool->cpu != cpu))
877 return NULL;
880 * The counterpart of the following dec_and_test, implied mb,
881 * worklist not empty test sequence is in insert_work().
882 * Please read comment there.
884 * NOT_RUNNING is clear. This means that we're bound to and
885 * running on the local cpu w/ rq lock held and preemption
886 * disabled, which in turn means that none else could be
887 * manipulating idle_list, so dereferencing idle_list without pool
888 * lock is safe.
890 if (atomic_dec_and_test(&pool->nr_running) &&
891 !list_empty(&pool->worklist))
892 to_wakeup = first_idle_worker(pool);
893 return to_wakeup ? to_wakeup->task : NULL;
897 * worker_set_flags - set worker flags and adjust nr_running accordingly
898 * @worker: self
899 * @flags: flags to set
901 * Set @flags in @worker->flags and adjust nr_running accordingly.
903 * CONTEXT:
904 * spin_lock_irq(pool->lock)
906 static inline void worker_set_flags(struct worker *worker, unsigned int flags)
908 struct worker_pool *pool = worker->pool;
910 WARN_ON_ONCE(worker->task != current);
912 /* If transitioning into NOT_RUNNING, adjust nr_running. */
913 if ((flags & WORKER_NOT_RUNNING) &&
914 !(worker->flags & WORKER_NOT_RUNNING)) {
915 atomic_dec(&pool->nr_running);
918 worker->flags |= flags;
922 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
923 * @worker: self
924 * @flags: flags to clear
926 * Clear @flags in @worker->flags and adjust nr_running accordingly.
928 * CONTEXT:
929 * spin_lock_irq(pool->lock)
931 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
933 struct worker_pool *pool = worker->pool;
934 unsigned int oflags = worker->flags;
936 WARN_ON_ONCE(worker->task != current);
938 worker->flags &= ~flags;
941 * If transitioning out of NOT_RUNNING, increment nr_running. Note
942 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
943 * of multiple flags, not a single flag.
945 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
946 if (!(worker->flags & WORKER_NOT_RUNNING))
947 atomic_inc(&pool->nr_running);
951 * find_worker_executing_work - find worker which is executing a work
952 * @pool: pool of interest
953 * @work: work to find worker for
955 * Find a worker which is executing @work on @pool by searching
956 * @pool->busy_hash which is keyed by the address of @work. For a worker
957 * to match, its current execution should match the address of @work and
958 * its work function. This is to avoid unwanted dependency between
959 * unrelated work executions through a work item being recycled while still
960 * being executed.
962 * This is a bit tricky. A work item may be freed once its execution
963 * starts and nothing prevents the freed area from being recycled for
964 * another work item. If the same work item address ends up being reused
965 * before the original execution finishes, workqueue will identify the
966 * recycled work item as currently executing and make it wait until the
967 * current execution finishes, introducing an unwanted dependency.
969 * This function checks the work item address and work function to avoid
970 * false positives. Note that this isn't complete as one may construct a
971 * work function which can introduce dependency onto itself through a
972 * recycled work item. Well, if somebody wants to shoot oneself in the
973 * foot that badly, there's only so much we can do, and if such deadlock
974 * actually occurs, it should be easy to locate the culprit work function.
976 * CONTEXT:
977 * spin_lock_irq(pool->lock).
979 * Return:
980 * Pointer to worker which is executing @work if found, %NULL
981 * otherwise.
983 static struct worker *find_worker_executing_work(struct worker_pool *pool,
984 struct work_struct *work)
986 struct worker *worker;
988 hash_for_each_possible(pool->busy_hash, worker, hentry,
989 (unsigned long)work)
990 if (worker->current_work == work &&
991 worker->current_func == work->func)
992 return worker;
994 return NULL;
998 * move_linked_works - move linked works to a list
999 * @work: start of series of works to be scheduled
1000 * @head: target list to append @work to
1001 * @nextp: out paramter for nested worklist walking
1003 * Schedule linked works starting from @work to @head. Work series to
1004 * be scheduled starts at @work and includes any consecutive work with
1005 * WORK_STRUCT_LINKED set in its predecessor.
1007 * If @nextp is not NULL, it's updated to point to the next work of
1008 * the last scheduled work. This allows move_linked_works() to be
1009 * nested inside outer list_for_each_entry_safe().
1011 * CONTEXT:
1012 * spin_lock_irq(pool->lock).
1014 static void move_linked_works(struct work_struct *work, struct list_head *head,
1015 struct work_struct **nextp)
1017 struct work_struct *n;
1020 * Linked worklist will always end before the end of the list,
1021 * use NULL for list head.
1023 list_for_each_entry_safe_from(work, n, NULL, entry) {
1024 list_move_tail(&work->entry, head);
1025 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1026 break;
1030 * If we're already inside safe list traversal and have moved
1031 * multiple works to the scheduled queue, the next position
1032 * needs to be updated.
1034 if (nextp)
1035 *nextp = n;
1039 * get_pwq - get an extra reference on the specified pool_workqueue
1040 * @pwq: pool_workqueue to get
1042 * Obtain an extra reference on @pwq. The caller should guarantee that
1043 * @pwq has positive refcnt and be holding the matching pool->lock.
1045 static void get_pwq(struct pool_workqueue *pwq)
1047 lockdep_assert_held(&pwq->pool->lock);
1048 WARN_ON_ONCE(pwq->refcnt <= 0);
1049 pwq->refcnt++;
1053 * put_pwq - put a pool_workqueue reference
1054 * @pwq: pool_workqueue to put
1056 * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
1057 * destruction. The caller should be holding the matching pool->lock.
1059 static void put_pwq(struct pool_workqueue *pwq)
1061 lockdep_assert_held(&pwq->pool->lock);
1062 if (likely(--pwq->refcnt))
1063 return;
1064 if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
1065 return;
1067 * @pwq can't be released under pool->lock, bounce to
1068 * pwq_unbound_release_workfn(). This never recurses on the same
1069 * pool->lock as this path is taken only for unbound workqueues and
1070 * the release work item is scheduled on a per-cpu workqueue. To
1071 * avoid lockdep warning, unbound pool->locks are given lockdep
1072 * subclass of 1 in get_unbound_pool().
1074 schedule_work(&pwq->unbound_release_work);
1078 * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1079 * @pwq: pool_workqueue to put (can be %NULL)
1081 * put_pwq() with locking. This function also allows %NULL @pwq.
1083 static void put_pwq_unlocked(struct pool_workqueue *pwq)
1085 if (pwq) {
1087 * As both pwqs and pools are sched-RCU protected, the
1088 * following lock operations are safe.
1090 spin_lock_irq(&pwq->pool->lock);
1091 put_pwq(pwq);
1092 spin_unlock_irq(&pwq->pool->lock);
1096 static void pwq_activate_delayed_work(struct work_struct *work)
1098 struct pool_workqueue *pwq = get_work_pwq(work);
1100 trace_workqueue_activate_work(work);
1101 move_linked_works(work, &pwq->pool->worklist, NULL);
1102 __clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
1103 pwq->nr_active++;
1106 static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
1108 struct work_struct *work = list_first_entry(&pwq->delayed_works,
1109 struct work_struct, entry);
1111 pwq_activate_delayed_work(work);
1115 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1116 * @pwq: pwq of interest
1117 * @color: color of work which left the queue
1119 * A work either has completed or is removed from pending queue,
1120 * decrement nr_in_flight of its pwq and handle workqueue flushing.
1122 * CONTEXT:
1123 * spin_lock_irq(pool->lock).
1125 static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
1127 /* uncolored work items don't participate in flushing or nr_active */
1128 if (color == WORK_NO_COLOR)
1129 goto out_put;
1131 pwq->nr_in_flight[color]--;
1133 pwq->nr_active--;
1134 if (!list_empty(&pwq->delayed_works)) {
1135 /* one down, submit a delayed one */
1136 if (pwq->nr_active < pwq->max_active)
1137 pwq_activate_first_delayed(pwq);
1140 /* is flush in progress and are we at the flushing tip? */
1141 if (likely(pwq->flush_color != color))
1142 goto out_put;
1144 /* are there still in-flight works? */
1145 if (pwq->nr_in_flight[color])
1146 goto out_put;
1148 /* this pwq is done, clear flush_color */
1149 pwq->flush_color = -1;
1152 * If this was the last pwq, wake up the first flusher. It
1153 * will handle the rest.
1155 if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1156 complete(&pwq->wq->first_flusher->done);
1157 out_put:
1158 put_pwq(pwq);
1162 * try_to_grab_pending - steal work item from worklist and disable irq
1163 * @work: work item to steal
1164 * @is_dwork: @work is a delayed_work
1165 * @flags: place to store irq state
1167 * Try to grab PENDING bit of @work. This function can handle @work in any
1168 * stable state - idle, on timer or on worklist.
1170 * Return:
1171 * 1 if @work was pending and we successfully stole PENDING
1172 * 0 if @work was idle and we claimed PENDING
1173 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1174 * -ENOENT if someone else is canceling @work, this state may persist
1175 * for arbitrarily long
1177 * Note:
1178 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1179 * interrupted while holding PENDING and @work off queue, irq must be
1180 * disabled on entry. This, combined with delayed_work->timer being
1181 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1183 * On successful return, >= 0, irq is disabled and the caller is
1184 * responsible for releasing it using local_irq_restore(*@flags).
1186 * This function is safe to call from any context including IRQ handler.
1188 static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1189 unsigned long *flags)
1191 struct worker_pool *pool;
1192 struct pool_workqueue *pwq;
1194 local_irq_save(*flags);
1196 /* try to steal the timer if it exists */
1197 if (is_dwork) {
1198 struct delayed_work *dwork = to_delayed_work(work);
1201 * dwork->timer is irqsafe. If del_timer() fails, it's
1202 * guaranteed that the timer is not queued anywhere and not
1203 * running on the local CPU.
1205 if (likely(del_timer(&dwork->timer)))
1206 return 1;
1209 /* try to claim PENDING the normal way */
1210 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1211 return 0;
1214 * The queueing is in progress, or it is already queued. Try to
1215 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1217 pool = get_work_pool(work);
1218 if (!pool)
1219 goto fail;
1221 spin_lock(&pool->lock);
1223 * work->data is guaranteed to point to pwq only while the work
1224 * item is queued on pwq->wq, and both updating work->data to point
1225 * to pwq on queueing and to pool on dequeueing are done under
1226 * pwq->pool->lock. This in turn guarantees that, if work->data
1227 * points to pwq which is associated with a locked pool, the work
1228 * item is currently queued on that pool.
1230 pwq = get_work_pwq(work);
1231 if (pwq && pwq->pool == pool) {
1232 debug_work_deactivate(work);
1235 * A delayed work item cannot be grabbed directly because
1236 * it might have linked NO_COLOR work items which, if left
1237 * on the delayed_list, will confuse pwq->nr_active
1238 * management later on and cause stall. Make sure the work
1239 * item is activated before grabbing.
1241 if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1242 pwq_activate_delayed_work(work);
1244 list_del_init(&work->entry);
1245 pwq_dec_nr_in_flight(pwq, get_work_color(work));
1247 /* work->data points to pwq iff queued, point to pool */
1248 set_work_pool_and_keep_pending(work, pool->id);
1250 spin_unlock(&pool->lock);
1251 return 1;
1253 spin_unlock(&pool->lock);
1254 fail:
1255 local_irq_restore(*flags);
1256 if (work_is_canceling(work))
1257 return -ENOENT;
1258 cpu_relax();
1259 return -EAGAIN;
1263 * insert_work - insert a work into a pool
1264 * @pwq: pwq @work belongs to
1265 * @work: work to insert
1266 * @head: insertion point
1267 * @extra_flags: extra WORK_STRUCT_* flags to set
1269 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
1270 * work_struct flags.
1272 * CONTEXT:
1273 * spin_lock_irq(pool->lock).
1275 static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1276 struct list_head *head, unsigned int extra_flags)
1278 struct worker_pool *pool = pwq->pool;
1280 /* we own @work, set data and link */
1281 set_work_pwq(work, pwq, extra_flags);
1282 list_add_tail(&work->entry, head);
1283 get_pwq(pwq);
1286 * Ensure either wq_worker_sleeping() sees the above
1287 * list_add_tail() or we see zero nr_running to avoid workers lying
1288 * around lazily while there are works to be processed.
1290 smp_mb();
1292 if (__need_more_worker(pool))
1293 wake_up_worker(pool);
1297 * Test whether @work is being queued from another work executing on the
1298 * same workqueue.
1300 static bool is_chained_work(struct workqueue_struct *wq)
1302 struct worker *worker;
1304 worker = current_wq_worker();
1306 * Return %true iff I'm a worker execuing a work item on @wq. If
1307 * I'm @worker, it's safe to dereference it without locking.
1309 return worker && worker->current_pwq->wq == wq;
1312 static void __queue_work(int cpu, struct workqueue_struct *wq,
1313 struct work_struct *work)
1315 struct pool_workqueue *pwq;
1316 struct worker_pool *last_pool;
1317 struct list_head *worklist;
1318 unsigned int work_flags;
1319 unsigned int req_cpu = cpu;
1322 * While a work item is PENDING && off queue, a task trying to
1323 * steal the PENDING will busy-loop waiting for it to either get
1324 * queued or lose PENDING. Grabbing PENDING and queueing should
1325 * happen with IRQ disabled.
1327 WARN_ON_ONCE(!irqs_disabled());
1329 debug_work_activate(work);
1331 /* if draining, only works from the same workqueue are allowed */
1332 if (unlikely(wq->flags & __WQ_DRAINING) &&
1333 WARN_ON_ONCE(!is_chained_work(wq)))
1334 return;
1335 retry:
1336 if (req_cpu == WORK_CPU_UNBOUND)
1337 cpu = raw_smp_processor_id();
1339 /* pwq which will be used unless @work is executing elsewhere */
1340 if (!(wq->flags & WQ_UNBOUND))
1341 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1342 else
1343 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1346 * If @work was previously on a different pool, it might still be
1347 * running there, in which case the work needs to be queued on that
1348 * pool to guarantee non-reentrancy.
1350 last_pool = get_work_pool(work);
1351 if (last_pool && last_pool != pwq->pool) {
1352 struct worker *worker;
1354 spin_lock(&last_pool->lock);
1356 worker = find_worker_executing_work(last_pool, work);
1358 if (worker && worker->current_pwq->wq == wq) {
1359 pwq = worker->current_pwq;
1360 } else {
1361 /* meh... not running there, queue here */
1362 spin_unlock(&last_pool->lock);
1363 spin_lock(&pwq->pool->lock);
1365 } else {
1366 spin_lock(&pwq->pool->lock);
1370 * pwq is determined and locked. For unbound pools, we could have
1371 * raced with pwq release and it could already be dead. If its
1372 * refcnt is zero, repeat pwq selection. Note that pwqs never die
1373 * without another pwq replacing it in the numa_pwq_tbl or while
1374 * work items are executing on it, so the retrying is guaranteed to
1375 * make forward-progress.
1377 if (unlikely(!pwq->refcnt)) {
1378 if (wq->flags & WQ_UNBOUND) {
1379 spin_unlock(&pwq->pool->lock);
1380 cpu_relax();
1381 goto retry;
1383 /* oops */
1384 WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
1385 wq->name, cpu);
1388 /* pwq determined, queue */
1389 trace_workqueue_queue_work(req_cpu, pwq, work);
1391 if (WARN_ON(!list_empty(&work->entry))) {
1392 spin_unlock(&pwq->pool->lock);
1393 return;
1396 pwq->nr_in_flight[pwq->work_color]++;
1397 work_flags = work_color_to_flags(pwq->work_color);
1399 if (likely(pwq->nr_active < pwq->max_active)) {
1400 trace_workqueue_activate_work(work);
1401 pwq->nr_active++;
1402 worklist = &pwq->pool->worklist;
1403 } else {
1404 work_flags |= WORK_STRUCT_DELAYED;
1405 worklist = &pwq->delayed_works;
1408 insert_work(pwq, work, worklist, work_flags);
1410 spin_unlock(&pwq->pool->lock);
1414 * queue_work_on - queue work on specific cpu
1415 * @cpu: CPU number to execute work on
1416 * @wq: workqueue to use
1417 * @work: work to queue
1419 * We queue the work to a specific CPU, the caller must ensure it
1420 * can't go away.
1422 * Return: %false if @work was already on a queue, %true otherwise.
1424 bool queue_work_on(int cpu, struct workqueue_struct *wq,
1425 struct work_struct *work)
1427 bool ret = false;
1428 unsigned long flags;
1430 local_irq_save(flags);
1432 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1433 __queue_work(cpu, wq, work);
1434 ret = true;
1437 local_irq_restore(flags);
1438 return ret;
1440 EXPORT_SYMBOL(queue_work_on);
1442 void delayed_work_timer_fn(unsigned long __data)
1444 struct delayed_work *dwork = (struct delayed_work *)__data;
1446 /* should have been called from irqsafe timer with irq already off */
1447 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
1449 EXPORT_SYMBOL(delayed_work_timer_fn);
1451 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
1452 struct delayed_work *dwork, unsigned long delay)
1454 struct timer_list *timer = &dwork->timer;
1455 struct work_struct *work = &dwork->work;
1457 WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
1458 timer->data != (unsigned long)dwork);
1459 WARN_ON_ONCE(timer_pending(timer));
1460 WARN_ON_ONCE(!list_empty(&work->entry));
1463 * If @delay is 0, queue @dwork->work immediately. This is for
1464 * both optimization and correctness. The earliest @timer can
1465 * expire is on the closest next tick and delayed_work users depend
1466 * on that there's no such delay when @delay is 0.
1468 if (!delay) {
1469 __queue_work(cpu, wq, &dwork->work);
1470 return;
1473 timer_stats_timer_set_start_info(&dwork->timer);
1475 dwork->wq = wq;
1476 dwork->cpu = cpu;
1477 timer->expires = jiffies + delay;
1479 if (unlikely(cpu != WORK_CPU_UNBOUND))
1480 add_timer_on(timer, cpu);
1481 else
1482 add_timer(timer);
1486 * queue_delayed_work_on - queue work on specific CPU after delay
1487 * @cpu: CPU number to execute work on
1488 * @wq: workqueue to use
1489 * @dwork: work to queue
1490 * @delay: number of jiffies to wait before queueing
1492 * Return: %false if @work was already on a queue, %true otherwise. If
1493 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1494 * execution.
1496 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1497 struct delayed_work *dwork, unsigned long delay)
1499 struct work_struct *work = &dwork->work;
1500 bool ret = false;
1501 unsigned long flags;
1503 /* read the comment in __queue_work() */
1504 local_irq_save(flags);
1506 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1507 __queue_delayed_work(cpu, wq, dwork, delay);
1508 ret = true;
1511 local_irq_restore(flags);
1512 return ret;
1514 EXPORT_SYMBOL(queue_delayed_work_on);
1517 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1518 * @cpu: CPU number to execute work on
1519 * @wq: workqueue to use
1520 * @dwork: work to queue
1521 * @delay: number of jiffies to wait before queueing
1523 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1524 * modify @dwork's timer so that it expires after @delay. If @delay is
1525 * zero, @work is guaranteed to be scheduled immediately regardless of its
1526 * current state.
1528 * Return: %false if @dwork was idle and queued, %true if @dwork was
1529 * pending and its timer was modified.
1531 * This function is safe to call from any context including IRQ handler.
1532 * See try_to_grab_pending() for details.
1534 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
1535 struct delayed_work *dwork, unsigned long delay)
1537 unsigned long flags;
1538 int ret;
1540 do {
1541 ret = try_to_grab_pending(&dwork->work, true, &flags);
1542 } while (unlikely(ret == -EAGAIN));
1544 if (likely(ret >= 0)) {
1545 __queue_delayed_work(cpu, wq, dwork, delay);
1546 local_irq_restore(flags);
1549 /* -ENOENT from try_to_grab_pending() becomes %true */
1550 return ret;
1552 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
1555 * worker_enter_idle - enter idle state
1556 * @worker: worker which is entering idle state
1558 * @worker is entering idle state. Update stats and idle timer if
1559 * necessary.
1561 * LOCKING:
1562 * spin_lock_irq(pool->lock).
1564 static void worker_enter_idle(struct worker *worker)
1566 struct worker_pool *pool = worker->pool;
1568 if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
1569 WARN_ON_ONCE(!list_empty(&worker->entry) &&
1570 (worker->hentry.next || worker->hentry.pprev)))
1571 return;
1573 /* can't use worker_set_flags(), also called from create_worker() */
1574 worker->flags |= WORKER_IDLE;
1575 pool->nr_idle++;
1576 worker->last_active = jiffies;
1578 /* idle_list is LIFO */
1579 list_add(&worker->entry, &pool->idle_list);
1581 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1582 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1585 * Sanity check nr_running. Because wq_unbind_fn() releases
1586 * pool->lock between setting %WORKER_UNBOUND and zapping
1587 * nr_running, the warning may trigger spuriously. Check iff
1588 * unbind is not in progress.
1590 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1591 pool->nr_workers == pool->nr_idle &&
1592 atomic_read(&pool->nr_running));
1596 * worker_leave_idle - leave idle state
1597 * @worker: worker which is leaving idle state
1599 * @worker is leaving idle state. Update stats.
1601 * LOCKING:
1602 * spin_lock_irq(pool->lock).
1604 static void worker_leave_idle(struct worker *worker)
1606 struct worker_pool *pool = worker->pool;
1608 if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
1609 return;
1610 worker_clr_flags(worker, WORKER_IDLE);
1611 pool->nr_idle--;
1612 list_del_init(&worker->entry);
1615 static struct worker *alloc_worker(int node)
1617 struct worker *worker;
1619 worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
1620 if (worker) {
1621 INIT_LIST_HEAD(&worker->entry);
1622 INIT_LIST_HEAD(&worker->scheduled);
1623 INIT_LIST_HEAD(&worker->node);
1624 /* on creation a worker is in !idle && prep state */
1625 worker->flags = WORKER_PREP;
1627 return worker;
1631 * worker_attach_to_pool() - attach a worker to a pool
1632 * @worker: worker to be attached
1633 * @pool: the target pool
1635 * Attach @worker to @pool. Once attached, the %WORKER_UNBOUND flag and
1636 * cpu-binding of @worker are kept coordinated with the pool across
1637 * cpu-[un]hotplugs.
1639 static void worker_attach_to_pool(struct worker *worker,
1640 struct worker_pool *pool)
1642 mutex_lock(&pool->attach_mutex);
1645 * set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
1646 * online CPUs. It'll be re-applied when any of the CPUs come up.
1648 set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
1651 * The pool->attach_mutex ensures %POOL_DISASSOCIATED remains
1652 * stable across this function. See the comments above the
1653 * flag definition for details.
1655 if (pool->flags & POOL_DISASSOCIATED)
1656 worker->flags |= WORKER_UNBOUND;
1658 list_add_tail(&worker->node, &pool->workers);
1660 mutex_unlock(&pool->attach_mutex);
1664 * worker_detach_from_pool() - detach a worker from its pool
1665 * @worker: worker which is attached to its pool
1666 * @pool: the pool @worker is attached to
1668 * Undo the attaching which had been done in worker_attach_to_pool(). The
1669 * caller worker shouldn't access to the pool after detached except it has
1670 * other reference to the pool.
1672 static void worker_detach_from_pool(struct worker *worker,
1673 struct worker_pool *pool)
1675 struct completion *detach_completion = NULL;
1677 mutex_lock(&pool->attach_mutex);
1678 list_del(&worker->node);
1679 if (list_empty(&pool->workers))
1680 detach_completion = pool->detach_completion;
1681 mutex_unlock(&pool->attach_mutex);
1683 /* clear leftover flags without pool->lock after it is detached */
1684 worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
1686 if (detach_completion)
1687 complete(detach_completion);
1691 * create_worker - create a new workqueue worker
1692 * @pool: pool the new worker will belong to
1694 * Create and start a new worker which is attached to @pool.
1696 * CONTEXT:
1697 * Might sleep. Does GFP_KERNEL allocations.
1699 * Return:
1700 * Pointer to the newly created worker.
1702 static struct worker *create_worker(struct worker_pool *pool)
1704 struct worker *worker = NULL;
1705 int id = -1;
1706 char id_buf[16];
1708 /* ID is needed to determine kthread name */
1709 id = ida_simple_get(&pool->worker_ida, 0, 0, GFP_KERNEL);
1710 if (id < 0)
1711 goto fail;
1713 worker = alloc_worker(pool->node);
1714 if (!worker)
1715 goto fail;
1717 worker->pool = pool;
1718 worker->id = id;
1720 if (pool->cpu >= 0)
1721 snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
1722 pool->attrs->nice < 0 ? "H" : "");
1723 else
1724 snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
1726 worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
1727 "kworker/%s", id_buf);
1728 if (IS_ERR(worker->task))
1729 goto fail;
1731 set_user_nice(worker->task, pool->attrs->nice);
1733 /* prevent userland from meddling with cpumask of workqueue workers */
1734 worker->task->flags |= PF_NO_SETAFFINITY;
1736 /* successful, attach the worker to the pool */
1737 worker_attach_to_pool(worker, pool);
1739 /* start the newly created worker */
1740 spin_lock_irq(&pool->lock);
1741 worker->pool->nr_workers++;
1742 worker_enter_idle(worker);
1743 wake_up_process(worker->task);
1744 spin_unlock_irq(&pool->lock);
1746 return worker;
1748 fail:
1749 if (id >= 0)
1750 ida_simple_remove(&pool->worker_ida, id);
1751 kfree(worker);
1752 return NULL;
1756 * destroy_worker - destroy a workqueue worker
1757 * @worker: worker to be destroyed
1759 * Destroy @worker and adjust @pool stats accordingly. The worker should
1760 * be idle.
1762 * CONTEXT:
1763 * spin_lock_irq(pool->lock).
1765 static void destroy_worker(struct worker *worker)
1767 struct worker_pool *pool = worker->pool;
1769 lockdep_assert_held(&pool->lock);
1771 /* sanity check frenzy */
1772 if (WARN_ON(worker->current_work) ||
1773 WARN_ON(!list_empty(&worker->scheduled)) ||
1774 WARN_ON(!(worker->flags & WORKER_IDLE)))
1775 return;
1777 pool->nr_workers--;
1778 pool->nr_idle--;
1780 list_del_init(&worker->entry);
1781 worker->flags |= WORKER_DIE;
1782 wake_up_process(worker->task);
1785 static void idle_worker_timeout(unsigned long __pool)
1787 struct worker_pool *pool = (void *)__pool;
1789 spin_lock_irq(&pool->lock);
1791 while (too_many_workers(pool)) {
1792 struct worker *worker;
1793 unsigned long expires;
1795 /* idle_list is kept in LIFO order, check the last one */
1796 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1797 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1799 if (time_before(jiffies, expires)) {
1800 mod_timer(&pool->idle_timer, expires);
1801 break;
1804 destroy_worker(worker);
1807 spin_unlock_irq(&pool->lock);
1810 static void send_mayday(struct work_struct *work)
1812 struct pool_workqueue *pwq = get_work_pwq(work);
1813 struct workqueue_struct *wq = pwq->wq;
1815 lockdep_assert_held(&wq_mayday_lock);
1817 if (!wq->rescuer)
1818 return;
1820 /* mayday mayday mayday */
1821 if (list_empty(&pwq->mayday_node)) {
1823 * If @pwq is for an unbound wq, its base ref may be put at
1824 * any time due to an attribute change. Pin @pwq until the
1825 * rescuer is done with it.
1827 get_pwq(pwq);
1828 list_add_tail(&pwq->mayday_node, &wq->maydays);
1829 wake_up_process(wq->rescuer->task);
1833 static void pool_mayday_timeout(unsigned long __pool)
1835 struct worker_pool *pool = (void *)__pool;
1836 struct work_struct *work;
1838 spin_lock_irq(&pool->lock);
1839 spin_lock(&wq_mayday_lock); /* for wq->maydays */
1841 if (need_to_create_worker(pool)) {
1843 * We've been trying to create a new worker but
1844 * haven't been successful. We might be hitting an
1845 * allocation deadlock. Send distress signals to
1846 * rescuers.
1848 list_for_each_entry(work, &pool->worklist, entry)
1849 send_mayday(work);
1852 spin_unlock(&wq_mayday_lock);
1853 spin_unlock_irq(&pool->lock);
1855 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1859 * maybe_create_worker - create a new worker if necessary
1860 * @pool: pool to create a new worker for
1862 * Create a new worker for @pool if necessary. @pool is guaranteed to
1863 * have at least one idle worker on return from this function. If
1864 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1865 * sent to all rescuers with works scheduled on @pool to resolve
1866 * possible allocation deadlock.
1868 * On return, need_to_create_worker() is guaranteed to be %false and
1869 * may_start_working() %true.
1871 * LOCKING:
1872 * spin_lock_irq(pool->lock) which may be released and regrabbed
1873 * multiple times. Does GFP_KERNEL allocations. Called only from
1874 * manager.
1876 static void maybe_create_worker(struct worker_pool *pool)
1877 __releases(&pool->lock)
1878 __acquires(&pool->lock)
1880 restart:
1881 spin_unlock_irq(&pool->lock);
1883 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1884 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1886 while (true) {
1887 if (create_worker(pool) || !need_to_create_worker(pool))
1888 break;
1890 schedule_timeout_interruptible(CREATE_COOLDOWN);
1892 if (!need_to_create_worker(pool))
1893 break;
1896 del_timer_sync(&pool->mayday_timer);
1897 spin_lock_irq(&pool->lock);
1899 * This is necessary even after a new worker was just successfully
1900 * created as @pool->lock was dropped and the new worker might have
1901 * already become busy.
1903 if (need_to_create_worker(pool))
1904 goto restart;
1908 * manage_workers - manage worker pool
1909 * @worker: self
1911 * Assume the manager role and manage the worker pool @worker belongs
1912 * to. At any given time, there can be only zero or one manager per
1913 * pool. The exclusion is handled automatically by this function.
1915 * The caller can safely start processing works on false return. On
1916 * true return, it's guaranteed that need_to_create_worker() is false
1917 * and may_start_working() is true.
1919 * CONTEXT:
1920 * spin_lock_irq(pool->lock) which may be released and regrabbed
1921 * multiple times. Does GFP_KERNEL allocations.
1923 * Return:
1924 * %false if the pool doesn't need management and the caller can safely
1925 * start processing works, %true if management function was performed and
1926 * the conditions that the caller verified before calling the function may
1927 * no longer be true.
1929 static bool manage_workers(struct worker *worker)
1931 struct worker_pool *pool = worker->pool;
1934 * Anyone who successfully grabs manager_arb wins the arbitration
1935 * and becomes the manager. mutex_trylock() on pool->manager_arb
1936 * failure while holding pool->lock reliably indicates that someone
1937 * else is managing the pool and the worker which failed trylock
1938 * can proceed to executing work items. This means that anyone
1939 * grabbing manager_arb is responsible for actually performing
1940 * manager duties. If manager_arb is grabbed and released without
1941 * actual management, the pool may stall indefinitely.
1943 if (!mutex_trylock(&pool->manager_arb))
1944 return false;
1945 pool->manager = worker;
1947 maybe_create_worker(pool);
1949 pool->manager = NULL;
1950 mutex_unlock(&pool->manager_arb);
1951 return true;
1955 * process_one_work - process single work
1956 * @worker: self
1957 * @work: work to process
1959 * Process @work. This function contains all the logics necessary to
1960 * process a single work including synchronization against and
1961 * interaction with other workers on the same cpu, queueing and
1962 * flushing. As long as context requirement is met, any worker can
1963 * call this function to process a work.
1965 * CONTEXT:
1966 * spin_lock_irq(pool->lock) which is released and regrabbed.
1968 static void process_one_work(struct worker *worker, struct work_struct *work)
1969 __releases(&pool->lock)
1970 __acquires(&pool->lock)
1972 struct pool_workqueue *pwq = get_work_pwq(work);
1973 struct worker_pool *pool = worker->pool;
1974 bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
1975 int work_color;
1976 struct worker *collision;
1977 #ifdef CONFIG_LOCKDEP
1979 * It is permissible to free the struct work_struct from
1980 * inside the function that is called from it, this we need to
1981 * take into account for lockdep too. To avoid bogus "held
1982 * lock freed" warnings as well as problems when looking into
1983 * work->lockdep_map, make a copy and use that here.
1985 struct lockdep_map lockdep_map;
1987 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
1988 #endif
1989 /* ensure we're on the correct CPU */
1990 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1991 raw_smp_processor_id() != pool->cpu);
1994 * A single work shouldn't be executed concurrently by
1995 * multiple workers on a single cpu. Check whether anyone is
1996 * already processing the work. If so, defer the work to the
1997 * currently executing one.
1999 collision = find_worker_executing_work(pool, work);
2000 if (unlikely(collision)) {
2001 move_linked_works(work, &collision->scheduled, NULL);
2002 return;
2005 /* claim and dequeue */
2006 debug_work_deactivate(work);
2007 hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2008 worker->current_work = work;
2009 worker->current_func = work->func;
2010 worker->current_pwq = pwq;
2011 work_color = get_work_color(work);
2013 list_del_init(&work->entry);
2016 * CPU intensive works don't participate in concurrency management.
2017 * They're the scheduler's responsibility. This takes @worker out
2018 * of concurrency management and the next code block will chain
2019 * execution of the pending work items.
2021 if (unlikely(cpu_intensive))
2022 worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2025 * Wake up another worker if necessary. The condition is always
2026 * false for normal per-cpu workers since nr_running would always
2027 * be >= 1 at this point. This is used to chain execution of the
2028 * pending work items for WORKER_NOT_RUNNING workers such as the
2029 * UNBOUND and CPU_INTENSIVE ones.
2031 if (need_more_worker(pool))
2032 wake_up_worker(pool);
2035 * Record the last pool and clear PENDING which should be the last
2036 * update to @work. Also, do this inside @pool->lock so that
2037 * PENDING and queued state changes happen together while IRQ is
2038 * disabled.
2040 set_work_pool_and_clear_pending(work, pool->id);
2042 spin_unlock_irq(&pool->lock);
2044 lock_map_acquire_read(&pwq->wq->lockdep_map);
2045 lock_map_acquire(&lockdep_map);
2046 trace_workqueue_execute_start(work);
2047 worker->current_func(work);
2049 * While we must be careful to not use "work" after this, the trace
2050 * point will only record its address.
2052 trace_workqueue_execute_end(work);
2053 lock_map_release(&lockdep_map);
2054 lock_map_release(&pwq->wq->lockdep_map);
2056 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2057 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2058 " last function: %pf\n",
2059 current->comm, preempt_count(), task_pid_nr(current),
2060 worker->current_func);
2061 debug_show_held_locks(current);
2062 dump_stack();
2066 * The following prevents a kworker from hogging CPU on !PREEMPT
2067 * kernels, where a requeueing work item waiting for something to
2068 * happen could deadlock with stop_machine as such work item could
2069 * indefinitely requeue itself while all other CPUs are trapped in
2070 * stop_machine. At the same time, report a quiescent RCU state so
2071 * the same condition doesn't freeze RCU.
2073 cond_resched_rcu_qs();
2075 spin_lock_irq(&pool->lock);
2077 /* clear cpu intensive status */
2078 if (unlikely(cpu_intensive))
2079 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2081 /* we're done with it, release */
2082 hash_del(&worker->hentry);
2083 worker->current_work = NULL;
2084 worker->current_func = NULL;
2085 worker->current_pwq = NULL;
2086 worker->desc_valid = false;
2087 pwq_dec_nr_in_flight(pwq, work_color);
2091 * process_scheduled_works - process scheduled works
2092 * @worker: self
2094 * Process all scheduled works. Please note that the scheduled list
2095 * may change while processing a work, so this function repeatedly
2096 * fetches a work from the top and executes it.
2098 * CONTEXT:
2099 * spin_lock_irq(pool->lock) which may be released and regrabbed
2100 * multiple times.
2102 static void process_scheduled_works(struct worker *worker)
2104 while (!list_empty(&worker->scheduled)) {
2105 struct work_struct *work = list_first_entry(&worker->scheduled,
2106 struct work_struct, entry);
2107 process_one_work(worker, work);
2112 * worker_thread - the worker thread function
2113 * @__worker: self
2115 * The worker thread function. All workers belong to a worker_pool -
2116 * either a per-cpu one or dynamic unbound one. These workers process all
2117 * work items regardless of their specific target workqueue. The only
2118 * exception is work items which belong to workqueues with a rescuer which
2119 * will be explained in rescuer_thread().
2121 * Return: 0
2123 static int worker_thread(void *__worker)
2125 struct worker *worker = __worker;
2126 struct worker_pool *pool = worker->pool;
2128 /* tell the scheduler that this is a workqueue worker */
2129 worker->task->flags |= PF_WQ_WORKER;
2130 woke_up:
2131 spin_lock_irq(&pool->lock);
2133 /* am I supposed to die? */
2134 if (unlikely(worker->flags & WORKER_DIE)) {
2135 spin_unlock_irq(&pool->lock);
2136 WARN_ON_ONCE(!list_empty(&worker->entry));
2137 worker->task->flags &= ~PF_WQ_WORKER;
2139 set_task_comm(worker->task, "kworker/dying");
2140 ida_simple_remove(&pool->worker_ida, worker->id);
2141 worker_detach_from_pool(worker, pool);
2142 kfree(worker);
2143 return 0;
2146 worker_leave_idle(worker);
2147 recheck:
2148 /* no more worker necessary? */
2149 if (!need_more_worker(pool))
2150 goto sleep;
2152 /* do we need to manage? */
2153 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2154 goto recheck;
2157 * ->scheduled list can only be filled while a worker is
2158 * preparing to process a work or actually processing it.
2159 * Make sure nobody diddled with it while I was sleeping.
2161 WARN_ON_ONCE(!list_empty(&worker->scheduled));
2164 * Finish PREP stage. We're guaranteed to have at least one idle
2165 * worker or that someone else has already assumed the manager
2166 * role. This is where @worker starts participating in concurrency
2167 * management if applicable and concurrency management is restored
2168 * after being rebound. See rebind_workers() for details.
2170 worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2172 do {
2173 struct work_struct *work =
2174 list_first_entry(&pool->worklist,
2175 struct work_struct, entry);
2177 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2178 /* optimization path, not strictly necessary */
2179 process_one_work(worker, work);
2180 if (unlikely(!list_empty(&worker->scheduled)))
2181 process_scheduled_works(worker);
2182 } else {
2183 move_linked_works(work, &worker->scheduled, NULL);
2184 process_scheduled_works(worker);
2186 } while (keep_working(pool));
2188 worker_set_flags(worker, WORKER_PREP);
2189 sleep:
2191 * pool->lock is held and there's no work to process and no need to
2192 * manage, sleep. Workers are woken up only while holding
2193 * pool->lock or from local cpu, so setting the current state
2194 * before releasing pool->lock is enough to prevent losing any
2195 * event.
2197 worker_enter_idle(worker);
2198 __set_current_state(TASK_INTERRUPTIBLE);
2199 spin_unlock_irq(&pool->lock);
2200 schedule();
2201 goto woke_up;
2205 * rescuer_thread - the rescuer thread function
2206 * @__rescuer: self
2208 * Workqueue rescuer thread function. There's one rescuer for each
2209 * workqueue which has WQ_MEM_RECLAIM set.
2211 * Regular work processing on a pool may block trying to create a new
2212 * worker which uses GFP_KERNEL allocation which has slight chance of
2213 * developing into deadlock if some works currently on the same queue
2214 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2215 * the problem rescuer solves.
2217 * When such condition is possible, the pool summons rescuers of all
2218 * workqueues which have works queued on the pool and let them process
2219 * those works so that forward progress can be guaranteed.
2221 * This should happen rarely.
2223 * Return: 0
2225 static int rescuer_thread(void *__rescuer)
2227 struct worker *rescuer = __rescuer;
2228 struct workqueue_struct *wq = rescuer->rescue_wq;
2229 struct list_head *scheduled = &rescuer->scheduled;
2230 bool should_stop;
2232 set_user_nice(current, RESCUER_NICE_LEVEL);
2235 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2236 * doesn't participate in concurrency management.
2238 rescuer->task->flags |= PF_WQ_WORKER;
2239 repeat:
2240 set_current_state(TASK_INTERRUPTIBLE);
2243 * By the time the rescuer is requested to stop, the workqueue
2244 * shouldn't have any work pending, but @wq->maydays may still have
2245 * pwq(s) queued. This can happen by non-rescuer workers consuming
2246 * all the work items before the rescuer got to them. Go through
2247 * @wq->maydays processing before acting on should_stop so that the
2248 * list is always empty on exit.
2250 should_stop = kthread_should_stop();
2252 /* see whether any pwq is asking for help */
2253 spin_lock_irq(&wq_mayday_lock);
2255 while (!list_empty(&wq->maydays)) {
2256 struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2257 struct pool_workqueue, mayday_node);
2258 struct worker_pool *pool = pwq->pool;
2259 struct work_struct *work, *n;
2261 __set_current_state(TASK_RUNNING);
2262 list_del_init(&pwq->mayday_node);
2264 spin_unlock_irq(&wq_mayday_lock);
2266 worker_attach_to_pool(rescuer, pool);
2268 spin_lock_irq(&pool->lock);
2269 rescuer->pool = pool;
2272 * Slurp in all works issued via this workqueue and
2273 * process'em.
2275 WARN_ON_ONCE(!list_empty(scheduled));
2276 list_for_each_entry_safe(work, n, &pool->worklist, entry)
2277 if (get_work_pwq(work) == pwq)
2278 move_linked_works(work, scheduled, &n);
2280 if (!list_empty(scheduled)) {
2281 process_scheduled_works(rescuer);
2284 * The above execution of rescued work items could
2285 * have created more to rescue through
2286 * pwq_activate_first_delayed() or chained
2287 * queueing. Let's put @pwq back on mayday list so
2288 * that such back-to-back work items, which may be
2289 * being used to relieve memory pressure, don't
2290 * incur MAYDAY_INTERVAL delay inbetween.
2292 if (need_to_create_worker(pool)) {
2293 spin_lock(&wq_mayday_lock);
2294 get_pwq(pwq);
2295 list_move_tail(&pwq->mayday_node, &wq->maydays);
2296 spin_unlock(&wq_mayday_lock);
2301 * Put the reference grabbed by send_mayday(). @pool won't
2302 * go away while we're still attached to it.
2304 put_pwq(pwq);
2307 * Leave this pool. If need_more_worker() is %true, notify a
2308 * regular worker; otherwise, we end up with 0 concurrency
2309 * and stalling the execution.
2311 if (need_more_worker(pool))
2312 wake_up_worker(pool);
2314 rescuer->pool = NULL;
2315 spin_unlock_irq(&pool->lock);
2317 worker_detach_from_pool(rescuer, pool);
2319 spin_lock_irq(&wq_mayday_lock);
2322 spin_unlock_irq(&wq_mayday_lock);
2324 if (should_stop) {
2325 __set_current_state(TASK_RUNNING);
2326 rescuer->task->flags &= ~PF_WQ_WORKER;
2327 return 0;
2330 /* rescuers should never participate in concurrency management */
2331 WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2332 schedule();
2333 goto repeat;
2336 struct wq_barrier {
2337 struct work_struct work;
2338 struct completion done;
2339 struct task_struct *task; /* purely informational */
2342 static void wq_barrier_func(struct work_struct *work)
2344 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2345 complete(&barr->done);
2349 * insert_wq_barrier - insert a barrier work
2350 * @pwq: pwq to insert barrier into
2351 * @barr: wq_barrier to insert
2352 * @target: target work to attach @barr to
2353 * @worker: worker currently executing @target, NULL if @target is not executing
2355 * @barr is linked to @target such that @barr is completed only after
2356 * @target finishes execution. Please note that the ordering
2357 * guarantee is observed only with respect to @target and on the local
2358 * cpu.
2360 * Currently, a queued barrier can't be canceled. This is because
2361 * try_to_grab_pending() can't determine whether the work to be
2362 * grabbed is at the head of the queue and thus can't clear LINKED
2363 * flag of the previous work while there must be a valid next work
2364 * after a work with LINKED flag set.
2366 * Note that when @worker is non-NULL, @target may be modified
2367 * underneath us, so we can't reliably determine pwq from @target.
2369 * CONTEXT:
2370 * spin_lock_irq(pool->lock).
2372 static void insert_wq_barrier(struct pool_workqueue *pwq,
2373 struct wq_barrier *barr,
2374 struct work_struct *target, struct worker *worker)
2376 struct list_head *head;
2377 unsigned int linked = 0;
2380 * debugobject calls are safe here even with pool->lock locked
2381 * as we know for sure that this will not trigger any of the
2382 * checks and call back into the fixup functions where we
2383 * might deadlock.
2385 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2386 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2387 init_completion(&barr->done);
2388 barr->task = current;
2391 * If @target is currently being executed, schedule the
2392 * barrier to the worker; otherwise, put it after @target.
2394 if (worker)
2395 head = worker->scheduled.next;
2396 else {
2397 unsigned long *bits = work_data_bits(target);
2399 head = target->entry.next;
2400 /* there can already be other linked works, inherit and set */
2401 linked = *bits & WORK_STRUCT_LINKED;
2402 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2405 debug_work_activate(&barr->work);
2406 insert_work(pwq, &barr->work, head,
2407 work_color_to_flags(WORK_NO_COLOR) | linked);
2411 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
2412 * @wq: workqueue being flushed
2413 * @flush_color: new flush color, < 0 for no-op
2414 * @work_color: new work color, < 0 for no-op
2416 * Prepare pwqs for workqueue flushing.
2418 * If @flush_color is non-negative, flush_color on all pwqs should be
2419 * -1. If no pwq has in-flight commands at the specified color, all
2420 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
2421 * has in flight commands, its pwq->flush_color is set to
2422 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
2423 * wakeup logic is armed and %true is returned.
2425 * The caller should have initialized @wq->first_flusher prior to
2426 * calling this function with non-negative @flush_color. If
2427 * @flush_color is negative, no flush color update is done and %false
2428 * is returned.
2430 * If @work_color is non-negative, all pwqs should have the same
2431 * work_color which is previous to @work_color and all will be
2432 * advanced to @work_color.
2434 * CONTEXT:
2435 * mutex_lock(wq->mutex).
2437 * Return:
2438 * %true if @flush_color >= 0 and there's something to flush. %false
2439 * otherwise.
2441 static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
2442 int flush_color, int work_color)
2444 bool wait = false;
2445 struct pool_workqueue *pwq;
2447 if (flush_color >= 0) {
2448 WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2449 atomic_set(&wq->nr_pwqs_to_flush, 1);
2452 for_each_pwq(pwq, wq) {
2453 struct worker_pool *pool = pwq->pool;
2455 spin_lock_irq(&pool->lock);
2457 if (flush_color >= 0) {
2458 WARN_ON_ONCE(pwq->flush_color != -1);
2460 if (pwq->nr_in_flight[flush_color]) {
2461 pwq->flush_color = flush_color;
2462 atomic_inc(&wq->nr_pwqs_to_flush);
2463 wait = true;
2467 if (work_color >= 0) {
2468 WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2469 pwq->work_color = work_color;
2472 spin_unlock_irq(&pool->lock);
2475 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
2476 complete(&wq->first_flusher->done);
2478 return wait;
2482 * flush_workqueue - ensure that any scheduled work has run to completion.
2483 * @wq: workqueue to flush
2485 * This function sleeps until all work items which were queued on entry
2486 * have finished execution, but it is not livelocked by new incoming ones.
2488 void flush_workqueue(struct workqueue_struct *wq)
2490 struct wq_flusher this_flusher = {
2491 .list = LIST_HEAD_INIT(this_flusher.list),
2492 .flush_color = -1,
2493 .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
2495 int next_color;
2497 lock_map_acquire(&wq->lockdep_map);
2498 lock_map_release(&wq->lockdep_map);
2500 mutex_lock(&wq->mutex);
2503 * Start-to-wait phase
2505 next_color = work_next_color(wq->work_color);
2507 if (next_color != wq->flush_color) {
2509 * Color space is not full. The current work_color
2510 * becomes our flush_color and work_color is advanced
2511 * by one.
2513 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
2514 this_flusher.flush_color = wq->work_color;
2515 wq->work_color = next_color;
2517 if (!wq->first_flusher) {
2518 /* no flush in progress, become the first flusher */
2519 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2521 wq->first_flusher = &this_flusher;
2523 if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
2524 wq->work_color)) {
2525 /* nothing to flush, done */
2526 wq->flush_color = next_color;
2527 wq->first_flusher = NULL;
2528 goto out_unlock;
2530 } else {
2531 /* wait in queue */
2532 WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
2533 list_add_tail(&this_flusher.list, &wq->flusher_queue);
2534 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2536 } else {
2538 * Oops, color space is full, wait on overflow queue.
2539 * The next flush completion will assign us
2540 * flush_color and transfer to flusher_queue.
2542 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2545 mutex_unlock(&wq->mutex);
2547 wait_for_completion(&this_flusher.done);
2550 * Wake-up-and-cascade phase
2552 * First flushers are responsible for cascading flushes and
2553 * handling overflow. Non-first flushers can simply return.
2555 if (wq->first_flusher != &this_flusher)
2556 return;
2558 mutex_lock(&wq->mutex);
2560 /* we might have raced, check again with mutex held */
2561 if (wq->first_flusher != &this_flusher)
2562 goto out_unlock;
2564 wq->first_flusher = NULL;
2566 WARN_ON_ONCE(!list_empty(&this_flusher.list));
2567 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2569 while (true) {
2570 struct wq_flusher *next, *tmp;
2572 /* complete all the flushers sharing the current flush color */
2573 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2574 if (next->flush_color != wq->flush_color)
2575 break;
2576 list_del_init(&next->list);
2577 complete(&next->done);
2580 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
2581 wq->flush_color != work_next_color(wq->work_color));
2583 /* this flush_color is finished, advance by one */
2584 wq->flush_color = work_next_color(wq->flush_color);
2586 /* one color has been freed, handle overflow queue */
2587 if (!list_empty(&wq->flusher_overflow)) {
2589 * Assign the same color to all overflowed
2590 * flushers, advance work_color and append to
2591 * flusher_queue. This is the start-to-wait
2592 * phase for these overflowed flushers.
2594 list_for_each_entry(tmp, &wq->flusher_overflow, list)
2595 tmp->flush_color = wq->work_color;
2597 wq->work_color = work_next_color(wq->work_color);
2599 list_splice_tail_init(&wq->flusher_overflow,
2600 &wq->flusher_queue);
2601 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2604 if (list_empty(&wq->flusher_queue)) {
2605 WARN_ON_ONCE(wq->flush_color != wq->work_color);
2606 break;
2610 * Need to flush more colors. Make the next flusher
2611 * the new first flusher and arm pwqs.
2613 WARN_ON_ONCE(wq->flush_color == wq->work_color);
2614 WARN_ON_ONCE(wq->flush_color != next->flush_color);
2616 list_del_init(&next->list);
2617 wq->first_flusher = next;
2619 if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
2620 break;
2623 * Meh... this color is already done, clear first
2624 * flusher and repeat cascading.
2626 wq->first_flusher = NULL;
2629 out_unlock:
2630 mutex_unlock(&wq->mutex);
2632 EXPORT_SYMBOL_GPL(flush_workqueue);
2635 * drain_workqueue - drain a workqueue
2636 * @wq: workqueue to drain
2638 * Wait until the workqueue becomes empty. While draining is in progress,
2639 * only chain queueing is allowed. IOW, only currently pending or running
2640 * work items on @wq can queue further work items on it. @wq is flushed
2641 * repeatedly until it becomes empty. The number of flushing is detemined
2642 * by the depth of chaining and should be relatively short. Whine if it
2643 * takes too long.
2645 void drain_workqueue(struct workqueue_struct *wq)
2647 unsigned int flush_cnt = 0;
2648 struct pool_workqueue *pwq;
2651 * __queue_work() needs to test whether there are drainers, is much
2652 * hotter than drain_workqueue() and already looks at @wq->flags.
2653 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
2655 mutex_lock(&wq->mutex);
2656 if (!wq->nr_drainers++)
2657 wq->flags |= __WQ_DRAINING;
2658 mutex_unlock(&wq->mutex);
2659 reflush:
2660 flush_workqueue(wq);
2662 mutex_lock(&wq->mutex);
2664 for_each_pwq(pwq, wq) {
2665 bool drained;
2667 spin_lock_irq(&pwq->pool->lock);
2668 drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
2669 spin_unlock_irq(&pwq->pool->lock);
2671 if (drained)
2672 continue;
2674 if (++flush_cnt == 10 ||
2675 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2676 pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
2677 wq->name, flush_cnt);
2679 mutex_unlock(&wq->mutex);
2680 goto reflush;
2683 if (!--wq->nr_drainers)
2684 wq->flags &= ~__WQ_DRAINING;
2685 mutex_unlock(&wq->mutex);
2687 EXPORT_SYMBOL_GPL(drain_workqueue);
2689 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2691 struct worker *worker = NULL;
2692 struct worker_pool *pool;
2693 struct pool_workqueue *pwq;
2695 might_sleep();
2697 local_irq_disable();
2698 pool = get_work_pool(work);
2699 if (!pool) {
2700 local_irq_enable();
2701 return false;
2704 spin_lock(&pool->lock);
2705 /* see the comment in try_to_grab_pending() with the same code */
2706 pwq = get_work_pwq(work);
2707 if (pwq) {
2708 if (unlikely(pwq->pool != pool))
2709 goto already_gone;
2710 } else {
2711 worker = find_worker_executing_work(pool, work);
2712 if (!worker)
2713 goto already_gone;
2714 pwq = worker->current_pwq;
2717 insert_wq_barrier(pwq, barr, work, worker);
2718 spin_unlock_irq(&pool->lock);
2721 * If @max_active is 1 or rescuer is in use, flushing another work
2722 * item on the same workqueue may lead to deadlock. Make sure the
2723 * flusher is not running on the same workqueue by verifying write
2724 * access.
2726 if (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)
2727 lock_map_acquire(&pwq->wq->lockdep_map);
2728 else
2729 lock_map_acquire_read(&pwq->wq->lockdep_map);
2730 lock_map_release(&pwq->wq->lockdep_map);
2732 return true;
2733 already_gone:
2734 spin_unlock_irq(&pool->lock);
2735 return false;
2739 * flush_work - wait for a work to finish executing the last queueing instance
2740 * @work: the work to flush
2742 * Wait until @work has finished execution. @work is guaranteed to be idle
2743 * on return if it hasn't been requeued since flush started.
2745 * Return:
2746 * %true if flush_work() waited for the work to finish execution,
2747 * %false if it was already idle.
2749 bool flush_work(struct work_struct *work)
2751 struct wq_barrier barr;
2753 lock_map_acquire(&work->lockdep_map);
2754 lock_map_release(&work->lockdep_map);
2756 if (start_flush_work(work, &barr)) {
2757 wait_for_completion(&barr.done);
2758 destroy_work_on_stack(&barr.work);
2759 return true;
2760 } else {
2761 return false;
2764 EXPORT_SYMBOL_GPL(flush_work);
2766 struct cwt_wait {
2767 wait_queue_t wait;
2768 struct work_struct *work;
2771 static int cwt_wakefn(wait_queue_t *wait, unsigned mode, int sync, void *key)
2773 struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
2775 if (cwait->work != key)
2776 return 0;
2777 return autoremove_wake_function(wait, mode, sync, key);
2780 static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2782 static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
2783 unsigned long flags;
2784 int ret;
2786 do {
2787 ret = try_to_grab_pending(work, is_dwork, &flags);
2789 * If someone else is already canceling, wait for it to
2790 * finish. flush_work() doesn't work for PREEMPT_NONE
2791 * because we may get scheduled between @work's completion
2792 * and the other canceling task resuming and clearing
2793 * CANCELING - flush_work() will return false immediately
2794 * as @work is no longer busy, try_to_grab_pending() will
2795 * return -ENOENT as @work is still being canceled and the
2796 * other canceling task won't be able to clear CANCELING as
2797 * we're hogging the CPU.
2799 * Let's wait for completion using a waitqueue. As this
2800 * may lead to the thundering herd problem, use a custom
2801 * wake function which matches @work along with exclusive
2802 * wait and wakeup.
2804 if (unlikely(ret == -ENOENT)) {
2805 struct cwt_wait cwait;
2807 init_wait(&cwait.wait);
2808 cwait.wait.func = cwt_wakefn;
2809 cwait.work = work;
2811 prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
2812 TASK_UNINTERRUPTIBLE);
2813 if (work_is_canceling(work))
2814 schedule();
2815 finish_wait(&cancel_waitq, &cwait.wait);
2817 } while (unlikely(ret < 0));
2819 /* tell other tasks trying to grab @work to back off */
2820 mark_work_canceling(work);
2821 local_irq_restore(flags);
2823 flush_work(work);
2824 clear_work_data(work);
2827 * Paired with prepare_to_wait() above so that either
2828 * waitqueue_active() is visible here or !work_is_canceling() is
2829 * visible there.
2831 smp_mb();
2832 if (waitqueue_active(&cancel_waitq))
2833 __wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
2835 return ret;
2839 * cancel_work_sync - cancel a work and wait for it to finish
2840 * @work: the work to cancel
2842 * Cancel @work and wait for its execution to finish. This function
2843 * can be used even if the work re-queues itself or migrates to
2844 * another workqueue. On return from this function, @work is
2845 * guaranteed to be not pending or executing on any CPU.
2847 * cancel_work_sync(&delayed_work->work) must not be used for
2848 * delayed_work's. Use cancel_delayed_work_sync() instead.
2850 * The caller must ensure that the workqueue on which @work was last
2851 * queued can't be destroyed before this function returns.
2853 * Return:
2854 * %true if @work was pending, %false otherwise.
2856 bool cancel_work_sync(struct work_struct *work)
2858 return __cancel_work_timer(work, false);
2860 EXPORT_SYMBOL_GPL(cancel_work_sync);
2863 * flush_delayed_work - wait for a dwork to finish executing the last queueing
2864 * @dwork: the delayed work to flush
2866 * Delayed timer is cancelled and the pending work is queued for
2867 * immediate execution. Like flush_work(), this function only
2868 * considers the last queueing instance of @dwork.
2870 * Return:
2871 * %true if flush_work() waited for the work to finish execution,
2872 * %false if it was already idle.
2874 bool flush_delayed_work(struct delayed_work *dwork)
2876 local_irq_disable();
2877 if (del_timer_sync(&dwork->timer))
2878 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
2879 local_irq_enable();
2880 return flush_work(&dwork->work);
2882 EXPORT_SYMBOL(flush_delayed_work);
2885 * cancel_delayed_work - cancel a delayed work
2886 * @dwork: delayed_work to cancel
2888 * Kill off a pending delayed_work.
2890 * Return: %true if @dwork was pending and canceled; %false if it wasn't
2891 * pending.
2893 * Note:
2894 * The work callback function may still be running on return, unless
2895 * it returns %true and the work doesn't re-arm itself. Explicitly flush or
2896 * use cancel_delayed_work_sync() to wait on it.
2898 * This function is safe to call from any context including IRQ handler.
2900 bool cancel_delayed_work(struct delayed_work *dwork)
2902 unsigned long flags;
2903 int ret;
2905 do {
2906 ret = try_to_grab_pending(&dwork->work, true, &flags);
2907 } while (unlikely(ret == -EAGAIN));
2909 if (unlikely(ret < 0))
2910 return false;
2912 set_work_pool_and_clear_pending(&dwork->work,
2913 get_work_pool_id(&dwork->work));
2914 local_irq_restore(flags);
2915 return ret;
2917 EXPORT_SYMBOL(cancel_delayed_work);
2920 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2921 * @dwork: the delayed work cancel
2923 * This is cancel_work_sync() for delayed works.
2925 * Return:
2926 * %true if @dwork was pending, %false otherwise.
2928 bool cancel_delayed_work_sync(struct delayed_work *dwork)
2930 return __cancel_work_timer(&dwork->work, true);
2932 EXPORT_SYMBOL(cancel_delayed_work_sync);
2935 * schedule_on_each_cpu - execute a function synchronously on each online CPU
2936 * @func: the function to call
2938 * schedule_on_each_cpu() executes @func on each online CPU using the
2939 * system workqueue and blocks until all CPUs have completed.
2940 * schedule_on_each_cpu() is very slow.
2942 * Return:
2943 * 0 on success, -errno on failure.
2945 int schedule_on_each_cpu(work_func_t func)
2947 int cpu;
2948 struct work_struct __percpu *works;
2950 works = alloc_percpu(struct work_struct);
2951 if (!works)
2952 return -ENOMEM;
2954 get_online_cpus();
2956 for_each_online_cpu(cpu) {
2957 struct work_struct *work = per_cpu_ptr(works, cpu);
2959 INIT_WORK(work, func);
2960 schedule_work_on(cpu, work);
2963 for_each_online_cpu(cpu)
2964 flush_work(per_cpu_ptr(works, cpu));
2966 put_online_cpus();
2967 free_percpu(works);
2968 return 0;
2972 * flush_scheduled_work - ensure that any scheduled work has run to completion.
2974 * Forces execution of the kernel-global workqueue and blocks until its
2975 * completion.
2977 * Think twice before calling this function! It's very easy to get into
2978 * trouble if you don't take great care. Either of the following situations
2979 * will lead to deadlock:
2981 * One of the work items currently on the workqueue needs to acquire
2982 * a lock held by your code or its caller.
2984 * Your code is running in the context of a work routine.
2986 * They will be detected by lockdep when they occur, but the first might not
2987 * occur very often. It depends on what work items are on the workqueue and
2988 * what locks they need, which you have no control over.
2990 * In most situations flushing the entire workqueue is overkill; you merely
2991 * need to know that a particular work item isn't queued and isn't running.
2992 * In such cases you should use cancel_delayed_work_sync() or
2993 * cancel_work_sync() instead.
2995 void flush_scheduled_work(void)
2997 flush_workqueue(system_wq);
2999 EXPORT_SYMBOL(flush_scheduled_work);
3002 * execute_in_process_context - reliably execute the routine with user context
3003 * @fn: the function to execute
3004 * @ew: guaranteed storage for the execute work structure (must
3005 * be available when the work executes)
3007 * Executes the function immediately if process context is available,
3008 * otherwise schedules the function for delayed execution.
3010 * Return: 0 - function was executed
3011 * 1 - function was scheduled for execution
3013 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
3015 if (!in_interrupt()) {
3016 fn(&ew->work);
3017 return 0;
3020 INIT_WORK(&ew->work, fn);
3021 schedule_work(&ew->work);
3023 return 1;
3025 EXPORT_SYMBOL_GPL(execute_in_process_context);
3028 * free_workqueue_attrs - free a workqueue_attrs
3029 * @attrs: workqueue_attrs to free
3031 * Undo alloc_workqueue_attrs().
3033 void free_workqueue_attrs(struct workqueue_attrs *attrs)
3035 if (attrs) {
3036 free_cpumask_var(attrs->cpumask);
3037 kfree(attrs);
3042 * alloc_workqueue_attrs - allocate a workqueue_attrs
3043 * @gfp_mask: allocation mask to use
3045 * Allocate a new workqueue_attrs, initialize with default settings and
3046 * return it.
3048 * Return: The allocated new workqueue_attr on success. %NULL on failure.
3050 struct workqueue_attrs *alloc_workqueue_attrs(gfp_t gfp_mask)
3052 struct workqueue_attrs *attrs;
3054 attrs = kzalloc(sizeof(*attrs), gfp_mask);
3055 if (!attrs)
3056 goto fail;
3057 if (!alloc_cpumask_var(&attrs->cpumask, gfp_mask))
3058 goto fail;
3060 cpumask_copy(attrs->cpumask, cpu_possible_mask);
3061 return attrs;
3062 fail:
3063 free_workqueue_attrs(attrs);
3064 return NULL;
3067 static void copy_workqueue_attrs(struct workqueue_attrs *to,
3068 const struct workqueue_attrs *from)
3070 to->nice = from->nice;
3071 cpumask_copy(to->cpumask, from->cpumask);
3073 * Unlike hash and equality test, this function doesn't ignore
3074 * ->no_numa as it is used for both pool and wq attrs. Instead,
3075 * get_unbound_pool() explicitly clears ->no_numa after copying.
3077 to->no_numa = from->no_numa;
3080 /* hash value of the content of @attr */
3081 static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
3083 u32 hash = 0;
3085 hash = jhash_1word(attrs->nice, hash);
3086 hash = jhash(cpumask_bits(attrs->cpumask),
3087 BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
3088 return hash;
3091 /* content equality test */
3092 static bool wqattrs_equal(const struct workqueue_attrs *a,
3093 const struct workqueue_attrs *b)
3095 if (a->nice != b->nice)
3096 return false;
3097 if (!cpumask_equal(a->cpumask, b->cpumask))
3098 return false;
3099 return true;
3103 * init_worker_pool - initialize a newly zalloc'd worker_pool
3104 * @pool: worker_pool to initialize
3106 * Initiailize a newly zalloc'd @pool. It also allocates @pool->attrs.
3108 * Return: 0 on success, -errno on failure. Even on failure, all fields
3109 * inside @pool proper are initialized and put_unbound_pool() can be called
3110 * on @pool safely to release it.
3112 static int init_worker_pool(struct worker_pool *pool)
3114 spin_lock_init(&pool->lock);
3115 pool->id = -1;
3116 pool->cpu = -1;
3117 pool->node = NUMA_NO_NODE;
3118 pool->flags |= POOL_DISASSOCIATED;
3119 INIT_LIST_HEAD(&pool->worklist);
3120 INIT_LIST_HEAD(&pool->idle_list);
3121 hash_init(pool->busy_hash);
3123 init_timer_deferrable(&pool->idle_timer);
3124 pool->idle_timer.function = idle_worker_timeout;
3125 pool->idle_timer.data = (unsigned long)pool;
3127 setup_timer(&pool->mayday_timer, pool_mayday_timeout,
3128 (unsigned long)pool);
3130 mutex_init(&pool->manager_arb);
3131 mutex_init(&pool->attach_mutex);
3132 INIT_LIST_HEAD(&pool->workers);
3134 ida_init(&pool->worker_ida);
3135 INIT_HLIST_NODE(&pool->hash_node);
3136 pool->refcnt = 1;
3138 /* shouldn't fail above this point */
3139 pool->attrs = alloc_workqueue_attrs(GFP_KERNEL);
3140 if (!pool->attrs)
3141 return -ENOMEM;
3142 return 0;
3145 static void rcu_free_wq(struct rcu_head *rcu)
3147 struct workqueue_struct *wq =
3148 container_of(rcu, struct workqueue_struct, rcu);
3150 if (!(wq->flags & WQ_UNBOUND))
3151 free_percpu(wq->cpu_pwqs);
3152 else
3153 free_workqueue_attrs(wq->unbound_attrs);
3155 kfree(wq->rescuer);
3156 kfree(wq);
3159 static void rcu_free_pool(struct rcu_head *rcu)
3161 struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
3163 ida_destroy(&pool->worker_ida);
3164 free_workqueue_attrs(pool->attrs);
3165 kfree(pool);
3169 * put_unbound_pool - put a worker_pool
3170 * @pool: worker_pool to put
3172 * Put @pool. If its refcnt reaches zero, it gets destroyed in sched-RCU
3173 * safe manner. get_unbound_pool() calls this function on its failure path
3174 * and this function should be able to release pools which went through,
3175 * successfully or not, init_worker_pool().
3177 * Should be called with wq_pool_mutex held.
3179 static void put_unbound_pool(struct worker_pool *pool)
3181 DECLARE_COMPLETION_ONSTACK(detach_completion);
3182 struct worker *worker;
3184 lockdep_assert_held(&wq_pool_mutex);
3186 if (--pool->refcnt)
3187 return;
3189 /* sanity checks */
3190 if (WARN_ON(!(pool->cpu < 0)) ||
3191 WARN_ON(!list_empty(&pool->worklist)))
3192 return;
3194 /* release id and unhash */
3195 if (pool->id >= 0)
3196 idr_remove(&worker_pool_idr, pool->id);
3197 hash_del(&pool->hash_node);
3200 * Become the manager and destroy all workers. Grabbing
3201 * manager_arb prevents @pool's workers from blocking on
3202 * attach_mutex.
3204 mutex_lock(&pool->manager_arb);
3206 spin_lock_irq(&pool->lock);
3207 while ((worker = first_idle_worker(pool)))
3208 destroy_worker(worker);
3209 WARN_ON(pool->nr_workers || pool->nr_idle);
3210 spin_unlock_irq(&pool->lock);
3212 mutex_lock(&pool->attach_mutex);
3213 if (!list_empty(&pool->workers))
3214 pool->detach_completion = &detach_completion;
3215 mutex_unlock(&pool->attach_mutex);
3217 if (pool->detach_completion)
3218 wait_for_completion(pool->detach_completion);
3220 mutex_unlock(&pool->manager_arb);
3222 /* shut down the timers */
3223 del_timer_sync(&pool->idle_timer);
3224 del_timer_sync(&pool->mayday_timer);
3226 /* sched-RCU protected to allow dereferences from get_work_pool() */
3227 call_rcu_sched(&pool->rcu, rcu_free_pool);
3231 * get_unbound_pool - get a worker_pool with the specified attributes
3232 * @attrs: the attributes of the worker_pool to get
3234 * Obtain a worker_pool which has the same attributes as @attrs, bump the
3235 * reference count and return it. If there already is a matching
3236 * worker_pool, it will be used; otherwise, this function attempts to
3237 * create a new one.
3239 * Should be called with wq_pool_mutex held.
3241 * Return: On success, a worker_pool with the same attributes as @attrs.
3242 * On failure, %NULL.
3244 static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
3246 u32 hash = wqattrs_hash(attrs);
3247 struct worker_pool *pool;
3248 int node;
3250 lockdep_assert_held(&wq_pool_mutex);
3252 /* do we already have a matching pool? */
3253 hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
3254 if (wqattrs_equal(pool->attrs, attrs)) {
3255 pool->refcnt++;
3256 return pool;
3260 /* nope, create a new one */
3261 pool = kzalloc(sizeof(*pool), GFP_KERNEL);
3262 if (!pool || init_worker_pool(pool) < 0)
3263 goto fail;
3265 lockdep_set_subclass(&pool->lock, 1); /* see put_pwq() */
3266 copy_workqueue_attrs(pool->attrs, attrs);
3269 * no_numa isn't a worker_pool attribute, always clear it. See
3270 * 'struct workqueue_attrs' comments for detail.
3272 pool->attrs->no_numa = false;
3274 /* if cpumask is contained inside a NUMA node, we belong to that node */
3275 if (wq_numa_enabled) {
3276 for_each_node(node) {
3277 if (cpumask_subset(pool->attrs->cpumask,
3278 wq_numa_possible_cpumask[node])) {
3279 pool->node = node;
3280 break;
3285 if (worker_pool_assign_id(pool) < 0)
3286 goto fail;
3288 /* create and start the initial worker */
3289 if (!create_worker(pool))
3290 goto fail;
3292 /* install */
3293 hash_add(unbound_pool_hash, &pool->hash_node, hash);
3295 return pool;
3296 fail:
3297 if (pool)
3298 put_unbound_pool(pool);
3299 return NULL;
3302 static void rcu_free_pwq(struct rcu_head *rcu)
3304 kmem_cache_free(pwq_cache,
3305 container_of(rcu, struct pool_workqueue, rcu));
3309 * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
3310 * and needs to be destroyed.
3312 static void pwq_unbound_release_workfn(struct work_struct *work)
3314 struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
3315 unbound_release_work);
3316 struct workqueue_struct *wq = pwq->wq;
3317 struct worker_pool *pool = pwq->pool;
3318 bool is_last;
3320 if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
3321 return;
3323 mutex_lock(&wq->mutex);
3324 list_del_rcu(&pwq->pwqs_node);
3325 is_last = list_empty(&wq->pwqs);
3326 mutex_unlock(&wq->mutex);
3328 mutex_lock(&wq_pool_mutex);
3329 put_unbound_pool(pool);
3330 mutex_unlock(&wq_pool_mutex);
3332 call_rcu_sched(&pwq->rcu, rcu_free_pwq);
3335 * If we're the last pwq going away, @wq is already dead and no one
3336 * is gonna access it anymore. Schedule RCU free.
3338 if (is_last)
3339 call_rcu_sched(&wq->rcu, rcu_free_wq);
3343 * pwq_adjust_max_active - update a pwq's max_active to the current setting
3344 * @pwq: target pool_workqueue
3346 * If @pwq isn't freezing, set @pwq->max_active to the associated
3347 * workqueue's saved_max_active and activate delayed work items
3348 * accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
3350 static void pwq_adjust_max_active(struct pool_workqueue *pwq)
3352 struct workqueue_struct *wq = pwq->wq;
3353 bool freezable = wq->flags & WQ_FREEZABLE;
3355 /* for @wq->saved_max_active */
3356 lockdep_assert_held(&wq->mutex);
3358 /* fast exit for non-freezable wqs */
3359 if (!freezable && pwq->max_active == wq->saved_max_active)
3360 return;
3362 spin_lock_irq(&pwq->pool->lock);
3365 * During [un]freezing, the caller is responsible for ensuring that
3366 * this function is called at least once after @workqueue_freezing
3367 * is updated and visible.
3369 if (!freezable || !workqueue_freezing) {
3370 pwq->max_active = wq->saved_max_active;
3372 while (!list_empty(&pwq->delayed_works) &&
3373 pwq->nr_active < pwq->max_active)
3374 pwq_activate_first_delayed(pwq);
3377 * Need to kick a worker after thawed or an unbound wq's
3378 * max_active is bumped. It's a slow path. Do it always.
3380 wake_up_worker(pwq->pool);
3381 } else {
3382 pwq->max_active = 0;
3385 spin_unlock_irq(&pwq->pool->lock);
3388 /* initialize newly alloced @pwq which is associated with @wq and @pool */
3389 static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
3390 struct worker_pool *pool)
3392 BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3394 memset(pwq, 0, sizeof(*pwq));
3396 pwq->pool = pool;
3397 pwq->wq = wq;
3398 pwq->flush_color = -1;
3399 pwq->refcnt = 1;
3400 INIT_LIST_HEAD(&pwq->delayed_works);
3401 INIT_LIST_HEAD(&pwq->pwqs_node);
3402 INIT_LIST_HEAD(&pwq->mayday_node);
3403 INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
3406 /* sync @pwq with the current state of its associated wq and link it */
3407 static void link_pwq(struct pool_workqueue *pwq)
3409 struct workqueue_struct *wq = pwq->wq;
3411 lockdep_assert_held(&wq->mutex);
3413 /* may be called multiple times, ignore if already linked */
3414 if (!list_empty(&pwq->pwqs_node))
3415 return;
3417 /* set the matching work_color */
3418 pwq->work_color = wq->work_color;
3420 /* sync max_active to the current setting */
3421 pwq_adjust_max_active(pwq);
3423 /* link in @pwq */
3424 list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
3427 /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
3428 static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
3429 const struct workqueue_attrs *attrs)
3431 struct worker_pool *pool;
3432 struct pool_workqueue *pwq;
3434 lockdep_assert_held(&wq_pool_mutex);
3436 pool = get_unbound_pool(attrs);
3437 if (!pool)
3438 return NULL;
3440 pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
3441 if (!pwq) {
3442 put_unbound_pool(pool);
3443 return NULL;
3446 init_pwq(pwq, wq, pool);
3447 return pwq;
3451 * wq_calc_node_mask - calculate a wq_attrs' cpumask for the specified node
3452 * @attrs: the wq_attrs of interest
3453 * @node: the target NUMA node
3454 * @cpu_going_down: if >= 0, the CPU to consider as offline
3455 * @cpumask: outarg, the resulting cpumask
3457 * Calculate the cpumask a workqueue with @attrs should use on @node. If
3458 * @cpu_going_down is >= 0, that cpu is considered offline during
3459 * calculation. The result is stored in @cpumask.
3461 * If NUMA affinity is not enabled, @attrs->cpumask is always used. If
3462 * enabled and @node has online CPUs requested by @attrs, the returned
3463 * cpumask is the intersection of the possible CPUs of @node and
3464 * @attrs->cpumask.
3466 * The caller is responsible for ensuring that the cpumask of @node stays
3467 * stable.
3469 * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
3470 * %false if equal.
3472 static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
3473 int cpu_going_down, cpumask_t *cpumask)
3475 if (!wq_numa_enabled || attrs->no_numa)
3476 goto use_dfl;
3478 /* does @node have any online CPUs @attrs wants? */
3479 cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
3480 if (cpu_going_down >= 0)
3481 cpumask_clear_cpu(cpu_going_down, cpumask);
3483 if (cpumask_empty(cpumask))
3484 goto use_dfl;
3486 /* yeap, return possible CPUs in @node that @attrs wants */
3487 cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
3488 return !cpumask_equal(cpumask, attrs->cpumask);
3490 use_dfl:
3491 cpumask_copy(cpumask, attrs->cpumask);
3492 return false;
3495 /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
3496 static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
3497 int node,
3498 struct pool_workqueue *pwq)
3500 struct pool_workqueue *old_pwq;
3502 lockdep_assert_held(&wq_pool_mutex);
3503 lockdep_assert_held(&wq->mutex);
3505 /* link_pwq() can handle duplicate calls */
3506 link_pwq(pwq);
3508 old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
3509 rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
3510 return old_pwq;
3513 /* context to store the prepared attrs & pwqs before applying */
3514 struct apply_wqattrs_ctx {
3515 struct workqueue_struct *wq; /* target workqueue */
3516 struct workqueue_attrs *attrs; /* attrs to apply */
3517 struct pool_workqueue *dfl_pwq;
3518 struct pool_workqueue *pwq_tbl[];
3521 /* free the resources after success or abort */
3522 static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
3524 if (ctx) {
3525 int node;
3527 for_each_node(node)
3528 put_pwq_unlocked(ctx->pwq_tbl[node]);
3529 put_pwq_unlocked(ctx->dfl_pwq);
3531 free_workqueue_attrs(ctx->attrs);
3533 kfree(ctx);
3537 /* allocate the attrs and pwqs for later installation */
3538 static struct apply_wqattrs_ctx *
3539 apply_wqattrs_prepare(struct workqueue_struct *wq,
3540 const struct workqueue_attrs *attrs)
3542 struct apply_wqattrs_ctx *ctx;
3543 struct workqueue_attrs *new_attrs, *tmp_attrs;
3544 int node;
3546 lockdep_assert_held(&wq_pool_mutex);
3548 ctx = kzalloc(sizeof(*ctx) + nr_node_ids * sizeof(ctx->pwq_tbl[0]),
3549 GFP_KERNEL);
3551 new_attrs = alloc_workqueue_attrs(GFP_KERNEL);
3552 tmp_attrs = alloc_workqueue_attrs(GFP_KERNEL);
3553 if (!ctx || !new_attrs || !tmp_attrs)
3554 goto out_free;
3556 /* make a copy of @attrs and sanitize it */
3557 copy_workqueue_attrs(new_attrs, attrs);
3558 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
3561 * We may create multiple pwqs with differing cpumasks. Make a
3562 * copy of @new_attrs which will be modified and used to obtain
3563 * pools.
3565 copy_workqueue_attrs(tmp_attrs, new_attrs);
3568 * If something goes wrong during CPU up/down, we'll fall back to
3569 * the default pwq covering whole @attrs->cpumask. Always create
3570 * it even if we don't use it immediately.
3572 ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
3573 if (!ctx->dfl_pwq)
3574 goto out_free;
3576 for_each_node(node) {
3577 if (wq_calc_node_cpumask(attrs, node, -1, tmp_attrs->cpumask)) {
3578 ctx->pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
3579 if (!ctx->pwq_tbl[node])
3580 goto out_free;
3581 } else {
3582 ctx->dfl_pwq->refcnt++;
3583 ctx->pwq_tbl[node] = ctx->dfl_pwq;
3587 ctx->attrs = new_attrs;
3588 ctx->wq = wq;
3589 free_workqueue_attrs(tmp_attrs);
3590 return ctx;
3592 out_free:
3593 free_workqueue_attrs(tmp_attrs);
3594 free_workqueue_attrs(new_attrs);
3595 apply_wqattrs_cleanup(ctx);
3596 return NULL;
3599 /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
3600 static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
3602 int node;
3604 /* all pwqs have been created successfully, let's install'em */
3605 mutex_lock(&ctx->wq->mutex);
3607 copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
3609 /* save the previous pwq and install the new one */
3610 for_each_node(node)
3611 ctx->pwq_tbl[node] = numa_pwq_tbl_install(ctx->wq, node,
3612 ctx->pwq_tbl[node]);
3614 /* @dfl_pwq might not have been used, ensure it's linked */
3615 link_pwq(ctx->dfl_pwq);
3616 swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
3618 mutex_unlock(&ctx->wq->mutex);
3622 * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
3623 * @wq: the target workqueue
3624 * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
3626 * Apply @attrs to an unbound workqueue @wq. Unless disabled, on NUMA
3627 * machines, this function maps a separate pwq to each NUMA node with
3628 * possibles CPUs in @attrs->cpumask so that work items are affine to the
3629 * NUMA node it was issued on. Older pwqs are released as in-flight work
3630 * items finish. Note that a work item which repeatedly requeues itself
3631 * back-to-back will stay on its current pwq.
3633 * Performs GFP_KERNEL allocations.
3635 * Return: 0 on success and -errno on failure.
3637 int apply_workqueue_attrs(struct workqueue_struct *wq,
3638 const struct workqueue_attrs *attrs)
3640 struct apply_wqattrs_ctx *ctx;
3641 int ret = -ENOMEM;
3643 /* only unbound workqueues can change attributes */
3644 if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
3645 return -EINVAL;
3647 /* creating multiple pwqs breaks ordering guarantee */
3648 if (WARN_ON((wq->flags & __WQ_ORDERED) && !list_empty(&wq->pwqs)))
3649 return -EINVAL;
3652 * CPUs should stay stable across pwq creations and installations.
3653 * Pin CPUs, determine the target cpumask for each node and create
3654 * pwqs accordingly.
3656 get_online_cpus();
3657 mutex_lock(&wq_pool_mutex);
3659 ctx = apply_wqattrs_prepare(wq, attrs);
3661 /* the ctx has been prepared successfully, let's commit it */
3662 if (ctx) {
3663 apply_wqattrs_commit(ctx);
3664 ret = 0;
3667 mutex_unlock(&wq_pool_mutex);
3668 put_online_cpus();
3670 apply_wqattrs_cleanup(ctx);
3672 return ret;
3676 * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
3677 * @wq: the target workqueue
3678 * @cpu: the CPU coming up or going down
3679 * @online: whether @cpu is coming up or going down
3681 * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
3682 * %CPU_DOWN_FAILED. @cpu is being hot[un]plugged, update NUMA affinity of
3683 * @wq accordingly.
3685 * If NUMA affinity can't be adjusted due to memory allocation failure, it
3686 * falls back to @wq->dfl_pwq which may not be optimal but is always
3687 * correct.
3689 * Note that when the last allowed CPU of a NUMA node goes offline for a
3690 * workqueue with a cpumask spanning multiple nodes, the workers which were
3691 * already executing the work items for the workqueue will lose their CPU
3692 * affinity and may execute on any CPU. This is similar to how per-cpu
3693 * workqueues behave on CPU_DOWN. If a workqueue user wants strict
3694 * affinity, it's the user's responsibility to flush the work item from
3695 * CPU_DOWN_PREPARE.
3697 static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
3698 bool online)
3700 int node = cpu_to_node(cpu);
3701 int cpu_off = online ? -1 : cpu;
3702 struct pool_workqueue *old_pwq = NULL, *pwq;
3703 struct workqueue_attrs *target_attrs;
3704 cpumask_t *cpumask;
3706 lockdep_assert_held(&wq_pool_mutex);
3708 if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND))
3709 return;
3712 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
3713 * Let's use a preallocated one. The following buf is protected by
3714 * CPU hotplug exclusion.
3716 target_attrs = wq_update_unbound_numa_attrs_buf;
3717 cpumask = target_attrs->cpumask;
3719 mutex_lock(&wq->mutex);
3720 if (wq->unbound_attrs->no_numa)
3721 goto out_unlock;
3723 copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
3724 pwq = unbound_pwq_by_node(wq, node);
3727 * Let's determine what needs to be done. If the target cpumask is
3728 * different from wq's, we need to compare it to @pwq's and create
3729 * a new one if they don't match. If the target cpumask equals
3730 * wq's, the default pwq should be used.
3732 if (wq_calc_node_cpumask(wq->unbound_attrs, node, cpu_off, cpumask)) {
3733 if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
3734 goto out_unlock;
3735 } else {
3736 goto use_dfl_pwq;
3739 mutex_unlock(&wq->mutex);
3741 /* create a new pwq */
3742 pwq = alloc_unbound_pwq(wq, target_attrs);
3743 if (!pwq) {
3744 pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
3745 wq->name);
3746 mutex_lock(&wq->mutex);
3747 goto use_dfl_pwq;
3751 * Install the new pwq. As this function is called only from CPU
3752 * hotplug callbacks and applying a new attrs is wrapped with
3753 * get/put_online_cpus(), @wq->unbound_attrs couldn't have changed
3754 * inbetween.
3756 mutex_lock(&wq->mutex);
3757 old_pwq = numa_pwq_tbl_install(wq, node, pwq);
3758 goto out_unlock;
3760 use_dfl_pwq:
3761 spin_lock_irq(&wq->dfl_pwq->pool->lock);
3762 get_pwq(wq->dfl_pwq);
3763 spin_unlock_irq(&wq->dfl_pwq->pool->lock);
3764 old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
3765 out_unlock:
3766 mutex_unlock(&wq->mutex);
3767 put_pwq_unlocked(old_pwq);
3770 static int alloc_and_link_pwqs(struct workqueue_struct *wq)
3772 bool highpri = wq->flags & WQ_HIGHPRI;
3773 int cpu, ret;
3775 if (!(wq->flags & WQ_UNBOUND)) {
3776 wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
3777 if (!wq->cpu_pwqs)
3778 return -ENOMEM;
3780 for_each_possible_cpu(cpu) {
3781 struct pool_workqueue *pwq =
3782 per_cpu_ptr(wq->cpu_pwqs, cpu);
3783 struct worker_pool *cpu_pools =
3784 per_cpu(cpu_worker_pools, cpu);
3786 init_pwq(pwq, wq, &cpu_pools[highpri]);
3788 mutex_lock(&wq->mutex);
3789 link_pwq(pwq);
3790 mutex_unlock(&wq->mutex);
3792 return 0;
3793 } else if (wq->flags & __WQ_ORDERED) {
3794 ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
3795 /* there should only be single pwq for ordering guarantee */
3796 WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
3797 wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
3798 "ordering guarantee broken for workqueue %s\n", wq->name);
3799 return ret;
3800 } else {
3801 return apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
3805 static int wq_clamp_max_active(int max_active, unsigned int flags,
3806 const char *name)
3808 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3810 if (max_active < 1 || max_active > lim)
3811 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3812 max_active, name, 1, lim);
3814 return clamp_val(max_active, 1, lim);
3817 struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
3818 unsigned int flags,
3819 int max_active,
3820 struct lock_class_key *key,
3821 const char *lock_name, ...)
3823 size_t tbl_size = 0;
3824 va_list args;
3825 struct workqueue_struct *wq;
3826 struct pool_workqueue *pwq;
3828 /* see the comment above the definition of WQ_POWER_EFFICIENT */
3829 if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
3830 flags |= WQ_UNBOUND;
3832 /* allocate wq and format name */
3833 if (flags & WQ_UNBOUND)
3834 tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
3836 wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
3837 if (!wq)
3838 return NULL;
3840 if (flags & WQ_UNBOUND) {
3841 wq->unbound_attrs = alloc_workqueue_attrs(GFP_KERNEL);
3842 if (!wq->unbound_attrs)
3843 goto err_free_wq;
3846 va_start(args, lock_name);
3847 vsnprintf(wq->name, sizeof(wq->name), fmt, args);
3848 va_end(args);
3850 max_active = max_active ?: WQ_DFL_ACTIVE;
3851 max_active = wq_clamp_max_active(max_active, flags, wq->name);
3853 /* init wq */
3854 wq->flags = flags;
3855 wq->saved_max_active = max_active;
3856 mutex_init(&wq->mutex);
3857 atomic_set(&wq->nr_pwqs_to_flush, 0);
3858 INIT_LIST_HEAD(&wq->pwqs);
3859 INIT_LIST_HEAD(&wq->flusher_queue);
3860 INIT_LIST_HEAD(&wq->flusher_overflow);
3861 INIT_LIST_HEAD(&wq->maydays);
3863 lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3864 INIT_LIST_HEAD(&wq->list);
3866 if (alloc_and_link_pwqs(wq) < 0)
3867 goto err_free_wq;
3870 * Workqueues which may be used during memory reclaim should
3871 * have a rescuer to guarantee forward progress.
3873 if (flags & WQ_MEM_RECLAIM) {
3874 struct worker *rescuer;
3876 rescuer = alloc_worker(NUMA_NO_NODE);
3877 if (!rescuer)
3878 goto err_destroy;
3880 rescuer->rescue_wq = wq;
3881 rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
3882 wq->name);
3883 if (IS_ERR(rescuer->task)) {
3884 kfree(rescuer);
3885 goto err_destroy;
3888 wq->rescuer = rescuer;
3889 rescuer->task->flags |= PF_NO_SETAFFINITY;
3890 wake_up_process(rescuer->task);
3893 if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
3894 goto err_destroy;
3897 * wq_pool_mutex protects global freeze state and workqueues list.
3898 * Grab it, adjust max_active and add the new @wq to workqueues
3899 * list.
3901 mutex_lock(&wq_pool_mutex);
3903 mutex_lock(&wq->mutex);
3904 for_each_pwq(pwq, wq)
3905 pwq_adjust_max_active(pwq);
3906 mutex_unlock(&wq->mutex);
3908 list_add_tail_rcu(&wq->list, &workqueues);
3910 mutex_unlock(&wq_pool_mutex);
3912 return wq;
3914 err_free_wq:
3915 free_workqueue_attrs(wq->unbound_attrs);
3916 kfree(wq);
3917 return NULL;
3918 err_destroy:
3919 destroy_workqueue(wq);
3920 return NULL;
3922 EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
3925 * destroy_workqueue - safely terminate a workqueue
3926 * @wq: target workqueue
3928 * Safely destroy a workqueue. All work currently pending will be done first.
3930 void destroy_workqueue(struct workqueue_struct *wq)
3932 struct pool_workqueue *pwq;
3933 int node;
3935 /* drain it before proceeding with destruction */
3936 drain_workqueue(wq);
3938 /* sanity checks */
3939 mutex_lock(&wq->mutex);
3940 for_each_pwq(pwq, wq) {
3941 int i;
3943 for (i = 0; i < WORK_NR_COLORS; i++) {
3944 if (WARN_ON(pwq->nr_in_flight[i])) {
3945 mutex_unlock(&wq->mutex);
3946 return;
3950 if (WARN_ON((pwq != wq->dfl_pwq) && (pwq->refcnt > 1)) ||
3951 WARN_ON(pwq->nr_active) ||
3952 WARN_ON(!list_empty(&pwq->delayed_works))) {
3953 mutex_unlock(&wq->mutex);
3954 return;
3957 mutex_unlock(&wq->mutex);
3960 * wq list is used to freeze wq, remove from list after
3961 * flushing is complete in case freeze races us.
3963 mutex_lock(&wq_pool_mutex);
3964 list_del_rcu(&wq->list);
3965 mutex_unlock(&wq_pool_mutex);
3967 workqueue_sysfs_unregister(wq);
3969 if (wq->rescuer)
3970 kthread_stop(wq->rescuer->task);
3972 if (!(wq->flags & WQ_UNBOUND)) {
3974 * The base ref is never dropped on per-cpu pwqs. Directly
3975 * schedule RCU free.
3977 call_rcu_sched(&wq->rcu, rcu_free_wq);
3978 } else {
3980 * We're the sole accessor of @wq at this point. Directly
3981 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
3982 * @wq will be freed when the last pwq is released.
3984 for_each_node(node) {
3985 pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
3986 RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
3987 put_pwq_unlocked(pwq);
3991 * Put dfl_pwq. @wq may be freed any time after dfl_pwq is
3992 * put. Don't access it afterwards.
3994 pwq = wq->dfl_pwq;
3995 wq->dfl_pwq = NULL;
3996 put_pwq_unlocked(pwq);
3999 EXPORT_SYMBOL_GPL(destroy_workqueue);
4002 * workqueue_set_max_active - adjust max_active of a workqueue
4003 * @wq: target workqueue
4004 * @max_active: new max_active value.
4006 * Set max_active of @wq to @max_active.
4008 * CONTEXT:
4009 * Don't call from IRQ context.
4011 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4013 struct pool_workqueue *pwq;
4015 /* disallow meddling with max_active for ordered workqueues */
4016 if (WARN_ON(wq->flags & __WQ_ORDERED))
4017 return;
4019 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4021 mutex_lock(&wq->mutex);
4023 wq->saved_max_active = max_active;
4025 for_each_pwq(pwq, wq)
4026 pwq_adjust_max_active(pwq);
4028 mutex_unlock(&wq->mutex);
4030 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4033 * current_is_workqueue_rescuer - is %current workqueue rescuer?
4035 * Determine whether %current is a workqueue rescuer. Can be used from
4036 * work functions to determine whether it's being run off the rescuer task.
4038 * Return: %true if %current is a workqueue rescuer. %false otherwise.
4040 bool current_is_workqueue_rescuer(void)
4042 struct worker *worker = current_wq_worker();
4044 return worker && worker->rescue_wq;
4048 * workqueue_congested - test whether a workqueue is congested
4049 * @cpu: CPU in question
4050 * @wq: target workqueue
4052 * Test whether @wq's cpu workqueue for @cpu is congested. There is
4053 * no synchronization around this function and the test result is
4054 * unreliable and only useful as advisory hints or for debugging.
4056 * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4057 * Note that both per-cpu and unbound workqueues may be associated with
4058 * multiple pool_workqueues which have separate congested states. A
4059 * workqueue being congested on one CPU doesn't mean the workqueue is also
4060 * contested on other CPUs / NUMA nodes.
4062 * Return:
4063 * %true if congested, %false otherwise.
4065 bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4067 struct pool_workqueue *pwq;
4068 bool ret;
4070 rcu_read_lock_sched();
4072 if (cpu == WORK_CPU_UNBOUND)
4073 cpu = smp_processor_id();
4075 if (!(wq->flags & WQ_UNBOUND))
4076 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
4077 else
4078 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4080 ret = !list_empty(&pwq->delayed_works);
4081 rcu_read_unlock_sched();
4083 return ret;
4085 EXPORT_SYMBOL_GPL(workqueue_congested);
4088 * work_busy - test whether a work is currently pending or running
4089 * @work: the work to be tested
4091 * Test whether @work is currently pending or running. There is no
4092 * synchronization around this function and the test result is
4093 * unreliable and only useful as advisory hints or for debugging.
4095 * Return:
4096 * OR'd bitmask of WORK_BUSY_* bits.
4098 unsigned int work_busy(struct work_struct *work)
4100 struct worker_pool *pool;
4101 unsigned long flags;
4102 unsigned int ret = 0;
4104 if (work_pending(work))
4105 ret |= WORK_BUSY_PENDING;
4107 local_irq_save(flags);
4108 pool = get_work_pool(work);
4109 if (pool) {
4110 spin_lock(&pool->lock);
4111 if (find_worker_executing_work(pool, work))
4112 ret |= WORK_BUSY_RUNNING;
4113 spin_unlock(&pool->lock);
4115 local_irq_restore(flags);
4117 return ret;
4119 EXPORT_SYMBOL_GPL(work_busy);
4122 * set_worker_desc - set description for the current work item
4123 * @fmt: printf-style format string
4124 * @...: arguments for the format string
4126 * This function can be called by a running work function to describe what
4127 * the work item is about. If the worker task gets dumped, this
4128 * information will be printed out together to help debugging. The
4129 * description can be at most WORKER_DESC_LEN including the trailing '\0'.
4131 void set_worker_desc(const char *fmt, ...)
4133 struct worker *worker = current_wq_worker();
4134 va_list args;
4136 if (worker) {
4137 va_start(args, fmt);
4138 vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
4139 va_end(args);
4140 worker->desc_valid = true;
4145 * print_worker_info - print out worker information and description
4146 * @log_lvl: the log level to use when printing
4147 * @task: target task
4149 * If @task is a worker and currently executing a work item, print out the
4150 * name of the workqueue being serviced and worker description set with
4151 * set_worker_desc() by the currently executing work item.
4153 * This function can be safely called on any task as long as the
4154 * task_struct itself is accessible. While safe, this function isn't
4155 * synchronized and may print out mixups or garbages of limited length.
4157 void print_worker_info(const char *log_lvl, struct task_struct *task)
4159 work_func_t *fn = NULL;
4160 char name[WQ_NAME_LEN] = { };
4161 char desc[WORKER_DESC_LEN] = { };
4162 struct pool_workqueue *pwq = NULL;
4163 struct workqueue_struct *wq = NULL;
4164 bool desc_valid = false;
4165 struct worker *worker;
4167 if (!(task->flags & PF_WQ_WORKER))
4168 return;
4171 * This function is called without any synchronization and @task
4172 * could be in any state. Be careful with dereferences.
4174 worker = probe_kthread_data(task);
4177 * Carefully copy the associated workqueue's workfn and name. Keep
4178 * the original last '\0' in case the original contains garbage.
4180 probe_kernel_read(&fn, &worker->current_func, sizeof(fn));
4181 probe_kernel_read(&pwq, &worker->current_pwq, sizeof(pwq));
4182 probe_kernel_read(&wq, &pwq->wq, sizeof(wq));
4183 probe_kernel_read(name, wq->name, sizeof(name) - 1);
4185 /* copy worker description */
4186 probe_kernel_read(&desc_valid, &worker->desc_valid, sizeof(desc_valid));
4187 if (desc_valid)
4188 probe_kernel_read(desc, worker->desc, sizeof(desc) - 1);
4190 if (fn || name[0] || desc[0]) {
4191 printk("%sWorkqueue: %s %pf", log_lvl, name, fn);
4192 if (desc[0])
4193 pr_cont(" (%s)", desc);
4194 pr_cont("\n");
4198 static void pr_cont_pool_info(struct worker_pool *pool)
4200 pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
4201 if (pool->node != NUMA_NO_NODE)
4202 pr_cont(" node=%d", pool->node);
4203 pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
4206 static void pr_cont_work(bool comma, struct work_struct *work)
4208 if (work->func == wq_barrier_func) {
4209 struct wq_barrier *barr;
4211 barr = container_of(work, struct wq_barrier, work);
4213 pr_cont("%s BAR(%d)", comma ? "," : "",
4214 task_pid_nr(barr->task));
4215 } else {
4216 pr_cont("%s %pf", comma ? "," : "", work->func);
4220 static void show_pwq(struct pool_workqueue *pwq)
4222 struct worker_pool *pool = pwq->pool;
4223 struct work_struct *work;
4224 struct worker *worker;
4225 bool has_in_flight = false, has_pending = false;
4226 int bkt;
4228 pr_info(" pwq %d:", pool->id);
4229 pr_cont_pool_info(pool);
4231 pr_cont(" active=%d/%d%s\n", pwq->nr_active, pwq->max_active,
4232 !list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
4234 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
4235 if (worker->current_pwq == pwq) {
4236 has_in_flight = true;
4237 break;
4240 if (has_in_flight) {
4241 bool comma = false;
4243 pr_info(" in-flight:");
4244 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
4245 if (worker->current_pwq != pwq)
4246 continue;
4248 pr_cont("%s %d%s:%pf", comma ? "," : "",
4249 task_pid_nr(worker->task),
4250 worker == pwq->wq->rescuer ? "(RESCUER)" : "",
4251 worker->current_func);
4252 list_for_each_entry(work, &worker->scheduled, entry)
4253 pr_cont_work(false, work);
4254 comma = true;
4256 pr_cont("\n");
4259 list_for_each_entry(work, &pool->worklist, entry) {
4260 if (get_work_pwq(work) == pwq) {
4261 has_pending = true;
4262 break;
4265 if (has_pending) {
4266 bool comma = false;
4268 pr_info(" pending:");
4269 list_for_each_entry(work, &pool->worklist, entry) {
4270 if (get_work_pwq(work) != pwq)
4271 continue;
4273 pr_cont_work(comma, work);
4274 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
4276 pr_cont("\n");
4279 if (!list_empty(&pwq->delayed_works)) {
4280 bool comma = false;
4282 pr_info(" delayed:");
4283 list_for_each_entry(work, &pwq->delayed_works, entry) {
4284 pr_cont_work(comma, work);
4285 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
4287 pr_cont("\n");
4292 * show_workqueue_state - dump workqueue state
4294 * Called from a sysrq handler and prints out all busy workqueues and
4295 * pools.
4297 void show_workqueue_state(void)
4299 struct workqueue_struct *wq;
4300 struct worker_pool *pool;
4301 unsigned long flags;
4302 int pi;
4304 rcu_read_lock_sched();
4306 pr_info("Showing busy workqueues and worker pools:\n");
4308 list_for_each_entry_rcu(wq, &workqueues, list) {
4309 struct pool_workqueue *pwq;
4310 bool idle = true;
4312 for_each_pwq(pwq, wq) {
4313 if (pwq->nr_active || !list_empty(&pwq->delayed_works)) {
4314 idle = false;
4315 break;
4318 if (idle)
4319 continue;
4321 pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
4323 for_each_pwq(pwq, wq) {
4324 spin_lock_irqsave(&pwq->pool->lock, flags);
4325 if (pwq->nr_active || !list_empty(&pwq->delayed_works))
4326 show_pwq(pwq);
4327 spin_unlock_irqrestore(&pwq->pool->lock, flags);
4331 for_each_pool(pool, pi) {
4332 struct worker *worker;
4333 bool first = true;
4335 spin_lock_irqsave(&pool->lock, flags);
4336 if (pool->nr_workers == pool->nr_idle)
4337 goto next_pool;
4339 pr_info("pool %d:", pool->id);
4340 pr_cont_pool_info(pool);
4341 pr_cont(" workers=%d", pool->nr_workers);
4342 if (pool->manager)
4343 pr_cont(" manager: %d",
4344 task_pid_nr(pool->manager->task));
4345 list_for_each_entry(worker, &pool->idle_list, entry) {
4346 pr_cont(" %s%d", first ? "idle: " : "",
4347 task_pid_nr(worker->task));
4348 first = false;
4350 pr_cont("\n");
4351 next_pool:
4352 spin_unlock_irqrestore(&pool->lock, flags);
4355 rcu_read_unlock_sched();
4359 * CPU hotplug.
4361 * There are two challenges in supporting CPU hotplug. Firstly, there
4362 * are a lot of assumptions on strong associations among work, pwq and
4363 * pool which make migrating pending and scheduled works very
4364 * difficult to implement without impacting hot paths. Secondly,
4365 * worker pools serve mix of short, long and very long running works making
4366 * blocked draining impractical.
4368 * This is solved by allowing the pools to be disassociated from the CPU
4369 * running as an unbound one and allowing it to be reattached later if the
4370 * cpu comes back online.
4373 static void wq_unbind_fn(struct work_struct *work)
4375 int cpu = smp_processor_id();
4376 struct worker_pool *pool;
4377 struct worker *worker;
4379 for_each_cpu_worker_pool(pool, cpu) {
4380 mutex_lock(&pool->attach_mutex);
4381 spin_lock_irq(&pool->lock);
4384 * We've blocked all attach/detach operations. Make all workers
4385 * unbound and set DISASSOCIATED. Before this, all workers
4386 * except for the ones which are still executing works from
4387 * before the last CPU down must be on the cpu. After
4388 * this, they may become diasporas.
4390 for_each_pool_worker(worker, pool)
4391 worker->flags |= WORKER_UNBOUND;
4393 pool->flags |= POOL_DISASSOCIATED;
4395 spin_unlock_irq(&pool->lock);
4396 mutex_unlock(&pool->attach_mutex);
4399 * Call schedule() so that we cross rq->lock and thus can
4400 * guarantee sched callbacks see the %WORKER_UNBOUND flag.
4401 * This is necessary as scheduler callbacks may be invoked
4402 * from other cpus.
4404 schedule();
4407 * Sched callbacks are disabled now. Zap nr_running.
4408 * After this, nr_running stays zero and need_more_worker()
4409 * and keep_working() are always true as long as the
4410 * worklist is not empty. This pool now behaves as an
4411 * unbound (in terms of concurrency management) pool which
4412 * are served by workers tied to the pool.
4414 atomic_set(&pool->nr_running, 0);
4417 * With concurrency management just turned off, a busy
4418 * worker blocking could lead to lengthy stalls. Kick off
4419 * unbound chain execution of currently pending work items.
4421 spin_lock_irq(&pool->lock);
4422 wake_up_worker(pool);
4423 spin_unlock_irq(&pool->lock);
4428 * rebind_workers - rebind all workers of a pool to the associated CPU
4429 * @pool: pool of interest
4431 * @pool->cpu is coming online. Rebind all workers to the CPU.
4433 static void rebind_workers(struct worker_pool *pool)
4435 struct worker *worker;
4437 lockdep_assert_held(&pool->attach_mutex);
4440 * Restore CPU affinity of all workers. As all idle workers should
4441 * be on the run-queue of the associated CPU before any local
4442 * wake-ups for concurrency management happen, restore CPU affinty
4443 * of all workers first and then clear UNBOUND. As we're called
4444 * from CPU_ONLINE, the following shouldn't fail.
4446 for_each_pool_worker(worker, pool)
4447 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4448 pool->attrs->cpumask) < 0);
4450 spin_lock_irq(&pool->lock);
4451 pool->flags &= ~POOL_DISASSOCIATED;
4453 for_each_pool_worker(worker, pool) {
4454 unsigned int worker_flags = worker->flags;
4457 * A bound idle worker should actually be on the runqueue
4458 * of the associated CPU for local wake-ups targeting it to
4459 * work. Kick all idle workers so that they migrate to the
4460 * associated CPU. Doing this in the same loop as
4461 * replacing UNBOUND with REBOUND is safe as no worker will
4462 * be bound before @pool->lock is released.
4464 if (worker_flags & WORKER_IDLE)
4465 wake_up_process(worker->task);
4468 * We want to clear UNBOUND but can't directly call
4469 * worker_clr_flags() or adjust nr_running. Atomically
4470 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
4471 * @worker will clear REBOUND using worker_clr_flags() when
4472 * it initiates the next execution cycle thus restoring
4473 * concurrency management. Note that when or whether
4474 * @worker clears REBOUND doesn't affect correctness.
4476 * ACCESS_ONCE() is necessary because @worker->flags may be
4477 * tested without holding any lock in
4478 * wq_worker_waking_up(). Without it, NOT_RUNNING test may
4479 * fail incorrectly leading to premature concurrency
4480 * management operations.
4482 WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
4483 worker_flags |= WORKER_REBOUND;
4484 worker_flags &= ~WORKER_UNBOUND;
4485 ACCESS_ONCE(worker->flags) = worker_flags;
4488 spin_unlock_irq(&pool->lock);
4492 * restore_unbound_workers_cpumask - restore cpumask of unbound workers
4493 * @pool: unbound pool of interest
4494 * @cpu: the CPU which is coming up
4496 * An unbound pool may end up with a cpumask which doesn't have any online
4497 * CPUs. When a worker of such pool get scheduled, the scheduler resets
4498 * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
4499 * online CPU before, cpus_allowed of all its workers should be restored.
4501 static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
4503 static cpumask_t cpumask;
4504 struct worker *worker;
4506 lockdep_assert_held(&pool->attach_mutex);
4508 /* is @cpu allowed for @pool? */
4509 if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
4510 return;
4512 /* is @cpu the only online CPU? */
4513 cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
4514 if (cpumask_weight(&cpumask) != 1)
4515 return;
4517 /* as we're called from CPU_ONLINE, the following shouldn't fail */
4518 for_each_pool_worker(worker, pool)
4519 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4520 pool->attrs->cpumask) < 0);
4524 * Workqueues should be brought up before normal priority CPU notifiers.
4525 * This will be registered high priority CPU notifier.
4527 static int workqueue_cpu_up_callback(struct notifier_block *nfb,
4528 unsigned long action,
4529 void *hcpu)
4531 int cpu = (unsigned long)hcpu;
4532 struct worker_pool *pool;
4533 struct workqueue_struct *wq;
4534 int pi;
4536 switch (action & ~CPU_TASKS_FROZEN) {
4537 case CPU_UP_PREPARE:
4538 for_each_cpu_worker_pool(pool, cpu) {
4539 if (pool->nr_workers)
4540 continue;
4541 if (!create_worker(pool))
4542 return NOTIFY_BAD;
4544 break;
4546 case CPU_DOWN_FAILED:
4547 case CPU_ONLINE:
4548 mutex_lock(&wq_pool_mutex);
4550 for_each_pool(pool, pi) {
4551 mutex_lock(&pool->attach_mutex);
4553 if (pool->cpu == cpu)
4554 rebind_workers(pool);
4555 else if (pool->cpu < 0)
4556 restore_unbound_workers_cpumask(pool, cpu);
4558 mutex_unlock(&pool->attach_mutex);
4561 /* update NUMA affinity of unbound workqueues */
4562 list_for_each_entry(wq, &workqueues, list)
4563 wq_update_unbound_numa(wq, cpu, true);
4565 mutex_unlock(&wq_pool_mutex);
4566 break;
4568 return NOTIFY_OK;
4572 * Workqueues should be brought down after normal priority CPU notifiers.
4573 * This will be registered as low priority CPU notifier.
4575 static int workqueue_cpu_down_callback(struct notifier_block *nfb,
4576 unsigned long action,
4577 void *hcpu)
4579 int cpu = (unsigned long)hcpu;
4580 struct work_struct unbind_work;
4581 struct workqueue_struct *wq;
4583 switch (action & ~CPU_TASKS_FROZEN) {
4584 case CPU_DOWN_PREPARE:
4585 /* unbinding per-cpu workers should happen on the local CPU */
4586 INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
4587 queue_work_on(cpu, system_highpri_wq, &unbind_work);
4589 /* update NUMA affinity of unbound workqueues */
4590 mutex_lock(&wq_pool_mutex);
4591 list_for_each_entry(wq, &workqueues, list)
4592 wq_update_unbound_numa(wq, cpu, false);
4593 mutex_unlock(&wq_pool_mutex);
4595 /* wait for per-cpu unbinding to finish */
4596 flush_work(&unbind_work);
4597 destroy_work_on_stack(&unbind_work);
4598 break;
4600 return NOTIFY_OK;
4603 #ifdef CONFIG_SMP
4605 struct work_for_cpu {
4606 struct work_struct work;
4607 long (*fn)(void *);
4608 void *arg;
4609 long ret;
4612 static void work_for_cpu_fn(struct work_struct *work)
4614 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
4616 wfc->ret = wfc->fn(wfc->arg);
4620 * work_on_cpu - run a function in user context on a particular cpu
4621 * @cpu: the cpu to run on
4622 * @fn: the function to run
4623 * @arg: the function arg
4625 * It is up to the caller to ensure that the cpu doesn't go offline.
4626 * The caller must not hold any locks which would prevent @fn from completing.
4628 * Return: The value @fn returns.
4630 long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
4632 struct work_for_cpu wfc = { .fn = fn, .arg = arg };
4634 INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
4635 schedule_work_on(cpu, &wfc.work);
4636 flush_work(&wfc.work);
4637 destroy_work_on_stack(&wfc.work);
4638 return wfc.ret;
4640 EXPORT_SYMBOL_GPL(work_on_cpu);
4641 #endif /* CONFIG_SMP */
4643 #ifdef CONFIG_FREEZER
4646 * freeze_workqueues_begin - begin freezing workqueues
4648 * Start freezing workqueues. After this function returns, all freezable
4649 * workqueues will queue new works to their delayed_works list instead of
4650 * pool->worklist.
4652 * CONTEXT:
4653 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4655 void freeze_workqueues_begin(void)
4657 struct workqueue_struct *wq;
4658 struct pool_workqueue *pwq;
4660 mutex_lock(&wq_pool_mutex);
4662 WARN_ON_ONCE(workqueue_freezing);
4663 workqueue_freezing = true;
4665 list_for_each_entry(wq, &workqueues, list) {
4666 mutex_lock(&wq->mutex);
4667 for_each_pwq(pwq, wq)
4668 pwq_adjust_max_active(pwq);
4669 mutex_unlock(&wq->mutex);
4672 mutex_unlock(&wq_pool_mutex);
4676 * freeze_workqueues_busy - are freezable workqueues still busy?
4678 * Check whether freezing is complete. This function must be called
4679 * between freeze_workqueues_begin() and thaw_workqueues().
4681 * CONTEXT:
4682 * Grabs and releases wq_pool_mutex.
4684 * Return:
4685 * %true if some freezable workqueues are still busy. %false if freezing
4686 * is complete.
4688 bool freeze_workqueues_busy(void)
4690 bool busy = false;
4691 struct workqueue_struct *wq;
4692 struct pool_workqueue *pwq;
4694 mutex_lock(&wq_pool_mutex);
4696 WARN_ON_ONCE(!workqueue_freezing);
4698 list_for_each_entry(wq, &workqueues, list) {
4699 if (!(wq->flags & WQ_FREEZABLE))
4700 continue;
4702 * nr_active is monotonically decreasing. It's safe
4703 * to peek without lock.
4705 rcu_read_lock_sched();
4706 for_each_pwq(pwq, wq) {
4707 WARN_ON_ONCE(pwq->nr_active < 0);
4708 if (pwq->nr_active) {
4709 busy = true;
4710 rcu_read_unlock_sched();
4711 goto out_unlock;
4714 rcu_read_unlock_sched();
4716 out_unlock:
4717 mutex_unlock(&wq_pool_mutex);
4718 return busy;
4722 * thaw_workqueues - thaw workqueues
4724 * Thaw workqueues. Normal queueing is restored and all collected
4725 * frozen works are transferred to their respective pool worklists.
4727 * CONTEXT:
4728 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4730 void thaw_workqueues(void)
4732 struct workqueue_struct *wq;
4733 struct pool_workqueue *pwq;
4735 mutex_lock(&wq_pool_mutex);
4737 if (!workqueue_freezing)
4738 goto out_unlock;
4740 workqueue_freezing = false;
4742 /* restore max_active and repopulate worklist */
4743 list_for_each_entry(wq, &workqueues, list) {
4744 mutex_lock(&wq->mutex);
4745 for_each_pwq(pwq, wq)
4746 pwq_adjust_max_active(pwq);
4747 mutex_unlock(&wq->mutex);
4750 out_unlock:
4751 mutex_unlock(&wq_pool_mutex);
4753 #endif /* CONFIG_FREEZER */
4755 #ifdef CONFIG_SYSFS
4757 * Workqueues with WQ_SYSFS flag set is visible to userland via
4758 * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
4759 * following attributes.
4761 * per_cpu RO bool : whether the workqueue is per-cpu or unbound
4762 * max_active RW int : maximum number of in-flight work items
4764 * Unbound workqueues have the following extra attributes.
4766 * id RO int : the associated pool ID
4767 * nice RW int : nice value of the workers
4768 * cpumask RW mask : bitmask of allowed CPUs for the workers
4770 struct wq_device {
4771 struct workqueue_struct *wq;
4772 struct device dev;
4775 static struct workqueue_struct *dev_to_wq(struct device *dev)
4777 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
4779 return wq_dev->wq;
4782 static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
4783 char *buf)
4785 struct workqueue_struct *wq = dev_to_wq(dev);
4787 return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
4789 static DEVICE_ATTR_RO(per_cpu);
4791 static ssize_t max_active_show(struct device *dev,
4792 struct device_attribute *attr, char *buf)
4794 struct workqueue_struct *wq = dev_to_wq(dev);
4796 return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
4799 static ssize_t max_active_store(struct device *dev,
4800 struct device_attribute *attr, const char *buf,
4801 size_t count)
4803 struct workqueue_struct *wq = dev_to_wq(dev);
4804 int val;
4806 if (sscanf(buf, "%d", &val) != 1 || val <= 0)
4807 return -EINVAL;
4809 workqueue_set_max_active(wq, val);
4810 return count;
4812 static DEVICE_ATTR_RW(max_active);
4814 static struct attribute *wq_sysfs_attrs[] = {
4815 &dev_attr_per_cpu.attr,
4816 &dev_attr_max_active.attr,
4817 NULL,
4819 ATTRIBUTE_GROUPS(wq_sysfs);
4821 static ssize_t wq_pool_ids_show(struct device *dev,
4822 struct device_attribute *attr, char *buf)
4824 struct workqueue_struct *wq = dev_to_wq(dev);
4825 const char *delim = "";
4826 int node, written = 0;
4828 rcu_read_lock_sched();
4829 for_each_node(node) {
4830 written += scnprintf(buf + written, PAGE_SIZE - written,
4831 "%s%d:%d", delim, node,
4832 unbound_pwq_by_node(wq, node)->pool->id);
4833 delim = " ";
4835 written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
4836 rcu_read_unlock_sched();
4838 return written;
4841 static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
4842 char *buf)
4844 struct workqueue_struct *wq = dev_to_wq(dev);
4845 int written;
4847 mutex_lock(&wq->mutex);
4848 written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
4849 mutex_unlock(&wq->mutex);
4851 return written;
4854 /* prepare workqueue_attrs for sysfs store operations */
4855 static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
4857 struct workqueue_attrs *attrs;
4859 attrs = alloc_workqueue_attrs(GFP_KERNEL);
4860 if (!attrs)
4861 return NULL;
4863 mutex_lock(&wq->mutex);
4864 copy_workqueue_attrs(attrs, wq->unbound_attrs);
4865 mutex_unlock(&wq->mutex);
4866 return attrs;
4869 static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
4870 const char *buf, size_t count)
4872 struct workqueue_struct *wq = dev_to_wq(dev);
4873 struct workqueue_attrs *attrs;
4874 int ret;
4876 attrs = wq_sysfs_prep_attrs(wq);
4877 if (!attrs)
4878 return -ENOMEM;
4880 if (sscanf(buf, "%d", &attrs->nice) == 1 &&
4881 attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
4882 ret = apply_workqueue_attrs(wq, attrs);
4883 else
4884 ret = -EINVAL;
4886 free_workqueue_attrs(attrs);
4887 return ret ?: count;
4890 static ssize_t wq_cpumask_show(struct device *dev,
4891 struct device_attribute *attr, char *buf)
4893 struct workqueue_struct *wq = dev_to_wq(dev);
4894 int written;
4896 mutex_lock(&wq->mutex);
4897 written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
4898 cpumask_pr_args(wq->unbound_attrs->cpumask));
4899 mutex_unlock(&wq->mutex);
4900 return written;
4903 static ssize_t wq_cpumask_store(struct device *dev,
4904 struct device_attribute *attr,
4905 const char *buf, size_t count)
4907 struct workqueue_struct *wq = dev_to_wq(dev);
4908 struct workqueue_attrs *attrs;
4909 int ret;
4911 attrs = wq_sysfs_prep_attrs(wq);
4912 if (!attrs)
4913 return -ENOMEM;
4915 ret = cpumask_parse(buf, attrs->cpumask);
4916 if (!ret)
4917 ret = apply_workqueue_attrs(wq, attrs);
4919 free_workqueue_attrs(attrs);
4920 return ret ?: count;
4923 static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
4924 char *buf)
4926 struct workqueue_struct *wq = dev_to_wq(dev);
4927 int written;
4929 mutex_lock(&wq->mutex);
4930 written = scnprintf(buf, PAGE_SIZE, "%d\n",
4931 !wq->unbound_attrs->no_numa);
4932 mutex_unlock(&wq->mutex);
4934 return written;
4937 static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
4938 const char *buf, size_t count)
4940 struct workqueue_struct *wq = dev_to_wq(dev);
4941 struct workqueue_attrs *attrs;
4942 int v, ret;
4944 attrs = wq_sysfs_prep_attrs(wq);
4945 if (!attrs)
4946 return -ENOMEM;
4948 ret = -EINVAL;
4949 if (sscanf(buf, "%d", &v) == 1) {
4950 attrs->no_numa = !v;
4951 ret = apply_workqueue_attrs(wq, attrs);
4954 free_workqueue_attrs(attrs);
4955 return ret ?: count;
4958 static struct device_attribute wq_sysfs_unbound_attrs[] = {
4959 __ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
4960 __ATTR(nice, 0644, wq_nice_show, wq_nice_store),
4961 __ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
4962 __ATTR(numa, 0644, wq_numa_show, wq_numa_store),
4963 __ATTR_NULL,
4966 static struct bus_type wq_subsys = {
4967 .name = "workqueue",
4968 .dev_groups = wq_sysfs_groups,
4971 static int __init wq_sysfs_init(void)
4973 return subsys_virtual_register(&wq_subsys, NULL);
4975 core_initcall(wq_sysfs_init);
4977 static void wq_device_release(struct device *dev)
4979 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
4981 kfree(wq_dev);
4985 * workqueue_sysfs_register - make a workqueue visible in sysfs
4986 * @wq: the workqueue to register
4988 * Expose @wq in sysfs under /sys/bus/workqueue/devices.
4989 * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
4990 * which is the preferred method.
4992 * Workqueue user should use this function directly iff it wants to apply
4993 * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
4994 * apply_workqueue_attrs() may race against userland updating the
4995 * attributes.
4997 * Return: 0 on success, -errno on failure.
4999 int workqueue_sysfs_register(struct workqueue_struct *wq)
5001 struct wq_device *wq_dev;
5002 int ret;
5005 * Adjusting max_active or creating new pwqs by applyting
5006 * attributes breaks ordering guarantee. Disallow exposing ordered
5007 * workqueues.
5009 if (WARN_ON(wq->flags & __WQ_ORDERED))
5010 return -EINVAL;
5012 wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
5013 if (!wq_dev)
5014 return -ENOMEM;
5016 wq_dev->wq = wq;
5017 wq_dev->dev.bus = &wq_subsys;
5018 wq_dev->dev.init_name = wq->name;
5019 wq_dev->dev.release = wq_device_release;
5022 * unbound_attrs are created separately. Suppress uevent until
5023 * everything is ready.
5025 dev_set_uevent_suppress(&wq_dev->dev, true);
5027 ret = device_register(&wq_dev->dev);
5028 if (ret) {
5029 kfree(wq_dev);
5030 wq->wq_dev = NULL;
5031 return ret;
5034 if (wq->flags & WQ_UNBOUND) {
5035 struct device_attribute *attr;
5037 for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
5038 ret = device_create_file(&wq_dev->dev, attr);
5039 if (ret) {
5040 device_unregister(&wq_dev->dev);
5041 wq->wq_dev = NULL;
5042 return ret;
5047 dev_set_uevent_suppress(&wq_dev->dev, false);
5048 kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
5049 return 0;
5053 * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
5054 * @wq: the workqueue to unregister
5056 * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
5058 static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
5060 struct wq_device *wq_dev = wq->wq_dev;
5062 if (!wq->wq_dev)
5063 return;
5065 wq->wq_dev = NULL;
5066 device_unregister(&wq_dev->dev);
5068 #else /* CONFIG_SYSFS */
5069 static void workqueue_sysfs_unregister(struct workqueue_struct *wq) { }
5070 #endif /* CONFIG_SYSFS */
5072 static void __init wq_numa_init(void)
5074 cpumask_var_t *tbl;
5075 int node, cpu;
5077 if (num_possible_nodes() <= 1)
5078 return;
5080 if (wq_disable_numa) {
5081 pr_info("workqueue: NUMA affinity support disabled\n");
5082 return;
5085 wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs(GFP_KERNEL);
5086 BUG_ON(!wq_update_unbound_numa_attrs_buf);
5089 * We want masks of possible CPUs of each node which isn't readily
5090 * available. Build one from cpu_to_node() which should have been
5091 * fully initialized by now.
5093 tbl = kzalloc(nr_node_ids * sizeof(tbl[0]), GFP_KERNEL);
5094 BUG_ON(!tbl);
5096 for_each_node(node)
5097 BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
5098 node_online(node) ? node : NUMA_NO_NODE));
5100 for_each_possible_cpu(cpu) {
5101 node = cpu_to_node(cpu);
5102 if (WARN_ON(node == NUMA_NO_NODE)) {
5103 pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
5104 /* happens iff arch is bonkers, let's just proceed */
5105 return;
5107 cpumask_set_cpu(cpu, tbl[node]);
5110 wq_numa_possible_cpumask = tbl;
5111 wq_numa_enabled = true;
5114 static int __init init_workqueues(void)
5116 int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
5117 int i, cpu;
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_worker(pool));
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);