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