1 // SPDX-License-Identifier: GPL-2.0-only
3 * kernel/workqueue.c - generic async execution with shared worker pool
5 * Copyright (C) 2002 Ingo Molnar
7 * Derived from the taskqueue/keventd code by:
13 * Made to use alloc_percpu by Christoph Lameter.
15 * Copyright (C) 2010 SUSE Linux Products GmbH
18 * This is the generic async execution mechanism. Work items as are
19 * executed in process context. The worker pool is shared and
20 * automatically managed. There are two worker pools for each CPU (one for
21 * normal work items and the other for high priority ones) and some extra
22 * pools for workqueues which are not bound to any specific CPU - the
23 * number of these backing pools is dynamic.
25 * Please read Documentation/core-api/workqueue.rst for details.
28 #include <linux/export.h>
29 #include <linux/kernel.h>
30 #include <linux/sched.h>
31 #include <linux/init.h>
32 #include <linux/signal.h>
33 #include <linux/completion.h>
34 #include <linux/workqueue.h>
35 #include <linux/slab.h>
36 #include <linux/cpu.h>
37 #include <linux/notifier.h>
38 #include <linux/kthread.h>
39 #include <linux/hardirq.h>
40 #include <linux/mempolicy.h>
41 #include <linux/freezer.h>
42 #include <linux/debug_locks.h>
43 #include <linux/lockdep.h>
44 #include <linux/idr.h>
45 #include <linux/jhash.h>
46 #include <linux/hashtable.h>
47 #include <linux/rculist.h>
48 #include <linux/nodemask.h>
49 #include <linux/moduleparam.h>
50 #include <linux/uaccess.h>
51 #include <linux/sched/isolation.h>
52 #include <linux/sched/debug.h>
53 #include <linux/nmi.h>
54 #include <linux/kvm_para.h>
56 #include "workqueue_internal.h"
62 * A bound pool is either associated or disassociated with its CPU.
63 * While associated (!DISASSOCIATED), all workers are bound to the
64 * CPU and none has %WORKER_UNBOUND set and concurrency management
67 * While DISASSOCIATED, the cpu may be offline and all workers have
68 * %WORKER_UNBOUND set and concurrency management disabled, and may
69 * be executing on any CPU. The pool behaves as an unbound one.
71 * Note that DISASSOCIATED should be flipped only while holding
72 * wq_pool_attach_mutex to avoid changing binding state while
73 * worker_attach_to_pool() is in progress.
75 POOL_MANAGER_ACTIVE = 1 << 0, /* being managed */
76 POOL_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
79 WORKER_DIE = 1 << 1, /* die die die */
80 WORKER_IDLE = 1 << 2, /* is idle */
81 WORKER_PREP = 1 << 3, /* preparing to run works */
82 WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
83 WORKER_UNBOUND = 1 << 7, /* worker is unbound */
84 WORKER_REBOUND = 1 << 8, /* worker was rebound */
86 WORKER_NOT_RUNNING = WORKER_PREP | WORKER_CPU_INTENSIVE |
87 WORKER_UNBOUND | WORKER_REBOUND,
89 NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */
91 UNBOUND_POOL_HASH_ORDER = 6, /* hashed by pool->attrs */
92 BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
94 MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
95 IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
97 MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
98 /* call for help after 10ms
100 MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
101 CREATE_COOLDOWN = HZ, /* time to breath after fail */
104 * Rescue workers are used only on emergencies and shared by
105 * all cpus. Give MIN_NICE.
107 RESCUER_NICE_LEVEL = MIN_NICE,
108 HIGHPRI_NICE_LEVEL = MIN_NICE,
114 * Structure fields follow one of the following exclusion rules.
116 * I: Modifiable by initialization/destruction paths and read-only for
119 * P: Preemption protected. Disabling preemption is enough and should
120 * only be modified and accessed from the local cpu.
122 * L: pool->lock protected. Access with pool->lock held.
124 * X: During normal operation, modification requires pool->lock and should
125 * be done only from local cpu. Either disabling preemption on local
126 * cpu or grabbing pool->lock is enough for read access. If
127 * POOL_DISASSOCIATED is set, it's identical to L.
129 * K: Only modified by worker while holding pool->lock. Can be safely read by
130 * self, while holding pool->lock or from IRQ context if %current is the
133 * S: Only modified by worker self.
135 * A: wq_pool_attach_mutex protected.
137 * PL: wq_pool_mutex protected.
139 * PR: wq_pool_mutex protected for writes. RCU protected for reads.
141 * PW: wq_pool_mutex and wq->mutex protected for writes. Either for reads.
143 * PWR: wq_pool_mutex and wq->mutex protected for writes. Either or
146 * WQ: wq->mutex protected.
148 * WR: wq->mutex protected for writes. RCU protected for reads.
150 * MD: wq_mayday_lock protected.
152 * WD: Used internally by the watchdog.
155 /* struct worker is defined in workqueue_internal.h */
158 raw_spinlock_t lock; /* the pool lock */
159 int cpu; /* I: the associated cpu */
160 int node; /* I: the associated node ID */
161 int id; /* I: pool ID */
162 unsigned int flags; /* X: flags */
164 unsigned long watchdog_ts; /* L: watchdog timestamp */
165 bool cpu_stall; /* WD: stalled cpu bound pool */
168 * The counter is incremented in a process context on the associated CPU
169 * w/ preemption disabled, and decremented or reset in the same context
170 * but w/ pool->lock held. The readers grab pool->lock and are
171 * guaranteed to see if the counter reached zero.
175 struct list_head worklist; /* L: list of pending works */
177 int nr_workers; /* L: total number of workers */
178 int nr_idle; /* L: currently idle workers */
180 struct list_head idle_list; /* L: list of idle workers */
181 struct timer_list idle_timer; /* L: worker idle timeout */
182 struct work_struct idle_cull_work; /* L: worker idle cleanup */
184 struct timer_list mayday_timer; /* L: SOS timer for workers */
186 /* a workers is either on busy_hash or idle_list, or the manager */
187 DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
188 /* L: hash of busy workers */
190 struct worker *manager; /* L: purely informational */
191 struct list_head workers; /* A: attached workers */
192 struct list_head dying_workers; /* A: workers about to die */
193 struct completion *detach_completion; /* all workers detached */
195 struct ida worker_ida; /* worker IDs for task name */
197 struct workqueue_attrs *attrs; /* I: worker attributes */
198 struct hlist_node hash_node; /* PL: unbound_pool_hash node */
199 int refcnt; /* PL: refcnt for unbound pools */
202 * Destruction of pool is RCU protected to allow dereferences
203 * from get_work_pool().
209 * Per-pool_workqueue statistics. These can be monitored using
210 * tools/workqueue/wq_monitor.py.
212 enum pool_workqueue_stats {
213 PWQ_STAT_STARTED, /* work items started execution */
214 PWQ_STAT_COMPLETED, /* work items completed execution */
215 PWQ_STAT_CPU_TIME, /* total CPU time consumed */
216 PWQ_STAT_CPU_INTENSIVE, /* wq_cpu_intensive_thresh_us violations */
217 PWQ_STAT_CM_WAKEUP, /* concurrency-management worker wakeups */
218 PWQ_STAT_MAYDAY, /* maydays to rescuer */
219 PWQ_STAT_RESCUED, /* linked work items executed by rescuer */
225 * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
226 * of work_struct->data are used for flags and the remaining high bits
227 * point to the pwq; thus, pwqs need to be aligned at two's power of the
228 * number of flag bits.
230 struct pool_workqueue {
231 struct worker_pool *pool; /* I: the associated pool */
232 struct workqueue_struct *wq; /* I: the owning workqueue */
233 int work_color; /* L: current color */
234 int flush_color; /* L: flushing color */
235 int refcnt; /* L: reference count */
236 int nr_in_flight[WORK_NR_COLORS];
237 /* L: nr of in_flight works */
240 * nr_active management and WORK_STRUCT_INACTIVE:
242 * When pwq->nr_active >= max_active, new work item is queued to
243 * pwq->inactive_works instead of pool->worklist and marked with
244 * WORK_STRUCT_INACTIVE.
246 * All work items marked with WORK_STRUCT_INACTIVE do not participate
247 * in pwq->nr_active and all work items in pwq->inactive_works are
248 * marked with WORK_STRUCT_INACTIVE. But not all WORK_STRUCT_INACTIVE
249 * work items are in pwq->inactive_works. Some of them are ready to
250 * run in pool->worklist or worker->scheduled. Those work itmes are
251 * only struct wq_barrier which is used for flush_work() and should
252 * not participate in pwq->nr_active. For non-barrier work item, it
253 * is marked with WORK_STRUCT_INACTIVE iff it is in pwq->inactive_works.
255 int nr_active; /* L: nr of active works */
256 int max_active; /* L: max active works */
257 struct list_head inactive_works; /* L: inactive works */
258 struct list_head pwqs_node; /* WR: node on wq->pwqs */
259 struct list_head mayday_node; /* MD: node on wq->maydays */
261 u64 stats[PWQ_NR_STATS];
264 * Release of unbound pwq is punted to system_wq. See put_pwq()
265 * and pwq_unbound_release_workfn() for details. pool_workqueue
266 * itself is also RCU protected so that the first pwq can be
267 * determined without grabbing wq->mutex.
269 struct work_struct unbound_release_work;
271 } __aligned(1 << WORK_STRUCT_FLAG_BITS);
274 * Structure used to wait for workqueue flush.
277 struct list_head list; /* WQ: list of flushers */
278 int flush_color; /* WQ: flush color waiting for */
279 struct completion done; /* flush completion */
285 * The externally visible workqueue. It relays the issued work items to
286 * the appropriate worker_pool through its pool_workqueues.
288 struct workqueue_struct {
289 struct list_head pwqs; /* WR: all pwqs of this wq */
290 struct list_head list; /* PR: list of all workqueues */
292 struct mutex mutex; /* protects this wq */
293 int work_color; /* WQ: current work color */
294 int flush_color; /* WQ: current flush color */
295 atomic_t nr_pwqs_to_flush; /* flush in progress */
296 struct wq_flusher *first_flusher; /* WQ: first flusher */
297 struct list_head flusher_queue; /* WQ: flush waiters */
298 struct list_head flusher_overflow; /* WQ: flush overflow list */
300 struct list_head maydays; /* MD: pwqs requesting rescue */
301 struct worker *rescuer; /* MD: rescue worker */
303 int nr_drainers; /* WQ: drain in progress */
304 int saved_max_active; /* WQ: saved pwq max_active */
306 struct workqueue_attrs *unbound_attrs; /* PW: only for unbound wqs */
307 struct pool_workqueue *dfl_pwq; /* PW: only for unbound wqs */
310 struct wq_device *wq_dev; /* I: for sysfs interface */
312 #ifdef CONFIG_LOCKDEP
314 struct lock_class_key key;
315 struct lockdep_map lockdep_map;
317 char name[WQ_NAME_LEN]; /* I: workqueue name */
320 * Destruction of workqueue_struct is RCU protected to allow walking
321 * the workqueues list without grabbing wq_pool_mutex.
322 * This is used to dump all workqueues from sysrq.
326 /* hot fields used during command issue, aligned to cacheline */
327 unsigned int flags ____cacheline_aligned; /* WQ: WQ_* flags */
328 struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */
329 struct pool_workqueue __rcu *numa_pwq_tbl[]; /* PWR: unbound pwqs indexed by node */
332 static struct kmem_cache *pwq_cache;
334 static cpumask_var_t *wq_numa_possible_cpumask;
335 /* possible CPUs of each node */
338 * Per-cpu work items which run for longer than the following threshold are
339 * automatically considered CPU intensive and excluded from concurrency
340 * management to prevent them from noticeably delaying other per-cpu work items.
342 static unsigned long wq_cpu_intensive_thresh_us = 10000;
343 module_param_named(cpu_intensive_thresh_us, wq_cpu_intensive_thresh_us, ulong, 0644);
345 static bool wq_disable_numa;
346 module_param_named(disable_numa, wq_disable_numa, bool, 0444);
348 /* see the comment above the definition of WQ_POWER_EFFICIENT */
349 static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
350 module_param_named(power_efficient, wq_power_efficient, bool, 0444);
352 static bool wq_online; /* can kworkers be created yet? */
354 static bool wq_numa_enabled; /* unbound NUMA affinity enabled */
356 /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
357 static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf;
359 static DEFINE_MUTEX(wq_pool_mutex); /* protects pools and workqueues list */
360 static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
361 static DEFINE_RAW_SPINLOCK(wq_mayday_lock); /* protects wq->maydays list */
362 /* wait for manager to go away */
363 static struct rcuwait manager_wait = __RCUWAIT_INITIALIZER(manager_wait);
365 static LIST_HEAD(workqueues); /* PR: list of all workqueues */
366 static bool workqueue_freezing; /* PL: have wqs started freezing? */
368 /* PL&A: allowable cpus for unbound wqs and work items */
369 static cpumask_var_t wq_unbound_cpumask;
371 /* CPU where unbound work was last round robin scheduled from this CPU */
372 static DEFINE_PER_CPU(int, wq_rr_cpu_last);
375 * Local execution of unbound work items is no longer guaranteed. The
376 * following always forces round-robin CPU selection on unbound work items
377 * to uncover usages which depend on it.
379 #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
380 static bool wq_debug_force_rr_cpu = true;
382 static bool wq_debug_force_rr_cpu = false;
384 module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
386 /* the per-cpu worker pools */
387 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools);
389 static DEFINE_IDR(worker_pool_idr); /* PR: idr of all pools */
391 /* PL: hash of all unbound pools keyed by pool->attrs */
392 static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
394 /* I: attributes used when instantiating standard unbound pools on demand */
395 static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
397 /* I: attributes used when instantiating ordered pools on demand */
398 static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
400 struct workqueue_struct *system_wq __read_mostly;
401 EXPORT_SYMBOL(system_wq);
402 struct workqueue_struct *system_highpri_wq __read_mostly;
403 EXPORT_SYMBOL_GPL(system_highpri_wq);
404 struct workqueue_struct *system_long_wq __read_mostly;
405 EXPORT_SYMBOL_GPL(system_long_wq);
406 struct workqueue_struct *system_unbound_wq __read_mostly;
407 EXPORT_SYMBOL_GPL(system_unbound_wq);
408 struct workqueue_struct *system_freezable_wq __read_mostly;
409 EXPORT_SYMBOL_GPL(system_freezable_wq);
410 struct workqueue_struct *system_power_efficient_wq __read_mostly;
411 EXPORT_SYMBOL_GPL(system_power_efficient_wq);
412 struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
413 EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
415 static int worker_thread(void *__worker);
416 static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
417 static void show_pwq(struct pool_workqueue *pwq);
418 static void show_one_worker_pool(struct worker_pool *pool);
420 #define CREATE_TRACE_POINTS
421 #include <trace/events/workqueue.h>
423 #define assert_rcu_or_pool_mutex() \
424 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
425 !lockdep_is_held(&wq_pool_mutex), \
426 "RCU or wq_pool_mutex should be held")
428 #define assert_rcu_or_wq_mutex_or_pool_mutex(wq) \
429 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
430 !lockdep_is_held(&wq->mutex) && \
431 !lockdep_is_held(&wq_pool_mutex), \
432 "RCU, wq->mutex or wq_pool_mutex should be held")
434 #define for_each_cpu_worker_pool(pool, cpu) \
435 for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
436 (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
440 * for_each_pool - iterate through all worker_pools in the system
441 * @pool: iteration cursor
442 * @pi: integer used for iteration
444 * This must be called either with wq_pool_mutex held or RCU read
445 * locked. If the pool needs to be used beyond the locking in effect, the
446 * caller is responsible for guaranteeing that the pool stays online.
448 * The if/else clause exists only for the lockdep assertion and can be
451 #define for_each_pool(pool, pi) \
452 idr_for_each_entry(&worker_pool_idr, pool, pi) \
453 if (({ assert_rcu_or_pool_mutex(); false; })) { } \
457 * for_each_pool_worker - iterate through all workers of a worker_pool
458 * @worker: iteration cursor
459 * @pool: worker_pool to iterate workers of
461 * This must be called with wq_pool_attach_mutex.
463 * The if/else clause exists only for the lockdep assertion and can be
466 #define for_each_pool_worker(worker, pool) \
467 list_for_each_entry((worker), &(pool)->workers, node) \
468 if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
472 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
473 * @pwq: iteration cursor
474 * @wq: the target workqueue
476 * This must be called either with wq->mutex held or RCU read locked.
477 * If the pwq needs to be used beyond the locking in effect, the caller is
478 * responsible for guaranteeing that the pwq stays online.
480 * The if/else clause exists only for the lockdep assertion and can be
483 #define for_each_pwq(pwq, wq) \
484 list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node, \
485 lockdep_is_held(&(wq->mutex)))
487 #ifdef CONFIG_DEBUG_OBJECTS_WORK
489 static const struct debug_obj_descr work_debug_descr;
491 static void *work_debug_hint(void *addr)
493 return ((struct work_struct *) addr)->func;
496 static bool work_is_static_object(void *addr)
498 struct work_struct *work = addr;
500 return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
504 * fixup_init is called when:
505 * - an active object is initialized
507 static bool work_fixup_init(void *addr, enum debug_obj_state state)
509 struct work_struct *work = addr;
512 case ODEBUG_STATE_ACTIVE:
513 cancel_work_sync(work);
514 debug_object_init(work, &work_debug_descr);
522 * fixup_free is called when:
523 * - an active object is freed
525 static bool work_fixup_free(void *addr, enum debug_obj_state state)
527 struct work_struct *work = addr;
530 case ODEBUG_STATE_ACTIVE:
531 cancel_work_sync(work);
532 debug_object_free(work, &work_debug_descr);
539 static const struct debug_obj_descr work_debug_descr = {
540 .name = "work_struct",
541 .debug_hint = work_debug_hint,
542 .is_static_object = work_is_static_object,
543 .fixup_init = work_fixup_init,
544 .fixup_free = work_fixup_free,
547 static inline void debug_work_activate(struct work_struct *work)
549 debug_object_activate(work, &work_debug_descr);
552 static inline void debug_work_deactivate(struct work_struct *work)
554 debug_object_deactivate(work, &work_debug_descr);
557 void __init_work(struct work_struct *work, int onstack)
560 debug_object_init_on_stack(work, &work_debug_descr);
562 debug_object_init(work, &work_debug_descr);
564 EXPORT_SYMBOL_GPL(__init_work);
566 void destroy_work_on_stack(struct work_struct *work)
568 debug_object_free(work, &work_debug_descr);
570 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
572 void destroy_delayed_work_on_stack(struct delayed_work *work)
574 destroy_timer_on_stack(&work->timer);
575 debug_object_free(&work->work, &work_debug_descr);
577 EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
580 static inline void debug_work_activate(struct work_struct *work) { }
581 static inline void debug_work_deactivate(struct work_struct *work) { }
585 * worker_pool_assign_id - allocate ID and assign it to @pool
586 * @pool: the pool pointer of interest
588 * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
589 * successfully, -errno on failure.
591 static int worker_pool_assign_id(struct worker_pool *pool)
595 lockdep_assert_held(&wq_pool_mutex);
597 ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
607 * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
608 * @wq: the target workqueue
611 * This must be called with any of wq_pool_mutex, wq->mutex or RCU
613 * If the pwq needs to be used beyond the locking in effect, the caller is
614 * responsible for guaranteeing that the pwq stays online.
616 * Return: The unbound pool_workqueue for @node.
618 static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
621 assert_rcu_or_wq_mutex_or_pool_mutex(wq);
624 * XXX: @node can be NUMA_NO_NODE if CPU goes offline while a
625 * delayed item is pending. The plan is to keep CPU -> NODE
626 * mapping valid and stable across CPU on/offlines. Once that
627 * happens, this workaround can be removed.
629 if (unlikely(node == NUMA_NO_NODE))
632 return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
635 static unsigned int work_color_to_flags(int color)
637 return color << WORK_STRUCT_COLOR_SHIFT;
640 static int get_work_color(unsigned long work_data)
642 return (work_data >> WORK_STRUCT_COLOR_SHIFT) &
643 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
646 static int work_next_color(int color)
648 return (color + 1) % WORK_NR_COLORS;
652 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
653 * contain the pointer to the queued pwq. Once execution starts, the flag
654 * is cleared and the high bits contain OFFQ flags and pool ID.
656 * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
657 * and clear_work_data() can be used to set the pwq, pool or clear
658 * work->data. These functions should only be called while the work is
659 * owned - ie. while the PENDING bit is set.
661 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
662 * corresponding to a work. Pool is available once the work has been
663 * queued anywhere after initialization until it is sync canceled. pwq is
664 * available only while the work item is queued.
666 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
667 * canceled. While being canceled, a work item may have its PENDING set
668 * but stay off timer and worklist for arbitrarily long and nobody should
669 * try to steal the PENDING bit.
671 static inline void set_work_data(struct work_struct *work, unsigned long data,
674 WARN_ON_ONCE(!work_pending(work));
675 atomic_long_set(&work->data, data | flags | work_static(work));
678 static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
679 unsigned long extra_flags)
681 set_work_data(work, (unsigned long)pwq,
682 WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
685 static void set_work_pool_and_keep_pending(struct work_struct *work,
688 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
689 WORK_STRUCT_PENDING);
692 static void set_work_pool_and_clear_pending(struct work_struct *work,
696 * The following wmb is paired with the implied mb in
697 * test_and_set_bit(PENDING) and ensures all updates to @work made
698 * here are visible to and precede any updates by the next PENDING
702 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
704 * The following mb guarantees that previous clear of a PENDING bit
705 * will not be reordered with any speculative LOADS or STORES from
706 * work->current_func, which is executed afterwards. This possible
707 * reordering can lead to a missed execution on attempt to queue
708 * the same @work. E.g. consider this case:
711 * ---------------------------- --------------------------------
713 * 1 STORE event_indicated
714 * 2 queue_work_on() {
715 * 3 test_and_set_bit(PENDING)
716 * 4 } set_..._and_clear_pending() {
717 * 5 set_work_data() # clear bit
719 * 7 work->current_func() {
720 * 8 LOAD event_indicated
723 * Without an explicit full barrier speculative LOAD on line 8 can
724 * be executed before CPU#0 does STORE on line 1. If that happens,
725 * CPU#0 observes the PENDING bit is still set and new execution of
726 * a @work is not queued in a hope, that CPU#1 will eventually
727 * finish the queued @work. Meanwhile CPU#1 does not see
728 * event_indicated is set, because speculative LOAD was executed
729 * before actual STORE.
734 static void clear_work_data(struct work_struct *work)
736 smp_wmb(); /* see set_work_pool_and_clear_pending() */
737 set_work_data(work, WORK_STRUCT_NO_POOL, 0);
740 static inline struct pool_workqueue *work_struct_pwq(unsigned long data)
742 return (struct pool_workqueue *)(data & WORK_STRUCT_WQ_DATA_MASK);
745 static struct pool_workqueue *get_work_pwq(struct work_struct *work)
747 unsigned long data = atomic_long_read(&work->data);
749 if (data & WORK_STRUCT_PWQ)
750 return work_struct_pwq(data);
756 * get_work_pool - return the worker_pool a given work was associated with
757 * @work: the work item of interest
759 * Pools are created and destroyed under wq_pool_mutex, and allows read
760 * access under RCU read lock. As such, this function should be
761 * called under wq_pool_mutex or inside of a rcu_read_lock() region.
763 * All fields of the returned pool are accessible as long as the above
764 * mentioned locking is in effect. If the returned pool needs to be used
765 * beyond the critical section, the caller is responsible for ensuring the
766 * returned pool is and stays online.
768 * Return: The worker_pool @work was last associated with. %NULL if none.
770 static struct worker_pool *get_work_pool(struct work_struct *work)
772 unsigned long data = atomic_long_read(&work->data);
775 assert_rcu_or_pool_mutex();
777 if (data & WORK_STRUCT_PWQ)
778 return work_struct_pwq(data)->pool;
780 pool_id = data >> WORK_OFFQ_POOL_SHIFT;
781 if (pool_id == WORK_OFFQ_POOL_NONE)
784 return idr_find(&worker_pool_idr, pool_id);
788 * get_work_pool_id - return the worker pool ID a given work is associated with
789 * @work: the work item of interest
791 * Return: The worker_pool ID @work was last associated with.
792 * %WORK_OFFQ_POOL_NONE if none.
794 static int get_work_pool_id(struct work_struct *work)
796 unsigned long data = atomic_long_read(&work->data);
798 if (data & WORK_STRUCT_PWQ)
799 return work_struct_pwq(data)->pool->id;
801 return data >> WORK_OFFQ_POOL_SHIFT;
804 static void mark_work_canceling(struct work_struct *work)
806 unsigned long pool_id = get_work_pool_id(work);
808 pool_id <<= WORK_OFFQ_POOL_SHIFT;
809 set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
812 static bool work_is_canceling(struct work_struct *work)
814 unsigned long data = atomic_long_read(&work->data);
816 return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
820 * Policy functions. These define the policies on how the global worker
821 * pools are managed. Unless noted otherwise, these functions assume that
822 * they're being called with pool->lock held.
825 static bool __need_more_worker(struct worker_pool *pool)
827 return !pool->nr_running;
831 * Need to wake up a worker? Called from anything but currently
834 * Note that, because unbound workers never contribute to nr_running, this
835 * function will always return %true for unbound pools as long as the
836 * worklist isn't empty.
838 static bool need_more_worker(struct worker_pool *pool)
840 return !list_empty(&pool->worklist) && __need_more_worker(pool);
843 /* Can I start working? Called from busy but !running workers. */
844 static bool may_start_working(struct worker_pool *pool)
846 return pool->nr_idle;
849 /* Do I need to keep working? Called from currently running workers. */
850 static bool keep_working(struct worker_pool *pool)
852 return !list_empty(&pool->worklist) && (pool->nr_running <= 1);
855 /* Do we need a new worker? Called from manager. */
856 static bool need_to_create_worker(struct worker_pool *pool)
858 return need_more_worker(pool) && !may_start_working(pool);
861 /* Do we have too many workers and should some go away? */
862 static bool too_many_workers(struct worker_pool *pool)
864 bool managing = pool->flags & POOL_MANAGER_ACTIVE;
865 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
866 int nr_busy = pool->nr_workers - nr_idle;
868 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
875 /* Return the first idle worker. Called with pool->lock held. */
876 static struct worker *first_idle_worker(struct worker_pool *pool)
878 if (unlikely(list_empty(&pool->idle_list)))
881 return list_first_entry(&pool->idle_list, struct worker, entry);
885 * wake_up_worker - wake up an idle worker
886 * @pool: worker pool to wake worker from
888 * Wake up the first idle worker of @pool.
891 * raw_spin_lock_irq(pool->lock).
893 static void wake_up_worker(struct worker_pool *pool)
895 struct worker *worker = first_idle_worker(pool);
898 wake_up_process(worker->task);
902 * worker_set_flags - set worker flags and adjust nr_running accordingly
904 * @flags: flags to set
906 * Set @flags in @worker->flags and adjust nr_running accordingly.
909 * raw_spin_lock_irq(pool->lock)
911 static inline void worker_set_flags(struct worker *worker, unsigned int flags)
913 struct worker_pool *pool = worker->pool;
915 WARN_ON_ONCE(worker->task != current);
917 /* If transitioning into NOT_RUNNING, adjust nr_running. */
918 if ((flags & WORKER_NOT_RUNNING) &&
919 !(worker->flags & WORKER_NOT_RUNNING)) {
923 worker->flags |= flags;
927 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
929 * @flags: flags to clear
931 * Clear @flags in @worker->flags and adjust nr_running accordingly.
934 * raw_spin_lock_irq(pool->lock)
936 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
938 struct worker_pool *pool = worker->pool;
939 unsigned int oflags = worker->flags;
941 WARN_ON_ONCE(worker->task != current);
943 worker->flags &= ~flags;
946 * If transitioning out of NOT_RUNNING, increment nr_running. Note
947 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
948 * of multiple flags, not a single flag.
950 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
951 if (!(worker->flags & WORKER_NOT_RUNNING))
955 #ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
958 * Concurrency-managed per-cpu work items that hog CPU for longer than
959 * wq_cpu_intensive_thresh_us trigger the automatic CPU_INTENSIVE mechanism,
960 * which prevents them from stalling other concurrency-managed work items. If a
961 * work function keeps triggering this mechanism, it's likely that the work item
962 * should be using an unbound workqueue instead.
964 * wq_cpu_intensive_report() tracks work functions which trigger such conditions
965 * and report them so that they can be examined and converted to use unbound
966 * workqueues as appropriate. To avoid flooding the console, each violating work
967 * function is tracked and reported with exponential backoff.
969 #define WCI_MAX_ENTS 128
974 struct hlist_node hash_node;
977 static struct wci_ent wci_ents[WCI_MAX_ENTS];
978 static int wci_nr_ents;
979 static DEFINE_RAW_SPINLOCK(wci_lock);
980 static DEFINE_HASHTABLE(wci_hash, ilog2(WCI_MAX_ENTS));
982 static struct wci_ent *wci_find_ent(work_func_t func)
986 hash_for_each_possible_rcu(wci_hash, ent, hash_node,
987 (unsigned long)func) {
988 if (ent->func == func)
994 static void wq_cpu_intensive_report(work_func_t func)
999 ent = wci_find_ent(func);
1004 * Start reporting from the fourth time and back off
1007 cnt = atomic64_inc_return_relaxed(&ent->cnt);
1008 if (cnt >= 4 && is_power_of_2(cnt))
1009 printk_deferred(KERN_WARNING "workqueue: %ps hogged CPU for >%luus %llu times, consider switching to WQ_UNBOUND\n",
1010 ent->func, wq_cpu_intensive_thresh_us,
1011 atomic64_read(&ent->cnt));
1016 * @func is a new violation. Allocate a new entry for it. If wcn_ents[]
1017 * is exhausted, something went really wrong and we probably made enough
1020 if (wci_nr_ents >= WCI_MAX_ENTS)
1023 raw_spin_lock(&wci_lock);
1025 if (wci_nr_ents >= WCI_MAX_ENTS) {
1026 raw_spin_unlock(&wci_lock);
1030 if (wci_find_ent(func)) {
1031 raw_spin_unlock(&wci_lock);
1035 ent = &wci_ents[wci_nr_ents++];
1037 atomic64_set(&ent->cnt, 1);
1038 hash_add_rcu(wci_hash, &ent->hash_node, (unsigned long)func);
1040 raw_spin_unlock(&wci_lock);
1043 #else /* CONFIG_WQ_CPU_INTENSIVE_REPORT */
1044 static void wq_cpu_intensive_report(work_func_t func) {}
1045 #endif /* CONFIG_WQ_CPU_INTENSIVE_REPORT */
1048 * wq_worker_running - a worker is running again
1049 * @task: task waking up
1051 * This function is called when a worker returns from schedule()
1053 void wq_worker_running(struct task_struct *task)
1055 struct worker *worker = kthread_data(task);
1057 if (!READ_ONCE(worker->sleeping))
1061 * If preempted by unbind_workers() between the WORKER_NOT_RUNNING check
1062 * and the nr_running increment below, we may ruin the nr_running reset
1063 * and leave with an unexpected pool->nr_running == 1 on the newly unbound
1064 * pool. Protect against such race.
1067 if (!(worker->flags & WORKER_NOT_RUNNING))
1068 worker->pool->nr_running++;
1072 * CPU intensive auto-detection cares about how long a work item hogged
1073 * CPU without sleeping. Reset the starting timestamp on wakeup.
1075 worker->current_at = worker->task->se.sum_exec_runtime;
1077 WRITE_ONCE(worker->sleeping, 0);
1081 * wq_worker_sleeping - a worker is going to sleep
1082 * @task: task going to sleep
1084 * This function is called from schedule() when a busy worker is
1087 void wq_worker_sleeping(struct task_struct *task)
1089 struct worker *worker = kthread_data(task);
1090 struct worker_pool *pool;
1093 * Rescuers, which may not have all the fields set up like normal
1094 * workers, also reach here, let's not access anything before
1095 * checking NOT_RUNNING.
1097 if (worker->flags & WORKER_NOT_RUNNING)
1100 pool = worker->pool;
1102 /* Return if preempted before wq_worker_running() was reached */
1103 if (READ_ONCE(worker->sleeping))
1106 WRITE_ONCE(worker->sleeping, 1);
1107 raw_spin_lock_irq(&pool->lock);
1110 * Recheck in case unbind_workers() preempted us. We don't
1111 * want to decrement nr_running after the worker is unbound
1112 * and nr_running has been reset.
1114 if (worker->flags & WORKER_NOT_RUNNING) {
1115 raw_spin_unlock_irq(&pool->lock);
1120 if (need_more_worker(pool)) {
1121 worker->current_pwq->stats[PWQ_STAT_CM_WAKEUP]++;
1122 wake_up_worker(pool);
1124 raw_spin_unlock_irq(&pool->lock);
1128 * wq_worker_tick - a scheduler tick occurred while a kworker is running
1129 * @task: task currently running
1131 * Called from scheduler_tick(). We're in the IRQ context and the current
1132 * worker's fields which follow the 'K' locking rule can be accessed safely.
1134 void wq_worker_tick(struct task_struct *task)
1136 struct worker *worker = kthread_data(task);
1137 struct pool_workqueue *pwq = worker->current_pwq;
1138 struct worker_pool *pool = worker->pool;
1143 pwq->stats[PWQ_STAT_CPU_TIME] += TICK_USEC;
1145 if (!wq_cpu_intensive_thresh_us)
1149 * If the current worker is concurrency managed and hogged the CPU for
1150 * longer than wq_cpu_intensive_thresh_us, it's automatically marked
1151 * CPU_INTENSIVE to avoid stalling other concurrency-managed work items.
1153 * Set @worker->sleeping means that @worker is in the process of
1154 * switching out voluntarily and won't be contributing to
1155 * @pool->nr_running until it wakes up. As wq_worker_sleeping() also
1156 * decrements ->nr_running, setting CPU_INTENSIVE here can lead to
1157 * double decrements. The task is releasing the CPU anyway. Let's skip.
1158 * We probably want to make this prettier in the future.
1160 if ((worker->flags & WORKER_NOT_RUNNING) || READ_ONCE(worker->sleeping) ||
1161 worker->task->se.sum_exec_runtime - worker->current_at <
1162 wq_cpu_intensive_thresh_us * NSEC_PER_USEC)
1165 raw_spin_lock(&pool->lock);
1167 worker_set_flags(worker, WORKER_CPU_INTENSIVE);
1168 wq_cpu_intensive_report(worker->current_func);
1169 pwq->stats[PWQ_STAT_CPU_INTENSIVE]++;
1171 if (need_more_worker(pool)) {
1172 pwq->stats[PWQ_STAT_CM_WAKEUP]++;
1173 wake_up_worker(pool);
1176 raw_spin_unlock(&pool->lock);
1180 * wq_worker_last_func - retrieve worker's last work function
1181 * @task: Task to retrieve last work function of.
1183 * Determine the last function a worker executed. This is called from
1184 * the scheduler to get a worker's last known identity.
1187 * raw_spin_lock_irq(rq->lock)
1189 * This function is called during schedule() when a kworker is going
1190 * to sleep. It's used by psi to identify aggregation workers during
1191 * dequeuing, to allow periodic aggregation to shut-off when that
1192 * worker is the last task in the system or cgroup to go to sleep.
1194 * As this function doesn't involve any workqueue-related locking, it
1195 * only returns stable values when called from inside the scheduler's
1196 * queuing and dequeuing paths, when @task, which must be a kworker,
1197 * is guaranteed to not be processing any works.
1200 * The last work function %current executed as a worker, NULL if it
1201 * hasn't executed any work yet.
1203 work_func_t wq_worker_last_func(struct task_struct *task)
1205 struct worker *worker = kthread_data(task);
1207 return worker->last_func;
1211 * find_worker_executing_work - find worker which is executing a work
1212 * @pool: pool of interest
1213 * @work: work to find worker for
1215 * Find a worker which is executing @work on @pool by searching
1216 * @pool->busy_hash which is keyed by the address of @work. For a worker
1217 * to match, its current execution should match the address of @work and
1218 * its work function. This is to avoid unwanted dependency between
1219 * unrelated work executions through a work item being recycled while still
1222 * This is a bit tricky. A work item may be freed once its execution
1223 * starts and nothing prevents the freed area from being recycled for
1224 * another work item. If the same work item address ends up being reused
1225 * before the original execution finishes, workqueue will identify the
1226 * recycled work item as currently executing and make it wait until the
1227 * current execution finishes, introducing an unwanted dependency.
1229 * This function checks the work item address and work function to avoid
1230 * false positives. Note that this isn't complete as one may construct a
1231 * work function which can introduce dependency onto itself through a
1232 * recycled work item. Well, if somebody wants to shoot oneself in the
1233 * foot that badly, there's only so much we can do, and if such deadlock
1234 * actually occurs, it should be easy to locate the culprit work function.
1237 * raw_spin_lock_irq(pool->lock).
1240 * Pointer to worker which is executing @work if found, %NULL
1243 static struct worker *find_worker_executing_work(struct worker_pool *pool,
1244 struct work_struct *work)
1246 struct worker *worker;
1248 hash_for_each_possible(pool->busy_hash, worker, hentry,
1249 (unsigned long)work)
1250 if (worker->current_work == work &&
1251 worker->current_func == work->func)
1258 * move_linked_works - move linked works to a list
1259 * @work: start of series of works to be scheduled
1260 * @head: target list to append @work to
1261 * @nextp: out parameter for nested worklist walking
1263 * Schedule linked works starting from @work to @head. Work series to
1264 * be scheduled starts at @work and includes any consecutive work with
1265 * WORK_STRUCT_LINKED set in its predecessor.
1267 * If @nextp is not NULL, it's updated to point to the next work of
1268 * the last scheduled work. This allows move_linked_works() to be
1269 * nested inside outer list_for_each_entry_safe().
1272 * raw_spin_lock_irq(pool->lock).
1274 static void move_linked_works(struct work_struct *work, struct list_head *head,
1275 struct work_struct **nextp)
1277 struct work_struct *n;
1280 * Linked worklist will always end before the end of the list,
1281 * use NULL for list head.
1283 list_for_each_entry_safe_from(work, n, NULL, entry) {
1284 list_move_tail(&work->entry, head);
1285 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1290 * If we're already inside safe list traversal and have moved
1291 * multiple works to the scheduled queue, the next position
1292 * needs to be updated.
1299 * get_pwq - get an extra reference on the specified pool_workqueue
1300 * @pwq: pool_workqueue to get
1302 * Obtain an extra reference on @pwq. The caller should guarantee that
1303 * @pwq has positive refcnt and be holding the matching pool->lock.
1305 static void get_pwq(struct pool_workqueue *pwq)
1307 lockdep_assert_held(&pwq->pool->lock);
1308 WARN_ON_ONCE(pwq->refcnt <= 0);
1313 * put_pwq - put a pool_workqueue reference
1314 * @pwq: pool_workqueue to put
1316 * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
1317 * destruction. The caller should be holding the matching pool->lock.
1319 static void put_pwq(struct pool_workqueue *pwq)
1321 lockdep_assert_held(&pwq->pool->lock);
1322 if (likely(--pwq->refcnt))
1324 if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
1327 * @pwq can't be released under pool->lock, bounce to
1328 * pwq_unbound_release_workfn(). This never recurses on the same
1329 * pool->lock as this path is taken only for unbound workqueues and
1330 * the release work item is scheduled on a per-cpu workqueue. To
1331 * avoid lockdep warning, unbound pool->locks are given lockdep
1332 * subclass of 1 in get_unbound_pool().
1334 schedule_work(&pwq->unbound_release_work);
1338 * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1339 * @pwq: pool_workqueue to put (can be %NULL)
1341 * put_pwq() with locking. This function also allows %NULL @pwq.
1343 static void put_pwq_unlocked(struct pool_workqueue *pwq)
1347 * As both pwqs and pools are RCU protected, the
1348 * following lock operations are safe.
1350 raw_spin_lock_irq(&pwq->pool->lock);
1352 raw_spin_unlock_irq(&pwq->pool->lock);
1356 static void pwq_activate_inactive_work(struct work_struct *work)
1358 struct pool_workqueue *pwq = get_work_pwq(work);
1360 trace_workqueue_activate_work(work);
1361 if (list_empty(&pwq->pool->worklist))
1362 pwq->pool->watchdog_ts = jiffies;
1363 move_linked_works(work, &pwq->pool->worklist, NULL);
1364 __clear_bit(WORK_STRUCT_INACTIVE_BIT, work_data_bits(work));
1368 static void pwq_activate_first_inactive(struct pool_workqueue *pwq)
1370 struct work_struct *work = list_first_entry(&pwq->inactive_works,
1371 struct work_struct, entry);
1373 pwq_activate_inactive_work(work);
1377 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1378 * @pwq: pwq of interest
1379 * @work_data: work_data of work which left the queue
1381 * A work either has completed or is removed from pending queue,
1382 * decrement nr_in_flight of its pwq and handle workqueue flushing.
1385 * raw_spin_lock_irq(pool->lock).
1387 static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data)
1389 int color = get_work_color(work_data);
1391 if (!(work_data & WORK_STRUCT_INACTIVE)) {
1393 if (!list_empty(&pwq->inactive_works)) {
1394 /* one down, submit an inactive one */
1395 if (pwq->nr_active < pwq->max_active)
1396 pwq_activate_first_inactive(pwq);
1400 pwq->nr_in_flight[color]--;
1402 /* is flush in progress and are we at the flushing tip? */
1403 if (likely(pwq->flush_color != color))
1406 /* are there still in-flight works? */
1407 if (pwq->nr_in_flight[color])
1410 /* this pwq is done, clear flush_color */
1411 pwq->flush_color = -1;
1414 * If this was the last pwq, wake up the first flusher. It
1415 * will handle the rest.
1417 if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1418 complete(&pwq->wq->first_flusher->done);
1424 * try_to_grab_pending - steal work item from worklist and disable irq
1425 * @work: work item to steal
1426 * @is_dwork: @work is a delayed_work
1427 * @flags: place to store irq state
1429 * Try to grab PENDING bit of @work. This function can handle @work in any
1430 * stable state - idle, on timer or on worklist.
1434 * ======== ================================================================
1435 * 1 if @work was pending and we successfully stole PENDING
1436 * 0 if @work was idle and we claimed PENDING
1437 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1438 * -ENOENT if someone else is canceling @work, this state may persist
1439 * for arbitrarily long
1440 * ======== ================================================================
1443 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1444 * interrupted while holding PENDING and @work off queue, irq must be
1445 * disabled on entry. This, combined with delayed_work->timer being
1446 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1448 * On successful return, >= 0, irq is disabled and the caller is
1449 * responsible for releasing it using local_irq_restore(*@flags).
1451 * This function is safe to call from any context including IRQ handler.
1453 static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1454 unsigned long *flags)
1456 struct worker_pool *pool;
1457 struct pool_workqueue *pwq;
1459 local_irq_save(*flags);
1461 /* try to steal the timer if it exists */
1463 struct delayed_work *dwork = to_delayed_work(work);
1466 * dwork->timer is irqsafe. If del_timer() fails, it's
1467 * guaranteed that the timer is not queued anywhere and not
1468 * running on the local CPU.
1470 if (likely(del_timer(&dwork->timer)))
1474 /* try to claim PENDING the normal way */
1475 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1480 * The queueing is in progress, or it is already queued. Try to
1481 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1483 pool = get_work_pool(work);
1487 raw_spin_lock(&pool->lock);
1489 * work->data is guaranteed to point to pwq only while the work
1490 * item is queued on pwq->wq, and both updating work->data to point
1491 * to pwq on queueing and to pool on dequeueing are done under
1492 * pwq->pool->lock. This in turn guarantees that, if work->data
1493 * points to pwq which is associated with a locked pool, the work
1494 * item is currently queued on that pool.
1496 pwq = get_work_pwq(work);
1497 if (pwq && pwq->pool == pool) {
1498 debug_work_deactivate(work);
1501 * A cancelable inactive work item must be in the
1502 * pwq->inactive_works since a queued barrier can't be
1503 * canceled (see the comments in insert_wq_barrier()).
1505 * An inactive work item cannot be grabbed directly because
1506 * it might have linked barrier work items which, if left
1507 * on the inactive_works list, will confuse pwq->nr_active
1508 * management later on and cause stall. Make sure the work
1509 * item is activated before grabbing.
1511 if (*work_data_bits(work) & WORK_STRUCT_INACTIVE)
1512 pwq_activate_inactive_work(work);
1514 list_del_init(&work->entry);
1515 pwq_dec_nr_in_flight(pwq, *work_data_bits(work));
1517 /* work->data points to pwq iff queued, point to pool */
1518 set_work_pool_and_keep_pending(work, pool->id);
1520 raw_spin_unlock(&pool->lock);
1524 raw_spin_unlock(&pool->lock);
1527 local_irq_restore(*flags);
1528 if (work_is_canceling(work))
1535 * insert_work - insert a work into a pool
1536 * @pwq: pwq @work belongs to
1537 * @work: work to insert
1538 * @head: insertion point
1539 * @extra_flags: extra WORK_STRUCT_* flags to set
1541 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
1542 * work_struct flags.
1545 * raw_spin_lock_irq(pool->lock).
1547 static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1548 struct list_head *head, unsigned int extra_flags)
1550 struct worker_pool *pool = pwq->pool;
1552 /* record the work call stack in order to print it in KASAN reports */
1553 kasan_record_aux_stack_noalloc(work);
1555 /* we own @work, set data and link */
1556 set_work_pwq(work, pwq, extra_flags);
1557 list_add_tail(&work->entry, head);
1560 if (__need_more_worker(pool))
1561 wake_up_worker(pool);
1565 * Test whether @work is being queued from another work executing on the
1568 static bool is_chained_work(struct workqueue_struct *wq)
1570 struct worker *worker;
1572 worker = current_wq_worker();
1574 * Return %true iff I'm a worker executing a work item on @wq. If
1575 * I'm @worker, it's safe to dereference it without locking.
1577 return worker && worker->current_pwq->wq == wq;
1581 * When queueing an unbound work item to a wq, prefer local CPU if allowed
1582 * by wq_unbound_cpumask. Otherwise, round robin among the allowed ones to
1583 * avoid perturbing sensitive tasks.
1585 static int wq_select_unbound_cpu(int cpu)
1589 if (likely(!wq_debug_force_rr_cpu)) {
1590 if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
1593 pr_warn_once("workqueue: round-robin CPU selection forced, expect performance impact\n");
1596 if (cpumask_empty(wq_unbound_cpumask))
1599 new_cpu = __this_cpu_read(wq_rr_cpu_last);
1600 new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
1601 if (unlikely(new_cpu >= nr_cpu_ids)) {
1602 new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
1603 if (unlikely(new_cpu >= nr_cpu_ids))
1606 __this_cpu_write(wq_rr_cpu_last, new_cpu);
1611 static void __queue_work(int cpu, struct workqueue_struct *wq,
1612 struct work_struct *work)
1614 struct pool_workqueue *pwq;
1615 struct worker_pool *last_pool;
1616 struct list_head *worklist;
1617 unsigned int work_flags;
1618 unsigned int req_cpu = cpu;
1621 * While a work item is PENDING && off queue, a task trying to
1622 * steal the PENDING will busy-loop waiting for it to either get
1623 * queued or lose PENDING. Grabbing PENDING and queueing should
1624 * happen with IRQ disabled.
1626 lockdep_assert_irqs_disabled();
1630 * For a draining wq, only works from the same workqueue are
1631 * allowed. The __WQ_DESTROYING helps to spot the issue that
1632 * queues a new work item to a wq after destroy_workqueue(wq).
1634 if (unlikely(wq->flags & (__WQ_DESTROYING | __WQ_DRAINING) &&
1635 WARN_ON_ONCE(!is_chained_work(wq))))
1639 /* pwq which will be used unless @work is executing elsewhere */
1640 if (wq->flags & WQ_UNBOUND) {
1641 if (req_cpu == WORK_CPU_UNBOUND)
1642 cpu = wq_select_unbound_cpu(raw_smp_processor_id());
1643 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1645 if (req_cpu == WORK_CPU_UNBOUND)
1646 cpu = raw_smp_processor_id();
1647 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1651 * If @work was previously on a different pool, it might still be
1652 * running there, in which case the work needs to be queued on that
1653 * pool to guarantee non-reentrancy.
1655 last_pool = get_work_pool(work);
1656 if (last_pool && last_pool != pwq->pool) {
1657 struct worker *worker;
1659 raw_spin_lock(&last_pool->lock);
1661 worker = find_worker_executing_work(last_pool, work);
1663 if (worker && worker->current_pwq->wq == wq) {
1664 pwq = worker->current_pwq;
1666 /* meh... not running there, queue here */
1667 raw_spin_unlock(&last_pool->lock);
1668 raw_spin_lock(&pwq->pool->lock);
1671 raw_spin_lock(&pwq->pool->lock);
1675 * pwq is determined and locked. For unbound pools, we could have
1676 * raced with pwq release and it could already be dead. If its
1677 * refcnt is zero, repeat pwq selection. Note that pwqs never die
1678 * without another pwq replacing it in the numa_pwq_tbl or while
1679 * work items are executing on it, so the retrying is guaranteed to
1680 * make forward-progress.
1682 if (unlikely(!pwq->refcnt)) {
1683 if (wq->flags & WQ_UNBOUND) {
1684 raw_spin_unlock(&pwq->pool->lock);
1689 WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
1693 /* pwq determined, queue */
1694 trace_workqueue_queue_work(req_cpu, pwq, work);
1696 if (WARN_ON(!list_empty(&work->entry)))
1699 pwq->nr_in_flight[pwq->work_color]++;
1700 work_flags = work_color_to_flags(pwq->work_color);
1702 if (likely(pwq->nr_active < pwq->max_active)) {
1703 trace_workqueue_activate_work(work);
1705 worklist = &pwq->pool->worklist;
1706 if (list_empty(worklist))
1707 pwq->pool->watchdog_ts = jiffies;
1709 work_flags |= WORK_STRUCT_INACTIVE;
1710 worklist = &pwq->inactive_works;
1713 debug_work_activate(work);
1714 insert_work(pwq, work, worklist, work_flags);
1717 raw_spin_unlock(&pwq->pool->lock);
1722 * queue_work_on - queue work on specific cpu
1723 * @cpu: CPU number to execute work on
1724 * @wq: workqueue to use
1725 * @work: work to queue
1727 * We queue the work to a specific CPU, the caller must ensure it
1728 * can't go away. Callers that fail to ensure that the specified
1729 * CPU cannot go away will execute on a randomly chosen CPU.
1730 * But note well that callers specifying a CPU that never has been
1731 * online will get a splat.
1733 * Return: %false if @work was already on a queue, %true otherwise.
1735 bool queue_work_on(int cpu, struct workqueue_struct *wq,
1736 struct work_struct *work)
1739 unsigned long flags;
1741 local_irq_save(flags);
1743 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1744 __queue_work(cpu, wq, work);
1748 local_irq_restore(flags);
1751 EXPORT_SYMBOL(queue_work_on);
1754 * workqueue_select_cpu_near - Select a CPU based on NUMA node
1755 * @node: NUMA node ID that we want to select a CPU from
1757 * This function will attempt to find a "random" cpu available on a given
1758 * node. If there are no CPUs available on the given node it will return
1759 * WORK_CPU_UNBOUND indicating that we should just schedule to any
1760 * available CPU if we need to schedule this work.
1762 static int workqueue_select_cpu_near(int node)
1766 /* No point in doing this if NUMA isn't enabled for workqueues */
1767 if (!wq_numa_enabled)
1768 return WORK_CPU_UNBOUND;
1770 /* Delay binding to CPU if node is not valid or online */
1771 if (node < 0 || node >= MAX_NUMNODES || !node_online(node))
1772 return WORK_CPU_UNBOUND;
1774 /* Use local node/cpu if we are already there */
1775 cpu = raw_smp_processor_id();
1776 if (node == cpu_to_node(cpu))
1779 /* Use "random" otherwise know as "first" online CPU of node */
1780 cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
1782 /* If CPU is valid return that, otherwise just defer */
1783 return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND;
1787 * queue_work_node - queue work on a "random" cpu for a given NUMA node
1788 * @node: NUMA node that we are targeting the work for
1789 * @wq: workqueue to use
1790 * @work: work to queue
1792 * We queue the work to a "random" CPU within a given NUMA node. The basic
1793 * idea here is to provide a way to somehow associate work with a given
1796 * This function will only make a best effort attempt at getting this onto
1797 * the right NUMA node. If no node is requested or the requested node is
1798 * offline then we just fall back to standard queue_work behavior.
1800 * Currently the "random" CPU ends up being the first available CPU in the
1801 * intersection of cpu_online_mask and the cpumask of the node, unless we
1802 * are running on the node. In that case we just use the current CPU.
1804 * Return: %false if @work was already on a queue, %true otherwise.
1806 bool queue_work_node(int node, struct workqueue_struct *wq,
1807 struct work_struct *work)
1809 unsigned long flags;
1813 * This current implementation is specific to unbound workqueues.
1814 * Specifically we only return the first available CPU for a given
1815 * node instead of cycling through individual CPUs within the node.
1817 * If this is used with a per-cpu workqueue then the logic in
1818 * workqueue_select_cpu_near would need to be updated to allow for
1819 * some round robin type logic.
1821 WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND));
1823 local_irq_save(flags);
1825 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1826 int cpu = workqueue_select_cpu_near(node);
1828 __queue_work(cpu, wq, work);
1832 local_irq_restore(flags);
1835 EXPORT_SYMBOL_GPL(queue_work_node);
1837 void delayed_work_timer_fn(struct timer_list *t)
1839 struct delayed_work *dwork = from_timer(dwork, t, timer);
1841 /* should have been called from irqsafe timer with irq already off */
1842 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
1844 EXPORT_SYMBOL(delayed_work_timer_fn);
1846 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
1847 struct delayed_work *dwork, unsigned long delay)
1849 struct timer_list *timer = &dwork->timer;
1850 struct work_struct *work = &dwork->work;
1853 WARN_ON_ONCE(timer->function != delayed_work_timer_fn);
1854 WARN_ON_ONCE(timer_pending(timer));
1855 WARN_ON_ONCE(!list_empty(&work->entry));
1858 * If @delay is 0, queue @dwork->work immediately. This is for
1859 * both optimization and correctness. The earliest @timer can
1860 * expire is on the closest next tick and delayed_work users depend
1861 * on that there's no such delay when @delay is 0.
1864 __queue_work(cpu, wq, &dwork->work);
1870 timer->expires = jiffies + delay;
1872 if (unlikely(cpu != WORK_CPU_UNBOUND))
1873 add_timer_on(timer, cpu);
1879 * queue_delayed_work_on - queue work on specific CPU after delay
1880 * @cpu: CPU number to execute work on
1881 * @wq: workqueue to use
1882 * @dwork: work to queue
1883 * @delay: number of jiffies to wait before queueing
1885 * Return: %false if @work was already on a queue, %true otherwise. If
1886 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1889 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1890 struct delayed_work *dwork, unsigned long delay)
1892 struct work_struct *work = &dwork->work;
1894 unsigned long flags;
1896 /* read the comment in __queue_work() */
1897 local_irq_save(flags);
1899 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1900 __queue_delayed_work(cpu, wq, dwork, delay);
1904 local_irq_restore(flags);
1907 EXPORT_SYMBOL(queue_delayed_work_on);
1910 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1911 * @cpu: CPU number to execute work on
1912 * @wq: workqueue to use
1913 * @dwork: work to queue
1914 * @delay: number of jiffies to wait before queueing
1916 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1917 * modify @dwork's timer so that it expires after @delay. If @delay is
1918 * zero, @work is guaranteed to be scheduled immediately regardless of its
1921 * Return: %false if @dwork was idle and queued, %true if @dwork was
1922 * pending and its timer was modified.
1924 * This function is safe to call from any context including IRQ handler.
1925 * See try_to_grab_pending() for details.
1927 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
1928 struct delayed_work *dwork, unsigned long delay)
1930 unsigned long flags;
1934 ret = try_to_grab_pending(&dwork->work, true, &flags);
1935 } while (unlikely(ret == -EAGAIN));
1937 if (likely(ret >= 0)) {
1938 __queue_delayed_work(cpu, wq, dwork, delay);
1939 local_irq_restore(flags);
1942 /* -ENOENT from try_to_grab_pending() becomes %true */
1945 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
1947 static void rcu_work_rcufn(struct rcu_head *rcu)
1949 struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
1951 /* read the comment in __queue_work() */
1952 local_irq_disable();
1953 __queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
1958 * queue_rcu_work - queue work after a RCU grace period
1959 * @wq: workqueue to use
1960 * @rwork: work to queue
1962 * Return: %false if @rwork was already pending, %true otherwise. Note
1963 * that a full RCU grace period is guaranteed only after a %true return.
1964 * While @rwork is guaranteed to be executed after a %false return, the
1965 * execution may happen before a full RCU grace period has passed.
1967 bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
1969 struct work_struct *work = &rwork->work;
1971 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1973 call_rcu_hurry(&rwork->rcu, rcu_work_rcufn);
1979 EXPORT_SYMBOL(queue_rcu_work);
1982 * worker_enter_idle - enter idle state
1983 * @worker: worker which is entering idle state
1985 * @worker is entering idle state. Update stats and idle timer if
1989 * raw_spin_lock_irq(pool->lock).
1991 static void worker_enter_idle(struct worker *worker)
1993 struct worker_pool *pool = worker->pool;
1995 if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
1996 WARN_ON_ONCE(!list_empty(&worker->entry) &&
1997 (worker->hentry.next || worker->hentry.pprev)))
2000 /* can't use worker_set_flags(), also called from create_worker() */
2001 worker->flags |= WORKER_IDLE;
2003 worker->last_active = jiffies;
2005 /* idle_list is LIFO */
2006 list_add(&worker->entry, &pool->idle_list);
2008 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
2009 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
2011 /* Sanity check nr_running. */
2012 WARN_ON_ONCE(pool->nr_workers == pool->nr_idle && pool->nr_running);
2016 * worker_leave_idle - leave idle state
2017 * @worker: worker which is leaving idle state
2019 * @worker is leaving idle state. Update stats.
2022 * raw_spin_lock_irq(pool->lock).
2024 static void worker_leave_idle(struct worker *worker)
2026 struct worker_pool *pool = worker->pool;
2028 if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
2030 worker_clr_flags(worker, WORKER_IDLE);
2032 list_del_init(&worker->entry);
2035 static struct worker *alloc_worker(int node)
2037 struct worker *worker;
2039 worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
2041 INIT_LIST_HEAD(&worker->entry);
2042 INIT_LIST_HEAD(&worker->scheduled);
2043 INIT_LIST_HEAD(&worker->node);
2044 /* on creation a worker is in !idle && prep state */
2045 worker->flags = WORKER_PREP;
2051 * worker_attach_to_pool() - attach a worker to a pool
2052 * @worker: worker to be attached
2053 * @pool: the target pool
2055 * Attach @worker to @pool. Once attached, the %WORKER_UNBOUND flag and
2056 * cpu-binding of @worker are kept coordinated with the pool across
2059 static void worker_attach_to_pool(struct worker *worker,
2060 struct worker_pool *pool)
2062 mutex_lock(&wq_pool_attach_mutex);
2065 * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains
2066 * stable across this function. See the comments above the flag
2067 * definition for details.
2069 if (pool->flags & POOL_DISASSOCIATED)
2070 worker->flags |= WORKER_UNBOUND;
2072 kthread_set_per_cpu(worker->task, pool->cpu);
2074 if (worker->rescue_wq)
2075 set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
2077 list_add_tail(&worker->node, &pool->workers);
2078 worker->pool = pool;
2080 mutex_unlock(&wq_pool_attach_mutex);
2084 * worker_detach_from_pool() - detach a worker from its pool
2085 * @worker: worker which is attached to its pool
2087 * Undo the attaching which had been done in worker_attach_to_pool(). The
2088 * caller worker shouldn't access to the pool after detached except it has
2089 * other reference to the pool.
2091 static void worker_detach_from_pool(struct worker *worker)
2093 struct worker_pool *pool = worker->pool;
2094 struct completion *detach_completion = NULL;
2096 mutex_lock(&wq_pool_attach_mutex);
2098 kthread_set_per_cpu(worker->task, -1);
2099 list_del(&worker->node);
2100 worker->pool = NULL;
2102 if (list_empty(&pool->workers) && list_empty(&pool->dying_workers))
2103 detach_completion = pool->detach_completion;
2104 mutex_unlock(&wq_pool_attach_mutex);
2106 /* clear leftover flags without pool->lock after it is detached */
2107 worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
2109 if (detach_completion)
2110 complete(detach_completion);
2114 * create_worker - create a new workqueue worker
2115 * @pool: pool the new worker will belong to
2117 * Create and start a new worker which is attached to @pool.
2120 * Might sleep. Does GFP_KERNEL allocations.
2123 * Pointer to the newly created worker.
2125 static struct worker *create_worker(struct worker_pool *pool)
2127 struct worker *worker;
2131 /* ID is needed to determine kthread name */
2132 id = ida_alloc(&pool->worker_ida, GFP_KERNEL);
2134 pr_err_once("workqueue: Failed to allocate a worker ID: %pe\n",
2139 worker = alloc_worker(pool->node);
2141 pr_err_once("workqueue: Failed to allocate a worker\n");
2148 snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
2149 pool->attrs->nice < 0 ? "H" : "");
2151 snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
2153 worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
2154 "kworker/%s", id_buf);
2155 if (IS_ERR(worker->task)) {
2156 if (PTR_ERR(worker->task) == -EINTR) {
2157 pr_err("workqueue: Interrupted when creating a worker thread \"kworker/%s\"\n",
2160 pr_err_once("workqueue: Failed to create a worker thread: %pe",
2166 set_user_nice(worker->task, pool->attrs->nice);
2167 kthread_bind_mask(worker->task, pool->attrs->cpumask);
2169 /* successful, attach the worker to the pool */
2170 worker_attach_to_pool(worker, pool);
2172 /* start the newly created worker */
2173 raw_spin_lock_irq(&pool->lock);
2174 worker->pool->nr_workers++;
2175 worker_enter_idle(worker);
2176 wake_up_process(worker->task);
2177 raw_spin_unlock_irq(&pool->lock);
2182 ida_free(&pool->worker_ida, id);
2187 static void unbind_worker(struct worker *worker)
2189 lockdep_assert_held(&wq_pool_attach_mutex);
2191 kthread_set_per_cpu(worker->task, -1);
2192 if (cpumask_intersects(wq_unbound_cpumask, cpu_active_mask))
2193 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, wq_unbound_cpumask) < 0);
2195 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, cpu_possible_mask) < 0);
2198 static void wake_dying_workers(struct list_head *cull_list)
2200 struct worker *worker, *tmp;
2202 list_for_each_entry_safe(worker, tmp, cull_list, entry) {
2203 list_del_init(&worker->entry);
2204 unbind_worker(worker);
2206 * If the worker was somehow already running, then it had to be
2207 * in pool->idle_list when set_worker_dying() happened or we
2208 * wouldn't have gotten here.
2210 * Thus, the worker must either have observed the WORKER_DIE
2211 * flag, or have set its state to TASK_IDLE. Either way, the
2212 * below will be observed by the worker and is safe to do
2213 * outside of pool->lock.
2215 wake_up_process(worker->task);
2220 * set_worker_dying - Tag a worker for destruction
2221 * @worker: worker to be destroyed
2222 * @list: transfer worker away from its pool->idle_list and into list
2224 * Tag @worker for destruction and adjust @pool stats accordingly. The worker
2228 * raw_spin_lock_irq(pool->lock).
2230 static void set_worker_dying(struct worker *worker, struct list_head *list)
2232 struct worker_pool *pool = worker->pool;
2234 lockdep_assert_held(&pool->lock);
2235 lockdep_assert_held(&wq_pool_attach_mutex);
2237 /* sanity check frenzy */
2238 if (WARN_ON(worker->current_work) ||
2239 WARN_ON(!list_empty(&worker->scheduled)) ||
2240 WARN_ON(!(worker->flags & WORKER_IDLE)))
2246 worker->flags |= WORKER_DIE;
2248 list_move(&worker->entry, list);
2249 list_move(&worker->node, &pool->dying_workers);
2253 * idle_worker_timeout - check if some idle workers can now be deleted.
2254 * @t: The pool's idle_timer that just expired
2256 * The timer is armed in worker_enter_idle(). Note that it isn't disarmed in
2257 * worker_leave_idle(), as a worker flicking between idle and active while its
2258 * pool is at the too_many_workers() tipping point would cause too much timer
2259 * housekeeping overhead. Since IDLE_WORKER_TIMEOUT is long enough, we just let
2260 * it expire and re-evaluate things from there.
2262 static void idle_worker_timeout(struct timer_list *t)
2264 struct worker_pool *pool = from_timer(pool, t, idle_timer);
2265 bool do_cull = false;
2267 if (work_pending(&pool->idle_cull_work))
2270 raw_spin_lock_irq(&pool->lock);
2272 if (too_many_workers(pool)) {
2273 struct worker *worker;
2274 unsigned long expires;
2276 /* idle_list is kept in LIFO order, check the last one */
2277 worker = list_entry(pool->idle_list.prev, struct worker, entry);
2278 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2279 do_cull = !time_before(jiffies, expires);
2282 mod_timer(&pool->idle_timer, expires);
2284 raw_spin_unlock_irq(&pool->lock);
2287 queue_work(system_unbound_wq, &pool->idle_cull_work);
2291 * idle_cull_fn - cull workers that have been idle for too long.
2292 * @work: the pool's work for handling these idle workers
2294 * This goes through a pool's idle workers and gets rid of those that have been
2295 * idle for at least IDLE_WORKER_TIMEOUT seconds.
2297 * We don't want to disturb isolated CPUs because of a pcpu kworker being
2298 * culled, so this also resets worker affinity. This requires a sleepable
2299 * context, hence the split between timer callback and work item.
2301 static void idle_cull_fn(struct work_struct *work)
2303 struct worker_pool *pool = container_of(work, struct worker_pool, idle_cull_work);
2304 struct list_head cull_list;
2306 INIT_LIST_HEAD(&cull_list);
2308 * Grabbing wq_pool_attach_mutex here ensures an already-running worker
2309 * cannot proceed beyong worker_detach_from_pool() in its self-destruct
2310 * path. This is required as a previously-preempted worker could run after
2311 * set_worker_dying() has happened but before wake_dying_workers() did.
2313 mutex_lock(&wq_pool_attach_mutex);
2314 raw_spin_lock_irq(&pool->lock);
2316 while (too_many_workers(pool)) {
2317 struct worker *worker;
2318 unsigned long expires;
2320 worker = list_entry(pool->idle_list.prev, struct worker, entry);
2321 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2323 if (time_before(jiffies, expires)) {
2324 mod_timer(&pool->idle_timer, expires);
2328 set_worker_dying(worker, &cull_list);
2331 raw_spin_unlock_irq(&pool->lock);
2332 wake_dying_workers(&cull_list);
2333 mutex_unlock(&wq_pool_attach_mutex);
2336 static void send_mayday(struct work_struct *work)
2338 struct pool_workqueue *pwq = get_work_pwq(work);
2339 struct workqueue_struct *wq = pwq->wq;
2341 lockdep_assert_held(&wq_mayday_lock);
2346 /* mayday mayday mayday */
2347 if (list_empty(&pwq->mayday_node)) {
2349 * If @pwq is for an unbound wq, its base ref may be put at
2350 * any time due to an attribute change. Pin @pwq until the
2351 * rescuer is done with it.
2354 list_add_tail(&pwq->mayday_node, &wq->maydays);
2355 wake_up_process(wq->rescuer->task);
2356 pwq->stats[PWQ_STAT_MAYDAY]++;
2360 static void pool_mayday_timeout(struct timer_list *t)
2362 struct worker_pool *pool = from_timer(pool, t, mayday_timer);
2363 struct work_struct *work;
2365 raw_spin_lock_irq(&pool->lock);
2366 raw_spin_lock(&wq_mayday_lock); /* for wq->maydays */
2368 if (need_to_create_worker(pool)) {
2370 * We've been trying to create a new worker but
2371 * haven't been successful. We might be hitting an
2372 * allocation deadlock. Send distress signals to
2375 list_for_each_entry(work, &pool->worklist, entry)
2379 raw_spin_unlock(&wq_mayday_lock);
2380 raw_spin_unlock_irq(&pool->lock);
2382 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
2386 * maybe_create_worker - create a new worker if necessary
2387 * @pool: pool to create a new worker for
2389 * Create a new worker for @pool if necessary. @pool is guaranteed to
2390 * have at least one idle worker on return from this function. If
2391 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
2392 * sent to all rescuers with works scheduled on @pool to resolve
2393 * possible allocation deadlock.
2395 * On return, need_to_create_worker() is guaranteed to be %false and
2396 * may_start_working() %true.
2399 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2400 * multiple times. Does GFP_KERNEL allocations. Called only from
2403 static void maybe_create_worker(struct worker_pool *pool)
2404 __releases(&pool->lock)
2405 __acquires(&pool->lock)
2408 raw_spin_unlock_irq(&pool->lock);
2410 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
2411 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
2414 if (create_worker(pool) || !need_to_create_worker(pool))
2417 schedule_timeout_interruptible(CREATE_COOLDOWN);
2419 if (!need_to_create_worker(pool))
2423 del_timer_sync(&pool->mayday_timer);
2424 raw_spin_lock_irq(&pool->lock);
2426 * This is necessary even after a new worker was just successfully
2427 * created as @pool->lock was dropped and the new worker might have
2428 * already become busy.
2430 if (need_to_create_worker(pool))
2435 * manage_workers - manage worker pool
2438 * Assume the manager role and manage the worker pool @worker belongs
2439 * to. At any given time, there can be only zero or one manager per
2440 * pool. The exclusion is handled automatically by this function.
2442 * The caller can safely start processing works on false return. On
2443 * true return, it's guaranteed that need_to_create_worker() is false
2444 * and may_start_working() is true.
2447 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2448 * multiple times. Does GFP_KERNEL allocations.
2451 * %false if the pool doesn't need management and the caller can safely
2452 * start processing works, %true if management function was performed and
2453 * the conditions that the caller verified before calling the function may
2454 * no longer be true.
2456 static bool manage_workers(struct worker *worker)
2458 struct worker_pool *pool = worker->pool;
2460 if (pool->flags & POOL_MANAGER_ACTIVE)
2463 pool->flags |= POOL_MANAGER_ACTIVE;
2464 pool->manager = worker;
2466 maybe_create_worker(pool);
2468 pool->manager = NULL;
2469 pool->flags &= ~POOL_MANAGER_ACTIVE;
2470 rcuwait_wake_up(&manager_wait);
2475 * process_one_work - process single work
2477 * @work: work to process
2479 * Process @work. This function contains all the logics necessary to
2480 * process a single work including synchronization against and
2481 * interaction with other workers on the same cpu, queueing and
2482 * flushing. As long as context requirement is met, any worker can
2483 * call this function to process a work.
2486 * raw_spin_lock_irq(pool->lock) which is released and regrabbed.
2488 static void process_one_work(struct worker *worker, struct work_struct *work)
2489 __releases(&pool->lock)
2490 __acquires(&pool->lock)
2492 struct pool_workqueue *pwq = get_work_pwq(work);
2493 struct worker_pool *pool = worker->pool;
2494 unsigned long work_data;
2495 struct worker *collision;
2496 #ifdef CONFIG_LOCKDEP
2498 * It is permissible to free the struct work_struct from
2499 * inside the function that is called from it, this we need to
2500 * take into account for lockdep too. To avoid bogus "held
2501 * lock freed" warnings as well as problems when looking into
2502 * work->lockdep_map, make a copy and use that here.
2504 struct lockdep_map lockdep_map;
2506 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
2508 /* ensure we're on the correct CPU */
2509 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2510 raw_smp_processor_id() != pool->cpu);
2513 * A single work shouldn't be executed concurrently by
2514 * multiple workers on a single cpu. Check whether anyone is
2515 * already processing the work. If so, defer the work to the
2516 * currently executing one.
2518 collision = find_worker_executing_work(pool, work);
2519 if (unlikely(collision)) {
2520 move_linked_works(work, &collision->scheduled, NULL);
2524 /* claim and dequeue */
2525 debug_work_deactivate(work);
2526 hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2527 worker->current_work = work;
2528 worker->current_func = work->func;
2529 worker->current_pwq = pwq;
2530 worker->current_at = worker->task->se.sum_exec_runtime;
2531 work_data = *work_data_bits(work);
2532 worker->current_color = get_work_color(work_data);
2535 * Record wq name for cmdline and debug reporting, may get
2536 * overridden through set_worker_desc().
2538 strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
2540 list_del_init(&work->entry);
2543 * CPU intensive works don't participate in concurrency management.
2544 * They're the scheduler's responsibility. This takes @worker out
2545 * of concurrency management and the next code block will chain
2546 * execution of the pending work items.
2548 if (unlikely(pwq->wq->flags & WQ_CPU_INTENSIVE))
2549 worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2552 * Wake up another worker if necessary. The condition is always
2553 * false for normal per-cpu workers since nr_running would always
2554 * be >= 1 at this point. This is used to chain execution of the
2555 * pending work items for WORKER_NOT_RUNNING workers such as the
2556 * UNBOUND and CPU_INTENSIVE ones.
2558 if (need_more_worker(pool))
2559 wake_up_worker(pool);
2562 * Record the last pool and clear PENDING which should be the last
2563 * update to @work. Also, do this inside @pool->lock so that
2564 * PENDING and queued state changes happen together while IRQ is
2567 set_work_pool_and_clear_pending(work, pool->id);
2569 raw_spin_unlock_irq(&pool->lock);
2571 lock_map_acquire(&pwq->wq->lockdep_map);
2572 lock_map_acquire(&lockdep_map);
2574 * Strictly speaking we should mark the invariant state without holding
2575 * any locks, that is, before these two lock_map_acquire()'s.
2577 * However, that would result in:
2584 * Which would create W1->C->W1 dependencies, even though there is no
2585 * actual deadlock possible. There are two solutions, using a
2586 * read-recursive acquire on the work(queue) 'locks', but this will then
2587 * hit the lockdep limitation on recursive locks, or simply discard
2590 * AFAICT there is no possible deadlock scenario between the
2591 * flush_work() and complete() primitives (except for single-threaded
2592 * workqueues), so hiding them isn't a problem.
2594 lockdep_invariant_state(true);
2595 pwq->stats[PWQ_STAT_STARTED]++;
2596 trace_workqueue_execute_start(work);
2597 worker->current_func(work);
2599 * While we must be careful to not use "work" after this, the trace
2600 * point will only record its address.
2602 trace_workqueue_execute_end(work, worker->current_func);
2603 pwq->stats[PWQ_STAT_COMPLETED]++;
2604 lock_map_release(&lockdep_map);
2605 lock_map_release(&pwq->wq->lockdep_map);
2607 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2608 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2609 " last function: %ps\n",
2610 current->comm, preempt_count(), task_pid_nr(current),
2611 worker->current_func);
2612 debug_show_held_locks(current);
2617 * The following prevents a kworker from hogging CPU on !PREEMPTION
2618 * kernels, where a requeueing work item waiting for something to
2619 * happen could deadlock with stop_machine as such work item could
2620 * indefinitely requeue itself while all other CPUs are trapped in
2621 * stop_machine. At the same time, report a quiescent RCU state so
2622 * the same condition doesn't freeze RCU.
2626 raw_spin_lock_irq(&pool->lock);
2629 * In addition to %WQ_CPU_INTENSIVE, @worker may also have been marked
2630 * CPU intensive by wq_worker_tick() if @work hogged CPU longer than
2631 * wq_cpu_intensive_thresh_us. Clear it.
2633 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2635 /* tag the worker for identification in schedule() */
2636 worker->last_func = worker->current_func;
2638 /* we're done with it, release */
2639 hash_del(&worker->hentry);
2640 worker->current_work = NULL;
2641 worker->current_func = NULL;
2642 worker->current_pwq = NULL;
2643 worker->current_color = INT_MAX;
2644 pwq_dec_nr_in_flight(pwq, work_data);
2648 * process_scheduled_works - process scheduled works
2651 * Process all scheduled works. Please note that the scheduled list
2652 * may change while processing a work, so this function repeatedly
2653 * fetches a work from the top and executes it.
2656 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2659 static void process_scheduled_works(struct worker *worker)
2661 while (!list_empty(&worker->scheduled)) {
2662 struct work_struct *work = list_first_entry(&worker->scheduled,
2663 struct work_struct, entry);
2664 process_one_work(worker, work);
2668 static void set_pf_worker(bool val)
2670 mutex_lock(&wq_pool_attach_mutex);
2672 current->flags |= PF_WQ_WORKER;
2674 current->flags &= ~PF_WQ_WORKER;
2675 mutex_unlock(&wq_pool_attach_mutex);
2679 * worker_thread - the worker thread function
2682 * The worker thread function. All workers belong to a worker_pool -
2683 * either a per-cpu one or dynamic unbound one. These workers process all
2684 * work items regardless of their specific target workqueue. The only
2685 * exception is work items which belong to workqueues with a rescuer which
2686 * will be explained in rescuer_thread().
2690 static int worker_thread(void *__worker)
2692 struct worker *worker = __worker;
2693 struct worker_pool *pool = worker->pool;
2695 /* tell the scheduler that this is a workqueue worker */
2696 set_pf_worker(true);
2698 raw_spin_lock_irq(&pool->lock);
2700 /* am I supposed to die? */
2701 if (unlikely(worker->flags & WORKER_DIE)) {
2702 raw_spin_unlock_irq(&pool->lock);
2703 set_pf_worker(false);
2705 set_task_comm(worker->task, "kworker/dying");
2706 ida_free(&pool->worker_ida, worker->id);
2707 worker_detach_from_pool(worker);
2708 WARN_ON_ONCE(!list_empty(&worker->entry));
2713 worker_leave_idle(worker);
2715 /* no more worker necessary? */
2716 if (!need_more_worker(pool))
2719 /* do we need to manage? */
2720 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2724 * ->scheduled list can only be filled while a worker is
2725 * preparing to process a work or actually processing it.
2726 * Make sure nobody diddled with it while I was sleeping.
2728 WARN_ON_ONCE(!list_empty(&worker->scheduled));
2731 * Finish PREP stage. We're guaranteed to have at least one idle
2732 * worker or that someone else has already assumed the manager
2733 * role. This is where @worker starts participating in concurrency
2734 * management if applicable and concurrency management is restored
2735 * after being rebound. See rebind_workers() for details.
2737 worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2740 struct work_struct *work =
2741 list_first_entry(&pool->worklist,
2742 struct work_struct, entry);
2744 pool->watchdog_ts = jiffies;
2746 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2747 /* optimization path, not strictly necessary */
2748 process_one_work(worker, work);
2749 if (unlikely(!list_empty(&worker->scheduled)))
2750 process_scheduled_works(worker);
2752 move_linked_works(work, &worker->scheduled, NULL);
2753 process_scheduled_works(worker);
2755 } while (keep_working(pool));
2757 worker_set_flags(worker, WORKER_PREP);
2760 * pool->lock is held and there's no work to process and no need to
2761 * manage, sleep. Workers are woken up only while holding
2762 * pool->lock or from local cpu, so setting the current state
2763 * before releasing pool->lock is enough to prevent losing any
2766 worker_enter_idle(worker);
2767 __set_current_state(TASK_IDLE);
2768 raw_spin_unlock_irq(&pool->lock);
2774 * rescuer_thread - the rescuer thread function
2777 * Workqueue rescuer thread function. There's one rescuer for each
2778 * workqueue which has WQ_MEM_RECLAIM set.
2780 * Regular work processing on a pool may block trying to create a new
2781 * worker which uses GFP_KERNEL allocation which has slight chance of
2782 * developing into deadlock if some works currently on the same queue
2783 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2784 * the problem rescuer solves.
2786 * When such condition is possible, the pool summons rescuers of all
2787 * workqueues which have works queued on the pool and let them process
2788 * those works so that forward progress can be guaranteed.
2790 * This should happen rarely.
2794 static int rescuer_thread(void *__rescuer)
2796 struct worker *rescuer = __rescuer;
2797 struct workqueue_struct *wq = rescuer->rescue_wq;
2798 struct list_head *scheduled = &rescuer->scheduled;
2801 set_user_nice(current, RESCUER_NICE_LEVEL);
2804 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2805 * doesn't participate in concurrency management.
2807 set_pf_worker(true);
2809 set_current_state(TASK_IDLE);
2812 * By the time the rescuer is requested to stop, the workqueue
2813 * shouldn't have any work pending, but @wq->maydays may still have
2814 * pwq(s) queued. This can happen by non-rescuer workers consuming
2815 * all the work items before the rescuer got to them. Go through
2816 * @wq->maydays processing before acting on should_stop so that the
2817 * list is always empty on exit.
2819 should_stop = kthread_should_stop();
2821 /* see whether any pwq is asking for help */
2822 raw_spin_lock_irq(&wq_mayday_lock);
2824 while (!list_empty(&wq->maydays)) {
2825 struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2826 struct pool_workqueue, mayday_node);
2827 struct worker_pool *pool = pwq->pool;
2828 struct work_struct *work, *n;
2831 __set_current_state(TASK_RUNNING);
2832 list_del_init(&pwq->mayday_node);
2834 raw_spin_unlock_irq(&wq_mayday_lock);
2836 worker_attach_to_pool(rescuer, pool);
2838 raw_spin_lock_irq(&pool->lock);
2841 * Slurp in all works issued via this workqueue and
2844 WARN_ON_ONCE(!list_empty(scheduled));
2845 list_for_each_entry_safe(work, n, &pool->worklist, entry) {
2846 if (get_work_pwq(work) == pwq) {
2848 pool->watchdog_ts = jiffies;
2849 move_linked_works(work, scheduled, &n);
2850 pwq->stats[PWQ_STAT_RESCUED]++;
2855 if (!list_empty(scheduled)) {
2856 process_scheduled_works(rescuer);
2859 * The above execution of rescued work items could
2860 * have created more to rescue through
2861 * pwq_activate_first_inactive() or chained
2862 * queueing. Let's put @pwq back on mayday list so
2863 * that such back-to-back work items, which may be
2864 * being used to relieve memory pressure, don't
2865 * incur MAYDAY_INTERVAL delay inbetween.
2867 if (pwq->nr_active && need_to_create_worker(pool)) {
2868 raw_spin_lock(&wq_mayday_lock);
2870 * Queue iff we aren't racing destruction
2871 * and somebody else hasn't queued it already.
2873 if (wq->rescuer && list_empty(&pwq->mayday_node)) {
2875 list_add_tail(&pwq->mayday_node, &wq->maydays);
2877 raw_spin_unlock(&wq_mayday_lock);
2882 * Put the reference grabbed by send_mayday(). @pool won't
2883 * go away while we're still attached to it.
2888 * Leave this pool. If need_more_worker() is %true, notify a
2889 * regular worker; otherwise, we end up with 0 concurrency
2890 * and stalling the execution.
2892 if (need_more_worker(pool))
2893 wake_up_worker(pool);
2895 raw_spin_unlock_irq(&pool->lock);
2897 worker_detach_from_pool(rescuer);
2899 raw_spin_lock_irq(&wq_mayday_lock);
2902 raw_spin_unlock_irq(&wq_mayday_lock);
2905 __set_current_state(TASK_RUNNING);
2906 set_pf_worker(false);
2910 /* rescuers should never participate in concurrency management */
2911 WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2917 * check_flush_dependency - check for flush dependency sanity
2918 * @target_wq: workqueue being flushed
2919 * @target_work: work item being flushed (NULL for workqueue flushes)
2921 * %current is trying to flush the whole @target_wq or @target_work on it.
2922 * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
2923 * reclaiming memory or running on a workqueue which doesn't have
2924 * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
2927 static void check_flush_dependency(struct workqueue_struct *target_wq,
2928 struct work_struct *target_work)
2930 work_func_t target_func = target_work ? target_work->func : NULL;
2931 struct worker *worker;
2933 if (target_wq->flags & WQ_MEM_RECLAIM)
2936 worker = current_wq_worker();
2938 WARN_ONCE(current->flags & PF_MEMALLOC,
2939 "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps",
2940 current->pid, current->comm, target_wq->name, target_func);
2941 WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
2942 (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
2943 "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps",
2944 worker->current_pwq->wq->name, worker->current_func,
2945 target_wq->name, target_func);
2949 struct work_struct work;
2950 struct completion done;
2951 struct task_struct *task; /* purely informational */
2954 static void wq_barrier_func(struct work_struct *work)
2956 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2957 complete(&barr->done);
2961 * insert_wq_barrier - insert a barrier work
2962 * @pwq: pwq to insert barrier into
2963 * @barr: wq_barrier to insert
2964 * @target: target work to attach @barr to
2965 * @worker: worker currently executing @target, NULL if @target is not executing
2967 * @barr is linked to @target such that @barr is completed only after
2968 * @target finishes execution. Please note that the ordering
2969 * guarantee is observed only with respect to @target and on the local
2972 * Currently, a queued barrier can't be canceled. This is because
2973 * try_to_grab_pending() can't determine whether the work to be
2974 * grabbed is at the head of the queue and thus can't clear LINKED
2975 * flag of the previous work while there must be a valid next work
2976 * after a work with LINKED flag set.
2978 * Note that when @worker is non-NULL, @target may be modified
2979 * underneath us, so we can't reliably determine pwq from @target.
2982 * raw_spin_lock_irq(pool->lock).
2984 static void insert_wq_barrier(struct pool_workqueue *pwq,
2985 struct wq_barrier *barr,
2986 struct work_struct *target, struct worker *worker)
2988 unsigned int work_flags = 0;
2989 unsigned int work_color;
2990 struct list_head *head;
2993 * debugobject calls are safe here even with pool->lock locked
2994 * as we know for sure that this will not trigger any of the
2995 * checks and call back into the fixup functions where we
2998 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2999 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
3001 init_completion_map(&barr->done, &target->lockdep_map);
3003 barr->task = current;
3005 /* The barrier work item does not participate in pwq->nr_active. */
3006 work_flags |= WORK_STRUCT_INACTIVE;
3009 * If @target is currently being executed, schedule the
3010 * barrier to the worker; otherwise, put it after @target.
3013 head = worker->scheduled.next;
3014 work_color = worker->current_color;
3016 unsigned long *bits = work_data_bits(target);
3018 head = target->entry.next;
3019 /* there can already be other linked works, inherit and set */
3020 work_flags |= *bits & WORK_STRUCT_LINKED;
3021 work_color = get_work_color(*bits);
3022 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
3025 pwq->nr_in_flight[work_color]++;
3026 work_flags |= work_color_to_flags(work_color);
3028 debug_work_activate(&barr->work);
3029 insert_work(pwq, &barr->work, head, work_flags);
3033 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
3034 * @wq: workqueue being flushed
3035 * @flush_color: new flush color, < 0 for no-op
3036 * @work_color: new work color, < 0 for no-op
3038 * Prepare pwqs for workqueue flushing.
3040 * If @flush_color is non-negative, flush_color on all pwqs should be
3041 * -1. If no pwq has in-flight commands at the specified color, all
3042 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
3043 * has in flight commands, its pwq->flush_color is set to
3044 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
3045 * wakeup logic is armed and %true is returned.
3047 * The caller should have initialized @wq->first_flusher prior to
3048 * calling this function with non-negative @flush_color. If
3049 * @flush_color is negative, no flush color update is done and %false
3052 * If @work_color is non-negative, all pwqs should have the same
3053 * work_color which is previous to @work_color and all will be
3054 * advanced to @work_color.
3057 * mutex_lock(wq->mutex).
3060 * %true if @flush_color >= 0 and there's something to flush. %false
3063 static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
3064 int flush_color, int work_color)
3067 struct pool_workqueue *pwq;
3069 if (flush_color >= 0) {
3070 WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
3071 atomic_set(&wq->nr_pwqs_to_flush, 1);
3074 for_each_pwq(pwq, wq) {
3075 struct worker_pool *pool = pwq->pool;
3077 raw_spin_lock_irq(&pool->lock);
3079 if (flush_color >= 0) {
3080 WARN_ON_ONCE(pwq->flush_color != -1);
3082 if (pwq->nr_in_flight[flush_color]) {
3083 pwq->flush_color = flush_color;
3084 atomic_inc(&wq->nr_pwqs_to_flush);
3089 if (work_color >= 0) {
3090 WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
3091 pwq->work_color = work_color;
3094 raw_spin_unlock_irq(&pool->lock);
3097 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
3098 complete(&wq->first_flusher->done);
3104 * __flush_workqueue - ensure that any scheduled work has run to completion.
3105 * @wq: workqueue to flush
3107 * This function sleeps until all work items which were queued on entry
3108 * have finished execution, but it is not livelocked by new incoming ones.
3110 void __flush_workqueue(struct workqueue_struct *wq)
3112 struct wq_flusher this_flusher = {
3113 .list = LIST_HEAD_INIT(this_flusher.list),
3115 .done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map),
3119 if (WARN_ON(!wq_online))
3122 lock_map_acquire(&wq->lockdep_map);
3123 lock_map_release(&wq->lockdep_map);
3125 mutex_lock(&wq->mutex);
3128 * Start-to-wait phase
3130 next_color = work_next_color(wq->work_color);
3132 if (next_color != wq->flush_color) {
3134 * Color space is not full. The current work_color
3135 * becomes our flush_color and work_color is advanced
3138 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
3139 this_flusher.flush_color = wq->work_color;
3140 wq->work_color = next_color;
3142 if (!wq->first_flusher) {
3143 /* no flush in progress, become the first flusher */
3144 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
3146 wq->first_flusher = &this_flusher;
3148 if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
3150 /* nothing to flush, done */
3151 wq->flush_color = next_color;
3152 wq->first_flusher = NULL;
3157 WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
3158 list_add_tail(&this_flusher.list, &wq->flusher_queue);
3159 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
3163 * Oops, color space is full, wait on overflow queue.
3164 * The next flush completion will assign us
3165 * flush_color and transfer to flusher_queue.
3167 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
3170 check_flush_dependency(wq, NULL);
3172 mutex_unlock(&wq->mutex);
3174 wait_for_completion(&this_flusher.done);
3177 * Wake-up-and-cascade phase
3179 * First flushers are responsible for cascading flushes and
3180 * handling overflow. Non-first flushers can simply return.
3182 if (READ_ONCE(wq->first_flusher) != &this_flusher)
3185 mutex_lock(&wq->mutex);
3187 /* we might have raced, check again with mutex held */
3188 if (wq->first_flusher != &this_flusher)
3191 WRITE_ONCE(wq->first_flusher, NULL);
3193 WARN_ON_ONCE(!list_empty(&this_flusher.list));
3194 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
3197 struct wq_flusher *next, *tmp;
3199 /* complete all the flushers sharing the current flush color */
3200 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
3201 if (next->flush_color != wq->flush_color)
3203 list_del_init(&next->list);
3204 complete(&next->done);
3207 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
3208 wq->flush_color != work_next_color(wq->work_color));
3210 /* this flush_color is finished, advance by one */
3211 wq->flush_color = work_next_color(wq->flush_color);
3213 /* one color has been freed, handle overflow queue */
3214 if (!list_empty(&wq->flusher_overflow)) {
3216 * Assign the same color to all overflowed
3217 * flushers, advance work_color and append to
3218 * flusher_queue. This is the start-to-wait
3219 * phase for these overflowed flushers.
3221 list_for_each_entry(tmp, &wq->flusher_overflow, list)
3222 tmp->flush_color = wq->work_color;
3224 wq->work_color = work_next_color(wq->work_color);
3226 list_splice_tail_init(&wq->flusher_overflow,
3227 &wq->flusher_queue);
3228 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
3231 if (list_empty(&wq->flusher_queue)) {
3232 WARN_ON_ONCE(wq->flush_color != wq->work_color);
3237 * Need to flush more colors. Make the next flusher
3238 * the new first flusher and arm pwqs.
3240 WARN_ON_ONCE(wq->flush_color == wq->work_color);
3241 WARN_ON_ONCE(wq->flush_color != next->flush_color);
3243 list_del_init(&next->list);
3244 wq->first_flusher = next;
3246 if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
3250 * Meh... this color is already done, clear first
3251 * flusher and repeat cascading.
3253 wq->first_flusher = NULL;
3257 mutex_unlock(&wq->mutex);
3259 EXPORT_SYMBOL(__flush_workqueue);
3262 * drain_workqueue - drain a workqueue
3263 * @wq: workqueue to drain
3265 * Wait until the workqueue becomes empty. While draining is in progress,
3266 * only chain queueing is allowed. IOW, only currently pending or running
3267 * work items on @wq can queue further work items on it. @wq is flushed
3268 * repeatedly until it becomes empty. The number of flushing is determined
3269 * by the depth of chaining and should be relatively short. Whine if it
3272 void drain_workqueue(struct workqueue_struct *wq)
3274 unsigned int flush_cnt = 0;
3275 struct pool_workqueue *pwq;
3278 * __queue_work() needs to test whether there are drainers, is much
3279 * hotter than drain_workqueue() and already looks at @wq->flags.
3280 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
3282 mutex_lock(&wq->mutex);
3283 if (!wq->nr_drainers++)
3284 wq->flags |= __WQ_DRAINING;
3285 mutex_unlock(&wq->mutex);
3287 __flush_workqueue(wq);
3289 mutex_lock(&wq->mutex);
3291 for_each_pwq(pwq, wq) {
3294 raw_spin_lock_irq(&pwq->pool->lock);
3295 drained = !pwq->nr_active && list_empty(&pwq->inactive_works);
3296 raw_spin_unlock_irq(&pwq->pool->lock);
3301 if (++flush_cnt == 10 ||
3302 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
3303 pr_warn("workqueue %s: %s() isn't complete after %u tries\n",
3304 wq->name, __func__, flush_cnt);
3306 mutex_unlock(&wq->mutex);
3310 if (!--wq->nr_drainers)
3311 wq->flags &= ~__WQ_DRAINING;
3312 mutex_unlock(&wq->mutex);
3314 EXPORT_SYMBOL_GPL(drain_workqueue);
3316 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
3319 struct worker *worker = NULL;
3320 struct worker_pool *pool;
3321 struct pool_workqueue *pwq;
3326 pool = get_work_pool(work);
3332 raw_spin_lock_irq(&pool->lock);
3333 /* see the comment in try_to_grab_pending() with the same code */
3334 pwq = get_work_pwq(work);
3336 if (unlikely(pwq->pool != pool))
3339 worker = find_worker_executing_work(pool, work);
3342 pwq = worker->current_pwq;
3345 check_flush_dependency(pwq->wq, work);
3347 insert_wq_barrier(pwq, barr, work, worker);
3348 raw_spin_unlock_irq(&pool->lock);
3351 * Force a lock recursion deadlock when using flush_work() inside a
3352 * single-threaded or rescuer equipped workqueue.
3354 * For single threaded workqueues the deadlock happens when the work
3355 * is after the work issuing the flush_work(). For rescuer equipped
3356 * workqueues the deadlock happens when the rescuer stalls, blocking
3360 (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)) {
3361 lock_map_acquire(&pwq->wq->lockdep_map);
3362 lock_map_release(&pwq->wq->lockdep_map);
3367 raw_spin_unlock_irq(&pool->lock);
3372 static bool __flush_work(struct work_struct *work, bool from_cancel)
3374 struct wq_barrier barr;
3376 if (WARN_ON(!wq_online))
3379 if (WARN_ON(!work->func))
3382 lock_map_acquire(&work->lockdep_map);
3383 lock_map_release(&work->lockdep_map);
3385 if (start_flush_work(work, &barr, from_cancel)) {
3386 wait_for_completion(&barr.done);
3387 destroy_work_on_stack(&barr.work);
3395 * flush_work - wait for a work to finish executing the last queueing instance
3396 * @work: the work to flush
3398 * Wait until @work has finished execution. @work is guaranteed to be idle
3399 * on return if it hasn't been requeued since flush started.
3402 * %true if flush_work() waited for the work to finish execution,
3403 * %false if it was already idle.
3405 bool flush_work(struct work_struct *work)
3407 return __flush_work(work, false);
3409 EXPORT_SYMBOL_GPL(flush_work);
3412 wait_queue_entry_t wait;
3413 struct work_struct *work;
3416 static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
3418 struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
3420 if (cwait->work != key)
3422 return autoremove_wake_function(wait, mode, sync, key);
3425 static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
3427 static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
3428 unsigned long flags;
3432 ret = try_to_grab_pending(work, is_dwork, &flags);
3434 * If someone else is already canceling, wait for it to
3435 * finish. flush_work() doesn't work for PREEMPT_NONE
3436 * because we may get scheduled between @work's completion
3437 * and the other canceling task resuming and clearing
3438 * CANCELING - flush_work() will return false immediately
3439 * as @work is no longer busy, try_to_grab_pending() will
3440 * return -ENOENT as @work is still being canceled and the
3441 * other canceling task won't be able to clear CANCELING as
3442 * we're hogging the CPU.
3444 * Let's wait for completion using a waitqueue. As this
3445 * may lead to the thundering herd problem, use a custom
3446 * wake function which matches @work along with exclusive
3449 if (unlikely(ret == -ENOENT)) {
3450 struct cwt_wait cwait;
3452 init_wait(&cwait.wait);
3453 cwait.wait.func = cwt_wakefn;
3456 prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
3457 TASK_UNINTERRUPTIBLE);
3458 if (work_is_canceling(work))
3460 finish_wait(&cancel_waitq, &cwait.wait);
3462 } while (unlikely(ret < 0));
3464 /* tell other tasks trying to grab @work to back off */
3465 mark_work_canceling(work);
3466 local_irq_restore(flags);
3469 * This allows canceling during early boot. We know that @work
3473 __flush_work(work, true);
3475 clear_work_data(work);
3478 * Paired with prepare_to_wait() above so that either
3479 * waitqueue_active() is visible here or !work_is_canceling() is
3483 if (waitqueue_active(&cancel_waitq))
3484 __wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
3490 * cancel_work_sync - cancel a work and wait for it to finish
3491 * @work: the work to cancel
3493 * Cancel @work and wait for its execution to finish. This function
3494 * can be used even if the work re-queues itself or migrates to
3495 * another workqueue. On return from this function, @work is
3496 * guaranteed to be not pending or executing on any CPU.
3498 * cancel_work_sync(&delayed_work->work) must not be used for
3499 * delayed_work's. Use cancel_delayed_work_sync() instead.
3501 * The caller must ensure that the workqueue on which @work was last
3502 * queued can't be destroyed before this function returns.
3505 * %true if @work was pending, %false otherwise.
3507 bool cancel_work_sync(struct work_struct *work)
3509 return __cancel_work_timer(work, false);
3511 EXPORT_SYMBOL_GPL(cancel_work_sync);
3514 * flush_delayed_work - wait for a dwork to finish executing the last queueing
3515 * @dwork: the delayed work to flush
3517 * Delayed timer is cancelled and the pending work is queued for
3518 * immediate execution. Like flush_work(), this function only
3519 * considers the last queueing instance of @dwork.
3522 * %true if flush_work() waited for the work to finish execution,
3523 * %false if it was already idle.
3525 bool flush_delayed_work(struct delayed_work *dwork)
3527 local_irq_disable();
3528 if (del_timer_sync(&dwork->timer))
3529 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
3531 return flush_work(&dwork->work);
3533 EXPORT_SYMBOL(flush_delayed_work);
3536 * flush_rcu_work - wait for a rwork to finish executing the last queueing
3537 * @rwork: the rcu work to flush
3540 * %true if flush_rcu_work() waited for the work to finish execution,
3541 * %false if it was already idle.
3543 bool flush_rcu_work(struct rcu_work *rwork)
3545 if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
3547 flush_work(&rwork->work);
3550 return flush_work(&rwork->work);
3553 EXPORT_SYMBOL(flush_rcu_work);
3555 static bool __cancel_work(struct work_struct *work, bool is_dwork)
3557 unsigned long flags;
3561 ret = try_to_grab_pending(work, is_dwork, &flags);
3562 } while (unlikely(ret == -EAGAIN));
3564 if (unlikely(ret < 0))
3567 set_work_pool_and_clear_pending(work, get_work_pool_id(work));
3568 local_irq_restore(flags);
3573 * See cancel_delayed_work()
3575 bool cancel_work(struct work_struct *work)
3577 return __cancel_work(work, false);
3579 EXPORT_SYMBOL(cancel_work);
3582 * cancel_delayed_work - cancel a delayed work
3583 * @dwork: delayed_work to cancel
3585 * Kill off a pending delayed_work.
3587 * Return: %true if @dwork was pending and canceled; %false if it wasn't
3591 * The work callback function may still be running on return, unless
3592 * it returns %true and the work doesn't re-arm itself. Explicitly flush or
3593 * use cancel_delayed_work_sync() to wait on it.
3595 * This function is safe to call from any context including IRQ handler.
3597 bool cancel_delayed_work(struct delayed_work *dwork)
3599 return __cancel_work(&dwork->work, true);
3601 EXPORT_SYMBOL(cancel_delayed_work);
3604 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3605 * @dwork: the delayed work cancel
3607 * This is cancel_work_sync() for delayed works.
3610 * %true if @dwork was pending, %false otherwise.
3612 bool cancel_delayed_work_sync(struct delayed_work *dwork)
3614 return __cancel_work_timer(&dwork->work, true);
3616 EXPORT_SYMBOL(cancel_delayed_work_sync);
3619 * schedule_on_each_cpu - execute a function synchronously on each online CPU
3620 * @func: the function to call
3622 * schedule_on_each_cpu() executes @func on each online CPU using the
3623 * system workqueue and blocks until all CPUs have completed.
3624 * schedule_on_each_cpu() is very slow.
3627 * 0 on success, -errno on failure.
3629 int schedule_on_each_cpu(work_func_t func)
3632 struct work_struct __percpu *works;
3634 works = alloc_percpu(struct work_struct);
3640 for_each_online_cpu(cpu) {
3641 struct work_struct *work = per_cpu_ptr(works, cpu);
3643 INIT_WORK(work, func);
3644 schedule_work_on(cpu, work);
3647 for_each_online_cpu(cpu)
3648 flush_work(per_cpu_ptr(works, cpu));
3656 * execute_in_process_context - reliably execute the routine with user context
3657 * @fn: the function to execute
3658 * @ew: guaranteed storage for the execute work structure (must
3659 * be available when the work executes)
3661 * Executes the function immediately if process context is available,
3662 * otherwise schedules the function for delayed execution.
3664 * Return: 0 - function was executed
3665 * 1 - function was scheduled for execution
3667 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
3669 if (!in_interrupt()) {
3674 INIT_WORK(&ew->work, fn);
3675 schedule_work(&ew->work);
3679 EXPORT_SYMBOL_GPL(execute_in_process_context);
3682 * free_workqueue_attrs - free a workqueue_attrs
3683 * @attrs: workqueue_attrs to free
3685 * Undo alloc_workqueue_attrs().
3687 void free_workqueue_attrs(struct workqueue_attrs *attrs)
3690 free_cpumask_var(attrs->cpumask);
3696 * alloc_workqueue_attrs - allocate a workqueue_attrs
3698 * Allocate a new workqueue_attrs, initialize with default settings and
3701 * Return: The allocated new workqueue_attr on success. %NULL on failure.
3703 struct workqueue_attrs *alloc_workqueue_attrs(void)
3705 struct workqueue_attrs *attrs;
3707 attrs = kzalloc(sizeof(*attrs), GFP_KERNEL);
3710 if (!alloc_cpumask_var(&attrs->cpumask, GFP_KERNEL))
3713 cpumask_copy(attrs->cpumask, cpu_possible_mask);
3716 free_workqueue_attrs(attrs);
3720 static void copy_workqueue_attrs(struct workqueue_attrs *to,
3721 const struct workqueue_attrs *from)
3723 to->nice = from->nice;
3724 cpumask_copy(to->cpumask, from->cpumask);
3726 * Unlike hash and equality test, this function doesn't ignore
3727 * ->no_numa as it is used for both pool and wq attrs. Instead,
3728 * get_unbound_pool() explicitly clears ->no_numa after copying.
3730 to->no_numa = from->no_numa;
3733 /* hash value of the content of @attr */
3734 static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
3738 hash = jhash_1word(attrs->nice, hash);
3739 hash = jhash(cpumask_bits(attrs->cpumask),
3740 BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
3744 /* content equality test */
3745 static bool wqattrs_equal(const struct workqueue_attrs *a,
3746 const struct workqueue_attrs *b)
3748 if (a->nice != b->nice)
3750 if (!cpumask_equal(a->cpumask, b->cpumask))
3756 * init_worker_pool - initialize a newly zalloc'd worker_pool
3757 * @pool: worker_pool to initialize
3759 * Initialize a newly zalloc'd @pool. It also allocates @pool->attrs.
3761 * Return: 0 on success, -errno on failure. Even on failure, all fields
3762 * inside @pool proper are initialized and put_unbound_pool() can be called
3763 * on @pool safely to release it.
3765 static int init_worker_pool(struct worker_pool *pool)
3767 raw_spin_lock_init(&pool->lock);
3770 pool->node = NUMA_NO_NODE;
3771 pool->flags |= POOL_DISASSOCIATED;
3772 pool->watchdog_ts = jiffies;
3773 INIT_LIST_HEAD(&pool->worklist);
3774 INIT_LIST_HEAD(&pool->idle_list);
3775 hash_init(pool->busy_hash);
3777 timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
3778 INIT_WORK(&pool->idle_cull_work, idle_cull_fn);
3780 timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
3782 INIT_LIST_HEAD(&pool->workers);
3783 INIT_LIST_HEAD(&pool->dying_workers);
3785 ida_init(&pool->worker_ida);
3786 INIT_HLIST_NODE(&pool->hash_node);
3789 /* shouldn't fail above this point */
3790 pool->attrs = alloc_workqueue_attrs();
3796 #ifdef CONFIG_LOCKDEP
3797 static void wq_init_lockdep(struct workqueue_struct *wq)
3801 lockdep_register_key(&wq->key);
3802 lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name);
3804 lock_name = wq->name;
3806 wq->lock_name = lock_name;
3807 lockdep_init_map(&wq->lockdep_map, lock_name, &wq->key, 0);
3810 static void wq_unregister_lockdep(struct workqueue_struct *wq)
3812 lockdep_unregister_key(&wq->key);
3815 static void wq_free_lockdep(struct workqueue_struct *wq)
3817 if (wq->lock_name != wq->name)
3818 kfree(wq->lock_name);
3821 static void wq_init_lockdep(struct workqueue_struct *wq)
3825 static void wq_unregister_lockdep(struct workqueue_struct *wq)
3829 static void wq_free_lockdep(struct workqueue_struct *wq)
3834 static void rcu_free_wq(struct rcu_head *rcu)
3836 struct workqueue_struct *wq =
3837 container_of(rcu, struct workqueue_struct, rcu);
3839 wq_free_lockdep(wq);
3841 if (!(wq->flags & WQ_UNBOUND))
3842 free_percpu(wq->cpu_pwqs);
3844 free_workqueue_attrs(wq->unbound_attrs);
3849 static void rcu_free_pool(struct rcu_head *rcu)
3851 struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
3853 ida_destroy(&pool->worker_ida);
3854 free_workqueue_attrs(pool->attrs);
3859 * put_unbound_pool - put a worker_pool
3860 * @pool: worker_pool to put
3862 * Put @pool. If its refcnt reaches zero, it gets destroyed in RCU
3863 * safe manner. get_unbound_pool() calls this function on its failure path
3864 * and this function should be able to release pools which went through,
3865 * successfully or not, init_worker_pool().
3867 * Should be called with wq_pool_mutex held.
3869 static void put_unbound_pool(struct worker_pool *pool)
3871 DECLARE_COMPLETION_ONSTACK(detach_completion);
3872 struct list_head cull_list;
3873 struct worker *worker;
3875 INIT_LIST_HEAD(&cull_list);
3877 lockdep_assert_held(&wq_pool_mutex);
3883 if (WARN_ON(!(pool->cpu < 0)) ||
3884 WARN_ON(!list_empty(&pool->worklist)))
3887 /* release id and unhash */
3889 idr_remove(&worker_pool_idr, pool->id);
3890 hash_del(&pool->hash_node);
3893 * Become the manager and destroy all workers. This prevents
3894 * @pool's workers from blocking on attach_mutex. We're the last
3895 * manager and @pool gets freed with the flag set.
3897 * Having a concurrent manager is quite unlikely to happen as we can
3898 * only get here with
3899 * pwq->refcnt == pool->refcnt == 0
3900 * which implies no work queued to the pool, which implies no worker can
3901 * become the manager. However a worker could have taken the role of
3902 * manager before the refcnts dropped to 0, since maybe_create_worker()
3906 rcuwait_wait_event(&manager_wait,
3907 !(pool->flags & POOL_MANAGER_ACTIVE),
3908 TASK_UNINTERRUPTIBLE);
3910 mutex_lock(&wq_pool_attach_mutex);
3911 raw_spin_lock_irq(&pool->lock);
3912 if (!(pool->flags & POOL_MANAGER_ACTIVE)) {
3913 pool->flags |= POOL_MANAGER_ACTIVE;
3916 raw_spin_unlock_irq(&pool->lock);
3917 mutex_unlock(&wq_pool_attach_mutex);
3920 while ((worker = first_idle_worker(pool)))
3921 set_worker_dying(worker, &cull_list);
3922 WARN_ON(pool->nr_workers || pool->nr_idle);
3923 raw_spin_unlock_irq(&pool->lock);
3925 wake_dying_workers(&cull_list);
3927 if (!list_empty(&pool->workers) || !list_empty(&pool->dying_workers))
3928 pool->detach_completion = &detach_completion;
3929 mutex_unlock(&wq_pool_attach_mutex);
3931 if (pool->detach_completion)
3932 wait_for_completion(pool->detach_completion);
3934 /* shut down the timers */
3935 del_timer_sync(&pool->idle_timer);
3936 cancel_work_sync(&pool->idle_cull_work);
3937 del_timer_sync(&pool->mayday_timer);
3939 /* RCU protected to allow dereferences from get_work_pool() */
3940 call_rcu(&pool->rcu, rcu_free_pool);
3944 * get_unbound_pool - get a worker_pool with the specified attributes
3945 * @attrs: the attributes of the worker_pool to get
3947 * Obtain a worker_pool which has the same attributes as @attrs, bump the
3948 * reference count and return it. If there already is a matching
3949 * worker_pool, it will be used; otherwise, this function attempts to
3952 * Should be called with wq_pool_mutex held.
3954 * Return: On success, a worker_pool with the same attributes as @attrs.
3955 * On failure, %NULL.
3957 static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
3959 u32 hash = wqattrs_hash(attrs);
3960 struct worker_pool *pool;
3962 int target_node = NUMA_NO_NODE;
3964 lockdep_assert_held(&wq_pool_mutex);
3966 /* do we already have a matching pool? */
3967 hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
3968 if (wqattrs_equal(pool->attrs, attrs)) {
3974 /* if cpumask is contained inside a NUMA node, we belong to that node */
3975 if (wq_numa_enabled) {
3976 for_each_node(node) {
3977 if (cpumask_subset(attrs->cpumask,
3978 wq_numa_possible_cpumask[node])) {
3985 /* nope, create a new one */
3986 pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, target_node);
3987 if (!pool || init_worker_pool(pool) < 0)
3990 lockdep_set_subclass(&pool->lock, 1); /* see put_pwq() */
3991 copy_workqueue_attrs(pool->attrs, attrs);
3992 pool->node = target_node;
3995 * no_numa isn't a worker_pool attribute, always clear it. See
3996 * 'struct workqueue_attrs' comments for detail.
3998 pool->attrs->no_numa = false;
4000 if (worker_pool_assign_id(pool) < 0)
4003 /* create and start the initial worker */
4004 if (wq_online && !create_worker(pool))
4008 hash_add(unbound_pool_hash, &pool->hash_node, hash);
4013 put_unbound_pool(pool);
4017 static void rcu_free_pwq(struct rcu_head *rcu)
4019 kmem_cache_free(pwq_cache,
4020 container_of(rcu, struct pool_workqueue, rcu));
4024 * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
4025 * and needs to be destroyed.
4027 static void pwq_unbound_release_workfn(struct work_struct *work)
4029 struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
4030 unbound_release_work);
4031 struct workqueue_struct *wq = pwq->wq;
4032 struct worker_pool *pool = pwq->pool;
4033 bool is_last = false;
4036 * when @pwq is not linked, it doesn't hold any reference to the
4037 * @wq, and @wq is invalid to access.
4039 if (!list_empty(&pwq->pwqs_node)) {
4040 if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
4043 mutex_lock(&wq->mutex);
4044 list_del_rcu(&pwq->pwqs_node);
4045 is_last = list_empty(&wq->pwqs);
4046 mutex_unlock(&wq->mutex);
4049 mutex_lock(&wq_pool_mutex);
4050 put_unbound_pool(pool);
4051 mutex_unlock(&wq_pool_mutex);
4053 call_rcu(&pwq->rcu, rcu_free_pwq);
4056 * If we're the last pwq going away, @wq is already dead and no one
4057 * is gonna access it anymore. Schedule RCU free.
4060 wq_unregister_lockdep(wq);
4061 call_rcu(&wq->rcu, rcu_free_wq);
4066 * pwq_adjust_max_active - update a pwq's max_active to the current setting
4067 * @pwq: target pool_workqueue
4069 * If @pwq isn't freezing, set @pwq->max_active to the associated
4070 * workqueue's saved_max_active and activate inactive work items
4071 * accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
4073 static void pwq_adjust_max_active(struct pool_workqueue *pwq)
4075 struct workqueue_struct *wq = pwq->wq;
4076 bool freezable = wq->flags & WQ_FREEZABLE;
4077 unsigned long flags;
4079 /* for @wq->saved_max_active */
4080 lockdep_assert_held(&wq->mutex);
4082 /* fast exit for non-freezable wqs */
4083 if (!freezable && pwq->max_active == wq->saved_max_active)
4086 /* this function can be called during early boot w/ irq disabled */
4087 raw_spin_lock_irqsave(&pwq->pool->lock, flags);
4090 * During [un]freezing, the caller is responsible for ensuring that
4091 * this function is called at least once after @workqueue_freezing
4092 * is updated and visible.
4094 if (!freezable || !workqueue_freezing) {
4097 pwq->max_active = wq->saved_max_active;
4099 while (!list_empty(&pwq->inactive_works) &&
4100 pwq->nr_active < pwq->max_active) {
4101 pwq_activate_first_inactive(pwq);
4106 * Need to kick a worker after thawed or an unbound wq's
4107 * max_active is bumped. In realtime scenarios, always kicking a
4108 * worker will cause interference on the isolated cpu cores, so
4109 * let's kick iff work items were activated.
4112 wake_up_worker(pwq->pool);
4114 pwq->max_active = 0;
4117 raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
4120 /* initialize newly allocated @pwq which is associated with @wq and @pool */
4121 static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
4122 struct worker_pool *pool)
4124 BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
4126 memset(pwq, 0, sizeof(*pwq));
4130 pwq->flush_color = -1;
4132 INIT_LIST_HEAD(&pwq->inactive_works);
4133 INIT_LIST_HEAD(&pwq->pwqs_node);
4134 INIT_LIST_HEAD(&pwq->mayday_node);
4135 INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
4138 /* sync @pwq with the current state of its associated wq and link it */
4139 static void link_pwq(struct pool_workqueue *pwq)
4141 struct workqueue_struct *wq = pwq->wq;
4143 lockdep_assert_held(&wq->mutex);
4145 /* may be called multiple times, ignore if already linked */
4146 if (!list_empty(&pwq->pwqs_node))
4149 /* set the matching work_color */
4150 pwq->work_color = wq->work_color;
4152 /* sync max_active to the current setting */
4153 pwq_adjust_max_active(pwq);
4156 list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
4159 /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
4160 static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
4161 const struct workqueue_attrs *attrs)
4163 struct worker_pool *pool;
4164 struct pool_workqueue *pwq;
4166 lockdep_assert_held(&wq_pool_mutex);
4168 pool = get_unbound_pool(attrs);
4172 pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
4174 put_unbound_pool(pool);
4178 init_pwq(pwq, wq, pool);
4183 * wq_calc_node_cpumask - calculate a wq_attrs' cpumask for the specified node
4184 * @attrs: the wq_attrs of the default pwq of the target workqueue
4185 * @node: the target NUMA node
4186 * @cpu_going_down: if >= 0, the CPU to consider as offline
4187 * @cpumask: outarg, the resulting cpumask
4189 * Calculate the cpumask a workqueue with @attrs should use on @node. If
4190 * @cpu_going_down is >= 0, that cpu is considered offline during
4191 * calculation. The result is stored in @cpumask.
4193 * If NUMA affinity is not enabled, @attrs->cpumask is always used. If
4194 * enabled and @node has online CPUs requested by @attrs, the returned
4195 * cpumask is the intersection of the possible CPUs of @node and
4198 * The caller is responsible for ensuring that the cpumask of @node stays
4201 * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
4204 static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
4205 int cpu_going_down, cpumask_t *cpumask)
4207 if (!wq_numa_enabled || attrs->no_numa)
4210 /* does @node have any online CPUs @attrs wants? */
4211 cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
4212 if (cpu_going_down >= 0)
4213 cpumask_clear_cpu(cpu_going_down, cpumask);
4215 if (cpumask_empty(cpumask))
4218 /* yeap, return possible CPUs in @node that @attrs wants */
4219 cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
4221 if (cpumask_empty(cpumask)) {
4222 pr_warn_once("WARNING: workqueue cpumask: online intersect > "
4223 "possible intersect\n");
4227 return !cpumask_equal(cpumask, attrs->cpumask);
4230 cpumask_copy(cpumask, attrs->cpumask);
4234 /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
4235 static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
4237 struct pool_workqueue *pwq)
4239 struct pool_workqueue *old_pwq;
4241 lockdep_assert_held(&wq_pool_mutex);
4242 lockdep_assert_held(&wq->mutex);
4244 /* link_pwq() can handle duplicate calls */
4247 old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
4248 rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
4252 /* context to store the prepared attrs & pwqs before applying */
4253 struct apply_wqattrs_ctx {
4254 struct workqueue_struct *wq; /* target workqueue */
4255 struct workqueue_attrs *attrs; /* attrs to apply */
4256 struct list_head list; /* queued for batching commit */
4257 struct pool_workqueue *dfl_pwq;
4258 struct pool_workqueue *pwq_tbl[];
4261 /* free the resources after success or abort */
4262 static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
4268 put_pwq_unlocked(ctx->pwq_tbl[node]);
4269 put_pwq_unlocked(ctx->dfl_pwq);
4271 free_workqueue_attrs(ctx->attrs);
4277 /* allocate the attrs and pwqs for later installation */
4278 static struct apply_wqattrs_ctx *
4279 apply_wqattrs_prepare(struct workqueue_struct *wq,
4280 const struct workqueue_attrs *attrs,
4281 const cpumask_var_t unbound_cpumask)
4283 struct apply_wqattrs_ctx *ctx;
4284 struct workqueue_attrs *new_attrs, *tmp_attrs;
4287 lockdep_assert_held(&wq_pool_mutex);
4289 ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_node_ids), GFP_KERNEL);
4291 new_attrs = alloc_workqueue_attrs();
4292 tmp_attrs = alloc_workqueue_attrs();
4293 if (!ctx || !new_attrs || !tmp_attrs)
4297 * Calculate the attrs of the default pwq with unbound_cpumask
4298 * which is wq_unbound_cpumask or to set to wq_unbound_cpumask.
4299 * If the user configured cpumask doesn't overlap with the
4300 * wq_unbound_cpumask, we fallback to the wq_unbound_cpumask.
4302 copy_workqueue_attrs(new_attrs, attrs);
4303 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, unbound_cpumask);
4304 if (unlikely(cpumask_empty(new_attrs->cpumask)))
4305 cpumask_copy(new_attrs->cpumask, unbound_cpumask);
4308 * We may create multiple pwqs with differing cpumasks. Make a
4309 * copy of @new_attrs which will be modified and used to obtain
4312 copy_workqueue_attrs(tmp_attrs, new_attrs);
4315 * If something goes wrong during CPU up/down, we'll fall back to
4316 * the default pwq covering whole @attrs->cpumask. Always create
4317 * it even if we don't use it immediately.
4319 ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
4323 for_each_node(node) {
4324 if (wq_calc_node_cpumask(new_attrs, node, -1, tmp_attrs->cpumask)) {
4325 ctx->pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
4326 if (!ctx->pwq_tbl[node])
4329 ctx->dfl_pwq->refcnt++;
4330 ctx->pwq_tbl[node] = ctx->dfl_pwq;
4334 /* save the user configured attrs and sanitize it. */
4335 copy_workqueue_attrs(new_attrs, attrs);
4336 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
4337 ctx->attrs = new_attrs;
4340 free_workqueue_attrs(tmp_attrs);
4344 free_workqueue_attrs(tmp_attrs);
4345 free_workqueue_attrs(new_attrs);
4346 apply_wqattrs_cleanup(ctx);
4350 /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
4351 static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
4355 /* all pwqs have been created successfully, let's install'em */
4356 mutex_lock(&ctx->wq->mutex);
4358 copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
4360 /* save the previous pwq and install the new one */
4362 ctx->pwq_tbl[node] = numa_pwq_tbl_install(ctx->wq, node,
4363 ctx->pwq_tbl[node]);
4365 /* @dfl_pwq might not have been used, ensure it's linked */
4366 link_pwq(ctx->dfl_pwq);
4367 swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
4369 mutex_unlock(&ctx->wq->mutex);
4372 static void apply_wqattrs_lock(void)
4374 /* CPUs should stay stable across pwq creations and installations */
4376 mutex_lock(&wq_pool_mutex);
4379 static void apply_wqattrs_unlock(void)
4381 mutex_unlock(&wq_pool_mutex);
4385 static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
4386 const struct workqueue_attrs *attrs)
4388 struct apply_wqattrs_ctx *ctx;
4390 /* only unbound workqueues can change attributes */
4391 if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
4394 /* creating multiple pwqs breaks ordering guarantee */
4395 if (!list_empty(&wq->pwqs)) {
4396 if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
4399 wq->flags &= ~__WQ_ORDERED;
4402 ctx = apply_wqattrs_prepare(wq, attrs, wq_unbound_cpumask);
4406 /* the ctx has been prepared successfully, let's commit it */
4407 apply_wqattrs_commit(ctx);
4408 apply_wqattrs_cleanup(ctx);
4414 * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
4415 * @wq: the target workqueue
4416 * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
4418 * Apply @attrs to an unbound workqueue @wq. Unless disabled, on NUMA
4419 * machines, this function maps a separate pwq to each NUMA node with
4420 * possibles CPUs in @attrs->cpumask so that work items are affine to the
4421 * NUMA node it was issued on. Older pwqs are released as in-flight work
4422 * items finish. Note that a work item which repeatedly requeues itself
4423 * back-to-back will stay on its current pwq.
4425 * Performs GFP_KERNEL allocations.
4427 * Assumes caller has CPU hotplug read exclusion, i.e. cpus_read_lock().
4429 * Return: 0 on success and -errno on failure.
4431 int apply_workqueue_attrs(struct workqueue_struct *wq,
4432 const struct workqueue_attrs *attrs)
4436 lockdep_assert_cpus_held();
4438 mutex_lock(&wq_pool_mutex);
4439 ret = apply_workqueue_attrs_locked(wq, attrs);
4440 mutex_unlock(&wq_pool_mutex);
4446 * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
4447 * @wq: the target workqueue
4448 * @cpu: the CPU coming up or going down
4449 * @online: whether @cpu is coming up or going down
4451 * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
4452 * %CPU_DOWN_FAILED. @cpu is being hot[un]plugged, update NUMA affinity of
4455 * If NUMA affinity can't be adjusted due to memory allocation failure, it
4456 * falls back to @wq->dfl_pwq which may not be optimal but is always
4459 * Note that when the last allowed CPU of a NUMA node goes offline for a
4460 * workqueue with a cpumask spanning multiple nodes, the workers which were
4461 * already executing the work items for the workqueue will lose their CPU
4462 * affinity and may execute on any CPU. This is similar to how per-cpu
4463 * workqueues behave on CPU_DOWN. If a workqueue user wants strict
4464 * affinity, it's the user's responsibility to flush the work item from
4467 static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
4470 int node = cpu_to_node(cpu);
4471 int cpu_off = online ? -1 : cpu;
4472 struct pool_workqueue *old_pwq = NULL, *pwq;
4473 struct workqueue_attrs *target_attrs;
4476 lockdep_assert_held(&wq_pool_mutex);
4478 if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND) ||
4479 wq->unbound_attrs->no_numa)
4483 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
4484 * Let's use a preallocated one. The following buf is protected by
4485 * CPU hotplug exclusion.
4487 target_attrs = wq_update_unbound_numa_attrs_buf;
4488 cpumask = target_attrs->cpumask;
4490 copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
4491 pwq = unbound_pwq_by_node(wq, node);
4494 * Let's determine what needs to be done. If the target cpumask is
4495 * different from the default pwq's, we need to compare it to @pwq's
4496 * and create a new one if they don't match. If the target cpumask
4497 * equals the default pwq's, the default pwq should be used.
4499 if (wq_calc_node_cpumask(wq->dfl_pwq->pool->attrs, node, cpu_off, cpumask)) {
4500 if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
4506 /* create a new pwq */
4507 pwq = alloc_unbound_pwq(wq, target_attrs);
4509 pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
4514 /* Install the new pwq. */
4515 mutex_lock(&wq->mutex);
4516 old_pwq = numa_pwq_tbl_install(wq, node, pwq);
4520 mutex_lock(&wq->mutex);
4521 raw_spin_lock_irq(&wq->dfl_pwq->pool->lock);
4522 get_pwq(wq->dfl_pwq);
4523 raw_spin_unlock_irq(&wq->dfl_pwq->pool->lock);
4524 old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
4526 mutex_unlock(&wq->mutex);
4527 put_pwq_unlocked(old_pwq);
4530 static int alloc_and_link_pwqs(struct workqueue_struct *wq)
4532 bool highpri = wq->flags & WQ_HIGHPRI;
4535 if (!(wq->flags & WQ_UNBOUND)) {
4536 wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
4540 for_each_possible_cpu(cpu) {
4541 struct pool_workqueue *pwq =
4542 per_cpu_ptr(wq->cpu_pwqs, cpu);
4543 struct worker_pool *cpu_pools =
4544 per_cpu(cpu_worker_pools, cpu);
4546 init_pwq(pwq, wq, &cpu_pools[highpri]);
4548 mutex_lock(&wq->mutex);
4550 mutex_unlock(&wq->mutex);
4556 if (wq->flags & __WQ_ORDERED) {
4557 ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
4558 /* there should only be single pwq for ordering guarantee */
4559 WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
4560 wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
4561 "ordering guarantee broken for workqueue %s\n", wq->name);
4563 ret = apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
4570 static int wq_clamp_max_active(int max_active, unsigned int flags,
4573 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
4575 if (max_active < 1 || max_active > lim)
4576 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
4577 max_active, name, 1, lim);
4579 return clamp_val(max_active, 1, lim);
4583 * Workqueues which may be used during memory reclaim should have a rescuer
4584 * to guarantee forward progress.
4586 static int init_rescuer(struct workqueue_struct *wq)
4588 struct worker *rescuer;
4591 if (!(wq->flags & WQ_MEM_RECLAIM))
4594 rescuer = alloc_worker(NUMA_NO_NODE);
4596 pr_err("workqueue: Failed to allocate a rescuer for wq \"%s\"\n",
4601 rescuer->rescue_wq = wq;
4602 rescuer->task = kthread_create(rescuer_thread, rescuer, "%s", wq->name);
4603 if (IS_ERR(rescuer->task)) {
4604 ret = PTR_ERR(rescuer->task);
4605 pr_err("workqueue: Failed to create a rescuer kthread for wq \"%s\": %pe",
4606 wq->name, ERR_PTR(ret));
4611 wq->rescuer = rescuer;
4612 kthread_bind_mask(rescuer->task, cpu_possible_mask);
4613 wake_up_process(rescuer->task);
4619 struct workqueue_struct *alloc_workqueue(const char *fmt,
4621 int max_active, ...)
4623 size_t tbl_size = 0;
4625 struct workqueue_struct *wq;
4626 struct pool_workqueue *pwq;
4629 * Unbound && max_active == 1 used to imply ordered, which is no
4630 * longer the case on NUMA machines due to per-node pools. While
4631 * alloc_ordered_workqueue() is the right way to create an ordered
4632 * workqueue, keep the previous behavior to avoid subtle breakages
4635 if ((flags & WQ_UNBOUND) && max_active == 1)
4636 flags |= __WQ_ORDERED;
4638 /* see the comment above the definition of WQ_POWER_EFFICIENT */
4639 if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
4640 flags |= WQ_UNBOUND;
4642 /* allocate wq and format name */
4643 if (flags & WQ_UNBOUND)
4644 tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
4646 wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
4650 if (flags & WQ_UNBOUND) {
4651 wq->unbound_attrs = alloc_workqueue_attrs();
4652 if (!wq->unbound_attrs)
4656 va_start(args, max_active);
4657 vsnprintf(wq->name, sizeof(wq->name), fmt, args);
4660 max_active = max_active ?: WQ_DFL_ACTIVE;
4661 max_active = wq_clamp_max_active(max_active, flags, wq->name);
4665 wq->saved_max_active = max_active;
4666 mutex_init(&wq->mutex);
4667 atomic_set(&wq->nr_pwqs_to_flush, 0);
4668 INIT_LIST_HEAD(&wq->pwqs);
4669 INIT_LIST_HEAD(&wq->flusher_queue);
4670 INIT_LIST_HEAD(&wq->flusher_overflow);
4671 INIT_LIST_HEAD(&wq->maydays);
4673 wq_init_lockdep(wq);
4674 INIT_LIST_HEAD(&wq->list);
4676 if (alloc_and_link_pwqs(wq) < 0)
4677 goto err_unreg_lockdep;
4679 if (wq_online && init_rescuer(wq) < 0)
4682 if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
4686 * wq_pool_mutex protects global freeze state and workqueues list.
4687 * Grab it, adjust max_active and add the new @wq to workqueues
4690 mutex_lock(&wq_pool_mutex);
4692 mutex_lock(&wq->mutex);
4693 for_each_pwq(pwq, wq)
4694 pwq_adjust_max_active(pwq);
4695 mutex_unlock(&wq->mutex);
4697 list_add_tail_rcu(&wq->list, &workqueues);
4699 mutex_unlock(&wq_pool_mutex);
4704 wq_unregister_lockdep(wq);
4705 wq_free_lockdep(wq);
4707 free_workqueue_attrs(wq->unbound_attrs);
4711 destroy_workqueue(wq);
4714 EXPORT_SYMBOL_GPL(alloc_workqueue);
4716 static bool pwq_busy(struct pool_workqueue *pwq)
4720 for (i = 0; i < WORK_NR_COLORS; i++)
4721 if (pwq->nr_in_flight[i])
4724 if ((pwq != pwq->wq->dfl_pwq) && (pwq->refcnt > 1))
4726 if (pwq->nr_active || !list_empty(&pwq->inactive_works))
4733 * destroy_workqueue - safely terminate a workqueue
4734 * @wq: target workqueue
4736 * Safely destroy a workqueue. All work currently pending will be done first.
4738 void destroy_workqueue(struct workqueue_struct *wq)
4740 struct pool_workqueue *pwq;
4744 * Remove it from sysfs first so that sanity check failure doesn't
4745 * lead to sysfs name conflicts.
4747 workqueue_sysfs_unregister(wq);
4749 /* mark the workqueue destruction is in progress */
4750 mutex_lock(&wq->mutex);
4751 wq->flags |= __WQ_DESTROYING;
4752 mutex_unlock(&wq->mutex);
4754 /* drain it before proceeding with destruction */
4755 drain_workqueue(wq);
4757 /* kill rescuer, if sanity checks fail, leave it w/o rescuer */
4759 struct worker *rescuer = wq->rescuer;
4761 /* this prevents new queueing */
4762 raw_spin_lock_irq(&wq_mayday_lock);
4764 raw_spin_unlock_irq(&wq_mayday_lock);
4766 /* rescuer will empty maydays list before exiting */
4767 kthread_stop(rescuer->task);
4772 * Sanity checks - grab all the locks so that we wait for all
4773 * in-flight operations which may do put_pwq().
4775 mutex_lock(&wq_pool_mutex);
4776 mutex_lock(&wq->mutex);
4777 for_each_pwq(pwq, wq) {
4778 raw_spin_lock_irq(&pwq->pool->lock);
4779 if (WARN_ON(pwq_busy(pwq))) {
4780 pr_warn("%s: %s has the following busy pwq\n",
4781 __func__, wq->name);
4783 raw_spin_unlock_irq(&pwq->pool->lock);
4784 mutex_unlock(&wq->mutex);
4785 mutex_unlock(&wq_pool_mutex);
4786 show_one_workqueue(wq);
4789 raw_spin_unlock_irq(&pwq->pool->lock);
4791 mutex_unlock(&wq->mutex);
4794 * wq list is used to freeze wq, remove from list after
4795 * flushing is complete in case freeze races us.
4797 list_del_rcu(&wq->list);
4798 mutex_unlock(&wq_pool_mutex);
4800 if (!(wq->flags & WQ_UNBOUND)) {
4801 wq_unregister_lockdep(wq);
4803 * The base ref is never dropped on per-cpu pwqs. Directly
4804 * schedule RCU free.
4806 call_rcu(&wq->rcu, rcu_free_wq);
4809 * We're the sole accessor of @wq at this point. Directly
4810 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
4811 * @wq will be freed when the last pwq is released.
4813 for_each_node(node) {
4814 pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
4815 RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
4816 put_pwq_unlocked(pwq);
4820 * Put dfl_pwq. @wq may be freed any time after dfl_pwq is
4821 * put. Don't access it afterwards.
4825 put_pwq_unlocked(pwq);
4828 EXPORT_SYMBOL_GPL(destroy_workqueue);
4831 * workqueue_set_max_active - adjust max_active of a workqueue
4832 * @wq: target workqueue
4833 * @max_active: new max_active value.
4835 * Set max_active of @wq to @max_active.
4838 * Don't call from IRQ context.
4840 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4842 struct pool_workqueue *pwq;
4844 /* disallow meddling with max_active for ordered workqueues */
4845 if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
4848 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4850 mutex_lock(&wq->mutex);
4852 wq->flags &= ~__WQ_ORDERED;
4853 wq->saved_max_active = max_active;
4855 for_each_pwq(pwq, wq)
4856 pwq_adjust_max_active(pwq);
4858 mutex_unlock(&wq->mutex);
4860 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4863 * current_work - retrieve %current task's work struct
4865 * Determine if %current task is a workqueue worker and what it's working on.
4866 * Useful to find out the context that the %current task is running in.
4868 * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
4870 struct work_struct *current_work(void)
4872 struct worker *worker = current_wq_worker();
4874 return worker ? worker->current_work : NULL;
4876 EXPORT_SYMBOL(current_work);
4879 * current_is_workqueue_rescuer - is %current workqueue rescuer?
4881 * Determine whether %current is a workqueue rescuer. Can be used from
4882 * work functions to determine whether it's being run off the rescuer task.
4884 * Return: %true if %current is a workqueue rescuer. %false otherwise.
4886 bool current_is_workqueue_rescuer(void)
4888 struct worker *worker = current_wq_worker();
4890 return worker && worker->rescue_wq;
4894 * workqueue_congested - test whether a workqueue is congested
4895 * @cpu: CPU in question
4896 * @wq: target workqueue
4898 * Test whether @wq's cpu workqueue for @cpu is congested. There is
4899 * no synchronization around this function and the test result is
4900 * unreliable and only useful as advisory hints or for debugging.
4902 * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4903 * Note that both per-cpu and unbound workqueues may be associated with
4904 * multiple pool_workqueues which have separate congested states. A
4905 * workqueue being congested on one CPU doesn't mean the workqueue is also
4906 * contested on other CPUs / NUMA nodes.
4909 * %true if congested, %false otherwise.
4911 bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4913 struct pool_workqueue *pwq;
4919 if (cpu == WORK_CPU_UNBOUND)
4920 cpu = smp_processor_id();
4922 if (!(wq->flags & WQ_UNBOUND))
4923 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
4925 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4927 ret = !list_empty(&pwq->inactive_works);
4933 EXPORT_SYMBOL_GPL(workqueue_congested);
4936 * work_busy - test whether a work is currently pending or running
4937 * @work: the work to be tested
4939 * Test whether @work is currently pending or running. There is no
4940 * synchronization around this function and the test result is
4941 * unreliable and only useful as advisory hints or for debugging.
4944 * OR'd bitmask of WORK_BUSY_* bits.
4946 unsigned int work_busy(struct work_struct *work)
4948 struct worker_pool *pool;
4949 unsigned long flags;
4950 unsigned int ret = 0;
4952 if (work_pending(work))
4953 ret |= WORK_BUSY_PENDING;
4956 pool = get_work_pool(work);
4958 raw_spin_lock_irqsave(&pool->lock, flags);
4959 if (find_worker_executing_work(pool, work))
4960 ret |= WORK_BUSY_RUNNING;
4961 raw_spin_unlock_irqrestore(&pool->lock, flags);
4967 EXPORT_SYMBOL_GPL(work_busy);
4970 * set_worker_desc - set description for the current work item
4971 * @fmt: printf-style format string
4972 * @...: arguments for the format string
4974 * This function can be called by a running work function to describe what
4975 * the work item is about. If the worker task gets dumped, this
4976 * information will be printed out together to help debugging. The
4977 * description can be at most WORKER_DESC_LEN including the trailing '\0'.
4979 void set_worker_desc(const char *fmt, ...)
4981 struct worker *worker = current_wq_worker();
4985 va_start(args, fmt);
4986 vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
4990 EXPORT_SYMBOL_GPL(set_worker_desc);
4993 * print_worker_info - print out worker information and description
4994 * @log_lvl: the log level to use when printing
4995 * @task: target task
4997 * If @task is a worker and currently executing a work item, print out the
4998 * name of the workqueue being serviced and worker description set with
4999 * set_worker_desc() by the currently executing work item.
5001 * This function can be safely called on any task as long as the
5002 * task_struct itself is accessible. While safe, this function isn't
5003 * synchronized and may print out mixups or garbages of limited length.
5005 void print_worker_info(const char *log_lvl, struct task_struct *task)
5007 work_func_t *fn = NULL;
5008 char name[WQ_NAME_LEN] = { };
5009 char desc[WORKER_DESC_LEN] = { };
5010 struct pool_workqueue *pwq = NULL;
5011 struct workqueue_struct *wq = NULL;
5012 struct worker *worker;
5014 if (!(task->flags & PF_WQ_WORKER))
5018 * This function is called without any synchronization and @task
5019 * could be in any state. Be careful with dereferences.
5021 worker = kthread_probe_data(task);
5024 * Carefully copy the associated workqueue's workfn, name and desc.
5025 * Keep the original last '\0' in case the original is garbage.
5027 copy_from_kernel_nofault(&fn, &worker->current_func, sizeof(fn));
5028 copy_from_kernel_nofault(&pwq, &worker->current_pwq, sizeof(pwq));
5029 copy_from_kernel_nofault(&wq, &pwq->wq, sizeof(wq));
5030 copy_from_kernel_nofault(name, wq->name, sizeof(name) - 1);
5031 copy_from_kernel_nofault(desc, worker->desc, sizeof(desc) - 1);
5033 if (fn || name[0] || desc[0]) {
5034 printk("%sWorkqueue: %s %ps", log_lvl, name, fn);
5035 if (strcmp(name, desc))
5036 pr_cont(" (%s)", desc);
5041 static void pr_cont_pool_info(struct worker_pool *pool)
5043 pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
5044 if (pool->node != NUMA_NO_NODE)
5045 pr_cont(" node=%d", pool->node);
5046 pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
5049 struct pr_cont_work_struct {
5055 static void pr_cont_work_flush(bool comma, work_func_t func, struct pr_cont_work_struct *pcwsp)
5059 if (func == pcwsp->func) {
5063 if (pcwsp->ctr == 1)
5064 pr_cont("%s %ps", pcwsp->comma ? "," : "", pcwsp->func);
5066 pr_cont("%s %ld*%ps", pcwsp->comma ? "," : "", pcwsp->ctr, pcwsp->func);
5069 if ((long)func == -1L)
5071 pcwsp->comma = comma;
5076 static void pr_cont_work(bool comma, struct work_struct *work, struct pr_cont_work_struct *pcwsp)
5078 if (work->func == wq_barrier_func) {
5079 struct wq_barrier *barr;
5081 barr = container_of(work, struct wq_barrier, work);
5083 pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
5084 pr_cont("%s BAR(%d)", comma ? "," : "",
5085 task_pid_nr(barr->task));
5088 pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
5089 pr_cont_work_flush(comma, work->func, pcwsp);
5093 static void show_pwq(struct pool_workqueue *pwq)
5095 struct pr_cont_work_struct pcws = { .ctr = 0, };
5096 struct worker_pool *pool = pwq->pool;
5097 struct work_struct *work;
5098 struct worker *worker;
5099 bool has_in_flight = false, has_pending = false;
5102 pr_info(" pwq %d:", pool->id);
5103 pr_cont_pool_info(pool);
5105 pr_cont(" active=%d/%d refcnt=%d%s\n",
5106 pwq->nr_active, pwq->max_active, pwq->refcnt,
5107 !list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
5109 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
5110 if (worker->current_pwq == pwq) {
5111 has_in_flight = true;
5115 if (has_in_flight) {
5118 pr_info(" in-flight:");
5119 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
5120 if (worker->current_pwq != pwq)
5123 pr_cont("%s %d%s:%ps", comma ? "," : "",
5124 task_pid_nr(worker->task),
5125 worker->rescue_wq ? "(RESCUER)" : "",
5126 worker->current_func);
5127 list_for_each_entry(work, &worker->scheduled, entry)
5128 pr_cont_work(false, work, &pcws);
5129 pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
5135 list_for_each_entry(work, &pool->worklist, entry) {
5136 if (get_work_pwq(work) == pwq) {
5144 pr_info(" pending:");
5145 list_for_each_entry(work, &pool->worklist, entry) {
5146 if (get_work_pwq(work) != pwq)
5149 pr_cont_work(comma, work, &pcws);
5150 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
5152 pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
5156 if (!list_empty(&pwq->inactive_works)) {
5159 pr_info(" inactive:");
5160 list_for_each_entry(work, &pwq->inactive_works, entry) {
5161 pr_cont_work(comma, work, &pcws);
5162 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
5164 pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
5170 * show_one_workqueue - dump state of specified workqueue
5171 * @wq: workqueue whose state will be printed
5173 void show_one_workqueue(struct workqueue_struct *wq)
5175 struct pool_workqueue *pwq;
5177 unsigned long flags;
5179 for_each_pwq(pwq, wq) {
5180 if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
5185 if (idle) /* Nothing to print for idle workqueue */
5188 pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
5190 for_each_pwq(pwq, wq) {
5191 raw_spin_lock_irqsave(&pwq->pool->lock, flags);
5192 if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
5194 * Defer printing to avoid deadlocks in console
5195 * drivers that queue work while holding locks
5196 * also taken in their write paths.
5198 printk_deferred_enter();
5200 printk_deferred_exit();
5202 raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
5204 * We could be printing a lot from atomic context, e.g.
5205 * sysrq-t -> show_all_workqueues(). Avoid triggering
5208 touch_nmi_watchdog();
5214 * show_one_worker_pool - dump state of specified worker pool
5215 * @pool: worker pool whose state will be printed
5217 static void show_one_worker_pool(struct worker_pool *pool)
5219 struct worker *worker;
5221 unsigned long flags;
5222 unsigned long hung = 0;
5224 raw_spin_lock_irqsave(&pool->lock, flags);
5225 if (pool->nr_workers == pool->nr_idle)
5228 /* How long the first pending work is waiting for a worker. */
5229 if (!list_empty(&pool->worklist))
5230 hung = jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000;
5233 * Defer printing to avoid deadlocks in console drivers that
5234 * queue work while holding locks also taken in their write
5237 printk_deferred_enter();
5238 pr_info("pool %d:", pool->id);
5239 pr_cont_pool_info(pool);
5240 pr_cont(" hung=%lus workers=%d", hung, pool->nr_workers);
5242 pr_cont(" manager: %d",
5243 task_pid_nr(pool->manager->task));
5244 list_for_each_entry(worker, &pool->idle_list, entry) {
5245 pr_cont(" %s%d", first ? "idle: " : "",
5246 task_pid_nr(worker->task));
5250 printk_deferred_exit();
5252 raw_spin_unlock_irqrestore(&pool->lock, flags);
5254 * We could be printing a lot from atomic context, e.g.
5255 * sysrq-t -> show_all_workqueues(). Avoid triggering
5258 touch_nmi_watchdog();
5263 * show_all_workqueues - dump workqueue state
5265 * Called from a sysrq handler and prints out all busy workqueues and pools.
5267 void show_all_workqueues(void)
5269 struct workqueue_struct *wq;
5270 struct worker_pool *pool;
5275 pr_info("Showing busy workqueues and worker pools:\n");
5277 list_for_each_entry_rcu(wq, &workqueues, list)
5278 show_one_workqueue(wq);
5280 for_each_pool(pool, pi)
5281 show_one_worker_pool(pool);
5287 * show_freezable_workqueues - dump freezable workqueue state
5289 * Called from try_to_freeze_tasks() and prints out all freezable workqueues
5292 void show_freezable_workqueues(void)
5294 struct workqueue_struct *wq;
5298 pr_info("Showing freezable workqueues that are still busy:\n");
5300 list_for_each_entry_rcu(wq, &workqueues, list) {
5301 if (!(wq->flags & WQ_FREEZABLE))
5303 show_one_workqueue(wq);
5309 /* used to show worker information through /proc/PID/{comm,stat,status} */
5310 void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
5314 /* always show the actual comm */
5315 off = strscpy(buf, task->comm, size);
5319 /* stabilize PF_WQ_WORKER and worker pool association */
5320 mutex_lock(&wq_pool_attach_mutex);
5322 if (task->flags & PF_WQ_WORKER) {
5323 struct worker *worker = kthread_data(task);
5324 struct worker_pool *pool = worker->pool;
5327 raw_spin_lock_irq(&pool->lock);
5329 * ->desc tracks information (wq name or
5330 * set_worker_desc()) for the latest execution. If
5331 * current, prepend '+', otherwise '-'.
5333 if (worker->desc[0] != '\0') {
5334 if (worker->current_work)
5335 scnprintf(buf + off, size - off, "+%s",
5338 scnprintf(buf + off, size - off, "-%s",
5341 raw_spin_unlock_irq(&pool->lock);
5345 mutex_unlock(&wq_pool_attach_mutex);
5353 * There are two challenges in supporting CPU hotplug. Firstly, there
5354 * are a lot of assumptions on strong associations among work, pwq and
5355 * pool which make migrating pending and scheduled works very
5356 * difficult to implement without impacting hot paths. Secondly,
5357 * worker pools serve mix of short, long and very long running works making
5358 * blocked draining impractical.
5360 * This is solved by allowing the pools to be disassociated from the CPU
5361 * running as an unbound one and allowing it to be reattached later if the
5362 * cpu comes back online.
5365 static void unbind_workers(int cpu)
5367 struct worker_pool *pool;
5368 struct worker *worker;
5370 for_each_cpu_worker_pool(pool, cpu) {
5371 mutex_lock(&wq_pool_attach_mutex);
5372 raw_spin_lock_irq(&pool->lock);
5375 * We've blocked all attach/detach operations. Make all workers
5376 * unbound and set DISASSOCIATED. Before this, all workers
5377 * must be on the cpu. After this, they may become diasporas.
5378 * And the preemption disabled section in their sched callbacks
5379 * are guaranteed to see WORKER_UNBOUND since the code here
5380 * is on the same cpu.
5382 for_each_pool_worker(worker, pool)
5383 worker->flags |= WORKER_UNBOUND;
5385 pool->flags |= POOL_DISASSOCIATED;
5388 * The handling of nr_running in sched callbacks are disabled
5389 * now. Zap nr_running. After this, nr_running stays zero and
5390 * need_more_worker() and keep_working() are always true as
5391 * long as the worklist is not empty. This pool now behaves as
5392 * an unbound (in terms of concurrency management) pool which
5393 * are served by workers tied to the pool.
5395 pool->nr_running = 0;
5398 * With concurrency management just turned off, a busy
5399 * worker blocking could lead to lengthy stalls. Kick off
5400 * unbound chain execution of currently pending work items.
5402 wake_up_worker(pool);
5404 raw_spin_unlock_irq(&pool->lock);
5406 for_each_pool_worker(worker, pool)
5407 unbind_worker(worker);
5409 mutex_unlock(&wq_pool_attach_mutex);
5414 * rebind_workers - rebind all workers of a pool to the associated CPU
5415 * @pool: pool of interest
5417 * @pool->cpu is coming online. Rebind all workers to the CPU.
5419 static void rebind_workers(struct worker_pool *pool)
5421 struct worker *worker;
5423 lockdep_assert_held(&wq_pool_attach_mutex);
5426 * Restore CPU affinity of all workers. As all idle workers should
5427 * be on the run-queue of the associated CPU before any local
5428 * wake-ups for concurrency management happen, restore CPU affinity
5429 * of all workers first and then clear UNBOUND. As we're called
5430 * from CPU_ONLINE, the following shouldn't fail.
5432 for_each_pool_worker(worker, pool) {
5433 kthread_set_per_cpu(worker->task, pool->cpu);
5434 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
5435 pool->attrs->cpumask) < 0);
5438 raw_spin_lock_irq(&pool->lock);
5440 pool->flags &= ~POOL_DISASSOCIATED;
5442 for_each_pool_worker(worker, pool) {
5443 unsigned int worker_flags = worker->flags;
5446 * We want to clear UNBOUND but can't directly call
5447 * worker_clr_flags() or adjust nr_running. Atomically
5448 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
5449 * @worker will clear REBOUND using worker_clr_flags() when
5450 * it initiates the next execution cycle thus restoring
5451 * concurrency management. Note that when or whether
5452 * @worker clears REBOUND doesn't affect correctness.
5454 * WRITE_ONCE() is necessary because @worker->flags may be
5455 * tested without holding any lock in
5456 * wq_worker_running(). Without it, NOT_RUNNING test may
5457 * fail incorrectly leading to premature concurrency
5458 * management operations.
5460 WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
5461 worker_flags |= WORKER_REBOUND;
5462 worker_flags &= ~WORKER_UNBOUND;
5463 WRITE_ONCE(worker->flags, worker_flags);
5466 raw_spin_unlock_irq(&pool->lock);
5470 * restore_unbound_workers_cpumask - restore cpumask of unbound workers
5471 * @pool: unbound pool of interest
5472 * @cpu: the CPU which is coming up
5474 * An unbound pool may end up with a cpumask which doesn't have any online
5475 * CPUs. When a worker of such pool get scheduled, the scheduler resets
5476 * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
5477 * online CPU before, cpus_allowed of all its workers should be restored.
5479 static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
5481 static cpumask_t cpumask;
5482 struct worker *worker;
5484 lockdep_assert_held(&wq_pool_attach_mutex);
5486 /* is @cpu allowed for @pool? */
5487 if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
5490 cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
5492 /* as we're called from CPU_ONLINE, the following shouldn't fail */
5493 for_each_pool_worker(worker, pool)
5494 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
5497 int workqueue_prepare_cpu(unsigned int cpu)
5499 struct worker_pool *pool;
5501 for_each_cpu_worker_pool(pool, cpu) {
5502 if (pool->nr_workers)
5504 if (!create_worker(pool))
5510 int workqueue_online_cpu(unsigned int cpu)
5512 struct worker_pool *pool;
5513 struct workqueue_struct *wq;
5516 mutex_lock(&wq_pool_mutex);
5518 for_each_pool(pool, pi) {
5519 mutex_lock(&wq_pool_attach_mutex);
5521 if (pool->cpu == cpu)
5522 rebind_workers(pool);
5523 else if (pool->cpu < 0)
5524 restore_unbound_workers_cpumask(pool, cpu);
5526 mutex_unlock(&wq_pool_attach_mutex);
5529 /* update NUMA affinity of unbound workqueues */
5530 list_for_each_entry(wq, &workqueues, list)
5531 wq_update_unbound_numa(wq, cpu, true);
5533 mutex_unlock(&wq_pool_mutex);
5537 int workqueue_offline_cpu(unsigned int cpu)
5539 struct workqueue_struct *wq;
5541 /* unbinding per-cpu workers should happen on the local CPU */
5542 if (WARN_ON(cpu != smp_processor_id()))
5545 unbind_workers(cpu);
5547 /* update NUMA affinity of unbound workqueues */
5548 mutex_lock(&wq_pool_mutex);
5549 list_for_each_entry(wq, &workqueues, list)
5550 wq_update_unbound_numa(wq, cpu, false);
5551 mutex_unlock(&wq_pool_mutex);
5556 struct work_for_cpu {
5557 struct work_struct work;
5563 static void work_for_cpu_fn(struct work_struct *work)
5565 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
5567 wfc->ret = wfc->fn(wfc->arg);
5571 * work_on_cpu - run a function in thread context on a particular cpu
5572 * @cpu: the cpu to run on
5573 * @fn: the function to run
5574 * @arg: the function arg
5576 * It is up to the caller to ensure that the cpu doesn't go offline.
5577 * The caller must not hold any locks which would prevent @fn from completing.
5579 * Return: The value @fn returns.
5581 long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
5583 struct work_for_cpu wfc = { .fn = fn, .arg = arg };
5585 INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
5586 schedule_work_on(cpu, &wfc.work);
5587 flush_work(&wfc.work);
5588 destroy_work_on_stack(&wfc.work);
5591 EXPORT_SYMBOL_GPL(work_on_cpu);
5594 * work_on_cpu_safe - run a function in thread context on a particular cpu
5595 * @cpu: the cpu to run on
5596 * @fn: the function to run
5597 * @arg: the function argument
5599 * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
5600 * any locks which would prevent @fn from completing.
5602 * Return: The value @fn returns.
5604 long work_on_cpu_safe(int cpu, long (*fn)(void *), void *arg)
5609 if (cpu_online(cpu))
5610 ret = work_on_cpu(cpu, fn, arg);
5614 EXPORT_SYMBOL_GPL(work_on_cpu_safe);
5615 #endif /* CONFIG_SMP */
5617 #ifdef CONFIG_FREEZER
5620 * freeze_workqueues_begin - begin freezing workqueues
5622 * Start freezing workqueues. After this function returns, all freezable
5623 * workqueues will queue new works to their inactive_works list instead of
5627 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5629 void freeze_workqueues_begin(void)
5631 struct workqueue_struct *wq;
5632 struct pool_workqueue *pwq;
5634 mutex_lock(&wq_pool_mutex);
5636 WARN_ON_ONCE(workqueue_freezing);
5637 workqueue_freezing = true;
5639 list_for_each_entry(wq, &workqueues, list) {
5640 mutex_lock(&wq->mutex);
5641 for_each_pwq(pwq, wq)
5642 pwq_adjust_max_active(pwq);
5643 mutex_unlock(&wq->mutex);
5646 mutex_unlock(&wq_pool_mutex);
5650 * freeze_workqueues_busy - are freezable workqueues still busy?
5652 * Check whether freezing is complete. This function must be called
5653 * between freeze_workqueues_begin() and thaw_workqueues().
5656 * Grabs and releases wq_pool_mutex.
5659 * %true if some freezable workqueues are still busy. %false if freezing
5662 bool freeze_workqueues_busy(void)
5665 struct workqueue_struct *wq;
5666 struct pool_workqueue *pwq;
5668 mutex_lock(&wq_pool_mutex);
5670 WARN_ON_ONCE(!workqueue_freezing);
5672 list_for_each_entry(wq, &workqueues, list) {
5673 if (!(wq->flags & WQ_FREEZABLE))
5676 * nr_active is monotonically decreasing. It's safe
5677 * to peek without lock.
5680 for_each_pwq(pwq, wq) {
5681 WARN_ON_ONCE(pwq->nr_active < 0);
5682 if (pwq->nr_active) {
5691 mutex_unlock(&wq_pool_mutex);
5696 * thaw_workqueues - thaw workqueues
5698 * Thaw workqueues. Normal queueing is restored and all collected
5699 * frozen works are transferred to their respective pool worklists.
5702 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5704 void thaw_workqueues(void)
5706 struct workqueue_struct *wq;
5707 struct pool_workqueue *pwq;
5709 mutex_lock(&wq_pool_mutex);
5711 if (!workqueue_freezing)
5714 workqueue_freezing = false;
5716 /* restore max_active and repopulate worklist */
5717 list_for_each_entry(wq, &workqueues, list) {
5718 mutex_lock(&wq->mutex);
5719 for_each_pwq(pwq, wq)
5720 pwq_adjust_max_active(pwq);
5721 mutex_unlock(&wq->mutex);
5725 mutex_unlock(&wq_pool_mutex);
5727 #endif /* CONFIG_FREEZER */
5729 static int workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask)
5733 struct workqueue_struct *wq;
5734 struct apply_wqattrs_ctx *ctx, *n;
5736 lockdep_assert_held(&wq_pool_mutex);
5738 list_for_each_entry(wq, &workqueues, list) {
5739 if (!(wq->flags & WQ_UNBOUND))
5741 /* creating multiple pwqs breaks ordering guarantee */
5742 if (wq->flags & __WQ_ORDERED)
5745 ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs, unbound_cpumask);
5751 list_add_tail(&ctx->list, &ctxs);
5754 list_for_each_entry_safe(ctx, n, &ctxs, list) {
5756 apply_wqattrs_commit(ctx);
5757 apply_wqattrs_cleanup(ctx);
5761 mutex_lock(&wq_pool_attach_mutex);
5762 cpumask_copy(wq_unbound_cpumask, unbound_cpumask);
5763 mutex_unlock(&wq_pool_attach_mutex);
5769 * workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
5770 * @cpumask: the cpumask to set
5772 * The low-level workqueues cpumask is a global cpumask that limits
5773 * the affinity of all unbound workqueues. This function check the @cpumask
5774 * and apply it to all unbound workqueues and updates all pwqs of them.
5776 * Return: 0 - Success
5777 * -EINVAL - Invalid @cpumask
5778 * -ENOMEM - Failed to allocate memory for attrs or pwqs.
5780 int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
5785 * Not excluding isolated cpus on purpose.
5786 * If the user wishes to include them, we allow that.
5788 cpumask_and(cpumask, cpumask, cpu_possible_mask);
5789 if (!cpumask_empty(cpumask)) {
5790 apply_wqattrs_lock();
5791 if (cpumask_equal(cpumask, wq_unbound_cpumask)) {
5796 ret = workqueue_apply_unbound_cpumask(cpumask);
5799 apply_wqattrs_unlock();
5807 * Workqueues with WQ_SYSFS flag set is visible to userland via
5808 * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
5809 * following attributes.
5811 * per_cpu RO bool : whether the workqueue is per-cpu or unbound
5812 * max_active RW int : maximum number of in-flight work items
5814 * Unbound workqueues have the following extra attributes.
5816 * pool_ids RO int : the associated pool IDs for each node
5817 * nice RW int : nice value of the workers
5818 * cpumask RW mask : bitmask of allowed CPUs for the workers
5819 * numa RW bool : whether enable NUMA affinity
5822 struct workqueue_struct *wq;
5826 static struct workqueue_struct *dev_to_wq(struct device *dev)
5828 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
5833 static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
5836 struct workqueue_struct *wq = dev_to_wq(dev);
5838 return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
5840 static DEVICE_ATTR_RO(per_cpu);
5842 static ssize_t max_active_show(struct device *dev,
5843 struct device_attribute *attr, char *buf)
5845 struct workqueue_struct *wq = dev_to_wq(dev);
5847 return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
5850 static ssize_t max_active_store(struct device *dev,
5851 struct device_attribute *attr, const char *buf,
5854 struct workqueue_struct *wq = dev_to_wq(dev);
5857 if (sscanf(buf, "%d", &val) != 1 || val <= 0)
5860 workqueue_set_max_active(wq, val);
5863 static DEVICE_ATTR_RW(max_active);
5865 static struct attribute *wq_sysfs_attrs[] = {
5866 &dev_attr_per_cpu.attr,
5867 &dev_attr_max_active.attr,
5870 ATTRIBUTE_GROUPS(wq_sysfs);
5872 static ssize_t wq_pool_ids_show(struct device *dev,
5873 struct device_attribute *attr, char *buf)
5875 struct workqueue_struct *wq = dev_to_wq(dev);
5876 const char *delim = "";
5877 int node, written = 0;
5881 for_each_node(node) {
5882 written += scnprintf(buf + written, PAGE_SIZE - written,
5883 "%s%d:%d", delim, node,
5884 unbound_pwq_by_node(wq, node)->pool->id);
5887 written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
5894 static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
5897 struct workqueue_struct *wq = dev_to_wq(dev);
5900 mutex_lock(&wq->mutex);
5901 written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
5902 mutex_unlock(&wq->mutex);
5907 /* prepare workqueue_attrs for sysfs store operations */
5908 static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
5910 struct workqueue_attrs *attrs;
5912 lockdep_assert_held(&wq_pool_mutex);
5914 attrs = alloc_workqueue_attrs();
5918 copy_workqueue_attrs(attrs, wq->unbound_attrs);
5922 static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
5923 const char *buf, size_t count)
5925 struct workqueue_struct *wq = dev_to_wq(dev);
5926 struct workqueue_attrs *attrs;
5929 apply_wqattrs_lock();
5931 attrs = wq_sysfs_prep_attrs(wq);
5935 if (sscanf(buf, "%d", &attrs->nice) == 1 &&
5936 attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
5937 ret = apply_workqueue_attrs_locked(wq, attrs);
5942 apply_wqattrs_unlock();
5943 free_workqueue_attrs(attrs);
5944 return ret ?: count;
5947 static ssize_t wq_cpumask_show(struct device *dev,
5948 struct device_attribute *attr, char *buf)
5950 struct workqueue_struct *wq = dev_to_wq(dev);
5953 mutex_lock(&wq->mutex);
5954 written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
5955 cpumask_pr_args(wq->unbound_attrs->cpumask));
5956 mutex_unlock(&wq->mutex);
5960 static ssize_t wq_cpumask_store(struct device *dev,
5961 struct device_attribute *attr,
5962 const char *buf, size_t count)
5964 struct workqueue_struct *wq = dev_to_wq(dev);
5965 struct workqueue_attrs *attrs;
5968 apply_wqattrs_lock();
5970 attrs = wq_sysfs_prep_attrs(wq);
5974 ret = cpumask_parse(buf, attrs->cpumask);
5976 ret = apply_workqueue_attrs_locked(wq, attrs);
5979 apply_wqattrs_unlock();
5980 free_workqueue_attrs(attrs);
5981 return ret ?: count;
5984 static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
5987 struct workqueue_struct *wq = dev_to_wq(dev);
5990 mutex_lock(&wq->mutex);
5991 written = scnprintf(buf, PAGE_SIZE, "%d\n",
5992 !wq->unbound_attrs->no_numa);
5993 mutex_unlock(&wq->mutex);
5998 static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
5999 const char *buf, size_t count)
6001 struct workqueue_struct *wq = dev_to_wq(dev);
6002 struct workqueue_attrs *attrs;
6003 int v, ret = -ENOMEM;
6005 apply_wqattrs_lock();
6007 attrs = wq_sysfs_prep_attrs(wq);
6012 if (sscanf(buf, "%d", &v) == 1) {
6013 attrs->no_numa = !v;
6014 ret = apply_workqueue_attrs_locked(wq, attrs);
6018 apply_wqattrs_unlock();
6019 free_workqueue_attrs(attrs);
6020 return ret ?: count;
6023 static struct device_attribute wq_sysfs_unbound_attrs[] = {
6024 __ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
6025 __ATTR(nice, 0644, wq_nice_show, wq_nice_store),
6026 __ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
6027 __ATTR(numa, 0644, wq_numa_show, wq_numa_store),
6031 static struct bus_type wq_subsys = {
6032 .name = "workqueue",
6033 .dev_groups = wq_sysfs_groups,
6036 static ssize_t wq_unbound_cpumask_show(struct device *dev,
6037 struct device_attribute *attr, char *buf)
6041 mutex_lock(&wq_pool_mutex);
6042 written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
6043 cpumask_pr_args(wq_unbound_cpumask));
6044 mutex_unlock(&wq_pool_mutex);
6049 static ssize_t wq_unbound_cpumask_store(struct device *dev,
6050 struct device_attribute *attr, const char *buf, size_t count)
6052 cpumask_var_t cpumask;
6055 if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
6058 ret = cpumask_parse(buf, cpumask);
6060 ret = workqueue_set_unbound_cpumask(cpumask);
6062 free_cpumask_var(cpumask);
6063 return ret ? ret : count;
6066 static struct device_attribute wq_sysfs_cpumask_attr =
6067 __ATTR(cpumask, 0644, wq_unbound_cpumask_show,
6068 wq_unbound_cpumask_store);
6070 static int __init wq_sysfs_init(void)
6072 struct device *dev_root;
6075 err = subsys_virtual_register(&wq_subsys, NULL);
6079 dev_root = bus_get_dev_root(&wq_subsys);
6081 err = device_create_file(dev_root, &wq_sysfs_cpumask_attr);
6082 put_device(dev_root);
6086 core_initcall(wq_sysfs_init);
6088 static void wq_device_release(struct device *dev)
6090 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
6096 * workqueue_sysfs_register - make a workqueue visible in sysfs
6097 * @wq: the workqueue to register
6099 * Expose @wq in sysfs under /sys/bus/workqueue/devices.
6100 * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
6101 * which is the preferred method.
6103 * Workqueue user should use this function directly iff it wants to apply
6104 * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
6105 * apply_workqueue_attrs() may race against userland updating the
6108 * Return: 0 on success, -errno on failure.
6110 int workqueue_sysfs_register(struct workqueue_struct *wq)
6112 struct wq_device *wq_dev;
6116 * Adjusting max_active or creating new pwqs by applying
6117 * attributes breaks ordering guarantee. Disallow exposing ordered
6120 if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
6123 wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
6128 wq_dev->dev.bus = &wq_subsys;
6129 wq_dev->dev.release = wq_device_release;
6130 dev_set_name(&wq_dev->dev, "%s", wq->name);
6133 * unbound_attrs are created separately. Suppress uevent until
6134 * everything is ready.
6136 dev_set_uevent_suppress(&wq_dev->dev, true);
6138 ret = device_register(&wq_dev->dev);
6140 put_device(&wq_dev->dev);
6145 if (wq->flags & WQ_UNBOUND) {
6146 struct device_attribute *attr;
6148 for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
6149 ret = device_create_file(&wq_dev->dev, attr);
6151 device_unregister(&wq_dev->dev);
6158 dev_set_uevent_suppress(&wq_dev->dev, false);
6159 kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
6164 * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
6165 * @wq: the workqueue to unregister
6167 * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
6169 static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
6171 struct wq_device *wq_dev = wq->wq_dev;
6177 device_unregister(&wq_dev->dev);
6179 #else /* CONFIG_SYSFS */
6180 static void workqueue_sysfs_unregister(struct workqueue_struct *wq) { }
6181 #endif /* CONFIG_SYSFS */
6184 * Workqueue watchdog.
6186 * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
6187 * flush dependency, a concurrency managed work item which stays RUNNING
6188 * indefinitely. Workqueue stalls can be very difficult to debug as the
6189 * usual warning mechanisms don't trigger and internal workqueue state is
6192 * Workqueue watchdog monitors all worker pools periodically and dumps
6193 * state if some pools failed to make forward progress for a while where
6194 * forward progress is defined as the first item on ->worklist changing.
6196 * This mechanism is controlled through the kernel parameter
6197 * "workqueue.watchdog_thresh" which can be updated at runtime through the
6198 * corresponding sysfs parameter file.
6200 #ifdef CONFIG_WQ_WATCHDOG
6202 static unsigned long wq_watchdog_thresh = 30;
6203 static struct timer_list wq_watchdog_timer;
6205 static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
6206 static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
6209 * Show workers that might prevent the processing of pending work items.
6210 * The only candidates are CPU-bound workers in the running state.
6211 * Pending work items should be handled by another idle worker
6212 * in all other situations.
6214 static void show_cpu_pool_hog(struct worker_pool *pool)
6216 struct worker *worker;
6217 unsigned long flags;
6220 raw_spin_lock_irqsave(&pool->lock, flags);
6222 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
6223 if (task_is_running(worker->task)) {
6225 * Defer printing to avoid deadlocks in console
6226 * drivers that queue work while holding locks
6227 * also taken in their write paths.
6229 printk_deferred_enter();
6231 pr_info("pool %d:\n", pool->id);
6232 sched_show_task(worker->task);
6234 printk_deferred_exit();
6238 raw_spin_unlock_irqrestore(&pool->lock, flags);
6241 static void show_cpu_pools_hogs(void)
6243 struct worker_pool *pool;
6246 pr_info("Showing backtraces of running workers in stalled CPU-bound worker pools:\n");
6250 for_each_pool(pool, pi) {
6251 if (pool->cpu_stall)
6252 show_cpu_pool_hog(pool);
6259 static void wq_watchdog_reset_touched(void)
6263 wq_watchdog_touched = jiffies;
6264 for_each_possible_cpu(cpu)
6265 per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
6268 static void wq_watchdog_timer_fn(struct timer_list *unused)
6270 unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
6271 bool lockup_detected = false;
6272 bool cpu_pool_stall = false;
6273 unsigned long now = jiffies;
6274 struct worker_pool *pool;
6282 for_each_pool(pool, pi) {
6283 unsigned long pool_ts, touched, ts;
6285 pool->cpu_stall = false;
6286 if (list_empty(&pool->worklist))
6290 * If a virtual machine is stopped by the host it can look to
6291 * the watchdog like a stall.
6293 kvm_check_and_clear_guest_paused();
6295 /* get the latest of pool and touched timestamps */
6297 touched = READ_ONCE(per_cpu(wq_watchdog_touched_cpu, pool->cpu));
6299 touched = READ_ONCE(wq_watchdog_touched);
6300 pool_ts = READ_ONCE(pool->watchdog_ts);
6302 if (time_after(pool_ts, touched))
6308 if (time_after(now, ts + thresh)) {
6309 lockup_detected = true;
6310 if (pool->cpu >= 0) {
6311 pool->cpu_stall = true;
6312 cpu_pool_stall = true;
6314 pr_emerg("BUG: workqueue lockup - pool");
6315 pr_cont_pool_info(pool);
6316 pr_cont(" stuck for %us!\n",
6317 jiffies_to_msecs(now - pool_ts) / 1000);
6325 if (lockup_detected)
6326 show_all_workqueues();
6329 show_cpu_pools_hogs();
6331 wq_watchdog_reset_touched();
6332 mod_timer(&wq_watchdog_timer, jiffies + thresh);
6335 notrace void wq_watchdog_touch(int cpu)
6338 per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
6340 wq_watchdog_touched = jiffies;
6343 static void wq_watchdog_set_thresh(unsigned long thresh)
6345 wq_watchdog_thresh = 0;
6346 del_timer_sync(&wq_watchdog_timer);
6349 wq_watchdog_thresh = thresh;
6350 wq_watchdog_reset_touched();
6351 mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
6355 static int wq_watchdog_param_set_thresh(const char *val,
6356 const struct kernel_param *kp)
6358 unsigned long thresh;
6361 ret = kstrtoul(val, 0, &thresh);
6366 wq_watchdog_set_thresh(thresh);
6368 wq_watchdog_thresh = thresh;
6373 static const struct kernel_param_ops wq_watchdog_thresh_ops = {
6374 .set = wq_watchdog_param_set_thresh,
6375 .get = param_get_ulong,
6378 module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
6381 static void wq_watchdog_init(void)
6383 timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
6384 wq_watchdog_set_thresh(wq_watchdog_thresh);
6387 #else /* CONFIG_WQ_WATCHDOG */
6389 static inline void wq_watchdog_init(void) { }
6391 #endif /* CONFIG_WQ_WATCHDOG */
6393 static void __init wq_numa_init(void)
6398 if (num_possible_nodes() <= 1)
6401 if (wq_disable_numa) {
6402 pr_info("workqueue: NUMA affinity support disabled\n");
6406 for_each_possible_cpu(cpu) {
6407 if (WARN_ON(cpu_to_node(cpu) == NUMA_NO_NODE)) {
6408 pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
6413 wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs();
6414 BUG_ON(!wq_update_unbound_numa_attrs_buf);
6417 * We want masks of possible CPUs of each node which isn't readily
6418 * available. Build one from cpu_to_node() which should have been
6419 * fully initialized by now.
6421 tbl = kcalloc(nr_node_ids, sizeof(tbl[0]), GFP_KERNEL);
6425 BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
6426 node_online(node) ? node : NUMA_NO_NODE));
6428 for_each_possible_cpu(cpu) {
6429 node = cpu_to_node(cpu);
6430 cpumask_set_cpu(cpu, tbl[node]);
6433 wq_numa_possible_cpumask = tbl;
6434 wq_numa_enabled = true;
6438 * workqueue_init_early - early init for workqueue subsystem
6440 * This is the first half of two-staged workqueue subsystem initialization
6441 * and invoked as soon as the bare basics - memory allocation, cpumasks and
6442 * idr are up. It sets up all the data structures and system workqueues
6443 * and allows early boot code to create workqueues and queue/cancel work
6444 * items. Actual work item execution starts only after kthreads can be
6445 * created and scheduled right before early initcalls.
6447 void __init workqueue_init_early(void)
6449 int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
6452 BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
6454 BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
6455 cpumask_copy(wq_unbound_cpumask, housekeeping_cpumask(HK_TYPE_WQ));
6456 cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, housekeeping_cpumask(HK_TYPE_DOMAIN));
6458 pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
6460 /* initialize CPU pools */
6461 for_each_possible_cpu(cpu) {
6462 struct worker_pool *pool;
6465 for_each_cpu_worker_pool(pool, cpu) {
6466 BUG_ON(init_worker_pool(pool));
6468 cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
6469 pool->attrs->nice = std_nice[i++];
6470 pool->node = cpu_to_node(cpu);
6473 mutex_lock(&wq_pool_mutex);
6474 BUG_ON(worker_pool_assign_id(pool));
6475 mutex_unlock(&wq_pool_mutex);
6479 /* create default unbound and ordered wq attrs */
6480 for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
6481 struct workqueue_attrs *attrs;
6483 BUG_ON(!(attrs = alloc_workqueue_attrs()));
6484 attrs->nice = std_nice[i];
6485 unbound_std_wq_attrs[i] = attrs;
6488 * An ordered wq should have only one pwq as ordering is
6489 * guaranteed by max_active which is enforced by pwqs.
6490 * Turn off NUMA so that dfl_pwq is used for all nodes.
6492 BUG_ON(!(attrs = alloc_workqueue_attrs()));
6493 attrs->nice = std_nice[i];
6494 attrs->no_numa = true;
6495 ordered_wq_attrs[i] = attrs;
6498 system_wq = alloc_workqueue("events", 0, 0);
6499 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
6500 system_long_wq = alloc_workqueue("events_long", 0, 0);
6501 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
6502 WQ_UNBOUND_MAX_ACTIVE);
6503 system_freezable_wq = alloc_workqueue("events_freezable",
6505 system_power_efficient_wq = alloc_workqueue("events_power_efficient",
6506 WQ_POWER_EFFICIENT, 0);
6507 system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
6508 WQ_FREEZABLE | WQ_POWER_EFFICIENT,
6510 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
6511 !system_unbound_wq || !system_freezable_wq ||
6512 !system_power_efficient_wq ||
6513 !system_freezable_power_efficient_wq);
6517 * workqueue_init - bring workqueue subsystem fully online
6519 * This is the latter half of two-staged workqueue subsystem initialization
6520 * and invoked as soon as kthreads can be created and scheduled.
6521 * Workqueues have been created and work items queued on them, but there
6522 * are no kworkers executing the work items yet. Populate the worker pools
6523 * with the initial workers and enable future kworker creations.
6525 void __init workqueue_init(void)
6527 struct workqueue_struct *wq;
6528 struct worker_pool *pool;
6532 * It'd be simpler to initialize NUMA in workqueue_init_early() but
6533 * CPU to node mapping may not be available that early on some
6534 * archs such as power and arm64. As per-cpu pools created
6535 * previously could be missing node hint and unbound pools NUMA
6536 * affinity, fix them up.
6538 * Also, while iterating workqueues, create rescuers if requested.
6542 mutex_lock(&wq_pool_mutex);
6544 for_each_possible_cpu(cpu) {
6545 for_each_cpu_worker_pool(pool, cpu) {
6546 pool->node = cpu_to_node(cpu);
6550 list_for_each_entry(wq, &workqueues, list) {
6551 wq_update_unbound_numa(wq, smp_processor_id(), true);
6552 WARN(init_rescuer(wq),
6553 "workqueue: failed to create early rescuer for %s",
6557 mutex_unlock(&wq_pool_mutex);
6559 /* create the initial workers */
6560 for_each_online_cpu(cpu) {
6561 for_each_cpu_worker_pool(pool, cpu) {
6562 pool->flags &= ~POOL_DISASSOCIATED;
6563 BUG_ON(!create_worker(pool));
6567 hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
6568 BUG_ON(!create_worker(pool));
6575 * Despite the naming, this is a no-op function which is here only for avoiding
6576 * link error. Since compile-time warning may fail to catch, we will need to
6577 * emit run-time warning from __flush_workqueue().
6579 void __warn_flushing_systemwide_wq(void) { }
6580 EXPORT_SYMBOL(__warn_flushing_systemwide_wq);