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