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