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/hashtable.h>
46 #include "workqueue_internal.h"
52 * A bound pool is either associated or disassociated with its CPU.
53 * While associated (!DISASSOCIATED), all workers are bound to the
54 * CPU and none has %WORKER_UNBOUND set and concurrency management
57 * While DISASSOCIATED, the cpu may be offline and all workers have
58 * %WORKER_UNBOUND set and concurrency management disabled, and may
59 * be executing on any CPU. The pool behaves as an unbound one.
61 * Note that DISASSOCIATED can be flipped only while holding
62 * assoc_mutex to avoid changing binding state while
63 * create_worker() is in progress.
65 POOL_MANAGE_WORKERS
= 1 << 0, /* need to manage workers */
66 POOL_MANAGING_WORKERS
= 1 << 1, /* managing workers */
67 POOL_DISASSOCIATED
= 1 << 2, /* cpu can't serve workers */
68 POOL_FREEZING
= 1 << 3, /* freeze in progress */
71 WORKER_STARTED
= 1 << 0, /* started */
72 WORKER_DIE
= 1 << 1, /* die die die */
73 WORKER_IDLE
= 1 << 2, /* is idle */
74 WORKER_PREP
= 1 << 3, /* preparing to run works */
75 WORKER_CPU_INTENSIVE
= 1 << 6, /* cpu intensive */
76 WORKER_UNBOUND
= 1 << 7, /* worker is unbound */
78 WORKER_NOT_RUNNING
= WORKER_PREP
| WORKER_UNBOUND
|
81 NR_STD_WORKER_POOLS
= 2, /* # standard pools per cpu */
83 BUSY_WORKER_HASH_ORDER
= 6, /* 64 pointers */
85 MAX_IDLE_WORKERS_RATIO
= 4, /* 1/4 of busy can be idle */
86 IDLE_WORKER_TIMEOUT
= 300 * HZ
, /* keep idle ones for 5 mins */
88 MAYDAY_INITIAL_TIMEOUT
= HZ
/ 100 >= 2 ? HZ
/ 100 : 2,
89 /* call for help after 10ms
91 MAYDAY_INTERVAL
= HZ
/ 10, /* and then every 100ms */
92 CREATE_COOLDOWN
= HZ
, /* time to breath after fail */
95 * Rescue workers are used only on emergencies and shared by
98 RESCUER_NICE_LEVEL
= -20,
99 HIGHPRI_NICE_LEVEL
= -20,
103 * Structure fields follow one of the following exclusion rules.
105 * I: Modifiable by initialization/destruction paths and read-only for
108 * P: Preemption protected. Disabling preemption is enough and should
109 * only be modified and accessed from the local cpu.
111 * L: pool->lock protected. Access with pool->lock held.
113 * X: During normal operation, modification requires pool->lock and should
114 * be done only from local cpu. Either disabling preemption on local
115 * cpu or grabbing pool->lock is enough for read access. If
116 * POOL_DISASSOCIATED is set, it's identical to L.
118 * F: wq->flush_mutex protected.
120 * W: workqueue_lock protected.
123 /* struct worker is defined in workqueue_internal.h */
126 spinlock_t lock
; /* the pool lock */
127 int cpu
; /* I: the associated cpu */
128 int id
; /* I: pool ID */
129 unsigned int flags
; /* X: flags */
131 struct list_head worklist
; /* L: list of pending works */
132 int nr_workers
; /* L: total number of workers */
134 /* nr_idle includes the ones off idle_list for rebinding */
135 int nr_idle
; /* L: currently idle ones */
137 struct list_head idle_list
; /* X: list of idle workers */
138 struct timer_list idle_timer
; /* L: worker idle timeout */
139 struct timer_list mayday_timer
; /* L: SOS timer for workers */
141 /* workers are chained either in busy_hash or idle_list */
142 DECLARE_HASHTABLE(busy_hash
, BUSY_WORKER_HASH_ORDER
);
143 /* L: hash of busy workers */
145 struct mutex assoc_mutex
; /* protect POOL_DISASSOCIATED */
146 struct ida worker_ida
; /* L: for worker IDs */
149 * The current concurrency level. As it's likely to be accessed
150 * from other CPUs during try_to_wake_up(), put it in a separate
153 atomic_t nr_running ____cacheline_aligned_in_smp
;
154 } ____cacheline_aligned_in_smp
;
157 * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
158 * of work_struct->data are used for flags and the remaining high bits
159 * point to the pwq; thus, pwqs need to be aligned at two's power of the
160 * number of flag bits.
162 struct pool_workqueue
{
163 struct worker_pool
*pool
; /* I: the associated pool */
164 struct workqueue_struct
*wq
; /* I: the owning workqueue */
165 int work_color
; /* L: current color */
166 int flush_color
; /* L: flushing color */
167 int nr_in_flight
[WORK_NR_COLORS
];
168 /* L: nr of in_flight works */
169 int nr_active
; /* L: nr of active works */
170 int max_active
; /* L: max active works */
171 struct list_head delayed_works
; /* L: delayed works */
172 struct list_head pwqs_node
; /* I: node on wq->pwqs */
173 struct list_head mayday_node
; /* W: node on wq->maydays */
174 } __aligned(1 << WORK_STRUCT_FLAG_BITS
);
177 * Structure used to wait for workqueue flush.
180 struct list_head list
; /* F: list of flushers */
181 int flush_color
; /* F: flush color waiting for */
182 struct completion done
; /* flush completion */
186 * The externally visible workqueue abstraction is an array of
187 * per-CPU workqueues:
189 struct workqueue_struct
{
190 unsigned int flags
; /* W: WQ_* flags */
192 struct pool_workqueue __percpu
*pcpu
;
193 struct pool_workqueue
*single
;
195 } pool_wq
; /* I: pwq's */
196 struct list_head pwqs
; /* I: all pwqs of this wq */
197 struct list_head list
; /* W: list of all workqueues */
199 struct mutex flush_mutex
; /* protects wq flushing */
200 int work_color
; /* F: current work color */
201 int flush_color
; /* F: current flush color */
202 atomic_t nr_pwqs_to_flush
; /* flush in progress */
203 struct wq_flusher
*first_flusher
; /* F: first flusher */
204 struct list_head flusher_queue
; /* F: flush waiters */
205 struct list_head flusher_overflow
; /* F: flush overflow list */
207 struct list_head maydays
; /* W: pwqs requesting rescue */
208 struct worker
*rescuer
; /* I: rescue worker */
210 int nr_drainers
; /* W: drain in progress */
211 int saved_max_active
; /* W: saved pwq max_active */
212 #ifdef CONFIG_LOCKDEP
213 struct lockdep_map lockdep_map
;
215 char name
[]; /* I: workqueue name */
218 static struct kmem_cache
*pwq_cache
;
220 struct workqueue_struct
*system_wq __read_mostly
;
221 EXPORT_SYMBOL_GPL(system_wq
);
222 struct workqueue_struct
*system_highpri_wq __read_mostly
;
223 EXPORT_SYMBOL_GPL(system_highpri_wq
);
224 struct workqueue_struct
*system_long_wq __read_mostly
;
225 EXPORT_SYMBOL_GPL(system_long_wq
);
226 struct workqueue_struct
*system_unbound_wq __read_mostly
;
227 EXPORT_SYMBOL_GPL(system_unbound_wq
);
228 struct workqueue_struct
*system_freezable_wq __read_mostly
;
229 EXPORT_SYMBOL_GPL(system_freezable_wq
);
231 #define CREATE_TRACE_POINTS
232 #include <trace/events/workqueue.h>
234 #define for_each_std_worker_pool(pool, cpu) \
235 for ((pool) = &std_worker_pools(cpu)[0]; \
236 (pool) < &std_worker_pools(cpu)[NR_STD_WORKER_POOLS]; (pool)++)
238 #define for_each_busy_worker(worker, i, pool) \
239 hash_for_each(pool->busy_hash, i, worker, hentry)
241 static inline int __next_wq_cpu(int cpu
, const struct cpumask
*mask
,
244 if (cpu
< nr_cpu_ids
) {
246 cpu
= cpumask_next(cpu
, mask
);
247 if (cpu
< nr_cpu_ids
)
251 return WORK_CPU_UNBOUND
;
259 * An extra cpu number is defined using an invalid cpu number
260 * (WORK_CPU_UNBOUND) to host workqueues which are not bound to any
261 * specific CPU. The following iterators are similar to for_each_*_cpu()
262 * iterators but also considers the unbound CPU.
264 * for_each_wq_cpu() : possible CPUs + WORK_CPU_UNBOUND
265 * for_each_online_wq_cpu() : online CPUs + WORK_CPU_UNBOUND
267 #define for_each_wq_cpu(cpu) \
268 for ((cpu) = __next_wq_cpu(-1, cpu_possible_mask, 3); \
269 (cpu) < WORK_CPU_END; \
270 (cpu) = __next_wq_cpu((cpu), cpu_possible_mask, 3))
272 #define for_each_online_wq_cpu(cpu) \
273 for ((cpu) = __next_wq_cpu(-1, cpu_online_mask, 3); \
274 (cpu) < WORK_CPU_END; \
275 (cpu) = __next_wq_cpu((cpu), cpu_online_mask, 3))
278 * for_each_pool - iterate through all worker_pools in the system
279 * @pool: iteration cursor
280 * @id: integer used for iteration
282 #define for_each_pool(pool, id) \
283 idr_for_each_entry(&worker_pool_idr, pool, id)
286 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
287 * @pwq: iteration cursor
288 * @wq: the target workqueue
290 #define for_each_pwq(pwq, wq) \
291 list_for_each_entry((pwq), &(wq)->pwqs, pwqs_node)
293 #ifdef CONFIG_DEBUG_OBJECTS_WORK
295 static struct debug_obj_descr work_debug_descr
;
297 static void *work_debug_hint(void *addr
)
299 return ((struct work_struct
*) addr
)->func
;
303 * fixup_init is called when:
304 * - an active object is initialized
306 static int work_fixup_init(void *addr
, enum debug_obj_state state
)
308 struct work_struct
*work
= addr
;
311 case ODEBUG_STATE_ACTIVE
:
312 cancel_work_sync(work
);
313 debug_object_init(work
, &work_debug_descr
);
321 * fixup_activate is called when:
322 * - an active object is activated
323 * - an unknown object is activated (might be a statically initialized object)
325 static int work_fixup_activate(void *addr
, enum debug_obj_state state
)
327 struct work_struct
*work
= addr
;
331 case ODEBUG_STATE_NOTAVAILABLE
:
333 * This is not really a fixup. The work struct was
334 * statically initialized. We just make sure that it
335 * is tracked in the object tracker.
337 if (test_bit(WORK_STRUCT_STATIC_BIT
, work_data_bits(work
))) {
338 debug_object_init(work
, &work_debug_descr
);
339 debug_object_activate(work
, &work_debug_descr
);
345 case ODEBUG_STATE_ACTIVE
:
354 * fixup_free is called when:
355 * - an active object is freed
357 static int work_fixup_free(void *addr
, enum debug_obj_state state
)
359 struct work_struct
*work
= addr
;
362 case ODEBUG_STATE_ACTIVE
:
363 cancel_work_sync(work
);
364 debug_object_free(work
, &work_debug_descr
);
371 static struct debug_obj_descr work_debug_descr
= {
372 .name
= "work_struct",
373 .debug_hint
= work_debug_hint
,
374 .fixup_init
= work_fixup_init
,
375 .fixup_activate
= work_fixup_activate
,
376 .fixup_free
= work_fixup_free
,
379 static inline void debug_work_activate(struct work_struct
*work
)
381 debug_object_activate(work
, &work_debug_descr
);
384 static inline void debug_work_deactivate(struct work_struct
*work
)
386 debug_object_deactivate(work
, &work_debug_descr
);
389 void __init_work(struct work_struct
*work
, int onstack
)
392 debug_object_init_on_stack(work
, &work_debug_descr
);
394 debug_object_init(work
, &work_debug_descr
);
396 EXPORT_SYMBOL_GPL(__init_work
);
398 void destroy_work_on_stack(struct work_struct
*work
)
400 debug_object_free(work
, &work_debug_descr
);
402 EXPORT_SYMBOL_GPL(destroy_work_on_stack
);
405 static inline void debug_work_activate(struct work_struct
*work
) { }
406 static inline void debug_work_deactivate(struct work_struct
*work
) { }
409 /* Serializes the accesses to the list of workqueues. */
410 static DEFINE_SPINLOCK(workqueue_lock
);
411 static LIST_HEAD(workqueues
);
412 static bool workqueue_freezing
; /* W: have wqs started freezing? */
415 * The CPU and unbound standard worker pools. The unbound ones have
416 * POOL_DISASSOCIATED set, and their workers have WORKER_UNBOUND set.
418 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool
[NR_STD_WORKER_POOLS
],
419 cpu_std_worker_pools
);
420 static struct worker_pool unbound_std_worker_pools
[NR_STD_WORKER_POOLS
];
422 /* idr of all pools */
423 static DEFINE_MUTEX(worker_pool_idr_mutex
);
424 static DEFINE_IDR(worker_pool_idr
);
426 static int worker_thread(void *__worker
);
428 static struct worker_pool
*std_worker_pools(int cpu
)
430 if (cpu
!= WORK_CPU_UNBOUND
)
431 return per_cpu(cpu_std_worker_pools
, cpu
);
433 return unbound_std_worker_pools
;
436 static int std_worker_pool_pri(struct worker_pool
*pool
)
438 return pool
- std_worker_pools(pool
->cpu
);
441 /* allocate ID and assign it to @pool */
442 static int worker_pool_assign_id(struct worker_pool
*pool
)
446 mutex_lock(&worker_pool_idr_mutex
);
447 idr_pre_get(&worker_pool_idr
, GFP_KERNEL
);
448 ret
= idr_get_new(&worker_pool_idr
, pool
, &pool
->id
);
449 mutex_unlock(&worker_pool_idr_mutex
);
455 * Lookup worker_pool by id. The idr currently is built during boot and
456 * never modified. Don't worry about locking for now.
458 static struct worker_pool
*worker_pool_by_id(int pool_id
)
460 return idr_find(&worker_pool_idr
, pool_id
);
463 static struct worker_pool
*get_std_worker_pool(int cpu
, bool highpri
)
465 struct worker_pool
*pools
= std_worker_pools(cpu
);
467 return &pools
[highpri
];
470 static struct pool_workqueue
*get_pwq(int cpu
, struct workqueue_struct
*wq
)
472 if (!(wq
->flags
& WQ_UNBOUND
)) {
473 if (likely(cpu
< nr_cpu_ids
))
474 return per_cpu_ptr(wq
->pool_wq
.pcpu
, cpu
);
475 } else if (likely(cpu
== WORK_CPU_UNBOUND
))
476 return wq
->pool_wq
.single
;
480 static unsigned int work_color_to_flags(int color
)
482 return color
<< WORK_STRUCT_COLOR_SHIFT
;
485 static int get_work_color(struct work_struct
*work
)
487 return (*work_data_bits(work
) >> WORK_STRUCT_COLOR_SHIFT
) &
488 ((1 << WORK_STRUCT_COLOR_BITS
) - 1);
491 static int work_next_color(int color
)
493 return (color
+ 1) % WORK_NR_COLORS
;
497 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
498 * contain the pointer to the queued pwq. Once execution starts, the flag
499 * is cleared and the high bits contain OFFQ flags and pool ID.
501 * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
502 * and clear_work_data() can be used to set the pwq, pool or clear
503 * work->data. These functions should only be called while the work is
504 * owned - ie. while the PENDING bit is set.
506 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
507 * corresponding to a work. Pool is available once the work has been
508 * queued anywhere after initialization until it is sync canceled. pwq is
509 * available only while the work item is queued.
511 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
512 * canceled. While being canceled, a work item may have its PENDING set
513 * but stay off timer and worklist for arbitrarily long and nobody should
514 * try to steal the PENDING bit.
516 static inline void set_work_data(struct work_struct
*work
, unsigned long data
,
519 WARN_ON_ONCE(!work_pending(work
));
520 atomic_long_set(&work
->data
, data
| flags
| work_static(work
));
523 static void set_work_pwq(struct work_struct
*work
, struct pool_workqueue
*pwq
,
524 unsigned long extra_flags
)
526 set_work_data(work
, (unsigned long)pwq
,
527 WORK_STRUCT_PENDING
| WORK_STRUCT_PWQ
| extra_flags
);
530 static void set_work_pool_and_keep_pending(struct work_struct
*work
,
533 set_work_data(work
, (unsigned long)pool_id
<< WORK_OFFQ_POOL_SHIFT
,
534 WORK_STRUCT_PENDING
);
537 static void set_work_pool_and_clear_pending(struct work_struct
*work
,
541 * The following wmb is paired with the implied mb in
542 * test_and_set_bit(PENDING) and ensures all updates to @work made
543 * here are visible to and precede any updates by the next PENDING
547 set_work_data(work
, (unsigned long)pool_id
<< WORK_OFFQ_POOL_SHIFT
, 0);
550 static void clear_work_data(struct work_struct
*work
)
552 smp_wmb(); /* see set_work_pool_and_clear_pending() */
553 set_work_data(work
, WORK_STRUCT_NO_POOL
, 0);
556 static struct pool_workqueue
*get_work_pwq(struct work_struct
*work
)
558 unsigned long data
= atomic_long_read(&work
->data
);
560 if (data
& WORK_STRUCT_PWQ
)
561 return (void *)(data
& WORK_STRUCT_WQ_DATA_MASK
);
567 * get_work_pool - return the worker_pool a given work was associated with
568 * @work: the work item of interest
570 * Return the worker_pool @work was last associated with. %NULL if none.
572 static struct worker_pool
*get_work_pool(struct work_struct
*work
)
574 unsigned long data
= atomic_long_read(&work
->data
);
575 struct worker_pool
*pool
;
578 if (data
& WORK_STRUCT_PWQ
)
579 return ((struct pool_workqueue
*)
580 (data
& WORK_STRUCT_WQ_DATA_MASK
))->pool
;
582 pool_id
= data
>> WORK_OFFQ_POOL_SHIFT
;
583 if (pool_id
== WORK_OFFQ_POOL_NONE
)
586 pool
= worker_pool_by_id(pool_id
);
592 * get_work_pool_id - return the worker pool ID a given work is associated with
593 * @work: the work item of interest
595 * Return the worker_pool ID @work was last associated with.
596 * %WORK_OFFQ_POOL_NONE if none.
598 static int get_work_pool_id(struct work_struct
*work
)
600 unsigned long data
= atomic_long_read(&work
->data
);
602 if (data
& WORK_STRUCT_PWQ
)
603 return ((struct pool_workqueue
*)
604 (data
& WORK_STRUCT_WQ_DATA_MASK
))->pool
->id
;
606 return data
>> WORK_OFFQ_POOL_SHIFT
;
609 static void mark_work_canceling(struct work_struct
*work
)
611 unsigned long pool_id
= get_work_pool_id(work
);
613 pool_id
<<= WORK_OFFQ_POOL_SHIFT
;
614 set_work_data(work
, pool_id
| WORK_OFFQ_CANCELING
, WORK_STRUCT_PENDING
);
617 static bool work_is_canceling(struct work_struct
*work
)
619 unsigned long data
= atomic_long_read(&work
->data
);
621 return !(data
& WORK_STRUCT_PWQ
) && (data
& WORK_OFFQ_CANCELING
);
625 * Policy functions. These define the policies on how the global worker
626 * pools are managed. Unless noted otherwise, these functions assume that
627 * they're being called with pool->lock held.
630 static bool __need_more_worker(struct worker_pool
*pool
)
632 return !atomic_read(&pool
->nr_running
);
636 * Need to wake up a worker? Called from anything but currently
639 * Note that, because unbound workers never contribute to nr_running, this
640 * function will always return %true for unbound pools as long as the
641 * worklist isn't empty.
643 static bool need_more_worker(struct worker_pool
*pool
)
645 return !list_empty(&pool
->worklist
) && __need_more_worker(pool
);
648 /* Can I start working? Called from busy but !running workers. */
649 static bool may_start_working(struct worker_pool
*pool
)
651 return pool
->nr_idle
;
654 /* Do I need to keep working? Called from currently running workers. */
655 static bool keep_working(struct worker_pool
*pool
)
657 return !list_empty(&pool
->worklist
) &&
658 atomic_read(&pool
->nr_running
) <= 1;
661 /* Do we need a new worker? Called from manager. */
662 static bool need_to_create_worker(struct worker_pool
*pool
)
664 return need_more_worker(pool
) && !may_start_working(pool
);
667 /* Do I need to be the manager? */
668 static bool need_to_manage_workers(struct worker_pool
*pool
)
670 return need_to_create_worker(pool
) ||
671 (pool
->flags
& POOL_MANAGE_WORKERS
);
674 /* Do we have too many workers and should some go away? */
675 static bool too_many_workers(struct worker_pool
*pool
)
677 bool managing
= pool
->flags
& POOL_MANAGING_WORKERS
;
678 int nr_idle
= pool
->nr_idle
+ managing
; /* manager is considered idle */
679 int nr_busy
= pool
->nr_workers
- nr_idle
;
682 * nr_idle and idle_list may disagree if idle rebinding is in
683 * progress. Never return %true if idle_list is empty.
685 if (list_empty(&pool
->idle_list
))
688 return nr_idle
> 2 && (nr_idle
- 2) * MAX_IDLE_WORKERS_RATIO
>= nr_busy
;
695 /* Return the first worker. Safe with preemption disabled */
696 static struct worker
*first_worker(struct worker_pool
*pool
)
698 if (unlikely(list_empty(&pool
->idle_list
)))
701 return list_first_entry(&pool
->idle_list
, struct worker
, entry
);
705 * wake_up_worker - wake up an idle worker
706 * @pool: worker pool to wake worker from
708 * Wake up the first idle worker of @pool.
711 * spin_lock_irq(pool->lock).
713 static void wake_up_worker(struct worker_pool
*pool
)
715 struct worker
*worker
= first_worker(pool
);
718 wake_up_process(worker
->task
);
722 * wq_worker_waking_up - a worker is waking up
723 * @task: task waking up
724 * @cpu: CPU @task is waking up to
726 * This function is called during try_to_wake_up() when a worker is
730 * spin_lock_irq(rq->lock)
732 void wq_worker_waking_up(struct task_struct
*task
, int cpu
)
734 struct worker
*worker
= kthread_data(task
);
736 if (!(worker
->flags
& WORKER_NOT_RUNNING
)) {
737 WARN_ON_ONCE(worker
->pool
->cpu
!= cpu
);
738 atomic_inc(&worker
->pool
->nr_running
);
743 * wq_worker_sleeping - a worker is going to sleep
744 * @task: task going to sleep
745 * @cpu: CPU in question, must be the current CPU number
747 * This function is called during schedule() when a busy worker is
748 * going to sleep. Worker on the same cpu can be woken up by
749 * returning pointer to its task.
752 * spin_lock_irq(rq->lock)
755 * Worker task on @cpu to wake up, %NULL if none.
757 struct task_struct
*wq_worker_sleeping(struct task_struct
*task
, int cpu
)
759 struct worker
*worker
= kthread_data(task
), *to_wakeup
= NULL
;
760 struct worker_pool
*pool
;
763 * Rescuers, which may not have all the fields set up like normal
764 * workers, also reach here, let's not access anything before
765 * checking NOT_RUNNING.
767 if (worker
->flags
& WORKER_NOT_RUNNING
)
772 /* this can only happen on the local cpu */
773 if (WARN_ON_ONCE(cpu
!= raw_smp_processor_id()))
777 * The counterpart of the following dec_and_test, implied mb,
778 * worklist not empty test sequence is in insert_work().
779 * Please read comment there.
781 * NOT_RUNNING is clear. This means that we're bound to and
782 * running on the local cpu w/ rq lock held and preemption
783 * disabled, which in turn means that none else could be
784 * manipulating idle_list, so dereferencing idle_list without pool
787 if (atomic_dec_and_test(&pool
->nr_running
) &&
788 !list_empty(&pool
->worklist
))
789 to_wakeup
= first_worker(pool
);
790 return to_wakeup
? to_wakeup
->task
: NULL
;
794 * worker_set_flags - set worker flags and adjust nr_running accordingly
796 * @flags: flags to set
797 * @wakeup: wakeup an idle worker if necessary
799 * Set @flags in @worker->flags and adjust nr_running accordingly. If
800 * nr_running becomes zero and @wakeup is %true, an idle worker is
804 * spin_lock_irq(pool->lock)
806 static inline void worker_set_flags(struct worker
*worker
, unsigned int flags
,
809 struct worker_pool
*pool
= worker
->pool
;
811 WARN_ON_ONCE(worker
->task
!= current
);
814 * If transitioning into NOT_RUNNING, adjust nr_running and
815 * wake up an idle worker as necessary if requested by
818 if ((flags
& WORKER_NOT_RUNNING
) &&
819 !(worker
->flags
& WORKER_NOT_RUNNING
)) {
821 if (atomic_dec_and_test(&pool
->nr_running
) &&
822 !list_empty(&pool
->worklist
))
823 wake_up_worker(pool
);
825 atomic_dec(&pool
->nr_running
);
828 worker
->flags
|= flags
;
832 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
834 * @flags: flags to clear
836 * Clear @flags in @worker->flags and adjust nr_running accordingly.
839 * spin_lock_irq(pool->lock)
841 static inline void worker_clr_flags(struct worker
*worker
, unsigned int flags
)
843 struct worker_pool
*pool
= worker
->pool
;
844 unsigned int oflags
= worker
->flags
;
846 WARN_ON_ONCE(worker
->task
!= current
);
848 worker
->flags
&= ~flags
;
851 * If transitioning out of NOT_RUNNING, increment nr_running. Note
852 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
853 * of multiple flags, not a single flag.
855 if ((flags
& WORKER_NOT_RUNNING
) && (oflags
& WORKER_NOT_RUNNING
))
856 if (!(worker
->flags
& WORKER_NOT_RUNNING
))
857 atomic_inc(&pool
->nr_running
);
861 * find_worker_executing_work - find worker which is executing a work
862 * @pool: pool of interest
863 * @work: work to find worker for
865 * Find a worker which is executing @work on @pool by searching
866 * @pool->busy_hash which is keyed by the address of @work. For a worker
867 * to match, its current execution should match the address of @work and
868 * its work function. This is to avoid unwanted dependency between
869 * unrelated work executions through a work item being recycled while still
872 * This is a bit tricky. A work item may be freed once its execution
873 * starts and nothing prevents the freed area from being recycled for
874 * another work item. If the same work item address ends up being reused
875 * before the original execution finishes, workqueue will identify the
876 * recycled work item as currently executing and make it wait until the
877 * current execution finishes, introducing an unwanted dependency.
879 * This function checks the work item address, work function and workqueue
880 * to avoid false positives. Note that this isn't complete as one may
881 * construct a work function which can introduce dependency onto itself
882 * through a recycled work item. Well, if somebody wants to shoot oneself
883 * in the foot that badly, there's only so much we can do, and if such
884 * deadlock actually occurs, it should be easy to locate the culprit work
888 * spin_lock_irq(pool->lock).
891 * Pointer to worker which is executing @work if found, NULL
894 static struct worker
*find_worker_executing_work(struct worker_pool
*pool
,
895 struct work_struct
*work
)
897 struct worker
*worker
;
899 hash_for_each_possible(pool
->busy_hash
, worker
, hentry
,
901 if (worker
->current_work
== work
&&
902 worker
->current_func
== work
->func
)
909 * move_linked_works - move linked works to a list
910 * @work: start of series of works to be scheduled
911 * @head: target list to append @work to
912 * @nextp: out paramter for nested worklist walking
914 * Schedule linked works starting from @work to @head. Work series to
915 * be scheduled starts at @work and includes any consecutive work with
916 * WORK_STRUCT_LINKED set in its predecessor.
918 * If @nextp is not NULL, it's updated to point to the next work of
919 * the last scheduled work. This allows move_linked_works() to be
920 * nested inside outer list_for_each_entry_safe().
923 * spin_lock_irq(pool->lock).
925 static void move_linked_works(struct work_struct
*work
, struct list_head
*head
,
926 struct work_struct
**nextp
)
928 struct work_struct
*n
;
931 * Linked worklist will always end before the end of the list,
932 * use NULL for list head.
934 list_for_each_entry_safe_from(work
, n
, NULL
, entry
) {
935 list_move_tail(&work
->entry
, head
);
936 if (!(*work_data_bits(work
) & WORK_STRUCT_LINKED
))
941 * If we're already inside safe list traversal and have moved
942 * multiple works to the scheduled queue, the next position
943 * needs to be updated.
949 static void pwq_activate_delayed_work(struct work_struct
*work
)
951 struct pool_workqueue
*pwq
= get_work_pwq(work
);
953 trace_workqueue_activate_work(work
);
954 move_linked_works(work
, &pwq
->pool
->worklist
, NULL
);
955 __clear_bit(WORK_STRUCT_DELAYED_BIT
, work_data_bits(work
));
959 static void pwq_activate_first_delayed(struct pool_workqueue
*pwq
)
961 struct work_struct
*work
= list_first_entry(&pwq
->delayed_works
,
962 struct work_struct
, entry
);
964 pwq_activate_delayed_work(work
);
968 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
969 * @pwq: pwq of interest
970 * @color: color of work which left the queue
972 * A work either has completed or is removed from pending queue,
973 * decrement nr_in_flight of its pwq and handle workqueue flushing.
976 * spin_lock_irq(pool->lock).
978 static void pwq_dec_nr_in_flight(struct pool_workqueue
*pwq
, int color
)
980 /* ignore uncolored works */
981 if (color
== WORK_NO_COLOR
)
984 pwq
->nr_in_flight
[color
]--;
987 if (!list_empty(&pwq
->delayed_works
)) {
988 /* one down, submit a delayed one */
989 if (pwq
->nr_active
< pwq
->max_active
)
990 pwq_activate_first_delayed(pwq
);
993 /* is flush in progress and are we at the flushing tip? */
994 if (likely(pwq
->flush_color
!= color
))
997 /* are there still in-flight works? */
998 if (pwq
->nr_in_flight
[color
])
1001 /* this pwq is done, clear flush_color */
1002 pwq
->flush_color
= -1;
1005 * If this was the last pwq, wake up the first flusher. It
1006 * will handle the rest.
1008 if (atomic_dec_and_test(&pwq
->wq
->nr_pwqs_to_flush
))
1009 complete(&pwq
->wq
->first_flusher
->done
);
1013 * try_to_grab_pending - steal work item from worklist and disable irq
1014 * @work: work item to steal
1015 * @is_dwork: @work is a delayed_work
1016 * @flags: place to store irq state
1018 * Try to grab PENDING bit of @work. This function can handle @work in any
1019 * stable state - idle, on timer or on worklist. Return values are
1021 * 1 if @work was pending and we successfully stole PENDING
1022 * 0 if @work was idle and we claimed PENDING
1023 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1024 * -ENOENT if someone else is canceling @work, this state may persist
1025 * for arbitrarily long
1027 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1028 * interrupted while holding PENDING and @work off queue, irq must be
1029 * disabled on entry. This, combined with delayed_work->timer being
1030 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1032 * On successful return, >= 0, irq is disabled and the caller is
1033 * responsible for releasing it using local_irq_restore(*@flags).
1035 * This function is safe to call from any context including IRQ handler.
1037 static int try_to_grab_pending(struct work_struct
*work
, bool is_dwork
,
1038 unsigned long *flags
)
1040 struct worker_pool
*pool
;
1041 struct pool_workqueue
*pwq
;
1043 local_irq_save(*flags
);
1045 /* try to steal the timer if it exists */
1047 struct delayed_work
*dwork
= to_delayed_work(work
);
1050 * dwork->timer is irqsafe. If del_timer() fails, it's
1051 * guaranteed that the timer is not queued anywhere and not
1052 * running on the local CPU.
1054 if (likely(del_timer(&dwork
->timer
)))
1058 /* try to claim PENDING the normal way */
1059 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(work
)))
1063 * The queueing is in progress, or it is already queued. Try to
1064 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1066 pool
= get_work_pool(work
);
1070 spin_lock(&pool
->lock
);
1072 * work->data is guaranteed to point to pwq only while the work
1073 * item is queued on pwq->wq, and both updating work->data to point
1074 * to pwq on queueing and to pool on dequeueing are done under
1075 * pwq->pool->lock. This in turn guarantees that, if work->data
1076 * points to pwq which is associated with a locked pool, the work
1077 * item is currently queued on that pool.
1079 pwq
= get_work_pwq(work
);
1080 if (pwq
&& pwq
->pool
== pool
) {
1081 debug_work_deactivate(work
);
1084 * A delayed work item cannot be grabbed directly because
1085 * it might have linked NO_COLOR work items which, if left
1086 * on the delayed_list, will confuse pwq->nr_active
1087 * management later on and cause stall. Make sure the work
1088 * item is activated before grabbing.
1090 if (*work_data_bits(work
) & WORK_STRUCT_DELAYED
)
1091 pwq_activate_delayed_work(work
);
1093 list_del_init(&work
->entry
);
1094 pwq_dec_nr_in_flight(get_work_pwq(work
), get_work_color(work
));
1096 /* work->data points to pwq iff queued, point to pool */
1097 set_work_pool_and_keep_pending(work
, pool
->id
);
1099 spin_unlock(&pool
->lock
);
1102 spin_unlock(&pool
->lock
);
1104 local_irq_restore(*flags
);
1105 if (work_is_canceling(work
))
1112 * insert_work - insert a work into a pool
1113 * @pwq: pwq @work belongs to
1114 * @work: work to insert
1115 * @head: insertion point
1116 * @extra_flags: extra WORK_STRUCT_* flags to set
1118 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
1119 * work_struct flags.
1122 * spin_lock_irq(pool->lock).
1124 static void insert_work(struct pool_workqueue
*pwq
, struct work_struct
*work
,
1125 struct list_head
*head
, unsigned int extra_flags
)
1127 struct worker_pool
*pool
= pwq
->pool
;
1129 /* we own @work, set data and link */
1130 set_work_pwq(work
, pwq
, extra_flags
);
1131 list_add_tail(&work
->entry
, head
);
1134 * Ensure either worker_sched_deactivated() sees the above
1135 * list_add_tail() or we see zero nr_running to avoid workers
1136 * lying around lazily while there are works to be processed.
1140 if (__need_more_worker(pool
))
1141 wake_up_worker(pool
);
1145 * Test whether @work is being queued from another work executing on the
1148 static bool is_chained_work(struct workqueue_struct
*wq
)
1150 struct worker
*worker
;
1152 worker
= current_wq_worker();
1154 * Return %true iff I'm a worker execuing a work item on @wq. If
1155 * I'm @worker, it's safe to dereference it without locking.
1157 return worker
&& worker
->current_pwq
->wq
== wq
;
1160 static void __queue_work(int cpu
, struct workqueue_struct
*wq
,
1161 struct work_struct
*work
)
1163 struct pool_workqueue
*pwq
;
1164 struct list_head
*worklist
;
1165 unsigned int work_flags
;
1166 unsigned int req_cpu
= cpu
;
1169 * While a work item is PENDING && off queue, a task trying to
1170 * steal the PENDING will busy-loop waiting for it to either get
1171 * queued or lose PENDING. Grabbing PENDING and queueing should
1172 * happen with IRQ disabled.
1174 WARN_ON_ONCE(!irqs_disabled());
1176 debug_work_activate(work
);
1178 /* if dying, only works from the same workqueue are allowed */
1179 if (unlikely(wq
->flags
& WQ_DRAINING
) &&
1180 WARN_ON_ONCE(!is_chained_work(wq
)))
1183 /* determine the pwq to use */
1184 if (!(wq
->flags
& WQ_UNBOUND
)) {
1185 struct worker_pool
*last_pool
;
1187 if (cpu
== WORK_CPU_UNBOUND
)
1188 cpu
= raw_smp_processor_id();
1191 * It's multi cpu. If @work was previously on a different
1192 * cpu, it might still be running there, in which case the
1193 * work needs to be queued on that cpu to guarantee
1196 pwq
= get_pwq(cpu
, wq
);
1197 last_pool
= get_work_pool(work
);
1199 if (last_pool
&& last_pool
!= pwq
->pool
) {
1200 struct worker
*worker
;
1202 spin_lock(&last_pool
->lock
);
1204 worker
= find_worker_executing_work(last_pool
, work
);
1206 if (worker
&& worker
->current_pwq
->wq
== wq
) {
1207 pwq
= get_pwq(last_pool
->cpu
, wq
);
1209 /* meh... not running there, queue here */
1210 spin_unlock(&last_pool
->lock
);
1211 spin_lock(&pwq
->pool
->lock
);
1214 spin_lock(&pwq
->pool
->lock
);
1217 pwq
= get_pwq(WORK_CPU_UNBOUND
, wq
);
1218 spin_lock(&pwq
->pool
->lock
);
1221 /* pwq determined, queue */
1222 trace_workqueue_queue_work(req_cpu
, pwq
, work
);
1224 if (WARN_ON(!list_empty(&work
->entry
))) {
1225 spin_unlock(&pwq
->pool
->lock
);
1229 pwq
->nr_in_flight
[pwq
->work_color
]++;
1230 work_flags
= work_color_to_flags(pwq
->work_color
);
1232 if (likely(pwq
->nr_active
< pwq
->max_active
)) {
1233 trace_workqueue_activate_work(work
);
1235 worklist
= &pwq
->pool
->worklist
;
1237 work_flags
|= WORK_STRUCT_DELAYED
;
1238 worklist
= &pwq
->delayed_works
;
1241 insert_work(pwq
, work
, worklist
, work_flags
);
1243 spin_unlock(&pwq
->pool
->lock
);
1247 * queue_work_on - queue work on specific cpu
1248 * @cpu: CPU number to execute work on
1249 * @wq: workqueue to use
1250 * @work: work to queue
1252 * Returns %false if @work was already on a queue, %true otherwise.
1254 * We queue the work to a specific CPU, the caller must ensure it
1257 bool queue_work_on(int cpu
, struct workqueue_struct
*wq
,
1258 struct work_struct
*work
)
1261 unsigned long flags
;
1263 local_irq_save(flags
);
1265 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(work
))) {
1266 __queue_work(cpu
, wq
, work
);
1270 local_irq_restore(flags
);
1273 EXPORT_SYMBOL_GPL(queue_work_on
);
1276 * queue_work - queue work on a workqueue
1277 * @wq: workqueue to use
1278 * @work: work to queue
1280 * Returns %false if @work was already on a queue, %true otherwise.
1282 * We queue the work to the CPU on which it was submitted, but if the CPU dies
1283 * it can be processed by another CPU.
1285 bool queue_work(struct workqueue_struct
*wq
, struct work_struct
*work
)
1287 return queue_work_on(WORK_CPU_UNBOUND
, wq
, work
);
1289 EXPORT_SYMBOL_GPL(queue_work
);
1291 void delayed_work_timer_fn(unsigned long __data
)
1293 struct delayed_work
*dwork
= (struct delayed_work
*)__data
;
1295 /* should have been called from irqsafe timer with irq already off */
1296 __queue_work(dwork
->cpu
, dwork
->wq
, &dwork
->work
);
1298 EXPORT_SYMBOL(delayed_work_timer_fn
);
1300 static void __queue_delayed_work(int cpu
, struct workqueue_struct
*wq
,
1301 struct delayed_work
*dwork
, unsigned long delay
)
1303 struct timer_list
*timer
= &dwork
->timer
;
1304 struct work_struct
*work
= &dwork
->work
;
1306 WARN_ON_ONCE(timer
->function
!= delayed_work_timer_fn
||
1307 timer
->data
!= (unsigned long)dwork
);
1308 WARN_ON_ONCE(timer_pending(timer
));
1309 WARN_ON_ONCE(!list_empty(&work
->entry
));
1312 * If @delay is 0, queue @dwork->work immediately. This is for
1313 * both optimization and correctness. The earliest @timer can
1314 * expire is on the closest next tick and delayed_work users depend
1315 * on that there's no such delay when @delay is 0.
1318 __queue_work(cpu
, wq
, &dwork
->work
);
1322 timer_stats_timer_set_start_info(&dwork
->timer
);
1326 timer
->expires
= jiffies
+ delay
;
1328 if (unlikely(cpu
!= WORK_CPU_UNBOUND
))
1329 add_timer_on(timer
, cpu
);
1335 * queue_delayed_work_on - queue work on specific CPU after delay
1336 * @cpu: CPU number to execute work on
1337 * @wq: workqueue to use
1338 * @dwork: work to queue
1339 * @delay: number of jiffies to wait before queueing
1341 * Returns %false if @work was already on a queue, %true otherwise. If
1342 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1345 bool queue_delayed_work_on(int cpu
, struct workqueue_struct
*wq
,
1346 struct delayed_work
*dwork
, unsigned long delay
)
1348 struct work_struct
*work
= &dwork
->work
;
1350 unsigned long flags
;
1352 /* read the comment in __queue_work() */
1353 local_irq_save(flags
);
1355 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(work
))) {
1356 __queue_delayed_work(cpu
, wq
, dwork
, delay
);
1360 local_irq_restore(flags
);
1363 EXPORT_SYMBOL_GPL(queue_delayed_work_on
);
1366 * queue_delayed_work - queue work on a workqueue after delay
1367 * @wq: workqueue to use
1368 * @dwork: delayable work to queue
1369 * @delay: number of jiffies to wait before queueing
1371 * Equivalent to queue_delayed_work_on() but tries to use the local CPU.
1373 bool queue_delayed_work(struct workqueue_struct
*wq
,
1374 struct delayed_work
*dwork
, unsigned long delay
)
1376 return queue_delayed_work_on(WORK_CPU_UNBOUND
, wq
, dwork
, delay
);
1378 EXPORT_SYMBOL_GPL(queue_delayed_work
);
1381 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1382 * @cpu: CPU number to execute work on
1383 * @wq: workqueue to use
1384 * @dwork: work to queue
1385 * @delay: number of jiffies to wait before queueing
1387 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1388 * modify @dwork's timer so that it expires after @delay. If @delay is
1389 * zero, @work is guaranteed to be scheduled immediately regardless of its
1392 * Returns %false if @dwork was idle and queued, %true if @dwork was
1393 * pending and its timer was modified.
1395 * This function is safe to call from any context including IRQ handler.
1396 * See try_to_grab_pending() for details.
1398 bool mod_delayed_work_on(int cpu
, struct workqueue_struct
*wq
,
1399 struct delayed_work
*dwork
, unsigned long delay
)
1401 unsigned long flags
;
1405 ret
= try_to_grab_pending(&dwork
->work
, true, &flags
);
1406 } while (unlikely(ret
== -EAGAIN
));
1408 if (likely(ret
>= 0)) {
1409 __queue_delayed_work(cpu
, wq
, dwork
, delay
);
1410 local_irq_restore(flags
);
1413 /* -ENOENT from try_to_grab_pending() becomes %true */
1416 EXPORT_SYMBOL_GPL(mod_delayed_work_on
);
1419 * mod_delayed_work - modify delay of or queue a delayed work
1420 * @wq: workqueue to use
1421 * @dwork: work to queue
1422 * @delay: number of jiffies to wait before queueing
1424 * mod_delayed_work_on() on local CPU.
1426 bool mod_delayed_work(struct workqueue_struct
*wq
, struct delayed_work
*dwork
,
1427 unsigned long delay
)
1429 return mod_delayed_work_on(WORK_CPU_UNBOUND
, wq
, dwork
, delay
);
1431 EXPORT_SYMBOL_GPL(mod_delayed_work
);
1434 * worker_enter_idle - enter idle state
1435 * @worker: worker which is entering idle state
1437 * @worker is entering idle state. Update stats and idle timer if
1441 * spin_lock_irq(pool->lock).
1443 static void worker_enter_idle(struct worker
*worker
)
1445 struct worker_pool
*pool
= worker
->pool
;
1447 if (WARN_ON_ONCE(worker
->flags
& WORKER_IDLE
) ||
1448 WARN_ON_ONCE(!list_empty(&worker
->entry
) &&
1449 (worker
->hentry
.next
|| worker
->hentry
.pprev
)))
1452 /* can't use worker_set_flags(), also called from start_worker() */
1453 worker
->flags
|= WORKER_IDLE
;
1455 worker
->last_active
= jiffies
;
1457 /* idle_list is LIFO */
1458 list_add(&worker
->entry
, &pool
->idle_list
);
1460 if (too_many_workers(pool
) && !timer_pending(&pool
->idle_timer
))
1461 mod_timer(&pool
->idle_timer
, jiffies
+ IDLE_WORKER_TIMEOUT
);
1464 * Sanity check nr_running. Because wq_unbind_fn() releases
1465 * pool->lock between setting %WORKER_UNBOUND and zapping
1466 * nr_running, the warning may trigger spuriously. Check iff
1467 * unbind is not in progress.
1469 WARN_ON_ONCE(!(pool
->flags
& POOL_DISASSOCIATED
) &&
1470 pool
->nr_workers
== pool
->nr_idle
&&
1471 atomic_read(&pool
->nr_running
));
1475 * worker_leave_idle - leave idle state
1476 * @worker: worker which is leaving idle state
1478 * @worker is leaving idle state. Update stats.
1481 * spin_lock_irq(pool->lock).
1483 static void worker_leave_idle(struct worker
*worker
)
1485 struct worker_pool
*pool
= worker
->pool
;
1487 if (WARN_ON_ONCE(!(worker
->flags
& WORKER_IDLE
)))
1489 worker_clr_flags(worker
, WORKER_IDLE
);
1491 list_del_init(&worker
->entry
);
1495 * worker_maybe_bind_and_lock - try to bind %current to worker_pool and lock it
1496 * @pool: target worker_pool
1498 * Bind %current to the cpu of @pool if it is associated and lock @pool.
1500 * Works which are scheduled while the cpu is online must at least be
1501 * scheduled to a worker which is bound to the cpu so that if they are
1502 * flushed from cpu callbacks while cpu is going down, they are
1503 * guaranteed to execute on the cpu.
1505 * This function is to be used by unbound workers and rescuers to bind
1506 * themselves to the target cpu and may race with cpu going down or
1507 * coming online. kthread_bind() can't be used because it may put the
1508 * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1509 * verbatim as it's best effort and blocking and pool may be
1510 * [dis]associated in the meantime.
1512 * This function tries set_cpus_allowed() and locks pool and verifies the
1513 * binding against %POOL_DISASSOCIATED which is set during
1514 * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
1515 * enters idle state or fetches works without dropping lock, it can
1516 * guarantee the scheduling requirement described in the first paragraph.
1519 * Might sleep. Called without any lock but returns with pool->lock
1523 * %true if the associated pool is online (@worker is successfully
1524 * bound), %false if offline.
1526 static bool worker_maybe_bind_and_lock(struct worker_pool
*pool
)
1527 __acquires(&pool
->lock
)
1531 * The following call may fail, succeed or succeed
1532 * without actually migrating the task to the cpu if
1533 * it races with cpu hotunplug operation. Verify
1534 * against POOL_DISASSOCIATED.
1536 if (!(pool
->flags
& POOL_DISASSOCIATED
))
1537 set_cpus_allowed_ptr(current
, get_cpu_mask(pool
->cpu
));
1539 spin_lock_irq(&pool
->lock
);
1540 if (pool
->flags
& POOL_DISASSOCIATED
)
1542 if (task_cpu(current
) == pool
->cpu
&&
1543 cpumask_equal(¤t
->cpus_allowed
,
1544 get_cpu_mask(pool
->cpu
)))
1546 spin_unlock_irq(&pool
->lock
);
1549 * We've raced with CPU hot[un]plug. Give it a breather
1550 * and retry migration. cond_resched() is required here;
1551 * otherwise, we might deadlock against cpu_stop trying to
1552 * bring down the CPU on non-preemptive kernel.
1560 * Rebind an idle @worker to its CPU. worker_thread() will test
1561 * list_empty(@worker->entry) before leaving idle and call this function.
1563 static void idle_worker_rebind(struct worker
*worker
)
1565 /* CPU may go down again inbetween, clear UNBOUND only on success */
1566 if (worker_maybe_bind_and_lock(worker
->pool
))
1567 worker_clr_flags(worker
, WORKER_UNBOUND
);
1569 /* rebind complete, become available again */
1570 list_add(&worker
->entry
, &worker
->pool
->idle_list
);
1571 spin_unlock_irq(&worker
->pool
->lock
);
1575 * Function for @worker->rebind.work used to rebind unbound busy workers to
1576 * the associated cpu which is coming back online. This is scheduled by
1577 * cpu up but can race with other cpu hotplug operations and may be
1578 * executed twice without intervening cpu down.
1580 static void busy_worker_rebind_fn(struct work_struct
*work
)
1582 struct worker
*worker
= container_of(work
, struct worker
, rebind_work
);
1584 if (worker_maybe_bind_and_lock(worker
->pool
))
1585 worker_clr_flags(worker
, WORKER_UNBOUND
);
1587 spin_unlock_irq(&worker
->pool
->lock
);
1591 * rebind_workers - rebind all workers of a pool to the associated CPU
1592 * @pool: pool of interest
1594 * @pool->cpu is coming online. Rebind all workers to the CPU. Rebinding
1595 * is different for idle and busy ones.
1597 * Idle ones will be removed from the idle_list and woken up. They will
1598 * add themselves back after completing rebind. This ensures that the
1599 * idle_list doesn't contain any unbound workers when re-bound busy workers
1600 * try to perform local wake-ups for concurrency management.
1602 * Busy workers can rebind after they finish their current work items.
1603 * Queueing the rebind work item at the head of the scheduled list is
1604 * enough. Note that nr_running will be properly bumped as busy workers
1607 * On return, all non-manager workers are scheduled for rebind - see
1608 * manage_workers() for the manager special case. Any idle worker
1609 * including the manager will not appear on @idle_list until rebind is
1610 * complete, making local wake-ups safe.
1612 static void rebind_workers(struct worker_pool
*pool
)
1614 struct worker
*worker
, *n
;
1617 lockdep_assert_held(&pool
->assoc_mutex
);
1618 lockdep_assert_held(&pool
->lock
);
1620 /* dequeue and kick idle ones */
1621 list_for_each_entry_safe(worker
, n
, &pool
->idle_list
, entry
) {
1623 * idle workers should be off @pool->idle_list until rebind
1624 * is complete to avoid receiving premature local wake-ups.
1626 list_del_init(&worker
->entry
);
1629 * worker_thread() will see the above dequeuing and call
1630 * idle_worker_rebind().
1632 wake_up_process(worker
->task
);
1635 /* rebind busy workers */
1636 for_each_busy_worker(worker
, i
, pool
) {
1637 struct work_struct
*rebind_work
= &worker
->rebind_work
;
1638 struct workqueue_struct
*wq
;
1640 if (test_and_set_bit(WORK_STRUCT_PENDING_BIT
,
1641 work_data_bits(rebind_work
)))
1644 debug_work_activate(rebind_work
);
1647 * wq doesn't really matter but let's keep @worker->pool
1648 * and @pwq->pool consistent for sanity.
1650 if (std_worker_pool_pri(worker
->pool
))
1651 wq
= system_highpri_wq
;
1655 insert_work(get_pwq(pool
->cpu
, wq
), rebind_work
,
1656 worker
->scheduled
.next
,
1657 work_color_to_flags(WORK_NO_COLOR
));
1661 static struct worker
*alloc_worker(void)
1663 struct worker
*worker
;
1665 worker
= kzalloc(sizeof(*worker
), GFP_KERNEL
);
1667 INIT_LIST_HEAD(&worker
->entry
);
1668 INIT_LIST_HEAD(&worker
->scheduled
);
1669 INIT_WORK(&worker
->rebind_work
, busy_worker_rebind_fn
);
1670 /* on creation a worker is in !idle && prep state */
1671 worker
->flags
= WORKER_PREP
;
1677 * create_worker - create a new workqueue worker
1678 * @pool: pool the new worker will belong to
1680 * Create a new worker which is bound to @pool. The returned worker
1681 * can be started by calling start_worker() or destroyed using
1685 * Might sleep. Does GFP_KERNEL allocations.
1688 * Pointer to the newly created worker.
1690 static struct worker
*create_worker(struct worker_pool
*pool
)
1692 const char *pri
= std_worker_pool_pri(pool
) ? "H" : "";
1693 struct worker
*worker
= NULL
;
1696 spin_lock_irq(&pool
->lock
);
1697 while (ida_get_new(&pool
->worker_ida
, &id
)) {
1698 spin_unlock_irq(&pool
->lock
);
1699 if (!ida_pre_get(&pool
->worker_ida
, GFP_KERNEL
))
1701 spin_lock_irq(&pool
->lock
);
1703 spin_unlock_irq(&pool
->lock
);
1705 worker
= alloc_worker();
1709 worker
->pool
= pool
;
1712 if (pool
->cpu
!= WORK_CPU_UNBOUND
)
1713 worker
->task
= kthread_create_on_node(worker_thread
,
1714 worker
, cpu_to_node(pool
->cpu
),
1715 "kworker/%d:%d%s", pool
->cpu
, id
, pri
);
1717 worker
->task
= kthread_create(worker_thread
, worker
,
1718 "kworker/u:%d%s", id
, pri
);
1719 if (IS_ERR(worker
->task
))
1722 if (std_worker_pool_pri(pool
))
1723 set_user_nice(worker
->task
, HIGHPRI_NICE_LEVEL
);
1726 * Determine CPU binding of the new worker depending on
1727 * %POOL_DISASSOCIATED. The caller is responsible for ensuring the
1728 * flag remains stable across this function. See the comments
1729 * above the flag definition for details.
1731 * As an unbound worker may later become a regular one if CPU comes
1732 * online, make sure every worker has %PF_THREAD_BOUND set.
1734 if (!(pool
->flags
& POOL_DISASSOCIATED
)) {
1735 kthread_bind(worker
->task
, pool
->cpu
);
1737 worker
->task
->flags
|= PF_THREAD_BOUND
;
1738 worker
->flags
|= WORKER_UNBOUND
;
1744 spin_lock_irq(&pool
->lock
);
1745 ida_remove(&pool
->worker_ida
, id
);
1746 spin_unlock_irq(&pool
->lock
);
1753 * start_worker - start a newly created worker
1754 * @worker: worker to start
1756 * Make the pool aware of @worker and start it.
1759 * spin_lock_irq(pool->lock).
1761 static void start_worker(struct worker
*worker
)
1763 worker
->flags
|= WORKER_STARTED
;
1764 worker
->pool
->nr_workers
++;
1765 worker_enter_idle(worker
);
1766 wake_up_process(worker
->task
);
1770 * destroy_worker - destroy a workqueue worker
1771 * @worker: worker to be destroyed
1773 * Destroy @worker and adjust @pool stats accordingly.
1776 * spin_lock_irq(pool->lock) which is released and regrabbed.
1778 static void destroy_worker(struct worker
*worker
)
1780 struct worker_pool
*pool
= worker
->pool
;
1781 int id
= worker
->id
;
1783 /* sanity check frenzy */
1784 if (WARN_ON(worker
->current_work
) ||
1785 WARN_ON(!list_empty(&worker
->scheduled
)))
1788 if (worker
->flags
& WORKER_STARTED
)
1790 if (worker
->flags
& WORKER_IDLE
)
1793 list_del_init(&worker
->entry
);
1794 worker
->flags
|= WORKER_DIE
;
1796 spin_unlock_irq(&pool
->lock
);
1798 kthread_stop(worker
->task
);
1801 spin_lock_irq(&pool
->lock
);
1802 ida_remove(&pool
->worker_ida
, id
);
1805 static void idle_worker_timeout(unsigned long __pool
)
1807 struct worker_pool
*pool
= (void *)__pool
;
1809 spin_lock_irq(&pool
->lock
);
1811 if (too_many_workers(pool
)) {
1812 struct worker
*worker
;
1813 unsigned long expires
;
1815 /* idle_list is kept in LIFO order, check the last one */
1816 worker
= list_entry(pool
->idle_list
.prev
, struct worker
, entry
);
1817 expires
= worker
->last_active
+ IDLE_WORKER_TIMEOUT
;
1819 if (time_before(jiffies
, expires
))
1820 mod_timer(&pool
->idle_timer
, expires
);
1822 /* it's been idle for too long, wake up manager */
1823 pool
->flags
|= POOL_MANAGE_WORKERS
;
1824 wake_up_worker(pool
);
1828 spin_unlock_irq(&pool
->lock
);
1831 static void send_mayday(struct work_struct
*work
)
1833 struct pool_workqueue
*pwq
= get_work_pwq(work
);
1834 struct workqueue_struct
*wq
= pwq
->wq
;
1836 lockdep_assert_held(&workqueue_lock
);
1838 if (!(wq
->flags
& WQ_RESCUER
))
1841 /* mayday mayday mayday */
1842 if (list_empty(&pwq
->mayday_node
)) {
1843 list_add_tail(&pwq
->mayday_node
, &wq
->maydays
);
1844 wake_up_process(wq
->rescuer
->task
);
1848 static void pool_mayday_timeout(unsigned long __pool
)
1850 struct worker_pool
*pool
= (void *)__pool
;
1851 struct work_struct
*work
;
1853 spin_lock_irq(&workqueue_lock
); /* for wq->maydays */
1854 spin_lock(&pool
->lock
);
1856 if (need_to_create_worker(pool
)) {
1858 * We've been trying to create a new worker but
1859 * haven't been successful. We might be hitting an
1860 * allocation deadlock. Send distress signals to
1863 list_for_each_entry(work
, &pool
->worklist
, entry
)
1867 spin_unlock(&pool
->lock
);
1868 spin_unlock_irq(&workqueue_lock
);
1870 mod_timer(&pool
->mayday_timer
, jiffies
+ MAYDAY_INTERVAL
);
1874 * maybe_create_worker - create a new worker if necessary
1875 * @pool: pool to create a new worker for
1877 * Create a new worker for @pool if necessary. @pool is guaranteed to
1878 * have at least one idle worker on return from this function. If
1879 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1880 * sent to all rescuers with works scheduled on @pool to resolve
1881 * possible allocation deadlock.
1883 * On return, need_to_create_worker() is guaranteed to be false and
1884 * may_start_working() true.
1887 * spin_lock_irq(pool->lock) which may be released and regrabbed
1888 * multiple times. Does GFP_KERNEL allocations. Called only from
1892 * false if no action was taken and pool->lock stayed locked, true
1895 static bool maybe_create_worker(struct worker_pool
*pool
)
1896 __releases(&pool
->lock
)
1897 __acquires(&pool
->lock
)
1899 if (!need_to_create_worker(pool
))
1902 spin_unlock_irq(&pool
->lock
);
1904 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1905 mod_timer(&pool
->mayday_timer
, jiffies
+ MAYDAY_INITIAL_TIMEOUT
);
1908 struct worker
*worker
;
1910 worker
= create_worker(pool
);
1912 del_timer_sync(&pool
->mayday_timer
);
1913 spin_lock_irq(&pool
->lock
);
1914 start_worker(worker
);
1915 if (WARN_ON_ONCE(need_to_create_worker(pool
)))
1920 if (!need_to_create_worker(pool
))
1923 __set_current_state(TASK_INTERRUPTIBLE
);
1924 schedule_timeout(CREATE_COOLDOWN
);
1926 if (!need_to_create_worker(pool
))
1930 del_timer_sync(&pool
->mayday_timer
);
1931 spin_lock_irq(&pool
->lock
);
1932 if (need_to_create_worker(pool
))
1938 * maybe_destroy_worker - destroy workers which have been idle for a while
1939 * @pool: pool to destroy workers for
1941 * Destroy @pool workers which have been idle for longer than
1942 * IDLE_WORKER_TIMEOUT.
1945 * spin_lock_irq(pool->lock) which may be released and regrabbed
1946 * multiple times. Called only from manager.
1949 * false if no action was taken and pool->lock stayed locked, true
1952 static bool maybe_destroy_workers(struct worker_pool
*pool
)
1956 while (too_many_workers(pool
)) {
1957 struct worker
*worker
;
1958 unsigned long expires
;
1960 worker
= list_entry(pool
->idle_list
.prev
, struct worker
, entry
);
1961 expires
= worker
->last_active
+ IDLE_WORKER_TIMEOUT
;
1963 if (time_before(jiffies
, expires
)) {
1964 mod_timer(&pool
->idle_timer
, expires
);
1968 destroy_worker(worker
);
1976 * manage_workers - manage worker pool
1979 * Assume the manager role and manage the worker pool @worker belongs
1980 * to. At any given time, there can be only zero or one manager per
1981 * pool. The exclusion is handled automatically by this function.
1983 * The caller can safely start processing works on false return. On
1984 * true return, it's guaranteed that need_to_create_worker() is false
1985 * and may_start_working() is true.
1988 * spin_lock_irq(pool->lock) which may be released and regrabbed
1989 * multiple times. Does GFP_KERNEL allocations.
1992 * spin_lock_irq(pool->lock) which may be released and regrabbed
1993 * multiple times. Does GFP_KERNEL allocations.
1995 static bool manage_workers(struct worker
*worker
)
1997 struct worker_pool
*pool
= worker
->pool
;
2000 if (pool
->flags
& POOL_MANAGING_WORKERS
)
2003 pool
->flags
|= POOL_MANAGING_WORKERS
;
2006 * To simplify both worker management and CPU hotplug, hold off
2007 * management while hotplug is in progress. CPU hotplug path can't
2008 * grab %POOL_MANAGING_WORKERS to achieve this because that can
2009 * lead to idle worker depletion (all become busy thinking someone
2010 * else is managing) which in turn can result in deadlock under
2011 * extreme circumstances. Use @pool->assoc_mutex to synchronize
2012 * manager against CPU hotplug.
2014 * assoc_mutex would always be free unless CPU hotplug is in
2015 * progress. trylock first without dropping @pool->lock.
2017 if (unlikely(!mutex_trylock(&pool
->assoc_mutex
))) {
2018 spin_unlock_irq(&pool
->lock
);
2019 mutex_lock(&pool
->assoc_mutex
);
2021 * CPU hotplug could have happened while we were waiting
2022 * for assoc_mutex. Hotplug itself can't handle us
2023 * because manager isn't either on idle or busy list, and
2024 * @pool's state and ours could have deviated.
2026 * As hotplug is now excluded via assoc_mutex, we can
2027 * simply try to bind. It will succeed or fail depending
2028 * on @pool's current state. Try it and adjust
2029 * %WORKER_UNBOUND accordingly.
2031 if (worker_maybe_bind_and_lock(pool
))
2032 worker
->flags
&= ~WORKER_UNBOUND
;
2034 worker
->flags
|= WORKER_UNBOUND
;
2039 pool
->flags
&= ~POOL_MANAGE_WORKERS
;
2042 * Destroy and then create so that may_start_working() is true
2045 ret
|= maybe_destroy_workers(pool
);
2046 ret
|= maybe_create_worker(pool
);
2048 pool
->flags
&= ~POOL_MANAGING_WORKERS
;
2049 mutex_unlock(&pool
->assoc_mutex
);
2054 * process_one_work - process single work
2056 * @work: work to process
2058 * Process @work. This function contains all the logics necessary to
2059 * process a single work including synchronization against and
2060 * interaction with other workers on the same cpu, queueing and
2061 * flushing. As long as context requirement is met, any worker can
2062 * call this function to process a work.
2065 * spin_lock_irq(pool->lock) which is released and regrabbed.
2067 static void process_one_work(struct worker
*worker
, struct work_struct
*work
)
2068 __releases(&pool
->lock
)
2069 __acquires(&pool
->lock
)
2071 struct pool_workqueue
*pwq
= get_work_pwq(work
);
2072 struct worker_pool
*pool
= worker
->pool
;
2073 bool cpu_intensive
= pwq
->wq
->flags
& WQ_CPU_INTENSIVE
;
2075 struct worker
*collision
;
2076 #ifdef CONFIG_LOCKDEP
2078 * It is permissible to free the struct work_struct from
2079 * inside the function that is called from it, this we need to
2080 * take into account for lockdep too. To avoid bogus "held
2081 * lock freed" warnings as well as problems when looking into
2082 * work->lockdep_map, make a copy and use that here.
2084 struct lockdep_map lockdep_map
;
2086 lockdep_copy_map(&lockdep_map
, &work
->lockdep_map
);
2089 * Ensure we're on the correct CPU. DISASSOCIATED test is
2090 * necessary to avoid spurious warnings from rescuers servicing the
2091 * unbound or a disassociated pool.
2093 WARN_ON_ONCE(!(worker
->flags
& WORKER_UNBOUND
) &&
2094 !(pool
->flags
& POOL_DISASSOCIATED
) &&
2095 raw_smp_processor_id() != pool
->cpu
);
2098 * A single work shouldn't be executed concurrently by
2099 * multiple workers on a single cpu. Check whether anyone is
2100 * already processing the work. If so, defer the work to the
2101 * currently executing one.
2103 collision
= find_worker_executing_work(pool
, work
);
2104 if (unlikely(collision
)) {
2105 move_linked_works(work
, &collision
->scheduled
, NULL
);
2109 /* claim and dequeue */
2110 debug_work_deactivate(work
);
2111 hash_add(pool
->busy_hash
, &worker
->hentry
, (unsigned long)work
);
2112 worker
->current_work
= work
;
2113 worker
->current_func
= work
->func
;
2114 worker
->current_pwq
= pwq
;
2115 work_color
= get_work_color(work
);
2117 list_del_init(&work
->entry
);
2120 * CPU intensive works don't participate in concurrency
2121 * management. They're the scheduler's responsibility.
2123 if (unlikely(cpu_intensive
))
2124 worker_set_flags(worker
, WORKER_CPU_INTENSIVE
, true);
2127 * Unbound pool isn't concurrency managed and work items should be
2128 * executed ASAP. Wake up another worker if necessary.
2130 if ((worker
->flags
& WORKER_UNBOUND
) && need_more_worker(pool
))
2131 wake_up_worker(pool
);
2134 * Record the last pool and clear PENDING which should be the last
2135 * update to @work. Also, do this inside @pool->lock so that
2136 * PENDING and queued state changes happen together while IRQ is
2139 set_work_pool_and_clear_pending(work
, pool
->id
);
2141 spin_unlock_irq(&pool
->lock
);
2143 lock_map_acquire_read(&pwq
->wq
->lockdep_map
);
2144 lock_map_acquire(&lockdep_map
);
2145 trace_workqueue_execute_start(work
);
2146 worker
->current_func(work
);
2148 * While we must be careful to not use "work" after this, the trace
2149 * point will only record its address.
2151 trace_workqueue_execute_end(work
);
2152 lock_map_release(&lockdep_map
);
2153 lock_map_release(&pwq
->wq
->lockdep_map
);
2155 if (unlikely(in_atomic() || lockdep_depth(current
) > 0)) {
2156 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2157 " last function: %pf\n",
2158 current
->comm
, preempt_count(), task_pid_nr(current
),
2159 worker
->current_func
);
2160 debug_show_held_locks(current
);
2164 spin_lock_irq(&pool
->lock
);
2166 /* clear cpu intensive status */
2167 if (unlikely(cpu_intensive
))
2168 worker_clr_flags(worker
, WORKER_CPU_INTENSIVE
);
2170 /* we're done with it, release */
2171 hash_del(&worker
->hentry
);
2172 worker
->current_work
= NULL
;
2173 worker
->current_func
= NULL
;
2174 worker
->current_pwq
= NULL
;
2175 pwq_dec_nr_in_flight(pwq
, work_color
);
2179 * process_scheduled_works - process scheduled works
2182 * Process all scheduled works. Please note that the scheduled list
2183 * may change while processing a work, so this function repeatedly
2184 * fetches a work from the top and executes it.
2187 * spin_lock_irq(pool->lock) which may be released and regrabbed
2190 static void process_scheduled_works(struct worker
*worker
)
2192 while (!list_empty(&worker
->scheduled
)) {
2193 struct work_struct
*work
= list_first_entry(&worker
->scheduled
,
2194 struct work_struct
, entry
);
2195 process_one_work(worker
, work
);
2200 * worker_thread - the worker thread function
2203 * The worker thread function. There are NR_CPU_WORKER_POOLS dynamic pools
2204 * of these per each cpu. These workers process all works regardless of
2205 * their specific target workqueue. The only exception is works which
2206 * belong to workqueues with a rescuer which will be explained in
2209 static int worker_thread(void *__worker
)
2211 struct worker
*worker
= __worker
;
2212 struct worker_pool
*pool
= worker
->pool
;
2214 /* tell the scheduler that this is a workqueue worker */
2215 worker
->task
->flags
|= PF_WQ_WORKER
;
2217 spin_lock_irq(&pool
->lock
);
2219 /* we are off idle list if destruction or rebind is requested */
2220 if (unlikely(list_empty(&worker
->entry
))) {
2221 spin_unlock_irq(&pool
->lock
);
2223 /* if DIE is set, destruction is requested */
2224 if (worker
->flags
& WORKER_DIE
) {
2225 worker
->task
->flags
&= ~PF_WQ_WORKER
;
2229 /* otherwise, rebind */
2230 idle_worker_rebind(worker
);
2234 worker_leave_idle(worker
);
2236 /* no more worker necessary? */
2237 if (!need_more_worker(pool
))
2240 /* do we need to manage? */
2241 if (unlikely(!may_start_working(pool
)) && manage_workers(worker
))
2245 * ->scheduled list can only be filled while a worker is
2246 * preparing to process a work or actually processing it.
2247 * Make sure nobody diddled with it while I was sleeping.
2249 WARN_ON_ONCE(!list_empty(&worker
->scheduled
));
2252 * When control reaches this point, we're guaranteed to have
2253 * at least one idle worker or that someone else has already
2254 * assumed the manager role.
2256 worker_clr_flags(worker
, WORKER_PREP
);
2259 struct work_struct
*work
=
2260 list_first_entry(&pool
->worklist
,
2261 struct work_struct
, entry
);
2263 if (likely(!(*work_data_bits(work
) & WORK_STRUCT_LINKED
))) {
2264 /* optimization path, not strictly necessary */
2265 process_one_work(worker
, work
);
2266 if (unlikely(!list_empty(&worker
->scheduled
)))
2267 process_scheduled_works(worker
);
2269 move_linked_works(work
, &worker
->scheduled
, NULL
);
2270 process_scheduled_works(worker
);
2272 } while (keep_working(pool
));
2274 worker_set_flags(worker
, WORKER_PREP
, false);
2276 if (unlikely(need_to_manage_workers(pool
)) && manage_workers(worker
))
2280 * pool->lock is held and there's no work to process and no need to
2281 * manage, sleep. Workers are woken up only while holding
2282 * pool->lock or from local cpu, so setting the current state
2283 * before releasing pool->lock is enough to prevent losing any
2286 worker_enter_idle(worker
);
2287 __set_current_state(TASK_INTERRUPTIBLE
);
2288 spin_unlock_irq(&pool
->lock
);
2294 * rescuer_thread - the rescuer thread function
2297 * Workqueue rescuer thread function. There's one rescuer for each
2298 * workqueue which has WQ_RESCUER set.
2300 * Regular work processing on a pool may block trying to create a new
2301 * worker which uses GFP_KERNEL allocation which has slight chance of
2302 * developing into deadlock if some works currently on the same queue
2303 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2304 * the problem rescuer solves.
2306 * When such condition is possible, the pool summons rescuers of all
2307 * workqueues which have works queued on the pool and let them process
2308 * those works so that forward progress can be guaranteed.
2310 * This should happen rarely.
2312 static int rescuer_thread(void *__rescuer
)
2314 struct worker
*rescuer
= __rescuer
;
2315 struct workqueue_struct
*wq
= rescuer
->rescue_wq
;
2316 struct list_head
*scheduled
= &rescuer
->scheduled
;
2318 set_user_nice(current
, RESCUER_NICE_LEVEL
);
2321 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2322 * doesn't participate in concurrency management.
2324 rescuer
->task
->flags
|= PF_WQ_WORKER
;
2326 set_current_state(TASK_INTERRUPTIBLE
);
2328 if (kthread_should_stop()) {
2329 __set_current_state(TASK_RUNNING
);
2330 rescuer
->task
->flags
&= ~PF_WQ_WORKER
;
2334 /* see whether any pwq is asking for help */
2335 spin_lock_irq(&workqueue_lock
);
2337 while (!list_empty(&wq
->maydays
)) {
2338 struct pool_workqueue
*pwq
= list_first_entry(&wq
->maydays
,
2339 struct pool_workqueue
, mayday_node
);
2340 struct worker_pool
*pool
= pwq
->pool
;
2341 struct work_struct
*work
, *n
;
2343 __set_current_state(TASK_RUNNING
);
2344 list_del_init(&pwq
->mayday_node
);
2346 spin_unlock_irq(&workqueue_lock
);
2348 /* migrate to the target cpu if possible */
2349 worker_maybe_bind_and_lock(pool
);
2350 rescuer
->pool
= pool
;
2353 * Slurp in all works issued via this workqueue and
2356 WARN_ON_ONCE(!list_empty(&rescuer
->scheduled
));
2357 list_for_each_entry_safe(work
, n
, &pool
->worklist
, entry
)
2358 if (get_work_pwq(work
) == pwq
)
2359 move_linked_works(work
, scheduled
, &n
);
2361 process_scheduled_works(rescuer
);
2364 * Leave this pool. If keep_working() is %true, notify a
2365 * regular worker; otherwise, we end up with 0 concurrency
2366 * and stalling the execution.
2368 if (keep_working(pool
))
2369 wake_up_worker(pool
);
2371 rescuer
->pool
= NULL
;
2372 spin_unlock(&pool
->lock
);
2373 spin_lock(&workqueue_lock
);
2376 spin_unlock_irq(&workqueue_lock
);
2378 /* rescuers should never participate in concurrency management */
2379 WARN_ON_ONCE(!(rescuer
->flags
& WORKER_NOT_RUNNING
));
2385 struct work_struct work
;
2386 struct completion done
;
2389 static void wq_barrier_func(struct work_struct
*work
)
2391 struct wq_barrier
*barr
= container_of(work
, struct wq_barrier
, work
);
2392 complete(&barr
->done
);
2396 * insert_wq_barrier - insert a barrier work
2397 * @pwq: pwq to insert barrier into
2398 * @barr: wq_barrier to insert
2399 * @target: target work to attach @barr to
2400 * @worker: worker currently executing @target, NULL if @target is not executing
2402 * @barr is linked to @target such that @barr is completed only after
2403 * @target finishes execution. Please note that the ordering
2404 * guarantee is observed only with respect to @target and on the local
2407 * Currently, a queued barrier can't be canceled. This is because
2408 * try_to_grab_pending() can't determine whether the work to be
2409 * grabbed is at the head of the queue and thus can't clear LINKED
2410 * flag of the previous work while there must be a valid next work
2411 * after a work with LINKED flag set.
2413 * Note that when @worker is non-NULL, @target may be modified
2414 * underneath us, so we can't reliably determine pwq from @target.
2417 * spin_lock_irq(pool->lock).
2419 static void insert_wq_barrier(struct pool_workqueue
*pwq
,
2420 struct wq_barrier
*barr
,
2421 struct work_struct
*target
, struct worker
*worker
)
2423 struct list_head
*head
;
2424 unsigned int linked
= 0;
2427 * debugobject calls are safe here even with pool->lock locked
2428 * as we know for sure that this will not trigger any of the
2429 * checks and call back into the fixup functions where we
2432 INIT_WORK_ONSTACK(&barr
->work
, wq_barrier_func
);
2433 __set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(&barr
->work
));
2434 init_completion(&barr
->done
);
2437 * If @target is currently being executed, schedule the
2438 * barrier to the worker; otherwise, put it after @target.
2441 head
= worker
->scheduled
.next
;
2443 unsigned long *bits
= work_data_bits(target
);
2445 head
= target
->entry
.next
;
2446 /* there can already be other linked works, inherit and set */
2447 linked
= *bits
& WORK_STRUCT_LINKED
;
2448 __set_bit(WORK_STRUCT_LINKED_BIT
, bits
);
2451 debug_work_activate(&barr
->work
);
2452 insert_work(pwq
, &barr
->work
, head
,
2453 work_color_to_flags(WORK_NO_COLOR
) | linked
);
2457 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
2458 * @wq: workqueue being flushed
2459 * @flush_color: new flush color, < 0 for no-op
2460 * @work_color: new work color, < 0 for no-op
2462 * Prepare pwqs for workqueue flushing.
2464 * If @flush_color is non-negative, flush_color on all pwqs should be
2465 * -1. If no pwq has in-flight commands at the specified color, all
2466 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
2467 * has in flight commands, its pwq->flush_color is set to
2468 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
2469 * wakeup logic is armed and %true is returned.
2471 * The caller should have initialized @wq->first_flusher prior to
2472 * calling this function with non-negative @flush_color. If
2473 * @flush_color is negative, no flush color update is done and %false
2476 * If @work_color is non-negative, all pwqs should have the same
2477 * work_color which is previous to @work_color and all will be
2478 * advanced to @work_color.
2481 * mutex_lock(wq->flush_mutex).
2484 * %true if @flush_color >= 0 and there's something to flush. %false
2487 static bool flush_workqueue_prep_pwqs(struct workqueue_struct
*wq
,
2488 int flush_color
, int work_color
)
2491 struct pool_workqueue
*pwq
;
2493 if (flush_color
>= 0) {
2494 WARN_ON_ONCE(atomic_read(&wq
->nr_pwqs_to_flush
));
2495 atomic_set(&wq
->nr_pwqs_to_flush
, 1);
2498 for_each_pwq(pwq
, wq
) {
2499 struct worker_pool
*pool
= pwq
->pool
;
2501 spin_lock_irq(&pool
->lock
);
2503 if (flush_color
>= 0) {
2504 WARN_ON_ONCE(pwq
->flush_color
!= -1);
2506 if (pwq
->nr_in_flight
[flush_color
]) {
2507 pwq
->flush_color
= flush_color
;
2508 atomic_inc(&wq
->nr_pwqs_to_flush
);
2513 if (work_color
>= 0) {
2514 WARN_ON_ONCE(work_color
!= work_next_color(pwq
->work_color
));
2515 pwq
->work_color
= work_color
;
2518 spin_unlock_irq(&pool
->lock
);
2521 if (flush_color
>= 0 && atomic_dec_and_test(&wq
->nr_pwqs_to_flush
))
2522 complete(&wq
->first_flusher
->done
);
2528 * flush_workqueue - ensure that any scheduled work has run to completion.
2529 * @wq: workqueue to flush
2531 * Forces execution of the workqueue and blocks until its completion.
2532 * This is typically used in driver shutdown handlers.
2534 * We sleep until all works which were queued on entry have been handled,
2535 * but we are not livelocked by new incoming ones.
2537 void flush_workqueue(struct workqueue_struct
*wq
)
2539 struct wq_flusher this_flusher
= {
2540 .list
= LIST_HEAD_INIT(this_flusher
.list
),
2542 .done
= COMPLETION_INITIALIZER_ONSTACK(this_flusher
.done
),
2546 lock_map_acquire(&wq
->lockdep_map
);
2547 lock_map_release(&wq
->lockdep_map
);
2549 mutex_lock(&wq
->flush_mutex
);
2552 * Start-to-wait phase
2554 next_color
= work_next_color(wq
->work_color
);
2556 if (next_color
!= wq
->flush_color
) {
2558 * Color space is not full. The current work_color
2559 * becomes our flush_color and work_color is advanced
2562 WARN_ON_ONCE(!list_empty(&wq
->flusher_overflow
));
2563 this_flusher
.flush_color
= wq
->work_color
;
2564 wq
->work_color
= next_color
;
2566 if (!wq
->first_flusher
) {
2567 /* no flush in progress, become the first flusher */
2568 WARN_ON_ONCE(wq
->flush_color
!= this_flusher
.flush_color
);
2570 wq
->first_flusher
= &this_flusher
;
2572 if (!flush_workqueue_prep_pwqs(wq
, wq
->flush_color
,
2574 /* nothing to flush, done */
2575 wq
->flush_color
= next_color
;
2576 wq
->first_flusher
= NULL
;
2581 WARN_ON_ONCE(wq
->flush_color
== this_flusher
.flush_color
);
2582 list_add_tail(&this_flusher
.list
, &wq
->flusher_queue
);
2583 flush_workqueue_prep_pwqs(wq
, -1, wq
->work_color
);
2587 * Oops, color space is full, wait on overflow queue.
2588 * The next flush completion will assign us
2589 * flush_color and transfer to flusher_queue.
2591 list_add_tail(&this_flusher
.list
, &wq
->flusher_overflow
);
2594 mutex_unlock(&wq
->flush_mutex
);
2596 wait_for_completion(&this_flusher
.done
);
2599 * Wake-up-and-cascade phase
2601 * First flushers are responsible for cascading flushes and
2602 * handling overflow. Non-first flushers can simply return.
2604 if (wq
->first_flusher
!= &this_flusher
)
2607 mutex_lock(&wq
->flush_mutex
);
2609 /* we might have raced, check again with mutex held */
2610 if (wq
->first_flusher
!= &this_flusher
)
2613 wq
->first_flusher
= NULL
;
2615 WARN_ON_ONCE(!list_empty(&this_flusher
.list
));
2616 WARN_ON_ONCE(wq
->flush_color
!= this_flusher
.flush_color
);
2619 struct wq_flusher
*next
, *tmp
;
2621 /* complete all the flushers sharing the current flush color */
2622 list_for_each_entry_safe(next
, tmp
, &wq
->flusher_queue
, list
) {
2623 if (next
->flush_color
!= wq
->flush_color
)
2625 list_del_init(&next
->list
);
2626 complete(&next
->done
);
2629 WARN_ON_ONCE(!list_empty(&wq
->flusher_overflow
) &&
2630 wq
->flush_color
!= work_next_color(wq
->work_color
));
2632 /* this flush_color is finished, advance by one */
2633 wq
->flush_color
= work_next_color(wq
->flush_color
);
2635 /* one color has been freed, handle overflow queue */
2636 if (!list_empty(&wq
->flusher_overflow
)) {
2638 * Assign the same color to all overflowed
2639 * flushers, advance work_color and append to
2640 * flusher_queue. This is the start-to-wait
2641 * phase for these overflowed flushers.
2643 list_for_each_entry(tmp
, &wq
->flusher_overflow
, list
)
2644 tmp
->flush_color
= wq
->work_color
;
2646 wq
->work_color
= work_next_color(wq
->work_color
);
2648 list_splice_tail_init(&wq
->flusher_overflow
,
2649 &wq
->flusher_queue
);
2650 flush_workqueue_prep_pwqs(wq
, -1, wq
->work_color
);
2653 if (list_empty(&wq
->flusher_queue
)) {
2654 WARN_ON_ONCE(wq
->flush_color
!= wq
->work_color
);
2659 * Need to flush more colors. Make the next flusher
2660 * the new first flusher and arm pwqs.
2662 WARN_ON_ONCE(wq
->flush_color
== wq
->work_color
);
2663 WARN_ON_ONCE(wq
->flush_color
!= next
->flush_color
);
2665 list_del_init(&next
->list
);
2666 wq
->first_flusher
= next
;
2668 if (flush_workqueue_prep_pwqs(wq
, wq
->flush_color
, -1))
2672 * Meh... this color is already done, clear first
2673 * flusher and repeat cascading.
2675 wq
->first_flusher
= NULL
;
2679 mutex_unlock(&wq
->flush_mutex
);
2681 EXPORT_SYMBOL_GPL(flush_workqueue
);
2684 * drain_workqueue - drain a workqueue
2685 * @wq: workqueue to drain
2687 * Wait until the workqueue becomes empty. While draining is in progress,
2688 * only chain queueing is allowed. IOW, only currently pending or running
2689 * work items on @wq can queue further work items on it. @wq is flushed
2690 * repeatedly until it becomes empty. The number of flushing is detemined
2691 * by the depth of chaining and should be relatively short. Whine if it
2694 void drain_workqueue(struct workqueue_struct
*wq
)
2696 unsigned int flush_cnt
= 0;
2697 struct pool_workqueue
*pwq
;
2700 * __queue_work() needs to test whether there are drainers, is much
2701 * hotter than drain_workqueue() and already looks at @wq->flags.
2702 * Use WQ_DRAINING so that queue doesn't have to check nr_drainers.
2704 spin_lock_irq(&workqueue_lock
);
2705 if (!wq
->nr_drainers
++)
2706 wq
->flags
|= WQ_DRAINING
;
2707 spin_unlock_irq(&workqueue_lock
);
2709 flush_workqueue(wq
);
2711 for_each_pwq(pwq
, wq
) {
2714 spin_lock_irq(&pwq
->pool
->lock
);
2715 drained
= !pwq
->nr_active
&& list_empty(&pwq
->delayed_works
);
2716 spin_unlock_irq(&pwq
->pool
->lock
);
2721 if (++flush_cnt
== 10 ||
2722 (flush_cnt
% 100 == 0 && flush_cnt
<= 1000))
2723 pr_warn("workqueue %s: flush on destruction isn't complete after %u tries\n",
2724 wq
->name
, flush_cnt
);
2728 spin_lock_irq(&workqueue_lock
);
2729 if (!--wq
->nr_drainers
)
2730 wq
->flags
&= ~WQ_DRAINING
;
2731 spin_unlock_irq(&workqueue_lock
);
2733 EXPORT_SYMBOL_GPL(drain_workqueue
);
2735 static bool start_flush_work(struct work_struct
*work
, struct wq_barrier
*barr
)
2737 struct worker
*worker
= NULL
;
2738 struct worker_pool
*pool
;
2739 struct pool_workqueue
*pwq
;
2742 pool
= get_work_pool(work
);
2746 spin_lock_irq(&pool
->lock
);
2747 /* see the comment in try_to_grab_pending() with the same code */
2748 pwq
= get_work_pwq(work
);
2750 if (unlikely(pwq
->pool
!= pool
))
2753 worker
= find_worker_executing_work(pool
, work
);
2756 pwq
= worker
->current_pwq
;
2759 insert_wq_barrier(pwq
, barr
, work
, worker
);
2760 spin_unlock_irq(&pool
->lock
);
2763 * If @max_active is 1 or rescuer is in use, flushing another work
2764 * item on the same workqueue may lead to deadlock. Make sure the
2765 * flusher is not running on the same workqueue by verifying write
2768 if (pwq
->wq
->saved_max_active
== 1 || pwq
->wq
->flags
& WQ_RESCUER
)
2769 lock_map_acquire(&pwq
->wq
->lockdep_map
);
2771 lock_map_acquire_read(&pwq
->wq
->lockdep_map
);
2772 lock_map_release(&pwq
->wq
->lockdep_map
);
2776 spin_unlock_irq(&pool
->lock
);
2781 * flush_work - wait for a work to finish executing the last queueing instance
2782 * @work: the work to flush
2784 * Wait until @work has finished execution. @work is guaranteed to be idle
2785 * on return if it hasn't been requeued since flush started.
2788 * %true if flush_work() waited for the work to finish execution,
2789 * %false if it was already idle.
2791 bool flush_work(struct work_struct
*work
)
2793 struct wq_barrier barr
;
2795 lock_map_acquire(&work
->lockdep_map
);
2796 lock_map_release(&work
->lockdep_map
);
2798 if (start_flush_work(work
, &barr
)) {
2799 wait_for_completion(&barr
.done
);
2800 destroy_work_on_stack(&barr
.work
);
2806 EXPORT_SYMBOL_GPL(flush_work
);
2808 static bool __cancel_work_timer(struct work_struct
*work
, bool is_dwork
)
2810 unsigned long flags
;
2814 ret
= try_to_grab_pending(work
, is_dwork
, &flags
);
2816 * If someone else is canceling, wait for the same event it
2817 * would be waiting for before retrying.
2819 if (unlikely(ret
== -ENOENT
))
2821 } while (unlikely(ret
< 0));
2823 /* tell other tasks trying to grab @work to back off */
2824 mark_work_canceling(work
);
2825 local_irq_restore(flags
);
2828 clear_work_data(work
);
2833 * cancel_work_sync - cancel a work and wait for it to finish
2834 * @work: the work to cancel
2836 * Cancel @work and wait for its execution to finish. This function
2837 * can be used even if the work re-queues itself or migrates to
2838 * another workqueue. On return from this function, @work is
2839 * guaranteed to be not pending or executing on any CPU.
2841 * cancel_work_sync(&delayed_work->work) must not be used for
2842 * delayed_work's. Use cancel_delayed_work_sync() instead.
2844 * The caller must ensure that the workqueue on which @work was last
2845 * queued can't be destroyed before this function returns.
2848 * %true if @work was pending, %false otherwise.
2850 bool cancel_work_sync(struct work_struct
*work
)
2852 return __cancel_work_timer(work
, false);
2854 EXPORT_SYMBOL_GPL(cancel_work_sync
);
2857 * flush_delayed_work - wait for a dwork to finish executing the last queueing
2858 * @dwork: the delayed work to flush
2860 * Delayed timer is cancelled and the pending work is queued for
2861 * immediate execution. Like flush_work(), this function only
2862 * considers the last queueing instance of @dwork.
2865 * %true if flush_work() waited for the work to finish execution,
2866 * %false if it was already idle.
2868 bool flush_delayed_work(struct delayed_work
*dwork
)
2870 local_irq_disable();
2871 if (del_timer_sync(&dwork
->timer
))
2872 __queue_work(dwork
->cpu
, dwork
->wq
, &dwork
->work
);
2874 return flush_work(&dwork
->work
);
2876 EXPORT_SYMBOL(flush_delayed_work
);
2879 * cancel_delayed_work - cancel a delayed work
2880 * @dwork: delayed_work to cancel
2882 * Kill off a pending delayed_work. Returns %true if @dwork was pending
2883 * and canceled; %false if wasn't pending. Note that the work callback
2884 * function may still be running on return, unless it returns %true and the
2885 * work doesn't re-arm itself. Explicitly flush or use
2886 * cancel_delayed_work_sync() to wait on it.
2888 * This function is safe to call from any context including IRQ handler.
2890 bool cancel_delayed_work(struct delayed_work
*dwork
)
2892 unsigned long flags
;
2896 ret
= try_to_grab_pending(&dwork
->work
, true, &flags
);
2897 } while (unlikely(ret
== -EAGAIN
));
2899 if (unlikely(ret
< 0))
2902 set_work_pool_and_clear_pending(&dwork
->work
,
2903 get_work_pool_id(&dwork
->work
));
2904 local_irq_restore(flags
);
2907 EXPORT_SYMBOL(cancel_delayed_work
);
2910 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2911 * @dwork: the delayed work cancel
2913 * This is cancel_work_sync() for delayed works.
2916 * %true if @dwork was pending, %false otherwise.
2918 bool cancel_delayed_work_sync(struct delayed_work
*dwork
)
2920 return __cancel_work_timer(&dwork
->work
, true);
2922 EXPORT_SYMBOL(cancel_delayed_work_sync
);
2925 * schedule_work_on - put work task on a specific cpu
2926 * @cpu: cpu to put the work task on
2927 * @work: job to be done
2929 * This puts a job on a specific cpu
2931 bool schedule_work_on(int cpu
, struct work_struct
*work
)
2933 return queue_work_on(cpu
, system_wq
, work
);
2935 EXPORT_SYMBOL(schedule_work_on
);
2938 * schedule_work - put work task in global workqueue
2939 * @work: job to be done
2941 * Returns %false if @work was already on the kernel-global workqueue and
2944 * This puts a job in the kernel-global workqueue if it was not already
2945 * queued and leaves it in the same position on the kernel-global
2946 * workqueue otherwise.
2948 bool schedule_work(struct work_struct
*work
)
2950 return queue_work(system_wq
, work
);
2952 EXPORT_SYMBOL(schedule_work
);
2955 * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
2957 * @dwork: job to be done
2958 * @delay: number of jiffies to wait
2960 * After waiting for a given time this puts a job in the kernel-global
2961 * workqueue on the specified CPU.
2963 bool schedule_delayed_work_on(int cpu
, struct delayed_work
*dwork
,
2964 unsigned long delay
)
2966 return queue_delayed_work_on(cpu
, system_wq
, dwork
, delay
);
2968 EXPORT_SYMBOL(schedule_delayed_work_on
);
2971 * schedule_delayed_work - put work task in global workqueue after delay
2972 * @dwork: job to be done
2973 * @delay: number of jiffies to wait or 0 for immediate execution
2975 * After waiting for a given time this puts a job in the kernel-global
2978 bool schedule_delayed_work(struct delayed_work
*dwork
, unsigned long delay
)
2980 return queue_delayed_work(system_wq
, dwork
, delay
);
2982 EXPORT_SYMBOL(schedule_delayed_work
);
2985 * schedule_on_each_cpu - execute a function synchronously on each online CPU
2986 * @func: the function to call
2988 * schedule_on_each_cpu() executes @func on each online CPU using the
2989 * system workqueue and blocks until all CPUs have completed.
2990 * schedule_on_each_cpu() is very slow.
2993 * 0 on success, -errno on failure.
2995 int schedule_on_each_cpu(work_func_t func
)
2998 struct work_struct __percpu
*works
;
3000 works
= alloc_percpu(struct work_struct
);
3006 for_each_online_cpu(cpu
) {
3007 struct work_struct
*work
= per_cpu_ptr(works
, cpu
);
3009 INIT_WORK(work
, func
);
3010 schedule_work_on(cpu
, work
);
3013 for_each_online_cpu(cpu
)
3014 flush_work(per_cpu_ptr(works
, cpu
));
3022 * flush_scheduled_work - ensure that any scheduled work has run to completion.
3024 * Forces execution of the kernel-global workqueue and blocks until its
3027 * Think twice before calling this function! It's very easy to get into
3028 * trouble if you don't take great care. Either of the following situations
3029 * will lead to deadlock:
3031 * One of the work items currently on the workqueue needs to acquire
3032 * a lock held by your code or its caller.
3034 * Your code is running in the context of a work routine.
3036 * They will be detected by lockdep when they occur, but the first might not
3037 * occur very often. It depends on what work items are on the workqueue and
3038 * what locks they need, which you have no control over.
3040 * In most situations flushing the entire workqueue is overkill; you merely
3041 * need to know that a particular work item isn't queued and isn't running.
3042 * In such cases you should use cancel_delayed_work_sync() or
3043 * cancel_work_sync() instead.
3045 void flush_scheduled_work(void)
3047 flush_workqueue(system_wq
);
3049 EXPORT_SYMBOL(flush_scheduled_work
);
3052 * execute_in_process_context - reliably execute the routine with user context
3053 * @fn: the function to execute
3054 * @ew: guaranteed storage for the execute work structure (must
3055 * be available when the work executes)
3057 * Executes the function immediately if process context is available,
3058 * otherwise schedules the function for delayed execution.
3060 * Returns: 0 - function was executed
3061 * 1 - function was scheduled for execution
3063 int execute_in_process_context(work_func_t fn
, struct execute_work
*ew
)
3065 if (!in_interrupt()) {
3070 INIT_WORK(&ew
->work
, fn
);
3071 schedule_work(&ew
->work
);
3075 EXPORT_SYMBOL_GPL(execute_in_process_context
);
3077 int keventd_up(void)
3079 return system_wq
!= NULL
;
3082 static int alloc_and_link_pwqs(struct workqueue_struct
*wq
)
3084 bool highpri
= wq
->flags
& WQ_HIGHPRI
;
3087 if (!(wq
->flags
& WQ_UNBOUND
)) {
3088 wq
->pool_wq
.pcpu
= alloc_percpu(struct pool_workqueue
);
3089 if (!wq
->pool_wq
.pcpu
)
3092 for_each_possible_cpu(cpu
) {
3093 struct pool_workqueue
*pwq
= get_pwq(cpu
, wq
);
3095 pwq
->pool
= get_std_worker_pool(cpu
, highpri
);
3096 list_add_tail(&pwq
->pwqs_node
, &wq
->pwqs
);
3099 struct pool_workqueue
*pwq
;
3101 pwq
= kmem_cache_zalloc(pwq_cache
, GFP_KERNEL
);
3105 wq
->pool_wq
.single
= pwq
;
3106 pwq
->pool
= get_std_worker_pool(WORK_CPU_UNBOUND
, highpri
);
3107 list_add_tail(&pwq
->pwqs_node
, &wq
->pwqs
);
3113 static void free_pwqs(struct workqueue_struct
*wq
)
3115 if (!(wq
->flags
& WQ_UNBOUND
))
3116 free_percpu(wq
->pool_wq
.pcpu
);
3118 kmem_cache_free(pwq_cache
, wq
->pool_wq
.single
);
3121 static int wq_clamp_max_active(int max_active
, unsigned int flags
,
3124 int lim
= flags
& WQ_UNBOUND
? WQ_UNBOUND_MAX_ACTIVE
: WQ_MAX_ACTIVE
;
3126 if (max_active
< 1 || max_active
> lim
)
3127 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3128 max_active
, name
, 1, lim
);
3130 return clamp_val(max_active
, 1, lim
);
3133 struct workqueue_struct
*__alloc_workqueue_key(const char *fmt
,
3136 struct lock_class_key
*key
,
3137 const char *lock_name
, ...)
3139 va_list args
, args1
;
3140 struct workqueue_struct
*wq
;
3141 struct pool_workqueue
*pwq
;
3144 /* determine namelen, allocate wq and format name */
3145 va_start(args
, lock_name
);
3146 va_copy(args1
, args
);
3147 namelen
= vsnprintf(NULL
, 0, fmt
, args
) + 1;
3149 wq
= kzalloc(sizeof(*wq
) + namelen
, GFP_KERNEL
);
3153 vsnprintf(wq
->name
, namelen
, fmt
, args1
);
3158 * Workqueues which may be used during memory reclaim should
3159 * have a rescuer to guarantee forward progress.
3161 if (flags
& WQ_MEM_RECLAIM
)
3162 flags
|= WQ_RESCUER
;
3164 max_active
= max_active
?: WQ_DFL_ACTIVE
;
3165 max_active
= wq_clamp_max_active(max_active
, flags
, wq
->name
);
3169 wq
->saved_max_active
= max_active
;
3170 mutex_init(&wq
->flush_mutex
);
3171 atomic_set(&wq
->nr_pwqs_to_flush
, 0);
3172 INIT_LIST_HEAD(&wq
->pwqs
);
3173 INIT_LIST_HEAD(&wq
->flusher_queue
);
3174 INIT_LIST_HEAD(&wq
->flusher_overflow
);
3175 INIT_LIST_HEAD(&wq
->maydays
);
3177 lockdep_init_map(&wq
->lockdep_map
, lock_name
, key
, 0);
3178 INIT_LIST_HEAD(&wq
->list
);
3180 if (alloc_and_link_pwqs(wq
) < 0)
3183 for_each_pwq(pwq
, wq
) {
3184 BUG_ON((unsigned long)pwq
& WORK_STRUCT_FLAG_MASK
);
3186 pwq
->flush_color
= -1;
3187 pwq
->max_active
= max_active
;
3188 INIT_LIST_HEAD(&pwq
->delayed_works
);
3189 INIT_LIST_HEAD(&pwq
->mayday_node
);
3192 if (flags
& WQ_RESCUER
) {
3193 struct worker
*rescuer
;
3195 wq
->rescuer
= rescuer
= alloc_worker();
3199 rescuer
->rescue_wq
= wq
;
3200 rescuer
->task
= kthread_create(rescuer_thread
, rescuer
, "%s",
3202 if (IS_ERR(rescuer
->task
))
3205 rescuer
->task
->flags
|= PF_THREAD_BOUND
;
3206 wake_up_process(rescuer
->task
);
3210 * workqueue_lock protects global freeze state and workqueues
3211 * list. Grab it, set max_active accordingly and add the new
3212 * workqueue to workqueues list.
3214 spin_lock_irq(&workqueue_lock
);
3216 if (workqueue_freezing
&& wq
->flags
& WQ_FREEZABLE
)
3217 for_each_pwq(pwq
, wq
)
3218 pwq
->max_active
= 0;
3220 list_add(&wq
->list
, &workqueues
);
3222 spin_unlock_irq(&workqueue_lock
);
3233 EXPORT_SYMBOL_GPL(__alloc_workqueue_key
);
3236 * destroy_workqueue - safely terminate a workqueue
3237 * @wq: target workqueue
3239 * Safely destroy a workqueue. All work currently pending will be done first.
3241 void destroy_workqueue(struct workqueue_struct
*wq
)
3243 struct pool_workqueue
*pwq
;
3245 /* drain it before proceeding with destruction */
3246 drain_workqueue(wq
);
3249 for_each_pwq(pwq
, wq
) {
3252 for (i
= 0; i
< WORK_NR_COLORS
; i
++)
3253 if (WARN_ON(pwq
->nr_in_flight
[i
]))
3255 if (WARN_ON(pwq
->nr_active
) ||
3256 WARN_ON(!list_empty(&pwq
->delayed_works
)))
3261 * wq list is used to freeze wq, remove from list after
3262 * flushing is complete in case freeze races us.
3264 spin_lock_irq(&workqueue_lock
);
3265 list_del(&wq
->list
);
3266 spin_unlock_irq(&workqueue_lock
);
3268 if (wq
->flags
& WQ_RESCUER
) {
3269 kthread_stop(wq
->rescuer
->task
);
3276 EXPORT_SYMBOL_GPL(destroy_workqueue
);
3279 * pwq_set_max_active - adjust max_active of a pwq
3280 * @pwq: target pool_workqueue
3281 * @max_active: new max_active value.
3283 * Set @pwq->max_active to @max_active and activate delayed works if
3287 * spin_lock_irq(pool->lock).
3289 static void pwq_set_max_active(struct pool_workqueue
*pwq
, int max_active
)
3291 pwq
->max_active
= max_active
;
3293 while (!list_empty(&pwq
->delayed_works
) &&
3294 pwq
->nr_active
< pwq
->max_active
)
3295 pwq_activate_first_delayed(pwq
);
3299 * workqueue_set_max_active - adjust max_active of a workqueue
3300 * @wq: target workqueue
3301 * @max_active: new max_active value.
3303 * Set max_active of @wq to @max_active.
3306 * Don't call from IRQ context.
3308 void workqueue_set_max_active(struct workqueue_struct
*wq
, int max_active
)
3310 struct pool_workqueue
*pwq
;
3312 max_active
= wq_clamp_max_active(max_active
, wq
->flags
, wq
->name
);
3314 spin_lock_irq(&workqueue_lock
);
3316 wq
->saved_max_active
= max_active
;
3318 for_each_pwq(pwq
, wq
) {
3319 struct worker_pool
*pool
= pwq
->pool
;
3321 spin_lock(&pool
->lock
);
3323 if (!(wq
->flags
& WQ_FREEZABLE
) ||
3324 !(pool
->flags
& POOL_FREEZING
))
3325 pwq_set_max_active(pwq
, max_active
);
3327 spin_unlock(&pool
->lock
);
3330 spin_unlock_irq(&workqueue_lock
);
3332 EXPORT_SYMBOL_GPL(workqueue_set_max_active
);
3335 * workqueue_congested - test whether a workqueue is congested
3336 * @cpu: CPU in question
3337 * @wq: target workqueue
3339 * Test whether @wq's cpu workqueue for @cpu is congested. There is
3340 * no synchronization around this function and the test result is
3341 * unreliable and only useful as advisory hints or for debugging.
3344 * %true if congested, %false otherwise.
3346 bool workqueue_congested(int cpu
, struct workqueue_struct
*wq
)
3348 struct pool_workqueue
*pwq
= get_pwq(cpu
, wq
);
3350 return !list_empty(&pwq
->delayed_works
);
3352 EXPORT_SYMBOL_GPL(workqueue_congested
);
3355 * work_busy - test whether a work is currently pending or running
3356 * @work: the work to be tested
3358 * Test whether @work is currently pending or running. There is no
3359 * synchronization around this function and the test result is
3360 * unreliable and only useful as advisory hints or for debugging.
3363 * OR'd bitmask of WORK_BUSY_* bits.
3365 unsigned int work_busy(struct work_struct
*work
)
3367 struct worker_pool
*pool
= get_work_pool(work
);
3368 unsigned long flags
;
3369 unsigned int ret
= 0;
3371 if (work_pending(work
))
3372 ret
|= WORK_BUSY_PENDING
;
3375 spin_lock_irqsave(&pool
->lock
, flags
);
3376 if (find_worker_executing_work(pool
, work
))
3377 ret
|= WORK_BUSY_RUNNING
;
3378 spin_unlock_irqrestore(&pool
->lock
, flags
);
3383 EXPORT_SYMBOL_GPL(work_busy
);
3388 * There are two challenges in supporting CPU hotplug. Firstly, there
3389 * are a lot of assumptions on strong associations among work, pwq and
3390 * pool which make migrating pending and scheduled works very
3391 * difficult to implement without impacting hot paths. Secondly,
3392 * worker pools serve mix of short, long and very long running works making
3393 * blocked draining impractical.
3395 * This is solved by allowing the pools to be disassociated from the CPU
3396 * running as an unbound one and allowing it to be reattached later if the
3397 * cpu comes back online.
3400 static void wq_unbind_fn(struct work_struct
*work
)
3402 int cpu
= smp_processor_id();
3403 struct worker_pool
*pool
;
3404 struct worker
*worker
;
3407 for_each_std_worker_pool(pool
, cpu
) {
3408 WARN_ON_ONCE(cpu
!= smp_processor_id());
3410 mutex_lock(&pool
->assoc_mutex
);
3411 spin_lock_irq(&pool
->lock
);
3414 * We've claimed all manager positions. Make all workers
3415 * unbound and set DISASSOCIATED. Before this, all workers
3416 * except for the ones which are still executing works from
3417 * before the last CPU down must be on the cpu. After
3418 * this, they may become diasporas.
3420 list_for_each_entry(worker
, &pool
->idle_list
, entry
)
3421 worker
->flags
|= WORKER_UNBOUND
;
3423 for_each_busy_worker(worker
, i
, pool
)
3424 worker
->flags
|= WORKER_UNBOUND
;
3426 pool
->flags
|= POOL_DISASSOCIATED
;
3428 spin_unlock_irq(&pool
->lock
);
3429 mutex_unlock(&pool
->assoc_mutex
);
3433 * Call schedule() so that we cross rq->lock and thus can guarantee
3434 * sched callbacks see the %WORKER_UNBOUND flag. This is necessary
3435 * as scheduler callbacks may be invoked from other cpus.
3440 * Sched callbacks are disabled now. Zap nr_running. After this,
3441 * nr_running stays zero and need_more_worker() and keep_working()
3442 * are always true as long as the worklist is not empty. Pools on
3443 * @cpu now behave as unbound (in terms of concurrency management)
3444 * pools which are served by workers tied to the CPU.
3446 * On return from this function, the current worker would trigger
3447 * unbound chain execution of pending work items if other workers
3450 for_each_std_worker_pool(pool
, cpu
)
3451 atomic_set(&pool
->nr_running
, 0);
3455 * Workqueues should be brought up before normal priority CPU notifiers.
3456 * This will be registered high priority CPU notifier.
3458 static int __cpuinit
workqueue_cpu_up_callback(struct notifier_block
*nfb
,
3459 unsigned long action
,
3462 int cpu
= (unsigned long)hcpu
;
3463 struct worker_pool
*pool
;
3465 switch (action
& ~CPU_TASKS_FROZEN
) {
3466 case CPU_UP_PREPARE
:
3467 for_each_std_worker_pool(pool
, cpu
) {
3468 struct worker
*worker
;
3470 if (pool
->nr_workers
)
3473 worker
= create_worker(pool
);
3477 spin_lock_irq(&pool
->lock
);
3478 start_worker(worker
);
3479 spin_unlock_irq(&pool
->lock
);
3483 case CPU_DOWN_FAILED
:
3485 for_each_std_worker_pool(pool
, cpu
) {
3486 mutex_lock(&pool
->assoc_mutex
);
3487 spin_lock_irq(&pool
->lock
);
3489 pool
->flags
&= ~POOL_DISASSOCIATED
;
3490 rebind_workers(pool
);
3492 spin_unlock_irq(&pool
->lock
);
3493 mutex_unlock(&pool
->assoc_mutex
);
3501 * Workqueues should be brought down after normal priority CPU notifiers.
3502 * This will be registered as low priority CPU notifier.
3504 static int __cpuinit
workqueue_cpu_down_callback(struct notifier_block
*nfb
,
3505 unsigned long action
,
3508 int cpu
= (unsigned long)hcpu
;
3509 struct work_struct unbind_work
;
3511 switch (action
& ~CPU_TASKS_FROZEN
) {
3512 case CPU_DOWN_PREPARE
:
3513 /* unbinding should happen on the local CPU */
3514 INIT_WORK_ONSTACK(&unbind_work
, wq_unbind_fn
);
3515 queue_work_on(cpu
, system_highpri_wq
, &unbind_work
);
3516 flush_work(&unbind_work
);
3524 struct work_for_cpu
{
3525 struct work_struct work
;
3531 static void work_for_cpu_fn(struct work_struct
*work
)
3533 struct work_for_cpu
*wfc
= container_of(work
, struct work_for_cpu
, work
);
3535 wfc
->ret
= wfc
->fn(wfc
->arg
);
3539 * work_on_cpu - run a function in user context on a particular cpu
3540 * @cpu: the cpu to run on
3541 * @fn: the function to run
3542 * @arg: the function arg
3544 * This will return the value @fn returns.
3545 * It is up to the caller to ensure that the cpu doesn't go offline.
3546 * The caller must not hold any locks which would prevent @fn from completing.
3548 long work_on_cpu(int cpu
, long (*fn
)(void *), void *arg
)
3550 struct work_for_cpu wfc
= { .fn
= fn
, .arg
= arg
};
3552 INIT_WORK_ONSTACK(&wfc
.work
, work_for_cpu_fn
);
3553 schedule_work_on(cpu
, &wfc
.work
);
3554 flush_work(&wfc
.work
);
3557 EXPORT_SYMBOL_GPL(work_on_cpu
);
3558 #endif /* CONFIG_SMP */
3560 #ifdef CONFIG_FREEZER
3563 * freeze_workqueues_begin - begin freezing workqueues
3565 * Start freezing workqueues. After this function returns, all freezable
3566 * workqueues will queue new works to their frozen_works list instead of
3570 * Grabs and releases workqueue_lock and pool->lock's.
3572 void freeze_workqueues_begin(void)
3574 struct worker_pool
*pool
;
3575 struct workqueue_struct
*wq
;
3576 struct pool_workqueue
*pwq
;
3579 spin_lock_irq(&workqueue_lock
);
3581 WARN_ON_ONCE(workqueue_freezing
);
3582 workqueue_freezing
= true;
3585 for_each_pool(pool
, id
) {
3586 spin_lock(&pool
->lock
);
3587 WARN_ON_ONCE(pool
->flags
& POOL_FREEZING
);
3588 pool
->flags
|= POOL_FREEZING
;
3589 spin_unlock(&pool
->lock
);
3592 /* suppress further executions by setting max_active to zero */
3593 list_for_each_entry(wq
, &workqueues
, list
) {
3594 if (!(wq
->flags
& WQ_FREEZABLE
))
3597 for_each_pwq(pwq
, wq
) {
3598 spin_lock(&pwq
->pool
->lock
);
3599 pwq
->max_active
= 0;
3600 spin_unlock(&pwq
->pool
->lock
);
3604 spin_unlock_irq(&workqueue_lock
);
3608 * freeze_workqueues_busy - are freezable workqueues still busy?
3610 * Check whether freezing is complete. This function must be called
3611 * between freeze_workqueues_begin() and thaw_workqueues().
3614 * Grabs and releases workqueue_lock.
3617 * %true if some freezable workqueues are still busy. %false if freezing
3620 bool freeze_workqueues_busy(void)
3623 struct workqueue_struct
*wq
;
3624 struct pool_workqueue
*pwq
;
3626 spin_lock_irq(&workqueue_lock
);
3628 WARN_ON_ONCE(!workqueue_freezing
);
3630 list_for_each_entry(wq
, &workqueues
, list
) {
3631 if (!(wq
->flags
& WQ_FREEZABLE
))
3634 * nr_active is monotonically decreasing. It's safe
3635 * to peek without lock.
3637 for_each_pwq(pwq
, wq
) {
3638 WARN_ON_ONCE(pwq
->nr_active
< 0);
3639 if (pwq
->nr_active
) {
3646 spin_unlock_irq(&workqueue_lock
);
3651 * thaw_workqueues - thaw workqueues
3653 * Thaw workqueues. Normal queueing is restored and all collected
3654 * frozen works are transferred to their respective pool worklists.
3657 * Grabs and releases workqueue_lock and pool->lock's.
3659 void thaw_workqueues(void)
3661 struct workqueue_struct
*wq
;
3662 struct pool_workqueue
*pwq
;
3663 struct worker_pool
*pool
;
3666 spin_lock_irq(&workqueue_lock
);
3668 if (!workqueue_freezing
)
3671 /* clear FREEZING */
3672 for_each_pool(pool
, id
) {
3673 spin_lock(&pool
->lock
);
3674 WARN_ON_ONCE(!(pool
->flags
& POOL_FREEZING
));
3675 pool
->flags
&= ~POOL_FREEZING
;
3676 spin_unlock(&pool
->lock
);
3679 /* restore max_active and repopulate worklist */
3680 list_for_each_entry(wq
, &workqueues
, list
) {
3681 if (!(wq
->flags
& WQ_FREEZABLE
))
3684 for_each_pwq(pwq
, wq
) {
3685 spin_lock(&pwq
->pool
->lock
);
3686 pwq_set_max_active(pwq
, wq
->saved_max_active
);
3687 spin_unlock(&pwq
->pool
->lock
);
3692 for_each_pool(pool
, id
) {
3693 spin_lock(&pool
->lock
);
3694 wake_up_worker(pool
);
3695 spin_unlock(&pool
->lock
);
3698 workqueue_freezing
= false;
3700 spin_unlock_irq(&workqueue_lock
);
3702 #endif /* CONFIG_FREEZER */
3704 static int __init
init_workqueues(void)
3708 /* make sure we have enough bits for OFFQ pool ID */
3709 BUILD_BUG_ON((1LU << (BITS_PER_LONG
- WORK_OFFQ_POOL_SHIFT
)) <
3710 WORK_CPU_END
* NR_STD_WORKER_POOLS
);
3712 WARN_ON(__alignof__(struct pool_workqueue
) < __alignof__(long long));
3714 pwq_cache
= KMEM_CACHE(pool_workqueue
, SLAB_PANIC
);
3716 cpu_notifier(workqueue_cpu_up_callback
, CPU_PRI_WORKQUEUE_UP
);
3717 hotcpu_notifier(workqueue_cpu_down_callback
, CPU_PRI_WORKQUEUE_DOWN
);
3719 /* initialize CPU pools */
3720 for_each_wq_cpu(cpu
) {
3721 struct worker_pool
*pool
;
3723 for_each_std_worker_pool(pool
, cpu
) {
3724 spin_lock_init(&pool
->lock
);
3726 pool
->flags
|= POOL_DISASSOCIATED
;
3727 INIT_LIST_HEAD(&pool
->worklist
);
3728 INIT_LIST_HEAD(&pool
->idle_list
);
3729 hash_init(pool
->busy_hash
);
3731 init_timer_deferrable(&pool
->idle_timer
);
3732 pool
->idle_timer
.function
= idle_worker_timeout
;
3733 pool
->idle_timer
.data
= (unsigned long)pool
;
3735 setup_timer(&pool
->mayday_timer
, pool_mayday_timeout
,
3736 (unsigned long)pool
);
3738 mutex_init(&pool
->assoc_mutex
);
3739 ida_init(&pool
->worker_ida
);
3742 BUG_ON(worker_pool_assign_id(pool
));
3746 /* create the initial worker */
3747 for_each_online_wq_cpu(cpu
) {
3748 struct worker_pool
*pool
;
3750 for_each_std_worker_pool(pool
, cpu
) {
3751 struct worker
*worker
;
3753 if (cpu
!= WORK_CPU_UNBOUND
)
3754 pool
->flags
&= ~POOL_DISASSOCIATED
;
3756 worker
= create_worker(pool
);
3758 spin_lock_irq(&pool
->lock
);
3759 start_worker(worker
);
3760 spin_unlock_irq(&pool
->lock
);
3764 system_wq
= alloc_workqueue("events", 0, 0);
3765 system_highpri_wq
= alloc_workqueue("events_highpri", WQ_HIGHPRI
, 0);
3766 system_long_wq
= alloc_workqueue("events_long", 0, 0);
3767 system_unbound_wq
= alloc_workqueue("events_unbound", WQ_UNBOUND
,
3768 WQ_UNBOUND_MAX_ACTIVE
);
3769 system_freezable_wq
= alloc_workqueue("events_freezable",
3771 BUG_ON(!system_wq
|| !system_highpri_wq
|| !system_long_wq
||
3772 !system_unbound_wq
|| !system_freezable_wq
);
3775 early_initcall(init_workqueues
);