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