workqueue: make get_work_pool_id() cheaper
[linux-2.6/btrfs-unstable.git] / kernel / workqueue.c
blob1801c37b28c45f49412ee7027d4850702ab5b100
1 /*
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>
8 * Andrew Morton
9 * Kai Petzke <wpp@marie.physik.tu-berlin.de>
10 * Theodore Ts'o <tytso@mit.edu>
12 * Made to use alloc_percpu by Christoph Lameter.
14 * Copyright (C) 2010 SUSE Linux Products GmbH
15 * Copyright (C) 2010 Tejun Heo <tj@kernel.org>
17 * This is the generic async execution mechanism. Work items as are
18 * executed in process context. The worker pool is shared and
19 * automatically managed. There is one worker pool for each CPU and
20 * one extra for works which are better served by workers which are
21 * not bound to any specific CPU.
23 * Please read Documentation/workqueue.txt for details.
26 #include <linux/export.h>
27 #include <linux/kernel.h>
28 #include <linux/sched.h>
29 #include <linux/init.h>
30 #include <linux/signal.h>
31 #include <linux/completion.h>
32 #include <linux/workqueue.h>
33 #include <linux/slab.h>
34 #include <linux/cpu.h>
35 #include <linux/notifier.h>
36 #include <linux/kthread.h>
37 #include <linux/hardirq.h>
38 #include <linux/mempolicy.h>
39 #include <linux/freezer.h>
40 #include <linux/kallsyms.h>
41 #include <linux/debug_locks.h>
42 #include <linux/lockdep.h>
43 #include <linux/idr.h>
44 #include <linux/hashtable.h>
46 #include "workqueue_internal.h"
48 enum {
50 * worker_pool flags
52 * A bound pool is either associated or disassociated with its CPU.
53 * While associated (!DISASSOCIATED), all workers are bound to the
54 * CPU and none has %WORKER_UNBOUND set and concurrency management
55 * is in effect.
57 * While DISASSOCIATED, the cpu may be offline and all workers have
58 * %WORKER_UNBOUND set and concurrency management disabled, and may
59 * be executing on any CPU. The pool behaves as an unbound one.
61 * Note that DISASSOCIATED can be flipped only while holding
62 * assoc_mutex to avoid changing binding state while
63 * create_worker() is in progress.
65 POOL_MANAGE_WORKERS = 1 << 0, /* need to manage workers */
66 POOL_MANAGING_WORKERS = 1 << 1, /* managing workers */
67 POOL_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
68 POOL_FREEZING = 1 << 3, /* freeze in progress */
70 /* worker flags */
71 WORKER_STARTED = 1 << 0, /* started */
72 WORKER_DIE = 1 << 1, /* die die die */
73 WORKER_IDLE = 1 << 2, /* is idle */
74 WORKER_PREP = 1 << 3, /* preparing to run works */
75 WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
76 WORKER_UNBOUND = 1 << 7, /* worker is unbound */
78 WORKER_NOT_RUNNING = WORKER_PREP | WORKER_UNBOUND |
79 WORKER_CPU_INTENSIVE,
81 NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */
83 BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
85 MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
86 IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
88 MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
89 /* call for help after 10ms
90 (min two ticks) */
91 MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
92 CREATE_COOLDOWN = HZ, /* time to breath after fail */
95 * Rescue workers are used only on emergencies and shared by
96 * all cpus. Give -20.
98 RESCUER_NICE_LEVEL = -20,
99 HIGHPRI_NICE_LEVEL = -20,
103 * Structure fields follow one of the following exclusion rules.
105 * I: Modifiable by initialization/destruction paths and read-only for
106 * everyone else.
108 * P: Preemption protected. Disabling preemption is enough and should
109 * only be modified and accessed from the local cpu.
111 * L: pool->lock protected. Access with pool->lock held.
113 * X: During normal operation, modification requires pool->lock and should
114 * be done only from local cpu. Either disabling preemption on local
115 * cpu or grabbing pool->lock is enough for read access. If
116 * POOL_DISASSOCIATED is set, it's identical to L.
118 * F: wq->flush_mutex protected.
120 * W: workqueue_lock protected.
123 /* struct worker is defined in workqueue_internal.h */
125 struct worker_pool {
126 spinlock_t lock; /* the pool lock */
127 unsigned int cpu; /* I: the associated cpu */
128 int id; /* I: pool ID */
129 unsigned int flags; /* X: flags */
131 struct list_head worklist; /* L: list of pending works */
132 int nr_workers; /* L: total number of workers */
134 /* nr_idle includes the ones off idle_list for rebinding */
135 int nr_idle; /* L: currently idle ones */
137 struct list_head idle_list; /* X: list of idle workers */
138 struct timer_list idle_timer; /* L: worker idle timeout */
139 struct timer_list mayday_timer; /* L: SOS timer for workers */
141 /* workers are chained either in busy_hash or idle_list */
142 DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
143 /* L: hash of busy workers */
145 struct mutex assoc_mutex; /* protect POOL_DISASSOCIATED */
146 struct ida worker_ida; /* L: for worker IDs */
149 * The current concurrency level. As it's likely to be accessed
150 * from other CPUs during try_to_wake_up(), put it in a separate
151 * cacheline.
153 atomic_t nr_running ____cacheline_aligned_in_smp;
154 } ____cacheline_aligned_in_smp;
157 * The per-CPU workqueue. The lower WORK_STRUCT_FLAG_BITS of
158 * work_struct->data are used for flags and thus cwqs need to be
159 * aligned at two's power of the number of flag bits.
161 struct cpu_workqueue_struct {
162 struct worker_pool *pool; /* I: the associated pool */
163 struct workqueue_struct *wq; /* I: the owning workqueue */
164 int work_color; /* L: current color */
165 int flush_color; /* L: flushing color */
166 int nr_in_flight[WORK_NR_COLORS];
167 /* L: nr of in_flight works */
168 int nr_active; /* L: nr of active works */
169 int max_active; /* L: max active works */
170 struct list_head delayed_works; /* L: delayed works */
174 * Structure used to wait for workqueue flush.
176 struct wq_flusher {
177 struct list_head list; /* F: list of flushers */
178 int flush_color; /* F: flush color waiting for */
179 struct completion done; /* flush completion */
183 * All cpumasks are assumed to be always set on UP and thus can't be
184 * used to determine whether there's something to be done.
186 #ifdef CONFIG_SMP
187 typedef cpumask_var_t mayday_mask_t;
188 #define mayday_test_and_set_cpu(cpu, mask) \
189 cpumask_test_and_set_cpu((cpu), (mask))
190 #define mayday_clear_cpu(cpu, mask) cpumask_clear_cpu((cpu), (mask))
191 #define for_each_mayday_cpu(cpu, mask) for_each_cpu((cpu), (mask))
192 #define alloc_mayday_mask(maskp, gfp) zalloc_cpumask_var((maskp), (gfp))
193 #define free_mayday_mask(mask) free_cpumask_var((mask))
194 #else
195 typedef unsigned long mayday_mask_t;
196 #define mayday_test_and_set_cpu(cpu, mask) test_and_set_bit(0, &(mask))
197 #define mayday_clear_cpu(cpu, mask) clear_bit(0, &(mask))
198 #define for_each_mayday_cpu(cpu, mask) if ((cpu) = 0, (mask))
199 #define alloc_mayday_mask(maskp, gfp) true
200 #define free_mayday_mask(mask) do { } while (0)
201 #endif
204 * The externally visible workqueue abstraction is an array of
205 * per-CPU workqueues:
207 struct workqueue_struct {
208 unsigned int flags; /* W: WQ_* flags */
209 union {
210 struct cpu_workqueue_struct __percpu *pcpu;
211 struct cpu_workqueue_struct *single;
212 unsigned long v;
213 } cpu_wq; /* I: cwq's */
214 struct list_head list; /* W: list of all workqueues */
216 struct mutex flush_mutex; /* protects wq flushing */
217 int work_color; /* F: current work color */
218 int flush_color; /* F: current flush color */
219 atomic_t nr_cwqs_to_flush; /* flush in progress */
220 struct wq_flusher *first_flusher; /* F: first flusher */
221 struct list_head flusher_queue; /* F: flush waiters */
222 struct list_head flusher_overflow; /* F: flush overflow list */
224 mayday_mask_t mayday_mask; /* cpus requesting rescue */
225 struct worker *rescuer; /* I: rescue worker */
227 int nr_drainers; /* W: drain in progress */
228 int saved_max_active; /* W: saved cwq max_active */
229 #ifdef CONFIG_LOCKDEP
230 struct lockdep_map lockdep_map;
231 #endif
232 char name[]; /* I: workqueue name */
235 struct workqueue_struct *system_wq __read_mostly;
236 EXPORT_SYMBOL_GPL(system_wq);
237 struct workqueue_struct *system_highpri_wq __read_mostly;
238 EXPORT_SYMBOL_GPL(system_highpri_wq);
239 struct workqueue_struct *system_long_wq __read_mostly;
240 EXPORT_SYMBOL_GPL(system_long_wq);
241 struct workqueue_struct *system_unbound_wq __read_mostly;
242 EXPORT_SYMBOL_GPL(system_unbound_wq);
243 struct workqueue_struct *system_freezable_wq __read_mostly;
244 EXPORT_SYMBOL_GPL(system_freezable_wq);
246 #define CREATE_TRACE_POINTS
247 #include <trace/events/workqueue.h>
249 #define for_each_std_worker_pool(pool, cpu) \
250 for ((pool) = &std_worker_pools(cpu)[0]; \
251 (pool) < &std_worker_pools(cpu)[NR_STD_WORKER_POOLS]; (pool)++)
253 #define for_each_busy_worker(worker, i, pos, pool) \
254 hash_for_each(pool->busy_hash, i, pos, worker, hentry)
256 static inline int __next_wq_cpu(int cpu, const struct cpumask *mask,
257 unsigned int sw)
259 if (cpu < nr_cpu_ids) {
260 if (sw & 1) {
261 cpu = cpumask_next(cpu, mask);
262 if (cpu < nr_cpu_ids)
263 return cpu;
265 if (sw & 2)
266 return WORK_CPU_UNBOUND;
268 return WORK_CPU_END;
271 static inline int __next_cwq_cpu(int cpu, const struct cpumask *mask,
272 struct workqueue_struct *wq)
274 return __next_wq_cpu(cpu, mask, !(wq->flags & WQ_UNBOUND) ? 1 : 2);
278 * CPU iterators
280 * An extra cpu number is defined using an invalid cpu number
281 * (WORK_CPU_UNBOUND) to host workqueues which are not bound to any
282 * specific CPU. The following iterators are similar to for_each_*_cpu()
283 * iterators but also considers the unbound CPU.
285 * for_each_wq_cpu() : possible CPUs + WORK_CPU_UNBOUND
286 * for_each_online_wq_cpu() : online CPUs + WORK_CPU_UNBOUND
287 * for_each_cwq_cpu() : possible CPUs for bound workqueues,
288 * WORK_CPU_UNBOUND for unbound workqueues
290 #define for_each_wq_cpu(cpu) \
291 for ((cpu) = __next_wq_cpu(-1, cpu_possible_mask, 3); \
292 (cpu) < WORK_CPU_END; \
293 (cpu) = __next_wq_cpu((cpu), cpu_possible_mask, 3))
295 #define for_each_online_wq_cpu(cpu) \
296 for ((cpu) = __next_wq_cpu(-1, cpu_online_mask, 3); \
297 (cpu) < WORK_CPU_END; \
298 (cpu) = __next_wq_cpu((cpu), cpu_online_mask, 3))
300 #define for_each_cwq_cpu(cpu, wq) \
301 for ((cpu) = __next_cwq_cpu(-1, cpu_possible_mask, (wq)); \
302 (cpu) < WORK_CPU_END; \
303 (cpu) = __next_cwq_cpu((cpu), cpu_possible_mask, (wq)))
305 #ifdef CONFIG_DEBUG_OBJECTS_WORK
307 static struct debug_obj_descr work_debug_descr;
309 static void *work_debug_hint(void *addr)
311 return ((struct work_struct *) addr)->func;
315 * fixup_init is called when:
316 * - an active object is initialized
318 static int work_fixup_init(void *addr, enum debug_obj_state state)
320 struct work_struct *work = addr;
322 switch (state) {
323 case ODEBUG_STATE_ACTIVE:
324 cancel_work_sync(work);
325 debug_object_init(work, &work_debug_descr);
326 return 1;
327 default:
328 return 0;
333 * fixup_activate is called when:
334 * - an active object is activated
335 * - an unknown object is activated (might be a statically initialized object)
337 static int work_fixup_activate(void *addr, enum debug_obj_state state)
339 struct work_struct *work = addr;
341 switch (state) {
343 case ODEBUG_STATE_NOTAVAILABLE:
345 * This is not really a fixup. The work struct was
346 * statically initialized. We just make sure that it
347 * is tracked in the object tracker.
349 if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
350 debug_object_init(work, &work_debug_descr);
351 debug_object_activate(work, &work_debug_descr);
352 return 0;
354 WARN_ON_ONCE(1);
355 return 0;
357 case ODEBUG_STATE_ACTIVE:
358 WARN_ON(1);
360 default:
361 return 0;
366 * fixup_free is called when:
367 * - an active object is freed
369 static int work_fixup_free(void *addr, enum debug_obj_state state)
371 struct work_struct *work = addr;
373 switch (state) {
374 case ODEBUG_STATE_ACTIVE:
375 cancel_work_sync(work);
376 debug_object_free(work, &work_debug_descr);
377 return 1;
378 default:
379 return 0;
383 static struct debug_obj_descr work_debug_descr = {
384 .name = "work_struct",
385 .debug_hint = work_debug_hint,
386 .fixup_init = work_fixup_init,
387 .fixup_activate = work_fixup_activate,
388 .fixup_free = work_fixup_free,
391 static inline void debug_work_activate(struct work_struct *work)
393 debug_object_activate(work, &work_debug_descr);
396 static inline void debug_work_deactivate(struct work_struct *work)
398 debug_object_deactivate(work, &work_debug_descr);
401 void __init_work(struct work_struct *work, int onstack)
403 if (onstack)
404 debug_object_init_on_stack(work, &work_debug_descr);
405 else
406 debug_object_init(work, &work_debug_descr);
408 EXPORT_SYMBOL_GPL(__init_work);
410 void destroy_work_on_stack(struct work_struct *work)
412 debug_object_free(work, &work_debug_descr);
414 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
416 #else
417 static inline void debug_work_activate(struct work_struct *work) { }
418 static inline void debug_work_deactivate(struct work_struct *work) { }
419 #endif
421 /* Serializes the accesses to the list of workqueues. */
422 static DEFINE_SPINLOCK(workqueue_lock);
423 static LIST_HEAD(workqueues);
424 static bool workqueue_freezing; /* W: have wqs started freezing? */
427 * The CPU and unbound standard worker pools. The unbound ones have
428 * POOL_DISASSOCIATED set, and their workers have WORKER_UNBOUND set.
430 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
431 cpu_std_worker_pools);
432 static struct worker_pool unbound_std_worker_pools[NR_STD_WORKER_POOLS];
434 /* idr of all pools */
435 static DEFINE_MUTEX(worker_pool_idr_mutex);
436 static DEFINE_IDR(worker_pool_idr);
438 static int worker_thread(void *__worker);
440 static struct worker_pool *std_worker_pools(int cpu)
442 if (cpu != WORK_CPU_UNBOUND)
443 return per_cpu(cpu_std_worker_pools, cpu);
444 else
445 return unbound_std_worker_pools;
448 static int std_worker_pool_pri(struct worker_pool *pool)
450 return pool - std_worker_pools(pool->cpu);
453 /* allocate ID and assign it to @pool */
454 static int worker_pool_assign_id(struct worker_pool *pool)
456 int ret;
458 mutex_lock(&worker_pool_idr_mutex);
459 idr_pre_get(&worker_pool_idr, GFP_KERNEL);
460 ret = idr_get_new(&worker_pool_idr, pool, &pool->id);
461 mutex_unlock(&worker_pool_idr_mutex);
463 return ret;
467 * Lookup worker_pool by id. The idr currently is built during boot and
468 * never modified. Don't worry about locking for now.
470 static struct worker_pool *worker_pool_by_id(int pool_id)
472 return idr_find(&worker_pool_idr, pool_id);
475 static struct worker_pool *get_std_worker_pool(int cpu, bool highpri)
477 struct worker_pool *pools = std_worker_pools(cpu);
479 return &pools[highpri];
482 static struct cpu_workqueue_struct *get_cwq(unsigned int cpu,
483 struct workqueue_struct *wq)
485 if (!(wq->flags & WQ_UNBOUND)) {
486 if (likely(cpu < nr_cpu_ids))
487 return per_cpu_ptr(wq->cpu_wq.pcpu, cpu);
488 } else if (likely(cpu == WORK_CPU_UNBOUND))
489 return wq->cpu_wq.single;
490 return NULL;
493 static unsigned int work_color_to_flags(int color)
495 return color << WORK_STRUCT_COLOR_SHIFT;
498 static int get_work_color(struct work_struct *work)
500 return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
501 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
504 static int work_next_color(int color)
506 return (color + 1) % WORK_NR_COLORS;
510 * While queued, %WORK_STRUCT_CWQ is set and non flag bits of a work's data
511 * contain the pointer to the queued cwq. Once execution starts, the flag
512 * is cleared and the high bits contain OFFQ flags and pool ID.
514 * set_work_cwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
515 * and clear_work_data() can be used to set the cwq, pool or clear
516 * work->data. These functions should only be called while the work is
517 * owned - ie. while the PENDING bit is set.
519 * get_work_pool() and get_work_cwq() can be used to obtain the pool or cwq
520 * corresponding to a work. Pool is available once the work has been
521 * queued anywhere after initialization until it is sync canceled. cwq is
522 * available only while the work item is queued.
524 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
525 * canceled. While being canceled, a work item may have its PENDING set
526 * but stay off timer and worklist for arbitrarily long and nobody should
527 * try to steal the PENDING bit.
529 static inline void set_work_data(struct work_struct *work, unsigned long data,
530 unsigned long flags)
532 BUG_ON(!work_pending(work));
533 atomic_long_set(&work->data, data | flags | work_static(work));
536 static void set_work_cwq(struct work_struct *work,
537 struct cpu_workqueue_struct *cwq,
538 unsigned long extra_flags)
540 set_work_data(work, (unsigned long)cwq,
541 WORK_STRUCT_PENDING | WORK_STRUCT_CWQ | extra_flags);
544 static void set_work_pool_and_keep_pending(struct work_struct *work,
545 int pool_id)
547 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
548 WORK_STRUCT_PENDING);
551 static void set_work_pool_and_clear_pending(struct work_struct *work,
552 int pool_id)
555 * The following wmb is paired with the implied mb in
556 * test_and_set_bit(PENDING) and ensures all updates to @work made
557 * here are visible to and precede any updates by the next PENDING
558 * owner.
560 smp_wmb();
561 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
564 static void clear_work_data(struct work_struct *work)
566 smp_wmb(); /* see set_work_pool_and_clear_pending() */
567 set_work_data(work, WORK_STRUCT_NO_POOL, 0);
570 static struct cpu_workqueue_struct *get_work_cwq(struct work_struct *work)
572 unsigned long data = atomic_long_read(&work->data);
574 if (data & WORK_STRUCT_CWQ)
575 return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
576 else
577 return NULL;
581 * get_work_pool - return the worker_pool a given work was associated with
582 * @work: the work item of interest
584 * Return the worker_pool @work was last associated with. %NULL if none.
586 static struct worker_pool *get_work_pool(struct work_struct *work)
588 unsigned long data = atomic_long_read(&work->data);
589 struct worker_pool *pool;
590 int pool_id;
592 if (data & WORK_STRUCT_CWQ)
593 return ((struct cpu_workqueue_struct *)
594 (data & WORK_STRUCT_WQ_DATA_MASK))->pool;
596 pool_id = data >> WORK_OFFQ_POOL_SHIFT;
597 if (pool_id == WORK_OFFQ_POOL_NONE)
598 return NULL;
600 pool = worker_pool_by_id(pool_id);
601 WARN_ON_ONCE(!pool);
602 return pool;
606 * get_work_pool_id - return the worker pool ID a given work is associated with
607 * @work: the work item of interest
609 * Return the worker_pool ID @work was last associated with.
610 * %WORK_OFFQ_POOL_NONE if none.
612 static int get_work_pool_id(struct work_struct *work)
614 unsigned long data = atomic_long_read(&work->data);
616 if (data & WORK_STRUCT_CWQ)
617 return ((struct cpu_workqueue_struct *)
618 (data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
620 return data >> WORK_OFFQ_POOL_SHIFT;
623 static void mark_work_canceling(struct work_struct *work)
625 unsigned long pool_id = get_work_pool_id(work);
627 pool_id <<= WORK_OFFQ_POOL_SHIFT;
628 set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
631 static bool work_is_canceling(struct work_struct *work)
633 unsigned long data = atomic_long_read(&work->data);
635 return !(data & WORK_STRUCT_CWQ) && (data & WORK_OFFQ_CANCELING);
639 * Policy functions. These define the policies on how the global worker
640 * pools are managed. Unless noted otherwise, these functions assume that
641 * they're being called with pool->lock held.
644 static bool __need_more_worker(struct worker_pool *pool)
646 return !atomic_read(&pool->nr_running);
650 * Need to wake up a worker? Called from anything but currently
651 * running workers.
653 * Note that, because unbound workers never contribute to nr_running, this
654 * function will always return %true for unbound pools as long as the
655 * worklist isn't empty.
657 static bool need_more_worker(struct worker_pool *pool)
659 return !list_empty(&pool->worklist) && __need_more_worker(pool);
662 /* Can I start working? Called from busy but !running workers. */
663 static bool may_start_working(struct worker_pool *pool)
665 return pool->nr_idle;
668 /* Do I need to keep working? Called from currently running workers. */
669 static bool keep_working(struct worker_pool *pool)
671 return !list_empty(&pool->worklist) &&
672 atomic_read(&pool->nr_running) <= 1;
675 /* Do we need a new worker? Called from manager. */
676 static bool need_to_create_worker(struct worker_pool *pool)
678 return need_more_worker(pool) && !may_start_working(pool);
681 /* Do I need to be the manager? */
682 static bool need_to_manage_workers(struct worker_pool *pool)
684 return need_to_create_worker(pool) ||
685 (pool->flags & POOL_MANAGE_WORKERS);
688 /* Do we have too many workers and should some go away? */
689 static bool too_many_workers(struct worker_pool *pool)
691 bool managing = pool->flags & POOL_MANAGING_WORKERS;
692 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
693 int nr_busy = pool->nr_workers - nr_idle;
696 * nr_idle and idle_list may disagree if idle rebinding is in
697 * progress. Never return %true if idle_list is empty.
699 if (list_empty(&pool->idle_list))
700 return false;
702 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
706 * Wake up functions.
709 /* Return the first worker. Safe with preemption disabled */
710 static struct worker *first_worker(struct worker_pool *pool)
712 if (unlikely(list_empty(&pool->idle_list)))
713 return NULL;
715 return list_first_entry(&pool->idle_list, struct worker, entry);
719 * wake_up_worker - wake up an idle worker
720 * @pool: worker pool to wake worker from
722 * Wake up the first idle worker of @pool.
724 * CONTEXT:
725 * spin_lock_irq(pool->lock).
727 static void wake_up_worker(struct worker_pool *pool)
729 struct worker *worker = first_worker(pool);
731 if (likely(worker))
732 wake_up_process(worker->task);
736 * wq_worker_waking_up - a worker is waking up
737 * @task: task waking up
738 * @cpu: CPU @task is waking up to
740 * This function is called during try_to_wake_up() when a worker is
741 * being awoken.
743 * CONTEXT:
744 * spin_lock_irq(rq->lock)
746 void wq_worker_waking_up(struct task_struct *task, unsigned int cpu)
748 struct worker *worker = kthread_data(task);
750 if (!(worker->flags & WORKER_NOT_RUNNING)) {
751 WARN_ON_ONCE(worker->pool->cpu != cpu);
752 atomic_inc(&worker->pool->nr_running);
757 * wq_worker_sleeping - a worker is going to sleep
758 * @task: task going to sleep
759 * @cpu: CPU in question, must be the current CPU number
761 * This function is called during schedule() when a busy worker is
762 * going to sleep. Worker on the same cpu can be woken up by
763 * returning pointer to its task.
765 * CONTEXT:
766 * spin_lock_irq(rq->lock)
768 * RETURNS:
769 * Worker task on @cpu to wake up, %NULL if none.
771 struct task_struct *wq_worker_sleeping(struct task_struct *task,
772 unsigned int cpu)
774 struct worker *worker = kthread_data(task), *to_wakeup = NULL;
775 struct worker_pool *pool;
778 * Rescuers, which may not have all the fields set up like normal
779 * workers, also reach here, let's not access anything before
780 * checking NOT_RUNNING.
782 if (worker->flags & WORKER_NOT_RUNNING)
783 return NULL;
785 pool = worker->pool;
787 /* this can only happen on the local cpu */
788 BUG_ON(cpu != raw_smp_processor_id());
791 * The counterpart of the following dec_and_test, implied mb,
792 * worklist not empty test sequence is in insert_work().
793 * Please read comment there.
795 * NOT_RUNNING is clear. This means that we're bound to and
796 * running on the local cpu w/ rq lock held and preemption
797 * disabled, which in turn means that none else could be
798 * manipulating idle_list, so dereferencing idle_list without pool
799 * lock is safe.
801 if (atomic_dec_and_test(&pool->nr_running) &&
802 !list_empty(&pool->worklist))
803 to_wakeup = first_worker(pool);
804 return to_wakeup ? to_wakeup->task : NULL;
808 * worker_set_flags - set worker flags and adjust nr_running accordingly
809 * @worker: self
810 * @flags: flags to set
811 * @wakeup: wakeup an idle worker if necessary
813 * Set @flags in @worker->flags and adjust nr_running accordingly. If
814 * nr_running becomes zero and @wakeup is %true, an idle worker is
815 * woken up.
817 * CONTEXT:
818 * spin_lock_irq(pool->lock)
820 static inline void worker_set_flags(struct worker *worker, unsigned int flags,
821 bool wakeup)
823 struct worker_pool *pool = worker->pool;
825 WARN_ON_ONCE(worker->task != current);
828 * If transitioning into NOT_RUNNING, adjust nr_running and
829 * wake up an idle worker as necessary if requested by
830 * @wakeup.
832 if ((flags & WORKER_NOT_RUNNING) &&
833 !(worker->flags & WORKER_NOT_RUNNING)) {
834 if (wakeup) {
835 if (atomic_dec_and_test(&pool->nr_running) &&
836 !list_empty(&pool->worklist))
837 wake_up_worker(pool);
838 } else
839 atomic_dec(&pool->nr_running);
842 worker->flags |= flags;
846 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
847 * @worker: self
848 * @flags: flags to clear
850 * Clear @flags in @worker->flags and adjust nr_running accordingly.
852 * CONTEXT:
853 * spin_lock_irq(pool->lock)
855 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
857 struct worker_pool *pool = worker->pool;
858 unsigned int oflags = worker->flags;
860 WARN_ON_ONCE(worker->task != current);
862 worker->flags &= ~flags;
865 * If transitioning out of NOT_RUNNING, increment nr_running. Note
866 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
867 * of multiple flags, not a single flag.
869 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
870 if (!(worker->flags & WORKER_NOT_RUNNING))
871 atomic_inc(&pool->nr_running);
875 * find_worker_executing_work - find worker which is executing a work
876 * @pool: pool of interest
877 * @work: work to find worker for
879 * Find a worker which is executing @work on @pool by searching
880 * @pool->busy_hash which is keyed by the address of @work. For a worker
881 * to match, its current execution should match the address of @work and
882 * its work function. This is to avoid unwanted dependency between
883 * unrelated work executions through a work item being recycled while still
884 * being executed.
886 * This is a bit tricky. A work item may be freed once its execution
887 * starts and nothing prevents the freed area from being recycled for
888 * another work item. If the same work item address ends up being reused
889 * before the original execution finishes, workqueue will identify the
890 * recycled work item as currently executing and make it wait until the
891 * current execution finishes, introducing an unwanted dependency.
893 * This function checks the work item address, work function and workqueue
894 * to avoid false positives. Note that this isn't complete as one may
895 * construct a work function which can introduce dependency onto itself
896 * through a recycled work item. Well, if somebody wants to shoot oneself
897 * in the foot that badly, there's only so much we can do, and if such
898 * deadlock actually occurs, it should be easy to locate the culprit work
899 * function.
901 * CONTEXT:
902 * spin_lock_irq(pool->lock).
904 * RETURNS:
905 * Pointer to worker which is executing @work if found, NULL
906 * otherwise.
908 static struct worker *find_worker_executing_work(struct worker_pool *pool,
909 struct work_struct *work)
911 struct worker *worker;
912 struct hlist_node *tmp;
914 hash_for_each_possible(pool->busy_hash, worker, tmp, hentry,
915 (unsigned long)work)
916 if (worker->current_work == work &&
917 worker->current_func == work->func)
918 return worker;
920 return NULL;
924 * move_linked_works - move linked works to a list
925 * @work: start of series of works to be scheduled
926 * @head: target list to append @work to
927 * @nextp: out paramter for nested worklist walking
929 * Schedule linked works starting from @work to @head. Work series to
930 * be scheduled starts at @work and includes any consecutive work with
931 * WORK_STRUCT_LINKED set in its predecessor.
933 * If @nextp is not NULL, it's updated to point to the next work of
934 * the last scheduled work. This allows move_linked_works() to be
935 * nested inside outer list_for_each_entry_safe().
937 * CONTEXT:
938 * spin_lock_irq(pool->lock).
940 static void move_linked_works(struct work_struct *work, struct list_head *head,
941 struct work_struct **nextp)
943 struct work_struct *n;
946 * Linked worklist will always end before the end of the list,
947 * use NULL for list head.
949 list_for_each_entry_safe_from(work, n, NULL, entry) {
950 list_move_tail(&work->entry, head);
951 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
952 break;
956 * If we're already inside safe list traversal and have moved
957 * multiple works to the scheduled queue, the next position
958 * needs to be updated.
960 if (nextp)
961 *nextp = n;
964 static void cwq_activate_delayed_work(struct work_struct *work)
966 struct cpu_workqueue_struct *cwq = get_work_cwq(work);
968 trace_workqueue_activate_work(work);
969 move_linked_works(work, &cwq->pool->worklist, NULL);
970 __clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
971 cwq->nr_active++;
974 static void cwq_activate_first_delayed(struct cpu_workqueue_struct *cwq)
976 struct work_struct *work = list_first_entry(&cwq->delayed_works,
977 struct work_struct, entry);
979 cwq_activate_delayed_work(work);
983 * cwq_dec_nr_in_flight - decrement cwq's nr_in_flight
984 * @cwq: cwq of interest
985 * @color: color of work which left the queue
987 * A work either has completed or is removed from pending queue,
988 * decrement nr_in_flight of its cwq and handle workqueue flushing.
990 * CONTEXT:
991 * spin_lock_irq(pool->lock).
993 static void cwq_dec_nr_in_flight(struct cpu_workqueue_struct *cwq, int color)
995 /* ignore uncolored works */
996 if (color == WORK_NO_COLOR)
997 return;
999 cwq->nr_in_flight[color]--;
1001 cwq->nr_active--;
1002 if (!list_empty(&cwq->delayed_works)) {
1003 /* one down, submit a delayed one */
1004 if (cwq->nr_active < cwq->max_active)
1005 cwq_activate_first_delayed(cwq);
1008 /* is flush in progress and are we at the flushing tip? */
1009 if (likely(cwq->flush_color != color))
1010 return;
1012 /* are there still in-flight works? */
1013 if (cwq->nr_in_flight[color])
1014 return;
1016 /* this cwq is done, clear flush_color */
1017 cwq->flush_color = -1;
1020 * If this was the last cwq, wake up the first flusher. It
1021 * will handle the rest.
1023 if (atomic_dec_and_test(&cwq->wq->nr_cwqs_to_flush))
1024 complete(&cwq->wq->first_flusher->done);
1028 * try_to_grab_pending - steal work item from worklist and disable irq
1029 * @work: work item to steal
1030 * @is_dwork: @work is a delayed_work
1031 * @flags: place to store irq state
1033 * Try to grab PENDING bit of @work. This function can handle @work in any
1034 * stable state - idle, on timer or on worklist. Return values are
1036 * 1 if @work was pending and we successfully stole PENDING
1037 * 0 if @work was idle and we claimed PENDING
1038 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1039 * -ENOENT if someone else is canceling @work, this state may persist
1040 * for arbitrarily long
1042 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1043 * interrupted while holding PENDING and @work off queue, irq must be
1044 * disabled on entry. This, combined with delayed_work->timer being
1045 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1047 * On successful return, >= 0, irq is disabled and the caller is
1048 * responsible for releasing it using local_irq_restore(*@flags).
1050 * This function is safe to call from any context including IRQ handler.
1052 static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1053 unsigned long *flags)
1055 struct worker_pool *pool;
1056 struct cpu_workqueue_struct *cwq;
1058 local_irq_save(*flags);
1060 /* try to steal the timer if it exists */
1061 if (is_dwork) {
1062 struct delayed_work *dwork = to_delayed_work(work);
1065 * dwork->timer is irqsafe. If del_timer() fails, it's
1066 * guaranteed that the timer is not queued anywhere and not
1067 * running on the local CPU.
1069 if (likely(del_timer(&dwork->timer)))
1070 return 1;
1073 /* try to claim PENDING the normal way */
1074 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1075 return 0;
1078 * The queueing is in progress, or it is already queued. Try to
1079 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1081 pool = get_work_pool(work);
1082 if (!pool)
1083 goto fail;
1085 spin_lock(&pool->lock);
1087 * work->data is guaranteed to point to cwq only while the work
1088 * item is queued on cwq->wq, and both updating work->data to point
1089 * to cwq on queueing and to pool on dequeueing are done under
1090 * cwq->pool->lock. This in turn guarantees that, if work->data
1091 * points to cwq which is associated with a locked pool, the work
1092 * item is currently queued on that pool.
1094 cwq = get_work_cwq(work);
1095 if (cwq && cwq->pool == pool) {
1096 debug_work_deactivate(work);
1099 * A delayed work item cannot be grabbed directly because
1100 * it might have linked NO_COLOR work items which, if left
1101 * on the delayed_list, will confuse cwq->nr_active
1102 * management later on and cause stall. Make sure the work
1103 * item is activated before grabbing.
1105 if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1106 cwq_activate_delayed_work(work);
1108 list_del_init(&work->entry);
1109 cwq_dec_nr_in_flight(get_work_cwq(work), get_work_color(work));
1111 /* work->data points to cwq iff queued, point to pool */
1112 set_work_pool_and_keep_pending(work, pool->id);
1114 spin_unlock(&pool->lock);
1115 return 1;
1117 spin_unlock(&pool->lock);
1118 fail:
1119 local_irq_restore(*flags);
1120 if (work_is_canceling(work))
1121 return -ENOENT;
1122 cpu_relax();
1123 return -EAGAIN;
1127 * insert_work - insert a work into a pool
1128 * @cwq: cwq @work belongs to
1129 * @work: work to insert
1130 * @head: insertion point
1131 * @extra_flags: extra WORK_STRUCT_* flags to set
1133 * Insert @work which belongs to @cwq after @head. @extra_flags is or'd to
1134 * work_struct flags.
1136 * CONTEXT:
1137 * spin_lock_irq(pool->lock).
1139 static void insert_work(struct cpu_workqueue_struct *cwq,
1140 struct work_struct *work, struct list_head *head,
1141 unsigned int extra_flags)
1143 struct worker_pool *pool = cwq->pool;
1145 /* we own @work, set data and link */
1146 set_work_cwq(work, cwq, extra_flags);
1147 list_add_tail(&work->entry, head);
1150 * Ensure either worker_sched_deactivated() sees the above
1151 * list_add_tail() or we see zero nr_running to avoid workers
1152 * lying around lazily while there are works to be processed.
1154 smp_mb();
1156 if (__need_more_worker(pool))
1157 wake_up_worker(pool);
1161 * Test whether @work is being queued from another work executing on the
1162 * same workqueue. This is rather expensive and should only be used from
1163 * cold paths.
1165 static bool is_chained_work(struct workqueue_struct *wq)
1167 unsigned long flags;
1168 unsigned int cpu;
1170 for_each_wq_cpu(cpu) {
1171 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
1172 struct worker_pool *pool = cwq->pool;
1173 struct worker *worker;
1174 struct hlist_node *pos;
1175 int i;
1177 spin_lock_irqsave(&pool->lock, flags);
1178 for_each_busy_worker(worker, i, pos, pool) {
1179 if (worker->task != current)
1180 continue;
1181 spin_unlock_irqrestore(&pool->lock, flags);
1183 * I'm @worker, no locking necessary. See if @work
1184 * is headed to the same workqueue.
1186 return worker->current_cwq->wq == wq;
1188 spin_unlock_irqrestore(&pool->lock, flags);
1190 return false;
1193 static void __queue_work(unsigned int cpu, struct workqueue_struct *wq,
1194 struct work_struct *work)
1196 bool highpri = wq->flags & WQ_HIGHPRI;
1197 struct worker_pool *pool;
1198 struct cpu_workqueue_struct *cwq;
1199 struct list_head *worklist;
1200 unsigned int work_flags;
1201 unsigned int req_cpu = cpu;
1204 * While a work item is PENDING && off queue, a task trying to
1205 * steal the PENDING will busy-loop waiting for it to either get
1206 * queued or lose PENDING. Grabbing PENDING and queueing should
1207 * happen with IRQ disabled.
1209 WARN_ON_ONCE(!irqs_disabled());
1211 debug_work_activate(work);
1213 /* if dying, only works from the same workqueue are allowed */
1214 if (unlikely(wq->flags & WQ_DRAINING) &&
1215 WARN_ON_ONCE(!is_chained_work(wq)))
1216 return;
1218 /* determine pool to use */
1219 if (!(wq->flags & WQ_UNBOUND)) {
1220 struct worker_pool *last_pool;
1222 if (cpu == WORK_CPU_UNBOUND)
1223 cpu = raw_smp_processor_id();
1226 * It's multi cpu. If @work was previously on a different
1227 * cpu, it might still be running there, in which case the
1228 * work needs to be queued on that cpu to guarantee
1229 * non-reentrancy.
1231 pool = get_std_worker_pool(cpu, highpri);
1232 last_pool = get_work_pool(work);
1234 if (last_pool && last_pool != pool) {
1235 struct worker *worker;
1237 spin_lock(&last_pool->lock);
1239 worker = find_worker_executing_work(last_pool, work);
1241 if (worker && worker->current_cwq->wq == wq)
1242 pool = last_pool;
1243 else {
1244 /* meh... not running there, queue here */
1245 spin_unlock(&last_pool->lock);
1246 spin_lock(&pool->lock);
1248 } else {
1249 spin_lock(&pool->lock);
1251 } else {
1252 pool = get_std_worker_pool(WORK_CPU_UNBOUND, highpri);
1253 spin_lock(&pool->lock);
1256 /* pool determined, get cwq and queue */
1257 cwq = get_cwq(pool->cpu, wq);
1258 trace_workqueue_queue_work(req_cpu, cwq, work);
1260 if (WARN_ON(!list_empty(&work->entry))) {
1261 spin_unlock(&pool->lock);
1262 return;
1265 cwq->nr_in_flight[cwq->work_color]++;
1266 work_flags = work_color_to_flags(cwq->work_color);
1268 if (likely(cwq->nr_active < cwq->max_active)) {
1269 trace_workqueue_activate_work(work);
1270 cwq->nr_active++;
1271 worklist = &cwq->pool->worklist;
1272 } else {
1273 work_flags |= WORK_STRUCT_DELAYED;
1274 worklist = &cwq->delayed_works;
1277 insert_work(cwq, work, worklist, work_flags);
1279 spin_unlock(&pool->lock);
1283 * queue_work_on - queue work on specific cpu
1284 * @cpu: CPU number to execute work on
1285 * @wq: workqueue to use
1286 * @work: work to queue
1288 * Returns %false if @work was already on a queue, %true otherwise.
1290 * We queue the work to a specific CPU, the caller must ensure it
1291 * can't go away.
1293 bool queue_work_on(int cpu, struct workqueue_struct *wq,
1294 struct work_struct *work)
1296 bool ret = false;
1297 unsigned long flags;
1299 local_irq_save(flags);
1301 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1302 __queue_work(cpu, wq, work);
1303 ret = true;
1306 local_irq_restore(flags);
1307 return ret;
1309 EXPORT_SYMBOL_GPL(queue_work_on);
1312 * queue_work - queue work on a workqueue
1313 * @wq: workqueue to use
1314 * @work: work to queue
1316 * Returns %false if @work was already on a queue, %true otherwise.
1318 * We queue the work to the CPU on which it was submitted, but if the CPU dies
1319 * it can be processed by another CPU.
1321 bool queue_work(struct workqueue_struct *wq, struct work_struct *work)
1323 return queue_work_on(WORK_CPU_UNBOUND, wq, work);
1325 EXPORT_SYMBOL_GPL(queue_work);
1327 void delayed_work_timer_fn(unsigned long __data)
1329 struct delayed_work *dwork = (struct delayed_work *)__data;
1331 /* should have been called from irqsafe timer with irq already off */
1332 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
1334 EXPORT_SYMBOL_GPL(delayed_work_timer_fn);
1336 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
1337 struct delayed_work *dwork, unsigned long delay)
1339 struct timer_list *timer = &dwork->timer;
1340 struct work_struct *work = &dwork->work;
1342 WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
1343 timer->data != (unsigned long)dwork);
1344 WARN_ON_ONCE(timer_pending(timer));
1345 WARN_ON_ONCE(!list_empty(&work->entry));
1348 * If @delay is 0, queue @dwork->work immediately. This is for
1349 * both optimization and correctness. The earliest @timer can
1350 * expire is on the closest next tick and delayed_work users depend
1351 * on that there's no such delay when @delay is 0.
1353 if (!delay) {
1354 __queue_work(cpu, wq, &dwork->work);
1355 return;
1358 timer_stats_timer_set_start_info(&dwork->timer);
1360 dwork->wq = wq;
1361 dwork->cpu = cpu;
1362 timer->expires = jiffies + delay;
1364 if (unlikely(cpu != WORK_CPU_UNBOUND))
1365 add_timer_on(timer, cpu);
1366 else
1367 add_timer(timer);
1371 * queue_delayed_work_on - queue work on specific CPU after delay
1372 * @cpu: CPU number to execute work on
1373 * @wq: workqueue to use
1374 * @dwork: work to queue
1375 * @delay: number of jiffies to wait before queueing
1377 * Returns %false if @work was already on a queue, %true otherwise. If
1378 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1379 * execution.
1381 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1382 struct delayed_work *dwork, unsigned long delay)
1384 struct work_struct *work = &dwork->work;
1385 bool ret = false;
1386 unsigned long flags;
1388 /* read the comment in __queue_work() */
1389 local_irq_save(flags);
1391 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1392 __queue_delayed_work(cpu, wq, dwork, delay);
1393 ret = true;
1396 local_irq_restore(flags);
1397 return ret;
1399 EXPORT_SYMBOL_GPL(queue_delayed_work_on);
1402 * queue_delayed_work - queue work on a workqueue after delay
1403 * @wq: workqueue to use
1404 * @dwork: delayable work to queue
1405 * @delay: number of jiffies to wait before queueing
1407 * Equivalent to queue_delayed_work_on() but tries to use the local CPU.
1409 bool queue_delayed_work(struct workqueue_struct *wq,
1410 struct delayed_work *dwork, unsigned long delay)
1412 return queue_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
1414 EXPORT_SYMBOL_GPL(queue_delayed_work);
1417 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1418 * @cpu: CPU number to execute work on
1419 * @wq: workqueue to use
1420 * @dwork: work to queue
1421 * @delay: number of jiffies to wait before queueing
1423 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1424 * modify @dwork's timer so that it expires after @delay. If @delay is
1425 * zero, @work is guaranteed to be scheduled immediately regardless of its
1426 * current state.
1428 * Returns %false if @dwork was idle and queued, %true if @dwork was
1429 * pending and its timer was modified.
1431 * This function is safe to call from any context including IRQ handler.
1432 * See try_to_grab_pending() for details.
1434 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
1435 struct delayed_work *dwork, unsigned long delay)
1437 unsigned long flags;
1438 int ret;
1440 do {
1441 ret = try_to_grab_pending(&dwork->work, true, &flags);
1442 } while (unlikely(ret == -EAGAIN));
1444 if (likely(ret >= 0)) {
1445 __queue_delayed_work(cpu, wq, dwork, delay);
1446 local_irq_restore(flags);
1449 /* -ENOENT from try_to_grab_pending() becomes %true */
1450 return ret;
1452 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
1455 * mod_delayed_work - modify delay of or queue a delayed work
1456 * @wq: workqueue to use
1457 * @dwork: work to queue
1458 * @delay: number of jiffies to wait before queueing
1460 * mod_delayed_work_on() on local CPU.
1462 bool mod_delayed_work(struct workqueue_struct *wq, struct delayed_work *dwork,
1463 unsigned long delay)
1465 return mod_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
1467 EXPORT_SYMBOL_GPL(mod_delayed_work);
1470 * worker_enter_idle - enter idle state
1471 * @worker: worker which is entering idle state
1473 * @worker is entering idle state. Update stats and idle timer if
1474 * necessary.
1476 * LOCKING:
1477 * spin_lock_irq(pool->lock).
1479 static void worker_enter_idle(struct worker *worker)
1481 struct worker_pool *pool = worker->pool;
1483 BUG_ON(worker->flags & WORKER_IDLE);
1484 BUG_ON(!list_empty(&worker->entry) &&
1485 (worker->hentry.next || worker->hentry.pprev));
1487 /* can't use worker_set_flags(), also called from start_worker() */
1488 worker->flags |= WORKER_IDLE;
1489 pool->nr_idle++;
1490 worker->last_active = jiffies;
1492 /* idle_list is LIFO */
1493 list_add(&worker->entry, &pool->idle_list);
1495 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1496 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1499 * Sanity check nr_running. Because wq_unbind_fn() releases
1500 * pool->lock between setting %WORKER_UNBOUND and zapping
1501 * nr_running, the warning may trigger spuriously. Check iff
1502 * unbind is not in progress.
1504 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1505 pool->nr_workers == pool->nr_idle &&
1506 atomic_read(&pool->nr_running));
1510 * worker_leave_idle - leave idle state
1511 * @worker: worker which is leaving idle state
1513 * @worker is leaving idle state. Update stats.
1515 * LOCKING:
1516 * spin_lock_irq(pool->lock).
1518 static void worker_leave_idle(struct worker *worker)
1520 struct worker_pool *pool = worker->pool;
1522 BUG_ON(!(worker->flags & WORKER_IDLE));
1523 worker_clr_flags(worker, WORKER_IDLE);
1524 pool->nr_idle--;
1525 list_del_init(&worker->entry);
1529 * worker_maybe_bind_and_lock - bind worker to its cpu if possible and lock pool
1530 * @worker: self
1532 * Works which are scheduled while the cpu is online must at least be
1533 * scheduled to a worker which is bound to the cpu so that if they are
1534 * flushed from cpu callbacks while cpu is going down, they are
1535 * guaranteed to execute on the cpu.
1537 * This function is to be used by rogue workers and rescuers to bind
1538 * themselves to the target cpu and may race with cpu going down or
1539 * coming online. kthread_bind() can't be used because it may put the
1540 * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1541 * verbatim as it's best effort and blocking and pool may be
1542 * [dis]associated in the meantime.
1544 * This function tries set_cpus_allowed() and locks pool and verifies the
1545 * binding against %POOL_DISASSOCIATED which is set during
1546 * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
1547 * enters idle state or fetches works without dropping lock, it can
1548 * guarantee the scheduling requirement described in the first paragraph.
1550 * CONTEXT:
1551 * Might sleep. Called without any lock but returns with pool->lock
1552 * held.
1554 * RETURNS:
1555 * %true if the associated pool is online (@worker is successfully
1556 * bound), %false if offline.
1558 static bool worker_maybe_bind_and_lock(struct worker *worker)
1559 __acquires(&pool->lock)
1561 struct worker_pool *pool = worker->pool;
1562 struct task_struct *task = worker->task;
1564 while (true) {
1566 * The following call may fail, succeed or succeed
1567 * without actually migrating the task to the cpu if
1568 * it races with cpu hotunplug operation. Verify
1569 * against POOL_DISASSOCIATED.
1571 if (!(pool->flags & POOL_DISASSOCIATED))
1572 set_cpus_allowed_ptr(task, get_cpu_mask(pool->cpu));
1574 spin_lock_irq(&pool->lock);
1575 if (pool->flags & POOL_DISASSOCIATED)
1576 return false;
1577 if (task_cpu(task) == pool->cpu &&
1578 cpumask_equal(&current->cpus_allowed,
1579 get_cpu_mask(pool->cpu)))
1580 return true;
1581 spin_unlock_irq(&pool->lock);
1584 * We've raced with CPU hot[un]plug. Give it a breather
1585 * and retry migration. cond_resched() is required here;
1586 * otherwise, we might deadlock against cpu_stop trying to
1587 * bring down the CPU on non-preemptive kernel.
1589 cpu_relax();
1590 cond_resched();
1595 * Rebind an idle @worker to its CPU. worker_thread() will test
1596 * list_empty(@worker->entry) before leaving idle and call this function.
1598 static void idle_worker_rebind(struct worker *worker)
1600 /* CPU may go down again inbetween, clear UNBOUND only on success */
1601 if (worker_maybe_bind_and_lock(worker))
1602 worker_clr_flags(worker, WORKER_UNBOUND);
1604 /* rebind complete, become available again */
1605 list_add(&worker->entry, &worker->pool->idle_list);
1606 spin_unlock_irq(&worker->pool->lock);
1610 * Function for @worker->rebind.work used to rebind unbound busy workers to
1611 * the associated cpu which is coming back online. This is scheduled by
1612 * cpu up but can race with other cpu hotplug operations and may be
1613 * executed twice without intervening cpu down.
1615 static void busy_worker_rebind_fn(struct work_struct *work)
1617 struct worker *worker = container_of(work, struct worker, rebind_work);
1619 if (worker_maybe_bind_and_lock(worker))
1620 worker_clr_flags(worker, WORKER_UNBOUND);
1622 spin_unlock_irq(&worker->pool->lock);
1626 * rebind_workers - rebind all workers of a pool to the associated CPU
1627 * @pool: pool of interest
1629 * @pool->cpu is coming online. Rebind all workers to the CPU. Rebinding
1630 * is different for idle and busy ones.
1632 * Idle ones will be removed from the idle_list and woken up. They will
1633 * add themselves back after completing rebind. This ensures that the
1634 * idle_list doesn't contain any unbound workers when re-bound busy workers
1635 * try to perform local wake-ups for concurrency management.
1637 * Busy workers can rebind after they finish their current work items.
1638 * Queueing the rebind work item at the head of the scheduled list is
1639 * enough. Note that nr_running will be properly bumped as busy workers
1640 * rebind.
1642 * On return, all non-manager workers are scheduled for rebind - see
1643 * manage_workers() for the manager special case. Any idle worker
1644 * including the manager will not appear on @idle_list until rebind is
1645 * complete, making local wake-ups safe.
1647 static void rebind_workers(struct worker_pool *pool)
1649 struct worker *worker, *n;
1650 struct hlist_node *pos;
1651 int i;
1653 lockdep_assert_held(&pool->assoc_mutex);
1654 lockdep_assert_held(&pool->lock);
1656 /* dequeue and kick idle ones */
1657 list_for_each_entry_safe(worker, n, &pool->idle_list, entry) {
1659 * idle workers should be off @pool->idle_list until rebind
1660 * is complete to avoid receiving premature local wake-ups.
1662 list_del_init(&worker->entry);
1665 * worker_thread() will see the above dequeuing and call
1666 * idle_worker_rebind().
1668 wake_up_process(worker->task);
1671 /* rebind busy workers */
1672 for_each_busy_worker(worker, i, pos, pool) {
1673 struct work_struct *rebind_work = &worker->rebind_work;
1674 struct workqueue_struct *wq;
1676 if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
1677 work_data_bits(rebind_work)))
1678 continue;
1680 debug_work_activate(rebind_work);
1683 * wq doesn't really matter but let's keep @worker->pool
1684 * and @cwq->pool consistent for sanity.
1686 if (std_worker_pool_pri(worker->pool))
1687 wq = system_highpri_wq;
1688 else
1689 wq = system_wq;
1691 insert_work(get_cwq(pool->cpu, wq), rebind_work,
1692 worker->scheduled.next,
1693 work_color_to_flags(WORK_NO_COLOR));
1697 static struct worker *alloc_worker(void)
1699 struct worker *worker;
1701 worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1702 if (worker) {
1703 INIT_LIST_HEAD(&worker->entry);
1704 INIT_LIST_HEAD(&worker->scheduled);
1705 INIT_WORK(&worker->rebind_work, busy_worker_rebind_fn);
1706 /* on creation a worker is in !idle && prep state */
1707 worker->flags = WORKER_PREP;
1709 return worker;
1713 * create_worker - create a new workqueue worker
1714 * @pool: pool the new worker will belong to
1716 * Create a new worker which is bound to @pool. The returned worker
1717 * can be started by calling start_worker() or destroyed using
1718 * destroy_worker().
1720 * CONTEXT:
1721 * Might sleep. Does GFP_KERNEL allocations.
1723 * RETURNS:
1724 * Pointer to the newly created worker.
1726 static struct worker *create_worker(struct worker_pool *pool)
1728 const char *pri = std_worker_pool_pri(pool) ? "H" : "";
1729 struct worker *worker = NULL;
1730 int id = -1;
1732 spin_lock_irq(&pool->lock);
1733 while (ida_get_new(&pool->worker_ida, &id)) {
1734 spin_unlock_irq(&pool->lock);
1735 if (!ida_pre_get(&pool->worker_ida, GFP_KERNEL))
1736 goto fail;
1737 spin_lock_irq(&pool->lock);
1739 spin_unlock_irq(&pool->lock);
1741 worker = alloc_worker();
1742 if (!worker)
1743 goto fail;
1745 worker->pool = pool;
1746 worker->id = id;
1748 if (pool->cpu != WORK_CPU_UNBOUND)
1749 worker->task = kthread_create_on_node(worker_thread,
1750 worker, cpu_to_node(pool->cpu),
1751 "kworker/%u:%d%s", pool->cpu, id, pri);
1752 else
1753 worker->task = kthread_create(worker_thread, worker,
1754 "kworker/u:%d%s", id, pri);
1755 if (IS_ERR(worker->task))
1756 goto fail;
1758 if (std_worker_pool_pri(pool))
1759 set_user_nice(worker->task, HIGHPRI_NICE_LEVEL);
1762 * Determine CPU binding of the new worker depending on
1763 * %POOL_DISASSOCIATED. The caller is responsible for ensuring the
1764 * flag remains stable across this function. See the comments
1765 * above the flag definition for details.
1767 * As an unbound worker may later become a regular one if CPU comes
1768 * online, make sure every worker has %PF_THREAD_BOUND set.
1770 if (!(pool->flags & POOL_DISASSOCIATED)) {
1771 kthread_bind(worker->task, pool->cpu);
1772 } else {
1773 worker->task->flags |= PF_THREAD_BOUND;
1774 worker->flags |= WORKER_UNBOUND;
1777 return worker;
1778 fail:
1779 if (id >= 0) {
1780 spin_lock_irq(&pool->lock);
1781 ida_remove(&pool->worker_ida, id);
1782 spin_unlock_irq(&pool->lock);
1784 kfree(worker);
1785 return NULL;
1789 * start_worker - start a newly created worker
1790 * @worker: worker to start
1792 * Make the pool aware of @worker and start it.
1794 * CONTEXT:
1795 * spin_lock_irq(pool->lock).
1797 static void start_worker(struct worker *worker)
1799 worker->flags |= WORKER_STARTED;
1800 worker->pool->nr_workers++;
1801 worker_enter_idle(worker);
1802 wake_up_process(worker->task);
1806 * destroy_worker - destroy a workqueue worker
1807 * @worker: worker to be destroyed
1809 * Destroy @worker and adjust @pool stats accordingly.
1811 * CONTEXT:
1812 * spin_lock_irq(pool->lock) which is released and regrabbed.
1814 static void destroy_worker(struct worker *worker)
1816 struct worker_pool *pool = worker->pool;
1817 int id = worker->id;
1819 /* sanity check frenzy */
1820 BUG_ON(worker->current_work);
1821 BUG_ON(!list_empty(&worker->scheduled));
1823 if (worker->flags & WORKER_STARTED)
1824 pool->nr_workers--;
1825 if (worker->flags & WORKER_IDLE)
1826 pool->nr_idle--;
1828 list_del_init(&worker->entry);
1829 worker->flags |= WORKER_DIE;
1831 spin_unlock_irq(&pool->lock);
1833 kthread_stop(worker->task);
1834 kfree(worker);
1836 spin_lock_irq(&pool->lock);
1837 ida_remove(&pool->worker_ida, id);
1840 static void idle_worker_timeout(unsigned long __pool)
1842 struct worker_pool *pool = (void *)__pool;
1844 spin_lock_irq(&pool->lock);
1846 if (too_many_workers(pool)) {
1847 struct worker *worker;
1848 unsigned long expires;
1850 /* idle_list is kept in LIFO order, check the last one */
1851 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1852 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1854 if (time_before(jiffies, expires))
1855 mod_timer(&pool->idle_timer, expires);
1856 else {
1857 /* it's been idle for too long, wake up manager */
1858 pool->flags |= POOL_MANAGE_WORKERS;
1859 wake_up_worker(pool);
1863 spin_unlock_irq(&pool->lock);
1866 static bool send_mayday(struct work_struct *work)
1868 struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1869 struct workqueue_struct *wq = cwq->wq;
1870 unsigned int cpu;
1872 if (!(wq->flags & WQ_RESCUER))
1873 return false;
1875 /* mayday mayday mayday */
1876 cpu = cwq->pool->cpu;
1877 /* WORK_CPU_UNBOUND can't be set in cpumask, use cpu 0 instead */
1878 if (cpu == WORK_CPU_UNBOUND)
1879 cpu = 0;
1880 if (!mayday_test_and_set_cpu(cpu, wq->mayday_mask))
1881 wake_up_process(wq->rescuer->task);
1882 return true;
1885 static void pool_mayday_timeout(unsigned long __pool)
1887 struct worker_pool *pool = (void *)__pool;
1888 struct work_struct *work;
1890 spin_lock_irq(&pool->lock);
1892 if (need_to_create_worker(pool)) {
1894 * We've been trying to create a new worker but
1895 * haven't been successful. We might be hitting an
1896 * allocation deadlock. Send distress signals to
1897 * rescuers.
1899 list_for_each_entry(work, &pool->worklist, entry)
1900 send_mayday(work);
1903 spin_unlock_irq(&pool->lock);
1905 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1909 * maybe_create_worker - create a new worker if necessary
1910 * @pool: pool to create a new worker for
1912 * Create a new worker for @pool if necessary. @pool is guaranteed to
1913 * have at least one idle worker on return from this function. If
1914 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1915 * sent to all rescuers with works scheduled on @pool to resolve
1916 * possible allocation deadlock.
1918 * On return, need_to_create_worker() is guaranteed to be false and
1919 * may_start_working() true.
1921 * LOCKING:
1922 * spin_lock_irq(pool->lock) which may be released and regrabbed
1923 * multiple times. Does GFP_KERNEL allocations. Called only from
1924 * manager.
1926 * RETURNS:
1927 * false if no action was taken and pool->lock stayed locked, true
1928 * otherwise.
1930 static bool maybe_create_worker(struct worker_pool *pool)
1931 __releases(&pool->lock)
1932 __acquires(&pool->lock)
1934 if (!need_to_create_worker(pool))
1935 return false;
1936 restart:
1937 spin_unlock_irq(&pool->lock);
1939 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1940 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1942 while (true) {
1943 struct worker *worker;
1945 worker = create_worker(pool);
1946 if (worker) {
1947 del_timer_sync(&pool->mayday_timer);
1948 spin_lock_irq(&pool->lock);
1949 start_worker(worker);
1950 BUG_ON(need_to_create_worker(pool));
1951 return true;
1954 if (!need_to_create_worker(pool))
1955 break;
1957 __set_current_state(TASK_INTERRUPTIBLE);
1958 schedule_timeout(CREATE_COOLDOWN);
1960 if (!need_to_create_worker(pool))
1961 break;
1964 del_timer_sync(&pool->mayday_timer);
1965 spin_lock_irq(&pool->lock);
1966 if (need_to_create_worker(pool))
1967 goto restart;
1968 return true;
1972 * maybe_destroy_worker - destroy workers which have been idle for a while
1973 * @pool: pool to destroy workers for
1975 * Destroy @pool workers which have been idle for longer than
1976 * IDLE_WORKER_TIMEOUT.
1978 * LOCKING:
1979 * spin_lock_irq(pool->lock) which may be released and regrabbed
1980 * multiple times. Called only from manager.
1982 * RETURNS:
1983 * false if no action was taken and pool->lock stayed locked, true
1984 * otherwise.
1986 static bool maybe_destroy_workers(struct worker_pool *pool)
1988 bool ret = false;
1990 while (too_many_workers(pool)) {
1991 struct worker *worker;
1992 unsigned long expires;
1994 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1995 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1997 if (time_before(jiffies, expires)) {
1998 mod_timer(&pool->idle_timer, expires);
1999 break;
2002 destroy_worker(worker);
2003 ret = true;
2006 return ret;
2010 * manage_workers - manage worker pool
2011 * @worker: self
2013 * Assume the manager role and manage the worker pool @worker belongs
2014 * to. At any given time, there can be only zero or one manager per
2015 * pool. The exclusion is handled automatically by this function.
2017 * The caller can safely start processing works on false return. On
2018 * true return, it's guaranteed that need_to_create_worker() is false
2019 * and may_start_working() is true.
2021 * CONTEXT:
2022 * spin_lock_irq(pool->lock) which may be released and regrabbed
2023 * multiple times. Does GFP_KERNEL allocations.
2025 * RETURNS:
2026 * spin_lock_irq(pool->lock) which may be released and regrabbed
2027 * multiple times. Does GFP_KERNEL allocations.
2029 static bool manage_workers(struct worker *worker)
2031 struct worker_pool *pool = worker->pool;
2032 bool ret = false;
2034 if (pool->flags & POOL_MANAGING_WORKERS)
2035 return ret;
2037 pool->flags |= POOL_MANAGING_WORKERS;
2040 * To simplify both worker management and CPU hotplug, hold off
2041 * management while hotplug is in progress. CPU hotplug path can't
2042 * grab %POOL_MANAGING_WORKERS to achieve this because that can
2043 * lead to idle worker depletion (all become busy thinking someone
2044 * else is managing) which in turn can result in deadlock under
2045 * extreme circumstances. Use @pool->assoc_mutex to synchronize
2046 * manager against CPU hotplug.
2048 * assoc_mutex would always be free unless CPU hotplug is in
2049 * progress. trylock first without dropping @pool->lock.
2051 if (unlikely(!mutex_trylock(&pool->assoc_mutex))) {
2052 spin_unlock_irq(&pool->lock);
2053 mutex_lock(&pool->assoc_mutex);
2055 * CPU hotplug could have happened while we were waiting
2056 * for assoc_mutex. Hotplug itself can't handle us
2057 * because manager isn't either on idle or busy list, and
2058 * @pool's state and ours could have deviated.
2060 * As hotplug is now excluded via assoc_mutex, we can
2061 * simply try to bind. It will succeed or fail depending
2062 * on @pool's current state. Try it and adjust
2063 * %WORKER_UNBOUND accordingly.
2065 if (worker_maybe_bind_and_lock(worker))
2066 worker->flags &= ~WORKER_UNBOUND;
2067 else
2068 worker->flags |= WORKER_UNBOUND;
2070 ret = true;
2073 pool->flags &= ~POOL_MANAGE_WORKERS;
2076 * Destroy and then create so that may_start_working() is true
2077 * on return.
2079 ret |= maybe_destroy_workers(pool);
2080 ret |= maybe_create_worker(pool);
2082 pool->flags &= ~POOL_MANAGING_WORKERS;
2083 mutex_unlock(&pool->assoc_mutex);
2084 return ret;
2088 * process_one_work - process single work
2089 * @worker: self
2090 * @work: work to process
2092 * Process @work. This function contains all the logics necessary to
2093 * process a single work including synchronization against and
2094 * interaction with other workers on the same cpu, queueing and
2095 * flushing. As long as context requirement is met, any worker can
2096 * call this function to process a work.
2098 * CONTEXT:
2099 * spin_lock_irq(pool->lock) which is released and regrabbed.
2101 static void process_one_work(struct worker *worker, struct work_struct *work)
2102 __releases(&pool->lock)
2103 __acquires(&pool->lock)
2105 struct cpu_workqueue_struct *cwq = get_work_cwq(work);
2106 struct worker_pool *pool = worker->pool;
2107 bool cpu_intensive = cwq->wq->flags & WQ_CPU_INTENSIVE;
2108 int work_color;
2109 struct worker *collision;
2110 #ifdef CONFIG_LOCKDEP
2112 * It is permissible to free the struct work_struct from
2113 * inside the function that is called from it, this we need to
2114 * take into account for lockdep too. To avoid bogus "held
2115 * lock freed" warnings as well as problems when looking into
2116 * work->lockdep_map, make a copy and use that here.
2118 struct lockdep_map lockdep_map;
2120 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
2121 #endif
2123 * Ensure we're on the correct CPU. DISASSOCIATED test is
2124 * necessary to avoid spurious warnings from rescuers servicing the
2125 * unbound or a disassociated pool.
2127 WARN_ON_ONCE(!(worker->flags & WORKER_UNBOUND) &&
2128 !(pool->flags & POOL_DISASSOCIATED) &&
2129 raw_smp_processor_id() != pool->cpu);
2132 * A single work shouldn't be executed concurrently by
2133 * multiple workers on a single cpu. Check whether anyone is
2134 * already processing the work. If so, defer the work to the
2135 * currently executing one.
2137 collision = find_worker_executing_work(pool, work);
2138 if (unlikely(collision)) {
2139 move_linked_works(work, &collision->scheduled, NULL);
2140 return;
2143 /* claim and dequeue */
2144 debug_work_deactivate(work);
2145 hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2146 worker->current_work = work;
2147 worker->current_func = work->func;
2148 worker->current_cwq = cwq;
2149 work_color = get_work_color(work);
2151 list_del_init(&work->entry);
2154 * CPU intensive works don't participate in concurrency
2155 * management. They're the scheduler's responsibility.
2157 if (unlikely(cpu_intensive))
2158 worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
2161 * Unbound pool isn't concurrency managed and work items should be
2162 * executed ASAP. Wake up another worker if necessary.
2164 if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
2165 wake_up_worker(pool);
2168 * Record the last pool and clear PENDING which should be the last
2169 * update to @work. Also, do this inside @pool->lock so that
2170 * PENDING and queued state changes happen together while IRQ is
2171 * disabled.
2173 set_work_pool_and_clear_pending(work, pool->id);
2175 spin_unlock_irq(&pool->lock);
2177 lock_map_acquire_read(&cwq->wq->lockdep_map);
2178 lock_map_acquire(&lockdep_map);
2179 trace_workqueue_execute_start(work);
2180 worker->current_func(work);
2182 * While we must be careful to not use "work" after this, the trace
2183 * point will only record its address.
2185 trace_workqueue_execute_end(work);
2186 lock_map_release(&lockdep_map);
2187 lock_map_release(&cwq->wq->lockdep_map);
2189 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2190 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2191 " last function: %pf\n",
2192 current->comm, preempt_count(), task_pid_nr(current),
2193 worker->current_func);
2194 debug_show_held_locks(current);
2195 dump_stack();
2198 spin_lock_irq(&pool->lock);
2200 /* clear cpu intensive status */
2201 if (unlikely(cpu_intensive))
2202 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2204 /* we're done with it, release */
2205 hash_del(&worker->hentry);
2206 worker->current_work = NULL;
2207 worker->current_func = NULL;
2208 worker->current_cwq = NULL;
2209 cwq_dec_nr_in_flight(cwq, work_color);
2213 * process_scheduled_works - process scheduled works
2214 * @worker: self
2216 * Process all scheduled works. Please note that the scheduled list
2217 * may change while processing a work, so this function repeatedly
2218 * fetches a work from the top and executes it.
2220 * CONTEXT:
2221 * spin_lock_irq(pool->lock) which may be released and regrabbed
2222 * multiple times.
2224 static void process_scheduled_works(struct worker *worker)
2226 while (!list_empty(&worker->scheduled)) {
2227 struct work_struct *work = list_first_entry(&worker->scheduled,
2228 struct work_struct, entry);
2229 process_one_work(worker, work);
2234 * worker_thread - the worker thread function
2235 * @__worker: self
2237 * The worker thread function. There are NR_CPU_WORKER_POOLS dynamic pools
2238 * of these per each cpu. These workers process all works regardless of
2239 * their specific target workqueue. The only exception is works which
2240 * belong to workqueues with a rescuer which will be explained in
2241 * rescuer_thread().
2243 static int worker_thread(void *__worker)
2245 struct worker *worker = __worker;
2246 struct worker_pool *pool = worker->pool;
2248 /* tell the scheduler that this is a workqueue worker */
2249 worker->task->flags |= PF_WQ_WORKER;
2250 woke_up:
2251 spin_lock_irq(&pool->lock);
2253 /* we are off idle list if destruction or rebind is requested */
2254 if (unlikely(list_empty(&worker->entry))) {
2255 spin_unlock_irq(&pool->lock);
2257 /* if DIE is set, destruction is requested */
2258 if (worker->flags & WORKER_DIE) {
2259 worker->task->flags &= ~PF_WQ_WORKER;
2260 return 0;
2263 /* otherwise, rebind */
2264 idle_worker_rebind(worker);
2265 goto woke_up;
2268 worker_leave_idle(worker);
2269 recheck:
2270 /* no more worker necessary? */
2271 if (!need_more_worker(pool))
2272 goto sleep;
2274 /* do we need to manage? */
2275 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2276 goto recheck;
2279 * ->scheduled list can only be filled while a worker is
2280 * preparing to process a work or actually processing it.
2281 * Make sure nobody diddled with it while I was sleeping.
2283 BUG_ON(!list_empty(&worker->scheduled));
2286 * When control reaches this point, we're guaranteed to have
2287 * at least one idle worker or that someone else has already
2288 * assumed the manager role.
2290 worker_clr_flags(worker, WORKER_PREP);
2292 do {
2293 struct work_struct *work =
2294 list_first_entry(&pool->worklist,
2295 struct work_struct, entry);
2297 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2298 /* optimization path, not strictly necessary */
2299 process_one_work(worker, work);
2300 if (unlikely(!list_empty(&worker->scheduled)))
2301 process_scheduled_works(worker);
2302 } else {
2303 move_linked_works(work, &worker->scheduled, NULL);
2304 process_scheduled_works(worker);
2306 } while (keep_working(pool));
2308 worker_set_flags(worker, WORKER_PREP, false);
2309 sleep:
2310 if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
2311 goto recheck;
2314 * pool->lock is held and there's no work to process and no need to
2315 * manage, sleep. Workers are woken up only while holding
2316 * pool->lock or from local cpu, so setting the current state
2317 * before releasing pool->lock is enough to prevent losing any
2318 * event.
2320 worker_enter_idle(worker);
2321 __set_current_state(TASK_INTERRUPTIBLE);
2322 spin_unlock_irq(&pool->lock);
2323 schedule();
2324 goto woke_up;
2328 * rescuer_thread - the rescuer thread function
2329 * @__rescuer: self
2331 * Workqueue rescuer thread function. There's one rescuer for each
2332 * workqueue which has WQ_RESCUER set.
2334 * Regular work processing on a pool may block trying to create a new
2335 * worker which uses GFP_KERNEL allocation which has slight chance of
2336 * developing into deadlock if some works currently on the same queue
2337 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2338 * the problem rescuer solves.
2340 * When such condition is possible, the pool summons rescuers of all
2341 * workqueues which have works queued on the pool and let them process
2342 * those works so that forward progress can be guaranteed.
2344 * This should happen rarely.
2346 static int rescuer_thread(void *__rescuer)
2348 struct worker *rescuer = __rescuer;
2349 struct workqueue_struct *wq = rescuer->rescue_wq;
2350 struct list_head *scheduled = &rescuer->scheduled;
2351 bool is_unbound = wq->flags & WQ_UNBOUND;
2352 unsigned int cpu;
2354 set_user_nice(current, RESCUER_NICE_LEVEL);
2357 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2358 * doesn't participate in concurrency management.
2360 rescuer->task->flags |= PF_WQ_WORKER;
2361 repeat:
2362 set_current_state(TASK_INTERRUPTIBLE);
2364 if (kthread_should_stop()) {
2365 __set_current_state(TASK_RUNNING);
2366 rescuer->task->flags &= ~PF_WQ_WORKER;
2367 return 0;
2371 * See whether any cpu is asking for help. Unbounded
2372 * workqueues use cpu 0 in mayday_mask for CPU_UNBOUND.
2374 for_each_mayday_cpu(cpu, wq->mayday_mask) {
2375 unsigned int tcpu = is_unbound ? WORK_CPU_UNBOUND : cpu;
2376 struct cpu_workqueue_struct *cwq = get_cwq(tcpu, wq);
2377 struct worker_pool *pool = cwq->pool;
2378 struct work_struct *work, *n;
2380 __set_current_state(TASK_RUNNING);
2381 mayday_clear_cpu(cpu, wq->mayday_mask);
2383 /* migrate to the target cpu if possible */
2384 rescuer->pool = pool;
2385 worker_maybe_bind_and_lock(rescuer);
2388 * Slurp in all works issued via this workqueue and
2389 * process'em.
2391 BUG_ON(!list_empty(&rescuer->scheduled));
2392 list_for_each_entry_safe(work, n, &pool->worklist, entry)
2393 if (get_work_cwq(work) == cwq)
2394 move_linked_works(work, scheduled, &n);
2396 process_scheduled_works(rescuer);
2399 * Leave this pool. If keep_working() is %true, notify a
2400 * regular worker; otherwise, we end up with 0 concurrency
2401 * and stalling the execution.
2403 if (keep_working(pool))
2404 wake_up_worker(pool);
2406 spin_unlock_irq(&pool->lock);
2409 /* rescuers should never participate in concurrency management */
2410 WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2411 schedule();
2412 goto repeat;
2415 struct wq_barrier {
2416 struct work_struct work;
2417 struct completion done;
2420 static void wq_barrier_func(struct work_struct *work)
2422 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2423 complete(&barr->done);
2427 * insert_wq_barrier - insert a barrier work
2428 * @cwq: cwq to insert barrier into
2429 * @barr: wq_barrier to insert
2430 * @target: target work to attach @barr to
2431 * @worker: worker currently executing @target, NULL if @target is not executing
2433 * @barr is linked to @target such that @barr is completed only after
2434 * @target finishes execution. Please note that the ordering
2435 * guarantee is observed only with respect to @target and on the local
2436 * cpu.
2438 * Currently, a queued barrier can't be canceled. This is because
2439 * try_to_grab_pending() can't determine whether the work to be
2440 * grabbed is at the head of the queue and thus can't clear LINKED
2441 * flag of the previous work while there must be a valid next work
2442 * after a work with LINKED flag set.
2444 * Note that when @worker is non-NULL, @target may be modified
2445 * underneath us, so we can't reliably determine cwq from @target.
2447 * CONTEXT:
2448 * spin_lock_irq(pool->lock).
2450 static void insert_wq_barrier(struct cpu_workqueue_struct *cwq,
2451 struct wq_barrier *barr,
2452 struct work_struct *target, struct worker *worker)
2454 struct list_head *head;
2455 unsigned int linked = 0;
2458 * debugobject calls are safe here even with pool->lock locked
2459 * as we know for sure that this will not trigger any of the
2460 * checks and call back into the fixup functions where we
2461 * might deadlock.
2463 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2464 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2465 init_completion(&barr->done);
2468 * If @target is currently being executed, schedule the
2469 * barrier to the worker; otherwise, put it after @target.
2471 if (worker)
2472 head = worker->scheduled.next;
2473 else {
2474 unsigned long *bits = work_data_bits(target);
2476 head = target->entry.next;
2477 /* there can already be other linked works, inherit and set */
2478 linked = *bits & WORK_STRUCT_LINKED;
2479 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2482 debug_work_activate(&barr->work);
2483 insert_work(cwq, &barr->work, head,
2484 work_color_to_flags(WORK_NO_COLOR) | linked);
2488 * flush_workqueue_prep_cwqs - prepare cwqs for workqueue flushing
2489 * @wq: workqueue being flushed
2490 * @flush_color: new flush color, < 0 for no-op
2491 * @work_color: new work color, < 0 for no-op
2493 * Prepare cwqs for workqueue flushing.
2495 * If @flush_color is non-negative, flush_color on all cwqs should be
2496 * -1. If no cwq has in-flight commands at the specified color, all
2497 * cwq->flush_color's stay at -1 and %false is returned. If any cwq
2498 * has in flight commands, its cwq->flush_color is set to
2499 * @flush_color, @wq->nr_cwqs_to_flush is updated accordingly, cwq
2500 * wakeup logic is armed and %true is returned.
2502 * The caller should have initialized @wq->first_flusher prior to
2503 * calling this function with non-negative @flush_color. If
2504 * @flush_color is negative, no flush color update is done and %false
2505 * is returned.
2507 * If @work_color is non-negative, all cwqs should have the same
2508 * work_color which is previous to @work_color and all will be
2509 * advanced to @work_color.
2511 * CONTEXT:
2512 * mutex_lock(wq->flush_mutex).
2514 * RETURNS:
2515 * %true if @flush_color >= 0 and there's something to flush. %false
2516 * otherwise.
2518 static bool flush_workqueue_prep_cwqs(struct workqueue_struct *wq,
2519 int flush_color, int work_color)
2521 bool wait = false;
2522 unsigned int cpu;
2524 if (flush_color >= 0) {
2525 BUG_ON(atomic_read(&wq->nr_cwqs_to_flush));
2526 atomic_set(&wq->nr_cwqs_to_flush, 1);
2529 for_each_cwq_cpu(cpu, wq) {
2530 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2531 struct worker_pool *pool = cwq->pool;
2533 spin_lock_irq(&pool->lock);
2535 if (flush_color >= 0) {
2536 BUG_ON(cwq->flush_color != -1);
2538 if (cwq->nr_in_flight[flush_color]) {
2539 cwq->flush_color = flush_color;
2540 atomic_inc(&wq->nr_cwqs_to_flush);
2541 wait = true;
2545 if (work_color >= 0) {
2546 BUG_ON(work_color != work_next_color(cwq->work_color));
2547 cwq->work_color = work_color;
2550 spin_unlock_irq(&pool->lock);
2553 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_cwqs_to_flush))
2554 complete(&wq->first_flusher->done);
2556 return wait;
2560 * flush_workqueue - ensure that any scheduled work has run to completion.
2561 * @wq: workqueue to flush
2563 * Forces execution of the workqueue and blocks until its completion.
2564 * This is typically used in driver shutdown handlers.
2566 * We sleep until all works which were queued on entry have been handled,
2567 * but we are not livelocked by new incoming ones.
2569 void flush_workqueue(struct workqueue_struct *wq)
2571 struct wq_flusher this_flusher = {
2572 .list = LIST_HEAD_INIT(this_flusher.list),
2573 .flush_color = -1,
2574 .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
2576 int next_color;
2578 lock_map_acquire(&wq->lockdep_map);
2579 lock_map_release(&wq->lockdep_map);
2581 mutex_lock(&wq->flush_mutex);
2584 * Start-to-wait phase
2586 next_color = work_next_color(wq->work_color);
2588 if (next_color != wq->flush_color) {
2590 * Color space is not full. The current work_color
2591 * becomes our flush_color and work_color is advanced
2592 * by one.
2594 BUG_ON(!list_empty(&wq->flusher_overflow));
2595 this_flusher.flush_color = wq->work_color;
2596 wq->work_color = next_color;
2598 if (!wq->first_flusher) {
2599 /* no flush in progress, become the first flusher */
2600 BUG_ON(wq->flush_color != this_flusher.flush_color);
2602 wq->first_flusher = &this_flusher;
2604 if (!flush_workqueue_prep_cwqs(wq, wq->flush_color,
2605 wq->work_color)) {
2606 /* nothing to flush, done */
2607 wq->flush_color = next_color;
2608 wq->first_flusher = NULL;
2609 goto out_unlock;
2611 } else {
2612 /* wait in queue */
2613 BUG_ON(wq->flush_color == this_flusher.flush_color);
2614 list_add_tail(&this_flusher.list, &wq->flusher_queue);
2615 flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2617 } else {
2619 * Oops, color space is full, wait on overflow queue.
2620 * The next flush completion will assign us
2621 * flush_color and transfer to flusher_queue.
2623 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2626 mutex_unlock(&wq->flush_mutex);
2628 wait_for_completion(&this_flusher.done);
2631 * Wake-up-and-cascade phase
2633 * First flushers are responsible for cascading flushes and
2634 * handling overflow. Non-first flushers can simply return.
2636 if (wq->first_flusher != &this_flusher)
2637 return;
2639 mutex_lock(&wq->flush_mutex);
2641 /* we might have raced, check again with mutex held */
2642 if (wq->first_flusher != &this_flusher)
2643 goto out_unlock;
2645 wq->first_flusher = NULL;
2647 BUG_ON(!list_empty(&this_flusher.list));
2648 BUG_ON(wq->flush_color != this_flusher.flush_color);
2650 while (true) {
2651 struct wq_flusher *next, *tmp;
2653 /* complete all the flushers sharing the current flush color */
2654 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2655 if (next->flush_color != wq->flush_color)
2656 break;
2657 list_del_init(&next->list);
2658 complete(&next->done);
2661 BUG_ON(!list_empty(&wq->flusher_overflow) &&
2662 wq->flush_color != work_next_color(wq->work_color));
2664 /* this flush_color is finished, advance by one */
2665 wq->flush_color = work_next_color(wq->flush_color);
2667 /* one color has been freed, handle overflow queue */
2668 if (!list_empty(&wq->flusher_overflow)) {
2670 * Assign the same color to all overflowed
2671 * flushers, advance work_color and append to
2672 * flusher_queue. This is the start-to-wait
2673 * phase for these overflowed flushers.
2675 list_for_each_entry(tmp, &wq->flusher_overflow, list)
2676 tmp->flush_color = wq->work_color;
2678 wq->work_color = work_next_color(wq->work_color);
2680 list_splice_tail_init(&wq->flusher_overflow,
2681 &wq->flusher_queue);
2682 flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2685 if (list_empty(&wq->flusher_queue)) {
2686 BUG_ON(wq->flush_color != wq->work_color);
2687 break;
2691 * Need to flush more colors. Make the next flusher
2692 * the new first flusher and arm cwqs.
2694 BUG_ON(wq->flush_color == wq->work_color);
2695 BUG_ON(wq->flush_color != next->flush_color);
2697 list_del_init(&next->list);
2698 wq->first_flusher = next;
2700 if (flush_workqueue_prep_cwqs(wq, wq->flush_color, -1))
2701 break;
2704 * Meh... this color is already done, clear first
2705 * flusher and repeat cascading.
2707 wq->first_flusher = NULL;
2710 out_unlock:
2711 mutex_unlock(&wq->flush_mutex);
2713 EXPORT_SYMBOL_GPL(flush_workqueue);
2716 * drain_workqueue - drain a workqueue
2717 * @wq: workqueue to drain
2719 * Wait until the workqueue becomes empty. While draining is in progress,
2720 * only chain queueing is allowed. IOW, only currently pending or running
2721 * work items on @wq can queue further work items on it. @wq is flushed
2722 * repeatedly until it becomes empty. The number of flushing is detemined
2723 * by the depth of chaining and should be relatively short. Whine if it
2724 * takes too long.
2726 void drain_workqueue(struct workqueue_struct *wq)
2728 unsigned int flush_cnt = 0;
2729 unsigned int cpu;
2732 * __queue_work() needs to test whether there are drainers, is much
2733 * hotter than drain_workqueue() and already looks at @wq->flags.
2734 * Use WQ_DRAINING so that queue doesn't have to check nr_drainers.
2736 spin_lock(&workqueue_lock);
2737 if (!wq->nr_drainers++)
2738 wq->flags |= WQ_DRAINING;
2739 spin_unlock(&workqueue_lock);
2740 reflush:
2741 flush_workqueue(wq);
2743 for_each_cwq_cpu(cpu, wq) {
2744 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2745 bool drained;
2747 spin_lock_irq(&cwq->pool->lock);
2748 drained = !cwq->nr_active && list_empty(&cwq->delayed_works);
2749 spin_unlock_irq(&cwq->pool->lock);
2751 if (drained)
2752 continue;
2754 if (++flush_cnt == 10 ||
2755 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2756 pr_warn("workqueue %s: flush on destruction isn't complete after %u tries\n",
2757 wq->name, flush_cnt);
2758 goto reflush;
2761 spin_lock(&workqueue_lock);
2762 if (!--wq->nr_drainers)
2763 wq->flags &= ~WQ_DRAINING;
2764 spin_unlock(&workqueue_lock);
2766 EXPORT_SYMBOL_GPL(drain_workqueue);
2768 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2770 struct worker *worker = NULL;
2771 struct worker_pool *pool;
2772 struct cpu_workqueue_struct *cwq;
2774 might_sleep();
2775 pool = get_work_pool(work);
2776 if (!pool)
2777 return false;
2779 spin_lock_irq(&pool->lock);
2780 /* see the comment in try_to_grab_pending() with the same code */
2781 cwq = get_work_cwq(work);
2782 if (cwq) {
2783 if (unlikely(cwq->pool != pool))
2784 goto already_gone;
2785 } else {
2786 worker = find_worker_executing_work(pool, work);
2787 if (!worker)
2788 goto already_gone;
2789 cwq = worker->current_cwq;
2792 insert_wq_barrier(cwq, barr, work, worker);
2793 spin_unlock_irq(&pool->lock);
2796 * If @max_active is 1 or rescuer is in use, flushing another work
2797 * item on the same workqueue may lead to deadlock. Make sure the
2798 * flusher is not running on the same workqueue by verifying write
2799 * access.
2801 if (cwq->wq->saved_max_active == 1 || cwq->wq->flags & WQ_RESCUER)
2802 lock_map_acquire(&cwq->wq->lockdep_map);
2803 else
2804 lock_map_acquire_read(&cwq->wq->lockdep_map);
2805 lock_map_release(&cwq->wq->lockdep_map);
2807 return true;
2808 already_gone:
2809 spin_unlock_irq(&pool->lock);
2810 return false;
2814 * flush_work - wait for a work to finish executing the last queueing instance
2815 * @work: the work to flush
2817 * Wait until @work has finished execution. @work is guaranteed to be idle
2818 * on return if it hasn't been requeued since flush started.
2820 * RETURNS:
2821 * %true if flush_work() waited for the work to finish execution,
2822 * %false if it was already idle.
2824 bool flush_work(struct work_struct *work)
2826 struct wq_barrier barr;
2828 lock_map_acquire(&work->lockdep_map);
2829 lock_map_release(&work->lockdep_map);
2831 if (start_flush_work(work, &barr)) {
2832 wait_for_completion(&barr.done);
2833 destroy_work_on_stack(&barr.work);
2834 return true;
2835 } else {
2836 return false;
2839 EXPORT_SYMBOL_GPL(flush_work);
2841 static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2843 unsigned long flags;
2844 int ret;
2846 do {
2847 ret = try_to_grab_pending(work, is_dwork, &flags);
2849 * If someone else is canceling, wait for the same event it
2850 * would be waiting for before retrying.
2852 if (unlikely(ret == -ENOENT))
2853 flush_work(work);
2854 } while (unlikely(ret < 0));
2856 /* tell other tasks trying to grab @work to back off */
2857 mark_work_canceling(work);
2858 local_irq_restore(flags);
2860 flush_work(work);
2861 clear_work_data(work);
2862 return ret;
2866 * cancel_work_sync - cancel a work and wait for it to finish
2867 * @work: the work to cancel
2869 * Cancel @work and wait for its execution to finish. This function
2870 * can be used even if the work re-queues itself or migrates to
2871 * another workqueue. On return from this function, @work is
2872 * guaranteed to be not pending or executing on any CPU.
2874 * cancel_work_sync(&delayed_work->work) must not be used for
2875 * delayed_work's. Use cancel_delayed_work_sync() instead.
2877 * The caller must ensure that the workqueue on which @work was last
2878 * queued can't be destroyed before this function returns.
2880 * RETURNS:
2881 * %true if @work was pending, %false otherwise.
2883 bool cancel_work_sync(struct work_struct *work)
2885 return __cancel_work_timer(work, false);
2887 EXPORT_SYMBOL_GPL(cancel_work_sync);
2890 * flush_delayed_work - wait for a dwork to finish executing the last queueing
2891 * @dwork: the delayed work to flush
2893 * Delayed timer is cancelled and the pending work is queued for
2894 * immediate execution. Like flush_work(), this function only
2895 * considers the last queueing instance of @dwork.
2897 * RETURNS:
2898 * %true if flush_work() waited for the work to finish execution,
2899 * %false if it was already idle.
2901 bool flush_delayed_work(struct delayed_work *dwork)
2903 local_irq_disable();
2904 if (del_timer_sync(&dwork->timer))
2905 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
2906 local_irq_enable();
2907 return flush_work(&dwork->work);
2909 EXPORT_SYMBOL(flush_delayed_work);
2912 * cancel_delayed_work - cancel a delayed work
2913 * @dwork: delayed_work to cancel
2915 * Kill off a pending delayed_work. Returns %true if @dwork was pending
2916 * and canceled; %false if wasn't pending. Note that the work callback
2917 * function may still be running on return, unless it returns %true and the
2918 * work doesn't re-arm itself. Explicitly flush or use
2919 * cancel_delayed_work_sync() to wait on it.
2921 * This function is safe to call from any context including IRQ handler.
2923 bool cancel_delayed_work(struct delayed_work *dwork)
2925 unsigned long flags;
2926 int ret;
2928 do {
2929 ret = try_to_grab_pending(&dwork->work, true, &flags);
2930 } while (unlikely(ret == -EAGAIN));
2932 if (unlikely(ret < 0))
2933 return false;
2935 set_work_pool_and_clear_pending(&dwork->work,
2936 get_work_pool_id(&dwork->work));
2937 local_irq_restore(flags);
2938 return ret;
2940 EXPORT_SYMBOL(cancel_delayed_work);
2943 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2944 * @dwork: the delayed work cancel
2946 * This is cancel_work_sync() for delayed works.
2948 * RETURNS:
2949 * %true if @dwork was pending, %false otherwise.
2951 bool cancel_delayed_work_sync(struct delayed_work *dwork)
2953 return __cancel_work_timer(&dwork->work, true);
2955 EXPORT_SYMBOL(cancel_delayed_work_sync);
2958 * schedule_work_on - put work task on a specific cpu
2959 * @cpu: cpu to put the work task on
2960 * @work: job to be done
2962 * This puts a job on a specific cpu
2964 bool schedule_work_on(int cpu, struct work_struct *work)
2966 return queue_work_on(cpu, system_wq, work);
2968 EXPORT_SYMBOL(schedule_work_on);
2971 * schedule_work - put work task in global workqueue
2972 * @work: job to be done
2974 * Returns %false if @work was already on the kernel-global workqueue and
2975 * %true otherwise.
2977 * This puts a job in the kernel-global workqueue if it was not already
2978 * queued and leaves it in the same position on the kernel-global
2979 * workqueue otherwise.
2981 bool schedule_work(struct work_struct *work)
2983 return queue_work(system_wq, work);
2985 EXPORT_SYMBOL(schedule_work);
2988 * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
2989 * @cpu: cpu to use
2990 * @dwork: job to be done
2991 * @delay: number of jiffies to wait
2993 * After waiting for a given time this puts a job in the kernel-global
2994 * workqueue on the specified CPU.
2996 bool schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
2997 unsigned long delay)
2999 return queue_delayed_work_on(cpu, system_wq, dwork, delay);
3001 EXPORT_SYMBOL(schedule_delayed_work_on);
3004 * schedule_delayed_work - put work task in global workqueue after delay
3005 * @dwork: job to be done
3006 * @delay: number of jiffies to wait or 0 for immediate execution
3008 * After waiting for a given time this puts a job in the kernel-global
3009 * workqueue.
3011 bool schedule_delayed_work(struct delayed_work *dwork, unsigned long delay)
3013 return queue_delayed_work(system_wq, dwork, delay);
3015 EXPORT_SYMBOL(schedule_delayed_work);
3018 * schedule_on_each_cpu - execute a function synchronously on each online CPU
3019 * @func: the function to call
3021 * schedule_on_each_cpu() executes @func on each online CPU using the
3022 * system workqueue and blocks until all CPUs have completed.
3023 * schedule_on_each_cpu() is very slow.
3025 * RETURNS:
3026 * 0 on success, -errno on failure.
3028 int schedule_on_each_cpu(work_func_t func)
3030 int cpu;
3031 struct work_struct __percpu *works;
3033 works = alloc_percpu(struct work_struct);
3034 if (!works)
3035 return -ENOMEM;
3037 get_online_cpus();
3039 for_each_online_cpu(cpu) {
3040 struct work_struct *work = per_cpu_ptr(works, cpu);
3042 INIT_WORK(work, func);
3043 schedule_work_on(cpu, work);
3046 for_each_online_cpu(cpu)
3047 flush_work(per_cpu_ptr(works, cpu));
3049 put_online_cpus();
3050 free_percpu(works);
3051 return 0;
3055 * flush_scheduled_work - ensure that any scheduled work has run to completion.
3057 * Forces execution of the kernel-global workqueue and blocks until its
3058 * completion.
3060 * Think twice before calling this function! It's very easy to get into
3061 * trouble if you don't take great care. Either of the following situations
3062 * will lead to deadlock:
3064 * One of the work items currently on the workqueue needs to acquire
3065 * a lock held by your code or its caller.
3067 * Your code is running in the context of a work routine.
3069 * They will be detected by lockdep when they occur, but the first might not
3070 * occur very often. It depends on what work items are on the workqueue and
3071 * what locks they need, which you have no control over.
3073 * In most situations flushing the entire workqueue is overkill; you merely
3074 * need to know that a particular work item isn't queued and isn't running.
3075 * In such cases you should use cancel_delayed_work_sync() or
3076 * cancel_work_sync() instead.
3078 void flush_scheduled_work(void)
3080 flush_workqueue(system_wq);
3082 EXPORT_SYMBOL(flush_scheduled_work);
3085 * execute_in_process_context - reliably execute the routine with user context
3086 * @fn: the function to execute
3087 * @ew: guaranteed storage for the execute work structure (must
3088 * be available when the work executes)
3090 * Executes the function immediately if process context is available,
3091 * otherwise schedules the function for delayed execution.
3093 * Returns: 0 - function was executed
3094 * 1 - function was scheduled for execution
3096 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
3098 if (!in_interrupt()) {
3099 fn(&ew->work);
3100 return 0;
3103 INIT_WORK(&ew->work, fn);
3104 schedule_work(&ew->work);
3106 return 1;
3108 EXPORT_SYMBOL_GPL(execute_in_process_context);
3110 int keventd_up(void)
3112 return system_wq != NULL;
3115 static int alloc_cwqs(struct workqueue_struct *wq)
3118 * cwqs are forced aligned according to WORK_STRUCT_FLAG_BITS.
3119 * Make sure that the alignment isn't lower than that of
3120 * unsigned long long.
3122 const size_t size = sizeof(struct cpu_workqueue_struct);
3123 const size_t align = max_t(size_t, 1 << WORK_STRUCT_FLAG_BITS,
3124 __alignof__(unsigned long long));
3126 if (!(wq->flags & WQ_UNBOUND))
3127 wq->cpu_wq.pcpu = __alloc_percpu(size, align);
3128 else {
3129 void *ptr;
3132 * Allocate enough room to align cwq and put an extra
3133 * pointer at the end pointing back to the originally
3134 * allocated pointer which will be used for free.
3136 ptr = kzalloc(size + align + sizeof(void *), GFP_KERNEL);
3137 if (ptr) {
3138 wq->cpu_wq.single = PTR_ALIGN(ptr, align);
3139 *(void **)(wq->cpu_wq.single + 1) = ptr;
3143 /* just in case, make sure it's actually aligned */
3144 BUG_ON(!IS_ALIGNED(wq->cpu_wq.v, align));
3145 return wq->cpu_wq.v ? 0 : -ENOMEM;
3148 static void free_cwqs(struct workqueue_struct *wq)
3150 if (!(wq->flags & WQ_UNBOUND))
3151 free_percpu(wq->cpu_wq.pcpu);
3152 else if (wq->cpu_wq.single) {
3153 /* the pointer to free is stored right after the cwq */
3154 kfree(*(void **)(wq->cpu_wq.single + 1));
3158 static int wq_clamp_max_active(int max_active, unsigned int flags,
3159 const char *name)
3161 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3163 if (max_active < 1 || max_active > lim)
3164 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3165 max_active, name, 1, lim);
3167 return clamp_val(max_active, 1, lim);
3170 struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
3171 unsigned int flags,
3172 int max_active,
3173 struct lock_class_key *key,
3174 const char *lock_name, ...)
3176 va_list args, args1;
3177 struct workqueue_struct *wq;
3178 unsigned int cpu;
3179 size_t namelen;
3181 /* determine namelen, allocate wq and format name */
3182 va_start(args, lock_name);
3183 va_copy(args1, args);
3184 namelen = vsnprintf(NULL, 0, fmt, args) + 1;
3186 wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
3187 if (!wq)
3188 goto err;
3190 vsnprintf(wq->name, namelen, fmt, args1);
3191 va_end(args);
3192 va_end(args1);
3195 * Workqueues which may be used during memory reclaim should
3196 * have a rescuer to guarantee forward progress.
3198 if (flags & WQ_MEM_RECLAIM)
3199 flags |= WQ_RESCUER;
3201 max_active = max_active ?: WQ_DFL_ACTIVE;
3202 max_active = wq_clamp_max_active(max_active, flags, wq->name);
3204 /* init wq */
3205 wq->flags = flags;
3206 wq->saved_max_active = max_active;
3207 mutex_init(&wq->flush_mutex);
3208 atomic_set(&wq->nr_cwqs_to_flush, 0);
3209 INIT_LIST_HEAD(&wq->flusher_queue);
3210 INIT_LIST_HEAD(&wq->flusher_overflow);
3212 lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3213 INIT_LIST_HEAD(&wq->list);
3215 if (alloc_cwqs(wq) < 0)
3216 goto err;
3218 for_each_cwq_cpu(cpu, wq) {
3219 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3221 BUG_ON((unsigned long)cwq & WORK_STRUCT_FLAG_MASK);
3222 cwq->pool = get_std_worker_pool(cpu, flags & WQ_HIGHPRI);
3223 cwq->wq = wq;
3224 cwq->flush_color = -1;
3225 cwq->max_active = max_active;
3226 INIT_LIST_HEAD(&cwq->delayed_works);
3229 if (flags & WQ_RESCUER) {
3230 struct worker *rescuer;
3232 if (!alloc_mayday_mask(&wq->mayday_mask, GFP_KERNEL))
3233 goto err;
3235 wq->rescuer = rescuer = alloc_worker();
3236 if (!rescuer)
3237 goto err;
3239 rescuer->rescue_wq = wq;
3240 rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
3241 wq->name);
3242 if (IS_ERR(rescuer->task))
3243 goto err;
3245 rescuer->task->flags |= PF_THREAD_BOUND;
3246 wake_up_process(rescuer->task);
3250 * workqueue_lock protects global freeze state and workqueues
3251 * list. Grab it, set max_active accordingly and add the new
3252 * workqueue to workqueues list.
3254 spin_lock(&workqueue_lock);
3256 if (workqueue_freezing && wq->flags & WQ_FREEZABLE)
3257 for_each_cwq_cpu(cpu, wq)
3258 get_cwq(cpu, wq)->max_active = 0;
3260 list_add(&wq->list, &workqueues);
3262 spin_unlock(&workqueue_lock);
3264 return wq;
3265 err:
3266 if (wq) {
3267 free_cwqs(wq);
3268 free_mayday_mask(wq->mayday_mask);
3269 kfree(wq->rescuer);
3270 kfree(wq);
3272 return NULL;
3274 EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
3277 * destroy_workqueue - safely terminate a workqueue
3278 * @wq: target workqueue
3280 * Safely destroy a workqueue. All work currently pending will be done first.
3282 void destroy_workqueue(struct workqueue_struct *wq)
3284 unsigned int cpu;
3286 /* drain it before proceeding with destruction */
3287 drain_workqueue(wq);
3290 * wq list is used to freeze wq, remove from list after
3291 * flushing is complete in case freeze races us.
3293 spin_lock(&workqueue_lock);
3294 list_del(&wq->list);
3295 spin_unlock(&workqueue_lock);
3297 /* sanity check */
3298 for_each_cwq_cpu(cpu, wq) {
3299 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3300 int i;
3302 for (i = 0; i < WORK_NR_COLORS; i++)
3303 BUG_ON(cwq->nr_in_flight[i]);
3304 BUG_ON(cwq->nr_active);
3305 BUG_ON(!list_empty(&cwq->delayed_works));
3308 if (wq->flags & WQ_RESCUER) {
3309 kthread_stop(wq->rescuer->task);
3310 free_mayday_mask(wq->mayday_mask);
3311 kfree(wq->rescuer);
3314 free_cwqs(wq);
3315 kfree(wq);
3317 EXPORT_SYMBOL_GPL(destroy_workqueue);
3320 * cwq_set_max_active - adjust max_active of a cwq
3321 * @cwq: target cpu_workqueue_struct
3322 * @max_active: new max_active value.
3324 * Set @cwq->max_active to @max_active and activate delayed works if
3325 * increased.
3327 * CONTEXT:
3328 * spin_lock_irq(pool->lock).
3330 static void cwq_set_max_active(struct cpu_workqueue_struct *cwq, int max_active)
3332 cwq->max_active = max_active;
3334 while (!list_empty(&cwq->delayed_works) &&
3335 cwq->nr_active < cwq->max_active)
3336 cwq_activate_first_delayed(cwq);
3340 * workqueue_set_max_active - adjust max_active of a workqueue
3341 * @wq: target workqueue
3342 * @max_active: new max_active value.
3344 * Set max_active of @wq to @max_active.
3346 * CONTEXT:
3347 * Don't call from IRQ context.
3349 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
3351 unsigned int cpu;
3353 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
3355 spin_lock(&workqueue_lock);
3357 wq->saved_max_active = max_active;
3359 for_each_cwq_cpu(cpu, wq) {
3360 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3361 struct worker_pool *pool = cwq->pool;
3363 spin_lock_irq(&pool->lock);
3365 if (!(wq->flags & WQ_FREEZABLE) ||
3366 !(pool->flags & POOL_FREEZING))
3367 cwq_set_max_active(cwq, max_active);
3369 spin_unlock_irq(&pool->lock);
3372 spin_unlock(&workqueue_lock);
3374 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
3377 * workqueue_congested - test whether a workqueue is congested
3378 * @cpu: CPU in question
3379 * @wq: target workqueue
3381 * Test whether @wq's cpu workqueue for @cpu is congested. There is
3382 * no synchronization around this function and the test result is
3383 * unreliable and only useful as advisory hints or for debugging.
3385 * RETURNS:
3386 * %true if congested, %false otherwise.
3388 bool workqueue_congested(unsigned int cpu, struct workqueue_struct *wq)
3390 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3392 return !list_empty(&cwq->delayed_works);
3394 EXPORT_SYMBOL_GPL(workqueue_congested);
3397 * work_busy - test whether a work is currently pending or running
3398 * @work: the work to be tested
3400 * Test whether @work is currently pending or running. There is no
3401 * synchronization around this function and the test result is
3402 * unreliable and only useful as advisory hints or for debugging.
3404 * RETURNS:
3405 * OR'd bitmask of WORK_BUSY_* bits.
3407 unsigned int work_busy(struct work_struct *work)
3409 struct worker_pool *pool = get_work_pool(work);
3410 unsigned long flags;
3411 unsigned int ret = 0;
3413 if (work_pending(work))
3414 ret |= WORK_BUSY_PENDING;
3416 if (pool) {
3417 spin_lock_irqsave(&pool->lock, flags);
3418 if (find_worker_executing_work(pool, work))
3419 ret |= WORK_BUSY_RUNNING;
3420 spin_unlock_irqrestore(&pool->lock, flags);
3423 return ret;
3425 EXPORT_SYMBOL_GPL(work_busy);
3428 * CPU hotplug.
3430 * There are two challenges in supporting CPU hotplug. Firstly, there
3431 * are a lot of assumptions on strong associations among work, cwq and
3432 * pool which make migrating pending and scheduled works very
3433 * difficult to implement without impacting hot paths. Secondly,
3434 * worker pools serve mix of short, long and very long running works making
3435 * blocked draining impractical.
3437 * This is solved by allowing the pools to be disassociated from the CPU
3438 * running as an unbound one and allowing it to be reattached later if the
3439 * cpu comes back online.
3442 static void wq_unbind_fn(struct work_struct *work)
3444 int cpu = smp_processor_id();
3445 struct worker_pool *pool;
3446 struct worker *worker;
3447 struct hlist_node *pos;
3448 int i;
3450 for_each_std_worker_pool(pool, cpu) {
3451 BUG_ON(cpu != smp_processor_id());
3453 mutex_lock(&pool->assoc_mutex);
3454 spin_lock_irq(&pool->lock);
3457 * We've claimed all manager positions. Make all workers
3458 * unbound and set DISASSOCIATED. Before this, all workers
3459 * except for the ones which are still executing works from
3460 * before the last CPU down must be on the cpu. After
3461 * this, they may become diasporas.
3463 list_for_each_entry(worker, &pool->idle_list, entry)
3464 worker->flags |= WORKER_UNBOUND;
3466 for_each_busy_worker(worker, i, pos, pool)
3467 worker->flags |= WORKER_UNBOUND;
3469 pool->flags |= POOL_DISASSOCIATED;
3471 spin_unlock_irq(&pool->lock);
3472 mutex_unlock(&pool->assoc_mutex);
3476 * Call schedule() so that we cross rq->lock and thus can guarantee
3477 * sched callbacks see the %WORKER_UNBOUND flag. This is necessary
3478 * as scheduler callbacks may be invoked from other cpus.
3480 schedule();
3483 * Sched callbacks are disabled now. Zap nr_running. After this,
3484 * nr_running stays zero and need_more_worker() and keep_working()
3485 * are always true as long as the worklist is not empty. Pools on
3486 * @cpu now behave as unbound (in terms of concurrency management)
3487 * pools which are served by workers tied to the CPU.
3489 * On return from this function, the current worker would trigger
3490 * unbound chain execution of pending work items if other workers
3491 * didn't already.
3493 for_each_std_worker_pool(pool, cpu)
3494 atomic_set(&pool->nr_running, 0);
3498 * Workqueues should be brought up before normal priority CPU notifiers.
3499 * This will be registered high priority CPU notifier.
3501 static int __cpuinit workqueue_cpu_up_callback(struct notifier_block *nfb,
3502 unsigned long action,
3503 void *hcpu)
3505 unsigned int cpu = (unsigned long)hcpu;
3506 struct worker_pool *pool;
3508 switch (action & ~CPU_TASKS_FROZEN) {
3509 case CPU_UP_PREPARE:
3510 for_each_std_worker_pool(pool, cpu) {
3511 struct worker *worker;
3513 if (pool->nr_workers)
3514 continue;
3516 worker = create_worker(pool);
3517 if (!worker)
3518 return NOTIFY_BAD;
3520 spin_lock_irq(&pool->lock);
3521 start_worker(worker);
3522 spin_unlock_irq(&pool->lock);
3524 break;
3526 case CPU_DOWN_FAILED:
3527 case CPU_ONLINE:
3528 for_each_std_worker_pool(pool, cpu) {
3529 mutex_lock(&pool->assoc_mutex);
3530 spin_lock_irq(&pool->lock);
3532 pool->flags &= ~POOL_DISASSOCIATED;
3533 rebind_workers(pool);
3535 spin_unlock_irq(&pool->lock);
3536 mutex_unlock(&pool->assoc_mutex);
3538 break;
3540 return NOTIFY_OK;
3544 * Workqueues should be brought down after normal priority CPU notifiers.
3545 * This will be registered as low priority CPU notifier.
3547 static int __cpuinit workqueue_cpu_down_callback(struct notifier_block *nfb,
3548 unsigned long action,
3549 void *hcpu)
3551 unsigned int cpu = (unsigned long)hcpu;
3552 struct work_struct unbind_work;
3554 switch (action & ~CPU_TASKS_FROZEN) {
3555 case CPU_DOWN_PREPARE:
3556 /* unbinding should happen on the local CPU */
3557 INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
3558 queue_work_on(cpu, system_highpri_wq, &unbind_work);
3559 flush_work(&unbind_work);
3560 break;
3562 return NOTIFY_OK;
3565 #ifdef CONFIG_SMP
3567 struct work_for_cpu {
3568 struct work_struct work;
3569 long (*fn)(void *);
3570 void *arg;
3571 long ret;
3574 static void work_for_cpu_fn(struct work_struct *work)
3576 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
3578 wfc->ret = wfc->fn(wfc->arg);
3582 * work_on_cpu - run a function in user context on a particular cpu
3583 * @cpu: the cpu to run on
3584 * @fn: the function to run
3585 * @arg: the function arg
3587 * This will return the value @fn returns.
3588 * It is up to the caller to ensure that the cpu doesn't go offline.
3589 * The caller must not hold any locks which would prevent @fn from completing.
3591 long work_on_cpu(unsigned int cpu, long (*fn)(void *), void *arg)
3593 struct work_for_cpu wfc = { .fn = fn, .arg = arg };
3595 INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
3596 schedule_work_on(cpu, &wfc.work);
3597 flush_work(&wfc.work);
3598 return wfc.ret;
3600 EXPORT_SYMBOL_GPL(work_on_cpu);
3601 #endif /* CONFIG_SMP */
3603 #ifdef CONFIG_FREEZER
3606 * freeze_workqueues_begin - begin freezing workqueues
3608 * Start freezing workqueues. After this function returns, all freezable
3609 * workqueues will queue new works to their frozen_works list instead of
3610 * pool->worklist.
3612 * CONTEXT:
3613 * Grabs and releases workqueue_lock and pool->lock's.
3615 void freeze_workqueues_begin(void)
3617 unsigned int cpu;
3619 spin_lock(&workqueue_lock);
3621 BUG_ON(workqueue_freezing);
3622 workqueue_freezing = true;
3624 for_each_wq_cpu(cpu) {
3625 struct worker_pool *pool;
3626 struct workqueue_struct *wq;
3628 for_each_std_worker_pool(pool, cpu) {
3629 spin_lock_irq(&pool->lock);
3631 WARN_ON_ONCE(pool->flags & POOL_FREEZING);
3632 pool->flags |= POOL_FREEZING;
3634 list_for_each_entry(wq, &workqueues, list) {
3635 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3637 if (cwq && cwq->pool == pool &&
3638 (wq->flags & WQ_FREEZABLE))
3639 cwq->max_active = 0;
3642 spin_unlock_irq(&pool->lock);
3646 spin_unlock(&workqueue_lock);
3650 * freeze_workqueues_busy - are freezable workqueues still busy?
3652 * Check whether freezing is complete. This function must be called
3653 * between freeze_workqueues_begin() and thaw_workqueues().
3655 * CONTEXT:
3656 * Grabs and releases workqueue_lock.
3658 * RETURNS:
3659 * %true if some freezable workqueues are still busy. %false if freezing
3660 * is complete.
3662 bool freeze_workqueues_busy(void)
3664 unsigned int cpu;
3665 bool busy = false;
3667 spin_lock(&workqueue_lock);
3669 BUG_ON(!workqueue_freezing);
3671 for_each_wq_cpu(cpu) {
3672 struct workqueue_struct *wq;
3674 * nr_active is monotonically decreasing. It's safe
3675 * to peek without lock.
3677 list_for_each_entry(wq, &workqueues, list) {
3678 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3680 if (!cwq || !(wq->flags & WQ_FREEZABLE))
3681 continue;
3683 BUG_ON(cwq->nr_active < 0);
3684 if (cwq->nr_active) {
3685 busy = true;
3686 goto out_unlock;
3690 out_unlock:
3691 spin_unlock(&workqueue_lock);
3692 return busy;
3696 * thaw_workqueues - thaw workqueues
3698 * Thaw workqueues. Normal queueing is restored and all collected
3699 * frozen works are transferred to their respective pool worklists.
3701 * CONTEXT:
3702 * Grabs and releases workqueue_lock and pool->lock's.
3704 void thaw_workqueues(void)
3706 unsigned int cpu;
3708 spin_lock(&workqueue_lock);
3710 if (!workqueue_freezing)
3711 goto out_unlock;
3713 for_each_wq_cpu(cpu) {
3714 struct worker_pool *pool;
3715 struct workqueue_struct *wq;
3717 for_each_std_worker_pool(pool, cpu) {
3718 spin_lock_irq(&pool->lock);
3720 WARN_ON_ONCE(!(pool->flags & POOL_FREEZING));
3721 pool->flags &= ~POOL_FREEZING;
3723 list_for_each_entry(wq, &workqueues, list) {
3724 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3726 if (!cwq || cwq->pool != pool ||
3727 !(wq->flags & WQ_FREEZABLE))
3728 continue;
3730 /* restore max_active and repopulate worklist */
3731 cwq_set_max_active(cwq, wq->saved_max_active);
3734 wake_up_worker(pool);
3736 spin_unlock_irq(&pool->lock);
3740 workqueue_freezing = false;
3741 out_unlock:
3742 spin_unlock(&workqueue_lock);
3744 #endif /* CONFIG_FREEZER */
3746 static int __init init_workqueues(void)
3748 unsigned int cpu;
3750 /* make sure we have enough bits for OFFQ pool ID */
3751 BUILD_BUG_ON((1LU << (BITS_PER_LONG - WORK_OFFQ_POOL_SHIFT)) <
3752 WORK_CPU_END * NR_STD_WORKER_POOLS);
3754 cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
3755 hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
3757 /* initialize CPU pools */
3758 for_each_wq_cpu(cpu) {
3759 struct worker_pool *pool;
3761 for_each_std_worker_pool(pool, cpu) {
3762 spin_lock_init(&pool->lock);
3763 pool->cpu = cpu;
3764 pool->flags |= POOL_DISASSOCIATED;
3765 INIT_LIST_HEAD(&pool->worklist);
3766 INIT_LIST_HEAD(&pool->idle_list);
3767 hash_init(pool->busy_hash);
3769 init_timer_deferrable(&pool->idle_timer);
3770 pool->idle_timer.function = idle_worker_timeout;
3771 pool->idle_timer.data = (unsigned long)pool;
3773 setup_timer(&pool->mayday_timer, pool_mayday_timeout,
3774 (unsigned long)pool);
3776 mutex_init(&pool->assoc_mutex);
3777 ida_init(&pool->worker_ida);
3779 /* alloc pool ID */
3780 BUG_ON(worker_pool_assign_id(pool));
3784 /* create the initial worker */
3785 for_each_online_wq_cpu(cpu) {
3786 struct worker_pool *pool;
3788 for_each_std_worker_pool(pool, cpu) {
3789 struct worker *worker;
3791 if (cpu != WORK_CPU_UNBOUND)
3792 pool->flags &= ~POOL_DISASSOCIATED;
3794 worker = create_worker(pool);
3795 BUG_ON(!worker);
3796 spin_lock_irq(&pool->lock);
3797 start_worker(worker);
3798 spin_unlock_irq(&pool->lock);
3802 system_wq = alloc_workqueue("events", 0, 0);
3803 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
3804 system_long_wq = alloc_workqueue("events_long", 0, 0);
3805 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
3806 WQ_UNBOUND_MAX_ACTIVE);
3807 system_freezable_wq = alloc_workqueue("events_freezable",
3808 WQ_FREEZABLE, 0);
3809 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
3810 !system_unbound_wq || !system_freezable_wq);
3811 return 0;
3813 early_initcall(init_workqueues);