xref: /linux-6.15/kernel/workqueue.c (revision 7a4e344c)
11da177e4SLinus Torvalds /*
2c54fce6eSTejun Heo  * kernel/workqueue.c - generic async execution with shared worker pool
31da177e4SLinus Torvalds  *
4c54fce6eSTejun Heo  * Copyright (C) 2002		Ingo Molnar
51da177e4SLinus Torvalds  *
61da177e4SLinus Torvalds  *   Derived from the taskqueue/keventd code by:
71da177e4SLinus Torvalds  *     David Woodhouse <[email protected]>
8e1f8e874SFrancois Cami  *     Andrew Morton
91da177e4SLinus Torvalds  *     Kai Petzke <[email protected]>
101da177e4SLinus Torvalds  *     Theodore Ts'o <[email protected]>
1189ada679SChristoph Lameter  *
12cde53535SChristoph Lameter  * Made to use alloc_percpu by Christoph Lameter.
13c54fce6eSTejun Heo  *
14c54fce6eSTejun Heo  * Copyright (C) 2010		SUSE Linux Products GmbH
15c54fce6eSTejun Heo  * Copyright (C) 2010		Tejun Heo <[email protected]>
16c54fce6eSTejun Heo  *
17c54fce6eSTejun Heo  * This is the generic async execution mechanism.  Work items as are
18c54fce6eSTejun Heo  * executed in process context.  The worker pool is shared and
19c54fce6eSTejun Heo  * automatically managed.  There is one worker pool for each CPU and
20c54fce6eSTejun Heo  * one extra for works which are better served by workers which are
21c54fce6eSTejun Heo  * not bound to any specific CPU.
22c54fce6eSTejun Heo  *
23c54fce6eSTejun Heo  * Please read Documentation/workqueue.txt for details.
241da177e4SLinus Torvalds  */
251da177e4SLinus Torvalds 
269984de1aSPaul Gortmaker #include <linux/export.h>
271da177e4SLinus Torvalds #include <linux/kernel.h>
281da177e4SLinus Torvalds #include <linux/sched.h>
291da177e4SLinus Torvalds #include <linux/init.h>
301da177e4SLinus Torvalds #include <linux/signal.h>
311da177e4SLinus Torvalds #include <linux/completion.h>
321da177e4SLinus Torvalds #include <linux/workqueue.h>
331da177e4SLinus Torvalds #include <linux/slab.h>
341da177e4SLinus Torvalds #include <linux/cpu.h>
351da177e4SLinus Torvalds #include <linux/notifier.h>
361da177e4SLinus Torvalds #include <linux/kthread.h>
371fa44ecaSJames Bottomley #include <linux/hardirq.h>
3846934023SChristoph Lameter #include <linux/mempolicy.h>
39341a5958SRafael J. Wysocki #include <linux/freezer.h>
40d5abe669SPeter Zijlstra #include <linux/kallsyms.h>
41d5abe669SPeter Zijlstra #include <linux/debug_locks.h>
424e6045f1SJohannes Berg #include <linux/lockdep.h>
43c34056a3STejun Heo #include <linux/idr.h>
4442f8570fSSasha Levin #include <linux/hashtable.h>
4576af4d93STejun Heo #include <linux/rculist.h>
46e22bee78STejun Heo 
47ea138446STejun Heo #include "workqueue_internal.h"
481da177e4SLinus Torvalds 
49c8e55f36STejun Heo enum {
50bc2ae0f5STejun Heo 	/*
5124647570STejun Heo 	 * worker_pool flags
52bc2ae0f5STejun Heo 	 *
5324647570STejun Heo 	 * A bound pool is either associated or disassociated with its CPU.
54bc2ae0f5STejun Heo 	 * While associated (!DISASSOCIATED), all workers are bound to the
55bc2ae0f5STejun Heo 	 * CPU and none has %WORKER_UNBOUND set and concurrency management
56bc2ae0f5STejun Heo 	 * is in effect.
57bc2ae0f5STejun Heo 	 *
58bc2ae0f5STejun Heo 	 * While DISASSOCIATED, the cpu may be offline and all workers have
59bc2ae0f5STejun Heo 	 * %WORKER_UNBOUND set and concurrency management disabled, and may
6024647570STejun Heo 	 * be executing on any CPU.  The pool behaves as an unbound one.
61bc2ae0f5STejun Heo 	 *
62bc2ae0f5STejun Heo 	 * Note that DISASSOCIATED can be flipped only while holding
6324647570STejun Heo 	 * assoc_mutex to avoid changing binding state while
6424647570STejun Heo 	 * create_worker() is in progress.
65bc2ae0f5STejun Heo 	 */
6611ebea50STejun Heo 	POOL_MANAGE_WORKERS	= 1 << 0,	/* need to manage workers */
6724647570STejun Heo 	POOL_DISASSOCIATED	= 1 << 2,	/* cpu can't serve workers */
6835b6bb63STejun Heo 	POOL_FREEZING		= 1 << 3,	/* freeze in progress */
69db7bccf4STejun Heo 
70c8e55f36STejun Heo 	/* worker flags */
71c8e55f36STejun Heo 	WORKER_STARTED		= 1 << 0,	/* started */
72c8e55f36STejun Heo 	WORKER_DIE		= 1 << 1,	/* die die die */
73c8e55f36STejun Heo 	WORKER_IDLE		= 1 << 2,	/* is idle */
74e22bee78STejun Heo 	WORKER_PREP		= 1 << 3,	/* preparing to run works */
75fb0e7bebSTejun Heo 	WORKER_CPU_INTENSIVE	= 1 << 6,	/* cpu intensive */
76f3421797STejun Heo 	WORKER_UNBOUND		= 1 << 7,	/* worker is unbound */
77e22bee78STejun Heo 
785f7dabfdSLai Jiangshan 	WORKER_NOT_RUNNING	= WORKER_PREP | WORKER_UNBOUND |
79403c821dSTejun Heo 				  WORKER_CPU_INTENSIVE,
80db7bccf4STejun Heo 
81e34cdddbSTejun Heo 	NR_STD_WORKER_POOLS	= 2,		/* # standard pools per cpu */
824ce62e9eSTejun Heo 
83c8e55f36STejun Heo 	BUSY_WORKER_HASH_ORDER	= 6,		/* 64 pointers */
84db7bccf4STejun Heo 
85e22bee78STejun Heo 	MAX_IDLE_WORKERS_RATIO	= 4,		/* 1/4 of busy can be idle */
86e22bee78STejun Heo 	IDLE_WORKER_TIMEOUT	= 300 * HZ,	/* keep idle ones for 5 mins */
87e22bee78STejun Heo 
883233cdbdSTejun Heo 	MAYDAY_INITIAL_TIMEOUT  = HZ / 100 >= 2 ? HZ / 100 : 2,
893233cdbdSTejun Heo 						/* call for help after 10ms
903233cdbdSTejun Heo 						   (min two ticks) */
91e22bee78STejun Heo 	MAYDAY_INTERVAL		= HZ / 10,	/* and then every 100ms */
92e22bee78STejun Heo 	CREATE_COOLDOWN		= HZ,		/* time to breath after fail */
931da177e4SLinus Torvalds 
941da177e4SLinus Torvalds 	/*
95e22bee78STejun Heo 	 * Rescue workers are used only on emergencies and shared by
96e22bee78STejun Heo 	 * all cpus.  Give -20.
97e22bee78STejun Heo 	 */
98e22bee78STejun Heo 	RESCUER_NICE_LEVEL	= -20,
993270476aSTejun Heo 	HIGHPRI_NICE_LEVEL	= -20,
100c8e55f36STejun Heo };
101c8e55f36STejun Heo 
1021da177e4SLinus Torvalds /*
1034690c4abSTejun Heo  * Structure fields follow one of the following exclusion rules.
1044690c4abSTejun Heo  *
105e41e704bSTejun Heo  * I: Modifiable by initialization/destruction paths and read-only for
106e41e704bSTejun Heo  *    everyone else.
1074690c4abSTejun Heo  *
108e22bee78STejun Heo  * P: Preemption protected.  Disabling preemption is enough and should
109e22bee78STejun Heo  *    only be modified and accessed from the local cpu.
110e22bee78STejun Heo  *
111d565ed63STejun Heo  * L: pool->lock protected.  Access with pool->lock held.
1124690c4abSTejun Heo  *
113d565ed63STejun Heo  * X: During normal operation, modification requires pool->lock and should
114d565ed63STejun Heo  *    be done only from local cpu.  Either disabling preemption on local
115d565ed63STejun Heo  *    cpu or grabbing pool->lock is enough for read access.  If
116d565ed63STejun Heo  *    POOL_DISASSOCIATED is set, it's identical to L.
117e22bee78STejun Heo  *
11873f53c4aSTejun Heo  * F: wq->flush_mutex protected.
11973f53c4aSTejun Heo  *
1204690c4abSTejun Heo  * W: workqueue_lock protected.
12176af4d93STejun Heo  *
12276af4d93STejun Heo  * R: workqueue_lock protected for writes.  Sched-RCU protected for reads.
1234690c4abSTejun Heo  */
1244690c4abSTejun Heo 
1252eaebdb3STejun Heo /* struct worker is defined in workqueue_internal.h */
126c34056a3STejun Heo 
127bd7bdd43STejun Heo struct worker_pool {
128d565ed63STejun Heo 	spinlock_t		lock;		/* the pool lock */
129d84ff051STejun Heo 	int			cpu;		/* I: the associated cpu */
1309daf9e67STejun Heo 	int			id;		/* I: pool ID */
13111ebea50STejun Heo 	unsigned int		flags;		/* X: flags */
132bd7bdd43STejun Heo 
133bd7bdd43STejun Heo 	struct list_head	worklist;	/* L: list of pending works */
134bd7bdd43STejun Heo 	int			nr_workers;	/* L: total number of workers */
135ea1abd61SLai Jiangshan 
136ea1abd61SLai Jiangshan 	/* nr_idle includes the ones off idle_list for rebinding */
137bd7bdd43STejun Heo 	int			nr_idle;	/* L: currently idle ones */
138bd7bdd43STejun Heo 
139bd7bdd43STejun Heo 	struct list_head	idle_list;	/* X: list of idle workers */
140bd7bdd43STejun Heo 	struct timer_list	idle_timer;	/* L: worker idle timeout */
141bd7bdd43STejun Heo 	struct timer_list	mayday_timer;	/* L: SOS timer for workers */
142bd7bdd43STejun Heo 
143c9e7cf27STejun Heo 	/* workers are chained either in busy_hash or idle_list */
144c9e7cf27STejun Heo 	DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
145c9e7cf27STejun Heo 						/* L: hash of busy workers */
146c9e7cf27STejun Heo 
14734a06bd6STejun Heo 	struct mutex		manager_arb;	/* manager arbitration */
14824647570STejun Heo 	struct mutex		assoc_mutex;	/* protect POOL_DISASSOCIATED */
149bd7bdd43STejun Heo 	struct ida		worker_ida;	/* L: for worker IDs */
150e19e397aSTejun Heo 
151*7a4e344cSTejun Heo 	struct workqueue_attrs	*attrs;		/* I: worker attributes */
152*7a4e344cSTejun Heo 
153e19e397aSTejun Heo 	/*
154e19e397aSTejun Heo 	 * The current concurrency level.  As it's likely to be accessed
155e19e397aSTejun Heo 	 * from other CPUs during try_to_wake_up(), put it in a separate
156e19e397aSTejun Heo 	 * cacheline.
157e19e397aSTejun Heo 	 */
158e19e397aSTejun Heo 	atomic_t		nr_running ____cacheline_aligned_in_smp;
1598b03ae3cSTejun Heo } ____cacheline_aligned_in_smp;
1608b03ae3cSTejun Heo 
1618b03ae3cSTejun Heo /*
162112202d9STejun Heo  * The per-pool workqueue.  While queued, the lower WORK_STRUCT_FLAG_BITS
163112202d9STejun Heo  * of work_struct->data are used for flags and the remaining high bits
164112202d9STejun Heo  * point to the pwq; thus, pwqs need to be aligned at two's power of the
165112202d9STejun Heo  * number of flag bits.
1661da177e4SLinus Torvalds  */
167112202d9STejun Heo struct pool_workqueue {
168bd7bdd43STejun Heo 	struct worker_pool	*pool;		/* I: the associated pool */
1694690c4abSTejun Heo 	struct workqueue_struct *wq;		/* I: the owning workqueue */
17073f53c4aSTejun Heo 	int			work_color;	/* L: current color */
17173f53c4aSTejun Heo 	int			flush_color;	/* L: flushing color */
17273f53c4aSTejun Heo 	int			nr_in_flight[WORK_NR_COLORS];
17373f53c4aSTejun Heo 						/* L: nr of in_flight works */
1741e19ffc6STejun Heo 	int			nr_active;	/* L: nr of active works */
175a0a1a5fdSTejun Heo 	int			max_active;	/* L: max active works */
1761e19ffc6STejun Heo 	struct list_head	delayed_works;	/* L: delayed works */
17776af4d93STejun Heo 	struct list_head	pwqs_node;	/* R: node on wq->pwqs */
178493a1724STejun Heo 	struct list_head	mayday_node;	/* W: node on wq->maydays */
179e904e6c2STejun Heo } __aligned(1 << WORK_STRUCT_FLAG_BITS);
1801da177e4SLinus Torvalds 
1811da177e4SLinus Torvalds /*
18273f53c4aSTejun Heo  * Structure used to wait for workqueue flush.
18373f53c4aSTejun Heo  */
18473f53c4aSTejun Heo struct wq_flusher {
18573f53c4aSTejun Heo 	struct list_head	list;		/* F: list of flushers */
18673f53c4aSTejun Heo 	int			flush_color;	/* F: flush color waiting for */
18773f53c4aSTejun Heo 	struct completion	done;		/* flush completion */
18873f53c4aSTejun Heo };
1891da177e4SLinus Torvalds 
19073f53c4aSTejun Heo /*
1911da177e4SLinus Torvalds  * The externally visible workqueue abstraction is an array of
1921da177e4SLinus Torvalds  * per-CPU workqueues:
1931da177e4SLinus Torvalds  */
1941da177e4SLinus Torvalds struct workqueue_struct {
1959c5a2ba7STejun Heo 	unsigned int		flags;		/* W: WQ_* flags */
196420c0ddbSTejun Heo 	struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwq's */
19776af4d93STejun Heo 	struct list_head	pwqs;		/* R: all pwqs of this wq */
1984690c4abSTejun Heo 	struct list_head	list;		/* W: list of all workqueues */
19973f53c4aSTejun Heo 
20073f53c4aSTejun Heo 	struct mutex		flush_mutex;	/* protects wq flushing */
20173f53c4aSTejun Heo 	int			work_color;	/* F: current work color */
20273f53c4aSTejun Heo 	int			flush_color;	/* F: current flush color */
203112202d9STejun Heo 	atomic_t		nr_pwqs_to_flush; /* flush in progress */
20473f53c4aSTejun Heo 	struct wq_flusher	*first_flusher;	/* F: first flusher */
20573f53c4aSTejun Heo 	struct list_head	flusher_queue;	/* F: flush waiters */
20673f53c4aSTejun Heo 	struct list_head	flusher_overflow; /* F: flush overflow list */
20773f53c4aSTejun Heo 
208493a1724STejun Heo 	struct list_head	maydays;	/* W: pwqs requesting rescue */
209e22bee78STejun Heo 	struct worker		*rescuer;	/* I: rescue worker */
210e22bee78STejun Heo 
2119c5a2ba7STejun Heo 	int			nr_drainers;	/* W: drain in progress */
212112202d9STejun Heo 	int			saved_max_active; /* W: saved pwq max_active */
2134e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
2144e6045f1SJohannes Berg 	struct lockdep_map	lockdep_map;
2154e6045f1SJohannes Berg #endif
216b196be89STejun Heo 	char			name[];		/* I: workqueue name */
2171da177e4SLinus Torvalds };
2181da177e4SLinus Torvalds 
219e904e6c2STejun Heo static struct kmem_cache *pwq_cache;
220e904e6c2STejun Heo 
221d320c038STejun Heo struct workqueue_struct *system_wq __read_mostly;
222d320c038STejun Heo EXPORT_SYMBOL_GPL(system_wq);
223044c782cSValentin Ilie struct workqueue_struct *system_highpri_wq __read_mostly;
2241aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
225044c782cSValentin Ilie struct workqueue_struct *system_long_wq __read_mostly;
226d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
227044c782cSValentin Ilie struct workqueue_struct *system_unbound_wq __read_mostly;
228f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
229044c782cSValentin Ilie struct workqueue_struct *system_freezable_wq __read_mostly;
23024d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
231d320c038STejun Heo 
23297bd2347STejun Heo #define CREATE_TRACE_POINTS
23397bd2347STejun Heo #include <trace/events/workqueue.h>
23497bd2347STejun Heo 
23576af4d93STejun Heo #define assert_rcu_or_wq_lock()						\
23676af4d93STejun Heo 	rcu_lockdep_assert(rcu_read_lock_sched_held() ||		\
23776af4d93STejun Heo 			   lockdep_is_held(&workqueue_lock),		\
23876af4d93STejun Heo 			   "sched RCU or workqueue lock should be held")
23976af4d93STejun Heo 
24038db41d9STejun Heo #define for_each_std_worker_pool(pool, cpu)				\
241a60dc39cSTejun Heo 	for ((pool) = &std_worker_pools(cpu)[0];			\
242a60dc39cSTejun Heo 	     (pool) < &std_worker_pools(cpu)[NR_STD_WORKER_POOLS]; (pool)++)
2434ce62e9eSTejun Heo 
244b67bfe0dSSasha Levin #define for_each_busy_worker(worker, i, pool)				\
245b67bfe0dSSasha Levin 	hash_for_each(pool->busy_hash, i, worker, hentry)
246db7bccf4STejun Heo 
247706026c2STejun Heo static inline int __next_wq_cpu(int cpu, const struct cpumask *mask,
248f3421797STejun Heo 				unsigned int sw)
249f3421797STejun Heo {
250f3421797STejun Heo 	if (cpu < nr_cpu_ids) {
251f3421797STejun Heo 		if (sw & 1) {
252f3421797STejun Heo 			cpu = cpumask_next(cpu, mask);
253f3421797STejun Heo 			if (cpu < nr_cpu_ids)
254f3421797STejun Heo 				return cpu;
255f3421797STejun Heo 		}
256f3421797STejun Heo 		if (sw & 2)
257f3421797STejun Heo 			return WORK_CPU_UNBOUND;
258f3421797STejun Heo 	}
2596be19588SLai Jiangshan 	return WORK_CPU_END;
260f3421797STejun Heo }
261f3421797STejun Heo 
26209884951STejun Heo /*
26309884951STejun Heo  * CPU iterators
26409884951STejun Heo  *
265706026c2STejun Heo  * An extra cpu number is defined using an invalid cpu number
26609884951STejun Heo  * (WORK_CPU_UNBOUND) to host workqueues which are not bound to any
267706026c2STejun Heo  * specific CPU.  The following iterators are similar to for_each_*_cpu()
268706026c2STejun Heo  * iterators but also considers the unbound CPU.
26909884951STejun Heo  *
270706026c2STejun Heo  * for_each_wq_cpu()		: possible CPUs + WORK_CPU_UNBOUND
271706026c2STejun Heo  * for_each_online_wq_cpu()	: online CPUs + WORK_CPU_UNBOUND
27209884951STejun Heo  */
273706026c2STejun Heo #define for_each_wq_cpu(cpu)						\
274706026c2STejun Heo 	for ((cpu) = __next_wq_cpu(-1, cpu_possible_mask, 3);		\
2756be19588SLai Jiangshan 	     (cpu) < WORK_CPU_END;					\
276706026c2STejun Heo 	     (cpu) = __next_wq_cpu((cpu), cpu_possible_mask, 3))
277f3421797STejun Heo 
278706026c2STejun Heo #define for_each_online_wq_cpu(cpu)					\
279706026c2STejun Heo 	for ((cpu) = __next_wq_cpu(-1, cpu_online_mask, 3);		\
2806be19588SLai Jiangshan 	     (cpu) < WORK_CPU_END;					\
281706026c2STejun Heo 	     (cpu) = __next_wq_cpu((cpu), cpu_online_mask, 3))
282f3421797STejun Heo 
28349e3cf44STejun Heo /**
28417116969STejun Heo  * for_each_pool - iterate through all worker_pools in the system
28517116969STejun Heo  * @pool: iteration cursor
28617116969STejun Heo  * @id: integer used for iteration
287fa1b54e6STejun Heo  *
288fa1b54e6STejun Heo  * This must be called either with workqueue_lock held or sched RCU read
289fa1b54e6STejun Heo  * locked.  If the pool needs to be used beyond the locking in effect, the
290fa1b54e6STejun Heo  * caller is responsible for guaranteeing that the pool stays online.
291fa1b54e6STejun Heo  *
292fa1b54e6STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
293fa1b54e6STejun Heo  * ignored.
29417116969STejun Heo  */
29517116969STejun Heo #define for_each_pool(pool, id)						\
296fa1b54e6STejun Heo 	idr_for_each_entry(&worker_pool_idr, pool, id)			\
297fa1b54e6STejun Heo 		if (({ assert_rcu_or_wq_lock(); false; })) { }		\
298fa1b54e6STejun Heo 		else
29917116969STejun Heo 
30017116969STejun Heo /**
30149e3cf44STejun Heo  * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
30249e3cf44STejun Heo  * @pwq: iteration cursor
30349e3cf44STejun Heo  * @wq: the target workqueue
30476af4d93STejun Heo  *
30576af4d93STejun Heo  * This must be called either with workqueue_lock held or sched RCU read
30676af4d93STejun Heo  * locked.  If the pwq needs to be used beyond the locking in effect, the
30776af4d93STejun Heo  * caller is responsible for guaranteeing that the pwq stays online.
30876af4d93STejun Heo  *
30976af4d93STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
31076af4d93STejun Heo  * ignored.
31149e3cf44STejun Heo  */
31249e3cf44STejun Heo #define for_each_pwq(pwq, wq)						\
31376af4d93STejun Heo 	list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node)		\
31476af4d93STejun Heo 		if (({ assert_rcu_or_wq_lock(); false; })) { }		\
31576af4d93STejun Heo 		else
316f3421797STejun Heo 
317dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
318dc186ad7SThomas Gleixner 
319dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr;
320dc186ad7SThomas Gleixner 
32199777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
32299777288SStanislaw Gruszka {
32399777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
32499777288SStanislaw Gruszka }
32599777288SStanislaw Gruszka 
326dc186ad7SThomas Gleixner /*
327dc186ad7SThomas Gleixner  * fixup_init is called when:
328dc186ad7SThomas Gleixner  * - an active object is initialized
329dc186ad7SThomas Gleixner  */
330dc186ad7SThomas Gleixner static int work_fixup_init(void *addr, enum debug_obj_state state)
331dc186ad7SThomas Gleixner {
332dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
333dc186ad7SThomas Gleixner 
334dc186ad7SThomas Gleixner 	switch (state) {
335dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
336dc186ad7SThomas Gleixner 		cancel_work_sync(work);
337dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
338dc186ad7SThomas Gleixner 		return 1;
339dc186ad7SThomas Gleixner 	default:
340dc186ad7SThomas Gleixner 		return 0;
341dc186ad7SThomas Gleixner 	}
342dc186ad7SThomas Gleixner }
343dc186ad7SThomas Gleixner 
344dc186ad7SThomas Gleixner /*
345dc186ad7SThomas Gleixner  * fixup_activate is called when:
346dc186ad7SThomas Gleixner  * - an active object is activated
347dc186ad7SThomas Gleixner  * - an unknown object is activated (might be a statically initialized object)
348dc186ad7SThomas Gleixner  */
349dc186ad7SThomas Gleixner static int work_fixup_activate(void *addr, enum debug_obj_state state)
350dc186ad7SThomas Gleixner {
351dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
352dc186ad7SThomas Gleixner 
353dc186ad7SThomas Gleixner 	switch (state) {
354dc186ad7SThomas Gleixner 
355dc186ad7SThomas Gleixner 	case ODEBUG_STATE_NOTAVAILABLE:
356dc186ad7SThomas Gleixner 		/*
357dc186ad7SThomas Gleixner 		 * This is not really a fixup. The work struct was
358dc186ad7SThomas Gleixner 		 * statically initialized. We just make sure that it
359dc186ad7SThomas Gleixner 		 * is tracked in the object tracker.
360dc186ad7SThomas Gleixner 		 */
36122df02bbSTejun Heo 		if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
362dc186ad7SThomas Gleixner 			debug_object_init(work, &work_debug_descr);
363dc186ad7SThomas Gleixner 			debug_object_activate(work, &work_debug_descr);
364dc186ad7SThomas Gleixner 			return 0;
365dc186ad7SThomas Gleixner 		}
366dc186ad7SThomas Gleixner 		WARN_ON_ONCE(1);
367dc186ad7SThomas Gleixner 		return 0;
368dc186ad7SThomas Gleixner 
369dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
370dc186ad7SThomas Gleixner 		WARN_ON(1);
371dc186ad7SThomas Gleixner 
372dc186ad7SThomas Gleixner 	default:
373dc186ad7SThomas Gleixner 		return 0;
374dc186ad7SThomas Gleixner 	}
375dc186ad7SThomas Gleixner }
376dc186ad7SThomas Gleixner 
377dc186ad7SThomas Gleixner /*
378dc186ad7SThomas Gleixner  * fixup_free is called when:
379dc186ad7SThomas Gleixner  * - an active object is freed
380dc186ad7SThomas Gleixner  */
381dc186ad7SThomas Gleixner static int work_fixup_free(void *addr, enum debug_obj_state state)
382dc186ad7SThomas Gleixner {
383dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
384dc186ad7SThomas Gleixner 
385dc186ad7SThomas Gleixner 	switch (state) {
386dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
387dc186ad7SThomas Gleixner 		cancel_work_sync(work);
388dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
389dc186ad7SThomas Gleixner 		return 1;
390dc186ad7SThomas Gleixner 	default:
391dc186ad7SThomas Gleixner 		return 0;
392dc186ad7SThomas Gleixner 	}
393dc186ad7SThomas Gleixner }
394dc186ad7SThomas Gleixner 
395dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr = {
396dc186ad7SThomas Gleixner 	.name		= "work_struct",
39799777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
398dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
399dc186ad7SThomas Gleixner 	.fixup_activate	= work_fixup_activate,
400dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
401dc186ad7SThomas Gleixner };
402dc186ad7SThomas Gleixner 
403dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
404dc186ad7SThomas Gleixner {
405dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
406dc186ad7SThomas Gleixner }
407dc186ad7SThomas Gleixner 
408dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
409dc186ad7SThomas Gleixner {
410dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
411dc186ad7SThomas Gleixner }
412dc186ad7SThomas Gleixner 
413dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
414dc186ad7SThomas Gleixner {
415dc186ad7SThomas Gleixner 	if (onstack)
416dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
417dc186ad7SThomas Gleixner 	else
418dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
419dc186ad7SThomas Gleixner }
420dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
421dc186ad7SThomas Gleixner 
422dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
423dc186ad7SThomas Gleixner {
424dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
425dc186ad7SThomas Gleixner }
426dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
427dc186ad7SThomas Gleixner 
428dc186ad7SThomas Gleixner #else
429dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
430dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
431dc186ad7SThomas Gleixner #endif
432dc186ad7SThomas Gleixner 
43395402b38SGautham R Shenoy /* Serializes the accesses to the list of workqueues. */
43495402b38SGautham R Shenoy static DEFINE_SPINLOCK(workqueue_lock);
4351da177e4SLinus Torvalds static LIST_HEAD(workqueues);
436a0a1a5fdSTejun Heo static bool workqueue_freezing;		/* W: have wqs started freezing? */
4371da177e4SLinus Torvalds 
43814441960SOleg Nesterov /*
439e19e397aSTejun Heo  * The CPU and unbound standard worker pools.  The unbound ones have
440e19e397aSTejun Heo  * POOL_DISASSOCIATED set, and their workers have WORKER_UNBOUND set.
44114441960SOleg Nesterov  */
442e19e397aSTejun Heo static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
443a60dc39cSTejun Heo 				     cpu_std_worker_pools);
444a60dc39cSTejun Heo static struct worker_pool unbound_std_worker_pools[NR_STD_WORKER_POOLS];
445f3421797STejun Heo 
446fa1b54e6STejun Heo /*
447fa1b54e6STejun Heo  * idr of all pools.  Modifications are protected by workqueue_lock.  Read
448fa1b54e6STejun Heo  * accesses are protected by sched-RCU protected.
449fa1b54e6STejun Heo  */
4509daf9e67STejun Heo static DEFINE_IDR(worker_pool_idr);
4519daf9e67STejun Heo 
452c34056a3STejun Heo static int worker_thread(void *__worker);
4531da177e4SLinus Torvalds 
454a60dc39cSTejun Heo static struct worker_pool *std_worker_pools(int cpu)
4551da177e4SLinus Torvalds {
456f3421797STejun Heo 	if (cpu != WORK_CPU_UNBOUND)
457a60dc39cSTejun Heo 		return per_cpu(cpu_std_worker_pools, cpu);
458f3421797STejun Heo 	else
459a60dc39cSTejun Heo 		return unbound_std_worker_pools;
4601da177e4SLinus Torvalds }
4611da177e4SLinus Torvalds 
4624e8f0a60STejun Heo static int std_worker_pool_pri(struct worker_pool *pool)
4634e8f0a60STejun Heo {
464a60dc39cSTejun Heo 	return pool - std_worker_pools(pool->cpu);
4654e8f0a60STejun Heo }
4664e8f0a60STejun Heo 
4679daf9e67STejun Heo /* allocate ID and assign it to @pool */
4689daf9e67STejun Heo static int worker_pool_assign_id(struct worker_pool *pool)
4699daf9e67STejun Heo {
4709daf9e67STejun Heo 	int ret;
4719daf9e67STejun Heo 
472fa1b54e6STejun Heo 	do {
473fa1b54e6STejun Heo 		if (!idr_pre_get(&worker_pool_idr, GFP_KERNEL))
474fa1b54e6STejun Heo 			return -ENOMEM;
475fa1b54e6STejun Heo 
476fa1b54e6STejun Heo 		spin_lock_irq(&workqueue_lock);
4779daf9e67STejun Heo 		ret = idr_get_new(&worker_pool_idr, pool, &pool->id);
478fa1b54e6STejun Heo 		spin_unlock_irq(&workqueue_lock);
479fa1b54e6STejun Heo 	} while (ret == -EAGAIN);
4809daf9e67STejun Heo 
4819daf9e67STejun Heo 	return ret;
4829daf9e67STejun Heo }
4839daf9e67STejun Heo 
484d565ed63STejun Heo static struct worker_pool *get_std_worker_pool(int cpu, bool highpri)
485d565ed63STejun Heo {
486a60dc39cSTejun Heo 	struct worker_pool *pools = std_worker_pools(cpu);
487d565ed63STejun Heo 
488a60dc39cSTejun Heo 	return &pools[highpri];
489d565ed63STejun Heo }
490d565ed63STejun Heo 
49176af4d93STejun Heo /**
49276af4d93STejun Heo  * first_pwq - return the first pool_workqueue of the specified workqueue
49376af4d93STejun Heo  * @wq: the target workqueue
49476af4d93STejun Heo  *
49576af4d93STejun Heo  * This must be called either with workqueue_lock held or sched RCU read
49676af4d93STejun Heo  * locked.  If the pwq needs to be used beyond the locking in effect, the
49776af4d93STejun Heo  * caller is responsible for guaranteeing that the pwq stays online.
49876af4d93STejun Heo  */
4997fb98ea7STejun Heo static struct pool_workqueue *first_pwq(struct workqueue_struct *wq)
500a848e3b6SOleg Nesterov {
50176af4d93STejun Heo 	assert_rcu_or_wq_lock();
50276af4d93STejun Heo 	return list_first_or_null_rcu(&wq->pwqs, struct pool_workqueue,
50376af4d93STejun Heo 				      pwqs_node);
504f3421797STejun Heo }
505a848e3b6SOleg Nesterov 
50673f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
50773f53c4aSTejun Heo {
50873f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
50973f53c4aSTejun Heo }
51073f53c4aSTejun Heo 
51173f53c4aSTejun Heo static int get_work_color(struct work_struct *work)
51273f53c4aSTejun Heo {
51373f53c4aSTejun Heo 	return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
51473f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
51573f53c4aSTejun Heo }
51673f53c4aSTejun Heo 
51773f53c4aSTejun Heo static int work_next_color(int color)
51873f53c4aSTejun Heo {
51973f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
520b1f4ec17SOleg Nesterov }
521b1f4ec17SOleg Nesterov 
5224594bf15SDavid Howells /*
523112202d9STejun Heo  * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
524112202d9STejun Heo  * contain the pointer to the queued pwq.  Once execution starts, the flag
5257c3eed5cSTejun Heo  * is cleared and the high bits contain OFFQ flags and pool ID.
5267a22ad75STejun Heo  *
527112202d9STejun Heo  * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
528112202d9STejun Heo  * and clear_work_data() can be used to set the pwq, pool or clear
529bbb68dfaSTejun Heo  * work->data.  These functions should only be called while the work is
530bbb68dfaSTejun Heo  * owned - ie. while the PENDING bit is set.
5317a22ad75STejun Heo  *
532112202d9STejun Heo  * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
5337c3eed5cSTejun Heo  * corresponding to a work.  Pool is available once the work has been
534112202d9STejun Heo  * queued anywhere after initialization until it is sync canceled.  pwq is
5357c3eed5cSTejun Heo  * available only while the work item is queued.
536bbb68dfaSTejun Heo  *
537bbb68dfaSTejun Heo  * %WORK_OFFQ_CANCELING is used to mark a work item which is being
538bbb68dfaSTejun Heo  * canceled.  While being canceled, a work item may have its PENDING set
539bbb68dfaSTejun Heo  * but stay off timer and worklist for arbitrarily long and nobody should
540bbb68dfaSTejun Heo  * try to steal the PENDING bit.
5414594bf15SDavid Howells  */
5427a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
5437a22ad75STejun Heo 				 unsigned long flags)
5447a22ad75STejun Heo {
5456183c009STejun Heo 	WARN_ON_ONCE(!work_pending(work));
5467a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
5477a22ad75STejun Heo }
5487a22ad75STejun Heo 
549112202d9STejun Heo static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
5504690c4abSTejun Heo 			 unsigned long extra_flags)
551365970a1SDavid Howells {
552112202d9STejun Heo 	set_work_data(work, (unsigned long)pwq,
553112202d9STejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
554365970a1SDavid Howells }
555365970a1SDavid Howells 
5564468a00fSLai Jiangshan static void set_work_pool_and_keep_pending(struct work_struct *work,
5574468a00fSLai Jiangshan 					   int pool_id)
5584468a00fSLai Jiangshan {
5594468a00fSLai Jiangshan 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
5604468a00fSLai Jiangshan 		      WORK_STRUCT_PENDING);
5614468a00fSLai Jiangshan }
5624468a00fSLai Jiangshan 
5637c3eed5cSTejun Heo static void set_work_pool_and_clear_pending(struct work_struct *work,
5647c3eed5cSTejun Heo 					    int pool_id)
5654d707b9fSOleg Nesterov {
56623657bb1STejun Heo 	/*
56723657bb1STejun Heo 	 * The following wmb is paired with the implied mb in
56823657bb1STejun Heo 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
56923657bb1STejun Heo 	 * here are visible to and precede any updates by the next PENDING
57023657bb1STejun Heo 	 * owner.
57123657bb1STejun Heo 	 */
57223657bb1STejun Heo 	smp_wmb();
5737c3eed5cSTejun Heo 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
5744d707b9fSOleg Nesterov }
5754d707b9fSOleg Nesterov 
5767a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
577365970a1SDavid Howells {
5787c3eed5cSTejun Heo 	smp_wmb();	/* see set_work_pool_and_clear_pending() */
5797c3eed5cSTejun Heo 	set_work_data(work, WORK_STRUCT_NO_POOL, 0);
5807a22ad75STejun Heo }
5817a22ad75STejun Heo 
582112202d9STejun Heo static struct pool_workqueue *get_work_pwq(struct work_struct *work)
5837a22ad75STejun Heo {
584e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
5857a22ad75STejun Heo 
586112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
587e120153dSTejun Heo 		return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
588e120153dSTejun Heo 	else
589e120153dSTejun Heo 		return NULL;
5907a22ad75STejun Heo }
5917a22ad75STejun Heo 
5927c3eed5cSTejun Heo /**
5937c3eed5cSTejun Heo  * get_work_pool - return the worker_pool a given work was associated with
5947c3eed5cSTejun Heo  * @work: the work item of interest
5957c3eed5cSTejun Heo  *
5967c3eed5cSTejun Heo  * Return the worker_pool @work was last associated with.  %NULL if none.
597fa1b54e6STejun Heo  *
598fa1b54e6STejun Heo  * Pools are created and destroyed under workqueue_lock, and allows read
599fa1b54e6STejun Heo  * access under sched-RCU read lock.  As such, this function should be
600fa1b54e6STejun Heo  * called under workqueue_lock or with preemption disabled.
601fa1b54e6STejun Heo  *
602fa1b54e6STejun Heo  * All fields of the returned pool are accessible as long as the above
603fa1b54e6STejun Heo  * mentioned locking is in effect.  If the returned pool needs to be used
604fa1b54e6STejun Heo  * beyond the critical section, the caller is responsible for ensuring the
605fa1b54e6STejun Heo  * returned pool is and stays online.
6067c3eed5cSTejun Heo  */
6077c3eed5cSTejun Heo static struct worker_pool *get_work_pool(struct work_struct *work)
6087a22ad75STejun Heo {
609e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
6107c3eed5cSTejun Heo 	int pool_id;
6117a22ad75STejun Heo 
612fa1b54e6STejun Heo 	assert_rcu_or_wq_lock();
613fa1b54e6STejun Heo 
614112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
615112202d9STejun Heo 		return ((struct pool_workqueue *)
6167c3eed5cSTejun Heo 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool;
6177a22ad75STejun Heo 
6187c3eed5cSTejun Heo 	pool_id = data >> WORK_OFFQ_POOL_SHIFT;
6197c3eed5cSTejun Heo 	if (pool_id == WORK_OFFQ_POOL_NONE)
6207a22ad75STejun Heo 		return NULL;
6217a22ad75STejun Heo 
622fa1b54e6STejun Heo 	return idr_find(&worker_pool_idr, pool_id);
6237c3eed5cSTejun Heo }
6247c3eed5cSTejun Heo 
6257c3eed5cSTejun Heo /**
6267c3eed5cSTejun Heo  * get_work_pool_id - return the worker pool ID a given work is associated with
6277c3eed5cSTejun Heo  * @work: the work item of interest
6287c3eed5cSTejun Heo  *
6297c3eed5cSTejun Heo  * Return the worker_pool ID @work was last associated with.
6307c3eed5cSTejun Heo  * %WORK_OFFQ_POOL_NONE if none.
6317c3eed5cSTejun Heo  */
6327c3eed5cSTejun Heo static int get_work_pool_id(struct work_struct *work)
6337c3eed5cSTejun Heo {
63454d5b7d0SLai Jiangshan 	unsigned long data = atomic_long_read(&work->data);
6357c3eed5cSTejun Heo 
636112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
637112202d9STejun Heo 		return ((struct pool_workqueue *)
63854d5b7d0SLai Jiangshan 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
63954d5b7d0SLai Jiangshan 
64054d5b7d0SLai Jiangshan 	return data >> WORK_OFFQ_POOL_SHIFT;
6417c3eed5cSTejun Heo }
6427c3eed5cSTejun Heo 
643bbb68dfaSTejun Heo static void mark_work_canceling(struct work_struct *work)
644bbb68dfaSTejun Heo {
6457c3eed5cSTejun Heo 	unsigned long pool_id = get_work_pool_id(work);
646bbb68dfaSTejun Heo 
6477c3eed5cSTejun Heo 	pool_id <<= WORK_OFFQ_POOL_SHIFT;
6487c3eed5cSTejun Heo 	set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
649bbb68dfaSTejun Heo }
650bbb68dfaSTejun Heo 
651bbb68dfaSTejun Heo static bool work_is_canceling(struct work_struct *work)
652bbb68dfaSTejun Heo {
653bbb68dfaSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
654bbb68dfaSTejun Heo 
655112202d9STejun Heo 	return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
656bbb68dfaSTejun Heo }
657bbb68dfaSTejun Heo 
658e22bee78STejun Heo /*
6593270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
6603270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
661d565ed63STejun Heo  * they're being called with pool->lock held.
662e22bee78STejun Heo  */
663e22bee78STejun Heo 
66463d95a91STejun Heo static bool __need_more_worker(struct worker_pool *pool)
665649027d7STejun Heo {
666e19e397aSTejun Heo 	return !atomic_read(&pool->nr_running);
667649027d7STejun Heo }
668649027d7STejun Heo 
669e22bee78STejun Heo /*
670e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
671e22bee78STejun Heo  * running workers.
672974271c4STejun Heo  *
673974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
674706026c2STejun Heo  * function will always return %true for unbound pools as long as the
675974271c4STejun Heo  * worklist isn't empty.
676e22bee78STejun Heo  */
67763d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
678e22bee78STejun Heo {
67963d95a91STejun Heo 	return !list_empty(&pool->worklist) && __need_more_worker(pool);
680e22bee78STejun Heo }
681e22bee78STejun Heo 
682e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
68363d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
684e22bee78STejun Heo {
68563d95a91STejun Heo 	return pool->nr_idle;
686e22bee78STejun Heo }
687e22bee78STejun Heo 
688e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
68963d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
690e22bee78STejun Heo {
691e19e397aSTejun Heo 	return !list_empty(&pool->worklist) &&
692e19e397aSTejun Heo 		atomic_read(&pool->nr_running) <= 1;
693e22bee78STejun Heo }
694e22bee78STejun Heo 
695e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
69663d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
697e22bee78STejun Heo {
69863d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
699e22bee78STejun Heo }
700e22bee78STejun Heo 
701e22bee78STejun Heo /* Do I need to be the manager? */
70263d95a91STejun Heo static bool need_to_manage_workers(struct worker_pool *pool)
703e22bee78STejun Heo {
70463d95a91STejun Heo 	return need_to_create_worker(pool) ||
70511ebea50STejun Heo 		(pool->flags & POOL_MANAGE_WORKERS);
706e22bee78STejun Heo }
707e22bee78STejun Heo 
708e22bee78STejun Heo /* Do we have too many workers and should some go away? */
70963d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
710e22bee78STejun Heo {
71134a06bd6STejun Heo 	bool managing = mutex_is_locked(&pool->manager_arb);
71263d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
71363d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
714e22bee78STejun Heo 
715ea1abd61SLai Jiangshan 	/*
716ea1abd61SLai Jiangshan 	 * nr_idle and idle_list may disagree if idle rebinding is in
717ea1abd61SLai Jiangshan 	 * progress.  Never return %true if idle_list is empty.
718ea1abd61SLai Jiangshan 	 */
719ea1abd61SLai Jiangshan 	if (list_empty(&pool->idle_list))
720ea1abd61SLai Jiangshan 		return false;
721ea1abd61SLai Jiangshan 
722e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
723e22bee78STejun Heo }
724e22bee78STejun Heo 
725e22bee78STejun Heo /*
726e22bee78STejun Heo  * Wake up functions.
727e22bee78STejun Heo  */
728e22bee78STejun Heo 
7297e11629dSTejun Heo /* Return the first worker.  Safe with preemption disabled */
73063d95a91STejun Heo static struct worker *first_worker(struct worker_pool *pool)
7317e11629dSTejun Heo {
73263d95a91STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
7337e11629dSTejun Heo 		return NULL;
7347e11629dSTejun Heo 
73563d95a91STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
7367e11629dSTejun Heo }
7377e11629dSTejun Heo 
7387e11629dSTejun Heo /**
7397e11629dSTejun Heo  * wake_up_worker - wake up an idle worker
74063d95a91STejun Heo  * @pool: worker pool to wake worker from
7417e11629dSTejun Heo  *
74263d95a91STejun Heo  * Wake up the first idle worker of @pool.
7437e11629dSTejun Heo  *
7447e11629dSTejun Heo  * CONTEXT:
745d565ed63STejun Heo  * spin_lock_irq(pool->lock).
7467e11629dSTejun Heo  */
74763d95a91STejun Heo static void wake_up_worker(struct worker_pool *pool)
7487e11629dSTejun Heo {
74963d95a91STejun Heo 	struct worker *worker = first_worker(pool);
7507e11629dSTejun Heo 
7517e11629dSTejun Heo 	if (likely(worker))
7527e11629dSTejun Heo 		wake_up_process(worker->task);
7537e11629dSTejun Heo }
7547e11629dSTejun Heo 
7554690c4abSTejun Heo /**
756e22bee78STejun Heo  * wq_worker_waking_up - a worker is waking up
757e22bee78STejun Heo  * @task: task waking up
758e22bee78STejun Heo  * @cpu: CPU @task is waking up to
759e22bee78STejun Heo  *
760e22bee78STejun Heo  * This function is called during try_to_wake_up() when a worker is
761e22bee78STejun Heo  * being awoken.
762e22bee78STejun Heo  *
763e22bee78STejun Heo  * CONTEXT:
764e22bee78STejun Heo  * spin_lock_irq(rq->lock)
765e22bee78STejun Heo  */
766d84ff051STejun Heo void wq_worker_waking_up(struct task_struct *task, int cpu)
767e22bee78STejun Heo {
768e22bee78STejun Heo 	struct worker *worker = kthread_data(task);
769e22bee78STejun Heo 
77036576000SJoonsoo Kim 	if (!(worker->flags & WORKER_NOT_RUNNING)) {
771ec22ca5eSTejun Heo 		WARN_ON_ONCE(worker->pool->cpu != cpu);
772e19e397aSTejun Heo 		atomic_inc(&worker->pool->nr_running);
773e22bee78STejun Heo 	}
77436576000SJoonsoo Kim }
775e22bee78STejun Heo 
776e22bee78STejun Heo /**
777e22bee78STejun Heo  * wq_worker_sleeping - a worker is going to sleep
778e22bee78STejun Heo  * @task: task going to sleep
779e22bee78STejun Heo  * @cpu: CPU in question, must be the current CPU number
780e22bee78STejun Heo  *
781e22bee78STejun Heo  * This function is called during schedule() when a busy worker is
782e22bee78STejun Heo  * going to sleep.  Worker on the same cpu can be woken up by
783e22bee78STejun Heo  * returning pointer to its task.
784e22bee78STejun Heo  *
785e22bee78STejun Heo  * CONTEXT:
786e22bee78STejun Heo  * spin_lock_irq(rq->lock)
787e22bee78STejun Heo  *
788e22bee78STejun Heo  * RETURNS:
789e22bee78STejun Heo  * Worker task on @cpu to wake up, %NULL if none.
790e22bee78STejun Heo  */
791d84ff051STejun Heo struct task_struct *wq_worker_sleeping(struct task_struct *task, int cpu)
792e22bee78STejun Heo {
793e22bee78STejun Heo 	struct worker *worker = kthread_data(task), *to_wakeup = NULL;
794111c225aSTejun Heo 	struct worker_pool *pool;
795e22bee78STejun Heo 
796111c225aSTejun Heo 	/*
797111c225aSTejun Heo 	 * Rescuers, which may not have all the fields set up like normal
798111c225aSTejun Heo 	 * workers, also reach here, let's not access anything before
799111c225aSTejun Heo 	 * checking NOT_RUNNING.
800111c225aSTejun Heo 	 */
8012d64672eSSteven Rostedt 	if (worker->flags & WORKER_NOT_RUNNING)
802e22bee78STejun Heo 		return NULL;
803e22bee78STejun Heo 
804111c225aSTejun Heo 	pool = worker->pool;
805111c225aSTejun Heo 
806e22bee78STejun Heo 	/* this can only happen on the local cpu */
8076183c009STejun Heo 	if (WARN_ON_ONCE(cpu != raw_smp_processor_id()))
8086183c009STejun Heo 		return NULL;
809e22bee78STejun Heo 
810e22bee78STejun Heo 	/*
811e22bee78STejun Heo 	 * The counterpart of the following dec_and_test, implied mb,
812e22bee78STejun Heo 	 * worklist not empty test sequence is in insert_work().
813e22bee78STejun Heo 	 * Please read comment there.
814e22bee78STejun Heo 	 *
815628c78e7STejun Heo 	 * NOT_RUNNING is clear.  This means that we're bound to and
816628c78e7STejun Heo 	 * running on the local cpu w/ rq lock held and preemption
817628c78e7STejun Heo 	 * disabled, which in turn means that none else could be
818d565ed63STejun Heo 	 * manipulating idle_list, so dereferencing idle_list without pool
819628c78e7STejun Heo 	 * lock is safe.
820e22bee78STejun Heo 	 */
821e19e397aSTejun Heo 	if (atomic_dec_and_test(&pool->nr_running) &&
822e19e397aSTejun Heo 	    !list_empty(&pool->worklist))
82363d95a91STejun Heo 		to_wakeup = first_worker(pool);
824e22bee78STejun Heo 	return to_wakeup ? to_wakeup->task : NULL;
825e22bee78STejun Heo }
826e22bee78STejun Heo 
827e22bee78STejun Heo /**
828e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
829cb444766STejun Heo  * @worker: self
830d302f017STejun Heo  * @flags: flags to set
831d302f017STejun Heo  * @wakeup: wakeup an idle worker if necessary
832d302f017STejun Heo  *
833e22bee78STejun Heo  * Set @flags in @worker->flags and adjust nr_running accordingly.  If
834e22bee78STejun Heo  * nr_running becomes zero and @wakeup is %true, an idle worker is
835e22bee78STejun Heo  * woken up.
836d302f017STejun Heo  *
837cb444766STejun Heo  * CONTEXT:
838d565ed63STejun Heo  * spin_lock_irq(pool->lock)
839d302f017STejun Heo  */
840d302f017STejun Heo static inline void worker_set_flags(struct worker *worker, unsigned int flags,
841d302f017STejun Heo 				    bool wakeup)
842d302f017STejun Heo {
843bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
844e22bee78STejun Heo 
845cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
846cb444766STejun Heo 
847e22bee78STejun Heo 	/*
848e22bee78STejun Heo 	 * If transitioning into NOT_RUNNING, adjust nr_running and
849e22bee78STejun Heo 	 * wake up an idle worker as necessary if requested by
850e22bee78STejun Heo 	 * @wakeup.
851e22bee78STejun Heo 	 */
852e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
853e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
854e22bee78STejun Heo 		if (wakeup) {
855e19e397aSTejun Heo 			if (atomic_dec_and_test(&pool->nr_running) &&
856bd7bdd43STejun Heo 			    !list_empty(&pool->worklist))
85763d95a91STejun Heo 				wake_up_worker(pool);
858e22bee78STejun Heo 		} else
859e19e397aSTejun Heo 			atomic_dec(&pool->nr_running);
860e22bee78STejun Heo 	}
861e22bee78STejun Heo 
862d302f017STejun Heo 	worker->flags |= flags;
863d302f017STejun Heo }
864d302f017STejun Heo 
865d302f017STejun Heo /**
866e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
867cb444766STejun Heo  * @worker: self
868d302f017STejun Heo  * @flags: flags to clear
869d302f017STejun Heo  *
870e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
871d302f017STejun Heo  *
872cb444766STejun Heo  * CONTEXT:
873d565ed63STejun Heo  * spin_lock_irq(pool->lock)
874d302f017STejun Heo  */
875d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
876d302f017STejun Heo {
87763d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
878e22bee78STejun Heo 	unsigned int oflags = worker->flags;
879e22bee78STejun Heo 
880cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
881cb444766STejun Heo 
882d302f017STejun Heo 	worker->flags &= ~flags;
883e22bee78STejun Heo 
88442c025f3STejun Heo 	/*
88542c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
88642c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
88742c025f3STejun Heo 	 * of multiple flags, not a single flag.
88842c025f3STejun Heo 	 */
889e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
890e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
891e19e397aSTejun Heo 			atomic_inc(&pool->nr_running);
892d302f017STejun Heo }
893d302f017STejun Heo 
894d302f017STejun Heo /**
8958cca0eeaSTejun Heo  * find_worker_executing_work - find worker which is executing a work
896c9e7cf27STejun Heo  * @pool: pool of interest
8978cca0eeaSTejun Heo  * @work: work to find worker for
8988cca0eeaSTejun Heo  *
899c9e7cf27STejun Heo  * Find a worker which is executing @work on @pool by searching
900c9e7cf27STejun Heo  * @pool->busy_hash which is keyed by the address of @work.  For a worker
901a2c1c57bSTejun Heo  * to match, its current execution should match the address of @work and
902a2c1c57bSTejun Heo  * its work function.  This is to avoid unwanted dependency between
903a2c1c57bSTejun Heo  * unrelated work executions through a work item being recycled while still
904a2c1c57bSTejun Heo  * being executed.
905a2c1c57bSTejun Heo  *
906a2c1c57bSTejun Heo  * This is a bit tricky.  A work item may be freed once its execution
907a2c1c57bSTejun Heo  * starts and nothing prevents the freed area from being recycled for
908a2c1c57bSTejun Heo  * another work item.  If the same work item address ends up being reused
909a2c1c57bSTejun Heo  * before the original execution finishes, workqueue will identify the
910a2c1c57bSTejun Heo  * recycled work item as currently executing and make it wait until the
911a2c1c57bSTejun Heo  * current execution finishes, introducing an unwanted dependency.
912a2c1c57bSTejun Heo  *
913a2c1c57bSTejun Heo  * This function checks the work item address, work function and workqueue
914a2c1c57bSTejun Heo  * to avoid false positives.  Note that this isn't complete as one may
915a2c1c57bSTejun Heo  * construct a work function which can introduce dependency onto itself
916a2c1c57bSTejun Heo  * through a recycled work item.  Well, if somebody wants to shoot oneself
917a2c1c57bSTejun Heo  * in the foot that badly, there's only so much we can do, and if such
918a2c1c57bSTejun Heo  * deadlock actually occurs, it should be easy to locate the culprit work
919a2c1c57bSTejun Heo  * function.
9208cca0eeaSTejun Heo  *
9218cca0eeaSTejun Heo  * CONTEXT:
922d565ed63STejun Heo  * spin_lock_irq(pool->lock).
9238cca0eeaSTejun Heo  *
9248cca0eeaSTejun Heo  * RETURNS:
9258cca0eeaSTejun Heo  * Pointer to worker which is executing @work if found, NULL
9268cca0eeaSTejun Heo  * otherwise.
9278cca0eeaSTejun Heo  */
928c9e7cf27STejun Heo static struct worker *find_worker_executing_work(struct worker_pool *pool,
9298cca0eeaSTejun Heo 						 struct work_struct *work)
9308cca0eeaSTejun Heo {
93142f8570fSSasha Levin 	struct worker *worker;
93242f8570fSSasha Levin 
933b67bfe0dSSasha Levin 	hash_for_each_possible(pool->busy_hash, worker, hentry,
934a2c1c57bSTejun Heo 			       (unsigned long)work)
935a2c1c57bSTejun Heo 		if (worker->current_work == work &&
936a2c1c57bSTejun Heo 		    worker->current_func == work->func)
93742f8570fSSasha Levin 			return worker;
93842f8570fSSasha Levin 
93942f8570fSSasha Levin 	return NULL;
9408cca0eeaSTejun Heo }
9418cca0eeaSTejun Heo 
9428cca0eeaSTejun Heo /**
943bf4ede01STejun Heo  * move_linked_works - move linked works to a list
944bf4ede01STejun Heo  * @work: start of series of works to be scheduled
945bf4ede01STejun Heo  * @head: target list to append @work to
946bf4ede01STejun Heo  * @nextp: out paramter for nested worklist walking
947bf4ede01STejun Heo  *
948bf4ede01STejun Heo  * Schedule linked works starting from @work to @head.  Work series to
949bf4ede01STejun Heo  * be scheduled starts at @work and includes any consecutive work with
950bf4ede01STejun Heo  * WORK_STRUCT_LINKED set in its predecessor.
951bf4ede01STejun Heo  *
952bf4ede01STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of
953bf4ede01STejun Heo  * the last scheduled work.  This allows move_linked_works() to be
954bf4ede01STejun Heo  * nested inside outer list_for_each_entry_safe().
955bf4ede01STejun Heo  *
956bf4ede01STejun Heo  * CONTEXT:
957d565ed63STejun Heo  * spin_lock_irq(pool->lock).
958bf4ede01STejun Heo  */
959bf4ede01STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
960bf4ede01STejun Heo 			      struct work_struct **nextp)
961bf4ede01STejun Heo {
962bf4ede01STejun Heo 	struct work_struct *n;
963bf4ede01STejun Heo 
964bf4ede01STejun Heo 	/*
965bf4ede01STejun Heo 	 * Linked worklist will always end before the end of the list,
966bf4ede01STejun Heo 	 * use NULL for list head.
967bf4ede01STejun Heo 	 */
968bf4ede01STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
969bf4ede01STejun Heo 		list_move_tail(&work->entry, head);
970bf4ede01STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
971bf4ede01STejun Heo 			break;
972bf4ede01STejun Heo 	}
973bf4ede01STejun Heo 
974bf4ede01STejun Heo 	/*
975bf4ede01STejun Heo 	 * If we're already inside safe list traversal and have moved
976bf4ede01STejun Heo 	 * multiple works to the scheduled queue, the next position
977bf4ede01STejun Heo 	 * needs to be updated.
978bf4ede01STejun Heo 	 */
979bf4ede01STejun Heo 	if (nextp)
980bf4ede01STejun Heo 		*nextp = n;
981bf4ede01STejun Heo }
982bf4ede01STejun Heo 
983112202d9STejun Heo static void pwq_activate_delayed_work(struct work_struct *work)
984bf4ede01STejun Heo {
985112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
986bf4ede01STejun Heo 
987bf4ede01STejun Heo 	trace_workqueue_activate_work(work);
988112202d9STejun Heo 	move_linked_works(work, &pwq->pool->worklist, NULL);
989bf4ede01STejun Heo 	__clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
990112202d9STejun Heo 	pwq->nr_active++;
991bf4ede01STejun Heo }
992bf4ede01STejun Heo 
993112202d9STejun Heo static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
9943aa62497SLai Jiangshan {
995112202d9STejun Heo 	struct work_struct *work = list_first_entry(&pwq->delayed_works,
9963aa62497SLai Jiangshan 						    struct work_struct, entry);
9973aa62497SLai Jiangshan 
998112202d9STejun Heo 	pwq_activate_delayed_work(work);
9993aa62497SLai Jiangshan }
10003aa62497SLai Jiangshan 
1001bf4ede01STejun Heo /**
1002112202d9STejun Heo  * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1003112202d9STejun Heo  * @pwq: pwq of interest
1004bf4ede01STejun Heo  * @color: color of work which left the queue
1005bf4ede01STejun Heo  *
1006bf4ede01STejun Heo  * A work either has completed or is removed from pending queue,
1007112202d9STejun Heo  * decrement nr_in_flight of its pwq and handle workqueue flushing.
1008bf4ede01STejun Heo  *
1009bf4ede01STejun Heo  * CONTEXT:
1010d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1011bf4ede01STejun Heo  */
1012112202d9STejun Heo static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
1013bf4ede01STejun Heo {
1014bf4ede01STejun Heo 	/* ignore uncolored works */
1015bf4ede01STejun Heo 	if (color == WORK_NO_COLOR)
1016bf4ede01STejun Heo 		return;
1017bf4ede01STejun Heo 
1018112202d9STejun Heo 	pwq->nr_in_flight[color]--;
1019bf4ede01STejun Heo 
1020112202d9STejun Heo 	pwq->nr_active--;
1021112202d9STejun Heo 	if (!list_empty(&pwq->delayed_works)) {
1022bf4ede01STejun Heo 		/* one down, submit a delayed one */
1023112202d9STejun Heo 		if (pwq->nr_active < pwq->max_active)
1024112202d9STejun Heo 			pwq_activate_first_delayed(pwq);
1025bf4ede01STejun Heo 	}
1026bf4ede01STejun Heo 
1027bf4ede01STejun Heo 	/* is flush in progress and are we at the flushing tip? */
1028112202d9STejun Heo 	if (likely(pwq->flush_color != color))
1029bf4ede01STejun Heo 		return;
1030bf4ede01STejun Heo 
1031bf4ede01STejun Heo 	/* are there still in-flight works? */
1032112202d9STejun Heo 	if (pwq->nr_in_flight[color])
1033bf4ede01STejun Heo 		return;
1034bf4ede01STejun Heo 
1035112202d9STejun Heo 	/* this pwq is done, clear flush_color */
1036112202d9STejun Heo 	pwq->flush_color = -1;
1037bf4ede01STejun Heo 
1038bf4ede01STejun Heo 	/*
1039112202d9STejun Heo 	 * If this was the last pwq, wake up the first flusher.  It
1040bf4ede01STejun Heo 	 * will handle the rest.
1041bf4ede01STejun Heo 	 */
1042112202d9STejun Heo 	if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1043112202d9STejun Heo 		complete(&pwq->wq->first_flusher->done);
1044bf4ede01STejun Heo }
1045bf4ede01STejun Heo 
104636e227d2STejun Heo /**
1047bbb68dfaSTejun Heo  * try_to_grab_pending - steal work item from worklist and disable irq
104836e227d2STejun Heo  * @work: work item to steal
104936e227d2STejun Heo  * @is_dwork: @work is a delayed_work
1050bbb68dfaSTejun Heo  * @flags: place to store irq state
105136e227d2STejun Heo  *
105236e227d2STejun Heo  * Try to grab PENDING bit of @work.  This function can handle @work in any
105336e227d2STejun Heo  * stable state - idle, on timer or on worklist.  Return values are
105436e227d2STejun Heo  *
105536e227d2STejun Heo  *  1		if @work was pending and we successfully stole PENDING
105636e227d2STejun Heo  *  0		if @work was idle and we claimed PENDING
105736e227d2STejun Heo  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
1058bbb68dfaSTejun Heo  *  -ENOENT	if someone else is canceling @work, this state may persist
1059bbb68dfaSTejun Heo  *		for arbitrarily long
106036e227d2STejun Heo  *
1061bbb68dfaSTejun Heo  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
1062e0aecdd8STejun Heo  * interrupted while holding PENDING and @work off queue, irq must be
1063e0aecdd8STejun Heo  * disabled on entry.  This, combined with delayed_work->timer being
1064e0aecdd8STejun Heo  * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1065bbb68dfaSTejun Heo  *
1066bbb68dfaSTejun Heo  * On successful return, >= 0, irq is disabled and the caller is
1067bbb68dfaSTejun Heo  * responsible for releasing it using local_irq_restore(*@flags).
1068bbb68dfaSTejun Heo  *
1069e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
1070bf4ede01STejun Heo  */
1071bbb68dfaSTejun Heo static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1072bbb68dfaSTejun Heo 			       unsigned long *flags)
1073bf4ede01STejun Heo {
1074d565ed63STejun Heo 	struct worker_pool *pool;
1075112202d9STejun Heo 	struct pool_workqueue *pwq;
1076bf4ede01STejun Heo 
1077bbb68dfaSTejun Heo 	local_irq_save(*flags);
1078bbb68dfaSTejun Heo 
107936e227d2STejun Heo 	/* try to steal the timer if it exists */
108036e227d2STejun Heo 	if (is_dwork) {
108136e227d2STejun Heo 		struct delayed_work *dwork = to_delayed_work(work);
108236e227d2STejun Heo 
1083e0aecdd8STejun Heo 		/*
1084e0aecdd8STejun Heo 		 * dwork->timer is irqsafe.  If del_timer() fails, it's
1085e0aecdd8STejun Heo 		 * guaranteed that the timer is not queued anywhere and not
1086e0aecdd8STejun Heo 		 * running on the local CPU.
1087e0aecdd8STejun Heo 		 */
108836e227d2STejun Heo 		if (likely(del_timer(&dwork->timer)))
108936e227d2STejun Heo 			return 1;
109036e227d2STejun Heo 	}
109136e227d2STejun Heo 
109236e227d2STejun Heo 	/* try to claim PENDING the normal way */
1093bf4ede01STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1094bf4ede01STejun Heo 		return 0;
1095bf4ede01STejun Heo 
1096bf4ede01STejun Heo 	/*
1097bf4ede01STejun Heo 	 * The queueing is in progress, or it is already queued. Try to
1098bf4ede01STejun Heo 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1099bf4ede01STejun Heo 	 */
1100d565ed63STejun Heo 	pool = get_work_pool(work);
1101d565ed63STejun Heo 	if (!pool)
1102bbb68dfaSTejun Heo 		goto fail;
1103bf4ede01STejun Heo 
1104d565ed63STejun Heo 	spin_lock(&pool->lock);
1105bf4ede01STejun Heo 	/*
1106112202d9STejun Heo 	 * work->data is guaranteed to point to pwq only while the work
1107112202d9STejun Heo 	 * item is queued on pwq->wq, and both updating work->data to point
1108112202d9STejun Heo 	 * to pwq on queueing and to pool on dequeueing are done under
1109112202d9STejun Heo 	 * pwq->pool->lock.  This in turn guarantees that, if work->data
1110112202d9STejun Heo 	 * points to pwq which is associated with a locked pool, the work
11110b3dae68SLai Jiangshan 	 * item is currently queued on that pool.
1112bf4ede01STejun Heo 	 */
1113112202d9STejun Heo 	pwq = get_work_pwq(work);
1114112202d9STejun Heo 	if (pwq && pwq->pool == pool) {
1115bf4ede01STejun Heo 		debug_work_deactivate(work);
11163aa62497SLai Jiangshan 
11173aa62497SLai Jiangshan 		/*
111816062836STejun Heo 		 * A delayed work item cannot be grabbed directly because
111916062836STejun Heo 		 * it might have linked NO_COLOR work items which, if left
1120112202d9STejun Heo 		 * on the delayed_list, will confuse pwq->nr_active
112116062836STejun Heo 		 * management later on and cause stall.  Make sure the work
112216062836STejun Heo 		 * item is activated before grabbing.
11233aa62497SLai Jiangshan 		 */
11243aa62497SLai Jiangshan 		if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1125112202d9STejun Heo 			pwq_activate_delayed_work(work);
11263aa62497SLai Jiangshan 
1127bf4ede01STejun Heo 		list_del_init(&work->entry);
1128112202d9STejun Heo 		pwq_dec_nr_in_flight(get_work_pwq(work), get_work_color(work));
112936e227d2STejun Heo 
1130112202d9STejun Heo 		/* work->data points to pwq iff queued, point to pool */
11314468a00fSLai Jiangshan 		set_work_pool_and_keep_pending(work, pool->id);
11324468a00fSLai Jiangshan 
1133d565ed63STejun Heo 		spin_unlock(&pool->lock);
113436e227d2STejun Heo 		return 1;
1135bf4ede01STejun Heo 	}
1136d565ed63STejun Heo 	spin_unlock(&pool->lock);
1137bbb68dfaSTejun Heo fail:
1138bbb68dfaSTejun Heo 	local_irq_restore(*flags);
1139bbb68dfaSTejun Heo 	if (work_is_canceling(work))
1140bbb68dfaSTejun Heo 		return -ENOENT;
1141bbb68dfaSTejun Heo 	cpu_relax();
114236e227d2STejun Heo 	return -EAGAIN;
1143bf4ede01STejun Heo }
1144bf4ede01STejun Heo 
1145bf4ede01STejun Heo /**
1146706026c2STejun Heo  * insert_work - insert a work into a pool
1147112202d9STejun Heo  * @pwq: pwq @work belongs to
11484690c4abSTejun Heo  * @work: work to insert
11494690c4abSTejun Heo  * @head: insertion point
11504690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
11514690c4abSTejun Heo  *
1152112202d9STejun Heo  * Insert @work which belongs to @pwq after @head.  @extra_flags is or'd to
1153706026c2STejun Heo  * work_struct flags.
11544690c4abSTejun Heo  *
11554690c4abSTejun Heo  * CONTEXT:
1156d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1157365970a1SDavid Howells  */
1158112202d9STejun Heo static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1159112202d9STejun Heo 			struct list_head *head, unsigned int extra_flags)
1160b89deed3SOleg Nesterov {
1161112202d9STejun Heo 	struct worker_pool *pool = pwq->pool;
1162e1d8aa9fSFrederic Weisbecker 
11634690c4abSTejun Heo 	/* we own @work, set data and link */
1164112202d9STejun Heo 	set_work_pwq(work, pwq, extra_flags);
11651a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
1166e22bee78STejun Heo 
1167e22bee78STejun Heo 	/*
1168e22bee78STejun Heo 	 * Ensure either worker_sched_deactivated() sees the above
1169e22bee78STejun Heo 	 * list_add_tail() or we see zero nr_running to avoid workers
1170e22bee78STejun Heo 	 * lying around lazily while there are works to be processed.
1171e22bee78STejun Heo 	 */
1172e22bee78STejun Heo 	smp_mb();
1173e22bee78STejun Heo 
117463d95a91STejun Heo 	if (__need_more_worker(pool))
117563d95a91STejun Heo 		wake_up_worker(pool);
1176b89deed3SOleg Nesterov }
1177b89deed3SOleg Nesterov 
1178c8efcc25STejun Heo /*
1179c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
11808d03ecfeSTejun Heo  * same workqueue.
1181c8efcc25STejun Heo  */
1182c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
1183c8efcc25STejun Heo {
1184c8efcc25STejun Heo 	struct worker *worker;
1185c8efcc25STejun Heo 
11868d03ecfeSTejun Heo 	worker = current_wq_worker();
1187c8efcc25STejun Heo 	/*
11888d03ecfeSTejun Heo 	 * Return %true iff I'm a worker execuing a work item on @wq.  If
11898d03ecfeSTejun Heo 	 * I'm @worker, it's safe to dereference it without locking.
1190c8efcc25STejun Heo 	 */
1191112202d9STejun Heo 	return worker && worker->current_pwq->wq == wq;
1192c8efcc25STejun Heo }
1193c8efcc25STejun Heo 
1194d84ff051STejun Heo static void __queue_work(int cpu, struct workqueue_struct *wq,
11951da177e4SLinus Torvalds 			 struct work_struct *work)
11961da177e4SLinus Torvalds {
1197112202d9STejun Heo 	struct pool_workqueue *pwq;
11981e19ffc6STejun Heo 	struct list_head *worklist;
11998a2e8e5dSTejun Heo 	unsigned int work_flags;
1200b75cac93SJoonsoo Kim 	unsigned int req_cpu = cpu;
12018930cabaSTejun Heo 
12028930cabaSTejun Heo 	/*
12038930cabaSTejun Heo 	 * While a work item is PENDING && off queue, a task trying to
12048930cabaSTejun Heo 	 * steal the PENDING will busy-loop waiting for it to either get
12058930cabaSTejun Heo 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
12068930cabaSTejun Heo 	 * happen with IRQ disabled.
12078930cabaSTejun Heo 	 */
12088930cabaSTejun Heo 	WARN_ON_ONCE(!irqs_disabled());
12091da177e4SLinus Torvalds 
1210dc186ad7SThomas Gleixner 	debug_work_activate(work);
12111e19ffc6STejun Heo 
1212c8efcc25STejun Heo 	/* if dying, only works from the same workqueue are allowed */
12139c5a2ba7STejun Heo 	if (unlikely(wq->flags & WQ_DRAINING) &&
1214c8efcc25STejun Heo 	    WARN_ON_ONCE(!is_chained_work(wq)))
1215e41e704bSTejun Heo 		return;
1216e41e704bSTejun Heo 
1217112202d9STejun Heo 	/* determine the pwq to use */
1218c7fc77f7STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
1219c9e7cf27STejun Heo 		struct worker_pool *last_pool;
1220c7fc77f7STejun Heo 
122157469821STejun Heo 		if (cpu == WORK_CPU_UNBOUND)
1222f3421797STejun Heo 			cpu = raw_smp_processor_id();
1223f3421797STejun Heo 
122418aa9effSTejun Heo 		/*
1225dbf2576eSTejun Heo 		 * It's multi cpu.  If @work was previously on a different
1226dbf2576eSTejun Heo 		 * cpu, it might still be running there, in which case the
1227dbf2576eSTejun Heo 		 * work needs to be queued on that cpu to guarantee
1228dbf2576eSTejun Heo 		 * non-reentrancy.
122918aa9effSTejun Heo 		 */
12307fb98ea7STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1231c9e7cf27STejun Heo 		last_pool = get_work_pool(work);
1232dbf2576eSTejun Heo 
1233112202d9STejun Heo 		if (last_pool && last_pool != pwq->pool) {
123418aa9effSTejun Heo 			struct worker *worker;
123518aa9effSTejun Heo 
1236d565ed63STejun Heo 			spin_lock(&last_pool->lock);
123718aa9effSTejun Heo 
1238c9e7cf27STejun Heo 			worker = find_worker_executing_work(last_pool, work);
123918aa9effSTejun Heo 
1240112202d9STejun Heo 			if (worker && worker->current_pwq->wq == wq) {
12417fb98ea7STejun Heo 				pwq = per_cpu_ptr(wq->cpu_pwqs, last_pool->cpu);
12428594fadeSLai Jiangshan 			} else {
124318aa9effSTejun Heo 				/* meh... not running there, queue here */
1244d565ed63STejun Heo 				spin_unlock(&last_pool->lock);
1245112202d9STejun Heo 				spin_lock(&pwq->pool->lock);
124618aa9effSTejun Heo 			}
12478930cabaSTejun Heo 		} else {
1248112202d9STejun Heo 			spin_lock(&pwq->pool->lock);
12498930cabaSTejun Heo 		}
1250f3421797STejun Heo 	} else {
12517fb98ea7STejun Heo 		pwq = first_pwq(wq);
1252112202d9STejun Heo 		spin_lock(&pwq->pool->lock);
1253502ca9d8STejun Heo 	}
1254502ca9d8STejun Heo 
1255112202d9STejun Heo 	/* pwq determined, queue */
1256112202d9STejun Heo 	trace_workqueue_queue_work(req_cpu, pwq, work);
1257502ca9d8STejun Heo 
1258f5b2552bSDan Carpenter 	if (WARN_ON(!list_empty(&work->entry))) {
1259112202d9STejun Heo 		spin_unlock(&pwq->pool->lock);
1260f5b2552bSDan Carpenter 		return;
1261f5b2552bSDan Carpenter 	}
12621e19ffc6STejun Heo 
1263112202d9STejun Heo 	pwq->nr_in_flight[pwq->work_color]++;
1264112202d9STejun Heo 	work_flags = work_color_to_flags(pwq->work_color);
12651e19ffc6STejun Heo 
1266112202d9STejun Heo 	if (likely(pwq->nr_active < pwq->max_active)) {
1267cdadf009STejun Heo 		trace_workqueue_activate_work(work);
1268112202d9STejun Heo 		pwq->nr_active++;
1269112202d9STejun Heo 		worklist = &pwq->pool->worklist;
12708a2e8e5dSTejun Heo 	} else {
12718a2e8e5dSTejun Heo 		work_flags |= WORK_STRUCT_DELAYED;
1272112202d9STejun Heo 		worklist = &pwq->delayed_works;
12738a2e8e5dSTejun Heo 	}
12741e19ffc6STejun Heo 
1275112202d9STejun Heo 	insert_work(pwq, work, worklist, work_flags);
12761e19ffc6STejun Heo 
1277112202d9STejun Heo 	spin_unlock(&pwq->pool->lock);
12781da177e4SLinus Torvalds }
12791da177e4SLinus Torvalds 
12800fcb78c2SRolf Eike Beer /**
1281c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
1282c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
1283c1a220e7SZhang Rui  * @wq: workqueue to use
1284c1a220e7SZhang Rui  * @work: work to queue
1285c1a220e7SZhang Rui  *
1286d4283e93STejun Heo  * Returns %false if @work was already on a queue, %true otherwise.
1287c1a220e7SZhang Rui  *
1288c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
1289c1a220e7SZhang Rui  * can't go away.
1290c1a220e7SZhang Rui  */
1291d4283e93STejun Heo bool queue_work_on(int cpu, struct workqueue_struct *wq,
1292d4283e93STejun Heo 		   struct work_struct *work)
1293c1a220e7SZhang Rui {
1294d4283e93STejun Heo 	bool ret = false;
12958930cabaSTejun Heo 	unsigned long flags;
12968930cabaSTejun Heo 
12978930cabaSTejun Heo 	local_irq_save(flags);
1298c1a220e7SZhang Rui 
129922df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
13004690c4abSTejun Heo 		__queue_work(cpu, wq, work);
1301d4283e93STejun Heo 		ret = true;
1302c1a220e7SZhang Rui 	}
13038930cabaSTejun Heo 
13048930cabaSTejun Heo 	local_irq_restore(flags);
1305c1a220e7SZhang Rui 	return ret;
1306c1a220e7SZhang Rui }
1307c1a220e7SZhang Rui EXPORT_SYMBOL_GPL(queue_work_on);
1308c1a220e7SZhang Rui 
13090a13c00eSTejun Heo /**
13100a13c00eSTejun Heo  * queue_work - queue work on a workqueue
13110a13c00eSTejun Heo  * @wq: workqueue to use
13120a13c00eSTejun Heo  * @work: work to queue
13130a13c00eSTejun Heo  *
1314d4283e93STejun Heo  * Returns %false if @work was already on a queue, %true otherwise.
13150a13c00eSTejun Heo  *
13160a13c00eSTejun Heo  * We queue the work to the CPU on which it was submitted, but if the CPU dies
13170a13c00eSTejun Heo  * it can be processed by another CPU.
13180a13c00eSTejun Heo  */
1319d4283e93STejun Heo bool queue_work(struct workqueue_struct *wq, struct work_struct *work)
13200a13c00eSTejun Heo {
132157469821STejun Heo 	return queue_work_on(WORK_CPU_UNBOUND, wq, work);
13220a13c00eSTejun Heo }
13230a13c00eSTejun Heo EXPORT_SYMBOL_GPL(queue_work);
13240a13c00eSTejun Heo 
1325d8e794dfSTejun Heo void delayed_work_timer_fn(unsigned long __data)
13261da177e4SLinus Torvalds {
132752bad64dSDavid Howells 	struct delayed_work *dwork = (struct delayed_work *)__data;
13281da177e4SLinus Torvalds 
1329e0aecdd8STejun Heo 	/* should have been called from irqsafe timer with irq already off */
133060c057bcSLai Jiangshan 	__queue_work(dwork->cpu, dwork->wq, &dwork->work);
13311da177e4SLinus Torvalds }
13321438ade5SKonstantin Khlebnikov EXPORT_SYMBOL(delayed_work_timer_fn);
13331da177e4SLinus Torvalds 
13347beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
133552bad64dSDavid Howells 				struct delayed_work *dwork, unsigned long delay)
13361da177e4SLinus Torvalds {
13377beb2edfSTejun Heo 	struct timer_list *timer = &dwork->timer;
13387beb2edfSTejun Heo 	struct work_struct *work = &dwork->work;
13391da177e4SLinus Torvalds 
13407beb2edfSTejun Heo 	WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
13417beb2edfSTejun Heo 		     timer->data != (unsigned long)dwork);
1342fc4b514fSTejun Heo 	WARN_ON_ONCE(timer_pending(timer));
1343fc4b514fSTejun Heo 	WARN_ON_ONCE(!list_empty(&work->entry));
13447beb2edfSTejun Heo 
13458852aac2STejun Heo 	/*
13468852aac2STejun Heo 	 * If @delay is 0, queue @dwork->work immediately.  This is for
13478852aac2STejun Heo 	 * both optimization and correctness.  The earliest @timer can
13488852aac2STejun Heo 	 * expire is on the closest next tick and delayed_work users depend
13498852aac2STejun Heo 	 * on that there's no such delay when @delay is 0.
13508852aac2STejun Heo 	 */
13518852aac2STejun Heo 	if (!delay) {
13528852aac2STejun Heo 		__queue_work(cpu, wq, &dwork->work);
13538852aac2STejun Heo 		return;
13548852aac2STejun Heo 	}
13558852aac2STejun Heo 
13567beb2edfSTejun Heo 	timer_stats_timer_set_start_info(&dwork->timer);
13577beb2edfSTejun Heo 
135860c057bcSLai Jiangshan 	dwork->wq = wq;
13591265057fSTejun Heo 	dwork->cpu = cpu;
13607beb2edfSTejun Heo 	timer->expires = jiffies + delay;
13617beb2edfSTejun Heo 
13627beb2edfSTejun Heo 	if (unlikely(cpu != WORK_CPU_UNBOUND))
13637beb2edfSTejun Heo 		add_timer_on(timer, cpu);
13647beb2edfSTejun Heo 	else
13657beb2edfSTejun Heo 		add_timer(timer);
13667beb2edfSTejun Heo }
13671da177e4SLinus Torvalds 
13680fcb78c2SRolf Eike Beer /**
13690fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
13700fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
13710fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1372af9997e4SRandy Dunlap  * @dwork: work to queue
13730fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
13740fcb78c2SRolf Eike Beer  *
1375715f1300STejun Heo  * Returns %false if @work was already on a queue, %true otherwise.  If
1376715f1300STejun Heo  * @delay is zero and @dwork is idle, it will be scheduled for immediate
1377715f1300STejun Heo  * execution.
13780fcb78c2SRolf Eike Beer  */
1379d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
138052bad64dSDavid Howells 			   struct delayed_work *dwork, unsigned long delay)
13817a6bc1cdSVenkatesh Pallipadi {
138252bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
1383d4283e93STejun Heo 	bool ret = false;
13848930cabaSTejun Heo 	unsigned long flags;
13858930cabaSTejun Heo 
13868930cabaSTejun Heo 	/* read the comment in __queue_work() */
13878930cabaSTejun Heo 	local_irq_save(flags);
13887a6bc1cdSVenkatesh Pallipadi 
138922df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
13907beb2edfSTejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
1391d4283e93STejun Heo 		ret = true;
13927a6bc1cdSVenkatesh Pallipadi 	}
13938930cabaSTejun Heo 
13948930cabaSTejun Heo 	local_irq_restore(flags);
13957a6bc1cdSVenkatesh Pallipadi 	return ret;
13967a6bc1cdSVenkatesh Pallipadi }
1397ae90dd5dSDave Jones EXPORT_SYMBOL_GPL(queue_delayed_work_on);
13981da177e4SLinus Torvalds 
1399c8e55f36STejun Heo /**
14000a13c00eSTejun Heo  * queue_delayed_work - queue work on a workqueue after delay
14010a13c00eSTejun Heo  * @wq: workqueue to use
14020a13c00eSTejun Heo  * @dwork: delayable work to queue
14030a13c00eSTejun Heo  * @delay: number of jiffies to wait before queueing
14040a13c00eSTejun Heo  *
1405715f1300STejun Heo  * Equivalent to queue_delayed_work_on() but tries to use the local CPU.
14060a13c00eSTejun Heo  */
1407d4283e93STejun Heo bool queue_delayed_work(struct workqueue_struct *wq,
14080a13c00eSTejun Heo 			struct delayed_work *dwork, unsigned long delay)
14090a13c00eSTejun Heo {
141057469821STejun Heo 	return queue_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
14110a13c00eSTejun Heo }
14120a13c00eSTejun Heo EXPORT_SYMBOL_GPL(queue_delayed_work);
14130a13c00eSTejun Heo 
14140a13c00eSTejun Heo /**
14158376fe22STejun Heo  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
14168376fe22STejun Heo  * @cpu: CPU number to execute work on
14178376fe22STejun Heo  * @wq: workqueue to use
14188376fe22STejun Heo  * @dwork: work to queue
14198376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
14208376fe22STejun Heo  *
14218376fe22STejun Heo  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
14228376fe22STejun Heo  * modify @dwork's timer so that it expires after @delay.  If @delay is
14238376fe22STejun Heo  * zero, @work is guaranteed to be scheduled immediately regardless of its
14248376fe22STejun Heo  * current state.
14258376fe22STejun Heo  *
14268376fe22STejun Heo  * Returns %false if @dwork was idle and queued, %true if @dwork was
14278376fe22STejun Heo  * pending and its timer was modified.
14288376fe22STejun Heo  *
1429e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
14308376fe22STejun Heo  * See try_to_grab_pending() for details.
14318376fe22STejun Heo  */
14328376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
14338376fe22STejun Heo 			 struct delayed_work *dwork, unsigned long delay)
14348376fe22STejun Heo {
14358376fe22STejun Heo 	unsigned long flags;
14368376fe22STejun Heo 	int ret;
14378376fe22STejun Heo 
14388376fe22STejun Heo 	do {
14398376fe22STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
14408376fe22STejun Heo 	} while (unlikely(ret == -EAGAIN));
14418376fe22STejun Heo 
14428376fe22STejun Heo 	if (likely(ret >= 0)) {
14438376fe22STejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
14448376fe22STejun Heo 		local_irq_restore(flags);
14458376fe22STejun Heo 	}
14468376fe22STejun Heo 
14478376fe22STejun Heo 	/* -ENOENT from try_to_grab_pending() becomes %true */
14488376fe22STejun Heo 	return ret;
14498376fe22STejun Heo }
14508376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
14518376fe22STejun Heo 
14528376fe22STejun Heo /**
14538376fe22STejun Heo  * mod_delayed_work - modify delay of or queue a delayed work
14548376fe22STejun Heo  * @wq: workqueue to use
14558376fe22STejun Heo  * @dwork: work to queue
14568376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
14578376fe22STejun Heo  *
14588376fe22STejun Heo  * mod_delayed_work_on() on local CPU.
14598376fe22STejun Heo  */
14608376fe22STejun Heo bool mod_delayed_work(struct workqueue_struct *wq, struct delayed_work *dwork,
14618376fe22STejun Heo 		      unsigned long delay)
14628376fe22STejun Heo {
14638376fe22STejun Heo 	return mod_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
14648376fe22STejun Heo }
14658376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work);
14668376fe22STejun Heo 
14678376fe22STejun Heo /**
1468c8e55f36STejun Heo  * worker_enter_idle - enter idle state
1469c8e55f36STejun Heo  * @worker: worker which is entering idle state
1470c8e55f36STejun Heo  *
1471c8e55f36STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
1472c8e55f36STejun Heo  * necessary.
1473c8e55f36STejun Heo  *
1474c8e55f36STejun Heo  * LOCKING:
1475d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1476c8e55f36STejun Heo  */
1477c8e55f36STejun Heo static void worker_enter_idle(struct worker *worker)
14781da177e4SLinus Torvalds {
1479bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1480c8e55f36STejun Heo 
14816183c009STejun Heo 	if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
14826183c009STejun Heo 	    WARN_ON_ONCE(!list_empty(&worker->entry) &&
14836183c009STejun Heo 			 (worker->hentry.next || worker->hentry.pprev)))
14846183c009STejun Heo 		return;
1485c8e55f36STejun Heo 
1486cb444766STejun Heo 	/* can't use worker_set_flags(), also called from start_worker() */
1487cb444766STejun Heo 	worker->flags |= WORKER_IDLE;
1488bd7bdd43STejun Heo 	pool->nr_idle++;
1489e22bee78STejun Heo 	worker->last_active = jiffies;
1490c8e55f36STejun Heo 
1491c8e55f36STejun Heo 	/* idle_list is LIFO */
1492bd7bdd43STejun Heo 	list_add(&worker->entry, &pool->idle_list);
1493db7bccf4STejun Heo 
149463d95a91STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1495628c78e7STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1496cb444766STejun Heo 
1497544ecf31STejun Heo 	/*
1498706026c2STejun Heo 	 * Sanity check nr_running.  Because wq_unbind_fn() releases
1499d565ed63STejun Heo 	 * pool->lock between setting %WORKER_UNBOUND and zapping
1500628c78e7STejun Heo 	 * nr_running, the warning may trigger spuriously.  Check iff
1501628c78e7STejun Heo 	 * unbind is not in progress.
1502544ecf31STejun Heo 	 */
150324647570STejun Heo 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1504bd7bdd43STejun Heo 		     pool->nr_workers == pool->nr_idle &&
1505e19e397aSTejun Heo 		     atomic_read(&pool->nr_running));
1506c8e55f36STejun Heo }
1507c8e55f36STejun Heo 
1508c8e55f36STejun Heo /**
1509c8e55f36STejun Heo  * worker_leave_idle - leave idle state
1510c8e55f36STejun Heo  * @worker: worker which is leaving idle state
1511c8e55f36STejun Heo  *
1512c8e55f36STejun Heo  * @worker is leaving idle state.  Update stats.
1513c8e55f36STejun Heo  *
1514c8e55f36STejun Heo  * LOCKING:
1515d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1516c8e55f36STejun Heo  */
1517c8e55f36STejun Heo static void worker_leave_idle(struct worker *worker)
1518c8e55f36STejun Heo {
1519bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1520c8e55f36STejun Heo 
15216183c009STejun Heo 	if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
15226183c009STejun Heo 		return;
1523d302f017STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
1524bd7bdd43STejun Heo 	pool->nr_idle--;
1525c8e55f36STejun Heo 	list_del_init(&worker->entry);
1526c8e55f36STejun Heo }
1527c8e55f36STejun Heo 
1528e22bee78STejun Heo /**
1529f36dc67bSLai Jiangshan  * worker_maybe_bind_and_lock - try to bind %current to worker_pool and lock it
1530f36dc67bSLai Jiangshan  * @pool: target worker_pool
1531f36dc67bSLai Jiangshan  *
1532f36dc67bSLai Jiangshan  * Bind %current to the cpu of @pool if it is associated and lock @pool.
1533e22bee78STejun Heo  *
1534e22bee78STejun Heo  * Works which are scheduled while the cpu is online must at least be
1535e22bee78STejun Heo  * scheduled to a worker which is bound to the cpu so that if they are
1536e22bee78STejun Heo  * flushed from cpu callbacks while cpu is going down, they are
1537e22bee78STejun Heo  * guaranteed to execute on the cpu.
1538e22bee78STejun Heo  *
1539f5faa077SLai Jiangshan  * This function is to be used by unbound workers and rescuers to bind
1540e22bee78STejun Heo  * themselves to the target cpu and may race with cpu going down or
1541e22bee78STejun Heo  * coming online.  kthread_bind() can't be used because it may put the
1542e22bee78STejun Heo  * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1543706026c2STejun Heo  * verbatim as it's best effort and blocking and pool may be
1544e22bee78STejun Heo  * [dis]associated in the meantime.
1545e22bee78STejun Heo  *
1546706026c2STejun Heo  * This function tries set_cpus_allowed() and locks pool and verifies the
154724647570STejun Heo  * binding against %POOL_DISASSOCIATED which is set during
1548f2d5a0eeSTejun Heo  * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
1549f2d5a0eeSTejun Heo  * enters idle state or fetches works without dropping lock, it can
1550f2d5a0eeSTejun Heo  * guarantee the scheduling requirement described in the first paragraph.
1551e22bee78STejun Heo  *
1552e22bee78STejun Heo  * CONTEXT:
1553d565ed63STejun Heo  * Might sleep.  Called without any lock but returns with pool->lock
1554e22bee78STejun Heo  * held.
1555e22bee78STejun Heo  *
1556e22bee78STejun Heo  * RETURNS:
1557706026c2STejun Heo  * %true if the associated pool is online (@worker is successfully
1558e22bee78STejun Heo  * bound), %false if offline.
1559e22bee78STejun Heo  */
1560f36dc67bSLai Jiangshan static bool worker_maybe_bind_and_lock(struct worker_pool *pool)
1561d565ed63STejun Heo __acquires(&pool->lock)
1562e22bee78STejun Heo {
1563e22bee78STejun Heo 	while (true) {
1564e22bee78STejun Heo 		/*
1565e22bee78STejun Heo 		 * The following call may fail, succeed or succeed
1566e22bee78STejun Heo 		 * without actually migrating the task to the cpu if
1567e22bee78STejun Heo 		 * it races with cpu hotunplug operation.  Verify
156824647570STejun Heo 		 * against POOL_DISASSOCIATED.
1569e22bee78STejun Heo 		 */
157024647570STejun Heo 		if (!(pool->flags & POOL_DISASSOCIATED))
1571*7a4e344cSTejun Heo 			set_cpus_allowed_ptr(current, pool->attrs->cpumask);
1572e22bee78STejun Heo 
1573d565ed63STejun Heo 		spin_lock_irq(&pool->lock);
157424647570STejun Heo 		if (pool->flags & POOL_DISASSOCIATED)
1575e22bee78STejun Heo 			return false;
1576f5faa077SLai Jiangshan 		if (task_cpu(current) == pool->cpu &&
1577*7a4e344cSTejun Heo 		    cpumask_equal(&current->cpus_allowed, pool->attrs->cpumask))
1578e22bee78STejun Heo 			return true;
1579d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
1580e22bee78STejun Heo 
15815035b20fSTejun Heo 		/*
15825035b20fSTejun Heo 		 * We've raced with CPU hot[un]plug.  Give it a breather
15835035b20fSTejun Heo 		 * and retry migration.  cond_resched() is required here;
15845035b20fSTejun Heo 		 * otherwise, we might deadlock against cpu_stop trying to
15855035b20fSTejun Heo 		 * bring down the CPU on non-preemptive kernel.
15865035b20fSTejun Heo 		 */
1587e22bee78STejun Heo 		cpu_relax();
15885035b20fSTejun Heo 		cond_resched();
1589e22bee78STejun Heo 	}
1590e22bee78STejun Heo }
1591e22bee78STejun Heo 
1592e22bee78STejun Heo /*
1593ea1abd61SLai Jiangshan  * Rebind an idle @worker to its CPU.  worker_thread() will test
15945f7dabfdSLai Jiangshan  * list_empty(@worker->entry) before leaving idle and call this function.
159525511a47STejun Heo  */
159625511a47STejun Heo static void idle_worker_rebind(struct worker *worker)
159725511a47STejun Heo {
15985f7dabfdSLai Jiangshan 	/* CPU may go down again inbetween, clear UNBOUND only on success */
1599f36dc67bSLai Jiangshan 	if (worker_maybe_bind_and_lock(worker->pool))
16005f7dabfdSLai Jiangshan 		worker_clr_flags(worker, WORKER_UNBOUND);
160125511a47STejun Heo 
1602ea1abd61SLai Jiangshan 	/* rebind complete, become available again */
1603ea1abd61SLai Jiangshan 	list_add(&worker->entry, &worker->pool->idle_list);
1604d565ed63STejun Heo 	spin_unlock_irq(&worker->pool->lock);
160525511a47STejun Heo }
160625511a47STejun Heo 
160725511a47STejun Heo /*
160825511a47STejun Heo  * Function for @worker->rebind.work used to rebind unbound busy workers to
1609403c821dSTejun Heo  * the associated cpu which is coming back online.  This is scheduled by
1610403c821dSTejun Heo  * cpu up but can race with other cpu hotplug operations and may be
1611403c821dSTejun Heo  * executed twice without intervening cpu down.
1612e22bee78STejun Heo  */
161325511a47STejun Heo static void busy_worker_rebind_fn(struct work_struct *work)
1614e22bee78STejun Heo {
1615e22bee78STejun Heo 	struct worker *worker = container_of(work, struct worker, rebind_work);
1616e22bee78STejun Heo 
1617f36dc67bSLai Jiangshan 	if (worker_maybe_bind_and_lock(worker->pool))
1618eab6d828SLai Jiangshan 		worker_clr_flags(worker, WORKER_UNBOUND);
1619e22bee78STejun Heo 
1620d565ed63STejun Heo 	spin_unlock_irq(&worker->pool->lock);
1621e22bee78STejun Heo }
1622e22bee78STejun Heo 
162325511a47STejun Heo /**
162494cf58bbSTejun Heo  * rebind_workers - rebind all workers of a pool to the associated CPU
162594cf58bbSTejun Heo  * @pool: pool of interest
162625511a47STejun Heo  *
162794cf58bbSTejun Heo  * @pool->cpu is coming online.  Rebind all workers to the CPU.  Rebinding
162825511a47STejun Heo  * is different for idle and busy ones.
162925511a47STejun Heo  *
1630ea1abd61SLai Jiangshan  * Idle ones will be removed from the idle_list and woken up.  They will
1631ea1abd61SLai Jiangshan  * add themselves back after completing rebind.  This ensures that the
1632ea1abd61SLai Jiangshan  * idle_list doesn't contain any unbound workers when re-bound busy workers
1633ea1abd61SLai Jiangshan  * try to perform local wake-ups for concurrency management.
163425511a47STejun Heo  *
1635ea1abd61SLai Jiangshan  * Busy workers can rebind after they finish their current work items.
1636ea1abd61SLai Jiangshan  * Queueing the rebind work item at the head of the scheduled list is
1637ea1abd61SLai Jiangshan  * enough.  Note that nr_running will be properly bumped as busy workers
1638ea1abd61SLai Jiangshan  * rebind.
163925511a47STejun Heo  *
1640ea1abd61SLai Jiangshan  * On return, all non-manager workers are scheduled for rebind - see
1641ea1abd61SLai Jiangshan  * manage_workers() for the manager special case.  Any idle worker
1642ea1abd61SLai Jiangshan  * including the manager will not appear on @idle_list until rebind is
1643ea1abd61SLai Jiangshan  * complete, making local wake-ups safe.
164425511a47STejun Heo  */
164594cf58bbSTejun Heo static void rebind_workers(struct worker_pool *pool)
164625511a47STejun Heo {
1647ea1abd61SLai Jiangshan 	struct worker *worker, *n;
164825511a47STejun Heo 	int i;
164925511a47STejun Heo 
1650b2eb83d1SLai Jiangshan 	lockdep_assert_held(&pool->assoc_mutex);
1651d565ed63STejun Heo 	lockdep_assert_held(&pool->lock);
165225511a47STejun Heo 
16535f7dabfdSLai Jiangshan 	/* dequeue and kick idle ones */
1654ea1abd61SLai Jiangshan 	list_for_each_entry_safe(worker, n, &pool->idle_list, entry) {
1655ea1abd61SLai Jiangshan 		/*
165694cf58bbSTejun Heo 		 * idle workers should be off @pool->idle_list until rebind
165794cf58bbSTejun Heo 		 * is complete to avoid receiving premature local wake-ups.
1658ea1abd61SLai Jiangshan 		 */
1659ea1abd61SLai Jiangshan 		list_del_init(&worker->entry);
166025511a47STejun Heo 
166125511a47STejun Heo 		/*
166294cf58bbSTejun Heo 		 * worker_thread() will see the above dequeuing and call
166394cf58bbSTejun Heo 		 * idle_worker_rebind().
166425511a47STejun Heo 		 */
166525511a47STejun Heo 		wake_up_process(worker->task);
166625511a47STejun Heo 	}
166725511a47STejun Heo 
1668ea1abd61SLai Jiangshan 	/* rebind busy workers */
1669b67bfe0dSSasha Levin 	for_each_busy_worker(worker, i, pool) {
167025511a47STejun Heo 		struct work_struct *rebind_work = &worker->rebind_work;
1671e2b6a6d5SJoonsoo Kim 		struct workqueue_struct *wq;
167225511a47STejun Heo 
167325511a47STejun Heo 		if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
167425511a47STejun Heo 				     work_data_bits(rebind_work)))
167525511a47STejun Heo 			continue;
167625511a47STejun Heo 
167725511a47STejun Heo 		debug_work_activate(rebind_work);
167890beca5dSTejun Heo 
167990beca5dSTejun Heo 		/*
168094cf58bbSTejun Heo 		 * wq doesn't really matter but let's keep @worker->pool
1681112202d9STejun Heo 		 * and @pwq->pool consistent for sanity.
168290beca5dSTejun Heo 		 */
1683*7a4e344cSTejun Heo 		if (worker->pool->attrs->nice < 0)
1684e2b6a6d5SJoonsoo Kim 			wq = system_highpri_wq;
1685e2b6a6d5SJoonsoo Kim 		else
1686e2b6a6d5SJoonsoo Kim 			wq = system_wq;
1687ec58815aSTejun Heo 
16887fb98ea7STejun Heo 		insert_work(per_cpu_ptr(wq->cpu_pwqs, pool->cpu), rebind_work,
168925511a47STejun Heo 			    worker->scheduled.next,
169025511a47STejun Heo 			    work_color_to_flags(WORK_NO_COLOR));
1691ec58815aSTejun Heo 	}
169225511a47STejun Heo }
169325511a47STejun Heo 
1694c34056a3STejun Heo static struct worker *alloc_worker(void)
1695c34056a3STejun Heo {
1696c34056a3STejun Heo 	struct worker *worker;
1697c34056a3STejun Heo 
1698c34056a3STejun Heo 	worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1699c8e55f36STejun Heo 	if (worker) {
1700c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
1701affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
170225511a47STejun Heo 		INIT_WORK(&worker->rebind_work, busy_worker_rebind_fn);
1703e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
1704e22bee78STejun Heo 		worker->flags = WORKER_PREP;
1705c8e55f36STejun Heo 	}
1706c34056a3STejun Heo 	return worker;
1707c34056a3STejun Heo }
1708c34056a3STejun Heo 
1709c34056a3STejun Heo /**
1710c34056a3STejun Heo  * create_worker - create a new workqueue worker
171163d95a91STejun Heo  * @pool: pool the new worker will belong to
1712c34056a3STejun Heo  *
171363d95a91STejun Heo  * Create a new worker which is bound to @pool.  The returned worker
1714c34056a3STejun Heo  * can be started by calling start_worker() or destroyed using
1715c34056a3STejun Heo  * destroy_worker().
1716c34056a3STejun Heo  *
1717c34056a3STejun Heo  * CONTEXT:
1718c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
1719c34056a3STejun Heo  *
1720c34056a3STejun Heo  * RETURNS:
1721c34056a3STejun Heo  * Pointer to the newly created worker.
1722c34056a3STejun Heo  */
1723bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
1724c34056a3STejun Heo {
1725*7a4e344cSTejun Heo 	const char *pri = pool->attrs->nice < 0  ? "H" : "";
1726c34056a3STejun Heo 	struct worker *worker = NULL;
1727f3421797STejun Heo 	int id = -1;
1728c34056a3STejun Heo 
1729d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
1730bd7bdd43STejun Heo 	while (ida_get_new(&pool->worker_ida, &id)) {
1731d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
1732bd7bdd43STejun Heo 		if (!ida_pre_get(&pool->worker_ida, GFP_KERNEL))
1733c34056a3STejun Heo 			goto fail;
1734d565ed63STejun Heo 		spin_lock_irq(&pool->lock);
1735c34056a3STejun Heo 	}
1736d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
1737c34056a3STejun Heo 
1738c34056a3STejun Heo 	worker = alloc_worker();
1739c34056a3STejun Heo 	if (!worker)
1740c34056a3STejun Heo 		goto fail;
1741c34056a3STejun Heo 
1742bd7bdd43STejun Heo 	worker->pool = pool;
1743c34056a3STejun Heo 	worker->id = id;
1744c34056a3STejun Heo 
1745ec22ca5eSTejun Heo 	if (pool->cpu != WORK_CPU_UNBOUND)
174694dcf29aSEric Dumazet 		worker->task = kthread_create_on_node(worker_thread,
1747ec22ca5eSTejun Heo 					worker, cpu_to_node(pool->cpu),
1748d84ff051STejun Heo 					"kworker/%d:%d%s", pool->cpu, id, pri);
1749f3421797STejun Heo 	else
1750f3421797STejun Heo 		worker->task = kthread_create(worker_thread, worker,
17513270476aSTejun Heo 					      "kworker/u:%d%s", id, pri);
1752c34056a3STejun Heo 	if (IS_ERR(worker->task))
1753c34056a3STejun Heo 		goto fail;
1754c34056a3STejun Heo 
1755*7a4e344cSTejun Heo 	set_user_nice(worker->task, pool->attrs->nice);
1756*7a4e344cSTejun Heo 	set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
17573270476aSTejun Heo 
1758db7bccf4STejun Heo 	/*
1759*7a4e344cSTejun Heo 	 * %PF_THREAD_BOUND is used to prevent userland from meddling with
1760*7a4e344cSTejun Heo 	 * cpumask of workqueue workers.  This is an abuse.  We need
1761*7a4e344cSTejun Heo 	 * %PF_NO_SETAFFINITY.
1762db7bccf4STejun Heo 	 */
1763db7bccf4STejun Heo 	worker->task->flags |= PF_THREAD_BOUND;
1764*7a4e344cSTejun Heo 
1765*7a4e344cSTejun Heo 	/*
1766*7a4e344cSTejun Heo 	 * The caller is responsible for ensuring %POOL_DISASSOCIATED
1767*7a4e344cSTejun Heo 	 * remains stable across this function.  See the comments above the
1768*7a4e344cSTejun Heo 	 * flag definition for details.
1769*7a4e344cSTejun Heo 	 */
1770*7a4e344cSTejun Heo 	if (pool->flags & POOL_DISASSOCIATED)
1771f3421797STejun Heo 		worker->flags |= WORKER_UNBOUND;
1772c34056a3STejun Heo 
1773c34056a3STejun Heo 	return worker;
1774c34056a3STejun Heo fail:
1775c34056a3STejun Heo 	if (id >= 0) {
1776d565ed63STejun Heo 		spin_lock_irq(&pool->lock);
1777bd7bdd43STejun Heo 		ida_remove(&pool->worker_ida, id);
1778d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
1779c34056a3STejun Heo 	}
1780c34056a3STejun Heo 	kfree(worker);
1781c34056a3STejun Heo 	return NULL;
1782c34056a3STejun Heo }
1783c34056a3STejun Heo 
1784c34056a3STejun Heo /**
1785c34056a3STejun Heo  * start_worker - start a newly created worker
1786c34056a3STejun Heo  * @worker: worker to start
1787c34056a3STejun Heo  *
1788706026c2STejun Heo  * Make the pool aware of @worker and start it.
1789c34056a3STejun Heo  *
1790c34056a3STejun Heo  * CONTEXT:
1791d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1792c34056a3STejun Heo  */
1793c34056a3STejun Heo static void start_worker(struct worker *worker)
1794c34056a3STejun Heo {
1795cb444766STejun Heo 	worker->flags |= WORKER_STARTED;
1796bd7bdd43STejun Heo 	worker->pool->nr_workers++;
1797c8e55f36STejun Heo 	worker_enter_idle(worker);
1798c34056a3STejun Heo 	wake_up_process(worker->task);
1799c34056a3STejun Heo }
1800c34056a3STejun Heo 
1801c34056a3STejun Heo /**
1802c34056a3STejun Heo  * destroy_worker - destroy a workqueue worker
1803c34056a3STejun Heo  * @worker: worker to be destroyed
1804c34056a3STejun Heo  *
1805706026c2STejun Heo  * Destroy @worker and adjust @pool stats accordingly.
1806c8e55f36STejun Heo  *
1807c8e55f36STejun Heo  * CONTEXT:
1808d565ed63STejun Heo  * spin_lock_irq(pool->lock) which is released and regrabbed.
1809c34056a3STejun Heo  */
1810c34056a3STejun Heo static void destroy_worker(struct worker *worker)
1811c34056a3STejun Heo {
1812bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1813c34056a3STejun Heo 	int id = worker->id;
1814c34056a3STejun Heo 
1815c34056a3STejun Heo 	/* sanity check frenzy */
18166183c009STejun Heo 	if (WARN_ON(worker->current_work) ||
18176183c009STejun Heo 	    WARN_ON(!list_empty(&worker->scheduled)))
18186183c009STejun Heo 		return;
1819c34056a3STejun Heo 
1820c8e55f36STejun Heo 	if (worker->flags & WORKER_STARTED)
1821bd7bdd43STejun Heo 		pool->nr_workers--;
1822c8e55f36STejun Heo 	if (worker->flags & WORKER_IDLE)
1823bd7bdd43STejun Heo 		pool->nr_idle--;
1824c8e55f36STejun Heo 
1825c8e55f36STejun Heo 	list_del_init(&worker->entry);
1826cb444766STejun Heo 	worker->flags |= WORKER_DIE;
1827c8e55f36STejun Heo 
1828d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
1829c8e55f36STejun Heo 
1830c34056a3STejun Heo 	kthread_stop(worker->task);
1831c34056a3STejun Heo 	kfree(worker);
1832c34056a3STejun Heo 
1833d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
1834bd7bdd43STejun Heo 	ida_remove(&pool->worker_ida, id);
1835c34056a3STejun Heo }
1836c34056a3STejun Heo 
183763d95a91STejun Heo static void idle_worker_timeout(unsigned long __pool)
1838e22bee78STejun Heo {
183963d95a91STejun Heo 	struct worker_pool *pool = (void *)__pool;
1840e22bee78STejun Heo 
1841d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
1842e22bee78STejun Heo 
184363d95a91STejun Heo 	if (too_many_workers(pool)) {
1844e22bee78STejun Heo 		struct worker *worker;
1845e22bee78STejun Heo 		unsigned long expires;
1846e22bee78STejun Heo 
1847e22bee78STejun Heo 		/* idle_list is kept in LIFO order, check the last one */
184863d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
1849e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1850e22bee78STejun Heo 
1851e22bee78STejun Heo 		if (time_before(jiffies, expires))
185263d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
1853e22bee78STejun Heo 		else {
1854e22bee78STejun Heo 			/* it's been idle for too long, wake up manager */
185511ebea50STejun Heo 			pool->flags |= POOL_MANAGE_WORKERS;
185663d95a91STejun Heo 			wake_up_worker(pool);
1857e22bee78STejun Heo 		}
1858e22bee78STejun Heo 	}
1859e22bee78STejun Heo 
1860d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
1861e22bee78STejun Heo }
1862e22bee78STejun Heo 
1863493a1724STejun Heo static void send_mayday(struct work_struct *work)
1864e22bee78STejun Heo {
1865112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1866112202d9STejun Heo 	struct workqueue_struct *wq = pwq->wq;
1867493a1724STejun Heo 
1868493a1724STejun Heo 	lockdep_assert_held(&workqueue_lock);
1869e22bee78STejun Heo 
1870e22bee78STejun Heo 	if (!(wq->flags & WQ_RESCUER))
1871493a1724STejun Heo 		return;
1872e22bee78STejun Heo 
1873e22bee78STejun Heo 	/* mayday mayday mayday */
1874493a1724STejun Heo 	if (list_empty(&pwq->mayday_node)) {
1875493a1724STejun Heo 		list_add_tail(&pwq->mayday_node, &wq->maydays);
1876e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
1877493a1724STejun Heo 	}
1878e22bee78STejun Heo }
1879e22bee78STejun Heo 
1880706026c2STejun Heo static void pool_mayday_timeout(unsigned long __pool)
1881e22bee78STejun Heo {
188263d95a91STejun Heo 	struct worker_pool *pool = (void *)__pool;
1883e22bee78STejun Heo 	struct work_struct *work;
1884e22bee78STejun Heo 
1885493a1724STejun Heo 	spin_lock_irq(&workqueue_lock);		/* for wq->maydays */
1886493a1724STejun Heo 	spin_lock(&pool->lock);
1887e22bee78STejun Heo 
188863d95a91STejun Heo 	if (need_to_create_worker(pool)) {
1889e22bee78STejun Heo 		/*
1890e22bee78STejun Heo 		 * We've been trying to create a new worker but
1891e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
1892e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
1893e22bee78STejun Heo 		 * rescuers.
1894e22bee78STejun Heo 		 */
189563d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
1896e22bee78STejun Heo 			send_mayday(work);
1897e22bee78STejun Heo 	}
1898e22bee78STejun Heo 
1899493a1724STejun Heo 	spin_unlock(&pool->lock);
1900493a1724STejun Heo 	spin_unlock_irq(&workqueue_lock);
1901e22bee78STejun Heo 
190263d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1903e22bee78STejun Heo }
1904e22bee78STejun Heo 
1905e22bee78STejun Heo /**
1906e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
190763d95a91STejun Heo  * @pool: pool to create a new worker for
1908e22bee78STejun Heo  *
190963d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
1910e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
1911e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
191263d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
1913e22bee78STejun Heo  * possible allocation deadlock.
1914e22bee78STejun Heo  *
1915e22bee78STejun Heo  * On return, need_to_create_worker() is guaranteed to be false and
1916e22bee78STejun Heo  * may_start_working() true.
1917e22bee78STejun Heo  *
1918e22bee78STejun Heo  * LOCKING:
1919d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
1920e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
1921e22bee78STejun Heo  * manager.
1922e22bee78STejun Heo  *
1923e22bee78STejun Heo  * RETURNS:
1924d565ed63STejun Heo  * false if no action was taken and pool->lock stayed locked, true
1925e22bee78STejun Heo  * otherwise.
1926e22bee78STejun Heo  */
192763d95a91STejun Heo static bool maybe_create_worker(struct worker_pool *pool)
1928d565ed63STejun Heo __releases(&pool->lock)
1929d565ed63STejun Heo __acquires(&pool->lock)
1930e22bee78STejun Heo {
193163d95a91STejun Heo 	if (!need_to_create_worker(pool))
1932e22bee78STejun Heo 		return false;
1933e22bee78STejun Heo restart:
1934d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
19359f9c2364STejun Heo 
1936e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
193763d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1938e22bee78STejun Heo 
1939e22bee78STejun Heo 	while (true) {
1940e22bee78STejun Heo 		struct worker *worker;
1941e22bee78STejun Heo 
1942bc2ae0f5STejun Heo 		worker = create_worker(pool);
1943e22bee78STejun Heo 		if (worker) {
194463d95a91STejun Heo 			del_timer_sync(&pool->mayday_timer);
1945d565ed63STejun Heo 			spin_lock_irq(&pool->lock);
1946e22bee78STejun Heo 			start_worker(worker);
19476183c009STejun Heo 			if (WARN_ON_ONCE(need_to_create_worker(pool)))
19486183c009STejun Heo 				goto restart;
1949e22bee78STejun Heo 			return true;
1950e22bee78STejun Heo 		}
1951e22bee78STejun Heo 
195263d95a91STejun Heo 		if (!need_to_create_worker(pool))
1953e22bee78STejun Heo 			break;
1954e22bee78STejun Heo 
1955e22bee78STejun Heo 		__set_current_state(TASK_INTERRUPTIBLE);
1956e22bee78STejun Heo 		schedule_timeout(CREATE_COOLDOWN);
19579f9c2364STejun Heo 
195863d95a91STejun Heo 		if (!need_to_create_worker(pool))
1959e22bee78STejun Heo 			break;
1960e22bee78STejun Heo 	}
1961e22bee78STejun Heo 
196263d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
1963d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
196463d95a91STejun Heo 	if (need_to_create_worker(pool))
1965e22bee78STejun Heo 		goto restart;
1966e22bee78STejun Heo 	return true;
1967e22bee78STejun Heo }
1968e22bee78STejun Heo 
1969e22bee78STejun Heo /**
1970e22bee78STejun Heo  * maybe_destroy_worker - destroy workers which have been idle for a while
197163d95a91STejun Heo  * @pool: pool to destroy workers for
1972e22bee78STejun Heo  *
197363d95a91STejun Heo  * Destroy @pool workers which have been idle for longer than
1974e22bee78STejun Heo  * IDLE_WORKER_TIMEOUT.
1975e22bee78STejun Heo  *
1976e22bee78STejun Heo  * LOCKING:
1977d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
1978e22bee78STejun Heo  * multiple times.  Called only from manager.
1979e22bee78STejun Heo  *
1980e22bee78STejun Heo  * RETURNS:
1981d565ed63STejun Heo  * false if no action was taken and pool->lock stayed locked, true
1982e22bee78STejun Heo  * otherwise.
1983e22bee78STejun Heo  */
198463d95a91STejun Heo static bool maybe_destroy_workers(struct worker_pool *pool)
1985e22bee78STejun Heo {
1986e22bee78STejun Heo 	bool ret = false;
1987e22bee78STejun Heo 
198863d95a91STejun Heo 	while (too_many_workers(pool)) {
1989e22bee78STejun Heo 		struct worker *worker;
1990e22bee78STejun Heo 		unsigned long expires;
1991e22bee78STejun Heo 
199263d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
1993e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1994e22bee78STejun Heo 
1995e22bee78STejun Heo 		if (time_before(jiffies, expires)) {
199663d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
1997e22bee78STejun Heo 			break;
1998e22bee78STejun Heo 		}
1999e22bee78STejun Heo 
2000e22bee78STejun Heo 		destroy_worker(worker);
2001e22bee78STejun Heo 		ret = true;
2002e22bee78STejun Heo 	}
2003e22bee78STejun Heo 
2004e22bee78STejun Heo 	return ret;
2005e22bee78STejun Heo }
2006e22bee78STejun Heo 
2007e22bee78STejun Heo /**
2008e22bee78STejun Heo  * manage_workers - manage worker pool
2009e22bee78STejun Heo  * @worker: self
2010e22bee78STejun Heo  *
2011706026c2STejun Heo  * Assume the manager role and manage the worker pool @worker belongs
2012e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
2013706026c2STejun Heo  * pool.  The exclusion is handled automatically by this function.
2014e22bee78STejun Heo  *
2015e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
2016e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
2017e22bee78STejun Heo  * and may_start_working() is true.
2018e22bee78STejun Heo  *
2019e22bee78STejun Heo  * CONTEXT:
2020d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
2021e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
2022e22bee78STejun Heo  *
2023e22bee78STejun Heo  * RETURNS:
2024d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
2025d565ed63STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
2026e22bee78STejun Heo  */
2027e22bee78STejun Heo static bool manage_workers(struct worker *worker)
2028e22bee78STejun Heo {
202963d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
2030e22bee78STejun Heo 	bool ret = false;
2031e22bee78STejun Heo 
203234a06bd6STejun Heo 	if (!mutex_trylock(&pool->manager_arb))
2033e22bee78STejun Heo 		return ret;
2034e22bee78STejun Heo 
2035ee378aa4SLai Jiangshan 	/*
2036ee378aa4SLai Jiangshan 	 * To simplify both worker management and CPU hotplug, hold off
2037ee378aa4SLai Jiangshan 	 * management while hotplug is in progress.  CPU hotplug path can't
203834a06bd6STejun Heo 	 * grab @pool->manager_arb to achieve this because that can lead to
203934a06bd6STejun Heo 	 * idle worker depletion (all become busy thinking someone else is
204034a06bd6STejun Heo 	 * managing) which in turn can result in deadlock under extreme
204134a06bd6STejun Heo 	 * circumstances.  Use @pool->assoc_mutex to synchronize manager
204234a06bd6STejun Heo 	 * against CPU hotplug.
2043ee378aa4SLai Jiangshan 	 *
2044b2eb83d1SLai Jiangshan 	 * assoc_mutex would always be free unless CPU hotplug is in
2045d565ed63STejun Heo 	 * progress.  trylock first without dropping @pool->lock.
2046ee378aa4SLai Jiangshan 	 */
2047b2eb83d1SLai Jiangshan 	if (unlikely(!mutex_trylock(&pool->assoc_mutex))) {
2048d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
2049b2eb83d1SLai Jiangshan 		mutex_lock(&pool->assoc_mutex);
2050ee378aa4SLai Jiangshan 		/*
2051ee378aa4SLai Jiangshan 		 * CPU hotplug could have happened while we were waiting
2052b2eb83d1SLai Jiangshan 		 * for assoc_mutex.  Hotplug itself can't handle us
2053ee378aa4SLai Jiangshan 		 * because manager isn't either on idle or busy list, and
2054706026c2STejun Heo 		 * @pool's state and ours could have deviated.
2055ee378aa4SLai Jiangshan 		 *
2056b2eb83d1SLai Jiangshan 		 * As hotplug is now excluded via assoc_mutex, we can
2057ee378aa4SLai Jiangshan 		 * simply try to bind.  It will succeed or fail depending
2058706026c2STejun Heo 		 * on @pool's current state.  Try it and adjust
2059ee378aa4SLai Jiangshan 		 * %WORKER_UNBOUND accordingly.
2060ee378aa4SLai Jiangshan 		 */
2061f36dc67bSLai Jiangshan 		if (worker_maybe_bind_and_lock(pool))
2062ee378aa4SLai Jiangshan 			worker->flags &= ~WORKER_UNBOUND;
2063ee378aa4SLai Jiangshan 		else
2064ee378aa4SLai Jiangshan 			worker->flags |= WORKER_UNBOUND;
2065ee378aa4SLai Jiangshan 
2066ee378aa4SLai Jiangshan 		ret = true;
2067ee378aa4SLai Jiangshan 	}
2068ee378aa4SLai Jiangshan 
206911ebea50STejun Heo 	pool->flags &= ~POOL_MANAGE_WORKERS;
2070e22bee78STejun Heo 
2071e22bee78STejun Heo 	/*
2072e22bee78STejun Heo 	 * Destroy and then create so that may_start_working() is true
2073e22bee78STejun Heo 	 * on return.
2074e22bee78STejun Heo 	 */
207563d95a91STejun Heo 	ret |= maybe_destroy_workers(pool);
207663d95a91STejun Heo 	ret |= maybe_create_worker(pool);
2077e22bee78STejun Heo 
2078b2eb83d1SLai Jiangshan 	mutex_unlock(&pool->assoc_mutex);
207934a06bd6STejun Heo 	mutex_unlock(&pool->manager_arb);
2080e22bee78STejun Heo 	return ret;
2081e22bee78STejun Heo }
2082e22bee78STejun Heo 
2083a62428c0STejun Heo /**
2084a62428c0STejun Heo  * process_one_work - process single work
2085c34056a3STejun Heo  * @worker: self
2086a62428c0STejun Heo  * @work: work to process
2087a62428c0STejun Heo  *
2088a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
2089a62428c0STejun Heo  * process a single work including synchronization against and
2090a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
2091a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
2092a62428c0STejun Heo  * call this function to process a work.
2093a62428c0STejun Heo  *
2094a62428c0STejun Heo  * CONTEXT:
2095d565ed63STejun Heo  * spin_lock_irq(pool->lock) which is released and regrabbed.
2096a62428c0STejun Heo  */
2097c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
2098d565ed63STejun Heo __releases(&pool->lock)
2099d565ed63STejun Heo __acquires(&pool->lock)
21001da177e4SLinus Torvalds {
2101112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2102bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2103112202d9STejun Heo 	bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
210473f53c4aSTejun Heo 	int work_color;
21057e11629dSTejun Heo 	struct worker *collision;
21064e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
21074e6045f1SJohannes Berg 	/*
2108a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
2109a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
2110a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
2111a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
2112a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
21134e6045f1SJohannes Berg 	 */
21144d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
21154d82a1deSPeter Zijlstra 
21164d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
21174e6045f1SJohannes Berg #endif
21186fec10a1STejun Heo 	/*
21196fec10a1STejun Heo 	 * Ensure we're on the correct CPU.  DISASSOCIATED test is
21206fec10a1STejun Heo 	 * necessary to avoid spurious warnings from rescuers servicing the
212124647570STejun Heo 	 * unbound or a disassociated pool.
21226fec10a1STejun Heo 	 */
21235f7dabfdSLai Jiangshan 	WARN_ON_ONCE(!(worker->flags & WORKER_UNBOUND) &&
212424647570STejun Heo 		     !(pool->flags & POOL_DISASSOCIATED) &&
2125ec22ca5eSTejun Heo 		     raw_smp_processor_id() != pool->cpu);
212625511a47STejun Heo 
21277e11629dSTejun Heo 	/*
21287e11629dSTejun Heo 	 * A single work shouldn't be executed concurrently by
21297e11629dSTejun Heo 	 * multiple workers on a single cpu.  Check whether anyone is
21307e11629dSTejun Heo 	 * already processing the work.  If so, defer the work to the
21317e11629dSTejun Heo 	 * currently executing one.
21327e11629dSTejun Heo 	 */
2133c9e7cf27STejun Heo 	collision = find_worker_executing_work(pool, work);
21347e11629dSTejun Heo 	if (unlikely(collision)) {
21357e11629dSTejun Heo 		move_linked_works(work, &collision->scheduled, NULL);
21367e11629dSTejun Heo 		return;
21377e11629dSTejun Heo 	}
21381da177e4SLinus Torvalds 
21398930cabaSTejun Heo 	/* claim and dequeue */
21401da177e4SLinus Torvalds 	debug_work_deactivate(work);
2141c9e7cf27STejun Heo 	hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2142c34056a3STejun Heo 	worker->current_work = work;
2143a2c1c57bSTejun Heo 	worker->current_func = work->func;
2144112202d9STejun Heo 	worker->current_pwq = pwq;
214573f53c4aSTejun Heo 	work_color = get_work_color(work);
21467a22ad75STejun Heo 
2147a62428c0STejun Heo 	list_del_init(&work->entry);
2148a62428c0STejun Heo 
2149649027d7STejun Heo 	/*
2150fb0e7bebSTejun Heo 	 * CPU intensive works don't participate in concurrency
2151fb0e7bebSTejun Heo 	 * management.  They're the scheduler's responsibility.
2152fb0e7bebSTejun Heo 	 */
2153fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2154fb0e7bebSTejun Heo 		worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
2155fb0e7bebSTejun Heo 
2156974271c4STejun Heo 	/*
2157d565ed63STejun Heo 	 * Unbound pool isn't concurrency managed and work items should be
2158974271c4STejun Heo 	 * executed ASAP.  Wake up another worker if necessary.
2159974271c4STejun Heo 	 */
216063d95a91STejun Heo 	if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
216163d95a91STejun Heo 		wake_up_worker(pool);
2162974271c4STejun Heo 
21638930cabaSTejun Heo 	/*
21647c3eed5cSTejun Heo 	 * Record the last pool and clear PENDING which should be the last
2165d565ed63STejun Heo 	 * update to @work.  Also, do this inside @pool->lock so that
216623657bb1STejun Heo 	 * PENDING and queued state changes happen together while IRQ is
216723657bb1STejun Heo 	 * disabled.
21688930cabaSTejun Heo 	 */
21697c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(work, pool->id);
21701da177e4SLinus Torvalds 
2171d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2172365970a1SDavid Howells 
2173112202d9STejun Heo 	lock_map_acquire_read(&pwq->wq->lockdep_map);
21743295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
2175e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
2176a2c1c57bSTejun Heo 	worker->current_func(work);
2177e36c886aSArjan van de Ven 	/*
2178e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
2179e36c886aSArjan van de Ven 	 * point will only record its address.
2180e36c886aSArjan van de Ven 	 */
2181e36c886aSArjan van de Ven 	trace_workqueue_execute_end(work);
21823295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
2183112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
21841da177e4SLinus Torvalds 
2185d5abe669SPeter Zijlstra 	if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2186044c782cSValentin Ilie 		pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2187044c782cSValentin Ilie 		       "     last function: %pf\n",
2188a2c1c57bSTejun Heo 		       current->comm, preempt_count(), task_pid_nr(current),
2189a2c1c57bSTejun Heo 		       worker->current_func);
2190d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
2191d5abe669SPeter Zijlstra 		dump_stack();
2192d5abe669SPeter Zijlstra 	}
2193d5abe669SPeter Zijlstra 
2194d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
2195a62428c0STejun Heo 
2196fb0e7bebSTejun Heo 	/* clear cpu intensive status */
2197fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2198fb0e7bebSTejun Heo 		worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2199fb0e7bebSTejun Heo 
2200a62428c0STejun Heo 	/* we're done with it, release */
220142f8570fSSasha Levin 	hash_del(&worker->hentry);
2202c34056a3STejun Heo 	worker->current_work = NULL;
2203a2c1c57bSTejun Heo 	worker->current_func = NULL;
2204112202d9STejun Heo 	worker->current_pwq = NULL;
2205112202d9STejun Heo 	pwq_dec_nr_in_flight(pwq, work_color);
22061da177e4SLinus Torvalds }
22071da177e4SLinus Torvalds 
2208affee4b2STejun Heo /**
2209affee4b2STejun Heo  * process_scheduled_works - process scheduled works
2210affee4b2STejun Heo  * @worker: self
2211affee4b2STejun Heo  *
2212affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
2213affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
2214affee4b2STejun Heo  * fetches a work from the top and executes it.
2215affee4b2STejun Heo  *
2216affee4b2STejun Heo  * CONTEXT:
2217d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
2218affee4b2STejun Heo  * multiple times.
2219affee4b2STejun Heo  */
2220affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
22211da177e4SLinus Torvalds {
2222affee4b2STejun Heo 	while (!list_empty(&worker->scheduled)) {
2223affee4b2STejun Heo 		struct work_struct *work = list_first_entry(&worker->scheduled,
2224a62428c0STejun Heo 						struct work_struct, entry);
2225c34056a3STejun Heo 		process_one_work(worker, work);
2226a62428c0STejun Heo 	}
22271da177e4SLinus Torvalds }
22281da177e4SLinus Torvalds 
22294690c4abSTejun Heo /**
22304690c4abSTejun Heo  * worker_thread - the worker thread function
2231c34056a3STejun Heo  * @__worker: self
22324690c4abSTejun Heo  *
2233706026c2STejun Heo  * The worker thread function.  There are NR_CPU_WORKER_POOLS dynamic pools
2234706026c2STejun Heo  * of these per each cpu.  These workers process all works regardless of
2235e22bee78STejun Heo  * their specific target workqueue.  The only exception is works which
2236e22bee78STejun Heo  * belong to workqueues with a rescuer which will be explained in
2237e22bee78STejun Heo  * rescuer_thread().
22384690c4abSTejun Heo  */
2239c34056a3STejun Heo static int worker_thread(void *__worker)
22401da177e4SLinus Torvalds {
2241c34056a3STejun Heo 	struct worker *worker = __worker;
2242bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
22431da177e4SLinus Torvalds 
2244e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
2245e22bee78STejun Heo 	worker->task->flags |= PF_WQ_WORKER;
2246c8e55f36STejun Heo woke_up:
2247d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
2248affee4b2STejun Heo 
22495f7dabfdSLai Jiangshan 	/* we are off idle list if destruction or rebind is requested */
22505f7dabfdSLai Jiangshan 	if (unlikely(list_empty(&worker->entry))) {
2251d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
225225511a47STejun Heo 
22535f7dabfdSLai Jiangshan 		/* if DIE is set, destruction is requested */
225425511a47STejun Heo 		if (worker->flags & WORKER_DIE) {
2255e22bee78STejun Heo 			worker->task->flags &= ~PF_WQ_WORKER;
2256c8e55f36STejun Heo 			return 0;
2257c8e55f36STejun Heo 		}
2258c8e55f36STejun Heo 
22595f7dabfdSLai Jiangshan 		/* otherwise, rebind */
226025511a47STejun Heo 		idle_worker_rebind(worker);
226125511a47STejun Heo 		goto woke_up;
226225511a47STejun Heo 	}
226325511a47STejun Heo 
2264c8e55f36STejun Heo 	worker_leave_idle(worker);
2265db7bccf4STejun Heo recheck:
2266e22bee78STejun Heo 	/* no more worker necessary? */
226763d95a91STejun Heo 	if (!need_more_worker(pool))
2268e22bee78STejun Heo 		goto sleep;
2269e22bee78STejun Heo 
2270e22bee78STejun Heo 	/* do we need to manage? */
227163d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2272e22bee78STejun Heo 		goto recheck;
2273e22bee78STejun Heo 
2274c8e55f36STejun Heo 	/*
2275c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
2276c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
2277c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
2278c8e55f36STejun Heo 	 */
22796183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
2280c8e55f36STejun Heo 
2281e22bee78STejun Heo 	/*
2282e22bee78STejun Heo 	 * When control reaches this point, we're guaranteed to have
2283e22bee78STejun Heo 	 * at least one idle worker or that someone else has already
2284e22bee78STejun Heo 	 * assumed the manager role.
2285e22bee78STejun Heo 	 */
2286e22bee78STejun Heo 	worker_clr_flags(worker, WORKER_PREP);
2287e22bee78STejun Heo 
2288e22bee78STejun Heo 	do {
2289affee4b2STejun Heo 		struct work_struct *work =
2290bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
2291affee4b2STejun Heo 					 struct work_struct, entry);
2292affee4b2STejun Heo 
2293c8e55f36STejun Heo 		if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2294affee4b2STejun Heo 			/* optimization path, not strictly necessary */
2295affee4b2STejun Heo 			process_one_work(worker, work);
2296affee4b2STejun Heo 			if (unlikely(!list_empty(&worker->scheduled)))
2297affee4b2STejun Heo 				process_scheduled_works(worker);
2298affee4b2STejun Heo 		} else {
2299c8e55f36STejun Heo 			move_linked_works(work, &worker->scheduled, NULL);
2300affee4b2STejun Heo 			process_scheduled_works(worker);
2301affee4b2STejun Heo 		}
230263d95a91STejun Heo 	} while (keep_working(pool));
2303affee4b2STejun Heo 
2304e22bee78STejun Heo 	worker_set_flags(worker, WORKER_PREP, false);
2305d313dd85STejun Heo sleep:
230663d95a91STejun Heo 	if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
2307e22bee78STejun Heo 		goto recheck;
2308d313dd85STejun Heo 
2309c8e55f36STejun Heo 	/*
2310d565ed63STejun Heo 	 * pool->lock is held and there's no work to process and no need to
2311d565ed63STejun Heo 	 * manage, sleep.  Workers are woken up only while holding
2312d565ed63STejun Heo 	 * pool->lock or from local cpu, so setting the current state
2313d565ed63STejun Heo 	 * before releasing pool->lock is enough to prevent losing any
2314d565ed63STejun Heo 	 * event.
2315c8e55f36STejun Heo 	 */
2316c8e55f36STejun Heo 	worker_enter_idle(worker);
2317c8e55f36STejun Heo 	__set_current_state(TASK_INTERRUPTIBLE);
2318d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
23191da177e4SLinus Torvalds 	schedule();
2320c8e55f36STejun Heo 	goto woke_up;
23211da177e4SLinus Torvalds }
23221da177e4SLinus Torvalds 
2323e22bee78STejun Heo /**
2324e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
2325111c225aSTejun Heo  * @__rescuer: self
2326e22bee78STejun Heo  *
2327e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
2328e22bee78STejun Heo  * workqueue which has WQ_RESCUER set.
2329e22bee78STejun Heo  *
2330706026c2STejun Heo  * Regular work processing on a pool may block trying to create a new
2331e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
2332e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
2333e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2334e22bee78STejun Heo  * the problem rescuer solves.
2335e22bee78STejun Heo  *
2336706026c2STejun Heo  * When such condition is possible, the pool summons rescuers of all
2337706026c2STejun Heo  * workqueues which have works queued on the pool and let them process
2338e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
2339e22bee78STejun Heo  *
2340e22bee78STejun Heo  * This should happen rarely.
2341e22bee78STejun Heo  */
2342111c225aSTejun Heo static int rescuer_thread(void *__rescuer)
2343e22bee78STejun Heo {
2344111c225aSTejun Heo 	struct worker *rescuer = __rescuer;
2345111c225aSTejun Heo 	struct workqueue_struct *wq = rescuer->rescue_wq;
2346e22bee78STejun Heo 	struct list_head *scheduled = &rescuer->scheduled;
2347e22bee78STejun Heo 
2348e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
2349111c225aSTejun Heo 
2350111c225aSTejun Heo 	/*
2351111c225aSTejun Heo 	 * Mark rescuer as worker too.  As WORKER_PREP is never cleared, it
2352111c225aSTejun Heo 	 * doesn't participate in concurrency management.
2353111c225aSTejun Heo 	 */
2354111c225aSTejun Heo 	rescuer->task->flags |= PF_WQ_WORKER;
2355e22bee78STejun Heo repeat:
2356e22bee78STejun Heo 	set_current_state(TASK_INTERRUPTIBLE);
23571da177e4SLinus Torvalds 
2358412d32e6SMike Galbraith 	if (kthread_should_stop()) {
2359412d32e6SMike Galbraith 		__set_current_state(TASK_RUNNING);
2360111c225aSTejun Heo 		rescuer->task->flags &= ~PF_WQ_WORKER;
2361e22bee78STejun Heo 		return 0;
2362412d32e6SMike Galbraith 	}
23631da177e4SLinus Torvalds 
2364493a1724STejun Heo 	/* see whether any pwq is asking for help */
2365493a1724STejun Heo 	spin_lock_irq(&workqueue_lock);
2366493a1724STejun Heo 
2367493a1724STejun Heo 	while (!list_empty(&wq->maydays)) {
2368493a1724STejun Heo 		struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2369493a1724STejun Heo 					struct pool_workqueue, mayday_node);
2370112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
2371e22bee78STejun Heo 		struct work_struct *work, *n;
2372e22bee78STejun Heo 
2373e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
2374493a1724STejun Heo 		list_del_init(&pwq->mayday_node);
2375493a1724STejun Heo 
2376493a1724STejun Heo 		spin_unlock_irq(&workqueue_lock);
2377e22bee78STejun Heo 
2378e22bee78STejun Heo 		/* migrate to the target cpu if possible */
2379f36dc67bSLai Jiangshan 		worker_maybe_bind_and_lock(pool);
2380b3104104SLai Jiangshan 		rescuer->pool = pool;
2381e22bee78STejun Heo 
2382e22bee78STejun Heo 		/*
2383e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
2384e22bee78STejun Heo 		 * process'em.
2385e22bee78STejun Heo 		 */
23866183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&rescuer->scheduled));
2387bd7bdd43STejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry)
2388112202d9STejun Heo 			if (get_work_pwq(work) == pwq)
2389e22bee78STejun Heo 				move_linked_works(work, scheduled, &n);
2390e22bee78STejun Heo 
2391e22bee78STejun Heo 		process_scheduled_works(rescuer);
23927576958aSTejun Heo 
23937576958aSTejun Heo 		/*
2394d565ed63STejun Heo 		 * Leave this pool.  If keep_working() is %true, notify a
23957576958aSTejun Heo 		 * regular worker; otherwise, we end up with 0 concurrency
23967576958aSTejun Heo 		 * and stalling the execution.
23977576958aSTejun Heo 		 */
239863d95a91STejun Heo 		if (keep_working(pool))
239963d95a91STejun Heo 			wake_up_worker(pool);
24007576958aSTejun Heo 
2401b3104104SLai Jiangshan 		rescuer->pool = NULL;
2402493a1724STejun Heo 		spin_unlock(&pool->lock);
2403493a1724STejun Heo 		spin_lock(&workqueue_lock);
24041da177e4SLinus Torvalds 	}
24051da177e4SLinus Torvalds 
2406493a1724STejun Heo 	spin_unlock_irq(&workqueue_lock);
2407493a1724STejun Heo 
2408111c225aSTejun Heo 	/* rescuers should never participate in concurrency management */
2409111c225aSTejun Heo 	WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2410e22bee78STejun Heo 	schedule();
2411e22bee78STejun Heo 	goto repeat;
24121da177e4SLinus Torvalds }
24131da177e4SLinus Torvalds 
2414fc2e4d70SOleg Nesterov struct wq_barrier {
2415fc2e4d70SOleg Nesterov 	struct work_struct	work;
2416fc2e4d70SOleg Nesterov 	struct completion	done;
2417fc2e4d70SOleg Nesterov };
2418fc2e4d70SOleg Nesterov 
2419fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
2420fc2e4d70SOleg Nesterov {
2421fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2422fc2e4d70SOleg Nesterov 	complete(&barr->done);
2423fc2e4d70SOleg Nesterov }
2424fc2e4d70SOleg Nesterov 
24254690c4abSTejun Heo /**
24264690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
2427112202d9STejun Heo  * @pwq: pwq to insert barrier into
24284690c4abSTejun Heo  * @barr: wq_barrier to insert
2429affee4b2STejun Heo  * @target: target work to attach @barr to
2430affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
24314690c4abSTejun Heo  *
2432affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
2433affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
2434affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
2435affee4b2STejun Heo  * cpu.
2436affee4b2STejun Heo  *
2437affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
2438affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
2439affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
2440affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
2441affee4b2STejun Heo  * after a work with LINKED flag set.
2442affee4b2STejun Heo  *
2443affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
2444112202d9STejun Heo  * underneath us, so we can't reliably determine pwq from @target.
24454690c4abSTejun Heo  *
24464690c4abSTejun Heo  * CONTEXT:
2447d565ed63STejun Heo  * spin_lock_irq(pool->lock).
24484690c4abSTejun Heo  */
2449112202d9STejun Heo static void insert_wq_barrier(struct pool_workqueue *pwq,
2450affee4b2STejun Heo 			      struct wq_barrier *barr,
2451affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
2452fc2e4d70SOleg Nesterov {
2453affee4b2STejun Heo 	struct list_head *head;
2454affee4b2STejun Heo 	unsigned int linked = 0;
2455affee4b2STejun Heo 
2456dc186ad7SThomas Gleixner 	/*
2457d565ed63STejun Heo 	 * debugobject calls are safe here even with pool->lock locked
2458dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
2459dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
2460dc186ad7SThomas Gleixner 	 * might deadlock.
2461dc186ad7SThomas Gleixner 	 */
2462ca1cab37SAndrew Morton 	INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
246322df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2464fc2e4d70SOleg Nesterov 	init_completion(&barr->done);
246583c22520SOleg Nesterov 
2466affee4b2STejun Heo 	/*
2467affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
2468affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
2469affee4b2STejun Heo 	 */
2470affee4b2STejun Heo 	if (worker)
2471affee4b2STejun Heo 		head = worker->scheduled.next;
2472affee4b2STejun Heo 	else {
2473affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
2474affee4b2STejun Heo 
2475affee4b2STejun Heo 		head = target->entry.next;
2476affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
2477affee4b2STejun Heo 		linked = *bits & WORK_STRUCT_LINKED;
2478affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
2479affee4b2STejun Heo 	}
2480affee4b2STejun Heo 
2481dc186ad7SThomas Gleixner 	debug_work_activate(&barr->work);
2482112202d9STejun Heo 	insert_work(pwq, &barr->work, head,
2483affee4b2STejun Heo 		    work_color_to_flags(WORK_NO_COLOR) | linked);
2484fc2e4d70SOleg Nesterov }
2485fc2e4d70SOleg Nesterov 
248673f53c4aSTejun Heo /**
2487112202d9STejun Heo  * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
248873f53c4aSTejun Heo  * @wq: workqueue being flushed
248973f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
249073f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
249173f53c4aSTejun Heo  *
2492112202d9STejun Heo  * Prepare pwqs for workqueue flushing.
249373f53c4aSTejun Heo  *
2494112202d9STejun Heo  * If @flush_color is non-negative, flush_color on all pwqs should be
2495112202d9STejun Heo  * -1.  If no pwq has in-flight commands at the specified color, all
2496112202d9STejun Heo  * pwq->flush_color's stay at -1 and %false is returned.  If any pwq
2497112202d9STejun Heo  * has in flight commands, its pwq->flush_color is set to
2498112202d9STejun Heo  * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
249973f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
250073f53c4aSTejun Heo  *
250173f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
250273f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
250373f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
250473f53c4aSTejun Heo  * is returned.
250573f53c4aSTejun Heo  *
2506112202d9STejun Heo  * If @work_color is non-negative, all pwqs should have the same
250773f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
250873f53c4aSTejun Heo  * advanced to @work_color.
250973f53c4aSTejun Heo  *
251073f53c4aSTejun Heo  * CONTEXT:
251173f53c4aSTejun Heo  * mutex_lock(wq->flush_mutex).
251273f53c4aSTejun Heo  *
251373f53c4aSTejun Heo  * RETURNS:
251473f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
251573f53c4aSTejun Heo  * otherwise.
251673f53c4aSTejun Heo  */
2517112202d9STejun Heo static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
251873f53c4aSTejun Heo 				      int flush_color, int work_color)
25191da177e4SLinus Torvalds {
252073f53c4aSTejun Heo 	bool wait = false;
252149e3cf44STejun Heo 	struct pool_workqueue *pwq;
25221da177e4SLinus Torvalds 
252373f53c4aSTejun Heo 	if (flush_color >= 0) {
25246183c009STejun Heo 		WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2525112202d9STejun Heo 		atomic_set(&wq->nr_pwqs_to_flush, 1);
2526dc186ad7SThomas Gleixner 	}
252714441960SOleg Nesterov 
252876af4d93STejun Heo 	local_irq_disable();
252976af4d93STejun Heo 
253049e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2531112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
25321da177e4SLinus Torvalds 
253376af4d93STejun Heo 		spin_lock(&pool->lock);
253473f53c4aSTejun Heo 
253573f53c4aSTejun Heo 		if (flush_color >= 0) {
25366183c009STejun Heo 			WARN_ON_ONCE(pwq->flush_color != -1);
253773f53c4aSTejun Heo 
2538112202d9STejun Heo 			if (pwq->nr_in_flight[flush_color]) {
2539112202d9STejun Heo 				pwq->flush_color = flush_color;
2540112202d9STejun Heo 				atomic_inc(&wq->nr_pwqs_to_flush);
254173f53c4aSTejun Heo 				wait = true;
25421da177e4SLinus Torvalds 			}
254373f53c4aSTejun Heo 		}
254473f53c4aSTejun Heo 
254573f53c4aSTejun Heo 		if (work_color >= 0) {
25466183c009STejun Heo 			WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2547112202d9STejun Heo 			pwq->work_color = work_color;
254873f53c4aSTejun Heo 		}
254973f53c4aSTejun Heo 
255076af4d93STejun Heo 		spin_unlock(&pool->lock);
25511da177e4SLinus Torvalds 	}
25521da177e4SLinus Torvalds 
255376af4d93STejun Heo 	local_irq_enable();
255476af4d93STejun Heo 
2555112202d9STejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
255673f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
255773f53c4aSTejun Heo 
255873f53c4aSTejun Heo 	return wait;
255983c22520SOleg Nesterov }
25601da177e4SLinus Torvalds 
25610fcb78c2SRolf Eike Beer /**
25621da177e4SLinus Torvalds  * flush_workqueue - ensure that any scheduled work has run to completion.
25630fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
25641da177e4SLinus Torvalds  *
25651da177e4SLinus Torvalds  * Forces execution of the workqueue and blocks until its completion.
25661da177e4SLinus Torvalds  * This is typically used in driver shutdown handlers.
25671da177e4SLinus Torvalds  *
2568fc2e4d70SOleg Nesterov  * We sleep until all works which were queued on entry have been handled,
2569fc2e4d70SOleg Nesterov  * but we are not livelocked by new incoming ones.
25701da177e4SLinus Torvalds  */
25717ad5b3a5SHarvey Harrison void flush_workqueue(struct workqueue_struct *wq)
25721da177e4SLinus Torvalds {
257373f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
257473f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
257573f53c4aSTejun Heo 		.flush_color = -1,
257673f53c4aSTejun Heo 		.done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
257773f53c4aSTejun Heo 	};
257873f53c4aSTejun Heo 	int next_color;
2579b1f4ec17SOleg Nesterov 
25803295f0efSIngo Molnar 	lock_map_acquire(&wq->lockdep_map);
25813295f0efSIngo Molnar 	lock_map_release(&wq->lockdep_map);
258273f53c4aSTejun Heo 
258373f53c4aSTejun Heo 	mutex_lock(&wq->flush_mutex);
258473f53c4aSTejun Heo 
258573f53c4aSTejun Heo 	/*
258673f53c4aSTejun Heo 	 * Start-to-wait phase
258773f53c4aSTejun Heo 	 */
258873f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
258973f53c4aSTejun Heo 
259073f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
259173f53c4aSTejun Heo 		/*
259273f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
259373f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
259473f53c4aSTejun Heo 		 * by one.
259573f53c4aSTejun Heo 		 */
25966183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
259773f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
259873f53c4aSTejun Heo 		wq->work_color = next_color;
259973f53c4aSTejun Heo 
260073f53c4aSTejun Heo 		if (!wq->first_flusher) {
260173f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
26026183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
260373f53c4aSTejun Heo 
260473f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
260573f53c4aSTejun Heo 
2606112202d9STejun Heo 			if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
260773f53c4aSTejun Heo 						       wq->work_color)) {
260873f53c4aSTejun Heo 				/* nothing to flush, done */
260973f53c4aSTejun Heo 				wq->flush_color = next_color;
261073f53c4aSTejun Heo 				wq->first_flusher = NULL;
261173f53c4aSTejun Heo 				goto out_unlock;
261273f53c4aSTejun Heo 			}
261373f53c4aSTejun Heo 		} else {
261473f53c4aSTejun Heo 			/* wait in queue */
26156183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
261673f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
2617112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
261873f53c4aSTejun Heo 		}
261973f53c4aSTejun Heo 	} else {
262073f53c4aSTejun Heo 		/*
262173f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
262273f53c4aSTejun Heo 		 * The next flush completion will assign us
262373f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
262473f53c4aSTejun Heo 		 */
262573f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
262673f53c4aSTejun Heo 	}
262773f53c4aSTejun Heo 
262873f53c4aSTejun Heo 	mutex_unlock(&wq->flush_mutex);
262973f53c4aSTejun Heo 
263073f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
263173f53c4aSTejun Heo 
263273f53c4aSTejun Heo 	/*
263373f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
263473f53c4aSTejun Heo 	 *
263573f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
263673f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
263773f53c4aSTejun Heo 	 */
263873f53c4aSTejun Heo 	if (wq->first_flusher != &this_flusher)
263973f53c4aSTejun Heo 		return;
264073f53c4aSTejun Heo 
264173f53c4aSTejun Heo 	mutex_lock(&wq->flush_mutex);
264273f53c4aSTejun Heo 
26434ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
26444ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
26454ce48b37STejun Heo 		goto out_unlock;
26464ce48b37STejun Heo 
264773f53c4aSTejun Heo 	wq->first_flusher = NULL;
264873f53c4aSTejun Heo 
26496183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&this_flusher.list));
26506183c009STejun Heo 	WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
265173f53c4aSTejun Heo 
265273f53c4aSTejun Heo 	while (true) {
265373f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
265473f53c4aSTejun Heo 
265573f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
265673f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
265773f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
265873f53c4aSTejun Heo 				break;
265973f53c4aSTejun Heo 			list_del_init(&next->list);
266073f53c4aSTejun Heo 			complete(&next->done);
266173f53c4aSTejun Heo 		}
266273f53c4aSTejun Heo 
26636183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
266473f53c4aSTejun Heo 			     wq->flush_color != work_next_color(wq->work_color));
266573f53c4aSTejun Heo 
266673f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
266773f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
266873f53c4aSTejun Heo 
266973f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
267073f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
267173f53c4aSTejun Heo 			/*
267273f53c4aSTejun Heo 			 * Assign the same color to all overflowed
267373f53c4aSTejun Heo 			 * flushers, advance work_color and append to
267473f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
267573f53c4aSTejun Heo 			 * phase for these overflowed flushers.
267673f53c4aSTejun Heo 			 */
267773f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
267873f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
267973f53c4aSTejun Heo 
268073f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
268173f53c4aSTejun Heo 
268273f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
268373f53c4aSTejun Heo 					      &wq->flusher_queue);
2684112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
268573f53c4aSTejun Heo 		}
268673f53c4aSTejun Heo 
268773f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
26886183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != wq->work_color);
268973f53c4aSTejun Heo 			break;
269073f53c4aSTejun Heo 		}
269173f53c4aSTejun Heo 
269273f53c4aSTejun Heo 		/*
269373f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
2694112202d9STejun Heo 		 * the new first flusher and arm pwqs.
269573f53c4aSTejun Heo 		 */
26966183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color == wq->work_color);
26976183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color != next->flush_color);
269873f53c4aSTejun Heo 
269973f53c4aSTejun Heo 		list_del_init(&next->list);
270073f53c4aSTejun Heo 		wq->first_flusher = next;
270173f53c4aSTejun Heo 
2702112202d9STejun Heo 		if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
270373f53c4aSTejun Heo 			break;
270473f53c4aSTejun Heo 
270573f53c4aSTejun Heo 		/*
270673f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
270773f53c4aSTejun Heo 		 * flusher and repeat cascading.
270873f53c4aSTejun Heo 		 */
270973f53c4aSTejun Heo 		wq->first_flusher = NULL;
271073f53c4aSTejun Heo 	}
271173f53c4aSTejun Heo 
271273f53c4aSTejun Heo out_unlock:
271373f53c4aSTejun Heo 	mutex_unlock(&wq->flush_mutex);
27141da177e4SLinus Torvalds }
2715ae90dd5dSDave Jones EXPORT_SYMBOL_GPL(flush_workqueue);
27161da177e4SLinus Torvalds 
27179c5a2ba7STejun Heo /**
27189c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
27199c5a2ba7STejun Heo  * @wq: workqueue to drain
27209c5a2ba7STejun Heo  *
27219c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
27229c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
27239c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
27249c5a2ba7STejun Heo  * repeatedly until it becomes empty.  The number of flushing is detemined
27259c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
27269c5a2ba7STejun Heo  * takes too long.
27279c5a2ba7STejun Heo  */
27289c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
27299c5a2ba7STejun Heo {
27309c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
273149e3cf44STejun Heo 	struct pool_workqueue *pwq;
27329c5a2ba7STejun Heo 
27339c5a2ba7STejun Heo 	/*
27349c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
27359c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
27369c5a2ba7STejun Heo 	 * Use WQ_DRAINING so that queue doesn't have to check nr_drainers.
27379c5a2ba7STejun Heo 	 */
2738e98d5b16STejun Heo 	spin_lock_irq(&workqueue_lock);
27399c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
27409c5a2ba7STejun Heo 		wq->flags |= WQ_DRAINING;
2741e98d5b16STejun Heo 	spin_unlock_irq(&workqueue_lock);
27429c5a2ba7STejun Heo reflush:
27439c5a2ba7STejun Heo 	flush_workqueue(wq);
27449c5a2ba7STejun Heo 
274576af4d93STejun Heo 	local_irq_disable();
274676af4d93STejun Heo 
274749e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2748fa2563e4SThomas Tuttle 		bool drained;
27499c5a2ba7STejun Heo 
275076af4d93STejun Heo 		spin_lock(&pwq->pool->lock);
2751112202d9STejun Heo 		drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
275276af4d93STejun Heo 		spin_unlock(&pwq->pool->lock);
2753fa2563e4SThomas Tuttle 
2754fa2563e4SThomas Tuttle 		if (drained)
27559c5a2ba7STejun Heo 			continue;
27569c5a2ba7STejun Heo 
27579c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
27589c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2759044c782cSValentin Ilie 			pr_warn("workqueue %s: flush on destruction isn't complete after %u tries\n",
27609c5a2ba7STejun Heo 				wq->name, flush_cnt);
276176af4d93STejun Heo 
276276af4d93STejun Heo 		local_irq_enable();
27639c5a2ba7STejun Heo 		goto reflush;
27649c5a2ba7STejun Heo 	}
27659c5a2ba7STejun Heo 
276676af4d93STejun Heo 	spin_lock(&workqueue_lock);
27679c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
27689c5a2ba7STejun Heo 		wq->flags &= ~WQ_DRAINING;
276976af4d93STejun Heo 	spin_unlock(&workqueue_lock);
277076af4d93STejun Heo 
277176af4d93STejun Heo 	local_irq_enable();
27729c5a2ba7STejun Heo }
27739c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
27749c5a2ba7STejun Heo 
2775606a5020STejun Heo static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2776baf59022STejun Heo {
2777baf59022STejun Heo 	struct worker *worker = NULL;
2778c9e7cf27STejun Heo 	struct worker_pool *pool;
2779112202d9STejun Heo 	struct pool_workqueue *pwq;
2780baf59022STejun Heo 
2781baf59022STejun Heo 	might_sleep();
2782baf59022STejun Heo 
2783fa1b54e6STejun Heo 	local_irq_disable();
2784fa1b54e6STejun Heo 	pool = get_work_pool(work);
2785fa1b54e6STejun Heo 	if (!pool) {
2786fa1b54e6STejun Heo 		local_irq_enable();
2787fa1b54e6STejun Heo 		return false;
2788fa1b54e6STejun Heo 	}
2789fa1b54e6STejun Heo 
2790fa1b54e6STejun Heo 	spin_lock(&pool->lock);
27910b3dae68SLai Jiangshan 	/* see the comment in try_to_grab_pending() with the same code */
2792112202d9STejun Heo 	pwq = get_work_pwq(work);
2793112202d9STejun Heo 	if (pwq) {
2794112202d9STejun Heo 		if (unlikely(pwq->pool != pool))
2795baf59022STejun Heo 			goto already_gone;
2796606a5020STejun Heo 	} else {
2797c9e7cf27STejun Heo 		worker = find_worker_executing_work(pool, work);
2798baf59022STejun Heo 		if (!worker)
2799baf59022STejun Heo 			goto already_gone;
2800112202d9STejun Heo 		pwq = worker->current_pwq;
2801606a5020STejun Heo 	}
2802baf59022STejun Heo 
2803112202d9STejun Heo 	insert_wq_barrier(pwq, barr, work, worker);
2804d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2805baf59022STejun Heo 
2806e159489bSTejun Heo 	/*
2807e159489bSTejun Heo 	 * If @max_active is 1 or rescuer is in use, flushing another work
2808e159489bSTejun Heo 	 * item on the same workqueue may lead to deadlock.  Make sure the
2809e159489bSTejun Heo 	 * flusher is not running on the same workqueue by verifying write
2810e159489bSTejun Heo 	 * access.
2811e159489bSTejun Heo 	 */
2812112202d9STejun Heo 	if (pwq->wq->saved_max_active == 1 || pwq->wq->flags & WQ_RESCUER)
2813112202d9STejun Heo 		lock_map_acquire(&pwq->wq->lockdep_map);
2814e159489bSTejun Heo 	else
2815112202d9STejun Heo 		lock_map_acquire_read(&pwq->wq->lockdep_map);
2816112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
2817e159489bSTejun Heo 
2818baf59022STejun Heo 	return true;
2819baf59022STejun Heo already_gone:
2820d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2821baf59022STejun Heo 	return false;
2822baf59022STejun Heo }
2823baf59022STejun Heo 
2824db700897SOleg Nesterov /**
2825401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
2826401a8d04STejun Heo  * @work: the work to flush
2827db700897SOleg Nesterov  *
2828606a5020STejun Heo  * Wait until @work has finished execution.  @work is guaranteed to be idle
2829606a5020STejun Heo  * on return if it hasn't been requeued since flush started.
2830401a8d04STejun Heo  *
2831401a8d04STejun Heo  * RETURNS:
2832401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
2833401a8d04STejun Heo  * %false if it was already idle.
2834db700897SOleg Nesterov  */
2835401a8d04STejun Heo bool flush_work(struct work_struct *work)
2836db700897SOleg Nesterov {
2837db700897SOleg Nesterov 	struct wq_barrier barr;
2838db700897SOleg Nesterov 
28390976dfc1SStephen Boyd 	lock_map_acquire(&work->lockdep_map);
28400976dfc1SStephen Boyd 	lock_map_release(&work->lockdep_map);
28410976dfc1SStephen Boyd 
2842606a5020STejun Heo 	if (start_flush_work(work, &barr)) {
2843db700897SOleg Nesterov 		wait_for_completion(&barr.done);
2844dc186ad7SThomas Gleixner 		destroy_work_on_stack(&barr.work);
2845401a8d04STejun Heo 		return true;
2846606a5020STejun Heo 	} else {
2847401a8d04STejun Heo 		return false;
2848db700897SOleg Nesterov 	}
2849606a5020STejun Heo }
2850db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
2851db700897SOleg Nesterov 
285236e227d2STejun Heo static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2853401a8d04STejun Heo {
2854bbb68dfaSTejun Heo 	unsigned long flags;
28551f1f642eSOleg Nesterov 	int ret;
28561f1f642eSOleg Nesterov 
28571f1f642eSOleg Nesterov 	do {
2858bbb68dfaSTejun Heo 		ret = try_to_grab_pending(work, is_dwork, &flags);
2859bbb68dfaSTejun Heo 		/*
2860bbb68dfaSTejun Heo 		 * If someone else is canceling, wait for the same event it
2861bbb68dfaSTejun Heo 		 * would be waiting for before retrying.
2862bbb68dfaSTejun Heo 		 */
2863bbb68dfaSTejun Heo 		if (unlikely(ret == -ENOENT))
2864606a5020STejun Heo 			flush_work(work);
28651f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
28661f1f642eSOleg Nesterov 
2867bbb68dfaSTejun Heo 	/* tell other tasks trying to grab @work to back off */
2868bbb68dfaSTejun Heo 	mark_work_canceling(work);
2869bbb68dfaSTejun Heo 	local_irq_restore(flags);
2870bbb68dfaSTejun Heo 
2871606a5020STejun Heo 	flush_work(work);
28727a22ad75STejun Heo 	clear_work_data(work);
28731f1f642eSOleg Nesterov 	return ret;
28741f1f642eSOleg Nesterov }
28751f1f642eSOleg Nesterov 
28766e84d644SOleg Nesterov /**
2877401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
2878401a8d04STejun Heo  * @work: the work to cancel
28796e84d644SOleg Nesterov  *
2880401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
2881401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
2882401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
2883401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
28841f1f642eSOleg Nesterov  *
2885401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
2886401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
28876e84d644SOleg Nesterov  *
2888401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
28896e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
2890401a8d04STejun Heo  *
2891401a8d04STejun Heo  * RETURNS:
2892401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
28936e84d644SOleg Nesterov  */
2894401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
28956e84d644SOleg Nesterov {
289636e227d2STejun Heo 	return __cancel_work_timer(work, false);
2897b89deed3SOleg Nesterov }
289828e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
2899b89deed3SOleg Nesterov 
29006e84d644SOleg Nesterov /**
2901401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
2902401a8d04STejun Heo  * @dwork: the delayed work to flush
29036e84d644SOleg Nesterov  *
2904401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
2905401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
2906401a8d04STejun Heo  * considers the last queueing instance of @dwork.
29071f1f642eSOleg Nesterov  *
2908401a8d04STejun Heo  * RETURNS:
2909401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
2910401a8d04STejun Heo  * %false if it was already idle.
29116e84d644SOleg Nesterov  */
2912401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
2913401a8d04STejun Heo {
29148930cabaSTejun Heo 	local_irq_disable();
2915401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
291660c057bcSLai Jiangshan 		__queue_work(dwork->cpu, dwork->wq, &dwork->work);
29178930cabaSTejun Heo 	local_irq_enable();
2918401a8d04STejun Heo 	return flush_work(&dwork->work);
2919401a8d04STejun Heo }
2920401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
2921401a8d04STejun Heo 
2922401a8d04STejun Heo /**
292357b30ae7STejun Heo  * cancel_delayed_work - cancel a delayed work
292457b30ae7STejun Heo  * @dwork: delayed_work to cancel
292509383498STejun Heo  *
292657b30ae7STejun Heo  * Kill off a pending delayed_work.  Returns %true if @dwork was pending
292757b30ae7STejun Heo  * and canceled; %false if wasn't pending.  Note that the work callback
292857b30ae7STejun Heo  * function may still be running on return, unless it returns %true and the
292957b30ae7STejun Heo  * work doesn't re-arm itself.  Explicitly flush or use
293057b30ae7STejun Heo  * cancel_delayed_work_sync() to wait on it.
293109383498STejun Heo  *
293257b30ae7STejun Heo  * This function is safe to call from any context including IRQ handler.
293309383498STejun Heo  */
293457b30ae7STejun Heo bool cancel_delayed_work(struct delayed_work *dwork)
293509383498STejun Heo {
293657b30ae7STejun Heo 	unsigned long flags;
293757b30ae7STejun Heo 	int ret;
293857b30ae7STejun Heo 
293957b30ae7STejun Heo 	do {
294057b30ae7STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
294157b30ae7STejun Heo 	} while (unlikely(ret == -EAGAIN));
294257b30ae7STejun Heo 
294357b30ae7STejun Heo 	if (unlikely(ret < 0))
294457b30ae7STejun Heo 		return false;
294557b30ae7STejun Heo 
29467c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(&dwork->work,
29477c3eed5cSTejun Heo 					get_work_pool_id(&dwork->work));
294857b30ae7STejun Heo 	local_irq_restore(flags);
2949c0158ca6SDan Magenheimer 	return ret;
295009383498STejun Heo }
295157b30ae7STejun Heo EXPORT_SYMBOL(cancel_delayed_work);
295209383498STejun Heo 
295309383498STejun Heo /**
2954401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2955401a8d04STejun Heo  * @dwork: the delayed work cancel
2956401a8d04STejun Heo  *
2957401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
2958401a8d04STejun Heo  *
2959401a8d04STejun Heo  * RETURNS:
2960401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
2961401a8d04STejun Heo  */
2962401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
29636e84d644SOleg Nesterov {
296436e227d2STejun Heo 	return __cancel_work_timer(&dwork->work, true);
29656e84d644SOleg Nesterov }
2966f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
29671da177e4SLinus Torvalds 
29680fcb78c2SRolf Eike Beer /**
2969c1a220e7SZhang Rui  * schedule_work_on - put work task on a specific cpu
2970c1a220e7SZhang Rui  * @cpu: cpu to put the work task on
2971c1a220e7SZhang Rui  * @work: job to be done
2972c1a220e7SZhang Rui  *
2973c1a220e7SZhang Rui  * This puts a job on a specific cpu
2974c1a220e7SZhang Rui  */
2975d4283e93STejun Heo bool schedule_work_on(int cpu, struct work_struct *work)
2976c1a220e7SZhang Rui {
2977d320c038STejun Heo 	return queue_work_on(cpu, system_wq, work);
2978c1a220e7SZhang Rui }
2979c1a220e7SZhang Rui EXPORT_SYMBOL(schedule_work_on);
2980c1a220e7SZhang Rui 
29810fcb78c2SRolf Eike Beer /**
2982ae90dd5dSDave Jones  * schedule_work - put work task in global workqueue
29831da177e4SLinus Torvalds  * @work: job to be done
29841da177e4SLinus Torvalds  *
2985d4283e93STejun Heo  * Returns %false if @work was already on the kernel-global workqueue and
2986d4283e93STejun Heo  * %true otherwise.
298752bad64dSDavid Howells  *
29880fcb78c2SRolf Eike Beer  * This puts a job in the kernel-global workqueue if it was not already
29890fcb78c2SRolf Eike Beer  * queued and leaves it in the same position on the kernel-global
29900fcb78c2SRolf Eike Beer  * workqueue otherwise.
29911da177e4SLinus Torvalds  */
2992d4283e93STejun Heo bool schedule_work(struct work_struct *work)
29931da177e4SLinus Torvalds {
29940fcb78c2SRolf Eike Beer 	return queue_work(system_wq, work);
29951da177e4SLinus Torvalds }
29960fcb78c2SRolf Eike Beer EXPORT_SYMBOL(schedule_work);
29971da177e4SLinus Torvalds 
29980fcb78c2SRolf Eike Beer /**
29990fcb78c2SRolf Eike Beer  * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
30000fcb78c2SRolf Eike Beer  * @cpu: cpu to use
30010fcb78c2SRolf Eike Beer  * @dwork: job to be done
30020fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait
30030fcb78c2SRolf Eike Beer  *
30040fcb78c2SRolf Eike Beer  * After waiting for a given time this puts a job in the kernel-global
30050fcb78c2SRolf Eike Beer  * workqueue on the specified CPU.
30060fcb78c2SRolf Eike Beer  */
3007d4283e93STejun Heo bool schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
3008d4283e93STejun Heo 			      unsigned long delay)
30091da177e4SLinus Torvalds {
3010d320c038STejun Heo 	return queue_delayed_work_on(cpu, system_wq, dwork, delay);
30111da177e4SLinus Torvalds }
3012ae90dd5dSDave Jones EXPORT_SYMBOL(schedule_delayed_work_on);
30131da177e4SLinus Torvalds 
3014b6136773SAndrew Morton /**
30150a13c00eSTejun Heo  * schedule_delayed_work - put work task in global workqueue after delay
30160a13c00eSTejun Heo  * @dwork: job to be done
30170a13c00eSTejun Heo  * @delay: number of jiffies to wait or 0 for immediate execution
30180a13c00eSTejun Heo  *
30190a13c00eSTejun Heo  * After waiting for a given time this puts a job in the kernel-global
30200a13c00eSTejun Heo  * workqueue.
30210a13c00eSTejun Heo  */
3022d4283e93STejun Heo bool schedule_delayed_work(struct delayed_work *dwork, unsigned long delay)
30230a13c00eSTejun Heo {
30240a13c00eSTejun Heo 	return queue_delayed_work(system_wq, dwork, delay);
30250a13c00eSTejun Heo }
30260a13c00eSTejun Heo EXPORT_SYMBOL(schedule_delayed_work);
30270a13c00eSTejun Heo 
30280a13c00eSTejun Heo /**
302931ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
3030b6136773SAndrew Morton  * @func: the function to call
3031b6136773SAndrew Morton  *
303231ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
303331ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
3034b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
303531ddd871STejun Heo  *
303631ddd871STejun Heo  * RETURNS:
303731ddd871STejun Heo  * 0 on success, -errno on failure.
3038b6136773SAndrew Morton  */
303965f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
304015316ba8SChristoph Lameter {
304115316ba8SChristoph Lameter 	int cpu;
304238f51568SNamhyung Kim 	struct work_struct __percpu *works;
304315316ba8SChristoph Lameter 
3044b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
3045b6136773SAndrew Morton 	if (!works)
304615316ba8SChristoph Lameter 		return -ENOMEM;
3047b6136773SAndrew Morton 
304895402b38SGautham R Shenoy 	get_online_cpus();
304993981800STejun Heo 
305015316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
30519bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
30529bfb1839SIngo Molnar 
30539bfb1839SIngo Molnar 		INIT_WORK(work, func);
30548de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
305515316ba8SChristoph Lameter 	}
305693981800STejun Heo 
305793981800STejun Heo 	for_each_online_cpu(cpu)
30588616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
305993981800STejun Heo 
306095402b38SGautham R Shenoy 	put_online_cpus();
3061b6136773SAndrew Morton 	free_percpu(works);
306215316ba8SChristoph Lameter 	return 0;
306315316ba8SChristoph Lameter }
306415316ba8SChristoph Lameter 
3065eef6a7d5SAlan Stern /**
3066eef6a7d5SAlan Stern  * flush_scheduled_work - ensure that any scheduled work has run to completion.
3067eef6a7d5SAlan Stern  *
3068eef6a7d5SAlan Stern  * Forces execution of the kernel-global workqueue and blocks until its
3069eef6a7d5SAlan Stern  * completion.
3070eef6a7d5SAlan Stern  *
3071eef6a7d5SAlan Stern  * Think twice before calling this function!  It's very easy to get into
3072eef6a7d5SAlan Stern  * trouble if you don't take great care.  Either of the following situations
3073eef6a7d5SAlan Stern  * will lead to deadlock:
3074eef6a7d5SAlan Stern  *
3075eef6a7d5SAlan Stern  *	One of the work items currently on the workqueue needs to acquire
3076eef6a7d5SAlan Stern  *	a lock held by your code or its caller.
3077eef6a7d5SAlan Stern  *
3078eef6a7d5SAlan Stern  *	Your code is running in the context of a work routine.
3079eef6a7d5SAlan Stern  *
3080eef6a7d5SAlan Stern  * They will be detected by lockdep when they occur, but the first might not
3081eef6a7d5SAlan Stern  * occur very often.  It depends on what work items are on the workqueue and
3082eef6a7d5SAlan Stern  * what locks they need, which you have no control over.
3083eef6a7d5SAlan Stern  *
3084eef6a7d5SAlan Stern  * In most situations flushing the entire workqueue is overkill; you merely
3085eef6a7d5SAlan Stern  * need to know that a particular work item isn't queued and isn't running.
3086eef6a7d5SAlan Stern  * In such cases you should use cancel_delayed_work_sync() or
3087eef6a7d5SAlan Stern  * cancel_work_sync() instead.
3088eef6a7d5SAlan Stern  */
30891da177e4SLinus Torvalds void flush_scheduled_work(void)
30901da177e4SLinus Torvalds {
3091d320c038STejun Heo 	flush_workqueue(system_wq);
30921da177e4SLinus Torvalds }
3093ae90dd5dSDave Jones EXPORT_SYMBOL(flush_scheduled_work);
30941da177e4SLinus Torvalds 
30951da177e4SLinus Torvalds /**
30961fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
30971fa44ecaSJames Bottomley  * @fn:		the function to execute
30981fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
30991fa44ecaSJames Bottomley  *		be available when the work executes)
31001fa44ecaSJames Bottomley  *
31011fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
31021fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
31031fa44ecaSJames Bottomley  *
31041fa44ecaSJames Bottomley  * Returns:	0 - function was executed
31051fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
31061fa44ecaSJames Bottomley  */
310765f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
31081fa44ecaSJames Bottomley {
31091fa44ecaSJames Bottomley 	if (!in_interrupt()) {
311065f27f38SDavid Howells 		fn(&ew->work);
31111fa44ecaSJames Bottomley 		return 0;
31121fa44ecaSJames Bottomley 	}
31131fa44ecaSJames Bottomley 
311465f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
31151fa44ecaSJames Bottomley 	schedule_work(&ew->work);
31161fa44ecaSJames Bottomley 
31171fa44ecaSJames Bottomley 	return 1;
31181fa44ecaSJames Bottomley }
31191fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
31201fa44ecaSJames Bottomley 
31211da177e4SLinus Torvalds int keventd_up(void)
31221da177e4SLinus Torvalds {
3123d320c038STejun Heo 	return system_wq != NULL;
31241da177e4SLinus Torvalds }
31251da177e4SLinus Torvalds 
3126*7a4e344cSTejun Heo /**
3127*7a4e344cSTejun Heo  * free_workqueue_attrs - free a workqueue_attrs
3128*7a4e344cSTejun Heo  * @attrs: workqueue_attrs to free
3129*7a4e344cSTejun Heo  *
3130*7a4e344cSTejun Heo  * Undo alloc_workqueue_attrs().
3131*7a4e344cSTejun Heo  */
3132*7a4e344cSTejun Heo void free_workqueue_attrs(struct workqueue_attrs *attrs)
3133*7a4e344cSTejun Heo {
3134*7a4e344cSTejun Heo 	if (attrs) {
3135*7a4e344cSTejun Heo 		free_cpumask_var(attrs->cpumask);
3136*7a4e344cSTejun Heo 		kfree(attrs);
3137*7a4e344cSTejun Heo 	}
3138*7a4e344cSTejun Heo }
3139*7a4e344cSTejun Heo 
3140*7a4e344cSTejun Heo /**
3141*7a4e344cSTejun Heo  * alloc_workqueue_attrs - allocate a workqueue_attrs
3142*7a4e344cSTejun Heo  * @gfp_mask: allocation mask to use
3143*7a4e344cSTejun Heo  *
3144*7a4e344cSTejun Heo  * Allocate a new workqueue_attrs, initialize with default settings and
3145*7a4e344cSTejun Heo  * return it.  Returns NULL on failure.
3146*7a4e344cSTejun Heo  */
3147*7a4e344cSTejun Heo struct workqueue_attrs *alloc_workqueue_attrs(gfp_t gfp_mask)
3148*7a4e344cSTejun Heo {
3149*7a4e344cSTejun Heo 	struct workqueue_attrs *attrs;
3150*7a4e344cSTejun Heo 
3151*7a4e344cSTejun Heo 	attrs = kzalloc(sizeof(*attrs), gfp_mask);
3152*7a4e344cSTejun Heo 	if (!attrs)
3153*7a4e344cSTejun Heo 		goto fail;
3154*7a4e344cSTejun Heo 	if (!alloc_cpumask_var(&attrs->cpumask, gfp_mask))
3155*7a4e344cSTejun Heo 		goto fail;
3156*7a4e344cSTejun Heo 
3157*7a4e344cSTejun Heo 	cpumask_setall(attrs->cpumask);
3158*7a4e344cSTejun Heo 	return attrs;
3159*7a4e344cSTejun Heo fail:
3160*7a4e344cSTejun Heo 	free_workqueue_attrs(attrs);
3161*7a4e344cSTejun Heo 	return NULL;
3162*7a4e344cSTejun Heo }
3163*7a4e344cSTejun Heo 
3164*7a4e344cSTejun Heo /**
3165*7a4e344cSTejun Heo  * init_worker_pool - initialize a newly zalloc'd worker_pool
3166*7a4e344cSTejun Heo  * @pool: worker_pool to initialize
3167*7a4e344cSTejun Heo  *
3168*7a4e344cSTejun Heo  * Initiailize a newly zalloc'd @pool.  It also allocates @pool->attrs.
3169*7a4e344cSTejun Heo  * Returns 0 on success, -errno on failure.
3170*7a4e344cSTejun Heo  */
3171*7a4e344cSTejun Heo static int init_worker_pool(struct worker_pool *pool)
31724e1a1f9aSTejun Heo {
31734e1a1f9aSTejun Heo 	spin_lock_init(&pool->lock);
31744e1a1f9aSTejun Heo 	pool->flags |= POOL_DISASSOCIATED;
31754e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->worklist);
31764e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->idle_list);
31774e1a1f9aSTejun Heo 	hash_init(pool->busy_hash);
31784e1a1f9aSTejun Heo 
31794e1a1f9aSTejun Heo 	init_timer_deferrable(&pool->idle_timer);
31804e1a1f9aSTejun Heo 	pool->idle_timer.function = idle_worker_timeout;
31814e1a1f9aSTejun Heo 	pool->idle_timer.data = (unsigned long)pool;
31824e1a1f9aSTejun Heo 
31834e1a1f9aSTejun Heo 	setup_timer(&pool->mayday_timer, pool_mayday_timeout,
31844e1a1f9aSTejun Heo 		    (unsigned long)pool);
31854e1a1f9aSTejun Heo 
31864e1a1f9aSTejun Heo 	mutex_init(&pool->manager_arb);
31874e1a1f9aSTejun Heo 	mutex_init(&pool->assoc_mutex);
31884e1a1f9aSTejun Heo 	ida_init(&pool->worker_ida);
3189*7a4e344cSTejun Heo 
3190*7a4e344cSTejun Heo 	pool->attrs = alloc_workqueue_attrs(GFP_KERNEL);
3191*7a4e344cSTejun Heo 	if (!pool->attrs)
3192*7a4e344cSTejun Heo 		return -ENOMEM;
3193*7a4e344cSTejun Heo 	return 0;
31944e1a1f9aSTejun Heo }
31954e1a1f9aSTejun Heo 
319630cdf249STejun Heo static int alloc_and_link_pwqs(struct workqueue_struct *wq)
31971da177e4SLinus Torvalds {
319849e3cf44STejun Heo 	bool highpri = wq->flags & WQ_HIGHPRI;
319930cdf249STejun Heo 	int cpu;
3200e1d8aa9fSFrederic Weisbecker 
320130cdf249STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
3202420c0ddbSTejun Heo 		wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
3203420c0ddbSTejun Heo 		if (!wq->cpu_pwqs)
320430cdf249STejun Heo 			return -ENOMEM;
320530cdf249STejun Heo 
320630cdf249STejun Heo 		for_each_possible_cpu(cpu) {
32077fb98ea7STejun Heo 			struct pool_workqueue *pwq =
32087fb98ea7STejun Heo 				per_cpu_ptr(wq->cpu_pwqs, cpu);
320930cdf249STejun Heo 
321049e3cf44STejun Heo 			pwq->pool = get_std_worker_pool(cpu, highpri);
321176af4d93STejun Heo 			list_add_tail_rcu(&pwq->pwqs_node, &wq->pwqs);
321230cdf249STejun Heo 		}
321330cdf249STejun Heo 	} else {
321430cdf249STejun Heo 		struct pool_workqueue *pwq;
321530cdf249STejun Heo 
321630cdf249STejun Heo 		pwq = kmem_cache_zalloc(pwq_cache, GFP_KERNEL);
321730cdf249STejun Heo 		if (!pwq)
321830cdf249STejun Heo 			return -ENOMEM;
321930cdf249STejun Heo 
322049e3cf44STejun Heo 		pwq->pool = get_std_worker_pool(WORK_CPU_UNBOUND, highpri);
322176af4d93STejun Heo 		list_add_tail_rcu(&pwq->pwqs_node, &wq->pwqs);
322230cdf249STejun Heo 	}
322330cdf249STejun Heo 
322430cdf249STejun Heo 	return 0;
32250f900049STejun Heo }
32260f900049STejun Heo 
3227112202d9STejun Heo static void free_pwqs(struct workqueue_struct *wq)
322806ba38a9SOleg Nesterov {
3229e06ffa1eSLai Jiangshan 	if (!(wq->flags & WQ_UNBOUND))
3230420c0ddbSTejun Heo 		free_percpu(wq->cpu_pwqs);
3231420c0ddbSTejun Heo 	else if (!list_empty(&wq->pwqs))
3232420c0ddbSTejun Heo 		kmem_cache_free(pwq_cache, list_first_entry(&wq->pwqs,
3233420c0ddbSTejun Heo 					struct pool_workqueue, pwqs_node));
323406ba38a9SOleg Nesterov }
323506ba38a9SOleg Nesterov 
3236f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
3237f3421797STejun Heo 			       const char *name)
3238b71ab8c2STejun Heo {
3239f3421797STejun Heo 	int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3240f3421797STejun Heo 
3241f3421797STejun Heo 	if (max_active < 1 || max_active > lim)
3242044c782cSValentin Ilie 		pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3243f3421797STejun Heo 			max_active, name, 1, lim);
3244b71ab8c2STejun Heo 
3245f3421797STejun Heo 	return clamp_val(max_active, 1, lim);
3246b71ab8c2STejun Heo }
3247b71ab8c2STejun Heo 
3248b196be89STejun Heo struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
324997e37d7bSTejun Heo 					       unsigned int flags,
32501e19ffc6STejun Heo 					       int max_active,
3251eb13ba87SJohannes Berg 					       struct lock_class_key *key,
3252b196be89STejun Heo 					       const char *lock_name, ...)
32533af24433SOleg Nesterov {
3254b196be89STejun Heo 	va_list args, args1;
32553af24433SOleg Nesterov 	struct workqueue_struct *wq;
325649e3cf44STejun Heo 	struct pool_workqueue *pwq;
3257b196be89STejun Heo 	size_t namelen;
3258b196be89STejun Heo 
3259b196be89STejun Heo 	/* determine namelen, allocate wq and format name */
3260b196be89STejun Heo 	va_start(args, lock_name);
3261b196be89STejun Heo 	va_copy(args1, args);
3262b196be89STejun Heo 	namelen = vsnprintf(NULL, 0, fmt, args) + 1;
3263b196be89STejun Heo 
3264b196be89STejun Heo 	wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
3265b196be89STejun Heo 	if (!wq)
3266b196be89STejun Heo 		goto err;
3267b196be89STejun Heo 
3268b196be89STejun Heo 	vsnprintf(wq->name, namelen, fmt, args1);
3269b196be89STejun Heo 	va_end(args);
3270b196be89STejun Heo 	va_end(args1);
32713af24433SOleg Nesterov 
3272f3421797STejun Heo 	/*
32736370a6adSTejun Heo 	 * Workqueues which may be used during memory reclaim should
32746370a6adSTejun Heo 	 * have a rescuer to guarantee forward progress.
32756370a6adSTejun Heo 	 */
32766370a6adSTejun Heo 	if (flags & WQ_MEM_RECLAIM)
32776370a6adSTejun Heo 		flags |= WQ_RESCUER;
32786370a6adSTejun Heo 
3279d320c038STejun Heo 	max_active = max_active ?: WQ_DFL_ACTIVE;
3280b196be89STejun Heo 	max_active = wq_clamp_max_active(max_active, flags, wq->name);
32813af24433SOleg Nesterov 
3282b196be89STejun Heo 	/* init wq */
328397e37d7bSTejun Heo 	wq->flags = flags;
3284a0a1a5fdSTejun Heo 	wq->saved_max_active = max_active;
328573f53c4aSTejun Heo 	mutex_init(&wq->flush_mutex);
3286112202d9STejun Heo 	atomic_set(&wq->nr_pwqs_to_flush, 0);
328730cdf249STejun Heo 	INIT_LIST_HEAD(&wq->pwqs);
328873f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
328973f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
3290493a1724STejun Heo 	INIT_LIST_HEAD(&wq->maydays);
32913af24433SOleg Nesterov 
3292eb13ba87SJohannes Berg 	lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3293cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
32943af24433SOleg Nesterov 
329530cdf249STejun Heo 	if (alloc_and_link_pwqs(wq) < 0)
3296bdbc5dd7STejun Heo 		goto err;
3297bdbc5dd7STejun Heo 
329876af4d93STejun Heo 	local_irq_disable();
329949e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
3300112202d9STejun Heo 		BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3301112202d9STejun Heo 		pwq->wq = wq;
3302112202d9STejun Heo 		pwq->flush_color = -1;
3303112202d9STejun Heo 		pwq->max_active = max_active;
3304112202d9STejun Heo 		INIT_LIST_HEAD(&pwq->delayed_works);
3305493a1724STejun Heo 		INIT_LIST_HEAD(&pwq->mayday_node);
3306e22bee78STejun Heo 	}
330776af4d93STejun Heo 	local_irq_enable();
33081537663fSTejun Heo 
3309e22bee78STejun Heo 	if (flags & WQ_RESCUER) {
3310e22bee78STejun Heo 		struct worker *rescuer;
3311e22bee78STejun Heo 
3312e22bee78STejun Heo 		wq->rescuer = rescuer = alloc_worker();
3313e22bee78STejun Heo 		if (!rescuer)
3314e22bee78STejun Heo 			goto err;
3315e22bee78STejun Heo 
3316111c225aSTejun Heo 		rescuer->rescue_wq = wq;
3317111c225aSTejun Heo 		rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
3318b196be89STejun Heo 					       wq->name);
3319e22bee78STejun Heo 		if (IS_ERR(rescuer->task))
3320e22bee78STejun Heo 			goto err;
3321e22bee78STejun Heo 
3322e22bee78STejun Heo 		rescuer->task->flags |= PF_THREAD_BOUND;
3323e22bee78STejun Heo 		wake_up_process(rescuer->task);
33243af24433SOleg Nesterov 	}
33251537663fSTejun Heo 
33263af24433SOleg Nesterov 	/*
3327a0a1a5fdSTejun Heo 	 * workqueue_lock protects global freeze state and workqueues
3328a0a1a5fdSTejun Heo 	 * list.  Grab it, set max_active accordingly and add the new
3329a0a1a5fdSTejun Heo 	 * workqueue to workqueues list.
33303af24433SOleg Nesterov 	 */
3331e98d5b16STejun Heo 	spin_lock_irq(&workqueue_lock);
3332a0a1a5fdSTejun Heo 
333358a69cb4STejun Heo 	if (workqueue_freezing && wq->flags & WQ_FREEZABLE)
333449e3cf44STejun Heo 		for_each_pwq(pwq, wq)
333549e3cf44STejun Heo 			pwq->max_active = 0;
3336a0a1a5fdSTejun Heo 
33373af24433SOleg Nesterov 	list_add(&wq->list, &workqueues);
3338a0a1a5fdSTejun Heo 
3339e98d5b16STejun Heo 	spin_unlock_irq(&workqueue_lock);
33403af24433SOleg Nesterov 
33413af24433SOleg Nesterov 	return wq;
33424690c4abSTejun Heo err:
33434690c4abSTejun Heo 	if (wq) {
3344112202d9STejun Heo 		free_pwqs(wq);
3345e22bee78STejun Heo 		kfree(wq->rescuer);
33464690c4abSTejun Heo 		kfree(wq);
33473af24433SOleg Nesterov 	}
33484690c4abSTejun Heo 	return NULL;
33491da177e4SLinus Torvalds }
3350d320c038STejun Heo EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
33511da177e4SLinus Torvalds 
33523af24433SOleg Nesterov /**
33533af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
33543af24433SOleg Nesterov  * @wq: target workqueue
33553af24433SOleg Nesterov  *
33563af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
33573af24433SOleg Nesterov  */
33583af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
33593af24433SOleg Nesterov {
336049e3cf44STejun Heo 	struct pool_workqueue *pwq;
33613af24433SOleg Nesterov 
33629c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
33639c5a2ba7STejun Heo 	drain_workqueue(wq);
3364c8efcc25STejun Heo 
336576af4d93STejun Heo 	spin_lock_irq(&workqueue_lock);
336676af4d93STejun Heo 
33676183c009STejun Heo 	/* sanity checks */
336849e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
33696183c009STejun Heo 		int i;
33706183c009STejun Heo 
337176af4d93STejun Heo 		for (i = 0; i < WORK_NR_COLORS; i++) {
337276af4d93STejun Heo 			if (WARN_ON(pwq->nr_in_flight[i])) {
337376af4d93STejun Heo 				spin_unlock_irq(&workqueue_lock);
33746183c009STejun Heo 				return;
337576af4d93STejun Heo 			}
337676af4d93STejun Heo 		}
337776af4d93STejun Heo 
33786183c009STejun Heo 		if (WARN_ON(pwq->nr_active) ||
337976af4d93STejun Heo 		    WARN_ON(!list_empty(&pwq->delayed_works))) {
338076af4d93STejun Heo 			spin_unlock_irq(&workqueue_lock);
33816183c009STejun Heo 			return;
33826183c009STejun Heo 		}
338376af4d93STejun Heo 	}
33846183c009STejun Heo 
3385a0a1a5fdSTejun Heo 	/*
3386a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
3387a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
3388a0a1a5fdSTejun Heo 	 */
33893af24433SOleg Nesterov 	list_del(&wq->list);
339076af4d93STejun Heo 
3391e98d5b16STejun Heo 	spin_unlock_irq(&workqueue_lock);
33923af24433SOleg Nesterov 
3393e22bee78STejun Heo 	if (wq->flags & WQ_RESCUER) {
3394e22bee78STejun Heo 		kthread_stop(wq->rescuer->task);
33958d9df9f0SXiaotian Feng 		kfree(wq->rescuer);
3396e22bee78STejun Heo 	}
3397e22bee78STejun Heo 
3398112202d9STejun Heo 	free_pwqs(wq);
33993af24433SOleg Nesterov 	kfree(wq);
34003af24433SOleg Nesterov }
34013af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
34023af24433SOleg Nesterov 
3403dcd989cbSTejun Heo /**
3404112202d9STejun Heo  * pwq_set_max_active - adjust max_active of a pwq
3405112202d9STejun Heo  * @pwq: target pool_workqueue
34069f4bd4cdSLai Jiangshan  * @max_active: new max_active value.
34079f4bd4cdSLai Jiangshan  *
3408112202d9STejun Heo  * Set @pwq->max_active to @max_active and activate delayed works if
34099f4bd4cdSLai Jiangshan  * increased.
34109f4bd4cdSLai Jiangshan  *
34119f4bd4cdSLai Jiangshan  * CONTEXT:
3412d565ed63STejun Heo  * spin_lock_irq(pool->lock).
34139f4bd4cdSLai Jiangshan  */
3414112202d9STejun Heo static void pwq_set_max_active(struct pool_workqueue *pwq, int max_active)
34159f4bd4cdSLai Jiangshan {
3416112202d9STejun Heo 	pwq->max_active = max_active;
34179f4bd4cdSLai Jiangshan 
3418112202d9STejun Heo 	while (!list_empty(&pwq->delayed_works) &&
3419112202d9STejun Heo 	       pwq->nr_active < pwq->max_active)
3420112202d9STejun Heo 		pwq_activate_first_delayed(pwq);
34219f4bd4cdSLai Jiangshan }
34229f4bd4cdSLai Jiangshan 
34239f4bd4cdSLai Jiangshan /**
3424dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
3425dcd989cbSTejun Heo  * @wq: target workqueue
3426dcd989cbSTejun Heo  * @max_active: new max_active value.
3427dcd989cbSTejun Heo  *
3428dcd989cbSTejun Heo  * Set max_active of @wq to @max_active.
3429dcd989cbSTejun Heo  *
3430dcd989cbSTejun Heo  * CONTEXT:
3431dcd989cbSTejun Heo  * Don't call from IRQ context.
3432dcd989cbSTejun Heo  */
3433dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
3434dcd989cbSTejun Heo {
343549e3cf44STejun Heo 	struct pool_workqueue *pwq;
3436dcd989cbSTejun Heo 
3437f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
3438dcd989cbSTejun Heo 
3439e98d5b16STejun Heo 	spin_lock_irq(&workqueue_lock);
3440dcd989cbSTejun Heo 
3441dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
3442dcd989cbSTejun Heo 
344349e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
3444112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
3445dcd989cbSTejun Heo 
3446e98d5b16STejun Heo 		spin_lock(&pool->lock);
3447dcd989cbSTejun Heo 
344858a69cb4STejun Heo 		if (!(wq->flags & WQ_FREEZABLE) ||
344935b6bb63STejun Heo 		    !(pool->flags & POOL_FREEZING))
3450112202d9STejun Heo 			pwq_set_max_active(pwq, max_active);
3451dcd989cbSTejun Heo 
3452e98d5b16STejun Heo 		spin_unlock(&pool->lock);
3453dcd989cbSTejun Heo 	}
3454dcd989cbSTejun Heo 
3455e98d5b16STejun Heo 	spin_unlock_irq(&workqueue_lock);
3456dcd989cbSTejun Heo }
3457dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
3458dcd989cbSTejun Heo 
3459dcd989cbSTejun Heo /**
3460dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
3461dcd989cbSTejun Heo  * @cpu: CPU in question
3462dcd989cbSTejun Heo  * @wq: target workqueue
3463dcd989cbSTejun Heo  *
3464dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
3465dcd989cbSTejun Heo  * no synchronization around this function and the test result is
3466dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
3467dcd989cbSTejun Heo  *
3468dcd989cbSTejun Heo  * RETURNS:
3469dcd989cbSTejun Heo  * %true if congested, %false otherwise.
3470dcd989cbSTejun Heo  */
3471d84ff051STejun Heo bool workqueue_congested(int cpu, struct workqueue_struct *wq)
3472dcd989cbSTejun Heo {
34737fb98ea7STejun Heo 	struct pool_workqueue *pwq;
347476af4d93STejun Heo 	bool ret;
347576af4d93STejun Heo 
347676af4d93STejun Heo 	preempt_disable();
34777fb98ea7STejun Heo 
34787fb98ea7STejun Heo 	if (!(wq->flags & WQ_UNBOUND))
34797fb98ea7STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
34807fb98ea7STejun Heo 	else
34817fb98ea7STejun Heo 		pwq = first_pwq(wq);
3482dcd989cbSTejun Heo 
348376af4d93STejun Heo 	ret = !list_empty(&pwq->delayed_works);
348476af4d93STejun Heo 	preempt_enable();
348576af4d93STejun Heo 
348676af4d93STejun Heo 	return ret;
3487dcd989cbSTejun Heo }
3488dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
3489dcd989cbSTejun Heo 
3490dcd989cbSTejun Heo /**
3491dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
3492dcd989cbSTejun Heo  * @work: the work to be tested
3493dcd989cbSTejun Heo  *
3494dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
3495dcd989cbSTejun Heo  * synchronization around this function and the test result is
3496dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
3497dcd989cbSTejun Heo  *
3498dcd989cbSTejun Heo  * RETURNS:
3499dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
3500dcd989cbSTejun Heo  */
3501dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
3502dcd989cbSTejun Heo {
3503fa1b54e6STejun Heo 	struct worker_pool *pool;
3504dcd989cbSTejun Heo 	unsigned long flags;
3505dcd989cbSTejun Heo 	unsigned int ret = 0;
3506dcd989cbSTejun Heo 
3507dcd989cbSTejun Heo 	if (work_pending(work))
3508dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
3509038366c5SLai Jiangshan 
3510fa1b54e6STejun Heo 	local_irq_save(flags);
3511fa1b54e6STejun Heo 	pool = get_work_pool(work);
3512038366c5SLai Jiangshan 	if (pool) {
3513fa1b54e6STejun Heo 		spin_lock(&pool->lock);
3514c9e7cf27STejun Heo 		if (find_worker_executing_work(pool, work))
3515dcd989cbSTejun Heo 			ret |= WORK_BUSY_RUNNING;
3516fa1b54e6STejun Heo 		spin_unlock(&pool->lock);
3517038366c5SLai Jiangshan 	}
3518fa1b54e6STejun Heo 	local_irq_restore(flags);
3519dcd989cbSTejun Heo 
3520dcd989cbSTejun Heo 	return ret;
3521dcd989cbSTejun Heo }
3522dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
3523dcd989cbSTejun Heo 
3524db7bccf4STejun Heo /*
3525db7bccf4STejun Heo  * CPU hotplug.
3526db7bccf4STejun Heo  *
3527e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
3528112202d9STejun Heo  * are a lot of assumptions on strong associations among work, pwq and
3529706026c2STejun Heo  * pool which make migrating pending and scheduled works very
3530e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
353194cf58bbSTejun Heo  * worker pools serve mix of short, long and very long running works making
3532e22bee78STejun Heo  * blocked draining impractical.
3533e22bee78STejun Heo  *
353424647570STejun Heo  * This is solved by allowing the pools to be disassociated from the CPU
3535628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
3536628c78e7STejun Heo  * cpu comes back online.
3537db7bccf4STejun Heo  */
3538db7bccf4STejun Heo 
3539706026c2STejun Heo static void wq_unbind_fn(struct work_struct *work)
3540db7bccf4STejun Heo {
354138db41d9STejun Heo 	int cpu = smp_processor_id();
35424ce62e9eSTejun Heo 	struct worker_pool *pool;
3543db7bccf4STejun Heo 	struct worker *worker;
3544db7bccf4STejun Heo 	int i;
3545db7bccf4STejun Heo 
354638db41d9STejun Heo 	for_each_std_worker_pool(pool, cpu) {
35476183c009STejun Heo 		WARN_ON_ONCE(cpu != smp_processor_id());
3548db7bccf4STejun Heo 
354994cf58bbSTejun Heo 		mutex_lock(&pool->assoc_mutex);
355094cf58bbSTejun Heo 		spin_lock_irq(&pool->lock);
3551e22bee78STejun Heo 
3552f2d5a0eeSTejun Heo 		/*
355394cf58bbSTejun Heo 		 * We've claimed all manager positions.  Make all workers
355494cf58bbSTejun Heo 		 * unbound and set DISASSOCIATED.  Before this, all workers
355594cf58bbSTejun Heo 		 * except for the ones which are still executing works from
355694cf58bbSTejun Heo 		 * before the last CPU down must be on the cpu.  After
355794cf58bbSTejun Heo 		 * this, they may become diasporas.
3558f2d5a0eeSTejun Heo 		 */
35594ce62e9eSTejun Heo 		list_for_each_entry(worker, &pool->idle_list, entry)
3560403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
3561db7bccf4STejun Heo 
3562b67bfe0dSSasha Levin 		for_each_busy_worker(worker, i, pool)
3563403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
3564db7bccf4STejun Heo 
356524647570STejun Heo 		pool->flags |= POOL_DISASSOCIATED;
3566f2d5a0eeSTejun Heo 
356794cf58bbSTejun Heo 		spin_unlock_irq(&pool->lock);
356894cf58bbSTejun Heo 		mutex_unlock(&pool->assoc_mutex);
356994cf58bbSTejun Heo 	}
3570e22bee78STejun Heo 
3571e22bee78STejun Heo 	/*
3572628c78e7STejun Heo 	 * Call schedule() so that we cross rq->lock and thus can guarantee
3573628c78e7STejun Heo 	 * sched callbacks see the %WORKER_UNBOUND flag.  This is necessary
3574628c78e7STejun Heo 	 * as scheduler callbacks may be invoked from other cpus.
3575628c78e7STejun Heo 	 */
3576628c78e7STejun Heo 	schedule();
3577628c78e7STejun Heo 
3578628c78e7STejun Heo 	/*
3579628c78e7STejun Heo 	 * Sched callbacks are disabled now.  Zap nr_running.  After this,
3580628c78e7STejun Heo 	 * nr_running stays zero and need_more_worker() and keep_working()
358138db41d9STejun Heo 	 * are always true as long as the worklist is not empty.  Pools on
358238db41d9STejun Heo 	 * @cpu now behave as unbound (in terms of concurrency management)
358338db41d9STejun Heo 	 * pools which are served by workers tied to the CPU.
3584628c78e7STejun Heo 	 *
3585628c78e7STejun Heo 	 * On return from this function, the current worker would trigger
3586628c78e7STejun Heo 	 * unbound chain execution of pending work items if other workers
3587628c78e7STejun Heo 	 * didn't already.
3588e22bee78STejun Heo 	 */
358938db41d9STejun Heo 	for_each_std_worker_pool(pool, cpu)
3590e19e397aSTejun Heo 		atomic_set(&pool->nr_running, 0);
3591db7bccf4STejun Heo }
3592db7bccf4STejun Heo 
35938db25e78STejun Heo /*
35948db25e78STejun Heo  * Workqueues should be brought up before normal priority CPU notifiers.
35958db25e78STejun Heo  * This will be registered high priority CPU notifier.
35968db25e78STejun Heo  */
35979fdf9b73SLai Jiangshan static int __cpuinit workqueue_cpu_up_callback(struct notifier_block *nfb,
35981da177e4SLinus Torvalds 					       unsigned long action,
35991da177e4SLinus Torvalds 					       void *hcpu)
36001da177e4SLinus Torvalds {
3601d84ff051STejun Heo 	int cpu = (unsigned long)hcpu;
36024ce62e9eSTejun Heo 	struct worker_pool *pool;
36031da177e4SLinus Torvalds 
36048db25e78STejun Heo 	switch (action & ~CPU_TASKS_FROZEN) {
36053af24433SOleg Nesterov 	case CPU_UP_PREPARE:
360638db41d9STejun Heo 		for_each_std_worker_pool(pool, cpu) {
36073ce63377STejun Heo 			struct worker *worker;
36083ce63377STejun Heo 
36093ce63377STejun Heo 			if (pool->nr_workers)
36103ce63377STejun Heo 				continue;
36113ce63377STejun Heo 
36123ce63377STejun Heo 			worker = create_worker(pool);
36133ce63377STejun Heo 			if (!worker)
36143ce63377STejun Heo 				return NOTIFY_BAD;
36153ce63377STejun Heo 
3616d565ed63STejun Heo 			spin_lock_irq(&pool->lock);
36173ce63377STejun Heo 			start_worker(worker);
3618d565ed63STejun Heo 			spin_unlock_irq(&pool->lock);
36193af24433SOleg Nesterov 		}
36201da177e4SLinus Torvalds 		break;
36211da177e4SLinus Torvalds 
362265758202STejun Heo 	case CPU_DOWN_FAILED:
362365758202STejun Heo 	case CPU_ONLINE:
362438db41d9STejun Heo 		for_each_std_worker_pool(pool, cpu) {
362594cf58bbSTejun Heo 			mutex_lock(&pool->assoc_mutex);
362694cf58bbSTejun Heo 			spin_lock_irq(&pool->lock);
362794cf58bbSTejun Heo 
362824647570STejun Heo 			pool->flags &= ~POOL_DISASSOCIATED;
362994cf58bbSTejun Heo 			rebind_workers(pool);
363094cf58bbSTejun Heo 
363194cf58bbSTejun Heo 			spin_unlock_irq(&pool->lock);
363294cf58bbSTejun Heo 			mutex_unlock(&pool->assoc_mutex);
363394cf58bbSTejun Heo 		}
36348db25e78STejun Heo 		break;
363565758202STejun Heo 	}
363665758202STejun Heo 	return NOTIFY_OK;
363765758202STejun Heo }
363865758202STejun Heo 
363965758202STejun Heo /*
364065758202STejun Heo  * Workqueues should be brought down after normal priority CPU notifiers.
364165758202STejun Heo  * This will be registered as low priority CPU notifier.
364265758202STejun Heo  */
36439fdf9b73SLai Jiangshan static int __cpuinit workqueue_cpu_down_callback(struct notifier_block *nfb,
364465758202STejun Heo 						 unsigned long action,
364565758202STejun Heo 						 void *hcpu)
364665758202STejun Heo {
3647d84ff051STejun Heo 	int cpu = (unsigned long)hcpu;
36488db25e78STejun Heo 	struct work_struct unbind_work;
36498db25e78STejun Heo 
365065758202STejun Heo 	switch (action & ~CPU_TASKS_FROZEN) {
365165758202STejun Heo 	case CPU_DOWN_PREPARE:
36528db25e78STejun Heo 		/* unbinding should happen on the local CPU */
3653706026c2STejun Heo 		INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
36547635d2fdSJoonsoo Kim 		queue_work_on(cpu, system_highpri_wq, &unbind_work);
36558db25e78STejun Heo 		flush_work(&unbind_work);
36568db25e78STejun Heo 		break;
365765758202STejun Heo 	}
365865758202STejun Heo 	return NOTIFY_OK;
365965758202STejun Heo }
366065758202STejun Heo 
36612d3854a3SRusty Russell #ifdef CONFIG_SMP
36628ccad40dSRusty Russell 
36632d3854a3SRusty Russell struct work_for_cpu {
3664ed48ece2STejun Heo 	struct work_struct work;
36652d3854a3SRusty Russell 	long (*fn)(void *);
36662d3854a3SRusty Russell 	void *arg;
36672d3854a3SRusty Russell 	long ret;
36682d3854a3SRusty Russell };
36692d3854a3SRusty Russell 
3670ed48ece2STejun Heo static void work_for_cpu_fn(struct work_struct *work)
36712d3854a3SRusty Russell {
3672ed48ece2STejun Heo 	struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
3673ed48ece2STejun Heo 
36742d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
36752d3854a3SRusty Russell }
36762d3854a3SRusty Russell 
36772d3854a3SRusty Russell /**
36782d3854a3SRusty Russell  * work_on_cpu - run a function in user context on a particular cpu
36792d3854a3SRusty Russell  * @cpu: the cpu to run on
36802d3854a3SRusty Russell  * @fn: the function to run
36812d3854a3SRusty Russell  * @arg: the function arg
36822d3854a3SRusty Russell  *
368331ad9081SRusty Russell  * This will return the value @fn returns.
368431ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
36856b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
36862d3854a3SRusty Russell  */
3687d84ff051STejun Heo long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
36882d3854a3SRusty Russell {
3689ed48ece2STejun Heo 	struct work_for_cpu wfc = { .fn = fn, .arg = arg };
36902d3854a3SRusty Russell 
3691ed48ece2STejun Heo 	INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
3692ed48ece2STejun Heo 	schedule_work_on(cpu, &wfc.work);
3693ed48ece2STejun Heo 	flush_work(&wfc.work);
36942d3854a3SRusty Russell 	return wfc.ret;
36952d3854a3SRusty Russell }
36962d3854a3SRusty Russell EXPORT_SYMBOL_GPL(work_on_cpu);
36972d3854a3SRusty Russell #endif /* CONFIG_SMP */
36982d3854a3SRusty Russell 
3699a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
3700e7577c50SRusty Russell 
3701a0a1a5fdSTejun Heo /**
3702a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
3703a0a1a5fdSTejun Heo  *
370458a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
370558a69cb4STejun Heo  * workqueues will queue new works to their frozen_works list instead of
3706706026c2STejun Heo  * pool->worklist.
3707a0a1a5fdSTejun Heo  *
3708a0a1a5fdSTejun Heo  * CONTEXT:
3709d565ed63STejun Heo  * Grabs and releases workqueue_lock and pool->lock's.
3710a0a1a5fdSTejun Heo  */
3711a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
3712a0a1a5fdSTejun Heo {
371317116969STejun Heo 	struct worker_pool *pool;
371424b8a847STejun Heo 	struct workqueue_struct *wq;
371524b8a847STejun Heo 	struct pool_workqueue *pwq;
371617116969STejun Heo 	int id;
3717a0a1a5fdSTejun Heo 
3718e98d5b16STejun Heo 	spin_lock_irq(&workqueue_lock);
3719a0a1a5fdSTejun Heo 
37206183c009STejun Heo 	WARN_ON_ONCE(workqueue_freezing);
3721a0a1a5fdSTejun Heo 	workqueue_freezing = true;
3722a0a1a5fdSTejun Heo 
372324b8a847STejun Heo 	/* set FREEZING */
372417116969STejun Heo 	for_each_pool(pool, id) {
3725e98d5b16STejun Heo 		spin_lock(&pool->lock);
372635b6bb63STejun Heo 		WARN_ON_ONCE(pool->flags & POOL_FREEZING);
372735b6bb63STejun Heo 		pool->flags |= POOL_FREEZING;
372824b8a847STejun Heo 		spin_unlock(&pool->lock);
37291da177e4SLinus Torvalds 	}
37308b03ae3cSTejun Heo 
373124b8a847STejun Heo 	/* suppress further executions by setting max_active to zero */
373224b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
373324b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
373424b8a847STejun Heo 			continue;
373524b8a847STejun Heo 
373624b8a847STejun Heo 		for_each_pwq(pwq, wq) {
373724b8a847STejun Heo 			spin_lock(&pwq->pool->lock);
373824b8a847STejun Heo 			pwq->max_active = 0;
373924b8a847STejun Heo 			spin_unlock(&pwq->pool->lock);
374024b8a847STejun Heo 		}
3741a1056305STejun Heo 	}
3742a0a1a5fdSTejun Heo 
3743e98d5b16STejun Heo 	spin_unlock_irq(&workqueue_lock);
3744a0a1a5fdSTejun Heo }
3745a0a1a5fdSTejun Heo 
3746a0a1a5fdSTejun Heo /**
374758a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
3748a0a1a5fdSTejun Heo  *
3749a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
3750a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
3751a0a1a5fdSTejun Heo  *
3752a0a1a5fdSTejun Heo  * CONTEXT:
3753a0a1a5fdSTejun Heo  * Grabs and releases workqueue_lock.
3754a0a1a5fdSTejun Heo  *
3755a0a1a5fdSTejun Heo  * RETURNS:
375658a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
375758a69cb4STejun Heo  * is complete.
3758a0a1a5fdSTejun Heo  */
3759a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
3760a0a1a5fdSTejun Heo {
3761a0a1a5fdSTejun Heo 	bool busy = false;
376224b8a847STejun Heo 	struct workqueue_struct *wq;
376324b8a847STejun Heo 	struct pool_workqueue *pwq;
3764a0a1a5fdSTejun Heo 
3765e98d5b16STejun Heo 	spin_lock_irq(&workqueue_lock);
3766a0a1a5fdSTejun Heo 
37676183c009STejun Heo 	WARN_ON_ONCE(!workqueue_freezing);
3768a0a1a5fdSTejun Heo 
376924b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
377024b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
377124b8a847STejun Heo 			continue;
3772a0a1a5fdSTejun Heo 		/*
3773a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
3774a0a1a5fdSTejun Heo 		 * to peek without lock.
3775a0a1a5fdSTejun Heo 		 */
377624b8a847STejun Heo 		for_each_pwq(pwq, wq) {
37776183c009STejun Heo 			WARN_ON_ONCE(pwq->nr_active < 0);
3778112202d9STejun Heo 			if (pwq->nr_active) {
3779a0a1a5fdSTejun Heo 				busy = true;
3780a0a1a5fdSTejun Heo 				goto out_unlock;
3781a0a1a5fdSTejun Heo 			}
3782a0a1a5fdSTejun Heo 		}
3783a0a1a5fdSTejun Heo 	}
3784a0a1a5fdSTejun Heo out_unlock:
3785e98d5b16STejun Heo 	spin_unlock_irq(&workqueue_lock);
3786a0a1a5fdSTejun Heo 	return busy;
3787a0a1a5fdSTejun Heo }
3788a0a1a5fdSTejun Heo 
3789a0a1a5fdSTejun Heo /**
3790a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
3791a0a1a5fdSTejun Heo  *
3792a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
3793706026c2STejun Heo  * frozen works are transferred to their respective pool worklists.
3794a0a1a5fdSTejun Heo  *
3795a0a1a5fdSTejun Heo  * CONTEXT:
3796d565ed63STejun Heo  * Grabs and releases workqueue_lock and pool->lock's.
3797a0a1a5fdSTejun Heo  */
3798a0a1a5fdSTejun Heo void thaw_workqueues(void)
3799a0a1a5fdSTejun Heo {
380024b8a847STejun Heo 	struct workqueue_struct *wq;
380124b8a847STejun Heo 	struct pool_workqueue *pwq;
380224b8a847STejun Heo 	struct worker_pool *pool;
380324b8a847STejun Heo 	int id;
3804a0a1a5fdSTejun Heo 
3805e98d5b16STejun Heo 	spin_lock_irq(&workqueue_lock);
3806a0a1a5fdSTejun Heo 
3807a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
3808a0a1a5fdSTejun Heo 		goto out_unlock;
3809a0a1a5fdSTejun Heo 
381024b8a847STejun Heo 	/* clear FREEZING */
381124b8a847STejun Heo 	for_each_pool(pool, id) {
3812e98d5b16STejun Heo 		spin_lock(&pool->lock);
381335b6bb63STejun Heo 		WARN_ON_ONCE(!(pool->flags & POOL_FREEZING));
381435b6bb63STejun Heo 		pool->flags &= ~POOL_FREEZING;
3815e98d5b16STejun Heo 		spin_unlock(&pool->lock);
3816d565ed63STejun Heo 	}
381724b8a847STejun Heo 
381824b8a847STejun Heo 	/* restore max_active and repopulate worklist */
381924b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
382024b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
382124b8a847STejun Heo 			continue;
382224b8a847STejun Heo 
382324b8a847STejun Heo 		for_each_pwq(pwq, wq) {
382424b8a847STejun Heo 			spin_lock(&pwq->pool->lock);
382524b8a847STejun Heo 			pwq_set_max_active(pwq, wq->saved_max_active);
382624b8a847STejun Heo 			spin_unlock(&pwq->pool->lock);
382724b8a847STejun Heo 		}
382824b8a847STejun Heo 	}
382924b8a847STejun Heo 
383024b8a847STejun Heo 	/* kick workers */
383124b8a847STejun Heo 	for_each_pool(pool, id) {
383224b8a847STejun Heo 		spin_lock(&pool->lock);
383324b8a847STejun Heo 		wake_up_worker(pool);
383424b8a847STejun Heo 		spin_unlock(&pool->lock);
3835a0a1a5fdSTejun Heo 	}
3836a0a1a5fdSTejun Heo 
3837a0a1a5fdSTejun Heo 	workqueue_freezing = false;
3838a0a1a5fdSTejun Heo out_unlock:
3839e98d5b16STejun Heo 	spin_unlock_irq(&workqueue_lock);
3840a0a1a5fdSTejun Heo }
3841a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
3842a0a1a5fdSTejun Heo 
38436ee0578bSSuresh Siddha static int __init init_workqueues(void)
38441da177e4SLinus Torvalds {
3845*7a4e344cSTejun Heo 	int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
3846*7a4e344cSTejun Heo 	int i, cpu;
3847c34056a3STejun Heo 
38487c3eed5cSTejun Heo 	/* make sure we have enough bits for OFFQ pool ID */
38497c3eed5cSTejun Heo 	BUILD_BUG_ON((1LU << (BITS_PER_LONG - WORK_OFFQ_POOL_SHIFT)) <
38506be19588SLai Jiangshan 		     WORK_CPU_END * NR_STD_WORKER_POOLS);
3851b5490077STejun Heo 
3852e904e6c2STejun Heo 	WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
3853e904e6c2STejun Heo 
3854e904e6c2STejun Heo 	pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
3855e904e6c2STejun Heo 
385665758202STejun Heo 	cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
3857a5b4e57dSLai Jiangshan 	hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
38588b03ae3cSTejun Heo 
3859706026c2STejun Heo 	/* initialize CPU pools */
3860706026c2STejun Heo 	for_each_wq_cpu(cpu) {
38614ce62e9eSTejun Heo 		struct worker_pool *pool;
38628b03ae3cSTejun Heo 
3863*7a4e344cSTejun Heo 		i = 0;
386438db41d9STejun Heo 		for_each_std_worker_pool(pool, cpu) {
3865*7a4e344cSTejun Heo 			BUG_ON(init_worker_pool(pool));
3866ec22ca5eSTejun Heo 			pool->cpu = cpu;
38679daf9e67STejun Heo 
3868*7a4e344cSTejun Heo 			if (cpu != WORK_CPU_UNBOUND)
3869*7a4e344cSTejun Heo 				cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
3870*7a4e344cSTejun Heo 			else
3871*7a4e344cSTejun Heo 				cpumask_setall(pool->attrs->cpumask);
3872*7a4e344cSTejun Heo 
3873*7a4e344cSTejun Heo 			pool->attrs->nice = std_nice[i++];
3874*7a4e344cSTejun Heo 
38759daf9e67STejun Heo 			/* alloc pool ID */
38769daf9e67STejun Heo 			BUG_ON(worker_pool_assign_id(pool));
38774ce62e9eSTejun Heo 		}
38788b03ae3cSTejun Heo 	}
38798b03ae3cSTejun Heo 
3880e22bee78STejun Heo 	/* create the initial worker */
3881706026c2STejun Heo 	for_each_online_wq_cpu(cpu) {
38824ce62e9eSTejun Heo 		struct worker_pool *pool;
3883e22bee78STejun Heo 
388438db41d9STejun Heo 		for_each_std_worker_pool(pool, cpu) {
38854ce62e9eSTejun Heo 			struct worker *worker;
38864ce62e9eSTejun Heo 
388724647570STejun Heo 			if (cpu != WORK_CPU_UNBOUND)
388824647570STejun Heo 				pool->flags &= ~POOL_DISASSOCIATED;
388924647570STejun Heo 
3890bc2ae0f5STejun Heo 			worker = create_worker(pool);
3891e22bee78STejun Heo 			BUG_ON(!worker);
3892d565ed63STejun Heo 			spin_lock_irq(&pool->lock);
3893e22bee78STejun Heo 			start_worker(worker);
3894d565ed63STejun Heo 			spin_unlock_irq(&pool->lock);
3895e22bee78STejun Heo 		}
38964ce62e9eSTejun Heo 	}
3897e22bee78STejun Heo 
3898d320c038STejun Heo 	system_wq = alloc_workqueue("events", 0, 0);
38991aabe902SJoonsoo Kim 	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
3900d320c038STejun Heo 	system_long_wq = alloc_workqueue("events_long", 0, 0);
3901f3421797STejun Heo 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
3902f3421797STejun Heo 					    WQ_UNBOUND_MAX_ACTIVE);
390324d51addSTejun Heo 	system_freezable_wq = alloc_workqueue("events_freezable",
390424d51addSTejun Heo 					      WQ_FREEZABLE, 0);
39051aabe902SJoonsoo Kim 	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
3906ae930e0fSTejun Heo 	       !system_unbound_wq || !system_freezable_wq);
39076ee0578bSSuresh Siddha 	return 0;
39081da177e4SLinus Torvalds }
39096ee0578bSSuresh Siddha early_initcall(init_workqueues);
3910