2 * kernel/workqueue.c - generic async execution with shared worker pool
4 * Copyright (C) 2002 Ingo Molnar
6 * Derived from the taskqueue/keventd code by:
7 * David Woodhouse <dwmw2@infradead.org>
9 * Kai Petzke <wpp@marie.physik.tu-berlin.de>
10 * Theodore Ts'o <tytso@mit.edu>
12 * Made to use alloc_percpu by Christoph Lameter.
14 * Copyright (C) 2010 SUSE Linux Products GmbH
15 * Copyright (C) 2010 Tejun Heo <tj@kernel.org>
17 * This is the generic async execution mechanism. Work items as are
18 * executed in process context. The worker pool is shared and
19 * automatically managed. There is one worker pool for each CPU and
20 * one extra for works which are better served by workers which are
21 * not bound to any specific CPU.
23 * Please read Documentation/workqueue.txt for details.
26 #include <linux/export.h>
27 #include <linux/kernel.h>
28 #include <linux/sched.h>
29 #include <linux/init.h>
30 #include <linux/signal.h>
31 #include <linux/completion.h>
32 #include <linux/workqueue.h>
33 #include <linux/slab.h>
34 #include <linux/cpu.h>
35 #include <linux/notifier.h>
36 #include <linux/kthread.h>
37 #include <linux/hardirq.h>
38 #include <linux/mempolicy.h>
39 #include <linux/freezer.h>
40 #include <linux/kallsyms.h>
41 #include <linux/debug_locks.h>
42 #include <linux/lockdep.h>
43 #include <linux/idr.h>
44 #include <linux/jhash.h>
45 #include <linux/hashtable.h>
46 #include <linux/rculist.h>
47 #include <linux/nodemask.h>
49 #include "workqueue_internal.h"
55 * A bound pool is either associated or disassociated with its CPU.
56 * While associated (!DISASSOCIATED), all workers are bound to the
57 * CPU and none has %WORKER_UNBOUND set and concurrency management
60 * While DISASSOCIATED, the cpu may be offline and all workers have
61 * %WORKER_UNBOUND set and concurrency management disabled, and may
62 * be executing on any CPU. The pool behaves as an unbound one.
64 * Note that DISASSOCIATED should be flipped only while holding
65 * manager_mutex to avoid changing binding state while
66 * create_worker() is in progress.
68 POOL_MANAGE_WORKERS = 1 << 0, /* need to manage workers */
69 POOL_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
70 POOL_FREEZING = 1 << 3, /* freeze in progress */
73 WORKER_STARTED = 1 << 0, /* started */
74 WORKER_DIE = 1 << 1, /* die die die */
75 WORKER_IDLE = 1 << 2, /* is idle */
76 WORKER_PREP = 1 << 3, /* preparing to run works */
77 WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
78 WORKER_UNBOUND = 1 << 7, /* worker is unbound */
79 WORKER_REBOUND = 1 << 8, /* worker was rebound */
81 WORKER_NOT_RUNNING = WORKER_PREP | WORKER_CPU_INTENSIVE |
82 WORKER_UNBOUND | WORKER_REBOUND,
84 NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */
86 UNBOUND_POOL_HASH_ORDER = 6, /* hashed by pool->attrs */
87 BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
89 MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
90 IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
92 MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
93 /* call for help after 10ms
95 MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
96 CREATE_COOLDOWN = HZ, /* time to breath after fail */
99 * Rescue workers are used only on emergencies and shared by
100 * all cpus. Give -20.
102 RESCUER_NICE_LEVEL = -20,
103 HIGHPRI_NICE_LEVEL = -20,
107 * Structure fields follow one of the following exclusion rules.
109 * I: Modifiable by initialization/destruction paths and read-only for
112 * P: Preemption protected. Disabling preemption is enough and should
113 * only be modified and accessed from the local cpu.
115 * L: pool->lock protected. Access with pool->lock held.
117 * X: During normal operation, modification requires pool->lock and should
118 * be done only from local cpu. Either disabling preemption on local
119 * cpu or grabbing pool->lock is enough for read access. If
120 * POOL_DISASSOCIATED is set, it's identical to L.
122 * MG: pool->manager_mutex and pool->lock protected. Writes require both
123 * locks. Reads can happen under either lock.
125 * PL: wq_pool_mutex protected.
127 * PR: wq_pool_mutex protected for writes. Sched-RCU protected for reads.
129 * WQ: wq->mutex protected.
131 * WR: wq->mutex protected for writes. Sched-RCU protected for reads.
133 * MD: wq_mayday_lock protected.
136 /* struct worker is defined in workqueue_internal.h */
139 spinlock_t lock; /* the pool lock */
140 int cpu; /* I: the associated cpu */
141 int node; /* I: the associated node ID */
142 int id; /* I: pool ID */
143 unsigned int flags; /* X: flags */
145 struct list_head worklist; /* L: list of pending works */
146 int nr_workers; /* L: total number of workers */
148 /* nr_idle includes the ones off idle_list for rebinding */
149 int nr_idle; /* L: currently idle ones */
151 struct list_head idle_list; /* X: list of idle workers */
152 struct timer_list idle_timer; /* L: worker idle timeout */
153 struct timer_list mayday_timer; /* L: SOS timer for workers */
155 /* a workers is either on busy_hash or idle_list, or the manager */
156 DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
157 /* L: hash of busy workers */
159 /* see manage_workers() for details on the two manager mutexes */
160 struct mutex manager_arb; /* manager arbitration */
161 struct mutex manager_mutex; /* manager exclusion */
162 struct idr worker_idr; /* MG: worker IDs and iteration */
164 struct workqueue_attrs *attrs; /* I: worker attributes */
165 struct hlist_node hash_node; /* PL: unbound_pool_hash node */
166 int refcnt; /* PL: refcnt for unbound pools */
169 * The current concurrency level. As it's likely to be accessed
170 * from other CPUs during try_to_wake_up(), put it in a separate
173 atomic_t nr_running ____cacheline_aligned_in_smp;
176 * Destruction of pool is sched-RCU protected to allow dereferences
177 * from get_work_pool().
180 } ____cacheline_aligned_in_smp;
183 * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
184 * of work_struct->data are used for flags and the remaining high bits
185 * point to the pwq; thus, pwqs need to be aligned at two's power of the
186 * number of flag bits.
188 struct pool_workqueue {
189 struct worker_pool *pool; /* I: the associated pool */
190 struct workqueue_struct *wq; /* I: the owning workqueue */
191 int work_color; /* L: current color */
192 int flush_color; /* L: flushing color */
193 int refcnt; /* L: reference count */
194 int nr_in_flight[WORK_NR_COLORS];
195 /* L: nr of in_flight works */
196 int nr_active; /* L: nr of active works */
197 int max_active; /* L: max active works */
198 struct list_head delayed_works; /* L: delayed works */
199 struct list_head pwqs_node; /* WR: node on wq->pwqs */
200 struct list_head mayday_node; /* MD: node on wq->maydays */
203 * Release of unbound pwq is punted to system_wq. See put_pwq()
204 * and pwq_unbound_release_workfn() for details. pool_workqueue
205 * itself is also sched-RCU protected so that the first pwq can be
206 * determined without grabbing wq->mutex.
208 struct work_struct unbound_release_work;
210 } __aligned(1 << WORK_STRUCT_FLAG_BITS);
213 * Structure used to wait for workqueue flush.
216 struct list_head list; /* WQ: list of flushers */
217 int flush_color; /* WQ: flush color waiting for */
218 struct completion done; /* flush completion */
224 * The externally visible workqueue. It relays the issued work items to
225 * the appropriate worker_pool through its pool_workqueues.
227 struct workqueue_struct {
228 unsigned int flags; /* WQ: WQ_* flags */
229 struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwq's */
230 struct list_head pwqs; /* WR: all pwqs of this wq */
231 struct list_head list; /* PL: list of all workqueues */
233 struct mutex mutex; /* protects this wq */
234 int work_color; /* WQ: current work color */
235 int flush_color; /* WQ: current flush color */
236 atomic_t nr_pwqs_to_flush; /* flush in progress */
237 struct wq_flusher *first_flusher; /* WQ: first flusher */
238 struct list_head flusher_queue; /* WQ: flush waiters */
239 struct list_head flusher_overflow; /* WQ: flush overflow list */
241 struct list_head maydays; /* MD: pwqs requesting rescue */
242 struct worker *rescuer; /* I: rescue worker */
244 int nr_drainers; /* WQ: drain in progress */
245 int saved_max_active; /* WQ: saved pwq max_active */
248 struct wq_device *wq_dev; /* I: for sysfs interface */
250 #ifdef CONFIG_LOCKDEP
251 struct lockdep_map lockdep_map;
253 char name[]; /* I: workqueue name */
256 static struct kmem_cache *pwq_cache;
258 static int wq_numa_tbl_len; /* highest possible NUMA node id + 1 */
259 static cpumask_var_t *wq_numa_possible_cpumask;
260 /* possible CPUs of each node */
262 static bool wq_numa_enabled; /* unbound NUMA affinity enabled */
264 static DEFINE_MUTEX(wq_pool_mutex); /* protects pools and workqueues list */
265 static DEFINE_SPINLOCK(wq_mayday_lock); /* protects wq->maydays list */
267 static LIST_HEAD(workqueues); /* PL: list of all workqueues */
268 static bool workqueue_freezing; /* PL: have wqs started freezing? */
270 /* the per-cpu worker pools */
271 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
274 static DEFINE_IDR(worker_pool_idr); /* PR: idr of all pools */
276 /* PL: hash of all unbound pools keyed by pool->attrs */
277 static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
279 /* I: attributes used when instantiating standard unbound pools on demand */
280 static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
282 struct workqueue_struct *system_wq __read_mostly;
283 EXPORT_SYMBOL_GPL(system_wq);
284 struct workqueue_struct *system_highpri_wq __read_mostly;
285 EXPORT_SYMBOL_GPL(system_highpri_wq);
286 struct workqueue_struct *system_long_wq __read_mostly;
287 EXPORT_SYMBOL_GPL(system_long_wq);
288 struct workqueue_struct *system_unbound_wq __read_mostly;
289 EXPORT_SYMBOL_GPL(system_unbound_wq);
290 struct workqueue_struct *system_freezable_wq __read_mostly;
291 EXPORT_SYMBOL_GPL(system_freezable_wq);
293 static int worker_thread(void *__worker);
294 static void copy_workqueue_attrs(struct workqueue_attrs *to,
295 const struct workqueue_attrs *from);
297 #define CREATE_TRACE_POINTS
298 #include <trace/events/workqueue.h>
300 #define assert_rcu_or_pool_mutex() \
301 rcu_lockdep_assert(rcu_read_lock_sched_held() || \
302 lockdep_is_held(&wq_pool_mutex), \
303 "sched RCU or wq_pool_mutex should be held")
305 #define assert_rcu_or_wq_mutex(wq) \
306 rcu_lockdep_assert(rcu_read_lock_sched_held() || \
307 lockdep_is_held(&wq->mutex), \
308 "sched RCU or wq->mutex should be held")
310 #ifdef CONFIG_LOCKDEP
311 #define assert_manager_or_pool_lock(pool) \
312 WARN_ONCE(debug_locks && \
313 !lockdep_is_held(&(pool)->manager_mutex) && \
314 !lockdep_is_held(&(pool)->lock), \
315 "pool->manager_mutex or ->lock should be held")
317 #define assert_manager_or_pool_lock(pool) do { } while (0)
320 #define for_each_cpu_worker_pool(pool, cpu) \
321 for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
322 (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
326 * for_each_pool - iterate through all worker_pools in the system
327 * @pool: iteration cursor
328 * @pi: integer used for iteration
330 * This must be called either with wq_pool_mutex held or sched RCU read
331 * locked. If the pool needs to be used beyond the locking in effect, the
332 * caller is responsible for guaranteeing that the pool stays online.
334 * The if/else clause exists only for the lockdep assertion and can be
337 #define for_each_pool(pool, pi) \
338 idr_for_each_entry(&worker_pool_idr, pool, pi) \
339 if (({ assert_rcu_or_pool_mutex(); false; })) { } \
343 * for_each_pool_worker - iterate through all workers of a worker_pool
344 * @worker: iteration cursor
345 * @wi: integer used for iteration
346 * @pool: worker_pool to iterate workers of
348 * This must be called with either @pool->manager_mutex or ->lock held.
350 * The if/else clause exists only for the lockdep assertion and can be
353 #define for_each_pool_worker(worker, wi, pool) \
354 idr_for_each_entry(&(pool)->worker_idr, (worker), (wi)) \
355 if (({ assert_manager_or_pool_lock((pool)); false; })) { } \
359 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
360 * @pwq: iteration cursor
361 * @wq: the target workqueue
363 * This must be called either with wq->mutex held or sched RCU read locked.
364 * If the pwq needs to be used beyond the locking in effect, the caller is
365 * responsible for guaranteeing that the pwq stays online.
367 * The if/else clause exists only for the lockdep assertion and can be
370 #define for_each_pwq(pwq, wq) \
371 list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node) \
372 if (({ assert_rcu_or_wq_mutex(wq); false; })) { } \
375 #ifdef CONFIG_DEBUG_OBJECTS_WORK
377 static struct debug_obj_descr work_debug_descr;
379 static void *work_debug_hint(void *addr)
381 return ((struct work_struct *) addr)->func;
385 * fixup_init is called when:
386 * - an active object is initialized
388 static int work_fixup_init(void *addr, enum debug_obj_state state)
390 struct work_struct *work = addr;
393 case ODEBUG_STATE_ACTIVE:
394 cancel_work_sync(work);
395 debug_object_init(work, &work_debug_descr);
403 * fixup_activate is called when:
404 * - an active object is activated
405 * - an unknown object is activated (might be a statically initialized object)
407 static int work_fixup_activate(void *addr, enum debug_obj_state state)
409 struct work_struct *work = addr;
413 case ODEBUG_STATE_NOTAVAILABLE:
415 * This is not really a fixup. The work struct was
416 * statically initialized. We just make sure that it
417 * is tracked in the object tracker.
419 if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
420 debug_object_init(work, &work_debug_descr);
421 debug_object_activate(work, &work_debug_descr);
427 case ODEBUG_STATE_ACTIVE:
436 * fixup_free is called when:
437 * - an active object is freed
439 static int work_fixup_free(void *addr, enum debug_obj_state state)
441 struct work_struct *work = addr;
444 case ODEBUG_STATE_ACTIVE:
445 cancel_work_sync(work);
446 debug_object_free(work, &work_debug_descr);
453 static struct debug_obj_descr work_debug_descr = {
454 .name = "work_struct",
455 .debug_hint = work_debug_hint,
456 .fixup_init = work_fixup_init,
457 .fixup_activate = work_fixup_activate,
458 .fixup_free = work_fixup_free,
461 static inline void debug_work_activate(struct work_struct *work)
463 debug_object_activate(work, &work_debug_descr);
466 static inline void debug_work_deactivate(struct work_struct *work)
468 debug_object_deactivate(work, &work_debug_descr);
471 void __init_work(struct work_struct *work, int onstack)
474 debug_object_init_on_stack(work, &work_debug_descr);
476 debug_object_init(work, &work_debug_descr);
478 EXPORT_SYMBOL_GPL(__init_work);
480 void destroy_work_on_stack(struct work_struct *work)
482 debug_object_free(work, &work_debug_descr);
484 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
487 static inline void debug_work_activate(struct work_struct *work) { }
488 static inline void debug_work_deactivate(struct work_struct *work) { }
491 /* allocate ID and assign it to @pool */
492 static int worker_pool_assign_id(struct worker_pool *pool)
496 lockdep_assert_held(&wq_pool_mutex);
499 if (!idr_pre_get(&worker_pool_idr, GFP_KERNEL))
501 ret = idr_get_new(&worker_pool_idr, pool, &pool->id);
502 } while (ret == -EAGAIN);
508 * first_pwq - return the first pool_workqueue of the specified workqueue
509 * @wq: the target workqueue
511 * This must be called either with wq->mutex held or sched RCU read locked.
512 * If the pwq needs to be used beyond the locking in effect, the caller is
513 * responsible for guaranteeing that the pwq stays online.
515 static struct pool_workqueue *first_pwq(struct workqueue_struct *wq)
517 assert_rcu_or_wq_mutex(wq);
518 return list_first_or_null_rcu(&wq->pwqs, struct pool_workqueue,
522 static unsigned int work_color_to_flags(int color)
524 return color << WORK_STRUCT_COLOR_SHIFT;
527 static int get_work_color(struct work_struct *work)
529 return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
530 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
533 static int work_next_color(int color)
535 return (color + 1) % WORK_NR_COLORS;
539 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
540 * contain the pointer to the queued pwq. Once execution starts, the flag
541 * is cleared and the high bits contain OFFQ flags and pool ID.
543 * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
544 * and clear_work_data() can be used to set the pwq, pool or clear
545 * work->data. These functions should only be called while the work is
546 * owned - ie. while the PENDING bit is set.
548 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
549 * corresponding to a work. Pool is available once the work has been
550 * queued anywhere after initialization until it is sync canceled. pwq is
551 * available only while the work item is queued.
553 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
554 * canceled. While being canceled, a work item may have its PENDING set
555 * but stay off timer and worklist for arbitrarily long and nobody should
556 * try to steal the PENDING bit.
558 static inline void set_work_data(struct work_struct *work, unsigned long data,
561 WARN_ON_ONCE(!work_pending(work));
562 atomic_long_set(&work->data, data | flags | work_static(work));
565 static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
566 unsigned long extra_flags)
568 set_work_data(work, (unsigned long)pwq,
569 WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
572 static void set_work_pool_and_keep_pending(struct work_struct *work,
575 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
576 WORK_STRUCT_PENDING);
579 static void set_work_pool_and_clear_pending(struct work_struct *work,
583 * The following wmb is paired with the implied mb in
584 * test_and_set_bit(PENDING) and ensures all updates to @work made
585 * here are visible to and precede any updates by the next PENDING
589 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
592 static void clear_work_data(struct work_struct *work)
594 smp_wmb(); /* see set_work_pool_and_clear_pending() */
595 set_work_data(work, WORK_STRUCT_NO_POOL, 0);
598 static struct pool_workqueue *get_work_pwq(struct work_struct *work)
600 unsigned long data = atomic_long_read(&work->data);
602 if (data & WORK_STRUCT_PWQ)
603 return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
609 * get_work_pool - return the worker_pool a given work was associated with
610 * @work: the work item of interest
612 * Return the worker_pool @work was last associated with. %NULL if none.
614 * Pools are created and destroyed under wq_pool_mutex, and allows read
615 * access under sched-RCU read lock. As such, this function should be
616 * called under wq_pool_mutex or with preemption disabled.
618 * All fields of the returned pool are accessible as long as the above
619 * mentioned locking is in effect. If the returned pool needs to be used
620 * beyond the critical section, the caller is responsible for ensuring the
621 * returned pool is and stays online.
623 static struct worker_pool *get_work_pool(struct work_struct *work)
625 unsigned long data = atomic_long_read(&work->data);
628 assert_rcu_or_pool_mutex();
630 if (data & WORK_STRUCT_PWQ)
631 return ((struct pool_workqueue *)
632 (data & WORK_STRUCT_WQ_DATA_MASK))->pool;
634 pool_id = data >> WORK_OFFQ_POOL_SHIFT;
635 if (pool_id == WORK_OFFQ_POOL_NONE)
638 return idr_find(&worker_pool_idr, pool_id);
642 * get_work_pool_id - return the worker pool ID a given work is associated with
643 * @work: the work item of interest
645 * Return the worker_pool ID @work was last associated with.
646 * %WORK_OFFQ_POOL_NONE if none.
648 static int get_work_pool_id(struct work_struct *work)
650 unsigned long data = atomic_long_read(&work->data);
652 if (data & WORK_STRUCT_PWQ)
653 return ((struct pool_workqueue *)
654 (data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
656 return data >> WORK_OFFQ_POOL_SHIFT;
659 static void mark_work_canceling(struct work_struct *work)
661 unsigned long pool_id = get_work_pool_id(work);
663 pool_id <<= WORK_OFFQ_POOL_SHIFT;
664 set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
667 static bool work_is_canceling(struct work_struct *work)
669 unsigned long data = atomic_long_read(&work->data);
671 return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
675 * Policy functions. These define the policies on how the global worker
676 * pools are managed. Unless noted otherwise, these functions assume that
677 * they're being called with pool->lock held.
680 static bool __need_more_worker(struct worker_pool *pool)
682 return !atomic_read(&pool->nr_running);
686 * Need to wake up a worker? Called from anything but currently
689 * Note that, because unbound workers never contribute to nr_running, this
690 * function will always return %true for unbound pools as long as the
691 * worklist isn't empty.
693 static bool need_more_worker(struct worker_pool *pool)
695 return !list_empty(&pool->worklist) && __need_more_worker(pool);
698 /* Can I start working? Called from busy but !running workers. */
699 static bool may_start_working(struct worker_pool *pool)
701 return pool->nr_idle;
704 /* Do I need to keep working? Called from currently running workers. */
705 static bool keep_working(struct worker_pool *pool)
707 return !list_empty(&pool->worklist) &&
708 atomic_read(&pool->nr_running) <= 1;
711 /* Do we need a new worker? Called from manager. */
712 static bool need_to_create_worker(struct worker_pool *pool)
714 return need_more_worker(pool) && !may_start_working(pool);
717 /* Do I need to be the manager? */
718 static bool need_to_manage_workers(struct worker_pool *pool)
720 return need_to_create_worker(pool) ||
721 (pool->flags & POOL_MANAGE_WORKERS);
724 /* Do we have too many workers and should some go away? */
725 static bool too_many_workers(struct worker_pool *pool)
727 bool managing = mutex_is_locked(&pool->manager_arb);
728 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
729 int nr_busy = pool->nr_workers - nr_idle;
732 * nr_idle and idle_list may disagree if idle rebinding is in
733 * progress. Never return %true if idle_list is empty.
735 if (list_empty(&pool->idle_list))
738 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
745 /* Return the first worker. Safe with preemption disabled */
746 static struct worker *first_worker(struct worker_pool *pool)
748 if (unlikely(list_empty(&pool->idle_list)))
751 return list_first_entry(&pool->idle_list, struct worker, entry);
755 * wake_up_worker - wake up an idle worker
756 * @pool: worker pool to wake worker from
758 * Wake up the first idle worker of @pool.
761 * spin_lock_irq(pool->lock).
763 static void wake_up_worker(struct worker_pool *pool)
765 struct worker *worker = first_worker(pool);
768 wake_up_process(worker->task);
772 * wq_worker_waking_up - a worker is waking up
773 * @task: task waking up
774 * @cpu: CPU @task is waking up to
776 * This function is called during try_to_wake_up() when a worker is
780 * spin_lock_irq(rq->lock)
782 void wq_worker_waking_up(struct task_struct *task, int cpu)
784 struct worker *worker = kthread_data(task);
786 if (!(worker->flags & WORKER_NOT_RUNNING)) {
787 WARN_ON_ONCE(worker->pool->cpu != cpu);
788 atomic_inc(&worker->pool->nr_running);
793 * wq_worker_sleeping - a worker is going to sleep
794 * @task: task going to sleep
795 * @cpu: CPU in question, must be the current CPU number
797 * This function is called during schedule() when a busy worker is
798 * going to sleep. Worker on the same cpu can be woken up by
799 * returning pointer to its task.
802 * spin_lock_irq(rq->lock)
805 * Worker task on @cpu to wake up, %NULL if none.
807 struct task_struct *wq_worker_sleeping(struct task_struct *task, int cpu)
809 struct worker *worker = kthread_data(task), *to_wakeup = NULL;
810 struct worker_pool *pool;
813 * Rescuers, which may not have all the fields set up like normal
814 * workers, also reach here, let's not access anything before
815 * checking NOT_RUNNING.
817 if (worker->flags & WORKER_NOT_RUNNING)
822 /* this can only happen on the local cpu */
823 if (WARN_ON_ONCE(cpu != raw_smp_processor_id()))
827 * The counterpart of the following dec_and_test, implied mb,
828 * worklist not empty test sequence is in insert_work().
829 * Please read comment there.
831 * NOT_RUNNING is clear. This means that we're bound to and
832 * running on the local cpu w/ rq lock held and preemption
833 * disabled, which in turn means that none else could be
834 * manipulating idle_list, so dereferencing idle_list without pool
837 if (atomic_dec_and_test(&pool->nr_running) &&
838 !list_empty(&pool->worklist))
839 to_wakeup = first_worker(pool);
840 return to_wakeup ? to_wakeup->task : NULL;
844 * worker_set_flags - set worker flags and adjust nr_running accordingly
846 * @flags: flags to set
847 * @wakeup: wakeup an idle worker if necessary
849 * Set @flags in @worker->flags and adjust nr_running accordingly. If
850 * nr_running becomes zero and @wakeup is %true, an idle worker is
854 * spin_lock_irq(pool->lock)
856 static inline void worker_set_flags(struct worker *worker, unsigned int flags,
859 struct worker_pool *pool = worker->pool;
861 WARN_ON_ONCE(worker->task != current);
864 * If transitioning into NOT_RUNNING, adjust nr_running and
865 * wake up an idle worker as necessary if requested by
868 if ((flags & WORKER_NOT_RUNNING) &&
869 !(worker->flags & WORKER_NOT_RUNNING)) {
871 if (atomic_dec_and_test(&pool->nr_running) &&
872 !list_empty(&pool->worklist))
873 wake_up_worker(pool);
875 atomic_dec(&pool->nr_running);
878 worker->flags |= flags;
882 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
884 * @flags: flags to clear
886 * Clear @flags in @worker->flags and adjust nr_running accordingly.
889 * spin_lock_irq(pool->lock)
891 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
893 struct worker_pool *pool = worker->pool;
894 unsigned int oflags = worker->flags;
896 WARN_ON_ONCE(worker->task != current);
898 worker->flags &= ~flags;
901 * If transitioning out of NOT_RUNNING, increment nr_running. Note
902 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
903 * of multiple flags, not a single flag.
905 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
906 if (!(worker->flags & WORKER_NOT_RUNNING))
907 atomic_inc(&pool->nr_running);
911 * find_worker_executing_work - find worker which is executing a work
912 * @pool: pool of interest
913 * @work: work to find worker for
915 * Find a worker which is executing @work on @pool by searching
916 * @pool->busy_hash which is keyed by the address of @work. For a worker
917 * to match, its current execution should match the address of @work and
918 * its work function. This is to avoid unwanted dependency between
919 * unrelated work executions through a work item being recycled while still
922 * This is a bit tricky. A work item may be freed once its execution
923 * starts and nothing prevents the freed area from being recycled for
924 * another work item. If the same work item address ends up being reused
925 * before the original execution finishes, workqueue will identify the
926 * recycled work item as currently executing and make it wait until the
927 * current execution finishes, introducing an unwanted dependency.
929 * This function checks the work item address and work function to avoid
930 * false positives. Note that this isn't complete as one may construct a
931 * work function which can introduce dependency onto itself through a
932 * recycled work item. Well, if somebody wants to shoot oneself in the
933 * foot that badly, there's only so much we can do, and if such deadlock
934 * actually occurs, it should be easy to locate the culprit work function.
937 * spin_lock_irq(pool->lock).
940 * Pointer to worker which is executing @work if found, NULL
943 static struct worker *find_worker_executing_work(struct worker_pool *pool,
944 struct work_struct *work)
946 struct worker *worker;
948 hash_for_each_possible(pool->busy_hash, worker, hentry,
950 if (worker->current_work == work &&
951 worker->current_func == work->func)
958 * move_linked_works - move linked works to a list
959 * @work: start of series of works to be scheduled
960 * @head: target list to append @work to
961 * @nextp: out paramter for nested worklist walking
963 * Schedule linked works starting from @work to @head. Work series to
964 * be scheduled starts at @work and includes any consecutive work with
965 * WORK_STRUCT_LINKED set in its predecessor.
967 * If @nextp is not NULL, it's updated to point to the next work of
968 * the last scheduled work. This allows move_linked_works() to be
969 * nested inside outer list_for_each_entry_safe().
972 * spin_lock_irq(pool->lock).
974 static void move_linked_works(struct work_struct *work, struct list_head *head,
975 struct work_struct **nextp)
977 struct work_struct *n;
980 * Linked worklist will always end before the end of the list,
981 * use NULL for list head.
983 list_for_each_entry_safe_from(work, n, NULL, entry) {
984 list_move_tail(&work->entry, head);
985 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
990 * If we're already inside safe list traversal and have moved
991 * multiple works to the scheduled queue, the next position
992 * needs to be updated.
999 * get_pwq - get an extra reference on the specified pool_workqueue
1000 * @pwq: pool_workqueue to get
1002 * Obtain an extra reference on @pwq. The caller should guarantee that
1003 * @pwq has positive refcnt and be holding the matching pool->lock.
1005 static void get_pwq(struct pool_workqueue *pwq)
1007 lockdep_assert_held(&pwq->pool->lock);
1008 WARN_ON_ONCE(pwq->refcnt <= 0);
1013 * put_pwq - put a pool_workqueue reference
1014 * @pwq: pool_workqueue to put
1016 * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
1017 * destruction. The caller should be holding the matching pool->lock.
1019 static void put_pwq(struct pool_workqueue *pwq)
1021 lockdep_assert_held(&pwq->pool->lock);
1022 if (likely(--pwq->refcnt))
1024 if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
1027 * @pwq can't be released under pool->lock, bounce to
1028 * pwq_unbound_release_workfn(). This never recurses on the same
1029 * pool->lock as this path is taken only for unbound workqueues and
1030 * the release work item is scheduled on a per-cpu workqueue. To
1031 * avoid lockdep warning, unbound pool->locks are given lockdep
1032 * subclass of 1 in get_unbound_pool().
1034 schedule_work(&pwq->unbound_release_work);
1037 static void pwq_activate_delayed_work(struct work_struct *work)
1039 struct pool_workqueue *pwq = get_work_pwq(work);
1041 trace_workqueue_activate_work(work);
1042 move_linked_works(work, &pwq->pool->worklist, NULL);
1043 __clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
1047 static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
1049 struct work_struct *work = list_first_entry(&pwq->delayed_works,
1050 struct work_struct, entry);
1052 pwq_activate_delayed_work(work);
1056 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1057 * @pwq: pwq of interest
1058 * @color: color of work which left the queue
1060 * A work either has completed or is removed from pending queue,
1061 * decrement nr_in_flight of its pwq and handle workqueue flushing.
1064 * spin_lock_irq(pool->lock).
1066 static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
1068 /* uncolored work items don't participate in flushing or nr_active */
1069 if (color == WORK_NO_COLOR)
1072 pwq->nr_in_flight[color]--;
1075 if (!list_empty(&pwq->delayed_works)) {
1076 /* one down, submit a delayed one */
1077 if (pwq->nr_active < pwq->max_active)
1078 pwq_activate_first_delayed(pwq);
1081 /* is flush in progress and are we at the flushing tip? */
1082 if (likely(pwq->flush_color != color))
1085 /* are there still in-flight works? */
1086 if (pwq->nr_in_flight[color])
1089 /* this pwq is done, clear flush_color */
1090 pwq->flush_color = -1;
1093 * If this was the last pwq, wake up the first flusher. It
1094 * will handle the rest.
1096 if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1097 complete(&pwq->wq->first_flusher->done);
1103 * try_to_grab_pending - steal work item from worklist and disable irq
1104 * @work: work item to steal
1105 * @is_dwork: @work is a delayed_work
1106 * @flags: place to store irq state
1108 * Try to grab PENDING bit of @work. This function can handle @work in any
1109 * stable state - idle, on timer or on worklist. Return values are
1111 * 1 if @work was pending and we successfully stole PENDING
1112 * 0 if @work was idle and we claimed PENDING
1113 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1114 * -ENOENT if someone else is canceling @work, this state may persist
1115 * for arbitrarily long
1117 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1118 * interrupted while holding PENDING and @work off queue, irq must be
1119 * disabled on entry. This, combined with delayed_work->timer being
1120 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1122 * On successful return, >= 0, irq is disabled and the caller is
1123 * responsible for releasing it using local_irq_restore(*@flags).
1125 * This function is safe to call from any context including IRQ handler.
1127 static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1128 unsigned long *flags)
1130 struct worker_pool *pool;
1131 struct pool_workqueue *pwq;
1133 local_irq_save(*flags);
1135 /* try to steal the timer if it exists */
1137 struct delayed_work *dwork = to_delayed_work(work);
1140 * dwork->timer is irqsafe. If del_timer() fails, it's
1141 * guaranteed that the timer is not queued anywhere and not
1142 * running on the local CPU.
1144 if (likely(del_timer(&dwork->timer)))
1148 /* try to claim PENDING the normal way */
1149 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1153 * The queueing is in progress, or it is already queued. Try to
1154 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1156 pool = get_work_pool(work);
1160 spin_lock(&pool->lock);
1162 * work->data is guaranteed to point to pwq only while the work
1163 * item is queued on pwq->wq, and both updating work->data to point
1164 * to pwq on queueing and to pool on dequeueing are done under
1165 * pwq->pool->lock. This in turn guarantees that, if work->data
1166 * points to pwq which is associated with a locked pool, the work
1167 * item is currently queued on that pool.
1169 pwq = get_work_pwq(work);
1170 if (pwq && pwq->pool == pool) {
1171 debug_work_deactivate(work);
1174 * A delayed work item cannot be grabbed directly because
1175 * it might have linked NO_COLOR work items which, if left
1176 * on the delayed_list, will confuse pwq->nr_active
1177 * management later on and cause stall. Make sure the work
1178 * item is activated before grabbing.
1180 if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1181 pwq_activate_delayed_work(work);
1183 list_del_init(&work->entry);
1184 pwq_dec_nr_in_flight(get_work_pwq(work), get_work_color(work));
1186 /* work->data points to pwq iff queued, point to pool */
1187 set_work_pool_and_keep_pending(work, pool->id);
1189 spin_unlock(&pool->lock);
1192 spin_unlock(&pool->lock);
1194 local_irq_restore(*flags);
1195 if (work_is_canceling(work))
1202 * insert_work - insert a work into a pool
1203 * @pwq: pwq @work belongs to
1204 * @work: work to insert
1205 * @head: insertion point
1206 * @extra_flags: extra WORK_STRUCT_* flags to set
1208 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
1209 * work_struct flags.
1212 * spin_lock_irq(pool->lock).
1214 static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1215 struct list_head *head, unsigned int extra_flags)
1217 struct worker_pool *pool = pwq->pool;
1219 /* we own @work, set data and link */
1220 set_work_pwq(work, pwq, extra_flags);
1221 list_add_tail(&work->entry, head);
1225 * Ensure either wq_worker_sleeping() sees the above
1226 * list_add_tail() or we see zero nr_running to avoid workers lying
1227 * around lazily while there are works to be processed.
1231 if (__need_more_worker(pool))
1232 wake_up_worker(pool);
1236 * Test whether @work is being queued from another work executing on the
1239 static bool is_chained_work(struct workqueue_struct *wq)
1241 struct worker *worker;
1243 worker = current_wq_worker();
1245 * Return %true iff I'm a worker execuing a work item on @wq. If
1246 * I'm @worker, it's safe to dereference it without locking.
1248 return worker && worker->current_pwq->wq == wq;
1251 static void __queue_work(int cpu, struct workqueue_struct *wq,
1252 struct work_struct *work)
1254 struct pool_workqueue *pwq;
1255 struct worker_pool *last_pool;
1256 struct list_head *worklist;
1257 unsigned int work_flags;
1258 unsigned int req_cpu = cpu;
1261 * While a work item is PENDING && off queue, a task trying to
1262 * steal the PENDING will busy-loop waiting for it to either get
1263 * queued or lose PENDING. Grabbing PENDING and queueing should
1264 * happen with IRQ disabled.
1266 WARN_ON_ONCE(!irqs_disabled());
1268 debug_work_activate(work);
1270 /* if dying, only works from the same workqueue are allowed */
1271 if (unlikely(wq->flags & __WQ_DRAINING) &&
1272 WARN_ON_ONCE(!is_chained_work(wq)))
1275 /* pwq which will be used unless @work is executing elsewhere */
1276 if (!(wq->flags & WQ_UNBOUND)) {
1277 if (cpu == WORK_CPU_UNBOUND)
1278 cpu = raw_smp_processor_id();
1279 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1281 pwq = first_pwq(wq);
1285 * If @work was previously on a different pool, it might still be
1286 * running there, in which case the work needs to be queued on that
1287 * pool to guarantee non-reentrancy.
1289 last_pool = get_work_pool(work);
1290 if (last_pool && last_pool != pwq->pool) {
1291 struct worker *worker;
1293 spin_lock(&last_pool->lock);
1295 worker = find_worker_executing_work(last_pool, work);
1297 if (worker && worker->current_pwq->wq == wq) {
1298 pwq = worker->current_pwq;
1300 /* meh... not running there, queue here */
1301 spin_unlock(&last_pool->lock);
1302 spin_lock(&pwq->pool->lock);
1305 spin_lock(&pwq->pool->lock);
1309 * pwq is determined and locked. For unbound pools, we could have
1310 * raced with pwq release and it could already be dead. If its
1311 * refcnt is zero, repeat pwq selection. Note that pwqs never die
1312 * without another pwq replacing it as the first pwq or while a
1313 * work item is executing on it, so the retying is guaranteed to
1314 * make forward-progress.
1316 if (unlikely(!pwq->refcnt)) {
1317 if (wq->flags & WQ_UNBOUND) {
1318 spin_unlock(&pwq->pool->lock);
1323 WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
1327 /* pwq determined, queue */
1328 trace_workqueue_queue_work(req_cpu, pwq, work);
1330 if (WARN_ON(!list_empty(&work->entry))) {
1331 spin_unlock(&pwq->pool->lock);
1335 pwq->nr_in_flight[pwq->work_color]++;
1336 work_flags = work_color_to_flags(pwq->work_color);
1338 if (likely(pwq->nr_active < pwq->max_active)) {
1339 trace_workqueue_activate_work(work);
1341 worklist = &pwq->pool->worklist;
1343 work_flags |= WORK_STRUCT_DELAYED;
1344 worklist = &pwq->delayed_works;
1347 insert_work(pwq, work, worklist, work_flags);
1349 spin_unlock(&pwq->pool->lock);
1353 * queue_work_on - queue work on specific cpu
1354 * @cpu: CPU number to execute work on
1355 * @wq: workqueue to use
1356 * @work: work to queue
1358 * Returns %false if @work was already on a queue, %true otherwise.
1360 * We queue the work to a specific CPU, the caller must ensure it
1363 bool queue_work_on(int cpu, struct workqueue_struct *wq,
1364 struct work_struct *work)
1367 unsigned long flags;
1369 local_irq_save(flags);
1371 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1372 __queue_work(cpu, wq, work);
1376 local_irq_restore(flags);
1379 EXPORT_SYMBOL_GPL(queue_work_on);
1381 void delayed_work_timer_fn(unsigned long __data)
1383 struct delayed_work *dwork = (struct delayed_work *)__data;
1385 /* should have been called from irqsafe timer with irq already off */
1386 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
1388 EXPORT_SYMBOL(delayed_work_timer_fn);
1390 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
1391 struct delayed_work *dwork, unsigned long delay)
1393 struct timer_list *timer = &dwork->timer;
1394 struct work_struct *work = &dwork->work;
1396 WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
1397 timer->data != (unsigned long)dwork);
1398 WARN_ON_ONCE(timer_pending(timer));
1399 WARN_ON_ONCE(!list_empty(&work->entry));
1402 * If @delay is 0, queue @dwork->work immediately. This is for
1403 * both optimization and correctness. The earliest @timer can
1404 * expire is on the closest next tick and delayed_work users depend
1405 * on that there's no such delay when @delay is 0.
1408 __queue_work(cpu, wq, &dwork->work);
1412 timer_stats_timer_set_start_info(&dwork->timer);
1416 timer->expires = jiffies + delay;
1418 if (unlikely(cpu != WORK_CPU_UNBOUND))
1419 add_timer_on(timer, cpu);
1425 * queue_delayed_work_on - queue work on specific CPU after delay
1426 * @cpu: CPU number to execute work on
1427 * @wq: workqueue to use
1428 * @dwork: work to queue
1429 * @delay: number of jiffies to wait before queueing
1431 * Returns %false if @work was already on a queue, %true otherwise. If
1432 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1435 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1436 struct delayed_work *dwork, unsigned long delay)
1438 struct work_struct *work = &dwork->work;
1440 unsigned long flags;
1442 /* read the comment in __queue_work() */
1443 local_irq_save(flags);
1445 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1446 __queue_delayed_work(cpu, wq, dwork, delay);
1450 local_irq_restore(flags);
1453 EXPORT_SYMBOL_GPL(queue_delayed_work_on);
1456 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1457 * @cpu: CPU number to execute work on
1458 * @wq: workqueue to use
1459 * @dwork: work to queue
1460 * @delay: number of jiffies to wait before queueing
1462 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1463 * modify @dwork's timer so that it expires after @delay. If @delay is
1464 * zero, @work is guaranteed to be scheduled immediately regardless of its
1467 * Returns %false if @dwork was idle and queued, %true if @dwork was
1468 * pending and its timer was modified.
1470 * This function is safe to call from any context including IRQ handler.
1471 * See try_to_grab_pending() for details.
1473 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
1474 struct delayed_work *dwork, unsigned long delay)
1476 unsigned long flags;
1480 ret = try_to_grab_pending(&dwork->work, true, &flags);
1481 } while (unlikely(ret == -EAGAIN));
1483 if (likely(ret >= 0)) {
1484 __queue_delayed_work(cpu, wq, dwork, delay);
1485 local_irq_restore(flags);
1488 /* -ENOENT from try_to_grab_pending() becomes %true */
1491 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
1494 * worker_enter_idle - enter idle state
1495 * @worker: worker which is entering idle state
1497 * @worker is entering idle state. Update stats and idle timer if
1501 * spin_lock_irq(pool->lock).
1503 static void worker_enter_idle(struct worker *worker)
1505 struct worker_pool *pool = worker->pool;
1507 if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
1508 WARN_ON_ONCE(!list_empty(&worker->entry) &&
1509 (worker->hentry.next || worker->hentry.pprev)))
1512 /* can't use worker_set_flags(), also called from start_worker() */
1513 worker->flags |= WORKER_IDLE;
1515 worker->last_active = jiffies;
1517 /* idle_list is LIFO */
1518 list_add(&worker->entry, &pool->idle_list);
1520 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1521 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1524 * Sanity check nr_running. Because wq_unbind_fn() releases
1525 * pool->lock between setting %WORKER_UNBOUND and zapping
1526 * nr_running, the warning may trigger spuriously. Check iff
1527 * unbind is not in progress.
1529 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1530 pool->nr_workers == pool->nr_idle &&
1531 atomic_read(&pool->nr_running));
1535 * worker_leave_idle - leave idle state
1536 * @worker: worker which is leaving idle state
1538 * @worker is leaving idle state. Update stats.
1541 * spin_lock_irq(pool->lock).
1543 static void worker_leave_idle(struct worker *worker)
1545 struct worker_pool *pool = worker->pool;
1547 if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
1549 worker_clr_flags(worker, WORKER_IDLE);
1551 list_del_init(&worker->entry);
1555 * worker_maybe_bind_and_lock - try to bind %current to worker_pool and lock it
1556 * @pool: target worker_pool
1558 * Bind %current to the cpu of @pool if it is associated and lock @pool.
1560 * Works which are scheduled while the cpu is online must at least be
1561 * scheduled to a worker which is bound to the cpu so that if they are
1562 * flushed from cpu callbacks while cpu is going down, they are
1563 * guaranteed to execute on the cpu.
1565 * This function is to be used by unbound workers and rescuers to bind
1566 * themselves to the target cpu and may race with cpu going down or
1567 * coming online. kthread_bind() can't be used because it may put the
1568 * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1569 * verbatim as it's best effort and blocking and pool may be
1570 * [dis]associated in the meantime.
1572 * This function tries set_cpus_allowed() and locks pool and verifies the
1573 * binding against %POOL_DISASSOCIATED which is set during
1574 * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
1575 * enters idle state or fetches works without dropping lock, it can
1576 * guarantee the scheduling requirement described in the first paragraph.
1579 * Might sleep. Called without any lock but returns with pool->lock
1583 * %true if the associated pool is online (@worker is successfully
1584 * bound), %false if offline.
1586 static bool worker_maybe_bind_and_lock(struct worker_pool *pool)
1587 __acquires(&pool->lock)
1591 * The following call may fail, succeed or succeed
1592 * without actually migrating the task to the cpu if
1593 * it races with cpu hotunplug operation. Verify
1594 * against POOL_DISASSOCIATED.
1596 if (!(pool->flags & POOL_DISASSOCIATED))
1597 set_cpus_allowed_ptr(current, pool->attrs->cpumask);
1599 spin_lock_irq(&pool->lock);
1600 if (pool->flags & POOL_DISASSOCIATED)
1602 if (task_cpu(current) == pool->cpu &&
1603 cpumask_equal(¤t->cpus_allowed, pool->attrs->cpumask))
1605 spin_unlock_irq(&pool->lock);
1608 * We've raced with CPU hot[un]plug. Give it a breather
1609 * and retry migration. cond_resched() is required here;
1610 * otherwise, we might deadlock against cpu_stop trying to
1611 * bring down the CPU on non-preemptive kernel.
1618 static struct worker *alloc_worker(void)
1620 struct worker *worker;
1622 worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1624 INIT_LIST_HEAD(&worker->entry);
1625 INIT_LIST_HEAD(&worker->scheduled);
1626 /* on creation a worker is in !idle && prep state */
1627 worker->flags = WORKER_PREP;
1633 * create_worker - create a new workqueue worker
1634 * @pool: pool the new worker will belong to
1636 * Create a new worker which is bound to @pool. The returned worker
1637 * can be started by calling start_worker() or destroyed using
1641 * Might sleep. Does GFP_KERNEL allocations.
1644 * Pointer to the newly created worker.
1646 static struct worker *create_worker(struct worker_pool *pool)
1648 struct worker *worker = NULL;
1652 lockdep_assert_held(&pool->manager_mutex);
1655 * ID is needed to determine kthread name. Allocate ID first
1656 * without installing the pointer.
1658 idr_preload(GFP_KERNEL);
1659 spin_lock_irq(&pool->lock);
1661 id = idr_alloc(&pool->worker_idr, NULL, 0, 0, GFP_NOWAIT);
1663 spin_unlock_irq(&pool->lock);
1668 worker = alloc_worker();
1672 worker->pool = pool;
1676 snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
1677 pool->attrs->nice < 0 ? "H" : "");
1679 snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
1681 worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
1682 "kworker/%s", id_buf);
1683 if (IS_ERR(worker->task))
1687 * set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
1688 * online CPUs. It'll be re-applied when any of the CPUs come up.
1690 set_user_nice(worker->task, pool->attrs->nice);
1691 set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
1693 /* prevent userland from meddling with cpumask of workqueue workers */
1694 worker->task->flags |= PF_NO_SETAFFINITY;
1697 * The caller is responsible for ensuring %POOL_DISASSOCIATED
1698 * remains stable across this function. See the comments above the
1699 * flag definition for details.
1701 if (pool->flags & POOL_DISASSOCIATED)
1702 worker->flags |= WORKER_UNBOUND;
1704 /* successful, commit the pointer to idr */
1705 spin_lock_irq(&pool->lock);
1706 idr_replace(&pool->worker_idr, worker, worker->id);
1707 spin_unlock_irq(&pool->lock);
1713 spin_lock_irq(&pool->lock);
1714 idr_remove(&pool->worker_idr, id);
1715 spin_unlock_irq(&pool->lock);
1722 * start_worker - start a newly created worker
1723 * @worker: worker to start
1725 * Make the pool aware of @worker and start it.
1728 * spin_lock_irq(pool->lock).
1730 static void start_worker(struct worker *worker)
1732 worker->flags |= WORKER_STARTED;
1733 worker->pool->nr_workers++;
1734 worker_enter_idle(worker);
1735 wake_up_process(worker->task);
1739 * create_and_start_worker - create and start a worker for a pool
1740 * @pool: the target pool
1742 * Grab the managership of @pool and create and start a new worker for it.
1744 static int create_and_start_worker(struct worker_pool *pool)
1746 struct worker *worker;
1748 mutex_lock(&pool->manager_mutex);
1750 worker = create_worker(pool);
1752 spin_lock_irq(&pool->lock);
1753 start_worker(worker);
1754 spin_unlock_irq(&pool->lock);
1757 mutex_unlock(&pool->manager_mutex);
1759 return worker ? 0 : -ENOMEM;
1763 * destroy_worker - destroy a workqueue worker
1764 * @worker: worker to be destroyed
1766 * Destroy @worker and adjust @pool stats accordingly.
1769 * spin_lock_irq(pool->lock) which is released and regrabbed.
1771 static void destroy_worker(struct worker *worker)
1773 struct worker_pool *pool = worker->pool;
1775 lockdep_assert_held(&pool->manager_mutex);
1776 lockdep_assert_held(&pool->lock);
1778 /* sanity check frenzy */
1779 if (WARN_ON(worker->current_work) ||
1780 WARN_ON(!list_empty(&worker->scheduled)))
1783 if (worker->flags & WORKER_STARTED)
1785 if (worker->flags & WORKER_IDLE)
1788 list_del_init(&worker->entry);
1789 worker->flags |= WORKER_DIE;
1791 idr_remove(&pool->worker_idr, worker->id);
1793 spin_unlock_irq(&pool->lock);
1795 kthread_stop(worker->task);
1798 spin_lock_irq(&pool->lock);
1801 static void idle_worker_timeout(unsigned long __pool)
1803 struct worker_pool *pool = (void *)__pool;
1805 spin_lock_irq(&pool->lock);
1807 if (too_many_workers(pool)) {
1808 struct worker *worker;
1809 unsigned long expires;
1811 /* idle_list is kept in LIFO order, check the last one */
1812 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1813 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1815 if (time_before(jiffies, expires))
1816 mod_timer(&pool->idle_timer, expires);
1818 /* it's been idle for too long, wake up manager */
1819 pool->flags |= POOL_MANAGE_WORKERS;
1820 wake_up_worker(pool);
1824 spin_unlock_irq(&pool->lock);
1827 static void send_mayday(struct work_struct *work)
1829 struct pool_workqueue *pwq = get_work_pwq(work);
1830 struct workqueue_struct *wq = pwq->wq;
1832 lockdep_assert_held(&wq_mayday_lock);
1837 /* mayday mayday mayday */
1838 if (list_empty(&pwq->mayday_node)) {
1839 list_add_tail(&pwq->mayday_node, &wq->maydays);
1840 wake_up_process(wq->rescuer->task);
1844 static void pool_mayday_timeout(unsigned long __pool)
1846 struct worker_pool *pool = (void *)__pool;
1847 struct work_struct *work;
1849 spin_lock_irq(&wq_mayday_lock); /* for wq->maydays */
1850 spin_lock(&pool->lock);
1852 if (need_to_create_worker(pool)) {
1854 * We've been trying to create a new worker but
1855 * haven't been successful. We might be hitting an
1856 * allocation deadlock. Send distress signals to
1859 list_for_each_entry(work, &pool->worklist, entry)
1863 spin_unlock(&pool->lock);
1864 spin_unlock_irq(&wq_mayday_lock);
1866 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1870 * maybe_create_worker - create a new worker if necessary
1871 * @pool: pool to create a new worker for
1873 * Create a new worker for @pool if necessary. @pool is guaranteed to
1874 * have at least one idle worker on return from this function. If
1875 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1876 * sent to all rescuers with works scheduled on @pool to resolve
1877 * possible allocation deadlock.
1879 * On return, need_to_create_worker() is guaranteed to be %false and
1880 * may_start_working() %true.
1883 * spin_lock_irq(pool->lock) which may be released and regrabbed
1884 * multiple times. Does GFP_KERNEL allocations. Called only from
1888 * %false if no action was taken and pool->lock stayed locked, %true
1891 static bool maybe_create_worker(struct worker_pool *pool)
1892 __releases(&pool->lock)
1893 __acquires(&pool->lock)
1895 if (!need_to_create_worker(pool))
1898 spin_unlock_irq(&pool->lock);
1900 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1901 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1904 struct worker *worker;
1906 worker = create_worker(pool);
1908 del_timer_sync(&pool->mayday_timer);
1909 spin_lock_irq(&pool->lock);
1910 start_worker(worker);
1911 if (WARN_ON_ONCE(need_to_create_worker(pool)))
1916 if (!need_to_create_worker(pool))
1919 __set_current_state(TASK_INTERRUPTIBLE);
1920 schedule_timeout(CREATE_COOLDOWN);
1922 if (!need_to_create_worker(pool))
1926 del_timer_sync(&pool->mayday_timer);
1927 spin_lock_irq(&pool->lock);
1928 if (need_to_create_worker(pool))
1934 * maybe_destroy_worker - destroy workers which have been idle for a while
1935 * @pool: pool to destroy workers for
1937 * Destroy @pool workers which have been idle for longer than
1938 * IDLE_WORKER_TIMEOUT.
1941 * spin_lock_irq(pool->lock) which may be released and regrabbed
1942 * multiple times. Called only from manager.
1945 * %false if no action was taken and pool->lock stayed locked, %true
1948 static bool maybe_destroy_workers(struct worker_pool *pool)
1952 while (too_many_workers(pool)) {
1953 struct worker *worker;
1954 unsigned long expires;
1956 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1957 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1959 if (time_before(jiffies, expires)) {
1960 mod_timer(&pool->idle_timer, expires);
1964 destroy_worker(worker);
1972 * manage_workers - manage worker pool
1975 * Assume the manager role and manage the worker pool @worker belongs
1976 * to. At any given time, there can be only zero or one manager per
1977 * pool. The exclusion is handled automatically by this function.
1979 * The caller can safely start processing works on false return. On
1980 * true return, it's guaranteed that need_to_create_worker() is false
1981 * and may_start_working() is true.
1984 * spin_lock_irq(pool->lock) which may be released and regrabbed
1985 * multiple times. Does GFP_KERNEL allocations.
1988 * spin_lock_irq(pool->lock) which may be released and regrabbed
1989 * multiple times. Does GFP_KERNEL allocations.
1991 static bool manage_workers(struct worker *worker)
1993 struct worker_pool *pool = worker->pool;
1997 * Managership is governed by two mutexes - manager_arb and
1998 * manager_mutex. manager_arb handles arbitration of manager role.
1999 * Anyone who successfully grabs manager_arb wins the arbitration
2000 * and becomes the manager. mutex_trylock() on pool->manager_arb
2001 * failure while holding pool->lock reliably indicates that someone
2002 * else is managing the pool and the worker which failed trylock
2003 * can proceed to executing work items. This means that anyone
2004 * grabbing manager_arb is responsible for actually performing
2005 * manager duties. If manager_arb is grabbed and released without
2006 * actual management, the pool may stall indefinitely.
2008 * manager_mutex is used for exclusion of actual management
2009 * operations. The holder of manager_mutex can be sure that none
2010 * of management operations, including creation and destruction of
2011 * workers, won't take place until the mutex is released. Because
2012 * manager_mutex doesn't interfere with manager role arbitration,
2013 * it is guaranteed that the pool's management, while may be
2014 * delayed, won't be disturbed by someone else grabbing
2017 if (!mutex_trylock(&pool->manager_arb))
2021 * With manager arbitration won, manager_mutex would be free in
2022 * most cases. trylock first without dropping @pool->lock.
2024 if (unlikely(!mutex_trylock(&pool->manager_mutex))) {
2025 spin_unlock_irq(&pool->lock);
2026 mutex_lock(&pool->manager_mutex);
2030 pool->flags &= ~POOL_MANAGE_WORKERS;
2033 * Destroy and then create so that may_start_working() is true
2036 ret |= maybe_destroy_workers(pool);
2037 ret |= maybe_create_worker(pool);
2039 mutex_unlock(&pool->manager_mutex);
2040 mutex_unlock(&pool->manager_arb);
2045 * process_one_work - process single work
2047 * @work: work to process
2049 * Process @work. This function contains all the logics necessary to
2050 * process a single work including synchronization against and
2051 * interaction with other workers on the same cpu, queueing and
2052 * flushing. As long as context requirement is met, any worker can
2053 * call this function to process a work.
2056 * spin_lock_irq(pool->lock) which is released and regrabbed.
2058 static void process_one_work(struct worker *worker, struct work_struct *work)
2059 __releases(&pool->lock)
2060 __acquires(&pool->lock)
2062 struct pool_workqueue *pwq = get_work_pwq(work);
2063 struct worker_pool *pool = worker->pool;
2064 bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
2066 struct worker *collision;
2067 #ifdef CONFIG_LOCKDEP
2069 * It is permissible to free the struct work_struct from
2070 * inside the function that is called from it, this we need to
2071 * take into account for lockdep too. To avoid bogus "held
2072 * lock freed" warnings as well as problems when looking into
2073 * work->lockdep_map, make a copy and use that here.
2075 struct lockdep_map lockdep_map;
2077 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
2080 * Ensure we're on the correct CPU. DISASSOCIATED test is
2081 * necessary to avoid spurious warnings from rescuers servicing the
2082 * unbound or a disassociated pool.
2084 WARN_ON_ONCE(!(worker->flags & WORKER_UNBOUND) &&
2085 !(pool->flags & POOL_DISASSOCIATED) &&
2086 raw_smp_processor_id() != pool->cpu);
2089 * A single work shouldn't be executed concurrently by
2090 * multiple workers on a single cpu. Check whether anyone is
2091 * already processing the work. If so, defer the work to the
2092 * currently executing one.
2094 collision = find_worker_executing_work(pool, work);
2095 if (unlikely(collision)) {
2096 move_linked_works(work, &collision->scheduled, NULL);
2100 /* claim and dequeue */
2101 debug_work_deactivate(work);
2102 hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2103 worker->current_work = work;
2104 worker->current_func = work->func;
2105 worker->current_pwq = pwq;
2106 work_color = get_work_color(work);
2108 list_del_init(&work->entry);
2111 * CPU intensive works don't participate in concurrency
2112 * management. They're the scheduler's responsibility.
2114 if (unlikely(cpu_intensive))
2115 worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
2118 * Unbound pool isn't concurrency managed and work items should be
2119 * executed ASAP. Wake up another worker if necessary.
2121 if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
2122 wake_up_worker(pool);
2125 * Record the last pool and clear PENDING which should be the last
2126 * update to @work. Also, do this inside @pool->lock so that
2127 * PENDING and queued state changes happen together while IRQ is
2130 set_work_pool_and_clear_pending(work, pool->id);
2132 spin_unlock_irq(&pool->lock);
2134 lock_map_acquire_read(&pwq->wq->lockdep_map);
2135 lock_map_acquire(&lockdep_map);
2136 trace_workqueue_execute_start(work);
2137 worker->current_func(work);
2139 * While we must be careful to not use "work" after this, the trace
2140 * point will only record its address.
2142 trace_workqueue_execute_end(work);
2143 lock_map_release(&lockdep_map);
2144 lock_map_release(&pwq->wq->lockdep_map);
2146 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2147 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2148 " last function: %pf\n",
2149 current->comm, preempt_count(), task_pid_nr(current),
2150 worker->current_func);
2151 debug_show_held_locks(current);
2155 spin_lock_irq(&pool->lock);
2157 /* clear cpu intensive status */
2158 if (unlikely(cpu_intensive))
2159 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2161 /* we're done with it, release */
2162 hash_del(&worker->hentry);
2163 worker->current_work = NULL;
2164 worker->current_func = NULL;
2165 worker->current_pwq = NULL;
2166 pwq_dec_nr_in_flight(pwq, work_color);
2170 * process_scheduled_works - process scheduled works
2173 * Process all scheduled works. Please note that the scheduled list
2174 * may change while processing a work, so this function repeatedly
2175 * fetches a work from the top and executes it.
2178 * spin_lock_irq(pool->lock) which may be released and regrabbed
2181 static void process_scheduled_works(struct worker *worker)
2183 while (!list_empty(&worker->scheduled)) {
2184 struct work_struct *work = list_first_entry(&worker->scheduled,
2185 struct work_struct, entry);
2186 process_one_work(worker, work);
2191 * worker_thread - the worker thread function
2194 * The worker thread function. All workers belong to a worker_pool -
2195 * either a per-cpu one or dynamic unbound one. These workers process all
2196 * work items regardless of their specific target workqueue. The only
2197 * exception is work items which belong to workqueues with a rescuer which
2198 * will be explained in rescuer_thread().
2200 static int worker_thread(void *__worker)
2202 struct worker *worker = __worker;
2203 struct worker_pool *pool = worker->pool;
2205 /* tell the scheduler that this is a workqueue worker */
2206 worker->task->flags |= PF_WQ_WORKER;
2208 spin_lock_irq(&pool->lock);
2210 /* am I supposed to die? */
2211 if (unlikely(worker->flags & WORKER_DIE)) {
2212 spin_unlock_irq(&pool->lock);
2213 WARN_ON_ONCE(!list_empty(&worker->entry));
2214 worker->task->flags &= ~PF_WQ_WORKER;
2218 worker_leave_idle(worker);
2220 /* no more worker necessary? */
2221 if (!need_more_worker(pool))
2224 /* do we need to manage? */
2225 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2229 * ->scheduled list can only be filled while a worker is
2230 * preparing to process a work or actually processing it.
2231 * Make sure nobody diddled with it while I was sleeping.
2233 WARN_ON_ONCE(!list_empty(&worker->scheduled));
2236 * Finish PREP stage. We're guaranteed to have at least one idle
2237 * worker or that someone else has already assumed the manager
2238 * role. This is where @worker starts participating in concurrency
2239 * management if applicable and concurrency management is restored
2240 * after being rebound. See rebind_workers() for details.
2242 worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2245 struct work_struct *work =
2246 list_first_entry(&pool->worklist,
2247 struct work_struct, entry);
2249 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2250 /* optimization path, not strictly necessary */
2251 process_one_work(worker, work);
2252 if (unlikely(!list_empty(&worker->scheduled)))
2253 process_scheduled_works(worker);
2255 move_linked_works(work, &worker->scheduled, NULL);
2256 process_scheduled_works(worker);
2258 } while (keep_working(pool));
2260 worker_set_flags(worker, WORKER_PREP, false);
2262 if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
2266 * pool->lock is held and there's no work to process and no need to
2267 * manage, sleep. Workers are woken up only while holding
2268 * pool->lock or from local cpu, so setting the current state
2269 * before releasing pool->lock is enough to prevent losing any
2272 worker_enter_idle(worker);
2273 __set_current_state(TASK_INTERRUPTIBLE);
2274 spin_unlock_irq(&pool->lock);
2280 * rescuer_thread - the rescuer thread function
2283 * Workqueue rescuer thread function. There's one rescuer for each
2284 * workqueue which has WQ_MEM_RECLAIM set.
2286 * Regular work processing on a pool may block trying to create a new
2287 * worker which uses GFP_KERNEL allocation which has slight chance of
2288 * developing into deadlock if some works currently on the same queue
2289 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2290 * the problem rescuer solves.
2292 * When such condition is possible, the pool summons rescuers of all
2293 * workqueues which have works queued on the pool and let them process
2294 * those works so that forward progress can be guaranteed.
2296 * This should happen rarely.
2298 static int rescuer_thread(void *__rescuer)
2300 struct worker *rescuer = __rescuer;
2301 struct workqueue_struct *wq = rescuer->rescue_wq;
2302 struct list_head *scheduled = &rescuer->scheduled;
2304 set_user_nice(current, RESCUER_NICE_LEVEL);
2307 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2308 * doesn't participate in concurrency management.
2310 rescuer->task->flags |= PF_WQ_WORKER;
2312 set_current_state(TASK_INTERRUPTIBLE);
2314 if (kthread_should_stop()) {
2315 __set_current_state(TASK_RUNNING);
2316 rescuer->task->flags &= ~PF_WQ_WORKER;
2320 /* see whether any pwq is asking for help */
2321 spin_lock_irq(&wq_mayday_lock);
2323 while (!list_empty(&wq->maydays)) {
2324 struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2325 struct pool_workqueue, mayday_node);
2326 struct worker_pool *pool = pwq->pool;
2327 struct work_struct *work, *n;
2329 __set_current_state(TASK_RUNNING);
2330 list_del_init(&pwq->mayday_node);
2332 spin_unlock_irq(&wq_mayday_lock);
2334 /* migrate to the target cpu if possible */
2335 worker_maybe_bind_and_lock(pool);
2336 rescuer->pool = pool;
2339 * Slurp in all works issued via this workqueue and
2342 WARN_ON_ONCE(!list_empty(&rescuer->scheduled));
2343 list_for_each_entry_safe(work, n, &pool->worklist, entry)
2344 if (get_work_pwq(work) == pwq)
2345 move_linked_works(work, scheduled, &n);
2347 process_scheduled_works(rescuer);
2350 * Leave this pool. If keep_working() is %true, notify a
2351 * regular worker; otherwise, we end up with 0 concurrency
2352 * and stalling the execution.
2354 if (keep_working(pool))
2355 wake_up_worker(pool);
2357 rescuer->pool = NULL;
2358 spin_unlock(&pool->lock);
2359 spin_lock(&wq_mayday_lock);
2362 spin_unlock_irq(&wq_mayday_lock);
2364 /* rescuers should never participate in concurrency management */
2365 WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2371 struct work_struct work;
2372 struct completion done;
2375 static void wq_barrier_func(struct work_struct *work)
2377 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2378 complete(&barr->done);
2382 * insert_wq_barrier - insert a barrier work
2383 * @pwq: pwq to insert barrier into
2384 * @barr: wq_barrier to insert
2385 * @target: target work to attach @barr to
2386 * @worker: worker currently executing @target, NULL if @target is not executing
2388 * @barr is linked to @target such that @barr is completed only after
2389 * @target finishes execution. Please note that the ordering
2390 * guarantee is observed only with respect to @target and on the local
2393 * Currently, a queued barrier can't be canceled. This is because
2394 * try_to_grab_pending() can't determine whether the work to be
2395 * grabbed is at the head of the queue and thus can't clear LINKED
2396 * flag of the previous work while there must be a valid next work
2397 * after a work with LINKED flag set.
2399 * Note that when @worker is non-NULL, @target may be modified
2400 * underneath us, so we can't reliably determine pwq from @target.
2403 * spin_lock_irq(pool->lock).
2405 static void insert_wq_barrier(struct pool_workqueue *pwq,
2406 struct wq_barrier *barr,
2407 struct work_struct *target, struct worker *worker)
2409 struct list_head *head;
2410 unsigned int linked = 0;
2413 * debugobject calls are safe here even with pool->lock locked
2414 * as we know for sure that this will not trigger any of the
2415 * checks and call back into the fixup functions where we
2418 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2419 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2420 init_completion(&barr->done);
2423 * If @target is currently being executed, schedule the
2424 * barrier to the worker; otherwise, put it after @target.
2427 head = worker->scheduled.next;
2429 unsigned long *bits = work_data_bits(target);
2431 head = target->entry.next;
2432 /* there can already be other linked works, inherit and set */
2433 linked = *bits & WORK_STRUCT_LINKED;
2434 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2437 debug_work_activate(&barr->work);
2438 insert_work(pwq, &barr->work, head,
2439 work_color_to_flags(WORK_NO_COLOR) | linked);
2443 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
2444 * @wq: workqueue being flushed
2445 * @flush_color: new flush color, < 0 for no-op
2446 * @work_color: new work color, < 0 for no-op
2448 * Prepare pwqs for workqueue flushing.
2450 * If @flush_color is non-negative, flush_color on all pwqs should be
2451 * -1. If no pwq has in-flight commands at the specified color, all
2452 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
2453 * has in flight commands, its pwq->flush_color is set to
2454 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
2455 * wakeup logic is armed and %true is returned.
2457 * The caller should have initialized @wq->first_flusher prior to
2458 * calling this function with non-negative @flush_color. If
2459 * @flush_color is negative, no flush color update is done and %false
2462 * If @work_color is non-negative, all pwqs should have the same
2463 * work_color which is previous to @work_color and all will be
2464 * advanced to @work_color.
2467 * mutex_lock(wq->mutex).
2470 * %true if @flush_color >= 0 and there's something to flush. %false
2473 static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
2474 int flush_color, int work_color)
2477 struct pool_workqueue *pwq;
2479 if (flush_color >= 0) {
2480 WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2481 atomic_set(&wq->nr_pwqs_to_flush, 1);
2484 for_each_pwq(pwq, wq) {
2485 struct worker_pool *pool = pwq->pool;
2487 spin_lock_irq(&pool->lock);
2489 if (flush_color >= 0) {
2490 WARN_ON_ONCE(pwq->flush_color != -1);
2492 if (pwq->nr_in_flight[flush_color]) {
2493 pwq->flush_color = flush_color;
2494 atomic_inc(&wq->nr_pwqs_to_flush);
2499 if (work_color >= 0) {
2500 WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2501 pwq->work_color = work_color;
2504 spin_unlock_irq(&pool->lock);
2507 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
2508 complete(&wq->first_flusher->done);
2514 * flush_workqueue - ensure that any scheduled work has run to completion.
2515 * @wq: workqueue to flush
2517 * This function sleeps until all work items which were queued on entry
2518 * have finished execution, but it is not livelocked by new incoming ones.
2520 void flush_workqueue(struct workqueue_struct *wq)
2522 struct wq_flusher this_flusher = {
2523 .list = LIST_HEAD_INIT(this_flusher.list),
2525 .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
2529 lock_map_acquire(&wq->lockdep_map);
2530 lock_map_release(&wq->lockdep_map);
2532 mutex_lock(&wq->mutex);
2535 * Start-to-wait phase
2537 next_color = work_next_color(wq->work_color);
2539 if (next_color != wq->flush_color) {
2541 * Color space is not full. The current work_color
2542 * becomes our flush_color and work_color is advanced
2545 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
2546 this_flusher.flush_color = wq->work_color;
2547 wq->work_color = next_color;
2549 if (!wq->first_flusher) {
2550 /* no flush in progress, become the first flusher */
2551 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2553 wq->first_flusher = &this_flusher;
2555 if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
2557 /* nothing to flush, done */
2558 wq->flush_color = next_color;
2559 wq->first_flusher = NULL;
2564 WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
2565 list_add_tail(&this_flusher.list, &wq->flusher_queue);
2566 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2570 * Oops, color space is full, wait on overflow queue.
2571 * The next flush completion will assign us
2572 * flush_color and transfer to flusher_queue.
2574 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2577 mutex_unlock(&wq->mutex);
2579 wait_for_completion(&this_flusher.done);
2582 * Wake-up-and-cascade phase
2584 * First flushers are responsible for cascading flushes and
2585 * handling overflow. Non-first flushers can simply return.
2587 if (wq->first_flusher != &this_flusher)
2590 mutex_lock(&wq->mutex);
2592 /* we might have raced, check again with mutex held */
2593 if (wq->first_flusher != &this_flusher)
2596 wq->first_flusher = NULL;
2598 WARN_ON_ONCE(!list_empty(&this_flusher.list));
2599 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2602 struct wq_flusher *next, *tmp;
2604 /* complete all the flushers sharing the current flush color */
2605 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2606 if (next->flush_color != wq->flush_color)
2608 list_del_init(&next->list);
2609 complete(&next->done);
2612 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
2613 wq->flush_color != work_next_color(wq->work_color));
2615 /* this flush_color is finished, advance by one */
2616 wq->flush_color = work_next_color(wq->flush_color);
2618 /* one color has been freed, handle overflow queue */
2619 if (!list_empty(&wq->flusher_overflow)) {
2621 * Assign the same color to all overflowed
2622 * flushers, advance work_color and append to
2623 * flusher_queue. This is the start-to-wait
2624 * phase for these overflowed flushers.
2626 list_for_each_entry(tmp, &wq->flusher_overflow, list)
2627 tmp->flush_color = wq->work_color;
2629 wq->work_color = work_next_color(wq->work_color);
2631 list_splice_tail_init(&wq->flusher_overflow,
2632 &wq->flusher_queue);
2633 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2636 if (list_empty(&wq->flusher_queue)) {
2637 WARN_ON_ONCE(wq->flush_color != wq->work_color);
2642 * Need to flush more colors. Make the next flusher
2643 * the new first flusher and arm pwqs.
2645 WARN_ON_ONCE(wq->flush_color == wq->work_color);
2646 WARN_ON_ONCE(wq->flush_color != next->flush_color);
2648 list_del_init(&next->list);
2649 wq->first_flusher = next;
2651 if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
2655 * Meh... this color is already done, clear first
2656 * flusher and repeat cascading.
2658 wq->first_flusher = NULL;
2662 mutex_unlock(&wq->mutex);
2664 EXPORT_SYMBOL_GPL(flush_workqueue);
2667 * drain_workqueue - drain a workqueue
2668 * @wq: workqueue to drain
2670 * Wait until the workqueue becomes empty. While draining is in progress,
2671 * only chain queueing is allowed. IOW, only currently pending or running
2672 * work items on @wq can queue further work items on it. @wq is flushed
2673 * repeatedly until it becomes empty. The number of flushing is detemined
2674 * by the depth of chaining and should be relatively short. Whine if it
2677 void drain_workqueue(struct workqueue_struct *wq)
2679 unsigned int flush_cnt = 0;
2680 struct pool_workqueue *pwq;
2683 * __queue_work() needs to test whether there are drainers, is much
2684 * hotter than drain_workqueue() and already looks at @wq->flags.
2685 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
2687 mutex_lock(&wq->mutex);
2688 if (!wq->nr_drainers++)
2689 wq->flags |= __WQ_DRAINING;
2690 mutex_unlock(&wq->mutex);
2692 flush_workqueue(wq);
2694 mutex_lock(&wq->mutex);
2696 for_each_pwq(pwq, wq) {
2699 spin_lock_irq(&pwq->pool->lock);
2700 drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
2701 spin_unlock_irq(&pwq->pool->lock);
2706 if (++flush_cnt == 10 ||
2707 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2708 pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
2709 wq->name, flush_cnt);
2711 mutex_unlock(&wq->mutex);
2715 if (!--wq->nr_drainers)
2716 wq->flags &= ~__WQ_DRAINING;
2717 mutex_unlock(&wq->mutex);
2719 EXPORT_SYMBOL_GPL(drain_workqueue);
2721 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2723 struct worker *worker = NULL;
2724 struct worker_pool *pool;
2725 struct pool_workqueue *pwq;
2729 local_irq_disable();
2730 pool = get_work_pool(work);
2736 spin_lock(&pool->lock);
2737 /* see the comment in try_to_grab_pending() with the same code */
2738 pwq = get_work_pwq(work);
2740 if (unlikely(pwq->pool != pool))
2743 worker = find_worker_executing_work(pool, work);
2746 pwq = worker->current_pwq;
2749 insert_wq_barrier(pwq, barr, work, worker);
2750 spin_unlock_irq(&pool->lock);
2753 * If @max_active is 1 or rescuer is in use, flushing another work
2754 * item on the same workqueue may lead to deadlock. Make sure the
2755 * flusher is not running on the same workqueue by verifying write
2758 if (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)
2759 lock_map_acquire(&pwq->wq->lockdep_map);
2761 lock_map_acquire_read(&pwq->wq->lockdep_map);
2762 lock_map_release(&pwq->wq->lockdep_map);
2766 spin_unlock_irq(&pool->lock);
2771 * flush_work - wait for a work to finish executing the last queueing instance
2772 * @work: the work to flush
2774 * Wait until @work has finished execution. @work is guaranteed to be idle
2775 * on return if it hasn't been requeued since flush started.
2778 * %true if flush_work() waited for the work to finish execution,
2779 * %false if it was already idle.
2781 bool flush_work(struct work_struct *work)
2783 struct wq_barrier barr;
2785 lock_map_acquire(&work->lockdep_map);
2786 lock_map_release(&work->lockdep_map);
2788 if (start_flush_work(work, &barr)) {
2789 wait_for_completion(&barr.done);
2790 destroy_work_on_stack(&barr.work);
2796 EXPORT_SYMBOL_GPL(flush_work);
2798 static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2800 unsigned long flags;
2804 ret = try_to_grab_pending(work, is_dwork, &flags);
2806 * If someone else is canceling, wait for the same event it
2807 * would be waiting for before retrying.
2809 if (unlikely(ret == -ENOENT))
2811 } while (unlikely(ret < 0));
2813 /* tell other tasks trying to grab @work to back off */
2814 mark_work_canceling(work);
2815 local_irq_restore(flags);
2818 clear_work_data(work);
2823 * cancel_work_sync - cancel a work and wait for it to finish
2824 * @work: the work to cancel
2826 * Cancel @work and wait for its execution to finish. This function
2827 * can be used even if the work re-queues itself or migrates to
2828 * another workqueue. On return from this function, @work is
2829 * guaranteed to be not pending or executing on any CPU.
2831 * cancel_work_sync(&delayed_work->work) must not be used for
2832 * delayed_work's. Use cancel_delayed_work_sync() instead.
2834 * The caller must ensure that the workqueue on which @work was last
2835 * queued can't be destroyed before this function returns.
2838 * %true if @work was pending, %false otherwise.
2840 bool cancel_work_sync(struct work_struct *work)
2842 return __cancel_work_timer(work, false);
2844 EXPORT_SYMBOL_GPL(cancel_work_sync);
2847 * flush_delayed_work - wait for a dwork to finish executing the last queueing
2848 * @dwork: the delayed work to flush
2850 * Delayed timer is cancelled and the pending work is queued for
2851 * immediate execution. Like flush_work(), this function only
2852 * considers the last queueing instance of @dwork.
2855 * %true if flush_work() waited for the work to finish execution,
2856 * %false if it was already idle.
2858 bool flush_delayed_work(struct delayed_work *dwork)
2860 local_irq_disable();
2861 if (del_timer_sync(&dwork->timer))
2862 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
2864 return flush_work(&dwork->work);
2866 EXPORT_SYMBOL(flush_delayed_work);
2869 * cancel_delayed_work - cancel a delayed work
2870 * @dwork: delayed_work to cancel
2872 * Kill off a pending delayed_work. Returns %true if @dwork was pending
2873 * and canceled; %false if wasn't pending. Note that the work callback
2874 * function may still be running on return, unless it returns %true and the
2875 * work doesn't re-arm itself. Explicitly flush or use
2876 * cancel_delayed_work_sync() to wait on it.
2878 * This function is safe to call from any context including IRQ handler.
2880 bool cancel_delayed_work(struct delayed_work *dwork)
2882 unsigned long flags;
2886 ret = try_to_grab_pending(&dwork->work, true, &flags);
2887 } while (unlikely(ret == -EAGAIN));
2889 if (unlikely(ret < 0))
2892 set_work_pool_and_clear_pending(&dwork->work,
2893 get_work_pool_id(&dwork->work));
2894 local_irq_restore(flags);
2897 EXPORT_SYMBOL(cancel_delayed_work);
2900 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2901 * @dwork: the delayed work cancel
2903 * This is cancel_work_sync() for delayed works.
2906 * %true if @dwork was pending, %false otherwise.
2908 bool cancel_delayed_work_sync(struct delayed_work *dwork)
2910 return __cancel_work_timer(&dwork->work, true);
2912 EXPORT_SYMBOL(cancel_delayed_work_sync);
2915 * schedule_on_each_cpu - execute a function synchronously on each online CPU
2916 * @func: the function to call
2918 * schedule_on_each_cpu() executes @func on each online CPU using the
2919 * system workqueue and blocks until all CPUs have completed.
2920 * schedule_on_each_cpu() is very slow.
2923 * 0 on success, -errno on failure.
2925 int schedule_on_each_cpu(work_func_t func)
2928 struct work_struct __percpu *works;
2930 works = alloc_percpu(struct work_struct);
2936 for_each_online_cpu(cpu) {
2937 struct work_struct *work = per_cpu_ptr(works, cpu);
2939 INIT_WORK(work, func);
2940 schedule_work_on(cpu, work);
2943 for_each_online_cpu(cpu)
2944 flush_work(per_cpu_ptr(works, cpu));
2952 * flush_scheduled_work - ensure that any scheduled work has run to completion.
2954 * Forces execution of the kernel-global workqueue and blocks until its
2957 * Think twice before calling this function! It's very easy to get into
2958 * trouble if you don't take great care. Either of the following situations
2959 * will lead to deadlock:
2961 * One of the work items currently on the workqueue needs to acquire
2962 * a lock held by your code or its caller.
2964 * Your code is running in the context of a work routine.
2966 * They will be detected by lockdep when they occur, but the first might not
2967 * occur very often. It depends on what work items are on the workqueue and
2968 * what locks they need, which you have no control over.
2970 * In most situations flushing the entire workqueue is overkill; you merely
2971 * need to know that a particular work item isn't queued and isn't running.
2972 * In such cases you should use cancel_delayed_work_sync() or
2973 * cancel_work_sync() instead.
2975 void flush_scheduled_work(void)
2977 flush_workqueue(system_wq);
2979 EXPORT_SYMBOL(flush_scheduled_work);
2982 * execute_in_process_context - reliably execute the routine with user context
2983 * @fn: the function to execute
2984 * @ew: guaranteed storage for the execute work structure (must
2985 * be available when the work executes)
2987 * Executes the function immediately if process context is available,
2988 * otherwise schedules the function for delayed execution.
2990 * Returns: 0 - function was executed
2991 * 1 - function was scheduled for execution
2993 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
2995 if (!in_interrupt()) {
3000 INIT_WORK(&ew->work, fn);
3001 schedule_work(&ew->work);
3005 EXPORT_SYMBOL_GPL(execute_in_process_context);
3009 * Workqueues with WQ_SYSFS flag set is visible to userland via
3010 * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
3011 * following attributes.
3013 * per_cpu RO bool : whether the workqueue is per-cpu or unbound
3014 * max_active RW int : maximum number of in-flight work items
3016 * Unbound workqueues have the following extra attributes.
3018 * id RO int : the associated pool ID
3019 * nice RW int : nice value of the workers
3020 * cpumask RW mask : bitmask of allowed CPUs for the workers
3023 struct workqueue_struct *wq;
3027 static struct workqueue_struct *dev_to_wq(struct device *dev)
3029 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
3034 static ssize_t wq_per_cpu_show(struct device *dev,
3035 struct device_attribute *attr, char *buf)
3037 struct workqueue_struct *wq = dev_to_wq(dev);
3039 return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
3042 static ssize_t wq_max_active_show(struct device *dev,
3043 struct device_attribute *attr, char *buf)
3045 struct workqueue_struct *wq = dev_to_wq(dev);
3047 return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
3050 static ssize_t wq_max_active_store(struct device *dev,
3051 struct device_attribute *attr,
3052 const char *buf, size_t count)
3054 struct workqueue_struct *wq = dev_to_wq(dev);
3057 if (sscanf(buf, "%d", &val) != 1 || val <= 0)
3060 workqueue_set_max_active(wq, val);
3064 static struct device_attribute wq_sysfs_attrs[] = {
3065 __ATTR(per_cpu, 0444, wq_per_cpu_show, NULL),
3066 __ATTR(max_active, 0644, wq_max_active_show, wq_max_active_store),
3070 static ssize_t wq_pool_id_show(struct device *dev,
3071 struct device_attribute *attr, char *buf)
3073 struct workqueue_struct *wq = dev_to_wq(dev);
3074 struct worker_pool *pool;
3077 rcu_read_lock_sched();
3078 pool = first_pwq(wq)->pool;
3079 written = scnprintf(buf, PAGE_SIZE, "%d\n", pool->id);
3080 rcu_read_unlock_sched();
3085 static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
3088 struct workqueue_struct *wq = dev_to_wq(dev);
3091 rcu_read_lock_sched();
3092 written = scnprintf(buf, PAGE_SIZE, "%d\n",
3093 first_pwq(wq)->pool->attrs->nice);
3094 rcu_read_unlock_sched();
3099 /* prepare workqueue_attrs for sysfs store operations */
3100 static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
3102 struct workqueue_attrs *attrs;
3104 attrs = alloc_workqueue_attrs(GFP_KERNEL);
3108 rcu_read_lock_sched();
3109 copy_workqueue_attrs(attrs, first_pwq(wq)->pool->attrs);
3110 rcu_read_unlock_sched();
3114 static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
3115 const char *buf, size_t count)
3117 struct workqueue_struct *wq = dev_to_wq(dev);
3118 struct workqueue_attrs *attrs;
3121 attrs = wq_sysfs_prep_attrs(wq);
3125 if (sscanf(buf, "%d", &attrs->nice) == 1 &&
3126 attrs->nice >= -20 && attrs->nice <= 19)
3127 ret = apply_workqueue_attrs(wq, attrs);
3131 free_workqueue_attrs(attrs);
3132 return ret ?: count;
3135 static ssize_t wq_cpumask_show(struct device *dev,
3136 struct device_attribute *attr, char *buf)
3138 struct workqueue_struct *wq = dev_to_wq(dev);
3141 rcu_read_lock_sched();
3142 written = cpumask_scnprintf(buf, PAGE_SIZE,
3143 first_pwq(wq)->pool->attrs->cpumask);
3144 rcu_read_unlock_sched();
3146 written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
3150 static ssize_t wq_cpumask_store(struct device *dev,
3151 struct device_attribute *attr,
3152 const char *buf, size_t count)
3154 struct workqueue_struct *wq = dev_to_wq(dev);
3155 struct workqueue_attrs *attrs;
3158 attrs = wq_sysfs_prep_attrs(wq);
3162 ret = cpumask_parse(buf, attrs->cpumask);
3164 ret = apply_workqueue_attrs(wq, attrs);
3166 free_workqueue_attrs(attrs);
3167 return ret ?: count;
3170 static struct device_attribute wq_sysfs_unbound_attrs[] = {
3171 __ATTR(pool_id, 0444, wq_pool_id_show, NULL),
3172 __ATTR(nice, 0644, wq_nice_show, wq_nice_store),
3173 __ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
3177 static struct bus_type wq_subsys = {
3178 .name = "workqueue",
3179 .dev_attrs = wq_sysfs_attrs,
3182 static int __init wq_sysfs_init(void)
3184 return subsys_virtual_register(&wq_subsys, NULL);
3186 core_initcall(wq_sysfs_init);
3188 static void wq_device_release(struct device *dev)
3190 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
3196 * workqueue_sysfs_register - make a workqueue visible in sysfs
3197 * @wq: the workqueue to register
3199 * Expose @wq in sysfs under /sys/bus/workqueue/devices.
3200 * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
3201 * which is the preferred method.
3203 * Workqueue user should use this function directly iff it wants to apply
3204 * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
3205 * apply_workqueue_attrs() may race against userland updating the
3208 * Returns 0 on success, -errno on failure.
3210 int workqueue_sysfs_register(struct workqueue_struct *wq)
3212 struct wq_device *wq_dev;
3216 * Adjusting max_active or creating new pwqs by applyting
3217 * attributes breaks ordering guarantee. Disallow exposing ordered
3220 if (WARN_ON(wq->flags & __WQ_ORDERED))
3223 wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
3228 wq_dev->dev.bus = &wq_subsys;
3229 wq_dev->dev.init_name = wq->name;
3230 wq_dev->dev.release = wq_device_release;
3233 * unbound_attrs are created separately. Suppress uevent until
3234 * everything is ready.
3236 dev_set_uevent_suppress(&wq_dev->dev, true);
3238 ret = device_register(&wq_dev->dev);
3245 if (wq->flags & WQ_UNBOUND) {
3246 struct device_attribute *attr;
3248 for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
3249 ret = device_create_file(&wq_dev->dev, attr);
3251 device_unregister(&wq_dev->dev);
3258 kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
3263 * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
3264 * @wq: the workqueue to unregister
3266 * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
3268 static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
3270 struct wq_device *wq_dev = wq->wq_dev;
3276 device_unregister(&wq_dev->dev);
3278 #else /* CONFIG_SYSFS */
3279 static void workqueue_sysfs_unregister(struct workqueue_struct *wq) { }
3280 #endif /* CONFIG_SYSFS */
3283 * free_workqueue_attrs - free a workqueue_attrs
3284 * @attrs: workqueue_attrs to free
3286 * Undo alloc_workqueue_attrs().
3288 void free_workqueue_attrs(struct workqueue_attrs *attrs)
3291 free_cpumask_var(attrs->cpumask);
3297 * alloc_workqueue_attrs - allocate a workqueue_attrs
3298 * @gfp_mask: allocation mask to use
3300 * Allocate a new workqueue_attrs, initialize with default settings and
3301 * return it. Returns NULL on failure.
3303 struct workqueue_attrs *alloc_workqueue_attrs(gfp_t gfp_mask)
3305 struct workqueue_attrs *attrs;
3307 attrs = kzalloc(sizeof(*attrs), gfp_mask);
3310 if (!alloc_cpumask_var(&attrs->cpumask, gfp_mask))
3313 cpumask_copy(attrs->cpumask, cpu_possible_mask);
3316 free_workqueue_attrs(attrs);
3320 static void copy_workqueue_attrs(struct workqueue_attrs *to,
3321 const struct workqueue_attrs *from)
3323 to->nice = from->nice;
3324 cpumask_copy(to->cpumask, from->cpumask);
3327 /* hash value of the content of @attr */
3328 static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
3332 hash = jhash_1word(attrs->nice, hash);
3333 hash = jhash(cpumask_bits(attrs->cpumask),
3334 BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
3338 /* content equality test */
3339 static bool wqattrs_equal(const struct workqueue_attrs *a,
3340 const struct workqueue_attrs *b)
3342 if (a->nice != b->nice)
3344 if (!cpumask_equal(a->cpumask, b->cpumask))
3350 * init_worker_pool - initialize a newly zalloc'd worker_pool
3351 * @pool: worker_pool to initialize
3353 * Initiailize a newly zalloc'd @pool. It also allocates @pool->attrs.
3354 * Returns 0 on success, -errno on failure. Even on failure, all fields
3355 * inside @pool proper are initialized and put_unbound_pool() can be called
3356 * on @pool safely to release it.
3358 static int init_worker_pool(struct worker_pool *pool)
3360 spin_lock_init(&pool->lock);
3363 pool->node = NUMA_NO_NODE;
3364 pool->flags |= POOL_DISASSOCIATED;
3365 INIT_LIST_HEAD(&pool->worklist);
3366 INIT_LIST_HEAD(&pool->idle_list);
3367 hash_init(pool->busy_hash);
3369 init_timer_deferrable(&pool->idle_timer);
3370 pool->idle_timer.function = idle_worker_timeout;
3371 pool->idle_timer.data = (unsigned long)pool;
3373 setup_timer(&pool->mayday_timer, pool_mayday_timeout,
3374 (unsigned long)pool);
3376 mutex_init(&pool->manager_arb);
3377 mutex_init(&pool->manager_mutex);
3378 idr_init(&pool->worker_idr);
3380 INIT_HLIST_NODE(&pool->hash_node);
3383 /* shouldn't fail above this point */
3384 pool->attrs = alloc_workqueue_attrs(GFP_KERNEL);
3390 static void rcu_free_pool(struct rcu_head *rcu)
3392 struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
3394 idr_destroy(&pool->worker_idr);
3395 free_workqueue_attrs(pool->attrs);
3400 * put_unbound_pool - put a worker_pool
3401 * @pool: worker_pool to put
3403 * Put @pool. If its refcnt reaches zero, it gets destroyed in sched-RCU
3404 * safe manner. get_unbound_pool() calls this function on its failure path
3405 * and this function should be able to release pools which went through,
3406 * successfully or not, init_worker_pool().
3408 * Should be called with wq_pool_mutex held.
3410 static void put_unbound_pool(struct worker_pool *pool)
3412 struct worker *worker;
3414 lockdep_assert_held(&wq_pool_mutex);
3420 if (WARN_ON(!(pool->flags & POOL_DISASSOCIATED)) ||
3421 WARN_ON(!list_empty(&pool->worklist)))
3424 /* release id and unhash */
3426 idr_remove(&worker_pool_idr, pool->id);
3427 hash_del(&pool->hash_node);
3430 * Become the manager and destroy all workers. Grabbing
3431 * manager_arb prevents @pool's workers from blocking on
3434 mutex_lock(&pool->manager_arb);
3435 mutex_lock(&pool->manager_mutex);
3436 spin_lock_irq(&pool->lock);
3438 while ((worker = first_worker(pool)))
3439 destroy_worker(worker);
3440 WARN_ON(pool->nr_workers || pool->nr_idle);
3442 spin_unlock_irq(&pool->lock);
3443 mutex_unlock(&pool->manager_mutex);
3444 mutex_unlock(&pool->manager_arb);
3446 /* shut down the timers */
3447 del_timer_sync(&pool->idle_timer);
3448 del_timer_sync(&pool->mayday_timer);
3450 /* sched-RCU protected to allow dereferences from get_work_pool() */
3451 call_rcu_sched(&pool->rcu, rcu_free_pool);
3455 * get_unbound_pool - get a worker_pool with the specified attributes
3456 * @attrs: the attributes of the worker_pool to get
3458 * Obtain a worker_pool which has the same attributes as @attrs, bump the
3459 * reference count and return it. If there already is a matching
3460 * worker_pool, it will be used; otherwise, this function attempts to
3461 * create a new one. On failure, returns NULL.
3463 * Should be called with wq_pool_mutex held.
3465 static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
3467 u32 hash = wqattrs_hash(attrs);
3468 struct worker_pool *pool;
3471 lockdep_assert_held(&wq_pool_mutex);
3473 /* do we already have a matching pool? */
3474 hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
3475 if (wqattrs_equal(pool->attrs, attrs)) {
3481 /* nope, create a new one */
3482 pool = kzalloc(sizeof(*pool), GFP_KERNEL);
3483 if (!pool || init_worker_pool(pool) < 0)
3486 if (workqueue_freezing)
3487 pool->flags |= POOL_FREEZING;
3489 lockdep_set_subclass(&pool->lock, 1); /* see put_pwq() */
3490 copy_workqueue_attrs(pool->attrs, attrs);
3492 /* if cpumask is contained inside a NUMA node, we belong to that node */
3493 if (wq_numa_enabled) {
3494 for_each_node(node) {
3495 if (cpumask_subset(pool->attrs->cpumask,
3496 wq_numa_possible_cpumask[node])) {
3503 if (worker_pool_assign_id(pool) < 0)
3506 /* create and start the initial worker */
3507 if (create_and_start_worker(pool) < 0)
3511 hash_add(unbound_pool_hash, &pool->hash_node, hash);
3516 put_unbound_pool(pool);
3520 static void rcu_free_pwq(struct rcu_head *rcu)
3522 kmem_cache_free(pwq_cache,
3523 container_of(rcu, struct pool_workqueue, rcu));
3527 * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
3528 * and needs to be destroyed.
3530 static void pwq_unbound_release_workfn(struct work_struct *work)
3532 struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
3533 unbound_release_work);
3534 struct workqueue_struct *wq = pwq->wq;
3535 struct worker_pool *pool = pwq->pool;
3538 if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
3542 * Unlink @pwq. Synchronization against wq->mutex isn't strictly
3543 * necessary on release but do it anyway. It's easier to verify
3544 * and consistent with the linking path.
3546 mutex_lock(&wq->mutex);
3547 list_del_rcu(&pwq->pwqs_node);
3548 is_last = list_empty(&wq->pwqs);
3549 mutex_unlock(&wq->mutex);
3551 mutex_lock(&wq_pool_mutex);
3552 put_unbound_pool(pool);
3553 mutex_unlock(&wq_pool_mutex);
3555 call_rcu_sched(&pwq->rcu, rcu_free_pwq);
3558 * If we're the last pwq going away, @wq is already dead and no one
3559 * is gonna access it anymore. Free it.
3566 * pwq_adjust_max_active - update a pwq's max_active to the current setting
3567 * @pwq: target pool_workqueue
3569 * If @pwq isn't freezing, set @pwq->max_active to the associated
3570 * workqueue's saved_max_active and activate delayed work items
3571 * accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
3573 static void pwq_adjust_max_active(struct pool_workqueue *pwq)
3575 struct workqueue_struct *wq = pwq->wq;
3576 bool freezable = wq->flags & WQ_FREEZABLE;
3578 /* for @wq->saved_max_active */
3579 lockdep_assert_held(&wq->mutex);
3581 /* fast exit for non-freezable wqs */
3582 if (!freezable && pwq->max_active == wq->saved_max_active)
3585 spin_lock_irq(&pwq->pool->lock);
3587 if (!freezable || !(pwq->pool->flags & POOL_FREEZING)) {
3588 pwq->max_active = wq->saved_max_active;
3590 while (!list_empty(&pwq->delayed_works) &&
3591 pwq->nr_active < pwq->max_active)
3592 pwq_activate_first_delayed(pwq);
3595 * Need to kick a worker after thawed or an unbound wq's
3596 * max_active is bumped. It's a slow path. Do it always.
3598 wake_up_worker(pwq->pool);
3600 pwq->max_active = 0;
3603 spin_unlock_irq(&pwq->pool->lock);
3606 static void init_and_link_pwq(struct pool_workqueue *pwq,
3607 struct workqueue_struct *wq,
3608 struct worker_pool *pool,
3609 struct pool_workqueue **p_last_pwq)
3611 BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3615 pwq->flush_color = -1;
3617 INIT_LIST_HEAD(&pwq->delayed_works);
3618 INIT_LIST_HEAD(&pwq->mayday_node);
3619 INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
3621 mutex_lock(&wq->mutex);
3624 * Set the matching work_color. This is synchronized with
3625 * wq->mutex to avoid confusing flush_workqueue().
3628 *p_last_pwq = first_pwq(wq);
3629 pwq->work_color = wq->work_color;
3631 /* sync max_active to the current setting */
3632 pwq_adjust_max_active(pwq);
3635 list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
3637 mutex_unlock(&wq->mutex);
3641 * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
3642 * @wq: the target workqueue
3643 * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
3645 * Apply @attrs to an unbound workqueue @wq. If @attrs doesn't match the
3646 * current attributes, a new pwq is created and made the first pwq which
3647 * will serve all new work items. Older pwqs are released as in-flight
3648 * work items finish. Note that a work item which repeatedly requeues
3649 * itself back-to-back will stay on its current pwq.
3651 * Performs GFP_KERNEL allocations. Returns 0 on success and -errno on
3654 int apply_workqueue_attrs(struct workqueue_struct *wq,
3655 const struct workqueue_attrs *attrs)
3657 struct workqueue_attrs *new_attrs;
3658 struct pool_workqueue *pwq = NULL, *last_pwq;
3659 struct worker_pool *pool;
3662 /* only unbound workqueues can change attributes */
3663 if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
3666 /* creating multiple pwqs breaks ordering guarantee */
3667 if (WARN_ON((wq->flags & __WQ_ORDERED) && !list_empty(&wq->pwqs)))
3670 /* make a copy of @attrs and sanitize it */
3671 new_attrs = alloc_workqueue_attrs(GFP_KERNEL);
3675 copy_workqueue_attrs(new_attrs, attrs);
3676 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
3678 mutex_lock(&wq_pool_mutex);
3680 pwq = kmem_cache_zalloc(pwq_cache, GFP_KERNEL);
3682 mutex_unlock(&wq_pool_mutex);
3686 pool = get_unbound_pool(new_attrs);
3688 mutex_unlock(&wq_pool_mutex);
3692 mutex_unlock(&wq_pool_mutex);
3694 init_and_link_pwq(pwq, wq, pool, &last_pwq);
3696 spin_lock_irq(&last_pwq->pool->lock);
3698 spin_unlock_irq(&last_pwq->pool->lock);
3704 free_workqueue_attrs(new_attrs);
3708 kmem_cache_free(pwq_cache, pwq);
3713 static int alloc_and_link_pwqs(struct workqueue_struct *wq)
3715 bool highpri = wq->flags & WQ_HIGHPRI;
3718 if (!(wq->flags & WQ_UNBOUND)) {
3719 wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
3723 for_each_possible_cpu(cpu) {
3724 struct pool_workqueue *pwq =
3725 per_cpu_ptr(wq->cpu_pwqs, cpu);
3726 struct worker_pool *cpu_pools =
3727 per_cpu(cpu_worker_pools, cpu);
3729 init_and_link_pwq(pwq, wq, &cpu_pools[highpri], NULL);
3733 return apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
3737 static int wq_clamp_max_active(int max_active, unsigned int flags,
3740 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3742 if (max_active < 1 || max_active > lim)
3743 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3744 max_active, name, 1, lim);
3746 return clamp_val(max_active, 1, lim);
3749 struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
3752 struct lock_class_key *key,
3753 const char *lock_name, ...)
3755 va_list args, args1;
3756 struct workqueue_struct *wq;
3757 struct pool_workqueue *pwq;
3760 /* determine namelen, allocate wq and format name */
3761 va_start(args, lock_name);
3762 va_copy(args1, args);
3763 namelen = vsnprintf(NULL, 0, fmt, args) + 1;
3765 wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
3769 vsnprintf(wq->name, namelen, fmt, args1);
3773 max_active = max_active ?: WQ_DFL_ACTIVE;
3774 max_active = wq_clamp_max_active(max_active, flags, wq->name);
3778 wq->saved_max_active = max_active;
3779 mutex_init(&wq->mutex);
3780 atomic_set(&wq->nr_pwqs_to_flush, 0);
3781 INIT_LIST_HEAD(&wq->pwqs);
3782 INIT_LIST_HEAD(&wq->flusher_queue);
3783 INIT_LIST_HEAD(&wq->flusher_overflow);
3784 INIT_LIST_HEAD(&wq->maydays);
3786 lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3787 INIT_LIST_HEAD(&wq->list);
3789 if (alloc_and_link_pwqs(wq) < 0)
3793 * Workqueues which may be used during memory reclaim should
3794 * have a rescuer to guarantee forward progress.
3796 if (flags & WQ_MEM_RECLAIM) {
3797 struct worker *rescuer;
3799 rescuer = alloc_worker();
3803 rescuer->rescue_wq = wq;
3804 rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
3806 if (IS_ERR(rescuer->task)) {
3811 wq->rescuer = rescuer;
3812 rescuer->task->flags |= PF_NO_SETAFFINITY;
3813 wake_up_process(rescuer->task);
3816 if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
3820 * wq_pool_mutex protects global freeze state and workqueues list.
3821 * Grab it, adjust max_active and add the new @wq to workqueues
3824 mutex_lock(&wq_pool_mutex);
3826 mutex_lock(&wq->mutex);
3827 for_each_pwq(pwq, wq)
3828 pwq_adjust_max_active(pwq);
3829 mutex_unlock(&wq->mutex);
3831 list_add(&wq->list, &workqueues);
3833 mutex_unlock(&wq_pool_mutex);
3841 destroy_workqueue(wq);
3844 EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
3847 * destroy_workqueue - safely terminate a workqueue
3848 * @wq: target workqueue
3850 * Safely destroy a workqueue. All work currently pending will be done first.
3852 void destroy_workqueue(struct workqueue_struct *wq)
3854 struct pool_workqueue *pwq;
3856 /* drain it before proceeding with destruction */
3857 drain_workqueue(wq);
3860 mutex_lock(&wq->mutex);
3861 for_each_pwq(pwq, wq) {
3864 for (i = 0; i < WORK_NR_COLORS; i++) {
3865 if (WARN_ON(pwq->nr_in_flight[i])) {
3866 mutex_unlock(&wq->mutex);
3871 if (WARN_ON(pwq->refcnt > 1) ||
3872 WARN_ON(pwq->nr_active) ||
3873 WARN_ON(!list_empty(&pwq->delayed_works))) {
3874 mutex_unlock(&wq->mutex);
3878 mutex_unlock(&wq->mutex);
3881 * wq list is used to freeze wq, remove from list after
3882 * flushing is complete in case freeze races us.
3884 mutex_lock(&wq_pool_mutex);
3885 list_del_init(&wq->list);
3886 mutex_unlock(&wq_pool_mutex);
3888 workqueue_sysfs_unregister(wq);
3891 kthread_stop(wq->rescuer->task);
3896 if (!(wq->flags & WQ_UNBOUND)) {
3898 * The base ref is never dropped on per-cpu pwqs. Directly
3899 * free the pwqs and wq.
3901 free_percpu(wq->cpu_pwqs);
3905 * We're the sole accessor of @wq at this point. Directly
3906 * access the first pwq and put the base ref. As both pwqs
3907 * and pools are sched-RCU protected, the lock operations
3908 * are safe. @wq will be freed when the last pwq is
3911 pwq = list_first_entry(&wq->pwqs, struct pool_workqueue,
3913 spin_lock_irq(&pwq->pool->lock);
3915 spin_unlock_irq(&pwq->pool->lock);
3918 EXPORT_SYMBOL_GPL(destroy_workqueue);
3921 * workqueue_set_max_active - adjust max_active of a workqueue
3922 * @wq: target workqueue
3923 * @max_active: new max_active value.
3925 * Set max_active of @wq to @max_active.
3928 * Don't call from IRQ context.
3930 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
3932 struct pool_workqueue *pwq;
3934 /* disallow meddling with max_active for ordered workqueues */
3935 if (WARN_ON(wq->flags & __WQ_ORDERED))
3938 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
3940 mutex_lock(&wq->mutex);
3942 wq->saved_max_active = max_active;
3944 for_each_pwq(pwq, wq)
3945 pwq_adjust_max_active(pwq);
3947 mutex_unlock(&wq->mutex);
3949 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
3952 * current_is_workqueue_rescuer - is %current workqueue rescuer?
3954 * Determine whether %current is a workqueue rescuer. Can be used from
3955 * work functions to determine whether it's being run off the rescuer task.
3957 bool current_is_workqueue_rescuer(void)
3959 struct worker *worker = current_wq_worker();
3961 return worker && worker->rescue_wq;
3965 * workqueue_congested - test whether a workqueue is congested
3966 * @cpu: CPU in question
3967 * @wq: target workqueue
3969 * Test whether @wq's cpu workqueue for @cpu is congested. There is
3970 * no synchronization around this function and the test result is
3971 * unreliable and only useful as advisory hints or for debugging.
3974 * %true if congested, %false otherwise.
3976 bool workqueue_congested(int cpu, struct workqueue_struct *wq)
3978 struct pool_workqueue *pwq;
3981 rcu_read_lock_sched();
3983 if (!(wq->flags & WQ_UNBOUND))
3984 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
3986 pwq = first_pwq(wq);
3988 ret = !list_empty(&pwq->delayed_works);
3989 rcu_read_unlock_sched();
3993 EXPORT_SYMBOL_GPL(workqueue_congested);
3996 * work_busy - test whether a work is currently pending or running
3997 * @work: the work to be tested
3999 * Test whether @work is currently pending or running. There is no
4000 * synchronization around this function and the test result is
4001 * unreliable and only useful as advisory hints or for debugging.
4004 * OR'd bitmask of WORK_BUSY_* bits.
4006 unsigned int work_busy(struct work_struct *work)
4008 struct worker_pool *pool;
4009 unsigned long flags;
4010 unsigned int ret = 0;
4012 if (work_pending(work))
4013 ret |= WORK_BUSY_PENDING;
4015 local_irq_save(flags);
4016 pool = get_work_pool(work);
4018 spin_lock(&pool->lock);
4019 if (find_worker_executing_work(pool, work))
4020 ret |= WORK_BUSY_RUNNING;
4021 spin_unlock(&pool->lock);
4023 local_irq_restore(flags);
4027 EXPORT_SYMBOL_GPL(work_busy);
4032 * There are two challenges in supporting CPU hotplug. Firstly, there
4033 * are a lot of assumptions on strong associations among work, pwq and
4034 * pool which make migrating pending and scheduled works very
4035 * difficult to implement without impacting hot paths. Secondly,
4036 * worker pools serve mix of short, long and very long running works making
4037 * blocked draining impractical.
4039 * This is solved by allowing the pools to be disassociated from the CPU
4040 * running as an unbound one and allowing it to be reattached later if the
4041 * cpu comes back online.
4044 static void wq_unbind_fn(struct work_struct *work)
4046 int cpu = smp_processor_id();
4047 struct worker_pool *pool;
4048 struct worker *worker;
4051 for_each_cpu_worker_pool(pool, cpu) {
4052 WARN_ON_ONCE(cpu != smp_processor_id());
4054 mutex_lock(&pool->manager_mutex);
4055 spin_lock_irq(&pool->lock);
4058 * We've blocked all manager operations. Make all workers
4059 * unbound and set DISASSOCIATED. Before this, all workers
4060 * except for the ones which are still executing works from
4061 * before the last CPU down must be on the cpu. After
4062 * this, they may become diasporas.
4064 for_each_pool_worker(worker, wi, pool)
4065 worker->flags |= WORKER_UNBOUND;
4067 pool->flags |= POOL_DISASSOCIATED;
4069 spin_unlock_irq(&pool->lock);
4070 mutex_unlock(&pool->manager_mutex);
4074 * Call schedule() so that we cross rq->lock and thus can guarantee
4075 * sched callbacks see the %WORKER_UNBOUND flag. This is necessary
4076 * as scheduler callbacks may be invoked from other cpus.
4081 * Sched callbacks are disabled now. Zap nr_running. After this,
4082 * nr_running stays zero and need_more_worker() and keep_working()
4083 * are always true as long as the worklist is not empty. Pools on
4084 * @cpu now behave as unbound (in terms of concurrency management)
4085 * pools which are served by workers tied to the CPU.
4087 * On return from this function, the current worker would trigger
4088 * unbound chain execution of pending work items if other workers
4091 for_each_cpu_worker_pool(pool, cpu)
4092 atomic_set(&pool->nr_running, 0);
4096 * rebind_workers - rebind all workers of a pool to the associated CPU
4097 * @pool: pool of interest
4099 * @pool->cpu is coming online. Rebind all workers to the CPU.
4101 static void rebind_workers(struct worker_pool *pool)
4103 struct worker *worker;
4106 lockdep_assert_held(&pool->manager_mutex);
4109 * Restore CPU affinity of all workers. As all idle workers should
4110 * be on the run-queue of the associated CPU before any local
4111 * wake-ups for concurrency management happen, restore CPU affinty
4112 * of all workers first and then clear UNBOUND. As we're called
4113 * from CPU_ONLINE, the following shouldn't fail.
4115 for_each_pool_worker(worker, wi, pool)
4116 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4117 pool->attrs->cpumask) < 0);
4119 spin_lock_irq(&pool->lock);
4121 for_each_pool_worker(worker, wi, pool) {
4122 unsigned int worker_flags = worker->flags;
4125 * A bound idle worker should actually be on the runqueue
4126 * of the associated CPU for local wake-ups targeting it to
4127 * work. Kick all idle workers so that they migrate to the
4128 * associated CPU. Doing this in the same loop as
4129 * replacing UNBOUND with REBOUND is safe as no worker will
4130 * be bound before @pool->lock is released.
4132 if (worker_flags & WORKER_IDLE)
4133 wake_up_process(worker->task);
4136 * We want to clear UNBOUND but can't directly call
4137 * worker_clr_flags() or adjust nr_running. Atomically
4138 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
4139 * @worker will clear REBOUND using worker_clr_flags() when
4140 * it initiates the next execution cycle thus restoring
4141 * concurrency management. Note that when or whether
4142 * @worker clears REBOUND doesn't affect correctness.
4144 * ACCESS_ONCE() is necessary because @worker->flags may be
4145 * tested without holding any lock in
4146 * wq_worker_waking_up(). Without it, NOT_RUNNING test may
4147 * fail incorrectly leading to premature concurrency
4148 * management operations.
4150 WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
4151 worker_flags |= WORKER_REBOUND;
4152 worker_flags &= ~WORKER_UNBOUND;
4153 ACCESS_ONCE(worker->flags) = worker_flags;
4156 spin_unlock_irq(&pool->lock);
4160 * restore_unbound_workers_cpumask - restore cpumask of unbound workers
4161 * @pool: unbound pool of interest
4162 * @cpu: the CPU which is coming up
4164 * An unbound pool may end up with a cpumask which doesn't have any online
4165 * CPUs. When a worker of such pool get scheduled, the scheduler resets
4166 * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
4167 * online CPU before, cpus_allowed of all its workers should be restored.
4169 static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
4171 static cpumask_t cpumask;
4172 struct worker *worker;
4175 lockdep_assert_held(&pool->manager_mutex);
4177 /* is @cpu allowed for @pool? */
4178 if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
4181 /* is @cpu the only online CPU? */
4182 cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
4183 if (cpumask_weight(&cpumask) != 1)
4186 /* as we're called from CPU_ONLINE, the following shouldn't fail */
4187 for_each_pool_worker(worker, wi, pool)
4188 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4189 pool->attrs->cpumask) < 0);
4193 * Workqueues should be brought up before normal priority CPU notifiers.
4194 * This will be registered high priority CPU notifier.
4196 static int __cpuinit workqueue_cpu_up_callback(struct notifier_block *nfb,
4197 unsigned long action,
4200 int cpu = (unsigned long)hcpu;
4201 struct worker_pool *pool;
4204 switch (action & ~CPU_TASKS_FROZEN) {
4205 case CPU_UP_PREPARE:
4206 for_each_cpu_worker_pool(pool, cpu) {
4207 if (pool->nr_workers)
4209 if (create_and_start_worker(pool) < 0)
4214 case CPU_DOWN_FAILED:
4216 mutex_lock(&wq_pool_mutex);
4218 for_each_pool(pool, pi) {
4219 mutex_lock(&pool->manager_mutex);
4221 if (pool->cpu == cpu) {
4222 spin_lock_irq(&pool->lock);
4223 pool->flags &= ~POOL_DISASSOCIATED;
4224 spin_unlock_irq(&pool->lock);
4226 rebind_workers(pool);
4227 } else if (pool->cpu < 0) {
4228 restore_unbound_workers_cpumask(pool, cpu);
4231 mutex_unlock(&pool->manager_mutex);
4234 mutex_unlock(&wq_pool_mutex);
4241 * Workqueues should be brought down after normal priority CPU notifiers.
4242 * This will be registered as low priority CPU notifier.
4244 static int __cpuinit workqueue_cpu_down_callback(struct notifier_block *nfb,
4245 unsigned long action,
4248 int cpu = (unsigned long)hcpu;
4249 struct work_struct unbind_work;
4251 switch (action & ~CPU_TASKS_FROZEN) {
4252 case CPU_DOWN_PREPARE:
4253 /* unbinding should happen on the local CPU */
4254 INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
4255 queue_work_on(cpu, system_highpri_wq, &unbind_work);
4256 flush_work(&unbind_work);
4264 struct work_for_cpu {
4265 struct work_struct work;
4271 static void work_for_cpu_fn(struct work_struct *work)
4273 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
4275 wfc->ret = wfc->fn(wfc->arg);
4279 * work_on_cpu - run a function in user context on a particular cpu
4280 * @cpu: the cpu to run on
4281 * @fn: the function to run
4282 * @arg: the function arg
4284 * This will return the value @fn returns.
4285 * It is up to the caller to ensure that the cpu doesn't go offline.
4286 * The caller must not hold any locks which would prevent @fn from completing.
4288 long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
4290 struct work_for_cpu wfc = { .fn = fn, .arg = arg };
4292 INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
4293 schedule_work_on(cpu, &wfc.work);
4294 flush_work(&wfc.work);
4297 EXPORT_SYMBOL_GPL(work_on_cpu);
4298 #endif /* CONFIG_SMP */
4300 #ifdef CONFIG_FREEZER
4303 * freeze_workqueues_begin - begin freezing workqueues
4305 * Start freezing workqueues. After this function returns, all freezable
4306 * workqueues will queue new works to their delayed_works list instead of
4310 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4312 void freeze_workqueues_begin(void)
4314 struct worker_pool *pool;
4315 struct workqueue_struct *wq;
4316 struct pool_workqueue *pwq;
4319 mutex_lock(&wq_pool_mutex);
4321 WARN_ON_ONCE(workqueue_freezing);
4322 workqueue_freezing = true;
4325 for_each_pool(pool, pi) {
4326 spin_lock_irq(&pool->lock);
4327 WARN_ON_ONCE(pool->flags & POOL_FREEZING);
4328 pool->flags |= POOL_FREEZING;
4329 spin_unlock_irq(&pool->lock);
4332 list_for_each_entry(wq, &workqueues, list) {
4333 mutex_lock(&wq->mutex);
4334 for_each_pwq(pwq, wq)
4335 pwq_adjust_max_active(pwq);
4336 mutex_unlock(&wq->mutex);
4339 mutex_unlock(&wq_pool_mutex);
4343 * freeze_workqueues_busy - are freezable workqueues still busy?
4345 * Check whether freezing is complete. This function must be called
4346 * between freeze_workqueues_begin() and thaw_workqueues().
4349 * Grabs and releases wq_pool_mutex.
4352 * %true if some freezable workqueues are still busy. %false if freezing
4355 bool freeze_workqueues_busy(void)
4358 struct workqueue_struct *wq;
4359 struct pool_workqueue *pwq;
4361 mutex_lock(&wq_pool_mutex);
4363 WARN_ON_ONCE(!workqueue_freezing);
4365 list_for_each_entry(wq, &workqueues, list) {
4366 if (!(wq->flags & WQ_FREEZABLE))
4369 * nr_active is monotonically decreasing. It's safe
4370 * to peek without lock.
4372 rcu_read_lock_sched();
4373 for_each_pwq(pwq, wq) {
4374 WARN_ON_ONCE(pwq->nr_active < 0);
4375 if (pwq->nr_active) {
4377 rcu_read_unlock_sched();
4381 rcu_read_unlock_sched();
4384 mutex_unlock(&wq_pool_mutex);
4389 * thaw_workqueues - thaw workqueues
4391 * Thaw workqueues. Normal queueing is restored and all collected
4392 * frozen works are transferred to their respective pool worklists.
4395 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4397 void thaw_workqueues(void)
4399 struct workqueue_struct *wq;
4400 struct pool_workqueue *pwq;
4401 struct worker_pool *pool;
4404 mutex_lock(&wq_pool_mutex);
4406 if (!workqueue_freezing)
4409 /* clear FREEZING */
4410 for_each_pool(pool, pi) {
4411 spin_lock_irq(&pool->lock);
4412 WARN_ON_ONCE(!(pool->flags & POOL_FREEZING));
4413 pool->flags &= ~POOL_FREEZING;
4414 spin_unlock_irq(&pool->lock);
4417 /* restore max_active and repopulate worklist */
4418 list_for_each_entry(wq, &workqueues, list) {
4419 mutex_lock(&wq->mutex);
4420 for_each_pwq(pwq, wq)
4421 pwq_adjust_max_active(pwq);
4422 mutex_unlock(&wq->mutex);
4425 workqueue_freezing = false;
4427 mutex_unlock(&wq_pool_mutex);
4429 #endif /* CONFIG_FREEZER */
4431 static void __init wq_numa_init(void)
4436 /* determine NUMA pwq table len - highest node id + 1 */
4438 wq_numa_tbl_len = max(wq_numa_tbl_len, node + 1);
4440 if (num_possible_nodes() <= 1)
4444 * We want masks of possible CPUs of each node which isn't readily
4445 * available. Build one from cpu_to_node() which should have been
4446 * fully initialized by now.
4448 tbl = kzalloc(wq_numa_tbl_len * sizeof(tbl[0]), GFP_KERNEL);
4452 BUG_ON(!alloc_cpumask_var_node(&tbl[node], GFP_KERNEL, node));
4454 for_each_possible_cpu(cpu) {
4455 node = cpu_to_node(cpu);
4456 if (WARN_ON(node == NUMA_NO_NODE)) {
4457 pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
4458 /* happens iff arch is bonkers, let's just proceed */
4461 cpumask_set_cpu(cpu, tbl[node]);
4464 wq_numa_possible_cpumask = tbl;
4465 wq_numa_enabled = true;
4468 static int __init init_workqueues(void)
4470 int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
4473 /* make sure we have enough bits for OFFQ pool ID */
4474 BUILD_BUG_ON((1LU << (BITS_PER_LONG - WORK_OFFQ_POOL_SHIFT)) <
4475 WORK_CPU_END * NR_STD_WORKER_POOLS);
4477 WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
4479 pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
4481 cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
4482 hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
4486 /* initialize CPU pools */
4487 for_each_possible_cpu(cpu) {
4488 struct worker_pool *pool;
4491 for_each_cpu_worker_pool(pool, cpu) {
4492 BUG_ON(init_worker_pool(pool));
4494 cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
4495 pool->attrs->nice = std_nice[i++];
4496 pool->node = cpu_to_node(cpu);
4499 mutex_lock(&wq_pool_mutex);
4500 BUG_ON(worker_pool_assign_id(pool));
4501 mutex_unlock(&wq_pool_mutex);
4505 /* create the initial worker */
4506 for_each_online_cpu(cpu) {
4507 struct worker_pool *pool;
4509 for_each_cpu_worker_pool(pool, cpu) {
4510 pool->flags &= ~POOL_DISASSOCIATED;
4511 BUG_ON(create_and_start_worker(pool) < 0);
4515 /* create default unbound wq attrs */
4516 for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
4517 struct workqueue_attrs *attrs;
4519 BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
4520 attrs->nice = std_nice[i];
4521 unbound_std_wq_attrs[i] = attrs;
4524 system_wq = alloc_workqueue("events", 0, 0);
4525 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
4526 system_long_wq = alloc_workqueue("events_long", 0, 0);
4527 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
4528 WQ_UNBOUND_MAX_ACTIVE);
4529 system_freezable_wq = alloc_workqueue("events_freezable",
4531 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
4532 !system_unbound_wq || !system_freezable_wq);
4535 early_initcall(init_workqueues);