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 * managership 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 */
71 WORKER_STARTED = 1 << 0, /* started */
72 WORKER_DIE = 1 << 1, /* die die die */
73 WORKER_IDLE = 1 << 2, /* is idle */
74 WORKER_PREP = 1 << 3, /* preparing to run works */
75 WORKER_REBIND = 1 << 5, /* mom is home, come back */
76 WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
77 WORKER_UNBOUND = 1 << 7, /* worker is unbound */
79 WORKER_NOT_RUNNING = WORKER_PREP | WORKER_REBIND | 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.
131 * The poor guys doing the actual heavy lifting. All on-duty workers
132 * are either serving the manager role, on idle list or on busy hash.
135 /* on idle list while idle, on busy hash table while busy */
137 struct list_head entry; /* L: while idle */
138 struct hlist_node hentry; /* L: while busy */
141 struct work_struct *current_work; /* L: work being processed */
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 idle_rebind *idle_rebind; /* L: for idle worker */
153 struct work_struct rebind_work; /* L: for busy worker */
157 struct global_cwq *gcwq; /* I: the owning gcwq */
158 unsigned int flags; /* X: flags */
160 struct list_head worklist; /* L: list of pending works */
161 int nr_workers; /* L: total number of workers */
162 int nr_idle; /* L: currently idle ones */
164 struct list_head idle_list; /* X: list of idle workers */
165 struct timer_list idle_timer; /* L: worker idle timeout */
166 struct timer_list mayday_timer; /* L: SOS timer for workers */
168 struct mutex manager_mutex; /* mutex manager should hold */
169 struct ida worker_ida; /* L: for worker IDs */
173 * Global per-cpu workqueue. There's one and only one for each cpu
174 * and all works are queued and processed here regardless of their
178 spinlock_t lock; /* the gcwq lock */
179 unsigned int cpu; /* I: the associated cpu */
180 unsigned int flags; /* L: GCWQ_* flags */
182 /* workers are chained either in busy_hash or pool idle_list */
183 struct hlist_head busy_hash[BUSY_WORKER_HASH_SIZE];
184 /* L: hash of busy workers */
186 struct worker_pool pools[NR_WORKER_POOLS];
187 /* normal and highpri pools */
189 wait_queue_head_t rebind_hold; /* rebind hold wait */
190 } ____cacheline_aligned_in_smp;
193 * The per-CPU workqueue. The lower WORK_STRUCT_FLAG_BITS of
194 * work_struct->data are used for flags and thus cwqs need to be
195 * aligned at two's power of the number of flag bits.
197 struct cpu_workqueue_struct {
198 struct worker_pool *pool; /* I: the associated pool */
199 struct workqueue_struct *wq; /* I: the owning workqueue */
200 int work_color; /* L: current color */
201 int flush_color; /* L: flushing color */
202 int nr_in_flight[WORK_NR_COLORS];
203 /* L: nr of in_flight works */
204 int nr_active; /* L: nr of active works */
205 int max_active; /* L: max active works */
206 struct list_head delayed_works; /* L: delayed works */
210 * Structure used to wait for workqueue flush.
213 struct list_head list; /* F: list of flushers */
214 int flush_color; /* F: flush color waiting for */
215 struct completion done; /* flush completion */
219 * All cpumasks are assumed to be always set on UP and thus can't be
220 * used to determine whether there's something to be done.
223 typedef cpumask_var_t mayday_mask_t;
224 #define mayday_test_and_set_cpu(cpu, mask) \
225 cpumask_test_and_set_cpu((cpu), (mask))
226 #define mayday_clear_cpu(cpu, mask) cpumask_clear_cpu((cpu), (mask))
227 #define for_each_mayday_cpu(cpu, mask) for_each_cpu((cpu), (mask))
228 #define alloc_mayday_mask(maskp, gfp) zalloc_cpumask_var((maskp), (gfp))
229 #define free_mayday_mask(mask) free_cpumask_var((mask))
231 typedef unsigned long mayday_mask_t;
232 #define mayday_test_and_set_cpu(cpu, mask) test_and_set_bit(0, &(mask))
233 #define mayday_clear_cpu(cpu, mask) clear_bit(0, &(mask))
234 #define for_each_mayday_cpu(cpu, mask) if ((cpu) = 0, (mask))
235 #define alloc_mayday_mask(maskp, gfp) true
236 #define free_mayday_mask(mask) do { } while (0)
240 * The externally visible workqueue abstraction is an array of
241 * per-CPU workqueues:
243 struct workqueue_struct {
244 unsigned int flags; /* W: WQ_* flags */
246 struct cpu_workqueue_struct __percpu *pcpu;
247 struct cpu_workqueue_struct *single;
249 } cpu_wq; /* I: cwq's */
250 struct list_head list; /* W: list of all workqueues */
252 struct mutex flush_mutex; /* protects wq flushing */
253 int work_color; /* F: current work color */
254 int flush_color; /* F: current flush color */
255 atomic_t nr_cwqs_to_flush; /* flush in progress */
256 struct wq_flusher *first_flusher; /* F: first flusher */
257 struct list_head flusher_queue; /* F: flush waiters */
258 struct list_head flusher_overflow; /* F: flush overflow list */
260 mayday_mask_t mayday_mask; /* cpus requesting rescue */
261 struct worker *rescuer; /* I: rescue worker */
263 int nr_drainers; /* W: drain in progress */
264 int saved_max_active; /* W: saved cwq max_active */
265 #ifdef CONFIG_LOCKDEP
266 struct lockdep_map lockdep_map;
268 char name[]; /* I: workqueue name */
271 struct workqueue_struct *system_wq __read_mostly;
272 EXPORT_SYMBOL_GPL(system_wq);
273 struct workqueue_struct *system_highpri_wq __read_mostly;
274 EXPORT_SYMBOL_GPL(system_highpri_wq);
275 struct workqueue_struct *system_long_wq __read_mostly;
276 EXPORT_SYMBOL_GPL(system_long_wq);
277 struct workqueue_struct *system_unbound_wq __read_mostly;
278 EXPORT_SYMBOL_GPL(system_unbound_wq);
279 struct workqueue_struct *system_freezable_wq __read_mostly;
280 EXPORT_SYMBOL_GPL(system_freezable_wq);
282 #define CREATE_TRACE_POINTS
283 #include <trace/events/workqueue.h>
285 #define for_each_worker_pool(pool, gcwq) \
286 for ((pool) = &(gcwq)->pools[0]; \
287 (pool) < &(gcwq)->pools[NR_WORKER_POOLS]; (pool)++)
289 #define for_each_busy_worker(worker, i, pos, gcwq) \
290 for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++) \
291 hlist_for_each_entry(worker, pos, &gcwq->busy_hash[i], hentry)
293 static inline int __next_gcwq_cpu(int cpu, const struct cpumask *mask,
296 if (cpu < nr_cpu_ids) {
298 cpu = cpumask_next(cpu, mask);
299 if (cpu < nr_cpu_ids)
303 return WORK_CPU_UNBOUND;
305 return WORK_CPU_NONE;
308 static inline int __next_wq_cpu(int cpu, const struct cpumask *mask,
309 struct workqueue_struct *wq)
311 return __next_gcwq_cpu(cpu, mask, !(wq->flags & WQ_UNBOUND) ? 1 : 2);
317 * An extra gcwq is defined for an invalid cpu number
318 * (WORK_CPU_UNBOUND) to host workqueues which are not bound to any
319 * specific CPU. The following iterators are similar to
320 * for_each_*_cpu() iterators but also considers the unbound gcwq.
322 * for_each_gcwq_cpu() : possible CPUs + WORK_CPU_UNBOUND
323 * for_each_online_gcwq_cpu() : online CPUs + WORK_CPU_UNBOUND
324 * for_each_cwq_cpu() : possible CPUs for bound workqueues,
325 * WORK_CPU_UNBOUND for unbound workqueues
327 #define for_each_gcwq_cpu(cpu) \
328 for ((cpu) = __next_gcwq_cpu(-1, cpu_possible_mask, 3); \
329 (cpu) < WORK_CPU_NONE; \
330 (cpu) = __next_gcwq_cpu((cpu), cpu_possible_mask, 3))
332 #define for_each_online_gcwq_cpu(cpu) \
333 for ((cpu) = __next_gcwq_cpu(-1, cpu_online_mask, 3); \
334 (cpu) < WORK_CPU_NONE; \
335 (cpu) = __next_gcwq_cpu((cpu), cpu_online_mask, 3))
337 #define for_each_cwq_cpu(cpu, wq) \
338 for ((cpu) = __next_wq_cpu(-1, cpu_possible_mask, (wq)); \
339 (cpu) < WORK_CPU_NONE; \
340 (cpu) = __next_wq_cpu((cpu), cpu_possible_mask, (wq)))
342 #ifdef CONFIG_DEBUG_OBJECTS_WORK
344 static struct debug_obj_descr work_debug_descr;
346 static void *work_debug_hint(void *addr)
348 return ((struct work_struct *) addr)->func;
352 * fixup_init is called when:
353 * - an active object is initialized
355 static int work_fixup_init(void *addr, enum debug_obj_state state)
357 struct work_struct *work = addr;
360 case ODEBUG_STATE_ACTIVE:
361 cancel_work_sync(work);
362 debug_object_init(work, &work_debug_descr);
370 * fixup_activate is called when:
371 * - an active object is activated
372 * - an unknown object is activated (might be a statically initialized object)
374 static int work_fixup_activate(void *addr, enum debug_obj_state state)
376 struct work_struct *work = addr;
380 case ODEBUG_STATE_NOTAVAILABLE:
382 * This is not really a fixup. The work struct was
383 * statically initialized. We just make sure that it
384 * is tracked in the object tracker.
386 if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
387 debug_object_init(work, &work_debug_descr);
388 debug_object_activate(work, &work_debug_descr);
394 case ODEBUG_STATE_ACTIVE:
403 * fixup_free is called when:
404 * - an active object is freed
406 static int work_fixup_free(void *addr, enum debug_obj_state state)
408 struct work_struct *work = addr;
411 case ODEBUG_STATE_ACTIVE:
412 cancel_work_sync(work);
413 debug_object_free(work, &work_debug_descr);
420 static struct debug_obj_descr work_debug_descr = {
421 .name = "work_struct",
422 .debug_hint = work_debug_hint,
423 .fixup_init = work_fixup_init,
424 .fixup_activate = work_fixup_activate,
425 .fixup_free = work_fixup_free,
428 static inline void debug_work_activate(struct work_struct *work)
430 debug_object_activate(work, &work_debug_descr);
433 static inline void debug_work_deactivate(struct work_struct *work)
435 debug_object_deactivate(work, &work_debug_descr);
438 void __init_work(struct work_struct *work, int onstack)
441 debug_object_init_on_stack(work, &work_debug_descr);
443 debug_object_init(work, &work_debug_descr);
445 EXPORT_SYMBOL_GPL(__init_work);
447 void destroy_work_on_stack(struct work_struct *work)
449 debug_object_free(work, &work_debug_descr);
451 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
454 static inline void debug_work_activate(struct work_struct *work) { }
455 static inline void debug_work_deactivate(struct work_struct *work) { }
458 /* Serializes the accesses to the list of workqueues. */
459 static DEFINE_SPINLOCK(workqueue_lock);
460 static LIST_HEAD(workqueues);
461 static bool workqueue_freezing; /* W: have wqs started freezing? */
464 * The almighty global cpu workqueues. nr_running is the only field
465 * which is expected to be used frequently by other cpus via
466 * try_to_wake_up(). Put it in a separate cacheline.
468 static DEFINE_PER_CPU(struct global_cwq, global_cwq);
469 static DEFINE_PER_CPU_SHARED_ALIGNED(atomic_t, pool_nr_running[NR_WORKER_POOLS]);
472 * Global cpu workqueue and nr_running counter for unbound gcwq. The
473 * gcwq is always online, has GCWQ_DISASSOCIATED set, and all its
474 * workers have WORKER_UNBOUND set.
476 static struct global_cwq unbound_global_cwq;
477 static atomic_t unbound_pool_nr_running[NR_WORKER_POOLS] = {
478 [0 ... NR_WORKER_POOLS - 1] = ATOMIC_INIT(0), /* always 0 */
481 static int worker_thread(void *__worker);
483 static int worker_pool_pri(struct worker_pool *pool)
485 return pool - pool->gcwq->pools;
488 static struct global_cwq *get_gcwq(unsigned int cpu)
490 if (cpu != WORK_CPU_UNBOUND)
491 return &per_cpu(global_cwq, cpu);
493 return &unbound_global_cwq;
496 static atomic_t *get_pool_nr_running(struct worker_pool *pool)
498 int cpu = pool->gcwq->cpu;
499 int idx = worker_pool_pri(pool);
501 if (cpu != WORK_CPU_UNBOUND)
502 return &per_cpu(pool_nr_running, cpu)[idx];
504 return &unbound_pool_nr_running[idx];
507 static struct cpu_workqueue_struct *get_cwq(unsigned int cpu,
508 struct workqueue_struct *wq)
510 if (!(wq->flags & WQ_UNBOUND)) {
511 if (likely(cpu < nr_cpu_ids))
512 return per_cpu_ptr(wq->cpu_wq.pcpu, cpu);
513 } else if (likely(cpu == WORK_CPU_UNBOUND))
514 return wq->cpu_wq.single;
518 static unsigned int work_color_to_flags(int color)
520 return color << WORK_STRUCT_COLOR_SHIFT;
523 static int get_work_color(struct work_struct *work)
525 return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
526 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
529 static int work_next_color(int color)
531 return (color + 1) % WORK_NR_COLORS;
535 * While queued, %WORK_STRUCT_CWQ is set and non flag bits of a work's data
536 * contain the pointer to the queued cwq. Once execution starts, the flag
537 * is cleared and the high bits contain OFFQ flags and CPU number.
539 * set_work_cwq(), set_work_cpu_and_clear_pending(), mark_work_canceling()
540 * and clear_work_data() can be used to set the cwq, cpu or clear
541 * work->data. These functions should only be called while the work is
542 * owned - ie. while the PENDING bit is set.
544 * get_work_[g]cwq() can be used to obtain the gcwq or cwq corresponding to
545 * a work. gcwq is available once the work has been queued anywhere after
546 * initialization until it is sync canceled. cwq is available only while
547 * the work item is queued.
549 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
550 * canceled. While being canceled, a work item may have its PENDING set
551 * but stay off timer and worklist for arbitrarily long and nobody should
552 * try to steal the PENDING bit.
554 static inline void set_work_data(struct work_struct *work, unsigned long data,
557 BUG_ON(!work_pending(work));
558 atomic_long_set(&work->data, data | flags | work_static(work));
561 static void set_work_cwq(struct work_struct *work,
562 struct cpu_workqueue_struct *cwq,
563 unsigned long extra_flags)
565 set_work_data(work, (unsigned long)cwq,
566 WORK_STRUCT_PENDING | WORK_STRUCT_CWQ | extra_flags);
569 static void set_work_cpu_and_clear_pending(struct work_struct *work,
573 * The following wmb is paired with the implied mb in
574 * test_and_set_bit(PENDING) and ensures all updates to @work made
575 * here are visible to and precede any updates by the next PENDING
579 set_work_data(work, (unsigned long)cpu << WORK_OFFQ_CPU_SHIFT, 0);
582 static void clear_work_data(struct work_struct *work)
584 smp_wmb(); /* see set_work_cpu_and_clear_pending() */
585 set_work_data(work, WORK_STRUCT_NO_CPU, 0);
588 static struct cpu_workqueue_struct *get_work_cwq(struct work_struct *work)
590 unsigned long data = atomic_long_read(&work->data);
592 if (data & WORK_STRUCT_CWQ)
593 return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
598 static struct global_cwq *get_work_gcwq(struct work_struct *work)
600 unsigned long data = atomic_long_read(&work->data);
603 if (data & WORK_STRUCT_CWQ)
604 return ((struct cpu_workqueue_struct *)
605 (data & WORK_STRUCT_WQ_DATA_MASK))->pool->gcwq;
607 cpu = data >> WORK_OFFQ_CPU_SHIFT;
608 if (cpu == WORK_CPU_NONE)
611 BUG_ON(cpu >= nr_cpu_ids && cpu != WORK_CPU_UNBOUND);
612 return get_gcwq(cpu);
615 static void mark_work_canceling(struct work_struct *work)
617 struct global_cwq *gcwq = get_work_gcwq(work);
618 unsigned long cpu = gcwq ? gcwq->cpu : WORK_CPU_NONE;
620 set_work_data(work, (cpu << WORK_OFFQ_CPU_SHIFT) | WORK_OFFQ_CANCELING,
621 WORK_STRUCT_PENDING);
624 static bool work_is_canceling(struct work_struct *work)
626 unsigned long data = atomic_long_read(&work->data);
628 return !(data & WORK_STRUCT_CWQ) && (data & WORK_OFFQ_CANCELING);
632 * Policy functions. These define the policies on how the global worker
633 * pools are managed. Unless noted otherwise, these functions assume that
634 * they're being called with gcwq->lock held.
637 static bool __need_more_worker(struct worker_pool *pool)
639 return !atomic_read(get_pool_nr_running(pool));
643 * Need to wake up a worker? Called from anything but currently
646 * Note that, because unbound workers never contribute to nr_running, this
647 * function will always return %true for unbound gcwq as long as the
648 * worklist isn't empty.
650 static bool need_more_worker(struct worker_pool *pool)
652 return !list_empty(&pool->worklist) && __need_more_worker(pool);
655 /* Can I start working? Called from busy but !running workers. */
656 static bool may_start_working(struct worker_pool *pool)
658 return pool->nr_idle;
661 /* Do I need to keep working? Called from currently running workers. */
662 static bool keep_working(struct worker_pool *pool)
664 atomic_t *nr_running = get_pool_nr_running(pool);
666 return !list_empty(&pool->worklist) && atomic_read(nr_running) <= 1;
669 /* Do we need a new worker? Called from manager. */
670 static bool need_to_create_worker(struct worker_pool *pool)
672 return need_more_worker(pool) && !may_start_working(pool);
675 /* Do I need to be the manager? */
676 static bool need_to_manage_workers(struct worker_pool *pool)
678 return need_to_create_worker(pool) ||
679 (pool->flags & POOL_MANAGE_WORKERS);
682 /* Do we have too many workers and should some go away? */
683 static bool too_many_workers(struct worker_pool *pool)
685 bool managing = mutex_is_locked(&pool->manager_mutex);
686 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
687 int nr_busy = pool->nr_workers - nr_idle;
689 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
696 /* Return the first worker. Safe with preemption disabled */
697 static struct worker *first_worker(struct worker_pool *pool)
699 if (unlikely(list_empty(&pool->idle_list)))
702 return list_first_entry(&pool->idle_list, struct worker, entry);
706 * wake_up_worker - wake up an idle worker
707 * @pool: worker pool to wake worker from
709 * Wake up the first idle worker of @pool.
712 * spin_lock_irq(gcwq->lock).
714 static void wake_up_worker(struct worker_pool *pool)
716 struct worker *worker = first_worker(pool);
719 wake_up_process(worker->task);
723 * wq_worker_waking_up - a worker is waking up
724 * @task: task waking up
725 * @cpu: CPU @task is waking up to
727 * This function is called during try_to_wake_up() when a worker is
731 * spin_lock_irq(rq->lock)
733 void wq_worker_waking_up(struct task_struct *task, unsigned int cpu)
735 struct worker *worker = kthread_data(task);
737 if (!(worker->flags & WORKER_NOT_RUNNING))
738 atomic_inc(get_pool_nr_running(worker->pool));
742 * wq_worker_sleeping - a worker is going to sleep
743 * @task: task going to sleep
744 * @cpu: CPU in question, must be the current CPU number
746 * This function is called during schedule() when a busy worker is
747 * going to sleep. Worker on the same cpu can be woken up by
748 * returning pointer to its task.
751 * spin_lock_irq(rq->lock)
754 * Worker task on @cpu to wake up, %NULL if none.
756 struct task_struct *wq_worker_sleeping(struct task_struct *task,
759 struct worker *worker = kthread_data(task), *to_wakeup = NULL;
760 struct worker_pool *pool = worker->pool;
761 atomic_t *nr_running = get_pool_nr_running(pool);
763 if (worker->flags & WORKER_NOT_RUNNING)
766 /* this can only happen on the local cpu */
767 BUG_ON(cpu != raw_smp_processor_id());
770 * The counterpart of the following dec_and_test, implied mb,
771 * worklist not empty test sequence is in insert_work().
772 * Please read comment there.
774 * NOT_RUNNING is clear. This means that we're bound to and
775 * running on the local cpu w/ rq lock held and preemption
776 * disabled, which in turn means that none else could be
777 * manipulating idle_list, so dereferencing idle_list without gcwq
780 if (atomic_dec_and_test(nr_running) && !list_empty(&pool->worklist))
781 to_wakeup = first_worker(pool);
782 return to_wakeup ? to_wakeup->task : NULL;
786 * worker_set_flags - set worker flags and adjust nr_running accordingly
788 * @flags: flags to set
789 * @wakeup: wakeup an idle worker if necessary
791 * Set @flags in @worker->flags and adjust nr_running accordingly. If
792 * nr_running becomes zero and @wakeup is %true, an idle worker is
796 * spin_lock_irq(gcwq->lock)
798 static inline void worker_set_flags(struct worker *worker, unsigned int flags,
801 struct worker_pool *pool = worker->pool;
803 WARN_ON_ONCE(worker->task != current);
806 * If transitioning into NOT_RUNNING, adjust nr_running and
807 * wake up an idle worker as necessary if requested by
810 if ((flags & WORKER_NOT_RUNNING) &&
811 !(worker->flags & WORKER_NOT_RUNNING)) {
812 atomic_t *nr_running = get_pool_nr_running(pool);
815 if (atomic_dec_and_test(nr_running) &&
816 !list_empty(&pool->worklist))
817 wake_up_worker(pool);
819 atomic_dec(nr_running);
822 worker->flags |= flags;
826 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
828 * @flags: flags to clear
830 * Clear @flags in @worker->flags and adjust nr_running accordingly.
833 * spin_lock_irq(gcwq->lock)
835 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
837 struct worker_pool *pool = worker->pool;
838 unsigned int oflags = worker->flags;
840 WARN_ON_ONCE(worker->task != current);
842 worker->flags &= ~flags;
845 * If transitioning out of NOT_RUNNING, increment nr_running. Note
846 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
847 * of multiple flags, not a single flag.
849 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
850 if (!(worker->flags & WORKER_NOT_RUNNING))
851 atomic_inc(get_pool_nr_running(pool));
855 * busy_worker_head - return the busy hash head for a work
856 * @gcwq: gcwq of interest
857 * @work: work to be hashed
859 * Return hash head of @gcwq for @work.
862 * spin_lock_irq(gcwq->lock).
865 * Pointer to the hash head.
867 static struct hlist_head *busy_worker_head(struct global_cwq *gcwq,
868 struct work_struct *work)
870 const int base_shift = ilog2(sizeof(struct work_struct));
871 unsigned long v = (unsigned long)work;
873 /* simple shift and fold hash, do we need something better? */
875 v += v >> BUSY_WORKER_HASH_ORDER;
876 v &= BUSY_WORKER_HASH_MASK;
878 return &gcwq->busy_hash[v];
882 * __find_worker_executing_work - find worker which is executing a work
883 * @gcwq: gcwq of interest
884 * @bwh: hash head as returned by busy_worker_head()
885 * @work: work to find worker for
887 * Find a worker which is executing @work on @gcwq. @bwh should be
888 * the hash head obtained by calling busy_worker_head() with the same
892 * spin_lock_irq(gcwq->lock).
895 * Pointer to worker which is executing @work if found, NULL
898 static struct worker *__find_worker_executing_work(struct global_cwq *gcwq,
899 struct hlist_head *bwh,
900 struct work_struct *work)
902 struct worker *worker;
903 struct hlist_node *tmp;
905 hlist_for_each_entry(worker, tmp, bwh, hentry)
906 if (worker->current_work == work)
912 * find_worker_executing_work - find worker which is executing a work
913 * @gcwq: gcwq of interest
914 * @work: work to find worker for
916 * Find a worker which is executing @work on @gcwq. This function is
917 * identical to __find_worker_executing_work() except that this
918 * function calculates @bwh itself.
921 * spin_lock_irq(gcwq->lock).
924 * Pointer to worker which is executing @work if found, NULL
927 static struct worker *find_worker_executing_work(struct global_cwq *gcwq,
928 struct work_struct *work)
930 return __find_worker_executing_work(gcwq, busy_worker_head(gcwq, work),
935 * move_linked_works - move linked works to a list
936 * @work: start of series of works to be scheduled
937 * @head: target list to append @work to
938 * @nextp: out paramter for nested worklist walking
940 * Schedule linked works starting from @work to @head. Work series to
941 * be scheduled starts at @work and includes any consecutive work with
942 * WORK_STRUCT_LINKED set in its predecessor.
944 * If @nextp is not NULL, it's updated to point to the next work of
945 * the last scheduled work. This allows move_linked_works() to be
946 * nested inside outer list_for_each_entry_safe().
949 * spin_lock_irq(gcwq->lock).
951 static void move_linked_works(struct work_struct *work, struct list_head *head,
952 struct work_struct **nextp)
954 struct work_struct *n;
957 * Linked worklist will always end before the end of the list,
958 * use NULL for list head.
960 list_for_each_entry_safe_from(work, n, NULL, entry) {
961 list_move_tail(&work->entry, head);
962 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
967 * If we're already inside safe list traversal and have moved
968 * multiple works to the scheduled queue, the next position
969 * needs to be updated.
975 static void cwq_activate_first_delayed(struct cpu_workqueue_struct *cwq)
977 struct work_struct *work = list_first_entry(&cwq->delayed_works,
978 struct work_struct, entry);
980 trace_workqueue_activate_work(work);
981 move_linked_works(work, &cwq->pool->worklist, NULL);
982 __clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
987 * cwq_dec_nr_in_flight - decrement cwq's nr_in_flight
988 * @cwq: cwq of interest
989 * @color: color of work which left the queue
990 * @delayed: for a delayed work
992 * A work either has completed or is removed from pending queue,
993 * decrement nr_in_flight of its cwq and handle workqueue flushing.
996 * spin_lock_irq(gcwq->lock).
998 static void cwq_dec_nr_in_flight(struct cpu_workqueue_struct *cwq, int color,
1001 /* ignore uncolored works */
1002 if (color == WORK_NO_COLOR)
1005 cwq->nr_in_flight[color]--;
1009 if (!list_empty(&cwq->delayed_works)) {
1010 /* one down, submit a delayed one */
1011 if (cwq->nr_active < cwq->max_active)
1012 cwq_activate_first_delayed(cwq);
1016 /* is flush in progress and are we at the flushing tip? */
1017 if (likely(cwq->flush_color != color))
1020 /* are there still in-flight works? */
1021 if (cwq->nr_in_flight[color])
1024 /* this cwq is done, clear flush_color */
1025 cwq->flush_color = -1;
1028 * If this was the last cwq, wake up the first flusher. It
1029 * will handle the rest.
1031 if (atomic_dec_and_test(&cwq->wq->nr_cwqs_to_flush))
1032 complete(&cwq->wq->first_flusher->done);
1036 * try_to_grab_pending - steal work item from worklist and disable irq
1037 * @work: work item to steal
1038 * @is_dwork: @work is a delayed_work
1039 * @flags: place to store irq state
1041 * Try to grab PENDING bit of @work. This function can handle @work in any
1042 * stable state - idle, on timer or on worklist. Return values are
1044 * 1 if @work was pending and we successfully stole PENDING
1045 * 0 if @work was idle and we claimed PENDING
1046 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1047 * -ENOENT if someone else is canceling @work, this state may persist
1048 * for arbitrarily long
1050 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1051 * interrupted while holding PENDING and @work off queue, irq must be
1052 * disabled on entry. This, combined with delayed_work->timer being
1053 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1055 * On successful return, >= 0, irq is disabled and the caller is
1056 * responsible for releasing it using local_irq_restore(*@flags).
1058 * This function is safe to call from any context including IRQ handler.
1060 static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1061 unsigned long *flags)
1063 struct global_cwq *gcwq;
1065 WARN_ON_ONCE(in_irq());
1067 local_irq_save(*flags);
1069 /* try to steal the timer if it exists */
1071 struct delayed_work *dwork = to_delayed_work(work);
1074 * dwork->timer is irqsafe. If del_timer() fails, it's
1075 * guaranteed that the timer is not queued anywhere and not
1076 * running on the local CPU.
1078 if (likely(del_timer(&dwork->timer)))
1082 /* try to claim PENDING the normal way */
1083 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1087 * The queueing is in progress, or it is already queued. Try to
1088 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1090 gcwq = get_work_gcwq(work);
1094 spin_lock(&gcwq->lock);
1095 if (!list_empty(&work->entry)) {
1097 * This work is queued, but perhaps we locked the wrong gcwq.
1098 * In that case we must see the new value after rmb(), see
1099 * insert_work()->wmb().
1102 if (gcwq == get_work_gcwq(work)) {
1103 debug_work_deactivate(work);
1104 list_del_init(&work->entry);
1105 cwq_dec_nr_in_flight(get_work_cwq(work),
1106 get_work_color(work),
1107 *work_data_bits(work) & WORK_STRUCT_DELAYED);
1109 spin_unlock(&gcwq->lock);
1113 spin_unlock(&gcwq->lock);
1115 local_irq_restore(*flags);
1116 if (work_is_canceling(work))
1123 * insert_work - insert a work into gcwq
1124 * @cwq: cwq @work belongs to
1125 * @work: work to insert
1126 * @head: insertion point
1127 * @extra_flags: extra WORK_STRUCT_* flags to set
1129 * Insert @work which belongs to @cwq into @gcwq after @head.
1130 * @extra_flags is or'd to work_struct flags.
1133 * spin_lock_irq(gcwq->lock).
1135 static void insert_work(struct cpu_workqueue_struct *cwq,
1136 struct work_struct *work, struct list_head *head,
1137 unsigned int extra_flags)
1139 struct worker_pool *pool = cwq->pool;
1141 /* we own @work, set data and link */
1142 set_work_cwq(work, cwq, extra_flags);
1145 * Ensure that we get the right work->data if we see the
1146 * result of list_add() below, see try_to_grab_pending().
1150 list_add_tail(&work->entry, head);
1153 * Ensure either worker_sched_deactivated() sees the above
1154 * list_add_tail() or we see zero nr_running to avoid workers
1155 * lying around lazily while there are works to be processed.
1159 if (__need_more_worker(pool))
1160 wake_up_worker(pool);
1164 * Test whether @work is being queued from another work executing on the
1165 * same workqueue. This is rather expensive and should only be used from
1168 static bool is_chained_work(struct workqueue_struct *wq)
1170 unsigned long flags;
1173 for_each_gcwq_cpu(cpu) {
1174 struct global_cwq *gcwq = get_gcwq(cpu);
1175 struct worker *worker;
1176 struct hlist_node *pos;
1179 spin_lock_irqsave(&gcwq->lock, flags);
1180 for_each_busy_worker(worker, i, pos, gcwq) {
1181 if (worker->task != current)
1183 spin_unlock_irqrestore(&gcwq->lock, flags);
1185 * I'm @worker, no locking necessary. See if @work
1186 * is headed to the same workqueue.
1188 return worker->current_cwq->wq == wq;
1190 spin_unlock_irqrestore(&gcwq->lock, flags);
1195 static void __queue_work(unsigned int cpu, struct workqueue_struct *wq,
1196 struct work_struct *work)
1198 struct global_cwq *gcwq;
1199 struct cpu_workqueue_struct *cwq;
1200 struct list_head *worklist;
1201 unsigned int work_flags;
1202 unsigned int req_cpu = cpu;
1205 * While a work item is PENDING && off queue, a task trying to
1206 * steal the PENDING will busy-loop waiting for it to either get
1207 * queued or lose PENDING. Grabbing PENDING and queueing should
1208 * happen with IRQ disabled.
1210 WARN_ON_ONCE(!irqs_disabled());
1212 debug_work_activate(work);
1214 /* if dying, only works from the same workqueue are allowed */
1215 if (unlikely(wq->flags & WQ_DRAINING) &&
1216 WARN_ON_ONCE(!is_chained_work(wq)))
1219 /* determine gcwq to use */
1220 if (!(wq->flags & WQ_UNBOUND)) {
1221 struct global_cwq *last_gcwq;
1223 if (cpu == WORK_CPU_UNBOUND)
1224 cpu = raw_smp_processor_id();
1227 * It's multi cpu. If @work was previously on a different
1228 * cpu, it might still be running there, in which case the
1229 * work needs to be queued on that cpu to guarantee
1232 gcwq = get_gcwq(cpu);
1233 last_gcwq = get_work_gcwq(work);
1235 if (last_gcwq && last_gcwq != gcwq) {
1236 struct worker *worker;
1238 spin_lock(&last_gcwq->lock);
1240 worker = find_worker_executing_work(last_gcwq, work);
1242 if (worker && worker->current_cwq->wq == wq)
1245 /* meh... not running there, queue here */
1246 spin_unlock(&last_gcwq->lock);
1247 spin_lock(&gcwq->lock);
1250 spin_lock(&gcwq->lock);
1253 gcwq = get_gcwq(WORK_CPU_UNBOUND);
1254 spin_lock(&gcwq->lock);
1257 /* gcwq determined, get cwq and queue */
1258 cwq = get_cwq(gcwq->cpu, wq);
1259 trace_workqueue_queue_work(req_cpu, cwq, work);
1261 if (WARN_ON(!list_empty(&work->entry))) {
1262 spin_unlock(&gcwq->lock);
1266 cwq->nr_in_flight[cwq->work_color]++;
1267 work_flags = work_color_to_flags(cwq->work_color);
1269 if (likely(cwq->nr_active < cwq->max_active)) {
1270 trace_workqueue_activate_work(work);
1272 worklist = &cwq->pool->worklist;
1274 work_flags |= WORK_STRUCT_DELAYED;
1275 worklist = &cwq->delayed_works;
1278 insert_work(cwq, work, worklist, work_flags);
1280 spin_unlock(&gcwq->lock);
1284 * queue_work_on - queue work on specific cpu
1285 * @cpu: CPU number to execute work on
1286 * @wq: workqueue to use
1287 * @work: work to queue
1289 * Returns %false if @work was already on a queue, %true otherwise.
1291 * We queue the work to a specific CPU, the caller must ensure it
1294 bool queue_work_on(int cpu, struct workqueue_struct *wq,
1295 struct work_struct *work)
1298 unsigned long flags;
1300 local_irq_save(flags);
1302 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1303 __queue_work(cpu, wq, work);
1307 local_irq_restore(flags);
1310 EXPORT_SYMBOL_GPL(queue_work_on);
1313 * queue_work - queue work on a workqueue
1314 * @wq: workqueue to use
1315 * @work: work to queue
1317 * Returns %false if @work was already on a queue, %true otherwise.
1319 * We queue the work to the CPU on which it was submitted, but if the CPU dies
1320 * it can be processed by another CPU.
1322 bool queue_work(struct workqueue_struct *wq, struct work_struct *work)
1324 return queue_work_on(WORK_CPU_UNBOUND, wq, work);
1326 EXPORT_SYMBOL_GPL(queue_work);
1328 void delayed_work_timer_fn(unsigned long __data)
1330 struct delayed_work *dwork = (struct delayed_work *)__data;
1331 struct cpu_workqueue_struct *cwq = get_work_cwq(&dwork->work);
1333 /* should have been called from irqsafe timer with irq already off */
1334 __queue_work(dwork->cpu, cwq->wq, &dwork->work);
1336 EXPORT_SYMBOL_GPL(delayed_work_timer_fn);
1338 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
1339 struct delayed_work *dwork, unsigned long delay)
1341 struct timer_list *timer = &dwork->timer;
1342 struct work_struct *work = &dwork->work;
1345 WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
1346 timer->data != (unsigned long)dwork);
1347 BUG_ON(timer_pending(timer));
1348 BUG_ON(!list_empty(&work->entry));
1350 timer_stats_timer_set_start_info(&dwork->timer);
1353 * This stores cwq for the moment, for the timer_fn. Note that the
1354 * work's gcwq is preserved to allow reentrance detection for
1357 if (!(wq->flags & WQ_UNBOUND)) {
1358 struct global_cwq *gcwq = get_work_gcwq(work);
1361 * If we cannot get the last gcwq from @work directly,
1362 * select the last CPU such that it avoids unnecessarily
1363 * triggering non-reentrancy check in __queue_work().
1368 if (lcpu == WORK_CPU_UNBOUND)
1369 lcpu = raw_smp_processor_id();
1371 lcpu = WORK_CPU_UNBOUND;
1374 set_work_cwq(work, get_cwq(lcpu, wq), 0);
1377 timer->expires = jiffies + delay;
1379 if (unlikely(cpu != WORK_CPU_UNBOUND))
1380 add_timer_on(timer, cpu);
1386 * queue_delayed_work_on - queue work on specific CPU after delay
1387 * @cpu: CPU number to execute work on
1388 * @wq: workqueue to use
1389 * @dwork: work to queue
1390 * @delay: number of jiffies to wait before queueing
1392 * Returns %false if @work was already on a queue, %true otherwise. If
1393 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1396 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1397 struct delayed_work *dwork, unsigned long delay)
1399 struct work_struct *work = &dwork->work;
1401 unsigned long flags;
1404 return queue_work_on(cpu, wq, &dwork->work);
1406 /* read the comment in __queue_work() */
1407 local_irq_save(flags);
1409 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1410 __queue_delayed_work(cpu, wq, dwork, delay);
1414 local_irq_restore(flags);
1417 EXPORT_SYMBOL_GPL(queue_delayed_work_on);
1420 * queue_delayed_work - queue work on a workqueue after delay
1421 * @wq: workqueue to use
1422 * @dwork: delayable work to queue
1423 * @delay: number of jiffies to wait before queueing
1425 * Equivalent to queue_delayed_work_on() but tries to use the local CPU.
1427 bool queue_delayed_work(struct workqueue_struct *wq,
1428 struct delayed_work *dwork, unsigned long delay)
1430 return queue_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
1432 EXPORT_SYMBOL_GPL(queue_delayed_work);
1435 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1436 * @cpu: CPU number to execute work on
1437 * @wq: workqueue to use
1438 * @dwork: work to queue
1439 * @delay: number of jiffies to wait before queueing
1441 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1442 * modify @dwork's timer so that it expires after @delay. If @delay is
1443 * zero, @work is guaranteed to be scheduled immediately regardless of its
1446 * Returns %false if @dwork was idle and queued, %true if @dwork was
1447 * pending and its timer was modified.
1449 * This function is safe to call from any context including IRQ handler.
1450 * See try_to_grab_pending() for details.
1452 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
1453 struct delayed_work *dwork, unsigned long delay)
1455 unsigned long flags;
1459 ret = try_to_grab_pending(&dwork->work, true, &flags);
1460 } while (unlikely(ret == -EAGAIN));
1462 if (likely(ret >= 0)) {
1463 __queue_delayed_work(cpu, wq, dwork, delay);
1464 local_irq_restore(flags);
1467 /* -ENOENT from try_to_grab_pending() becomes %true */
1470 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
1473 * mod_delayed_work - modify delay of or queue a delayed work
1474 * @wq: workqueue to use
1475 * @dwork: work to queue
1476 * @delay: number of jiffies to wait before queueing
1478 * mod_delayed_work_on() on local CPU.
1480 bool mod_delayed_work(struct workqueue_struct *wq, struct delayed_work *dwork,
1481 unsigned long delay)
1483 return mod_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
1485 EXPORT_SYMBOL_GPL(mod_delayed_work);
1488 * worker_enter_idle - enter idle state
1489 * @worker: worker which is entering idle state
1491 * @worker is entering idle state. Update stats and idle timer if
1495 * spin_lock_irq(gcwq->lock).
1497 static void worker_enter_idle(struct worker *worker)
1499 struct worker_pool *pool = worker->pool;
1500 struct global_cwq *gcwq = pool->gcwq;
1502 BUG_ON(worker->flags & WORKER_IDLE);
1503 BUG_ON(!list_empty(&worker->entry) &&
1504 (worker->hentry.next || worker->hentry.pprev));
1506 /* can't use worker_set_flags(), also called from start_worker() */
1507 worker->flags |= WORKER_IDLE;
1509 worker->last_active = jiffies;
1511 /* idle_list is LIFO */
1512 list_add(&worker->entry, &pool->idle_list);
1514 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1515 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1518 * Sanity check nr_running. Because gcwq_unbind_fn() releases
1519 * gcwq->lock between setting %WORKER_UNBOUND and zapping
1520 * nr_running, the warning may trigger spuriously. Check iff
1521 * unbind is not in progress.
1523 WARN_ON_ONCE(!(gcwq->flags & GCWQ_DISASSOCIATED) &&
1524 pool->nr_workers == pool->nr_idle &&
1525 atomic_read(get_pool_nr_running(pool)));
1529 * worker_leave_idle - leave idle state
1530 * @worker: worker which is leaving idle state
1532 * @worker is leaving idle state. Update stats.
1535 * spin_lock_irq(gcwq->lock).
1537 static void worker_leave_idle(struct worker *worker)
1539 struct worker_pool *pool = worker->pool;
1541 BUG_ON(!(worker->flags & WORKER_IDLE));
1542 worker_clr_flags(worker, WORKER_IDLE);
1544 list_del_init(&worker->entry);
1548 * worker_maybe_bind_and_lock - bind worker to its cpu if possible and lock gcwq
1551 * Works which are scheduled while the cpu is online must at least be
1552 * scheduled to a worker which is bound to the cpu so that if they are
1553 * flushed from cpu callbacks while cpu is going down, they are
1554 * guaranteed to execute on the cpu.
1556 * This function is to be used by rogue workers and rescuers to bind
1557 * themselves to the target cpu and may race with cpu going down or
1558 * coming online. kthread_bind() can't be used because it may put the
1559 * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1560 * verbatim as it's best effort and blocking and gcwq may be
1561 * [dis]associated in the meantime.
1563 * This function tries set_cpus_allowed() and locks gcwq and verifies the
1564 * binding against %GCWQ_DISASSOCIATED which is set during
1565 * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
1566 * enters idle state or fetches works without dropping lock, it can
1567 * guarantee the scheduling requirement described in the first paragraph.
1570 * Might sleep. Called without any lock but returns with gcwq->lock
1574 * %true if the associated gcwq is online (@worker is successfully
1575 * bound), %false if offline.
1577 static bool worker_maybe_bind_and_lock(struct worker *worker)
1578 __acquires(&gcwq->lock)
1580 struct global_cwq *gcwq = worker->pool->gcwq;
1581 struct task_struct *task = worker->task;
1585 * The following call may fail, succeed or succeed
1586 * without actually migrating the task to the cpu if
1587 * it races with cpu hotunplug operation. Verify
1588 * against GCWQ_DISASSOCIATED.
1590 if (!(gcwq->flags & GCWQ_DISASSOCIATED))
1591 set_cpus_allowed_ptr(task, get_cpu_mask(gcwq->cpu));
1593 spin_lock_irq(&gcwq->lock);
1594 if (gcwq->flags & GCWQ_DISASSOCIATED)
1596 if (task_cpu(task) == gcwq->cpu &&
1597 cpumask_equal(¤t->cpus_allowed,
1598 get_cpu_mask(gcwq->cpu)))
1600 spin_unlock_irq(&gcwq->lock);
1603 * We've raced with CPU hot[un]plug. Give it a breather
1604 * and retry migration. cond_resched() is required here;
1605 * otherwise, we might deadlock against cpu_stop trying to
1606 * bring down the CPU on non-preemptive kernel.
1613 struct idle_rebind {
1614 int cnt; /* # workers to be rebound */
1615 struct completion done; /* all workers rebound */
1619 * Rebind an idle @worker to its CPU. During CPU onlining, this has to
1620 * happen synchronously for idle workers. worker_thread() will test
1621 * %WORKER_REBIND before leaving idle and call this function.
1623 static void idle_worker_rebind(struct worker *worker)
1625 struct global_cwq *gcwq = worker->pool->gcwq;
1627 /* CPU must be online at this point */
1628 WARN_ON(!worker_maybe_bind_and_lock(worker));
1629 if (!--worker->idle_rebind->cnt)
1630 complete(&worker->idle_rebind->done);
1631 spin_unlock_irq(&worker->pool->gcwq->lock);
1633 /* we did our part, wait for rebind_workers() to finish up */
1634 wait_event(gcwq->rebind_hold, !(worker->flags & WORKER_REBIND));
1638 * Function for @worker->rebind.work used to rebind unbound busy workers to
1639 * the associated cpu which is coming back online. This is scheduled by
1640 * cpu up but can race with other cpu hotplug operations and may be
1641 * executed twice without intervening cpu down.
1643 static void busy_worker_rebind_fn(struct work_struct *work)
1645 struct worker *worker = container_of(work, struct worker, rebind_work);
1646 struct global_cwq *gcwq = worker->pool->gcwq;
1648 if (worker_maybe_bind_and_lock(worker))
1649 worker_clr_flags(worker, WORKER_REBIND);
1651 spin_unlock_irq(&gcwq->lock);
1655 * rebind_workers - rebind all workers of a gcwq to the associated CPU
1656 * @gcwq: gcwq of interest
1658 * @gcwq->cpu is coming online. Rebind all workers to the CPU. Rebinding
1659 * is different for idle and busy ones.
1661 * The idle ones should be rebound synchronously and idle rebinding should
1662 * be complete before any worker starts executing work items with
1663 * concurrency management enabled; otherwise, scheduler may oops trying to
1664 * wake up non-local idle worker from wq_worker_sleeping().
1666 * This is achieved by repeatedly requesting rebinding until all idle
1667 * workers are known to have been rebound under @gcwq->lock and holding all
1668 * idle workers from becoming busy until idle rebinding is complete.
1670 * Once idle workers are rebound, busy workers can be rebound as they
1671 * finish executing their current work items. Queueing the rebind work at
1672 * the head of their scheduled lists is enough. Note that nr_running will
1673 * be properbly bumped as busy workers rebind.
1675 * On return, all workers are guaranteed to either be bound or have rebind
1676 * work item scheduled.
1678 static void rebind_workers(struct global_cwq *gcwq)
1679 __releases(&gcwq->lock) __acquires(&gcwq->lock)
1681 struct idle_rebind idle_rebind;
1682 struct worker_pool *pool;
1683 struct worker *worker;
1684 struct hlist_node *pos;
1687 lockdep_assert_held(&gcwq->lock);
1689 for_each_worker_pool(pool, gcwq)
1690 lockdep_assert_held(&pool->manager_mutex);
1693 * Rebind idle workers. Interlocked both ways. We wait for
1694 * workers to rebind via @idle_rebind.done. Workers will wait for
1695 * us to finish up by watching %WORKER_REBIND.
1697 init_completion(&idle_rebind.done);
1699 idle_rebind.cnt = 1;
1700 INIT_COMPLETION(idle_rebind.done);
1702 /* set REBIND and kick idle ones, we'll wait for these later */
1703 for_each_worker_pool(pool, gcwq) {
1704 list_for_each_entry(worker, &pool->idle_list, entry) {
1705 if (worker->flags & WORKER_REBIND)
1708 /* morph UNBOUND to REBIND */
1709 worker->flags &= ~WORKER_UNBOUND;
1710 worker->flags |= WORKER_REBIND;
1713 worker->idle_rebind = &idle_rebind;
1715 /* worker_thread() will call idle_worker_rebind() */
1716 wake_up_process(worker->task);
1720 if (--idle_rebind.cnt) {
1721 spin_unlock_irq(&gcwq->lock);
1722 wait_for_completion(&idle_rebind.done);
1723 spin_lock_irq(&gcwq->lock);
1724 /* busy ones might have become idle while waiting, retry */
1729 * All idle workers are rebound and waiting for %WORKER_REBIND to
1730 * be cleared inside idle_worker_rebind(). Clear and release.
1731 * Clearing %WORKER_REBIND from this foreign context is safe
1732 * because these workers are still guaranteed to be idle.
1734 for_each_worker_pool(pool, gcwq)
1735 list_for_each_entry(worker, &pool->idle_list, entry)
1736 worker->flags &= ~WORKER_REBIND;
1738 wake_up_all(&gcwq->rebind_hold);
1740 /* rebind busy workers */
1741 for_each_busy_worker(worker, i, pos, gcwq) {
1742 struct work_struct *rebind_work = &worker->rebind_work;
1743 struct workqueue_struct *wq;
1745 /* morph UNBOUND to REBIND */
1746 worker->flags &= ~WORKER_UNBOUND;
1747 worker->flags |= WORKER_REBIND;
1749 if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
1750 work_data_bits(rebind_work)))
1753 debug_work_activate(rebind_work);
1756 * wq doesn't really matter but let's keep @worker->pool
1757 * and @cwq->pool consistent for sanity.
1759 if (worker_pool_pri(worker->pool))
1760 wq = system_highpri_wq;
1764 insert_work(get_cwq(gcwq->cpu, wq), rebind_work,
1765 worker->scheduled.next,
1766 work_color_to_flags(WORK_NO_COLOR));
1770 static struct worker *alloc_worker(void)
1772 struct worker *worker;
1774 worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1776 INIT_LIST_HEAD(&worker->entry);
1777 INIT_LIST_HEAD(&worker->scheduled);
1778 INIT_WORK(&worker->rebind_work, busy_worker_rebind_fn);
1779 /* on creation a worker is in !idle && prep state */
1780 worker->flags = WORKER_PREP;
1786 * create_worker - create a new workqueue worker
1787 * @pool: pool the new worker will belong to
1789 * Create a new worker which is bound to @pool. The returned worker
1790 * can be started by calling start_worker() or destroyed using
1794 * Might sleep. Does GFP_KERNEL allocations.
1797 * Pointer to the newly created worker.
1799 static struct worker *create_worker(struct worker_pool *pool)
1801 struct global_cwq *gcwq = pool->gcwq;
1802 const char *pri = worker_pool_pri(pool) ? "H" : "";
1803 struct worker *worker = NULL;
1806 spin_lock_irq(&gcwq->lock);
1807 while (ida_get_new(&pool->worker_ida, &id)) {
1808 spin_unlock_irq(&gcwq->lock);
1809 if (!ida_pre_get(&pool->worker_ida, GFP_KERNEL))
1811 spin_lock_irq(&gcwq->lock);
1813 spin_unlock_irq(&gcwq->lock);
1815 worker = alloc_worker();
1819 worker->pool = pool;
1822 if (gcwq->cpu != WORK_CPU_UNBOUND)
1823 worker->task = kthread_create_on_node(worker_thread,
1824 worker, cpu_to_node(gcwq->cpu),
1825 "kworker/%u:%d%s", gcwq->cpu, id, pri);
1827 worker->task = kthread_create(worker_thread, worker,
1828 "kworker/u:%d%s", id, pri);
1829 if (IS_ERR(worker->task))
1832 if (worker_pool_pri(pool))
1833 set_user_nice(worker->task, HIGHPRI_NICE_LEVEL);
1836 * Determine CPU binding of the new worker depending on
1837 * %GCWQ_DISASSOCIATED. The caller is responsible for ensuring the
1838 * flag remains stable across this function. See the comments
1839 * above the flag definition for details.
1841 * As an unbound worker may later become a regular one if CPU comes
1842 * online, make sure every worker has %PF_THREAD_BOUND set.
1844 if (!(gcwq->flags & GCWQ_DISASSOCIATED)) {
1845 kthread_bind(worker->task, gcwq->cpu);
1847 worker->task->flags |= PF_THREAD_BOUND;
1848 worker->flags |= WORKER_UNBOUND;
1854 spin_lock_irq(&gcwq->lock);
1855 ida_remove(&pool->worker_ida, id);
1856 spin_unlock_irq(&gcwq->lock);
1863 * start_worker - start a newly created worker
1864 * @worker: worker to start
1866 * Make the gcwq aware of @worker and start it.
1869 * spin_lock_irq(gcwq->lock).
1871 static void start_worker(struct worker *worker)
1873 worker->flags |= WORKER_STARTED;
1874 worker->pool->nr_workers++;
1875 worker_enter_idle(worker);
1876 wake_up_process(worker->task);
1880 * destroy_worker - destroy a workqueue worker
1881 * @worker: worker to be destroyed
1883 * Destroy @worker and adjust @gcwq stats accordingly.
1886 * spin_lock_irq(gcwq->lock) which is released and regrabbed.
1888 static void destroy_worker(struct worker *worker)
1890 struct worker_pool *pool = worker->pool;
1891 struct global_cwq *gcwq = pool->gcwq;
1892 int id = worker->id;
1894 /* sanity check frenzy */
1895 BUG_ON(worker->current_work);
1896 BUG_ON(!list_empty(&worker->scheduled));
1898 if (worker->flags & WORKER_STARTED)
1900 if (worker->flags & WORKER_IDLE)
1903 list_del_init(&worker->entry);
1904 worker->flags |= WORKER_DIE;
1906 spin_unlock_irq(&gcwq->lock);
1908 kthread_stop(worker->task);
1911 spin_lock_irq(&gcwq->lock);
1912 ida_remove(&pool->worker_ida, id);
1915 static void idle_worker_timeout(unsigned long __pool)
1917 struct worker_pool *pool = (void *)__pool;
1918 struct global_cwq *gcwq = pool->gcwq;
1920 spin_lock_irq(&gcwq->lock);
1922 if (too_many_workers(pool)) {
1923 struct worker *worker;
1924 unsigned long expires;
1926 /* idle_list is kept in LIFO order, check the last one */
1927 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1928 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1930 if (time_before(jiffies, expires))
1931 mod_timer(&pool->idle_timer, expires);
1933 /* it's been idle for too long, wake up manager */
1934 pool->flags |= POOL_MANAGE_WORKERS;
1935 wake_up_worker(pool);
1939 spin_unlock_irq(&gcwq->lock);
1942 static bool send_mayday(struct work_struct *work)
1944 struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1945 struct workqueue_struct *wq = cwq->wq;
1948 if (!(wq->flags & WQ_RESCUER))
1951 /* mayday mayday mayday */
1952 cpu = cwq->pool->gcwq->cpu;
1953 /* WORK_CPU_UNBOUND can't be set in cpumask, use cpu 0 instead */
1954 if (cpu == WORK_CPU_UNBOUND)
1956 if (!mayday_test_and_set_cpu(cpu, wq->mayday_mask))
1957 wake_up_process(wq->rescuer->task);
1961 static void gcwq_mayday_timeout(unsigned long __pool)
1963 struct worker_pool *pool = (void *)__pool;
1964 struct global_cwq *gcwq = pool->gcwq;
1965 struct work_struct *work;
1967 spin_lock_irq(&gcwq->lock);
1969 if (need_to_create_worker(pool)) {
1971 * We've been trying to create a new worker but
1972 * haven't been successful. We might be hitting an
1973 * allocation deadlock. Send distress signals to
1976 list_for_each_entry(work, &pool->worklist, entry)
1980 spin_unlock_irq(&gcwq->lock);
1982 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1986 * maybe_create_worker - create a new worker if necessary
1987 * @pool: pool to create a new worker for
1989 * Create a new worker for @pool if necessary. @pool is guaranteed to
1990 * have at least one idle worker on return from this function. If
1991 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1992 * sent to all rescuers with works scheduled on @pool to resolve
1993 * possible allocation deadlock.
1995 * On return, need_to_create_worker() is guaranteed to be false and
1996 * may_start_working() true.
1999 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2000 * multiple times. Does GFP_KERNEL allocations. Called only from
2004 * false if no action was taken and gcwq->lock stayed locked, true
2007 static bool maybe_create_worker(struct worker_pool *pool)
2008 __releases(&gcwq->lock)
2009 __acquires(&gcwq->lock)
2011 struct global_cwq *gcwq = pool->gcwq;
2013 if (!need_to_create_worker(pool))
2016 spin_unlock_irq(&gcwq->lock);
2018 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
2019 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
2022 struct worker *worker;
2024 worker = create_worker(pool);
2026 del_timer_sync(&pool->mayday_timer);
2027 spin_lock_irq(&gcwq->lock);
2028 start_worker(worker);
2029 BUG_ON(need_to_create_worker(pool));
2033 if (!need_to_create_worker(pool))
2036 __set_current_state(TASK_INTERRUPTIBLE);
2037 schedule_timeout(CREATE_COOLDOWN);
2039 if (!need_to_create_worker(pool))
2043 del_timer_sync(&pool->mayday_timer);
2044 spin_lock_irq(&gcwq->lock);
2045 if (need_to_create_worker(pool))
2051 * maybe_destroy_worker - destroy workers which have been idle for a while
2052 * @pool: pool to destroy workers for
2054 * Destroy @pool workers which have been idle for longer than
2055 * IDLE_WORKER_TIMEOUT.
2058 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2059 * multiple times. Called only from manager.
2062 * false if no action was taken and gcwq->lock stayed locked, true
2065 static bool maybe_destroy_workers(struct worker_pool *pool)
2069 while (too_many_workers(pool)) {
2070 struct worker *worker;
2071 unsigned long expires;
2073 worker = list_entry(pool->idle_list.prev, struct worker, entry);
2074 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2076 if (time_before(jiffies, expires)) {
2077 mod_timer(&pool->idle_timer, expires);
2081 destroy_worker(worker);
2089 * manage_workers - manage worker pool
2092 * Assume the manager role and manage gcwq worker pool @worker belongs
2093 * to. At any given time, there can be only zero or one manager per
2094 * gcwq. The exclusion is handled automatically by this function.
2096 * The caller can safely start processing works on false return. On
2097 * true return, it's guaranteed that need_to_create_worker() is false
2098 * and may_start_working() is true.
2101 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2102 * multiple times. Does GFP_KERNEL allocations.
2105 * false if no action was taken and gcwq->lock stayed locked, true if
2106 * some action was taken.
2108 static bool manage_workers(struct worker *worker)
2110 struct worker_pool *pool = worker->pool;
2113 if (!mutex_trylock(&pool->manager_mutex))
2116 pool->flags &= ~POOL_MANAGE_WORKERS;
2119 * Destroy and then create so that may_start_working() is true
2122 ret |= maybe_destroy_workers(pool);
2123 ret |= maybe_create_worker(pool);
2125 mutex_unlock(&pool->manager_mutex);
2130 * process_one_work - process single work
2132 * @work: work to process
2134 * Process @work. This function contains all the logics necessary to
2135 * process a single work including synchronization against and
2136 * interaction with other workers on the same cpu, queueing and
2137 * flushing. As long as context requirement is met, any worker can
2138 * call this function to process a work.
2141 * spin_lock_irq(gcwq->lock) which is released and regrabbed.
2143 static void process_one_work(struct worker *worker, struct work_struct *work)
2144 __releases(&gcwq->lock)
2145 __acquires(&gcwq->lock)
2147 struct cpu_workqueue_struct *cwq = get_work_cwq(work);
2148 struct worker_pool *pool = worker->pool;
2149 struct global_cwq *gcwq = pool->gcwq;
2150 struct hlist_head *bwh = busy_worker_head(gcwq, work);
2151 bool cpu_intensive = cwq->wq->flags & WQ_CPU_INTENSIVE;
2152 work_func_t f = work->func;
2154 struct worker *collision;
2155 #ifdef CONFIG_LOCKDEP
2157 * It is permissible to free the struct work_struct from
2158 * inside the function that is called from it, this we need to
2159 * take into account for lockdep too. To avoid bogus "held
2160 * lock freed" warnings as well as problems when looking into
2161 * work->lockdep_map, make a copy and use that here.
2163 struct lockdep_map lockdep_map;
2165 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
2168 * Ensure we're on the correct CPU. DISASSOCIATED test is
2169 * necessary to avoid spurious warnings from rescuers servicing the
2170 * unbound or a disassociated gcwq.
2172 WARN_ON_ONCE(!(worker->flags & (WORKER_UNBOUND | WORKER_REBIND)) &&
2173 !(gcwq->flags & GCWQ_DISASSOCIATED) &&
2174 raw_smp_processor_id() != gcwq->cpu);
2177 * A single work shouldn't be executed concurrently by
2178 * multiple workers on a single cpu. Check whether anyone is
2179 * already processing the work. If so, defer the work to the
2180 * currently executing one.
2182 collision = __find_worker_executing_work(gcwq, bwh, work);
2183 if (unlikely(collision)) {
2184 move_linked_works(work, &collision->scheduled, NULL);
2188 /* claim and dequeue */
2189 debug_work_deactivate(work);
2190 hlist_add_head(&worker->hentry, bwh);
2191 worker->current_work = work;
2192 worker->current_cwq = cwq;
2193 work_color = get_work_color(work);
2195 list_del_init(&work->entry);
2198 * CPU intensive works don't participate in concurrency
2199 * management. They're the scheduler's responsibility.
2201 if (unlikely(cpu_intensive))
2202 worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
2205 * Unbound gcwq isn't concurrency managed and work items should be
2206 * executed ASAP. Wake up another worker if necessary.
2208 if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
2209 wake_up_worker(pool);
2212 * Record the last CPU and clear PENDING which should be the last
2213 * update to @work. Also, do this inside @gcwq->lock so that
2214 * PENDING and queued state changes happen together while IRQ is
2217 set_work_cpu_and_clear_pending(work, gcwq->cpu);
2219 spin_unlock_irq(&gcwq->lock);
2221 lock_map_acquire_read(&cwq->wq->lockdep_map);
2222 lock_map_acquire(&lockdep_map);
2223 trace_workqueue_execute_start(work);
2226 * While we must be careful to not use "work" after this, the trace
2227 * point will only record its address.
2229 trace_workqueue_execute_end(work);
2230 lock_map_release(&lockdep_map);
2231 lock_map_release(&cwq->wq->lockdep_map);
2233 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2234 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2235 " last function: %pf\n",
2236 current->comm, preempt_count(), task_pid_nr(current), f);
2237 debug_show_held_locks(current);
2241 spin_lock_irq(&gcwq->lock);
2243 /* clear cpu intensive status */
2244 if (unlikely(cpu_intensive))
2245 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2247 /* we're done with it, release */
2248 hlist_del_init(&worker->hentry);
2249 worker->current_work = NULL;
2250 worker->current_cwq = NULL;
2251 cwq_dec_nr_in_flight(cwq, work_color, false);
2255 * process_scheduled_works - process scheduled works
2258 * Process all scheduled works. Please note that the scheduled list
2259 * may change while processing a work, so this function repeatedly
2260 * fetches a work from the top and executes it.
2263 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2266 static void process_scheduled_works(struct worker *worker)
2268 while (!list_empty(&worker->scheduled)) {
2269 struct work_struct *work = list_first_entry(&worker->scheduled,
2270 struct work_struct, entry);
2271 process_one_work(worker, work);
2276 * worker_thread - the worker thread function
2279 * The gcwq worker thread function. There's a single dynamic pool of
2280 * these per each cpu. These workers process all works regardless of
2281 * their specific target workqueue. The only exception is works which
2282 * belong to workqueues with a rescuer which will be explained in
2285 static int worker_thread(void *__worker)
2287 struct worker *worker = __worker;
2288 struct worker_pool *pool = worker->pool;
2289 struct global_cwq *gcwq = pool->gcwq;
2291 /* tell the scheduler that this is a workqueue worker */
2292 worker->task->flags |= PF_WQ_WORKER;
2294 spin_lock_irq(&gcwq->lock);
2297 * DIE can be set only while idle and REBIND set while busy has
2298 * @worker->rebind_work scheduled. Checking here is enough.
2300 if (unlikely(worker->flags & (WORKER_REBIND | WORKER_DIE))) {
2301 spin_unlock_irq(&gcwq->lock);
2303 if (worker->flags & WORKER_DIE) {
2304 worker->task->flags &= ~PF_WQ_WORKER;
2308 idle_worker_rebind(worker);
2312 worker_leave_idle(worker);
2314 /* no more worker necessary? */
2315 if (!need_more_worker(pool))
2318 /* do we need to manage? */
2319 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2323 * ->scheduled list can only be filled while a worker is
2324 * preparing to process a work or actually processing it.
2325 * Make sure nobody diddled with it while I was sleeping.
2327 BUG_ON(!list_empty(&worker->scheduled));
2330 * When control reaches this point, we're guaranteed to have
2331 * at least one idle worker or that someone else has already
2332 * assumed the manager role.
2334 worker_clr_flags(worker, WORKER_PREP);
2337 struct work_struct *work =
2338 list_first_entry(&pool->worklist,
2339 struct work_struct, entry);
2341 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2342 /* optimization path, not strictly necessary */
2343 process_one_work(worker, work);
2344 if (unlikely(!list_empty(&worker->scheduled)))
2345 process_scheduled_works(worker);
2347 move_linked_works(work, &worker->scheduled, NULL);
2348 process_scheduled_works(worker);
2350 } while (keep_working(pool));
2352 worker_set_flags(worker, WORKER_PREP, false);
2354 if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
2358 * gcwq->lock is held and there's no work to process and no
2359 * need to manage, sleep. Workers are woken up only while
2360 * holding gcwq->lock or from local cpu, so setting the
2361 * current state before releasing gcwq->lock is enough to
2362 * prevent losing any event.
2364 worker_enter_idle(worker);
2365 __set_current_state(TASK_INTERRUPTIBLE);
2366 spin_unlock_irq(&gcwq->lock);
2372 * rescuer_thread - the rescuer thread function
2373 * @__wq: the associated workqueue
2375 * Workqueue rescuer thread function. There's one rescuer for each
2376 * workqueue which has WQ_RESCUER set.
2378 * Regular work processing on a gcwq may block trying to create a new
2379 * worker which uses GFP_KERNEL allocation which has slight chance of
2380 * developing into deadlock if some works currently on the same queue
2381 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2382 * the problem rescuer solves.
2384 * When such condition is possible, the gcwq summons rescuers of all
2385 * workqueues which have works queued on the gcwq and let them process
2386 * those works so that forward progress can be guaranteed.
2388 * This should happen rarely.
2390 static int rescuer_thread(void *__wq)
2392 struct workqueue_struct *wq = __wq;
2393 struct worker *rescuer = wq->rescuer;
2394 struct list_head *scheduled = &rescuer->scheduled;
2395 bool is_unbound = wq->flags & WQ_UNBOUND;
2398 set_user_nice(current, RESCUER_NICE_LEVEL);
2400 set_current_state(TASK_INTERRUPTIBLE);
2402 if (kthread_should_stop())
2406 * See whether any cpu is asking for help. Unbounded
2407 * workqueues use cpu 0 in mayday_mask for CPU_UNBOUND.
2409 for_each_mayday_cpu(cpu, wq->mayday_mask) {
2410 unsigned int tcpu = is_unbound ? WORK_CPU_UNBOUND : cpu;
2411 struct cpu_workqueue_struct *cwq = get_cwq(tcpu, wq);
2412 struct worker_pool *pool = cwq->pool;
2413 struct global_cwq *gcwq = pool->gcwq;
2414 struct work_struct *work, *n;
2416 __set_current_state(TASK_RUNNING);
2417 mayday_clear_cpu(cpu, wq->mayday_mask);
2419 /* migrate to the target cpu if possible */
2420 rescuer->pool = pool;
2421 worker_maybe_bind_and_lock(rescuer);
2424 * Slurp in all works issued via this workqueue and
2427 BUG_ON(!list_empty(&rescuer->scheduled));
2428 list_for_each_entry_safe(work, n, &pool->worklist, entry)
2429 if (get_work_cwq(work) == cwq)
2430 move_linked_works(work, scheduled, &n);
2432 process_scheduled_works(rescuer);
2435 * Leave this gcwq. If keep_working() is %true, notify a
2436 * regular worker; otherwise, we end up with 0 concurrency
2437 * and stalling the execution.
2439 if (keep_working(pool))
2440 wake_up_worker(pool);
2442 spin_unlock_irq(&gcwq->lock);
2450 struct work_struct work;
2451 struct completion done;
2454 static void wq_barrier_func(struct work_struct *work)
2456 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2457 complete(&barr->done);
2461 * insert_wq_barrier - insert a barrier work
2462 * @cwq: cwq to insert barrier into
2463 * @barr: wq_barrier to insert
2464 * @target: target work to attach @barr to
2465 * @worker: worker currently executing @target, NULL if @target is not executing
2467 * @barr is linked to @target such that @barr is completed only after
2468 * @target finishes execution. Please note that the ordering
2469 * guarantee is observed only with respect to @target and on the local
2472 * Currently, a queued barrier can't be canceled. This is because
2473 * try_to_grab_pending() can't determine whether the work to be
2474 * grabbed is at the head of the queue and thus can't clear LINKED
2475 * flag of the previous work while there must be a valid next work
2476 * after a work with LINKED flag set.
2478 * Note that when @worker is non-NULL, @target may be modified
2479 * underneath us, so we can't reliably determine cwq from @target.
2482 * spin_lock_irq(gcwq->lock).
2484 static void insert_wq_barrier(struct cpu_workqueue_struct *cwq,
2485 struct wq_barrier *barr,
2486 struct work_struct *target, struct worker *worker)
2488 struct list_head *head;
2489 unsigned int linked = 0;
2492 * debugobject calls are safe here even with gcwq->lock locked
2493 * as we know for sure that this will not trigger any of the
2494 * checks and call back into the fixup functions where we
2497 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2498 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2499 init_completion(&barr->done);
2502 * If @target is currently being executed, schedule the
2503 * barrier to the worker; otherwise, put it after @target.
2506 head = worker->scheduled.next;
2508 unsigned long *bits = work_data_bits(target);
2510 head = target->entry.next;
2511 /* there can already be other linked works, inherit and set */
2512 linked = *bits & WORK_STRUCT_LINKED;
2513 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2516 debug_work_activate(&barr->work);
2517 insert_work(cwq, &barr->work, head,
2518 work_color_to_flags(WORK_NO_COLOR) | linked);
2522 * flush_workqueue_prep_cwqs - prepare cwqs for workqueue flushing
2523 * @wq: workqueue being flushed
2524 * @flush_color: new flush color, < 0 for no-op
2525 * @work_color: new work color, < 0 for no-op
2527 * Prepare cwqs for workqueue flushing.
2529 * If @flush_color is non-negative, flush_color on all cwqs should be
2530 * -1. If no cwq has in-flight commands at the specified color, all
2531 * cwq->flush_color's stay at -1 and %false is returned. If any cwq
2532 * has in flight commands, its cwq->flush_color is set to
2533 * @flush_color, @wq->nr_cwqs_to_flush is updated accordingly, cwq
2534 * wakeup logic is armed and %true is returned.
2536 * The caller should have initialized @wq->first_flusher prior to
2537 * calling this function with non-negative @flush_color. If
2538 * @flush_color is negative, no flush color update is done and %false
2541 * If @work_color is non-negative, all cwqs should have the same
2542 * work_color which is previous to @work_color and all will be
2543 * advanced to @work_color.
2546 * mutex_lock(wq->flush_mutex).
2549 * %true if @flush_color >= 0 and there's something to flush. %false
2552 static bool flush_workqueue_prep_cwqs(struct workqueue_struct *wq,
2553 int flush_color, int work_color)
2558 if (flush_color >= 0) {
2559 BUG_ON(atomic_read(&wq->nr_cwqs_to_flush));
2560 atomic_set(&wq->nr_cwqs_to_flush, 1);
2563 for_each_cwq_cpu(cpu, wq) {
2564 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2565 struct global_cwq *gcwq = cwq->pool->gcwq;
2567 spin_lock_irq(&gcwq->lock);
2569 if (flush_color >= 0) {
2570 BUG_ON(cwq->flush_color != -1);
2572 if (cwq->nr_in_flight[flush_color]) {
2573 cwq->flush_color = flush_color;
2574 atomic_inc(&wq->nr_cwqs_to_flush);
2579 if (work_color >= 0) {
2580 BUG_ON(work_color != work_next_color(cwq->work_color));
2581 cwq->work_color = work_color;
2584 spin_unlock_irq(&gcwq->lock);
2587 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_cwqs_to_flush))
2588 complete(&wq->first_flusher->done);
2594 * flush_workqueue - ensure that any scheduled work has run to completion.
2595 * @wq: workqueue to flush
2597 * Forces execution of the workqueue and blocks until its completion.
2598 * This is typically used in driver shutdown handlers.
2600 * We sleep until all works which were queued on entry have been handled,
2601 * but we are not livelocked by new incoming ones.
2603 void flush_workqueue(struct workqueue_struct *wq)
2605 struct wq_flusher this_flusher = {
2606 .list = LIST_HEAD_INIT(this_flusher.list),
2608 .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
2612 lock_map_acquire(&wq->lockdep_map);
2613 lock_map_release(&wq->lockdep_map);
2615 mutex_lock(&wq->flush_mutex);
2618 * Start-to-wait phase
2620 next_color = work_next_color(wq->work_color);
2622 if (next_color != wq->flush_color) {
2624 * Color space is not full. The current work_color
2625 * becomes our flush_color and work_color is advanced
2628 BUG_ON(!list_empty(&wq->flusher_overflow));
2629 this_flusher.flush_color = wq->work_color;
2630 wq->work_color = next_color;
2632 if (!wq->first_flusher) {
2633 /* no flush in progress, become the first flusher */
2634 BUG_ON(wq->flush_color != this_flusher.flush_color);
2636 wq->first_flusher = &this_flusher;
2638 if (!flush_workqueue_prep_cwqs(wq, wq->flush_color,
2640 /* nothing to flush, done */
2641 wq->flush_color = next_color;
2642 wq->first_flusher = NULL;
2647 BUG_ON(wq->flush_color == this_flusher.flush_color);
2648 list_add_tail(&this_flusher.list, &wq->flusher_queue);
2649 flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2653 * Oops, color space is full, wait on overflow queue.
2654 * The next flush completion will assign us
2655 * flush_color and transfer to flusher_queue.
2657 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2660 mutex_unlock(&wq->flush_mutex);
2662 wait_for_completion(&this_flusher.done);
2665 * Wake-up-and-cascade phase
2667 * First flushers are responsible for cascading flushes and
2668 * handling overflow. Non-first flushers can simply return.
2670 if (wq->first_flusher != &this_flusher)
2673 mutex_lock(&wq->flush_mutex);
2675 /* we might have raced, check again with mutex held */
2676 if (wq->first_flusher != &this_flusher)
2679 wq->first_flusher = NULL;
2681 BUG_ON(!list_empty(&this_flusher.list));
2682 BUG_ON(wq->flush_color != this_flusher.flush_color);
2685 struct wq_flusher *next, *tmp;
2687 /* complete all the flushers sharing the current flush color */
2688 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2689 if (next->flush_color != wq->flush_color)
2691 list_del_init(&next->list);
2692 complete(&next->done);
2695 BUG_ON(!list_empty(&wq->flusher_overflow) &&
2696 wq->flush_color != work_next_color(wq->work_color));
2698 /* this flush_color is finished, advance by one */
2699 wq->flush_color = work_next_color(wq->flush_color);
2701 /* one color has been freed, handle overflow queue */
2702 if (!list_empty(&wq->flusher_overflow)) {
2704 * Assign the same color to all overflowed
2705 * flushers, advance work_color and append to
2706 * flusher_queue. This is the start-to-wait
2707 * phase for these overflowed flushers.
2709 list_for_each_entry(tmp, &wq->flusher_overflow, list)
2710 tmp->flush_color = wq->work_color;
2712 wq->work_color = work_next_color(wq->work_color);
2714 list_splice_tail_init(&wq->flusher_overflow,
2715 &wq->flusher_queue);
2716 flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2719 if (list_empty(&wq->flusher_queue)) {
2720 BUG_ON(wq->flush_color != wq->work_color);
2725 * Need to flush more colors. Make the next flusher
2726 * the new first flusher and arm cwqs.
2728 BUG_ON(wq->flush_color == wq->work_color);
2729 BUG_ON(wq->flush_color != next->flush_color);
2731 list_del_init(&next->list);
2732 wq->first_flusher = next;
2734 if (flush_workqueue_prep_cwqs(wq, wq->flush_color, -1))
2738 * Meh... this color is already done, clear first
2739 * flusher and repeat cascading.
2741 wq->first_flusher = NULL;
2745 mutex_unlock(&wq->flush_mutex);
2747 EXPORT_SYMBOL_GPL(flush_workqueue);
2750 * drain_workqueue - drain a workqueue
2751 * @wq: workqueue to drain
2753 * Wait until the workqueue becomes empty. While draining is in progress,
2754 * only chain queueing is allowed. IOW, only currently pending or running
2755 * work items on @wq can queue further work items on it. @wq is flushed
2756 * repeatedly until it becomes empty. The number of flushing is detemined
2757 * by the depth of chaining and should be relatively short. Whine if it
2760 void drain_workqueue(struct workqueue_struct *wq)
2762 unsigned int flush_cnt = 0;
2766 * __queue_work() needs to test whether there are drainers, is much
2767 * hotter than drain_workqueue() and already looks at @wq->flags.
2768 * Use WQ_DRAINING so that queue doesn't have to check nr_drainers.
2770 spin_lock(&workqueue_lock);
2771 if (!wq->nr_drainers++)
2772 wq->flags |= WQ_DRAINING;
2773 spin_unlock(&workqueue_lock);
2775 flush_workqueue(wq);
2777 for_each_cwq_cpu(cpu, wq) {
2778 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2781 spin_lock_irq(&cwq->pool->gcwq->lock);
2782 drained = !cwq->nr_active && list_empty(&cwq->delayed_works);
2783 spin_unlock_irq(&cwq->pool->gcwq->lock);
2788 if (++flush_cnt == 10 ||
2789 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2790 pr_warn("workqueue %s: flush on destruction isn't complete after %u tries\n",
2791 wq->name, flush_cnt);
2795 spin_lock(&workqueue_lock);
2796 if (!--wq->nr_drainers)
2797 wq->flags &= ~WQ_DRAINING;
2798 spin_unlock(&workqueue_lock);
2800 EXPORT_SYMBOL_GPL(drain_workqueue);
2802 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2804 struct worker *worker = NULL;
2805 struct global_cwq *gcwq;
2806 struct cpu_workqueue_struct *cwq;
2809 gcwq = get_work_gcwq(work);
2813 spin_lock_irq(&gcwq->lock);
2814 if (!list_empty(&work->entry)) {
2816 * See the comment near try_to_grab_pending()->smp_rmb().
2817 * If it was re-queued to a different gcwq under us, we
2818 * are not going to wait.
2821 cwq = get_work_cwq(work);
2822 if (unlikely(!cwq || gcwq != cwq->pool->gcwq))
2825 worker = find_worker_executing_work(gcwq, work);
2828 cwq = worker->current_cwq;
2831 insert_wq_barrier(cwq, barr, work, worker);
2832 spin_unlock_irq(&gcwq->lock);
2835 * If @max_active is 1 or rescuer is in use, flushing another work
2836 * item on the same workqueue may lead to deadlock. Make sure the
2837 * flusher is not running on the same workqueue by verifying write
2840 if (cwq->wq->saved_max_active == 1 || cwq->wq->flags & WQ_RESCUER)
2841 lock_map_acquire(&cwq->wq->lockdep_map);
2843 lock_map_acquire_read(&cwq->wq->lockdep_map);
2844 lock_map_release(&cwq->wq->lockdep_map);
2848 spin_unlock_irq(&gcwq->lock);
2853 * flush_work - wait for a work to finish executing the last queueing instance
2854 * @work: the work to flush
2856 * Wait until @work has finished execution. @work is guaranteed to be idle
2857 * on return if it hasn't been requeued since flush started.
2860 * %true if flush_work() waited for the work to finish execution,
2861 * %false if it was already idle.
2863 bool flush_work(struct work_struct *work)
2865 struct wq_barrier barr;
2867 lock_map_acquire(&work->lockdep_map);
2868 lock_map_release(&work->lockdep_map);
2870 if (start_flush_work(work, &barr)) {
2871 wait_for_completion(&barr.done);
2872 destroy_work_on_stack(&barr.work);
2878 EXPORT_SYMBOL_GPL(flush_work);
2880 static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2882 unsigned long flags;
2886 ret = try_to_grab_pending(work, is_dwork, &flags);
2888 * If someone else is canceling, wait for the same event it
2889 * would be waiting for before retrying.
2891 if (unlikely(ret == -ENOENT))
2893 } while (unlikely(ret < 0));
2895 /* tell other tasks trying to grab @work to back off */
2896 mark_work_canceling(work);
2897 local_irq_restore(flags);
2900 clear_work_data(work);
2905 * cancel_work_sync - cancel a work and wait for it to finish
2906 * @work: the work to cancel
2908 * Cancel @work and wait for its execution to finish. This function
2909 * can be used even if the work re-queues itself or migrates to
2910 * another workqueue. On return from this function, @work is
2911 * guaranteed to be not pending or executing on any CPU.
2913 * cancel_work_sync(&delayed_work->work) must not be used for
2914 * delayed_work's. Use cancel_delayed_work_sync() instead.
2916 * The caller must ensure that the workqueue on which @work was last
2917 * queued can't be destroyed before this function returns.
2920 * %true if @work was pending, %false otherwise.
2922 bool cancel_work_sync(struct work_struct *work)
2924 return __cancel_work_timer(work, false);
2926 EXPORT_SYMBOL_GPL(cancel_work_sync);
2929 * flush_delayed_work - wait for a dwork to finish executing the last queueing
2930 * @dwork: the delayed work to flush
2932 * Delayed timer is cancelled and the pending work is queued for
2933 * immediate execution. Like flush_work(), this function only
2934 * considers the last queueing instance of @dwork.
2937 * %true if flush_work() waited for the work to finish execution,
2938 * %false if it was already idle.
2940 bool flush_delayed_work(struct delayed_work *dwork)
2942 local_irq_disable();
2943 if (del_timer_sync(&dwork->timer))
2944 __queue_work(dwork->cpu,
2945 get_work_cwq(&dwork->work)->wq, &dwork->work);
2947 return flush_work(&dwork->work);
2949 EXPORT_SYMBOL(flush_delayed_work);
2952 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2953 * @dwork: the delayed work cancel
2955 * This is cancel_work_sync() for delayed works.
2958 * %true if @dwork was pending, %false otherwise.
2960 bool cancel_delayed_work_sync(struct delayed_work *dwork)
2962 return __cancel_work_timer(&dwork->work, true);
2964 EXPORT_SYMBOL(cancel_delayed_work_sync);
2967 * schedule_work_on - put work task on a specific cpu
2968 * @cpu: cpu to put the work task on
2969 * @work: job to be done
2971 * This puts a job on a specific cpu
2973 bool schedule_work_on(int cpu, struct work_struct *work)
2975 return queue_work_on(cpu, system_wq, work);
2977 EXPORT_SYMBOL(schedule_work_on);
2980 * schedule_work - put work task in global workqueue
2981 * @work: job to be done
2983 * Returns %false if @work was already on the kernel-global workqueue and
2986 * This puts a job in the kernel-global workqueue if it was not already
2987 * queued and leaves it in the same position on the kernel-global
2988 * workqueue otherwise.
2990 bool schedule_work(struct work_struct *work)
2992 return queue_work(system_wq, work);
2994 EXPORT_SYMBOL(schedule_work);
2997 * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
2999 * @dwork: job to be done
3000 * @delay: number of jiffies to wait
3002 * After waiting for a given time this puts a job in the kernel-global
3003 * workqueue on the specified CPU.
3005 bool schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
3006 unsigned long delay)
3008 return queue_delayed_work_on(cpu, system_wq, dwork, delay);
3010 EXPORT_SYMBOL(schedule_delayed_work_on);
3013 * schedule_delayed_work - put work task in global workqueue after delay
3014 * @dwork: job to be done
3015 * @delay: number of jiffies to wait or 0 for immediate execution
3017 * After waiting for a given time this puts a job in the kernel-global
3020 bool schedule_delayed_work(struct delayed_work *dwork, unsigned long delay)
3022 return queue_delayed_work(system_wq, dwork, delay);
3024 EXPORT_SYMBOL(schedule_delayed_work);
3027 * schedule_on_each_cpu - execute a function synchronously on each online CPU
3028 * @func: the function to call
3030 * schedule_on_each_cpu() executes @func on each online CPU using the
3031 * system workqueue and blocks until all CPUs have completed.
3032 * schedule_on_each_cpu() is very slow.
3035 * 0 on success, -errno on failure.
3037 int schedule_on_each_cpu(work_func_t func)
3040 struct work_struct __percpu *works;
3042 works = alloc_percpu(struct work_struct);
3048 for_each_online_cpu(cpu) {
3049 struct work_struct *work = per_cpu_ptr(works, cpu);
3051 INIT_WORK(work, func);
3052 schedule_work_on(cpu, work);
3055 for_each_online_cpu(cpu)
3056 flush_work(per_cpu_ptr(works, cpu));
3064 * flush_scheduled_work - ensure that any scheduled work has run to completion.
3066 * Forces execution of the kernel-global workqueue and blocks until its
3069 * Think twice before calling this function! It's very easy to get into
3070 * trouble if you don't take great care. Either of the following situations
3071 * will lead to deadlock:
3073 * One of the work items currently on the workqueue needs to acquire
3074 * a lock held by your code or its caller.
3076 * Your code is running in the context of a work routine.
3078 * They will be detected by lockdep when they occur, but the first might not
3079 * occur very often. It depends on what work items are on the workqueue and
3080 * what locks they need, which you have no control over.
3082 * In most situations flushing the entire workqueue is overkill; you merely
3083 * need to know that a particular work item isn't queued and isn't running.
3084 * In such cases you should use cancel_delayed_work_sync() or
3085 * cancel_work_sync() instead.
3087 void flush_scheduled_work(void)
3089 flush_workqueue(system_wq);
3091 EXPORT_SYMBOL(flush_scheduled_work);
3094 * execute_in_process_context - reliably execute the routine with user context
3095 * @fn: the function to execute
3096 * @ew: guaranteed storage for the execute work structure (must
3097 * be available when the work executes)
3099 * Executes the function immediately if process context is available,
3100 * otherwise schedules the function for delayed execution.
3102 * Returns: 0 - function was executed
3103 * 1 - function was scheduled for execution
3105 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
3107 if (!in_interrupt()) {
3112 INIT_WORK(&ew->work, fn);
3113 schedule_work(&ew->work);
3117 EXPORT_SYMBOL_GPL(execute_in_process_context);
3119 int keventd_up(void)
3121 return system_wq != NULL;
3124 static int alloc_cwqs(struct workqueue_struct *wq)
3127 * cwqs are forced aligned according to WORK_STRUCT_FLAG_BITS.
3128 * Make sure that the alignment isn't lower than that of
3129 * unsigned long long.
3131 const size_t size = sizeof(struct cpu_workqueue_struct);
3132 const size_t align = max_t(size_t, 1 << WORK_STRUCT_FLAG_BITS,
3133 __alignof__(unsigned long long));
3135 if (!(wq->flags & WQ_UNBOUND))
3136 wq->cpu_wq.pcpu = __alloc_percpu(size, align);
3141 * Allocate enough room to align cwq and put an extra
3142 * pointer at the end pointing back to the originally
3143 * allocated pointer which will be used for free.
3145 ptr = kzalloc(size + align + sizeof(void *), GFP_KERNEL);
3147 wq->cpu_wq.single = PTR_ALIGN(ptr, align);
3148 *(void **)(wq->cpu_wq.single + 1) = ptr;
3152 /* just in case, make sure it's actually aligned */
3153 BUG_ON(!IS_ALIGNED(wq->cpu_wq.v, align));
3154 return wq->cpu_wq.v ? 0 : -ENOMEM;
3157 static void free_cwqs(struct workqueue_struct *wq)
3159 if (!(wq->flags & WQ_UNBOUND))
3160 free_percpu(wq->cpu_wq.pcpu);
3161 else if (wq->cpu_wq.single) {
3162 /* the pointer to free is stored right after the cwq */
3163 kfree(*(void **)(wq->cpu_wq.single + 1));
3167 static int wq_clamp_max_active(int max_active, unsigned int flags,
3170 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3172 if (max_active < 1 || max_active > lim)
3173 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3174 max_active, name, 1, lim);
3176 return clamp_val(max_active, 1, lim);
3179 struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
3182 struct lock_class_key *key,
3183 const char *lock_name, ...)
3185 va_list args, args1;
3186 struct workqueue_struct *wq;
3190 /* determine namelen, allocate wq and format name */
3191 va_start(args, lock_name);
3192 va_copy(args1, args);
3193 namelen = vsnprintf(NULL, 0, fmt, args) + 1;
3195 wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
3199 vsnprintf(wq->name, namelen, fmt, args1);
3204 * Workqueues which may be used during memory reclaim should
3205 * have a rescuer to guarantee forward progress.
3207 if (flags & WQ_MEM_RECLAIM)
3208 flags |= WQ_RESCUER;
3210 max_active = max_active ?: WQ_DFL_ACTIVE;
3211 max_active = wq_clamp_max_active(max_active, flags, wq->name);
3215 wq->saved_max_active = max_active;
3216 mutex_init(&wq->flush_mutex);
3217 atomic_set(&wq->nr_cwqs_to_flush, 0);
3218 INIT_LIST_HEAD(&wq->flusher_queue);
3219 INIT_LIST_HEAD(&wq->flusher_overflow);
3221 lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3222 INIT_LIST_HEAD(&wq->list);
3224 if (alloc_cwqs(wq) < 0)
3227 for_each_cwq_cpu(cpu, wq) {
3228 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3229 struct global_cwq *gcwq = get_gcwq(cpu);
3230 int pool_idx = (bool)(flags & WQ_HIGHPRI);
3232 BUG_ON((unsigned long)cwq & WORK_STRUCT_FLAG_MASK);
3233 cwq->pool = &gcwq->pools[pool_idx];
3235 cwq->flush_color = -1;
3236 cwq->max_active = max_active;
3237 INIT_LIST_HEAD(&cwq->delayed_works);
3240 if (flags & WQ_RESCUER) {
3241 struct worker *rescuer;
3243 if (!alloc_mayday_mask(&wq->mayday_mask, GFP_KERNEL))
3246 wq->rescuer = rescuer = alloc_worker();
3250 rescuer->task = kthread_create(rescuer_thread, wq, "%s",
3252 if (IS_ERR(rescuer->task))
3255 rescuer->task->flags |= PF_THREAD_BOUND;
3256 wake_up_process(rescuer->task);
3260 * workqueue_lock protects global freeze state and workqueues
3261 * list. Grab it, set max_active accordingly and add the new
3262 * workqueue to workqueues list.
3264 spin_lock(&workqueue_lock);
3266 if (workqueue_freezing && wq->flags & WQ_FREEZABLE)
3267 for_each_cwq_cpu(cpu, wq)
3268 get_cwq(cpu, wq)->max_active = 0;
3270 list_add(&wq->list, &workqueues);
3272 spin_unlock(&workqueue_lock);
3278 free_mayday_mask(wq->mayday_mask);
3284 EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
3287 * destroy_workqueue - safely terminate a workqueue
3288 * @wq: target workqueue
3290 * Safely destroy a workqueue. All work currently pending will be done first.
3292 void destroy_workqueue(struct workqueue_struct *wq)
3296 /* drain it before proceeding with destruction */
3297 drain_workqueue(wq);
3300 * wq list is used to freeze wq, remove from list after
3301 * flushing is complete in case freeze races us.
3303 spin_lock(&workqueue_lock);
3304 list_del(&wq->list);
3305 spin_unlock(&workqueue_lock);
3308 for_each_cwq_cpu(cpu, wq) {
3309 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3312 for (i = 0; i < WORK_NR_COLORS; i++)
3313 BUG_ON(cwq->nr_in_flight[i]);
3314 BUG_ON(cwq->nr_active);
3315 BUG_ON(!list_empty(&cwq->delayed_works));
3318 if (wq->flags & WQ_RESCUER) {
3319 kthread_stop(wq->rescuer->task);
3320 free_mayday_mask(wq->mayday_mask);
3327 EXPORT_SYMBOL_GPL(destroy_workqueue);
3330 * workqueue_set_max_active - adjust max_active of a workqueue
3331 * @wq: target workqueue
3332 * @max_active: new max_active value.
3334 * Set max_active of @wq to @max_active.
3337 * Don't call from IRQ context.
3339 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
3343 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
3345 spin_lock(&workqueue_lock);
3347 wq->saved_max_active = max_active;
3349 for_each_cwq_cpu(cpu, wq) {
3350 struct global_cwq *gcwq = get_gcwq(cpu);
3352 spin_lock_irq(&gcwq->lock);
3354 if (!(wq->flags & WQ_FREEZABLE) ||
3355 !(gcwq->flags & GCWQ_FREEZING))
3356 get_cwq(gcwq->cpu, wq)->max_active = max_active;
3358 spin_unlock_irq(&gcwq->lock);
3361 spin_unlock(&workqueue_lock);
3363 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
3366 * workqueue_congested - test whether a workqueue is congested
3367 * @cpu: CPU in question
3368 * @wq: target workqueue
3370 * Test whether @wq's cpu workqueue for @cpu is congested. There is
3371 * no synchronization around this function and the test result is
3372 * unreliable and only useful as advisory hints or for debugging.
3375 * %true if congested, %false otherwise.
3377 bool workqueue_congested(unsigned int cpu, struct workqueue_struct *wq)
3379 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3381 return !list_empty(&cwq->delayed_works);
3383 EXPORT_SYMBOL_GPL(workqueue_congested);
3386 * work_cpu - return the last known associated cpu for @work
3387 * @work: the work of interest
3390 * CPU number if @work was ever queued. WORK_CPU_NONE otherwise.
3392 unsigned int work_cpu(struct work_struct *work)
3394 struct global_cwq *gcwq = get_work_gcwq(work);
3396 return gcwq ? gcwq->cpu : WORK_CPU_NONE;
3398 EXPORT_SYMBOL_GPL(work_cpu);
3401 * work_busy - test whether a work is currently pending or running
3402 * @work: the work to be tested
3404 * Test whether @work is currently pending or running. There is no
3405 * synchronization around this function and the test result is
3406 * unreliable and only useful as advisory hints or for debugging.
3407 * Especially for reentrant wqs, the pending state might hide the
3411 * OR'd bitmask of WORK_BUSY_* bits.
3413 unsigned int work_busy(struct work_struct *work)
3415 struct global_cwq *gcwq = get_work_gcwq(work);
3416 unsigned long flags;
3417 unsigned int ret = 0;
3422 spin_lock_irqsave(&gcwq->lock, flags);
3424 if (work_pending(work))
3425 ret |= WORK_BUSY_PENDING;
3426 if (find_worker_executing_work(gcwq, work))
3427 ret |= WORK_BUSY_RUNNING;
3429 spin_unlock_irqrestore(&gcwq->lock, flags);
3433 EXPORT_SYMBOL_GPL(work_busy);
3438 * There are two challenges in supporting CPU hotplug. Firstly, there
3439 * are a lot of assumptions on strong associations among work, cwq and
3440 * gcwq which make migrating pending and scheduled works very
3441 * difficult to implement without impacting hot paths. Secondly,
3442 * gcwqs serve mix of short, long and very long running works making
3443 * blocked draining impractical.
3445 * This is solved by allowing a gcwq to be disassociated from the CPU
3446 * running as an unbound one and allowing it to be reattached later if the
3447 * cpu comes back online.
3450 /* claim manager positions of all pools */
3451 static void gcwq_claim_management_and_lock(struct global_cwq *gcwq)
3453 struct worker_pool *pool;
3455 for_each_worker_pool(pool, gcwq)
3456 mutex_lock_nested(&pool->manager_mutex, pool - gcwq->pools);
3457 spin_lock_irq(&gcwq->lock);
3460 /* release manager positions */
3461 static void gcwq_release_management_and_unlock(struct global_cwq *gcwq)
3463 struct worker_pool *pool;
3465 spin_unlock_irq(&gcwq->lock);
3466 for_each_worker_pool(pool, gcwq)
3467 mutex_unlock(&pool->manager_mutex);
3470 static void gcwq_unbind_fn(struct work_struct *work)
3472 struct global_cwq *gcwq = get_gcwq(smp_processor_id());
3473 struct worker_pool *pool;
3474 struct worker *worker;
3475 struct hlist_node *pos;
3478 BUG_ON(gcwq->cpu != smp_processor_id());
3480 gcwq_claim_management_and_lock(gcwq);
3483 * We've claimed all manager positions. Make all workers unbound
3484 * and set DISASSOCIATED. Before this, all workers except for the
3485 * ones which are still executing works from before the last CPU
3486 * down must be on the cpu. After this, they may become diasporas.
3488 for_each_worker_pool(pool, gcwq)
3489 list_for_each_entry(worker, &pool->idle_list, entry)
3490 worker->flags |= WORKER_UNBOUND;
3492 for_each_busy_worker(worker, i, pos, gcwq)
3493 worker->flags |= WORKER_UNBOUND;
3495 gcwq->flags |= GCWQ_DISASSOCIATED;
3497 gcwq_release_management_and_unlock(gcwq);
3500 * Call schedule() so that we cross rq->lock and thus can guarantee
3501 * sched callbacks see the %WORKER_UNBOUND flag. This is necessary
3502 * as scheduler callbacks may be invoked from other cpus.
3507 * Sched callbacks are disabled now. Zap nr_running. After this,
3508 * nr_running stays zero and need_more_worker() and keep_working()
3509 * are always true as long as the worklist is not empty. @gcwq now
3510 * behaves as unbound (in terms of concurrency management) gcwq
3511 * which is served by workers tied to the CPU.
3513 * On return from this function, the current worker would trigger
3514 * unbound chain execution of pending work items if other workers
3517 for_each_worker_pool(pool, gcwq)
3518 atomic_set(get_pool_nr_running(pool), 0);
3522 * Workqueues should be brought up before normal priority CPU notifiers.
3523 * This will be registered high priority CPU notifier.
3525 static int __devinit workqueue_cpu_up_callback(struct notifier_block *nfb,
3526 unsigned long action,
3529 unsigned int cpu = (unsigned long)hcpu;
3530 struct global_cwq *gcwq = get_gcwq(cpu);
3531 struct worker_pool *pool;
3533 switch (action & ~CPU_TASKS_FROZEN) {
3534 case CPU_UP_PREPARE:
3535 for_each_worker_pool(pool, gcwq) {
3536 struct worker *worker;
3538 if (pool->nr_workers)
3541 worker = create_worker(pool);
3545 spin_lock_irq(&gcwq->lock);
3546 start_worker(worker);
3547 spin_unlock_irq(&gcwq->lock);
3551 case CPU_DOWN_FAILED:
3553 gcwq_claim_management_and_lock(gcwq);
3554 gcwq->flags &= ~GCWQ_DISASSOCIATED;
3555 rebind_workers(gcwq);
3556 gcwq_release_management_and_unlock(gcwq);
3563 * Workqueues should be brought down after normal priority CPU notifiers.
3564 * This will be registered as low priority CPU notifier.
3566 static int __devinit workqueue_cpu_down_callback(struct notifier_block *nfb,
3567 unsigned long action,
3570 unsigned int cpu = (unsigned long)hcpu;
3571 struct work_struct unbind_work;
3573 switch (action & ~CPU_TASKS_FROZEN) {
3574 case CPU_DOWN_PREPARE:
3575 /* unbinding should happen on the local CPU */
3576 INIT_WORK_ONSTACK(&unbind_work, gcwq_unbind_fn);
3577 queue_work_on(cpu, system_highpri_wq, &unbind_work);
3578 flush_work(&unbind_work);
3586 struct work_for_cpu {
3587 struct completion completion;
3593 static int do_work_for_cpu(void *_wfc)
3595 struct work_for_cpu *wfc = _wfc;
3596 wfc->ret = wfc->fn(wfc->arg);
3597 complete(&wfc->completion);
3602 * work_on_cpu - run a function in user context on a particular cpu
3603 * @cpu: the cpu to run on
3604 * @fn: the function to run
3605 * @arg: the function arg
3607 * This will return the value @fn returns.
3608 * It is up to the caller to ensure that the cpu doesn't go offline.
3609 * The caller must not hold any locks which would prevent @fn from completing.
3611 long work_on_cpu(unsigned int cpu, long (*fn)(void *), void *arg)
3613 struct task_struct *sub_thread;
3614 struct work_for_cpu wfc = {
3615 .completion = COMPLETION_INITIALIZER_ONSTACK(wfc.completion),
3620 sub_thread = kthread_create(do_work_for_cpu, &wfc, "work_for_cpu");
3621 if (IS_ERR(sub_thread))
3622 return PTR_ERR(sub_thread);
3623 kthread_bind(sub_thread, cpu);
3624 wake_up_process(sub_thread);
3625 wait_for_completion(&wfc.completion);
3628 EXPORT_SYMBOL_GPL(work_on_cpu);
3629 #endif /* CONFIG_SMP */
3631 #ifdef CONFIG_FREEZER
3634 * freeze_workqueues_begin - begin freezing workqueues
3636 * Start freezing workqueues. After this function returns, all freezable
3637 * workqueues will queue new works to their frozen_works list instead of
3641 * Grabs and releases workqueue_lock and gcwq->lock's.
3643 void freeze_workqueues_begin(void)
3647 spin_lock(&workqueue_lock);
3649 BUG_ON(workqueue_freezing);
3650 workqueue_freezing = true;
3652 for_each_gcwq_cpu(cpu) {
3653 struct global_cwq *gcwq = get_gcwq(cpu);
3654 struct workqueue_struct *wq;
3656 spin_lock_irq(&gcwq->lock);
3658 BUG_ON(gcwq->flags & GCWQ_FREEZING);
3659 gcwq->flags |= GCWQ_FREEZING;
3661 list_for_each_entry(wq, &workqueues, list) {
3662 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3664 if (cwq && wq->flags & WQ_FREEZABLE)
3665 cwq->max_active = 0;
3668 spin_unlock_irq(&gcwq->lock);
3671 spin_unlock(&workqueue_lock);
3675 * freeze_workqueues_busy - are freezable workqueues still busy?
3677 * Check whether freezing is complete. This function must be called
3678 * between freeze_workqueues_begin() and thaw_workqueues().
3681 * Grabs and releases workqueue_lock.
3684 * %true if some freezable workqueues are still busy. %false if freezing
3687 bool freeze_workqueues_busy(void)
3692 spin_lock(&workqueue_lock);
3694 BUG_ON(!workqueue_freezing);
3696 for_each_gcwq_cpu(cpu) {
3697 struct workqueue_struct *wq;
3699 * nr_active is monotonically decreasing. It's safe
3700 * to peek without lock.
3702 list_for_each_entry(wq, &workqueues, list) {
3703 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3705 if (!cwq || !(wq->flags & WQ_FREEZABLE))
3708 BUG_ON(cwq->nr_active < 0);
3709 if (cwq->nr_active) {
3716 spin_unlock(&workqueue_lock);
3721 * thaw_workqueues - thaw workqueues
3723 * Thaw workqueues. Normal queueing is restored and all collected
3724 * frozen works are transferred to their respective gcwq worklists.
3727 * Grabs and releases workqueue_lock and gcwq->lock's.
3729 void thaw_workqueues(void)
3733 spin_lock(&workqueue_lock);
3735 if (!workqueue_freezing)
3738 for_each_gcwq_cpu(cpu) {
3739 struct global_cwq *gcwq = get_gcwq(cpu);
3740 struct worker_pool *pool;
3741 struct workqueue_struct *wq;
3743 spin_lock_irq(&gcwq->lock);
3745 BUG_ON(!(gcwq->flags & GCWQ_FREEZING));
3746 gcwq->flags &= ~GCWQ_FREEZING;
3748 list_for_each_entry(wq, &workqueues, list) {
3749 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3751 if (!cwq || !(wq->flags & WQ_FREEZABLE))
3754 /* restore max_active and repopulate worklist */
3755 cwq->max_active = wq->saved_max_active;
3757 while (!list_empty(&cwq->delayed_works) &&
3758 cwq->nr_active < cwq->max_active)
3759 cwq_activate_first_delayed(cwq);
3762 for_each_worker_pool(pool, gcwq)
3763 wake_up_worker(pool);
3765 spin_unlock_irq(&gcwq->lock);
3768 workqueue_freezing = false;
3770 spin_unlock(&workqueue_lock);
3772 #endif /* CONFIG_FREEZER */
3774 static int __init init_workqueues(void)
3779 /* make sure we have enough bits for OFFQ CPU number */
3780 BUILD_BUG_ON((1LU << (BITS_PER_LONG - WORK_OFFQ_CPU_SHIFT)) <
3783 cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
3784 cpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
3786 /* initialize gcwqs */
3787 for_each_gcwq_cpu(cpu) {
3788 struct global_cwq *gcwq = get_gcwq(cpu);
3789 struct worker_pool *pool;
3791 spin_lock_init(&gcwq->lock);
3793 gcwq->flags |= GCWQ_DISASSOCIATED;
3795 for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)
3796 INIT_HLIST_HEAD(&gcwq->busy_hash[i]);
3798 for_each_worker_pool(pool, gcwq) {
3800 INIT_LIST_HEAD(&pool->worklist);
3801 INIT_LIST_HEAD(&pool->idle_list);
3803 init_timer_deferrable(&pool->idle_timer);
3804 pool->idle_timer.function = idle_worker_timeout;
3805 pool->idle_timer.data = (unsigned long)pool;
3807 setup_timer(&pool->mayday_timer, gcwq_mayday_timeout,
3808 (unsigned long)pool);
3810 mutex_init(&pool->manager_mutex);
3811 ida_init(&pool->worker_ida);
3814 init_waitqueue_head(&gcwq->rebind_hold);
3817 /* create the initial worker */
3818 for_each_online_gcwq_cpu(cpu) {
3819 struct global_cwq *gcwq = get_gcwq(cpu);
3820 struct worker_pool *pool;
3822 if (cpu != WORK_CPU_UNBOUND)
3823 gcwq->flags &= ~GCWQ_DISASSOCIATED;
3825 for_each_worker_pool(pool, gcwq) {
3826 struct worker *worker;
3828 worker = create_worker(pool);
3830 spin_lock_irq(&gcwq->lock);
3831 start_worker(worker);
3832 spin_unlock_irq(&gcwq->lock);
3836 system_wq = alloc_workqueue("events", 0, 0);
3837 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
3838 system_long_wq = alloc_workqueue("events_long", 0, 0);
3839 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
3840 WQ_UNBOUND_MAX_ACTIVE);
3841 system_freezable_wq = alloc_workqueue("events_freezable",
3843 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
3844 !system_unbound_wq || !system_freezable_wq);
3847 early_initcall(init_workqueues);