2 * kernel/workqueue.c - generic async execution with shared worker pool
4 * Copyright (C) 2002 Ingo Molnar
6 * Derived from the taskqueue/keventd code by:
7 * David Woodhouse <dwmw2@infradead.org>
9 * Kai Petzke <wpp@marie.physik.tu-berlin.de>
10 * Theodore Ts'o <tytso@mit.edu>
12 * Made to use alloc_percpu by Christoph Lameter.
14 * Copyright (C) 2010 SUSE Linux Products GmbH
15 * Copyright (C) 2010 Tejun Heo <tj@kernel.org>
17 * This is the generic async execution mechanism. Work items as are
18 * executed in process context. The worker pool is shared and
19 * automatically managed. There is one worker pool for each CPU and
20 * one extra for works which are better served by workers which are
21 * not bound to any specific CPU.
23 * Please read Documentation/workqueue.txt for details.
26 #include <linux/export.h>
27 #include <linux/kernel.h>
28 #include <linux/sched.h>
29 #include <linux/init.h>
30 #include <linux/signal.h>
31 #include <linux/completion.h>
32 #include <linux/workqueue.h>
33 #include <linux/slab.h>
34 #include <linux/cpu.h>
35 #include <linux/notifier.h>
36 #include <linux/kthread.h>
37 #include <linux/hardirq.h>
38 #include <linux/mempolicy.h>
39 #include <linux/freezer.h>
40 #include <linux/kallsyms.h>
41 #include <linux/debug_locks.h>
42 #include <linux/lockdep.h>
43 #include <linux/idr.h>
45 #include "workqueue_sched.h"
51 * A bound gcwq is either associated or disassociated with its CPU.
52 * While associated (!DISASSOCIATED), all workers are bound to the
53 * CPU and none has %WORKER_UNBOUND set and concurrency management
56 * While DISASSOCIATED, the cpu may be offline and all workers have
57 * %WORKER_UNBOUND set and concurrency management disabled, and may
58 * be executing on any CPU. The gcwq behaves as an unbound one.
60 * Note that DISASSOCIATED can be flipped only while holding
61 * assoc_mutex of all pools on the gcwq to avoid changing binding
62 * state while create_worker() is in progress.
64 GCWQ_DISASSOCIATED = 1 << 0, /* cpu can't serve workers */
65 GCWQ_FREEZING = 1 << 1, /* freeze in progress */
68 POOL_MANAGE_WORKERS = 1 << 0, /* need to manage workers */
69 POOL_MANAGING_WORKERS = 1 << 1, /* managing workers */
72 WORKER_STARTED = 1 << 0, /* started */
73 WORKER_DIE = 1 << 1, /* die die die */
74 WORKER_IDLE = 1 << 2, /* is idle */
75 WORKER_PREP = 1 << 3, /* preparing to run works */
76 WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
77 WORKER_UNBOUND = 1 << 7, /* worker is unbound */
79 WORKER_NOT_RUNNING = WORKER_PREP | WORKER_UNBOUND |
82 NR_WORKER_POOLS = 2, /* # worker pools per gcwq */
84 BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
85 BUSY_WORKER_HASH_SIZE = 1 << BUSY_WORKER_HASH_ORDER,
86 BUSY_WORKER_HASH_MASK = BUSY_WORKER_HASH_SIZE - 1,
88 MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
89 IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
91 MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
92 /* call for help after 10ms
94 MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
95 CREATE_COOLDOWN = HZ, /* time to breath after fail */
98 * Rescue workers are used only on emergencies and shared by
101 RESCUER_NICE_LEVEL = -20,
102 HIGHPRI_NICE_LEVEL = -20,
106 * Structure fields follow one of the following exclusion rules.
108 * I: Modifiable by initialization/destruction paths and read-only for
111 * P: Preemption protected. Disabling preemption is enough and should
112 * only be modified and accessed from the local cpu.
114 * L: gcwq->lock protected. Access with gcwq->lock held.
116 * X: During normal operation, modification requires gcwq->lock and
117 * should be done only from local cpu. Either disabling preemption
118 * on local cpu or grabbing gcwq->lock is enough for read access.
119 * If GCWQ_DISASSOCIATED is set, it's identical to L.
121 * F: wq->flush_mutex protected.
123 * W: workqueue_lock protected.
130 * The poor guys doing the actual heavy lifting. All on-duty workers
131 * are either serving the manager role, on idle list or on busy hash.
134 /* on idle list while idle, on busy hash table while busy */
136 struct list_head entry; /* L: while idle */
137 struct hlist_node hentry; /* L: while busy */
140 struct work_struct *current_work; /* L: work being processed */
141 work_func_t current_func; /* L: current_work's fn */
142 struct cpu_workqueue_struct *current_cwq; /* L: current_work's cwq */
143 struct list_head scheduled; /* L: scheduled works */
144 struct task_struct *task; /* I: worker task */
145 struct worker_pool *pool; /* I: the associated pool */
146 /* 64 bytes boundary on 64bit, 32 on 32bit */
147 unsigned long last_active; /* L: last active timestamp */
148 unsigned int flags; /* X: flags */
149 int id; /* I: worker id */
151 /* for rebinding worker to CPU */
152 struct work_struct rebind_work; /* L: for busy worker */
156 struct global_cwq *gcwq; /* I: the owning gcwq */
157 unsigned int flags; /* X: flags */
159 struct list_head worklist; /* L: list of pending works */
160 int nr_workers; /* L: total number of workers */
162 /* nr_idle includes the ones off idle_list for rebinding */
163 int nr_idle; /* L: currently idle ones */
165 struct list_head idle_list; /* X: list of idle workers */
166 struct timer_list idle_timer; /* L: worker idle timeout */
167 struct timer_list mayday_timer; /* L: SOS timer for workers */
169 struct mutex assoc_mutex; /* protect GCWQ_DISASSOCIATED */
170 struct ida worker_ida; /* L: for worker IDs */
174 * Global per-cpu workqueue. There's one and only one for each cpu
175 * and all works are queued and processed here regardless of their
179 spinlock_t lock; /* the gcwq lock */
180 unsigned int cpu; /* I: the associated cpu */
181 unsigned int flags; /* L: GCWQ_* flags */
183 /* workers are chained either in busy_hash or pool idle_list */
184 struct hlist_head busy_hash[BUSY_WORKER_HASH_SIZE];
185 /* L: hash of busy workers */
187 struct worker_pool pools[NR_WORKER_POOLS];
188 /* normal and highpri pools */
189 } ____cacheline_aligned_in_smp;
192 * The per-CPU workqueue. The lower WORK_STRUCT_FLAG_BITS of
193 * work_struct->data are used for flags and thus cwqs need to be
194 * aligned at two's power of the number of flag bits.
196 struct cpu_workqueue_struct {
197 struct worker_pool *pool; /* I: the associated pool */
198 struct workqueue_struct *wq; /* I: the owning workqueue */
199 int work_color; /* L: current color */
200 int flush_color; /* L: flushing color */
201 int nr_in_flight[WORK_NR_COLORS];
202 /* L: nr of in_flight works */
203 int nr_active; /* L: nr of active works */
204 int max_active; /* L: max active works */
205 struct list_head delayed_works; /* L: delayed works */
209 * Structure used to wait for workqueue flush.
212 struct list_head list; /* F: list of flushers */
213 int flush_color; /* F: flush color waiting for */
214 struct completion done; /* flush completion */
218 * All cpumasks are assumed to be always set on UP and thus can't be
219 * used to determine whether there's something to be done.
222 typedef cpumask_var_t mayday_mask_t;
223 #define mayday_test_and_set_cpu(cpu, mask) \
224 cpumask_test_and_set_cpu((cpu), (mask))
225 #define mayday_clear_cpu(cpu, mask) cpumask_clear_cpu((cpu), (mask))
226 #define for_each_mayday_cpu(cpu, mask) for_each_cpu((cpu), (mask))
227 #define alloc_mayday_mask(maskp, gfp) zalloc_cpumask_var((maskp), (gfp))
228 #define free_mayday_mask(mask) free_cpumask_var((mask))
230 typedef unsigned long mayday_mask_t;
231 #define mayday_test_and_set_cpu(cpu, mask) test_and_set_bit(0, &(mask))
232 #define mayday_clear_cpu(cpu, mask) clear_bit(0, &(mask))
233 #define for_each_mayday_cpu(cpu, mask) if ((cpu) = 0, (mask))
234 #define alloc_mayday_mask(maskp, gfp) true
235 #define free_mayday_mask(mask) do { } while (0)
239 * The externally visible workqueue abstraction is an array of
240 * per-CPU workqueues:
242 struct workqueue_struct {
243 unsigned int flags; /* W: WQ_* flags */
245 struct cpu_workqueue_struct __percpu *pcpu;
246 struct cpu_workqueue_struct *single;
248 } cpu_wq; /* I: cwq's */
249 struct list_head list; /* W: list of all workqueues */
251 struct mutex flush_mutex; /* protects wq flushing */
252 int work_color; /* F: current work color */
253 int flush_color; /* F: current flush color */
254 atomic_t nr_cwqs_to_flush; /* flush in progress */
255 struct wq_flusher *first_flusher; /* F: first flusher */
256 struct list_head flusher_queue; /* F: flush waiters */
257 struct list_head flusher_overflow; /* F: flush overflow list */
259 mayday_mask_t mayday_mask; /* cpus requesting rescue */
260 struct worker *rescuer; /* I: rescue worker */
262 int nr_drainers; /* W: drain in progress */
263 int saved_max_active; /* W: saved cwq max_active */
264 #ifdef CONFIG_LOCKDEP
265 struct lockdep_map lockdep_map;
267 char name[]; /* I: workqueue name */
270 struct workqueue_struct *system_wq __read_mostly;
271 EXPORT_SYMBOL_GPL(system_wq);
272 struct workqueue_struct *system_highpri_wq __read_mostly;
273 EXPORT_SYMBOL_GPL(system_highpri_wq);
274 struct workqueue_struct *system_long_wq __read_mostly;
275 EXPORT_SYMBOL_GPL(system_long_wq);
276 struct workqueue_struct *system_unbound_wq __read_mostly;
277 EXPORT_SYMBOL_GPL(system_unbound_wq);
278 struct workqueue_struct *system_freezable_wq __read_mostly;
279 EXPORT_SYMBOL_GPL(system_freezable_wq);
281 #define CREATE_TRACE_POINTS
282 #include <trace/events/workqueue.h>
284 #define for_each_worker_pool(pool, gcwq) \
285 for ((pool) = &(gcwq)->pools[0]; \
286 (pool) < &(gcwq)->pools[NR_WORKER_POOLS]; (pool)++)
288 #define for_each_busy_worker(worker, i, pos, gcwq) \
289 for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++) \
290 hlist_for_each_entry(worker, pos, &gcwq->busy_hash[i], hentry)
292 static inline int __next_gcwq_cpu(int cpu, const struct cpumask *mask,
295 if (cpu < nr_cpu_ids) {
297 cpu = cpumask_next(cpu, mask);
298 if (cpu < nr_cpu_ids)
302 return WORK_CPU_UNBOUND;
304 return WORK_CPU_NONE;
307 static inline int __next_wq_cpu(int cpu, const struct cpumask *mask,
308 struct workqueue_struct *wq)
310 return __next_gcwq_cpu(cpu, mask, !(wq->flags & WQ_UNBOUND) ? 1 : 2);
316 * An extra gcwq is defined for an invalid cpu number
317 * (WORK_CPU_UNBOUND) to host workqueues which are not bound to any
318 * specific CPU. The following iterators are similar to
319 * for_each_*_cpu() iterators but also considers the unbound gcwq.
321 * for_each_gcwq_cpu() : possible CPUs + WORK_CPU_UNBOUND
322 * for_each_online_gcwq_cpu() : online CPUs + WORK_CPU_UNBOUND
323 * for_each_cwq_cpu() : possible CPUs for bound workqueues,
324 * WORK_CPU_UNBOUND for unbound workqueues
326 #define for_each_gcwq_cpu(cpu) \
327 for ((cpu) = __next_gcwq_cpu(-1, cpu_possible_mask, 3); \
328 (cpu) < WORK_CPU_NONE; \
329 (cpu) = __next_gcwq_cpu((cpu), cpu_possible_mask, 3))
331 #define for_each_online_gcwq_cpu(cpu) \
332 for ((cpu) = __next_gcwq_cpu(-1, cpu_online_mask, 3); \
333 (cpu) < WORK_CPU_NONE; \
334 (cpu) = __next_gcwq_cpu((cpu), cpu_online_mask, 3))
336 #define for_each_cwq_cpu(cpu, wq) \
337 for ((cpu) = __next_wq_cpu(-1, cpu_possible_mask, (wq)); \
338 (cpu) < WORK_CPU_NONE; \
339 (cpu) = __next_wq_cpu((cpu), cpu_possible_mask, (wq)))
341 #ifdef CONFIG_DEBUG_OBJECTS_WORK
343 static struct debug_obj_descr work_debug_descr;
345 static void *work_debug_hint(void *addr)
347 return ((struct work_struct *) addr)->func;
351 * fixup_init is called when:
352 * - an active object is initialized
354 static int work_fixup_init(void *addr, enum debug_obj_state state)
356 struct work_struct *work = addr;
359 case ODEBUG_STATE_ACTIVE:
360 cancel_work_sync(work);
361 debug_object_init(work, &work_debug_descr);
369 * fixup_activate is called when:
370 * - an active object is activated
371 * - an unknown object is activated (might be a statically initialized object)
373 static int work_fixup_activate(void *addr, enum debug_obj_state state)
375 struct work_struct *work = addr;
379 case ODEBUG_STATE_NOTAVAILABLE:
381 * This is not really a fixup. The work struct was
382 * statically initialized. We just make sure that it
383 * is tracked in the object tracker.
385 if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
386 debug_object_init(work, &work_debug_descr);
387 debug_object_activate(work, &work_debug_descr);
393 case ODEBUG_STATE_ACTIVE:
402 * fixup_free is called when:
403 * - an active object is freed
405 static int work_fixup_free(void *addr, enum debug_obj_state state)
407 struct work_struct *work = addr;
410 case ODEBUG_STATE_ACTIVE:
411 cancel_work_sync(work);
412 debug_object_free(work, &work_debug_descr);
419 static struct debug_obj_descr work_debug_descr = {
420 .name = "work_struct",
421 .debug_hint = work_debug_hint,
422 .fixup_init = work_fixup_init,
423 .fixup_activate = work_fixup_activate,
424 .fixup_free = work_fixup_free,
427 static inline void debug_work_activate(struct work_struct *work)
429 debug_object_activate(work, &work_debug_descr);
432 static inline void debug_work_deactivate(struct work_struct *work)
434 debug_object_deactivate(work, &work_debug_descr);
437 void __init_work(struct work_struct *work, int onstack)
440 debug_object_init_on_stack(work, &work_debug_descr);
442 debug_object_init(work, &work_debug_descr);
444 EXPORT_SYMBOL_GPL(__init_work);
446 void destroy_work_on_stack(struct work_struct *work)
448 debug_object_free(work, &work_debug_descr);
450 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
453 static inline void debug_work_activate(struct work_struct *work) { }
454 static inline void debug_work_deactivate(struct work_struct *work) { }
457 /* Serializes the accesses to the list of workqueues. */
458 static DEFINE_SPINLOCK(workqueue_lock);
459 static LIST_HEAD(workqueues);
460 static bool workqueue_freezing; /* W: have wqs started freezing? */
463 * The almighty global cpu workqueues. nr_running is the only field
464 * which is expected to be used frequently by other cpus via
465 * try_to_wake_up(). Put it in a separate cacheline.
467 static DEFINE_PER_CPU(struct global_cwq, global_cwq);
468 static DEFINE_PER_CPU_SHARED_ALIGNED(atomic_t, pool_nr_running[NR_WORKER_POOLS]);
471 * Global cpu workqueue and nr_running counter for unbound gcwq. The
472 * gcwq is always online, has GCWQ_DISASSOCIATED set, and all its
473 * workers have WORKER_UNBOUND set.
475 static struct global_cwq unbound_global_cwq;
476 static atomic_t unbound_pool_nr_running[NR_WORKER_POOLS] = {
477 [0 ... NR_WORKER_POOLS - 1] = ATOMIC_INIT(0), /* always 0 */
480 static int worker_thread(void *__worker);
482 static int worker_pool_pri(struct worker_pool *pool)
484 return pool - pool->gcwq->pools;
487 static struct global_cwq *get_gcwq(unsigned int cpu)
489 if (cpu != WORK_CPU_UNBOUND)
490 return &per_cpu(global_cwq, cpu);
492 return &unbound_global_cwq;
495 static atomic_t *get_pool_nr_running(struct worker_pool *pool)
497 int cpu = pool->gcwq->cpu;
498 int idx = worker_pool_pri(pool);
500 if (cpu != WORK_CPU_UNBOUND)
501 return &per_cpu(pool_nr_running, cpu)[idx];
503 return &unbound_pool_nr_running[idx];
506 static struct cpu_workqueue_struct *get_cwq(unsigned int cpu,
507 struct workqueue_struct *wq)
509 if (!(wq->flags & WQ_UNBOUND)) {
510 if (likely(cpu < nr_cpu_ids))
511 return per_cpu_ptr(wq->cpu_wq.pcpu, cpu);
512 } else if (likely(cpu == WORK_CPU_UNBOUND))
513 return wq->cpu_wq.single;
517 static unsigned int work_color_to_flags(int color)
519 return color << WORK_STRUCT_COLOR_SHIFT;
522 static int get_work_color(struct work_struct *work)
524 return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
525 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
528 static int work_next_color(int color)
530 return (color + 1) % WORK_NR_COLORS;
534 * While queued, %WORK_STRUCT_CWQ is set and non flag bits of a work's data
535 * contain the pointer to the queued cwq. Once execution starts, the flag
536 * is cleared and the high bits contain OFFQ flags and CPU number.
538 * set_work_cwq(), set_work_cpu_and_clear_pending(), mark_work_canceling()
539 * and clear_work_data() can be used to set the cwq, cpu or clear
540 * work->data. These functions should only be called while the work is
541 * owned - ie. while the PENDING bit is set.
543 * get_work_[g]cwq() can be used to obtain the gcwq or cwq corresponding to
544 * a work. gcwq is available once the work has been queued anywhere after
545 * initialization until it is sync canceled. cwq is available only while
546 * the work item is queued.
548 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
549 * canceled. While being canceled, a work item may have its PENDING set
550 * but stay off timer and worklist for arbitrarily long and nobody should
551 * try to steal the PENDING bit.
553 static inline void set_work_data(struct work_struct *work, unsigned long data,
556 BUG_ON(!work_pending(work));
557 atomic_long_set(&work->data, data | flags | work_static(work));
560 static void set_work_cwq(struct work_struct *work,
561 struct cpu_workqueue_struct *cwq,
562 unsigned long extra_flags)
564 set_work_data(work, (unsigned long)cwq,
565 WORK_STRUCT_PENDING | WORK_STRUCT_CWQ | extra_flags);
568 static void set_work_cpu_and_clear_pending(struct work_struct *work,
572 * The following wmb is paired with the implied mb in
573 * test_and_set_bit(PENDING) and ensures all updates to @work made
574 * here are visible to and precede any updates by the next PENDING
578 set_work_data(work, (unsigned long)cpu << WORK_OFFQ_CPU_SHIFT, 0);
581 static void clear_work_data(struct work_struct *work)
583 smp_wmb(); /* see set_work_cpu_and_clear_pending() */
584 set_work_data(work, WORK_STRUCT_NO_CPU, 0);
587 static struct cpu_workqueue_struct *get_work_cwq(struct work_struct *work)
589 unsigned long data = atomic_long_read(&work->data);
591 if (data & WORK_STRUCT_CWQ)
592 return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
597 static struct global_cwq *get_work_gcwq(struct work_struct *work)
599 unsigned long data = atomic_long_read(&work->data);
602 if (data & WORK_STRUCT_CWQ)
603 return ((struct cpu_workqueue_struct *)
604 (data & WORK_STRUCT_WQ_DATA_MASK))->pool->gcwq;
606 cpu = data >> WORK_OFFQ_CPU_SHIFT;
607 if (cpu == WORK_CPU_NONE)
610 BUG_ON(cpu >= nr_cpu_ids && cpu != WORK_CPU_UNBOUND);
611 return get_gcwq(cpu);
614 static void mark_work_canceling(struct work_struct *work)
616 struct global_cwq *gcwq = get_work_gcwq(work);
617 unsigned long cpu = gcwq ? gcwq->cpu : WORK_CPU_NONE;
619 set_work_data(work, (cpu << WORK_OFFQ_CPU_SHIFT) | WORK_OFFQ_CANCELING,
620 WORK_STRUCT_PENDING);
623 static bool work_is_canceling(struct work_struct *work)
625 unsigned long data = atomic_long_read(&work->data);
627 return !(data & WORK_STRUCT_CWQ) && (data & WORK_OFFQ_CANCELING);
631 * Policy functions. These define the policies on how the global worker
632 * pools are managed. Unless noted otherwise, these functions assume that
633 * they're being called with gcwq->lock held.
636 static bool __need_more_worker(struct worker_pool *pool)
638 return !atomic_read(get_pool_nr_running(pool));
642 * Need to wake up a worker? Called from anything but currently
645 * Note that, because unbound workers never contribute to nr_running, this
646 * function will always return %true for unbound gcwq as long as the
647 * worklist isn't empty.
649 static bool need_more_worker(struct worker_pool *pool)
651 return !list_empty(&pool->worklist) && __need_more_worker(pool);
654 /* Can I start working? Called from busy but !running workers. */
655 static bool may_start_working(struct worker_pool *pool)
657 return pool->nr_idle;
660 /* Do I need to keep working? Called from currently running workers. */
661 static bool keep_working(struct worker_pool *pool)
663 atomic_t *nr_running = get_pool_nr_running(pool);
665 return !list_empty(&pool->worklist) && atomic_read(nr_running) <= 1;
668 /* Do we need a new worker? Called from manager. */
669 static bool need_to_create_worker(struct worker_pool *pool)
671 return need_more_worker(pool) && !may_start_working(pool);
674 /* Do I need to be the manager? */
675 static bool need_to_manage_workers(struct worker_pool *pool)
677 return need_to_create_worker(pool) ||
678 (pool->flags & POOL_MANAGE_WORKERS);
681 /* Do we have too many workers and should some go away? */
682 static bool too_many_workers(struct worker_pool *pool)
684 bool managing = pool->flags & POOL_MANAGING_WORKERS;
685 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
686 int nr_busy = pool->nr_workers - nr_idle;
689 * nr_idle and idle_list may disagree if idle rebinding is in
690 * progress. Never return %true if idle_list is empty.
692 if (list_empty(&pool->idle_list))
695 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
702 /* Return the first worker. Safe with preemption disabled */
703 static struct worker *first_worker(struct worker_pool *pool)
705 if (unlikely(list_empty(&pool->idle_list)))
708 return list_first_entry(&pool->idle_list, struct worker, entry);
712 * wake_up_worker - wake up an idle worker
713 * @pool: worker pool to wake worker from
715 * Wake up the first idle worker of @pool.
718 * spin_lock_irq(gcwq->lock).
720 static void wake_up_worker(struct worker_pool *pool)
722 struct worker *worker = first_worker(pool);
725 wake_up_process(worker->task);
729 * wq_worker_waking_up - a worker is waking up
730 * @task: task waking up
731 * @cpu: CPU @task is waking up to
733 * This function is called during try_to_wake_up() when a worker is
737 * spin_lock_irq(rq->lock)
739 void wq_worker_waking_up(struct task_struct *task, unsigned int cpu)
741 struct worker *worker = kthread_data(task);
743 if (!(worker->flags & WORKER_NOT_RUNNING)) {
744 WARN_ON_ONCE(worker->pool->gcwq->cpu != cpu);
745 atomic_inc(get_pool_nr_running(worker->pool));
750 * wq_worker_sleeping - a worker is going to sleep
751 * @task: task going to sleep
752 * @cpu: CPU in question, must be the current CPU number
754 * This function is called during schedule() when a busy worker is
755 * going to sleep. Worker on the same cpu can be woken up by
756 * returning pointer to its task.
759 * spin_lock_irq(rq->lock)
762 * Worker task on @cpu to wake up, %NULL if none.
764 struct task_struct *wq_worker_sleeping(struct task_struct *task,
767 struct worker *worker = kthread_data(task), *to_wakeup = NULL;
768 struct worker_pool *pool = worker->pool;
769 atomic_t *nr_running = get_pool_nr_running(pool);
771 if (worker->flags & WORKER_NOT_RUNNING)
774 /* this can only happen on the local cpu */
775 BUG_ON(cpu != raw_smp_processor_id());
778 * The counterpart of the following dec_and_test, implied mb,
779 * worklist not empty test sequence is in insert_work().
780 * Please read comment there.
782 * NOT_RUNNING is clear. This means that we're bound to and
783 * running on the local cpu w/ rq lock held and preemption
784 * disabled, which in turn means that none else could be
785 * manipulating idle_list, so dereferencing idle_list without gcwq
788 if (atomic_dec_and_test(nr_running) && !list_empty(&pool->worklist))
789 to_wakeup = first_worker(pool);
790 return to_wakeup ? to_wakeup->task : NULL;
794 * worker_set_flags - set worker flags and adjust nr_running accordingly
796 * @flags: flags to set
797 * @wakeup: wakeup an idle worker if necessary
799 * Set @flags in @worker->flags and adjust nr_running accordingly. If
800 * nr_running becomes zero and @wakeup is %true, an idle worker is
804 * spin_lock_irq(gcwq->lock)
806 static inline void worker_set_flags(struct worker *worker, unsigned int flags,
809 struct worker_pool *pool = worker->pool;
811 WARN_ON_ONCE(worker->task != current);
814 * If transitioning into NOT_RUNNING, adjust nr_running and
815 * wake up an idle worker as necessary if requested by
818 if ((flags & WORKER_NOT_RUNNING) &&
819 !(worker->flags & WORKER_NOT_RUNNING)) {
820 atomic_t *nr_running = get_pool_nr_running(pool);
823 if (atomic_dec_and_test(nr_running) &&
824 !list_empty(&pool->worklist))
825 wake_up_worker(pool);
827 atomic_dec(nr_running);
830 worker->flags |= flags;
834 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
836 * @flags: flags to clear
838 * Clear @flags in @worker->flags and adjust nr_running accordingly.
841 * spin_lock_irq(gcwq->lock)
843 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
845 struct worker_pool *pool = worker->pool;
846 unsigned int oflags = worker->flags;
848 WARN_ON_ONCE(worker->task != current);
850 worker->flags &= ~flags;
853 * If transitioning out of NOT_RUNNING, increment nr_running. Note
854 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
855 * of multiple flags, not a single flag.
857 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
858 if (!(worker->flags & WORKER_NOT_RUNNING))
859 atomic_inc(get_pool_nr_running(pool));
863 * busy_worker_head - return the busy hash head for a work
864 * @gcwq: gcwq of interest
865 * @work: work to be hashed
867 * Return hash head of @gcwq for @work.
870 * spin_lock_irq(gcwq->lock).
873 * Pointer to the hash head.
875 static struct hlist_head *busy_worker_head(struct global_cwq *gcwq,
876 struct work_struct *work)
878 const int base_shift = ilog2(sizeof(struct work_struct));
879 unsigned long v = (unsigned long)work;
881 /* simple shift and fold hash, do we need something better? */
883 v += v >> BUSY_WORKER_HASH_ORDER;
884 v &= BUSY_WORKER_HASH_MASK;
886 return &gcwq->busy_hash[v];
890 * __find_worker_executing_work - find worker which is executing a work
891 * @gcwq: gcwq of interest
892 * @bwh: hash head as returned by busy_worker_head()
893 * @work: work to find worker for
895 * Find a worker which is executing @work on @gcwq. @bwh should be
896 * the hash head obtained by calling busy_worker_head() with the same
900 * spin_lock_irq(gcwq->lock).
903 * Pointer to worker which is executing @work if found, NULL
906 static struct worker *__find_worker_executing_work(struct global_cwq *gcwq,
907 struct hlist_head *bwh,
908 struct work_struct *work)
910 struct worker *worker;
911 struct hlist_node *tmp;
913 hlist_for_each_entry(worker, tmp, bwh, hentry)
914 if (worker->current_work == work &&
915 worker->current_func == work->func)
921 * find_worker_executing_work - find worker which is executing a work
922 * @gcwq: gcwq of interest
923 * @work: work to find worker for
925 * Find a worker which is executing @work on @gcwq by searching
926 * @gcwq->busy_hash which is keyed by the address of @work. For a worker
927 * to match, its current execution should match the address of @work and
928 * its work function. This is to avoid unwanted dependency between
929 * unrelated work executions through a work item being recycled while still
932 * This is a bit tricky. A work item may be freed once its execution
933 * starts and nothing prevents the freed area from being recycled for
934 * another work item. If the same work item address ends up being reused
935 * before the original execution finishes, workqueue will identify the
936 * recycled work item as currently executing and make it wait until the
937 * current execution finishes, introducing an unwanted dependency.
939 * This function checks the work item address, work function and workqueue
940 * to avoid false positives. Note that this isn't complete as one may
941 * construct a work function which can introduce dependency onto itself
942 * through a recycled work item. Well, if somebody wants to shoot oneself
943 * in the foot that badly, there's only so much we can do, and if such
944 * deadlock actually occurs, it should be easy to locate the culprit work
948 * spin_lock_irq(gcwq->lock).
951 * Pointer to worker which is executing @work if found, NULL
954 static struct worker *find_worker_executing_work(struct global_cwq *gcwq,
955 struct work_struct *work)
957 return __find_worker_executing_work(gcwq, busy_worker_head(gcwq, work),
962 * move_linked_works - move linked works to a list
963 * @work: start of series of works to be scheduled
964 * @head: target list to append @work to
965 * @nextp: out paramter for nested worklist walking
967 * Schedule linked works starting from @work to @head. Work series to
968 * be scheduled starts at @work and includes any consecutive work with
969 * WORK_STRUCT_LINKED set in its predecessor.
971 * If @nextp is not NULL, it's updated to point to the next work of
972 * the last scheduled work. This allows move_linked_works() to be
973 * nested inside outer list_for_each_entry_safe().
976 * spin_lock_irq(gcwq->lock).
978 static void move_linked_works(struct work_struct *work, struct list_head *head,
979 struct work_struct **nextp)
981 struct work_struct *n;
984 * Linked worklist will always end before the end of the list,
985 * use NULL for list head.
987 list_for_each_entry_safe_from(work, n, NULL, entry) {
988 list_move_tail(&work->entry, head);
989 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
994 * If we're already inside safe list traversal and have moved
995 * multiple works to the scheduled queue, the next position
996 * needs to be updated.
1002 static void cwq_activate_delayed_work(struct work_struct *work)
1004 struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1006 trace_workqueue_activate_work(work);
1007 move_linked_works(work, &cwq->pool->worklist, NULL);
1008 __clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
1012 static void cwq_activate_first_delayed(struct cpu_workqueue_struct *cwq)
1014 struct work_struct *work = list_first_entry(&cwq->delayed_works,
1015 struct work_struct, entry);
1017 cwq_activate_delayed_work(work);
1021 * cwq_dec_nr_in_flight - decrement cwq's nr_in_flight
1022 * @cwq: cwq of interest
1023 * @color: color of work which left the queue
1025 * A work either has completed or is removed from pending queue,
1026 * decrement nr_in_flight of its cwq and handle workqueue flushing.
1029 * spin_lock_irq(gcwq->lock).
1031 static void cwq_dec_nr_in_flight(struct cpu_workqueue_struct *cwq, int color)
1033 /* ignore uncolored works */
1034 if (color == WORK_NO_COLOR)
1037 cwq->nr_in_flight[color]--;
1040 if (!list_empty(&cwq->delayed_works)) {
1041 /* one down, submit a delayed one */
1042 if (cwq->nr_active < cwq->max_active)
1043 cwq_activate_first_delayed(cwq);
1046 /* is flush in progress and are we at the flushing tip? */
1047 if (likely(cwq->flush_color != color))
1050 /* are there still in-flight works? */
1051 if (cwq->nr_in_flight[color])
1054 /* this cwq is done, clear flush_color */
1055 cwq->flush_color = -1;
1058 * If this was the last cwq, wake up the first flusher. It
1059 * will handle the rest.
1061 if (atomic_dec_and_test(&cwq->wq->nr_cwqs_to_flush))
1062 complete(&cwq->wq->first_flusher->done);
1066 * try_to_grab_pending - steal work item from worklist and disable irq
1067 * @work: work item to steal
1068 * @is_dwork: @work is a delayed_work
1069 * @flags: place to store irq state
1071 * Try to grab PENDING bit of @work. This function can handle @work in any
1072 * stable state - idle, on timer or on worklist. Return values are
1074 * 1 if @work was pending and we successfully stole PENDING
1075 * 0 if @work was idle and we claimed PENDING
1076 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1077 * -ENOENT if someone else is canceling @work, this state may persist
1078 * for arbitrarily long
1080 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1081 * interrupted while holding PENDING and @work off queue, irq must be
1082 * disabled on entry. This, combined with delayed_work->timer being
1083 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1085 * On successful return, >= 0, irq is disabled and the caller is
1086 * responsible for releasing it using local_irq_restore(*@flags).
1088 * This function is safe to call from any context including IRQ handler.
1090 static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1091 unsigned long *flags)
1093 struct global_cwq *gcwq;
1095 local_irq_save(*flags);
1097 /* try to steal the timer if it exists */
1099 struct delayed_work *dwork = to_delayed_work(work);
1102 * dwork->timer is irqsafe. If del_timer() fails, it's
1103 * guaranteed that the timer is not queued anywhere and not
1104 * running on the local CPU.
1106 if (likely(del_timer(&dwork->timer)))
1110 /* try to claim PENDING the normal way */
1111 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1115 * The queueing is in progress, or it is already queued. Try to
1116 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1118 gcwq = get_work_gcwq(work);
1122 spin_lock(&gcwq->lock);
1123 if (!list_empty(&work->entry)) {
1125 * This work is queued, but perhaps we locked the wrong gcwq.
1126 * In that case we must see the new value after rmb(), see
1127 * insert_work()->wmb().
1130 if (gcwq == get_work_gcwq(work)) {
1131 debug_work_deactivate(work);
1134 * A delayed work item cannot be grabbed directly
1135 * because it might have linked NO_COLOR work items
1136 * which, if left on the delayed_list, will confuse
1137 * cwq->nr_active management later on and cause
1138 * stall. Make sure the work item is activated
1141 if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1142 cwq_activate_delayed_work(work);
1144 list_del_init(&work->entry);
1145 cwq_dec_nr_in_flight(get_work_cwq(work),
1146 get_work_color(work));
1148 spin_unlock(&gcwq->lock);
1152 spin_unlock(&gcwq->lock);
1154 local_irq_restore(*flags);
1155 if (work_is_canceling(work))
1162 * insert_work - insert a work into gcwq
1163 * @cwq: cwq @work belongs to
1164 * @work: work to insert
1165 * @head: insertion point
1166 * @extra_flags: extra WORK_STRUCT_* flags to set
1168 * Insert @work which belongs to @cwq into @gcwq after @head.
1169 * @extra_flags is or'd to work_struct flags.
1172 * spin_lock_irq(gcwq->lock).
1174 static void insert_work(struct cpu_workqueue_struct *cwq,
1175 struct work_struct *work, struct list_head *head,
1176 unsigned int extra_flags)
1178 struct worker_pool *pool = cwq->pool;
1180 /* we own @work, set data and link */
1181 set_work_cwq(work, cwq, extra_flags);
1184 * Ensure that we get the right work->data if we see the
1185 * result of list_add() below, see try_to_grab_pending().
1189 list_add_tail(&work->entry, head);
1192 * Ensure either worker_sched_deactivated() sees the above
1193 * list_add_tail() or we see zero nr_running to avoid workers
1194 * lying around lazily while there are works to be processed.
1198 if (__need_more_worker(pool))
1199 wake_up_worker(pool);
1203 * Test whether @work is being queued from another work executing on the
1204 * same workqueue. This is rather expensive and should only be used from
1207 static bool is_chained_work(struct workqueue_struct *wq)
1209 unsigned long flags;
1212 for_each_gcwq_cpu(cpu) {
1213 struct global_cwq *gcwq = get_gcwq(cpu);
1214 struct worker *worker;
1215 struct hlist_node *pos;
1218 spin_lock_irqsave(&gcwq->lock, flags);
1219 for_each_busy_worker(worker, i, pos, gcwq) {
1220 if (worker->task != current)
1222 spin_unlock_irqrestore(&gcwq->lock, flags);
1224 * I'm @worker, no locking necessary. See if @work
1225 * is headed to the same workqueue.
1227 return worker->current_cwq->wq == wq;
1229 spin_unlock_irqrestore(&gcwq->lock, flags);
1234 static void __queue_work(unsigned int cpu, struct workqueue_struct *wq,
1235 struct work_struct *work)
1237 struct global_cwq *gcwq;
1238 struct cpu_workqueue_struct *cwq;
1239 struct list_head *worklist;
1240 unsigned int work_flags;
1241 unsigned int req_cpu = cpu;
1244 * While a work item is PENDING && off queue, a task trying to
1245 * steal the PENDING will busy-loop waiting for it to either get
1246 * queued or lose PENDING. Grabbing PENDING and queueing should
1247 * happen with IRQ disabled.
1249 WARN_ON_ONCE(!irqs_disabled());
1251 debug_work_activate(work);
1253 /* if dying, only works from the same workqueue are allowed */
1254 if (unlikely(wq->flags & WQ_DRAINING) &&
1255 WARN_ON_ONCE(!is_chained_work(wq)))
1258 /* determine gcwq to use */
1259 if (!(wq->flags & WQ_UNBOUND)) {
1260 struct global_cwq *last_gcwq;
1262 if (cpu == WORK_CPU_UNBOUND)
1263 cpu = raw_smp_processor_id();
1266 * It's multi cpu. If @work was previously on a different
1267 * cpu, it might still be running there, in which case the
1268 * work needs to be queued on that cpu to guarantee
1271 gcwq = get_gcwq(cpu);
1272 last_gcwq = get_work_gcwq(work);
1274 if (last_gcwq && last_gcwq != gcwq) {
1275 struct worker *worker;
1277 spin_lock(&last_gcwq->lock);
1279 worker = find_worker_executing_work(last_gcwq, work);
1281 if (worker && worker->current_cwq->wq == wq)
1284 /* meh... not running there, queue here */
1285 spin_unlock(&last_gcwq->lock);
1286 spin_lock(&gcwq->lock);
1289 spin_lock(&gcwq->lock);
1292 gcwq = get_gcwq(WORK_CPU_UNBOUND);
1293 spin_lock(&gcwq->lock);
1296 /* gcwq determined, get cwq and queue */
1297 cwq = get_cwq(gcwq->cpu, wq);
1298 trace_workqueue_queue_work(req_cpu, cwq, work);
1300 if (WARN_ON(!list_empty(&work->entry))) {
1301 spin_unlock(&gcwq->lock);
1305 cwq->nr_in_flight[cwq->work_color]++;
1306 work_flags = work_color_to_flags(cwq->work_color);
1308 if (likely(cwq->nr_active < cwq->max_active)) {
1309 trace_workqueue_activate_work(work);
1311 worklist = &cwq->pool->worklist;
1313 work_flags |= WORK_STRUCT_DELAYED;
1314 worklist = &cwq->delayed_works;
1317 insert_work(cwq, work, worklist, work_flags);
1319 spin_unlock(&gcwq->lock);
1323 * queue_work_on - queue work on specific cpu
1324 * @cpu: CPU number to execute work on
1325 * @wq: workqueue to use
1326 * @work: work to queue
1328 * Returns %false if @work was already on a queue, %true otherwise.
1330 * We queue the work to a specific CPU, the caller must ensure it
1333 bool queue_work_on(int cpu, struct workqueue_struct *wq,
1334 struct work_struct *work)
1337 unsigned long flags;
1339 local_irq_save(flags);
1341 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1342 __queue_work(cpu, wq, work);
1346 local_irq_restore(flags);
1349 EXPORT_SYMBOL_GPL(queue_work_on);
1352 * queue_work - queue work on a workqueue
1353 * @wq: workqueue to use
1354 * @work: work to queue
1356 * Returns %false if @work was already on a queue, %true otherwise.
1358 * We queue the work to the CPU on which it was submitted, but if the CPU dies
1359 * it can be processed by another CPU.
1361 bool queue_work(struct workqueue_struct *wq, struct work_struct *work)
1363 return queue_work_on(WORK_CPU_UNBOUND, wq, work);
1365 EXPORT_SYMBOL_GPL(queue_work);
1367 void delayed_work_timer_fn(unsigned long __data)
1369 struct delayed_work *dwork = (struct delayed_work *)__data;
1370 struct cpu_workqueue_struct *cwq = get_work_cwq(&dwork->work);
1372 /* should have been called from irqsafe timer with irq already off */
1373 __queue_work(dwork->cpu, cwq->wq, &dwork->work);
1375 EXPORT_SYMBOL(delayed_work_timer_fn);
1377 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
1378 struct delayed_work *dwork, unsigned long delay)
1380 struct timer_list *timer = &dwork->timer;
1381 struct work_struct *work = &dwork->work;
1384 WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
1385 timer->data != (unsigned long)dwork);
1386 WARN_ON_ONCE(timer_pending(timer));
1387 WARN_ON_ONCE(!list_empty(&work->entry));
1390 * If @delay is 0, queue @dwork->work immediately. This is for
1391 * both optimization and correctness. The earliest @timer can
1392 * expire is on the closest next tick and delayed_work users depend
1393 * on that there's no such delay when @delay is 0.
1396 __queue_work(cpu, wq, &dwork->work);
1400 timer_stats_timer_set_start_info(&dwork->timer);
1403 * This stores cwq for the moment, for the timer_fn. Note that the
1404 * work's gcwq is preserved to allow reentrance detection for
1407 if (!(wq->flags & WQ_UNBOUND)) {
1408 struct global_cwq *gcwq = get_work_gcwq(work);
1411 * If we cannot get the last gcwq from @work directly,
1412 * select the last CPU such that it avoids unnecessarily
1413 * triggering non-reentrancy check in __queue_work().
1418 if (lcpu == WORK_CPU_UNBOUND)
1419 lcpu = raw_smp_processor_id();
1421 lcpu = WORK_CPU_UNBOUND;
1424 set_work_cwq(work, get_cwq(lcpu, wq), 0);
1427 timer->expires = jiffies + delay;
1429 if (unlikely(cpu != WORK_CPU_UNBOUND))
1430 add_timer_on(timer, cpu);
1436 * queue_delayed_work_on - queue work on specific CPU after delay
1437 * @cpu: CPU number to execute work on
1438 * @wq: workqueue to use
1439 * @dwork: work to queue
1440 * @delay: number of jiffies to wait before queueing
1442 * Returns %false if @work was already on a queue, %true otherwise. If
1443 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1446 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1447 struct delayed_work *dwork, unsigned long delay)
1449 struct work_struct *work = &dwork->work;
1451 unsigned long flags;
1453 /* read the comment in __queue_work() */
1454 local_irq_save(flags);
1456 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1457 __queue_delayed_work(cpu, wq, dwork, delay);
1461 local_irq_restore(flags);
1464 EXPORT_SYMBOL_GPL(queue_delayed_work_on);
1467 * queue_delayed_work - queue work on a workqueue after delay
1468 * @wq: workqueue to use
1469 * @dwork: delayable work to queue
1470 * @delay: number of jiffies to wait before queueing
1472 * Equivalent to queue_delayed_work_on() but tries to use the local CPU.
1474 bool queue_delayed_work(struct workqueue_struct *wq,
1475 struct delayed_work *dwork, unsigned long delay)
1477 return queue_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
1479 EXPORT_SYMBOL_GPL(queue_delayed_work);
1482 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1483 * @cpu: CPU number to execute work on
1484 * @wq: workqueue to use
1485 * @dwork: work to queue
1486 * @delay: number of jiffies to wait before queueing
1488 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1489 * modify @dwork's timer so that it expires after @delay. If @delay is
1490 * zero, @work is guaranteed to be scheduled immediately regardless of its
1493 * Returns %false if @dwork was idle and queued, %true if @dwork was
1494 * pending and its timer was modified.
1496 * This function is safe to call from any context including IRQ handler.
1497 * See try_to_grab_pending() for details.
1499 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
1500 struct delayed_work *dwork, unsigned long delay)
1502 unsigned long flags;
1506 ret = try_to_grab_pending(&dwork->work, true, &flags);
1507 } while (unlikely(ret == -EAGAIN));
1509 if (likely(ret >= 0)) {
1510 __queue_delayed_work(cpu, wq, dwork, delay);
1511 local_irq_restore(flags);
1514 /* -ENOENT from try_to_grab_pending() becomes %true */
1517 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
1520 * mod_delayed_work - modify delay of or queue a delayed work
1521 * @wq: workqueue to use
1522 * @dwork: work to queue
1523 * @delay: number of jiffies to wait before queueing
1525 * mod_delayed_work_on() on local CPU.
1527 bool mod_delayed_work(struct workqueue_struct *wq, struct delayed_work *dwork,
1528 unsigned long delay)
1530 return mod_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
1532 EXPORT_SYMBOL_GPL(mod_delayed_work);
1535 * worker_enter_idle - enter idle state
1536 * @worker: worker which is entering idle state
1538 * @worker is entering idle state. Update stats and idle timer if
1542 * spin_lock_irq(gcwq->lock).
1544 static void worker_enter_idle(struct worker *worker)
1546 struct worker_pool *pool = worker->pool;
1547 struct global_cwq *gcwq = pool->gcwq;
1549 BUG_ON(worker->flags & WORKER_IDLE);
1550 BUG_ON(!list_empty(&worker->entry) &&
1551 (worker->hentry.next || worker->hentry.pprev));
1553 /* can't use worker_set_flags(), also called from start_worker() */
1554 worker->flags |= WORKER_IDLE;
1556 worker->last_active = jiffies;
1558 /* idle_list is LIFO */
1559 list_add(&worker->entry, &pool->idle_list);
1561 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1562 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1565 * Sanity check nr_running. Because gcwq_unbind_fn() releases
1566 * gcwq->lock between setting %WORKER_UNBOUND and zapping
1567 * nr_running, the warning may trigger spuriously. Check iff
1568 * unbind is not in progress.
1570 WARN_ON_ONCE(!(gcwq->flags & GCWQ_DISASSOCIATED) &&
1571 pool->nr_workers == pool->nr_idle &&
1572 atomic_read(get_pool_nr_running(pool)));
1576 * worker_leave_idle - leave idle state
1577 * @worker: worker which is leaving idle state
1579 * @worker is leaving idle state. Update stats.
1582 * spin_lock_irq(gcwq->lock).
1584 static void worker_leave_idle(struct worker *worker)
1586 struct worker_pool *pool = worker->pool;
1588 BUG_ON(!(worker->flags & WORKER_IDLE));
1589 worker_clr_flags(worker, WORKER_IDLE);
1591 list_del_init(&worker->entry);
1595 * worker_maybe_bind_and_lock - bind worker to its cpu if possible and lock gcwq
1598 * Works which are scheduled while the cpu is online must at least be
1599 * scheduled to a worker which is bound to the cpu so that if they are
1600 * flushed from cpu callbacks while cpu is going down, they are
1601 * guaranteed to execute on the cpu.
1603 * This function is to be used by rogue workers and rescuers to bind
1604 * themselves to the target cpu and may race with cpu going down or
1605 * coming online. kthread_bind() can't be used because it may put the
1606 * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1607 * verbatim as it's best effort and blocking and gcwq may be
1608 * [dis]associated in the meantime.
1610 * This function tries set_cpus_allowed() and locks gcwq and verifies the
1611 * binding against %GCWQ_DISASSOCIATED which is set during
1612 * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
1613 * enters idle state or fetches works without dropping lock, it can
1614 * guarantee the scheduling requirement described in the first paragraph.
1617 * Might sleep. Called without any lock but returns with gcwq->lock
1621 * %true if the associated gcwq is online (@worker is successfully
1622 * bound), %false if offline.
1624 static bool worker_maybe_bind_and_lock(struct worker *worker)
1625 __acquires(&gcwq->lock)
1627 struct global_cwq *gcwq = worker->pool->gcwq;
1628 struct task_struct *task = worker->task;
1632 * The following call may fail, succeed or succeed
1633 * without actually migrating the task to the cpu if
1634 * it races with cpu hotunplug operation. Verify
1635 * against GCWQ_DISASSOCIATED.
1637 if (!(gcwq->flags & GCWQ_DISASSOCIATED))
1638 set_cpus_allowed_ptr(task, get_cpu_mask(gcwq->cpu));
1640 spin_lock_irq(&gcwq->lock);
1641 if (gcwq->flags & GCWQ_DISASSOCIATED)
1643 if (task_cpu(task) == gcwq->cpu &&
1644 cpumask_equal(¤t->cpus_allowed,
1645 get_cpu_mask(gcwq->cpu)))
1647 spin_unlock_irq(&gcwq->lock);
1650 * We've raced with CPU hot[un]plug. Give it a breather
1651 * and retry migration. cond_resched() is required here;
1652 * otherwise, we might deadlock against cpu_stop trying to
1653 * bring down the CPU on non-preemptive kernel.
1661 * Rebind an idle @worker to its CPU. worker_thread() will test
1662 * list_empty(@worker->entry) before leaving idle and call this function.
1664 static void idle_worker_rebind(struct worker *worker)
1666 struct global_cwq *gcwq = worker->pool->gcwq;
1668 /* CPU may go down again inbetween, clear UNBOUND only on success */
1669 if (worker_maybe_bind_and_lock(worker))
1670 worker_clr_flags(worker, WORKER_UNBOUND);
1672 /* rebind complete, become available again */
1673 list_add(&worker->entry, &worker->pool->idle_list);
1674 spin_unlock_irq(&gcwq->lock);
1678 * Function for @worker->rebind.work used to rebind unbound busy workers to
1679 * the associated cpu which is coming back online. This is scheduled by
1680 * cpu up but can race with other cpu hotplug operations and may be
1681 * executed twice without intervening cpu down.
1683 static void busy_worker_rebind_fn(struct work_struct *work)
1685 struct worker *worker = container_of(work, struct worker, rebind_work);
1686 struct global_cwq *gcwq = worker->pool->gcwq;
1688 if (worker_maybe_bind_and_lock(worker))
1689 worker_clr_flags(worker, WORKER_UNBOUND);
1691 spin_unlock_irq(&gcwq->lock);
1695 * rebind_workers - rebind all workers of a gcwq to the associated CPU
1696 * @gcwq: gcwq of interest
1698 * @gcwq->cpu is coming online. Rebind all workers to the CPU. Rebinding
1699 * is different for idle and busy ones.
1701 * Idle ones will be removed from the idle_list and woken up. They will
1702 * add themselves back after completing rebind. This ensures that the
1703 * idle_list doesn't contain any unbound workers when re-bound busy workers
1704 * try to perform local wake-ups for concurrency management.
1706 * Busy workers can rebind after they finish their current work items.
1707 * Queueing the rebind work item at the head of the scheduled list is
1708 * enough. Note that nr_running will be properly bumped as busy workers
1711 * On return, all non-manager workers are scheduled for rebind - see
1712 * manage_workers() for the manager special case. Any idle worker
1713 * including the manager will not appear on @idle_list until rebind is
1714 * complete, making local wake-ups safe.
1716 static void rebind_workers(struct global_cwq *gcwq)
1718 struct worker_pool *pool;
1719 struct worker *worker, *n;
1720 struct hlist_node *pos;
1723 lockdep_assert_held(&gcwq->lock);
1725 for_each_worker_pool(pool, gcwq)
1726 lockdep_assert_held(&pool->assoc_mutex);
1728 /* dequeue and kick idle ones */
1729 for_each_worker_pool(pool, gcwq) {
1730 list_for_each_entry_safe(worker, n, &pool->idle_list, entry) {
1732 * idle workers should be off @pool->idle_list
1733 * until rebind is complete to avoid receiving
1734 * premature local wake-ups.
1736 list_del_init(&worker->entry);
1739 * worker_thread() will see the above dequeuing
1740 * and call idle_worker_rebind().
1742 wake_up_process(worker->task);
1746 /* rebind busy workers */
1747 for_each_busy_worker(worker, i, pos, gcwq) {
1748 struct work_struct *rebind_work = &worker->rebind_work;
1749 struct workqueue_struct *wq;
1751 if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
1752 work_data_bits(rebind_work)))
1755 debug_work_activate(rebind_work);
1758 * wq doesn't really matter but let's keep @worker->pool
1759 * and @cwq->pool consistent for sanity.
1761 if (worker_pool_pri(worker->pool))
1762 wq = system_highpri_wq;
1766 insert_work(get_cwq(gcwq->cpu, wq), rebind_work,
1767 worker->scheduled.next,
1768 work_color_to_flags(WORK_NO_COLOR));
1772 static struct worker *alloc_worker(void)
1774 struct worker *worker;
1776 worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1778 INIT_LIST_HEAD(&worker->entry);
1779 INIT_LIST_HEAD(&worker->scheduled);
1780 INIT_WORK(&worker->rebind_work, busy_worker_rebind_fn);
1781 /* on creation a worker is in !idle && prep state */
1782 worker->flags = WORKER_PREP;
1788 * create_worker - create a new workqueue worker
1789 * @pool: pool the new worker will belong to
1791 * Create a new worker which is bound to @pool. The returned worker
1792 * can be started by calling start_worker() or destroyed using
1796 * Might sleep. Does GFP_KERNEL allocations.
1799 * Pointer to the newly created worker.
1801 static struct worker *create_worker(struct worker_pool *pool)
1803 struct global_cwq *gcwq = pool->gcwq;
1804 const char *pri = worker_pool_pri(pool) ? "H" : "";
1805 struct worker *worker = NULL;
1808 spin_lock_irq(&gcwq->lock);
1809 while (ida_get_new(&pool->worker_ida, &id)) {
1810 spin_unlock_irq(&gcwq->lock);
1811 if (!ida_pre_get(&pool->worker_ida, GFP_KERNEL))
1813 spin_lock_irq(&gcwq->lock);
1815 spin_unlock_irq(&gcwq->lock);
1817 worker = alloc_worker();
1821 worker->pool = pool;
1824 if (gcwq->cpu != WORK_CPU_UNBOUND)
1825 worker->task = kthread_create_on_node(worker_thread,
1826 worker, cpu_to_node(gcwq->cpu),
1827 "kworker/%u:%d%s", gcwq->cpu, id, pri);
1829 worker->task = kthread_create(worker_thread, worker,
1830 "kworker/u:%d%s", id, pri);
1831 if (IS_ERR(worker->task))
1834 if (worker_pool_pri(pool))
1835 set_user_nice(worker->task, HIGHPRI_NICE_LEVEL);
1838 * Determine CPU binding of the new worker depending on
1839 * %GCWQ_DISASSOCIATED. The caller is responsible for ensuring the
1840 * flag remains stable across this function. See the comments
1841 * above the flag definition for details.
1843 * As an unbound worker may later become a regular one if CPU comes
1844 * online, make sure every worker has %PF_THREAD_BOUND set.
1846 if (!(gcwq->flags & GCWQ_DISASSOCIATED)) {
1847 kthread_bind(worker->task, gcwq->cpu);
1849 worker->task->flags |= PF_THREAD_BOUND;
1850 worker->flags |= WORKER_UNBOUND;
1856 spin_lock_irq(&gcwq->lock);
1857 ida_remove(&pool->worker_ida, id);
1858 spin_unlock_irq(&gcwq->lock);
1865 * start_worker - start a newly created worker
1866 * @worker: worker to start
1868 * Make the gcwq aware of @worker and start it.
1871 * spin_lock_irq(gcwq->lock).
1873 static void start_worker(struct worker *worker)
1875 worker->flags |= WORKER_STARTED;
1876 worker->pool->nr_workers++;
1877 worker_enter_idle(worker);
1878 wake_up_process(worker->task);
1882 * destroy_worker - destroy a workqueue worker
1883 * @worker: worker to be destroyed
1885 * Destroy @worker and adjust @gcwq stats accordingly.
1888 * spin_lock_irq(gcwq->lock) which is released and regrabbed.
1890 static void destroy_worker(struct worker *worker)
1892 struct worker_pool *pool = worker->pool;
1893 struct global_cwq *gcwq = pool->gcwq;
1894 int id = worker->id;
1896 /* sanity check frenzy */
1897 BUG_ON(worker->current_work);
1898 BUG_ON(!list_empty(&worker->scheduled));
1900 if (worker->flags & WORKER_STARTED)
1902 if (worker->flags & WORKER_IDLE)
1905 list_del_init(&worker->entry);
1906 worker->flags |= WORKER_DIE;
1908 spin_unlock_irq(&gcwq->lock);
1910 kthread_stop(worker->task);
1913 spin_lock_irq(&gcwq->lock);
1914 ida_remove(&pool->worker_ida, id);
1917 static void idle_worker_timeout(unsigned long __pool)
1919 struct worker_pool *pool = (void *)__pool;
1920 struct global_cwq *gcwq = pool->gcwq;
1922 spin_lock_irq(&gcwq->lock);
1924 if (too_many_workers(pool)) {
1925 struct worker *worker;
1926 unsigned long expires;
1928 /* idle_list is kept in LIFO order, check the last one */
1929 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1930 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1932 if (time_before(jiffies, expires))
1933 mod_timer(&pool->idle_timer, expires);
1935 /* it's been idle for too long, wake up manager */
1936 pool->flags |= POOL_MANAGE_WORKERS;
1937 wake_up_worker(pool);
1941 spin_unlock_irq(&gcwq->lock);
1944 static bool send_mayday(struct work_struct *work)
1946 struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1947 struct workqueue_struct *wq = cwq->wq;
1950 if (!(wq->flags & WQ_RESCUER))
1953 /* mayday mayday mayday */
1954 cpu = cwq->pool->gcwq->cpu;
1955 /* WORK_CPU_UNBOUND can't be set in cpumask, use cpu 0 instead */
1956 if (cpu == WORK_CPU_UNBOUND)
1958 if (!mayday_test_and_set_cpu(cpu, wq->mayday_mask))
1959 wake_up_process(wq->rescuer->task);
1963 static void gcwq_mayday_timeout(unsigned long __pool)
1965 struct worker_pool *pool = (void *)__pool;
1966 struct global_cwq *gcwq = pool->gcwq;
1967 struct work_struct *work;
1969 spin_lock_irq(&gcwq->lock);
1971 if (need_to_create_worker(pool)) {
1973 * We've been trying to create a new worker but
1974 * haven't been successful. We might be hitting an
1975 * allocation deadlock. Send distress signals to
1978 list_for_each_entry(work, &pool->worklist, entry)
1982 spin_unlock_irq(&gcwq->lock);
1984 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1988 * maybe_create_worker - create a new worker if necessary
1989 * @pool: pool to create a new worker for
1991 * Create a new worker for @pool if necessary. @pool is guaranteed to
1992 * have at least one idle worker on return from this function. If
1993 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1994 * sent to all rescuers with works scheduled on @pool to resolve
1995 * possible allocation deadlock.
1997 * On return, need_to_create_worker() is guaranteed to be false and
1998 * may_start_working() true.
2001 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2002 * multiple times. Does GFP_KERNEL allocations. Called only from
2006 * false if no action was taken and gcwq->lock stayed locked, true
2009 static bool maybe_create_worker(struct worker_pool *pool)
2010 __releases(&gcwq->lock)
2011 __acquires(&gcwq->lock)
2013 struct global_cwq *gcwq = pool->gcwq;
2015 if (!need_to_create_worker(pool))
2018 spin_unlock_irq(&gcwq->lock);
2020 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
2021 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
2024 struct worker *worker;
2026 worker = create_worker(pool);
2028 del_timer_sync(&pool->mayday_timer);
2029 spin_lock_irq(&gcwq->lock);
2030 start_worker(worker);
2031 BUG_ON(need_to_create_worker(pool));
2035 if (!need_to_create_worker(pool))
2038 __set_current_state(TASK_INTERRUPTIBLE);
2039 schedule_timeout(CREATE_COOLDOWN);
2041 if (!need_to_create_worker(pool))
2045 del_timer_sync(&pool->mayday_timer);
2046 spin_lock_irq(&gcwq->lock);
2047 if (need_to_create_worker(pool))
2053 * maybe_destroy_worker - destroy workers which have been idle for a while
2054 * @pool: pool to destroy workers for
2056 * Destroy @pool workers which have been idle for longer than
2057 * IDLE_WORKER_TIMEOUT.
2060 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2061 * multiple times. Called only from manager.
2064 * false if no action was taken and gcwq->lock stayed locked, true
2067 static bool maybe_destroy_workers(struct worker_pool *pool)
2071 while (too_many_workers(pool)) {
2072 struct worker *worker;
2073 unsigned long expires;
2075 worker = list_entry(pool->idle_list.prev, struct worker, entry);
2076 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2078 if (time_before(jiffies, expires)) {
2079 mod_timer(&pool->idle_timer, expires);
2083 destroy_worker(worker);
2091 * manage_workers - manage worker pool
2094 * Assume the manager role and manage gcwq worker pool @worker belongs
2095 * to. At any given time, there can be only zero or one manager per
2096 * gcwq. The exclusion is handled automatically by this function.
2098 * The caller can safely start processing works on false return. On
2099 * true return, it's guaranteed that need_to_create_worker() is false
2100 * and may_start_working() is true.
2103 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2104 * multiple times. Does GFP_KERNEL allocations.
2107 * false if no action was taken and gcwq->lock stayed locked, true if
2108 * some action was taken.
2110 static bool manage_workers(struct worker *worker)
2112 struct worker_pool *pool = worker->pool;
2115 if (pool->flags & POOL_MANAGING_WORKERS)
2118 pool->flags |= POOL_MANAGING_WORKERS;
2121 * To simplify both worker management and CPU hotplug, hold off
2122 * management while hotplug is in progress. CPU hotplug path can't
2123 * grab %POOL_MANAGING_WORKERS to achieve this because that can
2124 * lead to idle worker depletion (all become busy thinking someone
2125 * else is managing) which in turn can result in deadlock under
2126 * extreme circumstances. Use @pool->assoc_mutex to synchronize
2127 * manager against CPU hotplug.
2129 * assoc_mutex would always be free unless CPU hotplug is in
2130 * progress. trylock first without dropping @gcwq->lock.
2132 if (unlikely(!mutex_trylock(&pool->assoc_mutex))) {
2133 spin_unlock_irq(&pool->gcwq->lock);
2134 mutex_lock(&pool->assoc_mutex);
2136 * CPU hotplug could have happened while we were waiting
2137 * for assoc_mutex. Hotplug itself can't handle us
2138 * because manager isn't either on idle or busy list, and
2139 * @gcwq's state and ours could have deviated.
2141 * As hotplug is now excluded via assoc_mutex, we can
2142 * simply try to bind. It will succeed or fail depending
2143 * on @gcwq's current state. Try it and adjust
2144 * %WORKER_UNBOUND accordingly.
2146 if (worker_maybe_bind_and_lock(worker))
2147 worker->flags &= ~WORKER_UNBOUND;
2149 worker->flags |= WORKER_UNBOUND;
2154 pool->flags &= ~POOL_MANAGE_WORKERS;
2157 * Destroy and then create so that may_start_working() is true
2160 ret |= maybe_destroy_workers(pool);
2161 ret |= maybe_create_worker(pool);
2163 pool->flags &= ~POOL_MANAGING_WORKERS;
2164 mutex_unlock(&pool->assoc_mutex);
2169 * process_one_work - process single work
2171 * @work: work to process
2173 * Process @work. This function contains all the logics necessary to
2174 * process a single work including synchronization against and
2175 * interaction with other workers on the same cpu, queueing and
2176 * flushing. As long as context requirement is met, any worker can
2177 * call this function to process a work.
2180 * spin_lock_irq(gcwq->lock) which is released and regrabbed.
2182 static void process_one_work(struct worker *worker, struct work_struct *work)
2183 __releases(&gcwq->lock)
2184 __acquires(&gcwq->lock)
2186 struct cpu_workqueue_struct *cwq = get_work_cwq(work);
2187 struct worker_pool *pool = worker->pool;
2188 struct global_cwq *gcwq = pool->gcwq;
2189 struct hlist_head *bwh = busy_worker_head(gcwq, work);
2190 bool cpu_intensive = cwq->wq->flags & WQ_CPU_INTENSIVE;
2192 struct worker *collision;
2193 #ifdef CONFIG_LOCKDEP
2195 * It is permissible to free the struct work_struct from
2196 * inside the function that is called from it, this we need to
2197 * take into account for lockdep too. To avoid bogus "held
2198 * lock freed" warnings as well as problems when looking into
2199 * work->lockdep_map, make a copy and use that here.
2201 struct lockdep_map lockdep_map;
2203 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
2206 * Ensure we're on the correct CPU. DISASSOCIATED test is
2207 * necessary to avoid spurious warnings from rescuers servicing the
2208 * unbound or a disassociated gcwq.
2210 WARN_ON_ONCE(!(worker->flags & WORKER_UNBOUND) &&
2211 !(gcwq->flags & GCWQ_DISASSOCIATED) &&
2212 raw_smp_processor_id() != gcwq->cpu);
2215 * A single work shouldn't be executed concurrently by
2216 * multiple workers on a single cpu. Check whether anyone is
2217 * already processing the work. If so, defer the work to the
2218 * currently executing one.
2220 collision = __find_worker_executing_work(gcwq, bwh, work);
2221 if (unlikely(collision)) {
2222 move_linked_works(work, &collision->scheduled, NULL);
2226 /* claim and dequeue */
2227 debug_work_deactivate(work);
2228 hlist_add_head(&worker->hentry, bwh);
2229 worker->current_work = work;
2230 worker->current_func = work->func;
2231 worker->current_cwq = cwq;
2232 work_color = get_work_color(work);
2234 list_del_init(&work->entry);
2237 * CPU intensive works don't participate in concurrency
2238 * management. They're the scheduler's responsibility.
2240 if (unlikely(cpu_intensive))
2241 worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
2244 * Unbound gcwq isn't concurrency managed and work items should be
2245 * executed ASAP. Wake up another worker if necessary.
2247 if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
2248 wake_up_worker(pool);
2251 * Record the last CPU and clear PENDING which should be the last
2252 * update to @work. Also, do this inside @gcwq->lock so that
2253 * PENDING and queued state changes happen together while IRQ is
2256 set_work_cpu_and_clear_pending(work, gcwq->cpu);
2258 spin_unlock_irq(&gcwq->lock);
2260 lock_map_acquire_read(&cwq->wq->lockdep_map);
2261 lock_map_acquire(&lockdep_map);
2262 trace_workqueue_execute_start(work);
2263 worker->current_func(work);
2265 * While we must be careful to not use "work" after this, the trace
2266 * point will only record its address.
2268 trace_workqueue_execute_end(work);
2269 lock_map_release(&lockdep_map);
2270 lock_map_release(&cwq->wq->lockdep_map);
2272 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2273 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2274 " last function: %pf\n",
2275 current->comm, preempt_count(), task_pid_nr(current),
2276 worker->current_func);
2277 debug_show_held_locks(current);
2281 spin_lock_irq(&gcwq->lock);
2283 /* clear cpu intensive status */
2284 if (unlikely(cpu_intensive))
2285 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2287 /* we're done with it, release */
2288 hlist_del_init(&worker->hentry);
2289 worker->current_work = NULL;
2290 worker->current_func = NULL;
2291 worker->current_cwq = NULL;
2292 cwq_dec_nr_in_flight(cwq, work_color);
2296 * process_scheduled_works - process scheduled works
2299 * Process all scheduled works. Please note that the scheduled list
2300 * may change while processing a work, so this function repeatedly
2301 * fetches a work from the top and executes it.
2304 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2307 static void process_scheduled_works(struct worker *worker)
2309 while (!list_empty(&worker->scheduled)) {
2310 struct work_struct *work = list_first_entry(&worker->scheduled,
2311 struct work_struct, entry);
2312 process_one_work(worker, work);
2317 * worker_thread - the worker thread function
2320 * The gcwq worker thread function. There's a single dynamic pool of
2321 * these per each cpu. These workers process all works regardless of
2322 * their specific target workqueue. The only exception is works which
2323 * belong to workqueues with a rescuer which will be explained in
2326 static int worker_thread(void *__worker)
2328 struct worker *worker = __worker;
2329 struct worker_pool *pool = worker->pool;
2330 struct global_cwq *gcwq = pool->gcwq;
2332 /* tell the scheduler that this is a workqueue worker */
2333 worker->task->flags |= PF_WQ_WORKER;
2335 spin_lock_irq(&gcwq->lock);
2337 /* we are off idle list if destruction or rebind is requested */
2338 if (unlikely(list_empty(&worker->entry))) {
2339 spin_unlock_irq(&gcwq->lock);
2341 /* if DIE is set, destruction is requested */
2342 if (worker->flags & WORKER_DIE) {
2343 worker->task->flags &= ~PF_WQ_WORKER;
2347 /* otherwise, rebind */
2348 idle_worker_rebind(worker);
2352 worker_leave_idle(worker);
2354 /* no more worker necessary? */
2355 if (!need_more_worker(pool))
2358 /* do we need to manage? */
2359 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2363 * ->scheduled list can only be filled while a worker is
2364 * preparing to process a work or actually processing it.
2365 * Make sure nobody diddled with it while I was sleeping.
2367 BUG_ON(!list_empty(&worker->scheduled));
2370 * When control reaches this point, we're guaranteed to have
2371 * at least one idle worker or that someone else has already
2372 * assumed the manager role.
2374 worker_clr_flags(worker, WORKER_PREP);
2377 struct work_struct *work =
2378 list_first_entry(&pool->worklist,
2379 struct work_struct, entry);
2381 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2382 /* optimization path, not strictly necessary */
2383 process_one_work(worker, work);
2384 if (unlikely(!list_empty(&worker->scheduled)))
2385 process_scheduled_works(worker);
2387 move_linked_works(work, &worker->scheduled, NULL);
2388 process_scheduled_works(worker);
2390 } while (keep_working(pool));
2392 worker_set_flags(worker, WORKER_PREP, false);
2394 if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
2398 * gcwq->lock is held and there's no work to process and no
2399 * need to manage, sleep. Workers are woken up only while
2400 * holding gcwq->lock or from local cpu, so setting the
2401 * current state before releasing gcwq->lock is enough to
2402 * prevent losing any event.
2404 worker_enter_idle(worker);
2405 __set_current_state(TASK_INTERRUPTIBLE);
2406 spin_unlock_irq(&gcwq->lock);
2412 * rescuer_thread - the rescuer thread function
2413 * @__wq: the associated workqueue
2415 * Workqueue rescuer thread function. There's one rescuer for each
2416 * workqueue which has WQ_RESCUER set.
2418 * Regular work processing on a gcwq may block trying to create a new
2419 * worker which uses GFP_KERNEL allocation which has slight chance of
2420 * developing into deadlock if some works currently on the same queue
2421 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2422 * the problem rescuer solves.
2424 * When such condition is possible, the gcwq summons rescuers of all
2425 * workqueues which have works queued on the gcwq and let them process
2426 * those works so that forward progress can be guaranteed.
2428 * This should happen rarely.
2430 static int rescuer_thread(void *__wq)
2432 struct workqueue_struct *wq = __wq;
2433 struct worker *rescuer = wq->rescuer;
2434 struct list_head *scheduled = &rescuer->scheduled;
2435 bool is_unbound = wq->flags & WQ_UNBOUND;
2438 set_user_nice(current, RESCUER_NICE_LEVEL);
2440 set_current_state(TASK_INTERRUPTIBLE);
2442 if (kthread_should_stop()) {
2443 __set_current_state(TASK_RUNNING);
2448 * See whether any cpu is asking for help. Unbounded
2449 * workqueues use cpu 0 in mayday_mask for CPU_UNBOUND.
2451 for_each_mayday_cpu(cpu, wq->mayday_mask) {
2452 unsigned int tcpu = is_unbound ? WORK_CPU_UNBOUND : cpu;
2453 struct cpu_workqueue_struct *cwq = get_cwq(tcpu, wq);
2454 struct worker_pool *pool = cwq->pool;
2455 struct global_cwq *gcwq = pool->gcwq;
2456 struct work_struct *work, *n;
2458 __set_current_state(TASK_RUNNING);
2459 mayday_clear_cpu(cpu, wq->mayday_mask);
2461 /* migrate to the target cpu if possible */
2462 rescuer->pool = pool;
2463 worker_maybe_bind_and_lock(rescuer);
2466 * Slurp in all works issued via this workqueue and
2469 BUG_ON(!list_empty(&rescuer->scheduled));
2470 list_for_each_entry_safe(work, n, &pool->worklist, entry)
2471 if (get_work_cwq(work) == cwq)
2472 move_linked_works(work, scheduled, &n);
2474 process_scheduled_works(rescuer);
2477 * Leave this gcwq. If keep_working() is %true, notify a
2478 * regular worker; otherwise, we end up with 0 concurrency
2479 * and stalling the execution.
2481 if (keep_working(pool))
2482 wake_up_worker(pool);
2484 spin_unlock_irq(&gcwq->lock);
2492 struct work_struct work;
2493 struct completion done;
2496 static void wq_barrier_func(struct work_struct *work)
2498 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2499 complete(&barr->done);
2503 * insert_wq_barrier - insert a barrier work
2504 * @cwq: cwq to insert barrier into
2505 * @barr: wq_barrier to insert
2506 * @target: target work to attach @barr to
2507 * @worker: worker currently executing @target, NULL if @target is not executing
2509 * @barr is linked to @target such that @barr is completed only after
2510 * @target finishes execution. Please note that the ordering
2511 * guarantee is observed only with respect to @target and on the local
2514 * Currently, a queued barrier can't be canceled. This is because
2515 * try_to_grab_pending() can't determine whether the work to be
2516 * grabbed is at the head of the queue and thus can't clear LINKED
2517 * flag of the previous work while there must be a valid next work
2518 * after a work with LINKED flag set.
2520 * Note that when @worker is non-NULL, @target may be modified
2521 * underneath us, so we can't reliably determine cwq from @target.
2524 * spin_lock_irq(gcwq->lock).
2526 static void insert_wq_barrier(struct cpu_workqueue_struct *cwq,
2527 struct wq_barrier *barr,
2528 struct work_struct *target, struct worker *worker)
2530 struct list_head *head;
2531 unsigned int linked = 0;
2534 * debugobject calls are safe here even with gcwq->lock locked
2535 * as we know for sure that this will not trigger any of the
2536 * checks and call back into the fixup functions where we
2539 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2540 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2541 init_completion(&barr->done);
2544 * If @target is currently being executed, schedule the
2545 * barrier to the worker; otherwise, put it after @target.
2548 head = worker->scheduled.next;
2550 unsigned long *bits = work_data_bits(target);
2552 head = target->entry.next;
2553 /* there can already be other linked works, inherit and set */
2554 linked = *bits & WORK_STRUCT_LINKED;
2555 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2558 debug_work_activate(&barr->work);
2559 insert_work(cwq, &barr->work, head,
2560 work_color_to_flags(WORK_NO_COLOR) | linked);
2564 * flush_workqueue_prep_cwqs - prepare cwqs for workqueue flushing
2565 * @wq: workqueue being flushed
2566 * @flush_color: new flush color, < 0 for no-op
2567 * @work_color: new work color, < 0 for no-op
2569 * Prepare cwqs for workqueue flushing.
2571 * If @flush_color is non-negative, flush_color on all cwqs should be
2572 * -1. If no cwq has in-flight commands at the specified color, all
2573 * cwq->flush_color's stay at -1 and %false is returned. If any cwq
2574 * has in flight commands, its cwq->flush_color is set to
2575 * @flush_color, @wq->nr_cwqs_to_flush is updated accordingly, cwq
2576 * wakeup logic is armed and %true is returned.
2578 * The caller should have initialized @wq->first_flusher prior to
2579 * calling this function with non-negative @flush_color. If
2580 * @flush_color is negative, no flush color update is done and %false
2583 * If @work_color is non-negative, all cwqs should have the same
2584 * work_color which is previous to @work_color and all will be
2585 * advanced to @work_color.
2588 * mutex_lock(wq->flush_mutex).
2591 * %true if @flush_color >= 0 and there's something to flush. %false
2594 static bool flush_workqueue_prep_cwqs(struct workqueue_struct *wq,
2595 int flush_color, int work_color)
2600 if (flush_color >= 0) {
2601 BUG_ON(atomic_read(&wq->nr_cwqs_to_flush));
2602 atomic_set(&wq->nr_cwqs_to_flush, 1);
2605 for_each_cwq_cpu(cpu, wq) {
2606 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2607 struct global_cwq *gcwq = cwq->pool->gcwq;
2609 spin_lock_irq(&gcwq->lock);
2611 if (flush_color >= 0) {
2612 BUG_ON(cwq->flush_color != -1);
2614 if (cwq->nr_in_flight[flush_color]) {
2615 cwq->flush_color = flush_color;
2616 atomic_inc(&wq->nr_cwqs_to_flush);
2621 if (work_color >= 0) {
2622 BUG_ON(work_color != work_next_color(cwq->work_color));
2623 cwq->work_color = work_color;
2626 spin_unlock_irq(&gcwq->lock);
2629 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_cwqs_to_flush))
2630 complete(&wq->first_flusher->done);
2636 * flush_workqueue - ensure that any scheduled work has run to completion.
2637 * @wq: workqueue to flush
2639 * Forces execution of the workqueue and blocks until its completion.
2640 * This is typically used in driver shutdown handlers.
2642 * We sleep until all works which were queued on entry have been handled,
2643 * but we are not livelocked by new incoming ones.
2645 void flush_workqueue(struct workqueue_struct *wq)
2647 struct wq_flusher this_flusher = {
2648 .list = LIST_HEAD_INIT(this_flusher.list),
2650 .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
2654 lock_map_acquire(&wq->lockdep_map);
2655 lock_map_release(&wq->lockdep_map);
2657 mutex_lock(&wq->flush_mutex);
2660 * Start-to-wait phase
2662 next_color = work_next_color(wq->work_color);
2664 if (next_color != wq->flush_color) {
2666 * Color space is not full. The current work_color
2667 * becomes our flush_color and work_color is advanced
2670 BUG_ON(!list_empty(&wq->flusher_overflow));
2671 this_flusher.flush_color = wq->work_color;
2672 wq->work_color = next_color;
2674 if (!wq->first_flusher) {
2675 /* no flush in progress, become the first flusher */
2676 BUG_ON(wq->flush_color != this_flusher.flush_color);
2678 wq->first_flusher = &this_flusher;
2680 if (!flush_workqueue_prep_cwqs(wq, wq->flush_color,
2682 /* nothing to flush, done */
2683 wq->flush_color = next_color;
2684 wq->first_flusher = NULL;
2689 BUG_ON(wq->flush_color == this_flusher.flush_color);
2690 list_add_tail(&this_flusher.list, &wq->flusher_queue);
2691 flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2695 * Oops, color space is full, wait on overflow queue.
2696 * The next flush completion will assign us
2697 * flush_color and transfer to flusher_queue.
2699 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2702 mutex_unlock(&wq->flush_mutex);
2704 wait_for_completion(&this_flusher.done);
2707 * Wake-up-and-cascade phase
2709 * First flushers are responsible for cascading flushes and
2710 * handling overflow. Non-first flushers can simply return.
2712 if (wq->first_flusher != &this_flusher)
2715 mutex_lock(&wq->flush_mutex);
2717 /* we might have raced, check again with mutex held */
2718 if (wq->first_flusher != &this_flusher)
2721 wq->first_flusher = NULL;
2723 BUG_ON(!list_empty(&this_flusher.list));
2724 BUG_ON(wq->flush_color != this_flusher.flush_color);
2727 struct wq_flusher *next, *tmp;
2729 /* complete all the flushers sharing the current flush color */
2730 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2731 if (next->flush_color != wq->flush_color)
2733 list_del_init(&next->list);
2734 complete(&next->done);
2737 BUG_ON(!list_empty(&wq->flusher_overflow) &&
2738 wq->flush_color != work_next_color(wq->work_color));
2740 /* this flush_color is finished, advance by one */
2741 wq->flush_color = work_next_color(wq->flush_color);
2743 /* one color has been freed, handle overflow queue */
2744 if (!list_empty(&wq->flusher_overflow)) {
2746 * Assign the same color to all overflowed
2747 * flushers, advance work_color and append to
2748 * flusher_queue. This is the start-to-wait
2749 * phase for these overflowed flushers.
2751 list_for_each_entry(tmp, &wq->flusher_overflow, list)
2752 tmp->flush_color = wq->work_color;
2754 wq->work_color = work_next_color(wq->work_color);
2756 list_splice_tail_init(&wq->flusher_overflow,
2757 &wq->flusher_queue);
2758 flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2761 if (list_empty(&wq->flusher_queue)) {
2762 BUG_ON(wq->flush_color != wq->work_color);
2767 * Need to flush more colors. Make the next flusher
2768 * the new first flusher and arm cwqs.
2770 BUG_ON(wq->flush_color == wq->work_color);
2771 BUG_ON(wq->flush_color != next->flush_color);
2773 list_del_init(&next->list);
2774 wq->first_flusher = next;
2776 if (flush_workqueue_prep_cwqs(wq, wq->flush_color, -1))
2780 * Meh... this color is already done, clear first
2781 * flusher and repeat cascading.
2783 wq->first_flusher = NULL;
2787 mutex_unlock(&wq->flush_mutex);
2789 EXPORT_SYMBOL_GPL(flush_workqueue);
2792 * drain_workqueue - drain a workqueue
2793 * @wq: workqueue to drain
2795 * Wait until the workqueue becomes empty. While draining is in progress,
2796 * only chain queueing is allowed. IOW, only currently pending or running
2797 * work items on @wq can queue further work items on it. @wq is flushed
2798 * repeatedly until it becomes empty. The number of flushing is detemined
2799 * by the depth of chaining and should be relatively short. Whine if it
2802 void drain_workqueue(struct workqueue_struct *wq)
2804 unsigned int flush_cnt = 0;
2808 * __queue_work() needs to test whether there are drainers, is much
2809 * hotter than drain_workqueue() and already looks at @wq->flags.
2810 * Use WQ_DRAINING so that queue doesn't have to check nr_drainers.
2812 spin_lock(&workqueue_lock);
2813 if (!wq->nr_drainers++)
2814 wq->flags |= WQ_DRAINING;
2815 spin_unlock(&workqueue_lock);
2817 flush_workqueue(wq);
2819 for_each_cwq_cpu(cpu, wq) {
2820 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2823 spin_lock_irq(&cwq->pool->gcwq->lock);
2824 drained = !cwq->nr_active && list_empty(&cwq->delayed_works);
2825 spin_unlock_irq(&cwq->pool->gcwq->lock);
2830 if (++flush_cnt == 10 ||
2831 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2832 pr_warn("workqueue %s: flush on destruction isn't complete after %u tries\n",
2833 wq->name, flush_cnt);
2837 spin_lock(&workqueue_lock);
2838 if (!--wq->nr_drainers)
2839 wq->flags &= ~WQ_DRAINING;
2840 spin_unlock(&workqueue_lock);
2842 EXPORT_SYMBOL_GPL(drain_workqueue);
2844 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2846 struct worker *worker = NULL;
2847 struct global_cwq *gcwq;
2848 struct cpu_workqueue_struct *cwq;
2851 gcwq = get_work_gcwq(work);
2855 spin_lock_irq(&gcwq->lock);
2856 if (!list_empty(&work->entry)) {
2858 * See the comment near try_to_grab_pending()->smp_rmb().
2859 * If it was re-queued to a different gcwq under us, we
2860 * are not going to wait.
2863 cwq = get_work_cwq(work);
2864 if (unlikely(!cwq || gcwq != cwq->pool->gcwq))
2867 worker = find_worker_executing_work(gcwq, work);
2870 cwq = worker->current_cwq;
2873 insert_wq_barrier(cwq, barr, work, worker);
2874 spin_unlock_irq(&gcwq->lock);
2877 * If @max_active is 1 or rescuer is in use, flushing another work
2878 * item on the same workqueue may lead to deadlock. Make sure the
2879 * flusher is not running on the same workqueue by verifying write
2882 if (cwq->wq->saved_max_active == 1 || cwq->wq->flags & WQ_RESCUER)
2883 lock_map_acquire(&cwq->wq->lockdep_map);
2885 lock_map_acquire_read(&cwq->wq->lockdep_map);
2886 lock_map_release(&cwq->wq->lockdep_map);
2890 spin_unlock_irq(&gcwq->lock);
2895 * flush_work - wait for a work to finish executing the last queueing instance
2896 * @work: the work to flush
2898 * Wait until @work has finished execution. @work is guaranteed to be idle
2899 * on return if it hasn't been requeued since flush started.
2902 * %true if flush_work() waited for the work to finish execution,
2903 * %false if it was already idle.
2905 bool flush_work(struct work_struct *work)
2907 struct wq_barrier barr;
2909 lock_map_acquire(&work->lockdep_map);
2910 lock_map_release(&work->lockdep_map);
2912 if (start_flush_work(work, &barr)) {
2913 wait_for_completion(&barr.done);
2914 destroy_work_on_stack(&barr.work);
2920 EXPORT_SYMBOL_GPL(flush_work);
2922 static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2924 unsigned long flags;
2928 ret = try_to_grab_pending(work, is_dwork, &flags);
2930 * If someone else is canceling, wait for the same event it
2931 * would be waiting for before retrying.
2933 if (unlikely(ret == -ENOENT))
2935 } while (unlikely(ret < 0));
2937 /* tell other tasks trying to grab @work to back off */
2938 mark_work_canceling(work);
2939 local_irq_restore(flags);
2942 clear_work_data(work);
2947 * cancel_work_sync - cancel a work and wait for it to finish
2948 * @work: the work to cancel
2950 * Cancel @work and wait for its execution to finish. This function
2951 * can be used even if the work re-queues itself or migrates to
2952 * another workqueue. On return from this function, @work is
2953 * guaranteed to be not pending or executing on any CPU.
2955 * cancel_work_sync(&delayed_work->work) must not be used for
2956 * delayed_work's. Use cancel_delayed_work_sync() instead.
2958 * The caller must ensure that the workqueue on which @work was last
2959 * queued can't be destroyed before this function returns.
2962 * %true if @work was pending, %false otherwise.
2964 bool cancel_work_sync(struct work_struct *work)
2966 return __cancel_work_timer(work, false);
2968 EXPORT_SYMBOL_GPL(cancel_work_sync);
2971 * flush_delayed_work - wait for a dwork to finish executing the last queueing
2972 * @dwork: the delayed work to flush
2974 * Delayed timer is cancelled and the pending work is queued for
2975 * immediate execution. Like flush_work(), this function only
2976 * considers the last queueing instance of @dwork.
2979 * %true if flush_work() waited for the work to finish execution,
2980 * %false if it was already idle.
2982 bool flush_delayed_work(struct delayed_work *dwork)
2984 local_irq_disable();
2985 if (del_timer_sync(&dwork->timer))
2986 __queue_work(dwork->cpu,
2987 get_work_cwq(&dwork->work)->wq, &dwork->work);
2989 return flush_work(&dwork->work);
2991 EXPORT_SYMBOL(flush_delayed_work);
2994 * cancel_delayed_work - cancel a delayed work
2995 * @dwork: delayed_work to cancel
2997 * Kill off a pending delayed_work. Returns %true if @dwork was pending
2998 * and canceled; %false if wasn't pending. Note that the work callback
2999 * function may still be running on return, unless it returns %true and the
3000 * work doesn't re-arm itself. Explicitly flush or use
3001 * cancel_delayed_work_sync() to wait on it.
3003 * This function is safe to call from any context including IRQ handler.
3005 bool cancel_delayed_work(struct delayed_work *dwork)
3007 unsigned long flags;
3011 ret = try_to_grab_pending(&dwork->work, true, &flags);
3012 } while (unlikely(ret == -EAGAIN));
3014 if (unlikely(ret < 0))
3017 set_work_cpu_and_clear_pending(&dwork->work, work_cpu(&dwork->work));
3018 local_irq_restore(flags);
3021 EXPORT_SYMBOL(cancel_delayed_work);
3024 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3025 * @dwork: the delayed work cancel
3027 * This is cancel_work_sync() for delayed works.
3030 * %true if @dwork was pending, %false otherwise.
3032 bool cancel_delayed_work_sync(struct delayed_work *dwork)
3034 return __cancel_work_timer(&dwork->work, true);
3036 EXPORT_SYMBOL(cancel_delayed_work_sync);
3039 * schedule_work_on - put work task on a specific cpu
3040 * @cpu: cpu to put the work task on
3041 * @work: job to be done
3043 * This puts a job on a specific cpu
3045 bool schedule_work_on(int cpu, struct work_struct *work)
3047 return queue_work_on(cpu, system_wq, work);
3049 EXPORT_SYMBOL(schedule_work_on);
3052 * schedule_work - put work task in global workqueue
3053 * @work: job to be done
3055 * Returns %false if @work was already on the kernel-global workqueue and
3058 * This puts a job in the kernel-global workqueue if it was not already
3059 * queued and leaves it in the same position on the kernel-global
3060 * workqueue otherwise.
3062 bool schedule_work(struct work_struct *work)
3064 return queue_work(system_wq, work);
3066 EXPORT_SYMBOL(schedule_work);
3069 * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
3071 * @dwork: job to be done
3072 * @delay: number of jiffies to wait
3074 * After waiting for a given time this puts a job in the kernel-global
3075 * workqueue on the specified CPU.
3077 bool schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
3078 unsigned long delay)
3080 return queue_delayed_work_on(cpu, system_wq, dwork, delay);
3082 EXPORT_SYMBOL(schedule_delayed_work_on);
3085 * schedule_delayed_work - put work task in global workqueue after delay
3086 * @dwork: job to be done
3087 * @delay: number of jiffies to wait or 0 for immediate execution
3089 * After waiting for a given time this puts a job in the kernel-global
3092 bool schedule_delayed_work(struct delayed_work *dwork, unsigned long delay)
3094 return queue_delayed_work(system_wq, dwork, delay);
3096 EXPORT_SYMBOL(schedule_delayed_work);
3099 * schedule_on_each_cpu - execute a function synchronously on each online CPU
3100 * @func: the function to call
3102 * schedule_on_each_cpu() executes @func on each online CPU using the
3103 * system workqueue and blocks until all CPUs have completed.
3104 * schedule_on_each_cpu() is very slow.
3107 * 0 on success, -errno on failure.
3109 int schedule_on_each_cpu(work_func_t func)
3112 struct work_struct __percpu *works;
3114 works = alloc_percpu(struct work_struct);
3120 for_each_online_cpu(cpu) {
3121 struct work_struct *work = per_cpu_ptr(works, cpu);
3123 INIT_WORK(work, func);
3124 schedule_work_on(cpu, work);
3127 for_each_online_cpu(cpu)
3128 flush_work(per_cpu_ptr(works, cpu));
3136 * flush_scheduled_work - ensure that any scheduled work has run to completion.
3138 * Forces execution of the kernel-global workqueue and blocks until its
3141 * Think twice before calling this function! It's very easy to get into
3142 * trouble if you don't take great care. Either of the following situations
3143 * will lead to deadlock:
3145 * One of the work items currently on the workqueue needs to acquire
3146 * a lock held by your code or its caller.
3148 * Your code is running in the context of a work routine.
3150 * They will be detected by lockdep when they occur, but the first might not
3151 * occur very often. It depends on what work items are on the workqueue and
3152 * what locks they need, which you have no control over.
3154 * In most situations flushing the entire workqueue is overkill; you merely
3155 * need to know that a particular work item isn't queued and isn't running.
3156 * In such cases you should use cancel_delayed_work_sync() or
3157 * cancel_work_sync() instead.
3159 void flush_scheduled_work(void)
3161 flush_workqueue(system_wq);
3163 EXPORT_SYMBOL(flush_scheduled_work);
3166 * execute_in_process_context - reliably execute the routine with user context
3167 * @fn: the function to execute
3168 * @ew: guaranteed storage for the execute work structure (must
3169 * be available when the work executes)
3171 * Executes the function immediately if process context is available,
3172 * otherwise schedules the function for delayed execution.
3174 * Returns: 0 - function was executed
3175 * 1 - function was scheduled for execution
3177 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
3179 if (!in_interrupt()) {
3184 INIT_WORK(&ew->work, fn);
3185 schedule_work(&ew->work);
3189 EXPORT_SYMBOL_GPL(execute_in_process_context);
3191 int keventd_up(void)
3193 return system_wq != NULL;
3196 static int alloc_cwqs(struct workqueue_struct *wq)
3199 * cwqs are forced aligned according to WORK_STRUCT_FLAG_BITS.
3200 * Make sure that the alignment isn't lower than that of
3201 * unsigned long long.
3203 const size_t size = sizeof(struct cpu_workqueue_struct);
3204 const size_t align = max_t(size_t, 1 << WORK_STRUCT_FLAG_BITS,
3205 __alignof__(unsigned long long));
3207 if (!(wq->flags & WQ_UNBOUND))
3208 wq->cpu_wq.pcpu = __alloc_percpu(size, align);
3213 * Allocate enough room to align cwq and put an extra
3214 * pointer at the end pointing back to the originally
3215 * allocated pointer which will be used for free.
3217 ptr = kzalloc(size + align + sizeof(void *), GFP_KERNEL);
3219 wq->cpu_wq.single = PTR_ALIGN(ptr, align);
3220 *(void **)(wq->cpu_wq.single + 1) = ptr;
3224 /* just in case, make sure it's actually aligned */
3225 BUG_ON(!IS_ALIGNED(wq->cpu_wq.v, align));
3226 return wq->cpu_wq.v ? 0 : -ENOMEM;
3229 static void free_cwqs(struct workqueue_struct *wq)
3231 if (!(wq->flags & WQ_UNBOUND))
3232 free_percpu(wq->cpu_wq.pcpu);
3233 else if (wq->cpu_wq.single) {
3234 /* the pointer to free is stored right after the cwq */
3235 kfree(*(void **)(wq->cpu_wq.single + 1));
3239 static int wq_clamp_max_active(int max_active, unsigned int flags,
3242 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3244 if (max_active < 1 || max_active > lim)
3245 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3246 max_active, name, 1, lim);
3248 return clamp_val(max_active, 1, lim);
3251 struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
3254 struct lock_class_key *key,
3255 const char *lock_name, ...)
3257 va_list args, args1;
3258 struct workqueue_struct *wq;
3262 /* determine namelen, allocate wq and format name */
3263 va_start(args, lock_name);
3264 va_copy(args1, args);
3265 namelen = vsnprintf(NULL, 0, fmt, args) + 1;
3267 wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
3271 vsnprintf(wq->name, namelen, fmt, args1);
3276 * Workqueues which may be used during memory reclaim should
3277 * have a rescuer to guarantee forward progress.
3279 if (flags & WQ_MEM_RECLAIM)
3280 flags |= WQ_RESCUER;
3282 max_active = max_active ?: WQ_DFL_ACTIVE;
3283 max_active = wq_clamp_max_active(max_active, flags, wq->name);
3287 wq->saved_max_active = max_active;
3288 mutex_init(&wq->flush_mutex);
3289 atomic_set(&wq->nr_cwqs_to_flush, 0);
3290 INIT_LIST_HEAD(&wq->flusher_queue);
3291 INIT_LIST_HEAD(&wq->flusher_overflow);
3293 lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3294 INIT_LIST_HEAD(&wq->list);
3296 if (alloc_cwqs(wq) < 0)
3299 for_each_cwq_cpu(cpu, wq) {
3300 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3301 struct global_cwq *gcwq = get_gcwq(cpu);
3302 int pool_idx = (bool)(flags & WQ_HIGHPRI);
3304 BUG_ON((unsigned long)cwq & WORK_STRUCT_FLAG_MASK);
3305 cwq->pool = &gcwq->pools[pool_idx];
3307 cwq->flush_color = -1;
3308 cwq->max_active = max_active;
3309 INIT_LIST_HEAD(&cwq->delayed_works);
3312 if (flags & WQ_RESCUER) {
3313 struct worker *rescuer;
3315 if (!alloc_mayday_mask(&wq->mayday_mask, GFP_KERNEL))
3318 wq->rescuer = rescuer = alloc_worker();
3322 rescuer->task = kthread_create(rescuer_thread, wq, "%s",
3324 if (IS_ERR(rescuer->task))
3327 rescuer->task->flags |= PF_THREAD_BOUND;
3328 wake_up_process(rescuer->task);
3332 * workqueue_lock protects global freeze state and workqueues
3333 * list. Grab it, set max_active accordingly and add the new
3334 * workqueue to workqueues list.
3336 spin_lock(&workqueue_lock);
3338 if (workqueue_freezing && wq->flags & WQ_FREEZABLE)
3339 for_each_cwq_cpu(cpu, wq)
3340 get_cwq(cpu, wq)->max_active = 0;
3342 list_add(&wq->list, &workqueues);
3344 spin_unlock(&workqueue_lock);
3350 free_mayday_mask(wq->mayday_mask);
3356 EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
3359 * destroy_workqueue - safely terminate a workqueue
3360 * @wq: target workqueue
3362 * Safely destroy a workqueue. All work currently pending will be done first.
3364 void destroy_workqueue(struct workqueue_struct *wq)
3368 /* drain it before proceeding with destruction */
3369 drain_workqueue(wq);
3372 * wq list is used to freeze wq, remove from list after
3373 * flushing is complete in case freeze races us.
3375 spin_lock(&workqueue_lock);
3376 list_del(&wq->list);
3377 spin_unlock(&workqueue_lock);
3380 for_each_cwq_cpu(cpu, wq) {
3381 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3384 for (i = 0; i < WORK_NR_COLORS; i++)
3385 BUG_ON(cwq->nr_in_flight[i]);
3386 BUG_ON(cwq->nr_active);
3387 BUG_ON(!list_empty(&cwq->delayed_works));
3390 if (wq->flags & WQ_RESCUER) {
3391 kthread_stop(wq->rescuer->task);
3392 free_mayday_mask(wq->mayday_mask);
3399 EXPORT_SYMBOL_GPL(destroy_workqueue);
3402 * cwq_set_max_active - adjust max_active of a cwq
3403 * @cwq: target cpu_workqueue_struct
3404 * @max_active: new max_active value.
3406 * Set @cwq->max_active to @max_active and activate delayed works if
3410 * spin_lock_irq(gcwq->lock).
3412 static void cwq_set_max_active(struct cpu_workqueue_struct *cwq, int max_active)
3414 cwq->max_active = max_active;
3416 while (!list_empty(&cwq->delayed_works) &&
3417 cwq->nr_active < cwq->max_active)
3418 cwq_activate_first_delayed(cwq);
3422 * workqueue_set_max_active - adjust max_active of a workqueue
3423 * @wq: target workqueue
3424 * @max_active: new max_active value.
3426 * Set max_active of @wq to @max_active.
3429 * Don't call from IRQ context.
3431 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
3435 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
3437 spin_lock(&workqueue_lock);
3439 wq->saved_max_active = max_active;
3441 for_each_cwq_cpu(cpu, wq) {
3442 struct global_cwq *gcwq = get_gcwq(cpu);
3444 spin_lock_irq(&gcwq->lock);
3446 if (!(wq->flags & WQ_FREEZABLE) ||
3447 !(gcwq->flags & GCWQ_FREEZING))
3448 cwq_set_max_active(get_cwq(gcwq->cpu, wq), max_active);
3450 spin_unlock_irq(&gcwq->lock);
3453 spin_unlock(&workqueue_lock);
3455 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
3458 * workqueue_congested - test whether a workqueue is congested
3459 * @cpu: CPU in question
3460 * @wq: target workqueue
3462 * Test whether @wq's cpu workqueue for @cpu is congested. There is
3463 * no synchronization around this function and the test result is
3464 * unreliable and only useful as advisory hints or for debugging.
3467 * %true if congested, %false otherwise.
3469 bool workqueue_congested(unsigned int cpu, struct workqueue_struct *wq)
3471 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3473 return !list_empty(&cwq->delayed_works);
3475 EXPORT_SYMBOL_GPL(workqueue_congested);
3478 * work_cpu - return the last known associated cpu for @work
3479 * @work: the work of interest
3482 * CPU number if @work was ever queued. WORK_CPU_NONE otherwise.
3484 unsigned int work_cpu(struct work_struct *work)
3486 struct global_cwq *gcwq = get_work_gcwq(work);
3488 return gcwq ? gcwq->cpu : WORK_CPU_NONE;
3490 EXPORT_SYMBOL_GPL(work_cpu);
3493 * work_busy - test whether a work is currently pending or running
3494 * @work: the work to be tested
3496 * Test whether @work is currently pending or running. There is no
3497 * synchronization around this function and the test result is
3498 * unreliable and only useful as advisory hints or for debugging.
3499 * Especially for reentrant wqs, the pending state might hide the
3503 * OR'd bitmask of WORK_BUSY_* bits.
3505 unsigned int work_busy(struct work_struct *work)
3507 struct global_cwq *gcwq = get_work_gcwq(work);
3508 unsigned long flags;
3509 unsigned int ret = 0;
3514 spin_lock_irqsave(&gcwq->lock, flags);
3516 if (work_pending(work))
3517 ret |= WORK_BUSY_PENDING;
3518 if (find_worker_executing_work(gcwq, work))
3519 ret |= WORK_BUSY_RUNNING;
3521 spin_unlock_irqrestore(&gcwq->lock, flags);
3525 EXPORT_SYMBOL_GPL(work_busy);
3530 * There are two challenges in supporting CPU hotplug. Firstly, there
3531 * are a lot of assumptions on strong associations among work, cwq and
3532 * gcwq which make migrating pending and scheduled works very
3533 * difficult to implement without impacting hot paths. Secondly,
3534 * gcwqs serve mix of short, long and very long running works making
3535 * blocked draining impractical.
3537 * This is solved by allowing a gcwq to be disassociated from the CPU
3538 * running as an unbound one and allowing it to be reattached later if the
3539 * cpu comes back online.
3542 /* claim manager positions of all pools */
3543 static void gcwq_claim_assoc_and_lock(struct global_cwq *gcwq)
3545 struct worker_pool *pool;
3547 for_each_worker_pool(pool, gcwq)
3548 mutex_lock_nested(&pool->assoc_mutex, pool - gcwq->pools);
3549 spin_lock_irq(&gcwq->lock);
3552 /* release manager positions */
3553 static void gcwq_release_assoc_and_unlock(struct global_cwq *gcwq)
3555 struct worker_pool *pool;
3557 spin_unlock_irq(&gcwq->lock);
3558 for_each_worker_pool(pool, gcwq)
3559 mutex_unlock(&pool->assoc_mutex);
3562 static void gcwq_unbind_fn(struct work_struct *work)
3564 struct global_cwq *gcwq = get_gcwq(smp_processor_id());
3565 struct worker_pool *pool;
3566 struct worker *worker;
3567 struct hlist_node *pos;
3570 BUG_ON(gcwq->cpu != smp_processor_id());
3572 gcwq_claim_assoc_and_lock(gcwq);
3575 * We've claimed all manager positions. Make all workers unbound
3576 * and set DISASSOCIATED. Before this, all workers except for the
3577 * ones which are still executing works from before the last CPU
3578 * down must be on the cpu. After this, they may become diasporas.
3580 for_each_worker_pool(pool, gcwq)
3581 list_for_each_entry(worker, &pool->idle_list, entry)
3582 worker->flags |= WORKER_UNBOUND;
3584 for_each_busy_worker(worker, i, pos, gcwq)
3585 worker->flags |= WORKER_UNBOUND;
3587 gcwq->flags |= GCWQ_DISASSOCIATED;
3589 gcwq_release_assoc_and_unlock(gcwq);
3592 * Call schedule() so that we cross rq->lock and thus can guarantee
3593 * sched callbacks see the %WORKER_UNBOUND flag. This is necessary
3594 * as scheduler callbacks may be invoked from other cpus.
3599 * Sched callbacks are disabled now. Zap nr_running. After this,
3600 * nr_running stays zero and need_more_worker() and keep_working()
3601 * are always true as long as the worklist is not empty. @gcwq now
3602 * behaves as unbound (in terms of concurrency management) gcwq
3603 * which is served by workers tied to the CPU.
3605 * On return from this function, the current worker would trigger
3606 * unbound chain execution of pending work items if other workers
3609 for_each_worker_pool(pool, gcwq)
3610 atomic_set(get_pool_nr_running(pool), 0);
3614 * Workqueues should be brought up before normal priority CPU notifiers.
3615 * This will be registered high priority CPU notifier.
3617 static int __cpuinit workqueue_cpu_up_callback(struct notifier_block *nfb,
3618 unsigned long action,
3621 unsigned int cpu = (unsigned long)hcpu;
3622 struct global_cwq *gcwq = get_gcwq(cpu);
3623 struct worker_pool *pool;
3625 switch (action & ~CPU_TASKS_FROZEN) {
3626 case CPU_UP_PREPARE:
3627 for_each_worker_pool(pool, gcwq) {
3628 struct worker *worker;
3630 if (pool->nr_workers)
3633 worker = create_worker(pool);
3637 spin_lock_irq(&gcwq->lock);
3638 start_worker(worker);
3639 spin_unlock_irq(&gcwq->lock);
3643 case CPU_DOWN_FAILED:
3645 gcwq_claim_assoc_and_lock(gcwq);
3646 gcwq->flags &= ~GCWQ_DISASSOCIATED;
3647 rebind_workers(gcwq);
3648 gcwq_release_assoc_and_unlock(gcwq);
3655 * Workqueues should be brought down after normal priority CPU notifiers.
3656 * This will be registered as low priority CPU notifier.
3658 static int __cpuinit workqueue_cpu_down_callback(struct notifier_block *nfb,
3659 unsigned long action,
3662 unsigned int cpu = (unsigned long)hcpu;
3663 struct work_struct unbind_work;
3665 switch (action & ~CPU_TASKS_FROZEN) {
3666 case CPU_DOWN_PREPARE:
3667 /* unbinding should happen on the local CPU */
3668 INIT_WORK_ONSTACK(&unbind_work, gcwq_unbind_fn);
3669 queue_work_on(cpu, system_highpri_wq, &unbind_work);
3670 flush_work(&unbind_work);
3678 struct work_for_cpu {
3679 struct work_struct work;
3685 static void work_for_cpu_fn(struct work_struct *work)
3687 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
3689 wfc->ret = wfc->fn(wfc->arg);
3693 * work_on_cpu - run a function in user context on a particular cpu
3694 * @cpu: the cpu to run on
3695 * @fn: the function to run
3696 * @arg: the function arg
3698 * This will return the value @fn returns.
3699 * It is up to the caller to ensure that the cpu doesn't go offline.
3700 * The caller must not hold any locks which would prevent @fn from completing.
3702 long work_on_cpu(unsigned int cpu, long (*fn)(void *), void *arg)
3704 struct work_for_cpu wfc = { .fn = fn, .arg = arg };
3706 INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
3707 schedule_work_on(cpu, &wfc.work);
3708 flush_work(&wfc.work);
3711 EXPORT_SYMBOL_GPL(work_on_cpu);
3712 #endif /* CONFIG_SMP */
3714 #ifdef CONFIG_FREEZER
3717 * freeze_workqueues_begin - begin freezing workqueues
3719 * Start freezing workqueues. After this function returns, all freezable
3720 * workqueues will queue new works to their frozen_works list instead of
3724 * Grabs and releases workqueue_lock and gcwq->lock's.
3726 void freeze_workqueues_begin(void)
3730 spin_lock(&workqueue_lock);
3732 BUG_ON(workqueue_freezing);
3733 workqueue_freezing = true;
3735 for_each_gcwq_cpu(cpu) {
3736 struct global_cwq *gcwq = get_gcwq(cpu);
3737 struct workqueue_struct *wq;
3739 spin_lock_irq(&gcwq->lock);
3741 BUG_ON(gcwq->flags & GCWQ_FREEZING);
3742 gcwq->flags |= GCWQ_FREEZING;
3744 list_for_each_entry(wq, &workqueues, list) {
3745 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3747 if (cwq && wq->flags & WQ_FREEZABLE)
3748 cwq->max_active = 0;
3751 spin_unlock_irq(&gcwq->lock);
3754 spin_unlock(&workqueue_lock);
3758 * freeze_workqueues_busy - are freezable workqueues still busy?
3760 * Check whether freezing is complete. This function must be called
3761 * between freeze_workqueues_begin() and thaw_workqueues().
3764 * Grabs and releases workqueue_lock.
3767 * %true if some freezable workqueues are still busy. %false if freezing
3770 bool freeze_workqueues_busy(void)
3775 spin_lock(&workqueue_lock);
3777 BUG_ON(!workqueue_freezing);
3779 for_each_gcwq_cpu(cpu) {
3780 struct workqueue_struct *wq;
3782 * nr_active is monotonically decreasing. It's safe
3783 * to peek without lock.
3785 list_for_each_entry(wq, &workqueues, list) {
3786 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3788 if (!cwq || !(wq->flags & WQ_FREEZABLE))
3791 BUG_ON(cwq->nr_active < 0);
3792 if (cwq->nr_active) {
3799 spin_unlock(&workqueue_lock);
3804 * thaw_workqueues - thaw workqueues
3806 * Thaw workqueues. Normal queueing is restored and all collected
3807 * frozen works are transferred to their respective gcwq worklists.
3810 * Grabs and releases workqueue_lock and gcwq->lock's.
3812 void thaw_workqueues(void)
3816 spin_lock(&workqueue_lock);
3818 if (!workqueue_freezing)
3821 for_each_gcwq_cpu(cpu) {
3822 struct global_cwq *gcwq = get_gcwq(cpu);
3823 struct worker_pool *pool;
3824 struct workqueue_struct *wq;
3826 spin_lock_irq(&gcwq->lock);
3828 BUG_ON(!(gcwq->flags & GCWQ_FREEZING));
3829 gcwq->flags &= ~GCWQ_FREEZING;
3831 list_for_each_entry(wq, &workqueues, list) {
3832 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3834 if (!cwq || !(wq->flags & WQ_FREEZABLE))
3837 /* restore max_active and repopulate worklist */
3838 cwq_set_max_active(cwq, wq->saved_max_active);
3841 for_each_worker_pool(pool, gcwq)
3842 wake_up_worker(pool);
3844 spin_unlock_irq(&gcwq->lock);
3847 workqueue_freezing = false;
3849 spin_unlock(&workqueue_lock);
3851 #endif /* CONFIG_FREEZER */
3853 static int __init init_workqueues(void)
3858 /* make sure we have enough bits for OFFQ CPU number */
3859 BUILD_BUG_ON((1LU << (BITS_PER_LONG - WORK_OFFQ_CPU_SHIFT)) <
3862 cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
3863 hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
3865 /* initialize gcwqs */
3866 for_each_gcwq_cpu(cpu) {
3867 struct global_cwq *gcwq = get_gcwq(cpu);
3868 struct worker_pool *pool;
3870 spin_lock_init(&gcwq->lock);
3872 gcwq->flags |= GCWQ_DISASSOCIATED;
3874 for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)
3875 INIT_HLIST_HEAD(&gcwq->busy_hash[i]);
3877 for_each_worker_pool(pool, gcwq) {
3879 INIT_LIST_HEAD(&pool->worklist);
3880 INIT_LIST_HEAD(&pool->idle_list);
3882 init_timer_deferrable(&pool->idle_timer);
3883 pool->idle_timer.function = idle_worker_timeout;
3884 pool->idle_timer.data = (unsigned long)pool;
3886 setup_timer(&pool->mayday_timer, gcwq_mayday_timeout,
3887 (unsigned long)pool);
3889 mutex_init(&pool->assoc_mutex);
3890 ida_init(&pool->worker_ida);
3894 /* create the initial worker */
3895 for_each_online_gcwq_cpu(cpu) {
3896 struct global_cwq *gcwq = get_gcwq(cpu);
3897 struct worker_pool *pool;
3899 if (cpu != WORK_CPU_UNBOUND)
3900 gcwq->flags &= ~GCWQ_DISASSOCIATED;
3902 for_each_worker_pool(pool, gcwq) {
3903 struct worker *worker;
3905 worker = create_worker(pool);
3907 spin_lock_irq(&gcwq->lock);
3908 start_worker(worker);
3909 spin_unlock_irq(&gcwq->lock);
3913 system_wq = alloc_workqueue("events", 0, 0);
3914 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
3915 system_long_wq = alloc_workqueue("events_long", 0, 0);
3916 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
3917 WQ_UNBOUND_MAX_ACTIVE);
3918 system_freezable_wq = alloc_workqueue("events_freezable",
3920 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
3921 !system_unbound_wq || !system_freezable_wq);
3924 early_initcall(init_workqueues);