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/interrupt.h>
33 #include <linux/signal.h>
34 #include <linux/completion.h>
35 #include <linux/workqueue.h>
36 #include <linux/slab.h>
37 #include <linux/cpu.h>
38 #include <linux/notifier.h>
39 #include <linux/kthread.h>
40 #include <linux/hardirq.h>
41 #include <linux/mempolicy.h>
42 #include <linux/freezer.h>
43 #include <linux/debug_locks.h>
44 #include <linux/lockdep.h>
45 #include <linux/idr.h>
46 #include <linux/jhash.h>
47 #include <linux/hashtable.h>
48 #include <linux/rculist.h>
49 #include <linux/nodemask.h>
50 #include <linux/moduleparam.h>
51 #include <linux/uaccess.h>
52 #include <linux/sched/isolation.h>
53 #include <linux/sched/debug.h>
54 #include <linux/nmi.h>
55 #include <linux/kvm_para.h>
56 #include <linux/delay.h>
57 #include <linux/irq_work.h>
59 #include "workqueue_internal.h"
61 enum worker_pool_flags {
65 * A bound pool is either associated or disassociated with its CPU.
66 * While associated (!DISASSOCIATED), all workers are bound to the
67 * CPU and none has %WORKER_UNBOUND set and concurrency management
70 * While DISASSOCIATED, the cpu may be offline and all workers have
71 * %WORKER_UNBOUND set and concurrency management disabled, and may
72 * be executing on any CPU. The pool behaves as an unbound one.
74 * Note that DISASSOCIATED should be flipped only while holding
75 * wq_pool_attach_mutex to avoid changing binding state while
76 * worker_attach_to_pool() is in progress.
78 * As there can only be one concurrent BH execution context per CPU, a
79 * BH pool is per-CPU and always DISASSOCIATED.
81 POOL_BH = 1 << 0, /* is a BH pool */
82 POOL_MANAGER_ACTIVE = 1 << 1, /* being managed */
83 POOL_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
88 WORKER_DIE = 1 << 1, /* die die die */
89 WORKER_IDLE = 1 << 2, /* is idle */
90 WORKER_PREP = 1 << 3, /* preparing to run works */
91 WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
92 WORKER_UNBOUND = 1 << 7, /* worker is unbound */
93 WORKER_REBOUND = 1 << 8, /* worker was rebound */
95 WORKER_NOT_RUNNING = WORKER_PREP | WORKER_CPU_INTENSIVE |
96 WORKER_UNBOUND | WORKER_REBOUND,
99 enum wq_internal_consts {
100 NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */
102 UNBOUND_POOL_HASH_ORDER = 6, /* hashed by pool->attrs */
103 BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
105 MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
106 IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
108 MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
109 /* call for help after 10ms
111 MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
112 CREATE_COOLDOWN = HZ, /* time to breath after fail */
115 * Rescue workers are used only on emergencies and shared by
116 * all cpus. Give MIN_NICE.
118 RESCUER_NICE_LEVEL = MIN_NICE,
119 HIGHPRI_NICE_LEVEL = MIN_NICE,
125 * We don't want to trap softirq for too long. See MAX_SOFTIRQ_TIME and
126 * MAX_SOFTIRQ_RESTART in kernel/softirq.c. These are macros because
127 * msecs_to_jiffies() can't be an initializer.
129 #define BH_WORKER_JIFFIES msecs_to_jiffies(2)
130 #define BH_WORKER_RESTARTS 10
133 * Structure fields follow one of the following exclusion rules.
135 * I: Modifiable by initialization/destruction paths and read-only for
138 * P: Preemption protected. Disabling preemption is enough and should
139 * only be modified and accessed from the local cpu.
141 * L: pool->lock protected. Access with pool->lock held.
143 * LN: pool->lock and wq_node_nr_active->lock protected for writes. Either for
146 * K: Only modified by worker while holding pool->lock. Can be safely read by
147 * self, while holding pool->lock or from IRQ context if %current is the
150 * S: Only modified by worker self.
152 * A: wq_pool_attach_mutex protected.
154 * PL: wq_pool_mutex protected.
156 * PR: wq_pool_mutex protected for writes. RCU protected for reads.
158 * PW: wq_pool_mutex and wq->mutex protected for writes. Either for reads.
160 * PWR: wq_pool_mutex and wq->mutex protected for writes. Either or
163 * WQ: wq->mutex protected.
165 * WR: wq->mutex protected for writes. RCU protected for reads.
167 * WO: wq->mutex protected for writes. Updated with WRITE_ONCE() and can be read
168 * with READ_ONCE() without locking.
170 * MD: wq_mayday_lock protected.
172 * WD: Used internally by the watchdog.
175 /* struct worker is defined in workqueue_internal.h */
178 raw_spinlock_t lock; /* the pool lock */
179 int cpu; /* I: the associated cpu */
180 int node; /* I: the associated node ID */
181 int id; /* I: pool ID */
182 unsigned int flags; /* L: flags */
184 unsigned long watchdog_ts; /* L: watchdog timestamp */
185 bool cpu_stall; /* WD: stalled cpu bound pool */
188 * The counter is incremented in a process context on the associated CPU
189 * w/ preemption disabled, and decremented or reset in the same context
190 * but w/ pool->lock held. The readers grab pool->lock and are
191 * guaranteed to see if the counter reached zero.
195 struct list_head worklist; /* L: list of pending works */
197 int nr_workers; /* L: total number of workers */
198 int nr_idle; /* L: currently idle workers */
200 struct list_head idle_list; /* L: list of idle workers */
201 struct timer_list idle_timer; /* L: worker idle timeout */
202 struct work_struct idle_cull_work; /* L: worker idle cleanup */
204 struct timer_list mayday_timer; /* L: SOS timer for workers */
206 /* a workers is either on busy_hash or idle_list, or the manager */
207 DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
208 /* L: hash of busy workers */
210 struct worker *manager; /* L: purely informational */
211 struct list_head workers; /* A: attached workers */
212 struct list_head dying_workers; /* A: workers about to die */
213 struct completion *detach_completion; /* all workers detached */
215 struct ida worker_ida; /* worker IDs for task name */
217 struct workqueue_attrs *attrs; /* I: worker attributes */
218 struct hlist_node hash_node; /* PL: unbound_pool_hash node */
219 int refcnt; /* PL: refcnt for unbound pools */
222 * Destruction of pool is RCU protected to allow dereferences
223 * from get_work_pool().
229 * Per-pool_workqueue statistics. These can be monitored using
230 * tools/workqueue/wq_monitor.py.
232 enum pool_workqueue_stats {
233 PWQ_STAT_STARTED, /* work items started execution */
234 PWQ_STAT_COMPLETED, /* work items completed execution */
235 PWQ_STAT_CPU_TIME, /* total CPU time consumed */
236 PWQ_STAT_CPU_INTENSIVE, /* wq_cpu_intensive_thresh_us violations */
237 PWQ_STAT_CM_WAKEUP, /* concurrency-management worker wakeups */
238 PWQ_STAT_REPATRIATED, /* unbound workers brought back into scope */
239 PWQ_STAT_MAYDAY, /* maydays to rescuer */
240 PWQ_STAT_RESCUED, /* linked work items executed by rescuer */
246 * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
247 * of work_struct->data are used for flags and the remaining high bits
248 * point to the pwq; thus, pwqs need to be aligned at two's power of the
249 * number of flag bits.
251 struct pool_workqueue {
252 struct worker_pool *pool; /* I: the associated pool */
253 struct workqueue_struct *wq; /* I: the owning workqueue */
254 int work_color; /* L: current color */
255 int flush_color; /* L: flushing color */
256 int refcnt; /* L: reference count */
257 int nr_in_flight[WORK_NR_COLORS];
258 /* L: nr of in_flight works */
259 bool plugged; /* L: execution suspended */
262 * nr_active management and WORK_STRUCT_INACTIVE:
264 * When pwq->nr_active >= max_active, new work item is queued to
265 * pwq->inactive_works instead of pool->worklist and marked with
266 * WORK_STRUCT_INACTIVE.
268 * All work items marked with WORK_STRUCT_INACTIVE do not participate in
269 * nr_active and all work items in pwq->inactive_works are marked with
270 * WORK_STRUCT_INACTIVE. But not all WORK_STRUCT_INACTIVE work items are
271 * in pwq->inactive_works. Some of them are ready to run in
272 * pool->worklist or worker->scheduled. Those work itmes are only struct
273 * wq_barrier which is used for flush_work() and should not participate
274 * in nr_active. For non-barrier work item, it is marked with
275 * WORK_STRUCT_INACTIVE iff it is in pwq->inactive_works.
277 int nr_active; /* L: nr of active works */
278 struct list_head inactive_works; /* L: inactive works */
279 struct list_head pending_node; /* LN: node on wq_node_nr_active->pending_pwqs */
280 struct list_head pwqs_node; /* WR: node on wq->pwqs */
281 struct list_head mayday_node; /* MD: node on wq->maydays */
283 u64 stats[PWQ_NR_STATS];
286 * Release of unbound pwq is punted to a kthread_worker. See put_pwq()
287 * and pwq_release_workfn() for details. pool_workqueue itself is also
288 * RCU protected so that the first pwq can be determined without
289 * grabbing wq->mutex.
291 struct kthread_work release_work;
293 } __aligned(1 << WORK_STRUCT_FLAG_BITS);
296 * Structure used to wait for workqueue flush.
299 struct list_head list; /* WQ: list of flushers */
300 int flush_color; /* WQ: flush color waiting for */
301 struct completion done; /* flush completion */
307 * Unlike in a per-cpu workqueue where max_active limits its concurrency level
308 * on each CPU, in an unbound workqueue, max_active applies to the whole system.
309 * As sharing a single nr_active across multiple sockets can be very expensive,
310 * the counting and enforcement is per NUMA node.
312 * The following struct is used to enforce per-node max_active. When a pwq wants
313 * to start executing a work item, it should increment ->nr using
314 * tryinc_node_nr_active(). If acquisition fails due to ->nr already being over
315 * ->max, the pwq is queued on ->pending_pwqs. As in-flight work items finish
316 * and decrement ->nr, node_activate_pending_pwq() activates the pending pwqs in
319 struct wq_node_nr_active {
320 int max; /* per-node max_active */
321 atomic_t nr; /* per-node nr_active */
322 raw_spinlock_t lock; /* nests inside pool locks */
323 struct list_head pending_pwqs; /* LN: pwqs with inactive works */
327 * The externally visible workqueue. It relays the issued work items to
328 * the appropriate worker_pool through its pool_workqueues.
330 struct workqueue_struct {
331 struct list_head pwqs; /* WR: all pwqs of this wq */
332 struct list_head list; /* PR: list of all workqueues */
334 struct mutex mutex; /* protects this wq */
335 int work_color; /* WQ: current work color */
336 int flush_color; /* WQ: current flush color */
337 atomic_t nr_pwqs_to_flush; /* flush in progress */
338 struct wq_flusher *first_flusher; /* WQ: first flusher */
339 struct list_head flusher_queue; /* WQ: flush waiters */
340 struct list_head flusher_overflow; /* WQ: flush overflow list */
342 struct list_head maydays; /* MD: pwqs requesting rescue */
343 struct worker *rescuer; /* MD: rescue worker */
345 int nr_drainers; /* WQ: drain in progress */
347 /* See alloc_workqueue() function comment for info on min/max_active */
348 int max_active; /* WO: max active works */
349 int min_active; /* WO: min active works */
350 int saved_max_active; /* WQ: saved max_active */
351 int saved_min_active; /* WQ: saved min_active */
353 struct workqueue_attrs *unbound_attrs; /* PW: only for unbound wqs */
354 struct pool_workqueue __rcu *dfl_pwq; /* PW: only for unbound wqs */
357 struct wq_device *wq_dev; /* I: for sysfs interface */
359 #ifdef CONFIG_LOCKDEP
361 struct lock_class_key key;
362 struct lockdep_map lockdep_map;
364 char name[WQ_NAME_LEN]; /* I: workqueue name */
367 * Destruction of workqueue_struct is RCU protected to allow walking
368 * the workqueues list without grabbing wq_pool_mutex.
369 * This is used to dump all workqueues from sysrq.
373 /* hot fields used during command issue, aligned to cacheline */
374 unsigned int flags ____cacheline_aligned; /* WQ: WQ_* flags */
375 struct pool_workqueue __percpu __rcu **cpu_pwq; /* I: per-cpu pwqs */
376 struct wq_node_nr_active *node_nr_active[]; /* I: per-node nr_active */
380 * Each pod type describes how CPUs should be grouped for unbound workqueues.
381 * See the comment above workqueue_attrs->affn_scope.
384 int nr_pods; /* number of pods */
385 cpumask_var_t *pod_cpus; /* pod -> cpus */
386 int *pod_node; /* pod -> node */
387 int *cpu_pod; /* cpu -> pod */
390 static const char *wq_affn_names[WQ_AFFN_NR_TYPES] = {
391 [WQ_AFFN_DFL] = "default",
392 [WQ_AFFN_CPU] = "cpu",
393 [WQ_AFFN_SMT] = "smt",
394 [WQ_AFFN_CACHE] = "cache",
395 [WQ_AFFN_NUMA] = "numa",
396 [WQ_AFFN_SYSTEM] = "system",
400 * Per-cpu work items which run for longer than the following threshold are
401 * automatically considered CPU intensive and excluded from concurrency
402 * management to prevent them from noticeably delaying other per-cpu work items.
403 * ULONG_MAX indicates that the user hasn't overridden it with a boot parameter.
404 * The actual value is initialized in wq_cpu_intensive_thresh_init().
406 static unsigned long wq_cpu_intensive_thresh_us = ULONG_MAX;
407 module_param_named(cpu_intensive_thresh_us, wq_cpu_intensive_thresh_us, ulong, 0644);
409 /* see the comment above the definition of WQ_POWER_EFFICIENT */
410 static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
411 module_param_named(power_efficient, wq_power_efficient, bool, 0444);
413 static bool wq_online; /* can kworkers be created yet? */
414 static bool wq_topo_initialized __read_mostly = false;
416 static struct kmem_cache *pwq_cache;
418 static struct wq_pod_type wq_pod_types[WQ_AFFN_NR_TYPES];
419 static enum wq_affn_scope wq_affn_dfl = WQ_AFFN_CACHE;
421 /* buf for wq_update_unbound_pod_attrs(), protected by CPU hotplug exclusion */
422 static struct workqueue_attrs *wq_update_pod_attrs_buf;
424 static DEFINE_MUTEX(wq_pool_mutex); /* protects pools and workqueues list */
425 static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
426 static DEFINE_RAW_SPINLOCK(wq_mayday_lock); /* protects wq->maydays list */
427 /* wait for manager to go away */
428 static struct rcuwait manager_wait = __RCUWAIT_INITIALIZER(manager_wait);
430 static LIST_HEAD(workqueues); /* PR: list of all workqueues */
431 static bool workqueue_freezing; /* PL: have wqs started freezing? */
433 /* PL&A: allowable cpus for unbound wqs and work items */
434 static cpumask_var_t wq_unbound_cpumask;
436 /* PL: user requested unbound cpumask via sysfs */
437 static cpumask_var_t wq_requested_unbound_cpumask;
439 /* PL: isolated cpumask to be excluded from unbound cpumask */
440 static cpumask_var_t wq_isolated_cpumask;
442 /* for further constrain wq_unbound_cpumask by cmdline parameter*/
443 static struct cpumask wq_cmdline_cpumask __initdata;
445 /* CPU where unbound work was last round robin scheduled from this CPU */
446 static DEFINE_PER_CPU(int, wq_rr_cpu_last);
449 * Local execution of unbound work items is no longer guaranteed. The
450 * following always forces round-robin CPU selection on unbound work items
451 * to uncover usages which depend on it.
453 #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
454 static bool wq_debug_force_rr_cpu = true;
456 static bool wq_debug_force_rr_cpu = false;
458 module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
460 /* to raise softirq for the BH worker pools on other CPUs */
461 static DEFINE_PER_CPU_SHARED_ALIGNED(struct irq_work [NR_STD_WORKER_POOLS],
464 /* the BH worker pools */
465 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
468 /* the per-cpu worker pools */
469 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
472 static DEFINE_IDR(worker_pool_idr); /* PR: idr of all pools */
474 /* PL: hash of all unbound pools keyed by pool->attrs */
475 static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
477 /* I: attributes used when instantiating standard unbound pools on demand */
478 static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
480 /* I: attributes used when instantiating ordered pools on demand */
481 static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
484 * I: kthread_worker to release pwq's. pwq release needs to be bounced to a
485 * process context while holding a pool lock. Bounce to a dedicated kthread
486 * worker to avoid A-A deadlocks.
488 static struct kthread_worker *pwq_release_worker __ro_after_init;
490 struct workqueue_struct *system_wq __ro_after_init;
491 EXPORT_SYMBOL(system_wq);
492 struct workqueue_struct *system_highpri_wq __ro_after_init;
493 EXPORT_SYMBOL_GPL(system_highpri_wq);
494 struct workqueue_struct *system_long_wq __ro_after_init;
495 EXPORT_SYMBOL_GPL(system_long_wq);
496 struct workqueue_struct *system_unbound_wq __ro_after_init;
497 EXPORT_SYMBOL_GPL(system_unbound_wq);
498 struct workqueue_struct *system_freezable_wq __ro_after_init;
499 EXPORT_SYMBOL_GPL(system_freezable_wq);
500 struct workqueue_struct *system_power_efficient_wq __ro_after_init;
501 EXPORT_SYMBOL_GPL(system_power_efficient_wq);
502 struct workqueue_struct *system_freezable_power_efficient_wq __ro_after_init;
503 EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
504 struct workqueue_struct *system_bh_wq;
505 EXPORT_SYMBOL_GPL(system_bh_wq);
506 struct workqueue_struct *system_bh_highpri_wq;
507 EXPORT_SYMBOL_GPL(system_bh_highpri_wq);
509 static int worker_thread(void *__worker);
510 static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
511 static void show_pwq(struct pool_workqueue *pwq);
512 static void show_one_worker_pool(struct worker_pool *pool);
514 #define CREATE_TRACE_POINTS
515 #include <trace/events/workqueue.h>
517 #define assert_rcu_or_pool_mutex() \
518 RCU_LOCKDEP_WARN(!rcu_read_lock_any_held() && \
519 !lockdep_is_held(&wq_pool_mutex), \
520 "RCU or wq_pool_mutex should be held")
522 #define assert_rcu_or_wq_mutex_or_pool_mutex(wq) \
523 RCU_LOCKDEP_WARN(!rcu_read_lock_any_held() && \
524 !lockdep_is_held(&wq->mutex) && \
525 !lockdep_is_held(&wq_pool_mutex), \
526 "RCU, wq->mutex or wq_pool_mutex should be held")
528 #define for_each_bh_worker_pool(pool, cpu) \
529 for ((pool) = &per_cpu(bh_worker_pools, cpu)[0]; \
530 (pool) < &per_cpu(bh_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
533 #define for_each_cpu_worker_pool(pool, cpu) \
534 for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
535 (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
539 * for_each_pool - iterate through all worker_pools in the system
540 * @pool: iteration cursor
541 * @pi: integer used for iteration
543 * This must be called either with wq_pool_mutex held or RCU read
544 * locked. If the pool needs to be used beyond the locking in effect, the
545 * caller is responsible for guaranteeing that the pool stays online.
547 * The if/else clause exists only for the lockdep assertion and can be
550 #define for_each_pool(pool, pi) \
551 idr_for_each_entry(&worker_pool_idr, pool, pi) \
552 if (({ assert_rcu_or_pool_mutex(); false; })) { } \
556 * for_each_pool_worker - iterate through all workers of a worker_pool
557 * @worker: iteration cursor
558 * @pool: worker_pool to iterate workers of
560 * This must be called with wq_pool_attach_mutex.
562 * The if/else clause exists only for the lockdep assertion and can be
565 #define for_each_pool_worker(worker, pool) \
566 list_for_each_entry((worker), &(pool)->workers, node) \
567 if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
571 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
572 * @pwq: iteration cursor
573 * @wq: the target workqueue
575 * This must be called either with wq->mutex held or RCU read locked.
576 * If the pwq needs to be used beyond the locking in effect, the caller is
577 * responsible for guaranteeing that the pwq stays online.
579 * The if/else clause exists only for the lockdep assertion and can be
582 #define for_each_pwq(pwq, wq) \
583 list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node, \
584 lockdep_is_held(&(wq->mutex)))
586 #ifdef CONFIG_DEBUG_OBJECTS_WORK
588 static const struct debug_obj_descr work_debug_descr;
590 static void *work_debug_hint(void *addr)
592 return ((struct work_struct *) addr)->func;
595 static bool work_is_static_object(void *addr)
597 struct work_struct *work = addr;
599 return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
603 * fixup_init is called when:
604 * - an active object is initialized
606 static bool work_fixup_init(void *addr, enum debug_obj_state state)
608 struct work_struct *work = addr;
611 case ODEBUG_STATE_ACTIVE:
612 cancel_work_sync(work);
613 debug_object_init(work, &work_debug_descr);
621 * fixup_free is called when:
622 * - an active object is freed
624 static bool work_fixup_free(void *addr, enum debug_obj_state state)
626 struct work_struct *work = addr;
629 case ODEBUG_STATE_ACTIVE:
630 cancel_work_sync(work);
631 debug_object_free(work, &work_debug_descr);
638 static const struct debug_obj_descr work_debug_descr = {
639 .name = "work_struct",
640 .debug_hint = work_debug_hint,
641 .is_static_object = work_is_static_object,
642 .fixup_init = work_fixup_init,
643 .fixup_free = work_fixup_free,
646 static inline void debug_work_activate(struct work_struct *work)
648 debug_object_activate(work, &work_debug_descr);
651 static inline void debug_work_deactivate(struct work_struct *work)
653 debug_object_deactivate(work, &work_debug_descr);
656 void __init_work(struct work_struct *work, int onstack)
659 debug_object_init_on_stack(work, &work_debug_descr);
661 debug_object_init(work, &work_debug_descr);
663 EXPORT_SYMBOL_GPL(__init_work);
665 void destroy_work_on_stack(struct work_struct *work)
667 debug_object_free(work, &work_debug_descr);
669 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
671 void destroy_delayed_work_on_stack(struct delayed_work *work)
673 destroy_timer_on_stack(&work->timer);
674 debug_object_free(&work->work, &work_debug_descr);
676 EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
679 static inline void debug_work_activate(struct work_struct *work) { }
680 static inline void debug_work_deactivate(struct work_struct *work) { }
684 * worker_pool_assign_id - allocate ID and assign it to @pool
685 * @pool: the pool pointer of interest
687 * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
688 * successfully, -errno on failure.
690 static int worker_pool_assign_id(struct worker_pool *pool)
694 lockdep_assert_held(&wq_pool_mutex);
696 ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
705 static struct pool_workqueue __rcu **
706 unbound_pwq_slot(struct workqueue_struct *wq, int cpu)
709 return per_cpu_ptr(wq->cpu_pwq, cpu);
714 /* @cpu < 0 for dfl_pwq */
715 static struct pool_workqueue *unbound_pwq(struct workqueue_struct *wq, int cpu)
717 return rcu_dereference_check(*unbound_pwq_slot(wq, cpu),
718 lockdep_is_held(&wq_pool_mutex) ||
719 lockdep_is_held(&wq->mutex));
723 * unbound_effective_cpumask - effective cpumask of an unbound workqueue
724 * @wq: workqueue of interest
726 * @wq->unbound_attrs->cpumask contains the cpumask requested by the user which
727 * is masked with wq_unbound_cpumask to determine the effective cpumask. The
728 * default pwq is always mapped to the pool with the current effective cpumask.
730 static struct cpumask *unbound_effective_cpumask(struct workqueue_struct *wq)
732 return unbound_pwq(wq, -1)->pool->attrs->__pod_cpumask;
735 static unsigned int work_color_to_flags(int color)
737 return color << WORK_STRUCT_COLOR_SHIFT;
740 static int get_work_color(unsigned long work_data)
742 return (work_data >> WORK_STRUCT_COLOR_SHIFT) &
743 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
746 static int work_next_color(int color)
748 return (color + 1) % WORK_NR_COLORS;
752 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
753 * contain the pointer to the queued pwq. Once execution starts, the flag
754 * is cleared and the high bits contain OFFQ flags and pool ID.
756 * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
757 * and clear_work_data() can be used to set the pwq, pool or clear
758 * work->data. These functions should only be called while the work is
759 * owned - ie. while the PENDING bit is set.
761 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
762 * corresponding to a work. Pool is available once the work has been
763 * queued anywhere after initialization until it is sync canceled. pwq is
764 * available only while the work item is queued.
766 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
767 * canceled. While being canceled, a work item may have its PENDING set
768 * but stay off timer and worklist for arbitrarily long and nobody should
769 * try to steal the PENDING bit.
771 static inline void set_work_data(struct work_struct *work, unsigned long data,
774 WARN_ON_ONCE(!work_pending(work));
775 atomic_long_set(&work->data, data | flags | work_static(work));
778 static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
779 unsigned long extra_flags)
781 set_work_data(work, (unsigned long)pwq,
782 WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
785 static void set_work_pool_and_keep_pending(struct work_struct *work,
788 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
789 WORK_STRUCT_PENDING);
792 static void set_work_pool_and_clear_pending(struct work_struct *work,
796 * The following wmb is paired with the implied mb in
797 * test_and_set_bit(PENDING) and ensures all updates to @work made
798 * here are visible to and precede any updates by the next PENDING
802 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
804 * The following mb guarantees that previous clear of a PENDING bit
805 * will not be reordered with any speculative LOADS or STORES from
806 * work->current_func, which is executed afterwards. This possible
807 * reordering can lead to a missed execution on attempt to queue
808 * the same @work. E.g. consider this case:
811 * ---------------------------- --------------------------------
813 * 1 STORE event_indicated
814 * 2 queue_work_on() {
815 * 3 test_and_set_bit(PENDING)
816 * 4 } set_..._and_clear_pending() {
817 * 5 set_work_data() # clear bit
819 * 7 work->current_func() {
820 * 8 LOAD event_indicated
823 * Without an explicit full barrier speculative LOAD on line 8 can
824 * be executed before CPU#0 does STORE on line 1. If that happens,
825 * CPU#0 observes the PENDING bit is still set and new execution of
826 * a @work is not queued in a hope, that CPU#1 will eventually
827 * finish the queued @work. Meanwhile CPU#1 does not see
828 * event_indicated is set, because speculative LOAD was executed
829 * before actual STORE.
834 static void clear_work_data(struct work_struct *work)
836 smp_wmb(); /* see set_work_pool_and_clear_pending() */
837 set_work_data(work, WORK_STRUCT_NO_POOL, 0);
840 static inline struct pool_workqueue *work_struct_pwq(unsigned long data)
842 return (struct pool_workqueue *)(data & WORK_STRUCT_WQ_DATA_MASK);
845 static struct pool_workqueue *get_work_pwq(struct work_struct *work)
847 unsigned long data = atomic_long_read(&work->data);
849 if (data & WORK_STRUCT_PWQ)
850 return work_struct_pwq(data);
856 * get_work_pool - return the worker_pool a given work was associated with
857 * @work: the work item of interest
859 * Pools are created and destroyed under wq_pool_mutex, and allows read
860 * access under RCU read lock. As such, this function should be
861 * called under wq_pool_mutex or inside of a rcu_read_lock() region.
863 * All fields of the returned pool are accessible as long as the above
864 * mentioned locking is in effect. If the returned pool needs to be used
865 * beyond the critical section, the caller is responsible for ensuring the
866 * returned pool is and stays online.
868 * Return: The worker_pool @work was last associated with. %NULL if none.
870 static struct worker_pool *get_work_pool(struct work_struct *work)
872 unsigned long data = atomic_long_read(&work->data);
875 assert_rcu_or_pool_mutex();
877 if (data & WORK_STRUCT_PWQ)
878 return work_struct_pwq(data)->pool;
880 pool_id = data >> WORK_OFFQ_POOL_SHIFT;
881 if (pool_id == WORK_OFFQ_POOL_NONE)
884 return idr_find(&worker_pool_idr, pool_id);
888 * get_work_pool_id - return the worker pool ID a given work is associated with
889 * @work: the work item of interest
891 * Return: The worker_pool ID @work was last associated with.
892 * %WORK_OFFQ_POOL_NONE if none.
894 static int get_work_pool_id(struct work_struct *work)
896 unsigned long data = atomic_long_read(&work->data);
898 if (data & WORK_STRUCT_PWQ)
899 return work_struct_pwq(data)->pool->id;
901 return data >> WORK_OFFQ_POOL_SHIFT;
904 static void mark_work_canceling(struct work_struct *work)
906 unsigned long pool_id = get_work_pool_id(work);
908 pool_id <<= WORK_OFFQ_POOL_SHIFT;
909 set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
912 static bool work_is_canceling(struct work_struct *work)
914 unsigned long data = atomic_long_read(&work->data);
916 return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
920 * Policy functions. These define the policies on how the global worker
921 * pools are managed. Unless noted otherwise, these functions assume that
922 * they're being called with pool->lock held.
926 * Need to wake up a worker? Called from anything but currently
929 * Note that, because unbound workers never contribute to nr_running, this
930 * function will always return %true for unbound pools as long as the
931 * worklist isn't empty.
933 static bool need_more_worker(struct worker_pool *pool)
935 return !list_empty(&pool->worklist) && !pool->nr_running;
938 /* Can I start working? Called from busy but !running workers. */
939 static bool may_start_working(struct worker_pool *pool)
941 return pool->nr_idle;
944 /* Do I need to keep working? Called from currently running workers. */
945 static bool keep_working(struct worker_pool *pool)
947 return !list_empty(&pool->worklist) && (pool->nr_running <= 1);
950 /* Do we need a new worker? Called from manager. */
951 static bool need_to_create_worker(struct worker_pool *pool)
953 return need_more_worker(pool) && !may_start_working(pool);
956 /* Do we have too many workers and should some go away? */
957 static bool too_many_workers(struct worker_pool *pool)
959 bool managing = pool->flags & POOL_MANAGER_ACTIVE;
960 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
961 int nr_busy = pool->nr_workers - nr_idle;
963 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
967 * worker_set_flags - set worker flags and adjust nr_running accordingly
969 * @flags: flags to set
971 * Set @flags in @worker->flags and adjust nr_running accordingly.
973 static inline void worker_set_flags(struct worker *worker, unsigned int flags)
975 struct worker_pool *pool = worker->pool;
977 lockdep_assert_held(&pool->lock);
979 /* If transitioning into NOT_RUNNING, adjust nr_running. */
980 if ((flags & WORKER_NOT_RUNNING) &&
981 !(worker->flags & WORKER_NOT_RUNNING)) {
985 worker->flags |= flags;
989 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
991 * @flags: flags to clear
993 * Clear @flags in @worker->flags and adjust nr_running accordingly.
995 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
997 struct worker_pool *pool = worker->pool;
998 unsigned int oflags = worker->flags;
1000 lockdep_assert_held(&pool->lock);
1002 worker->flags &= ~flags;
1005 * If transitioning out of NOT_RUNNING, increment nr_running. Note
1006 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
1007 * of multiple flags, not a single flag.
1009 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
1010 if (!(worker->flags & WORKER_NOT_RUNNING))
1014 /* Return the first idle worker. Called with pool->lock held. */
1015 static struct worker *first_idle_worker(struct worker_pool *pool)
1017 if (unlikely(list_empty(&pool->idle_list)))
1020 return list_first_entry(&pool->idle_list, struct worker, entry);
1024 * worker_enter_idle - enter idle state
1025 * @worker: worker which is entering idle state
1027 * @worker is entering idle state. Update stats and idle timer if
1031 * raw_spin_lock_irq(pool->lock).
1033 static void worker_enter_idle(struct worker *worker)
1035 struct worker_pool *pool = worker->pool;
1037 if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
1038 WARN_ON_ONCE(!list_empty(&worker->entry) &&
1039 (worker->hentry.next || worker->hentry.pprev)))
1042 /* can't use worker_set_flags(), also called from create_worker() */
1043 worker->flags |= WORKER_IDLE;
1045 worker->last_active = jiffies;
1047 /* idle_list is LIFO */
1048 list_add(&worker->entry, &pool->idle_list);
1050 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1051 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1053 /* Sanity check nr_running. */
1054 WARN_ON_ONCE(pool->nr_workers == pool->nr_idle && pool->nr_running);
1058 * worker_leave_idle - leave idle state
1059 * @worker: worker which is leaving idle state
1061 * @worker is leaving idle state. Update stats.
1064 * raw_spin_lock_irq(pool->lock).
1066 static void worker_leave_idle(struct worker *worker)
1068 struct worker_pool *pool = worker->pool;
1070 if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
1072 worker_clr_flags(worker, WORKER_IDLE);
1074 list_del_init(&worker->entry);
1078 * find_worker_executing_work - find worker which is executing a work
1079 * @pool: pool of interest
1080 * @work: work to find worker for
1082 * Find a worker which is executing @work on @pool by searching
1083 * @pool->busy_hash which is keyed by the address of @work. For a worker
1084 * to match, its current execution should match the address of @work and
1085 * its work function. This is to avoid unwanted dependency between
1086 * unrelated work executions through a work item being recycled while still
1089 * This is a bit tricky. A work item may be freed once its execution
1090 * starts and nothing prevents the freed area from being recycled for
1091 * another work item. If the same work item address ends up being reused
1092 * before the original execution finishes, workqueue will identify the
1093 * recycled work item as currently executing and make it wait until the
1094 * current execution finishes, introducing an unwanted dependency.
1096 * This function checks the work item address and work function to avoid
1097 * false positives. Note that this isn't complete as one may construct a
1098 * work function which can introduce dependency onto itself through a
1099 * recycled work item. Well, if somebody wants to shoot oneself in the
1100 * foot that badly, there's only so much we can do, and if such deadlock
1101 * actually occurs, it should be easy to locate the culprit work function.
1104 * raw_spin_lock_irq(pool->lock).
1107 * Pointer to worker which is executing @work if found, %NULL
1110 static struct worker *find_worker_executing_work(struct worker_pool *pool,
1111 struct work_struct *work)
1113 struct worker *worker;
1115 hash_for_each_possible(pool->busy_hash, worker, hentry,
1116 (unsigned long)work)
1117 if (worker->current_work == work &&
1118 worker->current_func == work->func)
1125 * move_linked_works - move linked works to a list
1126 * @work: start of series of works to be scheduled
1127 * @head: target list to append @work to
1128 * @nextp: out parameter for nested worklist walking
1130 * Schedule linked works starting from @work to @head. Work series to be
1131 * scheduled starts at @work and includes any consecutive work with
1132 * WORK_STRUCT_LINKED set in its predecessor. See assign_work() for details on
1136 * raw_spin_lock_irq(pool->lock).
1138 static void move_linked_works(struct work_struct *work, struct list_head *head,
1139 struct work_struct **nextp)
1141 struct work_struct *n;
1144 * Linked worklist will always end before the end of the list,
1145 * use NULL for list head.
1147 list_for_each_entry_safe_from(work, n, NULL, entry) {
1148 list_move_tail(&work->entry, head);
1149 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1154 * If we're already inside safe list traversal and have moved
1155 * multiple works to the scheduled queue, the next position
1156 * needs to be updated.
1163 * assign_work - assign a work item and its linked work items to a worker
1164 * @work: work to assign
1165 * @worker: worker to assign to
1166 * @nextp: out parameter for nested worklist walking
1168 * Assign @work and its linked work items to @worker. If @work is already being
1169 * executed by another worker in the same pool, it'll be punted there.
1171 * If @nextp is not NULL, it's updated to point to the next work of the last
1172 * scheduled work. This allows assign_work() to be nested inside
1173 * list_for_each_entry_safe().
1175 * Returns %true if @work was successfully assigned to @worker. %false if @work
1176 * was punted to another worker already executing it.
1178 static bool assign_work(struct work_struct *work, struct worker *worker,
1179 struct work_struct **nextp)
1181 struct worker_pool *pool = worker->pool;
1182 struct worker *collision;
1184 lockdep_assert_held(&pool->lock);
1187 * A single work shouldn't be executed concurrently by multiple workers.
1188 * __queue_work() ensures that @work doesn't jump to a different pool
1189 * while still running in the previous pool. Here, we should ensure that
1190 * @work is not executed concurrently by multiple workers from the same
1191 * pool. Check whether anyone is already processing the work. If so,
1192 * defer the work to the currently executing one.
1194 collision = find_worker_executing_work(pool, work);
1195 if (unlikely(collision)) {
1196 move_linked_works(work, &collision->scheduled, nextp);
1200 move_linked_works(work, &worker->scheduled, nextp);
1204 static struct irq_work *bh_pool_irq_work(struct worker_pool *pool)
1206 int high = pool->attrs->nice == HIGHPRI_NICE_LEVEL ? 1 : 0;
1208 return &per_cpu(bh_pool_irq_works, pool->cpu)[high];
1211 static void kick_bh_pool(struct worker_pool *pool)
1214 if (unlikely(pool->cpu != smp_processor_id())) {
1215 irq_work_queue_on(bh_pool_irq_work(pool), pool->cpu);
1219 if (pool->attrs->nice == HIGHPRI_NICE_LEVEL)
1220 raise_softirq_irqoff(HI_SOFTIRQ);
1222 raise_softirq_irqoff(TASKLET_SOFTIRQ);
1226 * kick_pool - wake up an idle worker if necessary
1227 * @pool: pool to kick
1229 * @pool may have pending work items. Wake up worker if necessary. Returns
1230 * whether a worker was woken up.
1232 static bool kick_pool(struct worker_pool *pool)
1234 struct worker *worker = first_idle_worker(pool);
1235 struct task_struct *p;
1237 lockdep_assert_held(&pool->lock);
1239 if (!need_more_worker(pool) || !worker)
1242 if (pool->flags & POOL_BH) {
1251 * Idle @worker is about to execute @work and waking up provides an
1252 * opportunity to migrate @worker at a lower cost by setting the task's
1253 * wake_cpu field. Let's see if we want to move @worker to improve
1254 * execution locality.
1256 * We're waking the worker that went idle the latest and there's some
1257 * chance that @worker is marked idle but hasn't gone off CPU yet. If
1258 * so, setting the wake_cpu won't do anything. As this is a best-effort
1259 * optimization and the race window is narrow, let's leave as-is for
1260 * now. If this becomes pronounced, we can skip over workers which are
1261 * still on cpu when picking an idle worker.
1263 * If @pool has non-strict affinity, @worker might have ended up outside
1264 * its affinity scope. Repatriate.
1266 if (!pool->attrs->affn_strict &&
1267 !cpumask_test_cpu(p->wake_cpu, pool->attrs->__pod_cpumask)) {
1268 struct work_struct *work = list_first_entry(&pool->worklist,
1269 struct work_struct, entry);
1270 p->wake_cpu = cpumask_any_distribute(pool->attrs->__pod_cpumask);
1271 get_work_pwq(work)->stats[PWQ_STAT_REPATRIATED]++;
1278 #ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
1281 * Concurrency-managed per-cpu work items that hog CPU for longer than
1282 * wq_cpu_intensive_thresh_us trigger the automatic CPU_INTENSIVE mechanism,
1283 * which prevents them from stalling other concurrency-managed work items. If a
1284 * work function keeps triggering this mechanism, it's likely that the work item
1285 * should be using an unbound workqueue instead.
1287 * wq_cpu_intensive_report() tracks work functions which trigger such conditions
1288 * and report them so that they can be examined and converted to use unbound
1289 * workqueues as appropriate. To avoid flooding the console, each violating work
1290 * function is tracked and reported with exponential backoff.
1292 #define WCI_MAX_ENTS 128
1297 struct hlist_node hash_node;
1300 static struct wci_ent wci_ents[WCI_MAX_ENTS];
1301 static int wci_nr_ents;
1302 static DEFINE_RAW_SPINLOCK(wci_lock);
1303 static DEFINE_HASHTABLE(wci_hash, ilog2(WCI_MAX_ENTS));
1305 static struct wci_ent *wci_find_ent(work_func_t func)
1307 struct wci_ent *ent;
1309 hash_for_each_possible_rcu(wci_hash, ent, hash_node,
1310 (unsigned long)func) {
1311 if (ent->func == func)
1317 static void wq_cpu_intensive_report(work_func_t func)
1319 struct wci_ent *ent;
1322 ent = wci_find_ent(func);
1327 * Start reporting from the fourth time and back off
1330 cnt = atomic64_inc_return_relaxed(&ent->cnt);
1331 if (cnt >= 4 && is_power_of_2(cnt))
1332 printk_deferred(KERN_WARNING "workqueue: %ps hogged CPU for >%luus %llu times, consider switching to WQ_UNBOUND\n",
1333 ent->func, wq_cpu_intensive_thresh_us,
1334 atomic64_read(&ent->cnt));
1339 * @func is a new violation. Allocate a new entry for it. If wcn_ents[]
1340 * is exhausted, something went really wrong and we probably made enough
1343 if (wci_nr_ents >= WCI_MAX_ENTS)
1346 raw_spin_lock(&wci_lock);
1348 if (wci_nr_ents >= WCI_MAX_ENTS) {
1349 raw_spin_unlock(&wci_lock);
1353 if (wci_find_ent(func)) {
1354 raw_spin_unlock(&wci_lock);
1358 ent = &wci_ents[wci_nr_ents++];
1360 atomic64_set(&ent->cnt, 1);
1361 hash_add_rcu(wci_hash, &ent->hash_node, (unsigned long)func);
1363 raw_spin_unlock(&wci_lock);
1366 #else /* CONFIG_WQ_CPU_INTENSIVE_REPORT */
1367 static void wq_cpu_intensive_report(work_func_t func) {}
1368 #endif /* CONFIG_WQ_CPU_INTENSIVE_REPORT */
1371 * wq_worker_running - a worker is running again
1372 * @task: task waking up
1374 * This function is called when a worker returns from schedule()
1376 void wq_worker_running(struct task_struct *task)
1378 struct worker *worker = kthread_data(task);
1380 if (!READ_ONCE(worker->sleeping))
1384 * If preempted by unbind_workers() between the WORKER_NOT_RUNNING check
1385 * and the nr_running increment below, we may ruin the nr_running reset
1386 * and leave with an unexpected pool->nr_running == 1 on the newly unbound
1387 * pool. Protect against such race.
1390 if (!(worker->flags & WORKER_NOT_RUNNING))
1391 worker->pool->nr_running++;
1395 * CPU intensive auto-detection cares about how long a work item hogged
1396 * CPU without sleeping. Reset the starting timestamp on wakeup.
1398 worker->current_at = worker->task->se.sum_exec_runtime;
1400 WRITE_ONCE(worker->sleeping, 0);
1404 * wq_worker_sleeping - a worker is going to sleep
1405 * @task: task going to sleep
1407 * This function is called from schedule() when a busy worker is
1410 void wq_worker_sleeping(struct task_struct *task)
1412 struct worker *worker = kthread_data(task);
1413 struct worker_pool *pool;
1416 * Rescuers, which may not have all the fields set up like normal
1417 * workers, also reach here, let's not access anything before
1418 * checking NOT_RUNNING.
1420 if (worker->flags & WORKER_NOT_RUNNING)
1423 pool = worker->pool;
1425 /* Return if preempted before wq_worker_running() was reached */
1426 if (READ_ONCE(worker->sleeping))
1429 WRITE_ONCE(worker->sleeping, 1);
1430 raw_spin_lock_irq(&pool->lock);
1433 * Recheck in case unbind_workers() preempted us. We don't
1434 * want to decrement nr_running after the worker is unbound
1435 * and nr_running has been reset.
1437 if (worker->flags & WORKER_NOT_RUNNING) {
1438 raw_spin_unlock_irq(&pool->lock);
1443 if (kick_pool(pool))
1444 worker->current_pwq->stats[PWQ_STAT_CM_WAKEUP]++;
1446 raw_spin_unlock_irq(&pool->lock);
1450 * wq_worker_tick - a scheduler tick occurred while a kworker is running
1451 * @task: task currently running
1453 * Called from scheduler_tick(). We're in the IRQ context and the current
1454 * worker's fields which follow the 'K' locking rule can be accessed safely.
1456 void wq_worker_tick(struct task_struct *task)
1458 struct worker *worker = kthread_data(task);
1459 struct pool_workqueue *pwq = worker->current_pwq;
1460 struct worker_pool *pool = worker->pool;
1465 pwq->stats[PWQ_STAT_CPU_TIME] += TICK_USEC;
1467 if (!wq_cpu_intensive_thresh_us)
1471 * If the current worker is concurrency managed and hogged the CPU for
1472 * longer than wq_cpu_intensive_thresh_us, it's automatically marked
1473 * CPU_INTENSIVE to avoid stalling other concurrency-managed work items.
1475 * Set @worker->sleeping means that @worker is in the process of
1476 * switching out voluntarily and won't be contributing to
1477 * @pool->nr_running until it wakes up. As wq_worker_sleeping() also
1478 * decrements ->nr_running, setting CPU_INTENSIVE here can lead to
1479 * double decrements. The task is releasing the CPU anyway. Let's skip.
1480 * We probably want to make this prettier in the future.
1482 if ((worker->flags & WORKER_NOT_RUNNING) || READ_ONCE(worker->sleeping) ||
1483 worker->task->se.sum_exec_runtime - worker->current_at <
1484 wq_cpu_intensive_thresh_us * NSEC_PER_USEC)
1487 raw_spin_lock(&pool->lock);
1489 worker_set_flags(worker, WORKER_CPU_INTENSIVE);
1490 wq_cpu_intensive_report(worker->current_func);
1491 pwq->stats[PWQ_STAT_CPU_INTENSIVE]++;
1493 if (kick_pool(pool))
1494 pwq->stats[PWQ_STAT_CM_WAKEUP]++;
1496 raw_spin_unlock(&pool->lock);
1500 * wq_worker_last_func - retrieve worker's last work function
1501 * @task: Task to retrieve last work function of.
1503 * Determine the last function a worker executed. This is called from
1504 * the scheduler to get a worker's last known identity.
1507 * raw_spin_lock_irq(rq->lock)
1509 * This function is called during schedule() when a kworker is going
1510 * to sleep. It's used by psi to identify aggregation workers during
1511 * dequeuing, to allow periodic aggregation to shut-off when that
1512 * worker is the last task in the system or cgroup to go to sleep.
1514 * As this function doesn't involve any workqueue-related locking, it
1515 * only returns stable values when called from inside the scheduler's
1516 * queuing and dequeuing paths, when @task, which must be a kworker,
1517 * is guaranteed to not be processing any works.
1520 * The last work function %current executed as a worker, NULL if it
1521 * hasn't executed any work yet.
1523 work_func_t wq_worker_last_func(struct task_struct *task)
1525 struct worker *worker = kthread_data(task);
1527 return worker->last_func;
1531 * wq_node_nr_active - Determine wq_node_nr_active to use
1532 * @wq: workqueue of interest
1533 * @node: NUMA node, can be %NUMA_NO_NODE
1535 * Determine wq_node_nr_active to use for @wq on @node. Returns:
1537 * - %NULL for per-cpu workqueues as they don't need to use shared nr_active.
1539 * - node_nr_active[nr_node_ids] if @node is %NUMA_NO_NODE.
1541 * - Otherwise, node_nr_active[@node].
1543 static struct wq_node_nr_active *wq_node_nr_active(struct workqueue_struct *wq,
1546 if (!(wq->flags & WQ_UNBOUND))
1549 if (node == NUMA_NO_NODE)
1552 return wq->node_nr_active[node];
1556 * wq_update_node_max_active - Update per-node max_actives to use
1557 * @wq: workqueue to update
1558 * @off_cpu: CPU that's going down, -1 if a CPU is not going down
1560 * Update @wq->node_nr_active[]->max. @wq must be unbound. max_active is
1561 * distributed among nodes according to the proportions of numbers of online
1562 * cpus. The result is always between @wq->min_active and max_active.
1564 static void wq_update_node_max_active(struct workqueue_struct *wq, int off_cpu)
1566 struct cpumask *effective = unbound_effective_cpumask(wq);
1567 int min_active = READ_ONCE(wq->min_active);
1568 int max_active = READ_ONCE(wq->max_active);
1569 int total_cpus, node;
1571 lockdep_assert_held(&wq->mutex);
1573 if (!wq_topo_initialized)
1576 if (off_cpu >= 0 && !cpumask_test_cpu(off_cpu, effective))
1579 total_cpus = cpumask_weight_and(effective, cpu_online_mask);
1583 for_each_node(node) {
1586 node_cpus = cpumask_weight_and(effective, cpumask_of_node(node));
1587 if (off_cpu >= 0 && cpu_to_node(off_cpu) == node)
1590 wq_node_nr_active(wq, node)->max =
1591 clamp(DIV_ROUND_UP(max_active * node_cpus, total_cpus),
1592 min_active, max_active);
1595 wq_node_nr_active(wq, NUMA_NO_NODE)->max = min_active;
1599 * get_pwq - get an extra reference on the specified pool_workqueue
1600 * @pwq: pool_workqueue to get
1602 * Obtain an extra reference on @pwq. The caller should guarantee that
1603 * @pwq has positive refcnt and be holding the matching pool->lock.
1605 static void get_pwq(struct pool_workqueue *pwq)
1607 lockdep_assert_held(&pwq->pool->lock);
1608 WARN_ON_ONCE(pwq->refcnt <= 0);
1613 * put_pwq - put a pool_workqueue reference
1614 * @pwq: pool_workqueue to put
1616 * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
1617 * destruction. The caller should be holding the matching pool->lock.
1619 static void put_pwq(struct pool_workqueue *pwq)
1621 lockdep_assert_held(&pwq->pool->lock);
1622 if (likely(--pwq->refcnt))
1625 * @pwq can't be released under pool->lock, bounce to a dedicated
1626 * kthread_worker to avoid A-A deadlocks.
1628 kthread_queue_work(pwq_release_worker, &pwq->release_work);
1632 * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1633 * @pwq: pool_workqueue to put (can be %NULL)
1635 * put_pwq() with locking. This function also allows %NULL @pwq.
1637 static void put_pwq_unlocked(struct pool_workqueue *pwq)
1641 * As both pwqs and pools are RCU protected, the
1642 * following lock operations are safe.
1644 raw_spin_lock_irq(&pwq->pool->lock);
1646 raw_spin_unlock_irq(&pwq->pool->lock);
1650 static bool pwq_is_empty(struct pool_workqueue *pwq)
1652 return !pwq->nr_active && list_empty(&pwq->inactive_works);
1655 static void __pwq_activate_work(struct pool_workqueue *pwq,
1656 struct work_struct *work)
1658 unsigned long *wdb = work_data_bits(work);
1660 WARN_ON_ONCE(!(*wdb & WORK_STRUCT_INACTIVE));
1661 trace_workqueue_activate_work(work);
1662 if (list_empty(&pwq->pool->worklist))
1663 pwq->pool->watchdog_ts = jiffies;
1664 move_linked_works(work, &pwq->pool->worklist, NULL);
1665 __clear_bit(WORK_STRUCT_INACTIVE_BIT, wdb);
1669 * pwq_activate_work - Activate a work item if inactive
1670 * @pwq: pool_workqueue @work belongs to
1671 * @work: work item to activate
1673 * Returns %true if activated. %false if already active.
1675 static bool pwq_activate_work(struct pool_workqueue *pwq,
1676 struct work_struct *work)
1678 struct worker_pool *pool = pwq->pool;
1679 struct wq_node_nr_active *nna;
1681 lockdep_assert_held(&pool->lock);
1683 if (!(*work_data_bits(work) & WORK_STRUCT_INACTIVE))
1686 nna = wq_node_nr_active(pwq->wq, pool->node);
1688 atomic_inc(&nna->nr);
1691 __pwq_activate_work(pwq, work);
1695 static bool tryinc_node_nr_active(struct wq_node_nr_active *nna)
1697 int max = READ_ONCE(nna->max);
1702 old = atomic_read(&nna->nr);
1705 tmp = atomic_cmpxchg_relaxed(&nna->nr, old, old + 1);
1712 * pwq_tryinc_nr_active - Try to increment nr_active for a pwq
1713 * @pwq: pool_workqueue of interest
1714 * @fill: max_active may have increased, try to increase concurrency level
1716 * Try to increment nr_active for @pwq. Returns %true if an nr_active count is
1717 * successfully obtained. %false otherwise.
1719 static bool pwq_tryinc_nr_active(struct pool_workqueue *pwq, bool fill)
1721 struct workqueue_struct *wq = pwq->wq;
1722 struct worker_pool *pool = pwq->pool;
1723 struct wq_node_nr_active *nna = wq_node_nr_active(wq, pool->node);
1724 bool obtained = false;
1726 lockdep_assert_held(&pool->lock);
1729 /* BH or per-cpu workqueue, pwq->nr_active is sufficient */
1730 obtained = pwq->nr_active < READ_ONCE(wq->max_active);
1734 if (unlikely(pwq->plugged))
1738 * Unbound workqueue uses per-node shared nr_active $nna. If @pwq is
1739 * already waiting on $nna, pwq_dec_nr_active() will maintain the
1740 * concurrency level. Don't jump the line.
1742 * We need to ignore the pending test after max_active has increased as
1743 * pwq_dec_nr_active() can only maintain the concurrency level but not
1744 * increase it. This is indicated by @fill.
1746 if (!list_empty(&pwq->pending_node) && likely(!fill))
1749 obtained = tryinc_node_nr_active(nna);
1754 * Lockless acquisition failed. Lock, add ourself to $nna->pending_pwqs
1755 * and try again. The smp_mb() is paired with the implied memory barrier
1756 * of atomic_dec_return() in pwq_dec_nr_active() to ensure that either
1757 * we see the decremented $nna->nr or they see non-empty
1758 * $nna->pending_pwqs.
1760 raw_spin_lock(&nna->lock);
1762 if (list_empty(&pwq->pending_node))
1763 list_add_tail(&pwq->pending_node, &nna->pending_pwqs);
1764 else if (likely(!fill))
1769 obtained = tryinc_node_nr_active(nna);
1772 * If @fill, @pwq might have already been pending. Being spuriously
1773 * pending in cold paths doesn't affect anything. Let's leave it be.
1775 if (obtained && likely(!fill))
1776 list_del_init(&pwq->pending_node);
1779 raw_spin_unlock(&nna->lock);
1787 * pwq_activate_first_inactive - Activate the first inactive work item on a pwq
1788 * @pwq: pool_workqueue of interest
1789 * @fill: max_active may have increased, try to increase concurrency level
1791 * Activate the first inactive work item of @pwq if available and allowed by
1794 * Returns %true if an inactive work item has been activated. %false if no
1795 * inactive work item is found or max_active limit is reached.
1797 static bool pwq_activate_first_inactive(struct pool_workqueue *pwq, bool fill)
1799 struct work_struct *work =
1800 list_first_entry_or_null(&pwq->inactive_works,
1801 struct work_struct, entry);
1803 if (work && pwq_tryinc_nr_active(pwq, fill)) {
1804 __pwq_activate_work(pwq, work);
1812 * unplug_oldest_pwq - unplug the oldest pool_workqueue
1813 * @wq: workqueue_struct where its oldest pwq is to be unplugged
1815 * This function should only be called for ordered workqueues where only the
1816 * oldest pwq is unplugged, the others are plugged to suspend execution to
1817 * ensure proper work item ordering::
1819 * dfl_pwq --------------+ [P] - plugged
1822 * pwqs -> A -> B [P] -> C [P] (newest)
1828 * When the oldest pwq is drained and removed, this function should be called
1829 * to unplug the next oldest one to start its work item execution. Note that
1830 * pwq's are linked into wq->pwqs with the oldest first, so the first one in
1831 * the list is the oldest.
1833 static void unplug_oldest_pwq(struct workqueue_struct *wq)
1835 struct pool_workqueue *pwq;
1837 lockdep_assert_held(&wq->mutex);
1839 /* Caller should make sure that pwqs isn't empty before calling */
1840 pwq = list_first_entry_or_null(&wq->pwqs, struct pool_workqueue,
1842 raw_spin_lock_irq(&pwq->pool->lock);
1844 pwq->plugged = false;
1845 if (pwq_activate_first_inactive(pwq, true))
1846 kick_pool(pwq->pool);
1848 raw_spin_unlock_irq(&pwq->pool->lock);
1852 * node_activate_pending_pwq - Activate a pending pwq on a wq_node_nr_active
1853 * @nna: wq_node_nr_active to activate a pending pwq for
1854 * @caller_pool: worker_pool the caller is locking
1856 * Activate a pwq in @nna->pending_pwqs. Called with @caller_pool locked.
1857 * @caller_pool may be unlocked and relocked to lock other worker_pools.
1859 static void node_activate_pending_pwq(struct wq_node_nr_active *nna,
1860 struct worker_pool *caller_pool)
1862 struct worker_pool *locked_pool = caller_pool;
1863 struct pool_workqueue *pwq;
1864 struct work_struct *work;
1866 lockdep_assert_held(&caller_pool->lock);
1868 raw_spin_lock(&nna->lock);
1870 pwq = list_first_entry_or_null(&nna->pending_pwqs,
1871 struct pool_workqueue, pending_node);
1876 * If @pwq is for a different pool than @locked_pool, we need to lock
1877 * @pwq->pool->lock. Let's trylock first. If unsuccessful, do the unlock
1878 * / lock dance. For that, we also need to release @nna->lock as it's
1879 * nested inside pool locks.
1881 if (pwq->pool != locked_pool) {
1882 raw_spin_unlock(&locked_pool->lock);
1883 locked_pool = pwq->pool;
1884 if (!raw_spin_trylock(&locked_pool->lock)) {
1885 raw_spin_unlock(&nna->lock);
1886 raw_spin_lock(&locked_pool->lock);
1887 raw_spin_lock(&nna->lock);
1893 * $pwq may not have any inactive work items due to e.g. cancellations.
1894 * Drop it from pending_pwqs and see if there's another one.
1896 work = list_first_entry_or_null(&pwq->inactive_works,
1897 struct work_struct, entry);
1899 list_del_init(&pwq->pending_node);
1904 * Acquire an nr_active count and activate the inactive work item. If
1905 * $pwq still has inactive work items, rotate it to the end of the
1906 * pending_pwqs so that we round-robin through them. This means that
1907 * inactive work items are not activated in queueing order which is fine
1908 * given that there has never been any ordering across different pwqs.
1910 if (likely(tryinc_node_nr_active(nna))) {
1912 __pwq_activate_work(pwq, work);
1914 if (list_empty(&pwq->inactive_works))
1915 list_del_init(&pwq->pending_node);
1917 list_move_tail(&pwq->pending_node, &nna->pending_pwqs);
1919 /* if activating a foreign pool, make sure it's running */
1920 if (pwq->pool != caller_pool)
1921 kick_pool(pwq->pool);
1925 raw_spin_unlock(&nna->lock);
1926 if (locked_pool != caller_pool) {
1927 raw_spin_unlock(&locked_pool->lock);
1928 raw_spin_lock(&caller_pool->lock);
1933 * pwq_dec_nr_active - Retire an active count
1934 * @pwq: pool_workqueue of interest
1936 * Decrement @pwq's nr_active and try to activate the first inactive work item.
1937 * For unbound workqueues, this function may temporarily drop @pwq->pool->lock.
1939 static void pwq_dec_nr_active(struct pool_workqueue *pwq)
1941 struct worker_pool *pool = pwq->pool;
1942 struct wq_node_nr_active *nna = wq_node_nr_active(pwq->wq, pool->node);
1944 lockdep_assert_held(&pool->lock);
1947 * @pwq->nr_active should be decremented for both percpu and unbound
1953 * For a percpu workqueue, it's simple. Just need to kick the first
1954 * inactive work item on @pwq itself.
1957 pwq_activate_first_inactive(pwq, false);
1962 * If @pwq is for an unbound workqueue, it's more complicated because
1963 * multiple pwqs and pools may be sharing the nr_active count. When a
1964 * pwq needs to wait for an nr_active count, it puts itself on
1965 * $nna->pending_pwqs. The following atomic_dec_return()'s implied
1966 * memory barrier is paired with smp_mb() in pwq_tryinc_nr_active() to
1967 * guarantee that either we see non-empty pending_pwqs or they see
1968 * decremented $nna->nr.
1970 * $nna->max may change as CPUs come online/offline and @pwq->wq's
1971 * max_active gets updated. However, it is guaranteed to be equal to or
1972 * larger than @pwq->wq->min_active which is above zero unless freezing.
1973 * This maintains the forward progress guarantee.
1975 if (atomic_dec_return(&nna->nr) >= READ_ONCE(nna->max))
1978 if (!list_empty(&nna->pending_pwqs))
1979 node_activate_pending_pwq(nna, pool);
1983 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1984 * @pwq: pwq of interest
1985 * @work_data: work_data of work which left the queue
1987 * A work either has completed or is removed from pending queue,
1988 * decrement nr_in_flight of its pwq and handle workqueue flushing.
1991 * For unbound workqueues, this function may temporarily drop @pwq->pool->lock
1992 * and thus should be called after all other state updates for the in-flight
1993 * work item is complete.
1996 * raw_spin_lock_irq(pool->lock).
1998 static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data)
2000 int color = get_work_color(work_data);
2002 if (!(work_data & WORK_STRUCT_INACTIVE))
2003 pwq_dec_nr_active(pwq);
2005 pwq->nr_in_flight[color]--;
2007 /* is flush in progress and are we at the flushing tip? */
2008 if (likely(pwq->flush_color != color))
2011 /* are there still in-flight works? */
2012 if (pwq->nr_in_flight[color])
2015 /* this pwq is done, clear flush_color */
2016 pwq->flush_color = -1;
2019 * If this was the last pwq, wake up the first flusher. It
2020 * will handle the rest.
2022 if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
2023 complete(&pwq->wq->first_flusher->done);
2029 * try_to_grab_pending - steal work item from worklist and disable irq
2030 * @work: work item to steal
2031 * @is_dwork: @work is a delayed_work
2032 * @flags: place to store irq state
2034 * Try to grab PENDING bit of @work. This function can handle @work in any
2035 * stable state - idle, on timer or on worklist.
2039 * ======== ================================================================
2040 * 1 if @work was pending and we successfully stole PENDING
2041 * 0 if @work was idle and we claimed PENDING
2042 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
2043 * -ENOENT if someone else is canceling @work, this state may persist
2044 * for arbitrarily long
2045 * ======== ================================================================
2048 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
2049 * interrupted while holding PENDING and @work off queue, irq must be
2050 * disabled on entry. This, combined with delayed_work->timer being
2051 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
2053 * On successful return, >= 0, irq is disabled and the caller is
2054 * responsible for releasing it using local_irq_restore(*@flags).
2056 * This function is safe to call from any context including IRQ handler.
2058 static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
2059 unsigned long *flags)
2061 struct worker_pool *pool;
2062 struct pool_workqueue *pwq;
2064 local_irq_save(*flags);
2066 /* try to steal the timer if it exists */
2068 struct delayed_work *dwork = to_delayed_work(work);
2071 * dwork->timer is irqsafe. If del_timer() fails, it's
2072 * guaranteed that the timer is not queued anywhere and not
2073 * running on the local CPU.
2075 if (likely(del_timer(&dwork->timer)))
2079 /* try to claim PENDING the normal way */
2080 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
2085 * The queueing is in progress, or it is already queued. Try to
2086 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
2088 pool = get_work_pool(work);
2092 raw_spin_lock(&pool->lock);
2094 * work->data is guaranteed to point to pwq only while the work
2095 * item is queued on pwq->wq, and both updating work->data to point
2096 * to pwq on queueing and to pool on dequeueing are done under
2097 * pwq->pool->lock. This in turn guarantees that, if work->data
2098 * points to pwq which is associated with a locked pool, the work
2099 * item is currently queued on that pool.
2101 pwq = get_work_pwq(work);
2102 if (pwq && pwq->pool == pool) {
2103 unsigned long work_data;
2105 debug_work_deactivate(work);
2108 * A cancelable inactive work item must be in the
2109 * pwq->inactive_works since a queued barrier can't be
2110 * canceled (see the comments in insert_wq_barrier()).
2112 * An inactive work item cannot be grabbed directly because
2113 * it might have linked barrier work items which, if left
2114 * on the inactive_works list, will confuse pwq->nr_active
2115 * management later on and cause stall. Make sure the work
2116 * item is activated before grabbing.
2118 pwq_activate_work(pwq, work);
2120 list_del_init(&work->entry);
2123 * work->data points to pwq iff queued. Let's point to pool. As
2124 * this destroys work->data needed by the next step, stash it.
2126 work_data = *work_data_bits(work);
2127 set_work_pool_and_keep_pending(work, pool->id);
2129 /* must be the last step, see the function comment */
2130 pwq_dec_nr_in_flight(pwq, work_data);
2132 raw_spin_unlock(&pool->lock);
2136 raw_spin_unlock(&pool->lock);
2139 local_irq_restore(*flags);
2140 if (work_is_canceling(work))
2147 * insert_work - insert a work into a pool
2148 * @pwq: pwq @work belongs to
2149 * @work: work to insert
2150 * @head: insertion point
2151 * @extra_flags: extra WORK_STRUCT_* flags to set
2153 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
2154 * work_struct flags.
2157 * raw_spin_lock_irq(pool->lock).
2159 static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
2160 struct list_head *head, unsigned int extra_flags)
2162 debug_work_activate(work);
2164 /* record the work call stack in order to print it in KASAN reports */
2165 kasan_record_aux_stack_noalloc(work);
2167 /* we own @work, set data and link */
2168 set_work_pwq(work, pwq, extra_flags);
2169 list_add_tail(&work->entry, head);
2174 * Test whether @work is being queued from another work executing on the
2177 static bool is_chained_work(struct workqueue_struct *wq)
2179 struct worker *worker;
2181 worker = current_wq_worker();
2183 * Return %true iff I'm a worker executing a work item on @wq. If
2184 * I'm @worker, it's safe to dereference it without locking.
2186 return worker && worker->current_pwq->wq == wq;
2190 * When queueing an unbound work item to a wq, prefer local CPU if allowed
2191 * by wq_unbound_cpumask. Otherwise, round robin among the allowed ones to
2192 * avoid perturbing sensitive tasks.
2194 static int wq_select_unbound_cpu(int cpu)
2198 if (likely(!wq_debug_force_rr_cpu)) {
2199 if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
2202 pr_warn_once("workqueue: round-robin CPU selection forced, expect performance impact\n");
2205 new_cpu = __this_cpu_read(wq_rr_cpu_last);
2206 new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
2207 if (unlikely(new_cpu >= nr_cpu_ids)) {
2208 new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
2209 if (unlikely(new_cpu >= nr_cpu_ids))
2212 __this_cpu_write(wq_rr_cpu_last, new_cpu);
2217 static void __queue_work(int cpu, struct workqueue_struct *wq,
2218 struct work_struct *work)
2220 struct pool_workqueue *pwq;
2221 struct worker_pool *last_pool, *pool;
2222 unsigned int work_flags;
2223 unsigned int req_cpu = cpu;
2226 * While a work item is PENDING && off queue, a task trying to
2227 * steal the PENDING will busy-loop waiting for it to either get
2228 * queued or lose PENDING. Grabbing PENDING and queueing should
2229 * happen with IRQ disabled.
2231 lockdep_assert_irqs_disabled();
2234 * For a draining wq, only works from the same workqueue are
2235 * allowed. The __WQ_DESTROYING helps to spot the issue that
2236 * queues a new work item to a wq after destroy_workqueue(wq).
2238 if (unlikely(wq->flags & (__WQ_DESTROYING | __WQ_DRAINING) &&
2239 WARN_ON_ONCE(!is_chained_work(wq))))
2243 /* pwq which will be used unless @work is executing elsewhere */
2244 if (req_cpu == WORK_CPU_UNBOUND) {
2245 if (wq->flags & WQ_UNBOUND)
2246 cpu = wq_select_unbound_cpu(raw_smp_processor_id());
2248 cpu = raw_smp_processor_id();
2251 pwq = rcu_dereference(*per_cpu_ptr(wq->cpu_pwq, cpu));
2255 * If @work was previously on a different pool, it might still be
2256 * running there, in which case the work needs to be queued on that
2257 * pool to guarantee non-reentrancy.
2259 last_pool = get_work_pool(work);
2260 if (last_pool && last_pool != pool) {
2261 struct worker *worker;
2263 raw_spin_lock(&last_pool->lock);
2265 worker = find_worker_executing_work(last_pool, work);
2267 if (worker && worker->current_pwq->wq == wq) {
2268 pwq = worker->current_pwq;
2270 WARN_ON_ONCE(pool != last_pool);
2272 /* meh... not running there, queue here */
2273 raw_spin_unlock(&last_pool->lock);
2274 raw_spin_lock(&pool->lock);
2277 raw_spin_lock(&pool->lock);
2281 * pwq is determined and locked. For unbound pools, we could have raced
2282 * with pwq release and it could already be dead. If its refcnt is zero,
2283 * repeat pwq selection. Note that unbound pwqs never die without
2284 * another pwq replacing it in cpu_pwq or while work items are executing
2285 * on it, so the retrying is guaranteed to make forward-progress.
2287 if (unlikely(!pwq->refcnt)) {
2288 if (wq->flags & WQ_UNBOUND) {
2289 raw_spin_unlock(&pool->lock);
2294 WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
2298 /* pwq determined, queue */
2299 trace_workqueue_queue_work(req_cpu, pwq, work);
2301 if (WARN_ON(!list_empty(&work->entry)))
2304 pwq->nr_in_flight[pwq->work_color]++;
2305 work_flags = work_color_to_flags(pwq->work_color);
2308 * Limit the number of concurrently active work items to max_active.
2309 * @work must also queue behind existing inactive work items to maintain
2310 * ordering when max_active changes. See wq_adjust_max_active().
2312 if (list_empty(&pwq->inactive_works) && pwq_tryinc_nr_active(pwq, false)) {
2313 if (list_empty(&pool->worklist))
2314 pool->watchdog_ts = jiffies;
2316 trace_workqueue_activate_work(work);
2317 insert_work(pwq, work, &pool->worklist, work_flags);
2320 work_flags |= WORK_STRUCT_INACTIVE;
2321 insert_work(pwq, work, &pwq->inactive_works, work_flags);
2325 raw_spin_unlock(&pool->lock);
2330 * queue_work_on - queue work on specific cpu
2331 * @cpu: CPU number to execute work on
2332 * @wq: workqueue to use
2333 * @work: work to queue
2335 * We queue the work to a specific CPU, the caller must ensure it
2336 * can't go away. Callers that fail to ensure that the specified
2337 * CPU cannot go away will execute on a randomly chosen CPU.
2338 * But note well that callers specifying a CPU that never has been
2339 * online will get a splat.
2341 * Return: %false if @work was already on a queue, %true otherwise.
2343 bool queue_work_on(int cpu, struct workqueue_struct *wq,
2344 struct work_struct *work)
2347 unsigned long flags;
2349 local_irq_save(flags);
2351 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
2352 __queue_work(cpu, wq, work);
2356 local_irq_restore(flags);
2359 EXPORT_SYMBOL(queue_work_on);
2362 * select_numa_node_cpu - Select a CPU based on NUMA node
2363 * @node: NUMA node ID that we want to select a CPU from
2365 * This function will attempt to find a "random" cpu available on a given
2366 * node. If there are no CPUs available on the given node it will return
2367 * WORK_CPU_UNBOUND indicating that we should just schedule to any
2368 * available CPU if we need to schedule this work.
2370 static int select_numa_node_cpu(int node)
2374 /* Delay binding to CPU if node is not valid or online */
2375 if (node < 0 || node >= MAX_NUMNODES || !node_online(node))
2376 return WORK_CPU_UNBOUND;
2378 /* Use local node/cpu if we are already there */
2379 cpu = raw_smp_processor_id();
2380 if (node == cpu_to_node(cpu))
2383 /* Use "random" otherwise know as "first" online CPU of node */
2384 cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
2386 /* If CPU is valid return that, otherwise just defer */
2387 return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND;
2391 * queue_work_node - queue work on a "random" cpu for a given NUMA node
2392 * @node: NUMA node that we are targeting the work for
2393 * @wq: workqueue to use
2394 * @work: work to queue
2396 * We queue the work to a "random" CPU within a given NUMA node. The basic
2397 * idea here is to provide a way to somehow associate work with a given
2400 * This function will only make a best effort attempt at getting this onto
2401 * the right NUMA node. If no node is requested or the requested node is
2402 * offline then we just fall back to standard queue_work behavior.
2404 * Currently the "random" CPU ends up being the first available CPU in the
2405 * intersection of cpu_online_mask and the cpumask of the node, unless we
2406 * are running on the node. In that case we just use the current CPU.
2408 * Return: %false if @work was already on a queue, %true otherwise.
2410 bool queue_work_node(int node, struct workqueue_struct *wq,
2411 struct work_struct *work)
2413 unsigned long flags;
2417 * This current implementation is specific to unbound workqueues.
2418 * Specifically we only return the first available CPU for a given
2419 * node instead of cycling through individual CPUs within the node.
2421 * If this is used with a per-cpu workqueue then the logic in
2422 * workqueue_select_cpu_near would need to be updated to allow for
2423 * some round robin type logic.
2425 WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND));
2427 local_irq_save(flags);
2429 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
2430 int cpu = select_numa_node_cpu(node);
2432 __queue_work(cpu, wq, work);
2436 local_irq_restore(flags);
2439 EXPORT_SYMBOL_GPL(queue_work_node);
2441 void delayed_work_timer_fn(struct timer_list *t)
2443 struct delayed_work *dwork = from_timer(dwork, t, timer);
2445 /* should have been called from irqsafe timer with irq already off */
2446 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
2448 EXPORT_SYMBOL(delayed_work_timer_fn);
2450 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
2451 struct delayed_work *dwork, unsigned long delay)
2453 struct timer_list *timer = &dwork->timer;
2454 struct work_struct *work = &dwork->work;
2457 WARN_ON_ONCE(timer->function != delayed_work_timer_fn);
2458 WARN_ON_ONCE(timer_pending(timer));
2459 WARN_ON_ONCE(!list_empty(&work->entry));
2462 * If @delay is 0, queue @dwork->work immediately. This is for
2463 * both optimization and correctness. The earliest @timer can
2464 * expire is on the closest next tick and delayed_work users depend
2465 * on that there's no such delay when @delay is 0.
2468 __queue_work(cpu, wq, &dwork->work);
2474 timer->expires = jiffies + delay;
2476 if (housekeeping_enabled(HK_TYPE_TIMER)) {
2477 /* If the current cpu is a housekeeping cpu, use it. */
2478 cpu = smp_processor_id();
2479 if (!housekeeping_test_cpu(cpu, HK_TYPE_TIMER))
2480 cpu = housekeeping_any_cpu(HK_TYPE_TIMER);
2481 add_timer_on(timer, cpu);
2483 if (likely(cpu == WORK_CPU_UNBOUND))
2486 add_timer_on(timer, cpu);
2491 * queue_delayed_work_on - queue work on specific CPU after delay
2492 * @cpu: CPU number to execute work on
2493 * @wq: workqueue to use
2494 * @dwork: work to queue
2495 * @delay: number of jiffies to wait before queueing
2497 * Return: %false if @work was already on a queue, %true otherwise. If
2498 * @delay is zero and @dwork is idle, it will be scheduled for immediate
2501 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
2502 struct delayed_work *dwork, unsigned long delay)
2504 struct work_struct *work = &dwork->work;
2506 unsigned long flags;
2508 /* read the comment in __queue_work() */
2509 local_irq_save(flags);
2511 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
2512 __queue_delayed_work(cpu, wq, dwork, delay);
2516 local_irq_restore(flags);
2519 EXPORT_SYMBOL(queue_delayed_work_on);
2522 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
2523 * @cpu: CPU number to execute work on
2524 * @wq: workqueue to use
2525 * @dwork: work to queue
2526 * @delay: number of jiffies to wait before queueing
2528 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
2529 * modify @dwork's timer so that it expires after @delay. If @delay is
2530 * zero, @work is guaranteed to be scheduled immediately regardless of its
2533 * Return: %false if @dwork was idle and queued, %true if @dwork was
2534 * pending and its timer was modified.
2536 * This function is safe to call from any context including IRQ handler.
2537 * See try_to_grab_pending() for details.
2539 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
2540 struct delayed_work *dwork, unsigned long delay)
2542 unsigned long flags;
2546 ret = try_to_grab_pending(&dwork->work, true, &flags);
2547 } while (unlikely(ret == -EAGAIN));
2549 if (likely(ret >= 0)) {
2550 __queue_delayed_work(cpu, wq, dwork, delay);
2551 local_irq_restore(flags);
2554 /* -ENOENT from try_to_grab_pending() becomes %true */
2557 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
2559 static void rcu_work_rcufn(struct rcu_head *rcu)
2561 struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
2563 /* read the comment in __queue_work() */
2564 local_irq_disable();
2565 __queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
2570 * queue_rcu_work - queue work after a RCU grace period
2571 * @wq: workqueue to use
2572 * @rwork: work to queue
2574 * Return: %false if @rwork was already pending, %true otherwise. Note
2575 * that a full RCU grace period is guaranteed only after a %true return.
2576 * While @rwork is guaranteed to be executed after a %false return, the
2577 * execution may happen before a full RCU grace period has passed.
2579 bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
2581 struct work_struct *work = &rwork->work;
2583 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
2585 call_rcu_hurry(&rwork->rcu, rcu_work_rcufn);
2591 EXPORT_SYMBOL(queue_rcu_work);
2593 static struct worker *alloc_worker(int node)
2595 struct worker *worker;
2597 worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
2599 INIT_LIST_HEAD(&worker->entry);
2600 INIT_LIST_HEAD(&worker->scheduled);
2601 INIT_LIST_HEAD(&worker->node);
2602 /* on creation a worker is in !idle && prep state */
2603 worker->flags = WORKER_PREP;
2608 static cpumask_t *pool_allowed_cpus(struct worker_pool *pool)
2610 if (pool->cpu < 0 && pool->attrs->affn_strict)
2611 return pool->attrs->__pod_cpumask;
2613 return pool->attrs->cpumask;
2617 * worker_attach_to_pool() - attach a worker to a pool
2618 * @worker: worker to be attached
2619 * @pool: the target pool
2621 * Attach @worker to @pool. Once attached, the %WORKER_UNBOUND flag and
2622 * cpu-binding of @worker are kept coordinated with the pool across
2625 static void worker_attach_to_pool(struct worker *worker,
2626 struct worker_pool *pool)
2628 mutex_lock(&wq_pool_attach_mutex);
2631 * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains stable
2632 * across this function. See the comments above the flag definition for
2633 * details. BH workers are, while per-CPU, always DISASSOCIATED.
2635 if (pool->flags & POOL_DISASSOCIATED) {
2636 worker->flags |= WORKER_UNBOUND;
2638 WARN_ON_ONCE(pool->flags & POOL_BH);
2639 kthread_set_per_cpu(worker->task, pool->cpu);
2642 if (worker->rescue_wq)
2643 set_cpus_allowed_ptr(worker->task, pool_allowed_cpus(pool));
2645 list_add_tail(&worker->node, &pool->workers);
2646 worker->pool = pool;
2648 mutex_unlock(&wq_pool_attach_mutex);
2652 * worker_detach_from_pool() - detach a worker from its pool
2653 * @worker: worker which is attached to its pool
2655 * Undo the attaching which had been done in worker_attach_to_pool(). The
2656 * caller worker shouldn't access to the pool after detached except it has
2657 * other reference to the pool.
2659 static void worker_detach_from_pool(struct worker *worker)
2661 struct worker_pool *pool = worker->pool;
2662 struct completion *detach_completion = NULL;
2664 /* there is one permanent BH worker per CPU which should never detach */
2665 WARN_ON_ONCE(pool->flags & POOL_BH);
2667 mutex_lock(&wq_pool_attach_mutex);
2669 kthread_set_per_cpu(worker->task, -1);
2670 list_del(&worker->node);
2671 worker->pool = NULL;
2673 if (list_empty(&pool->workers) && list_empty(&pool->dying_workers))
2674 detach_completion = pool->detach_completion;
2675 mutex_unlock(&wq_pool_attach_mutex);
2677 /* clear leftover flags without pool->lock after it is detached */
2678 worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
2680 if (detach_completion)
2681 complete(detach_completion);
2685 * create_worker - create a new workqueue worker
2686 * @pool: pool the new worker will belong to
2688 * Create and start a new worker which is attached to @pool.
2691 * Might sleep. Does GFP_KERNEL allocations.
2694 * Pointer to the newly created worker.
2696 static struct worker *create_worker(struct worker_pool *pool)
2698 struct worker *worker;
2702 /* ID is needed to determine kthread name */
2703 id = ida_alloc(&pool->worker_ida, GFP_KERNEL);
2705 pr_err_once("workqueue: Failed to allocate a worker ID: %pe\n",
2710 worker = alloc_worker(pool->node);
2712 pr_err_once("workqueue: Failed to allocate a worker\n");
2718 if (!(pool->flags & POOL_BH)) {
2720 snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
2721 pool->attrs->nice < 0 ? "H" : "");
2723 snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
2725 worker->task = kthread_create_on_node(worker_thread, worker,
2726 pool->node, "kworker/%s", id_buf);
2727 if (IS_ERR(worker->task)) {
2728 if (PTR_ERR(worker->task) == -EINTR) {
2729 pr_err("workqueue: Interrupted when creating a worker thread \"kworker/%s\"\n",
2732 pr_err_once("workqueue: Failed to create a worker thread: %pe",
2738 set_user_nice(worker->task, pool->attrs->nice);
2739 kthread_bind_mask(worker->task, pool_allowed_cpus(pool));
2742 /* successful, attach the worker to the pool */
2743 worker_attach_to_pool(worker, pool);
2745 /* start the newly created worker */
2746 raw_spin_lock_irq(&pool->lock);
2748 worker->pool->nr_workers++;
2749 worker_enter_idle(worker);
2752 * @worker is waiting on a completion in kthread() and will trigger hung
2753 * check if not woken up soon. As kick_pool() is noop if @pool is empty,
2754 * wake it up explicitly.
2757 wake_up_process(worker->task);
2759 raw_spin_unlock_irq(&pool->lock);
2764 ida_free(&pool->worker_ida, id);
2769 static void unbind_worker(struct worker *worker)
2771 lockdep_assert_held(&wq_pool_attach_mutex);
2773 kthread_set_per_cpu(worker->task, -1);
2774 if (cpumask_intersects(wq_unbound_cpumask, cpu_active_mask))
2775 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, wq_unbound_cpumask) < 0);
2777 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, cpu_possible_mask) < 0);
2780 static void wake_dying_workers(struct list_head *cull_list)
2782 struct worker *worker, *tmp;
2784 list_for_each_entry_safe(worker, tmp, cull_list, entry) {
2785 list_del_init(&worker->entry);
2786 unbind_worker(worker);
2788 * If the worker was somehow already running, then it had to be
2789 * in pool->idle_list when set_worker_dying() happened or we
2790 * wouldn't have gotten here.
2792 * Thus, the worker must either have observed the WORKER_DIE
2793 * flag, or have set its state to TASK_IDLE. Either way, the
2794 * below will be observed by the worker and is safe to do
2795 * outside of pool->lock.
2797 wake_up_process(worker->task);
2802 * set_worker_dying - Tag a worker for destruction
2803 * @worker: worker to be destroyed
2804 * @list: transfer worker away from its pool->idle_list and into list
2806 * Tag @worker for destruction and adjust @pool stats accordingly. The worker
2810 * raw_spin_lock_irq(pool->lock).
2812 static void set_worker_dying(struct worker *worker, struct list_head *list)
2814 struct worker_pool *pool = worker->pool;
2816 lockdep_assert_held(&pool->lock);
2817 lockdep_assert_held(&wq_pool_attach_mutex);
2819 /* sanity check frenzy */
2820 if (WARN_ON(worker->current_work) ||
2821 WARN_ON(!list_empty(&worker->scheduled)) ||
2822 WARN_ON(!(worker->flags & WORKER_IDLE)))
2828 worker->flags |= WORKER_DIE;
2830 list_move(&worker->entry, list);
2831 list_move(&worker->node, &pool->dying_workers);
2835 * idle_worker_timeout - check if some idle workers can now be deleted.
2836 * @t: The pool's idle_timer that just expired
2838 * The timer is armed in worker_enter_idle(). Note that it isn't disarmed in
2839 * worker_leave_idle(), as a worker flicking between idle and active while its
2840 * pool is at the too_many_workers() tipping point would cause too much timer
2841 * housekeeping overhead. Since IDLE_WORKER_TIMEOUT is long enough, we just let
2842 * it expire and re-evaluate things from there.
2844 static void idle_worker_timeout(struct timer_list *t)
2846 struct worker_pool *pool = from_timer(pool, t, idle_timer);
2847 bool do_cull = false;
2849 if (work_pending(&pool->idle_cull_work))
2852 raw_spin_lock_irq(&pool->lock);
2854 if (too_many_workers(pool)) {
2855 struct worker *worker;
2856 unsigned long expires;
2858 /* idle_list is kept in LIFO order, check the last one */
2859 worker = list_entry(pool->idle_list.prev, struct worker, entry);
2860 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2861 do_cull = !time_before(jiffies, expires);
2864 mod_timer(&pool->idle_timer, expires);
2866 raw_spin_unlock_irq(&pool->lock);
2869 queue_work(system_unbound_wq, &pool->idle_cull_work);
2873 * idle_cull_fn - cull workers that have been idle for too long.
2874 * @work: the pool's work for handling these idle workers
2876 * This goes through a pool's idle workers and gets rid of those that have been
2877 * idle for at least IDLE_WORKER_TIMEOUT seconds.
2879 * We don't want to disturb isolated CPUs because of a pcpu kworker being
2880 * culled, so this also resets worker affinity. This requires a sleepable
2881 * context, hence the split between timer callback and work item.
2883 static void idle_cull_fn(struct work_struct *work)
2885 struct worker_pool *pool = container_of(work, struct worker_pool, idle_cull_work);
2886 LIST_HEAD(cull_list);
2889 * Grabbing wq_pool_attach_mutex here ensures an already-running worker
2890 * cannot proceed beyong worker_detach_from_pool() in its self-destruct
2891 * path. This is required as a previously-preempted worker could run after
2892 * set_worker_dying() has happened but before wake_dying_workers() did.
2894 mutex_lock(&wq_pool_attach_mutex);
2895 raw_spin_lock_irq(&pool->lock);
2897 while (too_many_workers(pool)) {
2898 struct worker *worker;
2899 unsigned long expires;
2901 worker = list_entry(pool->idle_list.prev, struct worker, entry);
2902 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2904 if (time_before(jiffies, expires)) {
2905 mod_timer(&pool->idle_timer, expires);
2909 set_worker_dying(worker, &cull_list);
2912 raw_spin_unlock_irq(&pool->lock);
2913 wake_dying_workers(&cull_list);
2914 mutex_unlock(&wq_pool_attach_mutex);
2917 static void send_mayday(struct work_struct *work)
2919 struct pool_workqueue *pwq = get_work_pwq(work);
2920 struct workqueue_struct *wq = pwq->wq;
2922 lockdep_assert_held(&wq_mayday_lock);
2927 /* mayday mayday mayday */
2928 if (list_empty(&pwq->mayday_node)) {
2930 * If @pwq is for an unbound wq, its base ref may be put at
2931 * any time due to an attribute change. Pin @pwq until the
2932 * rescuer is done with it.
2935 list_add_tail(&pwq->mayday_node, &wq->maydays);
2936 wake_up_process(wq->rescuer->task);
2937 pwq->stats[PWQ_STAT_MAYDAY]++;
2941 static void pool_mayday_timeout(struct timer_list *t)
2943 struct worker_pool *pool = from_timer(pool, t, mayday_timer);
2944 struct work_struct *work;
2946 raw_spin_lock_irq(&pool->lock);
2947 raw_spin_lock(&wq_mayday_lock); /* for wq->maydays */
2949 if (need_to_create_worker(pool)) {
2951 * We've been trying to create a new worker but
2952 * haven't been successful. We might be hitting an
2953 * allocation deadlock. Send distress signals to
2956 list_for_each_entry(work, &pool->worklist, entry)
2960 raw_spin_unlock(&wq_mayday_lock);
2961 raw_spin_unlock_irq(&pool->lock);
2963 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
2967 * maybe_create_worker - create a new worker if necessary
2968 * @pool: pool to create a new worker for
2970 * Create a new worker for @pool if necessary. @pool is guaranteed to
2971 * have at least one idle worker on return from this function. If
2972 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
2973 * sent to all rescuers with works scheduled on @pool to resolve
2974 * possible allocation deadlock.
2976 * On return, need_to_create_worker() is guaranteed to be %false and
2977 * may_start_working() %true.
2980 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2981 * multiple times. Does GFP_KERNEL allocations. Called only from
2984 static void maybe_create_worker(struct worker_pool *pool)
2985 __releases(&pool->lock)
2986 __acquires(&pool->lock)
2989 raw_spin_unlock_irq(&pool->lock);
2991 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
2992 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
2995 if (create_worker(pool) || !need_to_create_worker(pool))
2998 schedule_timeout_interruptible(CREATE_COOLDOWN);
3000 if (!need_to_create_worker(pool))
3004 del_timer_sync(&pool->mayday_timer);
3005 raw_spin_lock_irq(&pool->lock);
3007 * This is necessary even after a new worker was just successfully
3008 * created as @pool->lock was dropped and the new worker might have
3009 * already become busy.
3011 if (need_to_create_worker(pool))
3016 * manage_workers - manage worker pool
3019 * Assume the manager role and manage the worker pool @worker belongs
3020 * to. At any given time, there can be only zero or one manager per
3021 * pool. The exclusion is handled automatically by this function.
3023 * The caller can safely start processing works on false return. On
3024 * true return, it's guaranteed that need_to_create_worker() is false
3025 * and may_start_working() is true.
3028 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
3029 * multiple times. Does GFP_KERNEL allocations.
3032 * %false if the pool doesn't need management and the caller can safely
3033 * start processing works, %true if management function was performed and
3034 * the conditions that the caller verified before calling the function may
3035 * no longer be true.
3037 static bool manage_workers(struct worker *worker)
3039 struct worker_pool *pool = worker->pool;
3041 if (pool->flags & POOL_MANAGER_ACTIVE)
3044 pool->flags |= POOL_MANAGER_ACTIVE;
3045 pool->manager = worker;
3047 maybe_create_worker(pool);
3049 pool->manager = NULL;
3050 pool->flags &= ~POOL_MANAGER_ACTIVE;
3051 rcuwait_wake_up(&manager_wait);
3056 * process_one_work - process single work
3058 * @work: work to process
3060 * Process @work. This function contains all the logics necessary to
3061 * process a single work including synchronization against and
3062 * interaction with other workers on the same cpu, queueing and
3063 * flushing. As long as context requirement is met, any worker can
3064 * call this function to process a work.
3067 * raw_spin_lock_irq(pool->lock) which is released and regrabbed.
3069 static void process_one_work(struct worker *worker, struct work_struct *work)
3070 __releases(&pool->lock)
3071 __acquires(&pool->lock)
3073 struct pool_workqueue *pwq = get_work_pwq(work);
3074 struct worker_pool *pool = worker->pool;
3075 unsigned long work_data;
3076 int lockdep_start_depth, rcu_start_depth;
3077 #ifdef CONFIG_LOCKDEP
3079 * It is permissible to free the struct work_struct from
3080 * inside the function that is called from it, this we need to
3081 * take into account for lockdep too. To avoid bogus "held
3082 * lock freed" warnings as well as problems when looking into
3083 * work->lockdep_map, make a copy and use that here.
3085 struct lockdep_map lockdep_map;
3087 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
3089 /* ensure we're on the correct CPU */
3090 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
3091 raw_smp_processor_id() != pool->cpu);
3093 /* claim and dequeue */
3094 debug_work_deactivate(work);
3095 hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
3096 worker->current_work = work;
3097 worker->current_func = work->func;
3098 worker->current_pwq = pwq;
3100 worker->current_at = worker->task->se.sum_exec_runtime;
3101 work_data = *work_data_bits(work);
3102 worker->current_color = get_work_color(work_data);
3105 * Record wq name for cmdline and debug reporting, may get
3106 * overridden through set_worker_desc().
3108 strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
3110 list_del_init(&work->entry);
3113 * CPU intensive works don't participate in concurrency management.
3114 * They're the scheduler's responsibility. This takes @worker out
3115 * of concurrency management and the next code block will chain
3116 * execution of the pending work items.
3118 if (unlikely(pwq->wq->flags & WQ_CPU_INTENSIVE))
3119 worker_set_flags(worker, WORKER_CPU_INTENSIVE);
3122 * Kick @pool if necessary. It's always noop for per-cpu worker pools
3123 * since nr_running would always be >= 1 at this point. This is used to
3124 * chain execution of the pending work items for WORKER_NOT_RUNNING
3125 * workers such as the UNBOUND and CPU_INTENSIVE ones.
3130 * Record the last pool and clear PENDING which should be the last
3131 * update to @work. Also, do this inside @pool->lock so that
3132 * PENDING and queued state changes happen together while IRQ is
3135 set_work_pool_and_clear_pending(work, pool->id);
3137 pwq->stats[PWQ_STAT_STARTED]++;
3138 raw_spin_unlock_irq(&pool->lock);
3140 rcu_start_depth = rcu_preempt_depth();
3141 lockdep_start_depth = lockdep_depth(current);
3142 lock_map_acquire(&pwq->wq->lockdep_map);
3143 lock_map_acquire(&lockdep_map);
3145 * Strictly speaking we should mark the invariant state without holding
3146 * any locks, that is, before these two lock_map_acquire()'s.
3148 * However, that would result in:
3155 * Which would create W1->C->W1 dependencies, even though there is no
3156 * actual deadlock possible. There are two solutions, using a
3157 * read-recursive acquire on the work(queue) 'locks', but this will then
3158 * hit the lockdep limitation on recursive locks, or simply discard
3161 * AFAICT there is no possible deadlock scenario between the
3162 * flush_work() and complete() primitives (except for single-threaded
3163 * workqueues), so hiding them isn't a problem.
3165 lockdep_invariant_state(true);
3166 trace_workqueue_execute_start(work);
3167 worker->current_func(work);
3169 * While we must be careful to not use "work" after this, the trace
3170 * point will only record its address.
3172 trace_workqueue_execute_end(work, worker->current_func);
3173 pwq->stats[PWQ_STAT_COMPLETED]++;
3174 lock_map_release(&lockdep_map);
3175 lock_map_release(&pwq->wq->lockdep_map);
3177 if (unlikely((worker->task && in_atomic()) ||
3178 lockdep_depth(current) != lockdep_start_depth ||
3179 rcu_preempt_depth() != rcu_start_depth)) {
3180 pr_err("BUG: workqueue leaked atomic, lock or RCU: %s[%d]\n"
3181 " preempt=0x%08x lock=%d->%d RCU=%d->%d workfn=%ps\n",
3182 current->comm, task_pid_nr(current), preempt_count(),
3183 lockdep_start_depth, lockdep_depth(current),
3184 rcu_start_depth, rcu_preempt_depth(),
3185 worker->current_func);
3186 debug_show_held_locks(current);
3191 * The following prevents a kworker from hogging CPU on !PREEMPTION
3192 * kernels, where a requeueing work item waiting for something to
3193 * happen could deadlock with stop_machine as such work item could
3194 * indefinitely requeue itself while all other CPUs are trapped in
3195 * stop_machine. At the same time, report a quiescent RCU state so
3196 * the same condition doesn't freeze RCU.
3201 raw_spin_lock_irq(&pool->lock);
3204 * In addition to %WQ_CPU_INTENSIVE, @worker may also have been marked
3205 * CPU intensive by wq_worker_tick() if @work hogged CPU longer than
3206 * wq_cpu_intensive_thresh_us. Clear it.
3208 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
3210 /* tag the worker for identification in schedule() */
3211 worker->last_func = worker->current_func;
3213 /* we're done with it, release */
3214 hash_del(&worker->hentry);
3215 worker->current_work = NULL;
3216 worker->current_func = NULL;
3217 worker->current_pwq = NULL;
3218 worker->current_color = INT_MAX;
3220 /* must be the last step, see the function comment */
3221 pwq_dec_nr_in_flight(pwq, work_data);
3225 * process_scheduled_works - process scheduled works
3228 * Process all scheduled works. Please note that the scheduled list
3229 * may change while processing a work, so this function repeatedly
3230 * fetches a work from the top and executes it.
3233 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
3236 static void process_scheduled_works(struct worker *worker)
3238 struct work_struct *work;
3241 while ((work = list_first_entry_or_null(&worker->scheduled,
3242 struct work_struct, entry))) {
3244 worker->pool->watchdog_ts = jiffies;
3247 process_one_work(worker, work);
3251 static void set_pf_worker(bool val)
3253 mutex_lock(&wq_pool_attach_mutex);
3255 current->flags |= PF_WQ_WORKER;
3257 current->flags &= ~PF_WQ_WORKER;
3258 mutex_unlock(&wq_pool_attach_mutex);
3262 * worker_thread - the worker thread function
3265 * The worker thread function. All workers belong to a worker_pool -
3266 * either a per-cpu one or dynamic unbound one. These workers process all
3267 * work items regardless of their specific target workqueue. The only
3268 * exception is work items which belong to workqueues with a rescuer which
3269 * will be explained in rescuer_thread().
3273 static int worker_thread(void *__worker)
3275 struct worker *worker = __worker;
3276 struct worker_pool *pool = worker->pool;
3278 /* tell the scheduler that this is a workqueue worker */
3279 set_pf_worker(true);
3281 raw_spin_lock_irq(&pool->lock);
3283 /* am I supposed to die? */
3284 if (unlikely(worker->flags & WORKER_DIE)) {
3285 raw_spin_unlock_irq(&pool->lock);
3286 set_pf_worker(false);
3288 set_task_comm(worker->task, "kworker/dying");
3289 ida_free(&pool->worker_ida, worker->id);
3290 worker_detach_from_pool(worker);
3291 WARN_ON_ONCE(!list_empty(&worker->entry));
3296 worker_leave_idle(worker);
3298 /* no more worker necessary? */
3299 if (!need_more_worker(pool))
3302 /* do we need to manage? */
3303 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
3307 * ->scheduled list can only be filled while a worker is
3308 * preparing to process a work or actually processing it.
3309 * Make sure nobody diddled with it while I was sleeping.
3311 WARN_ON_ONCE(!list_empty(&worker->scheduled));
3314 * Finish PREP stage. We're guaranteed to have at least one idle
3315 * worker or that someone else has already assumed the manager
3316 * role. This is where @worker starts participating in concurrency
3317 * management if applicable and concurrency management is restored
3318 * after being rebound. See rebind_workers() for details.
3320 worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
3323 struct work_struct *work =
3324 list_first_entry(&pool->worklist,
3325 struct work_struct, entry);
3327 if (assign_work(work, worker, NULL))
3328 process_scheduled_works(worker);
3329 } while (keep_working(pool));
3331 worker_set_flags(worker, WORKER_PREP);
3334 * pool->lock is held and there's no work to process and no need to
3335 * manage, sleep. Workers are woken up only while holding
3336 * pool->lock or from local cpu, so setting the current state
3337 * before releasing pool->lock is enough to prevent losing any
3340 worker_enter_idle(worker);
3341 __set_current_state(TASK_IDLE);
3342 raw_spin_unlock_irq(&pool->lock);
3348 * rescuer_thread - the rescuer thread function
3351 * Workqueue rescuer thread function. There's one rescuer for each
3352 * workqueue which has WQ_MEM_RECLAIM set.
3354 * Regular work processing on a pool may block trying to create a new
3355 * worker which uses GFP_KERNEL allocation which has slight chance of
3356 * developing into deadlock if some works currently on the same queue
3357 * need to be processed to satisfy the GFP_KERNEL allocation. This is
3358 * the problem rescuer solves.
3360 * When such condition is possible, the pool summons rescuers of all
3361 * workqueues which have works queued on the pool and let them process
3362 * those works so that forward progress can be guaranteed.
3364 * This should happen rarely.
3368 static int rescuer_thread(void *__rescuer)
3370 struct worker *rescuer = __rescuer;
3371 struct workqueue_struct *wq = rescuer->rescue_wq;
3374 set_user_nice(current, RESCUER_NICE_LEVEL);
3377 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
3378 * doesn't participate in concurrency management.
3380 set_pf_worker(true);
3382 set_current_state(TASK_IDLE);
3385 * By the time the rescuer is requested to stop, the workqueue
3386 * shouldn't have any work pending, but @wq->maydays may still have
3387 * pwq(s) queued. This can happen by non-rescuer workers consuming
3388 * all the work items before the rescuer got to them. Go through
3389 * @wq->maydays processing before acting on should_stop so that the
3390 * list is always empty on exit.
3392 should_stop = kthread_should_stop();
3394 /* see whether any pwq is asking for help */
3395 raw_spin_lock_irq(&wq_mayday_lock);
3397 while (!list_empty(&wq->maydays)) {
3398 struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
3399 struct pool_workqueue, mayday_node);
3400 struct worker_pool *pool = pwq->pool;
3401 struct work_struct *work, *n;
3403 __set_current_state(TASK_RUNNING);
3404 list_del_init(&pwq->mayday_node);
3406 raw_spin_unlock_irq(&wq_mayday_lock);
3408 worker_attach_to_pool(rescuer, pool);
3410 raw_spin_lock_irq(&pool->lock);
3413 * Slurp in all works issued via this workqueue and
3416 WARN_ON_ONCE(!list_empty(&rescuer->scheduled));
3417 list_for_each_entry_safe(work, n, &pool->worklist, entry) {
3418 if (get_work_pwq(work) == pwq &&
3419 assign_work(work, rescuer, &n))
3420 pwq->stats[PWQ_STAT_RESCUED]++;
3423 if (!list_empty(&rescuer->scheduled)) {
3424 process_scheduled_works(rescuer);
3427 * The above execution of rescued work items could
3428 * have created more to rescue through
3429 * pwq_activate_first_inactive() or chained
3430 * queueing. Let's put @pwq back on mayday list so
3431 * that such back-to-back work items, which may be
3432 * being used to relieve memory pressure, don't
3433 * incur MAYDAY_INTERVAL delay inbetween.
3435 if (pwq->nr_active && need_to_create_worker(pool)) {
3436 raw_spin_lock(&wq_mayday_lock);
3438 * Queue iff we aren't racing destruction
3439 * and somebody else hasn't queued it already.
3441 if (wq->rescuer && list_empty(&pwq->mayday_node)) {
3443 list_add_tail(&pwq->mayday_node, &wq->maydays);
3445 raw_spin_unlock(&wq_mayday_lock);
3450 * Put the reference grabbed by send_mayday(). @pool won't
3451 * go away while we're still attached to it.
3456 * Leave this pool. Notify regular workers; otherwise, we end up
3457 * with 0 concurrency and stalling the execution.
3461 raw_spin_unlock_irq(&pool->lock);
3463 worker_detach_from_pool(rescuer);
3465 raw_spin_lock_irq(&wq_mayday_lock);
3468 raw_spin_unlock_irq(&wq_mayday_lock);
3471 __set_current_state(TASK_RUNNING);
3472 set_pf_worker(false);
3476 /* rescuers should never participate in concurrency management */
3477 WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
3482 static void bh_worker(struct worker *worker)
3484 struct worker_pool *pool = worker->pool;
3485 int nr_restarts = BH_WORKER_RESTARTS;
3486 unsigned long end = jiffies + BH_WORKER_JIFFIES;
3488 raw_spin_lock_irq(&pool->lock);
3489 worker_leave_idle(worker);
3492 * This function follows the structure of worker_thread(). See there for
3493 * explanations on each step.
3495 if (!need_more_worker(pool))
3498 WARN_ON_ONCE(!list_empty(&worker->scheduled));
3499 worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
3502 struct work_struct *work =
3503 list_first_entry(&pool->worklist,
3504 struct work_struct, entry);
3506 if (assign_work(work, worker, NULL))
3507 process_scheduled_works(worker);
3508 } while (keep_working(pool) &&
3509 --nr_restarts && time_before(jiffies, end));
3511 worker_set_flags(worker, WORKER_PREP);
3513 worker_enter_idle(worker);
3515 raw_spin_unlock_irq(&pool->lock);
3519 * TODO: Convert all tasklet users to workqueue and use softirq directly.
3521 * This is currently called from tasklet[_hi]action() and thus is also called
3522 * whenever there are tasklets to run. Let's do an early exit if there's nothing
3523 * queued. Once conversion from tasklet is complete, the need_more_worker() test
3526 * After full conversion, we'll add worker->softirq_action, directly use the
3527 * softirq action and obtain the worker pointer from the softirq_action pointer.
3529 void workqueue_softirq_action(bool highpri)
3531 struct worker_pool *pool =
3532 &per_cpu(bh_worker_pools, smp_processor_id())[highpri];
3533 if (need_more_worker(pool))
3534 bh_worker(list_first_entry(&pool->workers, struct worker, node));
3538 * check_flush_dependency - check for flush dependency sanity
3539 * @target_wq: workqueue being flushed
3540 * @target_work: work item being flushed (NULL for workqueue flushes)
3542 * %current is trying to flush the whole @target_wq or @target_work on it.
3543 * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
3544 * reclaiming memory or running on a workqueue which doesn't have
3545 * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
3548 static void check_flush_dependency(struct workqueue_struct *target_wq,
3549 struct work_struct *target_work)
3551 work_func_t target_func = target_work ? target_work->func : NULL;
3552 struct worker *worker;
3554 if (target_wq->flags & WQ_MEM_RECLAIM)
3557 worker = current_wq_worker();
3559 WARN_ONCE(current->flags & PF_MEMALLOC,
3560 "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps",
3561 current->pid, current->comm, target_wq->name, target_func);
3562 WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
3563 (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
3564 "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps",
3565 worker->current_pwq->wq->name, worker->current_func,
3566 target_wq->name, target_func);
3570 struct work_struct work;
3571 struct completion done;
3572 struct task_struct *task; /* purely informational */
3575 static void wq_barrier_func(struct work_struct *work)
3577 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
3578 complete(&barr->done);
3582 * insert_wq_barrier - insert a barrier work
3583 * @pwq: pwq to insert barrier into
3584 * @barr: wq_barrier to insert
3585 * @target: target work to attach @barr to
3586 * @worker: worker currently executing @target, NULL if @target is not executing
3588 * @barr is linked to @target such that @barr is completed only after
3589 * @target finishes execution. Please note that the ordering
3590 * guarantee is observed only with respect to @target and on the local
3593 * Currently, a queued barrier can't be canceled. This is because
3594 * try_to_grab_pending() can't determine whether the work to be
3595 * grabbed is at the head of the queue and thus can't clear LINKED
3596 * flag of the previous work while there must be a valid next work
3597 * after a work with LINKED flag set.
3599 * Note that when @worker is non-NULL, @target may be modified
3600 * underneath us, so we can't reliably determine pwq from @target.
3603 * raw_spin_lock_irq(pool->lock).
3605 static void insert_wq_barrier(struct pool_workqueue *pwq,
3606 struct wq_barrier *barr,
3607 struct work_struct *target, struct worker *worker)
3609 static __maybe_unused struct lock_class_key bh_key, thr_key;
3610 unsigned int work_flags = 0;
3611 unsigned int work_color;
3612 struct list_head *head;
3615 * debugobject calls are safe here even with pool->lock locked
3616 * as we know for sure that this will not trigger any of the
3617 * checks and call back into the fixup functions where we
3620 * BH and threaded workqueues need separate lockdep keys to avoid
3621 * spuriously triggering "inconsistent {SOFTIRQ-ON-W} -> {IN-SOFTIRQ-W}
3624 INIT_WORK_ONSTACK_KEY(&barr->work, wq_barrier_func,
3625 (pwq->wq->flags & WQ_BH) ? &bh_key : &thr_key);
3626 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
3628 init_completion_map(&barr->done, &target->lockdep_map);
3630 barr->task = current;
3632 /* The barrier work item does not participate in nr_active. */
3633 work_flags |= WORK_STRUCT_INACTIVE;
3636 * If @target is currently being executed, schedule the
3637 * barrier to the worker; otherwise, put it after @target.
3640 head = worker->scheduled.next;
3641 work_color = worker->current_color;
3643 unsigned long *bits = work_data_bits(target);
3645 head = target->entry.next;
3646 /* there can already be other linked works, inherit and set */
3647 work_flags |= *bits & WORK_STRUCT_LINKED;
3648 work_color = get_work_color(*bits);
3649 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
3652 pwq->nr_in_flight[work_color]++;
3653 work_flags |= work_color_to_flags(work_color);
3655 insert_work(pwq, &barr->work, head, work_flags);
3659 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
3660 * @wq: workqueue being flushed
3661 * @flush_color: new flush color, < 0 for no-op
3662 * @work_color: new work color, < 0 for no-op
3664 * Prepare pwqs for workqueue flushing.
3666 * If @flush_color is non-negative, flush_color on all pwqs should be
3667 * -1. If no pwq has in-flight commands at the specified color, all
3668 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
3669 * has in flight commands, its pwq->flush_color is set to
3670 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
3671 * wakeup logic is armed and %true is returned.
3673 * The caller should have initialized @wq->first_flusher prior to
3674 * calling this function with non-negative @flush_color. If
3675 * @flush_color is negative, no flush color update is done and %false
3678 * If @work_color is non-negative, all pwqs should have the same
3679 * work_color which is previous to @work_color and all will be
3680 * advanced to @work_color.
3683 * mutex_lock(wq->mutex).
3686 * %true if @flush_color >= 0 and there's something to flush. %false
3689 static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
3690 int flush_color, int work_color)
3693 struct pool_workqueue *pwq;
3695 if (flush_color >= 0) {
3696 WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
3697 atomic_set(&wq->nr_pwqs_to_flush, 1);
3700 for_each_pwq(pwq, wq) {
3701 struct worker_pool *pool = pwq->pool;
3703 raw_spin_lock_irq(&pool->lock);
3705 if (flush_color >= 0) {
3706 WARN_ON_ONCE(pwq->flush_color != -1);
3708 if (pwq->nr_in_flight[flush_color]) {
3709 pwq->flush_color = flush_color;
3710 atomic_inc(&wq->nr_pwqs_to_flush);
3715 if (work_color >= 0) {
3716 WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
3717 pwq->work_color = work_color;
3720 raw_spin_unlock_irq(&pool->lock);
3723 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
3724 complete(&wq->first_flusher->done);
3729 static void touch_wq_lockdep_map(struct workqueue_struct *wq)
3731 #ifdef CONFIG_LOCKDEP
3732 if (wq->flags & WQ_BH)
3735 lock_map_acquire(&wq->lockdep_map);
3736 lock_map_release(&wq->lockdep_map);
3738 if (wq->flags & WQ_BH)
3743 static void touch_work_lockdep_map(struct work_struct *work,
3744 struct workqueue_struct *wq)
3746 #ifdef CONFIG_LOCKDEP
3747 if (wq->flags & WQ_BH)
3750 lock_map_acquire(&work->lockdep_map);
3751 lock_map_release(&work->lockdep_map);
3753 if (wq->flags & WQ_BH)
3759 * __flush_workqueue - ensure that any scheduled work has run to completion.
3760 * @wq: workqueue to flush
3762 * This function sleeps until all work items which were queued on entry
3763 * have finished execution, but it is not livelocked by new incoming ones.
3765 void __flush_workqueue(struct workqueue_struct *wq)
3767 struct wq_flusher this_flusher = {
3768 .list = LIST_HEAD_INIT(this_flusher.list),
3770 .done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map),
3774 if (WARN_ON(!wq_online))
3777 touch_wq_lockdep_map(wq);
3779 mutex_lock(&wq->mutex);
3782 * Start-to-wait phase
3784 next_color = work_next_color(wq->work_color);
3786 if (next_color != wq->flush_color) {
3788 * Color space is not full. The current work_color
3789 * becomes our flush_color and work_color is advanced
3792 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
3793 this_flusher.flush_color = wq->work_color;
3794 wq->work_color = next_color;
3796 if (!wq->first_flusher) {
3797 /* no flush in progress, become the first flusher */
3798 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
3800 wq->first_flusher = &this_flusher;
3802 if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
3804 /* nothing to flush, done */
3805 wq->flush_color = next_color;
3806 wq->first_flusher = NULL;
3811 WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
3812 list_add_tail(&this_flusher.list, &wq->flusher_queue);
3813 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
3817 * Oops, color space is full, wait on overflow queue.
3818 * The next flush completion will assign us
3819 * flush_color and transfer to flusher_queue.
3821 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
3824 check_flush_dependency(wq, NULL);
3826 mutex_unlock(&wq->mutex);
3828 wait_for_completion(&this_flusher.done);
3831 * Wake-up-and-cascade phase
3833 * First flushers are responsible for cascading flushes and
3834 * handling overflow. Non-first flushers can simply return.
3836 if (READ_ONCE(wq->first_flusher) != &this_flusher)
3839 mutex_lock(&wq->mutex);
3841 /* we might have raced, check again with mutex held */
3842 if (wq->first_flusher != &this_flusher)
3845 WRITE_ONCE(wq->first_flusher, NULL);
3847 WARN_ON_ONCE(!list_empty(&this_flusher.list));
3848 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
3851 struct wq_flusher *next, *tmp;
3853 /* complete all the flushers sharing the current flush color */
3854 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
3855 if (next->flush_color != wq->flush_color)
3857 list_del_init(&next->list);
3858 complete(&next->done);
3861 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
3862 wq->flush_color != work_next_color(wq->work_color));
3864 /* this flush_color is finished, advance by one */
3865 wq->flush_color = work_next_color(wq->flush_color);
3867 /* one color has been freed, handle overflow queue */
3868 if (!list_empty(&wq->flusher_overflow)) {
3870 * Assign the same color to all overflowed
3871 * flushers, advance work_color and append to
3872 * flusher_queue. This is the start-to-wait
3873 * phase for these overflowed flushers.
3875 list_for_each_entry(tmp, &wq->flusher_overflow, list)
3876 tmp->flush_color = wq->work_color;
3878 wq->work_color = work_next_color(wq->work_color);
3880 list_splice_tail_init(&wq->flusher_overflow,
3881 &wq->flusher_queue);
3882 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
3885 if (list_empty(&wq->flusher_queue)) {
3886 WARN_ON_ONCE(wq->flush_color != wq->work_color);
3891 * Need to flush more colors. Make the next flusher
3892 * the new first flusher and arm pwqs.
3894 WARN_ON_ONCE(wq->flush_color == wq->work_color);
3895 WARN_ON_ONCE(wq->flush_color != next->flush_color);
3897 list_del_init(&next->list);
3898 wq->first_flusher = next;
3900 if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
3904 * Meh... this color is already done, clear first
3905 * flusher and repeat cascading.
3907 wq->first_flusher = NULL;
3911 mutex_unlock(&wq->mutex);
3913 EXPORT_SYMBOL(__flush_workqueue);
3916 * drain_workqueue - drain a workqueue
3917 * @wq: workqueue to drain
3919 * Wait until the workqueue becomes empty. While draining is in progress,
3920 * only chain queueing is allowed. IOW, only currently pending or running
3921 * work items on @wq can queue further work items on it. @wq is flushed
3922 * repeatedly until it becomes empty. The number of flushing is determined
3923 * by the depth of chaining and should be relatively short. Whine if it
3926 void drain_workqueue(struct workqueue_struct *wq)
3928 unsigned int flush_cnt = 0;
3929 struct pool_workqueue *pwq;
3932 * __queue_work() needs to test whether there are drainers, is much
3933 * hotter than drain_workqueue() and already looks at @wq->flags.
3934 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
3936 mutex_lock(&wq->mutex);
3937 if (!wq->nr_drainers++)
3938 wq->flags |= __WQ_DRAINING;
3939 mutex_unlock(&wq->mutex);
3941 __flush_workqueue(wq);
3943 mutex_lock(&wq->mutex);
3945 for_each_pwq(pwq, wq) {
3948 raw_spin_lock_irq(&pwq->pool->lock);
3949 drained = pwq_is_empty(pwq);
3950 raw_spin_unlock_irq(&pwq->pool->lock);
3955 if (++flush_cnt == 10 ||
3956 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
3957 pr_warn("workqueue %s: %s() isn't complete after %u tries\n",
3958 wq->name, __func__, flush_cnt);
3960 mutex_unlock(&wq->mutex);
3964 if (!--wq->nr_drainers)
3965 wq->flags &= ~__WQ_DRAINING;
3966 mutex_unlock(&wq->mutex);
3968 EXPORT_SYMBOL_GPL(drain_workqueue);
3970 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
3973 struct worker *worker = NULL;
3974 struct worker_pool *pool;
3975 struct pool_workqueue *pwq;
3976 struct workqueue_struct *wq;
3981 pool = get_work_pool(work);
3987 raw_spin_lock_irq(&pool->lock);
3988 /* see the comment in try_to_grab_pending() with the same code */
3989 pwq = get_work_pwq(work);
3991 if (unlikely(pwq->pool != pool))
3994 worker = find_worker_executing_work(pool, work);
3997 pwq = worker->current_pwq;
4001 check_flush_dependency(wq, work);
4003 insert_wq_barrier(pwq, barr, work, worker);
4004 raw_spin_unlock_irq(&pool->lock);
4006 touch_work_lockdep_map(work, wq);
4009 * Force a lock recursion deadlock when using flush_work() inside a
4010 * single-threaded or rescuer equipped workqueue.
4012 * For single threaded workqueues the deadlock happens when the work
4013 * is after the work issuing the flush_work(). For rescuer equipped
4014 * workqueues the deadlock happens when the rescuer stalls, blocking
4017 if (!from_cancel && (wq->saved_max_active == 1 || wq->rescuer))
4018 touch_wq_lockdep_map(wq);
4023 raw_spin_unlock_irq(&pool->lock);
4028 static bool __flush_work(struct work_struct *work, bool from_cancel)
4030 struct wq_barrier barr;
4032 if (WARN_ON(!wq_online))
4035 if (WARN_ON(!work->func))
4038 if (start_flush_work(work, &barr, from_cancel)) {
4039 wait_for_completion(&barr.done);
4040 destroy_work_on_stack(&barr.work);
4048 * flush_work - wait for a work to finish executing the last queueing instance
4049 * @work: the work to flush
4051 * Wait until @work has finished execution. @work is guaranteed to be idle
4052 * on return if it hasn't been requeued since flush started.
4055 * %true if flush_work() waited for the work to finish execution,
4056 * %false if it was already idle.
4058 bool flush_work(struct work_struct *work)
4060 return __flush_work(work, false);
4062 EXPORT_SYMBOL_GPL(flush_work);
4065 * flush_delayed_work - wait for a dwork to finish executing the last queueing
4066 * @dwork: the delayed work to flush
4068 * Delayed timer is cancelled and the pending work is queued for
4069 * immediate execution. Like flush_work(), this function only
4070 * considers the last queueing instance of @dwork.
4073 * %true if flush_work() waited for the work to finish execution,
4074 * %false if it was already idle.
4076 bool flush_delayed_work(struct delayed_work *dwork)
4078 local_irq_disable();
4079 if (del_timer_sync(&dwork->timer))
4080 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
4082 return flush_work(&dwork->work);
4084 EXPORT_SYMBOL(flush_delayed_work);
4087 * flush_rcu_work - wait for a rwork to finish executing the last queueing
4088 * @rwork: the rcu work to flush
4091 * %true if flush_rcu_work() waited for the work to finish execution,
4092 * %false if it was already idle.
4094 bool flush_rcu_work(struct rcu_work *rwork)
4096 if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
4098 flush_work(&rwork->work);
4101 return flush_work(&rwork->work);
4104 EXPORT_SYMBOL(flush_rcu_work);
4106 static bool __cancel_work(struct work_struct *work, bool is_dwork)
4108 unsigned long flags;
4112 ret = try_to_grab_pending(work, is_dwork, &flags);
4113 } while (unlikely(ret == -EAGAIN));
4115 if (unlikely(ret < 0))
4118 set_work_pool_and_clear_pending(work, get_work_pool_id(work));
4119 local_irq_restore(flags);
4124 wait_queue_entry_t wait;
4125 struct work_struct *work;
4128 static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
4130 struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
4132 if (cwait->work != key)
4134 return autoremove_wake_function(wait, mode, sync, key);
4137 static bool __cancel_work_sync(struct work_struct *work, bool is_dwork)
4139 static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
4140 unsigned long flags;
4144 ret = try_to_grab_pending(work, is_dwork, &flags);
4146 * If someone else is already canceling, wait for it to
4147 * finish. flush_work() doesn't work for PREEMPT_NONE
4148 * because we may get scheduled between @work's completion
4149 * and the other canceling task resuming and clearing
4150 * CANCELING - flush_work() will return false immediately
4151 * as @work is no longer busy, try_to_grab_pending() will
4152 * return -ENOENT as @work is still being canceled and the
4153 * other canceling task won't be able to clear CANCELING as
4154 * we're hogging the CPU.
4156 * Let's wait for completion using a waitqueue. As this
4157 * may lead to the thundering herd problem, use a custom
4158 * wake function which matches @work along with exclusive
4161 if (unlikely(ret == -ENOENT)) {
4162 struct cwt_wait cwait;
4164 init_wait(&cwait.wait);
4165 cwait.wait.func = cwt_wakefn;
4168 prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
4169 TASK_UNINTERRUPTIBLE);
4170 if (work_is_canceling(work))
4172 finish_wait(&cancel_waitq, &cwait.wait);
4174 } while (unlikely(ret < 0));
4176 /* tell other tasks trying to grab @work to back off */
4177 mark_work_canceling(work);
4178 local_irq_restore(flags);
4181 * Skip __flush_work() during early boot when we know that @work isn't
4182 * executing. This allows canceling during early boot.
4185 __flush_work(work, true);
4187 clear_work_data(work);
4190 * Paired with prepare_to_wait() above so that either
4191 * waitqueue_active() is visible here or !work_is_canceling() is
4195 if (waitqueue_active(&cancel_waitq))
4196 __wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
4202 * See cancel_delayed_work()
4204 bool cancel_work(struct work_struct *work)
4206 return __cancel_work(work, false);
4208 EXPORT_SYMBOL(cancel_work);
4211 * cancel_work_sync - cancel a work and wait for it to finish
4212 * @work: the work to cancel
4214 * Cancel @work and wait for its execution to finish. This function
4215 * can be used even if the work re-queues itself or migrates to
4216 * another workqueue. On return from this function, @work is
4217 * guaranteed to be not pending or executing on any CPU.
4219 * cancel_work_sync(&delayed_work->work) must not be used for
4220 * delayed_work's. Use cancel_delayed_work_sync() instead.
4222 * The caller must ensure that the workqueue on which @work was last
4223 * queued can't be destroyed before this function returns.
4226 * %true if @work was pending, %false otherwise.
4228 bool cancel_work_sync(struct work_struct *work)
4230 return __cancel_work_sync(work, false);
4232 EXPORT_SYMBOL_GPL(cancel_work_sync);
4235 * cancel_delayed_work - cancel a delayed work
4236 * @dwork: delayed_work to cancel
4238 * Kill off a pending delayed_work.
4240 * Return: %true if @dwork was pending and canceled; %false if it wasn't
4244 * The work callback function may still be running on return, unless
4245 * it returns %true and the work doesn't re-arm itself. Explicitly flush or
4246 * use cancel_delayed_work_sync() to wait on it.
4248 * This function is safe to call from any context including IRQ handler.
4250 bool cancel_delayed_work(struct delayed_work *dwork)
4252 return __cancel_work(&dwork->work, true);
4254 EXPORT_SYMBOL(cancel_delayed_work);
4257 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
4258 * @dwork: the delayed work cancel
4260 * This is cancel_work_sync() for delayed works.
4263 * %true if @dwork was pending, %false otherwise.
4265 bool cancel_delayed_work_sync(struct delayed_work *dwork)
4267 return __cancel_work_sync(&dwork->work, true);
4269 EXPORT_SYMBOL(cancel_delayed_work_sync);
4272 * schedule_on_each_cpu - execute a function synchronously on each online CPU
4273 * @func: the function to call
4275 * schedule_on_each_cpu() executes @func on each online CPU using the
4276 * system workqueue and blocks until all CPUs have completed.
4277 * schedule_on_each_cpu() is very slow.
4280 * 0 on success, -errno on failure.
4282 int schedule_on_each_cpu(work_func_t func)
4285 struct work_struct __percpu *works;
4287 works = alloc_percpu(struct work_struct);
4293 for_each_online_cpu(cpu) {
4294 struct work_struct *work = per_cpu_ptr(works, cpu);
4296 INIT_WORK(work, func);
4297 schedule_work_on(cpu, work);
4300 for_each_online_cpu(cpu)
4301 flush_work(per_cpu_ptr(works, cpu));
4309 * execute_in_process_context - reliably execute the routine with user context
4310 * @fn: the function to execute
4311 * @ew: guaranteed storage for the execute work structure (must
4312 * be available when the work executes)
4314 * Executes the function immediately if process context is available,
4315 * otherwise schedules the function for delayed execution.
4317 * Return: 0 - function was executed
4318 * 1 - function was scheduled for execution
4320 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
4322 if (!in_interrupt()) {
4327 INIT_WORK(&ew->work, fn);
4328 schedule_work(&ew->work);
4332 EXPORT_SYMBOL_GPL(execute_in_process_context);
4335 * free_workqueue_attrs - free a workqueue_attrs
4336 * @attrs: workqueue_attrs to free
4338 * Undo alloc_workqueue_attrs().
4340 void free_workqueue_attrs(struct workqueue_attrs *attrs)
4343 free_cpumask_var(attrs->cpumask);
4344 free_cpumask_var(attrs->__pod_cpumask);
4350 * alloc_workqueue_attrs - allocate a workqueue_attrs
4352 * Allocate a new workqueue_attrs, initialize with default settings and
4355 * Return: The allocated new workqueue_attr on success. %NULL on failure.
4357 struct workqueue_attrs *alloc_workqueue_attrs(void)
4359 struct workqueue_attrs *attrs;
4361 attrs = kzalloc(sizeof(*attrs), GFP_KERNEL);
4364 if (!alloc_cpumask_var(&attrs->cpumask, GFP_KERNEL))
4366 if (!alloc_cpumask_var(&attrs->__pod_cpumask, GFP_KERNEL))
4369 cpumask_copy(attrs->cpumask, cpu_possible_mask);
4370 attrs->affn_scope = WQ_AFFN_DFL;
4373 free_workqueue_attrs(attrs);
4377 static void copy_workqueue_attrs(struct workqueue_attrs *to,
4378 const struct workqueue_attrs *from)
4380 to->nice = from->nice;
4381 cpumask_copy(to->cpumask, from->cpumask);
4382 cpumask_copy(to->__pod_cpumask, from->__pod_cpumask);
4383 to->affn_strict = from->affn_strict;
4386 * Unlike hash and equality test, copying shouldn't ignore wq-only
4387 * fields as copying is used for both pool and wq attrs. Instead,
4388 * get_unbound_pool() explicitly clears the fields.
4390 to->affn_scope = from->affn_scope;
4391 to->ordered = from->ordered;
4395 * Some attrs fields are workqueue-only. Clear them for worker_pool's. See the
4396 * comments in 'struct workqueue_attrs' definition.
4398 static void wqattrs_clear_for_pool(struct workqueue_attrs *attrs)
4400 attrs->affn_scope = WQ_AFFN_NR_TYPES;
4401 attrs->ordered = false;
4404 /* hash value of the content of @attr */
4405 static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
4409 hash = jhash_1word(attrs->nice, hash);
4410 hash = jhash(cpumask_bits(attrs->cpumask),
4411 BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
4412 hash = jhash(cpumask_bits(attrs->__pod_cpumask),
4413 BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
4414 hash = jhash_1word(attrs->affn_strict, hash);
4418 /* content equality test */
4419 static bool wqattrs_equal(const struct workqueue_attrs *a,
4420 const struct workqueue_attrs *b)
4422 if (a->nice != b->nice)
4424 if (!cpumask_equal(a->cpumask, b->cpumask))
4426 if (!cpumask_equal(a->__pod_cpumask, b->__pod_cpumask))
4428 if (a->affn_strict != b->affn_strict)
4433 /* Update @attrs with actually available CPUs */
4434 static void wqattrs_actualize_cpumask(struct workqueue_attrs *attrs,
4435 const cpumask_t *unbound_cpumask)
4438 * Calculate the effective CPU mask of @attrs given @unbound_cpumask. If
4439 * @attrs->cpumask doesn't overlap with @unbound_cpumask, we fallback to
4442 cpumask_and(attrs->cpumask, attrs->cpumask, unbound_cpumask);
4443 if (unlikely(cpumask_empty(attrs->cpumask)))
4444 cpumask_copy(attrs->cpumask, unbound_cpumask);
4447 /* find wq_pod_type to use for @attrs */
4448 static const struct wq_pod_type *
4449 wqattrs_pod_type(const struct workqueue_attrs *attrs)
4451 enum wq_affn_scope scope;
4452 struct wq_pod_type *pt;
4454 /* to synchronize access to wq_affn_dfl */
4455 lockdep_assert_held(&wq_pool_mutex);
4457 if (attrs->affn_scope == WQ_AFFN_DFL)
4458 scope = wq_affn_dfl;
4460 scope = attrs->affn_scope;
4462 pt = &wq_pod_types[scope];
4464 if (!WARN_ON_ONCE(attrs->affn_scope == WQ_AFFN_NR_TYPES) &&
4465 likely(pt->nr_pods))
4469 * Before workqueue_init_topology(), only SYSTEM is available which is
4470 * initialized in workqueue_init_early().
4472 pt = &wq_pod_types[WQ_AFFN_SYSTEM];
4473 BUG_ON(!pt->nr_pods);
4478 * init_worker_pool - initialize a newly zalloc'd worker_pool
4479 * @pool: worker_pool to initialize
4481 * Initialize a newly zalloc'd @pool. It also allocates @pool->attrs.
4483 * Return: 0 on success, -errno on failure. Even on failure, all fields
4484 * inside @pool proper are initialized and put_unbound_pool() can be called
4485 * on @pool safely to release it.
4487 static int init_worker_pool(struct worker_pool *pool)
4489 raw_spin_lock_init(&pool->lock);
4492 pool->node = NUMA_NO_NODE;
4493 pool->flags |= POOL_DISASSOCIATED;
4494 pool->watchdog_ts = jiffies;
4495 INIT_LIST_HEAD(&pool->worklist);
4496 INIT_LIST_HEAD(&pool->idle_list);
4497 hash_init(pool->busy_hash);
4499 timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
4500 INIT_WORK(&pool->idle_cull_work, idle_cull_fn);
4502 timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
4504 INIT_LIST_HEAD(&pool->workers);
4505 INIT_LIST_HEAD(&pool->dying_workers);
4507 ida_init(&pool->worker_ida);
4508 INIT_HLIST_NODE(&pool->hash_node);
4511 /* shouldn't fail above this point */
4512 pool->attrs = alloc_workqueue_attrs();
4516 wqattrs_clear_for_pool(pool->attrs);
4521 #ifdef CONFIG_LOCKDEP
4522 static void wq_init_lockdep(struct workqueue_struct *wq)
4526 lockdep_register_key(&wq->key);
4527 lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name);
4529 lock_name = wq->name;
4531 wq->lock_name = lock_name;
4532 lockdep_init_map(&wq->lockdep_map, lock_name, &wq->key, 0);
4535 static void wq_unregister_lockdep(struct workqueue_struct *wq)
4537 lockdep_unregister_key(&wq->key);
4540 static void wq_free_lockdep(struct workqueue_struct *wq)
4542 if (wq->lock_name != wq->name)
4543 kfree(wq->lock_name);
4546 static void wq_init_lockdep(struct workqueue_struct *wq)
4550 static void wq_unregister_lockdep(struct workqueue_struct *wq)
4554 static void wq_free_lockdep(struct workqueue_struct *wq)
4559 static void free_node_nr_active(struct wq_node_nr_active **nna_ar)
4563 for_each_node(node) {
4564 kfree(nna_ar[node]);
4565 nna_ar[node] = NULL;
4568 kfree(nna_ar[nr_node_ids]);
4569 nna_ar[nr_node_ids] = NULL;
4572 static void init_node_nr_active(struct wq_node_nr_active *nna)
4574 nna->max = WQ_DFL_MIN_ACTIVE;
4575 atomic_set(&nna->nr, 0);
4576 raw_spin_lock_init(&nna->lock);
4577 INIT_LIST_HEAD(&nna->pending_pwqs);
4581 * Each node's nr_active counter will be accessed mostly from its own node and
4582 * should be allocated in the node.
4584 static int alloc_node_nr_active(struct wq_node_nr_active **nna_ar)
4586 struct wq_node_nr_active *nna;
4589 for_each_node(node) {
4590 nna = kzalloc_node(sizeof(*nna), GFP_KERNEL, node);
4593 init_node_nr_active(nna);
4597 /* [nr_node_ids] is used as the fallback */
4598 nna = kzalloc_node(sizeof(*nna), GFP_KERNEL, NUMA_NO_NODE);
4601 init_node_nr_active(nna);
4602 nna_ar[nr_node_ids] = nna;
4607 free_node_nr_active(nna_ar);
4611 static void rcu_free_wq(struct rcu_head *rcu)
4613 struct workqueue_struct *wq =
4614 container_of(rcu, struct workqueue_struct, rcu);
4616 if (wq->flags & WQ_UNBOUND)
4617 free_node_nr_active(wq->node_nr_active);
4619 wq_free_lockdep(wq);
4620 free_percpu(wq->cpu_pwq);
4621 free_workqueue_attrs(wq->unbound_attrs);
4625 static void rcu_free_pool(struct rcu_head *rcu)
4627 struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
4629 ida_destroy(&pool->worker_ida);
4630 free_workqueue_attrs(pool->attrs);
4635 * put_unbound_pool - put a worker_pool
4636 * @pool: worker_pool to put
4638 * Put @pool. If its refcnt reaches zero, it gets destroyed in RCU
4639 * safe manner. get_unbound_pool() calls this function on its failure path
4640 * and this function should be able to release pools which went through,
4641 * successfully or not, init_worker_pool().
4643 * Should be called with wq_pool_mutex held.
4645 static void put_unbound_pool(struct worker_pool *pool)
4647 DECLARE_COMPLETION_ONSTACK(detach_completion);
4648 struct worker *worker;
4649 LIST_HEAD(cull_list);
4651 lockdep_assert_held(&wq_pool_mutex);
4657 if (WARN_ON(!(pool->cpu < 0)) ||
4658 WARN_ON(!list_empty(&pool->worklist)))
4661 /* release id and unhash */
4663 idr_remove(&worker_pool_idr, pool->id);
4664 hash_del(&pool->hash_node);
4667 * Become the manager and destroy all workers. This prevents
4668 * @pool's workers from blocking on attach_mutex. We're the last
4669 * manager and @pool gets freed with the flag set.
4671 * Having a concurrent manager is quite unlikely to happen as we can
4672 * only get here with
4673 * pwq->refcnt == pool->refcnt == 0
4674 * which implies no work queued to the pool, which implies no worker can
4675 * become the manager. However a worker could have taken the role of
4676 * manager before the refcnts dropped to 0, since maybe_create_worker()
4680 rcuwait_wait_event(&manager_wait,
4681 !(pool->flags & POOL_MANAGER_ACTIVE),
4682 TASK_UNINTERRUPTIBLE);
4684 mutex_lock(&wq_pool_attach_mutex);
4685 raw_spin_lock_irq(&pool->lock);
4686 if (!(pool->flags & POOL_MANAGER_ACTIVE)) {
4687 pool->flags |= POOL_MANAGER_ACTIVE;
4690 raw_spin_unlock_irq(&pool->lock);
4691 mutex_unlock(&wq_pool_attach_mutex);
4694 while ((worker = first_idle_worker(pool)))
4695 set_worker_dying(worker, &cull_list);
4696 WARN_ON(pool->nr_workers || pool->nr_idle);
4697 raw_spin_unlock_irq(&pool->lock);
4699 wake_dying_workers(&cull_list);
4701 if (!list_empty(&pool->workers) || !list_empty(&pool->dying_workers))
4702 pool->detach_completion = &detach_completion;
4703 mutex_unlock(&wq_pool_attach_mutex);
4705 if (pool->detach_completion)
4706 wait_for_completion(pool->detach_completion);
4708 /* shut down the timers */
4709 del_timer_sync(&pool->idle_timer);
4710 cancel_work_sync(&pool->idle_cull_work);
4711 del_timer_sync(&pool->mayday_timer);
4713 /* RCU protected to allow dereferences from get_work_pool() */
4714 call_rcu(&pool->rcu, rcu_free_pool);
4718 * get_unbound_pool - get a worker_pool with the specified attributes
4719 * @attrs: the attributes of the worker_pool to get
4721 * Obtain a worker_pool which has the same attributes as @attrs, bump the
4722 * reference count and return it. If there already is a matching
4723 * worker_pool, it will be used; otherwise, this function attempts to
4726 * Should be called with wq_pool_mutex held.
4728 * Return: On success, a worker_pool with the same attributes as @attrs.
4729 * On failure, %NULL.
4731 static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
4733 struct wq_pod_type *pt = &wq_pod_types[WQ_AFFN_NUMA];
4734 u32 hash = wqattrs_hash(attrs);
4735 struct worker_pool *pool;
4736 int pod, node = NUMA_NO_NODE;
4738 lockdep_assert_held(&wq_pool_mutex);
4740 /* do we already have a matching pool? */
4741 hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
4742 if (wqattrs_equal(pool->attrs, attrs)) {
4748 /* If __pod_cpumask is contained inside a NUMA pod, that's our node */
4749 for (pod = 0; pod < pt->nr_pods; pod++) {
4750 if (cpumask_subset(attrs->__pod_cpumask, pt->pod_cpus[pod])) {
4751 node = pt->pod_node[pod];
4756 /* nope, create a new one */
4757 pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, node);
4758 if (!pool || init_worker_pool(pool) < 0)
4762 copy_workqueue_attrs(pool->attrs, attrs);
4763 wqattrs_clear_for_pool(pool->attrs);
4765 if (worker_pool_assign_id(pool) < 0)
4768 /* create and start the initial worker */
4769 if (wq_online && !create_worker(pool))
4773 hash_add(unbound_pool_hash, &pool->hash_node, hash);
4778 put_unbound_pool(pool);
4782 static void rcu_free_pwq(struct rcu_head *rcu)
4784 kmem_cache_free(pwq_cache,
4785 container_of(rcu, struct pool_workqueue, rcu));
4789 * Scheduled on pwq_release_worker by put_pwq() when an unbound pwq hits zero
4790 * refcnt and needs to be destroyed.
4792 static void pwq_release_workfn(struct kthread_work *work)
4794 struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
4796 struct workqueue_struct *wq = pwq->wq;
4797 struct worker_pool *pool = pwq->pool;
4798 bool is_last = false;
4801 * When @pwq is not linked, it doesn't hold any reference to the
4802 * @wq, and @wq is invalid to access.
4804 if (!list_empty(&pwq->pwqs_node)) {
4805 mutex_lock(&wq->mutex);
4806 list_del_rcu(&pwq->pwqs_node);
4807 is_last = list_empty(&wq->pwqs);
4810 * For ordered workqueue with a plugged dfl_pwq, restart it now.
4812 if (!is_last && (wq->flags & __WQ_ORDERED))
4813 unplug_oldest_pwq(wq);
4815 mutex_unlock(&wq->mutex);
4818 if (wq->flags & WQ_UNBOUND) {
4819 mutex_lock(&wq_pool_mutex);
4820 put_unbound_pool(pool);
4821 mutex_unlock(&wq_pool_mutex);
4824 if (!list_empty(&pwq->pending_node)) {
4825 struct wq_node_nr_active *nna =
4826 wq_node_nr_active(pwq->wq, pwq->pool->node);
4828 raw_spin_lock_irq(&nna->lock);
4829 list_del_init(&pwq->pending_node);
4830 raw_spin_unlock_irq(&nna->lock);
4833 call_rcu(&pwq->rcu, rcu_free_pwq);
4836 * If we're the last pwq going away, @wq is already dead and no one
4837 * is gonna access it anymore. Schedule RCU free.
4840 wq_unregister_lockdep(wq);
4841 call_rcu(&wq->rcu, rcu_free_wq);
4845 /* initialize newly allocated @pwq which is associated with @wq and @pool */
4846 static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
4847 struct worker_pool *pool)
4849 BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
4851 memset(pwq, 0, sizeof(*pwq));
4855 pwq->flush_color = -1;
4857 INIT_LIST_HEAD(&pwq->inactive_works);
4858 INIT_LIST_HEAD(&pwq->pending_node);
4859 INIT_LIST_HEAD(&pwq->pwqs_node);
4860 INIT_LIST_HEAD(&pwq->mayday_node);
4861 kthread_init_work(&pwq->release_work, pwq_release_workfn);
4864 /* sync @pwq with the current state of its associated wq and link it */
4865 static void link_pwq(struct pool_workqueue *pwq)
4867 struct workqueue_struct *wq = pwq->wq;
4869 lockdep_assert_held(&wq->mutex);
4871 /* may be called multiple times, ignore if already linked */
4872 if (!list_empty(&pwq->pwqs_node))
4875 /* set the matching work_color */
4876 pwq->work_color = wq->work_color;
4879 list_add_tail_rcu(&pwq->pwqs_node, &wq->pwqs);
4882 /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
4883 static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
4884 const struct workqueue_attrs *attrs)
4886 struct worker_pool *pool;
4887 struct pool_workqueue *pwq;
4889 lockdep_assert_held(&wq_pool_mutex);
4891 pool = get_unbound_pool(attrs);
4895 pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
4897 put_unbound_pool(pool);
4901 init_pwq(pwq, wq, pool);
4906 * wq_calc_pod_cpumask - calculate a wq_attrs' cpumask for a pod
4907 * @attrs: the wq_attrs of the default pwq of the target workqueue
4908 * @cpu: the target CPU
4909 * @cpu_going_down: if >= 0, the CPU to consider as offline
4911 * Calculate the cpumask a workqueue with @attrs should use on @pod. If
4912 * @cpu_going_down is >= 0, that cpu is considered offline during calculation.
4913 * The result is stored in @attrs->__pod_cpumask.
4915 * If pod affinity is not enabled, @attrs->cpumask is always used. If enabled
4916 * and @pod has online CPUs requested by @attrs, the returned cpumask is the
4917 * intersection of the possible CPUs of @pod and @attrs->cpumask.
4919 * The caller is responsible for ensuring that the cpumask of @pod stays stable.
4921 static void wq_calc_pod_cpumask(struct workqueue_attrs *attrs, int cpu,
4924 const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
4925 int pod = pt->cpu_pod[cpu];
4927 /* does @pod have any online CPUs @attrs wants? */
4928 cpumask_and(attrs->__pod_cpumask, pt->pod_cpus[pod], attrs->cpumask);
4929 cpumask_and(attrs->__pod_cpumask, attrs->__pod_cpumask, cpu_online_mask);
4930 if (cpu_going_down >= 0)
4931 cpumask_clear_cpu(cpu_going_down, attrs->__pod_cpumask);
4933 if (cpumask_empty(attrs->__pod_cpumask)) {
4934 cpumask_copy(attrs->__pod_cpumask, attrs->cpumask);
4938 /* yeap, return possible CPUs in @pod that @attrs wants */
4939 cpumask_and(attrs->__pod_cpumask, attrs->cpumask, pt->pod_cpus[pod]);
4941 if (cpumask_empty(attrs->__pod_cpumask))
4942 pr_warn_once("WARNING: workqueue cpumask: online intersect > "
4943 "possible intersect\n");
4946 /* install @pwq into @wq and return the old pwq, @cpu < 0 for dfl_pwq */
4947 static struct pool_workqueue *install_unbound_pwq(struct workqueue_struct *wq,
4948 int cpu, struct pool_workqueue *pwq)
4950 struct pool_workqueue __rcu **slot = unbound_pwq_slot(wq, cpu);
4951 struct pool_workqueue *old_pwq;
4953 lockdep_assert_held(&wq_pool_mutex);
4954 lockdep_assert_held(&wq->mutex);
4956 /* link_pwq() can handle duplicate calls */
4959 old_pwq = rcu_access_pointer(*slot);
4960 rcu_assign_pointer(*slot, pwq);
4964 /* context to store the prepared attrs & pwqs before applying */
4965 struct apply_wqattrs_ctx {
4966 struct workqueue_struct *wq; /* target workqueue */
4967 struct workqueue_attrs *attrs; /* attrs to apply */
4968 struct list_head list; /* queued for batching commit */
4969 struct pool_workqueue *dfl_pwq;
4970 struct pool_workqueue *pwq_tbl[];
4973 /* free the resources after success or abort */
4974 static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
4979 for_each_possible_cpu(cpu)
4980 put_pwq_unlocked(ctx->pwq_tbl[cpu]);
4981 put_pwq_unlocked(ctx->dfl_pwq);
4983 free_workqueue_attrs(ctx->attrs);
4989 /* allocate the attrs and pwqs for later installation */
4990 static struct apply_wqattrs_ctx *
4991 apply_wqattrs_prepare(struct workqueue_struct *wq,
4992 const struct workqueue_attrs *attrs,
4993 const cpumask_var_t unbound_cpumask)
4995 struct apply_wqattrs_ctx *ctx;
4996 struct workqueue_attrs *new_attrs;
4999 lockdep_assert_held(&wq_pool_mutex);
5001 if (WARN_ON(attrs->affn_scope < 0 ||
5002 attrs->affn_scope >= WQ_AFFN_NR_TYPES))
5003 return ERR_PTR(-EINVAL);
5005 ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_cpu_ids), GFP_KERNEL);
5007 new_attrs = alloc_workqueue_attrs();
5008 if (!ctx || !new_attrs)
5012 * If something goes wrong during CPU up/down, we'll fall back to
5013 * the default pwq covering whole @attrs->cpumask. Always create
5014 * it even if we don't use it immediately.
5016 copy_workqueue_attrs(new_attrs, attrs);
5017 wqattrs_actualize_cpumask(new_attrs, unbound_cpumask);
5018 cpumask_copy(new_attrs->__pod_cpumask, new_attrs->cpumask);
5019 ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
5023 for_each_possible_cpu(cpu) {
5024 if (new_attrs->ordered) {
5025 ctx->dfl_pwq->refcnt++;
5026 ctx->pwq_tbl[cpu] = ctx->dfl_pwq;
5028 wq_calc_pod_cpumask(new_attrs, cpu, -1);
5029 ctx->pwq_tbl[cpu] = alloc_unbound_pwq(wq, new_attrs);
5030 if (!ctx->pwq_tbl[cpu])
5035 /* save the user configured attrs and sanitize it. */
5036 copy_workqueue_attrs(new_attrs, attrs);
5037 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
5038 cpumask_copy(new_attrs->__pod_cpumask, new_attrs->cpumask);
5039 ctx->attrs = new_attrs;
5042 * For initialized ordered workqueues, there should only be one pwq
5043 * (dfl_pwq). Set the plugged flag of ctx->dfl_pwq to suspend execution
5044 * of newly queued work items until execution of older work items in
5045 * the old pwq's have completed.
5047 if ((wq->flags & __WQ_ORDERED) && !list_empty(&wq->pwqs))
5048 ctx->dfl_pwq->plugged = true;
5054 free_workqueue_attrs(new_attrs);
5055 apply_wqattrs_cleanup(ctx);
5056 return ERR_PTR(-ENOMEM);
5059 /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
5060 static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
5064 /* all pwqs have been created successfully, let's install'em */
5065 mutex_lock(&ctx->wq->mutex);
5067 copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
5069 /* save the previous pwqs and install the new ones */
5070 for_each_possible_cpu(cpu)
5071 ctx->pwq_tbl[cpu] = install_unbound_pwq(ctx->wq, cpu,
5073 ctx->dfl_pwq = install_unbound_pwq(ctx->wq, -1, ctx->dfl_pwq);
5075 /* update node_nr_active->max */
5076 wq_update_node_max_active(ctx->wq, -1);
5078 /* rescuer needs to respect wq cpumask changes */
5079 if (ctx->wq->rescuer)
5080 set_cpus_allowed_ptr(ctx->wq->rescuer->task,
5081 unbound_effective_cpumask(ctx->wq));
5083 mutex_unlock(&ctx->wq->mutex);
5086 static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
5087 const struct workqueue_attrs *attrs)
5089 struct apply_wqattrs_ctx *ctx;
5091 /* only unbound workqueues can change attributes */
5092 if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
5095 ctx = apply_wqattrs_prepare(wq, attrs, wq_unbound_cpumask);
5097 return PTR_ERR(ctx);
5099 /* the ctx has been prepared successfully, let's commit it */
5100 apply_wqattrs_commit(ctx);
5101 apply_wqattrs_cleanup(ctx);
5107 * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
5108 * @wq: the target workqueue
5109 * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
5111 * Apply @attrs to an unbound workqueue @wq. Unless disabled, this function maps
5112 * a separate pwq to each CPU pod with possibles CPUs in @attrs->cpumask so that
5113 * work items are affine to the pod it was issued on. Older pwqs are released as
5114 * in-flight work items finish. Note that a work item which repeatedly requeues
5115 * itself back-to-back will stay on its current pwq.
5117 * Performs GFP_KERNEL allocations.
5119 * Assumes caller has CPU hotplug read exclusion, i.e. cpus_read_lock().
5121 * Return: 0 on success and -errno on failure.
5123 int apply_workqueue_attrs(struct workqueue_struct *wq,
5124 const struct workqueue_attrs *attrs)
5128 lockdep_assert_cpus_held();
5130 mutex_lock(&wq_pool_mutex);
5131 ret = apply_workqueue_attrs_locked(wq, attrs);
5132 mutex_unlock(&wq_pool_mutex);
5138 * wq_update_pod - update pod affinity of a wq for CPU hot[un]plug
5139 * @wq: the target workqueue
5140 * @cpu: the CPU to update pool association for
5141 * @hotplug_cpu: the CPU coming up or going down
5142 * @online: whether @cpu is coming up or going down
5144 * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
5145 * %CPU_DOWN_FAILED. @cpu is being hot[un]plugged, update pod affinity of
5149 * If pod affinity can't be adjusted due to memory allocation failure, it falls
5150 * back to @wq->dfl_pwq which may not be optimal but is always correct.
5152 * Note that when the last allowed CPU of a pod goes offline for a workqueue
5153 * with a cpumask spanning multiple pods, the workers which were already
5154 * executing the work items for the workqueue will lose their CPU affinity and
5155 * may execute on any CPU. This is similar to how per-cpu workqueues behave on
5156 * CPU_DOWN. If a workqueue user wants strict affinity, it's the user's
5157 * responsibility to flush the work item from CPU_DOWN_PREPARE.
5159 static void wq_update_pod(struct workqueue_struct *wq, int cpu,
5160 int hotplug_cpu, bool online)
5162 int off_cpu = online ? -1 : hotplug_cpu;
5163 struct pool_workqueue *old_pwq = NULL, *pwq;
5164 struct workqueue_attrs *target_attrs;
5166 lockdep_assert_held(&wq_pool_mutex);
5168 if (!(wq->flags & WQ_UNBOUND) || wq->unbound_attrs->ordered)
5172 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
5173 * Let's use a preallocated one. The following buf is protected by
5174 * CPU hotplug exclusion.
5176 target_attrs = wq_update_pod_attrs_buf;
5178 copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
5179 wqattrs_actualize_cpumask(target_attrs, wq_unbound_cpumask);
5181 /* nothing to do if the target cpumask matches the current pwq */
5182 wq_calc_pod_cpumask(target_attrs, cpu, off_cpu);
5183 if (wqattrs_equal(target_attrs, unbound_pwq(wq, cpu)->pool->attrs))
5186 /* create a new pwq */
5187 pwq = alloc_unbound_pwq(wq, target_attrs);
5189 pr_warn("workqueue: allocation failed while updating CPU pod affinity of \"%s\"\n",
5194 /* Install the new pwq. */
5195 mutex_lock(&wq->mutex);
5196 old_pwq = install_unbound_pwq(wq, cpu, pwq);
5200 mutex_lock(&wq->mutex);
5201 pwq = unbound_pwq(wq, -1);
5202 raw_spin_lock_irq(&pwq->pool->lock);
5204 raw_spin_unlock_irq(&pwq->pool->lock);
5205 old_pwq = install_unbound_pwq(wq, cpu, pwq);
5207 mutex_unlock(&wq->mutex);
5208 put_pwq_unlocked(old_pwq);
5211 static int alloc_and_link_pwqs(struct workqueue_struct *wq)
5213 bool highpri = wq->flags & WQ_HIGHPRI;
5216 wq->cpu_pwq = alloc_percpu(struct pool_workqueue *);
5220 if (!(wq->flags & WQ_UNBOUND)) {
5221 for_each_possible_cpu(cpu) {
5222 struct pool_workqueue **pwq_p;
5223 struct worker_pool __percpu *pools;
5224 struct worker_pool *pool;
5226 if (wq->flags & WQ_BH)
5227 pools = bh_worker_pools;
5229 pools = cpu_worker_pools;
5231 pool = &(per_cpu_ptr(pools, cpu)[highpri]);
5232 pwq_p = per_cpu_ptr(wq->cpu_pwq, cpu);
5234 *pwq_p = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL,
5239 init_pwq(*pwq_p, wq, pool);
5241 mutex_lock(&wq->mutex);
5243 mutex_unlock(&wq->mutex);
5249 if (wq->flags & __WQ_ORDERED) {
5250 struct pool_workqueue *dfl_pwq;
5252 ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
5253 /* there should only be single pwq for ordering guarantee */
5254 dfl_pwq = rcu_access_pointer(wq->dfl_pwq);
5255 WARN(!ret && (wq->pwqs.next != &dfl_pwq->pwqs_node ||
5256 wq->pwqs.prev != &dfl_pwq->pwqs_node),
5257 "ordering guarantee broken for workqueue %s\n", wq->name);
5259 ret = apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
5263 /* for unbound pwq, flush the pwq_release_worker ensures that the
5264 * pwq_release_workfn() completes before calling kfree(wq).
5267 kthread_flush_worker(pwq_release_worker);
5273 for_each_possible_cpu(cpu) {
5274 struct pool_workqueue *pwq = *per_cpu_ptr(wq->cpu_pwq, cpu);
5277 kmem_cache_free(pwq_cache, pwq);
5279 free_percpu(wq->cpu_pwq);
5285 static int wq_clamp_max_active(int max_active, unsigned int flags,
5288 if (max_active < 1 || max_active > WQ_MAX_ACTIVE)
5289 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
5290 max_active, name, 1, WQ_MAX_ACTIVE);
5292 return clamp_val(max_active, 1, WQ_MAX_ACTIVE);
5296 * Workqueues which may be used during memory reclaim should have a rescuer
5297 * to guarantee forward progress.
5299 static int init_rescuer(struct workqueue_struct *wq)
5301 struct worker *rescuer;
5304 if (!(wq->flags & WQ_MEM_RECLAIM))
5307 rescuer = alloc_worker(NUMA_NO_NODE);
5309 pr_err("workqueue: Failed to allocate a rescuer for wq \"%s\"\n",
5314 rescuer->rescue_wq = wq;
5315 rescuer->task = kthread_create(rescuer_thread, rescuer, "kworker/R-%s", wq->name);
5316 if (IS_ERR(rescuer->task)) {
5317 ret = PTR_ERR(rescuer->task);
5318 pr_err("workqueue: Failed to create a rescuer kthread for wq \"%s\": %pe",
5319 wq->name, ERR_PTR(ret));
5324 wq->rescuer = rescuer;
5325 if (wq->flags & WQ_UNBOUND)
5326 kthread_bind_mask(rescuer->task, wq_unbound_cpumask);
5328 kthread_bind_mask(rescuer->task, cpu_possible_mask);
5329 wake_up_process(rescuer->task);
5335 * wq_adjust_max_active - update a wq's max_active to the current setting
5336 * @wq: target workqueue
5338 * If @wq isn't freezing, set @wq->max_active to the saved_max_active and
5339 * activate inactive work items accordingly. If @wq is freezing, clear
5340 * @wq->max_active to zero.
5342 static void wq_adjust_max_active(struct workqueue_struct *wq)
5345 int new_max, new_min;
5347 lockdep_assert_held(&wq->mutex);
5349 if ((wq->flags & WQ_FREEZABLE) && workqueue_freezing) {
5353 new_max = wq->saved_max_active;
5354 new_min = wq->saved_min_active;
5357 if (wq->max_active == new_max && wq->min_active == new_min)
5361 * Update @wq->max/min_active and then kick inactive work items if more
5362 * active work items are allowed. This doesn't break work item ordering
5363 * because new work items are always queued behind existing inactive
5364 * work items if there are any.
5366 WRITE_ONCE(wq->max_active, new_max);
5367 WRITE_ONCE(wq->min_active, new_min);
5369 if (wq->flags & WQ_UNBOUND)
5370 wq_update_node_max_active(wq, -1);
5376 * Round-robin through pwq's activating the first inactive work item
5377 * until max_active is filled.
5380 struct pool_workqueue *pwq;
5383 for_each_pwq(pwq, wq) {
5384 unsigned long flags;
5386 /* can be called during early boot w/ irq disabled */
5387 raw_spin_lock_irqsave(&pwq->pool->lock, flags);
5388 if (pwq_activate_first_inactive(pwq, true)) {
5390 kick_pool(pwq->pool);
5392 raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
5394 } while (activated);
5398 struct workqueue_struct *alloc_workqueue(const char *fmt,
5400 int max_active, ...)
5403 struct workqueue_struct *wq;
5407 if (flags & WQ_BH) {
5408 if (WARN_ON_ONCE(flags & ~__WQ_BH_ALLOWS))
5410 if (WARN_ON_ONCE(max_active))
5414 /* see the comment above the definition of WQ_POWER_EFFICIENT */
5415 if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
5416 flags |= WQ_UNBOUND;
5418 /* allocate wq and format name */
5419 if (flags & WQ_UNBOUND)
5420 wq_size = struct_size(wq, node_nr_active, nr_node_ids + 1);
5422 wq_size = sizeof(*wq);
5424 wq = kzalloc(wq_size, GFP_KERNEL);
5428 if (flags & WQ_UNBOUND) {
5429 wq->unbound_attrs = alloc_workqueue_attrs();
5430 if (!wq->unbound_attrs)
5434 va_start(args, max_active);
5435 name_len = vsnprintf(wq->name, sizeof(wq->name), fmt, args);
5438 if (name_len >= WQ_NAME_LEN)
5439 pr_warn_once("workqueue: name exceeds WQ_NAME_LEN. Truncating to: %s\n",
5442 if (flags & WQ_BH) {
5444 * BH workqueues always share a single execution context per CPU
5445 * and don't impose any max_active limit.
5447 max_active = INT_MAX;
5449 max_active = max_active ?: WQ_DFL_ACTIVE;
5450 max_active = wq_clamp_max_active(max_active, flags, wq->name);
5455 wq->max_active = max_active;
5456 wq->min_active = min(max_active, WQ_DFL_MIN_ACTIVE);
5457 wq->saved_max_active = wq->max_active;
5458 wq->saved_min_active = wq->min_active;
5459 mutex_init(&wq->mutex);
5460 atomic_set(&wq->nr_pwqs_to_flush, 0);
5461 INIT_LIST_HEAD(&wq->pwqs);
5462 INIT_LIST_HEAD(&wq->flusher_queue);
5463 INIT_LIST_HEAD(&wq->flusher_overflow);
5464 INIT_LIST_HEAD(&wq->maydays);
5466 wq_init_lockdep(wq);
5467 INIT_LIST_HEAD(&wq->list);
5469 if (flags & WQ_UNBOUND) {
5470 if (alloc_node_nr_active(wq->node_nr_active) < 0)
5471 goto err_unreg_lockdep;
5474 if (alloc_and_link_pwqs(wq) < 0)
5475 goto err_free_node_nr_active;
5477 if (wq_online && init_rescuer(wq) < 0)
5480 if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
5484 * wq_pool_mutex protects global freeze state and workqueues list.
5485 * Grab it, adjust max_active and add the new @wq to workqueues
5488 mutex_lock(&wq_pool_mutex);
5490 mutex_lock(&wq->mutex);
5491 wq_adjust_max_active(wq);
5492 mutex_unlock(&wq->mutex);
5494 list_add_tail_rcu(&wq->list, &workqueues);
5496 mutex_unlock(&wq_pool_mutex);
5500 err_free_node_nr_active:
5501 if (wq->flags & WQ_UNBOUND)
5502 free_node_nr_active(wq->node_nr_active);
5504 wq_unregister_lockdep(wq);
5505 wq_free_lockdep(wq);
5507 free_workqueue_attrs(wq->unbound_attrs);
5511 destroy_workqueue(wq);
5514 EXPORT_SYMBOL_GPL(alloc_workqueue);
5516 static bool pwq_busy(struct pool_workqueue *pwq)
5520 for (i = 0; i < WORK_NR_COLORS; i++)
5521 if (pwq->nr_in_flight[i])
5524 if ((pwq != rcu_access_pointer(pwq->wq->dfl_pwq)) && (pwq->refcnt > 1))
5526 if (!pwq_is_empty(pwq))
5533 * destroy_workqueue - safely terminate a workqueue
5534 * @wq: target workqueue
5536 * Safely destroy a workqueue. All work currently pending will be done first.
5538 void destroy_workqueue(struct workqueue_struct *wq)
5540 struct pool_workqueue *pwq;
5544 * Remove it from sysfs first so that sanity check failure doesn't
5545 * lead to sysfs name conflicts.
5547 workqueue_sysfs_unregister(wq);
5549 /* mark the workqueue destruction is in progress */
5550 mutex_lock(&wq->mutex);
5551 wq->flags |= __WQ_DESTROYING;
5552 mutex_unlock(&wq->mutex);
5554 /* drain it before proceeding with destruction */
5555 drain_workqueue(wq);
5557 /* kill rescuer, if sanity checks fail, leave it w/o rescuer */
5559 struct worker *rescuer = wq->rescuer;
5561 /* this prevents new queueing */
5562 raw_spin_lock_irq(&wq_mayday_lock);
5564 raw_spin_unlock_irq(&wq_mayday_lock);
5566 /* rescuer will empty maydays list before exiting */
5567 kthread_stop(rescuer->task);
5572 * Sanity checks - grab all the locks so that we wait for all
5573 * in-flight operations which may do put_pwq().
5575 mutex_lock(&wq_pool_mutex);
5576 mutex_lock(&wq->mutex);
5577 for_each_pwq(pwq, wq) {
5578 raw_spin_lock_irq(&pwq->pool->lock);
5579 if (WARN_ON(pwq_busy(pwq))) {
5580 pr_warn("%s: %s has the following busy pwq\n",
5581 __func__, wq->name);
5583 raw_spin_unlock_irq(&pwq->pool->lock);
5584 mutex_unlock(&wq->mutex);
5585 mutex_unlock(&wq_pool_mutex);
5586 show_one_workqueue(wq);
5589 raw_spin_unlock_irq(&pwq->pool->lock);
5591 mutex_unlock(&wq->mutex);
5594 * wq list is used to freeze wq, remove from list after
5595 * flushing is complete in case freeze races us.
5597 list_del_rcu(&wq->list);
5598 mutex_unlock(&wq_pool_mutex);
5601 * We're the sole accessor of @wq. Directly access cpu_pwq and dfl_pwq
5602 * to put the base refs. @wq will be auto-destroyed from the last
5603 * pwq_put. RCU read lock prevents @wq from going away from under us.
5607 for_each_possible_cpu(cpu) {
5608 put_pwq_unlocked(unbound_pwq(wq, cpu));
5609 RCU_INIT_POINTER(*unbound_pwq_slot(wq, cpu), NULL);
5612 put_pwq_unlocked(unbound_pwq(wq, -1));
5613 RCU_INIT_POINTER(*unbound_pwq_slot(wq, -1), NULL);
5617 EXPORT_SYMBOL_GPL(destroy_workqueue);
5620 * workqueue_set_max_active - adjust max_active of a workqueue
5621 * @wq: target workqueue
5622 * @max_active: new max_active value.
5624 * Set max_active of @wq to @max_active. See the alloc_workqueue() function
5628 * Don't call from IRQ context.
5630 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
5632 /* max_active doesn't mean anything for BH workqueues */
5633 if (WARN_ON(wq->flags & WQ_BH))
5635 /* disallow meddling with max_active for ordered workqueues */
5636 if (WARN_ON(wq->flags & __WQ_ORDERED))
5639 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
5641 mutex_lock(&wq->mutex);
5643 wq->saved_max_active = max_active;
5644 if (wq->flags & WQ_UNBOUND)
5645 wq->saved_min_active = min(wq->saved_min_active, max_active);
5647 wq_adjust_max_active(wq);
5649 mutex_unlock(&wq->mutex);
5651 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
5654 * workqueue_set_min_active - adjust min_active of an unbound workqueue
5655 * @wq: target unbound workqueue
5656 * @min_active: new min_active value
5658 * Set min_active of an unbound workqueue. Unlike other types of workqueues, an
5659 * unbound workqueue is not guaranteed to be able to process max_active
5660 * interdependent work items. Instead, an unbound workqueue is guaranteed to be
5661 * able to process min_active number of interdependent work items which is
5662 * %WQ_DFL_MIN_ACTIVE by default.
5664 * Use this function to adjust the min_active value between 0 and the current
5667 void workqueue_set_min_active(struct workqueue_struct *wq, int min_active)
5669 /* min_active is only meaningful for non-ordered unbound workqueues */
5670 if (WARN_ON((wq->flags & (WQ_BH | WQ_UNBOUND | __WQ_ORDERED)) !=
5674 mutex_lock(&wq->mutex);
5675 wq->saved_min_active = clamp(min_active, 0, wq->saved_max_active);
5676 wq_adjust_max_active(wq);
5677 mutex_unlock(&wq->mutex);
5681 * current_work - retrieve %current task's work struct
5683 * Determine if %current task is a workqueue worker and what it's working on.
5684 * Useful to find out the context that the %current task is running in.
5686 * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
5688 struct work_struct *current_work(void)
5690 struct worker *worker = current_wq_worker();
5692 return worker ? worker->current_work : NULL;
5694 EXPORT_SYMBOL(current_work);
5697 * current_is_workqueue_rescuer - is %current workqueue rescuer?
5699 * Determine whether %current is a workqueue rescuer. Can be used from
5700 * work functions to determine whether it's being run off the rescuer task.
5702 * Return: %true if %current is a workqueue rescuer. %false otherwise.
5704 bool current_is_workqueue_rescuer(void)
5706 struct worker *worker = current_wq_worker();
5708 return worker && worker->rescue_wq;
5712 * workqueue_congested - test whether a workqueue is congested
5713 * @cpu: CPU in question
5714 * @wq: target workqueue
5716 * Test whether @wq's cpu workqueue for @cpu is congested. There is
5717 * no synchronization around this function and the test result is
5718 * unreliable and only useful as advisory hints or for debugging.
5720 * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
5722 * With the exception of ordered workqueues, all workqueues have per-cpu
5723 * pool_workqueues, each with its own congested state. A workqueue being
5724 * congested on one CPU doesn't mean that the workqueue is contested on any
5728 * %true if congested, %false otherwise.
5730 bool workqueue_congested(int cpu, struct workqueue_struct *wq)
5732 struct pool_workqueue *pwq;
5738 if (cpu == WORK_CPU_UNBOUND)
5739 cpu = smp_processor_id();
5741 pwq = *per_cpu_ptr(wq->cpu_pwq, cpu);
5742 ret = !list_empty(&pwq->inactive_works);
5749 EXPORT_SYMBOL_GPL(workqueue_congested);
5752 * work_busy - test whether a work is currently pending or running
5753 * @work: the work to be tested
5755 * Test whether @work is currently pending or running. There is no
5756 * synchronization around this function and the test result is
5757 * unreliable and only useful as advisory hints or for debugging.
5760 * OR'd bitmask of WORK_BUSY_* bits.
5762 unsigned int work_busy(struct work_struct *work)
5764 struct worker_pool *pool;
5765 unsigned long flags;
5766 unsigned int ret = 0;
5768 if (work_pending(work))
5769 ret |= WORK_BUSY_PENDING;
5772 pool = get_work_pool(work);
5774 raw_spin_lock_irqsave(&pool->lock, flags);
5775 if (find_worker_executing_work(pool, work))
5776 ret |= WORK_BUSY_RUNNING;
5777 raw_spin_unlock_irqrestore(&pool->lock, flags);
5783 EXPORT_SYMBOL_GPL(work_busy);
5786 * set_worker_desc - set description for the current work item
5787 * @fmt: printf-style format string
5788 * @...: arguments for the format string
5790 * This function can be called by a running work function to describe what
5791 * the work item is about. If the worker task gets dumped, this
5792 * information will be printed out together to help debugging. The
5793 * description can be at most WORKER_DESC_LEN including the trailing '\0'.
5795 void set_worker_desc(const char *fmt, ...)
5797 struct worker *worker = current_wq_worker();
5801 va_start(args, fmt);
5802 vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
5806 EXPORT_SYMBOL_GPL(set_worker_desc);
5809 * print_worker_info - print out worker information and description
5810 * @log_lvl: the log level to use when printing
5811 * @task: target task
5813 * If @task is a worker and currently executing a work item, print out the
5814 * name of the workqueue being serviced and worker description set with
5815 * set_worker_desc() by the currently executing work item.
5817 * This function can be safely called on any task as long as the
5818 * task_struct itself is accessible. While safe, this function isn't
5819 * synchronized and may print out mixups or garbages of limited length.
5821 void print_worker_info(const char *log_lvl, struct task_struct *task)
5823 work_func_t *fn = NULL;
5824 char name[WQ_NAME_LEN] = { };
5825 char desc[WORKER_DESC_LEN] = { };
5826 struct pool_workqueue *pwq = NULL;
5827 struct workqueue_struct *wq = NULL;
5828 struct worker *worker;
5830 if (!(task->flags & PF_WQ_WORKER))
5834 * This function is called without any synchronization and @task
5835 * could be in any state. Be careful with dereferences.
5837 worker = kthread_probe_data(task);
5840 * Carefully copy the associated workqueue's workfn, name and desc.
5841 * Keep the original last '\0' in case the original is garbage.
5843 copy_from_kernel_nofault(&fn, &worker->current_func, sizeof(fn));
5844 copy_from_kernel_nofault(&pwq, &worker->current_pwq, sizeof(pwq));
5845 copy_from_kernel_nofault(&wq, &pwq->wq, sizeof(wq));
5846 copy_from_kernel_nofault(name, wq->name, sizeof(name) - 1);
5847 copy_from_kernel_nofault(desc, worker->desc, sizeof(desc) - 1);
5849 if (fn || name[0] || desc[0]) {
5850 printk("%sWorkqueue: %s %ps", log_lvl, name, fn);
5851 if (strcmp(name, desc))
5852 pr_cont(" (%s)", desc);
5857 static void pr_cont_pool_info(struct worker_pool *pool)
5859 pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
5860 if (pool->node != NUMA_NO_NODE)
5861 pr_cont(" node=%d", pool->node);
5862 pr_cont(" flags=0x%x", pool->flags);
5863 if (pool->flags & POOL_BH)
5865 pool->attrs->nice == HIGHPRI_NICE_LEVEL ? "-hi" : "");
5867 pr_cont(" nice=%d", pool->attrs->nice);
5870 static void pr_cont_worker_id(struct worker *worker)
5872 struct worker_pool *pool = worker->pool;
5874 if (pool->flags & WQ_BH)
5876 pool->attrs->nice == HIGHPRI_NICE_LEVEL ? "-hi" : "");
5878 pr_cont("%d%s", task_pid_nr(worker->task),
5879 worker->rescue_wq ? "(RESCUER)" : "");
5882 struct pr_cont_work_struct {
5888 static void pr_cont_work_flush(bool comma, work_func_t func, struct pr_cont_work_struct *pcwsp)
5892 if (func == pcwsp->func) {
5896 if (pcwsp->ctr == 1)
5897 pr_cont("%s %ps", pcwsp->comma ? "," : "", pcwsp->func);
5899 pr_cont("%s %ld*%ps", pcwsp->comma ? "," : "", pcwsp->ctr, pcwsp->func);
5902 if ((long)func == -1L)
5904 pcwsp->comma = comma;
5909 static void pr_cont_work(bool comma, struct work_struct *work, struct pr_cont_work_struct *pcwsp)
5911 if (work->func == wq_barrier_func) {
5912 struct wq_barrier *barr;
5914 barr = container_of(work, struct wq_barrier, work);
5916 pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
5917 pr_cont("%s BAR(%d)", comma ? "," : "",
5918 task_pid_nr(barr->task));
5921 pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
5922 pr_cont_work_flush(comma, work->func, pcwsp);
5926 static void show_pwq(struct pool_workqueue *pwq)
5928 struct pr_cont_work_struct pcws = { .ctr = 0, };
5929 struct worker_pool *pool = pwq->pool;
5930 struct work_struct *work;
5931 struct worker *worker;
5932 bool has_in_flight = false, has_pending = false;
5935 pr_info(" pwq %d:", pool->id);
5936 pr_cont_pool_info(pool);
5938 pr_cont(" active=%d refcnt=%d%s\n",
5939 pwq->nr_active, pwq->refcnt,
5940 !list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
5942 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
5943 if (worker->current_pwq == pwq) {
5944 has_in_flight = true;
5948 if (has_in_flight) {
5951 pr_info(" in-flight:");
5952 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
5953 if (worker->current_pwq != pwq)
5956 pr_cont(" %s", comma ? "," : "");
5957 pr_cont_worker_id(worker);
5958 pr_cont(":%ps", worker->current_func);
5959 list_for_each_entry(work, &worker->scheduled, entry)
5960 pr_cont_work(false, work, &pcws);
5961 pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
5967 list_for_each_entry(work, &pool->worklist, entry) {
5968 if (get_work_pwq(work) == pwq) {
5976 pr_info(" pending:");
5977 list_for_each_entry(work, &pool->worklist, entry) {
5978 if (get_work_pwq(work) != pwq)
5981 pr_cont_work(comma, work, &pcws);
5982 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
5984 pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
5988 if (!list_empty(&pwq->inactive_works)) {
5991 pr_info(" inactive:");
5992 list_for_each_entry(work, &pwq->inactive_works, entry) {
5993 pr_cont_work(comma, work, &pcws);
5994 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
5996 pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
6002 * show_one_workqueue - dump state of specified workqueue
6003 * @wq: workqueue whose state will be printed
6005 void show_one_workqueue(struct workqueue_struct *wq)
6007 struct pool_workqueue *pwq;
6009 unsigned long flags;
6011 for_each_pwq(pwq, wq) {
6012 if (!pwq_is_empty(pwq)) {
6017 if (idle) /* Nothing to print for idle workqueue */
6020 pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
6022 for_each_pwq(pwq, wq) {
6023 raw_spin_lock_irqsave(&pwq->pool->lock, flags);
6024 if (!pwq_is_empty(pwq)) {
6026 * Defer printing to avoid deadlocks in console
6027 * drivers that queue work while holding locks
6028 * also taken in their write paths.
6030 printk_deferred_enter();
6032 printk_deferred_exit();
6034 raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
6036 * We could be printing a lot from atomic context, e.g.
6037 * sysrq-t -> show_all_workqueues(). Avoid triggering
6040 touch_nmi_watchdog();
6046 * show_one_worker_pool - dump state of specified worker pool
6047 * @pool: worker pool whose state will be printed
6049 static void show_one_worker_pool(struct worker_pool *pool)
6051 struct worker *worker;
6053 unsigned long flags;
6054 unsigned long hung = 0;
6056 raw_spin_lock_irqsave(&pool->lock, flags);
6057 if (pool->nr_workers == pool->nr_idle)
6060 /* How long the first pending work is waiting for a worker. */
6061 if (!list_empty(&pool->worklist))
6062 hung = jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000;
6065 * Defer printing to avoid deadlocks in console drivers that
6066 * queue work while holding locks also taken in their write
6069 printk_deferred_enter();
6070 pr_info("pool %d:", pool->id);
6071 pr_cont_pool_info(pool);
6072 pr_cont(" hung=%lus workers=%d", hung, pool->nr_workers);
6074 pr_cont(" manager: %d",
6075 task_pid_nr(pool->manager->task));
6076 list_for_each_entry(worker, &pool->idle_list, entry) {
6077 pr_cont(" %s", first ? "idle: " : "");
6078 pr_cont_worker_id(worker);
6082 printk_deferred_exit();
6084 raw_spin_unlock_irqrestore(&pool->lock, flags);
6086 * We could be printing a lot from atomic context, e.g.
6087 * sysrq-t -> show_all_workqueues(). Avoid triggering
6090 touch_nmi_watchdog();
6095 * show_all_workqueues - dump workqueue state
6097 * Called from a sysrq handler and prints out all busy workqueues and pools.
6099 void show_all_workqueues(void)
6101 struct workqueue_struct *wq;
6102 struct worker_pool *pool;
6107 pr_info("Showing busy workqueues and worker pools:\n");
6109 list_for_each_entry_rcu(wq, &workqueues, list)
6110 show_one_workqueue(wq);
6112 for_each_pool(pool, pi)
6113 show_one_worker_pool(pool);
6119 * show_freezable_workqueues - dump freezable workqueue state
6121 * Called from try_to_freeze_tasks() and prints out all freezable workqueues
6124 void show_freezable_workqueues(void)
6126 struct workqueue_struct *wq;
6130 pr_info("Showing freezable workqueues that are still busy:\n");
6132 list_for_each_entry_rcu(wq, &workqueues, list) {
6133 if (!(wq->flags & WQ_FREEZABLE))
6135 show_one_workqueue(wq);
6141 /* used to show worker information through /proc/PID/{comm,stat,status} */
6142 void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
6146 /* always show the actual comm */
6147 off = strscpy(buf, task->comm, size);
6151 /* stabilize PF_WQ_WORKER and worker pool association */
6152 mutex_lock(&wq_pool_attach_mutex);
6154 if (task->flags & PF_WQ_WORKER) {
6155 struct worker *worker = kthread_data(task);
6156 struct worker_pool *pool = worker->pool;
6159 raw_spin_lock_irq(&pool->lock);
6161 * ->desc tracks information (wq name or
6162 * set_worker_desc()) for the latest execution. If
6163 * current, prepend '+', otherwise '-'.
6165 if (worker->desc[0] != '\0') {
6166 if (worker->current_work)
6167 scnprintf(buf + off, size - off, "+%s",
6170 scnprintf(buf + off, size - off, "-%s",
6173 raw_spin_unlock_irq(&pool->lock);
6177 mutex_unlock(&wq_pool_attach_mutex);
6185 * There are two challenges in supporting CPU hotplug. Firstly, there
6186 * are a lot of assumptions on strong associations among work, pwq and
6187 * pool which make migrating pending and scheduled works very
6188 * difficult to implement without impacting hot paths. Secondly,
6189 * worker pools serve mix of short, long and very long running works making
6190 * blocked draining impractical.
6192 * This is solved by allowing the pools to be disassociated from the CPU
6193 * running as an unbound one and allowing it to be reattached later if the
6194 * cpu comes back online.
6197 static void unbind_workers(int cpu)
6199 struct worker_pool *pool;
6200 struct worker *worker;
6202 for_each_cpu_worker_pool(pool, cpu) {
6203 mutex_lock(&wq_pool_attach_mutex);
6204 raw_spin_lock_irq(&pool->lock);
6207 * We've blocked all attach/detach operations. Make all workers
6208 * unbound and set DISASSOCIATED. Before this, all workers
6209 * must be on the cpu. After this, they may become diasporas.
6210 * And the preemption disabled section in their sched callbacks
6211 * are guaranteed to see WORKER_UNBOUND since the code here
6212 * is on the same cpu.
6214 for_each_pool_worker(worker, pool)
6215 worker->flags |= WORKER_UNBOUND;
6217 pool->flags |= POOL_DISASSOCIATED;
6220 * The handling of nr_running in sched callbacks are disabled
6221 * now. Zap nr_running. After this, nr_running stays zero and
6222 * need_more_worker() and keep_working() are always true as
6223 * long as the worklist is not empty. This pool now behaves as
6224 * an unbound (in terms of concurrency management) pool which
6225 * are served by workers tied to the pool.
6227 pool->nr_running = 0;
6230 * With concurrency management just turned off, a busy
6231 * worker blocking could lead to lengthy stalls. Kick off
6232 * unbound chain execution of currently pending work items.
6236 raw_spin_unlock_irq(&pool->lock);
6238 for_each_pool_worker(worker, pool)
6239 unbind_worker(worker);
6241 mutex_unlock(&wq_pool_attach_mutex);
6246 * rebind_workers - rebind all workers of a pool to the associated CPU
6247 * @pool: pool of interest
6249 * @pool->cpu is coming online. Rebind all workers to the CPU.
6251 static void rebind_workers(struct worker_pool *pool)
6253 struct worker *worker;
6255 lockdep_assert_held(&wq_pool_attach_mutex);
6258 * Restore CPU affinity of all workers. As all idle workers should
6259 * be on the run-queue of the associated CPU before any local
6260 * wake-ups for concurrency management happen, restore CPU affinity
6261 * of all workers first and then clear UNBOUND. As we're called
6262 * from CPU_ONLINE, the following shouldn't fail.
6264 for_each_pool_worker(worker, pool) {
6265 kthread_set_per_cpu(worker->task, pool->cpu);
6266 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
6267 pool_allowed_cpus(pool)) < 0);
6270 raw_spin_lock_irq(&pool->lock);
6272 pool->flags &= ~POOL_DISASSOCIATED;
6274 for_each_pool_worker(worker, pool) {
6275 unsigned int worker_flags = worker->flags;
6278 * We want to clear UNBOUND but can't directly call
6279 * worker_clr_flags() or adjust nr_running. Atomically
6280 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
6281 * @worker will clear REBOUND using worker_clr_flags() when
6282 * it initiates the next execution cycle thus restoring
6283 * concurrency management. Note that when or whether
6284 * @worker clears REBOUND doesn't affect correctness.
6286 * WRITE_ONCE() is necessary because @worker->flags may be
6287 * tested without holding any lock in
6288 * wq_worker_running(). Without it, NOT_RUNNING test may
6289 * fail incorrectly leading to premature concurrency
6290 * management operations.
6292 WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
6293 worker_flags |= WORKER_REBOUND;
6294 worker_flags &= ~WORKER_UNBOUND;
6295 WRITE_ONCE(worker->flags, worker_flags);
6298 raw_spin_unlock_irq(&pool->lock);
6302 * restore_unbound_workers_cpumask - restore cpumask of unbound workers
6303 * @pool: unbound pool of interest
6304 * @cpu: the CPU which is coming up
6306 * An unbound pool may end up with a cpumask which doesn't have any online
6307 * CPUs. When a worker of such pool get scheduled, the scheduler resets
6308 * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
6309 * online CPU before, cpus_allowed of all its workers should be restored.
6311 static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
6313 static cpumask_t cpumask;
6314 struct worker *worker;
6316 lockdep_assert_held(&wq_pool_attach_mutex);
6318 /* is @cpu allowed for @pool? */
6319 if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
6322 cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
6324 /* as we're called from CPU_ONLINE, the following shouldn't fail */
6325 for_each_pool_worker(worker, pool)
6326 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
6329 int workqueue_prepare_cpu(unsigned int cpu)
6331 struct worker_pool *pool;
6333 for_each_cpu_worker_pool(pool, cpu) {
6334 if (pool->nr_workers)
6336 if (!create_worker(pool))
6342 int workqueue_online_cpu(unsigned int cpu)
6344 struct worker_pool *pool;
6345 struct workqueue_struct *wq;
6348 mutex_lock(&wq_pool_mutex);
6350 for_each_pool(pool, pi) {
6351 /* BH pools aren't affected by hotplug */
6352 if (pool->flags & POOL_BH)
6355 mutex_lock(&wq_pool_attach_mutex);
6356 if (pool->cpu == cpu)
6357 rebind_workers(pool);
6358 else if (pool->cpu < 0)
6359 restore_unbound_workers_cpumask(pool, cpu);
6360 mutex_unlock(&wq_pool_attach_mutex);
6363 /* update pod affinity of unbound workqueues */
6364 list_for_each_entry(wq, &workqueues, list) {
6365 struct workqueue_attrs *attrs = wq->unbound_attrs;
6368 const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
6371 for_each_cpu(tcpu, pt->pod_cpus[pt->cpu_pod[cpu]])
6372 wq_update_pod(wq, tcpu, cpu, true);
6374 mutex_lock(&wq->mutex);
6375 wq_update_node_max_active(wq, -1);
6376 mutex_unlock(&wq->mutex);
6380 mutex_unlock(&wq_pool_mutex);
6384 int workqueue_offline_cpu(unsigned int cpu)
6386 struct workqueue_struct *wq;
6388 /* unbinding per-cpu workers should happen on the local CPU */
6389 if (WARN_ON(cpu != smp_processor_id()))
6392 unbind_workers(cpu);
6394 /* update pod affinity of unbound workqueues */
6395 mutex_lock(&wq_pool_mutex);
6396 list_for_each_entry(wq, &workqueues, list) {
6397 struct workqueue_attrs *attrs = wq->unbound_attrs;
6400 const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
6403 for_each_cpu(tcpu, pt->pod_cpus[pt->cpu_pod[cpu]])
6404 wq_update_pod(wq, tcpu, cpu, false);
6406 mutex_lock(&wq->mutex);
6407 wq_update_node_max_active(wq, cpu);
6408 mutex_unlock(&wq->mutex);
6411 mutex_unlock(&wq_pool_mutex);
6416 struct work_for_cpu {
6417 struct work_struct work;
6423 static void work_for_cpu_fn(struct work_struct *work)
6425 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
6427 wfc->ret = wfc->fn(wfc->arg);
6431 * work_on_cpu_key - run a function in thread context on a particular cpu
6432 * @cpu: the cpu to run on
6433 * @fn: the function to run
6434 * @arg: the function arg
6435 * @key: The lock class key for lock debugging purposes
6437 * It is up to the caller to ensure that the cpu doesn't go offline.
6438 * The caller must not hold any locks which would prevent @fn from completing.
6440 * Return: The value @fn returns.
6442 long work_on_cpu_key(int cpu, long (*fn)(void *),
6443 void *arg, struct lock_class_key *key)
6445 struct work_for_cpu wfc = { .fn = fn, .arg = arg };
6447 INIT_WORK_ONSTACK_KEY(&wfc.work, work_for_cpu_fn, key);
6448 schedule_work_on(cpu, &wfc.work);
6449 flush_work(&wfc.work);
6450 destroy_work_on_stack(&wfc.work);
6453 EXPORT_SYMBOL_GPL(work_on_cpu_key);
6456 * work_on_cpu_safe_key - run a function in thread context on a particular cpu
6457 * @cpu: the cpu to run on
6458 * @fn: the function to run
6459 * @arg: the function argument
6460 * @key: The lock class key for lock debugging purposes
6462 * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
6463 * any locks which would prevent @fn from completing.
6465 * Return: The value @fn returns.
6467 long work_on_cpu_safe_key(int cpu, long (*fn)(void *),
6468 void *arg, struct lock_class_key *key)
6473 if (cpu_online(cpu))
6474 ret = work_on_cpu_key(cpu, fn, arg, key);
6478 EXPORT_SYMBOL_GPL(work_on_cpu_safe_key);
6479 #endif /* CONFIG_SMP */
6481 #ifdef CONFIG_FREEZER
6484 * freeze_workqueues_begin - begin freezing workqueues
6486 * Start freezing workqueues. After this function returns, all freezable
6487 * workqueues will queue new works to their inactive_works list instead of
6491 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
6493 void freeze_workqueues_begin(void)
6495 struct workqueue_struct *wq;
6497 mutex_lock(&wq_pool_mutex);
6499 WARN_ON_ONCE(workqueue_freezing);
6500 workqueue_freezing = true;
6502 list_for_each_entry(wq, &workqueues, list) {
6503 mutex_lock(&wq->mutex);
6504 wq_adjust_max_active(wq);
6505 mutex_unlock(&wq->mutex);
6508 mutex_unlock(&wq_pool_mutex);
6512 * freeze_workqueues_busy - are freezable workqueues still busy?
6514 * Check whether freezing is complete. This function must be called
6515 * between freeze_workqueues_begin() and thaw_workqueues().
6518 * Grabs and releases wq_pool_mutex.
6521 * %true if some freezable workqueues are still busy. %false if freezing
6524 bool freeze_workqueues_busy(void)
6527 struct workqueue_struct *wq;
6528 struct pool_workqueue *pwq;
6530 mutex_lock(&wq_pool_mutex);
6532 WARN_ON_ONCE(!workqueue_freezing);
6534 list_for_each_entry(wq, &workqueues, list) {
6535 if (!(wq->flags & WQ_FREEZABLE))
6538 * nr_active is monotonically decreasing. It's safe
6539 * to peek without lock.
6542 for_each_pwq(pwq, wq) {
6543 WARN_ON_ONCE(pwq->nr_active < 0);
6544 if (pwq->nr_active) {
6553 mutex_unlock(&wq_pool_mutex);
6558 * thaw_workqueues - thaw workqueues
6560 * Thaw workqueues. Normal queueing is restored and all collected
6561 * frozen works are transferred to their respective pool worklists.
6564 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
6566 void thaw_workqueues(void)
6568 struct workqueue_struct *wq;
6570 mutex_lock(&wq_pool_mutex);
6572 if (!workqueue_freezing)
6575 workqueue_freezing = false;
6577 /* restore max_active and repopulate worklist */
6578 list_for_each_entry(wq, &workqueues, list) {
6579 mutex_lock(&wq->mutex);
6580 wq_adjust_max_active(wq);
6581 mutex_unlock(&wq->mutex);
6585 mutex_unlock(&wq_pool_mutex);
6587 #endif /* CONFIG_FREEZER */
6589 static int workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask)
6593 struct workqueue_struct *wq;
6594 struct apply_wqattrs_ctx *ctx, *n;
6596 lockdep_assert_held(&wq_pool_mutex);
6598 list_for_each_entry(wq, &workqueues, list) {
6599 if (!(wq->flags & WQ_UNBOUND) || (wq->flags & __WQ_DESTROYING))
6602 ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs, unbound_cpumask);
6608 list_add_tail(&ctx->list, &ctxs);
6611 list_for_each_entry_safe(ctx, n, &ctxs, list) {
6613 apply_wqattrs_commit(ctx);
6614 apply_wqattrs_cleanup(ctx);
6618 mutex_lock(&wq_pool_attach_mutex);
6619 cpumask_copy(wq_unbound_cpumask, unbound_cpumask);
6620 mutex_unlock(&wq_pool_attach_mutex);
6626 * workqueue_unbound_exclude_cpumask - Exclude given CPUs from unbound cpumask
6627 * @exclude_cpumask: the cpumask to be excluded from wq_unbound_cpumask
6629 * This function can be called from cpuset code to provide a set of isolated
6630 * CPUs that should be excluded from wq_unbound_cpumask. The caller must hold
6631 * either cpus_read_lock or cpus_write_lock.
6633 int workqueue_unbound_exclude_cpumask(cpumask_var_t exclude_cpumask)
6635 cpumask_var_t cpumask;
6638 if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
6641 lockdep_assert_cpus_held();
6642 mutex_lock(&wq_pool_mutex);
6644 /* Save the current isolated cpumask & export it via sysfs */
6645 cpumask_copy(wq_isolated_cpumask, exclude_cpumask);
6648 * If the operation fails, it will fall back to
6649 * wq_requested_unbound_cpumask which is initially set to
6650 * (HK_TYPE_WQ ∩ HK_TYPE_DOMAIN) house keeping mask and rewritten
6651 * by any subsequent write to workqueue/cpumask sysfs file.
6653 if (!cpumask_andnot(cpumask, wq_requested_unbound_cpumask, exclude_cpumask))
6654 cpumask_copy(cpumask, wq_requested_unbound_cpumask);
6655 if (!cpumask_equal(cpumask, wq_unbound_cpumask))
6656 ret = workqueue_apply_unbound_cpumask(cpumask);
6658 mutex_unlock(&wq_pool_mutex);
6659 free_cpumask_var(cpumask);
6663 static int parse_affn_scope(const char *val)
6667 for (i = 0; i < ARRAY_SIZE(wq_affn_names); i++) {
6668 if (!strncasecmp(val, wq_affn_names[i], strlen(wq_affn_names[i])))
6674 static int wq_affn_dfl_set(const char *val, const struct kernel_param *kp)
6676 struct workqueue_struct *wq;
6679 affn = parse_affn_scope(val);
6682 if (affn == WQ_AFFN_DFL)
6686 mutex_lock(&wq_pool_mutex);
6690 list_for_each_entry(wq, &workqueues, list) {
6691 for_each_online_cpu(cpu) {
6692 wq_update_pod(wq, cpu, cpu, true);
6696 mutex_unlock(&wq_pool_mutex);
6702 static int wq_affn_dfl_get(char *buffer, const struct kernel_param *kp)
6704 return scnprintf(buffer, PAGE_SIZE, "%s\n", wq_affn_names[wq_affn_dfl]);
6707 static const struct kernel_param_ops wq_affn_dfl_ops = {
6708 .set = wq_affn_dfl_set,
6709 .get = wq_affn_dfl_get,
6712 module_param_cb(default_affinity_scope, &wq_affn_dfl_ops, NULL, 0644);
6716 * Workqueues with WQ_SYSFS flag set is visible to userland via
6717 * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
6718 * following attributes.
6720 * per_cpu RO bool : whether the workqueue is per-cpu or unbound
6721 * max_active RW int : maximum number of in-flight work items
6723 * Unbound workqueues have the following extra attributes.
6725 * nice RW int : nice value of the workers
6726 * cpumask RW mask : bitmask of allowed CPUs for the workers
6727 * affinity_scope RW str : worker CPU affinity scope (cache, numa, none)
6728 * affinity_strict RW bool : worker CPU affinity is strict
6731 struct workqueue_struct *wq;
6735 static struct workqueue_struct *dev_to_wq(struct device *dev)
6737 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
6742 static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
6745 struct workqueue_struct *wq = dev_to_wq(dev);
6747 return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
6749 static DEVICE_ATTR_RO(per_cpu);
6751 static ssize_t max_active_show(struct device *dev,
6752 struct device_attribute *attr, char *buf)
6754 struct workqueue_struct *wq = dev_to_wq(dev);
6756 return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
6759 static ssize_t max_active_store(struct device *dev,
6760 struct device_attribute *attr, const char *buf,
6763 struct workqueue_struct *wq = dev_to_wq(dev);
6766 if (sscanf(buf, "%d", &val) != 1 || val <= 0)
6769 workqueue_set_max_active(wq, val);
6772 static DEVICE_ATTR_RW(max_active);
6774 static struct attribute *wq_sysfs_attrs[] = {
6775 &dev_attr_per_cpu.attr,
6776 &dev_attr_max_active.attr,
6779 ATTRIBUTE_GROUPS(wq_sysfs);
6781 static void apply_wqattrs_lock(void)
6783 /* CPUs should stay stable across pwq creations and installations */
6785 mutex_lock(&wq_pool_mutex);
6788 static void apply_wqattrs_unlock(void)
6790 mutex_unlock(&wq_pool_mutex);
6794 static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
6797 struct workqueue_struct *wq = dev_to_wq(dev);
6800 mutex_lock(&wq->mutex);
6801 written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
6802 mutex_unlock(&wq->mutex);
6807 /* prepare workqueue_attrs for sysfs store operations */
6808 static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
6810 struct workqueue_attrs *attrs;
6812 lockdep_assert_held(&wq_pool_mutex);
6814 attrs = alloc_workqueue_attrs();
6818 copy_workqueue_attrs(attrs, wq->unbound_attrs);
6822 static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
6823 const char *buf, size_t count)
6825 struct workqueue_struct *wq = dev_to_wq(dev);
6826 struct workqueue_attrs *attrs;
6829 apply_wqattrs_lock();
6831 attrs = wq_sysfs_prep_attrs(wq);
6835 if (sscanf(buf, "%d", &attrs->nice) == 1 &&
6836 attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
6837 ret = apply_workqueue_attrs_locked(wq, attrs);
6842 apply_wqattrs_unlock();
6843 free_workqueue_attrs(attrs);
6844 return ret ?: count;
6847 static ssize_t wq_cpumask_show(struct device *dev,
6848 struct device_attribute *attr, char *buf)
6850 struct workqueue_struct *wq = dev_to_wq(dev);
6853 mutex_lock(&wq->mutex);
6854 written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
6855 cpumask_pr_args(wq->unbound_attrs->cpumask));
6856 mutex_unlock(&wq->mutex);
6860 static ssize_t wq_cpumask_store(struct device *dev,
6861 struct device_attribute *attr,
6862 const char *buf, size_t count)
6864 struct workqueue_struct *wq = dev_to_wq(dev);
6865 struct workqueue_attrs *attrs;
6868 apply_wqattrs_lock();
6870 attrs = wq_sysfs_prep_attrs(wq);
6874 ret = cpumask_parse(buf, attrs->cpumask);
6876 ret = apply_workqueue_attrs_locked(wq, attrs);
6879 apply_wqattrs_unlock();
6880 free_workqueue_attrs(attrs);
6881 return ret ?: count;
6884 static ssize_t wq_affn_scope_show(struct device *dev,
6885 struct device_attribute *attr, char *buf)
6887 struct workqueue_struct *wq = dev_to_wq(dev);
6890 mutex_lock(&wq->mutex);
6891 if (wq->unbound_attrs->affn_scope == WQ_AFFN_DFL)
6892 written = scnprintf(buf, PAGE_SIZE, "%s (%s)\n",
6893 wq_affn_names[WQ_AFFN_DFL],
6894 wq_affn_names[wq_affn_dfl]);
6896 written = scnprintf(buf, PAGE_SIZE, "%s\n",
6897 wq_affn_names[wq->unbound_attrs->affn_scope]);
6898 mutex_unlock(&wq->mutex);
6903 static ssize_t wq_affn_scope_store(struct device *dev,
6904 struct device_attribute *attr,
6905 const char *buf, size_t count)
6907 struct workqueue_struct *wq = dev_to_wq(dev);
6908 struct workqueue_attrs *attrs;
6909 int affn, ret = -ENOMEM;
6911 affn = parse_affn_scope(buf);
6915 apply_wqattrs_lock();
6916 attrs = wq_sysfs_prep_attrs(wq);
6918 attrs->affn_scope = affn;
6919 ret = apply_workqueue_attrs_locked(wq, attrs);
6921 apply_wqattrs_unlock();
6922 free_workqueue_attrs(attrs);
6923 return ret ?: count;
6926 static ssize_t wq_affinity_strict_show(struct device *dev,
6927 struct device_attribute *attr, char *buf)
6929 struct workqueue_struct *wq = dev_to_wq(dev);
6931 return scnprintf(buf, PAGE_SIZE, "%d\n",
6932 wq->unbound_attrs->affn_strict);
6935 static ssize_t wq_affinity_strict_store(struct device *dev,
6936 struct device_attribute *attr,
6937 const char *buf, size_t count)
6939 struct workqueue_struct *wq = dev_to_wq(dev);
6940 struct workqueue_attrs *attrs;
6941 int v, ret = -ENOMEM;
6943 if (sscanf(buf, "%d", &v) != 1)
6946 apply_wqattrs_lock();
6947 attrs = wq_sysfs_prep_attrs(wq);
6949 attrs->affn_strict = (bool)v;
6950 ret = apply_workqueue_attrs_locked(wq, attrs);
6952 apply_wqattrs_unlock();
6953 free_workqueue_attrs(attrs);
6954 return ret ?: count;
6957 static struct device_attribute wq_sysfs_unbound_attrs[] = {
6958 __ATTR(nice, 0644, wq_nice_show, wq_nice_store),
6959 __ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
6960 __ATTR(affinity_scope, 0644, wq_affn_scope_show, wq_affn_scope_store),
6961 __ATTR(affinity_strict, 0644, wq_affinity_strict_show, wq_affinity_strict_store),
6965 static struct bus_type wq_subsys = {
6966 .name = "workqueue",
6967 .dev_groups = wq_sysfs_groups,
6971 * workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
6972 * @cpumask: the cpumask to set
6974 * The low-level workqueues cpumask is a global cpumask that limits
6975 * the affinity of all unbound workqueues. This function check the @cpumask
6976 * and apply it to all unbound workqueues and updates all pwqs of them.
6978 * Return: 0 - Success
6979 * -EINVAL - Invalid @cpumask
6980 * -ENOMEM - Failed to allocate memory for attrs or pwqs.
6982 static int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
6987 * Not excluding isolated cpus on purpose.
6988 * If the user wishes to include them, we allow that.
6990 cpumask_and(cpumask, cpumask, cpu_possible_mask);
6991 if (!cpumask_empty(cpumask)) {
6992 apply_wqattrs_lock();
6993 cpumask_copy(wq_requested_unbound_cpumask, cpumask);
6994 if (cpumask_equal(cpumask, wq_unbound_cpumask)) {
6999 ret = workqueue_apply_unbound_cpumask(cpumask);
7002 apply_wqattrs_unlock();
7008 static ssize_t __wq_cpumask_show(struct device *dev,
7009 struct device_attribute *attr, char *buf, cpumask_var_t mask)
7013 mutex_lock(&wq_pool_mutex);
7014 written = scnprintf(buf, PAGE_SIZE, "%*pb\n", cpumask_pr_args(mask));
7015 mutex_unlock(&wq_pool_mutex);
7020 static ssize_t wq_unbound_cpumask_show(struct device *dev,
7021 struct device_attribute *attr, char *buf)
7023 return __wq_cpumask_show(dev, attr, buf, wq_unbound_cpumask);
7026 static ssize_t wq_requested_cpumask_show(struct device *dev,
7027 struct device_attribute *attr, char *buf)
7029 return __wq_cpumask_show(dev, attr, buf, wq_requested_unbound_cpumask);
7032 static ssize_t wq_isolated_cpumask_show(struct device *dev,
7033 struct device_attribute *attr, char *buf)
7035 return __wq_cpumask_show(dev, attr, buf, wq_isolated_cpumask);
7038 static ssize_t wq_unbound_cpumask_store(struct device *dev,
7039 struct device_attribute *attr, const char *buf, size_t count)
7041 cpumask_var_t cpumask;
7044 if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
7047 ret = cpumask_parse(buf, cpumask);
7049 ret = workqueue_set_unbound_cpumask(cpumask);
7051 free_cpumask_var(cpumask);
7052 return ret ? ret : count;
7055 static struct device_attribute wq_sysfs_cpumask_attrs[] = {
7056 __ATTR(cpumask, 0644, wq_unbound_cpumask_show,
7057 wq_unbound_cpumask_store),
7058 __ATTR(cpumask_requested, 0444, wq_requested_cpumask_show, NULL),
7059 __ATTR(cpumask_isolated, 0444, wq_isolated_cpumask_show, NULL),
7063 static int __init wq_sysfs_init(void)
7065 struct device *dev_root;
7068 err = subsys_virtual_register(&wq_subsys, NULL);
7072 dev_root = bus_get_dev_root(&wq_subsys);
7074 struct device_attribute *attr;
7076 for (attr = wq_sysfs_cpumask_attrs; attr->attr.name; attr++) {
7077 err = device_create_file(dev_root, attr);
7081 put_device(dev_root);
7085 core_initcall(wq_sysfs_init);
7087 static void wq_device_release(struct device *dev)
7089 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
7095 * workqueue_sysfs_register - make a workqueue visible in sysfs
7096 * @wq: the workqueue to register
7098 * Expose @wq in sysfs under /sys/bus/workqueue/devices.
7099 * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
7100 * which is the preferred method.
7102 * Workqueue user should use this function directly iff it wants to apply
7103 * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
7104 * apply_workqueue_attrs() may race against userland updating the
7107 * Return: 0 on success, -errno on failure.
7109 int workqueue_sysfs_register(struct workqueue_struct *wq)
7111 struct wq_device *wq_dev;
7115 * Adjusting max_active breaks ordering guarantee. Disallow exposing
7116 * ordered workqueues.
7118 if (WARN_ON(wq->flags & __WQ_ORDERED))
7121 wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
7126 wq_dev->dev.bus = &wq_subsys;
7127 wq_dev->dev.release = wq_device_release;
7128 dev_set_name(&wq_dev->dev, "%s", wq->name);
7131 * unbound_attrs are created separately. Suppress uevent until
7132 * everything is ready.
7134 dev_set_uevent_suppress(&wq_dev->dev, true);
7136 ret = device_register(&wq_dev->dev);
7138 put_device(&wq_dev->dev);
7143 if (wq->flags & WQ_UNBOUND) {
7144 struct device_attribute *attr;
7146 for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
7147 ret = device_create_file(&wq_dev->dev, attr);
7149 device_unregister(&wq_dev->dev);
7156 dev_set_uevent_suppress(&wq_dev->dev, false);
7157 kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
7162 * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
7163 * @wq: the workqueue to unregister
7165 * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
7167 static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
7169 struct wq_device *wq_dev = wq->wq_dev;
7175 device_unregister(&wq_dev->dev);
7177 #else /* CONFIG_SYSFS */
7178 static void workqueue_sysfs_unregister(struct workqueue_struct *wq) { }
7179 #endif /* CONFIG_SYSFS */
7182 * Workqueue watchdog.
7184 * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
7185 * flush dependency, a concurrency managed work item which stays RUNNING
7186 * indefinitely. Workqueue stalls can be very difficult to debug as the
7187 * usual warning mechanisms don't trigger and internal workqueue state is
7190 * Workqueue watchdog monitors all worker pools periodically and dumps
7191 * state if some pools failed to make forward progress for a while where
7192 * forward progress is defined as the first item on ->worklist changing.
7194 * This mechanism is controlled through the kernel parameter
7195 * "workqueue.watchdog_thresh" which can be updated at runtime through the
7196 * corresponding sysfs parameter file.
7198 #ifdef CONFIG_WQ_WATCHDOG
7200 static unsigned long wq_watchdog_thresh = 30;
7201 static struct timer_list wq_watchdog_timer;
7203 static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
7204 static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
7207 * Show workers that might prevent the processing of pending work items.
7208 * The only candidates are CPU-bound workers in the running state.
7209 * Pending work items should be handled by another idle worker
7210 * in all other situations.
7212 static void show_cpu_pool_hog(struct worker_pool *pool)
7214 struct worker *worker;
7215 unsigned long flags;
7218 raw_spin_lock_irqsave(&pool->lock, flags);
7220 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
7221 if (task_is_running(worker->task)) {
7223 * Defer printing to avoid deadlocks in console
7224 * drivers that queue work while holding locks
7225 * also taken in their write paths.
7227 printk_deferred_enter();
7229 pr_info("pool %d:\n", pool->id);
7230 sched_show_task(worker->task);
7232 printk_deferred_exit();
7236 raw_spin_unlock_irqrestore(&pool->lock, flags);
7239 static void show_cpu_pools_hogs(void)
7241 struct worker_pool *pool;
7244 pr_info("Showing backtraces of running workers in stalled CPU-bound worker pools:\n");
7248 for_each_pool(pool, pi) {
7249 if (pool->cpu_stall)
7250 show_cpu_pool_hog(pool);
7257 static void wq_watchdog_reset_touched(void)
7261 wq_watchdog_touched = jiffies;
7262 for_each_possible_cpu(cpu)
7263 per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
7266 static void wq_watchdog_timer_fn(struct timer_list *unused)
7268 unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
7269 bool lockup_detected = false;
7270 bool cpu_pool_stall = false;
7271 unsigned long now = jiffies;
7272 struct worker_pool *pool;
7280 for_each_pool(pool, pi) {
7281 unsigned long pool_ts, touched, ts;
7283 pool->cpu_stall = false;
7284 if (list_empty(&pool->worklist))
7288 * If a virtual machine is stopped by the host it can look to
7289 * the watchdog like a stall.
7291 kvm_check_and_clear_guest_paused();
7293 /* get the latest of pool and touched timestamps */
7295 touched = READ_ONCE(per_cpu(wq_watchdog_touched_cpu, pool->cpu));
7297 touched = READ_ONCE(wq_watchdog_touched);
7298 pool_ts = READ_ONCE(pool->watchdog_ts);
7300 if (time_after(pool_ts, touched))
7306 if (time_after(now, ts + thresh)) {
7307 lockup_detected = true;
7308 if (pool->cpu >= 0 && !(pool->flags & POOL_BH)) {
7309 pool->cpu_stall = true;
7310 cpu_pool_stall = true;
7312 pr_emerg("BUG: workqueue lockup - pool");
7313 pr_cont_pool_info(pool);
7314 pr_cont(" stuck for %us!\n",
7315 jiffies_to_msecs(now - pool_ts) / 1000);
7323 if (lockup_detected)
7324 show_all_workqueues();
7327 show_cpu_pools_hogs();
7329 wq_watchdog_reset_touched();
7330 mod_timer(&wq_watchdog_timer, jiffies + thresh);
7333 notrace void wq_watchdog_touch(int cpu)
7336 per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
7338 wq_watchdog_touched = jiffies;
7341 static void wq_watchdog_set_thresh(unsigned long thresh)
7343 wq_watchdog_thresh = 0;
7344 del_timer_sync(&wq_watchdog_timer);
7347 wq_watchdog_thresh = thresh;
7348 wq_watchdog_reset_touched();
7349 mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
7353 static int wq_watchdog_param_set_thresh(const char *val,
7354 const struct kernel_param *kp)
7356 unsigned long thresh;
7359 ret = kstrtoul(val, 0, &thresh);
7364 wq_watchdog_set_thresh(thresh);
7366 wq_watchdog_thresh = thresh;
7371 static const struct kernel_param_ops wq_watchdog_thresh_ops = {
7372 .set = wq_watchdog_param_set_thresh,
7373 .get = param_get_ulong,
7376 module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
7379 static void wq_watchdog_init(void)
7381 timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
7382 wq_watchdog_set_thresh(wq_watchdog_thresh);
7385 #else /* CONFIG_WQ_WATCHDOG */
7387 static inline void wq_watchdog_init(void) { }
7389 #endif /* CONFIG_WQ_WATCHDOG */
7391 static void bh_pool_kick_normal(struct irq_work *irq_work)
7393 raise_softirq_irqoff(TASKLET_SOFTIRQ);
7396 static void bh_pool_kick_highpri(struct irq_work *irq_work)
7398 raise_softirq_irqoff(HI_SOFTIRQ);
7401 static void __init restrict_unbound_cpumask(const char *name, const struct cpumask *mask)
7403 if (!cpumask_intersects(wq_unbound_cpumask, mask)) {
7404 pr_warn("workqueue: Restricting unbound_cpumask (%*pb) with %s (%*pb) leaves no CPU, ignoring\n",
7405 cpumask_pr_args(wq_unbound_cpumask), name, cpumask_pr_args(mask));
7409 cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, mask);
7412 static void __init init_cpu_worker_pool(struct worker_pool *pool, int cpu, int nice)
7414 BUG_ON(init_worker_pool(pool));
7416 cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
7417 cpumask_copy(pool->attrs->__pod_cpumask, cpumask_of(cpu));
7418 pool->attrs->nice = nice;
7419 pool->attrs->affn_strict = true;
7420 pool->node = cpu_to_node(cpu);
7423 mutex_lock(&wq_pool_mutex);
7424 BUG_ON(worker_pool_assign_id(pool));
7425 mutex_unlock(&wq_pool_mutex);
7429 * workqueue_init_early - early init for workqueue subsystem
7431 * This is the first step of three-staged workqueue subsystem initialization and
7432 * invoked as soon as the bare basics - memory allocation, cpumasks and idr are
7433 * up. It sets up all the data structures and system workqueues and allows early
7434 * boot code to create workqueues and queue/cancel work items. Actual work item
7435 * execution starts only after kthreads can be created and scheduled right
7436 * before early initcalls.
7438 void __init workqueue_init_early(void)
7440 struct wq_pod_type *pt = &wq_pod_types[WQ_AFFN_SYSTEM];
7441 int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
7442 void (*irq_work_fns[2])(struct irq_work *) = { bh_pool_kick_normal,
7443 bh_pool_kick_highpri };
7446 BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
7448 BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
7449 BUG_ON(!alloc_cpumask_var(&wq_requested_unbound_cpumask, GFP_KERNEL));
7450 BUG_ON(!zalloc_cpumask_var(&wq_isolated_cpumask, GFP_KERNEL));
7452 cpumask_copy(wq_unbound_cpumask, cpu_possible_mask);
7453 restrict_unbound_cpumask("HK_TYPE_WQ", housekeeping_cpumask(HK_TYPE_WQ));
7454 restrict_unbound_cpumask("HK_TYPE_DOMAIN", housekeeping_cpumask(HK_TYPE_DOMAIN));
7455 if (!cpumask_empty(&wq_cmdline_cpumask))
7456 restrict_unbound_cpumask("workqueue.unbound_cpus", &wq_cmdline_cpumask);
7458 cpumask_copy(wq_requested_unbound_cpumask, wq_unbound_cpumask);
7460 pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
7462 wq_update_pod_attrs_buf = alloc_workqueue_attrs();
7463 BUG_ON(!wq_update_pod_attrs_buf);
7466 * If nohz_full is enabled, set power efficient workqueue as unbound.
7467 * This allows workqueue items to be moved to HK CPUs.
7469 if (housekeeping_enabled(HK_TYPE_TICK))
7470 wq_power_efficient = true;
7472 /* initialize WQ_AFFN_SYSTEM pods */
7473 pt->pod_cpus = kcalloc(1, sizeof(pt->pod_cpus[0]), GFP_KERNEL);
7474 pt->pod_node = kcalloc(1, sizeof(pt->pod_node[0]), GFP_KERNEL);
7475 pt->cpu_pod = kcalloc(nr_cpu_ids, sizeof(pt->cpu_pod[0]), GFP_KERNEL);
7476 BUG_ON(!pt->pod_cpus || !pt->pod_node || !pt->cpu_pod);
7478 BUG_ON(!zalloc_cpumask_var_node(&pt->pod_cpus[0], GFP_KERNEL, NUMA_NO_NODE));
7481 cpumask_copy(pt->pod_cpus[0], cpu_possible_mask);
7482 pt->pod_node[0] = NUMA_NO_NODE;
7485 /* initialize BH and CPU pools */
7486 for_each_possible_cpu(cpu) {
7487 struct worker_pool *pool;
7490 for_each_bh_worker_pool(pool, cpu) {
7491 init_cpu_worker_pool(pool, cpu, std_nice[i]);
7492 pool->flags |= POOL_BH;
7493 init_irq_work(bh_pool_irq_work(pool), irq_work_fns[i]);
7498 for_each_cpu_worker_pool(pool, cpu)
7499 init_cpu_worker_pool(pool, cpu, std_nice[i++]);
7502 /* create default unbound and ordered wq attrs */
7503 for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
7504 struct workqueue_attrs *attrs;
7506 BUG_ON(!(attrs = alloc_workqueue_attrs()));
7507 attrs->nice = std_nice[i];
7508 unbound_std_wq_attrs[i] = attrs;
7511 * An ordered wq should have only one pwq as ordering is
7512 * guaranteed by max_active which is enforced by pwqs.
7514 BUG_ON(!(attrs = alloc_workqueue_attrs()));
7515 attrs->nice = std_nice[i];
7516 attrs->ordered = true;
7517 ordered_wq_attrs[i] = attrs;
7520 system_wq = alloc_workqueue("events", 0, 0);
7521 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
7522 system_long_wq = alloc_workqueue("events_long", 0, 0);
7523 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
7525 system_freezable_wq = alloc_workqueue("events_freezable",
7527 system_power_efficient_wq = alloc_workqueue("events_power_efficient",
7528 WQ_POWER_EFFICIENT, 0);
7529 system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_pwr_efficient",
7530 WQ_FREEZABLE | WQ_POWER_EFFICIENT,
7532 system_bh_wq = alloc_workqueue("events_bh", WQ_BH, 0);
7533 system_bh_highpri_wq = alloc_workqueue("events_bh_highpri",
7534 WQ_BH | WQ_HIGHPRI, 0);
7535 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
7536 !system_unbound_wq || !system_freezable_wq ||
7537 !system_power_efficient_wq ||
7538 !system_freezable_power_efficient_wq ||
7539 !system_bh_wq || !system_bh_highpri_wq);
7542 static void __init wq_cpu_intensive_thresh_init(void)
7544 unsigned long thresh;
7547 pwq_release_worker = kthread_create_worker(0, "pool_workqueue_release");
7548 BUG_ON(IS_ERR(pwq_release_worker));
7550 /* if the user set it to a specific value, keep it */
7551 if (wq_cpu_intensive_thresh_us != ULONG_MAX)
7555 * The default of 10ms is derived from the fact that most modern (as of
7556 * 2023) processors can do a lot in 10ms and that it's just below what
7557 * most consider human-perceivable. However, the kernel also runs on a
7558 * lot slower CPUs including microcontrollers where the threshold is way
7561 * Let's scale up the threshold upto 1 second if BogoMips is below 4000.
7562 * This is by no means accurate but it doesn't have to be. The mechanism
7563 * is still useful even when the threshold is fully scaled up. Also, as
7564 * the reports would usually be applicable to everyone, some machines
7565 * operating on longer thresholds won't significantly diminish their
7568 thresh = 10 * USEC_PER_MSEC;
7570 /* see init/calibrate.c for lpj -> BogoMIPS calculation */
7571 bogo = max_t(unsigned long, loops_per_jiffy / 500000 * HZ, 1);
7573 thresh = min_t(unsigned long, thresh * 4000 / bogo, USEC_PER_SEC);
7575 pr_debug("wq_cpu_intensive_thresh: lpj=%lu BogoMIPS=%lu thresh_us=%lu\n",
7576 loops_per_jiffy, bogo, thresh);
7578 wq_cpu_intensive_thresh_us = thresh;
7582 * workqueue_init - bring workqueue subsystem fully online
7584 * This is the second step of three-staged workqueue subsystem initialization
7585 * and invoked as soon as kthreads can be created and scheduled. Workqueues have
7586 * been created and work items queued on them, but there are no kworkers
7587 * executing the work items yet. Populate the worker pools with the initial
7588 * workers and enable future kworker creations.
7590 void __init workqueue_init(void)
7592 struct workqueue_struct *wq;
7593 struct worker_pool *pool;
7596 wq_cpu_intensive_thresh_init();
7598 mutex_lock(&wq_pool_mutex);
7601 * Per-cpu pools created earlier could be missing node hint. Fix them
7602 * up. Also, create a rescuer for workqueues that requested it.
7604 for_each_possible_cpu(cpu) {
7605 for_each_bh_worker_pool(pool, cpu)
7606 pool->node = cpu_to_node(cpu);
7607 for_each_cpu_worker_pool(pool, cpu)
7608 pool->node = cpu_to_node(cpu);
7611 list_for_each_entry(wq, &workqueues, list) {
7612 WARN(init_rescuer(wq),
7613 "workqueue: failed to create early rescuer for %s",
7617 mutex_unlock(&wq_pool_mutex);
7620 * Create the initial workers. A BH pool has one pseudo worker that
7621 * represents the shared BH execution context and thus doesn't get
7622 * affected by hotplug events. Create the BH pseudo workers for all
7623 * possible CPUs here.
7625 for_each_possible_cpu(cpu)
7626 for_each_bh_worker_pool(pool, cpu)
7627 BUG_ON(!create_worker(pool));
7629 for_each_online_cpu(cpu) {
7630 for_each_cpu_worker_pool(pool, cpu) {
7631 pool->flags &= ~POOL_DISASSOCIATED;
7632 BUG_ON(!create_worker(pool));
7636 hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
7637 BUG_ON(!create_worker(pool));
7644 * Initialize @pt by first initializing @pt->cpu_pod[] with pod IDs according to
7645 * @cpu_shares_pod(). Each subset of CPUs that share a pod is assigned a unique
7646 * and consecutive pod ID. The rest of @pt is initialized accordingly.
7648 static void __init init_pod_type(struct wq_pod_type *pt,
7649 bool (*cpus_share_pod)(int, int))
7651 int cur, pre, cpu, pod;
7655 /* init @pt->cpu_pod[] according to @cpus_share_pod() */
7656 pt->cpu_pod = kcalloc(nr_cpu_ids, sizeof(pt->cpu_pod[0]), GFP_KERNEL);
7657 BUG_ON(!pt->cpu_pod);
7659 for_each_possible_cpu(cur) {
7660 for_each_possible_cpu(pre) {
7662 pt->cpu_pod[cur] = pt->nr_pods++;
7665 if (cpus_share_pod(cur, pre)) {
7666 pt->cpu_pod[cur] = pt->cpu_pod[pre];
7672 /* init the rest to match @pt->cpu_pod[] */
7673 pt->pod_cpus = kcalloc(pt->nr_pods, sizeof(pt->pod_cpus[0]), GFP_KERNEL);
7674 pt->pod_node = kcalloc(pt->nr_pods, sizeof(pt->pod_node[0]), GFP_KERNEL);
7675 BUG_ON(!pt->pod_cpus || !pt->pod_node);
7677 for (pod = 0; pod < pt->nr_pods; pod++)
7678 BUG_ON(!zalloc_cpumask_var(&pt->pod_cpus[pod], GFP_KERNEL));
7680 for_each_possible_cpu(cpu) {
7681 cpumask_set_cpu(cpu, pt->pod_cpus[pt->cpu_pod[cpu]]);
7682 pt->pod_node[pt->cpu_pod[cpu]] = cpu_to_node(cpu);
7686 static bool __init cpus_dont_share(int cpu0, int cpu1)
7691 static bool __init cpus_share_smt(int cpu0, int cpu1)
7693 #ifdef CONFIG_SCHED_SMT
7694 return cpumask_test_cpu(cpu0, cpu_smt_mask(cpu1));
7700 static bool __init cpus_share_numa(int cpu0, int cpu1)
7702 return cpu_to_node(cpu0) == cpu_to_node(cpu1);
7706 * workqueue_init_topology - initialize CPU pods for unbound workqueues
7708 * This is the third step of three-staged workqueue subsystem initialization and
7709 * invoked after SMP and topology information are fully initialized. It
7710 * initializes the unbound CPU pods accordingly.
7712 void __init workqueue_init_topology(void)
7714 struct workqueue_struct *wq;
7717 init_pod_type(&wq_pod_types[WQ_AFFN_CPU], cpus_dont_share);
7718 init_pod_type(&wq_pod_types[WQ_AFFN_SMT], cpus_share_smt);
7719 init_pod_type(&wq_pod_types[WQ_AFFN_CACHE], cpus_share_cache);
7720 init_pod_type(&wq_pod_types[WQ_AFFN_NUMA], cpus_share_numa);
7722 wq_topo_initialized = true;
7724 mutex_lock(&wq_pool_mutex);
7727 * Workqueues allocated earlier would have all CPUs sharing the default
7728 * worker pool. Explicitly call wq_update_pod() on all workqueue and CPU
7729 * combinations to apply per-pod sharing.
7731 list_for_each_entry(wq, &workqueues, list) {
7732 for_each_online_cpu(cpu)
7733 wq_update_pod(wq, cpu, cpu, true);
7734 if (wq->flags & WQ_UNBOUND) {
7735 mutex_lock(&wq->mutex);
7736 wq_update_node_max_active(wq, -1);
7737 mutex_unlock(&wq->mutex);
7741 mutex_unlock(&wq_pool_mutex);
7744 void __warn_flushing_systemwide_wq(void)
7746 pr_warn("WARNING: Flushing system-wide workqueues will be prohibited in near future.\n");
7749 EXPORT_SYMBOL(__warn_flushing_systemwide_wq);
7751 static int __init workqueue_unbound_cpus_setup(char *str)
7753 if (cpulist_parse(str, &wq_cmdline_cpumask) < 0) {
7754 cpumask_clear(&wq_cmdline_cpumask);
7755 pr_warn("workqueue.unbound_cpus: incorrect CPU range, using default\n");
7760 __setup("workqueue.unbound_cpus=", workqueue_unbound_cpus_setup);