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(!lockdep_is_held(&(pool)->manager_mutex) && \
309 !lockdep_is_held(&(pool)->lock), \
310 "pool->manager_mutex or ->lock should be held")
312 #define assert_manager_or_pool_lock(pool) do { } while (0)
315 #define for_each_cpu_worker_pool(pool, cpu) \
316 for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
317 (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
321 * for_each_pool - iterate through all worker_pools in the system
322 * @pool: iteration cursor
323 * @pi: integer used for iteration
325 * This must be called either with wq_mutex held or sched RCU read locked.
326 * If the pool needs to be used beyond the locking in effect, the caller is
327 * responsible for guaranteeing that the pool stays online.
329 * The if/else clause exists only for the lockdep assertion and can be
332 #define for_each_pool(pool, pi) \
333 idr_for_each_entry(&worker_pool_idr, pool, pi) \
334 if (({ assert_rcu_or_wq_mutex(); false; })) { } \
338 * for_each_pool_worker - iterate through all workers of a worker_pool
339 * @worker: iteration cursor
340 * @wi: integer used for iteration
341 * @pool: worker_pool to iterate workers of
343 * This must be called with either @pool->manager_mutex or ->lock held.
345 * The if/else clause exists only for the lockdep assertion and can be
348 #define for_each_pool_worker(worker, wi, pool) \
349 idr_for_each_entry(&(pool)->worker_idr, (worker), (wi)) \
350 if (({ assert_manager_or_pool_lock((pool)); false; })) { } \
354 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
355 * @pwq: iteration cursor
356 * @wq: the target workqueue
358 * This must be called either with pwq_lock held or sched RCU read locked.
359 * If the pwq needs to be used beyond the locking in effect, the caller is
360 * responsible for guaranteeing that the pwq stays online.
362 * The if/else clause exists only for the lockdep assertion and can be
365 #define for_each_pwq(pwq, wq) \
366 list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node) \
367 if (({ assert_rcu_or_pwq_lock(); false; })) { } \
370 #ifdef CONFIG_DEBUG_OBJECTS_WORK
372 static struct debug_obj_descr work_debug_descr
;
374 static void *work_debug_hint(void *addr
)
376 return ((struct work_struct
*) addr
)->func
;
380 * fixup_init is called when:
381 * - an active object is initialized
383 static int work_fixup_init(void *addr
, enum debug_obj_state state
)
385 struct work_struct
*work
= addr
;
388 case ODEBUG_STATE_ACTIVE
:
389 cancel_work_sync(work
);
390 debug_object_init(work
, &work_debug_descr
);
398 * fixup_activate is called when:
399 * - an active object is activated
400 * - an unknown object is activated (might be a statically initialized object)
402 static int work_fixup_activate(void *addr
, enum debug_obj_state state
)
404 struct work_struct
*work
= addr
;
408 case ODEBUG_STATE_NOTAVAILABLE
:
410 * This is not really a fixup. The work struct was
411 * statically initialized. We just make sure that it
412 * is tracked in the object tracker.
414 if (test_bit(WORK_STRUCT_STATIC_BIT
, work_data_bits(work
))) {
415 debug_object_init(work
, &work_debug_descr
);
416 debug_object_activate(work
, &work_debug_descr
);
422 case ODEBUG_STATE_ACTIVE
:
431 * fixup_free is called when:
432 * - an active object is freed
434 static int work_fixup_free(void *addr
, enum debug_obj_state state
)
436 struct work_struct
*work
= addr
;
439 case ODEBUG_STATE_ACTIVE
:
440 cancel_work_sync(work
);
441 debug_object_free(work
, &work_debug_descr
);
448 static struct debug_obj_descr work_debug_descr
= {
449 .name
= "work_struct",
450 .debug_hint
= work_debug_hint
,
451 .fixup_init
= work_fixup_init
,
452 .fixup_activate
= work_fixup_activate
,
453 .fixup_free
= work_fixup_free
,
456 static inline void debug_work_activate(struct work_struct
*work
)
458 debug_object_activate(work
, &work_debug_descr
);
461 static inline void debug_work_deactivate(struct work_struct
*work
)
463 debug_object_deactivate(work
, &work_debug_descr
);
466 void __init_work(struct work_struct
*work
, int onstack
)
469 debug_object_init_on_stack(work
, &work_debug_descr
);
471 debug_object_init(work
, &work_debug_descr
);
473 EXPORT_SYMBOL_GPL(__init_work
);
475 void destroy_work_on_stack(struct work_struct
*work
)
477 debug_object_free(work
, &work_debug_descr
);
479 EXPORT_SYMBOL_GPL(destroy_work_on_stack
);
482 static inline void debug_work_activate(struct work_struct
*work
) { }
483 static inline void debug_work_deactivate(struct work_struct
*work
) { }
486 /* allocate ID and assign it to @pool */
487 static int worker_pool_assign_id(struct worker_pool
*pool
)
491 lockdep_assert_held(&wq_mutex
);
494 if (!idr_pre_get(&worker_pool_idr
, GFP_KERNEL
))
496 ret
= idr_get_new(&worker_pool_idr
, pool
, &pool
->id
);
497 } while (ret
== -EAGAIN
);
503 * first_pwq - return the first pool_workqueue of the specified workqueue
504 * @wq: the target workqueue
506 * This must be called either with pwq_lock held or sched RCU read locked.
507 * If the pwq needs to be used beyond the locking in effect, the caller is
508 * responsible for guaranteeing that the pwq stays online.
510 static struct pool_workqueue
*first_pwq(struct workqueue_struct
*wq
)
512 assert_rcu_or_pwq_lock();
513 return list_first_or_null_rcu(&wq
->pwqs
, struct pool_workqueue
,
517 static unsigned int work_color_to_flags(int color
)
519 return color
<< WORK_STRUCT_COLOR_SHIFT
;
522 static int get_work_color(struct work_struct
*work
)
524 return (*work_data_bits(work
) >> WORK_STRUCT_COLOR_SHIFT
) &
525 ((1 << WORK_STRUCT_COLOR_BITS
) - 1);
528 static int work_next_color(int color
)
530 return (color
+ 1) % WORK_NR_COLORS
;
534 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
535 * contain the pointer to the queued pwq. Once execution starts, the flag
536 * is cleared and the high bits contain OFFQ flags and pool ID.
538 * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
539 * and clear_work_data() can be used to set the pwq, pool or clear
540 * work->data. These functions should only be called while the work is
541 * owned - ie. while the PENDING bit is set.
543 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
544 * corresponding to a work. Pool is available once the work has been
545 * queued anywhere after initialization until it is sync canceled. pwq is
546 * available only while the work item is queued.
548 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
549 * canceled. While being canceled, a work item may have its PENDING set
550 * but stay off timer and worklist for arbitrarily long and nobody should
551 * try to steal the PENDING bit.
553 static inline void set_work_data(struct work_struct
*work
, unsigned long data
,
556 WARN_ON_ONCE(!work_pending(work
));
557 atomic_long_set(&work
->data
, data
| flags
| work_static(work
));
560 static void set_work_pwq(struct work_struct
*work
, struct pool_workqueue
*pwq
,
561 unsigned long extra_flags
)
563 set_work_data(work
, (unsigned long)pwq
,
564 WORK_STRUCT_PENDING
| WORK_STRUCT_PWQ
| extra_flags
);
567 static void set_work_pool_and_keep_pending(struct work_struct
*work
,
570 set_work_data(work
, (unsigned long)pool_id
<< WORK_OFFQ_POOL_SHIFT
,
571 WORK_STRUCT_PENDING
);
574 static void set_work_pool_and_clear_pending(struct work_struct
*work
,
578 * The following wmb is paired with the implied mb in
579 * test_and_set_bit(PENDING) and ensures all updates to @work made
580 * here are visible to and precede any updates by the next PENDING
584 set_work_data(work
, (unsigned long)pool_id
<< WORK_OFFQ_POOL_SHIFT
, 0);
587 static void clear_work_data(struct work_struct
*work
)
589 smp_wmb(); /* see set_work_pool_and_clear_pending() */
590 set_work_data(work
, WORK_STRUCT_NO_POOL
, 0);
593 static struct pool_workqueue
*get_work_pwq(struct work_struct
*work
)
595 unsigned long data
= atomic_long_read(&work
->data
);
597 if (data
& WORK_STRUCT_PWQ
)
598 return (void *)(data
& WORK_STRUCT_WQ_DATA_MASK
);
604 * get_work_pool - return the worker_pool a given work was associated with
605 * @work: the work item of interest
607 * Return the worker_pool @work was last associated with. %NULL if none.
609 * Pools are created and destroyed under wq_mutex, and allows read access
610 * under sched-RCU read lock. As such, this function should be called
611 * under wq_mutex or with preemption disabled.
613 * All fields of the returned pool are accessible as long as the above
614 * mentioned locking is in effect. If the returned pool needs to be used
615 * beyond the critical section, the caller is responsible for ensuring the
616 * returned pool is and stays online.
618 static struct worker_pool
*get_work_pool(struct work_struct
*work
)
620 unsigned long data
= atomic_long_read(&work
->data
);
623 assert_rcu_or_wq_mutex();
625 if (data
& WORK_STRUCT_PWQ
)
626 return ((struct pool_workqueue
*)
627 (data
& WORK_STRUCT_WQ_DATA_MASK
))->pool
;
629 pool_id
= data
>> WORK_OFFQ_POOL_SHIFT
;
630 if (pool_id
== WORK_OFFQ_POOL_NONE
)
633 return idr_find(&worker_pool_idr
, pool_id
);
637 * get_work_pool_id - return the worker pool ID a given work is associated with
638 * @work: the work item of interest
640 * Return the worker_pool ID @work was last associated with.
641 * %WORK_OFFQ_POOL_NONE if none.
643 static int get_work_pool_id(struct work_struct
*work
)
645 unsigned long data
= atomic_long_read(&work
->data
);
647 if (data
& WORK_STRUCT_PWQ
)
648 return ((struct pool_workqueue
*)
649 (data
& WORK_STRUCT_WQ_DATA_MASK
))->pool
->id
;
651 return data
>> WORK_OFFQ_POOL_SHIFT
;
654 static void mark_work_canceling(struct work_struct
*work
)
656 unsigned long pool_id
= get_work_pool_id(work
);
658 pool_id
<<= WORK_OFFQ_POOL_SHIFT
;
659 set_work_data(work
, pool_id
| WORK_OFFQ_CANCELING
, WORK_STRUCT_PENDING
);
662 static bool work_is_canceling(struct work_struct
*work
)
664 unsigned long data
= atomic_long_read(&work
->data
);
666 return !(data
& WORK_STRUCT_PWQ
) && (data
& WORK_OFFQ_CANCELING
);
670 * Policy functions. These define the policies on how the global worker
671 * pools are managed. Unless noted otherwise, these functions assume that
672 * they're being called with pool->lock held.
675 static bool __need_more_worker(struct worker_pool
*pool
)
677 return !atomic_read(&pool
->nr_running
);
681 * Need to wake up a worker? Called from anything but currently
684 * Note that, because unbound workers never contribute to nr_running, this
685 * function will always return %true for unbound pools as long as the
686 * worklist isn't empty.
688 static bool need_more_worker(struct worker_pool
*pool
)
690 return !list_empty(&pool
->worklist
) && __need_more_worker(pool
);
693 /* Can I start working? Called from busy but !running workers. */
694 static bool may_start_working(struct worker_pool
*pool
)
696 return pool
->nr_idle
;
699 /* Do I need to keep working? Called from currently running workers. */
700 static bool keep_working(struct worker_pool
*pool
)
702 return !list_empty(&pool
->worklist
) &&
703 atomic_read(&pool
->nr_running
) <= 1;
706 /* Do we need a new worker? Called from manager. */
707 static bool need_to_create_worker(struct worker_pool
*pool
)
709 return need_more_worker(pool
) && !may_start_working(pool
);
712 /* Do I need to be the manager? */
713 static bool need_to_manage_workers(struct worker_pool
*pool
)
715 return need_to_create_worker(pool
) ||
716 (pool
->flags
& POOL_MANAGE_WORKERS
);
719 /* Do we have too many workers and should some go away? */
720 static bool too_many_workers(struct worker_pool
*pool
)
722 bool managing
= mutex_is_locked(&pool
->manager_arb
);
723 int nr_idle
= pool
->nr_idle
+ managing
; /* manager is considered idle */
724 int nr_busy
= pool
->nr_workers
- nr_idle
;
727 * nr_idle and idle_list may disagree if idle rebinding is in
728 * progress. Never return %true if idle_list is empty.
730 if (list_empty(&pool
->idle_list
))
733 return nr_idle
> 2 && (nr_idle
- 2) * MAX_IDLE_WORKERS_RATIO
>= nr_busy
;
740 /* Return the first worker. Safe with preemption disabled */
741 static struct worker
*first_worker(struct worker_pool
*pool
)
743 if (unlikely(list_empty(&pool
->idle_list
)))
746 return list_first_entry(&pool
->idle_list
, struct worker
, entry
);
750 * wake_up_worker - wake up an idle worker
751 * @pool: worker pool to wake worker from
753 * Wake up the first idle worker of @pool.
756 * spin_lock_irq(pool->lock).
758 static void wake_up_worker(struct worker_pool
*pool
)
760 struct worker
*worker
= first_worker(pool
);
763 wake_up_process(worker
->task
);
767 * wq_worker_waking_up - a worker is waking up
768 * @task: task waking up
769 * @cpu: CPU @task is waking up to
771 * This function is called during try_to_wake_up() when a worker is
775 * spin_lock_irq(rq->lock)
777 void wq_worker_waking_up(struct task_struct
*task
, int cpu
)
779 struct worker
*worker
= kthread_data(task
);
781 if (!(worker
->flags
& WORKER_NOT_RUNNING
)) {
782 WARN_ON_ONCE(worker
->pool
->cpu
!= cpu
);
783 atomic_inc(&worker
->pool
->nr_running
);
788 * wq_worker_sleeping - a worker is going to sleep
789 * @task: task going to sleep
790 * @cpu: CPU in question, must be the current CPU number
792 * This function is called during schedule() when a busy worker is
793 * going to sleep. Worker on the same cpu can be woken up by
794 * returning pointer to its task.
797 * spin_lock_irq(rq->lock)
800 * Worker task on @cpu to wake up, %NULL if none.
802 struct task_struct
*wq_worker_sleeping(struct task_struct
*task
, int cpu
)
804 struct worker
*worker
= kthread_data(task
), *to_wakeup
= NULL
;
805 struct worker_pool
*pool
;
808 * Rescuers, which may not have all the fields set up like normal
809 * workers, also reach here, let's not access anything before
810 * checking NOT_RUNNING.
812 if (worker
->flags
& WORKER_NOT_RUNNING
)
817 /* this can only happen on the local cpu */
818 if (WARN_ON_ONCE(cpu
!= raw_smp_processor_id()))
822 * The counterpart of the following dec_and_test, implied mb,
823 * worklist not empty test sequence is in insert_work().
824 * Please read comment there.
826 * NOT_RUNNING is clear. This means that we're bound to and
827 * running on the local cpu w/ rq lock held and preemption
828 * disabled, which in turn means that none else could be
829 * manipulating idle_list, so dereferencing idle_list without pool
832 if (atomic_dec_and_test(&pool
->nr_running
) &&
833 !list_empty(&pool
->worklist
))
834 to_wakeup
= first_worker(pool
);
835 return to_wakeup
? to_wakeup
->task
: NULL
;
839 * worker_set_flags - set worker flags and adjust nr_running accordingly
841 * @flags: flags to set
842 * @wakeup: wakeup an idle worker if necessary
844 * Set @flags in @worker->flags and adjust nr_running accordingly. If
845 * nr_running becomes zero and @wakeup is %true, an idle worker is
849 * spin_lock_irq(pool->lock)
851 static inline void worker_set_flags(struct worker
*worker
, unsigned int flags
,
854 struct worker_pool
*pool
= worker
->pool
;
856 WARN_ON_ONCE(worker
->task
!= current
);
859 * If transitioning into NOT_RUNNING, adjust nr_running and
860 * wake up an idle worker as necessary if requested by
863 if ((flags
& WORKER_NOT_RUNNING
) &&
864 !(worker
->flags
& WORKER_NOT_RUNNING
)) {
866 if (atomic_dec_and_test(&pool
->nr_running
) &&
867 !list_empty(&pool
->worklist
))
868 wake_up_worker(pool
);
870 atomic_dec(&pool
->nr_running
);
873 worker
->flags
|= flags
;
877 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
879 * @flags: flags to clear
881 * Clear @flags in @worker->flags and adjust nr_running accordingly.
884 * spin_lock_irq(pool->lock)
886 static inline void worker_clr_flags(struct worker
*worker
, unsigned int flags
)
888 struct worker_pool
*pool
= worker
->pool
;
889 unsigned int oflags
= worker
->flags
;
891 WARN_ON_ONCE(worker
->task
!= current
);
893 worker
->flags
&= ~flags
;
896 * If transitioning out of NOT_RUNNING, increment nr_running. Note
897 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
898 * of multiple flags, not a single flag.
900 if ((flags
& WORKER_NOT_RUNNING
) && (oflags
& WORKER_NOT_RUNNING
))
901 if (!(worker
->flags
& WORKER_NOT_RUNNING
))
902 atomic_inc(&pool
->nr_running
);
906 * find_worker_executing_work - find worker which is executing a work
907 * @pool: pool of interest
908 * @work: work to find worker for
910 * Find a worker which is executing @work on @pool by searching
911 * @pool->busy_hash which is keyed by the address of @work. For a worker
912 * to match, its current execution should match the address of @work and
913 * its work function. This is to avoid unwanted dependency between
914 * unrelated work executions through a work item being recycled while still
917 * This is a bit tricky. A work item may be freed once its execution
918 * starts and nothing prevents the freed area from being recycled for
919 * another work item. If the same work item address ends up being reused
920 * before the original execution finishes, workqueue will identify the
921 * recycled work item as currently executing and make it wait until the
922 * current execution finishes, introducing an unwanted dependency.
924 * This function checks the work item address and work function to avoid
925 * false positives. Note that this isn't complete as one may construct a
926 * work function which can introduce dependency onto itself through a
927 * recycled work item. Well, if somebody wants to shoot oneself in the
928 * foot that badly, there's only so much we can do, and if such deadlock
929 * actually occurs, it should be easy to locate the culprit work function.
932 * spin_lock_irq(pool->lock).
935 * Pointer to worker which is executing @work if found, NULL
938 static struct worker
*find_worker_executing_work(struct worker_pool
*pool
,
939 struct work_struct
*work
)
941 struct worker
*worker
;
943 hash_for_each_possible(pool
->busy_hash
, worker
, hentry
,
945 if (worker
->current_work
== work
&&
946 worker
->current_func
== work
->func
)
953 * move_linked_works - move linked works to a list
954 * @work: start of series of works to be scheduled
955 * @head: target list to append @work to
956 * @nextp: out paramter for nested worklist walking
958 * Schedule linked works starting from @work to @head. Work series to
959 * be scheduled starts at @work and includes any consecutive work with
960 * WORK_STRUCT_LINKED set in its predecessor.
962 * If @nextp is not NULL, it's updated to point to the next work of
963 * the last scheduled work. This allows move_linked_works() to be
964 * nested inside outer list_for_each_entry_safe().
967 * spin_lock_irq(pool->lock).
969 static void move_linked_works(struct work_struct
*work
, struct list_head
*head
,
970 struct work_struct
**nextp
)
972 struct work_struct
*n
;
975 * Linked worklist will always end before the end of the list,
976 * use NULL for list head.
978 list_for_each_entry_safe_from(work
, n
, NULL
, entry
) {
979 list_move_tail(&work
->entry
, head
);
980 if (!(*work_data_bits(work
) & WORK_STRUCT_LINKED
))
985 * If we're already inside safe list traversal and have moved
986 * multiple works to the scheduled queue, the next position
987 * needs to be updated.
994 * get_pwq - get an extra reference on the specified pool_workqueue
995 * @pwq: pool_workqueue to get
997 * Obtain an extra reference on @pwq. The caller should guarantee that
998 * @pwq has positive refcnt and be holding the matching pool->lock.
1000 static void get_pwq(struct pool_workqueue
*pwq
)
1002 lockdep_assert_held(&pwq
->pool
->lock
);
1003 WARN_ON_ONCE(pwq
->refcnt
<= 0);
1008 * put_pwq - put a pool_workqueue reference
1009 * @pwq: pool_workqueue to put
1011 * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
1012 * destruction. The caller should be holding the matching pool->lock.
1014 static void put_pwq(struct pool_workqueue
*pwq
)
1016 lockdep_assert_held(&pwq
->pool
->lock
);
1017 if (likely(--pwq
->refcnt
))
1019 if (WARN_ON_ONCE(!(pwq
->wq
->flags
& WQ_UNBOUND
)))
1022 * @pwq can't be released under pool->lock, bounce to
1023 * pwq_unbound_release_workfn(). This never recurses on the same
1024 * pool->lock as this path is taken only for unbound workqueues and
1025 * the release work item is scheduled on a per-cpu workqueue. To
1026 * avoid lockdep warning, unbound pool->locks are given lockdep
1027 * subclass of 1 in get_unbound_pool().
1029 schedule_work(&pwq
->unbound_release_work
);
1032 static void pwq_activate_delayed_work(struct work_struct
*work
)
1034 struct pool_workqueue
*pwq
= get_work_pwq(work
);
1036 trace_workqueue_activate_work(work
);
1037 move_linked_works(work
, &pwq
->pool
->worklist
, NULL
);
1038 __clear_bit(WORK_STRUCT_DELAYED_BIT
, work_data_bits(work
));
1042 static void pwq_activate_first_delayed(struct pool_workqueue
*pwq
)
1044 struct work_struct
*work
= list_first_entry(&pwq
->delayed_works
,
1045 struct work_struct
, entry
);
1047 pwq_activate_delayed_work(work
);
1051 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1052 * @pwq: pwq of interest
1053 * @color: color of work which left the queue
1055 * A work either has completed or is removed from pending queue,
1056 * decrement nr_in_flight of its pwq and handle workqueue flushing.
1059 * spin_lock_irq(pool->lock).
1061 static void pwq_dec_nr_in_flight(struct pool_workqueue
*pwq
, int color
)
1063 /* uncolored work items don't participate in flushing or nr_active */
1064 if (color
== WORK_NO_COLOR
)
1067 pwq
->nr_in_flight
[color
]--;
1070 if (!list_empty(&pwq
->delayed_works
)) {
1071 /* one down, submit a delayed one */
1072 if (pwq
->nr_active
< pwq
->max_active
)
1073 pwq_activate_first_delayed(pwq
);
1076 /* is flush in progress and are we at the flushing tip? */
1077 if (likely(pwq
->flush_color
!= color
))
1080 /* are there still in-flight works? */
1081 if (pwq
->nr_in_flight
[color
])
1084 /* this pwq is done, clear flush_color */
1085 pwq
->flush_color
= -1;
1088 * If this was the last pwq, wake up the first flusher. It
1089 * will handle the rest.
1091 if (atomic_dec_and_test(&pwq
->wq
->nr_pwqs_to_flush
))
1092 complete(&pwq
->wq
->first_flusher
->done
);
1098 * try_to_grab_pending - steal work item from worklist and disable irq
1099 * @work: work item to steal
1100 * @is_dwork: @work is a delayed_work
1101 * @flags: place to store irq state
1103 * Try to grab PENDING bit of @work. This function can handle @work in any
1104 * stable state - idle, on timer or on worklist. Return values are
1106 * 1 if @work was pending and we successfully stole PENDING
1107 * 0 if @work was idle and we claimed PENDING
1108 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1109 * -ENOENT if someone else is canceling @work, this state may persist
1110 * for arbitrarily long
1112 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1113 * interrupted while holding PENDING and @work off queue, irq must be
1114 * disabled on entry. This, combined with delayed_work->timer being
1115 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1117 * On successful return, >= 0, irq is disabled and the caller is
1118 * responsible for releasing it using local_irq_restore(*@flags).
1120 * This function is safe to call from any context including IRQ handler.
1122 static int try_to_grab_pending(struct work_struct
*work
, bool is_dwork
,
1123 unsigned long *flags
)
1125 struct worker_pool
*pool
;
1126 struct pool_workqueue
*pwq
;
1128 local_irq_save(*flags
);
1130 /* try to steal the timer if it exists */
1132 struct delayed_work
*dwork
= to_delayed_work(work
);
1135 * dwork->timer is irqsafe. If del_timer() fails, it's
1136 * guaranteed that the timer is not queued anywhere and not
1137 * running on the local CPU.
1139 if (likely(del_timer(&dwork
->timer
)))
1143 /* try to claim PENDING the normal way */
1144 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(work
)))
1148 * The queueing is in progress, or it is already queued. Try to
1149 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1151 pool
= get_work_pool(work
);
1155 spin_lock(&pool
->lock
);
1157 * work->data is guaranteed to point to pwq only while the work
1158 * item is queued on pwq->wq, and both updating work->data to point
1159 * to pwq on queueing and to pool on dequeueing are done under
1160 * pwq->pool->lock. This in turn guarantees that, if work->data
1161 * points to pwq which is associated with a locked pool, the work
1162 * item is currently queued on that pool.
1164 pwq
= get_work_pwq(work
);
1165 if (pwq
&& pwq
->pool
== pool
) {
1166 debug_work_deactivate(work
);
1169 * A delayed work item cannot be grabbed directly because
1170 * it might have linked NO_COLOR work items which, if left
1171 * on the delayed_list, will confuse pwq->nr_active
1172 * management later on and cause stall. Make sure the work
1173 * item is activated before grabbing.
1175 if (*work_data_bits(work
) & WORK_STRUCT_DELAYED
)
1176 pwq_activate_delayed_work(work
);
1178 list_del_init(&work
->entry
);
1179 pwq_dec_nr_in_flight(get_work_pwq(work
), get_work_color(work
));
1181 /* work->data points to pwq iff queued, point to pool */
1182 set_work_pool_and_keep_pending(work
, pool
->id
);
1184 spin_unlock(&pool
->lock
);
1187 spin_unlock(&pool
->lock
);
1189 local_irq_restore(*flags
);
1190 if (work_is_canceling(work
))
1197 * insert_work - insert a work into a pool
1198 * @pwq: pwq @work belongs to
1199 * @work: work to insert
1200 * @head: insertion point
1201 * @extra_flags: extra WORK_STRUCT_* flags to set
1203 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
1204 * work_struct flags.
1207 * spin_lock_irq(pool->lock).
1209 static void insert_work(struct pool_workqueue
*pwq
, struct work_struct
*work
,
1210 struct list_head
*head
, unsigned int extra_flags
)
1212 struct worker_pool
*pool
= pwq
->pool
;
1214 /* we own @work, set data and link */
1215 set_work_pwq(work
, pwq
, extra_flags
);
1216 list_add_tail(&work
->entry
, head
);
1220 * Ensure either wq_worker_sleeping() sees the above
1221 * list_add_tail() or we see zero nr_running to avoid workers lying
1222 * around lazily while there are works to be processed.
1226 if (__need_more_worker(pool
))
1227 wake_up_worker(pool
);
1231 * Test whether @work is being queued from another work executing on the
1234 static bool is_chained_work(struct workqueue_struct
*wq
)
1236 struct worker
*worker
;
1238 worker
= current_wq_worker();
1240 * Return %true iff I'm a worker execuing a work item on @wq. If
1241 * I'm @worker, it's safe to dereference it without locking.
1243 return worker
&& worker
->current_pwq
->wq
== wq
;
1246 static void __queue_work(int cpu
, struct workqueue_struct
*wq
,
1247 struct work_struct
*work
)
1249 struct pool_workqueue
*pwq
;
1250 struct worker_pool
*last_pool
;
1251 struct list_head
*worklist
;
1252 unsigned int work_flags
;
1253 unsigned int req_cpu
= cpu
;
1256 * While a work item is PENDING && off queue, a task trying to
1257 * steal the PENDING will busy-loop waiting for it to either get
1258 * queued or lose PENDING. Grabbing PENDING and queueing should
1259 * happen with IRQ disabled.
1261 WARN_ON_ONCE(!irqs_disabled());
1263 debug_work_activate(work
);
1265 /* if dying, only works from the same workqueue are allowed */
1266 if (unlikely(wq
->flags
& __WQ_DRAINING
) &&
1267 WARN_ON_ONCE(!is_chained_work(wq
)))
1270 /* pwq which will be used unless @work is executing elsewhere */
1271 if (!(wq
->flags
& WQ_UNBOUND
)) {
1272 if (cpu
== WORK_CPU_UNBOUND
)
1273 cpu
= raw_smp_processor_id();
1274 pwq
= per_cpu_ptr(wq
->cpu_pwqs
, cpu
);
1276 pwq
= first_pwq(wq
);
1280 * If @work was previously on a different pool, it might still be
1281 * running there, in which case the work needs to be queued on that
1282 * pool to guarantee non-reentrancy.
1284 last_pool
= get_work_pool(work
);
1285 if (last_pool
&& last_pool
!= pwq
->pool
) {
1286 struct worker
*worker
;
1288 spin_lock(&last_pool
->lock
);
1290 worker
= find_worker_executing_work(last_pool
, work
);
1292 if (worker
&& worker
->current_pwq
->wq
== wq
) {
1293 pwq
= worker
->current_pwq
;
1295 /* meh... not running there, queue here */
1296 spin_unlock(&last_pool
->lock
);
1297 spin_lock(&pwq
->pool
->lock
);
1300 spin_lock(&pwq
->pool
->lock
);
1304 * pwq is determined and locked. For unbound pools, we could have
1305 * raced with pwq release and it could already be dead. If its
1306 * refcnt is zero, repeat pwq selection. Note that pwqs never die
1307 * without another pwq replacing it as the first pwq or while a
1308 * work item is executing on it, so the retying is guaranteed to
1309 * make forward-progress.
1311 if (unlikely(!pwq
->refcnt
)) {
1312 if (wq
->flags
& WQ_UNBOUND
) {
1313 spin_unlock(&pwq
->pool
->lock
);
1318 WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
1322 /* pwq determined, queue */
1323 trace_workqueue_queue_work(req_cpu
, pwq
, work
);
1325 if (WARN_ON(!list_empty(&work
->entry
))) {
1326 spin_unlock(&pwq
->pool
->lock
);
1330 pwq
->nr_in_flight
[pwq
->work_color
]++;
1331 work_flags
= work_color_to_flags(pwq
->work_color
);
1333 if (likely(pwq
->nr_active
< pwq
->max_active
)) {
1334 trace_workqueue_activate_work(work
);
1336 worklist
= &pwq
->pool
->worklist
;
1338 work_flags
|= WORK_STRUCT_DELAYED
;
1339 worklist
= &pwq
->delayed_works
;
1342 insert_work(pwq
, work
, worklist
, work_flags
);
1344 spin_unlock(&pwq
->pool
->lock
);
1348 * queue_work_on - queue work on specific cpu
1349 * @cpu: CPU number to execute work on
1350 * @wq: workqueue to use
1351 * @work: work to queue
1353 * Returns %false if @work was already on a queue, %true otherwise.
1355 * We queue the work to a specific CPU, the caller must ensure it
1358 bool queue_work_on(int cpu
, struct workqueue_struct
*wq
,
1359 struct work_struct
*work
)
1362 unsigned long flags
;
1364 local_irq_save(flags
);
1366 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(work
))) {
1367 __queue_work(cpu
, wq
, work
);
1371 local_irq_restore(flags
);
1374 EXPORT_SYMBOL_GPL(queue_work_on
);
1376 void delayed_work_timer_fn(unsigned long __data
)
1378 struct delayed_work
*dwork
= (struct delayed_work
*)__data
;
1380 /* should have been called from irqsafe timer with irq already off */
1381 __queue_work(dwork
->cpu
, dwork
->wq
, &dwork
->work
);
1383 EXPORT_SYMBOL(delayed_work_timer_fn
);
1385 static void __queue_delayed_work(int cpu
, struct workqueue_struct
*wq
,
1386 struct delayed_work
*dwork
, unsigned long delay
)
1388 struct timer_list
*timer
= &dwork
->timer
;
1389 struct work_struct
*work
= &dwork
->work
;
1391 WARN_ON_ONCE(timer
->function
!= delayed_work_timer_fn
||
1392 timer
->data
!= (unsigned long)dwork
);
1393 WARN_ON_ONCE(timer_pending(timer
));
1394 WARN_ON_ONCE(!list_empty(&work
->entry
));
1397 * If @delay is 0, queue @dwork->work immediately. This is for
1398 * both optimization and correctness. The earliest @timer can
1399 * expire is on the closest next tick and delayed_work users depend
1400 * on that there's no such delay when @delay is 0.
1403 __queue_work(cpu
, wq
, &dwork
->work
);
1407 timer_stats_timer_set_start_info(&dwork
->timer
);
1411 timer
->expires
= jiffies
+ delay
;
1413 if (unlikely(cpu
!= WORK_CPU_UNBOUND
))
1414 add_timer_on(timer
, cpu
);
1420 * queue_delayed_work_on - queue work on specific CPU after delay
1421 * @cpu: CPU number to execute work on
1422 * @wq: workqueue to use
1423 * @dwork: work to queue
1424 * @delay: number of jiffies to wait before queueing
1426 * Returns %false if @work was already on a queue, %true otherwise. If
1427 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1430 bool queue_delayed_work_on(int cpu
, struct workqueue_struct
*wq
,
1431 struct delayed_work
*dwork
, unsigned long delay
)
1433 struct work_struct
*work
= &dwork
->work
;
1435 unsigned long flags
;
1437 /* read the comment in __queue_work() */
1438 local_irq_save(flags
);
1440 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(work
))) {
1441 __queue_delayed_work(cpu
, wq
, dwork
, delay
);
1445 local_irq_restore(flags
);
1448 EXPORT_SYMBOL_GPL(queue_delayed_work_on
);
1451 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1452 * @cpu: CPU number to execute work on
1453 * @wq: workqueue to use
1454 * @dwork: work to queue
1455 * @delay: number of jiffies to wait before queueing
1457 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1458 * modify @dwork's timer so that it expires after @delay. If @delay is
1459 * zero, @work is guaranteed to be scheduled immediately regardless of its
1462 * Returns %false if @dwork was idle and queued, %true if @dwork was
1463 * pending and its timer was modified.
1465 * This function is safe to call from any context including IRQ handler.
1466 * See try_to_grab_pending() for details.
1468 bool mod_delayed_work_on(int cpu
, struct workqueue_struct
*wq
,
1469 struct delayed_work
*dwork
, unsigned long delay
)
1471 unsigned long flags
;
1475 ret
= try_to_grab_pending(&dwork
->work
, true, &flags
);
1476 } while (unlikely(ret
== -EAGAIN
));
1478 if (likely(ret
>= 0)) {
1479 __queue_delayed_work(cpu
, wq
, dwork
, delay
);
1480 local_irq_restore(flags
);
1483 /* -ENOENT from try_to_grab_pending() becomes %true */
1486 EXPORT_SYMBOL_GPL(mod_delayed_work_on
);
1489 * worker_enter_idle - enter idle state
1490 * @worker: worker which is entering idle state
1492 * @worker is entering idle state. Update stats and idle timer if
1496 * spin_lock_irq(pool->lock).
1498 static void worker_enter_idle(struct worker
*worker
)
1500 struct worker_pool
*pool
= worker
->pool
;
1502 if (WARN_ON_ONCE(worker
->flags
& WORKER_IDLE
) ||
1503 WARN_ON_ONCE(!list_empty(&worker
->entry
) &&
1504 (worker
->hentry
.next
|| worker
->hentry
.pprev
)))
1507 /* can't use worker_set_flags(), also called from start_worker() */
1508 worker
->flags
|= WORKER_IDLE
;
1510 worker
->last_active
= jiffies
;
1512 /* idle_list is LIFO */
1513 list_add(&worker
->entry
, &pool
->idle_list
);
1515 if (too_many_workers(pool
) && !timer_pending(&pool
->idle_timer
))
1516 mod_timer(&pool
->idle_timer
, jiffies
+ IDLE_WORKER_TIMEOUT
);
1519 * Sanity check nr_running. Because wq_unbind_fn() releases
1520 * pool->lock between setting %WORKER_UNBOUND and zapping
1521 * nr_running, the warning may trigger spuriously. Check iff
1522 * unbind is not in progress.
1524 WARN_ON_ONCE(!(pool
->flags
& POOL_DISASSOCIATED
) &&
1525 pool
->nr_workers
== pool
->nr_idle
&&
1526 atomic_read(&pool
->nr_running
));
1530 * worker_leave_idle - leave idle state
1531 * @worker: worker which is leaving idle state
1533 * @worker is leaving idle state. Update stats.
1536 * spin_lock_irq(pool->lock).
1538 static void worker_leave_idle(struct worker
*worker
)
1540 struct worker_pool
*pool
= worker
->pool
;
1542 if (WARN_ON_ONCE(!(worker
->flags
& WORKER_IDLE
)))
1544 worker_clr_flags(worker
, WORKER_IDLE
);
1546 list_del_init(&worker
->entry
);
1550 * worker_maybe_bind_and_lock - try to bind %current to worker_pool and lock it
1551 * @pool: target worker_pool
1553 * Bind %current to the cpu of @pool if it is associated and lock @pool.
1555 * Works which are scheduled while the cpu is online must at least be
1556 * scheduled to a worker which is bound to the cpu so that if they are
1557 * flushed from cpu callbacks while cpu is going down, they are
1558 * guaranteed to execute on the cpu.
1560 * This function is to be used by unbound workers and rescuers to bind
1561 * themselves to the target cpu and may race with cpu going down or
1562 * coming online. kthread_bind() can't be used because it may put the
1563 * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1564 * verbatim as it's best effort and blocking and pool may be
1565 * [dis]associated in the meantime.
1567 * This function tries set_cpus_allowed() and locks pool and verifies the
1568 * binding against %POOL_DISASSOCIATED which is set during
1569 * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
1570 * enters idle state or fetches works without dropping lock, it can
1571 * guarantee the scheduling requirement described in the first paragraph.
1574 * Might sleep. Called without any lock but returns with pool->lock
1578 * %true if the associated pool is online (@worker is successfully
1579 * bound), %false if offline.
1581 static bool worker_maybe_bind_and_lock(struct worker_pool
*pool
)
1582 __acquires(&pool
->lock
)
1586 * The following call may fail, succeed or succeed
1587 * without actually migrating the task to the cpu if
1588 * it races with cpu hotunplug operation. Verify
1589 * against POOL_DISASSOCIATED.
1591 if (!(pool
->flags
& POOL_DISASSOCIATED
))
1592 set_cpus_allowed_ptr(current
, pool
->attrs
->cpumask
);
1594 spin_lock_irq(&pool
->lock
);
1595 if (pool
->flags
& POOL_DISASSOCIATED
)
1597 if (task_cpu(current
) == pool
->cpu
&&
1598 cpumask_equal(¤t
->cpus_allowed
, pool
->attrs
->cpumask
))
1600 spin_unlock_irq(&pool
->lock
);
1603 * We've raced with CPU hot[un]plug. Give it a breather
1604 * and retry migration. cond_resched() is required here;
1605 * otherwise, we might deadlock against cpu_stop trying to
1606 * bring down the CPU on non-preemptive kernel.
1613 static struct worker
*alloc_worker(void)
1615 struct worker
*worker
;
1617 worker
= kzalloc(sizeof(*worker
), GFP_KERNEL
);
1619 INIT_LIST_HEAD(&worker
->entry
);
1620 INIT_LIST_HEAD(&worker
->scheduled
);
1621 /* on creation a worker is in !idle && prep state */
1622 worker
->flags
= WORKER_PREP
;
1628 * create_worker - create a new workqueue worker
1629 * @pool: pool the new worker will belong to
1631 * Create a new worker which is bound to @pool. The returned worker
1632 * can be started by calling start_worker() or destroyed using
1636 * Might sleep. Does GFP_KERNEL allocations.
1639 * Pointer to the newly created worker.
1641 static struct worker
*create_worker(struct worker_pool
*pool
)
1643 const char *pri
= pool
->attrs
->nice
< 0 ? "H" : "";
1644 struct worker
*worker
= NULL
;
1647 lockdep_assert_held(&pool
->manager_mutex
);
1650 * ID is needed to determine kthread name. Allocate ID first
1651 * without installing the pointer.
1653 idr_preload(GFP_KERNEL
);
1654 spin_lock_irq(&pool
->lock
);
1656 id
= idr_alloc(&pool
->worker_idr
, NULL
, 0, 0, GFP_NOWAIT
);
1658 spin_unlock_irq(&pool
->lock
);
1663 worker
= alloc_worker();
1667 worker
->pool
= pool
;
1671 worker
->task
= kthread_create_on_node(worker_thread
,
1672 worker
, cpu_to_node(pool
->cpu
),
1673 "kworker/%d:%d%s", pool
->cpu
, id
, pri
);
1675 worker
->task
= kthread_create(worker_thread
, worker
,
1678 if (IS_ERR(worker
->task
))
1682 * set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
1683 * online CPUs. It'll be re-applied when any of the CPUs come up.
1685 set_user_nice(worker
->task
, pool
->attrs
->nice
);
1686 set_cpus_allowed_ptr(worker
->task
, pool
->attrs
->cpumask
);
1688 /* prevent userland from meddling with cpumask of workqueue workers */
1689 worker
->task
->flags
|= PF_NO_SETAFFINITY
;
1692 * The caller is responsible for ensuring %POOL_DISASSOCIATED
1693 * remains stable across this function. See the comments above the
1694 * flag definition for details.
1696 if (pool
->flags
& POOL_DISASSOCIATED
)
1697 worker
->flags
|= WORKER_UNBOUND
;
1699 /* successful, commit the pointer to idr */
1700 spin_lock_irq(&pool
->lock
);
1701 idr_replace(&pool
->worker_idr
, worker
, worker
->id
);
1702 spin_unlock_irq(&pool
->lock
);
1708 spin_lock_irq(&pool
->lock
);
1709 idr_remove(&pool
->worker_idr
, id
);
1710 spin_unlock_irq(&pool
->lock
);
1717 * start_worker - start a newly created worker
1718 * @worker: worker to start
1720 * Make the pool aware of @worker and start it.
1723 * spin_lock_irq(pool->lock).
1725 static void start_worker(struct worker
*worker
)
1727 worker
->flags
|= WORKER_STARTED
;
1728 worker
->pool
->nr_workers
++;
1729 worker_enter_idle(worker
);
1730 wake_up_process(worker
->task
);
1734 * create_and_start_worker - create and start a worker for a pool
1735 * @pool: the target pool
1737 * Grab the managership of @pool and create and start a new worker for it.
1739 static int create_and_start_worker(struct worker_pool
*pool
)
1741 struct worker
*worker
;
1743 mutex_lock(&pool
->manager_mutex
);
1745 worker
= create_worker(pool
);
1747 spin_lock_irq(&pool
->lock
);
1748 start_worker(worker
);
1749 spin_unlock_irq(&pool
->lock
);
1752 mutex_unlock(&pool
->manager_mutex
);
1754 return worker
? 0 : -ENOMEM
;
1758 * destroy_worker - destroy a workqueue worker
1759 * @worker: worker to be destroyed
1761 * Destroy @worker and adjust @pool stats accordingly.
1764 * spin_lock_irq(pool->lock) which is released and regrabbed.
1766 static void destroy_worker(struct worker
*worker
)
1768 struct worker_pool
*pool
= worker
->pool
;
1770 lockdep_assert_held(&pool
->manager_mutex
);
1771 lockdep_assert_held(&pool
->lock
);
1773 /* sanity check frenzy */
1774 if (WARN_ON(worker
->current_work
) ||
1775 WARN_ON(!list_empty(&worker
->scheduled
)))
1778 if (worker
->flags
& WORKER_STARTED
)
1780 if (worker
->flags
& WORKER_IDLE
)
1783 list_del_init(&worker
->entry
);
1784 worker
->flags
|= WORKER_DIE
;
1786 idr_remove(&pool
->worker_idr
, worker
->id
);
1788 spin_unlock_irq(&pool
->lock
);
1790 kthread_stop(worker
->task
);
1793 spin_lock_irq(&pool
->lock
);
1796 static void idle_worker_timeout(unsigned long __pool
)
1798 struct worker_pool
*pool
= (void *)__pool
;
1800 spin_lock_irq(&pool
->lock
);
1802 if (too_many_workers(pool
)) {
1803 struct worker
*worker
;
1804 unsigned long expires
;
1806 /* idle_list is kept in LIFO order, check the last one */
1807 worker
= list_entry(pool
->idle_list
.prev
, struct worker
, entry
);
1808 expires
= worker
->last_active
+ IDLE_WORKER_TIMEOUT
;
1810 if (time_before(jiffies
, expires
))
1811 mod_timer(&pool
->idle_timer
, expires
);
1813 /* it's been idle for too long, wake up manager */
1814 pool
->flags
|= POOL_MANAGE_WORKERS
;
1815 wake_up_worker(pool
);
1819 spin_unlock_irq(&pool
->lock
);
1822 static void send_mayday(struct work_struct
*work
)
1824 struct pool_workqueue
*pwq
= get_work_pwq(work
);
1825 struct workqueue_struct
*wq
= pwq
->wq
;
1827 lockdep_assert_held(&wq_mayday_lock
);
1832 /* mayday mayday mayday */
1833 if (list_empty(&pwq
->mayday_node
)) {
1834 list_add_tail(&pwq
->mayday_node
, &wq
->maydays
);
1835 wake_up_process(wq
->rescuer
->task
);
1839 static void pool_mayday_timeout(unsigned long __pool
)
1841 struct worker_pool
*pool
= (void *)__pool
;
1842 struct work_struct
*work
;
1844 spin_lock_irq(&wq_mayday_lock
); /* for wq->maydays */
1845 spin_lock(&pool
->lock
);
1847 if (need_to_create_worker(pool
)) {
1849 * We've been trying to create a new worker but
1850 * haven't been successful. We might be hitting an
1851 * allocation deadlock. Send distress signals to
1854 list_for_each_entry(work
, &pool
->worklist
, entry
)
1858 spin_unlock(&pool
->lock
);
1859 spin_unlock_irq(&wq_mayday_lock
);
1861 mod_timer(&pool
->mayday_timer
, jiffies
+ MAYDAY_INTERVAL
);
1865 * maybe_create_worker - create a new worker if necessary
1866 * @pool: pool to create a new worker for
1868 * Create a new worker for @pool if necessary. @pool is guaranteed to
1869 * have at least one idle worker on return from this function. If
1870 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1871 * sent to all rescuers with works scheduled on @pool to resolve
1872 * possible allocation deadlock.
1874 * On return, need_to_create_worker() is guaranteed to be %false and
1875 * may_start_working() %true.
1878 * spin_lock_irq(pool->lock) which may be released and regrabbed
1879 * multiple times. Does GFP_KERNEL allocations. Called only from
1883 * %false if no action was taken and pool->lock stayed locked, %true
1886 static bool maybe_create_worker(struct worker_pool
*pool
)
1887 __releases(&pool
->lock
)
1888 __acquires(&pool
->lock
)
1890 if (!need_to_create_worker(pool
))
1893 spin_unlock_irq(&pool
->lock
);
1895 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1896 mod_timer(&pool
->mayday_timer
, jiffies
+ MAYDAY_INITIAL_TIMEOUT
);
1899 struct worker
*worker
;
1901 worker
= create_worker(pool
);
1903 del_timer_sync(&pool
->mayday_timer
);
1904 spin_lock_irq(&pool
->lock
);
1905 start_worker(worker
);
1906 if (WARN_ON_ONCE(need_to_create_worker(pool
)))
1911 if (!need_to_create_worker(pool
))
1914 __set_current_state(TASK_INTERRUPTIBLE
);
1915 schedule_timeout(CREATE_COOLDOWN
);
1917 if (!need_to_create_worker(pool
))
1921 del_timer_sync(&pool
->mayday_timer
);
1922 spin_lock_irq(&pool
->lock
);
1923 if (need_to_create_worker(pool
))
1929 * maybe_destroy_worker - destroy workers which have been idle for a while
1930 * @pool: pool to destroy workers for
1932 * Destroy @pool workers which have been idle for longer than
1933 * IDLE_WORKER_TIMEOUT.
1936 * spin_lock_irq(pool->lock) which may be released and regrabbed
1937 * multiple times. Called only from manager.
1940 * %false if no action was taken and pool->lock stayed locked, %true
1943 static bool maybe_destroy_workers(struct worker_pool
*pool
)
1947 while (too_many_workers(pool
)) {
1948 struct worker
*worker
;
1949 unsigned long expires
;
1951 worker
= list_entry(pool
->idle_list
.prev
, struct worker
, entry
);
1952 expires
= worker
->last_active
+ IDLE_WORKER_TIMEOUT
;
1954 if (time_before(jiffies
, expires
)) {
1955 mod_timer(&pool
->idle_timer
, expires
);
1959 destroy_worker(worker
);
1967 * manage_workers - manage worker pool
1970 * Assume the manager role and manage the worker pool @worker belongs
1971 * to. At any given time, there can be only zero or one manager per
1972 * pool. The exclusion is handled automatically by this function.
1974 * The caller can safely start processing works on false return. On
1975 * true return, it's guaranteed that need_to_create_worker() is false
1976 * and may_start_working() is true.
1979 * spin_lock_irq(pool->lock) which may be released and regrabbed
1980 * multiple times. Does GFP_KERNEL allocations.
1983 * spin_lock_irq(pool->lock) which may be released and regrabbed
1984 * multiple times. Does GFP_KERNEL allocations.
1986 static bool manage_workers(struct worker
*worker
)
1988 struct worker_pool
*pool
= worker
->pool
;
1992 * Managership is governed by two mutexes - manager_arb and
1993 * manager_mutex. manager_arb handles arbitration of manager role.
1994 * Anyone who successfully grabs manager_arb wins the arbitration
1995 * and becomes the manager. mutex_trylock() on pool->manager_arb
1996 * failure while holding pool->lock reliably indicates that someone
1997 * else is managing the pool and the worker which failed trylock
1998 * can proceed to executing work items. This means that anyone
1999 * grabbing manager_arb is responsible for actually performing
2000 * manager duties. If manager_arb is grabbed and released without
2001 * actual management, the pool may stall indefinitely.
2003 * manager_mutex is used for exclusion of actual management
2004 * operations. The holder of manager_mutex can be sure that none
2005 * of management operations, including creation and destruction of
2006 * workers, won't take place until the mutex is released. Because
2007 * manager_mutex doesn't interfere with manager role arbitration,
2008 * it is guaranteed that the pool's management, while may be
2009 * delayed, won't be disturbed by someone else grabbing
2012 if (!mutex_trylock(&pool
->manager_arb
))
2016 * With manager arbitration won, manager_mutex would be free in
2017 * most cases. trylock first without dropping @pool->lock.
2019 if (unlikely(!mutex_trylock(&pool
->manager_mutex
))) {
2020 spin_unlock_irq(&pool
->lock
);
2021 mutex_lock(&pool
->manager_mutex
);
2025 pool
->flags
&= ~POOL_MANAGE_WORKERS
;
2028 * Destroy and then create so that may_start_working() is true
2031 ret
|= maybe_destroy_workers(pool
);
2032 ret
|= maybe_create_worker(pool
);
2034 mutex_unlock(&pool
->manager_mutex
);
2035 mutex_unlock(&pool
->manager_arb
);
2040 * process_one_work - process single work
2042 * @work: work to process
2044 * Process @work. This function contains all the logics necessary to
2045 * process a single work including synchronization against and
2046 * interaction with other workers on the same cpu, queueing and
2047 * flushing. As long as context requirement is met, any worker can
2048 * call this function to process a work.
2051 * spin_lock_irq(pool->lock) which is released and regrabbed.
2053 static void process_one_work(struct worker
*worker
, struct work_struct
*work
)
2054 __releases(&pool
->lock
)
2055 __acquires(&pool
->lock
)
2057 struct pool_workqueue
*pwq
= get_work_pwq(work
);
2058 struct worker_pool
*pool
= worker
->pool
;
2059 bool cpu_intensive
= pwq
->wq
->flags
& WQ_CPU_INTENSIVE
;
2061 struct worker
*collision
;
2062 #ifdef CONFIG_LOCKDEP
2064 * It is permissible to free the struct work_struct from
2065 * inside the function that is called from it, this we need to
2066 * take into account for lockdep too. To avoid bogus "held
2067 * lock freed" warnings as well as problems when looking into
2068 * work->lockdep_map, make a copy and use that here.
2070 struct lockdep_map lockdep_map
;
2072 lockdep_copy_map(&lockdep_map
, &work
->lockdep_map
);
2075 * Ensure we're on the correct CPU. DISASSOCIATED test is
2076 * necessary to avoid spurious warnings from rescuers servicing the
2077 * unbound or a disassociated pool.
2079 WARN_ON_ONCE(!(worker
->flags
& WORKER_UNBOUND
) &&
2080 !(pool
->flags
& POOL_DISASSOCIATED
) &&
2081 raw_smp_processor_id() != pool
->cpu
);
2084 * A single work shouldn't be executed concurrently by
2085 * multiple workers on a single cpu. Check whether anyone is
2086 * already processing the work. If so, defer the work to the
2087 * currently executing one.
2089 collision
= find_worker_executing_work(pool
, work
);
2090 if (unlikely(collision
)) {
2091 move_linked_works(work
, &collision
->scheduled
, NULL
);
2095 /* claim and dequeue */
2096 debug_work_deactivate(work
);
2097 hash_add(pool
->busy_hash
, &worker
->hentry
, (unsigned long)work
);
2098 worker
->current_work
= work
;
2099 worker
->current_func
= work
->func
;
2100 worker
->current_pwq
= pwq
;
2101 work_color
= get_work_color(work
);
2103 list_del_init(&work
->entry
);
2106 * CPU intensive works don't participate in concurrency
2107 * management. They're the scheduler's responsibility.
2109 if (unlikely(cpu_intensive
))
2110 worker_set_flags(worker
, WORKER_CPU_INTENSIVE
, true);
2113 * Unbound pool isn't concurrency managed and work items should be
2114 * executed ASAP. Wake up another worker if necessary.
2116 if ((worker
->flags
& WORKER_UNBOUND
) && need_more_worker(pool
))
2117 wake_up_worker(pool
);
2120 * Record the last pool and clear PENDING which should be the last
2121 * update to @work. Also, do this inside @pool->lock so that
2122 * PENDING and queued state changes happen together while IRQ is
2125 set_work_pool_and_clear_pending(work
, pool
->id
);
2127 spin_unlock_irq(&pool
->lock
);
2129 lock_map_acquire_read(&pwq
->wq
->lockdep_map
);
2130 lock_map_acquire(&lockdep_map
);
2131 trace_workqueue_execute_start(work
);
2132 worker
->current_func(work
);
2134 * While we must be careful to not use "work" after this, the trace
2135 * point will only record its address.
2137 trace_workqueue_execute_end(work
);
2138 lock_map_release(&lockdep_map
);
2139 lock_map_release(&pwq
->wq
->lockdep_map
);
2141 if (unlikely(in_atomic() || lockdep_depth(current
) > 0)) {
2142 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2143 " last function: %pf\n",
2144 current
->comm
, preempt_count(), task_pid_nr(current
),
2145 worker
->current_func
);
2146 debug_show_held_locks(current
);
2150 spin_lock_irq(&pool
->lock
);
2152 /* clear cpu intensive status */
2153 if (unlikely(cpu_intensive
))
2154 worker_clr_flags(worker
, WORKER_CPU_INTENSIVE
);
2156 /* we're done with it, release */
2157 hash_del(&worker
->hentry
);
2158 worker
->current_work
= NULL
;
2159 worker
->current_func
= NULL
;
2160 worker
->current_pwq
= NULL
;
2161 pwq_dec_nr_in_flight(pwq
, work_color
);
2165 * process_scheduled_works - process scheduled works
2168 * Process all scheduled works. Please note that the scheduled list
2169 * may change while processing a work, so this function repeatedly
2170 * fetches a work from the top and executes it.
2173 * spin_lock_irq(pool->lock) which may be released and regrabbed
2176 static void process_scheduled_works(struct worker
*worker
)
2178 while (!list_empty(&worker
->scheduled
)) {
2179 struct work_struct
*work
= list_first_entry(&worker
->scheduled
,
2180 struct work_struct
, entry
);
2181 process_one_work(worker
, work
);
2186 * worker_thread - the worker thread function
2189 * The worker thread function. All workers belong to a worker_pool -
2190 * either a per-cpu one or dynamic unbound one. These workers process all
2191 * work items regardless of their specific target workqueue. The only
2192 * exception is work items which belong to workqueues with a rescuer which
2193 * will be explained in rescuer_thread().
2195 static int worker_thread(void *__worker
)
2197 struct worker
*worker
= __worker
;
2198 struct worker_pool
*pool
= worker
->pool
;
2200 /* tell the scheduler that this is a workqueue worker */
2201 worker
->task
->flags
|= PF_WQ_WORKER
;
2203 spin_lock_irq(&pool
->lock
);
2205 /* am I supposed to die? */
2206 if (unlikely(worker
->flags
& WORKER_DIE
)) {
2207 spin_unlock_irq(&pool
->lock
);
2208 WARN_ON_ONCE(!list_empty(&worker
->entry
));
2209 worker
->task
->flags
&= ~PF_WQ_WORKER
;
2213 worker_leave_idle(worker
);
2215 /* no more worker necessary? */
2216 if (!need_more_worker(pool
))
2219 /* do we need to manage? */
2220 if (unlikely(!may_start_working(pool
)) && manage_workers(worker
))
2224 * ->scheduled list can only be filled while a worker is
2225 * preparing to process a work or actually processing it.
2226 * Make sure nobody diddled with it while I was sleeping.
2228 WARN_ON_ONCE(!list_empty(&worker
->scheduled
));
2231 * Finish PREP stage. We're guaranteed to have at least one idle
2232 * worker or that someone else has already assumed the manager
2233 * role. This is where @worker starts participating in concurrency
2234 * management if applicable and concurrency management is restored
2235 * after being rebound. See rebind_workers() for details.
2237 worker_clr_flags(worker
, WORKER_PREP
| WORKER_REBOUND
);
2240 struct work_struct
*work
=
2241 list_first_entry(&pool
->worklist
,
2242 struct work_struct
, entry
);
2244 if (likely(!(*work_data_bits(work
) & WORK_STRUCT_LINKED
))) {
2245 /* optimization path, not strictly necessary */
2246 process_one_work(worker
, work
);
2247 if (unlikely(!list_empty(&worker
->scheduled
)))
2248 process_scheduled_works(worker
);
2250 move_linked_works(work
, &worker
->scheduled
, NULL
);
2251 process_scheduled_works(worker
);
2253 } while (keep_working(pool
));
2255 worker_set_flags(worker
, WORKER_PREP
, false);
2257 if (unlikely(need_to_manage_workers(pool
)) && manage_workers(worker
))
2261 * pool->lock is held and there's no work to process and no need to
2262 * manage, sleep. Workers are woken up only while holding
2263 * pool->lock or from local cpu, so setting the current state
2264 * before releasing pool->lock is enough to prevent losing any
2267 worker_enter_idle(worker
);
2268 __set_current_state(TASK_INTERRUPTIBLE
);
2269 spin_unlock_irq(&pool
->lock
);
2275 * rescuer_thread - the rescuer thread function
2278 * Workqueue rescuer thread function. There's one rescuer for each
2279 * workqueue which has WQ_MEM_RECLAIM set.
2281 * Regular work processing on a pool may block trying to create a new
2282 * worker which uses GFP_KERNEL allocation which has slight chance of
2283 * developing into deadlock if some works currently on the same queue
2284 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2285 * the problem rescuer solves.
2287 * When such condition is possible, the pool summons rescuers of all
2288 * workqueues which have works queued on the pool and let them process
2289 * those works so that forward progress can be guaranteed.
2291 * This should happen rarely.
2293 static int rescuer_thread(void *__rescuer
)
2295 struct worker
*rescuer
= __rescuer
;
2296 struct workqueue_struct
*wq
= rescuer
->rescue_wq
;
2297 struct list_head
*scheduled
= &rescuer
->scheduled
;
2299 set_user_nice(current
, RESCUER_NICE_LEVEL
);
2302 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2303 * doesn't participate in concurrency management.
2305 rescuer
->task
->flags
|= PF_WQ_WORKER
;
2307 set_current_state(TASK_INTERRUPTIBLE
);
2309 if (kthread_should_stop()) {
2310 __set_current_state(TASK_RUNNING
);
2311 rescuer
->task
->flags
&= ~PF_WQ_WORKER
;
2315 /* see whether any pwq is asking for help */
2316 spin_lock_irq(&wq_mayday_lock
);
2318 while (!list_empty(&wq
->maydays
)) {
2319 struct pool_workqueue
*pwq
= list_first_entry(&wq
->maydays
,
2320 struct pool_workqueue
, mayday_node
);
2321 struct worker_pool
*pool
= pwq
->pool
;
2322 struct work_struct
*work
, *n
;
2324 __set_current_state(TASK_RUNNING
);
2325 list_del_init(&pwq
->mayday_node
);
2327 spin_unlock_irq(&wq_mayday_lock
);
2329 /* migrate to the target cpu if possible */
2330 worker_maybe_bind_and_lock(pool
);
2331 rescuer
->pool
= pool
;
2334 * Slurp in all works issued via this workqueue and
2337 WARN_ON_ONCE(!list_empty(&rescuer
->scheduled
));
2338 list_for_each_entry_safe(work
, n
, &pool
->worklist
, entry
)
2339 if (get_work_pwq(work
) == pwq
)
2340 move_linked_works(work
, scheduled
, &n
);
2342 process_scheduled_works(rescuer
);
2345 * Leave this pool. If keep_working() is %true, notify a
2346 * regular worker; otherwise, we end up with 0 concurrency
2347 * and stalling the execution.
2349 if (keep_working(pool
))
2350 wake_up_worker(pool
);
2352 rescuer
->pool
= NULL
;
2353 spin_unlock(&pool
->lock
);
2354 spin_lock(&wq_mayday_lock
);
2357 spin_unlock_irq(&wq_mayday_lock
);
2359 /* rescuers should never participate in concurrency management */
2360 WARN_ON_ONCE(!(rescuer
->flags
& WORKER_NOT_RUNNING
));
2366 struct work_struct work
;
2367 struct completion done
;
2370 static void wq_barrier_func(struct work_struct
*work
)
2372 struct wq_barrier
*barr
= container_of(work
, struct wq_barrier
, work
);
2373 complete(&barr
->done
);
2377 * insert_wq_barrier - insert a barrier work
2378 * @pwq: pwq to insert barrier into
2379 * @barr: wq_barrier to insert
2380 * @target: target work to attach @barr to
2381 * @worker: worker currently executing @target, NULL if @target is not executing
2383 * @barr is linked to @target such that @barr is completed only after
2384 * @target finishes execution. Please note that the ordering
2385 * guarantee is observed only with respect to @target and on the local
2388 * Currently, a queued barrier can't be canceled. This is because
2389 * try_to_grab_pending() can't determine whether the work to be
2390 * grabbed is at the head of the queue and thus can't clear LINKED
2391 * flag of the previous work while there must be a valid next work
2392 * after a work with LINKED flag set.
2394 * Note that when @worker is non-NULL, @target may be modified
2395 * underneath us, so we can't reliably determine pwq from @target.
2398 * spin_lock_irq(pool->lock).
2400 static void insert_wq_barrier(struct pool_workqueue
*pwq
,
2401 struct wq_barrier
*barr
,
2402 struct work_struct
*target
, struct worker
*worker
)
2404 struct list_head
*head
;
2405 unsigned int linked
= 0;
2408 * debugobject calls are safe here even with pool->lock locked
2409 * as we know for sure that this will not trigger any of the
2410 * checks and call back into the fixup functions where we
2413 INIT_WORK_ONSTACK(&barr
->work
, wq_barrier_func
);
2414 __set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(&barr
->work
));
2415 init_completion(&barr
->done
);
2418 * If @target is currently being executed, schedule the
2419 * barrier to the worker; otherwise, put it after @target.
2422 head
= worker
->scheduled
.next
;
2424 unsigned long *bits
= work_data_bits(target
);
2426 head
= target
->entry
.next
;
2427 /* there can already be other linked works, inherit and set */
2428 linked
= *bits
& WORK_STRUCT_LINKED
;
2429 __set_bit(WORK_STRUCT_LINKED_BIT
, bits
);
2432 debug_work_activate(&barr
->work
);
2433 insert_work(pwq
, &barr
->work
, head
,
2434 work_color_to_flags(WORK_NO_COLOR
) | linked
);
2438 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
2439 * @wq: workqueue being flushed
2440 * @flush_color: new flush color, < 0 for no-op
2441 * @work_color: new work color, < 0 for no-op
2443 * Prepare pwqs for workqueue flushing.
2445 * If @flush_color is non-negative, flush_color on all pwqs should be
2446 * -1. If no pwq has in-flight commands at the specified color, all
2447 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
2448 * has in flight commands, its pwq->flush_color is set to
2449 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
2450 * wakeup logic is armed and %true is returned.
2452 * The caller should have initialized @wq->first_flusher prior to
2453 * calling this function with non-negative @flush_color. If
2454 * @flush_color is negative, no flush color update is done and %false
2457 * If @work_color is non-negative, all pwqs should have the same
2458 * work_color which is previous to @work_color and all will be
2459 * advanced to @work_color.
2462 * mutex_lock(wq->flush_mutex).
2465 * %true if @flush_color >= 0 and there's something to flush. %false
2468 static bool flush_workqueue_prep_pwqs(struct workqueue_struct
*wq
,
2469 int flush_color
, int work_color
)
2472 struct pool_workqueue
*pwq
;
2474 if (flush_color
>= 0) {
2475 WARN_ON_ONCE(atomic_read(&wq
->nr_pwqs_to_flush
));
2476 atomic_set(&wq
->nr_pwqs_to_flush
, 1);
2479 local_irq_disable();
2481 for_each_pwq(pwq
, wq
) {
2482 struct worker_pool
*pool
= pwq
->pool
;
2484 spin_lock(&pool
->lock
);
2486 if (flush_color
>= 0) {
2487 WARN_ON_ONCE(pwq
->flush_color
!= -1);
2489 if (pwq
->nr_in_flight
[flush_color
]) {
2490 pwq
->flush_color
= flush_color
;
2491 atomic_inc(&wq
->nr_pwqs_to_flush
);
2496 if (work_color
>= 0) {
2497 WARN_ON_ONCE(work_color
!= work_next_color(pwq
->work_color
));
2498 pwq
->work_color
= work_color
;
2501 spin_unlock(&pool
->lock
);
2506 if (flush_color
>= 0 && atomic_dec_and_test(&wq
->nr_pwqs_to_flush
))
2507 complete(&wq
->first_flusher
->done
);
2513 * flush_workqueue - ensure that any scheduled work has run to completion.
2514 * @wq: workqueue to flush
2516 * This function sleeps until all work items which were queued on entry
2517 * have finished execution, but it is not livelocked by new incoming ones.
2519 void flush_workqueue(struct workqueue_struct
*wq
)
2521 struct wq_flusher this_flusher
= {
2522 .list
= LIST_HEAD_INIT(this_flusher
.list
),
2524 .done
= COMPLETION_INITIALIZER_ONSTACK(this_flusher
.done
),
2528 lock_map_acquire(&wq
->lockdep_map
);
2529 lock_map_release(&wq
->lockdep_map
);
2531 mutex_lock(&wq
->flush_mutex
);
2534 * Start-to-wait phase
2536 next_color
= work_next_color(wq
->work_color
);
2538 if (next_color
!= wq
->flush_color
) {
2540 * Color space is not full. The current work_color
2541 * becomes our flush_color and work_color is advanced
2544 WARN_ON_ONCE(!list_empty(&wq
->flusher_overflow
));
2545 this_flusher
.flush_color
= wq
->work_color
;
2546 wq
->work_color
= next_color
;
2548 if (!wq
->first_flusher
) {
2549 /* no flush in progress, become the first flusher */
2550 WARN_ON_ONCE(wq
->flush_color
!= this_flusher
.flush_color
);
2552 wq
->first_flusher
= &this_flusher
;
2554 if (!flush_workqueue_prep_pwqs(wq
, wq
->flush_color
,
2556 /* nothing to flush, done */
2557 wq
->flush_color
= next_color
;
2558 wq
->first_flusher
= NULL
;
2563 WARN_ON_ONCE(wq
->flush_color
== this_flusher
.flush_color
);
2564 list_add_tail(&this_flusher
.list
, &wq
->flusher_queue
);
2565 flush_workqueue_prep_pwqs(wq
, -1, wq
->work_color
);
2569 * Oops, color space is full, wait on overflow queue.
2570 * The next flush completion will assign us
2571 * flush_color and transfer to flusher_queue.
2573 list_add_tail(&this_flusher
.list
, &wq
->flusher_overflow
);
2576 mutex_unlock(&wq
->flush_mutex
);
2578 wait_for_completion(&this_flusher
.done
);
2581 * Wake-up-and-cascade phase
2583 * First flushers are responsible for cascading flushes and
2584 * handling overflow. Non-first flushers can simply return.
2586 if (wq
->first_flusher
!= &this_flusher
)
2589 mutex_lock(&wq
->flush_mutex
);
2591 /* we might have raced, check again with mutex held */
2592 if (wq
->first_flusher
!= &this_flusher
)
2595 wq
->first_flusher
= NULL
;
2597 WARN_ON_ONCE(!list_empty(&this_flusher
.list
));
2598 WARN_ON_ONCE(wq
->flush_color
!= this_flusher
.flush_color
);
2601 struct wq_flusher
*next
, *tmp
;
2603 /* complete all the flushers sharing the current flush color */
2604 list_for_each_entry_safe(next
, tmp
, &wq
->flusher_queue
, list
) {
2605 if (next
->flush_color
!= wq
->flush_color
)
2607 list_del_init(&next
->list
);
2608 complete(&next
->done
);
2611 WARN_ON_ONCE(!list_empty(&wq
->flusher_overflow
) &&
2612 wq
->flush_color
!= work_next_color(wq
->work_color
));
2614 /* this flush_color is finished, advance by one */
2615 wq
->flush_color
= work_next_color(wq
->flush_color
);
2617 /* one color has been freed, handle overflow queue */
2618 if (!list_empty(&wq
->flusher_overflow
)) {
2620 * Assign the same color to all overflowed
2621 * flushers, advance work_color and append to
2622 * flusher_queue. This is the start-to-wait
2623 * phase for these overflowed flushers.
2625 list_for_each_entry(tmp
, &wq
->flusher_overflow
, list
)
2626 tmp
->flush_color
= wq
->work_color
;
2628 wq
->work_color
= work_next_color(wq
->work_color
);
2630 list_splice_tail_init(&wq
->flusher_overflow
,
2631 &wq
->flusher_queue
);
2632 flush_workqueue_prep_pwqs(wq
, -1, wq
->work_color
);
2635 if (list_empty(&wq
->flusher_queue
)) {
2636 WARN_ON_ONCE(wq
->flush_color
!= wq
->work_color
);
2641 * Need to flush more colors. Make the next flusher
2642 * the new first flusher and arm pwqs.
2644 WARN_ON_ONCE(wq
->flush_color
== wq
->work_color
);
2645 WARN_ON_ONCE(wq
->flush_color
!= next
->flush_color
);
2647 list_del_init(&next
->list
);
2648 wq
->first_flusher
= next
;
2650 if (flush_workqueue_prep_pwqs(wq
, wq
->flush_color
, -1))
2654 * Meh... this color is already done, clear first
2655 * flusher and repeat cascading.
2657 wq
->first_flusher
= NULL
;
2661 mutex_unlock(&wq
->flush_mutex
);
2663 EXPORT_SYMBOL_GPL(flush_workqueue
);
2666 * drain_workqueue - drain a workqueue
2667 * @wq: workqueue to drain
2669 * Wait until the workqueue becomes empty. While draining is in progress,
2670 * only chain queueing is allowed. IOW, only currently pending or running
2671 * work items on @wq can queue further work items on it. @wq is flushed
2672 * repeatedly until it becomes empty. The number of flushing is detemined
2673 * by the depth of chaining and should be relatively short. Whine if it
2676 void drain_workqueue(struct workqueue_struct
*wq
)
2678 unsigned int flush_cnt
= 0;
2679 struct pool_workqueue
*pwq
;
2682 * __queue_work() needs to test whether there are drainers, is much
2683 * hotter than drain_workqueue() and already looks at @wq->flags.
2684 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
2686 mutex_lock(&wq_mutex
);
2687 if (!wq
->nr_drainers
++)
2688 wq
->flags
|= __WQ_DRAINING
;
2689 mutex_unlock(&wq_mutex
);
2691 flush_workqueue(wq
);
2693 local_irq_disable();
2695 for_each_pwq(pwq
, wq
) {
2698 spin_lock(&pwq
->pool
->lock
);
2699 drained
= !pwq
->nr_active
&& list_empty(&pwq
->delayed_works
);
2700 spin_unlock(&pwq
->pool
->lock
);
2705 if (++flush_cnt
== 10 ||
2706 (flush_cnt
% 100 == 0 && flush_cnt
<= 1000))
2707 pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
2708 wq
->name
, flush_cnt
);
2716 mutex_lock(&wq_mutex
);
2717 if (!--wq
->nr_drainers
)
2718 wq
->flags
&= ~__WQ_DRAINING
;
2719 mutex_unlock(&wq_mutex
);
2721 EXPORT_SYMBOL_GPL(drain_workqueue
);
2723 static bool start_flush_work(struct work_struct
*work
, struct wq_barrier
*barr
)
2725 struct worker
*worker
= NULL
;
2726 struct worker_pool
*pool
;
2727 struct pool_workqueue
*pwq
;
2731 local_irq_disable();
2732 pool
= get_work_pool(work
);
2738 spin_lock(&pool
->lock
);
2739 /* see the comment in try_to_grab_pending() with the same code */
2740 pwq
= get_work_pwq(work
);
2742 if (unlikely(pwq
->pool
!= pool
))
2745 worker
= find_worker_executing_work(pool
, work
);
2748 pwq
= worker
->current_pwq
;
2751 insert_wq_barrier(pwq
, barr
, work
, worker
);
2752 spin_unlock_irq(&pool
->lock
);
2755 * If @max_active is 1 or rescuer is in use, flushing another work
2756 * item on the same workqueue may lead to deadlock. Make sure the
2757 * flusher is not running on the same workqueue by verifying write
2760 if (pwq
->wq
->saved_max_active
== 1 || pwq
->wq
->rescuer
)
2761 lock_map_acquire(&pwq
->wq
->lockdep_map
);
2763 lock_map_acquire_read(&pwq
->wq
->lockdep_map
);
2764 lock_map_release(&pwq
->wq
->lockdep_map
);
2768 spin_unlock_irq(&pool
->lock
);
2773 * flush_work - wait for a work to finish executing the last queueing instance
2774 * @work: the work to flush
2776 * Wait until @work has finished execution. @work is guaranteed to be idle
2777 * on return if it hasn't been requeued since flush started.
2780 * %true if flush_work() waited for the work to finish execution,
2781 * %false if it was already idle.
2783 bool flush_work(struct work_struct
*work
)
2785 struct wq_barrier barr
;
2787 lock_map_acquire(&work
->lockdep_map
);
2788 lock_map_release(&work
->lockdep_map
);
2790 if (start_flush_work(work
, &barr
)) {
2791 wait_for_completion(&barr
.done
);
2792 destroy_work_on_stack(&barr
.work
);
2798 EXPORT_SYMBOL_GPL(flush_work
);
2800 static bool __cancel_work_timer(struct work_struct
*work
, bool is_dwork
)
2802 unsigned long flags
;
2806 ret
= try_to_grab_pending(work
, is_dwork
, &flags
);
2808 * If someone else is canceling, wait for the same event it
2809 * would be waiting for before retrying.
2811 if (unlikely(ret
== -ENOENT
))
2813 } while (unlikely(ret
< 0));
2815 /* tell other tasks trying to grab @work to back off */
2816 mark_work_canceling(work
);
2817 local_irq_restore(flags
);
2820 clear_work_data(work
);
2825 * cancel_work_sync - cancel a work and wait for it to finish
2826 * @work: the work to cancel
2828 * Cancel @work and wait for its execution to finish. This function
2829 * can be used even if the work re-queues itself or migrates to
2830 * another workqueue. On return from this function, @work is
2831 * guaranteed to be not pending or executing on any CPU.
2833 * cancel_work_sync(&delayed_work->work) must not be used for
2834 * delayed_work's. Use cancel_delayed_work_sync() instead.
2836 * The caller must ensure that the workqueue on which @work was last
2837 * queued can't be destroyed before this function returns.
2840 * %true if @work was pending, %false otherwise.
2842 bool cancel_work_sync(struct work_struct
*work
)
2844 return __cancel_work_timer(work
, false);
2846 EXPORT_SYMBOL_GPL(cancel_work_sync
);
2849 * flush_delayed_work - wait for a dwork to finish executing the last queueing
2850 * @dwork: the delayed work to flush
2852 * Delayed timer is cancelled and the pending work is queued for
2853 * immediate execution. Like flush_work(), this function only
2854 * considers the last queueing instance of @dwork.
2857 * %true if flush_work() waited for the work to finish execution,
2858 * %false if it was already idle.
2860 bool flush_delayed_work(struct delayed_work
*dwork
)
2862 local_irq_disable();
2863 if (del_timer_sync(&dwork
->timer
))
2864 __queue_work(dwork
->cpu
, dwork
->wq
, &dwork
->work
);
2866 return flush_work(&dwork
->work
);
2868 EXPORT_SYMBOL(flush_delayed_work
);
2871 * cancel_delayed_work - cancel a delayed work
2872 * @dwork: delayed_work to cancel
2874 * Kill off a pending delayed_work. Returns %true if @dwork was pending
2875 * and canceled; %false if wasn't pending. Note that the work callback
2876 * function may still be running on return, unless it returns %true and the
2877 * work doesn't re-arm itself. Explicitly flush or use
2878 * cancel_delayed_work_sync() to wait on it.
2880 * This function is safe to call from any context including IRQ handler.
2882 bool cancel_delayed_work(struct delayed_work
*dwork
)
2884 unsigned long flags
;
2888 ret
= try_to_grab_pending(&dwork
->work
, true, &flags
);
2889 } while (unlikely(ret
== -EAGAIN
));
2891 if (unlikely(ret
< 0))
2894 set_work_pool_and_clear_pending(&dwork
->work
,
2895 get_work_pool_id(&dwork
->work
));
2896 local_irq_restore(flags
);
2899 EXPORT_SYMBOL(cancel_delayed_work
);
2902 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2903 * @dwork: the delayed work cancel
2905 * This is cancel_work_sync() for delayed works.
2908 * %true if @dwork was pending, %false otherwise.
2910 bool cancel_delayed_work_sync(struct delayed_work
*dwork
)
2912 return __cancel_work_timer(&dwork
->work
, true);
2914 EXPORT_SYMBOL(cancel_delayed_work_sync
);
2917 * schedule_on_each_cpu - execute a function synchronously on each online CPU
2918 * @func: the function to call
2920 * schedule_on_each_cpu() executes @func on each online CPU using the
2921 * system workqueue and blocks until all CPUs have completed.
2922 * schedule_on_each_cpu() is very slow.
2925 * 0 on success, -errno on failure.
2927 int schedule_on_each_cpu(work_func_t func
)
2930 struct work_struct __percpu
*works
;
2932 works
= alloc_percpu(struct work_struct
);
2938 for_each_online_cpu(cpu
) {
2939 struct work_struct
*work
= per_cpu_ptr(works
, cpu
);
2941 INIT_WORK(work
, func
);
2942 schedule_work_on(cpu
, work
);
2945 for_each_online_cpu(cpu
)
2946 flush_work(per_cpu_ptr(works
, cpu
));
2954 * flush_scheduled_work - ensure that any scheduled work has run to completion.
2956 * Forces execution of the kernel-global workqueue and blocks until its
2959 * Think twice before calling this function! It's very easy to get into
2960 * trouble if you don't take great care. Either of the following situations
2961 * will lead to deadlock:
2963 * One of the work items currently on the workqueue needs to acquire
2964 * a lock held by your code or its caller.
2966 * Your code is running in the context of a work routine.
2968 * They will be detected by lockdep when they occur, but the first might not
2969 * occur very often. It depends on what work items are on the workqueue and
2970 * what locks they need, which you have no control over.
2972 * In most situations flushing the entire workqueue is overkill; you merely
2973 * need to know that a particular work item isn't queued and isn't running.
2974 * In such cases you should use cancel_delayed_work_sync() or
2975 * cancel_work_sync() instead.
2977 void flush_scheduled_work(void)
2979 flush_workqueue(system_wq
);
2981 EXPORT_SYMBOL(flush_scheduled_work
);
2984 * execute_in_process_context - reliably execute the routine with user context
2985 * @fn: the function to execute
2986 * @ew: guaranteed storage for the execute work structure (must
2987 * be available when the work executes)
2989 * Executes the function immediately if process context is available,
2990 * otherwise schedules the function for delayed execution.
2992 * Returns: 0 - function was executed
2993 * 1 - function was scheduled for execution
2995 int execute_in_process_context(work_func_t fn
, struct execute_work
*ew
)
2997 if (!in_interrupt()) {
3002 INIT_WORK(&ew
->work
, fn
);
3003 schedule_work(&ew
->work
);
3007 EXPORT_SYMBOL_GPL(execute_in_process_context
);
3011 * Workqueues with WQ_SYSFS flag set is visible to userland via
3012 * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
3013 * following attributes.
3015 * per_cpu RO bool : whether the workqueue is per-cpu or unbound
3016 * max_active RW int : maximum number of in-flight work items
3018 * Unbound workqueues have the following extra attributes.
3020 * id RO int : the associated pool ID
3021 * nice RW int : nice value of the workers
3022 * cpumask RW mask : bitmask of allowed CPUs for the workers
3025 struct workqueue_struct
*wq
;
3029 static struct workqueue_struct
*dev_to_wq(struct device
*dev
)
3031 struct wq_device
*wq_dev
= container_of(dev
, struct wq_device
, dev
);
3036 static ssize_t
wq_per_cpu_show(struct device
*dev
,
3037 struct device_attribute
*attr
, char *buf
)
3039 struct workqueue_struct
*wq
= dev_to_wq(dev
);
3041 return scnprintf(buf
, PAGE_SIZE
, "%d\n", (bool)!(wq
->flags
& WQ_UNBOUND
));
3044 static ssize_t
wq_max_active_show(struct device
*dev
,
3045 struct device_attribute
*attr
, char *buf
)
3047 struct workqueue_struct
*wq
= dev_to_wq(dev
);
3049 return scnprintf(buf
, PAGE_SIZE
, "%d\n", wq
->saved_max_active
);
3052 static ssize_t
wq_max_active_store(struct device
*dev
,
3053 struct device_attribute
*attr
,
3054 const char *buf
, size_t count
)
3056 struct workqueue_struct
*wq
= dev_to_wq(dev
);
3059 if (sscanf(buf
, "%d", &val
) != 1 || val
<= 0)
3062 workqueue_set_max_active(wq
, val
);
3066 static struct device_attribute wq_sysfs_attrs
[] = {
3067 __ATTR(per_cpu
, 0444, wq_per_cpu_show
, NULL
),
3068 __ATTR(max_active
, 0644, wq_max_active_show
, wq_max_active_store
),
3072 static ssize_t
wq_pool_id_show(struct device
*dev
,
3073 struct device_attribute
*attr
, char *buf
)
3075 struct workqueue_struct
*wq
= dev_to_wq(dev
);
3076 struct worker_pool
*pool
;
3079 rcu_read_lock_sched();
3080 pool
= first_pwq(wq
)->pool
;
3081 written
= scnprintf(buf
, PAGE_SIZE
, "%d\n", pool
->id
);
3082 rcu_read_unlock_sched();
3087 static ssize_t
wq_nice_show(struct device
*dev
, struct device_attribute
*attr
,
3090 struct workqueue_struct
*wq
= dev_to_wq(dev
);
3093 rcu_read_lock_sched();
3094 written
= scnprintf(buf
, PAGE_SIZE
, "%d\n",
3095 first_pwq(wq
)->pool
->attrs
->nice
);
3096 rcu_read_unlock_sched();
3101 /* prepare workqueue_attrs for sysfs store operations */
3102 static struct workqueue_attrs
*wq_sysfs_prep_attrs(struct workqueue_struct
*wq
)
3104 struct workqueue_attrs
*attrs
;
3106 attrs
= alloc_workqueue_attrs(GFP_KERNEL
);
3110 rcu_read_lock_sched();
3111 copy_workqueue_attrs(attrs
, first_pwq(wq
)->pool
->attrs
);
3112 rcu_read_unlock_sched();
3116 static ssize_t
wq_nice_store(struct device
*dev
, struct device_attribute
*attr
,
3117 const char *buf
, size_t count
)
3119 struct workqueue_struct
*wq
= dev_to_wq(dev
);
3120 struct workqueue_attrs
*attrs
;
3123 attrs
= wq_sysfs_prep_attrs(wq
);
3127 if (sscanf(buf
, "%d", &attrs
->nice
) == 1 &&
3128 attrs
->nice
>= -20 && attrs
->nice
<= 19)
3129 ret
= apply_workqueue_attrs(wq
, attrs
);
3133 free_workqueue_attrs(attrs
);
3134 return ret
?: count
;
3137 static ssize_t
wq_cpumask_show(struct device
*dev
,
3138 struct device_attribute
*attr
, char *buf
)
3140 struct workqueue_struct
*wq
= dev_to_wq(dev
);
3143 rcu_read_lock_sched();
3144 written
= cpumask_scnprintf(buf
, PAGE_SIZE
,
3145 first_pwq(wq
)->pool
->attrs
->cpumask
);
3146 rcu_read_unlock_sched();
3148 written
+= scnprintf(buf
+ written
, PAGE_SIZE
- written
, "\n");
3152 static ssize_t
wq_cpumask_store(struct device
*dev
,
3153 struct device_attribute
*attr
,
3154 const char *buf
, size_t count
)
3156 struct workqueue_struct
*wq
= dev_to_wq(dev
);
3157 struct workqueue_attrs
*attrs
;
3160 attrs
= wq_sysfs_prep_attrs(wq
);
3164 ret
= cpumask_parse(buf
, attrs
->cpumask
);
3166 ret
= apply_workqueue_attrs(wq
, attrs
);
3168 free_workqueue_attrs(attrs
);
3169 return ret
?: count
;
3172 static struct device_attribute wq_sysfs_unbound_attrs
[] = {
3173 __ATTR(pool_id
, 0444, wq_pool_id_show
, NULL
),
3174 __ATTR(nice
, 0644, wq_nice_show
, wq_nice_store
),
3175 __ATTR(cpumask
, 0644, wq_cpumask_show
, wq_cpumask_store
),
3179 static struct bus_type wq_subsys
= {
3180 .name
= "workqueue",
3181 .dev_attrs
= wq_sysfs_attrs
,
3184 static int __init
wq_sysfs_init(void)
3186 return subsys_virtual_register(&wq_subsys
, NULL
);
3188 core_initcall(wq_sysfs_init
);
3190 static void wq_device_release(struct device
*dev
)
3192 struct wq_device
*wq_dev
= container_of(dev
, struct wq_device
, dev
);
3198 * workqueue_sysfs_register - make a workqueue visible in sysfs
3199 * @wq: the workqueue to register
3201 * Expose @wq in sysfs under /sys/bus/workqueue/devices.
3202 * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
3203 * which is the preferred method.
3205 * Workqueue user should use this function directly iff it wants to apply
3206 * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
3207 * apply_workqueue_attrs() may race against userland updating the
3210 * Returns 0 on success, -errno on failure.
3212 int workqueue_sysfs_register(struct workqueue_struct
*wq
)
3214 struct wq_device
*wq_dev
;
3218 * Adjusting max_active or creating new pwqs by applyting
3219 * attributes breaks ordering guarantee. Disallow exposing ordered
3222 if (WARN_ON(wq
->flags
& __WQ_ORDERED
))
3225 wq
->wq_dev
= wq_dev
= kzalloc(sizeof(*wq_dev
), GFP_KERNEL
);
3230 wq_dev
->dev
.bus
= &wq_subsys
;
3231 wq_dev
->dev
.init_name
= wq
->name
;
3232 wq_dev
->dev
.release
= wq_device_release
;
3235 * unbound_attrs are created separately. Suppress uevent until
3236 * everything is ready.
3238 dev_set_uevent_suppress(&wq_dev
->dev
, true);
3240 ret
= device_register(&wq_dev
->dev
);
3247 if (wq
->flags
& WQ_UNBOUND
) {
3248 struct device_attribute
*attr
;
3250 for (attr
= wq_sysfs_unbound_attrs
; attr
->attr
.name
; attr
++) {
3251 ret
= device_create_file(&wq_dev
->dev
, attr
);
3253 device_unregister(&wq_dev
->dev
);
3260 kobject_uevent(&wq_dev
->dev
.kobj
, KOBJ_ADD
);
3265 * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
3266 * @wq: the workqueue to unregister
3268 * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
3270 static void workqueue_sysfs_unregister(struct workqueue_struct
*wq
)
3272 struct wq_device
*wq_dev
= wq
->wq_dev
;
3278 device_unregister(&wq_dev
->dev
);
3280 #else /* CONFIG_SYSFS */
3281 static void workqueue_sysfs_unregister(struct workqueue_struct
*wq
) { }
3282 #endif /* CONFIG_SYSFS */
3285 * free_workqueue_attrs - free a workqueue_attrs
3286 * @attrs: workqueue_attrs to free
3288 * Undo alloc_workqueue_attrs().
3290 void free_workqueue_attrs(struct workqueue_attrs
*attrs
)
3293 free_cpumask_var(attrs
->cpumask
);
3299 * alloc_workqueue_attrs - allocate a workqueue_attrs
3300 * @gfp_mask: allocation mask to use
3302 * Allocate a new workqueue_attrs, initialize with default settings and
3303 * return it. Returns NULL on failure.
3305 struct workqueue_attrs
*alloc_workqueue_attrs(gfp_t gfp_mask
)
3307 struct workqueue_attrs
*attrs
;
3309 attrs
= kzalloc(sizeof(*attrs
), gfp_mask
);
3312 if (!alloc_cpumask_var(&attrs
->cpumask
, gfp_mask
))
3315 cpumask_setall(attrs
->cpumask
);
3318 free_workqueue_attrs(attrs
);
3322 static void copy_workqueue_attrs(struct workqueue_attrs
*to
,
3323 const struct workqueue_attrs
*from
)
3325 to
->nice
= from
->nice
;
3326 cpumask_copy(to
->cpumask
, from
->cpumask
);
3330 * Hacky implementation of jhash of bitmaps which only considers the
3331 * specified number of bits. We probably want a proper implementation in
3332 * include/linux/jhash.h.
3334 static u32
jhash_bitmap(const unsigned long *bitmap
, int bits
, u32 hash
)
3336 int nr_longs
= bits
/ BITS_PER_LONG
;
3337 int nr_leftover
= bits
% BITS_PER_LONG
;
3338 unsigned long leftover
= 0;
3341 hash
= jhash(bitmap
, nr_longs
* sizeof(long), hash
);
3343 bitmap_copy(&leftover
, bitmap
+ nr_longs
, nr_leftover
);
3344 hash
= jhash(&leftover
, sizeof(long), hash
);
3349 /* hash value of the content of @attr */
3350 static u32
wqattrs_hash(const struct workqueue_attrs
*attrs
)
3354 hash
= jhash_1word(attrs
->nice
, hash
);
3355 hash
= jhash_bitmap(cpumask_bits(attrs
->cpumask
), nr_cpu_ids
, hash
);
3359 /* content equality test */
3360 static bool wqattrs_equal(const struct workqueue_attrs
*a
,
3361 const struct workqueue_attrs
*b
)
3363 if (a
->nice
!= b
->nice
)
3365 if (!cpumask_equal(a
->cpumask
, b
->cpumask
))
3371 * init_worker_pool - initialize a newly zalloc'd worker_pool
3372 * @pool: worker_pool to initialize
3374 * Initiailize a newly zalloc'd @pool. It also allocates @pool->attrs.
3375 * Returns 0 on success, -errno on failure. Even on failure, all fields
3376 * inside @pool proper are initialized and put_unbound_pool() can be called
3377 * on @pool safely to release it.
3379 static int init_worker_pool(struct worker_pool
*pool
)
3381 spin_lock_init(&pool
->lock
);
3384 pool
->flags
|= POOL_DISASSOCIATED
;
3385 INIT_LIST_HEAD(&pool
->worklist
);
3386 INIT_LIST_HEAD(&pool
->idle_list
);
3387 hash_init(pool
->busy_hash
);
3389 init_timer_deferrable(&pool
->idle_timer
);
3390 pool
->idle_timer
.function
= idle_worker_timeout
;
3391 pool
->idle_timer
.data
= (unsigned long)pool
;
3393 setup_timer(&pool
->mayday_timer
, pool_mayday_timeout
,
3394 (unsigned long)pool
);
3396 mutex_init(&pool
->manager_arb
);
3397 mutex_init(&pool
->manager_mutex
);
3398 idr_init(&pool
->worker_idr
);
3400 INIT_HLIST_NODE(&pool
->hash_node
);
3403 /* shouldn't fail above this point */
3404 pool
->attrs
= alloc_workqueue_attrs(GFP_KERNEL
);
3410 static void rcu_free_pool(struct rcu_head
*rcu
)
3412 struct worker_pool
*pool
= container_of(rcu
, struct worker_pool
, rcu
);
3414 idr_destroy(&pool
->worker_idr
);
3415 free_workqueue_attrs(pool
->attrs
);
3420 * put_unbound_pool - put a worker_pool
3421 * @pool: worker_pool to put
3423 * Put @pool. If its refcnt reaches zero, it gets destroyed in sched-RCU
3424 * safe manner. get_unbound_pool() calls this function on its failure path
3425 * and this function should be able to release pools which went through,
3426 * successfully or not, init_worker_pool().
3428 static void put_unbound_pool(struct worker_pool
*pool
)
3430 struct worker
*worker
;
3432 mutex_lock(&wq_mutex
);
3433 if (--pool
->refcnt
) {
3434 mutex_unlock(&wq_mutex
);
3439 if (WARN_ON(!(pool
->flags
& POOL_DISASSOCIATED
)) ||
3440 WARN_ON(!list_empty(&pool
->worklist
))) {
3441 mutex_unlock(&wq_mutex
);
3445 /* release id and unhash */
3447 idr_remove(&worker_pool_idr
, pool
->id
);
3448 hash_del(&pool
->hash_node
);
3450 mutex_unlock(&wq_mutex
);
3453 * Become the manager and destroy all workers. Grabbing
3454 * manager_arb prevents @pool's workers from blocking on
3457 mutex_lock(&pool
->manager_arb
);
3458 mutex_lock(&pool
->manager_mutex
);
3459 spin_lock_irq(&pool
->lock
);
3461 while ((worker
= first_worker(pool
)))
3462 destroy_worker(worker
);
3463 WARN_ON(pool
->nr_workers
|| pool
->nr_idle
);
3465 spin_unlock_irq(&pool
->lock
);
3466 mutex_unlock(&pool
->manager_mutex
);
3467 mutex_unlock(&pool
->manager_arb
);
3469 /* shut down the timers */
3470 del_timer_sync(&pool
->idle_timer
);
3471 del_timer_sync(&pool
->mayday_timer
);
3473 /* sched-RCU protected to allow dereferences from get_work_pool() */
3474 call_rcu_sched(&pool
->rcu
, rcu_free_pool
);
3478 * get_unbound_pool - get a worker_pool with the specified attributes
3479 * @attrs: the attributes of the worker_pool to get
3481 * Obtain a worker_pool which has the same attributes as @attrs, bump the
3482 * reference count and return it. If there already is a matching
3483 * worker_pool, it will be used; otherwise, this function attempts to
3484 * create a new one. On failure, returns NULL.
3486 static struct worker_pool
*get_unbound_pool(const struct workqueue_attrs
*attrs
)
3488 u32 hash
= wqattrs_hash(attrs
);
3489 struct worker_pool
*pool
;
3491 mutex_lock(&wq_mutex
);
3493 /* do we already have a matching pool? */
3494 hash_for_each_possible(unbound_pool_hash
, pool
, hash_node
, hash
) {
3495 if (wqattrs_equal(pool
->attrs
, attrs
)) {
3501 /* nope, create a new one */
3502 pool
= kzalloc(sizeof(*pool
), GFP_KERNEL
);
3503 if (!pool
|| init_worker_pool(pool
) < 0)
3506 if (workqueue_freezing
)
3507 pool
->flags
|= POOL_FREEZING
;
3509 lockdep_set_subclass(&pool
->lock
, 1); /* see put_pwq() */
3510 copy_workqueue_attrs(pool
->attrs
, attrs
);
3512 if (worker_pool_assign_id(pool
) < 0)
3515 /* create and start the initial worker */
3516 if (create_and_start_worker(pool
) < 0)
3520 hash_add(unbound_pool_hash
, &pool
->hash_node
, hash
);
3522 mutex_unlock(&wq_mutex
);
3525 mutex_unlock(&wq_mutex
);
3527 put_unbound_pool(pool
);
3531 static void rcu_free_pwq(struct rcu_head
*rcu
)
3533 kmem_cache_free(pwq_cache
,
3534 container_of(rcu
, struct pool_workqueue
, rcu
));
3538 * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
3539 * and needs to be destroyed.
3541 static void pwq_unbound_release_workfn(struct work_struct
*work
)
3543 struct pool_workqueue
*pwq
= container_of(work
, struct pool_workqueue
,
3544 unbound_release_work
);
3545 struct workqueue_struct
*wq
= pwq
->wq
;
3546 struct worker_pool
*pool
= pwq
->pool
;
3548 if (WARN_ON_ONCE(!(wq
->flags
& WQ_UNBOUND
)))
3552 * Unlink @pwq. Synchronization against flush_mutex isn't strictly
3553 * necessary on release but do it anyway. It's easier to verify
3554 * and consistent with the linking path.
3556 mutex_lock(&wq
->flush_mutex
);
3557 spin_lock_irq(&pwq_lock
);
3558 list_del_rcu(&pwq
->pwqs_node
);
3559 spin_unlock_irq(&pwq_lock
);
3560 mutex_unlock(&wq
->flush_mutex
);
3562 put_unbound_pool(pool
);
3563 call_rcu_sched(&pwq
->rcu
, rcu_free_pwq
);
3566 * If we're the last pwq going away, @wq is already dead and no one
3567 * is gonna access it anymore. Free it.
3569 if (list_empty(&wq
->pwqs
))
3574 * pwq_adjust_max_active - update a pwq's max_active to the current setting
3575 * @pwq: target pool_workqueue
3577 * If @pwq isn't freezing, set @pwq->max_active to the associated
3578 * workqueue's saved_max_active and activate delayed work items
3579 * accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
3581 static void pwq_adjust_max_active(struct pool_workqueue
*pwq
)
3583 struct workqueue_struct
*wq
= pwq
->wq
;
3584 bool freezable
= wq
->flags
& WQ_FREEZABLE
;
3586 /* for @wq->saved_max_active */
3587 lockdep_assert_held(&pwq_lock
);
3589 /* fast exit for non-freezable wqs */
3590 if (!freezable
&& pwq
->max_active
== wq
->saved_max_active
)
3593 spin_lock(&pwq
->pool
->lock
);
3595 if (!freezable
|| !(pwq
->pool
->flags
& POOL_FREEZING
)) {
3596 pwq
->max_active
= wq
->saved_max_active
;
3598 while (!list_empty(&pwq
->delayed_works
) &&
3599 pwq
->nr_active
< pwq
->max_active
)
3600 pwq_activate_first_delayed(pwq
);
3603 * Need to kick a worker after thawed or an unbound wq's
3604 * max_active is bumped. It's a slow path. Do it always.
3606 wake_up_worker(pwq
->pool
);
3608 pwq
->max_active
= 0;
3611 spin_unlock(&pwq
->pool
->lock
);
3614 static void init_and_link_pwq(struct pool_workqueue
*pwq
,
3615 struct workqueue_struct
*wq
,
3616 struct worker_pool
*pool
,
3617 struct pool_workqueue
**p_last_pwq
)
3619 BUG_ON((unsigned long)pwq
& WORK_STRUCT_FLAG_MASK
);
3623 pwq
->flush_color
= -1;
3625 INIT_LIST_HEAD(&pwq
->delayed_works
);
3626 INIT_LIST_HEAD(&pwq
->mayday_node
);
3627 INIT_WORK(&pwq
->unbound_release_work
, pwq_unbound_release_workfn
);
3629 mutex_lock(&wq
->flush_mutex
);
3630 spin_lock_irq(&pwq_lock
);
3633 * Set the matching work_color. This is synchronized with
3634 * flush_mutex to avoid confusing flush_workqueue().
3637 *p_last_pwq
= first_pwq(wq
);
3638 pwq
->work_color
= wq
->work_color
;
3640 /* sync max_active to the current setting */
3641 pwq_adjust_max_active(pwq
);
3644 list_add_rcu(&pwq
->pwqs_node
, &wq
->pwqs
);
3646 spin_unlock_irq(&pwq_lock
);
3647 mutex_unlock(&wq
->flush_mutex
);
3651 * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
3652 * @wq: the target workqueue
3653 * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
3655 * Apply @attrs to an unbound workqueue @wq. If @attrs doesn't match the
3656 * current attributes, a new pwq is created and made the first pwq which
3657 * will serve all new work items. Older pwqs are released as in-flight
3658 * work items finish. Note that a work item which repeatedly requeues
3659 * itself back-to-back will stay on its current pwq.
3661 * Performs GFP_KERNEL allocations. Returns 0 on success and -errno on
3664 int apply_workqueue_attrs(struct workqueue_struct
*wq
,
3665 const struct workqueue_attrs
*attrs
)
3667 struct pool_workqueue
*pwq
, *last_pwq
;
3668 struct worker_pool
*pool
;
3670 /* only unbound workqueues can change attributes */
3671 if (WARN_ON(!(wq
->flags
& WQ_UNBOUND
)))
3674 /* creating multiple pwqs breaks ordering guarantee */
3675 if (WARN_ON((wq
->flags
& __WQ_ORDERED
) && !list_empty(&wq
->pwqs
)))
3678 pwq
= kmem_cache_zalloc(pwq_cache
, GFP_KERNEL
);
3682 pool
= get_unbound_pool(attrs
);
3684 kmem_cache_free(pwq_cache
, pwq
);
3688 init_and_link_pwq(pwq
, wq
, pool
, &last_pwq
);
3690 spin_lock_irq(&last_pwq
->pool
->lock
);
3692 spin_unlock_irq(&last_pwq
->pool
->lock
);
3698 static int alloc_and_link_pwqs(struct workqueue_struct
*wq
)
3700 bool highpri
= wq
->flags
& WQ_HIGHPRI
;
3703 if (!(wq
->flags
& WQ_UNBOUND
)) {
3704 wq
->cpu_pwqs
= alloc_percpu(struct pool_workqueue
);
3708 for_each_possible_cpu(cpu
) {
3709 struct pool_workqueue
*pwq
=
3710 per_cpu_ptr(wq
->cpu_pwqs
, cpu
);
3711 struct worker_pool
*cpu_pools
=
3712 per_cpu(cpu_worker_pools
, cpu
);
3714 init_and_link_pwq(pwq
, wq
, &cpu_pools
[highpri
], NULL
);
3718 return apply_workqueue_attrs(wq
, unbound_std_wq_attrs
[highpri
]);
3722 static int wq_clamp_max_active(int max_active
, unsigned int flags
,
3725 int lim
= flags
& WQ_UNBOUND
? WQ_UNBOUND_MAX_ACTIVE
: WQ_MAX_ACTIVE
;
3727 if (max_active
< 1 || max_active
> lim
)
3728 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3729 max_active
, name
, 1, lim
);
3731 return clamp_val(max_active
, 1, lim
);
3734 struct workqueue_struct
*__alloc_workqueue_key(const char *fmt
,
3737 struct lock_class_key
*key
,
3738 const char *lock_name
, ...)
3740 va_list args
, args1
;
3741 struct workqueue_struct
*wq
;
3742 struct pool_workqueue
*pwq
;
3745 /* determine namelen, allocate wq and format name */
3746 va_start(args
, lock_name
);
3747 va_copy(args1
, args
);
3748 namelen
= vsnprintf(NULL
, 0, fmt
, args
) + 1;
3750 wq
= kzalloc(sizeof(*wq
) + namelen
, GFP_KERNEL
);
3754 vsnprintf(wq
->name
, namelen
, fmt
, args1
);
3758 max_active
= max_active
?: WQ_DFL_ACTIVE
;
3759 max_active
= wq_clamp_max_active(max_active
, flags
, wq
->name
);
3763 wq
->saved_max_active
= max_active
;
3764 mutex_init(&wq
->flush_mutex
);
3765 atomic_set(&wq
->nr_pwqs_to_flush
, 0);
3766 INIT_LIST_HEAD(&wq
->pwqs
);
3767 INIT_LIST_HEAD(&wq
->flusher_queue
);
3768 INIT_LIST_HEAD(&wq
->flusher_overflow
);
3769 INIT_LIST_HEAD(&wq
->maydays
);
3771 lockdep_init_map(&wq
->lockdep_map
, lock_name
, key
, 0);
3772 INIT_LIST_HEAD(&wq
->list
);
3774 if (alloc_and_link_pwqs(wq
) < 0)
3778 * Workqueues which may be used during memory reclaim should
3779 * have a rescuer to guarantee forward progress.
3781 if (flags
& WQ_MEM_RECLAIM
) {
3782 struct worker
*rescuer
;
3784 rescuer
= alloc_worker();
3788 rescuer
->rescue_wq
= wq
;
3789 rescuer
->task
= kthread_create(rescuer_thread
, rescuer
, "%s",
3791 if (IS_ERR(rescuer
->task
)) {
3796 wq
->rescuer
= rescuer
;
3797 rescuer
->task
->flags
|= PF_NO_SETAFFINITY
;
3798 wake_up_process(rescuer
->task
);
3801 if ((wq
->flags
& WQ_SYSFS
) && workqueue_sysfs_register(wq
))
3805 * wq_mutex protects global freeze state and workqueues list. Grab
3806 * it, adjust max_active and add the new @wq to workqueues list.
3808 mutex_lock(&wq_mutex
);
3810 spin_lock_irq(&pwq_lock
);
3811 for_each_pwq(pwq
, wq
)
3812 pwq_adjust_max_active(pwq
);
3813 spin_unlock_irq(&pwq_lock
);
3815 list_add(&wq
->list
, &workqueues
);
3817 mutex_unlock(&wq_mutex
);
3825 destroy_workqueue(wq
);
3828 EXPORT_SYMBOL_GPL(__alloc_workqueue_key
);
3831 * destroy_workqueue - safely terminate a workqueue
3832 * @wq: target workqueue
3834 * Safely destroy a workqueue. All work currently pending will be done first.
3836 void destroy_workqueue(struct workqueue_struct
*wq
)
3838 struct pool_workqueue
*pwq
;
3840 /* drain it before proceeding with destruction */
3841 drain_workqueue(wq
);
3844 spin_lock_irq(&pwq_lock
);
3845 for_each_pwq(pwq
, wq
) {
3848 for (i
= 0; i
< WORK_NR_COLORS
; i
++) {
3849 if (WARN_ON(pwq
->nr_in_flight
[i
])) {
3850 spin_unlock_irq(&pwq_lock
);
3855 if (WARN_ON(pwq
->refcnt
> 1) ||
3856 WARN_ON(pwq
->nr_active
) ||
3857 WARN_ON(!list_empty(&pwq
->delayed_works
))) {
3858 spin_unlock_irq(&pwq_lock
);
3862 spin_unlock_irq(&pwq_lock
);
3865 * wq list is used to freeze wq, remove from list after
3866 * flushing is complete in case freeze races us.
3868 mutex_lock(&wq_mutex
);
3869 list_del_init(&wq
->list
);
3870 mutex_unlock(&wq_mutex
);
3872 workqueue_sysfs_unregister(wq
);
3875 kthread_stop(wq
->rescuer
->task
);
3880 if (!(wq
->flags
& WQ_UNBOUND
)) {
3882 * The base ref is never dropped on per-cpu pwqs. Directly
3883 * free the pwqs and wq.
3885 free_percpu(wq
->cpu_pwqs
);
3889 * We're the sole accessor of @wq at this point. Directly
3890 * access the first pwq and put the base ref. As both pwqs
3891 * and pools are sched-RCU protected, the lock operations
3892 * are safe. @wq will be freed when the last pwq is
3895 pwq
= list_first_entry(&wq
->pwqs
, struct pool_workqueue
,
3897 spin_lock_irq(&pwq
->pool
->lock
);
3899 spin_unlock_irq(&pwq
->pool
->lock
);
3902 EXPORT_SYMBOL_GPL(destroy_workqueue
);
3905 * workqueue_set_max_active - adjust max_active of a workqueue
3906 * @wq: target workqueue
3907 * @max_active: new max_active value.
3909 * Set max_active of @wq to @max_active.
3912 * Don't call from IRQ context.
3914 void workqueue_set_max_active(struct workqueue_struct
*wq
, int max_active
)
3916 struct pool_workqueue
*pwq
;
3918 /* disallow meddling with max_active for ordered workqueues */
3919 if (WARN_ON(wq
->flags
& __WQ_ORDERED
))
3922 max_active
= wq_clamp_max_active(max_active
, wq
->flags
, wq
->name
);
3924 spin_lock_irq(&pwq_lock
);
3926 wq
->saved_max_active
= max_active
;
3928 for_each_pwq(pwq
, wq
)
3929 pwq_adjust_max_active(pwq
);
3931 spin_unlock_irq(&pwq_lock
);
3933 EXPORT_SYMBOL_GPL(workqueue_set_max_active
);
3936 * current_is_workqueue_rescuer - is %current workqueue rescuer?
3938 * Determine whether %current is a workqueue rescuer. Can be used from
3939 * work functions to determine whether it's being run off the rescuer task.
3941 bool current_is_workqueue_rescuer(void)
3943 struct worker
*worker
= current_wq_worker();
3945 return worker
&& worker
->rescue_wq
;
3949 * workqueue_congested - test whether a workqueue is congested
3950 * @cpu: CPU in question
3951 * @wq: target workqueue
3953 * Test whether @wq's cpu workqueue for @cpu is congested. There is
3954 * no synchronization around this function and the test result is
3955 * unreliable and only useful as advisory hints or for debugging.
3958 * %true if congested, %false otherwise.
3960 bool workqueue_congested(int cpu
, struct workqueue_struct
*wq
)
3962 struct pool_workqueue
*pwq
;
3965 rcu_read_lock_sched();
3967 if (!(wq
->flags
& WQ_UNBOUND
))
3968 pwq
= per_cpu_ptr(wq
->cpu_pwqs
, cpu
);
3970 pwq
= first_pwq(wq
);
3972 ret
= !list_empty(&pwq
->delayed_works
);
3973 rcu_read_unlock_sched();
3977 EXPORT_SYMBOL_GPL(workqueue_congested
);
3980 * work_busy - test whether a work is currently pending or running
3981 * @work: the work to be tested
3983 * Test whether @work is currently pending or running. There is no
3984 * synchronization around this function and the test result is
3985 * unreliable and only useful as advisory hints or for debugging.
3988 * OR'd bitmask of WORK_BUSY_* bits.
3990 unsigned int work_busy(struct work_struct
*work
)
3992 struct worker_pool
*pool
;
3993 unsigned long flags
;
3994 unsigned int ret
= 0;
3996 if (work_pending(work
))
3997 ret
|= WORK_BUSY_PENDING
;
3999 local_irq_save(flags
);
4000 pool
= get_work_pool(work
);
4002 spin_lock(&pool
->lock
);
4003 if (find_worker_executing_work(pool
, work
))
4004 ret
|= WORK_BUSY_RUNNING
;
4005 spin_unlock(&pool
->lock
);
4007 local_irq_restore(flags
);
4011 EXPORT_SYMBOL_GPL(work_busy
);
4016 * There are two challenges in supporting CPU hotplug. Firstly, there
4017 * are a lot of assumptions on strong associations among work, pwq and
4018 * pool which make migrating pending and scheduled works very
4019 * difficult to implement without impacting hot paths. Secondly,
4020 * worker pools serve mix of short, long and very long running works making
4021 * blocked draining impractical.
4023 * This is solved by allowing the pools to be disassociated from the CPU
4024 * running as an unbound one and allowing it to be reattached later if the
4025 * cpu comes back online.
4028 static void wq_unbind_fn(struct work_struct
*work
)
4030 int cpu
= smp_processor_id();
4031 struct worker_pool
*pool
;
4032 struct worker
*worker
;
4035 for_each_cpu_worker_pool(pool
, cpu
) {
4036 WARN_ON_ONCE(cpu
!= smp_processor_id());
4038 mutex_lock(&pool
->manager_mutex
);
4039 spin_lock_irq(&pool
->lock
);
4042 * We've blocked all manager operations. Make all workers
4043 * unbound and set DISASSOCIATED. Before this, all workers
4044 * except for the ones which are still executing works from
4045 * before the last CPU down must be on the cpu. After
4046 * this, they may become diasporas.
4048 for_each_pool_worker(worker
, wi
, pool
)
4049 worker
->flags
|= WORKER_UNBOUND
;
4051 pool
->flags
|= POOL_DISASSOCIATED
;
4053 spin_unlock_irq(&pool
->lock
);
4054 mutex_unlock(&pool
->manager_mutex
);
4058 * Call schedule() so that we cross rq->lock and thus can guarantee
4059 * sched callbacks see the %WORKER_UNBOUND flag. This is necessary
4060 * as scheduler callbacks may be invoked from other cpus.
4065 * Sched callbacks are disabled now. Zap nr_running. After this,
4066 * nr_running stays zero and need_more_worker() and keep_working()
4067 * are always true as long as the worklist is not empty. Pools on
4068 * @cpu now behave as unbound (in terms of concurrency management)
4069 * pools which are served by workers tied to the CPU.
4071 * On return from this function, the current worker would trigger
4072 * unbound chain execution of pending work items if other workers
4075 for_each_cpu_worker_pool(pool
, cpu
)
4076 atomic_set(&pool
->nr_running
, 0);
4080 * rebind_workers - rebind all workers of a pool to the associated CPU
4081 * @pool: pool of interest
4083 * @pool->cpu is coming online. Rebind all workers to the CPU.
4085 static void rebind_workers(struct worker_pool
*pool
)
4087 struct worker
*worker
;
4090 lockdep_assert_held(&pool
->manager_mutex
);
4093 * Restore CPU affinity of all workers. As all idle workers should
4094 * be on the run-queue of the associated CPU before any local
4095 * wake-ups for concurrency management happen, restore CPU affinty
4096 * of all workers first and then clear UNBOUND. As we're called
4097 * from CPU_ONLINE, the following shouldn't fail.
4099 for_each_pool_worker(worker
, wi
, pool
)
4100 WARN_ON_ONCE(set_cpus_allowed_ptr(worker
->task
,
4101 pool
->attrs
->cpumask
) < 0);
4103 spin_lock_irq(&pool
->lock
);
4105 for_each_pool_worker(worker
, wi
, pool
) {
4106 unsigned int worker_flags
= worker
->flags
;
4109 * A bound idle worker should actually be on the runqueue
4110 * of the associated CPU for local wake-ups targeting it to
4111 * work. Kick all idle workers so that they migrate to the
4112 * associated CPU. Doing this in the same loop as
4113 * replacing UNBOUND with REBOUND is safe as no worker will
4114 * be bound before @pool->lock is released.
4116 if (worker_flags
& WORKER_IDLE
)
4117 wake_up_process(worker
->task
);
4120 * We want to clear UNBOUND but can't directly call
4121 * worker_clr_flags() or adjust nr_running. Atomically
4122 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
4123 * @worker will clear REBOUND using worker_clr_flags() when
4124 * it initiates the next execution cycle thus restoring
4125 * concurrency management. Note that when or whether
4126 * @worker clears REBOUND doesn't affect correctness.
4128 * ACCESS_ONCE() is necessary because @worker->flags may be
4129 * tested without holding any lock in
4130 * wq_worker_waking_up(). Without it, NOT_RUNNING test may
4131 * fail incorrectly leading to premature concurrency
4132 * management operations.
4134 WARN_ON_ONCE(!(worker_flags
& WORKER_UNBOUND
));
4135 worker_flags
|= WORKER_REBOUND
;
4136 worker_flags
&= ~WORKER_UNBOUND
;
4137 ACCESS_ONCE(worker
->flags
) = worker_flags
;
4140 spin_unlock_irq(&pool
->lock
);
4144 * restore_unbound_workers_cpumask - restore cpumask of unbound workers
4145 * @pool: unbound pool of interest
4146 * @cpu: the CPU which is coming up
4148 * An unbound pool may end up with a cpumask which doesn't have any online
4149 * CPUs. When a worker of such pool get scheduled, the scheduler resets
4150 * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
4151 * online CPU before, cpus_allowed of all its workers should be restored.
4153 static void restore_unbound_workers_cpumask(struct worker_pool
*pool
, int cpu
)
4155 static cpumask_t cpumask
;
4156 struct worker
*worker
;
4159 lockdep_assert_held(&pool
->manager_mutex
);
4161 /* is @cpu allowed for @pool? */
4162 if (!cpumask_test_cpu(cpu
, pool
->attrs
->cpumask
))
4165 /* is @cpu the only online CPU? */
4166 cpumask_and(&cpumask
, pool
->attrs
->cpumask
, cpu_online_mask
);
4167 if (cpumask_weight(&cpumask
) != 1)
4170 /* as we're called from CPU_ONLINE, the following shouldn't fail */
4171 for_each_pool_worker(worker
, wi
, pool
)
4172 WARN_ON_ONCE(set_cpus_allowed_ptr(worker
->task
,
4173 pool
->attrs
->cpumask
) < 0);
4177 * Workqueues should be brought up before normal priority CPU notifiers.
4178 * This will be registered high priority CPU notifier.
4180 static int __cpuinit
workqueue_cpu_up_callback(struct notifier_block
*nfb
,
4181 unsigned long action
,
4184 int cpu
= (unsigned long)hcpu
;
4185 struct worker_pool
*pool
;
4188 switch (action
& ~CPU_TASKS_FROZEN
) {
4189 case CPU_UP_PREPARE
:
4190 for_each_cpu_worker_pool(pool
, cpu
) {
4191 if (pool
->nr_workers
)
4193 if (create_and_start_worker(pool
) < 0)
4198 case CPU_DOWN_FAILED
:
4200 mutex_lock(&wq_mutex
);
4202 for_each_pool(pool
, pi
) {
4203 mutex_lock(&pool
->manager_mutex
);
4205 if (pool
->cpu
== cpu
) {
4206 spin_lock_irq(&pool
->lock
);
4207 pool
->flags
&= ~POOL_DISASSOCIATED
;
4208 spin_unlock_irq(&pool
->lock
);
4210 rebind_workers(pool
);
4211 } else if (pool
->cpu
< 0) {
4212 restore_unbound_workers_cpumask(pool
, cpu
);
4215 mutex_unlock(&pool
->manager_mutex
);
4218 mutex_unlock(&wq_mutex
);
4225 * Workqueues should be brought down after normal priority CPU notifiers.
4226 * This will be registered as low priority CPU notifier.
4228 static int __cpuinit
workqueue_cpu_down_callback(struct notifier_block
*nfb
,
4229 unsigned long action
,
4232 int cpu
= (unsigned long)hcpu
;
4233 struct work_struct unbind_work
;
4235 switch (action
& ~CPU_TASKS_FROZEN
) {
4236 case CPU_DOWN_PREPARE
:
4237 /* unbinding should happen on the local CPU */
4238 INIT_WORK_ONSTACK(&unbind_work
, wq_unbind_fn
);
4239 queue_work_on(cpu
, system_highpri_wq
, &unbind_work
);
4240 flush_work(&unbind_work
);
4248 struct work_for_cpu
{
4249 struct work_struct work
;
4255 static void work_for_cpu_fn(struct work_struct
*work
)
4257 struct work_for_cpu
*wfc
= container_of(work
, struct work_for_cpu
, work
);
4259 wfc
->ret
= wfc
->fn(wfc
->arg
);
4263 * work_on_cpu - run a function in user context on a particular cpu
4264 * @cpu: the cpu to run on
4265 * @fn: the function to run
4266 * @arg: the function arg
4268 * This will return the value @fn returns.
4269 * It is up to the caller to ensure that the cpu doesn't go offline.
4270 * The caller must not hold any locks which would prevent @fn from completing.
4272 long work_on_cpu(int cpu
, long (*fn
)(void *), void *arg
)
4274 struct work_for_cpu wfc
= { .fn
= fn
, .arg
= arg
};
4276 INIT_WORK_ONSTACK(&wfc
.work
, work_for_cpu_fn
);
4277 schedule_work_on(cpu
, &wfc
.work
);
4278 flush_work(&wfc
.work
);
4281 EXPORT_SYMBOL_GPL(work_on_cpu
);
4282 #endif /* CONFIG_SMP */
4284 #ifdef CONFIG_FREEZER
4287 * freeze_workqueues_begin - begin freezing workqueues
4289 * Start freezing workqueues. After this function returns, all freezable
4290 * workqueues will queue new works to their delayed_works list instead of
4294 * Grabs and releases wq_mutex, pwq_lock and pool->lock's.
4296 void freeze_workqueues_begin(void)
4298 struct worker_pool
*pool
;
4299 struct workqueue_struct
*wq
;
4300 struct pool_workqueue
*pwq
;
4303 mutex_lock(&wq_mutex
);
4305 WARN_ON_ONCE(workqueue_freezing
);
4306 workqueue_freezing
= true;
4309 for_each_pool(pool
, pi
) {
4310 spin_lock_irq(&pool
->lock
);
4311 WARN_ON_ONCE(pool
->flags
& POOL_FREEZING
);
4312 pool
->flags
|= POOL_FREEZING
;
4313 spin_unlock_irq(&pool
->lock
);
4316 /* suppress further executions by setting max_active to zero */
4317 spin_lock_irq(&pwq_lock
);
4318 list_for_each_entry(wq
, &workqueues
, list
) {
4319 for_each_pwq(pwq
, wq
)
4320 pwq_adjust_max_active(pwq
);
4322 spin_unlock_irq(&pwq_lock
);
4324 mutex_unlock(&wq_mutex
);
4328 * freeze_workqueues_busy - are freezable workqueues still busy?
4330 * Check whether freezing is complete. This function must be called
4331 * between freeze_workqueues_begin() and thaw_workqueues().
4334 * Grabs and releases wq_mutex.
4337 * %true if some freezable workqueues are still busy. %false if freezing
4340 bool freeze_workqueues_busy(void)
4343 struct workqueue_struct
*wq
;
4344 struct pool_workqueue
*pwq
;
4346 mutex_lock(&wq_mutex
);
4348 WARN_ON_ONCE(!workqueue_freezing
);
4350 list_for_each_entry(wq
, &workqueues
, list
) {
4351 if (!(wq
->flags
& WQ_FREEZABLE
))
4354 * nr_active is monotonically decreasing. It's safe
4355 * to peek without lock.
4357 rcu_read_lock_sched();
4358 for_each_pwq(pwq
, wq
) {
4359 WARN_ON_ONCE(pwq
->nr_active
< 0);
4360 if (pwq
->nr_active
) {
4362 rcu_read_unlock_sched();
4366 rcu_read_unlock_sched();
4369 mutex_unlock(&wq_mutex
);
4374 * thaw_workqueues - thaw workqueues
4376 * Thaw workqueues. Normal queueing is restored and all collected
4377 * frozen works are transferred to their respective pool worklists.
4380 * Grabs and releases wq_mutex, pwq_lock and pool->lock's.
4382 void thaw_workqueues(void)
4384 struct workqueue_struct
*wq
;
4385 struct pool_workqueue
*pwq
;
4386 struct worker_pool
*pool
;
4389 mutex_lock(&wq_mutex
);
4391 if (!workqueue_freezing
)
4394 /* clear FREEZING */
4395 for_each_pool(pool
, pi
) {
4396 spin_lock_irq(&pool
->lock
);
4397 WARN_ON_ONCE(!(pool
->flags
& POOL_FREEZING
));
4398 pool
->flags
&= ~POOL_FREEZING
;
4399 spin_unlock_irq(&pool
->lock
);
4402 /* restore max_active and repopulate worklist */
4403 spin_lock_irq(&pwq_lock
);
4404 list_for_each_entry(wq
, &workqueues
, list
) {
4405 for_each_pwq(pwq
, wq
)
4406 pwq_adjust_max_active(pwq
);
4408 spin_unlock_irq(&pwq_lock
);
4410 workqueue_freezing
= false;
4412 mutex_unlock(&wq_mutex
);
4414 #endif /* CONFIG_FREEZER */
4416 static int __init
init_workqueues(void)
4418 int std_nice
[NR_STD_WORKER_POOLS
] = { 0, HIGHPRI_NICE_LEVEL
};
4421 /* make sure we have enough bits for OFFQ pool ID */
4422 BUILD_BUG_ON((1LU << (BITS_PER_LONG
- WORK_OFFQ_POOL_SHIFT
)) <
4423 WORK_CPU_END
* NR_STD_WORKER_POOLS
);
4425 WARN_ON(__alignof__(struct pool_workqueue
) < __alignof__(long long));
4427 pwq_cache
= KMEM_CACHE(pool_workqueue
, SLAB_PANIC
);
4429 cpu_notifier(workqueue_cpu_up_callback
, CPU_PRI_WORKQUEUE_UP
);
4430 hotcpu_notifier(workqueue_cpu_down_callback
, CPU_PRI_WORKQUEUE_DOWN
);
4432 /* initialize CPU pools */
4433 for_each_possible_cpu(cpu
) {
4434 struct worker_pool
*pool
;
4437 for_each_cpu_worker_pool(pool
, cpu
) {
4438 BUG_ON(init_worker_pool(pool
));
4440 cpumask_copy(pool
->attrs
->cpumask
, cpumask_of(cpu
));
4441 pool
->attrs
->nice
= std_nice
[i
++];
4444 mutex_lock(&wq_mutex
);
4445 BUG_ON(worker_pool_assign_id(pool
));
4446 mutex_unlock(&wq_mutex
);
4450 /* create the initial worker */
4451 for_each_online_cpu(cpu
) {
4452 struct worker_pool
*pool
;
4454 for_each_cpu_worker_pool(pool
, cpu
) {
4455 pool
->flags
&= ~POOL_DISASSOCIATED
;
4456 BUG_ON(create_and_start_worker(pool
) < 0);
4460 /* create default unbound wq attrs */
4461 for (i
= 0; i
< NR_STD_WORKER_POOLS
; i
++) {
4462 struct workqueue_attrs
*attrs
;
4464 BUG_ON(!(attrs
= alloc_workqueue_attrs(GFP_KERNEL
)));
4466 attrs
->nice
= std_nice
[i
];
4467 cpumask_setall(attrs
->cpumask
);
4469 unbound_std_wq_attrs
[i
] = attrs
;
4472 system_wq
= alloc_workqueue("events", 0, 0);
4473 system_highpri_wq
= alloc_workqueue("events_highpri", WQ_HIGHPRI
, 0);
4474 system_long_wq
= alloc_workqueue("events_long", 0, 0);
4475 system_unbound_wq
= alloc_workqueue("events_unbound", WQ_UNBOUND
,
4476 WQ_UNBOUND_MAX_ACTIVE
);
4477 system_freezable_wq
= alloc_workqueue("events_freezable",
4479 BUG_ON(!system_wq
|| !system_highpri_wq
|| !system_long_wq
||
4480 !system_unbound_wq
|| !system_freezable_wq
);
4483 early_initcall(init_workqueues
);