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.
121 * The poor guys doing the actual heavy lifting. All on-duty workers
122 * are either serving the manager role, on idle list or on busy hash.
125 /* on idle list while idle, on busy hash table while busy */
127 struct list_head entry; /* L: while idle */
128 struct hlist_node hentry; /* L: while busy */
131 struct work_struct *current_work; /* L: work being processed */
132 struct cpu_workqueue_struct *current_cwq; /* L: current_work's cwq */
133 struct list_head scheduled; /* L: scheduled works */
134 struct task_struct *task; /* I: worker task */
135 struct worker_pool *pool; /* I: the associated pool */
136 /* 64 bytes boundary on 64bit, 32 on 32bit */
137 unsigned long last_active; /* L: last active timestamp */
138 unsigned int flags; /* X: flags */
139 int id; /* I: worker id */
140 struct work_struct rebind_work; /* L: rebind worker to cpu */
144 struct global_cwq *gcwq; /* I: the owning gcwq */
146 struct list_head worklist; /* L: list of pending works */
147 int nr_workers; /* L: total number of workers */
148 int nr_idle; /* L: currently idle ones */
150 struct list_head idle_list; /* X: list of idle workers */
151 struct timer_list idle_timer; /* L: worker idle timeout */
152 struct timer_list mayday_timer; /* L: SOS timer for workers */
154 struct ida worker_ida; /* L: for worker IDs */
155 struct worker *first_idle; /* L: first idle worker */
159 * Global per-cpu workqueue. There's one and only one for each cpu
160 * and all works are queued and processed here regardless of their
164 spinlock_t lock; /* the gcwq lock */
165 unsigned int cpu; /* I: the associated cpu */
166 unsigned int flags; /* L: GCWQ_* flags */
168 /* workers are chained either in busy_hash or pool idle_list */
169 struct hlist_head busy_hash[BUSY_WORKER_HASH_SIZE];
170 /* L: hash of busy workers */
172 struct worker_pool pool; /* the worker pools */
174 struct task_struct *trustee; /* L: for gcwq shutdown */
175 unsigned int trustee_state; /* L: trustee state */
176 wait_queue_head_t trustee_wait; /* trustee wait */
177 } ____cacheline_aligned_in_smp;
180 * The per-CPU workqueue. The lower WORK_STRUCT_FLAG_BITS of
181 * work_struct->data are used for flags and thus cwqs need to be
182 * aligned at two's power of the number of flag bits.
184 struct cpu_workqueue_struct {
185 struct worker_pool *pool; /* I: the associated pool */
186 struct workqueue_struct *wq; /* I: the owning workqueue */
187 int work_color; /* L: current color */
188 int flush_color; /* L: flushing color */
189 int nr_in_flight[WORK_NR_COLORS];
190 /* L: nr of in_flight works */
191 int nr_active; /* L: nr of active works */
192 int max_active; /* L: max active works */
193 struct list_head delayed_works; /* L: delayed works */
197 * Structure used to wait for workqueue flush.
200 struct list_head list; /* F: list of flushers */
201 int flush_color; /* F: flush color waiting for */
202 struct completion done; /* flush completion */
206 * All cpumasks are assumed to be always set on UP and thus can't be
207 * used to determine whether there's something to be done.
210 typedef cpumask_var_t mayday_mask_t;
211 #define mayday_test_and_set_cpu(cpu, mask) \
212 cpumask_test_and_set_cpu((cpu), (mask))
213 #define mayday_clear_cpu(cpu, mask) cpumask_clear_cpu((cpu), (mask))
214 #define for_each_mayday_cpu(cpu, mask) for_each_cpu((cpu), (mask))
215 #define alloc_mayday_mask(maskp, gfp) zalloc_cpumask_var((maskp), (gfp))
216 #define free_mayday_mask(mask) free_cpumask_var((mask))
218 typedef unsigned long mayday_mask_t;
219 #define mayday_test_and_set_cpu(cpu, mask) test_and_set_bit(0, &(mask))
220 #define mayday_clear_cpu(cpu, mask) clear_bit(0, &(mask))
221 #define for_each_mayday_cpu(cpu, mask) if ((cpu) = 0, (mask))
222 #define alloc_mayday_mask(maskp, gfp) true
223 #define free_mayday_mask(mask) do { } while (0)
227 * The externally visible workqueue abstraction is an array of
228 * per-CPU workqueues:
230 struct workqueue_struct {
231 unsigned int flags; /* W: WQ_* flags */
233 struct cpu_workqueue_struct __percpu *pcpu;
234 struct cpu_workqueue_struct *single;
236 } cpu_wq; /* I: cwq's */
237 struct list_head list; /* W: list of all workqueues */
239 struct mutex flush_mutex; /* protects wq flushing */
240 int work_color; /* F: current work color */
241 int flush_color; /* F: current flush color */
242 atomic_t nr_cwqs_to_flush; /* flush in progress */
243 struct wq_flusher *first_flusher; /* F: first flusher */
244 struct list_head flusher_queue; /* F: flush waiters */
245 struct list_head flusher_overflow; /* F: flush overflow list */
247 mayday_mask_t mayday_mask; /* cpus requesting rescue */
248 struct worker *rescuer; /* I: rescue worker */
250 int nr_drainers; /* W: drain in progress */
251 int saved_max_active; /* W: saved cwq max_active */
252 #ifdef CONFIG_LOCKDEP
253 struct lockdep_map lockdep_map;
255 char name[]; /* I: workqueue name */
258 struct workqueue_struct *system_wq __read_mostly;
259 struct workqueue_struct *system_long_wq __read_mostly;
260 struct workqueue_struct *system_nrt_wq __read_mostly;
261 struct workqueue_struct *system_unbound_wq __read_mostly;
262 struct workqueue_struct *system_freezable_wq __read_mostly;
263 struct workqueue_struct *system_nrt_freezable_wq __read_mostly;
264 EXPORT_SYMBOL_GPL(system_wq);
265 EXPORT_SYMBOL_GPL(system_long_wq);
266 EXPORT_SYMBOL_GPL(system_nrt_wq);
267 EXPORT_SYMBOL_GPL(system_unbound_wq);
268 EXPORT_SYMBOL_GPL(system_freezable_wq);
269 EXPORT_SYMBOL_GPL(system_nrt_freezable_wq);
271 #define CREATE_TRACE_POINTS
272 #include <trace/events/workqueue.h>
274 #define for_each_busy_worker(worker, i, pos, gcwq) \
275 for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++) \
276 hlist_for_each_entry(worker, pos, &gcwq->busy_hash[i], hentry)
278 static inline int __next_gcwq_cpu(int cpu, const struct cpumask *mask,
281 if (cpu < nr_cpu_ids) {
283 cpu = cpumask_next(cpu, mask);
284 if (cpu < nr_cpu_ids)
288 return WORK_CPU_UNBOUND;
290 return WORK_CPU_NONE;
293 static inline int __next_wq_cpu(int cpu, const struct cpumask *mask,
294 struct workqueue_struct *wq)
296 return __next_gcwq_cpu(cpu, mask, !(wq->flags & WQ_UNBOUND) ? 1 : 2);
302 * An extra gcwq is defined for an invalid cpu number
303 * (WORK_CPU_UNBOUND) to host workqueues which are not bound to any
304 * specific CPU. The following iterators are similar to
305 * for_each_*_cpu() iterators but also considers the unbound gcwq.
307 * for_each_gcwq_cpu() : possible CPUs + WORK_CPU_UNBOUND
308 * for_each_online_gcwq_cpu() : online CPUs + WORK_CPU_UNBOUND
309 * for_each_cwq_cpu() : possible CPUs for bound workqueues,
310 * WORK_CPU_UNBOUND for unbound workqueues
312 #define for_each_gcwq_cpu(cpu) \
313 for ((cpu) = __next_gcwq_cpu(-1, cpu_possible_mask, 3); \
314 (cpu) < WORK_CPU_NONE; \
315 (cpu) = __next_gcwq_cpu((cpu), cpu_possible_mask, 3))
317 #define for_each_online_gcwq_cpu(cpu) \
318 for ((cpu) = __next_gcwq_cpu(-1, cpu_online_mask, 3); \
319 (cpu) < WORK_CPU_NONE; \
320 (cpu) = __next_gcwq_cpu((cpu), cpu_online_mask, 3))
322 #define for_each_cwq_cpu(cpu, wq) \
323 for ((cpu) = __next_wq_cpu(-1, cpu_possible_mask, (wq)); \
324 (cpu) < WORK_CPU_NONE; \
325 (cpu) = __next_wq_cpu((cpu), cpu_possible_mask, (wq)))
327 #ifdef CONFIG_DEBUG_OBJECTS_WORK
329 static struct debug_obj_descr work_debug_descr;
331 static void *work_debug_hint(void *addr)
333 return ((struct work_struct *) addr)->func;
337 * fixup_init is called when:
338 * - an active object is initialized
340 static int work_fixup_init(void *addr, enum debug_obj_state state)
342 struct work_struct *work = addr;
345 case ODEBUG_STATE_ACTIVE:
346 cancel_work_sync(work);
347 debug_object_init(work, &work_debug_descr);
355 * fixup_activate is called when:
356 * - an active object is activated
357 * - an unknown object is activated (might be a statically initialized object)
359 static int work_fixup_activate(void *addr, enum debug_obj_state state)
361 struct work_struct *work = addr;
365 case ODEBUG_STATE_NOTAVAILABLE:
367 * This is not really a fixup. The work struct was
368 * statically initialized. We just make sure that it
369 * is tracked in the object tracker.
371 if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
372 debug_object_init(work, &work_debug_descr);
373 debug_object_activate(work, &work_debug_descr);
379 case ODEBUG_STATE_ACTIVE:
388 * fixup_free is called when:
389 * - an active object is freed
391 static int work_fixup_free(void *addr, enum debug_obj_state state)
393 struct work_struct *work = addr;
396 case ODEBUG_STATE_ACTIVE:
397 cancel_work_sync(work);
398 debug_object_free(work, &work_debug_descr);
405 static struct debug_obj_descr work_debug_descr = {
406 .name = "work_struct",
407 .debug_hint = work_debug_hint,
408 .fixup_init = work_fixup_init,
409 .fixup_activate = work_fixup_activate,
410 .fixup_free = work_fixup_free,
413 static inline void debug_work_activate(struct work_struct *work)
415 debug_object_activate(work, &work_debug_descr);
418 static inline void debug_work_deactivate(struct work_struct *work)
420 debug_object_deactivate(work, &work_debug_descr);
423 void __init_work(struct work_struct *work, int onstack)
426 debug_object_init_on_stack(work, &work_debug_descr);
428 debug_object_init(work, &work_debug_descr);
430 EXPORT_SYMBOL_GPL(__init_work);
432 void destroy_work_on_stack(struct work_struct *work)
434 debug_object_free(work, &work_debug_descr);
436 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
439 static inline void debug_work_activate(struct work_struct *work) { }
440 static inline void debug_work_deactivate(struct work_struct *work) { }
443 /* Serializes the accesses to the list of workqueues. */
444 static DEFINE_SPINLOCK(workqueue_lock);
445 static LIST_HEAD(workqueues);
446 static bool workqueue_freezing; /* W: have wqs started freezing? */
449 * The almighty global cpu workqueues. nr_running is the only field
450 * which is expected to be used frequently by other cpus via
451 * try_to_wake_up(). Put it in a separate cacheline.
453 static DEFINE_PER_CPU(struct global_cwq, global_cwq);
454 static DEFINE_PER_CPU_SHARED_ALIGNED(atomic_t, gcwq_nr_running);
457 * Global cpu workqueue and nr_running counter for unbound gcwq. The
458 * gcwq is always online, has GCWQ_DISASSOCIATED set, and all its
459 * workers have WORKER_UNBOUND set.
461 static struct global_cwq unbound_global_cwq;
462 static atomic_t unbound_gcwq_nr_running = ATOMIC_INIT(0); /* always 0 */
464 static int worker_thread(void *__worker);
466 static struct global_cwq *get_gcwq(unsigned int cpu)
468 if (cpu != WORK_CPU_UNBOUND)
469 return &per_cpu(global_cwq, cpu);
471 return &unbound_global_cwq;
474 static atomic_t *get_pool_nr_running(struct worker_pool *pool)
476 int cpu = pool->gcwq->cpu;
478 if (cpu != WORK_CPU_UNBOUND)
479 return &per_cpu(gcwq_nr_running, cpu);
481 return &unbound_gcwq_nr_running;
484 static struct cpu_workqueue_struct *get_cwq(unsigned int cpu,
485 struct workqueue_struct *wq)
487 if (!(wq->flags & WQ_UNBOUND)) {
488 if (likely(cpu < nr_cpu_ids))
489 return per_cpu_ptr(wq->cpu_wq.pcpu, cpu);
490 } else if (likely(cpu == WORK_CPU_UNBOUND))
491 return wq->cpu_wq.single;
495 static unsigned int work_color_to_flags(int color)
497 return color << WORK_STRUCT_COLOR_SHIFT;
500 static int get_work_color(struct work_struct *work)
502 return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
503 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
506 static int work_next_color(int color)
508 return (color + 1) % WORK_NR_COLORS;
512 * A work's data points to the cwq with WORK_STRUCT_CWQ set while the
513 * work is on queue. Once execution starts, WORK_STRUCT_CWQ is
514 * cleared and the work data contains the cpu number it was last on.
516 * set_work_{cwq|cpu}() and clear_work_data() can be used to set the
517 * cwq, cpu or clear work->data. These functions should only be
518 * called while the work is owned - ie. while the PENDING bit is set.
520 * get_work_[g]cwq() can be used to obtain the gcwq or cwq
521 * corresponding to a work. gcwq is available once the work has been
522 * queued anywhere after initialization. cwq is available only from
523 * queueing until execution starts.
525 static inline void set_work_data(struct work_struct *work, unsigned long data,
528 BUG_ON(!work_pending(work));
529 atomic_long_set(&work->data, data | flags | work_static(work));
532 static void set_work_cwq(struct work_struct *work,
533 struct cpu_workqueue_struct *cwq,
534 unsigned long extra_flags)
536 set_work_data(work, (unsigned long)cwq,
537 WORK_STRUCT_PENDING | WORK_STRUCT_CWQ | extra_flags);
540 static void set_work_cpu(struct work_struct *work, unsigned int cpu)
542 set_work_data(work, cpu << WORK_STRUCT_FLAG_BITS, WORK_STRUCT_PENDING);
545 static void clear_work_data(struct work_struct *work)
547 set_work_data(work, WORK_STRUCT_NO_CPU, 0);
550 static struct cpu_workqueue_struct *get_work_cwq(struct work_struct *work)
552 unsigned long data = atomic_long_read(&work->data);
554 if (data & WORK_STRUCT_CWQ)
555 return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
560 static struct global_cwq *get_work_gcwq(struct work_struct *work)
562 unsigned long data = atomic_long_read(&work->data);
565 if (data & WORK_STRUCT_CWQ)
566 return ((struct cpu_workqueue_struct *)
567 (data & WORK_STRUCT_WQ_DATA_MASK))->pool->gcwq;
569 cpu = data >> WORK_STRUCT_FLAG_BITS;
570 if (cpu == WORK_CPU_NONE)
573 BUG_ON(cpu >= nr_cpu_ids && cpu != WORK_CPU_UNBOUND);
574 return get_gcwq(cpu);
578 * Policy functions. These define the policies on how the global
579 * worker pool is managed. Unless noted otherwise, these functions
580 * assume that they're being called with gcwq->lock held.
583 static bool __need_more_worker(struct worker_pool *pool)
585 return !atomic_read(get_pool_nr_running(pool)) ||
586 pool->gcwq->flags & GCWQ_HIGHPRI_PENDING;
590 * Need to wake up a worker? Called from anything but currently
593 * Note that, because unbound workers never contribute to nr_running, this
594 * function will always return %true for unbound gcwq as long as the
595 * worklist isn't empty.
597 static bool need_more_worker(struct worker_pool *pool)
599 return !list_empty(&pool->worklist) && __need_more_worker(pool);
602 /* Can I start working? Called from busy but !running workers. */
603 static bool may_start_working(struct worker_pool *pool)
605 return pool->nr_idle;
608 /* Do I need to keep working? Called from currently running workers. */
609 static bool keep_working(struct worker_pool *pool)
611 atomic_t *nr_running = get_pool_nr_running(pool);
613 return !list_empty(&pool->worklist) &&
614 (atomic_read(nr_running) <= 1 ||
615 pool->gcwq->flags & GCWQ_HIGHPRI_PENDING);
618 /* Do we need a new worker? Called from manager. */
619 static bool need_to_create_worker(struct worker_pool *pool)
621 return need_more_worker(pool) && !may_start_working(pool);
624 /* Do I need to be the manager? */
625 static bool need_to_manage_workers(struct worker_pool *pool)
627 return need_to_create_worker(pool) ||
628 pool->gcwq->flags & GCWQ_MANAGE_WORKERS;
631 /* Do we have too many workers and should some go away? */
632 static bool too_many_workers(struct worker_pool *pool)
634 bool managing = pool->gcwq->flags & GCWQ_MANAGING_WORKERS;
635 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
636 int nr_busy = pool->nr_workers - nr_idle;
638 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
645 /* Return the first worker. Safe with preemption disabled */
646 static struct worker *first_worker(struct worker_pool *pool)
648 if (unlikely(list_empty(&pool->idle_list)))
651 return list_first_entry(&pool->idle_list, struct worker, entry);
655 * wake_up_worker - wake up an idle worker
656 * @pool: worker pool to wake worker from
658 * Wake up the first idle worker of @pool.
661 * spin_lock_irq(gcwq->lock).
663 static void wake_up_worker(struct worker_pool *pool)
665 struct worker *worker = first_worker(pool);
668 wake_up_process(worker->task);
672 * wq_worker_waking_up - a worker is waking up
673 * @task: task waking up
674 * @cpu: CPU @task is waking up to
676 * This function is called during try_to_wake_up() when a worker is
680 * spin_lock_irq(rq->lock)
682 void wq_worker_waking_up(struct task_struct *task, unsigned int cpu)
684 struct worker *worker = kthread_data(task);
686 if (!(worker->flags & WORKER_NOT_RUNNING))
687 atomic_inc(get_pool_nr_running(worker->pool));
691 * wq_worker_sleeping - a worker is going to sleep
692 * @task: task going to sleep
693 * @cpu: CPU in question, must be the current CPU number
695 * This function is called during schedule() when a busy worker is
696 * going to sleep. Worker on the same cpu can be woken up by
697 * returning pointer to its task.
700 * spin_lock_irq(rq->lock)
703 * Worker task on @cpu to wake up, %NULL if none.
705 struct task_struct *wq_worker_sleeping(struct task_struct *task,
708 struct worker *worker = kthread_data(task), *to_wakeup = NULL;
709 struct worker_pool *pool = worker->pool;
710 atomic_t *nr_running = get_pool_nr_running(pool);
712 if (worker->flags & WORKER_NOT_RUNNING)
715 /* this can only happen on the local cpu */
716 BUG_ON(cpu != raw_smp_processor_id());
719 * The counterpart of the following dec_and_test, implied mb,
720 * worklist not empty test sequence is in insert_work().
721 * Please read comment there.
723 * NOT_RUNNING is clear. This means that trustee is not in
724 * charge and we're running on the local cpu w/ rq lock held
725 * and preemption disabled, which in turn means that none else
726 * could be manipulating idle_list, so dereferencing idle_list
727 * without gcwq lock is safe.
729 if (atomic_dec_and_test(nr_running) && !list_empty(&pool->worklist))
730 to_wakeup = first_worker(pool);
731 return to_wakeup ? to_wakeup->task : NULL;
735 * worker_set_flags - set worker flags and adjust nr_running accordingly
737 * @flags: flags to set
738 * @wakeup: wakeup an idle worker if necessary
740 * Set @flags in @worker->flags and adjust nr_running accordingly. If
741 * nr_running becomes zero and @wakeup is %true, an idle worker is
745 * spin_lock_irq(gcwq->lock)
747 static inline void worker_set_flags(struct worker *worker, unsigned int flags,
750 struct worker_pool *pool = worker->pool;
752 WARN_ON_ONCE(worker->task != current);
755 * If transitioning into NOT_RUNNING, adjust nr_running and
756 * wake up an idle worker as necessary if requested by
759 if ((flags & WORKER_NOT_RUNNING) &&
760 !(worker->flags & WORKER_NOT_RUNNING)) {
761 atomic_t *nr_running = get_pool_nr_running(pool);
764 if (atomic_dec_and_test(nr_running) &&
765 !list_empty(&pool->worklist))
766 wake_up_worker(pool);
768 atomic_dec(nr_running);
771 worker->flags |= flags;
775 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
777 * @flags: flags to clear
779 * Clear @flags in @worker->flags and adjust nr_running accordingly.
782 * spin_lock_irq(gcwq->lock)
784 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
786 struct worker_pool *pool = worker->pool;
787 unsigned int oflags = worker->flags;
789 WARN_ON_ONCE(worker->task != current);
791 worker->flags &= ~flags;
794 * If transitioning out of NOT_RUNNING, increment nr_running. Note
795 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
796 * of multiple flags, not a single flag.
798 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
799 if (!(worker->flags & WORKER_NOT_RUNNING))
800 atomic_inc(get_pool_nr_running(pool));
804 * busy_worker_head - return the busy hash head for a work
805 * @gcwq: gcwq of interest
806 * @work: work to be hashed
808 * Return hash head of @gcwq for @work.
811 * spin_lock_irq(gcwq->lock).
814 * Pointer to the hash head.
816 static struct hlist_head *busy_worker_head(struct global_cwq *gcwq,
817 struct work_struct *work)
819 const int base_shift = ilog2(sizeof(struct work_struct));
820 unsigned long v = (unsigned long)work;
822 /* simple shift and fold hash, do we need something better? */
824 v += v >> BUSY_WORKER_HASH_ORDER;
825 v &= BUSY_WORKER_HASH_MASK;
827 return &gcwq->busy_hash[v];
831 * __find_worker_executing_work - find worker which is executing a work
832 * @gcwq: gcwq of interest
833 * @bwh: hash head as returned by busy_worker_head()
834 * @work: work to find worker for
836 * Find a worker which is executing @work on @gcwq. @bwh should be
837 * the hash head obtained by calling busy_worker_head() with the same
841 * spin_lock_irq(gcwq->lock).
844 * Pointer to worker which is executing @work if found, NULL
847 static struct worker *__find_worker_executing_work(struct global_cwq *gcwq,
848 struct hlist_head *bwh,
849 struct work_struct *work)
851 struct worker *worker;
852 struct hlist_node *tmp;
854 hlist_for_each_entry(worker, tmp, bwh, hentry)
855 if (worker->current_work == work)
861 * find_worker_executing_work - find worker which is executing a work
862 * @gcwq: gcwq of interest
863 * @work: work to find worker for
865 * Find a worker which is executing @work on @gcwq. This function is
866 * identical to __find_worker_executing_work() except that this
867 * function calculates @bwh itself.
870 * spin_lock_irq(gcwq->lock).
873 * Pointer to worker which is executing @work if found, NULL
876 static struct worker *find_worker_executing_work(struct global_cwq *gcwq,
877 struct work_struct *work)
879 return __find_worker_executing_work(gcwq, busy_worker_head(gcwq, work),
884 * pool_determine_ins_pos - find insertion position
885 * @pool: pool of interest
886 * @cwq: cwq a work is being queued for
888 * A work for @cwq is about to be queued on @pool, determine insertion
889 * position for the work. If @cwq is for HIGHPRI wq, the work is
890 * queued at the head of the queue but in FIFO order with respect to
891 * other HIGHPRI works; otherwise, at the end of the queue. This
892 * function also sets GCWQ_HIGHPRI_PENDING flag to hint @pool that
893 * there are HIGHPRI works pending.
896 * spin_lock_irq(gcwq->lock).
899 * Pointer to inserstion position.
901 static inline struct list_head *pool_determine_ins_pos(struct worker_pool *pool,
902 struct cpu_workqueue_struct *cwq)
904 struct work_struct *twork;
906 if (likely(!(cwq->wq->flags & WQ_HIGHPRI)))
907 return &pool->worklist;
909 list_for_each_entry(twork, &pool->worklist, entry) {
910 struct cpu_workqueue_struct *tcwq = get_work_cwq(twork);
912 if (!(tcwq->wq->flags & WQ_HIGHPRI))
916 pool->gcwq->flags |= GCWQ_HIGHPRI_PENDING;
917 return &twork->entry;
921 * insert_work - insert a work into gcwq
922 * @cwq: cwq @work belongs to
923 * @work: work to insert
924 * @head: insertion point
925 * @extra_flags: extra WORK_STRUCT_* flags to set
927 * Insert @work which belongs to @cwq into @gcwq after @head.
928 * @extra_flags is or'd to work_struct flags.
931 * spin_lock_irq(gcwq->lock).
933 static void insert_work(struct cpu_workqueue_struct *cwq,
934 struct work_struct *work, struct list_head *head,
935 unsigned int extra_flags)
937 struct worker_pool *pool = cwq->pool;
939 /* we own @work, set data and link */
940 set_work_cwq(work, cwq, extra_flags);
943 * Ensure that we get the right work->data if we see the
944 * result of list_add() below, see try_to_grab_pending().
948 list_add_tail(&work->entry, head);
951 * Ensure either worker_sched_deactivated() sees the above
952 * list_add_tail() or we see zero nr_running to avoid workers
953 * lying around lazily while there are works to be processed.
957 if (__need_more_worker(pool))
958 wake_up_worker(pool);
962 * Test whether @work is being queued from another work executing on the
963 * same workqueue. This is rather expensive and should only be used from
966 static bool is_chained_work(struct workqueue_struct *wq)
971 for_each_gcwq_cpu(cpu) {
972 struct global_cwq *gcwq = get_gcwq(cpu);
973 struct worker *worker;
974 struct hlist_node *pos;
977 spin_lock_irqsave(&gcwq->lock, flags);
978 for_each_busy_worker(worker, i, pos, gcwq) {
979 if (worker->task != current)
981 spin_unlock_irqrestore(&gcwq->lock, flags);
983 * I'm @worker, no locking necessary. See if @work
984 * is headed to the same workqueue.
986 return worker->current_cwq->wq == wq;
988 spin_unlock_irqrestore(&gcwq->lock, flags);
993 static void __queue_work(unsigned int cpu, struct workqueue_struct *wq,
994 struct work_struct *work)
996 struct global_cwq *gcwq;
997 struct cpu_workqueue_struct *cwq;
998 struct list_head *worklist;
999 unsigned int work_flags;
1000 unsigned long flags;
1002 debug_work_activate(work);
1004 /* if dying, only works from the same workqueue are allowed */
1005 if (unlikely(wq->flags & WQ_DRAINING) &&
1006 WARN_ON_ONCE(!is_chained_work(wq)))
1009 /* determine gcwq to use */
1010 if (!(wq->flags & WQ_UNBOUND)) {
1011 struct global_cwq *last_gcwq;
1013 if (unlikely(cpu == WORK_CPU_UNBOUND))
1014 cpu = raw_smp_processor_id();
1017 * It's multi cpu. If @wq is non-reentrant and @work
1018 * was previously on a different cpu, it might still
1019 * be running there, in which case the work needs to
1020 * be queued on that cpu to guarantee non-reentrance.
1022 gcwq = get_gcwq(cpu);
1023 if (wq->flags & WQ_NON_REENTRANT &&
1024 (last_gcwq = get_work_gcwq(work)) && last_gcwq != gcwq) {
1025 struct worker *worker;
1027 spin_lock_irqsave(&last_gcwq->lock, flags);
1029 worker = find_worker_executing_work(last_gcwq, work);
1031 if (worker && worker->current_cwq->wq == wq)
1034 /* meh... not running there, queue here */
1035 spin_unlock_irqrestore(&last_gcwq->lock, flags);
1036 spin_lock_irqsave(&gcwq->lock, flags);
1039 spin_lock_irqsave(&gcwq->lock, flags);
1041 gcwq = get_gcwq(WORK_CPU_UNBOUND);
1042 spin_lock_irqsave(&gcwq->lock, flags);
1045 /* gcwq determined, get cwq and queue */
1046 cwq = get_cwq(gcwq->cpu, wq);
1047 trace_workqueue_queue_work(cpu, cwq, work);
1049 if (WARN_ON(!list_empty(&work->entry))) {
1050 spin_unlock_irqrestore(&gcwq->lock, flags);
1054 cwq->nr_in_flight[cwq->work_color]++;
1055 work_flags = work_color_to_flags(cwq->work_color);
1057 if (likely(cwq->nr_active < cwq->max_active)) {
1058 trace_workqueue_activate_work(work);
1060 worklist = pool_determine_ins_pos(cwq->pool, cwq);
1062 work_flags |= WORK_STRUCT_DELAYED;
1063 worklist = &cwq->delayed_works;
1066 insert_work(cwq, work, worklist, work_flags);
1068 spin_unlock_irqrestore(&gcwq->lock, flags);
1072 * queue_work - queue work on a workqueue
1073 * @wq: workqueue to use
1074 * @work: work to queue
1076 * Returns 0 if @work was already on a queue, non-zero otherwise.
1078 * We queue the work to the CPU on which it was submitted, but if the CPU dies
1079 * it can be processed by another CPU.
1081 int queue_work(struct workqueue_struct *wq, struct work_struct *work)
1085 ret = queue_work_on(get_cpu(), wq, work);
1090 EXPORT_SYMBOL_GPL(queue_work);
1093 * queue_work_on - queue work on specific cpu
1094 * @cpu: CPU number to execute work on
1095 * @wq: workqueue to use
1096 * @work: work to queue
1098 * Returns 0 if @work was already on a queue, non-zero otherwise.
1100 * We queue the work to a specific CPU, the caller must ensure it
1104 queue_work_on(int cpu, struct workqueue_struct *wq, struct work_struct *work)
1108 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1109 __queue_work(cpu, wq, work);
1114 EXPORT_SYMBOL_GPL(queue_work_on);
1116 static void delayed_work_timer_fn(unsigned long __data)
1118 struct delayed_work *dwork = (struct delayed_work *)__data;
1119 struct cpu_workqueue_struct *cwq = get_work_cwq(&dwork->work);
1121 __queue_work(smp_processor_id(), cwq->wq, &dwork->work);
1125 * queue_delayed_work - queue work on a workqueue after delay
1126 * @wq: workqueue to use
1127 * @dwork: delayable 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(struct workqueue_struct *wq,
1133 struct delayed_work *dwork, unsigned long delay)
1136 return queue_work(wq, &dwork->work);
1138 return queue_delayed_work_on(-1, wq, dwork, delay);
1140 EXPORT_SYMBOL_GPL(queue_delayed_work);
1143 * queue_delayed_work_on - queue work on specific CPU after delay
1144 * @cpu: CPU number to execute work on
1145 * @wq: workqueue to use
1146 * @dwork: work to queue
1147 * @delay: number of jiffies to wait before queueing
1149 * Returns 0 if @work was already on a queue, non-zero otherwise.
1151 int queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1152 struct delayed_work *dwork, unsigned long delay)
1155 struct timer_list *timer = &dwork->timer;
1156 struct work_struct *work = &dwork->work;
1158 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1161 BUG_ON(timer_pending(timer));
1162 BUG_ON(!list_empty(&work->entry));
1164 timer_stats_timer_set_start_info(&dwork->timer);
1167 * This stores cwq for the moment, for the timer_fn.
1168 * Note that the work's gcwq is preserved to allow
1169 * reentrance detection for delayed works.
1171 if (!(wq->flags & WQ_UNBOUND)) {
1172 struct global_cwq *gcwq = get_work_gcwq(work);
1174 if (gcwq && gcwq->cpu != WORK_CPU_UNBOUND)
1177 lcpu = raw_smp_processor_id();
1179 lcpu = WORK_CPU_UNBOUND;
1181 set_work_cwq(work, get_cwq(lcpu, wq), 0);
1183 timer->expires = jiffies + delay;
1184 timer->data = (unsigned long)dwork;
1185 timer->function = delayed_work_timer_fn;
1187 if (unlikely(cpu >= 0))
1188 add_timer_on(timer, cpu);
1195 EXPORT_SYMBOL_GPL(queue_delayed_work_on);
1198 * worker_enter_idle - enter idle state
1199 * @worker: worker which is entering idle state
1201 * @worker is entering idle state. Update stats and idle timer if
1205 * spin_lock_irq(gcwq->lock).
1207 static void worker_enter_idle(struct worker *worker)
1209 struct worker_pool *pool = worker->pool;
1210 struct global_cwq *gcwq = pool->gcwq;
1212 BUG_ON(worker->flags & WORKER_IDLE);
1213 BUG_ON(!list_empty(&worker->entry) &&
1214 (worker->hentry.next || worker->hentry.pprev));
1216 /* can't use worker_set_flags(), also called from start_worker() */
1217 worker->flags |= WORKER_IDLE;
1219 worker->last_active = jiffies;
1221 /* idle_list is LIFO */
1222 list_add(&worker->entry, &pool->idle_list);
1224 if (likely(!(worker->flags & WORKER_ROGUE))) {
1225 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1226 mod_timer(&pool->idle_timer,
1227 jiffies + IDLE_WORKER_TIMEOUT);
1229 wake_up_all(&gcwq->trustee_wait);
1232 * Sanity check nr_running. Because trustee releases gcwq->lock
1233 * between setting %WORKER_ROGUE and zapping nr_running, the
1234 * warning may trigger spuriously. Check iff trustee is idle.
1236 WARN_ON_ONCE(gcwq->trustee_state == TRUSTEE_DONE &&
1237 pool->nr_workers == pool->nr_idle &&
1238 atomic_read(get_pool_nr_running(pool)));
1242 * worker_leave_idle - leave idle state
1243 * @worker: worker which is leaving idle state
1245 * @worker is leaving idle state. Update stats.
1248 * spin_lock_irq(gcwq->lock).
1250 static void worker_leave_idle(struct worker *worker)
1252 struct worker_pool *pool = worker->pool;
1254 BUG_ON(!(worker->flags & WORKER_IDLE));
1255 worker_clr_flags(worker, WORKER_IDLE);
1257 list_del_init(&worker->entry);
1261 * worker_maybe_bind_and_lock - bind worker to its cpu if possible and lock gcwq
1264 * Works which are scheduled while the cpu is online must at least be
1265 * scheduled to a worker which is bound to the cpu so that if they are
1266 * flushed from cpu callbacks while cpu is going down, they are
1267 * guaranteed to execute on the cpu.
1269 * This function is to be used by rogue workers and rescuers to bind
1270 * themselves to the target cpu and may race with cpu going down or
1271 * coming online. kthread_bind() can't be used because it may put the
1272 * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1273 * verbatim as it's best effort and blocking and gcwq may be
1274 * [dis]associated in the meantime.
1276 * This function tries set_cpus_allowed() and locks gcwq and verifies
1277 * the binding against GCWQ_DISASSOCIATED which is set during
1278 * CPU_DYING and cleared during CPU_ONLINE, so if the worker enters
1279 * idle state or fetches works without dropping lock, it can guarantee
1280 * the scheduling requirement described in the first paragraph.
1283 * Might sleep. Called without any lock but returns with gcwq->lock
1287 * %true if the associated gcwq is online (@worker is successfully
1288 * bound), %false if offline.
1290 static bool worker_maybe_bind_and_lock(struct worker *worker)
1291 __acquires(&gcwq->lock)
1293 struct global_cwq *gcwq = worker->pool->gcwq;
1294 struct task_struct *task = worker->task;
1298 * The following call may fail, succeed or succeed
1299 * without actually migrating the task to the cpu if
1300 * it races with cpu hotunplug operation. Verify
1301 * against GCWQ_DISASSOCIATED.
1303 if (!(gcwq->flags & GCWQ_DISASSOCIATED))
1304 set_cpus_allowed_ptr(task, get_cpu_mask(gcwq->cpu));
1306 spin_lock_irq(&gcwq->lock);
1307 if (gcwq->flags & GCWQ_DISASSOCIATED)
1309 if (task_cpu(task) == gcwq->cpu &&
1310 cpumask_equal(¤t->cpus_allowed,
1311 get_cpu_mask(gcwq->cpu)))
1313 spin_unlock_irq(&gcwq->lock);
1316 * We've raced with CPU hot[un]plug. Give it a breather
1317 * and retry migration. cond_resched() is required here;
1318 * otherwise, we might deadlock against cpu_stop trying to
1319 * bring down the CPU on non-preemptive kernel.
1327 * Function for worker->rebind_work used to rebind rogue busy workers
1328 * to the associated cpu which is coming back online. This is
1329 * scheduled by cpu up but can race with other cpu hotplug operations
1330 * and may be executed twice without intervening cpu down.
1332 static void worker_rebind_fn(struct work_struct *work)
1334 struct worker *worker = container_of(work, struct worker, rebind_work);
1335 struct global_cwq *gcwq = worker->pool->gcwq;
1337 if (worker_maybe_bind_and_lock(worker))
1338 worker_clr_flags(worker, WORKER_REBIND);
1340 spin_unlock_irq(&gcwq->lock);
1343 static struct worker *alloc_worker(void)
1345 struct worker *worker;
1347 worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1349 INIT_LIST_HEAD(&worker->entry);
1350 INIT_LIST_HEAD(&worker->scheduled);
1351 INIT_WORK(&worker->rebind_work, worker_rebind_fn);
1352 /* on creation a worker is in !idle && prep state */
1353 worker->flags = WORKER_PREP;
1359 * create_worker - create a new workqueue worker
1360 * @pool: pool the new worker will belong to
1361 * @bind: whether to set affinity to @cpu or not
1363 * Create a new worker which is bound to @pool. The returned worker
1364 * can be started by calling start_worker() or destroyed using
1368 * Might sleep. Does GFP_KERNEL allocations.
1371 * Pointer to the newly created worker.
1373 static struct worker *create_worker(struct worker_pool *pool, bool bind)
1375 struct global_cwq *gcwq = pool->gcwq;
1376 bool on_unbound_cpu = gcwq->cpu == WORK_CPU_UNBOUND;
1377 struct worker *worker = NULL;
1380 spin_lock_irq(&gcwq->lock);
1381 while (ida_get_new(&pool->worker_ida, &id)) {
1382 spin_unlock_irq(&gcwq->lock);
1383 if (!ida_pre_get(&pool->worker_ida, GFP_KERNEL))
1385 spin_lock_irq(&gcwq->lock);
1387 spin_unlock_irq(&gcwq->lock);
1389 worker = alloc_worker();
1393 worker->pool = pool;
1396 if (!on_unbound_cpu)
1397 worker->task = kthread_create_on_node(worker_thread,
1399 cpu_to_node(gcwq->cpu),
1400 "kworker/%u:%d", gcwq->cpu, id);
1402 worker->task = kthread_create(worker_thread, worker,
1403 "kworker/u:%d", id);
1404 if (IS_ERR(worker->task))
1408 * A rogue worker will become a regular one if CPU comes
1409 * online later on. Make sure every worker has
1410 * PF_THREAD_BOUND set.
1412 if (bind && !on_unbound_cpu)
1413 kthread_bind(worker->task, gcwq->cpu);
1415 worker->task->flags |= PF_THREAD_BOUND;
1417 worker->flags |= WORKER_UNBOUND;
1423 spin_lock_irq(&gcwq->lock);
1424 ida_remove(&pool->worker_ida, id);
1425 spin_unlock_irq(&gcwq->lock);
1432 * start_worker - start a newly created worker
1433 * @worker: worker to start
1435 * Make the gcwq aware of @worker and start it.
1438 * spin_lock_irq(gcwq->lock).
1440 static void start_worker(struct worker *worker)
1442 worker->flags |= WORKER_STARTED;
1443 worker->pool->nr_workers++;
1444 worker_enter_idle(worker);
1445 wake_up_process(worker->task);
1449 * destroy_worker - destroy a workqueue worker
1450 * @worker: worker to be destroyed
1452 * Destroy @worker and adjust @gcwq stats accordingly.
1455 * spin_lock_irq(gcwq->lock) which is released and regrabbed.
1457 static void destroy_worker(struct worker *worker)
1459 struct worker_pool *pool = worker->pool;
1460 struct global_cwq *gcwq = pool->gcwq;
1461 int id = worker->id;
1463 /* sanity check frenzy */
1464 BUG_ON(worker->current_work);
1465 BUG_ON(!list_empty(&worker->scheduled));
1467 if (worker->flags & WORKER_STARTED)
1469 if (worker->flags & WORKER_IDLE)
1472 list_del_init(&worker->entry);
1473 worker->flags |= WORKER_DIE;
1475 spin_unlock_irq(&gcwq->lock);
1477 kthread_stop(worker->task);
1480 spin_lock_irq(&gcwq->lock);
1481 ida_remove(&pool->worker_ida, id);
1484 static void idle_worker_timeout(unsigned long __pool)
1486 struct worker_pool *pool = (void *)__pool;
1487 struct global_cwq *gcwq = pool->gcwq;
1489 spin_lock_irq(&gcwq->lock);
1491 if (too_many_workers(pool)) {
1492 struct worker *worker;
1493 unsigned long expires;
1495 /* idle_list is kept in LIFO order, check the last one */
1496 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1497 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1499 if (time_before(jiffies, expires))
1500 mod_timer(&pool->idle_timer, expires);
1502 /* it's been idle for too long, wake up manager */
1503 gcwq->flags |= GCWQ_MANAGE_WORKERS;
1504 wake_up_worker(pool);
1508 spin_unlock_irq(&gcwq->lock);
1511 static bool send_mayday(struct work_struct *work)
1513 struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1514 struct workqueue_struct *wq = cwq->wq;
1517 if (!(wq->flags & WQ_RESCUER))
1520 /* mayday mayday mayday */
1521 cpu = cwq->pool->gcwq->cpu;
1522 /* WORK_CPU_UNBOUND can't be set in cpumask, use cpu 0 instead */
1523 if (cpu == WORK_CPU_UNBOUND)
1525 if (!mayday_test_and_set_cpu(cpu, wq->mayday_mask))
1526 wake_up_process(wq->rescuer->task);
1530 static void gcwq_mayday_timeout(unsigned long __pool)
1532 struct worker_pool *pool = (void *)__pool;
1533 struct global_cwq *gcwq = pool->gcwq;
1534 struct work_struct *work;
1536 spin_lock_irq(&gcwq->lock);
1538 if (need_to_create_worker(pool)) {
1540 * We've been trying to create a new worker but
1541 * haven't been successful. We might be hitting an
1542 * allocation deadlock. Send distress signals to
1545 list_for_each_entry(work, &pool->worklist, entry)
1549 spin_unlock_irq(&gcwq->lock);
1551 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1555 * maybe_create_worker - create a new worker if necessary
1556 * @pool: pool to create a new worker for
1558 * Create a new worker for @pool if necessary. @pool is guaranteed to
1559 * have at least one idle worker on return from this function. If
1560 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1561 * sent to all rescuers with works scheduled on @pool to resolve
1562 * possible allocation deadlock.
1564 * On return, need_to_create_worker() is guaranteed to be false and
1565 * may_start_working() true.
1568 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1569 * multiple times. Does GFP_KERNEL allocations. Called only from
1573 * false if no action was taken and gcwq->lock stayed locked, true
1576 static bool maybe_create_worker(struct worker_pool *pool)
1577 __releases(&gcwq->lock)
1578 __acquires(&gcwq->lock)
1580 struct global_cwq *gcwq = pool->gcwq;
1582 if (!need_to_create_worker(pool))
1585 spin_unlock_irq(&gcwq->lock);
1587 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1588 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1591 struct worker *worker;
1593 worker = create_worker(pool, true);
1595 del_timer_sync(&pool->mayday_timer);
1596 spin_lock_irq(&gcwq->lock);
1597 start_worker(worker);
1598 BUG_ON(need_to_create_worker(pool));
1602 if (!need_to_create_worker(pool))
1605 __set_current_state(TASK_INTERRUPTIBLE);
1606 schedule_timeout(CREATE_COOLDOWN);
1608 if (!need_to_create_worker(pool))
1612 del_timer_sync(&pool->mayday_timer);
1613 spin_lock_irq(&gcwq->lock);
1614 if (need_to_create_worker(pool))
1620 * maybe_destroy_worker - destroy workers which have been idle for a while
1621 * @pool: pool to destroy workers for
1623 * Destroy @pool workers which have been idle for longer than
1624 * IDLE_WORKER_TIMEOUT.
1627 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1628 * multiple times. Called only from manager.
1631 * false if no action was taken and gcwq->lock stayed locked, true
1634 static bool maybe_destroy_workers(struct worker_pool *pool)
1638 while (too_many_workers(pool)) {
1639 struct worker *worker;
1640 unsigned long expires;
1642 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1643 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1645 if (time_before(jiffies, expires)) {
1646 mod_timer(&pool->idle_timer, expires);
1650 destroy_worker(worker);
1658 * manage_workers - manage worker pool
1661 * Assume the manager role and manage gcwq worker pool @worker belongs
1662 * to. At any given time, there can be only zero or one manager per
1663 * gcwq. The exclusion is handled automatically by this function.
1665 * The caller can safely start processing works on false return. On
1666 * true return, it's guaranteed that need_to_create_worker() is false
1667 * and may_start_working() is true.
1670 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1671 * multiple times. Does GFP_KERNEL allocations.
1674 * false if no action was taken and gcwq->lock stayed locked, true if
1675 * some action was taken.
1677 static bool manage_workers(struct worker *worker)
1679 struct worker_pool *pool = worker->pool;
1680 struct global_cwq *gcwq = pool->gcwq;
1683 if (gcwq->flags & GCWQ_MANAGING_WORKERS)
1686 gcwq->flags &= ~GCWQ_MANAGE_WORKERS;
1687 gcwq->flags |= GCWQ_MANAGING_WORKERS;
1690 * Destroy and then create so that may_start_working() is true
1693 ret |= maybe_destroy_workers(pool);
1694 ret |= maybe_create_worker(pool);
1696 gcwq->flags &= ~GCWQ_MANAGING_WORKERS;
1699 * The trustee might be waiting to take over the manager
1700 * position, tell it we're done.
1702 if (unlikely(gcwq->trustee))
1703 wake_up_all(&gcwq->trustee_wait);
1709 * move_linked_works - move linked works to a list
1710 * @work: start of series of works to be scheduled
1711 * @head: target list to append @work to
1712 * @nextp: out paramter for nested worklist walking
1714 * Schedule linked works starting from @work to @head. Work series to
1715 * be scheduled starts at @work and includes any consecutive work with
1716 * WORK_STRUCT_LINKED set in its predecessor.
1718 * If @nextp is not NULL, it's updated to point to the next work of
1719 * the last scheduled work. This allows move_linked_works() to be
1720 * nested inside outer list_for_each_entry_safe().
1723 * spin_lock_irq(gcwq->lock).
1725 static void move_linked_works(struct work_struct *work, struct list_head *head,
1726 struct work_struct **nextp)
1728 struct work_struct *n;
1731 * Linked worklist will always end before the end of the list,
1732 * use NULL for list head.
1734 list_for_each_entry_safe_from(work, n, NULL, entry) {
1735 list_move_tail(&work->entry, head);
1736 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1741 * If we're already inside safe list traversal and have moved
1742 * multiple works to the scheduled queue, the next position
1743 * needs to be updated.
1749 static void cwq_activate_first_delayed(struct cpu_workqueue_struct *cwq)
1751 struct work_struct *work = list_first_entry(&cwq->delayed_works,
1752 struct work_struct, entry);
1753 struct list_head *pos = pool_determine_ins_pos(cwq->pool, cwq);
1755 trace_workqueue_activate_work(work);
1756 move_linked_works(work, pos, NULL);
1757 __clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
1762 * cwq_dec_nr_in_flight - decrement cwq's nr_in_flight
1763 * @cwq: cwq of interest
1764 * @color: color of work which left the queue
1765 * @delayed: for a delayed work
1767 * A work either has completed or is removed from pending queue,
1768 * decrement nr_in_flight of its cwq and handle workqueue flushing.
1771 * spin_lock_irq(gcwq->lock).
1773 static void cwq_dec_nr_in_flight(struct cpu_workqueue_struct *cwq, int color,
1776 /* ignore uncolored works */
1777 if (color == WORK_NO_COLOR)
1780 cwq->nr_in_flight[color]--;
1784 if (!list_empty(&cwq->delayed_works)) {
1785 /* one down, submit a delayed one */
1786 if (cwq->nr_active < cwq->max_active)
1787 cwq_activate_first_delayed(cwq);
1791 /* is flush in progress and are we at the flushing tip? */
1792 if (likely(cwq->flush_color != color))
1795 /* are there still in-flight works? */
1796 if (cwq->nr_in_flight[color])
1799 /* this cwq is done, clear flush_color */
1800 cwq->flush_color = -1;
1803 * If this was the last cwq, wake up the first flusher. It
1804 * will handle the rest.
1806 if (atomic_dec_and_test(&cwq->wq->nr_cwqs_to_flush))
1807 complete(&cwq->wq->first_flusher->done);
1811 * process_one_work - process single work
1813 * @work: work to process
1815 * Process @work. This function contains all the logics necessary to
1816 * process a single work including synchronization against and
1817 * interaction with other workers on the same cpu, queueing and
1818 * flushing. As long as context requirement is met, any worker can
1819 * call this function to process a work.
1822 * spin_lock_irq(gcwq->lock) which is released and regrabbed.
1824 static void process_one_work(struct worker *worker, struct work_struct *work)
1825 __releases(&gcwq->lock)
1826 __acquires(&gcwq->lock)
1828 struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1829 struct worker_pool *pool = worker->pool;
1830 struct global_cwq *gcwq = pool->gcwq;
1831 struct hlist_head *bwh = busy_worker_head(gcwq, work);
1832 bool cpu_intensive = cwq->wq->flags & WQ_CPU_INTENSIVE;
1833 work_func_t f = work->func;
1835 struct worker *collision;
1836 #ifdef CONFIG_LOCKDEP
1838 * It is permissible to free the struct work_struct from
1839 * inside the function that is called from it, this we need to
1840 * take into account for lockdep too. To avoid bogus "held
1841 * lock freed" warnings as well as problems when looking into
1842 * work->lockdep_map, make a copy and use that here.
1844 struct lockdep_map lockdep_map;
1846 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
1849 * A single work shouldn't be executed concurrently by
1850 * multiple workers on a single cpu. Check whether anyone is
1851 * already processing the work. If so, defer the work to the
1852 * currently executing one.
1854 collision = __find_worker_executing_work(gcwq, bwh, work);
1855 if (unlikely(collision)) {
1856 move_linked_works(work, &collision->scheduled, NULL);
1860 /* claim and process */
1861 debug_work_deactivate(work);
1862 hlist_add_head(&worker->hentry, bwh);
1863 worker->current_work = work;
1864 worker->current_cwq = cwq;
1865 work_color = get_work_color(work);
1867 /* record the current cpu number in the work data and dequeue */
1868 set_work_cpu(work, gcwq->cpu);
1869 list_del_init(&work->entry);
1872 * If HIGHPRI_PENDING, check the next work, and, if HIGHPRI,
1873 * wake up another worker; otherwise, clear HIGHPRI_PENDING.
1875 if (unlikely(gcwq->flags & GCWQ_HIGHPRI_PENDING)) {
1876 struct work_struct *nwork = list_first_entry(&pool->worklist,
1877 struct work_struct, entry);
1879 if (!list_empty(&pool->worklist) &&
1880 get_work_cwq(nwork)->wq->flags & WQ_HIGHPRI)
1881 wake_up_worker(pool);
1883 gcwq->flags &= ~GCWQ_HIGHPRI_PENDING;
1887 * CPU intensive works don't participate in concurrency
1888 * management. They're the scheduler's responsibility.
1890 if (unlikely(cpu_intensive))
1891 worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
1894 * Unbound gcwq isn't concurrency managed and work items should be
1895 * executed ASAP. Wake up another worker if necessary.
1897 if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
1898 wake_up_worker(pool);
1900 spin_unlock_irq(&gcwq->lock);
1902 work_clear_pending(work);
1903 lock_map_acquire_read(&cwq->wq->lockdep_map);
1904 lock_map_acquire(&lockdep_map);
1905 trace_workqueue_execute_start(work);
1908 * While we must be careful to not use "work" after this, the trace
1909 * point will only record its address.
1911 trace_workqueue_execute_end(work);
1912 lock_map_release(&lockdep_map);
1913 lock_map_release(&cwq->wq->lockdep_map);
1915 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
1916 printk(KERN_ERR "BUG: workqueue leaked lock or atomic: "
1918 current->comm, preempt_count(), task_pid_nr(current));
1919 printk(KERN_ERR " last function: ");
1920 print_symbol("%s\n", (unsigned long)f);
1921 debug_show_held_locks(current);
1925 spin_lock_irq(&gcwq->lock);
1927 /* clear cpu intensive status */
1928 if (unlikely(cpu_intensive))
1929 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
1931 /* we're done with it, release */
1932 hlist_del_init(&worker->hentry);
1933 worker->current_work = NULL;
1934 worker->current_cwq = NULL;
1935 cwq_dec_nr_in_flight(cwq, work_color, false);
1939 * process_scheduled_works - process scheduled works
1942 * Process all scheduled works. Please note that the scheduled list
1943 * may change while processing a work, so this function repeatedly
1944 * fetches a work from the top and executes it.
1947 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1950 static void process_scheduled_works(struct worker *worker)
1952 while (!list_empty(&worker->scheduled)) {
1953 struct work_struct *work = list_first_entry(&worker->scheduled,
1954 struct work_struct, entry);
1955 process_one_work(worker, work);
1960 * worker_thread - the worker thread function
1963 * The gcwq worker thread function. There's a single dynamic pool of
1964 * these per each cpu. These workers process all works regardless of
1965 * their specific target workqueue. The only exception is works which
1966 * belong to workqueues with a rescuer which will be explained in
1969 static int worker_thread(void *__worker)
1971 struct worker *worker = __worker;
1972 struct worker_pool *pool = worker->pool;
1973 struct global_cwq *gcwq = pool->gcwq;
1975 /* tell the scheduler that this is a workqueue worker */
1976 worker->task->flags |= PF_WQ_WORKER;
1978 spin_lock_irq(&gcwq->lock);
1980 /* DIE can be set only while we're idle, checking here is enough */
1981 if (worker->flags & WORKER_DIE) {
1982 spin_unlock_irq(&gcwq->lock);
1983 worker->task->flags &= ~PF_WQ_WORKER;
1987 worker_leave_idle(worker);
1989 /* no more worker necessary? */
1990 if (!need_more_worker(pool))
1993 /* do we need to manage? */
1994 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
1998 * ->scheduled list can only be filled while a worker is
1999 * preparing to process a work or actually processing it.
2000 * Make sure nobody diddled with it while I was sleeping.
2002 BUG_ON(!list_empty(&worker->scheduled));
2005 * When control reaches this point, we're guaranteed to have
2006 * at least one idle worker or that someone else has already
2007 * assumed the manager role.
2009 worker_clr_flags(worker, WORKER_PREP);
2012 struct work_struct *work =
2013 list_first_entry(&pool->worklist,
2014 struct work_struct, entry);
2016 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2017 /* optimization path, not strictly necessary */
2018 process_one_work(worker, work);
2019 if (unlikely(!list_empty(&worker->scheduled)))
2020 process_scheduled_works(worker);
2022 move_linked_works(work, &worker->scheduled, NULL);
2023 process_scheduled_works(worker);
2025 } while (keep_working(pool));
2027 worker_set_flags(worker, WORKER_PREP, false);
2029 if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
2033 * gcwq->lock is held and there's no work to process and no
2034 * need to manage, sleep. Workers are woken up only while
2035 * holding gcwq->lock or from local cpu, so setting the
2036 * current state before releasing gcwq->lock is enough to
2037 * prevent losing any event.
2039 worker_enter_idle(worker);
2040 __set_current_state(TASK_INTERRUPTIBLE);
2041 spin_unlock_irq(&gcwq->lock);
2047 * rescuer_thread - the rescuer thread function
2048 * @__wq: the associated workqueue
2050 * Workqueue rescuer thread function. There's one rescuer for each
2051 * workqueue which has WQ_RESCUER set.
2053 * Regular work processing on a gcwq may block trying to create a new
2054 * worker which uses GFP_KERNEL allocation which has slight chance of
2055 * developing into deadlock if some works currently on the same queue
2056 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2057 * the problem rescuer solves.
2059 * When such condition is possible, the gcwq summons rescuers of all
2060 * workqueues which have works queued on the gcwq and let them process
2061 * those works so that forward progress can be guaranteed.
2063 * This should happen rarely.
2065 static int rescuer_thread(void *__wq)
2067 struct workqueue_struct *wq = __wq;
2068 struct worker *rescuer = wq->rescuer;
2069 struct list_head *scheduled = &rescuer->scheduled;
2070 bool is_unbound = wq->flags & WQ_UNBOUND;
2073 set_user_nice(current, RESCUER_NICE_LEVEL);
2075 set_current_state(TASK_INTERRUPTIBLE);
2077 if (kthread_should_stop())
2081 * See whether any cpu is asking for help. Unbounded
2082 * workqueues use cpu 0 in mayday_mask for CPU_UNBOUND.
2084 for_each_mayday_cpu(cpu, wq->mayday_mask) {
2085 unsigned int tcpu = is_unbound ? WORK_CPU_UNBOUND : cpu;
2086 struct cpu_workqueue_struct *cwq = get_cwq(tcpu, wq);
2087 struct worker_pool *pool = cwq->pool;
2088 struct global_cwq *gcwq = pool->gcwq;
2089 struct work_struct *work, *n;
2091 __set_current_state(TASK_RUNNING);
2092 mayday_clear_cpu(cpu, wq->mayday_mask);
2094 /* migrate to the target cpu if possible */
2095 rescuer->pool = pool;
2096 worker_maybe_bind_and_lock(rescuer);
2099 * Slurp in all works issued via this workqueue and
2102 BUG_ON(!list_empty(&rescuer->scheduled));
2103 list_for_each_entry_safe(work, n, &pool->worklist, entry)
2104 if (get_work_cwq(work) == cwq)
2105 move_linked_works(work, scheduled, &n);
2107 process_scheduled_works(rescuer);
2110 * Leave this gcwq. If keep_working() is %true, notify a
2111 * regular worker; otherwise, we end up with 0 concurrency
2112 * and stalling the execution.
2114 if (keep_working(pool))
2115 wake_up_worker(pool);
2117 spin_unlock_irq(&gcwq->lock);
2125 struct work_struct work;
2126 struct completion done;
2129 static void wq_barrier_func(struct work_struct *work)
2131 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2132 complete(&barr->done);
2136 * insert_wq_barrier - insert a barrier work
2137 * @cwq: cwq to insert barrier into
2138 * @barr: wq_barrier to insert
2139 * @target: target work to attach @barr to
2140 * @worker: worker currently executing @target, NULL if @target is not executing
2142 * @barr is linked to @target such that @barr is completed only after
2143 * @target finishes execution. Please note that the ordering
2144 * guarantee is observed only with respect to @target and on the local
2147 * Currently, a queued barrier can't be canceled. This is because
2148 * try_to_grab_pending() can't determine whether the work to be
2149 * grabbed is at the head of the queue and thus can't clear LINKED
2150 * flag of the previous work while there must be a valid next work
2151 * after a work with LINKED flag set.
2153 * Note that when @worker is non-NULL, @target may be modified
2154 * underneath us, so we can't reliably determine cwq from @target.
2157 * spin_lock_irq(gcwq->lock).
2159 static void insert_wq_barrier(struct cpu_workqueue_struct *cwq,
2160 struct wq_barrier *barr,
2161 struct work_struct *target, struct worker *worker)
2163 struct list_head *head;
2164 unsigned int linked = 0;
2167 * debugobject calls are safe here even with gcwq->lock locked
2168 * as we know for sure that this will not trigger any of the
2169 * checks and call back into the fixup functions where we
2172 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2173 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2174 init_completion(&barr->done);
2177 * If @target is currently being executed, schedule the
2178 * barrier to the worker; otherwise, put it after @target.
2181 head = worker->scheduled.next;
2183 unsigned long *bits = work_data_bits(target);
2185 head = target->entry.next;
2186 /* there can already be other linked works, inherit and set */
2187 linked = *bits & WORK_STRUCT_LINKED;
2188 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2191 debug_work_activate(&barr->work);
2192 insert_work(cwq, &barr->work, head,
2193 work_color_to_flags(WORK_NO_COLOR) | linked);
2197 * flush_workqueue_prep_cwqs - prepare cwqs for workqueue flushing
2198 * @wq: workqueue being flushed
2199 * @flush_color: new flush color, < 0 for no-op
2200 * @work_color: new work color, < 0 for no-op
2202 * Prepare cwqs for workqueue flushing.
2204 * If @flush_color is non-negative, flush_color on all cwqs should be
2205 * -1. If no cwq has in-flight commands at the specified color, all
2206 * cwq->flush_color's stay at -1 and %false is returned. If any cwq
2207 * has in flight commands, its cwq->flush_color is set to
2208 * @flush_color, @wq->nr_cwqs_to_flush is updated accordingly, cwq
2209 * wakeup logic is armed and %true is returned.
2211 * The caller should have initialized @wq->first_flusher prior to
2212 * calling this function with non-negative @flush_color. If
2213 * @flush_color is negative, no flush color update is done and %false
2216 * If @work_color is non-negative, all cwqs should have the same
2217 * work_color which is previous to @work_color and all will be
2218 * advanced to @work_color.
2221 * mutex_lock(wq->flush_mutex).
2224 * %true if @flush_color >= 0 and there's something to flush. %false
2227 static bool flush_workqueue_prep_cwqs(struct workqueue_struct *wq,
2228 int flush_color, int work_color)
2233 if (flush_color >= 0) {
2234 BUG_ON(atomic_read(&wq->nr_cwqs_to_flush));
2235 atomic_set(&wq->nr_cwqs_to_flush, 1);
2238 for_each_cwq_cpu(cpu, wq) {
2239 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2240 struct global_cwq *gcwq = cwq->pool->gcwq;
2242 spin_lock_irq(&gcwq->lock);
2244 if (flush_color >= 0) {
2245 BUG_ON(cwq->flush_color != -1);
2247 if (cwq->nr_in_flight[flush_color]) {
2248 cwq->flush_color = flush_color;
2249 atomic_inc(&wq->nr_cwqs_to_flush);
2254 if (work_color >= 0) {
2255 BUG_ON(work_color != work_next_color(cwq->work_color));
2256 cwq->work_color = work_color;
2259 spin_unlock_irq(&gcwq->lock);
2262 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_cwqs_to_flush))
2263 complete(&wq->first_flusher->done);
2269 * flush_workqueue - ensure that any scheduled work has run to completion.
2270 * @wq: workqueue to flush
2272 * Forces execution of the workqueue and blocks until its completion.
2273 * This is typically used in driver shutdown handlers.
2275 * We sleep until all works which were queued on entry have been handled,
2276 * but we are not livelocked by new incoming ones.
2278 void flush_workqueue(struct workqueue_struct *wq)
2280 struct wq_flusher this_flusher = {
2281 .list = LIST_HEAD_INIT(this_flusher.list),
2283 .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
2287 lock_map_acquire(&wq->lockdep_map);
2288 lock_map_release(&wq->lockdep_map);
2290 mutex_lock(&wq->flush_mutex);
2293 * Start-to-wait phase
2295 next_color = work_next_color(wq->work_color);
2297 if (next_color != wq->flush_color) {
2299 * Color space is not full. The current work_color
2300 * becomes our flush_color and work_color is advanced
2303 BUG_ON(!list_empty(&wq->flusher_overflow));
2304 this_flusher.flush_color = wq->work_color;
2305 wq->work_color = next_color;
2307 if (!wq->first_flusher) {
2308 /* no flush in progress, become the first flusher */
2309 BUG_ON(wq->flush_color != this_flusher.flush_color);
2311 wq->first_flusher = &this_flusher;
2313 if (!flush_workqueue_prep_cwqs(wq, wq->flush_color,
2315 /* nothing to flush, done */
2316 wq->flush_color = next_color;
2317 wq->first_flusher = NULL;
2322 BUG_ON(wq->flush_color == this_flusher.flush_color);
2323 list_add_tail(&this_flusher.list, &wq->flusher_queue);
2324 flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2328 * Oops, color space is full, wait on overflow queue.
2329 * The next flush completion will assign us
2330 * flush_color and transfer to flusher_queue.
2332 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2335 mutex_unlock(&wq->flush_mutex);
2337 wait_for_completion(&this_flusher.done);
2340 * Wake-up-and-cascade phase
2342 * First flushers are responsible for cascading flushes and
2343 * handling overflow. Non-first flushers can simply return.
2345 if (wq->first_flusher != &this_flusher)
2348 mutex_lock(&wq->flush_mutex);
2350 /* we might have raced, check again with mutex held */
2351 if (wq->first_flusher != &this_flusher)
2354 wq->first_flusher = NULL;
2356 BUG_ON(!list_empty(&this_flusher.list));
2357 BUG_ON(wq->flush_color != this_flusher.flush_color);
2360 struct wq_flusher *next, *tmp;
2362 /* complete all the flushers sharing the current flush color */
2363 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2364 if (next->flush_color != wq->flush_color)
2366 list_del_init(&next->list);
2367 complete(&next->done);
2370 BUG_ON(!list_empty(&wq->flusher_overflow) &&
2371 wq->flush_color != work_next_color(wq->work_color));
2373 /* this flush_color is finished, advance by one */
2374 wq->flush_color = work_next_color(wq->flush_color);
2376 /* one color has been freed, handle overflow queue */
2377 if (!list_empty(&wq->flusher_overflow)) {
2379 * Assign the same color to all overflowed
2380 * flushers, advance work_color and append to
2381 * flusher_queue. This is the start-to-wait
2382 * phase for these overflowed flushers.
2384 list_for_each_entry(tmp, &wq->flusher_overflow, list)
2385 tmp->flush_color = wq->work_color;
2387 wq->work_color = work_next_color(wq->work_color);
2389 list_splice_tail_init(&wq->flusher_overflow,
2390 &wq->flusher_queue);
2391 flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2394 if (list_empty(&wq->flusher_queue)) {
2395 BUG_ON(wq->flush_color != wq->work_color);
2400 * Need to flush more colors. Make the next flusher
2401 * the new first flusher and arm cwqs.
2403 BUG_ON(wq->flush_color == wq->work_color);
2404 BUG_ON(wq->flush_color != next->flush_color);
2406 list_del_init(&next->list);
2407 wq->first_flusher = next;
2409 if (flush_workqueue_prep_cwqs(wq, wq->flush_color, -1))
2413 * Meh... this color is already done, clear first
2414 * flusher and repeat cascading.
2416 wq->first_flusher = NULL;
2420 mutex_unlock(&wq->flush_mutex);
2422 EXPORT_SYMBOL_GPL(flush_workqueue);
2425 * drain_workqueue - drain a workqueue
2426 * @wq: workqueue to drain
2428 * Wait until the workqueue becomes empty. While draining is in progress,
2429 * only chain queueing is allowed. IOW, only currently pending or running
2430 * work items on @wq can queue further work items on it. @wq is flushed
2431 * repeatedly until it becomes empty. The number of flushing is detemined
2432 * by the depth of chaining and should be relatively short. Whine if it
2435 void drain_workqueue(struct workqueue_struct *wq)
2437 unsigned int flush_cnt = 0;
2441 * __queue_work() needs to test whether there are drainers, is much
2442 * hotter than drain_workqueue() and already looks at @wq->flags.
2443 * Use WQ_DRAINING so that queue doesn't have to check nr_drainers.
2445 spin_lock(&workqueue_lock);
2446 if (!wq->nr_drainers++)
2447 wq->flags |= WQ_DRAINING;
2448 spin_unlock(&workqueue_lock);
2450 flush_workqueue(wq);
2452 for_each_cwq_cpu(cpu, wq) {
2453 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2456 spin_lock_irq(&cwq->pool->gcwq->lock);
2457 drained = !cwq->nr_active && list_empty(&cwq->delayed_works);
2458 spin_unlock_irq(&cwq->pool->gcwq->lock);
2463 if (++flush_cnt == 10 ||
2464 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2465 pr_warning("workqueue %s: flush on destruction isn't complete after %u tries\n",
2466 wq->name, flush_cnt);
2470 spin_lock(&workqueue_lock);
2471 if (!--wq->nr_drainers)
2472 wq->flags &= ~WQ_DRAINING;
2473 spin_unlock(&workqueue_lock);
2475 EXPORT_SYMBOL_GPL(drain_workqueue);
2477 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
2478 bool wait_executing)
2480 struct worker *worker = NULL;
2481 struct global_cwq *gcwq;
2482 struct cpu_workqueue_struct *cwq;
2485 gcwq = get_work_gcwq(work);
2489 spin_lock_irq(&gcwq->lock);
2490 if (!list_empty(&work->entry)) {
2492 * See the comment near try_to_grab_pending()->smp_rmb().
2493 * If it was re-queued to a different gcwq under us, we
2494 * are not going to wait.
2497 cwq = get_work_cwq(work);
2498 if (unlikely(!cwq || gcwq != cwq->pool->gcwq))
2500 } else if (wait_executing) {
2501 worker = find_worker_executing_work(gcwq, work);
2504 cwq = worker->current_cwq;
2508 insert_wq_barrier(cwq, barr, work, worker);
2509 spin_unlock_irq(&gcwq->lock);
2512 * If @max_active is 1 or rescuer is in use, flushing another work
2513 * item on the same workqueue may lead to deadlock. Make sure the
2514 * flusher is not running on the same workqueue by verifying write
2517 if (cwq->wq->saved_max_active == 1 || cwq->wq->flags & WQ_RESCUER)
2518 lock_map_acquire(&cwq->wq->lockdep_map);
2520 lock_map_acquire_read(&cwq->wq->lockdep_map);
2521 lock_map_release(&cwq->wq->lockdep_map);
2525 spin_unlock_irq(&gcwq->lock);
2530 * flush_work - wait for a work to finish executing the last queueing instance
2531 * @work: the work to flush
2533 * Wait until @work has finished execution. This function considers
2534 * only the last queueing instance of @work. If @work has been
2535 * enqueued across different CPUs on a non-reentrant workqueue or on
2536 * multiple workqueues, @work might still be executing on return on
2537 * some of the CPUs from earlier queueing.
2539 * If @work was queued only on a non-reentrant, ordered or unbound
2540 * workqueue, @work is guaranteed to be idle on return if it hasn't
2541 * been requeued since flush started.
2544 * %true if flush_work() waited for the work to finish execution,
2545 * %false if it was already idle.
2547 bool flush_work(struct work_struct *work)
2549 struct wq_barrier barr;
2551 lock_map_acquire(&work->lockdep_map);
2552 lock_map_release(&work->lockdep_map);
2554 if (start_flush_work(work, &barr, true)) {
2555 wait_for_completion(&barr.done);
2556 destroy_work_on_stack(&barr.work);
2561 EXPORT_SYMBOL_GPL(flush_work);
2563 static bool wait_on_cpu_work(struct global_cwq *gcwq, struct work_struct *work)
2565 struct wq_barrier barr;
2566 struct worker *worker;
2568 spin_lock_irq(&gcwq->lock);
2570 worker = find_worker_executing_work(gcwq, work);
2571 if (unlikely(worker))
2572 insert_wq_barrier(worker->current_cwq, &barr, work, worker);
2574 spin_unlock_irq(&gcwq->lock);
2576 if (unlikely(worker)) {
2577 wait_for_completion(&barr.done);
2578 destroy_work_on_stack(&barr.work);
2584 static bool wait_on_work(struct work_struct *work)
2591 lock_map_acquire(&work->lockdep_map);
2592 lock_map_release(&work->lockdep_map);
2594 for_each_gcwq_cpu(cpu)
2595 ret |= wait_on_cpu_work(get_gcwq(cpu), work);
2600 * flush_work_sync - wait until a work has finished execution
2601 * @work: the work to flush
2603 * Wait until @work has finished execution. On return, it's
2604 * guaranteed that all queueing instances of @work which happened
2605 * before this function is called are finished. In other words, if
2606 * @work hasn't been requeued since this function was called, @work is
2607 * guaranteed to be idle on return.
2610 * %true if flush_work_sync() waited for the work to finish execution,
2611 * %false if it was already idle.
2613 bool flush_work_sync(struct work_struct *work)
2615 struct wq_barrier barr;
2616 bool pending, waited;
2618 /* we'll wait for executions separately, queue barr only if pending */
2619 pending = start_flush_work(work, &barr, false);
2621 /* wait for executions to finish */
2622 waited = wait_on_work(work);
2624 /* wait for the pending one */
2626 wait_for_completion(&barr.done);
2627 destroy_work_on_stack(&barr.work);
2630 return pending || waited;
2632 EXPORT_SYMBOL_GPL(flush_work_sync);
2635 * Upon a successful return (>= 0), the caller "owns" WORK_STRUCT_PENDING bit,
2636 * so this work can't be re-armed in any way.
2638 static int try_to_grab_pending(struct work_struct *work)
2640 struct global_cwq *gcwq;
2643 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
2647 * The queueing is in progress, or it is already queued. Try to
2648 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
2650 gcwq = get_work_gcwq(work);
2654 spin_lock_irq(&gcwq->lock);
2655 if (!list_empty(&work->entry)) {
2657 * This work is queued, but perhaps we locked the wrong gcwq.
2658 * In that case we must see the new value after rmb(), see
2659 * insert_work()->wmb().
2662 if (gcwq == get_work_gcwq(work)) {
2663 debug_work_deactivate(work);
2664 list_del_init(&work->entry);
2665 cwq_dec_nr_in_flight(get_work_cwq(work),
2666 get_work_color(work),
2667 *work_data_bits(work) & WORK_STRUCT_DELAYED);
2671 spin_unlock_irq(&gcwq->lock);
2676 static bool __cancel_work_timer(struct work_struct *work,
2677 struct timer_list* timer)
2682 ret = (timer && likely(del_timer(timer)));
2684 ret = try_to_grab_pending(work);
2686 } while (unlikely(ret < 0));
2688 clear_work_data(work);
2693 * cancel_work_sync - cancel a work and wait for it to finish
2694 * @work: the work to cancel
2696 * Cancel @work and wait for its execution to finish. This function
2697 * can be used even if the work re-queues itself or migrates to
2698 * another workqueue. On return from this function, @work is
2699 * guaranteed to be not pending or executing on any CPU.
2701 * cancel_work_sync(&delayed_work->work) must not be used for
2702 * delayed_work's. Use cancel_delayed_work_sync() instead.
2704 * The caller must ensure that the workqueue on which @work was last
2705 * queued can't be destroyed before this function returns.
2708 * %true if @work was pending, %false otherwise.
2710 bool cancel_work_sync(struct work_struct *work)
2712 return __cancel_work_timer(work, NULL);
2714 EXPORT_SYMBOL_GPL(cancel_work_sync);
2717 * flush_delayed_work - wait for a dwork to finish executing the last queueing
2718 * @dwork: the delayed work to flush
2720 * Delayed timer is cancelled and the pending work is queued for
2721 * immediate execution. Like flush_work(), this function only
2722 * considers the last queueing instance of @dwork.
2725 * %true if flush_work() waited for the work to finish execution,
2726 * %false if it was already idle.
2728 bool flush_delayed_work(struct delayed_work *dwork)
2730 if (del_timer_sync(&dwork->timer))
2731 __queue_work(raw_smp_processor_id(),
2732 get_work_cwq(&dwork->work)->wq, &dwork->work);
2733 return flush_work(&dwork->work);
2735 EXPORT_SYMBOL(flush_delayed_work);
2738 * flush_delayed_work_sync - wait for a dwork to finish
2739 * @dwork: the delayed work to flush
2741 * Delayed timer is cancelled and the pending work is queued for
2742 * execution immediately. Other than timer handling, its behavior
2743 * is identical to flush_work_sync().
2746 * %true if flush_work_sync() waited for the work to finish execution,
2747 * %false if it was already idle.
2749 bool flush_delayed_work_sync(struct delayed_work *dwork)
2751 if (del_timer_sync(&dwork->timer))
2752 __queue_work(raw_smp_processor_id(),
2753 get_work_cwq(&dwork->work)->wq, &dwork->work);
2754 return flush_work_sync(&dwork->work);
2756 EXPORT_SYMBOL(flush_delayed_work_sync);
2759 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2760 * @dwork: the delayed work cancel
2762 * This is cancel_work_sync() for delayed works.
2765 * %true if @dwork was pending, %false otherwise.
2767 bool cancel_delayed_work_sync(struct delayed_work *dwork)
2769 return __cancel_work_timer(&dwork->work, &dwork->timer);
2771 EXPORT_SYMBOL(cancel_delayed_work_sync);
2774 * schedule_work - put work task in global workqueue
2775 * @work: job to be done
2777 * Returns zero if @work was already on the kernel-global workqueue and
2778 * non-zero otherwise.
2780 * This puts a job in the kernel-global workqueue if it was not already
2781 * queued and leaves it in the same position on the kernel-global
2782 * workqueue otherwise.
2784 int schedule_work(struct work_struct *work)
2786 return queue_work(system_wq, work);
2788 EXPORT_SYMBOL(schedule_work);
2791 * schedule_work_on - put work task on a specific cpu
2792 * @cpu: cpu to put the work task on
2793 * @work: job to be done
2795 * This puts a job on a specific cpu
2797 int schedule_work_on(int cpu, struct work_struct *work)
2799 return queue_work_on(cpu, system_wq, work);
2801 EXPORT_SYMBOL(schedule_work_on);
2804 * schedule_delayed_work - put work task in global workqueue after delay
2805 * @dwork: job to be done
2806 * @delay: number of jiffies to wait or 0 for immediate execution
2808 * After waiting for a given time this puts a job in the kernel-global
2811 int schedule_delayed_work(struct delayed_work *dwork,
2812 unsigned long delay)
2814 return queue_delayed_work(system_wq, dwork, delay);
2816 EXPORT_SYMBOL(schedule_delayed_work);
2819 * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
2821 * @dwork: job to be done
2822 * @delay: number of jiffies to wait
2824 * After waiting for a given time this puts a job in the kernel-global
2825 * workqueue on the specified CPU.
2827 int schedule_delayed_work_on(int cpu,
2828 struct delayed_work *dwork, unsigned long delay)
2830 return queue_delayed_work_on(cpu, system_wq, dwork, delay);
2832 EXPORT_SYMBOL(schedule_delayed_work_on);
2835 * schedule_on_each_cpu - execute a function synchronously on each online CPU
2836 * @func: the function to call
2838 * schedule_on_each_cpu() executes @func on each online CPU using the
2839 * system workqueue and blocks until all CPUs have completed.
2840 * schedule_on_each_cpu() is very slow.
2843 * 0 on success, -errno on failure.
2845 int schedule_on_each_cpu(work_func_t func)
2848 struct work_struct __percpu *works;
2850 works = alloc_percpu(struct work_struct);
2856 for_each_online_cpu(cpu) {
2857 struct work_struct *work = per_cpu_ptr(works, cpu);
2859 INIT_WORK(work, func);
2860 schedule_work_on(cpu, work);
2863 for_each_online_cpu(cpu)
2864 flush_work(per_cpu_ptr(works, cpu));
2872 * flush_scheduled_work - ensure that any scheduled work has run to completion.
2874 * Forces execution of the kernel-global workqueue and blocks until its
2877 * Think twice before calling this function! It's very easy to get into
2878 * trouble if you don't take great care. Either of the following situations
2879 * will lead to deadlock:
2881 * One of the work items currently on the workqueue needs to acquire
2882 * a lock held by your code or its caller.
2884 * Your code is running in the context of a work routine.
2886 * They will be detected by lockdep when they occur, but the first might not
2887 * occur very often. It depends on what work items are on the workqueue and
2888 * what locks they need, which you have no control over.
2890 * In most situations flushing the entire workqueue is overkill; you merely
2891 * need to know that a particular work item isn't queued and isn't running.
2892 * In such cases you should use cancel_delayed_work_sync() or
2893 * cancel_work_sync() instead.
2895 void flush_scheduled_work(void)
2897 flush_workqueue(system_wq);
2899 EXPORT_SYMBOL(flush_scheduled_work);
2902 * execute_in_process_context - reliably execute the routine with user context
2903 * @fn: the function to execute
2904 * @ew: guaranteed storage for the execute work structure (must
2905 * be available when the work executes)
2907 * Executes the function immediately if process context is available,
2908 * otherwise schedules the function for delayed execution.
2910 * Returns: 0 - function was executed
2911 * 1 - function was scheduled for execution
2913 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
2915 if (!in_interrupt()) {
2920 INIT_WORK(&ew->work, fn);
2921 schedule_work(&ew->work);
2925 EXPORT_SYMBOL_GPL(execute_in_process_context);
2927 int keventd_up(void)
2929 return system_wq != NULL;
2932 static int alloc_cwqs(struct workqueue_struct *wq)
2935 * cwqs are forced aligned according to WORK_STRUCT_FLAG_BITS.
2936 * Make sure that the alignment isn't lower than that of
2937 * unsigned long long.
2939 const size_t size = sizeof(struct cpu_workqueue_struct);
2940 const size_t align = max_t(size_t, 1 << WORK_STRUCT_FLAG_BITS,
2941 __alignof__(unsigned long long));
2943 if (!(wq->flags & WQ_UNBOUND))
2944 wq->cpu_wq.pcpu = __alloc_percpu(size, align);
2949 * Allocate enough room to align cwq and put an extra
2950 * pointer at the end pointing back to the originally
2951 * allocated pointer which will be used for free.
2953 ptr = kzalloc(size + align + sizeof(void *), GFP_KERNEL);
2955 wq->cpu_wq.single = PTR_ALIGN(ptr, align);
2956 *(void **)(wq->cpu_wq.single + 1) = ptr;
2960 /* just in case, make sure it's actually aligned */
2961 BUG_ON(!IS_ALIGNED(wq->cpu_wq.v, align));
2962 return wq->cpu_wq.v ? 0 : -ENOMEM;
2965 static void free_cwqs(struct workqueue_struct *wq)
2967 if (!(wq->flags & WQ_UNBOUND))
2968 free_percpu(wq->cpu_wq.pcpu);
2969 else if (wq->cpu_wq.single) {
2970 /* the pointer to free is stored right after the cwq */
2971 kfree(*(void **)(wq->cpu_wq.single + 1));
2975 static int wq_clamp_max_active(int max_active, unsigned int flags,
2978 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
2980 if (max_active < 1 || max_active > lim)
2981 printk(KERN_WARNING "workqueue: max_active %d requested for %s "
2982 "is out of range, clamping between %d and %d\n",
2983 max_active, name, 1, lim);
2985 return clamp_val(max_active, 1, lim);
2988 struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
2991 struct lock_class_key *key,
2992 const char *lock_name, ...)
2994 va_list args, args1;
2995 struct workqueue_struct *wq;
2999 /* determine namelen, allocate wq and format name */
3000 va_start(args, lock_name);
3001 va_copy(args1, args);
3002 namelen = vsnprintf(NULL, 0, fmt, args) + 1;
3004 wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
3008 vsnprintf(wq->name, namelen, fmt, args1);
3013 * Workqueues which may be used during memory reclaim should
3014 * have a rescuer to guarantee forward progress.
3016 if (flags & WQ_MEM_RECLAIM)
3017 flags |= WQ_RESCUER;
3019 max_active = max_active ?: WQ_DFL_ACTIVE;
3020 max_active = wq_clamp_max_active(max_active, flags, wq->name);
3024 wq->saved_max_active = max_active;
3025 mutex_init(&wq->flush_mutex);
3026 atomic_set(&wq->nr_cwqs_to_flush, 0);
3027 INIT_LIST_HEAD(&wq->flusher_queue);
3028 INIT_LIST_HEAD(&wq->flusher_overflow);
3030 lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3031 INIT_LIST_HEAD(&wq->list);
3033 if (alloc_cwqs(wq) < 0)
3036 for_each_cwq_cpu(cpu, wq) {
3037 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3038 struct global_cwq *gcwq = get_gcwq(cpu);
3040 BUG_ON((unsigned long)cwq & WORK_STRUCT_FLAG_MASK);
3041 cwq->pool = &gcwq->pool;
3043 cwq->flush_color = -1;
3044 cwq->max_active = max_active;
3045 INIT_LIST_HEAD(&cwq->delayed_works);
3048 if (flags & WQ_RESCUER) {
3049 struct worker *rescuer;
3051 if (!alloc_mayday_mask(&wq->mayday_mask, GFP_KERNEL))
3054 wq->rescuer = rescuer = alloc_worker();
3058 rescuer->task = kthread_create(rescuer_thread, wq, "%s",
3060 if (IS_ERR(rescuer->task))
3063 rescuer->task->flags |= PF_THREAD_BOUND;
3064 wake_up_process(rescuer->task);
3068 * workqueue_lock protects global freeze state and workqueues
3069 * list. Grab it, set max_active accordingly and add the new
3070 * workqueue to workqueues list.
3072 spin_lock(&workqueue_lock);
3074 if (workqueue_freezing && wq->flags & WQ_FREEZABLE)
3075 for_each_cwq_cpu(cpu, wq)
3076 get_cwq(cpu, wq)->max_active = 0;
3078 list_add(&wq->list, &workqueues);
3080 spin_unlock(&workqueue_lock);
3086 free_mayday_mask(wq->mayday_mask);
3092 EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
3095 * destroy_workqueue - safely terminate a workqueue
3096 * @wq: target workqueue
3098 * Safely destroy a workqueue. All work currently pending will be done first.
3100 void destroy_workqueue(struct workqueue_struct *wq)
3104 /* drain it before proceeding with destruction */
3105 drain_workqueue(wq);
3108 * wq list is used to freeze wq, remove from list after
3109 * flushing is complete in case freeze races us.
3111 spin_lock(&workqueue_lock);
3112 list_del(&wq->list);
3113 spin_unlock(&workqueue_lock);
3116 for_each_cwq_cpu(cpu, wq) {
3117 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3120 for (i = 0; i < WORK_NR_COLORS; i++)
3121 BUG_ON(cwq->nr_in_flight[i]);
3122 BUG_ON(cwq->nr_active);
3123 BUG_ON(!list_empty(&cwq->delayed_works));
3126 if (wq->flags & WQ_RESCUER) {
3127 kthread_stop(wq->rescuer->task);
3128 free_mayday_mask(wq->mayday_mask);
3135 EXPORT_SYMBOL_GPL(destroy_workqueue);
3138 * workqueue_set_max_active - adjust max_active of a workqueue
3139 * @wq: target workqueue
3140 * @max_active: new max_active value.
3142 * Set max_active of @wq to @max_active.
3145 * Don't call from IRQ context.
3147 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
3151 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
3153 spin_lock(&workqueue_lock);
3155 wq->saved_max_active = max_active;
3157 for_each_cwq_cpu(cpu, wq) {
3158 struct global_cwq *gcwq = get_gcwq(cpu);
3160 spin_lock_irq(&gcwq->lock);
3162 if (!(wq->flags & WQ_FREEZABLE) ||
3163 !(gcwq->flags & GCWQ_FREEZING))
3164 get_cwq(gcwq->cpu, wq)->max_active = max_active;
3166 spin_unlock_irq(&gcwq->lock);
3169 spin_unlock(&workqueue_lock);
3171 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
3174 * workqueue_congested - test whether a workqueue is congested
3175 * @cpu: CPU in question
3176 * @wq: target workqueue
3178 * Test whether @wq's cpu workqueue for @cpu is congested. There is
3179 * no synchronization around this function and the test result is
3180 * unreliable and only useful as advisory hints or for debugging.
3183 * %true if congested, %false otherwise.
3185 bool workqueue_congested(unsigned int cpu, struct workqueue_struct *wq)
3187 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3189 return !list_empty(&cwq->delayed_works);
3191 EXPORT_SYMBOL_GPL(workqueue_congested);
3194 * work_cpu - return the last known associated cpu for @work
3195 * @work: the work of interest
3198 * CPU number if @work was ever queued. WORK_CPU_NONE otherwise.
3200 unsigned int work_cpu(struct work_struct *work)
3202 struct global_cwq *gcwq = get_work_gcwq(work);
3204 return gcwq ? gcwq->cpu : WORK_CPU_NONE;
3206 EXPORT_SYMBOL_GPL(work_cpu);
3209 * work_busy - test whether a work is currently pending or running
3210 * @work: the work to be tested
3212 * Test whether @work is currently pending or running. There is no
3213 * synchronization around this function and the test result is
3214 * unreliable and only useful as advisory hints or for debugging.
3215 * Especially for reentrant wqs, the pending state might hide the
3219 * OR'd bitmask of WORK_BUSY_* bits.
3221 unsigned int work_busy(struct work_struct *work)
3223 struct global_cwq *gcwq = get_work_gcwq(work);
3224 unsigned long flags;
3225 unsigned int ret = 0;
3230 spin_lock_irqsave(&gcwq->lock, flags);
3232 if (work_pending(work))
3233 ret |= WORK_BUSY_PENDING;
3234 if (find_worker_executing_work(gcwq, work))
3235 ret |= WORK_BUSY_RUNNING;
3237 spin_unlock_irqrestore(&gcwq->lock, flags);
3241 EXPORT_SYMBOL_GPL(work_busy);
3246 * There are two challenges in supporting CPU hotplug. Firstly, there
3247 * are a lot of assumptions on strong associations among work, cwq and
3248 * gcwq which make migrating pending and scheduled works very
3249 * difficult to implement without impacting hot paths. Secondly,
3250 * gcwqs serve mix of short, long and very long running works making
3251 * blocked draining impractical.
3253 * This is solved by allowing a gcwq to be detached from CPU, running
3254 * it with unbound (rogue) workers and allowing it to be reattached
3255 * later if the cpu comes back online. A separate thread is created
3256 * to govern a gcwq in such state and is called the trustee of the
3259 * Trustee states and their descriptions.
3261 * START Command state used on startup. On CPU_DOWN_PREPARE, a
3262 * new trustee is started with this state.
3264 * IN_CHARGE Once started, trustee will enter this state after
3265 * assuming the manager role and making all existing
3266 * workers rogue. DOWN_PREPARE waits for trustee to
3267 * enter this state. After reaching IN_CHARGE, trustee
3268 * tries to execute the pending worklist until it's empty
3269 * and the state is set to BUTCHER, or the state is set
3272 * BUTCHER Command state which is set by the cpu callback after
3273 * the cpu has went down. Once this state is set trustee
3274 * knows that there will be no new works on the worklist
3275 * and once the worklist is empty it can proceed to
3276 * killing idle workers.
3278 * RELEASE Command state which is set by the cpu callback if the
3279 * cpu down has been canceled or it has come online
3280 * again. After recognizing this state, trustee stops
3281 * trying to drain or butcher and clears ROGUE, rebinds
3282 * all remaining workers back to the cpu and releases
3285 * DONE Trustee will enter this state after BUTCHER or RELEASE
3288 * trustee CPU draining
3289 * took over down complete
3290 * START -----------> IN_CHARGE -----------> BUTCHER -----------> DONE
3292 * | CPU is back online v return workers |
3293 * ----------------> RELEASE --------------
3297 * trustee_wait_event_timeout - timed event wait for trustee
3298 * @cond: condition to wait for
3299 * @timeout: timeout in jiffies
3301 * wait_event_timeout() for trustee to use. Handles locking and
3302 * checks for RELEASE request.
3305 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
3306 * multiple times. To be used by trustee.
3309 * Positive indicating left time if @cond is satisfied, 0 if timed
3310 * out, -1 if canceled.
3312 #define trustee_wait_event_timeout(cond, timeout) ({ \
3313 long __ret = (timeout); \
3314 while (!((cond) || (gcwq->trustee_state == TRUSTEE_RELEASE)) && \
3316 spin_unlock_irq(&gcwq->lock); \
3317 __wait_event_timeout(gcwq->trustee_wait, (cond) || \
3318 (gcwq->trustee_state == TRUSTEE_RELEASE), \
3320 spin_lock_irq(&gcwq->lock); \
3322 gcwq->trustee_state == TRUSTEE_RELEASE ? -1 : (__ret); \
3326 * trustee_wait_event - event wait for trustee
3327 * @cond: condition to wait for
3329 * wait_event() for trustee to use. Automatically handles locking and
3330 * checks for CANCEL request.
3333 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
3334 * multiple times. To be used by trustee.
3337 * 0 if @cond is satisfied, -1 if canceled.
3339 #define trustee_wait_event(cond) ({ \
3341 __ret1 = trustee_wait_event_timeout(cond, MAX_SCHEDULE_TIMEOUT);\
3342 __ret1 < 0 ? -1 : 0; \
3345 static int __cpuinit trustee_thread(void *__gcwq)
3347 struct global_cwq *gcwq = __gcwq;
3348 struct worker *worker;
3349 struct work_struct *work;
3350 struct hlist_node *pos;
3354 BUG_ON(gcwq->cpu != smp_processor_id());
3356 spin_lock_irq(&gcwq->lock);
3358 * Claim the manager position and make all workers rogue.
3359 * Trustee must be bound to the target cpu and can't be
3362 BUG_ON(gcwq->cpu != smp_processor_id());
3363 rc = trustee_wait_event(!(gcwq->flags & GCWQ_MANAGING_WORKERS));
3366 gcwq->flags |= GCWQ_MANAGING_WORKERS;
3368 list_for_each_entry(worker, &gcwq->pool.idle_list, entry)
3369 worker->flags |= WORKER_ROGUE;
3371 for_each_busy_worker(worker, i, pos, gcwq)
3372 worker->flags |= WORKER_ROGUE;
3375 * Call schedule() so that we cross rq->lock and thus can
3376 * guarantee sched callbacks see the rogue flag. This is
3377 * necessary as scheduler callbacks may be invoked from other
3380 spin_unlock_irq(&gcwq->lock);
3382 spin_lock_irq(&gcwq->lock);
3385 * Sched callbacks are disabled now. Zap nr_running. After
3386 * this, nr_running stays zero and need_more_worker() and
3387 * keep_working() are always true as long as the worklist is
3390 atomic_set(get_pool_nr_running(&gcwq->pool), 0);
3392 spin_unlock_irq(&gcwq->lock);
3393 del_timer_sync(&gcwq->pool.idle_timer);
3394 spin_lock_irq(&gcwq->lock);
3397 * We're now in charge. Notify and proceed to drain. We need
3398 * to keep the gcwq running during the whole CPU down
3399 * procedure as other cpu hotunplug callbacks may need to
3400 * flush currently running tasks.
3402 gcwq->trustee_state = TRUSTEE_IN_CHARGE;
3403 wake_up_all(&gcwq->trustee_wait);
3406 * The original cpu is in the process of dying and may go away
3407 * anytime now. When that happens, we and all workers would
3408 * be migrated to other cpus. Try draining any left work. We
3409 * want to get it over with ASAP - spam rescuers, wake up as
3410 * many idlers as necessary and create new ones till the
3411 * worklist is empty. Note that if the gcwq is frozen, there
3412 * may be frozen works in freezable cwqs. Don't declare
3413 * completion while frozen.
3415 while (gcwq->pool.nr_workers != gcwq->pool.nr_idle ||
3416 gcwq->flags & GCWQ_FREEZING ||
3417 gcwq->trustee_state == TRUSTEE_IN_CHARGE) {
3420 list_for_each_entry(work, &gcwq->pool.worklist, entry) {
3425 list_for_each_entry(worker, &gcwq->pool.idle_list, entry) {
3428 wake_up_process(worker->task);
3431 if (need_to_create_worker(&gcwq->pool)) {
3432 spin_unlock_irq(&gcwq->lock);
3433 worker = create_worker(&gcwq->pool, false);
3434 spin_lock_irq(&gcwq->lock);
3436 worker->flags |= WORKER_ROGUE;
3437 start_worker(worker);
3441 /* give a breather */
3442 if (trustee_wait_event_timeout(false, TRUSTEE_COOLDOWN) < 0)
3447 * Either all works have been scheduled and cpu is down, or
3448 * cpu down has already been canceled. Wait for and butcher
3449 * all workers till we're canceled.
3452 rc = trustee_wait_event(!list_empty(&gcwq->pool.idle_list));
3453 while (!list_empty(&gcwq->pool.idle_list))
3454 destroy_worker(list_first_entry(&gcwq->pool.idle_list,
3455 struct worker, entry));
3456 } while (gcwq->pool.nr_workers && rc >= 0);
3459 * At this point, either draining has completed and no worker
3460 * is left, or cpu down has been canceled or the cpu is being
3461 * brought back up. There shouldn't be any idle one left.
3462 * Tell the remaining busy ones to rebind once it finishes the
3463 * currently scheduled works by scheduling the rebind_work.
3465 WARN_ON(!list_empty(&gcwq->pool.idle_list));
3467 for_each_busy_worker(worker, i, pos, gcwq) {
3468 struct work_struct *rebind_work = &worker->rebind_work;
3471 * Rebind_work may race with future cpu hotplug
3472 * operations. Use a separate flag to mark that
3473 * rebinding is scheduled.
3475 worker->flags |= WORKER_REBIND;
3476 worker->flags &= ~WORKER_ROGUE;
3478 /* queue rebind_work, wq doesn't matter, use the default one */
3479 if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
3480 work_data_bits(rebind_work)))
3483 debug_work_activate(rebind_work);
3484 insert_work(get_cwq(gcwq->cpu, system_wq), rebind_work,
3485 worker->scheduled.next,
3486 work_color_to_flags(WORK_NO_COLOR));
3489 /* relinquish manager role */
3490 gcwq->flags &= ~GCWQ_MANAGING_WORKERS;
3492 /* notify completion */
3493 gcwq->trustee = NULL;
3494 gcwq->trustee_state = TRUSTEE_DONE;
3495 wake_up_all(&gcwq->trustee_wait);
3496 spin_unlock_irq(&gcwq->lock);
3501 * wait_trustee_state - wait for trustee to enter the specified state
3502 * @gcwq: gcwq the trustee of interest belongs to
3503 * @state: target state to wait for
3505 * Wait for the trustee to reach @state. DONE is already matched.
3508 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
3509 * multiple times. To be used by cpu_callback.
3511 static void __cpuinit wait_trustee_state(struct global_cwq *gcwq, int state)
3512 __releases(&gcwq->lock)
3513 __acquires(&gcwq->lock)
3515 if (!(gcwq->trustee_state == state ||
3516 gcwq->trustee_state == TRUSTEE_DONE)) {
3517 spin_unlock_irq(&gcwq->lock);
3518 __wait_event(gcwq->trustee_wait,
3519 gcwq->trustee_state == state ||
3520 gcwq->trustee_state == TRUSTEE_DONE);
3521 spin_lock_irq(&gcwq->lock);
3525 static int __devinit workqueue_cpu_callback(struct notifier_block *nfb,
3526 unsigned long action,
3529 unsigned int cpu = (unsigned long)hcpu;
3530 struct global_cwq *gcwq = get_gcwq(cpu);
3531 struct task_struct *new_trustee = NULL;
3532 struct worker *uninitialized_var(new_worker);
3533 unsigned long flags;
3535 action &= ~CPU_TASKS_FROZEN;
3538 case CPU_DOWN_PREPARE:
3539 new_trustee = kthread_create(trustee_thread, gcwq,
3540 "workqueue_trustee/%d\n", cpu);
3541 if (IS_ERR(new_trustee))
3542 return notifier_from_errno(PTR_ERR(new_trustee));
3543 kthread_bind(new_trustee, cpu);
3545 case CPU_UP_PREPARE:
3546 BUG_ON(gcwq->pool.first_idle);
3547 new_worker = create_worker(&gcwq->pool, false);
3550 kthread_stop(new_trustee);
3555 /* some are called w/ irq disabled, don't disturb irq status */
3556 spin_lock_irqsave(&gcwq->lock, flags);
3559 case CPU_DOWN_PREPARE:
3560 /* initialize trustee and tell it to acquire the gcwq */
3561 BUG_ON(gcwq->trustee || gcwq->trustee_state != TRUSTEE_DONE);
3562 gcwq->trustee = new_trustee;
3563 gcwq->trustee_state = TRUSTEE_START;
3564 wake_up_process(gcwq->trustee);
3565 wait_trustee_state(gcwq, TRUSTEE_IN_CHARGE);
3567 case CPU_UP_PREPARE:
3568 BUG_ON(gcwq->pool.first_idle);
3569 gcwq->pool.first_idle = new_worker;
3574 * Before this, the trustee and all workers except for
3575 * the ones which are still executing works from
3576 * before the last CPU down must be on the cpu. After
3577 * this, they'll all be diasporas.
3579 gcwq->flags |= GCWQ_DISASSOCIATED;
3583 gcwq->trustee_state = TRUSTEE_BUTCHER;
3585 case CPU_UP_CANCELED:
3586 destroy_worker(gcwq->pool.first_idle);
3587 gcwq->pool.first_idle = NULL;
3590 case CPU_DOWN_FAILED:
3592 gcwq->flags &= ~GCWQ_DISASSOCIATED;
3593 if (gcwq->trustee_state != TRUSTEE_DONE) {
3594 gcwq->trustee_state = TRUSTEE_RELEASE;
3595 wake_up_process(gcwq->trustee);
3596 wait_trustee_state(gcwq, TRUSTEE_DONE);
3600 * Trustee is done and there might be no worker left.
3601 * Put the first_idle in and request a real manager to
3604 spin_unlock_irq(&gcwq->lock);
3605 kthread_bind(gcwq->pool.first_idle->task, cpu);
3606 spin_lock_irq(&gcwq->lock);
3607 gcwq->flags |= GCWQ_MANAGE_WORKERS;
3608 start_worker(gcwq->pool.first_idle);
3609 gcwq->pool.first_idle = NULL;
3613 spin_unlock_irqrestore(&gcwq->lock, flags);
3615 return notifier_from_errno(0);
3620 struct work_for_cpu {
3621 struct completion completion;
3627 static int do_work_for_cpu(void *_wfc)
3629 struct work_for_cpu *wfc = _wfc;
3630 wfc->ret = wfc->fn(wfc->arg);
3631 complete(&wfc->completion);
3636 * work_on_cpu - run a function in user context on a particular cpu
3637 * @cpu: the cpu to run on
3638 * @fn: the function to run
3639 * @arg: the function arg
3641 * This will return the value @fn returns.
3642 * It is up to the caller to ensure that the cpu doesn't go offline.
3643 * The caller must not hold any locks which would prevent @fn from completing.
3645 long work_on_cpu(unsigned int cpu, long (*fn)(void *), void *arg)
3647 struct task_struct *sub_thread;
3648 struct work_for_cpu wfc = {
3649 .completion = COMPLETION_INITIALIZER_ONSTACK(wfc.completion),
3654 sub_thread = kthread_create(do_work_for_cpu, &wfc, "work_for_cpu");
3655 if (IS_ERR(sub_thread))
3656 return PTR_ERR(sub_thread);
3657 kthread_bind(sub_thread, cpu);
3658 wake_up_process(sub_thread);
3659 wait_for_completion(&wfc.completion);
3662 EXPORT_SYMBOL_GPL(work_on_cpu);
3663 #endif /* CONFIG_SMP */
3665 #ifdef CONFIG_FREEZER
3668 * freeze_workqueues_begin - begin freezing workqueues
3670 * Start freezing workqueues. After this function returns, all freezable
3671 * workqueues will queue new works to their frozen_works list instead of
3675 * Grabs and releases workqueue_lock and gcwq->lock's.
3677 void freeze_workqueues_begin(void)
3681 spin_lock(&workqueue_lock);
3683 BUG_ON(workqueue_freezing);
3684 workqueue_freezing = true;
3686 for_each_gcwq_cpu(cpu) {
3687 struct global_cwq *gcwq = get_gcwq(cpu);
3688 struct workqueue_struct *wq;
3690 spin_lock_irq(&gcwq->lock);
3692 BUG_ON(gcwq->flags & GCWQ_FREEZING);
3693 gcwq->flags |= GCWQ_FREEZING;
3695 list_for_each_entry(wq, &workqueues, list) {
3696 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3698 if (cwq && wq->flags & WQ_FREEZABLE)
3699 cwq->max_active = 0;
3702 spin_unlock_irq(&gcwq->lock);
3705 spin_unlock(&workqueue_lock);
3709 * freeze_workqueues_busy - are freezable workqueues still busy?
3711 * Check whether freezing is complete. This function must be called
3712 * between freeze_workqueues_begin() and thaw_workqueues().
3715 * Grabs and releases workqueue_lock.
3718 * %true if some freezable workqueues are still busy. %false if freezing
3721 bool freeze_workqueues_busy(void)
3726 spin_lock(&workqueue_lock);
3728 BUG_ON(!workqueue_freezing);
3730 for_each_gcwq_cpu(cpu) {
3731 struct workqueue_struct *wq;
3733 * nr_active is monotonically decreasing. It's safe
3734 * to peek without lock.
3736 list_for_each_entry(wq, &workqueues, list) {
3737 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3739 if (!cwq || !(wq->flags & WQ_FREEZABLE))
3742 BUG_ON(cwq->nr_active < 0);
3743 if (cwq->nr_active) {
3750 spin_unlock(&workqueue_lock);
3755 * thaw_workqueues - thaw workqueues
3757 * Thaw workqueues. Normal queueing is restored and all collected
3758 * frozen works are transferred to their respective gcwq worklists.
3761 * Grabs and releases workqueue_lock and gcwq->lock's.
3763 void thaw_workqueues(void)
3767 spin_lock(&workqueue_lock);
3769 if (!workqueue_freezing)
3772 for_each_gcwq_cpu(cpu) {
3773 struct global_cwq *gcwq = get_gcwq(cpu);
3774 struct workqueue_struct *wq;
3776 spin_lock_irq(&gcwq->lock);
3778 BUG_ON(!(gcwq->flags & GCWQ_FREEZING));
3779 gcwq->flags &= ~GCWQ_FREEZING;
3781 list_for_each_entry(wq, &workqueues, list) {
3782 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3784 if (!cwq || !(wq->flags & WQ_FREEZABLE))
3787 /* restore max_active and repopulate worklist */
3788 cwq->max_active = wq->saved_max_active;
3790 while (!list_empty(&cwq->delayed_works) &&
3791 cwq->nr_active < cwq->max_active)
3792 cwq_activate_first_delayed(cwq);
3795 wake_up_worker(&gcwq->pool);
3797 spin_unlock_irq(&gcwq->lock);
3800 workqueue_freezing = false;
3802 spin_unlock(&workqueue_lock);
3804 #endif /* CONFIG_FREEZER */
3806 static int __init init_workqueues(void)
3811 cpu_notifier(workqueue_cpu_callback, CPU_PRI_WORKQUEUE);
3813 /* initialize gcwqs */
3814 for_each_gcwq_cpu(cpu) {
3815 struct global_cwq *gcwq = get_gcwq(cpu);
3817 spin_lock_init(&gcwq->lock);
3818 gcwq->pool.gcwq = gcwq;
3819 INIT_LIST_HEAD(&gcwq->pool.worklist);
3821 gcwq->flags |= GCWQ_DISASSOCIATED;
3823 INIT_LIST_HEAD(&gcwq->pool.idle_list);
3824 for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)
3825 INIT_HLIST_HEAD(&gcwq->busy_hash[i]);
3827 init_timer_deferrable(&gcwq->pool.idle_timer);
3828 gcwq->pool.idle_timer.function = idle_worker_timeout;
3829 gcwq->pool.idle_timer.data = (unsigned long)&gcwq->pool;
3831 setup_timer(&gcwq->pool.mayday_timer, gcwq_mayday_timeout,
3832 (unsigned long)&gcwq->pool);
3834 ida_init(&gcwq->pool.worker_ida);
3836 gcwq->trustee_state = TRUSTEE_DONE;
3837 init_waitqueue_head(&gcwq->trustee_wait);
3840 /* create the initial worker */
3841 for_each_online_gcwq_cpu(cpu) {
3842 struct global_cwq *gcwq = get_gcwq(cpu);
3843 struct worker *worker;
3845 if (cpu != WORK_CPU_UNBOUND)
3846 gcwq->flags &= ~GCWQ_DISASSOCIATED;
3847 worker = create_worker(&gcwq->pool, true);
3849 spin_lock_irq(&gcwq->lock);
3850 start_worker(worker);
3851 spin_unlock_irq(&gcwq->lock);
3854 system_wq = alloc_workqueue("events", 0, 0);
3855 system_long_wq = alloc_workqueue("events_long", 0, 0);
3856 system_nrt_wq = alloc_workqueue("events_nrt", WQ_NON_REENTRANT, 0);
3857 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
3858 WQ_UNBOUND_MAX_ACTIVE);
3859 system_freezable_wq = alloc_workqueue("events_freezable",
3861 system_nrt_freezable_wq = alloc_workqueue("events_nrt_freezable",
3862 WQ_NON_REENTRANT | WQ_FREEZABLE, 0);
3863 BUG_ON(!system_wq || !system_long_wq || !system_nrt_wq ||
3864 !system_unbound_wq || !system_freezable_wq ||
3865 !system_nrt_freezable_wq);
3868 early_initcall(init_workqueues);