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