workqueue: implement NUMA affinity for unbound workqueues
[linux-2.6/btrfs-unstable.git] / kernel / workqueue.c
blob57cd77de4a4fdd8ead040bffab82f2e5614ecbb8
1 /*
2 * kernel/workqueue.c - generic async execution with shared worker pool
4 * Copyright (C) 2002 Ingo Molnar
6 * Derived from the taskqueue/keventd code by:
7 * David Woodhouse <dwmw2@infradead.org>
8 * Andrew Morton
9 * Kai Petzke <wpp@marie.physik.tu-berlin.de>
10 * Theodore Ts'o <tytso@mit.edu>
12 * Made to use alloc_percpu by Christoph Lameter.
14 * Copyright (C) 2010 SUSE Linux Products GmbH
15 * Copyright (C) 2010 Tejun Heo <tj@kernel.org>
17 * This is the generic async execution mechanism. Work items as are
18 * executed in process context. The worker pool is shared and
19 * automatically managed. There is one worker pool for each CPU and
20 * one extra for works which are better served by workers which are
21 * not bound to any specific CPU.
23 * Please read Documentation/workqueue.txt for details.
26 #include <linux/export.h>
27 #include <linux/kernel.h>
28 #include <linux/sched.h>
29 #include <linux/init.h>
30 #include <linux/signal.h>
31 #include <linux/completion.h>
32 #include <linux/workqueue.h>
33 #include <linux/slab.h>
34 #include <linux/cpu.h>
35 #include <linux/notifier.h>
36 #include <linux/kthread.h>
37 #include <linux/hardirq.h>
38 #include <linux/mempolicy.h>
39 #include <linux/freezer.h>
40 #include <linux/kallsyms.h>
41 #include <linux/debug_locks.h>
42 #include <linux/lockdep.h>
43 #include <linux/idr.h>
44 #include <linux/jhash.h>
45 #include <linux/hashtable.h>
46 #include <linux/rculist.h>
47 #include <linux/nodemask.h>
48 #include <linux/moduleparam.h>
50 #include "workqueue_internal.h"
52 enum {
54 * worker_pool flags
56 * A bound pool is either associated or disassociated with its CPU.
57 * While associated (!DISASSOCIATED), all workers are bound to the
58 * CPU and none has %WORKER_UNBOUND set and concurrency management
59 * is in effect.
61 * While DISASSOCIATED, the cpu may be offline and all workers have
62 * %WORKER_UNBOUND set and concurrency management disabled, and may
63 * be executing on any CPU. The pool behaves as an unbound one.
65 * Note that DISASSOCIATED should be flipped only while holding
66 * manager_mutex to avoid changing binding state while
67 * create_worker() is in progress.
69 POOL_MANAGE_WORKERS = 1 << 0, /* need to manage workers */
70 POOL_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
71 POOL_FREEZING = 1 << 3, /* freeze in progress */
73 /* worker flags */
74 WORKER_STARTED = 1 << 0, /* started */
75 WORKER_DIE = 1 << 1, /* die die die */
76 WORKER_IDLE = 1 << 2, /* is idle */
77 WORKER_PREP = 1 << 3, /* preparing to run works */
78 WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
79 WORKER_UNBOUND = 1 << 7, /* worker is unbound */
80 WORKER_REBOUND = 1 << 8, /* worker was rebound */
82 WORKER_NOT_RUNNING = WORKER_PREP | WORKER_CPU_INTENSIVE |
83 WORKER_UNBOUND | WORKER_REBOUND,
85 NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */
87 UNBOUND_POOL_HASH_ORDER = 6, /* hashed by pool->attrs */
88 BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
90 MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
91 IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
93 MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
94 /* call for help after 10ms
95 (min two ticks) */
96 MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
97 CREATE_COOLDOWN = HZ, /* time to breath after fail */
100 * Rescue workers are used only on emergencies and shared by
101 * all cpus. Give -20.
103 RESCUER_NICE_LEVEL = -20,
104 HIGHPRI_NICE_LEVEL = -20,
106 WQ_NAME_LEN = 24,
110 * Structure fields follow one of the following exclusion rules.
112 * I: Modifiable by initialization/destruction paths and read-only for
113 * everyone else.
115 * P: Preemption protected. Disabling preemption is enough and should
116 * only be modified and accessed from the local cpu.
118 * L: pool->lock protected. Access with pool->lock held.
120 * X: During normal operation, modification requires pool->lock and should
121 * be done only from local cpu. Either disabling preemption on local
122 * cpu or grabbing pool->lock is enough for read access. If
123 * POOL_DISASSOCIATED is set, it's identical to L.
125 * MG: pool->manager_mutex and pool->lock protected. Writes require both
126 * locks. Reads can happen under either lock.
128 * PL: wq_pool_mutex protected.
130 * PR: wq_pool_mutex protected for writes. Sched-RCU protected for reads.
132 * WQ: wq->mutex protected.
134 * WR: wq->mutex protected for writes. Sched-RCU protected for reads.
136 * MD: wq_mayday_lock protected.
139 /* struct worker is defined in workqueue_internal.h */
141 struct worker_pool {
142 spinlock_t lock; /* the pool lock */
143 int cpu; /* I: the associated cpu */
144 int node; /* I: the associated node ID */
145 int id; /* I: pool ID */
146 unsigned int flags; /* X: flags */
148 struct list_head worklist; /* L: list of pending works */
149 int nr_workers; /* L: total number of workers */
151 /* nr_idle includes the ones off idle_list for rebinding */
152 int nr_idle; /* L: currently idle ones */
154 struct list_head idle_list; /* X: list of idle workers */
155 struct timer_list idle_timer; /* L: worker idle timeout */
156 struct timer_list mayday_timer; /* L: SOS timer for workers */
158 /* a workers is either on busy_hash or idle_list, or the manager */
159 DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
160 /* L: hash of busy workers */
162 /* see manage_workers() for details on the two manager mutexes */
163 struct mutex manager_arb; /* manager arbitration */
164 struct mutex manager_mutex; /* manager exclusion */
165 struct idr worker_idr; /* MG: worker IDs and iteration */
167 struct workqueue_attrs *attrs; /* I: worker attributes */
168 struct hlist_node hash_node; /* PL: unbound_pool_hash node */
169 int refcnt; /* PL: refcnt for unbound pools */
172 * The current concurrency level. As it's likely to be accessed
173 * from other CPUs during try_to_wake_up(), put it in a separate
174 * cacheline.
176 atomic_t nr_running ____cacheline_aligned_in_smp;
179 * Destruction of pool is sched-RCU protected to allow dereferences
180 * from get_work_pool().
182 struct rcu_head rcu;
183 } ____cacheline_aligned_in_smp;
186 * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
187 * of work_struct->data are used for flags and the remaining high bits
188 * point to the pwq; thus, pwqs need to be aligned at two's power of the
189 * number of flag bits.
191 struct pool_workqueue {
192 struct worker_pool *pool; /* I: the associated pool */
193 struct workqueue_struct *wq; /* I: the owning workqueue */
194 int work_color; /* L: current color */
195 int flush_color; /* L: flushing color */
196 int refcnt; /* L: reference count */
197 int nr_in_flight[WORK_NR_COLORS];
198 /* L: nr of in_flight works */
199 int nr_active; /* L: nr of active works */
200 int max_active; /* L: max active works */
201 struct list_head delayed_works; /* L: delayed works */
202 struct list_head pwqs_node; /* WR: node on wq->pwqs */
203 struct list_head mayday_node; /* MD: node on wq->maydays */
206 * Release of unbound pwq is punted to system_wq. See put_pwq()
207 * and pwq_unbound_release_workfn() for details. pool_workqueue
208 * itself is also sched-RCU protected so that the first pwq can be
209 * determined without grabbing wq->mutex.
211 struct work_struct unbound_release_work;
212 struct rcu_head rcu;
213 } __aligned(1 << WORK_STRUCT_FLAG_BITS);
216 * Structure used to wait for workqueue flush.
218 struct wq_flusher {
219 struct list_head list; /* WQ: list of flushers */
220 int flush_color; /* WQ: flush color waiting for */
221 struct completion done; /* flush completion */
224 struct wq_device;
227 * The externally visible workqueue. It relays the issued work items to
228 * the appropriate worker_pool through its pool_workqueues.
230 struct workqueue_struct {
231 struct list_head pwqs; /* WR: all pwqs of this wq */
232 struct list_head list; /* PL: list of all workqueues */
234 struct mutex mutex; /* protects this wq */
235 int work_color; /* WQ: current work color */
236 int flush_color; /* WQ: current flush color */
237 atomic_t nr_pwqs_to_flush; /* flush in progress */
238 struct wq_flusher *first_flusher; /* WQ: first flusher */
239 struct list_head flusher_queue; /* WQ: flush waiters */
240 struct list_head flusher_overflow; /* WQ: flush overflow list */
242 struct list_head maydays; /* MD: pwqs requesting rescue */
243 struct worker *rescuer; /* I: rescue worker */
245 int nr_drainers; /* WQ: drain in progress */
246 int saved_max_active; /* WQ: saved pwq max_active */
248 struct workqueue_attrs *unbound_attrs; /* WQ: only for unbound wqs */
249 struct pool_workqueue *dfl_pwq; /* WQ: only for unbound wqs */
251 #ifdef CONFIG_SYSFS
252 struct wq_device *wq_dev; /* I: for sysfs interface */
253 #endif
254 #ifdef CONFIG_LOCKDEP
255 struct lockdep_map lockdep_map;
256 #endif
257 char name[WQ_NAME_LEN]; /* I: workqueue name */
259 /* hot fields used during command issue, aligned to cacheline */
260 unsigned int flags ____cacheline_aligned; /* WQ: WQ_* flags */
261 struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */
262 struct pool_workqueue __rcu *numa_pwq_tbl[]; /* FR: unbound pwqs indexed by node */
265 static struct kmem_cache *pwq_cache;
267 static int wq_numa_tbl_len; /* highest possible NUMA node id + 1 */
268 static cpumask_var_t *wq_numa_possible_cpumask;
269 /* possible CPUs of each node */
271 static bool wq_numa_enabled; /* unbound NUMA affinity enabled */
273 /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
274 static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf;
276 static DEFINE_MUTEX(wq_pool_mutex); /* protects pools and workqueues list */
277 static DEFINE_SPINLOCK(wq_mayday_lock); /* protects wq->maydays list */
279 static LIST_HEAD(workqueues); /* PL: list of all workqueues */
280 static bool workqueue_freezing; /* PL: have wqs started freezing? */
282 /* the per-cpu worker pools */
283 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
284 cpu_worker_pools);
286 static DEFINE_IDR(worker_pool_idr); /* PR: idr of all pools */
288 /* PL: hash of all unbound pools keyed by pool->attrs */
289 static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
291 /* I: attributes used when instantiating standard unbound pools on demand */
292 static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
294 struct workqueue_struct *system_wq __read_mostly;
295 EXPORT_SYMBOL_GPL(system_wq);
296 struct workqueue_struct *system_highpri_wq __read_mostly;
297 EXPORT_SYMBOL_GPL(system_highpri_wq);
298 struct workqueue_struct *system_long_wq __read_mostly;
299 EXPORT_SYMBOL_GPL(system_long_wq);
300 struct workqueue_struct *system_unbound_wq __read_mostly;
301 EXPORT_SYMBOL_GPL(system_unbound_wq);
302 struct workqueue_struct *system_freezable_wq __read_mostly;
303 EXPORT_SYMBOL_GPL(system_freezable_wq);
305 static int worker_thread(void *__worker);
306 static void copy_workqueue_attrs(struct workqueue_attrs *to,
307 const struct workqueue_attrs *from);
309 #define CREATE_TRACE_POINTS
310 #include <trace/events/workqueue.h>
312 #define assert_rcu_or_pool_mutex() \
313 rcu_lockdep_assert(rcu_read_lock_sched_held() || \
314 lockdep_is_held(&wq_pool_mutex), \
315 "sched RCU or wq_pool_mutex should be held")
317 #define assert_rcu_or_wq_mutex(wq) \
318 rcu_lockdep_assert(rcu_read_lock_sched_held() || \
319 lockdep_is_held(&wq->mutex), \
320 "sched RCU or wq->mutex should be held")
322 #ifdef CONFIG_LOCKDEP
323 #define assert_manager_or_pool_lock(pool) \
324 WARN_ONCE(debug_locks && \
325 !lockdep_is_held(&(pool)->manager_mutex) && \
326 !lockdep_is_held(&(pool)->lock), \
327 "pool->manager_mutex or ->lock should be held")
328 #else
329 #define assert_manager_or_pool_lock(pool) do { } while (0)
330 #endif
332 #define for_each_cpu_worker_pool(pool, cpu) \
333 for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
334 (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
335 (pool)++)
338 * for_each_pool - iterate through all worker_pools in the system
339 * @pool: iteration cursor
340 * @pi: integer used for iteration
342 * This must be called either with wq_pool_mutex held or sched RCU read
343 * locked. If the pool needs to be used beyond the locking in effect, the
344 * caller is responsible for guaranteeing that the pool stays online.
346 * The if/else clause exists only for the lockdep assertion and can be
347 * ignored.
349 #define for_each_pool(pool, pi) \
350 idr_for_each_entry(&worker_pool_idr, pool, pi) \
351 if (({ assert_rcu_or_pool_mutex(); false; })) { } \
352 else
355 * for_each_pool_worker - iterate through all workers of a worker_pool
356 * @worker: iteration cursor
357 * @wi: integer used for iteration
358 * @pool: worker_pool to iterate workers of
360 * This must be called with either @pool->manager_mutex or ->lock held.
362 * The if/else clause exists only for the lockdep assertion and can be
363 * ignored.
365 #define for_each_pool_worker(worker, wi, pool) \
366 idr_for_each_entry(&(pool)->worker_idr, (worker), (wi)) \
367 if (({ assert_manager_or_pool_lock((pool)); false; })) { } \
368 else
371 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
372 * @pwq: iteration cursor
373 * @wq: the target workqueue
375 * This must be called either with wq->mutex held or sched RCU read locked.
376 * If the pwq needs to be used beyond the locking in effect, the caller is
377 * responsible for guaranteeing that the pwq stays online.
379 * The if/else clause exists only for the lockdep assertion and can be
380 * ignored.
382 #define for_each_pwq(pwq, wq) \
383 list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node) \
384 if (({ assert_rcu_or_wq_mutex(wq); false; })) { } \
385 else
387 #ifdef CONFIG_DEBUG_OBJECTS_WORK
389 static struct debug_obj_descr work_debug_descr;
391 static void *work_debug_hint(void *addr)
393 return ((struct work_struct *) addr)->func;
397 * fixup_init is called when:
398 * - an active object is initialized
400 static int work_fixup_init(void *addr, enum debug_obj_state state)
402 struct work_struct *work = addr;
404 switch (state) {
405 case ODEBUG_STATE_ACTIVE:
406 cancel_work_sync(work);
407 debug_object_init(work, &work_debug_descr);
408 return 1;
409 default:
410 return 0;
415 * fixup_activate is called when:
416 * - an active object is activated
417 * - an unknown object is activated (might be a statically initialized object)
419 static int work_fixup_activate(void *addr, enum debug_obj_state state)
421 struct work_struct *work = addr;
423 switch (state) {
425 case ODEBUG_STATE_NOTAVAILABLE:
427 * This is not really a fixup. The work struct was
428 * statically initialized. We just make sure that it
429 * is tracked in the object tracker.
431 if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
432 debug_object_init(work, &work_debug_descr);
433 debug_object_activate(work, &work_debug_descr);
434 return 0;
436 WARN_ON_ONCE(1);
437 return 0;
439 case ODEBUG_STATE_ACTIVE:
440 WARN_ON(1);
442 default:
443 return 0;
448 * fixup_free is called when:
449 * - an active object is freed
451 static int work_fixup_free(void *addr, enum debug_obj_state state)
453 struct work_struct *work = addr;
455 switch (state) {
456 case ODEBUG_STATE_ACTIVE:
457 cancel_work_sync(work);
458 debug_object_free(work, &work_debug_descr);
459 return 1;
460 default:
461 return 0;
465 static struct debug_obj_descr work_debug_descr = {
466 .name = "work_struct",
467 .debug_hint = work_debug_hint,
468 .fixup_init = work_fixup_init,
469 .fixup_activate = work_fixup_activate,
470 .fixup_free = work_fixup_free,
473 static inline void debug_work_activate(struct work_struct *work)
475 debug_object_activate(work, &work_debug_descr);
478 static inline void debug_work_deactivate(struct work_struct *work)
480 debug_object_deactivate(work, &work_debug_descr);
483 void __init_work(struct work_struct *work, int onstack)
485 if (onstack)
486 debug_object_init_on_stack(work, &work_debug_descr);
487 else
488 debug_object_init(work, &work_debug_descr);
490 EXPORT_SYMBOL_GPL(__init_work);
492 void destroy_work_on_stack(struct work_struct *work)
494 debug_object_free(work, &work_debug_descr);
496 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
498 #else
499 static inline void debug_work_activate(struct work_struct *work) { }
500 static inline void debug_work_deactivate(struct work_struct *work) { }
501 #endif
503 /* allocate ID and assign it to @pool */
504 static int worker_pool_assign_id(struct worker_pool *pool)
506 int ret;
508 lockdep_assert_held(&wq_pool_mutex);
510 do {
511 if (!idr_pre_get(&worker_pool_idr, GFP_KERNEL))
512 return -ENOMEM;
513 ret = idr_get_new(&worker_pool_idr, pool, &pool->id);
514 } while (ret == -EAGAIN);
516 return ret;
520 * first_pwq - return the first pool_workqueue of the specified workqueue
521 * @wq: the target workqueue
523 * This must be called either with wq->mutex held or sched RCU read locked.
524 * If the pwq needs to be used beyond the locking in effect, the caller is
525 * responsible for guaranteeing that the pwq stays online.
527 static struct pool_workqueue *first_pwq(struct workqueue_struct *wq)
529 assert_rcu_or_wq_mutex(wq);
530 return list_first_or_null_rcu(&wq->pwqs, struct pool_workqueue,
531 pwqs_node);
535 * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
536 * @wq: the target workqueue
537 * @node: the node ID
539 * This must be called either with pwq_lock held or sched RCU read locked.
540 * If the pwq needs to be used beyond the locking in effect, the caller is
541 * responsible for guaranteeing that the pwq stays online.
543 static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
544 int node)
546 assert_rcu_or_wq_mutex(wq);
547 return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
550 static unsigned int work_color_to_flags(int color)
552 return color << WORK_STRUCT_COLOR_SHIFT;
555 static int get_work_color(struct work_struct *work)
557 return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
558 ((1 << WORK_STRUCT_COLOR_BITS) - 1);
561 static int work_next_color(int color)
563 return (color + 1) % WORK_NR_COLORS;
567 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
568 * contain the pointer to the queued pwq. Once execution starts, the flag
569 * is cleared and the high bits contain OFFQ flags and pool ID.
571 * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
572 * and clear_work_data() can be used to set the pwq, pool or clear
573 * work->data. These functions should only be called while the work is
574 * owned - ie. while the PENDING bit is set.
576 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
577 * corresponding to a work. Pool is available once the work has been
578 * queued anywhere after initialization until it is sync canceled. pwq is
579 * available only while the work item is queued.
581 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
582 * canceled. While being canceled, a work item may have its PENDING set
583 * but stay off timer and worklist for arbitrarily long and nobody should
584 * try to steal the PENDING bit.
586 static inline void set_work_data(struct work_struct *work, unsigned long data,
587 unsigned long flags)
589 WARN_ON_ONCE(!work_pending(work));
590 atomic_long_set(&work->data, data | flags | work_static(work));
593 static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
594 unsigned long extra_flags)
596 set_work_data(work, (unsigned long)pwq,
597 WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
600 static void set_work_pool_and_keep_pending(struct work_struct *work,
601 int pool_id)
603 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
604 WORK_STRUCT_PENDING);
607 static void set_work_pool_and_clear_pending(struct work_struct *work,
608 int pool_id)
611 * The following wmb is paired with the implied mb in
612 * test_and_set_bit(PENDING) and ensures all updates to @work made
613 * here are visible to and precede any updates by the next PENDING
614 * owner.
616 smp_wmb();
617 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
620 static void clear_work_data(struct work_struct *work)
622 smp_wmb(); /* see set_work_pool_and_clear_pending() */
623 set_work_data(work, WORK_STRUCT_NO_POOL, 0);
626 static struct pool_workqueue *get_work_pwq(struct work_struct *work)
628 unsigned long data = atomic_long_read(&work->data);
630 if (data & WORK_STRUCT_PWQ)
631 return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
632 else
633 return NULL;
637 * get_work_pool - return the worker_pool a given work was associated with
638 * @work: the work item of interest
640 * Return the worker_pool @work was last associated with. %NULL if none.
642 * Pools are created and destroyed under wq_pool_mutex, and allows read
643 * access under sched-RCU read lock. As such, this function should be
644 * called under wq_pool_mutex or with preemption disabled.
646 * All fields of the returned pool are accessible as long as the above
647 * mentioned locking is in effect. If the returned pool needs to be used
648 * beyond the critical section, the caller is responsible for ensuring the
649 * returned pool is and stays online.
651 static struct worker_pool *get_work_pool(struct work_struct *work)
653 unsigned long data = atomic_long_read(&work->data);
654 int pool_id;
656 assert_rcu_or_pool_mutex();
658 if (data & WORK_STRUCT_PWQ)
659 return ((struct pool_workqueue *)
660 (data & WORK_STRUCT_WQ_DATA_MASK))->pool;
662 pool_id = data >> WORK_OFFQ_POOL_SHIFT;
663 if (pool_id == WORK_OFFQ_POOL_NONE)
664 return NULL;
666 return idr_find(&worker_pool_idr, pool_id);
670 * get_work_pool_id - return the worker pool ID a given work is associated with
671 * @work: the work item of interest
673 * Return the worker_pool ID @work was last associated with.
674 * %WORK_OFFQ_POOL_NONE if none.
676 static int get_work_pool_id(struct work_struct *work)
678 unsigned long data = atomic_long_read(&work->data);
680 if (data & WORK_STRUCT_PWQ)
681 return ((struct pool_workqueue *)
682 (data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
684 return data >> WORK_OFFQ_POOL_SHIFT;
687 static void mark_work_canceling(struct work_struct *work)
689 unsigned long pool_id = get_work_pool_id(work);
691 pool_id <<= WORK_OFFQ_POOL_SHIFT;
692 set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
695 static bool work_is_canceling(struct work_struct *work)
697 unsigned long data = atomic_long_read(&work->data);
699 return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
703 * Policy functions. These define the policies on how the global worker
704 * pools are managed. Unless noted otherwise, these functions assume that
705 * they're being called with pool->lock held.
708 static bool __need_more_worker(struct worker_pool *pool)
710 return !atomic_read(&pool->nr_running);
714 * Need to wake up a worker? Called from anything but currently
715 * running workers.
717 * Note that, because unbound workers never contribute to nr_running, this
718 * function will always return %true for unbound pools as long as the
719 * worklist isn't empty.
721 static bool need_more_worker(struct worker_pool *pool)
723 return !list_empty(&pool->worklist) && __need_more_worker(pool);
726 /* Can I start working? Called from busy but !running workers. */
727 static bool may_start_working(struct worker_pool *pool)
729 return pool->nr_idle;
732 /* Do I need to keep working? Called from currently running workers. */
733 static bool keep_working(struct worker_pool *pool)
735 return !list_empty(&pool->worklist) &&
736 atomic_read(&pool->nr_running) <= 1;
739 /* Do we need a new worker? Called from manager. */
740 static bool need_to_create_worker(struct worker_pool *pool)
742 return need_more_worker(pool) && !may_start_working(pool);
745 /* Do I need to be the manager? */
746 static bool need_to_manage_workers(struct worker_pool *pool)
748 return need_to_create_worker(pool) ||
749 (pool->flags & POOL_MANAGE_WORKERS);
752 /* Do we have too many workers and should some go away? */
753 static bool too_many_workers(struct worker_pool *pool)
755 bool managing = mutex_is_locked(&pool->manager_arb);
756 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
757 int nr_busy = pool->nr_workers - nr_idle;
760 * nr_idle and idle_list may disagree if idle rebinding is in
761 * progress. Never return %true if idle_list is empty.
763 if (list_empty(&pool->idle_list))
764 return false;
766 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
770 * Wake up functions.
773 /* Return the first worker. Safe with preemption disabled */
774 static struct worker *first_worker(struct worker_pool *pool)
776 if (unlikely(list_empty(&pool->idle_list)))
777 return NULL;
779 return list_first_entry(&pool->idle_list, struct worker, entry);
783 * wake_up_worker - wake up an idle worker
784 * @pool: worker pool to wake worker from
786 * Wake up the first idle worker of @pool.
788 * CONTEXT:
789 * spin_lock_irq(pool->lock).
791 static void wake_up_worker(struct worker_pool *pool)
793 struct worker *worker = first_worker(pool);
795 if (likely(worker))
796 wake_up_process(worker->task);
800 * wq_worker_waking_up - a worker is waking up
801 * @task: task waking up
802 * @cpu: CPU @task is waking up to
804 * This function is called during try_to_wake_up() when a worker is
805 * being awoken.
807 * CONTEXT:
808 * spin_lock_irq(rq->lock)
810 void wq_worker_waking_up(struct task_struct *task, int cpu)
812 struct worker *worker = kthread_data(task);
814 if (!(worker->flags & WORKER_NOT_RUNNING)) {
815 WARN_ON_ONCE(worker->pool->cpu != cpu);
816 atomic_inc(&worker->pool->nr_running);
821 * wq_worker_sleeping - a worker is going to sleep
822 * @task: task going to sleep
823 * @cpu: CPU in question, must be the current CPU number
825 * This function is called during schedule() when a busy worker is
826 * going to sleep. Worker on the same cpu can be woken up by
827 * returning pointer to its task.
829 * CONTEXT:
830 * spin_lock_irq(rq->lock)
832 * RETURNS:
833 * Worker task on @cpu to wake up, %NULL if none.
835 struct task_struct *wq_worker_sleeping(struct task_struct *task, int cpu)
837 struct worker *worker = kthread_data(task), *to_wakeup = NULL;
838 struct worker_pool *pool;
841 * Rescuers, which may not have all the fields set up like normal
842 * workers, also reach here, let's not access anything before
843 * checking NOT_RUNNING.
845 if (worker->flags & WORKER_NOT_RUNNING)
846 return NULL;
848 pool = worker->pool;
850 /* this can only happen on the local cpu */
851 if (WARN_ON_ONCE(cpu != raw_smp_processor_id()))
852 return NULL;
855 * The counterpart of the following dec_and_test, implied mb,
856 * worklist not empty test sequence is in insert_work().
857 * Please read comment there.
859 * NOT_RUNNING is clear. This means that we're bound to and
860 * running on the local cpu w/ rq lock held and preemption
861 * disabled, which in turn means that none else could be
862 * manipulating idle_list, so dereferencing idle_list without pool
863 * lock is safe.
865 if (atomic_dec_and_test(&pool->nr_running) &&
866 !list_empty(&pool->worklist))
867 to_wakeup = first_worker(pool);
868 return to_wakeup ? to_wakeup->task : NULL;
872 * worker_set_flags - set worker flags and adjust nr_running accordingly
873 * @worker: self
874 * @flags: flags to set
875 * @wakeup: wakeup an idle worker if necessary
877 * Set @flags in @worker->flags and adjust nr_running accordingly. If
878 * nr_running becomes zero and @wakeup is %true, an idle worker is
879 * woken up.
881 * CONTEXT:
882 * spin_lock_irq(pool->lock)
884 static inline void worker_set_flags(struct worker *worker, unsigned int flags,
885 bool wakeup)
887 struct worker_pool *pool = worker->pool;
889 WARN_ON_ONCE(worker->task != current);
892 * If transitioning into NOT_RUNNING, adjust nr_running and
893 * wake up an idle worker as necessary if requested by
894 * @wakeup.
896 if ((flags & WORKER_NOT_RUNNING) &&
897 !(worker->flags & WORKER_NOT_RUNNING)) {
898 if (wakeup) {
899 if (atomic_dec_and_test(&pool->nr_running) &&
900 !list_empty(&pool->worklist))
901 wake_up_worker(pool);
902 } else
903 atomic_dec(&pool->nr_running);
906 worker->flags |= flags;
910 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
911 * @worker: self
912 * @flags: flags to clear
914 * Clear @flags in @worker->flags and adjust nr_running accordingly.
916 * CONTEXT:
917 * spin_lock_irq(pool->lock)
919 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
921 struct worker_pool *pool = worker->pool;
922 unsigned int oflags = worker->flags;
924 WARN_ON_ONCE(worker->task != current);
926 worker->flags &= ~flags;
929 * If transitioning out of NOT_RUNNING, increment nr_running. Note
930 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
931 * of multiple flags, not a single flag.
933 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
934 if (!(worker->flags & WORKER_NOT_RUNNING))
935 atomic_inc(&pool->nr_running);
939 * find_worker_executing_work - find worker which is executing a work
940 * @pool: pool of interest
941 * @work: work to find worker for
943 * Find a worker which is executing @work on @pool by searching
944 * @pool->busy_hash which is keyed by the address of @work. For a worker
945 * to match, its current execution should match the address of @work and
946 * its work function. This is to avoid unwanted dependency between
947 * unrelated work executions through a work item being recycled while still
948 * being executed.
950 * This is a bit tricky. A work item may be freed once its execution
951 * starts and nothing prevents the freed area from being recycled for
952 * another work item. If the same work item address ends up being reused
953 * before the original execution finishes, workqueue will identify the
954 * recycled work item as currently executing and make it wait until the
955 * current execution finishes, introducing an unwanted dependency.
957 * This function checks the work item address and work function to avoid
958 * false positives. Note that this isn't complete as one may construct a
959 * work function which can introduce dependency onto itself through a
960 * recycled work item. Well, if somebody wants to shoot oneself in the
961 * foot that badly, there's only so much we can do, and if such deadlock
962 * actually occurs, it should be easy to locate the culprit work function.
964 * CONTEXT:
965 * spin_lock_irq(pool->lock).
967 * RETURNS:
968 * Pointer to worker which is executing @work if found, NULL
969 * otherwise.
971 static struct worker *find_worker_executing_work(struct worker_pool *pool,
972 struct work_struct *work)
974 struct worker *worker;
976 hash_for_each_possible(pool->busy_hash, worker, hentry,
977 (unsigned long)work)
978 if (worker->current_work == work &&
979 worker->current_func == work->func)
980 return worker;
982 return NULL;
986 * move_linked_works - move linked works to a list
987 * @work: start of series of works to be scheduled
988 * @head: target list to append @work to
989 * @nextp: out paramter for nested worklist walking
991 * Schedule linked works starting from @work to @head. Work series to
992 * be scheduled starts at @work and includes any consecutive work with
993 * WORK_STRUCT_LINKED set in its predecessor.
995 * If @nextp is not NULL, it's updated to point to the next work of
996 * the last scheduled work. This allows move_linked_works() to be
997 * nested inside outer list_for_each_entry_safe().
999 * CONTEXT:
1000 * spin_lock_irq(pool->lock).
1002 static void move_linked_works(struct work_struct *work, struct list_head *head,
1003 struct work_struct **nextp)
1005 struct work_struct *n;
1008 * Linked worklist will always end before the end of the list,
1009 * use NULL for list head.
1011 list_for_each_entry_safe_from(work, n, NULL, entry) {
1012 list_move_tail(&work->entry, head);
1013 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1014 break;
1018 * If we're already inside safe list traversal and have moved
1019 * multiple works to the scheduled queue, the next position
1020 * needs to be updated.
1022 if (nextp)
1023 *nextp = n;
1027 * get_pwq - get an extra reference on the specified pool_workqueue
1028 * @pwq: pool_workqueue to get
1030 * Obtain an extra reference on @pwq. The caller should guarantee that
1031 * @pwq has positive refcnt and be holding the matching pool->lock.
1033 static void get_pwq(struct pool_workqueue *pwq)
1035 lockdep_assert_held(&pwq->pool->lock);
1036 WARN_ON_ONCE(pwq->refcnt <= 0);
1037 pwq->refcnt++;
1041 * put_pwq - put a pool_workqueue reference
1042 * @pwq: pool_workqueue to put
1044 * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
1045 * destruction. The caller should be holding the matching pool->lock.
1047 static void put_pwq(struct pool_workqueue *pwq)
1049 lockdep_assert_held(&pwq->pool->lock);
1050 if (likely(--pwq->refcnt))
1051 return;
1052 if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
1053 return;
1055 * @pwq can't be released under pool->lock, bounce to
1056 * pwq_unbound_release_workfn(). This never recurses on the same
1057 * pool->lock as this path is taken only for unbound workqueues and
1058 * the release work item is scheduled on a per-cpu workqueue. To
1059 * avoid lockdep warning, unbound pool->locks are given lockdep
1060 * subclass of 1 in get_unbound_pool().
1062 schedule_work(&pwq->unbound_release_work);
1066 * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1067 * @pwq: pool_workqueue to put (can be %NULL)
1069 * put_pwq() with locking. This function also allows %NULL @pwq.
1071 static void put_pwq_unlocked(struct pool_workqueue *pwq)
1073 if (pwq) {
1075 * As both pwqs and pools are sched-RCU protected, the
1076 * following lock operations are safe.
1078 spin_lock_irq(&pwq->pool->lock);
1079 put_pwq(pwq);
1080 spin_unlock_irq(&pwq->pool->lock);
1084 static void pwq_activate_delayed_work(struct work_struct *work)
1086 struct pool_workqueue *pwq = get_work_pwq(work);
1088 trace_workqueue_activate_work(work);
1089 move_linked_works(work, &pwq->pool->worklist, NULL);
1090 __clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
1091 pwq->nr_active++;
1094 static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
1096 struct work_struct *work = list_first_entry(&pwq->delayed_works,
1097 struct work_struct, entry);
1099 pwq_activate_delayed_work(work);
1103 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1104 * @pwq: pwq of interest
1105 * @color: color of work which left the queue
1107 * A work either has completed or is removed from pending queue,
1108 * decrement nr_in_flight of its pwq and handle workqueue flushing.
1110 * CONTEXT:
1111 * spin_lock_irq(pool->lock).
1113 static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
1115 /* uncolored work items don't participate in flushing or nr_active */
1116 if (color == WORK_NO_COLOR)
1117 goto out_put;
1119 pwq->nr_in_flight[color]--;
1121 pwq->nr_active--;
1122 if (!list_empty(&pwq->delayed_works)) {
1123 /* one down, submit a delayed one */
1124 if (pwq->nr_active < pwq->max_active)
1125 pwq_activate_first_delayed(pwq);
1128 /* is flush in progress and are we at the flushing tip? */
1129 if (likely(pwq->flush_color != color))
1130 goto out_put;
1132 /* are there still in-flight works? */
1133 if (pwq->nr_in_flight[color])
1134 goto out_put;
1136 /* this pwq is done, clear flush_color */
1137 pwq->flush_color = -1;
1140 * If this was the last pwq, wake up the first flusher. It
1141 * will handle the rest.
1143 if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1144 complete(&pwq->wq->first_flusher->done);
1145 out_put:
1146 put_pwq(pwq);
1150 * try_to_grab_pending - steal work item from worklist and disable irq
1151 * @work: work item to steal
1152 * @is_dwork: @work is a delayed_work
1153 * @flags: place to store irq state
1155 * Try to grab PENDING bit of @work. This function can handle @work in any
1156 * stable state - idle, on timer or on worklist. Return values are
1158 * 1 if @work was pending and we successfully stole PENDING
1159 * 0 if @work was idle and we claimed PENDING
1160 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1161 * -ENOENT if someone else is canceling @work, this state may persist
1162 * for arbitrarily long
1164 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1165 * interrupted while holding PENDING and @work off queue, irq must be
1166 * disabled on entry. This, combined with delayed_work->timer being
1167 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1169 * On successful return, >= 0, irq is disabled and the caller is
1170 * responsible for releasing it using local_irq_restore(*@flags).
1172 * This function is safe to call from any context including IRQ handler.
1174 static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1175 unsigned long *flags)
1177 struct worker_pool *pool;
1178 struct pool_workqueue *pwq;
1180 local_irq_save(*flags);
1182 /* try to steal the timer if it exists */
1183 if (is_dwork) {
1184 struct delayed_work *dwork = to_delayed_work(work);
1187 * dwork->timer is irqsafe. If del_timer() fails, it's
1188 * guaranteed that the timer is not queued anywhere and not
1189 * running on the local CPU.
1191 if (likely(del_timer(&dwork->timer)))
1192 return 1;
1195 /* try to claim PENDING the normal way */
1196 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1197 return 0;
1200 * The queueing is in progress, or it is already queued. Try to
1201 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1203 pool = get_work_pool(work);
1204 if (!pool)
1205 goto fail;
1207 spin_lock(&pool->lock);
1209 * work->data is guaranteed to point to pwq only while the work
1210 * item is queued on pwq->wq, and both updating work->data to point
1211 * to pwq on queueing and to pool on dequeueing are done under
1212 * pwq->pool->lock. This in turn guarantees that, if work->data
1213 * points to pwq which is associated with a locked pool, the work
1214 * item is currently queued on that pool.
1216 pwq = get_work_pwq(work);
1217 if (pwq && pwq->pool == pool) {
1218 debug_work_deactivate(work);
1221 * A delayed work item cannot be grabbed directly because
1222 * it might have linked NO_COLOR work items which, if left
1223 * on the delayed_list, will confuse pwq->nr_active
1224 * management later on and cause stall. Make sure the work
1225 * item is activated before grabbing.
1227 if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1228 pwq_activate_delayed_work(work);
1230 list_del_init(&work->entry);
1231 pwq_dec_nr_in_flight(get_work_pwq(work), get_work_color(work));
1233 /* work->data points to pwq iff queued, point to pool */
1234 set_work_pool_and_keep_pending(work, pool->id);
1236 spin_unlock(&pool->lock);
1237 return 1;
1239 spin_unlock(&pool->lock);
1240 fail:
1241 local_irq_restore(*flags);
1242 if (work_is_canceling(work))
1243 return -ENOENT;
1244 cpu_relax();
1245 return -EAGAIN;
1249 * insert_work - insert a work into a pool
1250 * @pwq: pwq @work belongs to
1251 * @work: work to insert
1252 * @head: insertion point
1253 * @extra_flags: extra WORK_STRUCT_* flags to set
1255 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
1256 * work_struct flags.
1258 * CONTEXT:
1259 * spin_lock_irq(pool->lock).
1261 static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1262 struct list_head *head, unsigned int extra_flags)
1264 struct worker_pool *pool = pwq->pool;
1266 /* we own @work, set data and link */
1267 set_work_pwq(work, pwq, extra_flags);
1268 list_add_tail(&work->entry, head);
1269 get_pwq(pwq);
1272 * Ensure either wq_worker_sleeping() sees the above
1273 * list_add_tail() or we see zero nr_running to avoid workers lying
1274 * around lazily while there are works to be processed.
1276 smp_mb();
1278 if (__need_more_worker(pool))
1279 wake_up_worker(pool);
1283 * Test whether @work is being queued from another work executing on the
1284 * same workqueue.
1286 static bool is_chained_work(struct workqueue_struct *wq)
1288 struct worker *worker;
1290 worker = current_wq_worker();
1292 * Return %true iff I'm a worker execuing a work item on @wq. If
1293 * I'm @worker, it's safe to dereference it without locking.
1295 return worker && worker->current_pwq->wq == wq;
1298 static void __queue_work(int cpu, struct workqueue_struct *wq,
1299 struct work_struct *work)
1301 struct pool_workqueue *pwq;
1302 struct worker_pool *last_pool;
1303 struct list_head *worklist;
1304 unsigned int work_flags;
1305 unsigned int req_cpu = cpu;
1308 * While a work item is PENDING && off queue, a task trying to
1309 * steal the PENDING will busy-loop waiting for it to either get
1310 * queued or lose PENDING. Grabbing PENDING and queueing should
1311 * happen with IRQ disabled.
1313 WARN_ON_ONCE(!irqs_disabled());
1315 debug_work_activate(work);
1317 /* if dying, only works from the same workqueue are allowed */
1318 if (unlikely(wq->flags & __WQ_DRAINING) &&
1319 WARN_ON_ONCE(!is_chained_work(wq)))
1320 return;
1321 retry:
1322 if (req_cpu == WORK_CPU_UNBOUND)
1323 cpu = raw_smp_processor_id();
1325 /* pwq which will be used unless @work is executing elsewhere */
1326 if (!(wq->flags & WQ_UNBOUND))
1327 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1328 else
1329 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1332 * If @work was previously on a different pool, it might still be
1333 * running there, in which case the work needs to be queued on that
1334 * pool to guarantee non-reentrancy.
1336 last_pool = get_work_pool(work);
1337 if (last_pool && last_pool != pwq->pool) {
1338 struct worker *worker;
1340 spin_lock(&last_pool->lock);
1342 worker = find_worker_executing_work(last_pool, work);
1344 if (worker && worker->current_pwq->wq == wq) {
1345 pwq = worker->current_pwq;
1346 } else {
1347 /* meh... not running there, queue here */
1348 spin_unlock(&last_pool->lock);
1349 spin_lock(&pwq->pool->lock);
1351 } else {
1352 spin_lock(&pwq->pool->lock);
1356 * pwq is determined and locked. For unbound pools, we could have
1357 * raced with pwq release and it could already be dead. If its
1358 * refcnt is zero, repeat pwq selection. Note that pwqs never die
1359 * without another pwq replacing it in the numa_pwq_tbl or while
1360 * work items are executing on it, so the retrying is guaranteed to
1361 * make forward-progress.
1363 if (unlikely(!pwq->refcnt)) {
1364 if (wq->flags & WQ_UNBOUND) {
1365 spin_unlock(&pwq->pool->lock);
1366 cpu_relax();
1367 goto retry;
1369 /* oops */
1370 WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
1371 wq->name, cpu);
1374 /* pwq determined, queue */
1375 trace_workqueue_queue_work(req_cpu, pwq, work);
1377 if (WARN_ON(!list_empty(&work->entry))) {
1378 spin_unlock(&pwq->pool->lock);
1379 return;
1382 pwq->nr_in_flight[pwq->work_color]++;
1383 work_flags = work_color_to_flags(pwq->work_color);
1385 if (likely(pwq->nr_active < pwq->max_active)) {
1386 trace_workqueue_activate_work(work);
1387 pwq->nr_active++;
1388 worklist = &pwq->pool->worklist;
1389 } else {
1390 work_flags |= WORK_STRUCT_DELAYED;
1391 worklist = &pwq->delayed_works;
1394 insert_work(pwq, work, worklist, work_flags);
1396 spin_unlock(&pwq->pool->lock);
1400 * queue_work_on - queue work on specific cpu
1401 * @cpu: CPU number to execute work on
1402 * @wq: workqueue to use
1403 * @work: work to queue
1405 * Returns %false if @work was already on a queue, %true otherwise.
1407 * We queue the work to a specific CPU, the caller must ensure it
1408 * can't go away.
1410 bool queue_work_on(int cpu, struct workqueue_struct *wq,
1411 struct work_struct *work)
1413 bool ret = false;
1414 unsigned long flags;
1416 local_irq_save(flags);
1418 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1419 __queue_work(cpu, wq, work);
1420 ret = true;
1423 local_irq_restore(flags);
1424 return ret;
1426 EXPORT_SYMBOL_GPL(queue_work_on);
1428 void delayed_work_timer_fn(unsigned long __data)
1430 struct delayed_work *dwork = (struct delayed_work *)__data;
1432 /* should have been called from irqsafe timer with irq already off */
1433 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
1435 EXPORT_SYMBOL(delayed_work_timer_fn);
1437 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
1438 struct delayed_work *dwork, unsigned long delay)
1440 struct timer_list *timer = &dwork->timer;
1441 struct work_struct *work = &dwork->work;
1443 WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
1444 timer->data != (unsigned long)dwork);
1445 WARN_ON_ONCE(timer_pending(timer));
1446 WARN_ON_ONCE(!list_empty(&work->entry));
1449 * If @delay is 0, queue @dwork->work immediately. This is for
1450 * both optimization and correctness. The earliest @timer can
1451 * expire is on the closest next tick and delayed_work users depend
1452 * on that there's no such delay when @delay is 0.
1454 if (!delay) {
1455 __queue_work(cpu, wq, &dwork->work);
1456 return;
1459 timer_stats_timer_set_start_info(&dwork->timer);
1461 dwork->wq = wq;
1462 dwork->cpu = cpu;
1463 timer->expires = jiffies + delay;
1465 if (unlikely(cpu != WORK_CPU_UNBOUND))
1466 add_timer_on(timer, cpu);
1467 else
1468 add_timer(timer);
1472 * queue_delayed_work_on - queue work on specific CPU after delay
1473 * @cpu: CPU number to execute work on
1474 * @wq: workqueue to use
1475 * @dwork: work to queue
1476 * @delay: number of jiffies to wait before queueing
1478 * Returns %false if @work was already on a queue, %true otherwise. If
1479 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1480 * execution.
1482 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
1483 struct delayed_work *dwork, unsigned long delay)
1485 struct work_struct *work = &dwork->work;
1486 bool ret = false;
1487 unsigned long flags;
1489 /* read the comment in __queue_work() */
1490 local_irq_save(flags);
1492 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1493 __queue_delayed_work(cpu, wq, dwork, delay);
1494 ret = true;
1497 local_irq_restore(flags);
1498 return ret;
1500 EXPORT_SYMBOL_GPL(queue_delayed_work_on);
1503 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1504 * @cpu: CPU number to execute work on
1505 * @wq: workqueue to use
1506 * @dwork: work to queue
1507 * @delay: number of jiffies to wait before queueing
1509 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1510 * modify @dwork's timer so that it expires after @delay. If @delay is
1511 * zero, @work is guaranteed to be scheduled immediately regardless of its
1512 * current state.
1514 * Returns %false if @dwork was idle and queued, %true if @dwork was
1515 * pending and its timer was modified.
1517 * This function is safe to call from any context including IRQ handler.
1518 * See try_to_grab_pending() for details.
1520 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
1521 struct delayed_work *dwork, unsigned long delay)
1523 unsigned long flags;
1524 int ret;
1526 do {
1527 ret = try_to_grab_pending(&dwork->work, true, &flags);
1528 } while (unlikely(ret == -EAGAIN));
1530 if (likely(ret >= 0)) {
1531 __queue_delayed_work(cpu, wq, dwork, delay);
1532 local_irq_restore(flags);
1535 /* -ENOENT from try_to_grab_pending() becomes %true */
1536 return ret;
1538 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
1541 * worker_enter_idle - enter idle state
1542 * @worker: worker which is entering idle state
1544 * @worker is entering idle state. Update stats and idle timer if
1545 * necessary.
1547 * LOCKING:
1548 * spin_lock_irq(pool->lock).
1550 static void worker_enter_idle(struct worker *worker)
1552 struct worker_pool *pool = worker->pool;
1554 if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
1555 WARN_ON_ONCE(!list_empty(&worker->entry) &&
1556 (worker->hentry.next || worker->hentry.pprev)))
1557 return;
1559 /* can't use worker_set_flags(), also called from start_worker() */
1560 worker->flags |= WORKER_IDLE;
1561 pool->nr_idle++;
1562 worker->last_active = jiffies;
1564 /* idle_list is LIFO */
1565 list_add(&worker->entry, &pool->idle_list);
1567 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1568 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1571 * Sanity check nr_running. Because wq_unbind_fn() releases
1572 * pool->lock between setting %WORKER_UNBOUND and zapping
1573 * nr_running, the warning may trigger spuriously. Check iff
1574 * unbind is not in progress.
1576 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1577 pool->nr_workers == pool->nr_idle &&
1578 atomic_read(&pool->nr_running));
1582 * worker_leave_idle - leave idle state
1583 * @worker: worker which is leaving idle state
1585 * @worker is leaving idle state. Update stats.
1587 * LOCKING:
1588 * spin_lock_irq(pool->lock).
1590 static void worker_leave_idle(struct worker *worker)
1592 struct worker_pool *pool = worker->pool;
1594 if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
1595 return;
1596 worker_clr_flags(worker, WORKER_IDLE);
1597 pool->nr_idle--;
1598 list_del_init(&worker->entry);
1602 * worker_maybe_bind_and_lock - try to bind %current to worker_pool and lock it
1603 * @pool: target worker_pool
1605 * Bind %current to the cpu of @pool if it is associated and lock @pool.
1607 * Works which are scheduled while the cpu is online must at least be
1608 * scheduled to a worker which is bound to the cpu so that if they are
1609 * flushed from cpu callbacks while cpu is going down, they are
1610 * guaranteed to execute on the cpu.
1612 * This function is to be used by unbound workers and rescuers to bind
1613 * themselves to the target cpu and may race with cpu going down or
1614 * coming online. kthread_bind() can't be used because it may put the
1615 * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1616 * verbatim as it's best effort and blocking and pool may be
1617 * [dis]associated in the meantime.
1619 * This function tries set_cpus_allowed() and locks pool and verifies the
1620 * binding against %POOL_DISASSOCIATED which is set during
1621 * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
1622 * enters idle state or fetches works without dropping lock, it can
1623 * guarantee the scheduling requirement described in the first paragraph.
1625 * CONTEXT:
1626 * Might sleep. Called without any lock but returns with pool->lock
1627 * held.
1629 * RETURNS:
1630 * %true if the associated pool is online (@worker is successfully
1631 * bound), %false if offline.
1633 static bool worker_maybe_bind_and_lock(struct worker_pool *pool)
1634 __acquires(&pool->lock)
1636 while (true) {
1638 * The following call may fail, succeed or succeed
1639 * without actually migrating the task to the cpu if
1640 * it races with cpu hotunplug operation. Verify
1641 * against POOL_DISASSOCIATED.
1643 if (!(pool->flags & POOL_DISASSOCIATED))
1644 set_cpus_allowed_ptr(current, pool->attrs->cpumask);
1646 spin_lock_irq(&pool->lock);
1647 if (pool->flags & POOL_DISASSOCIATED)
1648 return false;
1649 if (task_cpu(current) == pool->cpu &&
1650 cpumask_equal(&current->cpus_allowed, pool->attrs->cpumask))
1651 return true;
1652 spin_unlock_irq(&pool->lock);
1655 * We've raced with CPU hot[un]plug. Give it a breather
1656 * and retry migration. cond_resched() is required here;
1657 * otherwise, we might deadlock against cpu_stop trying to
1658 * bring down the CPU on non-preemptive kernel.
1660 cpu_relax();
1661 cond_resched();
1665 static struct worker *alloc_worker(void)
1667 struct worker *worker;
1669 worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1670 if (worker) {
1671 INIT_LIST_HEAD(&worker->entry);
1672 INIT_LIST_HEAD(&worker->scheduled);
1673 /* on creation a worker is in !idle && prep state */
1674 worker->flags = WORKER_PREP;
1676 return worker;
1680 * create_worker - create a new workqueue worker
1681 * @pool: pool the new worker will belong to
1683 * Create a new worker which is bound to @pool. The returned worker
1684 * can be started by calling start_worker() or destroyed using
1685 * destroy_worker().
1687 * CONTEXT:
1688 * Might sleep. Does GFP_KERNEL allocations.
1690 * RETURNS:
1691 * Pointer to the newly created worker.
1693 static struct worker *create_worker(struct worker_pool *pool)
1695 struct worker *worker = NULL;
1696 int id = -1;
1697 char id_buf[16];
1699 lockdep_assert_held(&pool->manager_mutex);
1702 * ID is needed to determine kthread name. Allocate ID first
1703 * without installing the pointer.
1705 idr_preload(GFP_KERNEL);
1706 spin_lock_irq(&pool->lock);
1708 id = idr_alloc(&pool->worker_idr, NULL, 0, 0, GFP_NOWAIT);
1710 spin_unlock_irq(&pool->lock);
1711 idr_preload_end();
1712 if (id < 0)
1713 goto fail;
1715 worker = alloc_worker();
1716 if (!worker)
1717 goto fail;
1719 worker->pool = pool;
1720 worker->id = id;
1722 if (pool->cpu >= 0)
1723 snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
1724 pool->attrs->nice < 0 ? "H" : "");
1725 else
1726 snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
1728 worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
1729 "kworker/%s", id_buf);
1730 if (IS_ERR(worker->task))
1731 goto fail;
1734 * set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
1735 * online CPUs. It'll be re-applied when any of the CPUs come up.
1737 set_user_nice(worker->task, pool->attrs->nice);
1738 set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
1740 /* prevent userland from meddling with cpumask of workqueue workers */
1741 worker->task->flags |= PF_NO_SETAFFINITY;
1744 * The caller is responsible for ensuring %POOL_DISASSOCIATED
1745 * remains stable across this function. See the comments above the
1746 * flag definition for details.
1748 if (pool->flags & POOL_DISASSOCIATED)
1749 worker->flags |= WORKER_UNBOUND;
1751 /* successful, commit the pointer to idr */
1752 spin_lock_irq(&pool->lock);
1753 idr_replace(&pool->worker_idr, worker, worker->id);
1754 spin_unlock_irq(&pool->lock);
1756 return worker;
1758 fail:
1759 if (id >= 0) {
1760 spin_lock_irq(&pool->lock);
1761 idr_remove(&pool->worker_idr, id);
1762 spin_unlock_irq(&pool->lock);
1764 kfree(worker);
1765 return NULL;
1769 * start_worker - start a newly created worker
1770 * @worker: worker to start
1772 * Make the pool aware of @worker and start it.
1774 * CONTEXT:
1775 * spin_lock_irq(pool->lock).
1777 static void start_worker(struct worker *worker)
1779 worker->flags |= WORKER_STARTED;
1780 worker->pool->nr_workers++;
1781 worker_enter_idle(worker);
1782 wake_up_process(worker->task);
1786 * create_and_start_worker - create and start a worker for a pool
1787 * @pool: the target pool
1789 * Grab the managership of @pool and create and start a new worker for it.
1791 static int create_and_start_worker(struct worker_pool *pool)
1793 struct worker *worker;
1795 mutex_lock(&pool->manager_mutex);
1797 worker = create_worker(pool);
1798 if (worker) {
1799 spin_lock_irq(&pool->lock);
1800 start_worker(worker);
1801 spin_unlock_irq(&pool->lock);
1804 mutex_unlock(&pool->manager_mutex);
1806 return worker ? 0 : -ENOMEM;
1810 * destroy_worker - destroy a workqueue worker
1811 * @worker: worker to be destroyed
1813 * Destroy @worker and adjust @pool stats accordingly.
1815 * CONTEXT:
1816 * spin_lock_irq(pool->lock) which is released and regrabbed.
1818 static void destroy_worker(struct worker *worker)
1820 struct worker_pool *pool = worker->pool;
1822 lockdep_assert_held(&pool->manager_mutex);
1823 lockdep_assert_held(&pool->lock);
1825 /* sanity check frenzy */
1826 if (WARN_ON(worker->current_work) ||
1827 WARN_ON(!list_empty(&worker->scheduled)))
1828 return;
1830 if (worker->flags & WORKER_STARTED)
1831 pool->nr_workers--;
1832 if (worker->flags & WORKER_IDLE)
1833 pool->nr_idle--;
1835 list_del_init(&worker->entry);
1836 worker->flags |= WORKER_DIE;
1838 idr_remove(&pool->worker_idr, worker->id);
1840 spin_unlock_irq(&pool->lock);
1842 kthread_stop(worker->task);
1843 kfree(worker);
1845 spin_lock_irq(&pool->lock);
1848 static void idle_worker_timeout(unsigned long __pool)
1850 struct worker_pool *pool = (void *)__pool;
1852 spin_lock_irq(&pool->lock);
1854 if (too_many_workers(pool)) {
1855 struct worker *worker;
1856 unsigned long expires;
1858 /* idle_list is kept in LIFO order, check the last one */
1859 worker = list_entry(pool->idle_list.prev, struct worker, entry);
1860 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1862 if (time_before(jiffies, expires))
1863 mod_timer(&pool->idle_timer, expires);
1864 else {
1865 /* it's been idle for too long, wake up manager */
1866 pool->flags |= POOL_MANAGE_WORKERS;
1867 wake_up_worker(pool);
1871 spin_unlock_irq(&pool->lock);
1874 static void send_mayday(struct work_struct *work)
1876 struct pool_workqueue *pwq = get_work_pwq(work);
1877 struct workqueue_struct *wq = pwq->wq;
1879 lockdep_assert_held(&wq_mayday_lock);
1881 if (!wq->rescuer)
1882 return;
1884 /* mayday mayday mayday */
1885 if (list_empty(&pwq->mayday_node)) {
1886 list_add_tail(&pwq->mayday_node, &wq->maydays);
1887 wake_up_process(wq->rescuer->task);
1891 static void pool_mayday_timeout(unsigned long __pool)
1893 struct worker_pool *pool = (void *)__pool;
1894 struct work_struct *work;
1896 spin_lock_irq(&wq_mayday_lock); /* for wq->maydays */
1897 spin_lock(&pool->lock);
1899 if (need_to_create_worker(pool)) {
1901 * We've been trying to create a new worker but
1902 * haven't been successful. We might be hitting an
1903 * allocation deadlock. Send distress signals to
1904 * rescuers.
1906 list_for_each_entry(work, &pool->worklist, entry)
1907 send_mayday(work);
1910 spin_unlock(&pool->lock);
1911 spin_unlock_irq(&wq_mayday_lock);
1913 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1917 * maybe_create_worker - create a new worker if necessary
1918 * @pool: pool to create a new worker for
1920 * Create a new worker for @pool if necessary. @pool is guaranteed to
1921 * have at least one idle worker on return from this function. If
1922 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1923 * sent to all rescuers with works scheduled on @pool to resolve
1924 * possible allocation deadlock.
1926 * On return, need_to_create_worker() is guaranteed to be %false and
1927 * may_start_working() %true.
1929 * LOCKING:
1930 * spin_lock_irq(pool->lock) which may be released and regrabbed
1931 * multiple times. Does GFP_KERNEL allocations. Called only from
1932 * manager.
1934 * RETURNS:
1935 * %false if no action was taken and pool->lock stayed locked, %true
1936 * otherwise.
1938 static bool maybe_create_worker(struct worker_pool *pool)
1939 __releases(&pool->lock)
1940 __acquires(&pool->lock)
1942 if (!need_to_create_worker(pool))
1943 return false;
1944 restart:
1945 spin_unlock_irq(&pool->lock);
1947 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1948 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1950 while (true) {
1951 struct worker *worker;
1953 worker = create_worker(pool);
1954 if (worker) {
1955 del_timer_sync(&pool->mayday_timer);
1956 spin_lock_irq(&pool->lock);
1957 start_worker(worker);
1958 if (WARN_ON_ONCE(need_to_create_worker(pool)))
1959 goto restart;
1960 return true;
1963 if (!need_to_create_worker(pool))
1964 break;
1966 __set_current_state(TASK_INTERRUPTIBLE);
1967 schedule_timeout(CREATE_COOLDOWN);
1969 if (!need_to_create_worker(pool))
1970 break;
1973 del_timer_sync(&pool->mayday_timer);
1974 spin_lock_irq(&pool->lock);
1975 if (need_to_create_worker(pool))
1976 goto restart;
1977 return true;
1981 * maybe_destroy_worker - destroy workers which have been idle for a while
1982 * @pool: pool to destroy workers for
1984 * Destroy @pool workers which have been idle for longer than
1985 * IDLE_WORKER_TIMEOUT.
1987 * LOCKING:
1988 * spin_lock_irq(pool->lock) which may be released and regrabbed
1989 * multiple times. Called only from manager.
1991 * RETURNS:
1992 * %false if no action was taken and pool->lock stayed locked, %true
1993 * otherwise.
1995 static bool maybe_destroy_workers(struct worker_pool *pool)
1997 bool ret = false;
1999 while (too_many_workers(pool)) {
2000 struct worker *worker;
2001 unsigned long expires;
2003 worker = list_entry(pool->idle_list.prev, struct worker, entry);
2004 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2006 if (time_before(jiffies, expires)) {
2007 mod_timer(&pool->idle_timer, expires);
2008 break;
2011 destroy_worker(worker);
2012 ret = true;
2015 return ret;
2019 * manage_workers - manage worker pool
2020 * @worker: self
2022 * Assume the manager role and manage the worker pool @worker belongs
2023 * to. At any given time, there can be only zero or one manager per
2024 * pool. The exclusion is handled automatically by this function.
2026 * The caller can safely start processing works on false return. On
2027 * true return, it's guaranteed that need_to_create_worker() is false
2028 * and may_start_working() is true.
2030 * CONTEXT:
2031 * spin_lock_irq(pool->lock) which may be released and regrabbed
2032 * multiple times. Does GFP_KERNEL allocations.
2034 * RETURNS:
2035 * spin_lock_irq(pool->lock) which may be released and regrabbed
2036 * multiple times. Does GFP_KERNEL allocations.
2038 static bool manage_workers(struct worker *worker)
2040 struct worker_pool *pool = worker->pool;
2041 bool ret = false;
2044 * Managership is governed by two mutexes - manager_arb and
2045 * manager_mutex. manager_arb handles arbitration of manager role.
2046 * Anyone who successfully grabs manager_arb wins the arbitration
2047 * and becomes the manager. mutex_trylock() on pool->manager_arb
2048 * failure while holding pool->lock reliably indicates that someone
2049 * else is managing the pool and the worker which failed trylock
2050 * can proceed to executing work items. This means that anyone
2051 * grabbing manager_arb is responsible for actually performing
2052 * manager duties. If manager_arb is grabbed and released without
2053 * actual management, the pool may stall indefinitely.
2055 * manager_mutex is used for exclusion of actual management
2056 * operations. The holder of manager_mutex can be sure that none
2057 * of management operations, including creation and destruction of
2058 * workers, won't take place until the mutex is released. Because
2059 * manager_mutex doesn't interfere with manager role arbitration,
2060 * it is guaranteed that the pool's management, while may be
2061 * delayed, won't be disturbed by someone else grabbing
2062 * manager_mutex.
2064 if (!mutex_trylock(&pool->manager_arb))
2065 return ret;
2068 * With manager arbitration won, manager_mutex would be free in
2069 * most cases. trylock first without dropping @pool->lock.
2071 if (unlikely(!mutex_trylock(&pool->manager_mutex))) {
2072 spin_unlock_irq(&pool->lock);
2073 mutex_lock(&pool->manager_mutex);
2074 ret = true;
2077 pool->flags &= ~POOL_MANAGE_WORKERS;
2080 * Destroy and then create so that may_start_working() is true
2081 * on return.
2083 ret |= maybe_destroy_workers(pool);
2084 ret |= maybe_create_worker(pool);
2086 mutex_unlock(&pool->manager_mutex);
2087 mutex_unlock(&pool->manager_arb);
2088 return ret;
2092 * process_one_work - process single work
2093 * @worker: self
2094 * @work: work to process
2096 * Process @work. This function contains all the logics necessary to
2097 * process a single work including synchronization against and
2098 * interaction with other workers on the same cpu, queueing and
2099 * flushing. As long as context requirement is met, any worker can
2100 * call this function to process a work.
2102 * CONTEXT:
2103 * spin_lock_irq(pool->lock) which is released and regrabbed.
2105 static void process_one_work(struct worker *worker, struct work_struct *work)
2106 __releases(&pool->lock)
2107 __acquires(&pool->lock)
2109 struct pool_workqueue *pwq = get_work_pwq(work);
2110 struct worker_pool *pool = worker->pool;
2111 bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
2112 int work_color;
2113 struct worker *collision;
2114 #ifdef CONFIG_LOCKDEP
2116 * It is permissible to free the struct work_struct from
2117 * inside the function that is called from it, this we need to
2118 * take into account for lockdep too. To avoid bogus "held
2119 * lock freed" warnings as well as problems when looking into
2120 * work->lockdep_map, make a copy and use that here.
2122 struct lockdep_map lockdep_map;
2124 lockdep_copy_map(&lockdep_map, &work->lockdep_map);
2125 #endif
2127 * Ensure we're on the correct CPU. DISASSOCIATED test is
2128 * necessary to avoid spurious warnings from rescuers servicing the
2129 * unbound or a disassociated pool.
2131 WARN_ON_ONCE(!(worker->flags & WORKER_UNBOUND) &&
2132 !(pool->flags & POOL_DISASSOCIATED) &&
2133 raw_smp_processor_id() != pool->cpu);
2136 * A single work shouldn't be executed concurrently by
2137 * multiple workers on a single cpu. Check whether anyone is
2138 * already processing the work. If so, defer the work to the
2139 * currently executing one.
2141 collision = find_worker_executing_work(pool, work);
2142 if (unlikely(collision)) {
2143 move_linked_works(work, &collision->scheduled, NULL);
2144 return;
2147 /* claim and dequeue */
2148 debug_work_deactivate(work);
2149 hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2150 worker->current_work = work;
2151 worker->current_func = work->func;
2152 worker->current_pwq = pwq;
2153 work_color = get_work_color(work);
2155 list_del_init(&work->entry);
2158 * CPU intensive works don't participate in concurrency
2159 * management. They're the scheduler's responsibility.
2161 if (unlikely(cpu_intensive))
2162 worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
2165 * Unbound pool isn't concurrency managed and work items should be
2166 * executed ASAP. Wake up another worker if necessary.
2168 if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
2169 wake_up_worker(pool);
2172 * Record the last pool and clear PENDING which should be the last
2173 * update to @work. Also, do this inside @pool->lock so that
2174 * PENDING and queued state changes happen together while IRQ is
2175 * disabled.
2177 set_work_pool_and_clear_pending(work, pool->id);
2179 spin_unlock_irq(&pool->lock);
2181 lock_map_acquire_read(&pwq->wq->lockdep_map);
2182 lock_map_acquire(&lockdep_map);
2183 trace_workqueue_execute_start(work);
2184 worker->current_func(work);
2186 * While we must be careful to not use "work" after this, the trace
2187 * point will only record its address.
2189 trace_workqueue_execute_end(work);
2190 lock_map_release(&lockdep_map);
2191 lock_map_release(&pwq->wq->lockdep_map);
2193 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2194 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2195 " last function: %pf\n",
2196 current->comm, preempt_count(), task_pid_nr(current),
2197 worker->current_func);
2198 debug_show_held_locks(current);
2199 dump_stack();
2202 spin_lock_irq(&pool->lock);
2204 /* clear cpu intensive status */
2205 if (unlikely(cpu_intensive))
2206 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2208 /* we're done with it, release */
2209 hash_del(&worker->hentry);
2210 worker->current_work = NULL;
2211 worker->current_func = NULL;
2212 worker->current_pwq = NULL;
2213 pwq_dec_nr_in_flight(pwq, work_color);
2217 * process_scheduled_works - process scheduled works
2218 * @worker: self
2220 * Process all scheduled works. Please note that the scheduled list
2221 * may change while processing a work, so this function repeatedly
2222 * fetches a work from the top and executes it.
2224 * CONTEXT:
2225 * spin_lock_irq(pool->lock) which may be released and regrabbed
2226 * multiple times.
2228 static void process_scheduled_works(struct worker *worker)
2230 while (!list_empty(&worker->scheduled)) {
2231 struct work_struct *work = list_first_entry(&worker->scheduled,
2232 struct work_struct, entry);
2233 process_one_work(worker, work);
2238 * worker_thread - the worker thread function
2239 * @__worker: self
2241 * The worker thread function. All workers belong to a worker_pool -
2242 * either a per-cpu one or dynamic unbound one. These workers process all
2243 * work items regardless of their specific target workqueue. The only
2244 * exception is work items which belong to workqueues with a rescuer which
2245 * will be explained in rescuer_thread().
2247 static int worker_thread(void *__worker)
2249 struct worker *worker = __worker;
2250 struct worker_pool *pool = worker->pool;
2252 /* tell the scheduler that this is a workqueue worker */
2253 worker->task->flags |= PF_WQ_WORKER;
2254 woke_up:
2255 spin_lock_irq(&pool->lock);
2257 /* am I supposed to die? */
2258 if (unlikely(worker->flags & WORKER_DIE)) {
2259 spin_unlock_irq(&pool->lock);
2260 WARN_ON_ONCE(!list_empty(&worker->entry));
2261 worker->task->flags &= ~PF_WQ_WORKER;
2262 return 0;
2265 worker_leave_idle(worker);
2266 recheck:
2267 /* no more worker necessary? */
2268 if (!need_more_worker(pool))
2269 goto sleep;
2271 /* do we need to manage? */
2272 if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2273 goto recheck;
2276 * ->scheduled list can only be filled while a worker is
2277 * preparing to process a work or actually processing it.
2278 * Make sure nobody diddled with it while I was sleeping.
2280 WARN_ON_ONCE(!list_empty(&worker->scheduled));
2283 * Finish PREP stage. We're guaranteed to have at least one idle
2284 * worker or that someone else has already assumed the manager
2285 * role. This is where @worker starts participating in concurrency
2286 * management if applicable and concurrency management is restored
2287 * after being rebound. See rebind_workers() for details.
2289 worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2291 do {
2292 struct work_struct *work =
2293 list_first_entry(&pool->worklist,
2294 struct work_struct, entry);
2296 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2297 /* optimization path, not strictly necessary */
2298 process_one_work(worker, work);
2299 if (unlikely(!list_empty(&worker->scheduled)))
2300 process_scheduled_works(worker);
2301 } else {
2302 move_linked_works(work, &worker->scheduled, NULL);
2303 process_scheduled_works(worker);
2305 } while (keep_working(pool));
2307 worker_set_flags(worker, WORKER_PREP, false);
2308 sleep:
2309 if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
2310 goto recheck;
2313 * pool->lock is held and there's no work to process and no need to
2314 * manage, sleep. Workers are woken up only while holding
2315 * pool->lock or from local cpu, so setting the current state
2316 * before releasing pool->lock is enough to prevent losing any
2317 * event.
2319 worker_enter_idle(worker);
2320 __set_current_state(TASK_INTERRUPTIBLE);
2321 spin_unlock_irq(&pool->lock);
2322 schedule();
2323 goto woke_up;
2327 * rescuer_thread - the rescuer thread function
2328 * @__rescuer: self
2330 * Workqueue rescuer thread function. There's one rescuer for each
2331 * workqueue which has WQ_MEM_RECLAIM set.
2333 * Regular work processing on a pool may block trying to create a new
2334 * worker which uses GFP_KERNEL allocation which has slight chance of
2335 * developing into deadlock if some works currently on the same queue
2336 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2337 * the problem rescuer solves.
2339 * When such condition is possible, the pool summons rescuers of all
2340 * workqueues which have works queued on the pool and let them process
2341 * those works so that forward progress can be guaranteed.
2343 * This should happen rarely.
2345 static int rescuer_thread(void *__rescuer)
2347 struct worker *rescuer = __rescuer;
2348 struct workqueue_struct *wq = rescuer->rescue_wq;
2349 struct list_head *scheduled = &rescuer->scheduled;
2351 set_user_nice(current, RESCUER_NICE_LEVEL);
2354 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2355 * doesn't participate in concurrency management.
2357 rescuer->task->flags |= PF_WQ_WORKER;
2358 repeat:
2359 set_current_state(TASK_INTERRUPTIBLE);
2361 if (kthread_should_stop()) {
2362 __set_current_state(TASK_RUNNING);
2363 rescuer->task->flags &= ~PF_WQ_WORKER;
2364 return 0;
2367 /* see whether any pwq is asking for help */
2368 spin_lock_irq(&wq_mayday_lock);
2370 while (!list_empty(&wq->maydays)) {
2371 struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2372 struct pool_workqueue, mayday_node);
2373 struct worker_pool *pool = pwq->pool;
2374 struct work_struct *work, *n;
2376 __set_current_state(TASK_RUNNING);
2377 list_del_init(&pwq->mayday_node);
2379 spin_unlock_irq(&wq_mayday_lock);
2381 /* migrate to the target cpu if possible */
2382 worker_maybe_bind_and_lock(pool);
2383 rescuer->pool = pool;
2386 * Slurp in all works issued via this workqueue and
2387 * process'em.
2389 WARN_ON_ONCE(!list_empty(&rescuer->scheduled));
2390 list_for_each_entry_safe(work, n, &pool->worklist, entry)
2391 if (get_work_pwq(work) == pwq)
2392 move_linked_works(work, scheduled, &n);
2394 process_scheduled_works(rescuer);
2397 * Leave this pool. If keep_working() is %true, notify a
2398 * regular worker; otherwise, we end up with 0 concurrency
2399 * and stalling the execution.
2401 if (keep_working(pool))
2402 wake_up_worker(pool);
2404 rescuer->pool = NULL;
2405 spin_unlock(&pool->lock);
2406 spin_lock(&wq_mayday_lock);
2409 spin_unlock_irq(&wq_mayday_lock);
2411 /* rescuers should never participate in concurrency management */
2412 WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2413 schedule();
2414 goto repeat;
2417 struct wq_barrier {
2418 struct work_struct work;
2419 struct completion done;
2422 static void wq_barrier_func(struct work_struct *work)
2424 struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2425 complete(&barr->done);
2429 * insert_wq_barrier - insert a barrier work
2430 * @pwq: pwq to insert barrier into
2431 * @barr: wq_barrier to insert
2432 * @target: target work to attach @barr to
2433 * @worker: worker currently executing @target, NULL if @target is not executing
2435 * @barr is linked to @target such that @barr is completed only after
2436 * @target finishes execution. Please note that the ordering
2437 * guarantee is observed only with respect to @target and on the local
2438 * cpu.
2440 * Currently, a queued barrier can't be canceled. This is because
2441 * try_to_grab_pending() can't determine whether the work to be
2442 * grabbed is at the head of the queue and thus can't clear LINKED
2443 * flag of the previous work while there must be a valid next work
2444 * after a work with LINKED flag set.
2446 * Note that when @worker is non-NULL, @target may be modified
2447 * underneath us, so we can't reliably determine pwq from @target.
2449 * CONTEXT:
2450 * spin_lock_irq(pool->lock).
2452 static void insert_wq_barrier(struct pool_workqueue *pwq,
2453 struct wq_barrier *barr,
2454 struct work_struct *target, struct worker *worker)
2456 struct list_head *head;
2457 unsigned int linked = 0;
2460 * debugobject calls are safe here even with pool->lock locked
2461 * as we know for sure that this will not trigger any of the
2462 * checks and call back into the fixup functions where we
2463 * might deadlock.
2465 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2466 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2467 init_completion(&barr->done);
2470 * If @target is currently being executed, schedule the
2471 * barrier to the worker; otherwise, put it after @target.
2473 if (worker)
2474 head = worker->scheduled.next;
2475 else {
2476 unsigned long *bits = work_data_bits(target);
2478 head = target->entry.next;
2479 /* there can already be other linked works, inherit and set */
2480 linked = *bits & WORK_STRUCT_LINKED;
2481 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2484 debug_work_activate(&barr->work);
2485 insert_work(pwq, &barr->work, head,
2486 work_color_to_flags(WORK_NO_COLOR) | linked);
2490 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
2491 * @wq: workqueue being flushed
2492 * @flush_color: new flush color, < 0 for no-op
2493 * @work_color: new work color, < 0 for no-op
2495 * Prepare pwqs for workqueue flushing.
2497 * If @flush_color is non-negative, flush_color on all pwqs should be
2498 * -1. If no pwq has in-flight commands at the specified color, all
2499 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
2500 * has in flight commands, its pwq->flush_color is set to
2501 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
2502 * wakeup logic is armed and %true is returned.
2504 * The caller should have initialized @wq->first_flusher prior to
2505 * calling this function with non-negative @flush_color. If
2506 * @flush_color is negative, no flush color update is done and %false
2507 * is returned.
2509 * If @work_color is non-negative, all pwqs should have the same
2510 * work_color which is previous to @work_color and all will be
2511 * advanced to @work_color.
2513 * CONTEXT:
2514 * mutex_lock(wq->mutex).
2516 * RETURNS:
2517 * %true if @flush_color >= 0 and there's something to flush. %false
2518 * otherwise.
2520 static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
2521 int flush_color, int work_color)
2523 bool wait = false;
2524 struct pool_workqueue *pwq;
2526 if (flush_color >= 0) {
2527 WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2528 atomic_set(&wq->nr_pwqs_to_flush, 1);
2531 for_each_pwq(pwq, wq) {
2532 struct worker_pool *pool = pwq->pool;
2534 spin_lock_irq(&pool->lock);
2536 if (flush_color >= 0) {
2537 WARN_ON_ONCE(pwq->flush_color != -1);
2539 if (pwq->nr_in_flight[flush_color]) {
2540 pwq->flush_color = flush_color;
2541 atomic_inc(&wq->nr_pwqs_to_flush);
2542 wait = true;
2546 if (work_color >= 0) {
2547 WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2548 pwq->work_color = work_color;
2551 spin_unlock_irq(&pool->lock);
2554 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
2555 complete(&wq->first_flusher->done);
2557 return wait;
2561 * flush_workqueue - ensure that any scheduled work has run to completion.
2562 * @wq: workqueue to flush
2564 * This function sleeps until all work items which were queued on entry
2565 * have finished execution, but it is not livelocked by new incoming ones.
2567 void flush_workqueue(struct workqueue_struct *wq)
2569 struct wq_flusher this_flusher = {
2570 .list = LIST_HEAD_INIT(this_flusher.list),
2571 .flush_color = -1,
2572 .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
2574 int next_color;
2576 lock_map_acquire(&wq->lockdep_map);
2577 lock_map_release(&wq->lockdep_map);
2579 mutex_lock(&wq->mutex);
2582 * Start-to-wait phase
2584 next_color = work_next_color(wq->work_color);
2586 if (next_color != wq->flush_color) {
2588 * Color space is not full. The current work_color
2589 * becomes our flush_color and work_color is advanced
2590 * by one.
2592 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
2593 this_flusher.flush_color = wq->work_color;
2594 wq->work_color = next_color;
2596 if (!wq->first_flusher) {
2597 /* no flush in progress, become the first flusher */
2598 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2600 wq->first_flusher = &this_flusher;
2602 if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
2603 wq->work_color)) {
2604 /* nothing to flush, done */
2605 wq->flush_color = next_color;
2606 wq->first_flusher = NULL;
2607 goto out_unlock;
2609 } else {
2610 /* wait in queue */
2611 WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
2612 list_add_tail(&this_flusher.list, &wq->flusher_queue);
2613 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2615 } else {
2617 * Oops, color space is full, wait on overflow queue.
2618 * The next flush completion will assign us
2619 * flush_color and transfer to flusher_queue.
2621 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2624 mutex_unlock(&wq->mutex);
2626 wait_for_completion(&this_flusher.done);
2629 * Wake-up-and-cascade phase
2631 * First flushers are responsible for cascading flushes and
2632 * handling overflow. Non-first flushers can simply return.
2634 if (wq->first_flusher != &this_flusher)
2635 return;
2637 mutex_lock(&wq->mutex);
2639 /* we might have raced, check again with mutex held */
2640 if (wq->first_flusher != &this_flusher)
2641 goto out_unlock;
2643 wq->first_flusher = NULL;
2645 WARN_ON_ONCE(!list_empty(&this_flusher.list));
2646 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
2648 while (true) {
2649 struct wq_flusher *next, *tmp;
2651 /* complete all the flushers sharing the current flush color */
2652 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2653 if (next->flush_color != wq->flush_color)
2654 break;
2655 list_del_init(&next->list);
2656 complete(&next->done);
2659 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
2660 wq->flush_color != work_next_color(wq->work_color));
2662 /* this flush_color is finished, advance by one */
2663 wq->flush_color = work_next_color(wq->flush_color);
2665 /* one color has been freed, handle overflow queue */
2666 if (!list_empty(&wq->flusher_overflow)) {
2668 * Assign the same color to all overflowed
2669 * flushers, advance work_color and append to
2670 * flusher_queue. This is the start-to-wait
2671 * phase for these overflowed flushers.
2673 list_for_each_entry(tmp, &wq->flusher_overflow, list)
2674 tmp->flush_color = wq->work_color;
2676 wq->work_color = work_next_color(wq->work_color);
2678 list_splice_tail_init(&wq->flusher_overflow,
2679 &wq->flusher_queue);
2680 flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
2683 if (list_empty(&wq->flusher_queue)) {
2684 WARN_ON_ONCE(wq->flush_color != wq->work_color);
2685 break;
2689 * Need to flush more colors. Make the next flusher
2690 * the new first flusher and arm pwqs.
2692 WARN_ON_ONCE(wq->flush_color == wq->work_color);
2693 WARN_ON_ONCE(wq->flush_color != next->flush_color);
2695 list_del_init(&next->list);
2696 wq->first_flusher = next;
2698 if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
2699 break;
2702 * Meh... this color is already done, clear first
2703 * flusher and repeat cascading.
2705 wq->first_flusher = NULL;
2708 out_unlock:
2709 mutex_unlock(&wq->mutex);
2711 EXPORT_SYMBOL_GPL(flush_workqueue);
2714 * drain_workqueue - drain a workqueue
2715 * @wq: workqueue to drain
2717 * Wait until the workqueue becomes empty. While draining is in progress,
2718 * only chain queueing is allowed. IOW, only currently pending or running
2719 * work items on @wq can queue further work items on it. @wq is flushed
2720 * repeatedly until it becomes empty. The number of flushing is detemined
2721 * by the depth of chaining and should be relatively short. Whine if it
2722 * takes too long.
2724 void drain_workqueue(struct workqueue_struct *wq)
2726 unsigned int flush_cnt = 0;
2727 struct pool_workqueue *pwq;
2730 * __queue_work() needs to test whether there are drainers, is much
2731 * hotter than drain_workqueue() and already looks at @wq->flags.
2732 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
2734 mutex_lock(&wq->mutex);
2735 if (!wq->nr_drainers++)
2736 wq->flags |= __WQ_DRAINING;
2737 mutex_unlock(&wq->mutex);
2738 reflush:
2739 flush_workqueue(wq);
2741 mutex_lock(&wq->mutex);
2743 for_each_pwq(pwq, wq) {
2744 bool drained;
2746 spin_lock_irq(&pwq->pool->lock);
2747 drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
2748 spin_unlock_irq(&pwq->pool->lock);
2750 if (drained)
2751 continue;
2753 if (++flush_cnt == 10 ||
2754 (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2755 pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
2756 wq->name, flush_cnt);
2758 mutex_unlock(&wq->mutex);
2759 goto reflush;
2762 if (!--wq->nr_drainers)
2763 wq->flags &= ~__WQ_DRAINING;
2764 mutex_unlock(&wq->mutex);
2766 EXPORT_SYMBOL_GPL(drain_workqueue);
2768 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2770 struct worker *worker = NULL;
2771 struct worker_pool *pool;
2772 struct pool_workqueue *pwq;
2774 might_sleep();
2776 local_irq_disable();
2777 pool = get_work_pool(work);
2778 if (!pool) {
2779 local_irq_enable();
2780 return false;
2783 spin_lock(&pool->lock);
2784 /* see the comment in try_to_grab_pending() with the same code */
2785 pwq = get_work_pwq(work);
2786 if (pwq) {
2787 if (unlikely(pwq->pool != pool))
2788 goto already_gone;
2789 } else {
2790 worker = find_worker_executing_work(pool, work);
2791 if (!worker)
2792 goto already_gone;
2793 pwq = worker->current_pwq;
2796 insert_wq_barrier(pwq, barr, work, worker);
2797 spin_unlock_irq(&pool->lock);
2800 * If @max_active is 1 or rescuer is in use, flushing another work
2801 * item on the same workqueue may lead to deadlock. Make sure the
2802 * flusher is not running on the same workqueue by verifying write
2803 * access.
2805 if (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)
2806 lock_map_acquire(&pwq->wq->lockdep_map);
2807 else
2808 lock_map_acquire_read(&pwq->wq->lockdep_map);
2809 lock_map_release(&pwq->wq->lockdep_map);
2811 return true;
2812 already_gone:
2813 spin_unlock_irq(&pool->lock);
2814 return false;
2818 * flush_work - wait for a work to finish executing the last queueing instance
2819 * @work: the work to flush
2821 * Wait until @work has finished execution. @work is guaranteed to be idle
2822 * on return if it hasn't been requeued since flush started.
2824 * RETURNS:
2825 * %true if flush_work() waited for the work to finish execution,
2826 * %false if it was already idle.
2828 bool flush_work(struct work_struct *work)
2830 struct wq_barrier barr;
2832 lock_map_acquire(&work->lockdep_map);
2833 lock_map_release(&work->lockdep_map);
2835 if (start_flush_work(work, &barr)) {
2836 wait_for_completion(&barr.done);
2837 destroy_work_on_stack(&barr.work);
2838 return true;
2839 } else {
2840 return false;
2843 EXPORT_SYMBOL_GPL(flush_work);
2845 static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2847 unsigned long flags;
2848 int ret;
2850 do {
2851 ret = try_to_grab_pending(work, is_dwork, &flags);
2853 * If someone else is canceling, wait for the same event it
2854 * would be waiting for before retrying.
2856 if (unlikely(ret == -ENOENT))
2857 flush_work(work);
2858 } while (unlikely(ret < 0));
2860 /* tell other tasks trying to grab @work to back off */
2861 mark_work_canceling(work);
2862 local_irq_restore(flags);
2864 flush_work(work);
2865 clear_work_data(work);
2866 return ret;
2870 * cancel_work_sync - cancel a work and wait for it to finish
2871 * @work: the work to cancel
2873 * Cancel @work and wait for its execution to finish. This function
2874 * can be used even if the work re-queues itself or migrates to
2875 * another workqueue. On return from this function, @work is
2876 * guaranteed to be not pending or executing on any CPU.
2878 * cancel_work_sync(&delayed_work->work) must not be used for
2879 * delayed_work's. Use cancel_delayed_work_sync() instead.
2881 * The caller must ensure that the workqueue on which @work was last
2882 * queued can't be destroyed before this function returns.
2884 * RETURNS:
2885 * %true if @work was pending, %false otherwise.
2887 bool cancel_work_sync(struct work_struct *work)
2889 return __cancel_work_timer(work, false);
2891 EXPORT_SYMBOL_GPL(cancel_work_sync);
2894 * flush_delayed_work - wait for a dwork to finish executing the last queueing
2895 * @dwork: the delayed work to flush
2897 * Delayed timer is cancelled and the pending work is queued for
2898 * immediate execution. Like flush_work(), this function only
2899 * considers the last queueing instance of @dwork.
2901 * RETURNS:
2902 * %true if flush_work() waited for the work to finish execution,
2903 * %false if it was already idle.
2905 bool flush_delayed_work(struct delayed_work *dwork)
2907 local_irq_disable();
2908 if (del_timer_sync(&dwork->timer))
2909 __queue_work(dwork->cpu, dwork->wq, &dwork->work);
2910 local_irq_enable();
2911 return flush_work(&dwork->work);
2913 EXPORT_SYMBOL(flush_delayed_work);
2916 * cancel_delayed_work - cancel a delayed work
2917 * @dwork: delayed_work to cancel
2919 * Kill off a pending delayed_work. Returns %true if @dwork was pending
2920 * and canceled; %false if wasn't pending. Note that the work callback
2921 * function may still be running on return, unless it returns %true and the
2922 * work doesn't re-arm itself. Explicitly flush or use
2923 * cancel_delayed_work_sync() to wait on it.
2925 * This function is safe to call from any context including IRQ handler.
2927 bool cancel_delayed_work(struct delayed_work *dwork)
2929 unsigned long flags;
2930 int ret;
2932 do {
2933 ret = try_to_grab_pending(&dwork->work, true, &flags);
2934 } while (unlikely(ret == -EAGAIN));
2936 if (unlikely(ret < 0))
2937 return false;
2939 set_work_pool_and_clear_pending(&dwork->work,
2940 get_work_pool_id(&dwork->work));
2941 local_irq_restore(flags);
2942 return ret;
2944 EXPORT_SYMBOL(cancel_delayed_work);
2947 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2948 * @dwork: the delayed work cancel
2950 * This is cancel_work_sync() for delayed works.
2952 * RETURNS:
2953 * %true if @dwork was pending, %false otherwise.
2955 bool cancel_delayed_work_sync(struct delayed_work *dwork)
2957 return __cancel_work_timer(&dwork->work, true);
2959 EXPORT_SYMBOL(cancel_delayed_work_sync);
2962 * schedule_on_each_cpu - execute a function synchronously on each online CPU
2963 * @func: the function to call
2965 * schedule_on_each_cpu() executes @func on each online CPU using the
2966 * system workqueue and blocks until all CPUs have completed.
2967 * schedule_on_each_cpu() is very slow.
2969 * RETURNS:
2970 * 0 on success, -errno on failure.
2972 int schedule_on_each_cpu(work_func_t func)
2974 int cpu;
2975 struct work_struct __percpu *works;
2977 works = alloc_percpu(struct work_struct);
2978 if (!works)
2979 return -ENOMEM;
2981 get_online_cpus();
2983 for_each_online_cpu(cpu) {
2984 struct work_struct *work = per_cpu_ptr(works, cpu);
2986 INIT_WORK(work, func);
2987 schedule_work_on(cpu, work);
2990 for_each_online_cpu(cpu)
2991 flush_work(per_cpu_ptr(works, cpu));
2993 put_online_cpus();
2994 free_percpu(works);
2995 return 0;
2999 * flush_scheduled_work - ensure that any scheduled work has run to completion.
3001 * Forces execution of the kernel-global workqueue and blocks until its
3002 * completion.
3004 * Think twice before calling this function! It's very easy to get into
3005 * trouble if you don't take great care. Either of the following situations
3006 * will lead to deadlock:
3008 * One of the work items currently on the workqueue needs to acquire
3009 * a lock held by your code or its caller.
3011 * Your code is running in the context of a work routine.
3013 * They will be detected by lockdep when they occur, but the first might not
3014 * occur very often. It depends on what work items are on the workqueue and
3015 * what locks they need, which you have no control over.
3017 * In most situations flushing the entire workqueue is overkill; you merely
3018 * need to know that a particular work item isn't queued and isn't running.
3019 * In such cases you should use cancel_delayed_work_sync() or
3020 * cancel_work_sync() instead.
3022 void flush_scheduled_work(void)
3024 flush_workqueue(system_wq);
3026 EXPORT_SYMBOL(flush_scheduled_work);
3029 * execute_in_process_context - reliably execute the routine with user context
3030 * @fn: the function to execute
3031 * @ew: guaranteed storage for the execute work structure (must
3032 * be available when the work executes)
3034 * Executes the function immediately if process context is available,
3035 * otherwise schedules the function for delayed execution.
3037 * Returns: 0 - function was executed
3038 * 1 - function was scheduled for execution
3040 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
3042 if (!in_interrupt()) {
3043 fn(&ew->work);
3044 return 0;
3047 INIT_WORK(&ew->work, fn);
3048 schedule_work(&ew->work);
3050 return 1;
3052 EXPORT_SYMBOL_GPL(execute_in_process_context);
3054 #ifdef CONFIG_SYSFS
3056 * Workqueues with WQ_SYSFS flag set is visible to userland via
3057 * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
3058 * following attributes.
3060 * per_cpu RO bool : whether the workqueue is per-cpu or unbound
3061 * max_active RW int : maximum number of in-flight work items
3063 * Unbound workqueues have the following extra attributes.
3065 * id RO int : the associated pool ID
3066 * nice RW int : nice value of the workers
3067 * cpumask RW mask : bitmask of allowed CPUs for the workers
3069 struct wq_device {
3070 struct workqueue_struct *wq;
3071 struct device dev;
3074 static struct workqueue_struct *dev_to_wq(struct device *dev)
3076 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
3078 return wq_dev->wq;
3081 static ssize_t wq_per_cpu_show(struct device *dev,
3082 struct device_attribute *attr, char *buf)
3084 struct workqueue_struct *wq = dev_to_wq(dev);
3086 return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
3089 static ssize_t wq_max_active_show(struct device *dev,
3090 struct device_attribute *attr, char *buf)
3092 struct workqueue_struct *wq = dev_to_wq(dev);
3094 return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
3097 static ssize_t wq_max_active_store(struct device *dev,
3098 struct device_attribute *attr,
3099 const char *buf, size_t count)
3101 struct workqueue_struct *wq = dev_to_wq(dev);
3102 int val;
3104 if (sscanf(buf, "%d", &val) != 1 || val <= 0)
3105 return -EINVAL;
3107 workqueue_set_max_active(wq, val);
3108 return count;
3111 static struct device_attribute wq_sysfs_attrs[] = {
3112 __ATTR(per_cpu, 0444, wq_per_cpu_show, NULL),
3113 __ATTR(max_active, 0644, wq_max_active_show, wq_max_active_store),
3114 __ATTR_NULL,
3117 static ssize_t wq_pool_id_show(struct device *dev,
3118 struct device_attribute *attr, char *buf)
3120 struct workqueue_struct *wq = dev_to_wq(dev);
3121 struct worker_pool *pool;
3122 int written;
3124 rcu_read_lock_sched();
3125 pool = first_pwq(wq)->pool;
3126 written = scnprintf(buf, PAGE_SIZE, "%d\n", pool->id);
3127 rcu_read_unlock_sched();
3129 return written;
3132 static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
3133 char *buf)
3135 struct workqueue_struct *wq = dev_to_wq(dev);
3136 int written;
3138 mutex_lock(&wq->mutex);
3139 written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
3140 mutex_unlock(&wq->mutex);
3142 return written;
3145 /* prepare workqueue_attrs for sysfs store operations */
3146 static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
3148 struct workqueue_attrs *attrs;
3150 attrs = alloc_workqueue_attrs(GFP_KERNEL);
3151 if (!attrs)
3152 return NULL;
3154 mutex_lock(&wq->mutex);
3155 copy_workqueue_attrs(attrs, wq->unbound_attrs);
3156 mutex_unlock(&wq->mutex);
3157 return attrs;
3160 static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
3161 const char *buf, size_t count)
3163 struct workqueue_struct *wq = dev_to_wq(dev);
3164 struct workqueue_attrs *attrs;
3165 int ret;
3167 attrs = wq_sysfs_prep_attrs(wq);
3168 if (!attrs)
3169 return -ENOMEM;
3171 if (sscanf(buf, "%d", &attrs->nice) == 1 &&
3172 attrs->nice >= -20 && attrs->nice <= 19)
3173 ret = apply_workqueue_attrs(wq, attrs);
3174 else
3175 ret = -EINVAL;
3177 free_workqueue_attrs(attrs);
3178 return ret ?: count;
3181 static ssize_t wq_cpumask_show(struct device *dev,
3182 struct device_attribute *attr, char *buf)
3184 struct workqueue_struct *wq = dev_to_wq(dev);
3185 int written;
3187 mutex_lock(&wq->mutex);
3188 written = cpumask_scnprintf(buf, PAGE_SIZE, wq->unbound_attrs->cpumask);
3189 mutex_unlock(&wq->mutex);
3191 written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
3192 return written;
3195 static ssize_t wq_cpumask_store(struct device *dev,
3196 struct device_attribute *attr,
3197 const char *buf, size_t count)
3199 struct workqueue_struct *wq = dev_to_wq(dev);
3200 struct workqueue_attrs *attrs;
3201 int ret;
3203 attrs = wq_sysfs_prep_attrs(wq);
3204 if (!attrs)
3205 return -ENOMEM;
3207 ret = cpumask_parse(buf, attrs->cpumask);
3208 if (!ret)
3209 ret = apply_workqueue_attrs(wq, attrs);
3211 free_workqueue_attrs(attrs);
3212 return ret ?: count;
3215 static struct device_attribute wq_sysfs_unbound_attrs[] = {
3216 __ATTR(pool_id, 0444, wq_pool_id_show, NULL),
3217 __ATTR(nice, 0644, wq_nice_show, wq_nice_store),
3218 __ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
3219 __ATTR_NULL,
3222 static struct bus_type wq_subsys = {
3223 .name = "workqueue",
3224 .dev_attrs = wq_sysfs_attrs,
3227 static int __init wq_sysfs_init(void)
3229 return subsys_virtual_register(&wq_subsys, NULL);
3231 core_initcall(wq_sysfs_init);
3233 static void wq_device_release(struct device *dev)
3235 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
3237 kfree(wq_dev);
3241 * workqueue_sysfs_register - make a workqueue visible in sysfs
3242 * @wq: the workqueue to register
3244 * Expose @wq in sysfs under /sys/bus/workqueue/devices.
3245 * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
3246 * which is the preferred method.
3248 * Workqueue user should use this function directly iff it wants to apply
3249 * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
3250 * apply_workqueue_attrs() may race against userland updating the
3251 * attributes.
3253 * Returns 0 on success, -errno on failure.
3255 int workqueue_sysfs_register(struct workqueue_struct *wq)
3257 struct wq_device *wq_dev;
3258 int ret;
3261 * Adjusting max_active or creating new pwqs by applyting
3262 * attributes breaks ordering guarantee. Disallow exposing ordered
3263 * workqueues.
3265 if (WARN_ON(wq->flags & __WQ_ORDERED))
3266 return -EINVAL;
3268 wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
3269 if (!wq_dev)
3270 return -ENOMEM;
3272 wq_dev->wq = wq;
3273 wq_dev->dev.bus = &wq_subsys;
3274 wq_dev->dev.init_name = wq->name;
3275 wq_dev->dev.release = wq_device_release;
3278 * unbound_attrs are created separately. Suppress uevent until
3279 * everything is ready.
3281 dev_set_uevent_suppress(&wq_dev->dev, true);
3283 ret = device_register(&wq_dev->dev);
3284 if (ret) {
3285 kfree(wq_dev);
3286 wq->wq_dev = NULL;
3287 return ret;
3290 if (wq->flags & WQ_UNBOUND) {
3291 struct device_attribute *attr;
3293 for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
3294 ret = device_create_file(&wq_dev->dev, attr);
3295 if (ret) {
3296 device_unregister(&wq_dev->dev);
3297 wq->wq_dev = NULL;
3298 return ret;
3303 kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
3304 return 0;
3308 * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
3309 * @wq: the workqueue to unregister
3311 * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
3313 static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
3315 struct wq_device *wq_dev = wq->wq_dev;
3317 if (!wq->wq_dev)
3318 return;
3320 wq->wq_dev = NULL;
3321 device_unregister(&wq_dev->dev);
3323 #else /* CONFIG_SYSFS */
3324 static void workqueue_sysfs_unregister(struct workqueue_struct *wq) { }
3325 #endif /* CONFIG_SYSFS */
3328 * free_workqueue_attrs - free a workqueue_attrs
3329 * @attrs: workqueue_attrs to free
3331 * Undo alloc_workqueue_attrs().
3333 void free_workqueue_attrs(struct workqueue_attrs *attrs)
3335 if (attrs) {
3336 free_cpumask_var(attrs->cpumask);
3337 kfree(attrs);
3342 * alloc_workqueue_attrs - allocate a workqueue_attrs
3343 * @gfp_mask: allocation mask to use
3345 * Allocate a new workqueue_attrs, initialize with default settings and
3346 * return it. Returns NULL on failure.
3348 struct workqueue_attrs *alloc_workqueue_attrs(gfp_t gfp_mask)
3350 struct workqueue_attrs *attrs;
3352 attrs = kzalloc(sizeof(*attrs), gfp_mask);
3353 if (!attrs)
3354 goto fail;
3355 if (!alloc_cpumask_var(&attrs->cpumask, gfp_mask))
3356 goto fail;
3358 cpumask_copy(attrs->cpumask, cpu_possible_mask);
3359 return attrs;
3360 fail:
3361 free_workqueue_attrs(attrs);
3362 return NULL;
3365 static void copy_workqueue_attrs(struct workqueue_attrs *to,
3366 const struct workqueue_attrs *from)
3368 to->nice = from->nice;
3369 cpumask_copy(to->cpumask, from->cpumask);
3372 /* hash value of the content of @attr */
3373 static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
3375 u32 hash = 0;
3377 hash = jhash_1word(attrs->nice, hash);
3378 hash = jhash(cpumask_bits(attrs->cpumask),
3379 BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
3380 return hash;
3383 /* content equality test */
3384 static bool wqattrs_equal(const struct workqueue_attrs *a,
3385 const struct workqueue_attrs *b)
3387 if (a->nice != b->nice)
3388 return false;
3389 if (!cpumask_equal(a->cpumask, b->cpumask))
3390 return false;
3391 return true;
3395 * init_worker_pool - initialize a newly zalloc'd worker_pool
3396 * @pool: worker_pool to initialize
3398 * Initiailize a newly zalloc'd @pool. It also allocates @pool->attrs.
3399 * Returns 0 on success, -errno on failure. Even on failure, all fields
3400 * inside @pool proper are initialized and put_unbound_pool() can be called
3401 * on @pool safely to release it.
3403 static int init_worker_pool(struct worker_pool *pool)
3405 spin_lock_init(&pool->lock);
3406 pool->id = -1;
3407 pool->cpu = -1;
3408 pool->node = NUMA_NO_NODE;
3409 pool->flags |= POOL_DISASSOCIATED;
3410 INIT_LIST_HEAD(&pool->worklist);
3411 INIT_LIST_HEAD(&pool->idle_list);
3412 hash_init(pool->busy_hash);
3414 init_timer_deferrable(&pool->idle_timer);
3415 pool->idle_timer.function = idle_worker_timeout;
3416 pool->idle_timer.data = (unsigned long)pool;
3418 setup_timer(&pool->mayday_timer, pool_mayday_timeout,
3419 (unsigned long)pool);
3421 mutex_init(&pool->manager_arb);
3422 mutex_init(&pool->manager_mutex);
3423 idr_init(&pool->worker_idr);
3425 INIT_HLIST_NODE(&pool->hash_node);
3426 pool->refcnt = 1;
3428 /* shouldn't fail above this point */
3429 pool->attrs = alloc_workqueue_attrs(GFP_KERNEL);
3430 if (!pool->attrs)
3431 return -ENOMEM;
3432 return 0;
3435 static void rcu_free_pool(struct rcu_head *rcu)
3437 struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
3439 idr_destroy(&pool->worker_idr);
3440 free_workqueue_attrs(pool->attrs);
3441 kfree(pool);
3445 * put_unbound_pool - put a worker_pool
3446 * @pool: worker_pool to put
3448 * Put @pool. If its refcnt reaches zero, it gets destroyed in sched-RCU
3449 * safe manner. get_unbound_pool() calls this function on its failure path
3450 * and this function should be able to release pools which went through,
3451 * successfully or not, init_worker_pool().
3453 * Should be called with wq_pool_mutex held.
3455 static void put_unbound_pool(struct worker_pool *pool)
3457 struct worker *worker;
3459 lockdep_assert_held(&wq_pool_mutex);
3461 if (--pool->refcnt)
3462 return;
3464 /* sanity checks */
3465 if (WARN_ON(!(pool->flags & POOL_DISASSOCIATED)) ||
3466 WARN_ON(!list_empty(&pool->worklist)))
3467 return;
3469 /* release id and unhash */
3470 if (pool->id >= 0)
3471 idr_remove(&worker_pool_idr, pool->id);
3472 hash_del(&pool->hash_node);
3475 * Become the manager and destroy all workers. Grabbing
3476 * manager_arb prevents @pool's workers from blocking on
3477 * manager_mutex.
3479 mutex_lock(&pool->manager_arb);
3480 mutex_lock(&pool->manager_mutex);
3481 spin_lock_irq(&pool->lock);
3483 while ((worker = first_worker(pool)))
3484 destroy_worker(worker);
3485 WARN_ON(pool->nr_workers || pool->nr_idle);
3487 spin_unlock_irq(&pool->lock);
3488 mutex_unlock(&pool->manager_mutex);
3489 mutex_unlock(&pool->manager_arb);
3491 /* shut down the timers */
3492 del_timer_sync(&pool->idle_timer);
3493 del_timer_sync(&pool->mayday_timer);
3495 /* sched-RCU protected to allow dereferences from get_work_pool() */
3496 call_rcu_sched(&pool->rcu, rcu_free_pool);
3500 * get_unbound_pool - get a worker_pool with the specified attributes
3501 * @attrs: the attributes of the worker_pool to get
3503 * Obtain a worker_pool which has the same attributes as @attrs, bump the
3504 * reference count and return it. If there already is a matching
3505 * worker_pool, it will be used; otherwise, this function attempts to
3506 * create a new one. On failure, returns NULL.
3508 * Should be called with wq_pool_mutex held.
3510 static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
3512 u32 hash = wqattrs_hash(attrs);
3513 struct worker_pool *pool;
3514 int node;
3516 lockdep_assert_held(&wq_pool_mutex);
3518 /* do we already have a matching pool? */
3519 hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
3520 if (wqattrs_equal(pool->attrs, attrs)) {
3521 pool->refcnt++;
3522 goto out_unlock;
3526 /* nope, create a new one */
3527 pool = kzalloc(sizeof(*pool), GFP_KERNEL);
3528 if (!pool || init_worker_pool(pool) < 0)
3529 goto fail;
3531 if (workqueue_freezing)
3532 pool->flags |= POOL_FREEZING;
3534 lockdep_set_subclass(&pool->lock, 1); /* see put_pwq() */
3535 copy_workqueue_attrs(pool->attrs, attrs);
3537 /* if cpumask is contained inside a NUMA node, we belong to that node */
3538 if (wq_numa_enabled) {
3539 for_each_node(node) {
3540 if (cpumask_subset(pool->attrs->cpumask,
3541 wq_numa_possible_cpumask[node])) {
3542 pool->node = node;
3543 break;
3548 if (worker_pool_assign_id(pool) < 0)
3549 goto fail;
3551 /* create and start the initial worker */
3552 if (create_and_start_worker(pool) < 0)
3553 goto fail;
3555 /* install */
3556 hash_add(unbound_pool_hash, &pool->hash_node, hash);
3557 out_unlock:
3558 return pool;
3559 fail:
3560 if (pool)
3561 put_unbound_pool(pool);
3562 return NULL;
3565 static void rcu_free_pwq(struct rcu_head *rcu)
3567 kmem_cache_free(pwq_cache,
3568 container_of(rcu, struct pool_workqueue, rcu));
3572 * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
3573 * and needs to be destroyed.
3575 static void pwq_unbound_release_workfn(struct work_struct *work)
3577 struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
3578 unbound_release_work);
3579 struct workqueue_struct *wq = pwq->wq;
3580 struct worker_pool *pool = pwq->pool;
3581 bool is_last;
3583 if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
3584 return;
3587 * Unlink @pwq. Synchronization against wq->mutex isn't strictly
3588 * necessary on release but do it anyway. It's easier to verify
3589 * and consistent with the linking path.
3591 mutex_lock(&wq->mutex);
3592 list_del_rcu(&pwq->pwqs_node);
3593 is_last = list_empty(&wq->pwqs);
3594 mutex_unlock(&wq->mutex);
3596 mutex_lock(&wq_pool_mutex);
3597 put_unbound_pool(pool);
3598 mutex_unlock(&wq_pool_mutex);
3600 call_rcu_sched(&pwq->rcu, rcu_free_pwq);
3603 * If we're the last pwq going away, @wq is already dead and no one
3604 * is gonna access it anymore. Free it.
3606 if (is_last) {
3607 free_workqueue_attrs(wq->unbound_attrs);
3608 kfree(wq);
3613 * pwq_adjust_max_active - update a pwq's max_active to the current setting
3614 * @pwq: target pool_workqueue
3616 * If @pwq isn't freezing, set @pwq->max_active to the associated
3617 * workqueue's saved_max_active and activate delayed work items
3618 * accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
3620 static void pwq_adjust_max_active(struct pool_workqueue *pwq)
3622 struct workqueue_struct *wq = pwq->wq;
3623 bool freezable = wq->flags & WQ_FREEZABLE;
3625 /* for @wq->saved_max_active */
3626 lockdep_assert_held(&wq->mutex);
3628 /* fast exit for non-freezable wqs */
3629 if (!freezable && pwq->max_active == wq->saved_max_active)
3630 return;
3632 spin_lock_irq(&pwq->pool->lock);
3634 if (!freezable || !(pwq->pool->flags & POOL_FREEZING)) {
3635 pwq->max_active = wq->saved_max_active;
3637 while (!list_empty(&pwq->delayed_works) &&
3638 pwq->nr_active < pwq->max_active)
3639 pwq_activate_first_delayed(pwq);
3642 * Need to kick a worker after thawed or an unbound wq's
3643 * max_active is bumped. It's a slow path. Do it always.
3645 wake_up_worker(pwq->pool);
3646 } else {
3647 pwq->max_active = 0;
3650 spin_unlock_irq(&pwq->pool->lock);
3653 /* initialize newly alloced @pwq which is associated with @wq and @pool */
3654 static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
3655 struct worker_pool *pool)
3657 BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3659 memset(pwq, 0, sizeof(*pwq));
3661 pwq->pool = pool;
3662 pwq->wq = wq;
3663 pwq->flush_color = -1;
3664 pwq->refcnt = 1;
3665 INIT_LIST_HEAD(&pwq->delayed_works);
3666 INIT_LIST_HEAD(&pwq->pwqs_node);
3667 INIT_LIST_HEAD(&pwq->mayday_node);
3668 INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
3671 /* sync @pwq with the current state of its associated wq and link it */
3672 static void link_pwq(struct pool_workqueue *pwq)
3674 struct workqueue_struct *wq = pwq->wq;
3676 lockdep_assert_held(&wq->mutex);
3678 /* may be called multiple times, ignore if already linked */
3679 if (!list_empty(&pwq->pwqs_node))
3680 return;
3683 * Set the matching work_color. This is synchronized with
3684 * wq->mutex to avoid confusing flush_workqueue().
3686 pwq->work_color = wq->work_color;
3688 /* sync max_active to the current setting */
3689 pwq_adjust_max_active(pwq);
3691 /* link in @pwq */
3692 list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
3695 /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
3696 static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
3697 const struct workqueue_attrs *attrs)
3699 struct worker_pool *pool;
3700 struct pool_workqueue *pwq;
3702 lockdep_assert_held(&wq_pool_mutex);
3704 pool = get_unbound_pool(attrs);
3705 if (!pool)
3706 return NULL;
3708 pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
3709 if (!pwq) {
3710 put_unbound_pool(pool);
3711 return NULL;
3714 init_pwq(pwq, wq, pool);
3715 return pwq;
3718 /* undo alloc_unbound_pwq(), used only in the error path */
3719 static void free_unbound_pwq(struct pool_workqueue *pwq)
3721 lockdep_assert_held(&wq_pool_mutex);
3723 if (pwq) {
3724 put_unbound_pool(pwq->pool);
3725 kfree(pwq);
3730 * wq_calc_node_mask - calculate a wq_attrs' cpumask for the specified node
3731 * @attrs: the wq_attrs of interest
3732 * @node: the target NUMA node
3733 * @cpu_going_down: if >= 0, the CPU to consider as offline
3734 * @cpumask: outarg, the resulting cpumask
3736 * Calculate the cpumask a workqueue with @attrs should use on @node. If
3737 * @cpu_going_down is >= 0, that cpu is considered offline during
3738 * calculation. The result is stored in @cpumask. This function returns
3739 * %true if the resulting @cpumask is different from @attrs->cpumask,
3740 * %false if equal.
3742 * If NUMA affinity is not enabled, @attrs->cpumask is always used. If
3743 * enabled and @node has online CPUs requested by @attrs, the returned
3744 * cpumask is the intersection of the possible CPUs of @node and
3745 * @attrs->cpumask.
3747 * The caller is responsible for ensuring that the cpumask of @node stays
3748 * stable.
3750 static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
3751 int cpu_going_down, cpumask_t *cpumask)
3753 if (!wq_numa_enabled)
3754 goto use_dfl;
3756 /* does @node have any online CPUs @attrs wants? */
3757 cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
3758 if (cpu_going_down >= 0)
3759 cpumask_clear_cpu(cpu_going_down, cpumask);
3761 if (cpumask_empty(cpumask))
3762 goto use_dfl;
3764 /* yeap, return possible CPUs in @node that @attrs wants */
3765 cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
3766 return !cpumask_equal(cpumask, attrs->cpumask);
3768 use_dfl:
3769 cpumask_copy(cpumask, attrs->cpumask);
3770 return false;
3773 /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
3774 static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
3775 int node,
3776 struct pool_workqueue *pwq)
3778 struct pool_workqueue *old_pwq;
3780 lockdep_assert_held(&wq->mutex);
3782 /* link_pwq() can handle duplicate calls */
3783 link_pwq(pwq);
3785 old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
3786 rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
3787 return old_pwq;
3791 * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
3792 * @wq: the target workqueue
3793 * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
3795 * Apply @attrs to an unbound workqueue @wq. Unless disabled, on NUMA
3796 * machines, this function maps a separate pwq to each NUMA node with
3797 * possibles CPUs in @attrs->cpumask so that work items are affine to the
3798 * NUMA node it was issued on. Older pwqs are released as in-flight work
3799 * items finish. Note that a work item which repeatedly requeues itself
3800 * back-to-back will stay on its current pwq.
3802 * Performs GFP_KERNEL allocations. Returns 0 on success and -errno on
3803 * failure.
3805 int apply_workqueue_attrs(struct workqueue_struct *wq,
3806 const struct workqueue_attrs *attrs)
3808 struct workqueue_attrs *new_attrs, *tmp_attrs;
3809 struct pool_workqueue **pwq_tbl, *dfl_pwq;
3810 int node, ret;
3812 /* only unbound workqueues can change attributes */
3813 if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
3814 return -EINVAL;
3816 /* creating multiple pwqs breaks ordering guarantee */
3817 if (WARN_ON((wq->flags & __WQ_ORDERED) && !list_empty(&wq->pwqs)))
3818 return -EINVAL;
3820 pwq_tbl = kzalloc(wq_numa_tbl_len * sizeof(pwq_tbl[0]), GFP_KERNEL);
3821 new_attrs = alloc_workqueue_attrs(GFP_KERNEL);
3822 tmp_attrs = alloc_workqueue_attrs(GFP_KERNEL);
3823 if (!pwq_tbl || !new_attrs || !tmp_attrs)
3824 goto enomem;
3826 /* make a copy of @attrs and sanitize it */
3827 copy_workqueue_attrs(new_attrs, attrs);
3828 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
3831 * We may create multiple pwqs with differing cpumasks. Make a
3832 * copy of @new_attrs which will be modified and used to obtain
3833 * pools.
3835 copy_workqueue_attrs(tmp_attrs, new_attrs);
3838 * CPUs should stay stable across pwq creations and installations.
3839 * Pin CPUs, determine the target cpumask for each node and create
3840 * pwqs accordingly.
3842 get_online_cpus();
3844 mutex_lock(&wq_pool_mutex);
3847 * If something goes wrong during CPU up/down, we'll fall back to
3848 * the default pwq covering whole @attrs->cpumask. Always create
3849 * it even if we don't use it immediately.
3851 dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
3852 if (!dfl_pwq)
3853 goto enomem_pwq;
3855 for_each_node(node) {
3856 if (wq_calc_node_cpumask(attrs, node, -1, tmp_attrs->cpumask)) {
3857 pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
3858 if (!pwq_tbl[node])
3859 goto enomem_pwq;
3860 } else {
3861 dfl_pwq->refcnt++;
3862 pwq_tbl[node] = dfl_pwq;
3866 mutex_unlock(&wq_pool_mutex);
3868 /* all pwqs have been created successfully, let's install'em */
3869 mutex_lock(&wq->mutex);
3871 copy_workqueue_attrs(wq->unbound_attrs, new_attrs);
3873 /* save the previous pwq and install the new one */
3874 for_each_node(node)
3875 pwq_tbl[node] = numa_pwq_tbl_install(wq, node, pwq_tbl[node]);
3877 /* @dfl_pwq might not have been used, ensure it's linked */
3878 link_pwq(dfl_pwq);
3879 swap(wq->dfl_pwq, dfl_pwq);
3881 mutex_unlock(&wq->mutex);
3883 /* put the old pwqs */
3884 for_each_node(node)
3885 put_pwq_unlocked(pwq_tbl[node]);
3886 put_pwq_unlocked(dfl_pwq);
3888 put_online_cpus();
3889 ret = 0;
3890 /* fall through */
3891 out_free:
3892 free_workqueue_attrs(tmp_attrs);
3893 free_workqueue_attrs(new_attrs);
3894 kfree(pwq_tbl);
3895 return ret;
3897 enomem_pwq:
3898 free_unbound_pwq(dfl_pwq);
3899 for_each_node(node)
3900 if (pwq_tbl && pwq_tbl[node] != dfl_pwq)
3901 free_unbound_pwq(pwq_tbl[node]);
3902 mutex_unlock(&wq_pool_mutex);
3903 put_online_cpus();
3904 enomem:
3905 ret = -ENOMEM;
3906 goto out_free;
3910 * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
3911 * @wq: the target workqueue
3912 * @cpu: the CPU coming up or going down
3913 * @online: whether @cpu is coming up or going down
3915 * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
3916 * %CPU_DOWN_FAILED. @cpu is being hot[un]plugged, update NUMA affinity of
3917 * @wq accordingly.
3919 * If NUMA affinity can't be adjusted due to memory allocation failure, it
3920 * falls back to @wq->dfl_pwq which may not be optimal but is always
3921 * correct.
3923 * Note that when the last allowed CPU of a NUMA node goes offline for a
3924 * workqueue with a cpumask spanning multiple nodes, the workers which were
3925 * already executing the work items for the workqueue will lose their CPU
3926 * affinity and may execute on any CPU. This is similar to how per-cpu
3927 * workqueues behave on CPU_DOWN. If a workqueue user wants strict
3928 * affinity, it's the user's responsibility to flush the work item from
3929 * CPU_DOWN_PREPARE.
3931 static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
3932 bool online)
3934 int node = cpu_to_node(cpu);
3935 int cpu_off = online ? -1 : cpu;
3936 struct pool_workqueue *old_pwq = NULL, *pwq;
3937 struct workqueue_attrs *target_attrs;
3938 cpumask_t *cpumask;
3940 lockdep_assert_held(&wq_pool_mutex);
3942 if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND))
3943 return;
3946 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
3947 * Let's use a preallocated one. The following buf is protected by
3948 * CPU hotplug exclusion.
3950 target_attrs = wq_update_unbound_numa_attrs_buf;
3951 cpumask = target_attrs->cpumask;
3953 mutex_lock(&wq->mutex);
3955 copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
3956 pwq = unbound_pwq_by_node(wq, node);
3959 * Let's determine what needs to be done. If the target cpumask is
3960 * different from wq's, we need to compare it to @pwq's and create
3961 * a new one if they don't match. If the target cpumask equals
3962 * wq's, the default pwq should be used. If @pwq is already the
3963 * default one, nothing to do; otherwise, install the default one.
3965 if (wq_calc_node_cpumask(wq->unbound_attrs, node, cpu_off, cpumask)) {
3966 if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
3967 goto out_unlock;
3968 } else {
3969 if (pwq == wq->dfl_pwq)
3970 goto out_unlock;
3971 else
3972 goto use_dfl_pwq;
3975 mutex_unlock(&wq->mutex);
3977 /* create a new pwq */
3978 pwq = alloc_unbound_pwq(wq, target_attrs);
3979 if (!pwq) {
3980 pr_warning("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
3981 wq->name);
3982 goto out_unlock;
3986 * Install the new pwq. As this function is called only from CPU
3987 * hotplug callbacks and applying a new attrs is wrapped with
3988 * get/put_online_cpus(), @wq->unbound_attrs couldn't have changed
3989 * inbetween.
3991 mutex_lock(&wq->mutex);
3992 old_pwq = numa_pwq_tbl_install(wq, node, pwq);
3993 goto out_unlock;
3995 use_dfl_pwq:
3996 spin_lock_irq(&wq->dfl_pwq->pool->lock);
3997 get_pwq(wq->dfl_pwq);
3998 spin_unlock_irq(&wq->dfl_pwq->pool->lock);
3999 old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
4000 out_unlock:
4001 mutex_unlock(&wq->mutex);
4002 put_pwq_unlocked(old_pwq);
4005 static int alloc_and_link_pwqs(struct workqueue_struct *wq)
4007 bool highpri = wq->flags & WQ_HIGHPRI;
4008 int cpu;
4010 if (!(wq->flags & WQ_UNBOUND)) {
4011 wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
4012 if (!wq->cpu_pwqs)
4013 return -ENOMEM;
4015 for_each_possible_cpu(cpu) {
4016 struct pool_workqueue *pwq =
4017 per_cpu_ptr(wq->cpu_pwqs, cpu);
4018 struct worker_pool *cpu_pools =
4019 per_cpu(cpu_worker_pools, cpu);
4021 init_pwq(pwq, wq, &cpu_pools[highpri]);
4023 mutex_lock(&wq->mutex);
4024 link_pwq(pwq);
4025 mutex_unlock(&wq->mutex);
4027 return 0;
4028 } else {
4029 return apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
4033 static int wq_clamp_max_active(int max_active, unsigned int flags,
4034 const char *name)
4036 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
4038 if (max_active < 1 || max_active > lim)
4039 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
4040 max_active, name, 1, lim);
4042 return clamp_val(max_active, 1, lim);
4045 struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
4046 unsigned int flags,
4047 int max_active,
4048 struct lock_class_key *key,
4049 const char *lock_name, ...)
4051 size_t tbl_size = 0;
4052 va_list args;
4053 struct workqueue_struct *wq;
4054 struct pool_workqueue *pwq;
4056 /* allocate wq and format name */
4057 if (flags & WQ_UNBOUND)
4058 tbl_size = wq_numa_tbl_len * sizeof(wq->numa_pwq_tbl[0]);
4060 wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
4061 if (!wq)
4062 return NULL;
4064 if (flags & WQ_UNBOUND) {
4065 wq->unbound_attrs = alloc_workqueue_attrs(GFP_KERNEL);
4066 if (!wq->unbound_attrs)
4067 goto err_free_wq;
4070 va_start(args, lock_name);
4071 vsnprintf(wq->name, sizeof(wq->name), fmt, args);
4072 va_end(args);
4074 max_active = max_active ?: WQ_DFL_ACTIVE;
4075 max_active = wq_clamp_max_active(max_active, flags, wq->name);
4077 /* init wq */
4078 wq->flags = flags;
4079 wq->saved_max_active = max_active;
4080 mutex_init(&wq->mutex);
4081 atomic_set(&wq->nr_pwqs_to_flush, 0);
4082 INIT_LIST_HEAD(&wq->pwqs);
4083 INIT_LIST_HEAD(&wq->flusher_queue);
4084 INIT_LIST_HEAD(&wq->flusher_overflow);
4085 INIT_LIST_HEAD(&wq->maydays);
4087 lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
4088 INIT_LIST_HEAD(&wq->list);
4090 if (alloc_and_link_pwqs(wq) < 0)
4091 goto err_free_wq;
4094 * Workqueues which may be used during memory reclaim should
4095 * have a rescuer to guarantee forward progress.
4097 if (flags & WQ_MEM_RECLAIM) {
4098 struct worker *rescuer;
4100 rescuer = alloc_worker();
4101 if (!rescuer)
4102 goto err_destroy;
4104 rescuer->rescue_wq = wq;
4105 rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
4106 wq->name);
4107 if (IS_ERR(rescuer->task)) {
4108 kfree(rescuer);
4109 goto err_destroy;
4112 wq->rescuer = rescuer;
4113 rescuer->task->flags |= PF_NO_SETAFFINITY;
4114 wake_up_process(rescuer->task);
4117 if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
4118 goto err_destroy;
4121 * wq_pool_mutex protects global freeze state and workqueues list.
4122 * Grab it, adjust max_active and add the new @wq to workqueues
4123 * list.
4125 mutex_lock(&wq_pool_mutex);
4127 mutex_lock(&wq->mutex);
4128 for_each_pwq(pwq, wq)
4129 pwq_adjust_max_active(pwq);
4130 mutex_unlock(&wq->mutex);
4132 list_add(&wq->list, &workqueues);
4134 mutex_unlock(&wq_pool_mutex);
4136 return wq;
4138 err_free_wq:
4139 free_workqueue_attrs(wq->unbound_attrs);
4140 kfree(wq);
4141 return NULL;
4142 err_destroy:
4143 destroy_workqueue(wq);
4144 return NULL;
4146 EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
4149 * destroy_workqueue - safely terminate a workqueue
4150 * @wq: target workqueue
4152 * Safely destroy a workqueue. All work currently pending will be done first.
4154 void destroy_workqueue(struct workqueue_struct *wq)
4156 struct pool_workqueue *pwq;
4157 int node;
4159 /* drain it before proceeding with destruction */
4160 drain_workqueue(wq);
4162 /* sanity checks */
4163 mutex_lock(&wq->mutex);
4164 for_each_pwq(pwq, wq) {
4165 int i;
4167 for (i = 0; i < WORK_NR_COLORS; i++) {
4168 if (WARN_ON(pwq->nr_in_flight[i])) {
4169 mutex_unlock(&wq->mutex);
4170 return;
4174 if (WARN_ON(pwq->refcnt > 1) ||
4175 WARN_ON(pwq->nr_active) ||
4176 WARN_ON(!list_empty(&pwq->delayed_works))) {
4177 mutex_unlock(&wq->mutex);
4178 return;
4181 mutex_unlock(&wq->mutex);
4184 * wq list is used to freeze wq, remove from list after
4185 * flushing is complete in case freeze races us.
4187 mutex_lock(&wq_pool_mutex);
4188 list_del_init(&wq->list);
4189 mutex_unlock(&wq_pool_mutex);
4191 workqueue_sysfs_unregister(wq);
4193 if (wq->rescuer) {
4194 kthread_stop(wq->rescuer->task);
4195 kfree(wq->rescuer);
4196 wq->rescuer = NULL;
4199 if (!(wq->flags & WQ_UNBOUND)) {
4201 * The base ref is never dropped on per-cpu pwqs. Directly
4202 * free the pwqs and wq.
4204 free_percpu(wq->cpu_pwqs);
4205 kfree(wq);
4206 } else {
4208 * We're the sole accessor of @wq at this point. Directly
4209 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
4210 * @wq will be freed when the last pwq is released.
4212 for_each_node(node) {
4213 pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
4214 RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
4215 put_pwq_unlocked(pwq);
4219 * Put dfl_pwq. @wq may be freed any time after dfl_pwq is
4220 * put. Don't access it afterwards.
4222 pwq = wq->dfl_pwq;
4223 wq->dfl_pwq = NULL;
4224 put_pwq_unlocked(pwq);
4227 EXPORT_SYMBOL_GPL(destroy_workqueue);
4230 * workqueue_set_max_active - adjust max_active of a workqueue
4231 * @wq: target workqueue
4232 * @max_active: new max_active value.
4234 * Set max_active of @wq to @max_active.
4236 * CONTEXT:
4237 * Don't call from IRQ context.
4239 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4241 struct pool_workqueue *pwq;
4243 /* disallow meddling with max_active for ordered workqueues */
4244 if (WARN_ON(wq->flags & __WQ_ORDERED))
4245 return;
4247 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4249 mutex_lock(&wq->mutex);
4251 wq->saved_max_active = max_active;
4253 for_each_pwq(pwq, wq)
4254 pwq_adjust_max_active(pwq);
4256 mutex_unlock(&wq->mutex);
4258 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4261 * current_is_workqueue_rescuer - is %current workqueue rescuer?
4263 * Determine whether %current is a workqueue rescuer. Can be used from
4264 * work functions to determine whether it's being run off the rescuer task.
4266 bool current_is_workqueue_rescuer(void)
4268 struct worker *worker = current_wq_worker();
4270 return worker && worker->rescue_wq;
4274 * workqueue_congested - test whether a workqueue is congested
4275 * @cpu: CPU in question
4276 * @wq: target workqueue
4278 * Test whether @wq's cpu workqueue for @cpu is congested. There is
4279 * no synchronization around this function and the test result is
4280 * unreliable and only useful as advisory hints or for debugging.
4282 * RETURNS:
4283 * %true if congested, %false otherwise.
4285 bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4287 struct pool_workqueue *pwq;
4288 bool ret;
4290 rcu_read_lock_sched();
4292 if (!(wq->flags & WQ_UNBOUND))
4293 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
4294 else
4295 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4297 ret = !list_empty(&pwq->delayed_works);
4298 rcu_read_unlock_sched();
4300 return ret;
4302 EXPORT_SYMBOL_GPL(workqueue_congested);
4305 * work_busy - test whether a work is currently pending or running
4306 * @work: the work to be tested
4308 * Test whether @work is currently pending or running. There is no
4309 * synchronization around this function and the test result is
4310 * unreliable and only useful as advisory hints or for debugging.
4312 * RETURNS:
4313 * OR'd bitmask of WORK_BUSY_* bits.
4315 unsigned int work_busy(struct work_struct *work)
4317 struct worker_pool *pool;
4318 unsigned long flags;
4319 unsigned int ret = 0;
4321 if (work_pending(work))
4322 ret |= WORK_BUSY_PENDING;
4324 local_irq_save(flags);
4325 pool = get_work_pool(work);
4326 if (pool) {
4327 spin_lock(&pool->lock);
4328 if (find_worker_executing_work(pool, work))
4329 ret |= WORK_BUSY_RUNNING;
4330 spin_unlock(&pool->lock);
4332 local_irq_restore(flags);
4334 return ret;
4336 EXPORT_SYMBOL_GPL(work_busy);
4339 * CPU hotplug.
4341 * There are two challenges in supporting CPU hotplug. Firstly, there
4342 * are a lot of assumptions on strong associations among work, pwq and
4343 * pool which make migrating pending and scheduled works very
4344 * difficult to implement without impacting hot paths. Secondly,
4345 * worker pools serve mix of short, long and very long running works making
4346 * blocked draining impractical.
4348 * This is solved by allowing the pools to be disassociated from the CPU
4349 * running as an unbound one and allowing it to be reattached later if the
4350 * cpu comes back online.
4353 static void wq_unbind_fn(struct work_struct *work)
4355 int cpu = smp_processor_id();
4356 struct worker_pool *pool;
4357 struct worker *worker;
4358 int wi;
4360 for_each_cpu_worker_pool(pool, cpu) {
4361 WARN_ON_ONCE(cpu != smp_processor_id());
4363 mutex_lock(&pool->manager_mutex);
4364 spin_lock_irq(&pool->lock);
4367 * We've blocked all manager operations. Make all workers
4368 * unbound and set DISASSOCIATED. Before this, all workers
4369 * except for the ones which are still executing works from
4370 * before the last CPU down must be on the cpu. After
4371 * this, they may become diasporas.
4373 for_each_pool_worker(worker, wi, pool)
4374 worker->flags |= WORKER_UNBOUND;
4376 pool->flags |= POOL_DISASSOCIATED;
4378 spin_unlock_irq(&pool->lock);
4379 mutex_unlock(&pool->manager_mutex);
4383 * Call schedule() so that we cross rq->lock and thus can guarantee
4384 * sched callbacks see the %WORKER_UNBOUND flag. This is necessary
4385 * as scheduler callbacks may be invoked from other cpus.
4387 schedule();
4390 * Sched callbacks are disabled now. Zap nr_running. After this,
4391 * nr_running stays zero and need_more_worker() and keep_working()
4392 * are always true as long as the worklist is not empty. Pools on
4393 * @cpu now behave as unbound (in terms of concurrency management)
4394 * pools which are served by workers tied to the CPU.
4396 * On return from this function, the current worker would trigger
4397 * unbound chain execution of pending work items if other workers
4398 * didn't already.
4400 for_each_cpu_worker_pool(pool, cpu)
4401 atomic_set(&pool->nr_running, 0);
4405 * rebind_workers - rebind all workers of a pool to the associated CPU
4406 * @pool: pool of interest
4408 * @pool->cpu is coming online. Rebind all workers to the CPU.
4410 static void rebind_workers(struct worker_pool *pool)
4412 struct worker *worker;
4413 int wi;
4415 lockdep_assert_held(&pool->manager_mutex);
4418 * Restore CPU affinity of all workers. As all idle workers should
4419 * be on the run-queue of the associated CPU before any local
4420 * wake-ups for concurrency management happen, restore CPU affinty
4421 * of all workers first and then clear UNBOUND. As we're called
4422 * from CPU_ONLINE, the following shouldn't fail.
4424 for_each_pool_worker(worker, wi, pool)
4425 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4426 pool->attrs->cpumask) < 0);
4428 spin_lock_irq(&pool->lock);
4430 for_each_pool_worker(worker, wi, pool) {
4431 unsigned int worker_flags = worker->flags;
4434 * A bound idle worker should actually be on the runqueue
4435 * of the associated CPU for local wake-ups targeting it to
4436 * work. Kick all idle workers so that they migrate to the
4437 * associated CPU. Doing this in the same loop as
4438 * replacing UNBOUND with REBOUND is safe as no worker will
4439 * be bound before @pool->lock is released.
4441 if (worker_flags & WORKER_IDLE)
4442 wake_up_process(worker->task);
4445 * We want to clear UNBOUND but can't directly call
4446 * worker_clr_flags() or adjust nr_running. Atomically
4447 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
4448 * @worker will clear REBOUND using worker_clr_flags() when
4449 * it initiates the next execution cycle thus restoring
4450 * concurrency management. Note that when or whether
4451 * @worker clears REBOUND doesn't affect correctness.
4453 * ACCESS_ONCE() is necessary because @worker->flags may be
4454 * tested without holding any lock in
4455 * wq_worker_waking_up(). Without it, NOT_RUNNING test may
4456 * fail incorrectly leading to premature concurrency
4457 * management operations.
4459 WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
4460 worker_flags |= WORKER_REBOUND;
4461 worker_flags &= ~WORKER_UNBOUND;
4462 ACCESS_ONCE(worker->flags) = worker_flags;
4465 spin_unlock_irq(&pool->lock);
4469 * restore_unbound_workers_cpumask - restore cpumask of unbound workers
4470 * @pool: unbound pool of interest
4471 * @cpu: the CPU which is coming up
4473 * An unbound pool may end up with a cpumask which doesn't have any online
4474 * CPUs. When a worker of such pool get scheduled, the scheduler resets
4475 * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
4476 * online CPU before, cpus_allowed of all its workers should be restored.
4478 static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
4480 static cpumask_t cpumask;
4481 struct worker *worker;
4482 int wi;
4484 lockdep_assert_held(&pool->manager_mutex);
4486 /* is @cpu allowed for @pool? */
4487 if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
4488 return;
4490 /* is @cpu the only online CPU? */
4491 cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
4492 if (cpumask_weight(&cpumask) != 1)
4493 return;
4495 /* as we're called from CPU_ONLINE, the following shouldn't fail */
4496 for_each_pool_worker(worker, wi, pool)
4497 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4498 pool->attrs->cpumask) < 0);
4502 * Workqueues should be brought up before normal priority CPU notifiers.
4503 * This will be registered high priority CPU notifier.
4505 static int __cpuinit workqueue_cpu_up_callback(struct notifier_block *nfb,
4506 unsigned long action,
4507 void *hcpu)
4509 int cpu = (unsigned long)hcpu;
4510 struct worker_pool *pool;
4511 struct workqueue_struct *wq;
4512 int pi;
4514 switch (action & ~CPU_TASKS_FROZEN) {
4515 case CPU_UP_PREPARE:
4516 for_each_cpu_worker_pool(pool, cpu) {
4517 if (pool->nr_workers)
4518 continue;
4519 if (create_and_start_worker(pool) < 0)
4520 return NOTIFY_BAD;
4522 break;
4524 case CPU_DOWN_FAILED:
4525 case CPU_ONLINE:
4526 mutex_lock(&wq_pool_mutex);
4528 for_each_pool(pool, pi) {
4529 mutex_lock(&pool->manager_mutex);
4531 if (pool->cpu == cpu) {
4532 spin_lock_irq(&pool->lock);
4533 pool->flags &= ~POOL_DISASSOCIATED;
4534 spin_unlock_irq(&pool->lock);
4536 rebind_workers(pool);
4537 } else if (pool->cpu < 0) {
4538 restore_unbound_workers_cpumask(pool, cpu);
4541 mutex_unlock(&pool->manager_mutex);
4544 /* update NUMA affinity of unbound workqueues */
4545 list_for_each_entry(wq, &workqueues, list)
4546 wq_update_unbound_numa(wq, cpu, true);
4548 mutex_unlock(&wq_pool_mutex);
4549 break;
4551 return NOTIFY_OK;
4555 * Workqueues should be brought down after normal priority CPU notifiers.
4556 * This will be registered as low priority CPU notifier.
4558 static int __cpuinit workqueue_cpu_down_callback(struct notifier_block *nfb,
4559 unsigned long action,
4560 void *hcpu)
4562 int cpu = (unsigned long)hcpu;
4563 struct work_struct unbind_work;
4564 struct workqueue_struct *wq;
4566 switch (action & ~CPU_TASKS_FROZEN) {
4567 case CPU_DOWN_PREPARE:
4568 /* unbinding per-cpu workers should happen on the local CPU */
4569 INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
4570 queue_work_on(cpu, system_highpri_wq, &unbind_work);
4572 /* update NUMA affinity of unbound workqueues */
4573 mutex_lock(&wq_pool_mutex);
4574 list_for_each_entry(wq, &workqueues, list)
4575 wq_update_unbound_numa(wq, cpu, false);
4576 mutex_unlock(&wq_pool_mutex);
4578 /* wait for per-cpu unbinding to finish */
4579 flush_work(&unbind_work);
4580 break;
4582 return NOTIFY_OK;
4585 #ifdef CONFIG_SMP
4587 struct work_for_cpu {
4588 struct work_struct work;
4589 long (*fn)(void *);
4590 void *arg;
4591 long ret;
4594 static void work_for_cpu_fn(struct work_struct *work)
4596 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
4598 wfc->ret = wfc->fn(wfc->arg);
4602 * work_on_cpu - run a function in user context on a particular cpu
4603 * @cpu: the cpu to run on
4604 * @fn: the function to run
4605 * @arg: the function arg
4607 * This will return the value @fn returns.
4608 * It is up to the caller to ensure that the cpu doesn't go offline.
4609 * The caller must not hold any locks which would prevent @fn from completing.
4611 long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
4613 struct work_for_cpu wfc = { .fn = fn, .arg = arg };
4615 INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
4616 schedule_work_on(cpu, &wfc.work);
4617 flush_work(&wfc.work);
4618 return wfc.ret;
4620 EXPORT_SYMBOL_GPL(work_on_cpu);
4621 #endif /* CONFIG_SMP */
4623 #ifdef CONFIG_FREEZER
4626 * freeze_workqueues_begin - begin freezing workqueues
4628 * Start freezing workqueues. After this function returns, all freezable
4629 * workqueues will queue new works to their delayed_works list instead of
4630 * pool->worklist.
4632 * CONTEXT:
4633 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4635 void freeze_workqueues_begin(void)
4637 struct worker_pool *pool;
4638 struct workqueue_struct *wq;
4639 struct pool_workqueue *pwq;
4640 int pi;
4642 mutex_lock(&wq_pool_mutex);
4644 WARN_ON_ONCE(workqueue_freezing);
4645 workqueue_freezing = true;
4647 /* set FREEZING */
4648 for_each_pool(pool, pi) {
4649 spin_lock_irq(&pool->lock);
4650 WARN_ON_ONCE(pool->flags & POOL_FREEZING);
4651 pool->flags |= POOL_FREEZING;
4652 spin_unlock_irq(&pool->lock);
4655 list_for_each_entry(wq, &workqueues, list) {
4656 mutex_lock(&wq->mutex);
4657 for_each_pwq(pwq, wq)
4658 pwq_adjust_max_active(pwq);
4659 mutex_unlock(&wq->mutex);
4662 mutex_unlock(&wq_pool_mutex);
4666 * freeze_workqueues_busy - are freezable workqueues still busy?
4668 * Check whether freezing is complete. This function must be called
4669 * between freeze_workqueues_begin() and thaw_workqueues().
4671 * CONTEXT:
4672 * Grabs and releases wq_pool_mutex.
4674 * RETURNS:
4675 * %true if some freezable workqueues are still busy. %false if freezing
4676 * is complete.
4678 bool freeze_workqueues_busy(void)
4680 bool busy = false;
4681 struct workqueue_struct *wq;
4682 struct pool_workqueue *pwq;
4684 mutex_lock(&wq_pool_mutex);
4686 WARN_ON_ONCE(!workqueue_freezing);
4688 list_for_each_entry(wq, &workqueues, list) {
4689 if (!(wq->flags & WQ_FREEZABLE))
4690 continue;
4692 * nr_active is monotonically decreasing. It's safe
4693 * to peek without lock.
4695 rcu_read_lock_sched();
4696 for_each_pwq(pwq, wq) {
4697 WARN_ON_ONCE(pwq->nr_active < 0);
4698 if (pwq->nr_active) {
4699 busy = true;
4700 rcu_read_unlock_sched();
4701 goto out_unlock;
4704 rcu_read_unlock_sched();
4706 out_unlock:
4707 mutex_unlock(&wq_pool_mutex);
4708 return busy;
4712 * thaw_workqueues - thaw workqueues
4714 * Thaw workqueues. Normal queueing is restored and all collected
4715 * frozen works are transferred to their respective pool worklists.
4717 * CONTEXT:
4718 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4720 void thaw_workqueues(void)
4722 struct workqueue_struct *wq;
4723 struct pool_workqueue *pwq;
4724 struct worker_pool *pool;
4725 int pi;
4727 mutex_lock(&wq_pool_mutex);
4729 if (!workqueue_freezing)
4730 goto out_unlock;
4732 /* clear FREEZING */
4733 for_each_pool(pool, pi) {
4734 spin_lock_irq(&pool->lock);
4735 WARN_ON_ONCE(!(pool->flags & POOL_FREEZING));
4736 pool->flags &= ~POOL_FREEZING;
4737 spin_unlock_irq(&pool->lock);
4740 /* restore max_active and repopulate worklist */
4741 list_for_each_entry(wq, &workqueues, list) {
4742 mutex_lock(&wq->mutex);
4743 for_each_pwq(pwq, wq)
4744 pwq_adjust_max_active(pwq);
4745 mutex_unlock(&wq->mutex);
4748 workqueue_freezing = false;
4749 out_unlock:
4750 mutex_unlock(&wq_pool_mutex);
4752 #endif /* CONFIG_FREEZER */
4754 static void __init wq_numa_init(void)
4756 cpumask_var_t *tbl;
4757 int node, cpu;
4759 /* determine NUMA pwq table len - highest node id + 1 */
4760 for_each_node(node)
4761 wq_numa_tbl_len = max(wq_numa_tbl_len, node + 1);
4763 if (num_possible_nodes() <= 1)
4764 return;
4766 wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs(GFP_KERNEL);
4767 BUG_ON(!wq_update_unbound_numa_attrs_buf);
4770 * We want masks of possible CPUs of each node which isn't readily
4771 * available. Build one from cpu_to_node() which should have been
4772 * fully initialized by now.
4774 tbl = kzalloc(wq_numa_tbl_len * sizeof(tbl[0]), GFP_KERNEL);
4775 BUG_ON(!tbl);
4777 for_each_node(node)
4778 BUG_ON(!alloc_cpumask_var_node(&tbl[node], GFP_KERNEL, node));
4780 for_each_possible_cpu(cpu) {
4781 node = cpu_to_node(cpu);
4782 if (WARN_ON(node == NUMA_NO_NODE)) {
4783 pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
4784 /* happens iff arch is bonkers, let's just proceed */
4785 return;
4787 cpumask_set_cpu(cpu, tbl[node]);
4790 wq_numa_possible_cpumask = tbl;
4791 wq_numa_enabled = true;
4794 static int __init init_workqueues(void)
4796 int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
4797 int i, cpu;
4799 /* make sure we have enough bits for OFFQ pool ID */
4800 BUILD_BUG_ON((1LU << (BITS_PER_LONG - WORK_OFFQ_POOL_SHIFT)) <
4801 WORK_CPU_END * NR_STD_WORKER_POOLS);
4803 WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
4805 pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
4807 cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
4808 hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
4810 wq_numa_init();
4812 /* initialize CPU pools */
4813 for_each_possible_cpu(cpu) {
4814 struct worker_pool *pool;
4816 i = 0;
4817 for_each_cpu_worker_pool(pool, cpu) {
4818 BUG_ON(init_worker_pool(pool));
4819 pool->cpu = cpu;
4820 cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
4821 pool->attrs->nice = std_nice[i++];
4822 pool->node = cpu_to_node(cpu);
4824 /* alloc pool ID */
4825 mutex_lock(&wq_pool_mutex);
4826 BUG_ON(worker_pool_assign_id(pool));
4827 mutex_unlock(&wq_pool_mutex);
4831 /* create the initial worker */
4832 for_each_online_cpu(cpu) {
4833 struct worker_pool *pool;
4835 for_each_cpu_worker_pool(pool, cpu) {
4836 pool->flags &= ~POOL_DISASSOCIATED;
4837 BUG_ON(create_and_start_worker(pool) < 0);
4841 /* create default unbound wq attrs */
4842 for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
4843 struct workqueue_attrs *attrs;
4845 BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
4846 attrs->nice = std_nice[i];
4847 unbound_std_wq_attrs[i] = attrs;
4850 system_wq = alloc_workqueue("events", 0, 0);
4851 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
4852 system_long_wq = alloc_workqueue("events_long", 0, 0);
4853 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
4854 WQ_UNBOUND_MAX_ACTIVE);
4855 system_freezable_wq = alloc_workqueue("events_freezable",
4856 WQ_FREEZABLE, 0);
4857 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
4858 !system_unbound_wq || !system_freezable_wq);
4859 return 0;
4861 early_initcall(init_workqueues);