2 * kernel/workqueue.c - generic async execution with shared worker pool
4 * Copyright (C) 2002 Ingo Molnar
6 * Derived from the taskqueue/keventd code by:
7 * David Woodhouse <dwmw2@infradead.org>
9 * Kai Petzke <wpp@marie.physik.tu-berlin.de>
10 * Theodore Ts'o <tytso@mit.edu>
12 * Made to use alloc_percpu by Christoph Lameter.
14 * Copyright (C) 2010 SUSE Linux Products GmbH
15 * Copyright (C) 2010 Tejun Heo <tj@kernel.org>
17 * This is the generic async execution mechanism. Work items as are
18 * executed in process context. The worker pool is shared and
19 * automatically managed. There is one worker pool for each CPU and
20 * one extra for works which are better served by workers which are
21 * not bound to any specific CPU.
23 * Please read Documentation/workqueue.txt for details.
26 #include <linux/export.h>
27 #include <linux/kernel.h>
28 #include <linux/sched.h>
29 #include <linux/init.h>
30 #include <linux/signal.h>
31 #include <linux/completion.h>
32 #include <linux/workqueue.h>
33 #include <linux/slab.h>
34 #include <linux/cpu.h>
35 #include <linux/notifier.h>
36 #include <linux/kthread.h>
37 #include <linux/hardirq.h>
38 #include <linux/mempolicy.h>
39 #include <linux/freezer.h>
40 #include <linux/kallsyms.h>
41 #include <linux/debug_locks.h>
42 #include <linux/lockdep.h>
43 #include <linux/idr.h>
44 #include <linux/hashtable.h>
46 #include "workqueue_internal.h"
52 * A bound pool is either associated or disassociated with its CPU.
53 * While associated (!DISASSOCIATED), all workers are bound to the
54 * CPU and none has %WORKER_UNBOUND set and concurrency management
57 * While DISASSOCIATED, the cpu may be offline and all workers have
58 * %WORKER_UNBOUND set and concurrency management disabled, and may
59 * be executing on any CPU. The pool behaves as an unbound one.
61 * Note that DISASSOCIATED can be flipped only while holding
62 * assoc_mutex to avoid changing binding state while
63 * create_worker() is in progress.
65 POOL_MANAGE_WORKERS = 1 << 0, /* need to manage workers */
66 POOL_MANAGING_WORKERS = 1 << 1, /* managing workers */
67 POOL_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
68 POOL_FREEZING = 1 << 3, /* freeze in progress */
71 WORKER_STARTED = 1 << 0, /* started */
72 WORKER_DIE = 1 << 1, /* die die die */
73 WORKER_IDLE = 1 << 2, /* is idle */
74 WORKER_PREP = 1 << 3, /* preparing to run works */
75 WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
76 WORKER_UNBOUND = 1 << 7, /* worker is unbound */
78 WORKER_NOT_RUNNING = WORKER_PREP | WORKER_UNBOUND |
81 NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */
83 BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
85 MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
86 IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
88 MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
89 /* call for help after 10ms
91 MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
92 CREATE_COOLDOWN = HZ, /* time to breath after fail */
95 * Rescue workers are used only on emergencies and shared by
98 RESCUER_NICE_LEVEL = -20,
99 HIGHPRI_NICE_LEVEL = -20,
103 * Structure fields follow one of the following exclusion rules.
105 * I: Modifiable by initialization/destruction paths and read-only for
108 * P: Preemption protected. Disabling preemption is enough and should
109 * only be modified and accessed from the local cpu.
111 * L: gcwq->lock protected. Access with gcwq->lock held.
113 * X: During normal operation, modification requires gcwq->lock and
114 * should be done only from local cpu. Either disabling preemption
115 * on local cpu or grabbing gcwq->lock is enough for read access.
116 * If POOL_DISASSOCIATED is set, it's identical to L.
118 * F: wq->flush_mutex protected.
120 * W: workqueue_lock protected.
123 /* struct worker is defined in workqueue_internal.h */
126 struct global_cwq *gcwq; /* I: the owning gcwq */
127 int id; /* I: pool ID */
128 unsigned int flags; /* X: flags */
130 struct list_head worklist; /* L: list of pending works */
131 int nr_workers; /* L: total number of workers */
133 /* nr_idle includes the ones off idle_list for rebinding */
134 int nr_idle; /* L: currently idle ones */
136 struct list_head idle_list; /* X: list of idle workers */
137 struct timer_list idle_timer; /* L: worker idle timeout */
138 struct timer_list mayday_timer; /* L: SOS timer for workers */
140 struct mutex assoc_mutex; /* protect POOL_DISASSOCIATED */
141 struct ida worker_ida; /* L: for worker IDs */
145 * Global per-cpu workqueue. There's one and only one for each cpu
146 * and all works are queued and processed here regardless of their
150 spinlock_t lock; /* the gcwq lock */
151 unsigned int cpu; /* I: the associated cpu */
153 /* workers are chained either in busy_hash or pool idle_list */
154 DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
155 /* L: hash of busy workers */
157 struct worker_pool pools[NR_STD_WORKER_POOLS];
158 /* normal and highpri pools */
159 } ____cacheline_aligned_in_smp;
162 * The per-CPU workqueue. The lower WORK_STRUCT_FLAG_BITS of
163 * work_struct->data are used for flags and thus cwqs need to be
164 * aligned at two's power of the number of flag bits.
166 struct cpu_workqueue_struct {
167 struct worker_pool *pool; /* I: the associated pool */
168 struct workqueue_struct *wq; /* I: the owning workqueue */
169 int work_color; /* L: current color */
170 int flush_color; /* L: flushing color */
171 int nr_in_flight[WORK_NR_COLORS];
172 /* L: nr of in_flight works */
173 int nr_active; /* L: nr of active works */
174 int max_active; /* L: max active works */
175 struct list_head delayed_works; /* L: delayed works */
179 * Structure used to wait for workqueue flush.
182 struct list_head list; /* F: list of flushers */
183 int flush_color; /* F: flush color waiting for */
184 struct completion done; /* flush completion */
188 * All cpumasks are assumed to be always set on UP and thus can't be
189 * used to determine whether there's something to be done.
192 typedef cpumask_var_t mayday_mask_t;
193 #define mayday_test_and_set_cpu(cpu, mask) \
194 cpumask_test_and_set_cpu((cpu), (mask))
195 #define mayday_clear_cpu(cpu, mask) cpumask_clear_cpu((cpu), (mask))
196 #define for_each_mayday_cpu(cpu, mask) for_each_cpu((cpu), (mask))
197 #define alloc_mayday_mask(maskp, gfp) zalloc_cpumask_var((maskp), (gfp))
198 #define free_mayday_mask(mask) free_cpumask_var((mask))
200 typedef unsigned long mayday_mask_t;
201 #define mayday_test_and_set_cpu(cpu, mask) test_and_set_bit(0, &(mask))
202 #define mayday_clear_cpu(cpu, mask) clear_bit(0, &(mask))
203 #define for_each_mayday_cpu(cpu, mask) if ((cpu) = 0, (mask))
204 #define alloc_mayday_mask(maskp, gfp) true
205 #define free_mayday_mask(mask) do { } while (0)
209 * The externally visible workqueue abstraction is an array of
210 * per-CPU workqueues:
212 struct workqueue_struct {
213 unsigned int flags; /* W: WQ_* flags */
215 struct cpu_workqueue_struct __percpu *pcpu;
216 struct cpu_workqueue_struct *single;
218 } cpu_wq; /* I: cwq's */
219 struct list_head list; /* W: list of all workqueues */
221 struct mutex flush_mutex; /* protects wq flushing */
222 int work_color; /* F: current work color */
223 int flush_color; /* F: current flush color */
224 atomic_t nr_cwqs_to_flush; /* flush in progress */
225 struct wq_flusher *first_flusher; /* F: first flusher */
226 struct list_head flusher_queue; /* F: flush waiters */
227 struct list_head flusher_overflow; /* F: flush overflow list */
229 mayday_mask_t mayday_mask; /* cpus requesting rescue */
230 struct worker *rescuer; /* I: rescue worker */
232 int nr_drainers; /* W: drain in progress */
233 int saved_max_active; /* W: saved cwq max_active */
234 #ifdef CONFIG_LOCKDEP
235 struct lockdep_map lockdep_map;
237 char name[]; /* I: workqueue name */
240 struct workqueue_struct *system_wq __read_mostly;
241 EXPORT_SYMBOL_GPL(system_wq);
242 struct workqueue_struct *system_highpri_wq __read_mostly;
243 EXPORT_SYMBOL_GPL(system_highpri_wq);
244 struct workqueue_struct *system_long_wq __read_mostly;
245 EXPORT_SYMBOL_GPL(system_long_wq);
246 struct workqueue_struct *system_unbound_wq __read_mostly;
247 EXPORT_SYMBOL_GPL(system_unbound_wq);
248 struct workqueue_struct *system_freezable_wq __read_mostly;
249 EXPORT_SYMBOL_GPL(system_freezable_wq);
251 #define CREATE_TRACE_POINTS
252 #include <trace/events/workqueue.h>
254 #define for_each_worker_pool(pool, gcwq) \
255 for ((pool) = &(gcwq)->pools[0]; \
256 (pool) < &(gcwq)->pools[NR_STD_WORKER_POOLS]; (pool)++)
258 #define for_each_busy_worker(worker, i, pos, gcwq) \
259 hash_for_each(gcwq->busy_hash, i, pos, worker, hentry)
261 static inline int __next_gcwq_cpu(int cpu, const struct cpumask *mask,
264 if (cpu < nr_cpu_ids) {
266 cpu = cpumask_next(cpu, mask);
267 if (cpu < nr_cpu_ids)
271 return WORK_CPU_UNBOUND;
273 return WORK_CPU_NONE;
276 static inline int __next_wq_cpu(int cpu, const struct cpumask *mask,
277 struct workqueue_struct *wq)
279 return __next_gcwq_cpu(cpu, mask, !(wq->flags & WQ_UNBOUND) ? 1 : 2);
285 * An extra gcwq is defined for an invalid cpu number
286 * (WORK_CPU_UNBOUND) to host workqueues which are not bound to any
287 * specific CPU. The following iterators are similar to
288 * for_each_*_cpu() iterators but also considers the unbound gcwq.
290 * for_each_gcwq_cpu() : possible CPUs + WORK_CPU_UNBOUND
291 * for_each_online_gcwq_cpu() : online CPUs + WORK_CPU_UNBOUND
292 * for_each_cwq_cpu() : possible CPUs for bound workqueues,
293 * WORK_CPU_UNBOUND for unbound workqueues
295 #define for_each_gcwq_cpu(cpu) \
296 for ((cpu) = __next_gcwq_cpu(-1, cpu_possible_mask, 3); \
297 (cpu) < WORK_CPU_NONE; \
298 (cpu) = __next_gcwq_cpu((cpu), cpu_possible_mask, 3))
300 #define for_each_online_gcwq_cpu(cpu) \
301 for ((cpu) = __next_gcwq_cpu(-1, cpu_online_mask, 3); \
302 (cpu) < WORK_CPU_NONE; \
303 (cpu) = __next_gcwq_cpu((cpu), cpu_online_mask, 3))
305 #define for_each_cwq_cpu(cpu, wq) \
306 for ((cpu) = __next_wq_cpu(-1, cpu_possible_mask, (wq)); \
307 (cpu) < WORK_CPU_NONE; \
308 (cpu) = __next_wq_cpu((cpu), cpu_possible_mask, (wq)))
310 #ifdef CONFIG_DEBUG_OBJECTS_WORK
312 static struct debug_obj_descr work_debug_descr;
314 static void *work_debug_hint(void *addr)
316 return ((struct work_struct *) addr)->func;
320 * fixup_init is called when:
321 * - an active object is initialized
323 static int work_fixup_init(void *addr, enum debug_obj_state state)
325 struct work_struct *work = addr;
328 case ODEBUG_STATE_ACTIVE:
329 cancel_work_sync(work);
330 debug_object_init(work, &work_debug_descr);
338 * fixup_activate is called when:
339 * - an active object is activated
340 * - an unknown object is activated (might be a statically initialized object)
342 static int work_fixup_activate(void *addr, enum debug_obj_state state)
344 struct work_struct *work = addr;
348 case ODEBUG_STATE_NOTAVAILABLE:
350 * This is not really a fixup. The work struct was
351 * statically initialized. We just make sure that it
352 * is tracked in the object tracker.
354 if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
355 debug_object_init(work, &work_debug_descr);
356 debug_object_activate(work, &work_debug_descr);
362 case ODEBUG_STATE_ACTIVE:
371 * fixup_free is called when:
372 * - an active object is freed
374 static int work_fixup_free(void *addr, enum debug_obj_state state)
376 struct work_struct *work = addr;
379 case ODEBUG_STATE_ACTIVE:
380 cancel_work_sync(work);
381 debug_object_free(work, &work_debug_descr);
388 static struct debug_obj_descr work_debug_descr = {
389 .name = "work_struct",
390 .debug_hint = work_debug_hint,
391 .fixup_init = work_fixup_init,
392 .fixup_activate = work_fixup_activate,
393 .fixup_free = work_fixup_free,
396 static inline void debug_work_activate(struct work_struct *work)
398 debug_object_activate(work, &work_debug_descr);
401 static inline void debug_work_deactivate(struct work_struct *work)
403 debug_object_deactivate(work, &work_debug_descr);
406 void __init_work(struct work_struct *work, int onstack)
409 debug_object_init_on_stack(work, &work_debug_descr);
411 debug_object_init(work, &work_debug_descr);
413 EXPORT_SYMBOL_GPL(__init_work);
415 void destroy_work_on_stack(struct work_struct *work)
417 debug_object_free(work, &work_debug_descr);
419 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
422 static inline void debug_work_activate(struct work_struct *work) { }
423 static inline void debug_work_deactivate(struct work_struct *work) { }
426 /* Serializes the accesses to the list of workqueues. */
427 static DEFINE_SPINLOCK(workqueue_lock);
428 static LIST_HEAD(workqueues);
429 static bool workqueue_freezing; /* W: have wqs started freezing? */
432 * The almighty global cpu workqueues. nr_running is the only field
433 * which is expected to be used frequently by other cpus via
434 * try_to_wake_up(). Put it in a separate cacheline.
436 static DEFINE_PER_CPU(struct global_cwq, global_cwq);
437 static DEFINE_PER_CPU_SHARED_ALIGNED(atomic_t, pool_nr_running[NR_STD_WORKER_POOLS]);
440 * Global cpu workqueue and nr_running counter for unbound gcwq. The pools
441 * for online CPUs have POOL_DISASSOCIATED set, and all their workers have
442 * WORKER_UNBOUND set.
444 static struct global_cwq unbound_global_cwq;
445 static atomic_t unbound_pool_nr_running[NR_STD_WORKER_POOLS] = {
446 [0 ... NR_STD_WORKER_POOLS - 1] = ATOMIC_INIT(0), /* always 0 */
449 /* idr of all pools */
450 static DEFINE_MUTEX(worker_pool_idr_mutex);
451 static DEFINE_IDR(worker_pool_idr);
453 static int worker_thread(void *__worker);
454 static unsigned int work_cpu(struct work_struct *work);
456 static int std_worker_pool_pri(struct worker_pool *pool)
458 return pool - pool->gcwq->pools;
461 static struct global_cwq *get_gcwq(unsigned int cpu)
463 if (cpu != WORK_CPU_UNBOUND)
464 return &per_cpu(global_cwq, cpu);
466 return &unbound_global_cwq;
469 /* allocate ID and assign it to @pool */
470 static int worker_pool_assign_id(struct worker_pool *pool)
474 mutex_lock(&worker_pool_idr_mutex);
475 idr_pre_get(&worker_pool_idr, GFP_KERNEL);
476 ret = idr_get_new(&worker_pool_idr, pool, &pool->id);
477 mutex_unlock(&worker_pool_idr_mutex);
482 static atomic_t *get_pool_nr_running(struct worker_pool *pool)
484 int cpu = pool->gcwq->cpu;
485 int idx = std_worker_pool_pri(pool);
487 if (cpu != WORK_CPU_UNBOUND)
488 return &per_cpu(pool_nr_running, cpu)[idx];
490 return &unbound_pool_nr_running[idx];
493 static struct cpu_workqueue_struct *get_cwq(unsigned int cpu,
494 struct workqueue_struct *wq)
496 if (!(wq->flags & WQ_UNBOUND)) {
497 if (likely(cpu < nr_cpu_ids))
498 return per_cpu_ptr(wq->cpu_wq.pcpu, cpu);
499 } else if (likely(cpu == WORK_CPU_UNBOUND))
500 return wq->cpu_wq.single;
504 static unsigned int work_color_to_flags(int color)
506 return color << WORK_STRUCT_COLOR_SHIFT;
509 static int get_work_color(struct work_struct *work)
511 return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
512 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
515 static int work_next_color(int color)
517 return (color + 1) % WORK_NR_COLORS;
521 * While queued, %WORK_STRUCT_CWQ is set and non flag bits of a work's data
522 * contain the pointer to the queued cwq. Once execution starts, the flag
523 * is cleared and the high bits contain OFFQ flags and CPU number.
525 * set_work_cwq(), set_work_cpu_and_clear_pending(), mark_work_canceling()
526 * and clear_work_data() can be used to set the cwq, cpu or clear
527 * work->data. These functions should only be called while the work is
528 * owned - ie. while the PENDING bit is set.
530 * get_work_[g]cwq() can be used to obtain the gcwq or cwq corresponding to
531 * a work. gcwq is available once the work has been queued anywhere after
532 * initialization until it is sync canceled. cwq is available only while
533 * the work item is queued.
535 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
536 * canceled. While being canceled, a work item may have its PENDING set
537 * but stay off timer and worklist for arbitrarily long and nobody should
538 * try to steal the PENDING bit.
540 static inline void set_work_data(struct work_struct *work, unsigned long data,
543 BUG_ON(!work_pending(work));
544 atomic_long_set(&work->data, data | flags | work_static(work));
547 static void set_work_cwq(struct work_struct *work,
548 struct cpu_workqueue_struct *cwq,
549 unsigned long extra_flags)
551 set_work_data(work, (unsigned long)cwq,
552 WORK_STRUCT_PENDING | WORK_STRUCT_CWQ | extra_flags);
555 static void set_work_cpu_and_clear_pending(struct work_struct *work,
559 * The following wmb is paired with the implied mb in
560 * test_and_set_bit(PENDING) and ensures all updates to @work made
561 * here are visible to and precede any updates by the next PENDING
565 set_work_data(work, (unsigned long)cpu << WORK_OFFQ_CPU_SHIFT, 0);
568 static void clear_work_data(struct work_struct *work)
570 smp_wmb(); /* see set_work_cpu_and_clear_pending() */
571 set_work_data(work, WORK_STRUCT_NO_CPU, 0);
574 static struct cpu_workqueue_struct *get_work_cwq(struct work_struct *work)
576 unsigned long data = atomic_long_read(&work->data);
578 if (data & WORK_STRUCT_CWQ)
579 return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
584 static struct global_cwq *get_work_gcwq(struct work_struct *work)
586 unsigned long data = atomic_long_read(&work->data);
589 if (data & WORK_STRUCT_CWQ)
590 return ((struct cpu_workqueue_struct *)
591 (data & WORK_STRUCT_WQ_DATA_MASK))->pool->gcwq;
593 cpu = data >> WORK_OFFQ_CPU_SHIFT;
594 if (cpu == WORK_OFFQ_CPU_NONE)
597 BUG_ON(cpu >= nr_cpu_ids && cpu != WORK_CPU_UNBOUND);
598 return get_gcwq(cpu);
601 static void mark_work_canceling(struct work_struct *work)
603 struct global_cwq *gcwq = get_work_gcwq(work);
604 unsigned long cpu = gcwq ? gcwq->cpu : WORK_OFFQ_CPU_NONE;
606 set_work_data(work, (cpu << WORK_OFFQ_CPU_SHIFT) | WORK_OFFQ_CANCELING,
607 WORK_STRUCT_PENDING);
610 static bool work_is_canceling(struct work_struct *work)
612 unsigned long data = atomic_long_read(&work->data);
614 return !(data & WORK_STRUCT_CWQ) && (data & WORK_OFFQ_CANCELING);
618 * Policy functions. These define the policies on how the global worker
619 * pools are managed. Unless noted otherwise, these functions assume that
620 * they're being called with gcwq->lock held.
623 static bool __need_more_worker(struct worker_pool *pool)
625 return !atomic_read(get_pool_nr_running(pool));
629 * Need to wake up a worker? Called from anything but currently
632 * Note that, because unbound workers never contribute to nr_running, this
633 * function will always return %true for unbound gcwq as long as the
634 * worklist isn't empty.
636 static bool need_more_worker(struct worker_pool *pool)
638 return !list_empty(&pool->worklist) && __need_more_worker(pool);
641 /* Can I start working? Called from busy but !running workers. */
642 static bool may_start_working(struct worker_pool *pool)
644 return pool->nr_idle;
647 /* Do I need to keep working? Called from currently running workers. */
648 static bool keep_working(struct worker_pool *pool)
650 atomic_t *nr_running = get_pool_nr_running(pool);
652 return !list_empty(&pool->worklist) && atomic_read(nr_running) <= 1;
655 /* Do we need a new worker? Called from manager. */
656 static bool need_to_create_worker(struct worker_pool *pool)
658 return need_more_worker(pool) && !may_start_working(pool);
661 /* Do I need to be the manager? */
662 static bool need_to_manage_workers(struct worker_pool *pool)
664 return need_to_create_worker(pool) ||
665 (pool->flags & POOL_MANAGE_WORKERS);
668 /* Do we have too many workers and should some go away? */
669 static bool too_many_workers(struct worker_pool *pool)
671 bool managing = pool->flags & POOL_MANAGING_WORKERS;
672 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
673 int nr_busy = pool->nr_workers - nr_idle;
676 * nr_idle and idle_list may disagree if idle rebinding is in
677 * progress. Never return %true if idle_list is empty.
679 if (list_empty(&pool->idle_list))
682 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
689 /* Return the first worker. Safe with preemption disabled */
690 static struct worker *first_worker(struct worker_pool *pool)
692 if (unlikely(list_empty(&pool->idle_list)))
695 return list_first_entry(&pool->idle_list, struct worker, entry);
699 * wake_up_worker - wake up an idle worker
700 * @pool: worker pool to wake worker from
702 * Wake up the first idle worker of @pool.
705 * spin_lock_irq(gcwq->lock).
707 static void wake_up_worker(struct worker_pool *pool)
709 struct worker *worker = first_worker(pool);
712 wake_up_process(worker->task);
716 * wq_worker_waking_up - a worker is waking up
717 * @task: task waking up
718 * @cpu: CPU @task is waking up to
720 * This function is called during try_to_wake_up() when a worker is
724 * spin_lock_irq(rq->lock)
726 void wq_worker_waking_up(struct task_struct *task, unsigned int cpu)
728 struct worker *worker = kthread_data(task);
730 if (!(worker->flags & WORKER_NOT_RUNNING)) {
731 WARN_ON_ONCE(worker->pool->gcwq->cpu != cpu);
732 atomic_inc(get_pool_nr_running(worker->pool));
737 * wq_worker_sleeping - a worker is going to sleep
738 * @task: task going to sleep
739 * @cpu: CPU in question, must be the current CPU number
741 * This function is called during schedule() when a busy worker is
742 * going to sleep. Worker on the same cpu can be woken up by
743 * returning pointer to its task.
746 * spin_lock_irq(rq->lock)
749 * Worker task on @cpu to wake up, %NULL if none.
751 struct task_struct *wq_worker_sleeping(struct task_struct *task,
754 struct worker *worker = kthread_data(task), *to_wakeup = NULL;
755 struct worker_pool *pool;
756 atomic_t *nr_running;
759 * Rescuers, which may not have all the fields set up like normal
760 * workers, also reach here, let's not access anything before
761 * checking NOT_RUNNING.
763 if (worker->flags & WORKER_NOT_RUNNING)
767 nr_running = get_pool_nr_running(pool);
769 /* this can only happen on the local cpu */
770 BUG_ON(cpu != raw_smp_processor_id());
773 * The counterpart of the following dec_and_test, implied mb,
774 * worklist not empty test sequence is in insert_work().
775 * Please read comment there.
777 * NOT_RUNNING is clear. This means that we're bound to and
778 * running on the local cpu w/ rq lock held and preemption
779 * disabled, which in turn means that none else could be
780 * manipulating idle_list, so dereferencing idle_list without gcwq
783 if (atomic_dec_and_test(nr_running) && !list_empty(&pool->worklist))
784 to_wakeup = first_worker(pool);
785 return to_wakeup ? to_wakeup->task : NULL;
789 * worker_set_flags - set worker flags and adjust nr_running accordingly
791 * @flags: flags to set
792 * @wakeup: wakeup an idle worker if necessary
794 * Set @flags in @worker->flags and adjust nr_running accordingly. If
795 * nr_running becomes zero and @wakeup is %true, an idle worker is
799 * spin_lock_irq(gcwq->lock)
801 static inline void worker_set_flags(struct worker *worker, unsigned int flags,
804 struct worker_pool *pool = worker->pool;
806 WARN_ON_ONCE(worker->task != current);
809 * If transitioning into NOT_RUNNING, adjust nr_running and
810 * wake up an idle worker as necessary if requested by
813 if ((flags & WORKER_NOT_RUNNING) &&
814 !(worker->flags & WORKER_NOT_RUNNING)) {
815 atomic_t *nr_running = get_pool_nr_running(pool);
818 if (atomic_dec_and_test(nr_running) &&
819 !list_empty(&pool->worklist))
820 wake_up_worker(pool);
822 atomic_dec(nr_running);
825 worker->flags |= flags;
829 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
831 * @flags: flags to clear
833 * Clear @flags in @worker->flags and adjust nr_running accordingly.
836 * spin_lock_irq(gcwq->lock)
838 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
840 struct worker_pool *pool = worker->pool;
841 unsigned int oflags = worker->flags;
843 WARN_ON_ONCE(worker->task != current);
845 worker->flags &= ~flags;
848 * If transitioning out of NOT_RUNNING, increment nr_running. Note
849 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
850 * of multiple flags, not a single flag.
852 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
853 if (!(worker->flags & WORKER_NOT_RUNNING))
854 atomic_inc(get_pool_nr_running(pool));
858 * find_worker_executing_work - find worker which is executing a work
859 * @gcwq: gcwq of interest
860 * @work: work to find worker for
862 * Find a worker which is executing @work on @gcwq by searching
863 * @gcwq->busy_hash which is keyed by the address of @work. For a worker
864 * to match, its current execution should match the address of @work and
865 * its work function. This is to avoid unwanted dependency between
866 * unrelated work executions through a work item being recycled while still
869 * This is a bit tricky. A work item may be freed once its execution
870 * starts and nothing prevents the freed area from being recycled for
871 * another work item. If the same work item address ends up being reused
872 * before the original execution finishes, workqueue will identify the
873 * recycled work item as currently executing and make it wait until the
874 * current execution finishes, introducing an unwanted dependency.
876 * This function checks the work item address, work function and workqueue
877 * to avoid false positives. Note that this isn't complete as one may
878 * construct a work function which can introduce dependency onto itself
879 * through a recycled work item. Well, if somebody wants to shoot oneself
880 * in the foot that badly, there's only so much we can do, and if such
881 * deadlock actually occurs, it should be easy to locate the culprit work
885 * spin_lock_irq(gcwq->lock).
888 * Pointer to worker which is executing @work if found, NULL
891 static struct worker *find_worker_executing_work(struct global_cwq *gcwq,
892 struct work_struct *work)
894 struct worker *worker;
895 struct hlist_node *tmp;
897 hash_for_each_possible(gcwq->busy_hash, worker, tmp, hentry,
899 if (worker->current_work == work &&
900 worker->current_func == work->func)
907 * move_linked_works - move linked works to a list
908 * @work: start of series of works to be scheduled
909 * @head: target list to append @work to
910 * @nextp: out paramter for nested worklist walking
912 * Schedule linked works starting from @work to @head. Work series to
913 * be scheduled starts at @work and includes any consecutive work with
914 * WORK_STRUCT_LINKED set in its predecessor.
916 * If @nextp is not NULL, it's updated to point to the next work of
917 * the last scheduled work. This allows move_linked_works() to be
918 * nested inside outer list_for_each_entry_safe().
921 * spin_lock_irq(gcwq->lock).
923 static void move_linked_works(struct work_struct *work, struct list_head *head,
924 struct work_struct **nextp)
926 struct work_struct *n;
929 * Linked worklist will always end before the end of the list,
930 * use NULL for list head.
932 list_for_each_entry_safe_from(work, n, NULL, entry) {
933 list_move_tail(&work->entry, head);
934 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
939 * If we're already inside safe list traversal and have moved
940 * multiple works to the scheduled queue, the next position
941 * needs to be updated.
947 static void cwq_activate_delayed_work(struct work_struct *work)
949 struct cpu_workqueue_struct *cwq = get_work_cwq(work);
951 trace_workqueue_activate_work(work);
952 move_linked_works(work, &cwq->pool->worklist, NULL);
953 __clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
957 static void cwq_activate_first_delayed(struct cpu_workqueue_struct *cwq)
959 struct work_struct *work = list_first_entry(&cwq->delayed_works,
960 struct work_struct, entry);
962 cwq_activate_delayed_work(work);
966 * cwq_dec_nr_in_flight - decrement cwq's nr_in_flight
967 * @cwq: cwq of interest
968 * @color: color of work which left the queue
970 * A work either has completed or is removed from pending queue,
971 * decrement nr_in_flight of its cwq and handle workqueue flushing.
974 * spin_lock_irq(gcwq->lock).
976 static void cwq_dec_nr_in_flight(struct cpu_workqueue_struct *cwq, int color)
978 /* ignore uncolored works */
979 if (color == WORK_NO_COLOR)
982 cwq->nr_in_flight[color]--;
985 if (!list_empty(&cwq->delayed_works)) {
986 /* one down, submit a delayed one */
987 if (cwq->nr_active < cwq->max_active)
988 cwq_activate_first_delayed(cwq);
991 /* is flush in progress and are we at the flushing tip? */
992 if (likely(cwq->flush_color != color))
995 /* are there still in-flight works? */
996 if (cwq->nr_in_flight[color])
999 /* this cwq is done, clear flush_color */
1000 cwq->flush_color = -1;
1003 * If this was the last cwq, wake up the first flusher. It
1004 * will handle the rest.
1006 if (atomic_dec_and_test(&cwq->wq->nr_cwqs_to_flush))
1007 complete(&cwq->wq->first_flusher->done);
1011 * try_to_grab_pending - steal work item from worklist and disable irq
1012 * @work: work item to steal
1013 * @is_dwork: @work is a delayed_work
1014 * @flags: place to store irq state
1016 * Try to grab PENDING bit of @work. This function can handle @work in any
1017 * stable state - idle, on timer or on worklist. Return values are
1019 * 1 if @work was pending and we successfully stole PENDING
1020 * 0 if @work was idle and we claimed PENDING
1021 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1022 * -ENOENT if someone else is canceling @work, this state may persist
1023 * for arbitrarily long
1025 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1026 * interrupted while holding PENDING and @work off queue, irq must be
1027 * disabled on entry. This, combined with delayed_work->timer being
1028 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1030 * On successful return, >= 0, irq is disabled and the caller is
1031 * responsible for releasing it using local_irq_restore(*@flags).
1033 * This function is safe to call from any context including IRQ handler.
1035 static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1036 unsigned long *flags)
1038 struct global_cwq *gcwq;
1040 local_irq_save(*flags);
1042 /* try to steal the timer if it exists */
1044 struct delayed_work *dwork = to_delayed_work(work);
1047 * dwork->timer is irqsafe. If del_timer() fails, it's
1048 * guaranteed that the timer is not queued anywhere and not
1049 * running on the local CPU.
1051 if (likely(del_timer(&dwork->timer)))
1055 /* try to claim PENDING the normal way */
1056 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1060 * The queueing is in progress, or it is already queued. Try to
1061 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1063 gcwq = get_work_gcwq(work);
1067 spin_lock(&gcwq->lock);
1068 if (!list_empty(&work->entry)) {
1070 * This work is queued, but perhaps we locked the wrong gcwq.
1071 * In that case we must see the new value after rmb(), see
1072 * insert_work()->wmb().
1075 if (gcwq == get_work_gcwq(work)) {
1076 debug_work_deactivate(work);
1079 * A delayed work item cannot be grabbed directly
1080 * because it might have linked NO_COLOR work items
1081 * which, if left on the delayed_list, will confuse
1082 * cwq->nr_active management later on and cause
1083 * stall. Make sure the work item is activated
1086 if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1087 cwq_activate_delayed_work(work);
1089 list_del_init(&work->entry);
1090 cwq_dec_nr_in_flight(get_work_cwq(work),
1091 get_work_color(work));
1093 spin_unlock(&gcwq->lock);
1097 spin_unlock(&gcwq->lock);
1099 local_irq_restore(*flags);
1100 if (work_is_canceling(work))
1107 * insert_work - insert a work into gcwq
1108 * @cwq: cwq @work belongs to
1109 * @work: work to insert
1110 * @head: insertion point
1111 * @extra_flags: extra WORK_STRUCT_* flags to set
1113 * Insert @work which belongs to @cwq into @gcwq after @head.
1114 * @extra_flags is or'd to work_struct flags.
1117 * spin_lock_irq(gcwq->lock).
1119 static void insert_work(struct cpu_workqueue_struct *cwq,
1120 struct work_struct *work, struct list_head *head,
1121 unsigned int extra_flags)
1123 struct worker_pool *pool = cwq->pool;
1125 /* we own @work, set data and link */
1126 set_work_cwq(work, cwq, extra_flags);
1129 * Ensure that we get the right work->data if we see the
1130 * result of list_add() below, see try_to_grab_pending().
1134 list_add_tail(&work->entry, head);
1137 * Ensure either worker_sched_deactivated() sees the above
1138 * list_add_tail() or we see zero nr_running to avoid workers
1139 * lying around lazily while there are works to be processed.
1143 if (__need_more_worker(pool))
1144 wake_up_worker(pool);
1148 * Test whether @work is being queued from another work executing on the
1149 * same workqueue. This is rather expensive and should only be used from
1152 static bool is_chained_work(struct workqueue_struct *wq)
1154 unsigned long flags;
1157 for_each_gcwq_cpu(cpu) {
1158 struct global_cwq *gcwq = get_gcwq(cpu);
1159 struct worker *worker;
1160 struct hlist_node *pos;
1163 spin_lock_irqsave(&gcwq->lock, flags);
1164 for_each_busy_worker(worker, i, pos, gcwq) {
1165 if (worker->task != current)
1167 spin_unlock_irqrestore(&gcwq->lock, flags);
1169 * I'm @worker, no locking necessary. See if @work
1170 * is headed to the same workqueue.
1172 return worker->current_cwq->wq == wq;
1174 spin_unlock_irqrestore(&gcwq->lock, flags);
1179 static void __queue_work(unsigned int cpu, struct workqueue_struct *wq,
1180 struct work_struct *work)
1182 struct global_cwq *gcwq;
1183 struct cpu_workqueue_struct *cwq;
1184 struct list_head *worklist;
1185 unsigned int work_flags;
1186 unsigned int req_cpu = cpu;
1189 * While a work item is PENDING && off queue, a task trying to
1190 * steal the PENDING will busy-loop waiting for it to either get
1191 * queued or lose PENDING. Grabbing PENDING and queueing should
1192 * happen with IRQ disabled.
1194 WARN_ON_ONCE(!irqs_disabled());
1196 debug_work_activate(work);
1198 /* if dying, only works from the same workqueue are allowed */
1199 if (unlikely(wq->flags & WQ_DRAINING) &&
1200 WARN_ON_ONCE(!is_chained_work(wq)))
1203 /* determine gcwq to use */
1204 if (!(wq->flags & WQ_UNBOUND)) {
1205 struct global_cwq *last_gcwq;
1207 if (cpu == WORK_CPU_UNBOUND)
1208 cpu = raw_smp_processor_id();
1211 * It's multi cpu. If @work was previously on a different
1212 * cpu, it might still be running there, in which case the
1213 * work needs to be queued on that cpu to guarantee
1216 gcwq = get_gcwq(cpu);
1217 last_gcwq = get_work_gcwq(work);
1219 if (last_gcwq && last_gcwq != gcwq) {
1220 struct worker *worker;
1222 spin_lock(&last_gcwq->lock);
1224 worker = find_worker_executing_work(last_gcwq, work);
1226 if (worker && worker->current_cwq->wq == wq)
1229 /* meh... not running there, queue here */
1230 spin_unlock(&last_gcwq->lock);
1231 spin_lock(&gcwq->lock);
1234 spin_lock(&gcwq->lock);
1237 gcwq = get_gcwq(WORK_CPU_UNBOUND);
1238 spin_lock(&gcwq->lock);
1241 /* gcwq determined, get cwq and queue */
1242 cwq = get_cwq(gcwq->cpu, wq);
1243 trace_workqueue_queue_work(req_cpu, cwq, work);
1245 if (WARN_ON(!list_empty(&work->entry))) {
1246 spin_unlock(&gcwq->lock);
1250 cwq->nr_in_flight[cwq->work_color]++;
1251 work_flags = work_color_to_flags(cwq->work_color);
1253 if (likely(cwq->nr_active < cwq->max_active)) {
1254 trace_workqueue_activate_work(work);
1256 worklist = &cwq->pool->worklist;
1258 work_flags |= WORK_STRUCT_DELAYED;
1259 worklist = &cwq->delayed_works;
1262 insert_work(cwq, work, worklist, work_flags);
1264 spin_unlock(&gcwq->lock);
1268 * queue_work_on - queue work on specific cpu
1269 * @cpu: CPU number to execute work on
1270 * @wq: workqueue to use
1271 * @work: work to queue
1273 * Returns %false if @work was already on a queue, %true otherwise.
1275 * We queue the work to a specific CPU, the caller must ensure it
1278 bool queue_work_on(int cpu, struct workqueue_struct *wq,
1279 struct work_struct *work)
1282 unsigned long flags;
1284 local_irq_save(flags);
1286 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1287 __queue_work(cpu, wq, work);
1291 local_irq_restore(flags);
1294 EXPORT_SYMBOL_GPL(queue_work_on);
1297 * queue_work - queue work on a workqueue
1298 * @wq: workqueue to use
1299 * @work: work to queue
1301 * Returns %false if @work was already on a queue, %true otherwise.
1303 * We queue the work to the CPU on which it was submitted, but if the CPU dies
1304 * it can be processed by another CPU.
1306 bool queue_work(struct workqueue_struct *wq, struct work_struct *work)
1308 return queue_work_on(WORK_CPU_UNBOUND, wq, work);
1310 EXPORT_SYMBOL_GPL(queue_work);
1312 void delayed_work_timer_fn(unsigned long __data)
1314 struct delayed_work *dwork = (struct delayed_work *)__data;
1315 struct cpu_workqueue_struct *cwq = get_work_cwq(&dwork->work);
1317 /* should have been called from irqsafe timer with irq already off */
1318 __queue_work(dwork->cpu, cwq->wq, &dwork->work);
1320 EXPORT_SYMBOL_GPL(delayed_work_timer_fn);
1322 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
1323 struct delayed_work *dwork, unsigned long delay)
1325 struct timer_list *timer = &dwork->timer;
1326 struct work_struct *work = &dwork->work;
1329 WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
1330 timer->data != (unsigned long)dwork);
1331 WARN_ON_ONCE(timer_pending(timer));
1332 WARN_ON_ONCE(!list_empty(&work->entry));
1335 * If @delay is 0, queue @dwork->work immediately. This is for
1336 * both optimization and correctness. The earliest @timer can
1337 * expire is on the closest next tick and delayed_work users depend
1338 * on that there's no such delay when @delay is 0.
1341 __queue_work(cpu, wq, &dwork->work);
1345 timer_stats_timer_set_start_info(&dwork->timer);
1348 * This stores cwq for the moment, for the timer_fn. Note that the
1349 * work's gcwq is preserved to allow reentrance detection for
1352 if (!(wq->flags & WQ_UNBOUND)) {
1353 struct global_cwq *gcwq = get_work_gcwq(work);
1356 * If we cannot get the last gcwq from @work directly,
1357 * select the last CPU such that it avoids unnecessarily
1358 * triggering non-reentrancy check in __queue_work().
1363 if (lcpu == WORK_CPU_UNBOUND)
1364 lcpu = raw_smp_processor_id();
1366 lcpu = WORK_CPU_UNBOUND;
1369 set_work_cwq(work, get_cwq(lcpu, wq), 0);
1372 timer->expires = jiffies + delay;
1374 if (unlikely(cpu != WORK_CPU_UNBOUND))
1375 add_timer_on(timer, cpu);
1381 * queue_delayed_work_on - queue work on specific CPU after delay
1382 * @cpu: CPU number to execute work on
1383 * @wq: workqueue to use
1384 * @dwork: work to queue
1385 * @delay: number of jiffies to wait before queueing
1387 * Returns %false if @work was already on a queue, %true otherwise. If
1388 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1391 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1392 struct delayed_work *dwork, unsigned long delay)
1394 struct work_struct *work = &dwork->work;
1396 unsigned long flags;
1398 /* read the comment in __queue_work() */
1399 local_irq_save(flags);
1401 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1402 __queue_delayed_work(cpu, wq, dwork, delay);
1406 local_irq_restore(flags);
1409 EXPORT_SYMBOL_GPL(queue_delayed_work_on);
1412 * queue_delayed_work - queue work on a workqueue after delay
1413 * @wq: workqueue to use
1414 * @dwork: delayable work to queue
1415 * @delay: number of jiffies to wait before queueing
1417 * Equivalent to queue_delayed_work_on() but tries to use the local CPU.
1419 bool queue_delayed_work(struct workqueue_struct *wq,
1420 struct delayed_work *dwork, unsigned long delay)
1422 return queue_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
1424 EXPORT_SYMBOL_GPL(queue_delayed_work);
1427 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1428 * @cpu: CPU number to execute work on
1429 * @wq: workqueue to use
1430 * @dwork: work to queue
1431 * @delay: number of jiffies to wait before queueing
1433 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1434 * modify @dwork's timer so that it expires after @delay. If @delay is
1435 * zero, @work is guaranteed to be scheduled immediately regardless of its
1438 * Returns %false if @dwork was idle and queued, %true if @dwork was
1439 * pending and its timer was modified.
1441 * This function is safe to call from any context including IRQ handler.
1442 * See try_to_grab_pending() for details.
1444 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
1445 struct delayed_work *dwork, unsigned long delay)
1447 unsigned long flags;
1451 ret = try_to_grab_pending(&dwork->work, true, &flags);
1452 } while (unlikely(ret == -EAGAIN));
1454 if (likely(ret >= 0)) {
1455 __queue_delayed_work(cpu, wq, dwork, delay);
1456 local_irq_restore(flags);
1459 /* -ENOENT from try_to_grab_pending() becomes %true */
1462 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
1465 * mod_delayed_work - modify delay of or queue a delayed work
1466 * @wq: workqueue to use
1467 * @dwork: work to queue
1468 * @delay: number of jiffies to wait before queueing
1470 * mod_delayed_work_on() on local CPU.
1472 bool mod_delayed_work(struct workqueue_struct *wq, struct delayed_work *dwork,
1473 unsigned long delay)
1475 return mod_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
1477 EXPORT_SYMBOL_GPL(mod_delayed_work);
1480 * worker_enter_idle - enter idle state
1481 * @worker: worker which is entering idle state
1483 * @worker is entering idle state. Update stats and idle timer if
1487 * spin_lock_irq(gcwq->lock).
1489 static void worker_enter_idle(struct worker *worker)
1491 struct worker_pool *pool = worker->pool;
1493 BUG_ON(worker->flags & WORKER_IDLE);
1494 BUG_ON(!list_empty(&worker->entry) &&
1495 (worker->hentry.next || worker->hentry.pprev));
1497 /* can't use worker_set_flags(), also called from start_worker() */
1498 worker->flags |= WORKER_IDLE;
1500 worker->last_active = jiffies;
1502 /* idle_list is LIFO */
1503 list_add(&worker->entry, &pool->idle_list);
1505 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1506 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1509 * Sanity check nr_running. Because gcwq_unbind_fn() releases
1510 * gcwq->lock between setting %WORKER_UNBOUND and zapping
1511 * nr_running, the warning may trigger spuriously. Check iff
1512 * unbind is not in progress.
1514 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1515 pool->nr_workers == pool->nr_idle &&
1516 atomic_read(get_pool_nr_running(pool)));
1520 * worker_leave_idle - leave idle state
1521 * @worker: worker which is leaving idle state
1523 * @worker is leaving idle state. Update stats.
1526 * spin_lock_irq(gcwq->lock).
1528 static void worker_leave_idle(struct worker *worker)
1530 struct worker_pool *pool = worker->pool;
1532 BUG_ON(!(worker->flags & WORKER_IDLE));
1533 worker_clr_flags(worker, WORKER_IDLE);
1535 list_del_init(&worker->entry);
1539 * worker_maybe_bind_and_lock - bind worker to its cpu if possible and lock gcwq
1542 * Works which are scheduled while the cpu is online must at least be
1543 * scheduled to a worker which is bound to the cpu so that if they are
1544 * flushed from cpu callbacks while cpu is going down, they are
1545 * guaranteed to execute on the cpu.
1547 * This function is to be used by rogue workers and rescuers to bind
1548 * themselves to the target cpu and may race with cpu going down or
1549 * coming online. kthread_bind() can't be used because it may put the
1550 * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1551 * verbatim as it's best effort and blocking and gcwq may be
1552 * [dis]associated in the meantime.
1554 * This function tries set_cpus_allowed() and locks gcwq and verifies the
1555 * binding against %POOL_DISASSOCIATED which is set during
1556 * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
1557 * enters idle state or fetches works without dropping lock, it can
1558 * guarantee the scheduling requirement described in the first paragraph.
1561 * Might sleep. Called without any lock but returns with gcwq->lock
1565 * %true if the associated gcwq is online (@worker is successfully
1566 * bound), %false if offline.
1568 static bool worker_maybe_bind_and_lock(struct worker *worker)
1569 __acquires(&gcwq->lock)
1571 struct worker_pool *pool = worker->pool;
1572 struct global_cwq *gcwq = pool->gcwq;
1573 struct task_struct *task = worker->task;
1577 * The following call may fail, succeed or succeed
1578 * without actually migrating the task to the cpu if
1579 * it races with cpu hotunplug operation. Verify
1580 * against POOL_DISASSOCIATED.
1582 if (!(pool->flags & POOL_DISASSOCIATED))
1583 set_cpus_allowed_ptr(task, get_cpu_mask(gcwq->cpu));
1585 spin_lock_irq(&gcwq->lock);
1586 if (pool->flags & POOL_DISASSOCIATED)
1588 if (task_cpu(task) == gcwq->cpu &&
1589 cpumask_equal(¤t->cpus_allowed,
1590 get_cpu_mask(gcwq->cpu)))
1592 spin_unlock_irq(&gcwq->lock);
1595 * We've raced with CPU hot[un]plug. Give it a breather
1596 * and retry migration. cond_resched() is required here;
1597 * otherwise, we might deadlock against cpu_stop trying to
1598 * bring down the CPU on non-preemptive kernel.
1606 * Rebind an idle @worker to its CPU. worker_thread() will test
1607 * list_empty(@worker->entry) before leaving idle and call this function.
1609 static void idle_worker_rebind(struct worker *worker)
1611 struct global_cwq *gcwq = worker->pool->gcwq;
1613 /* CPU may go down again inbetween, clear UNBOUND only on success */
1614 if (worker_maybe_bind_and_lock(worker))
1615 worker_clr_flags(worker, WORKER_UNBOUND);
1617 /* rebind complete, become available again */
1618 list_add(&worker->entry, &worker->pool->idle_list);
1619 spin_unlock_irq(&gcwq->lock);
1623 * Function for @worker->rebind.work used to rebind unbound busy workers to
1624 * the associated cpu which is coming back online. This is scheduled by
1625 * cpu up but can race with other cpu hotplug operations and may be
1626 * executed twice without intervening cpu down.
1628 static void busy_worker_rebind_fn(struct work_struct *work)
1630 struct worker *worker = container_of(work, struct worker, rebind_work);
1631 struct global_cwq *gcwq = worker->pool->gcwq;
1633 if (worker_maybe_bind_and_lock(worker))
1634 worker_clr_flags(worker, WORKER_UNBOUND);
1636 spin_unlock_irq(&gcwq->lock);
1640 * rebind_workers - rebind all workers of a gcwq to the associated CPU
1641 * @gcwq: gcwq of interest
1643 * @gcwq->cpu is coming online. Rebind all workers to the CPU. Rebinding
1644 * is different for idle and busy ones.
1646 * Idle ones will be removed from the idle_list and woken up. They will
1647 * add themselves back after completing rebind. This ensures that the
1648 * idle_list doesn't contain any unbound workers when re-bound busy workers
1649 * try to perform local wake-ups for concurrency management.
1651 * Busy workers can rebind after they finish their current work items.
1652 * Queueing the rebind work item at the head of the scheduled list is
1653 * enough. Note that nr_running will be properly bumped as busy workers
1656 * On return, all non-manager workers are scheduled for rebind - see
1657 * manage_workers() for the manager special case. Any idle worker
1658 * including the manager will not appear on @idle_list until rebind is
1659 * complete, making local wake-ups safe.
1661 static void rebind_workers(struct global_cwq *gcwq)
1663 struct worker_pool *pool;
1664 struct worker *worker, *n;
1665 struct hlist_node *pos;
1668 lockdep_assert_held(&gcwq->lock);
1670 for_each_worker_pool(pool, gcwq)
1671 lockdep_assert_held(&pool->assoc_mutex);
1673 /* dequeue and kick idle ones */
1674 for_each_worker_pool(pool, gcwq) {
1675 list_for_each_entry_safe(worker, n, &pool->idle_list, entry) {
1677 * idle workers should be off @pool->idle_list
1678 * until rebind is complete to avoid receiving
1679 * premature local wake-ups.
1681 list_del_init(&worker->entry);
1684 * worker_thread() will see the above dequeuing
1685 * and call idle_worker_rebind().
1687 wake_up_process(worker->task);
1691 /* rebind busy workers */
1692 for_each_busy_worker(worker, i, pos, gcwq) {
1693 struct work_struct *rebind_work = &worker->rebind_work;
1694 struct workqueue_struct *wq;
1696 if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
1697 work_data_bits(rebind_work)))
1700 debug_work_activate(rebind_work);
1703 * wq doesn't really matter but let's keep @worker->pool
1704 * and @cwq->pool consistent for sanity.
1706 if (std_worker_pool_pri(worker->pool))
1707 wq = system_highpri_wq;
1711 insert_work(get_cwq(gcwq->cpu, wq), rebind_work,
1712 worker->scheduled.next,
1713 work_color_to_flags(WORK_NO_COLOR));
1717 static struct worker *alloc_worker(void)
1719 struct worker *worker;
1721 worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1723 INIT_LIST_HEAD(&worker->entry);
1724 INIT_LIST_HEAD(&worker->scheduled);
1725 INIT_WORK(&worker->rebind_work, busy_worker_rebind_fn);
1726 /* on creation a worker is in !idle && prep state */
1727 worker->flags = WORKER_PREP;
1733 * create_worker - create a new workqueue worker
1734 * @pool: pool the new worker will belong to
1736 * Create a new worker which is bound to @pool. The returned worker
1737 * can be started by calling start_worker() or destroyed using
1741 * Might sleep. Does GFP_KERNEL allocations.
1744 * Pointer to the newly created worker.
1746 static struct worker *create_worker(struct worker_pool *pool)
1748 struct global_cwq *gcwq = pool->gcwq;
1749 const char *pri = std_worker_pool_pri(pool) ? "H" : "";
1750 struct worker *worker = NULL;
1753 spin_lock_irq(&gcwq->lock);
1754 while (ida_get_new(&pool->worker_ida, &id)) {
1755 spin_unlock_irq(&gcwq->lock);
1756 if (!ida_pre_get(&pool->worker_ida, GFP_KERNEL))
1758 spin_lock_irq(&gcwq->lock);
1760 spin_unlock_irq(&gcwq->lock);
1762 worker = alloc_worker();
1766 worker->pool = pool;
1769 if (gcwq->cpu != WORK_CPU_UNBOUND)
1770 worker->task = kthread_create_on_node(worker_thread,
1771 worker, cpu_to_node(gcwq->cpu),
1772 "kworker/%u:%d%s", gcwq->cpu, id, pri);
1774 worker->task = kthread_create(worker_thread, worker,
1775 "kworker/u:%d%s", id, pri);
1776 if (IS_ERR(worker->task))
1779 if (std_worker_pool_pri(pool))
1780 set_user_nice(worker->task, HIGHPRI_NICE_LEVEL);
1783 * Determine CPU binding of the new worker depending on
1784 * %POOL_DISASSOCIATED. The caller is responsible for ensuring the
1785 * flag remains stable across this function. See the comments
1786 * above the flag definition for details.
1788 * As an unbound worker may later become a regular one if CPU comes
1789 * online, make sure every worker has %PF_THREAD_BOUND set.
1791 if (!(pool->flags & POOL_DISASSOCIATED)) {
1792 kthread_bind(worker->task, gcwq->cpu);
1794 worker->task->flags |= PF_THREAD_BOUND;
1795 worker->flags |= WORKER_UNBOUND;
1801 spin_lock_irq(&gcwq->lock);
1802 ida_remove(&pool->worker_ida, id);
1803 spin_unlock_irq(&gcwq->lock);
1810 * start_worker - start a newly created worker
1811 * @worker: worker to start
1813 * Make the gcwq aware of @worker and start it.
1816 * spin_lock_irq(gcwq->lock).
1818 static void start_worker(struct worker *worker)
1820 worker->flags |= WORKER_STARTED;
1821 worker->pool->nr_workers++;
1822 worker_enter_idle(worker);
1823 wake_up_process(worker->task);
1827 * destroy_worker - destroy a workqueue worker
1828 * @worker: worker to be destroyed
1830 * Destroy @worker and adjust @gcwq stats accordingly.
1833 * spin_lock_irq(gcwq->lock) which is released and regrabbed.
1835 static void destroy_worker(struct worker *worker)
1837 struct worker_pool *pool = worker->pool;
1838 struct global_cwq *gcwq = pool->gcwq;
1839 int id = worker->id;
1841 /* sanity check frenzy */
1842 BUG_ON(worker->current_work);
1843 BUG_ON(!list_empty(&worker->scheduled));
1845 if (worker->flags & WORKER_STARTED)
1847 if (worker->flags & WORKER_IDLE)
1850 list_del_init(&worker->entry);
1851 worker->flags |= WORKER_DIE;
1853 spin_unlock_irq(&gcwq->lock);
1855 kthread_stop(worker->task);
1858 spin_lock_irq(&gcwq->lock);
1859 ida_remove(&pool->worker_ida, id);
1862 static void idle_worker_timeout(unsigned long __pool)
1864 struct worker_pool *pool = (void *)__pool;
1865 struct global_cwq *gcwq = pool->gcwq;
1867 spin_lock_irq(&gcwq->lock);
1869 if (too_many_workers(pool)) {
1870 struct worker *worker;
1871 unsigned long expires;
1873 /* idle_list is kept in LIFO order, check the last one */
1874 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1875 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1877 if (time_before(jiffies, expires))
1878 mod_timer(&pool->idle_timer, expires);
1880 /* it's been idle for too long, wake up manager */
1881 pool->flags |= POOL_MANAGE_WORKERS;
1882 wake_up_worker(pool);
1886 spin_unlock_irq(&gcwq->lock);
1889 static bool send_mayday(struct work_struct *work)
1891 struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1892 struct workqueue_struct *wq = cwq->wq;
1895 if (!(wq->flags & WQ_RESCUER))
1898 /* mayday mayday mayday */
1899 cpu = cwq->pool->gcwq->cpu;
1900 /* WORK_CPU_UNBOUND can't be set in cpumask, use cpu 0 instead */
1901 if (cpu == WORK_CPU_UNBOUND)
1903 if (!mayday_test_and_set_cpu(cpu, wq->mayday_mask))
1904 wake_up_process(wq->rescuer->task);
1908 static void gcwq_mayday_timeout(unsigned long __pool)
1910 struct worker_pool *pool = (void *)__pool;
1911 struct global_cwq *gcwq = pool->gcwq;
1912 struct work_struct *work;
1914 spin_lock_irq(&gcwq->lock);
1916 if (need_to_create_worker(pool)) {
1918 * We've been trying to create a new worker but
1919 * haven't been successful. We might be hitting an
1920 * allocation deadlock. Send distress signals to
1923 list_for_each_entry(work, &pool->worklist, entry)
1927 spin_unlock_irq(&gcwq->lock);
1929 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1933 * maybe_create_worker - create a new worker if necessary
1934 * @pool: pool to create a new worker for
1936 * Create a new worker for @pool if necessary. @pool is guaranteed to
1937 * have at least one idle worker on return from this function. If
1938 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1939 * sent to all rescuers with works scheduled on @pool to resolve
1940 * possible allocation deadlock.
1942 * On return, need_to_create_worker() is guaranteed to be false and
1943 * may_start_working() true.
1946 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1947 * multiple times. Does GFP_KERNEL allocations. Called only from
1951 * false if no action was taken and gcwq->lock stayed locked, true
1954 static bool maybe_create_worker(struct worker_pool *pool)
1955 __releases(&gcwq->lock)
1956 __acquires(&gcwq->lock)
1958 struct global_cwq *gcwq = pool->gcwq;
1960 if (!need_to_create_worker(pool))
1963 spin_unlock_irq(&gcwq->lock);
1965 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1966 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1969 struct worker *worker;
1971 worker = create_worker(pool);
1973 del_timer_sync(&pool->mayday_timer);
1974 spin_lock_irq(&gcwq->lock);
1975 start_worker(worker);
1976 BUG_ON(need_to_create_worker(pool));
1980 if (!need_to_create_worker(pool))
1983 __set_current_state(TASK_INTERRUPTIBLE);
1984 schedule_timeout(CREATE_COOLDOWN);
1986 if (!need_to_create_worker(pool))
1990 del_timer_sync(&pool->mayday_timer);
1991 spin_lock_irq(&gcwq->lock);
1992 if (need_to_create_worker(pool))
1998 * maybe_destroy_worker - destroy workers which have been idle for a while
1999 * @pool: pool to destroy workers for
2001 * Destroy @pool workers which have been idle for longer than
2002 * IDLE_WORKER_TIMEOUT.
2005 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2006 * multiple times. Called only from manager.
2009 * false if no action was taken and gcwq->lock stayed locked, true
2012 static bool maybe_destroy_workers(struct worker_pool *pool)
2016 while (too_many_workers(pool)) {
2017 struct worker *worker;
2018 unsigned long expires;
2020 worker = list_entry(pool->idle_list.prev, struct worker, entry);
2021 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2023 if (time_before(jiffies, expires)) {
2024 mod_timer(&pool->idle_timer, expires);
2028 destroy_worker(worker);
2036 * manage_workers - manage worker pool
2039 * Assume the manager role and manage gcwq worker pool @worker belongs
2040 * to. At any given time, there can be only zero or one manager per
2041 * gcwq. The exclusion is handled automatically by this function.
2043 * The caller can safely start processing works on false return. On
2044 * true return, it's guaranteed that need_to_create_worker() is false
2045 * and may_start_working() is true.
2048 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2049 * multiple times. Does GFP_KERNEL allocations.
2052 * false if no action was taken and gcwq->lock stayed locked, true if
2053 * some action was taken.
2055 static bool manage_workers(struct worker *worker)
2057 struct worker_pool *pool = worker->pool;
2060 if (pool->flags & POOL_MANAGING_WORKERS)
2063 pool->flags |= POOL_MANAGING_WORKERS;
2066 * To simplify both worker management and CPU hotplug, hold off
2067 * management while hotplug is in progress. CPU hotplug path can't
2068 * grab %POOL_MANAGING_WORKERS to achieve this because that can
2069 * lead to idle worker depletion (all become busy thinking someone
2070 * else is managing) which in turn can result in deadlock under
2071 * extreme circumstances. Use @pool->assoc_mutex to synchronize
2072 * manager against CPU hotplug.
2074 * assoc_mutex would always be free unless CPU hotplug is in
2075 * progress. trylock first without dropping @gcwq->lock.
2077 if (unlikely(!mutex_trylock(&pool->assoc_mutex))) {
2078 spin_unlock_irq(&pool->gcwq->lock);
2079 mutex_lock(&pool->assoc_mutex);
2081 * CPU hotplug could have happened while we were waiting
2082 * for assoc_mutex. Hotplug itself can't handle us
2083 * because manager isn't either on idle or busy list, and
2084 * @gcwq's state and ours could have deviated.
2086 * As hotplug is now excluded via assoc_mutex, we can
2087 * simply try to bind. It will succeed or fail depending
2088 * on @gcwq's current state. Try it and adjust
2089 * %WORKER_UNBOUND accordingly.
2091 if (worker_maybe_bind_and_lock(worker))
2092 worker->flags &= ~WORKER_UNBOUND;
2094 worker->flags |= WORKER_UNBOUND;
2099 pool->flags &= ~POOL_MANAGE_WORKERS;
2102 * Destroy and then create so that may_start_working() is true
2105 ret |= maybe_destroy_workers(pool);
2106 ret |= maybe_create_worker(pool);
2108 pool->flags &= ~POOL_MANAGING_WORKERS;
2109 mutex_unlock(&pool->assoc_mutex);
2114 * process_one_work - process single work
2116 * @work: work to process
2118 * Process @work. This function contains all the logics necessary to
2119 * process a single work including synchronization against and
2120 * interaction with other workers on the same cpu, queueing and
2121 * flushing. As long as context requirement is met, any worker can
2122 * call this function to process a work.
2125 * spin_lock_irq(gcwq->lock) which is released and regrabbed.
2127 static void process_one_work(struct worker *worker, struct work_struct *work)
2128 __releases(&gcwq->lock)
2129 __acquires(&gcwq->lock)
2131 struct cpu_workqueue_struct *cwq = get_work_cwq(work);
2132 struct worker_pool *pool = worker->pool;
2133 struct global_cwq *gcwq = pool->gcwq;
2134 bool cpu_intensive = cwq->wq->flags & WQ_CPU_INTENSIVE;
2136 struct worker *collision;
2137 #ifdef CONFIG_LOCKDEP
2139 * It is permissible to free the struct work_struct from
2140 * inside the function that is called from it, this we need to
2141 * take into account for lockdep too. To avoid bogus "held
2142 * lock freed" warnings as well as problems when looking into
2143 * work->lockdep_map, make a copy and use that here.
2145 struct lockdep_map lockdep_map;
2147 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
2150 * Ensure we're on the correct CPU. DISASSOCIATED test is
2151 * necessary to avoid spurious warnings from rescuers servicing the
2152 * unbound or a disassociated pool.
2154 WARN_ON_ONCE(!(worker->flags & WORKER_UNBOUND) &&
2155 !(pool->flags & POOL_DISASSOCIATED) &&
2156 raw_smp_processor_id() != gcwq->cpu);
2159 * A single work shouldn't be executed concurrently by
2160 * multiple workers on a single cpu. Check whether anyone is
2161 * already processing the work. If so, defer the work to the
2162 * currently executing one.
2164 collision = find_worker_executing_work(gcwq, work);
2165 if (unlikely(collision)) {
2166 move_linked_works(work, &collision->scheduled, NULL);
2170 /* claim and dequeue */
2171 debug_work_deactivate(work);
2172 hash_add(gcwq->busy_hash, &worker->hentry, (unsigned long)work);
2173 worker->current_work = work;
2174 worker->current_func = work->func;
2175 worker->current_cwq = cwq;
2176 work_color = get_work_color(work);
2178 list_del_init(&work->entry);
2181 * CPU intensive works don't participate in concurrency
2182 * management. They're the scheduler's responsibility.
2184 if (unlikely(cpu_intensive))
2185 worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
2188 * Unbound gcwq isn't concurrency managed and work items should be
2189 * executed ASAP. Wake up another worker if necessary.
2191 if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
2192 wake_up_worker(pool);
2195 * Record the last CPU and clear PENDING which should be the last
2196 * update to @work. Also, do this inside @gcwq->lock so that
2197 * PENDING and queued state changes happen together while IRQ is
2200 set_work_cpu_and_clear_pending(work, gcwq->cpu);
2202 spin_unlock_irq(&gcwq->lock);
2204 lock_map_acquire_read(&cwq->wq->lockdep_map);
2205 lock_map_acquire(&lockdep_map);
2206 trace_workqueue_execute_start(work);
2207 worker->current_func(work);
2209 * While we must be careful to not use "work" after this, the trace
2210 * point will only record its address.
2212 trace_workqueue_execute_end(work);
2213 lock_map_release(&lockdep_map);
2214 lock_map_release(&cwq->wq->lockdep_map);
2216 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2217 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2218 " last function: %pf\n",
2219 current->comm, preempt_count(), task_pid_nr(current),
2220 worker->current_func);
2221 debug_show_held_locks(current);
2225 spin_lock_irq(&gcwq->lock);
2227 /* clear cpu intensive status */
2228 if (unlikely(cpu_intensive))
2229 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2231 /* we're done with it, release */
2232 hash_del(&worker->hentry);
2233 worker->current_work = NULL;
2234 worker->current_func = NULL;
2235 worker->current_cwq = NULL;
2236 cwq_dec_nr_in_flight(cwq, work_color);
2240 * process_scheduled_works - process scheduled works
2243 * Process all scheduled works. Please note that the scheduled list
2244 * may change while processing a work, so this function repeatedly
2245 * fetches a work from the top and executes it.
2248 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2251 static void process_scheduled_works(struct worker *worker)
2253 while (!list_empty(&worker->scheduled)) {
2254 struct work_struct *work = list_first_entry(&worker->scheduled,
2255 struct work_struct, entry);
2256 process_one_work(worker, work);
2261 * worker_thread - the worker thread function
2264 * The gcwq worker thread function. There's a single dynamic pool of
2265 * these per each cpu. These workers process all works regardless of
2266 * their specific target workqueue. The only exception is works which
2267 * belong to workqueues with a rescuer which will be explained in
2270 static int worker_thread(void *__worker)
2272 struct worker *worker = __worker;
2273 struct worker_pool *pool = worker->pool;
2274 struct global_cwq *gcwq = pool->gcwq;
2276 /* tell the scheduler that this is a workqueue worker */
2277 worker->task->flags |= PF_WQ_WORKER;
2279 spin_lock_irq(&gcwq->lock);
2281 /* we are off idle list if destruction or rebind is requested */
2282 if (unlikely(list_empty(&worker->entry))) {
2283 spin_unlock_irq(&gcwq->lock);
2285 /* if DIE is set, destruction is requested */
2286 if (worker->flags & WORKER_DIE) {
2287 worker->task->flags &= ~PF_WQ_WORKER;
2291 /* otherwise, rebind */
2292 idle_worker_rebind(worker);
2296 worker_leave_idle(worker);
2298 /* no more worker necessary? */
2299 if (!need_more_worker(pool))
2302 /* do we need to manage? */
2303 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2307 * ->scheduled list can only be filled while a worker is
2308 * preparing to process a work or actually processing it.
2309 * Make sure nobody diddled with it while I was sleeping.
2311 BUG_ON(!list_empty(&worker->scheduled));
2314 * When control reaches this point, we're guaranteed to have
2315 * at least one idle worker or that someone else has already
2316 * assumed the manager role.
2318 worker_clr_flags(worker, WORKER_PREP);
2321 struct work_struct *work =
2322 list_first_entry(&pool->worklist,
2323 struct work_struct, entry);
2325 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2326 /* optimization path, not strictly necessary */
2327 process_one_work(worker, work);
2328 if (unlikely(!list_empty(&worker->scheduled)))
2329 process_scheduled_works(worker);
2331 move_linked_works(work, &worker->scheduled, NULL);
2332 process_scheduled_works(worker);
2334 } while (keep_working(pool));
2336 worker_set_flags(worker, WORKER_PREP, false);
2338 if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
2342 * gcwq->lock is held and there's no work to process and no
2343 * need to manage, sleep. Workers are woken up only while
2344 * holding gcwq->lock or from local cpu, so setting the
2345 * current state before releasing gcwq->lock is enough to
2346 * prevent losing any event.
2348 worker_enter_idle(worker);
2349 __set_current_state(TASK_INTERRUPTIBLE);
2350 spin_unlock_irq(&gcwq->lock);
2356 * rescuer_thread - the rescuer thread function
2359 * Workqueue rescuer thread function. There's one rescuer for each
2360 * workqueue which has WQ_RESCUER set.
2362 * Regular work processing on a gcwq may block trying to create a new
2363 * worker which uses GFP_KERNEL allocation which has slight chance of
2364 * developing into deadlock if some works currently on the same queue
2365 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2366 * the problem rescuer solves.
2368 * When such condition is possible, the gcwq summons rescuers of all
2369 * workqueues which have works queued on the gcwq and let them process
2370 * those works so that forward progress can be guaranteed.
2372 * This should happen rarely.
2374 static int rescuer_thread(void *__rescuer)
2376 struct worker *rescuer = __rescuer;
2377 struct workqueue_struct *wq = rescuer->rescue_wq;
2378 struct list_head *scheduled = &rescuer->scheduled;
2379 bool is_unbound = wq->flags & WQ_UNBOUND;
2382 set_user_nice(current, RESCUER_NICE_LEVEL);
2385 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2386 * doesn't participate in concurrency management.
2388 rescuer->task->flags |= PF_WQ_WORKER;
2390 set_current_state(TASK_INTERRUPTIBLE);
2392 if (kthread_should_stop()) {
2393 __set_current_state(TASK_RUNNING);
2394 rescuer->task->flags &= ~PF_WQ_WORKER;
2399 * See whether any cpu is asking for help. Unbounded
2400 * workqueues use cpu 0 in mayday_mask for CPU_UNBOUND.
2402 for_each_mayday_cpu(cpu, wq->mayday_mask) {
2403 unsigned int tcpu = is_unbound ? WORK_CPU_UNBOUND : cpu;
2404 struct cpu_workqueue_struct *cwq = get_cwq(tcpu, wq);
2405 struct worker_pool *pool = cwq->pool;
2406 struct global_cwq *gcwq = pool->gcwq;
2407 struct work_struct *work, *n;
2409 __set_current_state(TASK_RUNNING);
2410 mayday_clear_cpu(cpu, wq->mayday_mask);
2412 /* migrate to the target cpu if possible */
2413 rescuer->pool = pool;
2414 worker_maybe_bind_and_lock(rescuer);
2417 * Slurp in all works issued via this workqueue and
2420 BUG_ON(!list_empty(&rescuer->scheduled));
2421 list_for_each_entry_safe(work, n, &pool->worklist, entry)
2422 if (get_work_cwq(work) == cwq)
2423 move_linked_works(work, scheduled, &n);
2425 process_scheduled_works(rescuer);
2428 * Leave this gcwq. If keep_working() is %true, notify a
2429 * regular worker; otherwise, we end up with 0 concurrency
2430 * and stalling the execution.
2432 if (keep_working(pool))
2433 wake_up_worker(pool);
2435 spin_unlock_irq(&gcwq->lock);
2438 /* rescuers should never participate in concurrency management */
2439 WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2445 struct work_struct work;
2446 struct completion done;
2449 static void wq_barrier_func(struct work_struct *work)
2451 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2452 complete(&barr->done);
2456 * insert_wq_barrier - insert a barrier work
2457 * @cwq: cwq to insert barrier into
2458 * @barr: wq_barrier to insert
2459 * @target: target work to attach @barr to
2460 * @worker: worker currently executing @target, NULL if @target is not executing
2462 * @barr is linked to @target such that @barr is completed only after
2463 * @target finishes execution. Please note that the ordering
2464 * guarantee is observed only with respect to @target and on the local
2467 * Currently, a queued barrier can't be canceled. This is because
2468 * try_to_grab_pending() can't determine whether the work to be
2469 * grabbed is at the head of the queue and thus can't clear LINKED
2470 * flag of the previous work while there must be a valid next work
2471 * after a work with LINKED flag set.
2473 * Note that when @worker is non-NULL, @target may be modified
2474 * underneath us, so we can't reliably determine cwq from @target.
2477 * spin_lock_irq(gcwq->lock).
2479 static void insert_wq_barrier(struct cpu_workqueue_struct *cwq,
2480 struct wq_barrier *barr,
2481 struct work_struct *target, struct worker *worker)
2483 struct list_head *head;
2484 unsigned int linked = 0;
2487 * debugobject calls are safe here even with gcwq->lock locked
2488 * as we know for sure that this will not trigger any of the
2489 * checks and call back into the fixup functions where we
2492 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2493 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2494 init_completion(&barr->done);
2497 * If @target is currently being executed, schedule the
2498 * barrier to the worker; otherwise, put it after @target.
2501 head = worker->scheduled.next;
2503 unsigned long *bits = work_data_bits(target);
2505 head = target->entry.next;
2506 /* there can already be other linked works, inherit and set */
2507 linked = *bits & WORK_STRUCT_LINKED;
2508 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2511 debug_work_activate(&barr->work);
2512 insert_work(cwq, &barr->work, head,
2513 work_color_to_flags(WORK_NO_COLOR) | linked);
2517 * flush_workqueue_prep_cwqs - prepare cwqs for workqueue flushing
2518 * @wq: workqueue being flushed
2519 * @flush_color: new flush color, < 0 for no-op
2520 * @work_color: new work color, < 0 for no-op
2522 * Prepare cwqs for workqueue flushing.
2524 * If @flush_color is non-negative, flush_color on all cwqs should be
2525 * -1. If no cwq has in-flight commands at the specified color, all
2526 * cwq->flush_color's stay at -1 and %false is returned. If any cwq
2527 * has in flight commands, its cwq->flush_color is set to
2528 * @flush_color, @wq->nr_cwqs_to_flush is updated accordingly, cwq
2529 * wakeup logic is armed and %true is returned.
2531 * The caller should have initialized @wq->first_flusher prior to
2532 * calling this function with non-negative @flush_color. If
2533 * @flush_color is negative, no flush color update is done and %false
2536 * If @work_color is non-negative, all cwqs should have the same
2537 * work_color which is previous to @work_color and all will be
2538 * advanced to @work_color.
2541 * mutex_lock(wq->flush_mutex).
2544 * %true if @flush_color >= 0 and there's something to flush. %false
2547 static bool flush_workqueue_prep_cwqs(struct workqueue_struct *wq,
2548 int flush_color, int work_color)
2553 if (flush_color >= 0) {
2554 BUG_ON(atomic_read(&wq->nr_cwqs_to_flush));
2555 atomic_set(&wq->nr_cwqs_to_flush, 1);
2558 for_each_cwq_cpu(cpu, wq) {
2559 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2560 struct global_cwq *gcwq = cwq->pool->gcwq;
2562 spin_lock_irq(&gcwq->lock);
2564 if (flush_color >= 0) {
2565 BUG_ON(cwq->flush_color != -1);
2567 if (cwq->nr_in_flight[flush_color]) {
2568 cwq->flush_color = flush_color;
2569 atomic_inc(&wq->nr_cwqs_to_flush);
2574 if (work_color >= 0) {
2575 BUG_ON(work_color != work_next_color(cwq->work_color));
2576 cwq->work_color = work_color;
2579 spin_unlock_irq(&gcwq->lock);
2582 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_cwqs_to_flush))
2583 complete(&wq->first_flusher->done);
2589 * flush_workqueue - ensure that any scheduled work has run to completion.
2590 * @wq: workqueue to flush
2592 * Forces execution of the workqueue and blocks until its completion.
2593 * This is typically used in driver shutdown handlers.
2595 * We sleep until all works which were queued on entry have been handled,
2596 * but we are not livelocked by new incoming ones.
2598 void flush_workqueue(struct workqueue_struct *wq)
2600 struct wq_flusher this_flusher = {
2601 .list = LIST_HEAD_INIT(this_flusher.list),
2603 .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
2607 lock_map_acquire(&wq->lockdep_map);
2608 lock_map_release(&wq->lockdep_map);
2610 mutex_lock(&wq->flush_mutex);
2613 * Start-to-wait phase
2615 next_color = work_next_color(wq->work_color);
2617 if (next_color != wq->flush_color) {
2619 * Color space is not full. The current work_color
2620 * becomes our flush_color and work_color is advanced
2623 BUG_ON(!list_empty(&wq->flusher_overflow));
2624 this_flusher.flush_color = wq->work_color;
2625 wq->work_color = next_color;
2627 if (!wq->first_flusher) {
2628 /* no flush in progress, become the first flusher */
2629 BUG_ON(wq->flush_color != this_flusher.flush_color);
2631 wq->first_flusher = &this_flusher;
2633 if (!flush_workqueue_prep_cwqs(wq, wq->flush_color,
2635 /* nothing to flush, done */
2636 wq->flush_color = next_color;
2637 wq->first_flusher = NULL;
2642 BUG_ON(wq->flush_color == this_flusher.flush_color);
2643 list_add_tail(&this_flusher.list, &wq->flusher_queue);
2644 flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2648 * Oops, color space is full, wait on overflow queue.
2649 * The next flush completion will assign us
2650 * flush_color and transfer to flusher_queue.
2652 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2655 mutex_unlock(&wq->flush_mutex);
2657 wait_for_completion(&this_flusher.done);
2660 * Wake-up-and-cascade phase
2662 * First flushers are responsible for cascading flushes and
2663 * handling overflow. Non-first flushers can simply return.
2665 if (wq->first_flusher != &this_flusher)
2668 mutex_lock(&wq->flush_mutex);
2670 /* we might have raced, check again with mutex held */
2671 if (wq->first_flusher != &this_flusher)
2674 wq->first_flusher = NULL;
2676 BUG_ON(!list_empty(&this_flusher.list));
2677 BUG_ON(wq->flush_color != this_flusher.flush_color);
2680 struct wq_flusher *next, *tmp;
2682 /* complete all the flushers sharing the current flush color */
2683 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2684 if (next->flush_color != wq->flush_color)
2686 list_del_init(&next->list);
2687 complete(&next->done);
2690 BUG_ON(!list_empty(&wq->flusher_overflow) &&
2691 wq->flush_color != work_next_color(wq->work_color));
2693 /* this flush_color is finished, advance by one */
2694 wq->flush_color = work_next_color(wq->flush_color);
2696 /* one color has been freed, handle overflow queue */
2697 if (!list_empty(&wq->flusher_overflow)) {
2699 * Assign the same color to all overflowed
2700 * flushers, advance work_color and append to
2701 * flusher_queue. This is the start-to-wait
2702 * phase for these overflowed flushers.
2704 list_for_each_entry(tmp, &wq->flusher_overflow, list)
2705 tmp->flush_color = wq->work_color;
2707 wq->work_color = work_next_color(wq->work_color);
2709 list_splice_tail_init(&wq->flusher_overflow,
2710 &wq->flusher_queue);
2711 flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2714 if (list_empty(&wq->flusher_queue)) {
2715 BUG_ON(wq->flush_color != wq->work_color);
2720 * Need to flush more colors. Make the next flusher
2721 * the new first flusher and arm cwqs.
2723 BUG_ON(wq->flush_color == wq->work_color);
2724 BUG_ON(wq->flush_color != next->flush_color);
2726 list_del_init(&next->list);
2727 wq->first_flusher = next;
2729 if (flush_workqueue_prep_cwqs(wq, wq->flush_color, -1))
2733 * Meh... this color is already done, clear first
2734 * flusher and repeat cascading.
2736 wq->first_flusher = NULL;
2740 mutex_unlock(&wq->flush_mutex);
2742 EXPORT_SYMBOL_GPL(flush_workqueue);
2745 * drain_workqueue - drain a workqueue
2746 * @wq: workqueue to drain
2748 * Wait until the workqueue becomes empty. While draining is in progress,
2749 * only chain queueing is allowed. IOW, only currently pending or running
2750 * work items on @wq can queue further work items on it. @wq is flushed
2751 * repeatedly until it becomes empty. The number of flushing is detemined
2752 * by the depth of chaining and should be relatively short. Whine if it
2755 void drain_workqueue(struct workqueue_struct *wq)
2757 unsigned int flush_cnt = 0;
2761 * __queue_work() needs to test whether there are drainers, is much
2762 * hotter than drain_workqueue() and already looks at @wq->flags.
2763 * Use WQ_DRAINING so that queue doesn't have to check nr_drainers.
2765 spin_lock(&workqueue_lock);
2766 if (!wq->nr_drainers++)
2767 wq->flags |= WQ_DRAINING;
2768 spin_unlock(&workqueue_lock);
2770 flush_workqueue(wq);
2772 for_each_cwq_cpu(cpu, wq) {
2773 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2776 spin_lock_irq(&cwq->pool->gcwq->lock);
2777 drained = !cwq->nr_active && list_empty(&cwq->delayed_works);
2778 spin_unlock_irq(&cwq->pool->gcwq->lock);
2783 if (++flush_cnt == 10 ||
2784 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2785 pr_warn("workqueue %s: flush on destruction isn't complete after %u tries\n",
2786 wq->name, flush_cnt);
2790 spin_lock(&workqueue_lock);
2791 if (!--wq->nr_drainers)
2792 wq->flags &= ~WQ_DRAINING;
2793 spin_unlock(&workqueue_lock);
2795 EXPORT_SYMBOL_GPL(drain_workqueue);
2797 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2799 struct worker *worker = NULL;
2800 struct global_cwq *gcwq;
2801 struct cpu_workqueue_struct *cwq;
2804 gcwq = get_work_gcwq(work);
2808 spin_lock_irq(&gcwq->lock);
2809 if (!list_empty(&work->entry)) {
2811 * See the comment near try_to_grab_pending()->smp_rmb().
2812 * If it was re-queued to a different gcwq under us, we
2813 * are not going to wait.
2816 cwq = get_work_cwq(work);
2817 if (unlikely(!cwq || gcwq != cwq->pool->gcwq))
2820 worker = find_worker_executing_work(gcwq, work);
2823 cwq = worker->current_cwq;
2826 insert_wq_barrier(cwq, barr, work, worker);
2827 spin_unlock_irq(&gcwq->lock);
2830 * If @max_active is 1 or rescuer is in use, flushing another work
2831 * item on the same workqueue may lead to deadlock. Make sure the
2832 * flusher is not running on the same workqueue by verifying write
2835 if (cwq->wq->saved_max_active == 1 || cwq->wq->flags & WQ_RESCUER)
2836 lock_map_acquire(&cwq->wq->lockdep_map);
2838 lock_map_acquire_read(&cwq->wq->lockdep_map);
2839 lock_map_release(&cwq->wq->lockdep_map);
2843 spin_unlock_irq(&gcwq->lock);
2848 * flush_work - wait for a work to finish executing the last queueing instance
2849 * @work: the work to flush
2851 * Wait until @work has finished execution. @work is guaranteed to be idle
2852 * on return if it hasn't been requeued since flush started.
2855 * %true if flush_work() waited for the work to finish execution,
2856 * %false if it was already idle.
2858 bool flush_work(struct work_struct *work)
2860 struct wq_barrier barr;
2862 lock_map_acquire(&work->lockdep_map);
2863 lock_map_release(&work->lockdep_map);
2865 if (start_flush_work(work, &barr)) {
2866 wait_for_completion(&barr.done);
2867 destroy_work_on_stack(&barr.work);
2873 EXPORT_SYMBOL_GPL(flush_work);
2875 static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2877 unsigned long flags;
2881 ret = try_to_grab_pending(work, is_dwork, &flags);
2883 * If someone else is canceling, wait for the same event it
2884 * would be waiting for before retrying.
2886 if (unlikely(ret == -ENOENT))
2888 } while (unlikely(ret < 0));
2890 /* tell other tasks trying to grab @work to back off */
2891 mark_work_canceling(work);
2892 local_irq_restore(flags);
2895 clear_work_data(work);
2900 * cancel_work_sync - cancel a work and wait for it to finish
2901 * @work: the work to cancel
2903 * Cancel @work and wait for its execution to finish. This function
2904 * can be used even if the work re-queues itself or migrates to
2905 * another workqueue. On return from this function, @work is
2906 * guaranteed to be not pending or executing on any CPU.
2908 * cancel_work_sync(&delayed_work->work) must not be used for
2909 * delayed_work's. Use cancel_delayed_work_sync() instead.
2911 * The caller must ensure that the workqueue on which @work was last
2912 * queued can't be destroyed before this function returns.
2915 * %true if @work was pending, %false otherwise.
2917 bool cancel_work_sync(struct work_struct *work)
2919 return __cancel_work_timer(work, false);
2921 EXPORT_SYMBOL_GPL(cancel_work_sync);
2924 * flush_delayed_work - wait for a dwork to finish executing the last queueing
2925 * @dwork: the delayed work to flush
2927 * Delayed timer is cancelled and the pending work is queued for
2928 * immediate execution. Like flush_work(), this function only
2929 * considers the last queueing instance of @dwork.
2932 * %true if flush_work() waited for the work to finish execution,
2933 * %false if it was already idle.
2935 bool flush_delayed_work(struct delayed_work *dwork)
2937 local_irq_disable();
2938 if (del_timer_sync(&dwork->timer))
2939 __queue_work(dwork->cpu,
2940 get_work_cwq(&dwork->work)->wq, &dwork->work);
2942 return flush_work(&dwork->work);
2944 EXPORT_SYMBOL(flush_delayed_work);
2947 * cancel_delayed_work - cancel a delayed work
2948 * @dwork: delayed_work to cancel
2950 * Kill off a pending delayed_work. Returns %true if @dwork was pending
2951 * and canceled; %false if wasn't pending. Note that the work callback
2952 * function may still be running on return, unless it returns %true and the
2953 * work doesn't re-arm itself. Explicitly flush or use
2954 * cancel_delayed_work_sync() to wait on it.
2956 * This function is safe to call from any context including IRQ handler.
2958 bool cancel_delayed_work(struct delayed_work *dwork)
2960 unsigned long flags;
2964 ret = try_to_grab_pending(&dwork->work, true, &flags);
2965 } while (unlikely(ret == -EAGAIN));
2967 if (unlikely(ret < 0))
2970 set_work_cpu_and_clear_pending(&dwork->work, work_cpu(&dwork->work));
2971 local_irq_restore(flags);
2974 EXPORT_SYMBOL(cancel_delayed_work);
2977 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2978 * @dwork: the delayed work cancel
2980 * This is cancel_work_sync() for delayed works.
2983 * %true if @dwork was pending, %false otherwise.
2985 bool cancel_delayed_work_sync(struct delayed_work *dwork)
2987 return __cancel_work_timer(&dwork->work, true);
2989 EXPORT_SYMBOL(cancel_delayed_work_sync);
2992 * schedule_work_on - put work task on a specific cpu
2993 * @cpu: cpu to put the work task on
2994 * @work: job to be done
2996 * This puts a job on a specific cpu
2998 bool schedule_work_on(int cpu, struct work_struct *work)
3000 return queue_work_on(cpu, system_wq, work);
3002 EXPORT_SYMBOL(schedule_work_on);
3005 * schedule_work - put work task in global workqueue
3006 * @work: job to be done
3008 * Returns %false if @work was already on the kernel-global workqueue and
3011 * This puts a job in the kernel-global workqueue if it was not already
3012 * queued and leaves it in the same position on the kernel-global
3013 * workqueue otherwise.
3015 bool schedule_work(struct work_struct *work)
3017 return queue_work(system_wq, work);
3019 EXPORT_SYMBOL(schedule_work);
3022 * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
3024 * @dwork: job to be done
3025 * @delay: number of jiffies to wait
3027 * After waiting for a given time this puts a job in the kernel-global
3028 * workqueue on the specified CPU.
3030 bool schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
3031 unsigned long delay)
3033 return queue_delayed_work_on(cpu, system_wq, dwork, delay);
3035 EXPORT_SYMBOL(schedule_delayed_work_on);
3038 * schedule_delayed_work - put work task in global workqueue after delay
3039 * @dwork: job to be done
3040 * @delay: number of jiffies to wait or 0 for immediate execution
3042 * After waiting for a given time this puts a job in the kernel-global
3045 bool schedule_delayed_work(struct delayed_work *dwork, unsigned long delay)
3047 return queue_delayed_work(system_wq, dwork, delay);
3049 EXPORT_SYMBOL(schedule_delayed_work);
3052 * schedule_on_each_cpu - execute a function synchronously on each online CPU
3053 * @func: the function to call
3055 * schedule_on_each_cpu() executes @func on each online CPU using the
3056 * system workqueue and blocks until all CPUs have completed.
3057 * schedule_on_each_cpu() is very slow.
3060 * 0 on success, -errno on failure.
3062 int schedule_on_each_cpu(work_func_t func)
3065 struct work_struct __percpu *works;
3067 works = alloc_percpu(struct work_struct);
3073 for_each_online_cpu(cpu) {
3074 struct work_struct *work = per_cpu_ptr(works, cpu);
3076 INIT_WORK(work, func);
3077 schedule_work_on(cpu, work);
3080 for_each_online_cpu(cpu)
3081 flush_work(per_cpu_ptr(works, cpu));
3089 * flush_scheduled_work - ensure that any scheduled work has run to completion.
3091 * Forces execution of the kernel-global workqueue and blocks until its
3094 * Think twice before calling this function! It's very easy to get into
3095 * trouble if you don't take great care. Either of the following situations
3096 * will lead to deadlock:
3098 * One of the work items currently on the workqueue needs to acquire
3099 * a lock held by your code or its caller.
3101 * Your code is running in the context of a work routine.
3103 * They will be detected by lockdep when they occur, but the first might not
3104 * occur very often. It depends on what work items are on the workqueue and
3105 * what locks they need, which you have no control over.
3107 * In most situations flushing the entire workqueue is overkill; you merely
3108 * need to know that a particular work item isn't queued and isn't running.
3109 * In such cases you should use cancel_delayed_work_sync() or
3110 * cancel_work_sync() instead.
3112 void flush_scheduled_work(void)
3114 flush_workqueue(system_wq);
3116 EXPORT_SYMBOL(flush_scheduled_work);
3119 * execute_in_process_context - reliably execute the routine with user context
3120 * @fn: the function to execute
3121 * @ew: guaranteed storage for the execute work structure (must
3122 * be available when the work executes)
3124 * Executes the function immediately if process context is available,
3125 * otherwise schedules the function for delayed execution.
3127 * Returns: 0 - function was executed
3128 * 1 - function was scheduled for execution
3130 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
3132 if (!in_interrupt()) {
3137 INIT_WORK(&ew->work, fn);
3138 schedule_work(&ew->work);
3142 EXPORT_SYMBOL_GPL(execute_in_process_context);
3144 int keventd_up(void)
3146 return system_wq != NULL;
3149 static int alloc_cwqs(struct workqueue_struct *wq)
3152 * cwqs are forced aligned according to WORK_STRUCT_FLAG_BITS.
3153 * Make sure that the alignment isn't lower than that of
3154 * unsigned long long.
3156 const size_t size = sizeof(struct cpu_workqueue_struct);
3157 const size_t align = max_t(size_t, 1 << WORK_STRUCT_FLAG_BITS,
3158 __alignof__(unsigned long long));
3160 if (!(wq->flags & WQ_UNBOUND))
3161 wq->cpu_wq.pcpu = __alloc_percpu(size, align);
3166 * Allocate enough room to align cwq and put an extra
3167 * pointer at the end pointing back to the originally
3168 * allocated pointer which will be used for free.
3170 ptr = kzalloc(size + align + sizeof(void *), GFP_KERNEL);
3172 wq->cpu_wq.single = PTR_ALIGN(ptr, align);
3173 *(void **)(wq->cpu_wq.single + 1) = ptr;
3177 /* just in case, make sure it's actually aligned */
3178 BUG_ON(!IS_ALIGNED(wq->cpu_wq.v, align));
3179 return wq->cpu_wq.v ? 0 : -ENOMEM;
3182 static void free_cwqs(struct workqueue_struct *wq)
3184 if (!(wq->flags & WQ_UNBOUND))
3185 free_percpu(wq->cpu_wq.pcpu);
3186 else if (wq->cpu_wq.single) {
3187 /* the pointer to free is stored right after the cwq */
3188 kfree(*(void **)(wq->cpu_wq.single + 1));
3192 static int wq_clamp_max_active(int max_active, unsigned int flags,
3195 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3197 if (max_active < 1 || max_active > lim)
3198 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3199 max_active, name, 1, lim);
3201 return clamp_val(max_active, 1, lim);
3204 struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
3207 struct lock_class_key *key,
3208 const char *lock_name, ...)
3210 va_list args, args1;
3211 struct workqueue_struct *wq;
3215 /* determine namelen, allocate wq and format name */
3216 va_start(args, lock_name);
3217 va_copy(args1, args);
3218 namelen = vsnprintf(NULL, 0, fmt, args) + 1;
3220 wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
3224 vsnprintf(wq->name, namelen, fmt, args1);
3229 * Workqueues which may be used during memory reclaim should
3230 * have a rescuer to guarantee forward progress.
3232 if (flags & WQ_MEM_RECLAIM)
3233 flags |= WQ_RESCUER;
3235 max_active = max_active ?: WQ_DFL_ACTIVE;
3236 max_active = wq_clamp_max_active(max_active, flags, wq->name);
3240 wq->saved_max_active = max_active;
3241 mutex_init(&wq->flush_mutex);
3242 atomic_set(&wq->nr_cwqs_to_flush, 0);
3243 INIT_LIST_HEAD(&wq->flusher_queue);
3244 INIT_LIST_HEAD(&wq->flusher_overflow);
3246 lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3247 INIT_LIST_HEAD(&wq->list);
3249 if (alloc_cwqs(wq) < 0)
3252 for_each_cwq_cpu(cpu, wq) {
3253 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3254 struct global_cwq *gcwq = get_gcwq(cpu);
3255 int pool_idx = (bool)(flags & WQ_HIGHPRI);
3257 BUG_ON((unsigned long)cwq & WORK_STRUCT_FLAG_MASK);
3258 cwq->pool = &gcwq->pools[pool_idx];
3260 cwq->flush_color = -1;
3261 cwq->max_active = max_active;
3262 INIT_LIST_HEAD(&cwq->delayed_works);
3265 if (flags & WQ_RESCUER) {
3266 struct worker *rescuer;
3268 if (!alloc_mayday_mask(&wq->mayday_mask, GFP_KERNEL))
3271 wq->rescuer = rescuer = alloc_worker();
3275 rescuer->rescue_wq = wq;
3276 rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
3278 if (IS_ERR(rescuer->task))
3281 rescuer->task->flags |= PF_THREAD_BOUND;
3282 wake_up_process(rescuer->task);
3286 * workqueue_lock protects global freeze state and workqueues
3287 * list. Grab it, set max_active accordingly and add the new
3288 * workqueue to workqueues list.
3290 spin_lock(&workqueue_lock);
3292 if (workqueue_freezing && wq->flags & WQ_FREEZABLE)
3293 for_each_cwq_cpu(cpu, wq)
3294 get_cwq(cpu, wq)->max_active = 0;
3296 list_add(&wq->list, &workqueues);
3298 spin_unlock(&workqueue_lock);
3304 free_mayday_mask(wq->mayday_mask);
3310 EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
3313 * destroy_workqueue - safely terminate a workqueue
3314 * @wq: target workqueue
3316 * Safely destroy a workqueue. All work currently pending will be done first.
3318 void destroy_workqueue(struct workqueue_struct *wq)
3322 /* drain it before proceeding with destruction */
3323 drain_workqueue(wq);
3326 * wq list is used to freeze wq, remove from list after
3327 * flushing is complete in case freeze races us.
3329 spin_lock(&workqueue_lock);
3330 list_del(&wq->list);
3331 spin_unlock(&workqueue_lock);
3334 for_each_cwq_cpu(cpu, wq) {
3335 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3338 for (i = 0; i < WORK_NR_COLORS; i++)
3339 BUG_ON(cwq->nr_in_flight[i]);
3340 BUG_ON(cwq->nr_active);
3341 BUG_ON(!list_empty(&cwq->delayed_works));
3344 if (wq->flags & WQ_RESCUER) {
3345 kthread_stop(wq->rescuer->task);
3346 free_mayday_mask(wq->mayday_mask);
3353 EXPORT_SYMBOL_GPL(destroy_workqueue);
3356 * cwq_set_max_active - adjust max_active of a cwq
3357 * @cwq: target cpu_workqueue_struct
3358 * @max_active: new max_active value.
3360 * Set @cwq->max_active to @max_active and activate delayed works if
3364 * spin_lock_irq(gcwq->lock).
3366 static void cwq_set_max_active(struct cpu_workqueue_struct *cwq, int max_active)
3368 cwq->max_active = max_active;
3370 while (!list_empty(&cwq->delayed_works) &&
3371 cwq->nr_active < cwq->max_active)
3372 cwq_activate_first_delayed(cwq);
3376 * workqueue_set_max_active - adjust max_active of a workqueue
3377 * @wq: target workqueue
3378 * @max_active: new max_active value.
3380 * Set max_active of @wq to @max_active.
3383 * Don't call from IRQ context.
3385 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
3389 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
3391 spin_lock(&workqueue_lock);
3393 wq->saved_max_active = max_active;
3395 for_each_cwq_cpu(cpu, wq) {
3396 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3397 struct worker_pool *pool = cwq->pool;
3398 struct global_cwq *gcwq = pool->gcwq;
3400 spin_lock_irq(&gcwq->lock);
3402 if (!(wq->flags & WQ_FREEZABLE) ||
3403 !(pool->flags & POOL_FREEZING))
3404 cwq_set_max_active(cwq, max_active);
3406 spin_unlock_irq(&gcwq->lock);
3409 spin_unlock(&workqueue_lock);
3411 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
3414 * workqueue_congested - test whether a workqueue is congested
3415 * @cpu: CPU in question
3416 * @wq: target workqueue
3418 * Test whether @wq's cpu workqueue for @cpu is congested. There is
3419 * no synchronization around this function and the test result is
3420 * unreliable and only useful as advisory hints or for debugging.
3423 * %true if congested, %false otherwise.
3425 bool workqueue_congested(unsigned int cpu, struct workqueue_struct *wq)
3427 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3429 return !list_empty(&cwq->delayed_works);
3431 EXPORT_SYMBOL_GPL(workqueue_congested);
3434 * work_cpu - return the last known associated cpu for @work
3435 * @work: the work of interest
3438 * CPU number if @work was ever queued. WORK_CPU_NONE otherwise.
3440 static unsigned int work_cpu(struct work_struct *work)
3442 struct global_cwq *gcwq = get_work_gcwq(work);
3444 return gcwq ? gcwq->cpu : WORK_CPU_NONE;
3448 * work_busy - test whether a work is currently pending or running
3449 * @work: the work to be tested
3451 * Test whether @work is currently pending or running. There is no
3452 * synchronization around this function and the test result is
3453 * unreliable and only useful as advisory hints or for debugging.
3454 * Especially for reentrant wqs, the pending state might hide the
3458 * OR'd bitmask of WORK_BUSY_* bits.
3460 unsigned int work_busy(struct work_struct *work)
3462 struct global_cwq *gcwq = get_work_gcwq(work);
3463 unsigned long flags;
3464 unsigned int ret = 0;
3469 spin_lock_irqsave(&gcwq->lock, flags);
3471 if (work_pending(work))
3472 ret |= WORK_BUSY_PENDING;
3473 if (find_worker_executing_work(gcwq, work))
3474 ret |= WORK_BUSY_RUNNING;
3476 spin_unlock_irqrestore(&gcwq->lock, flags);
3480 EXPORT_SYMBOL_GPL(work_busy);
3485 * There are two challenges in supporting CPU hotplug. Firstly, there
3486 * are a lot of assumptions on strong associations among work, cwq and
3487 * gcwq which make migrating pending and scheduled works very
3488 * difficult to implement without impacting hot paths. Secondly,
3489 * gcwqs serve mix of short, long and very long running works making
3490 * blocked draining impractical.
3492 * This is solved by allowing the pools to be disassociated from the CPU
3493 * running as an unbound one and allowing it to be reattached later if the
3494 * cpu comes back online.
3497 /* claim manager positions of all pools */
3498 static void gcwq_claim_assoc_and_lock(struct global_cwq *gcwq)
3500 struct worker_pool *pool;
3502 for_each_worker_pool(pool, gcwq)
3503 mutex_lock_nested(&pool->assoc_mutex, pool - gcwq->pools);
3504 spin_lock_irq(&gcwq->lock);
3507 /* release manager positions */
3508 static void gcwq_release_assoc_and_unlock(struct global_cwq *gcwq)
3510 struct worker_pool *pool;
3512 spin_unlock_irq(&gcwq->lock);
3513 for_each_worker_pool(pool, gcwq)
3514 mutex_unlock(&pool->assoc_mutex);
3517 static void gcwq_unbind_fn(struct work_struct *work)
3519 struct global_cwq *gcwq = get_gcwq(smp_processor_id());
3520 struct worker_pool *pool;
3521 struct worker *worker;
3522 struct hlist_node *pos;
3525 BUG_ON(gcwq->cpu != smp_processor_id());
3527 gcwq_claim_assoc_and_lock(gcwq);
3530 * We've claimed all manager positions. Make all workers unbound
3531 * and set DISASSOCIATED. Before this, all workers except for the
3532 * ones which are still executing works from before the last CPU
3533 * down must be on the cpu. After this, they may become diasporas.
3535 for_each_worker_pool(pool, gcwq)
3536 list_for_each_entry(worker, &pool->idle_list, entry)
3537 worker->flags |= WORKER_UNBOUND;
3539 for_each_busy_worker(worker, i, pos, gcwq)
3540 worker->flags |= WORKER_UNBOUND;
3542 for_each_worker_pool(pool, gcwq)
3543 pool->flags |= POOL_DISASSOCIATED;
3545 gcwq_release_assoc_and_unlock(gcwq);
3548 * Call schedule() so that we cross rq->lock and thus can guarantee
3549 * sched callbacks see the %WORKER_UNBOUND flag. This is necessary
3550 * as scheduler callbacks may be invoked from other cpus.
3555 * Sched callbacks are disabled now. Zap nr_running. After this,
3556 * nr_running stays zero and need_more_worker() and keep_working()
3557 * are always true as long as the worklist is not empty. @gcwq now
3558 * behaves as unbound (in terms of concurrency management) gcwq
3559 * which is served by workers tied to the CPU.
3561 * On return from this function, the current worker would trigger
3562 * unbound chain execution of pending work items if other workers
3565 for_each_worker_pool(pool, gcwq)
3566 atomic_set(get_pool_nr_running(pool), 0);
3570 * Workqueues should be brought up before normal priority CPU notifiers.
3571 * This will be registered high priority CPU notifier.
3573 static int __cpuinit workqueue_cpu_up_callback(struct notifier_block *nfb,
3574 unsigned long action,
3577 unsigned int cpu = (unsigned long)hcpu;
3578 struct global_cwq *gcwq = get_gcwq(cpu);
3579 struct worker_pool *pool;
3581 switch (action & ~CPU_TASKS_FROZEN) {
3582 case CPU_UP_PREPARE:
3583 for_each_worker_pool(pool, gcwq) {
3584 struct worker *worker;
3586 if (pool->nr_workers)
3589 worker = create_worker(pool);
3593 spin_lock_irq(&gcwq->lock);
3594 start_worker(worker);
3595 spin_unlock_irq(&gcwq->lock);
3599 case CPU_DOWN_FAILED:
3601 gcwq_claim_assoc_and_lock(gcwq);
3602 for_each_worker_pool(pool, gcwq)
3603 pool->flags &= ~POOL_DISASSOCIATED;
3604 rebind_workers(gcwq);
3605 gcwq_release_assoc_and_unlock(gcwq);
3612 * Workqueues should be brought down after normal priority CPU notifiers.
3613 * This will be registered as low priority CPU notifier.
3615 static int __cpuinit workqueue_cpu_down_callback(struct notifier_block *nfb,
3616 unsigned long action,
3619 unsigned int cpu = (unsigned long)hcpu;
3620 struct work_struct unbind_work;
3622 switch (action & ~CPU_TASKS_FROZEN) {
3623 case CPU_DOWN_PREPARE:
3624 /* unbinding should happen on the local CPU */
3625 INIT_WORK_ONSTACK(&unbind_work, gcwq_unbind_fn);
3626 queue_work_on(cpu, system_highpri_wq, &unbind_work);
3627 flush_work(&unbind_work);
3635 struct work_for_cpu {
3636 struct work_struct work;
3642 static void work_for_cpu_fn(struct work_struct *work)
3644 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
3646 wfc->ret = wfc->fn(wfc->arg);
3650 * work_on_cpu - run a function in user context on a particular cpu
3651 * @cpu: the cpu to run on
3652 * @fn: the function to run
3653 * @arg: the function arg
3655 * This will return the value @fn returns.
3656 * It is up to the caller to ensure that the cpu doesn't go offline.
3657 * The caller must not hold any locks which would prevent @fn from completing.
3659 long work_on_cpu(unsigned int cpu, long (*fn)(void *), void *arg)
3661 struct work_for_cpu wfc = { .fn = fn, .arg = arg };
3663 INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
3664 schedule_work_on(cpu, &wfc.work);
3665 flush_work(&wfc.work);
3668 EXPORT_SYMBOL_GPL(work_on_cpu);
3669 #endif /* CONFIG_SMP */
3671 #ifdef CONFIG_FREEZER
3674 * freeze_workqueues_begin - begin freezing workqueues
3676 * Start freezing workqueues. After this function returns, all freezable
3677 * workqueues will queue new works to their frozen_works list instead of
3681 * Grabs and releases workqueue_lock and gcwq->lock's.
3683 void freeze_workqueues_begin(void)
3687 spin_lock(&workqueue_lock);
3689 BUG_ON(workqueue_freezing);
3690 workqueue_freezing = true;
3692 for_each_gcwq_cpu(cpu) {
3693 struct global_cwq *gcwq = get_gcwq(cpu);
3694 struct worker_pool *pool;
3695 struct workqueue_struct *wq;
3697 spin_lock_irq(&gcwq->lock);
3699 for_each_worker_pool(pool, gcwq) {
3700 WARN_ON_ONCE(pool->flags & POOL_FREEZING);
3701 pool->flags |= POOL_FREEZING;
3704 list_for_each_entry(wq, &workqueues, list) {
3705 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3707 if (cwq && wq->flags & WQ_FREEZABLE)
3708 cwq->max_active = 0;
3711 spin_unlock_irq(&gcwq->lock);
3714 spin_unlock(&workqueue_lock);
3718 * freeze_workqueues_busy - are freezable workqueues still busy?
3720 * Check whether freezing is complete. This function must be called
3721 * between freeze_workqueues_begin() and thaw_workqueues().
3724 * Grabs and releases workqueue_lock.
3727 * %true if some freezable workqueues are still busy. %false if freezing
3730 bool freeze_workqueues_busy(void)
3735 spin_lock(&workqueue_lock);
3737 BUG_ON(!workqueue_freezing);
3739 for_each_gcwq_cpu(cpu) {
3740 struct workqueue_struct *wq;
3742 * nr_active is monotonically decreasing. It's safe
3743 * to peek without lock.
3745 list_for_each_entry(wq, &workqueues, list) {
3746 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3748 if (!cwq || !(wq->flags & WQ_FREEZABLE))
3751 BUG_ON(cwq->nr_active < 0);
3752 if (cwq->nr_active) {
3759 spin_unlock(&workqueue_lock);
3764 * thaw_workqueues - thaw workqueues
3766 * Thaw workqueues. Normal queueing is restored and all collected
3767 * frozen works are transferred to their respective gcwq worklists.
3770 * Grabs and releases workqueue_lock and gcwq->lock's.
3772 void thaw_workqueues(void)
3776 spin_lock(&workqueue_lock);
3778 if (!workqueue_freezing)
3781 for_each_gcwq_cpu(cpu) {
3782 struct global_cwq *gcwq = get_gcwq(cpu);
3783 struct worker_pool *pool;
3784 struct workqueue_struct *wq;
3786 spin_lock_irq(&gcwq->lock);
3788 for_each_worker_pool(pool, gcwq) {
3789 WARN_ON_ONCE(!(pool->flags & POOL_FREEZING));
3790 pool->flags &= ~POOL_FREEZING;
3793 list_for_each_entry(wq, &workqueues, list) {
3794 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3796 if (!cwq || !(wq->flags & WQ_FREEZABLE))
3799 /* restore max_active and repopulate worklist */
3800 cwq_set_max_active(cwq, wq->saved_max_active);
3803 for_each_worker_pool(pool, gcwq)
3804 wake_up_worker(pool);
3806 spin_unlock_irq(&gcwq->lock);
3809 workqueue_freezing = false;
3811 spin_unlock(&workqueue_lock);
3813 #endif /* CONFIG_FREEZER */
3815 static int __init init_workqueues(void)
3819 /* make sure we have enough bits for OFFQ CPU number */
3820 BUILD_BUG_ON((1LU << (BITS_PER_LONG - WORK_OFFQ_CPU_SHIFT)) <
3823 cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
3824 hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
3826 /* initialize gcwqs */
3827 for_each_gcwq_cpu(cpu) {
3828 struct global_cwq *gcwq = get_gcwq(cpu);
3829 struct worker_pool *pool;
3831 spin_lock_init(&gcwq->lock);
3834 hash_init(gcwq->busy_hash);
3836 for_each_worker_pool(pool, gcwq) {
3838 pool->flags |= POOL_DISASSOCIATED;
3839 INIT_LIST_HEAD(&pool->worklist);
3840 INIT_LIST_HEAD(&pool->idle_list);
3842 init_timer_deferrable(&pool->idle_timer);
3843 pool->idle_timer.function = idle_worker_timeout;
3844 pool->idle_timer.data = (unsigned long)pool;
3846 setup_timer(&pool->mayday_timer, gcwq_mayday_timeout,
3847 (unsigned long)pool);
3849 mutex_init(&pool->assoc_mutex);
3850 ida_init(&pool->worker_ida);
3853 BUG_ON(worker_pool_assign_id(pool));
3857 /* create the initial worker */
3858 for_each_online_gcwq_cpu(cpu) {
3859 struct global_cwq *gcwq = get_gcwq(cpu);
3860 struct worker_pool *pool;
3862 for_each_worker_pool(pool, gcwq) {
3863 struct worker *worker;
3865 if (cpu != WORK_CPU_UNBOUND)
3866 pool->flags &= ~POOL_DISASSOCIATED;
3868 worker = create_worker(pool);
3870 spin_lock_irq(&gcwq->lock);
3871 start_worker(worker);
3872 spin_unlock_irq(&gcwq->lock);
3876 system_wq = alloc_workqueue("events", 0, 0);
3877 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
3878 system_long_wq = alloc_workqueue("events_long", 0, 0);
3879 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
3880 WQ_UNBOUND_MAX_ACTIVE);
3881 system_freezable_wq = alloc_workqueue("events_freezable",
3883 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
3884 !system_unbound_wq || !system_freezable_wq);
3887 early_initcall(init_workqueues);