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