workqueue: Initialize unbound CPU pods later in the boot
[linux-2.6-block.git] / kernel / workqueue.c
CommitLineData
457c8996 1// SPDX-License-Identifier: GPL-2.0-only
1da177e4 2/*
c54fce6e 3 * kernel/workqueue.c - generic async execution with shared worker pool
1da177e4 4 *
c54fce6e 5 * Copyright (C) 2002 Ingo Molnar
1da177e4 6 *
c54fce6e
TH
7 * Derived from the taskqueue/keventd code by:
8 * David Woodhouse <dwmw2@infradead.org>
9 * Andrew Morton
10 * Kai Petzke <wpp@marie.physik.tu-berlin.de>
11 * Theodore Ts'o <tytso@mit.edu>
1da177e4 12 *
c54fce6e 13 * Made to use alloc_percpu by Christoph Lameter.
1da177e4 14 *
c54fce6e
TH
15 * Copyright (C) 2010 SUSE Linux Products GmbH
16 * Copyright (C) 2010 Tejun Heo <tj@kernel.org>
89ada679 17 *
c54fce6e
TH
18 * This is the generic async execution mechanism. Work items as are
19 * executed in process context. The worker pool is shared and
b11895c4
L
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.
c54fce6e 24 *
9a261491 25 * Please read Documentation/core-api/workqueue.rst for details.
1da177e4
LT
26 */
27
9984de1a 28#include <linux/export.h>
1da177e4
LT
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>
1fa44eca 39#include <linux/hardirq.h>
46934023 40#include <linux/mempolicy.h>
341a5958 41#include <linux/freezer.h>
d5abe669 42#include <linux/debug_locks.h>
4e6045f1 43#include <linux/lockdep.h>
c34056a3 44#include <linux/idr.h>
29c91e99 45#include <linux/jhash.h>
42f8570f 46#include <linux/hashtable.h>
76af4d93 47#include <linux/rculist.h>
bce90380 48#include <linux/nodemask.h>
4c16bd32 49#include <linux/moduleparam.h>
3d1cb205 50#include <linux/uaccess.h>
c98a9805 51#include <linux/sched/isolation.h>
cd2440d6 52#include <linux/sched/debug.h>
62635ea8 53#include <linux/nmi.h>
940d71c6 54#include <linux/kvm_para.h>
aa6fde93 55#include <linux/delay.h>
e22bee78 56
ea138446 57#include "workqueue_internal.h"
1da177e4 58
c8e55f36 59enum {
24647570
TH
60 /*
61 * worker_pool flags
bc2ae0f5 62 *
24647570 63 * A bound pool is either associated or disassociated with its CPU.
bc2ae0f5
TH
64 * While associated (!DISASSOCIATED), all workers are bound to the
65 * CPU and none has %WORKER_UNBOUND set and concurrency management
66 * is in effect.
67 *
68 * While DISASSOCIATED, the cpu may be offline and all workers have
69 * %WORKER_UNBOUND set and concurrency management disabled, and may
24647570 70 * be executing on any CPU. The pool behaves as an unbound one.
bc2ae0f5 71 *
bc3a1afc 72 * Note that DISASSOCIATED should be flipped only while holding
1258fae7 73 * wq_pool_attach_mutex to avoid changing binding state while
4736cbf7 74 * worker_attach_to_pool() is in progress.
bc2ae0f5 75 */
692b4825 76 POOL_MANAGER_ACTIVE = 1 << 0, /* being managed */
24647570 77 POOL_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
db7bccf4 78
c8e55f36 79 /* worker flags */
c8e55f36
TH
80 WORKER_DIE = 1 << 1, /* die die die */
81 WORKER_IDLE = 1 << 2, /* is idle */
e22bee78 82 WORKER_PREP = 1 << 3, /* preparing to run works */
fb0e7beb 83 WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
f3421797 84 WORKER_UNBOUND = 1 << 7, /* worker is unbound */
a9ab775b 85 WORKER_REBOUND = 1 << 8, /* worker was rebound */
e22bee78 86
a9ab775b
TH
87 WORKER_NOT_RUNNING = WORKER_PREP | WORKER_CPU_INTENSIVE |
88 WORKER_UNBOUND | WORKER_REBOUND,
db7bccf4 89
e34cdddb 90 NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */
4ce62e9e 91
29c91e99 92 UNBOUND_POOL_HASH_ORDER = 6, /* hashed by pool->attrs */
c8e55f36 93 BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
db7bccf4 94
e22bee78
TH
95 MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
96 IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
97
3233cdbd
TH
98 MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
99 /* call for help after 10ms
100 (min two ticks) */
e22bee78
TH
101 MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
102 CREATE_COOLDOWN = HZ, /* time to breath after fail */
e22bee78
TH
103
104 /*
105 * Rescue workers are used only on emergencies and shared by
8698a745 106 * all cpus. Give MIN_NICE.
e22bee78 107 */
8698a745
DY
108 RESCUER_NICE_LEVEL = MIN_NICE,
109 HIGHPRI_NICE_LEVEL = MIN_NICE,
ecf6881f
TH
110
111 WQ_NAME_LEN = 24,
c8e55f36 112};
1da177e4
LT
113
114/*
4690c4ab
TH
115 * Structure fields follow one of the following exclusion rules.
116 *
e41e704b
TH
117 * I: Modifiable by initialization/destruction paths and read-only for
118 * everyone else.
4690c4ab 119 *
e22bee78
TH
120 * P: Preemption protected. Disabling preemption is enough and should
121 * only be modified and accessed from the local cpu.
122 *
d565ed63 123 * L: pool->lock protected. Access with pool->lock held.
4690c4ab 124 *
bdf8b9bf
TH
125 * K: Only modified by worker while holding pool->lock. Can be safely read by
126 * self, while holding pool->lock or from IRQ context if %current is the
127 * kworker.
128 *
129 * S: Only modified by worker self.
130 *
1258fae7 131 * A: wq_pool_attach_mutex protected.
822d8405 132 *
68e13a67 133 * PL: wq_pool_mutex protected.
5bcab335 134 *
24acfb71 135 * PR: wq_pool_mutex protected for writes. RCU protected for reads.
76af4d93 136 *
5b95e1af
LJ
137 * PW: wq_pool_mutex and wq->mutex protected for writes. Either for reads.
138 *
139 * PWR: wq_pool_mutex and wq->mutex protected for writes. Either or
24acfb71 140 * RCU for reads.
5b95e1af 141 *
3c25a55d
LJ
142 * WQ: wq->mutex protected.
143 *
24acfb71 144 * WR: wq->mutex protected for writes. RCU protected for reads.
2e109a28
TH
145 *
146 * MD: wq_mayday_lock protected.
cd2440d6
PM
147 *
148 * WD: Used internally by the watchdog.
1da177e4 149 */
1da177e4 150
2eaebdb3 151/* struct worker is defined in workqueue_internal.h */
c34056a3 152
bd7bdd43 153struct worker_pool {
a9b8a985 154 raw_spinlock_t lock; /* the pool lock */
d84ff051 155 int cpu; /* I: the associated cpu */
f3f90ad4 156 int node; /* I: the associated node ID */
9daf9e67 157 int id; /* I: pool ID */
bc8b50c2 158 unsigned int flags; /* L: flags */
bd7bdd43 159
82607adc 160 unsigned long watchdog_ts; /* L: watchdog timestamp */
cd2440d6 161 bool cpu_stall; /* WD: stalled cpu bound pool */
82607adc 162
bc35f7ef
LJ
163 /*
164 * The counter is incremented in a process context on the associated CPU
165 * w/ preemption disabled, and decremented or reset in the same context
166 * but w/ pool->lock held. The readers grab pool->lock and are
167 * guaranteed to see if the counter reached zero.
168 */
169 int nr_running;
84f91c62 170
bd7bdd43 171 struct list_head worklist; /* L: list of pending works */
ea1abd61 172
5826cc8f
LJ
173 int nr_workers; /* L: total number of workers */
174 int nr_idle; /* L: currently idle workers */
bd7bdd43 175
2c1f1a91 176 struct list_head idle_list; /* L: list of idle workers */
bd7bdd43 177 struct timer_list idle_timer; /* L: worker idle timeout */
3f959aa3
VS
178 struct work_struct idle_cull_work; /* L: worker idle cleanup */
179
180 struct timer_list mayday_timer; /* L: SOS timer for workers */
bd7bdd43 181
c5aa87bb 182 /* a workers is either on busy_hash or idle_list, or the manager */
c9e7cf27
TH
183 DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
184 /* L: hash of busy workers */
185
2607d7a6 186 struct worker *manager; /* L: purely informational */
92f9c5c4 187 struct list_head workers; /* A: attached workers */
e02b9312 188 struct list_head dying_workers; /* A: workers about to die */
60f5a4bc 189 struct completion *detach_completion; /* all workers detached */
e19e397a 190
7cda9aae 191 struct ida worker_ida; /* worker IDs for task name */
e19e397a 192
7a4e344c 193 struct workqueue_attrs *attrs; /* I: worker attributes */
68e13a67
LJ
194 struct hlist_node hash_node; /* PL: unbound_pool_hash node */
195 int refcnt; /* PL: refcnt for unbound pools */
7a4e344c 196
29c91e99 197 /*
24acfb71 198 * Destruction of pool is RCU protected to allow dereferences
29c91e99
TH
199 * from get_work_pool().
200 */
201 struct rcu_head rcu;
84f91c62 202};
8b03ae3c 203
725e8ec5
TH
204/*
205 * Per-pool_workqueue statistics. These can be monitored using
206 * tools/workqueue/wq_monitor.py.
207 */
208enum pool_workqueue_stats {
209 PWQ_STAT_STARTED, /* work items started execution */
210 PWQ_STAT_COMPLETED, /* work items completed execution */
8a1dd1e5 211 PWQ_STAT_CPU_TIME, /* total CPU time consumed */
616db877 212 PWQ_STAT_CPU_INTENSIVE, /* wq_cpu_intensive_thresh_us violations */
725e8ec5
TH
213 PWQ_STAT_CM_WAKEUP, /* concurrency-management worker wakeups */
214 PWQ_STAT_MAYDAY, /* maydays to rescuer */
215 PWQ_STAT_RESCUED, /* linked work items executed by rescuer */
216
217 PWQ_NR_STATS,
218};
219
1da177e4 220/*
112202d9
TH
221 * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
222 * of work_struct->data are used for flags and the remaining high bits
223 * point to the pwq; thus, pwqs need to be aligned at two's power of the
224 * number of flag bits.
1da177e4 225 */
112202d9 226struct pool_workqueue {
bd7bdd43 227 struct worker_pool *pool; /* I: the associated pool */
4690c4ab 228 struct workqueue_struct *wq; /* I: the owning workqueue */
73f53c4a
TH
229 int work_color; /* L: current color */
230 int flush_color; /* L: flushing color */
8864b4e5 231 int refcnt; /* L: reference count */
73f53c4a
TH
232 int nr_in_flight[WORK_NR_COLORS];
233 /* L: nr of in_flight works */
018f3a13
LJ
234
235 /*
236 * nr_active management and WORK_STRUCT_INACTIVE:
237 *
238 * When pwq->nr_active >= max_active, new work item is queued to
239 * pwq->inactive_works instead of pool->worklist and marked with
240 * WORK_STRUCT_INACTIVE.
241 *
242 * All work items marked with WORK_STRUCT_INACTIVE do not participate
243 * in pwq->nr_active and all work items in pwq->inactive_works are
244 * marked with WORK_STRUCT_INACTIVE. But not all WORK_STRUCT_INACTIVE
245 * work items are in pwq->inactive_works. Some of them are ready to
246 * run in pool->worklist or worker->scheduled. Those work itmes are
247 * only struct wq_barrier which is used for flush_work() and should
248 * not participate in pwq->nr_active. For non-barrier work item, it
249 * is marked with WORK_STRUCT_INACTIVE iff it is in pwq->inactive_works.
250 */
1e19ffc6 251 int nr_active; /* L: nr of active works */
a0a1a5fd 252 int max_active; /* L: max active works */
f97a4a1a 253 struct list_head inactive_works; /* L: inactive works */
3c25a55d 254 struct list_head pwqs_node; /* WR: node on wq->pwqs */
2e109a28 255 struct list_head mayday_node; /* MD: node on wq->maydays */
8864b4e5 256
725e8ec5
TH
257 u64 stats[PWQ_NR_STATS];
258
8864b4e5 259 /*
967b494e 260 * Release of unbound pwq is punted to a kthread_worker. See put_pwq()
687a9aa5
TH
261 * and pwq_release_workfn() for details. pool_workqueue itself is also
262 * RCU protected so that the first pwq can be determined without
967b494e 263 * grabbing wq->mutex.
8864b4e5 264 */
687a9aa5 265 struct kthread_work release_work;
8864b4e5 266 struct rcu_head rcu;
e904e6c2 267} __aligned(1 << WORK_STRUCT_FLAG_BITS);
1da177e4 268
73f53c4a
TH
269/*
270 * Structure used to wait for workqueue flush.
271 */
272struct wq_flusher {
3c25a55d
LJ
273 struct list_head list; /* WQ: list of flushers */
274 int flush_color; /* WQ: flush color waiting for */
73f53c4a
TH
275 struct completion done; /* flush completion */
276};
277
226223ab
TH
278struct wq_device;
279
1da177e4 280/*
c5aa87bb
TH
281 * The externally visible workqueue. It relays the issued work items to
282 * the appropriate worker_pool through its pool_workqueues.
1da177e4
LT
283 */
284struct workqueue_struct {
3c25a55d 285 struct list_head pwqs; /* WR: all pwqs of this wq */
e2dca7ad 286 struct list_head list; /* PR: list of all workqueues */
73f53c4a 287
3c25a55d
LJ
288 struct mutex mutex; /* protects this wq */
289 int work_color; /* WQ: current work color */
290 int flush_color; /* WQ: current flush color */
112202d9 291 atomic_t nr_pwqs_to_flush; /* flush in progress */
3c25a55d
LJ
292 struct wq_flusher *first_flusher; /* WQ: first flusher */
293 struct list_head flusher_queue; /* WQ: flush waiters */
294 struct list_head flusher_overflow; /* WQ: flush overflow list */
73f53c4a 295
2e109a28 296 struct list_head maydays; /* MD: pwqs requesting rescue */
30ae2fc0 297 struct worker *rescuer; /* MD: rescue worker */
e22bee78 298
87fc741e 299 int nr_drainers; /* WQ: drain in progress */
a357fc03 300 int saved_max_active; /* WQ: saved pwq max_active */
226223ab 301
5b95e1af
LJ
302 struct workqueue_attrs *unbound_attrs; /* PW: only for unbound wqs */
303 struct pool_workqueue *dfl_pwq; /* PW: only for unbound wqs */
6029a918 304
226223ab
TH
305#ifdef CONFIG_SYSFS
306 struct wq_device *wq_dev; /* I: for sysfs interface */
307#endif
4e6045f1 308#ifdef CONFIG_LOCKDEP
669de8bd
BVA
309 char *lock_name;
310 struct lock_class_key key;
4690c4ab 311 struct lockdep_map lockdep_map;
4e6045f1 312#endif
ecf6881f 313 char name[WQ_NAME_LEN]; /* I: workqueue name */
2728fd2f 314
e2dca7ad 315 /*
24acfb71
TG
316 * Destruction of workqueue_struct is RCU protected to allow walking
317 * the workqueues list without grabbing wq_pool_mutex.
e2dca7ad
TH
318 * This is used to dump all workqueues from sysrq.
319 */
320 struct rcu_head rcu;
321
2728fd2f
TH
322 /* hot fields used during command issue, aligned to cacheline */
323 unsigned int flags ____cacheline_aligned; /* WQ: WQ_* flags */
636b927e 324 struct pool_workqueue __percpu __rcu **cpu_pwq; /* I: per-cpu pwqs */
1da177e4
LT
325};
326
e904e6c2
TH
327static struct kmem_cache *pwq_cache;
328
fef59c9c 329static cpumask_var_t *wq_pod_cpus; /* possible CPUs of each node */
bce90380 330
616db877
TH
331/*
332 * Per-cpu work items which run for longer than the following threshold are
333 * automatically considered CPU intensive and excluded from concurrency
334 * management to prevent them from noticeably delaying other per-cpu work items.
aa6fde93
TH
335 * ULONG_MAX indicates that the user hasn't overridden it with a boot parameter.
336 * The actual value is initialized in wq_cpu_intensive_thresh_init().
616db877 337 */
aa6fde93 338static unsigned long wq_cpu_intensive_thresh_us = ULONG_MAX;
616db877
TH
339module_param_named(cpu_intensive_thresh_us, wq_cpu_intensive_thresh_us, ulong, 0644);
340
cee22a15 341/* see the comment above the definition of WQ_POWER_EFFICIENT */
552f530c 342static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
cee22a15
VK
343module_param_named(power_efficient, wq_power_efficient, bool, 0444);
344
863b710b 345static bool wq_online; /* can kworkers be created yet? */
3347fa09 346
fef59c9c 347static bool wq_pod_enabled; /* unbound CPU pod affinity enabled */
bce90380 348
fef59c9c
TH
349/* buf for wq_update_unbound_pod_attrs(), protected by CPU hotplug exclusion */
350static struct workqueue_attrs *wq_update_pod_attrs_buf;
4c16bd32 351
68e13a67 352static DEFINE_MUTEX(wq_pool_mutex); /* protects pools and workqueues list */
1258fae7 353static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
a9b8a985 354static DEFINE_RAW_SPINLOCK(wq_mayday_lock); /* protects wq->maydays list */
d8bb65ab
SAS
355/* wait for manager to go away */
356static struct rcuwait manager_wait = __RCUWAIT_INITIALIZER(manager_wait);
5bcab335 357
e2dca7ad 358static LIST_HEAD(workqueues); /* PR: list of all workqueues */
68e13a67 359static bool workqueue_freezing; /* PL: have wqs started freezing? */
7d19c5ce 360
99c621ef 361/* PL&A: allowable cpus for unbound wqs and work items */
ef557180
MG
362static cpumask_var_t wq_unbound_cpumask;
363
ace3c549 364/* for further constrain wq_unbound_cpumask by cmdline parameter*/
365static struct cpumask wq_cmdline_cpumask __initdata;
366
ef557180
MG
367/* CPU where unbound work was last round robin scheduled from this CPU */
368static DEFINE_PER_CPU(int, wq_rr_cpu_last);
b05a7928 369
f303fccb
TH
370/*
371 * Local execution of unbound work items is no longer guaranteed. The
372 * following always forces round-robin CPU selection on unbound work items
373 * to uncover usages which depend on it.
374 */
375#ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
376static bool wq_debug_force_rr_cpu = true;
377#else
378static bool wq_debug_force_rr_cpu = false;
379#endif
380module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
381
7d19c5ce 382/* the per-cpu worker pools */
25528213 383static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools);
7d19c5ce 384
68e13a67 385static DEFINE_IDR(worker_pool_idr); /* PR: idr of all pools */
7d19c5ce 386
68e13a67 387/* PL: hash of all unbound pools keyed by pool->attrs */
29c91e99
TH
388static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
389
c5aa87bb 390/* I: attributes used when instantiating standard unbound pools on demand */
29c91e99
TH
391static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
392
8a2b7538
TH
393/* I: attributes used when instantiating ordered pools on demand */
394static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
395
967b494e
TH
396/*
397 * I: kthread_worker to release pwq's. pwq release needs to be bounced to a
398 * process context while holding a pool lock. Bounce to a dedicated kthread
399 * worker to avoid A-A deadlocks.
400 */
401static struct kthread_worker *pwq_release_worker;
402
d320c038 403struct workqueue_struct *system_wq __read_mostly;
ad7b1f84 404EXPORT_SYMBOL(system_wq);
044c782c 405struct workqueue_struct *system_highpri_wq __read_mostly;
1aabe902 406EXPORT_SYMBOL_GPL(system_highpri_wq);
044c782c 407struct workqueue_struct *system_long_wq __read_mostly;
d320c038 408EXPORT_SYMBOL_GPL(system_long_wq);
044c782c 409struct workqueue_struct *system_unbound_wq __read_mostly;
f3421797 410EXPORT_SYMBOL_GPL(system_unbound_wq);
044c782c 411struct workqueue_struct *system_freezable_wq __read_mostly;
24d51add 412EXPORT_SYMBOL_GPL(system_freezable_wq);
0668106c
VK
413struct workqueue_struct *system_power_efficient_wq __read_mostly;
414EXPORT_SYMBOL_GPL(system_power_efficient_wq);
415struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
416EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
d320c038 417
7d19c5ce 418static int worker_thread(void *__worker);
6ba94429 419static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
c29eb853 420static void show_pwq(struct pool_workqueue *pwq);
55df0933 421static void show_one_worker_pool(struct worker_pool *pool);
7d19c5ce 422
97bd2347
TH
423#define CREATE_TRACE_POINTS
424#include <trace/events/workqueue.h>
425
68e13a67 426#define assert_rcu_or_pool_mutex() \
24acfb71 427 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
f78f5b90 428 !lockdep_is_held(&wq_pool_mutex), \
24acfb71 429 "RCU or wq_pool_mutex should be held")
5bcab335 430
5b95e1af 431#define assert_rcu_or_wq_mutex_or_pool_mutex(wq) \
24acfb71 432 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
f78f5b90
PM
433 !lockdep_is_held(&wq->mutex) && \
434 !lockdep_is_held(&wq_pool_mutex), \
24acfb71 435 "RCU, wq->mutex or wq_pool_mutex should be held")
5b95e1af 436
f02ae73a
TH
437#define for_each_cpu_worker_pool(pool, cpu) \
438 for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
439 (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
7a62c2c8 440 (pool)++)
4ce62e9e 441
17116969
TH
442/**
443 * for_each_pool - iterate through all worker_pools in the system
444 * @pool: iteration cursor
611c92a0 445 * @pi: integer used for iteration
fa1b54e6 446 *
24acfb71 447 * This must be called either with wq_pool_mutex held or RCU read
68e13a67
LJ
448 * locked. If the pool needs to be used beyond the locking in effect, the
449 * caller is responsible for guaranteeing that the pool stays online.
fa1b54e6
TH
450 *
451 * The if/else clause exists only for the lockdep assertion and can be
452 * ignored.
17116969 453 */
611c92a0
TH
454#define for_each_pool(pool, pi) \
455 idr_for_each_entry(&worker_pool_idr, pool, pi) \
68e13a67 456 if (({ assert_rcu_or_pool_mutex(); false; })) { } \
fa1b54e6 457 else
17116969 458
822d8405
TH
459/**
460 * for_each_pool_worker - iterate through all workers of a worker_pool
461 * @worker: iteration cursor
822d8405
TH
462 * @pool: worker_pool to iterate workers of
463 *
1258fae7 464 * This must be called with wq_pool_attach_mutex.
822d8405
TH
465 *
466 * The if/else clause exists only for the lockdep assertion and can be
467 * ignored.
468 */
da028469
LJ
469#define for_each_pool_worker(worker, pool) \
470 list_for_each_entry((worker), &(pool)->workers, node) \
1258fae7 471 if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
822d8405
TH
472 else
473
49e3cf44
TH
474/**
475 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
476 * @pwq: iteration cursor
477 * @wq: the target workqueue
76af4d93 478 *
24acfb71 479 * This must be called either with wq->mutex held or RCU read locked.
794b18bc
TH
480 * If the pwq needs to be used beyond the locking in effect, the caller is
481 * responsible for guaranteeing that the pwq stays online.
76af4d93
TH
482 *
483 * The if/else clause exists only for the lockdep assertion and can be
484 * ignored.
49e3cf44
TH
485 */
486#define for_each_pwq(pwq, wq) \
49e9d1a9 487 list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node, \
5a644662 488 lockdep_is_held(&(wq->mutex)))
f3421797 489
dc186ad7
TG
490#ifdef CONFIG_DEBUG_OBJECTS_WORK
491
f9e62f31 492static const struct debug_obj_descr work_debug_descr;
dc186ad7 493
99777288
SG
494static void *work_debug_hint(void *addr)
495{
496 return ((struct work_struct *) addr)->func;
497}
498
b9fdac7f
DC
499static bool work_is_static_object(void *addr)
500{
501 struct work_struct *work = addr;
502
503 return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
504}
505
dc186ad7
TG
506/*
507 * fixup_init is called when:
508 * - an active object is initialized
509 */
02a982a6 510static bool work_fixup_init(void *addr, enum debug_obj_state state)
dc186ad7
TG
511{
512 struct work_struct *work = addr;
513
514 switch (state) {
515 case ODEBUG_STATE_ACTIVE:
516 cancel_work_sync(work);
517 debug_object_init(work, &work_debug_descr);
02a982a6 518 return true;
dc186ad7 519 default:
02a982a6 520 return false;
dc186ad7
TG
521 }
522}
523
dc186ad7
TG
524/*
525 * fixup_free is called when:
526 * - an active object is freed
527 */
02a982a6 528static bool work_fixup_free(void *addr, enum debug_obj_state state)
dc186ad7
TG
529{
530 struct work_struct *work = addr;
531
532 switch (state) {
533 case ODEBUG_STATE_ACTIVE:
534 cancel_work_sync(work);
535 debug_object_free(work, &work_debug_descr);
02a982a6 536 return true;
dc186ad7 537 default:
02a982a6 538 return false;
dc186ad7
TG
539 }
540}
541
f9e62f31 542static const struct debug_obj_descr work_debug_descr = {
dc186ad7 543 .name = "work_struct",
99777288 544 .debug_hint = work_debug_hint,
b9fdac7f 545 .is_static_object = work_is_static_object,
dc186ad7 546 .fixup_init = work_fixup_init,
dc186ad7
TG
547 .fixup_free = work_fixup_free,
548};
549
550static inline void debug_work_activate(struct work_struct *work)
551{
552 debug_object_activate(work, &work_debug_descr);
553}
554
555static inline void debug_work_deactivate(struct work_struct *work)
556{
557 debug_object_deactivate(work, &work_debug_descr);
558}
559
560void __init_work(struct work_struct *work, int onstack)
561{
562 if (onstack)
563 debug_object_init_on_stack(work, &work_debug_descr);
564 else
565 debug_object_init(work, &work_debug_descr);
566}
567EXPORT_SYMBOL_GPL(__init_work);
568
569void destroy_work_on_stack(struct work_struct *work)
570{
571 debug_object_free(work, &work_debug_descr);
572}
573EXPORT_SYMBOL_GPL(destroy_work_on_stack);
574
ea2e64f2
TG
575void destroy_delayed_work_on_stack(struct delayed_work *work)
576{
577 destroy_timer_on_stack(&work->timer);
578 debug_object_free(&work->work, &work_debug_descr);
579}
580EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
581
dc186ad7
TG
582#else
583static inline void debug_work_activate(struct work_struct *work) { }
584static inline void debug_work_deactivate(struct work_struct *work) { }
585#endif
586
4e8b22bd 587/**
67dc8325 588 * worker_pool_assign_id - allocate ID and assign it to @pool
4e8b22bd
LB
589 * @pool: the pool pointer of interest
590 *
591 * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
592 * successfully, -errno on failure.
593 */
9daf9e67
TH
594static int worker_pool_assign_id(struct worker_pool *pool)
595{
596 int ret;
597
68e13a67 598 lockdep_assert_held(&wq_pool_mutex);
5bcab335 599
4e8b22bd
LB
600 ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
601 GFP_KERNEL);
229641a6 602 if (ret >= 0) {
e68035fb 603 pool->id = ret;
229641a6
TH
604 return 0;
605 }
fa1b54e6 606 return ret;
7c3eed5c
TH
607}
608
73f53c4a
TH
609static unsigned int work_color_to_flags(int color)
610{
611 return color << WORK_STRUCT_COLOR_SHIFT;
612}
613
c4560c2c 614static int get_work_color(unsigned long work_data)
73f53c4a 615{
c4560c2c 616 return (work_data >> WORK_STRUCT_COLOR_SHIFT) &
73f53c4a
TH
617 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
618}
619
620static int work_next_color(int color)
621{
622 return (color + 1) % WORK_NR_COLORS;
623}
1da177e4 624
14441960 625/*
112202d9
TH
626 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
627 * contain the pointer to the queued pwq. Once execution starts, the flag
7c3eed5c 628 * is cleared and the high bits contain OFFQ flags and pool ID.
7a22ad75 629 *
112202d9
TH
630 * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
631 * and clear_work_data() can be used to set the pwq, pool or clear
bbb68dfa
TH
632 * work->data. These functions should only be called while the work is
633 * owned - ie. while the PENDING bit is set.
7a22ad75 634 *
112202d9 635 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
7c3eed5c 636 * corresponding to a work. Pool is available once the work has been
112202d9 637 * queued anywhere after initialization until it is sync canceled. pwq is
7c3eed5c 638 * available only while the work item is queued.
7a22ad75 639 *
bbb68dfa
TH
640 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
641 * canceled. While being canceled, a work item may have its PENDING set
642 * but stay off timer and worklist for arbitrarily long and nobody should
643 * try to steal the PENDING bit.
14441960 644 */
7a22ad75
TH
645static inline void set_work_data(struct work_struct *work, unsigned long data,
646 unsigned long flags)
365970a1 647{
6183c009 648 WARN_ON_ONCE(!work_pending(work));
7a22ad75
TH
649 atomic_long_set(&work->data, data | flags | work_static(work));
650}
365970a1 651
112202d9 652static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
7a22ad75
TH
653 unsigned long extra_flags)
654{
112202d9
TH
655 set_work_data(work, (unsigned long)pwq,
656 WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
365970a1
DH
657}
658
4468a00f
LJ
659static void set_work_pool_and_keep_pending(struct work_struct *work,
660 int pool_id)
661{
662 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
663 WORK_STRUCT_PENDING);
664}
665
7c3eed5c
TH
666static void set_work_pool_and_clear_pending(struct work_struct *work,
667 int pool_id)
7a22ad75 668{
23657bb1
TH
669 /*
670 * The following wmb is paired with the implied mb in
671 * test_and_set_bit(PENDING) and ensures all updates to @work made
672 * here are visible to and precede any updates by the next PENDING
673 * owner.
674 */
675 smp_wmb();
7c3eed5c 676 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
346c09f8
RP
677 /*
678 * The following mb guarantees that previous clear of a PENDING bit
679 * will not be reordered with any speculative LOADS or STORES from
680 * work->current_func, which is executed afterwards. This possible
8bdc6201 681 * reordering can lead to a missed execution on attempt to queue
346c09f8
RP
682 * the same @work. E.g. consider this case:
683 *
684 * CPU#0 CPU#1
685 * ---------------------------- --------------------------------
686 *
687 * 1 STORE event_indicated
688 * 2 queue_work_on() {
689 * 3 test_and_set_bit(PENDING)
690 * 4 } set_..._and_clear_pending() {
691 * 5 set_work_data() # clear bit
692 * 6 smp_mb()
693 * 7 work->current_func() {
694 * 8 LOAD event_indicated
695 * }
696 *
697 * Without an explicit full barrier speculative LOAD on line 8 can
698 * be executed before CPU#0 does STORE on line 1. If that happens,
699 * CPU#0 observes the PENDING bit is still set and new execution of
700 * a @work is not queued in a hope, that CPU#1 will eventually
701 * finish the queued @work. Meanwhile CPU#1 does not see
702 * event_indicated is set, because speculative LOAD was executed
703 * before actual STORE.
704 */
705 smp_mb();
7a22ad75 706}
f756d5e2 707
7a22ad75 708static void clear_work_data(struct work_struct *work)
1da177e4 709{
7c3eed5c
TH
710 smp_wmb(); /* see set_work_pool_and_clear_pending() */
711 set_work_data(work, WORK_STRUCT_NO_POOL, 0);
1da177e4
LT
712}
713
afa4bb77
LT
714static inline struct pool_workqueue *work_struct_pwq(unsigned long data)
715{
716 return (struct pool_workqueue *)(data & WORK_STRUCT_WQ_DATA_MASK);
717}
718
112202d9 719static struct pool_workqueue *get_work_pwq(struct work_struct *work)
b1f4ec17 720{
e120153d 721 unsigned long data = atomic_long_read(&work->data);
7a22ad75 722
112202d9 723 if (data & WORK_STRUCT_PWQ)
afa4bb77 724 return work_struct_pwq(data);
e120153d
TH
725 else
726 return NULL;
4d707b9f
ON
727}
728
7c3eed5c
TH
729/**
730 * get_work_pool - return the worker_pool a given work was associated with
731 * @work: the work item of interest
732 *
68e13a67 733 * Pools are created and destroyed under wq_pool_mutex, and allows read
24acfb71
TG
734 * access under RCU read lock. As such, this function should be
735 * called under wq_pool_mutex or inside of a rcu_read_lock() region.
fa1b54e6
TH
736 *
737 * All fields of the returned pool are accessible as long as the above
738 * mentioned locking is in effect. If the returned pool needs to be used
739 * beyond the critical section, the caller is responsible for ensuring the
740 * returned pool is and stays online.
d185af30
YB
741 *
742 * Return: The worker_pool @work was last associated with. %NULL if none.
7c3eed5c
TH
743 */
744static struct worker_pool *get_work_pool(struct work_struct *work)
365970a1 745{
e120153d 746 unsigned long data = atomic_long_read(&work->data);
7c3eed5c 747 int pool_id;
7a22ad75 748
68e13a67 749 assert_rcu_or_pool_mutex();
fa1b54e6 750
112202d9 751 if (data & WORK_STRUCT_PWQ)
afa4bb77 752 return work_struct_pwq(data)->pool;
7a22ad75 753
7c3eed5c
TH
754 pool_id = data >> WORK_OFFQ_POOL_SHIFT;
755 if (pool_id == WORK_OFFQ_POOL_NONE)
7a22ad75
TH
756 return NULL;
757
fa1b54e6 758 return idr_find(&worker_pool_idr, pool_id);
7c3eed5c
TH
759}
760
761/**
762 * get_work_pool_id - return the worker pool ID a given work is associated with
763 * @work: the work item of interest
764 *
d185af30 765 * Return: The worker_pool ID @work was last associated with.
7c3eed5c
TH
766 * %WORK_OFFQ_POOL_NONE if none.
767 */
768static int get_work_pool_id(struct work_struct *work)
769{
54d5b7d0
LJ
770 unsigned long data = atomic_long_read(&work->data);
771
112202d9 772 if (data & WORK_STRUCT_PWQ)
afa4bb77 773 return work_struct_pwq(data)->pool->id;
7c3eed5c 774
54d5b7d0 775 return data >> WORK_OFFQ_POOL_SHIFT;
7c3eed5c
TH
776}
777
bbb68dfa
TH
778static void mark_work_canceling(struct work_struct *work)
779{
7c3eed5c 780 unsigned long pool_id = get_work_pool_id(work);
bbb68dfa 781
7c3eed5c
TH
782 pool_id <<= WORK_OFFQ_POOL_SHIFT;
783 set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
bbb68dfa
TH
784}
785
786static bool work_is_canceling(struct work_struct *work)
787{
788 unsigned long data = atomic_long_read(&work->data);
789
112202d9 790 return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
bbb68dfa
TH
791}
792
e22bee78 793/*
3270476a
TH
794 * Policy functions. These define the policies on how the global worker
795 * pools are managed. Unless noted otherwise, these functions assume that
d565ed63 796 * they're being called with pool->lock held.
e22bee78
TH
797 */
798
63d95a91 799static bool __need_more_worker(struct worker_pool *pool)
a848e3b6 800{
bc35f7ef 801 return !pool->nr_running;
a848e3b6
ON
802}
803
4594bf15 804/*
e22bee78
TH
805 * Need to wake up a worker? Called from anything but currently
806 * running workers.
974271c4
TH
807 *
808 * Note that, because unbound workers never contribute to nr_running, this
706026c2 809 * function will always return %true for unbound pools as long as the
974271c4 810 * worklist isn't empty.
4594bf15 811 */
63d95a91 812static bool need_more_worker(struct worker_pool *pool)
365970a1 813{
63d95a91 814 return !list_empty(&pool->worklist) && __need_more_worker(pool);
e22bee78 815}
4594bf15 816
e22bee78 817/* Can I start working? Called from busy but !running workers. */
63d95a91 818static bool may_start_working(struct worker_pool *pool)
e22bee78 819{
63d95a91 820 return pool->nr_idle;
e22bee78
TH
821}
822
823/* Do I need to keep working? Called from currently running workers. */
63d95a91 824static bool keep_working(struct worker_pool *pool)
e22bee78 825{
bc35f7ef 826 return !list_empty(&pool->worklist) && (pool->nr_running <= 1);
e22bee78
TH
827}
828
829/* Do we need a new worker? Called from manager. */
63d95a91 830static bool need_to_create_worker(struct worker_pool *pool)
e22bee78 831{
63d95a91 832 return need_more_worker(pool) && !may_start_working(pool);
e22bee78 833}
365970a1 834
e22bee78 835/* Do we have too many workers and should some go away? */
63d95a91 836static bool too_many_workers(struct worker_pool *pool)
e22bee78 837{
692b4825 838 bool managing = pool->flags & POOL_MANAGER_ACTIVE;
63d95a91
TH
839 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
840 int nr_busy = pool->nr_workers - nr_idle;
e22bee78
TH
841
842 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
365970a1
DH
843}
844
c54d5046
TH
845/**
846 * worker_set_flags - set worker flags and adjust nr_running accordingly
847 * @worker: self
848 * @flags: flags to set
849 *
850 * Set @flags in @worker->flags and adjust nr_running accordingly.
c54d5046
TH
851 */
852static inline void worker_set_flags(struct worker *worker, unsigned int flags)
853{
854 struct worker_pool *pool = worker->pool;
855
bc8b50c2 856 lockdep_assert_held(&pool->lock);
c54d5046
TH
857
858 /* If transitioning into NOT_RUNNING, adjust nr_running. */
859 if ((flags & WORKER_NOT_RUNNING) &&
860 !(worker->flags & WORKER_NOT_RUNNING)) {
861 pool->nr_running--;
862 }
863
864 worker->flags |= flags;
865}
866
867/**
868 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
869 * @worker: self
870 * @flags: flags to clear
871 *
872 * Clear @flags in @worker->flags and adjust nr_running accordingly.
c54d5046
TH
873 */
874static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
875{
876 struct worker_pool *pool = worker->pool;
877 unsigned int oflags = worker->flags;
878
bc8b50c2 879 lockdep_assert_held(&pool->lock);
c54d5046
TH
880
881 worker->flags &= ~flags;
882
883 /*
884 * If transitioning out of NOT_RUNNING, increment nr_running. Note
885 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
886 * of multiple flags, not a single flag.
887 */
888 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
889 if (!(worker->flags & WORKER_NOT_RUNNING))
890 pool->nr_running++;
891}
892
797e8345
TH
893/* Return the first idle worker. Called with pool->lock held. */
894static struct worker *first_idle_worker(struct worker_pool *pool)
895{
896 if (unlikely(list_empty(&pool->idle_list)))
897 return NULL;
898
899 return list_first_entry(&pool->idle_list, struct worker, entry);
900}
901
902/**
903 * worker_enter_idle - enter idle state
904 * @worker: worker which is entering idle state
905 *
906 * @worker is entering idle state. Update stats and idle timer if
907 * necessary.
908 *
909 * LOCKING:
910 * raw_spin_lock_irq(pool->lock).
911 */
912static void worker_enter_idle(struct worker *worker)
913{
914 struct worker_pool *pool = worker->pool;
915
916 if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
917 WARN_ON_ONCE(!list_empty(&worker->entry) &&
918 (worker->hentry.next || worker->hentry.pprev)))
919 return;
920
921 /* can't use worker_set_flags(), also called from create_worker() */
922 worker->flags |= WORKER_IDLE;
923 pool->nr_idle++;
924 worker->last_active = jiffies;
925
926 /* idle_list is LIFO */
927 list_add(&worker->entry, &pool->idle_list);
928
929 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
930 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
931
932 /* Sanity check nr_running. */
933 WARN_ON_ONCE(pool->nr_workers == pool->nr_idle && pool->nr_running);
934}
935
936/**
937 * worker_leave_idle - leave idle state
938 * @worker: worker which is leaving idle state
939 *
940 * @worker is leaving idle state. Update stats.
941 *
942 * LOCKING:
943 * raw_spin_lock_irq(pool->lock).
944 */
945static void worker_leave_idle(struct worker *worker)
946{
947 struct worker_pool *pool = worker->pool;
948
949 if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
950 return;
951 worker_clr_flags(worker, WORKER_IDLE);
952 pool->nr_idle--;
953 list_del_init(&worker->entry);
954}
955
956/**
957 * find_worker_executing_work - find worker which is executing a work
958 * @pool: pool of interest
959 * @work: work to find worker for
960 *
961 * Find a worker which is executing @work on @pool by searching
962 * @pool->busy_hash which is keyed by the address of @work. For a worker
963 * to match, its current execution should match the address of @work and
964 * its work function. This is to avoid unwanted dependency between
965 * unrelated work executions through a work item being recycled while still
966 * being executed.
967 *
968 * This is a bit tricky. A work item may be freed once its execution
969 * starts and nothing prevents the freed area from being recycled for
970 * another work item. If the same work item address ends up being reused
971 * before the original execution finishes, workqueue will identify the
972 * recycled work item as currently executing and make it wait until the
973 * current execution finishes, introducing an unwanted dependency.
974 *
975 * This function checks the work item address and work function to avoid
976 * false positives. Note that this isn't complete as one may construct a
977 * work function which can introduce dependency onto itself through a
978 * recycled work item. Well, if somebody wants to shoot oneself in the
979 * foot that badly, there's only so much we can do, and if such deadlock
980 * actually occurs, it should be easy to locate the culprit work function.
981 *
982 * CONTEXT:
983 * raw_spin_lock_irq(pool->lock).
984 *
985 * Return:
986 * Pointer to worker which is executing @work if found, %NULL
987 * otherwise.
988 */
989static struct worker *find_worker_executing_work(struct worker_pool *pool,
990 struct work_struct *work)
991{
992 struct worker *worker;
993
994 hash_for_each_possible(pool->busy_hash, worker, hentry,
995 (unsigned long)work)
996 if (worker->current_work == work &&
997 worker->current_func == work->func)
998 return worker;
999
1000 return NULL;
1001}
1002
1003/**
1004 * move_linked_works - move linked works to a list
1005 * @work: start of series of works to be scheduled
1006 * @head: target list to append @work to
1007 * @nextp: out parameter for nested worklist walking
1008 *
1009 * Schedule linked works starting from @work to @head. Work series to
1010 * be scheduled starts at @work and includes any consecutive work with
1011 * WORK_STRUCT_LINKED set in its predecessor.
1012 *
1013 * If @nextp is not NULL, it's updated to point to the next work of
1014 * the last scheduled work. This allows move_linked_works() to be
1015 * nested inside outer list_for_each_entry_safe().
1016 *
1017 * CONTEXT:
1018 * raw_spin_lock_irq(pool->lock).
1019 */
1020static void move_linked_works(struct work_struct *work, struct list_head *head,
1021 struct work_struct **nextp)
1022{
1023 struct work_struct *n;
1024
1025 /*
1026 * Linked worklist will always end before the end of the list,
1027 * use NULL for list head.
1028 */
1029 list_for_each_entry_safe_from(work, n, NULL, entry) {
1030 list_move_tail(&work->entry, head);
1031 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1032 break;
1033 }
1034
1035 /*
1036 * If we're already inside safe list traversal and have moved
1037 * multiple works to the scheduled queue, the next position
1038 * needs to be updated.
1039 */
1040 if (nextp)
1041 *nextp = n;
1042}
1043
1044/**
1045 * wake_up_worker - wake up an idle worker
1046 * @pool: worker pool to wake worker from
1047 *
1048 * Wake up the first idle worker of @pool.
1049 *
1050 * CONTEXT:
1051 * raw_spin_lock_irq(pool->lock).
1052 */
1053static void wake_up_worker(struct worker_pool *pool)
1054{
1055 struct worker *worker = first_idle_worker(pool);
1056
1057 if (likely(worker))
1058 wake_up_process(worker->task);
1059}
1060
63638450
TH
1061#ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
1062
1063/*
1064 * Concurrency-managed per-cpu work items that hog CPU for longer than
1065 * wq_cpu_intensive_thresh_us trigger the automatic CPU_INTENSIVE mechanism,
1066 * which prevents them from stalling other concurrency-managed work items. If a
1067 * work function keeps triggering this mechanism, it's likely that the work item
1068 * should be using an unbound workqueue instead.
1069 *
1070 * wq_cpu_intensive_report() tracks work functions which trigger such conditions
1071 * and report them so that they can be examined and converted to use unbound
1072 * workqueues as appropriate. To avoid flooding the console, each violating work
1073 * function is tracked and reported with exponential backoff.
1074 */
1075#define WCI_MAX_ENTS 128
1076
1077struct wci_ent {
1078 work_func_t func;
1079 atomic64_t cnt;
1080 struct hlist_node hash_node;
1081};
1082
1083static struct wci_ent wci_ents[WCI_MAX_ENTS];
1084static int wci_nr_ents;
1085static DEFINE_RAW_SPINLOCK(wci_lock);
1086static DEFINE_HASHTABLE(wci_hash, ilog2(WCI_MAX_ENTS));
1087
1088static struct wci_ent *wci_find_ent(work_func_t func)
1089{
1090 struct wci_ent *ent;
1091
1092 hash_for_each_possible_rcu(wci_hash, ent, hash_node,
1093 (unsigned long)func) {
1094 if (ent->func == func)
1095 return ent;
1096 }
1097 return NULL;
1098}
1099
1100static void wq_cpu_intensive_report(work_func_t func)
1101{
1102 struct wci_ent *ent;
1103
1104restart:
1105 ent = wci_find_ent(func);
1106 if (ent) {
1107 u64 cnt;
1108
1109 /*
1110 * Start reporting from the fourth time and back off
1111 * exponentially.
1112 */
1113 cnt = atomic64_inc_return_relaxed(&ent->cnt);
1114 if (cnt >= 4 && is_power_of_2(cnt))
1115 printk_deferred(KERN_WARNING "workqueue: %ps hogged CPU for >%luus %llu times, consider switching to WQ_UNBOUND\n",
1116 ent->func, wq_cpu_intensive_thresh_us,
1117 atomic64_read(&ent->cnt));
1118 return;
1119 }
1120
1121 /*
1122 * @func is a new violation. Allocate a new entry for it. If wcn_ents[]
1123 * is exhausted, something went really wrong and we probably made enough
1124 * noise already.
1125 */
1126 if (wci_nr_ents >= WCI_MAX_ENTS)
1127 return;
1128
1129 raw_spin_lock(&wci_lock);
1130
1131 if (wci_nr_ents >= WCI_MAX_ENTS) {
1132 raw_spin_unlock(&wci_lock);
1133 return;
1134 }
1135
1136 if (wci_find_ent(func)) {
1137 raw_spin_unlock(&wci_lock);
1138 goto restart;
1139 }
1140
1141 ent = &wci_ents[wci_nr_ents++];
1142 ent->func = func;
1143 atomic64_set(&ent->cnt, 1);
1144 hash_add_rcu(wci_hash, &ent->hash_node, (unsigned long)func);
1145
1146 raw_spin_unlock(&wci_lock);
1147}
1148
1149#else /* CONFIG_WQ_CPU_INTENSIVE_REPORT */
1150static void wq_cpu_intensive_report(work_func_t func) {}
1151#endif /* CONFIG_WQ_CPU_INTENSIVE_REPORT */
1152
d302f017 1153/**
6d25be57 1154 * wq_worker_running - a worker is running again
e22bee78 1155 * @task: task waking up
e22bee78 1156 *
6d25be57 1157 * This function is called when a worker returns from schedule()
e22bee78 1158 */
6d25be57 1159void wq_worker_running(struct task_struct *task)
e22bee78
TH
1160{
1161 struct worker *worker = kthread_data(task);
1162
c8f6219b 1163 if (!READ_ONCE(worker->sleeping))
6d25be57 1164 return;
07edfece
FW
1165
1166 /*
1167 * If preempted by unbind_workers() between the WORKER_NOT_RUNNING check
1168 * and the nr_running increment below, we may ruin the nr_running reset
1169 * and leave with an unexpected pool->nr_running == 1 on the newly unbound
1170 * pool. Protect against such race.
1171 */
1172 preempt_disable();
6d25be57 1173 if (!(worker->flags & WORKER_NOT_RUNNING))
bc35f7ef 1174 worker->pool->nr_running++;
07edfece 1175 preempt_enable();
616db877
TH
1176
1177 /*
1178 * CPU intensive auto-detection cares about how long a work item hogged
1179 * CPU without sleeping. Reset the starting timestamp on wakeup.
1180 */
1181 worker->current_at = worker->task->se.sum_exec_runtime;
1182
c8f6219b 1183 WRITE_ONCE(worker->sleeping, 0);
e22bee78
TH
1184}
1185
1186/**
1187 * wq_worker_sleeping - a worker is going to sleep
1188 * @task: task going to sleep
e22bee78 1189 *
6d25be57 1190 * This function is called from schedule() when a busy worker is
ccf45156 1191 * going to sleep.
e22bee78 1192 */
6d25be57 1193void wq_worker_sleeping(struct task_struct *task)
e22bee78 1194{
cc5bff38 1195 struct worker *worker = kthread_data(task);
111c225a 1196 struct worker_pool *pool;
e22bee78 1197
111c225a
TH
1198 /*
1199 * Rescuers, which may not have all the fields set up like normal
1200 * workers, also reach here, let's not access anything before
1201 * checking NOT_RUNNING.
1202 */
2d64672e 1203 if (worker->flags & WORKER_NOT_RUNNING)
6d25be57 1204 return;
e22bee78 1205
111c225a 1206 pool = worker->pool;
111c225a 1207
62849a96 1208 /* Return if preempted before wq_worker_running() was reached */
c8f6219b 1209 if (READ_ONCE(worker->sleeping))
6d25be57
TG
1210 return;
1211
c8f6219b 1212 WRITE_ONCE(worker->sleeping, 1);
a9b8a985 1213 raw_spin_lock_irq(&pool->lock);
e22bee78 1214
45c753f5
FW
1215 /*
1216 * Recheck in case unbind_workers() preempted us. We don't
1217 * want to decrement nr_running after the worker is unbound
1218 * and nr_running has been reset.
1219 */
1220 if (worker->flags & WORKER_NOT_RUNNING) {
1221 raw_spin_unlock_irq(&pool->lock);
1222 return;
1223 }
1224
bc35f7ef 1225 pool->nr_running--;
725e8ec5
TH
1226 if (need_more_worker(pool)) {
1227 worker->current_pwq->stats[PWQ_STAT_CM_WAKEUP]++;
cc5bff38 1228 wake_up_worker(pool);
725e8ec5 1229 }
a9b8a985 1230 raw_spin_unlock_irq(&pool->lock);
e22bee78
TH
1231}
1232
616db877
TH
1233/**
1234 * wq_worker_tick - a scheduler tick occurred while a kworker is running
1235 * @task: task currently running
1236 *
1237 * Called from scheduler_tick(). We're in the IRQ context and the current
1238 * worker's fields which follow the 'K' locking rule can be accessed safely.
1239 */
1240void wq_worker_tick(struct task_struct *task)
1241{
1242 struct worker *worker = kthread_data(task);
1243 struct pool_workqueue *pwq = worker->current_pwq;
1244 struct worker_pool *pool = worker->pool;
1245
1246 if (!pwq)
1247 return;
1248
8a1dd1e5
TH
1249 pwq->stats[PWQ_STAT_CPU_TIME] += TICK_USEC;
1250
18c8ae81
Z
1251 if (!wq_cpu_intensive_thresh_us)
1252 return;
1253
616db877
TH
1254 /*
1255 * If the current worker is concurrency managed and hogged the CPU for
1256 * longer than wq_cpu_intensive_thresh_us, it's automatically marked
1257 * CPU_INTENSIVE to avoid stalling other concurrency-managed work items.
c8f6219b
Z
1258 *
1259 * Set @worker->sleeping means that @worker is in the process of
1260 * switching out voluntarily and won't be contributing to
1261 * @pool->nr_running until it wakes up. As wq_worker_sleeping() also
1262 * decrements ->nr_running, setting CPU_INTENSIVE here can lead to
1263 * double decrements. The task is releasing the CPU anyway. Let's skip.
1264 * We probably want to make this prettier in the future.
616db877 1265 */
c8f6219b 1266 if ((worker->flags & WORKER_NOT_RUNNING) || READ_ONCE(worker->sleeping) ||
616db877
TH
1267 worker->task->se.sum_exec_runtime - worker->current_at <
1268 wq_cpu_intensive_thresh_us * NSEC_PER_USEC)
1269 return;
1270
1271 raw_spin_lock(&pool->lock);
1272
1273 worker_set_flags(worker, WORKER_CPU_INTENSIVE);
63638450 1274 wq_cpu_intensive_report(worker->current_func);
616db877
TH
1275 pwq->stats[PWQ_STAT_CPU_INTENSIVE]++;
1276
1277 if (need_more_worker(pool)) {
1278 pwq->stats[PWQ_STAT_CM_WAKEUP]++;
1279 wake_up_worker(pool);
1280 }
1281
1282 raw_spin_unlock(&pool->lock);
1283}
1284
1b69ac6b
JW
1285/**
1286 * wq_worker_last_func - retrieve worker's last work function
8194fe94 1287 * @task: Task to retrieve last work function of.
1b69ac6b
JW
1288 *
1289 * Determine the last function a worker executed. This is called from
1290 * the scheduler to get a worker's last known identity.
1291 *
1292 * CONTEXT:
a9b8a985 1293 * raw_spin_lock_irq(rq->lock)
1b69ac6b 1294 *
4b047002
JW
1295 * This function is called during schedule() when a kworker is going
1296 * to sleep. It's used by psi to identify aggregation workers during
1297 * dequeuing, to allow periodic aggregation to shut-off when that
1298 * worker is the last task in the system or cgroup to go to sleep.
1299 *
1300 * As this function doesn't involve any workqueue-related locking, it
1301 * only returns stable values when called from inside the scheduler's
1302 * queuing and dequeuing paths, when @task, which must be a kworker,
1303 * is guaranteed to not be processing any works.
1304 *
1b69ac6b
JW
1305 * Return:
1306 * The last work function %current executed as a worker, NULL if it
1307 * hasn't executed any work yet.
1308 */
1309work_func_t wq_worker_last_func(struct task_struct *task)
1310{
1311 struct worker *worker = kthread_data(task);
1312
1313 return worker->last_func;
1314}
1315
8864b4e5
TH
1316/**
1317 * get_pwq - get an extra reference on the specified pool_workqueue
1318 * @pwq: pool_workqueue to get
1319 *
1320 * Obtain an extra reference on @pwq. The caller should guarantee that
1321 * @pwq has positive refcnt and be holding the matching pool->lock.
1322 */
1323static void get_pwq(struct pool_workqueue *pwq)
1324{
1325 lockdep_assert_held(&pwq->pool->lock);
1326 WARN_ON_ONCE(pwq->refcnt <= 0);
1327 pwq->refcnt++;
1328}
1329
1330/**
1331 * put_pwq - put a pool_workqueue reference
1332 * @pwq: pool_workqueue to put
1333 *
1334 * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
1335 * destruction. The caller should be holding the matching pool->lock.
1336 */
1337static void put_pwq(struct pool_workqueue *pwq)
1338{
1339 lockdep_assert_held(&pwq->pool->lock);
1340 if (likely(--pwq->refcnt))
1341 return;
8864b4e5 1342 /*
967b494e
TH
1343 * @pwq can't be released under pool->lock, bounce to a dedicated
1344 * kthread_worker to avoid A-A deadlocks.
8864b4e5 1345 */
687a9aa5 1346 kthread_queue_work(pwq_release_worker, &pwq->release_work);
8864b4e5
TH
1347}
1348
dce90d47
TH
1349/**
1350 * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1351 * @pwq: pool_workqueue to put (can be %NULL)
1352 *
1353 * put_pwq() with locking. This function also allows %NULL @pwq.
1354 */
1355static void put_pwq_unlocked(struct pool_workqueue *pwq)
1356{
1357 if (pwq) {
1358 /*
24acfb71 1359 * As both pwqs and pools are RCU protected, the
dce90d47
TH
1360 * following lock operations are safe.
1361 */
a9b8a985 1362 raw_spin_lock_irq(&pwq->pool->lock);
dce90d47 1363 put_pwq(pwq);
a9b8a985 1364 raw_spin_unlock_irq(&pwq->pool->lock);
dce90d47
TH
1365 }
1366}
1367
f97a4a1a 1368static void pwq_activate_inactive_work(struct work_struct *work)
bf4ede01 1369{
112202d9 1370 struct pool_workqueue *pwq = get_work_pwq(work);
bf4ede01
TH
1371
1372 trace_workqueue_activate_work(work);
82607adc
TH
1373 if (list_empty(&pwq->pool->worklist))
1374 pwq->pool->watchdog_ts = jiffies;
112202d9 1375 move_linked_works(work, &pwq->pool->worklist, NULL);
f97a4a1a 1376 __clear_bit(WORK_STRUCT_INACTIVE_BIT, work_data_bits(work));
112202d9 1377 pwq->nr_active++;
bf4ede01
TH
1378}
1379
f97a4a1a 1380static void pwq_activate_first_inactive(struct pool_workqueue *pwq)
3aa62497 1381{
f97a4a1a 1382 struct work_struct *work = list_first_entry(&pwq->inactive_works,
3aa62497
LJ
1383 struct work_struct, entry);
1384
f97a4a1a 1385 pwq_activate_inactive_work(work);
3aa62497
LJ
1386}
1387
bf4ede01 1388/**
112202d9
TH
1389 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1390 * @pwq: pwq of interest
c4560c2c 1391 * @work_data: work_data of work which left the queue
bf4ede01
TH
1392 *
1393 * A work either has completed or is removed from pending queue,
112202d9 1394 * decrement nr_in_flight of its pwq and handle workqueue flushing.
bf4ede01
TH
1395 *
1396 * CONTEXT:
a9b8a985 1397 * raw_spin_lock_irq(pool->lock).
bf4ede01 1398 */
c4560c2c 1399static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data)
bf4ede01 1400{
c4560c2c
LJ
1401 int color = get_work_color(work_data);
1402
018f3a13
LJ
1403 if (!(work_data & WORK_STRUCT_INACTIVE)) {
1404 pwq->nr_active--;
1405 if (!list_empty(&pwq->inactive_works)) {
1406 /* one down, submit an inactive one */
1407 if (pwq->nr_active < pwq->max_active)
1408 pwq_activate_first_inactive(pwq);
1409 }
1410 }
1411
112202d9 1412 pwq->nr_in_flight[color]--;
bf4ede01 1413
bf4ede01 1414 /* is flush in progress and are we at the flushing tip? */
112202d9 1415 if (likely(pwq->flush_color != color))
8864b4e5 1416 goto out_put;
bf4ede01
TH
1417
1418 /* are there still in-flight works? */
112202d9 1419 if (pwq->nr_in_flight[color])
8864b4e5 1420 goto out_put;
bf4ede01 1421
112202d9
TH
1422 /* this pwq is done, clear flush_color */
1423 pwq->flush_color = -1;
bf4ede01
TH
1424
1425 /*
112202d9 1426 * If this was the last pwq, wake up the first flusher. It
bf4ede01
TH
1427 * will handle the rest.
1428 */
112202d9
TH
1429 if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1430 complete(&pwq->wq->first_flusher->done);
8864b4e5
TH
1431out_put:
1432 put_pwq(pwq);
bf4ede01
TH
1433}
1434
36e227d2 1435/**
bbb68dfa 1436 * try_to_grab_pending - steal work item from worklist and disable irq
36e227d2
TH
1437 * @work: work item to steal
1438 * @is_dwork: @work is a delayed_work
bbb68dfa 1439 * @flags: place to store irq state
36e227d2
TH
1440 *
1441 * Try to grab PENDING bit of @work. This function can handle @work in any
d185af30 1442 * stable state - idle, on timer or on worklist.
36e227d2 1443 *
d185af30 1444 * Return:
3eb6b31b
MCC
1445 *
1446 * ======== ================================================================
36e227d2
TH
1447 * 1 if @work was pending and we successfully stole PENDING
1448 * 0 if @work was idle and we claimed PENDING
1449 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
bbb68dfa
TH
1450 * -ENOENT if someone else is canceling @work, this state may persist
1451 * for arbitrarily long
3eb6b31b 1452 * ======== ================================================================
36e227d2 1453 *
d185af30 1454 * Note:
bbb68dfa 1455 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
e0aecdd8
TH
1456 * interrupted while holding PENDING and @work off queue, irq must be
1457 * disabled on entry. This, combined with delayed_work->timer being
1458 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
bbb68dfa
TH
1459 *
1460 * On successful return, >= 0, irq is disabled and the caller is
1461 * responsible for releasing it using local_irq_restore(*@flags).
1462 *
e0aecdd8 1463 * This function is safe to call from any context including IRQ handler.
bf4ede01 1464 */
bbb68dfa
TH
1465static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1466 unsigned long *flags)
bf4ede01 1467{
d565ed63 1468 struct worker_pool *pool;
112202d9 1469 struct pool_workqueue *pwq;
bf4ede01 1470
bbb68dfa
TH
1471 local_irq_save(*flags);
1472
36e227d2
TH
1473 /* try to steal the timer if it exists */
1474 if (is_dwork) {
1475 struct delayed_work *dwork = to_delayed_work(work);
1476
e0aecdd8
TH
1477 /*
1478 * dwork->timer is irqsafe. If del_timer() fails, it's
1479 * guaranteed that the timer is not queued anywhere and not
1480 * running on the local CPU.
1481 */
36e227d2
TH
1482 if (likely(del_timer(&dwork->timer)))
1483 return 1;
1484 }
1485
1486 /* try to claim PENDING the normal way */
bf4ede01
TH
1487 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1488 return 0;
1489
24acfb71 1490 rcu_read_lock();
bf4ede01
TH
1491 /*
1492 * The queueing is in progress, or it is already queued. Try to
1493 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1494 */
d565ed63
TH
1495 pool = get_work_pool(work);
1496 if (!pool)
bbb68dfa 1497 goto fail;
bf4ede01 1498
a9b8a985 1499 raw_spin_lock(&pool->lock);
0b3dae68 1500 /*
112202d9
TH
1501 * work->data is guaranteed to point to pwq only while the work
1502 * item is queued on pwq->wq, and both updating work->data to point
1503 * to pwq on queueing and to pool on dequeueing are done under
1504 * pwq->pool->lock. This in turn guarantees that, if work->data
1505 * points to pwq which is associated with a locked pool, the work
0b3dae68
LJ
1506 * item is currently queued on that pool.
1507 */
112202d9
TH
1508 pwq = get_work_pwq(work);
1509 if (pwq && pwq->pool == pool) {
16062836
TH
1510 debug_work_deactivate(work);
1511
1512 /*
018f3a13
LJ
1513 * A cancelable inactive work item must be in the
1514 * pwq->inactive_works since a queued barrier can't be
1515 * canceled (see the comments in insert_wq_barrier()).
1516 *
f97a4a1a 1517 * An inactive work item cannot be grabbed directly because
d812796e 1518 * it might have linked barrier work items which, if left
f97a4a1a 1519 * on the inactive_works list, will confuse pwq->nr_active
16062836
TH
1520 * management later on and cause stall. Make sure the work
1521 * item is activated before grabbing.
1522 */
f97a4a1a
LJ
1523 if (*work_data_bits(work) & WORK_STRUCT_INACTIVE)
1524 pwq_activate_inactive_work(work);
16062836
TH
1525
1526 list_del_init(&work->entry);
c4560c2c 1527 pwq_dec_nr_in_flight(pwq, *work_data_bits(work));
16062836 1528
112202d9 1529 /* work->data points to pwq iff queued, point to pool */
16062836
TH
1530 set_work_pool_and_keep_pending(work, pool->id);
1531
a9b8a985 1532 raw_spin_unlock(&pool->lock);
24acfb71 1533 rcu_read_unlock();
16062836 1534 return 1;
bf4ede01 1535 }
a9b8a985 1536 raw_spin_unlock(&pool->lock);
bbb68dfa 1537fail:
24acfb71 1538 rcu_read_unlock();
bbb68dfa
TH
1539 local_irq_restore(*flags);
1540 if (work_is_canceling(work))
1541 return -ENOENT;
1542 cpu_relax();
36e227d2 1543 return -EAGAIN;
bf4ede01
TH
1544}
1545
4690c4ab 1546/**
706026c2 1547 * insert_work - insert a work into a pool
112202d9 1548 * @pwq: pwq @work belongs to
4690c4ab
TH
1549 * @work: work to insert
1550 * @head: insertion point
1551 * @extra_flags: extra WORK_STRUCT_* flags to set
1552 *
112202d9 1553 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
706026c2 1554 * work_struct flags.
4690c4ab
TH
1555 *
1556 * CONTEXT:
a9b8a985 1557 * raw_spin_lock_irq(pool->lock).
4690c4ab 1558 */
112202d9
TH
1559static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1560 struct list_head *head, unsigned int extra_flags)
b89deed3 1561{
fe089f87 1562 debug_work_activate(work);
e22bee78 1563
e89a85d6 1564 /* record the work call stack in order to print it in KASAN reports */
f70da745 1565 kasan_record_aux_stack_noalloc(work);
e89a85d6 1566
4690c4ab 1567 /* we own @work, set data and link */
112202d9 1568 set_work_pwq(work, pwq, extra_flags);
1a4d9b0a 1569 list_add_tail(&work->entry, head);
8864b4e5 1570 get_pwq(pwq);
b89deed3
ON
1571}
1572
c8efcc25
TH
1573/*
1574 * Test whether @work is being queued from another work executing on the
8d03ecfe 1575 * same workqueue.
c8efcc25
TH
1576 */
1577static bool is_chained_work(struct workqueue_struct *wq)
1578{
8d03ecfe
TH
1579 struct worker *worker;
1580
1581 worker = current_wq_worker();
1582 /*
bf393fd4 1583 * Return %true iff I'm a worker executing a work item on @wq. If
8d03ecfe
TH
1584 * I'm @worker, it's safe to dereference it without locking.
1585 */
112202d9 1586 return worker && worker->current_pwq->wq == wq;
c8efcc25
TH
1587}
1588
ef557180
MG
1589/*
1590 * When queueing an unbound work item to a wq, prefer local CPU if allowed
1591 * by wq_unbound_cpumask. Otherwise, round robin among the allowed ones to
1592 * avoid perturbing sensitive tasks.
1593 */
1594static int wq_select_unbound_cpu(int cpu)
1595{
1596 int new_cpu;
1597
f303fccb
TH
1598 if (likely(!wq_debug_force_rr_cpu)) {
1599 if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
1600 return cpu;
a8ec5880
AF
1601 } else {
1602 pr_warn_once("workqueue: round-robin CPU selection forced, expect performance impact\n");
f303fccb
TH
1603 }
1604
ef557180
MG
1605 if (cpumask_empty(wq_unbound_cpumask))
1606 return cpu;
1607
1608 new_cpu = __this_cpu_read(wq_rr_cpu_last);
1609 new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
1610 if (unlikely(new_cpu >= nr_cpu_ids)) {
1611 new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
1612 if (unlikely(new_cpu >= nr_cpu_ids))
1613 return cpu;
1614 }
1615 __this_cpu_write(wq_rr_cpu_last, new_cpu);
1616
1617 return new_cpu;
1618}
1619
d84ff051 1620static void __queue_work(int cpu, struct workqueue_struct *wq,
1da177e4
LT
1621 struct work_struct *work)
1622{
112202d9 1623 struct pool_workqueue *pwq;
fe089f87 1624 struct worker_pool *last_pool, *pool;
8a2e8e5d 1625 unsigned int work_flags;
b75cac93 1626 unsigned int req_cpu = cpu;
8930caba
TH
1627
1628 /*
1629 * While a work item is PENDING && off queue, a task trying to
1630 * steal the PENDING will busy-loop waiting for it to either get
1631 * queued or lose PENDING. Grabbing PENDING and queueing should
1632 * happen with IRQ disabled.
1633 */
8e8eb730 1634 lockdep_assert_irqs_disabled();
1da177e4 1635
1e19ffc6 1636
33e3f0a3
RC
1637 /*
1638 * For a draining wq, only works from the same workqueue are
1639 * allowed. The __WQ_DESTROYING helps to spot the issue that
1640 * queues a new work item to a wq after destroy_workqueue(wq).
1641 */
1642 if (unlikely(wq->flags & (__WQ_DESTROYING | __WQ_DRAINING) &&
1643 WARN_ON_ONCE(!is_chained_work(wq))))
e41e704b 1644 return;
24acfb71 1645 rcu_read_lock();
9e8cd2f5 1646retry:
c9178087 1647 /* pwq which will be used unless @work is executing elsewhere */
636b927e
TH
1648 if (req_cpu == WORK_CPU_UNBOUND) {
1649 if (wq->flags & WQ_UNBOUND)
aa202f1f 1650 cpu = wq_select_unbound_cpu(raw_smp_processor_id());
636b927e 1651 else
aa202f1f 1652 cpu = raw_smp_processor_id();
aa202f1f 1653 }
dbf2576e 1654
636b927e 1655 pwq = rcu_dereference(*per_cpu_ptr(wq->cpu_pwq, cpu));
fe089f87
TH
1656 pool = pwq->pool;
1657
c9178087
TH
1658 /*
1659 * If @work was previously on a different pool, it might still be
1660 * running there, in which case the work needs to be queued on that
1661 * pool to guarantee non-reentrancy.
1662 */
1663 last_pool = get_work_pool(work);
fe089f87 1664 if (last_pool && last_pool != pool) {
c9178087 1665 struct worker *worker;
18aa9eff 1666
a9b8a985 1667 raw_spin_lock(&last_pool->lock);
18aa9eff 1668
c9178087 1669 worker = find_worker_executing_work(last_pool, work);
18aa9eff 1670
c9178087
TH
1671 if (worker && worker->current_pwq->wq == wq) {
1672 pwq = worker->current_pwq;
fe089f87
TH
1673 pool = pwq->pool;
1674 WARN_ON_ONCE(pool != last_pool);
8930caba 1675 } else {
c9178087 1676 /* meh... not running there, queue here */
a9b8a985 1677 raw_spin_unlock(&last_pool->lock);
fe089f87 1678 raw_spin_lock(&pool->lock);
8930caba 1679 }
f3421797 1680 } else {
fe089f87 1681 raw_spin_lock(&pool->lock);
502ca9d8
TH
1682 }
1683
9e8cd2f5 1684 /*
636b927e
TH
1685 * pwq is determined and locked. For unbound pools, we could have raced
1686 * with pwq release and it could already be dead. If its refcnt is zero,
1687 * repeat pwq selection. Note that unbound pwqs never die without
1688 * another pwq replacing it in cpu_pwq or while work items are executing
1689 * on it, so the retrying is guaranteed to make forward-progress.
9e8cd2f5
TH
1690 */
1691 if (unlikely(!pwq->refcnt)) {
1692 if (wq->flags & WQ_UNBOUND) {
fe089f87 1693 raw_spin_unlock(&pool->lock);
9e8cd2f5
TH
1694 cpu_relax();
1695 goto retry;
1696 }
1697 /* oops */
1698 WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
1699 wq->name, cpu);
1700 }
1701
112202d9
TH
1702 /* pwq determined, queue */
1703 trace_workqueue_queue_work(req_cpu, pwq, work);
502ca9d8 1704
24acfb71
TG
1705 if (WARN_ON(!list_empty(&work->entry)))
1706 goto out;
1e19ffc6 1707
112202d9
TH
1708 pwq->nr_in_flight[pwq->work_color]++;
1709 work_flags = work_color_to_flags(pwq->work_color);
1e19ffc6 1710
112202d9 1711 if (likely(pwq->nr_active < pwq->max_active)) {
fe089f87
TH
1712 if (list_empty(&pool->worklist))
1713 pool->watchdog_ts = jiffies;
1714
cdadf009 1715 trace_workqueue_activate_work(work);
112202d9 1716 pwq->nr_active++;
fe089f87
TH
1717 insert_work(pwq, work, &pool->worklist, work_flags);
1718
1719 if (__need_more_worker(pool))
1720 wake_up_worker(pool);
8a2e8e5d 1721 } else {
f97a4a1a 1722 work_flags |= WORK_STRUCT_INACTIVE;
fe089f87 1723 insert_work(pwq, work, &pwq->inactive_works, work_flags);
8a2e8e5d 1724 }
1e19ffc6 1725
24acfb71 1726out:
fe089f87 1727 raw_spin_unlock(&pool->lock);
24acfb71 1728 rcu_read_unlock();
1da177e4
LT
1729}
1730
0fcb78c2 1731/**
c1a220e7
ZR
1732 * queue_work_on - queue work on specific cpu
1733 * @cpu: CPU number to execute work on
0fcb78c2
REB
1734 * @wq: workqueue to use
1735 * @work: work to queue
1736 *
c1a220e7 1737 * We queue the work to a specific CPU, the caller must ensure it
443378f0
PM
1738 * can't go away. Callers that fail to ensure that the specified
1739 * CPU cannot go away will execute on a randomly chosen CPU.
854f5cc5
PM
1740 * But note well that callers specifying a CPU that never has been
1741 * online will get a splat.
d185af30
YB
1742 *
1743 * Return: %false if @work was already on a queue, %true otherwise.
1da177e4 1744 */
d4283e93
TH
1745bool queue_work_on(int cpu, struct workqueue_struct *wq,
1746 struct work_struct *work)
1da177e4 1747{
d4283e93 1748 bool ret = false;
8930caba 1749 unsigned long flags;
ef1ca236 1750
8930caba 1751 local_irq_save(flags);
c1a220e7 1752
22df02bb 1753 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
4690c4ab 1754 __queue_work(cpu, wq, work);
d4283e93 1755 ret = true;
c1a220e7 1756 }
ef1ca236 1757
8930caba 1758 local_irq_restore(flags);
1da177e4
LT
1759 return ret;
1760}
ad7b1f84 1761EXPORT_SYMBOL(queue_work_on);
1da177e4 1762
8204e0c1 1763/**
fef59c9c 1764 * select_numa_node_cpu - Select a CPU based on NUMA node
8204e0c1
AD
1765 * @node: NUMA node ID that we want to select a CPU from
1766 *
1767 * This function will attempt to find a "random" cpu available on a given
1768 * node. If there are no CPUs available on the given node it will return
1769 * WORK_CPU_UNBOUND indicating that we should just schedule to any
1770 * available CPU if we need to schedule this work.
1771 */
fef59c9c 1772static int select_numa_node_cpu(int node)
8204e0c1
AD
1773{
1774 int cpu;
1775
1776 /* No point in doing this if NUMA isn't enabled for workqueues */
fef59c9c 1777 if (!wq_pod_enabled)
8204e0c1
AD
1778 return WORK_CPU_UNBOUND;
1779
1780 /* Delay binding to CPU if node is not valid or online */
1781 if (node < 0 || node >= MAX_NUMNODES || !node_online(node))
1782 return WORK_CPU_UNBOUND;
1783
1784 /* Use local node/cpu if we are already there */
1785 cpu = raw_smp_processor_id();
1786 if (node == cpu_to_node(cpu))
1787 return cpu;
1788
1789 /* Use "random" otherwise know as "first" online CPU of node */
1790 cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
1791
1792 /* If CPU is valid return that, otherwise just defer */
1793 return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND;
1794}
1795
1796/**
1797 * queue_work_node - queue work on a "random" cpu for a given NUMA node
1798 * @node: NUMA node that we are targeting the work for
1799 * @wq: workqueue to use
1800 * @work: work to queue
1801 *
1802 * We queue the work to a "random" CPU within a given NUMA node. The basic
1803 * idea here is to provide a way to somehow associate work with a given
1804 * NUMA node.
1805 *
1806 * This function will only make a best effort attempt at getting this onto
1807 * the right NUMA node. If no node is requested or the requested node is
1808 * offline then we just fall back to standard queue_work behavior.
1809 *
1810 * Currently the "random" CPU ends up being the first available CPU in the
1811 * intersection of cpu_online_mask and the cpumask of the node, unless we
1812 * are running on the node. In that case we just use the current CPU.
1813 *
1814 * Return: %false if @work was already on a queue, %true otherwise.
1815 */
1816bool queue_work_node(int node, struct workqueue_struct *wq,
1817 struct work_struct *work)
1818{
1819 unsigned long flags;
1820 bool ret = false;
1821
1822 /*
1823 * This current implementation is specific to unbound workqueues.
1824 * Specifically we only return the first available CPU for a given
1825 * node instead of cycling through individual CPUs within the node.
1826 *
1827 * If this is used with a per-cpu workqueue then the logic in
1828 * workqueue_select_cpu_near would need to be updated to allow for
1829 * some round robin type logic.
1830 */
1831 WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND));
1832
1833 local_irq_save(flags);
1834
1835 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
fef59c9c 1836 int cpu = select_numa_node_cpu(node);
8204e0c1
AD
1837
1838 __queue_work(cpu, wq, work);
1839 ret = true;
1840 }
1841
1842 local_irq_restore(flags);
1843 return ret;
1844}
1845EXPORT_SYMBOL_GPL(queue_work_node);
1846
8c20feb6 1847void delayed_work_timer_fn(struct timer_list *t)
1da177e4 1848{
8c20feb6 1849 struct delayed_work *dwork = from_timer(dwork, t, timer);
1da177e4 1850
e0aecdd8 1851 /* should have been called from irqsafe timer with irq already off */
60c057bc 1852 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
1da177e4 1853}
1438ade5 1854EXPORT_SYMBOL(delayed_work_timer_fn);
1da177e4 1855
7beb2edf
TH
1856static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
1857 struct delayed_work *dwork, unsigned long delay)
1da177e4 1858{
7beb2edf
TH
1859 struct timer_list *timer = &dwork->timer;
1860 struct work_struct *work = &dwork->work;
7beb2edf 1861
637fdbae 1862 WARN_ON_ONCE(!wq);
4b243563 1863 WARN_ON_ONCE(timer->function != delayed_work_timer_fn);
fc4b514f
TH
1864 WARN_ON_ONCE(timer_pending(timer));
1865 WARN_ON_ONCE(!list_empty(&work->entry));
7beb2edf 1866
8852aac2
TH
1867 /*
1868 * If @delay is 0, queue @dwork->work immediately. This is for
1869 * both optimization and correctness. The earliest @timer can
1870 * expire is on the closest next tick and delayed_work users depend
1871 * on that there's no such delay when @delay is 0.
1872 */
1873 if (!delay) {
1874 __queue_work(cpu, wq, &dwork->work);
1875 return;
1876 }
1877
60c057bc 1878 dwork->wq = wq;
1265057f 1879 dwork->cpu = cpu;
7beb2edf
TH
1880 timer->expires = jiffies + delay;
1881
041bd12e
TH
1882 if (unlikely(cpu != WORK_CPU_UNBOUND))
1883 add_timer_on(timer, cpu);
1884 else
1885 add_timer(timer);
1da177e4
LT
1886}
1887
0fcb78c2
REB
1888/**
1889 * queue_delayed_work_on - queue work on specific CPU after delay
1890 * @cpu: CPU number to execute work on
1891 * @wq: workqueue to use
af9997e4 1892 * @dwork: work to queue
0fcb78c2
REB
1893 * @delay: number of jiffies to wait before queueing
1894 *
d185af30 1895 * Return: %false if @work was already on a queue, %true otherwise. If
715f1300
TH
1896 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1897 * execution.
0fcb78c2 1898 */
d4283e93
TH
1899bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1900 struct delayed_work *dwork, unsigned long delay)
7a6bc1cd 1901{
52bad64d 1902 struct work_struct *work = &dwork->work;
d4283e93 1903 bool ret = false;
8930caba 1904 unsigned long flags;
7a6bc1cd 1905
8930caba
TH
1906 /* read the comment in __queue_work() */
1907 local_irq_save(flags);
7a6bc1cd 1908
22df02bb 1909 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
7beb2edf 1910 __queue_delayed_work(cpu, wq, dwork, delay);
d4283e93 1911 ret = true;
7a6bc1cd 1912 }
8a3e77cc 1913
8930caba 1914 local_irq_restore(flags);
7a6bc1cd
VP
1915 return ret;
1916}
ad7b1f84 1917EXPORT_SYMBOL(queue_delayed_work_on);
c7fc77f7 1918
8376fe22
TH
1919/**
1920 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1921 * @cpu: CPU number to execute work on
1922 * @wq: workqueue to use
1923 * @dwork: work to queue
1924 * @delay: number of jiffies to wait before queueing
1925 *
1926 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1927 * modify @dwork's timer so that it expires after @delay. If @delay is
1928 * zero, @work is guaranteed to be scheduled immediately regardless of its
1929 * current state.
1930 *
d185af30 1931 * Return: %false if @dwork was idle and queued, %true if @dwork was
8376fe22
TH
1932 * pending and its timer was modified.
1933 *
e0aecdd8 1934 * This function is safe to call from any context including IRQ handler.
8376fe22
TH
1935 * See try_to_grab_pending() for details.
1936 */
1937bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
1938 struct delayed_work *dwork, unsigned long delay)
1939{
1940 unsigned long flags;
1941 int ret;
c7fc77f7 1942
8376fe22
TH
1943 do {
1944 ret = try_to_grab_pending(&dwork->work, true, &flags);
1945 } while (unlikely(ret == -EAGAIN));
63bc0362 1946
8376fe22
TH
1947 if (likely(ret >= 0)) {
1948 __queue_delayed_work(cpu, wq, dwork, delay);
1949 local_irq_restore(flags);
7a6bc1cd 1950 }
8376fe22
TH
1951
1952 /* -ENOENT from try_to_grab_pending() becomes %true */
7a6bc1cd
VP
1953 return ret;
1954}
8376fe22
TH
1955EXPORT_SYMBOL_GPL(mod_delayed_work_on);
1956
05f0fe6b
TH
1957static void rcu_work_rcufn(struct rcu_head *rcu)
1958{
1959 struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
1960
1961 /* read the comment in __queue_work() */
1962 local_irq_disable();
1963 __queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
1964 local_irq_enable();
1965}
1966
1967/**
1968 * queue_rcu_work - queue work after a RCU grace period
1969 * @wq: workqueue to use
1970 * @rwork: work to queue
1971 *
1972 * Return: %false if @rwork was already pending, %true otherwise. Note
1973 * that a full RCU grace period is guaranteed only after a %true return.
bf393fd4 1974 * While @rwork is guaranteed to be executed after a %false return, the
05f0fe6b
TH
1975 * execution may happen before a full RCU grace period has passed.
1976 */
1977bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
1978{
1979 struct work_struct *work = &rwork->work;
1980
1981 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1982 rwork->wq = wq;
a7e30c0e 1983 call_rcu_hurry(&rwork->rcu, rcu_work_rcufn);
05f0fe6b
TH
1984 return true;
1985 }
1986
1987 return false;
1988}
1989EXPORT_SYMBOL(queue_rcu_work);
1990
f7537df5 1991static struct worker *alloc_worker(int node)
c34056a3
TH
1992{
1993 struct worker *worker;
1994
f7537df5 1995 worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
c8e55f36
TH
1996 if (worker) {
1997 INIT_LIST_HEAD(&worker->entry);
affee4b2 1998 INIT_LIST_HEAD(&worker->scheduled);
da028469 1999 INIT_LIST_HEAD(&worker->node);
e22bee78
TH
2000 /* on creation a worker is in !idle && prep state */
2001 worker->flags = WORKER_PREP;
c8e55f36 2002 }
c34056a3
TH
2003 return worker;
2004}
2005
4736cbf7
LJ
2006/**
2007 * worker_attach_to_pool() - attach a worker to a pool
2008 * @worker: worker to be attached
2009 * @pool: the target pool
2010 *
2011 * Attach @worker to @pool. Once attached, the %WORKER_UNBOUND flag and
2012 * cpu-binding of @worker are kept coordinated with the pool across
2013 * cpu-[un]hotplugs.
2014 */
2015static void worker_attach_to_pool(struct worker *worker,
2016 struct worker_pool *pool)
2017{
1258fae7 2018 mutex_lock(&wq_pool_attach_mutex);
4736cbf7 2019
4736cbf7 2020 /*
1258fae7
TH
2021 * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains
2022 * stable across this function. See the comments above the flag
2023 * definition for details.
4736cbf7
LJ
2024 */
2025 if (pool->flags & POOL_DISASSOCIATED)
2026 worker->flags |= WORKER_UNBOUND;
5c25b5ff
PZ
2027 else
2028 kthread_set_per_cpu(worker->task, pool->cpu);
4736cbf7 2029
640f17c8
PZ
2030 if (worker->rescue_wq)
2031 set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
2032
4736cbf7 2033 list_add_tail(&worker->node, &pool->workers);
a2d812a2 2034 worker->pool = pool;
4736cbf7 2035
1258fae7 2036 mutex_unlock(&wq_pool_attach_mutex);
4736cbf7
LJ
2037}
2038
60f5a4bc
LJ
2039/**
2040 * worker_detach_from_pool() - detach a worker from its pool
2041 * @worker: worker which is attached to its pool
60f5a4bc 2042 *
4736cbf7
LJ
2043 * Undo the attaching which had been done in worker_attach_to_pool(). The
2044 * caller worker shouldn't access to the pool after detached except it has
2045 * other reference to the pool.
60f5a4bc 2046 */
a2d812a2 2047static void worker_detach_from_pool(struct worker *worker)
60f5a4bc 2048{
a2d812a2 2049 struct worker_pool *pool = worker->pool;
60f5a4bc
LJ
2050 struct completion *detach_completion = NULL;
2051
1258fae7 2052 mutex_lock(&wq_pool_attach_mutex);
a2d812a2 2053
5c25b5ff 2054 kthread_set_per_cpu(worker->task, -1);
da028469 2055 list_del(&worker->node);
a2d812a2
TH
2056 worker->pool = NULL;
2057
e02b9312 2058 if (list_empty(&pool->workers) && list_empty(&pool->dying_workers))
60f5a4bc 2059 detach_completion = pool->detach_completion;
1258fae7 2060 mutex_unlock(&wq_pool_attach_mutex);
60f5a4bc 2061
b62c0751
LJ
2062 /* clear leftover flags without pool->lock after it is detached */
2063 worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
2064
60f5a4bc
LJ
2065 if (detach_completion)
2066 complete(detach_completion);
2067}
2068
c34056a3
TH
2069/**
2070 * create_worker - create a new workqueue worker
63d95a91 2071 * @pool: pool the new worker will belong to
c34056a3 2072 *
051e1850 2073 * Create and start a new worker which is attached to @pool.
c34056a3
TH
2074 *
2075 * CONTEXT:
2076 * Might sleep. Does GFP_KERNEL allocations.
2077 *
d185af30 2078 * Return:
c34056a3
TH
2079 * Pointer to the newly created worker.
2080 */
bc2ae0f5 2081static struct worker *create_worker(struct worker_pool *pool)
c34056a3 2082{
e441b56f
ZL
2083 struct worker *worker;
2084 int id;
e3c916a4 2085 char id_buf[16];
c34056a3 2086
7cda9aae 2087 /* ID is needed to determine kthread name */
e441b56f 2088 id = ida_alloc(&pool->worker_ida, GFP_KERNEL);
3f0ea0b8
PM
2089 if (id < 0) {
2090 pr_err_once("workqueue: Failed to allocate a worker ID: %pe\n",
2091 ERR_PTR(id));
e441b56f 2092 return NULL;
3f0ea0b8 2093 }
c34056a3 2094
f7537df5 2095 worker = alloc_worker(pool->node);
3f0ea0b8
PM
2096 if (!worker) {
2097 pr_err_once("workqueue: Failed to allocate a worker\n");
c34056a3 2098 goto fail;
3f0ea0b8 2099 }
c34056a3 2100
c34056a3
TH
2101 worker->id = id;
2102
29c91e99 2103 if (pool->cpu >= 0)
e3c916a4
TH
2104 snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
2105 pool->attrs->nice < 0 ? "H" : "");
f3421797 2106 else
e3c916a4
TH
2107 snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
2108
f3f90ad4 2109 worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
e3c916a4 2110 "kworker/%s", id_buf);
3f0ea0b8 2111 if (IS_ERR(worker->task)) {
60f54038
PM
2112 if (PTR_ERR(worker->task) == -EINTR) {
2113 pr_err("workqueue: Interrupted when creating a worker thread \"kworker/%s\"\n",
2114 id_buf);
2115 } else {
2116 pr_err_once("workqueue: Failed to create a worker thread: %pe",
2117 worker->task);
2118 }
c34056a3 2119 goto fail;
3f0ea0b8 2120 }
c34056a3 2121
91151228 2122 set_user_nice(worker->task, pool->attrs->nice);
25834c73 2123 kthread_bind_mask(worker->task, pool->attrs->cpumask);
91151228 2124
da028469 2125 /* successful, attach the worker to the pool */
4736cbf7 2126 worker_attach_to_pool(worker, pool);
822d8405 2127
051e1850 2128 /* start the newly created worker */
a9b8a985 2129 raw_spin_lock_irq(&pool->lock);
051e1850
LJ
2130 worker->pool->nr_workers++;
2131 worker_enter_idle(worker);
2132 wake_up_process(worker->task);
a9b8a985 2133 raw_spin_unlock_irq(&pool->lock);
051e1850 2134
c34056a3 2135 return worker;
822d8405 2136
c34056a3 2137fail:
e441b56f 2138 ida_free(&pool->worker_ida, id);
c34056a3
TH
2139 kfree(worker);
2140 return NULL;
2141}
2142
793777bc
VS
2143static void unbind_worker(struct worker *worker)
2144{
2145 lockdep_assert_held(&wq_pool_attach_mutex);
2146
2147 kthread_set_per_cpu(worker->task, -1);
2148 if (cpumask_intersects(wq_unbound_cpumask, cpu_active_mask))
2149 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, wq_unbound_cpumask) < 0);
2150 else
2151 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, cpu_possible_mask) < 0);
2152}
2153
e02b9312
VS
2154static void wake_dying_workers(struct list_head *cull_list)
2155{
2156 struct worker *worker, *tmp;
2157
2158 list_for_each_entry_safe(worker, tmp, cull_list, entry) {
2159 list_del_init(&worker->entry);
2160 unbind_worker(worker);
2161 /*
2162 * If the worker was somehow already running, then it had to be
2163 * in pool->idle_list when set_worker_dying() happened or we
2164 * wouldn't have gotten here.
2165 *
2166 * Thus, the worker must either have observed the WORKER_DIE
2167 * flag, or have set its state to TASK_IDLE. Either way, the
2168 * below will be observed by the worker and is safe to do
2169 * outside of pool->lock.
2170 */
2171 wake_up_process(worker->task);
2172 }
2173}
2174
c34056a3 2175/**
e02b9312 2176 * set_worker_dying - Tag a worker for destruction
c34056a3 2177 * @worker: worker to be destroyed
e02b9312 2178 * @list: transfer worker away from its pool->idle_list and into list
c34056a3 2179 *
e02b9312
VS
2180 * Tag @worker for destruction and adjust @pool stats accordingly. The worker
2181 * should be idle.
c8e55f36
TH
2182 *
2183 * CONTEXT:
a9b8a985 2184 * raw_spin_lock_irq(pool->lock).
c34056a3 2185 */
e02b9312 2186static void set_worker_dying(struct worker *worker, struct list_head *list)
c34056a3 2187{
bd7bdd43 2188 struct worker_pool *pool = worker->pool;
c34056a3 2189
cd549687 2190 lockdep_assert_held(&pool->lock);
e02b9312 2191 lockdep_assert_held(&wq_pool_attach_mutex);
cd549687 2192
c34056a3 2193 /* sanity check frenzy */
6183c009 2194 if (WARN_ON(worker->current_work) ||
73eb7fe7
LJ
2195 WARN_ON(!list_empty(&worker->scheduled)) ||
2196 WARN_ON(!(worker->flags & WORKER_IDLE)))
6183c009 2197 return;
c34056a3 2198
73eb7fe7
LJ
2199 pool->nr_workers--;
2200 pool->nr_idle--;
5bdfff96 2201
cb444766 2202 worker->flags |= WORKER_DIE;
e02b9312
VS
2203
2204 list_move(&worker->entry, list);
2205 list_move(&worker->node, &pool->dying_workers);
c34056a3
TH
2206}
2207
3f959aa3
VS
2208/**
2209 * idle_worker_timeout - check if some idle workers can now be deleted.
2210 * @t: The pool's idle_timer that just expired
2211 *
2212 * The timer is armed in worker_enter_idle(). Note that it isn't disarmed in
2213 * worker_leave_idle(), as a worker flicking between idle and active while its
2214 * pool is at the too_many_workers() tipping point would cause too much timer
2215 * housekeeping overhead. Since IDLE_WORKER_TIMEOUT is long enough, we just let
2216 * it expire and re-evaluate things from there.
2217 */
32a6c723 2218static void idle_worker_timeout(struct timer_list *t)
e22bee78 2219{
32a6c723 2220 struct worker_pool *pool = from_timer(pool, t, idle_timer);
3f959aa3
VS
2221 bool do_cull = false;
2222
2223 if (work_pending(&pool->idle_cull_work))
2224 return;
e22bee78 2225
a9b8a985 2226 raw_spin_lock_irq(&pool->lock);
e22bee78 2227
3f959aa3 2228 if (too_many_workers(pool)) {
e22bee78
TH
2229 struct worker *worker;
2230 unsigned long expires;
2231
2232 /* idle_list is kept in LIFO order, check the last one */
3f959aa3
VS
2233 worker = list_entry(pool->idle_list.prev, struct worker, entry);
2234 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2235 do_cull = !time_before(jiffies, expires);
2236
2237 if (!do_cull)
2238 mod_timer(&pool->idle_timer, expires);
2239 }
2240 raw_spin_unlock_irq(&pool->lock);
2241
2242 if (do_cull)
2243 queue_work(system_unbound_wq, &pool->idle_cull_work);
2244}
2245
2246/**
2247 * idle_cull_fn - cull workers that have been idle for too long.
2248 * @work: the pool's work for handling these idle workers
2249 *
2250 * This goes through a pool's idle workers and gets rid of those that have been
2251 * idle for at least IDLE_WORKER_TIMEOUT seconds.
e02b9312
VS
2252 *
2253 * We don't want to disturb isolated CPUs because of a pcpu kworker being
2254 * culled, so this also resets worker affinity. This requires a sleepable
2255 * context, hence the split between timer callback and work item.
3f959aa3
VS
2256 */
2257static void idle_cull_fn(struct work_struct *work)
2258{
2259 struct worker_pool *pool = container_of(work, struct worker_pool, idle_cull_work);
9680540c 2260 LIST_HEAD(cull_list);
3f959aa3 2261
e02b9312
VS
2262 /*
2263 * Grabbing wq_pool_attach_mutex here ensures an already-running worker
2264 * cannot proceed beyong worker_detach_from_pool() in its self-destruct
2265 * path. This is required as a previously-preempted worker could run after
2266 * set_worker_dying() has happened but before wake_dying_workers() did.
2267 */
2268 mutex_lock(&wq_pool_attach_mutex);
3f959aa3
VS
2269 raw_spin_lock_irq(&pool->lock);
2270
2271 while (too_many_workers(pool)) {
2272 struct worker *worker;
2273 unsigned long expires;
2274
63d95a91 2275 worker = list_entry(pool->idle_list.prev, struct worker, entry);
e22bee78
TH
2276 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2277
3347fc9f 2278 if (time_before(jiffies, expires)) {
63d95a91 2279 mod_timer(&pool->idle_timer, expires);
3347fc9f 2280 break;
d5abe669 2281 }
3347fc9f 2282
e02b9312 2283 set_worker_dying(worker, &cull_list);
e22bee78
TH
2284 }
2285
a9b8a985 2286 raw_spin_unlock_irq(&pool->lock);
e02b9312
VS
2287 wake_dying_workers(&cull_list);
2288 mutex_unlock(&wq_pool_attach_mutex);
e22bee78 2289}
d5abe669 2290
493a1724 2291static void send_mayday(struct work_struct *work)
e22bee78 2292{
112202d9
TH
2293 struct pool_workqueue *pwq = get_work_pwq(work);
2294 struct workqueue_struct *wq = pwq->wq;
493a1724 2295
2e109a28 2296 lockdep_assert_held(&wq_mayday_lock);
e22bee78 2297
493008a8 2298 if (!wq->rescuer)
493a1724 2299 return;
e22bee78
TH
2300
2301 /* mayday mayday mayday */
493a1724 2302 if (list_empty(&pwq->mayday_node)) {
77668c8b
LJ
2303 /*
2304 * If @pwq is for an unbound wq, its base ref may be put at
2305 * any time due to an attribute change. Pin @pwq until the
2306 * rescuer is done with it.
2307 */
2308 get_pwq(pwq);
493a1724 2309 list_add_tail(&pwq->mayday_node, &wq->maydays);
e22bee78 2310 wake_up_process(wq->rescuer->task);
725e8ec5 2311 pwq->stats[PWQ_STAT_MAYDAY]++;
493a1724 2312 }
e22bee78
TH
2313}
2314
32a6c723 2315static void pool_mayday_timeout(struct timer_list *t)
e22bee78 2316{
32a6c723 2317 struct worker_pool *pool = from_timer(pool, t, mayday_timer);
e22bee78
TH
2318 struct work_struct *work;
2319
a9b8a985
SAS
2320 raw_spin_lock_irq(&pool->lock);
2321 raw_spin_lock(&wq_mayday_lock); /* for wq->maydays */
e22bee78 2322
63d95a91 2323 if (need_to_create_worker(pool)) {
e22bee78
TH
2324 /*
2325 * We've been trying to create a new worker but
2326 * haven't been successful. We might be hitting an
2327 * allocation deadlock. Send distress signals to
2328 * rescuers.
2329 */
63d95a91 2330 list_for_each_entry(work, &pool->worklist, entry)
e22bee78 2331 send_mayday(work);
1da177e4 2332 }
e22bee78 2333
a9b8a985
SAS
2334 raw_spin_unlock(&wq_mayday_lock);
2335 raw_spin_unlock_irq(&pool->lock);
e22bee78 2336
63d95a91 2337 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1da177e4
LT
2338}
2339
e22bee78
TH
2340/**
2341 * maybe_create_worker - create a new worker if necessary
63d95a91 2342 * @pool: pool to create a new worker for
e22bee78 2343 *
63d95a91 2344 * Create a new worker for @pool if necessary. @pool is guaranteed to
e22bee78
TH
2345 * have at least one idle worker on return from this function. If
2346 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
63d95a91 2347 * sent to all rescuers with works scheduled on @pool to resolve
e22bee78
TH
2348 * possible allocation deadlock.
2349 *
c5aa87bb
TH
2350 * On return, need_to_create_worker() is guaranteed to be %false and
2351 * may_start_working() %true.
e22bee78
TH
2352 *
2353 * LOCKING:
a9b8a985 2354 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
e22bee78
TH
2355 * multiple times. Does GFP_KERNEL allocations. Called only from
2356 * manager.
e22bee78 2357 */
29187a9e 2358static void maybe_create_worker(struct worker_pool *pool)
d565ed63
TH
2359__releases(&pool->lock)
2360__acquires(&pool->lock)
1da177e4 2361{
e22bee78 2362restart:
a9b8a985 2363 raw_spin_unlock_irq(&pool->lock);
9f9c2364 2364
e22bee78 2365 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
63d95a91 2366 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
e22bee78
TH
2367
2368 while (true) {
051e1850 2369 if (create_worker(pool) || !need_to_create_worker(pool))
e22bee78 2370 break;
1da177e4 2371
e212f361 2372 schedule_timeout_interruptible(CREATE_COOLDOWN);
9f9c2364 2373
63d95a91 2374 if (!need_to_create_worker(pool))
e22bee78
TH
2375 break;
2376 }
2377
63d95a91 2378 del_timer_sync(&pool->mayday_timer);
a9b8a985 2379 raw_spin_lock_irq(&pool->lock);
051e1850
LJ
2380 /*
2381 * This is necessary even after a new worker was just successfully
2382 * created as @pool->lock was dropped and the new worker might have
2383 * already become busy.
2384 */
63d95a91 2385 if (need_to_create_worker(pool))
e22bee78 2386 goto restart;
e22bee78
TH
2387}
2388
73f53c4a 2389/**
e22bee78
TH
2390 * manage_workers - manage worker pool
2391 * @worker: self
73f53c4a 2392 *
706026c2 2393 * Assume the manager role and manage the worker pool @worker belongs
e22bee78 2394 * to. At any given time, there can be only zero or one manager per
706026c2 2395 * pool. The exclusion is handled automatically by this function.
e22bee78
TH
2396 *
2397 * The caller can safely start processing works on false return. On
2398 * true return, it's guaranteed that need_to_create_worker() is false
2399 * and may_start_working() is true.
73f53c4a
TH
2400 *
2401 * CONTEXT:
a9b8a985 2402 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
e22bee78
TH
2403 * multiple times. Does GFP_KERNEL allocations.
2404 *
d185af30 2405 * Return:
29187a9e
TH
2406 * %false if the pool doesn't need management and the caller can safely
2407 * start processing works, %true if management function was performed and
2408 * the conditions that the caller verified before calling the function may
2409 * no longer be true.
73f53c4a 2410 */
e22bee78 2411static bool manage_workers(struct worker *worker)
73f53c4a 2412{
63d95a91 2413 struct worker_pool *pool = worker->pool;
73f53c4a 2414
692b4825 2415 if (pool->flags & POOL_MANAGER_ACTIVE)
29187a9e 2416 return false;
692b4825
TH
2417
2418 pool->flags |= POOL_MANAGER_ACTIVE;
2607d7a6 2419 pool->manager = worker;
1e19ffc6 2420
29187a9e 2421 maybe_create_worker(pool);
e22bee78 2422
2607d7a6 2423 pool->manager = NULL;
692b4825 2424 pool->flags &= ~POOL_MANAGER_ACTIVE;
d8bb65ab 2425 rcuwait_wake_up(&manager_wait);
29187a9e 2426 return true;
73f53c4a
TH
2427}
2428
a62428c0
TH
2429/**
2430 * process_one_work - process single work
c34056a3 2431 * @worker: self
a62428c0
TH
2432 * @work: work to process
2433 *
2434 * Process @work. This function contains all the logics necessary to
2435 * process a single work including synchronization against and
2436 * interaction with other workers on the same cpu, queueing and
2437 * flushing. As long as context requirement is met, any worker can
2438 * call this function to process a work.
2439 *
2440 * CONTEXT:
a9b8a985 2441 * raw_spin_lock_irq(pool->lock) which is released and regrabbed.
a62428c0 2442 */
c34056a3 2443static void process_one_work(struct worker *worker, struct work_struct *work)
d565ed63
TH
2444__releases(&pool->lock)
2445__acquires(&pool->lock)
a62428c0 2446{
112202d9 2447 struct pool_workqueue *pwq = get_work_pwq(work);
bd7bdd43 2448 struct worker_pool *pool = worker->pool;
c4560c2c 2449 unsigned long work_data;
7e11629d 2450 struct worker *collision;
a62428c0
TH
2451#ifdef CONFIG_LOCKDEP
2452 /*
2453 * It is permissible to free the struct work_struct from
2454 * inside the function that is called from it, this we need to
2455 * take into account for lockdep too. To avoid bogus "held
2456 * lock freed" warnings as well as problems when looking into
2457 * work->lockdep_map, make a copy and use that here.
2458 */
4d82a1de
PZ
2459 struct lockdep_map lockdep_map;
2460
2461 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
a62428c0 2462#endif
807407c0 2463 /* ensure we're on the correct CPU */
85327af6 2464 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
ec22ca5e 2465 raw_smp_processor_id() != pool->cpu);
25511a47 2466
7e11629d
TH
2467 /*
2468 * A single work shouldn't be executed concurrently by
2469 * multiple workers on a single cpu. Check whether anyone is
2470 * already processing the work. If so, defer the work to the
2471 * currently executing one.
2472 */
c9e7cf27 2473 collision = find_worker_executing_work(pool, work);
7e11629d
TH
2474 if (unlikely(collision)) {
2475 move_linked_works(work, &collision->scheduled, NULL);
2476 return;
2477 }
2478
8930caba 2479 /* claim and dequeue */
a62428c0 2480 debug_work_deactivate(work);
c9e7cf27 2481 hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
c34056a3 2482 worker->current_work = work;
a2c1c57b 2483 worker->current_func = work->func;
112202d9 2484 worker->current_pwq = pwq;
616db877 2485 worker->current_at = worker->task->se.sum_exec_runtime;
c4560c2c 2486 work_data = *work_data_bits(work);
d812796e 2487 worker->current_color = get_work_color(work_data);
7a22ad75 2488
8bf89593
TH
2489 /*
2490 * Record wq name for cmdline and debug reporting, may get
2491 * overridden through set_worker_desc().
2492 */
2493 strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
2494
a62428c0
TH
2495 list_del_init(&work->entry);
2496
fb0e7beb 2497 /*
228f1d00
LJ
2498 * CPU intensive works don't participate in concurrency management.
2499 * They're the scheduler's responsibility. This takes @worker out
2500 * of concurrency management and the next code block will chain
2501 * execution of the pending work items.
fb0e7beb 2502 */
616db877 2503 if (unlikely(pwq->wq->flags & WQ_CPU_INTENSIVE))
228f1d00 2504 worker_set_flags(worker, WORKER_CPU_INTENSIVE);
fb0e7beb 2505
974271c4 2506 /*
a489a03e
LJ
2507 * Wake up another worker if necessary. The condition is always
2508 * false for normal per-cpu workers since nr_running would always
2509 * be >= 1 at this point. This is used to chain execution of the
2510 * pending work items for WORKER_NOT_RUNNING workers such as the
228f1d00 2511 * UNBOUND and CPU_INTENSIVE ones.
974271c4 2512 */
a489a03e 2513 if (need_more_worker(pool))
63d95a91 2514 wake_up_worker(pool);
974271c4 2515
8930caba 2516 /*
7c3eed5c 2517 * Record the last pool and clear PENDING which should be the last
d565ed63 2518 * update to @work. Also, do this inside @pool->lock so that
23657bb1
TH
2519 * PENDING and queued state changes happen together while IRQ is
2520 * disabled.
8930caba 2521 */
7c3eed5c 2522 set_work_pool_and_clear_pending(work, pool->id);
a62428c0 2523
a9b8a985 2524 raw_spin_unlock_irq(&pool->lock);
a62428c0 2525
a1d14934 2526 lock_map_acquire(&pwq->wq->lockdep_map);
a62428c0 2527 lock_map_acquire(&lockdep_map);
e6f3faa7 2528 /*
f52be570
PZ
2529 * Strictly speaking we should mark the invariant state without holding
2530 * any locks, that is, before these two lock_map_acquire()'s.
e6f3faa7
PZ
2531 *
2532 * However, that would result in:
2533 *
2534 * A(W1)
2535 * WFC(C)
2536 * A(W1)
2537 * C(C)
2538 *
2539 * Which would create W1->C->W1 dependencies, even though there is no
2540 * actual deadlock possible. There are two solutions, using a
2541 * read-recursive acquire on the work(queue) 'locks', but this will then
f52be570 2542 * hit the lockdep limitation on recursive locks, or simply discard
e6f3faa7
PZ
2543 * these locks.
2544 *
2545 * AFAICT there is no possible deadlock scenario between the
2546 * flush_work() and complete() primitives (except for single-threaded
2547 * workqueues), so hiding them isn't a problem.
2548 */
f52be570 2549 lockdep_invariant_state(true);
725e8ec5 2550 pwq->stats[PWQ_STAT_STARTED]++;
e36c886a 2551 trace_workqueue_execute_start(work);
a2c1c57b 2552 worker->current_func(work);
e36c886a
AV
2553 /*
2554 * While we must be careful to not use "work" after this, the trace
2555 * point will only record its address.
2556 */
1c5da0ec 2557 trace_workqueue_execute_end(work, worker->current_func);
725e8ec5 2558 pwq->stats[PWQ_STAT_COMPLETED]++;
a62428c0 2559 lock_map_release(&lockdep_map);
112202d9 2560 lock_map_release(&pwq->wq->lockdep_map);
a62428c0
TH
2561
2562 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
044c782c 2563 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
d75f773c 2564 " last function: %ps\n",
a2c1c57b
TH
2565 current->comm, preempt_count(), task_pid_nr(current),
2566 worker->current_func);
a62428c0
TH
2567 debug_show_held_locks(current);
2568 dump_stack();
2569 }
2570
b22ce278 2571 /*
025f50f3 2572 * The following prevents a kworker from hogging CPU on !PREEMPTION
b22ce278
TH
2573 * kernels, where a requeueing work item waiting for something to
2574 * happen could deadlock with stop_machine as such work item could
2575 * indefinitely requeue itself while all other CPUs are trapped in
789cbbec
JL
2576 * stop_machine. At the same time, report a quiescent RCU state so
2577 * the same condition doesn't freeze RCU.
b22ce278 2578 */
a7e6425e 2579 cond_resched();
b22ce278 2580
a9b8a985 2581 raw_spin_lock_irq(&pool->lock);
a62428c0 2582
616db877
TH
2583 /*
2584 * In addition to %WQ_CPU_INTENSIVE, @worker may also have been marked
2585 * CPU intensive by wq_worker_tick() if @work hogged CPU longer than
2586 * wq_cpu_intensive_thresh_us. Clear it.
2587 */
2588 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
fb0e7beb 2589
1b69ac6b
JW
2590 /* tag the worker for identification in schedule() */
2591 worker->last_func = worker->current_func;
2592
a62428c0 2593 /* we're done with it, release */
42f8570f 2594 hash_del(&worker->hentry);
c34056a3 2595 worker->current_work = NULL;
a2c1c57b 2596 worker->current_func = NULL;
112202d9 2597 worker->current_pwq = NULL;
d812796e 2598 worker->current_color = INT_MAX;
c4560c2c 2599 pwq_dec_nr_in_flight(pwq, work_data);
a62428c0
TH
2600}
2601
affee4b2
TH
2602/**
2603 * process_scheduled_works - process scheduled works
2604 * @worker: self
2605 *
2606 * Process all scheduled works. Please note that the scheduled list
2607 * may change while processing a work, so this function repeatedly
2608 * fetches a work from the top and executes it.
2609 *
2610 * CONTEXT:
a9b8a985 2611 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
affee4b2
TH
2612 * multiple times.
2613 */
2614static void process_scheduled_works(struct worker *worker)
1da177e4 2615{
c0ab017d
TH
2616 struct work_struct *work;
2617 bool first = true;
2618
2619 while ((work = list_first_entry_or_null(&worker->scheduled,
2620 struct work_struct, entry))) {
2621 if (first) {
2622 worker->pool->watchdog_ts = jiffies;
2623 first = false;
2624 }
c34056a3 2625 process_one_work(worker, work);
1da177e4 2626 }
1da177e4
LT
2627}
2628
197f6acc
TH
2629static void set_pf_worker(bool val)
2630{
2631 mutex_lock(&wq_pool_attach_mutex);
2632 if (val)
2633 current->flags |= PF_WQ_WORKER;
2634 else
2635 current->flags &= ~PF_WQ_WORKER;
2636 mutex_unlock(&wq_pool_attach_mutex);
2637}
2638
4690c4ab
TH
2639/**
2640 * worker_thread - the worker thread function
c34056a3 2641 * @__worker: self
4690c4ab 2642 *
c5aa87bb
TH
2643 * The worker thread function. All workers belong to a worker_pool -
2644 * either a per-cpu one or dynamic unbound one. These workers process all
2645 * work items regardless of their specific target workqueue. The only
2646 * exception is work items which belong to workqueues with a rescuer which
2647 * will be explained in rescuer_thread().
d185af30
YB
2648 *
2649 * Return: 0
4690c4ab 2650 */
c34056a3 2651static int worker_thread(void *__worker)
1da177e4 2652{
c34056a3 2653 struct worker *worker = __worker;
bd7bdd43 2654 struct worker_pool *pool = worker->pool;
1da177e4 2655
e22bee78 2656 /* tell the scheduler that this is a workqueue worker */
197f6acc 2657 set_pf_worker(true);
c8e55f36 2658woke_up:
a9b8a985 2659 raw_spin_lock_irq(&pool->lock);
1da177e4 2660
a9ab775b
TH
2661 /* am I supposed to die? */
2662 if (unlikely(worker->flags & WORKER_DIE)) {
a9b8a985 2663 raw_spin_unlock_irq(&pool->lock);
197f6acc 2664 set_pf_worker(false);
60f5a4bc
LJ
2665
2666 set_task_comm(worker->task, "kworker/dying");
e441b56f 2667 ida_free(&pool->worker_ida, worker->id);
a2d812a2 2668 worker_detach_from_pool(worker);
e02b9312 2669 WARN_ON_ONCE(!list_empty(&worker->entry));
60f5a4bc 2670 kfree(worker);
a9ab775b 2671 return 0;
c8e55f36 2672 }
affee4b2 2673
c8e55f36 2674 worker_leave_idle(worker);
db7bccf4 2675recheck:
e22bee78 2676 /* no more worker necessary? */
63d95a91 2677 if (!need_more_worker(pool))
e22bee78
TH
2678 goto sleep;
2679
2680 /* do we need to manage? */
63d95a91 2681 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
e22bee78
TH
2682 goto recheck;
2683
c8e55f36
TH
2684 /*
2685 * ->scheduled list can only be filled while a worker is
2686 * preparing to process a work or actually processing it.
2687 * Make sure nobody diddled with it while I was sleeping.
2688 */
6183c009 2689 WARN_ON_ONCE(!list_empty(&worker->scheduled));
c8e55f36 2690
e22bee78 2691 /*
a9ab775b
TH
2692 * Finish PREP stage. We're guaranteed to have at least one idle
2693 * worker or that someone else has already assumed the manager
2694 * role. This is where @worker starts participating in concurrency
2695 * management if applicable and concurrency management is restored
2696 * after being rebound. See rebind_workers() for details.
e22bee78 2697 */
a9ab775b 2698 worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
e22bee78
TH
2699
2700 do {
c8e55f36 2701 struct work_struct *work =
bd7bdd43 2702 list_first_entry(&pool->worklist,
c8e55f36
TH
2703 struct work_struct, entry);
2704
c0ab017d
TH
2705 move_linked_works(work, &worker->scheduled, NULL);
2706 process_scheduled_works(worker);
63d95a91 2707 } while (keep_working(pool));
e22bee78 2708
228f1d00 2709 worker_set_flags(worker, WORKER_PREP);
d313dd85 2710sleep:
c8e55f36 2711 /*
d565ed63
TH
2712 * pool->lock is held and there's no work to process and no need to
2713 * manage, sleep. Workers are woken up only while holding
2714 * pool->lock or from local cpu, so setting the current state
2715 * before releasing pool->lock is enough to prevent losing any
2716 * event.
c8e55f36
TH
2717 */
2718 worker_enter_idle(worker);
c5a94a61 2719 __set_current_state(TASK_IDLE);
a9b8a985 2720 raw_spin_unlock_irq(&pool->lock);
c8e55f36
TH
2721 schedule();
2722 goto woke_up;
1da177e4
LT
2723}
2724
e22bee78
TH
2725/**
2726 * rescuer_thread - the rescuer thread function
111c225a 2727 * @__rescuer: self
e22bee78
TH
2728 *
2729 * Workqueue rescuer thread function. There's one rescuer for each
493008a8 2730 * workqueue which has WQ_MEM_RECLAIM set.
e22bee78 2731 *
706026c2 2732 * Regular work processing on a pool may block trying to create a new
e22bee78
TH
2733 * worker which uses GFP_KERNEL allocation which has slight chance of
2734 * developing into deadlock if some works currently on the same queue
2735 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2736 * the problem rescuer solves.
2737 *
706026c2
TH
2738 * When such condition is possible, the pool summons rescuers of all
2739 * workqueues which have works queued on the pool and let them process
e22bee78
TH
2740 * those works so that forward progress can be guaranteed.
2741 *
2742 * This should happen rarely.
d185af30
YB
2743 *
2744 * Return: 0
e22bee78 2745 */
111c225a 2746static int rescuer_thread(void *__rescuer)
e22bee78 2747{
111c225a
TH
2748 struct worker *rescuer = __rescuer;
2749 struct workqueue_struct *wq = rescuer->rescue_wq;
e22bee78 2750 struct list_head *scheduled = &rescuer->scheduled;
4d595b86 2751 bool should_stop;
e22bee78
TH
2752
2753 set_user_nice(current, RESCUER_NICE_LEVEL);
111c225a
TH
2754
2755 /*
2756 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2757 * doesn't participate in concurrency management.
2758 */
197f6acc 2759 set_pf_worker(true);
e22bee78 2760repeat:
c5a94a61 2761 set_current_state(TASK_IDLE);
e22bee78 2762
4d595b86
LJ
2763 /*
2764 * By the time the rescuer is requested to stop, the workqueue
2765 * shouldn't have any work pending, but @wq->maydays may still have
2766 * pwq(s) queued. This can happen by non-rescuer workers consuming
2767 * all the work items before the rescuer got to them. Go through
2768 * @wq->maydays processing before acting on should_stop so that the
2769 * list is always empty on exit.
2770 */
2771 should_stop = kthread_should_stop();
e22bee78 2772
493a1724 2773 /* see whether any pwq is asking for help */
a9b8a985 2774 raw_spin_lock_irq(&wq_mayday_lock);
493a1724
TH
2775
2776 while (!list_empty(&wq->maydays)) {
2777 struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2778 struct pool_workqueue, mayday_node);
112202d9 2779 struct worker_pool *pool = pwq->pool;
e22bee78
TH
2780 struct work_struct *work, *n;
2781
2782 __set_current_state(TASK_RUNNING);
493a1724
TH
2783 list_del_init(&pwq->mayday_node);
2784
a9b8a985 2785 raw_spin_unlock_irq(&wq_mayday_lock);
e22bee78 2786
51697d39
LJ
2787 worker_attach_to_pool(rescuer, pool);
2788
a9b8a985 2789 raw_spin_lock_irq(&pool->lock);
e22bee78
TH
2790
2791 /*
2792 * Slurp in all works issued via this workqueue and
2793 * process'em.
2794 */
0479c8c5 2795 WARN_ON_ONCE(!list_empty(scheduled));
82607adc
TH
2796 list_for_each_entry_safe(work, n, &pool->worklist, entry) {
2797 if (get_work_pwq(work) == pwq) {
e22bee78 2798 move_linked_works(work, scheduled, &n);
725e8ec5 2799 pwq->stats[PWQ_STAT_RESCUED]++;
82607adc 2800 }
82607adc 2801 }
e22bee78 2802
008847f6
N
2803 if (!list_empty(scheduled)) {
2804 process_scheduled_works(rescuer);
2805
2806 /*
2807 * The above execution of rescued work items could
2808 * have created more to rescue through
f97a4a1a 2809 * pwq_activate_first_inactive() or chained
008847f6
N
2810 * queueing. Let's put @pwq back on mayday list so
2811 * that such back-to-back work items, which may be
2812 * being used to relieve memory pressure, don't
2813 * incur MAYDAY_INTERVAL delay inbetween.
2814 */
4f3f4cf3 2815 if (pwq->nr_active && need_to_create_worker(pool)) {
a9b8a985 2816 raw_spin_lock(&wq_mayday_lock);
e66b39af
TH
2817 /*
2818 * Queue iff we aren't racing destruction
2819 * and somebody else hasn't queued it already.
2820 */
2821 if (wq->rescuer && list_empty(&pwq->mayday_node)) {
2822 get_pwq(pwq);
2823 list_add_tail(&pwq->mayday_node, &wq->maydays);
2824 }
a9b8a985 2825 raw_spin_unlock(&wq_mayday_lock);
008847f6
N
2826 }
2827 }
7576958a 2828
77668c8b
LJ
2829 /*
2830 * Put the reference grabbed by send_mayday(). @pool won't
13b1d625 2831 * go away while we're still attached to it.
77668c8b
LJ
2832 */
2833 put_pwq(pwq);
2834
7576958a 2835 /*
d8ca83e6 2836 * Leave this pool. If need_more_worker() is %true, notify a
7576958a
TH
2837 * regular worker; otherwise, we end up with 0 concurrency
2838 * and stalling the execution.
2839 */
d8ca83e6 2840 if (need_more_worker(pool))
63d95a91 2841 wake_up_worker(pool);
7576958a 2842
a9b8a985 2843 raw_spin_unlock_irq(&pool->lock);
13b1d625 2844
a2d812a2 2845 worker_detach_from_pool(rescuer);
13b1d625 2846
a9b8a985 2847 raw_spin_lock_irq(&wq_mayday_lock);
e22bee78
TH
2848 }
2849
a9b8a985 2850 raw_spin_unlock_irq(&wq_mayday_lock);
493a1724 2851
4d595b86
LJ
2852 if (should_stop) {
2853 __set_current_state(TASK_RUNNING);
197f6acc 2854 set_pf_worker(false);
4d595b86
LJ
2855 return 0;
2856 }
2857
111c225a
TH
2858 /* rescuers should never participate in concurrency management */
2859 WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
e22bee78
TH
2860 schedule();
2861 goto repeat;
1da177e4
LT
2862}
2863
fca839c0
TH
2864/**
2865 * check_flush_dependency - check for flush dependency sanity
2866 * @target_wq: workqueue being flushed
2867 * @target_work: work item being flushed (NULL for workqueue flushes)
2868 *
2869 * %current is trying to flush the whole @target_wq or @target_work on it.
2870 * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
2871 * reclaiming memory or running on a workqueue which doesn't have
2872 * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
2873 * a deadlock.
2874 */
2875static void check_flush_dependency(struct workqueue_struct *target_wq,
2876 struct work_struct *target_work)
2877{
2878 work_func_t target_func = target_work ? target_work->func : NULL;
2879 struct worker *worker;
2880
2881 if (target_wq->flags & WQ_MEM_RECLAIM)
2882 return;
2883
2884 worker = current_wq_worker();
2885
2886 WARN_ONCE(current->flags & PF_MEMALLOC,
d75f773c 2887 "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps",
fca839c0 2888 current->pid, current->comm, target_wq->name, target_func);
23d11a58
TH
2889 WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
2890 (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
d75f773c 2891 "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps",
fca839c0
TH
2892 worker->current_pwq->wq->name, worker->current_func,
2893 target_wq->name, target_func);
2894}
2895
fc2e4d70
ON
2896struct wq_barrier {
2897 struct work_struct work;
2898 struct completion done;
2607d7a6 2899 struct task_struct *task; /* purely informational */
fc2e4d70
ON
2900};
2901
2902static void wq_barrier_func(struct work_struct *work)
2903{
2904 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2905 complete(&barr->done);
2906}
2907
4690c4ab
TH
2908/**
2909 * insert_wq_barrier - insert a barrier work
112202d9 2910 * @pwq: pwq to insert barrier into
4690c4ab 2911 * @barr: wq_barrier to insert
affee4b2
TH
2912 * @target: target work to attach @barr to
2913 * @worker: worker currently executing @target, NULL if @target is not executing
4690c4ab 2914 *
affee4b2
TH
2915 * @barr is linked to @target such that @barr is completed only after
2916 * @target finishes execution. Please note that the ordering
2917 * guarantee is observed only with respect to @target and on the local
2918 * cpu.
2919 *
2920 * Currently, a queued barrier can't be canceled. This is because
2921 * try_to_grab_pending() can't determine whether the work to be
2922 * grabbed is at the head of the queue and thus can't clear LINKED
2923 * flag of the previous work while there must be a valid next work
2924 * after a work with LINKED flag set.
2925 *
2926 * Note that when @worker is non-NULL, @target may be modified
112202d9 2927 * underneath us, so we can't reliably determine pwq from @target.
4690c4ab
TH
2928 *
2929 * CONTEXT:
a9b8a985 2930 * raw_spin_lock_irq(pool->lock).
4690c4ab 2931 */
112202d9 2932static void insert_wq_barrier(struct pool_workqueue *pwq,
affee4b2
TH
2933 struct wq_barrier *barr,
2934 struct work_struct *target, struct worker *worker)
fc2e4d70 2935{
d812796e
LJ
2936 unsigned int work_flags = 0;
2937 unsigned int work_color;
affee4b2 2938 struct list_head *head;
affee4b2 2939
dc186ad7 2940 /*
d565ed63 2941 * debugobject calls are safe here even with pool->lock locked
dc186ad7
TG
2942 * as we know for sure that this will not trigger any of the
2943 * checks and call back into the fixup functions where we
2944 * might deadlock.
2945 */
ca1cab37 2946 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
22df02bb 2947 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
52fa5bc5 2948
fd1a5b04
BP
2949 init_completion_map(&barr->done, &target->lockdep_map);
2950
2607d7a6 2951 barr->task = current;
83c22520 2952
018f3a13
LJ
2953 /* The barrier work item does not participate in pwq->nr_active. */
2954 work_flags |= WORK_STRUCT_INACTIVE;
2955
affee4b2
TH
2956 /*
2957 * If @target is currently being executed, schedule the
2958 * barrier to the worker; otherwise, put it after @target.
2959 */
d812796e 2960 if (worker) {
affee4b2 2961 head = worker->scheduled.next;
d812796e
LJ
2962 work_color = worker->current_color;
2963 } else {
affee4b2
TH
2964 unsigned long *bits = work_data_bits(target);
2965
2966 head = target->entry.next;
2967 /* there can already be other linked works, inherit and set */
d21cece0 2968 work_flags |= *bits & WORK_STRUCT_LINKED;
d812796e 2969 work_color = get_work_color(*bits);
affee4b2
TH
2970 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2971 }
2972
d812796e
LJ
2973 pwq->nr_in_flight[work_color]++;
2974 work_flags |= work_color_to_flags(work_color);
2975
d21cece0 2976 insert_work(pwq, &barr->work, head, work_flags);
fc2e4d70
ON
2977}
2978
73f53c4a 2979/**
112202d9 2980 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
73f53c4a
TH
2981 * @wq: workqueue being flushed
2982 * @flush_color: new flush color, < 0 for no-op
2983 * @work_color: new work color, < 0 for no-op
2984 *
112202d9 2985 * Prepare pwqs for workqueue flushing.
73f53c4a 2986 *
112202d9
TH
2987 * If @flush_color is non-negative, flush_color on all pwqs should be
2988 * -1. If no pwq has in-flight commands at the specified color, all
2989 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
2990 * has in flight commands, its pwq->flush_color is set to
2991 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
73f53c4a
TH
2992 * wakeup logic is armed and %true is returned.
2993 *
2994 * The caller should have initialized @wq->first_flusher prior to
2995 * calling this function with non-negative @flush_color. If
2996 * @flush_color is negative, no flush color update is done and %false
2997 * is returned.
2998 *
112202d9 2999 * If @work_color is non-negative, all pwqs should have the same
73f53c4a
TH
3000 * work_color which is previous to @work_color and all will be
3001 * advanced to @work_color.
3002 *
3003 * CONTEXT:
3c25a55d 3004 * mutex_lock(wq->mutex).
73f53c4a 3005 *
d185af30 3006 * Return:
73f53c4a
TH
3007 * %true if @flush_color >= 0 and there's something to flush. %false
3008 * otherwise.
3009 */
112202d9 3010static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
73f53c4a 3011 int flush_color, int work_color)
1da177e4 3012{
73f53c4a 3013 bool wait = false;
49e3cf44 3014 struct pool_workqueue *pwq;
1da177e4 3015
73f53c4a 3016 if (flush_color >= 0) {
6183c009 3017 WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
112202d9 3018 atomic_set(&wq->nr_pwqs_to_flush, 1);
1da177e4 3019 }
2355b70f 3020
49e3cf44 3021 for_each_pwq(pwq, wq) {
112202d9 3022 struct worker_pool *pool = pwq->pool;
fc2e4d70 3023
a9b8a985 3024 raw_spin_lock_irq(&pool->lock);
83c22520 3025
73f53c4a 3026 if (flush_color >= 0) {
6183c009 3027 WARN_ON_ONCE(pwq->flush_color != -1);
fc2e4d70 3028
112202d9
TH
3029 if (pwq->nr_in_flight[flush_color]) {
3030 pwq->flush_color = flush_color;
3031 atomic_inc(&wq->nr_pwqs_to_flush);
73f53c4a
TH
3032 wait = true;
3033 }
3034 }
1da177e4 3035
73f53c4a 3036 if (work_color >= 0) {
6183c009 3037 WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
112202d9 3038 pwq->work_color = work_color;
73f53c4a 3039 }
1da177e4 3040
a9b8a985 3041 raw_spin_unlock_irq(&pool->lock);
1da177e4 3042 }
2355b70f 3043
112202d9 3044 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
73f53c4a 3045 complete(&wq->first_flusher->done);
14441960 3046
73f53c4a 3047 return wait;
1da177e4
LT
3048}
3049
0fcb78c2 3050/**
c4f135d6 3051 * __flush_workqueue - ensure that any scheduled work has run to completion.
0fcb78c2 3052 * @wq: workqueue to flush
1da177e4 3053 *
c5aa87bb
TH
3054 * This function sleeps until all work items which were queued on entry
3055 * have finished execution, but it is not livelocked by new incoming ones.
1da177e4 3056 */
c4f135d6 3057void __flush_workqueue(struct workqueue_struct *wq)
1da177e4 3058{
73f53c4a
TH
3059 struct wq_flusher this_flusher = {
3060 .list = LIST_HEAD_INIT(this_flusher.list),
3061 .flush_color = -1,
fd1a5b04 3062 .done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map),
73f53c4a
TH
3063 };
3064 int next_color;
1da177e4 3065
3347fa09
TH
3066 if (WARN_ON(!wq_online))
3067 return;
3068
87915adc
JB
3069 lock_map_acquire(&wq->lockdep_map);
3070 lock_map_release(&wq->lockdep_map);
3071
3c25a55d 3072 mutex_lock(&wq->mutex);
73f53c4a
TH
3073
3074 /*
3075 * Start-to-wait phase
3076 */
3077 next_color = work_next_color(wq->work_color);
3078
3079 if (next_color != wq->flush_color) {
3080 /*
3081 * Color space is not full. The current work_color
3082 * becomes our flush_color and work_color is advanced
3083 * by one.
3084 */
6183c009 3085 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
73f53c4a
TH
3086 this_flusher.flush_color = wq->work_color;
3087 wq->work_color = next_color;
3088
3089 if (!wq->first_flusher) {
3090 /* no flush in progress, become the first flusher */
6183c009 3091 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
73f53c4a
TH
3092
3093 wq->first_flusher = &this_flusher;
3094
112202d9 3095 if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
73f53c4a
TH
3096 wq->work_color)) {
3097 /* nothing to flush, done */
3098 wq->flush_color = next_color;
3099 wq->first_flusher = NULL;
3100 goto out_unlock;
3101 }
3102 } else {
3103 /* wait in queue */
6183c009 3104 WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
73f53c4a 3105 list_add_tail(&this_flusher.list, &wq->flusher_queue);
112202d9 3106 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
73f53c4a
TH
3107 }
3108 } else {
3109 /*
3110 * Oops, color space is full, wait on overflow queue.
3111 * The next flush completion will assign us
3112 * flush_color and transfer to flusher_queue.
3113 */
3114 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
3115 }
3116
fca839c0
TH
3117 check_flush_dependency(wq, NULL);
3118
3c25a55d 3119 mutex_unlock(&wq->mutex);
73f53c4a
TH
3120
3121 wait_for_completion(&this_flusher.done);
3122
3123 /*
3124 * Wake-up-and-cascade phase
3125 *
3126 * First flushers are responsible for cascading flushes and
3127 * handling overflow. Non-first flushers can simply return.
3128 */
00d5d15b 3129 if (READ_ONCE(wq->first_flusher) != &this_flusher)
73f53c4a
TH
3130 return;
3131
3c25a55d 3132 mutex_lock(&wq->mutex);
73f53c4a 3133
4ce48b37
TH
3134 /* we might have raced, check again with mutex held */
3135 if (wq->first_flusher != &this_flusher)
3136 goto out_unlock;
3137
00d5d15b 3138 WRITE_ONCE(wq->first_flusher, NULL);
73f53c4a 3139
6183c009
TH
3140 WARN_ON_ONCE(!list_empty(&this_flusher.list));
3141 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
73f53c4a
TH
3142
3143 while (true) {
3144 struct wq_flusher *next, *tmp;
3145
3146 /* complete all the flushers sharing the current flush color */
3147 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
3148 if (next->flush_color != wq->flush_color)
3149 break;
3150 list_del_init(&next->list);
3151 complete(&next->done);
3152 }
3153
6183c009
TH
3154 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
3155 wq->flush_color != work_next_color(wq->work_color));
73f53c4a
TH
3156
3157 /* this flush_color is finished, advance by one */
3158 wq->flush_color = work_next_color(wq->flush_color);
3159
3160 /* one color has been freed, handle overflow queue */
3161 if (!list_empty(&wq->flusher_overflow)) {
3162 /*
3163 * Assign the same color to all overflowed
3164 * flushers, advance work_color and append to
3165 * flusher_queue. This is the start-to-wait
3166 * phase for these overflowed flushers.
3167 */
3168 list_for_each_entry(tmp, &wq->flusher_overflow, list)
3169 tmp->flush_color = wq->work_color;
3170
3171 wq->work_color = work_next_color(wq->work_color);
3172
3173 list_splice_tail_init(&wq->flusher_overflow,
3174 &wq->flusher_queue);
112202d9 3175 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
73f53c4a
TH
3176 }
3177
3178 if (list_empty(&wq->flusher_queue)) {
6183c009 3179 WARN_ON_ONCE(wq->flush_color != wq->work_color);
73f53c4a
TH
3180 break;
3181 }
3182
3183 /*
3184 * Need to flush more colors. Make the next flusher
112202d9 3185 * the new first flusher and arm pwqs.
73f53c4a 3186 */
6183c009
TH
3187 WARN_ON_ONCE(wq->flush_color == wq->work_color);
3188 WARN_ON_ONCE(wq->flush_color != next->flush_color);
73f53c4a
TH
3189
3190 list_del_init(&next->list);
3191 wq->first_flusher = next;
3192
112202d9 3193 if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
73f53c4a
TH
3194 break;
3195
3196 /*
3197 * Meh... this color is already done, clear first
3198 * flusher and repeat cascading.
3199 */
3200 wq->first_flusher = NULL;
3201 }
3202
3203out_unlock:
3c25a55d 3204 mutex_unlock(&wq->mutex);
1da177e4 3205}
c4f135d6 3206EXPORT_SYMBOL(__flush_workqueue);
1da177e4 3207
9c5a2ba7
TH
3208/**
3209 * drain_workqueue - drain a workqueue
3210 * @wq: workqueue to drain
3211 *
3212 * Wait until the workqueue becomes empty. While draining is in progress,
3213 * only chain queueing is allowed. IOW, only currently pending or running
3214 * work items on @wq can queue further work items on it. @wq is flushed
b749b1b6 3215 * repeatedly until it becomes empty. The number of flushing is determined
9c5a2ba7
TH
3216 * by the depth of chaining and should be relatively short. Whine if it
3217 * takes too long.
3218 */
3219void drain_workqueue(struct workqueue_struct *wq)
3220{
3221 unsigned int flush_cnt = 0;
49e3cf44 3222 struct pool_workqueue *pwq;
9c5a2ba7
TH
3223
3224 /*
3225 * __queue_work() needs to test whether there are drainers, is much
3226 * hotter than drain_workqueue() and already looks at @wq->flags.
618b01eb 3227 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
9c5a2ba7 3228 */
87fc741e 3229 mutex_lock(&wq->mutex);
9c5a2ba7 3230 if (!wq->nr_drainers++)
618b01eb 3231 wq->flags |= __WQ_DRAINING;
87fc741e 3232 mutex_unlock(&wq->mutex);
9c5a2ba7 3233reflush:
c4f135d6 3234 __flush_workqueue(wq);
9c5a2ba7 3235
b09f4fd3 3236 mutex_lock(&wq->mutex);
76af4d93 3237
49e3cf44 3238 for_each_pwq(pwq, wq) {
fa2563e4 3239 bool drained;
9c5a2ba7 3240
a9b8a985 3241 raw_spin_lock_irq(&pwq->pool->lock);
f97a4a1a 3242 drained = !pwq->nr_active && list_empty(&pwq->inactive_works);
a9b8a985 3243 raw_spin_unlock_irq(&pwq->pool->lock);
fa2563e4
TT
3244
3245 if (drained)
9c5a2ba7
TH
3246 continue;
3247
3248 if (++flush_cnt == 10 ||
3249 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
e9ad2eb3
SZ
3250 pr_warn("workqueue %s: %s() isn't complete after %u tries\n",
3251 wq->name, __func__, flush_cnt);
76af4d93 3252
b09f4fd3 3253 mutex_unlock(&wq->mutex);
9c5a2ba7
TH
3254 goto reflush;
3255 }
3256
9c5a2ba7 3257 if (!--wq->nr_drainers)
618b01eb 3258 wq->flags &= ~__WQ_DRAINING;
87fc741e 3259 mutex_unlock(&wq->mutex);
9c5a2ba7
TH
3260}
3261EXPORT_SYMBOL_GPL(drain_workqueue);
3262
d6e89786
JB
3263static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
3264 bool from_cancel)
db700897 3265{
affee4b2 3266 struct worker *worker = NULL;
c9e7cf27 3267 struct worker_pool *pool;
112202d9 3268 struct pool_workqueue *pwq;
db700897
ON
3269
3270 might_sleep();
fa1b54e6 3271
24acfb71 3272 rcu_read_lock();
c9e7cf27 3273 pool = get_work_pool(work);
fa1b54e6 3274 if (!pool) {
24acfb71 3275 rcu_read_unlock();
baf59022 3276 return false;
fa1b54e6 3277 }
db700897 3278
a9b8a985 3279 raw_spin_lock_irq(&pool->lock);
0b3dae68 3280 /* see the comment in try_to_grab_pending() with the same code */
112202d9
TH
3281 pwq = get_work_pwq(work);
3282 if (pwq) {
3283 if (unlikely(pwq->pool != pool))
4690c4ab 3284 goto already_gone;
606a5020 3285 } else {
c9e7cf27 3286 worker = find_worker_executing_work(pool, work);
affee4b2 3287 if (!worker)
4690c4ab 3288 goto already_gone;
112202d9 3289 pwq = worker->current_pwq;
606a5020 3290 }
db700897 3291
fca839c0
TH
3292 check_flush_dependency(pwq->wq, work);
3293
112202d9 3294 insert_wq_barrier(pwq, barr, work, worker);
a9b8a985 3295 raw_spin_unlock_irq(&pool->lock);
7a22ad75 3296
e159489b 3297 /*
a1d14934
PZ
3298 * Force a lock recursion deadlock when using flush_work() inside a
3299 * single-threaded or rescuer equipped workqueue.
3300 *
3301 * For single threaded workqueues the deadlock happens when the work
3302 * is after the work issuing the flush_work(). For rescuer equipped
3303 * workqueues the deadlock happens when the rescuer stalls, blocking
3304 * forward progress.
e159489b 3305 */
d6e89786
JB
3306 if (!from_cancel &&
3307 (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)) {
112202d9 3308 lock_map_acquire(&pwq->wq->lockdep_map);
a1d14934
PZ
3309 lock_map_release(&pwq->wq->lockdep_map);
3310 }
24acfb71 3311 rcu_read_unlock();
401a8d04 3312 return true;
4690c4ab 3313already_gone:
a9b8a985 3314 raw_spin_unlock_irq(&pool->lock);
24acfb71 3315 rcu_read_unlock();
401a8d04 3316 return false;
db700897 3317}
baf59022 3318
d6e89786
JB
3319static bool __flush_work(struct work_struct *work, bool from_cancel)
3320{
3321 struct wq_barrier barr;
3322
3323 if (WARN_ON(!wq_online))
3324 return false;
3325
4d43d395
TH
3326 if (WARN_ON(!work->func))
3327 return false;
3328
c0feea59
TH
3329 lock_map_acquire(&work->lockdep_map);
3330 lock_map_release(&work->lockdep_map);
87915adc 3331
d6e89786
JB
3332 if (start_flush_work(work, &barr, from_cancel)) {
3333 wait_for_completion(&barr.done);
3334 destroy_work_on_stack(&barr.work);
3335 return true;
3336 } else {
3337 return false;
3338 }
3339}
3340
baf59022
TH
3341/**
3342 * flush_work - wait for a work to finish executing the last queueing instance
3343 * @work: the work to flush
3344 *
606a5020
TH
3345 * Wait until @work has finished execution. @work is guaranteed to be idle
3346 * on return if it hasn't been requeued since flush started.
baf59022 3347 *
d185af30 3348 * Return:
baf59022
TH
3349 * %true if flush_work() waited for the work to finish execution,
3350 * %false if it was already idle.
3351 */
3352bool flush_work(struct work_struct *work)
3353{
d6e89786 3354 return __flush_work(work, false);
6e84d644 3355}
606a5020 3356EXPORT_SYMBOL_GPL(flush_work);
6e84d644 3357
8603e1b3 3358struct cwt_wait {
ac6424b9 3359 wait_queue_entry_t wait;
8603e1b3
TH
3360 struct work_struct *work;
3361};
3362
ac6424b9 3363static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
8603e1b3
TH
3364{
3365 struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
3366
3367 if (cwait->work != key)
3368 return 0;
3369 return autoremove_wake_function(wait, mode, sync, key);
3370}
3371
36e227d2 3372static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
1f1f642e 3373{
8603e1b3 3374 static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
bbb68dfa 3375 unsigned long flags;
1f1f642e
ON
3376 int ret;
3377
3378 do {
bbb68dfa
TH
3379 ret = try_to_grab_pending(work, is_dwork, &flags);
3380 /*
8603e1b3
TH
3381 * If someone else is already canceling, wait for it to
3382 * finish. flush_work() doesn't work for PREEMPT_NONE
3383 * because we may get scheduled between @work's completion
3384 * and the other canceling task resuming and clearing
3385 * CANCELING - flush_work() will return false immediately
3386 * as @work is no longer busy, try_to_grab_pending() will
3387 * return -ENOENT as @work is still being canceled and the
3388 * other canceling task won't be able to clear CANCELING as
3389 * we're hogging the CPU.
3390 *
3391 * Let's wait for completion using a waitqueue. As this
3392 * may lead to the thundering herd problem, use a custom
3393 * wake function which matches @work along with exclusive
3394 * wait and wakeup.
bbb68dfa 3395 */
8603e1b3
TH
3396 if (unlikely(ret == -ENOENT)) {
3397 struct cwt_wait cwait;
3398
3399 init_wait(&cwait.wait);
3400 cwait.wait.func = cwt_wakefn;
3401 cwait.work = work;
3402
3403 prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
3404 TASK_UNINTERRUPTIBLE);
3405 if (work_is_canceling(work))
3406 schedule();
3407 finish_wait(&cancel_waitq, &cwait.wait);
3408 }
1f1f642e
ON
3409 } while (unlikely(ret < 0));
3410
bbb68dfa
TH
3411 /* tell other tasks trying to grab @work to back off */
3412 mark_work_canceling(work);
3413 local_irq_restore(flags);
3414
3347fa09
TH
3415 /*
3416 * This allows canceling during early boot. We know that @work
3417 * isn't executing.
3418 */
3419 if (wq_online)
d6e89786 3420 __flush_work(work, true);
3347fa09 3421
7a22ad75 3422 clear_work_data(work);
8603e1b3
TH
3423
3424 /*
3425 * Paired with prepare_to_wait() above so that either
3426 * waitqueue_active() is visible here or !work_is_canceling() is
3427 * visible there.
3428 */
3429 smp_mb();
3430 if (waitqueue_active(&cancel_waitq))
3431 __wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
3432
1f1f642e
ON
3433 return ret;
3434}
3435
6e84d644 3436/**
401a8d04
TH
3437 * cancel_work_sync - cancel a work and wait for it to finish
3438 * @work: the work to cancel
6e84d644 3439 *
401a8d04
TH
3440 * Cancel @work and wait for its execution to finish. This function
3441 * can be used even if the work re-queues itself or migrates to
3442 * another workqueue. On return from this function, @work is
3443 * guaranteed to be not pending or executing on any CPU.
1f1f642e 3444 *
401a8d04
TH
3445 * cancel_work_sync(&delayed_work->work) must not be used for
3446 * delayed_work's. Use cancel_delayed_work_sync() instead.
6e84d644 3447 *
401a8d04 3448 * The caller must ensure that the workqueue on which @work was last
6e84d644 3449 * queued can't be destroyed before this function returns.
401a8d04 3450 *
d185af30 3451 * Return:
401a8d04 3452 * %true if @work was pending, %false otherwise.
6e84d644 3453 */
401a8d04 3454bool cancel_work_sync(struct work_struct *work)
6e84d644 3455{
36e227d2 3456 return __cancel_work_timer(work, false);
b89deed3 3457}
28e53bdd 3458EXPORT_SYMBOL_GPL(cancel_work_sync);
b89deed3 3459
6e84d644 3460/**
401a8d04
TH
3461 * flush_delayed_work - wait for a dwork to finish executing the last queueing
3462 * @dwork: the delayed work to flush
6e84d644 3463 *
401a8d04
TH
3464 * Delayed timer is cancelled and the pending work is queued for
3465 * immediate execution. Like flush_work(), this function only
3466 * considers the last queueing instance of @dwork.
1f1f642e 3467 *
d185af30 3468 * Return:
401a8d04
TH
3469 * %true if flush_work() waited for the work to finish execution,
3470 * %false if it was already idle.
6e84d644 3471 */
401a8d04
TH
3472bool flush_delayed_work(struct delayed_work *dwork)
3473{
8930caba 3474 local_irq_disable();
401a8d04 3475 if (del_timer_sync(&dwork->timer))
60c057bc 3476 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
8930caba 3477 local_irq_enable();
401a8d04
TH
3478 return flush_work(&dwork->work);
3479}
3480EXPORT_SYMBOL(flush_delayed_work);
3481
05f0fe6b
TH
3482/**
3483 * flush_rcu_work - wait for a rwork to finish executing the last queueing
3484 * @rwork: the rcu work to flush
3485 *
3486 * Return:
3487 * %true if flush_rcu_work() waited for the work to finish execution,
3488 * %false if it was already idle.
3489 */
3490bool flush_rcu_work(struct rcu_work *rwork)
3491{
3492 if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
3493 rcu_barrier();
3494 flush_work(&rwork->work);
3495 return true;
3496 } else {
3497 return flush_work(&rwork->work);
3498 }
3499}
3500EXPORT_SYMBOL(flush_rcu_work);
3501
f72b8792
JA
3502static bool __cancel_work(struct work_struct *work, bool is_dwork)
3503{
3504 unsigned long flags;
3505 int ret;
3506
3507 do {
3508 ret = try_to_grab_pending(work, is_dwork, &flags);
3509 } while (unlikely(ret == -EAGAIN));
3510
3511 if (unlikely(ret < 0))
3512 return false;
3513
3514 set_work_pool_and_clear_pending(work, get_work_pool_id(work));
3515 local_irq_restore(flags);
3516 return ret;
3517}
3518
73b4b532
AG
3519/*
3520 * See cancel_delayed_work()
3521 */
3522bool cancel_work(struct work_struct *work)
3523{
3524 return __cancel_work(work, false);
3525}
3526EXPORT_SYMBOL(cancel_work);
3527
09383498 3528/**
57b30ae7
TH
3529 * cancel_delayed_work - cancel a delayed work
3530 * @dwork: delayed_work to cancel
09383498 3531 *
d185af30
YB
3532 * Kill off a pending delayed_work.
3533 *
3534 * Return: %true if @dwork was pending and canceled; %false if it wasn't
3535 * pending.
3536 *
3537 * Note:
3538 * The work callback function may still be running on return, unless
3539 * it returns %true and the work doesn't re-arm itself. Explicitly flush or
3540 * use cancel_delayed_work_sync() to wait on it.
09383498 3541 *
57b30ae7 3542 * This function is safe to call from any context including IRQ handler.
09383498 3543 */
57b30ae7 3544bool cancel_delayed_work(struct delayed_work *dwork)
09383498 3545{
f72b8792 3546 return __cancel_work(&dwork->work, true);
09383498 3547}
57b30ae7 3548EXPORT_SYMBOL(cancel_delayed_work);
09383498 3549
401a8d04
TH
3550/**
3551 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3552 * @dwork: the delayed work cancel
3553 *
3554 * This is cancel_work_sync() for delayed works.
3555 *
d185af30 3556 * Return:
401a8d04
TH
3557 * %true if @dwork was pending, %false otherwise.
3558 */
3559bool cancel_delayed_work_sync(struct delayed_work *dwork)
6e84d644 3560{
36e227d2 3561 return __cancel_work_timer(&dwork->work, true);
6e84d644 3562}
f5a421a4 3563EXPORT_SYMBOL(cancel_delayed_work_sync);
1da177e4 3564
b6136773 3565/**
31ddd871 3566 * schedule_on_each_cpu - execute a function synchronously on each online CPU
b6136773 3567 * @func: the function to call
b6136773 3568 *
31ddd871
TH
3569 * schedule_on_each_cpu() executes @func on each online CPU using the
3570 * system workqueue and blocks until all CPUs have completed.
b6136773 3571 * schedule_on_each_cpu() is very slow.
31ddd871 3572 *
d185af30 3573 * Return:
31ddd871 3574 * 0 on success, -errno on failure.
b6136773 3575 */
65f27f38 3576int schedule_on_each_cpu(work_func_t func)
15316ba8
CL
3577{
3578 int cpu;
38f51568 3579 struct work_struct __percpu *works;
15316ba8 3580
b6136773
AM
3581 works = alloc_percpu(struct work_struct);
3582 if (!works)
15316ba8 3583 return -ENOMEM;
b6136773 3584
ffd8bea8 3585 cpus_read_lock();
93981800 3586
15316ba8 3587 for_each_online_cpu(cpu) {
9bfb1839
IM
3588 struct work_struct *work = per_cpu_ptr(works, cpu);
3589
3590 INIT_WORK(work, func);
b71ab8c2 3591 schedule_work_on(cpu, work);
65a64464 3592 }
93981800
TH
3593
3594 for_each_online_cpu(cpu)
3595 flush_work(per_cpu_ptr(works, cpu));
3596
ffd8bea8 3597 cpus_read_unlock();
b6136773 3598 free_percpu(works);
15316ba8
CL
3599 return 0;
3600}
3601
1fa44eca
JB
3602/**
3603 * execute_in_process_context - reliably execute the routine with user context
3604 * @fn: the function to execute
1fa44eca
JB
3605 * @ew: guaranteed storage for the execute work structure (must
3606 * be available when the work executes)
3607 *
3608 * Executes the function immediately if process context is available,
3609 * otherwise schedules the function for delayed execution.
3610 *
d185af30 3611 * Return: 0 - function was executed
1fa44eca
JB
3612 * 1 - function was scheduled for execution
3613 */
65f27f38 3614int execute_in_process_context(work_func_t fn, struct execute_work *ew)
1fa44eca
JB
3615{
3616 if (!in_interrupt()) {
65f27f38 3617 fn(&ew->work);
1fa44eca
JB
3618 return 0;
3619 }
3620
65f27f38 3621 INIT_WORK(&ew->work, fn);
1fa44eca
JB
3622 schedule_work(&ew->work);
3623
3624 return 1;
3625}
3626EXPORT_SYMBOL_GPL(execute_in_process_context);
3627
6ba94429
FW
3628/**
3629 * free_workqueue_attrs - free a workqueue_attrs
3630 * @attrs: workqueue_attrs to free
226223ab 3631 *
6ba94429 3632 * Undo alloc_workqueue_attrs().
226223ab 3633 */
513c98d0 3634void free_workqueue_attrs(struct workqueue_attrs *attrs)
226223ab 3635{
6ba94429
FW
3636 if (attrs) {
3637 free_cpumask_var(attrs->cpumask);
3638 kfree(attrs);
3639 }
226223ab
TH
3640}
3641
6ba94429
FW
3642/**
3643 * alloc_workqueue_attrs - allocate a workqueue_attrs
6ba94429
FW
3644 *
3645 * Allocate a new workqueue_attrs, initialize with default settings and
3646 * return it.
3647 *
3648 * Return: The allocated new workqueue_attr on success. %NULL on failure.
3649 */
513c98d0 3650struct workqueue_attrs *alloc_workqueue_attrs(void)
226223ab 3651{
6ba94429 3652 struct workqueue_attrs *attrs;
226223ab 3653
be69d00d 3654 attrs = kzalloc(sizeof(*attrs), GFP_KERNEL);
6ba94429
FW
3655 if (!attrs)
3656 goto fail;
be69d00d 3657 if (!alloc_cpumask_var(&attrs->cpumask, GFP_KERNEL))
6ba94429
FW
3658 goto fail;
3659
3660 cpumask_copy(attrs->cpumask, cpu_possible_mask);
3661 return attrs;
3662fail:
3663 free_workqueue_attrs(attrs);
3664 return NULL;
226223ab
TH
3665}
3666
6ba94429
FW
3667static void copy_workqueue_attrs(struct workqueue_attrs *to,
3668 const struct workqueue_attrs *from)
226223ab 3669{
6ba94429
FW
3670 to->nice = from->nice;
3671 cpumask_copy(to->cpumask, from->cpumask);
3672 /*
3673 * Unlike hash and equality test, this function doesn't ignore
af73f5c9
TH
3674 * ->ordered as it is used for both pool and wq attrs. Instead,
3675 * get_unbound_pool() explicitly clears ->ordered after copying.
6ba94429 3676 */
af73f5c9 3677 to->ordered = from->ordered;
226223ab
TH
3678}
3679
6ba94429
FW
3680/* hash value of the content of @attr */
3681static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
226223ab 3682{
6ba94429 3683 u32 hash = 0;
226223ab 3684
6ba94429
FW
3685 hash = jhash_1word(attrs->nice, hash);
3686 hash = jhash(cpumask_bits(attrs->cpumask),
3687 BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
3688 return hash;
226223ab 3689}
226223ab 3690
6ba94429
FW
3691/* content equality test */
3692static bool wqattrs_equal(const struct workqueue_attrs *a,
3693 const struct workqueue_attrs *b)
226223ab 3694{
6ba94429
FW
3695 if (a->nice != b->nice)
3696 return false;
3697 if (!cpumask_equal(a->cpumask, b->cpumask))
3698 return false;
3699 return true;
226223ab
TH
3700}
3701
6ba94429
FW
3702/**
3703 * init_worker_pool - initialize a newly zalloc'd worker_pool
3704 * @pool: worker_pool to initialize
3705 *
402dd89d 3706 * Initialize a newly zalloc'd @pool. It also allocates @pool->attrs.
6ba94429
FW
3707 *
3708 * Return: 0 on success, -errno on failure. Even on failure, all fields
3709 * inside @pool proper are initialized and put_unbound_pool() can be called
3710 * on @pool safely to release it.
3711 */
3712static int init_worker_pool(struct worker_pool *pool)
226223ab 3713{
a9b8a985 3714 raw_spin_lock_init(&pool->lock);
6ba94429
FW
3715 pool->id = -1;
3716 pool->cpu = -1;
3717 pool->node = NUMA_NO_NODE;
3718 pool->flags |= POOL_DISASSOCIATED;
82607adc 3719 pool->watchdog_ts = jiffies;
6ba94429
FW
3720 INIT_LIST_HEAD(&pool->worklist);
3721 INIT_LIST_HEAD(&pool->idle_list);
3722 hash_init(pool->busy_hash);
226223ab 3723
32a6c723 3724 timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
3f959aa3 3725 INIT_WORK(&pool->idle_cull_work, idle_cull_fn);
226223ab 3726
32a6c723 3727 timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
226223ab 3728
6ba94429 3729 INIT_LIST_HEAD(&pool->workers);
e02b9312 3730 INIT_LIST_HEAD(&pool->dying_workers);
226223ab 3731
6ba94429
FW
3732 ida_init(&pool->worker_ida);
3733 INIT_HLIST_NODE(&pool->hash_node);
3734 pool->refcnt = 1;
226223ab 3735
6ba94429 3736 /* shouldn't fail above this point */
be69d00d 3737 pool->attrs = alloc_workqueue_attrs();
6ba94429
FW
3738 if (!pool->attrs)
3739 return -ENOMEM;
3740 return 0;
226223ab
TH
3741}
3742
669de8bd
BVA
3743#ifdef CONFIG_LOCKDEP
3744static void wq_init_lockdep(struct workqueue_struct *wq)
3745{
3746 char *lock_name;
3747
3748 lockdep_register_key(&wq->key);
3749 lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name);
3750 if (!lock_name)
3751 lock_name = wq->name;
69a106c0
QC
3752
3753 wq->lock_name = lock_name;
669de8bd
BVA
3754 lockdep_init_map(&wq->lockdep_map, lock_name, &wq->key, 0);
3755}
3756
3757static void wq_unregister_lockdep(struct workqueue_struct *wq)
3758{
3759 lockdep_unregister_key(&wq->key);
3760}
3761
3762static void wq_free_lockdep(struct workqueue_struct *wq)
3763{
3764 if (wq->lock_name != wq->name)
3765 kfree(wq->lock_name);
3766}
3767#else
3768static void wq_init_lockdep(struct workqueue_struct *wq)
3769{
3770}
3771
3772static void wq_unregister_lockdep(struct workqueue_struct *wq)
3773{
3774}
3775
3776static void wq_free_lockdep(struct workqueue_struct *wq)
3777{
3778}
3779#endif
3780
6ba94429 3781static void rcu_free_wq(struct rcu_head *rcu)
226223ab 3782{
6ba94429
FW
3783 struct workqueue_struct *wq =
3784 container_of(rcu, struct workqueue_struct, rcu);
226223ab 3785
669de8bd 3786 wq_free_lockdep(wq);
636b927e
TH
3787 free_percpu(wq->cpu_pwq);
3788 free_workqueue_attrs(wq->unbound_attrs);
6ba94429 3789 kfree(wq);
226223ab
TH
3790}
3791
6ba94429 3792static void rcu_free_pool(struct rcu_head *rcu)
226223ab 3793{
6ba94429 3794 struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
226223ab 3795
6ba94429
FW
3796 ida_destroy(&pool->worker_ida);
3797 free_workqueue_attrs(pool->attrs);
3798 kfree(pool);
226223ab
TH
3799}
3800
6ba94429
FW
3801/**
3802 * put_unbound_pool - put a worker_pool
3803 * @pool: worker_pool to put
3804 *
24acfb71 3805 * Put @pool. If its refcnt reaches zero, it gets destroyed in RCU
6ba94429
FW
3806 * safe manner. get_unbound_pool() calls this function on its failure path
3807 * and this function should be able to release pools which went through,
3808 * successfully or not, init_worker_pool().
3809 *
3810 * Should be called with wq_pool_mutex held.
3811 */
3812static void put_unbound_pool(struct worker_pool *pool)
226223ab 3813{
6ba94429
FW
3814 DECLARE_COMPLETION_ONSTACK(detach_completion);
3815 struct worker *worker;
9680540c 3816 LIST_HEAD(cull_list);
e02b9312 3817
6ba94429 3818 lockdep_assert_held(&wq_pool_mutex);
226223ab 3819
6ba94429
FW
3820 if (--pool->refcnt)
3821 return;
226223ab 3822
6ba94429
FW
3823 /* sanity checks */
3824 if (WARN_ON(!(pool->cpu < 0)) ||
3825 WARN_ON(!list_empty(&pool->worklist)))
3826 return;
226223ab 3827
6ba94429
FW
3828 /* release id and unhash */
3829 if (pool->id >= 0)
3830 idr_remove(&worker_pool_idr, pool->id);
3831 hash_del(&pool->hash_node);
d55262c4 3832
6ba94429 3833 /*
692b4825
TH
3834 * Become the manager and destroy all workers. This prevents
3835 * @pool's workers from blocking on attach_mutex. We're the last
3836 * manager and @pool gets freed with the flag set.
9ab03be4
VS
3837 *
3838 * Having a concurrent manager is quite unlikely to happen as we can
3839 * only get here with
3840 * pwq->refcnt == pool->refcnt == 0
3841 * which implies no work queued to the pool, which implies no worker can
3842 * become the manager. However a worker could have taken the role of
3843 * manager before the refcnts dropped to 0, since maybe_create_worker()
3844 * drops pool->lock
6ba94429 3845 */
9ab03be4
VS
3846 while (true) {
3847 rcuwait_wait_event(&manager_wait,
3848 !(pool->flags & POOL_MANAGER_ACTIVE),
3849 TASK_UNINTERRUPTIBLE);
e02b9312
VS
3850
3851 mutex_lock(&wq_pool_attach_mutex);
9ab03be4
VS
3852 raw_spin_lock_irq(&pool->lock);
3853 if (!(pool->flags & POOL_MANAGER_ACTIVE)) {
3854 pool->flags |= POOL_MANAGER_ACTIVE;
3855 break;
3856 }
3857 raw_spin_unlock_irq(&pool->lock);
e02b9312 3858 mutex_unlock(&wq_pool_attach_mutex);
9ab03be4 3859 }
692b4825 3860
6ba94429 3861 while ((worker = first_idle_worker(pool)))
e02b9312 3862 set_worker_dying(worker, &cull_list);
6ba94429 3863 WARN_ON(pool->nr_workers || pool->nr_idle);
a9b8a985 3864 raw_spin_unlock_irq(&pool->lock);
d55262c4 3865
e02b9312
VS
3866 wake_dying_workers(&cull_list);
3867
3868 if (!list_empty(&pool->workers) || !list_empty(&pool->dying_workers))
6ba94429 3869 pool->detach_completion = &detach_completion;
1258fae7 3870 mutex_unlock(&wq_pool_attach_mutex);
226223ab 3871
6ba94429
FW
3872 if (pool->detach_completion)
3873 wait_for_completion(pool->detach_completion);
226223ab 3874
6ba94429
FW
3875 /* shut down the timers */
3876 del_timer_sync(&pool->idle_timer);
3f959aa3 3877 cancel_work_sync(&pool->idle_cull_work);
6ba94429 3878 del_timer_sync(&pool->mayday_timer);
226223ab 3879
24acfb71 3880 /* RCU protected to allow dereferences from get_work_pool() */
25b00775 3881 call_rcu(&pool->rcu, rcu_free_pool);
226223ab
TH
3882}
3883
3884/**
6ba94429
FW
3885 * get_unbound_pool - get a worker_pool with the specified attributes
3886 * @attrs: the attributes of the worker_pool to get
226223ab 3887 *
6ba94429
FW
3888 * Obtain a worker_pool which has the same attributes as @attrs, bump the
3889 * reference count and return it. If there already is a matching
3890 * worker_pool, it will be used; otherwise, this function attempts to
3891 * create a new one.
226223ab 3892 *
6ba94429 3893 * Should be called with wq_pool_mutex held.
226223ab 3894 *
6ba94429
FW
3895 * Return: On success, a worker_pool with the same attributes as @attrs.
3896 * On failure, %NULL.
226223ab 3897 */
6ba94429 3898static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
226223ab 3899{
6ba94429
FW
3900 u32 hash = wqattrs_hash(attrs);
3901 struct worker_pool *pool;
fef59c9c
TH
3902 int pod;
3903 int target_pod = NUMA_NO_NODE;
226223ab 3904
6ba94429 3905 lockdep_assert_held(&wq_pool_mutex);
226223ab 3906
6ba94429
FW
3907 /* do we already have a matching pool? */
3908 hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
3909 if (wqattrs_equal(pool->attrs, attrs)) {
3910 pool->refcnt++;
3911 return pool;
3912 }
3913 }
226223ab 3914
fef59c9c
TH
3915 /* if cpumask is contained inside a pod, we belong to that pod */
3916 if (wq_pod_enabled) {
3917 for_each_node(pod) {
3918 if (cpumask_subset(attrs->cpumask, wq_pod_cpus[pod])) {
3919 target_pod = pod;
e2273584
XP
3920 break;
3921 }
3922 }
3923 }
3924
6ba94429 3925 /* nope, create a new one */
fef59c9c 3926 pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, target_pod);
6ba94429
FW
3927 if (!pool || init_worker_pool(pool) < 0)
3928 goto fail;
3929
6ba94429 3930 copy_workqueue_attrs(pool->attrs, attrs);
fef59c9c 3931 pool->node = target_pod;
226223ab
TH
3932
3933 /*
af73f5c9 3934 * ordered isn't a worker_pool attribute, always clear it. See
6ba94429 3935 * 'struct workqueue_attrs' comments for detail.
226223ab 3936 */
af73f5c9 3937 pool->attrs->ordered = false;
226223ab 3938
6ba94429
FW
3939 if (worker_pool_assign_id(pool) < 0)
3940 goto fail;
226223ab 3941
6ba94429 3942 /* create and start the initial worker */
3347fa09 3943 if (wq_online && !create_worker(pool))
6ba94429 3944 goto fail;
226223ab 3945
6ba94429
FW
3946 /* install */
3947 hash_add(unbound_pool_hash, &pool->hash_node, hash);
226223ab 3948
6ba94429
FW
3949 return pool;
3950fail:
3951 if (pool)
3952 put_unbound_pool(pool);
3953 return NULL;
226223ab 3954}
226223ab 3955
6ba94429 3956static void rcu_free_pwq(struct rcu_head *rcu)
7a4e344c 3957{
6ba94429
FW
3958 kmem_cache_free(pwq_cache,
3959 container_of(rcu, struct pool_workqueue, rcu));
7a4e344c
TH
3960}
3961
6ba94429 3962/*
967b494e
TH
3963 * Scheduled on pwq_release_worker by put_pwq() when an unbound pwq hits zero
3964 * refcnt and needs to be destroyed.
7a4e344c 3965 */
687a9aa5 3966static void pwq_release_workfn(struct kthread_work *work)
7a4e344c 3967{
6ba94429 3968 struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
687a9aa5 3969 release_work);
6ba94429
FW
3970 struct workqueue_struct *wq = pwq->wq;
3971 struct worker_pool *pool = pwq->pool;
b42b0bdd 3972 bool is_last = false;
7a4e344c 3973
b42b0bdd 3974 /*
687a9aa5 3975 * When @pwq is not linked, it doesn't hold any reference to the
b42b0bdd
YY
3976 * @wq, and @wq is invalid to access.
3977 */
3978 if (!list_empty(&pwq->pwqs_node)) {
b42b0bdd
YY
3979 mutex_lock(&wq->mutex);
3980 list_del_rcu(&pwq->pwqs_node);
3981 is_last = list_empty(&wq->pwqs);
3982 mutex_unlock(&wq->mutex);
3983 }
6ba94429 3984
687a9aa5
TH
3985 if (wq->flags & WQ_UNBOUND) {
3986 mutex_lock(&wq_pool_mutex);
3987 put_unbound_pool(pool);
3988 mutex_unlock(&wq_pool_mutex);
3989 }
6ba94429 3990
25b00775 3991 call_rcu(&pwq->rcu, rcu_free_pwq);
7a4e344c 3992
2865a8fb 3993 /*
6ba94429
FW
3994 * If we're the last pwq going away, @wq is already dead and no one
3995 * is gonna access it anymore. Schedule RCU free.
2865a8fb 3996 */
669de8bd
BVA
3997 if (is_last) {
3998 wq_unregister_lockdep(wq);
25b00775 3999 call_rcu(&wq->rcu, rcu_free_wq);
669de8bd 4000 }
29c91e99
TH
4001}
4002
7a4e344c 4003/**
6ba94429
FW
4004 * pwq_adjust_max_active - update a pwq's max_active to the current setting
4005 * @pwq: target pool_workqueue
d185af30 4006 *
6ba94429 4007 * If @pwq isn't freezing, set @pwq->max_active to the associated
f97a4a1a 4008 * workqueue's saved_max_active and activate inactive work items
6ba94429 4009 * accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
7a4e344c 4010 */
6ba94429 4011static void pwq_adjust_max_active(struct pool_workqueue *pwq)
4e1a1f9a 4012{
6ba94429
FW
4013 struct workqueue_struct *wq = pwq->wq;
4014 bool freezable = wq->flags & WQ_FREEZABLE;
3347fa09 4015 unsigned long flags;
4e1a1f9a 4016
6ba94429
FW
4017 /* for @wq->saved_max_active */
4018 lockdep_assert_held(&wq->mutex);
4e1a1f9a 4019
6ba94429
FW
4020 /* fast exit for non-freezable wqs */
4021 if (!freezable && pwq->max_active == wq->saved_max_active)
4022 return;
7a4e344c 4023
3347fa09 4024 /* this function can be called during early boot w/ irq disabled */
a9b8a985 4025 raw_spin_lock_irqsave(&pwq->pool->lock, flags);
29c91e99 4026
6ba94429
FW
4027 /*
4028 * During [un]freezing, the caller is responsible for ensuring that
4029 * this function is called at least once after @workqueue_freezing
4030 * is updated and visible.
4031 */
4032 if (!freezable || !workqueue_freezing) {
01341fbd
YY
4033 bool kick = false;
4034
6ba94429 4035 pwq->max_active = wq->saved_max_active;
4e1a1f9a 4036
f97a4a1a 4037 while (!list_empty(&pwq->inactive_works) &&
01341fbd 4038 pwq->nr_active < pwq->max_active) {
f97a4a1a 4039 pwq_activate_first_inactive(pwq);
01341fbd
YY
4040 kick = true;
4041 }
e2dca7ad 4042
6ba94429
FW
4043 /*
4044 * Need to kick a worker after thawed or an unbound wq's
01341fbd
YY
4045 * max_active is bumped. In realtime scenarios, always kicking a
4046 * worker will cause interference on the isolated cpu cores, so
4047 * let's kick iff work items were activated.
6ba94429 4048 */
01341fbd
YY
4049 if (kick)
4050 wake_up_worker(pwq->pool);
6ba94429
FW
4051 } else {
4052 pwq->max_active = 0;
4053 }
e2dca7ad 4054
a9b8a985 4055 raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
e2dca7ad
TH
4056}
4057
67dc8325 4058/* initialize newly allocated @pwq which is associated with @wq and @pool */
6ba94429
FW
4059static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
4060 struct worker_pool *pool)
29c91e99 4061{
6ba94429 4062 BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
29c91e99 4063
6ba94429
FW
4064 memset(pwq, 0, sizeof(*pwq));
4065
4066 pwq->pool = pool;
4067 pwq->wq = wq;
4068 pwq->flush_color = -1;
4069 pwq->refcnt = 1;
f97a4a1a 4070 INIT_LIST_HEAD(&pwq->inactive_works);
6ba94429
FW
4071 INIT_LIST_HEAD(&pwq->pwqs_node);
4072 INIT_LIST_HEAD(&pwq->mayday_node);
687a9aa5 4073 kthread_init_work(&pwq->release_work, pwq_release_workfn);
29c91e99
TH
4074}
4075
6ba94429
FW
4076/* sync @pwq with the current state of its associated wq and link it */
4077static void link_pwq(struct pool_workqueue *pwq)
29c91e99 4078{
6ba94429 4079 struct workqueue_struct *wq = pwq->wq;
29c91e99 4080
6ba94429 4081 lockdep_assert_held(&wq->mutex);
a892cacc 4082
6ba94429
FW
4083 /* may be called multiple times, ignore if already linked */
4084 if (!list_empty(&pwq->pwqs_node))
29c91e99 4085 return;
29c91e99 4086
6ba94429
FW
4087 /* set the matching work_color */
4088 pwq->work_color = wq->work_color;
29c91e99 4089
6ba94429
FW
4090 /* sync max_active to the current setting */
4091 pwq_adjust_max_active(pwq);
29c91e99 4092
6ba94429
FW
4093 /* link in @pwq */
4094 list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
4095}
29c91e99 4096
6ba94429
FW
4097/* obtain a pool matching @attr and create a pwq associating the pool and @wq */
4098static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
4099 const struct workqueue_attrs *attrs)
4100{
4101 struct worker_pool *pool;
4102 struct pool_workqueue *pwq;
60f5a4bc 4103
6ba94429 4104 lockdep_assert_held(&wq_pool_mutex);
60f5a4bc 4105
6ba94429
FW
4106 pool = get_unbound_pool(attrs);
4107 if (!pool)
4108 return NULL;
60f5a4bc 4109
6ba94429
FW
4110 pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
4111 if (!pwq) {
4112 put_unbound_pool(pool);
4113 return NULL;
4114 }
29c91e99 4115
6ba94429
FW
4116 init_pwq(pwq, wq, pool);
4117 return pwq;
4118}
29c91e99 4119
29c91e99 4120/**
fef59c9c 4121 * wq_calc_pod_cpumask - calculate a wq_attrs' cpumask for a pod
042f7df1 4122 * @attrs: the wq_attrs of the default pwq of the target workqueue
fef59c9c 4123 * @pod: the target CPU pod
6ba94429
FW
4124 * @cpu_going_down: if >= 0, the CPU to consider as offline
4125 * @cpumask: outarg, the resulting cpumask
29c91e99 4126 *
fef59c9c
TH
4127 * Calculate the cpumask a workqueue with @attrs should use on @pod. If
4128 * @cpu_going_down is >= 0, that cpu is considered offline during calculation.
4129 * The result is stored in @cpumask.
a892cacc 4130 *
fef59c9c
TH
4131 * If pod affinity is not enabled, @attrs->cpumask is always used. If enabled
4132 * and @pod has online CPUs requested by @attrs, the returned cpumask is the
4133 * intersection of the possible CPUs of @pod and @attrs->cpumask.
d185af30 4134 *
fef59c9c 4135 * The caller is responsible for ensuring that the cpumask of @pod stays stable.
29c91e99 4136 */
fef59c9c 4137static void wq_calc_pod_cpumask(const struct workqueue_attrs *attrs, int pod,
6ba94429 4138 int cpu_going_down, cpumask_t *cpumask)
29c91e99 4139{
fef59c9c 4140 if (!wq_pod_enabled || attrs->ordered)
6ba94429 4141 goto use_dfl;
29c91e99 4142
fef59c9c
TH
4143 /* does @pod have any online CPUs @attrs wants? */
4144 cpumask_and(cpumask, cpumask_of_node(pod), attrs->cpumask);
6ba94429
FW
4145 if (cpu_going_down >= 0)
4146 cpumask_clear_cpu(cpu_going_down, cpumask);
29c91e99 4147
6ba94429
FW
4148 if (cpumask_empty(cpumask))
4149 goto use_dfl;
4c16bd32 4150
fef59c9c
TH
4151 /* yeap, return possible CPUs in @pod that @attrs wants */
4152 cpumask_and(cpumask, attrs->cpumask, wq_pod_cpus[pod]);
1ad0f0a7 4153
636b927e 4154 if (cpumask_empty(cpumask))
1ad0f0a7
MB
4155 pr_warn_once("WARNING: workqueue cpumask: online intersect > "
4156 "possible intersect\n");
636b927e 4157 return;
4c16bd32
TH
4158
4159use_dfl:
4160 cpumask_copy(cpumask, attrs->cpumask);
4c16bd32
TH
4161}
4162
636b927e
TH
4163/* install @pwq into @wq's cpu_pwq and return the old pwq */
4164static struct pool_workqueue *install_unbound_pwq(struct workqueue_struct *wq,
4165 int cpu, struct pool_workqueue *pwq)
1befcf30
TH
4166{
4167 struct pool_workqueue *old_pwq;
4168
5b95e1af 4169 lockdep_assert_held(&wq_pool_mutex);
1befcf30
TH
4170 lockdep_assert_held(&wq->mutex);
4171
4172 /* link_pwq() can handle duplicate calls */
4173 link_pwq(pwq);
4174
636b927e
TH
4175 old_pwq = rcu_access_pointer(*per_cpu_ptr(wq->cpu_pwq, cpu));
4176 rcu_assign_pointer(*per_cpu_ptr(wq->cpu_pwq, cpu), pwq);
1befcf30
TH
4177 return old_pwq;
4178}
4179
2d5f0764
LJ
4180/* context to store the prepared attrs & pwqs before applying */
4181struct apply_wqattrs_ctx {
4182 struct workqueue_struct *wq; /* target workqueue */
4183 struct workqueue_attrs *attrs; /* attrs to apply */
042f7df1 4184 struct list_head list; /* queued for batching commit */
2d5f0764
LJ
4185 struct pool_workqueue *dfl_pwq;
4186 struct pool_workqueue *pwq_tbl[];
4187};
4188
4189/* free the resources after success or abort */
4190static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
4191{
4192 if (ctx) {
636b927e 4193 int cpu;
2d5f0764 4194
636b927e
TH
4195 for_each_possible_cpu(cpu)
4196 put_pwq_unlocked(ctx->pwq_tbl[cpu]);
2d5f0764
LJ
4197 put_pwq_unlocked(ctx->dfl_pwq);
4198
4199 free_workqueue_attrs(ctx->attrs);
4200
4201 kfree(ctx);
4202 }
4203}
4204
4205/* allocate the attrs and pwqs for later installation */
4206static struct apply_wqattrs_ctx *
4207apply_wqattrs_prepare(struct workqueue_struct *wq,
99c621ef
LJ
4208 const struct workqueue_attrs *attrs,
4209 const cpumask_var_t unbound_cpumask)
9e8cd2f5 4210{
2d5f0764 4211 struct apply_wqattrs_ctx *ctx;
4c16bd32 4212 struct workqueue_attrs *new_attrs, *tmp_attrs;
636b927e 4213 int cpu;
9e8cd2f5 4214
2d5f0764 4215 lockdep_assert_held(&wq_pool_mutex);
9e8cd2f5 4216
636b927e 4217 ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_cpu_ids), GFP_KERNEL);
8719dcea 4218
be69d00d
TG
4219 new_attrs = alloc_workqueue_attrs();
4220 tmp_attrs = alloc_workqueue_attrs();
2d5f0764
LJ
4221 if (!ctx || !new_attrs || !tmp_attrs)
4222 goto out_free;
13e2e556 4223
042f7df1 4224 /*
99c621ef
LJ
4225 * Calculate the attrs of the default pwq with unbound_cpumask
4226 * which is wq_unbound_cpumask or to set to wq_unbound_cpumask.
042f7df1
LJ
4227 * If the user configured cpumask doesn't overlap with the
4228 * wq_unbound_cpumask, we fallback to the wq_unbound_cpumask.
4229 */
13e2e556 4230 copy_workqueue_attrs(new_attrs, attrs);
99c621ef 4231 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, unbound_cpumask);
042f7df1 4232 if (unlikely(cpumask_empty(new_attrs->cpumask)))
99c621ef 4233 cpumask_copy(new_attrs->cpumask, unbound_cpumask);
13e2e556 4234
4c16bd32
TH
4235 /*
4236 * We may create multiple pwqs with differing cpumasks. Make a
4237 * copy of @new_attrs which will be modified and used to obtain
4238 * pools.
4239 */
4240 copy_workqueue_attrs(tmp_attrs, new_attrs);
4241
4c16bd32
TH
4242 /*
4243 * If something goes wrong during CPU up/down, we'll fall back to
4244 * the default pwq covering whole @attrs->cpumask. Always create
4245 * it even if we don't use it immediately.
4246 */
2d5f0764
LJ
4247 ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
4248 if (!ctx->dfl_pwq)
4249 goto out_free;
4c16bd32 4250
636b927e 4251 for_each_possible_cpu(cpu) {
af73f5c9 4252 if (new_attrs->ordered) {
2d5f0764 4253 ctx->dfl_pwq->refcnt++;
636b927e
TH
4254 ctx->pwq_tbl[cpu] = ctx->dfl_pwq;
4255 } else {
fef59c9c
TH
4256 wq_calc_pod_cpumask(new_attrs, cpu_to_node(cpu), -1,
4257 tmp_attrs->cpumask);
636b927e
TH
4258 ctx->pwq_tbl[cpu] = alloc_unbound_pwq(wq, tmp_attrs);
4259 if (!ctx->pwq_tbl[cpu])
4260 goto out_free;
4c16bd32
TH
4261 }
4262 }
4263
042f7df1
LJ
4264 /* save the user configured attrs and sanitize it. */
4265 copy_workqueue_attrs(new_attrs, attrs);
4266 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
2d5f0764 4267 ctx->attrs = new_attrs;
042f7df1 4268
2d5f0764
LJ
4269 ctx->wq = wq;
4270 free_workqueue_attrs(tmp_attrs);
4271 return ctx;
4272
4273out_free:
4274 free_workqueue_attrs(tmp_attrs);
4275 free_workqueue_attrs(new_attrs);
4276 apply_wqattrs_cleanup(ctx);
4277 return NULL;
4278}
4279
4280/* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
4281static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
4282{
636b927e 4283 int cpu;
9e8cd2f5 4284
4c16bd32 4285 /* all pwqs have been created successfully, let's install'em */
2d5f0764 4286 mutex_lock(&ctx->wq->mutex);
a892cacc 4287
2d5f0764 4288 copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
4c16bd32
TH
4289
4290 /* save the previous pwq and install the new one */
636b927e
TH
4291 for_each_possible_cpu(cpu)
4292 ctx->pwq_tbl[cpu] = install_unbound_pwq(ctx->wq, cpu,
4293 ctx->pwq_tbl[cpu]);
4c16bd32
TH
4294
4295 /* @dfl_pwq might not have been used, ensure it's linked */
2d5f0764
LJ
4296 link_pwq(ctx->dfl_pwq);
4297 swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
f147f29e 4298
2d5f0764
LJ
4299 mutex_unlock(&ctx->wq->mutex);
4300}
9e8cd2f5 4301
a0111cf6
LJ
4302static void apply_wqattrs_lock(void)
4303{
4304 /* CPUs should stay stable across pwq creations and installations */
ffd8bea8 4305 cpus_read_lock();
a0111cf6
LJ
4306 mutex_lock(&wq_pool_mutex);
4307}
4308
4309static void apply_wqattrs_unlock(void)
4310{
4311 mutex_unlock(&wq_pool_mutex);
ffd8bea8 4312 cpus_read_unlock();
a0111cf6
LJ
4313}
4314
4315static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
4316 const struct workqueue_attrs *attrs)
2d5f0764
LJ
4317{
4318 struct apply_wqattrs_ctx *ctx;
4c16bd32 4319
2d5f0764
LJ
4320 /* only unbound workqueues can change attributes */
4321 if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
4322 return -EINVAL;
13e2e556 4323
2d5f0764 4324 /* creating multiple pwqs breaks ordering guarantee */
0a94efb5
TH
4325 if (!list_empty(&wq->pwqs)) {
4326 if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
4327 return -EINVAL;
4328
4329 wq->flags &= ~__WQ_ORDERED;
4330 }
2d5f0764 4331
99c621ef 4332 ctx = apply_wqattrs_prepare(wq, attrs, wq_unbound_cpumask);
6201171e 4333 if (!ctx)
4334 return -ENOMEM;
2d5f0764
LJ
4335
4336 /* the ctx has been prepared successfully, let's commit it */
6201171e 4337 apply_wqattrs_commit(ctx);
2d5f0764
LJ
4338 apply_wqattrs_cleanup(ctx);
4339
6201171e 4340 return 0;
9e8cd2f5
TH
4341}
4342
a0111cf6
LJ
4343/**
4344 * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
4345 * @wq: the target workqueue
4346 * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
4347 *
fef59c9c
TH
4348 * Apply @attrs to an unbound workqueue @wq. Unless disabled, this function maps
4349 * a separate pwq to each CPU pod with possibles CPUs in @attrs->cpumask so that
4350 * work items are affine to the pod it was issued on. Older pwqs are released as
4351 * in-flight work items finish. Note that a work item which repeatedly requeues
4352 * itself back-to-back will stay on its current pwq.
a0111cf6
LJ
4353 *
4354 * Performs GFP_KERNEL allocations.
4355 *
ffd8bea8 4356 * Assumes caller has CPU hotplug read exclusion, i.e. cpus_read_lock().
509b3204 4357 *
a0111cf6
LJ
4358 * Return: 0 on success and -errno on failure.
4359 */
513c98d0 4360int apply_workqueue_attrs(struct workqueue_struct *wq,
a0111cf6
LJ
4361 const struct workqueue_attrs *attrs)
4362{
4363 int ret;
4364
509b3204
DJ
4365 lockdep_assert_cpus_held();
4366
4367 mutex_lock(&wq_pool_mutex);
a0111cf6 4368 ret = apply_workqueue_attrs_locked(wq, attrs);
509b3204 4369 mutex_unlock(&wq_pool_mutex);
a0111cf6
LJ
4370
4371 return ret;
4372}
4373
4c16bd32 4374/**
fef59c9c 4375 * wq_update_pod - update pod affinity of a wq for CPU hot[un]plug
4c16bd32 4376 * @wq: the target workqueue
4cbfd3de
TH
4377 * @cpu: the CPU to update pool association for
4378 * @hotplug_cpu: the CPU coming up or going down
4c16bd32
TH
4379 * @online: whether @cpu is coming up or going down
4380 *
4381 * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
fef59c9c 4382 * %CPU_DOWN_FAILED. @cpu is being hot[un]plugged, update pod affinity of
4c16bd32
TH
4383 * @wq accordingly.
4384 *
fef59c9c
TH
4385 *
4386 * If pod affinity can't be adjusted due to memory allocation failure, it falls
4387 * back to @wq->dfl_pwq which may not be optimal but is always correct.
4388 *
4389 * Note that when the last allowed CPU of a pod goes offline for a workqueue
4390 * with a cpumask spanning multiple pods, the workers which were already
4391 * executing the work items for the workqueue will lose their CPU affinity and
4392 * may execute on any CPU. This is similar to how per-cpu workqueues behave on
4393 * CPU_DOWN. If a workqueue user wants strict affinity, it's the user's
4394 * responsibility to flush the work item from CPU_DOWN_PREPARE.
4c16bd32 4395 */
fef59c9c
TH
4396static void wq_update_pod(struct workqueue_struct *wq, int cpu,
4397 int hotplug_cpu, bool online)
4c16bd32 4398{
fef59c9c 4399 int pod = cpu_to_node(cpu);
4cbfd3de 4400 int off_cpu = online ? -1 : hotplug_cpu;
4c16bd32
TH
4401 struct pool_workqueue *old_pwq = NULL, *pwq;
4402 struct workqueue_attrs *target_attrs;
4403 cpumask_t *cpumask;
4404
4405 lockdep_assert_held(&wq_pool_mutex);
4406
fef59c9c 4407 if (!wq_pod_enabled || !(wq->flags & WQ_UNBOUND) ||
af73f5c9 4408 wq->unbound_attrs->ordered)
4c16bd32
TH
4409 return;
4410
4411 /*
4412 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
4413 * Let's use a preallocated one. The following buf is protected by
4414 * CPU hotplug exclusion.
4415 */
fef59c9c 4416 target_attrs = wq_update_pod_attrs_buf;
4c16bd32
TH
4417 cpumask = target_attrs->cpumask;
4418
4c16bd32 4419 copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
4c16bd32 4420
636b927e 4421 /* nothing to do if the target cpumask matches the current pwq */
fef59c9c 4422 wq_calc_pod_cpumask(wq->dfl_pwq->pool->attrs, pod, off_cpu, cpumask);
636b927e
TH
4423 pwq = rcu_dereference_protected(*per_cpu_ptr(wq->cpu_pwq, cpu),
4424 lockdep_is_held(&wq_pool_mutex));
4425 if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
4426 return;
4c16bd32 4427
4c16bd32
TH
4428 /* create a new pwq */
4429 pwq = alloc_unbound_pwq(wq, target_attrs);
4430 if (!pwq) {
fef59c9c 4431 pr_warn("workqueue: allocation failed while updating CPU pod affinity of \"%s\"\n",
2d916033 4432 wq->name);
77f300b1 4433 goto use_dfl_pwq;
4c16bd32
TH
4434 }
4435
f7142ed4 4436 /* Install the new pwq. */
4c16bd32 4437 mutex_lock(&wq->mutex);
636b927e 4438 old_pwq = install_unbound_pwq(wq, cpu, pwq);
4c16bd32
TH
4439 goto out_unlock;
4440
4441use_dfl_pwq:
f7142ed4 4442 mutex_lock(&wq->mutex);
a9b8a985 4443 raw_spin_lock_irq(&wq->dfl_pwq->pool->lock);
4c16bd32 4444 get_pwq(wq->dfl_pwq);
a9b8a985 4445 raw_spin_unlock_irq(&wq->dfl_pwq->pool->lock);
636b927e 4446 old_pwq = install_unbound_pwq(wq, cpu, wq->dfl_pwq);
4c16bd32
TH
4447out_unlock:
4448 mutex_unlock(&wq->mutex);
4449 put_pwq_unlocked(old_pwq);
4450}
4451
30cdf249 4452static int alloc_and_link_pwqs(struct workqueue_struct *wq)
0f900049 4453{
49e3cf44 4454 bool highpri = wq->flags & WQ_HIGHPRI;
8a2b7538 4455 int cpu, ret;
30cdf249 4456
636b927e
TH
4457 wq->cpu_pwq = alloc_percpu(struct pool_workqueue *);
4458 if (!wq->cpu_pwq)
4459 goto enomem;
30cdf249 4460
636b927e 4461 if (!(wq->flags & WQ_UNBOUND)) {
30cdf249 4462 for_each_possible_cpu(cpu) {
687a9aa5 4463 struct pool_workqueue **pwq_p =
ee1ceef7 4464 per_cpu_ptr(wq->cpu_pwq, cpu);
687a9aa5
TH
4465 struct worker_pool *pool =
4466 &(per_cpu_ptr(cpu_worker_pools, cpu)[highpri]);
4467
4468 *pwq_p = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL,
4469 pool->node);
4470 if (!*pwq_p)
4471 goto enomem;
f3421797 4472
687a9aa5 4473 init_pwq(*pwq_p, wq, pool);
f147f29e
TH
4474
4475 mutex_lock(&wq->mutex);
687a9aa5 4476 link_pwq(*pwq_p);
f147f29e 4477 mutex_unlock(&wq->mutex);
30cdf249 4478 }
9e8cd2f5 4479 return 0;
509b3204
DJ
4480 }
4481
ffd8bea8 4482 cpus_read_lock();
509b3204 4483 if (wq->flags & __WQ_ORDERED) {
8a2b7538
TH
4484 ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
4485 /* there should only be single pwq for ordering guarantee */
4486 WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
4487 wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
4488 "ordering guarantee broken for workqueue %s\n", wq->name);
30cdf249 4489 } else {
509b3204 4490 ret = apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
30cdf249 4491 }
ffd8bea8 4492 cpus_read_unlock();
509b3204
DJ
4493
4494 return ret;
687a9aa5
TH
4495
4496enomem:
4497 if (wq->cpu_pwq) {
4498 for_each_possible_cpu(cpu)
4499 kfree(*per_cpu_ptr(wq->cpu_pwq, cpu));
4500 free_percpu(wq->cpu_pwq);
4501 wq->cpu_pwq = NULL;
4502 }
4503 return -ENOMEM;
0f900049
TH
4504}
4505
f3421797
TH
4506static int wq_clamp_max_active(int max_active, unsigned int flags,
4507 const char *name)
b71ab8c2 4508{
636b927e 4509 if (max_active < 1 || max_active > WQ_MAX_ACTIVE)
044c782c 4510 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
636b927e 4511 max_active, name, 1, WQ_MAX_ACTIVE);
b71ab8c2 4512
636b927e 4513 return clamp_val(max_active, 1, WQ_MAX_ACTIVE);
b71ab8c2
TH
4514}
4515
983c7515
TH
4516/*
4517 * Workqueues which may be used during memory reclaim should have a rescuer
4518 * to guarantee forward progress.
4519 */
4520static int init_rescuer(struct workqueue_struct *wq)
4521{
4522 struct worker *rescuer;
b92b36ea 4523 int ret;
983c7515
TH
4524
4525 if (!(wq->flags & WQ_MEM_RECLAIM))
4526 return 0;
4527
4528 rescuer = alloc_worker(NUMA_NO_NODE);
4c0736a7
PM
4529 if (!rescuer) {
4530 pr_err("workqueue: Failed to allocate a rescuer for wq \"%s\"\n",
4531 wq->name);
983c7515 4532 return -ENOMEM;
4c0736a7 4533 }
983c7515
TH
4534
4535 rescuer->rescue_wq = wq;
4536 rescuer->task = kthread_create(rescuer_thread, rescuer, "%s", wq->name);
f187b697 4537 if (IS_ERR(rescuer->task)) {
b92b36ea 4538 ret = PTR_ERR(rescuer->task);
4c0736a7
PM
4539 pr_err("workqueue: Failed to create a rescuer kthread for wq \"%s\": %pe",
4540 wq->name, ERR_PTR(ret));
983c7515 4541 kfree(rescuer);
b92b36ea 4542 return ret;
983c7515
TH
4543 }
4544
4545 wq->rescuer = rescuer;
4546 kthread_bind_mask(rescuer->task, cpu_possible_mask);
4547 wake_up_process(rescuer->task);
4548
4549 return 0;
4550}
4551
a2775bbc 4552__printf(1, 4)
669de8bd
BVA
4553struct workqueue_struct *alloc_workqueue(const char *fmt,
4554 unsigned int flags,
4555 int max_active, ...)
1da177e4 4556{
ecf6881f 4557 va_list args;
1da177e4 4558 struct workqueue_struct *wq;
49e3cf44 4559 struct pool_workqueue *pwq;
b196be89 4560
5c0338c6 4561 /*
fef59c9c
TH
4562 * Unbound && max_active == 1 used to imply ordered, which is no longer
4563 * the case on many machines due to per-pod pools. While
5c0338c6 4564 * alloc_ordered_workqueue() is the right way to create an ordered
fef59c9c 4565 * workqueue, keep the previous behavior to avoid subtle breakages.
5c0338c6
TH
4566 */
4567 if ((flags & WQ_UNBOUND) && max_active == 1)
4568 flags |= __WQ_ORDERED;
4569
cee22a15
VK
4570 /* see the comment above the definition of WQ_POWER_EFFICIENT */
4571 if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
4572 flags |= WQ_UNBOUND;
4573
ecf6881f 4574 /* allocate wq and format name */
636b927e 4575 wq = kzalloc(sizeof(*wq), GFP_KERNEL);
b196be89 4576 if (!wq)
d2c1d404 4577 return NULL;
b196be89 4578
6029a918 4579 if (flags & WQ_UNBOUND) {
be69d00d 4580 wq->unbound_attrs = alloc_workqueue_attrs();
6029a918
TH
4581 if (!wq->unbound_attrs)
4582 goto err_free_wq;
4583 }
4584
669de8bd 4585 va_start(args, max_active);
ecf6881f 4586 vsnprintf(wq->name, sizeof(wq->name), fmt, args);
b196be89 4587 va_end(args);
1da177e4 4588
d320c038 4589 max_active = max_active ?: WQ_DFL_ACTIVE;
b196be89 4590 max_active = wq_clamp_max_active(max_active, flags, wq->name);
3af24433 4591
b196be89 4592 /* init wq */
97e37d7b 4593 wq->flags = flags;
a0a1a5fd 4594 wq->saved_max_active = max_active;
3c25a55d 4595 mutex_init(&wq->mutex);
112202d9 4596 atomic_set(&wq->nr_pwqs_to_flush, 0);
30cdf249 4597 INIT_LIST_HEAD(&wq->pwqs);
73f53c4a
TH
4598 INIT_LIST_HEAD(&wq->flusher_queue);
4599 INIT_LIST_HEAD(&wq->flusher_overflow);
493a1724 4600 INIT_LIST_HEAD(&wq->maydays);
502ca9d8 4601
669de8bd 4602 wq_init_lockdep(wq);
cce1a165 4603 INIT_LIST_HEAD(&wq->list);
3af24433 4604
30cdf249 4605 if (alloc_and_link_pwqs(wq) < 0)
82efcab3 4606 goto err_unreg_lockdep;
1537663f 4607
40c17f75 4608 if (wq_online && init_rescuer(wq) < 0)
983c7515 4609 goto err_destroy;
3af24433 4610
226223ab
TH
4611 if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
4612 goto err_destroy;
4613
a0a1a5fd 4614 /*
68e13a67
LJ
4615 * wq_pool_mutex protects global freeze state and workqueues list.
4616 * Grab it, adjust max_active and add the new @wq to workqueues
4617 * list.
a0a1a5fd 4618 */
68e13a67 4619 mutex_lock(&wq_pool_mutex);
a0a1a5fd 4620
a357fc03 4621 mutex_lock(&wq->mutex);
699ce097
TH
4622 for_each_pwq(pwq, wq)
4623 pwq_adjust_max_active(pwq);
a357fc03 4624 mutex_unlock(&wq->mutex);
a0a1a5fd 4625
e2dca7ad 4626 list_add_tail_rcu(&wq->list, &workqueues);
a0a1a5fd 4627
68e13a67 4628 mutex_unlock(&wq_pool_mutex);
1537663f 4629
3af24433 4630 return wq;
d2c1d404 4631
82efcab3 4632err_unreg_lockdep:
009bb421
BVA
4633 wq_unregister_lockdep(wq);
4634 wq_free_lockdep(wq);
82efcab3 4635err_free_wq:
6029a918 4636 free_workqueue_attrs(wq->unbound_attrs);
d2c1d404
TH
4637 kfree(wq);
4638 return NULL;
4639err_destroy:
4640 destroy_workqueue(wq);
4690c4ab 4641 return NULL;
3af24433 4642}
669de8bd 4643EXPORT_SYMBOL_GPL(alloc_workqueue);
1da177e4 4644
c29eb853
TH
4645static bool pwq_busy(struct pool_workqueue *pwq)
4646{
4647 int i;
4648
4649 for (i = 0; i < WORK_NR_COLORS; i++)
4650 if (pwq->nr_in_flight[i])
4651 return true;
4652
4653 if ((pwq != pwq->wq->dfl_pwq) && (pwq->refcnt > 1))
4654 return true;
f97a4a1a 4655 if (pwq->nr_active || !list_empty(&pwq->inactive_works))
c29eb853
TH
4656 return true;
4657
4658 return false;
4659}
4660
3af24433
ON
4661/**
4662 * destroy_workqueue - safely terminate a workqueue
4663 * @wq: target workqueue
4664 *
4665 * Safely destroy a workqueue. All work currently pending will be done first.
4666 */
4667void destroy_workqueue(struct workqueue_struct *wq)
4668{
49e3cf44 4669 struct pool_workqueue *pwq;
636b927e 4670 int cpu;
3af24433 4671
def98c84
TH
4672 /*
4673 * Remove it from sysfs first so that sanity check failure doesn't
4674 * lead to sysfs name conflicts.
4675 */
4676 workqueue_sysfs_unregister(wq);
4677
33e3f0a3
RC
4678 /* mark the workqueue destruction is in progress */
4679 mutex_lock(&wq->mutex);
4680 wq->flags |= __WQ_DESTROYING;
4681 mutex_unlock(&wq->mutex);
4682
9c5a2ba7
TH
4683 /* drain it before proceeding with destruction */
4684 drain_workqueue(wq);
c8efcc25 4685
def98c84
TH
4686 /* kill rescuer, if sanity checks fail, leave it w/o rescuer */
4687 if (wq->rescuer) {
4688 struct worker *rescuer = wq->rescuer;
4689
4690 /* this prevents new queueing */
a9b8a985 4691 raw_spin_lock_irq(&wq_mayday_lock);
def98c84 4692 wq->rescuer = NULL;
a9b8a985 4693 raw_spin_unlock_irq(&wq_mayday_lock);
def98c84
TH
4694
4695 /* rescuer will empty maydays list before exiting */
4696 kthread_stop(rescuer->task);
8efe1223 4697 kfree(rescuer);
def98c84
TH
4698 }
4699
c29eb853
TH
4700 /*
4701 * Sanity checks - grab all the locks so that we wait for all
4702 * in-flight operations which may do put_pwq().
4703 */
4704 mutex_lock(&wq_pool_mutex);
b09f4fd3 4705 mutex_lock(&wq->mutex);
49e3cf44 4706 for_each_pwq(pwq, wq) {
a9b8a985 4707 raw_spin_lock_irq(&pwq->pool->lock);
c29eb853 4708 if (WARN_ON(pwq_busy(pwq))) {
1d9a6159
KW
4709 pr_warn("%s: %s has the following busy pwq\n",
4710 __func__, wq->name);
c29eb853 4711 show_pwq(pwq);
a9b8a985 4712 raw_spin_unlock_irq(&pwq->pool->lock);
b09f4fd3 4713 mutex_unlock(&wq->mutex);
c29eb853 4714 mutex_unlock(&wq_pool_mutex);
55df0933 4715 show_one_workqueue(wq);
6183c009 4716 return;
76af4d93 4717 }
a9b8a985 4718 raw_spin_unlock_irq(&pwq->pool->lock);
6183c009 4719 }
b09f4fd3 4720 mutex_unlock(&wq->mutex);
6183c009 4721
a0a1a5fd
TH
4722 /*
4723 * wq list is used to freeze wq, remove from list after
4724 * flushing is complete in case freeze races us.
4725 */
e2dca7ad 4726 list_del_rcu(&wq->list);
68e13a67 4727 mutex_unlock(&wq_pool_mutex);
3af24433 4728
636b927e
TH
4729 /*
4730 * We're the sole accessor of @wq. Directly access cpu_pwq and dfl_pwq
4731 * to put the base refs. @wq will be auto-destroyed from the last
4732 * pwq_put. RCU read lock prevents @wq from going away from under us.
4733 */
4734 rcu_read_lock();
4c16bd32 4735
636b927e
TH
4736 for_each_possible_cpu(cpu) {
4737 pwq = rcu_access_pointer(*per_cpu_ptr(wq->cpu_pwq, cpu));
4738 RCU_INIT_POINTER(*per_cpu_ptr(wq->cpu_pwq, cpu), NULL);
dce90d47 4739 put_pwq_unlocked(pwq);
29c91e99 4740 }
636b927e
TH
4741
4742 put_pwq_unlocked(wq->dfl_pwq);
4743 wq->dfl_pwq = NULL;
4744
4745 rcu_read_unlock();
3af24433
ON
4746}
4747EXPORT_SYMBOL_GPL(destroy_workqueue);
4748
dcd989cb
TH
4749/**
4750 * workqueue_set_max_active - adjust max_active of a workqueue
4751 * @wq: target workqueue
4752 * @max_active: new max_active value.
4753 *
4754 * Set max_active of @wq to @max_active.
4755 *
4756 * CONTEXT:
4757 * Don't call from IRQ context.
4758 */
4759void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4760{
49e3cf44 4761 struct pool_workqueue *pwq;
dcd989cb 4762
8719dcea 4763 /* disallow meddling with max_active for ordered workqueues */
0a94efb5 4764 if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
8719dcea
TH
4765 return;
4766
f3421797 4767 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
dcd989cb 4768
a357fc03 4769 mutex_lock(&wq->mutex);
dcd989cb 4770
0a94efb5 4771 wq->flags &= ~__WQ_ORDERED;
dcd989cb
TH
4772 wq->saved_max_active = max_active;
4773
699ce097
TH
4774 for_each_pwq(pwq, wq)
4775 pwq_adjust_max_active(pwq);
93981800 4776
a357fc03 4777 mutex_unlock(&wq->mutex);
15316ba8 4778}
dcd989cb 4779EXPORT_SYMBOL_GPL(workqueue_set_max_active);
15316ba8 4780
27d4ee03
LW
4781/**
4782 * current_work - retrieve %current task's work struct
4783 *
4784 * Determine if %current task is a workqueue worker and what it's working on.
4785 * Useful to find out the context that the %current task is running in.
4786 *
4787 * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
4788 */
4789struct work_struct *current_work(void)
4790{
4791 struct worker *worker = current_wq_worker();
4792
4793 return worker ? worker->current_work : NULL;
4794}
4795EXPORT_SYMBOL(current_work);
4796
e6267616
TH
4797/**
4798 * current_is_workqueue_rescuer - is %current workqueue rescuer?
4799 *
4800 * Determine whether %current is a workqueue rescuer. Can be used from
4801 * work functions to determine whether it's being run off the rescuer task.
d185af30
YB
4802 *
4803 * Return: %true if %current is a workqueue rescuer. %false otherwise.
e6267616
TH
4804 */
4805bool current_is_workqueue_rescuer(void)
4806{
4807 struct worker *worker = current_wq_worker();
4808
6a092dfd 4809 return worker && worker->rescue_wq;
e6267616
TH
4810}
4811
eef6a7d5 4812/**
dcd989cb
TH
4813 * workqueue_congested - test whether a workqueue is congested
4814 * @cpu: CPU in question
4815 * @wq: target workqueue
eef6a7d5 4816 *
dcd989cb
TH
4817 * Test whether @wq's cpu workqueue for @cpu is congested. There is
4818 * no synchronization around this function and the test result is
4819 * unreliable and only useful as advisory hints or for debugging.
eef6a7d5 4820 *
d3251859 4821 * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
636b927e
TH
4822 *
4823 * With the exception of ordered workqueues, all workqueues have per-cpu
4824 * pool_workqueues, each with its own congested state. A workqueue being
4825 * congested on one CPU doesn't mean that the workqueue is contested on any
4826 * other CPUs.
d3251859 4827 *
d185af30 4828 * Return:
dcd989cb 4829 * %true if congested, %false otherwise.
eef6a7d5 4830 */
d84ff051 4831bool workqueue_congested(int cpu, struct workqueue_struct *wq)
1da177e4 4832{
7fb98ea7 4833 struct pool_workqueue *pwq;
76af4d93
TH
4834 bool ret;
4835
24acfb71
TG
4836 rcu_read_lock();
4837 preempt_disable();
7fb98ea7 4838
d3251859
TH
4839 if (cpu == WORK_CPU_UNBOUND)
4840 cpu = smp_processor_id();
4841
636b927e 4842 pwq = *per_cpu_ptr(wq->cpu_pwq, cpu);
f97a4a1a 4843 ret = !list_empty(&pwq->inactive_works);
636b927e 4844
24acfb71
TG
4845 preempt_enable();
4846 rcu_read_unlock();
76af4d93
TH
4847
4848 return ret;
1da177e4 4849}
dcd989cb 4850EXPORT_SYMBOL_GPL(workqueue_congested);
1da177e4 4851
dcd989cb
TH
4852/**
4853 * work_busy - test whether a work is currently pending or running
4854 * @work: the work to be tested
4855 *
4856 * Test whether @work is currently pending or running. There is no
4857 * synchronization around this function and the test result is
4858 * unreliable and only useful as advisory hints or for debugging.
dcd989cb 4859 *
d185af30 4860 * Return:
dcd989cb
TH
4861 * OR'd bitmask of WORK_BUSY_* bits.
4862 */
4863unsigned int work_busy(struct work_struct *work)
1da177e4 4864{
fa1b54e6 4865 struct worker_pool *pool;
dcd989cb
TH
4866 unsigned long flags;
4867 unsigned int ret = 0;
1da177e4 4868
dcd989cb
TH
4869 if (work_pending(work))
4870 ret |= WORK_BUSY_PENDING;
1da177e4 4871
24acfb71 4872 rcu_read_lock();
fa1b54e6 4873 pool = get_work_pool(work);
038366c5 4874 if (pool) {
a9b8a985 4875 raw_spin_lock_irqsave(&pool->lock, flags);
038366c5
LJ
4876 if (find_worker_executing_work(pool, work))
4877 ret |= WORK_BUSY_RUNNING;
a9b8a985 4878 raw_spin_unlock_irqrestore(&pool->lock, flags);
038366c5 4879 }
24acfb71 4880 rcu_read_unlock();
1da177e4 4881
dcd989cb 4882 return ret;
1da177e4 4883}
dcd989cb 4884EXPORT_SYMBOL_GPL(work_busy);
1da177e4 4885
3d1cb205
TH
4886/**
4887 * set_worker_desc - set description for the current work item
4888 * @fmt: printf-style format string
4889 * @...: arguments for the format string
4890 *
4891 * This function can be called by a running work function to describe what
4892 * the work item is about. If the worker task gets dumped, this
4893 * information will be printed out together to help debugging. The
4894 * description can be at most WORKER_DESC_LEN including the trailing '\0'.
4895 */
4896void set_worker_desc(const char *fmt, ...)
4897{
4898 struct worker *worker = current_wq_worker();
4899 va_list args;
4900
4901 if (worker) {
4902 va_start(args, fmt);
4903 vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
4904 va_end(args);
3d1cb205
TH
4905 }
4906}
5c750d58 4907EXPORT_SYMBOL_GPL(set_worker_desc);
3d1cb205
TH
4908
4909/**
4910 * print_worker_info - print out worker information and description
4911 * @log_lvl: the log level to use when printing
4912 * @task: target task
4913 *
4914 * If @task is a worker and currently executing a work item, print out the
4915 * name of the workqueue being serviced and worker description set with
4916 * set_worker_desc() by the currently executing work item.
4917 *
4918 * This function can be safely called on any task as long as the
4919 * task_struct itself is accessible. While safe, this function isn't
4920 * synchronized and may print out mixups or garbages of limited length.
4921 */
4922void print_worker_info(const char *log_lvl, struct task_struct *task)
4923{
4924 work_func_t *fn = NULL;
4925 char name[WQ_NAME_LEN] = { };
4926 char desc[WORKER_DESC_LEN] = { };
4927 struct pool_workqueue *pwq = NULL;
4928 struct workqueue_struct *wq = NULL;
3d1cb205
TH
4929 struct worker *worker;
4930
4931 if (!(task->flags & PF_WQ_WORKER))
4932 return;
4933
4934 /*
4935 * This function is called without any synchronization and @task
4936 * could be in any state. Be careful with dereferences.
4937 */
e700591a 4938 worker = kthread_probe_data(task);
3d1cb205
TH
4939
4940 /*
8bf89593
TH
4941 * Carefully copy the associated workqueue's workfn, name and desc.
4942 * Keep the original last '\0' in case the original is garbage.
3d1cb205 4943 */
fe557319
CH
4944 copy_from_kernel_nofault(&fn, &worker->current_func, sizeof(fn));
4945 copy_from_kernel_nofault(&pwq, &worker->current_pwq, sizeof(pwq));
4946 copy_from_kernel_nofault(&wq, &pwq->wq, sizeof(wq));
4947 copy_from_kernel_nofault(name, wq->name, sizeof(name) - 1);
4948 copy_from_kernel_nofault(desc, worker->desc, sizeof(desc) - 1);
3d1cb205
TH
4949
4950 if (fn || name[0] || desc[0]) {
d75f773c 4951 printk("%sWorkqueue: %s %ps", log_lvl, name, fn);
8bf89593 4952 if (strcmp(name, desc))
3d1cb205
TH
4953 pr_cont(" (%s)", desc);
4954 pr_cont("\n");
4955 }
4956}
4957
3494fc30
TH
4958static void pr_cont_pool_info(struct worker_pool *pool)
4959{
4960 pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
4961 if (pool->node != NUMA_NO_NODE)
4962 pr_cont(" node=%d", pool->node);
4963 pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
4964}
4965
c76feb0d
PM
4966struct pr_cont_work_struct {
4967 bool comma;
4968 work_func_t func;
4969 long ctr;
4970};
4971
4972static void pr_cont_work_flush(bool comma, work_func_t func, struct pr_cont_work_struct *pcwsp)
4973{
4974 if (!pcwsp->ctr)
4975 goto out_record;
4976 if (func == pcwsp->func) {
4977 pcwsp->ctr++;
4978 return;
4979 }
4980 if (pcwsp->ctr == 1)
4981 pr_cont("%s %ps", pcwsp->comma ? "," : "", pcwsp->func);
4982 else
4983 pr_cont("%s %ld*%ps", pcwsp->comma ? "," : "", pcwsp->ctr, pcwsp->func);
4984 pcwsp->ctr = 0;
4985out_record:
4986 if ((long)func == -1L)
4987 return;
4988 pcwsp->comma = comma;
4989 pcwsp->func = func;
4990 pcwsp->ctr = 1;
4991}
4992
4993static void pr_cont_work(bool comma, struct work_struct *work, struct pr_cont_work_struct *pcwsp)
3494fc30
TH
4994{
4995 if (work->func == wq_barrier_func) {
4996 struct wq_barrier *barr;
4997
4998 barr = container_of(work, struct wq_barrier, work);
4999
c76feb0d 5000 pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
3494fc30
TH
5001 pr_cont("%s BAR(%d)", comma ? "," : "",
5002 task_pid_nr(barr->task));
5003 } else {
c76feb0d
PM
5004 if (!comma)
5005 pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
5006 pr_cont_work_flush(comma, work->func, pcwsp);
3494fc30
TH
5007 }
5008}
5009
5010static void show_pwq(struct pool_workqueue *pwq)
5011{
c76feb0d 5012 struct pr_cont_work_struct pcws = { .ctr = 0, };
3494fc30
TH
5013 struct worker_pool *pool = pwq->pool;
5014 struct work_struct *work;
5015 struct worker *worker;
5016 bool has_in_flight = false, has_pending = false;
5017 int bkt;
5018
5019 pr_info(" pwq %d:", pool->id);
5020 pr_cont_pool_info(pool);
5021
e66b39af
TH
5022 pr_cont(" active=%d/%d refcnt=%d%s\n",
5023 pwq->nr_active, pwq->max_active, pwq->refcnt,
3494fc30
TH
5024 !list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
5025
5026 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
5027 if (worker->current_pwq == pwq) {
5028 has_in_flight = true;
5029 break;
5030 }
5031 }
5032 if (has_in_flight) {
5033 bool comma = false;
5034
5035 pr_info(" in-flight:");
5036 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
5037 if (worker->current_pwq != pwq)
5038 continue;
5039
d75f773c 5040 pr_cont("%s %d%s:%ps", comma ? "," : "",
3494fc30 5041 task_pid_nr(worker->task),
30ae2fc0 5042 worker->rescue_wq ? "(RESCUER)" : "",
3494fc30
TH
5043 worker->current_func);
5044 list_for_each_entry(work, &worker->scheduled, entry)
c76feb0d
PM
5045 pr_cont_work(false, work, &pcws);
5046 pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
3494fc30
TH
5047 comma = true;
5048 }
5049 pr_cont("\n");
5050 }
5051
5052 list_for_each_entry(work, &pool->worklist, entry) {
5053 if (get_work_pwq(work) == pwq) {
5054 has_pending = true;
5055 break;
5056 }
5057 }
5058 if (has_pending) {
5059 bool comma = false;
5060
5061 pr_info(" pending:");
5062 list_for_each_entry(work, &pool->worklist, entry) {
5063 if (get_work_pwq(work) != pwq)
5064 continue;
5065
c76feb0d 5066 pr_cont_work(comma, work, &pcws);
3494fc30
TH
5067 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
5068 }
c76feb0d 5069 pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
3494fc30
TH
5070 pr_cont("\n");
5071 }
5072
f97a4a1a 5073 if (!list_empty(&pwq->inactive_works)) {
3494fc30
TH
5074 bool comma = false;
5075
f97a4a1a
LJ
5076 pr_info(" inactive:");
5077 list_for_each_entry(work, &pwq->inactive_works, entry) {
c76feb0d 5078 pr_cont_work(comma, work, &pcws);
3494fc30
TH
5079 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
5080 }
c76feb0d 5081 pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
3494fc30
TH
5082 pr_cont("\n");
5083 }
5084}
5085
5086/**
55df0933
IK
5087 * show_one_workqueue - dump state of specified workqueue
5088 * @wq: workqueue whose state will be printed
3494fc30 5089 */
55df0933 5090void show_one_workqueue(struct workqueue_struct *wq)
3494fc30 5091{
55df0933
IK
5092 struct pool_workqueue *pwq;
5093 bool idle = true;
3494fc30 5094 unsigned long flags;
3494fc30 5095
55df0933
IK
5096 for_each_pwq(pwq, wq) {
5097 if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
5098 idle = false;
5099 break;
3494fc30 5100 }
55df0933
IK
5101 }
5102 if (idle) /* Nothing to print for idle workqueue */
5103 return;
3494fc30 5104
55df0933 5105 pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
3494fc30 5106
55df0933
IK
5107 for_each_pwq(pwq, wq) {
5108 raw_spin_lock_irqsave(&pwq->pool->lock, flags);
5109 if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
62635ea8 5110 /*
55df0933
IK
5111 * Defer printing to avoid deadlocks in console
5112 * drivers that queue work while holding locks
5113 * also taken in their write paths.
62635ea8 5114 */
55df0933
IK
5115 printk_deferred_enter();
5116 show_pwq(pwq);
5117 printk_deferred_exit();
3494fc30 5118 }
55df0933 5119 raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
62635ea8
SS
5120 /*
5121 * We could be printing a lot from atomic context, e.g.
55df0933 5122 * sysrq-t -> show_all_workqueues(). Avoid triggering
62635ea8
SS
5123 * hard lockup.
5124 */
5125 touch_nmi_watchdog();
3494fc30
TH
5126 }
5127
55df0933
IK
5128}
5129
5130/**
5131 * show_one_worker_pool - dump state of specified worker pool
5132 * @pool: worker pool whose state will be printed
5133 */
5134static void show_one_worker_pool(struct worker_pool *pool)
5135{
5136 struct worker *worker;
5137 bool first = true;
5138 unsigned long flags;
335a42eb 5139 unsigned long hung = 0;
55df0933
IK
5140
5141 raw_spin_lock_irqsave(&pool->lock, flags);
5142 if (pool->nr_workers == pool->nr_idle)
5143 goto next_pool;
335a42eb
PM
5144
5145 /* How long the first pending work is waiting for a worker. */
5146 if (!list_empty(&pool->worklist))
5147 hung = jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000;
5148
55df0933
IK
5149 /*
5150 * Defer printing to avoid deadlocks in console drivers that
5151 * queue work while holding locks also taken in their write
5152 * paths.
5153 */
5154 printk_deferred_enter();
5155 pr_info("pool %d:", pool->id);
5156 pr_cont_pool_info(pool);
335a42eb 5157 pr_cont(" hung=%lus workers=%d", hung, pool->nr_workers);
55df0933
IK
5158 if (pool->manager)
5159 pr_cont(" manager: %d",
5160 task_pid_nr(pool->manager->task));
5161 list_for_each_entry(worker, &pool->idle_list, entry) {
5162 pr_cont(" %s%d", first ? "idle: " : "",
5163 task_pid_nr(worker->task));
5164 first = false;
5165 }
5166 pr_cont("\n");
5167 printk_deferred_exit();
5168next_pool:
5169 raw_spin_unlock_irqrestore(&pool->lock, flags);
5170 /*
5171 * We could be printing a lot from atomic context, e.g.
5172 * sysrq-t -> show_all_workqueues(). Avoid triggering
5173 * hard lockup.
5174 */
5175 touch_nmi_watchdog();
5176
5177}
5178
5179/**
5180 * show_all_workqueues - dump workqueue state
5181 *
704bc669 5182 * Called from a sysrq handler and prints out all busy workqueues and pools.
55df0933
IK
5183 */
5184void show_all_workqueues(void)
5185{
5186 struct workqueue_struct *wq;
5187 struct worker_pool *pool;
5188 int pi;
5189
5190 rcu_read_lock();
5191
5192 pr_info("Showing busy workqueues and worker pools:\n");
5193
5194 list_for_each_entry_rcu(wq, &workqueues, list)
5195 show_one_workqueue(wq);
5196
5197 for_each_pool(pool, pi)
5198 show_one_worker_pool(pool);
5199
24acfb71 5200 rcu_read_unlock();
3494fc30
TH
5201}
5202
704bc669
JL
5203/**
5204 * show_freezable_workqueues - dump freezable workqueue state
5205 *
5206 * Called from try_to_freeze_tasks() and prints out all freezable workqueues
5207 * still busy.
5208 */
5209void show_freezable_workqueues(void)
5210{
5211 struct workqueue_struct *wq;
5212
5213 rcu_read_lock();
5214
5215 pr_info("Showing freezable workqueues that are still busy:\n");
5216
5217 list_for_each_entry_rcu(wq, &workqueues, list) {
5218 if (!(wq->flags & WQ_FREEZABLE))
5219 continue;
5220 show_one_workqueue(wq);
5221 }
5222
5223 rcu_read_unlock();
5224}
5225
6b59808b
TH
5226/* used to show worker information through /proc/PID/{comm,stat,status} */
5227void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
5228{
6b59808b
TH
5229 int off;
5230
5231 /* always show the actual comm */
5232 off = strscpy(buf, task->comm, size);
5233 if (off < 0)
5234 return;
5235
197f6acc 5236 /* stabilize PF_WQ_WORKER and worker pool association */
6b59808b
TH
5237 mutex_lock(&wq_pool_attach_mutex);
5238
197f6acc
TH
5239 if (task->flags & PF_WQ_WORKER) {
5240 struct worker *worker = kthread_data(task);
5241 struct worker_pool *pool = worker->pool;
6b59808b 5242
197f6acc 5243 if (pool) {
a9b8a985 5244 raw_spin_lock_irq(&pool->lock);
197f6acc
TH
5245 /*
5246 * ->desc tracks information (wq name or
5247 * set_worker_desc()) for the latest execution. If
5248 * current, prepend '+', otherwise '-'.
5249 */
5250 if (worker->desc[0] != '\0') {
5251 if (worker->current_work)
5252 scnprintf(buf + off, size - off, "+%s",
5253 worker->desc);
5254 else
5255 scnprintf(buf + off, size - off, "-%s",
5256 worker->desc);
5257 }
a9b8a985 5258 raw_spin_unlock_irq(&pool->lock);
6b59808b 5259 }
6b59808b
TH
5260 }
5261
5262 mutex_unlock(&wq_pool_attach_mutex);
5263}
5264
66448bc2
MM
5265#ifdef CONFIG_SMP
5266
db7bccf4
TH
5267/*
5268 * CPU hotplug.
5269 *
e22bee78 5270 * There are two challenges in supporting CPU hotplug. Firstly, there
112202d9 5271 * are a lot of assumptions on strong associations among work, pwq and
706026c2 5272 * pool which make migrating pending and scheduled works very
e22bee78 5273 * difficult to implement without impacting hot paths. Secondly,
94cf58bb 5274 * worker pools serve mix of short, long and very long running works making
e22bee78
TH
5275 * blocked draining impractical.
5276 *
24647570 5277 * This is solved by allowing the pools to be disassociated from the CPU
628c78e7
TH
5278 * running as an unbound one and allowing it to be reattached later if the
5279 * cpu comes back online.
db7bccf4 5280 */
1da177e4 5281
e8b3f8db 5282static void unbind_workers(int cpu)
3af24433 5283{
4ce62e9e 5284 struct worker_pool *pool;
db7bccf4 5285 struct worker *worker;
3af24433 5286
f02ae73a 5287 for_each_cpu_worker_pool(pool, cpu) {
1258fae7 5288 mutex_lock(&wq_pool_attach_mutex);
a9b8a985 5289 raw_spin_lock_irq(&pool->lock);
3af24433 5290
94cf58bb 5291 /*
92f9c5c4 5292 * We've blocked all attach/detach operations. Make all workers
94cf58bb 5293 * unbound and set DISASSOCIATED. Before this, all workers
11b45b0b 5294 * must be on the cpu. After this, they may become diasporas.
b4ac9384
LJ
5295 * And the preemption disabled section in their sched callbacks
5296 * are guaranteed to see WORKER_UNBOUND since the code here
5297 * is on the same cpu.
94cf58bb 5298 */
da028469 5299 for_each_pool_worker(worker, pool)
c9e7cf27 5300 worker->flags |= WORKER_UNBOUND;
06ba38a9 5301
24647570 5302 pool->flags |= POOL_DISASSOCIATED;
f2d5a0ee 5303
eb283428 5304 /*
989442d7
LJ
5305 * The handling of nr_running in sched callbacks are disabled
5306 * now. Zap nr_running. After this, nr_running stays zero and
5307 * need_more_worker() and keep_working() are always true as
5308 * long as the worklist is not empty. This pool now behaves as
5309 * an unbound (in terms of concurrency management) pool which
eb283428
LJ
5310 * are served by workers tied to the pool.
5311 */
bc35f7ef 5312 pool->nr_running = 0;
eb283428
LJ
5313
5314 /*
5315 * With concurrency management just turned off, a busy
5316 * worker blocking could lead to lengthy stalls. Kick off
5317 * unbound chain execution of currently pending work items.
5318 */
eb283428 5319 wake_up_worker(pool);
989442d7 5320
a9b8a985 5321 raw_spin_unlock_irq(&pool->lock);
989442d7 5322
793777bc
VS
5323 for_each_pool_worker(worker, pool)
5324 unbind_worker(worker);
989442d7
LJ
5325
5326 mutex_unlock(&wq_pool_attach_mutex);
eb283428 5327 }
3af24433 5328}
3af24433 5329
bd7c089e
TH
5330/**
5331 * rebind_workers - rebind all workers of a pool to the associated CPU
5332 * @pool: pool of interest
5333 *
a9ab775b 5334 * @pool->cpu is coming online. Rebind all workers to the CPU.
bd7c089e
TH
5335 */
5336static void rebind_workers(struct worker_pool *pool)
5337{
a9ab775b 5338 struct worker *worker;
bd7c089e 5339
1258fae7 5340 lockdep_assert_held(&wq_pool_attach_mutex);
bd7c089e 5341
a9ab775b
TH
5342 /*
5343 * Restore CPU affinity of all workers. As all idle workers should
5344 * be on the run-queue of the associated CPU before any local
402dd89d 5345 * wake-ups for concurrency management happen, restore CPU affinity
a9ab775b
TH
5346 * of all workers first and then clear UNBOUND. As we're called
5347 * from CPU_ONLINE, the following shouldn't fail.
5348 */
c63a2e52
VS
5349 for_each_pool_worker(worker, pool) {
5350 kthread_set_per_cpu(worker->task, pool->cpu);
5351 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
5352 pool->attrs->cpumask) < 0);
5353 }
bd7c089e 5354
a9b8a985 5355 raw_spin_lock_irq(&pool->lock);
f7c17d26 5356
3de5e884 5357 pool->flags &= ~POOL_DISASSOCIATED;
bd7c089e 5358
da028469 5359 for_each_pool_worker(worker, pool) {
a9ab775b 5360 unsigned int worker_flags = worker->flags;
bd7c089e 5361
a9ab775b
TH
5362 /*
5363 * We want to clear UNBOUND but can't directly call
5364 * worker_clr_flags() or adjust nr_running. Atomically
5365 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
5366 * @worker will clear REBOUND using worker_clr_flags() when
5367 * it initiates the next execution cycle thus restoring
5368 * concurrency management. Note that when or whether
5369 * @worker clears REBOUND doesn't affect correctness.
5370 *
c95491ed 5371 * WRITE_ONCE() is necessary because @worker->flags may be
a9ab775b 5372 * tested without holding any lock in
6d25be57 5373 * wq_worker_running(). Without it, NOT_RUNNING test may
a9ab775b
TH
5374 * fail incorrectly leading to premature concurrency
5375 * management operations.
5376 */
5377 WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
5378 worker_flags |= WORKER_REBOUND;
5379 worker_flags &= ~WORKER_UNBOUND;
c95491ed 5380 WRITE_ONCE(worker->flags, worker_flags);
bd7c089e 5381 }
a9ab775b 5382
a9b8a985 5383 raw_spin_unlock_irq(&pool->lock);
bd7c089e
TH
5384}
5385
7dbc725e
TH
5386/**
5387 * restore_unbound_workers_cpumask - restore cpumask of unbound workers
5388 * @pool: unbound pool of interest
5389 * @cpu: the CPU which is coming up
5390 *
5391 * An unbound pool may end up with a cpumask which doesn't have any online
5392 * CPUs. When a worker of such pool get scheduled, the scheduler resets
5393 * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
5394 * online CPU before, cpus_allowed of all its workers should be restored.
5395 */
5396static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
5397{
5398 static cpumask_t cpumask;
5399 struct worker *worker;
7dbc725e 5400
1258fae7 5401 lockdep_assert_held(&wq_pool_attach_mutex);
7dbc725e
TH
5402
5403 /* is @cpu allowed for @pool? */
5404 if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
5405 return;
5406
7dbc725e 5407 cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
7dbc725e
TH
5408
5409 /* as we're called from CPU_ONLINE, the following shouldn't fail */
da028469 5410 for_each_pool_worker(worker, pool)
d945b5e9 5411 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
7dbc725e
TH
5412}
5413
7ee681b2
TG
5414int workqueue_prepare_cpu(unsigned int cpu)
5415{
5416 struct worker_pool *pool;
5417
5418 for_each_cpu_worker_pool(pool, cpu) {
5419 if (pool->nr_workers)
5420 continue;
5421 if (!create_worker(pool))
5422 return -ENOMEM;
5423 }
5424 return 0;
5425}
5426
5427int workqueue_online_cpu(unsigned int cpu)
3af24433 5428{
4ce62e9e 5429 struct worker_pool *pool;
4c16bd32 5430 struct workqueue_struct *wq;
7dbc725e 5431 int pi;
3ce63377 5432
7ee681b2 5433 mutex_lock(&wq_pool_mutex);
7dbc725e 5434
7ee681b2 5435 for_each_pool(pool, pi) {
1258fae7 5436 mutex_lock(&wq_pool_attach_mutex);
94cf58bb 5437
7ee681b2
TG
5438 if (pool->cpu == cpu)
5439 rebind_workers(pool);
5440 else if (pool->cpu < 0)
5441 restore_unbound_workers_cpumask(pool, cpu);
94cf58bb 5442
1258fae7 5443 mutex_unlock(&wq_pool_attach_mutex);
7ee681b2 5444 }
6ba94429 5445
fef59c9c 5446 /* update pod affinity of unbound workqueues */
4cbfd3de
TH
5447 list_for_each_entry(wq, &workqueues, list) {
5448 int tcpu;
5449
5450 for_each_possible_cpu(tcpu) {
5451 if (cpu_to_node(tcpu) == cpu_to_node(cpu)) {
fef59c9c 5452 wq_update_pod(wq, tcpu, cpu, true);
4cbfd3de
TH
5453 }
5454 }
5455 }
6ba94429 5456
7ee681b2
TG
5457 mutex_unlock(&wq_pool_mutex);
5458 return 0;
6ba94429
FW
5459}
5460
7ee681b2 5461int workqueue_offline_cpu(unsigned int cpu)
6ba94429 5462{
6ba94429
FW
5463 struct workqueue_struct *wq;
5464
7ee681b2 5465 /* unbinding per-cpu workers should happen on the local CPU */
e8b3f8db
LJ
5466 if (WARN_ON(cpu != smp_processor_id()))
5467 return -1;
5468
5469 unbind_workers(cpu);
7ee681b2 5470
fef59c9c 5471 /* update pod affinity of unbound workqueues */
7ee681b2 5472 mutex_lock(&wq_pool_mutex);
4cbfd3de
TH
5473 list_for_each_entry(wq, &workqueues, list) {
5474 int tcpu;
5475
5476 for_each_possible_cpu(tcpu) {
5477 if (cpu_to_node(tcpu) == cpu_to_node(cpu)) {
fef59c9c 5478 wq_update_pod(wq, tcpu, cpu, false);
4cbfd3de
TH
5479 }
5480 }
5481 }
7ee681b2
TG
5482 mutex_unlock(&wq_pool_mutex);
5483
7ee681b2 5484 return 0;
6ba94429
FW
5485}
5486
6ba94429
FW
5487struct work_for_cpu {
5488 struct work_struct work;
5489 long (*fn)(void *);
5490 void *arg;
5491 long ret;
5492};
5493
5494static void work_for_cpu_fn(struct work_struct *work)
5495{
5496 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
5497
5498 wfc->ret = wfc->fn(wfc->arg);
5499}
5500
5501/**
22aceb31 5502 * work_on_cpu - run a function in thread context on a particular cpu
6ba94429
FW
5503 * @cpu: the cpu to run on
5504 * @fn: the function to run
5505 * @arg: the function arg
5506 *
5507 * It is up to the caller to ensure that the cpu doesn't go offline.
5508 * The caller must not hold any locks which would prevent @fn from completing.
5509 *
5510 * Return: The value @fn returns.
5511 */
5512long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
5513{
5514 struct work_for_cpu wfc = { .fn = fn, .arg = arg };
5515
5516 INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
5517 schedule_work_on(cpu, &wfc.work);
5518 flush_work(&wfc.work);
5519 destroy_work_on_stack(&wfc.work);
5520 return wfc.ret;
5521}
5522EXPORT_SYMBOL_GPL(work_on_cpu);
0e8d6a93
TG
5523
5524/**
5525 * work_on_cpu_safe - run a function in thread context on a particular cpu
5526 * @cpu: the cpu to run on
5527 * @fn: the function to run
5528 * @arg: the function argument
5529 *
5530 * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
5531 * any locks which would prevent @fn from completing.
5532 *
5533 * Return: The value @fn returns.
5534 */
5535long work_on_cpu_safe(int cpu, long (*fn)(void *), void *arg)
5536{
5537 long ret = -ENODEV;
5538
ffd8bea8 5539 cpus_read_lock();
0e8d6a93
TG
5540 if (cpu_online(cpu))
5541 ret = work_on_cpu(cpu, fn, arg);
ffd8bea8 5542 cpus_read_unlock();
0e8d6a93
TG
5543 return ret;
5544}
5545EXPORT_SYMBOL_GPL(work_on_cpu_safe);
6ba94429
FW
5546#endif /* CONFIG_SMP */
5547
5548#ifdef CONFIG_FREEZER
5549
5550/**
5551 * freeze_workqueues_begin - begin freezing workqueues
5552 *
5553 * Start freezing workqueues. After this function returns, all freezable
f97a4a1a 5554 * workqueues will queue new works to their inactive_works list instead of
6ba94429
FW
5555 * pool->worklist.
5556 *
5557 * CONTEXT:
5558 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5559 */
5560void freeze_workqueues_begin(void)
5561{
5562 struct workqueue_struct *wq;
5563 struct pool_workqueue *pwq;
5564
5565 mutex_lock(&wq_pool_mutex);
5566
5567 WARN_ON_ONCE(workqueue_freezing);
5568 workqueue_freezing = true;
5569
5570 list_for_each_entry(wq, &workqueues, list) {
5571 mutex_lock(&wq->mutex);
5572 for_each_pwq(pwq, wq)
5573 pwq_adjust_max_active(pwq);
5574 mutex_unlock(&wq->mutex);
5575 }
5576
5577 mutex_unlock(&wq_pool_mutex);
5578}
5579
5580/**
5581 * freeze_workqueues_busy - are freezable workqueues still busy?
5582 *
5583 * Check whether freezing is complete. This function must be called
5584 * between freeze_workqueues_begin() and thaw_workqueues().
5585 *
5586 * CONTEXT:
5587 * Grabs and releases wq_pool_mutex.
5588 *
5589 * Return:
5590 * %true if some freezable workqueues are still busy. %false if freezing
5591 * is complete.
5592 */
5593bool freeze_workqueues_busy(void)
5594{
5595 bool busy = false;
5596 struct workqueue_struct *wq;
5597 struct pool_workqueue *pwq;
5598
5599 mutex_lock(&wq_pool_mutex);
5600
5601 WARN_ON_ONCE(!workqueue_freezing);
5602
5603 list_for_each_entry(wq, &workqueues, list) {
5604 if (!(wq->flags & WQ_FREEZABLE))
5605 continue;
5606 /*
5607 * nr_active is monotonically decreasing. It's safe
5608 * to peek without lock.
5609 */
24acfb71 5610 rcu_read_lock();
6ba94429
FW
5611 for_each_pwq(pwq, wq) {
5612 WARN_ON_ONCE(pwq->nr_active < 0);
5613 if (pwq->nr_active) {
5614 busy = true;
24acfb71 5615 rcu_read_unlock();
6ba94429
FW
5616 goto out_unlock;
5617 }
5618 }
24acfb71 5619 rcu_read_unlock();
6ba94429
FW
5620 }
5621out_unlock:
5622 mutex_unlock(&wq_pool_mutex);
5623 return busy;
5624}
5625
5626/**
5627 * thaw_workqueues - thaw workqueues
5628 *
5629 * Thaw workqueues. Normal queueing is restored and all collected
5630 * frozen works are transferred to their respective pool worklists.
5631 *
5632 * CONTEXT:
5633 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5634 */
5635void thaw_workqueues(void)
5636{
5637 struct workqueue_struct *wq;
5638 struct pool_workqueue *pwq;
5639
5640 mutex_lock(&wq_pool_mutex);
5641
5642 if (!workqueue_freezing)
5643 goto out_unlock;
5644
5645 workqueue_freezing = false;
5646
5647 /* restore max_active and repopulate worklist */
5648 list_for_each_entry(wq, &workqueues, list) {
5649 mutex_lock(&wq->mutex);
5650 for_each_pwq(pwq, wq)
5651 pwq_adjust_max_active(pwq);
5652 mutex_unlock(&wq->mutex);
5653 }
5654
5655out_unlock:
5656 mutex_unlock(&wq_pool_mutex);
5657}
5658#endif /* CONFIG_FREEZER */
5659
99c621ef 5660static int workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask)
042f7df1
LJ
5661{
5662 LIST_HEAD(ctxs);
5663 int ret = 0;
5664 struct workqueue_struct *wq;
5665 struct apply_wqattrs_ctx *ctx, *n;
5666
5667 lockdep_assert_held(&wq_pool_mutex);
5668
5669 list_for_each_entry(wq, &workqueues, list) {
5670 if (!(wq->flags & WQ_UNBOUND))
5671 continue;
5672 /* creating multiple pwqs breaks ordering guarantee */
5673 if (wq->flags & __WQ_ORDERED)
5674 continue;
5675
99c621ef 5676 ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs, unbound_cpumask);
042f7df1
LJ
5677 if (!ctx) {
5678 ret = -ENOMEM;
5679 break;
5680 }
5681
5682 list_add_tail(&ctx->list, &ctxs);
5683 }
5684
5685 list_for_each_entry_safe(ctx, n, &ctxs, list) {
5686 if (!ret)
5687 apply_wqattrs_commit(ctx);
5688 apply_wqattrs_cleanup(ctx);
5689 }
5690
99c621ef
LJ
5691 if (!ret) {
5692 mutex_lock(&wq_pool_attach_mutex);
5693 cpumask_copy(wq_unbound_cpumask, unbound_cpumask);
5694 mutex_unlock(&wq_pool_attach_mutex);
5695 }
042f7df1
LJ
5696 return ret;
5697}
5698
5699/**
5700 * workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
5701 * @cpumask: the cpumask to set
5702 *
5703 * The low-level workqueues cpumask is a global cpumask that limits
5704 * the affinity of all unbound workqueues. This function check the @cpumask
5705 * and apply it to all unbound workqueues and updates all pwqs of them.
5706 *
67dc8325 5707 * Return: 0 - Success
042f7df1
LJ
5708 * -EINVAL - Invalid @cpumask
5709 * -ENOMEM - Failed to allocate memory for attrs or pwqs.
5710 */
5711int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
5712{
5713 int ret = -EINVAL;
042f7df1 5714
c98a9805
TS
5715 /*
5716 * Not excluding isolated cpus on purpose.
5717 * If the user wishes to include them, we allow that.
5718 */
042f7df1
LJ
5719 cpumask_and(cpumask, cpumask, cpu_possible_mask);
5720 if (!cpumask_empty(cpumask)) {
a0111cf6 5721 apply_wqattrs_lock();
d25302e4
MD
5722 if (cpumask_equal(cpumask, wq_unbound_cpumask)) {
5723 ret = 0;
5724 goto out_unlock;
5725 }
5726
99c621ef 5727 ret = workqueue_apply_unbound_cpumask(cpumask);
042f7df1 5728
d25302e4 5729out_unlock:
a0111cf6 5730 apply_wqattrs_unlock();
042f7df1 5731 }
042f7df1 5732
042f7df1
LJ
5733 return ret;
5734}
5735
6ba94429
FW
5736#ifdef CONFIG_SYSFS
5737/*
5738 * Workqueues with WQ_SYSFS flag set is visible to userland via
5739 * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
5740 * following attributes.
5741 *
5742 * per_cpu RO bool : whether the workqueue is per-cpu or unbound
5743 * max_active RW int : maximum number of in-flight work items
5744 *
5745 * Unbound workqueues have the following extra attributes.
5746 *
6ba94429
FW
5747 * nice RW int : nice value of the workers
5748 * cpumask RW mask : bitmask of allowed CPUs for the workers
5749 */
5750struct wq_device {
5751 struct workqueue_struct *wq;
5752 struct device dev;
5753};
5754
5755static struct workqueue_struct *dev_to_wq(struct device *dev)
5756{
5757 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
5758
5759 return wq_dev->wq;
5760}
5761
5762static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
5763 char *buf)
5764{
5765 struct workqueue_struct *wq = dev_to_wq(dev);
5766
5767 return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
5768}
5769static DEVICE_ATTR_RO(per_cpu);
5770
5771static ssize_t max_active_show(struct device *dev,
5772 struct device_attribute *attr, char *buf)
5773{
5774 struct workqueue_struct *wq = dev_to_wq(dev);
5775
5776 return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
5777}
5778
5779static ssize_t max_active_store(struct device *dev,
5780 struct device_attribute *attr, const char *buf,
5781 size_t count)
5782{
5783 struct workqueue_struct *wq = dev_to_wq(dev);
5784 int val;
5785
5786 if (sscanf(buf, "%d", &val) != 1 || val <= 0)
5787 return -EINVAL;
5788
5789 workqueue_set_max_active(wq, val);
5790 return count;
5791}
5792static DEVICE_ATTR_RW(max_active);
5793
5794static struct attribute *wq_sysfs_attrs[] = {
5795 &dev_attr_per_cpu.attr,
5796 &dev_attr_max_active.attr,
5797 NULL,
5798};
5799ATTRIBUTE_GROUPS(wq_sysfs);
5800
6ba94429
FW
5801static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
5802 char *buf)
5803{
5804 struct workqueue_struct *wq = dev_to_wq(dev);
5805 int written;
5806
5807 mutex_lock(&wq->mutex);
5808 written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
5809 mutex_unlock(&wq->mutex);
5810
5811 return written;
5812}
5813
5814/* prepare workqueue_attrs for sysfs store operations */
5815static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
5816{
5817 struct workqueue_attrs *attrs;
5818
899a94fe
LJ
5819 lockdep_assert_held(&wq_pool_mutex);
5820
be69d00d 5821 attrs = alloc_workqueue_attrs();
6ba94429
FW
5822 if (!attrs)
5823 return NULL;
5824
6ba94429 5825 copy_workqueue_attrs(attrs, wq->unbound_attrs);
6ba94429
FW
5826 return attrs;
5827}
5828
5829static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
5830 const char *buf, size_t count)
5831{
5832 struct workqueue_struct *wq = dev_to_wq(dev);
5833 struct workqueue_attrs *attrs;
d4d3e257
LJ
5834 int ret = -ENOMEM;
5835
5836 apply_wqattrs_lock();
6ba94429
FW
5837
5838 attrs = wq_sysfs_prep_attrs(wq);
5839 if (!attrs)
d4d3e257 5840 goto out_unlock;
6ba94429
FW
5841
5842 if (sscanf(buf, "%d", &attrs->nice) == 1 &&
5843 attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
d4d3e257 5844 ret = apply_workqueue_attrs_locked(wq, attrs);
6ba94429
FW
5845 else
5846 ret = -EINVAL;
5847
d4d3e257
LJ
5848out_unlock:
5849 apply_wqattrs_unlock();
6ba94429
FW
5850 free_workqueue_attrs(attrs);
5851 return ret ?: count;
5852}
5853
5854static ssize_t wq_cpumask_show(struct device *dev,
5855 struct device_attribute *attr, char *buf)
5856{
5857 struct workqueue_struct *wq = dev_to_wq(dev);
5858 int written;
5859
5860 mutex_lock(&wq->mutex);
5861 written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
5862 cpumask_pr_args(wq->unbound_attrs->cpumask));
5863 mutex_unlock(&wq->mutex);
5864 return written;
5865}
5866
5867static ssize_t wq_cpumask_store(struct device *dev,
5868 struct device_attribute *attr,
5869 const char *buf, size_t count)
5870{
5871 struct workqueue_struct *wq = dev_to_wq(dev);
5872 struct workqueue_attrs *attrs;
d4d3e257
LJ
5873 int ret = -ENOMEM;
5874
5875 apply_wqattrs_lock();
6ba94429
FW
5876
5877 attrs = wq_sysfs_prep_attrs(wq);
5878 if (!attrs)
d4d3e257 5879 goto out_unlock;
6ba94429
FW
5880
5881 ret = cpumask_parse(buf, attrs->cpumask);
5882 if (!ret)
d4d3e257 5883 ret = apply_workqueue_attrs_locked(wq, attrs);
6ba94429 5884
d4d3e257
LJ
5885out_unlock:
5886 apply_wqattrs_unlock();
6ba94429
FW
5887 free_workqueue_attrs(attrs);
5888 return ret ?: count;
5889}
5890
6ba94429 5891static struct device_attribute wq_sysfs_unbound_attrs[] = {
6ba94429
FW
5892 __ATTR(nice, 0644, wq_nice_show, wq_nice_store),
5893 __ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
6ba94429
FW
5894 __ATTR_NULL,
5895};
8ccad40d 5896
6ba94429
FW
5897static struct bus_type wq_subsys = {
5898 .name = "workqueue",
5899 .dev_groups = wq_sysfs_groups,
2d3854a3
RR
5900};
5901
b05a7928
FW
5902static ssize_t wq_unbound_cpumask_show(struct device *dev,
5903 struct device_attribute *attr, char *buf)
5904{
5905 int written;
5906
042f7df1 5907 mutex_lock(&wq_pool_mutex);
b05a7928
FW
5908 written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
5909 cpumask_pr_args(wq_unbound_cpumask));
042f7df1 5910 mutex_unlock(&wq_pool_mutex);
b05a7928
FW
5911
5912 return written;
5913}
5914
042f7df1
LJ
5915static ssize_t wq_unbound_cpumask_store(struct device *dev,
5916 struct device_attribute *attr, const char *buf, size_t count)
5917{
5918 cpumask_var_t cpumask;
5919 int ret;
5920
5921 if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
5922 return -ENOMEM;
5923
5924 ret = cpumask_parse(buf, cpumask);
5925 if (!ret)
5926 ret = workqueue_set_unbound_cpumask(cpumask);
5927
5928 free_cpumask_var(cpumask);
5929 return ret ? ret : count;
5930}
5931
b05a7928 5932static struct device_attribute wq_sysfs_cpumask_attr =
042f7df1
LJ
5933 __ATTR(cpumask, 0644, wq_unbound_cpumask_show,
5934 wq_unbound_cpumask_store);
b05a7928 5935
6ba94429 5936static int __init wq_sysfs_init(void)
2d3854a3 5937{
686f6697 5938 struct device *dev_root;
b05a7928
FW
5939 int err;
5940
5941 err = subsys_virtual_register(&wq_subsys, NULL);
5942 if (err)
5943 return err;
5944
686f6697
GKH
5945 dev_root = bus_get_dev_root(&wq_subsys);
5946 if (dev_root) {
5947 err = device_create_file(dev_root, &wq_sysfs_cpumask_attr);
5948 put_device(dev_root);
5949 }
5950 return err;
2d3854a3 5951}
6ba94429 5952core_initcall(wq_sysfs_init);
2d3854a3 5953
6ba94429 5954static void wq_device_release(struct device *dev)
2d3854a3 5955{
6ba94429 5956 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
6b44003e 5957
6ba94429 5958 kfree(wq_dev);
2d3854a3 5959}
a0a1a5fd
TH
5960
5961/**
6ba94429
FW
5962 * workqueue_sysfs_register - make a workqueue visible in sysfs
5963 * @wq: the workqueue to register
a0a1a5fd 5964 *
6ba94429
FW
5965 * Expose @wq in sysfs under /sys/bus/workqueue/devices.
5966 * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
5967 * which is the preferred method.
a0a1a5fd 5968 *
6ba94429
FW
5969 * Workqueue user should use this function directly iff it wants to apply
5970 * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
5971 * apply_workqueue_attrs() may race against userland updating the
5972 * attributes.
5973 *
5974 * Return: 0 on success, -errno on failure.
a0a1a5fd 5975 */
6ba94429 5976int workqueue_sysfs_register(struct workqueue_struct *wq)
a0a1a5fd 5977{
6ba94429
FW
5978 struct wq_device *wq_dev;
5979 int ret;
a0a1a5fd 5980
6ba94429 5981 /*
402dd89d 5982 * Adjusting max_active or creating new pwqs by applying
6ba94429
FW
5983 * attributes breaks ordering guarantee. Disallow exposing ordered
5984 * workqueues.
5985 */
0a94efb5 5986 if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
6ba94429 5987 return -EINVAL;
a0a1a5fd 5988
6ba94429
FW
5989 wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
5990 if (!wq_dev)
5991 return -ENOMEM;
5bcab335 5992
6ba94429
FW
5993 wq_dev->wq = wq;
5994 wq_dev->dev.bus = &wq_subsys;
6ba94429 5995 wq_dev->dev.release = wq_device_release;
23217b44 5996 dev_set_name(&wq_dev->dev, "%s", wq->name);
a0a1a5fd 5997
6ba94429
FW
5998 /*
5999 * unbound_attrs are created separately. Suppress uevent until
6000 * everything is ready.
6001 */
6002 dev_set_uevent_suppress(&wq_dev->dev, true);
a0a1a5fd 6003
6ba94429
FW
6004 ret = device_register(&wq_dev->dev);
6005 if (ret) {
537f4146 6006 put_device(&wq_dev->dev);
6ba94429
FW
6007 wq->wq_dev = NULL;
6008 return ret;
6009 }
a0a1a5fd 6010
6ba94429
FW
6011 if (wq->flags & WQ_UNBOUND) {
6012 struct device_attribute *attr;
a0a1a5fd 6013
6ba94429
FW
6014 for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
6015 ret = device_create_file(&wq_dev->dev, attr);
6016 if (ret) {
6017 device_unregister(&wq_dev->dev);
6018 wq->wq_dev = NULL;
6019 return ret;
a0a1a5fd
TH
6020 }
6021 }
6022 }
6ba94429
FW
6023
6024 dev_set_uevent_suppress(&wq_dev->dev, false);
6025 kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
6026 return 0;
a0a1a5fd
TH
6027}
6028
6029/**
6ba94429
FW
6030 * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
6031 * @wq: the workqueue to unregister
a0a1a5fd 6032 *
6ba94429 6033 * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
a0a1a5fd 6034 */
6ba94429 6035static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
a0a1a5fd 6036{
6ba94429 6037 struct wq_device *wq_dev = wq->wq_dev;
8b03ae3c 6038
6ba94429
FW
6039 if (!wq->wq_dev)
6040 return;
a0a1a5fd 6041
6ba94429
FW
6042 wq->wq_dev = NULL;
6043 device_unregister(&wq_dev->dev);
a0a1a5fd 6044}
6ba94429
FW
6045#else /* CONFIG_SYSFS */
6046static void workqueue_sysfs_unregister(struct workqueue_struct *wq) { }
6047#endif /* CONFIG_SYSFS */
a0a1a5fd 6048
82607adc
TH
6049/*
6050 * Workqueue watchdog.
6051 *
6052 * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
6053 * flush dependency, a concurrency managed work item which stays RUNNING
6054 * indefinitely. Workqueue stalls can be very difficult to debug as the
6055 * usual warning mechanisms don't trigger and internal workqueue state is
6056 * largely opaque.
6057 *
6058 * Workqueue watchdog monitors all worker pools periodically and dumps
6059 * state if some pools failed to make forward progress for a while where
6060 * forward progress is defined as the first item on ->worklist changing.
6061 *
6062 * This mechanism is controlled through the kernel parameter
6063 * "workqueue.watchdog_thresh" which can be updated at runtime through the
6064 * corresponding sysfs parameter file.
6065 */
6066#ifdef CONFIG_WQ_WATCHDOG
6067
82607adc 6068static unsigned long wq_watchdog_thresh = 30;
5cd79d6a 6069static struct timer_list wq_watchdog_timer;
82607adc
TH
6070
6071static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
6072static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
6073
cd2440d6
PM
6074/*
6075 * Show workers that might prevent the processing of pending work items.
6076 * The only candidates are CPU-bound workers in the running state.
6077 * Pending work items should be handled by another idle worker
6078 * in all other situations.
6079 */
6080static void show_cpu_pool_hog(struct worker_pool *pool)
6081{
6082 struct worker *worker;
6083 unsigned long flags;
6084 int bkt;
6085
6086 raw_spin_lock_irqsave(&pool->lock, flags);
6087
6088 hash_for_each(pool->busy_hash, bkt, worker, hentry) {
6089 if (task_is_running(worker->task)) {
6090 /*
6091 * Defer printing to avoid deadlocks in console
6092 * drivers that queue work while holding locks
6093 * also taken in their write paths.
6094 */
6095 printk_deferred_enter();
6096
6097 pr_info("pool %d:\n", pool->id);
6098 sched_show_task(worker->task);
6099
6100 printk_deferred_exit();
6101 }
6102 }
6103
6104 raw_spin_unlock_irqrestore(&pool->lock, flags);
6105}
6106
6107static void show_cpu_pools_hogs(void)
6108{
6109 struct worker_pool *pool;
6110 int pi;
6111
6112 pr_info("Showing backtraces of running workers in stalled CPU-bound worker pools:\n");
6113
6114 rcu_read_lock();
6115
6116 for_each_pool(pool, pi) {
6117 if (pool->cpu_stall)
6118 show_cpu_pool_hog(pool);
6119
6120 }
6121
6122 rcu_read_unlock();
6123}
6124
82607adc
TH
6125static void wq_watchdog_reset_touched(void)
6126{
6127 int cpu;
6128
6129 wq_watchdog_touched = jiffies;
6130 for_each_possible_cpu(cpu)
6131 per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
6132}
6133
5cd79d6a 6134static void wq_watchdog_timer_fn(struct timer_list *unused)
82607adc
TH
6135{
6136 unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
6137 bool lockup_detected = false;
cd2440d6 6138 bool cpu_pool_stall = false;
940d71c6 6139 unsigned long now = jiffies;
82607adc
TH
6140 struct worker_pool *pool;
6141 int pi;
6142
6143 if (!thresh)
6144 return;
6145
6146 rcu_read_lock();
6147
6148 for_each_pool(pool, pi) {
6149 unsigned long pool_ts, touched, ts;
6150
cd2440d6 6151 pool->cpu_stall = false;
82607adc
TH
6152 if (list_empty(&pool->worklist))
6153 continue;
6154
940d71c6
SS
6155 /*
6156 * If a virtual machine is stopped by the host it can look to
6157 * the watchdog like a stall.
6158 */
6159 kvm_check_and_clear_guest_paused();
6160
82607adc 6161 /* get the latest of pool and touched timestamps */
89e28ce6
WQ
6162 if (pool->cpu >= 0)
6163 touched = READ_ONCE(per_cpu(wq_watchdog_touched_cpu, pool->cpu));
6164 else
6165 touched = READ_ONCE(wq_watchdog_touched);
82607adc 6166 pool_ts = READ_ONCE(pool->watchdog_ts);
82607adc
TH
6167
6168 if (time_after(pool_ts, touched))
6169 ts = pool_ts;
6170 else
6171 ts = touched;
6172
82607adc 6173 /* did we stall? */
940d71c6 6174 if (time_after(now, ts + thresh)) {
82607adc 6175 lockup_detected = true;
cd2440d6
PM
6176 if (pool->cpu >= 0) {
6177 pool->cpu_stall = true;
6178 cpu_pool_stall = true;
6179 }
82607adc
TH
6180 pr_emerg("BUG: workqueue lockup - pool");
6181 pr_cont_pool_info(pool);
6182 pr_cont(" stuck for %us!\n",
940d71c6 6183 jiffies_to_msecs(now - pool_ts) / 1000);
82607adc 6184 }
cd2440d6
PM
6185
6186
82607adc
TH
6187 }
6188
6189 rcu_read_unlock();
6190
6191 if (lockup_detected)
55df0933 6192 show_all_workqueues();
82607adc 6193
cd2440d6
PM
6194 if (cpu_pool_stall)
6195 show_cpu_pools_hogs();
6196
82607adc
TH
6197 wq_watchdog_reset_touched();
6198 mod_timer(&wq_watchdog_timer, jiffies + thresh);
6199}
6200
cb9d7fd5 6201notrace void wq_watchdog_touch(int cpu)
82607adc
TH
6202{
6203 if (cpu >= 0)
6204 per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
89e28ce6
WQ
6205
6206 wq_watchdog_touched = jiffies;
82607adc
TH
6207}
6208
6209static void wq_watchdog_set_thresh(unsigned long thresh)
6210{
6211 wq_watchdog_thresh = 0;
6212 del_timer_sync(&wq_watchdog_timer);
6213
6214 if (thresh) {
6215 wq_watchdog_thresh = thresh;
6216 wq_watchdog_reset_touched();
6217 mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
6218 }
6219}
6220
6221static int wq_watchdog_param_set_thresh(const char *val,
6222 const struct kernel_param *kp)
6223{
6224 unsigned long thresh;
6225 int ret;
6226
6227 ret = kstrtoul(val, 0, &thresh);
6228 if (ret)
6229 return ret;
6230
6231 if (system_wq)
6232 wq_watchdog_set_thresh(thresh);
6233 else
6234 wq_watchdog_thresh = thresh;
6235
6236 return 0;
6237}
6238
6239static const struct kernel_param_ops wq_watchdog_thresh_ops = {
6240 .set = wq_watchdog_param_set_thresh,
6241 .get = param_get_ulong,
6242};
6243
6244module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
6245 0644);
6246
6247static void wq_watchdog_init(void)
6248{
5cd79d6a 6249 timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
82607adc
TH
6250 wq_watchdog_set_thresh(wq_watchdog_thresh);
6251}
6252
6253#else /* CONFIG_WQ_WATCHDOG */
6254
6255static inline void wq_watchdog_init(void) { }
6256
6257#endif /* CONFIG_WQ_WATCHDOG */
6258
3347fa09
TH
6259/**
6260 * workqueue_init_early - early init for workqueue subsystem
6261 *
2930155b
TH
6262 * This is the first step of three-staged workqueue subsystem initialization and
6263 * invoked as soon as the bare basics - memory allocation, cpumasks and idr are
6264 * up. It sets up all the data structures and system workqueues and allows early
6265 * boot code to create workqueues and queue/cancel work items. Actual work item
6266 * execution starts only after kthreads can be created and scheduled right
6267 * before early initcalls.
3347fa09 6268 */
2333e829 6269void __init workqueue_init_early(void)
1da177e4 6270{
7a4e344c
TH
6271 int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
6272 int i, cpu;
c34056a3 6273
10cdb157 6274 BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
e904e6c2 6275
b05a7928 6276 BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
04d4e665
FW
6277 cpumask_copy(wq_unbound_cpumask, housekeeping_cpumask(HK_TYPE_WQ));
6278 cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, housekeeping_cpumask(HK_TYPE_DOMAIN));
b05a7928 6279
ace3c549 6280 if (!cpumask_empty(&wq_cmdline_cpumask))
6281 cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, &wq_cmdline_cpumask);
6282
e904e6c2
TH
6283 pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
6284
2930155b
TH
6285 wq_update_pod_attrs_buf = alloc_workqueue_attrs();
6286 BUG_ON(!wq_update_pod_attrs_buf);
6287
706026c2 6288 /* initialize CPU pools */
29c91e99 6289 for_each_possible_cpu(cpu) {
4ce62e9e 6290 struct worker_pool *pool;
8b03ae3c 6291
7a4e344c 6292 i = 0;
f02ae73a 6293 for_each_cpu_worker_pool(pool, cpu) {
7a4e344c 6294 BUG_ON(init_worker_pool(pool));
ec22ca5e 6295 pool->cpu = cpu;
29c91e99 6296 cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
7a4e344c 6297 pool->attrs->nice = std_nice[i++];
f3f90ad4 6298 pool->node = cpu_to_node(cpu);
7a4e344c 6299
9daf9e67 6300 /* alloc pool ID */
68e13a67 6301 mutex_lock(&wq_pool_mutex);
9daf9e67 6302 BUG_ON(worker_pool_assign_id(pool));
68e13a67 6303 mutex_unlock(&wq_pool_mutex);
4ce62e9e 6304 }
8b03ae3c
TH
6305 }
6306
8a2b7538 6307 /* create default unbound and ordered wq attrs */
29c91e99
TH
6308 for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
6309 struct workqueue_attrs *attrs;
6310
be69d00d 6311 BUG_ON(!(attrs = alloc_workqueue_attrs()));
29c91e99 6312 attrs->nice = std_nice[i];
29c91e99 6313 unbound_std_wq_attrs[i] = attrs;
8a2b7538
TH
6314
6315 /*
6316 * An ordered wq should have only one pwq as ordering is
6317 * guaranteed by max_active which is enforced by pwqs.
8a2b7538 6318 */
be69d00d 6319 BUG_ON(!(attrs = alloc_workqueue_attrs()));
8a2b7538 6320 attrs->nice = std_nice[i];
af73f5c9 6321 attrs->ordered = true;
8a2b7538 6322 ordered_wq_attrs[i] = attrs;
29c91e99
TH
6323 }
6324
d320c038 6325 system_wq = alloc_workqueue("events", 0, 0);
1aabe902 6326 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
d320c038 6327 system_long_wq = alloc_workqueue("events_long", 0, 0);
f3421797 6328 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
636b927e 6329 WQ_MAX_ACTIVE);
24d51add
TH
6330 system_freezable_wq = alloc_workqueue("events_freezable",
6331 WQ_FREEZABLE, 0);
0668106c
VK
6332 system_power_efficient_wq = alloc_workqueue("events_power_efficient",
6333 WQ_POWER_EFFICIENT, 0);
6334 system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
6335 WQ_FREEZABLE | WQ_POWER_EFFICIENT,
6336 0);
1aabe902 6337 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
0668106c
VK
6338 !system_unbound_wq || !system_freezable_wq ||
6339 !system_power_efficient_wq ||
6340 !system_freezable_power_efficient_wq);
3347fa09
TH
6341}
6342
aa6fde93
TH
6343static void __init wq_cpu_intensive_thresh_init(void)
6344{
6345 unsigned long thresh;
6346 unsigned long bogo;
6347
6348 /* if the user set it to a specific value, keep it */
6349 if (wq_cpu_intensive_thresh_us != ULONG_MAX)
6350 return;
6351
967b494e
TH
6352 pwq_release_worker = kthread_create_worker(0, "pool_workqueue_release");
6353 BUG_ON(IS_ERR(pwq_release_worker));
6354
aa6fde93
TH
6355 /*
6356 * The default of 10ms is derived from the fact that most modern (as of
6357 * 2023) processors can do a lot in 10ms and that it's just below what
6358 * most consider human-perceivable. However, the kernel also runs on a
6359 * lot slower CPUs including microcontrollers where the threshold is way
6360 * too low.
6361 *
6362 * Let's scale up the threshold upto 1 second if BogoMips is below 4000.
6363 * This is by no means accurate but it doesn't have to be. The mechanism
6364 * is still useful even when the threshold is fully scaled up. Also, as
6365 * the reports would usually be applicable to everyone, some machines
6366 * operating on longer thresholds won't significantly diminish their
6367 * usefulness.
6368 */
6369 thresh = 10 * USEC_PER_MSEC;
6370
6371 /* see init/calibrate.c for lpj -> BogoMIPS calculation */
6372 bogo = max_t(unsigned long, loops_per_jiffy / 500000 * HZ, 1);
6373 if (bogo < 4000)
6374 thresh = min_t(unsigned long, thresh * 4000 / bogo, USEC_PER_SEC);
6375
6376 pr_debug("wq_cpu_intensive_thresh: lpj=%lu BogoMIPS=%lu thresh_us=%lu\n",
6377 loops_per_jiffy, bogo, thresh);
6378
6379 wq_cpu_intensive_thresh_us = thresh;
6380}
6381
3347fa09
TH
6382/**
6383 * workqueue_init - bring workqueue subsystem fully online
6384 *
2930155b
TH
6385 * This is the second step of three-staged workqueue subsystem initialization
6386 * and invoked as soon as kthreads can be created and scheduled. Workqueues have
6387 * been created and work items queued on them, but there are no kworkers
6388 * executing the work items yet. Populate the worker pools with the initial
6389 * workers and enable future kworker creations.
3347fa09 6390 */
2333e829 6391void __init workqueue_init(void)
3347fa09 6392{
2186d9f9 6393 struct workqueue_struct *wq;
3347fa09
TH
6394 struct worker_pool *pool;
6395 int cpu, bkt;
6396
aa6fde93
TH
6397 wq_cpu_intensive_thresh_init();
6398
2186d9f9
TH
6399 mutex_lock(&wq_pool_mutex);
6400
2930155b
TH
6401 /*
6402 * Per-cpu pools created earlier could be missing node hint. Fix them
6403 * up. Also, create a rescuer for workqueues that requested it.
6404 */
2186d9f9
TH
6405 for_each_possible_cpu(cpu) {
6406 for_each_cpu_worker_pool(pool, cpu) {
6407 pool->node = cpu_to_node(cpu);
6408 }
6409 }
6410
40c17f75 6411 list_for_each_entry(wq, &workqueues, list) {
40c17f75
TH
6412 WARN(init_rescuer(wq),
6413 "workqueue: failed to create early rescuer for %s",
6414 wq->name);
6415 }
2186d9f9
TH
6416
6417 mutex_unlock(&wq_pool_mutex);
6418
3347fa09
TH
6419 /* create the initial workers */
6420 for_each_online_cpu(cpu) {
6421 for_each_cpu_worker_pool(pool, cpu) {
6422 pool->flags &= ~POOL_DISASSOCIATED;
6423 BUG_ON(!create_worker(pool));
6424 }
6425 }
6426
6427 hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
6428 BUG_ON(!create_worker(pool));
6429
6430 wq_online = true;
82607adc 6431 wq_watchdog_init();
1da177e4 6432}
c4f135d6 6433
2930155b
TH
6434/**
6435 * workqueue_init_topology - initialize CPU pods for unbound workqueues
6436 *
6437 * This is the third step of there-staged workqueue subsystem initialization and
6438 * invoked after SMP and topology information are fully initialized. It
6439 * initializes the unbound CPU pods accordingly.
6440 */
6441void __init workqueue_init_topology(void)
a86feae6 6442{
2930155b 6443 struct workqueue_struct *wq;
a86feae6
TH
6444 cpumask_var_t *tbl;
6445 int node, cpu;
6446
6447 if (num_possible_nodes() <= 1)
6448 return;
6449
6450 for_each_possible_cpu(cpu) {
6451 if (WARN_ON(cpu_to_node(cpu) == NUMA_NO_NODE)) {
6452 pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
6453 return;
6454 }
6455 }
6456
2930155b 6457 mutex_lock(&wq_pool_mutex);
a86feae6
TH
6458
6459 /*
6460 * We want masks of possible CPUs of each node which isn't readily
6461 * available. Build one from cpu_to_node() which should have been
6462 * fully initialized by now.
6463 */
6464 tbl = kcalloc(nr_node_ids, sizeof(tbl[0]), GFP_KERNEL);
6465 BUG_ON(!tbl);
6466
6467 for_each_node(node)
6468 BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
6469 node_online(node) ? node : NUMA_NO_NODE));
6470
6471 for_each_possible_cpu(cpu) {
6472 node = cpu_to_node(cpu);
6473 cpumask_set_cpu(cpu, tbl[node]);
6474 }
6475
6476 wq_pod_cpus = tbl;
6477 wq_pod_enabled = true;
2930155b
TH
6478
6479 /*
6480 * Workqueues allocated earlier would have all CPUs sharing the default
6481 * worker pool. Explicitly call wq_update_pod() on all workqueue and CPU
6482 * combinations to apply per-pod sharing.
6483 */
6484 list_for_each_entry(wq, &workqueues, list) {
6485 for_each_online_cpu(cpu) {
6486 wq_update_pod(wq, cpu, cpu, true);
6487 }
6488 }
6489
6490 mutex_unlock(&wq_pool_mutex);
a86feae6
TH
6491}
6492
20bdedaf
TH
6493void __warn_flushing_systemwide_wq(void)
6494{
6495 pr_warn("WARNING: Flushing system-wide workqueues will be prohibited in near future.\n");
6496 dump_stack();
6497}
c4f135d6 6498EXPORT_SYMBOL(__warn_flushing_systemwide_wq);
ace3c549 6499
6500static int __init workqueue_unbound_cpus_setup(char *str)
6501{
6502 if (cpulist_parse(str, &wq_cmdline_cpumask) < 0) {
6503 cpumask_clear(&wq_cmdline_cpumask);
6504 pr_warn("workqueue.unbound_cpus: incorrect CPU range, using default\n");
6505 }
6506
6507 return 1;
6508}
6509__setup("workqueue.unbound_cpus=", workqueue_unbound_cpus_setup);