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