xref: /linux-6.15/kernel/workqueue.c (revision 7635d2fd)
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>
44e22bee78STejun Heo 
45e22bee78STejun Heo #include "workqueue_sched.h"
461da177e4SLinus Torvalds 
47c8e55f36STejun Heo enum {
48bc2ae0f5STejun Heo 	/*
49bc2ae0f5STejun Heo 	 * global_cwq flags
50bc2ae0f5STejun Heo 	 *
51bc2ae0f5STejun Heo 	 * A bound gcwq is either associated or disassociated with its CPU.
52bc2ae0f5STejun Heo 	 * While associated (!DISASSOCIATED), all workers are bound to the
53bc2ae0f5STejun Heo 	 * CPU and none has %WORKER_UNBOUND set and concurrency management
54bc2ae0f5STejun Heo 	 * is in effect.
55bc2ae0f5STejun Heo 	 *
56bc2ae0f5STejun Heo 	 * While DISASSOCIATED, the cpu may be offline and all workers have
57bc2ae0f5STejun Heo 	 * %WORKER_UNBOUND set and concurrency management disabled, and may
58bc2ae0f5STejun Heo 	 * be executing on any CPU.  The gcwq behaves as an unbound one.
59bc2ae0f5STejun Heo 	 *
60bc2ae0f5STejun Heo 	 * Note that DISASSOCIATED can be flipped only while holding
61bc2ae0f5STejun Heo 	 * managership of all pools on the gcwq to avoid changing binding
62bc2ae0f5STejun Heo 	 * state while create_worker() is in progress.
63bc2ae0f5STejun Heo 	 */
6411ebea50STejun Heo 	GCWQ_DISASSOCIATED	= 1 << 0,	/* cpu can't serve workers */
6511ebea50STejun Heo 	GCWQ_FREEZING		= 1 << 1,	/* freeze in progress */
6611ebea50STejun Heo 
6711ebea50STejun Heo 	/* pool flags */
6811ebea50STejun Heo 	POOL_MANAGE_WORKERS	= 1 << 0,	/* need to manage workers */
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 */
75e22bee78STejun Heo 	WORKER_REBIND		= 1 << 5,	/* mom is home, come back */
76fb0e7bebSTejun Heo 	WORKER_CPU_INTENSIVE	= 1 << 6,	/* cpu intensive */
77f3421797STejun Heo 	WORKER_UNBOUND		= 1 << 7,	/* worker is unbound */
78e22bee78STejun Heo 
79403c821dSTejun Heo 	WORKER_NOT_RUNNING	= WORKER_PREP | WORKER_REBIND | WORKER_UNBOUND |
80403c821dSTejun Heo 				  WORKER_CPU_INTENSIVE,
81db7bccf4STejun Heo 
823270476aSTejun Heo 	NR_WORKER_POOLS		= 2,		/* # worker pools per gcwq */
834ce62e9eSTejun Heo 
84c8e55f36STejun Heo 	BUSY_WORKER_HASH_ORDER	= 6,		/* 64 pointers */
85c8e55f36STejun Heo 	BUSY_WORKER_HASH_SIZE	= 1 << BUSY_WORKER_HASH_ORDER,
86c8e55f36STejun Heo 	BUSY_WORKER_HASH_MASK	= BUSY_WORKER_HASH_SIZE - 1,
87db7bccf4STejun Heo 
88e22bee78STejun Heo 	MAX_IDLE_WORKERS_RATIO	= 4,		/* 1/4 of busy can be idle */
89e22bee78STejun Heo 	IDLE_WORKER_TIMEOUT	= 300 * HZ,	/* keep idle ones for 5 mins */
90e22bee78STejun Heo 
913233cdbdSTejun Heo 	MAYDAY_INITIAL_TIMEOUT  = HZ / 100 >= 2 ? HZ / 100 : 2,
923233cdbdSTejun Heo 						/* call for help after 10ms
933233cdbdSTejun Heo 						   (min two ticks) */
94e22bee78STejun Heo 	MAYDAY_INTERVAL		= HZ / 10,	/* and then every 100ms */
95e22bee78STejun Heo 	CREATE_COOLDOWN		= HZ,		/* time to breath after fail */
961da177e4SLinus Torvalds 
971da177e4SLinus Torvalds 	/*
98e22bee78STejun Heo 	 * Rescue workers are used only on emergencies and shared by
99e22bee78STejun Heo 	 * all cpus.  Give -20.
100e22bee78STejun Heo 	 */
101e22bee78STejun Heo 	RESCUER_NICE_LEVEL	= -20,
1023270476aSTejun Heo 	HIGHPRI_NICE_LEVEL	= -20,
103c8e55f36STejun Heo };
104c8e55f36STejun Heo 
1051da177e4SLinus Torvalds /*
1064690c4abSTejun Heo  * Structure fields follow one of the following exclusion rules.
1074690c4abSTejun Heo  *
108e41e704bSTejun Heo  * I: Modifiable by initialization/destruction paths and read-only for
109e41e704bSTejun Heo  *    everyone else.
1104690c4abSTejun Heo  *
111e22bee78STejun Heo  * P: Preemption protected.  Disabling preemption is enough and should
112e22bee78STejun Heo  *    only be modified and accessed from the local cpu.
113e22bee78STejun Heo  *
1148b03ae3cSTejun Heo  * L: gcwq->lock protected.  Access with gcwq->lock held.
1154690c4abSTejun Heo  *
116e22bee78STejun Heo  * X: During normal operation, modification requires gcwq->lock and
117e22bee78STejun Heo  *    should be done only from local cpu.  Either disabling preemption
118e22bee78STejun Heo  *    on local cpu or grabbing gcwq->lock is enough for read access.
119f3421797STejun Heo  *    If GCWQ_DISASSOCIATED is set, it's identical to L.
120e22bee78STejun Heo  *
12173f53c4aSTejun Heo  * F: wq->flush_mutex protected.
12273f53c4aSTejun Heo  *
1234690c4abSTejun Heo  * W: workqueue_lock protected.
1244690c4abSTejun Heo  */
1254690c4abSTejun Heo 
1268b03ae3cSTejun Heo struct global_cwq;
127bd7bdd43STejun Heo struct worker_pool;
12825511a47STejun Heo struct idle_rebind;
129c34056a3STejun Heo 
130e22bee78STejun Heo /*
131e22bee78STejun Heo  * The poor guys doing the actual heavy lifting.  All on-duty workers
132e22bee78STejun Heo  * are either serving the manager role, on idle list or on busy hash.
133e22bee78STejun Heo  */
134c34056a3STejun Heo struct worker {
135c8e55f36STejun Heo 	/* on idle list while idle, on busy hash table while busy */
136c8e55f36STejun Heo 	union {
137c8e55f36STejun Heo 		struct list_head	entry;	/* L: while idle */
138c8e55f36STejun Heo 		struct hlist_node	hentry;	/* L: while busy */
139c8e55f36STejun Heo 	};
140c8e55f36STejun Heo 
141c34056a3STejun Heo 	struct work_struct	*current_work;	/* L: work being processed */
1428cca0eeaSTejun Heo 	struct cpu_workqueue_struct *current_cwq; /* L: current_work's cwq */
143affee4b2STejun Heo 	struct list_head	scheduled;	/* L: scheduled works */
144c34056a3STejun Heo 	struct task_struct	*task;		/* I: worker task */
145bd7bdd43STejun Heo 	struct worker_pool	*pool;		/* I: the associated pool */
146e22bee78STejun Heo 	/* 64 bytes boundary on 64bit, 32 on 32bit */
147e22bee78STejun Heo 	unsigned long		last_active;	/* L: last active timestamp */
148e22bee78STejun Heo 	unsigned int		flags;		/* X: flags */
149c34056a3STejun Heo 	int			id;		/* I: worker id */
15025511a47STejun Heo 
15125511a47STejun Heo 	/* for rebinding worker to CPU */
15225511a47STejun Heo 	struct idle_rebind	*idle_rebind;	/* L: for idle worker */
15325511a47STejun Heo 	struct work_struct	rebind_work;	/* L: for busy worker */
154c34056a3STejun Heo };
155c34056a3STejun Heo 
156bd7bdd43STejun Heo struct worker_pool {
157bd7bdd43STejun Heo 	struct global_cwq	*gcwq;		/* I: the owning gcwq */
15811ebea50STejun Heo 	unsigned int		flags;		/* X: flags */
159bd7bdd43STejun Heo 
160bd7bdd43STejun Heo 	struct list_head	worklist;	/* L: list of pending works */
161bd7bdd43STejun Heo 	int			nr_workers;	/* L: total number of workers */
162bd7bdd43STejun Heo 	int			nr_idle;	/* L: currently idle ones */
163bd7bdd43STejun Heo 
164bd7bdd43STejun Heo 	struct list_head	idle_list;	/* X: list of idle workers */
165bd7bdd43STejun Heo 	struct timer_list	idle_timer;	/* L: worker idle timeout */
166bd7bdd43STejun Heo 	struct timer_list	mayday_timer;	/* L: SOS timer for workers */
167bd7bdd43STejun Heo 
16860373152STejun Heo 	struct mutex		manager_mutex;	/* mutex manager should hold */
169bd7bdd43STejun Heo 	struct ida		worker_ida;	/* L: for worker IDs */
170bd7bdd43STejun Heo };
171bd7bdd43STejun Heo 
1724690c4abSTejun Heo /*
173e22bee78STejun Heo  * Global per-cpu workqueue.  There's one and only one for each cpu
174e22bee78STejun Heo  * and all works are queued and processed here regardless of their
175e22bee78STejun Heo  * target workqueues.
1768b03ae3cSTejun Heo  */
1778b03ae3cSTejun Heo struct global_cwq {
1788b03ae3cSTejun Heo 	spinlock_t		lock;		/* the gcwq lock */
1798b03ae3cSTejun Heo 	unsigned int		cpu;		/* I: the associated cpu */
180db7bccf4STejun Heo 	unsigned int		flags;		/* L: GCWQ_* flags */
181c8e55f36STejun Heo 
182bd7bdd43STejun Heo 	/* workers are chained either in busy_hash or pool idle_list */
183c8e55f36STejun Heo 	struct hlist_head	busy_hash[BUSY_WORKER_HASH_SIZE];
184c8e55f36STejun Heo 						/* L: hash of busy workers */
185c8e55f36STejun Heo 
186330dad5bSJoonsoo Kim 	struct worker_pool	pools[NR_WORKER_POOLS];
187330dad5bSJoonsoo Kim 						/* normal and highpri pools */
188db7bccf4STejun Heo 
18925511a47STejun Heo 	wait_queue_head_t	rebind_hold;	/* rebind hold wait */
1908b03ae3cSTejun Heo } ____cacheline_aligned_in_smp;
1918b03ae3cSTejun Heo 
1928b03ae3cSTejun Heo /*
193502ca9d8STejun Heo  * The per-CPU workqueue.  The lower WORK_STRUCT_FLAG_BITS of
1940f900049STejun Heo  * work_struct->data are used for flags and thus cwqs need to be
1950f900049STejun Heo  * aligned at two's power of the number of flag bits.
1961da177e4SLinus Torvalds  */
1971da177e4SLinus Torvalds struct cpu_workqueue_struct {
198bd7bdd43STejun Heo 	struct worker_pool	*pool;		/* I: the associated pool */
1994690c4abSTejun Heo 	struct workqueue_struct *wq;		/* I: the owning workqueue */
20073f53c4aSTejun Heo 	int			work_color;	/* L: current color */
20173f53c4aSTejun Heo 	int			flush_color;	/* L: flushing color */
20273f53c4aSTejun Heo 	int			nr_in_flight[WORK_NR_COLORS];
20373f53c4aSTejun Heo 						/* L: nr of in_flight works */
2041e19ffc6STejun Heo 	int			nr_active;	/* L: nr of active works */
205a0a1a5fdSTejun Heo 	int			max_active;	/* L: max active works */
2061e19ffc6STejun Heo 	struct list_head	delayed_works;	/* L: delayed works */
2070f900049STejun Heo };
2081da177e4SLinus Torvalds 
2091da177e4SLinus Torvalds /*
21073f53c4aSTejun Heo  * Structure used to wait for workqueue flush.
21173f53c4aSTejun Heo  */
21273f53c4aSTejun Heo struct wq_flusher {
21373f53c4aSTejun Heo 	struct list_head	list;		/* F: list of flushers */
21473f53c4aSTejun Heo 	int			flush_color;	/* F: flush color waiting for */
21573f53c4aSTejun Heo 	struct completion	done;		/* flush completion */
21673f53c4aSTejun Heo };
2171da177e4SLinus Torvalds 
21873f53c4aSTejun Heo /*
219f2e005aaSTejun Heo  * All cpumasks are assumed to be always set on UP and thus can't be
220f2e005aaSTejun Heo  * used to determine whether there's something to be done.
221f2e005aaSTejun Heo  */
222f2e005aaSTejun Heo #ifdef CONFIG_SMP
223f2e005aaSTejun Heo typedef cpumask_var_t mayday_mask_t;
224f2e005aaSTejun Heo #define mayday_test_and_set_cpu(cpu, mask)	\
225f2e005aaSTejun Heo 	cpumask_test_and_set_cpu((cpu), (mask))
226f2e005aaSTejun Heo #define mayday_clear_cpu(cpu, mask)		cpumask_clear_cpu((cpu), (mask))
227f2e005aaSTejun Heo #define for_each_mayday_cpu(cpu, mask)		for_each_cpu((cpu), (mask))
2289c37547aSTejun Heo #define alloc_mayday_mask(maskp, gfp)		zalloc_cpumask_var((maskp), (gfp))
229f2e005aaSTejun Heo #define free_mayday_mask(mask)			free_cpumask_var((mask))
230f2e005aaSTejun Heo #else
231f2e005aaSTejun Heo typedef unsigned long mayday_mask_t;
232f2e005aaSTejun Heo #define mayday_test_and_set_cpu(cpu, mask)	test_and_set_bit(0, &(mask))
233f2e005aaSTejun Heo #define mayday_clear_cpu(cpu, mask)		clear_bit(0, &(mask))
234f2e005aaSTejun Heo #define for_each_mayday_cpu(cpu, mask)		if ((cpu) = 0, (mask))
235f2e005aaSTejun Heo #define alloc_mayday_mask(maskp, gfp)		true
236f2e005aaSTejun Heo #define free_mayday_mask(mask)			do { } while (0)
237f2e005aaSTejun Heo #endif
2381da177e4SLinus Torvalds 
2391da177e4SLinus Torvalds /*
2401da177e4SLinus Torvalds  * The externally visible workqueue abstraction is an array of
2411da177e4SLinus Torvalds  * per-CPU workqueues:
2421da177e4SLinus Torvalds  */
2431da177e4SLinus Torvalds struct workqueue_struct {
2449c5a2ba7STejun Heo 	unsigned int		flags;		/* W: WQ_* flags */
245bdbc5dd7STejun Heo 	union {
246bdbc5dd7STejun Heo 		struct cpu_workqueue_struct __percpu	*pcpu;
247bdbc5dd7STejun Heo 		struct cpu_workqueue_struct		*single;
248bdbc5dd7STejun Heo 		unsigned long				v;
249bdbc5dd7STejun Heo 	} cpu_wq;				/* I: cwq's */
2504690c4abSTejun Heo 	struct list_head	list;		/* W: list of all workqueues */
25173f53c4aSTejun Heo 
25273f53c4aSTejun Heo 	struct mutex		flush_mutex;	/* protects wq flushing */
25373f53c4aSTejun Heo 	int			work_color;	/* F: current work color */
25473f53c4aSTejun Heo 	int			flush_color;	/* F: current flush color */
25573f53c4aSTejun Heo 	atomic_t		nr_cwqs_to_flush; /* flush in progress */
25673f53c4aSTejun Heo 	struct wq_flusher	*first_flusher;	/* F: first flusher */
25773f53c4aSTejun Heo 	struct list_head	flusher_queue;	/* F: flush waiters */
25873f53c4aSTejun Heo 	struct list_head	flusher_overflow; /* F: flush overflow list */
25973f53c4aSTejun Heo 
260f2e005aaSTejun Heo 	mayday_mask_t		mayday_mask;	/* cpus requesting rescue */
261e22bee78STejun Heo 	struct worker		*rescuer;	/* I: rescue worker */
262e22bee78STejun Heo 
2639c5a2ba7STejun Heo 	int			nr_drainers;	/* W: drain in progress */
264dcd989cbSTejun Heo 	int			saved_max_active; /* W: saved cwq max_active */
2654e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
2664e6045f1SJohannes Berg 	struct lockdep_map	lockdep_map;
2674e6045f1SJohannes Berg #endif
268b196be89STejun Heo 	char			name[];		/* I: workqueue name */
2691da177e4SLinus Torvalds };
2701da177e4SLinus Torvalds 
271d320c038STejun Heo struct workqueue_struct *system_wq __read_mostly;
2721aabe902SJoonsoo Kim struct workqueue_struct *system_highpri_wq __read_mostly;
273d320c038STejun Heo struct workqueue_struct *system_long_wq __read_mostly;
274d320c038STejun Heo struct workqueue_struct *system_nrt_wq __read_mostly;
275f3421797STejun Heo struct workqueue_struct *system_unbound_wq __read_mostly;
27624d51addSTejun Heo struct workqueue_struct *system_freezable_wq __read_mostly;
27762d3c543SAlan Stern struct workqueue_struct *system_nrt_freezable_wq __read_mostly;
278d320c038STejun Heo EXPORT_SYMBOL_GPL(system_wq);
2791aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
280d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
281d320c038STejun Heo EXPORT_SYMBOL_GPL(system_nrt_wq);
282f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
28324d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
28462d3c543SAlan Stern EXPORT_SYMBOL_GPL(system_nrt_freezable_wq);
285d320c038STejun Heo 
28697bd2347STejun Heo #define CREATE_TRACE_POINTS
28797bd2347STejun Heo #include <trace/events/workqueue.h>
28897bd2347STejun Heo 
2894ce62e9eSTejun Heo #define for_each_worker_pool(pool, gcwq)				\
2903270476aSTejun Heo 	for ((pool) = &(gcwq)->pools[0];				\
2913270476aSTejun Heo 	     (pool) < &(gcwq)->pools[NR_WORKER_POOLS]; (pool)++)
2924ce62e9eSTejun Heo 
293db7bccf4STejun Heo #define for_each_busy_worker(worker, i, pos, gcwq)			\
294db7bccf4STejun Heo 	for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)			\
295db7bccf4STejun Heo 		hlist_for_each_entry(worker, pos, &gcwq->busy_hash[i], hentry)
296db7bccf4STejun Heo 
297f3421797STejun Heo static inline int __next_gcwq_cpu(int cpu, const struct cpumask *mask,
298f3421797STejun Heo 				  unsigned int sw)
299f3421797STejun Heo {
300f3421797STejun Heo 	if (cpu < nr_cpu_ids) {
301f3421797STejun Heo 		if (sw & 1) {
302f3421797STejun Heo 			cpu = cpumask_next(cpu, mask);
303f3421797STejun Heo 			if (cpu < nr_cpu_ids)
304f3421797STejun Heo 				return cpu;
305f3421797STejun Heo 		}
306f3421797STejun Heo 		if (sw & 2)
307f3421797STejun Heo 			return WORK_CPU_UNBOUND;
308f3421797STejun Heo 	}
309f3421797STejun Heo 	return WORK_CPU_NONE;
310f3421797STejun Heo }
311f3421797STejun Heo 
312f3421797STejun Heo static inline int __next_wq_cpu(int cpu, const struct cpumask *mask,
313f3421797STejun Heo 				struct workqueue_struct *wq)
314f3421797STejun Heo {
315f3421797STejun Heo 	return __next_gcwq_cpu(cpu, mask, !(wq->flags & WQ_UNBOUND) ? 1 : 2);
316f3421797STejun Heo }
317f3421797STejun Heo 
31809884951STejun Heo /*
31909884951STejun Heo  * CPU iterators
32009884951STejun Heo  *
32109884951STejun Heo  * An extra gcwq is defined for an invalid cpu number
32209884951STejun Heo  * (WORK_CPU_UNBOUND) to host workqueues which are not bound to any
32309884951STejun Heo  * specific CPU.  The following iterators are similar to
32409884951STejun Heo  * for_each_*_cpu() iterators but also considers the unbound gcwq.
32509884951STejun Heo  *
32609884951STejun Heo  * for_each_gcwq_cpu()		: possible CPUs + WORK_CPU_UNBOUND
32709884951STejun Heo  * for_each_online_gcwq_cpu()	: online CPUs + WORK_CPU_UNBOUND
32809884951STejun Heo  * for_each_cwq_cpu()		: possible CPUs for bound workqueues,
32909884951STejun Heo  *				  WORK_CPU_UNBOUND for unbound workqueues
33009884951STejun Heo  */
331f3421797STejun Heo #define for_each_gcwq_cpu(cpu)						\
332f3421797STejun Heo 	for ((cpu) = __next_gcwq_cpu(-1, cpu_possible_mask, 3);		\
333f3421797STejun Heo 	     (cpu) < WORK_CPU_NONE;					\
334f3421797STejun Heo 	     (cpu) = __next_gcwq_cpu((cpu), cpu_possible_mask, 3))
335f3421797STejun Heo 
336f3421797STejun Heo #define for_each_online_gcwq_cpu(cpu)					\
337f3421797STejun Heo 	for ((cpu) = __next_gcwq_cpu(-1, cpu_online_mask, 3);		\
338f3421797STejun Heo 	     (cpu) < WORK_CPU_NONE;					\
339f3421797STejun Heo 	     (cpu) = __next_gcwq_cpu((cpu), cpu_online_mask, 3))
340f3421797STejun Heo 
341f3421797STejun Heo #define for_each_cwq_cpu(cpu, wq)					\
342f3421797STejun Heo 	for ((cpu) = __next_wq_cpu(-1, cpu_possible_mask, (wq));	\
343f3421797STejun Heo 	     (cpu) < WORK_CPU_NONE;					\
344f3421797STejun Heo 	     (cpu) = __next_wq_cpu((cpu), cpu_possible_mask, (wq)))
345f3421797STejun Heo 
346dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
347dc186ad7SThomas Gleixner 
348dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr;
349dc186ad7SThomas Gleixner 
35099777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
35199777288SStanislaw Gruszka {
35299777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
35399777288SStanislaw Gruszka }
35499777288SStanislaw Gruszka 
355dc186ad7SThomas Gleixner /*
356dc186ad7SThomas Gleixner  * fixup_init is called when:
357dc186ad7SThomas Gleixner  * - an active object is initialized
358dc186ad7SThomas Gleixner  */
359dc186ad7SThomas Gleixner static int work_fixup_init(void *addr, enum debug_obj_state state)
360dc186ad7SThomas Gleixner {
361dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
362dc186ad7SThomas Gleixner 
363dc186ad7SThomas Gleixner 	switch (state) {
364dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
365dc186ad7SThomas Gleixner 		cancel_work_sync(work);
366dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
367dc186ad7SThomas Gleixner 		return 1;
368dc186ad7SThomas Gleixner 	default:
369dc186ad7SThomas Gleixner 		return 0;
370dc186ad7SThomas Gleixner 	}
371dc186ad7SThomas Gleixner }
372dc186ad7SThomas Gleixner 
373dc186ad7SThomas Gleixner /*
374dc186ad7SThomas Gleixner  * fixup_activate is called when:
375dc186ad7SThomas Gleixner  * - an active object is activated
376dc186ad7SThomas Gleixner  * - an unknown object is activated (might be a statically initialized object)
377dc186ad7SThomas Gleixner  */
378dc186ad7SThomas Gleixner static int work_fixup_activate(void *addr, enum debug_obj_state state)
379dc186ad7SThomas Gleixner {
380dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
381dc186ad7SThomas Gleixner 
382dc186ad7SThomas Gleixner 	switch (state) {
383dc186ad7SThomas Gleixner 
384dc186ad7SThomas Gleixner 	case ODEBUG_STATE_NOTAVAILABLE:
385dc186ad7SThomas Gleixner 		/*
386dc186ad7SThomas Gleixner 		 * This is not really a fixup. The work struct was
387dc186ad7SThomas Gleixner 		 * statically initialized. We just make sure that it
388dc186ad7SThomas Gleixner 		 * is tracked in the object tracker.
389dc186ad7SThomas Gleixner 		 */
39022df02bbSTejun Heo 		if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
391dc186ad7SThomas Gleixner 			debug_object_init(work, &work_debug_descr);
392dc186ad7SThomas Gleixner 			debug_object_activate(work, &work_debug_descr);
393dc186ad7SThomas Gleixner 			return 0;
394dc186ad7SThomas Gleixner 		}
395dc186ad7SThomas Gleixner 		WARN_ON_ONCE(1);
396dc186ad7SThomas Gleixner 		return 0;
397dc186ad7SThomas Gleixner 
398dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
399dc186ad7SThomas Gleixner 		WARN_ON(1);
400dc186ad7SThomas Gleixner 
401dc186ad7SThomas Gleixner 	default:
402dc186ad7SThomas Gleixner 		return 0;
403dc186ad7SThomas Gleixner 	}
404dc186ad7SThomas Gleixner }
405dc186ad7SThomas Gleixner 
406dc186ad7SThomas Gleixner /*
407dc186ad7SThomas Gleixner  * fixup_free is called when:
408dc186ad7SThomas Gleixner  * - an active object is freed
409dc186ad7SThomas Gleixner  */
410dc186ad7SThomas Gleixner static int work_fixup_free(void *addr, enum debug_obj_state state)
411dc186ad7SThomas Gleixner {
412dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
413dc186ad7SThomas Gleixner 
414dc186ad7SThomas Gleixner 	switch (state) {
415dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
416dc186ad7SThomas Gleixner 		cancel_work_sync(work);
417dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
418dc186ad7SThomas Gleixner 		return 1;
419dc186ad7SThomas Gleixner 	default:
420dc186ad7SThomas Gleixner 		return 0;
421dc186ad7SThomas Gleixner 	}
422dc186ad7SThomas Gleixner }
423dc186ad7SThomas Gleixner 
424dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr = {
425dc186ad7SThomas Gleixner 	.name		= "work_struct",
42699777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
427dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
428dc186ad7SThomas Gleixner 	.fixup_activate	= work_fixup_activate,
429dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
430dc186ad7SThomas Gleixner };
431dc186ad7SThomas Gleixner 
432dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
433dc186ad7SThomas Gleixner {
434dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
435dc186ad7SThomas Gleixner }
436dc186ad7SThomas Gleixner 
437dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
438dc186ad7SThomas Gleixner {
439dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
440dc186ad7SThomas Gleixner }
441dc186ad7SThomas Gleixner 
442dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
443dc186ad7SThomas Gleixner {
444dc186ad7SThomas Gleixner 	if (onstack)
445dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
446dc186ad7SThomas Gleixner 	else
447dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
448dc186ad7SThomas Gleixner }
449dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
450dc186ad7SThomas Gleixner 
451dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
452dc186ad7SThomas Gleixner {
453dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
454dc186ad7SThomas Gleixner }
455dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
456dc186ad7SThomas Gleixner 
457dc186ad7SThomas Gleixner #else
458dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
459dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
460dc186ad7SThomas Gleixner #endif
461dc186ad7SThomas Gleixner 
46295402b38SGautham R Shenoy /* Serializes the accesses to the list of workqueues. */
46395402b38SGautham R Shenoy static DEFINE_SPINLOCK(workqueue_lock);
4641da177e4SLinus Torvalds static LIST_HEAD(workqueues);
465a0a1a5fdSTejun Heo static bool workqueue_freezing;		/* W: have wqs started freezing? */
4661da177e4SLinus Torvalds 
46714441960SOleg Nesterov /*
468e22bee78STejun Heo  * The almighty global cpu workqueues.  nr_running is the only field
469e22bee78STejun Heo  * which is expected to be used frequently by other cpus via
470e22bee78STejun Heo  * try_to_wake_up().  Put it in a separate cacheline.
47114441960SOleg Nesterov  */
4728b03ae3cSTejun Heo static DEFINE_PER_CPU(struct global_cwq, global_cwq);
4734ce62e9eSTejun Heo static DEFINE_PER_CPU_SHARED_ALIGNED(atomic_t, pool_nr_running[NR_WORKER_POOLS]);
474f756d5e2SNathan Lynch 
475f3421797STejun Heo /*
476f3421797STejun Heo  * Global cpu workqueue and nr_running counter for unbound gcwq.  The
477f3421797STejun Heo  * gcwq is always online, has GCWQ_DISASSOCIATED set, and all its
478f3421797STejun Heo  * workers have WORKER_UNBOUND set.
479f3421797STejun Heo  */
480f3421797STejun Heo static struct global_cwq unbound_global_cwq;
4814ce62e9eSTejun Heo static atomic_t unbound_pool_nr_running[NR_WORKER_POOLS] = {
4824ce62e9eSTejun Heo 	[0 ... NR_WORKER_POOLS - 1]	= ATOMIC_INIT(0),	/* always 0 */
4834ce62e9eSTejun Heo };
484f3421797STejun Heo 
485c34056a3STejun Heo static int worker_thread(void *__worker);
4861da177e4SLinus Torvalds 
4873270476aSTejun Heo static int worker_pool_pri(struct worker_pool *pool)
4883270476aSTejun Heo {
4893270476aSTejun Heo 	return pool - pool->gcwq->pools;
4903270476aSTejun Heo }
4913270476aSTejun Heo 
4928b03ae3cSTejun Heo static struct global_cwq *get_gcwq(unsigned int cpu)
4931da177e4SLinus Torvalds {
494f3421797STejun Heo 	if (cpu != WORK_CPU_UNBOUND)
4958b03ae3cSTejun Heo 		return &per_cpu(global_cwq, cpu);
496f3421797STejun Heo 	else
497f3421797STejun Heo 		return &unbound_global_cwq;
4981da177e4SLinus Torvalds }
4991da177e4SLinus Torvalds 
50063d95a91STejun Heo static atomic_t *get_pool_nr_running(struct worker_pool *pool)
501b1f4ec17SOleg Nesterov {
50263d95a91STejun Heo 	int cpu = pool->gcwq->cpu;
5033270476aSTejun Heo 	int idx = worker_pool_pri(pool);
50463d95a91STejun Heo 
505f3421797STejun Heo 	if (cpu != WORK_CPU_UNBOUND)
5064ce62e9eSTejun Heo 		return &per_cpu(pool_nr_running, cpu)[idx];
507f3421797STejun Heo 	else
5084ce62e9eSTejun Heo 		return &unbound_pool_nr_running[idx];
509b1f4ec17SOleg Nesterov }
510b1f4ec17SOleg Nesterov 
5114690c4abSTejun Heo static struct cpu_workqueue_struct *get_cwq(unsigned int cpu,
5124690c4abSTejun Heo 					    struct workqueue_struct *wq)
513a848e3b6SOleg Nesterov {
514f3421797STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
515e06ffa1eSLai Jiangshan 		if (likely(cpu < nr_cpu_ids))
516bdbc5dd7STejun Heo 			return per_cpu_ptr(wq->cpu_wq.pcpu, cpu);
517f3421797STejun Heo 	} else if (likely(cpu == WORK_CPU_UNBOUND))
518f3421797STejun Heo 		return wq->cpu_wq.single;
519f3421797STejun Heo 	return NULL;
520f3421797STejun Heo }
521a848e3b6SOleg Nesterov 
52273f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
52373f53c4aSTejun Heo {
52473f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
52573f53c4aSTejun Heo }
52673f53c4aSTejun Heo 
52773f53c4aSTejun Heo static int get_work_color(struct work_struct *work)
52873f53c4aSTejun Heo {
52973f53c4aSTejun Heo 	return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
53073f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
53173f53c4aSTejun Heo }
53273f53c4aSTejun Heo 
53373f53c4aSTejun Heo static int work_next_color(int color)
53473f53c4aSTejun Heo {
53573f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
5361da177e4SLinus Torvalds }
5371da177e4SLinus Torvalds 
5384594bf15SDavid Howells /*
539b5490077STejun Heo  * While queued, %WORK_STRUCT_CWQ is set and non flag bits of a work's data
540b5490077STejun Heo  * contain the pointer to the queued cwq.  Once execution starts, the flag
541b5490077STejun Heo  * is cleared and the high bits contain OFFQ flags and CPU number.
5427a22ad75STejun Heo  *
543bbb68dfaSTejun Heo  * set_work_cwq(), set_work_cpu_and_clear_pending(), mark_work_canceling()
544bbb68dfaSTejun Heo  * and clear_work_data() can be used to set the cwq, cpu or clear
545bbb68dfaSTejun Heo  * work->data.  These functions should only be called while the work is
546bbb68dfaSTejun Heo  * owned - ie. while the PENDING bit is set.
5477a22ad75STejun Heo  *
548bbb68dfaSTejun Heo  * get_work_[g]cwq() can be used to obtain the gcwq or cwq corresponding to
549bbb68dfaSTejun Heo  * a work.  gcwq is available once the work has been queued anywhere after
550bbb68dfaSTejun Heo  * initialization until it is sync canceled.  cwq is available only while
551bbb68dfaSTejun Heo  * the work item is queued.
552bbb68dfaSTejun Heo  *
553bbb68dfaSTejun Heo  * %WORK_OFFQ_CANCELING is used to mark a work item which is being
554bbb68dfaSTejun Heo  * canceled.  While being canceled, a work item may have its PENDING set
555bbb68dfaSTejun Heo  * but stay off timer and worklist for arbitrarily long and nobody should
556bbb68dfaSTejun Heo  * try to steal the PENDING bit.
5574594bf15SDavid Howells  */
5587a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
5597a22ad75STejun Heo 				 unsigned long flags)
5607a22ad75STejun Heo {
5617a22ad75STejun Heo 	BUG_ON(!work_pending(work));
5627a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
5637a22ad75STejun Heo }
5647a22ad75STejun Heo 
5657a22ad75STejun Heo static void set_work_cwq(struct work_struct *work,
5664690c4abSTejun Heo 			 struct cpu_workqueue_struct *cwq,
5674690c4abSTejun Heo 			 unsigned long extra_flags)
568365970a1SDavid Howells {
5697a22ad75STejun Heo 	set_work_data(work, (unsigned long)cwq,
570e120153dSTejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_CWQ | extra_flags);
571365970a1SDavid Howells }
572365970a1SDavid Howells 
5738930cabaSTejun Heo static void set_work_cpu_and_clear_pending(struct work_struct *work,
5748930cabaSTejun Heo 					   unsigned int cpu)
5754d707b9fSOleg Nesterov {
57623657bb1STejun Heo 	/*
57723657bb1STejun Heo 	 * The following wmb is paired with the implied mb in
57823657bb1STejun Heo 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
57923657bb1STejun Heo 	 * here are visible to and precede any updates by the next PENDING
58023657bb1STejun Heo 	 * owner.
58123657bb1STejun Heo 	 */
58223657bb1STejun Heo 	smp_wmb();
583b5490077STejun Heo 	set_work_data(work, (unsigned long)cpu << WORK_OFFQ_CPU_SHIFT, 0);
5844d707b9fSOleg Nesterov }
5854d707b9fSOleg Nesterov 
5867a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
587365970a1SDavid Howells {
58823657bb1STejun Heo 	smp_wmb();	/* see set_work_cpu_and_clear_pending() */
5897a22ad75STejun Heo 	set_work_data(work, WORK_STRUCT_NO_CPU, 0);
5907a22ad75STejun Heo }
5917a22ad75STejun Heo 
5927a22ad75STejun Heo static struct cpu_workqueue_struct *get_work_cwq(struct work_struct *work)
5937a22ad75STejun Heo {
594e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
5957a22ad75STejun Heo 
596e120153dSTejun Heo 	if (data & WORK_STRUCT_CWQ)
597e120153dSTejun Heo 		return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
598e120153dSTejun Heo 	else
599e120153dSTejun Heo 		return NULL;
6007a22ad75STejun Heo }
6017a22ad75STejun Heo 
6027a22ad75STejun Heo static struct global_cwq *get_work_gcwq(struct work_struct *work)
6037a22ad75STejun Heo {
604e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
6057a22ad75STejun Heo 	unsigned int cpu;
6067a22ad75STejun Heo 
607e120153dSTejun Heo 	if (data & WORK_STRUCT_CWQ)
608e120153dSTejun Heo 		return ((struct cpu_workqueue_struct *)
609bd7bdd43STejun Heo 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool->gcwq;
6107a22ad75STejun Heo 
611b5490077STejun Heo 	cpu = data >> WORK_OFFQ_CPU_SHIFT;
612bdbc5dd7STejun Heo 	if (cpu == WORK_CPU_NONE)
6137a22ad75STejun Heo 		return NULL;
6147a22ad75STejun Heo 
615f3421797STejun Heo 	BUG_ON(cpu >= nr_cpu_ids && cpu != WORK_CPU_UNBOUND);
6167a22ad75STejun Heo 	return get_gcwq(cpu);
617365970a1SDavid Howells }
618365970a1SDavid Howells 
619bbb68dfaSTejun Heo static void mark_work_canceling(struct work_struct *work)
620bbb68dfaSTejun Heo {
621bbb68dfaSTejun Heo 	struct global_cwq *gcwq = get_work_gcwq(work);
622bbb68dfaSTejun Heo 	unsigned long cpu = gcwq ? gcwq->cpu : WORK_CPU_NONE;
623bbb68dfaSTejun Heo 
624bbb68dfaSTejun Heo 	set_work_data(work, (cpu << WORK_OFFQ_CPU_SHIFT) | WORK_OFFQ_CANCELING,
625bbb68dfaSTejun Heo 		      WORK_STRUCT_PENDING);
626bbb68dfaSTejun Heo }
627bbb68dfaSTejun Heo 
628bbb68dfaSTejun Heo static bool work_is_canceling(struct work_struct *work)
629bbb68dfaSTejun Heo {
630bbb68dfaSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
631bbb68dfaSTejun Heo 
632bbb68dfaSTejun Heo 	return !(data & WORK_STRUCT_CWQ) && (data & WORK_OFFQ_CANCELING);
633bbb68dfaSTejun Heo }
634bbb68dfaSTejun Heo 
635e22bee78STejun Heo /*
6363270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
6373270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
6383270476aSTejun Heo  * they're being called with gcwq->lock held.
639e22bee78STejun Heo  */
640e22bee78STejun Heo 
64163d95a91STejun Heo static bool __need_more_worker(struct worker_pool *pool)
642649027d7STejun Heo {
6433270476aSTejun Heo 	return !atomic_read(get_pool_nr_running(pool));
644649027d7STejun Heo }
645649027d7STejun Heo 
646e22bee78STejun Heo /*
647e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
648e22bee78STejun Heo  * running workers.
649974271c4STejun Heo  *
650974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
651974271c4STejun Heo  * function will always return %true for unbound gcwq as long as the
652974271c4STejun Heo  * worklist isn't empty.
653e22bee78STejun Heo  */
65463d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
655e22bee78STejun Heo {
65663d95a91STejun Heo 	return !list_empty(&pool->worklist) && __need_more_worker(pool);
657e22bee78STejun Heo }
658e22bee78STejun Heo 
659e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
66063d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
661e22bee78STejun Heo {
66263d95a91STejun Heo 	return pool->nr_idle;
663e22bee78STejun Heo }
664e22bee78STejun Heo 
665e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
66663d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
667e22bee78STejun Heo {
66863d95a91STejun Heo 	atomic_t *nr_running = get_pool_nr_running(pool);
669e22bee78STejun Heo 
6703270476aSTejun Heo 	return !list_empty(&pool->worklist) && atomic_read(nr_running) <= 1;
671e22bee78STejun Heo }
672e22bee78STejun Heo 
673e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
67463d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
675e22bee78STejun Heo {
67663d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
677e22bee78STejun Heo }
678e22bee78STejun Heo 
679e22bee78STejun Heo /* Do I need to be the manager? */
68063d95a91STejun Heo static bool need_to_manage_workers(struct worker_pool *pool)
681e22bee78STejun Heo {
68263d95a91STejun Heo 	return need_to_create_worker(pool) ||
68311ebea50STejun Heo 		(pool->flags & POOL_MANAGE_WORKERS);
684e22bee78STejun Heo }
685e22bee78STejun Heo 
686e22bee78STejun Heo /* Do we have too many workers and should some go away? */
68763d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
688e22bee78STejun Heo {
68960373152STejun Heo 	bool managing = mutex_is_locked(&pool->manager_mutex);
69063d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
69163d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
692e22bee78STejun Heo 
693e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
694e22bee78STejun Heo }
695e22bee78STejun Heo 
696e22bee78STejun Heo /*
697e22bee78STejun Heo  * Wake up functions.
698e22bee78STejun Heo  */
699e22bee78STejun Heo 
7007e11629dSTejun Heo /* Return the first worker.  Safe with preemption disabled */
70163d95a91STejun Heo static struct worker *first_worker(struct worker_pool *pool)
7027e11629dSTejun Heo {
70363d95a91STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
7047e11629dSTejun Heo 		return NULL;
7057e11629dSTejun Heo 
70663d95a91STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
7077e11629dSTejun Heo }
7087e11629dSTejun Heo 
7097e11629dSTejun Heo /**
7107e11629dSTejun Heo  * wake_up_worker - wake up an idle worker
71163d95a91STejun Heo  * @pool: worker pool to wake worker from
7127e11629dSTejun Heo  *
71363d95a91STejun Heo  * Wake up the first idle worker of @pool.
7147e11629dSTejun Heo  *
7157e11629dSTejun Heo  * CONTEXT:
7167e11629dSTejun Heo  * spin_lock_irq(gcwq->lock).
7177e11629dSTejun Heo  */
71863d95a91STejun Heo static void wake_up_worker(struct worker_pool *pool)
7197e11629dSTejun Heo {
72063d95a91STejun Heo 	struct worker *worker = first_worker(pool);
7217e11629dSTejun Heo 
7227e11629dSTejun Heo 	if (likely(worker))
7237e11629dSTejun Heo 		wake_up_process(worker->task);
7247e11629dSTejun Heo }
7257e11629dSTejun Heo 
7264690c4abSTejun Heo /**
727e22bee78STejun Heo  * wq_worker_waking_up - a worker is waking up
728e22bee78STejun Heo  * @task: task waking up
729e22bee78STejun Heo  * @cpu: CPU @task is waking up to
730e22bee78STejun Heo  *
731e22bee78STejun Heo  * This function is called during try_to_wake_up() when a worker is
732e22bee78STejun Heo  * being awoken.
733e22bee78STejun Heo  *
734e22bee78STejun Heo  * CONTEXT:
735e22bee78STejun Heo  * spin_lock_irq(rq->lock)
736e22bee78STejun Heo  */
737e22bee78STejun Heo void wq_worker_waking_up(struct task_struct *task, unsigned int cpu)
738e22bee78STejun Heo {
739e22bee78STejun Heo 	struct worker *worker = kthread_data(task);
740e22bee78STejun Heo 
7412d64672eSSteven Rostedt 	if (!(worker->flags & WORKER_NOT_RUNNING))
74263d95a91STejun Heo 		atomic_inc(get_pool_nr_running(worker->pool));
743e22bee78STejun Heo }
744e22bee78STejun Heo 
745e22bee78STejun Heo /**
746e22bee78STejun Heo  * wq_worker_sleeping - a worker is going to sleep
747e22bee78STejun Heo  * @task: task going to sleep
748e22bee78STejun Heo  * @cpu: CPU in question, must be the current CPU number
749e22bee78STejun Heo  *
750e22bee78STejun Heo  * This function is called during schedule() when a busy worker is
751e22bee78STejun Heo  * going to sleep.  Worker on the same cpu can be woken up by
752e22bee78STejun Heo  * returning pointer to its task.
753e22bee78STejun Heo  *
754e22bee78STejun Heo  * CONTEXT:
755e22bee78STejun Heo  * spin_lock_irq(rq->lock)
756e22bee78STejun Heo  *
757e22bee78STejun Heo  * RETURNS:
758e22bee78STejun Heo  * Worker task on @cpu to wake up, %NULL if none.
759e22bee78STejun Heo  */
760e22bee78STejun Heo struct task_struct *wq_worker_sleeping(struct task_struct *task,
761e22bee78STejun Heo 				       unsigned int cpu)
762e22bee78STejun Heo {
763e22bee78STejun Heo 	struct worker *worker = kthread_data(task), *to_wakeup = NULL;
764bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
76563d95a91STejun Heo 	atomic_t *nr_running = get_pool_nr_running(pool);
766e22bee78STejun Heo 
7672d64672eSSteven Rostedt 	if (worker->flags & WORKER_NOT_RUNNING)
768e22bee78STejun Heo 		return NULL;
769e22bee78STejun Heo 
770e22bee78STejun Heo 	/* this can only happen on the local cpu */
771e22bee78STejun Heo 	BUG_ON(cpu != raw_smp_processor_id());
772e22bee78STejun Heo 
773e22bee78STejun Heo 	/*
774e22bee78STejun Heo 	 * The counterpart of the following dec_and_test, implied mb,
775e22bee78STejun Heo 	 * worklist not empty test sequence is in insert_work().
776e22bee78STejun Heo 	 * Please read comment there.
777e22bee78STejun Heo 	 *
778628c78e7STejun Heo 	 * NOT_RUNNING is clear.  This means that we're bound to and
779628c78e7STejun Heo 	 * running on the local cpu w/ rq lock held and preemption
780628c78e7STejun Heo 	 * disabled, which in turn means that none else could be
781628c78e7STejun Heo 	 * manipulating idle_list, so dereferencing idle_list without gcwq
782628c78e7STejun Heo 	 * lock is safe.
783e22bee78STejun Heo 	 */
784bd7bdd43STejun Heo 	if (atomic_dec_and_test(nr_running) && !list_empty(&pool->worklist))
78563d95a91STejun Heo 		to_wakeup = first_worker(pool);
786e22bee78STejun Heo 	return to_wakeup ? to_wakeup->task : NULL;
787e22bee78STejun Heo }
788e22bee78STejun Heo 
789e22bee78STejun Heo /**
790e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
791cb444766STejun Heo  * @worker: self
792d302f017STejun Heo  * @flags: flags to set
793d302f017STejun Heo  * @wakeup: wakeup an idle worker if necessary
794d302f017STejun Heo  *
795e22bee78STejun Heo  * Set @flags in @worker->flags and adjust nr_running accordingly.  If
796e22bee78STejun Heo  * nr_running becomes zero and @wakeup is %true, an idle worker is
797e22bee78STejun Heo  * woken up.
798d302f017STejun Heo  *
799cb444766STejun Heo  * CONTEXT:
800cb444766STejun Heo  * spin_lock_irq(gcwq->lock)
801d302f017STejun Heo  */
802d302f017STejun Heo static inline void worker_set_flags(struct worker *worker, unsigned int flags,
803d302f017STejun Heo 				    bool wakeup)
804d302f017STejun Heo {
805bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
806e22bee78STejun Heo 
807cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
808cb444766STejun Heo 
809e22bee78STejun Heo 	/*
810e22bee78STejun Heo 	 * If transitioning into NOT_RUNNING, adjust nr_running and
811e22bee78STejun Heo 	 * wake up an idle worker as necessary if requested by
812e22bee78STejun Heo 	 * @wakeup.
813e22bee78STejun Heo 	 */
814e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
815e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
81663d95a91STejun Heo 		atomic_t *nr_running = get_pool_nr_running(pool);
817e22bee78STejun Heo 
818e22bee78STejun Heo 		if (wakeup) {
819e22bee78STejun Heo 			if (atomic_dec_and_test(nr_running) &&
820bd7bdd43STejun Heo 			    !list_empty(&pool->worklist))
82163d95a91STejun Heo 				wake_up_worker(pool);
822e22bee78STejun Heo 		} else
823e22bee78STejun Heo 			atomic_dec(nr_running);
824e22bee78STejun Heo 	}
825e22bee78STejun Heo 
826d302f017STejun Heo 	worker->flags |= flags;
827d302f017STejun Heo }
828d302f017STejun Heo 
829d302f017STejun Heo /**
830e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
831cb444766STejun Heo  * @worker: self
832d302f017STejun Heo  * @flags: flags to clear
833d302f017STejun Heo  *
834e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
835d302f017STejun Heo  *
836cb444766STejun Heo  * CONTEXT:
837cb444766STejun Heo  * spin_lock_irq(gcwq->lock)
838d302f017STejun Heo  */
839d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
840d302f017STejun Heo {
84163d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
842e22bee78STejun Heo 	unsigned int oflags = worker->flags;
843e22bee78STejun Heo 
844cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
845cb444766STejun Heo 
846d302f017STejun Heo 	worker->flags &= ~flags;
847e22bee78STejun Heo 
84842c025f3STejun Heo 	/*
84942c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
85042c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
85142c025f3STejun Heo 	 * of multiple flags, not a single flag.
85242c025f3STejun Heo 	 */
853e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
854e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
85563d95a91STejun Heo 			atomic_inc(get_pool_nr_running(pool));
856d302f017STejun Heo }
857d302f017STejun Heo 
858d302f017STejun Heo /**
859c8e55f36STejun Heo  * busy_worker_head - return the busy hash head for a work
860c8e55f36STejun Heo  * @gcwq: gcwq of interest
861c8e55f36STejun Heo  * @work: work to be hashed
862c8e55f36STejun Heo  *
863c8e55f36STejun Heo  * Return hash head of @gcwq for @work.
864c8e55f36STejun Heo  *
865c8e55f36STejun Heo  * CONTEXT:
866c8e55f36STejun Heo  * spin_lock_irq(gcwq->lock).
867c8e55f36STejun Heo  *
868c8e55f36STejun Heo  * RETURNS:
869c8e55f36STejun Heo  * Pointer to the hash head.
870c8e55f36STejun Heo  */
871c8e55f36STejun Heo static struct hlist_head *busy_worker_head(struct global_cwq *gcwq,
872c8e55f36STejun Heo 					   struct work_struct *work)
873c8e55f36STejun Heo {
874c8e55f36STejun Heo 	const int base_shift = ilog2(sizeof(struct work_struct));
875c8e55f36STejun Heo 	unsigned long v = (unsigned long)work;
876c8e55f36STejun Heo 
877c8e55f36STejun Heo 	/* simple shift and fold hash, do we need something better? */
878c8e55f36STejun Heo 	v >>= base_shift;
879c8e55f36STejun Heo 	v += v >> BUSY_WORKER_HASH_ORDER;
880c8e55f36STejun Heo 	v &= BUSY_WORKER_HASH_MASK;
881c8e55f36STejun Heo 
882c8e55f36STejun Heo 	return &gcwq->busy_hash[v];
883c8e55f36STejun Heo }
884c8e55f36STejun Heo 
885c8e55f36STejun Heo /**
8868cca0eeaSTejun Heo  * __find_worker_executing_work - find worker which is executing a work
8878cca0eeaSTejun Heo  * @gcwq: gcwq of interest
8888cca0eeaSTejun Heo  * @bwh: hash head as returned by busy_worker_head()
8898cca0eeaSTejun Heo  * @work: work to find worker for
8908cca0eeaSTejun Heo  *
8918cca0eeaSTejun Heo  * Find a worker which is executing @work on @gcwq.  @bwh should be
8928cca0eeaSTejun Heo  * the hash head obtained by calling busy_worker_head() with the same
8938cca0eeaSTejun Heo  * work.
8948cca0eeaSTejun Heo  *
8958cca0eeaSTejun Heo  * CONTEXT:
8968cca0eeaSTejun Heo  * spin_lock_irq(gcwq->lock).
8978cca0eeaSTejun Heo  *
8988cca0eeaSTejun Heo  * RETURNS:
8998cca0eeaSTejun Heo  * Pointer to worker which is executing @work if found, NULL
9008cca0eeaSTejun Heo  * otherwise.
9018cca0eeaSTejun Heo  */
9028cca0eeaSTejun Heo static struct worker *__find_worker_executing_work(struct global_cwq *gcwq,
9038cca0eeaSTejun Heo 						   struct hlist_head *bwh,
9048cca0eeaSTejun Heo 						   struct work_struct *work)
9058cca0eeaSTejun Heo {
9068cca0eeaSTejun Heo 	struct worker *worker;
9078cca0eeaSTejun Heo 	struct hlist_node *tmp;
9088cca0eeaSTejun Heo 
9098cca0eeaSTejun Heo 	hlist_for_each_entry(worker, tmp, bwh, hentry)
9108cca0eeaSTejun Heo 		if (worker->current_work == work)
9118cca0eeaSTejun Heo 			return worker;
9128cca0eeaSTejun Heo 	return NULL;
9138cca0eeaSTejun Heo }
9148cca0eeaSTejun Heo 
9158cca0eeaSTejun Heo /**
9168cca0eeaSTejun Heo  * find_worker_executing_work - find worker which is executing a work
9178cca0eeaSTejun Heo  * @gcwq: gcwq of interest
9188cca0eeaSTejun Heo  * @work: work to find worker for
9198cca0eeaSTejun Heo  *
9208cca0eeaSTejun Heo  * Find a worker which is executing @work on @gcwq.  This function is
9218cca0eeaSTejun Heo  * identical to __find_worker_executing_work() except that this
9228cca0eeaSTejun Heo  * function calculates @bwh itself.
9238cca0eeaSTejun Heo  *
9248cca0eeaSTejun Heo  * CONTEXT:
9258cca0eeaSTejun Heo  * spin_lock_irq(gcwq->lock).
9268cca0eeaSTejun Heo  *
9278cca0eeaSTejun Heo  * RETURNS:
9288cca0eeaSTejun Heo  * Pointer to worker which is executing @work if found, NULL
9298cca0eeaSTejun Heo  * otherwise.
9308cca0eeaSTejun Heo  */
9318cca0eeaSTejun Heo static struct worker *find_worker_executing_work(struct global_cwq *gcwq,
9328cca0eeaSTejun Heo 						 struct work_struct *work)
9338cca0eeaSTejun Heo {
9348cca0eeaSTejun Heo 	return __find_worker_executing_work(gcwq, busy_worker_head(gcwq, work),
9358cca0eeaSTejun Heo 					    work);
9368cca0eeaSTejun Heo }
9378cca0eeaSTejun Heo 
9388cca0eeaSTejun Heo /**
939bf4ede01STejun Heo  * move_linked_works - move linked works to a list
940bf4ede01STejun Heo  * @work: start of series of works to be scheduled
941bf4ede01STejun Heo  * @head: target list to append @work to
942bf4ede01STejun Heo  * @nextp: out paramter for nested worklist walking
943bf4ede01STejun Heo  *
944bf4ede01STejun Heo  * Schedule linked works starting from @work to @head.  Work series to
945bf4ede01STejun Heo  * be scheduled starts at @work and includes any consecutive work with
946bf4ede01STejun Heo  * WORK_STRUCT_LINKED set in its predecessor.
947bf4ede01STejun Heo  *
948bf4ede01STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of
949bf4ede01STejun Heo  * the last scheduled work.  This allows move_linked_works() to be
950bf4ede01STejun Heo  * nested inside outer list_for_each_entry_safe().
951bf4ede01STejun Heo  *
952bf4ede01STejun Heo  * CONTEXT:
953bf4ede01STejun Heo  * spin_lock_irq(gcwq->lock).
954bf4ede01STejun Heo  */
955bf4ede01STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
956bf4ede01STejun Heo 			      struct work_struct **nextp)
957bf4ede01STejun Heo {
958bf4ede01STejun Heo 	struct work_struct *n;
959bf4ede01STejun Heo 
960bf4ede01STejun Heo 	/*
961bf4ede01STejun Heo 	 * Linked worklist will always end before the end of the list,
962bf4ede01STejun Heo 	 * use NULL for list head.
963bf4ede01STejun Heo 	 */
964bf4ede01STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
965bf4ede01STejun Heo 		list_move_tail(&work->entry, head);
966bf4ede01STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
967bf4ede01STejun Heo 			break;
968bf4ede01STejun Heo 	}
969bf4ede01STejun Heo 
970bf4ede01STejun Heo 	/*
971bf4ede01STejun Heo 	 * If we're already inside safe list traversal and have moved
972bf4ede01STejun Heo 	 * multiple works to the scheduled queue, the next position
973bf4ede01STejun Heo 	 * needs to be updated.
974bf4ede01STejun Heo 	 */
975bf4ede01STejun Heo 	if (nextp)
976bf4ede01STejun Heo 		*nextp = n;
977bf4ede01STejun Heo }
978bf4ede01STejun Heo 
979bf4ede01STejun Heo static void cwq_activate_first_delayed(struct cpu_workqueue_struct *cwq)
980bf4ede01STejun Heo {
981bf4ede01STejun Heo 	struct work_struct *work = list_first_entry(&cwq->delayed_works,
982bf4ede01STejun Heo 						    struct work_struct, entry);
983bf4ede01STejun Heo 
984bf4ede01STejun Heo 	trace_workqueue_activate_work(work);
985bf4ede01STejun Heo 	move_linked_works(work, &cwq->pool->worklist, NULL);
986bf4ede01STejun Heo 	__clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
987bf4ede01STejun Heo 	cwq->nr_active++;
988bf4ede01STejun Heo }
989bf4ede01STejun Heo 
990bf4ede01STejun Heo /**
991bf4ede01STejun Heo  * cwq_dec_nr_in_flight - decrement cwq's nr_in_flight
992bf4ede01STejun Heo  * @cwq: cwq of interest
993bf4ede01STejun Heo  * @color: color of work which left the queue
994bf4ede01STejun Heo  * @delayed: for a delayed work
995bf4ede01STejun Heo  *
996bf4ede01STejun Heo  * A work either has completed or is removed from pending queue,
997bf4ede01STejun Heo  * decrement nr_in_flight of its cwq and handle workqueue flushing.
998bf4ede01STejun Heo  *
999bf4ede01STejun Heo  * CONTEXT:
1000bf4ede01STejun Heo  * spin_lock_irq(gcwq->lock).
1001bf4ede01STejun Heo  */
1002bf4ede01STejun Heo static void cwq_dec_nr_in_flight(struct cpu_workqueue_struct *cwq, int color,
1003bf4ede01STejun Heo 				 bool delayed)
1004bf4ede01STejun Heo {
1005bf4ede01STejun Heo 	/* ignore uncolored works */
1006bf4ede01STejun Heo 	if (color == WORK_NO_COLOR)
1007bf4ede01STejun Heo 		return;
1008bf4ede01STejun Heo 
1009bf4ede01STejun Heo 	cwq->nr_in_flight[color]--;
1010bf4ede01STejun Heo 
1011bf4ede01STejun Heo 	if (!delayed) {
1012bf4ede01STejun Heo 		cwq->nr_active--;
1013bf4ede01STejun Heo 		if (!list_empty(&cwq->delayed_works)) {
1014bf4ede01STejun Heo 			/* one down, submit a delayed one */
1015bf4ede01STejun Heo 			if (cwq->nr_active < cwq->max_active)
1016bf4ede01STejun Heo 				cwq_activate_first_delayed(cwq);
1017bf4ede01STejun Heo 		}
1018bf4ede01STejun Heo 	}
1019bf4ede01STejun Heo 
1020bf4ede01STejun Heo 	/* is flush in progress and are we at the flushing tip? */
1021bf4ede01STejun Heo 	if (likely(cwq->flush_color != color))
1022bf4ede01STejun Heo 		return;
1023bf4ede01STejun Heo 
1024bf4ede01STejun Heo 	/* are there still in-flight works? */
1025bf4ede01STejun Heo 	if (cwq->nr_in_flight[color])
1026bf4ede01STejun Heo 		return;
1027bf4ede01STejun Heo 
1028bf4ede01STejun Heo 	/* this cwq is done, clear flush_color */
1029bf4ede01STejun Heo 	cwq->flush_color = -1;
1030bf4ede01STejun Heo 
1031bf4ede01STejun Heo 	/*
1032bf4ede01STejun Heo 	 * If this was the last cwq, wake up the first flusher.  It
1033bf4ede01STejun Heo 	 * will handle the rest.
1034bf4ede01STejun Heo 	 */
1035bf4ede01STejun Heo 	if (atomic_dec_and_test(&cwq->wq->nr_cwqs_to_flush))
1036bf4ede01STejun Heo 		complete(&cwq->wq->first_flusher->done);
1037bf4ede01STejun Heo }
1038bf4ede01STejun Heo 
103936e227d2STejun Heo /**
1040bbb68dfaSTejun Heo  * try_to_grab_pending - steal work item from worklist and disable irq
104136e227d2STejun Heo  * @work: work item to steal
104236e227d2STejun Heo  * @is_dwork: @work is a delayed_work
1043bbb68dfaSTejun Heo  * @flags: place to store irq state
104436e227d2STejun Heo  *
104536e227d2STejun Heo  * Try to grab PENDING bit of @work.  This function can handle @work in any
104636e227d2STejun Heo  * stable state - idle, on timer or on worklist.  Return values are
104736e227d2STejun Heo  *
104836e227d2STejun Heo  *  1		if @work was pending and we successfully stole PENDING
104936e227d2STejun Heo  *  0		if @work was idle and we claimed PENDING
105036e227d2STejun Heo  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
1051bbb68dfaSTejun Heo  *  -ENOENT	if someone else is canceling @work, this state may persist
1052bbb68dfaSTejun Heo  *		for arbitrarily long
105336e227d2STejun Heo  *
1054bbb68dfaSTejun Heo  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
1055bbb68dfaSTejun Heo  * preempted while holding PENDING and @work off queue, preemption must be
1056bbb68dfaSTejun Heo  * disabled on entry.  This ensures that we don't return -EAGAIN while
1057bbb68dfaSTejun Heo  * another task is preempted in this function.
1058bbb68dfaSTejun Heo  *
1059bbb68dfaSTejun Heo  * On successful return, >= 0, irq is disabled and the caller is
1060bbb68dfaSTejun Heo  * responsible for releasing it using local_irq_restore(*@flags).
1061bbb68dfaSTejun Heo  *
1062bbb68dfaSTejun Heo  * This function is safe to call from any context other than IRQ handler.
1063bbb68dfaSTejun Heo  * An IRQ handler may run on top of delayed_work_timer_fn() which can make
1064bbb68dfaSTejun Heo  * this function return -EAGAIN perpetually.
1065bf4ede01STejun Heo  */
1066bbb68dfaSTejun Heo static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1067bbb68dfaSTejun Heo 			       unsigned long *flags)
1068bf4ede01STejun Heo {
1069bf4ede01STejun Heo 	struct global_cwq *gcwq;
1070bf4ede01STejun Heo 
1071bbb68dfaSTejun Heo 	WARN_ON_ONCE(in_irq());
1072bbb68dfaSTejun Heo 
1073bbb68dfaSTejun Heo 	local_irq_save(*flags);
1074bbb68dfaSTejun Heo 
107536e227d2STejun Heo 	/* try to steal the timer if it exists */
107636e227d2STejun Heo 	if (is_dwork) {
107736e227d2STejun Heo 		struct delayed_work *dwork = to_delayed_work(work);
107836e227d2STejun Heo 
107936e227d2STejun Heo 		if (likely(del_timer(&dwork->timer)))
108036e227d2STejun Heo 			return 1;
108136e227d2STejun Heo 	}
108236e227d2STejun Heo 
108336e227d2STejun Heo 	/* try to claim PENDING the normal way */
1084bf4ede01STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1085bf4ede01STejun Heo 		return 0;
1086bf4ede01STejun Heo 
1087bf4ede01STejun Heo 	/*
1088bf4ede01STejun Heo 	 * The queueing is in progress, or it is already queued. Try to
1089bf4ede01STejun Heo 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1090bf4ede01STejun Heo 	 */
1091bf4ede01STejun Heo 	gcwq = get_work_gcwq(work);
1092bf4ede01STejun Heo 	if (!gcwq)
1093bbb68dfaSTejun Heo 		goto fail;
1094bf4ede01STejun Heo 
1095bbb68dfaSTejun Heo 	spin_lock(&gcwq->lock);
1096bf4ede01STejun Heo 	if (!list_empty(&work->entry)) {
1097bf4ede01STejun Heo 		/*
1098bf4ede01STejun Heo 		 * This work is queued, but perhaps we locked the wrong gcwq.
1099bf4ede01STejun Heo 		 * In that case we must see the new value after rmb(), see
1100bf4ede01STejun Heo 		 * insert_work()->wmb().
1101bf4ede01STejun Heo 		 */
1102bf4ede01STejun Heo 		smp_rmb();
1103bf4ede01STejun Heo 		if (gcwq == get_work_gcwq(work)) {
1104bf4ede01STejun Heo 			debug_work_deactivate(work);
1105bf4ede01STejun Heo 			list_del_init(&work->entry);
1106bf4ede01STejun Heo 			cwq_dec_nr_in_flight(get_work_cwq(work),
1107bf4ede01STejun Heo 				get_work_color(work),
1108bf4ede01STejun Heo 				*work_data_bits(work) & WORK_STRUCT_DELAYED);
110936e227d2STejun Heo 
1110bbb68dfaSTejun Heo 			spin_unlock(&gcwq->lock);
111136e227d2STejun Heo 			return 1;
1112bf4ede01STejun Heo 		}
1113bf4ede01STejun Heo 	}
1114bbb68dfaSTejun Heo 	spin_unlock(&gcwq->lock);
1115bbb68dfaSTejun Heo fail:
1116bbb68dfaSTejun Heo 	local_irq_restore(*flags);
1117bbb68dfaSTejun Heo 	if (work_is_canceling(work))
1118bbb68dfaSTejun Heo 		return -ENOENT;
1119bbb68dfaSTejun Heo 	cpu_relax();
112036e227d2STejun Heo 	return -EAGAIN;
1121bf4ede01STejun Heo }
1122bf4ede01STejun Heo 
1123bf4ede01STejun Heo /**
11247e11629dSTejun Heo  * insert_work - insert a work into gcwq
11254690c4abSTejun Heo  * @cwq: cwq @work belongs to
11264690c4abSTejun Heo  * @work: work to insert
11274690c4abSTejun Heo  * @head: insertion point
11284690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
11294690c4abSTejun Heo  *
11307e11629dSTejun Heo  * Insert @work which belongs to @cwq into @gcwq after @head.
11317e11629dSTejun Heo  * @extra_flags is or'd to work_struct flags.
11324690c4abSTejun Heo  *
11334690c4abSTejun Heo  * CONTEXT:
11348b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock).
11351da177e4SLinus Torvalds  */
1136b89deed3SOleg Nesterov static void insert_work(struct cpu_workqueue_struct *cwq,
11374690c4abSTejun Heo 			struct work_struct *work, struct list_head *head,
11384690c4abSTejun Heo 			unsigned int extra_flags)
1139b89deed3SOleg Nesterov {
114063d95a91STejun Heo 	struct worker_pool *pool = cwq->pool;
1141e1d8aa9fSFrederic Weisbecker 
11424690c4abSTejun Heo 	/* we own @work, set data and link */
11437a22ad75STejun Heo 	set_work_cwq(work, cwq, extra_flags);
11444690c4abSTejun Heo 
11456e84d644SOleg Nesterov 	/*
11466e84d644SOleg Nesterov 	 * Ensure that we get the right work->data if we see the
11476e84d644SOleg Nesterov 	 * result of list_add() below, see try_to_grab_pending().
11486e84d644SOleg Nesterov 	 */
11496e84d644SOleg Nesterov 	smp_wmb();
11504690c4abSTejun Heo 
11511a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
1152e22bee78STejun Heo 
1153e22bee78STejun Heo 	/*
1154e22bee78STejun Heo 	 * Ensure either worker_sched_deactivated() sees the above
1155e22bee78STejun Heo 	 * list_add_tail() or we see zero nr_running to avoid workers
1156e22bee78STejun Heo 	 * lying around lazily while there are works to be processed.
1157e22bee78STejun Heo 	 */
1158e22bee78STejun Heo 	smp_mb();
1159e22bee78STejun Heo 
116063d95a91STejun Heo 	if (__need_more_worker(pool))
116163d95a91STejun Heo 		wake_up_worker(pool);
1162b89deed3SOleg Nesterov }
1163b89deed3SOleg Nesterov 
1164c8efcc25STejun Heo /*
1165c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
1166c8efcc25STejun Heo  * same workqueue.  This is rather expensive and should only be used from
1167c8efcc25STejun Heo  * cold paths.
1168c8efcc25STejun Heo  */
1169c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
1170c8efcc25STejun Heo {
1171c8efcc25STejun Heo 	unsigned long flags;
1172c8efcc25STejun Heo 	unsigned int cpu;
1173c8efcc25STejun Heo 
1174c8efcc25STejun Heo 	for_each_gcwq_cpu(cpu) {
1175c8efcc25STejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
1176c8efcc25STejun Heo 		struct worker *worker;
1177c8efcc25STejun Heo 		struct hlist_node *pos;
1178c8efcc25STejun Heo 		int i;
1179c8efcc25STejun Heo 
1180c8efcc25STejun Heo 		spin_lock_irqsave(&gcwq->lock, flags);
1181c8efcc25STejun Heo 		for_each_busy_worker(worker, i, pos, gcwq) {
1182c8efcc25STejun Heo 			if (worker->task != current)
1183c8efcc25STejun Heo 				continue;
1184c8efcc25STejun Heo 			spin_unlock_irqrestore(&gcwq->lock, flags);
1185c8efcc25STejun Heo 			/*
1186c8efcc25STejun Heo 			 * I'm @worker, no locking necessary.  See if @work
1187c8efcc25STejun Heo 			 * is headed to the same workqueue.
1188c8efcc25STejun Heo 			 */
1189c8efcc25STejun Heo 			return worker->current_cwq->wq == wq;
1190c8efcc25STejun Heo 		}
1191c8efcc25STejun Heo 		spin_unlock_irqrestore(&gcwq->lock, flags);
1192c8efcc25STejun Heo 	}
1193c8efcc25STejun Heo 	return false;
1194c8efcc25STejun Heo }
1195c8efcc25STejun Heo 
11964690c4abSTejun Heo static void __queue_work(unsigned int cpu, struct workqueue_struct *wq,
11971da177e4SLinus Torvalds 			 struct work_struct *work)
11981da177e4SLinus Torvalds {
1199502ca9d8STejun Heo 	struct global_cwq *gcwq;
1200502ca9d8STejun Heo 	struct cpu_workqueue_struct *cwq;
12011e19ffc6STejun Heo 	struct list_head *worklist;
12028a2e8e5dSTejun Heo 	unsigned int work_flags;
1203b75cac93SJoonsoo Kim 	unsigned int req_cpu = cpu;
12048930cabaSTejun Heo 
12058930cabaSTejun Heo 	/*
12068930cabaSTejun Heo 	 * While a work item is PENDING && off queue, a task trying to
12078930cabaSTejun Heo 	 * steal the PENDING will busy-loop waiting for it to either get
12088930cabaSTejun Heo 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
12098930cabaSTejun Heo 	 * happen with IRQ disabled.
12108930cabaSTejun Heo 	 */
12118930cabaSTejun Heo 	WARN_ON_ONCE(!irqs_disabled());
12121da177e4SLinus Torvalds 
1213dc186ad7SThomas Gleixner 	debug_work_activate(work);
12141e19ffc6STejun Heo 
1215c8efcc25STejun Heo 	/* if dying, only works from the same workqueue are allowed */
12169c5a2ba7STejun Heo 	if (unlikely(wq->flags & WQ_DRAINING) &&
1217c8efcc25STejun Heo 	    WARN_ON_ONCE(!is_chained_work(wq)))
1218e41e704bSTejun Heo 		return;
1219e41e704bSTejun Heo 
1220c7fc77f7STejun Heo 	/* determine gcwq to use */
1221c7fc77f7STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
1222c7fc77f7STejun Heo 		struct global_cwq *last_gcwq;
1223c7fc77f7STejun Heo 
122457469821STejun Heo 		if (cpu == WORK_CPU_UNBOUND)
1225f3421797STejun Heo 			cpu = raw_smp_processor_id();
1226f3421797STejun Heo 
122718aa9effSTejun Heo 		/*
122818aa9effSTejun Heo 		 * It's multi cpu.  If @wq is non-reentrant and @work
122918aa9effSTejun Heo 		 * was previously on a different cpu, it might still
123018aa9effSTejun Heo 		 * be running there, in which case the work needs to
123118aa9effSTejun Heo 		 * be queued on that cpu to guarantee non-reentrance.
123218aa9effSTejun Heo 		 */
1233502ca9d8STejun Heo 		gcwq = get_gcwq(cpu);
123418aa9effSTejun Heo 		if (wq->flags & WQ_NON_REENTRANT &&
123518aa9effSTejun Heo 		    (last_gcwq = get_work_gcwq(work)) && last_gcwq != gcwq) {
123618aa9effSTejun Heo 			struct worker *worker;
123718aa9effSTejun Heo 
12388930cabaSTejun Heo 			spin_lock(&last_gcwq->lock);
123918aa9effSTejun Heo 
124018aa9effSTejun Heo 			worker = find_worker_executing_work(last_gcwq, work);
124118aa9effSTejun Heo 
124218aa9effSTejun Heo 			if (worker && worker->current_cwq->wq == wq)
124318aa9effSTejun Heo 				gcwq = last_gcwq;
124418aa9effSTejun Heo 			else {
124518aa9effSTejun Heo 				/* meh... not running there, queue here */
12468930cabaSTejun Heo 				spin_unlock(&last_gcwq->lock);
12478930cabaSTejun Heo 				spin_lock(&gcwq->lock);
124818aa9effSTejun Heo 			}
12498930cabaSTejun Heo 		} else {
12508930cabaSTejun Heo 			spin_lock(&gcwq->lock);
12518930cabaSTejun Heo 		}
1252f3421797STejun Heo 	} else {
1253f3421797STejun Heo 		gcwq = get_gcwq(WORK_CPU_UNBOUND);
12548930cabaSTejun Heo 		spin_lock(&gcwq->lock);
1255502ca9d8STejun Heo 	}
1256502ca9d8STejun Heo 
1257502ca9d8STejun Heo 	/* gcwq determined, get cwq and queue */
1258502ca9d8STejun Heo 	cwq = get_cwq(gcwq->cpu, wq);
1259b75cac93SJoonsoo Kim 	trace_workqueue_queue_work(req_cpu, cwq, work);
1260502ca9d8STejun Heo 
1261f5b2552bSDan Carpenter 	if (WARN_ON(!list_empty(&work->entry))) {
12628930cabaSTejun Heo 		spin_unlock(&gcwq->lock);
1263f5b2552bSDan Carpenter 		return;
1264f5b2552bSDan Carpenter 	}
12651e19ffc6STejun Heo 
126673f53c4aSTejun Heo 	cwq->nr_in_flight[cwq->work_color]++;
12678a2e8e5dSTejun Heo 	work_flags = work_color_to_flags(cwq->work_color);
12681e19ffc6STejun Heo 
12691e19ffc6STejun Heo 	if (likely(cwq->nr_active < cwq->max_active)) {
1270cdadf009STejun Heo 		trace_workqueue_activate_work(work);
12711e19ffc6STejun Heo 		cwq->nr_active++;
12723270476aSTejun Heo 		worklist = &cwq->pool->worklist;
12738a2e8e5dSTejun Heo 	} else {
12748a2e8e5dSTejun Heo 		work_flags |= WORK_STRUCT_DELAYED;
12751e19ffc6STejun Heo 		worklist = &cwq->delayed_works;
12768a2e8e5dSTejun Heo 	}
12771e19ffc6STejun Heo 
12788a2e8e5dSTejun Heo 	insert_work(cwq, work, worklist, work_flags);
12791e19ffc6STejun Heo 
12808930cabaSTejun Heo 	spin_unlock(&gcwq->lock);
12811da177e4SLinus Torvalds }
12821da177e4SLinus Torvalds 
12830fcb78c2SRolf Eike Beer /**
1284c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
1285c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
1286c1a220e7SZhang Rui  * @wq: workqueue to use
1287c1a220e7SZhang Rui  * @work: work to queue
1288c1a220e7SZhang Rui  *
1289d4283e93STejun Heo  * Returns %false if @work was already on a queue, %true otherwise.
1290c1a220e7SZhang Rui  *
1291c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
1292c1a220e7SZhang Rui  * can't go away.
1293c1a220e7SZhang Rui  */
1294d4283e93STejun Heo bool queue_work_on(int cpu, struct workqueue_struct *wq,
1295d4283e93STejun Heo 		   struct work_struct *work)
1296c1a220e7SZhang Rui {
1297d4283e93STejun Heo 	bool ret = false;
12988930cabaSTejun Heo 	unsigned long flags;
12998930cabaSTejun Heo 
13008930cabaSTejun Heo 	local_irq_save(flags);
1301c1a220e7SZhang Rui 
130222df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
13034690c4abSTejun Heo 		__queue_work(cpu, wq, work);
1304d4283e93STejun Heo 		ret = true;
1305c1a220e7SZhang Rui 	}
13068930cabaSTejun Heo 
13078930cabaSTejun Heo 	local_irq_restore(flags);
1308c1a220e7SZhang Rui 	return ret;
1309c1a220e7SZhang Rui }
1310c1a220e7SZhang Rui EXPORT_SYMBOL_GPL(queue_work_on);
1311c1a220e7SZhang Rui 
13120a13c00eSTejun Heo /**
13130a13c00eSTejun Heo  * queue_work - queue work on a workqueue
13140a13c00eSTejun Heo  * @wq: workqueue to use
13150a13c00eSTejun Heo  * @work: work to queue
13160a13c00eSTejun Heo  *
1317d4283e93STejun Heo  * Returns %false if @work was already on a queue, %true otherwise.
13180a13c00eSTejun Heo  *
13190a13c00eSTejun Heo  * We queue the work to the CPU on which it was submitted, but if the CPU dies
13200a13c00eSTejun Heo  * it can be processed by another CPU.
13210a13c00eSTejun Heo  */
1322d4283e93STejun Heo bool queue_work(struct workqueue_struct *wq, struct work_struct *work)
13230a13c00eSTejun Heo {
132457469821STejun Heo 	return queue_work_on(WORK_CPU_UNBOUND, wq, work);
13250a13c00eSTejun Heo }
13260a13c00eSTejun Heo EXPORT_SYMBOL_GPL(queue_work);
13270a13c00eSTejun Heo 
1328d8e794dfSTejun Heo void delayed_work_timer_fn(unsigned long __data)
13291da177e4SLinus Torvalds {
133052bad64dSDavid Howells 	struct delayed_work *dwork = (struct delayed_work *)__data;
13317a22ad75STejun Heo 	struct cpu_workqueue_struct *cwq = get_work_cwq(&dwork->work);
13321da177e4SLinus Torvalds 
13338930cabaSTejun Heo 	local_irq_disable();
13341265057fSTejun Heo 	__queue_work(dwork->cpu, cwq->wq, &dwork->work);
13358930cabaSTejun Heo 	local_irq_enable();
13361da177e4SLinus Torvalds }
1337d8e794dfSTejun Heo EXPORT_SYMBOL_GPL(delayed_work_timer_fn);
13381da177e4SLinus Torvalds 
13397beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
13407beb2edfSTejun Heo 				struct delayed_work *dwork, unsigned long delay)
13417beb2edfSTejun Heo {
13427beb2edfSTejun Heo 	struct timer_list *timer = &dwork->timer;
13437beb2edfSTejun Heo 	struct work_struct *work = &dwork->work;
13447beb2edfSTejun Heo 	unsigned int lcpu;
13457beb2edfSTejun Heo 
13467beb2edfSTejun Heo 	WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
13477beb2edfSTejun Heo 		     timer->data != (unsigned long)dwork);
13487beb2edfSTejun Heo 	BUG_ON(timer_pending(timer));
13497beb2edfSTejun Heo 	BUG_ON(!list_empty(&work->entry));
13507beb2edfSTejun Heo 
13517beb2edfSTejun Heo 	timer_stats_timer_set_start_info(&dwork->timer);
13527beb2edfSTejun Heo 
13537beb2edfSTejun Heo 	/*
13547beb2edfSTejun Heo 	 * This stores cwq for the moment, for the timer_fn.  Note that the
13557beb2edfSTejun Heo 	 * work's gcwq is preserved to allow reentrance detection for
13567beb2edfSTejun Heo 	 * delayed works.
13577beb2edfSTejun Heo 	 */
13587beb2edfSTejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
13597beb2edfSTejun Heo 		struct global_cwq *gcwq = get_work_gcwq(work);
13607beb2edfSTejun Heo 
1361e42986deSJoonsoo Kim 		/*
1362e42986deSJoonsoo Kim 		 * If we cannot get the last gcwq from @work directly,
1363e42986deSJoonsoo Kim 		 * select the last CPU such that it avoids unnecessarily
1364e42986deSJoonsoo Kim 		 * triggering non-reentrancy check in __queue_work().
1365e42986deSJoonsoo Kim 		 */
1366e42986deSJoonsoo Kim 		lcpu = cpu;
1367e42986deSJoonsoo Kim 		if (gcwq)
13687beb2edfSTejun Heo 			lcpu = gcwq->cpu;
1369e42986deSJoonsoo Kim 		if (lcpu == WORK_CPU_UNBOUND)
13707beb2edfSTejun Heo 			lcpu = raw_smp_processor_id();
13717beb2edfSTejun Heo 	} else {
13727beb2edfSTejun Heo 		lcpu = WORK_CPU_UNBOUND;
13737beb2edfSTejun Heo 	}
13747beb2edfSTejun Heo 
13757beb2edfSTejun Heo 	set_work_cwq(work, get_cwq(lcpu, wq), 0);
13767beb2edfSTejun Heo 
13771265057fSTejun Heo 	dwork->cpu = cpu;
13787beb2edfSTejun Heo 	timer->expires = jiffies + delay;
13797beb2edfSTejun Heo 
13807beb2edfSTejun Heo 	if (unlikely(cpu != WORK_CPU_UNBOUND))
13817beb2edfSTejun Heo 		add_timer_on(timer, cpu);
13827beb2edfSTejun Heo 	else
13837beb2edfSTejun Heo 		add_timer(timer);
13847beb2edfSTejun Heo }
13857beb2edfSTejun Heo 
13860fcb78c2SRolf Eike Beer /**
13870fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
13880fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
13890fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1390af9997e4SRandy Dunlap  * @dwork: work to queue
13910fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
13920fcb78c2SRolf Eike Beer  *
1393715f1300STejun Heo  * Returns %false if @work was already on a queue, %true otherwise.  If
1394715f1300STejun Heo  * @delay is zero and @dwork is idle, it will be scheduled for immediate
1395715f1300STejun Heo  * execution.
13960fcb78c2SRolf Eike Beer  */
1397d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
139852bad64dSDavid Howells 			   struct delayed_work *dwork, unsigned long delay)
13997a6bc1cdSVenkatesh Pallipadi {
140052bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
1401d4283e93STejun Heo 	bool ret = false;
14028930cabaSTejun Heo 	unsigned long flags;
14038930cabaSTejun Heo 
1404715f1300STejun Heo 	if (!delay)
1405715f1300STejun Heo 		return queue_work_on(cpu, wq, &dwork->work);
1406715f1300STejun Heo 
14078930cabaSTejun Heo 	/* read the comment in __queue_work() */
14088930cabaSTejun Heo 	local_irq_save(flags);
14097a6bc1cdSVenkatesh Pallipadi 
141022df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
14117beb2edfSTejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
1412d4283e93STejun Heo 		ret = true;
14137a6bc1cdSVenkatesh Pallipadi 	}
14148930cabaSTejun Heo 
14158930cabaSTejun Heo 	local_irq_restore(flags);
14167a6bc1cdSVenkatesh Pallipadi 	return ret;
14177a6bc1cdSVenkatesh Pallipadi }
1418ae90dd5dSDave Jones EXPORT_SYMBOL_GPL(queue_delayed_work_on);
14191da177e4SLinus Torvalds 
1420c8e55f36STejun Heo /**
14210a13c00eSTejun Heo  * queue_delayed_work - queue work on a workqueue after delay
14220a13c00eSTejun Heo  * @wq: workqueue to use
14230a13c00eSTejun Heo  * @dwork: delayable work to queue
14240a13c00eSTejun Heo  * @delay: number of jiffies to wait before queueing
14250a13c00eSTejun Heo  *
1426715f1300STejun Heo  * Equivalent to queue_delayed_work_on() but tries to use the local CPU.
14270a13c00eSTejun Heo  */
1428d4283e93STejun Heo bool queue_delayed_work(struct workqueue_struct *wq,
14290a13c00eSTejun Heo 			struct delayed_work *dwork, unsigned long delay)
14300a13c00eSTejun Heo {
143157469821STejun Heo 	return queue_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
14320a13c00eSTejun Heo }
14330a13c00eSTejun Heo EXPORT_SYMBOL_GPL(queue_delayed_work);
14340a13c00eSTejun Heo 
14350a13c00eSTejun Heo /**
14368376fe22STejun Heo  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
14378376fe22STejun Heo  * @cpu: CPU number to execute work on
14388376fe22STejun Heo  * @wq: workqueue to use
14398376fe22STejun Heo  * @dwork: work to queue
14408376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
14418376fe22STejun Heo  *
14428376fe22STejun Heo  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
14438376fe22STejun Heo  * modify @dwork's timer so that it expires after @delay.  If @delay is
14448376fe22STejun Heo  * zero, @work is guaranteed to be scheduled immediately regardless of its
14458376fe22STejun Heo  * current state.
14468376fe22STejun Heo  *
14478376fe22STejun Heo  * Returns %false if @dwork was idle and queued, %true if @dwork was
14488376fe22STejun Heo  * pending and its timer was modified.
14498376fe22STejun Heo  *
14508376fe22STejun Heo  * This function is safe to call from any context other than IRQ handler.
14518376fe22STejun Heo  * See try_to_grab_pending() for details.
14528376fe22STejun Heo  */
14538376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
14548376fe22STejun Heo 			 struct delayed_work *dwork, unsigned long delay)
14558376fe22STejun Heo {
14568376fe22STejun Heo 	unsigned long flags;
14578376fe22STejun Heo 	int ret;
14588376fe22STejun Heo 
14598376fe22STejun Heo 	do {
14608376fe22STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
14618376fe22STejun Heo 	} while (unlikely(ret == -EAGAIN));
14628376fe22STejun Heo 
14638376fe22STejun Heo 	if (likely(ret >= 0)) {
14648376fe22STejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
14658376fe22STejun Heo 		local_irq_restore(flags);
14668376fe22STejun Heo 	}
14678376fe22STejun Heo 
14688376fe22STejun Heo 	/* -ENOENT from try_to_grab_pending() becomes %true */
14698376fe22STejun Heo 	return ret;
14708376fe22STejun Heo }
14718376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
14728376fe22STejun Heo 
14738376fe22STejun Heo /**
14748376fe22STejun Heo  * mod_delayed_work - modify delay of or queue a delayed work
14758376fe22STejun Heo  * @wq: workqueue to use
14768376fe22STejun Heo  * @dwork: work to queue
14778376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
14788376fe22STejun Heo  *
14798376fe22STejun Heo  * mod_delayed_work_on() on local CPU.
14808376fe22STejun Heo  */
14818376fe22STejun Heo bool mod_delayed_work(struct workqueue_struct *wq, struct delayed_work *dwork,
14828376fe22STejun Heo 		      unsigned long delay)
14838376fe22STejun Heo {
14848376fe22STejun Heo 	return mod_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
14858376fe22STejun Heo }
14868376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work);
14878376fe22STejun Heo 
14888376fe22STejun Heo /**
1489c8e55f36STejun Heo  * worker_enter_idle - enter idle state
1490c8e55f36STejun Heo  * @worker: worker which is entering idle state
1491c8e55f36STejun Heo  *
1492c8e55f36STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
1493c8e55f36STejun Heo  * necessary.
1494c8e55f36STejun Heo  *
1495c8e55f36STejun Heo  * LOCKING:
1496c8e55f36STejun Heo  * spin_lock_irq(gcwq->lock).
1497c8e55f36STejun Heo  */
1498c8e55f36STejun Heo static void worker_enter_idle(struct worker *worker)
14991da177e4SLinus Torvalds {
1500bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1501bd7bdd43STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
1502c8e55f36STejun Heo 
1503c8e55f36STejun Heo 	BUG_ON(worker->flags & WORKER_IDLE);
1504c8e55f36STejun Heo 	BUG_ON(!list_empty(&worker->entry) &&
1505c8e55f36STejun Heo 	       (worker->hentry.next || worker->hentry.pprev));
1506c8e55f36STejun Heo 
1507cb444766STejun Heo 	/* can't use worker_set_flags(), also called from start_worker() */
1508cb444766STejun Heo 	worker->flags |= WORKER_IDLE;
1509bd7bdd43STejun Heo 	pool->nr_idle++;
1510e22bee78STejun Heo 	worker->last_active = jiffies;
1511c8e55f36STejun Heo 
1512c8e55f36STejun Heo 	/* idle_list is LIFO */
1513bd7bdd43STejun Heo 	list_add(&worker->entry, &pool->idle_list);
1514db7bccf4STejun Heo 
151563d95a91STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1516628c78e7STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1517cb444766STejun Heo 
1518544ecf31STejun Heo 	/*
1519628c78e7STejun Heo 	 * Sanity check nr_running.  Because gcwq_unbind_fn() releases
1520628c78e7STejun Heo 	 * gcwq->lock between setting %WORKER_UNBOUND and zapping
1521628c78e7STejun Heo 	 * nr_running, the warning may trigger spuriously.  Check iff
1522628c78e7STejun Heo 	 * unbind is not in progress.
1523544ecf31STejun Heo 	 */
1524628c78e7STejun Heo 	WARN_ON_ONCE(!(gcwq->flags & GCWQ_DISASSOCIATED) &&
1525bd7bdd43STejun Heo 		     pool->nr_workers == pool->nr_idle &&
152663d95a91STejun Heo 		     atomic_read(get_pool_nr_running(pool)));
1527c8e55f36STejun Heo }
1528c8e55f36STejun Heo 
1529c8e55f36STejun Heo /**
1530c8e55f36STejun Heo  * worker_leave_idle - leave idle state
1531c8e55f36STejun Heo  * @worker: worker which is leaving idle state
1532c8e55f36STejun Heo  *
1533c8e55f36STejun Heo  * @worker is leaving idle state.  Update stats.
1534c8e55f36STejun Heo  *
1535c8e55f36STejun Heo  * LOCKING:
1536c8e55f36STejun Heo  * spin_lock_irq(gcwq->lock).
1537c8e55f36STejun Heo  */
1538c8e55f36STejun Heo static void worker_leave_idle(struct worker *worker)
1539c8e55f36STejun Heo {
1540bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1541c8e55f36STejun Heo 
1542c8e55f36STejun Heo 	BUG_ON(!(worker->flags & WORKER_IDLE));
1543d302f017STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
1544bd7bdd43STejun Heo 	pool->nr_idle--;
1545c8e55f36STejun Heo 	list_del_init(&worker->entry);
1546c8e55f36STejun Heo }
1547c8e55f36STejun Heo 
1548e22bee78STejun Heo /**
1549e22bee78STejun Heo  * worker_maybe_bind_and_lock - bind worker to its cpu if possible and lock gcwq
1550e22bee78STejun Heo  * @worker: self
1551e22bee78STejun Heo  *
1552e22bee78STejun Heo  * Works which are scheduled while the cpu is online must at least be
1553e22bee78STejun Heo  * scheduled to a worker which is bound to the cpu so that if they are
1554e22bee78STejun Heo  * flushed from cpu callbacks while cpu is going down, they are
1555e22bee78STejun Heo  * guaranteed to execute on the cpu.
1556e22bee78STejun Heo  *
1557e22bee78STejun Heo  * This function is to be used by rogue workers and rescuers to bind
1558e22bee78STejun Heo  * themselves to the target cpu and may race with cpu going down or
1559e22bee78STejun Heo  * coming online.  kthread_bind() can't be used because it may put the
1560e22bee78STejun Heo  * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1561e22bee78STejun Heo  * verbatim as it's best effort and blocking and gcwq may be
1562e22bee78STejun Heo  * [dis]associated in the meantime.
1563e22bee78STejun Heo  *
1564f2d5a0eeSTejun Heo  * This function tries set_cpus_allowed() and locks gcwq and verifies the
1565f2d5a0eeSTejun Heo  * binding against %GCWQ_DISASSOCIATED which is set during
1566f2d5a0eeSTejun Heo  * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
1567f2d5a0eeSTejun Heo  * enters idle state or fetches works without dropping lock, it can
1568f2d5a0eeSTejun Heo  * guarantee the scheduling requirement described in the first paragraph.
1569e22bee78STejun Heo  *
1570e22bee78STejun Heo  * CONTEXT:
1571e22bee78STejun Heo  * Might sleep.  Called without any lock but returns with gcwq->lock
1572e22bee78STejun Heo  * held.
1573e22bee78STejun Heo  *
1574e22bee78STejun Heo  * RETURNS:
1575e22bee78STejun Heo  * %true if the associated gcwq is online (@worker is successfully
1576e22bee78STejun Heo  * bound), %false if offline.
1577e22bee78STejun Heo  */
1578e22bee78STejun Heo static bool worker_maybe_bind_and_lock(struct worker *worker)
1579972fa1c5SNamhyung Kim __acquires(&gcwq->lock)
1580e22bee78STejun Heo {
1581bd7bdd43STejun Heo 	struct global_cwq *gcwq = worker->pool->gcwq;
1582e22bee78STejun Heo 	struct task_struct *task = worker->task;
1583e22bee78STejun Heo 
1584e22bee78STejun Heo 	while (true) {
1585e22bee78STejun Heo 		/*
1586e22bee78STejun Heo 		 * The following call may fail, succeed or succeed
1587e22bee78STejun Heo 		 * without actually migrating the task to the cpu if
1588e22bee78STejun Heo 		 * it races with cpu hotunplug operation.  Verify
1589e22bee78STejun Heo 		 * against GCWQ_DISASSOCIATED.
1590e22bee78STejun Heo 		 */
1591f3421797STejun Heo 		if (!(gcwq->flags & GCWQ_DISASSOCIATED))
1592e22bee78STejun Heo 			set_cpus_allowed_ptr(task, get_cpu_mask(gcwq->cpu));
1593e22bee78STejun Heo 
1594e22bee78STejun Heo 		spin_lock_irq(&gcwq->lock);
1595e22bee78STejun Heo 		if (gcwq->flags & GCWQ_DISASSOCIATED)
1596e22bee78STejun Heo 			return false;
1597e22bee78STejun Heo 		if (task_cpu(task) == gcwq->cpu &&
1598e22bee78STejun Heo 		    cpumask_equal(&current->cpus_allowed,
1599e22bee78STejun Heo 				  get_cpu_mask(gcwq->cpu)))
1600e22bee78STejun Heo 			return true;
1601e22bee78STejun Heo 		spin_unlock_irq(&gcwq->lock);
1602e22bee78STejun Heo 
16035035b20fSTejun Heo 		/*
16045035b20fSTejun Heo 		 * We've raced with CPU hot[un]plug.  Give it a breather
16055035b20fSTejun Heo 		 * and retry migration.  cond_resched() is required here;
16065035b20fSTejun Heo 		 * otherwise, we might deadlock against cpu_stop trying to
16075035b20fSTejun Heo 		 * bring down the CPU on non-preemptive kernel.
16085035b20fSTejun Heo 		 */
1609e22bee78STejun Heo 		cpu_relax();
16105035b20fSTejun Heo 		cond_resched();
1611e22bee78STejun Heo 	}
1612e22bee78STejun Heo }
1613e22bee78STejun Heo 
161425511a47STejun Heo struct idle_rebind {
161525511a47STejun Heo 	int			cnt;		/* # workers to be rebound */
161625511a47STejun Heo 	struct completion	done;		/* all workers rebound */
161725511a47STejun Heo };
161825511a47STejun Heo 
1619e22bee78STejun Heo /*
162025511a47STejun Heo  * Rebind an idle @worker to its CPU.  During CPU onlining, this has to
162125511a47STejun Heo  * happen synchronously for idle workers.  worker_thread() will test
162225511a47STejun Heo  * %WORKER_REBIND before leaving idle and call this function.
162325511a47STejun Heo  */
162425511a47STejun Heo static void idle_worker_rebind(struct worker *worker)
162525511a47STejun Heo {
162625511a47STejun Heo 	struct global_cwq *gcwq = worker->pool->gcwq;
162725511a47STejun Heo 
162825511a47STejun Heo 	/* CPU must be online at this point */
162925511a47STejun Heo 	WARN_ON(!worker_maybe_bind_and_lock(worker));
163025511a47STejun Heo 	if (!--worker->idle_rebind->cnt)
163125511a47STejun Heo 		complete(&worker->idle_rebind->done);
163225511a47STejun Heo 	spin_unlock_irq(&worker->pool->gcwq->lock);
163325511a47STejun Heo 
163425511a47STejun Heo 	/* we did our part, wait for rebind_workers() to finish up */
163525511a47STejun Heo 	wait_event(gcwq->rebind_hold, !(worker->flags & WORKER_REBIND));
163625511a47STejun Heo }
163725511a47STejun Heo 
163825511a47STejun Heo /*
163925511a47STejun Heo  * Function for @worker->rebind.work used to rebind unbound busy workers to
1640403c821dSTejun Heo  * the associated cpu which is coming back online.  This is scheduled by
1641403c821dSTejun Heo  * cpu up but can race with other cpu hotplug operations and may be
1642403c821dSTejun Heo  * executed twice without intervening cpu down.
1643e22bee78STejun Heo  */
164425511a47STejun Heo static void busy_worker_rebind_fn(struct work_struct *work)
1645e22bee78STejun Heo {
1646e22bee78STejun Heo 	struct worker *worker = container_of(work, struct worker, rebind_work);
1647bd7bdd43STejun Heo 	struct global_cwq *gcwq = worker->pool->gcwq;
1648e22bee78STejun Heo 
1649e22bee78STejun Heo 	if (worker_maybe_bind_and_lock(worker))
1650e22bee78STejun Heo 		worker_clr_flags(worker, WORKER_REBIND);
1651e22bee78STejun Heo 
1652e22bee78STejun Heo 	spin_unlock_irq(&gcwq->lock);
1653e22bee78STejun Heo }
1654e22bee78STejun Heo 
165525511a47STejun Heo /**
165625511a47STejun Heo  * rebind_workers - rebind all workers of a gcwq to the associated CPU
165725511a47STejun Heo  * @gcwq: gcwq of interest
165825511a47STejun Heo  *
165925511a47STejun Heo  * @gcwq->cpu is coming online.  Rebind all workers to the CPU.  Rebinding
166025511a47STejun Heo  * is different for idle and busy ones.
166125511a47STejun Heo  *
166225511a47STejun Heo  * The idle ones should be rebound synchronously and idle rebinding should
166325511a47STejun Heo  * be complete before any worker starts executing work items with
166425511a47STejun Heo  * concurrency management enabled; otherwise, scheduler may oops trying to
166525511a47STejun Heo  * wake up non-local idle worker from wq_worker_sleeping().
166625511a47STejun Heo  *
166725511a47STejun Heo  * This is achieved by repeatedly requesting rebinding until all idle
166825511a47STejun Heo  * workers are known to have been rebound under @gcwq->lock and holding all
166925511a47STejun Heo  * idle workers from becoming busy until idle rebinding is complete.
167025511a47STejun Heo  *
167125511a47STejun Heo  * Once idle workers are rebound, busy workers can be rebound as they
167225511a47STejun Heo  * finish executing their current work items.  Queueing the rebind work at
167325511a47STejun Heo  * the head of their scheduled lists is enough.  Note that nr_running will
167425511a47STejun Heo  * be properbly bumped as busy workers rebind.
167525511a47STejun Heo  *
167625511a47STejun Heo  * On return, all workers are guaranteed to either be bound or have rebind
167725511a47STejun Heo  * work item scheduled.
167825511a47STejun Heo  */
167925511a47STejun Heo static void rebind_workers(struct global_cwq *gcwq)
168025511a47STejun Heo 	__releases(&gcwq->lock) __acquires(&gcwq->lock)
168125511a47STejun Heo {
168225511a47STejun Heo 	struct idle_rebind idle_rebind;
168325511a47STejun Heo 	struct worker_pool *pool;
168425511a47STejun Heo 	struct worker *worker;
168525511a47STejun Heo 	struct hlist_node *pos;
168625511a47STejun Heo 	int i;
168725511a47STejun Heo 
168825511a47STejun Heo 	lockdep_assert_held(&gcwq->lock);
168925511a47STejun Heo 
169025511a47STejun Heo 	for_each_worker_pool(pool, gcwq)
169125511a47STejun Heo 		lockdep_assert_held(&pool->manager_mutex);
169225511a47STejun Heo 
169325511a47STejun Heo 	/*
169425511a47STejun Heo 	 * Rebind idle workers.  Interlocked both ways.  We wait for
169525511a47STejun Heo 	 * workers to rebind via @idle_rebind.done.  Workers will wait for
169625511a47STejun Heo 	 * us to finish up by watching %WORKER_REBIND.
169725511a47STejun Heo 	 */
169825511a47STejun Heo 	init_completion(&idle_rebind.done);
169925511a47STejun Heo retry:
170025511a47STejun Heo 	idle_rebind.cnt = 1;
170125511a47STejun Heo 	INIT_COMPLETION(idle_rebind.done);
170225511a47STejun Heo 
170325511a47STejun Heo 	/* set REBIND and kick idle ones, we'll wait for these later */
170425511a47STejun Heo 	for_each_worker_pool(pool, gcwq) {
170525511a47STejun Heo 		list_for_each_entry(worker, &pool->idle_list, entry) {
170625511a47STejun Heo 			if (worker->flags & WORKER_REBIND)
170725511a47STejun Heo 				continue;
170825511a47STejun Heo 
170925511a47STejun Heo 			/* morph UNBOUND to REBIND */
171025511a47STejun Heo 			worker->flags &= ~WORKER_UNBOUND;
171125511a47STejun Heo 			worker->flags |= WORKER_REBIND;
171225511a47STejun Heo 
171325511a47STejun Heo 			idle_rebind.cnt++;
171425511a47STejun Heo 			worker->idle_rebind = &idle_rebind;
171525511a47STejun Heo 
171625511a47STejun Heo 			/* worker_thread() will call idle_worker_rebind() */
171725511a47STejun Heo 			wake_up_process(worker->task);
171825511a47STejun Heo 		}
171925511a47STejun Heo 	}
172025511a47STejun Heo 
172125511a47STejun Heo 	if (--idle_rebind.cnt) {
172225511a47STejun Heo 		spin_unlock_irq(&gcwq->lock);
172325511a47STejun Heo 		wait_for_completion(&idle_rebind.done);
172425511a47STejun Heo 		spin_lock_irq(&gcwq->lock);
172525511a47STejun Heo 		/* busy ones might have become idle while waiting, retry */
172625511a47STejun Heo 		goto retry;
172725511a47STejun Heo 	}
172825511a47STejun Heo 
172925511a47STejun Heo 	/*
173025511a47STejun Heo 	 * All idle workers are rebound and waiting for %WORKER_REBIND to
173125511a47STejun Heo 	 * be cleared inside idle_worker_rebind().  Clear and release.
173225511a47STejun Heo 	 * Clearing %WORKER_REBIND from this foreign context is safe
173325511a47STejun Heo 	 * because these workers are still guaranteed to be idle.
173425511a47STejun Heo 	 */
173525511a47STejun Heo 	for_each_worker_pool(pool, gcwq)
173625511a47STejun Heo 		list_for_each_entry(worker, &pool->idle_list, entry)
173725511a47STejun Heo 			worker->flags &= ~WORKER_REBIND;
173825511a47STejun Heo 
173925511a47STejun Heo 	wake_up_all(&gcwq->rebind_hold);
174025511a47STejun Heo 
174125511a47STejun Heo 	/* rebind busy workers */
174225511a47STejun Heo 	for_each_busy_worker(worker, i, pos, gcwq) {
174325511a47STejun Heo 		struct work_struct *rebind_work = &worker->rebind_work;
1744e2b6a6d5SJoonsoo Kim 		struct workqueue_struct *wq;
174525511a47STejun Heo 
174625511a47STejun Heo 		/* morph UNBOUND to REBIND */
174725511a47STejun Heo 		worker->flags &= ~WORKER_UNBOUND;
174825511a47STejun Heo 		worker->flags |= WORKER_REBIND;
174925511a47STejun Heo 
175025511a47STejun Heo 		if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
175125511a47STejun Heo 				     work_data_bits(rebind_work)))
175225511a47STejun Heo 			continue;
175325511a47STejun Heo 
175425511a47STejun Heo 		debug_work_activate(rebind_work);
1755e2b6a6d5SJoonsoo Kim 
1756e2b6a6d5SJoonsoo Kim 		/*
1757e2b6a6d5SJoonsoo Kim 		 * wq doesn't really matter but let's keep @worker->pool
1758e2b6a6d5SJoonsoo Kim 		 * and @cwq->pool consistent for sanity.
1759e2b6a6d5SJoonsoo Kim 		 */
1760e2b6a6d5SJoonsoo Kim 		if (worker_pool_pri(worker->pool))
1761e2b6a6d5SJoonsoo Kim 			wq = system_highpri_wq;
1762e2b6a6d5SJoonsoo Kim 		else
1763e2b6a6d5SJoonsoo Kim 			wq = system_wq;
1764e2b6a6d5SJoonsoo Kim 
1765e2b6a6d5SJoonsoo Kim 		insert_work(get_cwq(gcwq->cpu, wq), rebind_work,
176625511a47STejun Heo 			worker->scheduled.next,
176725511a47STejun Heo 			work_color_to_flags(WORK_NO_COLOR));
176825511a47STejun Heo 	}
176925511a47STejun Heo }
177025511a47STejun Heo 
1771c34056a3STejun Heo static struct worker *alloc_worker(void)
1772c34056a3STejun Heo {
1773c34056a3STejun Heo 	struct worker *worker;
1774c34056a3STejun Heo 
1775c34056a3STejun Heo 	worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1776c8e55f36STejun Heo 	if (worker) {
1777c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
1778affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
177925511a47STejun Heo 		INIT_WORK(&worker->rebind_work, busy_worker_rebind_fn);
1780e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
1781e22bee78STejun Heo 		worker->flags = WORKER_PREP;
1782c8e55f36STejun Heo 	}
1783c34056a3STejun Heo 	return worker;
1784c34056a3STejun Heo }
1785c34056a3STejun Heo 
1786c34056a3STejun Heo /**
1787c34056a3STejun Heo  * create_worker - create a new workqueue worker
178863d95a91STejun Heo  * @pool: pool the new worker will belong to
1789c34056a3STejun Heo  *
179063d95a91STejun Heo  * Create a new worker which is bound to @pool.  The returned worker
1791c34056a3STejun Heo  * can be started by calling start_worker() or destroyed using
1792c34056a3STejun Heo  * destroy_worker().
1793c34056a3STejun Heo  *
1794c34056a3STejun Heo  * CONTEXT:
1795c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
1796c34056a3STejun Heo  *
1797c34056a3STejun Heo  * RETURNS:
1798c34056a3STejun Heo  * Pointer to the newly created worker.
1799c34056a3STejun Heo  */
1800bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
1801c34056a3STejun Heo {
180263d95a91STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
18033270476aSTejun Heo 	const char *pri = worker_pool_pri(pool) ? "H" : "";
1804c34056a3STejun Heo 	struct worker *worker = NULL;
1805f3421797STejun Heo 	int id = -1;
1806c34056a3STejun Heo 
18078b03ae3cSTejun Heo 	spin_lock_irq(&gcwq->lock);
1808bd7bdd43STejun Heo 	while (ida_get_new(&pool->worker_ida, &id)) {
18098b03ae3cSTejun Heo 		spin_unlock_irq(&gcwq->lock);
1810bd7bdd43STejun Heo 		if (!ida_pre_get(&pool->worker_ida, GFP_KERNEL))
1811c34056a3STejun Heo 			goto fail;
18128b03ae3cSTejun Heo 		spin_lock_irq(&gcwq->lock);
1813c34056a3STejun Heo 	}
18148b03ae3cSTejun Heo 	spin_unlock_irq(&gcwq->lock);
1815c34056a3STejun Heo 
1816c34056a3STejun Heo 	worker = alloc_worker();
1817c34056a3STejun Heo 	if (!worker)
1818c34056a3STejun Heo 		goto fail;
1819c34056a3STejun Heo 
1820bd7bdd43STejun Heo 	worker->pool = pool;
1821c34056a3STejun Heo 	worker->id = id;
1822c34056a3STejun Heo 
1823bc2ae0f5STejun Heo 	if (gcwq->cpu != WORK_CPU_UNBOUND)
182494dcf29aSEric Dumazet 		worker->task = kthread_create_on_node(worker_thread,
18253270476aSTejun Heo 					worker, cpu_to_node(gcwq->cpu),
18263270476aSTejun Heo 					"kworker/%u:%d%s", gcwq->cpu, id, pri);
1827f3421797STejun Heo 	else
1828f3421797STejun Heo 		worker->task = kthread_create(worker_thread, worker,
18293270476aSTejun Heo 					      "kworker/u:%d%s", id, pri);
1830c34056a3STejun Heo 	if (IS_ERR(worker->task))
1831c34056a3STejun Heo 		goto fail;
1832c34056a3STejun Heo 
18333270476aSTejun Heo 	if (worker_pool_pri(pool))
18343270476aSTejun Heo 		set_user_nice(worker->task, HIGHPRI_NICE_LEVEL);
18353270476aSTejun Heo 
1836db7bccf4STejun Heo 	/*
1837bc2ae0f5STejun Heo 	 * Determine CPU binding of the new worker depending on
1838bc2ae0f5STejun Heo 	 * %GCWQ_DISASSOCIATED.  The caller is responsible for ensuring the
1839bc2ae0f5STejun Heo 	 * flag remains stable across this function.  See the comments
1840bc2ae0f5STejun Heo 	 * above the flag definition for details.
1841bc2ae0f5STejun Heo 	 *
1842bc2ae0f5STejun Heo 	 * As an unbound worker may later become a regular one if CPU comes
1843bc2ae0f5STejun Heo 	 * online, make sure every worker has %PF_THREAD_BOUND set.
1844db7bccf4STejun Heo 	 */
1845bc2ae0f5STejun Heo 	if (!(gcwq->flags & GCWQ_DISASSOCIATED)) {
18468b03ae3cSTejun Heo 		kthread_bind(worker->task, gcwq->cpu);
1847bc2ae0f5STejun Heo 	} else {
1848db7bccf4STejun Heo 		worker->task->flags |= PF_THREAD_BOUND;
1849f3421797STejun Heo 		worker->flags |= WORKER_UNBOUND;
1850f3421797STejun Heo 	}
1851c34056a3STejun Heo 
1852c34056a3STejun Heo 	return worker;
1853c34056a3STejun Heo fail:
1854c34056a3STejun Heo 	if (id >= 0) {
18558b03ae3cSTejun Heo 		spin_lock_irq(&gcwq->lock);
1856bd7bdd43STejun Heo 		ida_remove(&pool->worker_ida, id);
18578b03ae3cSTejun Heo 		spin_unlock_irq(&gcwq->lock);
1858c34056a3STejun Heo 	}
1859c34056a3STejun Heo 	kfree(worker);
1860c34056a3STejun Heo 	return NULL;
1861c34056a3STejun Heo }
1862c34056a3STejun Heo 
1863c34056a3STejun Heo /**
1864c34056a3STejun Heo  * start_worker - start a newly created worker
1865c34056a3STejun Heo  * @worker: worker to start
1866c34056a3STejun Heo  *
1867c8e55f36STejun Heo  * Make the gcwq aware of @worker and start it.
1868c34056a3STejun Heo  *
1869c34056a3STejun Heo  * CONTEXT:
18708b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock).
1871c34056a3STejun Heo  */
1872c34056a3STejun Heo static void start_worker(struct worker *worker)
1873c34056a3STejun Heo {
1874cb444766STejun Heo 	worker->flags |= WORKER_STARTED;
1875bd7bdd43STejun Heo 	worker->pool->nr_workers++;
1876c8e55f36STejun Heo 	worker_enter_idle(worker);
1877c34056a3STejun Heo 	wake_up_process(worker->task);
1878c34056a3STejun Heo }
1879c34056a3STejun Heo 
1880c34056a3STejun Heo /**
1881c34056a3STejun Heo  * destroy_worker - destroy a workqueue worker
1882c34056a3STejun Heo  * @worker: worker to be destroyed
1883c34056a3STejun Heo  *
1884c8e55f36STejun Heo  * Destroy @worker and adjust @gcwq stats accordingly.
1885c8e55f36STejun Heo  *
1886c8e55f36STejun Heo  * CONTEXT:
1887c8e55f36STejun Heo  * spin_lock_irq(gcwq->lock) which is released and regrabbed.
1888c34056a3STejun Heo  */
1889c34056a3STejun Heo static void destroy_worker(struct worker *worker)
1890c34056a3STejun Heo {
1891bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1892bd7bdd43STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
1893c34056a3STejun Heo 	int id = worker->id;
1894c34056a3STejun Heo 
1895c34056a3STejun Heo 	/* sanity check frenzy */
1896c34056a3STejun Heo 	BUG_ON(worker->current_work);
1897affee4b2STejun Heo 	BUG_ON(!list_empty(&worker->scheduled));
1898c34056a3STejun Heo 
1899c8e55f36STejun Heo 	if (worker->flags & WORKER_STARTED)
1900bd7bdd43STejun Heo 		pool->nr_workers--;
1901c8e55f36STejun Heo 	if (worker->flags & WORKER_IDLE)
1902bd7bdd43STejun Heo 		pool->nr_idle--;
1903c8e55f36STejun Heo 
1904c8e55f36STejun Heo 	list_del_init(&worker->entry);
1905cb444766STejun Heo 	worker->flags |= WORKER_DIE;
1906c8e55f36STejun Heo 
1907c8e55f36STejun Heo 	spin_unlock_irq(&gcwq->lock);
1908c8e55f36STejun Heo 
1909c34056a3STejun Heo 	kthread_stop(worker->task);
1910c34056a3STejun Heo 	kfree(worker);
1911c34056a3STejun Heo 
19128b03ae3cSTejun Heo 	spin_lock_irq(&gcwq->lock);
1913bd7bdd43STejun Heo 	ida_remove(&pool->worker_ida, id);
1914c34056a3STejun Heo }
1915c34056a3STejun Heo 
191663d95a91STejun Heo static void idle_worker_timeout(unsigned long __pool)
1917e22bee78STejun Heo {
191863d95a91STejun Heo 	struct worker_pool *pool = (void *)__pool;
191963d95a91STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
1920e22bee78STejun Heo 
1921e22bee78STejun Heo 	spin_lock_irq(&gcwq->lock);
1922e22bee78STejun Heo 
192363d95a91STejun Heo 	if (too_many_workers(pool)) {
1924e22bee78STejun Heo 		struct worker *worker;
1925e22bee78STejun Heo 		unsigned long expires;
1926e22bee78STejun Heo 
1927e22bee78STejun Heo 		/* idle_list is kept in LIFO order, check the last one */
192863d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
1929e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1930e22bee78STejun Heo 
1931e22bee78STejun Heo 		if (time_before(jiffies, expires))
193263d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
1933e22bee78STejun Heo 		else {
1934e22bee78STejun Heo 			/* it's been idle for too long, wake up manager */
193511ebea50STejun Heo 			pool->flags |= POOL_MANAGE_WORKERS;
193663d95a91STejun Heo 			wake_up_worker(pool);
1937e22bee78STejun Heo 		}
1938e22bee78STejun Heo 	}
1939e22bee78STejun Heo 
1940e22bee78STejun Heo 	spin_unlock_irq(&gcwq->lock);
1941e22bee78STejun Heo }
1942e22bee78STejun Heo 
1943e22bee78STejun Heo static bool send_mayday(struct work_struct *work)
1944e22bee78STejun Heo {
1945e22bee78STejun Heo 	struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1946e22bee78STejun Heo 	struct workqueue_struct *wq = cwq->wq;
1947f3421797STejun Heo 	unsigned int cpu;
1948e22bee78STejun Heo 
1949e22bee78STejun Heo 	if (!(wq->flags & WQ_RESCUER))
1950e22bee78STejun Heo 		return false;
1951e22bee78STejun Heo 
1952e22bee78STejun Heo 	/* mayday mayday mayday */
1953bd7bdd43STejun Heo 	cpu = cwq->pool->gcwq->cpu;
1954f3421797STejun Heo 	/* WORK_CPU_UNBOUND can't be set in cpumask, use cpu 0 instead */
1955f3421797STejun Heo 	if (cpu == WORK_CPU_UNBOUND)
1956f3421797STejun Heo 		cpu = 0;
1957f2e005aaSTejun Heo 	if (!mayday_test_and_set_cpu(cpu, wq->mayday_mask))
1958e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
1959e22bee78STejun Heo 	return true;
1960e22bee78STejun Heo }
1961e22bee78STejun Heo 
196263d95a91STejun Heo static void gcwq_mayday_timeout(unsigned long __pool)
1963e22bee78STejun Heo {
196463d95a91STejun Heo 	struct worker_pool *pool = (void *)__pool;
196563d95a91STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
1966e22bee78STejun Heo 	struct work_struct *work;
1967e22bee78STejun Heo 
1968e22bee78STejun Heo 	spin_lock_irq(&gcwq->lock);
1969e22bee78STejun Heo 
197063d95a91STejun Heo 	if (need_to_create_worker(pool)) {
1971e22bee78STejun Heo 		/*
1972e22bee78STejun Heo 		 * We've been trying to create a new worker but
1973e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
1974e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
1975e22bee78STejun Heo 		 * rescuers.
1976e22bee78STejun Heo 		 */
197763d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
1978e22bee78STejun Heo 			send_mayday(work);
1979e22bee78STejun Heo 	}
1980e22bee78STejun Heo 
1981e22bee78STejun Heo 	spin_unlock_irq(&gcwq->lock);
1982e22bee78STejun Heo 
198363d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1984e22bee78STejun Heo }
1985e22bee78STejun Heo 
1986e22bee78STejun Heo /**
1987e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
198863d95a91STejun Heo  * @pool: pool to create a new worker for
1989e22bee78STejun Heo  *
199063d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
1991e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
1992e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
199363d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
1994e22bee78STejun Heo  * possible allocation deadlock.
1995e22bee78STejun Heo  *
1996e22bee78STejun Heo  * On return, need_to_create_worker() is guaranteed to be false and
1997e22bee78STejun Heo  * may_start_working() true.
1998e22bee78STejun Heo  *
1999e22bee78STejun Heo  * LOCKING:
2000e22bee78STejun Heo  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2001e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
2002e22bee78STejun Heo  * manager.
2003e22bee78STejun Heo  *
2004e22bee78STejun Heo  * RETURNS:
2005e22bee78STejun Heo  * false if no action was taken and gcwq->lock stayed locked, true
2006e22bee78STejun Heo  * otherwise.
2007e22bee78STejun Heo  */
200863d95a91STejun Heo static bool maybe_create_worker(struct worker_pool *pool)
200906bd6ebfSNamhyung Kim __releases(&gcwq->lock)
201006bd6ebfSNamhyung Kim __acquires(&gcwq->lock)
2011e22bee78STejun Heo {
201263d95a91STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
201363d95a91STejun Heo 
201463d95a91STejun Heo 	if (!need_to_create_worker(pool))
2015e22bee78STejun Heo 		return false;
2016e22bee78STejun Heo restart:
20179f9c2364STejun Heo 	spin_unlock_irq(&gcwq->lock);
20189f9c2364STejun Heo 
2019e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
202063d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
2021e22bee78STejun Heo 
2022e22bee78STejun Heo 	while (true) {
2023e22bee78STejun Heo 		struct worker *worker;
2024e22bee78STejun Heo 
2025bc2ae0f5STejun Heo 		worker = create_worker(pool);
2026e22bee78STejun Heo 		if (worker) {
202763d95a91STejun Heo 			del_timer_sync(&pool->mayday_timer);
2028e22bee78STejun Heo 			spin_lock_irq(&gcwq->lock);
2029e22bee78STejun Heo 			start_worker(worker);
203063d95a91STejun Heo 			BUG_ON(need_to_create_worker(pool));
2031e22bee78STejun Heo 			return true;
2032e22bee78STejun Heo 		}
2033e22bee78STejun Heo 
203463d95a91STejun Heo 		if (!need_to_create_worker(pool))
2035e22bee78STejun Heo 			break;
2036e22bee78STejun Heo 
2037e22bee78STejun Heo 		__set_current_state(TASK_INTERRUPTIBLE);
2038e22bee78STejun Heo 		schedule_timeout(CREATE_COOLDOWN);
20399f9c2364STejun Heo 
204063d95a91STejun Heo 		if (!need_to_create_worker(pool))
2041e22bee78STejun Heo 			break;
2042e22bee78STejun Heo 	}
2043e22bee78STejun Heo 
204463d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
2045e22bee78STejun Heo 	spin_lock_irq(&gcwq->lock);
204663d95a91STejun Heo 	if (need_to_create_worker(pool))
2047e22bee78STejun Heo 		goto restart;
2048e22bee78STejun Heo 	return true;
2049e22bee78STejun Heo }
2050e22bee78STejun Heo 
2051e22bee78STejun Heo /**
2052e22bee78STejun Heo  * maybe_destroy_worker - destroy workers which have been idle for a while
205363d95a91STejun Heo  * @pool: pool to destroy workers for
2054e22bee78STejun Heo  *
205563d95a91STejun Heo  * Destroy @pool workers which have been idle for longer than
2056e22bee78STejun Heo  * IDLE_WORKER_TIMEOUT.
2057e22bee78STejun Heo  *
2058e22bee78STejun Heo  * LOCKING:
2059e22bee78STejun Heo  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2060e22bee78STejun Heo  * multiple times.  Called only from manager.
2061e22bee78STejun Heo  *
2062e22bee78STejun Heo  * RETURNS:
2063e22bee78STejun Heo  * false if no action was taken and gcwq->lock stayed locked, true
2064e22bee78STejun Heo  * otherwise.
2065e22bee78STejun Heo  */
206663d95a91STejun Heo static bool maybe_destroy_workers(struct worker_pool *pool)
2067e22bee78STejun Heo {
2068e22bee78STejun Heo 	bool ret = false;
2069e22bee78STejun Heo 
207063d95a91STejun Heo 	while (too_many_workers(pool)) {
2071e22bee78STejun Heo 		struct worker *worker;
2072e22bee78STejun Heo 		unsigned long expires;
2073e22bee78STejun Heo 
207463d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
2075e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2076e22bee78STejun Heo 
2077e22bee78STejun Heo 		if (time_before(jiffies, expires)) {
207863d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
2079e22bee78STejun Heo 			break;
2080e22bee78STejun Heo 		}
2081e22bee78STejun Heo 
2082e22bee78STejun Heo 		destroy_worker(worker);
2083e22bee78STejun Heo 		ret = true;
2084e22bee78STejun Heo 	}
2085e22bee78STejun Heo 
2086e22bee78STejun Heo 	return ret;
2087e22bee78STejun Heo }
2088e22bee78STejun Heo 
2089e22bee78STejun Heo /**
2090e22bee78STejun Heo  * manage_workers - manage worker pool
2091e22bee78STejun Heo  * @worker: self
2092e22bee78STejun Heo  *
2093e22bee78STejun Heo  * Assume the manager role and manage gcwq worker pool @worker belongs
2094e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
2095e22bee78STejun Heo  * gcwq.  The exclusion is handled automatically by this function.
2096e22bee78STejun Heo  *
2097e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
2098e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
2099e22bee78STejun Heo  * and may_start_working() is true.
2100e22bee78STejun Heo  *
2101e22bee78STejun Heo  * CONTEXT:
2102e22bee78STejun Heo  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2103e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
2104e22bee78STejun Heo  *
2105e22bee78STejun Heo  * RETURNS:
2106e22bee78STejun Heo  * false if no action was taken and gcwq->lock stayed locked, true if
2107e22bee78STejun Heo  * some action was taken.
2108e22bee78STejun Heo  */
2109e22bee78STejun Heo static bool manage_workers(struct worker *worker)
2110e22bee78STejun Heo {
211163d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
2112e22bee78STejun Heo 	bool ret = false;
2113e22bee78STejun Heo 
211460373152STejun Heo 	if (!mutex_trylock(&pool->manager_mutex))
2115e22bee78STejun Heo 		return ret;
2116e22bee78STejun Heo 
211711ebea50STejun Heo 	pool->flags &= ~POOL_MANAGE_WORKERS;
2118e22bee78STejun Heo 
2119e22bee78STejun Heo 	/*
2120e22bee78STejun Heo 	 * Destroy and then create so that may_start_working() is true
2121e22bee78STejun Heo 	 * on return.
2122e22bee78STejun Heo 	 */
212363d95a91STejun Heo 	ret |= maybe_destroy_workers(pool);
212463d95a91STejun Heo 	ret |= maybe_create_worker(pool);
2125e22bee78STejun Heo 
212660373152STejun Heo 	mutex_unlock(&pool->manager_mutex);
2127e22bee78STejun Heo 	return ret;
2128e22bee78STejun Heo }
2129e22bee78STejun Heo 
2130a62428c0STejun Heo /**
2131a62428c0STejun Heo  * process_one_work - process single work
2132c34056a3STejun Heo  * @worker: self
2133a62428c0STejun Heo  * @work: work to process
2134a62428c0STejun Heo  *
2135a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
2136a62428c0STejun Heo  * process a single work including synchronization against and
2137a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
2138a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
2139a62428c0STejun Heo  * call this function to process a work.
2140a62428c0STejun Heo  *
2141a62428c0STejun Heo  * CONTEXT:
21428b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock) which is released and regrabbed.
2143a62428c0STejun Heo  */
2144c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
214506bd6ebfSNamhyung Kim __releases(&gcwq->lock)
214606bd6ebfSNamhyung Kim __acquires(&gcwq->lock)
21471da177e4SLinus Torvalds {
21487e11629dSTejun Heo 	struct cpu_workqueue_struct *cwq = get_work_cwq(work);
2149bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2150bd7bdd43STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
2151c8e55f36STejun Heo 	struct hlist_head *bwh = busy_worker_head(gcwq, work);
2152fb0e7bebSTejun Heo 	bool cpu_intensive = cwq->wq->flags & WQ_CPU_INTENSIVE;
21536bb49e59SDavid Howells 	work_func_t f = work->func;
215473f53c4aSTejun Heo 	int work_color;
21557e11629dSTejun Heo 	struct worker *collision;
21564e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
21574e6045f1SJohannes Berg 	/*
2158a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
2159a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
2160a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
2161a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
2162a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
21634e6045f1SJohannes Berg 	 */
21644d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
21654d82a1deSPeter Zijlstra 
21664d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
21674e6045f1SJohannes Berg #endif
21686fec10a1STejun Heo 	/*
21696fec10a1STejun Heo 	 * Ensure we're on the correct CPU.  DISASSOCIATED test is
21706fec10a1STejun Heo 	 * necessary to avoid spurious warnings from rescuers servicing the
21716fec10a1STejun Heo 	 * unbound or a disassociated gcwq.
21726fec10a1STejun Heo 	 */
217325511a47STejun Heo 	WARN_ON_ONCE(!(worker->flags & (WORKER_UNBOUND | WORKER_REBIND)) &&
21746fec10a1STejun Heo 		     !(gcwq->flags & GCWQ_DISASSOCIATED) &&
217525511a47STejun Heo 		     raw_smp_processor_id() != gcwq->cpu);
217625511a47STejun Heo 
21777e11629dSTejun Heo 	/*
21787e11629dSTejun Heo 	 * A single work shouldn't be executed concurrently by
21797e11629dSTejun Heo 	 * multiple workers on a single cpu.  Check whether anyone is
21807e11629dSTejun Heo 	 * already processing the work.  If so, defer the work to the
21817e11629dSTejun Heo 	 * currently executing one.
21827e11629dSTejun Heo 	 */
21837e11629dSTejun Heo 	collision = __find_worker_executing_work(gcwq, bwh, work);
21847e11629dSTejun Heo 	if (unlikely(collision)) {
21857e11629dSTejun Heo 		move_linked_works(work, &collision->scheduled, NULL);
21867e11629dSTejun Heo 		return;
21877e11629dSTejun Heo 	}
21881da177e4SLinus Torvalds 
21898930cabaSTejun Heo 	/* claim and dequeue */
21901da177e4SLinus Torvalds 	debug_work_deactivate(work);
2191c8e55f36STejun Heo 	hlist_add_head(&worker->hentry, bwh);
2192c34056a3STejun Heo 	worker->current_work = work;
21938cca0eeaSTejun Heo 	worker->current_cwq = cwq;
219473f53c4aSTejun Heo 	work_color = get_work_color(work);
21957a22ad75STejun Heo 
2196a62428c0STejun Heo 	list_del_init(&work->entry);
2197a62428c0STejun Heo 
2198649027d7STejun Heo 	/*
2199fb0e7bebSTejun Heo 	 * CPU intensive works don't participate in concurrency
2200fb0e7bebSTejun Heo 	 * management.  They're the scheduler's responsibility.
2201fb0e7bebSTejun Heo 	 */
2202fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2203fb0e7bebSTejun Heo 		worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
2204fb0e7bebSTejun Heo 
2205974271c4STejun Heo 	/*
2206974271c4STejun Heo 	 * Unbound gcwq isn't concurrency managed and work items should be
2207974271c4STejun Heo 	 * executed ASAP.  Wake up another worker if necessary.
2208974271c4STejun Heo 	 */
220963d95a91STejun Heo 	if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
221063d95a91STejun Heo 		wake_up_worker(pool);
2211974271c4STejun Heo 
22128930cabaSTejun Heo 	/*
221323657bb1STejun Heo 	 * Record the last CPU and clear PENDING which should be the last
221423657bb1STejun Heo 	 * update to @work.  Also, do this inside @gcwq->lock so that
221523657bb1STejun Heo 	 * PENDING and queued state changes happen together while IRQ is
221623657bb1STejun Heo 	 * disabled.
22178930cabaSTejun Heo 	 */
22188930cabaSTejun Heo 	set_work_cpu_and_clear_pending(work, gcwq->cpu);
22191da177e4SLinus Torvalds 
22208930cabaSTejun Heo 	spin_unlock_irq(&gcwq->lock);
2221959d1af8STejun Heo 
2222e159489bSTejun Heo 	lock_map_acquire_read(&cwq->wq->lockdep_map);
22233295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
2224e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
222565f27f38SDavid Howells 	f(work);
2226e36c886aSArjan van de Ven 	/*
2227e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
2228e36c886aSArjan van de Ven 	 * point will only record its address.
2229e36c886aSArjan van de Ven 	 */
2230e36c886aSArjan van de Ven 	trace_workqueue_execute_end(work);
22313295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
22323295f0efSIngo Molnar 	lock_map_release(&cwq->wq->lockdep_map);
22331da177e4SLinus Torvalds 
2234d5abe669SPeter Zijlstra 	if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2235d5abe669SPeter Zijlstra 		printk(KERN_ERR "BUG: workqueue leaked lock or atomic: "
2236d5abe669SPeter Zijlstra 		       "%s/0x%08x/%d\n",
2237a62428c0STejun Heo 		       current->comm, preempt_count(), task_pid_nr(current));
2238d5abe669SPeter Zijlstra 		printk(KERN_ERR "    last function: ");
2239d5abe669SPeter Zijlstra 		print_symbol("%s\n", (unsigned long)f);
2240d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
2241d5abe669SPeter Zijlstra 		dump_stack();
2242d5abe669SPeter Zijlstra 	}
2243d5abe669SPeter Zijlstra 
22448b03ae3cSTejun Heo 	spin_lock_irq(&gcwq->lock);
2245a62428c0STejun Heo 
2246fb0e7bebSTejun Heo 	/* clear cpu intensive status */
2247fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2248fb0e7bebSTejun Heo 		worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2249fb0e7bebSTejun Heo 
2250a62428c0STejun Heo 	/* we're done with it, release */
2251c8e55f36STejun Heo 	hlist_del_init(&worker->hentry);
2252c34056a3STejun Heo 	worker->current_work = NULL;
22538cca0eeaSTejun Heo 	worker->current_cwq = NULL;
22548a2e8e5dSTejun Heo 	cwq_dec_nr_in_flight(cwq, work_color, false);
22551da177e4SLinus Torvalds }
22561da177e4SLinus Torvalds 
2257affee4b2STejun Heo /**
2258affee4b2STejun Heo  * process_scheduled_works - process scheduled works
2259affee4b2STejun Heo  * @worker: self
2260affee4b2STejun Heo  *
2261affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
2262affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
2263affee4b2STejun Heo  * fetches a work from the top and executes it.
2264affee4b2STejun Heo  *
2265affee4b2STejun Heo  * CONTEXT:
22668b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2267affee4b2STejun Heo  * multiple times.
2268affee4b2STejun Heo  */
2269affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
22701da177e4SLinus Torvalds {
2271affee4b2STejun Heo 	while (!list_empty(&worker->scheduled)) {
2272affee4b2STejun Heo 		struct work_struct *work = list_first_entry(&worker->scheduled,
2273a62428c0STejun Heo 						struct work_struct, entry);
2274c34056a3STejun Heo 		process_one_work(worker, work);
2275a62428c0STejun Heo 	}
22761da177e4SLinus Torvalds }
22771da177e4SLinus Torvalds 
22784690c4abSTejun Heo /**
22794690c4abSTejun Heo  * worker_thread - the worker thread function
2280c34056a3STejun Heo  * @__worker: self
22814690c4abSTejun Heo  *
2282e22bee78STejun Heo  * The gcwq worker thread function.  There's a single dynamic pool of
2283e22bee78STejun Heo  * these per each cpu.  These workers process all works regardless of
2284e22bee78STejun Heo  * their specific target workqueue.  The only exception is works which
2285e22bee78STejun Heo  * belong to workqueues with a rescuer which will be explained in
2286e22bee78STejun Heo  * rescuer_thread().
22874690c4abSTejun Heo  */
2288c34056a3STejun Heo static int worker_thread(void *__worker)
22891da177e4SLinus Torvalds {
2290c34056a3STejun Heo 	struct worker *worker = __worker;
2291bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2292bd7bdd43STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
22931da177e4SLinus Torvalds 
2294e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
2295e22bee78STejun Heo 	worker->task->flags |= PF_WQ_WORKER;
2296c8e55f36STejun Heo woke_up:
22978b03ae3cSTejun Heo 	spin_lock_irq(&gcwq->lock);
2298affee4b2STejun Heo 
229925511a47STejun Heo 	/*
230025511a47STejun Heo 	 * DIE can be set only while idle and REBIND set while busy has
230125511a47STejun Heo 	 * @worker->rebind_work scheduled.  Checking here is enough.
230225511a47STejun Heo 	 */
230325511a47STejun Heo 	if (unlikely(worker->flags & (WORKER_REBIND | WORKER_DIE))) {
2304c8e55f36STejun Heo 		spin_unlock_irq(&gcwq->lock);
230525511a47STejun Heo 
230625511a47STejun Heo 		if (worker->flags & WORKER_DIE) {
2307e22bee78STejun Heo 			worker->task->flags &= ~PF_WQ_WORKER;
2308c8e55f36STejun Heo 			return 0;
2309c8e55f36STejun Heo 		}
2310c8e55f36STejun Heo 
231125511a47STejun Heo 		idle_worker_rebind(worker);
231225511a47STejun Heo 		goto woke_up;
231325511a47STejun Heo 	}
231425511a47STejun Heo 
2315c8e55f36STejun Heo 	worker_leave_idle(worker);
2316db7bccf4STejun Heo recheck:
2317e22bee78STejun Heo 	/* no more worker necessary? */
231863d95a91STejun Heo 	if (!need_more_worker(pool))
2319e22bee78STejun Heo 		goto sleep;
2320e22bee78STejun Heo 
2321e22bee78STejun Heo 	/* do we need to manage? */
232263d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2323e22bee78STejun Heo 		goto recheck;
2324e22bee78STejun Heo 
2325c8e55f36STejun Heo 	/*
2326c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
2327c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
2328c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
2329c8e55f36STejun Heo 	 */
2330c8e55f36STejun Heo 	BUG_ON(!list_empty(&worker->scheduled));
2331c8e55f36STejun Heo 
2332e22bee78STejun Heo 	/*
2333e22bee78STejun Heo 	 * When control reaches this point, we're guaranteed to have
2334e22bee78STejun Heo 	 * at least one idle worker or that someone else has already
2335e22bee78STejun Heo 	 * assumed the manager role.
2336e22bee78STejun Heo 	 */
2337e22bee78STejun Heo 	worker_clr_flags(worker, WORKER_PREP);
2338e22bee78STejun Heo 
2339e22bee78STejun Heo 	do {
2340affee4b2STejun Heo 		struct work_struct *work =
2341bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
2342affee4b2STejun Heo 					 struct work_struct, entry);
2343affee4b2STejun Heo 
2344c8e55f36STejun Heo 		if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2345affee4b2STejun Heo 			/* optimization path, not strictly necessary */
2346affee4b2STejun Heo 			process_one_work(worker, work);
2347affee4b2STejun Heo 			if (unlikely(!list_empty(&worker->scheduled)))
2348affee4b2STejun Heo 				process_scheduled_works(worker);
2349affee4b2STejun Heo 		} else {
2350c8e55f36STejun Heo 			move_linked_works(work, &worker->scheduled, NULL);
2351affee4b2STejun Heo 			process_scheduled_works(worker);
2352affee4b2STejun Heo 		}
235363d95a91STejun Heo 	} while (keep_working(pool));
2354affee4b2STejun Heo 
2355e22bee78STejun Heo 	worker_set_flags(worker, WORKER_PREP, false);
2356d313dd85STejun Heo sleep:
235763d95a91STejun Heo 	if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
2358e22bee78STejun Heo 		goto recheck;
2359d313dd85STejun Heo 
2360c8e55f36STejun Heo 	/*
2361e22bee78STejun Heo 	 * gcwq->lock is held and there's no work to process and no
2362e22bee78STejun Heo 	 * need to manage, sleep.  Workers are woken up only while
2363e22bee78STejun Heo 	 * holding gcwq->lock or from local cpu, so setting the
2364e22bee78STejun Heo 	 * current state before releasing gcwq->lock is enough to
2365e22bee78STejun Heo 	 * prevent losing any event.
2366c8e55f36STejun Heo 	 */
2367c8e55f36STejun Heo 	worker_enter_idle(worker);
2368c8e55f36STejun Heo 	__set_current_state(TASK_INTERRUPTIBLE);
23698b03ae3cSTejun Heo 	spin_unlock_irq(&gcwq->lock);
23701da177e4SLinus Torvalds 	schedule();
2371c8e55f36STejun Heo 	goto woke_up;
23721da177e4SLinus Torvalds }
23731da177e4SLinus Torvalds 
2374e22bee78STejun Heo /**
2375e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
2376e22bee78STejun Heo  * @__wq: the associated workqueue
2377e22bee78STejun Heo  *
2378e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
2379e22bee78STejun Heo  * workqueue which has WQ_RESCUER set.
2380e22bee78STejun Heo  *
2381e22bee78STejun Heo  * Regular work processing on a gcwq may block trying to create a new
2382e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
2383e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
2384e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2385e22bee78STejun Heo  * the problem rescuer solves.
2386e22bee78STejun Heo  *
2387e22bee78STejun Heo  * When such condition is possible, the gcwq summons rescuers of all
2388e22bee78STejun Heo  * workqueues which have works queued on the gcwq and let them process
2389e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
2390e22bee78STejun Heo  *
2391e22bee78STejun Heo  * This should happen rarely.
2392e22bee78STejun Heo  */
2393e22bee78STejun Heo static int rescuer_thread(void *__wq)
2394e22bee78STejun Heo {
2395e22bee78STejun Heo 	struct workqueue_struct *wq = __wq;
2396e22bee78STejun Heo 	struct worker *rescuer = wq->rescuer;
2397e22bee78STejun Heo 	struct list_head *scheduled = &rescuer->scheduled;
2398f3421797STejun Heo 	bool is_unbound = wq->flags & WQ_UNBOUND;
2399e22bee78STejun Heo 	unsigned int cpu;
2400e22bee78STejun Heo 
2401e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
2402e22bee78STejun Heo repeat:
2403e22bee78STejun Heo 	set_current_state(TASK_INTERRUPTIBLE);
24041da177e4SLinus Torvalds 
24051da177e4SLinus Torvalds 	if (kthread_should_stop())
2406e22bee78STejun Heo 		return 0;
24071da177e4SLinus Torvalds 
2408f3421797STejun Heo 	/*
2409f3421797STejun Heo 	 * See whether any cpu is asking for help.  Unbounded
2410f3421797STejun Heo 	 * workqueues use cpu 0 in mayday_mask for CPU_UNBOUND.
2411f3421797STejun Heo 	 */
2412f2e005aaSTejun Heo 	for_each_mayday_cpu(cpu, wq->mayday_mask) {
2413f3421797STejun Heo 		unsigned int tcpu = is_unbound ? WORK_CPU_UNBOUND : cpu;
2414f3421797STejun Heo 		struct cpu_workqueue_struct *cwq = get_cwq(tcpu, wq);
2415bd7bdd43STejun Heo 		struct worker_pool *pool = cwq->pool;
2416bd7bdd43STejun Heo 		struct global_cwq *gcwq = pool->gcwq;
2417e22bee78STejun Heo 		struct work_struct *work, *n;
2418e22bee78STejun Heo 
2419e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
2420f2e005aaSTejun Heo 		mayday_clear_cpu(cpu, wq->mayday_mask);
2421e22bee78STejun Heo 
2422e22bee78STejun Heo 		/* migrate to the target cpu if possible */
2423bd7bdd43STejun Heo 		rescuer->pool = pool;
2424e22bee78STejun Heo 		worker_maybe_bind_and_lock(rescuer);
2425e22bee78STejun Heo 
2426e22bee78STejun Heo 		/*
2427e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
2428e22bee78STejun Heo 		 * process'em.
2429e22bee78STejun Heo 		 */
2430e22bee78STejun Heo 		BUG_ON(!list_empty(&rescuer->scheduled));
2431bd7bdd43STejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry)
2432e22bee78STejun Heo 			if (get_work_cwq(work) == cwq)
2433e22bee78STejun Heo 				move_linked_works(work, scheduled, &n);
2434e22bee78STejun Heo 
2435e22bee78STejun Heo 		process_scheduled_works(rescuer);
24367576958aSTejun Heo 
24377576958aSTejun Heo 		/*
24387576958aSTejun Heo 		 * Leave this gcwq.  If keep_working() is %true, notify a
24397576958aSTejun Heo 		 * regular worker; otherwise, we end up with 0 concurrency
24407576958aSTejun Heo 		 * and stalling the execution.
24417576958aSTejun Heo 		 */
244263d95a91STejun Heo 		if (keep_working(pool))
244363d95a91STejun Heo 			wake_up_worker(pool);
24447576958aSTejun Heo 
2445e22bee78STejun Heo 		spin_unlock_irq(&gcwq->lock);
24461da177e4SLinus Torvalds 	}
24471da177e4SLinus Torvalds 
2448e22bee78STejun Heo 	schedule();
2449e22bee78STejun Heo 	goto repeat;
24501da177e4SLinus Torvalds }
24511da177e4SLinus Torvalds 
2452fc2e4d70SOleg Nesterov struct wq_barrier {
2453fc2e4d70SOleg Nesterov 	struct work_struct	work;
2454fc2e4d70SOleg Nesterov 	struct completion	done;
2455fc2e4d70SOleg Nesterov };
2456fc2e4d70SOleg Nesterov 
2457fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
2458fc2e4d70SOleg Nesterov {
2459fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2460fc2e4d70SOleg Nesterov 	complete(&barr->done);
2461fc2e4d70SOleg Nesterov }
2462fc2e4d70SOleg Nesterov 
24634690c4abSTejun Heo /**
24644690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
24654690c4abSTejun Heo  * @cwq: cwq to insert barrier into
24664690c4abSTejun Heo  * @barr: wq_barrier to insert
2467affee4b2STejun Heo  * @target: target work to attach @barr to
2468affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
24694690c4abSTejun Heo  *
2470affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
2471affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
2472affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
2473affee4b2STejun Heo  * cpu.
2474affee4b2STejun Heo  *
2475affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
2476affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
2477affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
2478affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
2479affee4b2STejun Heo  * after a work with LINKED flag set.
2480affee4b2STejun Heo  *
2481affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
2482affee4b2STejun Heo  * underneath us, so we can't reliably determine cwq from @target.
24834690c4abSTejun Heo  *
24844690c4abSTejun Heo  * CONTEXT:
24858b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock).
24864690c4abSTejun Heo  */
248783c22520SOleg Nesterov static void insert_wq_barrier(struct cpu_workqueue_struct *cwq,
2488affee4b2STejun Heo 			      struct wq_barrier *barr,
2489affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
2490fc2e4d70SOleg Nesterov {
2491affee4b2STejun Heo 	struct list_head *head;
2492affee4b2STejun Heo 	unsigned int linked = 0;
2493affee4b2STejun Heo 
2494dc186ad7SThomas Gleixner 	/*
24958b03ae3cSTejun Heo 	 * debugobject calls are safe here even with gcwq->lock locked
2496dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
2497dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
2498dc186ad7SThomas Gleixner 	 * might deadlock.
2499dc186ad7SThomas Gleixner 	 */
2500ca1cab37SAndrew Morton 	INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
250122df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2502fc2e4d70SOleg Nesterov 	init_completion(&barr->done);
250383c22520SOleg Nesterov 
2504affee4b2STejun Heo 	/*
2505affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
2506affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
2507affee4b2STejun Heo 	 */
2508affee4b2STejun Heo 	if (worker)
2509affee4b2STejun Heo 		head = worker->scheduled.next;
2510affee4b2STejun Heo 	else {
2511affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
2512affee4b2STejun Heo 
2513affee4b2STejun Heo 		head = target->entry.next;
2514affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
2515affee4b2STejun Heo 		linked = *bits & WORK_STRUCT_LINKED;
2516affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
2517affee4b2STejun Heo 	}
2518affee4b2STejun Heo 
2519dc186ad7SThomas Gleixner 	debug_work_activate(&barr->work);
2520affee4b2STejun Heo 	insert_work(cwq, &barr->work, head,
2521affee4b2STejun Heo 		    work_color_to_flags(WORK_NO_COLOR) | linked);
2522fc2e4d70SOleg Nesterov }
2523fc2e4d70SOleg Nesterov 
252473f53c4aSTejun Heo /**
252573f53c4aSTejun Heo  * flush_workqueue_prep_cwqs - prepare cwqs for workqueue flushing
252673f53c4aSTejun Heo  * @wq: workqueue being flushed
252773f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
252873f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
252973f53c4aSTejun Heo  *
253073f53c4aSTejun Heo  * Prepare cwqs for workqueue flushing.
253173f53c4aSTejun Heo  *
253273f53c4aSTejun Heo  * If @flush_color is non-negative, flush_color on all cwqs should be
253373f53c4aSTejun Heo  * -1.  If no cwq has in-flight commands at the specified color, all
253473f53c4aSTejun Heo  * cwq->flush_color's stay at -1 and %false is returned.  If any cwq
253573f53c4aSTejun Heo  * has in flight commands, its cwq->flush_color is set to
253673f53c4aSTejun Heo  * @flush_color, @wq->nr_cwqs_to_flush is updated accordingly, cwq
253773f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
253873f53c4aSTejun Heo  *
253973f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
254073f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
254173f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
254273f53c4aSTejun Heo  * is returned.
254373f53c4aSTejun Heo  *
254473f53c4aSTejun Heo  * If @work_color is non-negative, all cwqs should have the same
254573f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
254673f53c4aSTejun Heo  * advanced to @work_color.
254773f53c4aSTejun Heo  *
254873f53c4aSTejun Heo  * CONTEXT:
254973f53c4aSTejun Heo  * mutex_lock(wq->flush_mutex).
255073f53c4aSTejun Heo  *
255173f53c4aSTejun Heo  * RETURNS:
255273f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
255373f53c4aSTejun Heo  * otherwise.
255473f53c4aSTejun Heo  */
255573f53c4aSTejun Heo static bool flush_workqueue_prep_cwqs(struct workqueue_struct *wq,
255673f53c4aSTejun Heo 				      int flush_color, int work_color)
25571da177e4SLinus Torvalds {
255873f53c4aSTejun Heo 	bool wait = false;
255973f53c4aSTejun Heo 	unsigned int cpu;
25601da177e4SLinus Torvalds 
256173f53c4aSTejun Heo 	if (flush_color >= 0) {
256273f53c4aSTejun Heo 		BUG_ON(atomic_read(&wq->nr_cwqs_to_flush));
256373f53c4aSTejun Heo 		atomic_set(&wq->nr_cwqs_to_flush, 1);
2564dc186ad7SThomas Gleixner 	}
256514441960SOleg Nesterov 
2566f3421797STejun Heo 	for_each_cwq_cpu(cpu, wq) {
256773f53c4aSTejun Heo 		struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2568bd7bdd43STejun Heo 		struct global_cwq *gcwq = cwq->pool->gcwq;
25691da177e4SLinus Torvalds 
25708b03ae3cSTejun Heo 		spin_lock_irq(&gcwq->lock);
257173f53c4aSTejun Heo 
257273f53c4aSTejun Heo 		if (flush_color >= 0) {
257373f53c4aSTejun Heo 			BUG_ON(cwq->flush_color != -1);
257473f53c4aSTejun Heo 
257573f53c4aSTejun Heo 			if (cwq->nr_in_flight[flush_color]) {
257673f53c4aSTejun Heo 				cwq->flush_color = flush_color;
257773f53c4aSTejun Heo 				atomic_inc(&wq->nr_cwqs_to_flush);
257873f53c4aSTejun Heo 				wait = true;
25791da177e4SLinus Torvalds 			}
258073f53c4aSTejun Heo 		}
258173f53c4aSTejun Heo 
258273f53c4aSTejun Heo 		if (work_color >= 0) {
258373f53c4aSTejun Heo 			BUG_ON(work_color != work_next_color(cwq->work_color));
258473f53c4aSTejun Heo 			cwq->work_color = work_color;
258573f53c4aSTejun Heo 		}
258673f53c4aSTejun Heo 
25878b03ae3cSTejun Heo 		spin_unlock_irq(&gcwq->lock);
25881da177e4SLinus Torvalds 	}
25891da177e4SLinus Torvalds 
259073f53c4aSTejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_cwqs_to_flush))
259173f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
259273f53c4aSTejun Heo 
259373f53c4aSTejun Heo 	return wait;
259483c22520SOleg Nesterov }
25951da177e4SLinus Torvalds 
25960fcb78c2SRolf Eike Beer /**
25971da177e4SLinus Torvalds  * flush_workqueue - ensure that any scheduled work has run to completion.
25980fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
25991da177e4SLinus Torvalds  *
26001da177e4SLinus Torvalds  * Forces execution of the workqueue and blocks until its completion.
26011da177e4SLinus Torvalds  * This is typically used in driver shutdown handlers.
26021da177e4SLinus Torvalds  *
2603fc2e4d70SOleg Nesterov  * We sleep until all works which were queued on entry have been handled,
2604fc2e4d70SOleg Nesterov  * but we are not livelocked by new incoming ones.
26051da177e4SLinus Torvalds  */
26067ad5b3a5SHarvey Harrison void flush_workqueue(struct workqueue_struct *wq)
26071da177e4SLinus Torvalds {
260873f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
260973f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
261073f53c4aSTejun Heo 		.flush_color = -1,
261173f53c4aSTejun Heo 		.done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
261273f53c4aSTejun Heo 	};
261373f53c4aSTejun Heo 	int next_color;
2614b1f4ec17SOleg Nesterov 
26153295f0efSIngo Molnar 	lock_map_acquire(&wq->lockdep_map);
26163295f0efSIngo Molnar 	lock_map_release(&wq->lockdep_map);
261773f53c4aSTejun Heo 
261873f53c4aSTejun Heo 	mutex_lock(&wq->flush_mutex);
261973f53c4aSTejun Heo 
262073f53c4aSTejun Heo 	/*
262173f53c4aSTejun Heo 	 * Start-to-wait phase
262273f53c4aSTejun Heo 	 */
262373f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
262473f53c4aSTejun Heo 
262573f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
262673f53c4aSTejun Heo 		/*
262773f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
262873f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
262973f53c4aSTejun Heo 		 * by one.
263073f53c4aSTejun Heo 		 */
263173f53c4aSTejun Heo 		BUG_ON(!list_empty(&wq->flusher_overflow));
263273f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
263373f53c4aSTejun Heo 		wq->work_color = next_color;
263473f53c4aSTejun Heo 
263573f53c4aSTejun Heo 		if (!wq->first_flusher) {
263673f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
263773f53c4aSTejun Heo 			BUG_ON(wq->flush_color != this_flusher.flush_color);
263873f53c4aSTejun Heo 
263973f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
264073f53c4aSTejun Heo 
264173f53c4aSTejun Heo 			if (!flush_workqueue_prep_cwqs(wq, wq->flush_color,
264273f53c4aSTejun Heo 						       wq->work_color)) {
264373f53c4aSTejun Heo 				/* nothing to flush, done */
264473f53c4aSTejun Heo 				wq->flush_color = next_color;
264573f53c4aSTejun Heo 				wq->first_flusher = NULL;
264673f53c4aSTejun Heo 				goto out_unlock;
264773f53c4aSTejun Heo 			}
264873f53c4aSTejun Heo 		} else {
264973f53c4aSTejun Heo 			/* wait in queue */
265073f53c4aSTejun Heo 			BUG_ON(wq->flush_color == this_flusher.flush_color);
265173f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
265273f53c4aSTejun Heo 			flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
265373f53c4aSTejun Heo 		}
265473f53c4aSTejun Heo 	} else {
265573f53c4aSTejun Heo 		/*
265673f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
265773f53c4aSTejun Heo 		 * The next flush completion will assign us
265873f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
265973f53c4aSTejun Heo 		 */
266073f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
266173f53c4aSTejun Heo 	}
266273f53c4aSTejun Heo 
266373f53c4aSTejun Heo 	mutex_unlock(&wq->flush_mutex);
266473f53c4aSTejun Heo 
266573f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
266673f53c4aSTejun Heo 
266773f53c4aSTejun Heo 	/*
266873f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
266973f53c4aSTejun Heo 	 *
267073f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
267173f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
267273f53c4aSTejun Heo 	 */
267373f53c4aSTejun Heo 	if (wq->first_flusher != &this_flusher)
267473f53c4aSTejun Heo 		return;
267573f53c4aSTejun Heo 
267673f53c4aSTejun Heo 	mutex_lock(&wq->flush_mutex);
267773f53c4aSTejun Heo 
26784ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
26794ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
26804ce48b37STejun Heo 		goto out_unlock;
26814ce48b37STejun Heo 
268273f53c4aSTejun Heo 	wq->first_flusher = NULL;
268373f53c4aSTejun Heo 
268473f53c4aSTejun Heo 	BUG_ON(!list_empty(&this_flusher.list));
268573f53c4aSTejun Heo 	BUG_ON(wq->flush_color != this_flusher.flush_color);
268673f53c4aSTejun Heo 
268773f53c4aSTejun Heo 	while (true) {
268873f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
268973f53c4aSTejun Heo 
269073f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
269173f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
269273f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
269373f53c4aSTejun Heo 				break;
269473f53c4aSTejun Heo 			list_del_init(&next->list);
269573f53c4aSTejun Heo 			complete(&next->done);
269673f53c4aSTejun Heo 		}
269773f53c4aSTejun Heo 
269873f53c4aSTejun Heo 		BUG_ON(!list_empty(&wq->flusher_overflow) &&
269973f53c4aSTejun Heo 		       wq->flush_color != work_next_color(wq->work_color));
270073f53c4aSTejun Heo 
270173f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
270273f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
270373f53c4aSTejun Heo 
270473f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
270573f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
270673f53c4aSTejun Heo 			/*
270773f53c4aSTejun Heo 			 * Assign the same color to all overflowed
270873f53c4aSTejun Heo 			 * flushers, advance work_color and append to
270973f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
271073f53c4aSTejun Heo 			 * phase for these overflowed flushers.
271173f53c4aSTejun Heo 			 */
271273f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
271373f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
271473f53c4aSTejun Heo 
271573f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
271673f53c4aSTejun Heo 
271773f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
271873f53c4aSTejun Heo 					      &wq->flusher_queue);
271973f53c4aSTejun Heo 			flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
272073f53c4aSTejun Heo 		}
272173f53c4aSTejun Heo 
272273f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
272373f53c4aSTejun Heo 			BUG_ON(wq->flush_color != wq->work_color);
272473f53c4aSTejun Heo 			break;
272573f53c4aSTejun Heo 		}
272673f53c4aSTejun Heo 
272773f53c4aSTejun Heo 		/*
272873f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
272973f53c4aSTejun Heo 		 * the new first flusher and arm cwqs.
273073f53c4aSTejun Heo 		 */
273173f53c4aSTejun Heo 		BUG_ON(wq->flush_color == wq->work_color);
273273f53c4aSTejun Heo 		BUG_ON(wq->flush_color != next->flush_color);
273373f53c4aSTejun Heo 
273473f53c4aSTejun Heo 		list_del_init(&next->list);
273573f53c4aSTejun Heo 		wq->first_flusher = next;
273673f53c4aSTejun Heo 
273773f53c4aSTejun Heo 		if (flush_workqueue_prep_cwqs(wq, wq->flush_color, -1))
273873f53c4aSTejun Heo 			break;
273973f53c4aSTejun Heo 
274073f53c4aSTejun Heo 		/*
274173f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
274273f53c4aSTejun Heo 		 * flusher and repeat cascading.
274373f53c4aSTejun Heo 		 */
274473f53c4aSTejun Heo 		wq->first_flusher = NULL;
274573f53c4aSTejun Heo 	}
274673f53c4aSTejun Heo 
274773f53c4aSTejun Heo out_unlock:
274873f53c4aSTejun Heo 	mutex_unlock(&wq->flush_mutex);
27491da177e4SLinus Torvalds }
2750ae90dd5dSDave Jones EXPORT_SYMBOL_GPL(flush_workqueue);
27511da177e4SLinus Torvalds 
27529c5a2ba7STejun Heo /**
27539c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
27549c5a2ba7STejun Heo  * @wq: workqueue to drain
27559c5a2ba7STejun Heo  *
27569c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
27579c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
27589c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
27599c5a2ba7STejun Heo  * repeatedly until it becomes empty.  The number of flushing is detemined
27609c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
27619c5a2ba7STejun Heo  * takes too long.
27629c5a2ba7STejun Heo  */
27639c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
27649c5a2ba7STejun Heo {
27659c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
27669c5a2ba7STejun Heo 	unsigned int cpu;
27679c5a2ba7STejun Heo 
27689c5a2ba7STejun Heo 	/*
27699c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
27709c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
27719c5a2ba7STejun Heo 	 * Use WQ_DRAINING so that queue doesn't have to check nr_drainers.
27729c5a2ba7STejun Heo 	 */
27739c5a2ba7STejun Heo 	spin_lock(&workqueue_lock);
27749c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
27759c5a2ba7STejun Heo 		wq->flags |= WQ_DRAINING;
27769c5a2ba7STejun Heo 	spin_unlock(&workqueue_lock);
27779c5a2ba7STejun Heo reflush:
27789c5a2ba7STejun Heo 	flush_workqueue(wq);
27799c5a2ba7STejun Heo 
27809c5a2ba7STejun Heo 	for_each_cwq_cpu(cpu, wq) {
27819c5a2ba7STejun Heo 		struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2782fa2563e4SThomas Tuttle 		bool drained;
27839c5a2ba7STejun Heo 
2784bd7bdd43STejun Heo 		spin_lock_irq(&cwq->pool->gcwq->lock);
2785fa2563e4SThomas Tuttle 		drained = !cwq->nr_active && list_empty(&cwq->delayed_works);
2786bd7bdd43STejun Heo 		spin_unlock_irq(&cwq->pool->gcwq->lock);
2787fa2563e4SThomas Tuttle 
2788fa2563e4SThomas Tuttle 		if (drained)
27899c5a2ba7STejun Heo 			continue;
27909c5a2ba7STejun Heo 
27919c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
27929c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
27939c5a2ba7STejun Heo 			pr_warning("workqueue %s: flush on destruction isn't complete after %u tries\n",
27949c5a2ba7STejun Heo 				   wq->name, flush_cnt);
27959c5a2ba7STejun Heo 		goto reflush;
27969c5a2ba7STejun Heo 	}
27979c5a2ba7STejun Heo 
27989c5a2ba7STejun Heo 	spin_lock(&workqueue_lock);
27999c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
28009c5a2ba7STejun Heo 		wq->flags &= ~WQ_DRAINING;
28019c5a2ba7STejun Heo 	spin_unlock(&workqueue_lock);
28029c5a2ba7STejun Heo }
28039c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
28049c5a2ba7STejun Heo 
2805baf59022STejun Heo static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
2806baf59022STejun Heo 			     bool wait_executing)
2807baf59022STejun Heo {
2808baf59022STejun Heo 	struct worker *worker = NULL;
2809baf59022STejun Heo 	struct global_cwq *gcwq;
2810baf59022STejun Heo 	struct cpu_workqueue_struct *cwq;
2811baf59022STejun Heo 
2812baf59022STejun Heo 	might_sleep();
2813baf59022STejun Heo 	gcwq = get_work_gcwq(work);
2814baf59022STejun Heo 	if (!gcwq)
2815baf59022STejun Heo 		return false;
2816baf59022STejun Heo 
2817baf59022STejun Heo 	spin_lock_irq(&gcwq->lock);
2818baf59022STejun Heo 	if (!list_empty(&work->entry)) {
2819baf59022STejun Heo 		/*
2820baf59022STejun Heo 		 * See the comment near try_to_grab_pending()->smp_rmb().
2821baf59022STejun Heo 		 * If it was re-queued to a different gcwq under us, we
2822baf59022STejun Heo 		 * are not going to wait.
2823baf59022STejun Heo 		 */
2824baf59022STejun Heo 		smp_rmb();
2825baf59022STejun Heo 		cwq = get_work_cwq(work);
2826bd7bdd43STejun Heo 		if (unlikely(!cwq || gcwq != cwq->pool->gcwq))
2827baf59022STejun Heo 			goto already_gone;
2828baf59022STejun Heo 	} else if (wait_executing) {
2829baf59022STejun Heo 		worker = find_worker_executing_work(gcwq, work);
2830baf59022STejun Heo 		if (!worker)
2831baf59022STejun Heo 			goto already_gone;
2832baf59022STejun Heo 		cwq = worker->current_cwq;
2833baf59022STejun Heo 	} else
2834baf59022STejun Heo 		goto already_gone;
2835baf59022STejun Heo 
2836baf59022STejun Heo 	insert_wq_barrier(cwq, barr, work, worker);
2837baf59022STejun Heo 	spin_unlock_irq(&gcwq->lock);
2838baf59022STejun Heo 
2839e159489bSTejun Heo 	/*
2840e159489bSTejun Heo 	 * If @max_active is 1 or rescuer is in use, flushing another work
2841e159489bSTejun Heo 	 * item on the same workqueue may lead to deadlock.  Make sure the
2842e159489bSTejun Heo 	 * flusher is not running on the same workqueue by verifying write
2843e159489bSTejun Heo 	 * access.
2844e159489bSTejun Heo 	 */
2845e159489bSTejun Heo 	if (cwq->wq->saved_max_active == 1 || cwq->wq->flags & WQ_RESCUER)
2846baf59022STejun Heo 		lock_map_acquire(&cwq->wq->lockdep_map);
2847e159489bSTejun Heo 	else
2848e159489bSTejun Heo 		lock_map_acquire_read(&cwq->wq->lockdep_map);
2849baf59022STejun Heo 	lock_map_release(&cwq->wq->lockdep_map);
2850e159489bSTejun Heo 
2851baf59022STejun Heo 	return true;
2852baf59022STejun Heo already_gone:
2853baf59022STejun Heo 	spin_unlock_irq(&gcwq->lock);
2854baf59022STejun Heo 	return false;
2855baf59022STejun Heo }
2856baf59022STejun Heo 
2857db700897SOleg Nesterov /**
2858401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
2859401a8d04STejun Heo  * @work: the work to flush
2860db700897SOleg Nesterov  *
2861401a8d04STejun Heo  * Wait until @work has finished execution.  This function considers
2862401a8d04STejun Heo  * only the last queueing instance of @work.  If @work has been
2863401a8d04STejun Heo  * enqueued across different CPUs on a non-reentrant workqueue or on
2864401a8d04STejun Heo  * multiple workqueues, @work might still be executing on return on
2865401a8d04STejun Heo  * some of the CPUs from earlier queueing.
2866a67da70dSOleg Nesterov  *
2867401a8d04STejun Heo  * If @work was queued only on a non-reentrant, ordered or unbound
2868401a8d04STejun Heo  * workqueue, @work is guaranteed to be idle on return if it hasn't
2869401a8d04STejun Heo  * been requeued since flush started.
2870401a8d04STejun Heo  *
2871401a8d04STejun Heo  * RETURNS:
2872401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
2873401a8d04STejun Heo  * %false if it was already idle.
2874db700897SOleg Nesterov  */
2875401a8d04STejun Heo bool flush_work(struct work_struct *work)
2876db700897SOleg Nesterov {
2877db700897SOleg Nesterov 	struct wq_barrier barr;
2878db700897SOleg Nesterov 
28790976dfc1SStephen Boyd 	lock_map_acquire(&work->lockdep_map);
28800976dfc1SStephen Boyd 	lock_map_release(&work->lockdep_map);
28810976dfc1SStephen Boyd 
2882baf59022STejun Heo 	if (start_flush_work(work, &barr, true)) {
2883db700897SOleg Nesterov 		wait_for_completion(&barr.done);
2884dc186ad7SThomas Gleixner 		destroy_work_on_stack(&barr.work);
2885401a8d04STejun Heo 		return true;
2886baf59022STejun Heo 	} else
2887401a8d04STejun Heo 		return false;
2888db700897SOleg Nesterov }
2889db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
2890db700897SOleg Nesterov 
2891401a8d04STejun Heo static bool wait_on_cpu_work(struct global_cwq *gcwq, struct work_struct *work)
2892401a8d04STejun Heo {
2893401a8d04STejun Heo 	struct wq_barrier barr;
2894401a8d04STejun Heo 	struct worker *worker;
2895401a8d04STejun Heo 
2896401a8d04STejun Heo 	spin_lock_irq(&gcwq->lock);
2897401a8d04STejun Heo 
2898401a8d04STejun Heo 	worker = find_worker_executing_work(gcwq, work);
2899401a8d04STejun Heo 	if (unlikely(worker))
2900401a8d04STejun Heo 		insert_wq_barrier(worker->current_cwq, &barr, work, worker);
2901401a8d04STejun Heo 
2902401a8d04STejun Heo 	spin_unlock_irq(&gcwq->lock);
2903401a8d04STejun Heo 
2904401a8d04STejun Heo 	if (unlikely(worker)) {
2905401a8d04STejun Heo 		wait_for_completion(&barr.done);
2906401a8d04STejun Heo 		destroy_work_on_stack(&barr.work);
2907401a8d04STejun Heo 		return true;
2908401a8d04STejun Heo 	} else
2909401a8d04STejun Heo 		return false;
2910401a8d04STejun Heo }
2911401a8d04STejun Heo 
2912401a8d04STejun Heo static bool wait_on_work(struct work_struct *work)
2913401a8d04STejun Heo {
2914401a8d04STejun Heo 	bool ret = false;
2915401a8d04STejun Heo 	int cpu;
2916401a8d04STejun Heo 
2917401a8d04STejun Heo 	might_sleep();
2918401a8d04STejun Heo 
2919401a8d04STejun Heo 	lock_map_acquire(&work->lockdep_map);
2920401a8d04STejun Heo 	lock_map_release(&work->lockdep_map);
2921401a8d04STejun Heo 
2922401a8d04STejun Heo 	for_each_gcwq_cpu(cpu)
2923401a8d04STejun Heo 		ret |= wait_on_cpu_work(get_gcwq(cpu), work);
2924401a8d04STejun Heo 	return ret;
2925401a8d04STejun Heo }
2926401a8d04STejun Heo 
292709383498STejun Heo /**
292809383498STejun Heo  * flush_work_sync - wait until a work has finished execution
292909383498STejun Heo  * @work: the work to flush
293009383498STejun Heo  *
293109383498STejun Heo  * Wait until @work has finished execution.  On return, it's
293209383498STejun Heo  * guaranteed that all queueing instances of @work which happened
293309383498STejun Heo  * before this function is called are finished.  In other words, if
293409383498STejun Heo  * @work hasn't been requeued since this function was called, @work is
293509383498STejun Heo  * guaranteed to be idle on return.
293609383498STejun Heo  *
293709383498STejun Heo  * RETURNS:
293809383498STejun Heo  * %true if flush_work_sync() waited for the work to finish execution,
293909383498STejun Heo  * %false if it was already idle.
294009383498STejun Heo  */
294109383498STejun Heo bool flush_work_sync(struct work_struct *work)
294209383498STejun Heo {
294309383498STejun Heo 	struct wq_barrier barr;
294409383498STejun Heo 	bool pending, waited;
294509383498STejun Heo 
294609383498STejun Heo 	/* we'll wait for executions separately, queue barr only if pending */
294709383498STejun Heo 	pending = start_flush_work(work, &barr, false);
294809383498STejun Heo 
294909383498STejun Heo 	/* wait for executions to finish */
295009383498STejun Heo 	waited = wait_on_work(work);
295109383498STejun Heo 
295209383498STejun Heo 	/* wait for the pending one */
295309383498STejun Heo 	if (pending) {
295409383498STejun Heo 		wait_for_completion(&barr.done);
295509383498STejun Heo 		destroy_work_on_stack(&barr.work);
295609383498STejun Heo 	}
295709383498STejun Heo 
295809383498STejun Heo 	return pending || waited;
295909383498STejun Heo }
296009383498STejun Heo EXPORT_SYMBOL_GPL(flush_work_sync);
296109383498STejun Heo 
296236e227d2STejun Heo static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
29631f1f642eSOleg Nesterov {
2964bbb68dfaSTejun Heo 	unsigned long flags;
29651f1f642eSOleg Nesterov 	int ret;
29661f1f642eSOleg Nesterov 
29671f1f642eSOleg Nesterov 	do {
2968bbb68dfaSTejun Heo 		ret = try_to_grab_pending(work, is_dwork, &flags);
2969bbb68dfaSTejun Heo 		/*
2970bbb68dfaSTejun Heo 		 * If someone else is canceling, wait for the same event it
2971bbb68dfaSTejun Heo 		 * would be waiting for before retrying.
2972bbb68dfaSTejun Heo 		 */
2973bbb68dfaSTejun Heo 		if (unlikely(ret == -ENOENT))
29741f1f642eSOleg Nesterov 			wait_on_work(work);
29751f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
29761f1f642eSOleg Nesterov 
2977bbb68dfaSTejun Heo 	/* tell other tasks trying to grab @work to back off */
2978bbb68dfaSTejun Heo 	mark_work_canceling(work);
2979bbb68dfaSTejun Heo 	local_irq_restore(flags);
2980bbb68dfaSTejun Heo 
2981bbb68dfaSTejun Heo 	wait_on_work(work);
29827a22ad75STejun Heo 	clear_work_data(work);
29831f1f642eSOleg Nesterov 	return ret;
29841f1f642eSOleg Nesterov }
29851f1f642eSOleg Nesterov 
29866e84d644SOleg Nesterov /**
2987401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
2988401a8d04STejun Heo  * @work: the work to cancel
29896e84d644SOleg Nesterov  *
2990401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
2991401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
2992401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
2993401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
29941f1f642eSOleg Nesterov  *
2995401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
2996401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
29976e84d644SOleg Nesterov  *
2998401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
29996e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
3000401a8d04STejun Heo  *
3001401a8d04STejun Heo  * RETURNS:
3002401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
30036e84d644SOleg Nesterov  */
3004401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
30056e84d644SOleg Nesterov {
300636e227d2STejun Heo 	return __cancel_work_timer(work, false);
3007b89deed3SOleg Nesterov }
300828e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
3009b89deed3SOleg Nesterov 
30106e84d644SOleg Nesterov /**
3011401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
3012401a8d04STejun Heo  * @dwork: the delayed work to flush
30136e84d644SOleg Nesterov  *
3014401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
3015401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
3016401a8d04STejun Heo  * considers the last queueing instance of @dwork.
30171f1f642eSOleg Nesterov  *
3018401a8d04STejun Heo  * RETURNS:
3019401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3020401a8d04STejun Heo  * %false if it was already idle.
30216e84d644SOleg Nesterov  */
3022401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
3023401a8d04STejun Heo {
30248930cabaSTejun Heo 	local_irq_disable();
3025401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
30261265057fSTejun Heo 		__queue_work(dwork->cpu,
3027401a8d04STejun Heo 			     get_work_cwq(&dwork->work)->wq, &dwork->work);
30288930cabaSTejun Heo 	local_irq_enable();
3029401a8d04STejun Heo 	return flush_work(&dwork->work);
3030401a8d04STejun Heo }
3031401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
3032401a8d04STejun Heo 
3033401a8d04STejun Heo /**
303409383498STejun Heo  * flush_delayed_work_sync - wait for a dwork to finish
303509383498STejun Heo  * @dwork: the delayed work to flush
303609383498STejun Heo  *
303709383498STejun Heo  * Delayed timer is cancelled and the pending work is queued for
303809383498STejun Heo  * execution immediately.  Other than timer handling, its behavior
303909383498STejun Heo  * is identical to flush_work_sync().
304009383498STejun Heo  *
304109383498STejun Heo  * RETURNS:
304209383498STejun Heo  * %true if flush_work_sync() waited for the work to finish execution,
304309383498STejun Heo  * %false if it was already idle.
304409383498STejun Heo  */
304509383498STejun Heo bool flush_delayed_work_sync(struct delayed_work *dwork)
304609383498STejun Heo {
30478930cabaSTejun Heo 	local_irq_disable();
304809383498STejun Heo 	if (del_timer_sync(&dwork->timer))
30491265057fSTejun Heo 		__queue_work(dwork->cpu,
305009383498STejun Heo 			     get_work_cwq(&dwork->work)->wq, &dwork->work);
30518930cabaSTejun Heo 	local_irq_enable();
305209383498STejun Heo 	return flush_work_sync(&dwork->work);
305309383498STejun Heo }
305409383498STejun Heo EXPORT_SYMBOL(flush_delayed_work_sync);
305509383498STejun Heo 
305609383498STejun Heo /**
3057401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3058401a8d04STejun Heo  * @dwork: the delayed work cancel
3059401a8d04STejun Heo  *
3060401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
3061401a8d04STejun Heo  *
3062401a8d04STejun Heo  * RETURNS:
3063401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
3064401a8d04STejun Heo  */
3065401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
30666e84d644SOleg Nesterov {
306736e227d2STejun Heo 	return __cancel_work_timer(&dwork->work, true);
30686e84d644SOleg Nesterov }
3069f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
30701da177e4SLinus Torvalds 
3071d4283e93STejun Heo /**
30720a13c00eSTejun Heo  * schedule_work_on - put work task on a specific cpu
30730a13c00eSTejun Heo  * @cpu: cpu to put the work task on
30740a13c00eSTejun Heo  * @work: job to be done
30750a13c00eSTejun Heo  *
30760a13c00eSTejun Heo  * This puts a job on a specific cpu
30770a13c00eSTejun Heo  */
3078d4283e93STejun Heo bool schedule_work_on(int cpu, struct work_struct *work)
30790a13c00eSTejun Heo {
30800a13c00eSTejun Heo 	return queue_work_on(cpu, system_wq, work);
30810a13c00eSTejun Heo }
30820a13c00eSTejun Heo EXPORT_SYMBOL(schedule_work_on);
30830a13c00eSTejun Heo 
30840fcb78c2SRolf Eike Beer /**
30850fcb78c2SRolf Eike Beer  * schedule_work - put work task in global workqueue
30860fcb78c2SRolf Eike Beer  * @work: job to be done
30870fcb78c2SRolf Eike Beer  *
3088d4283e93STejun Heo  * Returns %false if @work was already on the kernel-global workqueue and
3089d4283e93STejun Heo  * %true otherwise.
30905b0f437dSBart Van Assche  *
30915b0f437dSBart Van Assche  * This puts a job in the kernel-global workqueue if it was not already
30925b0f437dSBart Van Assche  * queued and leaves it in the same position on the kernel-global
30935b0f437dSBart Van Assche  * workqueue otherwise.
30940fcb78c2SRolf Eike Beer  */
3095d4283e93STejun Heo bool schedule_work(struct work_struct *work)
30961da177e4SLinus Torvalds {
3097d320c038STejun Heo 	return queue_work(system_wq, work);
30981da177e4SLinus Torvalds }
3099ae90dd5dSDave Jones EXPORT_SYMBOL(schedule_work);
31001da177e4SLinus Torvalds 
31010fcb78c2SRolf Eike Beer /**
31020fcb78c2SRolf Eike Beer  * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
31030fcb78c2SRolf Eike Beer  * @cpu: cpu to use
310452bad64dSDavid Howells  * @dwork: job to be done
31050fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait
31060fcb78c2SRolf Eike Beer  *
31070fcb78c2SRolf Eike Beer  * After waiting for a given time this puts a job in the kernel-global
31080fcb78c2SRolf Eike Beer  * workqueue on the specified CPU.
31090fcb78c2SRolf Eike Beer  */
3110d4283e93STejun Heo bool schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
3111d4283e93STejun Heo 			      unsigned long delay)
31121da177e4SLinus Torvalds {
3113d320c038STejun Heo 	return queue_delayed_work_on(cpu, system_wq, dwork, delay);
31141da177e4SLinus Torvalds }
3115ae90dd5dSDave Jones EXPORT_SYMBOL(schedule_delayed_work_on);
31161da177e4SLinus Torvalds 
3117b6136773SAndrew Morton /**
31180a13c00eSTejun Heo  * schedule_delayed_work - put work task in global workqueue after delay
31190a13c00eSTejun Heo  * @dwork: job to be done
31200a13c00eSTejun Heo  * @delay: number of jiffies to wait or 0 for immediate execution
31210a13c00eSTejun Heo  *
31220a13c00eSTejun Heo  * After waiting for a given time this puts a job in the kernel-global
31230a13c00eSTejun Heo  * workqueue.
31240a13c00eSTejun Heo  */
3125d4283e93STejun Heo bool schedule_delayed_work(struct delayed_work *dwork, unsigned long delay)
31260a13c00eSTejun Heo {
31270a13c00eSTejun Heo 	return queue_delayed_work(system_wq, dwork, delay);
31280a13c00eSTejun Heo }
31290a13c00eSTejun Heo EXPORT_SYMBOL(schedule_delayed_work);
31300a13c00eSTejun Heo 
31310a13c00eSTejun Heo /**
313231ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
3133b6136773SAndrew Morton  * @func: the function to call
3134b6136773SAndrew Morton  *
313531ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
313631ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
3137b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
313831ddd871STejun Heo  *
313931ddd871STejun Heo  * RETURNS:
314031ddd871STejun Heo  * 0 on success, -errno on failure.
3141b6136773SAndrew Morton  */
314265f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
314315316ba8SChristoph Lameter {
314415316ba8SChristoph Lameter 	int cpu;
314538f51568SNamhyung Kim 	struct work_struct __percpu *works;
314615316ba8SChristoph Lameter 
3147b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
3148b6136773SAndrew Morton 	if (!works)
314915316ba8SChristoph Lameter 		return -ENOMEM;
3150b6136773SAndrew Morton 
315195402b38SGautham R Shenoy 	get_online_cpus();
315293981800STejun Heo 
315315316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
31549bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
31559bfb1839SIngo Molnar 
31569bfb1839SIngo Molnar 		INIT_WORK(work, func);
31578de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
315815316ba8SChristoph Lameter 	}
315993981800STejun Heo 
316093981800STejun Heo 	for_each_online_cpu(cpu)
31618616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
316293981800STejun Heo 
316395402b38SGautham R Shenoy 	put_online_cpus();
3164b6136773SAndrew Morton 	free_percpu(works);
316515316ba8SChristoph Lameter 	return 0;
316615316ba8SChristoph Lameter }
316715316ba8SChristoph Lameter 
3168eef6a7d5SAlan Stern /**
3169eef6a7d5SAlan Stern  * flush_scheduled_work - ensure that any scheduled work has run to completion.
3170eef6a7d5SAlan Stern  *
3171eef6a7d5SAlan Stern  * Forces execution of the kernel-global workqueue and blocks until its
3172eef6a7d5SAlan Stern  * completion.
3173eef6a7d5SAlan Stern  *
3174eef6a7d5SAlan Stern  * Think twice before calling this function!  It's very easy to get into
3175eef6a7d5SAlan Stern  * trouble if you don't take great care.  Either of the following situations
3176eef6a7d5SAlan Stern  * will lead to deadlock:
3177eef6a7d5SAlan Stern  *
3178eef6a7d5SAlan Stern  *	One of the work items currently on the workqueue needs to acquire
3179eef6a7d5SAlan Stern  *	a lock held by your code or its caller.
3180eef6a7d5SAlan Stern  *
3181eef6a7d5SAlan Stern  *	Your code is running in the context of a work routine.
3182eef6a7d5SAlan Stern  *
3183eef6a7d5SAlan Stern  * They will be detected by lockdep when they occur, but the first might not
3184eef6a7d5SAlan Stern  * occur very often.  It depends on what work items are on the workqueue and
3185eef6a7d5SAlan Stern  * what locks they need, which you have no control over.
3186eef6a7d5SAlan Stern  *
3187eef6a7d5SAlan Stern  * In most situations flushing the entire workqueue is overkill; you merely
3188eef6a7d5SAlan Stern  * need to know that a particular work item isn't queued and isn't running.
3189eef6a7d5SAlan Stern  * In such cases you should use cancel_delayed_work_sync() or
3190eef6a7d5SAlan Stern  * cancel_work_sync() instead.
3191eef6a7d5SAlan Stern  */
31921da177e4SLinus Torvalds void flush_scheduled_work(void)
31931da177e4SLinus Torvalds {
3194d320c038STejun Heo 	flush_workqueue(system_wq);
31951da177e4SLinus Torvalds }
3196ae90dd5dSDave Jones EXPORT_SYMBOL(flush_scheduled_work);
31971da177e4SLinus Torvalds 
31981da177e4SLinus Torvalds /**
31991fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
32001fa44ecaSJames Bottomley  * @fn:		the function to execute
32011fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
32021fa44ecaSJames Bottomley  *		be available when the work executes)
32031fa44ecaSJames Bottomley  *
32041fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
32051fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
32061fa44ecaSJames Bottomley  *
32071fa44ecaSJames Bottomley  * Returns:	0 - function was executed
32081fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
32091fa44ecaSJames Bottomley  */
321065f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
32111fa44ecaSJames Bottomley {
32121fa44ecaSJames Bottomley 	if (!in_interrupt()) {
321365f27f38SDavid Howells 		fn(&ew->work);
32141fa44ecaSJames Bottomley 		return 0;
32151fa44ecaSJames Bottomley 	}
32161fa44ecaSJames Bottomley 
321765f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
32181fa44ecaSJames Bottomley 	schedule_work(&ew->work);
32191fa44ecaSJames Bottomley 
32201fa44ecaSJames Bottomley 	return 1;
32211fa44ecaSJames Bottomley }
32221fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
32231fa44ecaSJames Bottomley 
32241da177e4SLinus Torvalds int keventd_up(void)
32251da177e4SLinus Torvalds {
3226d320c038STejun Heo 	return system_wq != NULL;
32271da177e4SLinus Torvalds }
32281da177e4SLinus Torvalds 
3229bdbc5dd7STejun Heo static int alloc_cwqs(struct workqueue_struct *wq)
32301da177e4SLinus Torvalds {
32313af24433SOleg Nesterov 	/*
32320f900049STejun Heo 	 * cwqs are forced aligned according to WORK_STRUCT_FLAG_BITS.
32330f900049STejun Heo 	 * Make sure that the alignment isn't lower than that of
32340f900049STejun Heo 	 * unsigned long long.
32353af24433SOleg Nesterov 	 */
32360f900049STejun Heo 	const size_t size = sizeof(struct cpu_workqueue_struct);
32370f900049STejun Heo 	const size_t align = max_t(size_t, 1 << WORK_STRUCT_FLAG_BITS,
32380f900049STejun Heo 				   __alignof__(unsigned long long));
32393af24433SOleg Nesterov 
3240e06ffa1eSLai Jiangshan 	if (!(wq->flags & WQ_UNBOUND))
3241f3421797STejun Heo 		wq->cpu_wq.pcpu = __alloc_percpu(size, align);
3242931ac77eSTejun Heo 	else {
32430f900049STejun Heo 		void *ptr;
3244e1d8aa9fSFrederic Weisbecker 
32450f900049STejun Heo 		/*
3246f3421797STejun Heo 		 * Allocate enough room to align cwq and put an extra
3247f3421797STejun Heo 		 * pointer at the end pointing back to the originally
3248f3421797STejun Heo 		 * allocated pointer which will be used for free.
32490f900049STejun Heo 		 */
3250bdbc5dd7STejun Heo 		ptr = kzalloc(size + align + sizeof(void *), GFP_KERNEL);
3251bdbc5dd7STejun Heo 		if (ptr) {
3252bdbc5dd7STejun Heo 			wq->cpu_wq.single = PTR_ALIGN(ptr, align);
3253bdbc5dd7STejun Heo 			*(void **)(wq->cpu_wq.single + 1) = ptr;
3254bdbc5dd7STejun Heo 		}
32553af24433SOleg Nesterov 	}
32563af24433SOleg Nesterov 
32570415b00dSTejun Heo 	/* just in case, make sure it's actually aligned */
3258bdbc5dd7STejun Heo 	BUG_ON(!IS_ALIGNED(wq->cpu_wq.v, align));
3259bdbc5dd7STejun Heo 	return wq->cpu_wq.v ? 0 : -ENOMEM;
32600f900049STejun Heo }
32610f900049STejun Heo 
3262bdbc5dd7STejun Heo static void free_cwqs(struct workqueue_struct *wq)
326306ba38a9SOleg Nesterov {
3264e06ffa1eSLai Jiangshan 	if (!(wq->flags & WQ_UNBOUND))
3265bdbc5dd7STejun Heo 		free_percpu(wq->cpu_wq.pcpu);
3266f3421797STejun Heo 	else if (wq->cpu_wq.single) {
3267f3421797STejun Heo 		/* the pointer to free is stored right after the cwq */
3268f3421797STejun Heo 		kfree(*(void **)(wq->cpu_wq.single + 1));
326906ba38a9SOleg Nesterov 	}
327006ba38a9SOleg Nesterov }
327106ba38a9SOleg Nesterov 
3272f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
3273f3421797STejun Heo 			       const char *name)
3274b71ab8c2STejun Heo {
3275f3421797STejun Heo 	int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3276f3421797STejun Heo 
3277f3421797STejun Heo 	if (max_active < 1 || max_active > lim)
3278b71ab8c2STejun Heo 		printk(KERN_WARNING "workqueue: max_active %d requested for %s "
3279b71ab8c2STejun Heo 		       "is out of range, clamping between %d and %d\n",
3280f3421797STejun Heo 		       max_active, name, 1, lim);
3281b71ab8c2STejun Heo 
3282f3421797STejun Heo 	return clamp_val(max_active, 1, lim);
3283b71ab8c2STejun Heo }
3284b71ab8c2STejun Heo 
3285b196be89STejun Heo struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
328697e37d7bSTejun Heo 					       unsigned int flags,
32871e19ffc6STejun Heo 					       int max_active,
3288eb13ba87SJohannes Berg 					       struct lock_class_key *key,
3289b196be89STejun Heo 					       const char *lock_name, ...)
32903af24433SOleg Nesterov {
3291b196be89STejun Heo 	va_list args, args1;
32923af24433SOleg Nesterov 	struct workqueue_struct *wq;
3293c34056a3STejun Heo 	unsigned int cpu;
3294b196be89STejun Heo 	size_t namelen;
3295b196be89STejun Heo 
3296b196be89STejun Heo 	/* determine namelen, allocate wq and format name */
3297b196be89STejun Heo 	va_start(args, lock_name);
3298b196be89STejun Heo 	va_copy(args1, args);
3299b196be89STejun Heo 	namelen = vsnprintf(NULL, 0, fmt, args) + 1;
3300b196be89STejun Heo 
3301b196be89STejun Heo 	wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
3302b196be89STejun Heo 	if (!wq)
3303b196be89STejun Heo 		goto err;
3304b196be89STejun Heo 
3305b196be89STejun Heo 	vsnprintf(wq->name, namelen, fmt, args1);
3306b196be89STejun Heo 	va_end(args);
3307b196be89STejun Heo 	va_end(args1);
33083af24433SOleg Nesterov 
3309f3421797STejun Heo 	/*
33106370a6adSTejun Heo 	 * Workqueues which may be used during memory reclaim should
33116370a6adSTejun Heo 	 * have a rescuer to guarantee forward progress.
33126370a6adSTejun Heo 	 */
33136370a6adSTejun Heo 	if (flags & WQ_MEM_RECLAIM)
33146370a6adSTejun Heo 		flags |= WQ_RESCUER;
33156370a6adSTejun Heo 
3316d320c038STejun Heo 	max_active = max_active ?: WQ_DFL_ACTIVE;
3317b196be89STejun Heo 	max_active = wq_clamp_max_active(max_active, flags, wq->name);
33183af24433SOleg Nesterov 
3319b196be89STejun Heo 	/* init wq */
332097e37d7bSTejun Heo 	wq->flags = flags;
3321a0a1a5fdSTejun Heo 	wq->saved_max_active = max_active;
332273f53c4aSTejun Heo 	mutex_init(&wq->flush_mutex);
332373f53c4aSTejun Heo 	atomic_set(&wq->nr_cwqs_to_flush, 0);
332473f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
332573f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
33263af24433SOleg Nesterov 
3327eb13ba87SJohannes Berg 	lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3328cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
33293af24433SOleg Nesterov 
3330bdbc5dd7STejun Heo 	if (alloc_cwqs(wq) < 0)
3331bdbc5dd7STejun Heo 		goto err;
3332bdbc5dd7STejun Heo 
3333f3421797STejun Heo 	for_each_cwq_cpu(cpu, wq) {
33341537663fSTejun Heo 		struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
33358b03ae3cSTejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
33363270476aSTejun Heo 		int pool_idx = (bool)(flags & WQ_HIGHPRI);
33371537663fSTejun Heo 
33380f900049STejun Heo 		BUG_ON((unsigned long)cwq & WORK_STRUCT_FLAG_MASK);
33393270476aSTejun Heo 		cwq->pool = &gcwq->pools[pool_idx];
3340c34056a3STejun Heo 		cwq->wq = wq;
334173f53c4aSTejun Heo 		cwq->flush_color = -1;
33421e19ffc6STejun Heo 		cwq->max_active = max_active;
33431e19ffc6STejun Heo 		INIT_LIST_HEAD(&cwq->delayed_works);
3344e22bee78STejun Heo 	}
33451537663fSTejun Heo 
3346e22bee78STejun Heo 	if (flags & WQ_RESCUER) {
3347e22bee78STejun Heo 		struct worker *rescuer;
3348e22bee78STejun Heo 
3349f2e005aaSTejun Heo 		if (!alloc_mayday_mask(&wq->mayday_mask, GFP_KERNEL))
3350e22bee78STejun Heo 			goto err;
3351e22bee78STejun Heo 
3352e22bee78STejun Heo 		wq->rescuer = rescuer = alloc_worker();
3353e22bee78STejun Heo 		if (!rescuer)
3354e22bee78STejun Heo 			goto err;
3355e22bee78STejun Heo 
3356b196be89STejun Heo 		rescuer->task = kthread_create(rescuer_thread, wq, "%s",
3357b196be89STejun Heo 					       wq->name);
3358e22bee78STejun Heo 		if (IS_ERR(rescuer->task))
3359e22bee78STejun Heo 			goto err;
3360e22bee78STejun Heo 
3361e22bee78STejun Heo 		rescuer->task->flags |= PF_THREAD_BOUND;
3362e22bee78STejun Heo 		wake_up_process(rescuer->task);
33633af24433SOleg Nesterov 	}
33641537663fSTejun Heo 
33653af24433SOleg Nesterov 	/*
3366a0a1a5fdSTejun Heo 	 * workqueue_lock protects global freeze state and workqueues
3367a0a1a5fdSTejun Heo 	 * list.  Grab it, set max_active accordingly and add the new
3368a0a1a5fdSTejun Heo 	 * workqueue to workqueues list.
33693af24433SOleg Nesterov 	 */
33703af24433SOleg Nesterov 	spin_lock(&workqueue_lock);
3371a0a1a5fdSTejun Heo 
337258a69cb4STejun Heo 	if (workqueue_freezing && wq->flags & WQ_FREEZABLE)
3373f3421797STejun Heo 		for_each_cwq_cpu(cpu, wq)
3374a0a1a5fdSTejun Heo 			get_cwq(cpu, wq)->max_active = 0;
3375a0a1a5fdSTejun Heo 
33763af24433SOleg Nesterov 	list_add(&wq->list, &workqueues);
3377a0a1a5fdSTejun Heo 
33783af24433SOleg Nesterov 	spin_unlock(&workqueue_lock);
33793af24433SOleg Nesterov 
33803af24433SOleg Nesterov 	return wq;
33814690c4abSTejun Heo err:
33824690c4abSTejun Heo 	if (wq) {
3383bdbc5dd7STejun Heo 		free_cwqs(wq);
3384f2e005aaSTejun Heo 		free_mayday_mask(wq->mayday_mask);
3385e22bee78STejun Heo 		kfree(wq->rescuer);
33864690c4abSTejun Heo 		kfree(wq);
33873af24433SOleg Nesterov 	}
33884690c4abSTejun Heo 	return NULL;
33891da177e4SLinus Torvalds }
3390d320c038STejun Heo EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
33911da177e4SLinus Torvalds 
33923af24433SOleg Nesterov /**
33933af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
33943af24433SOleg Nesterov  * @wq: target workqueue
33953af24433SOleg Nesterov  *
33963af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
33973af24433SOleg Nesterov  */
33983af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
33993af24433SOleg Nesterov {
3400c8e55f36STejun Heo 	unsigned int cpu;
34013af24433SOleg Nesterov 
34029c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
34039c5a2ba7STejun Heo 	drain_workqueue(wq);
3404c8efcc25STejun Heo 
3405a0a1a5fdSTejun Heo 	/*
3406a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
3407a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
3408a0a1a5fdSTejun Heo 	 */
340995402b38SGautham R Shenoy 	spin_lock(&workqueue_lock);
34103af24433SOleg Nesterov 	list_del(&wq->list);
341195402b38SGautham R Shenoy 	spin_unlock(&workqueue_lock);
34123af24433SOleg Nesterov 
3413e22bee78STejun Heo 	/* sanity check */
3414f3421797STejun Heo 	for_each_cwq_cpu(cpu, wq) {
341573f53c4aSTejun Heo 		struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
341673f53c4aSTejun Heo 		int i;
34173af24433SOleg Nesterov 
341873f53c4aSTejun Heo 		for (i = 0; i < WORK_NR_COLORS; i++)
341973f53c4aSTejun Heo 			BUG_ON(cwq->nr_in_flight[i]);
34201e19ffc6STejun Heo 		BUG_ON(cwq->nr_active);
34211e19ffc6STejun Heo 		BUG_ON(!list_empty(&cwq->delayed_works));
342273f53c4aSTejun Heo 	}
34231537663fSTejun Heo 
3424e22bee78STejun Heo 	if (wq->flags & WQ_RESCUER) {
3425e22bee78STejun Heo 		kthread_stop(wq->rescuer->task);
3426f2e005aaSTejun Heo 		free_mayday_mask(wq->mayday_mask);
34278d9df9f0SXiaotian Feng 		kfree(wq->rescuer);
3428e22bee78STejun Heo 	}
3429e22bee78STejun Heo 
3430bdbc5dd7STejun Heo 	free_cwqs(wq);
34313af24433SOleg Nesterov 	kfree(wq);
34323af24433SOleg Nesterov }
34333af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
34343af24433SOleg Nesterov 
3435dcd989cbSTejun Heo /**
3436dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
3437dcd989cbSTejun Heo  * @wq: target workqueue
3438dcd989cbSTejun Heo  * @max_active: new max_active value.
3439dcd989cbSTejun Heo  *
3440dcd989cbSTejun Heo  * Set max_active of @wq to @max_active.
3441dcd989cbSTejun Heo  *
3442dcd989cbSTejun Heo  * CONTEXT:
3443dcd989cbSTejun Heo  * Don't call from IRQ context.
3444dcd989cbSTejun Heo  */
3445dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
3446dcd989cbSTejun Heo {
3447dcd989cbSTejun Heo 	unsigned int cpu;
3448dcd989cbSTejun Heo 
3449f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
3450dcd989cbSTejun Heo 
3451dcd989cbSTejun Heo 	spin_lock(&workqueue_lock);
3452dcd989cbSTejun Heo 
3453dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
3454dcd989cbSTejun Heo 
3455f3421797STejun Heo 	for_each_cwq_cpu(cpu, wq) {
3456dcd989cbSTejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
3457dcd989cbSTejun Heo 
3458dcd989cbSTejun Heo 		spin_lock_irq(&gcwq->lock);
3459dcd989cbSTejun Heo 
346058a69cb4STejun Heo 		if (!(wq->flags & WQ_FREEZABLE) ||
3461dcd989cbSTejun Heo 		    !(gcwq->flags & GCWQ_FREEZING))
3462dcd989cbSTejun Heo 			get_cwq(gcwq->cpu, wq)->max_active = max_active;
3463dcd989cbSTejun Heo 
3464dcd989cbSTejun Heo 		spin_unlock_irq(&gcwq->lock);
3465dcd989cbSTejun Heo 	}
3466dcd989cbSTejun Heo 
3467dcd989cbSTejun Heo 	spin_unlock(&workqueue_lock);
3468dcd989cbSTejun Heo }
3469dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
3470dcd989cbSTejun Heo 
3471dcd989cbSTejun Heo /**
3472dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
3473dcd989cbSTejun Heo  * @cpu: CPU in question
3474dcd989cbSTejun Heo  * @wq: target workqueue
3475dcd989cbSTejun Heo  *
3476dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
3477dcd989cbSTejun Heo  * no synchronization around this function and the test result is
3478dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
3479dcd989cbSTejun Heo  *
3480dcd989cbSTejun Heo  * RETURNS:
3481dcd989cbSTejun Heo  * %true if congested, %false otherwise.
3482dcd989cbSTejun Heo  */
3483dcd989cbSTejun Heo bool workqueue_congested(unsigned int cpu, struct workqueue_struct *wq)
3484dcd989cbSTejun Heo {
3485dcd989cbSTejun Heo 	struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3486dcd989cbSTejun Heo 
3487dcd989cbSTejun Heo 	return !list_empty(&cwq->delayed_works);
3488dcd989cbSTejun Heo }
3489dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
3490dcd989cbSTejun Heo 
3491dcd989cbSTejun Heo /**
3492dcd989cbSTejun Heo  * work_cpu - return the last known associated cpu for @work
3493dcd989cbSTejun Heo  * @work: the work of interest
3494dcd989cbSTejun Heo  *
3495dcd989cbSTejun Heo  * RETURNS:
3496bdbc5dd7STejun Heo  * CPU number if @work was ever queued.  WORK_CPU_NONE otherwise.
3497dcd989cbSTejun Heo  */
3498dcd989cbSTejun Heo unsigned int work_cpu(struct work_struct *work)
3499dcd989cbSTejun Heo {
3500dcd989cbSTejun Heo 	struct global_cwq *gcwq = get_work_gcwq(work);
3501dcd989cbSTejun Heo 
3502bdbc5dd7STejun Heo 	return gcwq ? gcwq->cpu : WORK_CPU_NONE;
3503dcd989cbSTejun Heo }
3504dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_cpu);
3505dcd989cbSTejun Heo 
3506dcd989cbSTejun Heo /**
3507dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
3508dcd989cbSTejun Heo  * @work: the work to be tested
3509dcd989cbSTejun Heo  *
3510dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
3511dcd989cbSTejun Heo  * synchronization around this function and the test result is
3512dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
3513dcd989cbSTejun Heo  * Especially for reentrant wqs, the pending state might hide the
3514dcd989cbSTejun Heo  * running state.
3515dcd989cbSTejun Heo  *
3516dcd989cbSTejun Heo  * RETURNS:
3517dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
3518dcd989cbSTejun Heo  */
3519dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
3520dcd989cbSTejun Heo {
3521dcd989cbSTejun Heo 	struct global_cwq *gcwq = get_work_gcwq(work);
3522dcd989cbSTejun Heo 	unsigned long flags;
3523dcd989cbSTejun Heo 	unsigned int ret = 0;
3524dcd989cbSTejun Heo 
3525dcd989cbSTejun Heo 	if (!gcwq)
3526dcd989cbSTejun Heo 		return false;
3527dcd989cbSTejun Heo 
3528dcd989cbSTejun Heo 	spin_lock_irqsave(&gcwq->lock, flags);
3529dcd989cbSTejun Heo 
3530dcd989cbSTejun Heo 	if (work_pending(work))
3531dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
3532dcd989cbSTejun Heo 	if (find_worker_executing_work(gcwq, work))
3533dcd989cbSTejun Heo 		ret |= WORK_BUSY_RUNNING;
3534dcd989cbSTejun Heo 
3535dcd989cbSTejun Heo 	spin_unlock_irqrestore(&gcwq->lock, flags);
3536dcd989cbSTejun Heo 
3537dcd989cbSTejun Heo 	return ret;
3538dcd989cbSTejun Heo }
3539dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
3540dcd989cbSTejun Heo 
3541db7bccf4STejun Heo /*
3542db7bccf4STejun Heo  * CPU hotplug.
3543db7bccf4STejun Heo  *
3544e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
3545e22bee78STejun Heo  * are a lot of assumptions on strong associations among work, cwq and
3546e22bee78STejun Heo  * gcwq which make migrating pending and scheduled works very
3547e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
3548e22bee78STejun Heo  * gcwqs serve mix of short, long and very long running works making
3549e22bee78STejun Heo  * blocked draining impractical.
3550e22bee78STejun Heo  *
3551628c78e7STejun Heo  * This is solved by allowing a gcwq to be disassociated from the CPU
3552628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
3553628c78e7STejun Heo  * cpu comes back online.
3554db7bccf4STejun Heo  */
3555db7bccf4STejun Heo 
355660373152STejun Heo /* claim manager positions of all pools */
35578db25e78STejun Heo static void gcwq_claim_management_and_lock(struct global_cwq *gcwq)
355860373152STejun Heo {
355960373152STejun Heo 	struct worker_pool *pool;
356060373152STejun Heo 
356160373152STejun Heo 	for_each_worker_pool(pool, gcwq)
356260373152STejun Heo 		mutex_lock_nested(&pool->manager_mutex, pool - gcwq->pools);
35638db25e78STejun Heo 	spin_lock_irq(&gcwq->lock);
356460373152STejun Heo }
356560373152STejun Heo 
356660373152STejun Heo /* release manager positions */
35678db25e78STejun Heo static void gcwq_release_management_and_unlock(struct global_cwq *gcwq)
356860373152STejun Heo {
356960373152STejun Heo 	struct worker_pool *pool;
357060373152STejun Heo 
35718db25e78STejun Heo 	spin_unlock_irq(&gcwq->lock);
357260373152STejun Heo 	for_each_worker_pool(pool, gcwq)
357360373152STejun Heo 		mutex_unlock(&pool->manager_mutex);
357460373152STejun Heo }
357560373152STejun Heo 
3576628c78e7STejun Heo static void gcwq_unbind_fn(struct work_struct *work)
3577db7bccf4STejun Heo {
3578628c78e7STejun Heo 	struct global_cwq *gcwq = get_gcwq(smp_processor_id());
35794ce62e9eSTejun Heo 	struct worker_pool *pool;
3580db7bccf4STejun Heo 	struct worker *worker;
3581db7bccf4STejun Heo 	struct hlist_node *pos;
3582db7bccf4STejun Heo 	int i;
3583db7bccf4STejun Heo 
3584db7bccf4STejun Heo 	BUG_ON(gcwq->cpu != smp_processor_id());
3585db7bccf4STejun Heo 
35868db25e78STejun Heo 	gcwq_claim_management_and_lock(gcwq);
3587e22bee78STejun Heo 
3588f2d5a0eeSTejun Heo 	/*
3589f2d5a0eeSTejun Heo 	 * We've claimed all manager positions.  Make all workers unbound
3590f2d5a0eeSTejun Heo 	 * and set DISASSOCIATED.  Before this, all workers except for the
3591f2d5a0eeSTejun Heo 	 * ones which are still executing works from before the last CPU
3592f2d5a0eeSTejun Heo 	 * down must be on the cpu.  After this, they may become diasporas.
3593f2d5a0eeSTejun Heo 	 */
359460373152STejun Heo 	for_each_worker_pool(pool, gcwq)
35954ce62e9eSTejun Heo 		list_for_each_entry(worker, &pool->idle_list, entry)
3596403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
3597db7bccf4STejun Heo 
3598db7bccf4STejun Heo 	for_each_busy_worker(worker, i, pos, gcwq)
3599403c821dSTejun Heo 		worker->flags |= WORKER_UNBOUND;
3600db7bccf4STejun Heo 
3601f2d5a0eeSTejun Heo 	gcwq->flags |= GCWQ_DISASSOCIATED;
3602f2d5a0eeSTejun Heo 
36038db25e78STejun Heo 	gcwq_release_management_and_unlock(gcwq);
3604e22bee78STejun Heo 
3605e22bee78STejun Heo 	/*
3606628c78e7STejun Heo 	 * Call schedule() so that we cross rq->lock and thus can guarantee
3607628c78e7STejun Heo 	 * sched callbacks see the %WORKER_UNBOUND flag.  This is necessary
3608628c78e7STejun Heo 	 * as scheduler callbacks may be invoked from other cpus.
3609628c78e7STejun Heo 	 */
3610628c78e7STejun Heo 	schedule();
3611628c78e7STejun Heo 
3612628c78e7STejun Heo 	/*
3613628c78e7STejun Heo 	 * Sched callbacks are disabled now.  Zap nr_running.  After this,
3614628c78e7STejun Heo 	 * nr_running stays zero and need_more_worker() and keep_working()
3615628c78e7STejun Heo 	 * are always true as long as the worklist is not empty.  @gcwq now
3616628c78e7STejun Heo 	 * behaves as unbound (in terms of concurrency management) gcwq
3617628c78e7STejun Heo 	 * which is served by workers tied to the CPU.
3618628c78e7STejun Heo 	 *
3619628c78e7STejun Heo 	 * On return from this function, the current worker would trigger
3620628c78e7STejun Heo 	 * unbound chain execution of pending work items if other workers
3621628c78e7STejun Heo 	 * didn't already.
3622e22bee78STejun Heo 	 */
36234ce62e9eSTejun Heo 	for_each_worker_pool(pool, gcwq)
36244ce62e9eSTejun Heo 		atomic_set(get_pool_nr_running(pool), 0);
3625db7bccf4STejun Heo }
3626db7bccf4STejun Heo 
36278db25e78STejun Heo /*
36288db25e78STejun Heo  * Workqueues should be brought up before normal priority CPU notifiers.
36298db25e78STejun Heo  * This will be registered high priority CPU notifier.
36308db25e78STejun Heo  */
36318db25e78STejun Heo static int __devinit workqueue_cpu_up_callback(struct notifier_block *nfb,
36321da177e4SLinus Torvalds 					       unsigned long action,
36331da177e4SLinus Torvalds 					       void *hcpu)
36341da177e4SLinus Torvalds {
36353af24433SOleg Nesterov 	unsigned int cpu = (unsigned long)hcpu;
3636db7bccf4STejun Heo 	struct global_cwq *gcwq = get_gcwq(cpu);
36374ce62e9eSTejun Heo 	struct worker_pool *pool;
36381da177e4SLinus Torvalds 
36398db25e78STejun Heo 	switch (action & ~CPU_TASKS_FROZEN) {
36403af24433SOleg Nesterov 	case CPU_UP_PREPARE:
36414ce62e9eSTejun Heo 		for_each_worker_pool(pool, gcwq) {
36423ce63377STejun Heo 			struct worker *worker;
36433ce63377STejun Heo 
36443ce63377STejun Heo 			if (pool->nr_workers)
36453ce63377STejun Heo 				continue;
36463ce63377STejun Heo 
36473ce63377STejun Heo 			worker = create_worker(pool);
36483ce63377STejun Heo 			if (!worker)
36493ce63377STejun Heo 				return NOTIFY_BAD;
36503ce63377STejun Heo 
36513ce63377STejun Heo 			spin_lock_irq(&gcwq->lock);
36523ce63377STejun Heo 			start_worker(worker);
36533ce63377STejun Heo 			spin_unlock_irq(&gcwq->lock);
36543af24433SOleg Nesterov 		}
36551da177e4SLinus Torvalds 		break;
36561da177e4SLinus Torvalds 
365765758202STejun Heo 	case CPU_DOWN_FAILED:
365865758202STejun Heo 	case CPU_ONLINE:
36598db25e78STejun Heo 		gcwq_claim_management_and_lock(gcwq);
36608db25e78STejun Heo 		gcwq->flags &= ~GCWQ_DISASSOCIATED;
36618db25e78STejun Heo 		rebind_workers(gcwq);
36628db25e78STejun Heo 		gcwq_release_management_and_unlock(gcwq);
36638db25e78STejun Heo 		break;
366465758202STejun Heo 	}
366565758202STejun Heo 	return NOTIFY_OK;
366665758202STejun Heo }
366765758202STejun Heo 
366865758202STejun Heo /*
366965758202STejun Heo  * Workqueues should be brought down after normal priority CPU notifiers.
367065758202STejun Heo  * This will be registered as low priority CPU notifier.
367165758202STejun Heo  */
367265758202STejun Heo static int __devinit workqueue_cpu_down_callback(struct notifier_block *nfb,
367365758202STejun Heo 						 unsigned long action,
367465758202STejun Heo 						 void *hcpu)
367565758202STejun Heo {
36768db25e78STejun Heo 	unsigned int cpu = (unsigned long)hcpu;
36778db25e78STejun Heo 	struct work_struct unbind_work;
36788db25e78STejun Heo 
367965758202STejun Heo 	switch (action & ~CPU_TASKS_FROZEN) {
368065758202STejun Heo 	case CPU_DOWN_PREPARE:
36818db25e78STejun Heo 		/* unbinding should happen on the local CPU */
36828db25e78STejun Heo 		INIT_WORK_ONSTACK(&unbind_work, gcwq_unbind_fn);
3683*7635d2fdSJoonsoo Kim 		queue_work_on(cpu, system_highpri_wq, &unbind_work);
36848db25e78STejun Heo 		flush_work(&unbind_work);
36858db25e78STejun Heo 		break;
368665758202STejun Heo 	}
368765758202STejun Heo 	return NOTIFY_OK;
368865758202STejun Heo }
368965758202STejun Heo 
36902d3854a3SRusty Russell #ifdef CONFIG_SMP
36918ccad40dSRusty Russell 
36922d3854a3SRusty Russell struct work_for_cpu {
36936b44003eSAndrew Morton 	struct completion completion;
36942d3854a3SRusty Russell 	long (*fn)(void *);
36952d3854a3SRusty Russell 	void *arg;
36962d3854a3SRusty Russell 	long ret;
36972d3854a3SRusty Russell };
36982d3854a3SRusty Russell 
36996b44003eSAndrew Morton static int do_work_for_cpu(void *_wfc)
37002d3854a3SRusty Russell {
37016b44003eSAndrew Morton 	struct work_for_cpu *wfc = _wfc;
37022d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
37036b44003eSAndrew Morton 	complete(&wfc->completion);
37046b44003eSAndrew Morton 	return 0;
37052d3854a3SRusty Russell }
37062d3854a3SRusty Russell 
37072d3854a3SRusty Russell /**
37082d3854a3SRusty Russell  * work_on_cpu - run a function in user context on a particular cpu
37092d3854a3SRusty Russell  * @cpu: the cpu to run on
37102d3854a3SRusty Russell  * @fn: the function to run
37112d3854a3SRusty Russell  * @arg: the function arg
37122d3854a3SRusty Russell  *
371331ad9081SRusty Russell  * This will return the value @fn returns.
371431ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
37156b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
37162d3854a3SRusty Russell  */
37172d3854a3SRusty Russell long work_on_cpu(unsigned int cpu, long (*fn)(void *), void *arg)
37182d3854a3SRusty Russell {
37196b44003eSAndrew Morton 	struct task_struct *sub_thread;
37206b44003eSAndrew Morton 	struct work_for_cpu wfc = {
37216b44003eSAndrew Morton 		.completion = COMPLETION_INITIALIZER_ONSTACK(wfc.completion),
37226b44003eSAndrew Morton 		.fn = fn,
37236b44003eSAndrew Morton 		.arg = arg,
37246b44003eSAndrew Morton 	};
37252d3854a3SRusty Russell 
37266b44003eSAndrew Morton 	sub_thread = kthread_create(do_work_for_cpu, &wfc, "work_for_cpu");
37276b44003eSAndrew Morton 	if (IS_ERR(sub_thread))
37286b44003eSAndrew Morton 		return PTR_ERR(sub_thread);
37296b44003eSAndrew Morton 	kthread_bind(sub_thread, cpu);
37306b44003eSAndrew Morton 	wake_up_process(sub_thread);
37316b44003eSAndrew Morton 	wait_for_completion(&wfc.completion);
37322d3854a3SRusty Russell 	return wfc.ret;
37332d3854a3SRusty Russell }
37342d3854a3SRusty Russell EXPORT_SYMBOL_GPL(work_on_cpu);
37352d3854a3SRusty Russell #endif /* CONFIG_SMP */
37362d3854a3SRusty Russell 
3737a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
3738e7577c50SRusty Russell 
3739a0a1a5fdSTejun Heo /**
3740a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
3741a0a1a5fdSTejun Heo  *
374258a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
374358a69cb4STejun Heo  * workqueues will queue new works to their frozen_works list instead of
374458a69cb4STejun Heo  * gcwq->worklist.
3745a0a1a5fdSTejun Heo  *
3746a0a1a5fdSTejun Heo  * CONTEXT:
37478b03ae3cSTejun Heo  * Grabs and releases workqueue_lock and gcwq->lock's.
3748a0a1a5fdSTejun Heo  */
3749a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
3750a0a1a5fdSTejun Heo {
3751a0a1a5fdSTejun Heo 	unsigned int cpu;
3752a0a1a5fdSTejun Heo 
3753a0a1a5fdSTejun Heo 	spin_lock(&workqueue_lock);
3754a0a1a5fdSTejun Heo 
3755a0a1a5fdSTejun Heo 	BUG_ON(workqueue_freezing);
3756a0a1a5fdSTejun Heo 	workqueue_freezing = true;
3757a0a1a5fdSTejun Heo 
3758f3421797STejun Heo 	for_each_gcwq_cpu(cpu) {
37598b03ae3cSTejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
3760bdbc5dd7STejun Heo 		struct workqueue_struct *wq;
37618b03ae3cSTejun Heo 
37628b03ae3cSTejun Heo 		spin_lock_irq(&gcwq->lock);
37638b03ae3cSTejun Heo 
3764db7bccf4STejun Heo 		BUG_ON(gcwq->flags & GCWQ_FREEZING);
3765db7bccf4STejun Heo 		gcwq->flags |= GCWQ_FREEZING;
3766db7bccf4STejun Heo 
3767a0a1a5fdSTejun Heo 		list_for_each_entry(wq, &workqueues, list) {
3768a0a1a5fdSTejun Heo 			struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3769a0a1a5fdSTejun Heo 
377058a69cb4STejun Heo 			if (cwq && wq->flags & WQ_FREEZABLE)
3771a0a1a5fdSTejun Heo 				cwq->max_active = 0;
37721da177e4SLinus Torvalds 		}
37738b03ae3cSTejun Heo 
37748b03ae3cSTejun Heo 		spin_unlock_irq(&gcwq->lock);
3775a0a1a5fdSTejun Heo 	}
3776a0a1a5fdSTejun Heo 
3777a0a1a5fdSTejun Heo 	spin_unlock(&workqueue_lock);
3778a0a1a5fdSTejun Heo }
3779a0a1a5fdSTejun Heo 
3780a0a1a5fdSTejun Heo /**
378158a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
3782a0a1a5fdSTejun Heo  *
3783a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
3784a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
3785a0a1a5fdSTejun Heo  *
3786a0a1a5fdSTejun Heo  * CONTEXT:
3787a0a1a5fdSTejun Heo  * Grabs and releases workqueue_lock.
3788a0a1a5fdSTejun Heo  *
3789a0a1a5fdSTejun Heo  * RETURNS:
379058a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
379158a69cb4STejun Heo  * is complete.
3792a0a1a5fdSTejun Heo  */
3793a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
3794a0a1a5fdSTejun Heo {
3795a0a1a5fdSTejun Heo 	unsigned int cpu;
3796a0a1a5fdSTejun Heo 	bool busy = false;
3797a0a1a5fdSTejun Heo 
3798a0a1a5fdSTejun Heo 	spin_lock(&workqueue_lock);
3799a0a1a5fdSTejun Heo 
3800a0a1a5fdSTejun Heo 	BUG_ON(!workqueue_freezing);
3801a0a1a5fdSTejun Heo 
3802f3421797STejun Heo 	for_each_gcwq_cpu(cpu) {
3803bdbc5dd7STejun Heo 		struct workqueue_struct *wq;
3804a0a1a5fdSTejun Heo 		/*
3805a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
3806a0a1a5fdSTejun Heo 		 * to peek without lock.
3807a0a1a5fdSTejun Heo 		 */
3808a0a1a5fdSTejun Heo 		list_for_each_entry(wq, &workqueues, list) {
3809a0a1a5fdSTejun Heo 			struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3810a0a1a5fdSTejun Heo 
381158a69cb4STejun Heo 			if (!cwq || !(wq->flags & WQ_FREEZABLE))
3812a0a1a5fdSTejun Heo 				continue;
3813a0a1a5fdSTejun Heo 
3814a0a1a5fdSTejun Heo 			BUG_ON(cwq->nr_active < 0);
3815a0a1a5fdSTejun Heo 			if (cwq->nr_active) {
3816a0a1a5fdSTejun Heo 				busy = true;
3817a0a1a5fdSTejun Heo 				goto out_unlock;
3818a0a1a5fdSTejun Heo 			}
3819a0a1a5fdSTejun Heo 		}
3820a0a1a5fdSTejun Heo 	}
3821a0a1a5fdSTejun Heo out_unlock:
3822a0a1a5fdSTejun Heo 	spin_unlock(&workqueue_lock);
3823a0a1a5fdSTejun Heo 	return busy;
3824a0a1a5fdSTejun Heo }
3825a0a1a5fdSTejun Heo 
3826a0a1a5fdSTejun Heo /**
3827a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
3828a0a1a5fdSTejun Heo  *
3829a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
38307e11629dSTejun Heo  * frozen works are transferred to their respective gcwq worklists.
3831a0a1a5fdSTejun Heo  *
3832a0a1a5fdSTejun Heo  * CONTEXT:
38338b03ae3cSTejun Heo  * Grabs and releases workqueue_lock and gcwq->lock's.
3834a0a1a5fdSTejun Heo  */
3835a0a1a5fdSTejun Heo void thaw_workqueues(void)
3836a0a1a5fdSTejun Heo {
3837a0a1a5fdSTejun Heo 	unsigned int cpu;
3838a0a1a5fdSTejun Heo 
3839a0a1a5fdSTejun Heo 	spin_lock(&workqueue_lock);
3840a0a1a5fdSTejun Heo 
3841a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
3842a0a1a5fdSTejun Heo 		goto out_unlock;
3843a0a1a5fdSTejun Heo 
3844f3421797STejun Heo 	for_each_gcwq_cpu(cpu) {
38458b03ae3cSTejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
38464ce62e9eSTejun Heo 		struct worker_pool *pool;
3847bdbc5dd7STejun Heo 		struct workqueue_struct *wq;
38488b03ae3cSTejun Heo 
38498b03ae3cSTejun Heo 		spin_lock_irq(&gcwq->lock);
38508b03ae3cSTejun Heo 
3851db7bccf4STejun Heo 		BUG_ON(!(gcwq->flags & GCWQ_FREEZING));
3852db7bccf4STejun Heo 		gcwq->flags &= ~GCWQ_FREEZING;
3853db7bccf4STejun Heo 
3854a0a1a5fdSTejun Heo 		list_for_each_entry(wq, &workqueues, list) {
3855a0a1a5fdSTejun Heo 			struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3856a0a1a5fdSTejun Heo 
385758a69cb4STejun Heo 			if (!cwq || !(wq->flags & WQ_FREEZABLE))
3858a0a1a5fdSTejun Heo 				continue;
3859a0a1a5fdSTejun Heo 
3860a0a1a5fdSTejun Heo 			/* restore max_active and repopulate worklist */
3861a0a1a5fdSTejun Heo 			cwq->max_active = wq->saved_max_active;
3862a0a1a5fdSTejun Heo 
3863a0a1a5fdSTejun Heo 			while (!list_empty(&cwq->delayed_works) &&
3864a0a1a5fdSTejun Heo 			       cwq->nr_active < cwq->max_active)
3865a0a1a5fdSTejun Heo 				cwq_activate_first_delayed(cwq);
3866a0a1a5fdSTejun Heo 		}
38678b03ae3cSTejun Heo 
38684ce62e9eSTejun Heo 		for_each_worker_pool(pool, gcwq)
38694ce62e9eSTejun Heo 			wake_up_worker(pool);
3870e22bee78STejun Heo 
38718b03ae3cSTejun Heo 		spin_unlock_irq(&gcwq->lock);
3872a0a1a5fdSTejun Heo 	}
3873a0a1a5fdSTejun Heo 
3874a0a1a5fdSTejun Heo 	workqueue_freezing = false;
3875a0a1a5fdSTejun Heo out_unlock:
3876a0a1a5fdSTejun Heo 	spin_unlock(&workqueue_lock);
3877a0a1a5fdSTejun Heo }
3878a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
3879a0a1a5fdSTejun Heo 
38806ee0578bSSuresh Siddha static int __init init_workqueues(void)
38811da177e4SLinus Torvalds {
3882c34056a3STejun Heo 	unsigned int cpu;
3883c8e55f36STejun Heo 	int i;
3884c34056a3STejun Heo 
3885b5490077STejun Heo 	/* make sure we have enough bits for OFFQ CPU number */
3886b5490077STejun Heo 	BUILD_BUG_ON((1LU << (BITS_PER_LONG - WORK_OFFQ_CPU_SHIFT)) <
3887b5490077STejun Heo 		     WORK_CPU_LAST);
3888b5490077STejun Heo 
388965758202STejun Heo 	cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
389065758202STejun Heo 	cpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
38918b03ae3cSTejun Heo 
38928b03ae3cSTejun Heo 	/* initialize gcwqs */
3893f3421797STejun Heo 	for_each_gcwq_cpu(cpu) {
38948b03ae3cSTejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
38954ce62e9eSTejun Heo 		struct worker_pool *pool;
38968b03ae3cSTejun Heo 
38978b03ae3cSTejun Heo 		spin_lock_init(&gcwq->lock);
38988b03ae3cSTejun Heo 		gcwq->cpu = cpu;
3899f3421797STejun Heo 		gcwq->flags |= GCWQ_DISASSOCIATED;
39008b03ae3cSTejun Heo 
3901c8e55f36STejun Heo 		for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)
3902c8e55f36STejun Heo 			INIT_HLIST_HEAD(&gcwq->busy_hash[i]);
3903c8e55f36STejun Heo 
39044ce62e9eSTejun Heo 		for_each_worker_pool(pool, gcwq) {
39054ce62e9eSTejun Heo 			pool->gcwq = gcwq;
39064ce62e9eSTejun Heo 			INIT_LIST_HEAD(&pool->worklist);
39074ce62e9eSTejun Heo 			INIT_LIST_HEAD(&pool->idle_list);
3908e22bee78STejun Heo 
39094ce62e9eSTejun Heo 			init_timer_deferrable(&pool->idle_timer);
39104ce62e9eSTejun Heo 			pool->idle_timer.function = idle_worker_timeout;
39114ce62e9eSTejun Heo 			pool->idle_timer.data = (unsigned long)pool;
3912e22bee78STejun Heo 
39134ce62e9eSTejun Heo 			setup_timer(&pool->mayday_timer, gcwq_mayday_timeout,
39144ce62e9eSTejun Heo 				    (unsigned long)pool);
39154ce62e9eSTejun Heo 
391660373152STejun Heo 			mutex_init(&pool->manager_mutex);
39174ce62e9eSTejun Heo 			ida_init(&pool->worker_ida);
39184ce62e9eSTejun Heo 		}
3919db7bccf4STejun Heo 
392025511a47STejun Heo 		init_waitqueue_head(&gcwq->rebind_hold);
39218b03ae3cSTejun Heo 	}
39228b03ae3cSTejun Heo 
3923e22bee78STejun Heo 	/* create the initial worker */
3924f3421797STejun Heo 	for_each_online_gcwq_cpu(cpu) {
3925e22bee78STejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
39264ce62e9eSTejun Heo 		struct worker_pool *pool;
3927e22bee78STejun Heo 
3928477a3c33STejun Heo 		if (cpu != WORK_CPU_UNBOUND)
3929477a3c33STejun Heo 			gcwq->flags &= ~GCWQ_DISASSOCIATED;
39304ce62e9eSTejun Heo 
39314ce62e9eSTejun Heo 		for_each_worker_pool(pool, gcwq) {
39324ce62e9eSTejun Heo 			struct worker *worker;
39334ce62e9eSTejun Heo 
3934bc2ae0f5STejun Heo 			worker = create_worker(pool);
3935e22bee78STejun Heo 			BUG_ON(!worker);
3936e22bee78STejun Heo 			spin_lock_irq(&gcwq->lock);
3937e22bee78STejun Heo 			start_worker(worker);
3938e22bee78STejun Heo 			spin_unlock_irq(&gcwq->lock);
3939e22bee78STejun Heo 		}
39404ce62e9eSTejun Heo 	}
3941e22bee78STejun Heo 
3942d320c038STejun Heo 	system_wq = alloc_workqueue("events", 0, 0);
39431aabe902SJoonsoo Kim 	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
3944d320c038STejun Heo 	system_long_wq = alloc_workqueue("events_long", 0, 0);
3945d320c038STejun Heo 	system_nrt_wq = alloc_workqueue("events_nrt", WQ_NON_REENTRANT, 0);
3946f3421797STejun Heo 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
3947f3421797STejun Heo 					    WQ_UNBOUND_MAX_ACTIVE);
394824d51addSTejun Heo 	system_freezable_wq = alloc_workqueue("events_freezable",
394924d51addSTejun Heo 					      WQ_FREEZABLE, 0);
395062d3c543SAlan Stern 	system_nrt_freezable_wq = alloc_workqueue("events_nrt_freezable",
395162d3c543SAlan Stern 			WQ_NON_REENTRANT | WQ_FREEZABLE, 0);
39521aabe902SJoonsoo Kim 	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
39531aabe902SJoonsoo Kim 	       !system_nrt_wq || !system_unbound_wq || !system_freezable_wq ||
395462d3c543SAlan Stern 	       !system_nrt_freezable_wq);
39556ee0578bSSuresh Siddha 	return 0;
39561da177e4SLinus Torvalds }
39576ee0578bSSuresh Siddha early_initcall(init_workqueues);
3958