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