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