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