2 * linux/kernel/workqueue.c
4 * Generic mechanism for defining kernel helper threads for running
5 * arbitrary tasks in process context.
7 * Started by Ingo Molnar, Copyright (C) 2002
9 * Derived from the taskqueue/keventd code by:
11 * David Woodhouse <dwmw2@infradead.org>
13 * Kai Petzke <wpp@marie.physik.tu-berlin.de>
14 * Theodore Ts'o <tytso@mit.edu>
16 * Made to use alloc_percpu by Christoph Lameter.
19 #include <linux/module.h>
20 #include <linux/kernel.h>
21 #include <linux/sched.h>
22 #include <linux/init.h>
23 #include <linux/signal.h>
24 #include <linux/completion.h>
25 #include <linux/workqueue.h>
26 #include <linux/slab.h>
27 #include <linux/cpu.h>
28 #include <linux/notifier.h>
29 #include <linux/kthread.h>
30 #include <linux/hardirq.h>
31 #include <linux/mempolicy.h>
32 #include <linux/freezer.h>
33 #include <linux/kallsyms.h>
34 #include <linux/debug_locks.h>
35 #include <linux/lockdep.h>
36 #include <linux/idr.h>
38 #include "workqueue_sched.h"
41 /* global_cwq flags */
42 GCWQ_MANAGE_WORKERS = 1 << 0, /* need to manage workers */
43 GCWQ_MANAGING_WORKERS = 1 << 1, /* managing workers */
44 GCWQ_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
45 GCWQ_FREEZING = 1 << 3, /* freeze in progress */
46 GCWQ_HIGHPRI_PENDING = 1 << 4, /* highpri works on queue */
49 WORKER_STARTED = 1 << 0, /* started */
50 WORKER_DIE = 1 << 1, /* die die die */
51 WORKER_IDLE = 1 << 2, /* is idle */
52 WORKER_PREP = 1 << 3, /* preparing to run works */
53 WORKER_ROGUE = 1 << 4, /* not bound to any cpu */
54 WORKER_REBIND = 1 << 5, /* mom is home, come back */
55 WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
56 WORKER_UNBOUND = 1 << 7, /* worker is unbound */
58 WORKER_NOT_RUNNING = WORKER_PREP | WORKER_ROGUE | WORKER_REBIND |
59 WORKER_CPU_INTENSIVE | WORKER_UNBOUND,
61 /* gcwq->trustee_state */
62 TRUSTEE_START = 0, /* start */
63 TRUSTEE_IN_CHARGE = 1, /* trustee in charge of gcwq */
64 TRUSTEE_BUTCHER = 2, /* butcher workers */
65 TRUSTEE_RELEASE = 3, /* release workers */
66 TRUSTEE_DONE = 4, /* trustee is done */
68 BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
69 BUSY_WORKER_HASH_SIZE = 1 << BUSY_WORKER_HASH_ORDER,
70 BUSY_WORKER_HASH_MASK = BUSY_WORKER_HASH_SIZE - 1,
72 MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
73 IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
75 MAYDAY_INITIAL_TIMEOUT = HZ / 100, /* call for help after 10ms */
76 MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
77 CREATE_COOLDOWN = HZ, /* time to breath after fail */
78 TRUSTEE_COOLDOWN = HZ / 10, /* for trustee draining */
81 * Rescue workers are used only on emergencies and shared by
84 RESCUER_NICE_LEVEL = -20,
88 * Structure fields follow one of the following exclusion rules.
90 * I: Set during initialization and read-only afterwards.
92 * P: Preemption protected. Disabling preemption is enough and should
93 * only be modified and accessed from the local cpu.
95 * L: gcwq->lock protected. Access with gcwq->lock held.
97 * X: During normal operation, modification requires gcwq->lock and
98 * should be done only from local cpu. Either disabling preemption
99 * on local cpu or grabbing gcwq->lock is enough for read access.
100 * If GCWQ_DISASSOCIATED is set, it's identical to L.
102 * F: wq->flush_mutex protected.
104 * W: workqueue_lock protected.
110 * The poor guys doing the actual heavy lifting. All on-duty workers
111 * are either serving the manager role, on idle list or on busy hash.
114 /* on idle list while idle, on busy hash table while busy */
116 struct list_head entry; /* L: while idle */
117 struct hlist_node hentry; /* L: while busy */
120 struct work_struct *current_work; /* L: work being processed */
121 struct cpu_workqueue_struct *current_cwq; /* L: current_work's cwq */
122 struct list_head scheduled; /* L: scheduled works */
123 struct task_struct *task; /* I: worker task */
124 struct global_cwq *gcwq; /* I: the associated gcwq */
125 /* 64 bytes boundary on 64bit, 32 on 32bit */
126 unsigned long last_active; /* L: last active timestamp */
127 unsigned int flags; /* X: flags */
128 int id; /* I: worker id */
129 struct work_struct rebind_work; /* L: rebind worker to cpu */
133 * Global per-cpu workqueue. There's one and only one for each cpu
134 * and all works are queued and processed here regardless of their
138 spinlock_t lock; /* the gcwq lock */
139 struct list_head worklist; /* L: list of pending works */
140 unsigned int cpu; /* I: the associated cpu */
141 unsigned int flags; /* L: GCWQ_* flags */
143 int nr_workers; /* L: total number of workers */
144 int nr_idle; /* L: currently idle ones */
146 /* workers are chained either in the idle_list or busy_hash */
147 struct list_head idle_list; /* X: list of idle workers */
148 struct hlist_head busy_hash[BUSY_WORKER_HASH_SIZE];
149 /* L: hash of busy workers */
151 struct timer_list idle_timer; /* L: worker idle timeout */
152 struct timer_list mayday_timer; /* L: SOS timer for dworkers */
154 struct ida worker_ida; /* L: for worker IDs */
156 struct task_struct *trustee; /* L: for gcwq shutdown */
157 unsigned int trustee_state; /* L: trustee state */
158 wait_queue_head_t trustee_wait; /* trustee wait */
159 struct worker *first_idle; /* L: first idle worker */
160 } ____cacheline_aligned_in_smp;
163 * The per-CPU workqueue. The lower WORK_STRUCT_FLAG_BITS of
164 * work_struct->data are used for flags and thus cwqs need to be
165 * aligned at two's power of the number of flag bits.
167 struct cpu_workqueue_struct {
168 struct global_cwq *gcwq; /* I: the associated gcwq */
169 struct workqueue_struct *wq; /* I: the owning workqueue */
170 int work_color; /* L: current color */
171 int flush_color; /* L: flushing color */
172 int nr_in_flight[WORK_NR_COLORS];
173 /* L: nr of in_flight works */
174 int nr_active; /* L: nr of active works */
175 int max_active; /* L: max active works */
176 struct list_head delayed_works; /* L: delayed works */
180 * Structure used to wait for workqueue flush.
183 struct list_head list; /* F: list of flushers */
184 int flush_color; /* F: flush color waiting for */
185 struct completion done; /* flush completion */
189 * All cpumasks are assumed to be always set on UP and thus can't be
190 * used to determine whether there's something to be done.
193 typedef cpumask_var_t mayday_mask_t;
194 #define mayday_test_and_set_cpu(cpu, mask) \
195 cpumask_test_and_set_cpu((cpu), (mask))
196 #define mayday_clear_cpu(cpu, mask) cpumask_clear_cpu((cpu), (mask))
197 #define for_each_mayday_cpu(cpu, mask) for_each_cpu((cpu), (mask))
198 #define alloc_mayday_mask(maskp, gfp) alloc_cpumask_var((maskp), (gfp))
199 #define free_mayday_mask(mask) free_cpumask_var((mask))
201 typedef unsigned long mayday_mask_t;
202 #define mayday_test_and_set_cpu(cpu, mask) test_and_set_bit(0, &(mask))
203 #define mayday_clear_cpu(cpu, mask) clear_bit(0, &(mask))
204 #define for_each_mayday_cpu(cpu, mask) if ((cpu) = 0, (mask))
205 #define alloc_mayday_mask(maskp, gfp) true
206 #define free_mayday_mask(mask) do { } while (0)
210 * The externally visible workqueue abstraction is an array of
211 * per-CPU workqueues:
213 struct workqueue_struct {
214 unsigned int flags; /* I: WQ_* flags */
216 struct cpu_workqueue_struct __percpu *pcpu;
217 struct cpu_workqueue_struct *single;
219 } cpu_wq; /* I: cwq's */
220 struct list_head list; /* W: list of all workqueues */
222 struct mutex flush_mutex; /* protects wq flushing */
223 int work_color; /* F: current work color */
224 int flush_color; /* F: current flush color */
225 atomic_t nr_cwqs_to_flush; /* flush in progress */
226 struct wq_flusher *first_flusher; /* F: first flusher */
227 struct list_head flusher_queue; /* F: flush waiters */
228 struct list_head flusher_overflow; /* F: flush overflow list */
230 mayday_mask_t mayday_mask; /* cpus requesting rescue */
231 struct worker *rescuer; /* I: rescue worker */
233 int saved_max_active; /* W: saved cwq max_active */
234 const char *name; /* I: workqueue name */
235 #ifdef CONFIG_LOCKDEP
236 struct lockdep_map lockdep_map;
240 struct workqueue_struct *system_wq __read_mostly;
241 struct workqueue_struct *system_long_wq __read_mostly;
242 struct workqueue_struct *system_nrt_wq __read_mostly;
243 struct workqueue_struct *system_unbound_wq __read_mostly;
244 EXPORT_SYMBOL_GPL(system_wq);
245 EXPORT_SYMBOL_GPL(system_long_wq);
246 EXPORT_SYMBOL_GPL(system_nrt_wq);
247 EXPORT_SYMBOL_GPL(system_unbound_wq);
249 #define for_each_busy_worker(worker, i, pos, gcwq) \
250 for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++) \
251 hlist_for_each_entry(worker, pos, &gcwq->busy_hash[i], hentry)
253 static inline int __next_gcwq_cpu(int cpu, const struct cpumask *mask,
256 if (cpu < nr_cpu_ids) {
258 cpu = cpumask_next(cpu, mask);
259 if (cpu < nr_cpu_ids)
263 return WORK_CPU_UNBOUND;
265 return WORK_CPU_NONE;
268 static inline int __next_wq_cpu(int cpu, const struct cpumask *mask,
269 struct workqueue_struct *wq)
271 return __next_gcwq_cpu(cpu, mask, !(wq->flags & WQ_UNBOUND) ? 1 : 2);
274 #define for_each_gcwq_cpu(cpu) \
275 for ((cpu) = __next_gcwq_cpu(-1, cpu_possible_mask, 3); \
276 (cpu) < WORK_CPU_NONE; \
277 (cpu) = __next_gcwq_cpu((cpu), cpu_possible_mask, 3))
279 #define for_each_online_gcwq_cpu(cpu) \
280 for ((cpu) = __next_gcwq_cpu(-1, cpu_online_mask, 3); \
281 (cpu) < WORK_CPU_NONE; \
282 (cpu) = __next_gcwq_cpu((cpu), cpu_online_mask, 3))
284 #define for_each_cwq_cpu(cpu, wq) \
285 for ((cpu) = __next_wq_cpu(-1, cpu_possible_mask, (wq)); \
286 (cpu) < WORK_CPU_NONE; \
287 (cpu) = __next_wq_cpu((cpu), cpu_possible_mask, (wq)))
289 #ifdef CONFIG_DEBUG_OBJECTS_WORK
291 static struct debug_obj_descr work_debug_descr;
294 * fixup_init is called when:
295 * - an active object is initialized
297 static int work_fixup_init(void *addr, enum debug_obj_state state)
299 struct work_struct *work = addr;
302 case ODEBUG_STATE_ACTIVE:
303 cancel_work_sync(work);
304 debug_object_init(work, &work_debug_descr);
312 * fixup_activate is called when:
313 * - an active object is activated
314 * - an unknown object is activated (might be a statically initialized object)
316 static int work_fixup_activate(void *addr, enum debug_obj_state state)
318 struct work_struct *work = addr;
322 case ODEBUG_STATE_NOTAVAILABLE:
324 * This is not really a fixup. The work struct was
325 * statically initialized. We just make sure that it
326 * is tracked in the object tracker.
328 if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
329 debug_object_init(work, &work_debug_descr);
330 debug_object_activate(work, &work_debug_descr);
336 case ODEBUG_STATE_ACTIVE:
345 * fixup_free is called when:
346 * - an active object is freed
348 static int work_fixup_free(void *addr, enum debug_obj_state state)
350 struct work_struct *work = addr;
353 case ODEBUG_STATE_ACTIVE:
354 cancel_work_sync(work);
355 debug_object_free(work, &work_debug_descr);
362 static struct debug_obj_descr work_debug_descr = {
363 .name = "work_struct",
364 .fixup_init = work_fixup_init,
365 .fixup_activate = work_fixup_activate,
366 .fixup_free = work_fixup_free,
369 static inline void debug_work_activate(struct work_struct *work)
371 debug_object_activate(work, &work_debug_descr);
374 static inline void debug_work_deactivate(struct work_struct *work)
376 debug_object_deactivate(work, &work_debug_descr);
379 void __init_work(struct work_struct *work, int onstack)
382 debug_object_init_on_stack(work, &work_debug_descr);
384 debug_object_init(work, &work_debug_descr);
386 EXPORT_SYMBOL_GPL(__init_work);
388 void destroy_work_on_stack(struct work_struct *work)
390 debug_object_free(work, &work_debug_descr);
392 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
395 static inline void debug_work_activate(struct work_struct *work) { }
396 static inline void debug_work_deactivate(struct work_struct *work) { }
399 /* Serializes the accesses to the list of workqueues. */
400 static DEFINE_SPINLOCK(workqueue_lock);
401 static LIST_HEAD(workqueues);
402 static bool workqueue_freezing; /* W: have wqs started freezing? */
405 * The almighty global cpu workqueues. nr_running is the only field
406 * which is expected to be used frequently by other cpus via
407 * try_to_wake_up(). Put it in a separate cacheline.
409 static DEFINE_PER_CPU(struct global_cwq, global_cwq);
410 static DEFINE_PER_CPU_SHARED_ALIGNED(atomic_t, gcwq_nr_running);
413 * Global cpu workqueue and nr_running counter for unbound gcwq. The
414 * gcwq is always online, has GCWQ_DISASSOCIATED set, and all its
415 * workers have WORKER_UNBOUND set.
417 static struct global_cwq unbound_global_cwq;
418 static atomic_t unbound_gcwq_nr_running = ATOMIC_INIT(0); /* always 0 */
420 static int worker_thread(void *__worker);
422 static struct global_cwq *get_gcwq(unsigned int cpu)
424 if (cpu != WORK_CPU_UNBOUND)
425 return &per_cpu(global_cwq, cpu);
427 return &unbound_global_cwq;
430 static atomic_t *get_gcwq_nr_running(unsigned int cpu)
432 if (cpu != WORK_CPU_UNBOUND)
433 return &per_cpu(gcwq_nr_running, cpu);
435 return &unbound_gcwq_nr_running;
438 static struct cpu_workqueue_struct *get_cwq(unsigned int cpu,
439 struct workqueue_struct *wq)
441 if (!(wq->flags & WQ_UNBOUND)) {
442 if (likely(cpu < nr_cpu_ids)) {
444 return per_cpu_ptr(wq->cpu_wq.pcpu, cpu);
446 return wq->cpu_wq.single;
449 } else if (likely(cpu == WORK_CPU_UNBOUND))
450 return wq->cpu_wq.single;
454 static unsigned int work_color_to_flags(int color)
456 return color << WORK_STRUCT_COLOR_SHIFT;
459 static int get_work_color(struct work_struct *work)
461 return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
462 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
465 static int work_next_color(int color)
467 return (color + 1) % WORK_NR_COLORS;
471 * Work data points to the cwq while a work is on queue. Once
472 * execution starts, it points to the cpu the work was last on. This
473 * can be distinguished by comparing the data value against
476 * set_work_{cwq|cpu}() and clear_work_data() can be used to set the
477 * cwq, cpu or clear work->data. These functions should only be
478 * called while the work is owned - ie. while the PENDING bit is set.
480 * get_work_[g]cwq() can be used to obtain the gcwq or cwq
481 * corresponding to a work. gcwq is available once the work has been
482 * queued anywhere after initialization. cwq is available only from
483 * queueing until execution starts.
485 static inline void set_work_data(struct work_struct *work, unsigned long data,
488 BUG_ON(!work_pending(work));
489 atomic_long_set(&work->data, data | flags | work_static(work));
492 static void set_work_cwq(struct work_struct *work,
493 struct cpu_workqueue_struct *cwq,
494 unsigned long extra_flags)
496 set_work_data(work, (unsigned long)cwq,
497 WORK_STRUCT_PENDING | extra_flags);
500 static void set_work_cpu(struct work_struct *work, unsigned int cpu)
502 set_work_data(work, cpu << WORK_STRUCT_FLAG_BITS, WORK_STRUCT_PENDING);
505 static void clear_work_data(struct work_struct *work)
507 set_work_data(work, WORK_STRUCT_NO_CPU, 0);
510 static inline unsigned long get_work_data(struct work_struct *work)
512 return atomic_long_read(&work->data) & WORK_STRUCT_WQ_DATA_MASK;
515 static struct cpu_workqueue_struct *get_work_cwq(struct work_struct *work)
517 unsigned long data = get_work_data(work);
519 return data >= PAGE_OFFSET ? (void *)data : NULL;
522 static struct global_cwq *get_work_gcwq(struct work_struct *work)
524 unsigned long data = get_work_data(work);
527 if (data >= PAGE_OFFSET)
528 return ((struct cpu_workqueue_struct *)data)->gcwq;
530 cpu = data >> WORK_STRUCT_FLAG_BITS;
531 if (cpu == WORK_CPU_NONE)
534 BUG_ON(cpu >= nr_cpu_ids && cpu != WORK_CPU_UNBOUND);
535 return get_gcwq(cpu);
539 * Policy functions. These define the policies on how the global
540 * worker pool is managed. Unless noted otherwise, these functions
541 * assume that they're being called with gcwq->lock held.
544 static bool __need_more_worker(struct global_cwq *gcwq)
546 return !atomic_read(get_gcwq_nr_running(gcwq->cpu)) ||
547 gcwq->flags & GCWQ_HIGHPRI_PENDING;
551 * Need to wake up a worker? Called from anything but currently
554 static bool need_more_worker(struct global_cwq *gcwq)
556 return !list_empty(&gcwq->worklist) && __need_more_worker(gcwq);
559 /* Can I start working? Called from busy but !running workers. */
560 static bool may_start_working(struct global_cwq *gcwq)
562 return gcwq->nr_idle;
565 /* Do I need to keep working? Called from currently running workers. */
566 static bool keep_working(struct global_cwq *gcwq)
568 atomic_t *nr_running = get_gcwq_nr_running(gcwq->cpu);
570 return !list_empty(&gcwq->worklist) && atomic_read(nr_running) <= 1;
573 /* Do we need a new worker? Called from manager. */
574 static bool need_to_create_worker(struct global_cwq *gcwq)
576 return need_more_worker(gcwq) && !may_start_working(gcwq);
579 /* Do I need to be the manager? */
580 static bool need_to_manage_workers(struct global_cwq *gcwq)
582 return need_to_create_worker(gcwq) || gcwq->flags & GCWQ_MANAGE_WORKERS;
585 /* Do we have too many workers and should some go away? */
586 static bool too_many_workers(struct global_cwq *gcwq)
588 bool managing = gcwq->flags & GCWQ_MANAGING_WORKERS;
589 int nr_idle = gcwq->nr_idle + managing; /* manager is considered idle */
590 int nr_busy = gcwq->nr_workers - nr_idle;
592 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
599 /* Return the first worker. Safe with preemption disabled */
600 static struct worker *first_worker(struct global_cwq *gcwq)
602 if (unlikely(list_empty(&gcwq->idle_list)))
605 return list_first_entry(&gcwq->idle_list, struct worker, entry);
609 * wake_up_worker - wake up an idle worker
610 * @gcwq: gcwq to wake worker for
612 * Wake up the first idle worker of @gcwq.
615 * spin_lock_irq(gcwq->lock).
617 static void wake_up_worker(struct global_cwq *gcwq)
619 struct worker *worker = first_worker(gcwq);
622 wake_up_process(worker->task);
626 * wq_worker_waking_up - a worker is waking up
627 * @task: task waking up
628 * @cpu: CPU @task is waking up to
630 * This function is called during try_to_wake_up() when a worker is
634 * spin_lock_irq(rq->lock)
636 void wq_worker_waking_up(struct task_struct *task, unsigned int cpu)
638 struct worker *worker = kthread_data(task);
640 if (likely(!(worker->flags & WORKER_NOT_RUNNING)))
641 atomic_inc(get_gcwq_nr_running(cpu));
645 * wq_worker_sleeping - a worker is going to sleep
646 * @task: task going to sleep
647 * @cpu: CPU in question, must be the current CPU number
649 * This function is called during schedule() when a busy worker is
650 * going to sleep. Worker on the same cpu can be woken up by
651 * returning pointer to its task.
654 * spin_lock_irq(rq->lock)
657 * Worker task on @cpu to wake up, %NULL if none.
659 struct task_struct *wq_worker_sleeping(struct task_struct *task,
662 struct worker *worker = kthread_data(task), *to_wakeup = NULL;
663 struct global_cwq *gcwq = get_gcwq(cpu);
664 atomic_t *nr_running = get_gcwq_nr_running(cpu);
666 if (unlikely(worker->flags & WORKER_NOT_RUNNING))
669 /* this can only happen on the local cpu */
670 BUG_ON(cpu != raw_smp_processor_id());
673 * The counterpart of the following dec_and_test, implied mb,
674 * worklist not empty test sequence is in insert_work().
675 * Please read comment there.
677 * NOT_RUNNING is clear. This means that trustee is not in
678 * charge and we're running on the local cpu w/ rq lock held
679 * and preemption disabled, which in turn means that none else
680 * could be manipulating idle_list, so dereferencing idle_list
681 * without gcwq lock is safe.
683 if (atomic_dec_and_test(nr_running) && !list_empty(&gcwq->worklist))
684 to_wakeup = first_worker(gcwq);
685 return to_wakeup ? to_wakeup->task : NULL;
689 * worker_set_flags - set worker flags and adjust nr_running accordingly
691 * @flags: flags to set
692 * @wakeup: wakeup an idle worker if necessary
694 * Set @flags in @worker->flags and adjust nr_running accordingly. If
695 * nr_running becomes zero and @wakeup is %true, an idle worker is
699 * spin_lock_irq(gcwq->lock)
701 static inline void worker_set_flags(struct worker *worker, unsigned int flags,
704 struct global_cwq *gcwq = worker->gcwq;
706 WARN_ON_ONCE(worker->task != current);
709 * If transitioning into NOT_RUNNING, adjust nr_running and
710 * wake up an idle worker as necessary if requested by
713 if ((flags & WORKER_NOT_RUNNING) &&
714 !(worker->flags & WORKER_NOT_RUNNING)) {
715 atomic_t *nr_running = get_gcwq_nr_running(gcwq->cpu);
718 if (atomic_dec_and_test(nr_running) &&
719 !list_empty(&gcwq->worklist))
720 wake_up_worker(gcwq);
722 atomic_dec(nr_running);
725 worker->flags |= flags;
729 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
731 * @flags: flags to clear
733 * Clear @flags in @worker->flags and adjust nr_running accordingly.
736 * spin_lock_irq(gcwq->lock)
738 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
740 struct global_cwq *gcwq = worker->gcwq;
741 unsigned int oflags = worker->flags;
743 WARN_ON_ONCE(worker->task != current);
745 worker->flags &= ~flags;
747 /* if transitioning out of NOT_RUNNING, increment nr_running */
748 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
749 if (!(worker->flags & WORKER_NOT_RUNNING))
750 atomic_inc(get_gcwq_nr_running(gcwq->cpu));
754 * busy_worker_head - return the busy hash head for a work
755 * @gcwq: gcwq of interest
756 * @work: work to be hashed
758 * Return hash head of @gcwq for @work.
761 * spin_lock_irq(gcwq->lock).
764 * Pointer to the hash head.
766 static struct hlist_head *busy_worker_head(struct global_cwq *gcwq,
767 struct work_struct *work)
769 const int base_shift = ilog2(sizeof(struct work_struct));
770 unsigned long v = (unsigned long)work;
772 /* simple shift and fold hash, do we need something better? */
774 v += v >> BUSY_WORKER_HASH_ORDER;
775 v &= BUSY_WORKER_HASH_MASK;
777 return &gcwq->busy_hash[v];
781 * __find_worker_executing_work - find worker which is executing a work
782 * @gcwq: gcwq of interest
783 * @bwh: hash head as returned by busy_worker_head()
784 * @work: work to find worker for
786 * Find a worker which is executing @work on @gcwq. @bwh should be
787 * the hash head obtained by calling busy_worker_head() with the same
791 * spin_lock_irq(gcwq->lock).
794 * Pointer to worker which is executing @work if found, NULL
797 static struct worker *__find_worker_executing_work(struct global_cwq *gcwq,
798 struct hlist_head *bwh,
799 struct work_struct *work)
801 struct worker *worker;
802 struct hlist_node *tmp;
804 hlist_for_each_entry(worker, tmp, bwh, hentry)
805 if (worker->current_work == work)
811 * find_worker_executing_work - find worker which is executing a work
812 * @gcwq: gcwq of interest
813 * @work: work to find worker for
815 * Find a worker which is executing @work on @gcwq. This function is
816 * identical to __find_worker_executing_work() except that this
817 * function calculates @bwh itself.
820 * spin_lock_irq(gcwq->lock).
823 * Pointer to worker which is executing @work if found, NULL
826 static struct worker *find_worker_executing_work(struct global_cwq *gcwq,
827 struct work_struct *work)
829 return __find_worker_executing_work(gcwq, busy_worker_head(gcwq, work),
834 * gcwq_determine_ins_pos - find insertion position
835 * @gcwq: gcwq of interest
836 * @cwq: cwq a work is being queued for
838 * A work for @cwq is about to be queued on @gcwq, determine insertion
839 * position for the work. If @cwq is for HIGHPRI wq, the work is
840 * queued at the head of the queue but in FIFO order with respect to
841 * other HIGHPRI works; otherwise, at the end of the queue. This
842 * function also sets GCWQ_HIGHPRI_PENDING flag to hint @gcwq that
843 * there are HIGHPRI works pending.
846 * spin_lock_irq(gcwq->lock).
849 * Pointer to inserstion position.
851 static inline struct list_head *gcwq_determine_ins_pos(struct global_cwq *gcwq,
852 struct cpu_workqueue_struct *cwq)
854 struct work_struct *twork;
856 if (likely(!(cwq->wq->flags & WQ_HIGHPRI)))
857 return &gcwq->worklist;
859 list_for_each_entry(twork, &gcwq->worklist, entry) {
860 struct cpu_workqueue_struct *tcwq = get_work_cwq(twork);
862 if (!(tcwq->wq->flags & WQ_HIGHPRI))
866 gcwq->flags |= GCWQ_HIGHPRI_PENDING;
867 return &twork->entry;
871 * insert_work - insert a work into gcwq
872 * @cwq: cwq @work belongs to
873 * @work: work to insert
874 * @head: insertion point
875 * @extra_flags: extra WORK_STRUCT_* flags to set
877 * Insert @work which belongs to @cwq into @gcwq after @head.
878 * @extra_flags is or'd to work_struct flags.
881 * spin_lock_irq(gcwq->lock).
883 static void insert_work(struct cpu_workqueue_struct *cwq,
884 struct work_struct *work, struct list_head *head,
885 unsigned int extra_flags)
887 struct global_cwq *gcwq = cwq->gcwq;
889 /* we own @work, set data and link */
890 set_work_cwq(work, cwq, extra_flags);
893 * Ensure that we get the right work->data if we see the
894 * result of list_add() below, see try_to_grab_pending().
898 list_add_tail(&work->entry, head);
901 * Ensure either worker_sched_deactivated() sees the above
902 * list_add_tail() or we see zero nr_running to avoid workers
903 * lying around lazily while there are works to be processed.
907 if (__need_more_worker(gcwq))
908 wake_up_worker(gcwq);
911 static void __queue_work(unsigned int cpu, struct workqueue_struct *wq,
912 struct work_struct *work)
914 struct global_cwq *gcwq;
915 struct cpu_workqueue_struct *cwq;
916 struct list_head *worklist;
919 debug_work_activate(work);
921 /* determine gcwq to use */
922 if (!(wq->flags & WQ_UNBOUND)) {
923 struct global_cwq *last_gcwq;
925 if (unlikely(cpu == WORK_CPU_UNBOUND))
926 cpu = raw_smp_processor_id();
929 * It's multi cpu. If @wq is non-reentrant and @work
930 * was previously on a different cpu, it might still
931 * be running there, in which case the work needs to
932 * be queued on that cpu to guarantee non-reentrance.
934 gcwq = get_gcwq(cpu);
935 if (wq->flags & WQ_NON_REENTRANT &&
936 (last_gcwq = get_work_gcwq(work)) && last_gcwq != gcwq) {
937 struct worker *worker;
939 spin_lock_irqsave(&last_gcwq->lock, flags);
941 worker = find_worker_executing_work(last_gcwq, work);
943 if (worker && worker->current_cwq->wq == wq)
946 /* meh... not running there, queue here */
947 spin_unlock_irqrestore(&last_gcwq->lock, flags);
948 spin_lock_irqsave(&gcwq->lock, flags);
951 spin_lock_irqsave(&gcwq->lock, flags);
953 gcwq = get_gcwq(WORK_CPU_UNBOUND);
954 spin_lock_irqsave(&gcwq->lock, flags);
957 /* gcwq determined, get cwq and queue */
958 cwq = get_cwq(gcwq->cpu, wq);
960 BUG_ON(!list_empty(&work->entry));
962 cwq->nr_in_flight[cwq->work_color]++;
964 if (likely(cwq->nr_active < cwq->max_active)) {
966 worklist = gcwq_determine_ins_pos(gcwq, cwq);
968 worklist = &cwq->delayed_works;
970 insert_work(cwq, work, worklist, work_color_to_flags(cwq->work_color));
972 spin_unlock_irqrestore(&gcwq->lock, flags);
976 * queue_work - queue work on a workqueue
977 * @wq: workqueue to use
978 * @work: work to queue
980 * Returns 0 if @work was already on a queue, non-zero otherwise.
982 * We queue the work to the CPU on which it was submitted, but if the CPU dies
983 * it can be processed by another CPU.
985 int queue_work(struct workqueue_struct *wq, struct work_struct *work)
989 ret = queue_work_on(get_cpu(), wq, work);
994 EXPORT_SYMBOL_GPL(queue_work);
997 * queue_work_on - queue work on specific cpu
998 * @cpu: CPU number to execute work on
999 * @wq: workqueue to use
1000 * @work: work to queue
1002 * Returns 0 if @work was already on a queue, non-zero otherwise.
1004 * We queue the work to a specific CPU, the caller must ensure it
1008 queue_work_on(int cpu, struct workqueue_struct *wq, struct work_struct *work)
1012 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1013 __queue_work(cpu, wq, work);
1018 EXPORT_SYMBOL_GPL(queue_work_on);
1020 static void delayed_work_timer_fn(unsigned long __data)
1022 struct delayed_work *dwork = (struct delayed_work *)__data;
1023 struct cpu_workqueue_struct *cwq = get_work_cwq(&dwork->work);
1025 __queue_work(smp_processor_id(), cwq->wq, &dwork->work);
1029 * queue_delayed_work - queue work on a workqueue after delay
1030 * @wq: workqueue to use
1031 * @dwork: delayable work to queue
1032 * @delay: number of jiffies to wait before queueing
1034 * Returns 0 if @work was already on a queue, non-zero otherwise.
1036 int queue_delayed_work(struct workqueue_struct *wq,
1037 struct delayed_work *dwork, unsigned long delay)
1040 return queue_work(wq, &dwork->work);
1042 return queue_delayed_work_on(-1, wq, dwork, delay);
1044 EXPORT_SYMBOL_GPL(queue_delayed_work);
1047 * queue_delayed_work_on - queue work on specific CPU after delay
1048 * @cpu: CPU number to execute work on
1049 * @wq: workqueue to use
1050 * @dwork: work to queue
1051 * @delay: number of jiffies to wait before queueing
1053 * Returns 0 if @work was already on a queue, non-zero otherwise.
1055 int queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1056 struct delayed_work *dwork, unsigned long delay)
1059 struct timer_list *timer = &dwork->timer;
1060 struct work_struct *work = &dwork->work;
1062 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1065 BUG_ON(timer_pending(timer));
1066 BUG_ON(!list_empty(&work->entry));
1068 timer_stats_timer_set_start_info(&dwork->timer);
1071 * This stores cwq for the moment, for the timer_fn.
1072 * Note that the work's gcwq is preserved to allow
1073 * reentrance detection for delayed works.
1075 if (!(wq->flags & WQ_UNBOUND)) {
1076 struct global_cwq *gcwq = get_work_gcwq(work);
1078 if (gcwq && gcwq->cpu != WORK_CPU_UNBOUND)
1081 lcpu = raw_smp_processor_id();
1083 lcpu = WORK_CPU_UNBOUND;
1085 set_work_cwq(work, get_cwq(lcpu, wq), 0);
1087 timer->expires = jiffies + delay;
1088 timer->data = (unsigned long)dwork;
1089 timer->function = delayed_work_timer_fn;
1091 if (unlikely(cpu >= 0))
1092 add_timer_on(timer, cpu);
1099 EXPORT_SYMBOL_GPL(queue_delayed_work_on);
1102 * worker_enter_idle - enter idle state
1103 * @worker: worker which is entering idle state
1105 * @worker is entering idle state. Update stats and idle timer if
1109 * spin_lock_irq(gcwq->lock).
1111 static void worker_enter_idle(struct worker *worker)
1113 struct global_cwq *gcwq = worker->gcwq;
1115 BUG_ON(worker->flags & WORKER_IDLE);
1116 BUG_ON(!list_empty(&worker->entry) &&
1117 (worker->hentry.next || worker->hentry.pprev));
1119 /* can't use worker_set_flags(), also called from start_worker() */
1120 worker->flags |= WORKER_IDLE;
1122 worker->last_active = jiffies;
1124 /* idle_list is LIFO */
1125 list_add(&worker->entry, &gcwq->idle_list);
1127 if (likely(!(worker->flags & WORKER_ROGUE))) {
1128 if (too_many_workers(gcwq) && !timer_pending(&gcwq->idle_timer))
1129 mod_timer(&gcwq->idle_timer,
1130 jiffies + IDLE_WORKER_TIMEOUT);
1132 wake_up_all(&gcwq->trustee_wait);
1134 /* sanity check nr_running */
1135 WARN_ON_ONCE(gcwq->nr_workers == gcwq->nr_idle &&
1136 atomic_read(get_gcwq_nr_running(gcwq->cpu)));
1140 * worker_leave_idle - leave idle state
1141 * @worker: worker which is leaving idle state
1143 * @worker is leaving idle state. Update stats.
1146 * spin_lock_irq(gcwq->lock).
1148 static void worker_leave_idle(struct worker *worker)
1150 struct global_cwq *gcwq = worker->gcwq;
1152 BUG_ON(!(worker->flags & WORKER_IDLE));
1153 worker_clr_flags(worker, WORKER_IDLE);
1155 list_del_init(&worker->entry);
1159 * worker_maybe_bind_and_lock - bind worker to its cpu if possible and lock gcwq
1162 * Works which are scheduled while the cpu is online must at least be
1163 * scheduled to a worker which is bound to the cpu so that if they are
1164 * flushed from cpu callbacks while cpu is going down, they are
1165 * guaranteed to execute on the cpu.
1167 * This function is to be used by rogue workers and rescuers to bind
1168 * themselves to the target cpu and may race with cpu going down or
1169 * coming online. kthread_bind() can't be used because it may put the
1170 * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1171 * verbatim as it's best effort and blocking and gcwq may be
1172 * [dis]associated in the meantime.
1174 * This function tries set_cpus_allowed() and locks gcwq and verifies
1175 * the binding against GCWQ_DISASSOCIATED which is set during
1176 * CPU_DYING and cleared during CPU_ONLINE, so if the worker enters
1177 * idle state or fetches works without dropping lock, it can guarantee
1178 * the scheduling requirement described in the first paragraph.
1181 * Might sleep. Called without any lock but returns with gcwq->lock
1185 * %true if the associated gcwq is online (@worker is successfully
1186 * bound), %false if offline.
1188 static bool worker_maybe_bind_and_lock(struct worker *worker)
1190 struct global_cwq *gcwq = worker->gcwq;
1191 struct task_struct *task = worker->task;
1195 * The following call may fail, succeed or succeed
1196 * without actually migrating the task to the cpu if
1197 * it races with cpu hotunplug operation. Verify
1198 * against GCWQ_DISASSOCIATED.
1200 if (!(gcwq->flags & GCWQ_DISASSOCIATED))
1201 set_cpus_allowed_ptr(task, get_cpu_mask(gcwq->cpu));
1203 spin_lock_irq(&gcwq->lock);
1204 if (gcwq->flags & GCWQ_DISASSOCIATED)
1206 if (task_cpu(task) == gcwq->cpu &&
1207 cpumask_equal(¤t->cpus_allowed,
1208 get_cpu_mask(gcwq->cpu)))
1210 spin_unlock_irq(&gcwq->lock);
1212 /* CPU has come up inbetween, retry migration */
1218 * Function for worker->rebind_work used to rebind rogue busy workers
1219 * to the associated cpu which is coming back online. This is
1220 * scheduled by cpu up but can race with other cpu hotplug operations
1221 * and may be executed twice without intervening cpu down.
1223 static void worker_rebind_fn(struct work_struct *work)
1225 struct worker *worker = container_of(work, struct worker, rebind_work);
1226 struct global_cwq *gcwq = worker->gcwq;
1228 if (worker_maybe_bind_and_lock(worker))
1229 worker_clr_flags(worker, WORKER_REBIND);
1231 spin_unlock_irq(&gcwq->lock);
1234 static struct worker *alloc_worker(void)
1236 struct worker *worker;
1238 worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1240 INIT_LIST_HEAD(&worker->entry);
1241 INIT_LIST_HEAD(&worker->scheduled);
1242 INIT_WORK(&worker->rebind_work, worker_rebind_fn);
1243 /* on creation a worker is in !idle && prep state */
1244 worker->flags = WORKER_PREP;
1250 * create_worker - create a new workqueue worker
1251 * @gcwq: gcwq the new worker will belong to
1252 * @bind: whether to set affinity to @cpu or not
1254 * Create a new worker which is bound to @gcwq. The returned worker
1255 * can be started by calling start_worker() or destroyed using
1259 * Might sleep. Does GFP_KERNEL allocations.
1262 * Pointer to the newly created worker.
1264 static struct worker *create_worker(struct global_cwq *gcwq, bool bind)
1266 bool on_unbound_cpu = gcwq->cpu == WORK_CPU_UNBOUND;
1267 struct worker *worker = NULL;
1270 spin_lock_irq(&gcwq->lock);
1271 while (ida_get_new(&gcwq->worker_ida, &id)) {
1272 spin_unlock_irq(&gcwq->lock);
1273 if (!ida_pre_get(&gcwq->worker_ida, GFP_KERNEL))
1275 spin_lock_irq(&gcwq->lock);
1277 spin_unlock_irq(&gcwq->lock);
1279 worker = alloc_worker();
1283 worker->gcwq = gcwq;
1286 if (!on_unbound_cpu)
1287 worker->task = kthread_create(worker_thread, worker,
1288 "kworker/%u:%d", gcwq->cpu, id);
1290 worker->task = kthread_create(worker_thread, worker,
1291 "kworker/u:%d", id);
1292 if (IS_ERR(worker->task))
1296 * A rogue worker will become a regular one if CPU comes
1297 * online later on. Make sure every worker has
1298 * PF_THREAD_BOUND set.
1300 if (bind && !on_unbound_cpu)
1301 kthread_bind(worker->task, gcwq->cpu);
1303 worker->task->flags |= PF_THREAD_BOUND;
1305 worker->flags |= WORKER_UNBOUND;
1311 spin_lock_irq(&gcwq->lock);
1312 ida_remove(&gcwq->worker_ida, id);
1313 spin_unlock_irq(&gcwq->lock);
1320 * start_worker - start a newly created worker
1321 * @worker: worker to start
1323 * Make the gcwq aware of @worker and start it.
1326 * spin_lock_irq(gcwq->lock).
1328 static void start_worker(struct worker *worker)
1330 worker->flags |= WORKER_STARTED;
1331 worker->gcwq->nr_workers++;
1332 worker_enter_idle(worker);
1333 wake_up_process(worker->task);
1337 * destroy_worker - destroy a workqueue worker
1338 * @worker: worker to be destroyed
1340 * Destroy @worker and adjust @gcwq stats accordingly.
1343 * spin_lock_irq(gcwq->lock) which is released and regrabbed.
1345 static void destroy_worker(struct worker *worker)
1347 struct global_cwq *gcwq = worker->gcwq;
1348 int id = worker->id;
1350 /* sanity check frenzy */
1351 BUG_ON(worker->current_work);
1352 BUG_ON(!list_empty(&worker->scheduled));
1354 if (worker->flags & WORKER_STARTED)
1356 if (worker->flags & WORKER_IDLE)
1359 list_del_init(&worker->entry);
1360 worker->flags |= WORKER_DIE;
1362 spin_unlock_irq(&gcwq->lock);
1364 kthread_stop(worker->task);
1367 spin_lock_irq(&gcwq->lock);
1368 ida_remove(&gcwq->worker_ida, id);
1371 static void idle_worker_timeout(unsigned long __gcwq)
1373 struct global_cwq *gcwq = (void *)__gcwq;
1375 spin_lock_irq(&gcwq->lock);
1377 if (too_many_workers(gcwq)) {
1378 struct worker *worker;
1379 unsigned long expires;
1381 /* idle_list is kept in LIFO order, check the last one */
1382 worker = list_entry(gcwq->idle_list.prev, struct worker, entry);
1383 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1385 if (time_before(jiffies, expires))
1386 mod_timer(&gcwq->idle_timer, expires);
1388 /* it's been idle for too long, wake up manager */
1389 gcwq->flags |= GCWQ_MANAGE_WORKERS;
1390 wake_up_worker(gcwq);
1394 spin_unlock_irq(&gcwq->lock);
1397 static bool send_mayday(struct work_struct *work)
1399 struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1400 struct workqueue_struct *wq = cwq->wq;
1403 if (!(wq->flags & WQ_RESCUER))
1406 /* mayday mayday mayday */
1407 cpu = cwq->gcwq->cpu;
1408 /* WORK_CPU_UNBOUND can't be set in cpumask, use cpu 0 instead */
1409 if (cpu == WORK_CPU_UNBOUND)
1411 if (!mayday_test_and_set_cpu(cpu, wq->mayday_mask))
1412 wake_up_process(wq->rescuer->task);
1416 static void gcwq_mayday_timeout(unsigned long __gcwq)
1418 struct global_cwq *gcwq = (void *)__gcwq;
1419 struct work_struct *work;
1421 spin_lock_irq(&gcwq->lock);
1423 if (need_to_create_worker(gcwq)) {
1425 * We've been trying to create a new worker but
1426 * haven't been successful. We might be hitting an
1427 * allocation deadlock. Send distress signals to
1430 list_for_each_entry(work, &gcwq->worklist, entry)
1434 spin_unlock_irq(&gcwq->lock);
1436 mod_timer(&gcwq->mayday_timer, jiffies + MAYDAY_INTERVAL);
1440 * maybe_create_worker - create a new worker if necessary
1441 * @gcwq: gcwq to create a new worker for
1443 * Create a new worker for @gcwq if necessary. @gcwq is guaranteed to
1444 * have at least one idle worker on return from this function. If
1445 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1446 * sent to all rescuers with works scheduled on @gcwq to resolve
1447 * possible allocation deadlock.
1449 * On return, need_to_create_worker() is guaranteed to be false and
1450 * may_start_working() true.
1453 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1454 * multiple times. Does GFP_KERNEL allocations. Called only from
1458 * false if no action was taken and gcwq->lock stayed locked, true
1461 static bool maybe_create_worker(struct global_cwq *gcwq)
1463 if (!need_to_create_worker(gcwq))
1466 spin_unlock_irq(&gcwq->lock);
1468 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1469 mod_timer(&gcwq->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1472 struct worker *worker;
1474 worker = create_worker(gcwq, true);
1476 del_timer_sync(&gcwq->mayday_timer);
1477 spin_lock_irq(&gcwq->lock);
1478 start_worker(worker);
1479 BUG_ON(need_to_create_worker(gcwq));
1483 if (!need_to_create_worker(gcwq))
1486 __set_current_state(TASK_INTERRUPTIBLE);
1487 schedule_timeout(CREATE_COOLDOWN);
1489 if (!need_to_create_worker(gcwq))
1493 del_timer_sync(&gcwq->mayday_timer);
1494 spin_lock_irq(&gcwq->lock);
1495 if (need_to_create_worker(gcwq))
1501 * maybe_destroy_worker - destroy workers which have been idle for a while
1502 * @gcwq: gcwq to destroy workers for
1504 * Destroy @gcwq workers which have been idle for longer than
1505 * IDLE_WORKER_TIMEOUT.
1508 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1509 * multiple times. Called only from manager.
1512 * false if no action was taken and gcwq->lock stayed locked, true
1515 static bool maybe_destroy_workers(struct global_cwq *gcwq)
1519 while (too_many_workers(gcwq)) {
1520 struct worker *worker;
1521 unsigned long expires;
1523 worker = list_entry(gcwq->idle_list.prev, struct worker, entry);
1524 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1526 if (time_before(jiffies, expires)) {
1527 mod_timer(&gcwq->idle_timer, expires);
1531 destroy_worker(worker);
1539 * manage_workers - manage worker pool
1542 * Assume the manager role and manage gcwq worker pool @worker belongs
1543 * to. At any given time, there can be only zero or one manager per
1544 * gcwq. The exclusion is handled automatically by this function.
1546 * The caller can safely start processing works on false return. On
1547 * true return, it's guaranteed that need_to_create_worker() is false
1548 * and may_start_working() is true.
1551 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1552 * multiple times. Does GFP_KERNEL allocations.
1555 * false if no action was taken and gcwq->lock stayed locked, true if
1556 * some action was taken.
1558 static bool manage_workers(struct worker *worker)
1560 struct global_cwq *gcwq = worker->gcwq;
1563 if (gcwq->flags & GCWQ_MANAGING_WORKERS)
1566 gcwq->flags &= ~GCWQ_MANAGE_WORKERS;
1567 gcwq->flags |= GCWQ_MANAGING_WORKERS;
1570 * Destroy and then create so that may_start_working() is true
1573 ret |= maybe_destroy_workers(gcwq);
1574 ret |= maybe_create_worker(gcwq);
1576 gcwq->flags &= ~GCWQ_MANAGING_WORKERS;
1579 * The trustee might be waiting to take over the manager
1580 * position, tell it we're done.
1582 if (unlikely(gcwq->trustee))
1583 wake_up_all(&gcwq->trustee_wait);
1589 * move_linked_works - move linked works to a list
1590 * @work: start of series of works to be scheduled
1591 * @head: target list to append @work to
1592 * @nextp: out paramter for nested worklist walking
1594 * Schedule linked works starting from @work to @head. Work series to
1595 * be scheduled starts at @work and includes any consecutive work with
1596 * WORK_STRUCT_LINKED set in its predecessor.
1598 * If @nextp is not NULL, it's updated to point to the next work of
1599 * the last scheduled work. This allows move_linked_works() to be
1600 * nested inside outer list_for_each_entry_safe().
1603 * spin_lock_irq(gcwq->lock).
1605 static void move_linked_works(struct work_struct *work, struct list_head *head,
1606 struct work_struct **nextp)
1608 struct work_struct *n;
1611 * Linked worklist will always end before the end of the list,
1612 * use NULL for list head.
1614 list_for_each_entry_safe_from(work, n, NULL, entry) {
1615 list_move_tail(&work->entry, head);
1616 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1621 * If we're already inside safe list traversal and have moved
1622 * multiple works to the scheduled queue, the next position
1623 * needs to be updated.
1629 static void cwq_activate_first_delayed(struct cpu_workqueue_struct *cwq)
1631 struct work_struct *work = list_first_entry(&cwq->delayed_works,
1632 struct work_struct, entry);
1633 struct list_head *pos = gcwq_determine_ins_pos(cwq->gcwq, cwq);
1635 move_linked_works(work, pos, NULL);
1640 * cwq_dec_nr_in_flight - decrement cwq's nr_in_flight
1641 * @cwq: cwq of interest
1642 * @color: color of work which left the queue
1644 * A work either has completed or is removed from pending queue,
1645 * decrement nr_in_flight of its cwq and handle workqueue flushing.
1648 * spin_lock_irq(gcwq->lock).
1650 static void cwq_dec_nr_in_flight(struct cpu_workqueue_struct *cwq, int color)
1652 /* ignore uncolored works */
1653 if (color == WORK_NO_COLOR)
1656 cwq->nr_in_flight[color]--;
1659 if (!list_empty(&cwq->delayed_works)) {
1660 /* one down, submit a delayed one */
1661 if (cwq->nr_active < cwq->max_active)
1662 cwq_activate_first_delayed(cwq);
1665 /* is flush in progress and are we at the flushing tip? */
1666 if (likely(cwq->flush_color != color))
1669 /* are there still in-flight works? */
1670 if (cwq->nr_in_flight[color])
1673 /* this cwq is done, clear flush_color */
1674 cwq->flush_color = -1;
1677 * If this was the last cwq, wake up the first flusher. It
1678 * will handle the rest.
1680 if (atomic_dec_and_test(&cwq->wq->nr_cwqs_to_flush))
1681 complete(&cwq->wq->first_flusher->done);
1685 * process_one_work - process single work
1687 * @work: work to process
1689 * Process @work. This function contains all the logics necessary to
1690 * process a single work including synchronization against and
1691 * interaction with other workers on the same cpu, queueing and
1692 * flushing. As long as context requirement is met, any worker can
1693 * call this function to process a work.
1696 * spin_lock_irq(gcwq->lock) which is released and regrabbed.
1698 static void process_one_work(struct worker *worker, struct work_struct *work)
1700 struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1701 struct global_cwq *gcwq = cwq->gcwq;
1702 struct hlist_head *bwh = busy_worker_head(gcwq, work);
1703 bool cpu_intensive = cwq->wq->flags & WQ_CPU_INTENSIVE;
1704 work_func_t f = work->func;
1706 struct worker *collision;
1707 #ifdef CONFIG_LOCKDEP
1709 * It is permissible to free the struct work_struct from
1710 * inside the function that is called from it, this we need to
1711 * take into account for lockdep too. To avoid bogus "held
1712 * lock freed" warnings as well as problems when looking into
1713 * work->lockdep_map, make a copy and use that here.
1715 struct lockdep_map lockdep_map = work->lockdep_map;
1718 * A single work shouldn't be executed concurrently by
1719 * multiple workers on a single cpu. Check whether anyone is
1720 * already processing the work. If so, defer the work to the
1721 * currently executing one.
1723 collision = __find_worker_executing_work(gcwq, bwh, work);
1724 if (unlikely(collision)) {
1725 move_linked_works(work, &collision->scheduled, NULL);
1729 /* claim and process */
1730 debug_work_deactivate(work);
1731 hlist_add_head(&worker->hentry, bwh);
1732 worker->current_work = work;
1733 worker->current_cwq = cwq;
1734 work_color = get_work_color(work);
1736 /* record the current cpu number in the work data and dequeue */
1737 set_work_cpu(work, gcwq->cpu);
1738 list_del_init(&work->entry);
1741 * If HIGHPRI_PENDING, check the next work, and, if HIGHPRI,
1742 * wake up another worker; otherwise, clear HIGHPRI_PENDING.
1744 if (unlikely(gcwq->flags & GCWQ_HIGHPRI_PENDING)) {
1745 struct work_struct *nwork = list_first_entry(&gcwq->worklist,
1746 struct work_struct, entry);
1748 if (!list_empty(&gcwq->worklist) &&
1749 get_work_cwq(nwork)->wq->flags & WQ_HIGHPRI)
1750 wake_up_worker(gcwq);
1752 gcwq->flags &= ~GCWQ_HIGHPRI_PENDING;
1756 * CPU intensive works don't participate in concurrency
1757 * management. They're the scheduler's responsibility.
1759 if (unlikely(cpu_intensive))
1760 worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
1762 spin_unlock_irq(&gcwq->lock);
1764 work_clear_pending(work);
1765 lock_map_acquire(&cwq->wq->lockdep_map);
1766 lock_map_acquire(&lockdep_map);
1768 lock_map_release(&lockdep_map);
1769 lock_map_release(&cwq->wq->lockdep_map);
1771 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
1772 printk(KERN_ERR "BUG: workqueue leaked lock or atomic: "
1774 current->comm, preempt_count(), task_pid_nr(current));
1775 printk(KERN_ERR " last function: ");
1776 print_symbol("%s\n", (unsigned long)f);
1777 debug_show_held_locks(current);
1781 spin_lock_irq(&gcwq->lock);
1783 /* clear cpu intensive status */
1784 if (unlikely(cpu_intensive))
1785 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
1787 /* we're done with it, release */
1788 hlist_del_init(&worker->hentry);
1789 worker->current_work = NULL;
1790 worker->current_cwq = NULL;
1791 cwq_dec_nr_in_flight(cwq, work_color);
1795 * process_scheduled_works - process scheduled works
1798 * Process all scheduled works. Please note that the scheduled list
1799 * may change while processing a work, so this function repeatedly
1800 * fetches a work from the top and executes it.
1803 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1806 static void process_scheduled_works(struct worker *worker)
1808 while (!list_empty(&worker->scheduled)) {
1809 struct work_struct *work = list_first_entry(&worker->scheduled,
1810 struct work_struct, entry);
1811 process_one_work(worker, work);
1816 * worker_thread - the worker thread function
1819 * The gcwq worker thread function. There's a single dynamic pool of
1820 * these per each cpu. These workers process all works regardless of
1821 * their specific target workqueue. The only exception is works which
1822 * belong to workqueues with a rescuer which will be explained in
1825 static int worker_thread(void *__worker)
1827 struct worker *worker = __worker;
1828 struct global_cwq *gcwq = worker->gcwq;
1830 /* tell the scheduler that this is a workqueue worker */
1831 worker->task->flags |= PF_WQ_WORKER;
1833 spin_lock_irq(&gcwq->lock);
1835 /* DIE can be set only while we're idle, checking here is enough */
1836 if (worker->flags & WORKER_DIE) {
1837 spin_unlock_irq(&gcwq->lock);
1838 worker->task->flags &= ~PF_WQ_WORKER;
1842 worker_leave_idle(worker);
1844 /* no more worker necessary? */
1845 if (!need_more_worker(gcwq))
1848 /* do we need to manage? */
1849 if (unlikely(!may_start_working(gcwq)) && manage_workers(worker))
1853 * ->scheduled list can only be filled while a worker is
1854 * preparing to process a work or actually processing it.
1855 * Make sure nobody diddled with it while I was sleeping.
1857 BUG_ON(!list_empty(&worker->scheduled));
1860 * When control reaches this point, we're guaranteed to have
1861 * at least one idle worker or that someone else has already
1862 * assumed the manager role.
1864 worker_clr_flags(worker, WORKER_PREP);
1867 struct work_struct *work =
1868 list_first_entry(&gcwq->worklist,
1869 struct work_struct, entry);
1871 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
1872 /* optimization path, not strictly necessary */
1873 process_one_work(worker, work);
1874 if (unlikely(!list_empty(&worker->scheduled)))
1875 process_scheduled_works(worker);
1877 move_linked_works(work, &worker->scheduled, NULL);
1878 process_scheduled_works(worker);
1880 } while (keep_working(gcwq));
1882 worker_set_flags(worker, WORKER_PREP, false);
1884 if (unlikely(need_to_manage_workers(gcwq)) && manage_workers(worker))
1888 * gcwq->lock is held and there's no work to process and no
1889 * need to manage, sleep. Workers are woken up only while
1890 * holding gcwq->lock or from local cpu, so setting the
1891 * current state before releasing gcwq->lock is enough to
1892 * prevent losing any event.
1894 worker_enter_idle(worker);
1895 __set_current_state(TASK_INTERRUPTIBLE);
1896 spin_unlock_irq(&gcwq->lock);
1902 * rescuer_thread - the rescuer thread function
1903 * @__wq: the associated workqueue
1905 * Workqueue rescuer thread function. There's one rescuer for each
1906 * workqueue which has WQ_RESCUER set.
1908 * Regular work processing on a gcwq may block trying to create a new
1909 * worker which uses GFP_KERNEL allocation which has slight chance of
1910 * developing into deadlock if some works currently on the same queue
1911 * need to be processed to satisfy the GFP_KERNEL allocation. This is
1912 * the problem rescuer solves.
1914 * When such condition is possible, the gcwq summons rescuers of all
1915 * workqueues which have works queued on the gcwq and let them process
1916 * those works so that forward progress can be guaranteed.
1918 * This should happen rarely.
1920 static int rescuer_thread(void *__wq)
1922 struct workqueue_struct *wq = __wq;
1923 struct worker *rescuer = wq->rescuer;
1924 struct list_head *scheduled = &rescuer->scheduled;
1925 bool is_unbound = wq->flags & WQ_UNBOUND;
1928 set_user_nice(current, RESCUER_NICE_LEVEL);
1930 set_current_state(TASK_INTERRUPTIBLE);
1932 if (kthread_should_stop())
1936 * See whether any cpu is asking for help. Unbounded
1937 * workqueues use cpu 0 in mayday_mask for CPU_UNBOUND.
1939 for_each_mayday_cpu(cpu, wq->mayday_mask) {
1940 unsigned int tcpu = is_unbound ? WORK_CPU_UNBOUND : cpu;
1941 struct cpu_workqueue_struct *cwq = get_cwq(tcpu, wq);
1942 struct global_cwq *gcwq = cwq->gcwq;
1943 struct work_struct *work, *n;
1945 __set_current_state(TASK_RUNNING);
1946 mayday_clear_cpu(cpu, wq->mayday_mask);
1948 /* migrate to the target cpu if possible */
1949 rescuer->gcwq = gcwq;
1950 worker_maybe_bind_and_lock(rescuer);
1953 * Slurp in all works issued via this workqueue and
1956 BUG_ON(!list_empty(&rescuer->scheduled));
1957 list_for_each_entry_safe(work, n, &gcwq->worklist, entry)
1958 if (get_work_cwq(work) == cwq)
1959 move_linked_works(work, scheduled, &n);
1961 process_scheduled_works(rescuer);
1962 spin_unlock_irq(&gcwq->lock);
1970 struct work_struct work;
1971 struct completion done;
1974 static void wq_barrier_func(struct work_struct *work)
1976 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
1977 complete(&barr->done);
1981 * insert_wq_barrier - insert a barrier work
1982 * @cwq: cwq to insert barrier into
1983 * @barr: wq_barrier to insert
1984 * @target: target work to attach @barr to
1985 * @worker: worker currently executing @target, NULL if @target is not executing
1987 * @barr is linked to @target such that @barr is completed only after
1988 * @target finishes execution. Please note that the ordering
1989 * guarantee is observed only with respect to @target and on the local
1992 * Currently, a queued barrier can't be canceled. This is because
1993 * try_to_grab_pending() can't determine whether the work to be
1994 * grabbed is at the head of the queue and thus can't clear LINKED
1995 * flag of the previous work while there must be a valid next work
1996 * after a work with LINKED flag set.
1998 * Note that when @worker is non-NULL, @target may be modified
1999 * underneath us, so we can't reliably determine cwq from @target.
2002 * spin_lock_irq(gcwq->lock).
2004 static void insert_wq_barrier(struct cpu_workqueue_struct *cwq,
2005 struct wq_barrier *barr,
2006 struct work_struct *target, struct worker *worker)
2008 struct list_head *head;
2009 unsigned int linked = 0;
2012 * debugobject calls are safe here even with gcwq->lock locked
2013 * as we know for sure that this will not trigger any of the
2014 * checks and call back into the fixup functions where we
2017 INIT_WORK_ON_STACK(&barr->work, wq_barrier_func);
2018 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2019 init_completion(&barr->done);
2022 * If @target is currently being executed, schedule the
2023 * barrier to the worker; otherwise, put it after @target.
2026 head = worker->scheduled.next;
2028 unsigned long *bits = work_data_bits(target);
2030 head = target->entry.next;
2031 /* there can already be other linked works, inherit and set */
2032 linked = *bits & WORK_STRUCT_LINKED;
2033 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2036 debug_work_activate(&barr->work);
2037 insert_work(cwq, &barr->work, head,
2038 work_color_to_flags(WORK_NO_COLOR) | linked);
2042 * flush_workqueue_prep_cwqs - prepare cwqs for workqueue flushing
2043 * @wq: workqueue being flushed
2044 * @flush_color: new flush color, < 0 for no-op
2045 * @work_color: new work color, < 0 for no-op
2047 * Prepare cwqs for workqueue flushing.
2049 * If @flush_color is non-negative, flush_color on all cwqs should be
2050 * -1. If no cwq has in-flight commands at the specified color, all
2051 * cwq->flush_color's stay at -1 and %false is returned. If any cwq
2052 * has in flight commands, its cwq->flush_color is set to
2053 * @flush_color, @wq->nr_cwqs_to_flush is updated accordingly, cwq
2054 * wakeup logic is armed and %true is returned.
2056 * The caller should have initialized @wq->first_flusher prior to
2057 * calling this function with non-negative @flush_color. If
2058 * @flush_color is negative, no flush color update is done and %false
2061 * If @work_color is non-negative, all cwqs should have the same
2062 * work_color which is previous to @work_color and all will be
2063 * advanced to @work_color.
2066 * mutex_lock(wq->flush_mutex).
2069 * %true if @flush_color >= 0 and there's something to flush. %false
2072 static bool flush_workqueue_prep_cwqs(struct workqueue_struct *wq,
2073 int flush_color, int work_color)
2078 if (flush_color >= 0) {
2079 BUG_ON(atomic_read(&wq->nr_cwqs_to_flush));
2080 atomic_set(&wq->nr_cwqs_to_flush, 1);
2083 for_each_cwq_cpu(cpu, wq) {
2084 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2085 struct global_cwq *gcwq = cwq->gcwq;
2087 spin_lock_irq(&gcwq->lock);
2089 if (flush_color >= 0) {
2090 BUG_ON(cwq->flush_color != -1);
2092 if (cwq->nr_in_flight[flush_color]) {
2093 cwq->flush_color = flush_color;
2094 atomic_inc(&wq->nr_cwqs_to_flush);
2099 if (work_color >= 0) {
2100 BUG_ON(work_color != work_next_color(cwq->work_color));
2101 cwq->work_color = work_color;
2104 spin_unlock_irq(&gcwq->lock);
2107 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_cwqs_to_flush))
2108 complete(&wq->first_flusher->done);
2114 * flush_workqueue - ensure that any scheduled work has run to completion.
2115 * @wq: workqueue to flush
2117 * Forces execution of the workqueue and blocks until its completion.
2118 * This is typically used in driver shutdown handlers.
2120 * We sleep until all works which were queued on entry have been handled,
2121 * but we are not livelocked by new incoming ones.
2123 void flush_workqueue(struct workqueue_struct *wq)
2125 struct wq_flusher this_flusher = {
2126 .list = LIST_HEAD_INIT(this_flusher.list),
2128 .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
2132 lock_map_acquire(&wq->lockdep_map);
2133 lock_map_release(&wq->lockdep_map);
2135 mutex_lock(&wq->flush_mutex);
2138 * Start-to-wait phase
2140 next_color = work_next_color(wq->work_color);
2142 if (next_color != wq->flush_color) {
2144 * Color space is not full. The current work_color
2145 * becomes our flush_color and work_color is advanced
2148 BUG_ON(!list_empty(&wq->flusher_overflow));
2149 this_flusher.flush_color = wq->work_color;
2150 wq->work_color = next_color;
2152 if (!wq->first_flusher) {
2153 /* no flush in progress, become the first flusher */
2154 BUG_ON(wq->flush_color != this_flusher.flush_color);
2156 wq->first_flusher = &this_flusher;
2158 if (!flush_workqueue_prep_cwqs(wq, wq->flush_color,
2160 /* nothing to flush, done */
2161 wq->flush_color = next_color;
2162 wq->first_flusher = NULL;
2167 BUG_ON(wq->flush_color == this_flusher.flush_color);
2168 list_add_tail(&this_flusher.list, &wq->flusher_queue);
2169 flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2173 * Oops, color space is full, wait on overflow queue.
2174 * The next flush completion will assign us
2175 * flush_color and transfer to flusher_queue.
2177 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2180 mutex_unlock(&wq->flush_mutex);
2182 wait_for_completion(&this_flusher.done);
2185 * Wake-up-and-cascade phase
2187 * First flushers are responsible for cascading flushes and
2188 * handling overflow. Non-first flushers can simply return.
2190 if (wq->first_flusher != &this_flusher)
2193 mutex_lock(&wq->flush_mutex);
2195 /* we might have raced, check again with mutex held */
2196 if (wq->first_flusher != &this_flusher)
2199 wq->first_flusher = NULL;
2201 BUG_ON(!list_empty(&this_flusher.list));
2202 BUG_ON(wq->flush_color != this_flusher.flush_color);
2205 struct wq_flusher *next, *tmp;
2207 /* complete all the flushers sharing the current flush color */
2208 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2209 if (next->flush_color != wq->flush_color)
2211 list_del_init(&next->list);
2212 complete(&next->done);
2215 BUG_ON(!list_empty(&wq->flusher_overflow) &&
2216 wq->flush_color != work_next_color(wq->work_color));
2218 /* this flush_color is finished, advance by one */
2219 wq->flush_color = work_next_color(wq->flush_color);
2221 /* one color has been freed, handle overflow queue */
2222 if (!list_empty(&wq->flusher_overflow)) {
2224 * Assign the same color to all overflowed
2225 * flushers, advance work_color and append to
2226 * flusher_queue. This is the start-to-wait
2227 * phase for these overflowed flushers.
2229 list_for_each_entry(tmp, &wq->flusher_overflow, list)
2230 tmp->flush_color = wq->work_color;
2232 wq->work_color = work_next_color(wq->work_color);
2234 list_splice_tail_init(&wq->flusher_overflow,
2235 &wq->flusher_queue);
2236 flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2239 if (list_empty(&wq->flusher_queue)) {
2240 BUG_ON(wq->flush_color != wq->work_color);
2245 * Need to flush more colors. Make the next flusher
2246 * the new first flusher and arm cwqs.
2248 BUG_ON(wq->flush_color == wq->work_color);
2249 BUG_ON(wq->flush_color != next->flush_color);
2251 list_del_init(&next->list);
2252 wq->first_flusher = next;
2254 if (flush_workqueue_prep_cwqs(wq, wq->flush_color, -1))
2258 * Meh... this color is already done, clear first
2259 * flusher and repeat cascading.
2261 wq->first_flusher = NULL;
2265 mutex_unlock(&wq->flush_mutex);
2267 EXPORT_SYMBOL_GPL(flush_workqueue);
2270 * flush_work - block until a work_struct's callback has terminated
2271 * @work: the work which is to be flushed
2273 * Returns false if @work has already terminated.
2275 * It is expected that, prior to calling flush_work(), the caller has
2276 * arranged for the work to not be requeued, otherwise it doesn't make
2277 * sense to use this function.
2279 int flush_work(struct work_struct *work)
2281 struct worker *worker = NULL;
2282 struct global_cwq *gcwq;
2283 struct cpu_workqueue_struct *cwq;
2284 struct wq_barrier barr;
2287 gcwq = get_work_gcwq(work);
2291 spin_lock_irq(&gcwq->lock);
2292 if (!list_empty(&work->entry)) {
2294 * See the comment near try_to_grab_pending()->smp_rmb().
2295 * If it was re-queued to a different gcwq under us, we
2296 * are not going to wait.
2299 cwq = get_work_cwq(work);
2300 if (unlikely(!cwq || gcwq != cwq->gcwq))
2303 worker = find_worker_executing_work(gcwq, work);
2306 cwq = worker->current_cwq;
2309 insert_wq_barrier(cwq, &barr, work, worker);
2310 spin_unlock_irq(&gcwq->lock);
2312 lock_map_acquire(&cwq->wq->lockdep_map);
2313 lock_map_release(&cwq->wq->lockdep_map);
2315 wait_for_completion(&barr.done);
2316 destroy_work_on_stack(&barr.work);
2319 spin_unlock_irq(&gcwq->lock);
2322 EXPORT_SYMBOL_GPL(flush_work);
2325 * Upon a successful return (>= 0), the caller "owns" WORK_STRUCT_PENDING bit,
2326 * so this work can't be re-armed in any way.
2328 static int try_to_grab_pending(struct work_struct *work)
2330 struct global_cwq *gcwq;
2333 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
2337 * The queueing is in progress, or it is already queued. Try to
2338 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
2340 gcwq = get_work_gcwq(work);
2344 spin_lock_irq(&gcwq->lock);
2345 if (!list_empty(&work->entry)) {
2347 * This work is queued, but perhaps we locked the wrong gcwq.
2348 * In that case we must see the new value after rmb(), see
2349 * insert_work()->wmb().
2352 if (gcwq == get_work_gcwq(work)) {
2353 debug_work_deactivate(work);
2354 list_del_init(&work->entry);
2355 cwq_dec_nr_in_flight(get_work_cwq(work),
2356 get_work_color(work));
2360 spin_unlock_irq(&gcwq->lock);
2365 static void wait_on_cpu_work(struct global_cwq *gcwq, struct work_struct *work)
2367 struct wq_barrier barr;
2368 struct worker *worker;
2370 spin_lock_irq(&gcwq->lock);
2372 worker = find_worker_executing_work(gcwq, work);
2373 if (unlikely(worker))
2374 insert_wq_barrier(worker->current_cwq, &barr, work, worker);
2376 spin_unlock_irq(&gcwq->lock);
2378 if (unlikely(worker)) {
2379 wait_for_completion(&barr.done);
2380 destroy_work_on_stack(&barr.work);
2384 static void wait_on_work(struct work_struct *work)
2390 lock_map_acquire(&work->lockdep_map);
2391 lock_map_release(&work->lockdep_map);
2393 for_each_gcwq_cpu(cpu)
2394 wait_on_cpu_work(get_gcwq(cpu), work);
2397 static int __cancel_work_timer(struct work_struct *work,
2398 struct timer_list* timer)
2403 ret = (timer && likely(del_timer(timer)));
2405 ret = try_to_grab_pending(work);
2407 } while (unlikely(ret < 0));
2409 clear_work_data(work);
2414 * cancel_work_sync - block until a work_struct's callback has terminated
2415 * @work: the work which is to be flushed
2417 * Returns true if @work was pending.
2419 * cancel_work_sync() will cancel the work if it is queued. If the work's
2420 * callback appears to be running, cancel_work_sync() will block until it
2423 * It is possible to use this function if the work re-queues itself. It can
2424 * cancel the work even if it migrates to another workqueue, however in that
2425 * case it only guarantees that work->func() has completed on the last queued
2428 * cancel_work_sync(&delayed_work->work) should be used only if ->timer is not
2429 * pending, otherwise it goes into a busy-wait loop until the timer expires.
2431 * The caller must ensure that workqueue_struct on which this work was last
2432 * queued can't be destroyed before this function returns.
2434 int cancel_work_sync(struct work_struct *work)
2436 return __cancel_work_timer(work, NULL);
2438 EXPORT_SYMBOL_GPL(cancel_work_sync);
2441 * cancel_delayed_work_sync - reliably kill off a delayed work.
2442 * @dwork: the delayed work struct
2444 * Returns true if @dwork was pending.
2446 * It is possible to use this function if @dwork rearms itself via queue_work()
2447 * or queue_delayed_work(). See also the comment for cancel_work_sync().
2449 int cancel_delayed_work_sync(struct delayed_work *dwork)
2451 return __cancel_work_timer(&dwork->work, &dwork->timer);
2453 EXPORT_SYMBOL(cancel_delayed_work_sync);
2456 * schedule_work - put work task in global workqueue
2457 * @work: job to be done
2459 * Returns zero if @work was already on the kernel-global workqueue and
2460 * non-zero otherwise.
2462 * This puts a job in the kernel-global workqueue if it was not already
2463 * queued and leaves it in the same position on the kernel-global
2464 * workqueue otherwise.
2466 int schedule_work(struct work_struct *work)
2468 return queue_work(system_wq, work);
2470 EXPORT_SYMBOL(schedule_work);
2473 * schedule_work_on - put work task on a specific cpu
2474 * @cpu: cpu to put the work task on
2475 * @work: job to be done
2477 * This puts a job on a specific cpu
2479 int schedule_work_on(int cpu, struct work_struct *work)
2481 return queue_work_on(cpu, system_wq, work);
2483 EXPORT_SYMBOL(schedule_work_on);
2486 * schedule_delayed_work - put work task in global workqueue after delay
2487 * @dwork: job to be done
2488 * @delay: number of jiffies to wait or 0 for immediate execution
2490 * After waiting for a given time this puts a job in the kernel-global
2493 int schedule_delayed_work(struct delayed_work *dwork,
2494 unsigned long delay)
2496 return queue_delayed_work(system_wq, dwork, delay);
2498 EXPORT_SYMBOL(schedule_delayed_work);
2501 * flush_delayed_work - block until a dwork_struct's callback has terminated
2502 * @dwork: the delayed work which is to be flushed
2504 * Any timeout is cancelled, and any pending work is run immediately.
2506 void flush_delayed_work(struct delayed_work *dwork)
2508 if (del_timer_sync(&dwork->timer)) {
2509 __queue_work(get_cpu(), get_work_cwq(&dwork->work)->wq,
2513 flush_work(&dwork->work);
2515 EXPORT_SYMBOL(flush_delayed_work);
2518 * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
2520 * @dwork: job to be done
2521 * @delay: number of jiffies to wait
2523 * After waiting for a given time this puts a job in the kernel-global
2524 * workqueue on the specified CPU.
2526 int schedule_delayed_work_on(int cpu,
2527 struct delayed_work *dwork, unsigned long delay)
2529 return queue_delayed_work_on(cpu, system_wq, dwork, delay);
2531 EXPORT_SYMBOL(schedule_delayed_work_on);
2534 * schedule_on_each_cpu - call a function on each online CPU from keventd
2535 * @func: the function to call
2537 * Returns zero on success.
2538 * Returns -ve errno on failure.
2540 * schedule_on_each_cpu() is very slow.
2542 int schedule_on_each_cpu(work_func_t func)
2545 struct work_struct *works;
2547 works = alloc_percpu(struct work_struct);
2553 for_each_online_cpu(cpu) {
2554 struct work_struct *work = per_cpu_ptr(works, cpu);
2556 INIT_WORK(work, func);
2557 schedule_work_on(cpu, work);
2560 for_each_online_cpu(cpu)
2561 flush_work(per_cpu_ptr(works, cpu));
2569 * flush_scheduled_work - ensure that any scheduled work has run to completion.
2571 * Forces execution of the kernel-global workqueue and blocks until its
2574 * Think twice before calling this function! It's very easy to get into
2575 * trouble if you don't take great care. Either of the following situations
2576 * will lead to deadlock:
2578 * One of the work items currently on the workqueue needs to acquire
2579 * a lock held by your code or its caller.
2581 * Your code is running in the context of a work routine.
2583 * They will be detected by lockdep when they occur, but the first might not
2584 * occur very often. It depends on what work items are on the workqueue and
2585 * what locks they need, which you have no control over.
2587 * In most situations flushing the entire workqueue is overkill; you merely
2588 * need to know that a particular work item isn't queued and isn't running.
2589 * In such cases you should use cancel_delayed_work_sync() or
2590 * cancel_work_sync() instead.
2592 void flush_scheduled_work(void)
2594 flush_workqueue(system_wq);
2596 EXPORT_SYMBOL(flush_scheduled_work);
2599 * execute_in_process_context - reliably execute the routine with user context
2600 * @fn: the function to execute
2601 * @ew: guaranteed storage for the execute work structure (must
2602 * be available when the work executes)
2604 * Executes the function immediately if process context is available,
2605 * otherwise schedules the function for delayed execution.
2607 * Returns: 0 - function was executed
2608 * 1 - function was scheduled for execution
2610 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
2612 if (!in_interrupt()) {
2617 INIT_WORK(&ew->work, fn);
2618 schedule_work(&ew->work);
2622 EXPORT_SYMBOL_GPL(execute_in_process_context);
2624 int keventd_up(void)
2626 return system_wq != NULL;
2629 static int alloc_cwqs(struct workqueue_struct *wq)
2632 * cwqs are forced aligned according to WORK_STRUCT_FLAG_BITS.
2633 * Make sure that the alignment isn't lower than that of
2634 * unsigned long long.
2636 const size_t size = sizeof(struct cpu_workqueue_struct);
2637 const size_t align = max_t(size_t, 1 << WORK_STRUCT_FLAG_BITS,
2638 __alignof__(unsigned long long));
2640 bool percpu = !(wq->flags & WQ_UNBOUND);
2642 bool percpu = false;
2646 wq->cpu_wq.pcpu = __alloc_percpu(size, align);
2651 * Allocate enough room to align cwq and put an extra
2652 * pointer at the end pointing back to the originally
2653 * allocated pointer which will be used for free.
2655 ptr = kzalloc(size + align + sizeof(void *), GFP_KERNEL);
2657 wq->cpu_wq.single = PTR_ALIGN(ptr, align);
2658 *(void **)(wq->cpu_wq.single + 1) = ptr;
2662 /* just in case, make sure it's actually aligned */
2663 BUG_ON(!IS_ALIGNED(wq->cpu_wq.v, align));
2664 return wq->cpu_wq.v ? 0 : -ENOMEM;
2667 static void free_cwqs(struct workqueue_struct *wq)
2670 bool percpu = !(wq->flags & WQ_UNBOUND);
2672 bool percpu = false;
2676 free_percpu(wq->cpu_wq.pcpu);
2677 else if (wq->cpu_wq.single) {
2678 /* the pointer to free is stored right after the cwq */
2679 kfree(*(void **)(wq->cpu_wq.single + 1));
2683 static int wq_clamp_max_active(int max_active, unsigned int flags,
2686 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
2688 if (max_active < 1 || max_active > lim)
2689 printk(KERN_WARNING "workqueue: max_active %d requested for %s "
2690 "is out of range, clamping between %d and %d\n",
2691 max_active, name, 1, lim);
2693 return clamp_val(max_active, 1, lim);
2696 struct workqueue_struct *__alloc_workqueue_key(const char *name,
2699 struct lock_class_key *key,
2700 const char *lock_name)
2702 struct workqueue_struct *wq;
2706 * Unbound workqueues aren't concurrency managed and should be
2707 * dispatched to workers immediately.
2709 if (flags & WQ_UNBOUND)
2710 flags |= WQ_HIGHPRI;
2712 max_active = max_active ?: WQ_DFL_ACTIVE;
2713 max_active = wq_clamp_max_active(max_active, flags, name);
2715 wq = kzalloc(sizeof(*wq), GFP_KERNEL);
2720 wq->saved_max_active = max_active;
2721 mutex_init(&wq->flush_mutex);
2722 atomic_set(&wq->nr_cwqs_to_flush, 0);
2723 INIT_LIST_HEAD(&wq->flusher_queue);
2724 INIT_LIST_HEAD(&wq->flusher_overflow);
2727 lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
2728 INIT_LIST_HEAD(&wq->list);
2730 if (alloc_cwqs(wq) < 0)
2733 for_each_cwq_cpu(cpu, wq) {
2734 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2735 struct global_cwq *gcwq = get_gcwq(cpu);
2737 BUG_ON((unsigned long)cwq & WORK_STRUCT_FLAG_MASK);
2740 cwq->flush_color = -1;
2741 cwq->max_active = max_active;
2742 INIT_LIST_HEAD(&cwq->delayed_works);
2745 if (flags & WQ_RESCUER) {
2746 struct worker *rescuer;
2748 if (!alloc_mayday_mask(&wq->mayday_mask, GFP_KERNEL))
2751 wq->rescuer = rescuer = alloc_worker();
2755 rescuer->task = kthread_create(rescuer_thread, wq, "%s", name);
2756 if (IS_ERR(rescuer->task))
2759 wq->rescuer = rescuer;
2760 rescuer->task->flags |= PF_THREAD_BOUND;
2761 wake_up_process(rescuer->task);
2765 * workqueue_lock protects global freeze state and workqueues
2766 * list. Grab it, set max_active accordingly and add the new
2767 * workqueue to workqueues list.
2769 spin_lock(&workqueue_lock);
2771 if (workqueue_freezing && wq->flags & WQ_FREEZEABLE)
2772 for_each_cwq_cpu(cpu, wq)
2773 get_cwq(cpu, wq)->max_active = 0;
2775 list_add(&wq->list, &workqueues);
2777 spin_unlock(&workqueue_lock);
2783 free_mayday_mask(wq->mayday_mask);
2789 EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
2792 * destroy_workqueue - safely terminate a workqueue
2793 * @wq: target workqueue
2795 * Safely destroy a workqueue. All work currently pending will be done first.
2797 void destroy_workqueue(struct workqueue_struct *wq)
2801 flush_workqueue(wq);
2804 * wq list is used to freeze wq, remove from list after
2805 * flushing is complete in case freeze races us.
2807 spin_lock(&workqueue_lock);
2808 list_del(&wq->list);
2809 spin_unlock(&workqueue_lock);
2812 for_each_cwq_cpu(cpu, wq) {
2813 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2816 for (i = 0; i < WORK_NR_COLORS; i++)
2817 BUG_ON(cwq->nr_in_flight[i]);
2818 BUG_ON(cwq->nr_active);
2819 BUG_ON(!list_empty(&cwq->delayed_works));
2822 if (wq->flags & WQ_RESCUER) {
2823 kthread_stop(wq->rescuer->task);
2824 free_mayday_mask(wq->mayday_mask);
2830 EXPORT_SYMBOL_GPL(destroy_workqueue);
2833 * workqueue_set_max_active - adjust max_active of a workqueue
2834 * @wq: target workqueue
2835 * @max_active: new max_active value.
2837 * Set max_active of @wq to @max_active.
2840 * Don't call from IRQ context.
2842 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
2846 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
2848 spin_lock(&workqueue_lock);
2850 wq->saved_max_active = max_active;
2852 for_each_cwq_cpu(cpu, wq) {
2853 struct global_cwq *gcwq = get_gcwq(cpu);
2855 spin_lock_irq(&gcwq->lock);
2857 if (!(wq->flags & WQ_FREEZEABLE) ||
2858 !(gcwq->flags & GCWQ_FREEZING))
2859 get_cwq(gcwq->cpu, wq)->max_active = max_active;
2861 spin_unlock_irq(&gcwq->lock);
2864 spin_unlock(&workqueue_lock);
2866 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
2869 * workqueue_congested - test whether a workqueue is congested
2870 * @cpu: CPU in question
2871 * @wq: target workqueue
2873 * Test whether @wq's cpu workqueue for @cpu is congested. There is
2874 * no synchronization around this function and the test result is
2875 * unreliable and only useful as advisory hints or for debugging.
2878 * %true if congested, %false otherwise.
2880 bool workqueue_congested(unsigned int cpu, struct workqueue_struct *wq)
2882 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2884 return !list_empty(&cwq->delayed_works);
2886 EXPORT_SYMBOL_GPL(workqueue_congested);
2889 * work_cpu - return the last known associated cpu for @work
2890 * @work: the work of interest
2893 * CPU number if @work was ever queued. WORK_CPU_NONE otherwise.
2895 unsigned int work_cpu(struct work_struct *work)
2897 struct global_cwq *gcwq = get_work_gcwq(work);
2899 return gcwq ? gcwq->cpu : WORK_CPU_NONE;
2901 EXPORT_SYMBOL_GPL(work_cpu);
2904 * work_busy - test whether a work is currently pending or running
2905 * @work: the work to be tested
2907 * Test whether @work is currently pending or running. There is no
2908 * synchronization around this function and the test result is
2909 * unreliable and only useful as advisory hints or for debugging.
2910 * Especially for reentrant wqs, the pending state might hide the
2914 * OR'd bitmask of WORK_BUSY_* bits.
2916 unsigned int work_busy(struct work_struct *work)
2918 struct global_cwq *gcwq = get_work_gcwq(work);
2919 unsigned long flags;
2920 unsigned int ret = 0;
2925 spin_lock_irqsave(&gcwq->lock, flags);
2927 if (work_pending(work))
2928 ret |= WORK_BUSY_PENDING;
2929 if (find_worker_executing_work(gcwq, work))
2930 ret |= WORK_BUSY_RUNNING;
2932 spin_unlock_irqrestore(&gcwq->lock, flags);
2936 EXPORT_SYMBOL_GPL(work_busy);
2941 * There are two challenges in supporting CPU hotplug. Firstly, there
2942 * are a lot of assumptions on strong associations among work, cwq and
2943 * gcwq which make migrating pending and scheduled works very
2944 * difficult to implement without impacting hot paths. Secondly,
2945 * gcwqs serve mix of short, long and very long running works making
2946 * blocked draining impractical.
2948 * This is solved by allowing a gcwq to be detached from CPU, running
2949 * it with unbound (rogue) workers and allowing it to be reattached
2950 * later if the cpu comes back online. A separate thread is created
2951 * to govern a gcwq in such state and is called the trustee of the
2954 * Trustee states and their descriptions.
2956 * START Command state used on startup. On CPU_DOWN_PREPARE, a
2957 * new trustee is started with this state.
2959 * IN_CHARGE Once started, trustee will enter this state after
2960 * assuming the manager role and making all existing
2961 * workers rogue. DOWN_PREPARE waits for trustee to
2962 * enter this state. After reaching IN_CHARGE, trustee
2963 * tries to execute the pending worklist until it's empty
2964 * and the state is set to BUTCHER, or the state is set
2967 * BUTCHER Command state which is set by the cpu callback after
2968 * the cpu has went down. Once this state is set trustee
2969 * knows that there will be no new works on the worklist
2970 * and once the worklist is empty it can proceed to
2971 * killing idle workers.
2973 * RELEASE Command state which is set by the cpu callback if the
2974 * cpu down has been canceled or it has come online
2975 * again. After recognizing this state, trustee stops
2976 * trying to drain or butcher and clears ROGUE, rebinds
2977 * all remaining workers back to the cpu and releases
2980 * DONE Trustee will enter this state after BUTCHER or RELEASE
2983 * trustee CPU draining
2984 * took over down complete
2985 * START -----------> IN_CHARGE -----------> BUTCHER -----------> DONE
2987 * | CPU is back online v return workers |
2988 * ----------------> RELEASE --------------
2992 * trustee_wait_event_timeout - timed event wait for trustee
2993 * @cond: condition to wait for
2994 * @timeout: timeout in jiffies
2996 * wait_event_timeout() for trustee to use. Handles locking and
2997 * checks for RELEASE request.
3000 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
3001 * multiple times. To be used by trustee.
3004 * Positive indicating left time if @cond is satisfied, 0 if timed
3005 * out, -1 if canceled.
3007 #define trustee_wait_event_timeout(cond, timeout) ({ \
3008 long __ret = (timeout); \
3009 while (!((cond) || (gcwq->trustee_state == TRUSTEE_RELEASE)) && \
3011 spin_unlock_irq(&gcwq->lock); \
3012 __wait_event_timeout(gcwq->trustee_wait, (cond) || \
3013 (gcwq->trustee_state == TRUSTEE_RELEASE), \
3015 spin_lock_irq(&gcwq->lock); \
3017 gcwq->trustee_state == TRUSTEE_RELEASE ? -1 : (__ret); \
3021 * trustee_wait_event - event wait for trustee
3022 * @cond: condition to wait for
3024 * wait_event() for trustee to use. Automatically handles locking and
3025 * checks for CANCEL request.
3028 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
3029 * multiple times. To be used by trustee.
3032 * 0 if @cond is satisfied, -1 if canceled.
3034 #define trustee_wait_event(cond) ({ \
3036 __ret1 = trustee_wait_event_timeout(cond, MAX_SCHEDULE_TIMEOUT);\
3037 __ret1 < 0 ? -1 : 0; \
3040 static int __cpuinit trustee_thread(void *__gcwq)
3042 struct global_cwq *gcwq = __gcwq;
3043 struct worker *worker;
3044 struct work_struct *work;
3045 struct hlist_node *pos;
3049 BUG_ON(gcwq->cpu != smp_processor_id());
3051 spin_lock_irq(&gcwq->lock);
3053 * Claim the manager position and make all workers rogue.
3054 * Trustee must be bound to the target cpu and can't be
3057 BUG_ON(gcwq->cpu != smp_processor_id());
3058 rc = trustee_wait_event(!(gcwq->flags & GCWQ_MANAGING_WORKERS));
3061 gcwq->flags |= GCWQ_MANAGING_WORKERS;
3063 list_for_each_entry(worker, &gcwq->idle_list, entry)
3064 worker->flags |= WORKER_ROGUE;
3066 for_each_busy_worker(worker, i, pos, gcwq)
3067 worker->flags |= WORKER_ROGUE;
3070 * Call schedule() so that we cross rq->lock and thus can
3071 * guarantee sched callbacks see the rogue flag. This is
3072 * necessary as scheduler callbacks may be invoked from other
3075 spin_unlock_irq(&gcwq->lock);
3077 spin_lock_irq(&gcwq->lock);
3080 * Sched callbacks are disabled now. Zap nr_running. After
3081 * this, nr_running stays zero and need_more_worker() and
3082 * keep_working() are always true as long as the worklist is
3085 atomic_set(get_gcwq_nr_running(gcwq->cpu), 0);
3087 spin_unlock_irq(&gcwq->lock);
3088 del_timer_sync(&gcwq->idle_timer);
3089 spin_lock_irq(&gcwq->lock);
3092 * We're now in charge. Notify and proceed to drain. We need
3093 * to keep the gcwq running during the whole CPU down
3094 * procedure as other cpu hotunplug callbacks may need to
3095 * flush currently running tasks.
3097 gcwq->trustee_state = TRUSTEE_IN_CHARGE;
3098 wake_up_all(&gcwq->trustee_wait);
3101 * The original cpu is in the process of dying and may go away
3102 * anytime now. When that happens, we and all workers would
3103 * be migrated to other cpus. Try draining any left work. We
3104 * want to get it over with ASAP - spam rescuers, wake up as
3105 * many idlers as necessary and create new ones till the
3106 * worklist is empty. Note that if the gcwq is frozen, there
3107 * may be frozen works in freezeable cwqs. Don't declare
3108 * completion while frozen.
3110 while (gcwq->nr_workers != gcwq->nr_idle ||
3111 gcwq->flags & GCWQ_FREEZING ||
3112 gcwq->trustee_state == TRUSTEE_IN_CHARGE) {
3115 list_for_each_entry(work, &gcwq->worklist, entry) {
3120 list_for_each_entry(worker, &gcwq->idle_list, entry) {
3123 wake_up_process(worker->task);
3126 if (need_to_create_worker(gcwq)) {
3127 spin_unlock_irq(&gcwq->lock);
3128 worker = create_worker(gcwq, false);
3129 spin_lock_irq(&gcwq->lock);
3131 worker->flags |= WORKER_ROGUE;
3132 start_worker(worker);
3136 /* give a breather */
3137 if (trustee_wait_event_timeout(false, TRUSTEE_COOLDOWN) < 0)
3142 * Either all works have been scheduled and cpu is down, or
3143 * cpu down has already been canceled. Wait for and butcher
3144 * all workers till we're canceled.
3147 rc = trustee_wait_event(!list_empty(&gcwq->idle_list));
3148 while (!list_empty(&gcwq->idle_list))
3149 destroy_worker(list_first_entry(&gcwq->idle_list,
3150 struct worker, entry));
3151 } while (gcwq->nr_workers && rc >= 0);
3154 * At this point, either draining has completed and no worker
3155 * is left, or cpu down has been canceled or the cpu is being
3156 * brought back up. There shouldn't be any idle one left.
3157 * Tell the remaining busy ones to rebind once it finishes the
3158 * currently scheduled works by scheduling the rebind_work.
3160 WARN_ON(!list_empty(&gcwq->idle_list));
3162 for_each_busy_worker(worker, i, pos, gcwq) {
3163 struct work_struct *rebind_work = &worker->rebind_work;
3166 * Rebind_work may race with future cpu hotplug
3167 * operations. Use a separate flag to mark that
3168 * rebinding is scheduled.
3170 worker->flags |= WORKER_REBIND;
3171 worker->flags &= ~WORKER_ROGUE;
3173 /* queue rebind_work, wq doesn't matter, use the default one */
3174 if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
3175 work_data_bits(rebind_work)))
3178 debug_work_activate(rebind_work);
3179 insert_work(get_cwq(gcwq->cpu, system_wq), rebind_work,
3180 worker->scheduled.next,
3181 work_color_to_flags(WORK_NO_COLOR));
3184 /* relinquish manager role */
3185 gcwq->flags &= ~GCWQ_MANAGING_WORKERS;
3187 /* notify completion */
3188 gcwq->trustee = NULL;
3189 gcwq->trustee_state = TRUSTEE_DONE;
3190 wake_up_all(&gcwq->trustee_wait);
3191 spin_unlock_irq(&gcwq->lock);
3196 * wait_trustee_state - wait for trustee to enter the specified state
3197 * @gcwq: gcwq the trustee of interest belongs to
3198 * @state: target state to wait for
3200 * Wait for the trustee to reach @state. DONE is already matched.
3203 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
3204 * multiple times. To be used by cpu_callback.
3206 static void __cpuinit wait_trustee_state(struct global_cwq *gcwq, int state)
3208 if (!(gcwq->trustee_state == state ||
3209 gcwq->trustee_state == TRUSTEE_DONE)) {
3210 spin_unlock_irq(&gcwq->lock);
3211 __wait_event(gcwq->trustee_wait,
3212 gcwq->trustee_state == state ||
3213 gcwq->trustee_state == TRUSTEE_DONE);
3214 spin_lock_irq(&gcwq->lock);
3218 static int __devinit workqueue_cpu_callback(struct notifier_block *nfb,
3219 unsigned long action,
3222 unsigned int cpu = (unsigned long)hcpu;
3223 struct global_cwq *gcwq = get_gcwq(cpu);
3224 struct task_struct *new_trustee = NULL;
3225 struct worker *uninitialized_var(new_worker);
3226 unsigned long flags;
3228 action &= ~CPU_TASKS_FROZEN;
3231 case CPU_DOWN_PREPARE:
3232 new_trustee = kthread_create(trustee_thread, gcwq,
3233 "workqueue_trustee/%d\n", cpu);
3234 if (IS_ERR(new_trustee))
3235 return notifier_from_errno(PTR_ERR(new_trustee));
3236 kthread_bind(new_trustee, cpu);
3238 case CPU_UP_PREPARE:
3239 BUG_ON(gcwq->first_idle);
3240 new_worker = create_worker(gcwq, false);
3243 kthread_stop(new_trustee);
3248 /* some are called w/ irq disabled, don't disturb irq status */
3249 spin_lock_irqsave(&gcwq->lock, flags);
3252 case CPU_DOWN_PREPARE:
3253 /* initialize trustee and tell it to acquire the gcwq */
3254 BUG_ON(gcwq->trustee || gcwq->trustee_state != TRUSTEE_DONE);
3255 gcwq->trustee = new_trustee;
3256 gcwq->trustee_state = TRUSTEE_START;
3257 wake_up_process(gcwq->trustee);
3258 wait_trustee_state(gcwq, TRUSTEE_IN_CHARGE);
3260 case CPU_UP_PREPARE:
3261 BUG_ON(gcwq->first_idle);
3262 gcwq->first_idle = new_worker;
3267 * Before this, the trustee and all workers except for
3268 * the ones which are still executing works from
3269 * before the last CPU down must be on the cpu. After
3270 * this, they'll all be diasporas.
3272 gcwq->flags |= GCWQ_DISASSOCIATED;
3276 gcwq->trustee_state = TRUSTEE_BUTCHER;
3278 case CPU_UP_CANCELED:
3279 destroy_worker(gcwq->first_idle);
3280 gcwq->first_idle = NULL;
3283 case CPU_DOWN_FAILED:
3285 gcwq->flags &= ~GCWQ_DISASSOCIATED;
3286 if (gcwq->trustee_state != TRUSTEE_DONE) {
3287 gcwq->trustee_state = TRUSTEE_RELEASE;
3288 wake_up_process(gcwq->trustee);
3289 wait_trustee_state(gcwq, TRUSTEE_DONE);
3293 * Trustee is done and there might be no worker left.
3294 * Put the first_idle in and request a real manager to
3297 spin_unlock_irq(&gcwq->lock);
3298 kthread_bind(gcwq->first_idle->task, cpu);
3299 spin_lock_irq(&gcwq->lock);
3300 gcwq->flags |= GCWQ_MANAGE_WORKERS;
3301 start_worker(gcwq->first_idle);
3302 gcwq->first_idle = NULL;
3306 spin_unlock_irqrestore(&gcwq->lock, flags);
3308 return notifier_from_errno(0);
3313 struct work_for_cpu {
3314 struct completion completion;
3320 static int do_work_for_cpu(void *_wfc)
3322 struct work_for_cpu *wfc = _wfc;
3323 wfc->ret = wfc->fn(wfc->arg);
3324 complete(&wfc->completion);
3329 * work_on_cpu - run a function in user context on a particular cpu
3330 * @cpu: the cpu to run on
3331 * @fn: the function to run
3332 * @arg: the function arg
3334 * This will return the value @fn returns.
3335 * It is up to the caller to ensure that the cpu doesn't go offline.
3336 * The caller must not hold any locks which would prevent @fn from completing.
3338 long work_on_cpu(unsigned int cpu, long (*fn)(void *), void *arg)
3340 struct task_struct *sub_thread;
3341 struct work_for_cpu wfc = {
3342 .completion = COMPLETION_INITIALIZER_ONSTACK(wfc.completion),
3347 sub_thread = kthread_create(do_work_for_cpu, &wfc, "work_for_cpu");
3348 if (IS_ERR(sub_thread))
3349 return PTR_ERR(sub_thread);
3350 kthread_bind(sub_thread, cpu);
3351 wake_up_process(sub_thread);
3352 wait_for_completion(&wfc.completion);
3355 EXPORT_SYMBOL_GPL(work_on_cpu);
3356 #endif /* CONFIG_SMP */
3358 #ifdef CONFIG_FREEZER
3361 * freeze_workqueues_begin - begin freezing workqueues
3363 * Start freezing workqueues. After this function returns, all
3364 * freezeable workqueues will queue new works to their frozen_works
3365 * list instead of gcwq->worklist.
3368 * Grabs and releases workqueue_lock and gcwq->lock's.
3370 void freeze_workqueues_begin(void)
3374 spin_lock(&workqueue_lock);
3376 BUG_ON(workqueue_freezing);
3377 workqueue_freezing = true;
3379 for_each_gcwq_cpu(cpu) {
3380 struct global_cwq *gcwq = get_gcwq(cpu);
3381 struct workqueue_struct *wq;
3383 spin_lock_irq(&gcwq->lock);
3385 BUG_ON(gcwq->flags & GCWQ_FREEZING);
3386 gcwq->flags |= GCWQ_FREEZING;
3388 list_for_each_entry(wq, &workqueues, list) {
3389 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3391 if (cwq && wq->flags & WQ_FREEZEABLE)
3392 cwq->max_active = 0;
3395 spin_unlock_irq(&gcwq->lock);
3398 spin_unlock(&workqueue_lock);
3402 * freeze_workqueues_busy - are freezeable workqueues still busy?
3404 * Check whether freezing is complete. This function must be called
3405 * between freeze_workqueues_begin() and thaw_workqueues().
3408 * Grabs and releases workqueue_lock.
3411 * %true if some freezeable workqueues are still busy. %false if
3412 * freezing is complete.
3414 bool freeze_workqueues_busy(void)
3419 spin_lock(&workqueue_lock);
3421 BUG_ON(!workqueue_freezing);
3423 for_each_gcwq_cpu(cpu) {
3424 struct workqueue_struct *wq;
3426 * nr_active is monotonically decreasing. It's safe
3427 * to peek without lock.
3429 list_for_each_entry(wq, &workqueues, list) {
3430 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3432 if (!cwq || !(wq->flags & WQ_FREEZEABLE))
3435 BUG_ON(cwq->nr_active < 0);
3436 if (cwq->nr_active) {
3443 spin_unlock(&workqueue_lock);
3448 * thaw_workqueues - thaw workqueues
3450 * Thaw workqueues. Normal queueing is restored and all collected
3451 * frozen works are transferred to their respective gcwq worklists.
3454 * Grabs and releases workqueue_lock and gcwq->lock's.
3456 void thaw_workqueues(void)
3460 spin_lock(&workqueue_lock);
3462 if (!workqueue_freezing)
3465 for_each_gcwq_cpu(cpu) {
3466 struct global_cwq *gcwq = get_gcwq(cpu);
3467 struct workqueue_struct *wq;
3469 spin_lock_irq(&gcwq->lock);
3471 BUG_ON(!(gcwq->flags & GCWQ_FREEZING));
3472 gcwq->flags &= ~GCWQ_FREEZING;
3474 list_for_each_entry(wq, &workqueues, list) {
3475 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3477 if (!cwq || !(wq->flags & WQ_FREEZEABLE))
3480 /* restore max_active and repopulate worklist */
3481 cwq->max_active = wq->saved_max_active;
3483 while (!list_empty(&cwq->delayed_works) &&
3484 cwq->nr_active < cwq->max_active)
3485 cwq_activate_first_delayed(cwq);
3488 wake_up_worker(gcwq);
3490 spin_unlock_irq(&gcwq->lock);
3493 workqueue_freezing = false;
3495 spin_unlock(&workqueue_lock);
3497 #endif /* CONFIG_FREEZER */
3499 void __init init_workqueues(void)
3505 * The pointer part of work->data is either pointing to the
3506 * cwq or contains the cpu number the work ran last on. Make
3507 * sure cpu number won't overflow into kernel pointer area so
3508 * that they can be distinguished.
3510 BUILD_BUG_ON(WORK_CPU_LAST << WORK_STRUCT_FLAG_BITS >= PAGE_OFFSET);
3512 hotcpu_notifier(workqueue_cpu_callback, CPU_PRI_WORKQUEUE);
3514 /* initialize gcwqs */
3515 for_each_gcwq_cpu(cpu) {
3516 struct global_cwq *gcwq = get_gcwq(cpu);
3518 spin_lock_init(&gcwq->lock);
3519 INIT_LIST_HEAD(&gcwq->worklist);
3521 if (cpu == WORK_CPU_UNBOUND)
3522 gcwq->flags |= GCWQ_DISASSOCIATED;
3524 INIT_LIST_HEAD(&gcwq->idle_list);
3525 for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)
3526 INIT_HLIST_HEAD(&gcwq->busy_hash[i]);
3528 init_timer_deferrable(&gcwq->idle_timer);
3529 gcwq->idle_timer.function = idle_worker_timeout;
3530 gcwq->idle_timer.data = (unsigned long)gcwq;
3532 setup_timer(&gcwq->mayday_timer, gcwq_mayday_timeout,
3533 (unsigned long)gcwq);
3535 ida_init(&gcwq->worker_ida);
3537 gcwq->trustee_state = TRUSTEE_DONE;
3538 init_waitqueue_head(&gcwq->trustee_wait);
3541 /* create the initial worker */
3542 for_each_online_gcwq_cpu(cpu) {
3543 struct global_cwq *gcwq = get_gcwq(cpu);
3544 struct worker *worker;
3546 worker = create_worker(gcwq, true);
3548 spin_lock_irq(&gcwq->lock);
3549 start_worker(worker);
3550 spin_unlock_irq(&gcwq->lock);
3553 system_wq = alloc_workqueue("events", 0, 0);
3554 system_long_wq = alloc_workqueue("events_long", 0, 0);
3555 system_nrt_wq = alloc_workqueue("events_nrt", WQ_NON_REENTRANT, 0);
3556 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
3557 WQ_UNBOUND_MAX_ACTIVE);
3558 BUG_ON(!system_wq || !system_long_wq || !system_nrt_wq);