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:
8 * David Woodhouse <dwmw2@infradead.org>
10 * Kai Petzke <wpp@marie.physik.tu-berlin.de>
11 * Theodore Ts'o <tytso@mit.edu>
13 * Made to use alloc_percpu by Christoph Lameter.
15 * Copyright (C) 2010 SUSE Linux Products GmbH
16 * Copyright (C) 2010 Tejun Heo <tj@kernel.org>
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>
55 #include <linux/delay.h>
57 #include "workqueue_internal.h"
63 * A bound pool is either associated or disassociated with its CPU.
64 * While associated (!DISASSOCIATED), all workers are bound to the
65 * CPU and none has %WORKER_UNBOUND set and concurrency management
68 * While DISASSOCIATED, the cpu may be offline and all workers have
69 * %WORKER_UNBOUND set and concurrency management disabled, and may
70 * be executing on any CPU. The pool behaves as an unbound one.
72 * Note that DISASSOCIATED should be flipped only while holding
73 * wq_pool_attach_mutex to avoid changing binding state while
74 * worker_attach_to_pool() is in progress.
76 POOL_MANAGER_ACTIVE = 1 << 0, /* being managed */
77 POOL_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
80 WORKER_DIE = 1 << 1, /* die die die */
81 WORKER_IDLE = 1 << 2, /* is idle */
82 WORKER_PREP = 1 << 3, /* preparing to run works */
83 WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
84 WORKER_UNBOUND = 1 << 7, /* worker is unbound */
85 WORKER_REBOUND = 1 << 8, /* worker was rebound */
87 WORKER_NOT_RUNNING = WORKER_PREP | WORKER_CPU_INTENSIVE |
88 WORKER_UNBOUND | WORKER_REBOUND,
90 NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */
92 UNBOUND_POOL_HASH_ORDER = 6, /* hashed by pool->attrs */
93 BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
95 MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
96 IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
98 MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
99 /* call for help after 10ms
101 MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
102 CREATE_COOLDOWN = HZ, /* time to breath after fail */
105 * Rescue workers are used only on emergencies and shared by
106 * all cpus. Give MIN_NICE.
108 RESCUER_NICE_LEVEL = MIN_NICE,
109 HIGHPRI_NICE_LEVEL = MIN_NICE,
115 * Structure fields follow one of the following exclusion rules.
117 * I: Modifiable by initialization/destruction paths and read-only for
120 * P: Preemption protected. Disabling preemption is enough and should
121 * only be modified and accessed from the local cpu.
123 * L: pool->lock protected. Access with pool->lock held.
125 * K: Only modified by worker while holding pool->lock. Can be safely read by
126 * self, while holding pool->lock or from IRQ context if %current is the
129 * S: Only modified by worker self.
131 * A: wq_pool_attach_mutex protected.
133 * PL: wq_pool_mutex protected.
135 * PR: wq_pool_mutex protected for writes. RCU protected for reads.
137 * PW: wq_pool_mutex and wq->mutex protected for writes. Either for reads.
139 * PWR: wq_pool_mutex and wq->mutex protected for writes. Either or
142 * WQ: wq->mutex protected.
144 * WR: wq->mutex protected for writes. RCU protected for reads.
146 * MD: wq_mayday_lock protected.
148 * WD: Used internally by the watchdog.
151 /* struct worker is defined in workqueue_internal.h */
154 raw_spinlock_t lock; /* the pool lock */
155 int cpu; /* I: the associated cpu */
156 int node; /* I: the associated node ID */
157 int id; /* I: pool ID */
158 unsigned int flags; /* L: flags */
160 unsigned long watchdog_ts; /* L: watchdog timestamp */
161 bool cpu_stall; /* WD: stalled cpu bound pool */
164 * The counter is incremented in a process context on the associated CPU
165 * w/ preemption disabled, and decremented or reset in the same context
166 * but w/ pool->lock held. The readers grab pool->lock and are
167 * guaranteed to see if the counter reached zero.
171 struct list_head worklist; /* L: list of pending works */
173 int nr_workers; /* L: total number of workers */
174 int nr_idle; /* L: currently idle workers */
176 struct list_head idle_list; /* L: list of idle workers */
177 struct timer_list idle_timer; /* L: worker idle timeout */
178 struct work_struct idle_cull_work; /* L: worker idle cleanup */
180 struct timer_list mayday_timer; /* L: SOS timer for workers */
182 /* a workers is either on busy_hash or idle_list, or the manager */
183 DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
184 /* L: hash of busy workers */
186 struct worker *manager; /* L: purely informational */
187 struct list_head workers; /* A: attached workers */
188 struct list_head dying_workers; /* A: workers about to die */
189 struct completion *detach_completion; /* all workers detached */
191 struct ida worker_ida; /* worker IDs for task name */
193 struct workqueue_attrs *attrs; /* I: worker attributes */
194 struct hlist_node hash_node; /* PL: unbound_pool_hash node */
195 int refcnt; /* PL: refcnt for unbound pools */
198 * Destruction of pool is RCU protected to allow dereferences
199 * from get_work_pool().
205 * Per-pool_workqueue statistics. These can be monitored using
206 * tools/workqueue/wq_monitor.py.
208 enum pool_workqueue_stats {
209 PWQ_STAT_STARTED, /* work items started execution */
210 PWQ_STAT_COMPLETED, /* work items completed execution */
211 PWQ_STAT_CPU_TIME, /* total CPU time consumed */
212 PWQ_STAT_CPU_INTENSIVE, /* wq_cpu_intensive_thresh_us violations */
213 PWQ_STAT_CM_WAKEUP, /* concurrency-management worker wakeups */
214 PWQ_STAT_MAYDAY, /* maydays to rescuer */
215 PWQ_STAT_RESCUED, /* linked work items executed by rescuer */
221 * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
222 * of work_struct->data are used for flags and the remaining high bits
223 * point to the pwq; thus, pwqs need to be aligned at two's power of the
224 * number of flag bits.
226 struct pool_workqueue {
227 struct worker_pool *pool; /* I: the associated pool */
228 struct workqueue_struct *wq; /* I: the owning workqueue */
229 int work_color; /* L: current color */
230 int flush_color; /* L: flushing color */
231 int refcnt; /* L: reference count */
232 int nr_in_flight[WORK_NR_COLORS];
233 /* L: nr of in_flight works */
236 * nr_active management and WORK_STRUCT_INACTIVE:
238 * When pwq->nr_active >= max_active, new work item is queued to
239 * pwq->inactive_works instead of pool->worklist and marked with
240 * WORK_STRUCT_INACTIVE.
242 * All work items marked with WORK_STRUCT_INACTIVE do not participate
243 * in pwq->nr_active and all work items in pwq->inactive_works are
244 * marked with WORK_STRUCT_INACTIVE. But not all WORK_STRUCT_INACTIVE
245 * work items are in pwq->inactive_works. Some of them are ready to
246 * run in pool->worklist or worker->scheduled. Those work itmes are
247 * only struct wq_barrier which is used for flush_work() and should
248 * not participate in pwq->nr_active. For non-barrier work item, it
249 * is marked with WORK_STRUCT_INACTIVE iff it is in pwq->inactive_works.
251 int nr_active; /* L: nr of active works */
252 int max_active; /* L: max active works */
253 struct list_head inactive_works; /* L: inactive works */
254 struct list_head pwqs_node; /* WR: node on wq->pwqs */
255 struct list_head mayday_node; /* MD: node on wq->maydays */
257 u64 stats[PWQ_NR_STATS];
260 * Release of unbound pwq is punted to system_wq. See put_pwq()
261 * and pwq_unbound_release_workfn() for details. pool_workqueue
262 * itself is also RCU protected so that the first pwq can be
263 * determined without grabbing wq->mutex.
265 struct work_struct unbound_release_work;
267 } __aligned(1 << WORK_STRUCT_FLAG_BITS);
270 * Structure used to wait for workqueue flush.
273 struct list_head list; /* WQ: list of flushers */
274 int flush_color; /* WQ: flush color waiting for */
275 struct completion done; /* flush completion */
281 * The externally visible workqueue. It relays the issued work items to
282 * the appropriate worker_pool through its pool_workqueues.
284 struct workqueue_struct {
285 struct list_head pwqs; /* WR: all pwqs of this wq */
286 struct list_head list; /* PR: list of all workqueues */
288 struct mutex mutex; /* protects this wq */
289 int work_color; /* WQ: current work color */
290 int flush_color; /* WQ: current flush color */
291 atomic_t nr_pwqs_to_flush; /* flush in progress */
292 struct wq_flusher *first_flusher; /* WQ: first flusher */
293 struct list_head flusher_queue; /* WQ: flush waiters */
294 struct list_head flusher_overflow; /* WQ: flush overflow list */
296 struct list_head maydays; /* MD: pwqs requesting rescue */
297 struct worker *rescuer; /* MD: rescue worker */
299 int nr_drainers; /* WQ: drain in progress */
300 int saved_max_active; /* WQ: saved pwq max_active */
302 struct workqueue_attrs *unbound_attrs; /* PW: only for unbound wqs */
303 struct pool_workqueue *dfl_pwq; /* PW: only for unbound wqs */
306 struct wq_device *wq_dev; /* I: for sysfs interface */
308 #ifdef CONFIG_LOCKDEP
310 struct lock_class_key key;
311 struct lockdep_map lockdep_map;
313 char name[WQ_NAME_LEN]; /* I: workqueue name */
316 * Destruction of workqueue_struct is RCU protected to allow walking
317 * the workqueues list without grabbing wq_pool_mutex.
318 * This is used to dump all workqueues from sysrq.
322 /* hot fields used during command issue, aligned to cacheline */
323 unsigned int flags ____cacheline_aligned; /* WQ: WQ_* flags */
324 struct pool_workqueue __percpu *cpu_pwq; /* I: per-cpu pwqs */
325 struct pool_workqueue __rcu *numa_pwq_tbl[]; /* PWR: unbound pwqs indexed by node */
328 static struct kmem_cache *pwq_cache;
330 static cpumask_var_t *wq_numa_possible_cpumask;
331 /* possible CPUs of each node */
334 * Per-cpu work items which run for longer than the following threshold are
335 * automatically considered CPU intensive and excluded from concurrency
336 * management to prevent them from noticeably delaying other per-cpu work items.
337 * ULONG_MAX indicates that the user hasn't overridden it with a boot parameter.
338 * The actual value is initialized in wq_cpu_intensive_thresh_init().
340 static unsigned long wq_cpu_intensive_thresh_us = ULONG_MAX;
341 module_param_named(cpu_intensive_thresh_us, wq_cpu_intensive_thresh_us, ulong, 0644);
343 /* see the comment above the definition of WQ_POWER_EFFICIENT */
344 static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
345 module_param_named(power_efficient, wq_power_efficient, bool, 0444);
347 static bool wq_online; /* can kworkers be created yet? */
349 static bool wq_numa_enabled; /* unbound NUMA affinity enabled */
351 /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
352 static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf;
354 static DEFINE_MUTEX(wq_pool_mutex); /* protects pools and workqueues list */
355 static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
356 static DEFINE_RAW_SPINLOCK(wq_mayday_lock); /* protects wq->maydays list */
357 /* wait for manager to go away */
358 static struct rcuwait manager_wait = __RCUWAIT_INITIALIZER(manager_wait);
360 static LIST_HEAD(workqueues); /* PR: list of all workqueues */
361 static bool workqueue_freezing; /* PL: have wqs started freezing? */
363 /* PL&A: allowable cpus for unbound wqs and work items */
364 static cpumask_var_t wq_unbound_cpumask;
366 /* for further constrain wq_unbound_cpumask by cmdline parameter*/
367 static struct cpumask wq_cmdline_cpumask __initdata;
369 /* CPU where unbound work was last round robin scheduled from this CPU */
370 static DEFINE_PER_CPU(int, wq_rr_cpu_last);
373 * Local execution of unbound work items is no longer guaranteed. The
374 * following always forces round-robin CPU selection on unbound work items
375 * to uncover usages which depend on it.
377 #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
378 static bool wq_debug_force_rr_cpu = true;
380 static bool wq_debug_force_rr_cpu = false;
382 module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
384 /* the per-cpu worker pools */
385 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools);
387 static DEFINE_IDR(worker_pool_idr); /* PR: idr of all pools */
389 /* PL: hash of all unbound pools keyed by pool->attrs */
390 static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
392 /* I: attributes used when instantiating standard unbound pools on demand */
393 static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
395 /* I: attributes used when instantiating ordered pools on demand */
396 static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
398 struct workqueue_struct *system_wq __read_mostly;
399 EXPORT_SYMBOL(system_wq);
400 struct workqueue_struct *system_highpri_wq __read_mostly;
401 EXPORT_SYMBOL_GPL(system_highpri_wq);
402 struct workqueue_struct *system_long_wq __read_mostly;
403 EXPORT_SYMBOL_GPL(system_long_wq);
404 struct workqueue_struct *system_unbound_wq __read_mostly;
405 EXPORT_SYMBOL_GPL(system_unbound_wq);
406 struct workqueue_struct *system_freezable_wq __read_mostly;
407 EXPORT_SYMBOL_GPL(system_freezable_wq);
408 struct workqueue_struct *system_power_efficient_wq __read_mostly;
409 EXPORT_SYMBOL_GPL(system_power_efficient_wq);
410 struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
411 EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
413 static int worker_thread(void *__worker);
414 static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
415 static void show_pwq(struct pool_workqueue *pwq);
416 static void show_one_worker_pool(struct worker_pool *pool);
418 #define CREATE_TRACE_POINTS
419 #include <trace/events/workqueue.h>
421 #define assert_rcu_or_pool_mutex() \
422 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
423 !lockdep_is_held(&wq_pool_mutex), \
424 "RCU or wq_pool_mutex should be held")
426 #define assert_rcu_or_wq_mutex_or_pool_mutex(wq) \
427 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
428 !lockdep_is_held(&wq->mutex) && \
429 !lockdep_is_held(&wq_pool_mutex), \
430 "RCU, wq->mutex or wq_pool_mutex should be held")
432 #define for_each_cpu_worker_pool(pool, cpu) \
433 for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
434 (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
438 * for_each_pool - iterate through all worker_pools in the system
439 * @pool: iteration cursor
440 * @pi: integer used for iteration
442 * This must be called either with wq_pool_mutex held or RCU read
443 * locked. If the pool needs to be used beyond the locking in effect, the
444 * caller is responsible for guaranteeing that the pool stays online.
446 * The if/else clause exists only for the lockdep assertion and can be
449 #define for_each_pool(pool, pi) \
450 idr_for_each_entry(&worker_pool_idr, pool, pi) \
451 if (({ assert_rcu_or_pool_mutex(); false; })) { } \
455 * for_each_pool_worker - iterate through all workers of a worker_pool
456 * @worker: iteration cursor
457 * @pool: worker_pool to iterate workers of
459 * This must be called with wq_pool_attach_mutex.
461 * The if/else clause exists only for the lockdep assertion and can be
464 #define for_each_pool_worker(worker, pool) \
465 list_for_each_entry((worker), &(pool)->workers, node) \
466 if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
470 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
471 * @pwq: iteration cursor
472 * @wq: the target workqueue
474 * This must be called either with wq->mutex held or RCU read locked.
475 * If the pwq needs to be used beyond the locking in effect, the caller is
476 * responsible for guaranteeing that the pwq stays online.
478 * The if/else clause exists only for the lockdep assertion and can be
481 #define for_each_pwq(pwq, wq) \
482 list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node, \
483 lockdep_is_held(&(wq->mutex)))
485 #ifdef CONFIG_DEBUG_OBJECTS_WORK
487 static const struct debug_obj_descr work_debug_descr;
489 static void *work_debug_hint(void *addr)
491 return ((struct work_struct *) addr)->func;
494 static bool work_is_static_object(void *addr)
496 struct work_struct *work = addr;
498 return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
502 * fixup_init is called when:
503 * - an active object is initialized
505 static bool work_fixup_init(void *addr, enum debug_obj_state state)
507 struct work_struct *work = addr;
510 case ODEBUG_STATE_ACTIVE:
511 cancel_work_sync(work);
512 debug_object_init(work, &work_debug_descr);
520 * fixup_free is called when:
521 * - an active object is freed
523 static bool work_fixup_free(void *addr, enum debug_obj_state state)
525 struct work_struct *work = addr;
528 case ODEBUG_STATE_ACTIVE:
529 cancel_work_sync(work);
530 debug_object_free(work, &work_debug_descr);
537 static const struct debug_obj_descr work_debug_descr = {
538 .name = "work_struct",
539 .debug_hint = work_debug_hint,
540 .is_static_object = work_is_static_object,
541 .fixup_init = work_fixup_init,
542 .fixup_free = work_fixup_free,
545 static inline void debug_work_activate(struct work_struct *work)
547 debug_object_activate(work, &work_debug_descr);
550 static inline void debug_work_deactivate(struct work_struct *work)
552 debug_object_deactivate(work, &work_debug_descr);
555 void __init_work(struct work_struct *work, int onstack)
558 debug_object_init_on_stack(work, &work_debug_descr);
560 debug_object_init(work, &work_debug_descr);
562 EXPORT_SYMBOL_GPL(__init_work);
564 void destroy_work_on_stack(struct work_struct *work)
566 debug_object_free(work, &work_debug_descr);
568 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
570 void destroy_delayed_work_on_stack(struct delayed_work *work)
572 destroy_timer_on_stack(&work->timer);
573 debug_object_free(&work->work, &work_debug_descr);
575 EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
578 static inline void debug_work_activate(struct work_struct *work) { }
579 static inline void debug_work_deactivate(struct work_struct *work) { }
583 * worker_pool_assign_id - allocate ID and assign it to @pool
584 * @pool: the pool pointer of interest
586 * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
587 * successfully, -errno on failure.
589 static int worker_pool_assign_id(struct worker_pool *pool)
593 lockdep_assert_held(&wq_pool_mutex);
595 ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
605 * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
606 * @wq: the target workqueue
609 * This must be called with any of wq_pool_mutex, wq->mutex or RCU
611 * If the pwq needs to be used beyond the locking in effect, the caller is
612 * responsible for guaranteeing that the pwq stays online.
614 * Return: The unbound pool_workqueue for @node.
616 static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
619 assert_rcu_or_wq_mutex_or_pool_mutex(wq);
622 * XXX: @node can be NUMA_NO_NODE if CPU goes offline while a
623 * delayed item is pending. The plan is to keep CPU -> NODE
624 * mapping valid and stable across CPU on/offlines. Once that
625 * happens, this workaround can be removed.
627 if (unlikely(node == NUMA_NO_NODE))
630 return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
633 static unsigned int work_color_to_flags(int color)
635 return color << WORK_STRUCT_COLOR_SHIFT;
638 static int get_work_color(unsigned long work_data)
640 return (work_data >> WORK_STRUCT_COLOR_SHIFT) &
641 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
644 static int work_next_color(int color)
646 return (color + 1) % WORK_NR_COLORS;
650 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
651 * contain the pointer to the queued pwq. Once execution starts, the flag
652 * is cleared and the high bits contain OFFQ flags and pool ID.
654 * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
655 * and clear_work_data() can be used to set the pwq, pool or clear
656 * work->data. These functions should only be called while the work is
657 * owned - ie. while the PENDING bit is set.
659 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
660 * corresponding to a work. Pool is available once the work has been
661 * queued anywhere after initialization until it is sync canceled. pwq is
662 * available only while the work item is queued.
664 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
665 * canceled. While being canceled, a work item may have its PENDING set
666 * but stay off timer and worklist for arbitrarily long and nobody should
667 * try to steal the PENDING bit.
669 static inline void set_work_data(struct work_struct *work, unsigned long data,
672 WARN_ON_ONCE(!work_pending(work));
673 atomic_long_set(&work->data, data | flags | work_static(work));
676 static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
677 unsigned long extra_flags)
679 set_work_data(work, (unsigned long)pwq,
680 WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
683 static void set_work_pool_and_keep_pending(struct work_struct *work,
686 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
687 WORK_STRUCT_PENDING);
690 static void set_work_pool_and_clear_pending(struct work_struct *work,
694 * The following wmb is paired with the implied mb in
695 * test_and_set_bit(PENDING) and ensures all updates to @work made
696 * here are visible to and precede any updates by the next PENDING
700 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
702 * The following mb guarantees that previous clear of a PENDING bit
703 * will not be reordered with any speculative LOADS or STORES from
704 * work->current_func, which is executed afterwards. This possible
705 * reordering can lead to a missed execution on attempt to queue
706 * the same @work. E.g. consider this case:
709 * ---------------------------- --------------------------------
711 * 1 STORE event_indicated
712 * 2 queue_work_on() {
713 * 3 test_and_set_bit(PENDING)
714 * 4 } set_..._and_clear_pending() {
715 * 5 set_work_data() # clear bit
717 * 7 work->current_func() {
718 * 8 LOAD event_indicated
721 * Without an explicit full barrier speculative LOAD on line 8 can
722 * be executed before CPU#0 does STORE on line 1. If that happens,
723 * CPU#0 observes the PENDING bit is still set and new execution of
724 * a @work is not queued in a hope, that CPU#1 will eventually
725 * finish the queued @work. Meanwhile CPU#1 does not see
726 * event_indicated is set, because speculative LOAD was executed
727 * before actual STORE.
732 static void clear_work_data(struct work_struct *work)
734 smp_wmb(); /* see set_work_pool_and_clear_pending() */
735 set_work_data(work, WORK_STRUCT_NO_POOL, 0);
738 static inline struct pool_workqueue *work_struct_pwq(unsigned long data)
740 return (struct pool_workqueue *)(data & WORK_STRUCT_WQ_DATA_MASK);
743 static struct pool_workqueue *get_work_pwq(struct work_struct *work)
745 unsigned long data = atomic_long_read(&work->data);
747 if (data & WORK_STRUCT_PWQ)
748 return work_struct_pwq(data);
754 * get_work_pool - return the worker_pool a given work was associated with
755 * @work: the work item of interest
757 * Pools are created and destroyed under wq_pool_mutex, and allows read
758 * access under RCU read lock. As such, this function should be
759 * called under wq_pool_mutex or inside of a rcu_read_lock() region.
761 * All fields of the returned pool are accessible as long as the above
762 * mentioned locking is in effect. If the returned pool needs to be used
763 * beyond the critical section, the caller is responsible for ensuring the
764 * returned pool is and stays online.
766 * Return: The worker_pool @work was last associated with. %NULL if none.
768 static struct worker_pool *get_work_pool(struct work_struct *work)
770 unsigned long data = atomic_long_read(&work->data);
773 assert_rcu_or_pool_mutex();
775 if (data & WORK_STRUCT_PWQ)
776 return work_struct_pwq(data)->pool;
778 pool_id = data >> WORK_OFFQ_POOL_SHIFT;
779 if (pool_id == WORK_OFFQ_POOL_NONE)
782 return idr_find(&worker_pool_idr, pool_id);
786 * get_work_pool_id - return the worker pool ID a given work is associated with
787 * @work: the work item of interest
789 * Return: The worker_pool ID @work was last associated with.
790 * %WORK_OFFQ_POOL_NONE if none.
792 static int get_work_pool_id(struct work_struct *work)
794 unsigned long data = atomic_long_read(&work->data);
796 if (data & WORK_STRUCT_PWQ)
797 return work_struct_pwq(data)->pool->id;
799 return data >> WORK_OFFQ_POOL_SHIFT;
802 static void mark_work_canceling(struct work_struct *work)
804 unsigned long pool_id = get_work_pool_id(work);
806 pool_id <<= WORK_OFFQ_POOL_SHIFT;
807 set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
810 static bool work_is_canceling(struct work_struct *work)
812 unsigned long data = atomic_long_read(&work->data);
814 return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
818 * Policy functions. These define the policies on how the global worker
819 * pools are managed. Unless noted otherwise, these functions assume that
820 * they're being called with pool->lock held.
823 static bool __need_more_worker(struct worker_pool *pool)
825 return !pool->nr_running;
829 * Need to wake up a worker? Called from anything but currently
832 * Note that, because unbound workers never contribute to nr_running, this
833 * function will always return %true for unbound pools as long as the
834 * worklist isn't empty.
836 static bool need_more_worker(struct worker_pool *pool)
838 return !list_empty(&pool->worklist) && __need_more_worker(pool);
841 /* Can I start working? Called from busy but !running workers. */
842 static bool may_start_working(struct worker_pool *pool)
844 return pool->nr_idle;
847 /* Do I need to keep working? Called from currently running workers. */
848 static bool keep_working(struct worker_pool *pool)
850 return !list_empty(&pool->worklist) && (pool->nr_running <= 1);
853 /* Do we need a new worker? Called from manager. */
854 static bool need_to_create_worker(struct worker_pool *pool)
856 return need_more_worker(pool) && !may_start_working(pool);
859 /* Do we have too many workers and should some go away? */
860 static bool too_many_workers(struct worker_pool *pool)
862 bool managing = pool->flags & POOL_MANAGER_ACTIVE;
863 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
864 int nr_busy = pool->nr_workers - nr_idle;
866 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
870 * worker_set_flags - set worker flags and adjust nr_running accordingly
872 * @flags: flags to set
874 * Set @flags in @worker->flags and adjust nr_running accordingly.
876 static inline void worker_set_flags(struct worker *worker, unsigned int flags)
878 struct worker_pool *pool = worker->pool;
880 lockdep_assert_held(&pool->lock);
882 /* If transitioning into NOT_RUNNING, adjust nr_running. */
883 if ((flags & WORKER_NOT_RUNNING) &&
884 !(worker->flags & WORKER_NOT_RUNNING)) {
888 worker->flags |= flags;
892 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
894 * @flags: flags to clear
896 * Clear @flags in @worker->flags and adjust nr_running accordingly.
898 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
900 struct worker_pool *pool = worker->pool;
901 unsigned int oflags = worker->flags;
903 lockdep_assert_held(&pool->lock);
905 worker->flags &= ~flags;
908 * If transitioning out of NOT_RUNNING, increment nr_running. Note
909 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
910 * of multiple flags, not a single flag.
912 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
913 if (!(worker->flags & WORKER_NOT_RUNNING))
917 /* Return the first idle worker. Called with pool->lock held. */
918 static struct worker *first_idle_worker(struct worker_pool *pool)
920 if (unlikely(list_empty(&pool->idle_list)))
923 return list_first_entry(&pool->idle_list, struct worker, entry);
927 * worker_enter_idle - enter idle state
928 * @worker: worker which is entering idle state
930 * @worker is entering idle state. Update stats and idle timer if
934 * raw_spin_lock_irq(pool->lock).
936 static void worker_enter_idle(struct worker *worker)
938 struct worker_pool *pool = worker->pool;
940 if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
941 WARN_ON_ONCE(!list_empty(&worker->entry) &&
942 (worker->hentry.next || worker->hentry.pprev)))
945 /* can't use worker_set_flags(), also called from create_worker() */
946 worker->flags |= WORKER_IDLE;
948 worker->last_active = jiffies;
950 /* idle_list is LIFO */
951 list_add(&worker->entry, &pool->idle_list);
953 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
954 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
956 /* Sanity check nr_running. */
957 WARN_ON_ONCE(pool->nr_workers == pool->nr_idle && pool->nr_running);
961 * worker_leave_idle - leave idle state
962 * @worker: worker which is leaving idle state
964 * @worker is leaving idle state. Update stats.
967 * raw_spin_lock_irq(pool->lock).
969 static void worker_leave_idle(struct worker *worker)
971 struct worker_pool *pool = worker->pool;
973 if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
975 worker_clr_flags(worker, WORKER_IDLE);
977 list_del_init(&worker->entry);
981 * find_worker_executing_work - find worker which is executing a work
982 * @pool: pool of interest
983 * @work: work to find worker for
985 * Find a worker which is executing @work on @pool by searching
986 * @pool->busy_hash which is keyed by the address of @work. For a worker
987 * to match, its current execution should match the address of @work and
988 * its work function. This is to avoid unwanted dependency between
989 * unrelated work executions through a work item being recycled while still
992 * This is a bit tricky. A work item may be freed once its execution
993 * starts and nothing prevents the freed area from being recycled for
994 * another work item. If the same work item address ends up being reused
995 * before the original execution finishes, workqueue will identify the
996 * recycled work item as currently executing and make it wait until the
997 * current execution finishes, introducing an unwanted dependency.
999 * This function checks the work item address and work function to avoid
1000 * false positives. Note that this isn't complete as one may construct a
1001 * work function which can introduce dependency onto itself through a
1002 * recycled work item. Well, if somebody wants to shoot oneself in the
1003 * foot that badly, there's only so much we can do, and if such deadlock
1004 * actually occurs, it should be easy to locate the culprit work function.
1007 * raw_spin_lock_irq(pool->lock).
1010 * Pointer to worker which is executing @work if found, %NULL
1013 static struct worker *find_worker_executing_work(struct worker_pool *pool,
1014 struct work_struct *work)
1016 struct worker *worker;
1018 hash_for_each_possible(pool->busy_hash, worker, hentry,
1019 (unsigned long)work)
1020 if (worker->current_work == work &&
1021 worker->current_func == work->func)
1028 * move_linked_works - move linked works to a list
1029 * @work: start of series of works to be scheduled
1030 * @head: target list to append @work to
1031 * @nextp: out parameter for nested worklist walking
1033 * Schedule linked works starting from @work to @head. Work series to
1034 * be scheduled starts at @work and includes any consecutive work with
1035 * WORK_STRUCT_LINKED set in its predecessor.
1037 * If @nextp is not NULL, it's updated to point to the next work of
1038 * the last scheduled work. This allows move_linked_works() to be
1039 * nested inside outer list_for_each_entry_safe().
1042 * raw_spin_lock_irq(pool->lock).
1044 static void move_linked_works(struct work_struct *work, struct list_head *head,
1045 struct work_struct **nextp)
1047 struct work_struct *n;
1050 * Linked worklist will always end before the end of the list,
1051 * use NULL for list head.
1053 list_for_each_entry_safe_from(work, n, NULL, entry) {
1054 list_move_tail(&work->entry, head);
1055 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1060 * If we're already inside safe list traversal and have moved
1061 * multiple works to the scheduled queue, the next position
1062 * needs to be updated.
1069 * wake_up_worker - wake up an idle worker
1070 * @pool: worker pool to wake worker from
1072 * Wake up the first idle worker of @pool.
1075 * raw_spin_lock_irq(pool->lock).
1077 static void wake_up_worker(struct worker_pool *pool)
1079 struct worker *worker = first_idle_worker(pool);
1082 wake_up_process(worker->task);
1085 #ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
1088 * Concurrency-managed per-cpu work items that hog CPU for longer than
1089 * wq_cpu_intensive_thresh_us trigger the automatic CPU_INTENSIVE mechanism,
1090 * which prevents them from stalling other concurrency-managed work items. If a
1091 * work function keeps triggering this mechanism, it's likely that the work item
1092 * should be using an unbound workqueue instead.
1094 * wq_cpu_intensive_report() tracks work functions which trigger such conditions
1095 * and report them so that they can be examined and converted to use unbound
1096 * workqueues as appropriate. To avoid flooding the console, each violating work
1097 * function is tracked and reported with exponential backoff.
1099 #define WCI_MAX_ENTS 128
1104 struct hlist_node hash_node;
1107 static struct wci_ent wci_ents[WCI_MAX_ENTS];
1108 static int wci_nr_ents;
1109 static DEFINE_RAW_SPINLOCK(wci_lock);
1110 static DEFINE_HASHTABLE(wci_hash, ilog2(WCI_MAX_ENTS));
1112 static struct wci_ent *wci_find_ent(work_func_t func)
1114 struct wci_ent *ent;
1116 hash_for_each_possible_rcu(wci_hash, ent, hash_node,
1117 (unsigned long)func) {
1118 if (ent->func == func)
1124 static void wq_cpu_intensive_report(work_func_t func)
1126 struct wci_ent *ent;
1129 ent = wci_find_ent(func);
1134 * Start reporting from the fourth time and back off
1137 cnt = atomic64_inc_return_relaxed(&ent->cnt);
1138 if (cnt >= 4 && is_power_of_2(cnt))
1139 printk_deferred(KERN_WARNING "workqueue: %ps hogged CPU for >%luus %llu times, consider switching to WQ_UNBOUND\n",
1140 ent->func, wq_cpu_intensive_thresh_us,
1141 atomic64_read(&ent->cnt));
1146 * @func is a new violation. Allocate a new entry for it. If wcn_ents[]
1147 * is exhausted, something went really wrong and we probably made enough
1150 if (wci_nr_ents >= WCI_MAX_ENTS)
1153 raw_spin_lock(&wci_lock);
1155 if (wci_nr_ents >= WCI_MAX_ENTS) {
1156 raw_spin_unlock(&wci_lock);
1160 if (wci_find_ent(func)) {
1161 raw_spin_unlock(&wci_lock);
1165 ent = &wci_ents[wci_nr_ents++];
1167 atomic64_set(&ent->cnt, 1);
1168 hash_add_rcu(wci_hash, &ent->hash_node, (unsigned long)func);
1170 raw_spin_unlock(&wci_lock);
1173 #else /* CONFIG_WQ_CPU_INTENSIVE_REPORT */
1174 static void wq_cpu_intensive_report(work_func_t func) {}
1175 #endif /* CONFIG_WQ_CPU_INTENSIVE_REPORT */
1178 * wq_worker_running - a worker is running again
1179 * @task: task waking up
1181 * This function is called when a worker returns from schedule()
1183 void wq_worker_running(struct task_struct *task)
1185 struct worker *worker = kthread_data(task);
1187 if (!READ_ONCE(worker->sleeping))
1191 * If preempted by unbind_workers() between the WORKER_NOT_RUNNING check
1192 * and the nr_running increment below, we may ruin the nr_running reset
1193 * and leave with an unexpected pool->nr_running == 1 on the newly unbound
1194 * pool. Protect against such race.
1197 if (!(worker->flags & WORKER_NOT_RUNNING))
1198 worker->pool->nr_running++;
1202 * CPU intensive auto-detection cares about how long a work item hogged
1203 * CPU without sleeping. Reset the starting timestamp on wakeup.
1205 worker->current_at = worker->task->se.sum_exec_runtime;
1207 WRITE_ONCE(worker->sleeping, 0);
1211 * wq_worker_sleeping - a worker is going to sleep
1212 * @task: task going to sleep
1214 * This function is called from schedule() when a busy worker is
1217 void wq_worker_sleeping(struct task_struct *task)
1219 struct worker *worker = kthread_data(task);
1220 struct worker_pool *pool;
1223 * Rescuers, which may not have all the fields set up like normal
1224 * workers, also reach here, let's not access anything before
1225 * checking NOT_RUNNING.
1227 if (worker->flags & WORKER_NOT_RUNNING)
1230 pool = worker->pool;
1232 /* Return if preempted before wq_worker_running() was reached */
1233 if (READ_ONCE(worker->sleeping))
1236 WRITE_ONCE(worker->sleeping, 1);
1237 raw_spin_lock_irq(&pool->lock);
1240 * Recheck in case unbind_workers() preempted us. We don't
1241 * want to decrement nr_running after the worker is unbound
1242 * and nr_running has been reset.
1244 if (worker->flags & WORKER_NOT_RUNNING) {
1245 raw_spin_unlock_irq(&pool->lock);
1250 if (need_more_worker(pool)) {
1251 worker->current_pwq->stats[PWQ_STAT_CM_WAKEUP]++;
1252 wake_up_worker(pool);
1254 raw_spin_unlock_irq(&pool->lock);
1258 * wq_worker_tick - a scheduler tick occurred while a kworker is running
1259 * @task: task currently running
1261 * Called from scheduler_tick(). We're in the IRQ context and the current
1262 * worker's fields which follow the 'K' locking rule can be accessed safely.
1264 void wq_worker_tick(struct task_struct *task)
1266 struct worker *worker = kthread_data(task);
1267 struct pool_workqueue *pwq = worker->current_pwq;
1268 struct worker_pool *pool = worker->pool;
1273 pwq->stats[PWQ_STAT_CPU_TIME] += TICK_USEC;
1275 if (!wq_cpu_intensive_thresh_us)
1279 * If the current worker is concurrency managed and hogged the CPU for
1280 * longer than wq_cpu_intensive_thresh_us, it's automatically marked
1281 * CPU_INTENSIVE to avoid stalling other concurrency-managed work items.
1283 * Set @worker->sleeping means that @worker is in the process of
1284 * switching out voluntarily and won't be contributing to
1285 * @pool->nr_running until it wakes up. As wq_worker_sleeping() also
1286 * decrements ->nr_running, setting CPU_INTENSIVE here can lead to
1287 * double decrements. The task is releasing the CPU anyway. Let's skip.
1288 * We probably want to make this prettier in the future.
1290 if ((worker->flags & WORKER_NOT_RUNNING) || READ_ONCE(worker->sleeping) ||
1291 worker->task->se.sum_exec_runtime - worker->current_at <
1292 wq_cpu_intensive_thresh_us * NSEC_PER_USEC)
1295 raw_spin_lock(&pool->lock);
1297 worker_set_flags(worker, WORKER_CPU_INTENSIVE);
1298 wq_cpu_intensive_report(worker->current_func);
1299 pwq->stats[PWQ_STAT_CPU_INTENSIVE]++;
1301 if (need_more_worker(pool)) {
1302 pwq->stats[PWQ_STAT_CM_WAKEUP]++;
1303 wake_up_worker(pool);
1306 raw_spin_unlock(&pool->lock);
1310 * wq_worker_last_func - retrieve worker's last work function
1311 * @task: Task to retrieve last work function of.
1313 * Determine the last function a worker executed. This is called from
1314 * the scheduler to get a worker's last known identity.
1317 * raw_spin_lock_irq(rq->lock)
1319 * This function is called during schedule() when a kworker is going
1320 * to sleep. It's used by psi to identify aggregation workers during
1321 * dequeuing, to allow periodic aggregation to shut-off when that
1322 * worker is the last task in the system or cgroup to go to sleep.
1324 * As this function doesn't involve any workqueue-related locking, it
1325 * only returns stable values when called from inside the scheduler's
1326 * queuing and dequeuing paths, when @task, which must be a kworker,
1327 * is guaranteed to not be processing any works.
1330 * The last work function %current executed as a worker, NULL if it
1331 * hasn't executed any work yet.
1333 work_func_t wq_worker_last_func(struct task_struct *task)
1335 struct worker *worker = kthread_data(task);
1337 return worker->last_func;
1341 * get_pwq - get an extra reference on the specified pool_workqueue
1342 * @pwq: pool_workqueue to get
1344 * Obtain an extra reference on @pwq. The caller should guarantee that
1345 * @pwq has positive refcnt and be holding the matching pool->lock.
1347 static void get_pwq(struct pool_workqueue *pwq)
1349 lockdep_assert_held(&pwq->pool->lock);
1350 WARN_ON_ONCE(pwq->refcnt <= 0);
1355 * put_pwq - put a pool_workqueue reference
1356 * @pwq: pool_workqueue to put
1358 * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
1359 * destruction. The caller should be holding the matching pool->lock.
1361 static void put_pwq(struct pool_workqueue *pwq)
1363 lockdep_assert_held(&pwq->pool->lock);
1364 if (likely(--pwq->refcnt))
1366 if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
1369 * @pwq can't be released under pool->lock, bounce to
1370 * pwq_unbound_release_workfn(). This never recurses on the same
1371 * pool->lock as this path is taken only for unbound workqueues and
1372 * the release work item is scheduled on a per-cpu workqueue. To
1373 * avoid lockdep warning, unbound pool->locks are given lockdep
1374 * subclass of 1 in get_unbound_pool().
1376 schedule_work(&pwq->unbound_release_work);
1380 * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1381 * @pwq: pool_workqueue to put (can be %NULL)
1383 * put_pwq() with locking. This function also allows %NULL @pwq.
1385 static void put_pwq_unlocked(struct pool_workqueue *pwq)
1389 * As both pwqs and pools are RCU protected, the
1390 * following lock operations are safe.
1392 raw_spin_lock_irq(&pwq->pool->lock);
1394 raw_spin_unlock_irq(&pwq->pool->lock);
1398 static void pwq_activate_inactive_work(struct work_struct *work)
1400 struct pool_workqueue *pwq = get_work_pwq(work);
1402 trace_workqueue_activate_work(work);
1403 if (list_empty(&pwq->pool->worklist))
1404 pwq->pool->watchdog_ts = jiffies;
1405 move_linked_works(work, &pwq->pool->worklist, NULL);
1406 __clear_bit(WORK_STRUCT_INACTIVE_BIT, work_data_bits(work));
1410 static void pwq_activate_first_inactive(struct pool_workqueue *pwq)
1412 struct work_struct *work = list_first_entry(&pwq->inactive_works,
1413 struct work_struct, entry);
1415 pwq_activate_inactive_work(work);
1419 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1420 * @pwq: pwq of interest
1421 * @work_data: work_data of work which left the queue
1423 * A work either has completed or is removed from pending queue,
1424 * decrement nr_in_flight of its pwq and handle workqueue flushing.
1427 * raw_spin_lock_irq(pool->lock).
1429 static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data)
1431 int color = get_work_color(work_data);
1433 if (!(work_data & WORK_STRUCT_INACTIVE)) {
1435 if (!list_empty(&pwq->inactive_works)) {
1436 /* one down, submit an inactive one */
1437 if (pwq->nr_active < pwq->max_active)
1438 pwq_activate_first_inactive(pwq);
1442 pwq->nr_in_flight[color]--;
1444 /* is flush in progress and are we at the flushing tip? */
1445 if (likely(pwq->flush_color != color))
1448 /* are there still in-flight works? */
1449 if (pwq->nr_in_flight[color])
1452 /* this pwq is done, clear flush_color */
1453 pwq->flush_color = -1;
1456 * If this was the last pwq, wake up the first flusher. It
1457 * will handle the rest.
1459 if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1460 complete(&pwq->wq->first_flusher->done);
1466 * try_to_grab_pending - steal work item from worklist and disable irq
1467 * @work: work item to steal
1468 * @is_dwork: @work is a delayed_work
1469 * @flags: place to store irq state
1471 * Try to grab PENDING bit of @work. This function can handle @work in any
1472 * stable state - idle, on timer or on worklist.
1476 * ======== ================================================================
1477 * 1 if @work was pending and we successfully stole PENDING
1478 * 0 if @work was idle and we claimed PENDING
1479 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1480 * -ENOENT if someone else is canceling @work, this state may persist
1481 * for arbitrarily long
1482 * ======== ================================================================
1485 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1486 * interrupted while holding PENDING and @work off queue, irq must be
1487 * disabled on entry. This, combined with delayed_work->timer being
1488 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1490 * On successful return, >= 0, irq is disabled and the caller is
1491 * responsible for releasing it using local_irq_restore(*@flags).
1493 * This function is safe to call from any context including IRQ handler.
1495 static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1496 unsigned long *flags)
1498 struct worker_pool *pool;
1499 struct pool_workqueue *pwq;
1501 local_irq_save(*flags);
1503 /* try to steal the timer if it exists */
1505 struct delayed_work *dwork = to_delayed_work(work);
1508 * dwork->timer is irqsafe. If del_timer() fails, it's
1509 * guaranteed that the timer is not queued anywhere and not
1510 * running on the local CPU.
1512 if (likely(del_timer(&dwork->timer)))
1516 /* try to claim PENDING the normal way */
1517 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1522 * The queueing is in progress, or it is already queued. Try to
1523 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1525 pool = get_work_pool(work);
1529 raw_spin_lock(&pool->lock);
1531 * work->data is guaranteed to point to pwq only while the work
1532 * item is queued on pwq->wq, and both updating work->data to point
1533 * to pwq on queueing and to pool on dequeueing are done under
1534 * pwq->pool->lock. This in turn guarantees that, if work->data
1535 * points to pwq which is associated with a locked pool, the work
1536 * item is currently queued on that pool.
1538 pwq = get_work_pwq(work);
1539 if (pwq && pwq->pool == pool) {
1540 debug_work_deactivate(work);
1543 * A cancelable inactive work item must be in the
1544 * pwq->inactive_works since a queued barrier can't be
1545 * canceled (see the comments in insert_wq_barrier()).
1547 * An inactive work item cannot be grabbed directly because
1548 * it might have linked barrier work items which, if left
1549 * on the inactive_works list, will confuse pwq->nr_active
1550 * management later on and cause stall. Make sure the work
1551 * item is activated before grabbing.
1553 if (*work_data_bits(work) & WORK_STRUCT_INACTIVE)
1554 pwq_activate_inactive_work(work);
1556 list_del_init(&work->entry);
1557 pwq_dec_nr_in_flight(pwq, *work_data_bits(work));
1559 /* work->data points to pwq iff queued, point to pool */
1560 set_work_pool_and_keep_pending(work, pool->id);
1562 raw_spin_unlock(&pool->lock);
1566 raw_spin_unlock(&pool->lock);
1569 local_irq_restore(*flags);
1570 if (work_is_canceling(work))
1577 * insert_work - insert a work into a pool
1578 * @pwq: pwq @work belongs to
1579 * @work: work to insert
1580 * @head: insertion point
1581 * @extra_flags: extra WORK_STRUCT_* flags to set
1583 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
1584 * work_struct flags.
1587 * raw_spin_lock_irq(pool->lock).
1589 static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1590 struct list_head *head, unsigned int extra_flags)
1592 debug_work_activate(work);
1594 /* record the work call stack in order to print it in KASAN reports */
1595 kasan_record_aux_stack_noalloc(work);
1597 /* we own @work, set data and link */
1598 set_work_pwq(work, pwq, extra_flags);
1599 list_add_tail(&work->entry, head);
1604 * Test whether @work is being queued from another work executing on the
1607 static bool is_chained_work(struct workqueue_struct *wq)
1609 struct worker *worker;
1611 worker = current_wq_worker();
1613 * Return %true iff I'm a worker executing a work item on @wq. If
1614 * I'm @worker, it's safe to dereference it without locking.
1616 return worker && worker->current_pwq->wq == wq;
1620 * When queueing an unbound work item to a wq, prefer local CPU if allowed
1621 * by wq_unbound_cpumask. Otherwise, round robin among the allowed ones to
1622 * avoid perturbing sensitive tasks.
1624 static int wq_select_unbound_cpu(int cpu)
1628 if (likely(!wq_debug_force_rr_cpu)) {
1629 if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
1632 pr_warn_once("workqueue: round-robin CPU selection forced, expect performance impact\n");
1635 if (cpumask_empty(wq_unbound_cpumask))
1638 new_cpu = __this_cpu_read(wq_rr_cpu_last);
1639 new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
1640 if (unlikely(new_cpu >= nr_cpu_ids)) {
1641 new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
1642 if (unlikely(new_cpu >= nr_cpu_ids))
1645 __this_cpu_write(wq_rr_cpu_last, new_cpu);
1650 static void __queue_work(int cpu, struct workqueue_struct *wq,
1651 struct work_struct *work)
1653 struct pool_workqueue *pwq;
1654 struct worker_pool *last_pool, *pool;
1655 unsigned int work_flags;
1656 unsigned int req_cpu = cpu;
1659 * While a work item is PENDING && off queue, a task trying to
1660 * steal the PENDING will busy-loop waiting for it to either get
1661 * queued or lose PENDING. Grabbing PENDING and queueing should
1662 * happen with IRQ disabled.
1664 lockdep_assert_irqs_disabled();
1668 * For a draining wq, only works from the same workqueue are
1669 * allowed. The __WQ_DESTROYING helps to spot the issue that
1670 * queues a new work item to a wq after destroy_workqueue(wq).
1672 if (unlikely(wq->flags & (__WQ_DESTROYING | __WQ_DRAINING) &&
1673 WARN_ON_ONCE(!is_chained_work(wq))))
1677 /* pwq which will be used unless @work is executing elsewhere */
1678 if (wq->flags & WQ_UNBOUND) {
1679 if (req_cpu == WORK_CPU_UNBOUND)
1680 cpu = wq_select_unbound_cpu(raw_smp_processor_id());
1681 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1683 if (req_cpu == WORK_CPU_UNBOUND)
1684 cpu = raw_smp_processor_id();
1685 pwq = per_cpu_ptr(wq->cpu_pwq, cpu);
1691 * If @work was previously on a different pool, it might still be
1692 * running there, in which case the work needs to be queued on that
1693 * pool to guarantee non-reentrancy.
1695 last_pool = get_work_pool(work);
1696 if (last_pool && last_pool != pool) {
1697 struct worker *worker;
1699 raw_spin_lock(&last_pool->lock);
1701 worker = find_worker_executing_work(last_pool, work);
1703 if (worker && worker->current_pwq->wq == wq) {
1704 pwq = worker->current_pwq;
1706 WARN_ON_ONCE(pool != last_pool);
1708 /* meh... not running there, queue here */
1709 raw_spin_unlock(&last_pool->lock);
1710 raw_spin_lock(&pool->lock);
1713 raw_spin_lock(&pool->lock);
1717 * pwq is determined and locked. For unbound pools, we could have
1718 * raced with pwq release and it could already be dead. If its
1719 * refcnt is zero, repeat pwq selection. Note that pwqs never die
1720 * without another pwq replacing it in the numa_pwq_tbl or while
1721 * work items are executing on it, so the retrying is guaranteed to
1722 * make forward-progress.
1724 if (unlikely(!pwq->refcnt)) {
1725 if (wq->flags & WQ_UNBOUND) {
1726 raw_spin_unlock(&pool->lock);
1731 WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
1735 /* pwq determined, queue */
1736 trace_workqueue_queue_work(req_cpu, pwq, work);
1738 if (WARN_ON(!list_empty(&work->entry)))
1741 pwq->nr_in_flight[pwq->work_color]++;
1742 work_flags = work_color_to_flags(pwq->work_color);
1744 if (likely(pwq->nr_active < pwq->max_active)) {
1745 if (list_empty(&pool->worklist))
1746 pool->watchdog_ts = jiffies;
1748 trace_workqueue_activate_work(work);
1750 insert_work(pwq, work, &pool->worklist, work_flags);
1752 if (__need_more_worker(pool))
1753 wake_up_worker(pool);
1755 work_flags |= WORK_STRUCT_INACTIVE;
1756 insert_work(pwq, work, &pwq->inactive_works, work_flags);
1760 raw_spin_unlock(&pool->lock);
1765 * queue_work_on - queue work on specific cpu
1766 * @cpu: CPU number to execute work on
1767 * @wq: workqueue to use
1768 * @work: work to queue
1770 * We queue the work to a specific CPU, the caller must ensure it
1771 * can't go away. Callers that fail to ensure that the specified
1772 * CPU cannot go away will execute on a randomly chosen CPU.
1773 * But note well that callers specifying a CPU that never has been
1774 * online will get a splat.
1776 * Return: %false if @work was already on a queue, %true otherwise.
1778 bool queue_work_on(int cpu, struct workqueue_struct *wq,
1779 struct work_struct *work)
1782 unsigned long flags;
1784 local_irq_save(flags);
1786 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1787 __queue_work(cpu, wq, work);
1791 local_irq_restore(flags);
1794 EXPORT_SYMBOL(queue_work_on);
1797 * workqueue_select_cpu_near - Select a CPU based on NUMA node
1798 * @node: NUMA node ID that we want to select a CPU from
1800 * This function will attempt to find a "random" cpu available on a given
1801 * node. If there are no CPUs available on the given node it will return
1802 * WORK_CPU_UNBOUND indicating that we should just schedule to any
1803 * available CPU if we need to schedule this work.
1805 static int workqueue_select_cpu_near(int node)
1809 /* No point in doing this if NUMA isn't enabled for workqueues */
1810 if (!wq_numa_enabled)
1811 return WORK_CPU_UNBOUND;
1813 /* Delay binding to CPU if node is not valid or online */
1814 if (node < 0 || node >= MAX_NUMNODES || !node_online(node))
1815 return WORK_CPU_UNBOUND;
1817 /* Use local node/cpu if we are already there */
1818 cpu = raw_smp_processor_id();
1819 if (node == cpu_to_node(cpu))
1822 /* Use "random" otherwise know as "first" online CPU of node */
1823 cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
1825 /* If CPU is valid return that, otherwise just defer */
1826 return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND;
1830 * queue_work_node - queue work on a "random" cpu for a given NUMA node
1831 * @node: NUMA node that we are targeting the work for
1832 * @wq: workqueue to use
1833 * @work: work to queue
1835 * We queue the work to a "random" CPU within a given NUMA node. The basic
1836 * idea here is to provide a way to somehow associate work with a given
1839 * This function will only make a best effort attempt at getting this onto
1840 * the right NUMA node. If no node is requested or the requested node is
1841 * offline then we just fall back to standard queue_work behavior.
1843 * Currently the "random" CPU ends up being the first available CPU in the
1844 * intersection of cpu_online_mask and the cpumask of the node, unless we
1845 * are running on the node. In that case we just use the current CPU.
1847 * Return: %false if @work was already on a queue, %true otherwise.
1849 bool queue_work_node(int node, struct workqueue_struct *wq,
1850 struct work_struct *work)
1852 unsigned long flags;
1856 * This current implementation is specific to unbound workqueues.
1857 * Specifically we only return the first available CPU for a given
1858 * node instead of cycling through individual CPUs within the node.
1860 * If this is used with a per-cpu workqueue then the logic in
1861 * workqueue_select_cpu_near would need to be updated to allow for
1862 * some round robin type logic.
1864 WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND));
1866 local_irq_save(flags);
1868 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1869 int cpu = workqueue_select_cpu_near(node);
1871 __queue_work(cpu, wq, work);
1875 local_irq_restore(flags);
1878 EXPORT_SYMBOL_GPL(queue_work_node);
1880 void delayed_work_timer_fn(struct timer_list *t)
1882 struct delayed_work *dwork = from_timer(dwork, t, timer);
1884 /* should have been called from irqsafe timer with irq already off */
1885 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
1887 EXPORT_SYMBOL(delayed_work_timer_fn);
1889 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
1890 struct delayed_work *dwork, unsigned long delay)
1892 struct timer_list *timer = &dwork->timer;
1893 struct work_struct *work = &dwork->work;
1896 WARN_ON_ONCE(timer->function != delayed_work_timer_fn);
1897 WARN_ON_ONCE(timer_pending(timer));
1898 WARN_ON_ONCE(!list_empty(&work->entry));
1901 * If @delay is 0, queue @dwork->work immediately. This is for
1902 * both optimization and correctness. The earliest @timer can
1903 * expire is on the closest next tick and delayed_work users depend
1904 * on that there's no such delay when @delay is 0.
1907 __queue_work(cpu, wq, &dwork->work);
1913 timer->expires = jiffies + delay;
1915 if (unlikely(cpu != WORK_CPU_UNBOUND))
1916 add_timer_on(timer, cpu);
1922 * queue_delayed_work_on - queue work on specific CPU after delay
1923 * @cpu: CPU number to execute work on
1924 * @wq: workqueue to use
1925 * @dwork: work to queue
1926 * @delay: number of jiffies to wait before queueing
1928 * Return: %false if @work was already on a queue, %true otherwise. If
1929 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1932 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1933 struct delayed_work *dwork, unsigned long delay)
1935 struct work_struct *work = &dwork->work;
1937 unsigned long flags;
1939 /* read the comment in __queue_work() */
1940 local_irq_save(flags);
1942 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1943 __queue_delayed_work(cpu, wq, dwork, delay);
1947 local_irq_restore(flags);
1950 EXPORT_SYMBOL(queue_delayed_work_on);
1953 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1954 * @cpu: CPU number to execute work on
1955 * @wq: workqueue to use
1956 * @dwork: work to queue
1957 * @delay: number of jiffies to wait before queueing
1959 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1960 * modify @dwork's timer so that it expires after @delay. If @delay is
1961 * zero, @work is guaranteed to be scheduled immediately regardless of its
1964 * Return: %false if @dwork was idle and queued, %true if @dwork was
1965 * pending and its timer was modified.
1967 * This function is safe to call from any context including IRQ handler.
1968 * See try_to_grab_pending() for details.
1970 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
1971 struct delayed_work *dwork, unsigned long delay)
1973 unsigned long flags;
1977 ret = try_to_grab_pending(&dwork->work, true, &flags);
1978 } while (unlikely(ret == -EAGAIN));
1980 if (likely(ret >= 0)) {
1981 __queue_delayed_work(cpu, wq, dwork, delay);
1982 local_irq_restore(flags);
1985 /* -ENOENT from try_to_grab_pending() becomes %true */
1988 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
1990 static void rcu_work_rcufn(struct rcu_head *rcu)
1992 struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
1994 /* read the comment in __queue_work() */
1995 local_irq_disable();
1996 __queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
2001 * queue_rcu_work - queue work after a RCU grace period
2002 * @wq: workqueue to use
2003 * @rwork: work to queue
2005 * Return: %false if @rwork was already pending, %true otherwise. Note
2006 * that a full RCU grace period is guaranteed only after a %true return.
2007 * While @rwork is guaranteed to be executed after a %false return, the
2008 * execution may happen before a full RCU grace period has passed.
2010 bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
2012 struct work_struct *work = &rwork->work;
2014 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
2016 call_rcu_hurry(&rwork->rcu, rcu_work_rcufn);
2022 EXPORT_SYMBOL(queue_rcu_work);
2024 static struct worker *alloc_worker(int node)
2026 struct worker *worker;
2028 worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
2030 INIT_LIST_HEAD(&worker->entry);
2031 INIT_LIST_HEAD(&worker->scheduled);
2032 INIT_LIST_HEAD(&worker->node);
2033 /* on creation a worker is in !idle && prep state */
2034 worker->flags = WORKER_PREP;
2040 * worker_attach_to_pool() - attach a worker to a pool
2041 * @worker: worker to be attached
2042 * @pool: the target pool
2044 * Attach @worker to @pool. Once attached, the %WORKER_UNBOUND flag and
2045 * cpu-binding of @worker are kept coordinated with the pool across
2048 static void worker_attach_to_pool(struct worker *worker,
2049 struct worker_pool *pool)
2051 mutex_lock(&wq_pool_attach_mutex);
2054 * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains
2055 * stable across this function. See the comments above the flag
2056 * definition for details.
2058 if (pool->flags & POOL_DISASSOCIATED)
2059 worker->flags |= WORKER_UNBOUND;
2061 kthread_set_per_cpu(worker->task, pool->cpu);
2063 if (worker->rescue_wq)
2064 set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
2066 list_add_tail(&worker->node, &pool->workers);
2067 worker->pool = pool;
2069 mutex_unlock(&wq_pool_attach_mutex);
2073 * worker_detach_from_pool() - detach a worker from its pool
2074 * @worker: worker which is attached to its pool
2076 * Undo the attaching which had been done in worker_attach_to_pool(). The
2077 * caller worker shouldn't access to the pool after detached except it has
2078 * other reference to the pool.
2080 static void worker_detach_from_pool(struct worker *worker)
2082 struct worker_pool *pool = worker->pool;
2083 struct completion *detach_completion = NULL;
2085 mutex_lock(&wq_pool_attach_mutex);
2087 kthread_set_per_cpu(worker->task, -1);
2088 list_del(&worker->node);
2089 worker->pool = NULL;
2091 if (list_empty(&pool->workers) && list_empty(&pool->dying_workers))
2092 detach_completion = pool->detach_completion;
2093 mutex_unlock(&wq_pool_attach_mutex);
2095 /* clear leftover flags without pool->lock after it is detached */
2096 worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
2098 if (detach_completion)
2099 complete(detach_completion);
2103 * create_worker - create a new workqueue worker
2104 * @pool: pool the new worker will belong to
2106 * Create and start a new worker which is attached to @pool.
2109 * Might sleep. Does GFP_KERNEL allocations.
2112 * Pointer to the newly created worker.
2114 static struct worker *create_worker(struct worker_pool *pool)
2116 struct worker *worker;
2120 /* ID is needed to determine kthread name */
2121 id = ida_alloc(&pool->worker_ida, GFP_KERNEL);
2123 pr_err_once("workqueue: Failed to allocate a worker ID: %pe\n",
2128 worker = alloc_worker(pool->node);
2130 pr_err_once("workqueue: Failed to allocate a worker\n");
2137 snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
2138 pool->attrs->nice < 0 ? "H" : "");
2140 snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
2142 worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
2143 "kworker/%s", id_buf);
2144 if (IS_ERR(worker->task)) {
2145 if (PTR_ERR(worker->task) == -EINTR) {
2146 pr_err("workqueue: Interrupted when creating a worker thread \"kworker/%s\"\n",
2149 pr_err_once("workqueue: Failed to create a worker thread: %pe",
2155 set_user_nice(worker->task, pool->attrs->nice);
2156 kthread_bind_mask(worker->task, pool->attrs->cpumask);
2158 /* successful, attach the worker to the pool */
2159 worker_attach_to_pool(worker, pool);
2161 /* start the newly created worker */
2162 raw_spin_lock_irq(&pool->lock);
2163 worker->pool->nr_workers++;
2164 worker_enter_idle(worker);
2165 wake_up_process(worker->task);
2166 raw_spin_unlock_irq(&pool->lock);
2171 ida_free(&pool->worker_ida, id);
2176 static void unbind_worker(struct worker *worker)
2178 lockdep_assert_held(&wq_pool_attach_mutex);
2180 kthread_set_per_cpu(worker->task, -1);
2181 if (cpumask_intersects(wq_unbound_cpumask, cpu_active_mask))
2182 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, wq_unbound_cpumask) < 0);
2184 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, cpu_possible_mask) < 0);
2187 static void wake_dying_workers(struct list_head *cull_list)
2189 struct worker *worker, *tmp;
2191 list_for_each_entry_safe(worker, tmp, cull_list, entry) {
2192 list_del_init(&worker->entry);
2193 unbind_worker(worker);
2195 * If the worker was somehow already running, then it had to be
2196 * in pool->idle_list when set_worker_dying() happened or we
2197 * wouldn't have gotten here.
2199 * Thus, the worker must either have observed the WORKER_DIE
2200 * flag, or have set its state to TASK_IDLE. Either way, the
2201 * below will be observed by the worker and is safe to do
2202 * outside of pool->lock.
2204 wake_up_process(worker->task);
2209 * set_worker_dying - Tag a worker for destruction
2210 * @worker: worker to be destroyed
2211 * @list: transfer worker away from its pool->idle_list and into list
2213 * Tag @worker for destruction and adjust @pool stats accordingly. The worker
2217 * raw_spin_lock_irq(pool->lock).
2219 static void set_worker_dying(struct worker *worker, struct list_head *list)
2221 struct worker_pool *pool = worker->pool;
2223 lockdep_assert_held(&pool->lock);
2224 lockdep_assert_held(&wq_pool_attach_mutex);
2226 /* sanity check frenzy */
2227 if (WARN_ON(worker->current_work) ||
2228 WARN_ON(!list_empty(&worker->scheduled)) ||
2229 WARN_ON(!(worker->flags & WORKER_IDLE)))
2235 worker->flags |= WORKER_DIE;
2237 list_move(&worker->entry, list);
2238 list_move(&worker->node, &pool->dying_workers);
2242 * idle_worker_timeout - check if some idle workers can now be deleted.
2243 * @t: The pool's idle_timer that just expired
2245 * The timer is armed in worker_enter_idle(). Note that it isn't disarmed in
2246 * worker_leave_idle(), as a worker flicking between idle and active while its
2247 * pool is at the too_many_workers() tipping point would cause too much timer
2248 * housekeeping overhead. Since IDLE_WORKER_TIMEOUT is long enough, we just let
2249 * it expire and re-evaluate things from there.
2251 static void idle_worker_timeout(struct timer_list *t)
2253 struct worker_pool *pool = from_timer(pool, t, idle_timer);
2254 bool do_cull = false;
2256 if (work_pending(&pool->idle_cull_work))
2259 raw_spin_lock_irq(&pool->lock);
2261 if (too_many_workers(pool)) {
2262 struct worker *worker;
2263 unsigned long expires;
2265 /* idle_list is kept in LIFO order, check the last one */
2266 worker = list_entry(pool->idle_list.prev, struct worker, entry);
2267 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2268 do_cull = !time_before(jiffies, expires);
2271 mod_timer(&pool->idle_timer, expires);
2273 raw_spin_unlock_irq(&pool->lock);
2276 queue_work(system_unbound_wq, &pool->idle_cull_work);
2280 * idle_cull_fn - cull workers that have been idle for too long.
2281 * @work: the pool's work for handling these idle workers
2283 * This goes through a pool's idle workers and gets rid of those that have been
2284 * idle for at least IDLE_WORKER_TIMEOUT seconds.
2286 * We don't want to disturb isolated CPUs because of a pcpu kworker being
2287 * culled, so this also resets worker affinity. This requires a sleepable
2288 * context, hence the split between timer callback and work item.
2290 static void idle_cull_fn(struct work_struct *work)
2292 struct worker_pool *pool = container_of(work, struct worker_pool, idle_cull_work);
2293 LIST_HEAD(cull_list);
2296 * Grabbing wq_pool_attach_mutex here ensures an already-running worker
2297 * cannot proceed beyong worker_detach_from_pool() in its self-destruct
2298 * path. This is required as a previously-preempted worker could run after
2299 * set_worker_dying() has happened but before wake_dying_workers() did.
2301 mutex_lock(&wq_pool_attach_mutex);
2302 raw_spin_lock_irq(&pool->lock);
2304 while (too_many_workers(pool)) {
2305 struct worker *worker;
2306 unsigned long expires;
2308 worker = list_entry(pool->idle_list.prev, struct worker, entry);
2309 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2311 if (time_before(jiffies, expires)) {
2312 mod_timer(&pool->idle_timer, expires);
2316 set_worker_dying(worker, &cull_list);
2319 raw_spin_unlock_irq(&pool->lock);
2320 wake_dying_workers(&cull_list);
2321 mutex_unlock(&wq_pool_attach_mutex);
2324 static void send_mayday(struct work_struct *work)
2326 struct pool_workqueue *pwq = get_work_pwq(work);
2327 struct workqueue_struct *wq = pwq->wq;
2329 lockdep_assert_held(&wq_mayday_lock);
2334 /* mayday mayday mayday */
2335 if (list_empty(&pwq->mayday_node)) {
2337 * If @pwq is for an unbound wq, its base ref may be put at
2338 * any time due to an attribute change. Pin @pwq until the
2339 * rescuer is done with it.
2342 list_add_tail(&pwq->mayday_node, &wq->maydays);
2343 wake_up_process(wq->rescuer->task);
2344 pwq->stats[PWQ_STAT_MAYDAY]++;
2348 static void pool_mayday_timeout(struct timer_list *t)
2350 struct worker_pool *pool = from_timer(pool, t, mayday_timer);
2351 struct work_struct *work;
2353 raw_spin_lock_irq(&pool->lock);
2354 raw_spin_lock(&wq_mayday_lock); /* for wq->maydays */
2356 if (need_to_create_worker(pool)) {
2358 * We've been trying to create a new worker but
2359 * haven't been successful. We might be hitting an
2360 * allocation deadlock. Send distress signals to
2363 list_for_each_entry(work, &pool->worklist, entry)
2367 raw_spin_unlock(&wq_mayday_lock);
2368 raw_spin_unlock_irq(&pool->lock);
2370 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
2374 * maybe_create_worker - create a new worker if necessary
2375 * @pool: pool to create a new worker for
2377 * Create a new worker for @pool if necessary. @pool is guaranteed to
2378 * have at least one idle worker on return from this function. If
2379 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
2380 * sent to all rescuers with works scheduled on @pool to resolve
2381 * possible allocation deadlock.
2383 * On return, need_to_create_worker() is guaranteed to be %false and
2384 * may_start_working() %true.
2387 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2388 * multiple times. Does GFP_KERNEL allocations. Called only from
2391 static void maybe_create_worker(struct worker_pool *pool)
2392 __releases(&pool->lock)
2393 __acquires(&pool->lock)
2396 raw_spin_unlock_irq(&pool->lock);
2398 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
2399 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
2402 if (create_worker(pool) || !need_to_create_worker(pool))
2405 schedule_timeout_interruptible(CREATE_COOLDOWN);
2407 if (!need_to_create_worker(pool))
2411 del_timer_sync(&pool->mayday_timer);
2412 raw_spin_lock_irq(&pool->lock);
2414 * This is necessary even after a new worker was just successfully
2415 * created as @pool->lock was dropped and the new worker might have
2416 * already become busy.
2418 if (need_to_create_worker(pool))
2423 * manage_workers - manage worker pool
2426 * Assume the manager role and manage the worker pool @worker belongs
2427 * to. At any given time, there can be only zero or one manager per
2428 * pool. The exclusion is handled automatically by this function.
2430 * The caller can safely start processing works on false return. On
2431 * true return, it's guaranteed that need_to_create_worker() is false
2432 * and may_start_working() is true.
2435 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2436 * multiple times. Does GFP_KERNEL allocations.
2439 * %false if the pool doesn't need management and the caller can safely
2440 * start processing works, %true if management function was performed and
2441 * the conditions that the caller verified before calling the function may
2442 * no longer be true.
2444 static bool manage_workers(struct worker *worker)
2446 struct worker_pool *pool = worker->pool;
2448 if (pool->flags & POOL_MANAGER_ACTIVE)
2451 pool->flags |= POOL_MANAGER_ACTIVE;
2452 pool->manager = worker;
2454 maybe_create_worker(pool);
2456 pool->manager = NULL;
2457 pool->flags &= ~POOL_MANAGER_ACTIVE;
2458 rcuwait_wake_up(&manager_wait);
2463 * process_one_work - process single work
2465 * @work: work to process
2467 * Process @work. This function contains all the logics necessary to
2468 * process a single work including synchronization against and
2469 * interaction with other workers on the same cpu, queueing and
2470 * flushing. As long as context requirement is met, any worker can
2471 * call this function to process a work.
2474 * raw_spin_lock_irq(pool->lock) which is released and regrabbed.
2476 static void process_one_work(struct worker *worker, struct work_struct *work)
2477 __releases(&pool->lock)
2478 __acquires(&pool->lock)
2480 struct pool_workqueue *pwq = get_work_pwq(work);
2481 struct worker_pool *pool = worker->pool;
2482 unsigned long work_data;
2483 struct worker *collision;
2484 #ifdef CONFIG_LOCKDEP
2486 * It is permissible to free the struct work_struct from
2487 * inside the function that is called from it, this we need to
2488 * take into account for lockdep too. To avoid bogus "held
2489 * lock freed" warnings as well as problems when looking into
2490 * work->lockdep_map, make a copy and use that here.
2492 struct lockdep_map lockdep_map;
2494 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
2496 /* ensure we're on the correct CPU */
2497 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2498 raw_smp_processor_id() != pool->cpu);
2501 * A single work shouldn't be executed concurrently by
2502 * multiple workers on a single cpu. Check whether anyone is
2503 * already processing the work. If so, defer the work to the
2504 * currently executing one.
2506 collision = find_worker_executing_work(pool, work);
2507 if (unlikely(collision)) {
2508 move_linked_works(work, &collision->scheduled, NULL);
2512 /* claim and dequeue */
2513 debug_work_deactivate(work);
2514 hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2515 worker->current_work = work;
2516 worker->current_func = work->func;
2517 worker->current_pwq = pwq;
2518 worker->current_at = worker->task->se.sum_exec_runtime;
2519 work_data = *work_data_bits(work);
2520 worker->current_color = get_work_color(work_data);
2523 * Record wq name for cmdline and debug reporting, may get
2524 * overridden through set_worker_desc().
2526 strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
2528 list_del_init(&work->entry);
2531 * CPU intensive works don't participate in concurrency management.
2532 * They're the scheduler's responsibility. This takes @worker out
2533 * of concurrency management and the next code block will chain
2534 * execution of the pending work items.
2536 if (unlikely(pwq->wq->flags & WQ_CPU_INTENSIVE))
2537 worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2540 * Wake up another worker if necessary. The condition is always
2541 * false for normal per-cpu workers since nr_running would always
2542 * be >= 1 at this point. This is used to chain execution of the
2543 * pending work items for WORKER_NOT_RUNNING workers such as the
2544 * UNBOUND and CPU_INTENSIVE ones.
2546 if (need_more_worker(pool))
2547 wake_up_worker(pool);
2550 * Record the last pool and clear PENDING which should be the last
2551 * update to @work. Also, do this inside @pool->lock so that
2552 * PENDING and queued state changes happen together while IRQ is
2555 set_work_pool_and_clear_pending(work, pool->id);
2557 raw_spin_unlock_irq(&pool->lock);
2559 lock_map_acquire(&pwq->wq->lockdep_map);
2560 lock_map_acquire(&lockdep_map);
2562 * Strictly speaking we should mark the invariant state without holding
2563 * any locks, that is, before these two lock_map_acquire()'s.
2565 * However, that would result in:
2572 * Which would create W1->C->W1 dependencies, even though there is no
2573 * actual deadlock possible. There are two solutions, using a
2574 * read-recursive acquire on the work(queue) 'locks', but this will then
2575 * hit the lockdep limitation on recursive locks, or simply discard
2578 * AFAICT there is no possible deadlock scenario between the
2579 * flush_work() and complete() primitives (except for single-threaded
2580 * workqueues), so hiding them isn't a problem.
2582 lockdep_invariant_state(true);
2583 pwq->stats[PWQ_STAT_STARTED]++;
2584 trace_workqueue_execute_start(work);
2585 worker->current_func(work);
2587 * While we must be careful to not use "work" after this, the trace
2588 * point will only record its address.
2590 trace_workqueue_execute_end(work, worker->current_func);
2591 pwq->stats[PWQ_STAT_COMPLETED]++;
2592 lock_map_release(&lockdep_map);
2593 lock_map_release(&pwq->wq->lockdep_map);
2595 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2596 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2597 " last function: %ps\n",
2598 current->comm, preempt_count(), task_pid_nr(current),
2599 worker->current_func);
2600 debug_show_held_locks(current);
2605 * The following prevents a kworker from hogging CPU on !PREEMPTION
2606 * kernels, where a requeueing work item waiting for something to
2607 * happen could deadlock with stop_machine as such work item could
2608 * indefinitely requeue itself while all other CPUs are trapped in
2609 * stop_machine. At the same time, report a quiescent RCU state so
2610 * the same condition doesn't freeze RCU.
2614 raw_spin_lock_irq(&pool->lock);
2617 * In addition to %WQ_CPU_INTENSIVE, @worker may also have been marked
2618 * CPU intensive by wq_worker_tick() if @work hogged CPU longer than
2619 * wq_cpu_intensive_thresh_us. Clear it.
2621 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2623 /* tag the worker for identification in schedule() */
2624 worker->last_func = worker->current_func;
2626 /* we're done with it, release */
2627 hash_del(&worker->hentry);
2628 worker->current_work = NULL;
2629 worker->current_func = NULL;
2630 worker->current_pwq = NULL;
2631 worker->current_color = INT_MAX;
2632 pwq_dec_nr_in_flight(pwq, work_data);
2636 * process_scheduled_works - process scheduled works
2639 * Process all scheduled works. Please note that the scheduled list
2640 * may change while processing a work, so this function repeatedly
2641 * fetches a work from the top and executes it.
2644 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2647 static void process_scheduled_works(struct worker *worker)
2649 struct work_struct *work;
2652 while ((work = list_first_entry_or_null(&worker->scheduled,
2653 struct work_struct, entry))) {
2655 worker->pool->watchdog_ts = jiffies;
2658 process_one_work(worker, work);
2662 static void set_pf_worker(bool val)
2664 mutex_lock(&wq_pool_attach_mutex);
2666 current->flags |= PF_WQ_WORKER;
2668 current->flags &= ~PF_WQ_WORKER;
2669 mutex_unlock(&wq_pool_attach_mutex);
2673 * worker_thread - the worker thread function
2676 * The worker thread function. All workers belong to a worker_pool -
2677 * either a per-cpu one or dynamic unbound one. These workers process all
2678 * work items regardless of their specific target workqueue. The only
2679 * exception is work items which belong to workqueues with a rescuer which
2680 * will be explained in rescuer_thread().
2684 static int worker_thread(void *__worker)
2686 struct worker *worker = __worker;
2687 struct worker_pool *pool = worker->pool;
2689 /* tell the scheduler that this is a workqueue worker */
2690 set_pf_worker(true);
2692 raw_spin_lock_irq(&pool->lock);
2694 /* am I supposed to die? */
2695 if (unlikely(worker->flags & WORKER_DIE)) {
2696 raw_spin_unlock_irq(&pool->lock);
2697 set_pf_worker(false);
2699 set_task_comm(worker->task, "kworker/dying");
2700 ida_free(&pool->worker_ida, worker->id);
2701 worker_detach_from_pool(worker);
2702 WARN_ON_ONCE(!list_empty(&worker->entry));
2707 worker_leave_idle(worker);
2709 /* no more worker necessary? */
2710 if (!need_more_worker(pool))
2713 /* do we need to manage? */
2714 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2718 * ->scheduled list can only be filled while a worker is
2719 * preparing to process a work or actually processing it.
2720 * Make sure nobody diddled with it while I was sleeping.
2722 WARN_ON_ONCE(!list_empty(&worker->scheduled));
2725 * Finish PREP stage. We're guaranteed to have at least one idle
2726 * worker or that someone else has already assumed the manager
2727 * role. This is where @worker starts participating in concurrency
2728 * management if applicable and concurrency management is restored
2729 * after being rebound. See rebind_workers() for details.
2731 worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2734 struct work_struct *work =
2735 list_first_entry(&pool->worklist,
2736 struct work_struct, entry);
2738 move_linked_works(work, &worker->scheduled, NULL);
2739 process_scheduled_works(worker);
2740 } while (keep_working(pool));
2742 worker_set_flags(worker, WORKER_PREP);
2745 * pool->lock is held and there's no work to process and no need to
2746 * manage, sleep. Workers are woken up only while holding
2747 * pool->lock or from local cpu, so setting the current state
2748 * before releasing pool->lock is enough to prevent losing any
2751 worker_enter_idle(worker);
2752 __set_current_state(TASK_IDLE);
2753 raw_spin_unlock_irq(&pool->lock);
2759 * rescuer_thread - the rescuer thread function
2762 * Workqueue rescuer thread function. There's one rescuer for each
2763 * workqueue which has WQ_MEM_RECLAIM set.
2765 * Regular work processing on a pool may block trying to create a new
2766 * worker which uses GFP_KERNEL allocation which has slight chance of
2767 * developing into deadlock if some works currently on the same queue
2768 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2769 * the problem rescuer solves.
2771 * When such condition is possible, the pool summons rescuers of all
2772 * workqueues which have works queued on the pool and let them process
2773 * those works so that forward progress can be guaranteed.
2775 * This should happen rarely.
2779 static int rescuer_thread(void *__rescuer)
2781 struct worker *rescuer = __rescuer;
2782 struct workqueue_struct *wq = rescuer->rescue_wq;
2783 struct list_head *scheduled = &rescuer->scheduled;
2786 set_user_nice(current, RESCUER_NICE_LEVEL);
2789 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2790 * doesn't participate in concurrency management.
2792 set_pf_worker(true);
2794 set_current_state(TASK_IDLE);
2797 * By the time the rescuer is requested to stop, the workqueue
2798 * shouldn't have any work pending, but @wq->maydays may still have
2799 * pwq(s) queued. This can happen by non-rescuer workers consuming
2800 * all the work items before the rescuer got to them. Go through
2801 * @wq->maydays processing before acting on should_stop so that the
2802 * list is always empty on exit.
2804 should_stop = kthread_should_stop();
2806 /* see whether any pwq is asking for help */
2807 raw_spin_lock_irq(&wq_mayday_lock);
2809 while (!list_empty(&wq->maydays)) {
2810 struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2811 struct pool_workqueue, mayday_node);
2812 struct worker_pool *pool = pwq->pool;
2813 struct work_struct *work, *n;
2815 __set_current_state(TASK_RUNNING);
2816 list_del_init(&pwq->mayday_node);
2818 raw_spin_unlock_irq(&wq_mayday_lock);
2820 worker_attach_to_pool(rescuer, pool);
2822 raw_spin_lock_irq(&pool->lock);
2825 * Slurp in all works issued via this workqueue and
2828 WARN_ON_ONCE(!list_empty(scheduled));
2829 list_for_each_entry_safe(work, n, &pool->worklist, entry) {
2830 if (get_work_pwq(work) == pwq) {
2831 move_linked_works(work, scheduled, &n);
2832 pwq->stats[PWQ_STAT_RESCUED]++;
2836 if (!list_empty(scheduled)) {
2837 process_scheduled_works(rescuer);
2840 * The above execution of rescued work items could
2841 * have created more to rescue through
2842 * pwq_activate_first_inactive() or chained
2843 * queueing. Let's put @pwq back on mayday list so
2844 * that such back-to-back work items, which may be
2845 * being used to relieve memory pressure, don't
2846 * incur MAYDAY_INTERVAL delay inbetween.
2848 if (pwq->nr_active && need_to_create_worker(pool)) {
2849 raw_spin_lock(&wq_mayday_lock);
2851 * Queue iff we aren't racing destruction
2852 * and somebody else hasn't queued it already.
2854 if (wq->rescuer && list_empty(&pwq->mayday_node)) {
2856 list_add_tail(&pwq->mayday_node, &wq->maydays);
2858 raw_spin_unlock(&wq_mayday_lock);
2863 * Put the reference grabbed by send_mayday(). @pool won't
2864 * go away while we're still attached to it.
2869 * Leave this pool. If need_more_worker() is %true, notify a
2870 * regular worker; otherwise, we end up with 0 concurrency
2871 * and stalling the execution.
2873 if (need_more_worker(pool))
2874 wake_up_worker(pool);
2876 raw_spin_unlock_irq(&pool->lock);
2878 worker_detach_from_pool(rescuer);
2880 raw_spin_lock_irq(&wq_mayday_lock);
2883 raw_spin_unlock_irq(&wq_mayday_lock);
2886 __set_current_state(TASK_RUNNING);
2887 set_pf_worker(false);
2891 /* rescuers should never participate in concurrency management */
2892 WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2898 * check_flush_dependency - check for flush dependency sanity
2899 * @target_wq: workqueue being flushed
2900 * @target_work: work item being flushed (NULL for workqueue flushes)
2902 * %current is trying to flush the whole @target_wq or @target_work on it.
2903 * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
2904 * reclaiming memory or running on a workqueue which doesn't have
2905 * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
2908 static void check_flush_dependency(struct workqueue_struct *target_wq,
2909 struct work_struct *target_work)
2911 work_func_t target_func = target_work ? target_work->func : NULL;
2912 struct worker *worker;
2914 if (target_wq->flags & WQ_MEM_RECLAIM)
2917 worker = current_wq_worker();
2919 WARN_ONCE(current->flags & PF_MEMALLOC,
2920 "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps",
2921 current->pid, current->comm, target_wq->name, target_func);
2922 WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
2923 (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
2924 "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps",
2925 worker->current_pwq->wq->name, worker->current_func,
2926 target_wq->name, target_func);
2930 struct work_struct work;
2931 struct completion done;
2932 struct task_struct *task; /* purely informational */
2935 static void wq_barrier_func(struct work_struct *work)
2937 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2938 complete(&barr->done);
2942 * insert_wq_barrier - insert a barrier work
2943 * @pwq: pwq to insert barrier into
2944 * @barr: wq_barrier to insert
2945 * @target: target work to attach @barr to
2946 * @worker: worker currently executing @target, NULL if @target is not executing
2948 * @barr is linked to @target such that @barr is completed only after
2949 * @target finishes execution. Please note that the ordering
2950 * guarantee is observed only with respect to @target and on the local
2953 * Currently, a queued barrier can't be canceled. This is because
2954 * try_to_grab_pending() can't determine whether the work to be
2955 * grabbed is at the head of the queue and thus can't clear LINKED
2956 * flag of the previous work while there must be a valid next work
2957 * after a work with LINKED flag set.
2959 * Note that when @worker is non-NULL, @target may be modified
2960 * underneath us, so we can't reliably determine pwq from @target.
2963 * raw_spin_lock_irq(pool->lock).
2965 static void insert_wq_barrier(struct pool_workqueue *pwq,
2966 struct wq_barrier *barr,
2967 struct work_struct *target, struct worker *worker)
2969 unsigned int work_flags = 0;
2970 unsigned int work_color;
2971 struct list_head *head;
2974 * debugobject calls are safe here even with pool->lock locked
2975 * as we know for sure that this will not trigger any of the
2976 * checks and call back into the fixup functions where we
2979 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2980 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2982 init_completion_map(&barr->done, &target->lockdep_map);
2984 barr->task = current;
2986 /* The barrier work item does not participate in pwq->nr_active. */
2987 work_flags |= WORK_STRUCT_INACTIVE;
2990 * If @target is currently being executed, schedule the
2991 * barrier to the worker; otherwise, put it after @target.
2994 head = worker->scheduled.next;
2995 work_color = worker->current_color;
2997 unsigned long *bits = work_data_bits(target);
2999 head = target->entry.next;
3000 /* there can already be other linked works, inherit and set */
3001 work_flags |= *bits & WORK_STRUCT_LINKED;
3002 work_color = get_work_color(*bits);
3003 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
3006 pwq->nr_in_flight[work_color]++;
3007 work_flags |= work_color_to_flags(work_color);
3009 insert_work(pwq, &barr->work, head, work_flags);
3013 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
3014 * @wq: workqueue being flushed
3015 * @flush_color: new flush color, < 0 for no-op
3016 * @work_color: new work color, < 0 for no-op
3018 * Prepare pwqs for workqueue flushing.
3020 * If @flush_color is non-negative, flush_color on all pwqs should be
3021 * -1. If no pwq has in-flight commands at the specified color, all
3022 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
3023 * has in flight commands, its pwq->flush_color is set to
3024 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
3025 * wakeup logic is armed and %true is returned.
3027 * The caller should have initialized @wq->first_flusher prior to
3028 * calling this function with non-negative @flush_color. If
3029 * @flush_color is negative, no flush color update is done and %false
3032 * If @work_color is non-negative, all pwqs should have the same
3033 * work_color which is previous to @work_color and all will be
3034 * advanced to @work_color.
3037 * mutex_lock(wq->mutex).
3040 * %true if @flush_color >= 0 and there's something to flush. %false
3043 static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
3044 int flush_color, int work_color)
3047 struct pool_workqueue *pwq;
3049 if (flush_color >= 0) {
3050 WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
3051 atomic_set(&wq->nr_pwqs_to_flush, 1);
3054 for_each_pwq(pwq, wq) {
3055 struct worker_pool *pool = pwq->pool;
3057 raw_spin_lock_irq(&pool->lock);
3059 if (flush_color >= 0) {
3060 WARN_ON_ONCE(pwq->flush_color != -1);
3062 if (pwq->nr_in_flight[flush_color]) {
3063 pwq->flush_color = flush_color;
3064 atomic_inc(&wq->nr_pwqs_to_flush);
3069 if (work_color >= 0) {
3070 WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
3071 pwq->work_color = work_color;
3074 raw_spin_unlock_irq(&pool->lock);
3077 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
3078 complete(&wq->first_flusher->done);
3084 * __flush_workqueue - ensure that any scheduled work has run to completion.
3085 * @wq: workqueue to flush
3087 * This function sleeps until all work items which were queued on entry
3088 * have finished execution, but it is not livelocked by new incoming ones.
3090 void __flush_workqueue(struct workqueue_struct *wq)
3092 struct wq_flusher this_flusher = {
3093 .list = LIST_HEAD_INIT(this_flusher.list),
3095 .done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map),
3099 if (WARN_ON(!wq_online))
3102 lock_map_acquire(&wq->lockdep_map);
3103 lock_map_release(&wq->lockdep_map);
3105 mutex_lock(&wq->mutex);
3108 * Start-to-wait phase
3110 next_color = work_next_color(wq->work_color);
3112 if (next_color != wq->flush_color) {
3114 * Color space is not full. The current work_color
3115 * becomes our flush_color and work_color is advanced
3118 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
3119 this_flusher.flush_color = wq->work_color;
3120 wq->work_color = next_color;
3122 if (!wq->first_flusher) {
3123 /* no flush in progress, become the first flusher */
3124 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
3126 wq->first_flusher = &this_flusher;
3128 if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
3130 /* nothing to flush, done */
3131 wq->flush_color = next_color;
3132 wq->first_flusher = NULL;
3137 WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
3138 list_add_tail(&this_flusher.list, &wq->flusher_queue);
3139 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
3143 * Oops, color space is full, wait on overflow queue.
3144 * The next flush completion will assign us
3145 * flush_color and transfer to flusher_queue.
3147 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
3150 check_flush_dependency(wq, NULL);
3152 mutex_unlock(&wq->mutex);
3154 wait_for_completion(&this_flusher.done);
3157 * Wake-up-and-cascade phase
3159 * First flushers are responsible for cascading flushes and
3160 * handling overflow. Non-first flushers can simply return.
3162 if (READ_ONCE(wq->first_flusher) != &this_flusher)
3165 mutex_lock(&wq->mutex);
3167 /* we might have raced, check again with mutex held */
3168 if (wq->first_flusher != &this_flusher)
3171 WRITE_ONCE(wq->first_flusher, NULL);
3173 WARN_ON_ONCE(!list_empty(&this_flusher.list));
3174 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
3177 struct wq_flusher *next, *tmp;
3179 /* complete all the flushers sharing the current flush color */
3180 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
3181 if (next->flush_color != wq->flush_color)
3183 list_del_init(&next->list);
3184 complete(&next->done);
3187 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
3188 wq->flush_color != work_next_color(wq->work_color));
3190 /* this flush_color is finished, advance by one */
3191 wq->flush_color = work_next_color(wq->flush_color);
3193 /* one color has been freed, handle overflow queue */
3194 if (!list_empty(&wq->flusher_overflow)) {
3196 * Assign the same color to all overflowed
3197 * flushers, advance work_color and append to
3198 * flusher_queue. This is the start-to-wait
3199 * phase for these overflowed flushers.
3201 list_for_each_entry(tmp, &wq->flusher_overflow, list)
3202 tmp->flush_color = wq->work_color;
3204 wq->work_color = work_next_color(wq->work_color);
3206 list_splice_tail_init(&wq->flusher_overflow,
3207 &wq->flusher_queue);
3208 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
3211 if (list_empty(&wq->flusher_queue)) {
3212 WARN_ON_ONCE(wq->flush_color != wq->work_color);
3217 * Need to flush more colors. Make the next flusher
3218 * the new first flusher and arm pwqs.
3220 WARN_ON_ONCE(wq->flush_color == wq->work_color);
3221 WARN_ON_ONCE(wq->flush_color != next->flush_color);
3223 list_del_init(&next->list);
3224 wq->first_flusher = next;
3226 if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
3230 * Meh... this color is already done, clear first
3231 * flusher and repeat cascading.
3233 wq->first_flusher = NULL;
3237 mutex_unlock(&wq->mutex);
3239 EXPORT_SYMBOL(__flush_workqueue);
3242 * drain_workqueue - drain a workqueue
3243 * @wq: workqueue to drain
3245 * Wait until the workqueue becomes empty. While draining is in progress,
3246 * only chain queueing is allowed. IOW, only currently pending or running
3247 * work items on @wq can queue further work items on it. @wq is flushed
3248 * repeatedly until it becomes empty. The number of flushing is determined
3249 * by the depth of chaining and should be relatively short. Whine if it
3252 void drain_workqueue(struct workqueue_struct *wq)
3254 unsigned int flush_cnt = 0;
3255 struct pool_workqueue *pwq;
3258 * __queue_work() needs to test whether there are drainers, is much
3259 * hotter than drain_workqueue() and already looks at @wq->flags.
3260 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
3262 mutex_lock(&wq->mutex);
3263 if (!wq->nr_drainers++)
3264 wq->flags |= __WQ_DRAINING;
3265 mutex_unlock(&wq->mutex);
3267 __flush_workqueue(wq);
3269 mutex_lock(&wq->mutex);
3271 for_each_pwq(pwq, wq) {
3274 raw_spin_lock_irq(&pwq->pool->lock);
3275 drained = !pwq->nr_active && list_empty(&pwq->inactive_works);
3276 raw_spin_unlock_irq(&pwq->pool->lock);
3281 if (++flush_cnt == 10 ||
3282 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
3283 pr_warn("workqueue %s: %s() isn't complete after %u tries\n",
3284 wq->name, __func__, flush_cnt);
3286 mutex_unlock(&wq->mutex);
3290 if (!--wq->nr_drainers)
3291 wq->flags &= ~__WQ_DRAINING;
3292 mutex_unlock(&wq->mutex);
3294 EXPORT_SYMBOL_GPL(drain_workqueue);
3296 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
3299 struct worker *worker = NULL;
3300 struct worker_pool *pool;
3301 struct pool_workqueue *pwq;
3306 pool = get_work_pool(work);
3312 raw_spin_lock_irq(&pool->lock);
3313 /* see the comment in try_to_grab_pending() with the same code */
3314 pwq = get_work_pwq(work);
3316 if (unlikely(pwq->pool != pool))
3319 worker = find_worker_executing_work(pool, work);
3322 pwq = worker->current_pwq;
3325 check_flush_dependency(pwq->wq, work);
3327 insert_wq_barrier(pwq, barr, work, worker);
3328 raw_spin_unlock_irq(&pool->lock);
3331 * Force a lock recursion deadlock when using flush_work() inside a
3332 * single-threaded or rescuer equipped workqueue.
3334 * For single threaded workqueues the deadlock happens when the work
3335 * is after the work issuing the flush_work(). For rescuer equipped
3336 * workqueues the deadlock happens when the rescuer stalls, blocking
3340 (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)) {
3341 lock_map_acquire(&pwq->wq->lockdep_map);
3342 lock_map_release(&pwq->wq->lockdep_map);
3347 raw_spin_unlock_irq(&pool->lock);
3352 static bool __flush_work(struct work_struct *work, bool from_cancel)
3354 struct wq_barrier barr;
3356 if (WARN_ON(!wq_online))
3359 if (WARN_ON(!work->func))
3362 lock_map_acquire(&work->lockdep_map);
3363 lock_map_release(&work->lockdep_map);
3365 if (start_flush_work(work, &barr, from_cancel)) {
3366 wait_for_completion(&barr.done);
3367 destroy_work_on_stack(&barr.work);
3375 * flush_work - wait for a work to finish executing the last queueing instance
3376 * @work: the work to flush
3378 * Wait until @work has finished execution. @work is guaranteed to be idle
3379 * on return if it hasn't been requeued since flush started.
3382 * %true if flush_work() waited for the work to finish execution,
3383 * %false if it was already idle.
3385 bool flush_work(struct work_struct *work)
3387 return __flush_work(work, false);
3389 EXPORT_SYMBOL_GPL(flush_work);
3392 wait_queue_entry_t wait;
3393 struct work_struct *work;
3396 static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
3398 struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
3400 if (cwait->work != key)
3402 return autoremove_wake_function(wait, mode, sync, key);
3405 static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
3407 static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
3408 unsigned long flags;
3412 ret = try_to_grab_pending(work, is_dwork, &flags);
3414 * If someone else is already canceling, wait for it to
3415 * finish. flush_work() doesn't work for PREEMPT_NONE
3416 * because we may get scheduled between @work's completion
3417 * and the other canceling task resuming and clearing
3418 * CANCELING - flush_work() will return false immediately
3419 * as @work is no longer busy, try_to_grab_pending() will
3420 * return -ENOENT as @work is still being canceled and the
3421 * other canceling task won't be able to clear CANCELING as
3422 * we're hogging the CPU.
3424 * Let's wait for completion using a waitqueue. As this
3425 * may lead to the thundering herd problem, use a custom
3426 * wake function which matches @work along with exclusive
3429 if (unlikely(ret == -ENOENT)) {
3430 struct cwt_wait cwait;
3432 init_wait(&cwait.wait);
3433 cwait.wait.func = cwt_wakefn;
3436 prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
3437 TASK_UNINTERRUPTIBLE);
3438 if (work_is_canceling(work))
3440 finish_wait(&cancel_waitq, &cwait.wait);
3442 } while (unlikely(ret < 0));
3444 /* tell other tasks trying to grab @work to back off */
3445 mark_work_canceling(work);
3446 local_irq_restore(flags);
3449 * This allows canceling during early boot. We know that @work
3453 __flush_work(work, true);
3455 clear_work_data(work);
3458 * Paired with prepare_to_wait() above so that either
3459 * waitqueue_active() is visible here or !work_is_canceling() is
3463 if (waitqueue_active(&cancel_waitq))
3464 __wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
3470 * cancel_work_sync - cancel a work and wait for it to finish
3471 * @work: the work to cancel
3473 * Cancel @work and wait for its execution to finish. This function
3474 * can be used even if the work re-queues itself or migrates to
3475 * another workqueue. On return from this function, @work is
3476 * guaranteed to be not pending or executing on any CPU.
3478 * cancel_work_sync(&delayed_work->work) must not be used for
3479 * delayed_work's. Use cancel_delayed_work_sync() instead.
3481 * The caller must ensure that the workqueue on which @work was last
3482 * queued can't be destroyed before this function returns.
3485 * %true if @work was pending, %false otherwise.
3487 bool cancel_work_sync(struct work_struct *work)
3489 return __cancel_work_timer(work, false);
3491 EXPORT_SYMBOL_GPL(cancel_work_sync);
3494 * flush_delayed_work - wait for a dwork to finish executing the last queueing
3495 * @dwork: the delayed work to flush
3497 * Delayed timer is cancelled and the pending work is queued for
3498 * immediate execution. Like flush_work(), this function only
3499 * considers the last queueing instance of @dwork.
3502 * %true if flush_work() waited for the work to finish execution,
3503 * %false if it was already idle.
3505 bool flush_delayed_work(struct delayed_work *dwork)
3507 local_irq_disable();
3508 if (del_timer_sync(&dwork->timer))
3509 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
3511 return flush_work(&dwork->work);
3513 EXPORT_SYMBOL(flush_delayed_work);
3516 * flush_rcu_work - wait for a rwork to finish executing the last queueing
3517 * @rwork: the rcu work to flush
3520 * %true if flush_rcu_work() waited for the work to finish execution,
3521 * %false if it was already idle.
3523 bool flush_rcu_work(struct rcu_work *rwork)
3525 if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
3527 flush_work(&rwork->work);
3530 return flush_work(&rwork->work);
3533 EXPORT_SYMBOL(flush_rcu_work);
3535 static bool __cancel_work(struct work_struct *work, bool is_dwork)
3537 unsigned long flags;
3541 ret = try_to_grab_pending(work, is_dwork, &flags);
3542 } while (unlikely(ret == -EAGAIN));
3544 if (unlikely(ret < 0))
3547 set_work_pool_and_clear_pending(work, get_work_pool_id(work));
3548 local_irq_restore(flags);
3553 * See cancel_delayed_work()
3555 bool cancel_work(struct work_struct *work)
3557 return __cancel_work(work, false);
3559 EXPORT_SYMBOL(cancel_work);
3562 * cancel_delayed_work - cancel a delayed work
3563 * @dwork: delayed_work to cancel
3565 * Kill off a pending delayed_work.
3567 * Return: %true if @dwork was pending and canceled; %false if it wasn't
3571 * The work callback function may still be running on return, unless
3572 * it returns %true and the work doesn't re-arm itself. Explicitly flush or
3573 * use cancel_delayed_work_sync() to wait on it.
3575 * This function is safe to call from any context including IRQ handler.
3577 bool cancel_delayed_work(struct delayed_work *dwork)
3579 return __cancel_work(&dwork->work, true);
3581 EXPORT_SYMBOL(cancel_delayed_work);
3584 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3585 * @dwork: the delayed work cancel
3587 * This is cancel_work_sync() for delayed works.
3590 * %true if @dwork was pending, %false otherwise.
3592 bool cancel_delayed_work_sync(struct delayed_work *dwork)
3594 return __cancel_work_timer(&dwork->work, true);
3596 EXPORT_SYMBOL(cancel_delayed_work_sync);
3599 * schedule_on_each_cpu - execute a function synchronously on each online CPU
3600 * @func: the function to call
3602 * schedule_on_each_cpu() executes @func on each online CPU using the
3603 * system workqueue and blocks until all CPUs have completed.
3604 * schedule_on_each_cpu() is very slow.
3607 * 0 on success, -errno on failure.
3609 int schedule_on_each_cpu(work_func_t func)
3612 struct work_struct __percpu *works;
3614 works = alloc_percpu(struct work_struct);
3620 for_each_online_cpu(cpu) {
3621 struct work_struct *work = per_cpu_ptr(works, cpu);
3623 INIT_WORK(work, func);
3624 schedule_work_on(cpu, work);
3627 for_each_online_cpu(cpu)
3628 flush_work(per_cpu_ptr(works, cpu));
3636 * execute_in_process_context - reliably execute the routine with user context
3637 * @fn: the function to execute
3638 * @ew: guaranteed storage for the execute work structure (must
3639 * be available when the work executes)
3641 * Executes the function immediately if process context is available,
3642 * otherwise schedules the function for delayed execution.
3644 * Return: 0 - function was executed
3645 * 1 - function was scheduled for execution
3647 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
3649 if (!in_interrupt()) {
3654 INIT_WORK(&ew->work, fn);
3655 schedule_work(&ew->work);
3659 EXPORT_SYMBOL_GPL(execute_in_process_context);
3662 * free_workqueue_attrs - free a workqueue_attrs
3663 * @attrs: workqueue_attrs to free
3665 * Undo alloc_workqueue_attrs().
3667 void free_workqueue_attrs(struct workqueue_attrs *attrs)
3670 free_cpumask_var(attrs->cpumask);
3676 * alloc_workqueue_attrs - allocate a workqueue_attrs
3678 * Allocate a new workqueue_attrs, initialize with default settings and
3681 * Return: The allocated new workqueue_attr on success. %NULL on failure.
3683 struct workqueue_attrs *alloc_workqueue_attrs(void)
3685 struct workqueue_attrs *attrs;
3687 attrs = kzalloc(sizeof(*attrs), GFP_KERNEL);
3690 if (!alloc_cpumask_var(&attrs->cpumask, GFP_KERNEL))
3693 cpumask_copy(attrs->cpumask, cpu_possible_mask);
3696 free_workqueue_attrs(attrs);
3700 static void copy_workqueue_attrs(struct workqueue_attrs *to,
3701 const struct workqueue_attrs *from)
3703 to->nice = from->nice;
3704 cpumask_copy(to->cpumask, from->cpumask);
3706 * Unlike hash and equality test, this function doesn't ignore
3707 * ->no_numa as it is used for both pool and wq attrs. Instead,
3708 * get_unbound_pool() explicitly clears ->no_numa after copying.
3710 to->no_numa = from->no_numa;
3713 /* hash value of the content of @attr */
3714 static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
3718 hash = jhash_1word(attrs->nice, hash);
3719 hash = jhash(cpumask_bits(attrs->cpumask),
3720 BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
3724 /* content equality test */
3725 static bool wqattrs_equal(const struct workqueue_attrs *a,
3726 const struct workqueue_attrs *b)
3728 if (a->nice != b->nice)
3730 if (!cpumask_equal(a->cpumask, b->cpumask))
3736 * init_worker_pool - initialize a newly zalloc'd worker_pool
3737 * @pool: worker_pool to initialize
3739 * Initialize a newly zalloc'd @pool. It also allocates @pool->attrs.
3741 * Return: 0 on success, -errno on failure. Even on failure, all fields
3742 * inside @pool proper are initialized and put_unbound_pool() can be called
3743 * on @pool safely to release it.
3745 static int init_worker_pool(struct worker_pool *pool)
3747 raw_spin_lock_init(&pool->lock);
3750 pool->node = NUMA_NO_NODE;
3751 pool->flags |= POOL_DISASSOCIATED;
3752 pool->watchdog_ts = jiffies;
3753 INIT_LIST_HEAD(&pool->worklist);
3754 INIT_LIST_HEAD(&pool->idle_list);
3755 hash_init(pool->busy_hash);
3757 timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
3758 INIT_WORK(&pool->idle_cull_work, idle_cull_fn);
3760 timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
3762 INIT_LIST_HEAD(&pool->workers);
3763 INIT_LIST_HEAD(&pool->dying_workers);
3765 ida_init(&pool->worker_ida);
3766 INIT_HLIST_NODE(&pool->hash_node);
3769 /* shouldn't fail above this point */
3770 pool->attrs = alloc_workqueue_attrs();
3776 #ifdef CONFIG_LOCKDEP
3777 static void wq_init_lockdep(struct workqueue_struct *wq)
3781 lockdep_register_key(&wq->key);
3782 lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name);
3784 lock_name = wq->name;
3786 wq->lock_name = lock_name;
3787 lockdep_init_map(&wq->lockdep_map, lock_name, &wq->key, 0);
3790 static void wq_unregister_lockdep(struct workqueue_struct *wq)
3792 lockdep_unregister_key(&wq->key);
3795 static void wq_free_lockdep(struct workqueue_struct *wq)
3797 if (wq->lock_name != wq->name)
3798 kfree(wq->lock_name);
3801 static void wq_init_lockdep(struct workqueue_struct *wq)
3805 static void wq_unregister_lockdep(struct workqueue_struct *wq)
3809 static void wq_free_lockdep(struct workqueue_struct *wq)
3814 static void rcu_free_wq(struct rcu_head *rcu)
3816 struct workqueue_struct *wq =
3817 container_of(rcu, struct workqueue_struct, rcu);
3819 wq_free_lockdep(wq);
3821 if (!(wq->flags & WQ_UNBOUND))
3822 free_percpu(wq->cpu_pwq);
3824 free_workqueue_attrs(wq->unbound_attrs);
3829 static void rcu_free_pool(struct rcu_head *rcu)
3831 struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
3833 ida_destroy(&pool->worker_ida);
3834 free_workqueue_attrs(pool->attrs);
3839 * put_unbound_pool - put a worker_pool
3840 * @pool: worker_pool to put
3842 * Put @pool. If its refcnt reaches zero, it gets destroyed in RCU
3843 * safe manner. get_unbound_pool() calls this function on its failure path
3844 * and this function should be able to release pools which went through,
3845 * successfully or not, init_worker_pool().
3847 * Should be called with wq_pool_mutex held.
3849 static void put_unbound_pool(struct worker_pool *pool)
3851 DECLARE_COMPLETION_ONSTACK(detach_completion);
3852 struct worker *worker;
3853 LIST_HEAD(cull_list);
3855 lockdep_assert_held(&wq_pool_mutex);
3861 if (WARN_ON(!(pool->cpu < 0)) ||
3862 WARN_ON(!list_empty(&pool->worklist)))
3865 /* release id and unhash */
3867 idr_remove(&worker_pool_idr, pool->id);
3868 hash_del(&pool->hash_node);
3871 * Become the manager and destroy all workers. This prevents
3872 * @pool's workers from blocking on attach_mutex. We're the last
3873 * manager and @pool gets freed with the flag set.
3875 * Having a concurrent manager is quite unlikely to happen as we can
3876 * only get here with
3877 * pwq->refcnt == pool->refcnt == 0
3878 * which implies no work queued to the pool, which implies no worker can
3879 * become the manager. However a worker could have taken the role of
3880 * manager before the refcnts dropped to 0, since maybe_create_worker()
3884 rcuwait_wait_event(&manager_wait,
3885 !(pool->flags & POOL_MANAGER_ACTIVE),
3886 TASK_UNINTERRUPTIBLE);
3888 mutex_lock(&wq_pool_attach_mutex);
3889 raw_spin_lock_irq(&pool->lock);
3890 if (!(pool->flags & POOL_MANAGER_ACTIVE)) {
3891 pool->flags |= POOL_MANAGER_ACTIVE;
3894 raw_spin_unlock_irq(&pool->lock);
3895 mutex_unlock(&wq_pool_attach_mutex);
3898 while ((worker = first_idle_worker(pool)))
3899 set_worker_dying(worker, &cull_list);
3900 WARN_ON(pool->nr_workers || pool->nr_idle);
3901 raw_spin_unlock_irq(&pool->lock);
3903 wake_dying_workers(&cull_list);
3905 if (!list_empty(&pool->workers) || !list_empty(&pool->dying_workers))
3906 pool->detach_completion = &detach_completion;
3907 mutex_unlock(&wq_pool_attach_mutex);
3909 if (pool->detach_completion)
3910 wait_for_completion(pool->detach_completion);
3912 /* shut down the timers */
3913 del_timer_sync(&pool->idle_timer);
3914 cancel_work_sync(&pool->idle_cull_work);
3915 del_timer_sync(&pool->mayday_timer);
3917 /* RCU protected to allow dereferences from get_work_pool() */
3918 call_rcu(&pool->rcu, rcu_free_pool);
3922 * get_unbound_pool - get a worker_pool with the specified attributes
3923 * @attrs: the attributes of the worker_pool to get
3925 * Obtain a worker_pool which has the same attributes as @attrs, bump the
3926 * reference count and return it. If there already is a matching
3927 * worker_pool, it will be used; otherwise, this function attempts to
3930 * Should be called with wq_pool_mutex held.
3932 * Return: On success, a worker_pool with the same attributes as @attrs.
3933 * On failure, %NULL.
3935 static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
3937 u32 hash = wqattrs_hash(attrs);
3938 struct worker_pool *pool;
3940 int target_node = NUMA_NO_NODE;
3942 lockdep_assert_held(&wq_pool_mutex);
3944 /* do we already have a matching pool? */
3945 hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
3946 if (wqattrs_equal(pool->attrs, attrs)) {
3952 /* if cpumask is contained inside a NUMA node, we belong to that node */
3953 if (wq_numa_enabled) {
3954 for_each_node(node) {
3955 if (cpumask_subset(attrs->cpumask,
3956 wq_numa_possible_cpumask[node])) {
3963 /* nope, create a new one */
3964 pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, target_node);
3965 if (!pool || init_worker_pool(pool) < 0)
3968 lockdep_set_subclass(&pool->lock, 1); /* see put_pwq() */
3969 copy_workqueue_attrs(pool->attrs, attrs);
3970 pool->node = target_node;
3973 * no_numa isn't a worker_pool attribute, always clear it. See
3974 * 'struct workqueue_attrs' comments for detail.
3976 pool->attrs->no_numa = false;
3978 if (worker_pool_assign_id(pool) < 0)
3981 /* create and start the initial worker */
3982 if (wq_online && !create_worker(pool))
3986 hash_add(unbound_pool_hash, &pool->hash_node, hash);
3991 put_unbound_pool(pool);
3995 static void rcu_free_pwq(struct rcu_head *rcu)
3997 kmem_cache_free(pwq_cache,
3998 container_of(rcu, struct pool_workqueue, rcu));
4002 * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
4003 * and needs to be destroyed.
4005 static void pwq_unbound_release_workfn(struct work_struct *work)
4007 struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
4008 unbound_release_work);
4009 struct workqueue_struct *wq = pwq->wq;
4010 struct worker_pool *pool = pwq->pool;
4011 bool is_last = false;
4014 * when @pwq is not linked, it doesn't hold any reference to the
4015 * @wq, and @wq is invalid to access.
4017 if (!list_empty(&pwq->pwqs_node)) {
4018 if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
4021 mutex_lock(&wq->mutex);
4022 list_del_rcu(&pwq->pwqs_node);
4023 is_last = list_empty(&wq->pwqs);
4024 mutex_unlock(&wq->mutex);
4027 mutex_lock(&wq_pool_mutex);
4028 put_unbound_pool(pool);
4029 mutex_unlock(&wq_pool_mutex);
4031 call_rcu(&pwq->rcu, rcu_free_pwq);
4034 * If we're the last pwq going away, @wq is already dead and no one
4035 * is gonna access it anymore. Schedule RCU free.
4038 wq_unregister_lockdep(wq);
4039 call_rcu(&wq->rcu, rcu_free_wq);
4044 * pwq_adjust_max_active - update a pwq's max_active to the current setting
4045 * @pwq: target pool_workqueue
4047 * If @pwq isn't freezing, set @pwq->max_active to the associated
4048 * workqueue's saved_max_active and activate inactive work items
4049 * accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
4051 static void pwq_adjust_max_active(struct pool_workqueue *pwq)
4053 struct workqueue_struct *wq = pwq->wq;
4054 bool freezable = wq->flags & WQ_FREEZABLE;
4055 unsigned long flags;
4057 /* for @wq->saved_max_active */
4058 lockdep_assert_held(&wq->mutex);
4060 /* fast exit for non-freezable wqs */
4061 if (!freezable && pwq->max_active == wq->saved_max_active)
4064 /* this function can be called during early boot w/ irq disabled */
4065 raw_spin_lock_irqsave(&pwq->pool->lock, flags);
4068 * During [un]freezing, the caller is responsible for ensuring that
4069 * this function is called at least once after @workqueue_freezing
4070 * is updated and visible.
4072 if (!freezable || !workqueue_freezing) {
4075 pwq->max_active = wq->saved_max_active;
4077 while (!list_empty(&pwq->inactive_works) &&
4078 pwq->nr_active < pwq->max_active) {
4079 pwq_activate_first_inactive(pwq);
4084 * Need to kick a worker after thawed or an unbound wq's
4085 * max_active is bumped. In realtime scenarios, always kicking a
4086 * worker will cause interference on the isolated cpu cores, so
4087 * let's kick iff work items were activated.
4090 wake_up_worker(pwq->pool);
4092 pwq->max_active = 0;
4095 raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
4098 /* initialize newly allocated @pwq which is associated with @wq and @pool */
4099 static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
4100 struct worker_pool *pool)
4102 BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
4104 memset(pwq, 0, sizeof(*pwq));
4108 pwq->flush_color = -1;
4110 INIT_LIST_HEAD(&pwq->inactive_works);
4111 INIT_LIST_HEAD(&pwq->pwqs_node);
4112 INIT_LIST_HEAD(&pwq->mayday_node);
4113 INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
4116 /* sync @pwq with the current state of its associated wq and link it */
4117 static void link_pwq(struct pool_workqueue *pwq)
4119 struct workqueue_struct *wq = pwq->wq;
4121 lockdep_assert_held(&wq->mutex);
4123 /* may be called multiple times, ignore if already linked */
4124 if (!list_empty(&pwq->pwqs_node))
4127 /* set the matching work_color */
4128 pwq->work_color = wq->work_color;
4130 /* sync max_active to the current setting */
4131 pwq_adjust_max_active(pwq);
4134 list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
4137 /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
4138 static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
4139 const struct workqueue_attrs *attrs)
4141 struct worker_pool *pool;
4142 struct pool_workqueue *pwq;
4144 lockdep_assert_held(&wq_pool_mutex);
4146 pool = get_unbound_pool(attrs);
4150 pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
4152 put_unbound_pool(pool);
4156 init_pwq(pwq, wq, pool);
4161 * wq_calc_node_cpumask - calculate a wq_attrs' cpumask for the specified node
4162 * @attrs: the wq_attrs of the default pwq of the target workqueue
4163 * @node: the target NUMA node
4164 * @cpu_going_down: if >= 0, the CPU to consider as offline
4165 * @cpumask: outarg, the resulting cpumask
4167 * Calculate the cpumask a workqueue with @attrs should use on @node. If
4168 * @cpu_going_down is >= 0, that cpu is considered offline during
4169 * calculation. The result is stored in @cpumask.
4171 * If NUMA affinity is not enabled, @attrs->cpumask is always used. If
4172 * enabled and @node has online CPUs requested by @attrs, the returned
4173 * cpumask is the intersection of the possible CPUs of @node and
4176 * The caller is responsible for ensuring that the cpumask of @node stays
4179 * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
4182 static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
4183 int cpu_going_down, cpumask_t *cpumask)
4185 if (!wq_numa_enabled || attrs->no_numa)
4188 /* does @node have any online CPUs @attrs wants? */
4189 cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
4190 if (cpu_going_down >= 0)
4191 cpumask_clear_cpu(cpu_going_down, cpumask);
4193 if (cpumask_empty(cpumask))
4196 /* yeap, return possible CPUs in @node that @attrs wants */
4197 cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
4199 if (cpumask_empty(cpumask)) {
4200 pr_warn_once("WARNING: workqueue cpumask: online intersect > "
4201 "possible intersect\n");
4205 return !cpumask_equal(cpumask, attrs->cpumask);
4208 cpumask_copy(cpumask, attrs->cpumask);
4212 /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
4213 static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
4215 struct pool_workqueue *pwq)
4217 struct pool_workqueue *old_pwq;
4219 lockdep_assert_held(&wq_pool_mutex);
4220 lockdep_assert_held(&wq->mutex);
4222 /* link_pwq() can handle duplicate calls */
4225 old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
4226 rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
4230 /* context to store the prepared attrs & pwqs before applying */
4231 struct apply_wqattrs_ctx {
4232 struct workqueue_struct *wq; /* target workqueue */
4233 struct workqueue_attrs *attrs; /* attrs to apply */
4234 struct list_head list; /* queued for batching commit */
4235 struct pool_workqueue *dfl_pwq;
4236 struct pool_workqueue *pwq_tbl[];
4239 /* free the resources after success or abort */
4240 static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
4246 put_pwq_unlocked(ctx->pwq_tbl[node]);
4247 put_pwq_unlocked(ctx->dfl_pwq);
4249 free_workqueue_attrs(ctx->attrs);
4255 /* allocate the attrs and pwqs for later installation */
4256 static struct apply_wqattrs_ctx *
4257 apply_wqattrs_prepare(struct workqueue_struct *wq,
4258 const struct workqueue_attrs *attrs,
4259 const cpumask_var_t unbound_cpumask)
4261 struct apply_wqattrs_ctx *ctx;
4262 struct workqueue_attrs *new_attrs, *tmp_attrs;
4265 lockdep_assert_held(&wq_pool_mutex);
4267 ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_node_ids), GFP_KERNEL);
4269 new_attrs = alloc_workqueue_attrs();
4270 tmp_attrs = alloc_workqueue_attrs();
4271 if (!ctx || !new_attrs || !tmp_attrs)
4275 * Calculate the attrs of the default pwq with unbound_cpumask
4276 * which is wq_unbound_cpumask or to set to wq_unbound_cpumask.
4277 * If the user configured cpumask doesn't overlap with the
4278 * wq_unbound_cpumask, we fallback to the wq_unbound_cpumask.
4280 copy_workqueue_attrs(new_attrs, attrs);
4281 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, unbound_cpumask);
4282 if (unlikely(cpumask_empty(new_attrs->cpumask)))
4283 cpumask_copy(new_attrs->cpumask, unbound_cpumask);
4286 * We may create multiple pwqs with differing cpumasks. Make a
4287 * copy of @new_attrs which will be modified and used to obtain
4290 copy_workqueue_attrs(tmp_attrs, new_attrs);
4293 * If something goes wrong during CPU up/down, we'll fall back to
4294 * the default pwq covering whole @attrs->cpumask. Always create
4295 * it even if we don't use it immediately.
4297 ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
4301 for_each_node(node) {
4302 if (wq_calc_node_cpumask(new_attrs, node, -1, tmp_attrs->cpumask)) {
4303 ctx->pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
4304 if (!ctx->pwq_tbl[node])
4307 ctx->dfl_pwq->refcnt++;
4308 ctx->pwq_tbl[node] = ctx->dfl_pwq;
4312 /* save the user configured attrs and sanitize it. */
4313 copy_workqueue_attrs(new_attrs, attrs);
4314 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
4315 ctx->attrs = new_attrs;
4318 free_workqueue_attrs(tmp_attrs);
4322 free_workqueue_attrs(tmp_attrs);
4323 free_workqueue_attrs(new_attrs);
4324 apply_wqattrs_cleanup(ctx);
4328 /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
4329 static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
4333 /* all pwqs have been created successfully, let's install'em */
4334 mutex_lock(&ctx->wq->mutex);
4336 copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
4338 /* save the previous pwq and install the new one */
4340 ctx->pwq_tbl[node] = numa_pwq_tbl_install(ctx->wq, node,
4341 ctx->pwq_tbl[node]);
4343 /* @dfl_pwq might not have been used, ensure it's linked */
4344 link_pwq(ctx->dfl_pwq);
4345 swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
4347 mutex_unlock(&ctx->wq->mutex);
4350 static void apply_wqattrs_lock(void)
4352 /* CPUs should stay stable across pwq creations and installations */
4354 mutex_lock(&wq_pool_mutex);
4357 static void apply_wqattrs_unlock(void)
4359 mutex_unlock(&wq_pool_mutex);
4363 static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
4364 const struct workqueue_attrs *attrs)
4366 struct apply_wqattrs_ctx *ctx;
4368 /* only unbound workqueues can change attributes */
4369 if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
4372 /* creating multiple pwqs breaks ordering guarantee */
4373 if (!list_empty(&wq->pwqs)) {
4374 if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
4377 wq->flags &= ~__WQ_ORDERED;
4380 ctx = apply_wqattrs_prepare(wq, attrs, wq_unbound_cpumask);
4384 /* the ctx has been prepared successfully, let's commit it */
4385 apply_wqattrs_commit(ctx);
4386 apply_wqattrs_cleanup(ctx);
4392 * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
4393 * @wq: the target workqueue
4394 * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
4396 * Apply @attrs to an unbound workqueue @wq. Unless disabled, on NUMA
4397 * machines, this function maps a separate pwq to each NUMA node with
4398 * possibles CPUs in @attrs->cpumask so that work items are affine to the
4399 * NUMA node it was issued on. Older pwqs are released as in-flight work
4400 * items finish. Note that a work item which repeatedly requeues itself
4401 * back-to-back will stay on its current pwq.
4403 * Performs GFP_KERNEL allocations.
4405 * Assumes caller has CPU hotplug read exclusion, i.e. cpus_read_lock().
4407 * Return: 0 on success and -errno on failure.
4409 int apply_workqueue_attrs(struct workqueue_struct *wq,
4410 const struct workqueue_attrs *attrs)
4414 lockdep_assert_cpus_held();
4416 mutex_lock(&wq_pool_mutex);
4417 ret = apply_workqueue_attrs_locked(wq, attrs);
4418 mutex_unlock(&wq_pool_mutex);
4424 * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
4425 * @wq: the target workqueue
4426 * @cpu: the CPU coming up or going down
4427 * @online: whether @cpu is coming up or going down
4429 * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
4430 * %CPU_DOWN_FAILED. @cpu is being hot[un]plugged, update NUMA affinity of
4433 * If NUMA affinity can't be adjusted due to memory allocation failure, it
4434 * falls back to @wq->dfl_pwq which may not be optimal but is always
4437 * Note that when the last allowed CPU of a NUMA node goes offline for a
4438 * workqueue with a cpumask spanning multiple nodes, the workers which were
4439 * already executing the work items for the workqueue will lose their CPU
4440 * affinity and may execute on any CPU. This is similar to how per-cpu
4441 * workqueues behave on CPU_DOWN. If a workqueue user wants strict
4442 * affinity, it's the user's responsibility to flush the work item from
4445 static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
4448 int node = cpu_to_node(cpu);
4449 int cpu_off = online ? -1 : cpu;
4450 struct pool_workqueue *old_pwq = NULL, *pwq;
4451 struct workqueue_attrs *target_attrs;
4454 lockdep_assert_held(&wq_pool_mutex);
4456 if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND) ||
4457 wq->unbound_attrs->no_numa)
4461 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
4462 * Let's use a preallocated one. The following buf is protected by
4463 * CPU hotplug exclusion.
4465 target_attrs = wq_update_unbound_numa_attrs_buf;
4466 cpumask = target_attrs->cpumask;
4468 copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
4469 pwq = unbound_pwq_by_node(wq, node);
4472 * Let's determine what needs to be done. If the target cpumask is
4473 * different from the default pwq's, we need to compare it to @pwq's
4474 * and create a new one if they don't match. If the target cpumask
4475 * equals the default pwq's, the default pwq should be used.
4477 if (wq_calc_node_cpumask(wq->dfl_pwq->pool->attrs, node, cpu_off, cpumask)) {
4478 if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
4484 /* create a new pwq */
4485 pwq = alloc_unbound_pwq(wq, target_attrs);
4487 pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
4492 /* Install the new pwq. */
4493 mutex_lock(&wq->mutex);
4494 old_pwq = numa_pwq_tbl_install(wq, node, pwq);
4498 mutex_lock(&wq->mutex);
4499 raw_spin_lock_irq(&wq->dfl_pwq->pool->lock);
4500 get_pwq(wq->dfl_pwq);
4501 raw_spin_unlock_irq(&wq->dfl_pwq->pool->lock);
4502 old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
4504 mutex_unlock(&wq->mutex);
4505 put_pwq_unlocked(old_pwq);
4508 static int alloc_and_link_pwqs(struct workqueue_struct *wq)
4510 bool highpri = wq->flags & WQ_HIGHPRI;
4513 if (!(wq->flags & WQ_UNBOUND)) {
4514 wq->cpu_pwq = alloc_percpu(struct pool_workqueue);
4518 for_each_possible_cpu(cpu) {
4519 struct pool_workqueue *pwq =
4520 per_cpu_ptr(wq->cpu_pwq, cpu);
4521 struct worker_pool *cpu_pools =
4522 per_cpu(cpu_worker_pools, cpu);
4524 init_pwq(pwq, wq, &cpu_pools[highpri]);
4526 mutex_lock(&wq->mutex);
4528 mutex_unlock(&wq->mutex);
4534 if (wq->flags & __WQ_ORDERED) {
4535 ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
4536 /* there should only be single pwq for ordering guarantee */
4537 WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
4538 wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
4539 "ordering guarantee broken for workqueue %s\n", wq->name);
4541 ret = apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
4548 static int wq_clamp_max_active(int max_active, unsigned int flags,
4551 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
4553 if (max_active < 1 || max_active > lim)
4554 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
4555 max_active, name, 1, lim);
4557 return clamp_val(max_active, 1, lim);
4561 * Workqueues which may be used during memory reclaim should have a rescuer
4562 * to guarantee forward progress.
4564 static int init_rescuer(struct workqueue_struct *wq)
4566 struct worker *rescuer;
4569 if (!(wq->flags & WQ_MEM_RECLAIM))
4572 rescuer = alloc_worker(NUMA_NO_NODE);
4574 pr_err("workqueue: Failed to allocate a rescuer for wq \"%s\"\n",
4579 rescuer->rescue_wq = wq;
4580 rescuer->task = kthread_create(rescuer_thread, rescuer, "%s", wq->name);
4581 if (IS_ERR(rescuer->task)) {
4582 ret = PTR_ERR(rescuer->task);
4583 pr_err("workqueue: Failed to create a rescuer kthread for wq \"%s\": %pe",
4584 wq->name, ERR_PTR(ret));
4589 wq->rescuer = rescuer;
4590 kthread_bind_mask(rescuer->task, cpu_possible_mask);
4591 wake_up_process(rescuer->task);
4597 struct workqueue_struct *alloc_workqueue(const char *fmt,
4599 int max_active, ...)
4601 size_t tbl_size = 0;
4603 struct workqueue_struct *wq;
4604 struct pool_workqueue *pwq;
4607 * Unbound && max_active == 1 used to imply ordered, which is no
4608 * longer the case on NUMA machines due to per-node pools. While
4609 * alloc_ordered_workqueue() is the right way to create an ordered
4610 * workqueue, keep the previous behavior to avoid subtle breakages
4613 if ((flags & WQ_UNBOUND) && max_active == 1)
4614 flags |= __WQ_ORDERED;
4616 /* see the comment above the definition of WQ_POWER_EFFICIENT */
4617 if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
4618 flags |= WQ_UNBOUND;
4620 /* allocate wq and format name */
4621 if (flags & WQ_UNBOUND)
4622 tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
4624 wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
4628 if (flags & WQ_UNBOUND) {
4629 wq->unbound_attrs = alloc_workqueue_attrs();
4630 if (!wq->unbound_attrs)
4634 va_start(args, max_active);
4635 vsnprintf(wq->name, sizeof(wq->name), fmt, args);
4638 max_active = max_active ?: WQ_DFL_ACTIVE;
4639 max_active = wq_clamp_max_active(max_active, flags, wq->name);
4643 wq->saved_max_active = max_active;
4644 mutex_init(&wq->mutex);
4645 atomic_set(&wq->nr_pwqs_to_flush, 0);
4646 INIT_LIST_HEAD(&wq->pwqs);
4647 INIT_LIST_HEAD(&wq->flusher_queue);
4648 INIT_LIST_HEAD(&wq->flusher_overflow);
4649 INIT_LIST_HEAD(&wq->maydays);
4651 wq_init_lockdep(wq);
4652 INIT_LIST_HEAD(&wq->list);
4654 if (alloc_and_link_pwqs(wq) < 0)
4655 goto err_unreg_lockdep;
4657 if (wq_online && init_rescuer(wq) < 0)
4660 if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
4664 * wq_pool_mutex protects global freeze state and workqueues list.
4665 * Grab it, adjust max_active and add the new @wq to workqueues
4668 mutex_lock(&wq_pool_mutex);
4670 mutex_lock(&wq->mutex);
4671 for_each_pwq(pwq, wq)
4672 pwq_adjust_max_active(pwq);
4673 mutex_unlock(&wq->mutex);
4675 list_add_tail_rcu(&wq->list, &workqueues);
4677 mutex_unlock(&wq_pool_mutex);
4682 wq_unregister_lockdep(wq);
4683 wq_free_lockdep(wq);
4685 free_workqueue_attrs(wq->unbound_attrs);
4689 destroy_workqueue(wq);
4692 EXPORT_SYMBOL_GPL(alloc_workqueue);
4694 static bool pwq_busy(struct pool_workqueue *pwq)
4698 for (i = 0; i < WORK_NR_COLORS; i++)
4699 if (pwq->nr_in_flight[i])
4702 if ((pwq != pwq->wq->dfl_pwq) && (pwq->refcnt > 1))
4704 if (pwq->nr_active || !list_empty(&pwq->inactive_works))
4711 * destroy_workqueue - safely terminate a workqueue
4712 * @wq: target workqueue
4714 * Safely destroy a workqueue. All work currently pending will be done first.
4716 void destroy_workqueue(struct workqueue_struct *wq)
4718 struct pool_workqueue *pwq;
4722 * Remove it from sysfs first so that sanity check failure doesn't
4723 * lead to sysfs name conflicts.
4725 workqueue_sysfs_unregister(wq);
4727 /* mark the workqueue destruction is in progress */
4728 mutex_lock(&wq->mutex);
4729 wq->flags |= __WQ_DESTROYING;
4730 mutex_unlock(&wq->mutex);
4732 /* drain it before proceeding with destruction */
4733 drain_workqueue(wq);
4735 /* kill rescuer, if sanity checks fail, leave it w/o rescuer */
4737 struct worker *rescuer = wq->rescuer;
4739 /* this prevents new queueing */
4740 raw_spin_lock_irq(&wq_mayday_lock);
4742 raw_spin_unlock_irq(&wq_mayday_lock);
4744 /* rescuer will empty maydays list before exiting */
4745 kthread_stop(rescuer->task);
4750 * Sanity checks - grab all the locks so that we wait for all
4751 * in-flight operations which may do put_pwq().
4753 mutex_lock(&wq_pool_mutex);
4754 mutex_lock(&wq->mutex);
4755 for_each_pwq(pwq, wq) {
4756 raw_spin_lock_irq(&pwq->pool->lock);
4757 if (WARN_ON(pwq_busy(pwq))) {
4758 pr_warn("%s: %s has the following busy pwq\n",
4759 __func__, wq->name);
4761 raw_spin_unlock_irq(&pwq->pool->lock);
4762 mutex_unlock(&wq->mutex);
4763 mutex_unlock(&wq_pool_mutex);
4764 show_one_workqueue(wq);
4767 raw_spin_unlock_irq(&pwq->pool->lock);
4769 mutex_unlock(&wq->mutex);
4772 * wq list is used to freeze wq, remove from list after
4773 * flushing is complete in case freeze races us.
4775 list_del_rcu(&wq->list);
4776 mutex_unlock(&wq_pool_mutex);
4778 if (!(wq->flags & WQ_UNBOUND)) {
4779 wq_unregister_lockdep(wq);
4781 * The base ref is never dropped on per-cpu pwqs. Directly
4782 * schedule RCU free.
4784 call_rcu(&wq->rcu, rcu_free_wq);
4787 * We're the sole accessor of @wq at this point. Directly
4788 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
4789 * @wq will be freed when the last pwq is released.
4791 for_each_node(node) {
4792 pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
4793 RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
4794 put_pwq_unlocked(pwq);
4798 * Put dfl_pwq. @wq may be freed any time after dfl_pwq is
4799 * put. Don't access it afterwards.
4803 put_pwq_unlocked(pwq);
4806 EXPORT_SYMBOL_GPL(destroy_workqueue);
4809 * workqueue_set_max_active - adjust max_active of a workqueue
4810 * @wq: target workqueue
4811 * @max_active: new max_active value.
4813 * Set max_active of @wq to @max_active.
4816 * Don't call from IRQ context.
4818 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4820 struct pool_workqueue *pwq;
4822 /* disallow meddling with max_active for ordered workqueues */
4823 if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
4826 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4828 mutex_lock(&wq->mutex);
4830 wq->flags &= ~__WQ_ORDERED;
4831 wq->saved_max_active = max_active;
4833 for_each_pwq(pwq, wq)
4834 pwq_adjust_max_active(pwq);
4836 mutex_unlock(&wq->mutex);
4838 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4841 * current_work - retrieve %current task's work struct
4843 * Determine if %current task is a workqueue worker and what it's working on.
4844 * Useful to find out the context that the %current task is running in.
4846 * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
4848 struct work_struct *current_work(void)
4850 struct worker *worker = current_wq_worker();
4852 return worker ? worker->current_work : NULL;
4854 EXPORT_SYMBOL(current_work);
4857 * current_is_workqueue_rescuer - is %current workqueue rescuer?
4859 * Determine whether %current is a workqueue rescuer. Can be used from
4860 * work functions to determine whether it's being run off the rescuer task.
4862 * Return: %true if %current is a workqueue rescuer. %false otherwise.
4864 bool current_is_workqueue_rescuer(void)
4866 struct worker *worker = current_wq_worker();
4868 return worker && worker->rescue_wq;
4872 * workqueue_congested - test whether a workqueue is congested
4873 * @cpu: CPU in question
4874 * @wq: target workqueue
4876 * Test whether @wq's cpu workqueue for @cpu is congested. There is
4877 * no synchronization around this function and the test result is
4878 * unreliable and only useful as advisory hints or for debugging.
4880 * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4881 * Note that both per-cpu and unbound workqueues may be associated with
4882 * multiple pool_workqueues which have separate congested states. A
4883 * workqueue being congested on one CPU doesn't mean the workqueue is also
4884 * contested on other CPUs / NUMA nodes.
4887 * %true if congested, %false otherwise.
4889 bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4891 struct pool_workqueue *pwq;
4897 if (cpu == WORK_CPU_UNBOUND)
4898 cpu = smp_processor_id();
4900 if (!(wq->flags & WQ_UNBOUND))
4901 pwq = per_cpu_ptr(wq->cpu_pwq, cpu);
4903 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4905 ret = !list_empty(&pwq->inactive_works);
4911 EXPORT_SYMBOL_GPL(workqueue_congested);
4914 * work_busy - test whether a work is currently pending or running
4915 * @work: the work to be tested
4917 * Test whether @work is currently pending or running. There is no
4918 * synchronization around this function and the test result is
4919 * unreliable and only useful as advisory hints or for debugging.
4922 * OR'd bitmask of WORK_BUSY_* bits.
4924 unsigned int work_busy(struct work_struct *work)
4926 struct worker_pool *pool;
4927 unsigned long flags;
4928 unsigned int ret = 0;
4930 if (work_pending(work))
4931 ret |= WORK_BUSY_PENDING;
4934 pool = get_work_pool(work);
4936 raw_spin_lock_irqsave(&pool->lock, flags);
4937 if (find_worker_executing_work(pool, work))
4938 ret |= WORK_BUSY_RUNNING;
4939 raw_spin_unlock_irqrestore(&pool->lock, flags);
4945 EXPORT_SYMBOL_GPL(work_busy);
4948 * set_worker_desc - set description for the current work item
4949 * @fmt: printf-style format string
4950 * @...: arguments for the format string
4952 * This function can be called by a running work function to describe what
4953 * the work item is about. If the worker task gets dumped, this
4954 * information will be printed out together to help debugging. The
4955 * description can be at most WORKER_DESC_LEN including the trailing '\0'.
4957 void set_worker_desc(const char *fmt, ...)
4959 struct worker *worker = current_wq_worker();
4963 va_start(args, fmt);
4964 vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
4968 EXPORT_SYMBOL_GPL(set_worker_desc);
4971 * print_worker_info - print out worker information and description
4972 * @log_lvl: the log level to use when printing
4973 * @task: target task
4975 * If @task is a worker and currently executing a work item, print out the
4976 * name of the workqueue being serviced and worker description set with
4977 * set_worker_desc() by the currently executing work item.
4979 * This function can be safely called on any task as long as the
4980 * task_struct itself is accessible. While safe, this function isn't
4981 * synchronized and may print out mixups or garbages of limited length.
4983 void print_worker_info(const char *log_lvl, struct task_struct *task)
4985 work_func_t *fn = NULL;
4986 char name[WQ_NAME_LEN] = { };
4987 char desc[WORKER_DESC_LEN] = { };
4988 struct pool_workqueue *pwq = NULL;
4989 struct workqueue_struct *wq = NULL;
4990 struct worker *worker;
4992 if (!(task->flags & PF_WQ_WORKER))
4996 * This function is called without any synchronization and @task
4997 * could be in any state. Be careful with dereferences.
4999 worker = kthread_probe_data(task);
5002 * Carefully copy the associated workqueue's workfn, name and desc.
5003 * Keep the original last '\0' in case the original is garbage.
5005 copy_from_kernel_nofault(&fn, &worker->current_func, sizeof(fn));
5006 copy_from_kernel_nofault(&pwq, &worker->current_pwq, sizeof(pwq));
5007 copy_from_kernel_nofault(&wq, &pwq->wq, sizeof(wq));
5008 copy_from_kernel_nofault(name, wq->name, sizeof(name) - 1);
5009 copy_from_kernel_nofault(desc, worker->desc, sizeof(desc) - 1);
5011 if (fn || name[0] || desc[0]) {
5012 printk("%sWorkqueue: %s %ps", log_lvl, name, fn);
5013 if (strcmp(name, desc))
5014 pr_cont(" (%s)", desc);
5019 static void pr_cont_pool_info(struct worker_pool *pool)
5021 pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
5022 if (pool->node != NUMA_NO_NODE)
5023 pr_cont(" node=%d", pool->node);
5024 pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
5027 struct pr_cont_work_struct {
5033 static void pr_cont_work_flush(bool comma, work_func_t func, struct pr_cont_work_struct *pcwsp)
5037 if (func == pcwsp->func) {
5041 if (pcwsp->ctr == 1)
5042 pr_cont("%s %ps", pcwsp->comma ? "," : "", pcwsp->func);
5044 pr_cont("%s %ld*%ps", pcwsp->comma ? "," : "", pcwsp->ctr, pcwsp->func);
5047 if ((long)func == -1L)
5049 pcwsp->comma = comma;
5054 static void pr_cont_work(bool comma, struct work_struct *work, struct pr_cont_work_struct *pcwsp)
5056 if (work->func == wq_barrier_func) {
5057 struct wq_barrier *barr;
5059 barr = container_of(work, struct wq_barrier, work);
5061 pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
5062 pr_cont("%s BAR(%d)", comma ? "," : "",
5063 task_pid_nr(barr->task));
5066 pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
5067 pr_cont_work_flush(comma, work->func, pcwsp);
5071 static void show_pwq(struct pool_workqueue *pwq)
5073 struct pr_cont_work_struct pcws = { .ctr = 0, };
5074 struct worker_pool *pool = pwq->pool;
5075 struct work_struct *work;
5076 struct worker *worker;
5077 bool has_in_flight = false, has_pending = false;
5080 pr_info(" pwq %d:", pool->id);
5081 pr_cont_pool_info(pool);
5083 pr_cont(" active=%d/%d refcnt=%d%s\n",
5084 pwq->nr_active, pwq->max_active, pwq->refcnt,
5085 !list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
5087 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
5088 if (worker->current_pwq == pwq) {
5089 has_in_flight = true;
5093 if (has_in_flight) {
5096 pr_info(" in-flight:");
5097 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
5098 if (worker->current_pwq != pwq)
5101 pr_cont("%s %d%s:%ps", comma ? "," : "",
5102 task_pid_nr(worker->task),
5103 worker->rescue_wq ? "(RESCUER)" : "",
5104 worker->current_func);
5105 list_for_each_entry(work, &worker->scheduled, entry)
5106 pr_cont_work(false, work, &pcws);
5107 pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
5113 list_for_each_entry(work, &pool->worklist, entry) {
5114 if (get_work_pwq(work) == pwq) {
5122 pr_info(" pending:");
5123 list_for_each_entry(work, &pool->worklist, entry) {
5124 if (get_work_pwq(work) != pwq)
5127 pr_cont_work(comma, work, &pcws);
5128 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
5130 pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
5134 if (!list_empty(&pwq->inactive_works)) {
5137 pr_info(" inactive:");
5138 list_for_each_entry(work, &pwq->inactive_works, entry) {
5139 pr_cont_work(comma, work, &pcws);
5140 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
5142 pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
5148 * show_one_workqueue - dump state of specified workqueue
5149 * @wq: workqueue whose state will be printed
5151 void show_one_workqueue(struct workqueue_struct *wq)
5153 struct pool_workqueue *pwq;
5155 unsigned long flags;
5157 for_each_pwq(pwq, wq) {
5158 if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
5163 if (idle) /* Nothing to print for idle workqueue */
5166 pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
5168 for_each_pwq(pwq, wq) {
5169 raw_spin_lock_irqsave(&pwq->pool->lock, flags);
5170 if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
5172 * Defer printing to avoid deadlocks in console
5173 * drivers that queue work while holding locks
5174 * also taken in their write paths.
5176 printk_deferred_enter();
5178 printk_deferred_exit();
5180 raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
5182 * We could be printing a lot from atomic context, e.g.
5183 * sysrq-t -> show_all_workqueues(). Avoid triggering
5186 touch_nmi_watchdog();
5192 * show_one_worker_pool - dump state of specified worker pool
5193 * @pool: worker pool whose state will be printed
5195 static void show_one_worker_pool(struct worker_pool *pool)
5197 struct worker *worker;
5199 unsigned long flags;
5200 unsigned long hung = 0;
5202 raw_spin_lock_irqsave(&pool->lock, flags);
5203 if (pool->nr_workers == pool->nr_idle)
5206 /* How long the first pending work is waiting for a worker. */
5207 if (!list_empty(&pool->worklist))
5208 hung = jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000;
5211 * Defer printing to avoid deadlocks in console drivers that
5212 * queue work while holding locks also taken in their write
5215 printk_deferred_enter();
5216 pr_info("pool %d:", pool->id);
5217 pr_cont_pool_info(pool);
5218 pr_cont(" hung=%lus workers=%d", hung, pool->nr_workers);
5220 pr_cont(" manager: %d",
5221 task_pid_nr(pool->manager->task));
5222 list_for_each_entry(worker, &pool->idle_list, entry) {
5223 pr_cont(" %s%d", first ? "idle: " : "",
5224 task_pid_nr(worker->task));
5228 printk_deferred_exit();
5230 raw_spin_unlock_irqrestore(&pool->lock, flags);
5232 * We could be printing a lot from atomic context, e.g.
5233 * sysrq-t -> show_all_workqueues(). Avoid triggering
5236 touch_nmi_watchdog();
5241 * show_all_workqueues - dump workqueue state
5243 * Called from a sysrq handler and prints out all busy workqueues and pools.
5245 void show_all_workqueues(void)
5247 struct workqueue_struct *wq;
5248 struct worker_pool *pool;
5253 pr_info("Showing busy workqueues and worker pools:\n");
5255 list_for_each_entry_rcu(wq, &workqueues, list)
5256 show_one_workqueue(wq);
5258 for_each_pool(pool, pi)
5259 show_one_worker_pool(pool);
5265 * show_freezable_workqueues - dump freezable workqueue state
5267 * Called from try_to_freeze_tasks() and prints out all freezable workqueues
5270 void show_freezable_workqueues(void)
5272 struct workqueue_struct *wq;
5276 pr_info("Showing freezable workqueues that are still busy:\n");
5278 list_for_each_entry_rcu(wq, &workqueues, list) {
5279 if (!(wq->flags & WQ_FREEZABLE))
5281 show_one_workqueue(wq);
5287 /* used to show worker information through /proc/PID/{comm,stat,status} */
5288 void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
5292 /* always show the actual comm */
5293 off = strscpy(buf, task->comm, size);
5297 /* stabilize PF_WQ_WORKER and worker pool association */
5298 mutex_lock(&wq_pool_attach_mutex);
5300 if (task->flags & PF_WQ_WORKER) {
5301 struct worker *worker = kthread_data(task);
5302 struct worker_pool *pool = worker->pool;
5305 raw_spin_lock_irq(&pool->lock);
5307 * ->desc tracks information (wq name or
5308 * set_worker_desc()) for the latest execution. If
5309 * current, prepend '+', otherwise '-'.
5311 if (worker->desc[0] != '\0') {
5312 if (worker->current_work)
5313 scnprintf(buf + off, size - off, "+%s",
5316 scnprintf(buf + off, size - off, "-%s",
5319 raw_spin_unlock_irq(&pool->lock);
5323 mutex_unlock(&wq_pool_attach_mutex);
5331 * There are two challenges in supporting CPU hotplug. Firstly, there
5332 * are a lot of assumptions on strong associations among work, pwq and
5333 * pool which make migrating pending and scheduled works very
5334 * difficult to implement without impacting hot paths. Secondly,
5335 * worker pools serve mix of short, long and very long running works making
5336 * blocked draining impractical.
5338 * This is solved by allowing the pools to be disassociated from the CPU
5339 * running as an unbound one and allowing it to be reattached later if the
5340 * cpu comes back online.
5343 static void unbind_workers(int cpu)
5345 struct worker_pool *pool;
5346 struct worker *worker;
5348 for_each_cpu_worker_pool(pool, cpu) {
5349 mutex_lock(&wq_pool_attach_mutex);
5350 raw_spin_lock_irq(&pool->lock);
5353 * We've blocked all attach/detach operations. Make all workers
5354 * unbound and set DISASSOCIATED. Before this, all workers
5355 * must be on the cpu. After this, they may become diasporas.
5356 * And the preemption disabled section in their sched callbacks
5357 * are guaranteed to see WORKER_UNBOUND since the code here
5358 * is on the same cpu.
5360 for_each_pool_worker(worker, pool)
5361 worker->flags |= WORKER_UNBOUND;
5363 pool->flags |= POOL_DISASSOCIATED;
5366 * The handling of nr_running in sched callbacks are disabled
5367 * now. Zap nr_running. After this, nr_running stays zero and
5368 * need_more_worker() and keep_working() are always true as
5369 * long as the worklist is not empty. This pool now behaves as
5370 * an unbound (in terms of concurrency management) pool which
5371 * are served by workers tied to the pool.
5373 pool->nr_running = 0;
5376 * With concurrency management just turned off, a busy
5377 * worker blocking could lead to lengthy stalls. Kick off
5378 * unbound chain execution of currently pending work items.
5380 wake_up_worker(pool);
5382 raw_spin_unlock_irq(&pool->lock);
5384 for_each_pool_worker(worker, pool)
5385 unbind_worker(worker);
5387 mutex_unlock(&wq_pool_attach_mutex);
5392 * rebind_workers - rebind all workers of a pool to the associated CPU
5393 * @pool: pool of interest
5395 * @pool->cpu is coming online. Rebind all workers to the CPU.
5397 static void rebind_workers(struct worker_pool *pool)
5399 struct worker *worker;
5401 lockdep_assert_held(&wq_pool_attach_mutex);
5404 * Restore CPU affinity of all workers. As all idle workers should
5405 * be on the run-queue of the associated CPU before any local
5406 * wake-ups for concurrency management happen, restore CPU affinity
5407 * of all workers first and then clear UNBOUND. As we're called
5408 * from CPU_ONLINE, the following shouldn't fail.
5410 for_each_pool_worker(worker, pool) {
5411 kthread_set_per_cpu(worker->task, pool->cpu);
5412 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
5413 pool->attrs->cpumask) < 0);
5416 raw_spin_lock_irq(&pool->lock);
5418 pool->flags &= ~POOL_DISASSOCIATED;
5420 for_each_pool_worker(worker, pool) {
5421 unsigned int worker_flags = worker->flags;
5424 * We want to clear UNBOUND but can't directly call
5425 * worker_clr_flags() or adjust nr_running. Atomically
5426 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
5427 * @worker will clear REBOUND using worker_clr_flags() when
5428 * it initiates the next execution cycle thus restoring
5429 * concurrency management. Note that when or whether
5430 * @worker clears REBOUND doesn't affect correctness.
5432 * WRITE_ONCE() is necessary because @worker->flags may be
5433 * tested without holding any lock in
5434 * wq_worker_running(). Without it, NOT_RUNNING test may
5435 * fail incorrectly leading to premature concurrency
5436 * management operations.
5438 WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
5439 worker_flags |= WORKER_REBOUND;
5440 worker_flags &= ~WORKER_UNBOUND;
5441 WRITE_ONCE(worker->flags, worker_flags);
5444 raw_spin_unlock_irq(&pool->lock);
5448 * restore_unbound_workers_cpumask - restore cpumask of unbound workers
5449 * @pool: unbound pool of interest
5450 * @cpu: the CPU which is coming up
5452 * An unbound pool may end up with a cpumask which doesn't have any online
5453 * CPUs. When a worker of such pool get scheduled, the scheduler resets
5454 * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
5455 * online CPU before, cpus_allowed of all its workers should be restored.
5457 static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
5459 static cpumask_t cpumask;
5460 struct worker *worker;
5462 lockdep_assert_held(&wq_pool_attach_mutex);
5464 /* is @cpu allowed for @pool? */
5465 if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
5468 cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
5470 /* as we're called from CPU_ONLINE, the following shouldn't fail */
5471 for_each_pool_worker(worker, pool)
5472 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
5475 int workqueue_prepare_cpu(unsigned int cpu)
5477 struct worker_pool *pool;
5479 for_each_cpu_worker_pool(pool, cpu) {
5480 if (pool->nr_workers)
5482 if (!create_worker(pool))
5488 int workqueue_online_cpu(unsigned int cpu)
5490 struct worker_pool *pool;
5491 struct workqueue_struct *wq;
5494 mutex_lock(&wq_pool_mutex);
5496 for_each_pool(pool, pi) {
5497 mutex_lock(&wq_pool_attach_mutex);
5499 if (pool->cpu == cpu)
5500 rebind_workers(pool);
5501 else if (pool->cpu < 0)
5502 restore_unbound_workers_cpumask(pool, cpu);
5504 mutex_unlock(&wq_pool_attach_mutex);
5507 /* update NUMA affinity of unbound workqueues */
5508 list_for_each_entry(wq, &workqueues, list)
5509 wq_update_unbound_numa(wq, cpu, true);
5511 mutex_unlock(&wq_pool_mutex);
5515 int workqueue_offline_cpu(unsigned int cpu)
5517 struct workqueue_struct *wq;
5519 /* unbinding per-cpu workers should happen on the local CPU */
5520 if (WARN_ON(cpu != smp_processor_id()))
5523 unbind_workers(cpu);
5525 /* update NUMA affinity of unbound workqueues */
5526 mutex_lock(&wq_pool_mutex);
5527 list_for_each_entry(wq, &workqueues, list)
5528 wq_update_unbound_numa(wq, cpu, false);
5529 mutex_unlock(&wq_pool_mutex);
5534 struct work_for_cpu {
5535 struct work_struct work;
5541 static void work_for_cpu_fn(struct work_struct *work)
5543 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
5545 wfc->ret = wfc->fn(wfc->arg);
5549 * work_on_cpu - run a function in thread context on a particular cpu
5550 * @cpu: the cpu to run on
5551 * @fn: the function to run
5552 * @arg: the function arg
5554 * It is up to the caller to ensure that the cpu doesn't go offline.
5555 * The caller must not hold any locks which would prevent @fn from completing.
5557 * Return: The value @fn returns.
5559 long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
5561 struct work_for_cpu wfc = { .fn = fn, .arg = arg };
5563 INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
5564 schedule_work_on(cpu, &wfc.work);
5565 flush_work(&wfc.work);
5566 destroy_work_on_stack(&wfc.work);
5569 EXPORT_SYMBOL_GPL(work_on_cpu);
5572 * work_on_cpu_safe - run a function in thread context on a particular cpu
5573 * @cpu: the cpu to run on
5574 * @fn: the function to run
5575 * @arg: the function argument
5577 * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
5578 * any locks which would prevent @fn from completing.
5580 * Return: The value @fn returns.
5582 long work_on_cpu_safe(int cpu, long (*fn)(void *), void *arg)
5587 if (cpu_online(cpu))
5588 ret = work_on_cpu(cpu, fn, arg);
5592 EXPORT_SYMBOL_GPL(work_on_cpu_safe);
5593 #endif /* CONFIG_SMP */
5595 #ifdef CONFIG_FREEZER
5598 * freeze_workqueues_begin - begin freezing workqueues
5600 * Start freezing workqueues. After this function returns, all freezable
5601 * workqueues will queue new works to their inactive_works list instead of
5605 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5607 void freeze_workqueues_begin(void)
5609 struct workqueue_struct *wq;
5610 struct pool_workqueue *pwq;
5612 mutex_lock(&wq_pool_mutex);
5614 WARN_ON_ONCE(workqueue_freezing);
5615 workqueue_freezing = true;
5617 list_for_each_entry(wq, &workqueues, list) {
5618 mutex_lock(&wq->mutex);
5619 for_each_pwq(pwq, wq)
5620 pwq_adjust_max_active(pwq);
5621 mutex_unlock(&wq->mutex);
5624 mutex_unlock(&wq_pool_mutex);
5628 * freeze_workqueues_busy - are freezable workqueues still busy?
5630 * Check whether freezing is complete. This function must be called
5631 * between freeze_workqueues_begin() and thaw_workqueues().
5634 * Grabs and releases wq_pool_mutex.
5637 * %true if some freezable workqueues are still busy. %false if freezing
5640 bool freeze_workqueues_busy(void)
5643 struct workqueue_struct *wq;
5644 struct pool_workqueue *pwq;
5646 mutex_lock(&wq_pool_mutex);
5648 WARN_ON_ONCE(!workqueue_freezing);
5650 list_for_each_entry(wq, &workqueues, list) {
5651 if (!(wq->flags & WQ_FREEZABLE))
5654 * nr_active is monotonically decreasing. It's safe
5655 * to peek without lock.
5658 for_each_pwq(pwq, wq) {
5659 WARN_ON_ONCE(pwq->nr_active < 0);
5660 if (pwq->nr_active) {
5669 mutex_unlock(&wq_pool_mutex);
5674 * thaw_workqueues - thaw workqueues
5676 * Thaw workqueues. Normal queueing is restored and all collected
5677 * frozen works are transferred to their respective pool worklists.
5680 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5682 void thaw_workqueues(void)
5684 struct workqueue_struct *wq;
5685 struct pool_workqueue *pwq;
5687 mutex_lock(&wq_pool_mutex);
5689 if (!workqueue_freezing)
5692 workqueue_freezing = false;
5694 /* restore max_active and repopulate worklist */
5695 list_for_each_entry(wq, &workqueues, list) {
5696 mutex_lock(&wq->mutex);
5697 for_each_pwq(pwq, wq)
5698 pwq_adjust_max_active(pwq);
5699 mutex_unlock(&wq->mutex);
5703 mutex_unlock(&wq_pool_mutex);
5705 #endif /* CONFIG_FREEZER */
5707 static int workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask)
5711 struct workqueue_struct *wq;
5712 struct apply_wqattrs_ctx *ctx, *n;
5714 lockdep_assert_held(&wq_pool_mutex);
5716 list_for_each_entry(wq, &workqueues, list) {
5717 if (!(wq->flags & WQ_UNBOUND))
5719 /* creating multiple pwqs breaks ordering guarantee */
5720 if (wq->flags & __WQ_ORDERED)
5723 ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs, unbound_cpumask);
5729 list_add_tail(&ctx->list, &ctxs);
5732 list_for_each_entry_safe(ctx, n, &ctxs, list) {
5734 apply_wqattrs_commit(ctx);
5735 apply_wqattrs_cleanup(ctx);
5739 mutex_lock(&wq_pool_attach_mutex);
5740 cpumask_copy(wq_unbound_cpumask, unbound_cpumask);
5741 mutex_unlock(&wq_pool_attach_mutex);
5747 * workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
5748 * @cpumask: the cpumask to set
5750 * The low-level workqueues cpumask is a global cpumask that limits
5751 * the affinity of all unbound workqueues. This function check the @cpumask
5752 * and apply it to all unbound workqueues and updates all pwqs of them.
5754 * Return: 0 - Success
5755 * -EINVAL - Invalid @cpumask
5756 * -ENOMEM - Failed to allocate memory for attrs or pwqs.
5758 int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
5763 * Not excluding isolated cpus on purpose.
5764 * If the user wishes to include them, we allow that.
5766 cpumask_and(cpumask, cpumask, cpu_possible_mask);
5767 if (!cpumask_empty(cpumask)) {
5768 apply_wqattrs_lock();
5769 if (cpumask_equal(cpumask, wq_unbound_cpumask)) {
5774 ret = workqueue_apply_unbound_cpumask(cpumask);
5777 apply_wqattrs_unlock();
5785 * Workqueues with WQ_SYSFS flag set is visible to userland via
5786 * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
5787 * following attributes.
5789 * per_cpu RO bool : whether the workqueue is per-cpu or unbound
5790 * max_active RW int : maximum number of in-flight work items
5792 * Unbound workqueues have the following extra attributes.
5794 * nice RW int : nice value of the workers
5795 * cpumask RW mask : bitmask of allowed CPUs for the workers
5798 struct workqueue_struct *wq;
5802 static struct workqueue_struct *dev_to_wq(struct device *dev)
5804 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
5809 static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
5812 struct workqueue_struct *wq = dev_to_wq(dev);
5814 return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
5816 static DEVICE_ATTR_RO(per_cpu);
5818 static ssize_t max_active_show(struct device *dev,
5819 struct device_attribute *attr, char *buf)
5821 struct workqueue_struct *wq = dev_to_wq(dev);
5823 return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
5826 static ssize_t max_active_store(struct device *dev,
5827 struct device_attribute *attr, const char *buf,
5830 struct workqueue_struct *wq = dev_to_wq(dev);
5833 if (sscanf(buf, "%d", &val) != 1 || val <= 0)
5836 workqueue_set_max_active(wq, val);
5839 static DEVICE_ATTR_RW(max_active);
5841 static struct attribute *wq_sysfs_attrs[] = {
5842 &dev_attr_per_cpu.attr,
5843 &dev_attr_max_active.attr,
5846 ATTRIBUTE_GROUPS(wq_sysfs);
5848 static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
5851 struct workqueue_struct *wq = dev_to_wq(dev);
5854 mutex_lock(&wq->mutex);
5855 written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
5856 mutex_unlock(&wq->mutex);
5861 /* prepare workqueue_attrs for sysfs store operations */
5862 static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
5864 struct workqueue_attrs *attrs;
5866 lockdep_assert_held(&wq_pool_mutex);
5868 attrs = alloc_workqueue_attrs();
5872 copy_workqueue_attrs(attrs, wq->unbound_attrs);
5876 static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
5877 const char *buf, size_t count)
5879 struct workqueue_struct *wq = dev_to_wq(dev);
5880 struct workqueue_attrs *attrs;
5883 apply_wqattrs_lock();
5885 attrs = wq_sysfs_prep_attrs(wq);
5889 if (sscanf(buf, "%d", &attrs->nice) == 1 &&
5890 attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
5891 ret = apply_workqueue_attrs_locked(wq, attrs);
5896 apply_wqattrs_unlock();
5897 free_workqueue_attrs(attrs);
5898 return ret ?: count;
5901 static ssize_t wq_cpumask_show(struct device *dev,
5902 struct device_attribute *attr, char *buf)
5904 struct workqueue_struct *wq = dev_to_wq(dev);
5907 mutex_lock(&wq->mutex);
5908 written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
5909 cpumask_pr_args(wq->unbound_attrs->cpumask));
5910 mutex_unlock(&wq->mutex);
5914 static ssize_t wq_cpumask_store(struct device *dev,
5915 struct device_attribute *attr,
5916 const char *buf, size_t count)
5918 struct workqueue_struct *wq = dev_to_wq(dev);
5919 struct workqueue_attrs *attrs;
5922 apply_wqattrs_lock();
5924 attrs = wq_sysfs_prep_attrs(wq);
5928 ret = cpumask_parse(buf, attrs->cpumask);
5930 ret = apply_workqueue_attrs_locked(wq, attrs);
5933 apply_wqattrs_unlock();
5934 free_workqueue_attrs(attrs);
5935 return ret ?: count;
5938 static struct device_attribute wq_sysfs_unbound_attrs[] = {
5939 __ATTR(nice, 0644, wq_nice_show, wq_nice_store),
5940 __ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
5944 static struct bus_type wq_subsys = {
5945 .name = "workqueue",
5946 .dev_groups = wq_sysfs_groups,
5949 static ssize_t wq_unbound_cpumask_show(struct device *dev,
5950 struct device_attribute *attr, char *buf)
5954 mutex_lock(&wq_pool_mutex);
5955 written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
5956 cpumask_pr_args(wq_unbound_cpumask));
5957 mutex_unlock(&wq_pool_mutex);
5962 static ssize_t wq_unbound_cpumask_store(struct device *dev,
5963 struct device_attribute *attr, const char *buf, size_t count)
5965 cpumask_var_t cpumask;
5968 if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
5971 ret = cpumask_parse(buf, cpumask);
5973 ret = workqueue_set_unbound_cpumask(cpumask);
5975 free_cpumask_var(cpumask);
5976 return ret ? ret : count;
5979 static struct device_attribute wq_sysfs_cpumask_attr =
5980 __ATTR(cpumask, 0644, wq_unbound_cpumask_show,
5981 wq_unbound_cpumask_store);
5983 static int __init wq_sysfs_init(void)
5985 struct device *dev_root;
5988 err = subsys_virtual_register(&wq_subsys, NULL);
5992 dev_root = bus_get_dev_root(&wq_subsys);
5994 err = device_create_file(dev_root, &wq_sysfs_cpumask_attr);
5995 put_device(dev_root);
5999 core_initcall(wq_sysfs_init);
6001 static void wq_device_release(struct device *dev)
6003 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
6009 * workqueue_sysfs_register - make a workqueue visible in sysfs
6010 * @wq: the workqueue to register
6012 * Expose @wq in sysfs under /sys/bus/workqueue/devices.
6013 * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
6014 * which is the preferred method.
6016 * Workqueue user should use this function directly iff it wants to apply
6017 * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
6018 * apply_workqueue_attrs() may race against userland updating the
6021 * Return: 0 on success, -errno on failure.
6023 int workqueue_sysfs_register(struct workqueue_struct *wq)
6025 struct wq_device *wq_dev;
6029 * Adjusting max_active or creating new pwqs by applying
6030 * attributes breaks ordering guarantee. Disallow exposing ordered
6033 if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
6036 wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
6041 wq_dev->dev.bus = &wq_subsys;
6042 wq_dev->dev.release = wq_device_release;
6043 dev_set_name(&wq_dev->dev, "%s", wq->name);
6046 * unbound_attrs are created separately. Suppress uevent until
6047 * everything is ready.
6049 dev_set_uevent_suppress(&wq_dev->dev, true);
6051 ret = device_register(&wq_dev->dev);
6053 put_device(&wq_dev->dev);
6058 if (wq->flags & WQ_UNBOUND) {
6059 struct device_attribute *attr;
6061 for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
6062 ret = device_create_file(&wq_dev->dev, attr);
6064 device_unregister(&wq_dev->dev);
6071 dev_set_uevent_suppress(&wq_dev->dev, false);
6072 kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
6077 * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
6078 * @wq: the workqueue to unregister
6080 * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
6082 static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
6084 struct wq_device *wq_dev = wq->wq_dev;
6090 device_unregister(&wq_dev->dev);
6092 #else /* CONFIG_SYSFS */
6093 static void workqueue_sysfs_unregister(struct workqueue_struct *wq) { }
6094 #endif /* CONFIG_SYSFS */
6097 * Workqueue watchdog.
6099 * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
6100 * flush dependency, a concurrency managed work item which stays RUNNING
6101 * indefinitely. Workqueue stalls can be very difficult to debug as the
6102 * usual warning mechanisms don't trigger and internal workqueue state is
6105 * Workqueue watchdog monitors all worker pools periodically and dumps
6106 * state if some pools failed to make forward progress for a while where
6107 * forward progress is defined as the first item on ->worklist changing.
6109 * This mechanism is controlled through the kernel parameter
6110 * "workqueue.watchdog_thresh" which can be updated at runtime through the
6111 * corresponding sysfs parameter file.
6113 #ifdef CONFIG_WQ_WATCHDOG
6115 static unsigned long wq_watchdog_thresh = 30;
6116 static struct timer_list wq_watchdog_timer;
6118 static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
6119 static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
6122 * Show workers that might prevent the processing of pending work items.
6123 * The only candidates are CPU-bound workers in the running state.
6124 * Pending work items should be handled by another idle worker
6125 * in all other situations.
6127 static void show_cpu_pool_hog(struct worker_pool *pool)
6129 struct worker *worker;
6130 unsigned long flags;
6133 raw_spin_lock_irqsave(&pool->lock, flags);
6135 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
6136 if (task_is_running(worker->task)) {
6138 * Defer printing to avoid deadlocks in console
6139 * drivers that queue work while holding locks
6140 * also taken in their write paths.
6142 printk_deferred_enter();
6144 pr_info("pool %d:\n", pool->id);
6145 sched_show_task(worker->task);
6147 printk_deferred_exit();
6151 raw_spin_unlock_irqrestore(&pool->lock, flags);
6154 static void show_cpu_pools_hogs(void)
6156 struct worker_pool *pool;
6159 pr_info("Showing backtraces of running workers in stalled CPU-bound worker pools:\n");
6163 for_each_pool(pool, pi) {
6164 if (pool->cpu_stall)
6165 show_cpu_pool_hog(pool);
6172 static void wq_watchdog_reset_touched(void)
6176 wq_watchdog_touched = jiffies;
6177 for_each_possible_cpu(cpu)
6178 per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
6181 static void wq_watchdog_timer_fn(struct timer_list *unused)
6183 unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
6184 bool lockup_detected = false;
6185 bool cpu_pool_stall = false;
6186 unsigned long now = jiffies;
6187 struct worker_pool *pool;
6195 for_each_pool(pool, pi) {
6196 unsigned long pool_ts, touched, ts;
6198 pool->cpu_stall = false;
6199 if (list_empty(&pool->worklist))
6203 * If a virtual machine is stopped by the host it can look to
6204 * the watchdog like a stall.
6206 kvm_check_and_clear_guest_paused();
6208 /* get the latest of pool and touched timestamps */
6210 touched = READ_ONCE(per_cpu(wq_watchdog_touched_cpu, pool->cpu));
6212 touched = READ_ONCE(wq_watchdog_touched);
6213 pool_ts = READ_ONCE(pool->watchdog_ts);
6215 if (time_after(pool_ts, touched))
6221 if (time_after(now, ts + thresh)) {
6222 lockup_detected = true;
6223 if (pool->cpu >= 0) {
6224 pool->cpu_stall = true;
6225 cpu_pool_stall = true;
6227 pr_emerg("BUG: workqueue lockup - pool");
6228 pr_cont_pool_info(pool);
6229 pr_cont(" stuck for %us!\n",
6230 jiffies_to_msecs(now - pool_ts) / 1000);
6238 if (lockup_detected)
6239 show_all_workqueues();
6242 show_cpu_pools_hogs();
6244 wq_watchdog_reset_touched();
6245 mod_timer(&wq_watchdog_timer, jiffies + thresh);
6248 notrace void wq_watchdog_touch(int cpu)
6251 per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
6253 wq_watchdog_touched = jiffies;
6256 static void wq_watchdog_set_thresh(unsigned long thresh)
6258 wq_watchdog_thresh = 0;
6259 del_timer_sync(&wq_watchdog_timer);
6262 wq_watchdog_thresh = thresh;
6263 wq_watchdog_reset_touched();
6264 mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
6268 static int wq_watchdog_param_set_thresh(const char *val,
6269 const struct kernel_param *kp)
6271 unsigned long thresh;
6274 ret = kstrtoul(val, 0, &thresh);
6279 wq_watchdog_set_thresh(thresh);
6281 wq_watchdog_thresh = thresh;
6286 static const struct kernel_param_ops wq_watchdog_thresh_ops = {
6287 .set = wq_watchdog_param_set_thresh,
6288 .get = param_get_ulong,
6291 module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
6294 static void wq_watchdog_init(void)
6296 timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
6297 wq_watchdog_set_thresh(wq_watchdog_thresh);
6300 #else /* CONFIG_WQ_WATCHDOG */
6302 static inline void wq_watchdog_init(void) { }
6304 #endif /* CONFIG_WQ_WATCHDOG */
6306 static void __init wq_numa_init(void)
6311 if (num_possible_nodes() <= 1)
6314 for_each_possible_cpu(cpu) {
6315 if (WARN_ON(cpu_to_node(cpu) == NUMA_NO_NODE)) {
6316 pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
6321 wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs();
6322 BUG_ON(!wq_update_unbound_numa_attrs_buf);
6325 * We want masks of possible CPUs of each node which isn't readily
6326 * available. Build one from cpu_to_node() which should have been
6327 * fully initialized by now.
6329 tbl = kcalloc(nr_node_ids, sizeof(tbl[0]), GFP_KERNEL);
6333 BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
6334 node_online(node) ? node : NUMA_NO_NODE));
6336 for_each_possible_cpu(cpu) {
6337 node = cpu_to_node(cpu);
6338 cpumask_set_cpu(cpu, tbl[node]);
6341 wq_numa_possible_cpumask = tbl;
6342 wq_numa_enabled = true;
6346 * workqueue_init_early - early init for workqueue subsystem
6348 * This is the first half of two-staged workqueue subsystem initialization
6349 * and invoked as soon as the bare basics - memory allocation, cpumasks and
6350 * idr are up. It sets up all the data structures and system workqueues
6351 * and allows early boot code to create workqueues and queue/cancel work
6352 * items. Actual work item execution starts only after kthreads can be
6353 * created and scheduled right before early initcalls.
6355 void __init workqueue_init_early(void)
6357 int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
6360 BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
6362 BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
6363 cpumask_copy(wq_unbound_cpumask, housekeeping_cpumask(HK_TYPE_WQ));
6364 cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, housekeeping_cpumask(HK_TYPE_DOMAIN));
6366 if (!cpumask_empty(&wq_cmdline_cpumask))
6367 cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, &wq_cmdline_cpumask);
6369 pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
6371 /* initialize CPU pools */
6372 for_each_possible_cpu(cpu) {
6373 struct worker_pool *pool;
6376 for_each_cpu_worker_pool(pool, cpu) {
6377 BUG_ON(init_worker_pool(pool));
6379 cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
6380 pool->attrs->nice = std_nice[i++];
6381 pool->node = cpu_to_node(cpu);
6384 mutex_lock(&wq_pool_mutex);
6385 BUG_ON(worker_pool_assign_id(pool));
6386 mutex_unlock(&wq_pool_mutex);
6390 /* create default unbound and ordered wq attrs */
6391 for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
6392 struct workqueue_attrs *attrs;
6394 BUG_ON(!(attrs = alloc_workqueue_attrs()));
6395 attrs->nice = std_nice[i];
6396 unbound_std_wq_attrs[i] = attrs;
6399 * An ordered wq should have only one pwq as ordering is
6400 * guaranteed by max_active which is enforced by pwqs.
6401 * Turn off NUMA so that dfl_pwq is used for all nodes.
6403 BUG_ON(!(attrs = alloc_workqueue_attrs()));
6404 attrs->nice = std_nice[i];
6405 attrs->no_numa = true;
6406 ordered_wq_attrs[i] = attrs;
6409 system_wq = alloc_workqueue("events", 0, 0);
6410 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
6411 system_long_wq = alloc_workqueue("events_long", 0, 0);
6412 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
6413 WQ_UNBOUND_MAX_ACTIVE);
6414 system_freezable_wq = alloc_workqueue("events_freezable",
6416 system_power_efficient_wq = alloc_workqueue("events_power_efficient",
6417 WQ_POWER_EFFICIENT, 0);
6418 system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
6419 WQ_FREEZABLE | WQ_POWER_EFFICIENT,
6421 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
6422 !system_unbound_wq || !system_freezable_wq ||
6423 !system_power_efficient_wq ||
6424 !system_freezable_power_efficient_wq);
6427 static void __init wq_cpu_intensive_thresh_init(void)
6429 unsigned long thresh;
6432 /* if the user set it to a specific value, keep it */
6433 if (wq_cpu_intensive_thresh_us != ULONG_MAX)
6437 * The default of 10ms is derived from the fact that most modern (as of
6438 * 2023) processors can do a lot in 10ms and that it's just below what
6439 * most consider human-perceivable. However, the kernel also runs on a
6440 * lot slower CPUs including microcontrollers where the threshold is way
6443 * Let's scale up the threshold upto 1 second if BogoMips is below 4000.
6444 * This is by no means accurate but it doesn't have to be. The mechanism
6445 * is still useful even when the threshold is fully scaled up. Also, as
6446 * the reports would usually be applicable to everyone, some machines
6447 * operating on longer thresholds won't significantly diminish their
6450 thresh = 10 * USEC_PER_MSEC;
6452 /* see init/calibrate.c for lpj -> BogoMIPS calculation */
6453 bogo = max_t(unsigned long, loops_per_jiffy / 500000 * HZ, 1);
6455 thresh = min_t(unsigned long, thresh * 4000 / bogo, USEC_PER_SEC);
6457 pr_debug("wq_cpu_intensive_thresh: lpj=%lu BogoMIPS=%lu thresh_us=%lu\n",
6458 loops_per_jiffy, bogo, thresh);
6460 wq_cpu_intensive_thresh_us = thresh;
6464 * workqueue_init - bring workqueue subsystem fully online
6466 * This is the latter half of two-staged workqueue subsystem initialization
6467 * and invoked as soon as kthreads can be created and scheduled.
6468 * Workqueues have been created and work items queued on them, but there
6469 * are no kworkers executing the work items yet. Populate the worker pools
6470 * with the initial workers and enable future kworker creations.
6472 void __init workqueue_init(void)
6474 struct workqueue_struct *wq;
6475 struct worker_pool *pool;
6478 wq_cpu_intensive_thresh_init();
6481 * It'd be simpler to initialize NUMA in workqueue_init_early() but
6482 * CPU to node mapping may not be available that early on some
6483 * archs such as power and arm64. As per-cpu pools created
6484 * previously could be missing node hint and unbound pools NUMA
6485 * affinity, fix them up.
6487 * Also, while iterating workqueues, create rescuers if requested.
6491 mutex_lock(&wq_pool_mutex);
6493 for_each_possible_cpu(cpu) {
6494 for_each_cpu_worker_pool(pool, cpu) {
6495 pool->node = cpu_to_node(cpu);
6499 list_for_each_entry(wq, &workqueues, list) {
6500 wq_update_unbound_numa(wq, smp_processor_id(), true);
6501 WARN(init_rescuer(wq),
6502 "workqueue: failed to create early rescuer for %s",
6506 mutex_unlock(&wq_pool_mutex);
6508 /* create the initial workers */
6509 for_each_online_cpu(cpu) {
6510 for_each_cpu_worker_pool(pool, cpu) {
6511 pool->flags &= ~POOL_DISASSOCIATED;
6512 BUG_ON(!create_worker(pool));
6516 hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
6517 BUG_ON(!create_worker(pool));
6523 void __warn_flushing_systemwide_wq(void)
6525 pr_warn("WARNING: Flushing system-wide workqueues will be prohibited in near future.\n");
6528 EXPORT_SYMBOL(__warn_flushing_systemwide_wq);
6530 static int __init workqueue_unbound_cpus_setup(char *str)
6532 if (cpulist_parse(str, &wq_cmdline_cpumask) < 0) {
6533 cpumask_clear(&wq_cmdline_cpumask);
6534 pr_warn("workqueue.unbound_cpus: incorrect CPU range, using default\n");
6539 __setup("workqueue.unbound_cpus=", workqueue_unbound_cpus_setup);