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