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 struct list_head pwqs_node; /* I: node on wq->pwqs */
173 } __aligned(1 << WORK_STRUCT_FLAG_BITS);
176 * Structure used to wait for workqueue flush.
179 struct list_head list; /* F: list of flushers */
180 int flush_color; /* F: flush color waiting for */
181 struct completion done; /* flush completion */
185 * All cpumasks are assumed to be always set on UP and thus can't be
186 * used to determine whether there's something to be done.
189 typedef cpumask_var_t mayday_mask_t;
190 #define mayday_test_and_set_cpu(cpu, mask) \
191 cpumask_test_and_set_cpu((cpu), (mask))
192 #define mayday_clear_cpu(cpu, mask) cpumask_clear_cpu((cpu), (mask))
193 #define for_each_mayday_cpu(cpu, mask) for_each_cpu((cpu), (mask))
194 #define alloc_mayday_mask(maskp, gfp) zalloc_cpumask_var((maskp), (gfp))
195 #define free_mayday_mask(mask) free_cpumask_var((mask))
197 typedef unsigned long mayday_mask_t;
198 #define mayday_test_and_set_cpu(cpu, mask) test_and_set_bit(0, &(mask))
199 #define mayday_clear_cpu(cpu, mask) clear_bit(0, &(mask))
200 #define for_each_mayday_cpu(cpu, mask) if ((cpu) = 0, (mask))
201 #define alloc_mayday_mask(maskp, gfp) true
202 #define free_mayday_mask(mask) do { } while (0)
206 * The externally visible workqueue abstraction is an array of
207 * per-CPU workqueues:
209 struct workqueue_struct {
210 unsigned int flags; /* W: WQ_* flags */
212 struct pool_workqueue __percpu *pcpu;
213 struct pool_workqueue *single;
215 } pool_wq; /* I: pwq's */
216 struct list_head pwqs; /* I: all pwqs of this wq */
217 struct list_head list; /* W: list of all workqueues */
219 struct mutex flush_mutex; /* protects wq flushing */
220 int work_color; /* F: current work color */
221 int flush_color; /* F: current flush color */
222 atomic_t nr_pwqs_to_flush; /* flush in progress */
223 struct wq_flusher *first_flusher; /* F: first flusher */
224 struct list_head flusher_queue; /* F: flush waiters */
225 struct list_head flusher_overflow; /* F: flush overflow list */
227 mayday_mask_t mayday_mask; /* cpus requesting rescue */
228 struct worker *rescuer; /* I: rescue worker */
230 int nr_drainers; /* W: drain in progress */
231 int saved_max_active; /* W: saved pwq max_active */
232 #ifdef CONFIG_LOCKDEP
233 struct lockdep_map lockdep_map;
235 char name[]; /* I: workqueue name */
238 static struct kmem_cache *pwq_cache;
240 struct workqueue_struct *system_wq __read_mostly;
241 EXPORT_SYMBOL_GPL(system_wq);
242 struct workqueue_struct *system_highpri_wq __read_mostly;
243 EXPORT_SYMBOL_GPL(system_highpri_wq);
244 struct workqueue_struct *system_long_wq __read_mostly;
245 EXPORT_SYMBOL_GPL(system_long_wq);
246 struct workqueue_struct *system_unbound_wq __read_mostly;
247 EXPORT_SYMBOL_GPL(system_unbound_wq);
248 struct workqueue_struct *system_freezable_wq __read_mostly;
249 EXPORT_SYMBOL_GPL(system_freezable_wq);
251 #define CREATE_TRACE_POINTS
252 #include <trace/events/workqueue.h>
254 #define for_each_std_worker_pool(pool, cpu) \
255 for ((pool) = &std_worker_pools(cpu)[0]; \
256 (pool) < &std_worker_pools(cpu)[NR_STD_WORKER_POOLS]; (pool)++)
258 #define for_each_busy_worker(worker, i, pool) \
259 hash_for_each(pool->busy_hash, i, worker, hentry)
261 static inline int __next_wq_cpu(int cpu, const struct cpumask *mask,
264 if (cpu < nr_cpu_ids) {
266 cpu = cpumask_next(cpu, mask);
267 if (cpu < nr_cpu_ids)
271 return WORK_CPU_UNBOUND;
279 * An extra cpu number is defined using an invalid cpu number
280 * (WORK_CPU_UNBOUND) to host workqueues which are not bound to any
281 * specific CPU. The following iterators are similar to for_each_*_cpu()
282 * iterators but also considers the unbound CPU.
284 * for_each_wq_cpu() : possible CPUs + WORK_CPU_UNBOUND
285 * for_each_online_wq_cpu() : online CPUs + WORK_CPU_UNBOUND
287 #define for_each_wq_cpu(cpu) \
288 for ((cpu) = __next_wq_cpu(-1, cpu_possible_mask, 3); \
289 (cpu) < WORK_CPU_END; \
290 (cpu) = __next_wq_cpu((cpu), cpu_possible_mask, 3))
292 #define for_each_online_wq_cpu(cpu) \
293 for ((cpu) = __next_wq_cpu(-1, cpu_online_mask, 3); \
294 (cpu) < WORK_CPU_END; \
295 (cpu) = __next_wq_cpu((cpu), cpu_online_mask, 3))
298 * for_each_pool - iterate through all worker_pools in the system
299 * @pool: iteration cursor
300 * @id: integer used for iteration
302 #define for_each_pool(pool, id) \
303 idr_for_each_entry(&worker_pool_idr, pool, id)
306 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
307 * @pwq: iteration cursor
308 * @wq: the target workqueue
310 #define for_each_pwq(pwq, wq) \
311 list_for_each_entry((pwq), &(wq)->pwqs, pwqs_node)
313 #ifdef CONFIG_DEBUG_OBJECTS_WORK
315 static struct debug_obj_descr work_debug_descr;
317 static void *work_debug_hint(void *addr)
319 return ((struct work_struct *) addr)->func;
323 * fixup_init is called when:
324 * - an active object is initialized
326 static int work_fixup_init(void *addr, enum debug_obj_state state)
328 struct work_struct *work = addr;
331 case ODEBUG_STATE_ACTIVE:
332 cancel_work_sync(work);
333 debug_object_init(work, &work_debug_descr);
341 * fixup_activate is called when:
342 * - an active object is activated
343 * - an unknown object is activated (might be a statically initialized object)
345 static int work_fixup_activate(void *addr, enum debug_obj_state state)
347 struct work_struct *work = addr;
351 case ODEBUG_STATE_NOTAVAILABLE:
353 * This is not really a fixup. The work struct was
354 * statically initialized. We just make sure that it
355 * is tracked in the object tracker.
357 if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
358 debug_object_init(work, &work_debug_descr);
359 debug_object_activate(work, &work_debug_descr);
365 case ODEBUG_STATE_ACTIVE:
374 * fixup_free is called when:
375 * - an active object is freed
377 static int work_fixup_free(void *addr, enum debug_obj_state state)
379 struct work_struct *work = addr;
382 case ODEBUG_STATE_ACTIVE:
383 cancel_work_sync(work);
384 debug_object_free(work, &work_debug_descr);
391 static struct debug_obj_descr work_debug_descr = {
392 .name = "work_struct",
393 .debug_hint = work_debug_hint,
394 .fixup_init = work_fixup_init,
395 .fixup_activate = work_fixup_activate,
396 .fixup_free = work_fixup_free,
399 static inline void debug_work_activate(struct work_struct *work)
401 debug_object_activate(work, &work_debug_descr);
404 static inline void debug_work_deactivate(struct work_struct *work)
406 debug_object_deactivate(work, &work_debug_descr);
409 void __init_work(struct work_struct *work, int onstack)
412 debug_object_init_on_stack(work, &work_debug_descr);
414 debug_object_init(work, &work_debug_descr);
416 EXPORT_SYMBOL_GPL(__init_work);
418 void destroy_work_on_stack(struct work_struct *work)
420 debug_object_free(work, &work_debug_descr);
422 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
425 static inline void debug_work_activate(struct work_struct *work) { }
426 static inline void debug_work_deactivate(struct work_struct *work) { }
429 /* Serializes the accesses to the list of workqueues. */
430 static DEFINE_SPINLOCK(workqueue_lock);
431 static LIST_HEAD(workqueues);
432 static bool workqueue_freezing; /* W: have wqs started freezing? */
435 * The CPU and unbound standard worker pools. The unbound ones have
436 * POOL_DISASSOCIATED set, and their workers have WORKER_UNBOUND set.
438 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
439 cpu_std_worker_pools);
440 static struct worker_pool unbound_std_worker_pools[NR_STD_WORKER_POOLS];
442 /* idr of all pools */
443 static DEFINE_MUTEX(worker_pool_idr_mutex);
444 static DEFINE_IDR(worker_pool_idr);
446 static int worker_thread(void *__worker);
448 static struct worker_pool *std_worker_pools(int cpu)
450 if (cpu != WORK_CPU_UNBOUND)
451 return per_cpu(cpu_std_worker_pools, cpu);
453 return unbound_std_worker_pools;
456 static int std_worker_pool_pri(struct worker_pool *pool)
458 return pool - std_worker_pools(pool->cpu);
461 /* allocate ID and assign it to @pool */
462 static int worker_pool_assign_id(struct worker_pool *pool)
466 mutex_lock(&worker_pool_idr_mutex);
467 idr_pre_get(&worker_pool_idr, GFP_KERNEL);
468 ret = idr_get_new(&worker_pool_idr, pool, &pool->id);
469 mutex_unlock(&worker_pool_idr_mutex);
475 * Lookup worker_pool by id. The idr currently is built during boot and
476 * never modified. Don't worry about locking for now.
478 static struct worker_pool *worker_pool_by_id(int pool_id)
480 return idr_find(&worker_pool_idr, pool_id);
483 static struct worker_pool *get_std_worker_pool(int cpu, bool highpri)
485 struct worker_pool *pools = std_worker_pools(cpu);
487 return &pools[highpri];
490 static struct pool_workqueue *get_pwq(unsigned int cpu,
491 struct workqueue_struct *wq)
493 if (!(wq->flags & WQ_UNBOUND)) {
494 if (likely(cpu < nr_cpu_ids))
495 return per_cpu_ptr(wq->pool_wq.pcpu, cpu);
496 } else if (likely(cpu == WORK_CPU_UNBOUND))
497 return wq->pool_wq.single;
501 static unsigned int work_color_to_flags(int color)
503 return color << WORK_STRUCT_COLOR_SHIFT;
506 static int get_work_color(struct work_struct *work)
508 return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
509 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
512 static int work_next_color(int color)
514 return (color + 1) % WORK_NR_COLORS;
518 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
519 * contain the pointer to the queued pwq. Once execution starts, the flag
520 * is cleared and the high bits contain OFFQ flags and pool ID.
522 * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
523 * and clear_work_data() can be used to set the pwq, pool or clear
524 * work->data. These functions should only be called while the work is
525 * owned - ie. while the PENDING bit is set.
527 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
528 * corresponding to a work. Pool is available once the work has been
529 * queued anywhere after initialization until it is sync canceled. pwq is
530 * available only while the work item is queued.
532 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
533 * canceled. While being canceled, a work item may have its PENDING set
534 * but stay off timer and worklist for arbitrarily long and nobody should
535 * try to steal the PENDING bit.
537 static inline void set_work_data(struct work_struct *work, unsigned long data,
540 WARN_ON_ONCE(!work_pending(work));
541 atomic_long_set(&work->data, data | flags | work_static(work));
544 static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
545 unsigned long extra_flags)
547 set_work_data(work, (unsigned long)pwq,
548 WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
551 static void set_work_pool_and_keep_pending(struct work_struct *work,
554 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
555 WORK_STRUCT_PENDING);
558 static void set_work_pool_and_clear_pending(struct work_struct *work,
562 * The following wmb is paired with the implied mb in
563 * test_and_set_bit(PENDING) and ensures all updates to @work made
564 * here are visible to and precede any updates by the next PENDING
568 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
571 static void clear_work_data(struct work_struct *work)
573 smp_wmb(); /* see set_work_pool_and_clear_pending() */
574 set_work_data(work, WORK_STRUCT_NO_POOL, 0);
577 static struct pool_workqueue *get_work_pwq(struct work_struct *work)
579 unsigned long data = atomic_long_read(&work->data);
581 if (data & WORK_STRUCT_PWQ)
582 return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
588 * get_work_pool - return the worker_pool a given work was associated with
589 * @work: the work item of interest
591 * Return the worker_pool @work was last associated with. %NULL if none.
593 static struct worker_pool *get_work_pool(struct work_struct *work)
595 unsigned long data = atomic_long_read(&work->data);
596 struct worker_pool *pool;
599 if (data & WORK_STRUCT_PWQ)
600 return ((struct pool_workqueue *)
601 (data & WORK_STRUCT_WQ_DATA_MASK))->pool;
603 pool_id = data >> WORK_OFFQ_POOL_SHIFT;
604 if (pool_id == WORK_OFFQ_POOL_NONE)
607 pool = worker_pool_by_id(pool_id);
613 * get_work_pool_id - return the worker pool ID a given work is associated with
614 * @work: the work item of interest
616 * Return the worker_pool ID @work was last associated with.
617 * %WORK_OFFQ_POOL_NONE if none.
619 static int get_work_pool_id(struct work_struct *work)
621 unsigned long data = atomic_long_read(&work->data);
623 if (data & WORK_STRUCT_PWQ)
624 return ((struct pool_workqueue *)
625 (data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
627 return data >> WORK_OFFQ_POOL_SHIFT;
630 static void mark_work_canceling(struct work_struct *work)
632 unsigned long pool_id = get_work_pool_id(work);
634 pool_id <<= WORK_OFFQ_POOL_SHIFT;
635 set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
638 static bool work_is_canceling(struct work_struct *work)
640 unsigned long data = atomic_long_read(&work->data);
642 return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
646 * Policy functions. These define the policies on how the global worker
647 * pools are managed. Unless noted otherwise, these functions assume that
648 * they're being called with pool->lock held.
651 static bool __need_more_worker(struct worker_pool *pool)
653 return !atomic_read(&pool->nr_running);
657 * Need to wake up a worker? Called from anything but currently
660 * Note that, because unbound workers never contribute to nr_running, this
661 * function will always return %true for unbound pools as long as the
662 * worklist isn't empty.
664 static bool need_more_worker(struct worker_pool *pool)
666 return !list_empty(&pool->worklist) && __need_more_worker(pool);
669 /* Can I start working? Called from busy but !running workers. */
670 static bool may_start_working(struct worker_pool *pool)
672 return pool->nr_idle;
675 /* Do I need to keep working? Called from currently running workers. */
676 static bool keep_working(struct worker_pool *pool)
678 return !list_empty(&pool->worklist) &&
679 atomic_read(&pool->nr_running) <= 1;
682 /* Do we need a new worker? Called from manager. */
683 static bool need_to_create_worker(struct worker_pool *pool)
685 return need_more_worker(pool) && !may_start_working(pool);
688 /* Do I need to be the manager? */
689 static bool need_to_manage_workers(struct worker_pool *pool)
691 return need_to_create_worker(pool) ||
692 (pool->flags & POOL_MANAGE_WORKERS);
695 /* Do we have too many workers and should some go away? */
696 static bool too_many_workers(struct worker_pool *pool)
698 bool managing = pool->flags & POOL_MANAGING_WORKERS;
699 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
700 int nr_busy = pool->nr_workers - nr_idle;
703 * nr_idle and idle_list may disagree if idle rebinding is in
704 * progress. Never return %true if idle_list is empty.
706 if (list_empty(&pool->idle_list))
709 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
716 /* Return the first worker. Safe with preemption disabled */
717 static struct worker *first_worker(struct worker_pool *pool)
719 if (unlikely(list_empty(&pool->idle_list)))
722 return list_first_entry(&pool->idle_list, struct worker, entry);
726 * wake_up_worker - wake up an idle worker
727 * @pool: worker pool to wake worker from
729 * Wake up the first idle worker of @pool.
732 * spin_lock_irq(pool->lock).
734 static void wake_up_worker(struct worker_pool *pool)
736 struct worker *worker = first_worker(pool);
739 wake_up_process(worker->task);
743 * wq_worker_waking_up - a worker is waking up
744 * @task: task waking up
745 * @cpu: CPU @task is waking up to
747 * This function is called during try_to_wake_up() when a worker is
751 * spin_lock_irq(rq->lock)
753 void wq_worker_waking_up(struct task_struct *task, unsigned int cpu)
755 struct worker *worker = kthread_data(task);
757 if (!(worker->flags & WORKER_NOT_RUNNING)) {
758 WARN_ON_ONCE(worker->pool->cpu != cpu);
759 atomic_inc(&worker->pool->nr_running);
764 * wq_worker_sleeping - a worker is going to sleep
765 * @task: task going to sleep
766 * @cpu: CPU in question, must be the current CPU number
768 * This function is called during schedule() when a busy worker is
769 * going to sleep. Worker on the same cpu can be woken up by
770 * returning pointer to its task.
773 * spin_lock_irq(rq->lock)
776 * Worker task on @cpu to wake up, %NULL if none.
778 struct task_struct *wq_worker_sleeping(struct task_struct *task,
781 struct worker *worker = kthread_data(task), *to_wakeup = NULL;
782 struct worker_pool *pool;
785 * Rescuers, which may not have all the fields set up like normal
786 * workers, also reach here, let's not access anything before
787 * checking NOT_RUNNING.
789 if (worker->flags & WORKER_NOT_RUNNING)
794 /* this can only happen on the local cpu */
795 if (WARN_ON_ONCE(cpu != raw_smp_processor_id()))
799 * The counterpart of the following dec_and_test, implied mb,
800 * worklist not empty test sequence is in insert_work().
801 * Please read comment there.
803 * NOT_RUNNING is clear. This means that we're bound to and
804 * running on the local cpu w/ rq lock held and preemption
805 * disabled, which in turn means that none else could be
806 * manipulating idle_list, so dereferencing idle_list without pool
809 if (atomic_dec_and_test(&pool->nr_running) &&
810 !list_empty(&pool->worklist))
811 to_wakeup = first_worker(pool);
812 return to_wakeup ? to_wakeup->task : NULL;
816 * worker_set_flags - set worker flags and adjust nr_running accordingly
818 * @flags: flags to set
819 * @wakeup: wakeup an idle worker if necessary
821 * Set @flags in @worker->flags and adjust nr_running accordingly. If
822 * nr_running becomes zero and @wakeup is %true, an idle worker is
826 * spin_lock_irq(pool->lock)
828 static inline void worker_set_flags(struct worker *worker, unsigned int flags,
831 struct worker_pool *pool = worker->pool;
833 WARN_ON_ONCE(worker->task != current);
836 * If transitioning into NOT_RUNNING, adjust nr_running and
837 * wake up an idle worker as necessary if requested by
840 if ((flags & WORKER_NOT_RUNNING) &&
841 !(worker->flags & WORKER_NOT_RUNNING)) {
843 if (atomic_dec_and_test(&pool->nr_running) &&
844 !list_empty(&pool->worklist))
845 wake_up_worker(pool);
847 atomic_dec(&pool->nr_running);
850 worker->flags |= flags;
854 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
856 * @flags: flags to clear
858 * Clear @flags in @worker->flags and adjust nr_running accordingly.
861 * spin_lock_irq(pool->lock)
863 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
865 struct worker_pool *pool = worker->pool;
866 unsigned int oflags = worker->flags;
868 WARN_ON_ONCE(worker->task != current);
870 worker->flags &= ~flags;
873 * If transitioning out of NOT_RUNNING, increment nr_running. Note
874 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
875 * of multiple flags, not a single flag.
877 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
878 if (!(worker->flags & WORKER_NOT_RUNNING))
879 atomic_inc(&pool->nr_running);
883 * find_worker_executing_work - find worker which is executing a work
884 * @pool: pool of interest
885 * @work: work to find worker for
887 * Find a worker which is executing @work on @pool by searching
888 * @pool->busy_hash which is keyed by the address of @work. For a worker
889 * to match, its current execution should match the address of @work and
890 * its work function. This is to avoid unwanted dependency between
891 * unrelated work executions through a work item being recycled while still
894 * This is a bit tricky. A work item may be freed once its execution
895 * starts and nothing prevents the freed area from being recycled for
896 * another work item. If the same work item address ends up being reused
897 * before the original execution finishes, workqueue will identify the
898 * recycled work item as currently executing and make it wait until the
899 * current execution finishes, introducing an unwanted dependency.
901 * This function checks the work item address, work function and workqueue
902 * to avoid false positives. Note that this isn't complete as one may
903 * construct a work function which can introduce dependency onto itself
904 * through a recycled work item. Well, if somebody wants to shoot oneself
905 * in the foot that badly, there's only so much we can do, and if such
906 * deadlock actually occurs, it should be easy to locate the culprit work
910 * spin_lock_irq(pool->lock).
913 * Pointer to worker which is executing @work if found, NULL
916 static struct worker *find_worker_executing_work(struct worker_pool *pool,
917 struct work_struct *work)
919 struct worker *worker;
921 hash_for_each_possible(pool->busy_hash, worker, hentry,
923 if (worker->current_work == work &&
924 worker->current_func == work->func)
931 * move_linked_works - move linked works to a list
932 * @work: start of series of works to be scheduled
933 * @head: target list to append @work to
934 * @nextp: out paramter for nested worklist walking
936 * Schedule linked works starting from @work to @head. Work series to
937 * be scheduled starts at @work and includes any consecutive work with
938 * WORK_STRUCT_LINKED set in its predecessor.
940 * If @nextp is not NULL, it's updated to point to the next work of
941 * the last scheduled work. This allows move_linked_works() to be
942 * nested inside outer list_for_each_entry_safe().
945 * spin_lock_irq(pool->lock).
947 static void move_linked_works(struct work_struct *work, struct list_head *head,
948 struct work_struct **nextp)
950 struct work_struct *n;
953 * Linked worklist will always end before the end of the list,
954 * use NULL for list head.
956 list_for_each_entry_safe_from(work, n, NULL, entry) {
957 list_move_tail(&work->entry, head);
958 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
963 * If we're already inside safe list traversal and have moved
964 * multiple works to the scheduled queue, the next position
965 * needs to be updated.
971 static void pwq_activate_delayed_work(struct work_struct *work)
973 struct pool_workqueue *pwq = get_work_pwq(work);
975 trace_workqueue_activate_work(work);
976 move_linked_works(work, &pwq->pool->worklist, NULL);
977 __clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
981 static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
983 struct work_struct *work = list_first_entry(&pwq->delayed_works,
984 struct work_struct, entry);
986 pwq_activate_delayed_work(work);
990 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
991 * @pwq: pwq of interest
992 * @color: color of work which left the queue
994 * A work either has completed or is removed from pending queue,
995 * decrement nr_in_flight of its pwq and handle workqueue flushing.
998 * spin_lock_irq(pool->lock).
1000 static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
1002 /* ignore uncolored works */
1003 if (color == WORK_NO_COLOR)
1006 pwq->nr_in_flight[color]--;
1009 if (!list_empty(&pwq->delayed_works)) {
1010 /* one down, submit a delayed one */
1011 if (pwq->nr_active < pwq->max_active)
1012 pwq_activate_first_delayed(pwq);
1015 /* is flush in progress and are we at the flushing tip? */
1016 if (likely(pwq->flush_color != color))
1019 /* are there still in-flight works? */
1020 if (pwq->nr_in_flight[color])
1023 /* this pwq is done, clear flush_color */
1024 pwq->flush_color = -1;
1027 * If this was the last pwq, wake up the first flusher. It
1028 * will handle the rest.
1030 if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1031 complete(&pwq->wq->first_flusher->done);
1035 * try_to_grab_pending - steal work item from worklist and disable irq
1036 * @work: work item to steal
1037 * @is_dwork: @work is a delayed_work
1038 * @flags: place to store irq state
1040 * Try to grab PENDING bit of @work. This function can handle @work in any
1041 * stable state - idle, on timer or on worklist. Return values are
1043 * 1 if @work was pending and we successfully stole PENDING
1044 * 0 if @work was idle and we claimed PENDING
1045 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1046 * -ENOENT if someone else is canceling @work, this state may persist
1047 * for arbitrarily long
1049 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1050 * interrupted while holding PENDING and @work off queue, irq must be
1051 * disabled on entry. This, combined with delayed_work->timer being
1052 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1054 * On successful return, >= 0, irq is disabled and the caller is
1055 * responsible for releasing it using local_irq_restore(*@flags).
1057 * This function is safe to call from any context including IRQ handler.
1059 static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1060 unsigned long *flags)
1062 struct worker_pool *pool;
1063 struct pool_workqueue *pwq;
1065 local_irq_save(*flags);
1067 /* try to steal the timer if it exists */
1069 struct delayed_work *dwork = to_delayed_work(work);
1072 * dwork->timer is irqsafe. If del_timer() fails, it's
1073 * guaranteed that the timer is not queued anywhere and not
1074 * running on the local CPU.
1076 if (likely(del_timer(&dwork->timer)))
1080 /* try to claim PENDING the normal way */
1081 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1085 * The queueing is in progress, or it is already queued. Try to
1086 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1088 pool = get_work_pool(work);
1092 spin_lock(&pool->lock);
1094 * work->data is guaranteed to point to pwq only while the work
1095 * item is queued on pwq->wq, and both updating work->data to point
1096 * to pwq on queueing and to pool on dequeueing are done under
1097 * pwq->pool->lock. This in turn guarantees that, if work->data
1098 * points to pwq which is associated with a locked pool, the work
1099 * item is currently queued on that pool.
1101 pwq = get_work_pwq(work);
1102 if (pwq && pwq->pool == pool) {
1103 debug_work_deactivate(work);
1106 * A delayed work item cannot be grabbed directly because
1107 * it might have linked NO_COLOR work items which, if left
1108 * on the delayed_list, will confuse pwq->nr_active
1109 * management later on and cause stall. Make sure the work
1110 * item is activated before grabbing.
1112 if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1113 pwq_activate_delayed_work(work);
1115 list_del_init(&work->entry);
1116 pwq_dec_nr_in_flight(get_work_pwq(work), get_work_color(work));
1118 /* work->data points to pwq iff queued, point to pool */
1119 set_work_pool_and_keep_pending(work, pool->id);
1121 spin_unlock(&pool->lock);
1124 spin_unlock(&pool->lock);
1126 local_irq_restore(*flags);
1127 if (work_is_canceling(work))
1134 * insert_work - insert a work into a pool
1135 * @pwq: pwq @work belongs to
1136 * @work: work to insert
1137 * @head: insertion point
1138 * @extra_flags: extra WORK_STRUCT_* flags to set
1140 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
1141 * work_struct flags.
1144 * spin_lock_irq(pool->lock).
1146 static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1147 struct list_head *head, unsigned int extra_flags)
1149 struct worker_pool *pool = pwq->pool;
1151 /* we own @work, set data and link */
1152 set_work_pwq(work, pwq, extra_flags);
1153 list_add_tail(&work->entry, head);
1156 * Ensure either worker_sched_deactivated() sees the above
1157 * list_add_tail() or we see zero nr_running to avoid workers
1158 * lying around lazily while there are works to be processed.
1162 if (__need_more_worker(pool))
1163 wake_up_worker(pool);
1167 * Test whether @work is being queued from another work executing on the
1170 static bool is_chained_work(struct workqueue_struct *wq)
1172 struct worker *worker;
1174 worker = current_wq_worker();
1176 * Return %true iff I'm a worker execuing a work item on @wq. If
1177 * I'm @worker, it's safe to dereference it without locking.
1179 return worker && worker->current_pwq->wq == wq;
1182 static void __queue_work(unsigned int cpu, struct workqueue_struct *wq,
1183 struct work_struct *work)
1185 struct pool_workqueue *pwq;
1186 struct list_head *worklist;
1187 unsigned int work_flags;
1188 unsigned int req_cpu = cpu;
1191 * While a work item is PENDING && off queue, a task trying to
1192 * steal the PENDING will busy-loop waiting for it to either get
1193 * queued or lose PENDING. Grabbing PENDING and queueing should
1194 * happen with IRQ disabled.
1196 WARN_ON_ONCE(!irqs_disabled());
1198 debug_work_activate(work);
1200 /* if dying, only works from the same workqueue are allowed */
1201 if (unlikely(wq->flags & WQ_DRAINING) &&
1202 WARN_ON_ONCE(!is_chained_work(wq)))
1205 /* determine the pwq to use */
1206 if (!(wq->flags & WQ_UNBOUND)) {
1207 struct worker_pool *last_pool;
1209 if (cpu == WORK_CPU_UNBOUND)
1210 cpu = raw_smp_processor_id();
1213 * It's multi cpu. If @work was previously on a different
1214 * cpu, it might still be running there, in which case the
1215 * work needs to be queued on that cpu to guarantee
1218 pwq = get_pwq(cpu, wq);
1219 last_pool = get_work_pool(work);
1221 if (last_pool && last_pool != pwq->pool) {
1222 struct worker *worker;
1224 spin_lock(&last_pool->lock);
1226 worker = find_worker_executing_work(last_pool, work);
1228 if (worker && worker->current_pwq->wq == wq) {
1229 pwq = get_pwq(last_pool->cpu, wq);
1231 /* meh... not running there, queue here */
1232 spin_unlock(&last_pool->lock);
1233 spin_lock(&pwq->pool->lock);
1236 spin_lock(&pwq->pool->lock);
1239 pwq = get_pwq(WORK_CPU_UNBOUND, wq);
1240 spin_lock(&pwq->pool->lock);
1243 /* pwq determined, queue */
1244 trace_workqueue_queue_work(req_cpu, pwq, work);
1246 if (WARN_ON(!list_empty(&work->entry))) {
1247 spin_unlock(&pwq->pool->lock);
1251 pwq->nr_in_flight[pwq->work_color]++;
1252 work_flags = work_color_to_flags(pwq->work_color);
1254 if (likely(pwq->nr_active < pwq->max_active)) {
1255 trace_workqueue_activate_work(work);
1257 worklist = &pwq->pool->worklist;
1259 work_flags |= WORK_STRUCT_DELAYED;
1260 worklist = &pwq->delayed_works;
1263 insert_work(pwq, work, worklist, work_flags);
1265 spin_unlock(&pwq->pool->lock);
1269 * queue_work_on - queue work on specific cpu
1270 * @cpu: CPU number to execute work on
1271 * @wq: workqueue to use
1272 * @work: work to queue
1274 * Returns %false if @work was already on a queue, %true otherwise.
1276 * We queue the work to a specific CPU, the caller must ensure it
1279 bool queue_work_on(int cpu, struct workqueue_struct *wq,
1280 struct work_struct *work)
1283 unsigned long flags;
1285 local_irq_save(flags);
1287 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1288 __queue_work(cpu, wq, work);
1292 local_irq_restore(flags);
1295 EXPORT_SYMBOL_GPL(queue_work_on);
1298 * queue_work - queue work on a workqueue
1299 * @wq: workqueue to use
1300 * @work: work to queue
1302 * Returns %false if @work was already on a queue, %true otherwise.
1304 * We queue the work to the CPU on which it was submitted, but if the CPU dies
1305 * it can be processed by another CPU.
1307 bool queue_work(struct workqueue_struct *wq, struct work_struct *work)
1309 return queue_work_on(WORK_CPU_UNBOUND, wq, work);
1311 EXPORT_SYMBOL_GPL(queue_work);
1313 void delayed_work_timer_fn(unsigned long __data)
1315 struct delayed_work *dwork = (struct delayed_work *)__data;
1317 /* should have been called from irqsafe timer with irq already off */
1318 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
1320 EXPORT_SYMBOL(delayed_work_timer_fn);
1322 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
1323 struct delayed_work *dwork, unsigned long delay)
1325 struct timer_list *timer = &dwork->timer;
1326 struct work_struct *work = &dwork->work;
1328 WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
1329 timer->data != (unsigned long)dwork);
1330 WARN_ON_ONCE(timer_pending(timer));
1331 WARN_ON_ONCE(!list_empty(&work->entry));
1334 * If @delay is 0, queue @dwork->work immediately. This is for
1335 * both optimization and correctness. The earliest @timer can
1336 * expire is on the closest next tick and delayed_work users depend
1337 * on that there's no such delay when @delay is 0.
1340 __queue_work(cpu, wq, &dwork->work);
1344 timer_stats_timer_set_start_info(&dwork->timer);
1348 timer->expires = jiffies + delay;
1350 if (unlikely(cpu != WORK_CPU_UNBOUND))
1351 add_timer_on(timer, cpu);
1357 * queue_delayed_work_on - queue work on specific CPU after delay
1358 * @cpu: CPU number to execute work on
1359 * @wq: workqueue to use
1360 * @dwork: work to queue
1361 * @delay: number of jiffies to wait before queueing
1363 * Returns %false if @work was already on a queue, %true otherwise. If
1364 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1367 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1368 struct delayed_work *dwork, unsigned long delay)
1370 struct work_struct *work = &dwork->work;
1372 unsigned long flags;
1374 /* read the comment in __queue_work() */
1375 local_irq_save(flags);
1377 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1378 __queue_delayed_work(cpu, wq, dwork, delay);
1382 local_irq_restore(flags);
1385 EXPORT_SYMBOL_GPL(queue_delayed_work_on);
1388 * queue_delayed_work - queue work on a workqueue after delay
1389 * @wq: workqueue to use
1390 * @dwork: delayable work to queue
1391 * @delay: number of jiffies to wait before queueing
1393 * Equivalent to queue_delayed_work_on() but tries to use the local CPU.
1395 bool queue_delayed_work(struct workqueue_struct *wq,
1396 struct delayed_work *dwork, unsigned long delay)
1398 return queue_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
1400 EXPORT_SYMBOL_GPL(queue_delayed_work);
1403 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1404 * @cpu: CPU number to execute work on
1405 * @wq: workqueue to use
1406 * @dwork: work to queue
1407 * @delay: number of jiffies to wait before queueing
1409 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1410 * modify @dwork's timer so that it expires after @delay. If @delay is
1411 * zero, @work is guaranteed to be scheduled immediately regardless of its
1414 * Returns %false if @dwork was idle and queued, %true if @dwork was
1415 * pending and its timer was modified.
1417 * This function is safe to call from any context including IRQ handler.
1418 * See try_to_grab_pending() for details.
1420 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
1421 struct delayed_work *dwork, unsigned long delay)
1423 unsigned long flags;
1427 ret = try_to_grab_pending(&dwork->work, true, &flags);
1428 } while (unlikely(ret == -EAGAIN));
1430 if (likely(ret >= 0)) {
1431 __queue_delayed_work(cpu, wq, dwork, delay);
1432 local_irq_restore(flags);
1435 /* -ENOENT from try_to_grab_pending() becomes %true */
1438 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
1441 * mod_delayed_work - modify delay of or queue a delayed work
1442 * @wq: workqueue to use
1443 * @dwork: work to queue
1444 * @delay: number of jiffies to wait before queueing
1446 * mod_delayed_work_on() on local CPU.
1448 bool mod_delayed_work(struct workqueue_struct *wq, struct delayed_work *dwork,
1449 unsigned long delay)
1451 return mod_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
1453 EXPORT_SYMBOL_GPL(mod_delayed_work);
1456 * worker_enter_idle - enter idle state
1457 * @worker: worker which is entering idle state
1459 * @worker is entering idle state. Update stats and idle timer if
1463 * spin_lock_irq(pool->lock).
1465 static void worker_enter_idle(struct worker *worker)
1467 struct worker_pool *pool = worker->pool;
1469 if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
1470 WARN_ON_ONCE(!list_empty(&worker->entry) &&
1471 (worker->hentry.next || worker->hentry.pprev)))
1474 /* can't use worker_set_flags(), also called from start_worker() */
1475 worker->flags |= WORKER_IDLE;
1477 worker->last_active = jiffies;
1479 /* idle_list is LIFO */
1480 list_add(&worker->entry, &pool->idle_list);
1482 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1483 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1486 * Sanity check nr_running. Because wq_unbind_fn() releases
1487 * pool->lock between setting %WORKER_UNBOUND and zapping
1488 * nr_running, the warning may trigger spuriously. Check iff
1489 * unbind is not in progress.
1491 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1492 pool->nr_workers == pool->nr_idle &&
1493 atomic_read(&pool->nr_running));
1497 * worker_leave_idle - leave idle state
1498 * @worker: worker which is leaving idle state
1500 * @worker is leaving idle state. Update stats.
1503 * spin_lock_irq(pool->lock).
1505 static void worker_leave_idle(struct worker *worker)
1507 struct worker_pool *pool = worker->pool;
1509 if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
1511 worker_clr_flags(worker, WORKER_IDLE);
1513 list_del_init(&worker->entry);
1517 * worker_maybe_bind_and_lock - try to bind %current to worker_pool and lock it
1518 * @pool: target worker_pool
1520 * Bind %current to the cpu of @pool if it is associated and lock @pool.
1522 * Works which are scheduled while the cpu is online must at least be
1523 * scheduled to a worker which is bound to the cpu so that if they are
1524 * flushed from cpu callbacks while cpu is going down, they are
1525 * guaranteed to execute on the cpu.
1527 * This function is to be used by unbound workers and rescuers to bind
1528 * themselves to the target cpu and may race with cpu going down or
1529 * coming online. kthread_bind() can't be used because it may put the
1530 * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1531 * verbatim as it's best effort and blocking and pool may be
1532 * [dis]associated in the meantime.
1534 * This function tries set_cpus_allowed() and locks pool and verifies the
1535 * binding against %POOL_DISASSOCIATED which is set during
1536 * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
1537 * enters idle state or fetches works without dropping lock, it can
1538 * guarantee the scheduling requirement described in the first paragraph.
1541 * Might sleep. Called without any lock but returns with pool->lock
1545 * %true if the associated pool is online (@worker is successfully
1546 * bound), %false if offline.
1548 static bool worker_maybe_bind_and_lock(struct worker_pool *pool)
1549 __acquires(&pool->lock)
1553 * The following call may fail, succeed or succeed
1554 * without actually migrating the task to the cpu if
1555 * it races with cpu hotunplug operation. Verify
1556 * against POOL_DISASSOCIATED.
1558 if (!(pool->flags & POOL_DISASSOCIATED))
1559 set_cpus_allowed_ptr(current, get_cpu_mask(pool->cpu));
1561 spin_lock_irq(&pool->lock);
1562 if (pool->flags & POOL_DISASSOCIATED)
1564 if (task_cpu(current) == pool->cpu &&
1565 cpumask_equal(¤t->cpus_allowed,
1566 get_cpu_mask(pool->cpu)))
1568 spin_unlock_irq(&pool->lock);
1571 * We've raced with CPU hot[un]plug. Give it a breather
1572 * and retry migration. cond_resched() is required here;
1573 * otherwise, we might deadlock against cpu_stop trying to
1574 * bring down the CPU on non-preemptive kernel.
1582 * Rebind an idle @worker to its CPU. worker_thread() will test
1583 * list_empty(@worker->entry) before leaving idle and call this function.
1585 static void idle_worker_rebind(struct worker *worker)
1587 /* CPU may go down again inbetween, clear UNBOUND only on success */
1588 if (worker_maybe_bind_and_lock(worker->pool))
1589 worker_clr_flags(worker, WORKER_UNBOUND);
1591 /* rebind complete, become available again */
1592 list_add(&worker->entry, &worker->pool->idle_list);
1593 spin_unlock_irq(&worker->pool->lock);
1597 * Function for @worker->rebind.work used to rebind unbound busy workers to
1598 * the associated cpu which is coming back online. This is scheduled by
1599 * cpu up but can race with other cpu hotplug operations and may be
1600 * executed twice without intervening cpu down.
1602 static void busy_worker_rebind_fn(struct work_struct *work)
1604 struct worker *worker = container_of(work, struct worker, rebind_work);
1606 if (worker_maybe_bind_and_lock(worker->pool))
1607 worker_clr_flags(worker, WORKER_UNBOUND);
1609 spin_unlock_irq(&worker->pool->lock);
1613 * rebind_workers - rebind all workers of a pool to the associated CPU
1614 * @pool: pool of interest
1616 * @pool->cpu is coming online. Rebind all workers to the CPU. Rebinding
1617 * is different for idle and busy ones.
1619 * Idle ones will be removed from the idle_list and woken up. They will
1620 * add themselves back after completing rebind. This ensures that the
1621 * idle_list doesn't contain any unbound workers when re-bound busy workers
1622 * try to perform local wake-ups for concurrency management.
1624 * Busy workers can rebind after they finish their current work items.
1625 * Queueing the rebind work item at the head of the scheduled list is
1626 * enough. Note that nr_running will be properly bumped as busy workers
1629 * On return, all non-manager workers are scheduled for rebind - see
1630 * manage_workers() for the manager special case. Any idle worker
1631 * including the manager will not appear on @idle_list until rebind is
1632 * complete, making local wake-ups safe.
1634 static void rebind_workers(struct worker_pool *pool)
1636 struct worker *worker, *n;
1639 lockdep_assert_held(&pool->assoc_mutex);
1640 lockdep_assert_held(&pool->lock);
1642 /* dequeue and kick idle ones */
1643 list_for_each_entry_safe(worker, n, &pool->idle_list, entry) {
1645 * idle workers should be off @pool->idle_list until rebind
1646 * is complete to avoid receiving premature local wake-ups.
1648 list_del_init(&worker->entry);
1651 * worker_thread() will see the above dequeuing and call
1652 * idle_worker_rebind().
1654 wake_up_process(worker->task);
1657 /* rebind busy workers */
1658 for_each_busy_worker(worker, i, pool) {
1659 struct work_struct *rebind_work = &worker->rebind_work;
1660 struct workqueue_struct *wq;
1662 if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
1663 work_data_bits(rebind_work)))
1666 debug_work_activate(rebind_work);
1669 * wq doesn't really matter but let's keep @worker->pool
1670 * and @pwq->pool consistent for sanity.
1672 if (std_worker_pool_pri(worker->pool))
1673 wq = system_highpri_wq;
1677 insert_work(get_pwq(pool->cpu, wq), rebind_work,
1678 worker->scheduled.next,
1679 work_color_to_flags(WORK_NO_COLOR));
1683 static struct worker *alloc_worker(void)
1685 struct worker *worker;
1687 worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1689 INIT_LIST_HEAD(&worker->entry);
1690 INIT_LIST_HEAD(&worker->scheduled);
1691 INIT_WORK(&worker->rebind_work, busy_worker_rebind_fn);
1692 /* on creation a worker is in !idle && prep state */
1693 worker->flags = WORKER_PREP;
1699 * create_worker - create a new workqueue worker
1700 * @pool: pool the new worker will belong to
1702 * Create a new worker which is bound to @pool. The returned worker
1703 * can be started by calling start_worker() or destroyed using
1707 * Might sleep. Does GFP_KERNEL allocations.
1710 * Pointer to the newly created worker.
1712 static struct worker *create_worker(struct worker_pool *pool)
1714 const char *pri = std_worker_pool_pri(pool) ? "H" : "";
1715 struct worker *worker = NULL;
1718 spin_lock_irq(&pool->lock);
1719 while (ida_get_new(&pool->worker_ida, &id)) {
1720 spin_unlock_irq(&pool->lock);
1721 if (!ida_pre_get(&pool->worker_ida, GFP_KERNEL))
1723 spin_lock_irq(&pool->lock);
1725 spin_unlock_irq(&pool->lock);
1727 worker = alloc_worker();
1731 worker->pool = pool;
1734 if (pool->cpu != WORK_CPU_UNBOUND)
1735 worker->task = kthread_create_on_node(worker_thread,
1736 worker, cpu_to_node(pool->cpu),
1737 "kworker/%u:%d%s", pool->cpu, id, pri);
1739 worker->task = kthread_create(worker_thread, worker,
1740 "kworker/u:%d%s", id, pri);
1741 if (IS_ERR(worker->task))
1744 if (std_worker_pool_pri(pool))
1745 set_user_nice(worker->task, HIGHPRI_NICE_LEVEL);
1748 * Determine CPU binding of the new worker depending on
1749 * %POOL_DISASSOCIATED. The caller is responsible for ensuring the
1750 * flag remains stable across this function. See the comments
1751 * above the flag definition for details.
1753 * As an unbound worker may later become a regular one if CPU comes
1754 * online, make sure every worker has %PF_THREAD_BOUND set.
1756 if (!(pool->flags & POOL_DISASSOCIATED)) {
1757 kthread_bind(worker->task, pool->cpu);
1759 worker->task->flags |= PF_THREAD_BOUND;
1760 worker->flags |= WORKER_UNBOUND;
1766 spin_lock_irq(&pool->lock);
1767 ida_remove(&pool->worker_ida, id);
1768 spin_unlock_irq(&pool->lock);
1775 * start_worker - start a newly created worker
1776 * @worker: worker to start
1778 * Make the pool aware of @worker and start it.
1781 * spin_lock_irq(pool->lock).
1783 static void start_worker(struct worker *worker)
1785 worker->flags |= WORKER_STARTED;
1786 worker->pool->nr_workers++;
1787 worker_enter_idle(worker);
1788 wake_up_process(worker->task);
1792 * destroy_worker - destroy a workqueue worker
1793 * @worker: worker to be destroyed
1795 * Destroy @worker and adjust @pool stats accordingly.
1798 * spin_lock_irq(pool->lock) which is released and regrabbed.
1800 static void destroy_worker(struct worker *worker)
1802 struct worker_pool *pool = worker->pool;
1803 int id = worker->id;
1805 /* sanity check frenzy */
1806 if (WARN_ON(worker->current_work) ||
1807 WARN_ON(!list_empty(&worker->scheduled)))
1810 if (worker->flags & WORKER_STARTED)
1812 if (worker->flags & WORKER_IDLE)
1815 list_del_init(&worker->entry);
1816 worker->flags |= WORKER_DIE;
1818 spin_unlock_irq(&pool->lock);
1820 kthread_stop(worker->task);
1823 spin_lock_irq(&pool->lock);
1824 ida_remove(&pool->worker_ida, id);
1827 static void idle_worker_timeout(unsigned long __pool)
1829 struct worker_pool *pool = (void *)__pool;
1831 spin_lock_irq(&pool->lock);
1833 if (too_many_workers(pool)) {
1834 struct worker *worker;
1835 unsigned long expires;
1837 /* idle_list is kept in LIFO order, check the last one */
1838 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1839 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1841 if (time_before(jiffies, expires))
1842 mod_timer(&pool->idle_timer, expires);
1844 /* it's been idle for too long, wake up manager */
1845 pool->flags |= POOL_MANAGE_WORKERS;
1846 wake_up_worker(pool);
1850 spin_unlock_irq(&pool->lock);
1853 static bool send_mayday(struct work_struct *work)
1855 struct pool_workqueue *pwq = get_work_pwq(work);
1856 struct workqueue_struct *wq = pwq->wq;
1859 if (!(wq->flags & WQ_RESCUER))
1862 /* mayday mayday mayday */
1863 cpu = pwq->pool->cpu;
1864 /* WORK_CPU_UNBOUND can't be set in cpumask, use cpu 0 instead */
1865 if (cpu == WORK_CPU_UNBOUND)
1867 if (!mayday_test_and_set_cpu(cpu, wq->mayday_mask))
1868 wake_up_process(wq->rescuer->task);
1872 static void pool_mayday_timeout(unsigned long __pool)
1874 struct worker_pool *pool = (void *)__pool;
1875 struct work_struct *work;
1877 spin_lock_irq(&pool->lock);
1879 if (need_to_create_worker(pool)) {
1881 * We've been trying to create a new worker but
1882 * haven't been successful. We might be hitting an
1883 * allocation deadlock. Send distress signals to
1886 list_for_each_entry(work, &pool->worklist, entry)
1890 spin_unlock_irq(&pool->lock);
1892 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1896 * maybe_create_worker - create a new worker if necessary
1897 * @pool: pool to create a new worker for
1899 * Create a new worker for @pool if necessary. @pool is guaranteed to
1900 * have at least one idle worker on return from this function. If
1901 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1902 * sent to all rescuers with works scheduled on @pool to resolve
1903 * possible allocation deadlock.
1905 * On return, need_to_create_worker() is guaranteed to be false and
1906 * may_start_working() true.
1909 * spin_lock_irq(pool->lock) which may be released and regrabbed
1910 * multiple times. Does GFP_KERNEL allocations. Called only from
1914 * false if no action was taken and pool->lock stayed locked, true
1917 static bool maybe_create_worker(struct worker_pool *pool)
1918 __releases(&pool->lock)
1919 __acquires(&pool->lock)
1921 if (!need_to_create_worker(pool))
1924 spin_unlock_irq(&pool->lock);
1926 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1927 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1930 struct worker *worker;
1932 worker = create_worker(pool);
1934 del_timer_sync(&pool->mayday_timer);
1935 spin_lock_irq(&pool->lock);
1936 start_worker(worker);
1937 if (WARN_ON_ONCE(need_to_create_worker(pool)))
1942 if (!need_to_create_worker(pool))
1945 __set_current_state(TASK_INTERRUPTIBLE);
1946 schedule_timeout(CREATE_COOLDOWN);
1948 if (!need_to_create_worker(pool))
1952 del_timer_sync(&pool->mayday_timer);
1953 spin_lock_irq(&pool->lock);
1954 if (need_to_create_worker(pool))
1960 * maybe_destroy_worker - destroy workers which have been idle for a while
1961 * @pool: pool to destroy workers for
1963 * Destroy @pool workers which have been idle for longer than
1964 * IDLE_WORKER_TIMEOUT.
1967 * spin_lock_irq(pool->lock) which may be released and regrabbed
1968 * multiple times. Called only from manager.
1971 * false if no action was taken and pool->lock stayed locked, true
1974 static bool maybe_destroy_workers(struct worker_pool *pool)
1978 while (too_many_workers(pool)) {
1979 struct worker *worker;
1980 unsigned long expires;
1982 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1983 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1985 if (time_before(jiffies, expires)) {
1986 mod_timer(&pool->idle_timer, expires);
1990 destroy_worker(worker);
1998 * manage_workers - manage worker pool
2001 * Assume the manager role and manage the worker pool @worker belongs
2002 * to. At any given time, there can be only zero or one manager per
2003 * pool. The exclusion is handled automatically by this function.
2005 * The caller can safely start processing works on false return. On
2006 * true return, it's guaranteed that need_to_create_worker() is false
2007 * and may_start_working() is true.
2010 * spin_lock_irq(pool->lock) which may be released and regrabbed
2011 * multiple times. Does GFP_KERNEL allocations.
2014 * spin_lock_irq(pool->lock) which may be released and regrabbed
2015 * multiple times. Does GFP_KERNEL allocations.
2017 static bool manage_workers(struct worker *worker)
2019 struct worker_pool *pool = worker->pool;
2022 if (pool->flags & POOL_MANAGING_WORKERS)
2025 pool->flags |= POOL_MANAGING_WORKERS;
2028 * To simplify both worker management and CPU hotplug, hold off
2029 * management while hotplug is in progress. CPU hotplug path can't
2030 * grab %POOL_MANAGING_WORKERS to achieve this because that can
2031 * lead to idle worker depletion (all become busy thinking someone
2032 * else is managing) which in turn can result in deadlock under
2033 * extreme circumstances. Use @pool->assoc_mutex to synchronize
2034 * manager against CPU hotplug.
2036 * assoc_mutex would always be free unless CPU hotplug is in
2037 * progress. trylock first without dropping @pool->lock.
2039 if (unlikely(!mutex_trylock(&pool->assoc_mutex))) {
2040 spin_unlock_irq(&pool->lock);
2041 mutex_lock(&pool->assoc_mutex);
2043 * CPU hotplug could have happened while we were waiting
2044 * for assoc_mutex. Hotplug itself can't handle us
2045 * because manager isn't either on idle or busy list, and
2046 * @pool's state and ours could have deviated.
2048 * As hotplug is now excluded via assoc_mutex, we can
2049 * simply try to bind. It will succeed or fail depending
2050 * on @pool's current state. Try it and adjust
2051 * %WORKER_UNBOUND accordingly.
2053 if (worker_maybe_bind_and_lock(pool))
2054 worker->flags &= ~WORKER_UNBOUND;
2056 worker->flags |= WORKER_UNBOUND;
2061 pool->flags &= ~POOL_MANAGE_WORKERS;
2064 * Destroy and then create so that may_start_working() is true
2067 ret |= maybe_destroy_workers(pool);
2068 ret |= maybe_create_worker(pool);
2070 pool->flags &= ~POOL_MANAGING_WORKERS;
2071 mutex_unlock(&pool->assoc_mutex);
2076 * process_one_work - process single work
2078 * @work: work to process
2080 * Process @work. This function contains all the logics necessary to
2081 * process a single work including synchronization against and
2082 * interaction with other workers on the same cpu, queueing and
2083 * flushing. As long as context requirement is met, any worker can
2084 * call this function to process a work.
2087 * spin_lock_irq(pool->lock) which is released and regrabbed.
2089 static void process_one_work(struct worker *worker, struct work_struct *work)
2090 __releases(&pool->lock)
2091 __acquires(&pool->lock)
2093 struct pool_workqueue *pwq = get_work_pwq(work);
2094 struct worker_pool *pool = worker->pool;
2095 bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
2097 struct worker *collision;
2098 #ifdef CONFIG_LOCKDEP
2100 * It is permissible to free the struct work_struct from
2101 * inside the function that is called from it, this we need to
2102 * take into account for lockdep too. To avoid bogus "held
2103 * lock freed" warnings as well as problems when looking into
2104 * work->lockdep_map, make a copy and use that here.
2106 struct lockdep_map lockdep_map;
2108 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
2111 * Ensure we're on the correct CPU. DISASSOCIATED test is
2112 * necessary to avoid spurious warnings from rescuers servicing the
2113 * unbound or a disassociated pool.
2115 WARN_ON_ONCE(!(worker->flags & WORKER_UNBOUND) &&
2116 !(pool->flags & POOL_DISASSOCIATED) &&
2117 raw_smp_processor_id() != pool->cpu);
2120 * A single work shouldn't be executed concurrently by
2121 * multiple workers on a single cpu. Check whether anyone is
2122 * already processing the work. If so, defer the work to the
2123 * currently executing one.
2125 collision = find_worker_executing_work(pool, work);
2126 if (unlikely(collision)) {
2127 move_linked_works(work, &collision->scheduled, NULL);
2131 /* claim and dequeue */
2132 debug_work_deactivate(work);
2133 hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2134 worker->current_work = work;
2135 worker->current_func = work->func;
2136 worker->current_pwq = pwq;
2137 work_color = get_work_color(work);
2139 list_del_init(&work->entry);
2142 * CPU intensive works don't participate in concurrency
2143 * management. They're the scheduler's responsibility.
2145 if (unlikely(cpu_intensive))
2146 worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
2149 * Unbound pool isn't concurrency managed and work items should be
2150 * executed ASAP. Wake up another worker if necessary.
2152 if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
2153 wake_up_worker(pool);
2156 * Record the last pool and clear PENDING which should be the last
2157 * update to @work. Also, do this inside @pool->lock so that
2158 * PENDING and queued state changes happen together while IRQ is
2161 set_work_pool_and_clear_pending(work, pool->id);
2163 spin_unlock_irq(&pool->lock);
2165 lock_map_acquire_read(&pwq->wq->lockdep_map);
2166 lock_map_acquire(&lockdep_map);
2167 trace_workqueue_execute_start(work);
2168 worker->current_func(work);
2170 * While we must be careful to not use "work" after this, the trace
2171 * point will only record its address.
2173 trace_workqueue_execute_end(work);
2174 lock_map_release(&lockdep_map);
2175 lock_map_release(&pwq->wq->lockdep_map);
2177 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2178 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2179 " last function: %pf\n",
2180 current->comm, preempt_count(), task_pid_nr(current),
2181 worker->current_func);
2182 debug_show_held_locks(current);
2186 spin_lock_irq(&pool->lock);
2188 /* clear cpu intensive status */
2189 if (unlikely(cpu_intensive))
2190 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2192 /* we're done with it, release */
2193 hash_del(&worker->hentry);
2194 worker->current_work = NULL;
2195 worker->current_func = NULL;
2196 worker->current_pwq = NULL;
2197 pwq_dec_nr_in_flight(pwq, work_color);
2201 * process_scheduled_works - process scheduled works
2204 * Process all scheduled works. Please note that the scheduled list
2205 * may change while processing a work, so this function repeatedly
2206 * fetches a work from the top and executes it.
2209 * spin_lock_irq(pool->lock) which may be released and regrabbed
2212 static void process_scheduled_works(struct worker *worker)
2214 while (!list_empty(&worker->scheduled)) {
2215 struct work_struct *work = list_first_entry(&worker->scheduled,
2216 struct work_struct, entry);
2217 process_one_work(worker, work);
2222 * worker_thread - the worker thread function
2225 * The worker thread function. There are NR_CPU_WORKER_POOLS dynamic pools
2226 * of these per each cpu. These workers process all works regardless of
2227 * their specific target workqueue. The only exception is works which
2228 * belong to workqueues with a rescuer which will be explained in
2231 static int worker_thread(void *__worker)
2233 struct worker *worker = __worker;
2234 struct worker_pool *pool = worker->pool;
2236 /* tell the scheduler that this is a workqueue worker */
2237 worker->task->flags |= PF_WQ_WORKER;
2239 spin_lock_irq(&pool->lock);
2241 /* we are off idle list if destruction or rebind is requested */
2242 if (unlikely(list_empty(&worker->entry))) {
2243 spin_unlock_irq(&pool->lock);
2245 /* if DIE is set, destruction is requested */
2246 if (worker->flags & WORKER_DIE) {
2247 worker->task->flags &= ~PF_WQ_WORKER;
2251 /* otherwise, rebind */
2252 idle_worker_rebind(worker);
2256 worker_leave_idle(worker);
2258 /* no more worker necessary? */
2259 if (!need_more_worker(pool))
2262 /* do we need to manage? */
2263 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2267 * ->scheduled list can only be filled while a worker is
2268 * preparing to process a work or actually processing it.
2269 * Make sure nobody diddled with it while I was sleeping.
2271 WARN_ON_ONCE(!list_empty(&worker->scheduled));
2274 * When control reaches this point, we're guaranteed to have
2275 * at least one idle worker or that someone else has already
2276 * assumed the manager role.
2278 worker_clr_flags(worker, WORKER_PREP);
2281 struct work_struct *work =
2282 list_first_entry(&pool->worklist,
2283 struct work_struct, entry);
2285 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2286 /* optimization path, not strictly necessary */
2287 process_one_work(worker, work);
2288 if (unlikely(!list_empty(&worker->scheduled)))
2289 process_scheduled_works(worker);
2291 move_linked_works(work, &worker->scheduled, NULL);
2292 process_scheduled_works(worker);
2294 } while (keep_working(pool));
2296 worker_set_flags(worker, WORKER_PREP, false);
2298 if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
2302 * pool->lock is held and there's no work to process and no need to
2303 * manage, sleep. Workers are woken up only while holding
2304 * pool->lock or from local cpu, so setting the current state
2305 * before releasing pool->lock is enough to prevent losing any
2308 worker_enter_idle(worker);
2309 __set_current_state(TASK_INTERRUPTIBLE);
2310 spin_unlock_irq(&pool->lock);
2316 * rescuer_thread - the rescuer thread function
2319 * Workqueue rescuer thread function. There's one rescuer for each
2320 * workqueue which has WQ_RESCUER set.
2322 * Regular work processing on a pool may block trying to create a new
2323 * worker which uses GFP_KERNEL allocation which has slight chance of
2324 * developing into deadlock if some works currently on the same queue
2325 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2326 * the problem rescuer solves.
2328 * When such condition is possible, the pool summons rescuers of all
2329 * workqueues which have works queued on the pool and let them process
2330 * those works so that forward progress can be guaranteed.
2332 * This should happen rarely.
2334 static int rescuer_thread(void *__rescuer)
2336 struct worker *rescuer = __rescuer;
2337 struct workqueue_struct *wq = rescuer->rescue_wq;
2338 struct list_head *scheduled = &rescuer->scheduled;
2339 bool is_unbound = wq->flags & WQ_UNBOUND;
2342 set_user_nice(current, RESCUER_NICE_LEVEL);
2345 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2346 * doesn't participate in concurrency management.
2348 rescuer->task->flags |= PF_WQ_WORKER;
2350 set_current_state(TASK_INTERRUPTIBLE);
2352 if (kthread_should_stop()) {
2353 __set_current_state(TASK_RUNNING);
2354 rescuer->task->flags &= ~PF_WQ_WORKER;
2359 * See whether any cpu is asking for help. Unbounded
2360 * workqueues use cpu 0 in mayday_mask for CPU_UNBOUND.
2362 for_each_mayday_cpu(cpu, wq->mayday_mask) {
2363 unsigned int tcpu = is_unbound ? WORK_CPU_UNBOUND : cpu;
2364 struct pool_workqueue *pwq = get_pwq(tcpu, wq);
2365 struct worker_pool *pool = pwq->pool;
2366 struct work_struct *work, *n;
2368 __set_current_state(TASK_RUNNING);
2369 mayday_clear_cpu(cpu, wq->mayday_mask);
2371 /* migrate to the target cpu if possible */
2372 worker_maybe_bind_and_lock(pool);
2373 rescuer->pool = pool;
2376 * Slurp in all works issued via this workqueue and
2379 WARN_ON_ONCE(!list_empty(&rescuer->scheduled));
2380 list_for_each_entry_safe(work, n, &pool->worklist, entry)
2381 if (get_work_pwq(work) == pwq)
2382 move_linked_works(work, scheduled, &n);
2384 process_scheduled_works(rescuer);
2387 * Leave this pool. If keep_working() is %true, notify a
2388 * regular worker; otherwise, we end up with 0 concurrency
2389 * and stalling the execution.
2391 if (keep_working(pool))
2392 wake_up_worker(pool);
2394 rescuer->pool = NULL;
2395 spin_unlock_irq(&pool->lock);
2398 /* rescuers should never participate in concurrency management */
2399 WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2405 struct work_struct work;
2406 struct completion done;
2409 static void wq_barrier_func(struct work_struct *work)
2411 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2412 complete(&barr->done);
2416 * insert_wq_barrier - insert a barrier work
2417 * @pwq: pwq to insert barrier into
2418 * @barr: wq_barrier to insert
2419 * @target: target work to attach @barr to
2420 * @worker: worker currently executing @target, NULL if @target is not executing
2422 * @barr is linked to @target such that @barr is completed only after
2423 * @target finishes execution. Please note that the ordering
2424 * guarantee is observed only with respect to @target and on the local
2427 * Currently, a queued barrier can't be canceled. This is because
2428 * try_to_grab_pending() can't determine whether the work to be
2429 * grabbed is at the head of the queue and thus can't clear LINKED
2430 * flag of the previous work while there must be a valid next work
2431 * after a work with LINKED flag set.
2433 * Note that when @worker is non-NULL, @target may be modified
2434 * underneath us, so we can't reliably determine pwq from @target.
2437 * spin_lock_irq(pool->lock).
2439 static void insert_wq_barrier(struct pool_workqueue *pwq,
2440 struct wq_barrier *barr,
2441 struct work_struct *target, struct worker *worker)
2443 struct list_head *head;
2444 unsigned int linked = 0;
2447 * debugobject calls are safe here even with pool->lock locked
2448 * as we know for sure that this will not trigger any of the
2449 * checks and call back into the fixup functions where we
2452 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2453 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2454 init_completion(&barr->done);
2457 * If @target is currently being executed, schedule the
2458 * barrier to the worker; otherwise, put it after @target.
2461 head = worker->scheduled.next;
2463 unsigned long *bits = work_data_bits(target);
2465 head = target->entry.next;
2466 /* there can already be other linked works, inherit and set */
2467 linked = *bits & WORK_STRUCT_LINKED;
2468 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2471 debug_work_activate(&barr->work);
2472 insert_work(pwq, &barr->work, head,
2473 work_color_to_flags(WORK_NO_COLOR) | linked);
2477 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
2478 * @wq: workqueue being flushed
2479 * @flush_color: new flush color, < 0 for no-op
2480 * @work_color: new work color, < 0 for no-op
2482 * Prepare pwqs for workqueue flushing.
2484 * If @flush_color is non-negative, flush_color on all pwqs should be
2485 * -1. If no pwq has in-flight commands at the specified color, all
2486 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
2487 * has in flight commands, its pwq->flush_color is set to
2488 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
2489 * wakeup logic is armed and %true is returned.
2491 * The caller should have initialized @wq->first_flusher prior to
2492 * calling this function with non-negative @flush_color. If
2493 * @flush_color is negative, no flush color update is done and %false
2496 * If @work_color is non-negative, all pwqs should have the same
2497 * work_color which is previous to @work_color and all will be
2498 * advanced to @work_color.
2501 * mutex_lock(wq->flush_mutex).
2504 * %true if @flush_color >= 0 and there's something to flush. %false
2507 static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
2508 int flush_color, int work_color)
2511 struct pool_workqueue *pwq;
2513 if (flush_color >= 0) {
2514 WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2515 atomic_set(&wq->nr_pwqs_to_flush, 1);
2518 for_each_pwq(pwq, wq) {
2519 struct worker_pool *pool = pwq->pool;
2521 spin_lock_irq(&pool->lock);
2523 if (flush_color >= 0) {
2524 WARN_ON_ONCE(pwq->flush_color != -1);
2526 if (pwq->nr_in_flight[flush_color]) {
2527 pwq->flush_color = flush_color;
2528 atomic_inc(&wq->nr_pwqs_to_flush);
2533 if (work_color >= 0) {
2534 WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2535 pwq->work_color = work_color;
2538 spin_unlock_irq(&pool->lock);
2541 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
2542 complete(&wq->first_flusher->done);
2548 * flush_workqueue - ensure that any scheduled work has run to completion.
2549 * @wq: workqueue to flush
2551 * Forces execution of the workqueue and blocks until its completion.
2552 * This is typically used in driver shutdown handlers.
2554 * We sleep until all works which were queued on entry have been handled,
2555 * but we are not livelocked by new incoming ones.
2557 void flush_workqueue(struct workqueue_struct *wq)
2559 struct wq_flusher this_flusher = {
2560 .list = LIST_HEAD_INIT(this_flusher.list),
2562 .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
2566 lock_map_acquire(&wq->lockdep_map);
2567 lock_map_release(&wq->lockdep_map);
2569 mutex_lock(&wq->flush_mutex);
2572 * Start-to-wait phase
2574 next_color = work_next_color(wq->work_color);
2576 if (next_color != wq->flush_color) {
2578 * Color space is not full. The current work_color
2579 * becomes our flush_color and work_color is advanced
2582 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
2583 this_flusher.flush_color = wq->work_color;
2584 wq->work_color = next_color;
2586 if (!wq->first_flusher) {
2587 /* no flush in progress, become the first flusher */
2588 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2590 wq->first_flusher = &this_flusher;
2592 if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
2594 /* nothing to flush, done */
2595 wq->flush_color = next_color;
2596 wq->first_flusher = NULL;
2601 WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
2602 list_add_tail(&this_flusher.list, &wq->flusher_queue);
2603 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2607 * Oops, color space is full, wait on overflow queue.
2608 * The next flush completion will assign us
2609 * flush_color and transfer to flusher_queue.
2611 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2614 mutex_unlock(&wq->flush_mutex);
2616 wait_for_completion(&this_flusher.done);
2619 * Wake-up-and-cascade phase
2621 * First flushers are responsible for cascading flushes and
2622 * handling overflow. Non-first flushers can simply return.
2624 if (wq->first_flusher != &this_flusher)
2627 mutex_lock(&wq->flush_mutex);
2629 /* we might have raced, check again with mutex held */
2630 if (wq->first_flusher != &this_flusher)
2633 wq->first_flusher = NULL;
2635 WARN_ON_ONCE(!list_empty(&this_flusher.list));
2636 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2639 struct wq_flusher *next, *tmp;
2641 /* complete all the flushers sharing the current flush color */
2642 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2643 if (next->flush_color != wq->flush_color)
2645 list_del_init(&next->list);
2646 complete(&next->done);
2649 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
2650 wq->flush_color != work_next_color(wq->work_color));
2652 /* this flush_color is finished, advance by one */
2653 wq->flush_color = work_next_color(wq->flush_color);
2655 /* one color has been freed, handle overflow queue */
2656 if (!list_empty(&wq->flusher_overflow)) {
2658 * Assign the same color to all overflowed
2659 * flushers, advance work_color and append to
2660 * flusher_queue. This is the start-to-wait
2661 * phase for these overflowed flushers.
2663 list_for_each_entry(tmp, &wq->flusher_overflow, list)
2664 tmp->flush_color = wq->work_color;
2666 wq->work_color = work_next_color(wq->work_color);
2668 list_splice_tail_init(&wq->flusher_overflow,
2669 &wq->flusher_queue);
2670 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2673 if (list_empty(&wq->flusher_queue)) {
2674 WARN_ON_ONCE(wq->flush_color != wq->work_color);
2679 * Need to flush more colors. Make the next flusher
2680 * the new first flusher and arm pwqs.
2682 WARN_ON_ONCE(wq->flush_color == wq->work_color);
2683 WARN_ON_ONCE(wq->flush_color != next->flush_color);
2685 list_del_init(&next->list);
2686 wq->first_flusher = next;
2688 if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
2692 * Meh... this color is already done, clear first
2693 * flusher and repeat cascading.
2695 wq->first_flusher = NULL;
2699 mutex_unlock(&wq->flush_mutex);
2701 EXPORT_SYMBOL_GPL(flush_workqueue);
2704 * drain_workqueue - drain a workqueue
2705 * @wq: workqueue to drain
2707 * Wait until the workqueue becomes empty. While draining is in progress,
2708 * only chain queueing is allowed. IOW, only currently pending or running
2709 * work items on @wq can queue further work items on it. @wq is flushed
2710 * repeatedly until it becomes empty. The number of flushing is detemined
2711 * by the depth of chaining and should be relatively short. Whine if it
2714 void drain_workqueue(struct workqueue_struct *wq)
2716 unsigned int flush_cnt = 0;
2717 struct pool_workqueue *pwq;
2720 * __queue_work() needs to test whether there are drainers, is much
2721 * hotter than drain_workqueue() and already looks at @wq->flags.
2722 * Use WQ_DRAINING so that queue doesn't have to check nr_drainers.
2724 spin_lock_irq(&workqueue_lock);
2725 if (!wq->nr_drainers++)
2726 wq->flags |= WQ_DRAINING;
2727 spin_unlock_irq(&workqueue_lock);
2729 flush_workqueue(wq);
2731 for_each_pwq(pwq, wq) {
2734 spin_lock_irq(&pwq->pool->lock);
2735 drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
2736 spin_unlock_irq(&pwq->pool->lock);
2741 if (++flush_cnt == 10 ||
2742 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2743 pr_warn("workqueue %s: flush on destruction isn't complete after %u tries\n",
2744 wq->name, flush_cnt);
2748 spin_lock_irq(&workqueue_lock);
2749 if (!--wq->nr_drainers)
2750 wq->flags &= ~WQ_DRAINING;
2751 spin_unlock_irq(&workqueue_lock);
2753 EXPORT_SYMBOL_GPL(drain_workqueue);
2755 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2757 struct worker *worker = NULL;
2758 struct worker_pool *pool;
2759 struct pool_workqueue *pwq;
2762 pool = get_work_pool(work);
2766 spin_lock_irq(&pool->lock);
2767 /* see the comment in try_to_grab_pending() with the same code */
2768 pwq = get_work_pwq(work);
2770 if (unlikely(pwq->pool != pool))
2773 worker = find_worker_executing_work(pool, work);
2776 pwq = worker->current_pwq;
2779 insert_wq_barrier(pwq, barr, work, worker);
2780 spin_unlock_irq(&pool->lock);
2783 * If @max_active is 1 or rescuer is in use, flushing another work
2784 * item on the same workqueue may lead to deadlock. Make sure the
2785 * flusher is not running on the same workqueue by verifying write
2788 if (pwq->wq->saved_max_active == 1 || pwq->wq->flags & WQ_RESCUER)
2789 lock_map_acquire(&pwq->wq->lockdep_map);
2791 lock_map_acquire_read(&pwq->wq->lockdep_map);
2792 lock_map_release(&pwq->wq->lockdep_map);
2796 spin_unlock_irq(&pool->lock);
2801 * flush_work - wait for a work to finish executing the last queueing instance
2802 * @work: the work to flush
2804 * Wait until @work has finished execution. @work is guaranteed to be idle
2805 * on return if it hasn't been requeued since flush started.
2808 * %true if flush_work() waited for the work to finish execution,
2809 * %false if it was already idle.
2811 bool flush_work(struct work_struct *work)
2813 struct wq_barrier barr;
2815 lock_map_acquire(&work->lockdep_map);
2816 lock_map_release(&work->lockdep_map);
2818 if (start_flush_work(work, &barr)) {
2819 wait_for_completion(&barr.done);
2820 destroy_work_on_stack(&barr.work);
2826 EXPORT_SYMBOL_GPL(flush_work);
2828 static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2830 unsigned long flags;
2834 ret = try_to_grab_pending(work, is_dwork, &flags);
2836 * If someone else is canceling, wait for the same event it
2837 * would be waiting for before retrying.
2839 if (unlikely(ret == -ENOENT))
2841 } while (unlikely(ret < 0));
2843 /* tell other tasks trying to grab @work to back off */
2844 mark_work_canceling(work);
2845 local_irq_restore(flags);
2848 clear_work_data(work);
2853 * cancel_work_sync - cancel a work and wait for it to finish
2854 * @work: the work to cancel
2856 * Cancel @work and wait for its execution to finish. This function
2857 * can be used even if the work re-queues itself or migrates to
2858 * another workqueue. On return from this function, @work is
2859 * guaranteed to be not pending or executing on any CPU.
2861 * cancel_work_sync(&delayed_work->work) must not be used for
2862 * delayed_work's. Use cancel_delayed_work_sync() instead.
2864 * The caller must ensure that the workqueue on which @work was last
2865 * queued can't be destroyed before this function returns.
2868 * %true if @work was pending, %false otherwise.
2870 bool cancel_work_sync(struct work_struct *work)
2872 return __cancel_work_timer(work, false);
2874 EXPORT_SYMBOL_GPL(cancel_work_sync);
2877 * flush_delayed_work - wait for a dwork to finish executing the last queueing
2878 * @dwork: the delayed work to flush
2880 * Delayed timer is cancelled and the pending work is queued for
2881 * immediate execution. Like flush_work(), this function only
2882 * considers the last queueing instance of @dwork.
2885 * %true if flush_work() waited for the work to finish execution,
2886 * %false if it was already idle.
2888 bool flush_delayed_work(struct delayed_work *dwork)
2890 local_irq_disable();
2891 if (del_timer_sync(&dwork->timer))
2892 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
2894 return flush_work(&dwork->work);
2896 EXPORT_SYMBOL(flush_delayed_work);
2899 * cancel_delayed_work - cancel a delayed work
2900 * @dwork: delayed_work to cancel
2902 * Kill off a pending delayed_work. Returns %true if @dwork was pending
2903 * and canceled; %false if wasn't pending. Note that the work callback
2904 * function may still be running on return, unless it returns %true and the
2905 * work doesn't re-arm itself. Explicitly flush or use
2906 * cancel_delayed_work_sync() to wait on it.
2908 * This function is safe to call from any context including IRQ handler.
2910 bool cancel_delayed_work(struct delayed_work *dwork)
2912 unsigned long flags;
2916 ret = try_to_grab_pending(&dwork->work, true, &flags);
2917 } while (unlikely(ret == -EAGAIN));
2919 if (unlikely(ret < 0))
2922 set_work_pool_and_clear_pending(&dwork->work,
2923 get_work_pool_id(&dwork->work));
2924 local_irq_restore(flags);
2927 EXPORT_SYMBOL(cancel_delayed_work);
2930 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2931 * @dwork: the delayed work cancel
2933 * This is cancel_work_sync() for delayed works.
2936 * %true if @dwork was pending, %false otherwise.
2938 bool cancel_delayed_work_sync(struct delayed_work *dwork)
2940 return __cancel_work_timer(&dwork->work, true);
2942 EXPORT_SYMBOL(cancel_delayed_work_sync);
2945 * schedule_work_on - put work task on a specific cpu
2946 * @cpu: cpu to put the work task on
2947 * @work: job to be done
2949 * This puts a job on a specific cpu
2951 bool schedule_work_on(int cpu, struct work_struct *work)
2953 return queue_work_on(cpu, system_wq, work);
2955 EXPORT_SYMBOL(schedule_work_on);
2958 * schedule_work - put work task in global workqueue
2959 * @work: job to be done
2961 * Returns %false if @work was already on the kernel-global workqueue and
2964 * This puts a job in the kernel-global workqueue if it was not already
2965 * queued and leaves it in the same position on the kernel-global
2966 * workqueue otherwise.
2968 bool schedule_work(struct work_struct *work)
2970 return queue_work(system_wq, work);
2972 EXPORT_SYMBOL(schedule_work);
2975 * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
2977 * @dwork: job to be done
2978 * @delay: number of jiffies to wait
2980 * After waiting for a given time this puts a job in the kernel-global
2981 * workqueue on the specified CPU.
2983 bool schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
2984 unsigned long delay)
2986 return queue_delayed_work_on(cpu, system_wq, dwork, delay);
2988 EXPORT_SYMBOL(schedule_delayed_work_on);
2991 * schedule_delayed_work - put work task in global workqueue after delay
2992 * @dwork: job to be done
2993 * @delay: number of jiffies to wait or 0 for immediate execution
2995 * After waiting for a given time this puts a job in the kernel-global
2998 bool schedule_delayed_work(struct delayed_work *dwork, unsigned long delay)
3000 return queue_delayed_work(system_wq, dwork, delay);
3002 EXPORT_SYMBOL(schedule_delayed_work);
3005 * schedule_on_each_cpu - execute a function synchronously on each online CPU
3006 * @func: the function to call
3008 * schedule_on_each_cpu() executes @func on each online CPU using the
3009 * system workqueue and blocks until all CPUs have completed.
3010 * schedule_on_each_cpu() is very slow.
3013 * 0 on success, -errno on failure.
3015 int schedule_on_each_cpu(work_func_t func)
3018 struct work_struct __percpu *works;
3020 works = alloc_percpu(struct work_struct);
3026 for_each_online_cpu(cpu) {
3027 struct work_struct *work = per_cpu_ptr(works, cpu);
3029 INIT_WORK(work, func);
3030 schedule_work_on(cpu, work);
3033 for_each_online_cpu(cpu)
3034 flush_work(per_cpu_ptr(works, cpu));
3042 * flush_scheduled_work - ensure that any scheduled work has run to completion.
3044 * Forces execution of the kernel-global workqueue and blocks until its
3047 * Think twice before calling this function! It's very easy to get into
3048 * trouble if you don't take great care. Either of the following situations
3049 * will lead to deadlock:
3051 * One of the work items currently on the workqueue needs to acquire
3052 * a lock held by your code or its caller.
3054 * Your code is running in the context of a work routine.
3056 * They will be detected by lockdep when they occur, but the first might not
3057 * occur very often. It depends on what work items are on the workqueue and
3058 * what locks they need, which you have no control over.
3060 * In most situations flushing the entire workqueue is overkill; you merely
3061 * need to know that a particular work item isn't queued and isn't running.
3062 * In such cases you should use cancel_delayed_work_sync() or
3063 * cancel_work_sync() instead.
3065 void flush_scheduled_work(void)
3067 flush_workqueue(system_wq);
3069 EXPORT_SYMBOL(flush_scheduled_work);
3072 * execute_in_process_context - reliably execute the routine with user context
3073 * @fn: the function to execute
3074 * @ew: guaranteed storage for the execute work structure (must
3075 * be available when the work executes)
3077 * Executes the function immediately if process context is available,
3078 * otherwise schedules the function for delayed execution.
3080 * Returns: 0 - function was executed
3081 * 1 - function was scheduled for execution
3083 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
3085 if (!in_interrupt()) {
3090 INIT_WORK(&ew->work, fn);
3091 schedule_work(&ew->work);
3095 EXPORT_SYMBOL_GPL(execute_in_process_context);
3097 int keventd_up(void)
3099 return system_wq != NULL;
3102 static int alloc_and_link_pwqs(struct workqueue_struct *wq)
3104 bool highpri = wq->flags & WQ_HIGHPRI;
3107 if (!(wq->flags & WQ_UNBOUND)) {
3108 wq->pool_wq.pcpu = alloc_percpu(struct pool_workqueue);
3109 if (!wq->pool_wq.pcpu)
3112 for_each_possible_cpu(cpu) {
3113 struct pool_workqueue *pwq = get_pwq(cpu, wq);
3115 pwq->pool = get_std_worker_pool(cpu, highpri);
3116 list_add_tail(&pwq->pwqs_node, &wq->pwqs);
3119 struct pool_workqueue *pwq;
3121 pwq = kmem_cache_zalloc(pwq_cache, GFP_KERNEL);
3125 wq->pool_wq.single = pwq;
3126 pwq->pool = get_std_worker_pool(WORK_CPU_UNBOUND, highpri);
3127 list_add_tail(&pwq->pwqs_node, &wq->pwqs);
3133 static void free_pwqs(struct workqueue_struct *wq)
3135 if (!(wq->flags & WQ_UNBOUND))
3136 free_percpu(wq->pool_wq.pcpu);
3138 kmem_cache_free(pwq_cache, wq->pool_wq.single);
3141 static int wq_clamp_max_active(int max_active, unsigned int flags,
3144 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3146 if (max_active < 1 || max_active > lim)
3147 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3148 max_active, name, 1, lim);
3150 return clamp_val(max_active, 1, lim);
3153 struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
3156 struct lock_class_key *key,
3157 const char *lock_name, ...)
3159 va_list args, args1;
3160 struct workqueue_struct *wq;
3161 struct pool_workqueue *pwq;
3164 /* determine namelen, allocate wq and format name */
3165 va_start(args, lock_name);
3166 va_copy(args1, args);
3167 namelen = vsnprintf(NULL, 0, fmt, args) + 1;
3169 wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
3173 vsnprintf(wq->name, namelen, fmt, args1);
3178 * Workqueues which may be used during memory reclaim should
3179 * have a rescuer to guarantee forward progress.
3181 if (flags & WQ_MEM_RECLAIM)
3182 flags |= WQ_RESCUER;
3184 max_active = max_active ?: WQ_DFL_ACTIVE;
3185 max_active = wq_clamp_max_active(max_active, flags, wq->name);
3189 wq->saved_max_active = max_active;
3190 mutex_init(&wq->flush_mutex);
3191 atomic_set(&wq->nr_pwqs_to_flush, 0);
3192 INIT_LIST_HEAD(&wq->pwqs);
3193 INIT_LIST_HEAD(&wq->flusher_queue);
3194 INIT_LIST_HEAD(&wq->flusher_overflow);
3196 lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3197 INIT_LIST_HEAD(&wq->list);
3199 if (alloc_and_link_pwqs(wq) < 0)
3202 for_each_pwq(pwq, wq) {
3203 BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3205 pwq->flush_color = -1;
3206 pwq->max_active = max_active;
3207 INIT_LIST_HEAD(&pwq->delayed_works);
3210 if (flags & WQ_RESCUER) {
3211 struct worker *rescuer;
3213 if (!alloc_mayday_mask(&wq->mayday_mask, GFP_KERNEL))
3216 wq->rescuer = rescuer = alloc_worker();
3220 rescuer->rescue_wq = wq;
3221 rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
3223 if (IS_ERR(rescuer->task))
3226 rescuer->task->flags |= PF_THREAD_BOUND;
3227 wake_up_process(rescuer->task);
3231 * workqueue_lock protects global freeze state and workqueues
3232 * list. Grab it, set max_active accordingly and add the new
3233 * workqueue to workqueues list.
3235 spin_lock_irq(&workqueue_lock);
3237 if (workqueue_freezing && wq->flags & WQ_FREEZABLE)
3238 for_each_pwq(pwq, wq)
3239 pwq->max_active = 0;
3241 list_add(&wq->list, &workqueues);
3243 spin_unlock_irq(&workqueue_lock);
3249 free_mayday_mask(wq->mayday_mask);
3255 EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
3258 * destroy_workqueue - safely terminate a workqueue
3259 * @wq: target workqueue
3261 * Safely destroy a workqueue. All work currently pending will be done first.
3263 void destroy_workqueue(struct workqueue_struct *wq)
3265 struct pool_workqueue *pwq;
3267 /* drain it before proceeding with destruction */
3268 drain_workqueue(wq);
3271 for_each_pwq(pwq, wq) {
3274 for (i = 0; i < WORK_NR_COLORS; i++)
3275 if (WARN_ON(pwq->nr_in_flight[i]))
3277 if (WARN_ON(pwq->nr_active) ||
3278 WARN_ON(!list_empty(&pwq->delayed_works)))
3283 * wq list is used to freeze wq, remove from list after
3284 * flushing is complete in case freeze races us.
3286 spin_lock_irq(&workqueue_lock);
3287 list_del(&wq->list);
3288 spin_unlock_irq(&workqueue_lock);
3290 if (wq->flags & WQ_RESCUER) {
3291 kthread_stop(wq->rescuer->task);
3292 free_mayday_mask(wq->mayday_mask);
3299 EXPORT_SYMBOL_GPL(destroy_workqueue);
3302 * pwq_set_max_active - adjust max_active of a pwq
3303 * @pwq: target pool_workqueue
3304 * @max_active: new max_active value.
3306 * Set @pwq->max_active to @max_active and activate delayed works if
3310 * spin_lock_irq(pool->lock).
3312 static void pwq_set_max_active(struct pool_workqueue *pwq, int max_active)
3314 pwq->max_active = max_active;
3316 while (!list_empty(&pwq->delayed_works) &&
3317 pwq->nr_active < pwq->max_active)
3318 pwq_activate_first_delayed(pwq);
3322 * workqueue_set_max_active - adjust max_active of a workqueue
3323 * @wq: target workqueue
3324 * @max_active: new max_active value.
3326 * Set max_active of @wq to @max_active.
3329 * Don't call from IRQ context.
3331 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
3333 struct pool_workqueue *pwq;
3335 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
3337 spin_lock_irq(&workqueue_lock);
3339 wq->saved_max_active = max_active;
3341 for_each_pwq(pwq, wq) {
3342 struct worker_pool *pool = pwq->pool;
3344 spin_lock(&pool->lock);
3346 if (!(wq->flags & WQ_FREEZABLE) ||
3347 !(pool->flags & POOL_FREEZING))
3348 pwq_set_max_active(pwq, max_active);
3350 spin_unlock(&pool->lock);
3353 spin_unlock_irq(&workqueue_lock);
3355 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
3358 * workqueue_congested - test whether a workqueue is congested
3359 * @cpu: CPU in question
3360 * @wq: target workqueue
3362 * Test whether @wq's cpu workqueue for @cpu is congested. There is
3363 * no synchronization around this function and the test result is
3364 * unreliable and only useful as advisory hints or for debugging.
3367 * %true if congested, %false otherwise.
3369 bool workqueue_congested(unsigned int cpu, struct workqueue_struct *wq)
3371 struct pool_workqueue *pwq = get_pwq(cpu, wq);
3373 return !list_empty(&pwq->delayed_works);
3375 EXPORT_SYMBOL_GPL(workqueue_congested);
3378 * work_busy - test whether a work is currently pending or running
3379 * @work: the work to be tested
3381 * Test whether @work is currently pending or running. There is no
3382 * synchronization around this function and the test result is
3383 * unreliable and only useful as advisory hints or for debugging.
3386 * OR'd bitmask of WORK_BUSY_* bits.
3388 unsigned int work_busy(struct work_struct *work)
3390 struct worker_pool *pool = get_work_pool(work);
3391 unsigned long flags;
3392 unsigned int ret = 0;
3394 if (work_pending(work))
3395 ret |= WORK_BUSY_PENDING;
3398 spin_lock_irqsave(&pool->lock, flags);
3399 if (find_worker_executing_work(pool, work))
3400 ret |= WORK_BUSY_RUNNING;
3401 spin_unlock_irqrestore(&pool->lock, flags);
3406 EXPORT_SYMBOL_GPL(work_busy);
3411 * There are two challenges in supporting CPU hotplug. Firstly, there
3412 * are a lot of assumptions on strong associations among work, pwq and
3413 * pool which make migrating pending and scheduled works very
3414 * difficult to implement without impacting hot paths. Secondly,
3415 * worker pools serve mix of short, long and very long running works making
3416 * blocked draining impractical.
3418 * This is solved by allowing the pools to be disassociated from the CPU
3419 * running as an unbound one and allowing it to be reattached later if the
3420 * cpu comes back online.
3423 static void wq_unbind_fn(struct work_struct *work)
3425 int cpu = smp_processor_id();
3426 struct worker_pool *pool;
3427 struct worker *worker;
3430 for_each_std_worker_pool(pool, cpu) {
3431 WARN_ON_ONCE(cpu != smp_processor_id());
3433 mutex_lock(&pool->assoc_mutex);
3434 spin_lock_irq(&pool->lock);
3437 * We've claimed all manager positions. Make all workers
3438 * unbound and set DISASSOCIATED. Before this, all workers
3439 * except for the ones which are still executing works from
3440 * before the last CPU down must be on the cpu. After
3441 * this, they may become diasporas.
3443 list_for_each_entry(worker, &pool->idle_list, entry)
3444 worker->flags |= WORKER_UNBOUND;
3446 for_each_busy_worker(worker, i, pool)
3447 worker->flags |= WORKER_UNBOUND;
3449 pool->flags |= POOL_DISASSOCIATED;
3451 spin_unlock_irq(&pool->lock);
3452 mutex_unlock(&pool->assoc_mutex);
3456 * Call schedule() so that we cross rq->lock and thus can guarantee
3457 * sched callbacks see the %WORKER_UNBOUND flag. This is necessary
3458 * as scheduler callbacks may be invoked from other cpus.
3463 * Sched callbacks are disabled now. Zap nr_running. After this,
3464 * nr_running stays zero and need_more_worker() and keep_working()
3465 * are always true as long as the worklist is not empty. Pools on
3466 * @cpu now behave as unbound (in terms of concurrency management)
3467 * pools which are served by workers tied to the CPU.
3469 * On return from this function, the current worker would trigger
3470 * unbound chain execution of pending work items if other workers
3473 for_each_std_worker_pool(pool, cpu)
3474 atomic_set(&pool->nr_running, 0);
3478 * Workqueues should be brought up before normal priority CPU notifiers.
3479 * This will be registered high priority CPU notifier.
3481 static int __cpuinit workqueue_cpu_up_callback(struct notifier_block *nfb,
3482 unsigned long action,
3485 unsigned int cpu = (unsigned long)hcpu;
3486 struct worker_pool *pool;
3488 switch (action & ~CPU_TASKS_FROZEN) {
3489 case CPU_UP_PREPARE:
3490 for_each_std_worker_pool(pool, cpu) {
3491 struct worker *worker;
3493 if (pool->nr_workers)
3496 worker = create_worker(pool);
3500 spin_lock_irq(&pool->lock);
3501 start_worker(worker);
3502 spin_unlock_irq(&pool->lock);
3506 case CPU_DOWN_FAILED:
3508 for_each_std_worker_pool(pool, cpu) {
3509 mutex_lock(&pool->assoc_mutex);
3510 spin_lock_irq(&pool->lock);
3512 pool->flags &= ~POOL_DISASSOCIATED;
3513 rebind_workers(pool);
3515 spin_unlock_irq(&pool->lock);
3516 mutex_unlock(&pool->assoc_mutex);
3524 * Workqueues should be brought down after normal priority CPU notifiers.
3525 * This will be registered as low priority CPU notifier.
3527 static int __cpuinit workqueue_cpu_down_callback(struct notifier_block *nfb,
3528 unsigned long action,
3531 unsigned int cpu = (unsigned long)hcpu;
3532 struct work_struct unbind_work;
3534 switch (action & ~CPU_TASKS_FROZEN) {
3535 case CPU_DOWN_PREPARE:
3536 /* unbinding should happen on the local CPU */
3537 INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
3538 queue_work_on(cpu, system_highpri_wq, &unbind_work);
3539 flush_work(&unbind_work);
3547 struct work_for_cpu {
3548 struct work_struct work;
3554 static void work_for_cpu_fn(struct work_struct *work)
3556 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
3558 wfc->ret = wfc->fn(wfc->arg);
3562 * work_on_cpu - run a function in user context on a particular cpu
3563 * @cpu: the cpu to run on
3564 * @fn: the function to run
3565 * @arg: the function arg
3567 * This will return the value @fn returns.
3568 * It is up to the caller to ensure that the cpu doesn't go offline.
3569 * The caller must not hold any locks which would prevent @fn from completing.
3571 long work_on_cpu(unsigned int cpu, long (*fn)(void *), void *arg)
3573 struct work_for_cpu wfc = { .fn = fn, .arg = arg };
3575 INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
3576 schedule_work_on(cpu, &wfc.work);
3577 flush_work(&wfc.work);
3580 EXPORT_SYMBOL_GPL(work_on_cpu);
3581 #endif /* CONFIG_SMP */
3583 #ifdef CONFIG_FREEZER
3586 * freeze_workqueues_begin - begin freezing workqueues
3588 * Start freezing workqueues. After this function returns, all freezable
3589 * workqueues will queue new works to their frozen_works list instead of
3593 * Grabs and releases workqueue_lock and pool->lock's.
3595 void freeze_workqueues_begin(void)
3597 struct worker_pool *pool;
3600 spin_lock_irq(&workqueue_lock);
3602 WARN_ON_ONCE(workqueue_freezing);
3603 workqueue_freezing = true;
3605 for_each_pool(pool, id) {
3606 struct workqueue_struct *wq;
3608 spin_lock(&pool->lock);
3610 WARN_ON_ONCE(pool->flags & POOL_FREEZING);
3611 pool->flags |= POOL_FREEZING;
3613 list_for_each_entry(wq, &workqueues, list) {
3614 struct pool_workqueue *pwq = get_pwq(pool->cpu, wq);
3616 if (pwq && pwq->pool == pool &&
3617 (wq->flags & WQ_FREEZABLE))
3618 pwq->max_active = 0;
3621 spin_unlock(&pool->lock);
3624 spin_unlock_irq(&workqueue_lock);
3628 * freeze_workqueues_busy - are freezable workqueues still busy?
3630 * Check whether freezing is complete. This function must be called
3631 * between freeze_workqueues_begin() and thaw_workqueues().
3634 * Grabs and releases workqueue_lock.
3637 * %true if some freezable workqueues are still busy. %false if freezing
3640 bool freeze_workqueues_busy(void)
3645 spin_lock_irq(&workqueue_lock);
3647 WARN_ON_ONCE(!workqueue_freezing);
3649 for_each_wq_cpu(cpu) {
3650 struct workqueue_struct *wq;
3652 * nr_active is monotonically decreasing. It's safe
3653 * to peek without lock.
3655 list_for_each_entry(wq, &workqueues, list) {
3656 struct pool_workqueue *pwq = get_pwq(cpu, wq);
3658 if (!pwq || !(wq->flags & WQ_FREEZABLE))
3661 WARN_ON_ONCE(pwq->nr_active < 0);
3662 if (pwq->nr_active) {
3669 spin_unlock_irq(&workqueue_lock);
3674 * thaw_workqueues - thaw workqueues
3676 * Thaw workqueues. Normal queueing is restored and all collected
3677 * frozen works are transferred to their respective pool worklists.
3680 * Grabs and releases workqueue_lock and pool->lock's.
3682 void thaw_workqueues(void)
3686 spin_lock_irq(&workqueue_lock);
3688 if (!workqueue_freezing)
3691 for_each_wq_cpu(cpu) {
3692 struct worker_pool *pool;
3693 struct workqueue_struct *wq;
3695 for_each_std_worker_pool(pool, cpu) {
3696 spin_lock(&pool->lock);
3698 WARN_ON_ONCE(!(pool->flags & POOL_FREEZING));
3699 pool->flags &= ~POOL_FREEZING;
3701 list_for_each_entry(wq, &workqueues, list) {
3702 struct pool_workqueue *pwq = get_pwq(cpu, wq);
3704 if (!pwq || pwq->pool != pool ||
3705 !(wq->flags & WQ_FREEZABLE))
3708 /* restore max_active and repopulate worklist */
3709 pwq_set_max_active(pwq, wq->saved_max_active);
3712 wake_up_worker(pool);
3714 spin_unlock(&pool->lock);
3718 workqueue_freezing = false;
3720 spin_unlock_irq(&workqueue_lock);
3722 #endif /* CONFIG_FREEZER */
3724 static int __init init_workqueues(void)
3728 /* make sure we have enough bits for OFFQ pool ID */
3729 BUILD_BUG_ON((1LU << (BITS_PER_LONG - WORK_OFFQ_POOL_SHIFT)) <
3730 WORK_CPU_END * NR_STD_WORKER_POOLS);
3732 WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
3734 pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
3736 cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
3737 hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
3739 /* initialize CPU pools */
3740 for_each_wq_cpu(cpu) {
3741 struct worker_pool *pool;
3743 for_each_std_worker_pool(pool, cpu) {
3744 spin_lock_init(&pool->lock);
3746 pool->flags |= POOL_DISASSOCIATED;
3747 INIT_LIST_HEAD(&pool->worklist);
3748 INIT_LIST_HEAD(&pool->idle_list);
3749 hash_init(pool->busy_hash);
3751 init_timer_deferrable(&pool->idle_timer);
3752 pool->idle_timer.function = idle_worker_timeout;
3753 pool->idle_timer.data = (unsigned long)pool;
3755 setup_timer(&pool->mayday_timer, pool_mayday_timeout,
3756 (unsigned long)pool);
3758 mutex_init(&pool->assoc_mutex);
3759 ida_init(&pool->worker_ida);
3762 BUG_ON(worker_pool_assign_id(pool));
3766 /* create the initial worker */
3767 for_each_online_wq_cpu(cpu) {
3768 struct worker_pool *pool;
3770 for_each_std_worker_pool(pool, cpu) {
3771 struct worker *worker;
3773 if (cpu != WORK_CPU_UNBOUND)
3774 pool->flags &= ~POOL_DISASSOCIATED;
3776 worker = create_worker(pool);
3778 spin_lock_irq(&pool->lock);
3779 start_worker(worker);
3780 spin_unlock_irq(&pool->lock);
3784 system_wq = alloc_workqueue("events", 0, 0);
3785 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
3786 system_long_wq = alloc_workqueue("events_long", 0, 0);
3787 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
3788 WQ_UNBOUND_MAX_ACTIVE);
3789 system_freezable_wq = alloc_workqueue("events_freezable",
3791 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
3792 !system_unbound_wq || !system_freezable_wq);
3795 early_initcall(init_workqueues);