workqueue: fix incorrect cpu number BUG_ON() in get_work_gcwq()
[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
a1e453d2 448 BUG_ON(cpu >= nr_cpu_ids);
7a22ad75 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
4ce48b37
TH
2141 /* we might have raced, check again with mutex held */
2142 if (wq->first_flusher != &this_flusher)
2143 goto out_unlock;
2144
73f53c4a
TH
2145 wq->first_flusher = NULL;
2146
2147 BUG_ON(!list_empty(&this_flusher.list));
2148 BUG_ON(wq->flush_color != this_flusher.flush_color);
2149
2150 while (true) {
2151 struct wq_flusher *next, *tmp;
2152
2153 /* complete all the flushers sharing the current flush color */
2154 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2155 if (next->flush_color != wq->flush_color)
2156 break;
2157 list_del_init(&next->list);
2158 complete(&next->done);
2159 }
2160
2161 BUG_ON(!list_empty(&wq->flusher_overflow) &&
2162 wq->flush_color != work_next_color(wq->work_color));
2163
2164 /* this flush_color is finished, advance by one */
2165 wq->flush_color = work_next_color(wq->flush_color);
2166
2167 /* one color has been freed, handle overflow queue */
2168 if (!list_empty(&wq->flusher_overflow)) {
2169 /*
2170 * Assign the same color to all overflowed
2171 * flushers, advance work_color and append to
2172 * flusher_queue. This is the start-to-wait
2173 * phase for these overflowed flushers.
2174 */
2175 list_for_each_entry(tmp, &wq->flusher_overflow, list)
2176 tmp->flush_color = wq->work_color;
2177
2178 wq->work_color = work_next_color(wq->work_color);
2179
2180 list_splice_tail_init(&wq->flusher_overflow,
2181 &wq->flusher_queue);
2182 flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2183 }
2184
2185 if (list_empty(&wq->flusher_queue)) {
2186 BUG_ON(wq->flush_color != wq->work_color);
2187 break;
2188 }
2189
2190 /*
2191 * Need to flush more colors. Make the next flusher
2192 * the new first flusher and arm cwqs.
2193 */
2194 BUG_ON(wq->flush_color == wq->work_color);
2195 BUG_ON(wq->flush_color != next->flush_color);
2196
2197 list_del_init(&next->list);
2198 wq->first_flusher = next;
2199
2200 if (flush_workqueue_prep_cwqs(wq, wq->flush_color, -1))
2201 break;
2202
2203 /*
2204 * Meh... this color is already done, clear first
2205 * flusher and repeat cascading.
2206 */
2207 wq->first_flusher = NULL;
2208 }
2209
2210out_unlock:
2211 mutex_unlock(&wq->flush_mutex);
1da177e4 2212}
ae90dd5d 2213EXPORT_SYMBOL_GPL(flush_workqueue);
1da177e4 2214
db700897
ON
2215/**
2216 * flush_work - block until a work_struct's callback has terminated
2217 * @work: the work which is to be flushed
2218 *
a67da70d
ON
2219 * Returns false if @work has already terminated.
2220 *
db700897
ON
2221 * It is expected that, prior to calling flush_work(), the caller has
2222 * arranged for the work to not be requeued, otherwise it doesn't make
2223 * sense to use this function.
2224 */
2225int flush_work(struct work_struct *work)
2226{
affee4b2 2227 struct worker *worker = NULL;
8b03ae3c 2228 struct global_cwq *gcwq;
7a22ad75 2229 struct cpu_workqueue_struct *cwq;
db700897
ON
2230 struct wq_barrier barr;
2231
2232 might_sleep();
7a22ad75
TH
2233 gcwq = get_work_gcwq(work);
2234 if (!gcwq)
db700897 2235 return 0;
a67da70d 2236
8b03ae3c 2237 spin_lock_irq(&gcwq->lock);
db700897
ON
2238 if (!list_empty(&work->entry)) {
2239 /*
2240 * See the comment near try_to_grab_pending()->smp_rmb().
7a22ad75
TH
2241 * If it was re-queued to a different gcwq under us, we
2242 * are not going to wait.
db700897
ON
2243 */
2244 smp_rmb();
7a22ad75
TH
2245 cwq = get_work_cwq(work);
2246 if (unlikely(!cwq || gcwq != cwq->gcwq))
4690c4ab 2247 goto already_gone;
db700897 2248 } else {
7a22ad75 2249 worker = find_worker_executing_work(gcwq, work);
affee4b2 2250 if (!worker)
4690c4ab 2251 goto already_gone;
7a22ad75 2252 cwq = worker->current_cwq;
db700897 2253 }
db700897 2254
affee4b2 2255 insert_wq_barrier(cwq, &barr, work, worker);
8b03ae3c 2256 spin_unlock_irq(&gcwq->lock);
7a22ad75
TH
2257
2258 lock_map_acquire(&cwq->wq->lockdep_map);
2259 lock_map_release(&cwq->wq->lockdep_map);
2260
db700897 2261 wait_for_completion(&barr.done);
dc186ad7 2262 destroy_work_on_stack(&barr.work);
db700897 2263 return 1;
4690c4ab 2264already_gone:
8b03ae3c 2265 spin_unlock_irq(&gcwq->lock);
4690c4ab 2266 return 0;
db700897
ON
2267}
2268EXPORT_SYMBOL_GPL(flush_work);
2269
6e84d644 2270/*
1f1f642e 2271 * Upon a successful return (>= 0), the caller "owns" WORK_STRUCT_PENDING bit,
6e84d644
ON
2272 * so this work can't be re-armed in any way.
2273 */
2274static int try_to_grab_pending(struct work_struct *work)
2275{
8b03ae3c 2276 struct global_cwq *gcwq;
1f1f642e 2277 int ret = -1;
6e84d644 2278
22df02bb 2279 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1f1f642e 2280 return 0;
6e84d644
ON
2281
2282 /*
2283 * The queueing is in progress, or it is already queued. Try to
2284 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
2285 */
7a22ad75
TH
2286 gcwq = get_work_gcwq(work);
2287 if (!gcwq)
6e84d644
ON
2288 return ret;
2289
8b03ae3c 2290 spin_lock_irq(&gcwq->lock);
6e84d644
ON
2291 if (!list_empty(&work->entry)) {
2292 /*
7a22ad75 2293 * This work is queued, but perhaps we locked the wrong gcwq.
6e84d644
ON
2294 * In that case we must see the new value after rmb(), see
2295 * insert_work()->wmb().
2296 */
2297 smp_rmb();
7a22ad75 2298 if (gcwq == get_work_gcwq(work)) {
dc186ad7 2299 debug_work_deactivate(work);
6e84d644 2300 list_del_init(&work->entry);
7a22ad75
TH
2301 cwq_dec_nr_in_flight(get_work_cwq(work),
2302 get_work_color(work));
6e84d644
ON
2303 ret = 1;
2304 }
2305 }
8b03ae3c 2306 spin_unlock_irq(&gcwq->lock);
6e84d644
ON
2307
2308 return ret;
2309}
2310
7a22ad75 2311static void wait_on_cpu_work(struct global_cwq *gcwq, struct work_struct *work)
b89deed3
ON
2312{
2313 struct wq_barrier barr;
affee4b2 2314 struct worker *worker;
b89deed3 2315
8b03ae3c 2316 spin_lock_irq(&gcwq->lock);
affee4b2 2317
7a22ad75
TH
2318 worker = find_worker_executing_work(gcwq, work);
2319 if (unlikely(worker))
2320 insert_wq_barrier(worker->current_cwq, &barr, work, worker);
affee4b2 2321
8b03ae3c 2322 spin_unlock_irq(&gcwq->lock);
b89deed3 2323
affee4b2 2324 if (unlikely(worker)) {
b89deed3 2325 wait_for_completion(&barr.done);
dc186ad7
TG
2326 destroy_work_on_stack(&barr.work);
2327 }
b89deed3
ON
2328}
2329
6e84d644 2330static void wait_on_work(struct work_struct *work)
b89deed3 2331{
b1f4ec17 2332 int cpu;
b89deed3 2333
f293ea92
ON
2334 might_sleep();
2335
3295f0ef
IM
2336 lock_map_acquire(&work->lockdep_map);
2337 lock_map_release(&work->lockdep_map);
4e6045f1 2338
1537663f 2339 for_each_possible_cpu(cpu)
7a22ad75 2340 wait_on_cpu_work(get_gcwq(cpu), work);
6e84d644
ON
2341}
2342
1f1f642e
ON
2343static int __cancel_work_timer(struct work_struct *work,
2344 struct timer_list* timer)
2345{
2346 int ret;
2347
2348 do {
2349 ret = (timer && likely(del_timer(timer)));
2350 if (!ret)
2351 ret = try_to_grab_pending(work);
2352 wait_on_work(work);
2353 } while (unlikely(ret < 0));
2354
7a22ad75 2355 clear_work_data(work);
1f1f642e
ON
2356 return ret;
2357}
2358
6e84d644
ON
2359/**
2360 * cancel_work_sync - block until a work_struct's callback has terminated
2361 * @work: the work which is to be flushed
2362 *
1f1f642e
ON
2363 * Returns true if @work was pending.
2364 *
6e84d644
ON
2365 * cancel_work_sync() will cancel the work if it is queued. If the work's
2366 * callback appears to be running, cancel_work_sync() will block until it
2367 * has completed.
2368 *
2369 * It is possible to use this function if the work re-queues itself. It can
2370 * cancel the work even if it migrates to another workqueue, however in that
2371 * case it only guarantees that work->func() has completed on the last queued
2372 * workqueue.
2373 *
2374 * cancel_work_sync(&delayed_work->work) should be used only if ->timer is not
2375 * pending, otherwise it goes into a busy-wait loop until the timer expires.
2376 *
2377 * The caller must ensure that workqueue_struct on which this work was last
2378 * queued can't be destroyed before this function returns.
2379 */
1f1f642e 2380int cancel_work_sync(struct work_struct *work)
6e84d644 2381{
1f1f642e 2382 return __cancel_work_timer(work, NULL);
b89deed3 2383}
28e53bdd 2384EXPORT_SYMBOL_GPL(cancel_work_sync);
b89deed3 2385
6e84d644 2386/**
f5a421a4 2387 * cancel_delayed_work_sync - reliably kill off a delayed work.
6e84d644
ON
2388 * @dwork: the delayed work struct
2389 *
1f1f642e
ON
2390 * Returns true if @dwork was pending.
2391 *
6e84d644
ON
2392 * It is possible to use this function if @dwork rearms itself via queue_work()
2393 * or queue_delayed_work(). See also the comment for cancel_work_sync().
2394 */
1f1f642e 2395int cancel_delayed_work_sync(struct delayed_work *dwork)
6e84d644 2396{
1f1f642e 2397 return __cancel_work_timer(&dwork->work, &dwork->timer);
6e84d644 2398}
f5a421a4 2399EXPORT_SYMBOL(cancel_delayed_work_sync);
1da177e4 2400
0fcb78c2
REB
2401/**
2402 * schedule_work - put work task in global workqueue
2403 * @work: job to be done
2404 *
5b0f437d
BVA
2405 * Returns zero if @work was already on the kernel-global workqueue and
2406 * non-zero otherwise.
2407 *
2408 * This puts a job in the kernel-global workqueue if it was not already
2409 * queued and leaves it in the same position on the kernel-global
2410 * workqueue otherwise.
0fcb78c2 2411 */
7ad5b3a5 2412int schedule_work(struct work_struct *work)
1da177e4 2413{
d320c038 2414 return queue_work(system_wq, work);
1da177e4 2415}
ae90dd5d 2416EXPORT_SYMBOL(schedule_work);
1da177e4 2417
c1a220e7
ZR
2418/*
2419 * schedule_work_on - put work task on a specific cpu
2420 * @cpu: cpu to put the work task on
2421 * @work: job to be done
2422 *
2423 * This puts a job on a specific cpu
2424 */
2425int schedule_work_on(int cpu, struct work_struct *work)
2426{
d320c038 2427 return queue_work_on(cpu, system_wq, work);
c1a220e7
ZR
2428}
2429EXPORT_SYMBOL(schedule_work_on);
2430
0fcb78c2
REB
2431/**
2432 * schedule_delayed_work - put work task in global workqueue after delay
52bad64d
DH
2433 * @dwork: job to be done
2434 * @delay: number of jiffies to wait or 0 for immediate execution
0fcb78c2
REB
2435 *
2436 * After waiting for a given time this puts a job in the kernel-global
2437 * workqueue.
2438 */
7ad5b3a5 2439int schedule_delayed_work(struct delayed_work *dwork,
82f67cd9 2440 unsigned long delay)
1da177e4 2441{
d320c038 2442 return queue_delayed_work(system_wq, dwork, delay);
1da177e4 2443}
ae90dd5d 2444EXPORT_SYMBOL(schedule_delayed_work);
1da177e4 2445
8c53e463
LT
2446/**
2447 * flush_delayed_work - block until a dwork_struct's callback has terminated
2448 * @dwork: the delayed work which is to be flushed
2449 *
2450 * Any timeout is cancelled, and any pending work is run immediately.
2451 */
2452void flush_delayed_work(struct delayed_work *dwork)
2453{
2454 if (del_timer_sync(&dwork->timer)) {
7a22ad75 2455 __queue_work(get_cpu(), get_work_cwq(&dwork->work)->wq,
4690c4ab 2456 &dwork->work);
8c53e463
LT
2457 put_cpu();
2458 }
2459 flush_work(&dwork->work);
2460}
2461EXPORT_SYMBOL(flush_delayed_work);
2462
0fcb78c2
REB
2463/**
2464 * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
2465 * @cpu: cpu to use
52bad64d 2466 * @dwork: job to be done
0fcb78c2
REB
2467 * @delay: number of jiffies to wait
2468 *
2469 * After waiting for a given time this puts a job in the kernel-global
2470 * workqueue on the specified CPU.
2471 */
1da177e4 2472int schedule_delayed_work_on(int cpu,
52bad64d 2473 struct delayed_work *dwork, unsigned long delay)
1da177e4 2474{
d320c038 2475 return queue_delayed_work_on(cpu, system_wq, dwork, delay);
1da177e4 2476}
ae90dd5d 2477EXPORT_SYMBOL(schedule_delayed_work_on);
1da177e4 2478
b6136773
AM
2479/**
2480 * schedule_on_each_cpu - call a function on each online CPU from keventd
2481 * @func: the function to call
b6136773
AM
2482 *
2483 * Returns zero on success.
2484 * Returns -ve errno on failure.
2485 *
b6136773
AM
2486 * schedule_on_each_cpu() is very slow.
2487 */
65f27f38 2488int schedule_on_each_cpu(work_func_t func)
15316ba8
CL
2489{
2490 int cpu;
b6136773 2491 struct work_struct *works;
15316ba8 2492
b6136773
AM
2493 works = alloc_percpu(struct work_struct);
2494 if (!works)
15316ba8 2495 return -ENOMEM;
b6136773 2496
93981800
TH
2497 get_online_cpus();
2498
15316ba8 2499 for_each_online_cpu(cpu) {
9bfb1839
IM
2500 struct work_struct *work = per_cpu_ptr(works, cpu);
2501
2502 INIT_WORK(work, func);
b71ab8c2 2503 schedule_work_on(cpu, work);
65a64464 2504 }
93981800
TH
2505
2506 for_each_online_cpu(cpu)
2507 flush_work(per_cpu_ptr(works, cpu));
2508
95402b38 2509 put_online_cpus();
b6136773 2510 free_percpu(works);
15316ba8
CL
2511 return 0;
2512}
2513
eef6a7d5
AS
2514/**
2515 * flush_scheduled_work - ensure that any scheduled work has run to completion.
2516 *
2517 * Forces execution of the kernel-global workqueue and blocks until its
2518 * completion.
2519 *
2520 * Think twice before calling this function! It's very easy to get into
2521 * trouble if you don't take great care. Either of the following situations
2522 * will lead to deadlock:
2523 *
2524 * One of the work items currently on the workqueue needs to acquire
2525 * a lock held by your code or its caller.
2526 *
2527 * Your code is running in the context of a work routine.
2528 *
2529 * They will be detected by lockdep when they occur, but the first might not
2530 * occur very often. It depends on what work items are on the workqueue and
2531 * what locks they need, which you have no control over.
2532 *
2533 * In most situations flushing the entire workqueue is overkill; you merely
2534 * need to know that a particular work item isn't queued and isn't running.
2535 * In such cases you should use cancel_delayed_work_sync() or
2536 * cancel_work_sync() instead.
2537 */
1da177e4
LT
2538void flush_scheduled_work(void)
2539{
d320c038 2540 flush_workqueue(system_wq);
1da177e4 2541}
ae90dd5d 2542EXPORT_SYMBOL(flush_scheduled_work);
1da177e4 2543
1fa44eca
JB
2544/**
2545 * execute_in_process_context - reliably execute the routine with user context
2546 * @fn: the function to execute
1fa44eca
JB
2547 * @ew: guaranteed storage for the execute work structure (must
2548 * be available when the work executes)
2549 *
2550 * Executes the function immediately if process context is available,
2551 * otherwise schedules the function for delayed execution.
2552 *
2553 * Returns: 0 - function was executed
2554 * 1 - function was scheduled for execution
2555 */
65f27f38 2556int execute_in_process_context(work_func_t fn, struct execute_work *ew)
1fa44eca
JB
2557{
2558 if (!in_interrupt()) {
65f27f38 2559 fn(&ew->work);
1fa44eca
JB
2560 return 0;
2561 }
2562
65f27f38 2563 INIT_WORK(&ew->work, fn);
1fa44eca
JB
2564 schedule_work(&ew->work);
2565
2566 return 1;
2567}
2568EXPORT_SYMBOL_GPL(execute_in_process_context);
2569
1da177e4
LT
2570int keventd_up(void)
2571{
d320c038 2572 return system_wq != NULL;
1da177e4
LT
2573}
2574
0f900049
TH
2575static struct cpu_workqueue_struct *alloc_cwqs(void)
2576{
2577 /*
2578 * cwqs are forced aligned according to WORK_STRUCT_FLAG_BITS.
2579 * Make sure that the alignment isn't lower than that of
2580 * unsigned long long.
2581 */
2582 const size_t size = sizeof(struct cpu_workqueue_struct);
2583 const size_t align = max_t(size_t, 1 << WORK_STRUCT_FLAG_BITS,
2584 __alignof__(unsigned long long));
2585 struct cpu_workqueue_struct *cwqs;
2586#ifndef CONFIG_SMP
2587 void *ptr;
2588
2589 /*
2590 * On UP, percpu allocator doesn't honor alignment parameter
2591 * and simply uses arch-dependent default. Allocate enough
2592 * room to align cwq and put an extra pointer at the end
2593 * pointing back to the originally allocated pointer which
2594 * will be used for free.
2595 *
2596 * FIXME: This really belongs to UP percpu code. Update UP
2597 * percpu code to honor alignment and remove this ugliness.
2598 */
2599 ptr = __alloc_percpu(size + align + sizeof(void *), 1);
2600 cwqs = PTR_ALIGN(ptr, align);
2601 *(void **)per_cpu_ptr(cwqs + 1, 0) = ptr;
2602#else
2603 /* On SMP, percpu allocator can do it itself */
2604 cwqs = __alloc_percpu(size, align);
2605#endif
2606 /* just in case, make sure it's actually aligned */
2607 BUG_ON(!IS_ALIGNED((unsigned long)cwqs, align));
2608 return cwqs;
2609}
2610
2611static void free_cwqs(struct cpu_workqueue_struct *cwqs)
2612{
2613#ifndef CONFIG_SMP
2614 /* on UP, the pointer to free is stored right after the cwq */
2615 if (cwqs)
2616 free_percpu(*(void **)per_cpu_ptr(cwqs + 1, 0));
2617#else
2618 free_percpu(cwqs);
2619#endif
2620}
2621
b71ab8c2
TH
2622static int wq_clamp_max_active(int max_active, const char *name)
2623{
2624 if (max_active < 1 || max_active > WQ_MAX_ACTIVE)
2625 printk(KERN_WARNING "workqueue: max_active %d requested for %s "
2626 "is out of range, clamping between %d and %d\n",
2627 max_active, name, 1, WQ_MAX_ACTIVE);
2628
2629 return clamp_val(max_active, 1, WQ_MAX_ACTIVE);
2630}
2631
d320c038
TH
2632struct workqueue_struct *__alloc_workqueue_key(const char *name,
2633 unsigned int flags,
2634 int max_active,
2635 struct lock_class_key *key,
2636 const char *lock_name)
1da177e4 2637{
1da177e4 2638 struct workqueue_struct *wq;
c34056a3 2639 unsigned int cpu;
1da177e4 2640
d320c038 2641 max_active = max_active ?: WQ_DFL_ACTIVE;
b71ab8c2 2642 max_active = wq_clamp_max_active(max_active, name);
1e19ffc6 2643
3af24433
ON
2644 wq = kzalloc(sizeof(*wq), GFP_KERNEL);
2645 if (!wq)
4690c4ab 2646 goto err;
3af24433 2647
0f900049 2648 wq->cpu_wq = alloc_cwqs();
4690c4ab
TH
2649 if (!wq->cpu_wq)
2650 goto err;
3af24433 2651
97e37d7b 2652 wq->flags = flags;
a0a1a5fd 2653 wq->saved_max_active = max_active;
73f53c4a
TH
2654 mutex_init(&wq->flush_mutex);
2655 atomic_set(&wq->nr_cwqs_to_flush, 0);
2656 INIT_LIST_HEAD(&wq->flusher_queue);
2657 INIT_LIST_HEAD(&wq->flusher_overflow);
502ca9d8
TH
2658 wq->single_cpu = NR_CPUS;
2659
3af24433 2660 wq->name = name;
eb13ba87 2661 lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
cce1a165 2662 INIT_LIST_HEAD(&wq->list);
3af24433 2663
1537663f
TH
2664 for_each_possible_cpu(cpu) {
2665 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
8b03ae3c 2666 struct global_cwq *gcwq = get_gcwq(cpu);
1537663f 2667
0f900049 2668 BUG_ON((unsigned long)cwq & WORK_STRUCT_FLAG_MASK);
8b03ae3c 2669 cwq->gcwq = gcwq;
c34056a3 2670 cwq->wq = wq;
73f53c4a 2671 cwq->flush_color = -1;
1e19ffc6 2672 cwq->max_active = max_active;
1e19ffc6 2673 INIT_LIST_HEAD(&cwq->delayed_works);
e22bee78 2674 }
1537663f 2675
e22bee78
TH
2676 if (flags & WQ_RESCUER) {
2677 struct worker *rescuer;
2678
2679 if (!alloc_cpumask_var(&wq->mayday_mask, GFP_KERNEL))
2680 goto err;
2681
2682 wq->rescuer = rescuer = alloc_worker();
2683 if (!rescuer)
2684 goto err;
2685
2686 rescuer->task = kthread_create(rescuer_thread, wq, "%s", name);
2687 if (IS_ERR(rescuer->task))
2688 goto err;
2689
2690 wq->rescuer = rescuer;
2691 rescuer->task->flags |= PF_THREAD_BOUND;
2692 wake_up_process(rescuer->task);
3af24433
ON
2693 }
2694
a0a1a5fd
TH
2695 /*
2696 * workqueue_lock protects global freeze state and workqueues
2697 * list. Grab it, set max_active accordingly and add the new
2698 * workqueue to workqueues list.
2699 */
1537663f 2700 spin_lock(&workqueue_lock);
a0a1a5fd
TH
2701
2702 if (workqueue_freezing && wq->flags & WQ_FREEZEABLE)
2703 for_each_possible_cpu(cpu)
2704 get_cwq(cpu, wq)->max_active = 0;
2705
1537663f 2706 list_add(&wq->list, &workqueues);
a0a1a5fd 2707
1537663f
TH
2708 spin_unlock(&workqueue_lock);
2709
3af24433 2710 return wq;
4690c4ab
TH
2711err:
2712 if (wq) {
0f900049 2713 free_cwqs(wq->cpu_wq);
e22bee78
TH
2714 free_cpumask_var(wq->mayday_mask);
2715 kfree(wq->rescuer);
4690c4ab
TH
2716 kfree(wq);
2717 }
2718 return NULL;
3af24433 2719}
d320c038 2720EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
1da177e4 2721
3af24433
ON
2722/**
2723 * destroy_workqueue - safely terminate a workqueue
2724 * @wq: target workqueue
2725 *
2726 * Safely destroy a workqueue. All work currently pending will be done first.
2727 */
2728void destroy_workqueue(struct workqueue_struct *wq)
2729{
c8e55f36 2730 unsigned int cpu;
3af24433 2731
a0a1a5fd
TH
2732 flush_workqueue(wq);
2733
2734 /*
2735 * wq list is used to freeze wq, remove from list after
2736 * flushing is complete in case freeze races us.
2737 */
95402b38 2738 spin_lock(&workqueue_lock);
b1f4ec17 2739 list_del(&wq->list);
95402b38 2740 spin_unlock(&workqueue_lock);
3af24433 2741
e22bee78 2742 /* sanity check */
73f53c4a
TH
2743 for_each_possible_cpu(cpu) {
2744 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2745 int i;
2746
73f53c4a
TH
2747 for (i = 0; i < WORK_NR_COLORS; i++)
2748 BUG_ON(cwq->nr_in_flight[i]);
1e19ffc6
TH
2749 BUG_ON(cwq->nr_active);
2750 BUG_ON(!list_empty(&cwq->delayed_works));
73f53c4a 2751 }
9b41ea72 2752
e22bee78
TH
2753 if (wq->flags & WQ_RESCUER) {
2754 kthread_stop(wq->rescuer->task);
2755 free_cpumask_var(wq->mayday_mask);
2756 }
2757
0f900049 2758 free_cwqs(wq->cpu_wq);
3af24433
ON
2759 kfree(wq);
2760}
2761EXPORT_SYMBOL_GPL(destroy_workqueue);
2762
dcd989cb
TH
2763/**
2764 * workqueue_set_max_active - adjust max_active of a workqueue
2765 * @wq: target workqueue
2766 * @max_active: new max_active value.
2767 *
2768 * Set max_active of @wq to @max_active.
2769 *
2770 * CONTEXT:
2771 * Don't call from IRQ context.
2772 */
2773void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
2774{
2775 unsigned int cpu;
2776
2777 max_active = wq_clamp_max_active(max_active, wq->name);
2778
2779 spin_lock(&workqueue_lock);
2780
2781 wq->saved_max_active = max_active;
2782
2783 for_each_possible_cpu(cpu) {
2784 struct global_cwq *gcwq = get_gcwq(cpu);
2785
2786 spin_lock_irq(&gcwq->lock);
2787
2788 if (!(wq->flags & WQ_FREEZEABLE) ||
2789 !(gcwq->flags & GCWQ_FREEZING))
2790 get_cwq(gcwq->cpu, wq)->max_active = max_active;
2791
2792 spin_unlock_irq(&gcwq->lock);
2793 }
2794
2795 spin_unlock(&workqueue_lock);
2796}
2797EXPORT_SYMBOL_GPL(workqueue_set_max_active);
2798
2799/**
2800 * workqueue_congested - test whether a workqueue is congested
2801 * @cpu: CPU in question
2802 * @wq: target workqueue
2803 *
2804 * Test whether @wq's cpu workqueue for @cpu is congested. There is
2805 * no synchronization around this function and the test result is
2806 * unreliable and only useful as advisory hints or for debugging.
2807 *
2808 * RETURNS:
2809 * %true if congested, %false otherwise.
2810 */
2811bool workqueue_congested(unsigned int cpu, struct workqueue_struct *wq)
2812{
2813 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2814
2815 return !list_empty(&cwq->delayed_works);
2816}
2817EXPORT_SYMBOL_GPL(workqueue_congested);
2818
2819/**
2820 * work_cpu - return the last known associated cpu for @work
2821 * @work: the work of interest
2822 *
2823 * RETURNS:
2824 * CPU number if @work was ever queued. NR_CPUS otherwise.
2825 */
2826unsigned int work_cpu(struct work_struct *work)
2827{
2828 struct global_cwq *gcwq = get_work_gcwq(work);
2829
2830 return gcwq ? gcwq->cpu : NR_CPUS;
2831}
2832EXPORT_SYMBOL_GPL(work_cpu);
2833
2834/**
2835 * work_busy - test whether a work is currently pending or running
2836 * @work: the work to be tested
2837 *
2838 * Test whether @work is currently pending or running. There is no
2839 * synchronization around this function and the test result is
2840 * unreliable and only useful as advisory hints or for debugging.
2841 * Especially for reentrant wqs, the pending state might hide the
2842 * running state.
2843 *
2844 * RETURNS:
2845 * OR'd bitmask of WORK_BUSY_* bits.
2846 */
2847unsigned int work_busy(struct work_struct *work)
2848{
2849 struct global_cwq *gcwq = get_work_gcwq(work);
2850 unsigned long flags;
2851 unsigned int ret = 0;
2852
2853 if (!gcwq)
2854 return false;
2855
2856 spin_lock_irqsave(&gcwq->lock, flags);
2857
2858 if (work_pending(work))
2859 ret |= WORK_BUSY_PENDING;
2860 if (find_worker_executing_work(gcwq, work))
2861 ret |= WORK_BUSY_RUNNING;
2862
2863 spin_unlock_irqrestore(&gcwq->lock, flags);
2864
2865 return ret;
2866}
2867EXPORT_SYMBOL_GPL(work_busy);
2868
db7bccf4
TH
2869/*
2870 * CPU hotplug.
2871 *
e22bee78
TH
2872 * There are two challenges in supporting CPU hotplug. Firstly, there
2873 * are a lot of assumptions on strong associations among work, cwq and
2874 * gcwq which make migrating pending and scheduled works very
2875 * difficult to implement without impacting hot paths. Secondly,
2876 * gcwqs serve mix of short, long and very long running works making
2877 * blocked draining impractical.
2878 *
2879 * This is solved by allowing a gcwq to be detached from CPU, running
2880 * it with unbound (rogue) workers and allowing it to be reattached
2881 * later if the cpu comes back online. A separate thread is created
2882 * to govern a gcwq in such state and is called the trustee of the
2883 * gcwq.
db7bccf4
TH
2884 *
2885 * Trustee states and their descriptions.
2886 *
2887 * START Command state used on startup. On CPU_DOWN_PREPARE, a
2888 * new trustee is started with this state.
2889 *
2890 * IN_CHARGE Once started, trustee will enter this state after
e22bee78
TH
2891 * assuming the manager role and making all existing
2892 * workers rogue. DOWN_PREPARE waits for trustee to
2893 * enter this state. After reaching IN_CHARGE, trustee
2894 * tries to execute the pending worklist until it's empty
2895 * and the state is set to BUTCHER, or the state is set
2896 * to RELEASE.
db7bccf4
TH
2897 *
2898 * BUTCHER Command state which is set by the cpu callback after
2899 * the cpu has went down. Once this state is set trustee
2900 * knows that there will be no new works on the worklist
2901 * and once the worklist is empty it can proceed to
2902 * killing idle workers.
2903 *
2904 * RELEASE Command state which is set by the cpu callback if the
2905 * cpu down has been canceled or it has come online
2906 * again. After recognizing this state, trustee stops
e22bee78
TH
2907 * trying to drain or butcher and clears ROGUE, rebinds
2908 * all remaining workers back to the cpu and releases
2909 * manager role.
db7bccf4
TH
2910 *
2911 * DONE Trustee will enter this state after BUTCHER or RELEASE
2912 * is complete.
2913 *
2914 * trustee CPU draining
2915 * took over down complete
2916 * START -----------> IN_CHARGE -----------> BUTCHER -----------> DONE
2917 * | | ^
2918 * | CPU is back online v return workers |
2919 * ----------------> RELEASE --------------
2920 */
2921
2922/**
2923 * trustee_wait_event_timeout - timed event wait for trustee
2924 * @cond: condition to wait for
2925 * @timeout: timeout in jiffies
2926 *
2927 * wait_event_timeout() for trustee to use. Handles locking and
2928 * checks for RELEASE request.
2929 *
2930 * CONTEXT:
2931 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2932 * multiple times. To be used by trustee.
2933 *
2934 * RETURNS:
2935 * Positive indicating left time if @cond is satisfied, 0 if timed
2936 * out, -1 if canceled.
2937 */
2938#define trustee_wait_event_timeout(cond, timeout) ({ \
2939 long __ret = (timeout); \
2940 while (!((cond) || (gcwq->trustee_state == TRUSTEE_RELEASE)) && \
2941 __ret) { \
2942 spin_unlock_irq(&gcwq->lock); \
2943 __wait_event_timeout(gcwq->trustee_wait, (cond) || \
2944 (gcwq->trustee_state == TRUSTEE_RELEASE), \
2945 __ret); \
2946 spin_lock_irq(&gcwq->lock); \
2947 } \
2948 gcwq->trustee_state == TRUSTEE_RELEASE ? -1 : (__ret); \
2949})
2950
2951/**
2952 * trustee_wait_event - event wait for trustee
2953 * @cond: condition to wait for
2954 *
2955 * wait_event() for trustee to use. Automatically handles locking and
2956 * checks for CANCEL request.
2957 *
2958 * CONTEXT:
2959 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2960 * multiple times. To be used by trustee.
2961 *
2962 * RETURNS:
2963 * 0 if @cond is satisfied, -1 if canceled.
2964 */
2965#define trustee_wait_event(cond) ({ \
2966 long __ret1; \
2967 __ret1 = trustee_wait_event_timeout(cond, MAX_SCHEDULE_TIMEOUT);\
2968 __ret1 < 0 ? -1 : 0; \
2969})
2970
2971static int __cpuinit trustee_thread(void *__gcwq)
2972{
2973 struct global_cwq *gcwq = __gcwq;
2974 struct worker *worker;
e22bee78 2975 struct work_struct *work;
db7bccf4 2976 struct hlist_node *pos;
e22bee78 2977 long rc;
db7bccf4
TH
2978 int i;
2979
2980 BUG_ON(gcwq->cpu != smp_processor_id());
2981
2982 spin_lock_irq(&gcwq->lock);
2983 /*
e22bee78
TH
2984 * Claim the manager position and make all workers rogue.
2985 * Trustee must be bound to the target cpu and can't be
2986 * cancelled.
db7bccf4
TH
2987 */
2988 BUG_ON(gcwq->cpu != smp_processor_id());
e22bee78
TH
2989 rc = trustee_wait_event(!(gcwq->flags & GCWQ_MANAGING_WORKERS));
2990 BUG_ON(rc < 0);
2991
2992 gcwq->flags |= GCWQ_MANAGING_WORKERS;
db7bccf4
TH
2993
2994 list_for_each_entry(worker, &gcwq->idle_list, entry)
cb444766 2995 worker->flags |= WORKER_ROGUE;
db7bccf4
TH
2996
2997 for_each_busy_worker(worker, i, pos, gcwq)
cb444766 2998 worker->flags |= WORKER_ROGUE;
db7bccf4 2999
e22bee78
TH
3000 /*
3001 * Call schedule() so that we cross rq->lock and thus can
3002 * guarantee sched callbacks see the rogue flag. This is
3003 * necessary as scheduler callbacks may be invoked from other
3004 * cpus.
3005 */
3006 spin_unlock_irq(&gcwq->lock);
3007 schedule();
3008 spin_lock_irq(&gcwq->lock);
3009
3010 /*
cb444766
TH
3011 * Sched callbacks are disabled now. Zap nr_running. After
3012 * this, nr_running stays zero and need_more_worker() and
3013 * keep_working() are always true as long as the worklist is
3014 * not empty.
e22bee78 3015 */
cb444766 3016 atomic_set(get_gcwq_nr_running(gcwq->cpu), 0);
e22bee78
TH
3017
3018 spin_unlock_irq(&gcwq->lock);
3019 del_timer_sync(&gcwq->idle_timer);
3020 spin_lock_irq(&gcwq->lock);
3021
db7bccf4
TH
3022 /*
3023 * We're now in charge. Notify and proceed to drain. We need
3024 * to keep the gcwq running during the whole CPU down
3025 * procedure as other cpu hotunplug callbacks may need to
3026 * flush currently running tasks.
3027 */
3028 gcwq->trustee_state = TRUSTEE_IN_CHARGE;
3029 wake_up_all(&gcwq->trustee_wait);
3030
3031 /*
3032 * The original cpu is in the process of dying and may go away
3033 * anytime now. When that happens, we and all workers would
e22bee78
TH
3034 * be migrated to other cpus. Try draining any left work. We
3035 * want to get it over with ASAP - spam rescuers, wake up as
3036 * many idlers as necessary and create new ones till the
3037 * worklist is empty. Note that if the gcwq is frozen, there
3038 * may be frozen works in freezeable cwqs. Don't declare
3039 * completion while frozen.
db7bccf4
TH
3040 */
3041 while (gcwq->nr_workers != gcwq->nr_idle ||
3042 gcwq->flags & GCWQ_FREEZING ||
3043 gcwq->trustee_state == TRUSTEE_IN_CHARGE) {
e22bee78
TH
3044 int nr_works = 0;
3045
3046 list_for_each_entry(work, &gcwq->worklist, entry) {
3047 send_mayday(work);
3048 nr_works++;
3049 }
3050
3051 list_for_each_entry(worker, &gcwq->idle_list, entry) {
3052 if (!nr_works--)
3053 break;
3054 wake_up_process(worker->task);
3055 }
3056
3057 if (need_to_create_worker(gcwq)) {
3058 spin_unlock_irq(&gcwq->lock);
3059 worker = create_worker(gcwq, false);
3060 spin_lock_irq(&gcwq->lock);
3061 if (worker) {
cb444766 3062 worker->flags |= WORKER_ROGUE;
e22bee78
TH
3063 start_worker(worker);
3064 }
3065 }
3066
db7bccf4
TH
3067 /* give a breather */
3068 if (trustee_wait_event_timeout(false, TRUSTEE_COOLDOWN) < 0)
3069 break;
3070 }
3071
e22bee78
TH
3072 /*
3073 * Either all works have been scheduled and cpu is down, or
3074 * cpu down has already been canceled. Wait for and butcher
3075 * all workers till we're canceled.
3076 */
3077 do {
3078 rc = trustee_wait_event(!list_empty(&gcwq->idle_list));
3079 while (!list_empty(&gcwq->idle_list))
3080 destroy_worker(list_first_entry(&gcwq->idle_list,
3081 struct worker, entry));
3082 } while (gcwq->nr_workers && rc >= 0);
3083
3084 /*
3085 * At this point, either draining has completed and no worker
3086 * is left, or cpu down has been canceled or the cpu is being
3087 * brought back up. There shouldn't be any idle one left.
3088 * Tell the remaining busy ones to rebind once it finishes the
3089 * currently scheduled works by scheduling the rebind_work.
3090 */
3091 WARN_ON(!list_empty(&gcwq->idle_list));
3092
3093 for_each_busy_worker(worker, i, pos, gcwq) {
3094 struct work_struct *rebind_work = &worker->rebind_work;
3095
3096 /*
3097 * Rebind_work may race with future cpu hotplug
3098 * operations. Use a separate flag to mark that
3099 * rebinding is scheduled.
3100 */
cb444766
TH
3101 worker->flags |= WORKER_REBIND;
3102 worker->flags &= ~WORKER_ROGUE;
e22bee78
TH
3103
3104 /* queue rebind_work, wq doesn't matter, use the default one */
3105 if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
3106 work_data_bits(rebind_work)))
3107 continue;
3108
3109 debug_work_activate(rebind_work);
d320c038 3110 insert_work(get_cwq(gcwq->cpu, system_wq), rebind_work,
e22bee78
TH
3111 worker->scheduled.next,
3112 work_color_to_flags(WORK_NO_COLOR));
3113 }
3114
3115 /* relinquish manager role */
3116 gcwq->flags &= ~GCWQ_MANAGING_WORKERS;
3117
db7bccf4
TH
3118 /* notify completion */
3119 gcwq->trustee = NULL;
3120 gcwq->trustee_state = TRUSTEE_DONE;
3121 wake_up_all(&gcwq->trustee_wait);
3122 spin_unlock_irq(&gcwq->lock);
3123 return 0;
3124}
3125
3126/**
3127 * wait_trustee_state - wait for trustee to enter the specified state
3128 * @gcwq: gcwq the trustee of interest belongs to
3129 * @state: target state to wait for
3130 *
3131 * Wait for the trustee to reach @state. DONE is already matched.
3132 *
3133 * CONTEXT:
3134 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
3135 * multiple times. To be used by cpu_callback.
3136 */
3137static void __cpuinit wait_trustee_state(struct global_cwq *gcwq, int state)
3138{
3139 if (!(gcwq->trustee_state == state ||
3140 gcwq->trustee_state == TRUSTEE_DONE)) {
3141 spin_unlock_irq(&gcwq->lock);
3142 __wait_event(gcwq->trustee_wait,
3143 gcwq->trustee_state == state ||
3144 gcwq->trustee_state == TRUSTEE_DONE);
3145 spin_lock_irq(&gcwq->lock);
3146 }
3147}
3148
3af24433
ON
3149static int __devinit workqueue_cpu_callback(struct notifier_block *nfb,
3150 unsigned long action,
3151 void *hcpu)
3152{
3153 unsigned int cpu = (unsigned long)hcpu;
db7bccf4
TH
3154 struct global_cwq *gcwq = get_gcwq(cpu);
3155 struct task_struct *new_trustee = NULL;
e22bee78 3156 struct worker *uninitialized_var(new_worker);
db7bccf4 3157 unsigned long flags;
3af24433 3158
8bb78442
RW
3159 action &= ~CPU_TASKS_FROZEN;
3160
db7bccf4
TH
3161 switch (action) {
3162 case CPU_DOWN_PREPARE:
3163 new_trustee = kthread_create(trustee_thread, gcwq,
3164 "workqueue_trustee/%d\n", cpu);
3165 if (IS_ERR(new_trustee))
3166 return notifier_from_errno(PTR_ERR(new_trustee));
3167 kthread_bind(new_trustee, cpu);
e22bee78
TH
3168 /* fall through */
3169 case CPU_UP_PREPARE:
3170 BUG_ON(gcwq->first_idle);
3171 new_worker = create_worker(gcwq, false);
3172 if (!new_worker) {
3173 if (new_trustee)
3174 kthread_stop(new_trustee);
3175 return NOTIFY_BAD;
3176 }
db7bccf4 3177 }
3af24433 3178
db7bccf4
TH
3179 /* some are called w/ irq disabled, don't disturb irq status */
3180 spin_lock_irqsave(&gcwq->lock, flags);
3af24433 3181
db7bccf4
TH
3182 switch (action) {
3183 case CPU_DOWN_PREPARE:
3184 /* initialize trustee and tell it to acquire the gcwq */
3185 BUG_ON(gcwq->trustee || gcwq->trustee_state != TRUSTEE_DONE);
3186 gcwq->trustee = new_trustee;
3187 gcwq->trustee_state = TRUSTEE_START;
3188 wake_up_process(gcwq->trustee);
3189 wait_trustee_state(gcwq, TRUSTEE_IN_CHARGE);
e22bee78
TH
3190 /* fall through */
3191 case CPU_UP_PREPARE:
3192 BUG_ON(gcwq->first_idle);
3193 gcwq->first_idle = new_worker;
3194 break;
3195
3196 case CPU_DYING:
3197 /*
3198 * Before this, the trustee and all workers except for
3199 * the ones which are still executing works from
3200 * before the last CPU down must be on the cpu. After
3201 * this, they'll all be diasporas.
3202 */
3203 gcwq->flags |= GCWQ_DISASSOCIATED;
db7bccf4
TH
3204 break;
3205
3206 case CPU_POST_DEAD:
3207 gcwq->trustee_state = TRUSTEE_BUTCHER;
e22bee78
TH
3208 /* fall through */
3209 case CPU_UP_CANCELED:
3210 destroy_worker(gcwq->first_idle);
3211 gcwq->first_idle = NULL;
db7bccf4
TH
3212 break;
3213
3214 case CPU_DOWN_FAILED:
3215 case CPU_ONLINE:
e22bee78 3216 gcwq->flags &= ~GCWQ_DISASSOCIATED;
db7bccf4
TH
3217 if (gcwq->trustee_state != TRUSTEE_DONE) {
3218 gcwq->trustee_state = TRUSTEE_RELEASE;
3219 wake_up_process(gcwq->trustee);
3220 wait_trustee_state(gcwq, TRUSTEE_DONE);
3af24433 3221 }
db7bccf4 3222
e22bee78
TH
3223 /*
3224 * Trustee is done and there might be no worker left.
3225 * Put the first_idle in and request a real manager to
3226 * take a look.
3227 */
3228 spin_unlock_irq(&gcwq->lock);
3229 kthread_bind(gcwq->first_idle->task, cpu);
3230 spin_lock_irq(&gcwq->lock);
3231 gcwq->flags |= GCWQ_MANAGE_WORKERS;
3232 start_worker(gcwq->first_idle);
3233 gcwq->first_idle = NULL;
db7bccf4 3234 break;
1da177e4
LT
3235 }
3236
db7bccf4
TH
3237 spin_unlock_irqrestore(&gcwq->lock, flags);
3238
1537663f 3239 return notifier_from_errno(0);
1da177e4 3240}
1da177e4 3241
2d3854a3 3242#ifdef CONFIG_SMP
8ccad40d 3243
2d3854a3 3244struct work_for_cpu {
6b44003e 3245 struct completion completion;
2d3854a3
RR
3246 long (*fn)(void *);
3247 void *arg;
3248 long ret;
3249};
3250
6b44003e 3251static int do_work_for_cpu(void *_wfc)
2d3854a3 3252{
6b44003e 3253 struct work_for_cpu *wfc = _wfc;
2d3854a3 3254 wfc->ret = wfc->fn(wfc->arg);
6b44003e
AM
3255 complete(&wfc->completion);
3256 return 0;
2d3854a3
RR
3257}
3258
3259/**
3260 * work_on_cpu - run a function in user context on a particular cpu
3261 * @cpu: the cpu to run on
3262 * @fn: the function to run
3263 * @arg: the function arg
3264 *
31ad9081
RR
3265 * This will return the value @fn returns.
3266 * It is up to the caller to ensure that the cpu doesn't go offline.
6b44003e 3267 * The caller must not hold any locks which would prevent @fn from completing.
2d3854a3
RR
3268 */
3269long work_on_cpu(unsigned int cpu, long (*fn)(void *), void *arg)
3270{
6b44003e
AM
3271 struct task_struct *sub_thread;
3272 struct work_for_cpu wfc = {
3273 .completion = COMPLETION_INITIALIZER_ONSTACK(wfc.completion),
3274 .fn = fn,
3275 .arg = arg,
3276 };
3277
3278 sub_thread = kthread_create(do_work_for_cpu, &wfc, "work_for_cpu");
3279 if (IS_ERR(sub_thread))
3280 return PTR_ERR(sub_thread);
3281 kthread_bind(sub_thread, cpu);
3282 wake_up_process(sub_thread);
3283 wait_for_completion(&wfc.completion);
2d3854a3
RR
3284 return wfc.ret;
3285}
3286EXPORT_SYMBOL_GPL(work_on_cpu);
3287#endif /* CONFIG_SMP */
3288
a0a1a5fd
TH
3289#ifdef CONFIG_FREEZER
3290
3291/**
3292 * freeze_workqueues_begin - begin freezing workqueues
3293 *
3294 * Start freezing workqueues. After this function returns, all
3295 * freezeable workqueues will queue new works to their frozen_works
7e11629d 3296 * list instead of gcwq->worklist.
a0a1a5fd
TH
3297 *
3298 * CONTEXT:
8b03ae3c 3299 * Grabs and releases workqueue_lock and gcwq->lock's.
a0a1a5fd
TH
3300 */
3301void freeze_workqueues_begin(void)
3302{
3303 struct workqueue_struct *wq;
3304 unsigned int cpu;
3305
3306 spin_lock(&workqueue_lock);
3307
3308 BUG_ON(workqueue_freezing);
3309 workqueue_freezing = true;
3310
3311 for_each_possible_cpu(cpu) {
8b03ae3c
TH
3312 struct global_cwq *gcwq = get_gcwq(cpu);
3313
3314 spin_lock_irq(&gcwq->lock);
3315
db7bccf4
TH
3316 BUG_ON(gcwq->flags & GCWQ_FREEZING);
3317 gcwq->flags |= GCWQ_FREEZING;
3318
a0a1a5fd
TH
3319 list_for_each_entry(wq, &workqueues, list) {
3320 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3321
a0a1a5fd
TH
3322 if (wq->flags & WQ_FREEZEABLE)
3323 cwq->max_active = 0;
a0a1a5fd 3324 }
8b03ae3c
TH
3325
3326 spin_unlock_irq(&gcwq->lock);
a0a1a5fd
TH
3327 }
3328
3329 spin_unlock(&workqueue_lock);
3330}
3331
3332/**
3333 * freeze_workqueues_busy - are freezeable workqueues still busy?
3334 *
3335 * Check whether freezing is complete. This function must be called
3336 * between freeze_workqueues_begin() and thaw_workqueues().
3337 *
3338 * CONTEXT:
3339 * Grabs and releases workqueue_lock.
3340 *
3341 * RETURNS:
3342 * %true if some freezeable workqueues are still busy. %false if
3343 * freezing is complete.
3344 */
3345bool freeze_workqueues_busy(void)
3346{
3347 struct workqueue_struct *wq;
3348 unsigned int cpu;
3349 bool busy = false;
3350
3351 spin_lock(&workqueue_lock);
3352
3353 BUG_ON(!workqueue_freezing);
3354
3355 for_each_possible_cpu(cpu) {
3356 /*
3357 * nr_active is monotonically decreasing. It's safe
3358 * to peek without lock.
3359 */
3360 list_for_each_entry(wq, &workqueues, list) {
3361 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3362
3363 if (!(wq->flags & WQ_FREEZEABLE))
3364 continue;
3365
3366 BUG_ON(cwq->nr_active < 0);
3367 if (cwq->nr_active) {
3368 busy = true;
3369 goto out_unlock;
3370 }
3371 }
3372 }
3373out_unlock:
3374 spin_unlock(&workqueue_lock);
3375 return busy;
3376}
3377
3378/**
3379 * thaw_workqueues - thaw workqueues
3380 *
3381 * Thaw workqueues. Normal queueing is restored and all collected
7e11629d 3382 * frozen works are transferred to their respective gcwq worklists.
a0a1a5fd
TH
3383 *
3384 * CONTEXT:
8b03ae3c 3385 * Grabs and releases workqueue_lock and gcwq->lock's.
a0a1a5fd
TH
3386 */
3387void thaw_workqueues(void)
3388{
3389 struct workqueue_struct *wq;
3390 unsigned int cpu;
3391
3392 spin_lock(&workqueue_lock);
3393
3394 if (!workqueue_freezing)
3395 goto out_unlock;
3396
3397 for_each_possible_cpu(cpu) {
8b03ae3c
TH
3398 struct global_cwq *gcwq = get_gcwq(cpu);
3399
3400 spin_lock_irq(&gcwq->lock);
3401
db7bccf4
TH
3402 BUG_ON(!(gcwq->flags & GCWQ_FREEZING));
3403 gcwq->flags &= ~GCWQ_FREEZING;
3404
a0a1a5fd
TH
3405 list_for_each_entry(wq, &workqueues, list) {
3406 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3407
3408 if (!(wq->flags & WQ_FREEZEABLE))
3409 continue;
3410
a0a1a5fd
TH
3411 /* restore max_active and repopulate worklist */
3412 cwq->max_active = wq->saved_max_active;
3413
3414 while (!list_empty(&cwq->delayed_works) &&
3415 cwq->nr_active < cwq->max_active)
3416 cwq_activate_first_delayed(cwq);
3417
502ca9d8
TH
3418 /* perform delayed unbind from single cpu if empty */
3419 if (wq->single_cpu == gcwq->cpu &&
3420 !cwq->nr_active && list_empty(&cwq->delayed_works))
3421 cwq_unbind_single_cpu(cwq);
a0a1a5fd 3422 }
8b03ae3c 3423
e22bee78
TH
3424 wake_up_worker(gcwq);
3425
8b03ae3c 3426 spin_unlock_irq(&gcwq->lock);
a0a1a5fd
TH
3427 }
3428
3429 workqueue_freezing = false;
3430out_unlock:
3431 spin_unlock(&workqueue_lock);
3432}
3433#endif /* CONFIG_FREEZER */
3434
c12920d1 3435void __init init_workqueues(void)
1da177e4 3436{
c34056a3 3437 unsigned int cpu;
c8e55f36 3438 int i;
c34056a3 3439
7a22ad75
TH
3440 /*
3441 * The pointer part of work->data is either pointing to the
3442 * cwq or contains the cpu number the work ran last on. Make
3443 * sure cpu number won't overflow into kernel pointer area so
3444 * that they can be distinguished.
3445 */
3446 BUILD_BUG_ON(NR_CPUS << WORK_STRUCT_FLAG_BITS >= PAGE_OFFSET);
3447
db7bccf4 3448 hotcpu_notifier(workqueue_cpu_callback, CPU_PRI_WORKQUEUE);
8b03ae3c
TH
3449
3450 /* initialize gcwqs */
3451 for_each_possible_cpu(cpu) {
3452 struct global_cwq *gcwq = get_gcwq(cpu);
3453
3454 spin_lock_init(&gcwq->lock);
7e11629d 3455 INIT_LIST_HEAD(&gcwq->worklist);
8b03ae3c
TH
3456 gcwq->cpu = cpu;
3457
c8e55f36
TH
3458 INIT_LIST_HEAD(&gcwq->idle_list);
3459 for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)
3460 INIT_HLIST_HEAD(&gcwq->busy_hash[i]);
3461
e22bee78
TH
3462 init_timer_deferrable(&gcwq->idle_timer);
3463 gcwq->idle_timer.function = idle_worker_timeout;
3464 gcwq->idle_timer.data = (unsigned long)gcwq;
3465
3466 setup_timer(&gcwq->mayday_timer, gcwq_mayday_timeout,
3467 (unsigned long)gcwq);
3468
8b03ae3c 3469 ida_init(&gcwq->worker_ida);
db7bccf4
TH
3470
3471 gcwq->trustee_state = TRUSTEE_DONE;
3472 init_waitqueue_head(&gcwq->trustee_wait);
8b03ae3c
TH
3473 }
3474
e22bee78
TH
3475 /* create the initial worker */
3476 for_each_online_cpu(cpu) {
3477 struct global_cwq *gcwq = get_gcwq(cpu);
3478 struct worker *worker;
3479
3480 worker = create_worker(gcwq, true);
3481 BUG_ON(!worker);
3482 spin_lock_irq(&gcwq->lock);
3483 start_worker(worker);
3484 spin_unlock_irq(&gcwq->lock);
3485 }
3486
d320c038
TH
3487 system_wq = alloc_workqueue("events", 0, 0);
3488 system_long_wq = alloc_workqueue("events_long", 0, 0);
3489 system_nrt_wq = alloc_workqueue("events_nrt", WQ_NON_REENTRANT, 0);
3490 BUG_ON(!system_wq || !system_long_wq || !system_nrt_wq);
1da177e4 3491}