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