2 * kernel/workqueue.c - generic async execution with shared worker pool
4 * Copyright (C) 2002 Ingo Molnar
6 * Derived from the taskqueue/keventd code by:
7 * David Woodhouse <dwmw2@infradead.org>
9 * Kai Petzke <wpp@marie.physik.tu-berlin.de>
10 * Theodore Ts'o <tytso@mit.edu>
12 * Made to use alloc_percpu by Christoph Lameter.
14 * Copyright (C) 2010 SUSE Linux Products GmbH
15 * Copyright (C) 2010 Tejun Heo <tj@kernel.org>
17 * This is the generic async execution mechanism. Work items as are
18 * executed in process context. The worker pool is shared and
19 * automatically managed. There is one worker pool for each CPU and
20 * one extra for works which are better served by workers which are
21 * not bound to any specific CPU.
23 * Please read Documentation/workqueue.txt for details.
26 #include <linux/export.h>
27 #include <linux/kernel.h>
28 #include <linux/sched.h>
29 #include <linux/init.h>
30 #include <linux/signal.h>
31 #include <linux/completion.h>
32 #include <linux/workqueue.h>
33 #include <linux/slab.h>
34 #include <linux/cpu.h>
35 #include <linux/notifier.h>
36 #include <linux/kthread.h>
37 #include <linux/hardirq.h>
38 #include <linux/mempolicy.h>
39 #include <linux/freezer.h>
40 #include <linux/kallsyms.h>
41 #include <linux/debug_locks.h>
42 #include <linux/lockdep.h>
43 #include <linux/idr.h>
45 #include "workqueue_sched.h"
48 /* global_cwq flags */
49 GCWQ_MANAGE_WORKERS = 1 << 0, /* need to manage workers */
50 GCWQ_MANAGING_WORKERS = 1 << 1, /* managing workers */
51 GCWQ_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
52 GCWQ_FREEZING = 1 << 3, /* freeze in progress */
53 GCWQ_HIGHPRI_PENDING = 1 << 4, /* highpri works on queue */
56 WORKER_STARTED = 1 << 0, /* started */
57 WORKER_DIE = 1 << 1, /* die die die */
58 WORKER_IDLE = 1 << 2, /* is idle */
59 WORKER_PREP = 1 << 3, /* preparing to run works */
60 WORKER_ROGUE = 1 << 4, /* not bound to any cpu */
61 WORKER_REBIND = 1 << 5, /* mom is home, come back */
62 WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
63 WORKER_UNBOUND = 1 << 7, /* worker is unbound */
65 WORKER_NOT_RUNNING = WORKER_PREP | WORKER_ROGUE | WORKER_REBIND |
66 WORKER_CPU_INTENSIVE | WORKER_UNBOUND,
68 /* gcwq->trustee_state */
69 TRUSTEE_START = 0, /* start */
70 TRUSTEE_IN_CHARGE = 1, /* trustee in charge of gcwq */
71 TRUSTEE_BUTCHER = 2, /* butcher workers */
72 TRUSTEE_RELEASE = 3, /* release workers */
73 TRUSTEE_DONE = 4, /* trustee is done */
75 BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
76 BUSY_WORKER_HASH_SIZE = 1 << BUSY_WORKER_HASH_ORDER,
77 BUSY_WORKER_HASH_MASK = BUSY_WORKER_HASH_SIZE - 1,
79 MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
80 IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
82 MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
83 /* call for help after 10ms
85 MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
86 CREATE_COOLDOWN = HZ, /* time to breath after fail */
87 TRUSTEE_COOLDOWN = HZ / 10, /* for trustee draining */
90 * Rescue workers are used only on emergencies and shared by
93 RESCUER_NICE_LEVEL = -20,
97 * Structure fields follow one of the following exclusion rules.
99 * I: Modifiable by initialization/destruction paths and read-only for
102 * P: Preemption protected. Disabling preemption is enough and should
103 * only be modified and accessed from the local cpu.
105 * L: gcwq->lock protected. Access with gcwq->lock held.
107 * X: During normal operation, modification requires gcwq->lock and
108 * should be done only from local cpu. Either disabling preemption
109 * on local cpu or grabbing gcwq->lock is enough for read access.
110 * If GCWQ_DISASSOCIATED is set, it's identical to L.
112 * F: wq->flush_mutex protected.
114 * W: workqueue_lock protected.
120 * The poor guys doing the actual heavy lifting. All on-duty workers
121 * are either serving the manager role, on idle list or on busy hash.
124 /* on idle list while idle, on busy hash table while busy */
126 struct list_head entry; /* L: while idle */
127 struct hlist_node hentry; /* L: while busy */
130 struct work_struct *current_work; /* L: work being processed */
131 struct cpu_workqueue_struct *current_cwq; /* L: current_work's cwq */
132 struct list_head scheduled; /* L: scheduled works */
133 struct task_struct *task; /* I: worker task */
134 struct global_cwq *gcwq; /* I: the associated gcwq */
135 /* 64 bytes boundary on 64bit, 32 on 32bit */
136 unsigned long last_active; /* L: last active timestamp */
137 unsigned int flags; /* X: flags */
138 int id; /* I: worker id */
139 struct work_struct rebind_work; /* L: rebind worker to cpu */
143 * Global per-cpu workqueue. There's one and only one for each cpu
144 * and all works are queued and processed here regardless of their
148 spinlock_t lock; /* the gcwq lock */
149 struct list_head worklist; /* L: list of pending works */
150 unsigned int cpu; /* I: the associated cpu */
151 unsigned int flags; /* L: GCWQ_* flags */
153 int nr_workers; /* L: total number of workers */
154 int nr_idle; /* L: currently idle ones */
156 /* workers are chained either in the idle_list or busy_hash */
157 struct list_head idle_list; /* X: list of idle workers */
158 struct hlist_head busy_hash[BUSY_WORKER_HASH_SIZE];
159 /* L: hash of busy workers */
161 struct timer_list idle_timer; /* L: worker idle timeout */
162 struct timer_list mayday_timer; /* L: SOS timer for dworkers */
164 struct ida worker_ida; /* L: for worker IDs */
166 struct task_struct *trustee; /* L: for gcwq shutdown */
167 unsigned int trustee_state; /* L: trustee state */
168 wait_queue_head_t trustee_wait; /* trustee wait */
169 struct worker *first_idle; /* L: first idle worker */
170 } ____cacheline_aligned_in_smp;
173 * The per-CPU workqueue. The lower WORK_STRUCT_FLAG_BITS of
174 * work_struct->data are used for flags and thus cwqs need to be
175 * aligned at two's power of the number of flag bits.
177 struct cpu_workqueue_struct {
178 struct global_cwq *gcwq; /* I: the associated gcwq */
179 struct workqueue_struct *wq; /* I: the owning workqueue */
180 int work_color; /* L: current color */
181 int flush_color; /* L: flushing color */
182 int nr_in_flight[WORK_NR_COLORS];
183 /* L: nr of in_flight works */
184 int nr_active; /* L: nr of active works */
185 int max_active; /* L: max active works */
186 struct list_head delayed_works; /* L: delayed works */
190 * Structure used to wait for workqueue flush.
193 struct list_head list; /* F: list of flushers */
194 int flush_color; /* F: flush color waiting for */
195 struct completion done; /* flush completion */
199 * All cpumasks are assumed to be always set on UP and thus can't be
200 * used to determine whether there's something to be done.
203 typedef cpumask_var_t mayday_mask_t;
204 #define mayday_test_and_set_cpu(cpu, mask) \
205 cpumask_test_and_set_cpu((cpu), (mask))
206 #define mayday_clear_cpu(cpu, mask) cpumask_clear_cpu((cpu), (mask))
207 #define for_each_mayday_cpu(cpu, mask) for_each_cpu((cpu), (mask))
208 #define alloc_mayday_mask(maskp, gfp) zalloc_cpumask_var((maskp), (gfp))
209 #define free_mayday_mask(mask) free_cpumask_var((mask))
211 typedef unsigned long mayday_mask_t;
212 #define mayday_test_and_set_cpu(cpu, mask) test_and_set_bit(0, &(mask))
213 #define mayday_clear_cpu(cpu, mask) clear_bit(0, &(mask))
214 #define for_each_mayday_cpu(cpu, mask) if ((cpu) = 0, (mask))
215 #define alloc_mayday_mask(maskp, gfp) true
216 #define free_mayday_mask(mask) do { } while (0)
220 * The externally visible workqueue abstraction is an array of
221 * per-CPU workqueues:
223 struct workqueue_struct {
224 unsigned int flags; /* W: WQ_* flags */
226 struct cpu_workqueue_struct __percpu *pcpu;
227 struct cpu_workqueue_struct *single;
229 } cpu_wq; /* I: cwq's */
230 struct list_head list; /* W: list of all workqueues */
232 struct mutex flush_mutex; /* protects wq flushing */
233 int work_color; /* F: current work color */
234 int flush_color; /* F: current flush color */
235 atomic_t nr_cwqs_to_flush; /* flush in progress */
236 struct wq_flusher *first_flusher; /* F: first flusher */
237 struct list_head flusher_queue; /* F: flush waiters */
238 struct list_head flusher_overflow; /* F: flush overflow list */
240 mayday_mask_t mayday_mask; /* cpus requesting rescue */
241 struct worker *rescuer; /* I: rescue worker */
243 int nr_drainers; /* W: drain in progress */
244 int saved_max_active; /* W: saved cwq max_active */
245 #ifdef CONFIG_LOCKDEP
246 struct lockdep_map lockdep_map;
248 char name[]; /* I: workqueue name */
251 struct workqueue_struct *system_wq __read_mostly;
252 struct workqueue_struct *system_long_wq __read_mostly;
253 struct workqueue_struct *system_nrt_wq __read_mostly;
254 struct workqueue_struct *system_unbound_wq __read_mostly;
255 struct workqueue_struct *system_freezable_wq __read_mostly;
256 EXPORT_SYMBOL_GPL(system_wq);
257 EXPORT_SYMBOL_GPL(system_long_wq);
258 EXPORT_SYMBOL_GPL(system_nrt_wq);
259 EXPORT_SYMBOL_GPL(system_unbound_wq);
260 EXPORT_SYMBOL_GPL(system_freezable_wq);
262 #define CREATE_TRACE_POINTS
263 #include <trace/events/workqueue.h>
265 #define for_each_busy_worker(worker, i, pos, gcwq) \
266 for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++) \
267 hlist_for_each_entry(worker, pos, &gcwq->busy_hash[i], hentry)
269 static inline int __next_gcwq_cpu(int cpu, const struct cpumask *mask,
272 if (cpu < nr_cpu_ids) {
274 cpu = cpumask_next(cpu, mask);
275 if (cpu < nr_cpu_ids)
279 return WORK_CPU_UNBOUND;
281 return WORK_CPU_NONE;
284 static inline int __next_wq_cpu(int cpu, const struct cpumask *mask,
285 struct workqueue_struct *wq)
287 return __next_gcwq_cpu(cpu, mask, !(wq->flags & WQ_UNBOUND) ? 1 : 2);
293 * An extra gcwq is defined for an invalid cpu number
294 * (WORK_CPU_UNBOUND) to host workqueues which are not bound to any
295 * specific CPU. The following iterators are similar to
296 * for_each_*_cpu() iterators but also considers the unbound gcwq.
298 * for_each_gcwq_cpu() : possible CPUs + WORK_CPU_UNBOUND
299 * for_each_online_gcwq_cpu() : online CPUs + WORK_CPU_UNBOUND
300 * for_each_cwq_cpu() : possible CPUs for bound workqueues,
301 * WORK_CPU_UNBOUND for unbound workqueues
303 #define for_each_gcwq_cpu(cpu) \
304 for ((cpu) = __next_gcwq_cpu(-1, cpu_possible_mask, 3); \
305 (cpu) < WORK_CPU_NONE; \
306 (cpu) = __next_gcwq_cpu((cpu), cpu_possible_mask, 3))
308 #define for_each_online_gcwq_cpu(cpu) \
309 for ((cpu) = __next_gcwq_cpu(-1, cpu_online_mask, 3); \
310 (cpu) < WORK_CPU_NONE; \
311 (cpu) = __next_gcwq_cpu((cpu), cpu_online_mask, 3))
313 #define for_each_cwq_cpu(cpu, wq) \
314 for ((cpu) = __next_wq_cpu(-1, cpu_possible_mask, (wq)); \
315 (cpu) < WORK_CPU_NONE; \
316 (cpu) = __next_wq_cpu((cpu), cpu_possible_mask, (wq)))
318 #ifdef CONFIG_DEBUG_OBJECTS_WORK
320 static struct debug_obj_descr work_debug_descr;
322 static void *work_debug_hint(void *addr)
324 return ((struct work_struct *) addr)->func;
328 * fixup_init is called when:
329 * - an active object is initialized
331 static int work_fixup_init(void *addr, enum debug_obj_state state)
333 struct work_struct *work = addr;
336 case ODEBUG_STATE_ACTIVE:
337 cancel_work_sync(work);
338 debug_object_init(work, &work_debug_descr);
346 * fixup_activate is called when:
347 * - an active object is activated
348 * - an unknown object is activated (might be a statically initialized object)
350 static int work_fixup_activate(void *addr, enum debug_obj_state state)
352 struct work_struct *work = addr;
356 case ODEBUG_STATE_NOTAVAILABLE:
358 * This is not really a fixup. The work struct was
359 * statically initialized. We just make sure that it
360 * is tracked in the object tracker.
362 if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
363 debug_object_init(work, &work_debug_descr);
364 debug_object_activate(work, &work_debug_descr);
370 case ODEBUG_STATE_ACTIVE:
379 * fixup_free is called when:
380 * - an active object is freed
382 static int work_fixup_free(void *addr, enum debug_obj_state state)
384 struct work_struct *work = addr;
387 case ODEBUG_STATE_ACTIVE:
388 cancel_work_sync(work);
389 debug_object_free(work, &work_debug_descr);
396 static struct debug_obj_descr work_debug_descr = {
397 .name = "work_struct",
398 .debug_hint = work_debug_hint,
399 .fixup_init = work_fixup_init,
400 .fixup_activate = work_fixup_activate,
401 .fixup_free = work_fixup_free,
404 static inline void debug_work_activate(struct work_struct *work)
406 debug_object_activate(work, &work_debug_descr);
409 static inline void debug_work_deactivate(struct work_struct *work)
411 debug_object_deactivate(work, &work_debug_descr);
414 void __init_work(struct work_struct *work, int onstack)
417 debug_object_init_on_stack(work, &work_debug_descr);
419 debug_object_init(work, &work_debug_descr);
421 EXPORT_SYMBOL_GPL(__init_work);
423 void destroy_work_on_stack(struct work_struct *work)
425 debug_object_free(work, &work_debug_descr);
427 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
430 static inline void debug_work_activate(struct work_struct *work) { }
431 static inline void debug_work_deactivate(struct work_struct *work) { }
434 /* Serializes the accesses to the list of workqueues. */
435 static DEFINE_SPINLOCK(workqueue_lock);
436 static LIST_HEAD(workqueues);
437 static bool workqueue_freezing; /* W: have wqs started freezing? */
440 * The almighty global cpu workqueues. nr_running is the only field
441 * which is expected to be used frequently by other cpus via
442 * try_to_wake_up(). Put it in a separate cacheline.
444 static DEFINE_PER_CPU(struct global_cwq, global_cwq);
445 static DEFINE_PER_CPU_SHARED_ALIGNED(atomic_t, gcwq_nr_running);
448 * Global cpu workqueue and nr_running counter for unbound gcwq. The
449 * gcwq is always online, has GCWQ_DISASSOCIATED set, and all its
450 * workers have WORKER_UNBOUND set.
452 static struct global_cwq unbound_global_cwq;
453 static atomic_t unbound_gcwq_nr_running = ATOMIC_INIT(0); /* always 0 */
455 static int worker_thread(void *__worker);
457 static struct global_cwq *get_gcwq(unsigned int cpu)
459 if (cpu != WORK_CPU_UNBOUND)
460 return &per_cpu(global_cwq, cpu);
462 return &unbound_global_cwq;
465 static atomic_t *get_gcwq_nr_running(unsigned int cpu)
467 if (cpu != WORK_CPU_UNBOUND)
468 return &per_cpu(gcwq_nr_running, cpu);
470 return &unbound_gcwq_nr_running;
473 static struct cpu_workqueue_struct *get_cwq(unsigned int cpu,
474 struct workqueue_struct *wq)
476 if (!(wq->flags & WQ_UNBOUND)) {
477 if (likely(cpu < nr_cpu_ids))
478 return per_cpu_ptr(wq->cpu_wq.pcpu, cpu);
479 } else if (likely(cpu == WORK_CPU_UNBOUND))
480 return wq->cpu_wq.single;
484 static unsigned int work_color_to_flags(int color)
486 return color << WORK_STRUCT_COLOR_SHIFT;
489 static int get_work_color(struct work_struct *work)
491 return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
492 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
495 static int work_next_color(int color)
497 return (color + 1) % WORK_NR_COLORS;
501 * A work's data points to the cwq with WORK_STRUCT_CWQ set while the
502 * work is on queue. Once execution starts, WORK_STRUCT_CWQ is
503 * cleared and the work data contains the cpu number it was last on.
505 * set_work_{cwq|cpu}() and clear_work_data() can be used to set the
506 * cwq, cpu or clear work->data. These functions should only be
507 * called while the work is owned - ie. while the PENDING bit is set.
509 * get_work_[g]cwq() can be used to obtain the gcwq or cwq
510 * corresponding to a work. gcwq is available once the work has been
511 * queued anywhere after initialization. cwq is available only from
512 * queueing until execution starts.
514 static inline void set_work_data(struct work_struct *work, unsigned long data,
517 BUG_ON(!work_pending(work));
518 atomic_long_set(&work->data, data | flags | work_static(work));
521 static void set_work_cwq(struct work_struct *work,
522 struct cpu_workqueue_struct *cwq,
523 unsigned long extra_flags)
525 set_work_data(work, (unsigned long)cwq,
526 WORK_STRUCT_PENDING | WORK_STRUCT_CWQ | extra_flags);
529 static void set_work_cpu(struct work_struct *work, unsigned int cpu)
531 set_work_data(work, cpu << WORK_STRUCT_FLAG_BITS, WORK_STRUCT_PENDING);
534 static void clear_work_data(struct work_struct *work)
536 set_work_data(work, WORK_STRUCT_NO_CPU, 0);
539 static struct cpu_workqueue_struct *get_work_cwq(struct work_struct *work)
541 unsigned long data = atomic_long_read(&work->data);
543 if (data & WORK_STRUCT_CWQ)
544 return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
549 static struct global_cwq *get_work_gcwq(struct work_struct *work)
551 unsigned long data = atomic_long_read(&work->data);
554 if (data & WORK_STRUCT_CWQ)
555 return ((struct cpu_workqueue_struct *)
556 (data & WORK_STRUCT_WQ_DATA_MASK))->gcwq;
558 cpu = data >> WORK_STRUCT_FLAG_BITS;
559 if (cpu == WORK_CPU_NONE)
562 BUG_ON(cpu >= nr_cpu_ids && cpu != WORK_CPU_UNBOUND);
563 return get_gcwq(cpu);
567 * Policy functions. These define the policies on how the global
568 * worker pool is managed. Unless noted otherwise, these functions
569 * assume that they're being called with gcwq->lock held.
572 static bool __need_more_worker(struct global_cwq *gcwq)
574 return !atomic_read(get_gcwq_nr_running(gcwq->cpu)) ||
575 gcwq->flags & GCWQ_HIGHPRI_PENDING;
579 * Need to wake up a worker? Called from anything but currently
582 static bool need_more_worker(struct global_cwq *gcwq)
584 return !list_empty(&gcwq->worklist) && __need_more_worker(gcwq);
587 /* Can I start working? Called from busy but !running workers. */
588 static bool may_start_working(struct global_cwq *gcwq)
590 return gcwq->nr_idle;
593 /* Do I need to keep working? Called from currently running workers. */
594 static bool keep_working(struct global_cwq *gcwq)
596 atomic_t *nr_running = get_gcwq_nr_running(gcwq->cpu);
598 return !list_empty(&gcwq->worklist) &&
599 (atomic_read(nr_running) <= 1 ||
600 gcwq->flags & GCWQ_HIGHPRI_PENDING);
603 /* Do we need a new worker? Called from manager. */
604 static bool need_to_create_worker(struct global_cwq *gcwq)
606 return need_more_worker(gcwq) && !may_start_working(gcwq);
609 /* Do I need to be the manager? */
610 static bool need_to_manage_workers(struct global_cwq *gcwq)
612 return need_to_create_worker(gcwq) || gcwq->flags & GCWQ_MANAGE_WORKERS;
615 /* Do we have too many workers and should some go away? */
616 static bool too_many_workers(struct global_cwq *gcwq)
618 bool managing = gcwq->flags & GCWQ_MANAGING_WORKERS;
619 int nr_idle = gcwq->nr_idle + managing; /* manager is considered idle */
620 int nr_busy = gcwq->nr_workers - nr_idle;
622 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
629 /* Return the first worker. Safe with preemption disabled */
630 static struct worker *first_worker(struct global_cwq *gcwq)
632 if (unlikely(list_empty(&gcwq->idle_list)))
635 return list_first_entry(&gcwq->idle_list, struct worker, entry);
639 * wake_up_worker - wake up an idle worker
640 * @gcwq: gcwq to wake worker for
642 * Wake up the first idle worker of @gcwq.
645 * spin_lock_irq(gcwq->lock).
647 static void wake_up_worker(struct global_cwq *gcwq)
649 struct worker *worker = first_worker(gcwq);
652 wake_up_process(worker->task);
656 * wq_worker_waking_up - a worker is waking up
657 * @task: task waking up
658 * @cpu: CPU @task is waking up to
660 * This function is called during try_to_wake_up() when a worker is
664 * spin_lock_irq(rq->lock)
666 void wq_worker_waking_up(struct task_struct *task, unsigned int cpu)
668 struct worker *worker = kthread_data(task);
670 if (!(worker->flags & WORKER_NOT_RUNNING))
671 atomic_inc(get_gcwq_nr_running(cpu));
675 * wq_worker_sleeping - a worker is going to sleep
676 * @task: task going to sleep
677 * @cpu: CPU in question, must be the current CPU number
679 * This function is called during schedule() when a busy worker is
680 * going to sleep. Worker on the same cpu can be woken up by
681 * returning pointer to its task.
684 * spin_lock_irq(rq->lock)
687 * Worker task on @cpu to wake up, %NULL if none.
689 struct task_struct *wq_worker_sleeping(struct task_struct *task,
692 struct worker *worker = kthread_data(task), *to_wakeup = NULL;
693 struct global_cwq *gcwq = get_gcwq(cpu);
694 atomic_t *nr_running = get_gcwq_nr_running(cpu);
696 if (worker->flags & WORKER_NOT_RUNNING)
699 /* this can only happen on the local cpu */
700 BUG_ON(cpu != raw_smp_processor_id());
703 * The counterpart of the following dec_and_test, implied mb,
704 * worklist not empty test sequence is in insert_work().
705 * Please read comment there.
707 * NOT_RUNNING is clear. This means that trustee is not in
708 * charge and we're running on the local cpu w/ rq lock held
709 * and preemption disabled, which in turn means that none else
710 * could be manipulating idle_list, so dereferencing idle_list
711 * without gcwq lock is safe.
713 if (atomic_dec_and_test(nr_running) && !list_empty(&gcwq->worklist))
714 to_wakeup = first_worker(gcwq);
715 return to_wakeup ? to_wakeup->task : NULL;
719 * worker_set_flags - set worker flags and adjust nr_running accordingly
721 * @flags: flags to set
722 * @wakeup: wakeup an idle worker if necessary
724 * Set @flags in @worker->flags and adjust nr_running accordingly. If
725 * nr_running becomes zero and @wakeup is %true, an idle worker is
729 * spin_lock_irq(gcwq->lock)
731 static inline void worker_set_flags(struct worker *worker, unsigned int flags,
734 struct global_cwq *gcwq = worker->gcwq;
736 WARN_ON_ONCE(worker->task != current);
739 * If transitioning into NOT_RUNNING, adjust nr_running and
740 * wake up an idle worker as necessary if requested by
743 if ((flags & WORKER_NOT_RUNNING) &&
744 !(worker->flags & WORKER_NOT_RUNNING)) {
745 atomic_t *nr_running = get_gcwq_nr_running(gcwq->cpu);
748 if (atomic_dec_and_test(nr_running) &&
749 !list_empty(&gcwq->worklist))
750 wake_up_worker(gcwq);
752 atomic_dec(nr_running);
755 worker->flags |= flags;
759 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
761 * @flags: flags to clear
763 * Clear @flags in @worker->flags and adjust nr_running accordingly.
766 * spin_lock_irq(gcwq->lock)
768 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
770 struct global_cwq *gcwq = worker->gcwq;
771 unsigned int oflags = worker->flags;
773 WARN_ON_ONCE(worker->task != current);
775 worker->flags &= ~flags;
778 * If transitioning out of NOT_RUNNING, increment nr_running. Note
779 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
780 * of multiple flags, not a single flag.
782 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
783 if (!(worker->flags & WORKER_NOT_RUNNING))
784 atomic_inc(get_gcwq_nr_running(gcwq->cpu));
788 * busy_worker_head - return the busy hash head for a work
789 * @gcwq: gcwq of interest
790 * @work: work to be hashed
792 * Return hash head of @gcwq for @work.
795 * spin_lock_irq(gcwq->lock).
798 * Pointer to the hash head.
800 static struct hlist_head *busy_worker_head(struct global_cwq *gcwq,
801 struct work_struct *work)
803 const int base_shift = ilog2(sizeof(struct work_struct));
804 unsigned long v = (unsigned long)work;
806 /* simple shift and fold hash, do we need something better? */
808 v += v >> BUSY_WORKER_HASH_ORDER;
809 v &= BUSY_WORKER_HASH_MASK;
811 return &gcwq->busy_hash[v];
815 * __find_worker_executing_work - find worker which is executing a work
816 * @gcwq: gcwq of interest
817 * @bwh: hash head as returned by busy_worker_head()
818 * @work: work to find worker for
820 * Find a worker which is executing @work on @gcwq. @bwh should be
821 * the hash head obtained by calling busy_worker_head() with the same
825 * spin_lock_irq(gcwq->lock).
828 * Pointer to worker which is executing @work if found, NULL
831 static struct worker *__find_worker_executing_work(struct global_cwq *gcwq,
832 struct hlist_head *bwh,
833 struct work_struct *work)
835 struct worker *worker;
836 struct hlist_node *tmp;
838 hlist_for_each_entry(worker, tmp, bwh, hentry)
839 if (worker->current_work == work)
845 * find_worker_executing_work - find worker which is executing a work
846 * @gcwq: gcwq of interest
847 * @work: work to find worker for
849 * Find a worker which is executing @work on @gcwq. This function is
850 * identical to __find_worker_executing_work() except that this
851 * function calculates @bwh itself.
854 * spin_lock_irq(gcwq->lock).
857 * Pointer to worker which is executing @work if found, NULL
860 static struct worker *find_worker_executing_work(struct global_cwq *gcwq,
861 struct work_struct *work)
863 return __find_worker_executing_work(gcwq, busy_worker_head(gcwq, work),
868 * gcwq_determine_ins_pos - find insertion position
869 * @gcwq: gcwq of interest
870 * @cwq: cwq a work is being queued for
872 * A work for @cwq is about to be queued on @gcwq, determine insertion
873 * position for the work. If @cwq is for HIGHPRI wq, the work is
874 * queued at the head of the queue but in FIFO order with respect to
875 * other HIGHPRI works; otherwise, at the end of the queue. This
876 * function also sets GCWQ_HIGHPRI_PENDING flag to hint @gcwq that
877 * there are HIGHPRI works pending.
880 * spin_lock_irq(gcwq->lock).
883 * Pointer to inserstion position.
885 static inline struct list_head *gcwq_determine_ins_pos(struct global_cwq *gcwq,
886 struct cpu_workqueue_struct *cwq)
888 struct work_struct *twork;
890 if (likely(!(cwq->wq->flags & WQ_HIGHPRI)))
891 return &gcwq->worklist;
893 list_for_each_entry(twork, &gcwq->worklist, entry) {
894 struct cpu_workqueue_struct *tcwq = get_work_cwq(twork);
896 if (!(tcwq->wq->flags & WQ_HIGHPRI))
900 gcwq->flags |= GCWQ_HIGHPRI_PENDING;
901 return &twork->entry;
905 * insert_work - insert a work into gcwq
906 * @cwq: cwq @work belongs to
907 * @work: work to insert
908 * @head: insertion point
909 * @extra_flags: extra WORK_STRUCT_* flags to set
911 * Insert @work which belongs to @cwq into @gcwq after @head.
912 * @extra_flags is or'd to work_struct flags.
915 * spin_lock_irq(gcwq->lock).
917 static void insert_work(struct cpu_workqueue_struct *cwq,
918 struct work_struct *work, struct list_head *head,
919 unsigned int extra_flags)
921 struct global_cwq *gcwq = cwq->gcwq;
923 /* we own @work, set data and link */
924 set_work_cwq(work, cwq, extra_flags);
927 * Ensure that we get the right work->data if we see the
928 * result of list_add() below, see try_to_grab_pending().
932 list_add_tail(&work->entry, head);
935 * Ensure either worker_sched_deactivated() sees the above
936 * list_add_tail() or we see zero nr_running to avoid workers
937 * lying around lazily while there are works to be processed.
941 if (__need_more_worker(gcwq))
942 wake_up_worker(gcwq);
946 * Test whether @work is being queued from another work executing on the
947 * same workqueue. This is rather expensive and should only be used from
950 static bool is_chained_work(struct workqueue_struct *wq)
955 for_each_gcwq_cpu(cpu) {
956 struct global_cwq *gcwq = get_gcwq(cpu);
957 struct worker *worker;
958 struct hlist_node *pos;
961 spin_lock_irqsave(&gcwq->lock, flags);
962 for_each_busy_worker(worker, i, pos, gcwq) {
963 if (worker->task != current)
965 spin_unlock_irqrestore(&gcwq->lock, flags);
967 * I'm @worker, no locking necessary. See if @work
968 * is headed to the same workqueue.
970 return worker->current_cwq->wq == wq;
972 spin_unlock_irqrestore(&gcwq->lock, flags);
977 static void __queue_work(unsigned int cpu, struct workqueue_struct *wq,
978 struct work_struct *work)
980 struct global_cwq *gcwq;
981 struct cpu_workqueue_struct *cwq;
982 struct list_head *worklist;
983 unsigned int work_flags;
986 debug_work_activate(work);
988 /* if dying, only works from the same workqueue are allowed */
989 if (unlikely(wq->flags & WQ_DRAINING) &&
990 WARN_ON_ONCE(!is_chained_work(wq)))
993 /* determine gcwq to use */
994 if (!(wq->flags & WQ_UNBOUND)) {
995 struct global_cwq *last_gcwq;
997 if (unlikely(cpu == WORK_CPU_UNBOUND))
998 cpu = raw_smp_processor_id();
1001 * It's multi cpu. If @wq is non-reentrant and @work
1002 * was previously on a different cpu, it might still
1003 * be running there, in which case the work needs to
1004 * be queued on that cpu to guarantee non-reentrance.
1006 gcwq = get_gcwq(cpu);
1007 if (wq->flags & WQ_NON_REENTRANT &&
1008 (last_gcwq = get_work_gcwq(work)) && last_gcwq != gcwq) {
1009 struct worker *worker;
1011 spin_lock_irqsave(&last_gcwq->lock, flags);
1013 worker = find_worker_executing_work(last_gcwq, work);
1015 if (worker && worker->current_cwq->wq == wq)
1018 /* meh... not running there, queue here */
1019 spin_unlock_irqrestore(&last_gcwq->lock, flags);
1020 spin_lock_irqsave(&gcwq->lock, flags);
1023 spin_lock_irqsave(&gcwq->lock, flags);
1025 gcwq = get_gcwq(WORK_CPU_UNBOUND);
1026 spin_lock_irqsave(&gcwq->lock, flags);
1029 /* gcwq determined, get cwq and queue */
1030 cwq = get_cwq(gcwq->cpu, wq);
1031 trace_workqueue_queue_work(cpu, cwq, work);
1033 BUG_ON(!list_empty(&work->entry));
1035 cwq->nr_in_flight[cwq->work_color]++;
1036 work_flags = work_color_to_flags(cwq->work_color);
1038 if (likely(cwq->nr_active < cwq->max_active)) {
1039 trace_workqueue_activate_work(work);
1041 worklist = gcwq_determine_ins_pos(gcwq, cwq);
1043 work_flags |= WORK_STRUCT_DELAYED;
1044 worklist = &cwq->delayed_works;
1047 insert_work(cwq, work, worklist, work_flags);
1049 spin_unlock_irqrestore(&gcwq->lock, flags);
1053 * queue_work - queue work on a workqueue
1054 * @wq: workqueue to use
1055 * @work: work to queue
1057 * Returns 0 if @work was already on a queue, non-zero otherwise.
1059 * We queue the work to the CPU on which it was submitted, but if the CPU dies
1060 * it can be processed by another CPU.
1062 int queue_work(struct workqueue_struct *wq, struct work_struct *work)
1066 ret = queue_work_on(get_cpu(), wq, work);
1071 EXPORT_SYMBOL_GPL(queue_work);
1074 * queue_work_on - queue work on specific cpu
1075 * @cpu: CPU number to execute work on
1076 * @wq: workqueue to use
1077 * @work: work to queue
1079 * Returns 0 if @work was already on a queue, non-zero otherwise.
1081 * We queue the work to a specific CPU, the caller must ensure it
1085 queue_work_on(int cpu, struct workqueue_struct *wq, struct work_struct *work)
1089 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1090 __queue_work(cpu, wq, work);
1095 EXPORT_SYMBOL_GPL(queue_work_on);
1097 static void delayed_work_timer_fn(unsigned long __data)
1099 struct delayed_work *dwork = (struct delayed_work *)__data;
1100 struct cpu_workqueue_struct *cwq = get_work_cwq(&dwork->work);
1102 __queue_work(smp_processor_id(), cwq->wq, &dwork->work);
1106 * queue_delayed_work - queue work on a workqueue after delay
1107 * @wq: workqueue to use
1108 * @dwork: delayable work to queue
1109 * @delay: number of jiffies to wait before queueing
1111 * Returns 0 if @work was already on a queue, non-zero otherwise.
1113 int queue_delayed_work(struct workqueue_struct *wq,
1114 struct delayed_work *dwork, unsigned long delay)
1117 return queue_work(wq, &dwork->work);
1119 return queue_delayed_work_on(-1, wq, dwork, delay);
1121 EXPORT_SYMBOL_GPL(queue_delayed_work);
1124 * queue_delayed_work_on - queue work on specific CPU after delay
1125 * @cpu: CPU number to execute work on
1126 * @wq: workqueue to use
1127 * @dwork: work to queue
1128 * @delay: number of jiffies to wait before queueing
1130 * Returns 0 if @work was already on a queue, non-zero otherwise.
1132 int queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1133 struct delayed_work *dwork, unsigned long delay)
1136 struct timer_list *timer = &dwork->timer;
1137 struct work_struct *work = &dwork->work;
1139 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1142 BUG_ON(timer_pending(timer));
1143 BUG_ON(!list_empty(&work->entry));
1145 timer_stats_timer_set_start_info(&dwork->timer);
1148 * This stores cwq for the moment, for the timer_fn.
1149 * Note that the work's gcwq is preserved to allow
1150 * reentrance detection for delayed works.
1152 if (!(wq->flags & WQ_UNBOUND)) {
1153 struct global_cwq *gcwq = get_work_gcwq(work);
1155 if (gcwq && gcwq->cpu != WORK_CPU_UNBOUND)
1158 lcpu = raw_smp_processor_id();
1160 lcpu = WORK_CPU_UNBOUND;
1162 set_work_cwq(work, get_cwq(lcpu, wq), 0);
1164 timer->expires = jiffies + delay;
1165 timer->data = (unsigned long)dwork;
1166 timer->function = delayed_work_timer_fn;
1168 if (unlikely(cpu >= 0))
1169 add_timer_on(timer, cpu);
1176 EXPORT_SYMBOL_GPL(queue_delayed_work_on);
1179 * worker_enter_idle - enter idle state
1180 * @worker: worker which is entering idle state
1182 * @worker is entering idle state. Update stats and idle timer if
1186 * spin_lock_irq(gcwq->lock).
1188 static void worker_enter_idle(struct worker *worker)
1190 struct global_cwq *gcwq = worker->gcwq;
1192 BUG_ON(worker->flags & WORKER_IDLE);
1193 BUG_ON(!list_empty(&worker->entry) &&
1194 (worker->hentry.next || worker->hentry.pprev));
1196 /* can't use worker_set_flags(), also called from start_worker() */
1197 worker->flags |= WORKER_IDLE;
1199 worker->last_active = jiffies;
1201 /* idle_list is LIFO */
1202 list_add(&worker->entry, &gcwq->idle_list);
1204 if (likely(!(worker->flags & WORKER_ROGUE))) {
1205 if (too_many_workers(gcwq) && !timer_pending(&gcwq->idle_timer))
1206 mod_timer(&gcwq->idle_timer,
1207 jiffies + IDLE_WORKER_TIMEOUT);
1209 wake_up_all(&gcwq->trustee_wait);
1211 /* sanity check nr_running */
1212 WARN_ON_ONCE(gcwq->nr_workers == gcwq->nr_idle &&
1213 atomic_read(get_gcwq_nr_running(gcwq->cpu)));
1217 * worker_leave_idle - leave idle state
1218 * @worker: worker which is leaving idle state
1220 * @worker is leaving idle state. Update stats.
1223 * spin_lock_irq(gcwq->lock).
1225 static void worker_leave_idle(struct worker *worker)
1227 struct global_cwq *gcwq = worker->gcwq;
1229 BUG_ON(!(worker->flags & WORKER_IDLE));
1230 worker_clr_flags(worker, WORKER_IDLE);
1232 list_del_init(&worker->entry);
1236 * worker_maybe_bind_and_lock - bind worker to its cpu if possible and lock gcwq
1239 * Works which are scheduled while the cpu is online must at least be
1240 * scheduled to a worker which is bound to the cpu so that if they are
1241 * flushed from cpu callbacks while cpu is going down, they are
1242 * guaranteed to execute on the cpu.
1244 * This function is to be used by rogue workers and rescuers to bind
1245 * themselves to the target cpu and may race with cpu going down or
1246 * coming online. kthread_bind() can't be used because it may put the
1247 * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1248 * verbatim as it's best effort and blocking and gcwq may be
1249 * [dis]associated in the meantime.
1251 * This function tries set_cpus_allowed() and locks gcwq and verifies
1252 * the binding against GCWQ_DISASSOCIATED which is set during
1253 * CPU_DYING and cleared during CPU_ONLINE, so if the worker enters
1254 * idle state or fetches works without dropping lock, it can guarantee
1255 * the scheduling requirement described in the first paragraph.
1258 * Might sleep. Called without any lock but returns with gcwq->lock
1262 * %true if the associated gcwq is online (@worker is successfully
1263 * bound), %false if offline.
1265 static bool worker_maybe_bind_and_lock(struct worker *worker)
1266 __acquires(&gcwq->lock)
1268 struct global_cwq *gcwq = worker->gcwq;
1269 struct task_struct *task = worker->task;
1273 * The following call may fail, succeed or succeed
1274 * without actually migrating the task to the cpu if
1275 * it races with cpu hotunplug operation. Verify
1276 * against GCWQ_DISASSOCIATED.
1278 if (!(gcwq->flags & GCWQ_DISASSOCIATED))
1279 set_cpus_allowed_ptr(task, get_cpu_mask(gcwq->cpu));
1281 spin_lock_irq(&gcwq->lock);
1282 if (gcwq->flags & GCWQ_DISASSOCIATED)
1284 if (task_cpu(task) == gcwq->cpu &&
1285 cpumask_equal(¤t->cpus_allowed,
1286 get_cpu_mask(gcwq->cpu)))
1288 spin_unlock_irq(&gcwq->lock);
1291 * We've raced with CPU hot[un]plug. Give it a breather
1292 * and retry migration. cond_resched() is required here;
1293 * otherwise, we might deadlock against cpu_stop trying to
1294 * bring down the CPU on non-preemptive kernel.
1302 * Function for worker->rebind_work used to rebind rogue busy workers
1303 * to the associated cpu which is coming back online. This is
1304 * scheduled by cpu up but can race with other cpu hotplug operations
1305 * and may be executed twice without intervening cpu down.
1307 static void worker_rebind_fn(struct work_struct *work)
1309 struct worker *worker = container_of(work, struct worker, rebind_work);
1310 struct global_cwq *gcwq = worker->gcwq;
1312 if (worker_maybe_bind_and_lock(worker))
1313 worker_clr_flags(worker, WORKER_REBIND);
1315 spin_unlock_irq(&gcwq->lock);
1318 static struct worker *alloc_worker(void)
1320 struct worker *worker;
1322 worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1324 INIT_LIST_HEAD(&worker->entry);
1325 INIT_LIST_HEAD(&worker->scheduled);
1326 INIT_WORK(&worker->rebind_work, worker_rebind_fn);
1327 /* on creation a worker is in !idle && prep state */
1328 worker->flags = WORKER_PREP;
1334 * create_worker - create a new workqueue worker
1335 * @gcwq: gcwq the new worker will belong to
1336 * @bind: whether to set affinity to @cpu or not
1338 * Create a new worker which is bound to @gcwq. The returned worker
1339 * can be started by calling start_worker() or destroyed using
1343 * Might sleep. Does GFP_KERNEL allocations.
1346 * Pointer to the newly created worker.
1348 static struct worker *create_worker(struct global_cwq *gcwq, bool bind)
1350 bool on_unbound_cpu = gcwq->cpu == WORK_CPU_UNBOUND;
1351 struct worker *worker = NULL;
1354 spin_lock_irq(&gcwq->lock);
1355 while (ida_get_new(&gcwq->worker_ida, &id)) {
1356 spin_unlock_irq(&gcwq->lock);
1357 if (!ida_pre_get(&gcwq->worker_ida, GFP_KERNEL))
1359 spin_lock_irq(&gcwq->lock);
1361 spin_unlock_irq(&gcwq->lock);
1363 worker = alloc_worker();
1367 worker->gcwq = gcwq;
1370 if (!on_unbound_cpu)
1371 worker->task = kthread_create_on_node(worker_thread,
1373 cpu_to_node(gcwq->cpu),
1374 "kworker/%u:%d", gcwq->cpu, id);
1376 worker->task = kthread_create(worker_thread, worker,
1377 "kworker/u:%d", id);
1378 if (IS_ERR(worker->task))
1382 * A rogue worker will become a regular one if CPU comes
1383 * online later on. Make sure every worker has
1384 * PF_THREAD_BOUND set.
1386 if (bind && !on_unbound_cpu)
1387 kthread_bind(worker->task, gcwq->cpu);
1389 worker->task->flags |= PF_THREAD_BOUND;
1391 worker->flags |= WORKER_UNBOUND;
1397 spin_lock_irq(&gcwq->lock);
1398 ida_remove(&gcwq->worker_ida, id);
1399 spin_unlock_irq(&gcwq->lock);
1406 * start_worker - start a newly created worker
1407 * @worker: worker to start
1409 * Make the gcwq aware of @worker and start it.
1412 * spin_lock_irq(gcwq->lock).
1414 static void start_worker(struct worker *worker)
1416 worker->flags |= WORKER_STARTED;
1417 worker->gcwq->nr_workers++;
1418 worker_enter_idle(worker);
1419 wake_up_process(worker->task);
1423 * destroy_worker - destroy a workqueue worker
1424 * @worker: worker to be destroyed
1426 * Destroy @worker and adjust @gcwq stats accordingly.
1429 * spin_lock_irq(gcwq->lock) which is released and regrabbed.
1431 static void destroy_worker(struct worker *worker)
1433 struct global_cwq *gcwq = worker->gcwq;
1434 int id = worker->id;
1436 /* sanity check frenzy */
1437 BUG_ON(worker->current_work);
1438 BUG_ON(!list_empty(&worker->scheduled));
1440 if (worker->flags & WORKER_STARTED)
1442 if (worker->flags & WORKER_IDLE)
1445 list_del_init(&worker->entry);
1446 worker->flags |= WORKER_DIE;
1448 spin_unlock_irq(&gcwq->lock);
1450 kthread_stop(worker->task);
1453 spin_lock_irq(&gcwq->lock);
1454 ida_remove(&gcwq->worker_ida, id);
1457 static void idle_worker_timeout(unsigned long __gcwq)
1459 struct global_cwq *gcwq = (void *)__gcwq;
1461 spin_lock_irq(&gcwq->lock);
1463 if (too_many_workers(gcwq)) {
1464 struct worker *worker;
1465 unsigned long expires;
1467 /* idle_list is kept in LIFO order, check the last one */
1468 worker = list_entry(gcwq->idle_list.prev, struct worker, entry);
1469 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1471 if (time_before(jiffies, expires))
1472 mod_timer(&gcwq->idle_timer, expires);
1474 /* it's been idle for too long, wake up manager */
1475 gcwq->flags |= GCWQ_MANAGE_WORKERS;
1476 wake_up_worker(gcwq);
1480 spin_unlock_irq(&gcwq->lock);
1483 static bool send_mayday(struct work_struct *work)
1485 struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1486 struct workqueue_struct *wq = cwq->wq;
1489 if (!(wq->flags & WQ_RESCUER))
1492 /* mayday mayday mayday */
1493 cpu = cwq->gcwq->cpu;
1494 /* WORK_CPU_UNBOUND can't be set in cpumask, use cpu 0 instead */
1495 if (cpu == WORK_CPU_UNBOUND)
1497 if (!mayday_test_and_set_cpu(cpu, wq->mayday_mask))
1498 wake_up_process(wq->rescuer->task);
1502 static void gcwq_mayday_timeout(unsigned long __gcwq)
1504 struct global_cwq *gcwq = (void *)__gcwq;
1505 struct work_struct *work;
1507 spin_lock_irq(&gcwq->lock);
1509 if (need_to_create_worker(gcwq)) {
1511 * We've been trying to create a new worker but
1512 * haven't been successful. We might be hitting an
1513 * allocation deadlock. Send distress signals to
1516 list_for_each_entry(work, &gcwq->worklist, entry)
1520 spin_unlock_irq(&gcwq->lock);
1522 mod_timer(&gcwq->mayday_timer, jiffies + MAYDAY_INTERVAL);
1526 * maybe_create_worker - create a new worker if necessary
1527 * @gcwq: gcwq to create a new worker for
1529 * Create a new worker for @gcwq if necessary. @gcwq is guaranteed to
1530 * have at least one idle worker on return from this function. If
1531 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1532 * sent to all rescuers with works scheduled on @gcwq to resolve
1533 * possible allocation deadlock.
1535 * On return, need_to_create_worker() is guaranteed to be false and
1536 * may_start_working() true.
1539 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1540 * multiple times. Does GFP_KERNEL allocations. Called only from
1544 * false if no action was taken and gcwq->lock stayed locked, true
1547 static bool maybe_create_worker(struct global_cwq *gcwq)
1548 __releases(&gcwq->lock)
1549 __acquires(&gcwq->lock)
1551 if (!need_to_create_worker(gcwq))
1554 spin_unlock_irq(&gcwq->lock);
1556 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1557 mod_timer(&gcwq->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1560 struct worker *worker;
1562 worker = create_worker(gcwq, true);
1564 del_timer_sync(&gcwq->mayday_timer);
1565 spin_lock_irq(&gcwq->lock);
1566 start_worker(worker);
1567 BUG_ON(need_to_create_worker(gcwq));
1571 if (!need_to_create_worker(gcwq))
1574 __set_current_state(TASK_INTERRUPTIBLE);
1575 schedule_timeout(CREATE_COOLDOWN);
1577 if (!need_to_create_worker(gcwq))
1581 del_timer_sync(&gcwq->mayday_timer);
1582 spin_lock_irq(&gcwq->lock);
1583 if (need_to_create_worker(gcwq))
1589 * maybe_destroy_worker - destroy workers which have been idle for a while
1590 * @gcwq: gcwq to destroy workers for
1592 * Destroy @gcwq workers which have been idle for longer than
1593 * IDLE_WORKER_TIMEOUT.
1596 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1597 * multiple times. Called only from manager.
1600 * false if no action was taken and gcwq->lock stayed locked, true
1603 static bool maybe_destroy_workers(struct global_cwq *gcwq)
1607 while (too_many_workers(gcwq)) {
1608 struct worker *worker;
1609 unsigned long expires;
1611 worker = list_entry(gcwq->idle_list.prev, struct worker, entry);
1612 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1614 if (time_before(jiffies, expires)) {
1615 mod_timer(&gcwq->idle_timer, expires);
1619 destroy_worker(worker);
1627 * manage_workers - manage worker pool
1630 * Assume the manager role and manage gcwq worker pool @worker belongs
1631 * to. At any given time, there can be only zero or one manager per
1632 * gcwq. The exclusion is handled automatically by this function.
1634 * The caller can safely start processing works on false return. On
1635 * true return, it's guaranteed that need_to_create_worker() is false
1636 * and may_start_working() is true.
1639 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1640 * multiple times. Does GFP_KERNEL allocations.
1643 * false if no action was taken and gcwq->lock stayed locked, true if
1644 * some action was taken.
1646 static bool manage_workers(struct worker *worker)
1648 struct global_cwq *gcwq = worker->gcwq;
1651 if (gcwq->flags & GCWQ_MANAGING_WORKERS)
1654 gcwq->flags &= ~GCWQ_MANAGE_WORKERS;
1655 gcwq->flags |= GCWQ_MANAGING_WORKERS;
1658 * Destroy and then create so that may_start_working() is true
1661 ret |= maybe_destroy_workers(gcwq);
1662 ret |= maybe_create_worker(gcwq);
1664 gcwq->flags &= ~GCWQ_MANAGING_WORKERS;
1667 * The trustee might be waiting to take over the manager
1668 * position, tell it we're done.
1670 if (unlikely(gcwq->trustee))
1671 wake_up_all(&gcwq->trustee_wait);
1677 * move_linked_works - move linked works to a list
1678 * @work: start of series of works to be scheduled
1679 * @head: target list to append @work to
1680 * @nextp: out paramter for nested worklist walking
1682 * Schedule linked works starting from @work to @head. Work series to
1683 * be scheduled starts at @work and includes any consecutive work with
1684 * WORK_STRUCT_LINKED set in its predecessor.
1686 * If @nextp is not NULL, it's updated to point to the next work of
1687 * the last scheduled work. This allows move_linked_works() to be
1688 * nested inside outer list_for_each_entry_safe().
1691 * spin_lock_irq(gcwq->lock).
1693 static void move_linked_works(struct work_struct *work, struct list_head *head,
1694 struct work_struct **nextp)
1696 struct work_struct *n;
1699 * Linked worklist will always end before the end of the list,
1700 * use NULL for list head.
1702 list_for_each_entry_safe_from(work, n, NULL, entry) {
1703 list_move_tail(&work->entry, head);
1704 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1709 * If we're already inside safe list traversal and have moved
1710 * multiple works to the scheduled queue, the next position
1711 * needs to be updated.
1717 static void cwq_activate_first_delayed(struct cpu_workqueue_struct *cwq)
1719 struct work_struct *work = list_first_entry(&cwq->delayed_works,
1720 struct work_struct, entry);
1721 struct list_head *pos = gcwq_determine_ins_pos(cwq->gcwq, cwq);
1723 trace_workqueue_activate_work(work);
1724 move_linked_works(work, pos, NULL);
1725 __clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
1730 * cwq_dec_nr_in_flight - decrement cwq's nr_in_flight
1731 * @cwq: cwq of interest
1732 * @color: color of work which left the queue
1733 * @delayed: for a delayed work
1735 * A work either has completed or is removed from pending queue,
1736 * decrement nr_in_flight of its cwq and handle workqueue flushing.
1739 * spin_lock_irq(gcwq->lock).
1741 static void cwq_dec_nr_in_flight(struct cpu_workqueue_struct *cwq, int color,
1744 /* ignore uncolored works */
1745 if (color == WORK_NO_COLOR)
1748 cwq->nr_in_flight[color]--;
1752 if (!list_empty(&cwq->delayed_works)) {
1753 /* one down, submit a delayed one */
1754 if (cwq->nr_active < cwq->max_active)
1755 cwq_activate_first_delayed(cwq);
1759 /* is flush in progress and are we at the flushing tip? */
1760 if (likely(cwq->flush_color != color))
1763 /* are there still in-flight works? */
1764 if (cwq->nr_in_flight[color])
1767 /* this cwq is done, clear flush_color */
1768 cwq->flush_color = -1;
1771 * If this was the last cwq, wake up the first flusher. It
1772 * will handle the rest.
1774 if (atomic_dec_and_test(&cwq->wq->nr_cwqs_to_flush))
1775 complete(&cwq->wq->first_flusher->done);
1779 * process_one_work - process single work
1781 * @work: work to process
1783 * Process @work. This function contains all the logics necessary to
1784 * process a single work including synchronization against and
1785 * interaction with other workers on the same cpu, queueing and
1786 * flushing. As long as context requirement is met, any worker can
1787 * call this function to process a work.
1790 * spin_lock_irq(gcwq->lock) which is released and regrabbed.
1792 static void process_one_work(struct worker *worker, struct work_struct *work)
1793 __releases(&gcwq->lock)
1794 __acquires(&gcwq->lock)
1796 struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1797 struct global_cwq *gcwq = cwq->gcwq;
1798 struct hlist_head *bwh = busy_worker_head(gcwq, work);
1799 bool cpu_intensive = cwq->wq->flags & WQ_CPU_INTENSIVE;
1800 work_func_t f = work->func;
1802 struct worker *collision;
1803 #ifdef CONFIG_LOCKDEP
1805 * It is permissible to free the struct work_struct from
1806 * inside the function that is called from it, this we need to
1807 * take into account for lockdep too. To avoid bogus "held
1808 * lock freed" warnings as well as problems when looking into
1809 * work->lockdep_map, make a copy and use that here.
1811 struct lockdep_map lockdep_map = work->lockdep_map;
1814 * A single work shouldn't be executed concurrently by
1815 * multiple workers on a single cpu. Check whether anyone is
1816 * already processing the work. If so, defer the work to the
1817 * currently executing one.
1819 collision = __find_worker_executing_work(gcwq, bwh, work);
1820 if (unlikely(collision)) {
1821 move_linked_works(work, &collision->scheduled, NULL);
1825 /* claim and process */
1826 debug_work_deactivate(work);
1827 hlist_add_head(&worker->hentry, bwh);
1828 worker->current_work = work;
1829 worker->current_cwq = cwq;
1830 work_color = get_work_color(work);
1832 /* record the current cpu number in the work data and dequeue */
1833 set_work_cpu(work, gcwq->cpu);
1834 list_del_init(&work->entry);
1837 * If HIGHPRI_PENDING, check the next work, and, if HIGHPRI,
1838 * wake up another worker; otherwise, clear HIGHPRI_PENDING.
1840 if (unlikely(gcwq->flags & GCWQ_HIGHPRI_PENDING)) {
1841 struct work_struct *nwork = list_first_entry(&gcwq->worklist,
1842 struct work_struct, entry);
1844 if (!list_empty(&gcwq->worklist) &&
1845 get_work_cwq(nwork)->wq->flags & WQ_HIGHPRI)
1846 wake_up_worker(gcwq);
1848 gcwq->flags &= ~GCWQ_HIGHPRI_PENDING;
1852 * CPU intensive works don't participate in concurrency
1853 * management. They're the scheduler's responsibility.
1855 if (unlikely(cpu_intensive))
1856 worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
1858 spin_unlock_irq(&gcwq->lock);
1860 work_clear_pending(work);
1861 lock_map_acquire_read(&cwq->wq->lockdep_map);
1862 lock_map_acquire(&lockdep_map);
1863 trace_workqueue_execute_start(work);
1866 * While we must be careful to not use "work" after this, the trace
1867 * point will only record its address.
1869 trace_workqueue_execute_end(work);
1870 lock_map_release(&lockdep_map);
1871 lock_map_release(&cwq->wq->lockdep_map);
1873 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
1874 printk(KERN_ERR "BUG: workqueue leaked lock or atomic: "
1876 current->comm, preempt_count(), task_pid_nr(current));
1877 printk(KERN_ERR " last function: ");
1878 print_symbol("%s\n", (unsigned long)f);
1879 debug_show_held_locks(current);
1883 spin_lock_irq(&gcwq->lock);
1885 /* clear cpu intensive status */
1886 if (unlikely(cpu_intensive))
1887 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
1889 /* we're done with it, release */
1890 hlist_del_init(&worker->hentry);
1891 worker->current_work = NULL;
1892 worker->current_cwq = NULL;
1893 cwq_dec_nr_in_flight(cwq, work_color, false);
1897 * process_scheduled_works - process scheduled works
1900 * Process all scheduled works. Please note that the scheduled list
1901 * may change while processing a work, so this function repeatedly
1902 * fetches a work from the top and executes it.
1905 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1908 static void process_scheduled_works(struct worker *worker)
1910 while (!list_empty(&worker->scheduled)) {
1911 struct work_struct *work = list_first_entry(&worker->scheduled,
1912 struct work_struct, entry);
1913 process_one_work(worker, work);
1918 * worker_thread - the worker thread function
1921 * The gcwq worker thread function. There's a single dynamic pool of
1922 * these per each cpu. These workers process all works regardless of
1923 * their specific target workqueue. The only exception is works which
1924 * belong to workqueues with a rescuer which will be explained in
1927 static int worker_thread(void *__worker)
1929 struct worker *worker = __worker;
1930 struct global_cwq *gcwq = worker->gcwq;
1932 /* tell the scheduler that this is a workqueue worker */
1933 worker->task->flags |= PF_WQ_WORKER;
1935 spin_lock_irq(&gcwq->lock);
1937 /* DIE can be set only while we're idle, checking here is enough */
1938 if (worker->flags & WORKER_DIE) {
1939 spin_unlock_irq(&gcwq->lock);
1940 worker->task->flags &= ~PF_WQ_WORKER;
1944 worker_leave_idle(worker);
1946 /* no more worker necessary? */
1947 if (!need_more_worker(gcwq))
1950 /* do we need to manage? */
1951 if (unlikely(!may_start_working(gcwq)) && manage_workers(worker))
1955 * ->scheduled list can only be filled while a worker is
1956 * preparing to process a work or actually processing it.
1957 * Make sure nobody diddled with it while I was sleeping.
1959 BUG_ON(!list_empty(&worker->scheduled));
1962 * When control reaches this point, we're guaranteed to have
1963 * at least one idle worker or that someone else has already
1964 * assumed the manager role.
1966 worker_clr_flags(worker, WORKER_PREP);
1969 struct work_struct *work =
1970 list_first_entry(&gcwq->worklist,
1971 struct work_struct, entry);
1973 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
1974 /* optimization path, not strictly necessary */
1975 process_one_work(worker, work);
1976 if (unlikely(!list_empty(&worker->scheduled)))
1977 process_scheduled_works(worker);
1979 move_linked_works(work, &worker->scheduled, NULL);
1980 process_scheduled_works(worker);
1982 } while (keep_working(gcwq));
1984 worker_set_flags(worker, WORKER_PREP, false);
1986 if (unlikely(need_to_manage_workers(gcwq)) && manage_workers(worker))
1990 * gcwq->lock is held and there's no work to process and no
1991 * need to manage, sleep. Workers are woken up only while
1992 * holding gcwq->lock or from local cpu, so setting the
1993 * current state before releasing gcwq->lock is enough to
1994 * prevent losing any event.
1996 worker_enter_idle(worker);
1997 __set_current_state(TASK_INTERRUPTIBLE);
1998 spin_unlock_irq(&gcwq->lock);
2004 * rescuer_thread - the rescuer thread function
2005 * @__wq: the associated workqueue
2007 * Workqueue rescuer thread function. There's one rescuer for each
2008 * workqueue which has WQ_RESCUER set.
2010 * Regular work processing on a gcwq may block trying to create a new
2011 * worker which uses GFP_KERNEL allocation which has slight chance of
2012 * developing into deadlock if some works currently on the same queue
2013 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2014 * the problem rescuer solves.
2016 * When such condition is possible, the gcwq summons rescuers of all
2017 * workqueues which have works queued on the gcwq and let them process
2018 * those works so that forward progress can be guaranteed.
2020 * This should happen rarely.
2022 static int rescuer_thread(void *__wq)
2024 struct workqueue_struct *wq = __wq;
2025 struct worker *rescuer = wq->rescuer;
2026 struct list_head *scheduled = &rescuer->scheduled;
2027 bool is_unbound = wq->flags & WQ_UNBOUND;
2030 set_user_nice(current, RESCUER_NICE_LEVEL);
2032 set_current_state(TASK_INTERRUPTIBLE);
2034 if (kthread_should_stop())
2038 * See whether any cpu is asking for help. Unbounded
2039 * workqueues use cpu 0 in mayday_mask for CPU_UNBOUND.
2041 for_each_mayday_cpu(cpu, wq->mayday_mask) {
2042 unsigned int tcpu = is_unbound ? WORK_CPU_UNBOUND : cpu;
2043 struct cpu_workqueue_struct *cwq = get_cwq(tcpu, wq);
2044 struct global_cwq *gcwq = cwq->gcwq;
2045 struct work_struct *work, *n;
2047 __set_current_state(TASK_RUNNING);
2048 mayday_clear_cpu(cpu, wq->mayday_mask);
2050 /* migrate to the target cpu if possible */
2051 rescuer->gcwq = gcwq;
2052 worker_maybe_bind_and_lock(rescuer);
2055 * Slurp in all works issued via this workqueue and
2058 BUG_ON(!list_empty(&rescuer->scheduled));
2059 list_for_each_entry_safe(work, n, &gcwq->worklist, entry)
2060 if (get_work_cwq(work) == cwq)
2061 move_linked_works(work, scheduled, &n);
2063 process_scheduled_works(rescuer);
2066 * Leave this gcwq. If keep_working() is %true, notify a
2067 * regular worker; otherwise, we end up with 0 concurrency
2068 * and stalling the execution.
2070 if (keep_working(gcwq))
2071 wake_up_worker(gcwq);
2073 spin_unlock_irq(&gcwq->lock);
2081 struct work_struct work;
2082 struct completion done;
2085 static void wq_barrier_func(struct work_struct *work)
2087 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2088 complete(&barr->done);
2092 * insert_wq_barrier - insert a barrier work
2093 * @cwq: cwq to insert barrier into
2094 * @barr: wq_barrier to insert
2095 * @target: target work to attach @barr to
2096 * @worker: worker currently executing @target, NULL if @target is not executing
2098 * @barr is linked to @target such that @barr is completed only after
2099 * @target finishes execution. Please note that the ordering
2100 * guarantee is observed only with respect to @target and on the local
2103 * Currently, a queued barrier can't be canceled. This is because
2104 * try_to_grab_pending() can't determine whether the work to be
2105 * grabbed is at the head of the queue and thus can't clear LINKED
2106 * flag of the previous work while there must be a valid next work
2107 * after a work with LINKED flag set.
2109 * Note that when @worker is non-NULL, @target may be modified
2110 * underneath us, so we can't reliably determine cwq from @target.
2113 * spin_lock_irq(gcwq->lock).
2115 static void insert_wq_barrier(struct cpu_workqueue_struct *cwq,
2116 struct wq_barrier *barr,
2117 struct work_struct *target, struct worker *worker)
2119 struct list_head *head;
2120 unsigned int linked = 0;
2123 * debugobject calls are safe here even with gcwq->lock locked
2124 * as we know for sure that this will not trigger any of the
2125 * checks and call back into the fixup functions where we
2128 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2129 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2130 init_completion(&barr->done);
2133 * If @target is currently being executed, schedule the
2134 * barrier to the worker; otherwise, put it after @target.
2137 head = worker->scheduled.next;
2139 unsigned long *bits = work_data_bits(target);
2141 head = target->entry.next;
2142 /* there can already be other linked works, inherit and set */
2143 linked = *bits & WORK_STRUCT_LINKED;
2144 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2147 debug_work_activate(&barr->work);
2148 insert_work(cwq, &barr->work, head,
2149 work_color_to_flags(WORK_NO_COLOR) | linked);
2153 * flush_workqueue_prep_cwqs - prepare cwqs for workqueue flushing
2154 * @wq: workqueue being flushed
2155 * @flush_color: new flush color, < 0 for no-op
2156 * @work_color: new work color, < 0 for no-op
2158 * Prepare cwqs for workqueue flushing.
2160 * If @flush_color is non-negative, flush_color on all cwqs should be
2161 * -1. If no cwq has in-flight commands at the specified color, all
2162 * cwq->flush_color's stay at -1 and %false is returned. If any cwq
2163 * has in flight commands, its cwq->flush_color is set to
2164 * @flush_color, @wq->nr_cwqs_to_flush is updated accordingly, cwq
2165 * wakeup logic is armed and %true is returned.
2167 * The caller should have initialized @wq->first_flusher prior to
2168 * calling this function with non-negative @flush_color. If
2169 * @flush_color is negative, no flush color update is done and %false
2172 * If @work_color is non-negative, all cwqs should have the same
2173 * work_color which is previous to @work_color and all will be
2174 * advanced to @work_color.
2177 * mutex_lock(wq->flush_mutex).
2180 * %true if @flush_color >= 0 and there's something to flush. %false
2183 static bool flush_workqueue_prep_cwqs(struct workqueue_struct *wq,
2184 int flush_color, int work_color)
2189 if (flush_color >= 0) {
2190 BUG_ON(atomic_read(&wq->nr_cwqs_to_flush));
2191 atomic_set(&wq->nr_cwqs_to_flush, 1);
2194 for_each_cwq_cpu(cpu, wq) {
2195 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2196 struct global_cwq *gcwq = cwq->gcwq;
2198 spin_lock_irq(&gcwq->lock);
2200 if (flush_color >= 0) {
2201 BUG_ON(cwq->flush_color != -1);
2203 if (cwq->nr_in_flight[flush_color]) {
2204 cwq->flush_color = flush_color;
2205 atomic_inc(&wq->nr_cwqs_to_flush);
2210 if (work_color >= 0) {
2211 BUG_ON(work_color != work_next_color(cwq->work_color));
2212 cwq->work_color = work_color;
2215 spin_unlock_irq(&gcwq->lock);
2218 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_cwqs_to_flush))
2219 complete(&wq->first_flusher->done);
2225 * flush_workqueue - ensure that any scheduled work has run to completion.
2226 * @wq: workqueue to flush
2228 * Forces execution of the workqueue and blocks until its completion.
2229 * This is typically used in driver shutdown handlers.
2231 * We sleep until all works which were queued on entry have been handled,
2232 * but we are not livelocked by new incoming ones.
2234 void flush_workqueue(struct workqueue_struct *wq)
2236 struct wq_flusher this_flusher = {
2237 .list = LIST_HEAD_INIT(this_flusher.list),
2239 .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
2243 lock_map_acquire(&wq->lockdep_map);
2244 lock_map_release(&wq->lockdep_map);
2246 mutex_lock(&wq->flush_mutex);
2249 * Start-to-wait phase
2251 next_color = work_next_color(wq->work_color);
2253 if (next_color != wq->flush_color) {
2255 * Color space is not full. The current work_color
2256 * becomes our flush_color and work_color is advanced
2259 BUG_ON(!list_empty(&wq->flusher_overflow));
2260 this_flusher.flush_color = wq->work_color;
2261 wq->work_color = next_color;
2263 if (!wq->first_flusher) {
2264 /* no flush in progress, become the first flusher */
2265 BUG_ON(wq->flush_color != this_flusher.flush_color);
2267 wq->first_flusher = &this_flusher;
2269 if (!flush_workqueue_prep_cwqs(wq, wq->flush_color,
2271 /* nothing to flush, done */
2272 wq->flush_color = next_color;
2273 wq->first_flusher = NULL;
2278 BUG_ON(wq->flush_color == this_flusher.flush_color);
2279 list_add_tail(&this_flusher.list, &wq->flusher_queue);
2280 flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2284 * Oops, color space is full, wait on overflow queue.
2285 * The next flush completion will assign us
2286 * flush_color and transfer to flusher_queue.
2288 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2291 mutex_unlock(&wq->flush_mutex);
2293 wait_for_completion(&this_flusher.done);
2296 * Wake-up-and-cascade phase
2298 * First flushers are responsible for cascading flushes and
2299 * handling overflow. Non-first flushers can simply return.
2301 if (wq->first_flusher != &this_flusher)
2304 mutex_lock(&wq->flush_mutex);
2306 /* we might have raced, check again with mutex held */
2307 if (wq->first_flusher != &this_flusher)
2310 wq->first_flusher = NULL;
2312 BUG_ON(!list_empty(&this_flusher.list));
2313 BUG_ON(wq->flush_color != this_flusher.flush_color);
2316 struct wq_flusher *next, *tmp;
2318 /* complete all the flushers sharing the current flush color */
2319 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2320 if (next->flush_color != wq->flush_color)
2322 list_del_init(&next->list);
2323 complete(&next->done);
2326 BUG_ON(!list_empty(&wq->flusher_overflow) &&
2327 wq->flush_color != work_next_color(wq->work_color));
2329 /* this flush_color is finished, advance by one */
2330 wq->flush_color = work_next_color(wq->flush_color);
2332 /* one color has been freed, handle overflow queue */
2333 if (!list_empty(&wq->flusher_overflow)) {
2335 * Assign the same color to all overflowed
2336 * flushers, advance work_color and append to
2337 * flusher_queue. This is the start-to-wait
2338 * phase for these overflowed flushers.
2340 list_for_each_entry(tmp, &wq->flusher_overflow, list)
2341 tmp->flush_color = wq->work_color;
2343 wq->work_color = work_next_color(wq->work_color);
2345 list_splice_tail_init(&wq->flusher_overflow,
2346 &wq->flusher_queue);
2347 flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2350 if (list_empty(&wq->flusher_queue)) {
2351 BUG_ON(wq->flush_color != wq->work_color);
2356 * Need to flush more colors. Make the next flusher
2357 * the new first flusher and arm cwqs.
2359 BUG_ON(wq->flush_color == wq->work_color);
2360 BUG_ON(wq->flush_color != next->flush_color);
2362 list_del_init(&next->list);
2363 wq->first_flusher = next;
2365 if (flush_workqueue_prep_cwqs(wq, wq->flush_color, -1))
2369 * Meh... this color is already done, clear first
2370 * flusher and repeat cascading.
2372 wq->first_flusher = NULL;
2376 mutex_unlock(&wq->flush_mutex);
2378 EXPORT_SYMBOL_GPL(flush_workqueue);
2381 * drain_workqueue - drain a workqueue
2382 * @wq: workqueue to drain
2384 * Wait until the workqueue becomes empty. While draining is in progress,
2385 * only chain queueing is allowed. IOW, only currently pending or running
2386 * work items on @wq can queue further work items on it. @wq is flushed
2387 * repeatedly until it becomes empty. The number of flushing is detemined
2388 * by the depth of chaining and should be relatively short. Whine if it
2391 void drain_workqueue(struct workqueue_struct *wq)
2393 unsigned int flush_cnt = 0;
2397 * __queue_work() needs to test whether there are drainers, is much
2398 * hotter than drain_workqueue() and already looks at @wq->flags.
2399 * Use WQ_DRAINING so that queue doesn't have to check nr_drainers.
2401 spin_lock(&workqueue_lock);
2402 if (!wq->nr_drainers++)
2403 wq->flags |= WQ_DRAINING;
2404 spin_unlock(&workqueue_lock);
2406 flush_workqueue(wq);
2408 for_each_cwq_cpu(cpu, wq) {
2409 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2412 spin_lock_irq(&cwq->gcwq->lock);
2413 drained = !cwq->nr_active && list_empty(&cwq->delayed_works);
2414 spin_unlock_irq(&cwq->gcwq->lock);
2419 if (++flush_cnt == 10 ||
2420 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2421 pr_warning("workqueue %s: flush on destruction isn't complete after %u tries\n",
2422 wq->name, flush_cnt);
2426 spin_lock(&workqueue_lock);
2427 if (!--wq->nr_drainers)
2428 wq->flags &= ~WQ_DRAINING;
2429 spin_unlock(&workqueue_lock);
2431 EXPORT_SYMBOL_GPL(drain_workqueue);
2433 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
2434 bool wait_executing)
2436 struct worker *worker = NULL;
2437 struct global_cwq *gcwq;
2438 struct cpu_workqueue_struct *cwq;
2441 gcwq = get_work_gcwq(work);
2445 spin_lock_irq(&gcwq->lock);
2446 if (!list_empty(&work->entry)) {
2448 * See the comment near try_to_grab_pending()->smp_rmb().
2449 * If it was re-queued to a different gcwq under us, we
2450 * are not going to wait.
2453 cwq = get_work_cwq(work);
2454 if (unlikely(!cwq || gcwq != cwq->gcwq))
2456 } else if (wait_executing) {
2457 worker = find_worker_executing_work(gcwq, work);
2460 cwq = worker->current_cwq;
2464 insert_wq_barrier(cwq, barr, work, worker);
2465 spin_unlock_irq(&gcwq->lock);
2468 * If @max_active is 1 or rescuer is in use, flushing another work
2469 * item on the same workqueue may lead to deadlock. Make sure the
2470 * flusher is not running on the same workqueue by verifying write
2473 if (cwq->wq->saved_max_active == 1 || cwq->wq->flags & WQ_RESCUER)
2474 lock_map_acquire(&cwq->wq->lockdep_map);
2476 lock_map_acquire_read(&cwq->wq->lockdep_map);
2477 lock_map_release(&cwq->wq->lockdep_map);
2481 spin_unlock_irq(&gcwq->lock);
2486 * flush_work - wait for a work to finish executing the last queueing instance
2487 * @work: the work to flush
2489 * Wait until @work has finished execution. This function considers
2490 * only the last queueing instance of @work. If @work has been
2491 * enqueued across different CPUs on a non-reentrant workqueue or on
2492 * multiple workqueues, @work might still be executing on return on
2493 * some of the CPUs from earlier queueing.
2495 * If @work was queued only on a non-reentrant, ordered or unbound
2496 * workqueue, @work is guaranteed to be idle on return if it hasn't
2497 * been requeued since flush started.
2500 * %true if flush_work() waited for the work to finish execution,
2501 * %false if it was already idle.
2503 bool flush_work(struct work_struct *work)
2505 struct wq_barrier barr;
2507 if (start_flush_work(work, &barr, true)) {
2508 wait_for_completion(&barr.done);
2509 destroy_work_on_stack(&barr.work);
2514 EXPORT_SYMBOL_GPL(flush_work);
2516 static bool wait_on_cpu_work(struct global_cwq *gcwq, struct work_struct *work)
2518 struct wq_barrier barr;
2519 struct worker *worker;
2521 spin_lock_irq(&gcwq->lock);
2523 worker = find_worker_executing_work(gcwq, work);
2524 if (unlikely(worker))
2525 insert_wq_barrier(worker->current_cwq, &barr, work, worker);
2527 spin_unlock_irq(&gcwq->lock);
2529 if (unlikely(worker)) {
2530 wait_for_completion(&barr.done);
2531 destroy_work_on_stack(&barr.work);
2537 static bool wait_on_work(struct work_struct *work)
2544 lock_map_acquire(&work->lockdep_map);
2545 lock_map_release(&work->lockdep_map);
2547 for_each_gcwq_cpu(cpu)
2548 ret |= wait_on_cpu_work(get_gcwq(cpu), work);
2553 * flush_work_sync - wait until a work has finished execution
2554 * @work: the work to flush
2556 * Wait until @work has finished execution. On return, it's
2557 * guaranteed that all queueing instances of @work which happened
2558 * before this function is called are finished. In other words, if
2559 * @work hasn't been requeued since this function was called, @work is
2560 * guaranteed to be idle on return.
2563 * %true if flush_work_sync() waited for the work to finish execution,
2564 * %false if it was already idle.
2566 bool flush_work_sync(struct work_struct *work)
2568 struct wq_barrier barr;
2569 bool pending, waited;
2571 /* we'll wait for executions separately, queue barr only if pending */
2572 pending = start_flush_work(work, &barr, false);
2574 /* wait for executions to finish */
2575 waited = wait_on_work(work);
2577 /* wait for the pending one */
2579 wait_for_completion(&barr.done);
2580 destroy_work_on_stack(&barr.work);
2583 return pending || waited;
2585 EXPORT_SYMBOL_GPL(flush_work_sync);
2588 * Upon a successful return (>= 0), the caller "owns" WORK_STRUCT_PENDING bit,
2589 * so this work can't be re-armed in any way.
2591 static int try_to_grab_pending(struct work_struct *work)
2593 struct global_cwq *gcwq;
2596 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
2600 * The queueing is in progress, or it is already queued. Try to
2601 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
2603 gcwq = get_work_gcwq(work);
2607 spin_lock_irq(&gcwq->lock);
2608 if (!list_empty(&work->entry)) {
2610 * This work is queued, but perhaps we locked the wrong gcwq.
2611 * In that case we must see the new value after rmb(), see
2612 * insert_work()->wmb().
2615 if (gcwq == get_work_gcwq(work)) {
2616 debug_work_deactivate(work);
2617 list_del_init(&work->entry);
2618 cwq_dec_nr_in_flight(get_work_cwq(work),
2619 get_work_color(work),
2620 *work_data_bits(work) & WORK_STRUCT_DELAYED);
2624 spin_unlock_irq(&gcwq->lock);
2629 static bool __cancel_work_timer(struct work_struct *work,
2630 struct timer_list* timer)
2635 ret = (timer && likely(del_timer(timer)));
2637 ret = try_to_grab_pending(work);
2639 } while (unlikely(ret < 0));
2641 clear_work_data(work);
2646 * cancel_work_sync - cancel a work and wait for it to finish
2647 * @work: the work to cancel
2649 * Cancel @work and wait for its execution to finish. This function
2650 * can be used even if the work re-queues itself or migrates to
2651 * another workqueue. On return from this function, @work is
2652 * guaranteed to be not pending or executing on any CPU.
2654 * cancel_work_sync(&delayed_work->work) must not be used for
2655 * delayed_work's. Use cancel_delayed_work_sync() instead.
2657 * The caller must ensure that the workqueue on which @work was last
2658 * queued can't be destroyed before this function returns.
2661 * %true if @work was pending, %false otherwise.
2663 bool cancel_work_sync(struct work_struct *work)
2665 return __cancel_work_timer(work, NULL);
2667 EXPORT_SYMBOL_GPL(cancel_work_sync);
2670 * flush_delayed_work - wait for a dwork to finish executing the last queueing
2671 * @dwork: the delayed work to flush
2673 * Delayed timer is cancelled and the pending work is queued for
2674 * immediate execution. Like flush_work(), this function only
2675 * considers the last queueing instance of @dwork.
2678 * %true if flush_work() waited for the work to finish execution,
2679 * %false if it was already idle.
2681 bool flush_delayed_work(struct delayed_work *dwork)
2683 if (del_timer_sync(&dwork->timer))
2684 __queue_work(raw_smp_processor_id(),
2685 get_work_cwq(&dwork->work)->wq, &dwork->work);
2686 return flush_work(&dwork->work);
2688 EXPORT_SYMBOL(flush_delayed_work);
2691 * flush_delayed_work_sync - wait for a dwork to finish
2692 * @dwork: the delayed work to flush
2694 * Delayed timer is cancelled and the pending work is queued for
2695 * execution immediately. Other than timer handling, its behavior
2696 * is identical to flush_work_sync().
2699 * %true if flush_work_sync() waited for the work to finish execution,
2700 * %false if it was already idle.
2702 bool flush_delayed_work_sync(struct delayed_work *dwork)
2704 if (del_timer_sync(&dwork->timer))
2705 __queue_work(raw_smp_processor_id(),
2706 get_work_cwq(&dwork->work)->wq, &dwork->work);
2707 return flush_work_sync(&dwork->work);
2709 EXPORT_SYMBOL(flush_delayed_work_sync);
2712 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2713 * @dwork: the delayed work cancel
2715 * This is cancel_work_sync() for delayed works.
2718 * %true if @dwork was pending, %false otherwise.
2720 bool cancel_delayed_work_sync(struct delayed_work *dwork)
2722 return __cancel_work_timer(&dwork->work, &dwork->timer);
2724 EXPORT_SYMBOL(cancel_delayed_work_sync);
2727 * schedule_work - put work task in global workqueue
2728 * @work: job to be done
2730 * Returns zero if @work was already on the kernel-global workqueue and
2731 * non-zero otherwise.
2733 * This puts a job in the kernel-global workqueue if it was not already
2734 * queued and leaves it in the same position on the kernel-global
2735 * workqueue otherwise.
2737 int schedule_work(struct work_struct *work)
2739 return queue_work(system_wq, work);
2741 EXPORT_SYMBOL(schedule_work);
2744 * schedule_work_on - put work task on a specific cpu
2745 * @cpu: cpu to put the work task on
2746 * @work: job to be done
2748 * This puts a job on a specific cpu
2750 int schedule_work_on(int cpu, struct work_struct *work)
2752 return queue_work_on(cpu, system_wq, work);
2754 EXPORT_SYMBOL(schedule_work_on);
2757 * schedule_delayed_work - put work task in global workqueue after delay
2758 * @dwork: job to be done
2759 * @delay: number of jiffies to wait or 0 for immediate execution
2761 * After waiting for a given time this puts a job in the kernel-global
2764 int schedule_delayed_work(struct delayed_work *dwork,
2765 unsigned long delay)
2767 return queue_delayed_work(system_wq, dwork, delay);
2769 EXPORT_SYMBOL(schedule_delayed_work);
2772 * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
2774 * @dwork: job to be done
2775 * @delay: number of jiffies to wait
2777 * After waiting for a given time this puts a job in the kernel-global
2778 * workqueue on the specified CPU.
2780 int schedule_delayed_work_on(int cpu,
2781 struct delayed_work *dwork, unsigned long delay)
2783 return queue_delayed_work_on(cpu, system_wq, dwork, delay);
2785 EXPORT_SYMBOL(schedule_delayed_work_on);
2788 * schedule_on_each_cpu - execute a function synchronously on each online CPU
2789 * @func: the function to call
2791 * schedule_on_each_cpu() executes @func on each online CPU using the
2792 * system workqueue and blocks until all CPUs have completed.
2793 * schedule_on_each_cpu() is very slow.
2796 * 0 on success, -errno on failure.
2798 int schedule_on_each_cpu(work_func_t func)
2801 struct work_struct __percpu *works;
2803 works = alloc_percpu(struct work_struct);
2809 for_each_online_cpu(cpu) {
2810 struct work_struct *work = per_cpu_ptr(works, cpu);
2812 INIT_WORK(work, func);
2813 schedule_work_on(cpu, work);
2816 for_each_online_cpu(cpu)
2817 flush_work(per_cpu_ptr(works, cpu));
2825 * flush_scheduled_work - ensure that any scheduled work has run to completion.
2827 * Forces execution of the kernel-global workqueue and blocks until its
2830 * Think twice before calling this function! It's very easy to get into
2831 * trouble if you don't take great care. Either of the following situations
2832 * will lead to deadlock:
2834 * One of the work items currently on the workqueue needs to acquire
2835 * a lock held by your code or its caller.
2837 * Your code is running in the context of a work routine.
2839 * They will be detected by lockdep when they occur, but the first might not
2840 * occur very often. It depends on what work items are on the workqueue and
2841 * what locks they need, which you have no control over.
2843 * In most situations flushing the entire workqueue is overkill; you merely
2844 * need to know that a particular work item isn't queued and isn't running.
2845 * In such cases you should use cancel_delayed_work_sync() or
2846 * cancel_work_sync() instead.
2848 void flush_scheduled_work(void)
2850 flush_workqueue(system_wq);
2852 EXPORT_SYMBOL(flush_scheduled_work);
2855 * execute_in_process_context - reliably execute the routine with user context
2856 * @fn: the function to execute
2857 * @ew: guaranteed storage for the execute work structure (must
2858 * be available when the work executes)
2860 * Executes the function immediately if process context is available,
2861 * otherwise schedules the function for delayed execution.
2863 * Returns: 0 - function was executed
2864 * 1 - function was scheduled for execution
2866 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
2868 if (!in_interrupt()) {
2873 INIT_WORK(&ew->work, fn);
2874 schedule_work(&ew->work);
2878 EXPORT_SYMBOL_GPL(execute_in_process_context);
2880 int keventd_up(void)
2882 return system_wq != NULL;
2885 static int alloc_cwqs(struct workqueue_struct *wq)
2888 * cwqs are forced aligned according to WORK_STRUCT_FLAG_BITS.
2889 * Make sure that the alignment isn't lower than that of
2890 * unsigned long long.
2892 const size_t size = sizeof(struct cpu_workqueue_struct);
2893 const size_t align = max_t(size_t, 1 << WORK_STRUCT_FLAG_BITS,
2894 __alignof__(unsigned long long));
2896 if (!(wq->flags & WQ_UNBOUND))
2897 wq->cpu_wq.pcpu = __alloc_percpu(size, align);
2902 * Allocate enough room to align cwq and put an extra
2903 * pointer at the end pointing back to the originally
2904 * allocated pointer which will be used for free.
2906 ptr = kzalloc(size + align + sizeof(void *), GFP_KERNEL);
2908 wq->cpu_wq.single = PTR_ALIGN(ptr, align);
2909 *(void **)(wq->cpu_wq.single + 1) = ptr;
2913 /* just in case, make sure it's actually aligned */
2914 BUG_ON(!IS_ALIGNED(wq->cpu_wq.v, align));
2915 return wq->cpu_wq.v ? 0 : -ENOMEM;
2918 static void free_cwqs(struct workqueue_struct *wq)
2920 if (!(wq->flags & WQ_UNBOUND))
2921 free_percpu(wq->cpu_wq.pcpu);
2922 else if (wq->cpu_wq.single) {
2923 /* the pointer to free is stored right after the cwq */
2924 kfree(*(void **)(wq->cpu_wq.single + 1));
2928 static int wq_clamp_max_active(int max_active, unsigned int flags,
2931 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
2933 if (max_active < 1 || max_active > lim)
2934 printk(KERN_WARNING "workqueue: max_active %d requested for %s "
2935 "is out of range, clamping between %d and %d\n",
2936 max_active, name, 1, lim);
2938 return clamp_val(max_active, 1, lim);
2941 struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
2944 struct lock_class_key *key,
2945 const char *lock_name, ...)
2947 va_list args, args1;
2948 struct workqueue_struct *wq;
2952 /* determine namelen, allocate wq and format name */
2953 va_start(args, lock_name);
2954 va_copy(args1, args);
2955 namelen = vsnprintf(NULL, 0, fmt, args) + 1;
2957 wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
2961 vsnprintf(wq->name, namelen, fmt, args1);
2966 * Workqueues which may be used during memory reclaim should
2967 * have a rescuer to guarantee forward progress.
2969 if (flags & WQ_MEM_RECLAIM)
2970 flags |= WQ_RESCUER;
2973 * Unbound workqueues aren't concurrency managed and should be
2974 * dispatched to workers immediately.
2976 if (flags & WQ_UNBOUND)
2977 flags |= WQ_HIGHPRI;
2979 max_active = max_active ?: WQ_DFL_ACTIVE;
2980 max_active = wq_clamp_max_active(max_active, flags, wq->name);
2984 wq->saved_max_active = max_active;
2985 mutex_init(&wq->flush_mutex);
2986 atomic_set(&wq->nr_cwqs_to_flush, 0);
2987 INIT_LIST_HEAD(&wq->flusher_queue);
2988 INIT_LIST_HEAD(&wq->flusher_overflow);
2990 lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
2991 INIT_LIST_HEAD(&wq->list);
2993 if (alloc_cwqs(wq) < 0)
2996 for_each_cwq_cpu(cpu, wq) {
2997 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2998 struct global_cwq *gcwq = get_gcwq(cpu);
3000 BUG_ON((unsigned long)cwq & WORK_STRUCT_FLAG_MASK);
3003 cwq->flush_color = -1;
3004 cwq->max_active = max_active;
3005 INIT_LIST_HEAD(&cwq->delayed_works);
3008 if (flags & WQ_RESCUER) {
3009 struct worker *rescuer;
3011 if (!alloc_mayday_mask(&wq->mayday_mask, GFP_KERNEL))
3014 wq->rescuer = rescuer = alloc_worker();
3018 rescuer->task = kthread_create(rescuer_thread, wq, "%s",
3020 if (IS_ERR(rescuer->task))
3023 rescuer->task->flags |= PF_THREAD_BOUND;
3024 wake_up_process(rescuer->task);
3028 * workqueue_lock protects global freeze state and workqueues
3029 * list. Grab it, set max_active accordingly and add the new
3030 * workqueue to workqueues list.
3032 spin_lock(&workqueue_lock);
3034 if (workqueue_freezing && wq->flags & WQ_FREEZABLE)
3035 for_each_cwq_cpu(cpu, wq)
3036 get_cwq(cpu, wq)->max_active = 0;
3038 list_add(&wq->list, &workqueues);
3040 spin_unlock(&workqueue_lock);
3046 free_mayday_mask(wq->mayday_mask);
3052 EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
3055 * destroy_workqueue - safely terminate a workqueue
3056 * @wq: target workqueue
3058 * Safely destroy a workqueue. All work currently pending will be done first.
3060 void destroy_workqueue(struct workqueue_struct *wq)
3064 /* drain it before proceeding with destruction */
3065 drain_workqueue(wq);
3068 * wq list is used to freeze wq, remove from list after
3069 * flushing is complete in case freeze races us.
3071 spin_lock(&workqueue_lock);
3072 list_del(&wq->list);
3073 spin_unlock(&workqueue_lock);
3076 for_each_cwq_cpu(cpu, wq) {
3077 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3080 for (i = 0; i < WORK_NR_COLORS; i++)
3081 BUG_ON(cwq->nr_in_flight[i]);
3082 BUG_ON(cwq->nr_active);
3083 BUG_ON(!list_empty(&cwq->delayed_works));
3086 if (wq->flags & WQ_RESCUER) {
3087 kthread_stop(wq->rescuer->task);
3088 free_mayday_mask(wq->mayday_mask);
3095 EXPORT_SYMBOL_GPL(destroy_workqueue);
3098 * workqueue_set_max_active - adjust max_active of a workqueue
3099 * @wq: target workqueue
3100 * @max_active: new max_active value.
3102 * Set max_active of @wq to @max_active.
3105 * Don't call from IRQ context.
3107 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
3111 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
3113 spin_lock(&workqueue_lock);
3115 wq->saved_max_active = max_active;
3117 for_each_cwq_cpu(cpu, wq) {
3118 struct global_cwq *gcwq = get_gcwq(cpu);
3120 spin_lock_irq(&gcwq->lock);
3122 if (!(wq->flags & WQ_FREEZABLE) ||
3123 !(gcwq->flags & GCWQ_FREEZING))
3124 get_cwq(gcwq->cpu, wq)->max_active = max_active;
3126 spin_unlock_irq(&gcwq->lock);
3129 spin_unlock(&workqueue_lock);
3131 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
3134 * workqueue_congested - test whether a workqueue is congested
3135 * @cpu: CPU in question
3136 * @wq: target workqueue
3138 * Test whether @wq's cpu workqueue for @cpu is congested. There is
3139 * no synchronization around this function and the test result is
3140 * unreliable and only useful as advisory hints or for debugging.
3143 * %true if congested, %false otherwise.
3145 bool workqueue_congested(unsigned int cpu, struct workqueue_struct *wq)
3147 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3149 return !list_empty(&cwq->delayed_works);
3151 EXPORT_SYMBOL_GPL(workqueue_congested);
3154 * work_cpu - return the last known associated cpu for @work
3155 * @work: the work of interest
3158 * CPU number if @work was ever queued. WORK_CPU_NONE otherwise.
3160 unsigned int work_cpu(struct work_struct *work)
3162 struct global_cwq *gcwq = get_work_gcwq(work);
3164 return gcwq ? gcwq->cpu : WORK_CPU_NONE;
3166 EXPORT_SYMBOL_GPL(work_cpu);
3169 * work_busy - test whether a work is currently pending or running
3170 * @work: the work to be tested
3172 * Test whether @work is currently pending or running. There is no
3173 * synchronization around this function and the test result is
3174 * unreliable and only useful as advisory hints or for debugging.
3175 * Especially for reentrant wqs, the pending state might hide the
3179 * OR'd bitmask of WORK_BUSY_* bits.
3181 unsigned int work_busy(struct work_struct *work)
3183 struct global_cwq *gcwq = get_work_gcwq(work);
3184 unsigned long flags;
3185 unsigned int ret = 0;
3190 spin_lock_irqsave(&gcwq->lock, flags);
3192 if (work_pending(work))
3193 ret |= WORK_BUSY_PENDING;
3194 if (find_worker_executing_work(gcwq, work))
3195 ret |= WORK_BUSY_RUNNING;
3197 spin_unlock_irqrestore(&gcwq->lock, flags);
3201 EXPORT_SYMBOL_GPL(work_busy);
3206 * There are two challenges in supporting CPU hotplug. Firstly, there
3207 * are a lot of assumptions on strong associations among work, cwq and
3208 * gcwq which make migrating pending and scheduled works very
3209 * difficult to implement without impacting hot paths. Secondly,
3210 * gcwqs serve mix of short, long and very long running works making
3211 * blocked draining impractical.
3213 * This is solved by allowing a gcwq to be detached from CPU, running
3214 * it with unbound (rogue) workers and allowing it to be reattached
3215 * later if the cpu comes back online. A separate thread is created
3216 * to govern a gcwq in such state and is called the trustee of the
3219 * Trustee states and their descriptions.
3221 * START Command state used on startup. On CPU_DOWN_PREPARE, a
3222 * new trustee is started with this state.
3224 * IN_CHARGE Once started, trustee will enter this state after
3225 * assuming the manager role and making all existing
3226 * workers rogue. DOWN_PREPARE waits for trustee to
3227 * enter this state. After reaching IN_CHARGE, trustee
3228 * tries to execute the pending worklist until it's empty
3229 * and the state is set to BUTCHER, or the state is set
3232 * BUTCHER Command state which is set by the cpu callback after
3233 * the cpu has went down. Once this state is set trustee
3234 * knows that there will be no new works on the worklist
3235 * and once the worklist is empty it can proceed to
3236 * killing idle workers.
3238 * RELEASE Command state which is set by the cpu callback if the
3239 * cpu down has been canceled or it has come online
3240 * again. After recognizing this state, trustee stops
3241 * trying to drain or butcher and clears ROGUE, rebinds
3242 * all remaining workers back to the cpu and releases
3245 * DONE Trustee will enter this state after BUTCHER or RELEASE
3248 * trustee CPU draining
3249 * took over down complete
3250 * START -----------> IN_CHARGE -----------> BUTCHER -----------> DONE
3252 * | CPU is back online v return workers |
3253 * ----------------> RELEASE --------------
3257 * trustee_wait_event_timeout - timed event wait for trustee
3258 * @cond: condition to wait for
3259 * @timeout: timeout in jiffies
3261 * wait_event_timeout() for trustee to use. Handles locking and
3262 * checks for RELEASE request.
3265 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
3266 * multiple times. To be used by trustee.
3269 * Positive indicating left time if @cond is satisfied, 0 if timed
3270 * out, -1 if canceled.
3272 #define trustee_wait_event_timeout(cond, timeout) ({ \
3273 long __ret = (timeout); \
3274 while (!((cond) || (gcwq->trustee_state == TRUSTEE_RELEASE)) && \
3276 spin_unlock_irq(&gcwq->lock); \
3277 __wait_event_timeout(gcwq->trustee_wait, (cond) || \
3278 (gcwq->trustee_state == TRUSTEE_RELEASE), \
3280 spin_lock_irq(&gcwq->lock); \
3282 gcwq->trustee_state == TRUSTEE_RELEASE ? -1 : (__ret); \
3286 * trustee_wait_event - event wait for trustee
3287 * @cond: condition to wait for
3289 * wait_event() for trustee to use. Automatically handles locking and
3290 * checks for CANCEL request.
3293 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
3294 * multiple times. To be used by trustee.
3297 * 0 if @cond is satisfied, -1 if canceled.
3299 #define trustee_wait_event(cond) ({ \
3301 __ret1 = trustee_wait_event_timeout(cond, MAX_SCHEDULE_TIMEOUT);\
3302 __ret1 < 0 ? -1 : 0; \
3305 static int __cpuinit trustee_thread(void *__gcwq)
3307 struct global_cwq *gcwq = __gcwq;
3308 struct worker *worker;
3309 struct work_struct *work;
3310 struct hlist_node *pos;
3314 BUG_ON(gcwq->cpu != smp_processor_id());
3316 spin_lock_irq(&gcwq->lock);
3318 * Claim the manager position and make all workers rogue.
3319 * Trustee must be bound to the target cpu and can't be
3322 BUG_ON(gcwq->cpu != smp_processor_id());
3323 rc = trustee_wait_event(!(gcwq->flags & GCWQ_MANAGING_WORKERS));
3326 gcwq->flags |= GCWQ_MANAGING_WORKERS;
3328 list_for_each_entry(worker, &gcwq->idle_list, entry)
3329 worker->flags |= WORKER_ROGUE;
3331 for_each_busy_worker(worker, i, pos, gcwq)
3332 worker->flags |= WORKER_ROGUE;
3335 * Call schedule() so that we cross rq->lock and thus can
3336 * guarantee sched callbacks see the rogue flag. This is
3337 * necessary as scheduler callbacks may be invoked from other
3340 spin_unlock_irq(&gcwq->lock);
3342 spin_lock_irq(&gcwq->lock);
3345 * Sched callbacks are disabled now. Zap nr_running. After
3346 * this, nr_running stays zero and need_more_worker() and
3347 * keep_working() are always true as long as the worklist is
3350 atomic_set(get_gcwq_nr_running(gcwq->cpu), 0);
3352 spin_unlock_irq(&gcwq->lock);
3353 del_timer_sync(&gcwq->idle_timer);
3354 spin_lock_irq(&gcwq->lock);
3357 * We're now in charge. Notify and proceed to drain. We need
3358 * to keep the gcwq running during the whole CPU down
3359 * procedure as other cpu hotunplug callbacks may need to
3360 * flush currently running tasks.
3362 gcwq->trustee_state = TRUSTEE_IN_CHARGE;
3363 wake_up_all(&gcwq->trustee_wait);
3366 * The original cpu is in the process of dying and may go away
3367 * anytime now. When that happens, we and all workers would
3368 * be migrated to other cpus. Try draining any left work. We
3369 * want to get it over with ASAP - spam rescuers, wake up as
3370 * many idlers as necessary and create new ones till the
3371 * worklist is empty. Note that if the gcwq is frozen, there
3372 * may be frozen works in freezable cwqs. Don't declare
3373 * completion while frozen.
3375 while (gcwq->nr_workers != gcwq->nr_idle ||
3376 gcwq->flags & GCWQ_FREEZING ||
3377 gcwq->trustee_state == TRUSTEE_IN_CHARGE) {
3380 list_for_each_entry(work, &gcwq->worklist, entry) {
3385 list_for_each_entry(worker, &gcwq->idle_list, entry) {
3388 wake_up_process(worker->task);
3391 if (need_to_create_worker(gcwq)) {
3392 spin_unlock_irq(&gcwq->lock);
3393 worker = create_worker(gcwq, false);
3394 spin_lock_irq(&gcwq->lock);
3396 worker->flags |= WORKER_ROGUE;
3397 start_worker(worker);
3401 /* give a breather */
3402 if (trustee_wait_event_timeout(false, TRUSTEE_COOLDOWN) < 0)
3407 * Either all works have been scheduled and cpu is down, or
3408 * cpu down has already been canceled. Wait for and butcher
3409 * all workers till we're canceled.
3412 rc = trustee_wait_event(!list_empty(&gcwq->idle_list));
3413 while (!list_empty(&gcwq->idle_list))
3414 destroy_worker(list_first_entry(&gcwq->idle_list,
3415 struct worker, entry));
3416 } while (gcwq->nr_workers && rc >= 0);
3419 * At this point, either draining has completed and no worker
3420 * is left, or cpu down has been canceled or the cpu is being
3421 * brought back up. There shouldn't be any idle one left.
3422 * Tell the remaining busy ones to rebind once it finishes the
3423 * currently scheduled works by scheduling the rebind_work.
3425 WARN_ON(!list_empty(&gcwq->idle_list));
3427 for_each_busy_worker(worker, i, pos, gcwq) {
3428 struct work_struct *rebind_work = &worker->rebind_work;
3431 * Rebind_work may race with future cpu hotplug
3432 * operations. Use a separate flag to mark that
3433 * rebinding is scheduled.
3435 worker->flags |= WORKER_REBIND;
3436 worker->flags &= ~WORKER_ROGUE;
3438 /* queue rebind_work, wq doesn't matter, use the default one */
3439 if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
3440 work_data_bits(rebind_work)))
3443 debug_work_activate(rebind_work);
3444 insert_work(get_cwq(gcwq->cpu, system_wq), rebind_work,
3445 worker->scheduled.next,
3446 work_color_to_flags(WORK_NO_COLOR));
3449 /* relinquish manager role */
3450 gcwq->flags &= ~GCWQ_MANAGING_WORKERS;
3452 /* notify completion */
3453 gcwq->trustee = NULL;
3454 gcwq->trustee_state = TRUSTEE_DONE;
3455 wake_up_all(&gcwq->trustee_wait);
3456 spin_unlock_irq(&gcwq->lock);
3461 * wait_trustee_state - wait for trustee to enter the specified state
3462 * @gcwq: gcwq the trustee of interest belongs to
3463 * @state: target state to wait for
3465 * Wait for the trustee to reach @state. DONE is already matched.
3468 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
3469 * multiple times. To be used by cpu_callback.
3471 static void __cpuinit wait_trustee_state(struct global_cwq *gcwq, int state)
3472 __releases(&gcwq->lock)
3473 __acquires(&gcwq->lock)
3475 if (!(gcwq->trustee_state == state ||
3476 gcwq->trustee_state == TRUSTEE_DONE)) {
3477 spin_unlock_irq(&gcwq->lock);
3478 __wait_event(gcwq->trustee_wait,
3479 gcwq->trustee_state == state ||
3480 gcwq->trustee_state == TRUSTEE_DONE);
3481 spin_lock_irq(&gcwq->lock);
3485 static int __devinit workqueue_cpu_callback(struct notifier_block *nfb,
3486 unsigned long action,
3489 unsigned int cpu = (unsigned long)hcpu;
3490 struct global_cwq *gcwq = get_gcwq(cpu);
3491 struct task_struct *new_trustee = NULL;
3492 struct worker *uninitialized_var(new_worker);
3493 unsigned long flags;
3495 action &= ~CPU_TASKS_FROZEN;
3498 case CPU_DOWN_PREPARE:
3499 new_trustee = kthread_create(trustee_thread, gcwq,
3500 "workqueue_trustee/%d\n", cpu);
3501 if (IS_ERR(new_trustee))
3502 return notifier_from_errno(PTR_ERR(new_trustee));
3503 kthread_bind(new_trustee, cpu);
3505 case CPU_UP_PREPARE:
3506 BUG_ON(gcwq->first_idle);
3507 new_worker = create_worker(gcwq, false);
3510 kthread_stop(new_trustee);
3515 /* some are called w/ irq disabled, don't disturb irq status */
3516 spin_lock_irqsave(&gcwq->lock, flags);
3519 case CPU_DOWN_PREPARE:
3520 /* initialize trustee and tell it to acquire the gcwq */
3521 BUG_ON(gcwq->trustee || gcwq->trustee_state != TRUSTEE_DONE);
3522 gcwq->trustee = new_trustee;
3523 gcwq->trustee_state = TRUSTEE_START;
3524 wake_up_process(gcwq->trustee);
3525 wait_trustee_state(gcwq, TRUSTEE_IN_CHARGE);
3527 case CPU_UP_PREPARE:
3528 BUG_ON(gcwq->first_idle);
3529 gcwq->first_idle = new_worker;
3534 * Before this, the trustee and all workers except for
3535 * the ones which are still executing works from
3536 * before the last CPU down must be on the cpu. After
3537 * this, they'll all be diasporas.
3539 gcwq->flags |= GCWQ_DISASSOCIATED;
3543 gcwq->trustee_state = TRUSTEE_BUTCHER;
3545 case CPU_UP_CANCELED:
3546 destroy_worker(gcwq->first_idle);
3547 gcwq->first_idle = NULL;
3550 case CPU_DOWN_FAILED:
3552 gcwq->flags &= ~GCWQ_DISASSOCIATED;
3553 if (gcwq->trustee_state != TRUSTEE_DONE) {
3554 gcwq->trustee_state = TRUSTEE_RELEASE;
3555 wake_up_process(gcwq->trustee);
3556 wait_trustee_state(gcwq, TRUSTEE_DONE);
3560 * Trustee is done and there might be no worker left.
3561 * Put the first_idle in and request a real manager to
3564 spin_unlock_irq(&gcwq->lock);
3565 kthread_bind(gcwq->first_idle->task, cpu);
3566 spin_lock_irq(&gcwq->lock);
3567 gcwq->flags |= GCWQ_MANAGE_WORKERS;
3568 start_worker(gcwq->first_idle);
3569 gcwq->first_idle = NULL;
3573 spin_unlock_irqrestore(&gcwq->lock, flags);
3575 return notifier_from_errno(0);
3580 struct work_for_cpu {
3581 struct completion completion;
3587 static int do_work_for_cpu(void *_wfc)
3589 struct work_for_cpu *wfc = _wfc;
3590 wfc->ret = wfc->fn(wfc->arg);
3591 complete(&wfc->completion);
3596 * work_on_cpu - run a function in user context on a particular cpu
3597 * @cpu: the cpu to run on
3598 * @fn: the function to run
3599 * @arg: the function arg
3601 * This will return the value @fn returns.
3602 * It is up to the caller to ensure that the cpu doesn't go offline.
3603 * The caller must not hold any locks which would prevent @fn from completing.
3605 long work_on_cpu(unsigned int cpu, long (*fn)(void *), void *arg)
3607 struct task_struct *sub_thread;
3608 struct work_for_cpu wfc = {
3609 .completion = COMPLETION_INITIALIZER_ONSTACK(wfc.completion),
3614 sub_thread = kthread_create(do_work_for_cpu, &wfc, "work_for_cpu");
3615 if (IS_ERR(sub_thread))
3616 return PTR_ERR(sub_thread);
3617 kthread_bind(sub_thread, cpu);
3618 wake_up_process(sub_thread);
3619 wait_for_completion(&wfc.completion);
3622 EXPORT_SYMBOL_GPL(work_on_cpu);
3623 #endif /* CONFIG_SMP */
3625 #ifdef CONFIG_FREEZER
3628 * freeze_workqueues_begin - begin freezing workqueues
3630 * Start freezing workqueues. After this function returns, all freezable
3631 * workqueues will queue new works to their frozen_works list instead of
3635 * Grabs and releases workqueue_lock and gcwq->lock's.
3637 void freeze_workqueues_begin(void)
3641 spin_lock(&workqueue_lock);
3643 BUG_ON(workqueue_freezing);
3644 workqueue_freezing = true;
3646 for_each_gcwq_cpu(cpu) {
3647 struct global_cwq *gcwq = get_gcwq(cpu);
3648 struct workqueue_struct *wq;
3650 spin_lock_irq(&gcwq->lock);
3652 BUG_ON(gcwq->flags & GCWQ_FREEZING);
3653 gcwq->flags |= GCWQ_FREEZING;
3655 list_for_each_entry(wq, &workqueues, list) {
3656 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3658 if (cwq && wq->flags & WQ_FREEZABLE)
3659 cwq->max_active = 0;
3662 spin_unlock_irq(&gcwq->lock);
3665 spin_unlock(&workqueue_lock);
3669 * freeze_workqueues_busy - are freezable workqueues still busy?
3671 * Check whether freezing is complete. This function must be called
3672 * between freeze_workqueues_begin() and thaw_workqueues().
3675 * Grabs and releases workqueue_lock.
3678 * %true if some freezable workqueues are still busy. %false if freezing
3681 bool freeze_workqueues_busy(void)
3686 spin_lock(&workqueue_lock);
3688 BUG_ON(!workqueue_freezing);
3690 for_each_gcwq_cpu(cpu) {
3691 struct workqueue_struct *wq;
3693 * nr_active is monotonically decreasing. It's safe
3694 * to peek without lock.
3696 list_for_each_entry(wq, &workqueues, list) {
3697 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3699 if (!cwq || !(wq->flags & WQ_FREEZABLE))
3702 BUG_ON(cwq->nr_active < 0);
3703 if (cwq->nr_active) {
3710 spin_unlock(&workqueue_lock);
3715 * thaw_workqueues - thaw workqueues
3717 * Thaw workqueues. Normal queueing is restored and all collected
3718 * frozen works are transferred to their respective gcwq worklists.
3721 * Grabs and releases workqueue_lock and gcwq->lock's.
3723 void thaw_workqueues(void)
3727 spin_lock(&workqueue_lock);
3729 if (!workqueue_freezing)
3732 for_each_gcwq_cpu(cpu) {
3733 struct global_cwq *gcwq = get_gcwq(cpu);
3734 struct workqueue_struct *wq;
3736 spin_lock_irq(&gcwq->lock);
3738 BUG_ON(!(gcwq->flags & GCWQ_FREEZING));
3739 gcwq->flags &= ~GCWQ_FREEZING;
3741 list_for_each_entry(wq, &workqueues, list) {
3742 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3744 if (!cwq || !(wq->flags & WQ_FREEZABLE))
3747 /* restore max_active and repopulate worklist */
3748 cwq->max_active = wq->saved_max_active;
3750 while (!list_empty(&cwq->delayed_works) &&
3751 cwq->nr_active < cwq->max_active)
3752 cwq_activate_first_delayed(cwq);
3755 wake_up_worker(gcwq);
3757 spin_unlock_irq(&gcwq->lock);
3760 workqueue_freezing = false;
3762 spin_unlock(&workqueue_lock);
3764 #endif /* CONFIG_FREEZER */
3766 static int __init init_workqueues(void)
3771 cpu_notifier(workqueue_cpu_callback, CPU_PRI_WORKQUEUE);
3773 /* initialize gcwqs */
3774 for_each_gcwq_cpu(cpu) {
3775 struct global_cwq *gcwq = get_gcwq(cpu);
3777 spin_lock_init(&gcwq->lock);
3778 INIT_LIST_HEAD(&gcwq->worklist);
3780 gcwq->flags |= GCWQ_DISASSOCIATED;
3782 INIT_LIST_HEAD(&gcwq->idle_list);
3783 for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)
3784 INIT_HLIST_HEAD(&gcwq->busy_hash[i]);
3786 init_timer_deferrable(&gcwq->idle_timer);
3787 gcwq->idle_timer.function = idle_worker_timeout;
3788 gcwq->idle_timer.data = (unsigned long)gcwq;
3790 setup_timer(&gcwq->mayday_timer, gcwq_mayday_timeout,
3791 (unsigned long)gcwq);
3793 ida_init(&gcwq->worker_ida);
3795 gcwq->trustee_state = TRUSTEE_DONE;
3796 init_waitqueue_head(&gcwq->trustee_wait);
3799 /* create the initial worker */
3800 for_each_online_gcwq_cpu(cpu) {
3801 struct global_cwq *gcwq = get_gcwq(cpu);
3802 struct worker *worker;
3804 if (cpu != WORK_CPU_UNBOUND)
3805 gcwq->flags &= ~GCWQ_DISASSOCIATED;
3806 worker = create_worker(gcwq, true);
3808 spin_lock_irq(&gcwq->lock);
3809 start_worker(worker);
3810 spin_unlock_irq(&gcwq->lock);
3813 system_wq = alloc_workqueue("events", 0, 0);
3814 system_long_wq = alloc_workqueue("events_long", 0, 0);
3815 system_nrt_wq = alloc_workqueue("events_nrt", WQ_NON_REENTRANT, 0);
3816 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
3817 WQ_UNBOUND_MAX_ACTIVE);
3818 system_freezable_wq = alloc_workqueue("events_freezable",
3820 BUG_ON(!system_wq || !system_long_wq || !system_nrt_wq ||
3821 !system_unbound_wq || !system_freezable_wq);
3824 early_initcall(init_workqueues);