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