2 * kernel/workqueue.c - generic async execution with shared worker pool
4 * Copyright (C) 2002 Ingo Molnar
6 * Derived from the taskqueue/keventd code by:
7 * David Woodhouse <dwmw2@infradead.org>
9 * Kai Petzke <wpp@marie.physik.tu-berlin.de>
10 * Theodore Ts'o <tytso@mit.edu>
12 * Made to use alloc_percpu by Christoph Lameter.
14 * Copyright (C) 2010 SUSE Linux Products GmbH
15 * Copyright (C) 2010 Tejun Heo <tj@kernel.org>
17 * This is the generic async execution mechanism. Work items as are
18 * executed in process context. The worker pool is shared and
19 * automatically managed. There is one worker pool for each CPU and
20 * one extra for works which are better served by workers which are
21 * not bound to any specific CPU.
23 * Please read Documentation/workqueue.txt for details.
26 #include <linux/export.h>
27 #include <linux/kernel.h>
28 #include <linux/sched.h>
29 #include <linux/init.h>
30 #include <linux/signal.h>
31 #include <linux/completion.h>
32 #include <linux/workqueue.h>
33 #include <linux/slab.h>
34 #include <linux/cpu.h>
35 #include <linux/notifier.h>
36 #include <linux/kthread.h>
37 #include <linux/hardirq.h>
38 #include <linux/mempolicy.h>
39 #include <linux/freezer.h>
40 #include <linux/kallsyms.h>
41 #include <linux/debug_locks.h>
42 #include <linux/lockdep.h>
43 #include <linux/idr.h>
44 #include <linux/hashtable.h>
46 #include "workqueue_internal.h"
52 * A bound gcwq is either associated or disassociated with its CPU.
53 * While associated (!DISASSOCIATED), all workers are bound to the
54 * CPU and none has %WORKER_UNBOUND set and concurrency management
57 * While DISASSOCIATED, the cpu may be offline and all workers have
58 * %WORKER_UNBOUND set and concurrency management disabled, and may
59 * be executing on any CPU. The gcwq behaves as an unbound one.
61 * Note that DISASSOCIATED can be flipped only while holding
62 * assoc_mutex of all pools on the gcwq to avoid changing binding
63 * state while create_worker() is in progress.
65 GCWQ_DISASSOCIATED = 1 << 0, /* cpu can't serve workers */
66 GCWQ_FREEZING = 1 << 1, /* freeze in progress */
69 POOL_MANAGE_WORKERS = 1 << 0, /* need to manage workers */
70 POOL_MANAGING_WORKERS = 1 << 1, /* managing workers */
73 WORKER_STARTED = 1 << 0, /* started */
74 WORKER_DIE = 1 << 1, /* die die die */
75 WORKER_IDLE = 1 << 2, /* is idle */
76 WORKER_PREP = 1 << 3, /* preparing to run works */
77 WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
78 WORKER_UNBOUND = 1 << 7, /* worker is unbound */
80 WORKER_NOT_RUNNING = WORKER_PREP | WORKER_UNBOUND |
83 NR_WORKER_POOLS = 2, /* # worker pools per gcwq */
85 BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
87 MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
88 IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
90 MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
91 /* call for help after 10ms
93 MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
94 CREATE_COOLDOWN = HZ, /* time to breath after fail */
97 * Rescue workers are used only on emergencies and shared by
100 RESCUER_NICE_LEVEL = -20,
101 HIGHPRI_NICE_LEVEL = -20,
105 * Structure fields follow one of the following exclusion rules.
107 * I: Modifiable by initialization/destruction paths and read-only for
110 * P: Preemption protected. Disabling preemption is enough and should
111 * only be modified and accessed from the local cpu.
113 * L: gcwq->lock protected. Access with gcwq->lock held.
115 * X: During normal operation, modification requires gcwq->lock and
116 * should be done only from local cpu. Either disabling preemption
117 * on local cpu or grabbing gcwq->lock is enough for read access.
118 * If GCWQ_DISASSOCIATED is set, it's identical to L.
120 * F: wq->flush_mutex protected.
122 * W: workqueue_lock protected.
129 * The poor guys doing the actual heavy lifting. All on-duty workers
130 * are either serving the manager role, on idle list or on busy hash.
133 /* on idle list while idle, on busy hash table while busy */
135 struct list_head entry; /* L: while idle */
136 struct hlist_node hentry; /* L: while busy */
139 struct work_struct *current_work; /* L: work being processed */
140 work_func_t current_func; /* L: current_work's fn */
141 struct cpu_workqueue_struct *current_cwq; /* L: current_work's cwq */
142 struct list_head scheduled; /* L: scheduled works */
143 struct task_struct *task; /* I: worker task */
144 struct worker_pool *pool; /* I: the associated pool */
145 /* 64 bytes boundary on 64bit, 32 on 32bit */
146 unsigned long last_active; /* L: last active timestamp */
147 unsigned int flags; /* X: flags */
148 int id; /* I: worker id */
150 /* for rebinding worker to CPU */
151 struct work_struct rebind_work; /* L: for busy worker */
153 /* used only by rescuers to point to the target workqueue */
154 struct workqueue_struct *rescue_wq; /* I: the workqueue to rescue */
158 struct global_cwq *gcwq; /* I: the owning gcwq */
159 unsigned int flags; /* X: flags */
161 struct list_head worklist; /* L: list of pending works */
162 int nr_workers; /* L: total number of workers */
164 /* nr_idle includes the ones off idle_list for rebinding */
165 int nr_idle; /* L: currently idle ones */
167 struct list_head idle_list; /* X: list of idle workers */
168 struct timer_list idle_timer; /* L: worker idle timeout */
169 struct timer_list mayday_timer; /* L: SOS timer for workers */
171 struct mutex assoc_mutex; /* protect GCWQ_DISASSOCIATED */
172 struct ida worker_ida; /* L: for worker IDs */
176 * Global per-cpu workqueue. There's one and only one for each cpu
177 * and all works are queued and processed here regardless of their
181 spinlock_t lock; /* the gcwq lock */
182 unsigned int cpu; /* I: the associated cpu */
183 unsigned int flags; /* L: GCWQ_* flags */
185 /* workers are chained either in busy_hash or pool idle_list */
186 DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
187 /* L: hash of busy workers */
189 struct worker_pool pools[NR_WORKER_POOLS];
190 /* normal and highpri pools */
191 } ____cacheline_aligned_in_smp;
194 * The per-CPU workqueue. The lower WORK_STRUCT_FLAG_BITS of
195 * work_struct->data are used for flags and thus cwqs need to be
196 * aligned at two's power of the number of flag bits.
198 struct cpu_workqueue_struct {
199 struct worker_pool *pool; /* I: the associated pool */
200 struct workqueue_struct *wq; /* I: the owning workqueue */
201 int work_color; /* L: current color */
202 int flush_color; /* L: flushing color */
203 int nr_in_flight[WORK_NR_COLORS];
204 /* L: nr of in_flight works */
205 int nr_active; /* L: nr of active works */
206 int max_active; /* L: max active works */
207 struct list_head delayed_works; /* L: delayed works */
211 * Structure used to wait for workqueue flush.
214 struct list_head list; /* F: list of flushers */
215 int flush_color; /* F: flush color waiting for */
216 struct completion done; /* flush completion */
220 * All cpumasks are assumed to be always set on UP and thus can't be
221 * used to determine whether there's something to be done.
224 typedef cpumask_var_t mayday_mask_t;
225 #define mayday_test_and_set_cpu(cpu, mask) \
226 cpumask_test_and_set_cpu((cpu), (mask))
227 #define mayday_clear_cpu(cpu, mask) cpumask_clear_cpu((cpu), (mask))
228 #define for_each_mayday_cpu(cpu, mask) for_each_cpu((cpu), (mask))
229 #define alloc_mayday_mask(maskp, gfp) zalloc_cpumask_var((maskp), (gfp))
230 #define free_mayday_mask(mask) free_cpumask_var((mask))
232 typedef unsigned long mayday_mask_t;
233 #define mayday_test_and_set_cpu(cpu, mask) test_and_set_bit(0, &(mask))
234 #define mayday_clear_cpu(cpu, mask) clear_bit(0, &(mask))
235 #define for_each_mayday_cpu(cpu, mask) if ((cpu) = 0, (mask))
236 #define alloc_mayday_mask(maskp, gfp) true
237 #define free_mayday_mask(mask) do { } while (0)
241 * The externally visible workqueue abstraction is an array of
242 * per-CPU workqueues:
244 struct workqueue_struct {
245 unsigned int flags; /* W: WQ_* flags */
247 struct cpu_workqueue_struct __percpu *pcpu;
248 struct cpu_workqueue_struct *single;
250 } cpu_wq; /* I: cwq's */
251 struct list_head list; /* W: list of all workqueues */
253 struct mutex flush_mutex; /* protects wq flushing */
254 int work_color; /* F: current work color */
255 int flush_color; /* F: current flush color */
256 atomic_t nr_cwqs_to_flush; /* flush in progress */
257 struct wq_flusher *first_flusher; /* F: first flusher */
258 struct list_head flusher_queue; /* F: flush waiters */
259 struct list_head flusher_overflow; /* F: flush overflow list */
261 mayday_mask_t mayday_mask; /* cpus requesting rescue */
262 struct worker *rescuer; /* I: rescue worker */
264 int nr_drainers; /* W: drain in progress */
265 int saved_max_active; /* W: saved cwq max_active */
266 #ifdef CONFIG_LOCKDEP
267 struct lockdep_map lockdep_map;
269 char name[]; /* I: workqueue name */
272 struct workqueue_struct *system_wq __read_mostly;
273 EXPORT_SYMBOL_GPL(system_wq);
274 struct workqueue_struct *system_highpri_wq __read_mostly;
275 EXPORT_SYMBOL_GPL(system_highpri_wq);
276 struct workqueue_struct *system_long_wq __read_mostly;
277 EXPORT_SYMBOL_GPL(system_long_wq);
278 struct workqueue_struct *system_unbound_wq __read_mostly;
279 EXPORT_SYMBOL_GPL(system_unbound_wq);
280 struct workqueue_struct *system_freezable_wq __read_mostly;
281 EXPORT_SYMBOL_GPL(system_freezable_wq);
283 #define CREATE_TRACE_POINTS
284 #include <trace/events/workqueue.h>
286 #define for_each_worker_pool(pool, gcwq) \
287 for ((pool) = &(gcwq)->pools[0]; \
288 (pool) < &(gcwq)->pools[NR_WORKER_POOLS]; (pool)++)
290 #define for_each_busy_worker(worker, i, pos, gcwq) \
291 hash_for_each(gcwq->busy_hash, i, pos, worker, 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 = pool->flags & POOL_MANAGING_WORKERS;
686 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
687 int nr_busy = pool->nr_workers - nr_idle;
690 * nr_idle and idle_list may disagree if idle rebinding is in
691 * progress. Never return %true if idle_list is empty.
693 if (list_empty(&pool->idle_list))
696 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
703 /* Return the first worker. Safe with preemption disabled */
704 static struct worker *first_worker(struct worker_pool *pool)
706 if (unlikely(list_empty(&pool->idle_list)))
709 return list_first_entry(&pool->idle_list, struct worker, entry);
713 * wake_up_worker - wake up an idle worker
714 * @pool: worker pool to wake worker from
716 * Wake up the first idle worker of @pool.
719 * spin_lock_irq(gcwq->lock).
721 static void wake_up_worker(struct worker_pool *pool)
723 struct worker *worker = first_worker(pool);
726 wake_up_process(worker->task);
730 * wq_worker_waking_up - a worker is waking up
731 * @task: task waking up
732 * @cpu: CPU @task is waking up to
734 * This function is called during try_to_wake_up() when a worker is
738 * spin_lock_irq(rq->lock)
740 void wq_worker_waking_up(struct task_struct *task, unsigned int cpu)
742 struct worker *worker = kthread_data(task);
744 if (!(worker->flags & WORKER_NOT_RUNNING)) {
745 WARN_ON_ONCE(worker->pool->gcwq->cpu != cpu);
746 atomic_inc(get_pool_nr_running(worker->pool));
751 * wq_worker_sleeping - a worker is going to sleep
752 * @task: task going to sleep
753 * @cpu: CPU in question, must be the current CPU number
755 * This function is called during schedule() when a busy worker is
756 * going to sleep. Worker on the same cpu can be woken up by
757 * returning pointer to its task.
760 * spin_lock_irq(rq->lock)
763 * Worker task on @cpu to wake up, %NULL if none.
765 struct task_struct *wq_worker_sleeping(struct task_struct *task,
768 struct worker *worker = kthread_data(task), *to_wakeup = NULL;
769 struct worker_pool *pool;
770 atomic_t *nr_running;
773 * Rescuers, which may not have all the fields set up like normal
774 * workers, also reach here, let's not access anything before
775 * checking NOT_RUNNING.
777 if (worker->flags & WORKER_NOT_RUNNING)
781 nr_running = get_pool_nr_running(pool);
783 /* this can only happen on the local cpu */
784 BUG_ON(cpu != raw_smp_processor_id());
787 * The counterpart of the following dec_and_test, implied mb,
788 * worklist not empty test sequence is in insert_work().
789 * Please read comment there.
791 * NOT_RUNNING is clear. This means that we're bound to and
792 * running on the local cpu w/ rq lock held and preemption
793 * disabled, which in turn means that none else could be
794 * manipulating idle_list, so dereferencing idle_list without gcwq
797 if (atomic_dec_and_test(nr_running) && !list_empty(&pool->worklist))
798 to_wakeup = first_worker(pool);
799 return to_wakeup ? to_wakeup->task : NULL;
803 * worker_set_flags - set worker flags and adjust nr_running accordingly
805 * @flags: flags to set
806 * @wakeup: wakeup an idle worker if necessary
808 * Set @flags in @worker->flags and adjust nr_running accordingly. If
809 * nr_running becomes zero and @wakeup is %true, an idle worker is
813 * spin_lock_irq(gcwq->lock)
815 static inline void worker_set_flags(struct worker *worker, unsigned int flags,
818 struct worker_pool *pool = worker->pool;
820 WARN_ON_ONCE(worker->task != current);
823 * If transitioning into NOT_RUNNING, adjust nr_running and
824 * wake up an idle worker as necessary if requested by
827 if ((flags & WORKER_NOT_RUNNING) &&
828 !(worker->flags & WORKER_NOT_RUNNING)) {
829 atomic_t *nr_running = get_pool_nr_running(pool);
832 if (atomic_dec_and_test(nr_running) &&
833 !list_empty(&pool->worklist))
834 wake_up_worker(pool);
836 atomic_dec(nr_running);
839 worker->flags |= flags;
843 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
845 * @flags: flags to clear
847 * Clear @flags in @worker->flags and adjust nr_running accordingly.
850 * spin_lock_irq(gcwq->lock)
852 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
854 struct worker_pool *pool = worker->pool;
855 unsigned int oflags = worker->flags;
857 WARN_ON_ONCE(worker->task != current);
859 worker->flags &= ~flags;
862 * If transitioning out of NOT_RUNNING, increment nr_running. Note
863 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
864 * of multiple flags, not a single flag.
866 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
867 if (!(worker->flags & WORKER_NOT_RUNNING))
868 atomic_inc(get_pool_nr_running(pool));
872 * find_worker_executing_work - find worker which is executing a work
873 * @gcwq: gcwq of interest
874 * @work: work to find worker for
876 * Find a worker which is executing @work on @gcwq by searching
877 * @gcwq->busy_hash which is keyed by the address of @work. For a worker
878 * to match, its current execution should match the address of @work and
879 * its work function. This is to avoid unwanted dependency between
880 * unrelated work executions through a work item being recycled while still
883 * This is a bit tricky. A work item may be freed once its execution
884 * starts and nothing prevents the freed area from being recycled for
885 * another work item. If the same work item address ends up being reused
886 * before the original execution finishes, workqueue will identify the
887 * recycled work item as currently executing and make it wait until the
888 * current execution finishes, introducing an unwanted dependency.
890 * This function checks the work item address, work function and workqueue
891 * to avoid false positives. Note that this isn't complete as one may
892 * construct a work function which can introduce dependency onto itself
893 * through a recycled work item. Well, if somebody wants to shoot oneself
894 * in the foot that badly, there's only so much we can do, and if such
895 * deadlock actually occurs, it should be easy to locate the culprit work
899 * spin_lock_irq(gcwq->lock).
902 * Pointer to worker which is executing @work if found, NULL
905 static struct worker *find_worker_executing_work(struct global_cwq *gcwq,
906 struct work_struct *work)
908 struct worker *worker;
909 struct hlist_node *tmp;
911 hash_for_each_possible(gcwq->busy_hash, worker, tmp, hentry,
913 if (worker->current_work == work &&
914 worker->current_func == work->func)
921 * move_linked_works - move linked works to a list
922 * @work: start of series of works to be scheduled
923 * @head: target list to append @work to
924 * @nextp: out paramter for nested worklist walking
926 * Schedule linked works starting from @work to @head. Work series to
927 * be scheduled starts at @work and includes any consecutive work with
928 * WORK_STRUCT_LINKED set in its predecessor.
930 * If @nextp is not NULL, it's updated to point to the next work of
931 * the last scheduled work. This allows move_linked_works() to be
932 * nested inside outer list_for_each_entry_safe().
935 * spin_lock_irq(gcwq->lock).
937 static void move_linked_works(struct work_struct *work, struct list_head *head,
938 struct work_struct **nextp)
940 struct work_struct *n;
943 * Linked worklist will always end before the end of the list,
944 * use NULL for list head.
946 list_for_each_entry_safe_from(work, n, NULL, entry) {
947 list_move_tail(&work->entry, head);
948 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
953 * If we're already inside safe list traversal and have moved
954 * multiple works to the scheduled queue, the next position
955 * needs to be updated.
961 static void cwq_activate_delayed_work(struct work_struct *work)
963 struct cpu_workqueue_struct *cwq = get_work_cwq(work);
965 trace_workqueue_activate_work(work);
966 move_linked_works(work, &cwq->pool->worklist, NULL);
967 __clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
971 static void cwq_activate_first_delayed(struct cpu_workqueue_struct *cwq)
973 struct work_struct *work = list_first_entry(&cwq->delayed_works,
974 struct work_struct, entry);
976 cwq_activate_delayed_work(work);
980 * cwq_dec_nr_in_flight - decrement cwq's nr_in_flight
981 * @cwq: cwq of interest
982 * @color: color of work which left the queue
984 * A work either has completed or is removed from pending queue,
985 * decrement nr_in_flight of its cwq and handle workqueue flushing.
988 * spin_lock_irq(gcwq->lock).
990 static void cwq_dec_nr_in_flight(struct cpu_workqueue_struct *cwq, int color)
992 /* ignore uncolored works */
993 if (color == WORK_NO_COLOR)
996 cwq->nr_in_flight[color]--;
999 if (!list_empty(&cwq->delayed_works)) {
1000 /* one down, submit a delayed one */
1001 if (cwq->nr_active < cwq->max_active)
1002 cwq_activate_first_delayed(cwq);
1005 /* is flush in progress and are we at the flushing tip? */
1006 if (likely(cwq->flush_color != color))
1009 /* are there still in-flight works? */
1010 if (cwq->nr_in_flight[color])
1013 /* this cwq is done, clear flush_color */
1014 cwq->flush_color = -1;
1017 * If this was the last cwq, wake up the first flusher. It
1018 * will handle the rest.
1020 if (atomic_dec_and_test(&cwq->wq->nr_cwqs_to_flush))
1021 complete(&cwq->wq->first_flusher->done);
1025 * try_to_grab_pending - steal work item from worklist and disable irq
1026 * @work: work item to steal
1027 * @is_dwork: @work is a delayed_work
1028 * @flags: place to store irq state
1030 * Try to grab PENDING bit of @work. This function can handle @work in any
1031 * stable state - idle, on timer or on worklist. Return values are
1033 * 1 if @work was pending and we successfully stole PENDING
1034 * 0 if @work was idle and we claimed PENDING
1035 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1036 * -ENOENT if someone else is canceling @work, this state may persist
1037 * for arbitrarily long
1039 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1040 * interrupted while holding PENDING and @work off queue, irq must be
1041 * disabled on entry. This, combined with delayed_work->timer being
1042 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1044 * On successful return, >= 0, irq is disabled and the caller is
1045 * responsible for releasing it using local_irq_restore(*@flags).
1047 * This function is safe to call from any context including IRQ handler.
1049 static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1050 unsigned long *flags)
1052 struct global_cwq *gcwq;
1054 local_irq_save(*flags);
1056 /* try to steal the timer if it exists */
1058 struct delayed_work *dwork = to_delayed_work(work);
1061 * dwork->timer is irqsafe. If del_timer() fails, it's
1062 * guaranteed that the timer is not queued anywhere and not
1063 * running on the local CPU.
1065 if (likely(del_timer(&dwork->timer)))
1069 /* try to claim PENDING the normal way */
1070 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1074 * The queueing is in progress, or it is already queued. Try to
1075 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1077 gcwq = get_work_gcwq(work);
1081 spin_lock(&gcwq->lock);
1082 if (!list_empty(&work->entry)) {
1084 * This work is queued, but perhaps we locked the wrong gcwq.
1085 * In that case we must see the new value after rmb(), see
1086 * insert_work()->wmb().
1089 if (gcwq == get_work_gcwq(work)) {
1090 debug_work_deactivate(work);
1093 * A delayed work item cannot be grabbed directly
1094 * because it might have linked NO_COLOR work items
1095 * which, if left on the delayed_list, will confuse
1096 * cwq->nr_active management later on and cause
1097 * stall. Make sure the work item is activated
1100 if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1101 cwq_activate_delayed_work(work);
1103 list_del_init(&work->entry);
1104 cwq_dec_nr_in_flight(get_work_cwq(work),
1105 get_work_color(work));
1107 spin_unlock(&gcwq->lock);
1111 spin_unlock(&gcwq->lock);
1113 local_irq_restore(*flags);
1114 if (work_is_canceling(work))
1121 * insert_work - insert a work into gcwq
1122 * @cwq: cwq @work belongs to
1123 * @work: work to insert
1124 * @head: insertion point
1125 * @extra_flags: extra WORK_STRUCT_* flags to set
1127 * Insert @work which belongs to @cwq into @gcwq after @head.
1128 * @extra_flags is or'd to work_struct flags.
1131 * spin_lock_irq(gcwq->lock).
1133 static void insert_work(struct cpu_workqueue_struct *cwq,
1134 struct work_struct *work, struct list_head *head,
1135 unsigned int extra_flags)
1137 struct worker_pool *pool = cwq->pool;
1139 /* we own @work, set data and link */
1140 set_work_cwq(work, cwq, extra_flags);
1143 * Ensure that we get the right work->data if we see the
1144 * result of list_add() below, see try_to_grab_pending().
1148 list_add_tail(&work->entry, head);
1151 * Ensure either worker_sched_deactivated() sees the above
1152 * list_add_tail() or we see zero nr_running to avoid workers
1153 * lying around lazily while there are works to be processed.
1157 if (__need_more_worker(pool))
1158 wake_up_worker(pool);
1162 * Test whether @work is being queued from another work executing on the
1163 * same workqueue. This is rather expensive and should only be used from
1166 static bool is_chained_work(struct workqueue_struct *wq)
1168 unsigned long flags;
1171 for_each_gcwq_cpu(cpu) {
1172 struct global_cwq *gcwq = get_gcwq(cpu);
1173 struct worker *worker;
1174 struct hlist_node *pos;
1177 spin_lock_irqsave(&gcwq->lock, flags);
1178 for_each_busy_worker(worker, i, pos, gcwq) {
1179 if (worker->task != current)
1181 spin_unlock_irqrestore(&gcwq->lock, flags);
1183 * I'm @worker, no locking necessary. See if @work
1184 * is headed to the same workqueue.
1186 return worker->current_cwq->wq == wq;
1188 spin_unlock_irqrestore(&gcwq->lock, flags);
1193 static void __queue_work(unsigned int cpu, struct workqueue_struct *wq,
1194 struct work_struct *work)
1196 struct global_cwq *gcwq;
1197 struct cpu_workqueue_struct *cwq;
1198 struct list_head *worklist;
1199 unsigned int work_flags;
1200 unsigned int req_cpu = cpu;
1203 * While a work item is PENDING && off queue, a task trying to
1204 * steal the PENDING will busy-loop waiting for it to either get
1205 * queued or lose PENDING. Grabbing PENDING and queueing should
1206 * happen with IRQ disabled.
1208 WARN_ON_ONCE(!irqs_disabled());
1210 debug_work_activate(work);
1212 /* if dying, only works from the same workqueue are allowed */
1213 if (unlikely(wq->flags & WQ_DRAINING) &&
1214 WARN_ON_ONCE(!is_chained_work(wq)))
1217 /* determine gcwq to use */
1218 if (!(wq->flags & WQ_UNBOUND)) {
1219 struct global_cwq *last_gcwq;
1221 if (cpu == WORK_CPU_UNBOUND)
1222 cpu = raw_smp_processor_id();
1225 * It's multi cpu. If @work was previously on a different
1226 * cpu, it might still be running there, in which case the
1227 * work needs to be queued on that cpu to guarantee
1230 gcwq = get_gcwq(cpu);
1231 last_gcwq = get_work_gcwq(work);
1233 if (last_gcwq && last_gcwq != gcwq) {
1234 struct worker *worker;
1236 spin_lock(&last_gcwq->lock);
1238 worker = find_worker_executing_work(last_gcwq, work);
1240 if (worker && worker->current_cwq->wq == wq)
1243 /* meh... not running there, queue here */
1244 spin_unlock(&last_gcwq->lock);
1245 spin_lock(&gcwq->lock);
1248 spin_lock(&gcwq->lock);
1251 gcwq = get_gcwq(WORK_CPU_UNBOUND);
1252 spin_lock(&gcwq->lock);
1255 /* gcwq determined, get cwq and queue */
1256 cwq = get_cwq(gcwq->cpu, wq);
1257 trace_workqueue_queue_work(req_cpu, cwq, work);
1259 if (WARN_ON(!list_empty(&work->entry))) {
1260 spin_unlock(&gcwq->lock);
1264 cwq->nr_in_flight[cwq->work_color]++;
1265 work_flags = work_color_to_flags(cwq->work_color);
1267 if (likely(cwq->nr_active < cwq->max_active)) {
1268 trace_workqueue_activate_work(work);
1270 worklist = &cwq->pool->worklist;
1272 work_flags |= WORK_STRUCT_DELAYED;
1273 worklist = &cwq->delayed_works;
1276 insert_work(cwq, work, worklist, work_flags);
1278 spin_unlock(&gcwq->lock);
1282 * queue_work_on - queue work on specific cpu
1283 * @cpu: CPU number to execute work on
1284 * @wq: workqueue to use
1285 * @work: work to queue
1287 * Returns %false if @work was already on a queue, %true otherwise.
1289 * We queue the work to a specific CPU, the caller must ensure it
1292 bool queue_work_on(int cpu, struct workqueue_struct *wq,
1293 struct work_struct *work)
1296 unsigned long flags;
1298 local_irq_save(flags);
1300 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1301 __queue_work(cpu, wq, work);
1305 local_irq_restore(flags);
1308 EXPORT_SYMBOL_GPL(queue_work_on);
1311 * queue_work - queue work on a workqueue
1312 * @wq: workqueue to use
1313 * @work: work to queue
1315 * Returns %false if @work was already on a queue, %true otherwise.
1317 * We queue the work to the CPU on which it was submitted, but if the CPU dies
1318 * it can be processed by another CPU.
1320 bool queue_work(struct workqueue_struct *wq, struct work_struct *work)
1322 return queue_work_on(WORK_CPU_UNBOUND, wq, work);
1324 EXPORT_SYMBOL_GPL(queue_work);
1326 void delayed_work_timer_fn(unsigned long __data)
1328 struct delayed_work *dwork = (struct delayed_work *)__data;
1329 struct cpu_workqueue_struct *cwq = get_work_cwq(&dwork->work);
1331 /* should have been called from irqsafe timer with irq already off */
1332 __queue_work(dwork->cpu, cwq->wq, &dwork->work);
1334 EXPORT_SYMBOL_GPL(delayed_work_timer_fn);
1336 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
1337 struct delayed_work *dwork, unsigned long delay)
1339 struct timer_list *timer = &dwork->timer;
1340 struct work_struct *work = &dwork->work;
1343 WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
1344 timer->data != (unsigned long)dwork);
1345 WARN_ON_ONCE(timer_pending(timer));
1346 WARN_ON_ONCE(!list_empty(&work->entry));
1349 * If @delay is 0, queue @dwork->work immediately. This is for
1350 * both optimization and correctness. The earliest @timer can
1351 * expire is on the closest next tick and delayed_work users depend
1352 * on that there's no such delay when @delay is 0.
1355 __queue_work(cpu, wq, &dwork->work);
1359 timer_stats_timer_set_start_info(&dwork->timer);
1362 * This stores cwq for the moment, for the timer_fn. Note that the
1363 * work's gcwq is preserved to allow reentrance detection for
1366 if (!(wq->flags & WQ_UNBOUND)) {
1367 struct global_cwq *gcwq = get_work_gcwq(work);
1370 * If we cannot get the last gcwq from @work directly,
1371 * select the last CPU such that it avoids unnecessarily
1372 * triggering non-reentrancy check in __queue_work().
1377 if (lcpu == WORK_CPU_UNBOUND)
1378 lcpu = raw_smp_processor_id();
1380 lcpu = WORK_CPU_UNBOUND;
1383 set_work_cwq(work, get_cwq(lcpu, wq), 0);
1386 timer->expires = jiffies + delay;
1388 if (unlikely(cpu != WORK_CPU_UNBOUND))
1389 add_timer_on(timer, cpu);
1395 * queue_delayed_work_on - queue work on specific CPU after delay
1396 * @cpu: CPU number to execute work on
1397 * @wq: workqueue to use
1398 * @dwork: work to queue
1399 * @delay: number of jiffies to wait before queueing
1401 * Returns %false if @work was already on a queue, %true otherwise. If
1402 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1405 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1406 struct delayed_work *dwork, unsigned long delay)
1408 struct work_struct *work = &dwork->work;
1410 unsigned long flags;
1412 /* read the comment in __queue_work() */
1413 local_irq_save(flags);
1415 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1416 __queue_delayed_work(cpu, wq, dwork, delay);
1420 local_irq_restore(flags);
1423 EXPORT_SYMBOL_GPL(queue_delayed_work_on);
1426 * queue_delayed_work - queue work on a workqueue after delay
1427 * @wq: workqueue to use
1428 * @dwork: delayable work to queue
1429 * @delay: number of jiffies to wait before queueing
1431 * Equivalent to queue_delayed_work_on() but tries to use the local CPU.
1433 bool queue_delayed_work(struct workqueue_struct *wq,
1434 struct delayed_work *dwork, unsigned long delay)
1436 return queue_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
1438 EXPORT_SYMBOL_GPL(queue_delayed_work);
1441 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1442 * @cpu: CPU number to execute work on
1443 * @wq: workqueue to use
1444 * @dwork: work to queue
1445 * @delay: number of jiffies to wait before queueing
1447 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1448 * modify @dwork's timer so that it expires after @delay. If @delay is
1449 * zero, @work is guaranteed to be scheduled immediately regardless of its
1452 * Returns %false if @dwork was idle and queued, %true if @dwork was
1453 * pending and its timer was modified.
1455 * This function is safe to call from any context including IRQ handler.
1456 * See try_to_grab_pending() for details.
1458 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
1459 struct delayed_work *dwork, unsigned long delay)
1461 unsigned long flags;
1465 ret = try_to_grab_pending(&dwork->work, true, &flags);
1466 } while (unlikely(ret == -EAGAIN));
1468 if (likely(ret >= 0)) {
1469 __queue_delayed_work(cpu, wq, dwork, delay);
1470 local_irq_restore(flags);
1473 /* -ENOENT from try_to_grab_pending() becomes %true */
1476 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
1479 * mod_delayed_work - modify delay of or queue a delayed work
1480 * @wq: workqueue to use
1481 * @dwork: work to queue
1482 * @delay: number of jiffies to wait before queueing
1484 * mod_delayed_work_on() on local CPU.
1486 bool mod_delayed_work(struct workqueue_struct *wq, struct delayed_work *dwork,
1487 unsigned long delay)
1489 return mod_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
1491 EXPORT_SYMBOL_GPL(mod_delayed_work);
1494 * worker_enter_idle - enter idle state
1495 * @worker: worker which is entering idle state
1497 * @worker is entering idle state. Update stats and idle timer if
1501 * spin_lock_irq(gcwq->lock).
1503 static void worker_enter_idle(struct worker *worker)
1505 struct worker_pool *pool = worker->pool;
1506 struct global_cwq *gcwq = pool->gcwq;
1508 BUG_ON(worker->flags & WORKER_IDLE);
1509 BUG_ON(!list_empty(&worker->entry) &&
1510 (worker->hentry.next || worker->hentry.pprev));
1512 /* can't use worker_set_flags(), also called from start_worker() */
1513 worker->flags |= WORKER_IDLE;
1515 worker->last_active = jiffies;
1517 /* idle_list is LIFO */
1518 list_add(&worker->entry, &pool->idle_list);
1520 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1521 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1524 * Sanity check nr_running. Because gcwq_unbind_fn() releases
1525 * gcwq->lock between setting %WORKER_UNBOUND and zapping
1526 * nr_running, the warning may trigger spuriously. Check iff
1527 * unbind is not in progress.
1529 WARN_ON_ONCE(!(gcwq->flags & GCWQ_DISASSOCIATED) &&
1530 pool->nr_workers == pool->nr_idle &&
1531 atomic_read(get_pool_nr_running(pool)));
1535 * worker_leave_idle - leave idle state
1536 * @worker: worker which is leaving idle state
1538 * @worker is leaving idle state. Update stats.
1541 * spin_lock_irq(gcwq->lock).
1543 static void worker_leave_idle(struct worker *worker)
1545 struct worker_pool *pool = worker->pool;
1547 BUG_ON(!(worker->flags & WORKER_IDLE));
1548 worker_clr_flags(worker, WORKER_IDLE);
1550 list_del_init(&worker->entry);
1554 * worker_maybe_bind_and_lock - bind worker to its cpu if possible and lock gcwq
1557 * Works which are scheduled while the cpu is online must at least be
1558 * scheduled to a worker which is bound to the cpu so that if they are
1559 * flushed from cpu callbacks while cpu is going down, they are
1560 * guaranteed to execute on the cpu.
1562 * This function is to be used by rogue workers and rescuers to bind
1563 * themselves to the target cpu and may race with cpu going down or
1564 * coming online. kthread_bind() can't be used because it may put the
1565 * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1566 * verbatim as it's best effort and blocking and gcwq may be
1567 * [dis]associated in the meantime.
1569 * This function tries set_cpus_allowed() and locks gcwq and verifies the
1570 * binding against %GCWQ_DISASSOCIATED which is set during
1571 * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
1572 * enters idle state or fetches works without dropping lock, it can
1573 * guarantee the scheduling requirement described in the first paragraph.
1576 * Might sleep. Called without any lock but returns with gcwq->lock
1580 * %true if the associated gcwq is online (@worker is successfully
1581 * bound), %false if offline.
1583 static bool worker_maybe_bind_and_lock(struct worker *worker)
1584 __acquires(&gcwq->lock)
1586 struct global_cwq *gcwq = worker->pool->gcwq;
1587 struct task_struct *task = worker->task;
1591 * The following call may fail, succeed or succeed
1592 * without actually migrating the task to the cpu if
1593 * it races with cpu hotunplug operation. Verify
1594 * against GCWQ_DISASSOCIATED.
1596 if (!(gcwq->flags & GCWQ_DISASSOCIATED))
1597 set_cpus_allowed_ptr(task, get_cpu_mask(gcwq->cpu));
1599 spin_lock_irq(&gcwq->lock);
1600 if (gcwq->flags & GCWQ_DISASSOCIATED)
1602 if (task_cpu(task) == gcwq->cpu &&
1603 cpumask_equal(¤t->cpus_allowed,
1604 get_cpu_mask(gcwq->cpu)))
1606 spin_unlock_irq(&gcwq->lock);
1609 * We've raced with CPU hot[un]plug. Give it a breather
1610 * and retry migration. cond_resched() is required here;
1611 * otherwise, we might deadlock against cpu_stop trying to
1612 * bring down the CPU on non-preemptive kernel.
1620 * Rebind an idle @worker to its CPU. worker_thread() will test
1621 * list_empty(@worker->entry) 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 may go down again inbetween, clear UNBOUND only on success */
1628 if (worker_maybe_bind_and_lock(worker))
1629 worker_clr_flags(worker, WORKER_UNBOUND);
1631 /* rebind complete, become available again */
1632 list_add(&worker->entry, &worker->pool->idle_list);
1633 spin_unlock_irq(&gcwq->lock);
1637 * Function for @worker->rebind.work used to rebind unbound busy workers to
1638 * the associated cpu which is coming back online. This is scheduled by
1639 * cpu up but can race with other cpu hotplug operations and may be
1640 * executed twice without intervening cpu down.
1642 static void busy_worker_rebind_fn(struct work_struct *work)
1644 struct worker *worker = container_of(work, struct worker, rebind_work);
1645 struct global_cwq *gcwq = worker->pool->gcwq;
1647 if (worker_maybe_bind_and_lock(worker))
1648 worker_clr_flags(worker, WORKER_UNBOUND);
1650 spin_unlock_irq(&gcwq->lock);
1654 * rebind_workers - rebind all workers of a gcwq to the associated CPU
1655 * @gcwq: gcwq of interest
1657 * @gcwq->cpu is coming online. Rebind all workers to the CPU. Rebinding
1658 * is different for idle and busy ones.
1660 * Idle ones will be removed from the idle_list and woken up. They will
1661 * add themselves back after completing rebind. This ensures that the
1662 * idle_list doesn't contain any unbound workers when re-bound busy workers
1663 * try to perform local wake-ups for concurrency management.
1665 * Busy workers can rebind after they finish their current work items.
1666 * Queueing the rebind work item at the head of the scheduled list is
1667 * enough. Note that nr_running will be properly bumped as busy workers
1670 * On return, all non-manager workers are scheduled for rebind - see
1671 * manage_workers() for the manager special case. Any idle worker
1672 * including the manager will not appear on @idle_list until rebind is
1673 * complete, making local wake-ups safe.
1675 static void rebind_workers(struct global_cwq *gcwq)
1677 struct worker_pool *pool;
1678 struct worker *worker, *n;
1679 struct hlist_node *pos;
1682 lockdep_assert_held(&gcwq->lock);
1684 for_each_worker_pool(pool, gcwq)
1685 lockdep_assert_held(&pool->assoc_mutex);
1687 /* dequeue and kick idle ones */
1688 for_each_worker_pool(pool, gcwq) {
1689 list_for_each_entry_safe(worker, n, &pool->idle_list, entry) {
1691 * idle workers should be off @pool->idle_list
1692 * until rebind is complete to avoid receiving
1693 * premature local wake-ups.
1695 list_del_init(&worker->entry);
1698 * worker_thread() will see the above dequeuing
1699 * and call idle_worker_rebind().
1701 wake_up_process(worker->task);
1705 /* rebind busy workers */
1706 for_each_busy_worker(worker, i, pos, gcwq) {
1707 struct work_struct *rebind_work = &worker->rebind_work;
1708 struct workqueue_struct *wq;
1710 if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
1711 work_data_bits(rebind_work)))
1714 debug_work_activate(rebind_work);
1717 * wq doesn't really matter but let's keep @worker->pool
1718 * and @cwq->pool consistent for sanity.
1720 if (worker_pool_pri(worker->pool))
1721 wq = system_highpri_wq;
1725 insert_work(get_cwq(gcwq->cpu, wq), rebind_work,
1726 worker->scheduled.next,
1727 work_color_to_flags(WORK_NO_COLOR));
1731 static struct worker *alloc_worker(void)
1733 struct worker *worker;
1735 worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1737 INIT_LIST_HEAD(&worker->entry);
1738 INIT_LIST_HEAD(&worker->scheduled);
1739 INIT_WORK(&worker->rebind_work, busy_worker_rebind_fn);
1740 /* on creation a worker is in !idle && prep state */
1741 worker->flags = WORKER_PREP;
1747 * create_worker - create a new workqueue worker
1748 * @pool: pool the new worker will belong to
1750 * Create a new worker which is bound to @pool. The returned worker
1751 * can be started by calling start_worker() or destroyed using
1755 * Might sleep. Does GFP_KERNEL allocations.
1758 * Pointer to the newly created worker.
1760 static struct worker *create_worker(struct worker_pool *pool)
1762 struct global_cwq *gcwq = pool->gcwq;
1763 const char *pri = worker_pool_pri(pool) ? "H" : "";
1764 struct worker *worker = NULL;
1767 spin_lock_irq(&gcwq->lock);
1768 while (ida_get_new(&pool->worker_ida, &id)) {
1769 spin_unlock_irq(&gcwq->lock);
1770 if (!ida_pre_get(&pool->worker_ida, GFP_KERNEL))
1772 spin_lock_irq(&gcwq->lock);
1774 spin_unlock_irq(&gcwq->lock);
1776 worker = alloc_worker();
1780 worker->pool = pool;
1783 if (gcwq->cpu != WORK_CPU_UNBOUND)
1784 worker->task = kthread_create_on_node(worker_thread,
1785 worker, cpu_to_node(gcwq->cpu),
1786 "kworker/%u:%d%s", gcwq->cpu, id, pri);
1788 worker->task = kthread_create(worker_thread, worker,
1789 "kworker/u:%d%s", id, pri);
1790 if (IS_ERR(worker->task))
1793 if (worker_pool_pri(pool))
1794 set_user_nice(worker->task, HIGHPRI_NICE_LEVEL);
1797 * Determine CPU binding of the new worker depending on
1798 * %GCWQ_DISASSOCIATED. The caller is responsible for ensuring the
1799 * flag remains stable across this function. See the comments
1800 * above the flag definition for details.
1802 * As an unbound worker may later become a regular one if CPU comes
1803 * online, make sure every worker has %PF_THREAD_BOUND set.
1805 if (!(gcwq->flags & GCWQ_DISASSOCIATED)) {
1806 kthread_bind(worker->task, gcwq->cpu);
1808 worker->task->flags |= PF_THREAD_BOUND;
1809 worker->flags |= WORKER_UNBOUND;
1815 spin_lock_irq(&gcwq->lock);
1816 ida_remove(&pool->worker_ida, id);
1817 spin_unlock_irq(&gcwq->lock);
1824 * start_worker - start a newly created worker
1825 * @worker: worker to start
1827 * Make the gcwq aware of @worker and start it.
1830 * spin_lock_irq(gcwq->lock).
1832 static void start_worker(struct worker *worker)
1834 worker->flags |= WORKER_STARTED;
1835 worker->pool->nr_workers++;
1836 worker_enter_idle(worker);
1837 wake_up_process(worker->task);
1841 * destroy_worker - destroy a workqueue worker
1842 * @worker: worker to be destroyed
1844 * Destroy @worker and adjust @gcwq stats accordingly.
1847 * spin_lock_irq(gcwq->lock) which is released and regrabbed.
1849 static void destroy_worker(struct worker *worker)
1851 struct worker_pool *pool = worker->pool;
1852 struct global_cwq *gcwq = pool->gcwq;
1853 int id = worker->id;
1855 /* sanity check frenzy */
1856 BUG_ON(worker->current_work);
1857 BUG_ON(!list_empty(&worker->scheduled));
1859 if (worker->flags & WORKER_STARTED)
1861 if (worker->flags & WORKER_IDLE)
1864 list_del_init(&worker->entry);
1865 worker->flags |= WORKER_DIE;
1867 spin_unlock_irq(&gcwq->lock);
1869 kthread_stop(worker->task);
1872 spin_lock_irq(&gcwq->lock);
1873 ida_remove(&pool->worker_ida, id);
1876 static void idle_worker_timeout(unsigned long __pool)
1878 struct worker_pool *pool = (void *)__pool;
1879 struct global_cwq *gcwq = pool->gcwq;
1881 spin_lock_irq(&gcwq->lock);
1883 if (too_many_workers(pool)) {
1884 struct worker *worker;
1885 unsigned long expires;
1887 /* idle_list is kept in LIFO order, check the last one */
1888 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1889 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1891 if (time_before(jiffies, expires))
1892 mod_timer(&pool->idle_timer, expires);
1894 /* it's been idle for too long, wake up manager */
1895 pool->flags |= POOL_MANAGE_WORKERS;
1896 wake_up_worker(pool);
1900 spin_unlock_irq(&gcwq->lock);
1903 static bool send_mayday(struct work_struct *work)
1905 struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1906 struct workqueue_struct *wq = cwq->wq;
1909 if (!(wq->flags & WQ_RESCUER))
1912 /* mayday mayday mayday */
1913 cpu = cwq->pool->gcwq->cpu;
1914 /* WORK_CPU_UNBOUND can't be set in cpumask, use cpu 0 instead */
1915 if (cpu == WORK_CPU_UNBOUND)
1917 if (!mayday_test_and_set_cpu(cpu, wq->mayday_mask))
1918 wake_up_process(wq->rescuer->task);
1922 static void gcwq_mayday_timeout(unsigned long __pool)
1924 struct worker_pool *pool = (void *)__pool;
1925 struct global_cwq *gcwq = pool->gcwq;
1926 struct work_struct *work;
1928 spin_lock_irq(&gcwq->lock);
1930 if (need_to_create_worker(pool)) {
1932 * We've been trying to create a new worker but
1933 * haven't been successful. We might be hitting an
1934 * allocation deadlock. Send distress signals to
1937 list_for_each_entry(work, &pool->worklist, entry)
1941 spin_unlock_irq(&gcwq->lock);
1943 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1947 * maybe_create_worker - create a new worker if necessary
1948 * @pool: pool to create a new worker for
1950 * Create a new worker for @pool if necessary. @pool is guaranteed to
1951 * have at least one idle worker on return from this function. If
1952 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1953 * sent to all rescuers with works scheduled on @pool to resolve
1954 * possible allocation deadlock.
1956 * On return, need_to_create_worker() is guaranteed to be false and
1957 * may_start_working() true.
1960 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1961 * multiple times. Does GFP_KERNEL allocations. Called only from
1965 * false if no action was taken and gcwq->lock stayed locked, true
1968 static bool maybe_create_worker(struct worker_pool *pool)
1969 __releases(&gcwq->lock)
1970 __acquires(&gcwq->lock)
1972 struct global_cwq *gcwq = pool->gcwq;
1974 if (!need_to_create_worker(pool))
1977 spin_unlock_irq(&gcwq->lock);
1979 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1980 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1983 struct worker *worker;
1985 worker = create_worker(pool);
1987 del_timer_sync(&pool->mayday_timer);
1988 spin_lock_irq(&gcwq->lock);
1989 start_worker(worker);
1990 BUG_ON(need_to_create_worker(pool));
1994 if (!need_to_create_worker(pool))
1997 __set_current_state(TASK_INTERRUPTIBLE);
1998 schedule_timeout(CREATE_COOLDOWN);
2000 if (!need_to_create_worker(pool))
2004 del_timer_sync(&pool->mayday_timer);
2005 spin_lock_irq(&gcwq->lock);
2006 if (need_to_create_worker(pool))
2012 * maybe_destroy_worker - destroy workers which have been idle for a while
2013 * @pool: pool to destroy workers for
2015 * Destroy @pool workers which have been idle for longer than
2016 * IDLE_WORKER_TIMEOUT.
2019 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2020 * multiple times. Called only from manager.
2023 * false if no action was taken and gcwq->lock stayed locked, true
2026 static bool maybe_destroy_workers(struct worker_pool *pool)
2030 while (too_many_workers(pool)) {
2031 struct worker *worker;
2032 unsigned long expires;
2034 worker = list_entry(pool->idle_list.prev, struct worker, entry);
2035 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2037 if (time_before(jiffies, expires)) {
2038 mod_timer(&pool->idle_timer, expires);
2042 destroy_worker(worker);
2050 * manage_workers - manage worker pool
2053 * Assume the manager role and manage gcwq worker pool @worker belongs
2054 * to. At any given time, there can be only zero or one manager per
2055 * gcwq. The exclusion is handled automatically by this function.
2057 * The caller can safely start processing works on false return. On
2058 * true return, it's guaranteed that need_to_create_worker() is false
2059 * and may_start_working() is true.
2062 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2063 * multiple times. Does GFP_KERNEL allocations.
2066 * false if no action was taken and gcwq->lock stayed locked, true if
2067 * some action was taken.
2069 static bool manage_workers(struct worker *worker)
2071 struct worker_pool *pool = worker->pool;
2074 if (pool->flags & POOL_MANAGING_WORKERS)
2077 pool->flags |= POOL_MANAGING_WORKERS;
2080 * To simplify both worker management and CPU hotplug, hold off
2081 * management while hotplug is in progress. CPU hotplug path can't
2082 * grab %POOL_MANAGING_WORKERS to achieve this because that can
2083 * lead to idle worker depletion (all become busy thinking someone
2084 * else is managing) which in turn can result in deadlock under
2085 * extreme circumstances. Use @pool->assoc_mutex to synchronize
2086 * manager against CPU hotplug.
2088 * assoc_mutex would always be free unless CPU hotplug is in
2089 * progress. trylock first without dropping @gcwq->lock.
2091 if (unlikely(!mutex_trylock(&pool->assoc_mutex))) {
2092 spin_unlock_irq(&pool->gcwq->lock);
2093 mutex_lock(&pool->assoc_mutex);
2095 * CPU hotplug could have happened while we were waiting
2096 * for assoc_mutex. Hotplug itself can't handle us
2097 * because manager isn't either on idle or busy list, and
2098 * @gcwq's state and ours could have deviated.
2100 * As hotplug is now excluded via assoc_mutex, we can
2101 * simply try to bind. It will succeed or fail depending
2102 * on @gcwq's current state. Try it and adjust
2103 * %WORKER_UNBOUND accordingly.
2105 if (worker_maybe_bind_and_lock(worker))
2106 worker->flags &= ~WORKER_UNBOUND;
2108 worker->flags |= WORKER_UNBOUND;
2113 pool->flags &= ~POOL_MANAGE_WORKERS;
2116 * Destroy and then create so that may_start_working() is true
2119 ret |= maybe_destroy_workers(pool);
2120 ret |= maybe_create_worker(pool);
2122 pool->flags &= ~POOL_MANAGING_WORKERS;
2123 mutex_unlock(&pool->assoc_mutex);
2128 * process_one_work - process single work
2130 * @work: work to process
2132 * Process @work. This function contains all the logics necessary to
2133 * process a single work including synchronization against and
2134 * interaction with other workers on the same cpu, queueing and
2135 * flushing. As long as context requirement is met, any worker can
2136 * call this function to process a work.
2139 * spin_lock_irq(gcwq->lock) which is released and regrabbed.
2141 static void process_one_work(struct worker *worker, struct work_struct *work)
2142 __releases(&gcwq->lock)
2143 __acquires(&gcwq->lock)
2145 struct cpu_workqueue_struct *cwq = get_work_cwq(work);
2146 struct worker_pool *pool = worker->pool;
2147 struct global_cwq *gcwq = pool->gcwq;
2148 bool cpu_intensive = cwq->wq->flags & WQ_CPU_INTENSIVE;
2150 struct worker *collision;
2151 #ifdef CONFIG_LOCKDEP
2153 * It is permissible to free the struct work_struct from
2154 * inside the function that is called from it, this we need to
2155 * take into account for lockdep too. To avoid bogus "held
2156 * lock freed" warnings as well as problems when looking into
2157 * work->lockdep_map, make a copy and use that here.
2159 struct lockdep_map lockdep_map;
2161 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
2164 * Ensure we're on the correct CPU. DISASSOCIATED test is
2165 * necessary to avoid spurious warnings from rescuers servicing the
2166 * unbound or a disassociated gcwq.
2168 WARN_ON_ONCE(!(worker->flags & WORKER_UNBOUND) &&
2169 !(gcwq->flags & GCWQ_DISASSOCIATED) &&
2170 raw_smp_processor_id() != gcwq->cpu);
2173 * A single work shouldn't be executed concurrently by
2174 * multiple workers on a single cpu. Check whether anyone is
2175 * already processing the work. If so, defer the work to the
2176 * currently executing one.
2178 collision = find_worker_executing_work(gcwq, work);
2179 if (unlikely(collision)) {
2180 move_linked_works(work, &collision->scheduled, NULL);
2184 /* claim and dequeue */
2185 debug_work_deactivate(work);
2186 hash_add(gcwq->busy_hash, &worker->hentry, (unsigned long)work);
2187 worker->current_work = work;
2188 worker->current_func = work->func;
2189 worker->current_cwq = cwq;
2190 work_color = get_work_color(work);
2192 list_del_init(&work->entry);
2195 * CPU intensive works don't participate in concurrency
2196 * management. They're the scheduler's responsibility.
2198 if (unlikely(cpu_intensive))
2199 worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
2202 * Unbound gcwq isn't concurrency managed and work items should be
2203 * executed ASAP. Wake up another worker if necessary.
2205 if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
2206 wake_up_worker(pool);
2209 * Record the last CPU and clear PENDING which should be the last
2210 * update to @work. Also, do this inside @gcwq->lock so that
2211 * PENDING and queued state changes happen together while IRQ is
2214 set_work_cpu_and_clear_pending(work, gcwq->cpu);
2216 spin_unlock_irq(&gcwq->lock);
2218 lock_map_acquire_read(&cwq->wq->lockdep_map);
2219 lock_map_acquire(&lockdep_map);
2220 trace_workqueue_execute_start(work);
2221 worker->current_func(work);
2223 * While we must be careful to not use "work" after this, the trace
2224 * point will only record its address.
2226 trace_workqueue_execute_end(work);
2227 lock_map_release(&lockdep_map);
2228 lock_map_release(&cwq->wq->lockdep_map);
2230 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2231 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2232 " last function: %pf\n",
2233 current->comm, preempt_count(), task_pid_nr(current),
2234 worker->current_func);
2235 debug_show_held_locks(current);
2239 spin_lock_irq(&gcwq->lock);
2241 /* clear cpu intensive status */
2242 if (unlikely(cpu_intensive))
2243 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2245 /* we're done with it, release */
2246 hash_del(&worker->hentry);
2247 worker->current_work = NULL;
2248 worker->current_func = NULL;
2249 worker->current_cwq = NULL;
2250 cwq_dec_nr_in_flight(cwq, work_color);
2254 * process_scheduled_works - process scheduled works
2257 * Process all scheduled works. Please note that the scheduled list
2258 * may change while processing a work, so this function repeatedly
2259 * fetches a work from the top and executes it.
2262 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2265 static void process_scheduled_works(struct worker *worker)
2267 while (!list_empty(&worker->scheduled)) {
2268 struct work_struct *work = list_first_entry(&worker->scheduled,
2269 struct work_struct, entry);
2270 process_one_work(worker, work);
2275 * worker_thread - the worker thread function
2278 * The gcwq worker thread function. There's a single dynamic pool of
2279 * these per each cpu. These workers process all works regardless of
2280 * their specific target workqueue. The only exception is works which
2281 * belong to workqueues with a rescuer which will be explained in
2284 static int worker_thread(void *__worker)
2286 struct worker *worker = __worker;
2287 struct worker_pool *pool = worker->pool;
2288 struct global_cwq *gcwq = pool->gcwq;
2290 /* tell the scheduler that this is a workqueue worker */
2291 worker->task->flags |= PF_WQ_WORKER;
2293 spin_lock_irq(&gcwq->lock);
2295 /* we are off idle list if destruction or rebind is requested */
2296 if (unlikely(list_empty(&worker->entry))) {
2297 spin_unlock_irq(&gcwq->lock);
2299 /* if DIE is set, destruction is requested */
2300 if (worker->flags & WORKER_DIE) {
2301 worker->task->flags &= ~PF_WQ_WORKER;
2305 /* otherwise, rebind */
2306 idle_worker_rebind(worker);
2310 worker_leave_idle(worker);
2312 /* no more worker necessary? */
2313 if (!need_more_worker(pool))
2316 /* do we need to manage? */
2317 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2321 * ->scheduled list can only be filled while a worker is
2322 * preparing to process a work or actually processing it.
2323 * Make sure nobody diddled with it while I was sleeping.
2325 BUG_ON(!list_empty(&worker->scheduled));
2328 * When control reaches this point, we're guaranteed to have
2329 * at least one idle worker or that someone else has already
2330 * assumed the manager role.
2332 worker_clr_flags(worker, WORKER_PREP);
2335 struct work_struct *work =
2336 list_first_entry(&pool->worklist,
2337 struct work_struct, entry);
2339 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2340 /* optimization path, not strictly necessary */
2341 process_one_work(worker, work);
2342 if (unlikely(!list_empty(&worker->scheduled)))
2343 process_scheduled_works(worker);
2345 move_linked_works(work, &worker->scheduled, NULL);
2346 process_scheduled_works(worker);
2348 } while (keep_working(pool));
2350 worker_set_flags(worker, WORKER_PREP, false);
2352 if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
2356 * gcwq->lock is held and there's no work to process and no
2357 * need to manage, sleep. Workers are woken up only while
2358 * holding gcwq->lock or from local cpu, so setting the
2359 * current state before releasing gcwq->lock is enough to
2360 * prevent losing any event.
2362 worker_enter_idle(worker);
2363 __set_current_state(TASK_INTERRUPTIBLE);
2364 spin_unlock_irq(&gcwq->lock);
2370 * rescuer_thread - the rescuer thread function
2373 * Workqueue rescuer thread function. There's one rescuer for each
2374 * workqueue which has WQ_RESCUER set.
2376 * Regular work processing on a gcwq may block trying to create a new
2377 * worker which uses GFP_KERNEL allocation which has slight chance of
2378 * developing into deadlock if some works currently on the same queue
2379 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2380 * the problem rescuer solves.
2382 * When such condition is possible, the gcwq summons rescuers of all
2383 * workqueues which have works queued on the gcwq and let them process
2384 * those works so that forward progress can be guaranteed.
2386 * This should happen rarely.
2388 static int rescuer_thread(void *__rescuer)
2390 struct worker *rescuer = __rescuer;
2391 struct workqueue_struct *wq = rescuer->rescue_wq;
2392 struct list_head *scheduled = &rescuer->scheduled;
2393 bool is_unbound = wq->flags & WQ_UNBOUND;
2396 set_user_nice(current, RESCUER_NICE_LEVEL);
2399 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2400 * doesn't participate in concurrency management.
2402 rescuer->task->flags |= PF_WQ_WORKER;
2404 set_current_state(TASK_INTERRUPTIBLE);
2406 if (kthread_should_stop()) {
2407 __set_current_state(TASK_RUNNING);
2408 rescuer->task->flags &= ~PF_WQ_WORKER;
2413 * See whether any cpu is asking for help. Unbounded
2414 * workqueues use cpu 0 in mayday_mask for CPU_UNBOUND.
2416 for_each_mayday_cpu(cpu, wq->mayday_mask) {
2417 unsigned int tcpu = is_unbound ? WORK_CPU_UNBOUND : cpu;
2418 struct cpu_workqueue_struct *cwq = get_cwq(tcpu, wq);
2419 struct worker_pool *pool = cwq->pool;
2420 struct global_cwq *gcwq = pool->gcwq;
2421 struct work_struct *work, *n;
2423 __set_current_state(TASK_RUNNING);
2424 mayday_clear_cpu(cpu, wq->mayday_mask);
2426 /* migrate to the target cpu if possible */
2427 rescuer->pool = pool;
2428 worker_maybe_bind_and_lock(rescuer);
2431 * Slurp in all works issued via this workqueue and
2434 BUG_ON(!list_empty(&rescuer->scheduled));
2435 list_for_each_entry_safe(work, n, &pool->worklist, entry)
2436 if (get_work_cwq(work) == cwq)
2437 move_linked_works(work, scheduled, &n);
2439 process_scheduled_works(rescuer);
2442 * Leave this gcwq. If keep_working() is %true, notify a
2443 * regular worker; otherwise, we end up with 0 concurrency
2444 * and stalling the execution.
2446 if (keep_working(pool))
2447 wake_up_worker(pool);
2449 spin_unlock_irq(&gcwq->lock);
2452 /* rescuers should never participate in concurrency management */
2453 WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2459 struct work_struct work;
2460 struct completion done;
2463 static void wq_barrier_func(struct work_struct *work)
2465 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2466 complete(&barr->done);
2470 * insert_wq_barrier - insert a barrier work
2471 * @cwq: cwq to insert barrier into
2472 * @barr: wq_barrier to insert
2473 * @target: target work to attach @barr to
2474 * @worker: worker currently executing @target, NULL if @target is not executing
2476 * @barr is linked to @target such that @barr is completed only after
2477 * @target finishes execution. Please note that the ordering
2478 * guarantee is observed only with respect to @target and on the local
2481 * Currently, a queued barrier can't be canceled. This is because
2482 * try_to_grab_pending() can't determine whether the work to be
2483 * grabbed is at the head of the queue and thus can't clear LINKED
2484 * flag of the previous work while there must be a valid next work
2485 * after a work with LINKED flag set.
2487 * Note that when @worker is non-NULL, @target may be modified
2488 * underneath us, so we can't reliably determine cwq from @target.
2491 * spin_lock_irq(gcwq->lock).
2493 static void insert_wq_barrier(struct cpu_workqueue_struct *cwq,
2494 struct wq_barrier *barr,
2495 struct work_struct *target, struct worker *worker)
2497 struct list_head *head;
2498 unsigned int linked = 0;
2501 * debugobject calls are safe here even with gcwq->lock locked
2502 * as we know for sure that this will not trigger any of the
2503 * checks and call back into the fixup functions where we
2506 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2507 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2508 init_completion(&barr->done);
2511 * If @target is currently being executed, schedule the
2512 * barrier to the worker; otherwise, put it after @target.
2515 head = worker->scheduled.next;
2517 unsigned long *bits = work_data_bits(target);
2519 head = target->entry.next;
2520 /* there can already be other linked works, inherit and set */
2521 linked = *bits & WORK_STRUCT_LINKED;
2522 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2525 debug_work_activate(&barr->work);
2526 insert_work(cwq, &barr->work, head,
2527 work_color_to_flags(WORK_NO_COLOR) | linked);
2531 * flush_workqueue_prep_cwqs - prepare cwqs for workqueue flushing
2532 * @wq: workqueue being flushed
2533 * @flush_color: new flush color, < 0 for no-op
2534 * @work_color: new work color, < 0 for no-op
2536 * Prepare cwqs for workqueue flushing.
2538 * If @flush_color is non-negative, flush_color on all cwqs should be
2539 * -1. If no cwq has in-flight commands at the specified color, all
2540 * cwq->flush_color's stay at -1 and %false is returned. If any cwq
2541 * has in flight commands, its cwq->flush_color is set to
2542 * @flush_color, @wq->nr_cwqs_to_flush is updated accordingly, cwq
2543 * wakeup logic is armed and %true is returned.
2545 * The caller should have initialized @wq->first_flusher prior to
2546 * calling this function with non-negative @flush_color. If
2547 * @flush_color is negative, no flush color update is done and %false
2550 * If @work_color is non-negative, all cwqs should have the same
2551 * work_color which is previous to @work_color and all will be
2552 * advanced to @work_color.
2555 * mutex_lock(wq->flush_mutex).
2558 * %true if @flush_color >= 0 and there's something to flush. %false
2561 static bool flush_workqueue_prep_cwqs(struct workqueue_struct *wq,
2562 int flush_color, int work_color)
2567 if (flush_color >= 0) {
2568 BUG_ON(atomic_read(&wq->nr_cwqs_to_flush));
2569 atomic_set(&wq->nr_cwqs_to_flush, 1);
2572 for_each_cwq_cpu(cpu, wq) {
2573 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2574 struct global_cwq *gcwq = cwq->pool->gcwq;
2576 spin_lock_irq(&gcwq->lock);
2578 if (flush_color >= 0) {
2579 BUG_ON(cwq->flush_color != -1);
2581 if (cwq->nr_in_flight[flush_color]) {
2582 cwq->flush_color = flush_color;
2583 atomic_inc(&wq->nr_cwqs_to_flush);
2588 if (work_color >= 0) {
2589 BUG_ON(work_color != work_next_color(cwq->work_color));
2590 cwq->work_color = work_color;
2593 spin_unlock_irq(&gcwq->lock);
2596 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_cwqs_to_flush))
2597 complete(&wq->first_flusher->done);
2603 * flush_workqueue - ensure that any scheduled work has run to completion.
2604 * @wq: workqueue to flush
2606 * Forces execution of the workqueue and blocks until its completion.
2607 * This is typically used in driver shutdown handlers.
2609 * We sleep until all works which were queued on entry have been handled,
2610 * but we are not livelocked by new incoming ones.
2612 void flush_workqueue(struct workqueue_struct *wq)
2614 struct wq_flusher this_flusher = {
2615 .list = LIST_HEAD_INIT(this_flusher.list),
2617 .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
2621 lock_map_acquire(&wq->lockdep_map);
2622 lock_map_release(&wq->lockdep_map);
2624 mutex_lock(&wq->flush_mutex);
2627 * Start-to-wait phase
2629 next_color = work_next_color(wq->work_color);
2631 if (next_color != wq->flush_color) {
2633 * Color space is not full. The current work_color
2634 * becomes our flush_color and work_color is advanced
2637 BUG_ON(!list_empty(&wq->flusher_overflow));
2638 this_flusher.flush_color = wq->work_color;
2639 wq->work_color = next_color;
2641 if (!wq->first_flusher) {
2642 /* no flush in progress, become the first flusher */
2643 BUG_ON(wq->flush_color != this_flusher.flush_color);
2645 wq->first_flusher = &this_flusher;
2647 if (!flush_workqueue_prep_cwqs(wq, wq->flush_color,
2649 /* nothing to flush, done */
2650 wq->flush_color = next_color;
2651 wq->first_flusher = NULL;
2656 BUG_ON(wq->flush_color == this_flusher.flush_color);
2657 list_add_tail(&this_flusher.list, &wq->flusher_queue);
2658 flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2662 * Oops, color space is full, wait on overflow queue.
2663 * The next flush completion will assign us
2664 * flush_color and transfer to flusher_queue.
2666 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2669 mutex_unlock(&wq->flush_mutex);
2671 wait_for_completion(&this_flusher.done);
2674 * Wake-up-and-cascade phase
2676 * First flushers are responsible for cascading flushes and
2677 * handling overflow. Non-first flushers can simply return.
2679 if (wq->first_flusher != &this_flusher)
2682 mutex_lock(&wq->flush_mutex);
2684 /* we might have raced, check again with mutex held */
2685 if (wq->first_flusher != &this_flusher)
2688 wq->first_flusher = NULL;
2690 BUG_ON(!list_empty(&this_flusher.list));
2691 BUG_ON(wq->flush_color != this_flusher.flush_color);
2694 struct wq_flusher *next, *tmp;
2696 /* complete all the flushers sharing the current flush color */
2697 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2698 if (next->flush_color != wq->flush_color)
2700 list_del_init(&next->list);
2701 complete(&next->done);
2704 BUG_ON(!list_empty(&wq->flusher_overflow) &&
2705 wq->flush_color != work_next_color(wq->work_color));
2707 /* this flush_color is finished, advance by one */
2708 wq->flush_color = work_next_color(wq->flush_color);
2710 /* one color has been freed, handle overflow queue */
2711 if (!list_empty(&wq->flusher_overflow)) {
2713 * Assign the same color to all overflowed
2714 * flushers, advance work_color and append to
2715 * flusher_queue. This is the start-to-wait
2716 * phase for these overflowed flushers.
2718 list_for_each_entry(tmp, &wq->flusher_overflow, list)
2719 tmp->flush_color = wq->work_color;
2721 wq->work_color = work_next_color(wq->work_color);
2723 list_splice_tail_init(&wq->flusher_overflow,
2724 &wq->flusher_queue);
2725 flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2728 if (list_empty(&wq->flusher_queue)) {
2729 BUG_ON(wq->flush_color != wq->work_color);
2734 * Need to flush more colors. Make the next flusher
2735 * the new first flusher and arm cwqs.
2737 BUG_ON(wq->flush_color == wq->work_color);
2738 BUG_ON(wq->flush_color != next->flush_color);
2740 list_del_init(&next->list);
2741 wq->first_flusher = next;
2743 if (flush_workqueue_prep_cwqs(wq, wq->flush_color, -1))
2747 * Meh... this color is already done, clear first
2748 * flusher and repeat cascading.
2750 wq->first_flusher = NULL;
2754 mutex_unlock(&wq->flush_mutex);
2756 EXPORT_SYMBOL_GPL(flush_workqueue);
2759 * drain_workqueue - drain a workqueue
2760 * @wq: workqueue to drain
2762 * Wait until the workqueue becomes empty. While draining is in progress,
2763 * only chain queueing is allowed. IOW, only currently pending or running
2764 * work items on @wq can queue further work items on it. @wq is flushed
2765 * repeatedly until it becomes empty. The number of flushing is detemined
2766 * by the depth of chaining and should be relatively short. Whine if it
2769 void drain_workqueue(struct workqueue_struct *wq)
2771 unsigned int flush_cnt = 0;
2775 * __queue_work() needs to test whether there are drainers, is much
2776 * hotter than drain_workqueue() and already looks at @wq->flags.
2777 * Use WQ_DRAINING so that queue doesn't have to check nr_drainers.
2779 spin_lock(&workqueue_lock);
2780 if (!wq->nr_drainers++)
2781 wq->flags |= WQ_DRAINING;
2782 spin_unlock(&workqueue_lock);
2784 flush_workqueue(wq);
2786 for_each_cwq_cpu(cpu, wq) {
2787 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2790 spin_lock_irq(&cwq->pool->gcwq->lock);
2791 drained = !cwq->nr_active && list_empty(&cwq->delayed_works);
2792 spin_unlock_irq(&cwq->pool->gcwq->lock);
2797 if (++flush_cnt == 10 ||
2798 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2799 pr_warn("workqueue %s: flush on destruction isn't complete after %u tries\n",
2800 wq->name, flush_cnt);
2804 spin_lock(&workqueue_lock);
2805 if (!--wq->nr_drainers)
2806 wq->flags &= ~WQ_DRAINING;
2807 spin_unlock(&workqueue_lock);
2809 EXPORT_SYMBOL_GPL(drain_workqueue);
2811 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2813 struct worker *worker = NULL;
2814 struct global_cwq *gcwq;
2815 struct cpu_workqueue_struct *cwq;
2818 gcwq = get_work_gcwq(work);
2822 spin_lock_irq(&gcwq->lock);
2823 if (!list_empty(&work->entry)) {
2825 * See the comment near try_to_grab_pending()->smp_rmb().
2826 * If it was re-queued to a different gcwq under us, we
2827 * are not going to wait.
2830 cwq = get_work_cwq(work);
2831 if (unlikely(!cwq || gcwq != cwq->pool->gcwq))
2834 worker = find_worker_executing_work(gcwq, work);
2837 cwq = worker->current_cwq;
2840 insert_wq_barrier(cwq, barr, work, worker);
2841 spin_unlock_irq(&gcwq->lock);
2844 * If @max_active is 1 or rescuer is in use, flushing another work
2845 * item on the same workqueue may lead to deadlock. Make sure the
2846 * flusher is not running on the same workqueue by verifying write
2849 if (cwq->wq->saved_max_active == 1 || cwq->wq->flags & WQ_RESCUER)
2850 lock_map_acquire(&cwq->wq->lockdep_map);
2852 lock_map_acquire_read(&cwq->wq->lockdep_map);
2853 lock_map_release(&cwq->wq->lockdep_map);
2857 spin_unlock_irq(&gcwq->lock);
2862 * flush_work - wait for a work to finish executing the last queueing instance
2863 * @work: the work to flush
2865 * Wait until @work has finished execution. @work is guaranteed to be idle
2866 * on return if it hasn't been requeued since flush started.
2869 * %true if flush_work() waited for the work to finish execution,
2870 * %false if it was already idle.
2872 bool flush_work(struct work_struct *work)
2874 struct wq_barrier barr;
2876 lock_map_acquire(&work->lockdep_map);
2877 lock_map_release(&work->lockdep_map);
2879 if (start_flush_work(work, &barr)) {
2880 wait_for_completion(&barr.done);
2881 destroy_work_on_stack(&barr.work);
2887 EXPORT_SYMBOL_GPL(flush_work);
2889 static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2891 unsigned long flags;
2895 ret = try_to_grab_pending(work, is_dwork, &flags);
2897 * If someone else is canceling, wait for the same event it
2898 * would be waiting for before retrying.
2900 if (unlikely(ret == -ENOENT))
2902 } while (unlikely(ret < 0));
2904 /* tell other tasks trying to grab @work to back off */
2905 mark_work_canceling(work);
2906 local_irq_restore(flags);
2909 clear_work_data(work);
2914 * cancel_work_sync - cancel a work and wait for it to finish
2915 * @work: the work to cancel
2917 * Cancel @work and wait for its execution to finish. This function
2918 * can be used even if the work re-queues itself or migrates to
2919 * another workqueue. On return from this function, @work is
2920 * guaranteed to be not pending or executing on any CPU.
2922 * cancel_work_sync(&delayed_work->work) must not be used for
2923 * delayed_work's. Use cancel_delayed_work_sync() instead.
2925 * The caller must ensure that the workqueue on which @work was last
2926 * queued can't be destroyed before this function returns.
2929 * %true if @work was pending, %false otherwise.
2931 bool cancel_work_sync(struct work_struct *work)
2933 return __cancel_work_timer(work, false);
2935 EXPORT_SYMBOL_GPL(cancel_work_sync);
2938 * flush_delayed_work - wait for a dwork to finish executing the last queueing
2939 * @dwork: the delayed work to flush
2941 * Delayed timer is cancelled and the pending work is queued for
2942 * immediate execution. Like flush_work(), this function only
2943 * considers the last queueing instance of @dwork.
2946 * %true if flush_work() waited for the work to finish execution,
2947 * %false if it was already idle.
2949 bool flush_delayed_work(struct delayed_work *dwork)
2951 local_irq_disable();
2952 if (del_timer_sync(&dwork->timer))
2953 __queue_work(dwork->cpu,
2954 get_work_cwq(&dwork->work)->wq, &dwork->work);
2956 return flush_work(&dwork->work);
2958 EXPORT_SYMBOL(flush_delayed_work);
2961 * cancel_delayed_work - cancel a delayed work
2962 * @dwork: delayed_work to cancel
2964 * Kill off a pending delayed_work. Returns %true if @dwork was pending
2965 * and canceled; %false if wasn't pending. Note that the work callback
2966 * function may still be running on return, unless it returns %true and the
2967 * work doesn't re-arm itself. Explicitly flush or use
2968 * cancel_delayed_work_sync() to wait on it.
2970 * This function is safe to call from any context including IRQ handler.
2972 bool cancel_delayed_work(struct delayed_work *dwork)
2974 unsigned long flags;
2978 ret = try_to_grab_pending(&dwork->work, true, &flags);
2979 } while (unlikely(ret == -EAGAIN));
2981 if (unlikely(ret < 0))
2984 set_work_cpu_and_clear_pending(&dwork->work, work_cpu(&dwork->work));
2985 local_irq_restore(flags);
2988 EXPORT_SYMBOL(cancel_delayed_work);
2991 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2992 * @dwork: the delayed work cancel
2994 * This is cancel_work_sync() for delayed works.
2997 * %true if @dwork was pending, %false otherwise.
2999 bool cancel_delayed_work_sync(struct delayed_work *dwork)
3001 return __cancel_work_timer(&dwork->work, true);
3003 EXPORT_SYMBOL(cancel_delayed_work_sync);
3006 * schedule_work_on - put work task on a specific cpu
3007 * @cpu: cpu to put the work task on
3008 * @work: job to be done
3010 * This puts a job on a specific cpu
3012 bool schedule_work_on(int cpu, struct work_struct *work)
3014 return queue_work_on(cpu, system_wq, work);
3016 EXPORT_SYMBOL(schedule_work_on);
3019 * schedule_work - put work task in global workqueue
3020 * @work: job to be done
3022 * Returns %false if @work was already on the kernel-global workqueue and
3025 * This puts a job in the kernel-global workqueue if it was not already
3026 * queued and leaves it in the same position on the kernel-global
3027 * workqueue otherwise.
3029 bool schedule_work(struct work_struct *work)
3031 return queue_work(system_wq, work);
3033 EXPORT_SYMBOL(schedule_work);
3036 * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
3038 * @dwork: job to be done
3039 * @delay: number of jiffies to wait
3041 * After waiting for a given time this puts a job in the kernel-global
3042 * workqueue on the specified CPU.
3044 bool schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
3045 unsigned long delay)
3047 return queue_delayed_work_on(cpu, system_wq, dwork, delay);
3049 EXPORT_SYMBOL(schedule_delayed_work_on);
3052 * schedule_delayed_work - put work task in global workqueue after delay
3053 * @dwork: job to be done
3054 * @delay: number of jiffies to wait or 0 for immediate execution
3056 * After waiting for a given time this puts a job in the kernel-global
3059 bool schedule_delayed_work(struct delayed_work *dwork, unsigned long delay)
3061 return queue_delayed_work(system_wq, dwork, delay);
3063 EXPORT_SYMBOL(schedule_delayed_work);
3066 * schedule_on_each_cpu - execute a function synchronously on each online CPU
3067 * @func: the function to call
3069 * schedule_on_each_cpu() executes @func on each online CPU using the
3070 * system workqueue and blocks until all CPUs have completed.
3071 * schedule_on_each_cpu() is very slow.
3074 * 0 on success, -errno on failure.
3076 int schedule_on_each_cpu(work_func_t func)
3079 struct work_struct __percpu *works;
3081 works = alloc_percpu(struct work_struct);
3087 for_each_online_cpu(cpu) {
3088 struct work_struct *work = per_cpu_ptr(works, cpu);
3090 INIT_WORK(work, func);
3091 schedule_work_on(cpu, work);
3094 for_each_online_cpu(cpu)
3095 flush_work(per_cpu_ptr(works, cpu));
3103 * flush_scheduled_work - ensure that any scheduled work has run to completion.
3105 * Forces execution of the kernel-global workqueue and blocks until its
3108 * Think twice before calling this function! It's very easy to get into
3109 * trouble if you don't take great care. Either of the following situations
3110 * will lead to deadlock:
3112 * One of the work items currently on the workqueue needs to acquire
3113 * a lock held by your code or its caller.
3115 * Your code is running in the context of a work routine.
3117 * They will be detected by lockdep when they occur, but the first might not
3118 * occur very often. It depends on what work items are on the workqueue and
3119 * what locks they need, which you have no control over.
3121 * In most situations flushing the entire workqueue is overkill; you merely
3122 * need to know that a particular work item isn't queued and isn't running.
3123 * In such cases you should use cancel_delayed_work_sync() or
3124 * cancel_work_sync() instead.
3126 void flush_scheduled_work(void)
3128 flush_workqueue(system_wq);
3130 EXPORT_SYMBOL(flush_scheduled_work);
3133 * execute_in_process_context - reliably execute the routine with user context
3134 * @fn: the function to execute
3135 * @ew: guaranteed storage for the execute work structure (must
3136 * be available when the work executes)
3138 * Executes the function immediately if process context is available,
3139 * otherwise schedules the function for delayed execution.
3141 * Returns: 0 - function was executed
3142 * 1 - function was scheduled for execution
3144 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
3146 if (!in_interrupt()) {
3151 INIT_WORK(&ew->work, fn);
3152 schedule_work(&ew->work);
3156 EXPORT_SYMBOL_GPL(execute_in_process_context);
3158 int keventd_up(void)
3160 return system_wq != NULL;
3163 static int alloc_cwqs(struct workqueue_struct *wq)
3166 * cwqs are forced aligned according to WORK_STRUCT_FLAG_BITS.
3167 * Make sure that the alignment isn't lower than that of
3168 * unsigned long long.
3170 const size_t size = sizeof(struct cpu_workqueue_struct);
3171 const size_t align = max_t(size_t, 1 << WORK_STRUCT_FLAG_BITS,
3172 __alignof__(unsigned long long));
3174 if (!(wq->flags & WQ_UNBOUND))
3175 wq->cpu_wq.pcpu = __alloc_percpu(size, align);
3180 * Allocate enough room to align cwq and put an extra
3181 * pointer at the end pointing back to the originally
3182 * allocated pointer which will be used for free.
3184 ptr = kzalloc(size + align + sizeof(void *), GFP_KERNEL);
3186 wq->cpu_wq.single = PTR_ALIGN(ptr, align);
3187 *(void **)(wq->cpu_wq.single + 1) = ptr;
3191 /* just in case, make sure it's actually aligned */
3192 BUG_ON(!IS_ALIGNED(wq->cpu_wq.v, align));
3193 return wq->cpu_wq.v ? 0 : -ENOMEM;
3196 static void free_cwqs(struct workqueue_struct *wq)
3198 if (!(wq->flags & WQ_UNBOUND))
3199 free_percpu(wq->cpu_wq.pcpu);
3200 else if (wq->cpu_wq.single) {
3201 /* the pointer to free is stored right after the cwq */
3202 kfree(*(void **)(wq->cpu_wq.single + 1));
3206 static int wq_clamp_max_active(int max_active, unsigned int flags,
3209 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3211 if (max_active < 1 || max_active > lim)
3212 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3213 max_active, name, 1, lim);
3215 return clamp_val(max_active, 1, lim);
3218 struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
3221 struct lock_class_key *key,
3222 const char *lock_name, ...)
3224 va_list args, args1;
3225 struct workqueue_struct *wq;
3229 /* determine namelen, allocate wq and format name */
3230 va_start(args, lock_name);
3231 va_copy(args1, args);
3232 namelen = vsnprintf(NULL, 0, fmt, args) + 1;
3234 wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
3238 vsnprintf(wq->name, namelen, fmt, args1);
3243 * Workqueues which may be used during memory reclaim should
3244 * have a rescuer to guarantee forward progress.
3246 if (flags & WQ_MEM_RECLAIM)
3247 flags |= WQ_RESCUER;
3249 max_active = max_active ?: WQ_DFL_ACTIVE;
3250 max_active = wq_clamp_max_active(max_active, flags, wq->name);
3254 wq->saved_max_active = max_active;
3255 mutex_init(&wq->flush_mutex);
3256 atomic_set(&wq->nr_cwqs_to_flush, 0);
3257 INIT_LIST_HEAD(&wq->flusher_queue);
3258 INIT_LIST_HEAD(&wq->flusher_overflow);
3260 lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3261 INIT_LIST_HEAD(&wq->list);
3263 if (alloc_cwqs(wq) < 0)
3266 for_each_cwq_cpu(cpu, wq) {
3267 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3268 struct global_cwq *gcwq = get_gcwq(cpu);
3269 int pool_idx = (bool)(flags & WQ_HIGHPRI);
3271 BUG_ON((unsigned long)cwq & WORK_STRUCT_FLAG_MASK);
3272 cwq->pool = &gcwq->pools[pool_idx];
3274 cwq->flush_color = -1;
3275 cwq->max_active = max_active;
3276 INIT_LIST_HEAD(&cwq->delayed_works);
3279 if (flags & WQ_RESCUER) {
3280 struct worker *rescuer;
3282 if (!alloc_mayday_mask(&wq->mayday_mask, GFP_KERNEL))
3285 wq->rescuer = rescuer = alloc_worker();
3289 rescuer->rescue_wq = wq;
3290 rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
3292 if (IS_ERR(rescuer->task))
3295 rescuer->task->flags |= PF_THREAD_BOUND;
3296 wake_up_process(rescuer->task);
3300 * workqueue_lock protects global freeze state and workqueues
3301 * list. Grab it, set max_active accordingly and add the new
3302 * workqueue to workqueues list.
3304 spin_lock(&workqueue_lock);
3306 if (workqueue_freezing && wq->flags & WQ_FREEZABLE)
3307 for_each_cwq_cpu(cpu, wq)
3308 get_cwq(cpu, wq)->max_active = 0;
3310 list_add(&wq->list, &workqueues);
3312 spin_unlock(&workqueue_lock);
3318 free_mayday_mask(wq->mayday_mask);
3324 EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
3327 * destroy_workqueue - safely terminate a workqueue
3328 * @wq: target workqueue
3330 * Safely destroy a workqueue. All work currently pending will be done first.
3332 void destroy_workqueue(struct workqueue_struct *wq)
3336 /* drain it before proceeding with destruction */
3337 drain_workqueue(wq);
3340 * wq list is used to freeze wq, remove from list after
3341 * flushing is complete in case freeze races us.
3343 spin_lock(&workqueue_lock);
3344 list_del(&wq->list);
3345 spin_unlock(&workqueue_lock);
3348 for_each_cwq_cpu(cpu, wq) {
3349 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3352 for (i = 0; i < WORK_NR_COLORS; i++)
3353 BUG_ON(cwq->nr_in_flight[i]);
3354 BUG_ON(cwq->nr_active);
3355 BUG_ON(!list_empty(&cwq->delayed_works));
3358 if (wq->flags & WQ_RESCUER) {
3359 kthread_stop(wq->rescuer->task);
3360 free_mayday_mask(wq->mayday_mask);
3367 EXPORT_SYMBOL_GPL(destroy_workqueue);
3370 * cwq_set_max_active - adjust max_active of a cwq
3371 * @cwq: target cpu_workqueue_struct
3372 * @max_active: new max_active value.
3374 * Set @cwq->max_active to @max_active and activate delayed works if
3378 * spin_lock_irq(gcwq->lock).
3380 static void cwq_set_max_active(struct cpu_workqueue_struct *cwq, int max_active)
3382 cwq->max_active = max_active;
3384 while (!list_empty(&cwq->delayed_works) &&
3385 cwq->nr_active < cwq->max_active)
3386 cwq_activate_first_delayed(cwq);
3390 * workqueue_set_max_active - adjust max_active of a workqueue
3391 * @wq: target workqueue
3392 * @max_active: new max_active value.
3394 * Set max_active of @wq to @max_active.
3397 * Don't call from IRQ context.
3399 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
3403 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
3405 spin_lock(&workqueue_lock);
3407 wq->saved_max_active = max_active;
3409 for_each_cwq_cpu(cpu, wq) {
3410 struct global_cwq *gcwq = get_gcwq(cpu);
3412 spin_lock_irq(&gcwq->lock);
3414 if (!(wq->flags & WQ_FREEZABLE) ||
3415 !(gcwq->flags & GCWQ_FREEZING))
3416 cwq_set_max_active(get_cwq(gcwq->cpu, wq), max_active);
3418 spin_unlock_irq(&gcwq->lock);
3421 spin_unlock(&workqueue_lock);
3423 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
3426 * workqueue_congested - test whether a workqueue is congested
3427 * @cpu: CPU in question
3428 * @wq: target workqueue
3430 * Test whether @wq's cpu workqueue for @cpu is congested. There is
3431 * no synchronization around this function and the test result is
3432 * unreliable and only useful as advisory hints or for debugging.
3435 * %true if congested, %false otherwise.
3437 bool workqueue_congested(unsigned int cpu, struct workqueue_struct *wq)
3439 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3441 return !list_empty(&cwq->delayed_works);
3443 EXPORT_SYMBOL_GPL(workqueue_congested);
3446 * work_cpu - return the last known associated cpu for @work
3447 * @work: the work of interest
3450 * CPU number if @work was ever queued. WORK_CPU_NONE otherwise.
3452 unsigned int work_cpu(struct work_struct *work)
3454 struct global_cwq *gcwq = get_work_gcwq(work);
3456 return gcwq ? gcwq->cpu : WORK_CPU_NONE;
3458 EXPORT_SYMBOL_GPL(work_cpu);
3461 * work_busy - test whether a work is currently pending or running
3462 * @work: the work to be tested
3464 * Test whether @work is currently pending or running. There is no
3465 * synchronization around this function and the test result is
3466 * unreliable and only useful as advisory hints or for debugging.
3467 * Especially for reentrant wqs, the pending state might hide the
3471 * OR'd bitmask of WORK_BUSY_* bits.
3473 unsigned int work_busy(struct work_struct *work)
3475 struct global_cwq *gcwq = get_work_gcwq(work);
3476 unsigned long flags;
3477 unsigned int ret = 0;
3482 spin_lock_irqsave(&gcwq->lock, flags);
3484 if (work_pending(work))
3485 ret |= WORK_BUSY_PENDING;
3486 if (find_worker_executing_work(gcwq, work))
3487 ret |= WORK_BUSY_RUNNING;
3489 spin_unlock_irqrestore(&gcwq->lock, flags);
3493 EXPORT_SYMBOL_GPL(work_busy);
3498 * There are two challenges in supporting CPU hotplug. Firstly, there
3499 * are a lot of assumptions on strong associations among work, cwq and
3500 * gcwq which make migrating pending and scheduled works very
3501 * difficult to implement without impacting hot paths. Secondly,
3502 * gcwqs serve mix of short, long and very long running works making
3503 * blocked draining impractical.
3505 * This is solved by allowing a gcwq to be disassociated from the CPU
3506 * running as an unbound one and allowing it to be reattached later if the
3507 * cpu comes back online.
3510 /* claim manager positions of all pools */
3511 static void gcwq_claim_assoc_and_lock(struct global_cwq *gcwq)
3513 struct worker_pool *pool;
3515 for_each_worker_pool(pool, gcwq)
3516 mutex_lock_nested(&pool->assoc_mutex, pool - gcwq->pools);
3517 spin_lock_irq(&gcwq->lock);
3520 /* release manager positions */
3521 static void gcwq_release_assoc_and_unlock(struct global_cwq *gcwq)
3523 struct worker_pool *pool;
3525 spin_unlock_irq(&gcwq->lock);
3526 for_each_worker_pool(pool, gcwq)
3527 mutex_unlock(&pool->assoc_mutex);
3530 static void gcwq_unbind_fn(struct work_struct *work)
3532 struct global_cwq *gcwq = get_gcwq(smp_processor_id());
3533 struct worker_pool *pool;
3534 struct worker *worker;
3535 struct hlist_node *pos;
3538 BUG_ON(gcwq->cpu != smp_processor_id());
3540 gcwq_claim_assoc_and_lock(gcwq);
3543 * We've claimed all manager positions. Make all workers unbound
3544 * and set DISASSOCIATED. Before this, all workers except for the
3545 * ones which are still executing works from before the last CPU
3546 * down must be on the cpu. After this, they may become diasporas.
3548 for_each_worker_pool(pool, gcwq)
3549 list_for_each_entry(worker, &pool->idle_list, entry)
3550 worker->flags |= WORKER_UNBOUND;
3552 for_each_busy_worker(worker, i, pos, gcwq)
3553 worker->flags |= WORKER_UNBOUND;
3555 gcwq->flags |= GCWQ_DISASSOCIATED;
3557 gcwq_release_assoc_and_unlock(gcwq);
3560 * Call schedule() so that we cross rq->lock and thus can guarantee
3561 * sched callbacks see the %WORKER_UNBOUND flag. This is necessary
3562 * as scheduler callbacks may be invoked from other cpus.
3567 * Sched callbacks are disabled now. Zap nr_running. After this,
3568 * nr_running stays zero and need_more_worker() and keep_working()
3569 * are always true as long as the worklist is not empty. @gcwq now
3570 * behaves as unbound (in terms of concurrency management) gcwq
3571 * which is served by workers tied to the CPU.
3573 * On return from this function, the current worker would trigger
3574 * unbound chain execution of pending work items if other workers
3577 for_each_worker_pool(pool, gcwq)
3578 atomic_set(get_pool_nr_running(pool), 0);
3582 * Workqueues should be brought up before normal priority CPU notifiers.
3583 * This will be registered high priority CPU notifier.
3585 static int __cpuinit workqueue_cpu_up_callback(struct notifier_block *nfb,
3586 unsigned long action,
3589 unsigned int cpu = (unsigned long)hcpu;
3590 struct global_cwq *gcwq = get_gcwq(cpu);
3591 struct worker_pool *pool;
3593 switch (action & ~CPU_TASKS_FROZEN) {
3594 case CPU_UP_PREPARE:
3595 for_each_worker_pool(pool, gcwq) {
3596 struct worker *worker;
3598 if (pool->nr_workers)
3601 worker = create_worker(pool);
3605 spin_lock_irq(&gcwq->lock);
3606 start_worker(worker);
3607 spin_unlock_irq(&gcwq->lock);
3611 case CPU_DOWN_FAILED:
3613 gcwq_claim_assoc_and_lock(gcwq);
3614 gcwq->flags &= ~GCWQ_DISASSOCIATED;
3615 rebind_workers(gcwq);
3616 gcwq_release_assoc_and_unlock(gcwq);
3623 * Workqueues should be brought down after normal priority CPU notifiers.
3624 * This will be registered as low priority CPU notifier.
3626 static int __cpuinit workqueue_cpu_down_callback(struct notifier_block *nfb,
3627 unsigned long action,
3630 unsigned int cpu = (unsigned long)hcpu;
3631 struct work_struct unbind_work;
3633 switch (action & ~CPU_TASKS_FROZEN) {
3634 case CPU_DOWN_PREPARE:
3635 /* unbinding should happen on the local CPU */
3636 INIT_WORK_ONSTACK(&unbind_work, gcwq_unbind_fn);
3637 queue_work_on(cpu, system_highpri_wq, &unbind_work);
3638 flush_work(&unbind_work);
3646 struct work_for_cpu {
3647 struct work_struct work;
3653 static void work_for_cpu_fn(struct work_struct *work)
3655 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
3657 wfc->ret = wfc->fn(wfc->arg);
3661 * work_on_cpu - run a function in user context on a particular cpu
3662 * @cpu: the cpu to run on
3663 * @fn: the function to run
3664 * @arg: the function arg
3666 * This will return the value @fn returns.
3667 * It is up to the caller to ensure that the cpu doesn't go offline.
3668 * The caller must not hold any locks which would prevent @fn from completing.
3670 long work_on_cpu(unsigned int cpu, long (*fn)(void *), void *arg)
3672 struct work_for_cpu wfc = { .fn = fn, .arg = arg };
3674 INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
3675 schedule_work_on(cpu, &wfc.work);
3676 flush_work(&wfc.work);
3679 EXPORT_SYMBOL_GPL(work_on_cpu);
3680 #endif /* CONFIG_SMP */
3682 #ifdef CONFIG_FREEZER
3685 * freeze_workqueues_begin - begin freezing workqueues
3687 * Start freezing workqueues. After this function returns, all freezable
3688 * workqueues will queue new works to their frozen_works list instead of
3692 * Grabs and releases workqueue_lock and gcwq->lock's.
3694 void freeze_workqueues_begin(void)
3698 spin_lock(&workqueue_lock);
3700 BUG_ON(workqueue_freezing);
3701 workqueue_freezing = true;
3703 for_each_gcwq_cpu(cpu) {
3704 struct global_cwq *gcwq = get_gcwq(cpu);
3705 struct workqueue_struct *wq;
3707 spin_lock_irq(&gcwq->lock);
3709 BUG_ON(gcwq->flags & GCWQ_FREEZING);
3710 gcwq->flags |= GCWQ_FREEZING;
3712 list_for_each_entry(wq, &workqueues, list) {
3713 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3715 if (cwq && wq->flags & WQ_FREEZABLE)
3716 cwq->max_active = 0;
3719 spin_unlock_irq(&gcwq->lock);
3722 spin_unlock(&workqueue_lock);
3726 * freeze_workqueues_busy - are freezable workqueues still busy?
3728 * Check whether freezing is complete. This function must be called
3729 * between freeze_workqueues_begin() and thaw_workqueues().
3732 * Grabs and releases workqueue_lock.
3735 * %true if some freezable workqueues are still busy. %false if freezing
3738 bool freeze_workqueues_busy(void)
3743 spin_lock(&workqueue_lock);
3745 BUG_ON(!workqueue_freezing);
3747 for_each_gcwq_cpu(cpu) {
3748 struct workqueue_struct *wq;
3750 * nr_active is monotonically decreasing. It's safe
3751 * to peek without lock.
3753 list_for_each_entry(wq, &workqueues, list) {
3754 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3756 if (!cwq || !(wq->flags & WQ_FREEZABLE))
3759 BUG_ON(cwq->nr_active < 0);
3760 if (cwq->nr_active) {
3767 spin_unlock(&workqueue_lock);
3772 * thaw_workqueues - thaw workqueues
3774 * Thaw workqueues. Normal queueing is restored and all collected
3775 * frozen works are transferred to their respective gcwq worklists.
3778 * Grabs and releases workqueue_lock and gcwq->lock's.
3780 void thaw_workqueues(void)
3784 spin_lock(&workqueue_lock);
3786 if (!workqueue_freezing)
3789 for_each_gcwq_cpu(cpu) {
3790 struct global_cwq *gcwq = get_gcwq(cpu);
3791 struct worker_pool *pool;
3792 struct workqueue_struct *wq;
3794 spin_lock_irq(&gcwq->lock);
3796 BUG_ON(!(gcwq->flags & GCWQ_FREEZING));
3797 gcwq->flags &= ~GCWQ_FREEZING;
3799 list_for_each_entry(wq, &workqueues, list) {
3800 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3802 if (!cwq || !(wq->flags & WQ_FREEZABLE))
3805 /* restore max_active and repopulate worklist */
3806 cwq_set_max_active(cwq, wq->saved_max_active);
3809 for_each_worker_pool(pool, gcwq)
3810 wake_up_worker(pool);
3812 spin_unlock_irq(&gcwq->lock);
3815 workqueue_freezing = false;
3817 spin_unlock(&workqueue_lock);
3819 #endif /* CONFIG_FREEZER */
3821 static int __init init_workqueues(void)
3825 /* make sure we have enough bits for OFFQ CPU number */
3826 BUILD_BUG_ON((1LU << (BITS_PER_LONG - WORK_OFFQ_CPU_SHIFT)) <
3829 cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
3830 hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
3832 /* initialize gcwqs */
3833 for_each_gcwq_cpu(cpu) {
3834 struct global_cwq *gcwq = get_gcwq(cpu);
3835 struct worker_pool *pool;
3837 spin_lock_init(&gcwq->lock);
3839 gcwq->flags |= GCWQ_DISASSOCIATED;
3841 hash_init(gcwq->busy_hash);
3843 for_each_worker_pool(pool, gcwq) {
3845 INIT_LIST_HEAD(&pool->worklist);
3846 INIT_LIST_HEAD(&pool->idle_list);
3848 init_timer_deferrable(&pool->idle_timer);
3849 pool->idle_timer.function = idle_worker_timeout;
3850 pool->idle_timer.data = (unsigned long)pool;
3852 setup_timer(&pool->mayday_timer, gcwq_mayday_timeout,
3853 (unsigned long)pool);
3855 mutex_init(&pool->assoc_mutex);
3856 ida_init(&pool->worker_ida);
3860 /* create the initial worker */
3861 for_each_online_gcwq_cpu(cpu) {
3862 struct global_cwq *gcwq = get_gcwq(cpu);
3863 struct worker_pool *pool;
3865 if (cpu != WORK_CPU_UNBOUND)
3866 gcwq->flags &= ~GCWQ_DISASSOCIATED;
3868 for_each_worker_pool(pool, gcwq) {
3869 struct worker *worker;
3871 worker = create_worker(pool);
3873 spin_lock_irq(&gcwq->lock);
3874 start_worker(worker);
3875 spin_unlock_irq(&gcwq->lock);
3879 system_wq = alloc_workqueue("events", 0, 0);
3880 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
3881 system_long_wq = alloc_workqueue("events_long", 0, 0);
3882 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
3883 WQ_UNBOUND_MAX_ACTIVE);
3884 system_freezable_wq = alloc_workqueue("events_freezable",
3886 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
3887 !system_unbound_wq || !system_freezable_wq);
3890 early_initcall(init_workqueues);