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 * X: During normal operation, modification requires pool->lock and should
126 * be done only from local cpu. Either disabling preemption on local
127 * cpu or grabbing pool->lock is enough for read access. If
128 * POOL_DISASSOCIATED is set, it's identical to L.
130 * K: Only modified by worker while holding pool->lock. Can be safely read by
131 * self, while holding pool->lock or from IRQ context if %current is the
134 * S: Only modified by worker self.
136 * A: wq_pool_attach_mutex protected.
138 * PL: wq_pool_mutex protected.
140 * PR: wq_pool_mutex protected for writes. RCU protected for reads.
142 * PW: wq_pool_mutex and wq->mutex protected for writes. Either for reads.
144 * PWR: wq_pool_mutex and wq->mutex protected for writes. Either or
147 * WQ: wq->mutex protected.
149 * WR: wq->mutex protected for writes. RCU protected for reads.
151 * MD: wq_mayday_lock protected.
153 * WD: Used internally by the watchdog.
156 /* struct worker is defined in workqueue_internal.h */
159 raw_spinlock_t lock; /* the pool lock */
160 int cpu; /* I: the associated cpu */
161 int node; /* I: the associated node ID */
162 int id; /* I: pool ID */
163 unsigned int flags; /* X: flags */
165 unsigned long watchdog_ts; /* L: watchdog timestamp */
166 bool cpu_stall; /* WD: stalled cpu bound pool */
169 * The counter is incremented in a process context on the associated CPU
170 * w/ preemption disabled, and decremented or reset in the same context
171 * but w/ pool->lock held. The readers grab pool->lock and are
172 * guaranteed to see if the counter reached zero.
176 struct list_head worklist; /* L: list of pending works */
178 int nr_workers; /* L: total number of workers */
179 int nr_idle; /* L: currently idle workers */
181 struct list_head idle_list; /* L: list of idle workers */
182 struct timer_list idle_timer; /* L: worker idle timeout */
183 struct work_struct idle_cull_work; /* L: worker idle cleanup */
185 struct timer_list mayday_timer; /* L: SOS timer for workers */
187 /* a workers is either on busy_hash or idle_list, or the manager */
188 DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
189 /* L: hash of busy workers */
191 struct worker *manager; /* L: purely informational */
192 struct list_head workers; /* A: attached workers */
193 struct list_head dying_workers; /* A: workers about to die */
194 struct completion *detach_completion; /* all workers detached */
196 struct ida worker_ida; /* worker IDs for task name */
198 struct workqueue_attrs *attrs; /* I: worker attributes */
199 struct hlist_node hash_node; /* PL: unbound_pool_hash node */
200 int refcnt; /* PL: refcnt for unbound pools */
203 * Destruction of pool is RCU protected to allow dereferences
204 * from get_work_pool().
210 * Per-pool_workqueue statistics. These can be monitored using
211 * tools/workqueue/wq_monitor.py.
213 enum pool_workqueue_stats {
214 PWQ_STAT_STARTED, /* work items started execution */
215 PWQ_STAT_COMPLETED, /* work items completed execution */
216 PWQ_STAT_CPU_TIME, /* total CPU time consumed */
217 PWQ_STAT_CPU_INTENSIVE, /* wq_cpu_intensive_thresh_us violations */
218 PWQ_STAT_CM_WAKEUP, /* concurrency-management worker wakeups */
219 PWQ_STAT_MAYDAY, /* maydays to rescuer */
220 PWQ_STAT_RESCUED, /* linked work items executed by rescuer */
226 * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
227 * of work_struct->data are used for flags and the remaining high bits
228 * point to the pwq; thus, pwqs need to be aligned at two's power of the
229 * number of flag bits.
231 struct pool_workqueue {
232 struct worker_pool *pool; /* I: the associated pool */
233 struct workqueue_struct *wq; /* I: the owning workqueue */
234 int work_color; /* L: current color */
235 int flush_color; /* L: flushing color */
236 int refcnt; /* L: reference count */
237 int nr_in_flight[WORK_NR_COLORS];
238 /* L: nr of in_flight works */
241 * nr_active management and WORK_STRUCT_INACTIVE:
243 * When pwq->nr_active >= max_active, new work item is queued to
244 * pwq->inactive_works instead of pool->worklist and marked with
245 * WORK_STRUCT_INACTIVE.
247 * All work items marked with WORK_STRUCT_INACTIVE do not participate
248 * in pwq->nr_active and all work items in pwq->inactive_works are
249 * marked with WORK_STRUCT_INACTIVE. But not all WORK_STRUCT_INACTIVE
250 * work items are in pwq->inactive_works. Some of them are ready to
251 * run in pool->worklist or worker->scheduled. Those work itmes are
252 * only struct wq_barrier which is used for flush_work() and should
253 * not participate in pwq->nr_active. For non-barrier work item, it
254 * is marked with WORK_STRUCT_INACTIVE iff it is in pwq->inactive_works.
256 int nr_active; /* L: nr of active works */
257 int max_active; /* L: max active works */
258 struct list_head inactive_works; /* L: inactive works */
259 struct list_head pwqs_node; /* WR: node on wq->pwqs */
260 struct list_head mayday_node; /* MD: node on wq->maydays */
262 u64 stats[PWQ_NR_STATS];
265 * Release of unbound pwq is punted to system_wq. See put_pwq()
266 * and pwq_unbound_release_workfn() for details. pool_workqueue
267 * itself is also RCU protected so that the first pwq can be
268 * determined without grabbing wq->mutex.
270 struct work_struct unbound_release_work;
272 } __aligned(1 << WORK_STRUCT_FLAG_BITS);
275 * Structure used to wait for workqueue flush.
278 struct list_head list; /* WQ: list of flushers */
279 int flush_color; /* WQ: flush color waiting for */
280 struct completion done; /* flush completion */
286 * The externally visible workqueue. It relays the issued work items to
287 * the appropriate worker_pool through its pool_workqueues.
289 struct workqueue_struct {
290 struct list_head pwqs; /* WR: all pwqs of this wq */
291 struct list_head list; /* PR: list of all workqueues */
293 struct mutex mutex; /* protects this wq */
294 int work_color; /* WQ: current work color */
295 int flush_color; /* WQ: current flush color */
296 atomic_t nr_pwqs_to_flush; /* flush in progress */
297 struct wq_flusher *first_flusher; /* WQ: first flusher */
298 struct list_head flusher_queue; /* WQ: flush waiters */
299 struct list_head flusher_overflow; /* WQ: flush overflow list */
301 struct list_head maydays; /* MD: pwqs requesting rescue */
302 struct worker *rescuer; /* MD: rescue worker */
304 int nr_drainers; /* WQ: drain in progress */
305 int saved_max_active; /* WQ: saved pwq max_active */
307 struct workqueue_attrs *unbound_attrs; /* PW: only for unbound wqs */
308 struct pool_workqueue *dfl_pwq; /* PW: only for unbound wqs */
311 struct wq_device *wq_dev; /* I: for sysfs interface */
313 #ifdef CONFIG_LOCKDEP
315 struct lock_class_key key;
316 struct lockdep_map lockdep_map;
318 char name[WQ_NAME_LEN]; /* I: workqueue name */
321 * Destruction of workqueue_struct is RCU protected to allow walking
322 * the workqueues list without grabbing wq_pool_mutex.
323 * This is used to dump all workqueues from sysrq.
327 /* hot fields used during command issue, aligned to cacheline */
328 unsigned int flags ____cacheline_aligned; /* WQ: WQ_* flags */
329 struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */
330 struct pool_workqueue __rcu *numa_pwq_tbl[]; /* PWR: unbound pwqs indexed by node */
333 static struct kmem_cache *pwq_cache;
335 static cpumask_var_t *wq_numa_possible_cpumask;
336 /* possible CPUs of each node */
339 * Per-cpu work items which run for longer than the following threshold are
340 * automatically considered CPU intensive and excluded from concurrency
341 * management to prevent them from noticeably delaying other per-cpu work items.
342 * ULONG_MAX indicates that the user hasn't overridden it with a boot parameter.
343 * The actual value is initialized in wq_cpu_intensive_thresh_init().
345 static unsigned long wq_cpu_intensive_thresh_us = ULONG_MAX;
346 module_param_named(cpu_intensive_thresh_us, wq_cpu_intensive_thresh_us, ulong, 0644);
348 static bool wq_disable_numa;
349 module_param_named(disable_numa, wq_disable_numa, bool, 0444);
351 /* see the comment above the definition of WQ_POWER_EFFICIENT */
352 static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
353 module_param_named(power_efficient, wq_power_efficient, bool, 0444);
355 static bool wq_online; /* can kworkers be created yet? */
357 static bool wq_numa_enabled; /* unbound NUMA affinity enabled */
359 /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
360 static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf;
362 static DEFINE_MUTEX(wq_pool_mutex); /* protects pools and workqueues list */
363 static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
364 static DEFINE_RAW_SPINLOCK(wq_mayday_lock); /* protects wq->maydays list */
365 /* wait for manager to go away */
366 static struct rcuwait manager_wait = __RCUWAIT_INITIALIZER(manager_wait);
368 static LIST_HEAD(workqueues); /* PR: list of all workqueues */
369 static bool workqueue_freezing; /* PL: have wqs started freezing? */
371 /* PL&A: allowable cpus for unbound wqs and work items */
372 static cpumask_var_t wq_unbound_cpumask;
374 /* CPU where unbound work was last round robin scheduled from this CPU */
375 static DEFINE_PER_CPU(int, wq_rr_cpu_last);
378 * Local execution of unbound work items is no longer guaranteed. The
379 * following always forces round-robin CPU selection on unbound work items
380 * to uncover usages which depend on it.
382 #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
383 static bool wq_debug_force_rr_cpu = true;
385 static bool wq_debug_force_rr_cpu = false;
387 module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
389 /* the per-cpu worker pools */
390 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools);
392 static DEFINE_IDR(worker_pool_idr); /* PR: idr of all pools */
394 /* PL: hash of all unbound pools keyed by pool->attrs */
395 static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
397 /* I: attributes used when instantiating standard unbound pools on demand */
398 static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
400 /* I: attributes used when instantiating ordered pools on demand */
401 static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
403 struct workqueue_struct *system_wq __read_mostly;
404 EXPORT_SYMBOL(system_wq);
405 struct workqueue_struct *system_highpri_wq __read_mostly;
406 EXPORT_SYMBOL_GPL(system_highpri_wq);
407 struct workqueue_struct *system_long_wq __read_mostly;
408 EXPORT_SYMBOL_GPL(system_long_wq);
409 struct workqueue_struct *system_unbound_wq __read_mostly;
410 EXPORT_SYMBOL_GPL(system_unbound_wq);
411 struct workqueue_struct *system_freezable_wq __read_mostly;
412 EXPORT_SYMBOL_GPL(system_freezable_wq);
413 struct workqueue_struct *system_power_efficient_wq __read_mostly;
414 EXPORT_SYMBOL_GPL(system_power_efficient_wq);
415 struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
416 EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
418 static int worker_thread(void *__worker);
419 static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
420 static void show_pwq(struct pool_workqueue *pwq);
421 static void show_one_worker_pool(struct worker_pool *pool);
423 #define CREATE_TRACE_POINTS
424 #include <trace/events/workqueue.h>
426 #define assert_rcu_or_pool_mutex() \
427 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
428 !lockdep_is_held(&wq_pool_mutex), \
429 "RCU or wq_pool_mutex should be held")
431 #define assert_rcu_or_wq_mutex_or_pool_mutex(wq) \
432 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
433 !lockdep_is_held(&wq->mutex) && \
434 !lockdep_is_held(&wq_pool_mutex), \
435 "RCU, wq->mutex or wq_pool_mutex should be held")
437 #define for_each_cpu_worker_pool(pool, cpu) \
438 for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
439 (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
443 * for_each_pool - iterate through all worker_pools in the system
444 * @pool: iteration cursor
445 * @pi: integer used for iteration
447 * This must be called either with wq_pool_mutex held or RCU read
448 * locked. If the pool needs to be used beyond the locking in effect, the
449 * caller is responsible for guaranteeing that the pool stays online.
451 * The if/else clause exists only for the lockdep assertion and can be
454 #define for_each_pool(pool, pi) \
455 idr_for_each_entry(&worker_pool_idr, pool, pi) \
456 if (({ assert_rcu_or_pool_mutex(); false; })) { } \
460 * for_each_pool_worker - iterate through all workers of a worker_pool
461 * @worker: iteration cursor
462 * @pool: worker_pool to iterate workers of
464 * This must be called with wq_pool_attach_mutex.
466 * The if/else clause exists only for the lockdep assertion and can be
469 #define for_each_pool_worker(worker, pool) \
470 list_for_each_entry((worker), &(pool)->workers, node) \
471 if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
475 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
476 * @pwq: iteration cursor
477 * @wq: the target workqueue
479 * This must be called either with wq->mutex held or RCU read locked.
480 * If the pwq needs to be used beyond the locking in effect, the caller is
481 * responsible for guaranteeing that the pwq stays online.
483 * The if/else clause exists only for the lockdep assertion and can be
486 #define for_each_pwq(pwq, wq) \
487 list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node, \
488 lockdep_is_held(&(wq->mutex)))
490 #ifdef CONFIG_DEBUG_OBJECTS_WORK
492 static const struct debug_obj_descr work_debug_descr;
494 static void *work_debug_hint(void *addr)
496 return ((struct work_struct *) addr)->func;
499 static bool work_is_static_object(void *addr)
501 struct work_struct *work = addr;
503 return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
507 * fixup_init is called when:
508 * - an active object is initialized
510 static bool work_fixup_init(void *addr, enum debug_obj_state state)
512 struct work_struct *work = addr;
515 case ODEBUG_STATE_ACTIVE:
516 cancel_work_sync(work);
517 debug_object_init(work, &work_debug_descr);
525 * fixup_free is called when:
526 * - an active object is freed
528 static bool work_fixup_free(void *addr, enum debug_obj_state state)
530 struct work_struct *work = addr;
533 case ODEBUG_STATE_ACTIVE:
534 cancel_work_sync(work);
535 debug_object_free(work, &work_debug_descr);
542 static const struct debug_obj_descr work_debug_descr = {
543 .name = "work_struct",
544 .debug_hint = work_debug_hint,
545 .is_static_object = work_is_static_object,
546 .fixup_init = work_fixup_init,
547 .fixup_free = work_fixup_free,
550 static inline void debug_work_activate(struct work_struct *work)
552 debug_object_activate(work, &work_debug_descr);
555 static inline void debug_work_deactivate(struct work_struct *work)
557 debug_object_deactivate(work, &work_debug_descr);
560 void __init_work(struct work_struct *work, int onstack)
563 debug_object_init_on_stack(work, &work_debug_descr);
565 debug_object_init(work, &work_debug_descr);
567 EXPORT_SYMBOL_GPL(__init_work);
569 void destroy_work_on_stack(struct work_struct *work)
571 debug_object_free(work, &work_debug_descr);
573 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
575 void destroy_delayed_work_on_stack(struct delayed_work *work)
577 destroy_timer_on_stack(&work->timer);
578 debug_object_free(&work->work, &work_debug_descr);
580 EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
583 static inline void debug_work_activate(struct work_struct *work) { }
584 static inline void debug_work_deactivate(struct work_struct *work) { }
588 * worker_pool_assign_id - allocate ID and assign it to @pool
589 * @pool: the pool pointer of interest
591 * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
592 * successfully, -errno on failure.
594 static int worker_pool_assign_id(struct worker_pool *pool)
598 lockdep_assert_held(&wq_pool_mutex);
600 ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
610 * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
611 * @wq: the target workqueue
614 * This must be called with any of wq_pool_mutex, wq->mutex or RCU
616 * If the pwq needs to be used beyond the locking in effect, the caller is
617 * responsible for guaranteeing that the pwq stays online.
619 * Return: The unbound pool_workqueue for @node.
621 static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
624 assert_rcu_or_wq_mutex_or_pool_mutex(wq);
627 * XXX: @node can be NUMA_NO_NODE if CPU goes offline while a
628 * delayed item is pending. The plan is to keep CPU -> NODE
629 * mapping valid and stable across CPU on/offlines. Once that
630 * happens, this workaround can be removed.
632 if (unlikely(node == NUMA_NO_NODE))
635 return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
638 static unsigned int work_color_to_flags(int color)
640 return color << WORK_STRUCT_COLOR_SHIFT;
643 static int get_work_color(unsigned long work_data)
645 return (work_data >> WORK_STRUCT_COLOR_SHIFT) &
646 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
649 static int work_next_color(int color)
651 return (color + 1) % WORK_NR_COLORS;
655 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
656 * contain the pointer to the queued pwq. Once execution starts, the flag
657 * is cleared and the high bits contain OFFQ flags and pool ID.
659 * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
660 * and clear_work_data() can be used to set the pwq, pool or clear
661 * work->data. These functions should only be called while the work is
662 * owned - ie. while the PENDING bit is set.
664 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
665 * corresponding to a work. Pool is available once the work has been
666 * queued anywhere after initialization until it is sync canceled. pwq is
667 * available only while the work item is queued.
669 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
670 * canceled. While being canceled, a work item may have its PENDING set
671 * but stay off timer and worklist for arbitrarily long and nobody should
672 * try to steal the PENDING bit.
674 static inline void set_work_data(struct work_struct *work, unsigned long data,
677 WARN_ON_ONCE(!work_pending(work));
678 atomic_long_set(&work->data, data | flags | work_static(work));
681 static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
682 unsigned long extra_flags)
684 set_work_data(work, (unsigned long)pwq,
685 WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
688 static void set_work_pool_and_keep_pending(struct work_struct *work,
691 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
692 WORK_STRUCT_PENDING);
695 static void set_work_pool_and_clear_pending(struct work_struct *work,
699 * The following wmb is paired with the implied mb in
700 * test_and_set_bit(PENDING) and ensures all updates to @work made
701 * here are visible to and precede any updates by the next PENDING
705 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
707 * The following mb guarantees that previous clear of a PENDING bit
708 * will not be reordered with any speculative LOADS or STORES from
709 * work->current_func, which is executed afterwards. This possible
710 * reordering can lead to a missed execution on attempt to queue
711 * the same @work. E.g. consider this case:
714 * ---------------------------- --------------------------------
716 * 1 STORE event_indicated
717 * 2 queue_work_on() {
718 * 3 test_and_set_bit(PENDING)
719 * 4 } set_..._and_clear_pending() {
720 * 5 set_work_data() # clear bit
722 * 7 work->current_func() {
723 * 8 LOAD event_indicated
726 * Without an explicit full barrier speculative LOAD on line 8 can
727 * be executed before CPU#0 does STORE on line 1. If that happens,
728 * CPU#0 observes the PENDING bit is still set and new execution of
729 * a @work is not queued in a hope, that CPU#1 will eventually
730 * finish the queued @work. Meanwhile CPU#1 does not see
731 * event_indicated is set, because speculative LOAD was executed
732 * before actual STORE.
737 static void clear_work_data(struct work_struct *work)
739 smp_wmb(); /* see set_work_pool_and_clear_pending() */
740 set_work_data(work, WORK_STRUCT_NO_POOL, 0);
743 static inline struct pool_workqueue *work_struct_pwq(unsigned long data)
745 return (struct pool_workqueue *)(data & WORK_STRUCT_WQ_DATA_MASK);
748 static struct pool_workqueue *get_work_pwq(struct work_struct *work)
750 unsigned long data = atomic_long_read(&work->data);
752 if (data & WORK_STRUCT_PWQ)
753 return work_struct_pwq(data);
759 * get_work_pool - return the worker_pool a given work was associated with
760 * @work: the work item of interest
762 * Pools are created and destroyed under wq_pool_mutex, and allows read
763 * access under RCU read lock. As such, this function should be
764 * called under wq_pool_mutex or inside of a rcu_read_lock() region.
766 * All fields of the returned pool are accessible as long as the above
767 * mentioned locking is in effect. If the returned pool needs to be used
768 * beyond the critical section, the caller is responsible for ensuring the
769 * returned pool is and stays online.
771 * Return: The worker_pool @work was last associated with. %NULL if none.
773 static struct worker_pool *get_work_pool(struct work_struct *work)
775 unsigned long data = atomic_long_read(&work->data);
778 assert_rcu_or_pool_mutex();
780 if (data & WORK_STRUCT_PWQ)
781 return work_struct_pwq(data)->pool;
783 pool_id = data >> WORK_OFFQ_POOL_SHIFT;
784 if (pool_id == WORK_OFFQ_POOL_NONE)
787 return idr_find(&worker_pool_idr, pool_id);
791 * get_work_pool_id - return the worker pool ID a given work is associated with
792 * @work: the work item of interest
794 * Return: The worker_pool ID @work was last associated with.
795 * %WORK_OFFQ_POOL_NONE if none.
797 static int get_work_pool_id(struct work_struct *work)
799 unsigned long data = atomic_long_read(&work->data);
801 if (data & WORK_STRUCT_PWQ)
802 return work_struct_pwq(data)->pool->id;
804 return data >> WORK_OFFQ_POOL_SHIFT;
807 static void mark_work_canceling(struct work_struct *work)
809 unsigned long pool_id = get_work_pool_id(work);
811 pool_id <<= WORK_OFFQ_POOL_SHIFT;
812 set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
815 static bool work_is_canceling(struct work_struct *work)
817 unsigned long data = atomic_long_read(&work->data);
819 return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
823 * Policy functions. These define the policies on how the global worker
824 * pools are managed. Unless noted otherwise, these functions assume that
825 * they're being called with pool->lock held.
828 static bool __need_more_worker(struct worker_pool *pool)
830 return !pool->nr_running;
834 * Need to wake up a worker? Called from anything but currently
837 * Note that, because unbound workers never contribute to nr_running, this
838 * function will always return %true for unbound pools as long as the
839 * worklist isn't empty.
841 static bool need_more_worker(struct worker_pool *pool)
843 return !list_empty(&pool->worklist) && __need_more_worker(pool);
846 /* Can I start working? Called from busy but !running workers. */
847 static bool may_start_working(struct worker_pool *pool)
849 return pool->nr_idle;
852 /* Do I need to keep working? Called from currently running workers. */
853 static bool keep_working(struct worker_pool *pool)
855 return !list_empty(&pool->worklist) && (pool->nr_running <= 1);
858 /* Do we need a new worker? Called from manager. */
859 static bool need_to_create_worker(struct worker_pool *pool)
861 return need_more_worker(pool) && !may_start_working(pool);
864 /* Do we have too many workers and should some go away? */
865 static bool too_many_workers(struct worker_pool *pool)
867 bool managing = pool->flags & POOL_MANAGER_ACTIVE;
868 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
869 int nr_busy = pool->nr_workers - nr_idle;
871 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
878 /* Return the first idle worker. Called with pool->lock held. */
879 static struct worker *first_idle_worker(struct worker_pool *pool)
881 if (unlikely(list_empty(&pool->idle_list)))
884 return list_first_entry(&pool->idle_list, struct worker, entry);
888 * wake_up_worker - wake up an idle worker
889 * @pool: worker pool to wake worker from
891 * Wake up the first idle worker of @pool.
894 * raw_spin_lock_irq(pool->lock).
896 static void wake_up_worker(struct worker_pool *pool)
898 struct worker *worker = first_idle_worker(pool);
901 wake_up_process(worker->task);
905 * worker_set_flags - set worker flags and adjust nr_running accordingly
907 * @flags: flags to set
909 * Set @flags in @worker->flags and adjust nr_running accordingly.
912 * raw_spin_lock_irq(pool->lock)
914 static inline void worker_set_flags(struct worker *worker, unsigned int flags)
916 struct worker_pool *pool = worker->pool;
918 WARN_ON_ONCE(worker->task != current);
920 /* If transitioning into NOT_RUNNING, adjust nr_running. */
921 if ((flags & WORKER_NOT_RUNNING) &&
922 !(worker->flags & WORKER_NOT_RUNNING)) {
926 worker->flags |= flags;
930 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
932 * @flags: flags to clear
934 * Clear @flags in @worker->flags and adjust nr_running accordingly.
937 * raw_spin_lock_irq(pool->lock)
939 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
941 struct worker_pool *pool = worker->pool;
942 unsigned int oflags = worker->flags;
944 WARN_ON_ONCE(worker->task != current);
946 worker->flags &= ~flags;
949 * If transitioning out of NOT_RUNNING, increment nr_running. Note
950 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
951 * of multiple flags, not a single flag.
953 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
954 if (!(worker->flags & WORKER_NOT_RUNNING))
958 #ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
961 * Concurrency-managed per-cpu work items that hog CPU for longer than
962 * wq_cpu_intensive_thresh_us trigger the automatic CPU_INTENSIVE mechanism,
963 * which prevents them from stalling other concurrency-managed work items. If a
964 * work function keeps triggering this mechanism, it's likely that the work item
965 * should be using an unbound workqueue instead.
967 * wq_cpu_intensive_report() tracks work functions which trigger such conditions
968 * and report them so that they can be examined and converted to use unbound
969 * workqueues as appropriate. To avoid flooding the console, each violating work
970 * function is tracked and reported with exponential backoff.
972 #define WCI_MAX_ENTS 128
977 struct hlist_node hash_node;
980 static struct wci_ent wci_ents[WCI_MAX_ENTS];
981 static int wci_nr_ents;
982 static DEFINE_RAW_SPINLOCK(wci_lock);
983 static DEFINE_HASHTABLE(wci_hash, ilog2(WCI_MAX_ENTS));
985 static struct wci_ent *wci_find_ent(work_func_t func)
989 hash_for_each_possible_rcu(wci_hash, ent, hash_node,
990 (unsigned long)func) {
991 if (ent->func == func)
997 static void wq_cpu_intensive_report(work_func_t func)
1002 ent = wci_find_ent(func);
1007 * Start reporting from the fourth time and back off
1010 cnt = atomic64_inc_return_relaxed(&ent->cnt);
1011 if (cnt >= 4 && is_power_of_2(cnt))
1012 printk_deferred(KERN_WARNING "workqueue: %ps hogged CPU for >%luus %llu times, consider switching to WQ_UNBOUND\n",
1013 ent->func, wq_cpu_intensive_thresh_us,
1014 atomic64_read(&ent->cnt));
1019 * @func is a new violation. Allocate a new entry for it. If wcn_ents[]
1020 * is exhausted, something went really wrong and we probably made enough
1023 if (wci_nr_ents >= WCI_MAX_ENTS)
1026 raw_spin_lock(&wci_lock);
1028 if (wci_nr_ents >= WCI_MAX_ENTS) {
1029 raw_spin_unlock(&wci_lock);
1033 if (wci_find_ent(func)) {
1034 raw_spin_unlock(&wci_lock);
1038 ent = &wci_ents[wci_nr_ents++];
1040 atomic64_set(&ent->cnt, 1);
1041 hash_add_rcu(wci_hash, &ent->hash_node, (unsigned long)func);
1043 raw_spin_unlock(&wci_lock);
1046 #else /* CONFIG_WQ_CPU_INTENSIVE_REPORT */
1047 static void wq_cpu_intensive_report(work_func_t func) {}
1048 #endif /* CONFIG_WQ_CPU_INTENSIVE_REPORT */
1051 * wq_worker_running - a worker is running again
1052 * @task: task waking up
1054 * This function is called when a worker returns from schedule()
1056 void wq_worker_running(struct task_struct *task)
1058 struct worker *worker = kthread_data(task);
1060 if (!READ_ONCE(worker->sleeping))
1064 * If preempted by unbind_workers() between the WORKER_NOT_RUNNING check
1065 * and the nr_running increment below, we may ruin the nr_running reset
1066 * and leave with an unexpected pool->nr_running == 1 on the newly unbound
1067 * pool. Protect against such race.
1070 if (!(worker->flags & WORKER_NOT_RUNNING))
1071 worker->pool->nr_running++;
1075 * CPU intensive auto-detection cares about how long a work item hogged
1076 * CPU without sleeping. Reset the starting timestamp on wakeup.
1078 worker->current_at = worker->task->se.sum_exec_runtime;
1080 WRITE_ONCE(worker->sleeping, 0);
1084 * wq_worker_sleeping - a worker is going to sleep
1085 * @task: task going to sleep
1087 * This function is called from schedule() when a busy worker is
1090 void wq_worker_sleeping(struct task_struct *task)
1092 struct worker *worker = kthread_data(task);
1093 struct worker_pool *pool;
1096 * Rescuers, which may not have all the fields set up like normal
1097 * workers, also reach here, let's not access anything before
1098 * checking NOT_RUNNING.
1100 if (worker->flags & WORKER_NOT_RUNNING)
1103 pool = worker->pool;
1105 /* Return if preempted before wq_worker_running() was reached */
1106 if (READ_ONCE(worker->sleeping))
1109 WRITE_ONCE(worker->sleeping, 1);
1110 raw_spin_lock_irq(&pool->lock);
1113 * Recheck in case unbind_workers() preempted us. We don't
1114 * want to decrement nr_running after the worker is unbound
1115 * and nr_running has been reset.
1117 if (worker->flags & WORKER_NOT_RUNNING) {
1118 raw_spin_unlock_irq(&pool->lock);
1123 if (need_more_worker(pool)) {
1124 worker->current_pwq->stats[PWQ_STAT_CM_WAKEUP]++;
1125 wake_up_worker(pool);
1127 raw_spin_unlock_irq(&pool->lock);
1131 * wq_worker_tick - a scheduler tick occurred while a kworker is running
1132 * @task: task currently running
1134 * Called from scheduler_tick(). We're in the IRQ context and the current
1135 * worker's fields which follow the 'K' locking rule can be accessed safely.
1137 void wq_worker_tick(struct task_struct *task)
1139 struct worker *worker = kthread_data(task);
1140 struct pool_workqueue *pwq = worker->current_pwq;
1141 struct worker_pool *pool = worker->pool;
1146 pwq->stats[PWQ_STAT_CPU_TIME] += TICK_USEC;
1148 if (!wq_cpu_intensive_thresh_us)
1152 * If the current worker is concurrency managed and hogged the CPU for
1153 * longer than wq_cpu_intensive_thresh_us, it's automatically marked
1154 * CPU_INTENSIVE to avoid stalling other concurrency-managed work items.
1156 * Set @worker->sleeping means that @worker is in the process of
1157 * switching out voluntarily and won't be contributing to
1158 * @pool->nr_running until it wakes up. As wq_worker_sleeping() also
1159 * decrements ->nr_running, setting CPU_INTENSIVE here can lead to
1160 * double decrements. The task is releasing the CPU anyway. Let's skip.
1161 * We probably want to make this prettier in the future.
1163 if ((worker->flags & WORKER_NOT_RUNNING) || READ_ONCE(worker->sleeping) ||
1164 worker->task->se.sum_exec_runtime - worker->current_at <
1165 wq_cpu_intensive_thresh_us * NSEC_PER_USEC)
1168 raw_spin_lock(&pool->lock);
1170 worker_set_flags(worker, WORKER_CPU_INTENSIVE);
1171 wq_cpu_intensive_report(worker->current_func);
1172 pwq->stats[PWQ_STAT_CPU_INTENSIVE]++;
1174 if (need_more_worker(pool)) {
1175 pwq->stats[PWQ_STAT_CM_WAKEUP]++;
1176 wake_up_worker(pool);
1179 raw_spin_unlock(&pool->lock);
1183 * wq_worker_last_func - retrieve worker's last work function
1184 * @task: Task to retrieve last work function of.
1186 * Determine the last function a worker executed. This is called from
1187 * the scheduler to get a worker's last known identity.
1190 * raw_spin_lock_irq(rq->lock)
1192 * This function is called during schedule() when a kworker is going
1193 * to sleep. It's used by psi to identify aggregation workers during
1194 * dequeuing, to allow periodic aggregation to shut-off when that
1195 * worker is the last task in the system or cgroup to go to sleep.
1197 * As this function doesn't involve any workqueue-related locking, it
1198 * only returns stable values when called from inside the scheduler's
1199 * queuing and dequeuing paths, when @task, which must be a kworker,
1200 * is guaranteed to not be processing any works.
1203 * The last work function %current executed as a worker, NULL if it
1204 * hasn't executed any work yet.
1206 work_func_t wq_worker_last_func(struct task_struct *task)
1208 struct worker *worker = kthread_data(task);
1210 return worker->last_func;
1214 * find_worker_executing_work - find worker which is executing a work
1215 * @pool: pool of interest
1216 * @work: work to find worker for
1218 * Find a worker which is executing @work on @pool by searching
1219 * @pool->busy_hash which is keyed by the address of @work. For a worker
1220 * to match, its current execution should match the address of @work and
1221 * its work function. This is to avoid unwanted dependency between
1222 * unrelated work executions through a work item being recycled while still
1225 * This is a bit tricky. A work item may be freed once its execution
1226 * starts and nothing prevents the freed area from being recycled for
1227 * another work item. If the same work item address ends up being reused
1228 * before the original execution finishes, workqueue will identify the
1229 * recycled work item as currently executing and make it wait until the
1230 * current execution finishes, introducing an unwanted dependency.
1232 * This function checks the work item address and work function to avoid
1233 * false positives. Note that this isn't complete as one may construct a
1234 * work function which can introduce dependency onto itself through a
1235 * recycled work item. Well, if somebody wants to shoot oneself in the
1236 * foot that badly, there's only so much we can do, and if such deadlock
1237 * actually occurs, it should be easy to locate the culprit work function.
1240 * raw_spin_lock_irq(pool->lock).
1243 * Pointer to worker which is executing @work if found, %NULL
1246 static struct worker *find_worker_executing_work(struct worker_pool *pool,
1247 struct work_struct *work)
1249 struct worker *worker;
1251 hash_for_each_possible(pool->busy_hash, worker, hentry,
1252 (unsigned long)work)
1253 if (worker->current_work == work &&
1254 worker->current_func == work->func)
1261 * move_linked_works - move linked works to a list
1262 * @work: start of series of works to be scheduled
1263 * @head: target list to append @work to
1264 * @nextp: out parameter for nested worklist walking
1266 * Schedule linked works starting from @work to @head. Work series to
1267 * be scheduled starts at @work and includes any consecutive work with
1268 * WORK_STRUCT_LINKED set in its predecessor.
1270 * If @nextp is not NULL, it's updated to point to the next work of
1271 * the last scheduled work. This allows move_linked_works() to be
1272 * nested inside outer list_for_each_entry_safe().
1275 * raw_spin_lock_irq(pool->lock).
1277 static void move_linked_works(struct work_struct *work, struct list_head *head,
1278 struct work_struct **nextp)
1280 struct work_struct *n;
1283 * Linked worklist will always end before the end of the list,
1284 * use NULL for list head.
1286 list_for_each_entry_safe_from(work, n, NULL, entry) {
1287 list_move_tail(&work->entry, head);
1288 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1293 * If we're already inside safe list traversal and have moved
1294 * multiple works to the scheduled queue, the next position
1295 * needs to be updated.
1302 * get_pwq - get an extra reference on the specified pool_workqueue
1303 * @pwq: pool_workqueue to get
1305 * Obtain an extra reference on @pwq. The caller should guarantee that
1306 * @pwq has positive refcnt and be holding the matching pool->lock.
1308 static void get_pwq(struct pool_workqueue *pwq)
1310 lockdep_assert_held(&pwq->pool->lock);
1311 WARN_ON_ONCE(pwq->refcnt <= 0);
1316 * put_pwq - put a pool_workqueue reference
1317 * @pwq: pool_workqueue to put
1319 * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
1320 * destruction. The caller should be holding the matching pool->lock.
1322 static void put_pwq(struct pool_workqueue *pwq)
1324 lockdep_assert_held(&pwq->pool->lock);
1325 if (likely(--pwq->refcnt))
1327 if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
1330 * @pwq can't be released under pool->lock, bounce to
1331 * pwq_unbound_release_workfn(). This never recurses on the same
1332 * pool->lock as this path is taken only for unbound workqueues and
1333 * the release work item is scheduled on a per-cpu workqueue. To
1334 * avoid lockdep warning, unbound pool->locks are given lockdep
1335 * subclass of 1 in get_unbound_pool().
1337 schedule_work(&pwq->unbound_release_work);
1341 * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1342 * @pwq: pool_workqueue to put (can be %NULL)
1344 * put_pwq() with locking. This function also allows %NULL @pwq.
1346 static void put_pwq_unlocked(struct pool_workqueue *pwq)
1350 * As both pwqs and pools are RCU protected, the
1351 * following lock operations are safe.
1353 raw_spin_lock_irq(&pwq->pool->lock);
1355 raw_spin_unlock_irq(&pwq->pool->lock);
1359 static void pwq_activate_inactive_work(struct work_struct *work)
1361 struct pool_workqueue *pwq = get_work_pwq(work);
1363 trace_workqueue_activate_work(work);
1364 if (list_empty(&pwq->pool->worklist))
1365 pwq->pool->watchdog_ts = jiffies;
1366 move_linked_works(work, &pwq->pool->worklist, NULL);
1367 __clear_bit(WORK_STRUCT_INACTIVE_BIT, work_data_bits(work));
1371 static void pwq_activate_first_inactive(struct pool_workqueue *pwq)
1373 struct work_struct *work = list_first_entry(&pwq->inactive_works,
1374 struct work_struct, entry);
1376 pwq_activate_inactive_work(work);
1380 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1381 * @pwq: pwq of interest
1382 * @work_data: work_data of work which left the queue
1384 * A work either has completed or is removed from pending queue,
1385 * decrement nr_in_flight of its pwq and handle workqueue flushing.
1388 * raw_spin_lock_irq(pool->lock).
1390 static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data)
1392 int color = get_work_color(work_data);
1394 if (!(work_data & WORK_STRUCT_INACTIVE)) {
1396 if (!list_empty(&pwq->inactive_works)) {
1397 /* one down, submit an inactive one */
1398 if (pwq->nr_active < pwq->max_active)
1399 pwq_activate_first_inactive(pwq);
1403 pwq->nr_in_flight[color]--;
1405 /* is flush in progress and are we at the flushing tip? */
1406 if (likely(pwq->flush_color != color))
1409 /* are there still in-flight works? */
1410 if (pwq->nr_in_flight[color])
1413 /* this pwq is done, clear flush_color */
1414 pwq->flush_color = -1;
1417 * If this was the last pwq, wake up the first flusher. It
1418 * will handle the rest.
1420 if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1421 complete(&pwq->wq->first_flusher->done);
1427 * try_to_grab_pending - steal work item from worklist and disable irq
1428 * @work: work item to steal
1429 * @is_dwork: @work is a delayed_work
1430 * @flags: place to store irq state
1432 * Try to grab PENDING bit of @work. This function can handle @work in any
1433 * stable state - idle, on timer or on worklist.
1437 * ======== ================================================================
1438 * 1 if @work was pending and we successfully stole PENDING
1439 * 0 if @work was idle and we claimed PENDING
1440 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1441 * -ENOENT if someone else is canceling @work, this state may persist
1442 * for arbitrarily long
1443 * ======== ================================================================
1446 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1447 * interrupted while holding PENDING and @work off queue, irq must be
1448 * disabled on entry. This, combined with delayed_work->timer being
1449 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1451 * On successful return, >= 0, irq is disabled and the caller is
1452 * responsible for releasing it using local_irq_restore(*@flags).
1454 * This function is safe to call from any context including IRQ handler.
1456 static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1457 unsigned long *flags)
1459 struct worker_pool *pool;
1460 struct pool_workqueue *pwq;
1462 local_irq_save(*flags);
1464 /* try to steal the timer if it exists */
1466 struct delayed_work *dwork = to_delayed_work(work);
1469 * dwork->timer is irqsafe. If del_timer() fails, it's
1470 * guaranteed that the timer is not queued anywhere and not
1471 * running on the local CPU.
1473 if (likely(del_timer(&dwork->timer)))
1477 /* try to claim PENDING the normal way */
1478 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1483 * The queueing is in progress, or it is already queued. Try to
1484 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1486 pool = get_work_pool(work);
1490 raw_spin_lock(&pool->lock);
1492 * work->data is guaranteed to point to pwq only while the work
1493 * item is queued on pwq->wq, and both updating work->data to point
1494 * to pwq on queueing and to pool on dequeueing are done under
1495 * pwq->pool->lock. This in turn guarantees that, if work->data
1496 * points to pwq which is associated with a locked pool, the work
1497 * item is currently queued on that pool.
1499 pwq = get_work_pwq(work);
1500 if (pwq && pwq->pool == pool) {
1501 debug_work_deactivate(work);
1504 * A cancelable inactive work item must be in the
1505 * pwq->inactive_works since a queued barrier can't be
1506 * canceled (see the comments in insert_wq_barrier()).
1508 * An inactive work item cannot be grabbed directly because
1509 * it might have linked barrier work items which, if left
1510 * on the inactive_works list, will confuse pwq->nr_active
1511 * management later on and cause stall. Make sure the work
1512 * item is activated before grabbing.
1514 if (*work_data_bits(work) & WORK_STRUCT_INACTIVE)
1515 pwq_activate_inactive_work(work);
1517 list_del_init(&work->entry);
1518 pwq_dec_nr_in_flight(pwq, *work_data_bits(work));
1520 /* work->data points to pwq iff queued, point to pool */
1521 set_work_pool_and_keep_pending(work, pool->id);
1523 raw_spin_unlock(&pool->lock);
1527 raw_spin_unlock(&pool->lock);
1530 local_irq_restore(*flags);
1531 if (work_is_canceling(work))
1538 * insert_work - insert a work into a pool
1539 * @pwq: pwq @work belongs to
1540 * @work: work to insert
1541 * @head: insertion point
1542 * @extra_flags: extra WORK_STRUCT_* flags to set
1544 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
1545 * work_struct flags.
1548 * raw_spin_lock_irq(pool->lock).
1550 static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1551 struct list_head *head, unsigned int extra_flags)
1553 struct worker_pool *pool = pwq->pool;
1555 /* record the work call stack in order to print it in KASAN reports */
1556 kasan_record_aux_stack_noalloc(work);
1558 /* we own @work, set data and link */
1559 set_work_pwq(work, pwq, extra_flags);
1560 list_add_tail(&work->entry, head);
1563 if (__need_more_worker(pool))
1564 wake_up_worker(pool);
1568 * Test whether @work is being queued from another work executing on the
1571 static bool is_chained_work(struct workqueue_struct *wq)
1573 struct worker *worker;
1575 worker = current_wq_worker();
1577 * Return %true iff I'm a worker executing a work item on @wq. If
1578 * I'm @worker, it's safe to dereference it without locking.
1580 return worker && worker->current_pwq->wq == wq;
1584 * When queueing an unbound work item to a wq, prefer local CPU if allowed
1585 * by wq_unbound_cpumask. Otherwise, round robin among the allowed ones to
1586 * avoid perturbing sensitive tasks.
1588 static int wq_select_unbound_cpu(int cpu)
1592 if (likely(!wq_debug_force_rr_cpu)) {
1593 if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
1596 pr_warn_once("workqueue: round-robin CPU selection forced, expect performance impact\n");
1599 if (cpumask_empty(wq_unbound_cpumask))
1602 new_cpu = __this_cpu_read(wq_rr_cpu_last);
1603 new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
1604 if (unlikely(new_cpu >= nr_cpu_ids)) {
1605 new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
1606 if (unlikely(new_cpu >= nr_cpu_ids))
1609 __this_cpu_write(wq_rr_cpu_last, new_cpu);
1614 static void __queue_work(int cpu, struct workqueue_struct *wq,
1615 struct work_struct *work)
1617 struct pool_workqueue *pwq;
1618 struct worker_pool *last_pool;
1619 struct list_head *worklist;
1620 unsigned int work_flags;
1621 unsigned int req_cpu = cpu;
1624 * While a work item is PENDING && off queue, a task trying to
1625 * steal the PENDING will busy-loop waiting for it to either get
1626 * queued or lose PENDING. Grabbing PENDING and queueing should
1627 * happen with IRQ disabled.
1629 lockdep_assert_irqs_disabled();
1633 * For a draining wq, only works from the same workqueue are
1634 * allowed. The __WQ_DESTROYING helps to spot the issue that
1635 * queues a new work item to a wq after destroy_workqueue(wq).
1637 if (unlikely(wq->flags & (__WQ_DESTROYING | __WQ_DRAINING) &&
1638 WARN_ON_ONCE(!is_chained_work(wq))))
1642 /* pwq which will be used unless @work is executing elsewhere */
1643 if (wq->flags & WQ_UNBOUND) {
1644 if (req_cpu == WORK_CPU_UNBOUND)
1645 cpu = wq_select_unbound_cpu(raw_smp_processor_id());
1646 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1648 if (req_cpu == WORK_CPU_UNBOUND)
1649 cpu = raw_smp_processor_id();
1650 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1654 * If @work was previously on a different pool, it might still be
1655 * running there, in which case the work needs to be queued on that
1656 * pool to guarantee non-reentrancy.
1658 last_pool = get_work_pool(work);
1659 if (last_pool && last_pool != pwq->pool) {
1660 struct worker *worker;
1662 raw_spin_lock(&last_pool->lock);
1664 worker = find_worker_executing_work(last_pool, work);
1666 if (worker && worker->current_pwq->wq == wq) {
1667 pwq = worker->current_pwq;
1669 /* meh... not running there, queue here */
1670 raw_spin_unlock(&last_pool->lock);
1671 raw_spin_lock(&pwq->pool->lock);
1674 raw_spin_lock(&pwq->pool->lock);
1678 * pwq is determined and locked. For unbound pools, we could have
1679 * raced with pwq release and it could already be dead. If its
1680 * refcnt is zero, repeat pwq selection. Note that pwqs never die
1681 * without another pwq replacing it in the numa_pwq_tbl or while
1682 * work items are executing on it, so the retrying is guaranteed to
1683 * make forward-progress.
1685 if (unlikely(!pwq->refcnt)) {
1686 if (wq->flags & WQ_UNBOUND) {
1687 raw_spin_unlock(&pwq->pool->lock);
1692 WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
1696 /* pwq determined, queue */
1697 trace_workqueue_queue_work(req_cpu, pwq, work);
1699 if (WARN_ON(!list_empty(&work->entry)))
1702 pwq->nr_in_flight[pwq->work_color]++;
1703 work_flags = work_color_to_flags(pwq->work_color);
1705 if (likely(pwq->nr_active < pwq->max_active)) {
1706 trace_workqueue_activate_work(work);
1708 worklist = &pwq->pool->worklist;
1709 if (list_empty(worklist))
1710 pwq->pool->watchdog_ts = jiffies;
1712 work_flags |= WORK_STRUCT_INACTIVE;
1713 worklist = &pwq->inactive_works;
1716 debug_work_activate(work);
1717 insert_work(pwq, work, worklist, work_flags);
1720 raw_spin_unlock(&pwq->pool->lock);
1725 * queue_work_on - queue work on specific cpu
1726 * @cpu: CPU number to execute work on
1727 * @wq: workqueue to use
1728 * @work: work to queue
1730 * We queue the work to a specific CPU, the caller must ensure it
1731 * can't go away. Callers that fail to ensure that the specified
1732 * CPU cannot go away will execute on a randomly chosen CPU.
1733 * But note well that callers specifying a CPU that never has been
1734 * online will get a splat.
1736 * Return: %false if @work was already on a queue, %true otherwise.
1738 bool queue_work_on(int cpu, struct workqueue_struct *wq,
1739 struct work_struct *work)
1742 unsigned long flags;
1744 local_irq_save(flags);
1746 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1747 __queue_work(cpu, wq, work);
1751 local_irq_restore(flags);
1754 EXPORT_SYMBOL(queue_work_on);
1757 * workqueue_select_cpu_near - Select a CPU based on NUMA node
1758 * @node: NUMA node ID that we want to select a CPU from
1760 * This function will attempt to find a "random" cpu available on a given
1761 * node. If there are no CPUs available on the given node it will return
1762 * WORK_CPU_UNBOUND indicating that we should just schedule to any
1763 * available CPU if we need to schedule this work.
1765 static int workqueue_select_cpu_near(int node)
1769 /* No point in doing this if NUMA isn't enabled for workqueues */
1770 if (!wq_numa_enabled)
1771 return WORK_CPU_UNBOUND;
1773 /* Delay binding to CPU if node is not valid or online */
1774 if (node < 0 || node >= MAX_NUMNODES || !node_online(node))
1775 return WORK_CPU_UNBOUND;
1777 /* Use local node/cpu if we are already there */
1778 cpu = raw_smp_processor_id();
1779 if (node == cpu_to_node(cpu))
1782 /* Use "random" otherwise know as "first" online CPU of node */
1783 cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
1785 /* If CPU is valid return that, otherwise just defer */
1786 return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND;
1790 * queue_work_node - queue work on a "random" cpu for a given NUMA node
1791 * @node: NUMA node that we are targeting the work for
1792 * @wq: workqueue to use
1793 * @work: work to queue
1795 * We queue the work to a "random" CPU within a given NUMA node. The basic
1796 * idea here is to provide a way to somehow associate work with a given
1799 * This function will only make a best effort attempt at getting this onto
1800 * the right NUMA node. If no node is requested or the requested node is
1801 * offline then we just fall back to standard queue_work behavior.
1803 * Currently the "random" CPU ends up being the first available CPU in the
1804 * intersection of cpu_online_mask and the cpumask of the node, unless we
1805 * are running on the node. In that case we just use the current CPU.
1807 * Return: %false if @work was already on a queue, %true otherwise.
1809 bool queue_work_node(int node, struct workqueue_struct *wq,
1810 struct work_struct *work)
1812 unsigned long flags;
1816 * This current implementation is specific to unbound workqueues.
1817 * Specifically we only return the first available CPU for a given
1818 * node instead of cycling through individual CPUs within the node.
1820 * If this is used with a per-cpu workqueue then the logic in
1821 * workqueue_select_cpu_near would need to be updated to allow for
1822 * some round robin type logic.
1824 WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND));
1826 local_irq_save(flags);
1828 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1829 int cpu = workqueue_select_cpu_near(node);
1831 __queue_work(cpu, wq, work);
1835 local_irq_restore(flags);
1838 EXPORT_SYMBOL_GPL(queue_work_node);
1840 void delayed_work_timer_fn(struct timer_list *t)
1842 struct delayed_work *dwork = from_timer(dwork, t, timer);
1844 /* should have been called from irqsafe timer with irq already off */
1845 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
1847 EXPORT_SYMBOL(delayed_work_timer_fn);
1849 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
1850 struct delayed_work *dwork, unsigned long delay)
1852 struct timer_list *timer = &dwork->timer;
1853 struct work_struct *work = &dwork->work;
1856 WARN_ON_ONCE(timer->function != delayed_work_timer_fn);
1857 WARN_ON_ONCE(timer_pending(timer));
1858 WARN_ON_ONCE(!list_empty(&work->entry));
1861 * If @delay is 0, queue @dwork->work immediately. This is for
1862 * both optimization and correctness. The earliest @timer can
1863 * expire is on the closest next tick and delayed_work users depend
1864 * on that there's no such delay when @delay is 0.
1867 __queue_work(cpu, wq, &dwork->work);
1873 timer->expires = jiffies + delay;
1875 if (unlikely(cpu != WORK_CPU_UNBOUND))
1876 add_timer_on(timer, cpu);
1882 * queue_delayed_work_on - queue work on specific CPU after delay
1883 * @cpu: CPU number to execute work on
1884 * @wq: workqueue to use
1885 * @dwork: work to queue
1886 * @delay: number of jiffies to wait before queueing
1888 * Return: %false if @work was already on a queue, %true otherwise. If
1889 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1892 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1893 struct delayed_work *dwork, unsigned long delay)
1895 struct work_struct *work = &dwork->work;
1897 unsigned long flags;
1899 /* read the comment in __queue_work() */
1900 local_irq_save(flags);
1902 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1903 __queue_delayed_work(cpu, wq, dwork, delay);
1907 local_irq_restore(flags);
1910 EXPORT_SYMBOL(queue_delayed_work_on);
1913 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1914 * @cpu: CPU number to execute work on
1915 * @wq: workqueue to use
1916 * @dwork: work to queue
1917 * @delay: number of jiffies to wait before queueing
1919 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1920 * modify @dwork's timer so that it expires after @delay. If @delay is
1921 * zero, @work is guaranteed to be scheduled immediately regardless of its
1924 * Return: %false if @dwork was idle and queued, %true if @dwork was
1925 * pending and its timer was modified.
1927 * This function is safe to call from any context including IRQ handler.
1928 * See try_to_grab_pending() for details.
1930 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
1931 struct delayed_work *dwork, unsigned long delay)
1933 unsigned long flags;
1937 ret = try_to_grab_pending(&dwork->work, true, &flags);
1938 } while (unlikely(ret == -EAGAIN));
1940 if (likely(ret >= 0)) {
1941 __queue_delayed_work(cpu, wq, dwork, delay);
1942 local_irq_restore(flags);
1945 /* -ENOENT from try_to_grab_pending() becomes %true */
1948 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
1950 static void rcu_work_rcufn(struct rcu_head *rcu)
1952 struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
1954 /* read the comment in __queue_work() */
1955 local_irq_disable();
1956 __queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
1961 * queue_rcu_work - queue work after a RCU grace period
1962 * @wq: workqueue to use
1963 * @rwork: work to queue
1965 * Return: %false if @rwork was already pending, %true otherwise. Note
1966 * that a full RCU grace period is guaranteed only after a %true return.
1967 * While @rwork is guaranteed to be executed after a %false return, the
1968 * execution may happen before a full RCU grace period has passed.
1970 bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
1972 struct work_struct *work = &rwork->work;
1974 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1976 call_rcu_hurry(&rwork->rcu, rcu_work_rcufn);
1982 EXPORT_SYMBOL(queue_rcu_work);
1985 * worker_enter_idle - enter idle state
1986 * @worker: worker which is entering idle state
1988 * @worker is entering idle state. Update stats and idle timer if
1992 * raw_spin_lock_irq(pool->lock).
1994 static void worker_enter_idle(struct worker *worker)
1996 struct worker_pool *pool = worker->pool;
1998 if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
1999 WARN_ON_ONCE(!list_empty(&worker->entry) &&
2000 (worker->hentry.next || worker->hentry.pprev)))
2003 /* can't use worker_set_flags(), also called from create_worker() */
2004 worker->flags |= WORKER_IDLE;
2006 worker->last_active = jiffies;
2008 /* idle_list is LIFO */
2009 list_add(&worker->entry, &pool->idle_list);
2011 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
2012 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
2014 /* Sanity check nr_running. */
2015 WARN_ON_ONCE(pool->nr_workers == pool->nr_idle && pool->nr_running);
2019 * worker_leave_idle - leave idle state
2020 * @worker: worker which is leaving idle state
2022 * @worker is leaving idle state. Update stats.
2025 * raw_spin_lock_irq(pool->lock).
2027 static void worker_leave_idle(struct worker *worker)
2029 struct worker_pool *pool = worker->pool;
2031 if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
2033 worker_clr_flags(worker, WORKER_IDLE);
2035 list_del_init(&worker->entry);
2038 static struct worker *alloc_worker(int node)
2040 struct worker *worker;
2042 worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
2044 INIT_LIST_HEAD(&worker->entry);
2045 INIT_LIST_HEAD(&worker->scheduled);
2046 INIT_LIST_HEAD(&worker->node);
2047 /* on creation a worker is in !idle && prep state */
2048 worker->flags = WORKER_PREP;
2054 * worker_attach_to_pool() - attach a worker to a pool
2055 * @worker: worker to be attached
2056 * @pool: the target pool
2058 * Attach @worker to @pool. Once attached, the %WORKER_UNBOUND flag and
2059 * cpu-binding of @worker are kept coordinated with the pool across
2062 static void worker_attach_to_pool(struct worker *worker,
2063 struct worker_pool *pool)
2065 mutex_lock(&wq_pool_attach_mutex);
2068 * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains
2069 * stable across this function. See the comments above the flag
2070 * definition for details.
2072 if (pool->flags & POOL_DISASSOCIATED)
2073 worker->flags |= WORKER_UNBOUND;
2075 kthread_set_per_cpu(worker->task, pool->cpu);
2077 if (worker->rescue_wq)
2078 set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
2080 list_add_tail(&worker->node, &pool->workers);
2081 worker->pool = pool;
2083 mutex_unlock(&wq_pool_attach_mutex);
2087 * worker_detach_from_pool() - detach a worker from its pool
2088 * @worker: worker which is attached to its pool
2090 * Undo the attaching which had been done in worker_attach_to_pool(). The
2091 * caller worker shouldn't access to the pool after detached except it has
2092 * other reference to the pool.
2094 static void worker_detach_from_pool(struct worker *worker)
2096 struct worker_pool *pool = worker->pool;
2097 struct completion *detach_completion = NULL;
2099 mutex_lock(&wq_pool_attach_mutex);
2101 kthread_set_per_cpu(worker->task, -1);
2102 list_del(&worker->node);
2103 worker->pool = NULL;
2105 if (list_empty(&pool->workers) && list_empty(&pool->dying_workers))
2106 detach_completion = pool->detach_completion;
2107 mutex_unlock(&wq_pool_attach_mutex);
2109 /* clear leftover flags without pool->lock after it is detached */
2110 worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
2112 if (detach_completion)
2113 complete(detach_completion);
2117 * create_worker - create a new workqueue worker
2118 * @pool: pool the new worker will belong to
2120 * Create and start a new worker which is attached to @pool.
2123 * Might sleep. Does GFP_KERNEL allocations.
2126 * Pointer to the newly created worker.
2128 static struct worker *create_worker(struct worker_pool *pool)
2130 struct worker *worker;
2134 /* ID is needed to determine kthread name */
2135 id = ida_alloc(&pool->worker_ida, GFP_KERNEL);
2137 pr_err_once("workqueue: Failed to allocate a worker ID: %pe\n",
2142 worker = alloc_worker(pool->node);
2144 pr_err_once("workqueue: Failed to allocate a worker\n");
2151 snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
2152 pool->attrs->nice < 0 ? "H" : "");
2154 snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
2156 worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
2157 "kworker/%s", id_buf);
2158 if (IS_ERR(worker->task)) {
2159 if (PTR_ERR(worker->task) == -EINTR) {
2160 pr_err("workqueue: Interrupted when creating a worker thread \"kworker/%s\"\n",
2163 pr_err_once("workqueue: Failed to create a worker thread: %pe",
2169 set_user_nice(worker->task, pool->attrs->nice);
2170 kthread_bind_mask(worker->task, pool->attrs->cpumask);
2172 /* successful, attach the worker to the pool */
2173 worker_attach_to_pool(worker, pool);
2175 /* start the newly created worker */
2176 raw_spin_lock_irq(&pool->lock);
2177 worker->pool->nr_workers++;
2178 worker_enter_idle(worker);
2179 wake_up_process(worker->task);
2180 raw_spin_unlock_irq(&pool->lock);
2185 ida_free(&pool->worker_ida, id);
2190 static void unbind_worker(struct worker *worker)
2192 lockdep_assert_held(&wq_pool_attach_mutex);
2194 kthread_set_per_cpu(worker->task, -1);
2195 if (cpumask_intersects(wq_unbound_cpumask, cpu_active_mask))
2196 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, wq_unbound_cpumask) < 0);
2198 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, cpu_possible_mask) < 0);
2201 static void wake_dying_workers(struct list_head *cull_list)
2203 struct worker *worker, *tmp;
2205 list_for_each_entry_safe(worker, tmp, cull_list, entry) {
2206 list_del_init(&worker->entry);
2207 unbind_worker(worker);
2209 * If the worker was somehow already running, then it had to be
2210 * in pool->idle_list when set_worker_dying() happened or we
2211 * wouldn't have gotten here.
2213 * Thus, the worker must either have observed the WORKER_DIE
2214 * flag, or have set its state to TASK_IDLE. Either way, the
2215 * below will be observed by the worker and is safe to do
2216 * outside of pool->lock.
2218 wake_up_process(worker->task);
2223 * set_worker_dying - Tag a worker for destruction
2224 * @worker: worker to be destroyed
2225 * @list: transfer worker away from its pool->idle_list and into list
2227 * Tag @worker for destruction and adjust @pool stats accordingly. The worker
2231 * raw_spin_lock_irq(pool->lock).
2233 static void set_worker_dying(struct worker *worker, struct list_head *list)
2235 struct worker_pool *pool = worker->pool;
2237 lockdep_assert_held(&pool->lock);
2238 lockdep_assert_held(&wq_pool_attach_mutex);
2240 /* sanity check frenzy */
2241 if (WARN_ON(worker->current_work) ||
2242 WARN_ON(!list_empty(&worker->scheduled)) ||
2243 WARN_ON(!(worker->flags & WORKER_IDLE)))
2249 worker->flags |= WORKER_DIE;
2251 list_move(&worker->entry, list);
2252 list_move(&worker->node, &pool->dying_workers);
2256 * idle_worker_timeout - check if some idle workers can now be deleted.
2257 * @t: The pool's idle_timer that just expired
2259 * The timer is armed in worker_enter_idle(). Note that it isn't disarmed in
2260 * worker_leave_idle(), as a worker flicking between idle and active while its
2261 * pool is at the too_many_workers() tipping point would cause too much timer
2262 * housekeeping overhead. Since IDLE_WORKER_TIMEOUT is long enough, we just let
2263 * it expire and re-evaluate things from there.
2265 static void idle_worker_timeout(struct timer_list *t)
2267 struct worker_pool *pool = from_timer(pool, t, idle_timer);
2268 bool do_cull = false;
2270 if (work_pending(&pool->idle_cull_work))
2273 raw_spin_lock_irq(&pool->lock);
2275 if (too_many_workers(pool)) {
2276 struct worker *worker;
2277 unsigned long expires;
2279 /* idle_list is kept in LIFO order, check the last one */
2280 worker = list_entry(pool->idle_list.prev, struct worker, entry);
2281 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2282 do_cull = !time_before(jiffies, expires);
2285 mod_timer(&pool->idle_timer, expires);
2287 raw_spin_unlock_irq(&pool->lock);
2290 queue_work(system_unbound_wq, &pool->idle_cull_work);
2294 * idle_cull_fn - cull workers that have been idle for too long.
2295 * @work: the pool's work for handling these idle workers
2297 * This goes through a pool's idle workers and gets rid of those that have been
2298 * idle for at least IDLE_WORKER_TIMEOUT seconds.
2300 * We don't want to disturb isolated CPUs because of a pcpu kworker being
2301 * culled, so this also resets worker affinity. This requires a sleepable
2302 * context, hence the split between timer callback and work item.
2304 static void idle_cull_fn(struct work_struct *work)
2306 struct worker_pool *pool = container_of(work, struct worker_pool, idle_cull_work);
2307 struct list_head cull_list;
2309 INIT_LIST_HEAD(&cull_list);
2311 * Grabbing wq_pool_attach_mutex here ensures an already-running worker
2312 * cannot proceed beyong worker_detach_from_pool() in its self-destruct
2313 * path. This is required as a previously-preempted worker could run after
2314 * set_worker_dying() has happened but before wake_dying_workers() did.
2316 mutex_lock(&wq_pool_attach_mutex);
2317 raw_spin_lock_irq(&pool->lock);
2319 while (too_many_workers(pool)) {
2320 struct worker *worker;
2321 unsigned long expires;
2323 worker = list_entry(pool->idle_list.prev, struct worker, entry);
2324 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2326 if (time_before(jiffies, expires)) {
2327 mod_timer(&pool->idle_timer, expires);
2331 set_worker_dying(worker, &cull_list);
2334 raw_spin_unlock_irq(&pool->lock);
2335 wake_dying_workers(&cull_list);
2336 mutex_unlock(&wq_pool_attach_mutex);
2339 static void send_mayday(struct work_struct *work)
2341 struct pool_workqueue *pwq = get_work_pwq(work);
2342 struct workqueue_struct *wq = pwq->wq;
2344 lockdep_assert_held(&wq_mayday_lock);
2349 /* mayday mayday mayday */
2350 if (list_empty(&pwq->mayday_node)) {
2352 * If @pwq is for an unbound wq, its base ref may be put at
2353 * any time due to an attribute change. Pin @pwq until the
2354 * rescuer is done with it.
2357 list_add_tail(&pwq->mayday_node, &wq->maydays);
2358 wake_up_process(wq->rescuer->task);
2359 pwq->stats[PWQ_STAT_MAYDAY]++;
2363 static void pool_mayday_timeout(struct timer_list *t)
2365 struct worker_pool *pool = from_timer(pool, t, mayday_timer);
2366 struct work_struct *work;
2368 raw_spin_lock_irq(&pool->lock);
2369 raw_spin_lock(&wq_mayday_lock); /* for wq->maydays */
2371 if (need_to_create_worker(pool)) {
2373 * We've been trying to create a new worker but
2374 * haven't been successful. We might be hitting an
2375 * allocation deadlock. Send distress signals to
2378 list_for_each_entry(work, &pool->worklist, entry)
2382 raw_spin_unlock(&wq_mayday_lock);
2383 raw_spin_unlock_irq(&pool->lock);
2385 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
2389 * maybe_create_worker - create a new worker if necessary
2390 * @pool: pool to create a new worker for
2392 * Create a new worker for @pool if necessary. @pool is guaranteed to
2393 * have at least one idle worker on return from this function. If
2394 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
2395 * sent to all rescuers with works scheduled on @pool to resolve
2396 * possible allocation deadlock.
2398 * On return, need_to_create_worker() is guaranteed to be %false and
2399 * may_start_working() %true.
2402 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2403 * multiple times. Does GFP_KERNEL allocations. Called only from
2406 static void maybe_create_worker(struct worker_pool *pool)
2407 __releases(&pool->lock)
2408 __acquires(&pool->lock)
2411 raw_spin_unlock_irq(&pool->lock);
2413 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
2414 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
2417 if (create_worker(pool) || !need_to_create_worker(pool))
2420 schedule_timeout_interruptible(CREATE_COOLDOWN);
2422 if (!need_to_create_worker(pool))
2426 del_timer_sync(&pool->mayday_timer);
2427 raw_spin_lock_irq(&pool->lock);
2429 * This is necessary even after a new worker was just successfully
2430 * created as @pool->lock was dropped and the new worker might have
2431 * already become busy.
2433 if (need_to_create_worker(pool))
2438 * manage_workers - manage worker pool
2441 * Assume the manager role and manage the worker pool @worker belongs
2442 * to. At any given time, there can be only zero or one manager per
2443 * pool. The exclusion is handled automatically by this function.
2445 * The caller can safely start processing works on false return. On
2446 * true return, it's guaranteed that need_to_create_worker() is false
2447 * and may_start_working() is true.
2450 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2451 * multiple times. Does GFP_KERNEL allocations.
2454 * %false if the pool doesn't need management and the caller can safely
2455 * start processing works, %true if management function was performed and
2456 * the conditions that the caller verified before calling the function may
2457 * no longer be true.
2459 static bool manage_workers(struct worker *worker)
2461 struct worker_pool *pool = worker->pool;
2463 if (pool->flags & POOL_MANAGER_ACTIVE)
2466 pool->flags |= POOL_MANAGER_ACTIVE;
2467 pool->manager = worker;
2469 maybe_create_worker(pool);
2471 pool->manager = NULL;
2472 pool->flags &= ~POOL_MANAGER_ACTIVE;
2473 rcuwait_wake_up(&manager_wait);
2478 * process_one_work - process single work
2480 * @work: work to process
2482 * Process @work. This function contains all the logics necessary to
2483 * process a single work including synchronization against and
2484 * interaction with other workers on the same cpu, queueing and
2485 * flushing. As long as context requirement is met, any worker can
2486 * call this function to process a work.
2489 * raw_spin_lock_irq(pool->lock) which is released and regrabbed.
2491 static void process_one_work(struct worker *worker, struct work_struct *work)
2492 __releases(&pool->lock)
2493 __acquires(&pool->lock)
2495 struct pool_workqueue *pwq = get_work_pwq(work);
2496 struct worker_pool *pool = worker->pool;
2497 unsigned long work_data;
2498 struct worker *collision;
2499 #ifdef CONFIG_LOCKDEP
2501 * It is permissible to free the struct work_struct from
2502 * inside the function that is called from it, this we need to
2503 * take into account for lockdep too. To avoid bogus "held
2504 * lock freed" warnings as well as problems when looking into
2505 * work->lockdep_map, make a copy and use that here.
2507 struct lockdep_map lockdep_map;
2509 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
2511 /* ensure we're on the correct CPU */
2512 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2513 raw_smp_processor_id() != pool->cpu);
2516 * A single work shouldn't be executed concurrently by
2517 * multiple workers on a single cpu. Check whether anyone is
2518 * already processing the work. If so, defer the work to the
2519 * currently executing one.
2521 collision = find_worker_executing_work(pool, work);
2522 if (unlikely(collision)) {
2523 move_linked_works(work, &collision->scheduled, NULL);
2527 /* claim and dequeue */
2528 debug_work_deactivate(work);
2529 hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2530 worker->current_work = work;
2531 worker->current_func = work->func;
2532 worker->current_pwq = pwq;
2533 worker->current_at = worker->task->se.sum_exec_runtime;
2534 work_data = *work_data_bits(work);
2535 worker->current_color = get_work_color(work_data);
2538 * Record wq name for cmdline and debug reporting, may get
2539 * overridden through set_worker_desc().
2541 strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
2543 list_del_init(&work->entry);
2546 * CPU intensive works don't participate in concurrency management.
2547 * They're the scheduler's responsibility. This takes @worker out
2548 * of concurrency management and the next code block will chain
2549 * execution of the pending work items.
2551 if (unlikely(pwq->wq->flags & WQ_CPU_INTENSIVE))
2552 worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2555 * Wake up another worker if necessary. The condition is always
2556 * false for normal per-cpu workers since nr_running would always
2557 * be >= 1 at this point. This is used to chain execution of the
2558 * pending work items for WORKER_NOT_RUNNING workers such as the
2559 * UNBOUND and CPU_INTENSIVE ones.
2561 if (need_more_worker(pool))
2562 wake_up_worker(pool);
2565 * Record the last pool and clear PENDING which should be the last
2566 * update to @work. Also, do this inside @pool->lock so that
2567 * PENDING and queued state changes happen together while IRQ is
2570 set_work_pool_and_clear_pending(work, pool->id);
2572 raw_spin_unlock_irq(&pool->lock);
2574 lock_map_acquire(&pwq->wq->lockdep_map);
2575 lock_map_acquire(&lockdep_map);
2577 * Strictly speaking we should mark the invariant state without holding
2578 * any locks, that is, before these two lock_map_acquire()'s.
2580 * However, that would result in:
2587 * Which would create W1->C->W1 dependencies, even though there is no
2588 * actual deadlock possible. There are two solutions, using a
2589 * read-recursive acquire on the work(queue) 'locks', but this will then
2590 * hit the lockdep limitation on recursive locks, or simply discard
2593 * AFAICT there is no possible deadlock scenario between the
2594 * flush_work() and complete() primitives (except for single-threaded
2595 * workqueues), so hiding them isn't a problem.
2597 lockdep_invariant_state(true);
2598 pwq->stats[PWQ_STAT_STARTED]++;
2599 trace_workqueue_execute_start(work);
2600 worker->current_func(work);
2602 * While we must be careful to not use "work" after this, the trace
2603 * point will only record its address.
2605 trace_workqueue_execute_end(work, worker->current_func);
2606 pwq->stats[PWQ_STAT_COMPLETED]++;
2607 lock_map_release(&lockdep_map);
2608 lock_map_release(&pwq->wq->lockdep_map);
2610 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2611 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2612 " last function: %ps\n",
2613 current->comm, preempt_count(), task_pid_nr(current),
2614 worker->current_func);
2615 debug_show_held_locks(current);
2620 * The following prevents a kworker from hogging CPU on !PREEMPTION
2621 * kernels, where a requeueing work item waiting for something to
2622 * happen could deadlock with stop_machine as such work item could
2623 * indefinitely requeue itself while all other CPUs are trapped in
2624 * stop_machine. At the same time, report a quiescent RCU state so
2625 * the same condition doesn't freeze RCU.
2629 raw_spin_lock_irq(&pool->lock);
2632 * In addition to %WQ_CPU_INTENSIVE, @worker may also have been marked
2633 * CPU intensive by wq_worker_tick() if @work hogged CPU longer than
2634 * wq_cpu_intensive_thresh_us. Clear it.
2636 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2638 /* tag the worker for identification in schedule() */
2639 worker->last_func = worker->current_func;
2641 /* we're done with it, release */
2642 hash_del(&worker->hentry);
2643 worker->current_work = NULL;
2644 worker->current_func = NULL;
2645 worker->current_pwq = NULL;
2646 worker->current_color = INT_MAX;
2647 pwq_dec_nr_in_flight(pwq, work_data);
2651 * process_scheduled_works - process scheduled works
2654 * Process all scheduled works. Please note that the scheduled list
2655 * may change while processing a work, so this function repeatedly
2656 * fetches a work from the top and executes it.
2659 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2662 static void process_scheduled_works(struct worker *worker)
2664 while (!list_empty(&worker->scheduled)) {
2665 struct work_struct *work = list_first_entry(&worker->scheduled,
2666 struct work_struct, entry);
2667 process_one_work(worker, work);
2671 static void set_pf_worker(bool val)
2673 mutex_lock(&wq_pool_attach_mutex);
2675 current->flags |= PF_WQ_WORKER;
2677 current->flags &= ~PF_WQ_WORKER;
2678 mutex_unlock(&wq_pool_attach_mutex);
2682 * worker_thread - the worker thread function
2685 * The worker thread function. All workers belong to a worker_pool -
2686 * either a per-cpu one or dynamic unbound one. These workers process all
2687 * work items regardless of their specific target workqueue. The only
2688 * exception is work items which belong to workqueues with a rescuer which
2689 * will be explained in rescuer_thread().
2693 static int worker_thread(void *__worker)
2695 struct worker *worker = __worker;
2696 struct worker_pool *pool = worker->pool;
2698 /* tell the scheduler that this is a workqueue worker */
2699 set_pf_worker(true);
2701 raw_spin_lock_irq(&pool->lock);
2703 /* am I supposed to die? */
2704 if (unlikely(worker->flags & WORKER_DIE)) {
2705 raw_spin_unlock_irq(&pool->lock);
2706 set_pf_worker(false);
2708 set_task_comm(worker->task, "kworker/dying");
2709 ida_free(&pool->worker_ida, worker->id);
2710 worker_detach_from_pool(worker);
2711 WARN_ON_ONCE(!list_empty(&worker->entry));
2716 worker_leave_idle(worker);
2718 /* no more worker necessary? */
2719 if (!need_more_worker(pool))
2722 /* do we need to manage? */
2723 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2727 * ->scheduled list can only be filled while a worker is
2728 * preparing to process a work or actually processing it.
2729 * Make sure nobody diddled with it while I was sleeping.
2731 WARN_ON_ONCE(!list_empty(&worker->scheduled));
2734 * Finish PREP stage. We're guaranteed to have at least one idle
2735 * worker or that someone else has already assumed the manager
2736 * role. This is where @worker starts participating in concurrency
2737 * management if applicable and concurrency management is restored
2738 * after being rebound. See rebind_workers() for details.
2740 worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2743 struct work_struct *work =
2744 list_first_entry(&pool->worklist,
2745 struct work_struct, entry);
2747 pool->watchdog_ts = jiffies;
2749 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2750 /* optimization path, not strictly necessary */
2751 process_one_work(worker, work);
2752 if (unlikely(!list_empty(&worker->scheduled)))
2753 process_scheduled_works(worker);
2755 move_linked_works(work, &worker->scheduled, NULL);
2756 process_scheduled_works(worker);
2758 } while (keep_working(pool));
2760 worker_set_flags(worker, WORKER_PREP);
2763 * pool->lock is held and there's no work to process and no need to
2764 * manage, sleep. Workers are woken up only while holding
2765 * pool->lock or from local cpu, so setting the current state
2766 * before releasing pool->lock is enough to prevent losing any
2769 worker_enter_idle(worker);
2770 __set_current_state(TASK_IDLE);
2771 raw_spin_unlock_irq(&pool->lock);
2777 * rescuer_thread - the rescuer thread function
2780 * Workqueue rescuer thread function. There's one rescuer for each
2781 * workqueue which has WQ_MEM_RECLAIM set.
2783 * Regular work processing on a pool may block trying to create a new
2784 * worker which uses GFP_KERNEL allocation which has slight chance of
2785 * developing into deadlock if some works currently on the same queue
2786 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2787 * the problem rescuer solves.
2789 * When such condition is possible, the pool summons rescuers of all
2790 * workqueues which have works queued on the pool and let them process
2791 * those works so that forward progress can be guaranteed.
2793 * This should happen rarely.
2797 static int rescuer_thread(void *__rescuer)
2799 struct worker *rescuer = __rescuer;
2800 struct workqueue_struct *wq = rescuer->rescue_wq;
2801 struct list_head *scheduled = &rescuer->scheduled;
2804 set_user_nice(current, RESCUER_NICE_LEVEL);
2807 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2808 * doesn't participate in concurrency management.
2810 set_pf_worker(true);
2812 set_current_state(TASK_IDLE);
2815 * By the time the rescuer is requested to stop, the workqueue
2816 * shouldn't have any work pending, but @wq->maydays may still have
2817 * pwq(s) queued. This can happen by non-rescuer workers consuming
2818 * all the work items before the rescuer got to them. Go through
2819 * @wq->maydays processing before acting on should_stop so that the
2820 * list is always empty on exit.
2822 should_stop = kthread_should_stop();
2824 /* see whether any pwq is asking for help */
2825 raw_spin_lock_irq(&wq_mayday_lock);
2827 while (!list_empty(&wq->maydays)) {
2828 struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2829 struct pool_workqueue, mayday_node);
2830 struct worker_pool *pool = pwq->pool;
2831 struct work_struct *work, *n;
2834 __set_current_state(TASK_RUNNING);
2835 list_del_init(&pwq->mayday_node);
2837 raw_spin_unlock_irq(&wq_mayday_lock);
2839 worker_attach_to_pool(rescuer, pool);
2841 raw_spin_lock_irq(&pool->lock);
2844 * Slurp in all works issued via this workqueue and
2847 WARN_ON_ONCE(!list_empty(scheduled));
2848 list_for_each_entry_safe(work, n, &pool->worklist, entry) {
2849 if (get_work_pwq(work) == pwq) {
2851 pool->watchdog_ts = jiffies;
2852 move_linked_works(work, scheduled, &n);
2853 pwq->stats[PWQ_STAT_RESCUED]++;
2858 if (!list_empty(scheduled)) {
2859 process_scheduled_works(rescuer);
2862 * The above execution of rescued work items could
2863 * have created more to rescue through
2864 * pwq_activate_first_inactive() or chained
2865 * queueing. Let's put @pwq back on mayday list so
2866 * that such back-to-back work items, which may be
2867 * being used to relieve memory pressure, don't
2868 * incur MAYDAY_INTERVAL delay inbetween.
2870 if (pwq->nr_active && need_to_create_worker(pool)) {
2871 raw_spin_lock(&wq_mayday_lock);
2873 * Queue iff we aren't racing destruction
2874 * and somebody else hasn't queued it already.
2876 if (wq->rescuer && list_empty(&pwq->mayday_node)) {
2878 list_add_tail(&pwq->mayday_node, &wq->maydays);
2880 raw_spin_unlock(&wq_mayday_lock);
2885 * Put the reference grabbed by send_mayday(). @pool won't
2886 * go away while we're still attached to it.
2891 * Leave this pool. If need_more_worker() is %true, notify a
2892 * regular worker; otherwise, we end up with 0 concurrency
2893 * and stalling the execution.
2895 if (need_more_worker(pool))
2896 wake_up_worker(pool);
2898 raw_spin_unlock_irq(&pool->lock);
2900 worker_detach_from_pool(rescuer);
2902 raw_spin_lock_irq(&wq_mayday_lock);
2905 raw_spin_unlock_irq(&wq_mayday_lock);
2908 __set_current_state(TASK_RUNNING);
2909 set_pf_worker(false);
2913 /* rescuers should never participate in concurrency management */
2914 WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2920 * check_flush_dependency - check for flush dependency sanity
2921 * @target_wq: workqueue being flushed
2922 * @target_work: work item being flushed (NULL for workqueue flushes)
2924 * %current is trying to flush the whole @target_wq or @target_work on it.
2925 * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
2926 * reclaiming memory or running on a workqueue which doesn't have
2927 * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
2930 static void check_flush_dependency(struct workqueue_struct *target_wq,
2931 struct work_struct *target_work)
2933 work_func_t target_func = target_work ? target_work->func : NULL;
2934 struct worker *worker;
2936 if (target_wq->flags & WQ_MEM_RECLAIM)
2939 worker = current_wq_worker();
2941 WARN_ONCE(current->flags & PF_MEMALLOC,
2942 "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps",
2943 current->pid, current->comm, target_wq->name, target_func);
2944 WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
2945 (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
2946 "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps",
2947 worker->current_pwq->wq->name, worker->current_func,
2948 target_wq->name, target_func);
2952 struct work_struct work;
2953 struct completion done;
2954 struct task_struct *task; /* purely informational */
2957 static void wq_barrier_func(struct work_struct *work)
2959 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2960 complete(&barr->done);
2964 * insert_wq_barrier - insert a barrier work
2965 * @pwq: pwq to insert barrier into
2966 * @barr: wq_barrier to insert
2967 * @target: target work to attach @barr to
2968 * @worker: worker currently executing @target, NULL if @target is not executing
2970 * @barr is linked to @target such that @barr is completed only after
2971 * @target finishes execution. Please note that the ordering
2972 * guarantee is observed only with respect to @target and on the local
2975 * Currently, a queued barrier can't be canceled. This is because
2976 * try_to_grab_pending() can't determine whether the work to be
2977 * grabbed is at the head of the queue and thus can't clear LINKED
2978 * flag of the previous work while there must be a valid next work
2979 * after a work with LINKED flag set.
2981 * Note that when @worker is non-NULL, @target may be modified
2982 * underneath us, so we can't reliably determine pwq from @target.
2985 * raw_spin_lock_irq(pool->lock).
2987 static void insert_wq_barrier(struct pool_workqueue *pwq,
2988 struct wq_barrier *barr,
2989 struct work_struct *target, struct worker *worker)
2991 unsigned int work_flags = 0;
2992 unsigned int work_color;
2993 struct list_head *head;
2996 * debugobject calls are safe here even with pool->lock locked
2997 * as we know for sure that this will not trigger any of the
2998 * checks and call back into the fixup functions where we
3001 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
3002 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
3004 init_completion_map(&barr->done, &target->lockdep_map);
3006 barr->task = current;
3008 /* The barrier work item does not participate in pwq->nr_active. */
3009 work_flags |= WORK_STRUCT_INACTIVE;
3012 * If @target is currently being executed, schedule the
3013 * barrier to the worker; otherwise, put it after @target.
3016 head = worker->scheduled.next;
3017 work_color = worker->current_color;
3019 unsigned long *bits = work_data_bits(target);
3021 head = target->entry.next;
3022 /* there can already be other linked works, inherit and set */
3023 work_flags |= *bits & WORK_STRUCT_LINKED;
3024 work_color = get_work_color(*bits);
3025 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
3028 pwq->nr_in_flight[work_color]++;
3029 work_flags |= work_color_to_flags(work_color);
3031 debug_work_activate(&barr->work);
3032 insert_work(pwq, &barr->work, head, work_flags);
3036 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
3037 * @wq: workqueue being flushed
3038 * @flush_color: new flush color, < 0 for no-op
3039 * @work_color: new work color, < 0 for no-op
3041 * Prepare pwqs for workqueue flushing.
3043 * If @flush_color is non-negative, flush_color on all pwqs should be
3044 * -1. If no pwq has in-flight commands at the specified color, all
3045 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
3046 * has in flight commands, its pwq->flush_color is set to
3047 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
3048 * wakeup logic is armed and %true is returned.
3050 * The caller should have initialized @wq->first_flusher prior to
3051 * calling this function with non-negative @flush_color. If
3052 * @flush_color is negative, no flush color update is done and %false
3055 * If @work_color is non-negative, all pwqs should have the same
3056 * work_color which is previous to @work_color and all will be
3057 * advanced to @work_color.
3060 * mutex_lock(wq->mutex).
3063 * %true if @flush_color >= 0 and there's something to flush. %false
3066 static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
3067 int flush_color, int work_color)
3070 struct pool_workqueue *pwq;
3072 if (flush_color >= 0) {
3073 WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
3074 atomic_set(&wq->nr_pwqs_to_flush, 1);
3077 for_each_pwq(pwq, wq) {
3078 struct worker_pool *pool = pwq->pool;
3080 raw_spin_lock_irq(&pool->lock);
3082 if (flush_color >= 0) {
3083 WARN_ON_ONCE(pwq->flush_color != -1);
3085 if (pwq->nr_in_flight[flush_color]) {
3086 pwq->flush_color = flush_color;
3087 atomic_inc(&wq->nr_pwqs_to_flush);
3092 if (work_color >= 0) {
3093 WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
3094 pwq->work_color = work_color;
3097 raw_spin_unlock_irq(&pool->lock);
3100 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
3101 complete(&wq->first_flusher->done);
3107 * __flush_workqueue - ensure that any scheduled work has run to completion.
3108 * @wq: workqueue to flush
3110 * This function sleeps until all work items which were queued on entry
3111 * have finished execution, but it is not livelocked by new incoming ones.
3113 void __flush_workqueue(struct workqueue_struct *wq)
3115 struct wq_flusher this_flusher = {
3116 .list = LIST_HEAD_INIT(this_flusher.list),
3118 .done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map),
3122 if (WARN_ON(!wq_online))
3125 lock_map_acquire(&wq->lockdep_map);
3126 lock_map_release(&wq->lockdep_map);
3128 mutex_lock(&wq->mutex);
3131 * Start-to-wait phase
3133 next_color = work_next_color(wq->work_color);
3135 if (next_color != wq->flush_color) {
3137 * Color space is not full. The current work_color
3138 * becomes our flush_color and work_color is advanced
3141 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
3142 this_flusher.flush_color = wq->work_color;
3143 wq->work_color = next_color;
3145 if (!wq->first_flusher) {
3146 /* no flush in progress, become the first flusher */
3147 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
3149 wq->first_flusher = &this_flusher;
3151 if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
3153 /* nothing to flush, done */
3154 wq->flush_color = next_color;
3155 wq->first_flusher = NULL;
3160 WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
3161 list_add_tail(&this_flusher.list, &wq->flusher_queue);
3162 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
3166 * Oops, color space is full, wait on overflow queue.
3167 * The next flush completion will assign us
3168 * flush_color and transfer to flusher_queue.
3170 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
3173 check_flush_dependency(wq, NULL);
3175 mutex_unlock(&wq->mutex);
3177 wait_for_completion(&this_flusher.done);
3180 * Wake-up-and-cascade phase
3182 * First flushers are responsible for cascading flushes and
3183 * handling overflow. Non-first flushers can simply return.
3185 if (READ_ONCE(wq->first_flusher) != &this_flusher)
3188 mutex_lock(&wq->mutex);
3190 /* we might have raced, check again with mutex held */
3191 if (wq->first_flusher != &this_flusher)
3194 WRITE_ONCE(wq->first_flusher, NULL);
3196 WARN_ON_ONCE(!list_empty(&this_flusher.list));
3197 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
3200 struct wq_flusher *next, *tmp;
3202 /* complete all the flushers sharing the current flush color */
3203 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
3204 if (next->flush_color != wq->flush_color)
3206 list_del_init(&next->list);
3207 complete(&next->done);
3210 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
3211 wq->flush_color != work_next_color(wq->work_color));
3213 /* this flush_color is finished, advance by one */
3214 wq->flush_color = work_next_color(wq->flush_color);
3216 /* one color has been freed, handle overflow queue */
3217 if (!list_empty(&wq->flusher_overflow)) {
3219 * Assign the same color to all overflowed
3220 * flushers, advance work_color and append to
3221 * flusher_queue. This is the start-to-wait
3222 * phase for these overflowed flushers.
3224 list_for_each_entry(tmp, &wq->flusher_overflow, list)
3225 tmp->flush_color = wq->work_color;
3227 wq->work_color = work_next_color(wq->work_color);
3229 list_splice_tail_init(&wq->flusher_overflow,
3230 &wq->flusher_queue);
3231 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
3234 if (list_empty(&wq->flusher_queue)) {
3235 WARN_ON_ONCE(wq->flush_color != wq->work_color);
3240 * Need to flush more colors. Make the next flusher
3241 * the new first flusher and arm pwqs.
3243 WARN_ON_ONCE(wq->flush_color == wq->work_color);
3244 WARN_ON_ONCE(wq->flush_color != next->flush_color);
3246 list_del_init(&next->list);
3247 wq->first_flusher = next;
3249 if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
3253 * Meh... this color is already done, clear first
3254 * flusher and repeat cascading.
3256 wq->first_flusher = NULL;
3260 mutex_unlock(&wq->mutex);
3262 EXPORT_SYMBOL(__flush_workqueue);
3265 * drain_workqueue - drain a workqueue
3266 * @wq: workqueue to drain
3268 * Wait until the workqueue becomes empty. While draining is in progress,
3269 * only chain queueing is allowed. IOW, only currently pending or running
3270 * work items on @wq can queue further work items on it. @wq is flushed
3271 * repeatedly until it becomes empty. The number of flushing is determined
3272 * by the depth of chaining and should be relatively short. Whine if it
3275 void drain_workqueue(struct workqueue_struct *wq)
3277 unsigned int flush_cnt = 0;
3278 struct pool_workqueue *pwq;
3281 * __queue_work() needs to test whether there are drainers, is much
3282 * hotter than drain_workqueue() and already looks at @wq->flags.
3283 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
3285 mutex_lock(&wq->mutex);
3286 if (!wq->nr_drainers++)
3287 wq->flags |= __WQ_DRAINING;
3288 mutex_unlock(&wq->mutex);
3290 __flush_workqueue(wq);
3292 mutex_lock(&wq->mutex);
3294 for_each_pwq(pwq, wq) {
3297 raw_spin_lock_irq(&pwq->pool->lock);
3298 drained = !pwq->nr_active && list_empty(&pwq->inactive_works);
3299 raw_spin_unlock_irq(&pwq->pool->lock);
3304 if (++flush_cnt == 10 ||
3305 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
3306 pr_warn("workqueue %s: %s() isn't complete after %u tries\n",
3307 wq->name, __func__, flush_cnt);
3309 mutex_unlock(&wq->mutex);
3313 if (!--wq->nr_drainers)
3314 wq->flags &= ~__WQ_DRAINING;
3315 mutex_unlock(&wq->mutex);
3317 EXPORT_SYMBOL_GPL(drain_workqueue);
3319 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
3322 struct worker *worker = NULL;
3323 struct worker_pool *pool;
3324 struct pool_workqueue *pwq;
3329 pool = get_work_pool(work);
3335 raw_spin_lock_irq(&pool->lock);
3336 /* see the comment in try_to_grab_pending() with the same code */
3337 pwq = get_work_pwq(work);
3339 if (unlikely(pwq->pool != pool))
3342 worker = find_worker_executing_work(pool, work);
3345 pwq = worker->current_pwq;
3348 check_flush_dependency(pwq->wq, work);
3350 insert_wq_barrier(pwq, barr, work, worker);
3351 raw_spin_unlock_irq(&pool->lock);
3354 * Force a lock recursion deadlock when using flush_work() inside a
3355 * single-threaded or rescuer equipped workqueue.
3357 * For single threaded workqueues the deadlock happens when the work
3358 * is after the work issuing the flush_work(). For rescuer equipped
3359 * workqueues the deadlock happens when the rescuer stalls, blocking
3363 (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)) {
3364 lock_map_acquire(&pwq->wq->lockdep_map);
3365 lock_map_release(&pwq->wq->lockdep_map);
3370 raw_spin_unlock_irq(&pool->lock);
3375 static bool __flush_work(struct work_struct *work, bool from_cancel)
3377 struct wq_barrier barr;
3379 if (WARN_ON(!wq_online))
3382 if (WARN_ON(!work->func))
3385 lock_map_acquire(&work->lockdep_map);
3386 lock_map_release(&work->lockdep_map);
3388 if (start_flush_work(work, &barr, from_cancel)) {
3389 wait_for_completion(&barr.done);
3390 destroy_work_on_stack(&barr.work);
3398 * flush_work - wait for a work to finish executing the last queueing instance
3399 * @work: the work to flush
3401 * Wait until @work has finished execution. @work is guaranteed to be idle
3402 * on return if it hasn't been requeued since flush started.
3405 * %true if flush_work() waited for the work to finish execution,
3406 * %false if it was already idle.
3408 bool flush_work(struct work_struct *work)
3410 return __flush_work(work, false);
3412 EXPORT_SYMBOL_GPL(flush_work);
3415 wait_queue_entry_t wait;
3416 struct work_struct *work;
3419 static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
3421 struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
3423 if (cwait->work != key)
3425 return autoremove_wake_function(wait, mode, sync, key);
3428 static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
3430 static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
3431 unsigned long flags;
3435 ret = try_to_grab_pending(work, is_dwork, &flags);
3437 * If someone else is already canceling, wait for it to
3438 * finish. flush_work() doesn't work for PREEMPT_NONE
3439 * because we may get scheduled between @work's completion
3440 * and the other canceling task resuming and clearing
3441 * CANCELING - flush_work() will return false immediately
3442 * as @work is no longer busy, try_to_grab_pending() will
3443 * return -ENOENT as @work is still being canceled and the
3444 * other canceling task won't be able to clear CANCELING as
3445 * we're hogging the CPU.
3447 * Let's wait for completion using a waitqueue. As this
3448 * may lead to the thundering herd problem, use a custom
3449 * wake function which matches @work along with exclusive
3452 if (unlikely(ret == -ENOENT)) {
3453 struct cwt_wait cwait;
3455 init_wait(&cwait.wait);
3456 cwait.wait.func = cwt_wakefn;
3459 prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
3460 TASK_UNINTERRUPTIBLE);
3461 if (work_is_canceling(work))
3463 finish_wait(&cancel_waitq, &cwait.wait);
3465 } while (unlikely(ret < 0));
3467 /* tell other tasks trying to grab @work to back off */
3468 mark_work_canceling(work);
3469 local_irq_restore(flags);
3472 * This allows canceling during early boot. We know that @work
3476 __flush_work(work, true);
3478 clear_work_data(work);
3481 * Paired with prepare_to_wait() above so that either
3482 * waitqueue_active() is visible here or !work_is_canceling() is
3486 if (waitqueue_active(&cancel_waitq))
3487 __wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
3493 * cancel_work_sync - cancel a work and wait for it to finish
3494 * @work: the work to cancel
3496 * Cancel @work and wait for its execution to finish. This function
3497 * can be used even if the work re-queues itself or migrates to
3498 * another workqueue. On return from this function, @work is
3499 * guaranteed to be not pending or executing on any CPU.
3501 * cancel_work_sync(&delayed_work->work) must not be used for
3502 * delayed_work's. Use cancel_delayed_work_sync() instead.
3504 * The caller must ensure that the workqueue on which @work was last
3505 * queued can't be destroyed before this function returns.
3508 * %true if @work was pending, %false otherwise.
3510 bool cancel_work_sync(struct work_struct *work)
3512 return __cancel_work_timer(work, false);
3514 EXPORT_SYMBOL_GPL(cancel_work_sync);
3517 * flush_delayed_work - wait for a dwork to finish executing the last queueing
3518 * @dwork: the delayed work to flush
3520 * Delayed timer is cancelled and the pending work is queued for
3521 * immediate execution. Like flush_work(), this function only
3522 * considers the last queueing instance of @dwork.
3525 * %true if flush_work() waited for the work to finish execution,
3526 * %false if it was already idle.
3528 bool flush_delayed_work(struct delayed_work *dwork)
3530 local_irq_disable();
3531 if (del_timer_sync(&dwork->timer))
3532 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
3534 return flush_work(&dwork->work);
3536 EXPORT_SYMBOL(flush_delayed_work);
3539 * flush_rcu_work - wait for a rwork to finish executing the last queueing
3540 * @rwork: the rcu work to flush
3543 * %true if flush_rcu_work() waited for the work to finish execution,
3544 * %false if it was already idle.
3546 bool flush_rcu_work(struct rcu_work *rwork)
3548 if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
3550 flush_work(&rwork->work);
3553 return flush_work(&rwork->work);
3556 EXPORT_SYMBOL(flush_rcu_work);
3558 static bool __cancel_work(struct work_struct *work, bool is_dwork)
3560 unsigned long flags;
3564 ret = try_to_grab_pending(work, is_dwork, &flags);
3565 } while (unlikely(ret == -EAGAIN));
3567 if (unlikely(ret < 0))
3570 set_work_pool_and_clear_pending(work, get_work_pool_id(work));
3571 local_irq_restore(flags);
3576 * See cancel_delayed_work()
3578 bool cancel_work(struct work_struct *work)
3580 return __cancel_work(work, false);
3582 EXPORT_SYMBOL(cancel_work);
3585 * cancel_delayed_work - cancel a delayed work
3586 * @dwork: delayed_work to cancel
3588 * Kill off a pending delayed_work.
3590 * Return: %true if @dwork was pending and canceled; %false if it wasn't
3594 * The work callback function may still be running on return, unless
3595 * it returns %true and the work doesn't re-arm itself. Explicitly flush or
3596 * use cancel_delayed_work_sync() to wait on it.
3598 * This function is safe to call from any context including IRQ handler.
3600 bool cancel_delayed_work(struct delayed_work *dwork)
3602 return __cancel_work(&dwork->work, true);
3604 EXPORT_SYMBOL(cancel_delayed_work);
3607 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3608 * @dwork: the delayed work cancel
3610 * This is cancel_work_sync() for delayed works.
3613 * %true if @dwork was pending, %false otherwise.
3615 bool cancel_delayed_work_sync(struct delayed_work *dwork)
3617 return __cancel_work_timer(&dwork->work, true);
3619 EXPORT_SYMBOL(cancel_delayed_work_sync);
3622 * schedule_on_each_cpu - execute a function synchronously on each online CPU
3623 * @func: the function to call
3625 * schedule_on_each_cpu() executes @func on each online CPU using the
3626 * system workqueue and blocks until all CPUs have completed.
3627 * schedule_on_each_cpu() is very slow.
3630 * 0 on success, -errno on failure.
3632 int schedule_on_each_cpu(work_func_t func)
3635 struct work_struct __percpu *works;
3637 works = alloc_percpu(struct work_struct);
3643 for_each_online_cpu(cpu) {
3644 struct work_struct *work = per_cpu_ptr(works, cpu);
3646 INIT_WORK(work, func);
3647 schedule_work_on(cpu, work);
3650 for_each_online_cpu(cpu)
3651 flush_work(per_cpu_ptr(works, cpu));
3659 * execute_in_process_context - reliably execute the routine with user context
3660 * @fn: the function to execute
3661 * @ew: guaranteed storage for the execute work structure (must
3662 * be available when the work executes)
3664 * Executes the function immediately if process context is available,
3665 * otherwise schedules the function for delayed execution.
3667 * Return: 0 - function was executed
3668 * 1 - function was scheduled for execution
3670 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
3672 if (!in_interrupt()) {
3677 INIT_WORK(&ew->work, fn);
3678 schedule_work(&ew->work);
3682 EXPORT_SYMBOL_GPL(execute_in_process_context);
3685 * free_workqueue_attrs - free a workqueue_attrs
3686 * @attrs: workqueue_attrs to free
3688 * Undo alloc_workqueue_attrs().
3690 void free_workqueue_attrs(struct workqueue_attrs *attrs)
3693 free_cpumask_var(attrs->cpumask);
3699 * alloc_workqueue_attrs - allocate a workqueue_attrs
3701 * Allocate a new workqueue_attrs, initialize with default settings and
3704 * Return: The allocated new workqueue_attr on success. %NULL on failure.
3706 struct workqueue_attrs *alloc_workqueue_attrs(void)
3708 struct workqueue_attrs *attrs;
3710 attrs = kzalloc(sizeof(*attrs), GFP_KERNEL);
3713 if (!alloc_cpumask_var(&attrs->cpumask, GFP_KERNEL))
3716 cpumask_copy(attrs->cpumask, cpu_possible_mask);
3719 free_workqueue_attrs(attrs);
3723 static void copy_workqueue_attrs(struct workqueue_attrs *to,
3724 const struct workqueue_attrs *from)
3726 to->nice = from->nice;
3727 cpumask_copy(to->cpumask, from->cpumask);
3729 * Unlike hash and equality test, this function doesn't ignore
3730 * ->no_numa as it is used for both pool and wq attrs. Instead,
3731 * get_unbound_pool() explicitly clears ->no_numa after copying.
3733 to->no_numa = from->no_numa;
3736 /* hash value of the content of @attr */
3737 static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
3741 hash = jhash_1word(attrs->nice, hash);
3742 hash = jhash(cpumask_bits(attrs->cpumask),
3743 BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
3747 /* content equality test */
3748 static bool wqattrs_equal(const struct workqueue_attrs *a,
3749 const struct workqueue_attrs *b)
3751 if (a->nice != b->nice)
3753 if (!cpumask_equal(a->cpumask, b->cpumask))
3759 * init_worker_pool - initialize a newly zalloc'd worker_pool
3760 * @pool: worker_pool to initialize
3762 * Initialize a newly zalloc'd @pool. It also allocates @pool->attrs.
3764 * Return: 0 on success, -errno on failure. Even on failure, all fields
3765 * inside @pool proper are initialized and put_unbound_pool() can be called
3766 * on @pool safely to release it.
3768 static int init_worker_pool(struct worker_pool *pool)
3770 raw_spin_lock_init(&pool->lock);
3773 pool->node = NUMA_NO_NODE;
3774 pool->flags |= POOL_DISASSOCIATED;
3775 pool->watchdog_ts = jiffies;
3776 INIT_LIST_HEAD(&pool->worklist);
3777 INIT_LIST_HEAD(&pool->idle_list);
3778 hash_init(pool->busy_hash);
3780 timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
3781 INIT_WORK(&pool->idle_cull_work, idle_cull_fn);
3783 timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
3785 INIT_LIST_HEAD(&pool->workers);
3786 INIT_LIST_HEAD(&pool->dying_workers);
3788 ida_init(&pool->worker_ida);
3789 INIT_HLIST_NODE(&pool->hash_node);
3792 /* shouldn't fail above this point */
3793 pool->attrs = alloc_workqueue_attrs();
3799 #ifdef CONFIG_LOCKDEP
3800 static void wq_init_lockdep(struct workqueue_struct *wq)
3804 lockdep_register_key(&wq->key);
3805 lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name);
3807 lock_name = wq->name;
3809 wq->lock_name = lock_name;
3810 lockdep_init_map(&wq->lockdep_map, lock_name, &wq->key, 0);
3813 static void wq_unregister_lockdep(struct workqueue_struct *wq)
3815 lockdep_unregister_key(&wq->key);
3818 static void wq_free_lockdep(struct workqueue_struct *wq)
3820 if (wq->lock_name != wq->name)
3821 kfree(wq->lock_name);
3824 static void wq_init_lockdep(struct workqueue_struct *wq)
3828 static void wq_unregister_lockdep(struct workqueue_struct *wq)
3832 static void wq_free_lockdep(struct workqueue_struct *wq)
3837 static void rcu_free_wq(struct rcu_head *rcu)
3839 struct workqueue_struct *wq =
3840 container_of(rcu, struct workqueue_struct, rcu);
3842 wq_free_lockdep(wq);
3844 if (!(wq->flags & WQ_UNBOUND))
3845 free_percpu(wq->cpu_pwqs);
3847 free_workqueue_attrs(wq->unbound_attrs);
3852 static void rcu_free_pool(struct rcu_head *rcu)
3854 struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
3856 ida_destroy(&pool->worker_ida);
3857 free_workqueue_attrs(pool->attrs);
3862 * put_unbound_pool - put a worker_pool
3863 * @pool: worker_pool to put
3865 * Put @pool. If its refcnt reaches zero, it gets destroyed in RCU
3866 * safe manner. get_unbound_pool() calls this function on its failure path
3867 * and this function should be able to release pools which went through,
3868 * successfully or not, init_worker_pool().
3870 * Should be called with wq_pool_mutex held.
3872 static void put_unbound_pool(struct worker_pool *pool)
3874 DECLARE_COMPLETION_ONSTACK(detach_completion);
3875 struct list_head cull_list;
3876 struct worker *worker;
3878 INIT_LIST_HEAD(&cull_list);
3880 lockdep_assert_held(&wq_pool_mutex);
3886 if (WARN_ON(!(pool->cpu < 0)) ||
3887 WARN_ON(!list_empty(&pool->worklist)))
3890 /* release id and unhash */
3892 idr_remove(&worker_pool_idr, pool->id);
3893 hash_del(&pool->hash_node);
3896 * Become the manager and destroy all workers. This prevents
3897 * @pool's workers from blocking on attach_mutex. We're the last
3898 * manager and @pool gets freed with the flag set.
3900 * Having a concurrent manager is quite unlikely to happen as we can
3901 * only get here with
3902 * pwq->refcnt == pool->refcnt == 0
3903 * which implies no work queued to the pool, which implies no worker can
3904 * become the manager. However a worker could have taken the role of
3905 * manager before the refcnts dropped to 0, since maybe_create_worker()
3909 rcuwait_wait_event(&manager_wait,
3910 !(pool->flags & POOL_MANAGER_ACTIVE),
3911 TASK_UNINTERRUPTIBLE);
3913 mutex_lock(&wq_pool_attach_mutex);
3914 raw_spin_lock_irq(&pool->lock);
3915 if (!(pool->flags & POOL_MANAGER_ACTIVE)) {
3916 pool->flags |= POOL_MANAGER_ACTIVE;
3919 raw_spin_unlock_irq(&pool->lock);
3920 mutex_unlock(&wq_pool_attach_mutex);
3923 while ((worker = first_idle_worker(pool)))
3924 set_worker_dying(worker, &cull_list);
3925 WARN_ON(pool->nr_workers || pool->nr_idle);
3926 raw_spin_unlock_irq(&pool->lock);
3928 wake_dying_workers(&cull_list);
3930 if (!list_empty(&pool->workers) || !list_empty(&pool->dying_workers))
3931 pool->detach_completion = &detach_completion;
3932 mutex_unlock(&wq_pool_attach_mutex);
3934 if (pool->detach_completion)
3935 wait_for_completion(pool->detach_completion);
3937 /* shut down the timers */
3938 del_timer_sync(&pool->idle_timer);
3939 cancel_work_sync(&pool->idle_cull_work);
3940 del_timer_sync(&pool->mayday_timer);
3942 /* RCU protected to allow dereferences from get_work_pool() */
3943 call_rcu(&pool->rcu, rcu_free_pool);
3947 * get_unbound_pool - get a worker_pool with the specified attributes
3948 * @attrs: the attributes of the worker_pool to get
3950 * Obtain a worker_pool which has the same attributes as @attrs, bump the
3951 * reference count and return it. If there already is a matching
3952 * worker_pool, it will be used; otherwise, this function attempts to
3955 * Should be called with wq_pool_mutex held.
3957 * Return: On success, a worker_pool with the same attributes as @attrs.
3958 * On failure, %NULL.
3960 static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
3962 u32 hash = wqattrs_hash(attrs);
3963 struct worker_pool *pool;
3965 int target_node = NUMA_NO_NODE;
3967 lockdep_assert_held(&wq_pool_mutex);
3969 /* do we already have a matching pool? */
3970 hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
3971 if (wqattrs_equal(pool->attrs, attrs)) {
3977 /* if cpumask is contained inside a NUMA node, we belong to that node */
3978 if (wq_numa_enabled) {
3979 for_each_node(node) {
3980 if (cpumask_subset(attrs->cpumask,
3981 wq_numa_possible_cpumask[node])) {
3988 /* nope, create a new one */
3989 pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, target_node);
3990 if (!pool || init_worker_pool(pool) < 0)
3993 lockdep_set_subclass(&pool->lock, 1); /* see put_pwq() */
3994 copy_workqueue_attrs(pool->attrs, attrs);
3995 pool->node = target_node;
3998 * no_numa isn't a worker_pool attribute, always clear it. See
3999 * 'struct workqueue_attrs' comments for detail.
4001 pool->attrs->no_numa = false;
4003 if (worker_pool_assign_id(pool) < 0)
4006 /* create and start the initial worker */
4007 if (wq_online && !create_worker(pool))
4011 hash_add(unbound_pool_hash, &pool->hash_node, hash);
4016 put_unbound_pool(pool);
4020 static void rcu_free_pwq(struct rcu_head *rcu)
4022 kmem_cache_free(pwq_cache,
4023 container_of(rcu, struct pool_workqueue, rcu));
4027 * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
4028 * and needs to be destroyed.
4030 static void pwq_unbound_release_workfn(struct work_struct *work)
4032 struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
4033 unbound_release_work);
4034 struct workqueue_struct *wq = pwq->wq;
4035 struct worker_pool *pool = pwq->pool;
4036 bool is_last = false;
4039 * when @pwq is not linked, it doesn't hold any reference to the
4040 * @wq, and @wq is invalid to access.
4042 if (!list_empty(&pwq->pwqs_node)) {
4043 if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
4046 mutex_lock(&wq->mutex);
4047 list_del_rcu(&pwq->pwqs_node);
4048 is_last = list_empty(&wq->pwqs);
4049 mutex_unlock(&wq->mutex);
4052 mutex_lock(&wq_pool_mutex);
4053 put_unbound_pool(pool);
4054 mutex_unlock(&wq_pool_mutex);
4056 call_rcu(&pwq->rcu, rcu_free_pwq);
4059 * If we're the last pwq going away, @wq is already dead and no one
4060 * is gonna access it anymore. Schedule RCU free.
4063 wq_unregister_lockdep(wq);
4064 call_rcu(&wq->rcu, rcu_free_wq);
4069 * pwq_adjust_max_active - update a pwq's max_active to the current setting
4070 * @pwq: target pool_workqueue
4072 * If @pwq isn't freezing, set @pwq->max_active to the associated
4073 * workqueue's saved_max_active and activate inactive work items
4074 * accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
4076 static void pwq_adjust_max_active(struct pool_workqueue *pwq)
4078 struct workqueue_struct *wq = pwq->wq;
4079 bool freezable = wq->flags & WQ_FREEZABLE;
4080 unsigned long flags;
4082 /* for @wq->saved_max_active */
4083 lockdep_assert_held(&wq->mutex);
4085 /* fast exit for non-freezable wqs */
4086 if (!freezable && pwq->max_active == wq->saved_max_active)
4089 /* this function can be called during early boot w/ irq disabled */
4090 raw_spin_lock_irqsave(&pwq->pool->lock, flags);
4093 * During [un]freezing, the caller is responsible for ensuring that
4094 * this function is called at least once after @workqueue_freezing
4095 * is updated and visible.
4097 if (!freezable || !workqueue_freezing) {
4100 pwq->max_active = wq->saved_max_active;
4102 while (!list_empty(&pwq->inactive_works) &&
4103 pwq->nr_active < pwq->max_active) {
4104 pwq_activate_first_inactive(pwq);
4109 * Need to kick a worker after thawed or an unbound wq's
4110 * max_active is bumped. In realtime scenarios, always kicking a
4111 * worker will cause interference on the isolated cpu cores, so
4112 * let's kick iff work items were activated.
4115 wake_up_worker(pwq->pool);
4117 pwq->max_active = 0;
4120 raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
4123 /* initialize newly allocated @pwq which is associated with @wq and @pool */
4124 static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
4125 struct worker_pool *pool)
4127 BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
4129 memset(pwq, 0, sizeof(*pwq));
4133 pwq->flush_color = -1;
4135 INIT_LIST_HEAD(&pwq->inactive_works);
4136 INIT_LIST_HEAD(&pwq->pwqs_node);
4137 INIT_LIST_HEAD(&pwq->mayday_node);
4138 INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
4141 /* sync @pwq with the current state of its associated wq and link it */
4142 static void link_pwq(struct pool_workqueue *pwq)
4144 struct workqueue_struct *wq = pwq->wq;
4146 lockdep_assert_held(&wq->mutex);
4148 /* may be called multiple times, ignore if already linked */
4149 if (!list_empty(&pwq->pwqs_node))
4152 /* set the matching work_color */
4153 pwq->work_color = wq->work_color;
4155 /* sync max_active to the current setting */
4156 pwq_adjust_max_active(pwq);
4159 list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
4162 /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
4163 static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
4164 const struct workqueue_attrs *attrs)
4166 struct worker_pool *pool;
4167 struct pool_workqueue *pwq;
4169 lockdep_assert_held(&wq_pool_mutex);
4171 pool = get_unbound_pool(attrs);
4175 pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
4177 put_unbound_pool(pool);
4181 init_pwq(pwq, wq, pool);
4186 * wq_calc_node_cpumask - calculate a wq_attrs' cpumask for the specified node
4187 * @attrs: the wq_attrs of the default pwq of the target workqueue
4188 * @node: the target NUMA node
4189 * @cpu_going_down: if >= 0, the CPU to consider as offline
4190 * @cpumask: outarg, the resulting cpumask
4192 * Calculate the cpumask a workqueue with @attrs should use on @node. If
4193 * @cpu_going_down is >= 0, that cpu is considered offline during
4194 * calculation. The result is stored in @cpumask.
4196 * If NUMA affinity is not enabled, @attrs->cpumask is always used. If
4197 * enabled and @node has online CPUs requested by @attrs, the returned
4198 * cpumask is the intersection of the possible CPUs of @node and
4201 * The caller is responsible for ensuring that the cpumask of @node stays
4204 * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
4207 static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
4208 int cpu_going_down, cpumask_t *cpumask)
4210 if (!wq_numa_enabled || attrs->no_numa)
4213 /* does @node have any online CPUs @attrs wants? */
4214 cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
4215 if (cpu_going_down >= 0)
4216 cpumask_clear_cpu(cpu_going_down, cpumask);
4218 if (cpumask_empty(cpumask))
4221 /* yeap, return possible CPUs in @node that @attrs wants */
4222 cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
4224 if (cpumask_empty(cpumask)) {
4225 pr_warn_once("WARNING: workqueue cpumask: online intersect > "
4226 "possible intersect\n");
4230 return !cpumask_equal(cpumask, attrs->cpumask);
4233 cpumask_copy(cpumask, attrs->cpumask);
4237 /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
4238 static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
4240 struct pool_workqueue *pwq)
4242 struct pool_workqueue *old_pwq;
4244 lockdep_assert_held(&wq_pool_mutex);
4245 lockdep_assert_held(&wq->mutex);
4247 /* link_pwq() can handle duplicate calls */
4250 old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
4251 rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
4255 /* context to store the prepared attrs & pwqs before applying */
4256 struct apply_wqattrs_ctx {
4257 struct workqueue_struct *wq; /* target workqueue */
4258 struct workqueue_attrs *attrs; /* attrs to apply */
4259 struct list_head list; /* queued for batching commit */
4260 struct pool_workqueue *dfl_pwq;
4261 struct pool_workqueue *pwq_tbl[];
4264 /* free the resources after success or abort */
4265 static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
4271 put_pwq_unlocked(ctx->pwq_tbl[node]);
4272 put_pwq_unlocked(ctx->dfl_pwq);
4274 free_workqueue_attrs(ctx->attrs);
4280 /* allocate the attrs and pwqs for later installation */
4281 static struct apply_wqattrs_ctx *
4282 apply_wqattrs_prepare(struct workqueue_struct *wq,
4283 const struct workqueue_attrs *attrs,
4284 const cpumask_var_t unbound_cpumask)
4286 struct apply_wqattrs_ctx *ctx;
4287 struct workqueue_attrs *new_attrs, *tmp_attrs;
4290 lockdep_assert_held(&wq_pool_mutex);
4292 ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_node_ids), GFP_KERNEL);
4294 new_attrs = alloc_workqueue_attrs();
4295 tmp_attrs = alloc_workqueue_attrs();
4296 if (!ctx || !new_attrs || !tmp_attrs)
4300 * Calculate the attrs of the default pwq with unbound_cpumask
4301 * which is wq_unbound_cpumask or to set to wq_unbound_cpumask.
4302 * If the user configured cpumask doesn't overlap with the
4303 * wq_unbound_cpumask, we fallback to the wq_unbound_cpumask.
4305 copy_workqueue_attrs(new_attrs, attrs);
4306 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, unbound_cpumask);
4307 if (unlikely(cpumask_empty(new_attrs->cpumask)))
4308 cpumask_copy(new_attrs->cpumask, unbound_cpumask);
4311 * We may create multiple pwqs with differing cpumasks. Make a
4312 * copy of @new_attrs which will be modified and used to obtain
4315 copy_workqueue_attrs(tmp_attrs, new_attrs);
4318 * If something goes wrong during CPU up/down, we'll fall back to
4319 * the default pwq covering whole @attrs->cpumask. Always create
4320 * it even if we don't use it immediately.
4322 ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
4326 for_each_node(node) {
4327 if (wq_calc_node_cpumask(new_attrs, node, -1, tmp_attrs->cpumask)) {
4328 ctx->pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
4329 if (!ctx->pwq_tbl[node])
4332 ctx->dfl_pwq->refcnt++;
4333 ctx->pwq_tbl[node] = ctx->dfl_pwq;
4337 /* save the user configured attrs and sanitize it. */
4338 copy_workqueue_attrs(new_attrs, attrs);
4339 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
4340 ctx->attrs = new_attrs;
4343 free_workqueue_attrs(tmp_attrs);
4347 free_workqueue_attrs(tmp_attrs);
4348 free_workqueue_attrs(new_attrs);
4349 apply_wqattrs_cleanup(ctx);
4353 /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
4354 static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
4358 /* all pwqs have been created successfully, let's install'em */
4359 mutex_lock(&ctx->wq->mutex);
4361 copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
4363 /* save the previous pwq and install the new one */
4365 ctx->pwq_tbl[node] = numa_pwq_tbl_install(ctx->wq, node,
4366 ctx->pwq_tbl[node]);
4368 /* @dfl_pwq might not have been used, ensure it's linked */
4369 link_pwq(ctx->dfl_pwq);
4370 swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
4372 mutex_unlock(&ctx->wq->mutex);
4375 static void apply_wqattrs_lock(void)
4377 /* CPUs should stay stable across pwq creations and installations */
4379 mutex_lock(&wq_pool_mutex);
4382 static void apply_wqattrs_unlock(void)
4384 mutex_unlock(&wq_pool_mutex);
4388 static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
4389 const struct workqueue_attrs *attrs)
4391 struct apply_wqattrs_ctx *ctx;
4393 /* only unbound workqueues can change attributes */
4394 if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
4397 /* creating multiple pwqs breaks ordering guarantee */
4398 if (!list_empty(&wq->pwqs)) {
4399 if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
4402 wq->flags &= ~__WQ_ORDERED;
4405 ctx = apply_wqattrs_prepare(wq, attrs, wq_unbound_cpumask);
4409 /* the ctx has been prepared successfully, let's commit it */
4410 apply_wqattrs_commit(ctx);
4411 apply_wqattrs_cleanup(ctx);
4417 * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
4418 * @wq: the target workqueue
4419 * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
4421 * Apply @attrs to an unbound workqueue @wq. Unless disabled, on NUMA
4422 * machines, this function maps a separate pwq to each NUMA node with
4423 * possibles CPUs in @attrs->cpumask so that work items are affine to the
4424 * NUMA node it was issued on. Older pwqs are released as in-flight work
4425 * items finish. Note that a work item which repeatedly requeues itself
4426 * back-to-back will stay on its current pwq.
4428 * Performs GFP_KERNEL allocations.
4430 * Assumes caller has CPU hotplug read exclusion, i.e. cpus_read_lock().
4432 * Return: 0 on success and -errno on failure.
4434 int apply_workqueue_attrs(struct workqueue_struct *wq,
4435 const struct workqueue_attrs *attrs)
4439 lockdep_assert_cpus_held();
4441 mutex_lock(&wq_pool_mutex);
4442 ret = apply_workqueue_attrs_locked(wq, attrs);
4443 mutex_unlock(&wq_pool_mutex);
4449 * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
4450 * @wq: the target workqueue
4451 * @cpu: the CPU coming up or going down
4452 * @online: whether @cpu is coming up or going down
4454 * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
4455 * %CPU_DOWN_FAILED. @cpu is being hot[un]plugged, update NUMA affinity of
4458 * If NUMA affinity can't be adjusted due to memory allocation failure, it
4459 * falls back to @wq->dfl_pwq which may not be optimal but is always
4462 * Note that when the last allowed CPU of a NUMA node goes offline for a
4463 * workqueue with a cpumask spanning multiple nodes, the workers which were
4464 * already executing the work items for the workqueue will lose their CPU
4465 * affinity and may execute on any CPU. This is similar to how per-cpu
4466 * workqueues behave on CPU_DOWN. If a workqueue user wants strict
4467 * affinity, it's the user's responsibility to flush the work item from
4470 static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
4473 int node = cpu_to_node(cpu);
4474 int cpu_off = online ? -1 : cpu;
4475 struct pool_workqueue *old_pwq = NULL, *pwq;
4476 struct workqueue_attrs *target_attrs;
4479 lockdep_assert_held(&wq_pool_mutex);
4481 if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND) ||
4482 wq->unbound_attrs->no_numa)
4486 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
4487 * Let's use a preallocated one. The following buf is protected by
4488 * CPU hotplug exclusion.
4490 target_attrs = wq_update_unbound_numa_attrs_buf;
4491 cpumask = target_attrs->cpumask;
4493 copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
4494 pwq = unbound_pwq_by_node(wq, node);
4497 * Let's determine what needs to be done. If the target cpumask is
4498 * different from the default pwq's, we need to compare it to @pwq's
4499 * and create a new one if they don't match. If the target cpumask
4500 * equals the default pwq's, the default pwq should be used.
4502 if (wq_calc_node_cpumask(wq->dfl_pwq->pool->attrs, node, cpu_off, cpumask)) {
4503 if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
4509 /* create a new pwq */
4510 pwq = alloc_unbound_pwq(wq, target_attrs);
4512 pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
4517 /* Install the new pwq. */
4518 mutex_lock(&wq->mutex);
4519 old_pwq = numa_pwq_tbl_install(wq, node, pwq);
4523 mutex_lock(&wq->mutex);
4524 raw_spin_lock_irq(&wq->dfl_pwq->pool->lock);
4525 get_pwq(wq->dfl_pwq);
4526 raw_spin_unlock_irq(&wq->dfl_pwq->pool->lock);
4527 old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
4529 mutex_unlock(&wq->mutex);
4530 put_pwq_unlocked(old_pwq);
4533 static int alloc_and_link_pwqs(struct workqueue_struct *wq)
4535 bool highpri = wq->flags & WQ_HIGHPRI;
4538 if (!(wq->flags & WQ_UNBOUND)) {
4539 wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
4543 for_each_possible_cpu(cpu) {
4544 struct pool_workqueue *pwq =
4545 per_cpu_ptr(wq->cpu_pwqs, cpu);
4546 struct worker_pool *cpu_pools =
4547 per_cpu(cpu_worker_pools, cpu);
4549 init_pwq(pwq, wq, &cpu_pools[highpri]);
4551 mutex_lock(&wq->mutex);
4553 mutex_unlock(&wq->mutex);
4559 if (wq->flags & __WQ_ORDERED) {
4560 ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
4561 /* there should only be single pwq for ordering guarantee */
4562 WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
4563 wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
4564 "ordering guarantee broken for workqueue %s\n", wq->name);
4566 ret = apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
4573 static int wq_clamp_max_active(int max_active, unsigned int flags,
4576 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
4578 if (max_active < 1 || max_active > lim)
4579 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
4580 max_active, name, 1, lim);
4582 return clamp_val(max_active, 1, lim);
4586 * Workqueues which may be used during memory reclaim should have a rescuer
4587 * to guarantee forward progress.
4589 static int init_rescuer(struct workqueue_struct *wq)
4591 struct worker *rescuer;
4594 if (!(wq->flags & WQ_MEM_RECLAIM))
4597 rescuer = alloc_worker(NUMA_NO_NODE);
4599 pr_err("workqueue: Failed to allocate a rescuer for wq \"%s\"\n",
4604 rescuer->rescue_wq = wq;
4605 rescuer->task = kthread_create(rescuer_thread, rescuer, "%s", wq->name);
4606 if (IS_ERR(rescuer->task)) {
4607 ret = PTR_ERR(rescuer->task);
4608 pr_err("workqueue: Failed to create a rescuer kthread for wq \"%s\": %pe",
4609 wq->name, ERR_PTR(ret));
4614 wq->rescuer = rescuer;
4615 kthread_bind_mask(rescuer->task, cpu_possible_mask);
4616 wake_up_process(rescuer->task);
4622 struct workqueue_struct *alloc_workqueue(const char *fmt,
4624 int max_active, ...)
4626 size_t tbl_size = 0;
4628 struct workqueue_struct *wq;
4629 struct pool_workqueue *pwq;
4632 * Unbound && max_active == 1 used to imply ordered, which is no
4633 * longer the case on NUMA machines due to per-node pools. While
4634 * alloc_ordered_workqueue() is the right way to create an ordered
4635 * workqueue, keep the previous behavior to avoid subtle breakages
4638 if ((flags & WQ_UNBOUND) && max_active == 1)
4639 flags |= __WQ_ORDERED;
4641 /* see the comment above the definition of WQ_POWER_EFFICIENT */
4642 if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
4643 flags |= WQ_UNBOUND;
4645 /* allocate wq and format name */
4646 if (flags & WQ_UNBOUND)
4647 tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
4649 wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
4653 if (flags & WQ_UNBOUND) {
4654 wq->unbound_attrs = alloc_workqueue_attrs();
4655 if (!wq->unbound_attrs)
4659 va_start(args, max_active);
4660 vsnprintf(wq->name, sizeof(wq->name), fmt, args);
4663 max_active = max_active ?: WQ_DFL_ACTIVE;
4664 max_active = wq_clamp_max_active(max_active, flags, wq->name);
4668 wq->saved_max_active = max_active;
4669 mutex_init(&wq->mutex);
4670 atomic_set(&wq->nr_pwqs_to_flush, 0);
4671 INIT_LIST_HEAD(&wq->pwqs);
4672 INIT_LIST_HEAD(&wq->flusher_queue);
4673 INIT_LIST_HEAD(&wq->flusher_overflow);
4674 INIT_LIST_HEAD(&wq->maydays);
4676 wq_init_lockdep(wq);
4677 INIT_LIST_HEAD(&wq->list);
4679 if (alloc_and_link_pwqs(wq) < 0)
4680 goto err_unreg_lockdep;
4682 if (wq_online && init_rescuer(wq) < 0)
4685 if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
4689 * wq_pool_mutex protects global freeze state and workqueues list.
4690 * Grab it, adjust max_active and add the new @wq to workqueues
4693 mutex_lock(&wq_pool_mutex);
4695 mutex_lock(&wq->mutex);
4696 for_each_pwq(pwq, wq)
4697 pwq_adjust_max_active(pwq);
4698 mutex_unlock(&wq->mutex);
4700 list_add_tail_rcu(&wq->list, &workqueues);
4702 mutex_unlock(&wq_pool_mutex);
4707 wq_unregister_lockdep(wq);
4708 wq_free_lockdep(wq);
4710 free_workqueue_attrs(wq->unbound_attrs);
4714 destroy_workqueue(wq);
4717 EXPORT_SYMBOL_GPL(alloc_workqueue);
4719 static bool pwq_busy(struct pool_workqueue *pwq)
4723 for (i = 0; i < WORK_NR_COLORS; i++)
4724 if (pwq->nr_in_flight[i])
4727 if ((pwq != pwq->wq->dfl_pwq) && (pwq->refcnt > 1))
4729 if (pwq->nr_active || !list_empty(&pwq->inactive_works))
4736 * destroy_workqueue - safely terminate a workqueue
4737 * @wq: target workqueue
4739 * Safely destroy a workqueue. All work currently pending will be done first.
4741 void destroy_workqueue(struct workqueue_struct *wq)
4743 struct pool_workqueue *pwq;
4747 * Remove it from sysfs first so that sanity check failure doesn't
4748 * lead to sysfs name conflicts.
4750 workqueue_sysfs_unregister(wq);
4752 /* mark the workqueue destruction is in progress */
4753 mutex_lock(&wq->mutex);
4754 wq->flags |= __WQ_DESTROYING;
4755 mutex_unlock(&wq->mutex);
4757 /* drain it before proceeding with destruction */
4758 drain_workqueue(wq);
4760 /* kill rescuer, if sanity checks fail, leave it w/o rescuer */
4762 struct worker *rescuer = wq->rescuer;
4764 /* this prevents new queueing */
4765 raw_spin_lock_irq(&wq_mayday_lock);
4767 raw_spin_unlock_irq(&wq_mayday_lock);
4769 /* rescuer will empty maydays list before exiting */
4770 kthread_stop(rescuer->task);
4775 * Sanity checks - grab all the locks so that we wait for all
4776 * in-flight operations which may do put_pwq().
4778 mutex_lock(&wq_pool_mutex);
4779 mutex_lock(&wq->mutex);
4780 for_each_pwq(pwq, wq) {
4781 raw_spin_lock_irq(&pwq->pool->lock);
4782 if (WARN_ON(pwq_busy(pwq))) {
4783 pr_warn("%s: %s has the following busy pwq\n",
4784 __func__, wq->name);
4786 raw_spin_unlock_irq(&pwq->pool->lock);
4787 mutex_unlock(&wq->mutex);
4788 mutex_unlock(&wq_pool_mutex);
4789 show_one_workqueue(wq);
4792 raw_spin_unlock_irq(&pwq->pool->lock);
4794 mutex_unlock(&wq->mutex);
4797 * wq list is used to freeze wq, remove from list after
4798 * flushing is complete in case freeze races us.
4800 list_del_rcu(&wq->list);
4801 mutex_unlock(&wq_pool_mutex);
4803 if (!(wq->flags & WQ_UNBOUND)) {
4804 wq_unregister_lockdep(wq);
4806 * The base ref is never dropped on per-cpu pwqs. Directly
4807 * schedule RCU free.
4809 call_rcu(&wq->rcu, rcu_free_wq);
4812 * We're the sole accessor of @wq at this point. Directly
4813 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
4814 * @wq will be freed when the last pwq is released.
4816 for_each_node(node) {
4817 pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
4818 RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
4819 put_pwq_unlocked(pwq);
4823 * Put dfl_pwq. @wq may be freed any time after dfl_pwq is
4824 * put. Don't access it afterwards.
4828 put_pwq_unlocked(pwq);
4831 EXPORT_SYMBOL_GPL(destroy_workqueue);
4834 * workqueue_set_max_active - adjust max_active of a workqueue
4835 * @wq: target workqueue
4836 * @max_active: new max_active value.
4838 * Set max_active of @wq to @max_active.
4841 * Don't call from IRQ context.
4843 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4845 struct pool_workqueue *pwq;
4847 /* disallow meddling with max_active for ordered workqueues */
4848 if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
4851 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4853 mutex_lock(&wq->mutex);
4855 wq->flags &= ~__WQ_ORDERED;
4856 wq->saved_max_active = max_active;
4858 for_each_pwq(pwq, wq)
4859 pwq_adjust_max_active(pwq);
4861 mutex_unlock(&wq->mutex);
4863 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4866 * current_work - retrieve %current task's work struct
4868 * Determine if %current task is a workqueue worker and what it's working on.
4869 * Useful to find out the context that the %current task is running in.
4871 * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
4873 struct work_struct *current_work(void)
4875 struct worker *worker = current_wq_worker();
4877 return worker ? worker->current_work : NULL;
4879 EXPORT_SYMBOL(current_work);
4882 * current_is_workqueue_rescuer - is %current workqueue rescuer?
4884 * Determine whether %current is a workqueue rescuer. Can be used from
4885 * work functions to determine whether it's being run off the rescuer task.
4887 * Return: %true if %current is a workqueue rescuer. %false otherwise.
4889 bool current_is_workqueue_rescuer(void)
4891 struct worker *worker = current_wq_worker();
4893 return worker && worker->rescue_wq;
4897 * workqueue_congested - test whether a workqueue is congested
4898 * @cpu: CPU in question
4899 * @wq: target workqueue
4901 * Test whether @wq's cpu workqueue for @cpu is congested. There is
4902 * no synchronization around this function and the test result is
4903 * unreliable and only useful as advisory hints or for debugging.
4905 * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4906 * Note that both per-cpu and unbound workqueues may be associated with
4907 * multiple pool_workqueues which have separate congested states. A
4908 * workqueue being congested on one CPU doesn't mean the workqueue is also
4909 * contested on other CPUs / NUMA nodes.
4912 * %true if congested, %false otherwise.
4914 bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4916 struct pool_workqueue *pwq;
4922 if (cpu == WORK_CPU_UNBOUND)
4923 cpu = smp_processor_id();
4925 if (!(wq->flags & WQ_UNBOUND))
4926 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
4928 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4930 ret = !list_empty(&pwq->inactive_works);
4936 EXPORT_SYMBOL_GPL(workqueue_congested);
4939 * work_busy - test whether a work is currently pending or running
4940 * @work: the work to be tested
4942 * Test whether @work is currently pending or running. There is no
4943 * synchronization around this function and the test result is
4944 * unreliable and only useful as advisory hints or for debugging.
4947 * OR'd bitmask of WORK_BUSY_* bits.
4949 unsigned int work_busy(struct work_struct *work)
4951 struct worker_pool *pool;
4952 unsigned long flags;
4953 unsigned int ret = 0;
4955 if (work_pending(work))
4956 ret |= WORK_BUSY_PENDING;
4959 pool = get_work_pool(work);
4961 raw_spin_lock_irqsave(&pool->lock, flags);
4962 if (find_worker_executing_work(pool, work))
4963 ret |= WORK_BUSY_RUNNING;
4964 raw_spin_unlock_irqrestore(&pool->lock, flags);
4970 EXPORT_SYMBOL_GPL(work_busy);
4973 * set_worker_desc - set description for the current work item
4974 * @fmt: printf-style format string
4975 * @...: arguments for the format string
4977 * This function can be called by a running work function to describe what
4978 * the work item is about. If the worker task gets dumped, this
4979 * information will be printed out together to help debugging. The
4980 * description can be at most WORKER_DESC_LEN including the trailing '\0'.
4982 void set_worker_desc(const char *fmt, ...)
4984 struct worker *worker = current_wq_worker();
4988 va_start(args, fmt);
4989 vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
4993 EXPORT_SYMBOL_GPL(set_worker_desc);
4996 * print_worker_info - print out worker information and description
4997 * @log_lvl: the log level to use when printing
4998 * @task: target task
5000 * If @task is a worker and currently executing a work item, print out the
5001 * name of the workqueue being serviced and worker description set with
5002 * set_worker_desc() by the currently executing work item.
5004 * This function can be safely called on any task as long as the
5005 * task_struct itself is accessible. While safe, this function isn't
5006 * synchronized and may print out mixups or garbages of limited length.
5008 void print_worker_info(const char *log_lvl, struct task_struct *task)
5010 work_func_t *fn = NULL;
5011 char name[WQ_NAME_LEN] = { };
5012 char desc[WORKER_DESC_LEN] = { };
5013 struct pool_workqueue *pwq = NULL;
5014 struct workqueue_struct *wq = NULL;
5015 struct worker *worker;
5017 if (!(task->flags & PF_WQ_WORKER))
5021 * This function is called without any synchronization and @task
5022 * could be in any state. Be careful with dereferences.
5024 worker = kthread_probe_data(task);
5027 * Carefully copy the associated workqueue's workfn, name and desc.
5028 * Keep the original last '\0' in case the original is garbage.
5030 copy_from_kernel_nofault(&fn, &worker->current_func, sizeof(fn));
5031 copy_from_kernel_nofault(&pwq, &worker->current_pwq, sizeof(pwq));
5032 copy_from_kernel_nofault(&wq, &pwq->wq, sizeof(wq));
5033 copy_from_kernel_nofault(name, wq->name, sizeof(name) - 1);
5034 copy_from_kernel_nofault(desc, worker->desc, sizeof(desc) - 1);
5036 if (fn || name[0] || desc[0]) {
5037 printk("%sWorkqueue: %s %ps", log_lvl, name, fn);
5038 if (strcmp(name, desc))
5039 pr_cont(" (%s)", desc);
5044 static void pr_cont_pool_info(struct worker_pool *pool)
5046 pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
5047 if (pool->node != NUMA_NO_NODE)
5048 pr_cont(" node=%d", pool->node);
5049 pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
5052 struct pr_cont_work_struct {
5058 static void pr_cont_work_flush(bool comma, work_func_t func, struct pr_cont_work_struct *pcwsp)
5062 if (func == pcwsp->func) {
5066 if (pcwsp->ctr == 1)
5067 pr_cont("%s %ps", pcwsp->comma ? "," : "", pcwsp->func);
5069 pr_cont("%s %ld*%ps", pcwsp->comma ? "," : "", pcwsp->ctr, pcwsp->func);
5072 if ((long)func == -1L)
5074 pcwsp->comma = comma;
5079 static void pr_cont_work(bool comma, struct work_struct *work, struct pr_cont_work_struct *pcwsp)
5081 if (work->func == wq_barrier_func) {
5082 struct wq_barrier *barr;
5084 barr = container_of(work, struct wq_barrier, work);
5086 pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
5087 pr_cont("%s BAR(%d)", comma ? "," : "",
5088 task_pid_nr(barr->task));
5091 pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
5092 pr_cont_work_flush(comma, work->func, pcwsp);
5096 static void show_pwq(struct pool_workqueue *pwq)
5098 struct pr_cont_work_struct pcws = { .ctr = 0, };
5099 struct worker_pool *pool = pwq->pool;
5100 struct work_struct *work;
5101 struct worker *worker;
5102 bool has_in_flight = false, has_pending = false;
5105 pr_info(" pwq %d:", pool->id);
5106 pr_cont_pool_info(pool);
5108 pr_cont(" active=%d/%d refcnt=%d%s\n",
5109 pwq->nr_active, pwq->max_active, pwq->refcnt,
5110 !list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
5112 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
5113 if (worker->current_pwq == pwq) {
5114 has_in_flight = true;
5118 if (has_in_flight) {
5121 pr_info(" in-flight:");
5122 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
5123 if (worker->current_pwq != pwq)
5126 pr_cont("%s %d%s:%ps", comma ? "," : "",
5127 task_pid_nr(worker->task),
5128 worker->rescue_wq ? "(RESCUER)" : "",
5129 worker->current_func);
5130 list_for_each_entry(work, &worker->scheduled, entry)
5131 pr_cont_work(false, work, &pcws);
5132 pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
5138 list_for_each_entry(work, &pool->worklist, entry) {
5139 if (get_work_pwq(work) == pwq) {
5147 pr_info(" pending:");
5148 list_for_each_entry(work, &pool->worklist, entry) {
5149 if (get_work_pwq(work) != pwq)
5152 pr_cont_work(comma, work, &pcws);
5153 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
5155 pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
5159 if (!list_empty(&pwq->inactive_works)) {
5162 pr_info(" inactive:");
5163 list_for_each_entry(work, &pwq->inactive_works, entry) {
5164 pr_cont_work(comma, work, &pcws);
5165 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
5167 pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
5173 * show_one_workqueue - dump state of specified workqueue
5174 * @wq: workqueue whose state will be printed
5176 void show_one_workqueue(struct workqueue_struct *wq)
5178 struct pool_workqueue *pwq;
5180 unsigned long flags;
5182 for_each_pwq(pwq, wq) {
5183 if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
5188 if (idle) /* Nothing to print for idle workqueue */
5191 pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
5193 for_each_pwq(pwq, wq) {
5194 raw_spin_lock_irqsave(&pwq->pool->lock, flags);
5195 if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
5197 * Defer printing to avoid deadlocks in console
5198 * drivers that queue work while holding locks
5199 * also taken in their write paths.
5201 printk_deferred_enter();
5203 printk_deferred_exit();
5205 raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
5207 * We could be printing a lot from atomic context, e.g.
5208 * sysrq-t -> show_all_workqueues(). Avoid triggering
5211 touch_nmi_watchdog();
5217 * show_one_worker_pool - dump state of specified worker pool
5218 * @pool: worker pool whose state will be printed
5220 static void show_one_worker_pool(struct worker_pool *pool)
5222 struct worker *worker;
5224 unsigned long flags;
5225 unsigned long hung = 0;
5227 raw_spin_lock_irqsave(&pool->lock, flags);
5228 if (pool->nr_workers == pool->nr_idle)
5231 /* How long the first pending work is waiting for a worker. */
5232 if (!list_empty(&pool->worklist))
5233 hung = jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000;
5236 * Defer printing to avoid deadlocks in console drivers that
5237 * queue work while holding locks also taken in their write
5240 printk_deferred_enter();
5241 pr_info("pool %d:", pool->id);
5242 pr_cont_pool_info(pool);
5243 pr_cont(" hung=%lus workers=%d", hung, pool->nr_workers);
5245 pr_cont(" manager: %d",
5246 task_pid_nr(pool->manager->task));
5247 list_for_each_entry(worker, &pool->idle_list, entry) {
5248 pr_cont(" %s%d", first ? "idle: " : "",
5249 task_pid_nr(worker->task));
5253 printk_deferred_exit();
5255 raw_spin_unlock_irqrestore(&pool->lock, flags);
5257 * We could be printing a lot from atomic context, e.g.
5258 * sysrq-t -> show_all_workqueues(). Avoid triggering
5261 touch_nmi_watchdog();
5266 * show_all_workqueues - dump workqueue state
5268 * Called from a sysrq handler and prints out all busy workqueues and pools.
5270 void show_all_workqueues(void)
5272 struct workqueue_struct *wq;
5273 struct worker_pool *pool;
5278 pr_info("Showing busy workqueues and worker pools:\n");
5280 list_for_each_entry_rcu(wq, &workqueues, list)
5281 show_one_workqueue(wq);
5283 for_each_pool(pool, pi)
5284 show_one_worker_pool(pool);
5290 * show_freezable_workqueues - dump freezable workqueue state
5292 * Called from try_to_freeze_tasks() and prints out all freezable workqueues
5295 void show_freezable_workqueues(void)
5297 struct workqueue_struct *wq;
5301 pr_info("Showing freezable workqueues that are still busy:\n");
5303 list_for_each_entry_rcu(wq, &workqueues, list) {
5304 if (!(wq->flags & WQ_FREEZABLE))
5306 show_one_workqueue(wq);
5312 /* used to show worker information through /proc/PID/{comm,stat,status} */
5313 void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
5317 /* always show the actual comm */
5318 off = strscpy(buf, task->comm, size);
5322 /* stabilize PF_WQ_WORKER and worker pool association */
5323 mutex_lock(&wq_pool_attach_mutex);
5325 if (task->flags & PF_WQ_WORKER) {
5326 struct worker *worker = kthread_data(task);
5327 struct worker_pool *pool = worker->pool;
5330 raw_spin_lock_irq(&pool->lock);
5332 * ->desc tracks information (wq name or
5333 * set_worker_desc()) for the latest execution. If
5334 * current, prepend '+', otherwise '-'.
5336 if (worker->desc[0] != '\0') {
5337 if (worker->current_work)
5338 scnprintf(buf + off, size - off, "+%s",
5341 scnprintf(buf + off, size - off, "-%s",
5344 raw_spin_unlock_irq(&pool->lock);
5348 mutex_unlock(&wq_pool_attach_mutex);
5356 * There are two challenges in supporting CPU hotplug. Firstly, there
5357 * are a lot of assumptions on strong associations among work, pwq and
5358 * pool which make migrating pending and scheduled works very
5359 * difficult to implement without impacting hot paths. Secondly,
5360 * worker pools serve mix of short, long and very long running works making
5361 * blocked draining impractical.
5363 * This is solved by allowing the pools to be disassociated from the CPU
5364 * running as an unbound one and allowing it to be reattached later if the
5365 * cpu comes back online.
5368 static void unbind_workers(int cpu)
5370 struct worker_pool *pool;
5371 struct worker *worker;
5373 for_each_cpu_worker_pool(pool, cpu) {
5374 mutex_lock(&wq_pool_attach_mutex);
5375 raw_spin_lock_irq(&pool->lock);
5378 * We've blocked all attach/detach operations. Make all workers
5379 * unbound and set DISASSOCIATED. Before this, all workers
5380 * must be on the cpu. After this, they may become diasporas.
5381 * And the preemption disabled section in their sched callbacks
5382 * are guaranteed to see WORKER_UNBOUND since the code here
5383 * is on the same cpu.
5385 for_each_pool_worker(worker, pool)
5386 worker->flags |= WORKER_UNBOUND;
5388 pool->flags |= POOL_DISASSOCIATED;
5391 * The handling of nr_running in sched callbacks are disabled
5392 * now. Zap nr_running. After this, nr_running stays zero and
5393 * need_more_worker() and keep_working() are always true as
5394 * long as the worklist is not empty. This pool now behaves as
5395 * an unbound (in terms of concurrency management) pool which
5396 * are served by workers tied to the pool.
5398 pool->nr_running = 0;
5401 * With concurrency management just turned off, a busy
5402 * worker blocking could lead to lengthy stalls. Kick off
5403 * unbound chain execution of currently pending work items.
5405 wake_up_worker(pool);
5407 raw_spin_unlock_irq(&pool->lock);
5409 for_each_pool_worker(worker, pool)
5410 unbind_worker(worker);
5412 mutex_unlock(&wq_pool_attach_mutex);
5417 * rebind_workers - rebind all workers of a pool to the associated CPU
5418 * @pool: pool of interest
5420 * @pool->cpu is coming online. Rebind all workers to the CPU.
5422 static void rebind_workers(struct worker_pool *pool)
5424 struct worker *worker;
5426 lockdep_assert_held(&wq_pool_attach_mutex);
5429 * Restore CPU affinity of all workers. As all idle workers should
5430 * be on the run-queue of the associated CPU before any local
5431 * wake-ups for concurrency management happen, restore CPU affinity
5432 * of all workers first and then clear UNBOUND. As we're called
5433 * from CPU_ONLINE, the following shouldn't fail.
5435 for_each_pool_worker(worker, pool) {
5436 kthread_set_per_cpu(worker->task, pool->cpu);
5437 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
5438 pool->attrs->cpumask) < 0);
5441 raw_spin_lock_irq(&pool->lock);
5443 pool->flags &= ~POOL_DISASSOCIATED;
5445 for_each_pool_worker(worker, pool) {
5446 unsigned int worker_flags = worker->flags;
5449 * We want to clear UNBOUND but can't directly call
5450 * worker_clr_flags() or adjust nr_running. Atomically
5451 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
5452 * @worker will clear REBOUND using worker_clr_flags() when
5453 * it initiates the next execution cycle thus restoring
5454 * concurrency management. Note that when or whether
5455 * @worker clears REBOUND doesn't affect correctness.
5457 * WRITE_ONCE() is necessary because @worker->flags may be
5458 * tested without holding any lock in
5459 * wq_worker_running(). Without it, NOT_RUNNING test may
5460 * fail incorrectly leading to premature concurrency
5461 * management operations.
5463 WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
5464 worker_flags |= WORKER_REBOUND;
5465 worker_flags &= ~WORKER_UNBOUND;
5466 WRITE_ONCE(worker->flags, worker_flags);
5469 raw_spin_unlock_irq(&pool->lock);
5473 * restore_unbound_workers_cpumask - restore cpumask of unbound workers
5474 * @pool: unbound pool of interest
5475 * @cpu: the CPU which is coming up
5477 * An unbound pool may end up with a cpumask which doesn't have any online
5478 * CPUs. When a worker of such pool get scheduled, the scheduler resets
5479 * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
5480 * online CPU before, cpus_allowed of all its workers should be restored.
5482 static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
5484 static cpumask_t cpumask;
5485 struct worker *worker;
5487 lockdep_assert_held(&wq_pool_attach_mutex);
5489 /* is @cpu allowed for @pool? */
5490 if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
5493 cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
5495 /* as we're called from CPU_ONLINE, the following shouldn't fail */
5496 for_each_pool_worker(worker, pool)
5497 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
5500 int workqueue_prepare_cpu(unsigned int cpu)
5502 struct worker_pool *pool;
5504 for_each_cpu_worker_pool(pool, cpu) {
5505 if (pool->nr_workers)
5507 if (!create_worker(pool))
5513 int workqueue_online_cpu(unsigned int cpu)
5515 struct worker_pool *pool;
5516 struct workqueue_struct *wq;
5519 mutex_lock(&wq_pool_mutex);
5521 for_each_pool(pool, pi) {
5522 mutex_lock(&wq_pool_attach_mutex);
5524 if (pool->cpu == cpu)
5525 rebind_workers(pool);
5526 else if (pool->cpu < 0)
5527 restore_unbound_workers_cpumask(pool, cpu);
5529 mutex_unlock(&wq_pool_attach_mutex);
5532 /* update NUMA affinity of unbound workqueues */
5533 list_for_each_entry(wq, &workqueues, list)
5534 wq_update_unbound_numa(wq, cpu, true);
5536 mutex_unlock(&wq_pool_mutex);
5540 int workqueue_offline_cpu(unsigned int cpu)
5542 struct workqueue_struct *wq;
5544 /* unbinding per-cpu workers should happen on the local CPU */
5545 if (WARN_ON(cpu != smp_processor_id()))
5548 unbind_workers(cpu);
5550 /* update NUMA affinity of unbound workqueues */
5551 mutex_lock(&wq_pool_mutex);
5552 list_for_each_entry(wq, &workqueues, list)
5553 wq_update_unbound_numa(wq, cpu, false);
5554 mutex_unlock(&wq_pool_mutex);
5559 struct work_for_cpu {
5560 struct work_struct work;
5566 static void work_for_cpu_fn(struct work_struct *work)
5568 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
5570 wfc->ret = wfc->fn(wfc->arg);
5574 * work_on_cpu - run a function in thread context on a particular cpu
5575 * @cpu: the cpu to run on
5576 * @fn: the function to run
5577 * @arg: the function arg
5579 * It is up to the caller to ensure that the cpu doesn't go offline.
5580 * The caller must not hold any locks which would prevent @fn from completing.
5582 * Return: The value @fn returns.
5584 long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
5586 struct work_for_cpu wfc = { .fn = fn, .arg = arg };
5588 INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
5589 schedule_work_on(cpu, &wfc.work);
5590 flush_work(&wfc.work);
5591 destroy_work_on_stack(&wfc.work);
5594 EXPORT_SYMBOL_GPL(work_on_cpu);
5597 * work_on_cpu_safe - run a function in thread context on a particular cpu
5598 * @cpu: the cpu to run on
5599 * @fn: the function to run
5600 * @arg: the function argument
5602 * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
5603 * any locks which would prevent @fn from completing.
5605 * Return: The value @fn returns.
5607 long work_on_cpu_safe(int cpu, long (*fn)(void *), void *arg)
5612 if (cpu_online(cpu))
5613 ret = work_on_cpu(cpu, fn, arg);
5617 EXPORT_SYMBOL_GPL(work_on_cpu_safe);
5618 #endif /* CONFIG_SMP */
5620 #ifdef CONFIG_FREEZER
5623 * freeze_workqueues_begin - begin freezing workqueues
5625 * Start freezing workqueues. After this function returns, all freezable
5626 * workqueues will queue new works to their inactive_works list instead of
5630 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5632 void freeze_workqueues_begin(void)
5634 struct workqueue_struct *wq;
5635 struct pool_workqueue *pwq;
5637 mutex_lock(&wq_pool_mutex);
5639 WARN_ON_ONCE(workqueue_freezing);
5640 workqueue_freezing = true;
5642 list_for_each_entry(wq, &workqueues, list) {
5643 mutex_lock(&wq->mutex);
5644 for_each_pwq(pwq, wq)
5645 pwq_adjust_max_active(pwq);
5646 mutex_unlock(&wq->mutex);
5649 mutex_unlock(&wq_pool_mutex);
5653 * freeze_workqueues_busy - are freezable workqueues still busy?
5655 * Check whether freezing is complete. This function must be called
5656 * between freeze_workqueues_begin() and thaw_workqueues().
5659 * Grabs and releases wq_pool_mutex.
5662 * %true if some freezable workqueues are still busy. %false if freezing
5665 bool freeze_workqueues_busy(void)
5668 struct workqueue_struct *wq;
5669 struct pool_workqueue *pwq;
5671 mutex_lock(&wq_pool_mutex);
5673 WARN_ON_ONCE(!workqueue_freezing);
5675 list_for_each_entry(wq, &workqueues, list) {
5676 if (!(wq->flags & WQ_FREEZABLE))
5679 * nr_active is monotonically decreasing. It's safe
5680 * to peek without lock.
5683 for_each_pwq(pwq, wq) {
5684 WARN_ON_ONCE(pwq->nr_active < 0);
5685 if (pwq->nr_active) {
5694 mutex_unlock(&wq_pool_mutex);
5699 * thaw_workqueues - thaw workqueues
5701 * Thaw workqueues. Normal queueing is restored and all collected
5702 * frozen works are transferred to their respective pool worklists.
5705 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5707 void thaw_workqueues(void)
5709 struct workqueue_struct *wq;
5710 struct pool_workqueue *pwq;
5712 mutex_lock(&wq_pool_mutex);
5714 if (!workqueue_freezing)
5717 workqueue_freezing = false;
5719 /* restore max_active and repopulate worklist */
5720 list_for_each_entry(wq, &workqueues, list) {
5721 mutex_lock(&wq->mutex);
5722 for_each_pwq(pwq, wq)
5723 pwq_adjust_max_active(pwq);
5724 mutex_unlock(&wq->mutex);
5728 mutex_unlock(&wq_pool_mutex);
5730 #endif /* CONFIG_FREEZER */
5732 static int workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask)
5736 struct workqueue_struct *wq;
5737 struct apply_wqattrs_ctx *ctx, *n;
5739 lockdep_assert_held(&wq_pool_mutex);
5741 list_for_each_entry(wq, &workqueues, list) {
5742 if (!(wq->flags & WQ_UNBOUND))
5744 /* creating multiple pwqs breaks ordering guarantee */
5745 if (wq->flags & __WQ_ORDERED)
5748 ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs, unbound_cpumask);
5754 list_add_tail(&ctx->list, &ctxs);
5757 list_for_each_entry_safe(ctx, n, &ctxs, list) {
5759 apply_wqattrs_commit(ctx);
5760 apply_wqattrs_cleanup(ctx);
5764 mutex_lock(&wq_pool_attach_mutex);
5765 cpumask_copy(wq_unbound_cpumask, unbound_cpumask);
5766 mutex_unlock(&wq_pool_attach_mutex);
5772 * workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
5773 * @cpumask: the cpumask to set
5775 * The low-level workqueues cpumask is a global cpumask that limits
5776 * the affinity of all unbound workqueues. This function check the @cpumask
5777 * and apply it to all unbound workqueues and updates all pwqs of them.
5779 * Return: 0 - Success
5780 * -EINVAL - Invalid @cpumask
5781 * -ENOMEM - Failed to allocate memory for attrs or pwqs.
5783 int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
5788 * Not excluding isolated cpus on purpose.
5789 * If the user wishes to include them, we allow that.
5791 cpumask_and(cpumask, cpumask, cpu_possible_mask);
5792 if (!cpumask_empty(cpumask)) {
5793 apply_wqattrs_lock();
5794 if (cpumask_equal(cpumask, wq_unbound_cpumask)) {
5799 ret = workqueue_apply_unbound_cpumask(cpumask);
5802 apply_wqattrs_unlock();
5810 * Workqueues with WQ_SYSFS flag set is visible to userland via
5811 * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
5812 * following attributes.
5814 * per_cpu RO bool : whether the workqueue is per-cpu or unbound
5815 * max_active RW int : maximum number of in-flight work items
5817 * Unbound workqueues have the following extra attributes.
5819 * pool_ids RO int : the associated pool IDs for each node
5820 * nice RW int : nice value of the workers
5821 * cpumask RW mask : bitmask of allowed CPUs for the workers
5822 * numa RW bool : whether enable NUMA affinity
5825 struct workqueue_struct *wq;
5829 static struct workqueue_struct *dev_to_wq(struct device *dev)
5831 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
5836 static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
5839 struct workqueue_struct *wq = dev_to_wq(dev);
5841 return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
5843 static DEVICE_ATTR_RO(per_cpu);
5845 static ssize_t max_active_show(struct device *dev,
5846 struct device_attribute *attr, char *buf)
5848 struct workqueue_struct *wq = dev_to_wq(dev);
5850 return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
5853 static ssize_t max_active_store(struct device *dev,
5854 struct device_attribute *attr, const char *buf,
5857 struct workqueue_struct *wq = dev_to_wq(dev);
5860 if (sscanf(buf, "%d", &val) != 1 || val <= 0)
5863 workqueue_set_max_active(wq, val);
5866 static DEVICE_ATTR_RW(max_active);
5868 static struct attribute *wq_sysfs_attrs[] = {
5869 &dev_attr_per_cpu.attr,
5870 &dev_attr_max_active.attr,
5873 ATTRIBUTE_GROUPS(wq_sysfs);
5875 static ssize_t wq_pool_ids_show(struct device *dev,
5876 struct device_attribute *attr, char *buf)
5878 struct workqueue_struct *wq = dev_to_wq(dev);
5879 const char *delim = "";
5880 int node, written = 0;
5884 for_each_node(node) {
5885 written += scnprintf(buf + written, PAGE_SIZE - written,
5886 "%s%d:%d", delim, node,
5887 unbound_pwq_by_node(wq, node)->pool->id);
5890 written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
5897 static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
5900 struct workqueue_struct *wq = dev_to_wq(dev);
5903 mutex_lock(&wq->mutex);
5904 written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
5905 mutex_unlock(&wq->mutex);
5910 /* prepare workqueue_attrs for sysfs store operations */
5911 static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
5913 struct workqueue_attrs *attrs;
5915 lockdep_assert_held(&wq_pool_mutex);
5917 attrs = alloc_workqueue_attrs();
5921 copy_workqueue_attrs(attrs, wq->unbound_attrs);
5925 static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
5926 const char *buf, size_t count)
5928 struct workqueue_struct *wq = dev_to_wq(dev);
5929 struct workqueue_attrs *attrs;
5932 apply_wqattrs_lock();
5934 attrs = wq_sysfs_prep_attrs(wq);
5938 if (sscanf(buf, "%d", &attrs->nice) == 1 &&
5939 attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
5940 ret = apply_workqueue_attrs_locked(wq, attrs);
5945 apply_wqattrs_unlock();
5946 free_workqueue_attrs(attrs);
5947 return ret ?: count;
5950 static ssize_t wq_cpumask_show(struct device *dev,
5951 struct device_attribute *attr, char *buf)
5953 struct workqueue_struct *wq = dev_to_wq(dev);
5956 mutex_lock(&wq->mutex);
5957 written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
5958 cpumask_pr_args(wq->unbound_attrs->cpumask));
5959 mutex_unlock(&wq->mutex);
5963 static ssize_t wq_cpumask_store(struct device *dev,
5964 struct device_attribute *attr,
5965 const char *buf, size_t count)
5967 struct workqueue_struct *wq = dev_to_wq(dev);
5968 struct workqueue_attrs *attrs;
5971 apply_wqattrs_lock();
5973 attrs = wq_sysfs_prep_attrs(wq);
5977 ret = cpumask_parse(buf, attrs->cpumask);
5979 ret = apply_workqueue_attrs_locked(wq, attrs);
5982 apply_wqattrs_unlock();
5983 free_workqueue_attrs(attrs);
5984 return ret ?: count;
5987 static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
5990 struct workqueue_struct *wq = dev_to_wq(dev);
5993 mutex_lock(&wq->mutex);
5994 written = scnprintf(buf, PAGE_SIZE, "%d\n",
5995 !wq->unbound_attrs->no_numa);
5996 mutex_unlock(&wq->mutex);
6001 static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
6002 const char *buf, size_t count)
6004 struct workqueue_struct *wq = dev_to_wq(dev);
6005 struct workqueue_attrs *attrs;
6006 int v, ret = -ENOMEM;
6008 apply_wqattrs_lock();
6010 attrs = wq_sysfs_prep_attrs(wq);
6015 if (sscanf(buf, "%d", &v) == 1) {
6016 attrs->no_numa = !v;
6017 ret = apply_workqueue_attrs_locked(wq, attrs);
6021 apply_wqattrs_unlock();
6022 free_workqueue_attrs(attrs);
6023 return ret ?: count;
6026 static struct device_attribute wq_sysfs_unbound_attrs[] = {
6027 __ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
6028 __ATTR(nice, 0644, wq_nice_show, wq_nice_store),
6029 __ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
6030 __ATTR(numa, 0644, wq_numa_show, wq_numa_store),
6034 static struct bus_type wq_subsys = {
6035 .name = "workqueue",
6036 .dev_groups = wq_sysfs_groups,
6039 static ssize_t wq_unbound_cpumask_show(struct device *dev,
6040 struct device_attribute *attr, char *buf)
6044 mutex_lock(&wq_pool_mutex);
6045 written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
6046 cpumask_pr_args(wq_unbound_cpumask));
6047 mutex_unlock(&wq_pool_mutex);
6052 static ssize_t wq_unbound_cpumask_store(struct device *dev,
6053 struct device_attribute *attr, const char *buf, size_t count)
6055 cpumask_var_t cpumask;
6058 if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
6061 ret = cpumask_parse(buf, cpumask);
6063 ret = workqueue_set_unbound_cpumask(cpumask);
6065 free_cpumask_var(cpumask);
6066 return ret ? ret : count;
6069 static struct device_attribute wq_sysfs_cpumask_attr =
6070 __ATTR(cpumask, 0644, wq_unbound_cpumask_show,
6071 wq_unbound_cpumask_store);
6073 static int __init wq_sysfs_init(void)
6075 struct device *dev_root;
6078 err = subsys_virtual_register(&wq_subsys, NULL);
6082 dev_root = bus_get_dev_root(&wq_subsys);
6084 err = device_create_file(dev_root, &wq_sysfs_cpumask_attr);
6085 put_device(dev_root);
6089 core_initcall(wq_sysfs_init);
6091 static void wq_device_release(struct device *dev)
6093 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
6099 * workqueue_sysfs_register - make a workqueue visible in sysfs
6100 * @wq: the workqueue to register
6102 * Expose @wq in sysfs under /sys/bus/workqueue/devices.
6103 * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
6104 * which is the preferred method.
6106 * Workqueue user should use this function directly iff it wants to apply
6107 * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
6108 * apply_workqueue_attrs() may race against userland updating the
6111 * Return: 0 on success, -errno on failure.
6113 int workqueue_sysfs_register(struct workqueue_struct *wq)
6115 struct wq_device *wq_dev;
6119 * Adjusting max_active or creating new pwqs by applying
6120 * attributes breaks ordering guarantee. Disallow exposing ordered
6123 if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
6126 wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
6131 wq_dev->dev.bus = &wq_subsys;
6132 wq_dev->dev.release = wq_device_release;
6133 dev_set_name(&wq_dev->dev, "%s", wq->name);
6136 * unbound_attrs are created separately. Suppress uevent until
6137 * everything is ready.
6139 dev_set_uevent_suppress(&wq_dev->dev, true);
6141 ret = device_register(&wq_dev->dev);
6143 put_device(&wq_dev->dev);
6148 if (wq->flags & WQ_UNBOUND) {
6149 struct device_attribute *attr;
6151 for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
6152 ret = device_create_file(&wq_dev->dev, attr);
6154 device_unregister(&wq_dev->dev);
6161 dev_set_uevent_suppress(&wq_dev->dev, false);
6162 kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
6167 * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
6168 * @wq: the workqueue to unregister
6170 * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
6172 static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
6174 struct wq_device *wq_dev = wq->wq_dev;
6180 device_unregister(&wq_dev->dev);
6182 #else /* CONFIG_SYSFS */
6183 static void workqueue_sysfs_unregister(struct workqueue_struct *wq) { }
6184 #endif /* CONFIG_SYSFS */
6187 * Workqueue watchdog.
6189 * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
6190 * flush dependency, a concurrency managed work item which stays RUNNING
6191 * indefinitely. Workqueue stalls can be very difficult to debug as the
6192 * usual warning mechanisms don't trigger and internal workqueue state is
6195 * Workqueue watchdog monitors all worker pools periodically and dumps
6196 * state if some pools failed to make forward progress for a while where
6197 * forward progress is defined as the first item on ->worklist changing.
6199 * This mechanism is controlled through the kernel parameter
6200 * "workqueue.watchdog_thresh" which can be updated at runtime through the
6201 * corresponding sysfs parameter file.
6203 #ifdef CONFIG_WQ_WATCHDOG
6205 static unsigned long wq_watchdog_thresh = 30;
6206 static struct timer_list wq_watchdog_timer;
6208 static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
6209 static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
6212 * Show workers that might prevent the processing of pending work items.
6213 * The only candidates are CPU-bound workers in the running state.
6214 * Pending work items should be handled by another idle worker
6215 * in all other situations.
6217 static void show_cpu_pool_hog(struct worker_pool *pool)
6219 struct worker *worker;
6220 unsigned long flags;
6223 raw_spin_lock_irqsave(&pool->lock, flags);
6225 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
6226 if (task_is_running(worker->task)) {
6228 * Defer printing to avoid deadlocks in console
6229 * drivers that queue work while holding locks
6230 * also taken in their write paths.
6232 printk_deferred_enter();
6234 pr_info("pool %d:\n", pool->id);
6235 sched_show_task(worker->task);
6237 printk_deferred_exit();
6241 raw_spin_unlock_irqrestore(&pool->lock, flags);
6244 static void show_cpu_pools_hogs(void)
6246 struct worker_pool *pool;
6249 pr_info("Showing backtraces of running workers in stalled CPU-bound worker pools:\n");
6253 for_each_pool(pool, pi) {
6254 if (pool->cpu_stall)
6255 show_cpu_pool_hog(pool);
6262 static void wq_watchdog_reset_touched(void)
6266 wq_watchdog_touched = jiffies;
6267 for_each_possible_cpu(cpu)
6268 per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
6271 static void wq_watchdog_timer_fn(struct timer_list *unused)
6273 unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
6274 bool lockup_detected = false;
6275 bool cpu_pool_stall = false;
6276 unsigned long now = jiffies;
6277 struct worker_pool *pool;
6285 for_each_pool(pool, pi) {
6286 unsigned long pool_ts, touched, ts;
6288 pool->cpu_stall = false;
6289 if (list_empty(&pool->worklist))
6293 * If a virtual machine is stopped by the host it can look to
6294 * the watchdog like a stall.
6296 kvm_check_and_clear_guest_paused();
6298 /* get the latest of pool and touched timestamps */
6300 touched = READ_ONCE(per_cpu(wq_watchdog_touched_cpu, pool->cpu));
6302 touched = READ_ONCE(wq_watchdog_touched);
6303 pool_ts = READ_ONCE(pool->watchdog_ts);
6305 if (time_after(pool_ts, touched))
6311 if (time_after(now, ts + thresh)) {
6312 lockup_detected = true;
6313 if (pool->cpu >= 0) {
6314 pool->cpu_stall = true;
6315 cpu_pool_stall = true;
6317 pr_emerg("BUG: workqueue lockup - pool");
6318 pr_cont_pool_info(pool);
6319 pr_cont(" stuck for %us!\n",
6320 jiffies_to_msecs(now - pool_ts) / 1000);
6328 if (lockup_detected)
6329 show_all_workqueues();
6332 show_cpu_pools_hogs();
6334 wq_watchdog_reset_touched();
6335 mod_timer(&wq_watchdog_timer, jiffies + thresh);
6338 notrace void wq_watchdog_touch(int cpu)
6341 per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
6343 wq_watchdog_touched = jiffies;
6346 static void wq_watchdog_set_thresh(unsigned long thresh)
6348 wq_watchdog_thresh = 0;
6349 del_timer_sync(&wq_watchdog_timer);
6352 wq_watchdog_thresh = thresh;
6353 wq_watchdog_reset_touched();
6354 mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
6358 static int wq_watchdog_param_set_thresh(const char *val,
6359 const struct kernel_param *kp)
6361 unsigned long thresh;
6364 ret = kstrtoul(val, 0, &thresh);
6369 wq_watchdog_set_thresh(thresh);
6371 wq_watchdog_thresh = thresh;
6376 static const struct kernel_param_ops wq_watchdog_thresh_ops = {
6377 .set = wq_watchdog_param_set_thresh,
6378 .get = param_get_ulong,
6381 module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
6384 static void wq_watchdog_init(void)
6386 timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
6387 wq_watchdog_set_thresh(wq_watchdog_thresh);
6390 #else /* CONFIG_WQ_WATCHDOG */
6392 static inline void wq_watchdog_init(void) { }
6394 #endif /* CONFIG_WQ_WATCHDOG */
6396 static void __init wq_numa_init(void)
6401 if (num_possible_nodes() <= 1)
6404 if (wq_disable_numa) {
6405 pr_info("workqueue: NUMA affinity support disabled\n");
6409 for_each_possible_cpu(cpu) {
6410 if (WARN_ON(cpu_to_node(cpu) == NUMA_NO_NODE)) {
6411 pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
6416 wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs();
6417 BUG_ON(!wq_update_unbound_numa_attrs_buf);
6420 * We want masks of possible CPUs of each node which isn't readily
6421 * available. Build one from cpu_to_node() which should have been
6422 * fully initialized by now.
6424 tbl = kcalloc(nr_node_ids, sizeof(tbl[0]), GFP_KERNEL);
6428 BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
6429 node_online(node) ? node : NUMA_NO_NODE));
6431 for_each_possible_cpu(cpu) {
6432 node = cpu_to_node(cpu);
6433 cpumask_set_cpu(cpu, tbl[node]);
6436 wq_numa_possible_cpumask = tbl;
6437 wq_numa_enabled = true;
6441 * workqueue_init_early - early init for workqueue subsystem
6443 * This is the first half of two-staged workqueue subsystem initialization
6444 * and invoked as soon as the bare basics - memory allocation, cpumasks and
6445 * idr are up. It sets up all the data structures and system workqueues
6446 * and allows early boot code to create workqueues and queue/cancel work
6447 * items. Actual work item execution starts only after kthreads can be
6448 * created and scheduled right before early initcalls.
6450 void __init workqueue_init_early(void)
6452 int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
6455 BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
6457 BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
6458 cpumask_copy(wq_unbound_cpumask, housekeeping_cpumask(HK_TYPE_WQ));
6459 cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, housekeeping_cpumask(HK_TYPE_DOMAIN));
6461 pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
6463 /* initialize CPU pools */
6464 for_each_possible_cpu(cpu) {
6465 struct worker_pool *pool;
6468 for_each_cpu_worker_pool(pool, cpu) {
6469 BUG_ON(init_worker_pool(pool));
6471 cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
6472 pool->attrs->nice = std_nice[i++];
6473 pool->node = cpu_to_node(cpu);
6476 mutex_lock(&wq_pool_mutex);
6477 BUG_ON(worker_pool_assign_id(pool));
6478 mutex_unlock(&wq_pool_mutex);
6482 /* create default unbound and ordered wq attrs */
6483 for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
6484 struct workqueue_attrs *attrs;
6486 BUG_ON(!(attrs = alloc_workqueue_attrs()));
6487 attrs->nice = std_nice[i];
6488 unbound_std_wq_attrs[i] = attrs;
6491 * An ordered wq should have only one pwq as ordering is
6492 * guaranteed by max_active which is enforced by pwqs.
6493 * Turn off NUMA so that dfl_pwq is used for all nodes.
6495 BUG_ON(!(attrs = alloc_workqueue_attrs()));
6496 attrs->nice = std_nice[i];
6497 attrs->no_numa = true;
6498 ordered_wq_attrs[i] = attrs;
6501 system_wq = alloc_workqueue("events", 0, 0);
6502 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
6503 system_long_wq = alloc_workqueue("events_long", 0, 0);
6504 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
6505 WQ_UNBOUND_MAX_ACTIVE);
6506 system_freezable_wq = alloc_workqueue("events_freezable",
6508 system_power_efficient_wq = alloc_workqueue("events_power_efficient",
6509 WQ_POWER_EFFICIENT, 0);
6510 system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
6511 WQ_FREEZABLE | WQ_POWER_EFFICIENT,
6513 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
6514 !system_unbound_wq || !system_freezable_wq ||
6515 !system_power_efficient_wq ||
6516 !system_freezable_power_efficient_wq);
6519 static void __init wq_cpu_intensive_thresh_init(void)
6521 unsigned long thresh;
6524 /* if the user set it to a specific value, keep it */
6525 if (wq_cpu_intensive_thresh_us != ULONG_MAX)
6529 * The default of 10ms is derived from the fact that most modern (as of
6530 * 2023) processors can do a lot in 10ms and that it's just below what
6531 * most consider human-perceivable. However, the kernel also runs on a
6532 * lot slower CPUs including microcontrollers where the threshold is way
6535 * Let's scale up the threshold upto 1 second if BogoMips is below 4000.
6536 * This is by no means accurate but it doesn't have to be. The mechanism
6537 * is still useful even when the threshold is fully scaled up. Also, as
6538 * the reports would usually be applicable to everyone, some machines
6539 * operating on longer thresholds won't significantly diminish their
6542 thresh = 10 * USEC_PER_MSEC;
6544 /* see init/calibrate.c for lpj -> BogoMIPS calculation */
6545 bogo = max_t(unsigned long, loops_per_jiffy / 500000 * HZ, 1);
6547 thresh = min_t(unsigned long, thresh * 4000 / bogo, USEC_PER_SEC);
6549 pr_debug("wq_cpu_intensive_thresh: lpj=%lu BogoMIPS=%lu thresh_us=%lu\n",
6550 loops_per_jiffy, bogo, thresh);
6552 wq_cpu_intensive_thresh_us = thresh;
6556 * workqueue_init - bring workqueue subsystem fully online
6558 * This is the latter half of two-staged workqueue subsystem initialization
6559 * and invoked as soon as kthreads can be created and scheduled.
6560 * Workqueues have been created and work items queued on them, but there
6561 * are no kworkers executing the work items yet. Populate the worker pools
6562 * with the initial workers and enable future kworker creations.
6564 void __init workqueue_init(void)
6566 struct workqueue_struct *wq;
6567 struct worker_pool *pool;
6570 wq_cpu_intensive_thresh_init();
6573 * It'd be simpler to initialize NUMA in workqueue_init_early() but
6574 * CPU to node mapping may not be available that early on some
6575 * archs such as power and arm64. As per-cpu pools created
6576 * previously could be missing node hint and unbound pools NUMA
6577 * affinity, fix them up.
6579 * Also, while iterating workqueues, create rescuers if requested.
6583 mutex_lock(&wq_pool_mutex);
6585 for_each_possible_cpu(cpu) {
6586 for_each_cpu_worker_pool(pool, cpu) {
6587 pool->node = cpu_to_node(cpu);
6591 list_for_each_entry(wq, &workqueues, list) {
6592 wq_update_unbound_numa(wq, smp_processor_id(), true);
6593 WARN(init_rescuer(wq),
6594 "workqueue: failed to create early rescuer for %s",
6598 mutex_unlock(&wq_pool_mutex);
6600 /* create the initial workers */
6601 for_each_online_cpu(cpu) {
6602 for_each_cpu_worker_pool(pool, cpu) {
6603 pool->flags &= ~POOL_DISASSOCIATED;
6604 BUG_ON(!create_worker(pool));
6608 hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
6609 BUG_ON(!create_worker(pool));
6616 * Despite the naming, this is a no-op function which is here only for avoiding
6617 * link error. Since compile-time warning may fail to catch, we will need to
6618 * emit run-time warning from __flush_workqueue().
6620 void __warn_flushing_systemwide_wq(void) { }
6621 EXPORT_SYMBOL(__warn_flushing_systemwide_wq);