1 // SPDX-License-Identifier: GPL-2.0-only
3 * kernel/workqueue.c - generic async execution with shared worker pool
5 * Copyright (C) 2002 Ingo Molnar
7 * Derived from the taskqueue/keventd code by:
8 * David Woodhouse <dwmw2@infradead.org>
10 * Kai Petzke <wpp@marie.physik.tu-berlin.de>
11 * Theodore Ts'o <tytso@mit.edu>
13 * Made to use alloc_percpu by Christoph Lameter.
15 * Copyright (C) 2010 SUSE Linux Products GmbH
16 * Copyright (C) 2010 Tejun Heo <tj@kernel.org>
18 * This is the generic async execution mechanism. Work items as are
19 * executed in process context. The worker pool is shared and
20 * automatically managed. There are two worker pools for each CPU (one for
21 * normal work items and the other for high priority ones) and some extra
22 * pools for workqueues which are not bound to any specific CPU - the
23 * number of these backing pools is dynamic.
25 * Please read Documentation/core-api/workqueue.rst for details.
28 #include <linux/export.h>
29 #include <linux/kernel.h>
30 #include <linux/sched.h>
31 #include <linux/init.h>
32 #include <linux/signal.h>
33 #include <linux/completion.h>
34 #include <linux/workqueue.h>
35 #include <linux/slab.h>
36 #include <linux/cpu.h>
37 #include <linux/notifier.h>
38 #include <linux/kthread.h>
39 #include <linux/hardirq.h>
40 #include <linux/mempolicy.h>
41 #include <linux/freezer.h>
42 #include <linux/debug_locks.h>
43 #include <linux/lockdep.h>
44 #include <linux/idr.h>
45 #include <linux/jhash.h>
46 #include <linux/hashtable.h>
47 #include <linux/rculist.h>
48 #include <linux/nodemask.h>
49 #include <linux/moduleparam.h>
50 #include <linux/uaccess.h>
51 #include <linux/sched/isolation.h>
52 #include <linux/nmi.h>
53 #include <linux/kvm_para.h>
55 #include "workqueue_internal.h"
61 * A bound pool is either associated or disassociated with its CPU.
62 * While associated (!DISASSOCIATED), all workers are bound to the
63 * CPU and none has %WORKER_UNBOUND set and concurrency management
66 * While DISASSOCIATED, the cpu may be offline and all workers have
67 * %WORKER_UNBOUND set and concurrency management disabled, and may
68 * be executing on any CPU. The pool behaves as an unbound one.
70 * Note that DISASSOCIATED should be flipped only while holding
71 * wq_pool_attach_mutex to avoid changing binding state while
72 * worker_attach_to_pool() is in progress.
74 POOL_MANAGER_ACTIVE = 1 << 0, /* being managed */
75 POOL_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
78 WORKER_DIE = 1 << 1, /* die die die */
79 WORKER_IDLE = 1 << 2, /* is idle */
80 WORKER_PREP = 1 << 3, /* preparing to run works */
81 WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
82 WORKER_UNBOUND = 1 << 7, /* worker is unbound */
83 WORKER_REBOUND = 1 << 8, /* worker was rebound */
85 WORKER_NOT_RUNNING = WORKER_PREP | WORKER_CPU_INTENSIVE |
86 WORKER_UNBOUND | WORKER_REBOUND,
88 NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */
90 UNBOUND_POOL_HASH_ORDER = 6, /* hashed by pool->attrs */
91 BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
93 MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
94 IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
96 MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
97 /* call for help after 10ms
99 MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
100 CREATE_COOLDOWN = HZ, /* time to breath after fail */
103 * Rescue workers are used only on emergencies and shared by
104 * all cpus. Give MIN_NICE.
106 RESCUER_NICE_LEVEL = MIN_NICE,
107 HIGHPRI_NICE_LEVEL = MIN_NICE,
113 * Structure fields follow one of the following exclusion rules.
115 * I: Modifiable by initialization/destruction paths and read-only for
118 * P: Preemption protected. Disabling preemption is enough and should
119 * only be modified and accessed from the local cpu.
121 * L: pool->lock protected. Access with pool->lock held.
123 * X: During normal operation, modification requires pool->lock and should
124 * be done only from local cpu. Either disabling preemption on local
125 * cpu or grabbing pool->lock is enough for read access. If
126 * POOL_DISASSOCIATED is set, it's identical to L.
128 * A: wq_pool_attach_mutex protected.
130 * PL: wq_pool_mutex protected.
132 * PR: wq_pool_mutex protected for writes. RCU protected for reads.
134 * PW: wq_pool_mutex and wq->mutex protected for writes. Either for reads.
136 * PWR: wq_pool_mutex and wq->mutex protected for writes. Either or
139 * WQ: wq->mutex protected.
141 * WR: wq->mutex protected for writes. RCU protected for reads.
143 * MD: wq_mayday_lock protected.
146 /* struct worker is defined in workqueue_internal.h */
149 raw_spinlock_t lock; /* the pool lock */
150 int cpu; /* I: the associated cpu */
151 int node; /* I: the associated node ID */
152 int id; /* I: pool ID */
153 unsigned int flags; /* X: flags */
155 unsigned long watchdog_ts; /* L: watchdog timestamp */
158 * The counter is incremented in a process context on the associated CPU
159 * w/ preemption disabled, and decremented or reset in the same context
160 * but w/ pool->lock held. The readers grab pool->lock and are
161 * guaranteed to see if the counter reached zero.
165 struct list_head worklist; /* L: list of pending works */
167 int nr_workers; /* L: total number of workers */
168 int nr_idle; /* L: currently idle workers */
170 struct list_head idle_list; /* L: list of idle workers */
171 struct timer_list idle_timer; /* L: worker idle timeout */
172 struct timer_list mayday_timer; /* L: SOS timer for workers */
174 /* a workers is either on busy_hash or idle_list, or the manager */
175 DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
176 /* L: hash of busy workers */
178 struct worker *manager; /* L: purely informational */
179 struct list_head workers; /* A: attached workers */
180 struct completion *detach_completion; /* all workers detached */
182 struct ida worker_ida; /* worker IDs for task name */
184 struct workqueue_attrs *attrs; /* I: worker attributes */
185 struct hlist_node hash_node; /* PL: unbound_pool_hash node */
186 int refcnt; /* PL: refcnt for unbound pools */
189 * Destruction of pool is RCU protected to allow dereferences
190 * from get_work_pool().
196 * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
197 * of work_struct->data are used for flags and the remaining high bits
198 * point to the pwq; thus, pwqs need to be aligned at two's power of the
199 * number of flag bits.
201 struct pool_workqueue {
202 struct worker_pool *pool; /* I: the associated pool */
203 struct workqueue_struct *wq; /* I: the owning workqueue */
204 int work_color; /* L: current color */
205 int flush_color; /* L: flushing color */
206 int refcnt; /* L: reference count */
207 int nr_in_flight[WORK_NR_COLORS];
208 /* L: nr of in_flight works */
211 * nr_active management and WORK_STRUCT_INACTIVE:
213 * When pwq->nr_active >= max_active, new work item is queued to
214 * pwq->inactive_works instead of pool->worklist and marked with
215 * WORK_STRUCT_INACTIVE.
217 * All work items marked with WORK_STRUCT_INACTIVE do not participate
218 * in pwq->nr_active and all work items in pwq->inactive_works are
219 * marked with WORK_STRUCT_INACTIVE. But not all WORK_STRUCT_INACTIVE
220 * work items are in pwq->inactive_works. Some of them are ready to
221 * run in pool->worklist or worker->scheduled. Those work itmes are
222 * only struct wq_barrier which is used for flush_work() and should
223 * not participate in pwq->nr_active. For non-barrier work item, it
224 * is marked with WORK_STRUCT_INACTIVE iff it is in pwq->inactive_works.
226 int nr_active; /* L: nr of active works */
227 int max_active; /* L: max active works */
228 struct list_head inactive_works; /* L: inactive works */
229 struct list_head pwqs_node; /* WR: node on wq->pwqs */
230 struct list_head mayday_node; /* MD: node on wq->maydays */
233 * Release of unbound pwq is punted to system_wq. See put_pwq()
234 * and pwq_unbound_release_workfn() for details. pool_workqueue
235 * itself is also RCU protected so that the first pwq can be
236 * determined without grabbing wq->mutex.
238 struct work_struct unbound_release_work;
240 } __aligned(1 << WORK_STRUCT_FLAG_BITS);
243 * Structure used to wait for workqueue flush.
246 struct list_head list; /* WQ: list of flushers */
247 int flush_color; /* WQ: flush color waiting for */
248 struct completion done; /* flush completion */
254 * The externally visible workqueue. It relays the issued work items to
255 * the appropriate worker_pool through its pool_workqueues.
257 struct workqueue_struct {
258 struct list_head pwqs; /* WR: all pwqs of this wq */
259 struct list_head list; /* PR: list of all workqueues */
261 struct mutex mutex; /* protects this wq */
262 int work_color; /* WQ: current work color */
263 int flush_color; /* WQ: current flush color */
264 atomic_t nr_pwqs_to_flush; /* flush in progress */
265 struct wq_flusher *first_flusher; /* WQ: first flusher */
266 struct list_head flusher_queue; /* WQ: flush waiters */
267 struct list_head flusher_overflow; /* WQ: flush overflow list */
269 struct list_head maydays; /* MD: pwqs requesting rescue */
270 struct worker *rescuer; /* MD: rescue worker */
272 int nr_drainers; /* WQ: drain in progress */
273 int saved_max_active; /* WQ: saved pwq max_active */
275 struct workqueue_attrs *unbound_attrs; /* PW: only for unbound wqs */
276 struct pool_workqueue *dfl_pwq; /* PW: only for unbound wqs */
279 struct wq_device *wq_dev; /* I: for sysfs interface */
281 #ifdef CONFIG_LOCKDEP
283 struct lock_class_key key;
284 struct lockdep_map lockdep_map;
286 char name[WQ_NAME_LEN]; /* I: workqueue name */
289 * Destruction of workqueue_struct is RCU protected to allow walking
290 * the workqueues list without grabbing wq_pool_mutex.
291 * This is used to dump all workqueues from sysrq.
295 /* hot fields used during command issue, aligned to cacheline */
296 unsigned int flags ____cacheline_aligned; /* WQ: WQ_* flags */
297 struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */
298 struct pool_workqueue __rcu *numa_pwq_tbl[]; /* PWR: unbound pwqs indexed by node */
301 static struct kmem_cache *pwq_cache;
303 static cpumask_var_t *wq_numa_possible_cpumask;
304 /* possible CPUs of each node */
306 static bool wq_disable_numa;
307 module_param_named(disable_numa, wq_disable_numa, bool, 0444);
309 /* see the comment above the definition of WQ_POWER_EFFICIENT */
310 static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
311 module_param_named(power_efficient, wq_power_efficient, bool, 0444);
313 static bool wq_online; /* can kworkers be created yet? */
315 static bool wq_numa_enabled; /* unbound NUMA affinity enabled */
317 /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
318 static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf;
320 static DEFINE_MUTEX(wq_pool_mutex); /* protects pools and workqueues list */
321 static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
322 static DEFINE_RAW_SPINLOCK(wq_mayday_lock); /* protects wq->maydays list */
323 /* wait for manager to go away */
324 static struct rcuwait manager_wait = __RCUWAIT_INITIALIZER(manager_wait);
326 static LIST_HEAD(workqueues); /* PR: list of all workqueues */
327 static bool workqueue_freezing; /* PL: have wqs started freezing? */
329 /* PL&A: allowable cpus for unbound wqs and work items */
330 static cpumask_var_t wq_unbound_cpumask;
332 /* CPU where unbound work was last round robin scheduled from this CPU */
333 static DEFINE_PER_CPU(int, wq_rr_cpu_last);
336 * Local execution of unbound work items is no longer guaranteed. The
337 * following always forces round-robin CPU selection on unbound work items
338 * to uncover usages which depend on it.
340 #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
341 static bool wq_debug_force_rr_cpu = true;
343 static bool wq_debug_force_rr_cpu = false;
345 module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
347 /* the per-cpu worker pools */
348 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools);
350 static DEFINE_IDR(worker_pool_idr); /* PR: idr of all pools */
352 /* PL: hash of all unbound pools keyed by pool->attrs */
353 static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
355 /* I: attributes used when instantiating standard unbound pools on demand */
356 static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
358 /* I: attributes used when instantiating ordered pools on demand */
359 static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
361 struct workqueue_struct *system_wq __read_mostly;
362 EXPORT_SYMBOL(system_wq);
363 struct workqueue_struct *system_highpri_wq __read_mostly;
364 EXPORT_SYMBOL_GPL(system_highpri_wq);
365 struct workqueue_struct *system_long_wq __read_mostly;
366 EXPORT_SYMBOL_GPL(system_long_wq);
367 struct workqueue_struct *system_unbound_wq __read_mostly;
368 EXPORT_SYMBOL_GPL(system_unbound_wq);
369 struct workqueue_struct *system_freezable_wq __read_mostly;
370 EXPORT_SYMBOL_GPL(system_freezable_wq);
371 struct workqueue_struct *system_power_efficient_wq __read_mostly;
372 EXPORT_SYMBOL_GPL(system_power_efficient_wq);
373 struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
374 EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
376 static int worker_thread(void *__worker);
377 static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
378 static void show_pwq(struct pool_workqueue *pwq);
379 static void show_one_worker_pool(struct worker_pool *pool);
381 #define CREATE_TRACE_POINTS
382 #include <trace/events/workqueue.h>
384 #define assert_rcu_or_pool_mutex() \
385 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
386 !lockdep_is_held(&wq_pool_mutex), \
387 "RCU or wq_pool_mutex should be held")
389 #define assert_rcu_or_wq_mutex_or_pool_mutex(wq) \
390 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
391 !lockdep_is_held(&wq->mutex) && \
392 !lockdep_is_held(&wq_pool_mutex), \
393 "RCU, wq->mutex or wq_pool_mutex should be held")
395 #define for_each_cpu_worker_pool(pool, cpu) \
396 for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
397 (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
401 * for_each_pool - iterate through all worker_pools in the system
402 * @pool: iteration cursor
403 * @pi: integer used for iteration
405 * This must be called either with wq_pool_mutex held or RCU read
406 * locked. If the pool needs to be used beyond the locking in effect, the
407 * caller is responsible for guaranteeing that the pool stays online.
409 * The if/else clause exists only for the lockdep assertion and can be
412 #define for_each_pool(pool, pi) \
413 idr_for_each_entry(&worker_pool_idr, pool, pi) \
414 if (({ assert_rcu_or_pool_mutex(); false; })) { } \
418 * for_each_pool_worker - iterate through all workers of a worker_pool
419 * @worker: iteration cursor
420 * @pool: worker_pool to iterate workers of
422 * This must be called with wq_pool_attach_mutex.
424 * The if/else clause exists only for the lockdep assertion and can be
427 #define for_each_pool_worker(worker, pool) \
428 list_for_each_entry((worker), &(pool)->workers, node) \
429 if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
433 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
434 * @pwq: iteration cursor
435 * @wq: the target workqueue
437 * This must be called either with wq->mutex held or RCU read locked.
438 * If the pwq needs to be used beyond the locking in effect, the caller is
439 * responsible for guaranteeing that the pwq stays online.
441 * The if/else clause exists only for the lockdep assertion and can be
444 #define for_each_pwq(pwq, wq) \
445 list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node, \
446 lockdep_is_held(&(wq->mutex)))
448 #ifdef CONFIG_DEBUG_OBJECTS_WORK
450 static const struct debug_obj_descr work_debug_descr;
452 static void *work_debug_hint(void *addr)
454 return ((struct work_struct *) addr)->func;
457 static bool work_is_static_object(void *addr)
459 struct work_struct *work = addr;
461 return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
465 * fixup_init is called when:
466 * - an active object is initialized
468 static bool work_fixup_init(void *addr, enum debug_obj_state state)
470 struct work_struct *work = addr;
473 case ODEBUG_STATE_ACTIVE:
474 cancel_work_sync(work);
475 debug_object_init(work, &work_debug_descr);
483 * fixup_free is called when:
484 * - an active object is freed
486 static bool work_fixup_free(void *addr, enum debug_obj_state state)
488 struct work_struct *work = addr;
491 case ODEBUG_STATE_ACTIVE:
492 cancel_work_sync(work);
493 debug_object_free(work, &work_debug_descr);
500 static const struct debug_obj_descr work_debug_descr = {
501 .name = "work_struct",
502 .debug_hint = work_debug_hint,
503 .is_static_object = work_is_static_object,
504 .fixup_init = work_fixup_init,
505 .fixup_free = work_fixup_free,
508 static inline void debug_work_activate(struct work_struct *work)
510 debug_object_activate(work, &work_debug_descr);
513 static inline void debug_work_deactivate(struct work_struct *work)
515 debug_object_deactivate(work, &work_debug_descr);
518 void __init_work(struct work_struct *work, int onstack)
521 debug_object_init_on_stack(work, &work_debug_descr);
523 debug_object_init(work, &work_debug_descr);
525 EXPORT_SYMBOL_GPL(__init_work);
527 void destroy_work_on_stack(struct work_struct *work)
529 debug_object_free(work, &work_debug_descr);
531 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
533 void destroy_delayed_work_on_stack(struct delayed_work *work)
535 destroy_timer_on_stack(&work->timer);
536 debug_object_free(&work->work, &work_debug_descr);
538 EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
541 static inline void debug_work_activate(struct work_struct *work) { }
542 static inline void debug_work_deactivate(struct work_struct *work) { }
546 * worker_pool_assign_id - allocate ID and assign it to @pool
547 * @pool: the pool pointer of interest
549 * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
550 * successfully, -errno on failure.
552 static int worker_pool_assign_id(struct worker_pool *pool)
556 lockdep_assert_held(&wq_pool_mutex);
558 ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
568 * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
569 * @wq: the target workqueue
572 * This must be called with any of wq_pool_mutex, wq->mutex or RCU
574 * If the pwq needs to be used beyond the locking in effect, the caller is
575 * responsible for guaranteeing that the pwq stays online.
577 * Return: The unbound pool_workqueue for @node.
579 static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
582 assert_rcu_or_wq_mutex_or_pool_mutex(wq);
585 * XXX: @node can be NUMA_NO_NODE if CPU goes offline while a
586 * delayed item is pending. The plan is to keep CPU -> NODE
587 * mapping valid and stable across CPU on/offlines. Once that
588 * happens, this workaround can be removed.
590 if (unlikely(node == NUMA_NO_NODE))
593 return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
596 static unsigned int work_color_to_flags(int color)
598 return color << WORK_STRUCT_COLOR_SHIFT;
601 static int get_work_color(unsigned long work_data)
603 return (work_data >> WORK_STRUCT_COLOR_SHIFT) &
604 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
607 static int work_next_color(int color)
609 return (color + 1) % WORK_NR_COLORS;
613 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
614 * contain the pointer to the queued pwq. Once execution starts, the flag
615 * is cleared and the high bits contain OFFQ flags and pool ID.
617 * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
618 * and clear_work_data() can be used to set the pwq, pool or clear
619 * work->data. These functions should only be called while the work is
620 * owned - ie. while the PENDING bit is set.
622 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
623 * corresponding to a work. Pool is available once the work has been
624 * queued anywhere after initialization until it is sync canceled. pwq is
625 * available only while the work item is queued.
627 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
628 * canceled. While being canceled, a work item may have its PENDING set
629 * but stay off timer and worklist for arbitrarily long and nobody should
630 * try to steal the PENDING bit.
632 static inline void set_work_data(struct work_struct *work, unsigned long data,
635 WARN_ON_ONCE(!work_pending(work));
636 atomic_long_set(&work->data, data | flags | work_static(work));
639 static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
640 unsigned long extra_flags)
642 set_work_data(work, (unsigned long)pwq,
643 WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
646 static void set_work_pool_and_keep_pending(struct work_struct *work,
649 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
650 WORK_STRUCT_PENDING);
653 static void set_work_pool_and_clear_pending(struct work_struct *work,
657 * The following wmb is paired with the implied mb in
658 * test_and_set_bit(PENDING) and ensures all updates to @work made
659 * here are visible to and precede any updates by the next PENDING
663 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
665 * The following mb guarantees that previous clear of a PENDING bit
666 * will not be reordered with any speculative LOADS or STORES from
667 * work->current_func, which is executed afterwards. This possible
668 * reordering can lead to a missed execution on attempt to queue
669 * the same @work. E.g. consider this case:
672 * ---------------------------- --------------------------------
674 * 1 STORE event_indicated
675 * 2 queue_work_on() {
676 * 3 test_and_set_bit(PENDING)
677 * 4 } set_..._and_clear_pending() {
678 * 5 set_work_data() # clear bit
680 * 7 work->current_func() {
681 * 8 LOAD event_indicated
684 * Without an explicit full barrier speculative LOAD on line 8 can
685 * be executed before CPU#0 does STORE on line 1. If that happens,
686 * CPU#0 observes the PENDING bit is still set and new execution of
687 * a @work is not queued in a hope, that CPU#1 will eventually
688 * finish the queued @work. Meanwhile CPU#1 does not see
689 * event_indicated is set, because speculative LOAD was executed
690 * before actual STORE.
695 static void clear_work_data(struct work_struct *work)
697 smp_wmb(); /* see set_work_pool_and_clear_pending() */
698 set_work_data(work, WORK_STRUCT_NO_POOL, 0);
701 static inline struct pool_workqueue *work_struct_pwq(unsigned long data)
703 return (struct pool_workqueue *)(data & WORK_STRUCT_WQ_DATA_MASK);
706 static struct pool_workqueue *get_work_pwq(struct work_struct *work)
708 unsigned long data = atomic_long_read(&work->data);
710 if (data & WORK_STRUCT_PWQ)
711 return work_struct_pwq(data);
717 * get_work_pool - return the worker_pool a given work was associated with
718 * @work: the work item of interest
720 * Pools are created and destroyed under wq_pool_mutex, and allows read
721 * access under RCU read lock. As such, this function should be
722 * called under wq_pool_mutex or inside of a rcu_read_lock() region.
724 * All fields of the returned pool are accessible as long as the above
725 * mentioned locking is in effect. If the returned pool needs to be used
726 * beyond the critical section, the caller is responsible for ensuring the
727 * returned pool is and stays online.
729 * Return: The worker_pool @work was last associated with. %NULL if none.
731 static struct worker_pool *get_work_pool(struct work_struct *work)
733 unsigned long data = atomic_long_read(&work->data);
736 assert_rcu_or_pool_mutex();
738 if (data & WORK_STRUCT_PWQ)
739 return work_struct_pwq(data)->pool;
741 pool_id = data >> WORK_OFFQ_POOL_SHIFT;
742 if (pool_id == WORK_OFFQ_POOL_NONE)
745 return idr_find(&worker_pool_idr, pool_id);
749 * get_work_pool_id - return the worker pool ID a given work is associated with
750 * @work: the work item of interest
752 * Return: The worker_pool ID @work was last associated with.
753 * %WORK_OFFQ_POOL_NONE if none.
755 static int get_work_pool_id(struct work_struct *work)
757 unsigned long data = atomic_long_read(&work->data);
759 if (data & WORK_STRUCT_PWQ)
760 return work_struct_pwq(data)->pool->id;
762 return data >> WORK_OFFQ_POOL_SHIFT;
765 static void mark_work_canceling(struct work_struct *work)
767 unsigned long pool_id = get_work_pool_id(work);
769 pool_id <<= WORK_OFFQ_POOL_SHIFT;
770 set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
773 static bool work_is_canceling(struct work_struct *work)
775 unsigned long data = atomic_long_read(&work->data);
777 return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
781 * Policy functions. These define the policies on how the global worker
782 * pools are managed. Unless noted otherwise, these functions assume that
783 * they're being called with pool->lock held.
786 static bool __need_more_worker(struct worker_pool *pool)
788 return !pool->nr_running;
792 * Need to wake up a worker? Called from anything but currently
795 * Note that, because unbound workers never contribute to nr_running, this
796 * function will always return %true for unbound pools as long as the
797 * worklist isn't empty.
799 static bool need_more_worker(struct worker_pool *pool)
801 return !list_empty(&pool->worklist) && __need_more_worker(pool);
804 /* Can I start working? Called from busy but !running workers. */
805 static bool may_start_working(struct worker_pool *pool)
807 return pool->nr_idle;
810 /* Do I need to keep working? Called from currently running workers. */
811 static bool keep_working(struct worker_pool *pool)
813 return !list_empty(&pool->worklist) && (pool->nr_running <= 1);
816 /* Do we need a new worker? Called from manager. */
817 static bool need_to_create_worker(struct worker_pool *pool)
819 return need_more_worker(pool) && !may_start_working(pool);
822 /* Do we have too many workers and should some go away? */
823 static bool too_many_workers(struct worker_pool *pool)
825 bool managing = pool->flags & POOL_MANAGER_ACTIVE;
826 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
827 int nr_busy = pool->nr_workers - nr_idle;
829 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
836 /* Return the first idle worker. Called with pool->lock held. */
837 static struct worker *first_idle_worker(struct worker_pool *pool)
839 if (unlikely(list_empty(&pool->idle_list)))
842 return list_first_entry(&pool->idle_list, struct worker, entry);
846 * wake_up_worker - wake up an idle worker
847 * @pool: worker pool to wake worker from
849 * Wake up the first idle worker of @pool.
852 * raw_spin_lock_irq(pool->lock).
854 static void wake_up_worker(struct worker_pool *pool)
856 struct worker *worker = first_idle_worker(pool);
859 wake_up_process(worker->task);
863 * wq_worker_running - a worker is running again
864 * @task: task waking up
866 * This function is called when a worker returns from schedule()
868 void wq_worker_running(struct task_struct *task)
870 struct worker *worker = kthread_data(task);
872 if (!worker->sleeping)
876 * If preempted by unbind_workers() between the WORKER_NOT_RUNNING check
877 * and the nr_running increment below, we may ruin the nr_running reset
878 * and leave with an unexpected pool->nr_running == 1 on the newly unbound
879 * pool. Protect against such race.
882 if (!(worker->flags & WORKER_NOT_RUNNING))
883 worker->pool->nr_running++;
885 worker->sleeping = 0;
889 * wq_worker_sleeping - a worker is going to sleep
890 * @task: task going to sleep
892 * This function is called from schedule() when a busy worker is
895 void wq_worker_sleeping(struct task_struct *task)
897 struct worker *worker = kthread_data(task);
898 struct worker_pool *pool;
901 * Rescuers, which may not have all the fields set up like normal
902 * workers, also reach here, let's not access anything before
903 * checking NOT_RUNNING.
905 if (worker->flags & WORKER_NOT_RUNNING)
910 /* Return if preempted before wq_worker_running() was reached */
911 if (worker->sleeping)
914 worker->sleeping = 1;
915 raw_spin_lock_irq(&pool->lock);
918 * Recheck in case unbind_workers() preempted us. We don't
919 * want to decrement nr_running after the worker is unbound
920 * and nr_running has been reset.
922 if (worker->flags & WORKER_NOT_RUNNING) {
923 raw_spin_unlock_irq(&pool->lock);
928 if (need_more_worker(pool))
929 wake_up_worker(pool);
930 raw_spin_unlock_irq(&pool->lock);
934 * wq_worker_last_func - retrieve worker's last work function
935 * @task: Task to retrieve last work function of.
937 * Determine the last function a worker executed. This is called from
938 * the scheduler to get a worker's last known identity.
941 * raw_spin_lock_irq(rq->lock)
943 * This function is called during schedule() when a kworker is going
944 * to sleep. It's used by psi to identify aggregation workers during
945 * dequeuing, to allow periodic aggregation to shut-off when that
946 * worker is the last task in the system or cgroup to go to sleep.
948 * As this function doesn't involve any workqueue-related locking, it
949 * only returns stable values when called from inside the scheduler's
950 * queuing and dequeuing paths, when @task, which must be a kworker,
951 * is guaranteed to not be processing any works.
954 * The last work function %current executed as a worker, NULL if it
955 * hasn't executed any work yet.
957 work_func_t wq_worker_last_func(struct task_struct *task)
959 struct worker *worker = kthread_data(task);
961 return worker->last_func;
965 * worker_set_flags - set worker flags and adjust nr_running accordingly
967 * @flags: flags to set
969 * Set @flags in @worker->flags and adjust nr_running accordingly.
972 * raw_spin_lock_irq(pool->lock)
974 static inline void worker_set_flags(struct worker *worker, unsigned int flags)
976 struct worker_pool *pool = worker->pool;
978 WARN_ON_ONCE(worker->task != current);
980 /* If transitioning into NOT_RUNNING, adjust nr_running. */
981 if ((flags & WORKER_NOT_RUNNING) &&
982 !(worker->flags & WORKER_NOT_RUNNING)) {
986 worker->flags |= flags;
990 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
992 * @flags: flags to clear
994 * Clear @flags in @worker->flags and adjust nr_running accordingly.
997 * raw_spin_lock_irq(pool->lock)
999 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
1001 struct worker_pool *pool = worker->pool;
1002 unsigned int oflags = worker->flags;
1004 WARN_ON_ONCE(worker->task != current);
1006 worker->flags &= ~flags;
1009 * If transitioning out of NOT_RUNNING, increment nr_running. Note
1010 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
1011 * of multiple flags, not a single flag.
1013 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
1014 if (!(worker->flags & WORKER_NOT_RUNNING))
1019 * find_worker_executing_work - find worker which is executing a work
1020 * @pool: pool of interest
1021 * @work: work to find worker for
1023 * Find a worker which is executing @work on @pool by searching
1024 * @pool->busy_hash which is keyed by the address of @work. For a worker
1025 * to match, its current execution should match the address of @work and
1026 * its work function. This is to avoid unwanted dependency between
1027 * unrelated work executions through a work item being recycled while still
1030 * This is a bit tricky. A work item may be freed once its execution
1031 * starts and nothing prevents the freed area from being recycled for
1032 * another work item. If the same work item address ends up being reused
1033 * before the original execution finishes, workqueue will identify the
1034 * recycled work item as currently executing and make it wait until the
1035 * current execution finishes, introducing an unwanted dependency.
1037 * This function checks the work item address and work function to avoid
1038 * false positives. Note that this isn't complete as one may construct a
1039 * work function which can introduce dependency onto itself through a
1040 * recycled work item. Well, if somebody wants to shoot oneself in the
1041 * foot that badly, there's only so much we can do, and if such deadlock
1042 * actually occurs, it should be easy to locate the culprit work function.
1045 * raw_spin_lock_irq(pool->lock).
1048 * Pointer to worker which is executing @work if found, %NULL
1051 static struct worker *find_worker_executing_work(struct worker_pool *pool,
1052 struct work_struct *work)
1054 struct worker *worker;
1056 hash_for_each_possible(pool->busy_hash, worker, hentry,
1057 (unsigned long)work)
1058 if (worker->current_work == work &&
1059 worker->current_func == work->func)
1066 * move_linked_works - move linked works to a list
1067 * @work: start of series of works to be scheduled
1068 * @head: target list to append @work to
1069 * @nextp: out parameter for nested worklist walking
1071 * Schedule linked works starting from @work to @head. Work series to
1072 * be scheduled starts at @work and includes any consecutive work with
1073 * WORK_STRUCT_LINKED set in its predecessor.
1075 * If @nextp is not NULL, it's updated to point to the next work of
1076 * the last scheduled work. This allows move_linked_works() to be
1077 * nested inside outer list_for_each_entry_safe().
1080 * raw_spin_lock_irq(pool->lock).
1082 static void move_linked_works(struct work_struct *work, struct list_head *head,
1083 struct work_struct **nextp)
1085 struct work_struct *n;
1088 * Linked worklist will always end before the end of the list,
1089 * use NULL for list head.
1091 list_for_each_entry_safe_from(work, n, NULL, entry) {
1092 list_move_tail(&work->entry, head);
1093 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1098 * If we're already inside safe list traversal and have moved
1099 * multiple works to the scheduled queue, the next position
1100 * needs to be updated.
1107 * get_pwq - get an extra reference on the specified pool_workqueue
1108 * @pwq: pool_workqueue to get
1110 * Obtain an extra reference on @pwq. The caller should guarantee that
1111 * @pwq has positive refcnt and be holding the matching pool->lock.
1113 static void get_pwq(struct pool_workqueue *pwq)
1115 lockdep_assert_held(&pwq->pool->lock);
1116 WARN_ON_ONCE(pwq->refcnt <= 0);
1121 * put_pwq - put a pool_workqueue reference
1122 * @pwq: pool_workqueue to put
1124 * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
1125 * destruction. The caller should be holding the matching pool->lock.
1127 static void put_pwq(struct pool_workqueue *pwq)
1129 lockdep_assert_held(&pwq->pool->lock);
1130 if (likely(--pwq->refcnt))
1132 if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
1135 * @pwq can't be released under pool->lock, bounce to
1136 * pwq_unbound_release_workfn(). This never recurses on the same
1137 * pool->lock as this path is taken only for unbound workqueues and
1138 * the release work item is scheduled on a per-cpu workqueue. To
1139 * avoid lockdep warning, unbound pool->locks are given lockdep
1140 * subclass of 1 in get_unbound_pool().
1142 schedule_work(&pwq->unbound_release_work);
1146 * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1147 * @pwq: pool_workqueue to put (can be %NULL)
1149 * put_pwq() with locking. This function also allows %NULL @pwq.
1151 static void put_pwq_unlocked(struct pool_workqueue *pwq)
1155 * As both pwqs and pools are RCU protected, the
1156 * following lock operations are safe.
1158 raw_spin_lock_irq(&pwq->pool->lock);
1160 raw_spin_unlock_irq(&pwq->pool->lock);
1164 static void pwq_activate_inactive_work(struct work_struct *work)
1166 struct pool_workqueue *pwq = get_work_pwq(work);
1168 trace_workqueue_activate_work(work);
1169 if (list_empty(&pwq->pool->worklist))
1170 pwq->pool->watchdog_ts = jiffies;
1171 move_linked_works(work, &pwq->pool->worklist, NULL);
1172 __clear_bit(WORK_STRUCT_INACTIVE_BIT, work_data_bits(work));
1176 static void pwq_activate_first_inactive(struct pool_workqueue *pwq)
1178 struct work_struct *work = list_first_entry(&pwq->inactive_works,
1179 struct work_struct, entry);
1181 pwq_activate_inactive_work(work);
1185 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1186 * @pwq: pwq of interest
1187 * @work_data: work_data of work which left the queue
1189 * A work either has completed or is removed from pending queue,
1190 * decrement nr_in_flight of its pwq and handle workqueue flushing.
1193 * raw_spin_lock_irq(pool->lock).
1195 static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data)
1197 int color = get_work_color(work_data);
1199 if (!(work_data & WORK_STRUCT_INACTIVE)) {
1201 if (!list_empty(&pwq->inactive_works)) {
1202 /* one down, submit an inactive one */
1203 if (pwq->nr_active < pwq->max_active)
1204 pwq_activate_first_inactive(pwq);
1208 pwq->nr_in_flight[color]--;
1210 /* is flush in progress and are we at the flushing tip? */
1211 if (likely(pwq->flush_color != color))
1214 /* are there still in-flight works? */
1215 if (pwq->nr_in_flight[color])
1218 /* this pwq is done, clear flush_color */
1219 pwq->flush_color = -1;
1222 * If this was the last pwq, wake up the first flusher. It
1223 * will handle the rest.
1225 if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1226 complete(&pwq->wq->first_flusher->done);
1232 * try_to_grab_pending - steal work item from worklist and disable irq
1233 * @work: work item to steal
1234 * @is_dwork: @work is a delayed_work
1235 * @flags: place to store irq state
1237 * Try to grab PENDING bit of @work. This function can handle @work in any
1238 * stable state - idle, on timer or on worklist.
1242 * ======== ================================================================
1243 * 1 if @work was pending and we successfully stole PENDING
1244 * 0 if @work was idle and we claimed PENDING
1245 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1246 * -ENOENT if someone else is canceling @work, this state may persist
1247 * for arbitrarily long
1248 * ======== ================================================================
1251 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1252 * interrupted while holding PENDING and @work off queue, irq must be
1253 * disabled on entry. This, combined with delayed_work->timer being
1254 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1256 * On successful return, >= 0, irq is disabled and the caller is
1257 * responsible for releasing it using local_irq_restore(*@flags).
1259 * This function is safe to call from any context including IRQ handler.
1261 static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1262 unsigned long *flags)
1264 struct worker_pool *pool;
1265 struct pool_workqueue *pwq;
1267 local_irq_save(*flags);
1269 /* try to steal the timer if it exists */
1271 struct delayed_work *dwork = to_delayed_work(work);
1274 * dwork->timer is irqsafe. If del_timer() fails, it's
1275 * guaranteed that the timer is not queued anywhere and not
1276 * running on the local CPU.
1278 if (likely(del_timer(&dwork->timer)))
1282 /* try to claim PENDING the normal way */
1283 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1288 * The queueing is in progress, or it is already queued. Try to
1289 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1291 pool = get_work_pool(work);
1295 raw_spin_lock(&pool->lock);
1297 * work->data is guaranteed to point to pwq only while the work
1298 * item is queued on pwq->wq, and both updating work->data to point
1299 * to pwq on queueing and to pool on dequeueing are done under
1300 * pwq->pool->lock. This in turn guarantees that, if work->data
1301 * points to pwq which is associated with a locked pool, the work
1302 * item is currently queued on that pool.
1304 pwq = get_work_pwq(work);
1305 if (pwq && pwq->pool == pool) {
1306 debug_work_deactivate(work);
1309 * A cancelable inactive work item must be in the
1310 * pwq->inactive_works since a queued barrier can't be
1311 * canceled (see the comments in insert_wq_barrier()).
1313 * An inactive work item cannot be grabbed directly because
1314 * it might have linked barrier work items which, if left
1315 * on the inactive_works list, will confuse pwq->nr_active
1316 * management later on and cause stall. Make sure the work
1317 * item is activated before grabbing.
1319 if (*work_data_bits(work) & WORK_STRUCT_INACTIVE)
1320 pwq_activate_inactive_work(work);
1322 list_del_init(&work->entry);
1323 pwq_dec_nr_in_flight(pwq, *work_data_bits(work));
1325 /* work->data points to pwq iff queued, point to pool */
1326 set_work_pool_and_keep_pending(work, pool->id);
1328 raw_spin_unlock(&pool->lock);
1332 raw_spin_unlock(&pool->lock);
1335 local_irq_restore(*flags);
1336 if (work_is_canceling(work))
1343 * insert_work - insert a work into a pool
1344 * @pwq: pwq @work belongs to
1345 * @work: work to insert
1346 * @head: insertion point
1347 * @extra_flags: extra WORK_STRUCT_* flags to set
1349 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
1350 * work_struct flags.
1353 * raw_spin_lock_irq(pool->lock).
1355 static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1356 struct list_head *head, unsigned int extra_flags)
1358 struct worker_pool *pool = pwq->pool;
1360 /* record the work call stack in order to print it in KASAN reports */
1361 kasan_record_aux_stack_noalloc(work);
1363 /* we own @work, set data and link */
1364 set_work_pwq(work, pwq, extra_flags);
1365 list_add_tail(&work->entry, head);
1368 if (__need_more_worker(pool))
1369 wake_up_worker(pool);
1373 * Test whether @work is being queued from another work executing on the
1376 static bool is_chained_work(struct workqueue_struct *wq)
1378 struct worker *worker;
1380 worker = current_wq_worker();
1382 * Return %true iff I'm a worker executing a work item on @wq. If
1383 * I'm @worker, it's safe to dereference it without locking.
1385 return worker && worker->current_pwq->wq == wq;
1389 * When queueing an unbound work item to a wq, prefer local CPU if allowed
1390 * by wq_unbound_cpumask. Otherwise, round robin among the allowed ones to
1391 * avoid perturbing sensitive tasks.
1393 static int wq_select_unbound_cpu(int cpu)
1395 static bool printed_dbg_warning;
1398 if (likely(!wq_debug_force_rr_cpu)) {
1399 if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
1401 } else if (!printed_dbg_warning) {
1402 pr_warn("workqueue: round-robin CPU selection forced, expect performance impact\n");
1403 printed_dbg_warning = true;
1406 if (cpumask_empty(wq_unbound_cpumask))
1409 new_cpu = __this_cpu_read(wq_rr_cpu_last);
1410 new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
1411 if (unlikely(new_cpu >= nr_cpu_ids)) {
1412 new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
1413 if (unlikely(new_cpu >= nr_cpu_ids))
1416 __this_cpu_write(wq_rr_cpu_last, new_cpu);
1421 static void __queue_work(int cpu, struct workqueue_struct *wq,
1422 struct work_struct *work)
1424 struct pool_workqueue *pwq;
1425 struct worker_pool *last_pool;
1426 struct list_head *worklist;
1427 unsigned int work_flags;
1428 unsigned int req_cpu = cpu;
1431 * While a work item is PENDING && off queue, a task trying to
1432 * steal the PENDING will busy-loop waiting for it to either get
1433 * queued or lose PENDING. Grabbing PENDING and queueing should
1434 * happen with IRQ disabled.
1436 lockdep_assert_irqs_disabled();
1439 /* if draining, only works from the same workqueue are allowed */
1440 if (unlikely(wq->flags & __WQ_DRAINING) &&
1441 WARN_ON_ONCE(!is_chained_work(wq)))
1445 /* pwq which will be used unless @work is executing elsewhere */
1446 if (wq->flags & WQ_UNBOUND) {
1447 if (req_cpu == WORK_CPU_UNBOUND)
1448 cpu = wq_select_unbound_cpu(raw_smp_processor_id());
1449 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1451 if (req_cpu == WORK_CPU_UNBOUND)
1452 cpu = raw_smp_processor_id();
1453 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1457 * If @work was previously on a different pool, it might still be
1458 * running there, in which case the work needs to be queued on that
1459 * pool to guarantee non-reentrancy.
1461 last_pool = get_work_pool(work);
1462 if (last_pool && last_pool != pwq->pool) {
1463 struct worker *worker;
1465 raw_spin_lock(&last_pool->lock);
1467 worker = find_worker_executing_work(last_pool, work);
1469 if (worker && worker->current_pwq->wq == wq) {
1470 pwq = worker->current_pwq;
1472 /* meh... not running there, queue here */
1473 raw_spin_unlock(&last_pool->lock);
1474 raw_spin_lock(&pwq->pool->lock);
1477 raw_spin_lock(&pwq->pool->lock);
1481 * pwq is determined and locked. For unbound pools, we could have
1482 * raced with pwq release and it could already be dead. If its
1483 * refcnt is zero, repeat pwq selection. Note that pwqs never die
1484 * without another pwq replacing it in the numa_pwq_tbl or while
1485 * work items are executing on it, so the retrying is guaranteed to
1486 * make forward-progress.
1488 if (unlikely(!pwq->refcnt)) {
1489 if (wq->flags & WQ_UNBOUND) {
1490 raw_spin_unlock(&pwq->pool->lock);
1495 WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
1499 /* pwq determined, queue */
1500 trace_workqueue_queue_work(req_cpu, pwq, work);
1502 if (WARN_ON(!list_empty(&work->entry)))
1505 pwq->nr_in_flight[pwq->work_color]++;
1506 work_flags = work_color_to_flags(pwq->work_color);
1508 if (likely(pwq->nr_active < pwq->max_active)) {
1509 trace_workqueue_activate_work(work);
1511 worklist = &pwq->pool->worklist;
1512 if (list_empty(worklist))
1513 pwq->pool->watchdog_ts = jiffies;
1515 work_flags |= WORK_STRUCT_INACTIVE;
1516 worklist = &pwq->inactive_works;
1519 debug_work_activate(work);
1520 insert_work(pwq, work, worklist, work_flags);
1523 raw_spin_unlock(&pwq->pool->lock);
1528 * queue_work_on - queue work on specific cpu
1529 * @cpu: CPU number to execute work on
1530 * @wq: workqueue to use
1531 * @work: work to queue
1533 * We queue the work to a specific CPU, the caller must ensure it
1534 * can't go away. Callers that fail to ensure that the specified
1535 * CPU cannot go away will execute on a randomly chosen CPU.
1537 * Return: %false if @work was already on a queue, %true otherwise.
1539 bool queue_work_on(int cpu, struct workqueue_struct *wq,
1540 struct work_struct *work)
1543 unsigned long flags;
1545 local_irq_save(flags);
1547 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1548 __queue_work(cpu, wq, work);
1552 local_irq_restore(flags);
1555 EXPORT_SYMBOL(queue_work_on);
1558 * workqueue_select_cpu_near - Select a CPU based on NUMA node
1559 * @node: NUMA node ID that we want to select a CPU from
1561 * This function will attempt to find a "random" cpu available on a given
1562 * node. If there are no CPUs available on the given node it will return
1563 * WORK_CPU_UNBOUND indicating that we should just schedule to any
1564 * available CPU if we need to schedule this work.
1566 static int workqueue_select_cpu_near(int node)
1570 /* No point in doing this if NUMA isn't enabled for workqueues */
1571 if (!wq_numa_enabled)
1572 return WORK_CPU_UNBOUND;
1574 /* Delay binding to CPU if node is not valid or online */
1575 if (node < 0 || node >= MAX_NUMNODES || !node_online(node))
1576 return WORK_CPU_UNBOUND;
1578 /* Use local node/cpu if we are already there */
1579 cpu = raw_smp_processor_id();
1580 if (node == cpu_to_node(cpu))
1583 /* Use "random" otherwise know as "first" online CPU of node */
1584 cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
1586 /* If CPU is valid return that, otherwise just defer */
1587 return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND;
1591 * queue_work_node - queue work on a "random" cpu for a given NUMA node
1592 * @node: NUMA node that we are targeting the work for
1593 * @wq: workqueue to use
1594 * @work: work to queue
1596 * We queue the work to a "random" CPU within a given NUMA node. The basic
1597 * idea here is to provide a way to somehow associate work with a given
1600 * This function will only make a best effort attempt at getting this onto
1601 * the right NUMA node. If no node is requested or the requested node is
1602 * offline then we just fall back to standard queue_work behavior.
1604 * Currently the "random" CPU ends up being the first available CPU in the
1605 * intersection of cpu_online_mask and the cpumask of the node, unless we
1606 * are running on the node. In that case we just use the current CPU.
1608 * Return: %false if @work was already on a queue, %true otherwise.
1610 bool queue_work_node(int node, struct workqueue_struct *wq,
1611 struct work_struct *work)
1613 unsigned long flags;
1617 * This current implementation is specific to unbound workqueues.
1618 * Specifically we only return the first available CPU for a given
1619 * node instead of cycling through individual CPUs within the node.
1621 * If this is used with a per-cpu workqueue then the logic in
1622 * workqueue_select_cpu_near would need to be updated to allow for
1623 * some round robin type logic.
1625 WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND));
1627 local_irq_save(flags);
1629 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1630 int cpu = workqueue_select_cpu_near(node);
1632 __queue_work(cpu, wq, work);
1636 local_irq_restore(flags);
1639 EXPORT_SYMBOL_GPL(queue_work_node);
1641 void delayed_work_timer_fn(struct timer_list *t)
1643 struct delayed_work *dwork = from_timer(dwork, t, timer);
1645 /* should have been called from irqsafe timer with irq already off */
1646 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
1648 EXPORT_SYMBOL(delayed_work_timer_fn);
1650 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
1651 struct delayed_work *dwork, unsigned long delay)
1653 struct timer_list *timer = &dwork->timer;
1654 struct work_struct *work = &dwork->work;
1657 WARN_ON_ONCE(timer->function != delayed_work_timer_fn);
1658 WARN_ON_ONCE(timer_pending(timer));
1659 WARN_ON_ONCE(!list_empty(&work->entry));
1662 * If @delay is 0, queue @dwork->work immediately. This is for
1663 * both optimization and correctness. The earliest @timer can
1664 * expire is on the closest next tick and delayed_work users depend
1665 * on that there's no such delay when @delay is 0.
1668 __queue_work(cpu, wq, &dwork->work);
1674 timer->expires = jiffies + delay;
1676 if (unlikely(cpu != WORK_CPU_UNBOUND))
1677 add_timer_on(timer, cpu);
1683 * queue_delayed_work_on - queue work on specific CPU after delay
1684 * @cpu: CPU number to execute work on
1685 * @wq: workqueue to use
1686 * @dwork: work to queue
1687 * @delay: number of jiffies to wait before queueing
1689 * Return: %false if @work was already on a queue, %true otherwise. If
1690 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1693 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1694 struct delayed_work *dwork, unsigned long delay)
1696 struct work_struct *work = &dwork->work;
1698 unsigned long flags;
1700 /* read the comment in __queue_work() */
1701 local_irq_save(flags);
1703 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1704 __queue_delayed_work(cpu, wq, dwork, delay);
1708 local_irq_restore(flags);
1711 EXPORT_SYMBOL(queue_delayed_work_on);
1714 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1715 * @cpu: CPU number to execute work on
1716 * @wq: workqueue to use
1717 * @dwork: work to queue
1718 * @delay: number of jiffies to wait before queueing
1720 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1721 * modify @dwork's timer so that it expires after @delay. If @delay is
1722 * zero, @work is guaranteed to be scheduled immediately regardless of its
1725 * Return: %false if @dwork was idle and queued, %true if @dwork was
1726 * pending and its timer was modified.
1728 * This function is safe to call from any context including IRQ handler.
1729 * See try_to_grab_pending() for details.
1731 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
1732 struct delayed_work *dwork, unsigned long delay)
1734 unsigned long flags;
1738 ret = try_to_grab_pending(&dwork->work, true, &flags);
1739 } while (unlikely(ret == -EAGAIN));
1741 if (likely(ret >= 0)) {
1742 __queue_delayed_work(cpu, wq, dwork, delay);
1743 local_irq_restore(flags);
1746 /* -ENOENT from try_to_grab_pending() becomes %true */
1749 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
1751 static void rcu_work_rcufn(struct rcu_head *rcu)
1753 struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
1755 /* read the comment in __queue_work() */
1756 local_irq_disable();
1757 __queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
1762 * queue_rcu_work - queue work after a RCU grace period
1763 * @wq: workqueue to use
1764 * @rwork: work to queue
1766 * Return: %false if @rwork was already pending, %true otherwise. Note
1767 * that a full RCU grace period is guaranteed only after a %true return.
1768 * While @rwork is guaranteed to be executed after a %false return, the
1769 * execution may happen before a full RCU grace period has passed.
1771 bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
1773 struct work_struct *work = &rwork->work;
1775 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1777 call_rcu(&rwork->rcu, rcu_work_rcufn);
1783 EXPORT_SYMBOL(queue_rcu_work);
1786 * worker_enter_idle - enter idle state
1787 * @worker: worker which is entering idle state
1789 * @worker is entering idle state. Update stats and idle timer if
1793 * raw_spin_lock_irq(pool->lock).
1795 static void worker_enter_idle(struct worker *worker)
1797 struct worker_pool *pool = worker->pool;
1799 if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
1800 WARN_ON_ONCE(!list_empty(&worker->entry) &&
1801 (worker->hentry.next || worker->hentry.pprev)))
1804 /* can't use worker_set_flags(), also called from create_worker() */
1805 worker->flags |= WORKER_IDLE;
1807 worker->last_active = jiffies;
1809 /* idle_list is LIFO */
1810 list_add(&worker->entry, &pool->idle_list);
1812 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1813 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1815 /* Sanity check nr_running. */
1816 WARN_ON_ONCE(pool->nr_workers == pool->nr_idle && pool->nr_running);
1820 * worker_leave_idle - leave idle state
1821 * @worker: worker which is leaving idle state
1823 * @worker is leaving idle state. Update stats.
1826 * raw_spin_lock_irq(pool->lock).
1828 static void worker_leave_idle(struct worker *worker)
1830 struct worker_pool *pool = worker->pool;
1832 if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
1834 worker_clr_flags(worker, WORKER_IDLE);
1836 list_del_init(&worker->entry);
1839 static struct worker *alloc_worker(int node)
1841 struct worker *worker;
1843 worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
1845 INIT_LIST_HEAD(&worker->entry);
1846 INIT_LIST_HEAD(&worker->scheduled);
1847 INIT_LIST_HEAD(&worker->node);
1848 /* on creation a worker is in !idle && prep state */
1849 worker->flags = WORKER_PREP;
1855 * worker_attach_to_pool() - attach a worker to a pool
1856 * @worker: worker to be attached
1857 * @pool: the target pool
1859 * Attach @worker to @pool. Once attached, the %WORKER_UNBOUND flag and
1860 * cpu-binding of @worker are kept coordinated with the pool across
1863 static void worker_attach_to_pool(struct worker *worker,
1864 struct worker_pool *pool)
1866 mutex_lock(&wq_pool_attach_mutex);
1869 * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains
1870 * stable across this function. See the comments above the flag
1871 * definition for details.
1873 if (pool->flags & POOL_DISASSOCIATED)
1874 worker->flags |= WORKER_UNBOUND;
1876 kthread_set_per_cpu(worker->task, pool->cpu);
1878 if (worker->rescue_wq)
1879 set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
1881 list_add_tail(&worker->node, &pool->workers);
1882 worker->pool = pool;
1884 mutex_unlock(&wq_pool_attach_mutex);
1888 * worker_detach_from_pool() - detach a worker from its pool
1889 * @worker: worker which is attached to its pool
1891 * Undo the attaching which had been done in worker_attach_to_pool(). The
1892 * caller worker shouldn't access to the pool after detached except it has
1893 * other reference to the pool.
1895 static void worker_detach_from_pool(struct worker *worker)
1897 struct worker_pool *pool = worker->pool;
1898 struct completion *detach_completion = NULL;
1900 mutex_lock(&wq_pool_attach_mutex);
1902 kthread_set_per_cpu(worker->task, -1);
1903 list_del(&worker->node);
1904 worker->pool = NULL;
1906 if (list_empty(&pool->workers))
1907 detach_completion = pool->detach_completion;
1908 mutex_unlock(&wq_pool_attach_mutex);
1910 /* clear leftover flags without pool->lock after it is detached */
1911 worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
1913 if (detach_completion)
1914 complete(detach_completion);
1918 * create_worker - create a new workqueue worker
1919 * @pool: pool the new worker will belong to
1921 * Create and start a new worker which is attached to @pool.
1924 * Might sleep. Does GFP_KERNEL allocations.
1927 * Pointer to the newly created worker.
1929 static struct worker *create_worker(struct worker_pool *pool)
1931 struct worker *worker;
1935 /* ID is needed to determine kthread name */
1936 id = ida_alloc(&pool->worker_ida, GFP_KERNEL);
1940 worker = alloc_worker(pool->node);
1947 snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
1948 pool->attrs->nice < 0 ? "H" : "");
1950 snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
1952 worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
1953 "kworker/%s", id_buf);
1954 if (IS_ERR(worker->task))
1957 set_user_nice(worker->task, pool->attrs->nice);
1958 kthread_bind_mask(worker->task, pool->attrs->cpumask);
1960 /* successful, attach the worker to the pool */
1961 worker_attach_to_pool(worker, pool);
1963 /* start the newly created worker */
1964 raw_spin_lock_irq(&pool->lock);
1965 worker->pool->nr_workers++;
1966 worker_enter_idle(worker);
1967 wake_up_process(worker->task);
1968 raw_spin_unlock_irq(&pool->lock);
1973 ida_free(&pool->worker_ida, id);
1979 * destroy_worker - destroy a workqueue worker
1980 * @worker: worker to be destroyed
1982 * Destroy @worker and adjust @pool stats accordingly. The worker should
1986 * raw_spin_lock_irq(pool->lock).
1988 static void destroy_worker(struct worker *worker)
1990 struct worker_pool *pool = worker->pool;
1992 lockdep_assert_held(&pool->lock);
1994 /* sanity check frenzy */
1995 if (WARN_ON(worker->current_work) ||
1996 WARN_ON(!list_empty(&worker->scheduled)) ||
1997 WARN_ON(!(worker->flags & WORKER_IDLE)))
2003 list_del_init(&worker->entry);
2004 worker->flags |= WORKER_DIE;
2005 wake_up_process(worker->task);
2008 static void idle_worker_timeout(struct timer_list *t)
2010 struct worker_pool *pool = from_timer(pool, t, idle_timer);
2012 raw_spin_lock_irq(&pool->lock);
2014 while (too_many_workers(pool)) {
2015 struct worker *worker;
2016 unsigned long expires;
2018 /* idle_list is kept in LIFO order, check the last one */
2019 worker = list_entry(pool->idle_list.prev, struct worker, entry);
2020 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2022 if (time_before(jiffies, expires)) {
2023 mod_timer(&pool->idle_timer, expires);
2027 destroy_worker(worker);
2030 raw_spin_unlock_irq(&pool->lock);
2033 static void send_mayday(struct work_struct *work)
2035 struct pool_workqueue *pwq = get_work_pwq(work);
2036 struct workqueue_struct *wq = pwq->wq;
2038 lockdep_assert_held(&wq_mayday_lock);
2043 /* mayday mayday mayday */
2044 if (list_empty(&pwq->mayday_node)) {
2046 * If @pwq is for an unbound wq, its base ref may be put at
2047 * any time due to an attribute change. Pin @pwq until the
2048 * rescuer is done with it.
2051 list_add_tail(&pwq->mayday_node, &wq->maydays);
2052 wake_up_process(wq->rescuer->task);
2056 static void pool_mayday_timeout(struct timer_list *t)
2058 struct worker_pool *pool = from_timer(pool, t, mayday_timer);
2059 struct work_struct *work;
2061 raw_spin_lock_irq(&pool->lock);
2062 raw_spin_lock(&wq_mayday_lock); /* for wq->maydays */
2064 if (need_to_create_worker(pool)) {
2066 * We've been trying to create a new worker but
2067 * haven't been successful. We might be hitting an
2068 * allocation deadlock. Send distress signals to
2071 list_for_each_entry(work, &pool->worklist, entry)
2075 raw_spin_unlock(&wq_mayday_lock);
2076 raw_spin_unlock_irq(&pool->lock);
2078 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
2082 * maybe_create_worker - create a new worker if necessary
2083 * @pool: pool to create a new worker for
2085 * Create a new worker for @pool if necessary. @pool is guaranteed to
2086 * have at least one idle worker on return from this function. If
2087 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
2088 * sent to all rescuers with works scheduled on @pool to resolve
2089 * possible allocation deadlock.
2091 * On return, need_to_create_worker() is guaranteed to be %false and
2092 * may_start_working() %true.
2095 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2096 * multiple times. Does GFP_KERNEL allocations. Called only from
2099 static void maybe_create_worker(struct worker_pool *pool)
2100 __releases(&pool->lock)
2101 __acquires(&pool->lock)
2104 raw_spin_unlock_irq(&pool->lock);
2106 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
2107 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
2110 if (create_worker(pool) || !need_to_create_worker(pool))
2113 schedule_timeout_interruptible(CREATE_COOLDOWN);
2115 if (!need_to_create_worker(pool))
2119 del_timer_sync(&pool->mayday_timer);
2120 raw_spin_lock_irq(&pool->lock);
2122 * This is necessary even after a new worker was just successfully
2123 * created as @pool->lock was dropped and the new worker might have
2124 * already become busy.
2126 if (need_to_create_worker(pool))
2131 * manage_workers - manage worker pool
2134 * Assume the manager role and manage the worker pool @worker belongs
2135 * to. At any given time, there can be only zero or one manager per
2136 * pool. The exclusion is handled automatically by this function.
2138 * The caller can safely start processing works on false return. On
2139 * true return, it's guaranteed that need_to_create_worker() is false
2140 * and may_start_working() is true.
2143 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2144 * multiple times. Does GFP_KERNEL allocations.
2147 * %false if the pool doesn't need management and the caller can safely
2148 * start processing works, %true if management function was performed and
2149 * the conditions that the caller verified before calling the function may
2150 * no longer be true.
2152 static bool manage_workers(struct worker *worker)
2154 struct worker_pool *pool = worker->pool;
2156 if (pool->flags & POOL_MANAGER_ACTIVE)
2159 pool->flags |= POOL_MANAGER_ACTIVE;
2160 pool->manager = worker;
2162 maybe_create_worker(pool);
2164 pool->manager = NULL;
2165 pool->flags &= ~POOL_MANAGER_ACTIVE;
2166 rcuwait_wake_up(&manager_wait);
2171 * process_one_work - process single work
2173 * @work: work to process
2175 * Process @work. This function contains all the logics necessary to
2176 * process a single work including synchronization against and
2177 * interaction with other workers on the same cpu, queueing and
2178 * flushing. As long as context requirement is met, any worker can
2179 * call this function to process a work.
2182 * raw_spin_lock_irq(pool->lock) which is released and regrabbed.
2184 static void process_one_work(struct worker *worker, struct work_struct *work)
2185 __releases(&pool->lock)
2186 __acquires(&pool->lock)
2188 struct pool_workqueue *pwq = get_work_pwq(work);
2189 struct worker_pool *pool = worker->pool;
2190 bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
2191 unsigned long work_data;
2192 struct worker *collision;
2193 #ifdef CONFIG_LOCKDEP
2195 * It is permissible to free the struct work_struct from
2196 * inside the function that is called from it, this we need to
2197 * take into account for lockdep too. To avoid bogus "held
2198 * lock freed" warnings as well as problems when looking into
2199 * work->lockdep_map, make a copy and use that here.
2201 struct lockdep_map lockdep_map;
2203 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
2205 /* ensure we're on the correct CPU */
2206 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2207 raw_smp_processor_id() != pool->cpu);
2210 * A single work shouldn't be executed concurrently by
2211 * multiple workers on a single cpu. Check whether anyone is
2212 * already processing the work. If so, defer the work to the
2213 * currently executing one.
2215 collision = find_worker_executing_work(pool, work);
2216 if (unlikely(collision)) {
2217 move_linked_works(work, &collision->scheduled, NULL);
2221 /* claim and dequeue */
2222 debug_work_deactivate(work);
2223 hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2224 worker->current_work = work;
2225 worker->current_func = work->func;
2226 worker->current_pwq = pwq;
2227 work_data = *work_data_bits(work);
2228 worker->current_color = get_work_color(work_data);
2231 * Record wq name for cmdline and debug reporting, may get
2232 * overridden through set_worker_desc().
2234 strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
2236 list_del_init(&work->entry);
2239 * CPU intensive works don't participate in concurrency management.
2240 * They're the scheduler's responsibility. This takes @worker out
2241 * of concurrency management and the next code block will chain
2242 * execution of the pending work items.
2244 if (unlikely(cpu_intensive))
2245 worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2248 * Wake up another worker if necessary. The condition is always
2249 * false for normal per-cpu workers since nr_running would always
2250 * be >= 1 at this point. This is used to chain execution of the
2251 * pending work items for WORKER_NOT_RUNNING workers such as the
2252 * UNBOUND and CPU_INTENSIVE ones.
2254 if (need_more_worker(pool))
2255 wake_up_worker(pool);
2258 * Record the last pool and clear PENDING which should be the last
2259 * update to @work. Also, do this inside @pool->lock so that
2260 * PENDING and queued state changes happen together while IRQ is
2263 set_work_pool_and_clear_pending(work, pool->id);
2265 raw_spin_unlock_irq(&pool->lock);
2267 lock_map_acquire(&pwq->wq->lockdep_map);
2268 lock_map_acquire(&lockdep_map);
2270 * Strictly speaking we should mark the invariant state without holding
2271 * any locks, that is, before these two lock_map_acquire()'s.
2273 * However, that would result in:
2280 * Which would create W1->C->W1 dependencies, even though there is no
2281 * actual deadlock possible. There are two solutions, using a
2282 * read-recursive acquire on the work(queue) 'locks', but this will then
2283 * hit the lockdep limitation on recursive locks, or simply discard
2286 * AFAICT there is no possible deadlock scenario between the
2287 * flush_work() and complete() primitives (except for single-threaded
2288 * workqueues), so hiding them isn't a problem.
2290 lockdep_invariant_state(true);
2291 trace_workqueue_execute_start(work);
2292 worker->current_func(work);
2294 * While we must be careful to not use "work" after this, the trace
2295 * point will only record its address.
2297 trace_workqueue_execute_end(work, worker->current_func);
2298 lock_map_release(&lockdep_map);
2299 lock_map_release(&pwq->wq->lockdep_map);
2301 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2302 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2303 " last function: %ps\n",
2304 current->comm, preempt_count(), task_pid_nr(current),
2305 worker->current_func);
2306 debug_show_held_locks(current);
2311 * The following prevents a kworker from hogging CPU on !PREEMPTION
2312 * kernels, where a requeueing work item waiting for something to
2313 * happen could deadlock with stop_machine as such work item could
2314 * indefinitely requeue itself while all other CPUs are trapped in
2315 * stop_machine. At the same time, report a quiescent RCU state so
2316 * the same condition doesn't freeze RCU.
2320 raw_spin_lock_irq(&pool->lock);
2322 /* clear cpu intensive status */
2323 if (unlikely(cpu_intensive))
2324 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2326 /* tag the worker for identification in schedule() */
2327 worker->last_func = worker->current_func;
2329 /* we're done with it, release */
2330 hash_del(&worker->hentry);
2331 worker->current_work = NULL;
2332 worker->current_func = NULL;
2333 worker->current_pwq = NULL;
2334 worker->current_color = INT_MAX;
2335 pwq_dec_nr_in_flight(pwq, work_data);
2339 * process_scheduled_works - process scheduled works
2342 * Process all scheduled works. Please note that the scheduled list
2343 * may change while processing a work, so this function repeatedly
2344 * fetches a work from the top and executes it.
2347 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2350 static void process_scheduled_works(struct worker *worker)
2352 while (!list_empty(&worker->scheduled)) {
2353 struct work_struct *work = list_first_entry(&worker->scheduled,
2354 struct work_struct, entry);
2355 process_one_work(worker, work);
2359 static void set_pf_worker(bool val)
2361 mutex_lock(&wq_pool_attach_mutex);
2363 current->flags |= PF_WQ_WORKER;
2365 current->flags &= ~PF_WQ_WORKER;
2366 mutex_unlock(&wq_pool_attach_mutex);
2370 * worker_thread - the worker thread function
2373 * The worker thread function. All workers belong to a worker_pool -
2374 * either a per-cpu one or dynamic unbound one. These workers process all
2375 * work items regardless of their specific target workqueue. The only
2376 * exception is work items which belong to workqueues with a rescuer which
2377 * will be explained in rescuer_thread().
2381 static int worker_thread(void *__worker)
2383 struct worker *worker = __worker;
2384 struct worker_pool *pool = worker->pool;
2386 /* tell the scheduler that this is a workqueue worker */
2387 set_pf_worker(true);
2389 raw_spin_lock_irq(&pool->lock);
2391 /* am I supposed to die? */
2392 if (unlikely(worker->flags & WORKER_DIE)) {
2393 raw_spin_unlock_irq(&pool->lock);
2394 WARN_ON_ONCE(!list_empty(&worker->entry));
2395 set_pf_worker(false);
2397 set_task_comm(worker->task, "kworker/dying");
2398 ida_free(&pool->worker_ida, worker->id);
2399 worker_detach_from_pool(worker);
2404 worker_leave_idle(worker);
2406 /* no more worker necessary? */
2407 if (!need_more_worker(pool))
2410 /* do we need to manage? */
2411 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2415 * ->scheduled list can only be filled while a worker is
2416 * preparing to process a work or actually processing it.
2417 * Make sure nobody diddled with it while I was sleeping.
2419 WARN_ON_ONCE(!list_empty(&worker->scheduled));
2422 * Finish PREP stage. We're guaranteed to have at least one idle
2423 * worker or that someone else has already assumed the manager
2424 * role. This is where @worker starts participating in concurrency
2425 * management if applicable and concurrency management is restored
2426 * after being rebound. See rebind_workers() for details.
2428 worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2431 struct work_struct *work =
2432 list_first_entry(&pool->worklist,
2433 struct work_struct, entry);
2435 pool->watchdog_ts = jiffies;
2437 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2438 /* optimization path, not strictly necessary */
2439 process_one_work(worker, work);
2440 if (unlikely(!list_empty(&worker->scheduled)))
2441 process_scheduled_works(worker);
2443 move_linked_works(work, &worker->scheduled, NULL);
2444 process_scheduled_works(worker);
2446 } while (keep_working(pool));
2448 worker_set_flags(worker, WORKER_PREP);
2451 * pool->lock is held and there's no work to process and no need to
2452 * manage, sleep. Workers are woken up only while holding
2453 * pool->lock or from local cpu, so setting the current state
2454 * before releasing pool->lock is enough to prevent losing any
2457 worker_enter_idle(worker);
2458 __set_current_state(TASK_IDLE);
2459 raw_spin_unlock_irq(&pool->lock);
2465 * rescuer_thread - the rescuer thread function
2468 * Workqueue rescuer thread function. There's one rescuer for each
2469 * workqueue which has WQ_MEM_RECLAIM set.
2471 * Regular work processing on a pool may block trying to create a new
2472 * worker which uses GFP_KERNEL allocation which has slight chance of
2473 * developing into deadlock if some works currently on the same queue
2474 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2475 * the problem rescuer solves.
2477 * When such condition is possible, the pool summons rescuers of all
2478 * workqueues which have works queued on the pool and let them process
2479 * those works so that forward progress can be guaranteed.
2481 * This should happen rarely.
2485 static int rescuer_thread(void *__rescuer)
2487 struct worker *rescuer = __rescuer;
2488 struct workqueue_struct *wq = rescuer->rescue_wq;
2489 struct list_head *scheduled = &rescuer->scheduled;
2492 set_user_nice(current, RESCUER_NICE_LEVEL);
2495 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2496 * doesn't participate in concurrency management.
2498 set_pf_worker(true);
2500 set_current_state(TASK_IDLE);
2503 * By the time the rescuer is requested to stop, the workqueue
2504 * shouldn't have any work pending, but @wq->maydays may still have
2505 * pwq(s) queued. This can happen by non-rescuer workers consuming
2506 * all the work items before the rescuer got to them. Go through
2507 * @wq->maydays processing before acting on should_stop so that the
2508 * list is always empty on exit.
2510 should_stop = kthread_should_stop();
2512 /* see whether any pwq is asking for help */
2513 raw_spin_lock_irq(&wq_mayday_lock);
2515 while (!list_empty(&wq->maydays)) {
2516 struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2517 struct pool_workqueue, mayday_node);
2518 struct worker_pool *pool = pwq->pool;
2519 struct work_struct *work, *n;
2522 __set_current_state(TASK_RUNNING);
2523 list_del_init(&pwq->mayday_node);
2525 raw_spin_unlock_irq(&wq_mayday_lock);
2527 worker_attach_to_pool(rescuer, pool);
2529 raw_spin_lock_irq(&pool->lock);
2532 * Slurp in all works issued via this workqueue and
2535 WARN_ON_ONCE(!list_empty(scheduled));
2536 list_for_each_entry_safe(work, n, &pool->worklist, entry) {
2537 if (get_work_pwq(work) == pwq) {
2539 pool->watchdog_ts = jiffies;
2540 move_linked_works(work, scheduled, &n);
2545 if (!list_empty(scheduled)) {
2546 process_scheduled_works(rescuer);
2549 * The above execution of rescued work items could
2550 * have created more to rescue through
2551 * pwq_activate_first_inactive() or chained
2552 * queueing. Let's put @pwq back on mayday list so
2553 * that such back-to-back work items, which may be
2554 * being used to relieve memory pressure, don't
2555 * incur MAYDAY_INTERVAL delay inbetween.
2557 if (pwq->nr_active && need_to_create_worker(pool)) {
2558 raw_spin_lock(&wq_mayday_lock);
2560 * Queue iff we aren't racing destruction
2561 * and somebody else hasn't queued it already.
2563 if (wq->rescuer && list_empty(&pwq->mayday_node)) {
2565 list_add_tail(&pwq->mayday_node, &wq->maydays);
2567 raw_spin_unlock(&wq_mayday_lock);
2572 * Put the reference grabbed by send_mayday(). @pool won't
2573 * go away while we're still attached to it.
2578 * Leave this pool. If need_more_worker() is %true, notify a
2579 * regular worker; otherwise, we end up with 0 concurrency
2580 * and stalling the execution.
2582 if (need_more_worker(pool))
2583 wake_up_worker(pool);
2585 raw_spin_unlock_irq(&pool->lock);
2587 worker_detach_from_pool(rescuer);
2589 raw_spin_lock_irq(&wq_mayday_lock);
2592 raw_spin_unlock_irq(&wq_mayday_lock);
2595 __set_current_state(TASK_RUNNING);
2596 set_pf_worker(false);
2600 /* rescuers should never participate in concurrency management */
2601 WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2607 * check_flush_dependency - check for flush dependency sanity
2608 * @target_wq: workqueue being flushed
2609 * @target_work: work item being flushed (NULL for workqueue flushes)
2611 * %current is trying to flush the whole @target_wq or @target_work on it.
2612 * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
2613 * reclaiming memory or running on a workqueue which doesn't have
2614 * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
2617 static void check_flush_dependency(struct workqueue_struct *target_wq,
2618 struct work_struct *target_work)
2620 work_func_t target_func = target_work ? target_work->func : NULL;
2621 struct worker *worker;
2623 if (target_wq->flags & WQ_MEM_RECLAIM)
2626 worker = current_wq_worker();
2628 WARN_ONCE(current->flags & PF_MEMALLOC,
2629 "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps",
2630 current->pid, current->comm, target_wq->name, target_func);
2631 WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
2632 (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
2633 "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps",
2634 worker->current_pwq->wq->name, worker->current_func,
2635 target_wq->name, target_func);
2639 struct work_struct work;
2640 struct completion done;
2641 struct task_struct *task; /* purely informational */
2644 static void wq_barrier_func(struct work_struct *work)
2646 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2647 complete(&barr->done);
2651 * insert_wq_barrier - insert a barrier work
2652 * @pwq: pwq to insert barrier into
2653 * @barr: wq_barrier to insert
2654 * @target: target work to attach @barr to
2655 * @worker: worker currently executing @target, NULL if @target is not executing
2657 * @barr is linked to @target such that @barr is completed only after
2658 * @target finishes execution. Please note that the ordering
2659 * guarantee is observed only with respect to @target and on the local
2662 * Currently, a queued barrier can't be canceled. This is because
2663 * try_to_grab_pending() can't determine whether the work to be
2664 * grabbed is at the head of the queue and thus can't clear LINKED
2665 * flag of the previous work while there must be a valid next work
2666 * after a work with LINKED flag set.
2668 * Note that when @worker is non-NULL, @target may be modified
2669 * underneath us, so we can't reliably determine pwq from @target.
2672 * raw_spin_lock_irq(pool->lock).
2674 static void insert_wq_barrier(struct pool_workqueue *pwq,
2675 struct wq_barrier *barr,
2676 struct work_struct *target, struct worker *worker)
2678 unsigned int work_flags = 0;
2679 unsigned int work_color;
2680 struct list_head *head;
2683 * debugobject calls are safe here even with pool->lock locked
2684 * as we know for sure that this will not trigger any of the
2685 * checks and call back into the fixup functions where we
2688 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2689 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2691 init_completion_map(&barr->done, &target->lockdep_map);
2693 barr->task = current;
2695 /* The barrier work item does not participate in pwq->nr_active. */
2696 work_flags |= WORK_STRUCT_INACTIVE;
2699 * If @target is currently being executed, schedule the
2700 * barrier to the worker; otherwise, put it after @target.
2703 head = worker->scheduled.next;
2704 work_color = worker->current_color;
2706 unsigned long *bits = work_data_bits(target);
2708 head = target->entry.next;
2709 /* there can already be other linked works, inherit and set */
2710 work_flags |= *bits & WORK_STRUCT_LINKED;
2711 work_color = get_work_color(*bits);
2712 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2715 pwq->nr_in_flight[work_color]++;
2716 work_flags |= work_color_to_flags(work_color);
2718 debug_work_activate(&barr->work);
2719 insert_work(pwq, &barr->work, head, work_flags);
2723 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
2724 * @wq: workqueue being flushed
2725 * @flush_color: new flush color, < 0 for no-op
2726 * @work_color: new work color, < 0 for no-op
2728 * Prepare pwqs for workqueue flushing.
2730 * If @flush_color is non-negative, flush_color on all pwqs should be
2731 * -1. If no pwq has in-flight commands at the specified color, all
2732 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
2733 * has in flight commands, its pwq->flush_color is set to
2734 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
2735 * wakeup logic is armed and %true is returned.
2737 * The caller should have initialized @wq->first_flusher prior to
2738 * calling this function with non-negative @flush_color. If
2739 * @flush_color is negative, no flush color update is done and %false
2742 * If @work_color is non-negative, all pwqs should have the same
2743 * work_color which is previous to @work_color and all will be
2744 * advanced to @work_color.
2747 * mutex_lock(wq->mutex).
2750 * %true if @flush_color >= 0 and there's something to flush. %false
2753 static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
2754 int flush_color, int work_color)
2757 struct pool_workqueue *pwq;
2759 if (flush_color >= 0) {
2760 WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2761 atomic_set(&wq->nr_pwqs_to_flush, 1);
2764 for_each_pwq(pwq, wq) {
2765 struct worker_pool *pool = pwq->pool;
2767 raw_spin_lock_irq(&pool->lock);
2769 if (flush_color >= 0) {
2770 WARN_ON_ONCE(pwq->flush_color != -1);
2772 if (pwq->nr_in_flight[flush_color]) {
2773 pwq->flush_color = flush_color;
2774 atomic_inc(&wq->nr_pwqs_to_flush);
2779 if (work_color >= 0) {
2780 WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2781 pwq->work_color = work_color;
2784 raw_spin_unlock_irq(&pool->lock);
2787 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
2788 complete(&wq->first_flusher->done);
2794 * __flush_workqueue - ensure that any scheduled work has run to completion.
2795 * @wq: workqueue to flush
2797 * This function sleeps until all work items which were queued on entry
2798 * have finished execution, but it is not livelocked by new incoming ones.
2800 void __flush_workqueue(struct workqueue_struct *wq)
2802 struct wq_flusher this_flusher = {
2803 .list = LIST_HEAD_INIT(this_flusher.list),
2805 .done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map),
2809 if (WARN_ON(!wq_online))
2812 lock_map_acquire(&wq->lockdep_map);
2813 lock_map_release(&wq->lockdep_map);
2815 mutex_lock(&wq->mutex);
2818 * Start-to-wait phase
2820 next_color = work_next_color(wq->work_color);
2822 if (next_color != wq->flush_color) {
2824 * Color space is not full. The current work_color
2825 * becomes our flush_color and work_color is advanced
2828 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
2829 this_flusher.flush_color = wq->work_color;
2830 wq->work_color = next_color;
2832 if (!wq->first_flusher) {
2833 /* no flush in progress, become the first flusher */
2834 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2836 wq->first_flusher = &this_flusher;
2838 if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
2840 /* nothing to flush, done */
2841 wq->flush_color = next_color;
2842 wq->first_flusher = NULL;
2847 WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
2848 list_add_tail(&this_flusher.list, &wq->flusher_queue);
2849 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2853 * Oops, color space is full, wait on overflow queue.
2854 * The next flush completion will assign us
2855 * flush_color and transfer to flusher_queue.
2857 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2860 check_flush_dependency(wq, NULL);
2862 mutex_unlock(&wq->mutex);
2864 wait_for_completion(&this_flusher.done);
2867 * Wake-up-and-cascade phase
2869 * First flushers are responsible for cascading flushes and
2870 * handling overflow. Non-first flushers can simply return.
2872 if (READ_ONCE(wq->first_flusher) != &this_flusher)
2875 mutex_lock(&wq->mutex);
2877 /* we might have raced, check again with mutex held */
2878 if (wq->first_flusher != &this_flusher)
2881 WRITE_ONCE(wq->first_flusher, NULL);
2883 WARN_ON_ONCE(!list_empty(&this_flusher.list));
2884 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2887 struct wq_flusher *next, *tmp;
2889 /* complete all the flushers sharing the current flush color */
2890 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2891 if (next->flush_color != wq->flush_color)
2893 list_del_init(&next->list);
2894 complete(&next->done);
2897 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
2898 wq->flush_color != work_next_color(wq->work_color));
2900 /* this flush_color is finished, advance by one */
2901 wq->flush_color = work_next_color(wq->flush_color);
2903 /* one color has been freed, handle overflow queue */
2904 if (!list_empty(&wq->flusher_overflow)) {
2906 * Assign the same color to all overflowed
2907 * flushers, advance work_color and append to
2908 * flusher_queue. This is the start-to-wait
2909 * phase for these overflowed flushers.
2911 list_for_each_entry(tmp, &wq->flusher_overflow, list)
2912 tmp->flush_color = wq->work_color;
2914 wq->work_color = work_next_color(wq->work_color);
2916 list_splice_tail_init(&wq->flusher_overflow,
2917 &wq->flusher_queue);
2918 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2921 if (list_empty(&wq->flusher_queue)) {
2922 WARN_ON_ONCE(wq->flush_color != wq->work_color);
2927 * Need to flush more colors. Make the next flusher
2928 * the new first flusher and arm pwqs.
2930 WARN_ON_ONCE(wq->flush_color == wq->work_color);
2931 WARN_ON_ONCE(wq->flush_color != next->flush_color);
2933 list_del_init(&next->list);
2934 wq->first_flusher = next;
2936 if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
2940 * Meh... this color is already done, clear first
2941 * flusher and repeat cascading.
2943 wq->first_flusher = NULL;
2947 mutex_unlock(&wq->mutex);
2949 EXPORT_SYMBOL(__flush_workqueue);
2952 * drain_workqueue - drain a workqueue
2953 * @wq: workqueue to drain
2955 * Wait until the workqueue becomes empty. While draining is in progress,
2956 * only chain queueing is allowed. IOW, only currently pending or running
2957 * work items on @wq can queue further work items on it. @wq is flushed
2958 * repeatedly until it becomes empty. The number of flushing is determined
2959 * by the depth of chaining and should be relatively short. Whine if it
2962 void drain_workqueue(struct workqueue_struct *wq)
2964 unsigned int flush_cnt = 0;
2965 struct pool_workqueue *pwq;
2968 * __queue_work() needs to test whether there are drainers, is much
2969 * hotter than drain_workqueue() and already looks at @wq->flags.
2970 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
2972 mutex_lock(&wq->mutex);
2973 if (!wq->nr_drainers++)
2974 wq->flags |= __WQ_DRAINING;
2975 mutex_unlock(&wq->mutex);
2977 __flush_workqueue(wq);
2979 mutex_lock(&wq->mutex);
2981 for_each_pwq(pwq, wq) {
2984 raw_spin_lock_irq(&pwq->pool->lock);
2985 drained = !pwq->nr_active && list_empty(&pwq->inactive_works);
2986 raw_spin_unlock_irq(&pwq->pool->lock);
2991 if (++flush_cnt == 10 ||
2992 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2993 pr_warn("workqueue %s: %s() isn't complete after %u tries\n",
2994 wq->name, __func__, flush_cnt);
2996 mutex_unlock(&wq->mutex);
3000 if (!--wq->nr_drainers)
3001 wq->flags &= ~__WQ_DRAINING;
3002 mutex_unlock(&wq->mutex);
3004 EXPORT_SYMBOL_GPL(drain_workqueue);
3006 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
3009 struct worker *worker = NULL;
3010 struct worker_pool *pool;
3011 struct pool_workqueue *pwq;
3016 pool = get_work_pool(work);
3022 raw_spin_lock_irq(&pool->lock);
3023 /* see the comment in try_to_grab_pending() with the same code */
3024 pwq = get_work_pwq(work);
3026 if (unlikely(pwq->pool != pool))
3029 worker = find_worker_executing_work(pool, work);
3032 pwq = worker->current_pwq;
3035 check_flush_dependency(pwq->wq, work);
3037 insert_wq_barrier(pwq, barr, work, worker);
3038 raw_spin_unlock_irq(&pool->lock);
3041 * Force a lock recursion deadlock when using flush_work() inside a
3042 * single-threaded or rescuer equipped workqueue.
3044 * For single threaded workqueues the deadlock happens when the work
3045 * is after the work issuing the flush_work(). For rescuer equipped
3046 * workqueues the deadlock happens when the rescuer stalls, blocking
3050 (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)) {
3051 lock_map_acquire(&pwq->wq->lockdep_map);
3052 lock_map_release(&pwq->wq->lockdep_map);
3057 raw_spin_unlock_irq(&pool->lock);
3062 static bool __flush_work(struct work_struct *work, bool from_cancel)
3064 struct wq_barrier barr;
3066 if (WARN_ON(!wq_online))
3069 if (WARN_ON(!work->func))
3072 lock_map_acquire(&work->lockdep_map);
3073 lock_map_release(&work->lockdep_map);
3075 if (start_flush_work(work, &barr, from_cancel)) {
3076 wait_for_completion(&barr.done);
3077 destroy_work_on_stack(&barr.work);
3085 * flush_work - wait for a work to finish executing the last queueing instance
3086 * @work: the work to flush
3088 * Wait until @work has finished execution. @work is guaranteed to be idle
3089 * on return if it hasn't been requeued since flush started.
3092 * %true if flush_work() waited for the work to finish execution,
3093 * %false if it was already idle.
3095 bool flush_work(struct work_struct *work)
3097 return __flush_work(work, false);
3099 EXPORT_SYMBOL_GPL(flush_work);
3102 wait_queue_entry_t wait;
3103 struct work_struct *work;
3106 static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
3108 struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
3110 if (cwait->work != key)
3112 return autoremove_wake_function(wait, mode, sync, key);
3115 static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
3117 static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
3118 unsigned long flags;
3122 ret = try_to_grab_pending(work, is_dwork, &flags);
3124 * If someone else is already canceling, wait for it to
3125 * finish. flush_work() doesn't work for PREEMPT_NONE
3126 * because we may get scheduled between @work's completion
3127 * and the other canceling task resuming and clearing
3128 * CANCELING - flush_work() will return false immediately
3129 * as @work is no longer busy, try_to_grab_pending() will
3130 * return -ENOENT as @work is still being canceled and the
3131 * other canceling task won't be able to clear CANCELING as
3132 * we're hogging the CPU.
3134 * Let's wait for completion using a waitqueue. As this
3135 * may lead to the thundering herd problem, use a custom
3136 * wake function which matches @work along with exclusive
3139 if (unlikely(ret == -ENOENT)) {
3140 struct cwt_wait cwait;
3142 init_wait(&cwait.wait);
3143 cwait.wait.func = cwt_wakefn;
3146 prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
3147 TASK_UNINTERRUPTIBLE);
3148 if (work_is_canceling(work))
3150 finish_wait(&cancel_waitq, &cwait.wait);
3152 } while (unlikely(ret < 0));
3154 /* tell other tasks trying to grab @work to back off */
3155 mark_work_canceling(work);
3156 local_irq_restore(flags);
3159 * This allows canceling during early boot. We know that @work
3163 __flush_work(work, true);
3165 clear_work_data(work);
3168 * Paired with prepare_to_wait() above so that either
3169 * waitqueue_active() is visible here or !work_is_canceling() is
3173 if (waitqueue_active(&cancel_waitq))
3174 __wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
3180 * cancel_work_sync - cancel a work and wait for it to finish
3181 * @work: the work to cancel
3183 * Cancel @work and wait for its execution to finish. This function
3184 * can be used even if the work re-queues itself or migrates to
3185 * another workqueue. On return from this function, @work is
3186 * guaranteed to be not pending or executing on any CPU.
3188 * cancel_work_sync(&delayed_work->work) must not be used for
3189 * delayed_work's. Use cancel_delayed_work_sync() instead.
3191 * The caller must ensure that the workqueue on which @work was last
3192 * queued can't be destroyed before this function returns.
3195 * %true if @work was pending, %false otherwise.
3197 bool cancel_work_sync(struct work_struct *work)
3199 return __cancel_work_timer(work, false);
3201 EXPORT_SYMBOL_GPL(cancel_work_sync);
3204 * flush_delayed_work - wait for a dwork to finish executing the last queueing
3205 * @dwork: the delayed work to flush
3207 * Delayed timer is cancelled and the pending work is queued for
3208 * immediate execution. Like flush_work(), this function only
3209 * considers the last queueing instance of @dwork.
3212 * %true if flush_work() waited for the work to finish execution,
3213 * %false if it was already idle.
3215 bool flush_delayed_work(struct delayed_work *dwork)
3217 local_irq_disable();
3218 if (del_timer_sync(&dwork->timer))
3219 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
3221 return flush_work(&dwork->work);
3223 EXPORT_SYMBOL(flush_delayed_work);
3226 * flush_rcu_work - wait for a rwork to finish executing the last queueing
3227 * @rwork: the rcu work to flush
3230 * %true if flush_rcu_work() waited for the work to finish execution,
3231 * %false if it was already idle.
3233 bool flush_rcu_work(struct rcu_work *rwork)
3235 if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
3237 flush_work(&rwork->work);
3240 return flush_work(&rwork->work);
3243 EXPORT_SYMBOL(flush_rcu_work);
3245 static bool __cancel_work(struct work_struct *work, bool is_dwork)
3247 unsigned long flags;
3251 ret = try_to_grab_pending(work, is_dwork, &flags);
3252 } while (unlikely(ret == -EAGAIN));
3254 if (unlikely(ret < 0))
3257 set_work_pool_and_clear_pending(work, get_work_pool_id(work));
3258 local_irq_restore(flags);
3263 * See cancel_delayed_work()
3265 bool cancel_work(struct work_struct *work)
3267 return __cancel_work(work, false);
3269 EXPORT_SYMBOL(cancel_work);
3272 * cancel_delayed_work - cancel a delayed work
3273 * @dwork: delayed_work to cancel
3275 * Kill off a pending delayed_work.
3277 * Return: %true if @dwork was pending and canceled; %false if it wasn't
3281 * The work callback function may still be running on return, unless
3282 * it returns %true and the work doesn't re-arm itself. Explicitly flush or
3283 * use cancel_delayed_work_sync() to wait on it.
3285 * This function is safe to call from any context including IRQ handler.
3287 bool cancel_delayed_work(struct delayed_work *dwork)
3289 return __cancel_work(&dwork->work, true);
3291 EXPORT_SYMBOL(cancel_delayed_work);
3294 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3295 * @dwork: the delayed work cancel
3297 * This is cancel_work_sync() for delayed works.
3300 * %true if @dwork was pending, %false otherwise.
3302 bool cancel_delayed_work_sync(struct delayed_work *dwork)
3304 return __cancel_work_timer(&dwork->work, true);
3306 EXPORT_SYMBOL(cancel_delayed_work_sync);
3309 * schedule_on_each_cpu - execute a function synchronously on each online CPU
3310 * @func: the function to call
3312 * schedule_on_each_cpu() executes @func on each online CPU using the
3313 * system workqueue and blocks until all CPUs have completed.
3314 * schedule_on_each_cpu() is very slow.
3317 * 0 on success, -errno on failure.
3319 int schedule_on_each_cpu(work_func_t func)
3322 struct work_struct __percpu *works;
3324 works = alloc_percpu(struct work_struct);
3330 for_each_online_cpu(cpu) {
3331 struct work_struct *work = per_cpu_ptr(works, cpu);
3333 INIT_WORK(work, func);
3334 schedule_work_on(cpu, work);
3337 for_each_online_cpu(cpu)
3338 flush_work(per_cpu_ptr(works, cpu));
3346 * execute_in_process_context - reliably execute the routine with user context
3347 * @fn: the function to execute
3348 * @ew: guaranteed storage for the execute work structure (must
3349 * be available when the work executes)
3351 * Executes the function immediately if process context is available,
3352 * otherwise schedules the function for delayed execution.
3354 * Return: 0 - function was executed
3355 * 1 - function was scheduled for execution
3357 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
3359 if (!in_interrupt()) {
3364 INIT_WORK(&ew->work, fn);
3365 schedule_work(&ew->work);
3369 EXPORT_SYMBOL_GPL(execute_in_process_context);
3372 * free_workqueue_attrs - free a workqueue_attrs
3373 * @attrs: workqueue_attrs to free
3375 * Undo alloc_workqueue_attrs().
3377 void free_workqueue_attrs(struct workqueue_attrs *attrs)
3380 free_cpumask_var(attrs->cpumask);
3386 * alloc_workqueue_attrs - allocate a workqueue_attrs
3388 * Allocate a new workqueue_attrs, initialize with default settings and
3391 * Return: The allocated new workqueue_attr on success. %NULL on failure.
3393 struct workqueue_attrs *alloc_workqueue_attrs(void)
3395 struct workqueue_attrs *attrs;
3397 attrs = kzalloc(sizeof(*attrs), GFP_KERNEL);
3400 if (!alloc_cpumask_var(&attrs->cpumask, GFP_KERNEL))
3403 cpumask_copy(attrs->cpumask, cpu_possible_mask);
3406 free_workqueue_attrs(attrs);
3410 static void copy_workqueue_attrs(struct workqueue_attrs *to,
3411 const struct workqueue_attrs *from)
3413 to->nice = from->nice;
3414 cpumask_copy(to->cpumask, from->cpumask);
3416 * Unlike hash and equality test, this function doesn't ignore
3417 * ->no_numa as it is used for both pool and wq attrs. Instead,
3418 * get_unbound_pool() explicitly clears ->no_numa after copying.
3420 to->no_numa = from->no_numa;
3423 /* hash value of the content of @attr */
3424 static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
3428 hash = jhash_1word(attrs->nice, hash);
3429 hash = jhash(cpumask_bits(attrs->cpumask),
3430 BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
3434 /* content equality test */
3435 static bool wqattrs_equal(const struct workqueue_attrs *a,
3436 const struct workqueue_attrs *b)
3438 if (a->nice != b->nice)
3440 if (!cpumask_equal(a->cpumask, b->cpumask))
3446 * init_worker_pool - initialize a newly zalloc'd worker_pool
3447 * @pool: worker_pool to initialize
3449 * Initialize a newly zalloc'd @pool. It also allocates @pool->attrs.
3451 * Return: 0 on success, -errno on failure. Even on failure, all fields
3452 * inside @pool proper are initialized and put_unbound_pool() can be called
3453 * on @pool safely to release it.
3455 static int init_worker_pool(struct worker_pool *pool)
3457 raw_spin_lock_init(&pool->lock);
3460 pool->node = NUMA_NO_NODE;
3461 pool->flags |= POOL_DISASSOCIATED;
3462 pool->watchdog_ts = jiffies;
3463 INIT_LIST_HEAD(&pool->worklist);
3464 INIT_LIST_HEAD(&pool->idle_list);
3465 hash_init(pool->busy_hash);
3467 timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
3469 timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
3471 INIT_LIST_HEAD(&pool->workers);
3473 ida_init(&pool->worker_ida);
3474 INIT_HLIST_NODE(&pool->hash_node);
3477 /* shouldn't fail above this point */
3478 pool->attrs = alloc_workqueue_attrs();
3484 #ifdef CONFIG_LOCKDEP
3485 static void wq_init_lockdep(struct workqueue_struct *wq)
3489 lockdep_register_key(&wq->key);
3490 lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name);
3492 lock_name = wq->name;
3494 wq->lock_name = lock_name;
3495 lockdep_init_map(&wq->lockdep_map, lock_name, &wq->key, 0);
3498 static void wq_unregister_lockdep(struct workqueue_struct *wq)
3500 lockdep_unregister_key(&wq->key);
3503 static void wq_free_lockdep(struct workqueue_struct *wq)
3505 if (wq->lock_name != wq->name)
3506 kfree(wq->lock_name);
3509 static void wq_init_lockdep(struct workqueue_struct *wq)
3513 static void wq_unregister_lockdep(struct workqueue_struct *wq)
3517 static void wq_free_lockdep(struct workqueue_struct *wq)
3522 static void rcu_free_wq(struct rcu_head *rcu)
3524 struct workqueue_struct *wq =
3525 container_of(rcu, struct workqueue_struct, rcu);
3527 wq_free_lockdep(wq);
3529 if (!(wq->flags & WQ_UNBOUND))
3530 free_percpu(wq->cpu_pwqs);
3532 free_workqueue_attrs(wq->unbound_attrs);
3537 static void rcu_free_pool(struct rcu_head *rcu)
3539 struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
3541 ida_destroy(&pool->worker_ida);
3542 free_workqueue_attrs(pool->attrs);
3546 /* This returns with the lock held on success (pool manager is inactive). */
3547 static bool wq_manager_inactive(struct worker_pool *pool)
3549 raw_spin_lock_irq(&pool->lock);
3551 if (pool->flags & POOL_MANAGER_ACTIVE) {
3552 raw_spin_unlock_irq(&pool->lock);
3559 * put_unbound_pool - put a worker_pool
3560 * @pool: worker_pool to put
3562 * Put @pool. If its refcnt reaches zero, it gets destroyed in RCU
3563 * safe manner. get_unbound_pool() calls this function on its failure path
3564 * and this function should be able to release pools which went through,
3565 * successfully or not, init_worker_pool().
3567 * Should be called with wq_pool_mutex held.
3569 static void put_unbound_pool(struct worker_pool *pool)
3571 DECLARE_COMPLETION_ONSTACK(detach_completion);
3572 struct worker *worker;
3574 lockdep_assert_held(&wq_pool_mutex);
3580 if (WARN_ON(!(pool->cpu < 0)) ||
3581 WARN_ON(!list_empty(&pool->worklist)))
3584 /* release id and unhash */
3586 idr_remove(&worker_pool_idr, pool->id);
3587 hash_del(&pool->hash_node);
3590 * Become the manager and destroy all workers. This prevents
3591 * @pool's workers from blocking on attach_mutex. We're the last
3592 * manager and @pool gets freed with the flag set.
3593 * Because of how wq_manager_inactive() works, we will hold the
3594 * spinlock after a successful wait.
3596 rcuwait_wait_event(&manager_wait, wq_manager_inactive(pool),
3597 TASK_UNINTERRUPTIBLE);
3598 pool->flags |= POOL_MANAGER_ACTIVE;
3600 while ((worker = first_idle_worker(pool)))
3601 destroy_worker(worker);
3602 WARN_ON(pool->nr_workers || pool->nr_idle);
3603 raw_spin_unlock_irq(&pool->lock);
3605 mutex_lock(&wq_pool_attach_mutex);
3606 if (!list_empty(&pool->workers))
3607 pool->detach_completion = &detach_completion;
3608 mutex_unlock(&wq_pool_attach_mutex);
3610 if (pool->detach_completion)
3611 wait_for_completion(pool->detach_completion);
3613 /* shut down the timers */
3614 del_timer_sync(&pool->idle_timer);
3615 del_timer_sync(&pool->mayday_timer);
3617 /* RCU protected to allow dereferences from get_work_pool() */
3618 call_rcu(&pool->rcu, rcu_free_pool);
3622 * get_unbound_pool - get a worker_pool with the specified attributes
3623 * @attrs: the attributes of the worker_pool to get
3625 * Obtain a worker_pool which has the same attributes as @attrs, bump the
3626 * reference count and return it. If there already is a matching
3627 * worker_pool, it will be used; otherwise, this function attempts to
3630 * Should be called with wq_pool_mutex held.
3632 * Return: On success, a worker_pool with the same attributes as @attrs.
3633 * On failure, %NULL.
3635 static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
3637 u32 hash = wqattrs_hash(attrs);
3638 struct worker_pool *pool;
3640 int target_node = NUMA_NO_NODE;
3642 lockdep_assert_held(&wq_pool_mutex);
3644 /* do we already have a matching pool? */
3645 hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
3646 if (wqattrs_equal(pool->attrs, attrs)) {
3652 /* if cpumask is contained inside a NUMA node, we belong to that node */
3653 if (wq_numa_enabled) {
3654 for_each_node(node) {
3655 if (cpumask_subset(attrs->cpumask,
3656 wq_numa_possible_cpumask[node])) {
3663 /* nope, create a new one */
3664 pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, target_node);
3665 if (!pool || init_worker_pool(pool) < 0)
3668 lockdep_set_subclass(&pool->lock, 1); /* see put_pwq() */
3669 copy_workqueue_attrs(pool->attrs, attrs);
3670 pool->node = target_node;
3673 * no_numa isn't a worker_pool attribute, always clear it. See
3674 * 'struct workqueue_attrs' comments for detail.
3676 pool->attrs->no_numa = false;
3678 if (worker_pool_assign_id(pool) < 0)
3681 /* create and start the initial worker */
3682 if (wq_online && !create_worker(pool))
3686 hash_add(unbound_pool_hash, &pool->hash_node, hash);
3691 put_unbound_pool(pool);
3695 static void rcu_free_pwq(struct rcu_head *rcu)
3697 kmem_cache_free(pwq_cache,
3698 container_of(rcu, struct pool_workqueue, rcu));
3702 * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
3703 * and needs to be destroyed.
3705 static void pwq_unbound_release_workfn(struct work_struct *work)
3707 struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
3708 unbound_release_work);
3709 struct workqueue_struct *wq = pwq->wq;
3710 struct worker_pool *pool = pwq->pool;
3711 bool is_last = false;
3714 * when @pwq is not linked, it doesn't hold any reference to the
3715 * @wq, and @wq is invalid to access.
3717 if (!list_empty(&pwq->pwqs_node)) {
3718 if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
3721 mutex_lock(&wq->mutex);
3722 list_del_rcu(&pwq->pwqs_node);
3723 is_last = list_empty(&wq->pwqs);
3724 mutex_unlock(&wq->mutex);
3727 mutex_lock(&wq_pool_mutex);
3728 put_unbound_pool(pool);
3729 mutex_unlock(&wq_pool_mutex);
3731 call_rcu(&pwq->rcu, rcu_free_pwq);
3734 * If we're the last pwq going away, @wq is already dead and no one
3735 * is gonna access it anymore. Schedule RCU free.
3738 wq_unregister_lockdep(wq);
3739 call_rcu(&wq->rcu, rcu_free_wq);
3744 * pwq_adjust_max_active - update a pwq's max_active to the current setting
3745 * @pwq: target pool_workqueue
3747 * If @pwq isn't freezing, set @pwq->max_active to the associated
3748 * workqueue's saved_max_active and activate inactive work items
3749 * accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
3751 static void pwq_adjust_max_active(struct pool_workqueue *pwq)
3753 struct workqueue_struct *wq = pwq->wq;
3754 bool freezable = wq->flags & WQ_FREEZABLE;
3755 unsigned long flags;
3757 /* for @wq->saved_max_active */
3758 lockdep_assert_held(&wq->mutex);
3760 /* fast exit for non-freezable wqs */
3761 if (!freezable && pwq->max_active == wq->saved_max_active)
3764 /* this function can be called during early boot w/ irq disabled */
3765 raw_spin_lock_irqsave(&pwq->pool->lock, flags);
3768 * During [un]freezing, the caller is responsible for ensuring that
3769 * this function is called at least once after @workqueue_freezing
3770 * is updated and visible.
3772 if (!freezable || !workqueue_freezing) {
3775 pwq->max_active = wq->saved_max_active;
3777 while (!list_empty(&pwq->inactive_works) &&
3778 pwq->nr_active < pwq->max_active) {
3779 pwq_activate_first_inactive(pwq);
3784 * Need to kick a worker after thawed or an unbound wq's
3785 * max_active is bumped. In realtime scenarios, always kicking a
3786 * worker will cause interference on the isolated cpu cores, so
3787 * let's kick iff work items were activated.
3790 wake_up_worker(pwq->pool);
3792 pwq->max_active = 0;
3795 raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
3798 /* initialize newly allocated @pwq which is associated with @wq and @pool */
3799 static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
3800 struct worker_pool *pool)
3802 BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3804 memset(pwq, 0, sizeof(*pwq));
3808 pwq->flush_color = -1;
3810 INIT_LIST_HEAD(&pwq->inactive_works);
3811 INIT_LIST_HEAD(&pwq->pwqs_node);
3812 INIT_LIST_HEAD(&pwq->mayday_node);
3813 INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
3816 /* sync @pwq with the current state of its associated wq and link it */
3817 static void link_pwq(struct pool_workqueue *pwq)
3819 struct workqueue_struct *wq = pwq->wq;
3821 lockdep_assert_held(&wq->mutex);
3823 /* may be called multiple times, ignore if already linked */
3824 if (!list_empty(&pwq->pwqs_node))
3827 /* set the matching work_color */
3828 pwq->work_color = wq->work_color;
3830 /* sync max_active to the current setting */
3831 pwq_adjust_max_active(pwq);
3834 list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
3837 /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
3838 static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
3839 const struct workqueue_attrs *attrs)
3841 struct worker_pool *pool;
3842 struct pool_workqueue *pwq;
3844 lockdep_assert_held(&wq_pool_mutex);
3846 pool = get_unbound_pool(attrs);
3850 pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
3852 put_unbound_pool(pool);
3856 init_pwq(pwq, wq, pool);
3861 * wq_calc_node_cpumask - calculate a wq_attrs' cpumask for the specified node
3862 * @attrs: the wq_attrs of the default pwq of the target workqueue
3863 * @node: the target NUMA node
3864 * @cpu_going_down: if >= 0, the CPU to consider as offline
3865 * @cpumask: outarg, the resulting cpumask
3867 * Calculate the cpumask a workqueue with @attrs should use on @node. If
3868 * @cpu_going_down is >= 0, that cpu is considered offline during
3869 * calculation. The result is stored in @cpumask.
3871 * If NUMA affinity is not enabled, @attrs->cpumask is always used. If
3872 * enabled and @node has online CPUs requested by @attrs, the returned
3873 * cpumask is the intersection of the possible CPUs of @node and
3876 * The caller is responsible for ensuring that the cpumask of @node stays
3879 * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
3882 static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
3883 int cpu_going_down, cpumask_t *cpumask)
3885 if (!wq_numa_enabled || attrs->no_numa)
3888 /* does @node have any online CPUs @attrs wants? */
3889 cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
3890 if (cpu_going_down >= 0)
3891 cpumask_clear_cpu(cpu_going_down, cpumask);
3893 if (cpumask_empty(cpumask))
3896 /* yeap, return possible CPUs in @node that @attrs wants */
3897 cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
3899 if (cpumask_empty(cpumask)) {
3900 pr_warn_once("WARNING: workqueue cpumask: online intersect > "
3901 "possible intersect\n");
3905 return !cpumask_equal(cpumask, attrs->cpumask);
3908 cpumask_copy(cpumask, attrs->cpumask);
3912 /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
3913 static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
3915 struct pool_workqueue *pwq)
3917 struct pool_workqueue *old_pwq;
3919 lockdep_assert_held(&wq_pool_mutex);
3920 lockdep_assert_held(&wq->mutex);
3922 /* link_pwq() can handle duplicate calls */
3925 old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
3926 rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
3930 /* context to store the prepared attrs & pwqs before applying */
3931 struct apply_wqattrs_ctx {
3932 struct workqueue_struct *wq; /* target workqueue */
3933 struct workqueue_attrs *attrs; /* attrs to apply */
3934 struct list_head list; /* queued for batching commit */
3935 struct pool_workqueue *dfl_pwq;
3936 struct pool_workqueue *pwq_tbl[];
3939 /* free the resources after success or abort */
3940 static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
3946 put_pwq_unlocked(ctx->pwq_tbl[node]);
3947 put_pwq_unlocked(ctx->dfl_pwq);
3949 free_workqueue_attrs(ctx->attrs);
3955 /* allocate the attrs and pwqs for later installation */
3956 static struct apply_wqattrs_ctx *
3957 apply_wqattrs_prepare(struct workqueue_struct *wq,
3958 const struct workqueue_attrs *attrs,
3959 const cpumask_var_t unbound_cpumask)
3961 struct apply_wqattrs_ctx *ctx;
3962 struct workqueue_attrs *new_attrs, *tmp_attrs;
3965 lockdep_assert_held(&wq_pool_mutex);
3967 ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_node_ids), GFP_KERNEL);
3969 new_attrs = alloc_workqueue_attrs();
3970 tmp_attrs = alloc_workqueue_attrs();
3971 if (!ctx || !new_attrs || !tmp_attrs)
3975 * Calculate the attrs of the default pwq with unbound_cpumask
3976 * which is wq_unbound_cpumask or to set to wq_unbound_cpumask.
3977 * If the user configured cpumask doesn't overlap with the
3978 * wq_unbound_cpumask, we fallback to the wq_unbound_cpumask.
3980 copy_workqueue_attrs(new_attrs, attrs);
3981 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, unbound_cpumask);
3982 if (unlikely(cpumask_empty(new_attrs->cpumask)))
3983 cpumask_copy(new_attrs->cpumask, unbound_cpumask);
3986 * We may create multiple pwqs with differing cpumasks. Make a
3987 * copy of @new_attrs which will be modified and used to obtain
3990 copy_workqueue_attrs(tmp_attrs, new_attrs);
3993 * If something goes wrong during CPU up/down, we'll fall back to
3994 * the default pwq covering whole @attrs->cpumask. Always create
3995 * it even if we don't use it immediately.
3997 ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
4001 for_each_node(node) {
4002 if (wq_calc_node_cpumask(new_attrs, node, -1, tmp_attrs->cpumask)) {
4003 ctx->pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
4004 if (!ctx->pwq_tbl[node])
4007 ctx->dfl_pwq->refcnt++;
4008 ctx->pwq_tbl[node] = ctx->dfl_pwq;
4012 /* save the user configured attrs and sanitize it. */
4013 copy_workqueue_attrs(new_attrs, attrs);
4014 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
4015 ctx->attrs = new_attrs;
4018 free_workqueue_attrs(tmp_attrs);
4022 free_workqueue_attrs(tmp_attrs);
4023 free_workqueue_attrs(new_attrs);
4024 apply_wqattrs_cleanup(ctx);
4028 /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
4029 static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
4033 /* all pwqs have been created successfully, let's install'em */
4034 mutex_lock(&ctx->wq->mutex);
4036 copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
4038 /* save the previous pwq and install the new one */
4040 ctx->pwq_tbl[node] = numa_pwq_tbl_install(ctx->wq, node,
4041 ctx->pwq_tbl[node]);
4043 /* @dfl_pwq might not have been used, ensure it's linked */
4044 link_pwq(ctx->dfl_pwq);
4045 swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
4047 mutex_unlock(&ctx->wq->mutex);
4050 static void apply_wqattrs_lock(void)
4052 /* CPUs should stay stable across pwq creations and installations */
4054 mutex_lock(&wq_pool_mutex);
4057 static void apply_wqattrs_unlock(void)
4059 mutex_unlock(&wq_pool_mutex);
4063 static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
4064 const struct workqueue_attrs *attrs)
4066 struct apply_wqattrs_ctx *ctx;
4068 /* only unbound workqueues can change attributes */
4069 if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
4072 /* creating multiple pwqs breaks ordering guarantee */
4073 if (!list_empty(&wq->pwqs)) {
4074 if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
4077 wq->flags &= ~__WQ_ORDERED;
4080 ctx = apply_wqattrs_prepare(wq, attrs, wq_unbound_cpumask);
4084 /* the ctx has been prepared successfully, let's commit it */
4085 apply_wqattrs_commit(ctx);
4086 apply_wqattrs_cleanup(ctx);
4092 * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
4093 * @wq: the target workqueue
4094 * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
4096 * Apply @attrs to an unbound workqueue @wq. Unless disabled, on NUMA
4097 * machines, this function maps a separate pwq to each NUMA node with
4098 * possibles CPUs in @attrs->cpumask so that work items are affine to the
4099 * NUMA node it was issued on. Older pwqs are released as in-flight work
4100 * items finish. Note that a work item which repeatedly requeues itself
4101 * back-to-back will stay on its current pwq.
4103 * Performs GFP_KERNEL allocations.
4105 * Assumes caller has CPU hotplug read exclusion, i.e. cpus_read_lock().
4107 * Return: 0 on success and -errno on failure.
4109 int apply_workqueue_attrs(struct workqueue_struct *wq,
4110 const struct workqueue_attrs *attrs)
4114 lockdep_assert_cpus_held();
4116 mutex_lock(&wq_pool_mutex);
4117 ret = apply_workqueue_attrs_locked(wq, attrs);
4118 mutex_unlock(&wq_pool_mutex);
4124 * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
4125 * @wq: the target workqueue
4126 * @cpu: the CPU coming up or going down
4127 * @online: whether @cpu is coming up or going down
4129 * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
4130 * %CPU_DOWN_FAILED. @cpu is being hot[un]plugged, update NUMA affinity of
4133 * If NUMA affinity can't be adjusted due to memory allocation failure, it
4134 * falls back to @wq->dfl_pwq which may not be optimal but is always
4137 * Note that when the last allowed CPU of a NUMA node goes offline for a
4138 * workqueue with a cpumask spanning multiple nodes, the workers which were
4139 * already executing the work items for the workqueue will lose their CPU
4140 * affinity and may execute on any CPU. This is similar to how per-cpu
4141 * workqueues behave on CPU_DOWN. If a workqueue user wants strict
4142 * affinity, it's the user's responsibility to flush the work item from
4145 static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
4148 int node = cpu_to_node(cpu);
4149 int cpu_off = online ? -1 : cpu;
4150 struct pool_workqueue *old_pwq = NULL, *pwq;
4151 struct workqueue_attrs *target_attrs;
4154 lockdep_assert_held(&wq_pool_mutex);
4156 if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND) ||
4157 wq->unbound_attrs->no_numa)
4161 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
4162 * Let's use a preallocated one. The following buf is protected by
4163 * CPU hotplug exclusion.
4165 target_attrs = wq_update_unbound_numa_attrs_buf;
4166 cpumask = target_attrs->cpumask;
4168 copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
4169 pwq = unbound_pwq_by_node(wq, node);
4172 * Let's determine what needs to be done. If the target cpumask is
4173 * different from the default pwq's, we need to compare it to @pwq's
4174 * and create a new one if they don't match. If the target cpumask
4175 * equals the default pwq's, the default pwq should be used.
4177 if (wq_calc_node_cpumask(wq->dfl_pwq->pool->attrs, node, cpu_off, cpumask)) {
4178 if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
4184 /* create a new pwq */
4185 pwq = alloc_unbound_pwq(wq, target_attrs);
4187 pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
4192 /* Install the new pwq. */
4193 mutex_lock(&wq->mutex);
4194 old_pwq = numa_pwq_tbl_install(wq, node, pwq);
4198 mutex_lock(&wq->mutex);
4199 raw_spin_lock_irq(&wq->dfl_pwq->pool->lock);
4200 get_pwq(wq->dfl_pwq);
4201 raw_spin_unlock_irq(&wq->dfl_pwq->pool->lock);
4202 old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
4204 mutex_unlock(&wq->mutex);
4205 put_pwq_unlocked(old_pwq);
4208 static int alloc_and_link_pwqs(struct workqueue_struct *wq)
4210 bool highpri = wq->flags & WQ_HIGHPRI;
4213 if (!(wq->flags & WQ_UNBOUND)) {
4214 wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
4218 for_each_possible_cpu(cpu) {
4219 struct pool_workqueue *pwq =
4220 per_cpu_ptr(wq->cpu_pwqs, cpu);
4221 struct worker_pool *cpu_pools =
4222 per_cpu(cpu_worker_pools, cpu);
4224 init_pwq(pwq, wq, &cpu_pools[highpri]);
4226 mutex_lock(&wq->mutex);
4228 mutex_unlock(&wq->mutex);
4234 if (wq->flags & __WQ_ORDERED) {
4235 ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
4236 /* there should only be single pwq for ordering guarantee */
4237 WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
4238 wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
4239 "ordering guarantee broken for workqueue %s\n", wq->name);
4241 ret = apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
4248 static int wq_clamp_max_active(int max_active, unsigned int flags,
4251 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
4253 if (max_active < 1 || max_active > lim)
4254 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
4255 max_active, name, 1, lim);
4257 return clamp_val(max_active, 1, lim);
4261 * Workqueues which may be used during memory reclaim should have a rescuer
4262 * to guarantee forward progress.
4264 static int init_rescuer(struct workqueue_struct *wq)
4266 struct worker *rescuer;
4269 if (!(wq->flags & WQ_MEM_RECLAIM))
4272 rescuer = alloc_worker(NUMA_NO_NODE);
4276 rescuer->rescue_wq = wq;
4277 rescuer->task = kthread_create(rescuer_thread, rescuer, "%s", wq->name);
4278 if (IS_ERR(rescuer->task)) {
4279 ret = PTR_ERR(rescuer->task);
4284 wq->rescuer = rescuer;
4285 kthread_bind_mask(rescuer->task, cpu_possible_mask);
4286 wake_up_process(rescuer->task);
4292 struct workqueue_struct *alloc_workqueue(const char *fmt,
4294 int max_active, ...)
4296 size_t tbl_size = 0;
4298 struct workqueue_struct *wq;
4299 struct pool_workqueue *pwq;
4302 * Unbound && max_active == 1 used to imply ordered, which is no
4303 * longer the case on NUMA machines due to per-node pools. While
4304 * alloc_ordered_workqueue() is the right way to create an ordered
4305 * workqueue, keep the previous behavior to avoid subtle breakages
4308 if ((flags & WQ_UNBOUND) && max_active == 1)
4309 flags |= __WQ_ORDERED;
4311 /* see the comment above the definition of WQ_POWER_EFFICIENT */
4312 if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
4313 flags |= WQ_UNBOUND;
4315 /* allocate wq and format name */
4316 if (flags & WQ_UNBOUND)
4317 tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
4319 wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
4323 if (flags & WQ_UNBOUND) {
4324 wq->unbound_attrs = alloc_workqueue_attrs();
4325 if (!wq->unbound_attrs)
4329 va_start(args, max_active);
4330 vsnprintf(wq->name, sizeof(wq->name), fmt, args);
4333 max_active = max_active ?: WQ_DFL_ACTIVE;
4334 max_active = wq_clamp_max_active(max_active, flags, wq->name);
4338 wq->saved_max_active = max_active;
4339 mutex_init(&wq->mutex);
4340 atomic_set(&wq->nr_pwqs_to_flush, 0);
4341 INIT_LIST_HEAD(&wq->pwqs);
4342 INIT_LIST_HEAD(&wq->flusher_queue);
4343 INIT_LIST_HEAD(&wq->flusher_overflow);
4344 INIT_LIST_HEAD(&wq->maydays);
4346 wq_init_lockdep(wq);
4347 INIT_LIST_HEAD(&wq->list);
4349 if (alloc_and_link_pwqs(wq) < 0)
4350 goto err_unreg_lockdep;
4352 if (wq_online && init_rescuer(wq) < 0)
4355 if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
4359 * wq_pool_mutex protects global freeze state and workqueues list.
4360 * Grab it, adjust max_active and add the new @wq to workqueues
4363 mutex_lock(&wq_pool_mutex);
4365 mutex_lock(&wq->mutex);
4366 for_each_pwq(pwq, wq)
4367 pwq_adjust_max_active(pwq);
4368 mutex_unlock(&wq->mutex);
4370 list_add_tail_rcu(&wq->list, &workqueues);
4372 mutex_unlock(&wq_pool_mutex);
4377 wq_unregister_lockdep(wq);
4378 wq_free_lockdep(wq);
4380 free_workqueue_attrs(wq->unbound_attrs);
4384 destroy_workqueue(wq);
4387 EXPORT_SYMBOL_GPL(alloc_workqueue);
4389 static bool pwq_busy(struct pool_workqueue *pwq)
4393 for (i = 0; i < WORK_NR_COLORS; i++)
4394 if (pwq->nr_in_flight[i])
4397 if ((pwq != pwq->wq->dfl_pwq) && (pwq->refcnt > 1))
4399 if (pwq->nr_active || !list_empty(&pwq->inactive_works))
4406 * destroy_workqueue - safely terminate a workqueue
4407 * @wq: target workqueue
4409 * Safely destroy a workqueue. All work currently pending will be done first.
4411 void destroy_workqueue(struct workqueue_struct *wq)
4413 struct pool_workqueue *pwq;
4417 * Remove it from sysfs first so that sanity check failure doesn't
4418 * lead to sysfs name conflicts.
4420 workqueue_sysfs_unregister(wq);
4422 /* drain it before proceeding with destruction */
4423 drain_workqueue(wq);
4425 /* kill rescuer, if sanity checks fail, leave it w/o rescuer */
4427 struct worker *rescuer = wq->rescuer;
4429 /* this prevents new queueing */
4430 raw_spin_lock_irq(&wq_mayday_lock);
4432 raw_spin_unlock_irq(&wq_mayday_lock);
4434 /* rescuer will empty maydays list before exiting */
4435 kthread_stop(rescuer->task);
4440 * Sanity checks - grab all the locks so that we wait for all
4441 * in-flight operations which may do put_pwq().
4443 mutex_lock(&wq_pool_mutex);
4444 mutex_lock(&wq->mutex);
4445 for_each_pwq(pwq, wq) {
4446 raw_spin_lock_irq(&pwq->pool->lock);
4447 if (WARN_ON(pwq_busy(pwq))) {
4448 pr_warn("%s: %s has the following busy pwq\n",
4449 __func__, wq->name);
4451 raw_spin_unlock_irq(&pwq->pool->lock);
4452 mutex_unlock(&wq->mutex);
4453 mutex_unlock(&wq_pool_mutex);
4454 show_one_workqueue(wq);
4457 raw_spin_unlock_irq(&pwq->pool->lock);
4459 mutex_unlock(&wq->mutex);
4462 * wq list is used to freeze wq, remove from list after
4463 * flushing is complete in case freeze races us.
4465 list_del_rcu(&wq->list);
4466 mutex_unlock(&wq_pool_mutex);
4468 if (!(wq->flags & WQ_UNBOUND)) {
4469 wq_unregister_lockdep(wq);
4471 * The base ref is never dropped on per-cpu pwqs. Directly
4472 * schedule RCU free.
4474 call_rcu(&wq->rcu, rcu_free_wq);
4477 * We're the sole accessor of @wq at this point. Directly
4478 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
4479 * @wq will be freed when the last pwq is released.
4481 for_each_node(node) {
4482 pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
4483 RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
4484 put_pwq_unlocked(pwq);
4488 * Put dfl_pwq. @wq may be freed any time after dfl_pwq is
4489 * put. Don't access it afterwards.
4493 put_pwq_unlocked(pwq);
4496 EXPORT_SYMBOL_GPL(destroy_workqueue);
4499 * workqueue_set_max_active - adjust max_active of a workqueue
4500 * @wq: target workqueue
4501 * @max_active: new max_active value.
4503 * Set max_active of @wq to @max_active.
4506 * Don't call from IRQ context.
4508 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4510 struct pool_workqueue *pwq;
4512 /* disallow meddling with max_active for ordered workqueues */
4513 if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
4516 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4518 mutex_lock(&wq->mutex);
4520 wq->flags &= ~__WQ_ORDERED;
4521 wq->saved_max_active = max_active;
4523 for_each_pwq(pwq, wq)
4524 pwq_adjust_max_active(pwq);
4526 mutex_unlock(&wq->mutex);
4528 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4531 * current_work - retrieve %current task's work struct
4533 * Determine if %current task is a workqueue worker and what it's working on.
4534 * Useful to find out the context that the %current task is running in.
4536 * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
4538 struct work_struct *current_work(void)
4540 struct worker *worker = current_wq_worker();
4542 return worker ? worker->current_work : NULL;
4544 EXPORT_SYMBOL(current_work);
4547 * current_is_workqueue_rescuer - is %current workqueue rescuer?
4549 * Determine whether %current is a workqueue rescuer. Can be used from
4550 * work functions to determine whether it's being run off the rescuer task.
4552 * Return: %true if %current is a workqueue rescuer. %false otherwise.
4554 bool current_is_workqueue_rescuer(void)
4556 struct worker *worker = current_wq_worker();
4558 return worker && worker->rescue_wq;
4562 * workqueue_congested - test whether a workqueue is congested
4563 * @cpu: CPU in question
4564 * @wq: target workqueue
4566 * Test whether @wq's cpu workqueue for @cpu is congested. There is
4567 * no synchronization around this function and the test result is
4568 * unreliable and only useful as advisory hints or for debugging.
4570 * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4571 * Note that both per-cpu and unbound workqueues may be associated with
4572 * multiple pool_workqueues which have separate congested states. A
4573 * workqueue being congested on one CPU doesn't mean the workqueue is also
4574 * contested on other CPUs / NUMA nodes.
4577 * %true if congested, %false otherwise.
4579 bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4581 struct pool_workqueue *pwq;
4587 if (cpu == WORK_CPU_UNBOUND)
4588 cpu = smp_processor_id();
4590 if (!(wq->flags & WQ_UNBOUND))
4591 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
4593 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4595 ret = !list_empty(&pwq->inactive_works);
4601 EXPORT_SYMBOL_GPL(workqueue_congested);
4604 * work_busy - test whether a work is currently pending or running
4605 * @work: the work to be tested
4607 * Test whether @work is currently pending or running. There is no
4608 * synchronization around this function and the test result is
4609 * unreliable and only useful as advisory hints or for debugging.
4612 * OR'd bitmask of WORK_BUSY_* bits.
4614 unsigned int work_busy(struct work_struct *work)
4616 struct worker_pool *pool;
4617 unsigned long flags;
4618 unsigned int ret = 0;
4620 if (work_pending(work))
4621 ret |= WORK_BUSY_PENDING;
4624 pool = get_work_pool(work);
4626 raw_spin_lock_irqsave(&pool->lock, flags);
4627 if (find_worker_executing_work(pool, work))
4628 ret |= WORK_BUSY_RUNNING;
4629 raw_spin_unlock_irqrestore(&pool->lock, flags);
4635 EXPORT_SYMBOL_GPL(work_busy);
4638 * set_worker_desc - set description for the current work item
4639 * @fmt: printf-style format string
4640 * @...: arguments for the format string
4642 * This function can be called by a running work function to describe what
4643 * the work item is about. If the worker task gets dumped, this
4644 * information will be printed out together to help debugging. The
4645 * description can be at most WORKER_DESC_LEN including the trailing '\0'.
4647 void set_worker_desc(const char *fmt, ...)
4649 struct worker *worker = current_wq_worker();
4653 va_start(args, fmt);
4654 vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
4658 EXPORT_SYMBOL_GPL(set_worker_desc);
4661 * print_worker_info - print out worker information and description
4662 * @log_lvl: the log level to use when printing
4663 * @task: target task
4665 * If @task is a worker and currently executing a work item, print out the
4666 * name of the workqueue being serviced and worker description set with
4667 * set_worker_desc() by the currently executing work item.
4669 * This function can be safely called on any task as long as the
4670 * task_struct itself is accessible. While safe, this function isn't
4671 * synchronized and may print out mixups or garbages of limited length.
4673 void print_worker_info(const char *log_lvl, struct task_struct *task)
4675 work_func_t *fn = NULL;
4676 char name[WQ_NAME_LEN] = { };
4677 char desc[WORKER_DESC_LEN] = { };
4678 struct pool_workqueue *pwq = NULL;
4679 struct workqueue_struct *wq = NULL;
4680 struct worker *worker;
4682 if (!(task->flags & PF_WQ_WORKER))
4686 * This function is called without any synchronization and @task
4687 * could be in any state. Be careful with dereferences.
4689 worker = kthread_probe_data(task);
4692 * Carefully copy the associated workqueue's workfn, name and desc.
4693 * Keep the original last '\0' in case the original is garbage.
4695 copy_from_kernel_nofault(&fn, &worker->current_func, sizeof(fn));
4696 copy_from_kernel_nofault(&pwq, &worker->current_pwq, sizeof(pwq));
4697 copy_from_kernel_nofault(&wq, &pwq->wq, sizeof(wq));
4698 copy_from_kernel_nofault(name, wq->name, sizeof(name) - 1);
4699 copy_from_kernel_nofault(desc, worker->desc, sizeof(desc) - 1);
4701 if (fn || name[0] || desc[0]) {
4702 printk("%sWorkqueue: %s %ps", log_lvl, name, fn);
4703 if (strcmp(name, desc))
4704 pr_cont(" (%s)", desc);
4709 static void pr_cont_pool_info(struct worker_pool *pool)
4711 pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
4712 if (pool->node != NUMA_NO_NODE)
4713 pr_cont(" node=%d", pool->node);
4714 pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
4717 static void pr_cont_work(bool comma, struct work_struct *work)
4719 if (work->func == wq_barrier_func) {
4720 struct wq_barrier *barr;
4722 barr = container_of(work, struct wq_barrier, work);
4724 pr_cont("%s BAR(%d)", comma ? "," : "",
4725 task_pid_nr(barr->task));
4727 pr_cont("%s %ps", comma ? "," : "", work->func);
4731 static void show_pwq(struct pool_workqueue *pwq)
4733 struct worker_pool *pool = pwq->pool;
4734 struct work_struct *work;
4735 struct worker *worker;
4736 bool has_in_flight = false, has_pending = false;
4739 pr_info(" pwq %d:", pool->id);
4740 pr_cont_pool_info(pool);
4742 pr_cont(" active=%d/%d refcnt=%d%s\n",
4743 pwq->nr_active, pwq->max_active, pwq->refcnt,
4744 !list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
4746 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
4747 if (worker->current_pwq == pwq) {
4748 has_in_flight = true;
4752 if (has_in_flight) {
4755 pr_info(" in-flight:");
4756 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
4757 if (worker->current_pwq != pwq)
4760 pr_cont("%s %d%s:%ps", comma ? "," : "",
4761 task_pid_nr(worker->task),
4762 worker->rescue_wq ? "(RESCUER)" : "",
4763 worker->current_func);
4764 list_for_each_entry(work, &worker->scheduled, entry)
4765 pr_cont_work(false, work);
4771 list_for_each_entry(work, &pool->worklist, entry) {
4772 if (get_work_pwq(work) == pwq) {
4780 pr_info(" pending:");
4781 list_for_each_entry(work, &pool->worklist, entry) {
4782 if (get_work_pwq(work) != pwq)
4785 pr_cont_work(comma, work);
4786 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
4791 if (!list_empty(&pwq->inactive_works)) {
4794 pr_info(" inactive:");
4795 list_for_each_entry(work, &pwq->inactive_works, entry) {
4796 pr_cont_work(comma, work);
4797 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
4804 * show_one_workqueue - dump state of specified workqueue
4805 * @wq: workqueue whose state will be printed
4807 void show_one_workqueue(struct workqueue_struct *wq)
4809 struct pool_workqueue *pwq;
4811 unsigned long flags;
4813 for_each_pwq(pwq, wq) {
4814 if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
4819 if (idle) /* Nothing to print for idle workqueue */
4822 pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
4824 for_each_pwq(pwq, wq) {
4825 raw_spin_lock_irqsave(&pwq->pool->lock, flags);
4826 if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
4828 * Defer printing to avoid deadlocks in console
4829 * drivers that queue work while holding locks
4830 * also taken in their write paths.
4832 printk_deferred_enter();
4834 printk_deferred_exit();
4836 raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
4838 * We could be printing a lot from atomic context, e.g.
4839 * sysrq-t -> show_all_workqueues(). Avoid triggering
4842 touch_nmi_watchdog();
4848 * show_one_worker_pool - dump state of specified worker pool
4849 * @pool: worker pool whose state will be printed
4851 static void show_one_worker_pool(struct worker_pool *pool)
4853 struct worker *worker;
4855 unsigned long flags;
4856 unsigned long hung = 0;
4858 raw_spin_lock_irqsave(&pool->lock, flags);
4859 if (pool->nr_workers == pool->nr_idle)
4862 /* How long the first pending work is waiting for a worker. */
4863 if (!list_empty(&pool->worklist))
4864 hung = jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000;
4867 * Defer printing to avoid deadlocks in console drivers that
4868 * queue work while holding locks also taken in their write
4871 printk_deferred_enter();
4872 pr_info("pool %d:", pool->id);
4873 pr_cont_pool_info(pool);
4874 pr_cont(" hung=%lus workers=%d", hung, pool->nr_workers);
4876 pr_cont(" manager: %d",
4877 task_pid_nr(pool->manager->task));
4878 list_for_each_entry(worker, &pool->idle_list, entry) {
4879 pr_cont(" %s%d", first ? "idle: " : "",
4880 task_pid_nr(worker->task));
4884 printk_deferred_exit();
4886 raw_spin_unlock_irqrestore(&pool->lock, flags);
4888 * We could be printing a lot from atomic context, e.g.
4889 * sysrq-t -> show_all_workqueues(). Avoid triggering
4892 touch_nmi_watchdog();
4897 * show_all_workqueues - dump workqueue state
4899 * Called from a sysrq handler or try_to_freeze_tasks() and prints out
4900 * all busy workqueues and pools.
4902 void show_all_workqueues(void)
4904 struct workqueue_struct *wq;
4905 struct worker_pool *pool;
4910 pr_info("Showing busy workqueues and worker pools:\n");
4912 list_for_each_entry_rcu(wq, &workqueues, list)
4913 show_one_workqueue(wq);
4915 for_each_pool(pool, pi)
4916 show_one_worker_pool(pool);
4921 /* used to show worker information through /proc/PID/{comm,stat,status} */
4922 void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
4926 /* always show the actual comm */
4927 off = strscpy(buf, task->comm, size);
4931 /* stabilize PF_WQ_WORKER and worker pool association */
4932 mutex_lock(&wq_pool_attach_mutex);
4934 if (task->flags & PF_WQ_WORKER) {
4935 struct worker *worker = kthread_data(task);
4936 struct worker_pool *pool = worker->pool;
4939 raw_spin_lock_irq(&pool->lock);
4941 * ->desc tracks information (wq name or
4942 * set_worker_desc()) for the latest execution. If
4943 * current, prepend '+', otherwise '-'.
4945 if (worker->desc[0] != '\0') {
4946 if (worker->current_work)
4947 scnprintf(buf + off, size - off, "+%s",
4950 scnprintf(buf + off, size - off, "-%s",
4953 raw_spin_unlock_irq(&pool->lock);
4957 mutex_unlock(&wq_pool_attach_mutex);
4965 * There are two challenges in supporting CPU hotplug. Firstly, there
4966 * are a lot of assumptions on strong associations among work, pwq and
4967 * pool which make migrating pending and scheduled works very
4968 * difficult to implement without impacting hot paths. Secondly,
4969 * worker pools serve mix of short, long and very long running works making
4970 * blocked draining impractical.
4972 * This is solved by allowing the pools to be disassociated from the CPU
4973 * running as an unbound one and allowing it to be reattached later if the
4974 * cpu comes back online.
4977 static void unbind_workers(int cpu)
4979 struct worker_pool *pool;
4980 struct worker *worker;
4982 for_each_cpu_worker_pool(pool, cpu) {
4983 mutex_lock(&wq_pool_attach_mutex);
4984 raw_spin_lock_irq(&pool->lock);
4987 * We've blocked all attach/detach operations. Make all workers
4988 * unbound and set DISASSOCIATED. Before this, all workers
4989 * must be on the cpu. After this, they may become diasporas.
4990 * And the preemption disabled section in their sched callbacks
4991 * are guaranteed to see WORKER_UNBOUND since the code here
4992 * is on the same cpu.
4994 for_each_pool_worker(worker, pool)
4995 worker->flags |= WORKER_UNBOUND;
4997 pool->flags |= POOL_DISASSOCIATED;
5000 * The handling of nr_running in sched callbacks are disabled
5001 * now. Zap nr_running. After this, nr_running stays zero and
5002 * need_more_worker() and keep_working() are always true as
5003 * long as the worklist is not empty. This pool now behaves as
5004 * an unbound (in terms of concurrency management) pool which
5005 * are served by workers tied to the pool.
5007 pool->nr_running = 0;
5010 * With concurrency management just turned off, a busy
5011 * worker blocking could lead to lengthy stalls. Kick off
5012 * unbound chain execution of currently pending work items.
5014 wake_up_worker(pool);
5016 raw_spin_unlock_irq(&pool->lock);
5018 for_each_pool_worker(worker, pool) {
5019 kthread_set_per_cpu(worker->task, -1);
5020 if (cpumask_intersects(wq_unbound_cpumask, cpu_active_mask))
5021 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, wq_unbound_cpumask) < 0);
5023 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, cpu_possible_mask) < 0);
5026 mutex_unlock(&wq_pool_attach_mutex);
5031 * rebind_workers - rebind all workers of a pool to the associated CPU
5032 * @pool: pool of interest
5034 * @pool->cpu is coming online. Rebind all workers to the CPU.
5036 static void rebind_workers(struct worker_pool *pool)
5038 struct worker *worker;
5040 lockdep_assert_held(&wq_pool_attach_mutex);
5043 * Restore CPU affinity of all workers. As all idle workers should
5044 * be on the run-queue of the associated CPU before any local
5045 * wake-ups for concurrency management happen, restore CPU affinity
5046 * of all workers first and then clear UNBOUND. As we're called
5047 * from CPU_ONLINE, the following shouldn't fail.
5049 for_each_pool_worker(worker, pool) {
5050 kthread_set_per_cpu(worker->task, pool->cpu);
5051 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
5052 pool->attrs->cpumask) < 0);
5055 raw_spin_lock_irq(&pool->lock);
5057 pool->flags &= ~POOL_DISASSOCIATED;
5059 for_each_pool_worker(worker, pool) {
5060 unsigned int worker_flags = worker->flags;
5063 * We want to clear UNBOUND but can't directly call
5064 * worker_clr_flags() or adjust nr_running. Atomically
5065 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
5066 * @worker will clear REBOUND using worker_clr_flags() when
5067 * it initiates the next execution cycle thus restoring
5068 * concurrency management. Note that when or whether
5069 * @worker clears REBOUND doesn't affect correctness.
5071 * WRITE_ONCE() is necessary because @worker->flags may be
5072 * tested without holding any lock in
5073 * wq_worker_running(). Without it, NOT_RUNNING test may
5074 * fail incorrectly leading to premature concurrency
5075 * management operations.
5077 WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
5078 worker_flags |= WORKER_REBOUND;
5079 worker_flags &= ~WORKER_UNBOUND;
5080 WRITE_ONCE(worker->flags, worker_flags);
5083 raw_spin_unlock_irq(&pool->lock);
5087 * restore_unbound_workers_cpumask - restore cpumask of unbound workers
5088 * @pool: unbound pool of interest
5089 * @cpu: the CPU which is coming up
5091 * An unbound pool may end up with a cpumask which doesn't have any online
5092 * CPUs. When a worker of such pool get scheduled, the scheduler resets
5093 * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
5094 * online CPU before, cpus_allowed of all its workers should be restored.
5096 static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
5098 static cpumask_t cpumask;
5099 struct worker *worker;
5101 lockdep_assert_held(&wq_pool_attach_mutex);
5103 /* is @cpu allowed for @pool? */
5104 if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
5107 cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
5109 /* as we're called from CPU_ONLINE, the following shouldn't fail */
5110 for_each_pool_worker(worker, pool)
5111 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
5114 int workqueue_prepare_cpu(unsigned int cpu)
5116 struct worker_pool *pool;
5118 for_each_cpu_worker_pool(pool, cpu) {
5119 if (pool->nr_workers)
5121 if (!create_worker(pool))
5127 int workqueue_online_cpu(unsigned int cpu)
5129 struct worker_pool *pool;
5130 struct workqueue_struct *wq;
5133 mutex_lock(&wq_pool_mutex);
5135 for_each_pool(pool, pi) {
5136 mutex_lock(&wq_pool_attach_mutex);
5138 if (pool->cpu == cpu)
5139 rebind_workers(pool);
5140 else if (pool->cpu < 0)
5141 restore_unbound_workers_cpumask(pool, cpu);
5143 mutex_unlock(&wq_pool_attach_mutex);
5146 /* update NUMA affinity of unbound workqueues */
5147 list_for_each_entry(wq, &workqueues, list)
5148 wq_update_unbound_numa(wq, cpu, true);
5150 mutex_unlock(&wq_pool_mutex);
5154 int workqueue_offline_cpu(unsigned int cpu)
5156 struct workqueue_struct *wq;
5158 /* unbinding per-cpu workers should happen on the local CPU */
5159 if (WARN_ON(cpu != smp_processor_id()))
5162 unbind_workers(cpu);
5164 /* update NUMA affinity of unbound workqueues */
5165 mutex_lock(&wq_pool_mutex);
5166 list_for_each_entry(wq, &workqueues, list)
5167 wq_update_unbound_numa(wq, cpu, false);
5168 mutex_unlock(&wq_pool_mutex);
5173 struct work_for_cpu {
5174 struct work_struct work;
5180 static void work_for_cpu_fn(struct work_struct *work)
5182 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
5184 wfc->ret = wfc->fn(wfc->arg);
5188 * work_on_cpu_key - run a function in thread context on a particular cpu
5189 * @cpu: the cpu to run on
5190 * @fn: the function to run
5191 * @arg: the function arg
5192 * @key: The lock class key for lock debugging purposes
5194 * It is up to the caller to ensure that the cpu doesn't go offline.
5195 * The caller must not hold any locks which would prevent @fn from completing.
5197 * Return: The value @fn returns.
5199 long work_on_cpu_key(int cpu, long (*fn)(void *),
5200 void *arg, struct lock_class_key *key)
5202 struct work_for_cpu wfc = { .fn = fn, .arg = arg };
5204 INIT_WORK_ONSTACK_KEY(&wfc.work, work_for_cpu_fn, key);
5205 schedule_work_on(cpu, &wfc.work);
5206 flush_work(&wfc.work);
5207 destroy_work_on_stack(&wfc.work);
5210 EXPORT_SYMBOL_GPL(work_on_cpu_key);
5213 * work_on_cpu_safe_key - run a function in thread context on a particular cpu
5214 * @cpu: the cpu to run on
5215 * @fn: the function to run
5216 * @arg: the function argument
5217 * @key: The lock class key for lock debugging purposes
5219 * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
5220 * any locks which would prevent @fn from completing.
5222 * Return: The value @fn returns.
5224 long work_on_cpu_safe_key(int cpu, long (*fn)(void *),
5225 void *arg, struct lock_class_key *key)
5230 if (cpu_online(cpu))
5231 ret = work_on_cpu_key(cpu, fn, arg, key);
5235 EXPORT_SYMBOL_GPL(work_on_cpu_safe_key);
5236 #endif /* CONFIG_SMP */
5238 #ifdef CONFIG_FREEZER
5241 * freeze_workqueues_begin - begin freezing workqueues
5243 * Start freezing workqueues. After this function returns, all freezable
5244 * workqueues will queue new works to their inactive_works list instead of
5248 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5250 void freeze_workqueues_begin(void)
5252 struct workqueue_struct *wq;
5253 struct pool_workqueue *pwq;
5255 mutex_lock(&wq_pool_mutex);
5257 WARN_ON_ONCE(workqueue_freezing);
5258 workqueue_freezing = true;
5260 list_for_each_entry(wq, &workqueues, list) {
5261 mutex_lock(&wq->mutex);
5262 for_each_pwq(pwq, wq)
5263 pwq_adjust_max_active(pwq);
5264 mutex_unlock(&wq->mutex);
5267 mutex_unlock(&wq_pool_mutex);
5271 * freeze_workqueues_busy - are freezable workqueues still busy?
5273 * Check whether freezing is complete. This function must be called
5274 * between freeze_workqueues_begin() and thaw_workqueues().
5277 * Grabs and releases wq_pool_mutex.
5280 * %true if some freezable workqueues are still busy. %false if freezing
5283 bool freeze_workqueues_busy(void)
5286 struct workqueue_struct *wq;
5287 struct pool_workqueue *pwq;
5289 mutex_lock(&wq_pool_mutex);
5291 WARN_ON_ONCE(!workqueue_freezing);
5293 list_for_each_entry(wq, &workqueues, list) {
5294 if (!(wq->flags & WQ_FREEZABLE))
5297 * nr_active is monotonically decreasing. It's safe
5298 * to peek without lock.
5301 for_each_pwq(pwq, wq) {
5302 WARN_ON_ONCE(pwq->nr_active < 0);
5303 if (pwq->nr_active) {
5312 mutex_unlock(&wq_pool_mutex);
5317 * thaw_workqueues - thaw workqueues
5319 * Thaw workqueues. Normal queueing is restored and all collected
5320 * frozen works are transferred to their respective pool worklists.
5323 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5325 void thaw_workqueues(void)
5327 struct workqueue_struct *wq;
5328 struct pool_workqueue *pwq;
5330 mutex_lock(&wq_pool_mutex);
5332 if (!workqueue_freezing)
5335 workqueue_freezing = false;
5337 /* restore max_active and repopulate worklist */
5338 list_for_each_entry(wq, &workqueues, list) {
5339 mutex_lock(&wq->mutex);
5340 for_each_pwq(pwq, wq)
5341 pwq_adjust_max_active(pwq);
5342 mutex_unlock(&wq->mutex);
5346 mutex_unlock(&wq_pool_mutex);
5348 #endif /* CONFIG_FREEZER */
5350 static int workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask)
5354 struct workqueue_struct *wq;
5355 struct apply_wqattrs_ctx *ctx, *n;
5357 lockdep_assert_held(&wq_pool_mutex);
5359 list_for_each_entry(wq, &workqueues, list) {
5360 if (!(wq->flags & WQ_UNBOUND))
5363 /* creating multiple pwqs breaks ordering guarantee */
5364 if (!list_empty(&wq->pwqs)) {
5365 if (wq->flags & __WQ_ORDERED_EXPLICIT)
5367 wq->flags &= ~__WQ_ORDERED;
5370 ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs, unbound_cpumask);
5376 list_add_tail(&ctx->list, &ctxs);
5379 list_for_each_entry_safe(ctx, n, &ctxs, list) {
5381 apply_wqattrs_commit(ctx);
5382 apply_wqattrs_cleanup(ctx);
5386 mutex_lock(&wq_pool_attach_mutex);
5387 cpumask_copy(wq_unbound_cpumask, unbound_cpumask);
5388 mutex_unlock(&wq_pool_attach_mutex);
5394 * workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
5395 * @cpumask: the cpumask to set
5397 * The low-level workqueues cpumask is a global cpumask that limits
5398 * the affinity of all unbound workqueues. This function check the @cpumask
5399 * and apply it to all unbound workqueues and updates all pwqs of them.
5401 * Return: 0 - Success
5402 * -EINVAL - Invalid @cpumask
5403 * -ENOMEM - Failed to allocate memory for attrs or pwqs.
5405 int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
5410 * Not excluding isolated cpus on purpose.
5411 * If the user wishes to include them, we allow that.
5413 cpumask_and(cpumask, cpumask, cpu_possible_mask);
5414 if (!cpumask_empty(cpumask)) {
5415 apply_wqattrs_lock();
5416 if (cpumask_equal(cpumask, wq_unbound_cpumask)) {
5421 ret = workqueue_apply_unbound_cpumask(cpumask);
5424 apply_wqattrs_unlock();
5432 * Workqueues with WQ_SYSFS flag set is visible to userland via
5433 * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
5434 * following attributes.
5436 * per_cpu RO bool : whether the workqueue is per-cpu or unbound
5437 * max_active RW int : maximum number of in-flight work items
5439 * Unbound workqueues have the following extra attributes.
5441 * pool_ids RO int : the associated pool IDs for each node
5442 * nice RW int : nice value of the workers
5443 * cpumask RW mask : bitmask of allowed CPUs for the workers
5444 * numa RW bool : whether enable NUMA affinity
5447 struct workqueue_struct *wq;
5451 static struct workqueue_struct *dev_to_wq(struct device *dev)
5453 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
5458 static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
5461 struct workqueue_struct *wq = dev_to_wq(dev);
5463 return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
5465 static DEVICE_ATTR_RO(per_cpu);
5467 static ssize_t max_active_show(struct device *dev,
5468 struct device_attribute *attr, char *buf)
5470 struct workqueue_struct *wq = dev_to_wq(dev);
5472 return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
5475 static ssize_t max_active_store(struct device *dev,
5476 struct device_attribute *attr, const char *buf,
5479 struct workqueue_struct *wq = dev_to_wq(dev);
5482 if (sscanf(buf, "%d", &val) != 1 || val <= 0)
5485 workqueue_set_max_active(wq, val);
5488 static DEVICE_ATTR_RW(max_active);
5490 static struct attribute *wq_sysfs_attrs[] = {
5491 &dev_attr_per_cpu.attr,
5492 &dev_attr_max_active.attr,
5495 ATTRIBUTE_GROUPS(wq_sysfs);
5497 static ssize_t wq_pool_ids_show(struct device *dev,
5498 struct device_attribute *attr, char *buf)
5500 struct workqueue_struct *wq = dev_to_wq(dev);
5501 const char *delim = "";
5502 int node, written = 0;
5506 for_each_node(node) {
5507 written += scnprintf(buf + written, PAGE_SIZE - written,
5508 "%s%d:%d", delim, node,
5509 unbound_pwq_by_node(wq, node)->pool->id);
5512 written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
5519 static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
5522 struct workqueue_struct *wq = dev_to_wq(dev);
5525 mutex_lock(&wq->mutex);
5526 written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
5527 mutex_unlock(&wq->mutex);
5532 /* prepare workqueue_attrs for sysfs store operations */
5533 static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
5535 struct workqueue_attrs *attrs;
5537 lockdep_assert_held(&wq_pool_mutex);
5539 attrs = alloc_workqueue_attrs();
5543 copy_workqueue_attrs(attrs, wq->unbound_attrs);
5547 static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
5548 const char *buf, size_t count)
5550 struct workqueue_struct *wq = dev_to_wq(dev);
5551 struct workqueue_attrs *attrs;
5554 apply_wqattrs_lock();
5556 attrs = wq_sysfs_prep_attrs(wq);
5560 if (sscanf(buf, "%d", &attrs->nice) == 1 &&
5561 attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
5562 ret = apply_workqueue_attrs_locked(wq, attrs);
5567 apply_wqattrs_unlock();
5568 free_workqueue_attrs(attrs);
5569 return ret ?: count;
5572 static ssize_t wq_cpumask_show(struct device *dev,
5573 struct device_attribute *attr, char *buf)
5575 struct workqueue_struct *wq = dev_to_wq(dev);
5578 mutex_lock(&wq->mutex);
5579 written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
5580 cpumask_pr_args(wq->unbound_attrs->cpumask));
5581 mutex_unlock(&wq->mutex);
5585 static ssize_t wq_cpumask_store(struct device *dev,
5586 struct device_attribute *attr,
5587 const char *buf, size_t count)
5589 struct workqueue_struct *wq = dev_to_wq(dev);
5590 struct workqueue_attrs *attrs;
5593 apply_wqattrs_lock();
5595 attrs = wq_sysfs_prep_attrs(wq);
5599 ret = cpumask_parse(buf, attrs->cpumask);
5601 ret = apply_workqueue_attrs_locked(wq, attrs);
5604 apply_wqattrs_unlock();
5605 free_workqueue_attrs(attrs);
5606 return ret ?: count;
5609 static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
5612 struct workqueue_struct *wq = dev_to_wq(dev);
5615 mutex_lock(&wq->mutex);
5616 written = scnprintf(buf, PAGE_SIZE, "%d\n",
5617 !wq->unbound_attrs->no_numa);
5618 mutex_unlock(&wq->mutex);
5623 static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
5624 const char *buf, size_t count)
5626 struct workqueue_struct *wq = dev_to_wq(dev);
5627 struct workqueue_attrs *attrs;
5628 int v, ret = -ENOMEM;
5630 apply_wqattrs_lock();
5632 attrs = wq_sysfs_prep_attrs(wq);
5637 if (sscanf(buf, "%d", &v) == 1) {
5638 attrs->no_numa = !v;
5639 ret = apply_workqueue_attrs_locked(wq, attrs);
5643 apply_wqattrs_unlock();
5644 free_workqueue_attrs(attrs);
5645 return ret ?: count;
5648 static struct device_attribute wq_sysfs_unbound_attrs[] = {
5649 __ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
5650 __ATTR(nice, 0644, wq_nice_show, wq_nice_store),
5651 __ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
5652 __ATTR(numa, 0644, wq_numa_show, wq_numa_store),
5656 static struct bus_type wq_subsys = {
5657 .name = "workqueue",
5658 .dev_groups = wq_sysfs_groups,
5661 static ssize_t wq_unbound_cpumask_show(struct device *dev,
5662 struct device_attribute *attr, char *buf)
5666 mutex_lock(&wq_pool_mutex);
5667 written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
5668 cpumask_pr_args(wq_unbound_cpumask));
5669 mutex_unlock(&wq_pool_mutex);
5674 static ssize_t wq_unbound_cpumask_store(struct device *dev,
5675 struct device_attribute *attr, const char *buf, size_t count)
5677 cpumask_var_t cpumask;
5680 if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
5683 ret = cpumask_parse(buf, cpumask);
5685 ret = workqueue_set_unbound_cpumask(cpumask);
5687 free_cpumask_var(cpumask);
5688 return ret ? ret : count;
5691 static struct device_attribute wq_sysfs_cpumask_attr =
5692 __ATTR(cpumask, 0644, wq_unbound_cpumask_show,
5693 wq_unbound_cpumask_store);
5695 static int __init wq_sysfs_init(void)
5699 err = subsys_virtual_register(&wq_subsys, NULL);
5703 return device_create_file(wq_subsys.dev_root, &wq_sysfs_cpumask_attr);
5705 core_initcall(wq_sysfs_init);
5707 static void wq_device_release(struct device *dev)
5709 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
5715 * workqueue_sysfs_register - make a workqueue visible in sysfs
5716 * @wq: the workqueue to register
5718 * Expose @wq in sysfs under /sys/bus/workqueue/devices.
5719 * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
5720 * which is the preferred method.
5722 * Workqueue user should use this function directly iff it wants to apply
5723 * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
5724 * apply_workqueue_attrs() may race against userland updating the
5727 * Return: 0 on success, -errno on failure.
5729 int workqueue_sysfs_register(struct workqueue_struct *wq)
5731 struct wq_device *wq_dev;
5735 * Adjusting max_active or creating new pwqs by applying
5736 * attributes breaks ordering guarantee. Disallow exposing ordered
5739 if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
5742 wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
5747 wq_dev->dev.bus = &wq_subsys;
5748 wq_dev->dev.release = wq_device_release;
5749 dev_set_name(&wq_dev->dev, "%s", wq->name);
5752 * unbound_attrs are created separately. Suppress uevent until
5753 * everything is ready.
5755 dev_set_uevent_suppress(&wq_dev->dev, true);
5757 ret = device_register(&wq_dev->dev);
5759 put_device(&wq_dev->dev);
5764 if (wq->flags & WQ_UNBOUND) {
5765 struct device_attribute *attr;
5767 for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
5768 ret = device_create_file(&wq_dev->dev, attr);
5770 device_unregister(&wq_dev->dev);
5777 dev_set_uevent_suppress(&wq_dev->dev, false);
5778 kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
5783 * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
5784 * @wq: the workqueue to unregister
5786 * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
5788 static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
5790 struct wq_device *wq_dev = wq->wq_dev;
5796 device_unregister(&wq_dev->dev);
5798 #else /* CONFIG_SYSFS */
5799 static void workqueue_sysfs_unregister(struct workqueue_struct *wq) { }
5800 #endif /* CONFIG_SYSFS */
5803 * Workqueue watchdog.
5805 * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
5806 * flush dependency, a concurrency managed work item which stays RUNNING
5807 * indefinitely. Workqueue stalls can be very difficult to debug as the
5808 * usual warning mechanisms don't trigger and internal workqueue state is
5811 * Workqueue watchdog monitors all worker pools periodically and dumps
5812 * state if some pools failed to make forward progress for a while where
5813 * forward progress is defined as the first item on ->worklist changing.
5815 * This mechanism is controlled through the kernel parameter
5816 * "workqueue.watchdog_thresh" which can be updated at runtime through the
5817 * corresponding sysfs parameter file.
5819 #ifdef CONFIG_WQ_WATCHDOG
5821 static unsigned long wq_watchdog_thresh = 30;
5822 static struct timer_list wq_watchdog_timer;
5824 static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
5825 static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
5827 static void wq_watchdog_reset_touched(void)
5831 wq_watchdog_touched = jiffies;
5832 for_each_possible_cpu(cpu)
5833 per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
5836 static void wq_watchdog_timer_fn(struct timer_list *unused)
5838 unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
5839 bool lockup_detected = false;
5840 unsigned long now = jiffies;
5841 struct worker_pool *pool;
5849 for_each_pool(pool, pi) {
5850 unsigned long pool_ts, touched, ts;
5852 if (list_empty(&pool->worklist))
5856 * If a virtual machine is stopped by the host it can look to
5857 * the watchdog like a stall.
5859 kvm_check_and_clear_guest_paused();
5861 /* get the latest of pool and touched timestamps */
5863 touched = READ_ONCE(per_cpu(wq_watchdog_touched_cpu, pool->cpu));
5865 touched = READ_ONCE(wq_watchdog_touched);
5866 pool_ts = READ_ONCE(pool->watchdog_ts);
5868 if (time_after(pool_ts, touched))
5874 if (time_after(now, ts + thresh)) {
5875 lockup_detected = true;
5876 pr_emerg("BUG: workqueue lockup - pool");
5877 pr_cont_pool_info(pool);
5878 pr_cont(" stuck for %us!\n",
5879 jiffies_to_msecs(now - pool_ts) / 1000);
5885 if (lockup_detected)
5886 show_all_workqueues();
5888 wq_watchdog_reset_touched();
5889 mod_timer(&wq_watchdog_timer, jiffies + thresh);
5892 notrace void wq_watchdog_touch(int cpu)
5895 per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
5897 wq_watchdog_touched = jiffies;
5900 static void wq_watchdog_set_thresh(unsigned long thresh)
5902 wq_watchdog_thresh = 0;
5903 del_timer_sync(&wq_watchdog_timer);
5906 wq_watchdog_thresh = thresh;
5907 wq_watchdog_reset_touched();
5908 mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
5912 static int wq_watchdog_param_set_thresh(const char *val,
5913 const struct kernel_param *kp)
5915 unsigned long thresh;
5918 ret = kstrtoul(val, 0, &thresh);
5923 wq_watchdog_set_thresh(thresh);
5925 wq_watchdog_thresh = thresh;
5930 static const struct kernel_param_ops wq_watchdog_thresh_ops = {
5931 .set = wq_watchdog_param_set_thresh,
5932 .get = param_get_ulong,
5935 module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
5938 static void wq_watchdog_init(void)
5940 timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
5941 wq_watchdog_set_thresh(wq_watchdog_thresh);
5944 #else /* CONFIG_WQ_WATCHDOG */
5946 static inline void wq_watchdog_init(void) { }
5948 #endif /* CONFIG_WQ_WATCHDOG */
5950 static void __init wq_numa_init(void)
5955 if (num_possible_nodes() <= 1)
5958 if (wq_disable_numa) {
5959 pr_info("workqueue: NUMA affinity support disabled\n");
5963 for_each_possible_cpu(cpu) {
5964 if (WARN_ON(cpu_to_node(cpu) == NUMA_NO_NODE)) {
5965 pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
5970 wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs();
5971 BUG_ON(!wq_update_unbound_numa_attrs_buf);
5974 * We want masks of possible CPUs of each node which isn't readily
5975 * available. Build one from cpu_to_node() which should have been
5976 * fully initialized by now.
5978 tbl = kcalloc(nr_node_ids, sizeof(tbl[0]), GFP_KERNEL);
5982 BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
5983 node_online(node) ? node : NUMA_NO_NODE));
5985 for_each_possible_cpu(cpu) {
5986 node = cpu_to_node(cpu);
5987 cpumask_set_cpu(cpu, tbl[node]);
5990 wq_numa_possible_cpumask = tbl;
5991 wq_numa_enabled = true;
5995 * workqueue_init_early - early init for workqueue subsystem
5997 * This is the first half of two-staged workqueue subsystem initialization
5998 * and invoked as soon as the bare basics - memory allocation, cpumasks and
5999 * idr are up. It sets up all the data structures and system workqueues
6000 * and allows early boot code to create workqueues and queue/cancel work
6001 * items. Actual work item execution starts only after kthreads can be
6002 * created and scheduled right before early initcalls.
6004 void __init workqueue_init_early(void)
6006 int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
6009 BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
6011 BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
6012 cpumask_copy(wq_unbound_cpumask, housekeeping_cpumask(HK_TYPE_WQ));
6013 cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, housekeeping_cpumask(HK_TYPE_DOMAIN));
6015 pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
6017 /* initialize CPU pools */
6018 for_each_possible_cpu(cpu) {
6019 struct worker_pool *pool;
6022 for_each_cpu_worker_pool(pool, cpu) {
6023 BUG_ON(init_worker_pool(pool));
6025 cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
6026 pool->attrs->nice = std_nice[i++];
6027 pool->node = cpu_to_node(cpu);
6030 mutex_lock(&wq_pool_mutex);
6031 BUG_ON(worker_pool_assign_id(pool));
6032 mutex_unlock(&wq_pool_mutex);
6036 /* create default unbound and ordered wq attrs */
6037 for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
6038 struct workqueue_attrs *attrs;
6040 BUG_ON(!(attrs = alloc_workqueue_attrs()));
6041 attrs->nice = std_nice[i];
6042 unbound_std_wq_attrs[i] = attrs;
6045 * An ordered wq should have only one pwq as ordering is
6046 * guaranteed by max_active which is enforced by pwqs.
6047 * Turn off NUMA so that dfl_pwq is used for all nodes.
6049 BUG_ON(!(attrs = alloc_workqueue_attrs()));
6050 attrs->nice = std_nice[i];
6051 attrs->no_numa = true;
6052 ordered_wq_attrs[i] = attrs;
6055 system_wq = alloc_workqueue("events", 0, 0);
6056 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
6057 system_long_wq = alloc_workqueue("events_long", 0, 0);
6058 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
6059 WQ_UNBOUND_MAX_ACTIVE);
6060 system_freezable_wq = alloc_workqueue("events_freezable",
6062 system_power_efficient_wq = alloc_workqueue("events_power_efficient",
6063 WQ_POWER_EFFICIENT, 0);
6064 system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
6065 WQ_FREEZABLE | WQ_POWER_EFFICIENT,
6067 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
6068 !system_unbound_wq || !system_freezable_wq ||
6069 !system_power_efficient_wq ||
6070 !system_freezable_power_efficient_wq);
6074 * workqueue_init - bring workqueue subsystem fully online
6076 * This is the latter half of two-staged workqueue subsystem initialization
6077 * and invoked as soon as kthreads can be created and scheduled.
6078 * Workqueues have been created and work items queued on them, but there
6079 * are no kworkers executing the work items yet. Populate the worker pools
6080 * with the initial workers and enable future kworker creations.
6082 void __init workqueue_init(void)
6084 struct workqueue_struct *wq;
6085 struct worker_pool *pool;
6089 * It'd be simpler to initialize NUMA in workqueue_init_early() but
6090 * CPU to node mapping may not be available that early on some
6091 * archs such as power and arm64. As per-cpu pools created
6092 * previously could be missing node hint and unbound pools NUMA
6093 * affinity, fix them up.
6095 * Also, while iterating workqueues, create rescuers if requested.
6099 mutex_lock(&wq_pool_mutex);
6101 for_each_possible_cpu(cpu) {
6102 for_each_cpu_worker_pool(pool, cpu) {
6103 pool->node = cpu_to_node(cpu);
6107 list_for_each_entry(wq, &workqueues, list) {
6108 wq_update_unbound_numa(wq, smp_processor_id(), true);
6109 WARN(init_rescuer(wq),
6110 "workqueue: failed to create early rescuer for %s",
6114 mutex_unlock(&wq_pool_mutex);
6116 /* create the initial workers */
6117 for_each_online_cpu(cpu) {
6118 for_each_cpu_worker_pool(pool, cpu) {
6119 pool->flags &= ~POOL_DISASSOCIATED;
6120 BUG_ON(!create_worker(pool));
6124 hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
6125 BUG_ON(!create_worker(pool));
6132 * Despite the naming, this is a no-op function which is here only for avoiding
6133 * link error. Since compile-time warning may fail to catch, we will need to
6134 * emit run-time warning from __flush_workqueue().
6136 void __warn_flushing_systemwide_wq(void) { }
6137 EXPORT_SYMBOL(__warn_flushing_systemwide_wq);