2 * kernel/workqueue.c - generic async execution with shared worker pool
4 * Copyright (C) 2002 Ingo Molnar
6 * Derived from the taskqueue/keventd code by:
7 * David Woodhouse <dwmw2@infradead.org>
9 * Kai Petzke <wpp@marie.physik.tu-berlin.de>
10 * Theodore Ts'o <tytso@mit.edu>
12 * Made to use alloc_percpu by Christoph Lameter.
14 * Copyright (C) 2010 SUSE Linux Products GmbH
15 * Copyright (C) 2010 Tejun Heo <tj@kernel.org>
17 * This is the generic async execution mechanism. Work items as are
18 * executed in process context. The worker pool is shared and
19 * automatically managed. There is one worker pool for each CPU and
20 * one extra for works which are better served by workers which are
21 * not bound to any specific CPU.
23 * Please read Documentation/workqueue.txt for details.
26 #include <linux/export.h>
27 #include <linux/kernel.h>
28 #include <linux/sched.h>
29 #include <linux/init.h>
30 #include <linux/signal.h>
31 #include <linux/completion.h>
32 #include <linux/workqueue.h>
33 #include <linux/slab.h>
34 #include <linux/cpu.h>
35 #include <linux/notifier.h>
36 #include <linux/kthread.h>
37 #include <linux/hardirq.h>
38 #include <linux/mempolicy.h>
39 #include <linux/freezer.h>
40 #include <linux/kallsyms.h>
41 #include <linux/debug_locks.h>
42 #include <linux/lockdep.h>
43 #include <linux/idr.h>
45 #include "workqueue_sched.h"
51 * A bound gcwq is either associated or disassociated with its CPU.
52 * While associated (!DISASSOCIATED), all workers are bound to the
53 * CPU and none has %WORKER_UNBOUND set and concurrency management
56 * While DISASSOCIATED, the cpu may be offline and all workers have
57 * %WORKER_UNBOUND set and concurrency management disabled, and may
58 * be executing on any CPU. The gcwq behaves as an unbound one.
60 * Note that DISASSOCIATED can be flipped only while holding
61 * managership of all pools on the gcwq to avoid changing binding
62 * state while create_worker() is in progress.
64 GCWQ_DISASSOCIATED = 1 << 0, /* cpu can't serve workers */
65 GCWQ_FREEZING = 1 << 1, /* freeze in progress */
68 POOL_MANAGE_WORKERS = 1 << 0, /* need to manage workers */
69 POOL_MANAGING_WORKERS = 1 << 1, /* managing workers */
72 WORKER_STARTED = 1 << 0, /* started */
73 WORKER_DIE = 1 << 1, /* die die die */
74 WORKER_IDLE = 1 << 2, /* is idle */
75 WORKER_PREP = 1 << 3, /* preparing to run works */
76 WORKER_REBIND = 1 << 5, /* mom is home, come back */
77 WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
78 WORKER_UNBOUND = 1 << 7, /* worker is unbound */
80 WORKER_NOT_RUNNING = WORKER_PREP | WORKER_REBIND | WORKER_UNBOUND |
83 NR_WORKER_POOLS = 2, /* # worker pools per gcwq */
85 BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
86 BUSY_WORKER_HASH_SIZE = 1 << BUSY_WORKER_HASH_ORDER,
87 BUSY_WORKER_HASH_MASK = BUSY_WORKER_HASH_SIZE - 1,
89 MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
90 IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
92 MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
93 /* call for help after 10ms
95 MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
96 CREATE_COOLDOWN = HZ, /* time to breath after fail */
99 * Rescue workers are used only on emergencies and shared by
100 * all cpus. Give -20.
102 RESCUER_NICE_LEVEL = -20,
103 HIGHPRI_NICE_LEVEL = -20,
107 * Structure fields follow one of the following exclusion rules.
109 * I: Modifiable by initialization/destruction paths and read-only for
112 * P: Preemption protected. Disabling preemption is enough and should
113 * only be modified and accessed from the local cpu.
115 * L: gcwq->lock protected. Access with gcwq->lock held.
117 * X: During normal operation, modification requires gcwq->lock and
118 * should be done only from local cpu. Either disabling preemption
119 * on local cpu or grabbing gcwq->lock is enough for read access.
120 * If GCWQ_DISASSOCIATED is set, it's identical to L.
122 * F: wq->flush_mutex protected.
124 * W: workqueue_lock protected.
132 * The poor guys doing the actual heavy lifting. All on-duty workers
133 * are either serving the manager role, on idle list or on busy hash.
136 /* on idle list while idle, on busy hash table while busy */
138 struct list_head entry; /* L: while idle */
139 struct hlist_node hentry; /* L: while busy */
142 struct work_struct *current_work; /* L: work being processed */
143 struct cpu_workqueue_struct *current_cwq; /* L: current_work's cwq */
144 struct list_head scheduled; /* L: scheduled works */
145 struct task_struct *task; /* I: worker task */
146 struct worker_pool *pool; /* I: the associated pool */
147 /* 64 bytes boundary on 64bit, 32 on 32bit */
148 unsigned long last_active; /* L: last active timestamp */
149 unsigned int flags; /* X: flags */
150 int id; /* I: worker id */
152 /* for rebinding worker to CPU */
153 struct idle_rebind *idle_rebind; /* L: for idle worker */
154 struct work_struct rebind_work; /* L: for busy worker */
158 struct global_cwq *gcwq; /* I: the owning gcwq */
159 unsigned int flags; /* X: flags */
161 struct list_head worklist; /* L: list of pending works */
162 int nr_workers; /* L: total number of workers */
163 int nr_idle; /* L: currently idle ones */
165 struct list_head idle_list; /* X: list of idle workers */
166 struct timer_list idle_timer; /* L: worker idle timeout */
167 struct timer_list mayday_timer; /* L: SOS timer for workers */
169 struct mutex manager_mutex; /* mutex manager should hold */
170 struct ida worker_ida; /* L: for worker IDs */
174 * Global per-cpu workqueue. There's one and only one for each cpu
175 * and all works are queued and processed here regardless of their
179 spinlock_t lock; /* the gcwq lock */
180 unsigned int cpu; /* I: the associated cpu */
181 unsigned int flags; /* L: GCWQ_* flags */
183 /* workers are chained either in busy_hash or pool idle_list */
184 struct hlist_head busy_hash[BUSY_WORKER_HASH_SIZE];
185 /* L: hash of busy workers */
187 struct worker_pool pools[NR_WORKER_POOLS];
188 /* normal and highpri pools */
190 wait_queue_head_t rebind_hold; /* rebind hold wait */
191 } ____cacheline_aligned_in_smp;
194 * The per-CPU workqueue. The lower WORK_STRUCT_FLAG_BITS of
195 * work_struct->data are used for flags and thus cwqs need to be
196 * aligned at two's power of the number of flag bits.
198 struct cpu_workqueue_struct {
199 struct worker_pool *pool; /* I: the associated pool */
200 struct workqueue_struct *wq; /* I: the owning workqueue */
201 int work_color; /* L: current color */
202 int flush_color; /* L: flushing color */
203 int nr_in_flight[WORK_NR_COLORS];
204 /* L: nr of in_flight works */
205 int nr_active; /* L: nr of active works */
206 int max_active; /* L: max active works */
207 struct list_head delayed_works; /* L: delayed works */
211 * Structure used to wait for workqueue flush.
214 struct list_head list; /* F: list of flushers */
215 int flush_color; /* F: flush color waiting for */
216 struct completion done; /* flush completion */
220 * All cpumasks are assumed to be always set on UP and thus can't be
221 * used to determine whether there's something to be done.
224 typedef cpumask_var_t mayday_mask_t;
225 #define mayday_test_and_set_cpu(cpu, mask) \
226 cpumask_test_and_set_cpu((cpu), (mask))
227 #define mayday_clear_cpu(cpu, mask) cpumask_clear_cpu((cpu), (mask))
228 #define for_each_mayday_cpu(cpu, mask) for_each_cpu((cpu), (mask))
229 #define alloc_mayday_mask(maskp, gfp) zalloc_cpumask_var((maskp), (gfp))
230 #define free_mayday_mask(mask) free_cpumask_var((mask))
232 typedef unsigned long mayday_mask_t;
233 #define mayday_test_and_set_cpu(cpu, mask) test_and_set_bit(0, &(mask))
234 #define mayday_clear_cpu(cpu, mask) clear_bit(0, &(mask))
235 #define for_each_mayday_cpu(cpu, mask) if ((cpu) = 0, (mask))
236 #define alloc_mayday_mask(maskp, gfp) true
237 #define free_mayday_mask(mask) do { } while (0)
241 * The externally visible workqueue abstraction is an array of
242 * per-CPU workqueues:
244 struct workqueue_struct {
245 unsigned int flags; /* W: WQ_* flags */
247 struct cpu_workqueue_struct __percpu *pcpu;
248 struct cpu_workqueue_struct *single;
250 } cpu_wq; /* I: cwq's */
251 struct list_head list; /* W: list of all workqueues */
253 struct mutex flush_mutex; /* protects wq flushing */
254 int work_color; /* F: current work color */
255 int flush_color; /* F: current flush color */
256 atomic_t nr_cwqs_to_flush; /* flush in progress */
257 struct wq_flusher *first_flusher; /* F: first flusher */
258 struct list_head flusher_queue; /* F: flush waiters */
259 struct list_head flusher_overflow; /* F: flush overflow list */
261 mayday_mask_t mayday_mask; /* cpus requesting rescue */
262 struct worker *rescuer; /* I: rescue worker */
264 int nr_drainers; /* W: drain in progress */
265 int saved_max_active; /* W: saved cwq max_active */
266 #ifdef CONFIG_LOCKDEP
267 struct lockdep_map lockdep_map;
269 char name[]; /* I: workqueue name */
272 struct workqueue_struct *system_wq __read_mostly;
273 EXPORT_SYMBOL_GPL(system_wq);
274 struct workqueue_struct *system_highpri_wq __read_mostly;
275 EXPORT_SYMBOL_GPL(system_highpri_wq);
276 struct workqueue_struct *system_long_wq __read_mostly;
277 EXPORT_SYMBOL_GPL(system_long_wq);
278 struct workqueue_struct *system_unbound_wq __read_mostly;
279 EXPORT_SYMBOL_GPL(system_unbound_wq);
280 struct workqueue_struct *system_freezable_wq __read_mostly;
281 EXPORT_SYMBOL_GPL(system_freezable_wq);
283 #define CREATE_TRACE_POINTS
284 #include <trace/events/workqueue.h>
286 #define for_each_worker_pool(pool, gcwq) \
287 for ((pool) = &(gcwq)->pools[0]; \
288 (pool) < &(gcwq)->pools[NR_WORKER_POOLS]; (pool)++)
290 #define for_each_busy_worker(worker, i, pos, gcwq) \
291 for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++) \
292 hlist_for_each_entry(worker, pos, &gcwq->busy_hash[i], hentry)
294 static inline int __next_gcwq_cpu(int cpu, const struct cpumask *mask,
297 if (cpu < nr_cpu_ids) {
299 cpu = cpumask_next(cpu, mask);
300 if (cpu < nr_cpu_ids)
304 return WORK_CPU_UNBOUND;
306 return WORK_CPU_NONE;
309 static inline int __next_wq_cpu(int cpu, const struct cpumask *mask,
310 struct workqueue_struct *wq)
312 return __next_gcwq_cpu(cpu, mask, !(wq->flags & WQ_UNBOUND) ? 1 : 2);
318 * An extra gcwq is defined for an invalid cpu number
319 * (WORK_CPU_UNBOUND) to host workqueues which are not bound to any
320 * specific CPU. The following iterators are similar to
321 * for_each_*_cpu() iterators but also considers the unbound gcwq.
323 * for_each_gcwq_cpu() : possible CPUs + WORK_CPU_UNBOUND
324 * for_each_online_gcwq_cpu() : online CPUs + WORK_CPU_UNBOUND
325 * for_each_cwq_cpu() : possible CPUs for bound workqueues,
326 * WORK_CPU_UNBOUND for unbound workqueues
328 #define for_each_gcwq_cpu(cpu) \
329 for ((cpu) = __next_gcwq_cpu(-1, cpu_possible_mask, 3); \
330 (cpu) < WORK_CPU_NONE; \
331 (cpu) = __next_gcwq_cpu((cpu), cpu_possible_mask, 3))
333 #define for_each_online_gcwq_cpu(cpu) \
334 for ((cpu) = __next_gcwq_cpu(-1, cpu_online_mask, 3); \
335 (cpu) < WORK_CPU_NONE; \
336 (cpu) = __next_gcwq_cpu((cpu), cpu_online_mask, 3))
338 #define for_each_cwq_cpu(cpu, wq) \
339 for ((cpu) = __next_wq_cpu(-1, cpu_possible_mask, (wq)); \
340 (cpu) < WORK_CPU_NONE; \
341 (cpu) = __next_wq_cpu((cpu), cpu_possible_mask, (wq)))
343 #ifdef CONFIG_DEBUG_OBJECTS_WORK
345 static struct debug_obj_descr work_debug_descr;
347 static void *work_debug_hint(void *addr)
349 return ((struct work_struct *) addr)->func;
353 * fixup_init is called when:
354 * - an active object is initialized
356 static int work_fixup_init(void *addr, enum debug_obj_state state)
358 struct work_struct *work = addr;
361 case ODEBUG_STATE_ACTIVE:
362 cancel_work_sync(work);
363 debug_object_init(work, &work_debug_descr);
371 * fixup_activate is called when:
372 * - an active object is activated
373 * - an unknown object is activated (might be a statically initialized object)
375 static int work_fixup_activate(void *addr, enum debug_obj_state state)
377 struct work_struct *work = addr;
381 case ODEBUG_STATE_NOTAVAILABLE:
383 * This is not really a fixup. The work struct was
384 * statically initialized. We just make sure that it
385 * is tracked in the object tracker.
387 if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
388 debug_object_init(work, &work_debug_descr);
389 debug_object_activate(work, &work_debug_descr);
395 case ODEBUG_STATE_ACTIVE:
404 * fixup_free is called when:
405 * - an active object is freed
407 static int work_fixup_free(void *addr, enum debug_obj_state state)
409 struct work_struct *work = addr;
412 case ODEBUG_STATE_ACTIVE:
413 cancel_work_sync(work);
414 debug_object_free(work, &work_debug_descr);
421 static struct debug_obj_descr work_debug_descr = {
422 .name = "work_struct",
423 .debug_hint = work_debug_hint,
424 .fixup_init = work_fixup_init,
425 .fixup_activate = work_fixup_activate,
426 .fixup_free = work_fixup_free,
429 static inline void debug_work_activate(struct work_struct *work)
431 debug_object_activate(work, &work_debug_descr);
434 static inline void debug_work_deactivate(struct work_struct *work)
436 debug_object_deactivate(work, &work_debug_descr);
439 void __init_work(struct work_struct *work, int onstack)
442 debug_object_init_on_stack(work, &work_debug_descr);
444 debug_object_init(work, &work_debug_descr);
446 EXPORT_SYMBOL_GPL(__init_work);
448 void destroy_work_on_stack(struct work_struct *work)
450 debug_object_free(work, &work_debug_descr);
452 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
455 static inline void debug_work_activate(struct work_struct *work) { }
456 static inline void debug_work_deactivate(struct work_struct *work) { }
459 /* Serializes the accesses to the list of workqueues. */
460 static DEFINE_SPINLOCK(workqueue_lock);
461 static LIST_HEAD(workqueues);
462 static bool workqueue_freezing; /* W: have wqs started freezing? */
465 * The almighty global cpu workqueues. nr_running is the only field
466 * which is expected to be used frequently by other cpus via
467 * try_to_wake_up(). Put it in a separate cacheline.
469 static DEFINE_PER_CPU(struct global_cwq, global_cwq);
470 static DEFINE_PER_CPU_SHARED_ALIGNED(atomic_t, pool_nr_running[NR_WORKER_POOLS]);
473 * Global cpu workqueue and nr_running counter for unbound gcwq. The
474 * gcwq is always online, has GCWQ_DISASSOCIATED set, and all its
475 * workers have WORKER_UNBOUND set.
477 static struct global_cwq unbound_global_cwq;
478 static atomic_t unbound_pool_nr_running[NR_WORKER_POOLS] = {
479 [0 ... NR_WORKER_POOLS - 1] = ATOMIC_INIT(0), /* always 0 */
482 static int worker_thread(void *__worker);
484 static int worker_pool_pri(struct worker_pool *pool)
486 return pool - pool->gcwq->pools;
489 static struct global_cwq *get_gcwq(unsigned int cpu)
491 if (cpu != WORK_CPU_UNBOUND)
492 return &per_cpu(global_cwq, cpu);
494 return &unbound_global_cwq;
497 static atomic_t *get_pool_nr_running(struct worker_pool *pool)
499 int cpu = pool->gcwq->cpu;
500 int idx = worker_pool_pri(pool);
502 if (cpu != WORK_CPU_UNBOUND)
503 return &per_cpu(pool_nr_running, cpu)[idx];
505 return &unbound_pool_nr_running[idx];
508 static struct cpu_workqueue_struct *get_cwq(unsigned int cpu,
509 struct workqueue_struct *wq)
511 if (!(wq->flags & WQ_UNBOUND)) {
512 if (likely(cpu < nr_cpu_ids))
513 return per_cpu_ptr(wq->cpu_wq.pcpu, cpu);
514 } else if (likely(cpu == WORK_CPU_UNBOUND))
515 return wq->cpu_wq.single;
519 static unsigned int work_color_to_flags(int color)
521 return color << WORK_STRUCT_COLOR_SHIFT;
524 static int get_work_color(struct work_struct *work)
526 return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
527 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
530 static int work_next_color(int color)
532 return (color + 1) % WORK_NR_COLORS;
536 * While queued, %WORK_STRUCT_CWQ is set and non flag bits of a work's data
537 * contain the pointer to the queued cwq. Once execution starts, the flag
538 * is cleared and the high bits contain OFFQ flags and CPU number.
540 * set_work_cwq(), set_work_cpu_and_clear_pending(), mark_work_canceling()
541 * and clear_work_data() can be used to set the cwq, cpu or clear
542 * work->data. These functions should only be called while the work is
543 * owned - ie. while the PENDING bit is set.
545 * get_work_[g]cwq() can be used to obtain the gcwq or cwq corresponding to
546 * a work. gcwq is available once the work has been queued anywhere after
547 * initialization until it is sync canceled. cwq is available only while
548 * the work item is queued.
550 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
551 * canceled. While being canceled, a work item may have its PENDING set
552 * but stay off timer and worklist for arbitrarily long and nobody should
553 * try to steal the PENDING bit.
555 static inline void set_work_data(struct work_struct *work, unsigned long data,
558 BUG_ON(!work_pending(work));
559 atomic_long_set(&work->data, data | flags | work_static(work));
562 static void set_work_cwq(struct work_struct *work,
563 struct cpu_workqueue_struct *cwq,
564 unsigned long extra_flags)
566 set_work_data(work, (unsigned long)cwq,
567 WORK_STRUCT_PENDING | WORK_STRUCT_CWQ | extra_flags);
570 static void set_work_cpu_and_clear_pending(struct work_struct *work,
574 * The following wmb is paired with the implied mb in
575 * test_and_set_bit(PENDING) and ensures all updates to @work made
576 * here are visible to and precede any updates by the next PENDING
580 set_work_data(work, (unsigned long)cpu << WORK_OFFQ_CPU_SHIFT, 0);
583 static void clear_work_data(struct work_struct *work)
585 smp_wmb(); /* see set_work_cpu_and_clear_pending() */
586 set_work_data(work, WORK_STRUCT_NO_CPU, 0);
589 static struct cpu_workqueue_struct *get_work_cwq(struct work_struct *work)
591 unsigned long data = atomic_long_read(&work->data);
593 if (data & WORK_STRUCT_CWQ)
594 return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
599 static struct global_cwq *get_work_gcwq(struct work_struct *work)
601 unsigned long data = atomic_long_read(&work->data);
604 if (data & WORK_STRUCT_CWQ)
605 return ((struct cpu_workqueue_struct *)
606 (data & WORK_STRUCT_WQ_DATA_MASK))->pool->gcwq;
608 cpu = data >> WORK_OFFQ_CPU_SHIFT;
609 if (cpu == WORK_CPU_NONE)
612 BUG_ON(cpu >= nr_cpu_ids && cpu != WORK_CPU_UNBOUND);
613 return get_gcwq(cpu);
616 static void mark_work_canceling(struct work_struct *work)
618 struct global_cwq *gcwq = get_work_gcwq(work);
619 unsigned long cpu = gcwq ? gcwq->cpu : WORK_CPU_NONE;
621 set_work_data(work, (cpu << WORK_OFFQ_CPU_SHIFT) | WORK_OFFQ_CANCELING,
622 WORK_STRUCT_PENDING);
625 static bool work_is_canceling(struct work_struct *work)
627 unsigned long data = atomic_long_read(&work->data);
629 return !(data & WORK_STRUCT_CWQ) && (data & WORK_OFFQ_CANCELING);
633 * Policy functions. These define the policies on how the global worker
634 * pools are managed. Unless noted otherwise, these functions assume that
635 * they're being called with gcwq->lock held.
638 static bool __need_more_worker(struct worker_pool *pool)
640 return !atomic_read(get_pool_nr_running(pool));
644 * Need to wake up a worker? Called from anything but currently
647 * Note that, because unbound workers never contribute to nr_running, this
648 * function will always return %true for unbound gcwq as long as the
649 * worklist isn't empty.
651 static bool need_more_worker(struct worker_pool *pool)
653 return !list_empty(&pool->worklist) && __need_more_worker(pool);
656 /* Can I start working? Called from busy but !running workers. */
657 static bool may_start_working(struct worker_pool *pool)
659 return pool->nr_idle;
662 /* Do I need to keep working? Called from currently running workers. */
663 static bool keep_working(struct worker_pool *pool)
665 atomic_t *nr_running = get_pool_nr_running(pool);
667 return !list_empty(&pool->worklist) && atomic_read(nr_running) <= 1;
670 /* Do we need a new worker? Called from manager. */
671 static bool need_to_create_worker(struct worker_pool *pool)
673 return need_more_worker(pool) && !may_start_working(pool);
676 /* Do I need to be the manager? */
677 static bool need_to_manage_workers(struct worker_pool *pool)
679 return need_to_create_worker(pool) ||
680 (pool->flags & POOL_MANAGE_WORKERS);
683 /* Do we have too many workers and should some go away? */
684 static bool too_many_workers(struct worker_pool *pool)
686 bool managing = pool->flags & POOL_MANAGING_WORKERS;
687 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
688 int nr_busy = pool->nr_workers - nr_idle;
690 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
697 /* Return the first worker. Safe with preemption disabled */
698 static struct worker *first_worker(struct worker_pool *pool)
700 if (unlikely(list_empty(&pool->idle_list)))
703 return list_first_entry(&pool->idle_list, struct worker, entry);
707 * wake_up_worker - wake up an idle worker
708 * @pool: worker pool to wake worker from
710 * Wake up the first idle worker of @pool.
713 * spin_lock_irq(gcwq->lock).
715 static void wake_up_worker(struct worker_pool *pool)
717 struct worker *worker = first_worker(pool);
720 wake_up_process(worker->task);
724 * wq_worker_waking_up - a worker is waking up
725 * @task: task waking up
726 * @cpu: CPU @task is waking up to
728 * This function is called during try_to_wake_up() when a worker is
732 * spin_lock_irq(rq->lock)
734 void wq_worker_waking_up(struct task_struct *task, unsigned int cpu)
736 struct worker *worker = kthread_data(task);
738 if (!(worker->flags & WORKER_NOT_RUNNING))
739 atomic_inc(get_pool_nr_running(worker->pool));
743 * wq_worker_sleeping - a worker is going to sleep
744 * @task: task going to sleep
745 * @cpu: CPU in question, must be the current CPU number
747 * This function is called during schedule() when a busy worker is
748 * going to sleep. Worker on the same cpu can be woken up by
749 * returning pointer to its task.
752 * spin_lock_irq(rq->lock)
755 * Worker task on @cpu to wake up, %NULL if none.
757 struct task_struct *wq_worker_sleeping(struct task_struct *task,
760 struct worker *worker = kthread_data(task), *to_wakeup = NULL;
761 struct worker_pool *pool = worker->pool;
762 atomic_t *nr_running = get_pool_nr_running(pool);
764 if (worker->flags & WORKER_NOT_RUNNING)
767 /* this can only happen on the local cpu */
768 BUG_ON(cpu != raw_smp_processor_id());
771 * The counterpart of the following dec_and_test, implied mb,
772 * worklist not empty test sequence is in insert_work().
773 * Please read comment there.
775 * NOT_RUNNING is clear. This means that we're bound to and
776 * running on the local cpu w/ rq lock held and preemption
777 * disabled, which in turn means that none else could be
778 * manipulating idle_list, so dereferencing idle_list without gcwq
781 if (atomic_dec_and_test(nr_running) && !list_empty(&pool->worklist))
782 to_wakeup = first_worker(pool);
783 return to_wakeup ? to_wakeup->task : NULL;
787 * worker_set_flags - set worker flags and adjust nr_running accordingly
789 * @flags: flags to set
790 * @wakeup: wakeup an idle worker if necessary
792 * Set @flags in @worker->flags and adjust nr_running accordingly. If
793 * nr_running becomes zero and @wakeup is %true, an idle worker is
797 * spin_lock_irq(gcwq->lock)
799 static inline void worker_set_flags(struct worker *worker, unsigned int flags,
802 struct worker_pool *pool = worker->pool;
804 WARN_ON_ONCE(worker->task != current);
807 * If transitioning into NOT_RUNNING, adjust nr_running and
808 * wake up an idle worker as necessary if requested by
811 if ((flags & WORKER_NOT_RUNNING) &&
812 !(worker->flags & WORKER_NOT_RUNNING)) {
813 atomic_t *nr_running = get_pool_nr_running(pool);
816 if (atomic_dec_and_test(nr_running) &&
817 !list_empty(&pool->worklist))
818 wake_up_worker(pool);
820 atomic_dec(nr_running);
823 worker->flags |= flags;
827 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
829 * @flags: flags to clear
831 * Clear @flags in @worker->flags and adjust nr_running accordingly.
834 * spin_lock_irq(gcwq->lock)
836 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
838 struct worker_pool *pool = worker->pool;
839 unsigned int oflags = worker->flags;
841 WARN_ON_ONCE(worker->task != current);
843 worker->flags &= ~flags;
846 * If transitioning out of NOT_RUNNING, increment nr_running. Note
847 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
848 * of multiple flags, not a single flag.
850 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
851 if (!(worker->flags & WORKER_NOT_RUNNING))
852 atomic_inc(get_pool_nr_running(pool));
856 * busy_worker_head - return the busy hash head for a work
857 * @gcwq: gcwq of interest
858 * @work: work to be hashed
860 * Return hash head of @gcwq for @work.
863 * spin_lock_irq(gcwq->lock).
866 * Pointer to the hash head.
868 static struct hlist_head *busy_worker_head(struct global_cwq *gcwq,
869 struct work_struct *work)
871 const int base_shift = ilog2(sizeof(struct work_struct));
872 unsigned long v = (unsigned long)work;
874 /* simple shift and fold hash, do we need something better? */
876 v += v >> BUSY_WORKER_HASH_ORDER;
877 v &= BUSY_WORKER_HASH_MASK;
879 return &gcwq->busy_hash[v];
883 * __find_worker_executing_work - find worker which is executing a work
884 * @gcwq: gcwq of interest
885 * @bwh: hash head as returned by busy_worker_head()
886 * @work: work to find worker for
888 * Find a worker which is executing @work on @gcwq. @bwh should be
889 * the hash head obtained by calling busy_worker_head() with the same
893 * spin_lock_irq(gcwq->lock).
896 * Pointer to worker which is executing @work if found, NULL
899 static struct worker *__find_worker_executing_work(struct global_cwq *gcwq,
900 struct hlist_head *bwh,
901 struct work_struct *work)
903 struct worker *worker;
904 struct hlist_node *tmp;
906 hlist_for_each_entry(worker, tmp, bwh, hentry)
907 if (worker->current_work == work)
913 * find_worker_executing_work - find worker which is executing a work
914 * @gcwq: gcwq of interest
915 * @work: work to find worker for
917 * Find a worker which is executing @work on @gcwq. This function is
918 * identical to __find_worker_executing_work() except that this
919 * function calculates @bwh itself.
922 * spin_lock_irq(gcwq->lock).
925 * Pointer to worker which is executing @work if found, NULL
928 static struct worker *find_worker_executing_work(struct global_cwq *gcwq,
929 struct work_struct *work)
931 return __find_worker_executing_work(gcwq, busy_worker_head(gcwq, work),
936 * move_linked_works - move linked works to a list
937 * @work: start of series of works to be scheduled
938 * @head: target list to append @work to
939 * @nextp: out paramter for nested worklist walking
941 * Schedule linked works starting from @work to @head. Work series to
942 * be scheduled starts at @work and includes any consecutive work with
943 * WORK_STRUCT_LINKED set in its predecessor.
945 * If @nextp is not NULL, it's updated to point to the next work of
946 * the last scheduled work. This allows move_linked_works() to be
947 * nested inside outer list_for_each_entry_safe().
950 * spin_lock_irq(gcwq->lock).
952 static void move_linked_works(struct work_struct *work, struct list_head *head,
953 struct work_struct **nextp)
955 struct work_struct *n;
958 * Linked worklist will always end before the end of the list,
959 * use NULL for list head.
961 list_for_each_entry_safe_from(work, n, NULL, entry) {
962 list_move_tail(&work->entry, head);
963 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
968 * If we're already inside safe list traversal and have moved
969 * multiple works to the scheduled queue, the next position
970 * needs to be updated.
976 static void cwq_activate_first_delayed(struct cpu_workqueue_struct *cwq)
978 struct work_struct *work = list_first_entry(&cwq->delayed_works,
979 struct work_struct, entry);
981 trace_workqueue_activate_work(work);
982 move_linked_works(work, &cwq->pool->worklist, NULL);
983 __clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
988 * cwq_dec_nr_in_flight - decrement cwq's nr_in_flight
989 * @cwq: cwq of interest
990 * @color: color of work which left the queue
991 * @delayed: for a delayed work
993 * A work either has completed or is removed from pending queue,
994 * decrement nr_in_flight of its cwq and handle workqueue flushing.
997 * spin_lock_irq(gcwq->lock).
999 static void cwq_dec_nr_in_flight(struct cpu_workqueue_struct *cwq, int color,
1002 /* ignore uncolored works */
1003 if (color == WORK_NO_COLOR)
1006 cwq->nr_in_flight[color]--;
1010 if (!list_empty(&cwq->delayed_works)) {
1011 /* one down, submit a delayed one */
1012 if (cwq->nr_active < cwq->max_active)
1013 cwq_activate_first_delayed(cwq);
1017 /* is flush in progress and are we at the flushing tip? */
1018 if (likely(cwq->flush_color != color))
1021 /* are there still in-flight works? */
1022 if (cwq->nr_in_flight[color])
1025 /* this cwq is done, clear flush_color */
1026 cwq->flush_color = -1;
1029 * If this was the last cwq, wake up the first flusher. It
1030 * will handle the rest.
1032 if (atomic_dec_and_test(&cwq->wq->nr_cwqs_to_flush))
1033 complete(&cwq->wq->first_flusher->done);
1037 * try_to_grab_pending - steal work item from worklist and disable irq
1038 * @work: work item to steal
1039 * @is_dwork: @work is a delayed_work
1040 * @flags: place to store irq state
1042 * Try to grab PENDING bit of @work. This function can handle @work in any
1043 * stable state - idle, on timer or on worklist. Return values are
1045 * 1 if @work was pending and we successfully stole PENDING
1046 * 0 if @work was idle and we claimed PENDING
1047 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1048 * -ENOENT if someone else is canceling @work, this state may persist
1049 * for arbitrarily long
1051 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1052 * interrupted while holding PENDING and @work off queue, irq must be
1053 * disabled on entry. This, combined with delayed_work->timer being
1054 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1056 * On successful return, >= 0, irq is disabled and the caller is
1057 * responsible for releasing it using local_irq_restore(*@flags).
1059 * This function is safe to call from any context including IRQ handler.
1061 static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1062 unsigned long *flags)
1064 struct global_cwq *gcwq;
1066 WARN_ON_ONCE(in_irq());
1068 local_irq_save(*flags);
1070 /* try to steal the timer if it exists */
1072 struct delayed_work *dwork = to_delayed_work(work);
1075 * dwork->timer is irqsafe. If del_timer() fails, it's
1076 * guaranteed that the timer is not queued anywhere and not
1077 * running on the local CPU.
1079 if (likely(del_timer(&dwork->timer)))
1083 /* try to claim PENDING the normal way */
1084 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1088 * The queueing is in progress, or it is already queued. Try to
1089 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1091 gcwq = get_work_gcwq(work);
1095 spin_lock(&gcwq->lock);
1096 if (!list_empty(&work->entry)) {
1098 * This work is queued, but perhaps we locked the wrong gcwq.
1099 * In that case we must see the new value after rmb(), see
1100 * insert_work()->wmb().
1103 if (gcwq == get_work_gcwq(work)) {
1104 debug_work_deactivate(work);
1105 list_del_init(&work->entry);
1106 cwq_dec_nr_in_flight(get_work_cwq(work),
1107 get_work_color(work),
1108 *work_data_bits(work) & WORK_STRUCT_DELAYED);
1110 spin_unlock(&gcwq->lock);
1114 spin_unlock(&gcwq->lock);
1116 local_irq_restore(*flags);
1117 if (work_is_canceling(work))
1124 * insert_work - insert a work into gcwq
1125 * @cwq: cwq @work belongs to
1126 * @work: work to insert
1127 * @head: insertion point
1128 * @extra_flags: extra WORK_STRUCT_* flags to set
1130 * Insert @work which belongs to @cwq into @gcwq after @head.
1131 * @extra_flags is or'd to work_struct flags.
1134 * spin_lock_irq(gcwq->lock).
1136 static void insert_work(struct cpu_workqueue_struct *cwq,
1137 struct work_struct *work, struct list_head *head,
1138 unsigned int extra_flags)
1140 struct worker_pool *pool = cwq->pool;
1142 /* we own @work, set data and link */
1143 set_work_cwq(work, cwq, extra_flags);
1146 * Ensure that we get the right work->data if we see the
1147 * result of list_add() below, see try_to_grab_pending().
1151 list_add_tail(&work->entry, head);
1154 * Ensure either worker_sched_deactivated() sees the above
1155 * list_add_tail() or we see zero nr_running to avoid workers
1156 * lying around lazily while there are works to be processed.
1160 if (__need_more_worker(pool))
1161 wake_up_worker(pool);
1165 * Test whether @work is being queued from another work executing on the
1166 * same workqueue. This is rather expensive and should only be used from
1169 static bool is_chained_work(struct workqueue_struct *wq)
1171 unsigned long flags;
1174 for_each_gcwq_cpu(cpu) {
1175 struct global_cwq *gcwq = get_gcwq(cpu);
1176 struct worker *worker;
1177 struct hlist_node *pos;
1180 spin_lock_irqsave(&gcwq->lock, flags);
1181 for_each_busy_worker(worker, i, pos, gcwq) {
1182 if (worker->task != current)
1184 spin_unlock_irqrestore(&gcwq->lock, flags);
1186 * I'm @worker, no locking necessary. See if @work
1187 * is headed to the same workqueue.
1189 return worker->current_cwq->wq == wq;
1191 spin_unlock_irqrestore(&gcwq->lock, flags);
1196 static void __queue_work(unsigned int cpu, struct workqueue_struct *wq,
1197 struct work_struct *work)
1199 struct global_cwq *gcwq;
1200 struct cpu_workqueue_struct *cwq;
1201 struct list_head *worklist;
1202 unsigned int work_flags;
1203 unsigned int req_cpu = cpu;
1206 * While a work item is PENDING && off queue, a task trying to
1207 * steal the PENDING will busy-loop waiting for it to either get
1208 * queued or lose PENDING. Grabbing PENDING and queueing should
1209 * happen with IRQ disabled.
1211 WARN_ON_ONCE(!irqs_disabled());
1213 debug_work_activate(work);
1215 /* if dying, only works from the same workqueue are allowed */
1216 if (unlikely(wq->flags & WQ_DRAINING) &&
1217 WARN_ON_ONCE(!is_chained_work(wq)))
1220 /* determine gcwq to use */
1221 if (!(wq->flags & WQ_UNBOUND)) {
1222 struct global_cwq *last_gcwq;
1224 if (cpu == WORK_CPU_UNBOUND)
1225 cpu = raw_smp_processor_id();
1228 * It's multi cpu. If @work was previously on a different
1229 * cpu, it might still be running there, in which case the
1230 * work needs to be queued on that cpu to guarantee
1233 gcwq = get_gcwq(cpu);
1234 last_gcwq = get_work_gcwq(work);
1236 if (last_gcwq && last_gcwq != gcwq) {
1237 struct worker *worker;
1239 spin_lock(&last_gcwq->lock);
1241 worker = find_worker_executing_work(last_gcwq, work);
1243 if (worker && worker->current_cwq->wq == wq)
1246 /* meh... not running there, queue here */
1247 spin_unlock(&last_gcwq->lock);
1248 spin_lock(&gcwq->lock);
1251 spin_lock(&gcwq->lock);
1254 gcwq = get_gcwq(WORK_CPU_UNBOUND);
1255 spin_lock(&gcwq->lock);
1258 /* gcwq determined, get cwq and queue */
1259 cwq = get_cwq(gcwq->cpu, wq);
1260 trace_workqueue_queue_work(req_cpu, cwq, work);
1262 if (WARN_ON(!list_empty(&work->entry))) {
1263 spin_unlock(&gcwq->lock);
1267 cwq->nr_in_flight[cwq->work_color]++;
1268 work_flags = work_color_to_flags(cwq->work_color);
1270 if (likely(cwq->nr_active < cwq->max_active)) {
1271 trace_workqueue_activate_work(work);
1273 worklist = &cwq->pool->worklist;
1275 work_flags |= WORK_STRUCT_DELAYED;
1276 worklist = &cwq->delayed_works;
1279 insert_work(cwq, work, worklist, work_flags);
1281 spin_unlock(&gcwq->lock);
1285 * queue_work_on - queue work on specific cpu
1286 * @cpu: CPU number to execute work on
1287 * @wq: workqueue to use
1288 * @work: work to queue
1290 * Returns %false if @work was already on a queue, %true otherwise.
1292 * We queue the work to a specific CPU, the caller must ensure it
1295 bool queue_work_on(int cpu, struct workqueue_struct *wq,
1296 struct work_struct *work)
1299 unsigned long flags;
1301 local_irq_save(flags);
1303 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1304 __queue_work(cpu, wq, work);
1308 local_irq_restore(flags);
1311 EXPORT_SYMBOL_GPL(queue_work_on);
1314 * queue_work - queue work on a workqueue
1315 * @wq: workqueue to use
1316 * @work: work to queue
1318 * Returns %false if @work was already on a queue, %true otherwise.
1320 * We queue the work to the CPU on which it was submitted, but if the CPU dies
1321 * it can be processed by another CPU.
1323 bool queue_work(struct workqueue_struct *wq, struct work_struct *work)
1325 return queue_work_on(WORK_CPU_UNBOUND, wq, work);
1327 EXPORT_SYMBOL_GPL(queue_work);
1329 void delayed_work_timer_fn(unsigned long __data)
1331 struct delayed_work *dwork = (struct delayed_work *)__data;
1332 struct cpu_workqueue_struct *cwq = get_work_cwq(&dwork->work);
1334 /* should have been called from irqsafe timer with irq already off */
1335 __queue_work(dwork->cpu, cwq->wq, &dwork->work);
1337 EXPORT_SYMBOL_GPL(delayed_work_timer_fn);
1339 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
1340 struct delayed_work *dwork, unsigned long delay)
1342 struct timer_list *timer = &dwork->timer;
1343 struct work_struct *work = &dwork->work;
1346 WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
1347 timer->data != (unsigned long)dwork);
1348 BUG_ON(timer_pending(timer));
1349 BUG_ON(!list_empty(&work->entry));
1351 timer_stats_timer_set_start_info(&dwork->timer);
1354 * This stores cwq for the moment, for the timer_fn. Note that the
1355 * work's gcwq is preserved to allow reentrance detection for
1358 if (!(wq->flags & WQ_UNBOUND)) {
1359 struct global_cwq *gcwq = get_work_gcwq(work);
1362 * If we cannot get the last gcwq from @work directly,
1363 * select the last CPU such that it avoids unnecessarily
1364 * triggering non-reentrancy check in __queue_work().
1369 if (lcpu == WORK_CPU_UNBOUND)
1370 lcpu = raw_smp_processor_id();
1372 lcpu = WORK_CPU_UNBOUND;
1375 set_work_cwq(work, get_cwq(lcpu, wq), 0);
1378 timer->expires = jiffies + delay;
1380 if (unlikely(cpu != WORK_CPU_UNBOUND))
1381 add_timer_on(timer, cpu);
1387 * queue_delayed_work_on - queue work on specific CPU after delay
1388 * @cpu: CPU number to execute work on
1389 * @wq: workqueue to use
1390 * @dwork: work to queue
1391 * @delay: number of jiffies to wait before queueing
1393 * Returns %false if @work was already on a queue, %true otherwise. If
1394 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1397 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1398 struct delayed_work *dwork, unsigned long delay)
1400 struct work_struct *work = &dwork->work;
1402 unsigned long flags;
1405 return queue_work_on(cpu, wq, &dwork->work);
1407 /* read the comment in __queue_work() */
1408 local_irq_save(flags);
1410 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1411 __queue_delayed_work(cpu, wq, dwork, delay);
1415 local_irq_restore(flags);
1418 EXPORT_SYMBOL_GPL(queue_delayed_work_on);
1421 * queue_delayed_work - queue work on a workqueue after delay
1422 * @wq: workqueue to use
1423 * @dwork: delayable work to queue
1424 * @delay: number of jiffies to wait before queueing
1426 * Equivalent to queue_delayed_work_on() but tries to use the local CPU.
1428 bool queue_delayed_work(struct workqueue_struct *wq,
1429 struct delayed_work *dwork, unsigned long delay)
1431 return queue_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
1433 EXPORT_SYMBOL_GPL(queue_delayed_work);
1436 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1437 * @cpu: CPU number to execute work on
1438 * @wq: workqueue to use
1439 * @dwork: work to queue
1440 * @delay: number of jiffies to wait before queueing
1442 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1443 * modify @dwork's timer so that it expires after @delay. If @delay is
1444 * zero, @work is guaranteed to be scheduled immediately regardless of its
1447 * Returns %false if @dwork was idle and queued, %true if @dwork was
1448 * pending and its timer was modified.
1450 * This function is safe to call from any context including IRQ handler.
1451 * See try_to_grab_pending() for details.
1453 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
1454 struct delayed_work *dwork, unsigned long delay)
1456 unsigned long flags;
1460 ret = try_to_grab_pending(&dwork->work, true, &flags);
1461 } while (unlikely(ret == -EAGAIN));
1463 if (likely(ret >= 0)) {
1464 __queue_delayed_work(cpu, wq, dwork, delay);
1465 local_irq_restore(flags);
1468 /* -ENOENT from try_to_grab_pending() becomes %true */
1471 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
1474 * mod_delayed_work - modify delay of or queue a delayed work
1475 * @wq: workqueue to use
1476 * @dwork: work to queue
1477 * @delay: number of jiffies to wait before queueing
1479 * mod_delayed_work_on() on local CPU.
1481 bool mod_delayed_work(struct workqueue_struct *wq, struct delayed_work *dwork,
1482 unsigned long delay)
1484 return mod_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
1486 EXPORT_SYMBOL_GPL(mod_delayed_work);
1489 * worker_enter_idle - enter idle state
1490 * @worker: worker which is entering idle state
1492 * @worker is entering idle state. Update stats and idle timer if
1496 * spin_lock_irq(gcwq->lock).
1498 static void worker_enter_idle(struct worker *worker)
1500 struct worker_pool *pool = worker->pool;
1501 struct global_cwq *gcwq = pool->gcwq;
1503 BUG_ON(worker->flags & WORKER_IDLE);
1504 BUG_ON(!list_empty(&worker->entry) &&
1505 (worker->hentry.next || worker->hentry.pprev));
1507 /* can't use worker_set_flags(), also called from start_worker() */
1508 worker->flags |= WORKER_IDLE;
1510 worker->last_active = jiffies;
1512 /* idle_list is LIFO */
1513 list_add(&worker->entry, &pool->idle_list);
1515 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1516 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1519 * Sanity check nr_running. Because gcwq_unbind_fn() releases
1520 * gcwq->lock between setting %WORKER_UNBOUND and zapping
1521 * nr_running, the warning may trigger spuriously. Check iff
1522 * unbind is not in progress.
1524 WARN_ON_ONCE(!(gcwq->flags & GCWQ_DISASSOCIATED) &&
1525 pool->nr_workers == pool->nr_idle &&
1526 atomic_read(get_pool_nr_running(pool)));
1530 * worker_leave_idle - leave idle state
1531 * @worker: worker which is leaving idle state
1533 * @worker is leaving idle state. Update stats.
1536 * spin_lock_irq(gcwq->lock).
1538 static void worker_leave_idle(struct worker *worker)
1540 struct worker_pool *pool = worker->pool;
1542 BUG_ON(!(worker->flags & WORKER_IDLE));
1543 worker_clr_flags(worker, WORKER_IDLE);
1545 list_del_init(&worker->entry);
1549 * worker_maybe_bind_and_lock - bind worker to its cpu if possible and lock gcwq
1552 * Works which are scheduled while the cpu is online must at least be
1553 * scheduled to a worker which is bound to the cpu so that if they are
1554 * flushed from cpu callbacks while cpu is going down, they are
1555 * guaranteed to execute on the cpu.
1557 * This function is to be used by rogue workers and rescuers to bind
1558 * themselves to the target cpu and may race with cpu going down or
1559 * coming online. kthread_bind() can't be used because it may put the
1560 * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1561 * verbatim as it's best effort and blocking and gcwq may be
1562 * [dis]associated in the meantime.
1564 * This function tries set_cpus_allowed() and locks gcwq and verifies the
1565 * binding against %GCWQ_DISASSOCIATED which is set during
1566 * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
1567 * enters idle state or fetches works without dropping lock, it can
1568 * guarantee the scheduling requirement described in the first paragraph.
1571 * Might sleep. Called without any lock but returns with gcwq->lock
1575 * %true if the associated gcwq is online (@worker is successfully
1576 * bound), %false if offline.
1578 static bool worker_maybe_bind_and_lock(struct worker *worker)
1579 __acquires(&gcwq->lock)
1581 struct global_cwq *gcwq = worker->pool->gcwq;
1582 struct task_struct *task = worker->task;
1586 * The following call may fail, succeed or succeed
1587 * without actually migrating the task to the cpu if
1588 * it races with cpu hotunplug operation. Verify
1589 * against GCWQ_DISASSOCIATED.
1591 if (!(gcwq->flags & GCWQ_DISASSOCIATED))
1592 set_cpus_allowed_ptr(task, get_cpu_mask(gcwq->cpu));
1594 spin_lock_irq(&gcwq->lock);
1595 if (gcwq->flags & GCWQ_DISASSOCIATED)
1597 if (task_cpu(task) == gcwq->cpu &&
1598 cpumask_equal(¤t->cpus_allowed,
1599 get_cpu_mask(gcwq->cpu)))
1601 spin_unlock_irq(&gcwq->lock);
1604 * We've raced with CPU hot[un]plug. Give it a breather
1605 * and retry migration. cond_resched() is required here;
1606 * otherwise, we might deadlock against cpu_stop trying to
1607 * bring down the CPU on non-preemptive kernel.
1614 struct idle_rebind {
1615 int cnt; /* # workers to be rebound */
1616 struct completion done; /* all workers rebound */
1620 * Rebind an idle @worker to its CPU. During CPU onlining, this has to
1621 * happen synchronously for idle workers. worker_thread() will test
1622 * %WORKER_REBIND before leaving idle and call this function.
1624 static void idle_worker_rebind(struct worker *worker)
1626 struct global_cwq *gcwq = worker->pool->gcwq;
1628 /* CPU must be online at this point */
1629 WARN_ON(!worker_maybe_bind_and_lock(worker));
1630 if (!--worker->idle_rebind->cnt)
1631 complete(&worker->idle_rebind->done);
1632 spin_unlock_irq(&worker->pool->gcwq->lock);
1634 /* we did our part, wait for rebind_workers() to finish up */
1635 wait_event(gcwq->rebind_hold, !(worker->flags & WORKER_REBIND));
1638 * rebind_workers() shouldn't finish until all workers passed the
1639 * above WORKER_REBIND wait. Tell it when done.
1641 spin_lock_irq(&worker->pool->gcwq->lock);
1642 if (!--worker->idle_rebind->cnt)
1643 complete(&worker->idle_rebind->done);
1644 spin_unlock_irq(&worker->pool->gcwq->lock);
1648 * Function for @worker->rebind.work used to rebind unbound busy workers to
1649 * the associated cpu which is coming back online. This is scheduled by
1650 * cpu up but can race with other cpu hotplug operations and may be
1651 * executed twice without intervening cpu down.
1653 static void busy_worker_rebind_fn(struct work_struct *work)
1655 struct worker *worker = container_of(work, struct worker, rebind_work);
1656 struct global_cwq *gcwq = worker->pool->gcwq;
1658 worker_maybe_bind_and_lock(worker);
1661 * %WORKER_REBIND must be cleared even if the above binding failed;
1662 * otherwise, we may confuse the next CPU_UP cycle or oops / get
1663 * stuck by calling idle_worker_rebind() prematurely. If CPU went
1664 * down again inbetween, %WORKER_UNBOUND would be set, so clearing
1665 * %WORKER_REBIND is always safe.
1667 worker_clr_flags(worker, WORKER_REBIND);
1669 spin_unlock_irq(&gcwq->lock);
1673 * rebind_workers - rebind all workers of a gcwq to the associated CPU
1674 * @gcwq: gcwq of interest
1676 * @gcwq->cpu is coming online. Rebind all workers to the CPU. Rebinding
1677 * is different for idle and busy ones.
1679 * The idle ones should be rebound synchronously and idle rebinding should
1680 * be complete before any worker starts executing work items with
1681 * concurrency management enabled; otherwise, scheduler may oops trying to
1682 * wake up non-local idle worker from wq_worker_sleeping().
1684 * This is achieved by repeatedly requesting rebinding until all idle
1685 * workers are known to have been rebound under @gcwq->lock and holding all
1686 * idle workers from becoming busy until idle rebinding is complete.
1688 * Once idle workers are rebound, busy workers can be rebound as they
1689 * finish executing their current work items. Queueing the rebind work at
1690 * the head of their scheduled lists is enough. Note that nr_running will
1691 * be properbly bumped as busy workers rebind.
1693 * On return, all workers are guaranteed to either be bound or have rebind
1694 * work item scheduled.
1696 static void rebind_workers(struct global_cwq *gcwq)
1697 __releases(&gcwq->lock) __acquires(&gcwq->lock)
1699 struct idle_rebind idle_rebind;
1700 struct worker_pool *pool;
1701 struct worker *worker;
1702 struct hlist_node *pos;
1705 lockdep_assert_held(&gcwq->lock);
1707 for_each_worker_pool(pool, gcwq)
1708 lockdep_assert_held(&pool->manager_mutex);
1711 * Rebind idle workers. Interlocked both ways. We wait for
1712 * workers to rebind via @idle_rebind.done. Workers will wait for
1713 * us to finish up by watching %WORKER_REBIND.
1715 init_completion(&idle_rebind.done);
1717 idle_rebind.cnt = 1;
1718 INIT_COMPLETION(idle_rebind.done);
1720 /* set REBIND and kick idle ones, we'll wait for these later */
1721 for_each_worker_pool(pool, gcwq) {
1722 list_for_each_entry(worker, &pool->idle_list, entry) {
1723 unsigned long worker_flags = worker->flags;
1725 if (worker->flags & WORKER_REBIND)
1728 /* morph UNBOUND to REBIND atomically */
1729 worker_flags &= ~WORKER_UNBOUND;
1730 worker_flags |= WORKER_REBIND;
1731 ACCESS_ONCE(worker->flags) = worker_flags;
1734 worker->idle_rebind = &idle_rebind;
1736 /* worker_thread() will call idle_worker_rebind() */
1737 wake_up_process(worker->task);
1741 if (--idle_rebind.cnt) {
1742 spin_unlock_irq(&gcwq->lock);
1743 wait_for_completion(&idle_rebind.done);
1744 spin_lock_irq(&gcwq->lock);
1745 /* busy ones might have become idle while waiting, retry */
1749 /* all idle workers are rebound, rebind busy workers */
1750 for_each_busy_worker(worker, i, pos, gcwq) {
1751 unsigned long worker_flags = worker->flags;
1752 struct work_struct *rebind_work = &worker->rebind_work;
1753 struct workqueue_struct *wq;
1755 /* morph UNBOUND to REBIND atomically */
1756 worker_flags &= ~WORKER_UNBOUND;
1757 worker_flags |= WORKER_REBIND;
1758 ACCESS_ONCE(worker->flags) = worker_flags;
1760 if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
1761 work_data_bits(rebind_work)))
1764 debug_work_activate(rebind_work);
1767 * wq doesn't really matter but let's keep @worker->pool
1768 * and @cwq->pool consistent for sanity.
1770 if (worker_pool_pri(worker->pool))
1771 wq = system_highpri_wq;
1775 insert_work(get_cwq(gcwq->cpu, wq), rebind_work,
1776 worker->scheduled.next,
1777 work_color_to_flags(WORK_NO_COLOR));
1781 * All idle workers are rebound and waiting for %WORKER_REBIND to
1782 * be cleared inside idle_worker_rebind(). Clear and release.
1783 * Clearing %WORKER_REBIND from this foreign context is safe
1784 * because these workers are still guaranteed to be idle.
1786 * We need to make sure all idle workers passed WORKER_REBIND wait
1787 * in idle_worker_rebind() before returning; otherwise, workers can
1788 * get stuck at the wait if hotplug cycle repeats.
1790 idle_rebind.cnt = 1;
1791 INIT_COMPLETION(idle_rebind.done);
1793 for_each_worker_pool(pool, gcwq) {
1794 list_for_each_entry(worker, &pool->idle_list, entry) {
1795 worker->flags &= ~WORKER_REBIND;
1800 wake_up_all(&gcwq->rebind_hold);
1802 if (--idle_rebind.cnt) {
1803 spin_unlock_irq(&gcwq->lock);
1804 wait_for_completion(&idle_rebind.done);
1805 spin_lock_irq(&gcwq->lock);
1809 static struct worker *alloc_worker(void)
1811 struct worker *worker;
1813 worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1815 INIT_LIST_HEAD(&worker->entry);
1816 INIT_LIST_HEAD(&worker->scheduled);
1817 INIT_WORK(&worker->rebind_work, busy_worker_rebind_fn);
1818 /* on creation a worker is in !idle && prep state */
1819 worker->flags = WORKER_PREP;
1825 * create_worker - create a new workqueue worker
1826 * @pool: pool the new worker will belong to
1828 * Create a new worker which is bound to @pool. The returned worker
1829 * can be started by calling start_worker() or destroyed using
1833 * Might sleep. Does GFP_KERNEL allocations.
1836 * Pointer to the newly created worker.
1838 static struct worker *create_worker(struct worker_pool *pool)
1840 struct global_cwq *gcwq = pool->gcwq;
1841 const char *pri = worker_pool_pri(pool) ? "H" : "";
1842 struct worker *worker = NULL;
1845 spin_lock_irq(&gcwq->lock);
1846 while (ida_get_new(&pool->worker_ida, &id)) {
1847 spin_unlock_irq(&gcwq->lock);
1848 if (!ida_pre_get(&pool->worker_ida, GFP_KERNEL))
1850 spin_lock_irq(&gcwq->lock);
1852 spin_unlock_irq(&gcwq->lock);
1854 worker = alloc_worker();
1858 worker->pool = pool;
1861 if (gcwq->cpu != WORK_CPU_UNBOUND)
1862 worker->task = kthread_create_on_node(worker_thread,
1863 worker, cpu_to_node(gcwq->cpu),
1864 "kworker/%u:%d%s", gcwq->cpu, id, pri);
1866 worker->task = kthread_create(worker_thread, worker,
1867 "kworker/u:%d%s", id, pri);
1868 if (IS_ERR(worker->task))
1871 if (worker_pool_pri(pool))
1872 set_user_nice(worker->task, HIGHPRI_NICE_LEVEL);
1875 * Determine CPU binding of the new worker depending on
1876 * %GCWQ_DISASSOCIATED. The caller is responsible for ensuring the
1877 * flag remains stable across this function. See the comments
1878 * above the flag definition for details.
1880 * As an unbound worker may later become a regular one if CPU comes
1881 * online, make sure every worker has %PF_THREAD_BOUND set.
1883 if (!(gcwq->flags & GCWQ_DISASSOCIATED)) {
1884 kthread_bind(worker->task, gcwq->cpu);
1886 worker->task->flags |= PF_THREAD_BOUND;
1887 worker->flags |= WORKER_UNBOUND;
1893 spin_lock_irq(&gcwq->lock);
1894 ida_remove(&pool->worker_ida, id);
1895 spin_unlock_irq(&gcwq->lock);
1902 * start_worker - start a newly created worker
1903 * @worker: worker to start
1905 * Make the gcwq aware of @worker and start it.
1908 * spin_lock_irq(gcwq->lock).
1910 static void start_worker(struct worker *worker)
1912 worker->flags |= WORKER_STARTED;
1913 worker->pool->nr_workers++;
1914 worker_enter_idle(worker);
1915 wake_up_process(worker->task);
1919 * destroy_worker - destroy a workqueue worker
1920 * @worker: worker to be destroyed
1922 * Destroy @worker and adjust @gcwq stats accordingly.
1925 * spin_lock_irq(gcwq->lock) which is released and regrabbed.
1927 static void destroy_worker(struct worker *worker)
1929 struct worker_pool *pool = worker->pool;
1930 struct global_cwq *gcwq = pool->gcwq;
1931 int id = worker->id;
1933 /* sanity check frenzy */
1934 BUG_ON(worker->current_work);
1935 BUG_ON(!list_empty(&worker->scheduled));
1937 if (worker->flags & WORKER_STARTED)
1939 if (worker->flags & WORKER_IDLE)
1942 list_del_init(&worker->entry);
1943 worker->flags |= WORKER_DIE;
1945 spin_unlock_irq(&gcwq->lock);
1947 kthread_stop(worker->task);
1950 spin_lock_irq(&gcwq->lock);
1951 ida_remove(&pool->worker_ida, id);
1954 static void idle_worker_timeout(unsigned long __pool)
1956 struct worker_pool *pool = (void *)__pool;
1957 struct global_cwq *gcwq = pool->gcwq;
1959 spin_lock_irq(&gcwq->lock);
1961 if (too_many_workers(pool)) {
1962 struct worker *worker;
1963 unsigned long expires;
1965 /* idle_list is kept in LIFO order, check the last one */
1966 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1967 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1969 if (time_before(jiffies, expires))
1970 mod_timer(&pool->idle_timer, expires);
1972 /* it's been idle for too long, wake up manager */
1973 pool->flags |= POOL_MANAGE_WORKERS;
1974 wake_up_worker(pool);
1978 spin_unlock_irq(&gcwq->lock);
1981 static bool send_mayday(struct work_struct *work)
1983 struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1984 struct workqueue_struct *wq = cwq->wq;
1987 if (!(wq->flags & WQ_RESCUER))
1990 /* mayday mayday mayday */
1991 cpu = cwq->pool->gcwq->cpu;
1992 /* WORK_CPU_UNBOUND can't be set in cpumask, use cpu 0 instead */
1993 if (cpu == WORK_CPU_UNBOUND)
1995 if (!mayday_test_and_set_cpu(cpu, wq->mayday_mask))
1996 wake_up_process(wq->rescuer->task);
2000 static void gcwq_mayday_timeout(unsigned long __pool)
2002 struct worker_pool *pool = (void *)__pool;
2003 struct global_cwq *gcwq = pool->gcwq;
2004 struct work_struct *work;
2006 spin_lock_irq(&gcwq->lock);
2008 if (need_to_create_worker(pool)) {
2010 * We've been trying to create a new worker but
2011 * haven't been successful. We might be hitting an
2012 * allocation deadlock. Send distress signals to
2015 list_for_each_entry(work, &pool->worklist, entry)
2019 spin_unlock_irq(&gcwq->lock);
2021 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
2025 * maybe_create_worker - create a new worker if necessary
2026 * @pool: pool to create a new worker for
2028 * Create a new worker for @pool if necessary. @pool is guaranteed to
2029 * have at least one idle worker on return from this function. If
2030 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
2031 * sent to all rescuers with works scheduled on @pool to resolve
2032 * possible allocation deadlock.
2034 * On return, need_to_create_worker() is guaranteed to be false and
2035 * may_start_working() true.
2038 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2039 * multiple times. Does GFP_KERNEL allocations. Called only from
2043 * false if no action was taken and gcwq->lock stayed locked, true
2046 static bool maybe_create_worker(struct worker_pool *pool)
2047 __releases(&gcwq->lock)
2048 __acquires(&gcwq->lock)
2050 struct global_cwq *gcwq = pool->gcwq;
2052 if (!need_to_create_worker(pool))
2055 spin_unlock_irq(&gcwq->lock);
2057 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
2058 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
2061 struct worker *worker;
2063 worker = create_worker(pool);
2065 del_timer_sync(&pool->mayday_timer);
2066 spin_lock_irq(&gcwq->lock);
2067 start_worker(worker);
2068 BUG_ON(need_to_create_worker(pool));
2072 if (!need_to_create_worker(pool))
2075 __set_current_state(TASK_INTERRUPTIBLE);
2076 schedule_timeout(CREATE_COOLDOWN);
2078 if (!need_to_create_worker(pool))
2082 del_timer_sync(&pool->mayday_timer);
2083 spin_lock_irq(&gcwq->lock);
2084 if (need_to_create_worker(pool))
2090 * maybe_destroy_worker - destroy workers which have been idle for a while
2091 * @pool: pool to destroy workers for
2093 * Destroy @pool workers which have been idle for longer than
2094 * IDLE_WORKER_TIMEOUT.
2097 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2098 * multiple times. Called only from manager.
2101 * false if no action was taken and gcwq->lock stayed locked, true
2104 static bool maybe_destroy_workers(struct worker_pool *pool)
2108 while (too_many_workers(pool)) {
2109 struct worker *worker;
2110 unsigned long expires;
2112 worker = list_entry(pool->idle_list.prev, struct worker, entry);
2113 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2115 if (time_before(jiffies, expires)) {
2116 mod_timer(&pool->idle_timer, expires);
2120 destroy_worker(worker);
2128 * manage_workers - manage worker pool
2131 * Assume the manager role and manage gcwq worker pool @worker belongs
2132 * to. At any given time, there can be only zero or one manager per
2133 * gcwq. The exclusion is handled automatically by this function.
2135 * The caller can safely start processing works on false return. On
2136 * true return, it's guaranteed that need_to_create_worker() is false
2137 * and may_start_working() is true.
2140 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2141 * multiple times. Does GFP_KERNEL allocations.
2144 * false if no action was taken and gcwq->lock stayed locked, true if
2145 * some action was taken.
2147 static bool manage_workers(struct worker *worker)
2149 struct worker_pool *pool = worker->pool;
2152 if (pool->flags & POOL_MANAGING_WORKERS)
2155 pool->flags |= POOL_MANAGING_WORKERS;
2158 * To simplify both worker management and CPU hotplug, hold off
2159 * management while hotplug is in progress. CPU hotplug path can't
2160 * grab %POOL_MANAGING_WORKERS to achieve this because that can
2161 * lead to idle worker depletion (all become busy thinking someone
2162 * else is managing) which in turn can result in deadlock under
2163 * extreme circumstances. Use @pool->manager_mutex to synchronize
2164 * manager against CPU hotplug.
2166 * manager_mutex would always be free unless CPU hotplug is in
2167 * progress. trylock first without dropping @gcwq->lock.
2169 if (unlikely(!mutex_trylock(&pool->manager_mutex))) {
2170 spin_unlock_irq(&pool->gcwq->lock);
2171 mutex_lock(&pool->manager_mutex);
2173 * CPU hotplug could have happened while we were waiting
2174 * for manager_mutex. Hotplug itself can't handle us
2175 * because manager isn't either on idle or busy list, and
2176 * @gcwq's state and ours could have deviated.
2178 * As hotplug is now excluded via manager_mutex, we can
2179 * simply try to bind. It will succeed or fail depending
2180 * on @gcwq's current state. Try it and adjust
2181 * %WORKER_UNBOUND accordingly.
2183 if (worker_maybe_bind_and_lock(worker))
2184 worker->flags &= ~WORKER_UNBOUND;
2186 worker->flags |= WORKER_UNBOUND;
2191 pool->flags &= ~POOL_MANAGE_WORKERS;
2194 * Destroy and then create so that may_start_working() is true
2197 ret |= maybe_destroy_workers(pool);
2198 ret |= maybe_create_worker(pool);
2200 pool->flags &= ~POOL_MANAGING_WORKERS;
2201 mutex_unlock(&pool->manager_mutex);
2206 * process_one_work - process single work
2208 * @work: work to process
2210 * Process @work. This function contains all the logics necessary to
2211 * process a single work including synchronization against and
2212 * interaction with other workers on the same cpu, queueing and
2213 * flushing. As long as context requirement is met, any worker can
2214 * call this function to process a work.
2217 * spin_lock_irq(gcwq->lock) which is released and regrabbed.
2219 static void process_one_work(struct worker *worker, struct work_struct *work)
2220 __releases(&gcwq->lock)
2221 __acquires(&gcwq->lock)
2223 struct cpu_workqueue_struct *cwq = get_work_cwq(work);
2224 struct worker_pool *pool = worker->pool;
2225 struct global_cwq *gcwq = pool->gcwq;
2226 struct hlist_head *bwh = busy_worker_head(gcwq, work);
2227 bool cpu_intensive = cwq->wq->flags & WQ_CPU_INTENSIVE;
2228 work_func_t f = work->func;
2230 struct worker *collision;
2231 #ifdef CONFIG_LOCKDEP
2233 * It is permissible to free the struct work_struct from
2234 * inside the function that is called from it, this we need to
2235 * take into account for lockdep too. To avoid bogus "held
2236 * lock freed" warnings as well as problems when looking into
2237 * work->lockdep_map, make a copy and use that here.
2239 struct lockdep_map lockdep_map;
2241 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
2244 * Ensure we're on the correct CPU. DISASSOCIATED test is
2245 * necessary to avoid spurious warnings from rescuers servicing the
2246 * unbound or a disassociated gcwq.
2248 WARN_ON_ONCE(!(worker->flags & (WORKER_UNBOUND | WORKER_REBIND)) &&
2249 !(gcwq->flags & GCWQ_DISASSOCIATED) &&
2250 raw_smp_processor_id() != gcwq->cpu);
2253 * A single work shouldn't be executed concurrently by
2254 * multiple workers on a single cpu. Check whether anyone is
2255 * already processing the work. If so, defer the work to the
2256 * currently executing one.
2258 collision = __find_worker_executing_work(gcwq, bwh, work);
2259 if (unlikely(collision)) {
2260 move_linked_works(work, &collision->scheduled, NULL);
2264 /* claim and dequeue */
2265 debug_work_deactivate(work);
2266 hlist_add_head(&worker->hentry, bwh);
2267 worker->current_work = work;
2268 worker->current_cwq = cwq;
2269 work_color = get_work_color(work);
2271 list_del_init(&work->entry);
2274 * CPU intensive works don't participate in concurrency
2275 * management. They're the scheduler's responsibility.
2277 if (unlikely(cpu_intensive))
2278 worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
2281 * Unbound gcwq isn't concurrency managed and work items should be
2282 * executed ASAP. Wake up another worker if necessary.
2284 if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
2285 wake_up_worker(pool);
2288 * Record the last CPU and clear PENDING which should be the last
2289 * update to @work. Also, do this inside @gcwq->lock so that
2290 * PENDING and queued state changes happen together while IRQ is
2293 set_work_cpu_and_clear_pending(work, gcwq->cpu);
2295 spin_unlock_irq(&gcwq->lock);
2297 lock_map_acquire_read(&cwq->wq->lockdep_map);
2298 lock_map_acquire(&lockdep_map);
2299 trace_workqueue_execute_start(work);
2302 * While we must be careful to not use "work" after this, the trace
2303 * point will only record its address.
2305 trace_workqueue_execute_end(work);
2306 lock_map_release(&lockdep_map);
2307 lock_map_release(&cwq->wq->lockdep_map);
2309 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2310 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2311 " last function: %pf\n",
2312 current->comm, preempt_count(), task_pid_nr(current), f);
2313 debug_show_held_locks(current);
2317 spin_lock_irq(&gcwq->lock);
2319 /* clear cpu intensive status */
2320 if (unlikely(cpu_intensive))
2321 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2323 /* we're done with it, release */
2324 hlist_del_init(&worker->hentry);
2325 worker->current_work = NULL;
2326 worker->current_cwq = NULL;
2327 cwq_dec_nr_in_flight(cwq, work_color, false);
2331 * process_scheduled_works - process scheduled works
2334 * Process all scheduled works. Please note that the scheduled list
2335 * may change while processing a work, so this function repeatedly
2336 * fetches a work from the top and executes it.
2339 * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2342 static void process_scheduled_works(struct worker *worker)
2344 while (!list_empty(&worker->scheduled)) {
2345 struct work_struct *work = list_first_entry(&worker->scheduled,
2346 struct work_struct, entry);
2347 process_one_work(worker, work);
2352 * worker_thread - the worker thread function
2355 * The gcwq worker thread function. There's a single dynamic pool of
2356 * these per each cpu. These workers process all works regardless of
2357 * their specific target workqueue. The only exception is works which
2358 * belong to workqueues with a rescuer which will be explained in
2361 static int worker_thread(void *__worker)
2363 struct worker *worker = __worker;
2364 struct worker_pool *pool = worker->pool;
2365 struct global_cwq *gcwq = pool->gcwq;
2367 /* tell the scheduler that this is a workqueue worker */
2368 worker->task->flags |= PF_WQ_WORKER;
2370 spin_lock_irq(&gcwq->lock);
2373 * DIE can be set only while idle and REBIND set while busy has
2374 * @worker->rebind_work scheduled. Checking here is enough.
2376 if (unlikely(worker->flags & (WORKER_REBIND | WORKER_DIE))) {
2377 spin_unlock_irq(&gcwq->lock);
2379 if (worker->flags & WORKER_DIE) {
2380 worker->task->flags &= ~PF_WQ_WORKER;
2384 idle_worker_rebind(worker);
2388 worker_leave_idle(worker);
2390 /* no more worker necessary? */
2391 if (!need_more_worker(pool))
2394 /* do we need to manage? */
2395 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2399 * ->scheduled list can only be filled while a worker is
2400 * preparing to process a work or actually processing it.
2401 * Make sure nobody diddled with it while I was sleeping.
2403 BUG_ON(!list_empty(&worker->scheduled));
2406 * When control reaches this point, we're guaranteed to have
2407 * at least one idle worker or that someone else has already
2408 * assumed the manager role.
2410 worker_clr_flags(worker, WORKER_PREP);
2413 struct work_struct *work =
2414 list_first_entry(&pool->worklist,
2415 struct work_struct, entry);
2417 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2418 /* optimization path, not strictly necessary */
2419 process_one_work(worker, work);
2420 if (unlikely(!list_empty(&worker->scheduled)))
2421 process_scheduled_works(worker);
2423 move_linked_works(work, &worker->scheduled, NULL);
2424 process_scheduled_works(worker);
2426 } while (keep_working(pool));
2428 worker_set_flags(worker, WORKER_PREP, false);
2430 if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
2434 * gcwq->lock is held and there's no work to process and no
2435 * need to manage, sleep. Workers are woken up only while
2436 * holding gcwq->lock or from local cpu, so setting the
2437 * current state before releasing gcwq->lock is enough to
2438 * prevent losing any event.
2440 worker_enter_idle(worker);
2441 __set_current_state(TASK_INTERRUPTIBLE);
2442 spin_unlock_irq(&gcwq->lock);
2448 * rescuer_thread - the rescuer thread function
2449 * @__wq: the associated workqueue
2451 * Workqueue rescuer thread function. There's one rescuer for each
2452 * workqueue which has WQ_RESCUER set.
2454 * Regular work processing on a gcwq may block trying to create a new
2455 * worker which uses GFP_KERNEL allocation which has slight chance of
2456 * developing into deadlock if some works currently on the same queue
2457 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2458 * the problem rescuer solves.
2460 * When such condition is possible, the gcwq summons rescuers of all
2461 * workqueues which have works queued on the gcwq and let them process
2462 * those works so that forward progress can be guaranteed.
2464 * This should happen rarely.
2466 static int rescuer_thread(void *__wq)
2468 struct workqueue_struct *wq = __wq;
2469 struct worker *rescuer = wq->rescuer;
2470 struct list_head *scheduled = &rescuer->scheduled;
2471 bool is_unbound = wq->flags & WQ_UNBOUND;
2474 set_user_nice(current, RESCUER_NICE_LEVEL);
2476 set_current_state(TASK_INTERRUPTIBLE);
2478 if (kthread_should_stop())
2482 * See whether any cpu is asking for help. Unbounded
2483 * workqueues use cpu 0 in mayday_mask for CPU_UNBOUND.
2485 for_each_mayday_cpu(cpu, wq->mayday_mask) {
2486 unsigned int tcpu = is_unbound ? WORK_CPU_UNBOUND : cpu;
2487 struct cpu_workqueue_struct *cwq = get_cwq(tcpu, wq);
2488 struct worker_pool *pool = cwq->pool;
2489 struct global_cwq *gcwq = pool->gcwq;
2490 struct work_struct *work, *n;
2492 __set_current_state(TASK_RUNNING);
2493 mayday_clear_cpu(cpu, wq->mayday_mask);
2495 /* migrate to the target cpu if possible */
2496 rescuer->pool = pool;
2497 worker_maybe_bind_and_lock(rescuer);
2500 * Slurp in all works issued via this workqueue and
2503 BUG_ON(!list_empty(&rescuer->scheduled));
2504 list_for_each_entry_safe(work, n, &pool->worklist, entry)
2505 if (get_work_cwq(work) == cwq)
2506 move_linked_works(work, scheduled, &n);
2508 process_scheduled_works(rescuer);
2511 * Leave this gcwq. If keep_working() is %true, notify a
2512 * regular worker; otherwise, we end up with 0 concurrency
2513 * and stalling the execution.
2515 if (keep_working(pool))
2516 wake_up_worker(pool);
2518 spin_unlock_irq(&gcwq->lock);
2526 struct work_struct work;
2527 struct completion done;
2530 static void wq_barrier_func(struct work_struct *work)
2532 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2533 complete(&barr->done);
2537 * insert_wq_barrier - insert a barrier work
2538 * @cwq: cwq to insert barrier into
2539 * @barr: wq_barrier to insert
2540 * @target: target work to attach @barr to
2541 * @worker: worker currently executing @target, NULL if @target is not executing
2543 * @barr is linked to @target such that @barr is completed only after
2544 * @target finishes execution. Please note that the ordering
2545 * guarantee is observed only with respect to @target and on the local
2548 * Currently, a queued barrier can't be canceled. This is because
2549 * try_to_grab_pending() can't determine whether the work to be
2550 * grabbed is at the head of the queue and thus can't clear LINKED
2551 * flag of the previous work while there must be a valid next work
2552 * after a work with LINKED flag set.
2554 * Note that when @worker is non-NULL, @target may be modified
2555 * underneath us, so we can't reliably determine cwq from @target.
2558 * spin_lock_irq(gcwq->lock).
2560 static void insert_wq_barrier(struct cpu_workqueue_struct *cwq,
2561 struct wq_barrier *barr,
2562 struct work_struct *target, struct worker *worker)
2564 struct list_head *head;
2565 unsigned int linked = 0;
2568 * debugobject calls are safe here even with gcwq->lock locked
2569 * as we know for sure that this will not trigger any of the
2570 * checks and call back into the fixup functions where we
2573 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2574 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2575 init_completion(&barr->done);
2578 * If @target is currently being executed, schedule the
2579 * barrier to the worker; otherwise, put it after @target.
2582 head = worker->scheduled.next;
2584 unsigned long *bits = work_data_bits(target);
2586 head = target->entry.next;
2587 /* there can already be other linked works, inherit and set */
2588 linked = *bits & WORK_STRUCT_LINKED;
2589 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2592 debug_work_activate(&barr->work);
2593 insert_work(cwq, &barr->work, head,
2594 work_color_to_flags(WORK_NO_COLOR) | linked);
2598 * flush_workqueue_prep_cwqs - prepare cwqs for workqueue flushing
2599 * @wq: workqueue being flushed
2600 * @flush_color: new flush color, < 0 for no-op
2601 * @work_color: new work color, < 0 for no-op
2603 * Prepare cwqs for workqueue flushing.
2605 * If @flush_color is non-negative, flush_color on all cwqs should be
2606 * -1. If no cwq has in-flight commands at the specified color, all
2607 * cwq->flush_color's stay at -1 and %false is returned. If any cwq
2608 * has in flight commands, its cwq->flush_color is set to
2609 * @flush_color, @wq->nr_cwqs_to_flush is updated accordingly, cwq
2610 * wakeup logic is armed and %true is returned.
2612 * The caller should have initialized @wq->first_flusher prior to
2613 * calling this function with non-negative @flush_color. If
2614 * @flush_color is negative, no flush color update is done and %false
2617 * If @work_color is non-negative, all cwqs should have the same
2618 * work_color which is previous to @work_color and all will be
2619 * advanced to @work_color.
2622 * mutex_lock(wq->flush_mutex).
2625 * %true if @flush_color >= 0 and there's something to flush. %false
2628 static bool flush_workqueue_prep_cwqs(struct workqueue_struct *wq,
2629 int flush_color, int work_color)
2634 if (flush_color >= 0) {
2635 BUG_ON(atomic_read(&wq->nr_cwqs_to_flush));
2636 atomic_set(&wq->nr_cwqs_to_flush, 1);
2639 for_each_cwq_cpu(cpu, wq) {
2640 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2641 struct global_cwq *gcwq = cwq->pool->gcwq;
2643 spin_lock_irq(&gcwq->lock);
2645 if (flush_color >= 0) {
2646 BUG_ON(cwq->flush_color != -1);
2648 if (cwq->nr_in_flight[flush_color]) {
2649 cwq->flush_color = flush_color;
2650 atomic_inc(&wq->nr_cwqs_to_flush);
2655 if (work_color >= 0) {
2656 BUG_ON(work_color != work_next_color(cwq->work_color));
2657 cwq->work_color = work_color;
2660 spin_unlock_irq(&gcwq->lock);
2663 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_cwqs_to_flush))
2664 complete(&wq->first_flusher->done);
2670 * flush_workqueue - ensure that any scheduled work has run to completion.
2671 * @wq: workqueue to flush
2673 * Forces execution of the workqueue and blocks until its completion.
2674 * This is typically used in driver shutdown handlers.
2676 * We sleep until all works which were queued on entry have been handled,
2677 * but we are not livelocked by new incoming ones.
2679 void flush_workqueue(struct workqueue_struct *wq)
2681 struct wq_flusher this_flusher = {
2682 .list = LIST_HEAD_INIT(this_flusher.list),
2684 .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
2688 lock_map_acquire(&wq->lockdep_map);
2689 lock_map_release(&wq->lockdep_map);
2691 mutex_lock(&wq->flush_mutex);
2694 * Start-to-wait phase
2696 next_color = work_next_color(wq->work_color);
2698 if (next_color != wq->flush_color) {
2700 * Color space is not full. The current work_color
2701 * becomes our flush_color and work_color is advanced
2704 BUG_ON(!list_empty(&wq->flusher_overflow));
2705 this_flusher.flush_color = wq->work_color;
2706 wq->work_color = next_color;
2708 if (!wq->first_flusher) {
2709 /* no flush in progress, become the first flusher */
2710 BUG_ON(wq->flush_color != this_flusher.flush_color);
2712 wq->first_flusher = &this_flusher;
2714 if (!flush_workqueue_prep_cwqs(wq, wq->flush_color,
2716 /* nothing to flush, done */
2717 wq->flush_color = next_color;
2718 wq->first_flusher = NULL;
2723 BUG_ON(wq->flush_color == this_flusher.flush_color);
2724 list_add_tail(&this_flusher.list, &wq->flusher_queue);
2725 flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2729 * Oops, color space is full, wait on overflow queue.
2730 * The next flush completion will assign us
2731 * flush_color and transfer to flusher_queue.
2733 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2736 mutex_unlock(&wq->flush_mutex);
2738 wait_for_completion(&this_flusher.done);
2741 * Wake-up-and-cascade phase
2743 * First flushers are responsible for cascading flushes and
2744 * handling overflow. Non-first flushers can simply return.
2746 if (wq->first_flusher != &this_flusher)
2749 mutex_lock(&wq->flush_mutex);
2751 /* we might have raced, check again with mutex held */
2752 if (wq->first_flusher != &this_flusher)
2755 wq->first_flusher = NULL;
2757 BUG_ON(!list_empty(&this_flusher.list));
2758 BUG_ON(wq->flush_color != this_flusher.flush_color);
2761 struct wq_flusher *next, *tmp;
2763 /* complete all the flushers sharing the current flush color */
2764 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2765 if (next->flush_color != wq->flush_color)
2767 list_del_init(&next->list);
2768 complete(&next->done);
2771 BUG_ON(!list_empty(&wq->flusher_overflow) &&
2772 wq->flush_color != work_next_color(wq->work_color));
2774 /* this flush_color is finished, advance by one */
2775 wq->flush_color = work_next_color(wq->flush_color);
2777 /* one color has been freed, handle overflow queue */
2778 if (!list_empty(&wq->flusher_overflow)) {
2780 * Assign the same color to all overflowed
2781 * flushers, advance work_color and append to
2782 * flusher_queue. This is the start-to-wait
2783 * phase for these overflowed flushers.
2785 list_for_each_entry(tmp, &wq->flusher_overflow, list)
2786 tmp->flush_color = wq->work_color;
2788 wq->work_color = work_next_color(wq->work_color);
2790 list_splice_tail_init(&wq->flusher_overflow,
2791 &wq->flusher_queue);
2792 flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2795 if (list_empty(&wq->flusher_queue)) {
2796 BUG_ON(wq->flush_color != wq->work_color);
2801 * Need to flush more colors. Make the next flusher
2802 * the new first flusher and arm cwqs.
2804 BUG_ON(wq->flush_color == wq->work_color);
2805 BUG_ON(wq->flush_color != next->flush_color);
2807 list_del_init(&next->list);
2808 wq->first_flusher = next;
2810 if (flush_workqueue_prep_cwqs(wq, wq->flush_color, -1))
2814 * Meh... this color is already done, clear first
2815 * flusher and repeat cascading.
2817 wq->first_flusher = NULL;
2821 mutex_unlock(&wq->flush_mutex);
2823 EXPORT_SYMBOL_GPL(flush_workqueue);
2826 * drain_workqueue - drain a workqueue
2827 * @wq: workqueue to drain
2829 * Wait until the workqueue becomes empty. While draining is in progress,
2830 * only chain queueing is allowed. IOW, only currently pending or running
2831 * work items on @wq can queue further work items on it. @wq is flushed
2832 * repeatedly until it becomes empty. The number of flushing is detemined
2833 * by the depth of chaining and should be relatively short. Whine if it
2836 void drain_workqueue(struct workqueue_struct *wq)
2838 unsigned int flush_cnt = 0;
2842 * __queue_work() needs to test whether there are drainers, is much
2843 * hotter than drain_workqueue() and already looks at @wq->flags.
2844 * Use WQ_DRAINING so that queue doesn't have to check nr_drainers.
2846 spin_lock(&workqueue_lock);
2847 if (!wq->nr_drainers++)
2848 wq->flags |= WQ_DRAINING;
2849 spin_unlock(&workqueue_lock);
2851 flush_workqueue(wq);
2853 for_each_cwq_cpu(cpu, wq) {
2854 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2857 spin_lock_irq(&cwq->pool->gcwq->lock);
2858 drained = !cwq->nr_active && list_empty(&cwq->delayed_works);
2859 spin_unlock_irq(&cwq->pool->gcwq->lock);
2864 if (++flush_cnt == 10 ||
2865 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2866 pr_warn("workqueue %s: flush on destruction isn't complete after %u tries\n",
2867 wq->name, flush_cnt);
2871 spin_lock(&workqueue_lock);
2872 if (!--wq->nr_drainers)
2873 wq->flags &= ~WQ_DRAINING;
2874 spin_unlock(&workqueue_lock);
2876 EXPORT_SYMBOL_GPL(drain_workqueue);
2878 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2880 struct worker *worker = NULL;
2881 struct global_cwq *gcwq;
2882 struct cpu_workqueue_struct *cwq;
2885 gcwq = get_work_gcwq(work);
2889 spin_lock_irq(&gcwq->lock);
2890 if (!list_empty(&work->entry)) {
2892 * See the comment near try_to_grab_pending()->smp_rmb().
2893 * If it was re-queued to a different gcwq under us, we
2894 * are not going to wait.
2897 cwq = get_work_cwq(work);
2898 if (unlikely(!cwq || gcwq != cwq->pool->gcwq))
2901 worker = find_worker_executing_work(gcwq, work);
2904 cwq = worker->current_cwq;
2907 insert_wq_barrier(cwq, barr, work, worker);
2908 spin_unlock_irq(&gcwq->lock);
2911 * If @max_active is 1 or rescuer is in use, flushing another work
2912 * item on the same workqueue may lead to deadlock. Make sure the
2913 * flusher is not running on the same workqueue by verifying write
2916 if (cwq->wq->saved_max_active == 1 || cwq->wq->flags & WQ_RESCUER)
2917 lock_map_acquire(&cwq->wq->lockdep_map);
2919 lock_map_acquire_read(&cwq->wq->lockdep_map);
2920 lock_map_release(&cwq->wq->lockdep_map);
2924 spin_unlock_irq(&gcwq->lock);
2929 * flush_work - wait for a work to finish executing the last queueing instance
2930 * @work: the work to flush
2932 * Wait until @work has finished execution. @work is guaranteed to be idle
2933 * on return if it hasn't been requeued since flush started.
2936 * %true if flush_work() waited for the work to finish execution,
2937 * %false if it was already idle.
2939 bool flush_work(struct work_struct *work)
2941 struct wq_barrier barr;
2943 lock_map_acquire(&work->lockdep_map);
2944 lock_map_release(&work->lockdep_map);
2946 if (start_flush_work(work, &barr)) {
2947 wait_for_completion(&barr.done);
2948 destroy_work_on_stack(&barr.work);
2954 EXPORT_SYMBOL_GPL(flush_work);
2956 static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2958 unsigned long flags;
2962 ret = try_to_grab_pending(work, is_dwork, &flags);
2964 * If someone else is canceling, wait for the same event it
2965 * would be waiting for before retrying.
2967 if (unlikely(ret == -ENOENT))
2969 } while (unlikely(ret < 0));
2971 /* tell other tasks trying to grab @work to back off */
2972 mark_work_canceling(work);
2973 local_irq_restore(flags);
2976 clear_work_data(work);
2981 * cancel_work_sync - cancel a work and wait for it to finish
2982 * @work: the work to cancel
2984 * Cancel @work and wait for its execution to finish. This function
2985 * can be used even if the work re-queues itself or migrates to
2986 * another workqueue. On return from this function, @work is
2987 * guaranteed to be not pending or executing on any CPU.
2989 * cancel_work_sync(&delayed_work->work) must not be used for
2990 * delayed_work's. Use cancel_delayed_work_sync() instead.
2992 * The caller must ensure that the workqueue on which @work was last
2993 * queued can't be destroyed before this function returns.
2996 * %true if @work was pending, %false otherwise.
2998 bool cancel_work_sync(struct work_struct *work)
3000 return __cancel_work_timer(work, false);
3002 EXPORT_SYMBOL_GPL(cancel_work_sync);
3005 * flush_delayed_work - wait for a dwork to finish executing the last queueing
3006 * @dwork: the delayed work to flush
3008 * Delayed timer is cancelled and the pending work is queued for
3009 * immediate execution. Like flush_work(), this function only
3010 * considers the last queueing instance of @dwork.
3013 * %true if flush_work() waited for the work to finish execution,
3014 * %false if it was already idle.
3016 bool flush_delayed_work(struct delayed_work *dwork)
3018 local_irq_disable();
3019 if (del_timer_sync(&dwork->timer))
3020 __queue_work(dwork->cpu,
3021 get_work_cwq(&dwork->work)->wq, &dwork->work);
3023 return flush_work(&dwork->work);
3025 EXPORT_SYMBOL(flush_delayed_work);
3028 * cancel_delayed_work - cancel a delayed work
3029 * @dwork: delayed_work to cancel
3031 * Kill off a pending delayed_work. Returns %true if @dwork was pending
3032 * and canceled; %false if wasn't pending. Note that the work callback
3033 * function may still be running on return, unless it returns %true and the
3034 * work doesn't re-arm itself. Explicitly flush or use
3035 * cancel_delayed_work_sync() to wait on it.
3037 * This function is safe to call from any context including IRQ handler.
3039 bool cancel_delayed_work(struct delayed_work *dwork)
3041 unsigned long flags;
3045 ret = try_to_grab_pending(&dwork->work, true, &flags);
3046 } while (unlikely(ret == -EAGAIN));
3048 if (unlikely(ret < 0))
3051 set_work_cpu_and_clear_pending(&dwork->work, work_cpu(&dwork->work));
3052 local_irq_restore(flags);
3055 EXPORT_SYMBOL(cancel_delayed_work);
3058 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3059 * @dwork: the delayed work cancel
3061 * This is cancel_work_sync() for delayed works.
3064 * %true if @dwork was pending, %false otherwise.
3066 bool cancel_delayed_work_sync(struct delayed_work *dwork)
3068 return __cancel_work_timer(&dwork->work, true);
3070 EXPORT_SYMBOL(cancel_delayed_work_sync);
3073 * schedule_work_on - put work task on a specific cpu
3074 * @cpu: cpu to put the work task on
3075 * @work: job to be done
3077 * This puts a job on a specific cpu
3079 bool schedule_work_on(int cpu, struct work_struct *work)
3081 return queue_work_on(cpu, system_wq, work);
3083 EXPORT_SYMBOL(schedule_work_on);
3086 * schedule_work - put work task in global workqueue
3087 * @work: job to be done
3089 * Returns %false if @work was already on the kernel-global workqueue and
3092 * This puts a job in the kernel-global workqueue if it was not already
3093 * queued and leaves it in the same position on the kernel-global
3094 * workqueue otherwise.
3096 bool schedule_work(struct work_struct *work)
3098 return queue_work(system_wq, work);
3100 EXPORT_SYMBOL(schedule_work);
3103 * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
3105 * @dwork: job to be done
3106 * @delay: number of jiffies to wait
3108 * After waiting for a given time this puts a job in the kernel-global
3109 * workqueue on the specified CPU.
3111 bool schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
3112 unsigned long delay)
3114 return queue_delayed_work_on(cpu, system_wq, dwork, delay);
3116 EXPORT_SYMBOL(schedule_delayed_work_on);
3119 * schedule_delayed_work - put work task in global workqueue after delay
3120 * @dwork: job to be done
3121 * @delay: number of jiffies to wait or 0 for immediate execution
3123 * After waiting for a given time this puts a job in the kernel-global
3126 bool schedule_delayed_work(struct delayed_work *dwork, unsigned long delay)
3128 return queue_delayed_work(system_wq, dwork, delay);
3130 EXPORT_SYMBOL(schedule_delayed_work);
3133 * schedule_on_each_cpu - execute a function synchronously on each online CPU
3134 * @func: the function to call
3136 * schedule_on_each_cpu() executes @func on each online CPU using the
3137 * system workqueue and blocks until all CPUs have completed.
3138 * schedule_on_each_cpu() is very slow.
3141 * 0 on success, -errno on failure.
3143 int schedule_on_each_cpu(work_func_t func)
3146 struct work_struct __percpu *works;
3148 works = alloc_percpu(struct work_struct);
3154 for_each_online_cpu(cpu) {
3155 struct work_struct *work = per_cpu_ptr(works, cpu);
3157 INIT_WORK(work, func);
3158 schedule_work_on(cpu, work);
3161 for_each_online_cpu(cpu)
3162 flush_work(per_cpu_ptr(works, cpu));
3170 * flush_scheduled_work - ensure that any scheduled work has run to completion.
3172 * Forces execution of the kernel-global workqueue and blocks until its
3175 * Think twice before calling this function! It's very easy to get into
3176 * trouble if you don't take great care. Either of the following situations
3177 * will lead to deadlock:
3179 * One of the work items currently on the workqueue needs to acquire
3180 * a lock held by your code or its caller.
3182 * Your code is running in the context of a work routine.
3184 * They will be detected by lockdep when they occur, but the first might not
3185 * occur very often. It depends on what work items are on the workqueue and
3186 * what locks they need, which you have no control over.
3188 * In most situations flushing the entire workqueue is overkill; you merely
3189 * need to know that a particular work item isn't queued and isn't running.
3190 * In such cases you should use cancel_delayed_work_sync() or
3191 * cancel_work_sync() instead.
3193 void flush_scheduled_work(void)
3195 flush_workqueue(system_wq);
3197 EXPORT_SYMBOL(flush_scheduled_work);
3200 * execute_in_process_context - reliably execute the routine with user context
3201 * @fn: the function to execute
3202 * @ew: guaranteed storage for the execute work structure (must
3203 * be available when the work executes)
3205 * Executes the function immediately if process context is available,
3206 * otherwise schedules the function for delayed execution.
3208 * Returns: 0 - function was executed
3209 * 1 - function was scheduled for execution
3211 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
3213 if (!in_interrupt()) {
3218 INIT_WORK(&ew->work, fn);
3219 schedule_work(&ew->work);
3223 EXPORT_SYMBOL_GPL(execute_in_process_context);
3225 int keventd_up(void)
3227 return system_wq != NULL;
3230 static int alloc_cwqs(struct workqueue_struct *wq)
3233 * cwqs are forced aligned according to WORK_STRUCT_FLAG_BITS.
3234 * Make sure that the alignment isn't lower than that of
3235 * unsigned long long.
3237 const size_t size = sizeof(struct cpu_workqueue_struct);
3238 const size_t align = max_t(size_t, 1 << WORK_STRUCT_FLAG_BITS,
3239 __alignof__(unsigned long long));
3241 if (!(wq->flags & WQ_UNBOUND))
3242 wq->cpu_wq.pcpu = __alloc_percpu(size, align);
3247 * Allocate enough room to align cwq and put an extra
3248 * pointer at the end pointing back to the originally
3249 * allocated pointer which will be used for free.
3251 ptr = kzalloc(size + align + sizeof(void *), GFP_KERNEL);
3253 wq->cpu_wq.single = PTR_ALIGN(ptr, align);
3254 *(void **)(wq->cpu_wq.single + 1) = ptr;
3258 /* just in case, make sure it's actually aligned */
3259 BUG_ON(!IS_ALIGNED(wq->cpu_wq.v, align));
3260 return wq->cpu_wq.v ? 0 : -ENOMEM;
3263 static void free_cwqs(struct workqueue_struct *wq)
3265 if (!(wq->flags & WQ_UNBOUND))
3266 free_percpu(wq->cpu_wq.pcpu);
3267 else if (wq->cpu_wq.single) {
3268 /* the pointer to free is stored right after the cwq */
3269 kfree(*(void **)(wq->cpu_wq.single + 1));
3273 static int wq_clamp_max_active(int max_active, unsigned int flags,
3276 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3278 if (max_active < 1 || max_active > lim)
3279 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3280 max_active, name, 1, lim);
3282 return clamp_val(max_active, 1, lim);
3285 struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
3288 struct lock_class_key *key,
3289 const char *lock_name, ...)
3291 va_list args, args1;
3292 struct workqueue_struct *wq;
3296 /* determine namelen, allocate wq and format name */
3297 va_start(args, lock_name);
3298 va_copy(args1, args);
3299 namelen = vsnprintf(NULL, 0, fmt, args) + 1;
3301 wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
3305 vsnprintf(wq->name, namelen, fmt, args1);
3310 * Workqueues which may be used during memory reclaim should
3311 * have a rescuer to guarantee forward progress.
3313 if (flags & WQ_MEM_RECLAIM)
3314 flags |= WQ_RESCUER;
3316 max_active = max_active ?: WQ_DFL_ACTIVE;
3317 max_active = wq_clamp_max_active(max_active, flags, wq->name);
3321 wq->saved_max_active = max_active;
3322 mutex_init(&wq->flush_mutex);
3323 atomic_set(&wq->nr_cwqs_to_flush, 0);
3324 INIT_LIST_HEAD(&wq->flusher_queue);
3325 INIT_LIST_HEAD(&wq->flusher_overflow);
3327 lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3328 INIT_LIST_HEAD(&wq->list);
3330 if (alloc_cwqs(wq) < 0)
3333 for_each_cwq_cpu(cpu, wq) {
3334 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3335 struct global_cwq *gcwq = get_gcwq(cpu);
3336 int pool_idx = (bool)(flags & WQ_HIGHPRI);
3338 BUG_ON((unsigned long)cwq & WORK_STRUCT_FLAG_MASK);
3339 cwq->pool = &gcwq->pools[pool_idx];
3341 cwq->flush_color = -1;
3342 cwq->max_active = max_active;
3343 INIT_LIST_HEAD(&cwq->delayed_works);
3346 if (flags & WQ_RESCUER) {
3347 struct worker *rescuer;
3349 if (!alloc_mayday_mask(&wq->mayday_mask, GFP_KERNEL))
3352 wq->rescuer = rescuer = alloc_worker();
3356 rescuer->task = kthread_create(rescuer_thread, wq, "%s",
3358 if (IS_ERR(rescuer->task))
3361 rescuer->task->flags |= PF_THREAD_BOUND;
3362 wake_up_process(rescuer->task);
3366 * workqueue_lock protects global freeze state and workqueues
3367 * list. Grab it, set max_active accordingly and add the new
3368 * workqueue to workqueues list.
3370 spin_lock(&workqueue_lock);
3372 if (workqueue_freezing && wq->flags & WQ_FREEZABLE)
3373 for_each_cwq_cpu(cpu, wq)
3374 get_cwq(cpu, wq)->max_active = 0;
3376 list_add(&wq->list, &workqueues);
3378 spin_unlock(&workqueue_lock);
3384 free_mayday_mask(wq->mayday_mask);
3390 EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
3393 * destroy_workqueue - safely terminate a workqueue
3394 * @wq: target workqueue
3396 * Safely destroy a workqueue. All work currently pending will be done first.
3398 void destroy_workqueue(struct workqueue_struct *wq)
3402 /* drain it before proceeding with destruction */
3403 drain_workqueue(wq);
3406 * wq list is used to freeze wq, remove from list after
3407 * flushing is complete in case freeze races us.
3409 spin_lock(&workqueue_lock);
3410 list_del(&wq->list);
3411 spin_unlock(&workqueue_lock);
3414 for_each_cwq_cpu(cpu, wq) {
3415 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3418 for (i = 0; i < WORK_NR_COLORS; i++)
3419 BUG_ON(cwq->nr_in_flight[i]);
3420 BUG_ON(cwq->nr_active);
3421 BUG_ON(!list_empty(&cwq->delayed_works));
3424 if (wq->flags & WQ_RESCUER) {
3425 kthread_stop(wq->rescuer->task);
3426 free_mayday_mask(wq->mayday_mask);
3433 EXPORT_SYMBOL_GPL(destroy_workqueue);
3436 * workqueue_set_max_active - adjust max_active of a workqueue
3437 * @wq: target workqueue
3438 * @max_active: new max_active value.
3440 * Set max_active of @wq to @max_active.
3443 * Don't call from IRQ context.
3445 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
3449 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
3451 spin_lock(&workqueue_lock);
3453 wq->saved_max_active = max_active;
3455 for_each_cwq_cpu(cpu, wq) {
3456 struct global_cwq *gcwq = get_gcwq(cpu);
3458 spin_lock_irq(&gcwq->lock);
3460 if (!(wq->flags & WQ_FREEZABLE) ||
3461 !(gcwq->flags & GCWQ_FREEZING))
3462 get_cwq(gcwq->cpu, wq)->max_active = max_active;
3464 spin_unlock_irq(&gcwq->lock);
3467 spin_unlock(&workqueue_lock);
3469 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
3472 * workqueue_congested - test whether a workqueue is congested
3473 * @cpu: CPU in question
3474 * @wq: target workqueue
3476 * Test whether @wq's cpu workqueue for @cpu is congested. There is
3477 * no synchronization around this function and the test result is
3478 * unreliable and only useful as advisory hints or for debugging.
3481 * %true if congested, %false otherwise.
3483 bool workqueue_congested(unsigned int cpu, struct workqueue_struct *wq)
3485 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3487 return !list_empty(&cwq->delayed_works);
3489 EXPORT_SYMBOL_GPL(workqueue_congested);
3492 * work_cpu - return the last known associated cpu for @work
3493 * @work: the work of interest
3496 * CPU number if @work was ever queued. WORK_CPU_NONE otherwise.
3498 unsigned int work_cpu(struct work_struct *work)
3500 struct global_cwq *gcwq = get_work_gcwq(work);
3502 return gcwq ? gcwq->cpu : WORK_CPU_NONE;
3504 EXPORT_SYMBOL_GPL(work_cpu);
3507 * work_busy - test whether a work is currently pending or running
3508 * @work: the work to be tested
3510 * Test whether @work is currently pending or running. There is no
3511 * synchronization around this function and the test result is
3512 * unreliable and only useful as advisory hints or for debugging.
3513 * Especially for reentrant wqs, the pending state might hide the
3517 * OR'd bitmask of WORK_BUSY_* bits.
3519 unsigned int work_busy(struct work_struct *work)
3521 struct global_cwq *gcwq = get_work_gcwq(work);
3522 unsigned long flags;
3523 unsigned int ret = 0;
3528 spin_lock_irqsave(&gcwq->lock, flags);
3530 if (work_pending(work))
3531 ret |= WORK_BUSY_PENDING;
3532 if (find_worker_executing_work(gcwq, work))
3533 ret |= WORK_BUSY_RUNNING;
3535 spin_unlock_irqrestore(&gcwq->lock, flags);
3539 EXPORT_SYMBOL_GPL(work_busy);
3544 * There are two challenges in supporting CPU hotplug. Firstly, there
3545 * are a lot of assumptions on strong associations among work, cwq and
3546 * gcwq which make migrating pending and scheduled works very
3547 * difficult to implement without impacting hot paths. Secondly,
3548 * gcwqs serve mix of short, long and very long running works making
3549 * blocked draining impractical.
3551 * This is solved by allowing a gcwq to be disassociated from the CPU
3552 * running as an unbound one and allowing it to be reattached later if the
3553 * cpu comes back online.
3556 /* claim manager positions of all pools */
3557 static void gcwq_claim_management_and_lock(struct global_cwq *gcwq)
3559 struct worker_pool *pool;
3561 for_each_worker_pool(pool, gcwq)
3562 mutex_lock_nested(&pool->manager_mutex, pool - gcwq->pools);
3563 spin_lock_irq(&gcwq->lock);
3566 /* release manager positions */
3567 static void gcwq_release_management_and_unlock(struct global_cwq *gcwq)
3569 struct worker_pool *pool;
3571 spin_unlock_irq(&gcwq->lock);
3572 for_each_worker_pool(pool, gcwq)
3573 mutex_unlock(&pool->manager_mutex);
3576 static void gcwq_unbind_fn(struct work_struct *work)
3578 struct global_cwq *gcwq = get_gcwq(smp_processor_id());
3579 struct worker_pool *pool;
3580 struct worker *worker;
3581 struct hlist_node *pos;
3584 BUG_ON(gcwq->cpu != smp_processor_id());
3586 gcwq_claim_management_and_lock(gcwq);
3589 * We've claimed all manager positions. Make all workers unbound
3590 * and set DISASSOCIATED. Before this, all workers except for the
3591 * ones which are still executing works from before the last CPU
3592 * down must be on the cpu. After this, they may become diasporas.
3594 for_each_worker_pool(pool, gcwq)
3595 list_for_each_entry(worker, &pool->idle_list, entry)
3596 worker->flags |= WORKER_UNBOUND;
3598 for_each_busy_worker(worker, i, pos, gcwq)
3599 worker->flags |= WORKER_UNBOUND;
3601 gcwq->flags |= GCWQ_DISASSOCIATED;
3603 gcwq_release_management_and_unlock(gcwq);
3606 * Call schedule() so that we cross rq->lock and thus can guarantee
3607 * sched callbacks see the %WORKER_UNBOUND flag. This is necessary
3608 * as scheduler callbacks may be invoked from other cpus.
3613 * Sched callbacks are disabled now. Zap nr_running. After this,
3614 * nr_running stays zero and need_more_worker() and keep_working()
3615 * are always true as long as the worklist is not empty. @gcwq now
3616 * behaves as unbound (in terms of concurrency management) gcwq
3617 * which is served by workers tied to the CPU.
3619 * On return from this function, the current worker would trigger
3620 * unbound chain execution of pending work items if other workers
3623 for_each_worker_pool(pool, gcwq)
3624 atomic_set(get_pool_nr_running(pool), 0);
3628 * Workqueues should be brought up before normal priority CPU notifiers.
3629 * This will be registered high priority CPU notifier.
3631 static int __devinit workqueue_cpu_up_callback(struct notifier_block *nfb,
3632 unsigned long action,
3635 unsigned int cpu = (unsigned long)hcpu;
3636 struct global_cwq *gcwq = get_gcwq(cpu);
3637 struct worker_pool *pool;
3639 switch (action & ~CPU_TASKS_FROZEN) {
3640 case CPU_UP_PREPARE:
3641 for_each_worker_pool(pool, gcwq) {
3642 struct worker *worker;
3644 if (pool->nr_workers)
3647 worker = create_worker(pool);
3651 spin_lock_irq(&gcwq->lock);
3652 start_worker(worker);
3653 spin_unlock_irq(&gcwq->lock);
3657 case CPU_DOWN_FAILED:
3659 gcwq_claim_management_and_lock(gcwq);
3660 gcwq->flags &= ~GCWQ_DISASSOCIATED;
3661 rebind_workers(gcwq);
3662 gcwq_release_management_and_unlock(gcwq);
3669 * Workqueues should be brought down after normal priority CPU notifiers.
3670 * This will be registered as low priority CPU notifier.
3672 static int __devinit workqueue_cpu_down_callback(struct notifier_block *nfb,
3673 unsigned long action,
3676 unsigned int cpu = (unsigned long)hcpu;
3677 struct work_struct unbind_work;
3679 switch (action & ~CPU_TASKS_FROZEN) {
3680 case CPU_DOWN_PREPARE:
3681 /* unbinding should happen on the local CPU */
3682 INIT_WORK_ONSTACK(&unbind_work, gcwq_unbind_fn);
3683 queue_work_on(cpu, system_highpri_wq, &unbind_work);
3684 flush_work(&unbind_work);
3692 struct work_for_cpu {
3693 struct completion completion;
3699 static int do_work_for_cpu(void *_wfc)
3701 struct work_for_cpu *wfc = _wfc;
3702 wfc->ret = wfc->fn(wfc->arg);
3703 complete(&wfc->completion);
3708 * work_on_cpu - run a function in user context on a particular cpu
3709 * @cpu: the cpu to run on
3710 * @fn: the function to run
3711 * @arg: the function arg
3713 * This will return the value @fn returns.
3714 * It is up to the caller to ensure that the cpu doesn't go offline.
3715 * The caller must not hold any locks which would prevent @fn from completing.
3717 long work_on_cpu(unsigned int cpu, long (*fn)(void *), void *arg)
3719 struct task_struct *sub_thread;
3720 struct work_for_cpu wfc = {
3721 .completion = COMPLETION_INITIALIZER_ONSTACK(wfc.completion),
3726 sub_thread = kthread_create(do_work_for_cpu, &wfc, "work_for_cpu");
3727 if (IS_ERR(sub_thread))
3728 return PTR_ERR(sub_thread);
3729 kthread_bind(sub_thread, cpu);
3730 wake_up_process(sub_thread);
3731 wait_for_completion(&wfc.completion);
3734 EXPORT_SYMBOL_GPL(work_on_cpu);
3735 #endif /* CONFIG_SMP */
3737 #ifdef CONFIG_FREEZER
3740 * freeze_workqueues_begin - begin freezing workqueues
3742 * Start freezing workqueues. After this function returns, all freezable
3743 * workqueues will queue new works to their frozen_works list instead of
3747 * Grabs and releases workqueue_lock and gcwq->lock's.
3749 void freeze_workqueues_begin(void)
3753 spin_lock(&workqueue_lock);
3755 BUG_ON(workqueue_freezing);
3756 workqueue_freezing = true;
3758 for_each_gcwq_cpu(cpu) {
3759 struct global_cwq *gcwq = get_gcwq(cpu);
3760 struct workqueue_struct *wq;
3762 spin_lock_irq(&gcwq->lock);
3764 BUG_ON(gcwq->flags & GCWQ_FREEZING);
3765 gcwq->flags |= GCWQ_FREEZING;
3767 list_for_each_entry(wq, &workqueues, list) {
3768 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3770 if (cwq && wq->flags & WQ_FREEZABLE)
3771 cwq->max_active = 0;
3774 spin_unlock_irq(&gcwq->lock);
3777 spin_unlock(&workqueue_lock);
3781 * freeze_workqueues_busy - are freezable workqueues still busy?
3783 * Check whether freezing is complete. This function must be called
3784 * between freeze_workqueues_begin() and thaw_workqueues().
3787 * Grabs and releases workqueue_lock.
3790 * %true if some freezable workqueues are still busy. %false if freezing
3793 bool freeze_workqueues_busy(void)
3798 spin_lock(&workqueue_lock);
3800 BUG_ON(!workqueue_freezing);
3802 for_each_gcwq_cpu(cpu) {
3803 struct workqueue_struct *wq;
3805 * nr_active is monotonically decreasing. It's safe
3806 * to peek without lock.
3808 list_for_each_entry(wq, &workqueues, list) {
3809 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3811 if (!cwq || !(wq->flags & WQ_FREEZABLE))
3814 BUG_ON(cwq->nr_active < 0);
3815 if (cwq->nr_active) {
3822 spin_unlock(&workqueue_lock);
3827 * thaw_workqueues - thaw workqueues
3829 * Thaw workqueues. Normal queueing is restored and all collected
3830 * frozen works are transferred to their respective gcwq worklists.
3833 * Grabs and releases workqueue_lock and gcwq->lock's.
3835 void thaw_workqueues(void)
3839 spin_lock(&workqueue_lock);
3841 if (!workqueue_freezing)
3844 for_each_gcwq_cpu(cpu) {
3845 struct global_cwq *gcwq = get_gcwq(cpu);
3846 struct worker_pool *pool;
3847 struct workqueue_struct *wq;
3849 spin_lock_irq(&gcwq->lock);
3851 BUG_ON(!(gcwq->flags & GCWQ_FREEZING));
3852 gcwq->flags &= ~GCWQ_FREEZING;
3854 list_for_each_entry(wq, &workqueues, list) {
3855 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3857 if (!cwq || !(wq->flags & WQ_FREEZABLE))
3860 /* restore max_active and repopulate worklist */
3861 cwq->max_active = wq->saved_max_active;
3863 while (!list_empty(&cwq->delayed_works) &&
3864 cwq->nr_active < cwq->max_active)
3865 cwq_activate_first_delayed(cwq);
3868 for_each_worker_pool(pool, gcwq)
3869 wake_up_worker(pool);
3871 spin_unlock_irq(&gcwq->lock);
3874 workqueue_freezing = false;
3876 spin_unlock(&workqueue_lock);
3878 #endif /* CONFIG_FREEZER */
3880 static int __init init_workqueues(void)
3885 /* make sure we have enough bits for OFFQ CPU number */
3886 BUILD_BUG_ON((1LU << (BITS_PER_LONG - WORK_OFFQ_CPU_SHIFT)) <
3889 cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
3890 cpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
3892 /* initialize gcwqs */
3893 for_each_gcwq_cpu(cpu) {
3894 struct global_cwq *gcwq = get_gcwq(cpu);
3895 struct worker_pool *pool;
3897 spin_lock_init(&gcwq->lock);
3899 gcwq->flags |= GCWQ_DISASSOCIATED;
3901 for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)
3902 INIT_HLIST_HEAD(&gcwq->busy_hash[i]);
3904 for_each_worker_pool(pool, gcwq) {
3906 INIT_LIST_HEAD(&pool->worklist);
3907 INIT_LIST_HEAD(&pool->idle_list);
3909 init_timer_deferrable(&pool->idle_timer);
3910 pool->idle_timer.function = idle_worker_timeout;
3911 pool->idle_timer.data = (unsigned long)pool;
3913 setup_timer(&pool->mayday_timer, gcwq_mayday_timeout,
3914 (unsigned long)pool);
3916 mutex_init(&pool->manager_mutex);
3917 ida_init(&pool->worker_ida);
3920 init_waitqueue_head(&gcwq->rebind_hold);
3923 /* create the initial worker */
3924 for_each_online_gcwq_cpu(cpu) {
3925 struct global_cwq *gcwq = get_gcwq(cpu);
3926 struct worker_pool *pool;
3928 if (cpu != WORK_CPU_UNBOUND)
3929 gcwq->flags &= ~GCWQ_DISASSOCIATED;
3931 for_each_worker_pool(pool, gcwq) {
3932 struct worker *worker;
3934 worker = create_worker(pool);
3936 spin_lock_irq(&gcwq->lock);
3937 start_worker(worker);
3938 spin_unlock_irq(&gcwq->lock);
3942 system_wq = alloc_workqueue("events", 0, 0);
3943 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
3944 system_long_wq = alloc_workqueue("events_long", 0, 0);
3945 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
3946 WQ_UNBOUND_MAX_ACTIVE);
3947 system_freezable_wq = alloc_workqueue("events_freezable",
3949 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
3950 !system_unbound_wq || !system_freezable_wq);
3953 early_initcall(init_workqueues);