2 * kernel/workqueue.c - generic async execution with shared worker pool
4 * Copyright (C) 2002 Ingo Molnar
6 * Derived from the taskqueue/keventd code by:
7 * David Woodhouse <dwmw2@infradead.org>
9 * Kai Petzke <wpp@marie.physik.tu-berlin.de>
10 * Theodore Ts'o <tytso@mit.edu>
12 * Made to use alloc_percpu by Christoph Lameter.
14 * Copyright (C) 2010 SUSE Linux Products GmbH
15 * Copyright (C) 2010 Tejun Heo <tj@kernel.org>
17 * This is the generic async execution mechanism. Work items as are
18 * executed in process context. The worker pool is shared and
19 * automatically managed. There is one worker pool for each CPU and
20 * one extra for works which are better served by workers which are
21 * not bound to any specific CPU.
23 * Please read Documentation/workqueue.txt for details.
26 #include <linux/export.h>
27 #include <linux/kernel.h>
28 #include <linux/sched.h>
29 #include <linux/init.h>
30 #include <linux/signal.h>
31 #include <linux/completion.h>
32 #include <linux/workqueue.h>
33 #include <linux/slab.h>
34 #include <linux/cpu.h>
35 #include <linux/notifier.h>
36 #include <linux/kthread.h>
37 #include <linux/hardirq.h>
38 #include <linux/mempolicy.h>
39 #include <linux/freezer.h>
40 #include <linux/kallsyms.h>
41 #include <linux/debug_locks.h>
42 #include <linux/lockdep.h>
43 #include <linux/idr.h>
44 #include <linux/hashtable.h>
46 #include "workqueue_internal.h"
52 * A bound pool is either associated or disassociated with its CPU.
53 * While associated (!DISASSOCIATED), all workers are bound to the
54 * CPU and none has %WORKER_UNBOUND set and concurrency management
57 * While DISASSOCIATED, the cpu may be offline and all workers have
58 * %WORKER_UNBOUND set and concurrency management disabled, and may
59 * be executing on any CPU. The pool behaves as an unbound one.
61 * Note that DISASSOCIATED can be flipped only while holding
62 * assoc_mutex to avoid changing binding state while
63 * create_worker() is in progress.
65 POOL_MANAGE_WORKERS = 1 << 0, /* need to manage workers */
66 POOL_MANAGING_WORKERS = 1 << 1, /* managing workers */
67 POOL_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
68 POOL_FREEZING = 1 << 3, /* freeze in progress */
71 WORKER_STARTED = 1 << 0, /* started */
72 WORKER_DIE = 1 << 1, /* die die die */
73 WORKER_IDLE = 1 << 2, /* is idle */
74 WORKER_PREP = 1 << 3, /* preparing to run works */
75 WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
76 WORKER_UNBOUND = 1 << 7, /* worker is unbound */
78 WORKER_NOT_RUNNING = WORKER_PREP | WORKER_UNBOUND |
81 NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */
83 BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
85 MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
86 IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
88 MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
89 /* call for help after 10ms
91 MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
92 CREATE_COOLDOWN = HZ, /* time to breath after fail */
95 * Rescue workers are used only on emergencies and shared by
98 RESCUER_NICE_LEVEL = -20,
99 HIGHPRI_NICE_LEVEL = -20,
103 * Structure fields follow one of the following exclusion rules.
105 * I: Modifiable by initialization/destruction paths and read-only for
108 * P: Preemption protected. Disabling preemption is enough and should
109 * only be modified and accessed from the local cpu.
111 * L: pool->lock protected. Access with pool->lock held.
113 * X: During normal operation, modification requires pool->lock and should
114 * be done only from local cpu. Either disabling preemption on local
115 * cpu or grabbing pool->lock is enough for read access. If
116 * POOL_DISASSOCIATED is set, it's identical to L.
118 * F: wq->flush_mutex protected.
120 * W: workqueue_lock protected.
123 /* struct worker is defined in workqueue_internal.h */
126 spinlock_t lock; /* the pool lock */
127 unsigned int cpu; /* I: the associated cpu */
128 int id; /* I: pool ID */
129 unsigned int flags; /* X: flags */
131 struct list_head worklist; /* L: list of pending works */
132 int nr_workers; /* L: total number of workers */
134 /* nr_idle includes the ones off idle_list for rebinding */
135 int nr_idle; /* L: currently idle ones */
137 struct list_head idle_list; /* X: list of idle workers */
138 struct timer_list idle_timer; /* L: worker idle timeout */
139 struct timer_list mayday_timer; /* L: SOS timer for workers */
141 /* workers are chained either in busy_hash or idle_list */
142 DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
143 /* L: hash of busy workers */
145 struct mutex assoc_mutex; /* protect POOL_DISASSOCIATED */
146 struct ida worker_ida; /* L: for worker IDs */
149 * The current concurrency level. As it's likely to be accessed
150 * from other CPUs during try_to_wake_up(), put it in a separate
153 atomic_t nr_running ____cacheline_aligned_in_smp;
154 } ____cacheline_aligned_in_smp;
157 * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
158 * of work_struct->data are used for flags and the remaining high bits
159 * point to the pwq; thus, pwqs need to be aligned at two's power of the
160 * number of flag bits.
162 struct pool_workqueue {
163 struct worker_pool *pool; /* I: the associated pool */
164 struct workqueue_struct *wq; /* I: the owning workqueue */
165 int work_color; /* L: current color */
166 int flush_color; /* L: flushing color */
167 int nr_in_flight[WORK_NR_COLORS];
168 /* L: nr of in_flight works */
169 int nr_active; /* L: nr of active works */
170 int max_active; /* L: max active works */
171 struct list_head delayed_works; /* L: delayed works */
172 } __aligned(1 << WORK_STRUCT_FLAG_BITS);
175 * Structure used to wait for workqueue flush.
178 struct list_head list; /* F: list of flushers */
179 int flush_color; /* F: flush color waiting for */
180 struct completion done; /* flush completion */
184 * All cpumasks are assumed to be always set on UP and thus can't be
185 * used to determine whether there's something to be done.
188 typedef cpumask_var_t mayday_mask_t;
189 #define mayday_test_and_set_cpu(cpu, mask) \
190 cpumask_test_and_set_cpu((cpu), (mask))
191 #define mayday_clear_cpu(cpu, mask) cpumask_clear_cpu((cpu), (mask))
192 #define for_each_mayday_cpu(cpu, mask) for_each_cpu((cpu), (mask))
193 #define alloc_mayday_mask(maskp, gfp) zalloc_cpumask_var((maskp), (gfp))
194 #define free_mayday_mask(mask) free_cpumask_var((mask))
196 typedef unsigned long mayday_mask_t;
197 #define mayday_test_and_set_cpu(cpu, mask) test_and_set_bit(0, &(mask))
198 #define mayday_clear_cpu(cpu, mask) clear_bit(0, &(mask))
199 #define for_each_mayday_cpu(cpu, mask) if ((cpu) = 0, (mask))
200 #define alloc_mayday_mask(maskp, gfp) true
201 #define free_mayday_mask(mask) do { } while (0)
205 * The externally visible workqueue abstraction is an array of
206 * per-CPU workqueues:
208 struct workqueue_struct {
209 unsigned int flags; /* W: WQ_* flags */
211 struct pool_workqueue __percpu *pcpu;
212 struct pool_workqueue *single;
214 } pool_wq; /* I: pwq's */
215 struct list_head list; /* W: list of all workqueues */
217 struct mutex flush_mutex; /* protects wq flushing */
218 int work_color; /* F: current work color */
219 int flush_color; /* F: current flush color */
220 atomic_t nr_pwqs_to_flush; /* flush in progress */
221 struct wq_flusher *first_flusher; /* F: first flusher */
222 struct list_head flusher_queue; /* F: flush waiters */
223 struct list_head flusher_overflow; /* F: flush overflow list */
225 mayday_mask_t mayday_mask; /* cpus requesting rescue */
226 struct worker *rescuer; /* I: rescue worker */
228 int nr_drainers; /* W: drain in progress */
229 int saved_max_active; /* W: saved pwq max_active */
230 #ifdef CONFIG_LOCKDEP
231 struct lockdep_map lockdep_map;
233 char name[]; /* I: workqueue name */
236 static struct kmem_cache *pwq_cache;
238 struct workqueue_struct *system_wq __read_mostly;
239 EXPORT_SYMBOL_GPL(system_wq);
240 struct workqueue_struct *system_highpri_wq __read_mostly;
241 EXPORT_SYMBOL_GPL(system_highpri_wq);
242 struct workqueue_struct *system_long_wq __read_mostly;
243 EXPORT_SYMBOL_GPL(system_long_wq);
244 struct workqueue_struct *system_unbound_wq __read_mostly;
245 EXPORT_SYMBOL_GPL(system_unbound_wq);
246 struct workqueue_struct *system_freezable_wq __read_mostly;
247 EXPORT_SYMBOL_GPL(system_freezable_wq);
249 #define CREATE_TRACE_POINTS
250 #include <trace/events/workqueue.h>
252 #define for_each_std_worker_pool(pool, cpu) \
253 for ((pool) = &std_worker_pools(cpu)[0]; \
254 (pool) < &std_worker_pools(cpu)[NR_STD_WORKER_POOLS]; (pool)++)
256 #define for_each_busy_worker(worker, i, pool) \
257 hash_for_each(pool->busy_hash, i, worker, hentry)
259 static inline int __next_wq_cpu(int cpu, const struct cpumask *mask,
262 if (cpu < nr_cpu_ids) {
264 cpu = cpumask_next(cpu, mask);
265 if (cpu < nr_cpu_ids)
269 return WORK_CPU_UNBOUND;
274 static inline int __next_pwq_cpu(int cpu, const struct cpumask *mask,
275 struct workqueue_struct *wq)
277 return __next_wq_cpu(cpu, mask, !(wq->flags & WQ_UNBOUND) ? 1 : 2);
283 * An extra cpu number is defined using an invalid cpu number
284 * (WORK_CPU_UNBOUND) to host workqueues which are not bound to any
285 * specific CPU. The following iterators are similar to for_each_*_cpu()
286 * iterators but also considers the unbound CPU.
288 * for_each_wq_cpu() : possible CPUs + WORK_CPU_UNBOUND
289 * for_each_online_wq_cpu() : online CPUs + WORK_CPU_UNBOUND
290 * for_each_pwq_cpu() : possible CPUs for bound workqueues,
291 * WORK_CPU_UNBOUND for unbound workqueues
293 #define for_each_wq_cpu(cpu) \
294 for ((cpu) = __next_wq_cpu(-1, cpu_possible_mask, 3); \
295 (cpu) < WORK_CPU_END; \
296 (cpu) = __next_wq_cpu((cpu), cpu_possible_mask, 3))
298 #define for_each_online_wq_cpu(cpu) \
299 for ((cpu) = __next_wq_cpu(-1, cpu_online_mask, 3); \
300 (cpu) < WORK_CPU_END; \
301 (cpu) = __next_wq_cpu((cpu), cpu_online_mask, 3))
303 #define for_each_pwq_cpu(cpu, wq) \
304 for ((cpu) = __next_pwq_cpu(-1, cpu_possible_mask, (wq)); \
305 (cpu) < WORK_CPU_END; \
306 (cpu) = __next_pwq_cpu((cpu), cpu_possible_mask, (wq)))
308 #ifdef CONFIG_DEBUG_OBJECTS_WORK
310 static struct debug_obj_descr work_debug_descr;
312 static void *work_debug_hint(void *addr)
314 return ((struct work_struct *) addr)->func;
318 * fixup_init is called when:
319 * - an active object is initialized
321 static int work_fixup_init(void *addr, enum debug_obj_state state)
323 struct work_struct *work = addr;
326 case ODEBUG_STATE_ACTIVE:
327 cancel_work_sync(work);
328 debug_object_init(work, &work_debug_descr);
336 * fixup_activate is called when:
337 * - an active object is activated
338 * - an unknown object is activated (might be a statically initialized object)
340 static int work_fixup_activate(void *addr, enum debug_obj_state state)
342 struct work_struct *work = addr;
346 case ODEBUG_STATE_NOTAVAILABLE:
348 * This is not really a fixup. The work struct was
349 * statically initialized. We just make sure that it
350 * is tracked in the object tracker.
352 if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
353 debug_object_init(work, &work_debug_descr);
354 debug_object_activate(work, &work_debug_descr);
360 case ODEBUG_STATE_ACTIVE:
369 * fixup_free is called when:
370 * - an active object is freed
372 static int work_fixup_free(void *addr, enum debug_obj_state state)
374 struct work_struct *work = addr;
377 case ODEBUG_STATE_ACTIVE:
378 cancel_work_sync(work);
379 debug_object_free(work, &work_debug_descr);
386 static struct debug_obj_descr work_debug_descr = {
387 .name = "work_struct",
388 .debug_hint = work_debug_hint,
389 .fixup_init = work_fixup_init,
390 .fixup_activate = work_fixup_activate,
391 .fixup_free = work_fixup_free,
394 static inline void debug_work_activate(struct work_struct *work)
396 debug_object_activate(work, &work_debug_descr);
399 static inline void debug_work_deactivate(struct work_struct *work)
401 debug_object_deactivate(work, &work_debug_descr);
404 void __init_work(struct work_struct *work, int onstack)
407 debug_object_init_on_stack(work, &work_debug_descr);
409 debug_object_init(work, &work_debug_descr);
411 EXPORT_SYMBOL_GPL(__init_work);
413 void destroy_work_on_stack(struct work_struct *work)
415 debug_object_free(work, &work_debug_descr);
417 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
420 static inline void debug_work_activate(struct work_struct *work) { }
421 static inline void debug_work_deactivate(struct work_struct *work) { }
424 /* Serializes the accesses to the list of workqueues. */
425 static DEFINE_SPINLOCK(workqueue_lock);
426 static LIST_HEAD(workqueues);
427 static bool workqueue_freezing; /* W: have wqs started freezing? */
430 * The CPU and unbound standard worker pools. The unbound ones have
431 * POOL_DISASSOCIATED set, and their workers have WORKER_UNBOUND set.
433 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
434 cpu_std_worker_pools);
435 static struct worker_pool unbound_std_worker_pools[NR_STD_WORKER_POOLS];
437 /* idr of all pools */
438 static DEFINE_MUTEX(worker_pool_idr_mutex);
439 static DEFINE_IDR(worker_pool_idr);
441 static int worker_thread(void *__worker);
443 static struct worker_pool *std_worker_pools(int cpu)
445 if (cpu != WORK_CPU_UNBOUND)
446 return per_cpu(cpu_std_worker_pools, cpu);
448 return unbound_std_worker_pools;
451 static int std_worker_pool_pri(struct worker_pool *pool)
453 return pool - std_worker_pools(pool->cpu);
456 /* allocate ID and assign it to @pool */
457 static int worker_pool_assign_id(struct worker_pool *pool)
461 mutex_lock(&worker_pool_idr_mutex);
462 idr_pre_get(&worker_pool_idr, GFP_KERNEL);
463 ret = idr_get_new(&worker_pool_idr, pool, &pool->id);
464 mutex_unlock(&worker_pool_idr_mutex);
470 * Lookup worker_pool by id. The idr currently is built during boot and
471 * never modified. Don't worry about locking for now.
473 static struct worker_pool *worker_pool_by_id(int pool_id)
475 return idr_find(&worker_pool_idr, pool_id);
478 static struct worker_pool *get_std_worker_pool(int cpu, bool highpri)
480 struct worker_pool *pools = std_worker_pools(cpu);
482 return &pools[highpri];
485 static struct pool_workqueue *get_pwq(unsigned int cpu,
486 struct workqueue_struct *wq)
488 if (!(wq->flags & WQ_UNBOUND)) {
489 if (likely(cpu < nr_cpu_ids))
490 return per_cpu_ptr(wq->pool_wq.pcpu, cpu);
491 } else if (likely(cpu == WORK_CPU_UNBOUND))
492 return wq->pool_wq.single;
496 static unsigned int work_color_to_flags(int color)
498 return color << WORK_STRUCT_COLOR_SHIFT;
501 static int get_work_color(struct work_struct *work)
503 return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
504 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
507 static int work_next_color(int color)
509 return (color + 1) % WORK_NR_COLORS;
513 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
514 * contain the pointer to the queued pwq. Once execution starts, the flag
515 * is cleared and the high bits contain OFFQ flags and pool ID.
517 * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
518 * and clear_work_data() can be used to set the pwq, pool or clear
519 * work->data. These functions should only be called while the work is
520 * owned - ie. while the PENDING bit is set.
522 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
523 * corresponding to a work. Pool is available once the work has been
524 * queued anywhere after initialization until it is sync canceled. pwq is
525 * available only while the work item is queued.
527 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
528 * canceled. While being canceled, a work item may have its PENDING set
529 * but stay off timer and worklist for arbitrarily long and nobody should
530 * try to steal the PENDING bit.
532 static inline void set_work_data(struct work_struct *work, unsigned long data,
535 WARN_ON_ONCE(!work_pending(work));
536 atomic_long_set(&work->data, data | flags | work_static(work));
539 static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
540 unsigned long extra_flags)
542 set_work_data(work, (unsigned long)pwq,
543 WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
546 static void set_work_pool_and_keep_pending(struct work_struct *work,
549 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
550 WORK_STRUCT_PENDING);
553 static void set_work_pool_and_clear_pending(struct work_struct *work,
557 * The following wmb is paired with the implied mb in
558 * test_and_set_bit(PENDING) and ensures all updates to @work made
559 * here are visible to and precede any updates by the next PENDING
563 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
566 static void clear_work_data(struct work_struct *work)
568 smp_wmb(); /* see set_work_pool_and_clear_pending() */
569 set_work_data(work, WORK_STRUCT_NO_POOL, 0);
572 static struct pool_workqueue *get_work_pwq(struct work_struct *work)
574 unsigned long data = atomic_long_read(&work->data);
576 if (data & WORK_STRUCT_PWQ)
577 return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
583 * get_work_pool - return the worker_pool a given work was associated with
584 * @work: the work item of interest
586 * Return the worker_pool @work was last associated with. %NULL if none.
588 static struct worker_pool *get_work_pool(struct work_struct *work)
590 unsigned long data = atomic_long_read(&work->data);
591 struct worker_pool *pool;
594 if (data & WORK_STRUCT_PWQ)
595 return ((struct pool_workqueue *)
596 (data & WORK_STRUCT_WQ_DATA_MASK))->pool;
598 pool_id = data >> WORK_OFFQ_POOL_SHIFT;
599 if (pool_id == WORK_OFFQ_POOL_NONE)
602 pool = worker_pool_by_id(pool_id);
608 * get_work_pool_id - return the worker pool ID a given work is associated with
609 * @work: the work item of interest
611 * Return the worker_pool ID @work was last associated with.
612 * %WORK_OFFQ_POOL_NONE if none.
614 static int get_work_pool_id(struct work_struct *work)
616 unsigned long data = atomic_long_read(&work->data);
618 if (data & WORK_STRUCT_PWQ)
619 return ((struct pool_workqueue *)
620 (data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
622 return data >> WORK_OFFQ_POOL_SHIFT;
625 static void mark_work_canceling(struct work_struct *work)
627 unsigned long pool_id = get_work_pool_id(work);
629 pool_id <<= WORK_OFFQ_POOL_SHIFT;
630 set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
633 static bool work_is_canceling(struct work_struct *work)
635 unsigned long data = atomic_long_read(&work->data);
637 return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
641 * Policy functions. These define the policies on how the global worker
642 * pools are managed. Unless noted otherwise, these functions assume that
643 * they're being called with pool->lock held.
646 static bool __need_more_worker(struct worker_pool *pool)
648 return !atomic_read(&pool->nr_running);
652 * Need to wake up a worker? Called from anything but currently
655 * Note that, because unbound workers never contribute to nr_running, this
656 * function will always return %true for unbound pools as long as the
657 * worklist isn't empty.
659 static bool need_more_worker(struct worker_pool *pool)
661 return !list_empty(&pool->worklist) && __need_more_worker(pool);
664 /* Can I start working? Called from busy but !running workers. */
665 static bool may_start_working(struct worker_pool *pool)
667 return pool->nr_idle;
670 /* Do I need to keep working? Called from currently running workers. */
671 static bool keep_working(struct worker_pool *pool)
673 return !list_empty(&pool->worklist) &&
674 atomic_read(&pool->nr_running) <= 1;
677 /* Do we need a new worker? Called from manager. */
678 static bool need_to_create_worker(struct worker_pool *pool)
680 return need_more_worker(pool) && !may_start_working(pool);
683 /* Do I need to be the manager? */
684 static bool need_to_manage_workers(struct worker_pool *pool)
686 return need_to_create_worker(pool) ||
687 (pool->flags & POOL_MANAGE_WORKERS);
690 /* Do we have too many workers and should some go away? */
691 static bool too_many_workers(struct worker_pool *pool)
693 bool managing = pool->flags & POOL_MANAGING_WORKERS;
694 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
695 int nr_busy = pool->nr_workers - nr_idle;
698 * nr_idle and idle_list may disagree if idle rebinding is in
699 * progress. Never return %true if idle_list is empty.
701 if (list_empty(&pool->idle_list))
704 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
711 /* Return the first worker. Safe with preemption disabled */
712 static struct worker *first_worker(struct worker_pool *pool)
714 if (unlikely(list_empty(&pool->idle_list)))
717 return list_first_entry(&pool->idle_list, struct worker, entry);
721 * wake_up_worker - wake up an idle worker
722 * @pool: worker pool to wake worker from
724 * Wake up the first idle worker of @pool.
727 * spin_lock_irq(pool->lock).
729 static void wake_up_worker(struct worker_pool *pool)
731 struct worker *worker = first_worker(pool);
734 wake_up_process(worker->task);
738 * wq_worker_waking_up - a worker is waking up
739 * @task: task waking up
740 * @cpu: CPU @task is waking up to
742 * This function is called during try_to_wake_up() when a worker is
746 * spin_lock_irq(rq->lock)
748 void wq_worker_waking_up(struct task_struct *task, unsigned int cpu)
750 struct worker *worker = kthread_data(task);
752 if (!(worker->flags & WORKER_NOT_RUNNING)) {
753 WARN_ON_ONCE(worker->pool->cpu != cpu);
754 atomic_inc(&worker->pool->nr_running);
759 * wq_worker_sleeping - a worker is going to sleep
760 * @task: task going to sleep
761 * @cpu: CPU in question, must be the current CPU number
763 * This function is called during schedule() when a busy worker is
764 * going to sleep. Worker on the same cpu can be woken up by
765 * returning pointer to its task.
768 * spin_lock_irq(rq->lock)
771 * Worker task on @cpu to wake up, %NULL if none.
773 struct task_struct *wq_worker_sleeping(struct task_struct *task,
776 struct worker *worker = kthread_data(task), *to_wakeup = NULL;
777 struct worker_pool *pool;
780 * Rescuers, which may not have all the fields set up like normal
781 * workers, also reach here, let's not access anything before
782 * checking NOT_RUNNING.
784 if (worker->flags & WORKER_NOT_RUNNING)
789 /* this can only happen on the local cpu */
790 if (WARN_ON_ONCE(cpu != raw_smp_processor_id()))
794 * The counterpart of the following dec_and_test, implied mb,
795 * worklist not empty test sequence is in insert_work().
796 * Please read comment there.
798 * NOT_RUNNING is clear. This means that we're bound to and
799 * running on the local cpu w/ rq lock held and preemption
800 * disabled, which in turn means that none else could be
801 * manipulating idle_list, so dereferencing idle_list without pool
804 if (atomic_dec_and_test(&pool->nr_running) &&
805 !list_empty(&pool->worklist))
806 to_wakeup = first_worker(pool);
807 return to_wakeup ? to_wakeup->task : NULL;
811 * worker_set_flags - set worker flags and adjust nr_running accordingly
813 * @flags: flags to set
814 * @wakeup: wakeup an idle worker if necessary
816 * Set @flags in @worker->flags and adjust nr_running accordingly. If
817 * nr_running becomes zero and @wakeup is %true, an idle worker is
821 * spin_lock_irq(pool->lock)
823 static inline void worker_set_flags(struct worker *worker, unsigned int flags,
826 struct worker_pool *pool = worker->pool;
828 WARN_ON_ONCE(worker->task != current);
831 * If transitioning into NOT_RUNNING, adjust nr_running and
832 * wake up an idle worker as necessary if requested by
835 if ((flags & WORKER_NOT_RUNNING) &&
836 !(worker->flags & WORKER_NOT_RUNNING)) {
838 if (atomic_dec_and_test(&pool->nr_running) &&
839 !list_empty(&pool->worklist))
840 wake_up_worker(pool);
842 atomic_dec(&pool->nr_running);
845 worker->flags |= flags;
849 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
851 * @flags: flags to clear
853 * Clear @flags in @worker->flags and adjust nr_running accordingly.
856 * spin_lock_irq(pool->lock)
858 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
860 struct worker_pool *pool = worker->pool;
861 unsigned int oflags = worker->flags;
863 WARN_ON_ONCE(worker->task != current);
865 worker->flags &= ~flags;
868 * If transitioning out of NOT_RUNNING, increment nr_running. Note
869 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
870 * of multiple flags, not a single flag.
872 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
873 if (!(worker->flags & WORKER_NOT_RUNNING))
874 atomic_inc(&pool->nr_running);
878 * find_worker_executing_work - find worker which is executing a work
879 * @pool: pool of interest
880 * @work: work to find worker for
882 * Find a worker which is executing @work on @pool by searching
883 * @pool->busy_hash which is keyed by the address of @work. For a worker
884 * to match, its current execution should match the address of @work and
885 * its work function. This is to avoid unwanted dependency between
886 * unrelated work executions through a work item being recycled while still
889 * This is a bit tricky. A work item may be freed once its execution
890 * starts and nothing prevents the freed area from being recycled for
891 * another work item. If the same work item address ends up being reused
892 * before the original execution finishes, workqueue will identify the
893 * recycled work item as currently executing and make it wait until the
894 * current execution finishes, introducing an unwanted dependency.
896 * This function checks the work item address, work function and workqueue
897 * to avoid false positives. Note that this isn't complete as one may
898 * construct a work function which can introduce dependency onto itself
899 * through a recycled work item. Well, if somebody wants to shoot oneself
900 * in the foot that badly, there's only so much we can do, and if such
901 * deadlock actually occurs, it should be easy to locate the culprit work
905 * spin_lock_irq(pool->lock).
908 * Pointer to worker which is executing @work if found, NULL
911 static struct worker *find_worker_executing_work(struct worker_pool *pool,
912 struct work_struct *work)
914 struct worker *worker;
916 hash_for_each_possible(pool->busy_hash, worker, hentry,
918 if (worker->current_work == work &&
919 worker->current_func == work->func)
926 * move_linked_works - move linked works to a list
927 * @work: start of series of works to be scheduled
928 * @head: target list to append @work to
929 * @nextp: out paramter for nested worklist walking
931 * Schedule linked works starting from @work to @head. Work series to
932 * be scheduled starts at @work and includes any consecutive work with
933 * WORK_STRUCT_LINKED set in its predecessor.
935 * If @nextp is not NULL, it's updated to point to the next work of
936 * the last scheduled work. This allows move_linked_works() to be
937 * nested inside outer list_for_each_entry_safe().
940 * spin_lock_irq(pool->lock).
942 static void move_linked_works(struct work_struct *work, struct list_head *head,
943 struct work_struct **nextp)
945 struct work_struct *n;
948 * Linked worklist will always end before the end of the list,
949 * use NULL for list head.
951 list_for_each_entry_safe_from(work, n, NULL, entry) {
952 list_move_tail(&work->entry, head);
953 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
958 * If we're already inside safe list traversal and have moved
959 * multiple works to the scheduled queue, the next position
960 * needs to be updated.
966 static void pwq_activate_delayed_work(struct work_struct *work)
968 struct pool_workqueue *pwq = get_work_pwq(work);
970 trace_workqueue_activate_work(work);
971 move_linked_works(work, &pwq->pool->worklist, NULL);
972 __clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
976 static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
978 struct work_struct *work = list_first_entry(&pwq->delayed_works,
979 struct work_struct, entry);
981 pwq_activate_delayed_work(work);
985 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
986 * @pwq: pwq of interest
987 * @color: color of work which left the queue
989 * A work either has completed or is removed from pending queue,
990 * decrement nr_in_flight of its pwq and handle workqueue flushing.
993 * spin_lock_irq(pool->lock).
995 static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
997 /* ignore uncolored works */
998 if (color == WORK_NO_COLOR)
1001 pwq->nr_in_flight[color]--;
1004 if (!list_empty(&pwq->delayed_works)) {
1005 /* one down, submit a delayed one */
1006 if (pwq->nr_active < pwq->max_active)
1007 pwq_activate_first_delayed(pwq);
1010 /* is flush in progress and are we at the flushing tip? */
1011 if (likely(pwq->flush_color != color))
1014 /* are there still in-flight works? */
1015 if (pwq->nr_in_flight[color])
1018 /* this pwq is done, clear flush_color */
1019 pwq->flush_color = -1;
1022 * If this was the last pwq, wake up the first flusher. It
1023 * will handle the rest.
1025 if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1026 complete(&pwq->wq->first_flusher->done);
1030 * try_to_grab_pending - steal work item from worklist and disable irq
1031 * @work: work item to steal
1032 * @is_dwork: @work is a delayed_work
1033 * @flags: place to store irq state
1035 * Try to grab PENDING bit of @work. This function can handle @work in any
1036 * stable state - idle, on timer or on worklist. Return values are
1038 * 1 if @work was pending and we successfully stole PENDING
1039 * 0 if @work was idle and we claimed PENDING
1040 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1041 * -ENOENT if someone else is canceling @work, this state may persist
1042 * for arbitrarily long
1044 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1045 * interrupted while holding PENDING and @work off queue, irq must be
1046 * disabled on entry. This, combined with delayed_work->timer being
1047 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1049 * On successful return, >= 0, irq is disabled and the caller is
1050 * responsible for releasing it using local_irq_restore(*@flags).
1052 * This function is safe to call from any context including IRQ handler.
1054 static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1055 unsigned long *flags)
1057 struct worker_pool *pool;
1058 struct pool_workqueue *pwq;
1060 local_irq_save(*flags);
1062 /* try to steal the timer if it exists */
1064 struct delayed_work *dwork = to_delayed_work(work);
1067 * dwork->timer is irqsafe. If del_timer() fails, it's
1068 * guaranteed that the timer is not queued anywhere and not
1069 * running on the local CPU.
1071 if (likely(del_timer(&dwork->timer)))
1075 /* try to claim PENDING the normal way */
1076 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1080 * The queueing is in progress, or it is already queued. Try to
1081 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1083 pool = get_work_pool(work);
1087 spin_lock(&pool->lock);
1089 * work->data is guaranteed to point to pwq only while the work
1090 * item is queued on pwq->wq, and both updating work->data to point
1091 * to pwq on queueing and to pool on dequeueing are done under
1092 * pwq->pool->lock. This in turn guarantees that, if work->data
1093 * points to pwq which is associated with a locked pool, the work
1094 * item is currently queued on that pool.
1096 pwq = get_work_pwq(work);
1097 if (pwq && pwq->pool == pool) {
1098 debug_work_deactivate(work);
1101 * A delayed work item cannot be grabbed directly because
1102 * it might have linked NO_COLOR work items which, if left
1103 * on the delayed_list, will confuse pwq->nr_active
1104 * management later on and cause stall. Make sure the work
1105 * item is activated before grabbing.
1107 if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1108 pwq_activate_delayed_work(work);
1110 list_del_init(&work->entry);
1111 pwq_dec_nr_in_flight(get_work_pwq(work), get_work_color(work));
1113 /* work->data points to pwq iff queued, point to pool */
1114 set_work_pool_and_keep_pending(work, pool->id);
1116 spin_unlock(&pool->lock);
1119 spin_unlock(&pool->lock);
1121 local_irq_restore(*flags);
1122 if (work_is_canceling(work))
1129 * insert_work - insert a work into a pool
1130 * @pwq: pwq @work belongs to
1131 * @work: work to insert
1132 * @head: insertion point
1133 * @extra_flags: extra WORK_STRUCT_* flags to set
1135 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
1136 * work_struct flags.
1139 * spin_lock_irq(pool->lock).
1141 static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1142 struct list_head *head, unsigned int extra_flags)
1144 struct worker_pool *pool = pwq->pool;
1146 /* we own @work, set data and link */
1147 set_work_pwq(work, pwq, extra_flags);
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
1165 static bool is_chained_work(struct workqueue_struct *wq)
1167 struct worker *worker;
1169 worker = current_wq_worker();
1171 * Return %true iff I'm a worker execuing a work item on @wq. If
1172 * I'm @worker, it's safe to dereference it without locking.
1174 return worker && worker->current_pwq->wq == wq;
1177 static void __queue_work(unsigned int cpu, struct workqueue_struct *wq,
1178 struct work_struct *work)
1180 struct pool_workqueue *pwq;
1181 struct list_head *worklist;
1182 unsigned int work_flags;
1183 unsigned int req_cpu = cpu;
1186 * While a work item is PENDING && off queue, a task trying to
1187 * steal the PENDING will busy-loop waiting for it to either get
1188 * queued or lose PENDING. Grabbing PENDING and queueing should
1189 * happen with IRQ disabled.
1191 WARN_ON_ONCE(!irqs_disabled());
1193 debug_work_activate(work);
1195 /* if dying, only works from the same workqueue are allowed */
1196 if (unlikely(wq->flags & WQ_DRAINING) &&
1197 WARN_ON_ONCE(!is_chained_work(wq)))
1200 /* determine the pwq to use */
1201 if (!(wq->flags & WQ_UNBOUND)) {
1202 struct worker_pool *last_pool;
1204 if (cpu == WORK_CPU_UNBOUND)
1205 cpu = raw_smp_processor_id();
1208 * It's multi cpu. If @work was previously on a different
1209 * cpu, it might still be running there, in which case the
1210 * work needs to be queued on that cpu to guarantee
1213 pwq = get_pwq(cpu, wq);
1214 last_pool = get_work_pool(work);
1216 if (last_pool && last_pool != pwq->pool) {
1217 struct worker *worker;
1219 spin_lock(&last_pool->lock);
1221 worker = find_worker_executing_work(last_pool, work);
1223 if (worker && worker->current_pwq->wq == wq) {
1224 pwq = get_pwq(last_pool->cpu, wq);
1226 /* meh... not running there, queue here */
1227 spin_unlock(&last_pool->lock);
1228 spin_lock(&pwq->pool->lock);
1231 spin_lock(&pwq->pool->lock);
1234 pwq = get_pwq(WORK_CPU_UNBOUND, wq);
1235 spin_lock(&pwq->pool->lock);
1238 /* pwq determined, queue */
1239 trace_workqueue_queue_work(req_cpu, pwq, work);
1241 if (WARN_ON(!list_empty(&work->entry))) {
1242 spin_unlock(&pwq->pool->lock);
1246 pwq->nr_in_flight[pwq->work_color]++;
1247 work_flags = work_color_to_flags(pwq->work_color);
1249 if (likely(pwq->nr_active < pwq->max_active)) {
1250 trace_workqueue_activate_work(work);
1252 worklist = &pwq->pool->worklist;
1254 work_flags |= WORK_STRUCT_DELAYED;
1255 worklist = &pwq->delayed_works;
1258 insert_work(pwq, work, worklist, work_flags);
1260 spin_unlock(&pwq->pool->lock);
1264 * queue_work_on - queue work on specific cpu
1265 * @cpu: CPU number to execute work on
1266 * @wq: workqueue to use
1267 * @work: work to queue
1269 * Returns %false if @work was already on a queue, %true otherwise.
1271 * We queue the work to a specific CPU, the caller must ensure it
1274 bool queue_work_on(int cpu, struct workqueue_struct *wq,
1275 struct work_struct *work)
1278 unsigned long flags;
1280 local_irq_save(flags);
1282 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1283 __queue_work(cpu, wq, work);
1287 local_irq_restore(flags);
1290 EXPORT_SYMBOL_GPL(queue_work_on);
1293 * queue_work - queue work on a workqueue
1294 * @wq: workqueue to use
1295 * @work: work to queue
1297 * Returns %false if @work was already on a queue, %true otherwise.
1299 * We queue the work to the CPU on which it was submitted, but if the CPU dies
1300 * it can be processed by another CPU.
1302 bool queue_work(struct workqueue_struct *wq, struct work_struct *work)
1304 return queue_work_on(WORK_CPU_UNBOUND, wq, work);
1306 EXPORT_SYMBOL_GPL(queue_work);
1308 void delayed_work_timer_fn(unsigned long __data)
1310 struct delayed_work *dwork = (struct delayed_work *)__data;
1312 /* should have been called from irqsafe timer with irq already off */
1313 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
1315 EXPORT_SYMBOL(delayed_work_timer_fn);
1317 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
1318 struct delayed_work *dwork, unsigned long delay)
1320 struct timer_list *timer = &dwork->timer;
1321 struct work_struct *work = &dwork->work;
1323 WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
1324 timer->data != (unsigned long)dwork);
1325 WARN_ON_ONCE(timer_pending(timer));
1326 WARN_ON_ONCE(!list_empty(&work->entry));
1329 * If @delay is 0, queue @dwork->work immediately. This is for
1330 * both optimization and correctness. The earliest @timer can
1331 * expire is on the closest next tick and delayed_work users depend
1332 * on that there's no such delay when @delay is 0.
1335 __queue_work(cpu, wq, &dwork->work);
1339 timer_stats_timer_set_start_info(&dwork->timer);
1343 timer->expires = jiffies + delay;
1345 if (unlikely(cpu != WORK_CPU_UNBOUND))
1346 add_timer_on(timer, cpu);
1352 * queue_delayed_work_on - queue work on specific CPU after delay
1353 * @cpu: CPU number to execute work on
1354 * @wq: workqueue to use
1355 * @dwork: work to queue
1356 * @delay: number of jiffies to wait before queueing
1358 * Returns %false if @work was already on a queue, %true otherwise. If
1359 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1362 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1363 struct delayed_work *dwork, unsigned long delay)
1365 struct work_struct *work = &dwork->work;
1367 unsigned long flags;
1369 /* read the comment in __queue_work() */
1370 local_irq_save(flags);
1372 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1373 __queue_delayed_work(cpu, wq, dwork, delay);
1377 local_irq_restore(flags);
1380 EXPORT_SYMBOL_GPL(queue_delayed_work_on);
1383 * queue_delayed_work - queue work on a workqueue after delay
1384 * @wq: workqueue to use
1385 * @dwork: delayable work to queue
1386 * @delay: number of jiffies to wait before queueing
1388 * Equivalent to queue_delayed_work_on() but tries to use the local CPU.
1390 bool queue_delayed_work(struct workqueue_struct *wq,
1391 struct delayed_work *dwork, unsigned long delay)
1393 return queue_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
1395 EXPORT_SYMBOL_GPL(queue_delayed_work);
1398 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1399 * @cpu: CPU number to execute work on
1400 * @wq: workqueue to use
1401 * @dwork: work to queue
1402 * @delay: number of jiffies to wait before queueing
1404 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1405 * modify @dwork's timer so that it expires after @delay. If @delay is
1406 * zero, @work is guaranteed to be scheduled immediately regardless of its
1409 * Returns %false if @dwork was idle and queued, %true if @dwork was
1410 * pending and its timer was modified.
1412 * This function is safe to call from any context including IRQ handler.
1413 * See try_to_grab_pending() for details.
1415 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
1416 struct delayed_work *dwork, unsigned long delay)
1418 unsigned long flags;
1422 ret = try_to_grab_pending(&dwork->work, true, &flags);
1423 } while (unlikely(ret == -EAGAIN));
1425 if (likely(ret >= 0)) {
1426 __queue_delayed_work(cpu, wq, dwork, delay);
1427 local_irq_restore(flags);
1430 /* -ENOENT from try_to_grab_pending() becomes %true */
1433 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
1436 * mod_delayed_work - modify delay of or queue a delayed work
1437 * @wq: workqueue to use
1438 * @dwork: work to queue
1439 * @delay: number of jiffies to wait before queueing
1441 * mod_delayed_work_on() on local CPU.
1443 bool mod_delayed_work(struct workqueue_struct *wq, struct delayed_work *dwork,
1444 unsigned long delay)
1446 return mod_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
1448 EXPORT_SYMBOL_GPL(mod_delayed_work);
1451 * worker_enter_idle - enter idle state
1452 * @worker: worker which is entering idle state
1454 * @worker is entering idle state. Update stats and idle timer if
1458 * spin_lock_irq(pool->lock).
1460 static void worker_enter_idle(struct worker *worker)
1462 struct worker_pool *pool = worker->pool;
1464 if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
1465 WARN_ON_ONCE(!list_empty(&worker->entry) &&
1466 (worker->hentry.next || worker->hentry.pprev)))
1469 /* can't use worker_set_flags(), also called from start_worker() */
1470 worker->flags |= WORKER_IDLE;
1472 worker->last_active = jiffies;
1474 /* idle_list is LIFO */
1475 list_add(&worker->entry, &pool->idle_list);
1477 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1478 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1481 * Sanity check nr_running. Because wq_unbind_fn() releases
1482 * pool->lock between setting %WORKER_UNBOUND and zapping
1483 * nr_running, the warning may trigger spuriously. Check iff
1484 * unbind is not in progress.
1486 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1487 pool->nr_workers == pool->nr_idle &&
1488 atomic_read(&pool->nr_running));
1492 * worker_leave_idle - leave idle state
1493 * @worker: worker which is leaving idle state
1495 * @worker is leaving idle state. Update stats.
1498 * spin_lock_irq(pool->lock).
1500 static void worker_leave_idle(struct worker *worker)
1502 struct worker_pool *pool = worker->pool;
1504 if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
1506 worker_clr_flags(worker, WORKER_IDLE);
1508 list_del_init(&worker->entry);
1512 * worker_maybe_bind_and_lock - try to bind %current to worker_pool and lock it
1513 * @pool: target worker_pool
1515 * Bind %current to the cpu of @pool if it is associated and lock @pool.
1517 * Works which are scheduled while the cpu is online must at least be
1518 * scheduled to a worker which is bound to the cpu so that if they are
1519 * flushed from cpu callbacks while cpu is going down, they are
1520 * guaranteed to execute on the cpu.
1522 * This function is to be used by unbound workers and rescuers to bind
1523 * themselves to the target cpu and may race with cpu going down or
1524 * coming online. kthread_bind() can't be used because it may put the
1525 * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1526 * verbatim as it's best effort and blocking and pool may be
1527 * [dis]associated in the meantime.
1529 * This function tries set_cpus_allowed() and locks pool and verifies the
1530 * binding against %POOL_DISASSOCIATED which is set during
1531 * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
1532 * enters idle state or fetches works without dropping lock, it can
1533 * guarantee the scheduling requirement described in the first paragraph.
1536 * Might sleep. Called without any lock but returns with pool->lock
1540 * %true if the associated pool is online (@worker is successfully
1541 * bound), %false if offline.
1543 static bool worker_maybe_bind_and_lock(struct worker_pool *pool)
1544 __acquires(&pool->lock)
1548 * The following call may fail, succeed or succeed
1549 * without actually migrating the task to the cpu if
1550 * it races with cpu hotunplug operation. Verify
1551 * against POOL_DISASSOCIATED.
1553 if (!(pool->flags & POOL_DISASSOCIATED))
1554 set_cpus_allowed_ptr(current, get_cpu_mask(pool->cpu));
1556 spin_lock_irq(&pool->lock);
1557 if (pool->flags & POOL_DISASSOCIATED)
1559 if (task_cpu(current) == pool->cpu &&
1560 cpumask_equal(¤t->cpus_allowed,
1561 get_cpu_mask(pool->cpu)))
1563 spin_unlock_irq(&pool->lock);
1566 * We've raced with CPU hot[un]plug. Give it a breather
1567 * and retry migration. cond_resched() is required here;
1568 * otherwise, we might deadlock against cpu_stop trying to
1569 * bring down the CPU on non-preemptive kernel.
1577 * Rebind an idle @worker to its CPU. worker_thread() will test
1578 * list_empty(@worker->entry) before leaving idle and call this function.
1580 static void idle_worker_rebind(struct worker *worker)
1582 /* CPU may go down again inbetween, clear UNBOUND only on success */
1583 if (worker_maybe_bind_and_lock(worker->pool))
1584 worker_clr_flags(worker, WORKER_UNBOUND);
1586 /* rebind complete, become available again */
1587 list_add(&worker->entry, &worker->pool->idle_list);
1588 spin_unlock_irq(&worker->pool->lock);
1592 * Function for @worker->rebind.work used to rebind unbound busy workers to
1593 * the associated cpu which is coming back online. This is scheduled by
1594 * cpu up but can race with other cpu hotplug operations and may be
1595 * executed twice without intervening cpu down.
1597 static void busy_worker_rebind_fn(struct work_struct *work)
1599 struct worker *worker = container_of(work, struct worker, rebind_work);
1601 if (worker_maybe_bind_and_lock(worker->pool))
1602 worker_clr_flags(worker, WORKER_UNBOUND);
1604 spin_unlock_irq(&worker->pool->lock);
1608 * rebind_workers - rebind all workers of a pool to the associated CPU
1609 * @pool: pool of interest
1611 * @pool->cpu is coming online. Rebind all workers to the CPU. Rebinding
1612 * is different for idle and busy ones.
1614 * Idle ones will be removed from the idle_list and woken up. They will
1615 * add themselves back after completing rebind. This ensures that the
1616 * idle_list doesn't contain any unbound workers when re-bound busy workers
1617 * try to perform local wake-ups for concurrency management.
1619 * Busy workers can rebind after they finish their current work items.
1620 * Queueing the rebind work item at the head of the scheduled list is
1621 * enough. Note that nr_running will be properly bumped as busy workers
1624 * On return, all non-manager workers are scheduled for rebind - see
1625 * manage_workers() for the manager special case. Any idle worker
1626 * including the manager will not appear on @idle_list until rebind is
1627 * complete, making local wake-ups safe.
1629 static void rebind_workers(struct worker_pool *pool)
1631 struct worker *worker, *n;
1634 lockdep_assert_held(&pool->assoc_mutex);
1635 lockdep_assert_held(&pool->lock);
1637 /* dequeue and kick idle ones */
1638 list_for_each_entry_safe(worker, n, &pool->idle_list, entry) {
1640 * idle workers should be off @pool->idle_list until rebind
1641 * is complete to avoid receiving premature local wake-ups.
1643 list_del_init(&worker->entry);
1646 * worker_thread() will see the above dequeuing and call
1647 * idle_worker_rebind().
1649 wake_up_process(worker->task);
1652 /* rebind busy workers */
1653 for_each_busy_worker(worker, i, pool) {
1654 struct work_struct *rebind_work = &worker->rebind_work;
1655 struct workqueue_struct *wq;
1657 if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
1658 work_data_bits(rebind_work)))
1661 debug_work_activate(rebind_work);
1664 * wq doesn't really matter but let's keep @worker->pool
1665 * and @pwq->pool consistent for sanity.
1667 if (std_worker_pool_pri(worker->pool))
1668 wq = system_highpri_wq;
1672 insert_work(get_pwq(pool->cpu, wq), rebind_work,
1673 worker->scheduled.next,
1674 work_color_to_flags(WORK_NO_COLOR));
1678 static struct worker *alloc_worker(void)
1680 struct worker *worker;
1682 worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1684 INIT_LIST_HEAD(&worker->entry);
1685 INIT_LIST_HEAD(&worker->scheduled);
1686 INIT_WORK(&worker->rebind_work, busy_worker_rebind_fn);
1687 /* on creation a worker is in !idle && prep state */
1688 worker->flags = WORKER_PREP;
1694 * create_worker - create a new workqueue worker
1695 * @pool: pool the new worker will belong to
1697 * Create a new worker which is bound to @pool. The returned worker
1698 * can be started by calling start_worker() or destroyed using
1702 * Might sleep. Does GFP_KERNEL allocations.
1705 * Pointer to the newly created worker.
1707 static struct worker *create_worker(struct worker_pool *pool)
1709 const char *pri = std_worker_pool_pri(pool) ? "H" : "";
1710 struct worker *worker = NULL;
1713 spin_lock_irq(&pool->lock);
1714 while (ida_get_new(&pool->worker_ida, &id)) {
1715 spin_unlock_irq(&pool->lock);
1716 if (!ida_pre_get(&pool->worker_ida, GFP_KERNEL))
1718 spin_lock_irq(&pool->lock);
1720 spin_unlock_irq(&pool->lock);
1722 worker = alloc_worker();
1726 worker->pool = pool;
1729 if (pool->cpu != WORK_CPU_UNBOUND)
1730 worker->task = kthread_create_on_node(worker_thread,
1731 worker, cpu_to_node(pool->cpu),
1732 "kworker/%u:%d%s", pool->cpu, id, pri);
1734 worker->task = kthread_create(worker_thread, worker,
1735 "kworker/u:%d%s", id, pri);
1736 if (IS_ERR(worker->task))
1739 if (std_worker_pool_pri(pool))
1740 set_user_nice(worker->task, HIGHPRI_NICE_LEVEL);
1743 * Determine CPU binding of the new worker depending on
1744 * %POOL_DISASSOCIATED. The caller is responsible for ensuring the
1745 * flag remains stable across this function. See the comments
1746 * above the flag definition for details.
1748 * As an unbound worker may later become a regular one if CPU comes
1749 * online, make sure every worker has %PF_THREAD_BOUND set.
1751 if (!(pool->flags & POOL_DISASSOCIATED)) {
1752 kthread_bind(worker->task, pool->cpu);
1754 worker->task->flags |= PF_THREAD_BOUND;
1755 worker->flags |= WORKER_UNBOUND;
1761 spin_lock_irq(&pool->lock);
1762 ida_remove(&pool->worker_ida, id);
1763 spin_unlock_irq(&pool->lock);
1770 * start_worker - start a newly created worker
1771 * @worker: worker to start
1773 * Make the pool aware of @worker and start it.
1776 * spin_lock_irq(pool->lock).
1778 static void start_worker(struct worker *worker)
1780 worker->flags |= WORKER_STARTED;
1781 worker->pool->nr_workers++;
1782 worker_enter_idle(worker);
1783 wake_up_process(worker->task);
1787 * destroy_worker - destroy a workqueue worker
1788 * @worker: worker to be destroyed
1790 * Destroy @worker and adjust @pool stats accordingly.
1793 * spin_lock_irq(pool->lock) which is released and regrabbed.
1795 static void destroy_worker(struct worker *worker)
1797 struct worker_pool *pool = worker->pool;
1798 int id = worker->id;
1800 /* sanity check frenzy */
1801 if (WARN_ON(worker->current_work) ||
1802 WARN_ON(!list_empty(&worker->scheduled)))
1805 if (worker->flags & WORKER_STARTED)
1807 if (worker->flags & WORKER_IDLE)
1810 list_del_init(&worker->entry);
1811 worker->flags |= WORKER_DIE;
1813 spin_unlock_irq(&pool->lock);
1815 kthread_stop(worker->task);
1818 spin_lock_irq(&pool->lock);
1819 ida_remove(&pool->worker_ida, id);
1822 static void idle_worker_timeout(unsigned long __pool)
1824 struct worker_pool *pool = (void *)__pool;
1826 spin_lock_irq(&pool->lock);
1828 if (too_many_workers(pool)) {
1829 struct worker *worker;
1830 unsigned long expires;
1832 /* idle_list is kept in LIFO order, check the last one */
1833 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1834 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1836 if (time_before(jiffies, expires))
1837 mod_timer(&pool->idle_timer, expires);
1839 /* it's been idle for too long, wake up manager */
1840 pool->flags |= POOL_MANAGE_WORKERS;
1841 wake_up_worker(pool);
1845 spin_unlock_irq(&pool->lock);
1848 static bool send_mayday(struct work_struct *work)
1850 struct pool_workqueue *pwq = get_work_pwq(work);
1851 struct workqueue_struct *wq = pwq->wq;
1854 if (!(wq->flags & WQ_RESCUER))
1857 /* mayday mayday mayday */
1858 cpu = pwq->pool->cpu;
1859 /* WORK_CPU_UNBOUND can't be set in cpumask, use cpu 0 instead */
1860 if (cpu == WORK_CPU_UNBOUND)
1862 if (!mayday_test_and_set_cpu(cpu, wq->mayday_mask))
1863 wake_up_process(wq->rescuer->task);
1867 static void pool_mayday_timeout(unsigned long __pool)
1869 struct worker_pool *pool = (void *)__pool;
1870 struct work_struct *work;
1872 spin_lock_irq(&pool->lock);
1874 if (need_to_create_worker(pool)) {
1876 * We've been trying to create a new worker but
1877 * haven't been successful. We might be hitting an
1878 * allocation deadlock. Send distress signals to
1881 list_for_each_entry(work, &pool->worklist, entry)
1885 spin_unlock_irq(&pool->lock);
1887 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1891 * maybe_create_worker - create a new worker if necessary
1892 * @pool: pool to create a new worker for
1894 * Create a new worker for @pool if necessary. @pool is guaranteed to
1895 * have at least one idle worker on return from this function. If
1896 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1897 * sent to all rescuers with works scheduled on @pool to resolve
1898 * possible allocation deadlock.
1900 * On return, need_to_create_worker() is guaranteed to be false and
1901 * may_start_working() true.
1904 * spin_lock_irq(pool->lock) which may be released and regrabbed
1905 * multiple times. Does GFP_KERNEL allocations. Called only from
1909 * false if no action was taken and pool->lock stayed locked, true
1912 static bool maybe_create_worker(struct worker_pool *pool)
1913 __releases(&pool->lock)
1914 __acquires(&pool->lock)
1916 if (!need_to_create_worker(pool))
1919 spin_unlock_irq(&pool->lock);
1921 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1922 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1925 struct worker *worker;
1927 worker = create_worker(pool);
1929 del_timer_sync(&pool->mayday_timer);
1930 spin_lock_irq(&pool->lock);
1931 start_worker(worker);
1932 if (WARN_ON_ONCE(need_to_create_worker(pool)))
1937 if (!need_to_create_worker(pool))
1940 __set_current_state(TASK_INTERRUPTIBLE);
1941 schedule_timeout(CREATE_COOLDOWN);
1943 if (!need_to_create_worker(pool))
1947 del_timer_sync(&pool->mayday_timer);
1948 spin_lock_irq(&pool->lock);
1949 if (need_to_create_worker(pool))
1955 * maybe_destroy_worker - destroy workers which have been idle for a while
1956 * @pool: pool to destroy workers for
1958 * Destroy @pool workers which have been idle for longer than
1959 * IDLE_WORKER_TIMEOUT.
1962 * spin_lock_irq(pool->lock) which may be released and regrabbed
1963 * multiple times. Called only from manager.
1966 * false if no action was taken and pool->lock stayed locked, true
1969 static bool maybe_destroy_workers(struct worker_pool *pool)
1973 while (too_many_workers(pool)) {
1974 struct worker *worker;
1975 unsigned long expires;
1977 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1978 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1980 if (time_before(jiffies, expires)) {
1981 mod_timer(&pool->idle_timer, expires);
1985 destroy_worker(worker);
1993 * manage_workers - manage worker pool
1996 * Assume the manager role and manage the worker pool @worker belongs
1997 * to. At any given time, there can be only zero or one manager per
1998 * pool. The exclusion is handled automatically by this function.
2000 * The caller can safely start processing works on false return. On
2001 * true return, it's guaranteed that need_to_create_worker() is false
2002 * and may_start_working() is true.
2005 * spin_lock_irq(pool->lock) which may be released and regrabbed
2006 * multiple times. Does GFP_KERNEL allocations.
2009 * spin_lock_irq(pool->lock) which may be released and regrabbed
2010 * multiple times. Does GFP_KERNEL allocations.
2012 static bool manage_workers(struct worker *worker)
2014 struct worker_pool *pool = worker->pool;
2017 if (pool->flags & POOL_MANAGING_WORKERS)
2020 pool->flags |= POOL_MANAGING_WORKERS;
2023 * To simplify both worker management and CPU hotplug, hold off
2024 * management while hotplug is in progress. CPU hotplug path can't
2025 * grab %POOL_MANAGING_WORKERS to achieve this because that can
2026 * lead to idle worker depletion (all become busy thinking someone
2027 * else is managing) which in turn can result in deadlock under
2028 * extreme circumstances. Use @pool->assoc_mutex to synchronize
2029 * manager against CPU hotplug.
2031 * assoc_mutex would always be free unless CPU hotplug is in
2032 * progress. trylock first without dropping @pool->lock.
2034 if (unlikely(!mutex_trylock(&pool->assoc_mutex))) {
2035 spin_unlock_irq(&pool->lock);
2036 mutex_lock(&pool->assoc_mutex);
2038 * CPU hotplug could have happened while we were waiting
2039 * for assoc_mutex. Hotplug itself can't handle us
2040 * because manager isn't either on idle or busy list, and
2041 * @pool's state and ours could have deviated.
2043 * As hotplug is now excluded via assoc_mutex, we can
2044 * simply try to bind. It will succeed or fail depending
2045 * on @pool's current state. Try it and adjust
2046 * %WORKER_UNBOUND accordingly.
2048 if (worker_maybe_bind_and_lock(pool))
2049 worker->flags &= ~WORKER_UNBOUND;
2051 worker->flags |= WORKER_UNBOUND;
2056 pool->flags &= ~POOL_MANAGE_WORKERS;
2059 * Destroy and then create so that may_start_working() is true
2062 ret |= maybe_destroy_workers(pool);
2063 ret |= maybe_create_worker(pool);
2065 pool->flags &= ~POOL_MANAGING_WORKERS;
2066 mutex_unlock(&pool->assoc_mutex);
2071 * process_one_work - process single work
2073 * @work: work to process
2075 * Process @work. This function contains all the logics necessary to
2076 * process a single work including synchronization against and
2077 * interaction with other workers on the same cpu, queueing and
2078 * flushing. As long as context requirement is met, any worker can
2079 * call this function to process a work.
2082 * spin_lock_irq(pool->lock) which is released and regrabbed.
2084 static void process_one_work(struct worker *worker, struct work_struct *work)
2085 __releases(&pool->lock)
2086 __acquires(&pool->lock)
2088 struct pool_workqueue *pwq = get_work_pwq(work);
2089 struct worker_pool *pool = worker->pool;
2090 bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
2092 struct worker *collision;
2093 #ifdef CONFIG_LOCKDEP
2095 * It is permissible to free the struct work_struct from
2096 * inside the function that is called from it, this we need to
2097 * take into account for lockdep too. To avoid bogus "held
2098 * lock freed" warnings as well as problems when looking into
2099 * work->lockdep_map, make a copy and use that here.
2101 struct lockdep_map lockdep_map;
2103 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
2106 * Ensure we're on the correct CPU. DISASSOCIATED test is
2107 * necessary to avoid spurious warnings from rescuers servicing the
2108 * unbound or a disassociated pool.
2110 WARN_ON_ONCE(!(worker->flags & WORKER_UNBOUND) &&
2111 !(pool->flags & POOL_DISASSOCIATED) &&
2112 raw_smp_processor_id() != pool->cpu);
2115 * A single work shouldn't be executed concurrently by
2116 * multiple workers on a single cpu. Check whether anyone is
2117 * already processing the work. If so, defer the work to the
2118 * currently executing one.
2120 collision = find_worker_executing_work(pool, work);
2121 if (unlikely(collision)) {
2122 move_linked_works(work, &collision->scheduled, NULL);
2126 /* claim and dequeue */
2127 debug_work_deactivate(work);
2128 hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2129 worker->current_work = work;
2130 worker->current_func = work->func;
2131 worker->current_pwq = pwq;
2132 work_color = get_work_color(work);
2134 list_del_init(&work->entry);
2137 * CPU intensive works don't participate in concurrency
2138 * management. They're the scheduler's responsibility.
2140 if (unlikely(cpu_intensive))
2141 worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
2144 * Unbound pool isn't concurrency managed and work items should be
2145 * executed ASAP. Wake up another worker if necessary.
2147 if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
2148 wake_up_worker(pool);
2151 * Record the last pool and clear PENDING which should be the last
2152 * update to @work. Also, do this inside @pool->lock so that
2153 * PENDING and queued state changes happen together while IRQ is
2156 set_work_pool_and_clear_pending(work, pool->id);
2158 spin_unlock_irq(&pool->lock);
2160 lock_map_acquire_read(&pwq->wq->lockdep_map);
2161 lock_map_acquire(&lockdep_map);
2162 trace_workqueue_execute_start(work);
2163 worker->current_func(work);
2165 * While we must be careful to not use "work" after this, the trace
2166 * point will only record its address.
2168 trace_workqueue_execute_end(work);
2169 lock_map_release(&lockdep_map);
2170 lock_map_release(&pwq->wq->lockdep_map);
2172 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2173 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2174 " last function: %pf\n",
2175 current->comm, preempt_count(), task_pid_nr(current),
2176 worker->current_func);
2177 debug_show_held_locks(current);
2181 spin_lock_irq(&pool->lock);
2183 /* clear cpu intensive status */
2184 if (unlikely(cpu_intensive))
2185 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2187 /* we're done with it, release */
2188 hash_del(&worker->hentry);
2189 worker->current_work = NULL;
2190 worker->current_func = NULL;
2191 worker->current_pwq = NULL;
2192 pwq_dec_nr_in_flight(pwq, work_color);
2196 * process_scheduled_works - process scheduled works
2199 * Process all scheduled works. Please note that the scheduled list
2200 * may change while processing a work, so this function repeatedly
2201 * fetches a work from the top and executes it.
2204 * spin_lock_irq(pool->lock) which may be released and regrabbed
2207 static void process_scheduled_works(struct worker *worker)
2209 while (!list_empty(&worker->scheduled)) {
2210 struct work_struct *work = list_first_entry(&worker->scheduled,
2211 struct work_struct, entry);
2212 process_one_work(worker, work);
2217 * worker_thread - the worker thread function
2220 * The worker thread function. There are NR_CPU_WORKER_POOLS dynamic pools
2221 * of these per each cpu. These workers process all works regardless of
2222 * their specific target workqueue. The only exception is works which
2223 * belong to workqueues with a rescuer which will be explained in
2226 static int worker_thread(void *__worker)
2228 struct worker *worker = __worker;
2229 struct worker_pool *pool = worker->pool;
2231 /* tell the scheduler that this is a workqueue worker */
2232 worker->task->flags |= PF_WQ_WORKER;
2234 spin_lock_irq(&pool->lock);
2236 /* we are off idle list if destruction or rebind is requested */
2237 if (unlikely(list_empty(&worker->entry))) {
2238 spin_unlock_irq(&pool->lock);
2240 /* if DIE is set, destruction is requested */
2241 if (worker->flags & WORKER_DIE) {
2242 worker->task->flags &= ~PF_WQ_WORKER;
2246 /* otherwise, rebind */
2247 idle_worker_rebind(worker);
2251 worker_leave_idle(worker);
2253 /* no more worker necessary? */
2254 if (!need_more_worker(pool))
2257 /* do we need to manage? */
2258 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2262 * ->scheduled list can only be filled while a worker is
2263 * preparing to process a work or actually processing it.
2264 * Make sure nobody diddled with it while I was sleeping.
2266 WARN_ON_ONCE(!list_empty(&worker->scheduled));
2269 * When control reaches this point, we're guaranteed to have
2270 * at least one idle worker or that someone else has already
2271 * assumed the manager role.
2273 worker_clr_flags(worker, WORKER_PREP);
2276 struct work_struct *work =
2277 list_first_entry(&pool->worklist,
2278 struct work_struct, entry);
2280 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2281 /* optimization path, not strictly necessary */
2282 process_one_work(worker, work);
2283 if (unlikely(!list_empty(&worker->scheduled)))
2284 process_scheduled_works(worker);
2286 move_linked_works(work, &worker->scheduled, NULL);
2287 process_scheduled_works(worker);
2289 } while (keep_working(pool));
2291 worker_set_flags(worker, WORKER_PREP, false);
2293 if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
2297 * pool->lock is held and there's no work to process and no need to
2298 * manage, sleep. Workers are woken up only while holding
2299 * pool->lock or from local cpu, so setting the current state
2300 * before releasing pool->lock is enough to prevent losing any
2303 worker_enter_idle(worker);
2304 __set_current_state(TASK_INTERRUPTIBLE);
2305 spin_unlock_irq(&pool->lock);
2311 * rescuer_thread - the rescuer thread function
2314 * Workqueue rescuer thread function. There's one rescuer for each
2315 * workqueue which has WQ_RESCUER set.
2317 * Regular work processing on a pool may block trying to create a new
2318 * worker which uses GFP_KERNEL allocation which has slight chance of
2319 * developing into deadlock if some works currently on the same queue
2320 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2321 * the problem rescuer solves.
2323 * When such condition is possible, the pool summons rescuers of all
2324 * workqueues which have works queued on the pool and let them process
2325 * those works so that forward progress can be guaranteed.
2327 * This should happen rarely.
2329 static int rescuer_thread(void *__rescuer)
2331 struct worker *rescuer = __rescuer;
2332 struct workqueue_struct *wq = rescuer->rescue_wq;
2333 struct list_head *scheduled = &rescuer->scheduled;
2334 bool is_unbound = wq->flags & WQ_UNBOUND;
2337 set_user_nice(current, RESCUER_NICE_LEVEL);
2340 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2341 * doesn't participate in concurrency management.
2343 rescuer->task->flags |= PF_WQ_WORKER;
2345 set_current_state(TASK_INTERRUPTIBLE);
2347 if (kthread_should_stop()) {
2348 __set_current_state(TASK_RUNNING);
2349 rescuer->task->flags &= ~PF_WQ_WORKER;
2354 * See whether any cpu is asking for help. Unbounded
2355 * workqueues use cpu 0 in mayday_mask for CPU_UNBOUND.
2357 for_each_mayday_cpu(cpu, wq->mayday_mask) {
2358 unsigned int tcpu = is_unbound ? WORK_CPU_UNBOUND : cpu;
2359 struct pool_workqueue *pwq = get_pwq(tcpu, wq);
2360 struct worker_pool *pool = pwq->pool;
2361 struct work_struct *work, *n;
2363 __set_current_state(TASK_RUNNING);
2364 mayday_clear_cpu(cpu, wq->mayday_mask);
2366 /* migrate to the target cpu if possible */
2367 worker_maybe_bind_and_lock(pool);
2368 rescuer->pool = pool;
2371 * Slurp in all works issued via this workqueue and
2374 WARN_ON_ONCE(!list_empty(&rescuer->scheduled));
2375 list_for_each_entry_safe(work, n, &pool->worklist, entry)
2376 if (get_work_pwq(work) == pwq)
2377 move_linked_works(work, scheduled, &n);
2379 process_scheduled_works(rescuer);
2382 * Leave this pool. If keep_working() is %true, notify a
2383 * regular worker; otherwise, we end up with 0 concurrency
2384 * and stalling the execution.
2386 if (keep_working(pool))
2387 wake_up_worker(pool);
2389 rescuer->pool = NULL;
2390 spin_unlock_irq(&pool->lock);
2393 /* rescuers should never participate in concurrency management */
2394 WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2400 struct work_struct work;
2401 struct completion done;
2404 static void wq_barrier_func(struct work_struct *work)
2406 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2407 complete(&barr->done);
2411 * insert_wq_barrier - insert a barrier work
2412 * @pwq: pwq to insert barrier into
2413 * @barr: wq_barrier to insert
2414 * @target: target work to attach @barr to
2415 * @worker: worker currently executing @target, NULL if @target is not executing
2417 * @barr is linked to @target such that @barr is completed only after
2418 * @target finishes execution. Please note that the ordering
2419 * guarantee is observed only with respect to @target and on the local
2422 * Currently, a queued barrier can't be canceled. This is because
2423 * try_to_grab_pending() can't determine whether the work to be
2424 * grabbed is at the head of the queue and thus can't clear LINKED
2425 * flag of the previous work while there must be a valid next work
2426 * after a work with LINKED flag set.
2428 * Note that when @worker is non-NULL, @target may be modified
2429 * underneath us, so we can't reliably determine pwq from @target.
2432 * spin_lock_irq(pool->lock).
2434 static void insert_wq_barrier(struct pool_workqueue *pwq,
2435 struct wq_barrier *barr,
2436 struct work_struct *target, struct worker *worker)
2438 struct list_head *head;
2439 unsigned int linked = 0;
2442 * debugobject calls are safe here even with pool->lock locked
2443 * as we know for sure that this will not trigger any of the
2444 * checks and call back into the fixup functions where we
2447 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2448 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2449 init_completion(&barr->done);
2452 * If @target is currently being executed, schedule the
2453 * barrier to the worker; otherwise, put it after @target.
2456 head = worker->scheduled.next;
2458 unsigned long *bits = work_data_bits(target);
2460 head = target->entry.next;
2461 /* there can already be other linked works, inherit and set */
2462 linked = *bits & WORK_STRUCT_LINKED;
2463 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2466 debug_work_activate(&barr->work);
2467 insert_work(pwq, &barr->work, head,
2468 work_color_to_flags(WORK_NO_COLOR) | linked);
2472 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
2473 * @wq: workqueue being flushed
2474 * @flush_color: new flush color, < 0 for no-op
2475 * @work_color: new work color, < 0 for no-op
2477 * Prepare pwqs for workqueue flushing.
2479 * If @flush_color is non-negative, flush_color on all pwqs should be
2480 * -1. If no pwq has in-flight commands at the specified color, all
2481 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
2482 * has in flight commands, its pwq->flush_color is set to
2483 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
2484 * wakeup logic is armed and %true is returned.
2486 * The caller should have initialized @wq->first_flusher prior to
2487 * calling this function with non-negative @flush_color. If
2488 * @flush_color is negative, no flush color update is done and %false
2491 * If @work_color is non-negative, all pwqs should have the same
2492 * work_color which is previous to @work_color and all will be
2493 * advanced to @work_color.
2496 * mutex_lock(wq->flush_mutex).
2499 * %true if @flush_color >= 0 and there's something to flush. %false
2502 static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
2503 int flush_color, int work_color)
2508 if (flush_color >= 0) {
2509 WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2510 atomic_set(&wq->nr_pwqs_to_flush, 1);
2513 for_each_pwq_cpu(cpu, wq) {
2514 struct pool_workqueue *pwq = get_pwq(cpu, wq);
2515 struct worker_pool *pool = pwq->pool;
2517 spin_lock_irq(&pool->lock);
2519 if (flush_color >= 0) {
2520 WARN_ON_ONCE(pwq->flush_color != -1);
2522 if (pwq->nr_in_flight[flush_color]) {
2523 pwq->flush_color = flush_color;
2524 atomic_inc(&wq->nr_pwqs_to_flush);
2529 if (work_color >= 0) {
2530 WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2531 pwq->work_color = work_color;
2534 spin_unlock_irq(&pool->lock);
2537 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
2538 complete(&wq->first_flusher->done);
2544 * flush_workqueue - ensure that any scheduled work has run to completion.
2545 * @wq: workqueue to flush
2547 * Forces execution of the workqueue and blocks until its completion.
2548 * This is typically used in driver shutdown handlers.
2550 * We sleep until all works which were queued on entry have been handled,
2551 * but we are not livelocked by new incoming ones.
2553 void flush_workqueue(struct workqueue_struct *wq)
2555 struct wq_flusher this_flusher = {
2556 .list = LIST_HEAD_INIT(this_flusher.list),
2558 .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
2562 lock_map_acquire(&wq->lockdep_map);
2563 lock_map_release(&wq->lockdep_map);
2565 mutex_lock(&wq->flush_mutex);
2568 * Start-to-wait phase
2570 next_color = work_next_color(wq->work_color);
2572 if (next_color != wq->flush_color) {
2574 * Color space is not full. The current work_color
2575 * becomes our flush_color and work_color is advanced
2578 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
2579 this_flusher.flush_color = wq->work_color;
2580 wq->work_color = next_color;
2582 if (!wq->first_flusher) {
2583 /* no flush in progress, become the first flusher */
2584 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2586 wq->first_flusher = &this_flusher;
2588 if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
2590 /* nothing to flush, done */
2591 wq->flush_color = next_color;
2592 wq->first_flusher = NULL;
2597 WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
2598 list_add_tail(&this_flusher.list, &wq->flusher_queue);
2599 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2603 * Oops, color space is full, wait on overflow queue.
2604 * The next flush completion will assign us
2605 * flush_color and transfer to flusher_queue.
2607 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2610 mutex_unlock(&wq->flush_mutex);
2612 wait_for_completion(&this_flusher.done);
2615 * Wake-up-and-cascade phase
2617 * First flushers are responsible for cascading flushes and
2618 * handling overflow. Non-first flushers can simply return.
2620 if (wq->first_flusher != &this_flusher)
2623 mutex_lock(&wq->flush_mutex);
2625 /* we might have raced, check again with mutex held */
2626 if (wq->first_flusher != &this_flusher)
2629 wq->first_flusher = NULL;
2631 WARN_ON_ONCE(!list_empty(&this_flusher.list));
2632 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2635 struct wq_flusher *next, *tmp;
2637 /* complete all the flushers sharing the current flush color */
2638 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2639 if (next->flush_color != wq->flush_color)
2641 list_del_init(&next->list);
2642 complete(&next->done);
2645 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
2646 wq->flush_color != work_next_color(wq->work_color));
2648 /* this flush_color is finished, advance by one */
2649 wq->flush_color = work_next_color(wq->flush_color);
2651 /* one color has been freed, handle overflow queue */
2652 if (!list_empty(&wq->flusher_overflow)) {
2654 * Assign the same color to all overflowed
2655 * flushers, advance work_color and append to
2656 * flusher_queue. This is the start-to-wait
2657 * phase for these overflowed flushers.
2659 list_for_each_entry(tmp, &wq->flusher_overflow, list)
2660 tmp->flush_color = wq->work_color;
2662 wq->work_color = work_next_color(wq->work_color);
2664 list_splice_tail_init(&wq->flusher_overflow,
2665 &wq->flusher_queue);
2666 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2669 if (list_empty(&wq->flusher_queue)) {
2670 WARN_ON_ONCE(wq->flush_color != wq->work_color);
2675 * Need to flush more colors. Make the next flusher
2676 * the new first flusher and arm pwqs.
2678 WARN_ON_ONCE(wq->flush_color == wq->work_color);
2679 WARN_ON_ONCE(wq->flush_color != next->flush_color);
2681 list_del_init(&next->list);
2682 wq->first_flusher = next;
2684 if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
2688 * Meh... this color is already done, clear first
2689 * flusher and repeat cascading.
2691 wq->first_flusher = NULL;
2695 mutex_unlock(&wq->flush_mutex);
2697 EXPORT_SYMBOL_GPL(flush_workqueue);
2700 * drain_workqueue - drain a workqueue
2701 * @wq: workqueue to drain
2703 * Wait until the workqueue becomes empty. While draining is in progress,
2704 * only chain queueing is allowed. IOW, only currently pending or running
2705 * work items on @wq can queue further work items on it. @wq is flushed
2706 * repeatedly until it becomes empty. The number of flushing is detemined
2707 * by the depth of chaining and should be relatively short. Whine if it
2710 void drain_workqueue(struct workqueue_struct *wq)
2712 unsigned int flush_cnt = 0;
2716 * __queue_work() needs to test whether there are drainers, is much
2717 * hotter than drain_workqueue() and already looks at @wq->flags.
2718 * Use WQ_DRAINING so that queue doesn't have to check nr_drainers.
2720 spin_lock_irq(&workqueue_lock);
2721 if (!wq->nr_drainers++)
2722 wq->flags |= WQ_DRAINING;
2723 spin_unlock_irq(&workqueue_lock);
2725 flush_workqueue(wq);
2727 for_each_pwq_cpu(cpu, wq) {
2728 struct pool_workqueue *pwq = get_pwq(cpu, wq);
2731 spin_lock_irq(&pwq->pool->lock);
2732 drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
2733 spin_unlock_irq(&pwq->pool->lock);
2738 if (++flush_cnt == 10 ||
2739 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2740 pr_warn("workqueue %s: flush on destruction isn't complete after %u tries\n",
2741 wq->name, flush_cnt);
2745 spin_lock_irq(&workqueue_lock);
2746 if (!--wq->nr_drainers)
2747 wq->flags &= ~WQ_DRAINING;
2748 spin_unlock_irq(&workqueue_lock);
2750 EXPORT_SYMBOL_GPL(drain_workqueue);
2752 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2754 struct worker *worker = NULL;
2755 struct worker_pool *pool;
2756 struct pool_workqueue *pwq;
2759 pool = get_work_pool(work);
2763 spin_lock_irq(&pool->lock);
2764 /* see the comment in try_to_grab_pending() with the same code */
2765 pwq = get_work_pwq(work);
2767 if (unlikely(pwq->pool != pool))
2770 worker = find_worker_executing_work(pool, work);
2773 pwq = worker->current_pwq;
2776 insert_wq_barrier(pwq, barr, work, worker);
2777 spin_unlock_irq(&pool->lock);
2780 * If @max_active is 1 or rescuer is in use, flushing another work
2781 * item on the same workqueue may lead to deadlock. Make sure the
2782 * flusher is not running on the same workqueue by verifying write
2785 if (pwq->wq->saved_max_active == 1 || pwq->wq->flags & WQ_RESCUER)
2786 lock_map_acquire(&pwq->wq->lockdep_map);
2788 lock_map_acquire_read(&pwq->wq->lockdep_map);
2789 lock_map_release(&pwq->wq->lockdep_map);
2793 spin_unlock_irq(&pool->lock);
2798 * flush_work - wait for a work to finish executing the last queueing instance
2799 * @work: the work to flush
2801 * Wait until @work has finished execution. @work is guaranteed to be idle
2802 * on return if it hasn't been requeued since flush started.
2805 * %true if flush_work() waited for the work to finish execution,
2806 * %false if it was already idle.
2808 bool flush_work(struct work_struct *work)
2810 struct wq_barrier barr;
2812 lock_map_acquire(&work->lockdep_map);
2813 lock_map_release(&work->lockdep_map);
2815 if (start_flush_work(work, &barr)) {
2816 wait_for_completion(&barr.done);
2817 destroy_work_on_stack(&barr.work);
2823 EXPORT_SYMBOL_GPL(flush_work);
2825 static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2827 unsigned long flags;
2831 ret = try_to_grab_pending(work, is_dwork, &flags);
2833 * If someone else is canceling, wait for the same event it
2834 * would be waiting for before retrying.
2836 if (unlikely(ret == -ENOENT))
2838 } while (unlikely(ret < 0));
2840 /* tell other tasks trying to grab @work to back off */
2841 mark_work_canceling(work);
2842 local_irq_restore(flags);
2845 clear_work_data(work);
2850 * cancel_work_sync - cancel a work and wait for it to finish
2851 * @work: the work to cancel
2853 * Cancel @work and wait for its execution to finish. This function
2854 * can be used even if the work re-queues itself or migrates to
2855 * another workqueue. On return from this function, @work is
2856 * guaranteed to be not pending or executing on any CPU.
2858 * cancel_work_sync(&delayed_work->work) must not be used for
2859 * delayed_work's. Use cancel_delayed_work_sync() instead.
2861 * The caller must ensure that the workqueue on which @work was last
2862 * queued can't be destroyed before this function returns.
2865 * %true if @work was pending, %false otherwise.
2867 bool cancel_work_sync(struct work_struct *work)
2869 return __cancel_work_timer(work, false);
2871 EXPORT_SYMBOL_GPL(cancel_work_sync);
2874 * flush_delayed_work - wait for a dwork to finish executing the last queueing
2875 * @dwork: the delayed work to flush
2877 * Delayed timer is cancelled and the pending work is queued for
2878 * immediate execution. Like flush_work(), this function only
2879 * considers the last queueing instance of @dwork.
2882 * %true if flush_work() waited for the work to finish execution,
2883 * %false if it was already idle.
2885 bool flush_delayed_work(struct delayed_work *dwork)
2887 local_irq_disable();
2888 if (del_timer_sync(&dwork->timer))
2889 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
2891 return flush_work(&dwork->work);
2893 EXPORT_SYMBOL(flush_delayed_work);
2896 * cancel_delayed_work - cancel a delayed work
2897 * @dwork: delayed_work to cancel
2899 * Kill off a pending delayed_work. Returns %true if @dwork was pending
2900 * and canceled; %false if wasn't pending. Note that the work callback
2901 * function may still be running on return, unless it returns %true and the
2902 * work doesn't re-arm itself. Explicitly flush or use
2903 * cancel_delayed_work_sync() to wait on it.
2905 * This function is safe to call from any context including IRQ handler.
2907 bool cancel_delayed_work(struct delayed_work *dwork)
2909 unsigned long flags;
2913 ret = try_to_grab_pending(&dwork->work, true, &flags);
2914 } while (unlikely(ret == -EAGAIN));
2916 if (unlikely(ret < 0))
2919 set_work_pool_and_clear_pending(&dwork->work,
2920 get_work_pool_id(&dwork->work));
2921 local_irq_restore(flags);
2924 EXPORT_SYMBOL(cancel_delayed_work);
2927 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2928 * @dwork: the delayed work cancel
2930 * This is cancel_work_sync() for delayed works.
2933 * %true if @dwork was pending, %false otherwise.
2935 bool cancel_delayed_work_sync(struct delayed_work *dwork)
2937 return __cancel_work_timer(&dwork->work, true);
2939 EXPORT_SYMBOL(cancel_delayed_work_sync);
2942 * schedule_work_on - put work task on a specific cpu
2943 * @cpu: cpu to put the work task on
2944 * @work: job to be done
2946 * This puts a job on a specific cpu
2948 bool schedule_work_on(int cpu, struct work_struct *work)
2950 return queue_work_on(cpu, system_wq, work);
2952 EXPORT_SYMBOL(schedule_work_on);
2955 * schedule_work - put work task in global workqueue
2956 * @work: job to be done
2958 * Returns %false if @work was already on the kernel-global workqueue and
2961 * This puts a job in the kernel-global workqueue if it was not already
2962 * queued and leaves it in the same position on the kernel-global
2963 * workqueue otherwise.
2965 bool schedule_work(struct work_struct *work)
2967 return queue_work(system_wq, work);
2969 EXPORT_SYMBOL(schedule_work);
2972 * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
2974 * @dwork: job to be done
2975 * @delay: number of jiffies to wait
2977 * After waiting for a given time this puts a job in the kernel-global
2978 * workqueue on the specified CPU.
2980 bool schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
2981 unsigned long delay)
2983 return queue_delayed_work_on(cpu, system_wq, dwork, delay);
2985 EXPORT_SYMBOL(schedule_delayed_work_on);
2988 * schedule_delayed_work - put work task in global workqueue after delay
2989 * @dwork: job to be done
2990 * @delay: number of jiffies to wait or 0 for immediate execution
2992 * After waiting for a given time this puts a job in the kernel-global
2995 bool schedule_delayed_work(struct delayed_work *dwork, unsigned long delay)
2997 return queue_delayed_work(system_wq, dwork, delay);
2999 EXPORT_SYMBOL(schedule_delayed_work);
3002 * schedule_on_each_cpu - execute a function synchronously on each online CPU
3003 * @func: the function to call
3005 * schedule_on_each_cpu() executes @func on each online CPU using the
3006 * system workqueue and blocks until all CPUs have completed.
3007 * schedule_on_each_cpu() is very slow.
3010 * 0 on success, -errno on failure.
3012 int schedule_on_each_cpu(work_func_t func)
3015 struct work_struct __percpu *works;
3017 works = alloc_percpu(struct work_struct);
3023 for_each_online_cpu(cpu) {
3024 struct work_struct *work = per_cpu_ptr(works, cpu);
3026 INIT_WORK(work, func);
3027 schedule_work_on(cpu, work);
3030 for_each_online_cpu(cpu)
3031 flush_work(per_cpu_ptr(works, cpu));
3039 * flush_scheduled_work - ensure that any scheduled work has run to completion.
3041 * Forces execution of the kernel-global workqueue and blocks until its
3044 * Think twice before calling this function! It's very easy to get into
3045 * trouble if you don't take great care. Either of the following situations
3046 * will lead to deadlock:
3048 * One of the work items currently on the workqueue needs to acquire
3049 * a lock held by your code or its caller.
3051 * Your code is running in the context of a work routine.
3053 * They will be detected by lockdep when they occur, but the first might not
3054 * occur very often. It depends on what work items are on the workqueue and
3055 * what locks they need, which you have no control over.
3057 * In most situations flushing the entire workqueue is overkill; you merely
3058 * need to know that a particular work item isn't queued and isn't running.
3059 * In such cases you should use cancel_delayed_work_sync() or
3060 * cancel_work_sync() instead.
3062 void flush_scheduled_work(void)
3064 flush_workqueue(system_wq);
3066 EXPORT_SYMBOL(flush_scheduled_work);
3069 * execute_in_process_context - reliably execute the routine with user context
3070 * @fn: the function to execute
3071 * @ew: guaranteed storage for the execute work structure (must
3072 * be available when the work executes)
3074 * Executes the function immediately if process context is available,
3075 * otherwise schedules the function for delayed execution.
3077 * Returns: 0 - function was executed
3078 * 1 - function was scheduled for execution
3080 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
3082 if (!in_interrupt()) {
3087 INIT_WORK(&ew->work, fn);
3088 schedule_work(&ew->work);
3092 EXPORT_SYMBOL_GPL(execute_in_process_context);
3094 int keventd_up(void)
3096 return system_wq != NULL;
3099 static int alloc_pwqs(struct workqueue_struct *wq)
3101 if (!(wq->flags & WQ_UNBOUND))
3102 wq->pool_wq.pcpu = alloc_percpu(struct pool_workqueue);
3104 wq->pool_wq.single = kmem_cache_zalloc(pwq_cache, GFP_KERNEL);
3106 return wq->pool_wq.v ? 0 : -ENOMEM;
3109 static void free_pwqs(struct workqueue_struct *wq)
3111 if (!(wq->flags & WQ_UNBOUND))
3112 free_percpu(wq->pool_wq.pcpu);
3114 kmem_cache_free(pwq_cache, wq->pool_wq.single);
3117 static int wq_clamp_max_active(int max_active, unsigned int flags,
3120 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3122 if (max_active < 1 || max_active > lim)
3123 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3124 max_active, name, 1, lim);
3126 return clamp_val(max_active, 1, lim);
3129 struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
3132 struct lock_class_key *key,
3133 const char *lock_name, ...)
3135 va_list args, args1;
3136 struct workqueue_struct *wq;
3140 /* determine namelen, allocate wq and format name */
3141 va_start(args, lock_name);
3142 va_copy(args1, args);
3143 namelen = vsnprintf(NULL, 0, fmt, args) + 1;
3145 wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
3149 vsnprintf(wq->name, namelen, fmt, args1);
3154 * Workqueues which may be used during memory reclaim should
3155 * have a rescuer to guarantee forward progress.
3157 if (flags & WQ_MEM_RECLAIM)
3158 flags |= WQ_RESCUER;
3160 max_active = max_active ?: WQ_DFL_ACTIVE;
3161 max_active = wq_clamp_max_active(max_active, flags, wq->name);
3165 wq->saved_max_active = max_active;
3166 mutex_init(&wq->flush_mutex);
3167 atomic_set(&wq->nr_pwqs_to_flush, 0);
3168 INIT_LIST_HEAD(&wq->flusher_queue);
3169 INIT_LIST_HEAD(&wq->flusher_overflow);
3171 lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3172 INIT_LIST_HEAD(&wq->list);
3174 if (alloc_pwqs(wq) < 0)
3177 for_each_pwq_cpu(cpu, wq) {
3178 struct pool_workqueue *pwq = get_pwq(cpu, wq);
3180 BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3181 pwq->pool = get_std_worker_pool(cpu, flags & WQ_HIGHPRI);
3183 pwq->flush_color = -1;
3184 pwq->max_active = max_active;
3185 INIT_LIST_HEAD(&pwq->delayed_works);
3188 if (flags & WQ_RESCUER) {
3189 struct worker *rescuer;
3191 if (!alloc_mayday_mask(&wq->mayday_mask, GFP_KERNEL))
3194 wq->rescuer = rescuer = alloc_worker();
3198 rescuer->rescue_wq = wq;
3199 rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
3201 if (IS_ERR(rescuer->task))
3204 rescuer->task->flags |= PF_THREAD_BOUND;
3205 wake_up_process(rescuer->task);
3209 * workqueue_lock protects global freeze state and workqueues
3210 * list. Grab it, set max_active accordingly and add the new
3211 * workqueue to workqueues list.
3213 spin_lock_irq(&workqueue_lock);
3215 if (workqueue_freezing && wq->flags & WQ_FREEZABLE)
3216 for_each_pwq_cpu(cpu, wq)
3217 get_pwq(cpu, wq)->max_active = 0;
3219 list_add(&wq->list, &workqueues);
3221 spin_unlock_irq(&workqueue_lock);
3227 free_mayday_mask(wq->mayday_mask);
3233 EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
3236 * destroy_workqueue - safely terminate a workqueue
3237 * @wq: target workqueue
3239 * Safely destroy a workqueue. All work currently pending will be done first.
3241 void destroy_workqueue(struct workqueue_struct *wq)
3245 /* drain it before proceeding with destruction */
3246 drain_workqueue(wq);
3249 for_each_pwq_cpu(cpu, wq) {
3250 struct pool_workqueue *pwq = get_pwq(cpu, wq);
3253 for (i = 0; i < WORK_NR_COLORS; i++)
3254 if (WARN_ON(pwq->nr_in_flight[i]))
3256 if (WARN_ON(pwq->nr_active) ||
3257 WARN_ON(!list_empty(&pwq->delayed_works)))
3262 * wq list is used to freeze wq, remove from list after
3263 * flushing is complete in case freeze races us.
3265 spin_lock_irq(&workqueue_lock);
3266 list_del(&wq->list);
3267 spin_unlock_irq(&workqueue_lock);
3269 if (wq->flags & WQ_RESCUER) {
3270 kthread_stop(wq->rescuer->task);
3271 free_mayday_mask(wq->mayday_mask);
3278 EXPORT_SYMBOL_GPL(destroy_workqueue);
3281 * pwq_set_max_active - adjust max_active of a pwq
3282 * @pwq: target pool_workqueue
3283 * @max_active: new max_active value.
3285 * Set @pwq->max_active to @max_active and activate delayed works if
3289 * spin_lock_irq(pool->lock).
3291 static void pwq_set_max_active(struct pool_workqueue *pwq, int max_active)
3293 pwq->max_active = max_active;
3295 while (!list_empty(&pwq->delayed_works) &&
3296 pwq->nr_active < pwq->max_active)
3297 pwq_activate_first_delayed(pwq);
3301 * workqueue_set_max_active - adjust max_active of a workqueue
3302 * @wq: target workqueue
3303 * @max_active: new max_active value.
3305 * Set max_active of @wq to @max_active.
3308 * Don't call from IRQ context.
3310 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
3314 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
3316 spin_lock_irq(&workqueue_lock);
3318 wq->saved_max_active = max_active;
3320 for_each_pwq_cpu(cpu, wq) {
3321 struct pool_workqueue *pwq = get_pwq(cpu, wq);
3322 struct worker_pool *pool = pwq->pool;
3324 spin_lock(&pool->lock);
3326 if (!(wq->flags & WQ_FREEZABLE) ||
3327 !(pool->flags & POOL_FREEZING))
3328 pwq_set_max_active(pwq, max_active);
3330 spin_unlock(&pool->lock);
3333 spin_unlock_irq(&workqueue_lock);
3335 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
3338 * workqueue_congested - test whether a workqueue is congested
3339 * @cpu: CPU in question
3340 * @wq: target workqueue
3342 * Test whether @wq's cpu workqueue for @cpu is congested. There is
3343 * no synchronization around this function and the test result is
3344 * unreliable and only useful as advisory hints or for debugging.
3347 * %true if congested, %false otherwise.
3349 bool workqueue_congested(unsigned int cpu, struct workqueue_struct *wq)
3351 struct pool_workqueue *pwq = get_pwq(cpu, wq);
3353 return !list_empty(&pwq->delayed_works);
3355 EXPORT_SYMBOL_GPL(workqueue_congested);
3358 * work_busy - test whether a work is currently pending or running
3359 * @work: the work to be tested
3361 * Test whether @work is currently pending or running. There is no
3362 * synchronization around this function and the test result is
3363 * unreliable and only useful as advisory hints or for debugging.
3366 * OR'd bitmask of WORK_BUSY_* bits.
3368 unsigned int work_busy(struct work_struct *work)
3370 struct worker_pool *pool = get_work_pool(work);
3371 unsigned long flags;
3372 unsigned int ret = 0;
3374 if (work_pending(work))
3375 ret |= WORK_BUSY_PENDING;
3378 spin_lock_irqsave(&pool->lock, flags);
3379 if (find_worker_executing_work(pool, work))
3380 ret |= WORK_BUSY_RUNNING;
3381 spin_unlock_irqrestore(&pool->lock, flags);
3386 EXPORT_SYMBOL_GPL(work_busy);
3391 * There are two challenges in supporting CPU hotplug. Firstly, there
3392 * are a lot of assumptions on strong associations among work, pwq and
3393 * pool which make migrating pending and scheduled works very
3394 * difficult to implement without impacting hot paths. Secondly,
3395 * worker pools serve mix of short, long and very long running works making
3396 * blocked draining impractical.
3398 * This is solved by allowing the pools to be disassociated from the CPU
3399 * running as an unbound one and allowing it to be reattached later if the
3400 * cpu comes back online.
3403 static void wq_unbind_fn(struct work_struct *work)
3405 int cpu = smp_processor_id();
3406 struct worker_pool *pool;
3407 struct worker *worker;
3410 for_each_std_worker_pool(pool, cpu) {
3411 WARN_ON_ONCE(cpu != smp_processor_id());
3413 mutex_lock(&pool->assoc_mutex);
3414 spin_lock_irq(&pool->lock);
3417 * We've claimed all manager positions. Make all workers
3418 * unbound and set DISASSOCIATED. Before this, all workers
3419 * except for the ones which are still executing works from
3420 * before the last CPU down must be on the cpu. After
3421 * this, they may become diasporas.
3423 list_for_each_entry(worker, &pool->idle_list, entry)
3424 worker->flags |= WORKER_UNBOUND;
3426 for_each_busy_worker(worker, i, pool)
3427 worker->flags |= WORKER_UNBOUND;
3429 pool->flags |= POOL_DISASSOCIATED;
3431 spin_unlock_irq(&pool->lock);
3432 mutex_unlock(&pool->assoc_mutex);
3436 * Call schedule() so that we cross rq->lock and thus can guarantee
3437 * sched callbacks see the %WORKER_UNBOUND flag. This is necessary
3438 * as scheduler callbacks may be invoked from other cpus.
3443 * Sched callbacks are disabled now. Zap nr_running. After this,
3444 * nr_running stays zero and need_more_worker() and keep_working()
3445 * are always true as long as the worklist is not empty. Pools on
3446 * @cpu now behave as unbound (in terms of concurrency management)
3447 * pools which are served by workers tied to the CPU.
3449 * On return from this function, the current worker would trigger
3450 * unbound chain execution of pending work items if other workers
3453 for_each_std_worker_pool(pool, cpu)
3454 atomic_set(&pool->nr_running, 0);
3458 * Workqueues should be brought up before normal priority CPU notifiers.
3459 * This will be registered high priority CPU notifier.
3461 static int __cpuinit workqueue_cpu_up_callback(struct notifier_block *nfb,
3462 unsigned long action,
3465 unsigned int cpu = (unsigned long)hcpu;
3466 struct worker_pool *pool;
3468 switch (action & ~CPU_TASKS_FROZEN) {
3469 case CPU_UP_PREPARE:
3470 for_each_std_worker_pool(pool, cpu) {
3471 struct worker *worker;
3473 if (pool->nr_workers)
3476 worker = create_worker(pool);
3480 spin_lock_irq(&pool->lock);
3481 start_worker(worker);
3482 spin_unlock_irq(&pool->lock);
3486 case CPU_DOWN_FAILED:
3488 for_each_std_worker_pool(pool, cpu) {
3489 mutex_lock(&pool->assoc_mutex);
3490 spin_lock_irq(&pool->lock);
3492 pool->flags &= ~POOL_DISASSOCIATED;
3493 rebind_workers(pool);
3495 spin_unlock_irq(&pool->lock);
3496 mutex_unlock(&pool->assoc_mutex);
3504 * Workqueues should be brought down after normal priority CPU notifiers.
3505 * This will be registered as low priority CPU notifier.
3507 static int __cpuinit workqueue_cpu_down_callback(struct notifier_block *nfb,
3508 unsigned long action,
3511 unsigned int cpu = (unsigned long)hcpu;
3512 struct work_struct unbind_work;
3514 switch (action & ~CPU_TASKS_FROZEN) {
3515 case CPU_DOWN_PREPARE:
3516 /* unbinding should happen on the local CPU */
3517 INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
3518 queue_work_on(cpu, system_highpri_wq, &unbind_work);
3519 flush_work(&unbind_work);
3527 struct work_for_cpu {
3528 struct work_struct work;
3534 static void work_for_cpu_fn(struct work_struct *work)
3536 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
3538 wfc->ret = wfc->fn(wfc->arg);
3542 * work_on_cpu - run a function in user context on a particular cpu
3543 * @cpu: the cpu to run on
3544 * @fn: the function to run
3545 * @arg: the function arg
3547 * This will return the value @fn returns.
3548 * It is up to the caller to ensure that the cpu doesn't go offline.
3549 * The caller must not hold any locks which would prevent @fn from completing.
3551 long work_on_cpu(unsigned int cpu, long (*fn)(void *), void *arg)
3553 struct work_for_cpu wfc = { .fn = fn, .arg = arg };
3555 INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
3556 schedule_work_on(cpu, &wfc.work);
3557 flush_work(&wfc.work);
3560 EXPORT_SYMBOL_GPL(work_on_cpu);
3561 #endif /* CONFIG_SMP */
3563 #ifdef CONFIG_FREEZER
3566 * freeze_workqueues_begin - begin freezing workqueues
3568 * Start freezing workqueues. After this function returns, all freezable
3569 * workqueues will queue new works to their frozen_works list instead of
3573 * Grabs and releases workqueue_lock and pool->lock's.
3575 void freeze_workqueues_begin(void)
3579 spin_lock_irq(&workqueue_lock);
3581 WARN_ON_ONCE(workqueue_freezing);
3582 workqueue_freezing = true;
3584 for_each_wq_cpu(cpu) {
3585 struct worker_pool *pool;
3586 struct workqueue_struct *wq;
3588 for_each_std_worker_pool(pool, cpu) {
3589 spin_lock(&pool->lock);
3591 WARN_ON_ONCE(pool->flags & POOL_FREEZING);
3592 pool->flags |= POOL_FREEZING;
3594 list_for_each_entry(wq, &workqueues, list) {
3595 struct pool_workqueue *pwq = get_pwq(cpu, wq);
3597 if (pwq && pwq->pool == pool &&
3598 (wq->flags & WQ_FREEZABLE))
3599 pwq->max_active = 0;
3602 spin_unlock(&pool->lock);
3606 spin_unlock_irq(&workqueue_lock);
3610 * freeze_workqueues_busy - are freezable workqueues still busy?
3612 * Check whether freezing is complete. This function must be called
3613 * between freeze_workqueues_begin() and thaw_workqueues().
3616 * Grabs and releases workqueue_lock.
3619 * %true if some freezable workqueues are still busy. %false if freezing
3622 bool freeze_workqueues_busy(void)
3627 spin_lock_irq(&workqueue_lock);
3629 WARN_ON_ONCE(!workqueue_freezing);
3631 for_each_wq_cpu(cpu) {
3632 struct workqueue_struct *wq;
3634 * nr_active is monotonically decreasing. It's safe
3635 * to peek without lock.
3637 list_for_each_entry(wq, &workqueues, list) {
3638 struct pool_workqueue *pwq = get_pwq(cpu, wq);
3640 if (!pwq || !(wq->flags & WQ_FREEZABLE))
3643 WARN_ON_ONCE(pwq->nr_active < 0);
3644 if (pwq->nr_active) {
3651 spin_unlock_irq(&workqueue_lock);
3656 * thaw_workqueues - thaw workqueues
3658 * Thaw workqueues. Normal queueing is restored and all collected
3659 * frozen works are transferred to their respective pool worklists.
3662 * Grabs and releases workqueue_lock and pool->lock's.
3664 void thaw_workqueues(void)
3668 spin_lock_irq(&workqueue_lock);
3670 if (!workqueue_freezing)
3673 for_each_wq_cpu(cpu) {
3674 struct worker_pool *pool;
3675 struct workqueue_struct *wq;
3677 for_each_std_worker_pool(pool, cpu) {
3678 spin_lock(&pool->lock);
3680 WARN_ON_ONCE(!(pool->flags & POOL_FREEZING));
3681 pool->flags &= ~POOL_FREEZING;
3683 list_for_each_entry(wq, &workqueues, list) {
3684 struct pool_workqueue *pwq = get_pwq(cpu, wq);
3686 if (!pwq || pwq->pool != pool ||
3687 !(wq->flags & WQ_FREEZABLE))
3690 /* restore max_active and repopulate worklist */
3691 pwq_set_max_active(pwq, wq->saved_max_active);
3694 wake_up_worker(pool);
3696 spin_unlock(&pool->lock);
3700 workqueue_freezing = false;
3702 spin_unlock_irq(&workqueue_lock);
3704 #endif /* CONFIG_FREEZER */
3706 static int __init init_workqueues(void)
3710 /* make sure we have enough bits for OFFQ pool ID */
3711 BUILD_BUG_ON((1LU << (BITS_PER_LONG - WORK_OFFQ_POOL_SHIFT)) <
3712 WORK_CPU_END * NR_STD_WORKER_POOLS);
3714 WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
3716 pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
3718 cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
3719 hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
3721 /* initialize CPU pools */
3722 for_each_wq_cpu(cpu) {
3723 struct worker_pool *pool;
3725 for_each_std_worker_pool(pool, cpu) {
3726 spin_lock_init(&pool->lock);
3728 pool->flags |= POOL_DISASSOCIATED;
3729 INIT_LIST_HEAD(&pool->worklist);
3730 INIT_LIST_HEAD(&pool->idle_list);
3731 hash_init(pool->busy_hash);
3733 init_timer_deferrable(&pool->idle_timer);
3734 pool->idle_timer.function = idle_worker_timeout;
3735 pool->idle_timer.data = (unsigned long)pool;
3737 setup_timer(&pool->mayday_timer, pool_mayday_timeout,
3738 (unsigned long)pool);
3740 mutex_init(&pool->assoc_mutex);
3741 ida_init(&pool->worker_ida);
3744 BUG_ON(worker_pool_assign_id(pool));
3748 /* create the initial worker */
3749 for_each_online_wq_cpu(cpu) {
3750 struct worker_pool *pool;
3752 for_each_std_worker_pool(pool, cpu) {
3753 struct worker *worker;
3755 if (cpu != WORK_CPU_UNBOUND)
3756 pool->flags &= ~POOL_DISASSOCIATED;
3758 worker = create_worker(pool);
3760 spin_lock_irq(&pool->lock);
3761 start_worker(worker);
3762 spin_unlock_irq(&pool->lock);
3766 system_wq = alloc_workqueue("events", 0, 0);
3767 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
3768 system_long_wq = alloc_workqueue("events_long", 0, 0);
3769 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
3770 WQ_UNBOUND_MAX_ACTIVE);
3771 system_freezable_wq = alloc_workqueue("events_freezable",
3773 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
3774 !system_unbound_wq || !system_freezable_wq);
3777 early_initcall(init_workqueues);