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