2 * kernel/workqueue.c - generic async execution with shared worker pool
4 * Copyright (C) 2002 Ingo Molnar
6 * Derived from the taskqueue/keventd code by:
7 * David Woodhouse <dwmw2@infradead.org>
9 * Kai Petzke <wpp@marie.physik.tu-berlin.de>
10 * Theodore Ts'o <tytso@mit.edu>
12 * Made to use alloc_percpu by Christoph Lameter.
14 * Copyright (C) 2010 SUSE Linux Products GmbH
15 * Copyright (C) 2010 Tejun Heo <tj@kernel.org>
17 * This is the generic async execution mechanism. Work items as are
18 * executed in process context. The worker pool is shared and
19 * automatically managed. There is one worker pool for each CPU and
20 * one extra for works which are better served by workers which are
21 * not bound to any specific CPU.
23 * Please read Documentation/workqueue.txt for details.
26 #include <linux/export.h>
27 #include <linux/kernel.h>
28 #include <linux/sched.h>
29 #include <linux/init.h>
30 #include <linux/signal.h>
31 #include <linux/completion.h>
32 #include <linux/workqueue.h>
33 #include <linux/slab.h>
34 #include <linux/cpu.h>
35 #include <linux/notifier.h>
36 #include <linux/kthread.h>
37 #include <linux/hardirq.h>
38 #include <linux/mempolicy.h>
39 #include <linux/freezer.h>
40 #include <linux/kallsyms.h>
41 #include <linux/debug_locks.h>
42 #include <linux/lockdep.h>
43 #include <linux/idr.h>
44 #include <linux/jhash.h>
45 #include <linux/hashtable.h>
46 #include <linux/rculist.h>
48 #include "workqueue_internal.h"
54 * A bound pool is either associated or disassociated with its CPU.
55 * While associated (!DISASSOCIATED), all workers are bound to the
56 * CPU and none has %WORKER_UNBOUND set and concurrency management
59 * While DISASSOCIATED, the cpu may be offline and all workers have
60 * %WORKER_UNBOUND set and concurrency management disabled, and may
61 * be executing on any CPU. The pool behaves as an unbound one.
63 * Note that DISASSOCIATED should be flipped only while holding
64 * manager_mutex to avoid changing binding state while
65 * create_worker() is in progress.
67 POOL_MANAGE_WORKERS
= 1 << 0, /* need to manage workers */
68 POOL_DISASSOCIATED
= 1 << 2, /* cpu can't serve workers */
69 POOL_FREEZING
= 1 << 3, /* freeze in progress */
72 WORKER_STARTED
= 1 << 0, /* started */
73 WORKER_DIE
= 1 << 1, /* die die die */
74 WORKER_IDLE
= 1 << 2, /* is idle */
75 WORKER_PREP
= 1 << 3, /* preparing to run works */
76 WORKER_CPU_INTENSIVE
= 1 << 6, /* cpu intensive */
77 WORKER_UNBOUND
= 1 << 7, /* worker is unbound */
78 WORKER_REBOUND
= 1 << 8, /* worker was rebound */
80 WORKER_NOT_RUNNING
= WORKER_PREP
| WORKER_CPU_INTENSIVE
|
81 WORKER_UNBOUND
| WORKER_REBOUND
,
83 NR_STD_WORKER_POOLS
= 2, /* # standard pools per cpu */
85 UNBOUND_POOL_HASH_ORDER
= 6, /* hashed by pool->attrs */
86 BUSY_WORKER_HASH_ORDER
= 6, /* 64 pointers */
88 MAX_IDLE_WORKERS_RATIO
= 4, /* 1/4 of busy can be idle */
89 IDLE_WORKER_TIMEOUT
= 300 * HZ
, /* keep idle ones for 5 mins */
91 MAYDAY_INITIAL_TIMEOUT
= HZ
/ 100 >= 2 ? HZ
/ 100 : 2,
92 /* call for help after 10ms
94 MAYDAY_INTERVAL
= HZ
/ 10, /* and then every 100ms */
95 CREATE_COOLDOWN
= HZ
, /* time to breath after fail */
98 * Rescue workers are used only on emergencies and shared by
101 RESCUER_NICE_LEVEL
= -20,
102 HIGHPRI_NICE_LEVEL
= -20,
106 * Structure fields follow one of the following exclusion rules.
108 * I: Modifiable by initialization/destruction paths and read-only for
111 * P: Preemption protected. Disabling preemption is enough and should
112 * only be modified and accessed from the local cpu.
114 * L: pool->lock protected. Access with pool->lock held.
116 * X: During normal operation, modification requires pool->lock and should
117 * be done only from local cpu. Either disabling preemption on local
118 * cpu or grabbing pool->lock is enough for read access. If
119 * POOL_DISASSOCIATED is set, it's identical to L.
121 * F: wq->flush_mutex protected.
123 * MG: pool->manager_mutex and pool->lock protected. Writes require both
124 * locks. Reads can happen under either lock.
126 * WQ: wq_mutex protected.
128 * WR: wq_mutex protected for writes. Sched-RCU protected for reads.
130 * PW: pwq_lock protected.
132 * FR: wq->flush_mutex and pwq_lock protected for writes. Sched-RCU
133 * protected for reads.
135 * MD: wq_mayday_lock protected.
138 /* struct worker is defined in workqueue_internal.h */
141 spinlock_t lock
; /* the pool lock */
142 int cpu
; /* I: the associated cpu */
143 int id
; /* I: pool ID */
144 unsigned int flags
; /* X: flags */
146 struct list_head worklist
; /* L: list of pending works */
147 int nr_workers
; /* L: total number of workers */
149 /* nr_idle includes the ones off idle_list for rebinding */
150 int nr_idle
; /* L: currently idle ones */
152 struct list_head idle_list
; /* X: list of idle workers */
153 struct timer_list idle_timer
; /* L: worker idle timeout */
154 struct timer_list mayday_timer
; /* L: SOS timer for workers */
156 /* a workers is either on busy_hash or idle_list, or the manager */
157 DECLARE_HASHTABLE(busy_hash
, BUSY_WORKER_HASH_ORDER
);
158 /* L: hash of busy workers */
160 /* see manage_workers() for details on the two manager mutexes */
161 struct mutex manager_arb
; /* manager arbitration */
162 struct mutex manager_mutex
; /* manager exclusion */
163 struct idr worker_idr
; /* MG: worker IDs and iteration */
165 struct workqueue_attrs
*attrs
; /* I: worker attributes */
166 struct hlist_node hash_node
; /* WQ: unbound_pool_hash node */
167 int refcnt
; /* WQ: refcnt for unbound pools */
170 * The current concurrency level. As it's likely to be accessed
171 * from other CPUs during try_to_wake_up(), put it in a separate
174 atomic_t nr_running ____cacheline_aligned_in_smp
;
177 * Destruction of pool is sched-RCU protected to allow dereferences
178 * from get_work_pool().
181 } ____cacheline_aligned_in_smp
;
184 * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
185 * of work_struct->data are used for flags and the remaining high bits
186 * point to the pwq; thus, pwqs need to be aligned at two's power of the
187 * number of flag bits.
189 struct pool_workqueue
{
190 struct worker_pool
*pool
; /* I: the associated pool */
191 struct workqueue_struct
*wq
; /* I: the owning workqueue */
192 int work_color
; /* L: current color */
193 int flush_color
; /* L: flushing color */
194 int refcnt
; /* L: reference count */
195 int nr_in_flight
[WORK_NR_COLORS
];
196 /* L: nr of in_flight works */
197 int nr_active
; /* L: nr of active works */
198 int max_active
; /* L: max active works */
199 struct list_head delayed_works
; /* L: delayed works */
200 struct list_head pwqs_node
; /* FR: node on wq->pwqs */
201 struct list_head mayday_node
; /* MD: node on wq->maydays */
204 * Release of unbound pwq is punted to system_wq. See put_pwq()
205 * and pwq_unbound_release_workfn() for details. pool_workqueue
206 * itself is also sched-RCU protected so that the first pwq can be
207 * determined without grabbing pwq_lock.
209 struct work_struct unbound_release_work
;
211 } __aligned(1 << WORK_STRUCT_FLAG_BITS
);
214 * Structure used to wait for workqueue flush.
217 struct list_head list
; /* F: list of flushers */
218 int flush_color
; /* F: flush color waiting for */
219 struct completion done
; /* flush completion */
225 * The externally visible workqueue. It relays the issued work items to
226 * the appropriate worker_pool through its pool_workqueues.
228 struct workqueue_struct
{
229 unsigned int flags
; /* WQ: WQ_* flags */
230 struct pool_workqueue __percpu
*cpu_pwqs
; /* I: per-cpu pwq's */
231 struct list_head pwqs
; /* FR: all pwqs of this wq */
232 struct list_head list
; /* WQ: list of all workqueues */
234 struct mutex flush_mutex
; /* protects wq flushing */
235 int work_color
; /* F: current work color */
236 int flush_color
; /* F: current flush color */
237 atomic_t nr_pwqs_to_flush
; /* flush in progress */
238 struct wq_flusher
*first_flusher
; /* F: first flusher */
239 struct list_head flusher_queue
; /* F: flush waiters */
240 struct list_head flusher_overflow
; /* F: 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
; /* PW: saved pwq max_active */
249 struct wq_device
*wq_dev
; /* I: for sysfs interface */
251 #ifdef CONFIG_LOCKDEP
252 struct lockdep_map lockdep_map
;
254 char name
[]; /* I: workqueue name */
257 static struct kmem_cache
*pwq_cache
;
259 static DEFINE_MUTEX(wq_mutex
); /* protects workqueues and pools */
260 static DEFINE_SPINLOCK(pwq_lock
); /* protects pool_workqueues */
261 static DEFINE_SPINLOCK(wq_mayday_lock
); /* protects wq->maydays list */
263 static LIST_HEAD(workqueues
); /* WQ: list of all workqueues */
264 static bool workqueue_freezing
; /* WQ: have wqs started freezing? */
266 /* the per-cpu worker pools */
267 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool
[NR_STD_WORKER_POOLS
],
270 static DEFINE_IDR(worker_pool_idr
); /* WR: idr of all pools */
272 /* WQ: hash of all unbound pools keyed by pool->attrs */
273 static DEFINE_HASHTABLE(unbound_pool_hash
, UNBOUND_POOL_HASH_ORDER
);
275 /* I: attributes used when instantiating standard unbound pools on demand */
276 static struct workqueue_attrs
*unbound_std_wq_attrs
[NR_STD_WORKER_POOLS
];
278 struct workqueue_struct
*system_wq __read_mostly
;
279 EXPORT_SYMBOL_GPL(system_wq
);
280 struct workqueue_struct
*system_highpri_wq __read_mostly
;
281 EXPORT_SYMBOL_GPL(system_highpri_wq
);
282 struct workqueue_struct
*system_long_wq __read_mostly
;
283 EXPORT_SYMBOL_GPL(system_long_wq
);
284 struct workqueue_struct
*system_unbound_wq __read_mostly
;
285 EXPORT_SYMBOL_GPL(system_unbound_wq
);
286 struct workqueue_struct
*system_freezable_wq __read_mostly
;
287 EXPORT_SYMBOL_GPL(system_freezable_wq
);
289 static int worker_thread(void *__worker
);
290 static void copy_workqueue_attrs(struct workqueue_attrs
*to
,
291 const struct workqueue_attrs
*from
);
293 #define CREATE_TRACE_POINTS
294 #include <trace/events/workqueue.h>
296 #define assert_rcu_or_wq_mutex() \
297 rcu_lockdep_assert(rcu_read_lock_sched_held() || \
298 lockdep_is_held(&wq_mutex), \
299 "sched RCU or wq_mutex should be held")
301 #define assert_rcu_or_pwq_lock() \
302 rcu_lockdep_assert(rcu_read_lock_sched_held() || \
303 lockdep_is_held(&pwq_lock), \
304 "sched RCU or pwq_lock should be held")
306 #ifdef CONFIG_LOCKDEP
307 #define assert_manager_or_pool_lock(pool) \
308 WARN_ONCE(debug_locks && \
309 !lockdep_is_held(&(pool)->manager_mutex) && \
310 !lockdep_is_held(&(pool)->lock), \
311 "pool->manager_mutex or ->lock should be held")
313 #define assert_manager_or_pool_lock(pool) do { } while (0)
316 #define for_each_cpu_worker_pool(pool, cpu) \
317 for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
318 (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
322 * for_each_pool - iterate through all worker_pools in the system
323 * @pool: iteration cursor
324 * @pi: integer used for iteration
326 * This must be called either with wq_mutex held or sched RCU read locked.
327 * If the pool needs to be used beyond the locking in effect, the caller is
328 * responsible for guaranteeing that the pool stays online.
330 * The if/else clause exists only for the lockdep assertion and can be
333 #define for_each_pool(pool, pi) \
334 idr_for_each_entry(&worker_pool_idr, pool, pi) \
335 if (({ assert_rcu_or_wq_mutex(); false; })) { } \
339 * for_each_pool_worker - iterate through all workers of a worker_pool
340 * @worker: iteration cursor
341 * @wi: integer used for iteration
342 * @pool: worker_pool to iterate workers of
344 * This must be called with either @pool->manager_mutex or ->lock held.
346 * The if/else clause exists only for the lockdep assertion and can be
349 #define for_each_pool_worker(worker, wi, pool) \
350 idr_for_each_entry(&(pool)->worker_idr, (worker), (wi)) \
351 if (({ assert_manager_or_pool_lock((pool)); false; })) { } \
355 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
356 * @pwq: iteration cursor
357 * @wq: the target workqueue
359 * This must be called either with pwq_lock held or sched RCU read locked.
360 * If the pwq needs to be used beyond the locking in effect, the caller is
361 * responsible for guaranteeing that the pwq stays online.
363 * The if/else clause exists only for the lockdep assertion and can be
366 #define for_each_pwq(pwq, wq) \
367 list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node) \
368 if (({ assert_rcu_or_pwq_lock(); false; })) { } \
371 #ifdef CONFIG_DEBUG_OBJECTS_WORK
373 static struct debug_obj_descr work_debug_descr
;
375 static void *work_debug_hint(void *addr
)
377 return ((struct work_struct
*) addr
)->func
;
381 * fixup_init is called when:
382 * - an active object is initialized
384 static int work_fixup_init(void *addr
, enum debug_obj_state state
)
386 struct work_struct
*work
= addr
;
389 case ODEBUG_STATE_ACTIVE
:
390 cancel_work_sync(work
);
391 debug_object_init(work
, &work_debug_descr
);
399 * fixup_activate is called when:
400 * - an active object is activated
401 * - an unknown object is activated (might be a statically initialized object)
403 static int work_fixup_activate(void *addr
, enum debug_obj_state state
)
405 struct work_struct
*work
= addr
;
409 case ODEBUG_STATE_NOTAVAILABLE
:
411 * This is not really a fixup. The work struct was
412 * statically initialized. We just make sure that it
413 * is tracked in the object tracker.
415 if (test_bit(WORK_STRUCT_STATIC_BIT
, work_data_bits(work
))) {
416 debug_object_init(work
, &work_debug_descr
);
417 debug_object_activate(work
, &work_debug_descr
);
423 case ODEBUG_STATE_ACTIVE
:
432 * fixup_free is called when:
433 * - an active object is freed
435 static int work_fixup_free(void *addr
, enum debug_obj_state state
)
437 struct work_struct
*work
= addr
;
440 case ODEBUG_STATE_ACTIVE
:
441 cancel_work_sync(work
);
442 debug_object_free(work
, &work_debug_descr
);
449 static struct debug_obj_descr work_debug_descr
= {
450 .name
= "work_struct",
451 .debug_hint
= work_debug_hint
,
452 .fixup_init
= work_fixup_init
,
453 .fixup_activate
= work_fixup_activate
,
454 .fixup_free
= work_fixup_free
,
457 static inline void debug_work_activate(struct work_struct
*work
)
459 debug_object_activate(work
, &work_debug_descr
);
462 static inline void debug_work_deactivate(struct work_struct
*work
)
464 debug_object_deactivate(work
, &work_debug_descr
);
467 void __init_work(struct work_struct
*work
, int onstack
)
470 debug_object_init_on_stack(work
, &work_debug_descr
);
472 debug_object_init(work
, &work_debug_descr
);
474 EXPORT_SYMBOL_GPL(__init_work
);
476 void destroy_work_on_stack(struct work_struct
*work
)
478 debug_object_free(work
, &work_debug_descr
);
480 EXPORT_SYMBOL_GPL(destroy_work_on_stack
);
483 static inline void debug_work_activate(struct work_struct
*work
) { }
484 static inline void debug_work_deactivate(struct work_struct
*work
) { }
487 /* allocate ID and assign it to @pool */
488 static int worker_pool_assign_id(struct worker_pool
*pool
)
492 lockdep_assert_held(&wq_mutex
);
495 if (!idr_pre_get(&worker_pool_idr
, GFP_KERNEL
))
497 ret
= idr_get_new(&worker_pool_idr
, pool
, &pool
->id
);
498 } while (ret
== -EAGAIN
);
504 * first_pwq - return the first pool_workqueue of the specified workqueue
505 * @wq: the target workqueue
507 * This must be called either with pwq_lock held or sched RCU read locked.
508 * If the pwq needs to be used beyond the locking in effect, the caller is
509 * responsible for guaranteeing that the pwq stays online.
511 static struct pool_workqueue
*first_pwq(struct workqueue_struct
*wq
)
513 assert_rcu_or_pwq_lock();
514 return list_first_or_null_rcu(&wq
->pwqs
, struct pool_workqueue
,
518 static unsigned int work_color_to_flags(int color
)
520 return color
<< WORK_STRUCT_COLOR_SHIFT
;
523 static int get_work_color(struct work_struct
*work
)
525 return (*work_data_bits(work
) >> WORK_STRUCT_COLOR_SHIFT
) &
526 ((1 << WORK_STRUCT_COLOR_BITS
) - 1);
529 static int work_next_color(int color
)
531 return (color
+ 1) % WORK_NR_COLORS
;
535 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
536 * contain the pointer to the queued pwq. Once execution starts, the flag
537 * is cleared and the high bits contain OFFQ flags and pool ID.
539 * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
540 * and clear_work_data() can be used to set the pwq, pool or clear
541 * work->data. These functions should only be called while the work is
542 * owned - ie. while the PENDING bit is set.
544 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
545 * corresponding to a work. Pool is available once the work has been
546 * queued anywhere after initialization until it is sync canceled. pwq is
547 * available only while the work item is queued.
549 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
550 * canceled. While being canceled, a work item may have its PENDING set
551 * but stay off timer and worklist for arbitrarily long and nobody should
552 * try to steal the PENDING bit.
554 static inline void set_work_data(struct work_struct
*work
, unsigned long data
,
557 WARN_ON_ONCE(!work_pending(work
));
558 atomic_long_set(&work
->data
, data
| flags
| work_static(work
));
561 static void set_work_pwq(struct work_struct
*work
, struct pool_workqueue
*pwq
,
562 unsigned long extra_flags
)
564 set_work_data(work
, (unsigned long)pwq
,
565 WORK_STRUCT_PENDING
| WORK_STRUCT_PWQ
| extra_flags
);
568 static void set_work_pool_and_keep_pending(struct work_struct
*work
,
571 set_work_data(work
, (unsigned long)pool_id
<< WORK_OFFQ_POOL_SHIFT
,
572 WORK_STRUCT_PENDING
);
575 static void set_work_pool_and_clear_pending(struct work_struct
*work
,
579 * The following wmb is paired with the implied mb in
580 * test_and_set_bit(PENDING) and ensures all updates to @work made
581 * here are visible to and precede any updates by the next PENDING
585 set_work_data(work
, (unsigned long)pool_id
<< WORK_OFFQ_POOL_SHIFT
, 0);
588 static void clear_work_data(struct work_struct
*work
)
590 smp_wmb(); /* see set_work_pool_and_clear_pending() */
591 set_work_data(work
, WORK_STRUCT_NO_POOL
, 0);
594 static struct pool_workqueue
*get_work_pwq(struct work_struct
*work
)
596 unsigned long data
= atomic_long_read(&work
->data
);
598 if (data
& WORK_STRUCT_PWQ
)
599 return (void *)(data
& WORK_STRUCT_WQ_DATA_MASK
);
605 * get_work_pool - return the worker_pool a given work was associated with
606 * @work: the work item of interest
608 * Return the worker_pool @work was last associated with. %NULL if none.
610 * Pools are created and destroyed under wq_mutex, and allows read access
611 * under sched-RCU read lock. As such, this function should be called
612 * under wq_mutex or with preemption disabled.
614 * All fields of the returned pool are accessible as long as the above
615 * mentioned locking is in effect. If the returned pool needs to be used
616 * beyond the critical section, the caller is responsible for ensuring the
617 * returned pool is and stays online.
619 static struct worker_pool
*get_work_pool(struct work_struct
*work
)
621 unsigned long data
= atomic_long_read(&work
->data
);
624 assert_rcu_or_wq_mutex();
626 if (data
& WORK_STRUCT_PWQ
)
627 return ((struct pool_workqueue
*)
628 (data
& WORK_STRUCT_WQ_DATA_MASK
))->pool
;
630 pool_id
= data
>> WORK_OFFQ_POOL_SHIFT
;
631 if (pool_id
== WORK_OFFQ_POOL_NONE
)
634 return idr_find(&worker_pool_idr
, pool_id
);
638 * get_work_pool_id - return the worker pool ID a given work is associated with
639 * @work: the work item of interest
641 * Return the worker_pool ID @work was last associated with.
642 * %WORK_OFFQ_POOL_NONE if none.
644 static int get_work_pool_id(struct work_struct
*work
)
646 unsigned long data
= atomic_long_read(&work
->data
);
648 if (data
& WORK_STRUCT_PWQ
)
649 return ((struct pool_workqueue
*)
650 (data
& WORK_STRUCT_WQ_DATA_MASK
))->pool
->id
;
652 return data
>> WORK_OFFQ_POOL_SHIFT
;
655 static void mark_work_canceling(struct work_struct
*work
)
657 unsigned long pool_id
= get_work_pool_id(work
);
659 pool_id
<<= WORK_OFFQ_POOL_SHIFT
;
660 set_work_data(work
, pool_id
| WORK_OFFQ_CANCELING
, WORK_STRUCT_PENDING
);
663 static bool work_is_canceling(struct work_struct
*work
)
665 unsigned long data
= atomic_long_read(&work
->data
);
667 return !(data
& WORK_STRUCT_PWQ
) && (data
& WORK_OFFQ_CANCELING
);
671 * Policy functions. These define the policies on how the global worker
672 * pools are managed. Unless noted otherwise, these functions assume that
673 * they're being called with pool->lock held.
676 static bool __need_more_worker(struct worker_pool
*pool
)
678 return !atomic_read(&pool
->nr_running
);
682 * Need to wake up a worker? Called from anything but currently
685 * Note that, because unbound workers never contribute to nr_running, this
686 * function will always return %true for unbound pools as long as the
687 * worklist isn't empty.
689 static bool need_more_worker(struct worker_pool
*pool
)
691 return !list_empty(&pool
->worklist
) && __need_more_worker(pool
);
694 /* Can I start working? Called from busy but !running workers. */
695 static bool may_start_working(struct worker_pool
*pool
)
697 return pool
->nr_idle
;
700 /* Do I need to keep working? Called from currently running workers. */
701 static bool keep_working(struct worker_pool
*pool
)
703 return !list_empty(&pool
->worklist
) &&
704 atomic_read(&pool
->nr_running
) <= 1;
707 /* Do we need a new worker? Called from manager. */
708 static bool need_to_create_worker(struct worker_pool
*pool
)
710 return need_more_worker(pool
) && !may_start_working(pool
);
713 /* Do I need to be the manager? */
714 static bool need_to_manage_workers(struct worker_pool
*pool
)
716 return need_to_create_worker(pool
) ||
717 (pool
->flags
& POOL_MANAGE_WORKERS
);
720 /* Do we have too many workers and should some go away? */
721 static bool too_many_workers(struct worker_pool
*pool
)
723 bool managing
= mutex_is_locked(&pool
->manager_arb
);
724 int nr_idle
= pool
->nr_idle
+ managing
; /* manager is considered idle */
725 int nr_busy
= pool
->nr_workers
- nr_idle
;
728 * nr_idle and idle_list may disagree if idle rebinding is in
729 * progress. Never return %true if idle_list is empty.
731 if (list_empty(&pool
->idle_list
))
734 return nr_idle
> 2 && (nr_idle
- 2) * MAX_IDLE_WORKERS_RATIO
>= nr_busy
;
741 /* Return the first worker. Safe with preemption disabled */
742 static struct worker
*first_worker(struct worker_pool
*pool
)
744 if (unlikely(list_empty(&pool
->idle_list
)))
747 return list_first_entry(&pool
->idle_list
, struct worker
, entry
);
751 * wake_up_worker - wake up an idle worker
752 * @pool: worker pool to wake worker from
754 * Wake up the first idle worker of @pool.
757 * spin_lock_irq(pool->lock).
759 static void wake_up_worker(struct worker_pool
*pool
)
761 struct worker
*worker
= first_worker(pool
);
764 wake_up_process(worker
->task
);
768 * wq_worker_waking_up - a worker is waking up
769 * @task: task waking up
770 * @cpu: CPU @task is waking up to
772 * This function is called during try_to_wake_up() when a worker is
776 * spin_lock_irq(rq->lock)
778 void wq_worker_waking_up(struct task_struct
*task
, int cpu
)
780 struct worker
*worker
= kthread_data(task
);
782 if (!(worker
->flags
& WORKER_NOT_RUNNING
)) {
783 WARN_ON_ONCE(worker
->pool
->cpu
!= cpu
);
784 atomic_inc(&worker
->pool
->nr_running
);
789 * wq_worker_sleeping - a worker is going to sleep
790 * @task: task going to sleep
791 * @cpu: CPU in question, must be the current CPU number
793 * This function is called during schedule() when a busy worker is
794 * going to sleep. Worker on the same cpu can be woken up by
795 * returning pointer to its task.
798 * spin_lock_irq(rq->lock)
801 * Worker task on @cpu to wake up, %NULL if none.
803 struct task_struct
*wq_worker_sleeping(struct task_struct
*task
, int cpu
)
805 struct worker
*worker
= kthread_data(task
), *to_wakeup
= NULL
;
806 struct worker_pool
*pool
;
809 * Rescuers, which may not have all the fields set up like normal
810 * workers, also reach here, let's not access anything before
811 * checking NOT_RUNNING.
813 if (worker
->flags
& WORKER_NOT_RUNNING
)
818 /* this can only happen on the local cpu */
819 if (WARN_ON_ONCE(cpu
!= raw_smp_processor_id()))
823 * The counterpart of the following dec_and_test, implied mb,
824 * worklist not empty test sequence is in insert_work().
825 * Please read comment there.
827 * NOT_RUNNING is clear. This means that we're bound to and
828 * running on the local cpu w/ rq lock held and preemption
829 * disabled, which in turn means that none else could be
830 * manipulating idle_list, so dereferencing idle_list without pool
833 if (atomic_dec_and_test(&pool
->nr_running
) &&
834 !list_empty(&pool
->worklist
))
835 to_wakeup
= first_worker(pool
);
836 return to_wakeup
? to_wakeup
->task
: NULL
;
840 * worker_set_flags - set worker flags and adjust nr_running accordingly
842 * @flags: flags to set
843 * @wakeup: wakeup an idle worker if necessary
845 * Set @flags in @worker->flags and adjust nr_running accordingly. If
846 * nr_running becomes zero and @wakeup is %true, an idle worker is
850 * spin_lock_irq(pool->lock)
852 static inline void worker_set_flags(struct worker
*worker
, unsigned int flags
,
855 struct worker_pool
*pool
= worker
->pool
;
857 WARN_ON_ONCE(worker
->task
!= current
);
860 * If transitioning into NOT_RUNNING, adjust nr_running and
861 * wake up an idle worker as necessary if requested by
864 if ((flags
& WORKER_NOT_RUNNING
) &&
865 !(worker
->flags
& WORKER_NOT_RUNNING
)) {
867 if (atomic_dec_and_test(&pool
->nr_running
) &&
868 !list_empty(&pool
->worklist
))
869 wake_up_worker(pool
);
871 atomic_dec(&pool
->nr_running
);
874 worker
->flags
|= flags
;
878 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
880 * @flags: flags to clear
882 * Clear @flags in @worker->flags and adjust nr_running accordingly.
885 * spin_lock_irq(pool->lock)
887 static inline void worker_clr_flags(struct worker
*worker
, unsigned int flags
)
889 struct worker_pool
*pool
= worker
->pool
;
890 unsigned int oflags
= worker
->flags
;
892 WARN_ON_ONCE(worker
->task
!= current
);
894 worker
->flags
&= ~flags
;
897 * If transitioning out of NOT_RUNNING, increment nr_running. Note
898 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
899 * of multiple flags, not a single flag.
901 if ((flags
& WORKER_NOT_RUNNING
) && (oflags
& WORKER_NOT_RUNNING
))
902 if (!(worker
->flags
& WORKER_NOT_RUNNING
))
903 atomic_inc(&pool
->nr_running
);
907 * find_worker_executing_work - find worker which is executing a work
908 * @pool: pool of interest
909 * @work: work to find worker for
911 * Find a worker which is executing @work on @pool by searching
912 * @pool->busy_hash which is keyed by the address of @work. For a worker
913 * to match, its current execution should match the address of @work and
914 * its work function. This is to avoid unwanted dependency between
915 * unrelated work executions through a work item being recycled while still
918 * This is a bit tricky. A work item may be freed once its execution
919 * starts and nothing prevents the freed area from being recycled for
920 * another work item. If the same work item address ends up being reused
921 * before the original execution finishes, workqueue will identify the
922 * recycled work item as currently executing and make it wait until the
923 * current execution finishes, introducing an unwanted dependency.
925 * This function checks the work item address and work function to avoid
926 * false positives. Note that this isn't complete as one may construct a
927 * work function which can introduce dependency onto itself through a
928 * recycled work item. Well, if somebody wants to shoot oneself in the
929 * foot that badly, there's only so much we can do, and if such deadlock
930 * actually occurs, it should be easy to locate the culprit work function.
933 * spin_lock_irq(pool->lock).
936 * Pointer to worker which is executing @work if found, NULL
939 static struct worker
*find_worker_executing_work(struct worker_pool
*pool
,
940 struct work_struct
*work
)
942 struct worker
*worker
;
944 hash_for_each_possible(pool
->busy_hash
, worker
, hentry
,
946 if (worker
->current_work
== work
&&
947 worker
->current_func
== work
->func
)
954 * move_linked_works - move linked works to a list
955 * @work: start of series of works to be scheduled
956 * @head: target list to append @work to
957 * @nextp: out paramter for nested worklist walking
959 * Schedule linked works starting from @work to @head. Work series to
960 * be scheduled starts at @work and includes any consecutive work with
961 * WORK_STRUCT_LINKED set in its predecessor.
963 * If @nextp is not NULL, it's updated to point to the next work of
964 * the last scheduled work. This allows move_linked_works() to be
965 * nested inside outer list_for_each_entry_safe().
968 * spin_lock_irq(pool->lock).
970 static void move_linked_works(struct work_struct
*work
, struct list_head
*head
,
971 struct work_struct
**nextp
)
973 struct work_struct
*n
;
976 * Linked worklist will always end before the end of the list,
977 * use NULL for list head.
979 list_for_each_entry_safe_from(work
, n
, NULL
, entry
) {
980 list_move_tail(&work
->entry
, head
);
981 if (!(*work_data_bits(work
) & WORK_STRUCT_LINKED
))
986 * If we're already inside safe list traversal and have moved
987 * multiple works to the scheduled queue, the next position
988 * needs to be updated.
995 * get_pwq - get an extra reference on the specified pool_workqueue
996 * @pwq: pool_workqueue to get
998 * Obtain an extra reference on @pwq. The caller should guarantee that
999 * @pwq has positive refcnt and be holding the matching pool->lock.
1001 static void get_pwq(struct pool_workqueue
*pwq
)
1003 lockdep_assert_held(&pwq
->pool
->lock
);
1004 WARN_ON_ONCE(pwq
->refcnt
<= 0);
1009 * put_pwq - put a pool_workqueue reference
1010 * @pwq: pool_workqueue to put
1012 * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
1013 * destruction. The caller should be holding the matching pool->lock.
1015 static void put_pwq(struct pool_workqueue
*pwq
)
1017 lockdep_assert_held(&pwq
->pool
->lock
);
1018 if (likely(--pwq
->refcnt
))
1020 if (WARN_ON_ONCE(!(pwq
->wq
->flags
& WQ_UNBOUND
)))
1023 * @pwq can't be released under pool->lock, bounce to
1024 * pwq_unbound_release_workfn(). This never recurses on the same
1025 * pool->lock as this path is taken only for unbound workqueues and
1026 * the release work item is scheduled on a per-cpu workqueue. To
1027 * avoid lockdep warning, unbound pool->locks are given lockdep
1028 * subclass of 1 in get_unbound_pool().
1030 schedule_work(&pwq
->unbound_release_work
);
1033 static void pwq_activate_delayed_work(struct work_struct
*work
)
1035 struct pool_workqueue
*pwq
= get_work_pwq(work
);
1037 trace_workqueue_activate_work(work
);
1038 move_linked_works(work
, &pwq
->pool
->worklist
, NULL
);
1039 __clear_bit(WORK_STRUCT_DELAYED_BIT
, work_data_bits(work
));
1043 static void pwq_activate_first_delayed(struct pool_workqueue
*pwq
)
1045 struct work_struct
*work
= list_first_entry(&pwq
->delayed_works
,
1046 struct work_struct
, entry
);
1048 pwq_activate_delayed_work(work
);
1052 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1053 * @pwq: pwq of interest
1054 * @color: color of work which left the queue
1056 * A work either has completed or is removed from pending queue,
1057 * decrement nr_in_flight of its pwq and handle workqueue flushing.
1060 * spin_lock_irq(pool->lock).
1062 static void pwq_dec_nr_in_flight(struct pool_workqueue
*pwq
, int color
)
1064 /* uncolored work items don't participate in flushing or nr_active */
1065 if (color
== WORK_NO_COLOR
)
1068 pwq
->nr_in_flight
[color
]--;
1071 if (!list_empty(&pwq
->delayed_works
)) {
1072 /* one down, submit a delayed one */
1073 if (pwq
->nr_active
< pwq
->max_active
)
1074 pwq_activate_first_delayed(pwq
);
1077 /* is flush in progress and are we at the flushing tip? */
1078 if (likely(pwq
->flush_color
!= color
))
1081 /* are there still in-flight works? */
1082 if (pwq
->nr_in_flight
[color
])
1085 /* this pwq is done, clear flush_color */
1086 pwq
->flush_color
= -1;
1089 * If this was the last pwq, wake up the first flusher. It
1090 * will handle the rest.
1092 if (atomic_dec_and_test(&pwq
->wq
->nr_pwqs_to_flush
))
1093 complete(&pwq
->wq
->first_flusher
->done
);
1099 * try_to_grab_pending - steal work item from worklist and disable irq
1100 * @work: work item to steal
1101 * @is_dwork: @work is a delayed_work
1102 * @flags: place to store irq state
1104 * Try to grab PENDING bit of @work. This function can handle @work in any
1105 * stable state - idle, on timer or on worklist. Return values are
1107 * 1 if @work was pending and we successfully stole PENDING
1108 * 0 if @work was idle and we claimed PENDING
1109 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1110 * -ENOENT if someone else is canceling @work, this state may persist
1111 * for arbitrarily long
1113 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1114 * interrupted while holding PENDING and @work off queue, irq must be
1115 * disabled on entry. This, combined with delayed_work->timer being
1116 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1118 * On successful return, >= 0, irq is disabled and the caller is
1119 * responsible for releasing it using local_irq_restore(*@flags).
1121 * This function is safe to call from any context including IRQ handler.
1123 static int try_to_grab_pending(struct work_struct
*work
, bool is_dwork
,
1124 unsigned long *flags
)
1126 struct worker_pool
*pool
;
1127 struct pool_workqueue
*pwq
;
1129 local_irq_save(*flags
);
1131 /* try to steal the timer if it exists */
1133 struct delayed_work
*dwork
= to_delayed_work(work
);
1136 * dwork->timer is irqsafe. If del_timer() fails, it's
1137 * guaranteed that the timer is not queued anywhere and not
1138 * running on the local CPU.
1140 if (likely(del_timer(&dwork
->timer
)))
1144 /* try to claim PENDING the normal way */
1145 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(work
)))
1149 * The queueing is in progress, or it is already queued. Try to
1150 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1152 pool
= get_work_pool(work
);
1156 spin_lock(&pool
->lock
);
1158 * work->data is guaranteed to point to pwq only while the work
1159 * item is queued on pwq->wq, and both updating work->data to point
1160 * to pwq on queueing and to pool on dequeueing are done under
1161 * pwq->pool->lock. This in turn guarantees that, if work->data
1162 * points to pwq which is associated with a locked pool, the work
1163 * item is currently queued on that pool.
1165 pwq
= get_work_pwq(work
);
1166 if (pwq
&& pwq
->pool
== pool
) {
1167 debug_work_deactivate(work
);
1170 * A delayed work item cannot be grabbed directly because
1171 * it might have linked NO_COLOR work items which, if left
1172 * on the delayed_list, will confuse pwq->nr_active
1173 * management later on and cause stall. Make sure the work
1174 * item is activated before grabbing.
1176 if (*work_data_bits(work
) & WORK_STRUCT_DELAYED
)
1177 pwq_activate_delayed_work(work
);
1179 list_del_init(&work
->entry
);
1180 pwq_dec_nr_in_flight(get_work_pwq(work
), get_work_color(work
));
1182 /* work->data points to pwq iff queued, point to pool */
1183 set_work_pool_and_keep_pending(work
, pool
->id
);
1185 spin_unlock(&pool
->lock
);
1188 spin_unlock(&pool
->lock
);
1190 local_irq_restore(*flags
);
1191 if (work_is_canceling(work
))
1198 * insert_work - insert a work into a pool
1199 * @pwq: pwq @work belongs to
1200 * @work: work to insert
1201 * @head: insertion point
1202 * @extra_flags: extra WORK_STRUCT_* flags to set
1204 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
1205 * work_struct flags.
1208 * spin_lock_irq(pool->lock).
1210 static void insert_work(struct pool_workqueue
*pwq
, struct work_struct
*work
,
1211 struct list_head
*head
, unsigned int extra_flags
)
1213 struct worker_pool
*pool
= pwq
->pool
;
1215 /* we own @work, set data and link */
1216 set_work_pwq(work
, pwq
, extra_flags
);
1217 list_add_tail(&work
->entry
, head
);
1221 * Ensure either wq_worker_sleeping() sees the above
1222 * list_add_tail() or we see zero nr_running to avoid workers lying
1223 * around lazily while there are works to be processed.
1227 if (__need_more_worker(pool
))
1228 wake_up_worker(pool
);
1232 * Test whether @work is being queued from another work executing on the
1235 static bool is_chained_work(struct workqueue_struct
*wq
)
1237 struct worker
*worker
;
1239 worker
= current_wq_worker();
1241 * Return %true iff I'm a worker execuing a work item on @wq. If
1242 * I'm @worker, it's safe to dereference it without locking.
1244 return worker
&& worker
->current_pwq
->wq
== wq
;
1247 static void __queue_work(int cpu
, struct workqueue_struct
*wq
,
1248 struct work_struct
*work
)
1250 struct pool_workqueue
*pwq
;
1251 struct worker_pool
*last_pool
;
1252 struct list_head
*worklist
;
1253 unsigned int work_flags
;
1254 unsigned int req_cpu
= cpu
;
1257 * While a work item is PENDING && off queue, a task trying to
1258 * steal the PENDING will busy-loop waiting for it to either get
1259 * queued or lose PENDING. Grabbing PENDING and queueing should
1260 * happen with IRQ disabled.
1262 WARN_ON_ONCE(!irqs_disabled());
1264 debug_work_activate(work
);
1266 /* if dying, only works from the same workqueue are allowed */
1267 if (unlikely(wq
->flags
& __WQ_DRAINING
) &&
1268 WARN_ON_ONCE(!is_chained_work(wq
)))
1271 /* pwq which will be used unless @work is executing elsewhere */
1272 if (!(wq
->flags
& WQ_UNBOUND
)) {
1273 if (cpu
== WORK_CPU_UNBOUND
)
1274 cpu
= raw_smp_processor_id();
1275 pwq
= per_cpu_ptr(wq
->cpu_pwqs
, cpu
);
1277 pwq
= first_pwq(wq
);
1281 * If @work was previously on a different pool, it might still be
1282 * running there, in which case the work needs to be queued on that
1283 * pool to guarantee non-reentrancy.
1285 last_pool
= get_work_pool(work
);
1286 if (last_pool
&& last_pool
!= pwq
->pool
) {
1287 struct worker
*worker
;
1289 spin_lock(&last_pool
->lock
);
1291 worker
= find_worker_executing_work(last_pool
, work
);
1293 if (worker
&& worker
->current_pwq
->wq
== wq
) {
1294 pwq
= worker
->current_pwq
;
1296 /* meh... not running there, queue here */
1297 spin_unlock(&last_pool
->lock
);
1298 spin_lock(&pwq
->pool
->lock
);
1301 spin_lock(&pwq
->pool
->lock
);
1305 * pwq is determined and locked. For unbound pools, we could have
1306 * raced with pwq release and it could already be dead. If its
1307 * refcnt is zero, repeat pwq selection. Note that pwqs never die
1308 * without another pwq replacing it as the first pwq or while a
1309 * work item is executing on it, so the retying is guaranteed to
1310 * make forward-progress.
1312 if (unlikely(!pwq
->refcnt
)) {
1313 if (wq
->flags
& WQ_UNBOUND
) {
1314 spin_unlock(&pwq
->pool
->lock
);
1319 WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
1323 /* pwq determined, queue */
1324 trace_workqueue_queue_work(req_cpu
, pwq
, work
);
1326 if (WARN_ON(!list_empty(&work
->entry
))) {
1327 spin_unlock(&pwq
->pool
->lock
);
1331 pwq
->nr_in_flight
[pwq
->work_color
]++;
1332 work_flags
= work_color_to_flags(pwq
->work_color
);
1334 if (likely(pwq
->nr_active
< pwq
->max_active
)) {
1335 trace_workqueue_activate_work(work
);
1337 worklist
= &pwq
->pool
->worklist
;
1339 work_flags
|= WORK_STRUCT_DELAYED
;
1340 worklist
= &pwq
->delayed_works
;
1343 insert_work(pwq
, work
, worklist
, work_flags
);
1345 spin_unlock(&pwq
->pool
->lock
);
1349 * queue_work_on - queue work on specific cpu
1350 * @cpu: CPU number to execute work on
1351 * @wq: workqueue to use
1352 * @work: work to queue
1354 * Returns %false if @work was already on a queue, %true otherwise.
1356 * We queue the work to a specific CPU, the caller must ensure it
1359 bool queue_work_on(int cpu
, struct workqueue_struct
*wq
,
1360 struct work_struct
*work
)
1363 unsigned long flags
;
1365 local_irq_save(flags
);
1367 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(work
))) {
1368 __queue_work(cpu
, wq
, work
);
1372 local_irq_restore(flags
);
1375 EXPORT_SYMBOL_GPL(queue_work_on
);
1377 void delayed_work_timer_fn(unsigned long __data
)
1379 struct delayed_work
*dwork
= (struct delayed_work
*)__data
;
1381 /* should have been called from irqsafe timer with irq already off */
1382 __queue_work(dwork
->cpu
, dwork
->wq
, &dwork
->work
);
1384 EXPORT_SYMBOL(delayed_work_timer_fn
);
1386 static void __queue_delayed_work(int cpu
, struct workqueue_struct
*wq
,
1387 struct delayed_work
*dwork
, unsigned long delay
)
1389 struct timer_list
*timer
= &dwork
->timer
;
1390 struct work_struct
*work
= &dwork
->work
;
1392 WARN_ON_ONCE(timer
->function
!= delayed_work_timer_fn
||
1393 timer
->data
!= (unsigned long)dwork
);
1394 WARN_ON_ONCE(timer_pending(timer
));
1395 WARN_ON_ONCE(!list_empty(&work
->entry
));
1398 * If @delay is 0, queue @dwork->work immediately. This is for
1399 * both optimization and correctness. The earliest @timer can
1400 * expire is on the closest next tick and delayed_work users depend
1401 * on that there's no such delay when @delay is 0.
1404 __queue_work(cpu
, wq
, &dwork
->work
);
1408 timer_stats_timer_set_start_info(&dwork
->timer
);
1412 timer
->expires
= jiffies
+ delay
;
1414 if (unlikely(cpu
!= WORK_CPU_UNBOUND
))
1415 add_timer_on(timer
, cpu
);
1421 * queue_delayed_work_on - queue work on specific CPU after delay
1422 * @cpu: CPU number to execute work on
1423 * @wq: workqueue to use
1424 * @dwork: work to queue
1425 * @delay: number of jiffies to wait before queueing
1427 * Returns %false if @work was already on a queue, %true otherwise. If
1428 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1431 bool queue_delayed_work_on(int cpu
, struct workqueue_struct
*wq
,
1432 struct delayed_work
*dwork
, unsigned long delay
)
1434 struct work_struct
*work
= &dwork
->work
;
1436 unsigned long flags
;
1438 /* read the comment in __queue_work() */
1439 local_irq_save(flags
);
1441 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(work
))) {
1442 __queue_delayed_work(cpu
, wq
, dwork
, delay
);
1446 local_irq_restore(flags
);
1449 EXPORT_SYMBOL_GPL(queue_delayed_work_on
);
1452 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1453 * @cpu: CPU number to execute work on
1454 * @wq: workqueue to use
1455 * @dwork: work to queue
1456 * @delay: number of jiffies to wait before queueing
1458 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1459 * modify @dwork's timer so that it expires after @delay. If @delay is
1460 * zero, @work is guaranteed to be scheduled immediately regardless of its
1463 * Returns %false if @dwork was idle and queued, %true if @dwork was
1464 * pending and its timer was modified.
1466 * This function is safe to call from any context including IRQ handler.
1467 * See try_to_grab_pending() for details.
1469 bool mod_delayed_work_on(int cpu
, struct workqueue_struct
*wq
,
1470 struct delayed_work
*dwork
, unsigned long delay
)
1472 unsigned long flags
;
1476 ret
= try_to_grab_pending(&dwork
->work
, true, &flags
);
1477 } while (unlikely(ret
== -EAGAIN
));
1479 if (likely(ret
>= 0)) {
1480 __queue_delayed_work(cpu
, wq
, dwork
, delay
);
1481 local_irq_restore(flags
);
1484 /* -ENOENT from try_to_grab_pending() becomes %true */
1487 EXPORT_SYMBOL_GPL(mod_delayed_work_on
);
1490 * worker_enter_idle - enter idle state
1491 * @worker: worker which is entering idle state
1493 * @worker is entering idle state. Update stats and idle timer if
1497 * spin_lock_irq(pool->lock).
1499 static void worker_enter_idle(struct worker
*worker
)
1501 struct worker_pool
*pool
= worker
->pool
;
1503 if (WARN_ON_ONCE(worker
->flags
& WORKER_IDLE
) ||
1504 WARN_ON_ONCE(!list_empty(&worker
->entry
) &&
1505 (worker
->hentry
.next
|| worker
->hentry
.pprev
)))
1508 /* can't use worker_set_flags(), also called from start_worker() */
1509 worker
->flags
|= WORKER_IDLE
;
1511 worker
->last_active
= jiffies
;
1513 /* idle_list is LIFO */
1514 list_add(&worker
->entry
, &pool
->idle_list
);
1516 if (too_many_workers(pool
) && !timer_pending(&pool
->idle_timer
))
1517 mod_timer(&pool
->idle_timer
, jiffies
+ IDLE_WORKER_TIMEOUT
);
1520 * Sanity check nr_running. Because wq_unbind_fn() releases
1521 * pool->lock between setting %WORKER_UNBOUND and zapping
1522 * nr_running, the warning may trigger spuriously. Check iff
1523 * unbind is not in progress.
1525 WARN_ON_ONCE(!(pool
->flags
& POOL_DISASSOCIATED
) &&
1526 pool
->nr_workers
== pool
->nr_idle
&&
1527 atomic_read(&pool
->nr_running
));
1531 * worker_leave_idle - leave idle state
1532 * @worker: worker which is leaving idle state
1534 * @worker is leaving idle state. Update stats.
1537 * spin_lock_irq(pool->lock).
1539 static void worker_leave_idle(struct worker
*worker
)
1541 struct worker_pool
*pool
= worker
->pool
;
1543 if (WARN_ON_ONCE(!(worker
->flags
& WORKER_IDLE
)))
1545 worker_clr_flags(worker
, WORKER_IDLE
);
1547 list_del_init(&worker
->entry
);
1551 * worker_maybe_bind_and_lock - try to bind %current to worker_pool and lock it
1552 * @pool: target worker_pool
1554 * Bind %current to the cpu of @pool if it is associated and lock @pool.
1556 * Works which are scheduled while the cpu is online must at least be
1557 * scheduled to a worker which is bound to the cpu so that if they are
1558 * flushed from cpu callbacks while cpu is going down, they are
1559 * guaranteed to execute on the cpu.
1561 * This function is to be used by unbound workers and rescuers to bind
1562 * themselves to the target cpu and may race with cpu going down or
1563 * coming online. kthread_bind() can't be used because it may put the
1564 * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1565 * verbatim as it's best effort and blocking and pool may be
1566 * [dis]associated in the meantime.
1568 * This function tries set_cpus_allowed() and locks pool and verifies the
1569 * binding against %POOL_DISASSOCIATED which is set during
1570 * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
1571 * enters idle state or fetches works without dropping lock, it can
1572 * guarantee the scheduling requirement described in the first paragraph.
1575 * Might sleep. Called without any lock but returns with pool->lock
1579 * %true if the associated pool is online (@worker is successfully
1580 * bound), %false if offline.
1582 static bool worker_maybe_bind_and_lock(struct worker_pool
*pool
)
1583 __acquires(&pool
->lock
)
1587 * The following call may fail, succeed or succeed
1588 * without actually migrating the task to the cpu if
1589 * it races with cpu hotunplug operation. Verify
1590 * against POOL_DISASSOCIATED.
1592 if (!(pool
->flags
& POOL_DISASSOCIATED
))
1593 set_cpus_allowed_ptr(current
, pool
->attrs
->cpumask
);
1595 spin_lock_irq(&pool
->lock
);
1596 if (pool
->flags
& POOL_DISASSOCIATED
)
1598 if (task_cpu(current
) == pool
->cpu
&&
1599 cpumask_equal(¤t
->cpus_allowed
, pool
->attrs
->cpumask
))
1601 spin_unlock_irq(&pool
->lock
);
1604 * We've raced with CPU hot[un]plug. Give it a breather
1605 * and retry migration. cond_resched() is required here;
1606 * otherwise, we might deadlock against cpu_stop trying to
1607 * bring down the CPU on non-preemptive kernel.
1614 static struct worker
*alloc_worker(void)
1616 struct worker
*worker
;
1618 worker
= kzalloc(sizeof(*worker
), GFP_KERNEL
);
1620 INIT_LIST_HEAD(&worker
->entry
);
1621 INIT_LIST_HEAD(&worker
->scheduled
);
1622 /* on creation a worker is in !idle && prep state */
1623 worker
->flags
= WORKER_PREP
;
1629 * create_worker - create a new workqueue worker
1630 * @pool: pool the new worker will belong to
1632 * Create a new worker which is bound to @pool. The returned worker
1633 * can be started by calling start_worker() or destroyed using
1637 * Might sleep. Does GFP_KERNEL allocations.
1640 * Pointer to the newly created worker.
1642 static struct worker
*create_worker(struct worker_pool
*pool
)
1644 const char *pri
= pool
->attrs
->nice
< 0 ? "H" : "";
1645 struct worker
*worker
= NULL
;
1648 lockdep_assert_held(&pool
->manager_mutex
);
1651 * ID is needed to determine kthread name. Allocate ID first
1652 * without installing the pointer.
1654 idr_preload(GFP_KERNEL
);
1655 spin_lock_irq(&pool
->lock
);
1657 id
= idr_alloc(&pool
->worker_idr
, NULL
, 0, 0, GFP_NOWAIT
);
1659 spin_unlock_irq(&pool
->lock
);
1664 worker
= alloc_worker();
1668 worker
->pool
= pool
;
1672 worker
->task
= kthread_create_on_node(worker_thread
,
1673 worker
, cpu_to_node(pool
->cpu
),
1674 "kworker/%d:%d%s", pool
->cpu
, id
, pri
);
1676 worker
->task
= kthread_create(worker_thread
, worker
,
1679 if (IS_ERR(worker
->task
))
1683 * set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
1684 * online CPUs. It'll be re-applied when any of the CPUs come up.
1686 set_user_nice(worker
->task
, pool
->attrs
->nice
);
1687 set_cpus_allowed_ptr(worker
->task
, pool
->attrs
->cpumask
);
1689 /* prevent userland from meddling with cpumask of workqueue workers */
1690 worker
->task
->flags
|= PF_NO_SETAFFINITY
;
1693 * The caller is responsible for ensuring %POOL_DISASSOCIATED
1694 * remains stable across this function. See the comments above the
1695 * flag definition for details.
1697 if (pool
->flags
& POOL_DISASSOCIATED
)
1698 worker
->flags
|= WORKER_UNBOUND
;
1700 /* successful, commit the pointer to idr */
1701 spin_lock_irq(&pool
->lock
);
1702 idr_replace(&pool
->worker_idr
, worker
, worker
->id
);
1703 spin_unlock_irq(&pool
->lock
);
1709 spin_lock_irq(&pool
->lock
);
1710 idr_remove(&pool
->worker_idr
, id
);
1711 spin_unlock_irq(&pool
->lock
);
1718 * start_worker - start a newly created worker
1719 * @worker: worker to start
1721 * Make the pool aware of @worker and start it.
1724 * spin_lock_irq(pool->lock).
1726 static void start_worker(struct worker
*worker
)
1728 worker
->flags
|= WORKER_STARTED
;
1729 worker
->pool
->nr_workers
++;
1730 worker_enter_idle(worker
);
1731 wake_up_process(worker
->task
);
1735 * create_and_start_worker - create and start a worker for a pool
1736 * @pool: the target pool
1738 * Grab the managership of @pool and create and start a new worker for it.
1740 static int create_and_start_worker(struct worker_pool
*pool
)
1742 struct worker
*worker
;
1744 mutex_lock(&pool
->manager_mutex
);
1746 worker
= create_worker(pool
);
1748 spin_lock_irq(&pool
->lock
);
1749 start_worker(worker
);
1750 spin_unlock_irq(&pool
->lock
);
1753 mutex_unlock(&pool
->manager_mutex
);
1755 return worker
? 0 : -ENOMEM
;
1759 * destroy_worker - destroy a workqueue worker
1760 * @worker: worker to be destroyed
1762 * Destroy @worker and adjust @pool stats accordingly.
1765 * spin_lock_irq(pool->lock) which is released and regrabbed.
1767 static void destroy_worker(struct worker
*worker
)
1769 struct worker_pool
*pool
= worker
->pool
;
1771 lockdep_assert_held(&pool
->manager_mutex
);
1772 lockdep_assert_held(&pool
->lock
);
1774 /* sanity check frenzy */
1775 if (WARN_ON(worker
->current_work
) ||
1776 WARN_ON(!list_empty(&worker
->scheduled
)))
1779 if (worker
->flags
& WORKER_STARTED
)
1781 if (worker
->flags
& WORKER_IDLE
)
1784 list_del_init(&worker
->entry
);
1785 worker
->flags
|= WORKER_DIE
;
1787 idr_remove(&pool
->worker_idr
, worker
->id
);
1789 spin_unlock_irq(&pool
->lock
);
1791 kthread_stop(worker
->task
);
1794 spin_lock_irq(&pool
->lock
);
1797 static void idle_worker_timeout(unsigned long __pool
)
1799 struct worker_pool
*pool
= (void *)__pool
;
1801 spin_lock_irq(&pool
->lock
);
1803 if (too_many_workers(pool
)) {
1804 struct worker
*worker
;
1805 unsigned long expires
;
1807 /* idle_list is kept in LIFO order, check the last one */
1808 worker
= list_entry(pool
->idle_list
.prev
, struct worker
, entry
);
1809 expires
= worker
->last_active
+ IDLE_WORKER_TIMEOUT
;
1811 if (time_before(jiffies
, expires
))
1812 mod_timer(&pool
->idle_timer
, expires
);
1814 /* it's been idle for too long, wake up manager */
1815 pool
->flags
|= POOL_MANAGE_WORKERS
;
1816 wake_up_worker(pool
);
1820 spin_unlock_irq(&pool
->lock
);
1823 static void send_mayday(struct work_struct
*work
)
1825 struct pool_workqueue
*pwq
= get_work_pwq(work
);
1826 struct workqueue_struct
*wq
= pwq
->wq
;
1828 lockdep_assert_held(&wq_mayday_lock
);
1833 /* mayday mayday mayday */
1834 if (list_empty(&pwq
->mayday_node
)) {
1835 list_add_tail(&pwq
->mayday_node
, &wq
->maydays
);
1836 wake_up_process(wq
->rescuer
->task
);
1840 static void pool_mayday_timeout(unsigned long __pool
)
1842 struct worker_pool
*pool
= (void *)__pool
;
1843 struct work_struct
*work
;
1845 spin_lock_irq(&wq_mayday_lock
); /* for wq->maydays */
1846 spin_lock(&pool
->lock
);
1848 if (need_to_create_worker(pool
)) {
1850 * We've been trying to create a new worker but
1851 * haven't been successful. We might be hitting an
1852 * allocation deadlock. Send distress signals to
1855 list_for_each_entry(work
, &pool
->worklist
, entry
)
1859 spin_unlock(&pool
->lock
);
1860 spin_unlock_irq(&wq_mayday_lock
);
1862 mod_timer(&pool
->mayday_timer
, jiffies
+ MAYDAY_INTERVAL
);
1866 * maybe_create_worker - create a new worker if necessary
1867 * @pool: pool to create a new worker for
1869 * Create a new worker for @pool if necessary. @pool is guaranteed to
1870 * have at least one idle worker on return from this function. If
1871 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1872 * sent to all rescuers with works scheduled on @pool to resolve
1873 * possible allocation deadlock.
1875 * On return, need_to_create_worker() is guaranteed to be %false and
1876 * may_start_working() %true.
1879 * spin_lock_irq(pool->lock) which may be released and regrabbed
1880 * multiple times. Does GFP_KERNEL allocations. Called only from
1884 * %false if no action was taken and pool->lock stayed locked, %true
1887 static bool maybe_create_worker(struct worker_pool
*pool
)
1888 __releases(&pool
->lock
)
1889 __acquires(&pool
->lock
)
1891 if (!need_to_create_worker(pool
))
1894 spin_unlock_irq(&pool
->lock
);
1896 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1897 mod_timer(&pool
->mayday_timer
, jiffies
+ MAYDAY_INITIAL_TIMEOUT
);
1900 struct worker
*worker
;
1902 worker
= create_worker(pool
);
1904 del_timer_sync(&pool
->mayday_timer
);
1905 spin_lock_irq(&pool
->lock
);
1906 start_worker(worker
);
1907 if (WARN_ON_ONCE(need_to_create_worker(pool
)))
1912 if (!need_to_create_worker(pool
))
1915 __set_current_state(TASK_INTERRUPTIBLE
);
1916 schedule_timeout(CREATE_COOLDOWN
);
1918 if (!need_to_create_worker(pool
))
1922 del_timer_sync(&pool
->mayday_timer
);
1923 spin_lock_irq(&pool
->lock
);
1924 if (need_to_create_worker(pool
))
1930 * maybe_destroy_worker - destroy workers which have been idle for a while
1931 * @pool: pool to destroy workers for
1933 * Destroy @pool workers which have been idle for longer than
1934 * IDLE_WORKER_TIMEOUT.
1937 * spin_lock_irq(pool->lock) which may be released and regrabbed
1938 * multiple times. Called only from manager.
1941 * %false if no action was taken and pool->lock stayed locked, %true
1944 static bool maybe_destroy_workers(struct worker_pool
*pool
)
1948 while (too_many_workers(pool
)) {
1949 struct worker
*worker
;
1950 unsigned long expires
;
1952 worker
= list_entry(pool
->idle_list
.prev
, struct worker
, entry
);
1953 expires
= worker
->last_active
+ IDLE_WORKER_TIMEOUT
;
1955 if (time_before(jiffies
, expires
)) {
1956 mod_timer(&pool
->idle_timer
, expires
);
1960 destroy_worker(worker
);
1968 * manage_workers - manage worker pool
1971 * Assume the manager role and manage the worker pool @worker belongs
1972 * to. At any given time, there can be only zero or one manager per
1973 * pool. The exclusion is handled automatically by this function.
1975 * The caller can safely start processing works on false return. On
1976 * true return, it's guaranteed that need_to_create_worker() is false
1977 * and may_start_working() is true.
1980 * spin_lock_irq(pool->lock) which may be released and regrabbed
1981 * multiple times. Does GFP_KERNEL allocations.
1984 * spin_lock_irq(pool->lock) which may be released and regrabbed
1985 * multiple times. Does GFP_KERNEL allocations.
1987 static bool manage_workers(struct worker
*worker
)
1989 struct worker_pool
*pool
= worker
->pool
;
1993 * Managership is governed by two mutexes - manager_arb and
1994 * manager_mutex. manager_arb handles arbitration of manager role.
1995 * Anyone who successfully grabs manager_arb wins the arbitration
1996 * and becomes the manager. mutex_trylock() on pool->manager_arb
1997 * failure while holding pool->lock reliably indicates that someone
1998 * else is managing the pool and the worker which failed trylock
1999 * can proceed to executing work items. This means that anyone
2000 * grabbing manager_arb is responsible for actually performing
2001 * manager duties. If manager_arb is grabbed and released without
2002 * actual management, the pool may stall indefinitely.
2004 * manager_mutex is used for exclusion of actual management
2005 * operations. The holder of manager_mutex can be sure that none
2006 * of management operations, including creation and destruction of
2007 * workers, won't take place until the mutex is released. Because
2008 * manager_mutex doesn't interfere with manager role arbitration,
2009 * it is guaranteed that the pool's management, while may be
2010 * delayed, won't be disturbed by someone else grabbing
2013 if (!mutex_trylock(&pool
->manager_arb
))
2017 * With manager arbitration won, manager_mutex would be free in
2018 * most cases. trylock first without dropping @pool->lock.
2020 if (unlikely(!mutex_trylock(&pool
->manager_mutex
))) {
2021 spin_unlock_irq(&pool
->lock
);
2022 mutex_lock(&pool
->manager_mutex
);
2026 pool
->flags
&= ~POOL_MANAGE_WORKERS
;
2029 * Destroy and then create so that may_start_working() is true
2032 ret
|= maybe_destroy_workers(pool
);
2033 ret
|= maybe_create_worker(pool
);
2035 mutex_unlock(&pool
->manager_mutex
);
2036 mutex_unlock(&pool
->manager_arb
);
2041 * process_one_work - process single work
2043 * @work: work to process
2045 * Process @work. This function contains all the logics necessary to
2046 * process a single work including synchronization against and
2047 * interaction with other workers on the same cpu, queueing and
2048 * flushing. As long as context requirement is met, any worker can
2049 * call this function to process a work.
2052 * spin_lock_irq(pool->lock) which is released and regrabbed.
2054 static void process_one_work(struct worker
*worker
, struct work_struct
*work
)
2055 __releases(&pool
->lock
)
2056 __acquires(&pool
->lock
)
2058 struct pool_workqueue
*pwq
= get_work_pwq(work
);
2059 struct worker_pool
*pool
= worker
->pool
;
2060 bool cpu_intensive
= pwq
->wq
->flags
& WQ_CPU_INTENSIVE
;
2062 struct worker
*collision
;
2063 #ifdef CONFIG_LOCKDEP
2065 * It is permissible to free the struct work_struct from
2066 * inside the function that is called from it, this we need to
2067 * take into account for lockdep too. To avoid bogus "held
2068 * lock freed" warnings as well as problems when looking into
2069 * work->lockdep_map, make a copy and use that here.
2071 struct lockdep_map lockdep_map
;
2073 lockdep_copy_map(&lockdep_map
, &work
->lockdep_map
);
2076 * Ensure we're on the correct CPU. DISASSOCIATED test is
2077 * necessary to avoid spurious warnings from rescuers servicing the
2078 * unbound or a disassociated pool.
2080 WARN_ON_ONCE(!(worker
->flags
& WORKER_UNBOUND
) &&
2081 !(pool
->flags
& POOL_DISASSOCIATED
) &&
2082 raw_smp_processor_id() != pool
->cpu
);
2085 * A single work shouldn't be executed concurrently by
2086 * multiple workers on a single cpu. Check whether anyone is
2087 * already processing the work. If so, defer the work to the
2088 * currently executing one.
2090 collision
= find_worker_executing_work(pool
, work
);
2091 if (unlikely(collision
)) {
2092 move_linked_works(work
, &collision
->scheduled
, NULL
);
2096 /* claim and dequeue */
2097 debug_work_deactivate(work
);
2098 hash_add(pool
->busy_hash
, &worker
->hentry
, (unsigned long)work
);
2099 worker
->current_work
= work
;
2100 worker
->current_func
= work
->func
;
2101 worker
->current_pwq
= pwq
;
2102 work_color
= get_work_color(work
);
2104 list_del_init(&work
->entry
);
2107 * CPU intensive works don't participate in concurrency
2108 * management. They're the scheduler's responsibility.
2110 if (unlikely(cpu_intensive
))
2111 worker_set_flags(worker
, WORKER_CPU_INTENSIVE
, true);
2114 * Unbound pool isn't concurrency managed and work items should be
2115 * executed ASAP. Wake up another worker if necessary.
2117 if ((worker
->flags
& WORKER_UNBOUND
) && need_more_worker(pool
))
2118 wake_up_worker(pool
);
2121 * Record the last pool and clear PENDING which should be the last
2122 * update to @work. Also, do this inside @pool->lock so that
2123 * PENDING and queued state changes happen together while IRQ is
2126 set_work_pool_and_clear_pending(work
, pool
->id
);
2128 spin_unlock_irq(&pool
->lock
);
2130 lock_map_acquire_read(&pwq
->wq
->lockdep_map
);
2131 lock_map_acquire(&lockdep_map
);
2132 trace_workqueue_execute_start(work
);
2133 worker
->current_func(work
);
2135 * While we must be careful to not use "work" after this, the trace
2136 * point will only record its address.
2138 trace_workqueue_execute_end(work
);
2139 lock_map_release(&lockdep_map
);
2140 lock_map_release(&pwq
->wq
->lockdep_map
);
2142 if (unlikely(in_atomic() || lockdep_depth(current
) > 0)) {
2143 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2144 " last function: %pf\n",
2145 current
->comm
, preempt_count(), task_pid_nr(current
),
2146 worker
->current_func
);
2147 debug_show_held_locks(current
);
2151 spin_lock_irq(&pool
->lock
);
2153 /* clear cpu intensive status */
2154 if (unlikely(cpu_intensive
))
2155 worker_clr_flags(worker
, WORKER_CPU_INTENSIVE
);
2157 /* we're done with it, release */
2158 hash_del(&worker
->hentry
);
2159 worker
->current_work
= NULL
;
2160 worker
->current_func
= NULL
;
2161 worker
->current_pwq
= NULL
;
2162 pwq_dec_nr_in_flight(pwq
, work_color
);
2166 * process_scheduled_works - process scheduled works
2169 * Process all scheduled works. Please note that the scheduled list
2170 * may change while processing a work, so this function repeatedly
2171 * fetches a work from the top and executes it.
2174 * spin_lock_irq(pool->lock) which may be released and regrabbed
2177 static void process_scheduled_works(struct worker
*worker
)
2179 while (!list_empty(&worker
->scheduled
)) {
2180 struct work_struct
*work
= list_first_entry(&worker
->scheduled
,
2181 struct work_struct
, entry
);
2182 process_one_work(worker
, work
);
2187 * worker_thread - the worker thread function
2190 * The worker thread function. All workers belong to a worker_pool -
2191 * either a per-cpu one or dynamic unbound one. These workers process all
2192 * work items regardless of their specific target workqueue. The only
2193 * exception is work items which belong to workqueues with a rescuer which
2194 * will be explained in rescuer_thread().
2196 static int worker_thread(void *__worker
)
2198 struct worker
*worker
= __worker
;
2199 struct worker_pool
*pool
= worker
->pool
;
2201 /* tell the scheduler that this is a workqueue worker */
2202 worker
->task
->flags
|= PF_WQ_WORKER
;
2204 spin_lock_irq(&pool
->lock
);
2206 /* am I supposed to die? */
2207 if (unlikely(worker
->flags
& WORKER_DIE
)) {
2208 spin_unlock_irq(&pool
->lock
);
2209 WARN_ON_ONCE(!list_empty(&worker
->entry
));
2210 worker
->task
->flags
&= ~PF_WQ_WORKER
;
2214 worker_leave_idle(worker
);
2216 /* no more worker necessary? */
2217 if (!need_more_worker(pool
))
2220 /* do we need to manage? */
2221 if (unlikely(!may_start_working(pool
)) && manage_workers(worker
))
2225 * ->scheduled list can only be filled while a worker is
2226 * preparing to process a work or actually processing it.
2227 * Make sure nobody diddled with it while I was sleeping.
2229 WARN_ON_ONCE(!list_empty(&worker
->scheduled
));
2232 * Finish PREP stage. We're guaranteed to have at least one idle
2233 * worker or that someone else has already assumed the manager
2234 * role. This is where @worker starts participating in concurrency
2235 * management if applicable and concurrency management is restored
2236 * after being rebound. See rebind_workers() for details.
2238 worker_clr_flags(worker
, WORKER_PREP
| WORKER_REBOUND
);
2241 struct work_struct
*work
=
2242 list_first_entry(&pool
->worklist
,
2243 struct work_struct
, entry
);
2245 if (likely(!(*work_data_bits(work
) & WORK_STRUCT_LINKED
))) {
2246 /* optimization path, not strictly necessary */
2247 process_one_work(worker
, work
);
2248 if (unlikely(!list_empty(&worker
->scheduled
)))
2249 process_scheduled_works(worker
);
2251 move_linked_works(work
, &worker
->scheduled
, NULL
);
2252 process_scheduled_works(worker
);
2254 } while (keep_working(pool
));
2256 worker_set_flags(worker
, WORKER_PREP
, false);
2258 if (unlikely(need_to_manage_workers(pool
)) && manage_workers(worker
))
2262 * pool->lock is held and there's no work to process and no need to
2263 * manage, sleep. Workers are woken up only while holding
2264 * pool->lock or from local cpu, so setting the current state
2265 * before releasing pool->lock is enough to prevent losing any
2268 worker_enter_idle(worker
);
2269 __set_current_state(TASK_INTERRUPTIBLE
);
2270 spin_unlock_irq(&pool
->lock
);
2276 * rescuer_thread - the rescuer thread function
2279 * Workqueue rescuer thread function. There's one rescuer for each
2280 * workqueue which has WQ_MEM_RECLAIM set.
2282 * Regular work processing on a pool may block trying to create a new
2283 * worker which uses GFP_KERNEL allocation which has slight chance of
2284 * developing into deadlock if some works currently on the same queue
2285 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2286 * the problem rescuer solves.
2288 * When such condition is possible, the pool summons rescuers of all
2289 * workqueues which have works queued on the pool and let them process
2290 * those works so that forward progress can be guaranteed.
2292 * This should happen rarely.
2294 static int rescuer_thread(void *__rescuer
)
2296 struct worker
*rescuer
= __rescuer
;
2297 struct workqueue_struct
*wq
= rescuer
->rescue_wq
;
2298 struct list_head
*scheduled
= &rescuer
->scheduled
;
2300 set_user_nice(current
, RESCUER_NICE_LEVEL
);
2303 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2304 * doesn't participate in concurrency management.
2306 rescuer
->task
->flags
|= PF_WQ_WORKER
;
2308 set_current_state(TASK_INTERRUPTIBLE
);
2310 if (kthread_should_stop()) {
2311 __set_current_state(TASK_RUNNING
);
2312 rescuer
->task
->flags
&= ~PF_WQ_WORKER
;
2316 /* see whether any pwq is asking for help */
2317 spin_lock_irq(&wq_mayday_lock
);
2319 while (!list_empty(&wq
->maydays
)) {
2320 struct pool_workqueue
*pwq
= list_first_entry(&wq
->maydays
,
2321 struct pool_workqueue
, mayday_node
);
2322 struct worker_pool
*pool
= pwq
->pool
;
2323 struct work_struct
*work
, *n
;
2325 __set_current_state(TASK_RUNNING
);
2326 list_del_init(&pwq
->mayday_node
);
2328 spin_unlock_irq(&wq_mayday_lock
);
2330 /* migrate to the target cpu if possible */
2331 worker_maybe_bind_and_lock(pool
);
2332 rescuer
->pool
= pool
;
2335 * Slurp in all works issued via this workqueue and
2338 WARN_ON_ONCE(!list_empty(&rescuer
->scheduled
));
2339 list_for_each_entry_safe(work
, n
, &pool
->worklist
, entry
)
2340 if (get_work_pwq(work
) == pwq
)
2341 move_linked_works(work
, scheduled
, &n
);
2343 process_scheduled_works(rescuer
);
2346 * Leave this pool. If keep_working() is %true, notify a
2347 * regular worker; otherwise, we end up with 0 concurrency
2348 * and stalling the execution.
2350 if (keep_working(pool
))
2351 wake_up_worker(pool
);
2353 rescuer
->pool
= NULL
;
2354 spin_unlock(&pool
->lock
);
2355 spin_lock(&wq_mayday_lock
);
2358 spin_unlock_irq(&wq_mayday_lock
);
2360 /* rescuers should never participate in concurrency management */
2361 WARN_ON_ONCE(!(rescuer
->flags
& WORKER_NOT_RUNNING
));
2367 struct work_struct work
;
2368 struct completion done
;
2371 static void wq_barrier_func(struct work_struct
*work
)
2373 struct wq_barrier
*barr
= container_of(work
, struct wq_barrier
, work
);
2374 complete(&barr
->done
);
2378 * insert_wq_barrier - insert a barrier work
2379 * @pwq: pwq to insert barrier into
2380 * @barr: wq_barrier to insert
2381 * @target: target work to attach @barr to
2382 * @worker: worker currently executing @target, NULL if @target is not executing
2384 * @barr is linked to @target such that @barr is completed only after
2385 * @target finishes execution. Please note that the ordering
2386 * guarantee is observed only with respect to @target and on the local
2389 * Currently, a queued barrier can't be canceled. This is because
2390 * try_to_grab_pending() can't determine whether the work to be
2391 * grabbed is at the head of the queue and thus can't clear LINKED
2392 * flag of the previous work while there must be a valid next work
2393 * after a work with LINKED flag set.
2395 * Note that when @worker is non-NULL, @target may be modified
2396 * underneath us, so we can't reliably determine pwq from @target.
2399 * spin_lock_irq(pool->lock).
2401 static void insert_wq_barrier(struct pool_workqueue
*pwq
,
2402 struct wq_barrier
*barr
,
2403 struct work_struct
*target
, struct worker
*worker
)
2405 struct list_head
*head
;
2406 unsigned int linked
= 0;
2409 * debugobject calls are safe here even with pool->lock locked
2410 * as we know for sure that this will not trigger any of the
2411 * checks and call back into the fixup functions where we
2414 INIT_WORK_ONSTACK(&barr
->work
, wq_barrier_func
);
2415 __set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(&barr
->work
));
2416 init_completion(&barr
->done
);
2419 * If @target is currently being executed, schedule the
2420 * barrier to the worker; otherwise, put it after @target.
2423 head
= worker
->scheduled
.next
;
2425 unsigned long *bits
= work_data_bits(target
);
2427 head
= target
->entry
.next
;
2428 /* there can already be other linked works, inherit and set */
2429 linked
= *bits
& WORK_STRUCT_LINKED
;
2430 __set_bit(WORK_STRUCT_LINKED_BIT
, bits
);
2433 debug_work_activate(&barr
->work
);
2434 insert_work(pwq
, &barr
->work
, head
,
2435 work_color_to_flags(WORK_NO_COLOR
) | linked
);
2439 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
2440 * @wq: workqueue being flushed
2441 * @flush_color: new flush color, < 0 for no-op
2442 * @work_color: new work color, < 0 for no-op
2444 * Prepare pwqs for workqueue flushing.
2446 * If @flush_color is non-negative, flush_color on all pwqs should be
2447 * -1. If no pwq has in-flight commands at the specified color, all
2448 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
2449 * has in flight commands, its pwq->flush_color is set to
2450 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
2451 * wakeup logic is armed and %true is returned.
2453 * The caller should have initialized @wq->first_flusher prior to
2454 * calling this function with non-negative @flush_color. If
2455 * @flush_color is negative, no flush color update is done and %false
2458 * If @work_color is non-negative, all pwqs should have the same
2459 * work_color which is previous to @work_color and all will be
2460 * advanced to @work_color.
2463 * mutex_lock(wq->flush_mutex).
2466 * %true if @flush_color >= 0 and there's something to flush. %false
2469 static bool flush_workqueue_prep_pwqs(struct workqueue_struct
*wq
,
2470 int flush_color
, int work_color
)
2473 struct pool_workqueue
*pwq
;
2475 if (flush_color
>= 0) {
2476 WARN_ON_ONCE(atomic_read(&wq
->nr_pwqs_to_flush
));
2477 atomic_set(&wq
->nr_pwqs_to_flush
, 1);
2480 local_irq_disable();
2482 for_each_pwq(pwq
, wq
) {
2483 struct worker_pool
*pool
= pwq
->pool
;
2485 spin_lock(&pool
->lock
);
2487 if (flush_color
>= 0) {
2488 WARN_ON_ONCE(pwq
->flush_color
!= -1);
2490 if (pwq
->nr_in_flight
[flush_color
]) {
2491 pwq
->flush_color
= flush_color
;
2492 atomic_inc(&wq
->nr_pwqs_to_flush
);
2497 if (work_color
>= 0) {
2498 WARN_ON_ONCE(work_color
!= work_next_color(pwq
->work_color
));
2499 pwq
->work_color
= work_color
;
2502 spin_unlock(&pool
->lock
);
2507 if (flush_color
>= 0 && atomic_dec_and_test(&wq
->nr_pwqs_to_flush
))
2508 complete(&wq
->first_flusher
->done
);
2514 * flush_workqueue - ensure that any scheduled work has run to completion.
2515 * @wq: workqueue to flush
2517 * This function sleeps until all work items which were queued on entry
2518 * have finished execution, but it is not livelocked by new incoming ones.
2520 void flush_workqueue(struct workqueue_struct
*wq
)
2522 struct wq_flusher this_flusher
= {
2523 .list
= LIST_HEAD_INIT(this_flusher
.list
),
2525 .done
= COMPLETION_INITIALIZER_ONSTACK(this_flusher
.done
),
2529 lock_map_acquire(&wq
->lockdep_map
);
2530 lock_map_release(&wq
->lockdep_map
);
2532 mutex_lock(&wq
->flush_mutex
);
2535 * Start-to-wait phase
2537 next_color
= work_next_color(wq
->work_color
);
2539 if (next_color
!= wq
->flush_color
) {
2541 * Color space is not full. The current work_color
2542 * becomes our flush_color and work_color is advanced
2545 WARN_ON_ONCE(!list_empty(&wq
->flusher_overflow
));
2546 this_flusher
.flush_color
= wq
->work_color
;
2547 wq
->work_color
= next_color
;
2549 if (!wq
->first_flusher
) {
2550 /* no flush in progress, become the first flusher */
2551 WARN_ON_ONCE(wq
->flush_color
!= this_flusher
.flush_color
);
2553 wq
->first_flusher
= &this_flusher
;
2555 if (!flush_workqueue_prep_pwqs(wq
, wq
->flush_color
,
2557 /* nothing to flush, done */
2558 wq
->flush_color
= next_color
;
2559 wq
->first_flusher
= NULL
;
2564 WARN_ON_ONCE(wq
->flush_color
== this_flusher
.flush_color
);
2565 list_add_tail(&this_flusher
.list
, &wq
->flusher_queue
);
2566 flush_workqueue_prep_pwqs(wq
, -1, wq
->work_color
);
2570 * Oops, color space is full, wait on overflow queue.
2571 * The next flush completion will assign us
2572 * flush_color and transfer to flusher_queue.
2574 list_add_tail(&this_flusher
.list
, &wq
->flusher_overflow
);
2577 mutex_unlock(&wq
->flush_mutex
);
2579 wait_for_completion(&this_flusher
.done
);
2582 * Wake-up-and-cascade phase
2584 * First flushers are responsible for cascading flushes and
2585 * handling overflow. Non-first flushers can simply return.
2587 if (wq
->first_flusher
!= &this_flusher
)
2590 mutex_lock(&wq
->flush_mutex
);
2592 /* we might have raced, check again with mutex held */
2593 if (wq
->first_flusher
!= &this_flusher
)
2596 wq
->first_flusher
= NULL
;
2598 WARN_ON_ONCE(!list_empty(&this_flusher
.list
));
2599 WARN_ON_ONCE(wq
->flush_color
!= this_flusher
.flush_color
);
2602 struct wq_flusher
*next
, *tmp
;
2604 /* complete all the flushers sharing the current flush color */
2605 list_for_each_entry_safe(next
, tmp
, &wq
->flusher_queue
, list
) {
2606 if (next
->flush_color
!= wq
->flush_color
)
2608 list_del_init(&next
->list
);
2609 complete(&next
->done
);
2612 WARN_ON_ONCE(!list_empty(&wq
->flusher_overflow
) &&
2613 wq
->flush_color
!= work_next_color(wq
->work_color
));
2615 /* this flush_color is finished, advance by one */
2616 wq
->flush_color
= work_next_color(wq
->flush_color
);
2618 /* one color has been freed, handle overflow queue */
2619 if (!list_empty(&wq
->flusher_overflow
)) {
2621 * Assign the same color to all overflowed
2622 * flushers, advance work_color and append to
2623 * flusher_queue. This is the start-to-wait
2624 * phase for these overflowed flushers.
2626 list_for_each_entry(tmp
, &wq
->flusher_overflow
, list
)
2627 tmp
->flush_color
= wq
->work_color
;
2629 wq
->work_color
= work_next_color(wq
->work_color
);
2631 list_splice_tail_init(&wq
->flusher_overflow
,
2632 &wq
->flusher_queue
);
2633 flush_workqueue_prep_pwqs(wq
, -1, wq
->work_color
);
2636 if (list_empty(&wq
->flusher_queue
)) {
2637 WARN_ON_ONCE(wq
->flush_color
!= wq
->work_color
);
2642 * Need to flush more colors. Make the next flusher
2643 * the new first flusher and arm pwqs.
2645 WARN_ON_ONCE(wq
->flush_color
== wq
->work_color
);
2646 WARN_ON_ONCE(wq
->flush_color
!= next
->flush_color
);
2648 list_del_init(&next
->list
);
2649 wq
->first_flusher
= next
;
2651 if (flush_workqueue_prep_pwqs(wq
, wq
->flush_color
, -1))
2655 * Meh... this color is already done, clear first
2656 * flusher and repeat cascading.
2658 wq
->first_flusher
= NULL
;
2662 mutex_unlock(&wq
->flush_mutex
);
2664 EXPORT_SYMBOL_GPL(flush_workqueue
);
2667 * drain_workqueue - drain a workqueue
2668 * @wq: workqueue to drain
2670 * Wait until the workqueue becomes empty. While draining is in progress,
2671 * only chain queueing is allowed. IOW, only currently pending or running
2672 * work items on @wq can queue further work items on it. @wq is flushed
2673 * repeatedly until it becomes empty. The number of flushing is detemined
2674 * by the depth of chaining and should be relatively short. Whine if it
2677 void drain_workqueue(struct workqueue_struct
*wq
)
2679 unsigned int flush_cnt
= 0;
2680 struct pool_workqueue
*pwq
;
2683 * __queue_work() needs to test whether there are drainers, is much
2684 * hotter than drain_workqueue() and already looks at @wq->flags.
2685 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
2687 mutex_lock(&wq_mutex
);
2688 if (!wq
->nr_drainers
++)
2689 wq
->flags
|= __WQ_DRAINING
;
2690 mutex_unlock(&wq_mutex
);
2692 flush_workqueue(wq
);
2694 local_irq_disable();
2696 for_each_pwq(pwq
, wq
) {
2699 spin_lock(&pwq
->pool
->lock
);
2700 drained
= !pwq
->nr_active
&& list_empty(&pwq
->delayed_works
);
2701 spin_unlock(&pwq
->pool
->lock
);
2706 if (++flush_cnt
== 10 ||
2707 (flush_cnt
% 100 == 0 && flush_cnt
<= 1000))
2708 pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
2709 wq
->name
, flush_cnt
);
2717 mutex_lock(&wq_mutex
);
2718 if (!--wq
->nr_drainers
)
2719 wq
->flags
&= ~__WQ_DRAINING
;
2720 mutex_unlock(&wq_mutex
);
2722 EXPORT_SYMBOL_GPL(drain_workqueue
);
2724 static bool start_flush_work(struct work_struct
*work
, struct wq_barrier
*barr
)
2726 struct worker
*worker
= NULL
;
2727 struct worker_pool
*pool
;
2728 struct pool_workqueue
*pwq
;
2732 local_irq_disable();
2733 pool
= get_work_pool(work
);
2739 spin_lock(&pool
->lock
);
2740 /* see the comment in try_to_grab_pending() with the same code */
2741 pwq
= get_work_pwq(work
);
2743 if (unlikely(pwq
->pool
!= pool
))
2746 worker
= find_worker_executing_work(pool
, work
);
2749 pwq
= worker
->current_pwq
;
2752 insert_wq_barrier(pwq
, barr
, work
, worker
);
2753 spin_unlock_irq(&pool
->lock
);
2756 * If @max_active is 1 or rescuer is in use, flushing another work
2757 * item on the same workqueue may lead to deadlock. Make sure the
2758 * flusher is not running on the same workqueue by verifying write
2761 if (pwq
->wq
->saved_max_active
== 1 || pwq
->wq
->rescuer
)
2762 lock_map_acquire(&pwq
->wq
->lockdep_map
);
2764 lock_map_acquire_read(&pwq
->wq
->lockdep_map
);
2765 lock_map_release(&pwq
->wq
->lockdep_map
);
2769 spin_unlock_irq(&pool
->lock
);
2774 * flush_work - wait for a work to finish executing the last queueing instance
2775 * @work: the work to flush
2777 * Wait until @work has finished execution. @work is guaranteed to be idle
2778 * on return if it hasn't been requeued since flush started.
2781 * %true if flush_work() waited for the work to finish execution,
2782 * %false if it was already idle.
2784 bool flush_work(struct work_struct
*work
)
2786 struct wq_barrier barr
;
2788 lock_map_acquire(&work
->lockdep_map
);
2789 lock_map_release(&work
->lockdep_map
);
2791 if (start_flush_work(work
, &barr
)) {
2792 wait_for_completion(&barr
.done
);
2793 destroy_work_on_stack(&barr
.work
);
2799 EXPORT_SYMBOL_GPL(flush_work
);
2801 static bool __cancel_work_timer(struct work_struct
*work
, bool is_dwork
)
2803 unsigned long flags
;
2807 ret
= try_to_grab_pending(work
, is_dwork
, &flags
);
2809 * If someone else is canceling, wait for the same event it
2810 * would be waiting for before retrying.
2812 if (unlikely(ret
== -ENOENT
))
2814 } while (unlikely(ret
< 0));
2816 /* tell other tasks trying to grab @work to back off */
2817 mark_work_canceling(work
);
2818 local_irq_restore(flags
);
2821 clear_work_data(work
);
2826 * cancel_work_sync - cancel a work and wait for it to finish
2827 * @work: the work to cancel
2829 * Cancel @work and wait for its execution to finish. This function
2830 * can be used even if the work re-queues itself or migrates to
2831 * another workqueue. On return from this function, @work is
2832 * guaranteed to be not pending or executing on any CPU.
2834 * cancel_work_sync(&delayed_work->work) must not be used for
2835 * delayed_work's. Use cancel_delayed_work_sync() instead.
2837 * The caller must ensure that the workqueue on which @work was last
2838 * queued can't be destroyed before this function returns.
2841 * %true if @work was pending, %false otherwise.
2843 bool cancel_work_sync(struct work_struct
*work
)
2845 return __cancel_work_timer(work
, false);
2847 EXPORT_SYMBOL_GPL(cancel_work_sync
);
2850 * flush_delayed_work - wait for a dwork to finish executing the last queueing
2851 * @dwork: the delayed work to flush
2853 * Delayed timer is cancelled and the pending work is queued for
2854 * immediate execution. Like flush_work(), this function only
2855 * considers the last queueing instance of @dwork.
2858 * %true if flush_work() waited for the work to finish execution,
2859 * %false if it was already idle.
2861 bool flush_delayed_work(struct delayed_work
*dwork
)
2863 local_irq_disable();
2864 if (del_timer_sync(&dwork
->timer
))
2865 __queue_work(dwork
->cpu
, dwork
->wq
, &dwork
->work
);
2867 return flush_work(&dwork
->work
);
2869 EXPORT_SYMBOL(flush_delayed_work
);
2872 * cancel_delayed_work - cancel a delayed work
2873 * @dwork: delayed_work to cancel
2875 * Kill off a pending delayed_work. Returns %true if @dwork was pending
2876 * and canceled; %false if wasn't pending. Note that the work callback
2877 * function may still be running on return, unless it returns %true and the
2878 * work doesn't re-arm itself. Explicitly flush or use
2879 * cancel_delayed_work_sync() to wait on it.
2881 * This function is safe to call from any context including IRQ handler.
2883 bool cancel_delayed_work(struct delayed_work
*dwork
)
2885 unsigned long flags
;
2889 ret
= try_to_grab_pending(&dwork
->work
, true, &flags
);
2890 } while (unlikely(ret
== -EAGAIN
));
2892 if (unlikely(ret
< 0))
2895 set_work_pool_and_clear_pending(&dwork
->work
,
2896 get_work_pool_id(&dwork
->work
));
2897 local_irq_restore(flags
);
2900 EXPORT_SYMBOL(cancel_delayed_work
);
2903 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2904 * @dwork: the delayed work cancel
2906 * This is cancel_work_sync() for delayed works.
2909 * %true if @dwork was pending, %false otherwise.
2911 bool cancel_delayed_work_sync(struct delayed_work
*dwork
)
2913 return __cancel_work_timer(&dwork
->work
, true);
2915 EXPORT_SYMBOL(cancel_delayed_work_sync
);
2918 * schedule_on_each_cpu - execute a function synchronously on each online CPU
2919 * @func: the function to call
2921 * schedule_on_each_cpu() executes @func on each online CPU using the
2922 * system workqueue and blocks until all CPUs have completed.
2923 * schedule_on_each_cpu() is very slow.
2926 * 0 on success, -errno on failure.
2928 int schedule_on_each_cpu(work_func_t func
)
2931 struct work_struct __percpu
*works
;
2933 works
= alloc_percpu(struct work_struct
);
2939 for_each_online_cpu(cpu
) {
2940 struct work_struct
*work
= per_cpu_ptr(works
, cpu
);
2942 INIT_WORK(work
, func
);
2943 schedule_work_on(cpu
, work
);
2946 for_each_online_cpu(cpu
)
2947 flush_work(per_cpu_ptr(works
, cpu
));
2955 * flush_scheduled_work - ensure that any scheduled work has run to completion.
2957 * Forces execution of the kernel-global workqueue and blocks until its
2960 * Think twice before calling this function! It's very easy to get into
2961 * trouble if you don't take great care. Either of the following situations
2962 * will lead to deadlock:
2964 * One of the work items currently on the workqueue needs to acquire
2965 * a lock held by your code or its caller.
2967 * Your code is running in the context of a work routine.
2969 * They will be detected by lockdep when they occur, but the first might not
2970 * occur very often. It depends on what work items are on the workqueue and
2971 * what locks they need, which you have no control over.
2973 * In most situations flushing the entire workqueue is overkill; you merely
2974 * need to know that a particular work item isn't queued and isn't running.
2975 * In such cases you should use cancel_delayed_work_sync() or
2976 * cancel_work_sync() instead.
2978 void flush_scheduled_work(void)
2980 flush_workqueue(system_wq
);
2982 EXPORT_SYMBOL(flush_scheduled_work
);
2985 * execute_in_process_context - reliably execute the routine with user context
2986 * @fn: the function to execute
2987 * @ew: guaranteed storage for the execute work structure (must
2988 * be available when the work executes)
2990 * Executes the function immediately if process context is available,
2991 * otherwise schedules the function for delayed execution.
2993 * Returns: 0 - function was executed
2994 * 1 - function was scheduled for execution
2996 int execute_in_process_context(work_func_t fn
, struct execute_work
*ew
)
2998 if (!in_interrupt()) {
3003 INIT_WORK(&ew
->work
, fn
);
3004 schedule_work(&ew
->work
);
3008 EXPORT_SYMBOL_GPL(execute_in_process_context
);
3012 * Workqueues with WQ_SYSFS flag set is visible to userland via
3013 * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
3014 * following attributes.
3016 * per_cpu RO bool : whether the workqueue is per-cpu or unbound
3017 * max_active RW int : maximum number of in-flight work items
3019 * Unbound workqueues have the following extra attributes.
3021 * id RO int : the associated pool ID
3022 * nice RW int : nice value of the workers
3023 * cpumask RW mask : bitmask of allowed CPUs for the workers
3026 struct workqueue_struct
*wq
;
3030 static struct workqueue_struct
*dev_to_wq(struct device
*dev
)
3032 struct wq_device
*wq_dev
= container_of(dev
, struct wq_device
, dev
);
3037 static ssize_t
wq_per_cpu_show(struct device
*dev
,
3038 struct device_attribute
*attr
, char *buf
)
3040 struct workqueue_struct
*wq
= dev_to_wq(dev
);
3042 return scnprintf(buf
, PAGE_SIZE
, "%d\n", (bool)!(wq
->flags
& WQ_UNBOUND
));
3045 static ssize_t
wq_max_active_show(struct device
*dev
,
3046 struct device_attribute
*attr
, char *buf
)
3048 struct workqueue_struct
*wq
= dev_to_wq(dev
);
3050 return scnprintf(buf
, PAGE_SIZE
, "%d\n", wq
->saved_max_active
);
3053 static ssize_t
wq_max_active_store(struct device
*dev
,
3054 struct device_attribute
*attr
,
3055 const char *buf
, size_t count
)
3057 struct workqueue_struct
*wq
= dev_to_wq(dev
);
3060 if (sscanf(buf
, "%d", &val
) != 1 || val
<= 0)
3063 workqueue_set_max_active(wq
, val
);
3067 static struct device_attribute wq_sysfs_attrs
[] = {
3068 __ATTR(per_cpu
, 0444, wq_per_cpu_show
, NULL
),
3069 __ATTR(max_active
, 0644, wq_max_active_show
, wq_max_active_store
),
3073 static ssize_t
wq_pool_id_show(struct device
*dev
,
3074 struct device_attribute
*attr
, char *buf
)
3076 struct workqueue_struct
*wq
= dev_to_wq(dev
);
3077 struct worker_pool
*pool
;
3080 rcu_read_lock_sched();
3081 pool
= first_pwq(wq
)->pool
;
3082 written
= scnprintf(buf
, PAGE_SIZE
, "%d\n", pool
->id
);
3083 rcu_read_unlock_sched();
3088 static ssize_t
wq_nice_show(struct device
*dev
, struct device_attribute
*attr
,
3091 struct workqueue_struct
*wq
= dev_to_wq(dev
);
3094 rcu_read_lock_sched();
3095 written
= scnprintf(buf
, PAGE_SIZE
, "%d\n",
3096 first_pwq(wq
)->pool
->attrs
->nice
);
3097 rcu_read_unlock_sched();
3102 /* prepare workqueue_attrs for sysfs store operations */
3103 static struct workqueue_attrs
*wq_sysfs_prep_attrs(struct workqueue_struct
*wq
)
3105 struct workqueue_attrs
*attrs
;
3107 attrs
= alloc_workqueue_attrs(GFP_KERNEL
);
3111 rcu_read_lock_sched();
3112 copy_workqueue_attrs(attrs
, first_pwq(wq
)->pool
->attrs
);
3113 rcu_read_unlock_sched();
3117 static ssize_t
wq_nice_store(struct device
*dev
, struct device_attribute
*attr
,
3118 const char *buf
, size_t count
)
3120 struct workqueue_struct
*wq
= dev_to_wq(dev
);
3121 struct workqueue_attrs
*attrs
;
3124 attrs
= wq_sysfs_prep_attrs(wq
);
3128 if (sscanf(buf
, "%d", &attrs
->nice
) == 1 &&
3129 attrs
->nice
>= -20 && attrs
->nice
<= 19)
3130 ret
= apply_workqueue_attrs(wq
, attrs
);
3134 free_workqueue_attrs(attrs
);
3135 return ret
?: count
;
3138 static ssize_t
wq_cpumask_show(struct device
*dev
,
3139 struct device_attribute
*attr
, char *buf
)
3141 struct workqueue_struct
*wq
= dev_to_wq(dev
);
3144 rcu_read_lock_sched();
3145 written
= cpumask_scnprintf(buf
, PAGE_SIZE
,
3146 first_pwq(wq
)->pool
->attrs
->cpumask
);
3147 rcu_read_unlock_sched();
3149 written
+= scnprintf(buf
+ written
, PAGE_SIZE
- written
, "\n");
3153 static ssize_t
wq_cpumask_store(struct device
*dev
,
3154 struct device_attribute
*attr
,
3155 const char *buf
, size_t count
)
3157 struct workqueue_struct
*wq
= dev_to_wq(dev
);
3158 struct workqueue_attrs
*attrs
;
3161 attrs
= wq_sysfs_prep_attrs(wq
);
3165 ret
= cpumask_parse(buf
, attrs
->cpumask
);
3167 ret
= apply_workqueue_attrs(wq
, attrs
);
3169 free_workqueue_attrs(attrs
);
3170 return ret
?: count
;
3173 static struct device_attribute wq_sysfs_unbound_attrs
[] = {
3174 __ATTR(pool_id
, 0444, wq_pool_id_show
, NULL
),
3175 __ATTR(nice
, 0644, wq_nice_show
, wq_nice_store
),
3176 __ATTR(cpumask
, 0644, wq_cpumask_show
, wq_cpumask_store
),
3180 static struct bus_type wq_subsys
= {
3181 .name
= "workqueue",
3182 .dev_attrs
= wq_sysfs_attrs
,
3185 static int __init
wq_sysfs_init(void)
3187 return subsys_virtual_register(&wq_subsys
, NULL
);
3189 core_initcall(wq_sysfs_init
);
3191 static void wq_device_release(struct device
*dev
)
3193 struct wq_device
*wq_dev
= container_of(dev
, struct wq_device
, dev
);
3199 * workqueue_sysfs_register - make a workqueue visible in sysfs
3200 * @wq: the workqueue to register
3202 * Expose @wq in sysfs under /sys/bus/workqueue/devices.
3203 * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
3204 * which is the preferred method.
3206 * Workqueue user should use this function directly iff it wants to apply
3207 * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
3208 * apply_workqueue_attrs() may race against userland updating the
3211 * Returns 0 on success, -errno on failure.
3213 int workqueue_sysfs_register(struct workqueue_struct
*wq
)
3215 struct wq_device
*wq_dev
;
3219 * Adjusting max_active or creating new pwqs by applyting
3220 * attributes breaks ordering guarantee. Disallow exposing ordered
3223 if (WARN_ON(wq
->flags
& __WQ_ORDERED
))
3226 wq
->wq_dev
= wq_dev
= kzalloc(sizeof(*wq_dev
), GFP_KERNEL
);
3231 wq_dev
->dev
.bus
= &wq_subsys
;
3232 wq_dev
->dev
.init_name
= wq
->name
;
3233 wq_dev
->dev
.release
= wq_device_release
;
3236 * unbound_attrs are created separately. Suppress uevent until
3237 * everything is ready.
3239 dev_set_uevent_suppress(&wq_dev
->dev
, true);
3241 ret
= device_register(&wq_dev
->dev
);
3248 if (wq
->flags
& WQ_UNBOUND
) {
3249 struct device_attribute
*attr
;
3251 for (attr
= wq_sysfs_unbound_attrs
; attr
->attr
.name
; attr
++) {
3252 ret
= device_create_file(&wq_dev
->dev
, attr
);
3254 device_unregister(&wq_dev
->dev
);
3261 kobject_uevent(&wq_dev
->dev
.kobj
, KOBJ_ADD
);
3266 * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
3267 * @wq: the workqueue to unregister
3269 * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
3271 static void workqueue_sysfs_unregister(struct workqueue_struct
*wq
)
3273 struct wq_device
*wq_dev
= wq
->wq_dev
;
3279 device_unregister(&wq_dev
->dev
);
3281 #else /* CONFIG_SYSFS */
3282 static void workqueue_sysfs_unregister(struct workqueue_struct
*wq
) { }
3283 #endif /* CONFIG_SYSFS */
3286 * free_workqueue_attrs - free a workqueue_attrs
3287 * @attrs: workqueue_attrs to free
3289 * Undo alloc_workqueue_attrs().
3291 void free_workqueue_attrs(struct workqueue_attrs
*attrs
)
3294 free_cpumask_var(attrs
->cpumask
);
3300 * alloc_workqueue_attrs - allocate a workqueue_attrs
3301 * @gfp_mask: allocation mask to use
3303 * Allocate a new workqueue_attrs, initialize with default settings and
3304 * return it. Returns NULL on failure.
3306 struct workqueue_attrs
*alloc_workqueue_attrs(gfp_t gfp_mask
)
3308 struct workqueue_attrs
*attrs
;
3310 attrs
= kzalloc(sizeof(*attrs
), gfp_mask
);
3313 if (!alloc_cpumask_var(&attrs
->cpumask
, gfp_mask
))
3316 cpumask_setall(attrs
->cpumask
);
3319 free_workqueue_attrs(attrs
);
3323 static void copy_workqueue_attrs(struct workqueue_attrs
*to
,
3324 const struct workqueue_attrs
*from
)
3326 to
->nice
= from
->nice
;
3327 cpumask_copy(to
->cpumask
, from
->cpumask
);
3331 * Hacky implementation of jhash of bitmaps which only considers the
3332 * specified number of bits. We probably want a proper implementation in
3333 * include/linux/jhash.h.
3335 static u32
jhash_bitmap(const unsigned long *bitmap
, int bits
, u32 hash
)
3337 int nr_longs
= bits
/ BITS_PER_LONG
;
3338 int nr_leftover
= bits
% BITS_PER_LONG
;
3339 unsigned long leftover
= 0;
3342 hash
= jhash(bitmap
, nr_longs
* sizeof(long), hash
);
3344 bitmap_copy(&leftover
, bitmap
+ nr_longs
, nr_leftover
);
3345 hash
= jhash(&leftover
, sizeof(long), hash
);
3350 /* hash value of the content of @attr */
3351 static u32
wqattrs_hash(const struct workqueue_attrs
*attrs
)
3355 hash
= jhash_1word(attrs
->nice
, hash
);
3356 hash
= jhash_bitmap(cpumask_bits(attrs
->cpumask
), nr_cpu_ids
, hash
);
3360 /* content equality test */
3361 static bool wqattrs_equal(const struct workqueue_attrs
*a
,
3362 const struct workqueue_attrs
*b
)
3364 if (a
->nice
!= b
->nice
)
3366 if (!cpumask_equal(a
->cpumask
, b
->cpumask
))
3372 * init_worker_pool - initialize a newly zalloc'd worker_pool
3373 * @pool: worker_pool to initialize
3375 * Initiailize a newly zalloc'd @pool. It also allocates @pool->attrs.
3376 * Returns 0 on success, -errno on failure. Even on failure, all fields
3377 * inside @pool proper are initialized and put_unbound_pool() can be called
3378 * on @pool safely to release it.
3380 static int init_worker_pool(struct worker_pool
*pool
)
3382 spin_lock_init(&pool
->lock
);
3385 pool
->flags
|= POOL_DISASSOCIATED
;
3386 INIT_LIST_HEAD(&pool
->worklist
);
3387 INIT_LIST_HEAD(&pool
->idle_list
);
3388 hash_init(pool
->busy_hash
);
3390 init_timer_deferrable(&pool
->idle_timer
);
3391 pool
->idle_timer
.function
= idle_worker_timeout
;
3392 pool
->idle_timer
.data
= (unsigned long)pool
;
3394 setup_timer(&pool
->mayday_timer
, pool_mayday_timeout
,
3395 (unsigned long)pool
);
3397 mutex_init(&pool
->manager_arb
);
3398 mutex_init(&pool
->manager_mutex
);
3399 idr_init(&pool
->worker_idr
);
3401 INIT_HLIST_NODE(&pool
->hash_node
);
3404 /* shouldn't fail above this point */
3405 pool
->attrs
= alloc_workqueue_attrs(GFP_KERNEL
);
3411 static void rcu_free_pool(struct rcu_head
*rcu
)
3413 struct worker_pool
*pool
= container_of(rcu
, struct worker_pool
, rcu
);
3415 idr_destroy(&pool
->worker_idr
);
3416 free_workqueue_attrs(pool
->attrs
);
3421 * put_unbound_pool - put a worker_pool
3422 * @pool: worker_pool to put
3424 * Put @pool. If its refcnt reaches zero, it gets destroyed in sched-RCU
3425 * safe manner. get_unbound_pool() calls this function on its failure path
3426 * and this function should be able to release pools which went through,
3427 * successfully or not, init_worker_pool().
3429 static void put_unbound_pool(struct worker_pool
*pool
)
3431 struct worker
*worker
;
3433 mutex_lock(&wq_mutex
);
3434 if (--pool
->refcnt
) {
3435 mutex_unlock(&wq_mutex
);
3440 if (WARN_ON(!(pool
->flags
& POOL_DISASSOCIATED
)) ||
3441 WARN_ON(!list_empty(&pool
->worklist
))) {
3442 mutex_unlock(&wq_mutex
);
3446 /* release id and unhash */
3448 idr_remove(&worker_pool_idr
, pool
->id
);
3449 hash_del(&pool
->hash_node
);
3451 mutex_unlock(&wq_mutex
);
3454 * Become the manager and destroy all workers. Grabbing
3455 * manager_arb prevents @pool's workers from blocking on
3458 mutex_lock(&pool
->manager_arb
);
3459 mutex_lock(&pool
->manager_mutex
);
3460 spin_lock_irq(&pool
->lock
);
3462 while ((worker
= first_worker(pool
)))
3463 destroy_worker(worker
);
3464 WARN_ON(pool
->nr_workers
|| pool
->nr_idle
);
3466 spin_unlock_irq(&pool
->lock
);
3467 mutex_unlock(&pool
->manager_mutex
);
3468 mutex_unlock(&pool
->manager_arb
);
3470 /* shut down the timers */
3471 del_timer_sync(&pool
->idle_timer
);
3472 del_timer_sync(&pool
->mayday_timer
);
3474 /* sched-RCU protected to allow dereferences from get_work_pool() */
3475 call_rcu_sched(&pool
->rcu
, rcu_free_pool
);
3479 * get_unbound_pool - get a worker_pool with the specified attributes
3480 * @attrs: the attributes of the worker_pool to get
3482 * Obtain a worker_pool which has the same attributes as @attrs, bump the
3483 * reference count and return it. If there already is a matching
3484 * worker_pool, it will be used; otherwise, this function attempts to
3485 * create a new one. On failure, returns NULL.
3487 static struct worker_pool
*get_unbound_pool(const struct workqueue_attrs
*attrs
)
3489 u32 hash
= wqattrs_hash(attrs
);
3490 struct worker_pool
*pool
;
3492 mutex_lock(&wq_mutex
);
3494 /* do we already have a matching pool? */
3495 hash_for_each_possible(unbound_pool_hash
, pool
, hash_node
, hash
) {
3496 if (wqattrs_equal(pool
->attrs
, attrs
)) {
3502 /* nope, create a new one */
3503 pool
= kzalloc(sizeof(*pool
), GFP_KERNEL
);
3504 if (!pool
|| init_worker_pool(pool
) < 0)
3507 if (workqueue_freezing
)
3508 pool
->flags
|= POOL_FREEZING
;
3510 lockdep_set_subclass(&pool
->lock
, 1); /* see put_pwq() */
3511 copy_workqueue_attrs(pool
->attrs
, attrs
);
3513 if (worker_pool_assign_id(pool
) < 0)
3516 /* create and start the initial worker */
3517 if (create_and_start_worker(pool
) < 0)
3521 hash_add(unbound_pool_hash
, &pool
->hash_node
, hash
);
3523 mutex_unlock(&wq_mutex
);
3526 mutex_unlock(&wq_mutex
);
3528 put_unbound_pool(pool
);
3532 static void rcu_free_pwq(struct rcu_head
*rcu
)
3534 kmem_cache_free(pwq_cache
,
3535 container_of(rcu
, struct pool_workqueue
, rcu
));
3539 * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
3540 * and needs to be destroyed.
3542 static void pwq_unbound_release_workfn(struct work_struct
*work
)
3544 struct pool_workqueue
*pwq
= container_of(work
, struct pool_workqueue
,
3545 unbound_release_work
);
3546 struct workqueue_struct
*wq
= pwq
->wq
;
3547 struct worker_pool
*pool
= pwq
->pool
;
3549 if (WARN_ON_ONCE(!(wq
->flags
& WQ_UNBOUND
)))
3553 * Unlink @pwq. Synchronization against flush_mutex isn't strictly
3554 * necessary on release but do it anyway. It's easier to verify
3555 * and consistent with the linking path.
3557 mutex_lock(&wq
->flush_mutex
);
3558 spin_lock_irq(&pwq_lock
);
3559 list_del_rcu(&pwq
->pwqs_node
);
3560 spin_unlock_irq(&pwq_lock
);
3561 mutex_unlock(&wq
->flush_mutex
);
3563 put_unbound_pool(pool
);
3564 call_rcu_sched(&pwq
->rcu
, rcu_free_pwq
);
3567 * If we're the last pwq going away, @wq is already dead and no one
3568 * is gonna access it anymore. Free it.
3570 if (list_empty(&wq
->pwqs
))
3575 * pwq_adjust_max_active - update a pwq's max_active to the current setting
3576 * @pwq: target pool_workqueue
3578 * If @pwq isn't freezing, set @pwq->max_active to the associated
3579 * workqueue's saved_max_active and activate delayed work items
3580 * accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
3582 static void pwq_adjust_max_active(struct pool_workqueue
*pwq
)
3584 struct workqueue_struct
*wq
= pwq
->wq
;
3585 bool freezable
= wq
->flags
& WQ_FREEZABLE
;
3587 /* for @wq->saved_max_active */
3588 lockdep_assert_held(&pwq_lock
);
3590 /* fast exit for non-freezable wqs */
3591 if (!freezable
&& pwq
->max_active
== wq
->saved_max_active
)
3594 spin_lock(&pwq
->pool
->lock
);
3596 if (!freezable
|| !(pwq
->pool
->flags
& POOL_FREEZING
)) {
3597 pwq
->max_active
= wq
->saved_max_active
;
3599 while (!list_empty(&pwq
->delayed_works
) &&
3600 pwq
->nr_active
< pwq
->max_active
)
3601 pwq_activate_first_delayed(pwq
);
3604 * Need to kick a worker after thawed or an unbound wq's
3605 * max_active is bumped. It's a slow path. Do it always.
3607 wake_up_worker(pwq
->pool
);
3609 pwq
->max_active
= 0;
3612 spin_unlock(&pwq
->pool
->lock
);
3615 static void init_and_link_pwq(struct pool_workqueue
*pwq
,
3616 struct workqueue_struct
*wq
,
3617 struct worker_pool
*pool
,
3618 struct pool_workqueue
**p_last_pwq
)
3620 BUG_ON((unsigned long)pwq
& WORK_STRUCT_FLAG_MASK
);
3624 pwq
->flush_color
= -1;
3626 INIT_LIST_HEAD(&pwq
->delayed_works
);
3627 INIT_LIST_HEAD(&pwq
->mayday_node
);
3628 INIT_WORK(&pwq
->unbound_release_work
, pwq_unbound_release_workfn
);
3630 mutex_lock(&wq
->flush_mutex
);
3631 spin_lock_irq(&pwq_lock
);
3634 * Set the matching work_color. This is synchronized with
3635 * flush_mutex to avoid confusing flush_workqueue().
3638 *p_last_pwq
= first_pwq(wq
);
3639 pwq
->work_color
= wq
->work_color
;
3641 /* sync max_active to the current setting */
3642 pwq_adjust_max_active(pwq
);
3645 list_add_rcu(&pwq
->pwqs_node
, &wq
->pwqs
);
3647 spin_unlock_irq(&pwq_lock
);
3648 mutex_unlock(&wq
->flush_mutex
);
3652 * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
3653 * @wq: the target workqueue
3654 * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
3656 * Apply @attrs to an unbound workqueue @wq. If @attrs doesn't match the
3657 * current attributes, a new pwq is created and made the first pwq which
3658 * will serve all new work items. Older pwqs are released as in-flight
3659 * work items finish. Note that a work item which repeatedly requeues
3660 * itself back-to-back will stay on its current pwq.
3662 * Performs GFP_KERNEL allocations. Returns 0 on success and -errno on
3665 int apply_workqueue_attrs(struct workqueue_struct
*wq
,
3666 const struct workqueue_attrs
*attrs
)
3668 struct pool_workqueue
*pwq
, *last_pwq
;
3669 struct worker_pool
*pool
;
3671 /* only unbound workqueues can change attributes */
3672 if (WARN_ON(!(wq
->flags
& WQ_UNBOUND
)))
3675 /* creating multiple pwqs breaks ordering guarantee */
3676 if (WARN_ON((wq
->flags
& __WQ_ORDERED
) && !list_empty(&wq
->pwqs
)))
3679 pwq
= kmem_cache_zalloc(pwq_cache
, GFP_KERNEL
);
3683 pool
= get_unbound_pool(attrs
);
3685 kmem_cache_free(pwq_cache
, pwq
);
3689 init_and_link_pwq(pwq
, wq
, pool
, &last_pwq
);
3691 spin_lock_irq(&last_pwq
->pool
->lock
);
3693 spin_unlock_irq(&last_pwq
->pool
->lock
);
3699 static int alloc_and_link_pwqs(struct workqueue_struct
*wq
)
3701 bool highpri
= wq
->flags
& WQ_HIGHPRI
;
3704 if (!(wq
->flags
& WQ_UNBOUND
)) {
3705 wq
->cpu_pwqs
= alloc_percpu(struct pool_workqueue
);
3709 for_each_possible_cpu(cpu
) {
3710 struct pool_workqueue
*pwq
=
3711 per_cpu_ptr(wq
->cpu_pwqs
, cpu
);
3712 struct worker_pool
*cpu_pools
=
3713 per_cpu(cpu_worker_pools
, cpu
);
3715 init_and_link_pwq(pwq
, wq
, &cpu_pools
[highpri
], NULL
);
3719 return apply_workqueue_attrs(wq
, unbound_std_wq_attrs
[highpri
]);
3723 static int wq_clamp_max_active(int max_active
, unsigned int flags
,
3726 int lim
= flags
& WQ_UNBOUND
? WQ_UNBOUND_MAX_ACTIVE
: WQ_MAX_ACTIVE
;
3728 if (max_active
< 1 || max_active
> lim
)
3729 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3730 max_active
, name
, 1, lim
);
3732 return clamp_val(max_active
, 1, lim
);
3735 struct workqueue_struct
*__alloc_workqueue_key(const char *fmt
,
3738 struct lock_class_key
*key
,
3739 const char *lock_name
, ...)
3741 va_list args
, args1
;
3742 struct workqueue_struct
*wq
;
3743 struct pool_workqueue
*pwq
;
3746 /* determine namelen, allocate wq and format name */
3747 va_start(args
, lock_name
);
3748 va_copy(args1
, args
);
3749 namelen
= vsnprintf(NULL
, 0, fmt
, args
) + 1;
3751 wq
= kzalloc(sizeof(*wq
) + namelen
, GFP_KERNEL
);
3755 vsnprintf(wq
->name
, namelen
, fmt
, args1
);
3759 max_active
= max_active
?: WQ_DFL_ACTIVE
;
3760 max_active
= wq_clamp_max_active(max_active
, flags
, wq
->name
);
3764 wq
->saved_max_active
= max_active
;
3765 mutex_init(&wq
->flush_mutex
);
3766 atomic_set(&wq
->nr_pwqs_to_flush
, 0);
3767 INIT_LIST_HEAD(&wq
->pwqs
);
3768 INIT_LIST_HEAD(&wq
->flusher_queue
);
3769 INIT_LIST_HEAD(&wq
->flusher_overflow
);
3770 INIT_LIST_HEAD(&wq
->maydays
);
3772 lockdep_init_map(&wq
->lockdep_map
, lock_name
, key
, 0);
3773 INIT_LIST_HEAD(&wq
->list
);
3775 if (alloc_and_link_pwqs(wq
) < 0)
3779 * Workqueues which may be used during memory reclaim should
3780 * have a rescuer to guarantee forward progress.
3782 if (flags
& WQ_MEM_RECLAIM
) {
3783 struct worker
*rescuer
;
3785 rescuer
= alloc_worker();
3789 rescuer
->rescue_wq
= wq
;
3790 rescuer
->task
= kthread_create(rescuer_thread
, rescuer
, "%s",
3792 if (IS_ERR(rescuer
->task
)) {
3797 wq
->rescuer
= rescuer
;
3798 rescuer
->task
->flags
|= PF_NO_SETAFFINITY
;
3799 wake_up_process(rescuer
->task
);
3802 if ((wq
->flags
& WQ_SYSFS
) && workqueue_sysfs_register(wq
))
3806 * wq_mutex protects global freeze state and workqueues list. Grab
3807 * it, adjust max_active and add the new @wq to workqueues list.
3809 mutex_lock(&wq_mutex
);
3811 spin_lock_irq(&pwq_lock
);
3812 for_each_pwq(pwq
, wq
)
3813 pwq_adjust_max_active(pwq
);
3814 spin_unlock_irq(&pwq_lock
);
3816 list_add(&wq
->list
, &workqueues
);
3818 mutex_unlock(&wq_mutex
);
3826 destroy_workqueue(wq
);
3829 EXPORT_SYMBOL_GPL(__alloc_workqueue_key
);
3832 * destroy_workqueue - safely terminate a workqueue
3833 * @wq: target workqueue
3835 * Safely destroy a workqueue. All work currently pending will be done first.
3837 void destroy_workqueue(struct workqueue_struct
*wq
)
3839 struct pool_workqueue
*pwq
;
3841 /* drain it before proceeding with destruction */
3842 drain_workqueue(wq
);
3845 spin_lock_irq(&pwq_lock
);
3846 for_each_pwq(pwq
, wq
) {
3849 for (i
= 0; i
< WORK_NR_COLORS
; i
++) {
3850 if (WARN_ON(pwq
->nr_in_flight
[i
])) {
3851 spin_unlock_irq(&pwq_lock
);
3856 if (WARN_ON(pwq
->refcnt
> 1) ||
3857 WARN_ON(pwq
->nr_active
) ||
3858 WARN_ON(!list_empty(&pwq
->delayed_works
))) {
3859 spin_unlock_irq(&pwq_lock
);
3863 spin_unlock_irq(&pwq_lock
);
3866 * wq list is used to freeze wq, remove from list after
3867 * flushing is complete in case freeze races us.
3869 mutex_lock(&wq_mutex
);
3870 list_del_init(&wq
->list
);
3871 mutex_unlock(&wq_mutex
);
3873 workqueue_sysfs_unregister(wq
);
3876 kthread_stop(wq
->rescuer
->task
);
3881 if (!(wq
->flags
& WQ_UNBOUND
)) {
3883 * The base ref is never dropped on per-cpu pwqs. Directly
3884 * free the pwqs and wq.
3886 free_percpu(wq
->cpu_pwqs
);
3890 * We're the sole accessor of @wq at this point. Directly
3891 * access the first pwq and put the base ref. As both pwqs
3892 * and pools are sched-RCU protected, the lock operations
3893 * are safe. @wq will be freed when the last pwq is
3896 pwq
= list_first_entry(&wq
->pwqs
, struct pool_workqueue
,
3898 spin_lock_irq(&pwq
->pool
->lock
);
3900 spin_unlock_irq(&pwq
->pool
->lock
);
3903 EXPORT_SYMBOL_GPL(destroy_workqueue
);
3906 * workqueue_set_max_active - adjust max_active of a workqueue
3907 * @wq: target workqueue
3908 * @max_active: new max_active value.
3910 * Set max_active of @wq to @max_active.
3913 * Don't call from IRQ context.
3915 void workqueue_set_max_active(struct workqueue_struct
*wq
, int max_active
)
3917 struct pool_workqueue
*pwq
;
3919 /* disallow meddling with max_active for ordered workqueues */
3920 if (WARN_ON(wq
->flags
& __WQ_ORDERED
))
3923 max_active
= wq_clamp_max_active(max_active
, wq
->flags
, wq
->name
);
3925 spin_lock_irq(&pwq_lock
);
3927 wq
->saved_max_active
= max_active
;
3929 for_each_pwq(pwq
, wq
)
3930 pwq_adjust_max_active(pwq
);
3932 spin_unlock_irq(&pwq_lock
);
3934 EXPORT_SYMBOL_GPL(workqueue_set_max_active
);
3937 * current_is_workqueue_rescuer - is %current workqueue rescuer?
3939 * Determine whether %current is a workqueue rescuer. Can be used from
3940 * work functions to determine whether it's being run off the rescuer task.
3942 bool current_is_workqueue_rescuer(void)
3944 struct worker
*worker
= current_wq_worker();
3946 return worker
&& worker
->rescue_wq
;
3950 * workqueue_congested - test whether a workqueue is congested
3951 * @cpu: CPU in question
3952 * @wq: target workqueue
3954 * Test whether @wq's cpu workqueue for @cpu is congested. There is
3955 * no synchronization around this function and the test result is
3956 * unreliable and only useful as advisory hints or for debugging.
3959 * %true if congested, %false otherwise.
3961 bool workqueue_congested(int cpu
, struct workqueue_struct
*wq
)
3963 struct pool_workqueue
*pwq
;
3966 rcu_read_lock_sched();
3968 if (!(wq
->flags
& WQ_UNBOUND
))
3969 pwq
= per_cpu_ptr(wq
->cpu_pwqs
, cpu
);
3971 pwq
= first_pwq(wq
);
3973 ret
= !list_empty(&pwq
->delayed_works
);
3974 rcu_read_unlock_sched();
3978 EXPORT_SYMBOL_GPL(workqueue_congested
);
3981 * work_busy - test whether a work is currently pending or running
3982 * @work: the work to be tested
3984 * Test whether @work is currently pending or running. There is no
3985 * synchronization around this function and the test result is
3986 * unreliable and only useful as advisory hints or for debugging.
3989 * OR'd bitmask of WORK_BUSY_* bits.
3991 unsigned int work_busy(struct work_struct
*work
)
3993 struct worker_pool
*pool
;
3994 unsigned long flags
;
3995 unsigned int ret
= 0;
3997 if (work_pending(work
))
3998 ret
|= WORK_BUSY_PENDING
;
4000 local_irq_save(flags
);
4001 pool
= get_work_pool(work
);
4003 spin_lock(&pool
->lock
);
4004 if (find_worker_executing_work(pool
, work
))
4005 ret
|= WORK_BUSY_RUNNING
;
4006 spin_unlock(&pool
->lock
);
4008 local_irq_restore(flags
);
4012 EXPORT_SYMBOL_GPL(work_busy
);
4017 * There are two challenges in supporting CPU hotplug. Firstly, there
4018 * are a lot of assumptions on strong associations among work, pwq and
4019 * pool which make migrating pending and scheduled works very
4020 * difficult to implement without impacting hot paths. Secondly,
4021 * worker pools serve mix of short, long and very long running works making
4022 * blocked draining impractical.
4024 * This is solved by allowing the pools to be disassociated from the CPU
4025 * running as an unbound one and allowing it to be reattached later if the
4026 * cpu comes back online.
4029 static void wq_unbind_fn(struct work_struct
*work
)
4031 int cpu
= smp_processor_id();
4032 struct worker_pool
*pool
;
4033 struct worker
*worker
;
4036 for_each_cpu_worker_pool(pool
, cpu
) {
4037 WARN_ON_ONCE(cpu
!= smp_processor_id());
4039 mutex_lock(&pool
->manager_mutex
);
4040 spin_lock_irq(&pool
->lock
);
4043 * We've blocked all manager operations. Make all workers
4044 * unbound and set DISASSOCIATED. Before this, all workers
4045 * except for the ones which are still executing works from
4046 * before the last CPU down must be on the cpu. After
4047 * this, they may become diasporas.
4049 for_each_pool_worker(worker
, wi
, pool
)
4050 worker
->flags
|= WORKER_UNBOUND
;
4052 pool
->flags
|= POOL_DISASSOCIATED
;
4054 spin_unlock_irq(&pool
->lock
);
4055 mutex_unlock(&pool
->manager_mutex
);
4059 * Call schedule() so that we cross rq->lock and thus can guarantee
4060 * sched callbacks see the %WORKER_UNBOUND flag. This is necessary
4061 * as scheduler callbacks may be invoked from other cpus.
4066 * Sched callbacks are disabled now. Zap nr_running. After this,
4067 * nr_running stays zero and need_more_worker() and keep_working()
4068 * are always true as long as the worklist is not empty. Pools on
4069 * @cpu now behave as unbound (in terms of concurrency management)
4070 * pools which are served by workers tied to the CPU.
4072 * On return from this function, the current worker would trigger
4073 * unbound chain execution of pending work items if other workers
4076 for_each_cpu_worker_pool(pool
, cpu
)
4077 atomic_set(&pool
->nr_running
, 0);
4081 * rebind_workers - rebind all workers of a pool to the associated CPU
4082 * @pool: pool of interest
4084 * @pool->cpu is coming online. Rebind all workers to the CPU.
4086 static void rebind_workers(struct worker_pool
*pool
)
4088 struct worker
*worker
;
4091 lockdep_assert_held(&pool
->manager_mutex
);
4094 * Restore CPU affinity of all workers. As all idle workers should
4095 * be on the run-queue of the associated CPU before any local
4096 * wake-ups for concurrency management happen, restore CPU affinty
4097 * of all workers first and then clear UNBOUND. As we're called
4098 * from CPU_ONLINE, the following shouldn't fail.
4100 for_each_pool_worker(worker
, wi
, pool
)
4101 WARN_ON_ONCE(set_cpus_allowed_ptr(worker
->task
,
4102 pool
->attrs
->cpumask
) < 0);
4104 spin_lock_irq(&pool
->lock
);
4106 for_each_pool_worker(worker
, wi
, pool
) {
4107 unsigned int worker_flags
= worker
->flags
;
4110 * A bound idle worker should actually be on the runqueue
4111 * of the associated CPU for local wake-ups targeting it to
4112 * work. Kick all idle workers so that they migrate to the
4113 * associated CPU. Doing this in the same loop as
4114 * replacing UNBOUND with REBOUND is safe as no worker will
4115 * be bound before @pool->lock is released.
4117 if (worker_flags
& WORKER_IDLE
)
4118 wake_up_process(worker
->task
);
4121 * We want to clear UNBOUND but can't directly call
4122 * worker_clr_flags() or adjust nr_running. Atomically
4123 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
4124 * @worker will clear REBOUND using worker_clr_flags() when
4125 * it initiates the next execution cycle thus restoring
4126 * concurrency management. Note that when or whether
4127 * @worker clears REBOUND doesn't affect correctness.
4129 * ACCESS_ONCE() is necessary because @worker->flags may be
4130 * tested without holding any lock in
4131 * wq_worker_waking_up(). Without it, NOT_RUNNING test may
4132 * fail incorrectly leading to premature concurrency
4133 * management operations.
4135 WARN_ON_ONCE(!(worker_flags
& WORKER_UNBOUND
));
4136 worker_flags
|= WORKER_REBOUND
;
4137 worker_flags
&= ~WORKER_UNBOUND
;
4138 ACCESS_ONCE(worker
->flags
) = worker_flags
;
4141 spin_unlock_irq(&pool
->lock
);
4145 * restore_unbound_workers_cpumask - restore cpumask of unbound workers
4146 * @pool: unbound pool of interest
4147 * @cpu: the CPU which is coming up
4149 * An unbound pool may end up with a cpumask which doesn't have any online
4150 * CPUs. When a worker of such pool get scheduled, the scheduler resets
4151 * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
4152 * online CPU before, cpus_allowed of all its workers should be restored.
4154 static void restore_unbound_workers_cpumask(struct worker_pool
*pool
, int cpu
)
4156 static cpumask_t cpumask
;
4157 struct worker
*worker
;
4160 lockdep_assert_held(&pool
->manager_mutex
);
4162 /* is @cpu allowed for @pool? */
4163 if (!cpumask_test_cpu(cpu
, pool
->attrs
->cpumask
))
4166 /* is @cpu the only online CPU? */
4167 cpumask_and(&cpumask
, pool
->attrs
->cpumask
, cpu_online_mask
);
4168 if (cpumask_weight(&cpumask
) != 1)
4171 /* as we're called from CPU_ONLINE, the following shouldn't fail */
4172 for_each_pool_worker(worker
, wi
, pool
)
4173 WARN_ON_ONCE(set_cpus_allowed_ptr(worker
->task
,
4174 pool
->attrs
->cpumask
) < 0);
4178 * Workqueues should be brought up before normal priority CPU notifiers.
4179 * This will be registered high priority CPU notifier.
4181 static int __cpuinit
workqueue_cpu_up_callback(struct notifier_block
*nfb
,
4182 unsigned long action
,
4185 int cpu
= (unsigned long)hcpu
;
4186 struct worker_pool
*pool
;
4189 switch (action
& ~CPU_TASKS_FROZEN
) {
4190 case CPU_UP_PREPARE
:
4191 for_each_cpu_worker_pool(pool
, cpu
) {
4192 if (pool
->nr_workers
)
4194 if (create_and_start_worker(pool
) < 0)
4199 case CPU_DOWN_FAILED
:
4201 mutex_lock(&wq_mutex
);
4203 for_each_pool(pool
, pi
) {
4204 mutex_lock(&pool
->manager_mutex
);
4206 if (pool
->cpu
== cpu
) {
4207 spin_lock_irq(&pool
->lock
);
4208 pool
->flags
&= ~POOL_DISASSOCIATED
;
4209 spin_unlock_irq(&pool
->lock
);
4211 rebind_workers(pool
);
4212 } else if (pool
->cpu
< 0) {
4213 restore_unbound_workers_cpumask(pool
, cpu
);
4216 mutex_unlock(&pool
->manager_mutex
);
4219 mutex_unlock(&wq_mutex
);
4226 * Workqueues should be brought down after normal priority CPU notifiers.
4227 * This will be registered as low priority CPU notifier.
4229 static int __cpuinit
workqueue_cpu_down_callback(struct notifier_block
*nfb
,
4230 unsigned long action
,
4233 int cpu
= (unsigned long)hcpu
;
4234 struct work_struct unbind_work
;
4236 switch (action
& ~CPU_TASKS_FROZEN
) {
4237 case CPU_DOWN_PREPARE
:
4238 /* unbinding should happen on the local CPU */
4239 INIT_WORK_ONSTACK(&unbind_work
, wq_unbind_fn
);
4240 queue_work_on(cpu
, system_highpri_wq
, &unbind_work
);
4241 flush_work(&unbind_work
);
4249 struct work_for_cpu
{
4250 struct work_struct work
;
4256 static void work_for_cpu_fn(struct work_struct
*work
)
4258 struct work_for_cpu
*wfc
= container_of(work
, struct work_for_cpu
, work
);
4260 wfc
->ret
= wfc
->fn(wfc
->arg
);
4264 * work_on_cpu - run a function in user context on a particular cpu
4265 * @cpu: the cpu to run on
4266 * @fn: the function to run
4267 * @arg: the function arg
4269 * This will return the value @fn returns.
4270 * It is up to the caller to ensure that the cpu doesn't go offline.
4271 * The caller must not hold any locks which would prevent @fn from completing.
4273 long work_on_cpu(int cpu
, long (*fn
)(void *), void *arg
)
4275 struct work_for_cpu wfc
= { .fn
= fn
, .arg
= arg
};
4277 INIT_WORK_ONSTACK(&wfc
.work
, work_for_cpu_fn
);
4278 schedule_work_on(cpu
, &wfc
.work
);
4279 flush_work(&wfc
.work
);
4282 EXPORT_SYMBOL_GPL(work_on_cpu
);
4283 #endif /* CONFIG_SMP */
4285 #ifdef CONFIG_FREEZER
4288 * freeze_workqueues_begin - begin freezing workqueues
4290 * Start freezing workqueues. After this function returns, all freezable
4291 * workqueues will queue new works to their delayed_works list instead of
4295 * Grabs and releases wq_mutex, pwq_lock and pool->lock's.
4297 void freeze_workqueues_begin(void)
4299 struct worker_pool
*pool
;
4300 struct workqueue_struct
*wq
;
4301 struct pool_workqueue
*pwq
;
4304 mutex_lock(&wq_mutex
);
4306 WARN_ON_ONCE(workqueue_freezing
);
4307 workqueue_freezing
= true;
4310 for_each_pool(pool
, pi
) {
4311 spin_lock_irq(&pool
->lock
);
4312 WARN_ON_ONCE(pool
->flags
& POOL_FREEZING
);
4313 pool
->flags
|= POOL_FREEZING
;
4314 spin_unlock_irq(&pool
->lock
);
4317 /* suppress further executions by setting max_active to zero */
4318 spin_lock_irq(&pwq_lock
);
4319 list_for_each_entry(wq
, &workqueues
, list
) {
4320 for_each_pwq(pwq
, wq
)
4321 pwq_adjust_max_active(pwq
);
4323 spin_unlock_irq(&pwq_lock
);
4325 mutex_unlock(&wq_mutex
);
4329 * freeze_workqueues_busy - are freezable workqueues still busy?
4331 * Check whether freezing is complete. This function must be called
4332 * between freeze_workqueues_begin() and thaw_workqueues().
4335 * Grabs and releases wq_mutex.
4338 * %true if some freezable workqueues are still busy. %false if freezing
4341 bool freeze_workqueues_busy(void)
4344 struct workqueue_struct
*wq
;
4345 struct pool_workqueue
*pwq
;
4347 mutex_lock(&wq_mutex
);
4349 WARN_ON_ONCE(!workqueue_freezing
);
4351 list_for_each_entry(wq
, &workqueues
, list
) {
4352 if (!(wq
->flags
& WQ_FREEZABLE
))
4355 * nr_active is monotonically decreasing. It's safe
4356 * to peek without lock.
4358 rcu_read_lock_sched();
4359 for_each_pwq(pwq
, wq
) {
4360 WARN_ON_ONCE(pwq
->nr_active
< 0);
4361 if (pwq
->nr_active
) {
4363 rcu_read_unlock_sched();
4367 rcu_read_unlock_sched();
4370 mutex_unlock(&wq_mutex
);
4375 * thaw_workqueues - thaw workqueues
4377 * Thaw workqueues. Normal queueing is restored and all collected
4378 * frozen works are transferred to their respective pool worklists.
4381 * Grabs and releases wq_mutex, pwq_lock and pool->lock's.
4383 void thaw_workqueues(void)
4385 struct workqueue_struct
*wq
;
4386 struct pool_workqueue
*pwq
;
4387 struct worker_pool
*pool
;
4390 mutex_lock(&wq_mutex
);
4392 if (!workqueue_freezing
)
4395 /* clear FREEZING */
4396 for_each_pool(pool
, pi
) {
4397 spin_lock_irq(&pool
->lock
);
4398 WARN_ON_ONCE(!(pool
->flags
& POOL_FREEZING
));
4399 pool
->flags
&= ~POOL_FREEZING
;
4400 spin_unlock_irq(&pool
->lock
);
4403 /* restore max_active and repopulate worklist */
4404 spin_lock_irq(&pwq_lock
);
4405 list_for_each_entry(wq
, &workqueues
, list
) {
4406 for_each_pwq(pwq
, wq
)
4407 pwq_adjust_max_active(pwq
);
4409 spin_unlock_irq(&pwq_lock
);
4411 workqueue_freezing
= false;
4413 mutex_unlock(&wq_mutex
);
4415 #endif /* CONFIG_FREEZER */
4417 static int __init
init_workqueues(void)
4419 int std_nice
[NR_STD_WORKER_POOLS
] = { 0, HIGHPRI_NICE_LEVEL
};
4422 /* make sure we have enough bits for OFFQ pool ID */
4423 BUILD_BUG_ON((1LU << (BITS_PER_LONG
- WORK_OFFQ_POOL_SHIFT
)) <
4424 WORK_CPU_END
* NR_STD_WORKER_POOLS
);
4426 WARN_ON(__alignof__(struct pool_workqueue
) < __alignof__(long long));
4428 pwq_cache
= KMEM_CACHE(pool_workqueue
, SLAB_PANIC
);
4430 cpu_notifier(workqueue_cpu_up_callback
, CPU_PRI_WORKQUEUE_UP
);
4431 hotcpu_notifier(workqueue_cpu_down_callback
, CPU_PRI_WORKQUEUE_DOWN
);
4433 /* initialize CPU pools */
4434 for_each_possible_cpu(cpu
) {
4435 struct worker_pool
*pool
;
4438 for_each_cpu_worker_pool(pool
, cpu
) {
4439 BUG_ON(init_worker_pool(pool
));
4441 cpumask_copy(pool
->attrs
->cpumask
, cpumask_of(cpu
));
4442 pool
->attrs
->nice
= std_nice
[i
++];
4445 mutex_lock(&wq_mutex
);
4446 BUG_ON(worker_pool_assign_id(pool
));
4447 mutex_unlock(&wq_mutex
);
4451 /* create the initial worker */
4452 for_each_online_cpu(cpu
) {
4453 struct worker_pool
*pool
;
4455 for_each_cpu_worker_pool(pool
, cpu
) {
4456 pool
->flags
&= ~POOL_DISASSOCIATED
;
4457 BUG_ON(create_and_start_worker(pool
) < 0);
4461 /* create default unbound wq attrs */
4462 for (i
= 0; i
< NR_STD_WORKER_POOLS
; i
++) {
4463 struct workqueue_attrs
*attrs
;
4465 BUG_ON(!(attrs
= alloc_workqueue_attrs(GFP_KERNEL
)));
4467 attrs
->nice
= std_nice
[i
];
4468 cpumask_setall(attrs
->cpumask
);
4470 unbound_std_wq_attrs
[i
] = attrs
;
4473 system_wq
= alloc_workqueue("events", 0, 0);
4474 system_highpri_wq
= alloc_workqueue("events_highpri", WQ_HIGHPRI
, 0);
4475 system_long_wq
= alloc_workqueue("events_long", 0, 0);
4476 system_unbound_wq
= alloc_workqueue("events_unbound", WQ_UNBOUND
,
4477 WQ_UNBOUND_MAX_ACTIVE
);
4478 system_freezable_wq
= alloc_workqueue("events_freezable",
4480 BUG_ON(!system_wq
|| !system_highpri_wq
|| !system_long_wq
||
4481 !system_unbound_wq
|| !system_freezable_wq
);
4484 early_initcall(init_workqueues
);