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