1 // SPDX-License-Identifier: GPL-2.0-only
3 * kernel/workqueue.c - generic async execution with shared worker pool
5 * Copyright (C) 2002 Ingo Molnar
7 * Derived from the taskqueue/keventd code by:
13 * Made to use alloc_percpu by Christoph Lameter.
15 * Copyright (C) 2010 SUSE Linux Products GmbH
18 * This is the generic async execution mechanism. Work items as are
19 * executed in process context. The worker pool is shared and
20 * automatically managed. There are two worker pools for each CPU (one for
21 * normal work items and the other for high priority ones) and some extra
22 * pools for workqueues which are not bound to any specific CPU - the
23 * number of these backing pools is dynamic.
25 * Please read Documentation/core-api/workqueue.rst for details.
28 #include <linux/export.h>
29 #include <linux/kernel.h>
30 #include <linux/sched.h>
31 #include <linux/init.h>
32 #include <linux/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 work_cancel_flags {
100 WORK_CANCEL_DELAYED = 1 << 0, /* canceling a delayed_work */
103 enum wq_internal_consts {
104 NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */
106 UNBOUND_POOL_HASH_ORDER = 6, /* hashed by pool->attrs */
107 BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
109 MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
110 IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
112 MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
113 /* call for help after 10ms
115 MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
116 CREATE_COOLDOWN = HZ, /* time to breath after fail */
119 * Rescue workers are used only on emergencies and shared by
120 * all cpus. Give MIN_NICE.
122 RESCUER_NICE_LEVEL = MIN_NICE,
123 HIGHPRI_NICE_LEVEL = MIN_NICE,
129 * We don't want to trap softirq for too long. See MAX_SOFTIRQ_TIME and
130 * MAX_SOFTIRQ_RESTART in kernel/softirq.c. These are macros because
131 * msecs_to_jiffies() can't be an initializer.
133 #define BH_WORKER_JIFFIES msecs_to_jiffies(2)
134 #define BH_WORKER_RESTARTS 10
137 * Structure fields follow one of the following exclusion rules.
139 * I: Modifiable by initialization/destruction paths and read-only for
142 * P: Preemption protected. Disabling preemption is enough and should
143 * only be modified and accessed from the local cpu.
145 * L: pool->lock protected. Access with pool->lock held.
147 * LN: pool->lock and wq_node_nr_active->lock protected for writes. Either for
150 * K: Only modified by worker while holding pool->lock. Can be safely read by
151 * self, while holding pool->lock or from IRQ context if %current is the
154 * S: Only modified by worker self.
156 * A: wq_pool_attach_mutex protected.
158 * PL: wq_pool_mutex protected.
160 * PR: wq_pool_mutex protected for writes. RCU protected for reads.
162 * PW: wq_pool_mutex and wq->mutex protected for writes. Either for reads.
164 * PWR: wq_pool_mutex and wq->mutex protected for writes. Either or
167 * WQ: wq->mutex protected.
169 * WR: wq->mutex protected for writes. RCU protected for reads.
171 * WO: wq->mutex protected for writes. Updated with WRITE_ONCE() and can be read
172 * with READ_ONCE() without locking.
174 * MD: wq_mayday_lock protected.
176 * WD: Used internally by the watchdog.
179 /* struct worker is defined in workqueue_internal.h */
182 raw_spinlock_t lock; /* the pool lock */
183 int cpu; /* I: the associated cpu */
184 int node; /* I: the associated node ID */
185 int id; /* I: pool ID */
186 unsigned int flags; /* L: flags */
188 unsigned long watchdog_ts; /* L: watchdog timestamp */
189 bool cpu_stall; /* WD: stalled cpu bound pool */
192 * The counter is incremented in a process context on the associated CPU
193 * w/ preemption disabled, and decremented or reset in the same context
194 * but w/ pool->lock held. The readers grab pool->lock and are
195 * guaranteed to see if the counter reached zero.
199 struct list_head worklist; /* L: list of pending works */
201 int nr_workers; /* L: total number of workers */
202 int nr_idle; /* L: currently idle workers */
204 struct list_head idle_list; /* L: list of idle workers */
205 struct timer_list idle_timer; /* L: worker idle timeout */
206 struct work_struct idle_cull_work; /* L: worker idle cleanup */
208 struct timer_list mayday_timer; /* L: SOS timer for workers */
210 /* a workers is either on busy_hash or idle_list, or the manager */
211 DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
212 /* L: hash of busy workers */
214 struct worker *manager; /* L: purely informational */
215 struct list_head workers; /* A: attached workers */
216 struct list_head dying_workers; /* A: workers about to die */
217 struct completion *detach_completion; /* all workers detached */
219 struct ida worker_ida; /* worker IDs for task name */
221 struct workqueue_attrs *attrs; /* I: worker attributes */
222 struct hlist_node hash_node; /* PL: unbound_pool_hash node */
223 int refcnt; /* PL: refcnt for unbound pools */
226 * Destruction of pool is RCU protected to allow dereferences
227 * from get_work_pool().
233 * Per-pool_workqueue statistics. These can be monitored using
234 * tools/workqueue/wq_monitor.py.
236 enum pool_workqueue_stats {
237 PWQ_STAT_STARTED, /* work items started execution */
238 PWQ_STAT_COMPLETED, /* work items completed execution */
239 PWQ_STAT_CPU_TIME, /* total CPU time consumed */
240 PWQ_STAT_CPU_INTENSIVE, /* wq_cpu_intensive_thresh_us violations */
241 PWQ_STAT_CM_WAKEUP, /* concurrency-management worker wakeups */
242 PWQ_STAT_REPATRIATED, /* unbound workers brought back into scope */
243 PWQ_STAT_MAYDAY, /* maydays to rescuer */
244 PWQ_STAT_RESCUED, /* linked work items executed by rescuer */
250 * The per-pool workqueue. While queued, bits below WORK_PWQ_SHIFT
251 * of work_struct->data are used for flags and the remaining high bits
252 * point to the pwq; thus, pwqs need to be aligned at two's power of the
253 * number of flag bits.
255 struct pool_workqueue {
256 struct worker_pool *pool; /* I: the associated pool */
257 struct workqueue_struct *wq; /* I: the owning workqueue */
258 int work_color; /* L: current color */
259 int flush_color; /* L: flushing color */
260 int refcnt; /* L: reference count */
261 int nr_in_flight[WORK_NR_COLORS];
262 /* L: nr of in_flight works */
263 bool plugged; /* L: execution suspended */
266 * nr_active management and WORK_STRUCT_INACTIVE:
268 * When pwq->nr_active >= max_active, new work item is queued to
269 * pwq->inactive_works instead of pool->worklist and marked with
270 * WORK_STRUCT_INACTIVE.
272 * All work items marked with WORK_STRUCT_INACTIVE do not participate in
273 * nr_active and all work items in pwq->inactive_works are marked with
274 * WORK_STRUCT_INACTIVE. But not all WORK_STRUCT_INACTIVE work items are
275 * in pwq->inactive_works. Some of them are ready to run in
276 * pool->worklist or worker->scheduled. Those work itmes are only struct
277 * wq_barrier which is used for flush_work() and should not participate
278 * in nr_active. For non-barrier work item, it is marked with
279 * WORK_STRUCT_INACTIVE iff it is in pwq->inactive_works.
281 int nr_active; /* L: nr of active works */
282 struct list_head inactive_works; /* L: inactive works */
283 struct list_head pending_node; /* LN: node on wq_node_nr_active->pending_pwqs */
284 struct list_head pwqs_node; /* WR: node on wq->pwqs */
285 struct list_head mayday_node; /* MD: node on wq->maydays */
287 u64 stats[PWQ_NR_STATS];
290 * Release of unbound pwq is punted to a kthread_worker. See put_pwq()
291 * and pwq_release_workfn() for details. pool_workqueue itself is also
292 * RCU protected so that the first pwq can be determined without
293 * grabbing wq->mutex.
295 struct kthread_work release_work;
297 } __aligned(1 << WORK_STRUCT_PWQ_SHIFT);
300 * Structure used to wait for workqueue flush.
303 struct list_head list; /* WQ: list of flushers */
304 int flush_color; /* WQ: flush color waiting for */
305 struct completion done; /* flush completion */
311 * Unlike in a per-cpu workqueue where max_active limits its concurrency level
312 * on each CPU, in an unbound workqueue, max_active applies to the whole system.
313 * As sharing a single nr_active across multiple sockets can be very expensive,
314 * the counting and enforcement is per NUMA node.
316 * The following struct is used to enforce per-node max_active. When a pwq wants
317 * to start executing a work item, it should increment ->nr using
318 * tryinc_node_nr_active(). If acquisition fails due to ->nr already being over
319 * ->max, the pwq is queued on ->pending_pwqs. As in-flight work items finish
320 * and decrement ->nr, node_activate_pending_pwq() activates the pending pwqs in
323 struct wq_node_nr_active {
324 int max; /* per-node max_active */
325 atomic_t nr; /* per-node nr_active */
326 raw_spinlock_t lock; /* nests inside pool locks */
327 struct list_head pending_pwqs; /* LN: pwqs with inactive works */
331 * The externally visible workqueue. It relays the issued work items to
332 * the appropriate worker_pool through its pool_workqueues.
334 struct workqueue_struct {
335 struct list_head pwqs; /* WR: all pwqs of this wq */
336 struct list_head list; /* PR: list of all workqueues */
338 struct mutex mutex; /* protects this wq */
339 int work_color; /* WQ: current work color */
340 int flush_color; /* WQ: current flush color */
341 atomic_t nr_pwqs_to_flush; /* flush in progress */
342 struct wq_flusher *first_flusher; /* WQ: first flusher */
343 struct list_head flusher_queue; /* WQ: flush waiters */
344 struct list_head flusher_overflow; /* WQ: flush overflow list */
346 struct list_head maydays; /* MD: pwqs requesting rescue */
347 struct worker *rescuer; /* MD: rescue worker */
349 int nr_drainers; /* WQ: drain in progress */
351 /* See alloc_workqueue() function comment for info on min/max_active */
352 int max_active; /* WO: max active works */
353 int min_active; /* WO: min active works */
354 int saved_max_active; /* WQ: saved max_active */
355 int saved_min_active; /* WQ: saved min_active */
357 struct workqueue_attrs *unbound_attrs; /* PW: only for unbound wqs */
358 struct pool_workqueue __rcu *dfl_pwq; /* PW: only for unbound wqs */
361 struct wq_device *wq_dev; /* I: for sysfs interface */
363 #ifdef CONFIG_LOCKDEP
365 struct lock_class_key key;
366 struct lockdep_map lockdep_map;
368 char name[WQ_NAME_LEN]; /* I: workqueue name */
371 * Destruction of workqueue_struct is RCU protected to allow walking
372 * the workqueues list without grabbing wq_pool_mutex.
373 * This is used to dump all workqueues from sysrq.
377 /* hot fields used during command issue, aligned to cacheline */
378 unsigned int flags ____cacheline_aligned; /* WQ: WQ_* flags */
379 struct pool_workqueue __percpu __rcu **cpu_pwq; /* I: per-cpu pwqs */
380 struct wq_node_nr_active *node_nr_active[]; /* I: per-node nr_active */
384 * Each pod type describes how CPUs should be grouped for unbound workqueues.
385 * See the comment above workqueue_attrs->affn_scope.
388 int nr_pods; /* number of pods */
389 cpumask_var_t *pod_cpus; /* pod -> cpus */
390 int *pod_node; /* pod -> node */
391 int *cpu_pod; /* cpu -> pod */
394 static const char *wq_affn_names[WQ_AFFN_NR_TYPES] = {
395 [WQ_AFFN_DFL] = "default",
396 [WQ_AFFN_CPU] = "cpu",
397 [WQ_AFFN_SMT] = "smt",
398 [WQ_AFFN_CACHE] = "cache",
399 [WQ_AFFN_NUMA] = "numa",
400 [WQ_AFFN_SYSTEM] = "system",
404 * Per-cpu work items which run for longer than the following threshold are
405 * automatically considered CPU intensive and excluded from concurrency
406 * management to prevent them from noticeably delaying other per-cpu work items.
407 * ULONG_MAX indicates that the user hasn't overridden it with a boot parameter.
408 * The actual value is initialized in wq_cpu_intensive_thresh_init().
410 static unsigned long wq_cpu_intensive_thresh_us = ULONG_MAX;
411 module_param_named(cpu_intensive_thresh_us, wq_cpu_intensive_thresh_us, ulong, 0644);
412 #ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
413 static unsigned int wq_cpu_intensive_warning_thresh = 4;
414 module_param_named(cpu_intensive_warning_thresh, wq_cpu_intensive_warning_thresh, uint, 0644);
417 /* see the comment above the definition of WQ_POWER_EFFICIENT */
418 static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
419 module_param_named(power_efficient, wq_power_efficient, bool, 0444);
421 static bool wq_online; /* can kworkers be created yet? */
422 static bool wq_topo_initialized __read_mostly = false;
424 static struct kmem_cache *pwq_cache;
426 static struct wq_pod_type wq_pod_types[WQ_AFFN_NR_TYPES];
427 static enum wq_affn_scope wq_affn_dfl = WQ_AFFN_CACHE;
429 /* buf for wq_update_unbound_pod_attrs(), protected by CPU hotplug exclusion */
430 static struct workqueue_attrs *wq_update_pod_attrs_buf;
432 static DEFINE_MUTEX(wq_pool_mutex); /* protects pools and workqueues list */
433 static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
434 static DEFINE_RAW_SPINLOCK(wq_mayday_lock); /* protects wq->maydays list */
435 /* wait for manager to go away */
436 static struct rcuwait manager_wait = __RCUWAIT_INITIALIZER(manager_wait);
438 static LIST_HEAD(workqueues); /* PR: list of all workqueues */
439 static bool workqueue_freezing; /* PL: have wqs started freezing? */
441 /* PL&A: allowable cpus for unbound wqs and work items */
442 static cpumask_var_t wq_unbound_cpumask;
444 /* PL: user requested unbound cpumask via sysfs */
445 static cpumask_var_t wq_requested_unbound_cpumask;
447 /* PL: isolated cpumask to be excluded from unbound cpumask */
448 static cpumask_var_t wq_isolated_cpumask;
450 /* for further constrain wq_unbound_cpumask by cmdline parameter*/
451 static struct cpumask wq_cmdline_cpumask __initdata;
453 /* CPU where unbound work was last round robin scheduled from this CPU */
454 static DEFINE_PER_CPU(int, wq_rr_cpu_last);
457 * Local execution of unbound work items is no longer guaranteed. The
458 * following always forces round-robin CPU selection on unbound work items
459 * to uncover usages which depend on it.
461 #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
462 static bool wq_debug_force_rr_cpu = true;
464 static bool wq_debug_force_rr_cpu = false;
466 module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
468 /* to raise softirq for the BH worker pools on other CPUs */
469 static DEFINE_PER_CPU_SHARED_ALIGNED(struct irq_work [NR_STD_WORKER_POOLS],
472 /* the BH worker pools */
473 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
476 /* the per-cpu worker pools */
477 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
480 static DEFINE_IDR(worker_pool_idr); /* PR: idr of all pools */
482 /* PL: hash of all unbound pools keyed by pool->attrs */
483 static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
485 /* I: attributes used when instantiating standard unbound pools on demand */
486 static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
488 /* I: attributes used when instantiating ordered pools on demand */
489 static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
492 * Used to synchronize multiple cancel_sync attempts on the same work item. See
493 * work_grab_pending() and __cancel_work_sync().
495 static DECLARE_WAIT_QUEUE_HEAD(wq_cancel_waitq);
498 * I: kthread_worker to release pwq's. pwq release needs to be bounced to a
499 * process context while holding a pool lock. Bounce to a dedicated kthread
500 * worker to avoid A-A deadlocks.
502 static struct kthread_worker *pwq_release_worker __ro_after_init;
504 struct workqueue_struct *system_wq __ro_after_init;
505 EXPORT_SYMBOL(system_wq);
506 struct workqueue_struct *system_highpri_wq __ro_after_init;
507 EXPORT_SYMBOL_GPL(system_highpri_wq);
508 struct workqueue_struct *system_long_wq __ro_after_init;
509 EXPORT_SYMBOL_GPL(system_long_wq);
510 struct workqueue_struct *system_unbound_wq __ro_after_init;
511 EXPORT_SYMBOL_GPL(system_unbound_wq);
512 struct workqueue_struct *system_freezable_wq __ro_after_init;
513 EXPORT_SYMBOL_GPL(system_freezable_wq);
514 struct workqueue_struct *system_power_efficient_wq __ro_after_init;
515 EXPORT_SYMBOL_GPL(system_power_efficient_wq);
516 struct workqueue_struct *system_freezable_power_efficient_wq __ro_after_init;
517 EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
518 struct workqueue_struct *system_bh_wq;
519 EXPORT_SYMBOL_GPL(system_bh_wq);
520 struct workqueue_struct *system_bh_highpri_wq;
521 EXPORT_SYMBOL_GPL(system_bh_highpri_wq);
523 static int worker_thread(void *__worker);
524 static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
525 static void show_pwq(struct pool_workqueue *pwq);
526 static void show_one_worker_pool(struct worker_pool *pool);
528 #define CREATE_TRACE_POINTS
529 #include <trace/events/workqueue.h>
531 #define assert_rcu_or_pool_mutex() \
532 RCU_LOCKDEP_WARN(!rcu_read_lock_any_held() && \
533 !lockdep_is_held(&wq_pool_mutex), \
534 "RCU or wq_pool_mutex should be held")
536 #define assert_rcu_or_wq_mutex_or_pool_mutex(wq) \
537 RCU_LOCKDEP_WARN(!rcu_read_lock_any_held() && \
538 !lockdep_is_held(&wq->mutex) && \
539 !lockdep_is_held(&wq_pool_mutex), \
540 "RCU, wq->mutex or wq_pool_mutex should be held")
542 #define for_each_bh_worker_pool(pool, cpu) \
543 for ((pool) = &per_cpu(bh_worker_pools, cpu)[0]; \
544 (pool) < &per_cpu(bh_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
547 #define for_each_cpu_worker_pool(pool, cpu) \
548 for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
549 (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
553 * for_each_pool - iterate through all worker_pools in the system
554 * @pool: iteration cursor
555 * @pi: integer used for iteration
557 * This must be called either with wq_pool_mutex held or RCU read
558 * locked. If the pool needs to be used beyond the locking in effect, the
559 * caller is responsible for guaranteeing that the pool stays online.
561 * The if/else clause exists only for the lockdep assertion and can be
564 #define for_each_pool(pool, pi) \
565 idr_for_each_entry(&worker_pool_idr, pool, pi) \
566 if (({ assert_rcu_or_pool_mutex(); false; })) { } \
570 * for_each_pool_worker - iterate through all workers of a worker_pool
571 * @worker: iteration cursor
572 * @pool: worker_pool to iterate workers of
574 * This must be called with wq_pool_attach_mutex.
576 * The if/else clause exists only for the lockdep assertion and can be
579 #define for_each_pool_worker(worker, pool) \
580 list_for_each_entry((worker), &(pool)->workers, node) \
581 if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
585 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
586 * @pwq: iteration cursor
587 * @wq: the target workqueue
589 * This must be called either with wq->mutex held or RCU read locked.
590 * If the pwq needs to be used beyond the locking in effect, the caller is
591 * responsible for guaranteeing that the pwq stays online.
593 * The if/else clause exists only for the lockdep assertion and can be
596 #define for_each_pwq(pwq, wq) \
597 list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node, \
598 lockdep_is_held(&(wq->mutex)))
600 #ifdef CONFIG_DEBUG_OBJECTS_WORK
602 static const struct debug_obj_descr work_debug_descr;
604 static void *work_debug_hint(void *addr)
606 return ((struct work_struct *) addr)->func;
609 static bool work_is_static_object(void *addr)
611 struct work_struct *work = addr;
613 return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
617 * fixup_init is called when:
618 * - an active object is initialized
620 static bool work_fixup_init(void *addr, enum debug_obj_state state)
622 struct work_struct *work = addr;
625 case ODEBUG_STATE_ACTIVE:
626 cancel_work_sync(work);
627 debug_object_init(work, &work_debug_descr);
635 * fixup_free is called when:
636 * - an active object is freed
638 static bool work_fixup_free(void *addr, enum debug_obj_state state)
640 struct work_struct *work = addr;
643 case ODEBUG_STATE_ACTIVE:
644 cancel_work_sync(work);
645 debug_object_free(work, &work_debug_descr);
652 static const struct debug_obj_descr work_debug_descr = {
653 .name = "work_struct",
654 .debug_hint = work_debug_hint,
655 .is_static_object = work_is_static_object,
656 .fixup_init = work_fixup_init,
657 .fixup_free = work_fixup_free,
660 static inline void debug_work_activate(struct work_struct *work)
662 debug_object_activate(work, &work_debug_descr);
665 static inline void debug_work_deactivate(struct work_struct *work)
667 debug_object_deactivate(work, &work_debug_descr);
670 void __init_work(struct work_struct *work, int onstack)
673 debug_object_init_on_stack(work, &work_debug_descr);
675 debug_object_init(work, &work_debug_descr);
677 EXPORT_SYMBOL_GPL(__init_work);
679 void destroy_work_on_stack(struct work_struct *work)
681 debug_object_free(work, &work_debug_descr);
683 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
685 void destroy_delayed_work_on_stack(struct delayed_work *work)
687 destroy_timer_on_stack(&work->timer);
688 debug_object_free(&work->work, &work_debug_descr);
690 EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
693 static inline void debug_work_activate(struct work_struct *work) { }
694 static inline void debug_work_deactivate(struct work_struct *work) { }
698 * worker_pool_assign_id - allocate ID and assign it to @pool
699 * @pool: the pool pointer of interest
701 * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
702 * successfully, -errno on failure.
704 static int worker_pool_assign_id(struct worker_pool *pool)
708 lockdep_assert_held(&wq_pool_mutex);
710 ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
719 static struct pool_workqueue __rcu **
720 unbound_pwq_slot(struct workqueue_struct *wq, int cpu)
723 return per_cpu_ptr(wq->cpu_pwq, cpu);
728 /* @cpu < 0 for dfl_pwq */
729 static struct pool_workqueue *unbound_pwq(struct workqueue_struct *wq, int cpu)
731 return rcu_dereference_check(*unbound_pwq_slot(wq, cpu),
732 lockdep_is_held(&wq_pool_mutex) ||
733 lockdep_is_held(&wq->mutex));
737 * unbound_effective_cpumask - effective cpumask of an unbound workqueue
738 * @wq: workqueue of interest
740 * @wq->unbound_attrs->cpumask contains the cpumask requested by the user which
741 * is masked with wq_unbound_cpumask to determine the effective cpumask. The
742 * default pwq is always mapped to the pool with the current effective cpumask.
744 static struct cpumask *unbound_effective_cpumask(struct workqueue_struct *wq)
746 return unbound_pwq(wq, -1)->pool->attrs->__pod_cpumask;
749 static unsigned int work_color_to_flags(int color)
751 return color << WORK_STRUCT_COLOR_SHIFT;
754 static int get_work_color(unsigned long work_data)
756 return (work_data >> WORK_STRUCT_COLOR_SHIFT) &
757 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
760 static int work_next_color(int color)
762 return (color + 1) % WORK_NR_COLORS;
766 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
767 * contain the pointer to the queued pwq. Once execution starts, the flag
768 * is cleared and the high bits contain OFFQ flags and pool ID.
770 * set_work_pwq(), set_work_pool_and_clear_pending() and mark_work_canceling()
771 * can be used to set the pwq, pool or clear work->data. These functions should
772 * only be called while the work is owned - ie. while the PENDING bit is set.
774 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
775 * corresponding to a work. Pool is available once the work has been
776 * queued anywhere after initialization until it is sync canceled. pwq is
777 * available only while the work item is queued.
779 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
780 * canceled. While being canceled, a work item may have its PENDING set
781 * but stay off timer and worklist for arbitrarily long and nobody should
782 * try to steal the PENDING bit.
784 static inline void set_work_data(struct work_struct *work, unsigned long data)
786 WARN_ON_ONCE(!work_pending(work));
787 atomic_long_set(&work->data, data | work_static(work));
790 static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
793 set_work_data(work, (unsigned long)pwq | WORK_STRUCT_PENDING |
794 WORK_STRUCT_PWQ | flags);
797 static void set_work_pool_and_keep_pending(struct work_struct *work,
798 int pool_id, unsigned long flags)
800 set_work_data(work, ((unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT) |
801 WORK_STRUCT_PENDING | flags);
804 static void set_work_pool_and_clear_pending(struct work_struct *work,
805 int pool_id, unsigned long flags)
808 * The following wmb is paired with the implied mb in
809 * test_and_set_bit(PENDING) and ensures all updates to @work made
810 * here are visible to and precede any updates by the next PENDING
814 set_work_data(work, ((unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT) |
817 * The following mb guarantees that previous clear of a PENDING bit
818 * will not be reordered with any speculative LOADS or STORES from
819 * work->current_func, which is executed afterwards. This possible
820 * reordering can lead to a missed execution on attempt to queue
821 * the same @work. E.g. consider this case:
824 * ---------------------------- --------------------------------
826 * 1 STORE event_indicated
827 * 2 queue_work_on() {
828 * 3 test_and_set_bit(PENDING)
829 * 4 } set_..._and_clear_pending() {
830 * 5 set_work_data() # clear bit
832 * 7 work->current_func() {
833 * 8 LOAD event_indicated
836 * Without an explicit full barrier speculative LOAD on line 8 can
837 * be executed before CPU#0 does STORE on line 1. If that happens,
838 * CPU#0 observes the PENDING bit is still set and new execution of
839 * a @work is not queued in a hope, that CPU#1 will eventually
840 * finish the queued @work. Meanwhile CPU#1 does not see
841 * event_indicated is set, because speculative LOAD was executed
842 * before actual STORE.
847 static inline struct pool_workqueue *work_struct_pwq(unsigned long data)
849 return (struct pool_workqueue *)(data & WORK_STRUCT_PWQ_MASK);
852 static struct pool_workqueue *get_work_pwq(struct work_struct *work)
854 unsigned long data = atomic_long_read(&work->data);
856 if (data & WORK_STRUCT_PWQ)
857 return work_struct_pwq(data);
863 * get_work_pool - return the worker_pool a given work was associated with
864 * @work: the work item of interest
866 * Pools are created and destroyed under wq_pool_mutex, and allows read
867 * access under RCU read lock. As such, this function should be
868 * called under wq_pool_mutex or inside of a rcu_read_lock() region.
870 * All fields of the returned pool are accessible as long as the above
871 * mentioned locking is in effect. If the returned pool needs to be used
872 * beyond the critical section, the caller is responsible for ensuring the
873 * returned pool is and stays online.
875 * Return: The worker_pool @work was last associated with. %NULL if none.
877 static struct worker_pool *get_work_pool(struct work_struct *work)
879 unsigned long data = atomic_long_read(&work->data);
882 assert_rcu_or_pool_mutex();
884 if (data & WORK_STRUCT_PWQ)
885 return work_struct_pwq(data)->pool;
887 pool_id = data >> WORK_OFFQ_POOL_SHIFT;
888 if (pool_id == WORK_OFFQ_POOL_NONE)
891 return idr_find(&worker_pool_idr, pool_id);
895 * get_work_pool_id - return the worker pool ID a given work is associated with
896 * @work: the work item of interest
898 * Return: The worker_pool ID @work was last associated with.
899 * %WORK_OFFQ_POOL_NONE if none.
901 static int get_work_pool_id(struct work_struct *work)
903 unsigned long data = atomic_long_read(&work->data);
905 if (data & WORK_STRUCT_PWQ)
906 return work_struct_pwq(data)->pool->id;
908 return data >> WORK_OFFQ_POOL_SHIFT;
911 static void mark_work_canceling(struct work_struct *work)
913 unsigned long pool_id = get_work_pool_id(work);
915 pool_id <<= WORK_OFFQ_POOL_SHIFT;
916 set_work_data(work, pool_id | WORK_STRUCT_PENDING | WORK_OFFQ_CANCELING);
919 static bool work_is_canceling(struct work_struct *work)
921 unsigned long data = atomic_long_read(&work->data);
923 return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
927 * Policy functions. These define the policies on how the global worker
928 * pools are managed. Unless noted otherwise, these functions assume that
929 * they're being called with pool->lock held.
933 * Need to wake up a worker? Called from anything but currently
936 * Note that, because unbound workers never contribute to nr_running, this
937 * function will always return %true for unbound pools as long as the
938 * worklist isn't empty.
940 static bool need_more_worker(struct worker_pool *pool)
942 return !list_empty(&pool->worklist) && !pool->nr_running;
945 /* Can I start working? Called from busy but !running workers. */
946 static bool may_start_working(struct worker_pool *pool)
948 return pool->nr_idle;
951 /* Do I need to keep working? Called from currently running workers. */
952 static bool keep_working(struct worker_pool *pool)
954 return !list_empty(&pool->worklist) && (pool->nr_running <= 1);
957 /* Do we need a new worker? Called from manager. */
958 static bool need_to_create_worker(struct worker_pool *pool)
960 return need_more_worker(pool) && !may_start_working(pool);
963 /* Do we have too many workers and should some go away? */
964 static bool too_many_workers(struct worker_pool *pool)
966 bool managing = pool->flags & POOL_MANAGER_ACTIVE;
967 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
968 int nr_busy = pool->nr_workers - nr_idle;
970 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
974 * worker_set_flags - set worker flags and adjust nr_running accordingly
976 * @flags: flags to set
978 * Set @flags in @worker->flags and adjust nr_running accordingly.
980 static inline void worker_set_flags(struct worker *worker, unsigned int flags)
982 struct worker_pool *pool = worker->pool;
984 lockdep_assert_held(&pool->lock);
986 /* If transitioning into NOT_RUNNING, adjust nr_running. */
987 if ((flags & WORKER_NOT_RUNNING) &&
988 !(worker->flags & WORKER_NOT_RUNNING)) {
992 worker->flags |= flags;
996 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
998 * @flags: flags to clear
1000 * Clear @flags in @worker->flags and adjust nr_running accordingly.
1002 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
1004 struct worker_pool *pool = worker->pool;
1005 unsigned int oflags = worker->flags;
1007 lockdep_assert_held(&pool->lock);
1009 worker->flags &= ~flags;
1012 * If transitioning out of NOT_RUNNING, increment nr_running. Note
1013 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
1014 * of multiple flags, not a single flag.
1016 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
1017 if (!(worker->flags & WORKER_NOT_RUNNING))
1021 /* Return the first idle worker. Called with pool->lock held. */
1022 static struct worker *first_idle_worker(struct worker_pool *pool)
1024 if (unlikely(list_empty(&pool->idle_list)))
1027 return list_first_entry(&pool->idle_list, struct worker, entry);
1031 * worker_enter_idle - enter idle state
1032 * @worker: worker which is entering idle state
1034 * @worker is entering idle state. Update stats and idle timer if
1038 * raw_spin_lock_irq(pool->lock).
1040 static void worker_enter_idle(struct worker *worker)
1042 struct worker_pool *pool = worker->pool;
1044 if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
1045 WARN_ON_ONCE(!list_empty(&worker->entry) &&
1046 (worker->hentry.next || worker->hentry.pprev)))
1049 /* can't use worker_set_flags(), also called from create_worker() */
1050 worker->flags |= WORKER_IDLE;
1052 worker->last_active = jiffies;
1054 /* idle_list is LIFO */
1055 list_add(&worker->entry, &pool->idle_list);
1057 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1058 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1060 /* Sanity check nr_running. */
1061 WARN_ON_ONCE(pool->nr_workers == pool->nr_idle && pool->nr_running);
1065 * worker_leave_idle - leave idle state
1066 * @worker: worker which is leaving idle state
1068 * @worker is leaving idle state. Update stats.
1071 * raw_spin_lock_irq(pool->lock).
1073 static void worker_leave_idle(struct worker *worker)
1075 struct worker_pool *pool = worker->pool;
1077 if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
1079 worker_clr_flags(worker, WORKER_IDLE);
1081 list_del_init(&worker->entry);
1085 * find_worker_executing_work - find worker which is executing a work
1086 * @pool: pool of interest
1087 * @work: work to find worker for
1089 * Find a worker which is executing @work on @pool by searching
1090 * @pool->busy_hash which is keyed by the address of @work. For a worker
1091 * to match, its current execution should match the address of @work and
1092 * its work function. This is to avoid unwanted dependency between
1093 * unrelated work executions through a work item being recycled while still
1096 * This is a bit tricky. A work item may be freed once its execution
1097 * starts and nothing prevents the freed area from being recycled for
1098 * another work item. If the same work item address ends up being reused
1099 * before the original execution finishes, workqueue will identify the
1100 * recycled work item as currently executing and make it wait until the
1101 * current execution finishes, introducing an unwanted dependency.
1103 * This function checks the work item address and work function to avoid
1104 * false positives. Note that this isn't complete as one may construct a
1105 * work function which can introduce dependency onto itself through a
1106 * recycled work item. Well, if somebody wants to shoot oneself in the
1107 * foot that badly, there's only so much we can do, and if such deadlock
1108 * actually occurs, it should be easy to locate the culprit work function.
1111 * raw_spin_lock_irq(pool->lock).
1114 * Pointer to worker which is executing @work if found, %NULL
1117 static struct worker *find_worker_executing_work(struct worker_pool *pool,
1118 struct work_struct *work)
1120 struct worker *worker;
1122 hash_for_each_possible(pool->busy_hash, worker, hentry,
1123 (unsigned long)work)
1124 if (worker->current_work == work &&
1125 worker->current_func == work->func)
1132 * move_linked_works - move linked works to a list
1133 * @work: start of series of works to be scheduled
1134 * @head: target list to append @work to
1135 * @nextp: out parameter for nested worklist walking
1137 * Schedule linked works starting from @work to @head. Work series to be
1138 * scheduled starts at @work and includes any consecutive work with
1139 * WORK_STRUCT_LINKED set in its predecessor. See assign_work() for details on
1143 * raw_spin_lock_irq(pool->lock).
1145 static void move_linked_works(struct work_struct *work, struct list_head *head,
1146 struct work_struct **nextp)
1148 struct work_struct *n;
1151 * Linked worklist will always end before the end of the list,
1152 * use NULL for list head.
1154 list_for_each_entry_safe_from(work, n, NULL, entry) {
1155 list_move_tail(&work->entry, head);
1156 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1161 * If we're already inside safe list traversal and have moved
1162 * multiple works to the scheduled queue, the next position
1163 * needs to be updated.
1170 * assign_work - assign a work item and its linked work items to a worker
1171 * @work: work to assign
1172 * @worker: worker to assign to
1173 * @nextp: out parameter for nested worklist walking
1175 * Assign @work and its linked work items to @worker. If @work is already being
1176 * executed by another worker in the same pool, it'll be punted there.
1178 * If @nextp is not NULL, it's updated to point to the next work of the last
1179 * scheduled work. This allows assign_work() to be nested inside
1180 * list_for_each_entry_safe().
1182 * Returns %true if @work was successfully assigned to @worker. %false if @work
1183 * was punted to another worker already executing it.
1185 static bool assign_work(struct work_struct *work, struct worker *worker,
1186 struct work_struct **nextp)
1188 struct worker_pool *pool = worker->pool;
1189 struct worker *collision;
1191 lockdep_assert_held(&pool->lock);
1194 * A single work shouldn't be executed concurrently by multiple workers.
1195 * __queue_work() ensures that @work doesn't jump to a different pool
1196 * while still running in the previous pool. Here, we should ensure that
1197 * @work is not executed concurrently by multiple workers from the same
1198 * pool. Check whether anyone is already processing the work. If so,
1199 * defer the work to the currently executing one.
1201 collision = find_worker_executing_work(pool, work);
1202 if (unlikely(collision)) {
1203 move_linked_works(work, &collision->scheduled, nextp);
1207 move_linked_works(work, &worker->scheduled, nextp);
1211 static struct irq_work *bh_pool_irq_work(struct worker_pool *pool)
1213 int high = pool->attrs->nice == HIGHPRI_NICE_LEVEL ? 1 : 0;
1215 return &per_cpu(bh_pool_irq_works, pool->cpu)[high];
1218 static void kick_bh_pool(struct worker_pool *pool)
1221 if (unlikely(pool->cpu != smp_processor_id())) {
1222 irq_work_queue_on(bh_pool_irq_work(pool), pool->cpu);
1226 if (pool->attrs->nice == HIGHPRI_NICE_LEVEL)
1227 raise_softirq_irqoff(HI_SOFTIRQ);
1229 raise_softirq_irqoff(TASKLET_SOFTIRQ);
1233 * kick_pool - wake up an idle worker if necessary
1234 * @pool: pool to kick
1236 * @pool may have pending work items. Wake up worker if necessary. Returns
1237 * whether a worker was woken up.
1239 static bool kick_pool(struct worker_pool *pool)
1241 struct worker *worker = first_idle_worker(pool);
1242 struct task_struct *p;
1244 lockdep_assert_held(&pool->lock);
1246 if (!need_more_worker(pool) || !worker)
1249 if (pool->flags & POOL_BH) {
1258 * Idle @worker is about to execute @work and waking up provides an
1259 * opportunity to migrate @worker at a lower cost by setting the task's
1260 * wake_cpu field. Let's see if we want to move @worker to improve
1261 * execution locality.
1263 * We're waking the worker that went idle the latest and there's some
1264 * chance that @worker is marked idle but hasn't gone off CPU yet. If
1265 * so, setting the wake_cpu won't do anything. As this is a best-effort
1266 * optimization and the race window is narrow, let's leave as-is for
1267 * now. If this becomes pronounced, we can skip over workers which are
1268 * still on cpu when picking an idle worker.
1270 * If @pool has non-strict affinity, @worker might have ended up outside
1271 * its affinity scope. Repatriate.
1273 if (!pool->attrs->affn_strict &&
1274 !cpumask_test_cpu(p->wake_cpu, pool->attrs->__pod_cpumask)) {
1275 struct work_struct *work = list_first_entry(&pool->worklist,
1276 struct work_struct, entry);
1277 p->wake_cpu = cpumask_any_distribute(pool->attrs->__pod_cpumask);
1278 get_work_pwq(work)->stats[PWQ_STAT_REPATRIATED]++;
1285 #ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
1288 * Concurrency-managed per-cpu work items that hog CPU for longer than
1289 * wq_cpu_intensive_thresh_us trigger the automatic CPU_INTENSIVE mechanism,
1290 * which prevents them from stalling other concurrency-managed work items. If a
1291 * work function keeps triggering this mechanism, it's likely that the work item
1292 * should be using an unbound workqueue instead.
1294 * wq_cpu_intensive_report() tracks work functions which trigger such conditions
1295 * and report them so that they can be examined and converted to use unbound
1296 * workqueues as appropriate. To avoid flooding the console, each violating work
1297 * function is tracked and reported with exponential backoff.
1299 #define WCI_MAX_ENTS 128
1304 struct hlist_node hash_node;
1307 static struct wci_ent wci_ents[WCI_MAX_ENTS];
1308 static int wci_nr_ents;
1309 static DEFINE_RAW_SPINLOCK(wci_lock);
1310 static DEFINE_HASHTABLE(wci_hash, ilog2(WCI_MAX_ENTS));
1312 static struct wci_ent *wci_find_ent(work_func_t func)
1314 struct wci_ent *ent;
1316 hash_for_each_possible_rcu(wci_hash, ent, hash_node,
1317 (unsigned long)func) {
1318 if (ent->func == func)
1324 static void wq_cpu_intensive_report(work_func_t func)
1326 struct wci_ent *ent;
1329 ent = wci_find_ent(func);
1334 * Start reporting from the warning_thresh and back off
1337 cnt = atomic64_inc_return_relaxed(&ent->cnt);
1338 if (wq_cpu_intensive_warning_thresh &&
1339 cnt >= wq_cpu_intensive_warning_thresh &&
1340 is_power_of_2(cnt + 1 - wq_cpu_intensive_warning_thresh))
1341 printk_deferred(KERN_WARNING "workqueue: %ps hogged CPU for >%luus %llu times, consider switching to WQ_UNBOUND\n",
1342 ent->func, wq_cpu_intensive_thresh_us,
1343 atomic64_read(&ent->cnt));
1348 * @func is a new violation. Allocate a new entry for it. If wcn_ents[]
1349 * is exhausted, something went really wrong and we probably made enough
1352 if (wci_nr_ents >= WCI_MAX_ENTS)
1355 raw_spin_lock(&wci_lock);
1357 if (wci_nr_ents >= WCI_MAX_ENTS) {
1358 raw_spin_unlock(&wci_lock);
1362 if (wci_find_ent(func)) {
1363 raw_spin_unlock(&wci_lock);
1367 ent = &wci_ents[wci_nr_ents++];
1369 atomic64_set(&ent->cnt, 0);
1370 hash_add_rcu(wci_hash, &ent->hash_node, (unsigned long)func);
1372 raw_spin_unlock(&wci_lock);
1377 #else /* CONFIG_WQ_CPU_INTENSIVE_REPORT */
1378 static void wq_cpu_intensive_report(work_func_t func) {}
1379 #endif /* CONFIG_WQ_CPU_INTENSIVE_REPORT */
1382 * wq_worker_running - a worker is running again
1383 * @task: task waking up
1385 * This function is called when a worker returns from schedule()
1387 void wq_worker_running(struct task_struct *task)
1389 struct worker *worker = kthread_data(task);
1391 if (!READ_ONCE(worker->sleeping))
1395 * If preempted by unbind_workers() between the WORKER_NOT_RUNNING check
1396 * and the nr_running increment below, we may ruin the nr_running reset
1397 * and leave with an unexpected pool->nr_running == 1 on the newly unbound
1398 * pool. Protect against such race.
1401 if (!(worker->flags & WORKER_NOT_RUNNING))
1402 worker->pool->nr_running++;
1406 * CPU intensive auto-detection cares about how long a work item hogged
1407 * CPU without sleeping. Reset the starting timestamp on wakeup.
1409 worker->current_at = worker->task->se.sum_exec_runtime;
1411 WRITE_ONCE(worker->sleeping, 0);
1415 * wq_worker_sleeping - a worker is going to sleep
1416 * @task: task going to sleep
1418 * This function is called from schedule() when a busy worker is
1421 void wq_worker_sleeping(struct task_struct *task)
1423 struct worker *worker = kthread_data(task);
1424 struct worker_pool *pool;
1427 * Rescuers, which may not have all the fields set up like normal
1428 * workers, also reach here, let's not access anything before
1429 * checking NOT_RUNNING.
1431 if (worker->flags & WORKER_NOT_RUNNING)
1434 pool = worker->pool;
1436 /* Return if preempted before wq_worker_running() was reached */
1437 if (READ_ONCE(worker->sleeping))
1440 WRITE_ONCE(worker->sleeping, 1);
1441 raw_spin_lock_irq(&pool->lock);
1444 * Recheck in case unbind_workers() preempted us. We don't
1445 * want to decrement nr_running after the worker is unbound
1446 * and nr_running has been reset.
1448 if (worker->flags & WORKER_NOT_RUNNING) {
1449 raw_spin_unlock_irq(&pool->lock);
1454 if (kick_pool(pool))
1455 worker->current_pwq->stats[PWQ_STAT_CM_WAKEUP]++;
1457 raw_spin_unlock_irq(&pool->lock);
1461 * wq_worker_tick - a scheduler tick occurred while a kworker is running
1462 * @task: task currently running
1464 * Called from scheduler_tick(). We're in the IRQ context and the current
1465 * worker's fields which follow the 'K' locking rule can be accessed safely.
1467 void wq_worker_tick(struct task_struct *task)
1469 struct worker *worker = kthread_data(task);
1470 struct pool_workqueue *pwq = worker->current_pwq;
1471 struct worker_pool *pool = worker->pool;
1476 pwq->stats[PWQ_STAT_CPU_TIME] += TICK_USEC;
1478 if (!wq_cpu_intensive_thresh_us)
1482 * If the current worker is concurrency managed and hogged the CPU for
1483 * longer than wq_cpu_intensive_thresh_us, it's automatically marked
1484 * CPU_INTENSIVE to avoid stalling other concurrency-managed work items.
1486 * Set @worker->sleeping means that @worker is in the process of
1487 * switching out voluntarily and won't be contributing to
1488 * @pool->nr_running until it wakes up. As wq_worker_sleeping() also
1489 * decrements ->nr_running, setting CPU_INTENSIVE here can lead to
1490 * double decrements. The task is releasing the CPU anyway. Let's skip.
1491 * We probably want to make this prettier in the future.
1493 if ((worker->flags & WORKER_NOT_RUNNING) || READ_ONCE(worker->sleeping) ||
1494 worker->task->se.sum_exec_runtime - worker->current_at <
1495 wq_cpu_intensive_thresh_us * NSEC_PER_USEC)
1498 raw_spin_lock(&pool->lock);
1500 worker_set_flags(worker, WORKER_CPU_INTENSIVE);
1501 wq_cpu_intensive_report(worker->current_func);
1502 pwq->stats[PWQ_STAT_CPU_INTENSIVE]++;
1504 if (kick_pool(pool))
1505 pwq->stats[PWQ_STAT_CM_WAKEUP]++;
1507 raw_spin_unlock(&pool->lock);
1511 * wq_worker_last_func - retrieve worker's last work function
1512 * @task: Task to retrieve last work function of.
1514 * Determine the last function a worker executed. This is called from
1515 * the scheduler to get a worker's last known identity.
1518 * raw_spin_lock_irq(rq->lock)
1520 * This function is called during schedule() when a kworker is going
1521 * to sleep. It's used by psi to identify aggregation workers during
1522 * dequeuing, to allow periodic aggregation to shut-off when that
1523 * worker is the last task in the system or cgroup to go to sleep.
1525 * As this function doesn't involve any workqueue-related locking, it
1526 * only returns stable values when called from inside the scheduler's
1527 * queuing and dequeuing paths, when @task, which must be a kworker,
1528 * is guaranteed to not be processing any works.
1531 * The last work function %current executed as a worker, NULL if it
1532 * hasn't executed any work yet.
1534 work_func_t wq_worker_last_func(struct task_struct *task)
1536 struct worker *worker = kthread_data(task);
1538 return worker->last_func;
1542 * wq_node_nr_active - Determine wq_node_nr_active to use
1543 * @wq: workqueue of interest
1544 * @node: NUMA node, can be %NUMA_NO_NODE
1546 * Determine wq_node_nr_active to use for @wq on @node. Returns:
1548 * - %NULL for per-cpu workqueues as they don't need to use shared nr_active.
1550 * - node_nr_active[nr_node_ids] if @node is %NUMA_NO_NODE.
1552 * - Otherwise, node_nr_active[@node].
1554 static struct wq_node_nr_active *wq_node_nr_active(struct workqueue_struct *wq,
1557 if (!(wq->flags & WQ_UNBOUND))
1560 if (node == NUMA_NO_NODE)
1563 return wq->node_nr_active[node];
1567 * wq_update_node_max_active - Update per-node max_actives to use
1568 * @wq: workqueue to update
1569 * @off_cpu: CPU that's going down, -1 if a CPU is not going down
1571 * Update @wq->node_nr_active[]->max. @wq must be unbound. max_active is
1572 * distributed among nodes according to the proportions of numbers of online
1573 * cpus. The result is always between @wq->min_active and max_active.
1575 static void wq_update_node_max_active(struct workqueue_struct *wq, int off_cpu)
1577 struct cpumask *effective = unbound_effective_cpumask(wq);
1578 int min_active = READ_ONCE(wq->min_active);
1579 int max_active = READ_ONCE(wq->max_active);
1580 int total_cpus, node;
1582 lockdep_assert_held(&wq->mutex);
1584 if (!wq_topo_initialized)
1587 if (off_cpu >= 0 && !cpumask_test_cpu(off_cpu, effective))
1590 total_cpus = cpumask_weight_and(effective, cpu_online_mask);
1594 for_each_node(node) {
1597 node_cpus = cpumask_weight_and(effective, cpumask_of_node(node));
1598 if (off_cpu >= 0 && cpu_to_node(off_cpu) == node)
1601 wq_node_nr_active(wq, node)->max =
1602 clamp(DIV_ROUND_UP(max_active * node_cpus, total_cpus),
1603 min_active, max_active);
1606 wq_node_nr_active(wq, NUMA_NO_NODE)->max = min_active;
1610 * get_pwq - get an extra reference on the specified pool_workqueue
1611 * @pwq: pool_workqueue to get
1613 * Obtain an extra reference on @pwq. The caller should guarantee that
1614 * @pwq has positive refcnt and be holding the matching pool->lock.
1616 static void get_pwq(struct pool_workqueue *pwq)
1618 lockdep_assert_held(&pwq->pool->lock);
1619 WARN_ON_ONCE(pwq->refcnt <= 0);
1624 * put_pwq - put a pool_workqueue reference
1625 * @pwq: pool_workqueue to put
1627 * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
1628 * destruction. The caller should be holding the matching pool->lock.
1630 static void put_pwq(struct pool_workqueue *pwq)
1632 lockdep_assert_held(&pwq->pool->lock);
1633 if (likely(--pwq->refcnt))
1636 * @pwq can't be released under pool->lock, bounce to a dedicated
1637 * kthread_worker to avoid A-A deadlocks.
1639 kthread_queue_work(pwq_release_worker, &pwq->release_work);
1643 * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1644 * @pwq: pool_workqueue to put (can be %NULL)
1646 * put_pwq() with locking. This function also allows %NULL @pwq.
1648 static void put_pwq_unlocked(struct pool_workqueue *pwq)
1652 * As both pwqs and pools are RCU protected, the
1653 * following lock operations are safe.
1655 raw_spin_lock_irq(&pwq->pool->lock);
1657 raw_spin_unlock_irq(&pwq->pool->lock);
1661 static bool pwq_is_empty(struct pool_workqueue *pwq)
1663 return !pwq->nr_active && list_empty(&pwq->inactive_works);
1666 static void __pwq_activate_work(struct pool_workqueue *pwq,
1667 struct work_struct *work)
1669 unsigned long *wdb = work_data_bits(work);
1671 WARN_ON_ONCE(!(*wdb & WORK_STRUCT_INACTIVE));
1672 trace_workqueue_activate_work(work);
1673 if (list_empty(&pwq->pool->worklist))
1674 pwq->pool->watchdog_ts = jiffies;
1675 move_linked_works(work, &pwq->pool->worklist, NULL);
1676 __clear_bit(WORK_STRUCT_INACTIVE_BIT, wdb);
1680 * pwq_activate_work - Activate a work item if inactive
1681 * @pwq: pool_workqueue @work belongs to
1682 * @work: work item to activate
1684 * Returns %true if activated. %false if already active.
1686 static bool pwq_activate_work(struct pool_workqueue *pwq,
1687 struct work_struct *work)
1689 struct worker_pool *pool = pwq->pool;
1690 struct wq_node_nr_active *nna;
1692 lockdep_assert_held(&pool->lock);
1694 if (!(*work_data_bits(work) & WORK_STRUCT_INACTIVE))
1697 nna = wq_node_nr_active(pwq->wq, pool->node);
1699 atomic_inc(&nna->nr);
1702 __pwq_activate_work(pwq, work);
1706 static bool tryinc_node_nr_active(struct wq_node_nr_active *nna)
1708 int max = READ_ONCE(nna->max);
1713 old = atomic_read(&nna->nr);
1716 tmp = atomic_cmpxchg_relaxed(&nna->nr, old, old + 1);
1723 * pwq_tryinc_nr_active - Try to increment nr_active for a pwq
1724 * @pwq: pool_workqueue of interest
1725 * @fill: max_active may have increased, try to increase concurrency level
1727 * Try to increment nr_active for @pwq. Returns %true if an nr_active count is
1728 * successfully obtained. %false otherwise.
1730 static bool pwq_tryinc_nr_active(struct pool_workqueue *pwq, bool fill)
1732 struct workqueue_struct *wq = pwq->wq;
1733 struct worker_pool *pool = pwq->pool;
1734 struct wq_node_nr_active *nna = wq_node_nr_active(wq, pool->node);
1735 bool obtained = false;
1737 lockdep_assert_held(&pool->lock);
1740 /* BH or per-cpu workqueue, pwq->nr_active is sufficient */
1741 obtained = pwq->nr_active < READ_ONCE(wq->max_active);
1745 if (unlikely(pwq->plugged))
1749 * Unbound workqueue uses per-node shared nr_active $nna. If @pwq is
1750 * already waiting on $nna, pwq_dec_nr_active() will maintain the
1751 * concurrency level. Don't jump the line.
1753 * We need to ignore the pending test after max_active has increased as
1754 * pwq_dec_nr_active() can only maintain the concurrency level but not
1755 * increase it. This is indicated by @fill.
1757 if (!list_empty(&pwq->pending_node) && likely(!fill))
1760 obtained = tryinc_node_nr_active(nna);
1765 * Lockless acquisition failed. Lock, add ourself to $nna->pending_pwqs
1766 * and try again. The smp_mb() is paired with the implied memory barrier
1767 * of atomic_dec_return() in pwq_dec_nr_active() to ensure that either
1768 * we see the decremented $nna->nr or they see non-empty
1769 * $nna->pending_pwqs.
1771 raw_spin_lock(&nna->lock);
1773 if (list_empty(&pwq->pending_node))
1774 list_add_tail(&pwq->pending_node, &nna->pending_pwqs);
1775 else if (likely(!fill))
1780 obtained = tryinc_node_nr_active(nna);
1783 * If @fill, @pwq might have already been pending. Being spuriously
1784 * pending in cold paths doesn't affect anything. Let's leave it be.
1786 if (obtained && likely(!fill))
1787 list_del_init(&pwq->pending_node);
1790 raw_spin_unlock(&nna->lock);
1798 * pwq_activate_first_inactive - Activate the first inactive work item on a pwq
1799 * @pwq: pool_workqueue of interest
1800 * @fill: max_active may have increased, try to increase concurrency level
1802 * Activate the first inactive work item of @pwq if available and allowed by
1805 * Returns %true if an inactive work item has been activated. %false if no
1806 * inactive work item is found or max_active limit is reached.
1808 static bool pwq_activate_first_inactive(struct pool_workqueue *pwq, bool fill)
1810 struct work_struct *work =
1811 list_first_entry_or_null(&pwq->inactive_works,
1812 struct work_struct, entry);
1814 if (work && pwq_tryinc_nr_active(pwq, fill)) {
1815 __pwq_activate_work(pwq, work);
1823 * unplug_oldest_pwq - unplug the oldest pool_workqueue
1824 * @wq: workqueue_struct where its oldest pwq is to be unplugged
1826 * This function should only be called for ordered workqueues where only the
1827 * oldest pwq is unplugged, the others are plugged to suspend execution to
1828 * ensure proper work item ordering::
1830 * dfl_pwq --------------+ [P] - plugged
1833 * pwqs -> A -> B [P] -> C [P] (newest)
1839 * When the oldest pwq is drained and removed, this function should be called
1840 * to unplug the next oldest one to start its work item execution. Note that
1841 * pwq's are linked into wq->pwqs with the oldest first, so the first one in
1842 * the list is the oldest.
1844 static void unplug_oldest_pwq(struct workqueue_struct *wq)
1846 struct pool_workqueue *pwq;
1848 lockdep_assert_held(&wq->mutex);
1850 /* Caller should make sure that pwqs isn't empty before calling */
1851 pwq = list_first_entry_or_null(&wq->pwqs, struct pool_workqueue,
1853 raw_spin_lock_irq(&pwq->pool->lock);
1855 pwq->plugged = false;
1856 if (pwq_activate_first_inactive(pwq, true))
1857 kick_pool(pwq->pool);
1859 raw_spin_unlock_irq(&pwq->pool->lock);
1863 * node_activate_pending_pwq - Activate a pending pwq on a wq_node_nr_active
1864 * @nna: wq_node_nr_active to activate a pending pwq for
1865 * @caller_pool: worker_pool the caller is locking
1867 * Activate a pwq in @nna->pending_pwqs. Called with @caller_pool locked.
1868 * @caller_pool may be unlocked and relocked to lock other worker_pools.
1870 static void node_activate_pending_pwq(struct wq_node_nr_active *nna,
1871 struct worker_pool *caller_pool)
1873 struct worker_pool *locked_pool = caller_pool;
1874 struct pool_workqueue *pwq;
1875 struct work_struct *work;
1877 lockdep_assert_held(&caller_pool->lock);
1879 raw_spin_lock(&nna->lock);
1881 pwq = list_first_entry_or_null(&nna->pending_pwqs,
1882 struct pool_workqueue, pending_node);
1887 * If @pwq is for a different pool than @locked_pool, we need to lock
1888 * @pwq->pool->lock. Let's trylock first. If unsuccessful, do the unlock
1889 * / lock dance. For that, we also need to release @nna->lock as it's
1890 * nested inside pool locks.
1892 if (pwq->pool != locked_pool) {
1893 raw_spin_unlock(&locked_pool->lock);
1894 locked_pool = pwq->pool;
1895 if (!raw_spin_trylock(&locked_pool->lock)) {
1896 raw_spin_unlock(&nna->lock);
1897 raw_spin_lock(&locked_pool->lock);
1898 raw_spin_lock(&nna->lock);
1904 * $pwq may not have any inactive work items due to e.g. cancellations.
1905 * Drop it from pending_pwqs and see if there's another one.
1907 work = list_first_entry_or_null(&pwq->inactive_works,
1908 struct work_struct, entry);
1910 list_del_init(&pwq->pending_node);
1915 * Acquire an nr_active count and activate the inactive work item. If
1916 * $pwq still has inactive work items, rotate it to the end of the
1917 * pending_pwqs so that we round-robin through them. This means that
1918 * inactive work items are not activated in queueing order which is fine
1919 * given that there has never been any ordering across different pwqs.
1921 if (likely(tryinc_node_nr_active(nna))) {
1923 __pwq_activate_work(pwq, work);
1925 if (list_empty(&pwq->inactive_works))
1926 list_del_init(&pwq->pending_node);
1928 list_move_tail(&pwq->pending_node, &nna->pending_pwqs);
1930 /* if activating a foreign pool, make sure it's running */
1931 if (pwq->pool != caller_pool)
1932 kick_pool(pwq->pool);
1936 raw_spin_unlock(&nna->lock);
1937 if (locked_pool != caller_pool) {
1938 raw_spin_unlock(&locked_pool->lock);
1939 raw_spin_lock(&caller_pool->lock);
1944 * pwq_dec_nr_active - Retire an active count
1945 * @pwq: pool_workqueue of interest
1947 * Decrement @pwq's nr_active and try to activate the first inactive work item.
1948 * For unbound workqueues, this function may temporarily drop @pwq->pool->lock.
1950 static void pwq_dec_nr_active(struct pool_workqueue *pwq)
1952 struct worker_pool *pool = pwq->pool;
1953 struct wq_node_nr_active *nna = wq_node_nr_active(pwq->wq, pool->node);
1955 lockdep_assert_held(&pool->lock);
1958 * @pwq->nr_active should be decremented for both percpu and unbound
1964 * For a percpu workqueue, it's simple. Just need to kick the first
1965 * inactive work item on @pwq itself.
1968 pwq_activate_first_inactive(pwq, false);
1973 * If @pwq is for an unbound workqueue, it's more complicated because
1974 * multiple pwqs and pools may be sharing the nr_active count. When a
1975 * pwq needs to wait for an nr_active count, it puts itself on
1976 * $nna->pending_pwqs. The following atomic_dec_return()'s implied
1977 * memory barrier is paired with smp_mb() in pwq_tryinc_nr_active() to
1978 * guarantee that either we see non-empty pending_pwqs or they see
1979 * decremented $nna->nr.
1981 * $nna->max may change as CPUs come online/offline and @pwq->wq's
1982 * max_active gets updated. However, it is guaranteed to be equal to or
1983 * larger than @pwq->wq->min_active which is above zero unless freezing.
1984 * This maintains the forward progress guarantee.
1986 if (atomic_dec_return(&nna->nr) >= READ_ONCE(nna->max))
1989 if (!list_empty(&nna->pending_pwqs))
1990 node_activate_pending_pwq(nna, pool);
1994 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1995 * @pwq: pwq of interest
1996 * @work_data: work_data of work which left the queue
1998 * A work either has completed or is removed from pending queue,
1999 * decrement nr_in_flight of its pwq and handle workqueue flushing.
2002 * For unbound workqueues, this function may temporarily drop @pwq->pool->lock
2003 * and thus should be called after all other state updates for the in-flight
2004 * work item is complete.
2007 * raw_spin_lock_irq(pool->lock).
2009 static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data)
2011 int color = get_work_color(work_data);
2013 if (!(work_data & WORK_STRUCT_INACTIVE))
2014 pwq_dec_nr_active(pwq);
2016 pwq->nr_in_flight[color]--;
2018 /* is flush in progress and are we at the flushing tip? */
2019 if (likely(pwq->flush_color != color))
2022 /* are there still in-flight works? */
2023 if (pwq->nr_in_flight[color])
2026 /* this pwq is done, clear flush_color */
2027 pwq->flush_color = -1;
2030 * If this was the last pwq, wake up the first flusher. It
2031 * will handle the rest.
2033 if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
2034 complete(&pwq->wq->first_flusher->done);
2040 * try_to_grab_pending - steal work item from worklist and disable irq
2041 * @work: work item to steal
2042 * @cflags: %WORK_CANCEL_ flags
2043 * @irq_flags: place to store irq state
2045 * Try to grab PENDING bit of @work. This function can handle @work in any
2046 * stable state - idle, on timer or on worklist.
2050 * ======== ================================================================
2051 * 1 if @work was pending and we successfully stole PENDING
2052 * 0 if @work was idle and we claimed PENDING
2053 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
2054 * -ENOENT if someone else is canceling @work, this state may persist
2055 * for arbitrarily long
2056 * ======== ================================================================
2059 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
2060 * interrupted while holding PENDING and @work off queue, irq must be
2061 * disabled on entry. This, combined with delayed_work->timer being
2062 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
2064 * On successful return, >= 0, irq is disabled and the caller is
2065 * responsible for releasing it using local_irq_restore(*@irq_flags).
2067 * This function is safe to call from any context including IRQ handler.
2069 static int try_to_grab_pending(struct work_struct *work, u32 cflags,
2070 unsigned long *irq_flags)
2072 struct worker_pool *pool;
2073 struct pool_workqueue *pwq;
2075 local_irq_save(*irq_flags);
2077 /* try to steal the timer if it exists */
2078 if (cflags & WORK_CANCEL_DELAYED) {
2079 struct delayed_work *dwork = to_delayed_work(work);
2082 * dwork->timer is irqsafe. If del_timer() fails, it's
2083 * guaranteed that the timer is not queued anywhere and not
2084 * running on the local CPU.
2086 if (likely(del_timer(&dwork->timer)))
2090 /* try to claim PENDING the normal way */
2091 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
2096 * The queueing is in progress, or it is already queued. Try to
2097 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
2099 pool = get_work_pool(work);
2103 raw_spin_lock(&pool->lock);
2105 * work->data is guaranteed to point to pwq only while the work
2106 * item is queued on pwq->wq, and both updating work->data to point
2107 * to pwq on queueing and to pool on dequeueing are done under
2108 * pwq->pool->lock. This in turn guarantees that, if work->data
2109 * points to pwq which is associated with a locked pool, the work
2110 * item is currently queued on that pool.
2112 pwq = get_work_pwq(work);
2113 if (pwq && pwq->pool == pool) {
2114 unsigned long work_data;
2116 debug_work_deactivate(work);
2119 * A cancelable inactive work item must be in the
2120 * pwq->inactive_works since a queued barrier can't be
2121 * canceled (see the comments in insert_wq_barrier()).
2123 * An inactive work item cannot be grabbed directly because
2124 * it might have linked barrier work items which, if left
2125 * on the inactive_works list, will confuse pwq->nr_active
2126 * management later on and cause stall. Make sure the work
2127 * item is activated before grabbing.
2129 pwq_activate_work(pwq, work);
2131 list_del_init(&work->entry);
2134 * work->data points to pwq iff queued. Let's point to pool. As
2135 * this destroys work->data needed by the next step, stash it.
2137 work_data = *work_data_bits(work);
2138 set_work_pool_and_keep_pending(work, pool->id, 0);
2140 /* must be the last step, see the function comment */
2141 pwq_dec_nr_in_flight(pwq, work_data);
2143 raw_spin_unlock(&pool->lock);
2147 raw_spin_unlock(&pool->lock);
2150 local_irq_restore(*irq_flags);
2151 if (work_is_canceling(work))
2158 wait_queue_entry_t wait;
2159 struct work_struct *work;
2162 static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
2164 struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
2166 if (cwait->work != key)
2168 return autoremove_wake_function(wait, mode, sync, key);
2172 * work_grab_pending - steal work item from worklist and disable irq
2173 * @work: work item to steal
2174 * @cflags: %WORK_CANCEL_ flags
2175 * @irq_flags: place to store IRQ state
2177 * Grab PENDING bit of @work. @work can be in any stable state - idle, on timer
2180 * Must be called in process context. IRQ is disabled on return with IRQ state
2181 * stored in *@irq_flags. The caller is responsible for re-enabling it using
2182 * local_irq_restore().
2184 * Returns %true if @work was pending. %false if idle.
2186 static bool work_grab_pending(struct work_struct *work, u32 cflags,
2187 unsigned long *irq_flags)
2189 struct cwt_wait cwait;
2194 ret = try_to_grab_pending(work, cflags, irq_flags);
2195 if (likely(ret >= 0))
2201 * Someone is already canceling. Wait for it to finish. flush_work()
2202 * doesn't work for PREEMPT_NONE because we may get woken up between
2203 * @work's completion and the other canceling task resuming and clearing
2204 * CANCELING - flush_work() will return false immediately as @work is no
2205 * longer busy, try_to_grab_pending() will return -ENOENT as @work is
2206 * still being canceled and the other canceling task won't be able to
2207 * clear CANCELING as we're hogging the CPU.
2209 * Let's wait for completion using a waitqueue. As this may lead to the
2210 * thundering herd problem, use a custom wake function which matches
2211 * @work along with exclusive wait and wakeup.
2213 init_wait(&cwait.wait);
2214 cwait.wait.func = cwt_wakefn;
2217 prepare_to_wait_exclusive(&wq_cancel_waitq, &cwait.wait,
2218 TASK_UNINTERRUPTIBLE);
2219 if (work_is_canceling(work))
2221 finish_wait(&wq_cancel_waitq, &cwait.wait);
2227 * insert_work - insert a work into a pool
2228 * @pwq: pwq @work belongs to
2229 * @work: work to insert
2230 * @head: insertion point
2231 * @extra_flags: extra WORK_STRUCT_* flags to set
2233 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
2234 * work_struct flags.
2237 * raw_spin_lock_irq(pool->lock).
2239 static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
2240 struct list_head *head, unsigned int extra_flags)
2242 debug_work_activate(work);
2244 /* record the work call stack in order to print it in KASAN reports */
2245 kasan_record_aux_stack_noalloc(work);
2247 /* we own @work, set data and link */
2248 set_work_pwq(work, pwq, extra_flags);
2249 list_add_tail(&work->entry, head);
2254 * Test whether @work is being queued from another work executing on the
2257 static bool is_chained_work(struct workqueue_struct *wq)
2259 struct worker *worker;
2261 worker = current_wq_worker();
2263 * Return %true iff I'm a worker executing a work item on @wq. If
2264 * I'm @worker, it's safe to dereference it without locking.
2266 return worker && worker->current_pwq->wq == wq;
2270 * When queueing an unbound work item to a wq, prefer local CPU if allowed
2271 * by wq_unbound_cpumask. Otherwise, round robin among the allowed ones to
2272 * avoid perturbing sensitive tasks.
2274 static int wq_select_unbound_cpu(int cpu)
2278 if (likely(!wq_debug_force_rr_cpu)) {
2279 if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
2282 pr_warn_once("workqueue: round-robin CPU selection forced, expect performance impact\n");
2285 new_cpu = __this_cpu_read(wq_rr_cpu_last);
2286 new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
2287 if (unlikely(new_cpu >= nr_cpu_ids)) {
2288 new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
2289 if (unlikely(new_cpu >= nr_cpu_ids))
2292 __this_cpu_write(wq_rr_cpu_last, new_cpu);
2297 static void __queue_work(int cpu, struct workqueue_struct *wq,
2298 struct work_struct *work)
2300 struct pool_workqueue *pwq;
2301 struct worker_pool *last_pool, *pool;
2302 unsigned int work_flags;
2303 unsigned int req_cpu = cpu;
2306 * While a work item is PENDING && off queue, a task trying to
2307 * steal the PENDING will busy-loop waiting for it to either get
2308 * queued or lose PENDING. Grabbing PENDING and queueing should
2309 * happen with IRQ disabled.
2311 lockdep_assert_irqs_disabled();
2314 * For a draining wq, only works from the same workqueue are
2315 * allowed. The __WQ_DESTROYING helps to spot the issue that
2316 * queues a new work item to a wq after destroy_workqueue(wq).
2318 if (unlikely(wq->flags & (__WQ_DESTROYING | __WQ_DRAINING) &&
2319 WARN_ON_ONCE(!is_chained_work(wq))))
2323 /* pwq which will be used unless @work is executing elsewhere */
2324 if (req_cpu == WORK_CPU_UNBOUND) {
2325 if (wq->flags & WQ_UNBOUND)
2326 cpu = wq_select_unbound_cpu(raw_smp_processor_id());
2328 cpu = raw_smp_processor_id();
2331 pwq = rcu_dereference(*per_cpu_ptr(wq->cpu_pwq, cpu));
2335 * If @work was previously on a different pool, it might still be
2336 * running there, in which case the work needs to be queued on that
2337 * pool to guarantee non-reentrancy.
2339 last_pool = get_work_pool(work);
2340 if (last_pool && last_pool != pool) {
2341 struct worker *worker;
2343 raw_spin_lock(&last_pool->lock);
2345 worker = find_worker_executing_work(last_pool, work);
2347 if (worker && worker->current_pwq->wq == wq) {
2348 pwq = worker->current_pwq;
2350 WARN_ON_ONCE(pool != last_pool);
2352 /* meh... not running there, queue here */
2353 raw_spin_unlock(&last_pool->lock);
2354 raw_spin_lock(&pool->lock);
2357 raw_spin_lock(&pool->lock);
2361 * pwq is determined and locked. For unbound pools, we could have raced
2362 * with pwq release and it could already be dead. If its refcnt is zero,
2363 * repeat pwq selection. Note that unbound pwqs never die without
2364 * another pwq replacing it in cpu_pwq or while work items are executing
2365 * on it, so the retrying is guaranteed to make forward-progress.
2367 if (unlikely(!pwq->refcnt)) {
2368 if (wq->flags & WQ_UNBOUND) {
2369 raw_spin_unlock(&pool->lock);
2374 WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
2378 /* pwq determined, queue */
2379 trace_workqueue_queue_work(req_cpu, pwq, work);
2381 if (WARN_ON(!list_empty(&work->entry)))
2384 pwq->nr_in_flight[pwq->work_color]++;
2385 work_flags = work_color_to_flags(pwq->work_color);
2388 * Limit the number of concurrently active work items to max_active.
2389 * @work must also queue behind existing inactive work items to maintain
2390 * ordering when max_active changes. See wq_adjust_max_active().
2392 if (list_empty(&pwq->inactive_works) && pwq_tryinc_nr_active(pwq, false)) {
2393 if (list_empty(&pool->worklist))
2394 pool->watchdog_ts = jiffies;
2396 trace_workqueue_activate_work(work);
2397 insert_work(pwq, work, &pool->worklist, work_flags);
2400 work_flags |= WORK_STRUCT_INACTIVE;
2401 insert_work(pwq, work, &pwq->inactive_works, work_flags);
2405 raw_spin_unlock(&pool->lock);
2410 * queue_work_on - queue work on specific cpu
2411 * @cpu: CPU number to execute work on
2412 * @wq: workqueue to use
2413 * @work: work to queue
2415 * We queue the work to a specific CPU, the caller must ensure it
2416 * can't go away. Callers that fail to ensure that the specified
2417 * CPU cannot go away will execute on a randomly chosen CPU.
2418 * But note well that callers specifying a CPU that never has been
2419 * online will get a splat.
2421 * Return: %false if @work was already on a queue, %true otherwise.
2423 bool queue_work_on(int cpu, struct workqueue_struct *wq,
2424 struct work_struct *work)
2427 unsigned long irq_flags;
2429 local_irq_save(irq_flags);
2431 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
2432 __queue_work(cpu, wq, work);
2436 local_irq_restore(irq_flags);
2439 EXPORT_SYMBOL(queue_work_on);
2442 * select_numa_node_cpu - Select a CPU based on NUMA node
2443 * @node: NUMA node ID that we want to select a CPU from
2445 * This function will attempt to find a "random" cpu available on a given
2446 * node. If there are no CPUs available on the given node it will return
2447 * WORK_CPU_UNBOUND indicating that we should just schedule to any
2448 * available CPU if we need to schedule this work.
2450 static int select_numa_node_cpu(int node)
2454 /* Delay binding to CPU if node is not valid or online */
2455 if (node < 0 || node >= MAX_NUMNODES || !node_online(node))
2456 return WORK_CPU_UNBOUND;
2458 /* Use local node/cpu if we are already there */
2459 cpu = raw_smp_processor_id();
2460 if (node == cpu_to_node(cpu))
2463 /* Use "random" otherwise know as "first" online CPU of node */
2464 cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
2466 /* If CPU is valid return that, otherwise just defer */
2467 return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND;
2471 * queue_work_node - queue work on a "random" cpu for a given NUMA node
2472 * @node: NUMA node that we are targeting the work for
2473 * @wq: workqueue to use
2474 * @work: work to queue
2476 * We queue the work to a "random" CPU within a given NUMA node. The basic
2477 * idea here is to provide a way to somehow associate work with a given
2480 * This function will only make a best effort attempt at getting this onto
2481 * the right NUMA node. If no node is requested or the requested node is
2482 * offline then we just fall back to standard queue_work behavior.
2484 * Currently the "random" CPU ends up being the first available CPU in the
2485 * intersection of cpu_online_mask and the cpumask of the node, unless we
2486 * are running on the node. In that case we just use the current CPU.
2488 * Return: %false if @work was already on a queue, %true otherwise.
2490 bool queue_work_node(int node, struct workqueue_struct *wq,
2491 struct work_struct *work)
2493 unsigned long irq_flags;
2497 * This current implementation is specific to unbound workqueues.
2498 * Specifically we only return the first available CPU for a given
2499 * node instead of cycling through individual CPUs within the node.
2501 * If this is used with a per-cpu workqueue then the logic in
2502 * workqueue_select_cpu_near would need to be updated to allow for
2503 * some round robin type logic.
2505 WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND));
2507 local_irq_save(irq_flags);
2509 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
2510 int cpu = select_numa_node_cpu(node);
2512 __queue_work(cpu, wq, work);
2516 local_irq_restore(irq_flags);
2519 EXPORT_SYMBOL_GPL(queue_work_node);
2521 void delayed_work_timer_fn(struct timer_list *t)
2523 struct delayed_work *dwork = from_timer(dwork, t, timer);
2525 /* should have been called from irqsafe timer with irq already off */
2526 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
2528 EXPORT_SYMBOL(delayed_work_timer_fn);
2530 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
2531 struct delayed_work *dwork, unsigned long delay)
2533 struct timer_list *timer = &dwork->timer;
2534 struct work_struct *work = &dwork->work;
2537 WARN_ON_ONCE(timer->function != delayed_work_timer_fn);
2538 WARN_ON_ONCE(timer_pending(timer));
2539 WARN_ON_ONCE(!list_empty(&work->entry));
2542 * If @delay is 0, queue @dwork->work immediately. This is for
2543 * both optimization and correctness. The earliest @timer can
2544 * expire is on the closest next tick and delayed_work users depend
2545 * on that there's no such delay when @delay is 0.
2548 __queue_work(cpu, wq, &dwork->work);
2554 timer->expires = jiffies + delay;
2556 if (housekeeping_enabled(HK_TYPE_TIMER)) {
2557 /* If the current cpu is a housekeeping cpu, use it. */
2558 cpu = smp_processor_id();
2559 if (!housekeeping_test_cpu(cpu, HK_TYPE_TIMER))
2560 cpu = housekeeping_any_cpu(HK_TYPE_TIMER);
2561 add_timer_on(timer, cpu);
2563 if (likely(cpu == WORK_CPU_UNBOUND))
2566 add_timer_on(timer, cpu);
2571 * queue_delayed_work_on - queue work on specific CPU after delay
2572 * @cpu: CPU number to execute work on
2573 * @wq: workqueue to use
2574 * @dwork: work to queue
2575 * @delay: number of jiffies to wait before queueing
2577 * Return: %false if @work was already on a queue, %true otherwise. If
2578 * @delay is zero and @dwork is idle, it will be scheduled for immediate
2581 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
2582 struct delayed_work *dwork, unsigned long delay)
2584 struct work_struct *work = &dwork->work;
2586 unsigned long irq_flags;
2588 /* read the comment in __queue_work() */
2589 local_irq_save(irq_flags);
2591 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
2592 __queue_delayed_work(cpu, wq, dwork, delay);
2596 local_irq_restore(irq_flags);
2599 EXPORT_SYMBOL(queue_delayed_work_on);
2602 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
2603 * @cpu: CPU number to execute work on
2604 * @wq: workqueue to use
2605 * @dwork: work to queue
2606 * @delay: number of jiffies to wait before queueing
2608 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
2609 * modify @dwork's timer so that it expires after @delay. If @delay is
2610 * zero, @work is guaranteed to be scheduled immediately regardless of its
2613 * Return: %false if @dwork was idle and queued, %true if @dwork was
2614 * pending and its timer was modified.
2616 * This function is safe to call from any context including IRQ handler.
2617 * See try_to_grab_pending() for details.
2619 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
2620 struct delayed_work *dwork, unsigned long delay)
2622 unsigned long irq_flags;
2626 ret = try_to_grab_pending(&dwork->work, WORK_CANCEL_DELAYED,
2628 } while (unlikely(ret == -EAGAIN));
2630 if (likely(ret >= 0)) {
2631 __queue_delayed_work(cpu, wq, dwork, delay);
2632 local_irq_restore(irq_flags);
2635 /* -ENOENT from try_to_grab_pending() becomes %true */
2638 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
2640 static void rcu_work_rcufn(struct rcu_head *rcu)
2642 struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
2644 /* read the comment in __queue_work() */
2645 local_irq_disable();
2646 __queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
2651 * queue_rcu_work - queue work after a RCU grace period
2652 * @wq: workqueue to use
2653 * @rwork: work to queue
2655 * Return: %false if @rwork was already pending, %true otherwise. Note
2656 * that a full RCU grace period is guaranteed only after a %true return.
2657 * While @rwork is guaranteed to be executed after a %false return, the
2658 * execution may happen before a full RCU grace period has passed.
2660 bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
2662 struct work_struct *work = &rwork->work;
2664 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
2666 call_rcu_hurry(&rwork->rcu, rcu_work_rcufn);
2672 EXPORT_SYMBOL(queue_rcu_work);
2674 static struct worker *alloc_worker(int node)
2676 struct worker *worker;
2678 worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
2680 INIT_LIST_HEAD(&worker->entry);
2681 INIT_LIST_HEAD(&worker->scheduled);
2682 INIT_LIST_HEAD(&worker->node);
2683 /* on creation a worker is in !idle && prep state */
2684 worker->flags = WORKER_PREP;
2689 static cpumask_t *pool_allowed_cpus(struct worker_pool *pool)
2691 if (pool->cpu < 0 && pool->attrs->affn_strict)
2692 return pool->attrs->__pod_cpumask;
2694 return pool->attrs->cpumask;
2698 * worker_attach_to_pool() - attach a worker to a pool
2699 * @worker: worker to be attached
2700 * @pool: the target pool
2702 * Attach @worker to @pool. Once attached, the %WORKER_UNBOUND flag and
2703 * cpu-binding of @worker are kept coordinated with the pool across
2706 static void worker_attach_to_pool(struct worker *worker,
2707 struct worker_pool *pool)
2709 mutex_lock(&wq_pool_attach_mutex);
2712 * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains stable
2713 * across this function. See the comments above the flag definition for
2714 * details. BH workers are, while per-CPU, always DISASSOCIATED.
2716 if (pool->flags & POOL_DISASSOCIATED) {
2717 worker->flags |= WORKER_UNBOUND;
2719 WARN_ON_ONCE(pool->flags & POOL_BH);
2720 kthread_set_per_cpu(worker->task, pool->cpu);
2723 if (worker->rescue_wq)
2724 set_cpus_allowed_ptr(worker->task, pool_allowed_cpus(pool));
2726 list_add_tail(&worker->node, &pool->workers);
2727 worker->pool = pool;
2729 mutex_unlock(&wq_pool_attach_mutex);
2733 * worker_detach_from_pool() - detach a worker from its pool
2734 * @worker: worker which is attached to its pool
2736 * Undo the attaching which had been done in worker_attach_to_pool(). The
2737 * caller worker shouldn't access to the pool after detached except it has
2738 * other reference to the pool.
2740 static void worker_detach_from_pool(struct worker *worker)
2742 struct worker_pool *pool = worker->pool;
2743 struct completion *detach_completion = NULL;
2745 /* there is one permanent BH worker per CPU which should never detach */
2746 WARN_ON_ONCE(pool->flags & POOL_BH);
2748 mutex_lock(&wq_pool_attach_mutex);
2750 kthread_set_per_cpu(worker->task, -1);
2751 list_del(&worker->node);
2752 worker->pool = NULL;
2754 if (list_empty(&pool->workers) && list_empty(&pool->dying_workers))
2755 detach_completion = pool->detach_completion;
2756 mutex_unlock(&wq_pool_attach_mutex);
2758 /* clear leftover flags without pool->lock after it is detached */
2759 worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
2761 if (detach_completion)
2762 complete(detach_completion);
2766 * create_worker - create a new workqueue worker
2767 * @pool: pool the new worker will belong to
2769 * Create and start a new worker which is attached to @pool.
2772 * Might sleep. Does GFP_KERNEL allocations.
2775 * Pointer to the newly created worker.
2777 static struct worker *create_worker(struct worker_pool *pool)
2779 struct worker *worker;
2783 /* ID is needed to determine kthread name */
2784 id = ida_alloc(&pool->worker_ida, GFP_KERNEL);
2786 pr_err_once("workqueue: Failed to allocate a worker ID: %pe\n",
2791 worker = alloc_worker(pool->node);
2793 pr_err_once("workqueue: Failed to allocate a worker\n");
2799 if (!(pool->flags & POOL_BH)) {
2801 snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
2802 pool->attrs->nice < 0 ? "H" : "");
2804 snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
2806 worker->task = kthread_create_on_node(worker_thread, worker,
2807 pool->node, "kworker/%s", id_buf);
2808 if (IS_ERR(worker->task)) {
2809 if (PTR_ERR(worker->task) == -EINTR) {
2810 pr_err("workqueue: Interrupted when creating a worker thread \"kworker/%s\"\n",
2813 pr_err_once("workqueue: Failed to create a worker thread: %pe",
2819 set_user_nice(worker->task, pool->attrs->nice);
2820 kthread_bind_mask(worker->task, pool_allowed_cpus(pool));
2823 /* successful, attach the worker to the pool */
2824 worker_attach_to_pool(worker, pool);
2826 /* start the newly created worker */
2827 raw_spin_lock_irq(&pool->lock);
2829 worker->pool->nr_workers++;
2830 worker_enter_idle(worker);
2833 * @worker is waiting on a completion in kthread() and will trigger hung
2834 * check if not woken up soon. As kick_pool() is noop if @pool is empty,
2835 * wake it up explicitly.
2838 wake_up_process(worker->task);
2840 raw_spin_unlock_irq(&pool->lock);
2845 ida_free(&pool->worker_ida, id);
2850 static void unbind_worker(struct worker *worker)
2852 lockdep_assert_held(&wq_pool_attach_mutex);
2854 kthread_set_per_cpu(worker->task, -1);
2855 if (cpumask_intersects(wq_unbound_cpumask, cpu_active_mask))
2856 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, wq_unbound_cpumask) < 0);
2858 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, cpu_possible_mask) < 0);
2861 static void wake_dying_workers(struct list_head *cull_list)
2863 struct worker *worker, *tmp;
2865 list_for_each_entry_safe(worker, tmp, cull_list, entry) {
2866 list_del_init(&worker->entry);
2867 unbind_worker(worker);
2869 * If the worker was somehow already running, then it had to be
2870 * in pool->idle_list when set_worker_dying() happened or we
2871 * wouldn't have gotten here.
2873 * Thus, the worker must either have observed the WORKER_DIE
2874 * flag, or have set its state to TASK_IDLE. Either way, the
2875 * below will be observed by the worker and is safe to do
2876 * outside of pool->lock.
2878 wake_up_process(worker->task);
2883 * set_worker_dying - Tag a worker for destruction
2884 * @worker: worker to be destroyed
2885 * @list: transfer worker away from its pool->idle_list and into list
2887 * Tag @worker for destruction and adjust @pool stats accordingly. The worker
2891 * raw_spin_lock_irq(pool->lock).
2893 static void set_worker_dying(struct worker *worker, struct list_head *list)
2895 struct worker_pool *pool = worker->pool;
2897 lockdep_assert_held(&pool->lock);
2898 lockdep_assert_held(&wq_pool_attach_mutex);
2900 /* sanity check frenzy */
2901 if (WARN_ON(worker->current_work) ||
2902 WARN_ON(!list_empty(&worker->scheduled)) ||
2903 WARN_ON(!(worker->flags & WORKER_IDLE)))
2909 worker->flags |= WORKER_DIE;
2911 list_move(&worker->entry, list);
2912 list_move(&worker->node, &pool->dying_workers);
2916 * idle_worker_timeout - check if some idle workers can now be deleted.
2917 * @t: The pool's idle_timer that just expired
2919 * The timer is armed in worker_enter_idle(). Note that it isn't disarmed in
2920 * worker_leave_idle(), as a worker flicking between idle and active while its
2921 * pool is at the too_many_workers() tipping point would cause too much timer
2922 * housekeeping overhead. Since IDLE_WORKER_TIMEOUT is long enough, we just let
2923 * it expire and re-evaluate things from there.
2925 static void idle_worker_timeout(struct timer_list *t)
2927 struct worker_pool *pool = from_timer(pool, t, idle_timer);
2928 bool do_cull = false;
2930 if (work_pending(&pool->idle_cull_work))
2933 raw_spin_lock_irq(&pool->lock);
2935 if (too_many_workers(pool)) {
2936 struct worker *worker;
2937 unsigned long expires;
2939 /* idle_list is kept in LIFO order, check the last one */
2940 worker = list_entry(pool->idle_list.prev, struct worker, entry);
2941 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2942 do_cull = !time_before(jiffies, expires);
2945 mod_timer(&pool->idle_timer, expires);
2947 raw_spin_unlock_irq(&pool->lock);
2950 queue_work(system_unbound_wq, &pool->idle_cull_work);
2954 * idle_cull_fn - cull workers that have been idle for too long.
2955 * @work: the pool's work for handling these idle workers
2957 * This goes through a pool's idle workers and gets rid of those that have been
2958 * idle for at least IDLE_WORKER_TIMEOUT seconds.
2960 * We don't want to disturb isolated CPUs because of a pcpu kworker being
2961 * culled, so this also resets worker affinity. This requires a sleepable
2962 * context, hence the split between timer callback and work item.
2964 static void idle_cull_fn(struct work_struct *work)
2966 struct worker_pool *pool = container_of(work, struct worker_pool, idle_cull_work);
2967 LIST_HEAD(cull_list);
2970 * Grabbing wq_pool_attach_mutex here ensures an already-running worker
2971 * cannot proceed beyong worker_detach_from_pool() in its self-destruct
2972 * path. This is required as a previously-preempted worker could run after
2973 * set_worker_dying() has happened but before wake_dying_workers() did.
2975 mutex_lock(&wq_pool_attach_mutex);
2976 raw_spin_lock_irq(&pool->lock);
2978 while (too_many_workers(pool)) {
2979 struct worker *worker;
2980 unsigned long expires;
2982 worker = list_entry(pool->idle_list.prev, struct worker, entry);
2983 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2985 if (time_before(jiffies, expires)) {
2986 mod_timer(&pool->idle_timer, expires);
2990 set_worker_dying(worker, &cull_list);
2993 raw_spin_unlock_irq(&pool->lock);
2994 wake_dying_workers(&cull_list);
2995 mutex_unlock(&wq_pool_attach_mutex);
2998 static void send_mayday(struct work_struct *work)
3000 struct pool_workqueue *pwq = get_work_pwq(work);
3001 struct workqueue_struct *wq = pwq->wq;
3003 lockdep_assert_held(&wq_mayday_lock);
3008 /* mayday mayday mayday */
3009 if (list_empty(&pwq->mayday_node)) {
3011 * If @pwq is for an unbound wq, its base ref may be put at
3012 * any time due to an attribute change. Pin @pwq until the
3013 * rescuer is done with it.
3016 list_add_tail(&pwq->mayday_node, &wq->maydays);
3017 wake_up_process(wq->rescuer->task);
3018 pwq->stats[PWQ_STAT_MAYDAY]++;
3022 static void pool_mayday_timeout(struct timer_list *t)
3024 struct worker_pool *pool = from_timer(pool, t, mayday_timer);
3025 struct work_struct *work;
3027 raw_spin_lock_irq(&pool->lock);
3028 raw_spin_lock(&wq_mayday_lock); /* for wq->maydays */
3030 if (need_to_create_worker(pool)) {
3032 * We've been trying to create a new worker but
3033 * haven't been successful. We might be hitting an
3034 * allocation deadlock. Send distress signals to
3037 list_for_each_entry(work, &pool->worklist, entry)
3041 raw_spin_unlock(&wq_mayday_lock);
3042 raw_spin_unlock_irq(&pool->lock);
3044 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
3048 * maybe_create_worker - create a new worker if necessary
3049 * @pool: pool to create a new worker for
3051 * Create a new worker for @pool if necessary. @pool is guaranteed to
3052 * have at least one idle worker on return from this function. If
3053 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
3054 * sent to all rescuers with works scheduled on @pool to resolve
3055 * possible allocation deadlock.
3057 * On return, need_to_create_worker() is guaranteed to be %false and
3058 * may_start_working() %true.
3061 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
3062 * multiple times. Does GFP_KERNEL allocations. Called only from
3065 static void maybe_create_worker(struct worker_pool *pool)
3066 __releases(&pool->lock)
3067 __acquires(&pool->lock)
3070 raw_spin_unlock_irq(&pool->lock);
3072 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
3073 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
3076 if (create_worker(pool) || !need_to_create_worker(pool))
3079 schedule_timeout_interruptible(CREATE_COOLDOWN);
3081 if (!need_to_create_worker(pool))
3085 del_timer_sync(&pool->mayday_timer);
3086 raw_spin_lock_irq(&pool->lock);
3088 * This is necessary even after a new worker was just successfully
3089 * created as @pool->lock was dropped and the new worker might have
3090 * already become busy.
3092 if (need_to_create_worker(pool))
3097 * manage_workers - manage worker pool
3100 * Assume the manager role and manage the worker pool @worker belongs
3101 * to. At any given time, there can be only zero or one manager per
3102 * pool. The exclusion is handled automatically by this function.
3104 * The caller can safely start processing works on false return. On
3105 * true return, it's guaranteed that need_to_create_worker() is false
3106 * and may_start_working() is true.
3109 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
3110 * multiple times. Does GFP_KERNEL allocations.
3113 * %false if the pool doesn't need management and the caller can safely
3114 * start processing works, %true if management function was performed and
3115 * the conditions that the caller verified before calling the function may
3116 * no longer be true.
3118 static bool manage_workers(struct worker *worker)
3120 struct worker_pool *pool = worker->pool;
3122 if (pool->flags & POOL_MANAGER_ACTIVE)
3125 pool->flags |= POOL_MANAGER_ACTIVE;
3126 pool->manager = worker;
3128 maybe_create_worker(pool);
3130 pool->manager = NULL;
3131 pool->flags &= ~POOL_MANAGER_ACTIVE;
3132 rcuwait_wake_up(&manager_wait);
3137 * process_one_work - process single work
3139 * @work: work to process
3141 * Process @work. This function contains all the logics necessary to
3142 * process a single work including synchronization against and
3143 * interaction with other workers on the same cpu, queueing and
3144 * flushing. As long as context requirement is met, any worker can
3145 * call this function to process a work.
3148 * raw_spin_lock_irq(pool->lock) which is released and regrabbed.
3150 static void process_one_work(struct worker *worker, struct work_struct *work)
3151 __releases(&pool->lock)
3152 __acquires(&pool->lock)
3154 struct pool_workqueue *pwq = get_work_pwq(work);
3155 struct worker_pool *pool = worker->pool;
3156 unsigned long work_data;
3157 int lockdep_start_depth, rcu_start_depth;
3158 #ifdef CONFIG_LOCKDEP
3160 * It is permissible to free the struct work_struct from
3161 * inside the function that is called from it, this we need to
3162 * take into account for lockdep too. To avoid bogus "held
3163 * lock freed" warnings as well as problems when looking into
3164 * work->lockdep_map, make a copy and use that here.
3166 struct lockdep_map lockdep_map;
3168 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
3170 /* ensure we're on the correct CPU */
3171 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
3172 raw_smp_processor_id() != pool->cpu);
3174 /* claim and dequeue */
3175 debug_work_deactivate(work);
3176 hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
3177 worker->current_work = work;
3178 worker->current_func = work->func;
3179 worker->current_pwq = pwq;
3181 worker->current_at = worker->task->se.sum_exec_runtime;
3182 work_data = *work_data_bits(work);
3183 worker->current_color = get_work_color(work_data);
3186 * Record wq name for cmdline and debug reporting, may get
3187 * overridden through set_worker_desc().
3189 strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
3191 list_del_init(&work->entry);
3194 * CPU intensive works don't participate in concurrency management.
3195 * They're the scheduler's responsibility. This takes @worker out
3196 * of concurrency management and the next code block will chain
3197 * execution of the pending work items.
3199 if (unlikely(pwq->wq->flags & WQ_CPU_INTENSIVE))
3200 worker_set_flags(worker, WORKER_CPU_INTENSIVE);
3203 * Kick @pool if necessary. It's always noop for per-cpu worker pools
3204 * since nr_running would always be >= 1 at this point. This is used to
3205 * chain execution of the pending work items for WORKER_NOT_RUNNING
3206 * workers such as the UNBOUND and CPU_INTENSIVE ones.
3211 * Record the last pool and clear PENDING which should be the last
3212 * update to @work. Also, do this inside @pool->lock so that
3213 * PENDING and queued state changes happen together while IRQ is
3216 set_work_pool_and_clear_pending(work, pool->id, 0);
3218 pwq->stats[PWQ_STAT_STARTED]++;
3219 raw_spin_unlock_irq(&pool->lock);
3221 rcu_start_depth = rcu_preempt_depth();
3222 lockdep_start_depth = lockdep_depth(current);
3223 lock_map_acquire(&pwq->wq->lockdep_map);
3224 lock_map_acquire(&lockdep_map);
3226 * Strictly speaking we should mark the invariant state without holding
3227 * any locks, that is, before these two lock_map_acquire()'s.
3229 * However, that would result in:
3236 * Which would create W1->C->W1 dependencies, even though there is no
3237 * actual deadlock possible. There are two solutions, using a
3238 * read-recursive acquire on the work(queue) 'locks', but this will then
3239 * hit the lockdep limitation on recursive locks, or simply discard
3242 * AFAICT there is no possible deadlock scenario between the
3243 * flush_work() and complete() primitives (except for single-threaded
3244 * workqueues), so hiding them isn't a problem.
3246 lockdep_invariant_state(true);
3247 trace_workqueue_execute_start(work);
3248 worker->current_func(work);
3250 * While we must be careful to not use "work" after this, the trace
3251 * point will only record its address.
3253 trace_workqueue_execute_end(work, worker->current_func);
3254 pwq->stats[PWQ_STAT_COMPLETED]++;
3255 lock_map_release(&lockdep_map);
3256 lock_map_release(&pwq->wq->lockdep_map);
3258 if (unlikely((worker->task && in_atomic()) ||
3259 lockdep_depth(current) != lockdep_start_depth ||
3260 rcu_preempt_depth() != rcu_start_depth)) {
3261 pr_err("BUG: workqueue leaked atomic, lock or RCU: %s[%d]\n"
3262 " preempt=0x%08x lock=%d->%d RCU=%d->%d workfn=%ps\n",
3263 current->comm, task_pid_nr(current), preempt_count(),
3264 lockdep_start_depth, lockdep_depth(current),
3265 rcu_start_depth, rcu_preempt_depth(),
3266 worker->current_func);
3267 debug_show_held_locks(current);
3272 * The following prevents a kworker from hogging CPU on !PREEMPTION
3273 * kernels, where a requeueing work item waiting for something to
3274 * happen could deadlock with stop_machine as such work item could
3275 * indefinitely requeue itself while all other CPUs are trapped in
3276 * stop_machine. At the same time, report a quiescent RCU state so
3277 * the same condition doesn't freeze RCU.
3282 raw_spin_lock_irq(&pool->lock);
3285 * In addition to %WQ_CPU_INTENSIVE, @worker may also have been marked
3286 * CPU intensive by wq_worker_tick() if @work hogged CPU longer than
3287 * wq_cpu_intensive_thresh_us. Clear it.
3289 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
3291 /* tag the worker for identification in schedule() */
3292 worker->last_func = worker->current_func;
3294 /* we're done with it, release */
3295 hash_del(&worker->hentry);
3296 worker->current_work = NULL;
3297 worker->current_func = NULL;
3298 worker->current_pwq = NULL;
3299 worker->current_color = INT_MAX;
3301 /* must be the last step, see the function comment */
3302 pwq_dec_nr_in_flight(pwq, work_data);
3306 * process_scheduled_works - process scheduled works
3309 * Process all scheduled works. Please note that the scheduled list
3310 * may change while processing a work, so this function repeatedly
3311 * fetches a work from the top and executes it.
3314 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
3317 static void process_scheduled_works(struct worker *worker)
3319 struct work_struct *work;
3322 while ((work = list_first_entry_or_null(&worker->scheduled,
3323 struct work_struct, entry))) {
3325 worker->pool->watchdog_ts = jiffies;
3328 process_one_work(worker, work);
3332 static void set_pf_worker(bool val)
3334 mutex_lock(&wq_pool_attach_mutex);
3336 current->flags |= PF_WQ_WORKER;
3338 current->flags &= ~PF_WQ_WORKER;
3339 mutex_unlock(&wq_pool_attach_mutex);
3343 * worker_thread - the worker thread function
3346 * The worker thread function. All workers belong to a worker_pool -
3347 * either a per-cpu one or dynamic unbound one. These workers process all
3348 * work items regardless of their specific target workqueue. The only
3349 * exception is work items which belong to workqueues with a rescuer which
3350 * will be explained in rescuer_thread().
3354 static int worker_thread(void *__worker)
3356 struct worker *worker = __worker;
3357 struct worker_pool *pool = worker->pool;
3359 /* tell the scheduler that this is a workqueue worker */
3360 set_pf_worker(true);
3362 raw_spin_lock_irq(&pool->lock);
3364 /* am I supposed to die? */
3365 if (unlikely(worker->flags & WORKER_DIE)) {
3366 raw_spin_unlock_irq(&pool->lock);
3367 set_pf_worker(false);
3369 set_task_comm(worker->task, "kworker/dying");
3370 ida_free(&pool->worker_ida, worker->id);
3371 worker_detach_from_pool(worker);
3372 WARN_ON_ONCE(!list_empty(&worker->entry));
3377 worker_leave_idle(worker);
3379 /* no more worker necessary? */
3380 if (!need_more_worker(pool))
3383 /* do we need to manage? */
3384 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
3388 * ->scheduled list can only be filled while a worker is
3389 * preparing to process a work or actually processing it.
3390 * Make sure nobody diddled with it while I was sleeping.
3392 WARN_ON_ONCE(!list_empty(&worker->scheduled));
3395 * Finish PREP stage. We're guaranteed to have at least one idle
3396 * worker or that someone else has already assumed the manager
3397 * role. This is where @worker starts participating in concurrency
3398 * management if applicable and concurrency management is restored
3399 * after being rebound. See rebind_workers() for details.
3401 worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
3404 struct work_struct *work =
3405 list_first_entry(&pool->worklist,
3406 struct work_struct, entry);
3408 if (assign_work(work, worker, NULL))
3409 process_scheduled_works(worker);
3410 } while (keep_working(pool));
3412 worker_set_flags(worker, WORKER_PREP);
3415 * pool->lock is held and there's no work to process and no need to
3416 * manage, sleep. Workers are woken up only while holding
3417 * pool->lock or from local cpu, so setting the current state
3418 * before releasing pool->lock is enough to prevent losing any
3421 worker_enter_idle(worker);
3422 __set_current_state(TASK_IDLE);
3423 raw_spin_unlock_irq(&pool->lock);
3429 * rescuer_thread - the rescuer thread function
3432 * Workqueue rescuer thread function. There's one rescuer for each
3433 * workqueue which has WQ_MEM_RECLAIM set.
3435 * Regular work processing on a pool may block trying to create a new
3436 * worker which uses GFP_KERNEL allocation which has slight chance of
3437 * developing into deadlock if some works currently on the same queue
3438 * need to be processed to satisfy the GFP_KERNEL allocation. This is
3439 * the problem rescuer solves.
3441 * When such condition is possible, the pool summons rescuers of all
3442 * workqueues which have works queued on the pool and let them process
3443 * those works so that forward progress can be guaranteed.
3445 * This should happen rarely.
3449 static int rescuer_thread(void *__rescuer)
3451 struct worker *rescuer = __rescuer;
3452 struct workqueue_struct *wq = rescuer->rescue_wq;
3455 set_user_nice(current, RESCUER_NICE_LEVEL);
3458 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
3459 * doesn't participate in concurrency management.
3461 set_pf_worker(true);
3463 set_current_state(TASK_IDLE);
3466 * By the time the rescuer is requested to stop, the workqueue
3467 * shouldn't have any work pending, but @wq->maydays may still have
3468 * pwq(s) queued. This can happen by non-rescuer workers consuming
3469 * all the work items before the rescuer got to them. Go through
3470 * @wq->maydays processing before acting on should_stop so that the
3471 * list is always empty on exit.
3473 should_stop = kthread_should_stop();
3475 /* see whether any pwq is asking for help */
3476 raw_spin_lock_irq(&wq_mayday_lock);
3478 while (!list_empty(&wq->maydays)) {
3479 struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
3480 struct pool_workqueue, mayday_node);
3481 struct worker_pool *pool = pwq->pool;
3482 struct work_struct *work, *n;
3484 __set_current_state(TASK_RUNNING);
3485 list_del_init(&pwq->mayday_node);
3487 raw_spin_unlock_irq(&wq_mayday_lock);
3489 worker_attach_to_pool(rescuer, pool);
3491 raw_spin_lock_irq(&pool->lock);
3494 * Slurp in all works issued via this workqueue and
3497 WARN_ON_ONCE(!list_empty(&rescuer->scheduled));
3498 list_for_each_entry_safe(work, n, &pool->worklist, entry) {
3499 if (get_work_pwq(work) == pwq &&
3500 assign_work(work, rescuer, &n))
3501 pwq->stats[PWQ_STAT_RESCUED]++;
3504 if (!list_empty(&rescuer->scheduled)) {
3505 process_scheduled_works(rescuer);
3508 * The above execution of rescued work items could
3509 * have created more to rescue through
3510 * pwq_activate_first_inactive() or chained
3511 * queueing. Let's put @pwq back on mayday list so
3512 * that such back-to-back work items, which may be
3513 * being used to relieve memory pressure, don't
3514 * incur MAYDAY_INTERVAL delay inbetween.
3516 if (pwq->nr_active && need_to_create_worker(pool)) {
3517 raw_spin_lock(&wq_mayday_lock);
3519 * Queue iff we aren't racing destruction
3520 * and somebody else hasn't queued it already.
3522 if (wq->rescuer && list_empty(&pwq->mayday_node)) {
3524 list_add_tail(&pwq->mayday_node, &wq->maydays);
3526 raw_spin_unlock(&wq_mayday_lock);
3531 * Put the reference grabbed by send_mayday(). @pool won't
3532 * go away while we're still attached to it.
3537 * Leave this pool. Notify regular workers; otherwise, we end up
3538 * with 0 concurrency and stalling the execution.
3542 raw_spin_unlock_irq(&pool->lock);
3544 worker_detach_from_pool(rescuer);
3546 raw_spin_lock_irq(&wq_mayday_lock);
3549 raw_spin_unlock_irq(&wq_mayday_lock);
3552 __set_current_state(TASK_RUNNING);
3553 set_pf_worker(false);
3557 /* rescuers should never participate in concurrency management */
3558 WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
3563 static void bh_worker(struct worker *worker)
3565 struct worker_pool *pool = worker->pool;
3566 int nr_restarts = BH_WORKER_RESTARTS;
3567 unsigned long end = jiffies + BH_WORKER_JIFFIES;
3569 raw_spin_lock_irq(&pool->lock);
3570 worker_leave_idle(worker);
3573 * This function follows the structure of worker_thread(). See there for
3574 * explanations on each step.
3576 if (!need_more_worker(pool))
3579 WARN_ON_ONCE(!list_empty(&worker->scheduled));
3580 worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
3583 struct work_struct *work =
3584 list_first_entry(&pool->worklist,
3585 struct work_struct, entry);
3587 if (assign_work(work, worker, NULL))
3588 process_scheduled_works(worker);
3589 } while (keep_working(pool) &&
3590 --nr_restarts && time_before(jiffies, end));
3592 worker_set_flags(worker, WORKER_PREP);
3594 worker_enter_idle(worker);
3596 raw_spin_unlock_irq(&pool->lock);
3600 * TODO: Convert all tasklet users to workqueue and use softirq directly.
3602 * This is currently called from tasklet[_hi]action() and thus is also called
3603 * whenever there are tasklets to run. Let's do an early exit if there's nothing
3604 * queued. Once conversion from tasklet is complete, the need_more_worker() test
3607 * After full conversion, we'll add worker->softirq_action, directly use the
3608 * softirq action and obtain the worker pointer from the softirq_action pointer.
3610 void workqueue_softirq_action(bool highpri)
3612 struct worker_pool *pool =
3613 &per_cpu(bh_worker_pools, smp_processor_id())[highpri];
3614 if (need_more_worker(pool))
3615 bh_worker(list_first_entry(&pool->workers, struct worker, node));
3619 * check_flush_dependency - check for flush dependency sanity
3620 * @target_wq: workqueue being flushed
3621 * @target_work: work item being flushed (NULL for workqueue flushes)
3623 * %current is trying to flush the whole @target_wq or @target_work on it.
3624 * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
3625 * reclaiming memory or running on a workqueue which doesn't have
3626 * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
3629 static void check_flush_dependency(struct workqueue_struct *target_wq,
3630 struct work_struct *target_work)
3632 work_func_t target_func = target_work ? target_work->func : NULL;
3633 struct worker *worker;
3635 if (target_wq->flags & WQ_MEM_RECLAIM)
3638 worker = current_wq_worker();
3640 WARN_ONCE(current->flags & PF_MEMALLOC,
3641 "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps",
3642 current->pid, current->comm, target_wq->name, target_func);
3643 WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
3644 (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
3645 "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps",
3646 worker->current_pwq->wq->name, worker->current_func,
3647 target_wq->name, target_func);
3651 struct work_struct work;
3652 struct completion done;
3653 struct task_struct *task; /* purely informational */
3656 static void wq_barrier_func(struct work_struct *work)
3658 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
3659 complete(&barr->done);
3663 * insert_wq_barrier - insert a barrier work
3664 * @pwq: pwq to insert barrier into
3665 * @barr: wq_barrier to insert
3666 * @target: target work to attach @barr to
3667 * @worker: worker currently executing @target, NULL if @target is not executing
3669 * @barr is linked to @target such that @barr is completed only after
3670 * @target finishes execution. Please note that the ordering
3671 * guarantee is observed only with respect to @target and on the local
3674 * Currently, a queued barrier can't be canceled. This is because
3675 * try_to_grab_pending() can't determine whether the work to be
3676 * grabbed is at the head of the queue and thus can't clear LINKED
3677 * flag of the previous work while there must be a valid next work
3678 * after a work with LINKED flag set.
3680 * Note that when @worker is non-NULL, @target may be modified
3681 * underneath us, so we can't reliably determine pwq from @target.
3684 * raw_spin_lock_irq(pool->lock).
3686 static void insert_wq_barrier(struct pool_workqueue *pwq,
3687 struct wq_barrier *barr,
3688 struct work_struct *target, struct worker *worker)
3690 static __maybe_unused struct lock_class_key bh_key, thr_key;
3691 unsigned int work_flags = 0;
3692 unsigned int work_color;
3693 struct list_head *head;
3696 * debugobject calls are safe here even with pool->lock locked
3697 * as we know for sure that this will not trigger any of the
3698 * checks and call back into the fixup functions where we
3701 * BH and threaded workqueues need separate lockdep keys to avoid
3702 * spuriously triggering "inconsistent {SOFTIRQ-ON-W} -> {IN-SOFTIRQ-W}
3705 INIT_WORK_ONSTACK_KEY(&barr->work, wq_barrier_func,
3706 (pwq->wq->flags & WQ_BH) ? &bh_key : &thr_key);
3707 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
3709 init_completion_map(&barr->done, &target->lockdep_map);
3711 barr->task = current;
3713 /* The barrier work item does not participate in nr_active. */
3714 work_flags |= WORK_STRUCT_INACTIVE;
3717 * If @target is currently being executed, schedule the
3718 * barrier to the worker; otherwise, put it after @target.
3721 head = worker->scheduled.next;
3722 work_color = worker->current_color;
3724 unsigned long *bits = work_data_bits(target);
3726 head = target->entry.next;
3727 /* there can already be other linked works, inherit and set */
3728 work_flags |= *bits & WORK_STRUCT_LINKED;
3729 work_color = get_work_color(*bits);
3730 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
3733 pwq->nr_in_flight[work_color]++;
3734 work_flags |= work_color_to_flags(work_color);
3736 insert_work(pwq, &barr->work, head, work_flags);
3740 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
3741 * @wq: workqueue being flushed
3742 * @flush_color: new flush color, < 0 for no-op
3743 * @work_color: new work color, < 0 for no-op
3745 * Prepare pwqs for workqueue flushing.
3747 * If @flush_color is non-negative, flush_color on all pwqs should be
3748 * -1. If no pwq has in-flight commands at the specified color, all
3749 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
3750 * has in flight commands, its pwq->flush_color is set to
3751 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
3752 * wakeup logic is armed and %true is returned.
3754 * The caller should have initialized @wq->first_flusher prior to
3755 * calling this function with non-negative @flush_color. If
3756 * @flush_color is negative, no flush color update is done and %false
3759 * If @work_color is non-negative, all pwqs should have the same
3760 * work_color which is previous to @work_color and all will be
3761 * advanced to @work_color.
3764 * mutex_lock(wq->mutex).
3767 * %true if @flush_color >= 0 and there's something to flush. %false
3770 static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
3771 int flush_color, int work_color)
3774 struct pool_workqueue *pwq;
3776 if (flush_color >= 0) {
3777 WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
3778 atomic_set(&wq->nr_pwqs_to_flush, 1);
3781 for_each_pwq(pwq, wq) {
3782 struct worker_pool *pool = pwq->pool;
3784 raw_spin_lock_irq(&pool->lock);
3786 if (flush_color >= 0) {
3787 WARN_ON_ONCE(pwq->flush_color != -1);
3789 if (pwq->nr_in_flight[flush_color]) {
3790 pwq->flush_color = flush_color;
3791 atomic_inc(&wq->nr_pwqs_to_flush);
3796 if (work_color >= 0) {
3797 WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
3798 pwq->work_color = work_color;
3801 raw_spin_unlock_irq(&pool->lock);
3804 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
3805 complete(&wq->first_flusher->done);
3810 static void touch_wq_lockdep_map(struct workqueue_struct *wq)
3812 #ifdef CONFIG_LOCKDEP
3813 if (wq->flags & WQ_BH)
3816 lock_map_acquire(&wq->lockdep_map);
3817 lock_map_release(&wq->lockdep_map);
3819 if (wq->flags & WQ_BH)
3824 static void touch_work_lockdep_map(struct work_struct *work,
3825 struct workqueue_struct *wq)
3827 #ifdef CONFIG_LOCKDEP
3828 if (wq->flags & WQ_BH)
3831 lock_map_acquire(&work->lockdep_map);
3832 lock_map_release(&work->lockdep_map);
3834 if (wq->flags & WQ_BH)
3840 * __flush_workqueue - ensure that any scheduled work has run to completion.
3841 * @wq: workqueue to flush
3843 * This function sleeps until all work items which were queued on entry
3844 * have finished execution, but it is not livelocked by new incoming ones.
3846 void __flush_workqueue(struct workqueue_struct *wq)
3848 struct wq_flusher this_flusher = {
3849 .list = LIST_HEAD_INIT(this_flusher.list),
3851 .done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map),
3855 if (WARN_ON(!wq_online))
3858 touch_wq_lockdep_map(wq);
3860 mutex_lock(&wq->mutex);
3863 * Start-to-wait phase
3865 next_color = work_next_color(wq->work_color);
3867 if (next_color != wq->flush_color) {
3869 * Color space is not full. The current work_color
3870 * becomes our flush_color and work_color is advanced
3873 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
3874 this_flusher.flush_color = wq->work_color;
3875 wq->work_color = next_color;
3877 if (!wq->first_flusher) {
3878 /* no flush in progress, become the first flusher */
3879 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
3881 wq->first_flusher = &this_flusher;
3883 if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
3885 /* nothing to flush, done */
3886 wq->flush_color = next_color;
3887 wq->first_flusher = NULL;
3892 WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
3893 list_add_tail(&this_flusher.list, &wq->flusher_queue);
3894 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
3898 * Oops, color space is full, wait on overflow queue.
3899 * The next flush completion will assign us
3900 * flush_color and transfer to flusher_queue.
3902 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
3905 check_flush_dependency(wq, NULL);
3907 mutex_unlock(&wq->mutex);
3909 wait_for_completion(&this_flusher.done);
3912 * Wake-up-and-cascade phase
3914 * First flushers are responsible for cascading flushes and
3915 * handling overflow. Non-first flushers can simply return.
3917 if (READ_ONCE(wq->first_flusher) != &this_flusher)
3920 mutex_lock(&wq->mutex);
3922 /* we might have raced, check again with mutex held */
3923 if (wq->first_flusher != &this_flusher)
3926 WRITE_ONCE(wq->first_flusher, NULL);
3928 WARN_ON_ONCE(!list_empty(&this_flusher.list));
3929 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
3932 struct wq_flusher *next, *tmp;
3934 /* complete all the flushers sharing the current flush color */
3935 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
3936 if (next->flush_color != wq->flush_color)
3938 list_del_init(&next->list);
3939 complete(&next->done);
3942 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
3943 wq->flush_color != work_next_color(wq->work_color));
3945 /* this flush_color is finished, advance by one */
3946 wq->flush_color = work_next_color(wq->flush_color);
3948 /* one color has been freed, handle overflow queue */
3949 if (!list_empty(&wq->flusher_overflow)) {
3951 * Assign the same color to all overflowed
3952 * flushers, advance work_color and append to
3953 * flusher_queue. This is the start-to-wait
3954 * phase for these overflowed flushers.
3956 list_for_each_entry(tmp, &wq->flusher_overflow, list)
3957 tmp->flush_color = wq->work_color;
3959 wq->work_color = work_next_color(wq->work_color);
3961 list_splice_tail_init(&wq->flusher_overflow,
3962 &wq->flusher_queue);
3963 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
3966 if (list_empty(&wq->flusher_queue)) {
3967 WARN_ON_ONCE(wq->flush_color != wq->work_color);
3972 * Need to flush more colors. Make the next flusher
3973 * the new first flusher and arm pwqs.
3975 WARN_ON_ONCE(wq->flush_color == wq->work_color);
3976 WARN_ON_ONCE(wq->flush_color != next->flush_color);
3978 list_del_init(&next->list);
3979 wq->first_flusher = next;
3981 if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
3985 * Meh... this color is already done, clear first
3986 * flusher and repeat cascading.
3988 wq->first_flusher = NULL;
3992 mutex_unlock(&wq->mutex);
3994 EXPORT_SYMBOL(__flush_workqueue);
3997 * drain_workqueue - drain a workqueue
3998 * @wq: workqueue to drain
4000 * Wait until the workqueue becomes empty. While draining is in progress,
4001 * only chain queueing is allowed. IOW, only currently pending or running
4002 * work items on @wq can queue further work items on it. @wq is flushed
4003 * repeatedly until it becomes empty. The number of flushing is determined
4004 * by the depth of chaining and should be relatively short. Whine if it
4007 void drain_workqueue(struct workqueue_struct *wq)
4009 unsigned int flush_cnt = 0;
4010 struct pool_workqueue *pwq;
4013 * __queue_work() needs to test whether there are drainers, is much
4014 * hotter than drain_workqueue() and already looks at @wq->flags.
4015 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
4017 mutex_lock(&wq->mutex);
4018 if (!wq->nr_drainers++)
4019 wq->flags |= __WQ_DRAINING;
4020 mutex_unlock(&wq->mutex);
4022 __flush_workqueue(wq);
4024 mutex_lock(&wq->mutex);
4026 for_each_pwq(pwq, wq) {
4029 raw_spin_lock_irq(&pwq->pool->lock);
4030 drained = pwq_is_empty(pwq);
4031 raw_spin_unlock_irq(&pwq->pool->lock);
4036 if (++flush_cnt == 10 ||
4037 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
4038 pr_warn("workqueue %s: %s() isn't complete after %u tries\n",
4039 wq->name, __func__, flush_cnt);
4041 mutex_unlock(&wq->mutex);
4045 if (!--wq->nr_drainers)
4046 wq->flags &= ~__WQ_DRAINING;
4047 mutex_unlock(&wq->mutex);
4049 EXPORT_SYMBOL_GPL(drain_workqueue);
4051 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
4054 struct worker *worker = NULL;
4055 struct worker_pool *pool;
4056 struct pool_workqueue *pwq;
4057 struct workqueue_struct *wq;
4062 pool = get_work_pool(work);
4068 raw_spin_lock_irq(&pool->lock);
4069 /* see the comment in try_to_grab_pending() with the same code */
4070 pwq = get_work_pwq(work);
4072 if (unlikely(pwq->pool != pool))
4075 worker = find_worker_executing_work(pool, work);
4078 pwq = worker->current_pwq;
4082 check_flush_dependency(wq, work);
4084 insert_wq_barrier(pwq, barr, work, worker);
4085 raw_spin_unlock_irq(&pool->lock);
4087 touch_work_lockdep_map(work, wq);
4090 * Force a lock recursion deadlock when using flush_work() inside a
4091 * single-threaded or rescuer equipped workqueue.
4093 * For single threaded workqueues the deadlock happens when the work
4094 * is after the work issuing the flush_work(). For rescuer equipped
4095 * workqueues the deadlock happens when the rescuer stalls, blocking
4098 if (!from_cancel && (wq->saved_max_active == 1 || wq->rescuer))
4099 touch_wq_lockdep_map(wq);
4104 raw_spin_unlock_irq(&pool->lock);
4109 static bool __flush_work(struct work_struct *work, bool from_cancel)
4111 struct wq_barrier barr;
4113 if (WARN_ON(!wq_online))
4116 if (WARN_ON(!work->func))
4119 if (start_flush_work(work, &barr, from_cancel)) {
4120 wait_for_completion(&barr.done);
4121 destroy_work_on_stack(&barr.work);
4129 * flush_work - wait for a work to finish executing the last queueing instance
4130 * @work: the work to flush
4132 * Wait until @work has finished execution. @work is guaranteed to be idle
4133 * on return if it hasn't been requeued since flush started.
4136 * %true if flush_work() waited for the work to finish execution,
4137 * %false if it was already idle.
4139 bool flush_work(struct work_struct *work)
4141 return __flush_work(work, false);
4143 EXPORT_SYMBOL_GPL(flush_work);
4146 * flush_delayed_work - wait for a dwork to finish executing the last queueing
4147 * @dwork: the delayed work to flush
4149 * Delayed timer is cancelled and the pending work is queued for
4150 * immediate execution. Like flush_work(), this function only
4151 * considers the last queueing instance of @dwork.
4154 * %true if flush_work() waited for the work to finish execution,
4155 * %false if it was already idle.
4157 bool flush_delayed_work(struct delayed_work *dwork)
4159 local_irq_disable();
4160 if (del_timer_sync(&dwork->timer))
4161 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
4163 return flush_work(&dwork->work);
4165 EXPORT_SYMBOL(flush_delayed_work);
4168 * flush_rcu_work - wait for a rwork to finish executing the last queueing
4169 * @rwork: the rcu work to flush
4172 * %true if flush_rcu_work() waited for the work to finish execution,
4173 * %false if it was already idle.
4175 bool flush_rcu_work(struct rcu_work *rwork)
4177 if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
4179 flush_work(&rwork->work);
4182 return flush_work(&rwork->work);
4185 EXPORT_SYMBOL(flush_rcu_work);
4187 static bool __cancel_work(struct work_struct *work, u32 cflags)
4189 unsigned long irq_flags;
4193 ret = try_to_grab_pending(work, cflags, &irq_flags);
4194 } while (unlikely(ret == -EAGAIN));
4196 if (unlikely(ret < 0))
4199 set_work_pool_and_clear_pending(work, get_work_pool_id(work), 0);
4200 local_irq_restore(irq_flags);
4204 static bool __cancel_work_sync(struct work_struct *work, u32 cflags)
4206 unsigned long irq_flags;
4209 /* claim @work and tell other tasks trying to grab @work to back off */
4210 ret = work_grab_pending(work, cflags, &irq_flags);
4211 mark_work_canceling(work);
4212 local_irq_restore(irq_flags);
4215 * Skip __flush_work() during early boot when we know that @work isn't
4216 * executing. This allows canceling during early boot.
4219 __flush_work(work, true);
4222 * smp_mb() at the end of set_work_pool_and_clear_pending() is paired
4223 * with prepare_to_wait() above so that either waitqueue_active() is
4224 * visible here or !work_is_canceling() is visible there.
4226 set_work_pool_and_clear_pending(work, WORK_OFFQ_POOL_NONE, 0);
4228 if (waitqueue_active(&wq_cancel_waitq))
4229 __wake_up(&wq_cancel_waitq, TASK_NORMAL, 1, work);
4235 * See cancel_delayed_work()
4237 bool cancel_work(struct work_struct *work)
4239 return __cancel_work(work, 0);
4241 EXPORT_SYMBOL(cancel_work);
4244 * cancel_work_sync - cancel a work and wait for it to finish
4245 * @work: the work to cancel
4247 * Cancel @work and wait for its execution to finish. This function
4248 * can be used even if the work re-queues itself or migrates to
4249 * another workqueue. On return from this function, @work is
4250 * guaranteed to be not pending or executing on any CPU.
4252 * cancel_work_sync(&delayed_work->work) must not be used for
4253 * delayed_work's. Use cancel_delayed_work_sync() instead.
4255 * The caller must ensure that the workqueue on which @work was last
4256 * queued can't be destroyed before this function returns.
4259 * %true if @work was pending, %false otherwise.
4261 bool cancel_work_sync(struct work_struct *work)
4263 return __cancel_work_sync(work, 0);
4265 EXPORT_SYMBOL_GPL(cancel_work_sync);
4268 * cancel_delayed_work - cancel a delayed work
4269 * @dwork: delayed_work to cancel
4271 * Kill off a pending delayed_work.
4273 * Return: %true if @dwork was pending and canceled; %false if it wasn't
4277 * The work callback function may still be running on return, unless
4278 * it returns %true and the work doesn't re-arm itself. Explicitly flush or
4279 * use cancel_delayed_work_sync() to wait on it.
4281 * This function is safe to call from any context including IRQ handler.
4283 bool cancel_delayed_work(struct delayed_work *dwork)
4285 return __cancel_work(&dwork->work, WORK_CANCEL_DELAYED);
4287 EXPORT_SYMBOL(cancel_delayed_work);
4290 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
4291 * @dwork: the delayed work cancel
4293 * This is cancel_work_sync() for delayed works.
4296 * %true if @dwork was pending, %false otherwise.
4298 bool cancel_delayed_work_sync(struct delayed_work *dwork)
4300 return __cancel_work_sync(&dwork->work, WORK_CANCEL_DELAYED);
4302 EXPORT_SYMBOL(cancel_delayed_work_sync);
4305 * schedule_on_each_cpu - execute a function synchronously on each online CPU
4306 * @func: the function to call
4308 * schedule_on_each_cpu() executes @func on each online CPU using the
4309 * system workqueue and blocks until all CPUs have completed.
4310 * schedule_on_each_cpu() is very slow.
4313 * 0 on success, -errno on failure.
4315 int schedule_on_each_cpu(work_func_t func)
4318 struct work_struct __percpu *works;
4320 works = alloc_percpu(struct work_struct);
4326 for_each_online_cpu(cpu) {
4327 struct work_struct *work = per_cpu_ptr(works, cpu);
4329 INIT_WORK(work, func);
4330 schedule_work_on(cpu, work);
4333 for_each_online_cpu(cpu)
4334 flush_work(per_cpu_ptr(works, cpu));
4342 * execute_in_process_context - reliably execute the routine with user context
4343 * @fn: the function to execute
4344 * @ew: guaranteed storage for the execute work structure (must
4345 * be available when the work executes)
4347 * Executes the function immediately if process context is available,
4348 * otherwise schedules the function for delayed execution.
4350 * Return: 0 - function was executed
4351 * 1 - function was scheduled for execution
4353 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
4355 if (!in_interrupt()) {
4360 INIT_WORK(&ew->work, fn);
4361 schedule_work(&ew->work);
4365 EXPORT_SYMBOL_GPL(execute_in_process_context);
4368 * free_workqueue_attrs - free a workqueue_attrs
4369 * @attrs: workqueue_attrs to free
4371 * Undo alloc_workqueue_attrs().
4373 void free_workqueue_attrs(struct workqueue_attrs *attrs)
4376 free_cpumask_var(attrs->cpumask);
4377 free_cpumask_var(attrs->__pod_cpumask);
4383 * alloc_workqueue_attrs - allocate a workqueue_attrs
4385 * Allocate a new workqueue_attrs, initialize with default settings and
4388 * Return: The allocated new workqueue_attr on success. %NULL on failure.
4390 struct workqueue_attrs *alloc_workqueue_attrs(void)
4392 struct workqueue_attrs *attrs;
4394 attrs = kzalloc(sizeof(*attrs), GFP_KERNEL);
4397 if (!alloc_cpumask_var(&attrs->cpumask, GFP_KERNEL))
4399 if (!alloc_cpumask_var(&attrs->__pod_cpumask, GFP_KERNEL))
4402 cpumask_copy(attrs->cpumask, cpu_possible_mask);
4403 attrs->affn_scope = WQ_AFFN_DFL;
4406 free_workqueue_attrs(attrs);
4410 static void copy_workqueue_attrs(struct workqueue_attrs *to,
4411 const struct workqueue_attrs *from)
4413 to->nice = from->nice;
4414 cpumask_copy(to->cpumask, from->cpumask);
4415 cpumask_copy(to->__pod_cpumask, from->__pod_cpumask);
4416 to->affn_strict = from->affn_strict;
4419 * Unlike hash and equality test, copying shouldn't ignore wq-only
4420 * fields as copying is used for both pool and wq attrs. Instead,
4421 * get_unbound_pool() explicitly clears the fields.
4423 to->affn_scope = from->affn_scope;
4424 to->ordered = from->ordered;
4428 * Some attrs fields are workqueue-only. Clear them for worker_pool's. See the
4429 * comments in 'struct workqueue_attrs' definition.
4431 static void wqattrs_clear_for_pool(struct workqueue_attrs *attrs)
4433 attrs->affn_scope = WQ_AFFN_NR_TYPES;
4434 attrs->ordered = false;
4437 /* hash value of the content of @attr */
4438 static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
4442 hash = jhash_1word(attrs->nice, hash);
4443 hash = jhash(cpumask_bits(attrs->cpumask),
4444 BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
4445 hash = jhash(cpumask_bits(attrs->__pod_cpumask),
4446 BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
4447 hash = jhash_1word(attrs->affn_strict, hash);
4451 /* content equality test */
4452 static bool wqattrs_equal(const struct workqueue_attrs *a,
4453 const struct workqueue_attrs *b)
4455 if (a->nice != b->nice)
4457 if (!cpumask_equal(a->cpumask, b->cpumask))
4459 if (!cpumask_equal(a->__pod_cpumask, b->__pod_cpumask))
4461 if (a->affn_strict != b->affn_strict)
4466 /* Update @attrs with actually available CPUs */
4467 static void wqattrs_actualize_cpumask(struct workqueue_attrs *attrs,
4468 const cpumask_t *unbound_cpumask)
4471 * Calculate the effective CPU mask of @attrs given @unbound_cpumask. If
4472 * @attrs->cpumask doesn't overlap with @unbound_cpumask, we fallback to
4475 cpumask_and(attrs->cpumask, attrs->cpumask, unbound_cpumask);
4476 if (unlikely(cpumask_empty(attrs->cpumask)))
4477 cpumask_copy(attrs->cpumask, unbound_cpumask);
4480 /* find wq_pod_type to use for @attrs */
4481 static const struct wq_pod_type *
4482 wqattrs_pod_type(const struct workqueue_attrs *attrs)
4484 enum wq_affn_scope scope;
4485 struct wq_pod_type *pt;
4487 /* to synchronize access to wq_affn_dfl */
4488 lockdep_assert_held(&wq_pool_mutex);
4490 if (attrs->affn_scope == WQ_AFFN_DFL)
4491 scope = wq_affn_dfl;
4493 scope = attrs->affn_scope;
4495 pt = &wq_pod_types[scope];
4497 if (!WARN_ON_ONCE(attrs->affn_scope == WQ_AFFN_NR_TYPES) &&
4498 likely(pt->nr_pods))
4502 * Before workqueue_init_topology(), only SYSTEM is available which is
4503 * initialized in workqueue_init_early().
4505 pt = &wq_pod_types[WQ_AFFN_SYSTEM];
4506 BUG_ON(!pt->nr_pods);
4511 * init_worker_pool - initialize a newly zalloc'd worker_pool
4512 * @pool: worker_pool to initialize
4514 * Initialize a newly zalloc'd @pool. It also allocates @pool->attrs.
4516 * Return: 0 on success, -errno on failure. Even on failure, all fields
4517 * inside @pool proper are initialized and put_unbound_pool() can be called
4518 * on @pool safely to release it.
4520 static int init_worker_pool(struct worker_pool *pool)
4522 raw_spin_lock_init(&pool->lock);
4525 pool->node = NUMA_NO_NODE;
4526 pool->flags |= POOL_DISASSOCIATED;
4527 pool->watchdog_ts = jiffies;
4528 INIT_LIST_HEAD(&pool->worklist);
4529 INIT_LIST_HEAD(&pool->idle_list);
4530 hash_init(pool->busy_hash);
4532 timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
4533 INIT_WORK(&pool->idle_cull_work, idle_cull_fn);
4535 timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
4537 INIT_LIST_HEAD(&pool->workers);
4538 INIT_LIST_HEAD(&pool->dying_workers);
4540 ida_init(&pool->worker_ida);
4541 INIT_HLIST_NODE(&pool->hash_node);
4544 /* shouldn't fail above this point */
4545 pool->attrs = alloc_workqueue_attrs();
4549 wqattrs_clear_for_pool(pool->attrs);
4554 #ifdef CONFIG_LOCKDEP
4555 static void wq_init_lockdep(struct workqueue_struct *wq)
4559 lockdep_register_key(&wq->key);
4560 lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name);
4562 lock_name = wq->name;
4564 wq->lock_name = lock_name;
4565 lockdep_init_map(&wq->lockdep_map, lock_name, &wq->key, 0);
4568 static void wq_unregister_lockdep(struct workqueue_struct *wq)
4570 lockdep_unregister_key(&wq->key);
4573 static void wq_free_lockdep(struct workqueue_struct *wq)
4575 if (wq->lock_name != wq->name)
4576 kfree(wq->lock_name);
4579 static void wq_init_lockdep(struct workqueue_struct *wq)
4583 static void wq_unregister_lockdep(struct workqueue_struct *wq)
4587 static void wq_free_lockdep(struct workqueue_struct *wq)
4592 static void free_node_nr_active(struct wq_node_nr_active **nna_ar)
4596 for_each_node(node) {
4597 kfree(nna_ar[node]);
4598 nna_ar[node] = NULL;
4601 kfree(nna_ar[nr_node_ids]);
4602 nna_ar[nr_node_ids] = NULL;
4605 static void init_node_nr_active(struct wq_node_nr_active *nna)
4607 nna->max = WQ_DFL_MIN_ACTIVE;
4608 atomic_set(&nna->nr, 0);
4609 raw_spin_lock_init(&nna->lock);
4610 INIT_LIST_HEAD(&nna->pending_pwqs);
4614 * Each node's nr_active counter will be accessed mostly from its own node and
4615 * should be allocated in the node.
4617 static int alloc_node_nr_active(struct wq_node_nr_active **nna_ar)
4619 struct wq_node_nr_active *nna;
4622 for_each_node(node) {
4623 nna = kzalloc_node(sizeof(*nna), GFP_KERNEL, node);
4626 init_node_nr_active(nna);
4630 /* [nr_node_ids] is used as the fallback */
4631 nna = kzalloc_node(sizeof(*nna), GFP_KERNEL, NUMA_NO_NODE);
4634 init_node_nr_active(nna);
4635 nna_ar[nr_node_ids] = nna;
4640 free_node_nr_active(nna_ar);
4644 static void rcu_free_wq(struct rcu_head *rcu)
4646 struct workqueue_struct *wq =
4647 container_of(rcu, struct workqueue_struct, rcu);
4649 if (wq->flags & WQ_UNBOUND)
4650 free_node_nr_active(wq->node_nr_active);
4652 wq_free_lockdep(wq);
4653 free_percpu(wq->cpu_pwq);
4654 free_workqueue_attrs(wq->unbound_attrs);
4658 static void rcu_free_pool(struct rcu_head *rcu)
4660 struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
4662 ida_destroy(&pool->worker_ida);
4663 free_workqueue_attrs(pool->attrs);
4668 * put_unbound_pool - put a worker_pool
4669 * @pool: worker_pool to put
4671 * Put @pool. If its refcnt reaches zero, it gets destroyed in RCU
4672 * safe manner. get_unbound_pool() calls this function on its failure path
4673 * and this function should be able to release pools which went through,
4674 * successfully or not, init_worker_pool().
4676 * Should be called with wq_pool_mutex held.
4678 static void put_unbound_pool(struct worker_pool *pool)
4680 DECLARE_COMPLETION_ONSTACK(detach_completion);
4681 struct worker *worker;
4682 LIST_HEAD(cull_list);
4684 lockdep_assert_held(&wq_pool_mutex);
4690 if (WARN_ON(!(pool->cpu < 0)) ||
4691 WARN_ON(!list_empty(&pool->worklist)))
4694 /* release id and unhash */
4696 idr_remove(&worker_pool_idr, pool->id);
4697 hash_del(&pool->hash_node);
4700 * Become the manager and destroy all workers. This prevents
4701 * @pool's workers from blocking on attach_mutex. We're the last
4702 * manager and @pool gets freed with the flag set.
4704 * Having a concurrent manager is quite unlikely to happen as we can
4705 * only get here with
4706 * pwq->refcnt == pool->refcnt == 0
4707 * which implies no work queued to the pool, which implies no worker can
4708 * become the manager. However a worker could have taken the role of
4709 * manager before the refcnts dropped to 0, since maybe_create_worker()
4713 rcuwait_wait_event(&manager_wait,
4714 !(pool->flags & POOL_MANAGER_ACTIVE),
4715 TASK_UNINTERRUPTIBLE);
4717 mutex_lock(&wq_pool_attach_mutex);
4718 raw_spin_lock_irq(&pool->lock);
4719 if (!(pool->flags & POOL_MANAGER_ACTIVE)) {
4720 pool->flags |= POOL_MANAGER_ACTIVE;
4723 raw_spin_unlock_irq(&pool->lock);
4724 mutex_unlock(&wq_pool_attach_mutex);
4727 while ((worker = first_idle_worker(pool)))
4728 set_worker_dying(worker, &cull_list);
4729 WARN_ON(pool->nr_workers || pool->nr_idle);
4730 raw_spin_unlock_irq(&pool->lock);
4732 wake_dying_workers(&cull_list);
4734 if (!list_empty(&pool->workers) || !list_empty(&pool->dying_workers))
4735 pool->detach_completion = &detach_completion;
4736 mutex_unlock(&wq_pool_attach_mutex);
4738 if (pool->detach_completion)
4739 wait_for_completion(pool->detach_completion);
4741 /* shut down the timers */
4742 del_timer_sync(&pool->idle_timer);
4743 cancel_work_sync(&pool->idle_cull_work);
4744 del_timer_sync(&pool->mayday_timer);
4746 /* RCU protected to allow dereferences from get_work_pool() */
4747 call_rcu(&pool->rcu, rcu_free_pool);
4751 * get_unbound_pool - get a worker_pool with the specified attributes
4752 * @attrs: the attributes of the worker_pool to get
4754 * Obtain a worker_pool which has the same attributes as @attrs, bump the
4755 * reference count and return it. If there already is a matching
4756 * worker_pool, it will be used; otherwise, this function attempts to
4759 * Should be called with wq_pool_mutex held.
4761 * Return: On success, a worker_pool with the same attributes as @attrs.
4762 * On failure, %NULL.
4764 static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
4766 struct wq_pod_type *pt = &wq_pod_types[WQ_AFFN_NUMA];
4767 u32 hash = wqattrs_hash(attrs);
4768 struct worker_pool *pool;
4769 int pod, node = NUMA_NO_NODE;
4771 lockdep_assert_held(&wq_pool_mutex);
4773 /* do we already have a matching pool? */
4774 hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
4775 if (wqattrs_equal(pool->attrs, attrs)) {
4781 /* If __pod_cpumask is contained inside a NUMA pod, that's our node */
4782 for (pod = 0; pod < pt->nr_pods; pod++) {
4783 if (cpumask_subset(attrs->__pod_cpumask, pt->pod_cpus[pod])) {
4784 node = pt->pod_node[pod];
4789 /* nope, create a new one */
4790 pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, node);
4791 if (!pool || init_worker_pool(pool) < 0)
4795 copy_workqueue_attrs(pool->attrs, attrs);
4796 wqattrs_clear_for_pool(pool->attrs);
4798 if (worker_pool_assign_id(pool) < 0)
4801 /* create and start the initial worker */
4802 if (wq_online && !create_worker(pool))
4806 hash_add(unbound_pool_hash, &pool->hash_node, hash);
4811 put_unbound_pool(pool);
4815 static void rcu_free_pwq(struct rcu_head *rcu)
4817 kmem_cache_free(pwq_cache,
4818 container_of(rcu, struct pool_workqueue, rcu));
4822 * Scheduled on pwq_release_worker by put_pwq() when an unbound pwq hits zero
4823 * refcnt and needs to be destroyed.
4825 static void pwq_release_workfn(struct kthread_work *work)
4827 struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
4829 struct workqueue_struct *wq = pwq->wq;
4830 struct worker_pool *pool = pwq->pool;
4831 bool is_last = false;
4834 * When @pwq is not linked, it doesn't hold any reference to the
4835 * @wq, and @wq is invalid to access.
4837 if (!list_empty(&pwq->pwqs_node)) {
4838 mutex_lock(&wq->mutex);
4839 list_del_rcu(&pwq->pwqs_node);
4840 is_last = list_empty(&wq->pwqs);
4843 * For ordered workqueue with a plugged dfl_pwq, restart it now.
4845 if (!is_last && (wq->flags & __WQ_ORDERED))
4846 unplug_oldest_pwq(wq);
4848 mutex_unlock(&wq->mutex);
4851 if (wq->flags & WQ_UNBOUND) {
4852 mutex_lock(&wq_pool_mutex);
4853 put_unbound_pool(pool);
4854 mutex_unlock(&wq_pool_mutex);
4857 if (!list_empty(&pwq->pending_node)) {
4858 struct wq_node_nr_active *nna =
4859 wq_node_nr_active(pwq->wq, pwq->pool->node);
4861 raw_spin_lock_irq(&nna->lock);
4862 list_del_init(&pwq->pending_node);
4863 raw_spin_unlock_irq(&nna->lock);
4866 call_rcu(&pwq->rcu, rcu_free_pwq);
4869 * If we're the last pwq going away, @wq is already dead and no one
4870 * is gonna access it anymore. Schedule RCU free.
4873 wq_unregister_lockdep(wq);
4874 call_rcu(&wq->rcu, rcu_free_wq);
4878 /* initialize newly allocated @pwq which is associated with @wq and @pool */
4879 static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
4880 struct worker_pool *pool)
4882 BUG_ON((unsigned long)pwq & ~WORK_STRUCT_PWQ_MASK);
4884 memset(pwq, 0, sizeof(*pwq));
4888 pwq->flush_color = -1;
4890 INIT_LIST_HEAD(&pwq->inactive_works);
4891 INIT_LIST_HEAD(&pwq->pending_node);
4892 INIT_LIST_HEAD(&pwq->pwqs_node);
4893 INIT_LIST_HEAD(&pwq->mayday_node);
4894 kthread_init_work(&pwq->release_work, pwq_release_workfn);
4897 /* sync @pwq with the current state of its associated wq and link it */
4898 static void link_pwq(struct pool_workqueue *pwq)
4900 struct workqueue_struct *wq = pwq->wq;
4902 lockdep_assert_held(&wq->mutex);
4904 /* may be called multiple times, ignore if already linked */
4905 if (!list_empty(&pwq->pwqs_node))
4908 /* set the matching work_color */
4909 pwq->work_color = wq->work_color;
4912 list_add_tail_rcu(&pwq->pwqs_node, &wq->pwqs);
4915 /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
4916 static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
4917 const struct workqueue_attrs *attrs)
4919 struct worker_pool *pool;
4920 struct pool_workqueue *pwq;
4922 lockdep_assert_held(&wq_pool_mutex);
4924 pool = get_unbound_pool(attrs);
4928 pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
4930 put_unbound_pool(pool);
4934 init_pwq(pwq, wq, pool);
4939 * wq_calc_pod_cpumask - calculate a wq_attrs' cpumask for a pod
4940 * @attrs: the wq_attrs of the default pwq of the target workqueue
4941 * @cpu: the target CPU
4942 * @cpu_going_down: if >= 0, the CPU to consider as offline
4944 * Calculate the cpumask a workqueue with @attrs should use on @pod. If
4945 * @cpu_going_down is >= 0, that cpu is considered offline during calculation.
4946 * The result is stored in @attrs->__pod_cpumask.
4948 * If pod affinity is not enabled, @attrs->cpumask is always used. If enabled
4949 * and @pod has online CPUs requested by @attrs, the returned cpumask is the
4950 * intersection of the possible CPUs of @pod and @attrs->cpumask.
4952 * The caller is responsible for ensuring that the cpumask of @pod stays stable.
4954 static void wq_calc_pod_cpumask(struct workqueue_attrs *attrs, int cpu,
4957 const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
4958 int pod = pt->cpu_pod[cpu];
4960 /* does @pod have any online CPUs @attrs wants? */
4961 cpumask_and(attrs->__pod_cpumask, pt->pod_cpus[pod], attrs->cpumask);
4962 cpumask_and(attrs->__pod_cpumask, attrs->__pod_cpumask, cpu_online_mask);
4963 if (cpu_going_down >= 0)
4964 cpumask_clear_cpu(cpu_going_down, attrs->__pod_cpumask);
4966 if (cpumask_empty(attrs->__pod_cpumask)) {
4967 cpumask_copy(attrs->__pod_cpumask, attrs->cpumask);
4971 /* yeap, return possible CPUs in @pod that @attrs wants */
4972 cpumask_and(attrs->__pod_cpumask, attrs->cpumask, pt->pod_cpus[pod]);
4974 if (cpumask_empty(attrs->__pod_cpumask))
4975 pr_warn_once("WARNING: workqueue cpumask: online intersect > "
4976 "possible intersect\n");
4979 /* install @pwq into @wq and return the old pwq, @cpu < 0 for dfl_pwq */
4980 static struct pool_workqueue *install_unbound_pwq(struct workqueue_struct *wq,
4981 int cpu, struct pool_workqueue *pwq)
4983 struct pool_workqueue __rcu **slot = unbound_pwq_slot(wq, cpu);
4984 struct pool_workqueue *old_pwq;
4986 lockdep_assert_held(&wq_pool_mutex);
4987 lockdep_assert_held(&wq->mutex);
4989 /* link_pwq() can handle duplicate calls */
4992 old_pwq = rcu_access_pointer(*slot);
4993 rcu_assign_pointer(*slot, pwq);
4997 /* context to store the prepared attrs & pwqs before applying */
4998 struct apply_wqattrs_ctx {
4999 struct workqueue_struct *wq; /* target workqueue */
5000 struct workqueue_attrs *attrs; /* attrs to apply */
5001 struct list_head list; /* queued for batching commit */
5002 struct pool_workqueue *dfl_pwq;
5003 struct pool_workqueue *pwq_tbl[];
5006 /* free the resources after success or abort */
5007 static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
5012 for_each_possible_cpu(cpu)
5013 put_pwq_unlocked(ctx->pwq_tbl[cpu]);
5014 put_pwq_unlocked(ctx->dfl_pwq);
5016 free_workqueue_attrs(ctx->attrs);
5022 /* allocate the attrs and pwqs for later installation */
5023 static struct apply_wqattrs_ctx *
5024 apply_wqattrs_prepare(struct workqueue_struct *wq,
5025 const struct workqueue_attrs *attrs,
5026 const cpumask_var_t unbound_cpumask)
5028 struct apply_wqattrs_ctx *ctx;
5029 struct workqueue_attrs *new_attrs;
5032 lockdep_assert_held(&wq_pool_mutex);
5034 if (WARN_ON(attrs->affn_scope < 0 ||
5035 attrs->affn_scope >= WQ_AFFN_NR_TYPES))
5036 return ERR_PTR(-EINVAL);
5038 ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_cpu_ids), GFP_KERNEL);
5040 new_attrs = alloc_workqueue_attrs();
5041 if (!ctx || !new_attrs)
5045 * If something goes wrong during CPU up/down, we'll fall back to
5046 * the default pwq covering whole @attrs->cpumask. Always create
5047 * it even if we don't use it immediately.
5049 copy_workqueue_attrs(new_attrs, attrs);
5050 wqattrs_actualize_cpumask(new_attrs, unbound_cpumask);
5051 cpumask_copy(new_attrs->__pod_cpumask, new_attrs->cpumask);
5052 ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
5056 for_each_possible_cpu(cpu) {
5057 if (new_attrs->ordered) {
5058 ctx->dfl_pwq->refcnt++;
5059 ctx->pwq_tbl[cpu] = ctx->dfl_pwq;
5061 wq_calc_pod_cpumask(new_attrs, cpu, -1);
5062 ctx->pwq_tbl[cpu] = alloc_unbound_pwq(wq, new_attrs);
5063 if (!ctx->pwq_tbl[cpu])
5068 /* save the user configured attrs and sanitize it. */
5069 copy_workqueue_attrs(new_attrs, attrs);
5070 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
5071 cpumask_copy(new_attrs->__pod_cpumask, new_attrs->cpumask);
5072 ctx->attrs = new_attrs;
5075 * For initialized ordered workqueues, there should only be one pwq
5076 * (dfl_pwq). Set the plugged flag of ctx->dfl_pwq to suspend execution
5077 * of newly queued work items until execution of older work items in
5078 * the old pwq's have completed.
5080 if ((wq->flags & __WQ_ORDERED) && !list_empty(&wq->pwqs))
5081 ctx->dfl_pwq->plugged = true;
5087 free_workqueue_attrs(new_attrs);
5088 apply_wqattrs_cleanup(ctx);
5089 return ERR_PTR(-ENOMEM);
5092 /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
5093 static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
5097 /* all pwqs have been created successfully, let's install'em */
5098 mutex_lock(&ctx->wq->mutex);
5100 copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
5102 /* save the previous pwqs and install the new ones */
5103 for_each_possible_cpu(cpu)
5104 ctx->pwq_tbl[cpu] = install_unbound_pwq(ctx->wq, cpu,
5106 ctx->dfl_pwq = install_unbound_pwq(ctx->wq, -1, ctx->dfl_pwq);
5108 /* update node_nr_active->max */
5109 wq_update_node_max_active(ctx->wq, -1);
5111 /* rescuer needs to respect wq cpumask changes */
5112 if (ctx->wq->rescuer)
5113 set_cpus_allowed_ptr(ctx->wq->rescuer->task,
5114 unbound_effective_cpumask(ctx->wq));
5116 mutex_unlock(&ctx->wq->mutex);
5119 static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
5120 const struct workqueue_attrs *attrs)
5122 struct apply_wqattrs_ctx *ctx;
5124 /* only unbound workqueues can change attributes */
5125 if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
5128 ctx = apply_wqattrs_prepare(wq, attrs, wq_unbound_cpumask);
5130 return PTR_ERR(ctx);
5132 /* the ctx has been prepared successfully, let's commit it */
5133 apply_wqattrs_commit(ctx);
5134 apply_wqattrs_cleanup(ctx);
5140 * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
5141 * @wq: the target workqueue
5142 * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
5144 * Apply @attrs to an unbound workqueue @wq. Unless disabled, this function maps
5145 * a separate pwq to each CPU pod with possibles CPUs in @attrs->cpumask so that
5146 * work items are affine to the pod it was issued on. Older pwqs are released as
5147 * in-flight work items finish. Note that a work item which repeatedly requeues
5148 * itself back-to-back will stay on its current pwq.
5150 * Performs GFP_KERNEL allocations.
5152 * Assumes caller has CPU hotplug read exclusion, i.e. cpus_read_lock().
5154 * Return: 0 on success and -errno on failure.
5156 int apply_workqueue_attrs(struct workqueue_struct *wq,
5157 const struct workqueue_attrs *attrs)
5161 lockdep_assert_cpus_held();
5163 mutex_lock(&wq_pool_mutex);
5164 ret = apply_workqueue_attrs_locked(wq, attrs);
5165 mutex_unlock(&wq_pool_mutex);
5171 * wq_update_pod - update pod affinity of a wq for CPU hot[un]plug
5172 * @wq: the target workqueue
5173 * @cpu: the CPU to update pool association for
5174 * @hotplug_cpu: the CPU coming up or going down
5175 * @online: whether @cpu is coming up or going down
5177 * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
5178 * %CPU_DOWN_FAILED. @cpu is being hot[un]plugged, update pod affinity of
5182 * If pod affinity can't be adjusted due to memory allocation failure, it falls
5183 * back to @wq->dfl_pwq which may not be optimal but is always correct.
5185 * Note that when the last allowed CPU of a pod goes offline for a workqueue
5186 * with a cpumask spanning multiple pods, the workers which were already
5187 * executing the work items for the workqueue will lose their CPU affinity and
5188 * may execute on any CPU. This is similar to how per-cpu workqueues behave on
5189 * CPU_DOWN. If a workqueue user wants strict affinity, it's the user's
5190 * responsibility to flush the work item from CPU_DOWN_PREPARE.
5192 static void wq_update_pod(struct workqueue_struct *wq, int cpu,
5193 int hotplug_cpu, bool online)
5195 int off_cpu = online ? -1 : hotplug_cpu;
5196 struct pool_workqueue *old_pwq = NULL, *pwq;
5197 struct workqueue_attrs *target_attrs;
5199 lockdep_assert_held(&wq_pool_mutex);
5201 if (!(wq->flags & WQ_UNBOUND) || wq->unbound_attrs->ordered)
5205 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
5206 * Let's use a preallocated one. The following buf is protected by
5207 * CPU hotplug exclusion.
5209 target_attrs = wq_update_pod_attrs_buf;
5211 copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
5212 wqattrs_actualize_cpumask(target_attrs, wq_unbound_cpumask);
5214 /* nothing to do if the target cpumask matches the current pwq */
5215 wq_calc_pod_cpumask(target_attrs, cpu, off_cpu);
5216 if (wqattrs_equal(target_attrs, unbound_pwq(wq, cpu)->pool->attrs))
5219 /* create a new pwq */
5220 pwq = alloc_unbound_pwq(wq, target_attrs);
5222 pr_warn("workqueue: allocation failed while updating CPU pod affinity of \"%s\"\n",
5227 /* Install the new pwq. */
5228 mutex_lock(&wq->mutex);
5229 old_pwq = install_unbound_pwq(wq, cpu, pwq);
5233 mutex_lock(&wq->mutex);
5234 pwq = unbound_pwq(wq, -1);
5235 raw_spin_lock_irq(&pwq->pool->lock);
5237 raw_spin_unlock_irq(&pwq->pool->lock);
5238 old_pwq = install_unbound_pwq(wq, cpu, pwq);
5240 mutex_unlock(&wq->mutex);
5241 put_pwq_unlocked(old_pwq);
5244 static int alloc_and_link_pwqs(struct workqueue_struct *wq)
5246 bool highpri = wq->flags & WQ_HIGHPRI;
5249 wq->cpu_pwq = alloc_percpu(struct pool_workqueue *);
5253 if (!(wq->flags & WQ_UNBOUND)) {
5254 for_each_possible_cpu(cpu) {
5255 struct pool_workqueue **pwq_p;
5256 struct worker_pool __percpu *pools;
5257 struct worker_pool *pool;
5259 if (wq->flags & WQ_BH)
5260 pools = bh_worker_pools;
5262 pools = cpu_worker_pools;
5264 pool = &(per_cpu_ptr(pools, cpu)[highpri]);
5265 pwq_p = per_cpu_ptr(wq->cpu_pwq, cpu);
5267 *pwq_p = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL,
5272 init_pwq(*pwq_p, wq, pool);
5274 mutex_lock(&wq->mutex);
5276 mutex_unlock(&wq->mutex);
5282 if (wq->flags & __WQ_ORDERED) {
5283 struct pool_workqueue *dfl_pwq;
5285 ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
5286 /* there should only be single pwq for ordering guarantee */
5287 dfl_pwq = rcu_access_pointer(wq->dfl_pwq);
5288 WARN(!ret && (wq->pwqs.next != &dfl_pwq->pwqs_node ||
5289 wq->pwqs.prev != &dfl_pwq->pwqs_node),
5290 "ordering guarantee broken for workqueue %s\n", wq->name);
5292 ret = apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
5296 /* for unbound pwq, flush the pwq_release_worker ensures that the
5297 * pwq_release_workfn() completes before calling kfree(wq).
5300 kthread_flush_worker(pwq_release_worker);
5306 for_each_possible_cpu(cpu) {
5307 struct pool_workqueue *pwq = *per_cpu_ptr(wq->cpu_pwq, cpu);
5310 kmem_cache_free(pwq_cache, pwq);
5312 free_percpu(wq->cpu_pwq);
5318 static int wq_clamp_max_active(int max_active, unsigned int flags,
5321 if (max_active < 1 || max_active > WQ_MAX_ACTIVE)
5322 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
5323 max_active, name, 1, WQ_MAX_ACTIVE);
5325 return clamp_val(max_active, 1, WQ_MAX_ACTIVE);
5329 * Workqueues which may be used during memory reclaim should have a rescuer
5330 * to guarantee forward progress.
5332 static int init_rescuer(struct workqueue_struct *wq)
5334 struct worker *rescuer;
5337 if (!(wq->flags & WQ_MEM_RECLAIM))
5340 rescuer = alloc_worker(NUMA_NO_NODE);
5342 pr_err("workqueue: Failed to allocate a rescuer for wq \"%s\"\n",
5347 rescuer->rescue_wq = wq;
5348 rescuer->task = kthread_create(rescuer_thread, rescuer, "kworker/R-%s", wq->name);
5349 if (IS_ERR(rescuer->task)) {
5350 ret = PTR_ERR(rescuer->task);
5351 pr_err("workqueue: Failed to create a rescuer kthread for wq \"%s\": %pe",
5352 wq->name, ERR_PTR(ret));
5357 wq->rescuer = rescuer;
5358 if (wq->flags & WQ_UNBOUND)
5359 kthread_bind_mask(rescuer->task, wq_unbound_cpumask);
5361 kthread_bind_mask(rescuer->task, cpu_possible_mask);
5362 wake_up_process(rescuer->task);
5368 * wq_adjust_max_active - update a wq's max_active to the current setting
5369 * @wq: target workqueue
5371 * If @wq isn't freezing, set @wq->max_active to the saved_max_active and
5372 * activate inactive work items accordingly. If @wq is freezing, clear
5373 * @wq->max_active to zero.
5375 static void wq_adjust_max_active(struct workqueue_struct *wq)
5378 int new_max, new_min;
5380 lockdep_assert_held(&wq->mutex);
5382 if ((wq->flags & WQ_FREEZABLE) && workqueue_freezing) {
5386 new_max = wq->saved_max_active;
5387 new_min = wq->saved_min_active;
5390 if (wq->max_active == new_max && wq->min_active == new_min)
5394 * Update @wq->max/min_active and then kick inactive work items if more
5395 * active work items are allowed. This doesn't break work item ordering
5396 * because new work items are always queued behind existing inactive
5397 * work items if there are any.
5399 WRITE_ONCE(wq->max_active, new_max);
5400 WRITE_ONCE(wq->min_active, new_min);
5402 if (wq->flags & WQ_UNBOUND)
5403 wq_update_node_max_active(wq, -1);
5409 * Round-robin through pwq's activating the first inactive work item
5410 * until max_active is filled.
5413 struct pool_workqueue *pwq;
5416 for_each_pwq(pwq, wq) {
5417 unsigned long irq_flags;
5419 /* can be called during early boot w/ irq disabled */
5420 raw_spin_lock_irqsave(&pwq->pool->lock, irq_flags);
5421 if (pwq_activate_first_inactive(pwq, true)) {
5423 kick_pool(pwq->pool);
5425 raw_spin_unlock_irqrestore(&pwq->pool->lock, irq_flags);
5427 } while (activated);
5431 struct workqueue_struct *alloc_workqueue(const char *fmt,
5433 int max_active, ...)
5436 struct workqueue_struct *wq;
5440 if (flags & WQ_BH) {
5441 if (WARN_ON_ONCE(flags & ~__WQ_BH_ALLOWS))
5443 if (WARN_ON_ONCE(max_active))
5447 /* see the comment above the definition of WQ_POWER_EFFICIENT */
5448 if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
5449 flags |= WQ_UNBOUND;
5451 /* allocate wq and format name */
5452 if (flags & WQ_UNBOUND)
5453 wq_size = struct_size(wq, node_nr_active, nr_node_ids + 1);
5455 wq_size = sizeof(*wq);
5457 wq = kzalloc(wq_size, GFP_KERNEL);
5461 if (flags & WQ_UNBOUND) {
5462 wq->unbound_attrs = alloc_workqueue_attrs();
5463 if (!wq->unbound_attrs)
5467 va_start(args, max_active);
5468 name_len = vsnprintf(wq->name, sizeof(wq->name), fmt, args);
5471 if (name_len >= WQ_NAME_LEN)
5472 pr_warn_once("workqueue: name exceeds WQ_NAME_LEN. Truncating to: %s\n",
5475 if (flags & WQ_BH) {
5477 * BH workqueues always share a single execution context per CPU
5478 * and don't impose any max_active limit.
5480 max_active = INT_MAX;
5482 max_active = max_active ?: WQ_DFL_ACTIVE;
5483 max_active = wq_clamp_max_active(max_active, flags, wq->name);
5488 wq->max_active = max_active;
5489 wq->min_active = min(max_active, WQ_DFL_MIN_ACTIVE);
5490 wq->saved_max_active = wq->max_active;
5491 wq->saved_min_active = wq->min_active;
5492 mutex_init(&wq->mutex);
5493 atomic_set(&wq->nr_pwqs_to_flush, 0);
5494 INIT_LIST_HEAD(&wq->pwqs);
5495 INIT_LIST_HEAD(&wq->flusher_queue);
5496 INIT_LIST_HEAD(&wq->flusher_overflow);
5497 INIT_LIST_HEAD(&wq->maydays);
5499 wq_init_lockdep(wq);
5500 INIT_LIST_HEAD(&wq->list);
5502 if (flags & WQ_UNBOUND) {
5503 if (alloc_node_nr_active(wq->node_nr_active) < 0)
5504 goto err_unreg_lockdep;
5507 if (alloc_and_link_pwqs(wq) < 0)
5508 goto err_free_node_nr_active;
5510 if (wq_online && init_rescuer(wq) < 0)
5513 if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
5517 * wq_pool_mutex protects global freeze state and workqueues list.
5518 * Grab it, adjust max_active and add the new @wq to workqueues
5521 mutex_lock(&wq_pool_mutex);
5523 mutex_lock(&wq->mutex);
5524 wq_adjust_max_active(wq);
5525 mutex_unlock(&wq->mutex);
5527 list_add_tail_rcu(&wq->list, &workqueues);
5529 mutex_unlock(&wq_pool_mutex);
5533 err_free_node_nr_active:
5534 if (wq->flags & WQ_UNBOUND)
5535 free_node_nr_active(wq->node_nr_active);
5537 wq_unregister_lockdep(wq);
5538 wq_free_lockdep(wq);
5540 free_workqueue_attrs(wq->unbound_attrs);
5544 destroy_workqueue(wq);
5547 EXPORT_SYMBOL_GPL(alloc_workqueue);
5549 static bool pwq_busy(struct pool_workqueue *pwq)
5553 for (i = 0; i < WORK_NR_COLORS; i++)
5554 if (pwq->nr_in_flight[i])
5557 if ((pwq != rcu_access_pointer(pwq->wq->dfl_pwq)) && (pwq->refcnt > 1))
5559 if (!pwq_is_empty(pwq))
5566 * destroy_workqueue - safely terminate a workqueue
5567 * @wq: target workqueue
5569 * Safely destroy a workqueue. All work currently pending will be done first.
5571 void destroy_workqueue(struct workqueue_struct *wq)
5573 struct pool_workqueue *pwq;
5577 * Remove it from sysfs first so that sanity check failure doesn't
5578 * lead to sysfs name conflicts.
5580 workqueue_sysfs_unregister(wq);
5582 /* mark the workqueue destruction is in progress */
5583 mutex_lock(&wq->mutex);
5584 wq->flags |= __WQ_DESTROYING;
5585 mutex_unlock(&wq->mutex);
5587 /* drain it before proceeding with destruction */
5588 drain_workqueue(wq);
5590 /* kill rescuer, if sanity checks fail, leave it w/o rescuer */
5592 struct worker *rescuer = wq->rescuer;
5594 /* this prevents new queueing */
5595 raw_spin_lock_irq(&wq_mayday_lock);
5597 raw_spin_unlock_irq(&wq_mayday_lock);
5599 /* rescuer will empty maydays list before exiting */
5600 kthread_stop(rescuer->task);
5605 * Sanity checks - grab all the locks so that we wait for all
5606 * in-flight operations which may do put_pwq().
5608 mutex_lock(&wq_pool_mutex);
5609 mutex_lock(&wq->mutex);
5610 for_each_pwq(pwq, wq) {
5611 raw_spin_lock_irq(&pwq->pool->lock);
5612 if (WARN_ON(pwq_busy(pwq))) {
5613 pr_warn("%s: %s has the following busy pwq\n",
5614 __func__, wq->name);
5616 raw_spin_unlock_irq(&pwq->pool->lock);
5617 mutex_unlock(&wq->mutex);
5618 mutex_unlock(&wq_pool_mutex);
5619 show_one_workqueue(wq);
5622 raw_spin_unlock_irq(&pwq->pool->lock);
5624 mutex_unlock(&wq->mutex);
5627 * wq list is used to freeze wq, remove from list after
5628 * flushing is complete in case freeze races us.
5630 list_del_rcu(&wq->list);
5631 mutex_unlock(&wq_pool_mutex);
5634 * We're the sole accessor of @wq. Directly access cpu_pwq and dfl_pwq
5635 * to put the base refs. @wq will be auto-destroyed from the last
5636 * pwq_put. RCU read lock prevents @wq from going away from under us.
5640 for_each_possible_cpu(cpu) {
5641 put_pwq_unlocked(unbound_pwq(wq, cpu));
5642 RCU_INIT_POINTER(*unbound_pwq_slot(wq, cpu), NULL);
5645 put_pwq_unlocked(unbound_pwq(wq, -1));
5646 RCU_INIT_POINTER(*unbound_pwq_slot(wq, -1), NULL);
5650 EXPORT_SYMBOL_GPL(destroy_workqueue);
5653 * workqueue_set_max_active - adjust max_active of a workqueue
5654 * @wq: target workqueue
5655 * @max_active: new max_active value.
5657 * Set max_active of @wq to @max_active. See the alloc_workqueue() function
5661 * Don't call from IRQ context.
5663 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
5665 /* max_active doesn't mean anything for BH workqueues */
5666 if (WARN_ON(wq->flags & WQ_BH))
5668 /* disallow meddling with max_active for ordered workqueues */
5669 if (WARN_ON(wq->flags & __WQ_ORDERED))
5672 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
5674 mutex_lock(&wq->mutex);
5676 wq->saved_max_active = max_active;
5677 if (wq->flags & WQ_UNBOUND)
5678 wq->saved_min_active = min(wq->saved_min_active, max_active);
5680 wq_adjust_max_active(wq);
5682 mutex_unlock(&wq->mutex);
5684 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
5687 * workqueue_set_min_active - adjust min_active of an unbound workqueue
5688 * @wq: target unbound workqueue
5689 * @min_active: new min_active value
5691 * Set min_active of an unbound workqueue. Unlike other types of workqueues, an
5692 * unbound workqueue is not guaranteed to be able to process max_active
5693 * interdependent work items. Instead, an unbound workqueue is guaranteed to be
5694 * able to process min_active number of interdependent work items which is
5695 * %WQ_DFL_MIN_ACTIVE by default.
5697 * Use this function to adjust the min_active value between 0 and the current
5700 void workqueue_set_min_active(struct workqueue_struct *wq, int min_active)
5702 /* min_active is only meaningful for non-ordered unbound workqueues */
5703 if (WARN_ON((wq->flags & (WQ_BH | WQ_UNBOUND | __WQ_ORDERED)) !=
5707 mutex_lock(&wq->mutex);
5708 wq->saved_min_active = clamp(min_active, 0, wq->saved_max_active);
5709 wq_adjust_max_active(wq);
5710 mutex_unlock(&wq->mutex);
5714 * current_work - retrieve %current task's work struct
5716 * Determine if %current task is a workqueue worker and what it's working on.
5717 * Useful to find out the context that the %current task is running in.
5719 * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
5721 struct work_struct *current_work(void)
5723 struct worker *worker = current_wq_worker();
5725 return worker ? worker->current_work : NULL;
5727 EXPORT_SYMBOL(current_work);
5730 * current_is_workqueue_rescuer - is %current workqueue rescuer?
5732 * Determine whether %current is a workqueue rescuer. Can be used from
5733 * work functions to determine whether it's being run off the rescuer task.
5735 * Return: %true if %current is a workqueue rescuer. %false otherwise.
5737 bool current_is_workqueue_rescuer(void)
5739 struct worker *worker = current_wq_worker();
5741 return worker && worker->rescue_wq;
5745 * workqueue_congested - test whether a workqueue is congested
5746 * @cpu: CPU in question
5747 * @wq: target workqueue
5749 * Test whether @wq's cpu workqueue for @cpu is congested. There is
5750 * no synchronization around this function and the test result is
5751 * unreliable and only useful as advisory hints or for debugging.
5753 * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
5755 * With the exception of ordered workqueues, all workqueues have per-cpu
5756 * pool_workqueues, each with its own congested state. A workqueue being
5757 * congested on one CPU doesn't mean that the workqueue is contested on any
5761 * %true if congested, %false otherwise.
5763 bool workqueue_congested(int cpu, struct workqueue_struct *wq)
5765 struct pool_workqueue *pwq;
5771 if (cpu == WORK_CPU_UNBOUND)
5772 cpu = smp_processor_id();
5774 pwq = *per_cpu_ptr(wq->cpu_pwq, cpu);
5775 ret = !list_empty(&pwq->inactive_works);
5782 EXPORT_SYMBOL_GPL(workqueue_congested);
5785 * work_busy - test whether a work is currently pending or running
5786 * @work: the work to be tested
5788 * Test whether @work is currently pending or running. There is no
5789 * synchronization around this function and the test result is
5790 * unreliable and only useful as advisory hints or for debugging.
5793 * OR'd bitmask of WORK_BUSY_* bits.
5795 unsigned int work_busy(struct work_struct *work)
5797 struct worker_pool *pool;
5798 unsigned long irq_flags;
5799 unsigned int ret = 0;
5801 if (work_pending(work))
5802 ret |= WORK_BUSY_PENDING;
5805 pool = get_work_pool(work);
5807 raw_spin_lock_irqsave(&pool->lock, irq_flags);
5808 if (find_worker_executing_work(pool, work))
5809 ret |= WORK_BUSY_RUNNING;
5810 raw_spin_unlock_irqrestore(&pool->lock, irq_flags);
5816 EXPORT_SYMBOL_GPL(work_busy);
5819 * set_worker_desc - set description for the current work item
5820 * @fmt: printf-style format string
5821 * @...: arguments for the format string
5823 * This function can be called by a running work function to describe what
5824 * the work item is about. If the worker task gets dumped, this
5825 * information will be printed out together to help debugging. The
5826 * description can be at most WORKER_DESC_LEN including the trailing '\0'.
5828 void set_worker_desc(const char *fmt, ...)
5830 struct worker *worker = current_wq_worker();
5834 va_start(args, fmt);
5835 vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
5839 EXPORT_SYMBOL_GPL(set_worker_desc);
5842 * print_worker_info - print out worker information and description
5843 * @log_lvl: the log level to use when printing
5844 * @task: target task
5846 * If @task is a worker and currently executing a work item, print out the
5847 * name of the workqueue being serviced and worker description set with
5848 * set_worker_desc() by the currently executing work item.
5850 * This function can be safely called on any task as long as the
5851 * task_struct itself is accessible. While safe, this function isn't
5852 * synchronized and may print out mixups or garbages of limited length.
5854 void print_worker_info(const char *log_lvl, struct task_struct *task)
5856 work_func_t *fn = NULL;
5857 char name[WQ_NAME_LEN] = { };
5858 char desc[WORKER_DESC_LEN] = { };
5859 struct pool_workqueue *pwq = NULL;
5860 struct workqueue_struct *wq = NULL;
5861 struct worker *worker;
5863 if (!(task->flags & PF_WQ_WORKER))
5867 * This function is called without any synchronization and @task
5868 * could be in any state. Be careful with dereferences.
5870 worker = kthread_probe_data(task);
5873 * Carefully copy the associated workqueue's workfn, name and desc.
5874 * Keep the original last '\0' in case the original is garbage.
5876 copy_from_kernel_nofault(&fn, &worker->current_func, sizeof(fn));
5877 copy_from_kernel_nofault(&pwq, &worker->current_pwq, sizeof(pwq));
5878 copy_from_kernel_nofault(&wq, &pwq->wq, sizeof(wq));
5879 copy_from_kernel_nofault(name, wq->name, sizeof(name) - 1);
5880 copy_from_kernel_nofault(desc, worker->desc, sizeof(desc) - 1);
5882 if (fn || name[0] || desc[0]) {
5883 printk("%sWorkqueue: %s %ps", log_lvl, name, fn);
5884 if (strcmp(name, desc))
5885 pr_cont(" (%s)", desc);
5890 static void pr_cont_pool_info(struct worker_pool *pool)
5892 pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
5893 if (pool->node != NUMA_NO_NODE)
5894 pr_cont(" node=%d", pool->node);
5895 pr_cont(" flags=0x%x", pool->flags);
5896 if (pool->flags & POOL_BH)
5898 pool->attrs->nice == HIGHPRI_NICE_LEVEL ? "-hi" : "");
5900 pr_cont(" nice=%d", pool->attrs->nice);
5903 static void pr_cont_worker_id(struct worker *worker)
5905 struct worker_pool *pool = worker->pool;
5907 if (pool->flags & WQ_BH)
5909 pool->attrs->nice == HIGHPRI_NICE_LEVEL ? "-hi" : "");
5911 pr_cont("%d%s", task_pid_nr(worker->task),
5912 worker->rescue_wq ? "(RESCUER)" : "");
5915 struct pr_cont_work_struct {
5921 static void pr_cont_work_flush(bool comma, work_func_t func, struct pr_cont_work_struct *pcwsp)
5925 if (func == pcwsp->func) {
5929 if (pcwsp->ctr == 1)
5930 pr_cont("%s %ps", pcwsp->comma ? "," : "", pcwsp->func);
5932 pr_cont("%s %ld*%ps", pcwsp->comma ? "," : "", pcwsp->ctr, pcwsp->func);
5935 if ((long)func == -1L)
5937 pcwsp->comma = comma;
5942 static void pr_cont_work(bool comma, struct work_struct *work, struct pr_cont_work_struct *pcwsp)
5944 if (work->func == wq_barrier_func) {
5945 struct wq_barrier *barr;
5947 barr = container_of(work, struct wq_barrier, work);
5949 pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
5950 pr_cont("%s BAR(%d)", comma ? "," : "",
5951 task_pid_nr(barr->task));
5954 pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
5955 pr_cont_work_flush(comma, work->func, pcwsp);
5959 static void show_pwq(struct pool_workqueue *pwq)
5961 struct pr_cont_work_struct pcws = { .ctr = 0, };
5962 struct worker_pool *pool = pwq->pool;
5963 struct work_struct *work;
5964 struct worker *worker;
5965 bool has_in_flight = false, has_pending = false;
5968 pr_info(" pwq %d:", pool->id);
5969 pr_cont_pool_info(pool);
5971 pr_cont(" active=%d refcnt=%d%s\n",
5972 pwq->nr_active, pwq->refcnt,
5973 !list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
5975 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
5976 if (worker->current_pwq == pwq) {
5977 has_in_flight = true;
5981 if (has_in_flight) {
5984 pr_info(" in-flight:");
5985 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
5986 if (worker->current_pwq != pwq)
5989 pr_cont(" %s", comma ? "," : "");
5990 pr_cont_worker_id(worker);
5991 pr_cont(":%ps", worker->current_func);
5992 list_for_each_entry(work, &worker->scheduled, entry)
5993 pr_cont_work(false, work, &pcws);
5994 pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
6000 list_for_each_entry(work, &pool->worklist, entry) {
6001 if (get_work_pwq(work) == pwq) {
6009 pr_info(" pending:");
6010 list_for_each_entry(work, &pool->worklist, entry) {
6011 if (get_work_pwq(work) != pwq)
6014 pr_cont_work(comma, work, &pcws);
6015 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
6017 pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
6021 if (!list_empty(&pwq->inactive_works)) {
6024 pr_info(" inactive:");
6025 list_for_each_entry(work, &pwq->inactive_works, entry) {
6026 pr_cont_work(comma, work, &pcws);
6027 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
6029 pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
6035 * show_one_workqueue - dump state of specified workqueue
6036 * @wq: workqueue whose state will be printed
6038 void show_one_workqueue(struct workqueue_struct *wq)
6040 struct pool_workqueue *pwq;
6042 unsigned long irq_flags;
6044 for_each_pwq(pwq, wq) {
6045 if (!pwq_is_empty(pwq)) {
6050 if (idle) /* Nothing to print for idle workqueue */
6053 pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
6055 for_each_pwq(pwq, wq) {
6056 raw_spin_lock_irqsave(&pwq->pool->lock, irq_flags);
6057 if (!pwq_is_empty(pwq)) {
6059 * Defer printing to avoid deadlocks in console
6060 * drivers that queue work while holding locks
6061 * also taken in their write paths.
6063 printk_deferred_enter();
6065 printk_deferred_exit();
6067 raw_spin_unlock_irqrestore(&pwq->pool->lock, irq_flags);
6069 * We could be printing a lot from atomic context, e.g.
6070 * sysrq-t -> show_all_workqueues(). Avoid triggering
6073 touch_nmi_watchdog();
6079 * show_one_worker_pool - dump state of specified worker pool
6080 * @pool: worker pool whose state will be printed
6082 static void show_one_worker_pool(struct worker_pool *pool)
6084 struct worker *worker;
6086 unsigned long irq_flags;
6087 unsigned long hung = 0;
6089 raw_spin_lock_irqsave(&pool->lock, irq_flags);
6090 if (pool->nr_workers == pool->nr_idle)
6093 /* How long the first pending work is waiting for a worker. */
6094 if (!list_empty(&pool->worklist))
6095 hung = jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000;
6098 * Defer printing to avoid deadlocks in console drivers that
6099 * queue work while holding locks also taken in their write
6102 printk_deferred_enter();
6103 pr_info("pool %d:", pool->id);
6104 pr_cont_pool_info(pool);
6105 pr_cont(" hung=%lus workers=%d", hung, pool->nr_workers);
6107 pr_cont(" manager: %d",
6108 task_pid_nr(pool->manager->task));
6109 list_for_each_entry(worker, &pool->idle_list, entry) {
6110 pr_cont(" %s", first ? "idle: " : "");
6111 pr_cont_worker_id(worker);
6115 printk_deferred_exit();
6117 raw_spin_unlock_irqrestore(&pool->lock, irq_flags);
6119 * We could be printing a lot from atomic context, e.g.
6120 * sysrq-t -> show_all_workqueues(). Avoid triggering
6123 touch_nmi_watchdog();
6128 * show_all_workqueues - dump workqueue state
6130 * Called from a sysrq handler and prints out all busy workqueues and pools.
6132 void show_all_workqueues(void)
6134 struct workqueue_struct *wq;
6135 struct worker_pool *pool;
6140 pr_info("Showing busy workqueues and worker pools:\n");
6142 list_for_each_entry_rcu(wq, &workqueues, list)
6143 show_one_workqueue(wq);
6145 for_each_pool(pool, pi)
6146 show_one_worker_pool(pool);
6152 * show_freezable_workqueues - dump freezable workqueue state
6154 * Called from try_to_freeze_tasks() and prints out all freezable workqueues
6157 void show_freezable_workqueues(void)
6159 struct workqueue_struct *wq;
6163 pr_info("Showing freezable workqueues that are still busy:\n");
6165 list_for_each_entry_rcu(wq, &workqueues, list) {
6166 if (!(wq->flags & WQ_FREEZABLE))
6168 show_one_workqueue(wq);
6174 /* used to show worker information through /proc/PID/{comm,stat,status} */
6175 void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
6179 /* always show the actual comm */
6180 off = strscpy(buf, task->comm, size);
6184 /* stabilize PF_WQ_WORKER and worker pool association */
6185 mutex_lock(&wq_pool_attach_mutex);
6187 if (task->flags & PF_WQ_WORKER) {
6188 struct worker *worker = kthread_data(task);
6189 struct worker_pool *pool = worker->pool;
6192 raw_spin_lock_irq(&pool->lock);
6194 * ->desc tracks information (wq name or
6195 * set_worker_desc()) for the latest execution. If
6196 * current, prepend '+', otherwise '-'.
6198 if (worker->desc[0] != '\0') {
6199 if (worker->current_work)
6200 scnprintf(buf + off, size - off, "+%s",
6203 scnprintf(buf + off, size - off, "-%s",
6206 raw_spin_unlock_irq(&pool->lock);
6210 mutex_unlock(&wq_pool_attach_mutex);
6218 * There are two challenges in supporting CPU hotplug. Firstly, there
6219 * are a lot of assumptions on strong associations among work, pwq and
6220 * pool which make migrating pending and scheduled works very
6221 * difficult to implement without impacting hot paths. Secondly,
6222 * worker pools serve mix of short, long and very long running works making
6223 * blocked draining impractical.
6225 * This is solved by allowing the pools to be disassociated from the CPU
6226 * running as an unbound one and allowing it to be reattached later if the
6227 * cpu comes back online.
6230 static void unbind_workers(int cpu)
6232 struct worker_pool *pool;
6233 struct worker *worker;
6235 for_each_cpu_worker_pool(pool, cpu) {
6236 mutex_lock(&wq_pool_attach_mutex);
6237 raw_spin_lock_irq(&pool->lock);
6240 * We've blocked all attach/detach operations. Make all workers
6241 * unbound and set DISASSOCIATED. Before this, all workers
6242 * must be on the cpu. After this, they may become diasporas.
6243 * And the preemption disabled section in their sched callbacks
6244 * are guaranteed to see WORKER_UNBOUND since the code here
6245 * is on the same cpu.
6247 for_each_pool_worker(worker, pool)
6248 worker->flags |= WORKER_UNBOUND;
6250 pool->flags |= POOL_DISASSOCIATED;
6253 * The handling of nr_running in sched callbacks are disabled
6254 * now. Zap nr_running. After this, nr_running stays zero and
6255 * need_more_worker() and keep_working() are always true as
6256 * long as the worklist is not empty. This pool now behaves as
6257 * an unbound (in terms of concurrency management) pool which
6258 * are served by workers tied to the pool.
6260 pool->nr_running = 0;
6263 * With concurrency management just turned off, a busy
6264 * worker blocking could lead to lengthy stalls. Kick off
6265 * unbound chain execution of currently pending work items.
6269 raw_spin_unlock_irq(&pool->lock);
6271 for_each_pool_worker(worker, pool)
6272 unbind_worker(worker);
6274 mutex_unlock(&wq_pool_attach_mutex);
6279 * rebind_workers - rebind all workers of a pool to the associated CPU
6280 * @pool: pool of interest
6282 * @pool->cpu is coming online. Rebind all workers to the CPU.
6284 static void rebind_workers(struct worker_pool *pool)
6286 struct worker *worker;
6288 lockdep_assert_held(&wq_pool_attach_mutex);
6291 * Restore CPU affinity of all workers. As all idle workers should
6292 * be on the run-queue of the associated CPU before any local
6293 * wake-ups for concurrency management happen, restore CPU affinity
6294 * of all workers first and then clear UNBOUND. As we're called
6295 * from CPU_ONLINE, the following shouldn't fail.
6297 for_each_pool_worker(worker, pool) {
6298 kthread_set_per_cpu(worker->task, pool->cpu);
6299 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
6300 pool_allowed_cpus(pool)) < 0);
6303 raw_spin_lock_irq(&pool->lock);
6305 pool->flags &= ~POOL_DISASSOCIATED;
6307 for_each_pool_worker(worker, pool) {
6308 unsigned int worker_flags = worker->flags;
6311 * We want to clear UNBOUND but can't directly call
6312 * worker_clr_flags() or adjust nr_running. Atomically
6313 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
6314 * @worker will clear REBOUND using worker_clr_flags() when
6315 * it initiates the next execution cycle thus restoring
6316 * concurrency management. Note that when or whether
6317 * @worker clears REBOUND doesn't affect correctness.
6319 * WRITE_ONCE() is necessary because @worker->flags may be
6320 * tested without holding any lock in
6321 * wq_worker_running(). Without it, NOT_RUNNING test may
6322 * fail incorrectly leading to premature concurrency
6323 * management operations.
6325 WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
6326 worker_flags |= WORKER_REBOUND;
6327 worker_flags &= ~WORKER_UNBOUND;
6328 WRITE_ONCE(worker->flags, worker_flags);
6331 raw_spin_unlock_irq(&pool->lock);
6335 * restore_unbound_workers_cpumask - restore cpumask of unbound workers
6336 * @pool: unbound pool of interest
6337 * @cpu: the CPU which is coming up
6339 * An unbound pool may end up with a cpumask which doesn't have any online
6340 * CPUs. When a worker of such pool get scheduled, the scheduler resets
6341 * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
6342 * online CPU before, cpus_allowed of all its workers should be restored.
6344 static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
6346 static cpumask_t cpumask;
6347 struct worker *worker;
6349 lockdep_assert_held(&wq_pool_attach_mutex);
6351 /* is @cpu allowed for @pool? */
6352 if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
6355 cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
6357 /* as we're called from CPU_ONLINE, the following shouldn't fail */
6358 for_each_pool_worker(worker, pool)
6359 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
6362 int workqueue_prepare_cpu(unsigned int cpu)
6364 struct worker_pool *pool;
6366 for_each_cpu_worker_pool(pool, cpu) {
6367 if (pool->nr_workers)
6369 if (!create_worker(pool))
6375 int workqueue_online_cpu(unsigned int cpu)
6377 struct worker_pool *pool;
6378 struct workqueue_struct *wq;
6381 mutex_lock(&wq_pool_mutex);
6383 for_each_pool(pool, pi) {
6384 /* BH pools aren't affected by hotplug */
6385 if (pool->flags & POOL_BH)
6388 mutex_lock(&wq_pool_attach_mutex);
6389 if (pool->cpu == cpu)
6390 rebind_workers(pool);
6391 else if (pool->cpu < 0)
6392 restore_unbound_workers_cpumask(pool, cpu);
6393 mutex_unlock(&wq_pool_attach_mutex);
6396 /* update pod affinity of unbound workqueues */
6397 list_for_each_entry(wq, &workqueues, list) {
6398 struct workqueue_attrs *attrs = wq->unbound_attrs;
6401 const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
6404 for_each_cpu(tcpu, pt->pod_cpus[pt->cpu_pod[cpu]])
6405 wq_update_pod(wq, tcpu, cpu, true);
6407 mutex_lock(&wq->mutex);
6408 wq_update_node_max_active(wq, -1);
6409 mutex_unlock(&wq->mutex);
6413 mutex_unlock(&wq_pool_mutex);
6417 int workqueue_offline_cpu(unsigned int cpu)
6419 struct workqueue_struct *wq;
6421 /* unbinding per-cpu workers should happen on the local CPU */
6422 if (WARN_ON(cpu != smp_processor_id()))
6425 unbind_workers(cpu);
6427 /* update pod affinity of unbound workqueues */
6428 mutex_lock(&wq_pool_mutex);
6429 list_for_each_entry(wq, &workqueues, list) {
6430 struct workqueue_attrs *attrs = wq->unbound_attrs;
6433 const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
6436 for_each_cpu(tcpu, pt->pod_cpus[pt->cpu_pod[cpu]])
6437 wq_update_pod(wq, tcpu, cpu, false);
6439 mutex_lock(&wq->mutex);
6440 wq_update_node_max_active(wq, cpu);
6441 mutex_unlock(&wq->mutex);
6444 mutex_unlock(&wq_pool_mutex);
6449 struct work_for_cpu {
6450 struct work_struct work;
6456 static void work_for_cpu_fn(struct work_struct *work)
6458 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
6460 wfc->ret = wfc->fn(wfc->arg);
6464 * work_on_cpu_key - run a function in thread context on a particular cpu
6465 * @cpu: the cpu to run on
6466 * @fn: the function to run
6467 * @arg: the function arg
6468 * @key: The lock class key for lock debugging purposes
6470 * It is up to the caller to ensure that the cpu doesn't go offline.
6471 * The caller must not hold any locks which would prevent @fn from completing.
6473 * Return: The value @fn returns.
6475 long work_on_cpu_key(int cpu, long (*fn)(void *),
6476 void *arg, struct lock_class_key *key)
6478 struct work_for_cpu wfc = { .fn = fn, .arg = arg };
6480 INIT_WORK_ONSTACK_KEY(&wfc.work, work_for_cpu_fn, key);
6481 schedule_work_on(cpu, &wfc.work);
6482 flush_work(&wfc.work);
6483 destroy_work_on_stack(&wfc.work);
6486 EXPORT_SYMBOL_GPL(work_on_cpu_key);
6489 * work_on_cpu_safe_key - run a function in thread context on a particular cpu
6490 * @cpu: the cpu to run on
6491 * @fn: the function to run
6492 * @arg: the function argument
6493 * @key: The lock class key for lock debugging purposes
6495 * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
6496 * any locks which would prevent @fn from completing.
6498 * Return: The value @fn returns.
6500 long work_on_cpu_safe_key(int cpu, long (*fn)(void *),
6501 void *arg, struct lock_class_key *key)
6506 if (cpu_online(cpu))
6507 ret = work_on_cpu_key(cpu, fn, arg, key);
6511 EXPORT_SYMBOL_GPL(work_on_cpu_safe_key);
6512 #endif /* CONFIG_SMP */
6514 #ifdef CONFIG_FREEZER
6517 * freeze_workqueues_begin - begin freezing workqueues
6519 * Start freezing workqueues. After this function returns, all freezable
6520 * workqueues will queue new works to their inactive_works list instead of
6524 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
6526 void freeze_workqueues_begin(void)
6528 struct workqueue_struct *wq;
6530 mutex_lock(&wq_pool_mutex);
6532 WARN_ON_ONCE(workqueue_freezing);
6533 workqueue_freezing = true;
6535 list_for_each_entry(wq, &workqueues, list) {
6536 mutex_lock(&wq->mutex);
6537 wq_adjust_max_active(wq);
6538 mutex_unlock(&wq->mutex);
6541 mutex_unlock(&wq_pool_mutex);
6545 * freeze_workqueues_busy - are freezable workqueues still busy?
6547 * Check whether freezing is complete. This function must be called
6548 * between freeze_workqueues_begin() and thaw_workqueues().
6551 * Grabs and releases wq_pool_mutex.
6554 * %true if some freezable workqueues are still busy. %false if freezing
6557 bool freeze_workqueues_busy(void)
6560 struct workqueue_struct *wq;
6561 struct pool_workqueue *pwq;
6563 mutex_lock(&wq_pool_mutex);
6565 WARN_ON_ONCE(!workqueue_freezing);
6567 list_for_each_entry(wq, &workqueues, list) {
6568 if (!(wq->flags & WQ_FREEZABLE))
6571 * nr_active is monotonically decreasing. It's safe
6572 * to peek without lock.
6575 for_each_pwq(pwq, wq) {
6576 WARN_ON_ONCE(pwq->nr_active < 0);
6577 if (pwq->nr_active) {
6586 mutex_unlock(&wq_pool_mutex);
6591 * thaw_workqueues - thaw workqueues
6593 * Thaw workqueues. Normal queueing is restored and all collected
6594 * frozen works are transferred to their respective pool worklists.
6597 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
6599 void thaw_workqueues(void)
6601 struct workqueue_struct *wq;
6603 mutex_lock(&wq_pool_mutex);
6605 if (!workqueue_freezing)
6608 workqueue_freezing = false;
6610 /* restore max_active and repopulate worklist */
6611 list_for_each_entry(wq, &workqueues, list) {
6612 mutex_lock(&wq->mutex);
6613 wq_adjust_max_active(wq);
6614 mutex_unlock(&wq->mutex);
6618 mutex_unlock(&wq_pool_mutex);
6620 #endif /* CONFIG_FREEZER */
6622 static int workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask)
6626 struct workqueue_struct *wq;
6627 struct apply_wqattrs_ctx *ctx, *n;
6629 lockdep_assert_held(&wq_pool_mutex);
6631 list_for_each_entry(wq, &workqueues, list) {
6632 if (!(wq->flags & WQ_UNBOUND) || (wq->flags & __WQ_DESTROYING))
6635 ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs, unbound_cpumask);
6641 list_add_tail(&ctx->list, &ctxs);
6644 list_for_each_entry_safe(ctx, n, &ctxs, list) {
6646 apply_wqattrs_commit(ctx);
6647 apply_wqattrs_cleanup(ctx);
6651 mutex_lock(&wq_pool_attach_mutex);
6652 cpumask_copy(wq_unbound_cpumask, unbound_cpumask);
6653 mutex_unlock(&wq_pool_attach_mutex);
6659 * workqueue_unbound_exclude_cpumask - Exclude given CPUs from unbound cpumask
6660 * @exclude_cpumask: the cpumask to be excluded from wq_unbound_cpumask
6662 * This function can be called from cpuset code to provide a set of isolated
6663 * CPUs that should be excluded from wq_unbound_cpumask. The caller must hold
6664 * either cpus_read_lock or cpus_write_lock.
6666 int workqueue_unbound_exclude_cpumask(cpumask_var_t exclude_cpumask)
6668 cpumask_var_t cpumask;
6671 if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
6674 lockdep_assert_cpus_held();
6675 mutex_lock(&wq_pool_mutex);
6677 /* Save the current isolated cpumask & export it via sysfs */
6678 cpumask_copy(wq_isolated_cpumask, exclude_cpumask);
6681 * If the operation fails, it will fall back to
6682 * wq_requested_unbound_cpumask which is initially set to
6683 * (HK_TYPE_WQ ∩ HK_TYPE_DOMAIN) house keeping mask and rewritten
6684 * by any subsequent write to workqueue/cpumask sysfs file.
6686 if (!cpumask_andnot(cpumask, wq_requested_unbound_cpumask, exclude_cpumask))
6687 cpumask_copy(cpumask, wq_requested_unbound_cpumask);
6688 if (!cpumask_equal(cpumask, wq_unbound_cpumask))
6689 ret = workqueue_apply_unbound_cpumask(cpumask);
6691 mutex_unlock(&wq_pool_mutex);
6692 free_cpumask_var(cpumask);
6696 static int parse_affn_scope(const char *val)
6700 for (i = 0; i < ARRAY_SIZE(wq_affn_names); i++) {
6701 if (!strncasecmp(val, wq_affn_names[i], strlen(wq_affn_names[i])))
6707 static int wq_affn_dfl_set(const char *val, const struct kernel_param *kp)
6709 struct workqueue_struct *wq;
6712 affn = parse_affn_scope(val);
6715 if (affn == WQ_AFFN_DFL)
6719 mutex_lock(&wq_pool_mutex);
6723 list_for_each_entry(wq, &workqueues, list) {
6724 for_each_online_cpu(cpu) {
6725 wq_update_pod(wq, cpu, cpu, true);
6729 mutex_unlock(&wq_pool_mutex);
6735 static int wq_affn_dfl_get(char *buffer, const struct kernel_param *kp)
6737 return scnprintf(buffer, PAGE_SIZE, "%s\n", wq_affn_names[wq_affn_dfl]);
6740 static const struct kernel_param_ops wq_affn_dfl_ops = {
6741 .set = wq_affn_dfl_set,
6742 .get = wq_affn_dfl_get,
6745 module_param_cb(default_affinity_scope, &wq_affn_dfl_ops, NULL, 0644);
6749 * Workqueues with WQ_SYSFS flag set is visible to userland via
6750 * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
6751 * following attributes.
6753 * per_cpu RO bool : whether the workqueue is per-cpu or unbound
6754 * max_active RW int : maximum number of in-flight work items
6756 * Unbound workqueues have the following extra attributes.
6758 * nice RW int : nice value of the workers
6759 * cpumask RW mask : bitmask of allowed CPUs for the workers
6760 * affinity_scope RW str : worker CPU affinity scope (cache, numa, none)
6761 * affinity_strict RW bool : worker CPU affinity is strict
6764 struct workqueue_struct *wq;
6768 static struct workqueue_struct *dev_to_wq(struct device *dev)
6770 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
6775 static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
6778 struct workqueue_struct *wq = dev_to_wq(dev);
6780 return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
6782 static DEVICE_ATTR_RO(per_cpu);
6784 static ssize_t max_active_show(struct device *dev,
6785 struct device_attribute *attr, char *buf)
6787 struct workqueue_struct *wq = dev_to_wq(dev);
6789 return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
6792 static ssize_t max_active_store(struct device *dev,
6793 struct device_attribute *attr, const char *buf,
6796 struct workqueue_struct *wq = dev_to_wq(dev);
6799 if (sscanf(buf, "%d", &val) != 1 || val <= 0)
6802 workqueue_set_max_active(wq, val);
6805 static DEVICE_ATTR_RW(max_active);
6807 static struct attribute *wq_sysfs_attrs[] = {
6808 &dev_attr_per_cpu.attr,
6809 &dev_attr_max_active.attr,
6812 ATTRIBUTE_GROUPS(wq_sysfs);
6814 static void apply_wqattrs_lock(void)
6816 /* CPUs should stay stable across pwq creations and installations */
6818 mutex_lock(&wq_pool_mutex);
6821 static void apply_wqattrs_unlock(void)
6823 mutex_unlock(&wq_pool_mutex);
6827 static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
6830 struct workqueue_struct *wq = dev_to_wq(dev);
6833 mutex_lock(&wq->mutex);
6834 written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
6835 mutex_unlock(&wq->mutex);
6840 /* prepare workqueue_attrs for sysfs store operations */
6841 static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
6843 struct workqueue_attrs *attrs;
6845 lockdep_assert_held(&wq_pool_mutex);
6847 attrs = alloc_workqueue_attrs();
6851 copy_workqueue_attrs(attrs, wq->unbound_attrs);
6855 static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
6856 const char *buf, size_t count)
6858 struct workqueue_struct *wq = dev_to_wq(dev);
6859 struct workqueue_attrs *attrs;
6862 apply_wqattrs_lock();
6864 attrs = wq_sysfs_prep_attrs(wq);
6868 if (sscanf(buf, "%d", &attrs->nice) == 1 &&
6869 attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
6870 ret = apply_workqueue_attrs_locked(wq, attrs);
6875 apply_wqattrs_unlock();
6876 free_workqueue_attrs(attrs);
6877 return ret ?: count;
6880 static ssize_t wq_cpumask_show(struct device *dev,
6881 struct device_attribute *attr, char *buf)
6883 struct workqueue_struct *wq = dev_to_wq(dev);
6886 mutex_lock(&wq->mutex);
6887 written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
6888 cpumask_pr_args(wq->unbound_attrs->cpumask));
6889 mutex_unlock(&wq->mutex);
6893 static ssize_t wq_cpumask_store(struct device *dev,
6894 struct device_attribute *attr,
6895 const char *buf, size_t count)
6897 struct workqueue_struct *wq = dev_to_wq(dev);
6898 struct workqueue_attrs *attrs;
6901 apply_wqattrs_lock();
6903 attrs = wq_sysfs_prep_attrs(wq);
6907 ret = cpumask_parse(buf, attrs->cpumask);
6909 ret = apply_workqueue_attrs_locked(wq, attrs);
6912 apply_wqattrs_unlock();
6913 free_workqueue_attrs(attrs);
6914 return ret ?: count;
6917 static ssize_t wq_affn_scope_show(struct device *dev,
6918 struct device_attribute *attr, char *buf)
6920 struct workqueue_struct *wq = dev_to_wq(dev);
6923 mutex_lock(&wq->mutex);
6924 if (wq->unbound_attrs->affn_scope == WQ_AFFN_DFL)
6925 written = scnprintf(buf, PAGE_SIZE, "%s (%s)\n",
6926 wq_affn_names[WQ_AFFN_DFL],
6927 wq_affn_names[wq_affn_dfl]);
6929 written = scnprintf(buf, PAGE_SIZE, "%s\n",
6930 wq_affn_names[wq->unbound_attrs->affn_scope]);
6931 mutex_unlock(&wq->mutex);
6936 static ssize_t wq_affn_scope_store(struct device *dev,
6937 struct device_attribute *attr,
6938 const char *buf, size_t count)
6940 struct workqueue_struct *wq = dev_to_wq(dev);
6941 struct workqueue_attrs *attrs;
6942 int affn, ret = -ENOMEM;
6944 affn = parse_affn_scope(buf);
6948 apply_wqattrs_lock();
6949 attrs = wq_sysfs_prep_attrs(wq);
6951 attrs->affn_scope = affn;
6952 ret = apply_workqueue_attrs_locked(wq, attrs);
6954 apply_wqattrs_unlock();
6955 free_workqueue_attrs(attrs);
6956 return ret ?: count;
6959 static ssize_t wq_affinity_strict_show(struct device *dev,
6960 struct device_attribute *attr, char *buf)
6962 struct workqueue_struct *wq = dev_to_wq(dev);
6964 return scnprintf(buf, PAGE_SIZE, "%d\n",
6965 wq->unbound_attrs->affn_strict);
6968 static ssize_t wq_affinity_strict_store(struct device *dev,
6969 struct device_attribute *attr,
6970 const char *buf, size_t count)
6972 struct workqueue_struct *wq = dev_to_wq(dev);
6973 struct workqueue_attrs *attrs;
6974 int v, ret = -ENOMEM;
6976 if (sscanf(buf, "%d", &v) != 1)
6979 apply_wqattrs_lock();
6980 attrs = wq_sysfs_prep_attrs(wq);
6982 attrs->affn_strict = (bool)v;
6983 ret = apply_workqueue_attrs_locked(wq, attrs);
6985 apply_wqattrs_unlock();
6986 free_workqueue_attrs(attrs);
6987 return ret ?: count;
6990 static struct device_attribute wq_sysfs_unbound_attrs[] = {
6991 __ATTR(nice, 0644, wq_nice_show, wq_nice_store),
6992 __ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
6993 __ATTR(affinity_scope, 0644, wq_affn_scope_show, wq_affn_scope_store),
6994 __ATTR(affinity_strict, 0644, wq_affinity_strict_show, wq_affinity_strict_store),
6998 static struct bus_type wq_subsys = {
6999 .name = "workqueue",
7000 .dev_groups = wq_sysfs_groups,
7004 * workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
7005 * @cpumask: the cpumask to set
7007 * The low-level workqueues cpumask is a global cpumask that limits
7008 * the affinity of all unbound workqueues. This function check the @cpumask
7009 * and apply it to all unbound workqueues and updates all pwqs of them.
7011 * Return: 0 - Success
7012 * -EINVAL - Invalid @cpumask
7013 * -ENOMEM - Failed to allocate memory for attrs or pwqs.
7015 static int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
7020 * Not excluding isolated cpus on purpose.
7021 * If the user wishes to include them, we allow that.
7023 cpumask_and(cpumask, cpumask, cpu_possible_mask);
7024 if (!cpumask_empty(cpumask)) {
7025 apply_wqattrs_lock();
7026 cpumask_copy(wq_requested_unbound_cpumask, cpumask);
7027 if (cpumask_equal(cpumask, wq_unbound_cpumask)) {
7032 ret = workqueue_apply_unbound_cpumask(cpumask);
7035 apply_wqattrs_unlock();
7041 static ssize_t __wq_cpumask_show(struct device *dev,
7042 struct device_attribute *attr, char *buf, cpumask_var_t mask)
7046 mutex_lock(&wq_pool_mutex);
7047 written = scnprintf(buf, PAGE_SIZE, "%*pb\n", cpumask_pr_args(mask));
7048 mutex_unlock(&wq_pool_mutex);
7053 static ssize_t wq_unbound_cpumask_show(struct device *dev,
7054 struct device_attribute *attr, char *buf)
7056 return __wq_cpumask_show(dev, attr, buf, wq_unbound_cpumask);
7059 static ssize_t wq_requested_cpumask_show(struct device *dev,
7060 struct device_attribute *attr, char *buf)
7062 return __wq_cpumask_show(dev, attr, buf, wq_requested_unbound_cpumask);
7065 static ssize_t wq_isolated_cpumask_show(struct device *dev,
7066 struct device_attribute *attr, char *buf)
7068 return __wq_cpumask_show(dev, attr, buf, wq_isolated_cpumask);
7071 static ssize_t wq_unbound_cpumask_store(struct device *dev,
7072 struct device_attribute *attr, const char *buf, size_t count)
7074 cpumask_var_t cpumask;
7077 if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
7080 ret = cpumask_parse(buf, cpumask);
7082 ret = workqueue_set_unbound_cpumask(cpumask);
7084 free_cpumask_var(cpumask);
7085 return ret ? ret : count;
7088 static struct device_attribute wq_sysfs_cpumask_attrs[] = {
7089 __ATTR(cpumask, 0644, wq_unbound_cpumask_show,
7090 wq_unbound_cpumask_store),
7091 __ATTR(cpumask_requested, 0444, wq_requested_cpumask_show, NULL),
7092 __ATTR(cpumask_isolated, 0444, wq_isolated_cpumask_show, NULL),
7096 static int __init wq_sysfs_init(void)
7098 struct device *dev_root;
7101 err = subsys_virtual_register(&wq_subsys, NULL);
7105 dev_root = bus_get_dev_root(&wq_subsys);
7107 struct device_attribute *attr;
7109 for (attr = wq_sysfs_cpumask_attrs; attr->attr.name; attr++) {
7110 err = device_create_file(dev_root, attr);
7114 put_device(dev_root);
7118 core_initcall(wq_sysfs_init);
7120 static void wq_device_release(struct device *dev)
7122 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
7128 * workqueue_sysfs_register - make a workqueue visible in sysfs
7129 * @wq: the workqueue to register
7131 * Expose @wq in sysfs under /sys/bus/workqueue/devices.
7132 * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
7133 * which is the preferred method.
7135 * Workqueue user should use this function directly iff it wants to apply
7136 * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
7137 * apply_workqueue_attrs() may race against userland updating the
7140 * Return: 0 on success, -errno on failure.
7142 int workqueue_sysfs_register(struct workqueue_struct *wq)
7144 struct wq_device *wq_dev;
7148 * Adjusting max_active breaks ordering guarantee. Disallow exposing
7149 * ordered workqueues.
7151 if (WARN_ON(wq->flags & __WQ_ORDERED))
7154 wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
7159 wq_dev->dev.bus = &wq_subsys;
7160 wq_dev->dev.release = wq_device_release;
7161 dev_set_name(&wq_dev->dev, "%s", wq->name);
7164 * unbound_attrs are created separately. Suppress uevent until
7165 * everything is ready.
7167 dev_set_uevent_suppress(&wq_dev->dev, true);
7169 ret = device_register(&wq_dev->dev);
7171 put_device(&wq_dev->dev);
7176 if (wq->flags & WQ_UNBOUND) {
7177 struct device_attribute *attr;
7179 for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
7180 ret = device_create_file(&wq_dev->dev, attr);
7182 device_unregister(&wq_dev->dev);
7189 dev_set_uevent_suppress(&wq_dev->dev, false);
7190 kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
7195 * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
7196 * @wq: the workqueue to unregister
7198 * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
7200 static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
7202 struct wq_device *wq_dev = wq->wq_dev;
7208 device_unregister(&wq_dev->dev);
7210 #else /* CONFIG_SYSFS */
7211 static void workqueue_sysfs_unregister(struct workqueue_struct *wq) { }
7212 #endif /* CONFIG_SYSFS */
7215 * Workqueue watchdog.
7217 * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
7218 * flush dependency, a concurrency managed work item which stays RUNNING
7219 * indefinitely. Workqueue stalls can be very difficult to debug as the
7220 * usual warning mechanisms don't trigger and internal workqueue state is
7223 * Workqueue watchdog monitors all worker pools periodically and dumps
7224 * state if some pools failed to make forward progress for a while where
7225 * forward progress is defined as the first item on ->worklist changing.
7227 * This mechanism is controlled through the kernel parameter
7228 * "workqueue.watchdog_thresh" which can be updated at runtime through the
7229 * corresponding sysfs parameter file.
7231 #ifdef CONFIG_WQ_WATCHDOG
7233 static unsigned long wq_watchdog_thresh = 30;
7234 static struct timer_list wq_watchdog_timer;
7236 static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
7237 static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
7240 * Show workers that might prevent the processing of pending work items.
7241 * The only candidates are CPU-bound workers in the running state.
7242 * Pending work items should be handled by another idle worker
7243 * in all other situations.
7245 static void show_cpu_pool_hog(struct worker_pool *pool)
7247 struct worker *worker;
7248 unsigned long irq_flags;
7251 raw_spin_lock_irqsave(&pool->lock, irq_flags);
7253 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
7254 if (task_is_running(worker->task)) {
7256 * Defer printing to avoid deadlocks in console
7257 * drivers that queue work while holding locks
7258 * also taken in their write paths.
7260 printk_deferred_enter();
7262 pr_info("pool %d:\n", pool->id);
7263 sched_show_task(worker->task);
7265 printk_deferred_exit();
7269 raw_spin_unlock_irqrestore(&pool->lock, irq_flags);
7272 static void show_cpu_pools_hogs(void)
7274 struct worker_pool *pool;
7277 pr_info("Showing backtraces of running workers in stalled CPU-bound worker pools:\n");
7281 for_each_pool(pool, pi) {
7282 if (pool->cpu_stall)
7283 show_cpu_pool_hog(pool);
7290 static void wq_watchdog_reset_touched(void)
7294 wq_watchdog_touched = jiffies;
7295 for_each_possible_cpu(cpu)
7296 per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
7299 static void wq_watchdog_timer_fn(struct timer_list *unused)
7301 unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
7302 bool lockup_detected = false;
7303 bool cpu_pool_stall = false;
7304 unsigned long now = jiffies;
7305 struct worker_pool *pool;
7313 for_each_pool(pool, pi) {
7314 unsigned long pool_ts, touched, ts;
7316 pool->cpu_stall = false;
7317 if (list_empty(&pool->worklist))
7321 * If a virtual machine is stopped by the host it can look to
7322 * the watchdog like a stall.
7324 kvm_check_and_clear_guest_paused();
7326 /* get the latest of pool and touched timestamps */
7328 touched = READ_ONCE(per_cpu(wq_watchdog_touched_cpu, pool->cpu));
7330 touched = READ_ONCE(wq_watchdog_touched);
7331 pool_ts = READ_ONCE(pool->watchdog_ts);
7333 if (time_after(pool_ts, touched))
7339 if (time_after(now, ts + thresh)) {
7340 lockup_detected = true;
7341 if (pool->cpu >= 0 && !(pool->flags & POOL_BH)) {
7342 pool->cpu_stall = true;
7343 cpu_pool_stall = true;
7345 pr_emerg("BUG: workqueue lockup - pool");
7346 pr_cont_pool_info(pool);
7347 pr_cont(" stuck for %us!\n",
7348 jiffies_to_msecs(now - pool_ts) / 1000);
7356 if (lockup_detected)
7357 show_all_workqueues();
7360 show_cpu_pools_hogs();
7362 wq_watchdog_reset_touched();
7363 mod_timer(&wq_watchdog_timer, jiffies + thresh);
7366 notrace void wq_watchdog_touch(int cpu)
7369 per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
7371 wq_watchdog_touched = jiffies;
7374 static void wq_watchdog_set_thresh(unsigned long thresh)
7376 wq_watchdog_thresh = 0;
7377 del_timer_sync(&wq_watchdog_timer);
7380 wq_watchdog_thresh = thresh;
7381 wq_watchdog_reset_touched();
7382 mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
7386 static int wq_watchdog_param_set_thresh(const char *val,
7387 const struct kernel_param *kp)
7389 unsigned long thresh;
7392 ret = kstrtoul(val, 0, &thresh);
7397 wq_watchdog_set_thresh(thresh);
7399 wq_watchdog_thresh = thresh;
7404 static const struct kernel_param_ops wq_watchdog_thresh_ops = {
7405 .set = wq_watchdog_param_set_thresh,
7406 .get = param_get_ulong,
7409 module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
7412 static void wq_watchdog_init(void)
7414 timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
7415 wq_watchdog_set_thresh(wq_watchdog_thresh);
7418 #else /* CONFIG_WQ_WATCHDOG */
7420 static inline void wq_watchdog_init(void) { }
7422 #endif /* CONFIG_WQ_WATCHDOG */
7424 static void bh_pool_kick_normal(struct irq_work *irq_work)
7426 raise_softirq_irqoff(TASKLET_SOFTIRQ);
7429 static void bh_pool_kick_highpri(struct irq_work *irq_work)
7431 raise_softirq_irqoff(HI_SOFTIRQ);
7434 static void __init restrict_unbound_cpumask(const char *name, const struct cpumask *mask)
7436 if (!cpumask_intersects(wq_unbound_cpumask, mask)) {
7437 pr_warn("workqueue: Restricting unbound_cpumask (%*pb) with %s (%*pb) leaves no CPU, ignoring\n",
7438 cpumask_pr_args(wq_unbound_cpumask), name, cpumask_pr_args(mask));
7442 cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, mask);
7445 static void __init init_cpu_worker_pool(struct worker_pool *pool, int cpu, int nice)
7447 BUG_ON(init_worker_pool(pool));
7449 cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
7450 cpumask_copy(pool->attrs->__pod_cpumask, cpumask_of(cpu));
7451 pool->attrs->nice = nice;
7452 pool->attrs->affn_strict = true;
7453 pool->node = cpu_to_node(cpu);
7456 mutex_lock(&wq_pool_mutex);
7457 BUG_ON(worker_pool_assign_id(pool));
7458 mutex_unlock(&wq_pool_mutex);
7462 * workqueue_init_early - early init for workqueue subsystem
7464 * This is the first step of three-staged workqueue subsystem initialization and
7465 * invoked as soon as the bare basics - memory allocation, cpumasks and idr are
7466 * up. It sets up all the data structures and system workqueues and allows early
7467 * boot code to create workqueues and queue/cancel work items. Actual work item
7468 * execution starts only after kthreads can be created and scheduled right
7469 * before early initcalls.
7471 void __init workqueue_init_early(void)
7473 struct wq_pod_type *pt = &wq_pod_types[WQ_AFFN_SYSTEM];
7474 int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
7475 void (*irq_work_fns[2])(struct irq_work *) = { bh_pool_kick_normal,
7476 bh_pool_kick_highpri };
7479 BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
7481 BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
7482 BUG_ON(!alloc_cpumask_var(&wq_requested_unbound_cpumask, GFP_KERNEL));
7483 BUG_ON(!zalloc_cpumask_var(&wq_isolated_cpumask, GFP_KERNEL));
7485 cpumask_copy(wq_unbound_cpumask, cpu_possible_mask);
7486 restrict_unbound_cpumask("HK_TYPE_WQ", housekeeping_cpumask(HK_TYPE_WQ));
7487 restrict_unbound_cpumask("HK_TYPE_DOMAIN", housekeeping_cpumask(HK_TYPE_DOMAIN));
7488 if (!cpumask_empty(&wq_cmdline_cpumask))
7489 restrict_unbound_cpumask("workqueue.unbound_cpus", &wq_cmdline_cpumask);
7491 cpumask_copy(wq_requested_unbound_cpumask, wq_unbound_cpumask);
7493 pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
7495 wq_update_pod_attrs_buf = alloc_workqueue_attrs();
7496 BUG_ON(!wq_update_pod_attrs_buf);
7499 * If nohz_full is enabled, set power efficient workqueue as unbound.
7500 * This allows workqueue items to be moved to HK CPUs.
7502 if (housekeeping_enabled(HK_TYPE_TICK))
7503 wq_power_efficient = true;
7505 /* initialize WQ_AFFN_SYSTEM pods */
7506 pt->pod_cpus = kcalloc(1, sizeof(pt->pod_cpus[0]), GFP_KERNEL);
7507 pt->pod_node = kcalloc(1, sizeof(pt->pod_node[0]), GFP_KERNEL);
7508 pt->cpu_pod = kcalloc(nr_cpu_ids, sizeof(pt->cpu_pod[0]), GFP_KERNEL);
7509 BUG_ON(!pt->pod_cpus || !pt->pod_node || !pt->cpu_pod);
7511 BUG_ON(!zalloc_cpumask_var_node(&pt->pod_cpus[0], GFP_KERNEL, NUMA_NO_NODE));
7514 cpumask_copy(pt->pod_cpus[0], cpu_possible_mask);
7515 pt->pod_node[0] = NUMA_NO_NODE;
7518 /* initialize BH and CPU pools */
7519 for_each_possible_cpu(cpu) {
7520 struct worker_pool *pool;
7523 for_each_bh_worker_pool(pool, cpu) {
7524 init_cpu_worker_pool(pool, cpu, std_nice[i]);
7525 pool->flags |= POOL_BH;
7526 init_irq_work(bh_pool_irq_work(pool), irq_work_fns[i]);
7531 for_each_cpu_worker_pool(pool, cpu)
7532 init_cpu_worker_pool(pool, cpu, std_nice[i++]);
7535 /* create default unbound and ordered wq attrs */
7536 for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
7537 struct workqueue_attrs *attrs;
7539 BUG_ON(!(attrs = alloc_workqueue_attrs()));
7540 attrs->nice = std_nice[i];
7541 unbound_std_wq_attrs[i] = attrs;
7544 * An ordered wq should have only one pwq as ordering is
7545 * guaranteed by max_active which is enforced by pwqs.
7547 BUG_ON(!(attrs = alloc_workqueue_attrs()));
7548 attrs->nice = std_nice[i];
7549 attrs->ordered = true;
7550 ordered_wq_attrs[i] = attrs;
7553 system_wq = alloc_workqueue("events", 0, 0);
7554 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
7555 system_long_wq = alloc_workqueue("events_long", 0, 0);
7556 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
7558 system_freezable_wq = alloc_workqueue("events_freezable",
7560 system_power_efficient_wq = alloc_workqueue("events_power_efficient",
7561 WQ_POWER_EFFICIENT, 0);
7562 system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_pwr_efficient",
7563 WQ_FREEZABLE | WQ_POWER_EFFICIENT,
7565 system_bh_wq = alloc_workqueue("events_bh", WQ_BH, 0);
7566 system_bh_highpri_wq = alloc_workqueue("events_bh_highpri",
7567 WQ_BH | WQ_HIGHPRI, 0);
7568 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
7569 !system_unbound_wq || !system_freezable_wq ||
7570 !system_power_efficient_wq ||
7571 !system_freezable_power_efficient_wq ||
7572 !system_bh_wq || !system_bh_highpri_wq);
7575 static void __init wq_cpu_intensive_thresh_init(void)
7577 unsigned long thresh;
7580 pwq_release_worker = kthread_create_worker(0, "pool_workqueue_release");
7581 BUG_ON(IS_ERR(pwq_release_worker));
7583 /* if the user set it to a specific value, keep it */
7584 if (wq_cpu_intensive_thresh_us != ULONG_MAX)
7588 * The default of 10ms is derived from the fact that most modern (as of
7589 * 2023) processors can do a lot in 10ms and that it's just below what
7590 * most consider human-perceivable. However, the kernel also runs on a
7591 * lot slower CPUs including microcontrollers where the threshold is way
7594 * Let's scale up the threshold upto 1 second if BogoMips is below 4000.
7595 * This is by no means accurate but it doesn't have to be. The mechanism
7596 * is still useful even when the threshold is fully scaled up. Also, as
7597 * the reports would usually be applicable to everyone, some machines
7598 * operating on longer thresholds won't significantly diminish their
7601 thresh = 10 * USEC_PER_MSEC;
7603 /* see init/calibrate.c for lpj -> BogoMIPS calculation */
7604 bogo = max_t(unsigned long, loops_per_jiffy / 500000 * HZ, 1);
7606 thresh = min_t(unsigned long, thresh * 4000 / bogo, USEC_PER_SEC);
7608 pr_debug("wq_cpu_intensive_thresh: lpj=%lu BogoMIPS=%lu thresh_us=%lu\n",
7609 loops_per_jiffy, bogo, thresh);
7611 wq_cpu_intensive_thresh_us = thresh;
7615 * workqueue_init - bring workqueue subsystem fully online
7617 * This is the second step of three-staged workqueue subsystem initialization
7618 * and invoked as soon as kthreads can be created and scheduled. Workqueues have
7619 * been created and work items queued on them, but there are no kworkers
7620 * executing the work items yet. Populate the worker pools with the initial
7621 * workers and enable future kworker creations.
7623 void __init workqueue_init(void)
7625 struct workqueue_struct *wq;
7626 struct worker_pool *pool;
7629 wq_cpu_intensive_thresh_init();
7631 mutex_lock(&wq_pool_mutex);
7634 * Per-cpu pools created earlier could be missing node hint. Fix them
7635 * up. Also, create a rescuer for workqueues that requested it.
7637 for_each_possible_cpu(cpu) {
7638 for_each_bh_worker_pool(pool, cpu)
7639 pool->node = cpu_to_node(cpu);
7640 for_each_cpu_worker_pool(pool, cpu)
7641 pool->node = cpu_to_node(cpu);
7644 list_for_each_entry(wq, &workqueues, list) {
7645 WARN(init_rescuer(wq),
7646 "workqueue: failed to create early rescuer for %s",
7650 mutex_unlock(&wq_pool_mutex);
7653 * Create the initial workers. A BH pool has one pseudo worker that
7654 * represents the shared BH execution context and thus doesn't get
7655 * affected by hotplug events. Create the BH pseudo workers for all
7656 * possible CPUs here.
7658 for_each_possible_cpu(cpu)
7659 for_each_bh_worker_pool(pool, cpu)
7660 BUG_ON(!create_worker(pool));
7662 for_each_online_cpu(cpu) {
7663 for_each_cpu_worker_pool(pool, cpu) {
7664 pool->flags &= ~POOL_DISASSOCIATED;
7665 BUG_ON(!create_worker(pool));
7669 hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
7670 BUG_ON(!create_worker(pool));
7677 * Initialize @pt by first initializing @pt->cpu_pod[] with pod IDs according to
7678 * @cpu_shares_pod(). Each subset of CPUs that share a pod is assigned a unique
7679 * and consecutive pod ID. The rest of @pt is initialized accordingly.
7681 static void __init init_pod_type(struct wq_pod_type *pt,
7682 bool (*cpus_share_pod)(int, int))
7684 int cur, pre, cpu, pod;
7688 /* init @pt->cpu_pod[] according to @cpus_share_pod() */
7689 pt->cpu_pod = kcalloc(nr_cpu_ids, sizeof(pt->cpu_pod[0]), GFP_KERNEL);
7690 BUG_ON(!pt->cpu_pod);
7692 for_each_possible_cpu(cur) {
7693 for_each_possible_cpu(pre) {
7695 pt->cpu_pod[cur] = pt->nr_pods++;
7698 if (cpus_share_pod(cur, pre)) {
7699 pt->cpu_pod[cur] = pt->cpu_pod[pre];
7705 /* init the rest to match @pt->cpu_pod[] */
7706 pt->pod_cpus = kcalloc(pt->nr_pods, sizeof(pt->pod_cpus[0]), GFP_KERNEL);
7707 pt->pod_node = kcalloc(pt->nr_pods, sizeof(pt->pod_node[0]), GFP_KERNEL);
7708 BUG_ON(!pt->pod_cpus || !pt->pod_node);
7710 for (pod = 0; pod < pt->nr_pods; pod++)
7711 BUG_ON(!zalloc_cpumask_var(&pt->pod_cpus[pod], GFP_KERNEL));
7713 for_each_possible_cpu(cpu) {
7714 cpumask_set_cpu(cpu, pt->pod_cpus[pt->cpu_pod[cpu]]);
7715 pt->pod_node[pt->cpu_pod[cpu]] = cpu_to_node(cpu);
7719 static bool __init cpus_dont_share(int cpu0, int cpu1)
7724 static bool __init cpus_share_smt(int cpu0, int cpu1)
7726 #ifdef CONFIG_SCHED_SMT
7727 return cpumask_test_cpu(cpu0, cpu_smt_mask(cpu1));
7733 static bool __init cpus_share_numa(int cpu0, int cpu1)
7735 return cpu_to_node(cpu0) == cpu_to_node(cpu1);
7739 * workqueue_init_topology - initialize CPU pods for unbound workqueues
7741 * This is the third step of three-staged workqueue subsystem initialization and
7742 * invoked after SMP and topology information are fully initialized. It
7743 * initializes the unbound CPU pods accordingly.
7745 void __init workqueue_init_topology(void)
7747 struct workqueue_struct *wq;
7750 init_pod_type(&wq_pod_types[WQ_AFFN_CPU], cpus_dont_share);
7751 init_pod_type(&wq_pod_types[WQ_AFFN_SMT], cpus_share_smt);
7752 init_pod_type(&wq_pod_types[WQ_AFFN_CACHE], cpus_share_cache);
7753 init_pod_type(&wq_pod_types[WQ_AFFN_NUMA], cpus_share_numa);
7755 wq_topo_initialized = true;
7757 mutex_lock(&wq_pool_mutex);
7760 * Workqueues allocated earlier would have all CPUs sharing the default
7761 * worker pool. Explicitly call wq_update_pod() on all workqueue and CPU
7762 * combinations to apply per-pod sharing.
7764 list_for_each_entry(wq, &workqueues, list) {
7765 for_each_online_cpu(cpu)
7766 wq_update_pod(wq, cpu, cpu, true);
7767 if (wq->flags & WQ_UNBOUND) {
7768 mutex_lock(&wq->mutex);
7769 wq_update_node_max_active(wq, -1);
7770 mutex_unlock(&wq->mutex);
7774 mutex_unlock(&wq_pool_mutex);
7777 void __warn_flushing_systemwide_wq(void)
7779 pr_warn("WARNING: Flushing system-wide workqueues will be prohibited in near future.\n");
7782 EXPORT_SYMBOL(__warn_flushing_systemwide_wq);
7784 static int __init workqueue_unbound_cpus_setup(char *str)
7786 if (cpulist_parse(str, &wq_cmdline_cpumask) < 0) {
7787 cpumask_clear(&wq_cmdline_cpumask);
7788 pr_warn("workqueue.unbound_cpus: incorrect CPU range, using default\n");
7793 __setup("workqueue.unbound_cpus=", workqueue_unbound_cpus_setup);