xref: /linux-6.15/kernel/workqueue.c (revision e0aecdd8)
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;
272d320c038STejun Heo EXPORT_SYMBOL_GPL(system_wq);
273044c782cSValentin Ilie struct workqueue_struct *system_highpri_wq __read_mostly;
2741aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
275044c782cSValentin Ilie struct workqueue_struct *system_long_wq __read_mostly;
276d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
277044c782cSValentin Ilie struct workqueue_struct *system_unbound_wq __read_mostly;
278f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
279044c782cSValentin Ilie struct workqueue_struct *system_freezable_wq __read_mostly;
28024d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
281d320c038STejun Heo 
28297bd2347STejun Heo #define CREATE_TRACE_POINTS
28397bd2347STejun Heo #include <trace/events/workqueue.h>
28497bd2347STejun Heo 
2854ce62e9eSTejun Heo #define for_each_worker_pool(pool, gcwq)				\
2863270476aSTejun Heo 	for ((pool) = &(gcwq)->pools[0];				\
2873270476aSTejun Heo 	     (pool) < &(gcwq)->pools[NR_WORKER_POOLS]; (pool)++)
2884ce62e9eSTejun Heo 
289db7bccf4STejun Heo #define for_each_busy_worker(worker, i, pos, gcwq)			\
290db7bccf4STejun Heo 	for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)			\
291db7bccf4STejun Heo 		hlist_for_each_entry(worker, pos, &gcwq->busy_hash[i], hentry)
292db7bccf4STejun Heo 
293f3421797STejun Heo static inline int __next_gcwq_cpu(int cpu, const struct cpumask *mask,
294f3421797STejun Heo 				  unsigned int sw)
295f3421797STejun Heo {
296f3421797STejun Heo 	if (cpu < nr_cpu_ids) {
297f3421797STejun Heo 		if (sw & 1) {
298f3421797STejun Heo 			cpu = cpumask_next(cpu, mask);
299f3421797STejun Heo 			if (cpu < nr_cpu_ids)
300f3421797STejun Heo 				return cpu;
301f3421797STejun Heo 		}
302f3421797STejun Heo 		if (sw & 2)
303f3421797STejun Heo 			return WORK_CPU_UNBOUND;
304f3421797STejun Heo 	}
305f3421797STejun Heo 	return WORK_CPU_NONE;
306f3421797STejun Heo }
307f3421797STejun Heo 
308f3421797STejun Heo static inline int __next_wq_cpu(int cpu, const struct cpumask *mask,
309f3421797STejun Heo 				struct workqueue_struct *wq)
310f3421797STejun Heo {
311f3421797STejun Heo 	return __next_gcwq_cpu(cpu, mask, !(wq->flags & WQ_UNBOUND) ? 1 : 2);
312f3421797STejun Heo }
313f3421797STejun Heo 
31409884951STejun Heo /*
31509884951STejun Heo  * CPU iterators
31609884951STejun Heo  *
31709884951STejun Heo  * An extra gcwq is defined for an invalid cpu number
31809884951STejun Heo  * (WORK_CPU_UNBOUND) to host workqueues which are not bound to any
31909884951STejun Heo  * specific CPU.  The following iterators are similar to
32009884951STejun Heo  * for_each_*_cpu() iterators but also considers the unbound gcwq.
32109884951STejun Heo  *
32209884951STejun Heo  * for_each_gcwq_cpu()		: possible CPUs + WORK_CPU_UNBOUND
32309884951STejun Heo  * for_each_online_gcwq_cpu()	: online CPUs + WORK_CPU_UNBOUND
32409884951STejun Heo  * for_each_cwq_cpu()		: possible CPUs for bound workqueues,
32509884951STejun Heo  *				  WORK_CPU_UNBOUND for unbound workqueues
32609884951STejun Heo  */
327f3421797STejun Heo #define for_each_gcwq_cpu(cpu)						\
328f3421797STejun Heo 	for ((cpu) = __next_gcwq_cpu(-1, cpu_possible_mask, 3);		\
329f3421797STejun Heo 	     (cpu) < WORK_CPU_NONE;					\
330f3421797STejun Heo 	     (cpu) = __next_gcwq_cpu((cpu), cpu_possible_mask, 3))
331f3421797STejun Heo 
332f3421797STejun Heo #define for_each_online_gcwq_cpu(cpu)					\
333f3421797STejun Heo 	for ((cpu) = __next_gcwq_cpu(-1, cpu_online_mask, 3);		\
334f3421797STejun Heo 	     (cpu) < WORK_CPU_NONE;					\
335f3421797STejun Heo 	     (cpu) = __next_gcwq_cpu((cpu), cpu_online_mask, 3))
336f3421797STejun Heo 
337f3421797STejun Heo #define for_each_cwq_cpu(cpu, wq)					\
338f3421797STejun Heo 	for ((cpu) = __next_wq_cpu(-1, cpu_possible_mask, (wq));	\
339f3421797STejun Heo 	     (cpu) < WORK_CPU_NONE;					\
340f3421797STejun Heo 	     (cpu) = __next_wq_cpu((cpu), cpu_possible_mask, (wq)))
341f3421797STejun Heo 
342dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
343dc186ad7SThomas Gleixner 
344dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr;
345dc186ad7SThomas Gleixner 
34699777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
34799777288SStanislaw Gruszka {
34899777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
34999777288SStanislaw Gruszka }
35099777288SStanislaw Gruszka 
351dc186ad7SThomas Gleixner /*
352dc186ad7SThomas Gleixner  * fixup_init is called when:
353dc186ad7SThomas Gleixner  * - an active object is initialized
354dc186ad7SThomas Gleixner  */
355dc186ad7SThomas Gleixner static int work_fixup_init(void *addr, enum debug_obj_state state)
356dc186ad7SThomas Gleixner {
357dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
358dc186ad7SThomas Gleixner 
359dc186ad7SThomas Gleixner 	switch (state) {
360dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
361dc186ad7SThomas Gleixner 		cancel_work_sync(work);
362dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
363dc186ad7SThomas Gleixner 		return 1;
364dc186ad7SThomas Gleixner 	default:
365dc186ad7SThomas Gleixner 		return 0;
366dc186ad7SThomas Gleixner 	}
367dc186ad7SThomas Gleixner }
368dc186ad7SThomas Gleixner 
369dc186ad7SThomas Gleixner /*
370dc186ad7SThomas Gleixner  * fixup_activate is called when:
371dc186ad7SThomas Gleixner  * - an active object is activated
372dc186ad7SThomas Gleixner  * - an unknown object is activated (might be a statically initialized object)
373dc186ad7SThomas Gleixner  */
374dc186ad7SThomas Gleixner static int work_fixup_activate(void *addr, enum debug_obj_state state)
375dc186ad7SThomas Gleixner {
376dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
377dc186ad7SThomas Gleixner 
378dc186ad7SThomas Gleixner 	switch (state) {
379dc186ad7SThomas Gleixner 
380dc186ad7SThomas Gleixner 	case ODEBUG_STATE_NOTAVAILABLE:
381dc186ad7SThomas Gleixner 		/*
382dc186ad7SThomas Gleixner 		 * This is not really a fixup. The work struct was
383dc186ad7SThomas Gleixner 		 * statically initialized. We just make sure that it
384dc186ad7SThomas Gleixner 		 * is tracked in the object tracker.
385dc186ad7SThomas Gleixner 		 */
38622df02bbSTejun Heo 		if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
387dc186ad7SThomas Gleixner 			debug_object_init(work, &work_debug_descr);
388dc186ad7SThomas Gleixner 			debug_object_activate(work, &work_debug_descr);
389dc186ad7SThomas Gleixner 			return 0;
390dc186ad7SThomas Gleixner 		}
391dc186ad7SThomas Gleixner 		WARN_ON_ONCE(1);
392dc186ad7SThomas Gleixner 		return 0;
393dc186ad7SThomas Gleixner 
394dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
395dc186ad7SThomas Gleixner 		WARN_ON(1);
396dc186ad7SThomas Gleixner 
397dc186ad7SThomas Gleixner 	default:
398dc186ad7SThomas Gleixner 		return 0;
399dc186ad7SThomas Gleixner 	}
400dc186ad7SThomas Gleixner }
401dc186ad7SThomas Gleixner 
402dc186ad7SThomas Gleixner /*
403dc186ad7SThomas Gleixner  * fixup_free is called when:
404dc186ad7SThomas Gleixner  * - an active object is freed
405dc186ad7SThomas Gleixner  */
406dc186ad7SThomas Gleixner static int work_fixup_free(void *addr, enum debug_obj_state state)
407dc186ad7SThomas Gleixner {
408dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
409dc186ad7SThomas Gleixner 
410dc186ad7SThomas Gleixner 	switch (state) {
411dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
412dc186ad7SThomas Gleixner 		cancel_work_sync(work);
413dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
414dc186ad7SThomas Gleixner 		return 1;
415dc186ad7SThomas Gleixner 	default:
416dc186ad7SThomas Gleixner 		return 0;
417dc186ad7SThomas Gleixner 	}
418dc186ad7SThomas Gleixner }
419dc186ad7SThomas Gleixner 
420dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr = {
421dc186ad7SThomas Gleixner 	.name		= "work_struct",
42299777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
423dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
424dc186ad7SThomas Gleixner 	.fixup_activate	= work_fixup_activate,
425dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
426dc186ad7SThomas Gleixner };
427dc186ad7SThomas Gleixner 
428dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
429dc186ad7SThomas Gleixner {
430dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
431dc186ad7SThomas Gleixner }
432dc186ad7SThomas Gleixner 
433dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
434dc186ad7SThomas Gleixner {
435dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
436dc186ad7SThomas Gleixner }
437dc186ad7SThomas Gleixner 
438dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
439dc186ad7SThomas Gleixner {
440dc186ad7SThomas Gleixner 	if (onstack)
441dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
442dc186ad7SThomas Gleixner 	else
443dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
444dc186ad7SThomas Gleixner }
445dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
446dc186ad7SThomas Gleixner 
447dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
448dc186ad7SThomas Gleixner {
449dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
450dc186ad7SThomas Gleixner }
451dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
452dc186ad7SThomas Gleixner 
453dc186ad7SThomas Gleixner #else
454dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
455dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
456dc186ad7SThomas Gleixner #endif
457dc186ad7SThomas Gleixner 
45895402b38SGautham R Shenoy /* Serializes the accesses to the list of workqueues. */
45995402b38SGautham R Shenoy static DEFINE_SPINLOCK(workqueue_lock);
4601da177e4SLinus Torvalds static LIST_HEAD(workqueues);
461a0a1a5fdSTejun Heo static bool workqueue_freezing;		/* W: have wqs started freezing? */
4621da177e4SLinus Torvalds 
46314441960SOleg Nesterov /*
464e22bee78STejun Heo  * The almighty global cpu workqueues.  nr_running is the only field
465e22bee78STejun Heo  * which is expected to be used frequently by other cpus via
466e22bee78STejun Heo  * try_to_wake_up().  Put it in a separate cacheline.
46714441960SOleg Nesterov  */
4688b03ae3cSTejun Heo static DEFINE_PER_CPU(struct global_cwq, global_cwq);
4694ce62e9eSTejun Heo static DEFINE_PER_CPU_SHARED_ALIGNED(atomic_t, pool_nr_running[NR_WORKER_POOLS]);
470f756d5e2SNathan Lynch 
471f3421797STejun Heo /*
472f3421797STejun Heo  * Global cpu workqueue and nr_running counter for unbound gcwq.  The
473f3421797STejun Heo  * gcwq is always online, has GCWQ_DISASSOCIATED set, and all its
474f3421797STejun Heo  * workers have WORKER_UNBOUND set.
475f3421797STejun Heo  */
476f3421797STejun Heo static struct global_cwq unbound_global_cwq;
4774ce62e9eSTejun Heo static atomic_t unbound_pool_nr_running[NR_WORKER_POOLS] = {
4784ce62e9eSTejun Heo 	[0 ... NR_WORKER_POOLS - 1]	= ATOMIC_INIT(0),	/* always 0 */
4794ce62e9eSTejun Heo };
480f3421797STejun Heo 
481c34056a3STejun Heo static int worker_thread(void *__worker);
4821da177e4SLinus Torvalds 
4833270476aSTejun Heo static int worker_pool_pri(struct worker_pool *pool)
4843270476aSTejun Heo {
4853270476aSTejun Heo 	return pool - pool->gcwq->pools;
4863270476aSTejun Heo }
4873270476aSTejun Heo 
4888b03ae3cSTejun Heo static struct global_cwq *get_gcwq(unsigned int cpu)
4891da177e4SLinus Torvalds {
490f3421797STejun Heo 	if (cpu != WORK_CPU_UNBOUND)
4918b03ae3cSTejun Heo 		return &per_cpu(global_cwq, cpu);
492f3421797STejun Heo 	else
493f3421797STejun Heo 		return &unbound_global_cwq;
4941da177e4SLinus Torvalds }
4951da177e4SLinus Torvalds 
49663d95a91STejun Heo static atomic_t *get_pool_nr_running(struct worker_pool *pool)
497b1f4ec17SOleg Nesterov {
49863d95a91STejun Heo 	int cpu = pool->gcwq->cpu;
4993270476aSTejun Heo 	int idx = worker_pool_pri(pool);
50063d95a91STejun Heo 
501f3421797STejun Heo 	if (cpu != WORK_CPU_UNBOUND)
5024ce62e9eSTejun Heo 		return &per_cpu(pool_nr_running, cpu)[idx];
503f3421797STejun Heo 	else
5044ce62e9eSTejun Heo 		return &unbound_pool_nr_running[idx];
505b1f4ec17SOleg Nesterov }
506b1f4ec17SOleg Nesterov 
5074690c4abSTejun Heo static struct cpu_workqueue_struct *get_cwq(unsigned int cpu,
5084690c4abSTejun Heo 					    struct workqueue_struct *wq)
509a848e3b6SOleg Nesterov {
510f3421797STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
511e06ffa1eSLai Jiangshan 		if (likely(cpu < nr_cpu_ids))
512bdbc5dd7STejun Heo 			return per_cpu_ptr(wq->cpu_wq.pcpu, cpu);
513f3421797STejun Heo 	} else if (likely(cpu == WORK_CPU_UNBOUND))
514f3421797STejun Heo 		return wq->cpu_wq.single;
515f3421797STejun Heo 	return NULL;
516f3421797STejun Heo }
517a848e3b6SOleg Nesterov 
51873f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
51973f53c4aSTejun Heo {
52073f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
52173f53c4aSTejun Heo }
52273f53c4aSTejun Heo 
52373f53c4aSTejun Heo static int get_work_color(struct work_struct *work)
52473f53c4aSTejun Heo {
52573f53c4aSTejun Heo 	return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
52673f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
52773f53c4aSTejun Heo }
52873f53c4aSTejun Heo 
52973f53c4aSTejun Heo static int work_next_color(int color)
53073f53c4aSTejun Heo {
53173f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
5321da177e4SLinus Torvalds }
5331da177e4SLinus Torvalds 
5344594bf15SDavid Howells /*
535b5490077STejun Heo  * While queued, %WORK_STRUCT_CWQ is set and non flag bits of a work's data
536b5490077STejun Heo  * contain the pointer to the queued cwq.  Once execution starts, the flag
537b5490077STejun Heo  * is cleared and the high bits contain OFFQ flags and CPU number.
5387a22ad75STejun Heo  *
539bbb68dfaSTejun Heo  * set_work_cwq(), set_work_cpu_and_clear_pending(), mark_work_canceling()
540bbb68dfaSTejun Heo  * and clear_work_data() can be used to set the cwq, cpu or clear
541bbb68dfaSTejun Heo  * work->data.  These functions should only be called while the work is
542bbb68dfaSTejun Heo  * owned - ie. while the PENDING bit is set.
5437a22ad75STejun Heo  *
544bbb68dfaSTejun Heo  * get_work_[g]cwq() can be used to obtain the gcwq or cwq corresponding to
545bbb68dfaSTejun Heo  * a work.  gcwq is available once the work has been queued anywhere after
546bbb68dfaSTejun Heo  * initialization until it is sync canceled.  cwq is available only while
547bbb68dfaSTejun Heo  * the work item is queued.
548bbb68dfaSTejun Heo  *
549bbb68dfaSTejun Heo  * %WORK_OFFQ_CANCELING is used to mark a work item which is being
550bbb68dfaSTejun Heo  * canceled.  While being canceled, a work item may have its PENDING set
551bbb68dfaSTejun Heo  * but stay off timer and worklist for arbitrarily long and nobody should
552bbb68dfaSTejun Heo  * try to steal the PENDING bit.
5534594bf15SDavid Howells  */
5547a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
5557a22ad75STejun Heo 				 unsigned long flags)
5567a22ad75STejun Heo {
5577a22ad75STejun Heo 	BUG_ON(!work_pending(work));
5587a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
5597a22ad75STejun Heo }
5607a22ad75STejun Heo 
5617a22ad75STejun Heo static void set_work_cwq(struct work_struct *work,
5624690c4abSTejun Heo 			 struct cpu_workqueue_struct *cwq,
5634690c4abSTejun Heo 			 unsigned long extra_flags)
564365970a1SDavid Howells {
5657a22ad75STejun Heo 	set_work_data(work, (unsigned long)cwq,
566e120153dSTejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_CWQ | extra_flags);
567365970a1SDavid Howells }
568365970a1SDavid Howells 
5698930cabaSTejun Heo static void set_work_cpu_and_clear_pending(struct work_struct *work,
5708930cabaSTejun Heo 					   unsigned int cpu)
5714d707b9fSOleg Nesterov {
57223657bb1STejun Heo 	/*
57323657bb1STejun Heo 	 * The following wmb is paired with the implied mb in
57423657bb1STejun Heo 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
57523657bb1STejun Heo 	 * here are visible to and precede any updates by the next PENDING
57623657bb1STejun Heo 	 * owner.
57723657bb1STejun Heo 	 */
57823657bb1STejun Heo 	smp_wmb();
579b5490077STejun Heo 	set_work_data(work, (unsigned long)cpu << WORK_OFFQ_CPU_SHIFT, 0);
5804d707b9fSOleg Nesterov }
5814d707b9fSOleg Nesterov 
5827a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
583365970a1SDavid Howells {
58423657bb1STejun Heo 	smp_wmb();	/* see set_work_cpu_and_clear_pending() */
5857a22ad75STejun Heo 	set_work_data(work, WORK_STRUCT_NO_CPU, 0);
5867a22ad75STejun Heo }
5877a22ad75STejun Heo 
5887a22ad75STejun Heo static struct cpu_workqueue_struct *get_work_cwq(struct work_struct *work)
5897a22ad75STejun Heo {
590e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
5917a22ad75STejun Heo 
592e120153dSTejun Heo 	if (data & WORK_STRUCT_CWQ)
593e120153dSTejun Heo 		return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
594e120153dSTejun Heo 	else
595e120153dSTejun Heo 		return NULL;
5967a22ad75STejun Heo }
5977a22ad75STejun Heo 
5987a22ad75STejun Heo static struct global_cwq *get_work_gcwq(struct work_struct *work)
5997a22ad75STejun Heo {
600e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
6017a22ad75STejun Heo 	unsigned int cpu;
6027a22ad75STejun Heo 
603e120153dSTejun Heo 	if (data & WORK_STRUCT_CWQ)
604e120153dSTejun Heo 		return ((struct cpu_workqueue_struct *)
605bd7bdd43STejun Heo 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool->gcwq;
6067a22ad75STejun Heo 
607b5490077STejun Heo 	cpu = data >> WORK_OFFQ_CPU_SHIFT;
608bdbc5dd7STejun Heo 	if (cpu == WORK_CPU_NONE)
6097a22ad75STejun Heo 		return NULL;
6107a22ad75STejun Heo 
611f3421797STejun Heo 	BUG_ON(cpu >= nr_cpu_ids && cpu != WORK_CPU_UNBOUND);
6127a22ad75STejun Heo 	return get_gcwq(cpu);
613365970a1SDavid Howells }
614365970a1SDavid Howells 
615bbb68dfaSTejun Heo static void mark_work_canceling(struct work_struct *work)
616bbb68dfaSTejun Heo {
617bbb68dfaSTejun Heo 	struct global_cwq *gcwq = get_work_gcwq(work);
618bbb68dfaSTejun Heo 	unsigned long cpu = gcwq ? gcwq->cpu : WORK_CPU_NONE;
619bbb68dfaSTejun Heo 
620bbb68dfaSTejun Heo 	set_work_data(work, (cpu << WORK_OFFQ_CPU_SHIFT) | WORK_OFFQ_CANCELING,
621bbb68dfaSTejun Heo 		      WORK_STRUCT_PENDING);
622bbb68dfaSTejun Heo }
623bbb68dfaSTejun Heo 
624bbb68dfaSTejun Heo static bool work_is_canceling(struct work_struct *work)
625bbb68dfaSTejun Heo {
626bbb68dfaSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
627bbb68dfaSTejun Heo 
628bbb68dfaSTejun Heo 	return !(data & WORK_STRUCT_CWQ) && (data & WORK_OFFQ_CANCELING);
629bbb68dfaSTejun Heo }
630bbb68dfaSTejun Heo 
631e22bee78STejun Heo /*
6323270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
6333270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
6343270476aSTejun Heo  * they're being called with gcwq->lock held.
635e22bee78STejun Heo  */
636e22bee78STejun Heo 
63763d95a91STejun Heo static bool __need_more_worker(struct worker_pool *pool)
638649027d7STejun Heo {
6393270476aSTejun Heo 	return !atomic_read(get_pool_nr_running(pool));
640649027d7STejun Heo }
641649027d7STejun Heo 
642e22bee78STejun Heo /*
643e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
644e22bee78STejun Heo  * running workers.
645974271c4STejun Heo  *
646974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
647974271c4STejun Heo  * function will always return %true for unbound gcwq as long as the
648974271c4STejun Heo  * worklist isn't empty.
649e22bee78STejun Heo  */
65063d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
651e22bee78STejun Heo {
65263d95a91STejun Heo 	return !list_empty(&pool->worklist) && __need_more_worker(pool);
653e22bee78STejun Heo }
654e22bee78STejun Heo 
655e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
65663d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
657e22bee78STejun Heo {
65863d95a91STejun Heo 	return pool->nr_idle;
659e22bee78STejun Heo }
660e22bee78STejun Heo 
661e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
66263d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
663e22bee78STejun Heo {
66463d95a91STejun Heo 	atomic_t *nr_running = get_pool_nr_running(pool);
665e22bee78STejun Heo 
6663270476aSTejun Heo 	return !list_empty(&pool->worklist) && atomic_read(nr_running) <= 1;
667e22bee78STejun Heo }
668e22bee78STejun Heo 
669e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
67063d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
671e22bee78STejun Heo {
67263d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
673e22bee78STejun Heo }
674e22bee78STejun Heo 
675e22bee78STejun Heo /* Do I need to be the manager? */
67663d95a91STejun Heo static bool need_to_manage_workers(struct worker_pool *pool)
677e22bee78STejun Heo {
67863d95a91STejun Heo 	return need_to_create_worker(pool) ||
67911ebea50STejun Heo 		(pool->flags & POOL_MANAGE_WORKERS);
680e22bee78STejun Heo }
681e22bee78STejun Heo 
682e22bee78STejun Heo /* Do we have too many workers and should some go away? */
68363d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
684e22bee78STejun Heo {
68560373152STejun Heo 	bool managing = mutex_is_locked(&pool->manager_mutex);
68663d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
68763d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
688e22bee78STejun Heo 
689e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
690e22bee78STejun Heo }
691e22bee78STejun Heo 
692e22bee78STejun Heo /*
693e22bee78STejun Heo  * Wake up functions.
694e22bee78STejun Heo  */
695e22bee78STejun Heo 
6967e11629dSTejun Heo /* Return the first worker.  Safe with preemption disabled */
69763d95a91STejun Heo static struct worker *first_worker(struct worker_pool *pool)
6987e11629dSTejun Heo {
69963d95a91STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
7007e11629dSTejun Heo 		return NULL;
7017e11629dSTejun Heo 
70263d95a91STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
7037e11629dSTejun Heo }
7047e11629dSTejun Heo 
7057e11629dSTejun Heo /**
7067e11629dSTejun Heo  * wake_up_worker - wake up an idle worker
70763d95a91STejun Heo  * @pool: worker pool to wake worker from
7087e11629dSTejun Heo  *
70963d95a91STejun Heo  * Wake up the first idle worker of @pool.
7107e11629dSTejun Heo  *
7117e11629dSTejun Heo  * CONTEXT:
7127e11629dSTejun Heo  * spin_lock_irq(gcwq->lock).
7137e11629dSTejun Heo  */
71463d95a91STejun Heo static void wake_up_worker(struct worker_pool *pool)
7157e11629dSTejun Heo {
71663d95a91STejun Heo 	struct worker *worker = first_worker(pool);
7177e11629dSTejun Heo 
7187e11629dSTejun Heo 	if (likely(worker))
7197e11629dSTejun Heo 		wake_up_process(worker->task);
7207e11629dSTejun Heo }
7217e11629dSTejun Heo 
7224690c4abSTejun Heo /**
723e22bee78STejun Heo  * wq_worker_waking_up - a worker is waking up
724e22bee78STejun Heo  * @task: task waking up
725e22bee78STejun Heo  * @cpu: CPU @task is waking up to
726e22bee78STejun Heo  *
727e22bee78STejun Heo  * This function is called during try_to_wake_up() when a worker is
728e22bee78STejun Heo  * being awoken.
729e22bee78STejun Heo  *
730e22bee78STejun Heo  * CONTEXT:
731e22bee78STejun Heo  * spin_lock_irq(rq->lock)
732e22bee78STejun Heo  */
733e22bee78STejun Heo void wq_worker_waking_up(struct task_struct *task, unsigned int cpu)
734e22bee78STejun Heo {
735e22bee78STejun Heo 	struct worker *worker = kthread_data(task);
736e22bee78STejun Heo 
7372d64672eSSteven Rostedt 	if (!(worker->flags & WORKER_NOT_RUNNING))
73863d95a91STejun Heo 		atomic_inc(get_pool_nr_running(worker->pool));
739e22bee78STejun Heo }
740e22bee78STejun Heo 
741e22bee78STejun Heo /**
742e22bee78STejun Heo  * wq_worker_sleeping - a worker is going to sleep
743e22bee78STejun Heo  * @task: task going to sleep
744e22bee78STejun Heo  * @cpu: CPU in question, must be the current CPU number
745e22bee78STejun Heo  *
746e22bee78STejun Heo  * This function is called during schedule() when a busy worker is
747e22bee78STejun Heo  * going to sleep.  Worker on the same cpu can be woken up by
748e22bee78STejun Heo  * returning pointer to its task.
749e22bee78STejun Heo  *
750e22bee78STejun Heo  * CONTEXT:
751e22bee78STejun Heo  * spin_lock_irq(rq->lock)
752e22bee78STejun Heo  *
753e22bee78STejun Heo  * RETURNS:
754e22bee78STejun Heo  * Worker task on @cpu to wake up, %NULL if none.
755e22bee78STejun Heo  */
756e22bee78STejun Heo struct task_struct *wq_worker_sleeping(struct task_struct *task,
757e22bee78STejun Heo 				       unsigned int cpu)
758e22bee78STejun Heo {
759e22bee78STejun Heo 	struct worker *worker = kthread_data(task), *to_wakeup = NULL;
760bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
76163d95a91STejun Heo 	atomic_t *nr_running = get_pool_nr_running(pool);
762e22bee78STejun Heo 
7632d64672eSSteven Rostedt 	if (worker->flags & WORKER_NOT_RUNNING)
764e22bee78STejun Heo 		return NULL;
765e22bee78STejun Heo 
766e22bee78STejun Heo 	/* this can only happen on the local cpu */
767e22bee78STejun Heo 	BUG_ON(cpu != raw_smp_processor_id());
768e22bee78STejun Heo 
769e22bee78STejun Heo 	/*
770e22bee78STejun Heo 	 * The counterpart of the following dec_and_test, implied mb,
771e22bee78STejun Heo 	 * worklist not empty test sequence is in insert_work().
772e22bee78STejun Heo 	 * Please read comment there.
773e22bee78STejun Heo 	 *
774628c78e7STejun Heo 	 * NOT_RUNNING is clear.  This means that we're bound to and
775628c78e7STejun Heo 	 * running on the local cpu w/ rq lock held and preemption
776628c78e7STejun Heo 	 * disabled, which in turn means that none else could be
777628c78e7STejun Heo 	 * manipulating idle_list, so dereferencing idle_list without gcwq
778628c78e7STejun Heo 	 * lock is safe.
779e22bee78STejun Heo 	 */
780bd7bdd43STejun Heo 	if (atomic_dec_and_test(nr_running) && !list_empty(&pool->worklist))
78163d95a91STejun Heo 		to_wakeup = first_worker(pool);
782e22bee78STejun Heo 	return to_wakeup ? to_wakeup->task : NULL;
783e22bee78STejun Heo }
784e22bee78STejun Heo 
785e22bee78STejun Heo /**
786e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
787cb444766STejun Heo  * @worker: self
788d302f017STejun Heo  * @flags: flags to set
789d302f017STejun Heo  * @wakeup: wakeup an idle worker if necessary
790d302f017STejun Heo  *
791e22bee78STejun Heo  * Set @flags in @worker->flags and adjust nr_running accordingly.  If
792e22bee78STejun Heo  * nr_running becomes zero and @wakeup is %true, an idle worker is
793e22bee78STejun Heo  * woken up.
794d302f017STejun Heo  *
795cb444766STejun Heo  * CONTEXT:
796cb444766STejun Heo  * spin_lock_irq(gcwq->lock)
797d302f017STejun Heo  */
798d302f017STejun Heo static inline void worker_set_flags(struct worker *worker, unsigned int flags,
799d302f017STejun Heo 				    bool wakeup)
800d302f017STejun Heo {
801bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
802e22bee78STejun Heo 
803cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
804cb444766STejun Heo 
805e22bee78STejun Heo 	/*
806e22bee78STejun Heo 	 * If transitioning into NOT_RUNNING, adjust nr_running and
807e22bee78STejun Heo 	 * wake up an idle worker as necessary if requested by
808e22bee78STejun Heo 	 * @wakeup.
809e22bee78STejun Heo 	 */
810e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
811e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
81263d95a91STejun Heo 		atomic_t *nr_running = get_pool_nr_running(pool);
813e22bee78STejun Heo 
814e22bee78STejun Heo 		if (wakeup) {
815e22bee78STejun Heo 			if (atomic_dec_and_test(nr_running) &&
816bd7bdd43STejun Heo 			    !list_empty(&pool->worklist))
81763d95a91STejun Heo 				wake_up_worker(pool);
818e22bee78STejun Heo 		} else
819e22bee78STejun Heo 			atomic_dec(nr_running);
820e22bee78STejun Heo 	}
821e22bee78STejun Heo 
822d302f017STejun Heo 	worker->flags |= flags;
823d302f017STejun Heo }
824d302f017STejun Heo 
825d302f017STejun Heo /**
826e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
827cb444766STejun Heo  * @worker: self
828d302f017STejun Heo  * @flags: flags to clear
829d302f017STejun Heo  *
830e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
831d302f017STejun Heo  *
832cb444766STejun Heo  * CONTEXT:
833cb444766STejun Heo  * spin_lock_irq(gcwq->lock)
834d302f017STejun Heo  */
835d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
836d302f017STejun Heo {
83763d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
838e22bee78STejun Heo 	unsigned int oflags = worker->flags;
839e22bee78STejun Heo 
840cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
841cb444766STejun Heo 
842d302f017STejun Heo 	worker->flags &= ~flags;
843e22bee78STejun Heo 
84442c025f3STejun Heo 	/*
84542c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
84642c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
84742c025f3STejun Heo 	 * of multiple flags, not a single flag.
84842c025f3STejun Heo 	 */
849e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
850e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
85163d95a91STejun Heo 			atomic_inc(get_pool_nr_running(pool));
852d302f017STejun Heo }
853d302f017STejun Heo 
854d302f017STejun Heo /**
855c8e55f36STejun Heo  * busy_worker_head - return the busy hash head for a work
856c8e55f36STejun Heo  * @gcwq: gcwq of interest
857c8e55f36STejun Heo  * @work: work to be hashed
858c8e55f36STejun Heo  *
859c8e55f36STejun Heo  * Return hash head of @gcwq for @work.
860c8e55f36STejun Heo  *
861c8e55f36STejun Heo  * CONTEXT:
862c8e55f36STejun Heo  * spin_lock_irq(gcwq->lock).
863c8e55f36STejun Heo  *
864c8e55f36STejun Heo  * RETURNS:
865c8e55f36STejun Heo  * Pointer to the hash head.
866c8e55f36STejun Heo  */
867c8e55f36STejun Heo static struct hlist_head *busy_worker_head(struct global_cwq *gcwq,
868c8e55f36STejun Heo 					   struct work_struct *work)
869c8e55f36STejun Heo {
870c8e55f36STejun Heo 	const int base_shift = ilog2(sizeof(struct work_struct));
871c8e55f36STejun Heo 	unsigned long v = (unsigned long)work;
872c8e55f36STejun Heo 
873c8e55f36STejun Heo 	/* simple shift and fold hash, do we need something better? */
874c8e55f36STejun Heo 	v >>= base_shift;
875c8e55f36STejun Heo 	v += v >> BUSY_WORKER_HASH_ORDER;
876c8e55f36STejun Heo 	v &= BUSY_WORKER_HASH_MASK;
877c8e55f36STejun Heo 
878c8e55f36STejun Heo 	return &gcwq->busy_hash[v];
879c8e55f36STejun Heo }
880c8e55f36STejun Heo 
881c8e55f36STejun Heo /**
8828cca0eeaSTejun Heo  * __find_worker_executing_work - find worker which is executing a work
8838cca0eeaSTejun Heo  * @gcwq: gcwq of interest
8848cca0eeaSTejun Heo  * @bwh: hash head as returned by busy_worker_head()
8858cca0eeaSTejun Heo  * @work: work to find worker for
8868cca0eeaSTejun Heo  *
8878cca0eeaSTejun Heo  * Find a worker which is executing @work on @gcwq.  @bwh should be
8888cca0eeaSTejun Heo  * the hash head obtained by calling busy_worker_head() with the same
8898cca0eeaSTejun Heo  * work.
8908cca0eeaSTejun Heo  *
8918cca0eeaSTejun Heo  * CONTEXT:
8928cca0eeaSTejun Heo  * spin_lock_irq(gcwq->lock).
8938cca0eeaSTejun Heo  *
8948cca0eeaSTejun Heo  * RETURNS:
8958cca0eeaSTejun Heo  * Pointer to worker which is executing @work if found, NULL
8968cca0eeaSTejun Heo  * otherwise.
8978cca0eeaSTejun Heo  */
8988cca0eeaSTejun Heo static struct worker *__find_worker_executing_work(struct global_cwq *gcwq,
8998cca0eeaSTejun Heo 						   struct hlist_head *bwh,
9008cca0eeaSTejun Heo 						   struct work_struct *work)
9018cca0eeaSTejun Heo {
9028cca0eeaSTejun Heo 	struct worker *worker;
9038cca0eeaSTejun Heo 	struct hlist_node *tmp;
9048cca0eeaSTejun Heo 
9058cca0eeaSTejun Heo 	hlist_for_each_entry(worker, tmp, bwh, hentry)
9068cca0eeaSTejun Heo 		if (worker->current_work == work)
9078cca0eeaSTejun Heo 			return worker;
9088cca0eeaSTejun Heo 	return NULL;
9098cca0eeaSTejun Heo }
9108cca0eeaSTejun Heo 
9118cca0eeaSTejun Heo /**
9128cca0eeaSTejun Heo  * find_worker_executing_work - find worker which is executing a work
9138cca0eeaSTejun Heo  * @gcwq: gcwq of interest
9148cca0eeaSTejun Heo  * @work: work to find worker for
9158cca0eeaSTejun Heo  *
9168cca0eeaSTejun Heo  * Find a worker which is executing @work on @gcwq.  This function is
9178cca0eeaSTejun Heo  * identical to __find_worker_executing_work() except that this
9188cca0eeaSTejun Heo  * function calculates @bwh itself.
9198cca0eeaSTejun Heo  *
9208cca0eeaSTejun Heo  * CONTEXT:
9218cca0eeaSTejun Heo  * spin_lock_irq(gcwq->lock).
9228cca0eeaSTejun Heo  *
9238cca0eeaSTejun Heo  * RETURNS:
9248cca0eeaSTejun Heo  * Pointer to worker which is executing @work if found, NULL
9258cca0eeaSTejun Heo  * otherwise.
9268cca0eeaSTejun Heo  */
9278cca0eeaSTejun Heo static struct worker *find_worker_executing_work(struct global_cwq *gcwq,
9288cca0eeaSTejun Heo 						 struct work_struct *work)
9298cca0eeaSTejun Heo {
9308cca0eeaSTejun Heo 	return __find_worker_executing_work(gcwq, busy_worker_head(gcwq, work),
9318cca0eeaSTejun Heo 					    work);
9328cca0eeaSTejun Heo }
9338cca0eeaSTejun Heo 
9348cca0eeaSTejun Heo /**
935bf4ede01STejun Heo  * move_linked_works - move linked works to a list
936bf4ede01STejun Heo  * @work: start of series of works to be scheduled
937bf4ede01STejun Heo  * @head: target list to append @work to
938bf4ede01STejun Heo  * @nextp: out paramter for nested worklist walking
939bf4ede01STejun Heo  *
940bf4ede01STejun Heo  * Schedule linked works starting from @work to @head.  Work series to
941bf4ede01STejun Heo  * be scheduled starts at @work and includes any consecutive work with
942bf4ede01STejun Heo  * WORK_STRUCT_LINKED set in its predecessor.
943bf4ede01STejun Heo  *
944bf4ede01STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of
945bf4ede01STejun Heo  * the last scheduled work.  This allows move_linked_works() to be
946bf4ede01STejun Heo  * nested inside outer list_for_each_entry_safe().
947bf4ede01STejun Heo  *
948bf4ede01STejun Heo  * CONTEXT:
949bf4ede01STejun Heo  * spin_lock_irq(gcwq->lock).
950bf4ede01STejun Heo  */
951bf4ede01STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
952bf4ede01STejun Heo 			      struct work_struct **nextp)
953bf4ede01STejun Heo {
954bf4ede01STejun Heo 	struct work_struct *n;
955bf4ede01STejun Heo 
956bf4ede01STejun Heo 	/*
957bf4ede01STejun Heo 	 * Linked worklist will always end before the end of the list,
958bf4ede01STejun Heo 	 * use NULL for list head.
959bf4ede01STejun Heo 	 */
960bf4ede01STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
961bf4ede01STejun Heo 		list_move_tail(&work->entry, head);
962bf4ede01STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
963bf4ede01STejun Heo 			break;
964bf4ede01STejun Heo 	}
965bf4ede01STejun Heo 
966bf4ede01STejun Heo 	/*
967bf4ede01STejun Heo 	 * If we're already inside safe list traversal and have moved
968bf4ede01STejun Heo 	 * multiple works to the scheduled queue, the next position
969bf4ede01STejun Heo 	 * needs to be updated.
970bf4ede01STejun Heo 	 */
971bf4ede01STejun Heo 	if (nextp)
972bf4ede01STejun Heo 		*nextp = n;
973bf4ede01STejun Heo }
974bf4ede01STejun Heo 
975bf4ede01STejun Heo static void cwq_activate_first_delayed(struct cpu_workqueue_struct *cwq)
976bf4ede01STejun Heo {
977bf4ede01STejun Heo 	struct work_struct *work = list_first_entry(&cwq->delayed_works,
978bf4ede01STejun Heo 						    struct work_struct, entry);
979bf4ede01STejun Heo 
980bf4ede01STejun Heo 	trace_workqueue_activate_work(work);
981bf4ede01STejun Heo 	move_linked_works(work, &cwq->pool->worklist, NULL);
982bf4ede01STejun Heo 	__clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
983bf4ede01STejun Heo 	cwq->nr_active++;
984bf4ede01STejun Heo }
985bf4ede01STejun Heo 
986bf4ede01STejun Heo /**
987bf4ede01STejun Heo  * cwq_dec_nr_in_flight - decrement cwq's nr_in_flight
988bf4ede01STejun Heo  * @cwq: cwq of interest
989bf4ede01STejun Heo  * @color: color of work which left the queue
990bf4ede01STejun Heo  * @delayed: for a delayed work
991bf4ede01STejun Heo  *
992bf4ede01STejun Heo  * A work either has completed or is removed from pending queue,
993bf4ede01STejun Heo  * decrement nr_in_flight of its cwq and handle workqueue flushing.
994bf4ede01STejun Heo  *
995bf4ede01STejun Heo  * CONTEXT:
996bf4ede01STejun Heo  * spin_lock_irq(gcwq->lock).
997bf4ede01STejun Heo  */
998bf4ede01STejun Heo static void cwq_dec_nr_in_flight(struct cpu_workqueue_struct *cwq, int color,
999bf4ede01STejun Heo 				 bool delayed)
1000bf4ede01STejun Heo {
1001bf4ede01STejun Heo 	/* ignore uncolored works */
1002bf4ede01STejun Heo 	if (color == WORK_NO_COLOR)
1003bf4ede01STejun Heo 		return;
1004bf4ede01STejun Heo 
1005bf4ede01STejun Heo 	cwq->nr_in_flight[color]--;
1006bf4ede01STejun Heo 
1007bf4ede01STejun Heo 	if (!delayed) {
1008bf4ede01STejun Heo 		cwq->nr_active--;
1009bf4ede01STejun Heo 		if (!list_empty(&cwq->delayed_works)) {
1010bf4ede01STejun Heo 			/* one down, submit a delayed one */
1011bf4ede01STejun Heo 			if (cwq->nr_active < cwq->max_active)
1012bf4ede01STejun Heo 				cwq_activate_first_delayed(cwq);
1013bf4ede01STejun Heo 		}
1014bf4ede01STejun Heo 	}
1015bf4ede01STejun Heo 
1016bf4ede01STejun Heo 	/* is flush in progress and are we at the flushing tip? */
1017bf4ede01STejun Heo 	if (likely(cwq->flush_color != color))
1018bf4ede01STejun Heo 		return;
1019bf4ede01STejun Heo 
1020bf4ede01STejun Heo 	/* are there still in-flight works? */
1021bf4ede01STejun Heo 	if (cwq->nr_in_flight[color])
1022bf4ede01STejun Heo 		return;
1023bf4ede01STejun Heo 
1024bf4ede01STejun Heo 	/* this cwq is done, clear flush_color */
1025bf4ede01STejun Heo 	cwq->flush_color = -1;
1026bf4ede01STejun Heo 
1027bf4ede01STejun Heo 	/*
1028bf4ede01STejun Heo 	 * If this was the last cwq, wake up the first flusher.  It
1029bf4ede01STejun Heo 	 * will handle the rest.
1030bf4ede01STejun Heo 	 */
1031bf4ede01STejun Heo 	if (atomic_dec_and_test(&cwq->wq->nr_cwqs_to_flush))
1032bf4ede01STejun Heo 		complete(&cwq->wq->first_flusher->done);
1033bf4ede01STejun Heo }
1034bf4ede01STejun Heo 
103536e227d2STejun Heo /**
1036bbb68dfaSTejun Heo  * try_to_grab_pending - steal work item from worklist and disable irq
103736e227d2STejun Heo  * @work: work item to steal
103836e227d2STejun Heo  * @is_dwork: @work is a delayed_work
1039bbb68dfaSTejun Heo  * @flags: place to store irq state
104036e227d2STejun Heo  *
104136e227d2STejun Heo  * Try to grab PENDING bit of @work.  This function can handle @work in any
104236e227d2STejun Heo  * stable state - idle, on timer or on worklist.  Return values are
104336e227d2STejun Heo  *
104436e227d2STejun Heo  *  1		if @work was pending and we successfully stole PENDING
104536e227d2STejun Heo  *  0		if @work was idle and we claimed PENDING
104636e227d2STejun Heo  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
1047bbb68dfaSTejun Heo  *  -ENOENT	if someone else is canceling @work, this state may persist
1048bbb68dfaSTejun Heo  *		for arbitrarily long
104936e227d2STejun Heo  *
1050bbb68dfaSTejun Heo  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
1051*e0aecdd8STejun Heo  * interrupted while holding PENDING and @work off queue, irq must be
1052*e0aecdd8STejun Heo  * disabled on entry.  This, combined with delayed_work->timer being
1053*e0aecdd8STejun Heo  * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1054bbb68dfaSTejun Heo  *
1055bbb68dfaSTejun Heo  * On successful return, >= 0, irq is disabled and the caller is
1056bbb68dfaSTejun Heo  * responsible for releasing it using local_irq_restore(*@flags).
1057bbb68dfaSTejun Heo  *
1058*e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
1059bf4ede01STejun Heo  */
1060bbb68dfaSTejun Heo static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1061bbb68dfaSTejun Heo 			       unsigned long *flags)
1062bf4ede01STejun Heo {
1063bf4ede01STejun Heo 	struct global_cwq *gcwq;
1064bf4ede01STejun Heo 
1065bbb68dfaSTejun Heo 	WARN_ON_ONCE(in_irq());
1066bbb68dfaSTejun Heo 
1067bbb68dfaSTejun Heo 	local_irq_save(*flags);
1068bbb68dfaSTejun Heo 
106936e227d2STejun Heo 	/* try to steal the timer if it exists */
107036e227d2STejun Heo 	if (is_dwork) {
107136e227d2STejun Heo 		struct delayed_work *dwork = to_delayed_work(work);
107236e227d2STejun Heo 
1073*e0aecdd8STejun Heo 		/*
1074*e0aecdd8STejun Heo 		 * dwork->timer is irqsafe.  If del_timer() fails, it's
1075*e0aecdd8STejun Heo 		 * guaranteed that the timer is not queued anywhere and not
1076*e0aecdd8STejun Heo 		 * running on the local CPU.
1077*e0aecdd8STejun Heo 		 */
107836e227d2STejun Heo 		if (likely(del_timer(&dwork->timer)))
107936e227d2STejun Heo 			return 1;
108036e227d2STejun Heo 	}
108136e227d2STejun Heo 
108236e227d2STejun Heo 	/* try to claim PENDING the normal way */
1083bf4ede01STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1084bf4ede01STejun Heo 		return 0;
1085bf4ede01STejun Heo 
1086bf4ede01STejun Heo 	/*
1087bf4ede01STejun Heo 	 * The queueing is in progress, or it is already queued. Try to
1088bf4ede01STejun Heo 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1089bf4ede01STejun Heo 	 */
1090bf4ede01STejun Heo 	gcwq = get_work_gcwq(work);
1091bf4ede01STejun Heo 	if (!gcwq)
1092bbb68dfaSTejun Heo 		goto fail;
1093bf4ede01STejun Heo 
1094bbb68dfaSTejun Heo 	spin_lock(&gcwq->lock);
1095bf4ede01STejun Heo 	if (!list_empty(&work->entry)) {
1096bf4ede01STejun Heo 		/*
1097bf4ede01STejun Heo 		 * This work is queued, but perhaps we locked the wrong gcwq.
1098bf4ede01STejun Heo 		 * In that case we must see the new value after rmb(), see
1099bf4ede01STejun Heo 		 * insert_work()->wmb().
1100bf4ede01STejun Heo 		 */
1101bf4ede01STejun Heo 		smp_rmb();
1102bf4ede01STejun Heo 		if (gcwq == get_work_gcwq(work)) {
1103bf4ede01STejun Heo 			debug_work_deactivate(work);
1104bf4ede01STejun Heo 			list_del_init(&work->entry);
1105bf4ede01STejun Heo 			cwq_dec_nr_in_flight(get_work_cwq(work),
1106bf4ede01STejun Heo 				get_work_color(work),
1107bf4ede01STejun Heo 				*work_data_bits(work) & WORK_STRUCT_DELAYED);
110836e227d2STejun Heo 
1109bbb68dfaSTejun Heo 			spin_unlock(&gcwq->lock);
111036e227d2STejun Heo 			return 1;
1111bf4ede01STejun Heo 		}
1112bf4ede01STejun Heo 	}
1113bbb68dfaSTejun Heo 	spin_unlock(&gcwq->lock);
1114bbb68dfaSTejun Heo fail:
1115bbb68dfaSTejun Heo 	local_irq_restore(*flags);
1116bbb68dfaSTejun Heo 	if (work_is_canceling(work))
1117bbb68dfaSTejun Heo 		return -ENOENT;
1118bbb68dfaSTejun Heo 	cpu_relax();
111936e227d2STejun Heo 	return -EAGAIN;
1120bf4ede01STejun Heo }
1121bf4ede01STejun Heo 
1122bf4ede01STejun Heo /**
11237e11629dSTejun Heo  * insert_work - insert a work into gcwq
11244690c4abSTejun Heo  * @cwq: cwq @work belongs to
11254690c4abSTejun Heo  * @work: work to insert
11264690c4abSTejun Heo  * @head: insertion point
11274690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
11284690c4abSTejun Heo  *
11297e11629dSTejun Heo  * Insert @work which belongs to @cwq into @gcwq after @head.
11307e11629dSTejun Heo  * @extra_flags is or'd to work_struct flags.
11314690c4abSTejun Heo  *
11324690c4abSTejun Heo  * CONTEXT:
11338b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock).
11341da177e4SLinus Torvalds  */
1135b89deed3SOleg Nesterov static void insert_work(struct cpu_workqueue_struct *cwq,
11364690c4abSTejun Heo 			struct work_struct *work, struct list_head *head,
11374690c4abSTejun Heo 			unsigned int extra_flags)
1138b89deed3SOleg Nesterov {
113963d95a91STejun Heo 	struct worker_pool *pool = cwq->pool;
1140e1d8aa9fSFrederic Weisbecker 
11414690c4abSTejun Heo 	/* we own @work, set data and link */
11427a22ad75STejun Heo 	set_work_cwq(work, cwq, extra_flags);
11434690c4abSTejun Heo 
11446e84d644SOleg Nesterov 	/*
11456e84d644SOleg Nesterov 	 * Ensure that we get the right work->data if we see the
11466e84d644SOleg Nesterov 	 * result of list_add() below, see try_to_grab_pending().
11476e84d644SOleg Nesterov 	 */
11486e84d644SOleg Nesterov 	smp_wmb();
11494690c4abSTejun Heo 
11501a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
1151e22bee78STejun Heo 
1152e22bee78STejun Heo 	/*
1153e22bee78STejun Heo 	 * Ensure either worker_sched_deactivated() sees the above
1154e22bee78STejun Heo 	 * list_add_tail() or we see zero nr_running to avoid workers
1155e22bee78STejun Heo 	 * lying around lazily while there are works to be processed.
1156e22bee78STejun Heo 	 */
1157e22bee78STejun Heo 	smp_mb();
1158e22bee78STejun Heo 
115963d95a91STejun Heo 	if (__need_more_worker(pool))
116063d95a91STejun Heo 		wake_up_worker(pool);
1161b89deed3SOleg Nesterov }
1162b89deed3SOleg Nesterov 
1163c8efcc25STejun Heo /*
1164c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
1165c8efcc25STejun Heo  * same workqueue.  This is rather expensive and should only be used from
1166c8efcc25STejun Heo  * cold paths.
1167c8efcc25STejun Heo  */
1168c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
1169c8efcc25STejun Heo {
1170c8efcc25STejun Heo 	unsigned long flags;
1171c8efcc25STejun Heo 	unsigned int cpu;
1172c8efcc25STejun Heo 
1173c8efcc25STejun Heo 	for_each_gcwq_cpu(cpu) {
1174c8efcc25STejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
1175c8efcc25STejun Heo 		struct worker *worker;
1176c8efcc25STejun Heo 		struct hlist_node *pos;
1177c8efcc25STejun Heo 		int i;
1178c8efcc25STejun Heo 
1179c8efcc25STejun Heo 		spin_lock_irqsave(&gcwq->lock, flags);
1180c8efcc25STejun Heo 		for_each_busy_worker(worker, i, pos, gcwq) {
1181c8efcc25STejun Heo 			if (worker->task != current)
1182c8efcc25STejun Heo 				continue;
1183c8efcc25STejun Heo 			spin_unlock_irqrestore(&gcwq->lock, flags);
1184c8efcc25STejun Heo 			/*
1185c8efcc25STejun Heo 			 * I'm @worker, no locking necessary.  See if @work
1186c8efcc25STejun Heo 			 * is headed to the same workqueue.
1187c8efcc25STejun Heo 			 */
1188c8efcc25STejun Heo 			return worker->current_cwq->wq == wq;
1189c8efcc25STejun Heo 		}
1190c8efcc25STejun Heo 		spin_unlock_irqrestore(&gcwq->lock, flags);
1191c8efcc25STejun Heo 	}
1192c8efcc25STejun Heo 	return false;
1193c8efcc25STejun Heo }
1194c8efcc25STejun Heo 
11954690c4abSTejun Heo static void __queue_work(unsigned int cpu, struct workqueue_struct *wq,
11961da177e4SLinus Torvalds 			 struct work_struct *work)
11971da177e4SLinus Torvalds {
1198502ca9d8STejun Heo 	struct global_cwq *gcwq;
1199502ca9d8STejun Heo 	struct cpu_workqueue_struct *cwq;
12001e19ffc6STejun Heo 	struct list_head *worklist;
12018a2e8e5dSTejun Heo 	unsigned int work_flags;
1202b75cac93SJoonsoo Kim 	unsigned int req_cpu = cpu;
12038930cabaSTejun Heo 
12048930cabaSTejun Heo 	/*
12058930cabaSTejun Heo 	 * While a work item is PENDING && off queue, a task trying to
12068930cabaSTejun Heo 	 * steal the PENDING will busy-loop waiting for it to either get
12078930cabaSTejun Heo 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
12088930cabaSTejun Heo 	 * happen with IRQ disabled.
12098930cabaSTejun Heo 	 */
12108930cabaSTejun Heo 	WARN_ON_ONCE(!irqs_disabled());
12111da177e4SLinus Torvalds 
1212dc186ad7SThomas Gleixner 	debug_work_activate(work);
12131e19ffc6STejun Heo 
1214c8efcc25STejun Heo 	/* if dying, only works from the same workqueue are allowed */
12159c5a2ba7STejun Heo 	if (unlikely(wq->flags & WQ_DRAINING) &&
1216c8efcc25STejun Heo 	    WARN_ON_ONCE(!is_chained_work(wq)))
1217e41e704bSTejun Heo 		return;
1218e41e704bSTejun Heo 
1219c7fc77f7STejun Heo 	/* determine gcwq to use */
1220c7fc77f7STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
1221c7fc77f7STejun Heo 		struct global_cwq *last_gcwq;
1222c7fc77f7STejun Heo 
122357469821STejun Heo 		if (cpu == WORK_CPU_UNBOUND)
1224f3421797STejun Heo 			cpu = raw_smp_processor_id();
1225f3421797STejun Heo 
122618aa9effSTejun Heo 		/*
1227dbf2576eSTejun Heo 		 * It's multi cpu.  If @work was previously on a different
1228dbf2576eSTejun Heo 		 * cpu, it might still be running there, in which case the
1229dbf2576eSTejun Heo 		 * work needs to be queued on that cpu to guarantee
1230dbf2576eSTejun Heo 		 * non-reentrancy.
123118aa9effSTejun Heo 		 */
1232502ca9d8STejun Heo 		gcwq = get_gcwq(cpu);
1233dbf2576eSTejun Heo 		last_gcwq = get_work_gcwq(work);
1234dbf2576eSTejun Heo 
1235dbf2576eSTejun Heo 		if (last_gcwq && 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 
1333*e0aecdd8STejun Heo 	/* should have been called from irqsafe timer with irq already off */
13341265057fSTejun Heo 	__queue_work(dwork->cpu, cwq->wq, &dwork->work);
13351da177e4SLinus Torvalds }
1336d8e794dfSTejun Heo EXPORT_SYMBOL_GPL(delayed_work_timer_fn);
13371da177e4SLinus Torvalds 
13387beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
13397beb2edfSTejun Heo 				struct delayed_work *dwork, unsigned long delay)
13407beb2edfSTejun Heo {
13417beb2edfSTejun Heo 	struct timer_list *timer = &dwork->timer;
13427beb2edfSTejun Heo 	struct work_struct *work = &dwork->work;
13437beb2edfSTejun Heo 	unsigned int lcpu;
13447beb2edfSTejun Heo 
13457beb2edfSTejun Heo 	WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
13467beb2edfSTejun Heo 		     timer->data != (unsigned long)dwork);
13477beb2edfSTejun Heo 	BUG_ON(timer_pending(timer));
13487beb2edfSTejun Heo 	BUG_ON(!list_empty(&work->entry));
13497beb2edfSTejun Heo 
13507beb2edfSTejun Heo 	timer_stats_timer_set_start_info(&dwork->timer);
13517beb2edfSTejun Heo 
13527beb2edfSTejun Heo 	/*
13537beb2edfSTejun Heo 	 * This stores cwq for the moment, for the timer_fn.  Note that the
13547beb2edfSTejun Heo 	 * work's gcwq is preserved to allow reentrance detection for
13557beb2edfSTejun Heo 	 * delayed works.
13567beb2edfSTejun Heo 	 */
13577beb2edfSTejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
13587beb2edfSTejun Heo 		struct global_cwq *gcwq = get_work_gcwq(work);
13597beb2edfSTejun Heo 
1360e42986deSJoonsoo Kim 		/*
1361e42986deSJoonsoo Kim 		 * If we cannot get the last gcwq from @work directly,
1362e42986deSJoonsoo Kim 		 * select the last CPU such that it avoids unnecessarily
1363e42986deSJoonsoo Kim 		 * triggering non-reentrancy check in __queue_work().
1364e42986deSJoonsoo Kim 		 */
1365e42986deSJoonsoo Kim 		lcpu = cpu;
1366e42986deSJoonsoo Kim 		if (gcwq)
13677beb2edfSTejun Heo 			lcpu = gcwq->cpu;
1368e42986deSJoonsoo Kim 		if (lcpu == WORK_CPU_UNBOUND)
13697beb2edfSTejun Heo 			lcpu = raw_smp_processor_id();
13707beb2edfSTejun Heo 	} else {
13717beb2edfSTejun Heo 		lcpu = WORK_CPU_UNBOUND;
13727beb2edfSTejun Heo 	}
13737beb2edfSTejun Heo 
13747beb2edfSTejun Heo 	set_work_cwq(work, get_cwq(lcpu, wq), 0);
13757beb2edfSTejun Heo 
13761265057fSTejun Heo 	dwork->cpu = cpu;
13777beb2edfSTejun Heo 	timer->expires = jiffies + delay;
13787beb2edfSTejun Heo 
13797beb2edfSTejun Heo 	if (unlikely(cpu != WORK_CPU_UNBOUND))
13807beb2edfSTejun Heo 		add_timer_on(timer, cpu);
13817beb2edfSTejun Heo 	else
13827beb2edfSTejun Heo 		add_timer(timer);
13837beb2edfSTejun Heo }
13847beb2edfSTejun Heo 
13850fcb78c2SRolf Eike Beer /**
13860fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
13870fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
13880fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1389af9997e4SRandy Dunlap  * @dwork: work to queue
13900fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
13910fcb78c2SRolf Eike Beer  *
1392715f1300STejun Heo  * Returns %false if @work was already on a queue, %true otherwise.  If
1393715f1300STejun Heo  * @delay is zero and @dwork is idle, it will be scheduled for immediate
1394715f1300STejun Heo  * execution.
13950fcb78c2SRolf Eike Beer  */
1396d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
139752bad64dSDavid Howells 			   struct delayed_work *dwork, unsigned long delay)
13987a6bc1cdSVenkatesh Pallipadi {
139952bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
1400d4283e93STejun Heo 	bool ret = false;
14018930cabaSTejun Heo 	unsigned long flags;
14028930cabaSTejun Heo 
1403715f1300STejun Heo 	if (!delay)
1404715f1300STejun Heo 		return queue_work_on(cpu, wq, &dwork->work);
1405715f1300STejun Heo 
14068930cabaSTejun Heo 	/* read the comment in __queue_work() */
14078930cabaSTejun Heo 	local_irq_save(flags);
14087a6bc1cdSVenkatesh Pallipadi 
140922df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
14107beb2edfSTejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
1411d4283e93STejun Heo 		ret = true;
14127a6bc1cdSVenkatesh Pallipadi 	}
14138930cabaSTejun Heo 
14148930cabaSTejun Heo 	local_irq_restore(flags);
14157a6bc1cdSVenkatesh Pallipadi 	return ret;
14167a6bc1cdSVenkatesh Pallipadi }
1417ae90dd5dSDave Jones EXPORT_SYMBOL_GPL(queue_delayed_work_on);
14181da177e4SLinus Torvalds 
1419c8e55f36STejun Heo /**
14200a13c00eSTejun Heo  * queue_delayed_work - queue work on a workqueue after delay
14210a13c00eSTejun Heo  * @wq: workqueue to use
14220a13c00eSTejun Heo  * @dwork: delayable work to queue
14230a13c00eSTejun Heo  * @delay: number of jiffies to wait before queueing
14240a13c00eSTejun Heo  *
1425715f1300STejun Heo  * Equivalent to queue_delayed_work_on() but tries to use the local CPU.
14260a13c00eSTejun Heo  */
1427d4283e93STejun Heo bool queue_delayed_work(struct workqueue_struct *wq,
14280a13c00eSTejun Heo 			struct delayed_work *dwork, unsigned long delay)
14290a13c00eSTejun Heo {
143057469821STejun Heo 	return queue_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
14310a13c00eSTejun Heo }
14320a13c00eSTejun Heo EXPORT_SYMBOL_GPL(queue_delayed_work);
14330a13c00eSTejun Heo 
14340a13c00eSTejun Heo /**
14358376fe22STejun Heo  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
14368376fe22STejun Heo  * @cpu: CPU number to execute work on
14378376fe22STejun Heo  * @wq: workqueue to use
14388376fe22STejun Heo  * @dwork: work to queue
14398376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
14408376fe22STejun Heo  *
14418376fe22STejun Heo  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
14428376fe22STejun Heo  * modify @dwork's timer so that it expires after @delay.  If @delay is
14438376fe22STejun Heo  * zero, @work is guaranteed to be scheduled immediately regardless of its
14448376fe22STejun Heo  * current state.
14458376fe22STejun Heo  *
14468376fe22STejun Heo  * Returns %false if @dwork was idle and queued, %true if @dwork was
14478376fe22STejun Heo  * pending and its timer was modified.
14488376fe22STejun Heo  *
1449*e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
14508376fe22STejun Heo  * See try_to_grab_pending() for details.
14518376fe22STejun Heo  */
14528376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
14538376fe22STejun Heo 			 struct delayed_work *dwork, unsigned long delay)
14548376fe22STejun Heo {
14558376fe22STejun Heo 	unsigned long flags;
14568376fe22STejun Heo 	int ret;
14578376fe22STejun Heo 
14588376fe22STejun Heo 	do {
14598376fe22STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
14608376fe22STejun Heo 	} while (unlikely(ret == -EAGAIN));
14618376fe22STejun Heo 
14628376fe22STejun Heo 	if (likely(ret >= 0)) {
14638376fe22STejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
14648376fe22STejun Heo 		local_irq_restore(flags);
14658376fe22STejun Heo 	}
14668376fe22STejun Heo 
14678376fe22STejun Heo 	/* -ENOENT from try_to_grab_pending() becomes %true */
14688376fe22STejun Heo 	return ret;
14698376fe22STejun Heo }
14708376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
14718376fe22STejun Heo 
14728376fe22STejun Heo /**
14738376fe22STejun Heo  * mod_delayed_work - modify delay of or queue a delayed work
14748376fe22STejun Heo  * @wq: workqueue to use
14758376fe22STejun Heo  * @dwork: work to queue
14768376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
14778376fe22STejun Heo  *
14788376fe22STejun Heo  * mod_delayed_work_on() on local CPU.
14798376fe22STejun Heo  */
14808376fe22STejun Heo bool mod_delayed_work(struct workqueue_struct *wq, struct delayed_work *dwork,
14818376fe22STejun Heo 		      unsigned long delay)
14828376fe22STejun Heo {
14838376fe22STejun Heo 	return mod_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
14848376fe22STejun Heo }
14858376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work);
14868376fe22STejun Heo 
14878376fe22STejun Heo /**
1488c8e55f36STejun Heo  * worker_enter_idle - enter idle state
1489c8e55f36STejun Heo  * @worker: worker which is entering idle state
1490c8e55f36STejun Heo  *
1491c8e55f36STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
1492c8e55f36STejun Heo  * necessary.
1493c8e55f36STejun Heo  *
1494c8e55f36STejun Heo  * LOCKING:
1495c8e55f36STejun Heo  * spin_lock_irq(gcwq->lock).
1496c8e55f36STejun Heo  */
1497c8e55f36STejun Heo static void worker_enter_idle(struct worker *worker)
14981da177e4SLinus Torvalds {
1499bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1500bd7bdd43STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
1501c8e55f36STejun Heo 
1502c8e55f36STejun Heo 	BUG_ON(worker->flags & WORKER_IDLE);
1503c8e55f36STejun Heo 	BUG_ON(!list_empty(&worker->entry) &&
1504c8e55f36STejun Heo 	       (worker->hentry.next || worker->hentry.pprev));
1505c8e55f36STejun Heo 
1506cb444766STejun Heo 	/* can't use worker_set_flags(), also called from start_worker() */
1507cb444766STejun Heo 	worker->flags |= WORKER_IDLE;
1508bd7bdd43STejun Heo 	pool->nr_idle++;
1509e22bee78STejun Heo 	worker->last_active = jiffies;
1510c8e55f36STejun Heo 
1511c8e55f36STejun Heo 	/* idle_list is LIFO */
1512bd7bdd43STejun Heo 	list_add(&worker->entry, &pool->idle_list);
1513db7bccf4STejun Heo 
151463d95a91STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1515628c78e7STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1516cb444766STejun Heo 
1517544ecf31STejun Heo 	/*
1518628c78e7STejun Heo 	 * Sanity check nr_running.  Because gcwq_unbind_fn() releases
1519628c78e7STejun Heo 	 * gcwq->lock between setting %WORKER_UNBOUND and zapping
1520628c78e7STejun Heo 	 * nr_running, the warning may trigger spuriously.  Check iff
1521628c78e7STejun Heo 	 * unbind is not in progress.
1522544ecf31STejun Heo 	 */
1523628c78e7STejun Heo 	WARN_ON_ONCE(!(gcwq->flags & GCWQ_DISASSOCIATED) &&
1524bd7bdd43STejun Heo 		     pool->nr_workers == pool->nr_idle &&
152563d95a91STejun Heo 		     atomic_read(get_pool_nr_running(pool)));
1526c8e55f36STejun Heo }
1527c8e55f36STejun Heo 
1528c8e55f36STejun Heo /**
1529c8e55f36STejun Heo  * worker_leave_idle - leave idle state
1530c8e55f36STejun Heo  * @worker: worker which is leaving idle state
1531c8e55f36STejun Heo  *
1532c8e55f36STejun Heo  * @worker is leaving idle state.  Update stats.
1533c8e55f36STejun Heo  *
1534c8e55f36STejun Heo  * LOCKING:
1535c8e55f36STejun Heo  * spin_lock_irq(gcwq->lock).
1536c8e55f36STejun Heo  */
1537c8e55f36STejun Heo static void worker_leave_idle(struct worker *worker)
1538c8e55f36STejun Heo {
1539bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1540c8e55f36STejun Heo 
1541c8e55f36STejun Heo 	BUG_ON(!(worker->flags & WORKER_IDLE));
1542d302f017STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
1543bd7bdd43STejun Heo 	pool->nr_idle--;
1544c8e55f36STejun Heo 	list_del_init(&worker->entry);
1545c8e55f36STejun Heo }
1546c8e55f36STejun Heo 
1547e22bee78STejun Heo /**
1548e22bee78STejun Heo  * worker_maybe_bind_and_lock - bind worker to its cpu if possible and lock gcwq
1549e22bee78STejun Heo  * @worker: self
1550e22bee78STejun Heo  *
1551e22bee78STejun Heo  * Works which are scheduled while the cpu is online must at least be
1552e22bee78STejun Heo  * scheduled to a worker which is bound to the cpu so that if they are
1553e22bee78STejun Heo  * flushed from cpu callbacks while cpu is going down, they are
1554e22bee78STejun Heo  * guaranteed to execute on the cpu.
1555e22bee78STejun Heo  *
1556e22bee78STejun Heo  * This function is to be used by rogue workers and rescuers to bind
1557e22bee78STejun Heo  * themselves to the target cpu and may race with cpu going down or
1558e22bee78STejun Heo  * coming online.  kthread_bind() can't be used because it may put the
1559e22bee78STejun Heo  * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1560e22bee78STejun Heo  * verbatim as it's best effort and blocking and gcwq may be
1561e22bee78STejun Heo  * [dis]associated in the meantime.
1562e22bee78STejun Heo  *
1563f2d5a0eeSTejun Heo  * This function tries set_cpus_allowed() and locks gcwq and verifies the
1564f2d5a0eeSTejun Heo  * binding against %GCWQ_DISASSOCIATED which is set during
1565f2d5a0eeSTejun Heo  * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
1566f2d5a0eeSTejun Heo  * enters idle state or fetches works without dropping lock, it can
1567f2d5a0eeSTejun Heo  * guarantee the scheduling requirement described in the first paragraph.
1568e22bee78STejun Heo  *
1569e22bee78STejun Heo  * CONTEXT:
1570e22bee78STejun Heo  * Might sleep.  Called without any lock but returns with gcwq->lock
1571e22bee78STejun Heo  * held.
1572e22bee78STejun Heo  *
1573e22bee78STejun Heo  * RETURNS:
1574e22bee78STejun Heo  * %true if the associated gcwq is online (@worker is successfully
1575e22bee78STejun Heo  * bound), %false if offline.
1576e22bee78STejun Heo  */
1577e22bee78STejun Heo static bool worker_maybe_bind_and_lock(struct worker *worker)
1578972fa1c5SNamhyung Kim __acquires(&gcwq->lock)
1579e22bee78STejun Heo {
1580bd7bdd43STejun Heo 	struct global_cwq *gcwq = worker->pool->gcwq;
1581e22bee78STejun Heo 	struct task_struct *task = worker->task;
1582e22bee78STejun Heo 
1583e22bee78STejun Heo 	while (true) {
1584e22bee78STejun Heo 		/*
1585e22bee78STejun Heo 		 * The following call may fail, succeed or succeed
1586e22bee78STejun Heo 		 * without actually migrating the task to the cpu if
1587e22bee78STejun Heo 		 * it races with cpu hotunplug operation.  Verify
1588e22bee78STejun Heo 		 * against GCWQ_DISASSOCIATED.
1589e22bee78STejun Heo 		 */
1590f3421797STejun Heo 		if (!(gcwq->flags & GCWQ_DISASSOCIATED))
1591e22bee78STejun Heo 			set_cpus_allowed_ptr(task, get_cpu_mask(gcwq->cpu));
1592e22bee78STejun Heo 
1593e22bee78STejun Heo 		spin_lock_irq(&gcwq->lock);
1594e22bee78STejun Heo 		if (gcwq->flags & GCWQ_DISASSOCIATED)
1595e22bee78STejun Heo 			return false;
1596e22bee78STejun Heo 		if (task_cpu(task) == gcwq->cpu &&
1597e22bee78STejun Heo 		    cpumask_equal(&current->cpus_allowed,
1598e22bee78STejun Heo 				  get_cpu_mask(gcwq->cpu)))
1599e22bee78STejun Heo 			return true;
1600e22bee78STejun Heo 		spin_unlock_irq(&gcwq->lock);
1601e22bee78STejun Heo 
16025035b20fSTejun Heo 		/*
16035035b20fSTejun Heo 		 * We've raced with CPU hot[un]plug.  Give it a breather
16045035b20fSTejun Heo 		 * and retry migration.  cond_resched() is required here;
16055035b20fSTejun Heo 		 * otherwise, we might deadlock against cpu_stop trying to
16065035b20fSTejun Heo 		 * bring down the CPU on non-preemptive kernel.
16075035b20fSTejun Heo 		 */
1608e22bee78STejun Heo 		cpu_relax();
16095035b20fSTejun Heo 		cond_resched();
1610e22bee78STejun Heo 	}
1611e22bee78STejun Heo }
1612e22bee78STejun Heo 
161325511a47STejun Heo struct idle_rebind {
161425511a47STejun Heo 	int			cnt;		/* # workers to be rebound */
161525511a47STejun Heo 	struct completion	done;		/* all workers rebound */
161625511a47STejun Heo };
161725511a47STejun Heo 
1618e22bee78STejun Heo /*
161925511a47STejun Heo  * Rebind an idle @worker to its CPU.  During CPU onlining, this has to
162025511a47STejun Heo  * happen synchronously for idle workers.  worker_thread() will test
162125511a47STejun Heo  * %WORKER_REBIND before leaving idle and call this function.
162225511a47STejun Heo  */
162325511a47STejun Heo static void idle_worker_rebind(struct worker *worker)
162425511a47STejun Heo {
162525511a47STejun Heo 	struct global_cwq *gcwq = worker->pool->gcwq;
162625511a47STejun Heo 
162725511a47STejun Heo 	/* CPU must be online at this point */
162825511a47STejun Heo 	WARN_ON(!worker_maybe_bind_and_lock(worker));
162925511a47STejun Heo 	if (!--worker->idle_rebind->cnt)
163025511a47STejun Heo 		complete(&worker->idle_rebind->done);
163125511a47STejun Heo 	spin_unlock_irq(&worker->pool->gcwq->lock);
163225511a47STejun Heo 
163325511a47STejun Heo 	/* we did our part, wait for rebind_workers() to finish up */
163425511a47STejun Heo 	wait_event(gcwq->rebind_hold, !(worker->flags & WORKER_REBIND));
163525511a47STejun Heo }
163625511a47STejun Heo 
163725511a47STejun Heo /*
163825511a47STejun Heo  * Function for @worker->rebind.work used to rebind unbound busy workers to
1639403c821dSTejun Heo  * the associated cpu which is coming back online.  This is scheduled by
1640403c821dSTejun Heo  * cpu up but can race with other cpu hotplug operations and may be
1641403c821dSTejun Heo  * executed twice without intervening cpu down.
1642e22bee78STejun Heo  */
164325511a47STejun Heo static void busy_worker_rebind_fn(struct work_struct *work)
1644e22bee78STejun Heo {
1645e22bee78STejun Heo 	struct worker *worker = container_of(work, struct worker, rebind_work);
1646bd7bdd43STejun Heo 	struct global_cwq *gcwq = worker->pool->gcwq;
1647e22bee78STejun Heo 
1648e22bee78STejun Heo 	if (worker_maybe_bind_and_lock(worker))
1649e22bee78STejun Heo 		worker_clr_flags(worker, WORKER_REBIND);
1650e22bee78STejun Heo 
1651e22bee78STejun Heo 	spin_unlock_irq(&gcwq->lock);
1652e22bee78STejun Heo }
1653e22bee78STejun Heo 
165425511a47STejun Heo /**
165525511a47STejun Heo  * rebind_workers - rebind all workers of a gcwq to the associated CPU
165625511a47STejun Heo  * @gcwq: gcwq of interest
165725511a47STejun Heo  *
165825511a47STejun Heo  * @gcwq->cpu is coming online.  Rebind all workers to the CPU.  Rebinding
165925511a47STejun Heo  * is different for idle and busy ones.
166025511a47STejun Heo  *
166125511a47STejun Heo  * The idle ones should be rebound synchronously and idle rebinding should
166225511a47STejun Heo  * be complete before any worker starts executing work items with
166325511a47STejun Heo  * concurrency management enabled; otherwise, scheduler may oops trying to
166425511a47STejun Heo  * wake up non-local idle worker from wq_worker_sleeping().
166525511a47STejun Heo  *
166625511a47STejun Heo  * This is achieved by repeatedly requesting rebinding until all idle
166725511a47STejun Heo  * workers are known to have been rebound under @gcwq->lock and holding all
166825511a47STejun Heo  * idle workers from becoming busy until idle rebinding is complete.
166925511a47STejun Heo  *
167025511a47STejun Heo  * Once idle workers are rebound, busy workers can be rebound as they
167125511a47STejun Heo  * finish executing their current work items.  Queueing the rebind work at
167225511a47STejun Heo  * the head of their scheduled lists is enough.  Note that nr_running will
167325511a47STejun Heo  * be properbly bumped as busy workers rebind.
167425511a47STejun Heo  *
167525511a47STejun Heo  * On return, all workers are guaranteed to either be bound or have rebind
167625511a47STejun Heo  * work item scheduled.
167725511a47STejun Heo  */
167825511a47STejun Heo static void rebind_workers(struct global_cwq *gcwq)
167925511a47STejun Heo 	__releases(&gcwq->lock) __acquires(&gcwq->lock)
168025511a47STejun Heo {
168125511a47STejun Heo 	struct idle_rebind idle_rebind;
168225511a47STejun Heo 	struct worker_pool *pool;
168325511a47STejun Heo 	struct worker *worker;
168425511a47STejun Heo 	struct hlist_node *pos;
168525511a47STejun Heo 	int i;
168625511a47STejun Heo 
168725511a47STejun Heo 	lockdep_assert_held(&gcwq->lock);
168825511a47STejun Heo 
168925511a47STejun Heo 	for_each_worker_pool(pool, gcwq)
169025511a47STejun Heo 		lockdep_assert_held(&pool->manager_mutex);
169125511a47STejun Heo 
169225511a47STejun Heo 	/*
169325511a47STejun Heo 	 * Rebind idle workers.  Interlocked both ways.  We wait for
169425511a47STejun Heo 	 * workers to rebind via @idle_rebind.done.  Workers will wait for
169525511a47STejun Heo 	 * us to finish up by watching %WORKER_REBIND.
169625511a47STejun Heo 	 */
169725511a47STejun Heo 	init_completion(&idle_rebind.done);
169825511a47STejun Heo retry:
169925511a47STejun Heo 	idle_rebind.cnt = 1;
170025511a47STejun Heo 	INIT_COMPLETION(idle_rebind.done);
170125511a47STejun Heo 
170225511a47STejun Heo 	/* set REBIND and kick idle ones, we'll wait for these later */
170325511a47STejun Heo 	for_each_worker_pool(pool, gcwq) {
170425511a47STejun Heo 		list_for_each_entry(worker, &pool->idle_list, entry) {
170525511a47STejun Heo 			if (worker->flags & WORKER_REBIND)
170625511a47STejun Heo 				continue;
170725511a47STejun Heo 
170825511a47STejun Heo 			/* morph UNBOUND to REBIND */
170925511a47STejun Heo 			worker->flags &= ~WORKER_UNBOUND;
171025511a47STejun Heo 			worker->flags |= WORKER_REBIND;
171125511a47STejun Heo 
171225511a47STejun Heo 			idle_rebind.cnt++;
171325511a47STejun Heo 			worker->idle_rebind = &idle_rebind;
171425511a47STejun Heo 
171525511a47STejun Heo 			/* worker_thread() will call idle_worker_rebind() */
171625511a47STejun Heo 			wake_up_process(worker->task);
171725511a47STejun Heo 		}
171825511a47STejun Heo 	}
171925511a47STejun Heo 
172025511a47STejun Heo 	if (--idle_rebind.cnt) {
172125511a47STejun Heo 		spin_unlock_irq(&gcwq->lock);
172225511a47STejun Heo 		wait_for_completion(&idle_rebind.done);
172325511a47STejun Heo 		spin_lock_irq(&gcwq->lock);
172425511a47STejun Heo 		/* busy ones might have become idle while waiting, retry */
172525511a47STejun Heo 		goto retry;
172625511a47STejun Heo 	}
172725511a47STejun Heo 
172825511a47STejun Heo 	/*
172925511a47STejun Heo 	 * All idle workers are rebound and waiting for %WORKER_REBIND to
173025511a47STejun Heo 	 * be cleared inside idle_worker_rebind().  Clear and release.
173125511a47STejun Heo 	 * Clearing %WORKER_REBIND from this foreign context is safe
173225511a47STejun Heo 	 * because these workers are still guaranteed to be idle.
173325511a47STejun Heo 	 */
173425511a47STejun Heo 	for_each_worker_pool(pool, gcwq)
173525511a47STejun Heo 		list_for_each_entry(worker, &pool->idle_list, entry)
173625511a47STejun Heo 			worker->flags &= ~WORKER_REBIND;
173725511a47STejun Heo 
173825511a47STejun Heo 	wake_up_all(&gcwq->rebind_hold);
173925511a47STejun Heo 
174025511a47STejun Heo 	/* rebind busy workers */
174125511a47STejun Heo 	for_each_busy_worker(worker, i, pos, gcwq) {
174225511a47STejun Heo 		struct work_struct *rebind_work = &worker->rebind_work;
1743e2b6a6d5SJoonsoo Kim 		struct workqueue_struct *wq;
174425511a47STejun Heo 
174525511a47STejun Heo 		/* morph UNBOUND to REBIND */
174625511a47STejun Heo 		worker->flags &= ~WORKER_UNBOUND;
174725511a47STejun Heo 		worker->flags |= WORKER_REBIND;
174825511a47STejun Heo 
174925511a47STejun Heo 		if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
175025511a47STejun Heo 				     work_data_bits(rebind_work)))
175125511a47STejun Heo 			continue;
175225511a47STejun Heo 
175325511a47STejun Heo 		debug_work_activate(rebind_work);
1754e2b6a6d5SJoonsoo Kim 
1755e2b6a6d5SJoonsoo Kim 		/*
1756e2b6a6d5SJoonsoo Kim 		 * wq doesn't really matter but let's keep @worker->pool
1757e2b6a6d5SJoonsoo Kim 		 * and @cwq->pool consistent for sanity.
1758e2b6a6d5SJoonsoo Kim 		 */
1759e2b6a6d5SJoonsoo Kim 		if (worker_pool_pri(worker->pool))
1760e2b6a6d5SJoonsoo Kim 			wq = system_highpri_wq;
1761e2b6a6d5SJoonsoo Kim 		else
1762e2b6a6d5SJoonsoo Kim 			wq = system_wq;
1763e2b6a6d5SJoonsoo Kim 
1764e2b6a6d5SJoonsoo Kim 		insert_work(get_cwq(gcwq->cpu, wq), rebind_work,
176525511a47STejun Heo 			worker->scheduled.next,
176625511a47STejun Heo 			work_color_to_flags(WORK_NO_COLOR));
176725511a47STejun Heo 	}
176825511a47STejun Heo }
176925511a47STejun Heo 
1770c34056a3STejun Heo static struct worker *alloc_worker(void)
1771c34056a3STejun Heo {
1772c34056a3STejun Heo 	struct worker *worker;
1773c34056a3STejun Heo 
1774c34056a3STejun Heo 	worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1775c8e55f36STejun Heo 	if (worker) {
1776c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
1777affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
177825511a47STejun Heo 		INIT_WORK(&worker->rebind_work, busy_worker_rebind_fn);
1779e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
1780e22bee78STejun Heo 		worker->flags = WORKER_PREP;
1781c8e55f36STejun Heo 	}
1782c34056a3STejun Heo 	return worker;
1783c34056a3STejun Heo }
1784c34056a3STejun Heo 
1785c34056a3STejun Heo /**
1786c34056a3STejun Heo  * create_worker - create a new workqueue worker
178763d95a91STejun Heo  * @pool: pool the new worker will belong to
1788c34056a3STejun Heo  *
178963d95a91STejun Heo  * Create a new worker which is bound to @pool.  The returned worker
1790c34056a3STejun Heo  * can be started by calling start_worker() or destroyed using
1791c34056a3STejun Heo  * destroy_worker().
1792c34056a3STejun Heo  *
1793c34056a3STejun Heo  * CONTEXT:
1794c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
1795c34056a3STejun Heo  *
1796c34056a3STejun Heo  * RETURNS:
1797c34056a3STejun Heo  * Pointer to the newly created worker.
1798c34056a3STejun Heo  */
1799bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
1800c34056a3STejun Heo {
180163d95a91STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
18023270476aSTejun Heo 	const char *pri = worker_pool_pri(pool) ? "H" : "";
1803c34056a3STejun Heo 	struct worker *worker = NULL;
1804f3421797STejun Heo 	int id = -1;
1805c34056a3STejun Heo 
18068b03ae3cSTejun Heo 	spin_lock_irq(&gcwq->lock);
1807bd7bdd43STejun Heo 	while (ida_get_new(&pool->worker_ida, &id)) {
18088b03ae3cSTejun Heo 		spin_unlock_irq(&gcwq->lock);
1809bd7bdd43STejun Heo 		if (!ida_pre_get(&pool->worker_ida, GFP_KERNEL))
1810c34056a3STejun Heo 			goto fail;
18118b03ae3cSTejun Heo 		spin_lock_irq(&gcwq->lock);
1812c34056a3STejun Heo 	}
18138b03ae3cSTejun Heo 	spin_unlock_irq(&gcwq->lock);
1814c34056a3STejun Heo 
1815c34056a3STejun Heo 	worker = alloc_worker();
1816c34056a3STejun Heo 	if (!worker)
1817c34056a3STejun Heo 		goto fail;
1818c34056a3STejun Heo 
1819bd7bdd43STejun Heo 	worker->pool = pool;
1820c34056a3STejun Heo 	worker->id = id;
1821c34056a3STejun Heo 
1822bc2ae0f5STejun Heo 	if (gcwq->cpu != WORK_CPU_UNBOUND)
182394dcf29aSEric Dumazet 		worker->task = kthread_create_on_node(worker_thread,
18243270476aSTejun Heo 					worker, cpu_to_node(gcwq->cpu),
18253270476aSTejun Heo 					"kworker/%u:%d%s", gcwq->cpu, id, pri);
1826f3421797STejun Heo 	else
1827f3421797STejun Heo 		worker->task = kthread_create(worker_thread, worker,
18283270476aSTejun Heo 					      "kworker/u:%d%s", id, pri);
1829c34056a3STejun Heo 	if (IS_ERR(worker->task))
1830c34056a3STejun Heo 		goto fail;
1831c34056a3STejun Heo 
18323270476aSTejun Heo 	if (worker_pool_pri(pool))
18333270476aSTejun Heo 		set_user_nice(worker->task, HIGHPRI_NICE_LEVEL);
18343270476aSTejun Heo 
1835db7bccf4STejun Heo 	/*
1836bc2ae0f5STejun Heo 	 * Determine CPU binding of the new worker depending on
1837bc2ae0f5STejun Heo 	 * %GCWQ_DISASSOCIATED.  The caller is responsible for ensuring the
1838bc2ae0f5STejun Heo 	 * flag remains stable across this function.  See the comments
1839bc2ae0f5STejun Heo 	 * above the flag definition for details.
1840bc2ae0f5STejun Heo 	 *
1841bc2ae0f5STejun Heo 	 * As an unbound worker may later become a regular one if CPU comes
1842bc2ae0f5STejun Heo 	 * online, make sure every worker has %PF_THREAD_BOUND set.
1843db7bccf4STejun Heo 	 */
1844bc2ae0f5STejun Heo 	if (!(gcwq->flags & GCWQ_DISASSOCIATED)) {
18458b03ae3cSTejun Heo 		kthread_bind(worker->task, gcwq->cpu);
1846bc2ae0f5STejun Heo 	} else {
1847db7bccf4STejun Heo 		worker->task->flags |= PF_THREAD_BOUND;
1848f3421797STejun Heo 		worker->flags |= WORKER_UNBOUND;
1849f3421797STejun Heo 	}
1850c34056a3STejun Heo 
1851c34056a3STejun Heo 	return worker;
1852c34056a3STejun Heo fail:
1853c34056a3STejun Heo 	if (id >= 0) {
18548b03ae3cSTejun Heo 		spin_lock_irq(&gcwq->lock);
1855bd7bdd43STejun Heo 		ida_remove(&pool->worker_ida, id);
18568b03ae3cSTejun Heo 		spin_unlock_irq(&gcwq->lock);
1857c34056a3STejun Heo 	}
1858c34056a3STejun Heo 	kfree(worker);
1859c34056a3STejun Heo 	return NULL;
1860c34056a3STejun Heo }
1861c34056a3STejun Heo 
1862c34056a3STejun Heo /**
1863c34056a3STejun Heo  * start_worker - start a newly created worker
1864c34056a3STejun Heo  * @worker: worker to start
1865c34056a3STejun Heo  *
1866c8e55f36STejun Heo  * Make the gcwq aware of @worker and start it.
1867c34056a3STejun Heo  *
1868c34056a3STejun Heo  * CONTEXT:
18698b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock).
1870c34056a3STejun Heo  */
1871c34056a3STejun Heo static void start_worker(struct worker *worker)
1872c34056a3STejun Heo {
1873cb444766STejun Heo 	worker->flags |= WORKER_STARTED;
1874bd7bdd43STejun Heo 	worker->pool->nr_workers++;
1875c8e55f36STejun Heo 	worker_enter_idle(worker);
1876c34056a3STejun Heo 	wake_up_process(worker->task);
1877c34056a3STejun Heo }
1878c34056a3STejun Heo 
1879c34056a3STejun Heo /**
1880c34056a3STejun Heo  * destroy_worker - destroy a workqueue worker
1881c34056a3STejun Heo  * @worker: worker to be destroyed
1882c34056a3STejun Heo  *
1883c8e55f36STejun Heo  * Destroy @worker and adjust @gcwq stats accordingly.
1884c8e55f36STejun Heo  *
1885c8e55f36STejun Heo  * CONTEXT:
1886c8e55f36STejun Heo  * spin_lock_irq(gcwq->lock) which is released and regrabbed.
1887c34056a3STejun Heo  */
1888c34056a3STejun Heo static void destroy_worker(struct worker *worker)
1889c34056a3STejun Heo {
1890bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1891bd7bdd43STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
1892c34056a3STejun Heo 	int id = worker->id;
1893c34056a3STejun Heo 
1894c34056a3STejun Heo 	/* sanity check frenzy */
1895c34056a3STejun Heo 	BUG_ON(worker->current_work);
1896affee4b2STejun Heo 	BUG_ON(!list_empty(&worker->scheduled));
1897c34056a3STejun Heo 
1898c8e55f36STejun Heo 	if (worker->flags & WORKER_STARTED)
1899bd7bdd43STejun Heo 		pool->nr_workers--;
1900c8e55f36STejun Heo 	if (worker->flags & WORKER_IDLE)
1901bd7bdd43STejun Heo 		pool->nr_idle--;
1902c8e55f36STejun Heo 
1903c8e55f36STejun Heo 	list_del_init(&worker->entry);
1904cb444766STejun Heo 	worker->flags |= WORKER_DIE;
1905c8e55f36STejun Heo 
1906c8e55f36STejun Heo 	spin_unlock_irq(&gcwq->lock);
1907c8e55f36STejun Heo 
1908c34056a3STejun Heo 	kthread_stop(worker->task);
1909c34056a3STejun Heo 	kfree(worker);
1910c34056a3STejun Heo 
19118b03ae3cSTejun Heo 	spin_lock_irq(&gcwq->lock);
1912bd7bdd43STejun Heo 	ida_remove(&pool->worker_ida, id);
1913c34056a3STejun Heo }
1914c34056a3STejun Heo 
191563d95a91STejun Heo static void idle_worker_timeout(unsigned long __pool)
1916e22bee78STejun Heo {
191763d95a91STejun Heo 	struct worker_pool *pool = (void *)__pool;
191863d95a91STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
1919e22bee78STejun Heo 
1920e22bee78STejun Heo 	spin_lock_irq(&gcwq->lock);
1921e22bee78STejun Heo 
192263d95a91STejun Heo 	if (too_many_workers(pool)) {
1923e22bee78STejun Heo 		struct worker *worker;
1924e22bee78STejun Heo 		unsigned long expires;
1925e22bee78STejun Heo 
1926e22bee78STejun Heo 		/* idle_list is kept in LIFO order, check the last one */
192763d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
1928e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1929e22bee78STejun Heo 
1930e22bee78STejun Heo 		if (time_before(jiffies, expires))
193163d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
1932e22bee78STejun Heo 		else {
1933e22bee78STejun Heo 			/* it's been idle for too long, wake up manager */
193411ebea50STejun Heo 			pool->flags |= POOL_MANAGE_WORKERS;
193563d95a91STejun Heo 			wake_up_worker(pool);
1936e22bee78STejun Heo 		}
1937e22bee78STejun Heo 	}
1938e22bee78STejun Heo 
1939e22bee78STejun Heo 	spin_unlock_irq(&gcwq->lock);
1940e22bee78STejun Heo }
1941e22bee78STejun Heo 
1942e22bee78STejun Heo static bool send_mayday(struct work_struct *work)
1943e22bee78STejun Heo {
1944e22bee78STejun Heo 	struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1945e22bee78STejun Heo 	struct workqueue_struct *wq = cwq->wq;
1946f3421797STejun Heo 	unsigned int cpu;
1947e22bee78STejun Heo 
1948e22bee78STejun Heo 	if (!(wq->flags & WQ_RESCUER))
1949e22bee78STejun Heo 		return false;
1950e22bee78STejun Heo 
1951e22bee78STejun Heo 	/* mayday mayday mayday */
1952bd7bdd43STejun Heo 	cpu = cwq->pool->gcwq->cpu;
1953f3421797STejun Heo 	/* WORK_CPU_UNBOUND can't be set in cpumask, use cpu 0 instead */
1954f3421797STejun Heo 	if (cpu == WORK_CPU_UNBOUND)
1955f3421797STejun Heo 		cpu = 0;
1956f2e005aaSTejun Heo 	if (!mayday_test_and_set_cpu(cpu, wq->mayday_mask))
1957e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
1958e22bee78STejun Heo 	return true;
1959e22bee78STejun Heo }
1960e22bee78STejun Heo 
196163d95a91STejun Heo static void gcwq_mayday_timeout(unsigned long __pool)
1962e22bee78STejun Heo {
196363d95a91STejun Heo 	struct worker_pool *pool = (void *)__pool;
196463d95a91STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
1965e22bee78STejun Heo 	struct work_struct *work;
1966e22bee78STejun Heo 
1967e22bee78STejun Heo 	spin_lock_irq(&gcwq->lock);
1968e22bee78STejun Heo 
196963d95a91STejun Heo 	if (need_to_create_worker(pool)) {
1970e22bee78STejun Heo 		/*
1971e22bee78STejun Heo 		 * We've been trying to create a new worker but
1972e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
1973e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
1974e22bee78STejun Heo 		 * rescuers.
1975e22bee78STejun Heo 		 */
197663d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
1977e22bee78STejun Heo 			send_mayday(work);
1978e22bee78STejun Heo 	}
1979e22bee78STejun Heo 
1980e22bee78STejun Heo 	spin_unlock_irq(&gcwq->lock);
1981e22bee78STejun Heo 
198263d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1983e22bee78STejun Heo }
1984e22bee78STejun Heo 
1985e22bee78STejun Heo /**
1986e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
198763d95a91STejun Heo  * @pool: pool to create a new worker for
1988e22bee78STejun Heo  *
198963d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
1990e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
1991e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
199263d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
1993e22bee78STejun Heo  * possible allocation deadlock.
1994e22bee78STejun Heo  *
1995e22bee78STejun Heo  * On return, need_to_create_worker() is guaranteed to be false and
1996e22bee78STejun Heo  * may_start_working() true.
1997e22bee78STejun Heo  *
1998e22bee78STejun Heo  * LOCKING:
1999e22bee78STejun Heo  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2000e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
2001e22bee78STejun Heo  * manager.
2002e22bee78STejun Heo  *
2003e22bee78STejun Heo  * RETURNS:
2004e22bee78STejun Heo  * false if no action was taken and gcwq->lock stayed locked, true
2005e22bee78STejun Heo  * otherwise.
2006e22bee78STejun Heo  */
200763d95a91STejun Heo static bool maybe_create_worker(struct worker_pool *pool)
200806bd6ebfSNamhyung Kim __releases(&gcwq->lock)
200906bd6ebfSNamhyung Kim __acquires(&gcwq->lock)
2010e22bee78STejun Heo {
201163d95a91STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
201263d95a91STejun Heo 
201363d95a91STejun Heo 	if (!need_to_create_worker(pool))
2014e22bee78STejun Heo 		return false;
2015e22bee78STejun Heo restart:
20169f9c2364STejun Heo 	spin_unlock_irq(&gcwq->lock);
20179f9c2364STejun Heo 
2018e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
201963d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
2020e22bee78STejun Heo 
2021e22bee78STejun Heo 	while (true) {
2022e22bee78STejun Heo 		struct worker *worker;
2023e22bee78STejun Heo 
2024bc2ae0f5STejun Heo 		worker = create_worker(pool);
2025e22bee78STejun Heo 		if (worker) {
202663d95a91STejun Heo 			del_timer_sync(&pool->mayday_timer);
2027e22bee78STejun Heo 			spin_lock_irq(&gcwq->lock);
2028e22bee78STejun Heo 			start_worker(worker);
202963d95a91STejun Heo 			BUG_ON(need_to_create_worker(pool));
2030e22bee78STejun Heo 			return true;
2031e22bee78STejun Heo 		}
2032e22bee78STejun Heo 
203363d95a91STejun Heo 		if (!need_to_create_worker(pool))
2034e22bee78STejun Heo 			break;
2035e22bee78STejun Heo 
2036e22bee78STejun Heo 		__set_current_state(TASK_INTERRUPTIBLE);
2037e22bee78STejun Heo 		schedule_timeout(CREATE_COOLDOWN);
20389f9c2364STejun Heo 
203963d95a91STejun Heo 		if (!need_to_create_worker(pool))
2040e22bee78STejun Heo 			break;
2041e22bee78STejun Heo 	}
2042e22bee78STejun Heo 
204363d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
2044e22bee78STejun Heo 	spin_lock_irq(&gcwq->lock);
204563d95a91STejun Heo 	if (need_to_create_worker(pool))
2046e22bee78STejun Heo 		goto restart;
2047e22bee78STejun Heo 	return true;
2048e22bee78STejun Heo }
2049e22bee78STejun Heo 
2050e22bee78STejun Heo /**
2051e22bee78STejun Heo  * maybe_destroy_worker - destroy workers which have been idle for a while
205263d95a91STejun Heo  * @pool: pool to destroy workers for
2053e22bee78STejun Heo  *
205463d95a91STejun Heo  * Destroy @pool workers which have been idle for longer than
2055e22bee78STejun Heo  * IDLE_WORKER_TIMEOUT.
2056e22bee78STejun Heo  *
2057e22bee78STejun Heo  * LOCKING:
2058e22bee78STejun Heo  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2059e22bee78STejun Heo  * multiple times.  Called only from manager.
2060e22bee78STejun Heo  *
2061e22bee78STejun Heo  * RETURNS:
2062e22bee78STejun Heo  * false if no action was taken and gcwq->lock stayed locked, true
2063e22bee78STejun Heo  * otherwise.
2064e22bee78STejun Heo  */
206563d95a91STejun Heo static bool maybe_destroy_workers(struct worker_pool *pool)
2066e22bee78STejun Heo {
2067e22bee78STejun Heo 	bool ret = false;
2068e22bee78STejun Heo 
206963d95a91STejun Heo 	while (too_many_workers(pool)) {
2070e22bee78STejun Heo 		struct worker *worker;
2071e22bee78STejun Heo 		unsigned long expires;
2072e22bee78STejun Heo 
207363d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
2074e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2075e22bee78STejun Heo 
2076e22bee78STejun Heo 		if (time_before(jiffies, expires)) {
207763d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
2078e22bee78STejun Heo 			break;
2079e22bee78STejun Heo 		}
2080e22bee78STejun Heo 
2081e22bee78STejun Heo 		destroy_worker(worker);
2082e22bee78STejun Heo 		ret = true;
2083e22bee78STejun Heo 	}
2084e22bee78STejun Heo 
2085e22bee78STejun Heo 	return ret;
2086e22bee78STejun Heo }
2087e22bee78STejun Heo 
2088e22bee78STejun Heo /**
2089e22bee78STejun Heo  * manage_workers - manage worker pool
2090e22bee78STejun Heo  * @worker: self
2091e22bee78STejun Heo  *
2092e22bee78STejun Heo  * Assume the manager role and manage gcwq worker pool @worker belongs
2093e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
2094e22bee78STejun Heo  * gcwq.  The exclusion is handled automatically by this function.
2095e22bee78STejun Heo  *
2096e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
2097e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
2098e22bee78STejun Heo  * and may_start_working() is true.
2099e22bee78STejun Heo  *
2100e22bee78STejun Heo  * CONTEXT:
2101e22bee78STejun Heo  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2102e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
2103e22bee78STejun Heo  *
2104e22bee78STejun Heo  * RETURNS:
2105e22bee78STejun Heo  * false if no action was taken and gcwq->lock stayed locked, true if
2106e22bee78STejun Heo  * some action was taken.
2107e22bee78STejun Heo  */
2108e22bee78STejun Heo static bool manage_workers(struct worker *worker)
2109e22bee78STejun Heo {
211063d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
2111e22bee78STejun Heo 	bool ret = false;
2112e22bee78STejun Heo 
211360373152STejun Heo 	if (!mutex_trylock(&pool->manager_mutex))
2114e22bee78STejun Heo 		return ret;
2115e22bee78STejun Heo 
211611ebea50STejun Heo 	pool->flags &= ~POOL_MANAGE_WORKERS;
2117e22bee78STejun Heo 
2118e22bee78STejun Heo 	/*
2119e22bee78STejun Heo 	 * Destroy and then create so that may_start_working() is true
2120e22bee78STejun Heo 	 * on return.
2121e22bee78STejun Heo 	 */
212263d95a91STejun Heo 	ret |= maybe_destroy_workers(pool);
212363d95a91STejun Heo 	ret |= maybe_create_worker(pool);
2124e22bee78STejun Heo 
212560373152STejun Heo 	mutex_unlock(&pool->manager_mutex);
2126e22bee78STejun Heo 	return ret;
2127e22bee78STejun Heo }
2128e22bee78STejun Heo 
2129a62428c0STejun Heo /**
2130a62428c0STejun Heo  * process_one_work - process single work
2131c34056a3STejun Heo  * @worker: self
2132a62428c0STejun Heo  * @work: work to process
2133a62428c0STejun Heo  *
2134a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
2135a62428c0STejun Heo  * process a single work including synchronization against and
2136a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
2137a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
2138a62428c0STejun Heo  * call this function to process a work.
2139a62428c0STejun Heo  *
2140a62428c0STejun Heo  * CONTEXT:
21418b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock) which is released and regrabbed.
2142a62428c0STejun Heo  */
2143c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
214406bd6ebfSNamhyung Kim __releases(&gcwq->lock)
214506bd6ebfSNamhyung Kim __acquires(&gcwq->lock)
21461da177e4SLinus Torvalds {
21477e11629dSTejun Heo 	struct cpu_workqueue_struct *cwq = get_work_cwq(work);
2148bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2149bd7bdd43STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
2150c8e55f36STejun Heo 	struct hlist_head *bwh = busy_worker_head(gcwq, work);
2151fb0e7bebSTejun Heo 	bool cpu_intensive = cwq->wq->flags & WQ_CPU_INTENSIVE;
21526bb49e59SDavid Howells 	work_func_t f = work->func;
215373f53c4aSTejun Heo 	int work_color;
21547e11629dSTejun Heo 	struct worker *collision;
21554e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
21564e6045f1SJohannes Berg 	/*
2157a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
2158a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
2159a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
2160a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
2161a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
21624e6045f1SJohannes Berg 	 */
21634d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
21644d82a1deSPeter Zijlstra 
21654d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
21664e6045f1SJohannes Berg #endif
21676fec10a1STejun Heo 	/*
21686fec10a1STejun Heo 	 * Ensure we're on the correct CPU.  DISASSOCIATED test is
21696fec10a1STejun Heo 	 * necessary to avoid spurious warnings from rescuers servicing the
21706fec10a1STejun Heo 	 * unbound or a disassociated gcwq.
21716fec10a1STejun Heo 	 */
217225511a47STejun Heo 	WARN_ON_ONCE(!(worker->flags & (WORKER_UNBOUND | WORKER_REBIND)) &&
21736fec10a1STejun Heo 		     !(gcwq->flags & GCWQ_DISASSOCIATED) &&
217425511a47STejun Heo 		     raw_smp_processor_id() != gcwq->cpu);
217525511a47STejun Heo 
21767e11629dSTejun Heo 	/*
21777e11629dSTejun Heo 	 * A single work shouldn't be executed concurrently by
21787e11629dSTejun Heo 	 * multiple workers on a single cpu.  Check whether anyone is
21797e11629dSTejun Heo 	 * already processing the work.  If so, defer the work to the
21807e11629dSTejun Heo 	 * currently executing one.
21817e11629dSTejun Heo 	 */
21827e11629dSTejun Heo 	collision = __find_worker_executing_work(gcwq, bwh, work);
21837e11629dSTejun Heo 	if (unlikely(collision)) {
21847e11629dSTejun Heo 		move_linked_works(work, &collision->scheduled, NULL);
21857e11629dSTejun Heo 		return;
21867e11629dSTejun Heo 	}
21871da177e4SLinus Torvalds 
21888930cabaSTejun Heo 	/* claim and dequeue */
21891da177e4SLinus Torvalds 	debug_work_deactivate(work);
2190c8e55f36STejun Heo 	hlist_add_head(&worker->hentry, bwh);
2191c34056a3STejun Heo 	worker->current_work = work;
21928cca0eeaSTejun Heo 	worker->current_cwq = cwq;
219373f53c4aSTejun Heo 	work_color = get_work_color(work);
21947a22ad75STejun Heo 
2195a62428c0STejun Heo 	list_del_init(&work->entry);
2196a62428c0STejun Heo 
2197649027d7STejun Heo 	/*
2198fb0e7bebSTejun Heo 	 * CPU intensive works don't participate in concurrency
2199fb0e7bebSTejun Heo 	 * management.  They're the scheduler's responsibility.
2200fb0e7bebSTejun Heo 	 */
2201fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2202fb0e7bebSTejun Heo 		worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
2203fb0e7bebSTejun Heo 
2204974271c4STejun Heo 	/*
2205974271c4STejun Heo 	 * Unbound gcwq isn't concurrency managed and work items should be
2206974271c4STejun Heo 	 * executed ASAP.  Wake up another worker if necessary.
2207974271c4STejun Heo 	 */
220863d95a91STejun Heo 	if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
220963d95a91STejun Heo 		wake_up_worker(pool);
2210974271c4STejun Heo 
22118930cabaSTejun Heo 	/*
221223657bb1STejun Heo 	 * Record the last CPU and clear PENDING which should be the last
221323657bb1STejun Heo 	 * update to @work.  Also, do this inside @gcwq->lock so that
221423657bb1STejun Heo 	 * PENDING and queued state changes happen together while IRQ is
221523657bb1STejun Heo 	 * disabled.
22168930cabaSTejun Heo 	 */
22178930cabaSTejun Heo 	set_work_cpu_and_clear_pending(work, gcwq->cpu);
22181da177e4SLinus Torvalds 
22198930cabaSTejun Heo 	spin_unlock_irq(&gcwq->lock);
2220959d1af8STejun Heo 
2221e159489bSTejun Heo 	lock_map_acquire_read(&cwq->wq->lockdep_map);
22223295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
2223e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
222465f27f38SDavid Howells 	f(work);
2225e36c886aSArjan van de Ven 	/*
2226e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
2227e36c886aSArjan van de Ven 	 * point will only record its address.
2228e36c886aSArjan van de Ven 	 */
2229e36c886aSArjan van de Ven 	trace_workqueue_execute_end(work);
22303295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
22313295f0efSIngo Molnar 	lock_map_release(&cwq->wq->lockdep_map);
22321da177e4SLinus Torvalds 
2233d5abe669SPeter Zijlstra 	if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2234044c782cSValentin Ilie 		pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2235044c782cSValentin Ilie 		       "     last function: %pf\n",
2236044c782cSValentin Ilie 		       current->comm, preempt_count(), task_pid_nr(current), f);
2237d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
2238d5abe669SPeter Zijlstra 		dump_stack();
2239d5abe669SPeter Zijlstra 	}
2240d5abe669SPeter Zijlstra 
22418b03ae3cSTejun Heo 	spin_lock_irq(&gcwq->lock);
2242a62428c0STejun Heo 
2243fb0e7bebSTejun Heo 	/* clear cpu intensive status */
2244fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2245fb0e7bebSTejun Heo 		worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2246fb0e7bebSTejun Heo 
2247a62428c0STejun Heo 	/* we're done with it, release */
2248c8e55f36STejun Heo 	hlist_del_init(&worker->hentry);
2249c34056a3STejun Heo 	worker->current_work = NULL;
22508cca0eeaSTejun Heo 	worker->current_cwq = NULL;
22518a2e8e5dSTejun Heo 	cwq_dec_nr_in_flight(cwq, work_color, false);
22521da177e4SLinus Torvalds }
22531da177e4SLinus Torvalds 
2254affee4b2STejun Heo /**
2255affee4b2STejun Heo  * process_scheduled_works - process scheduled works
2256affee4b2STejun Heo  * @worker: self
2257affee4b2STejun Heo  *
2258affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
2259affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
2260affee4b2STejun Heo  * fetches a work from the top and executes it.
2261affee4b2STejun Heo  *
2262affee4b2STejun Heo  * CONTEXT:
22638b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2264affee4b2STejun Heo  * multiple times.
2265affee4b2STejun Heo  */
2266affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
22671da177e4SLinus Torvalds {
2268affee4b2STejun Heo 	while (!list_empty(&worker->scheduled)) {
2269affee4b2STejun Heo 		struct work_struct *work = list_first_entry(&worker->scheduled,
2270a62428c0STejun Heo 						struct work_struct, entry);
2271c34056a3STejun Heo 		process_one_work(worker, work);
2272a62428c0STejun Heo 	}
22731da177e4SLinus Torvalds }
22741da177e4SLinus Torvalds 
22754690c4abSTejun Heo /**
22764690c4abSTejun Heo  * worker_thread - the worker thread function
2277c34056a3STejun Heo  * @__worker: self
22784690c4abSTejun Heo  *
2279e22bee78STejun Heo  * The gcwq worker thread function.  There's a single dynamic pool of
2280e22bee78STejun Heo  * these per each cpu.  These workers process all works regardless of
2281e22bee78STejun Heo  * their specific target workqueue.  The only exception is works which
2282e22bee78STejun Heo  * belong to workqueues with a rescuer which will be explained in
2283e22bee78STejun Heo  * rescuer_thread().
22844690c4abSTejun Heo  */
2285c34056a3STejun Heo static int worker_thread(void *__worker)
22861da177e4SLinus Torvalds {
2287c34056a3STejun Heo 	struct worker *worker = __worker;
2288bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2289bd7bdd43STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
22901da177e4SLinus Torvalds 
2291e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
2292e22bee78STejun Heo 	worker->task->flags |= PF_WQ_WORKER;
2293c8e55f36STejun Heo woke_up:
22948b03ae3cSTejun Heo 	spin_lock_irq(&gcwq->lock);
2295affee4b2STejun Heo 
229625511a47STejun Heo 	/*
229725511a47STejun Heo 	 * DIE can be set only while idle and REBIND set while busy has
229825511a47STejun Heo 	 * @worker->rebind_work scheduled.  Checking here is enough.
229925511a47STejun Heo 	 */
230025511a47STejun Heo 	if (unlikely(worker->flags & (WORKER_REBIND | WORKER_DIE))) {
2301c8e55f36STejun Heo 		spin_unlock_irq(&gcwq->lock);
230225511a47STejun Heo 
230325511a47STejun Heo 		if (worker->flags & WORKER_DIE) {
2304e22bee78STejun Heo 			worker->task->flags &= ~PF_WQ_WORKER;
2305c8e55f36STejun Heo 			return 0;
2306c8e55f36STejun Heo 		}
2307c8e55f36STejun Heo 
230825511a47STejun Heo 		idle_worker_rebind(worker);
230925511a47STejun Heo 		goto woke_up;
231025511a47STejun Heo 	}
231125511a47STejun Heo 
2312c8e55f36STejun Heo 	worker_leave_idle(worker);
2313db7bccf4STejun Heo recheck:
2314e22bee78STejun Heo 	/* no more worker necessary? */
231563d95a91STejun Heo 	if (!need_more_worker(pool))
2316e22bee78STejun Heo 		goto sleep;
2317e22bee78STejun Heo 
2318e22bee78STejun Heo 	/* do we need to manage? */
231963d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2320e22bee78STejun Heo 		goto recheck;
2321e22bee78STejun Heo 
2322c8e55f36STejun Heo 	/*
2323c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
2324c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
2325c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
2326c8e55f36STejun Heo 	 */
2327c8e55f36STejun Heo 	BUG_ON(!list_empty(&worker->scheduled));
2328c8e55f36STejun Heo 
2329e22bee78STejun Heo 	/*
2330e22bee78STejun Heo 	 * When control reaches this point, we're guaranteed to have
2331e22bee78STejun Heo 	 * at least one idle worker or that someone else has already
2332e22bee78STejun Heo 	 * assumed the manager role.
2333e22bee78STejun Heo 	 */
2334e22bee78STejun Heo 	worker_clr_flags(worker, WORKER_PREP);
2335e22bee78STejun Heo 
2336e22bee78STejun Heo 	do {
2337affee4b2STejun Heo 		struct work_struct *work =
2338bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
2339affee4b2STejun Heo 					 struct work_struct, entry);
2340affee4b2STejun Heo 
2341c8e55f36STejun Heo 		if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2342affee4b2STejun Heo 			/* optimization path, not strictly necessary */
2343affee4b2STejun Heo 			process_one_work(worker, work);
2344affee4b2STejun Heo 			if (unlikely(!list_empty(&worker->scheduled)))
2345affee4b2STejun Heo 				process_scheduled_works(worker);
2346affee4b2STejun Heo 		} else {
2347c8e55f36STejun Heo 			move_linked_works(work, &worker->scheduled, NULL);
2348affee4b2STejun Heo 			process_scheduled_works(worker);
2349affee4b2STejun Heo 		}
235063d95a91STejun Heo 	} while (keep_working(pool));
2351affee4b2STejun Heo 
2352e22bee78STejun Heo 	worker_set_flags(worker, WORKER_PREP, false);
2353d313dd85STejun Heo sleep:
235463d95a91STejun Heo 	if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
2355e22bee78STejun Heo 		goto recheck;
2356d313dd85STejun Heo 
2357c8e55f36STejun Heo 	/*
2358e22bee78STejun Heo 	 * gcwq->lock is held and there's no work to process and no
2359e22bee78STejun Heo 	 * need to manage, sleep.  Workers are woken up only while
2360e22bee78STejun Heo 	 * holding gcwq->lock or from local cpu, so setting the
2361e22bee78STejun Heo 	 * current state before releasing gcwq->lock is enough to
2362e22bee78STejun Heo 	 * prevent losing any event.
2363c8e55f36STejun Heo 	 */
2364c8e55f36STejun Heo 	worker_enter_idle(worker);
2365c8e55f36STejun Heo 	__set_current_state(TASK_INTERRUPTIBLE);
23668b03ae3cSTejun Heo 	spin_unlock_irq(&gcwq->lock);
23671da177e4SLinus Torvalds 	schedule();
2368c8e55f36STejun Heo 	goto woke_up;
23691da177e4SLinus Torvalds }
23701da177e4SLinus Torvalds 
2371e22bee78STejun Heo /**
2372e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
2373e22bee78STejun Heo  * @__wq: the associated workqueue
2374e22bee78STejun Heo  *
2375e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
2376e22bee78STejun Heo  * workqueue which has WQ_RESCUER set.
2377e22bee78STejun Heo  *
2378e22bee78STejun Heo  * Regular work processing on a gcwq may block trying to create a new
2379e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
2380e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
2381e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2382e22bee78STejun Heo  * the problem rescuer solves.
2383e22bee78STejun Heo  *
2384e22bee78STejun Heo  * When such condition is possible, the gcwq summons rescuers of all
2385e22bee78STejun Heo  * workqueues which have works queued on the gcwq and let them process
2386e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
2387e22bee78STejun Heo  *
2388e22bee78STejun Heo  * This should happen rarely.
2389e22bee78STejun Heo  */
2390e22bee78STejun Heo static int rescuer_thread(void *__wq)
2391e22bee78STejun Heo {
2392e22bee78STejun Heo 	struct workqueue_struct *wq = __wq;
2393e22bee78STejun Heo 	struct worker *rescuer = wq->rescuer;
2394e22bee78STejun Heo 	struct list_head *scheduled = &rescuer->scheduled;
2395f3421797STejun Heo 	bool is_unbound = wq->flags & WQ_UNBOUND;
2396e22bee78STejun Heo 	unsigned int cpu;
2397e22bee78STejun Heo 
2398e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
2399e22bee78STejun Heo repeat:
2400e22bee78STejun Heo 	set_current_state(TASK_INTERRUPTIBLE);
24011da177e4SLinus Torvalds 
24021da177e4SLinus Torvalds 	if (kthread_should_stop())
2403e22bee78STejun Heo 		return 0;
24041da177e4SLinus Torvalds 
2405f3421797STejun Heo 	/*
2406f3421797STejun Heo 	 * See whether any cpu is asking for help.  Unbounded
2407f3421797STejun Heo 	 * workqueues use cpu 0 in mayday_mask for CPU_UNBOUND.
2408f3421797STejun Heo 	 */
2409f2e005aaSTejun Heo 	for_each_mayday_cpu(cpu, wq->mayday_mask) {
2410f3421797STejun Heo 		unsigned int tcpu = is_unbound ? WORK_CPU_UNBOUND : cpu;
2411f3421797STejun Heo 		struct cpu_workqueue_struct *cwq = get_cwq(tcpu, wq);
2412bd7bdd43STejun Heo 		struct worker_pool *pool = cwq->pool;
2413bd7bdd43STejun Heo 		struct global_cwq *gcwq = pool->gcwq;
2414e22bee78STejun Heo 		struct work_struct *work, *n;
2415e22bee78STejun Heo 
2416e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
2417f2e005aaSTejun Heo 		mayday_clear_cpu(cpu, wq->mayday_mask);
2418e22bee78STejun Heo 
2419e22bee78STejun Heo 		/* migrate to the target cpu if possible */
2420bd7bdd43STejun Heo 		rescuer->pool = pool;
2421e22bee78STejun Heo 		worker_maybe_bind_and_lock(rescuer);
2422e22bee78STejun Heo 
2423e22bee78STejun Heo 		/*
2424e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
2425e22bee78STejun Heo 		 * process'em.
2426e22bee78STejun Heo 		 */
2427e22bee78STejun Heo 		BUG_ON(!list_empty(&rescuer->scheduled));
2428bd7bdd43STejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry)
2429e22bee78STejun Heo 			if (get_work_cwq(work) == cwq)
2430e22bee78STejun Heo 				move_linked_works(work, scheduled, &n);
2431e22bee78STejun Heo 
2432e22bee78STejun Heo 		process_scheduled_works(rescuer);
24337576958aSTejun Heo 
24347576958aSTejun Heo 		/*
24357576958aSTejun Heo 		 * Leave this gcwq.  If keep_working() is %true, notify a
24367576958aSTejun Heo 		 * regular worker; otherwise, we end up with 0 concurrency
24377576958aSTejun Heo 		 * and stalling the execution.
24387576958aSTejun Heo 		 */
243963d95a91STejun Heo 		if (keep_working(pool))
244063d95a91STejun Heo 			wake_up_worker(pool);
24417576958aSTejun Heo 
2442e22bee78STejun Heo 		spin_unlock_irq(&gcwq->lock);
24431da177e4SLinus Torvalds 	}
24441da177e4SLinus Torvalds 
2445e22bee78STejun Heo 	schedule();
2446e22bee78STejun Heo 	goto repeat;
24471da177e4SLinus Torvalds }
24481da177e4SLinus Torvalds 
2449fc2e4d70SOleg Nesterov struct wq_barrier {
2450fc2e4d70SOleg Nesterov 	struct work_struct	work;
2451fc2e4d70SOleg Nesterov 	struct completion	done;
2452fc2e4d70SOleg Nesterov };
2453fc2e4d70SOleg Nesterov 
2454fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
2455fc2e4d70SOleg Nesterov {
2456fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2457fc2e4d70SOleg Nesterov 	complete(&barr->done);
2458fc2e4d70SOleg Nesterov }
2459fc2e4d70SOleg Nesterov 
24604690c4abSTejun Heo /**
24614690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
24624690c4abSTejun Heo  * @cwq: cwq to insert barrier into
24634690c4abSTejun Heo  * @barr: wq_barrier to insert
2464affee4b2STejun Heo  * @target: target work to attach @barr to
2465affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
24664690c4abSTejun Heo  *
2467affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
2468affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
2469affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
2470affee4b2STejun Heo  * cpu.
2471affee4b2STejun Heo  *
2472affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
2473affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
2474affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
2475affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
2476affee4b2STejun Heo  * after a work with LINKED flag set.
2477affee4b2STejun Heo  *
2478affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
2479affee4b2STejun Heo  * underneath us, so we can't reliably determine cwq from @target.
24804690c4abSTejun Heo  *
24814690c4abSTejun Heo  * CONTEXT:
24828b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock).
24834690c4abSTejun Heo  */
248483c22520SOleg Nesterov static void insert_wq_barrier(struct cpu_workqueue_struct *cwq,
2485affee4b2STejun Heo 			      struct wq_barrier *barr,
2486affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
2487fc2e4d70SOleg Nesterov {
2488affee4b2STejun Heo 	struct list_head *head;
2489affee4b2STejun Heo 	unsigned int linked = 0;
2490affee4b2STejun Heo 
2491dc186ad7SThomas Gleixner 	/*
24928b03ae3cSTejun Heo 	 * debugobject calls are safe here even with gcwq->lock locked
2493dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
2494dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
2495dc186ad7SThomas Gleixner 	 * might deadlock.
2496dc186ad7SThomas Gleixner 	 */
2497ca1cab37SAndrew Morton 	INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
249822df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2499fc2e4d70SOleg Nesterov 	init_completion(&barr->done);
250083c22520SOleg Nesterov 
2501affee4b2STejun Heo 	/*
2502affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
2503affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
2504affee4b2STejun Heo 	 */
2505affee4b2STejun Heo 	if (worker)
2506affee4b2STejun Heo 		head = worker->scheduled.next;
2507affee4b2STejun Heo 	else {
2508affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
2509affee4b2STejun Heo 
2510affee4b2STejun Heo 		head = target->entry.next;
2511affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
2512affee4b2STejun Heo 		linked = *bits & WORK_STRUCT_LINKED;
2513affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
2514affee4b2STejun Heo 	}
2515affee4b2STejun Heo 
2516dc186ad7SThomas Gleixner 	debug_work_activate(&barr->work);
2517affee4b2STejun Heo 	insert_work(cwq, &barr->work, head,
2518affee4b2STejun Heo 		    work_color_to_flags(WORK_NO_COLOR) | linked);
2519fc2e4d70SOleg Nesterov }
2520fc2e4d70SOleg Nesterov 
252173f53c4aSTejun Heo /**
252273f53c4aSTejun Heo  * flush_workqueue_prep_cwqs - prepare cwqs for workqueue flushing
252373f53c4aSTejun Heo  * @wq: workqueue being flushed
252473f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
252573f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
252673f53c4aSTejun Heo  *
252773f53c4aSTejun Heo  * Prepare cwqs for workqueue flushing.
252873f53c4aSTejun Heo  *
252973f53c4aSTejun Heo  * If @flush_color is non-negative, flush_color on all cwqs should be
253073f53c4aSTejun Heo  * -1.  If no cwq has in-flight commands at the specified color, all
253173f53c4aSTejun Heo  * cwq->flush_color's stay at -1 and %false is returned.  If any cwq
253273f53c4aSTejun Heo  * has in flight commands, its cwq->flush_color is set to
253373f53c4aSTejun Heo  * @flush_color, @wq->nr_cwqs_to_flush is updated accordingly, cwq
253473f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
253573f53c4aSTejun Heo  *
253673f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
253773f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
253873f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
253973f53c4aSTejun Heo  * is returned.
254073f53c4aSTejun Heo  *
254173f53c4aSTejun Heo  * If @work_color is non-negative, all cwqs should have the same
254273f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
254373f53c4aSTejun Heo  * advanced to @work_color.
254473f53c4aSTejun Heo  *
254573f53c4aSTejun Heo  * CONTEXT:
254673f53c4aSTejun Heo  * mutex_lock(wq->flush_mutex).
254773f53c4aSTejun Heo  *
254873f53c4aSTejun Heo  * RETURNS:
254973f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
255073f53c4aSTejun Heo  * otherwise.
255173f53c4aSTejun Heo  */
255273f53c4aSTejun Heo static bool flush_workqueue_prep_cwqs(struct workqueue_struct *wq,
255373f53c4aSTejun Heo 				      int flush_color, int work_color)
25541da177e4SLinus Torvalds {
255573f53c4aSTejun Heo 	bool wait = false;
255673f53c4aSTejun Heo 	unsigned int cpu;
25571da177e4SLinus Torvalds 
255873f53c4aSTejun Heo 	if (flush_color >= 0) {
255973f53c4aSTejun Heo 		BUG_ON(atomic_read(&wq->nr_cwqs_to_flush));
256073f53c4aSTejun Heo 		atomic_set(&wq->nr_cwqs_to_flush, 1);
2561dc186ad7SThomas Gleixner 	}
256214441960SOleg Nesterov 
2563f3421797STejun Heo 	for_each_cwq_cpu(cpu, wq) {
256473f53c4aSTejun Heo 		struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2565bd7bdd43STejun Heo 		struct global_cwq *gcwq = cwq->pool->gcwq;
25661da177e4SLinus Torvalds 
25678b03ae3cSTejun Heo 		spin_lock_irq(&gcwq->lock);
256873f53c4aSTejun Heo 
256973f53c4aSTejun Heo 		if (flush_color >= 0) {
257073f53c4aSTejun Heo 			BUG_ON(cwq->flush_color != -1);
257173f53c4aSTejun Heo 
257273f53c4aSTejun Heo 			if (cwq->nr_in_flight[flush_color]) {
257373f53c4aSTejun Heo 				cwq->flush_color = flush_color;
257473f53c4aSTejun Heo 				atomic_inc(&wq->nr_cwqs_to_flush);
257573f53c4aSTejun Heo 				wait = true;
25761da177e4SLinus Torvalds 			}
257773f53c4aSTejun Heo 		}
257873f53c4aSTejun Heo 
257973f53c4aSTejun Heo 		if (work_color >= 0) {
258073f53c4aSTejun Heo 			BUG_ON(work_color != work_next_color(cwq->work_color));
258173f53c4aSTejun Heo 			cwq->work_color = work_color;
258273f53c4aSTejun Heo 		}
258373f53c4aSTejun Heo 
25848b03ae3cSTejun Heo 		spin_unlock_irq(&gcwq->lock);
25851da177e4SLinus Torvalds 	}
25861da177e4SLinus Torvalds 
258773f53c4aSTejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_cwqs_to_flush))
258873f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
258973f53c4aSTejun Heo 
259073f53c4aSTejun Heo 	return wait;
259183c22520SOleg Nesterov }
25921da177e4SLinus Torvalds 
25930fcb78c2SRolf Eike Beer /**
25941da177e4SLinus Torvalds  * flush_workqueue - ensure that any scheduled work has run to completion.
25950fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
25961da177e4SLinus Torvalds  *
25971da177e4SLinus Torvalds  * Forces execution of the workqueue and blocks until its completion.
25981da177e4SLinus Torvalds  * This is typically used in driver shutdown handlers.
25991da177e4SLinus Torvalds  *
2600fc2e4d70SOleg Nesterov  * We sleep until all works which were queued on entry have been handled,
2601fc2e4d70SOleg Nesterov  * but we are not livelocked by new incoming ones.
26021da177e4SLinus Torvalds  */
26037ad5b3a5SHarvey Harrison void flush_workqueue(struct workqueue_struct *wq)
26041da177e4SLinus Torvalds {
260573f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
260673f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
260773f53c4aSTejun Heo 		.flush_color = -1,
260873f53c4aSTejun Heo 		.done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
260973f53c4aSTejun Heo 	};
261073f53c4aSTejun Heo 	int next_color;
2611b1f4ec17SOleg Nesterov 
26123295f0efSIngo Molnar 	lock_map_acquire(&wq->lockdep_map);
26133295f0efSIngo Molnar 	lock_map_release(&wq->lockdep_map);
261473f53c4aSTejun Heo 
261573f53c4aSTejun Heo 	mutex_lock(&wq->flush_mutex);
261673f53c4aSTejun Heo 
261773f53c4aSTejun Heo 	/*
261873f53c4aSTejun Heo 	 * Start-to-wait phase
261973f53c4aSTejun Heo 	 */
262073f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
262173f53c4aSTejun Heo 
262273f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
262373f53c4aSTejun Heo 		/*
262473f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
262573f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
262673f53c4aSTejun Heo 		 * by one.
262773f53c4aSTejun Heo 		 */
262873f53c4aSTejun Heo 		BUG_ON(!list_empty(&wq->flusher_overflow));
262973f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
263073f53c4aSTejun Heo 		wq->work_color = next_color;
263173f53c4aSTejun Heo 
263273f53c4aSTejun Heo 		if (!wq->first_flusher) {
263373f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
263473f53c4aSTejun Heo 			BUG_ON(wq->flush_color != this_flusher.flush_color);
263573f53c4aSTejun Heo 
263673f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
263773f53c4aSTejun Heo 
263873f53c4aSTejun Heo 			if (!flush_workqueue_prep_cwqs(wq, wq->flush_color,
263973f53c4aSTejun Heo 						       wq->work_color)) {
264073f53c4aSTejun Heo 				/* nothing to flush, done */
264173f53c4aSTejun Heo 				wq->flush_color = next_color;
264273f53c4aSTejun Heo 				wq->first_flusher = NULL;
264373f53c4aSTejun Heo 				goto out_unlock;
264473f53c4aSTejun Heo 			}
264573f53c4aSTejun Heo 		} else {
264673f53c4aSTejun Heo 			/* wait in queue */
264773f53c4aSTejun Heo 			BUG_ON(wq->flush_color == this_flusher.flush_color);
264873f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
264973f53c4aSTejun Heo 			flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
265073f53c4aSTejun Heo 		}
265173f53c4aSTejun Heo 	} else {
265273f53c4aSTejun Heo 		/*
265373f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
265473f53c4aSTejun Heo 		 * The next flush completion will assign us
265573f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
265673f53c4aSTejun Heo 		 */
265773f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
265873f53c4aSTejun Heo 	}
265973f53c4aSTejun Heo 
266073f53c4aSTejun Heo 	mutex_unlock(&wq->flush_mutex);
266173f53c4aSTejun Heo 
266273f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
266373f53c4aSTejun Heo 
266473f53c4aSTejun Heo 	/*
266573f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
266673f53c4aSTejun Heo 	 *
266773f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
266873f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
266973f53c4aSTejun Heo 	 */
267073f53c4aSTejun Heo 	if (wq->first_flusher != &this_flusher)
267173f53c4aSTejun Heo 		return;
267273f53c4aSTejun Heo 
267373f53c4aSTejun Heo 	mutex_lock(&wq->flush_mutex);
267473f53c4aSTejun Heo 
26754ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
26764ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
26774ce48b37STejun Heo 		goto out_unlock;
26784ce48b37STejun Heo 
267973f53c4aSTejun Heo 	wq->first_flusher = NULL;
268073f53c4aSTejun Heo 
268173f53c4aSTejun Heo 	BUG_ON(!list_empty(&this_flusher.list));
268273f53c4aSTejun Heo 	BUG_ON(wq->flush_color != this_flusher.flush_color);
268373f53c4aSTejun Heo 
268473f53c4aSTejun Heo 	while (true) {
268573f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
268673f53c4aSTejun Heo 
268773f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
268873f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
268973f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
269073f53c4aSTejun Heo 				break;
269173f53c4aSTejun Heo 			list_del_init(&next->list);
269273f53c4aSTejun Heo 			complete(&next->done);
269373f53c4aSTejun Heo 		}
269473f53c4aSTejun Heo 
269573f53c4aSTejun Heo 		BUG_ON(!list_empty(&wq->flusher_overflow) &&
269673f53c4aSTejun Heo 		       wq->flush_color != work_next_color(wq->work_color));
269773f53c4aSTejun Heo 
269873f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
269973f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
270073f53c4aSTejun Heo 
270173f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
270273f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
270373f53c4aSTejun Heo 			/*
270473f53c4aSTejun Heo 			 * Assign the same color to all overflowed
270573f53c4aSTejun Heo 			 * flushers, advance work_color and append to
270673f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
270773f53c4aSTejun Heo 			 * phase for these overflowed flushers.
270873f53c4aSTejun Heo 			 */
270973f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
271073f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
271173f53c4aSTejun Heo 
271273f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
271373f53c4aSTejun Heo 
271473f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
271573f53c4aSTejun Heo 					      &wq->flusher_queue);
271673f53c4aSTejun Heo 			flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
271773f53c4aSTejun Heo 		}
271873f53c4aSTejun Heo 
271973f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
272073f53c4aSTejun Heo 			BUG_ON(wq->flush_color != wq->work_color);
272173f53c4aSTejun Heo 			break;
272273f53c4aSTejun Heo 		}
272373f53c4aSTejun Heo 
272473f53c4aSTejun Heo 		/*
272573f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
272673f53c4aSTejun Heo 		 * the new first flusher and arm cwqs.
272773f53c4aSTejun Heo 		 */
272873f53c4aSTejun Heo 		BUG_ON(wq->flush_color == wq->work_color);
272973f53c4aSTejun Heo 		BUG_ON(wq->flush_color != next->flush_color);
273073f53c4aSTejun Heo 
273173f53c4aSTejun Heo 		list_del_init(&next->list);
273273f53c4aSTejun Heo 		wq->first_flusher = next;
273373f53c4aSTejun Heo 
273473f53c4aSTejun Heo 		if (flush_workqueue_prep_cwqs(wq, wq->flush_color, -1))
273573f53c4aSTejun Heo 			break;
273673f53c4aSTejun Heo 
273773f53c4aSTejun Heo 		/*
273873f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
273973f53c4aSTejun Heo 		 * flusher and repeat cascading.
274073f53c4aSTejun Heo 		 */
274173f53c4aSTejun Heo 		wq->first_flusher = NULL;
274273f53c4aSTejun Heo 	}
274373f53c4aSTejun Heo 
274473f53c4aSTejun Heo out_unlock:
274573f53c4aSTejun Heo 	mutex_unlock(&wq->flush_mutex);
27461da177e4SLinus Torvalds }
2747ae90dd5dSDave Jones EXPORT_SYMBOL_GPL(flush_workqueue);
27481da177e4SLinus Torvalds 
27499c5a2ba7STejun Heo /**
27509c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
27519c5a2ba7STejun Heo  * @wq: workqueue to drain
27529c5a2ba7STejun Heo  *
27539c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
27549c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
27559c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
27569c5a2ba7STejun Heo  * repeatedly until it becomes empty.  The number of flushing is detemined
27579c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
27589c5a2ba7STejun Heo  * takes too long.
27599c5a2ba7STejun Heo  */
27609c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
27619c5a2ba7STejun Heo {
27629c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
27639c5a2ba7STejun Heo 	unsigned int cpu;
27649c5a2ba7STejun Heo 
27659c5a2ba7STejun Heo 	/*
27669c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
27679c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
27689c5a2ba7STejun Heo 	 * Use WQ_DRAINING so that queue doesn't have to check nr_drainers.
27699c5a2ba7STejun Heo 	 */
27709c5a2ba7STejun Heo 	spin_lock(&workqueue_lock);
27719c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
27729c5a2ba7STejun Heo 		wq->flags |= WQ_DRAINING;
27739c5a2ba7STejun Heo 	spin_unlock(&workqueue_lock);
27749c5a2ba7STejun Heo reflush:
27759c5a2ba7STejun Heo 	flush_workqueue(wq);
27769c5a2ba7STejun Heo 
27779c5a2ba7STejun Heo 	for_each_cwq_cpu(cpu, wq) {
27789c5a2ba7STejun Heo 		struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2779fa2563e4SThomas Tuttle 		bool drained;
27809c5a2ba7STejun Heo 
2781bd7bdd43STejun Heo 		spin_lock_irq(&cwq->pool->gcwq->lock);
2782fa2563e4SThomas Tuttle 		drained = !cwq->nr_active && list_empty(&cwq->delayed_works);
2783bd7bdd43STejun Heo 		spin_unlock_irq(&cwq->pool->gcwq->lock);
2784fa2563e4SThomas Tuttle 
2785fa2563e4SThomas Tuttle 		if (drained)
27869c5a2ba7STejun Heo 			continue;
27879c5a2ba7STejun Heo 
27889c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
27899c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2790044c782cSValentin Ilie 			pr_warn("workqueue %s: flush on destruction isn't complete after %u tries\n",
27919c5a2ba7STejun Heo 				wq->name, flush_cnt);
27929c5a2ba7STejun Heo 		goto reflush;
27939c5a2ba7STejun Heo 	}
27949c5a2ba7STejun Heo 
27959c5a2ba7STejun Heo 	spin_lock(&workqueue_lock);
27969c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
27979c5a2ba7STejun Heo 		wq->flags &= ~WQ_DRAINING;
27989c5a2ba7STejun Heo 	spin_unlock(&workqueue_lock);
27999c5a2ba7STejun Heo }
28009c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
28019c5a2ba7STejun Heo 
2802606a5020STejun Heo static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2803baf59022STejun Heo {
2804baf59022STejun Heo 	struct worker *worker = NULL;
2805baf59022STejun Heo 	struct global_cwq *gcwq;
2806baf59022STejun Heo 	struct cpu_workqueue_struct *cwq;
2807baf59022STejun Heo 
2808baf59022STejun Heo 	might_sleep();
2809baf59022STejun Heo 	gcwq = get_work_gcwq(work);
2810baf59022STejun Heo 	if (!gcwq)
2811baf59022STejun Heo 		return false;
2812baf59022STejun Heo 
2813baf59022STejun Heo 	spin_lock_irq(&gcwq->lock);
2814baf59022STejun Heo 	if (!list_empty(&work->entry)) {
2815baf59022STejun Heo 		/*
2816baf59022STejun Heo 		 * See the comment near try_to_grab_pending()->smp_rmb().
2817baf59022STejun Heo 		 * If it was re-queued to a different gcwq under us, we
2818baf59022STejun Heo 		 * are not going to wait.
2819baf59022STejun Heo 		 */
2820baf59022STejun Heo 		smp_rmb();
2821baf59022STejun Heo 		cwq = get_work_cwq(work);
2822bd7bdd43STejun Heo 		if (unlikely(!cwq || gcwq != cwq->pool->gcwq))
2823baf59022STejun Heo 			goto already_gone;
2824606a5020STejun Heo 	} else {
2825baf59022STejun Heo 		worker = find_worker_executing_work(gcwq, work);
2826baf59022STejun Heo 		if (!worker)
2827baf59022STejun Heo 			goto already_gone;
2828baf59022STejun Heo 		cwq = worker->current_cwq;
2829606a5020STejun Heo 	}
2830baf59022STejun Heo 
2831baf59022STejun Heo 	insert_wq_barrier(cwq, barr, work, worker);
2832baf59022STejun Heo 	spin_unlock_irq(&gcwq->lock);
2833baf59022STejun Heo 
2834e159489bSTejun Heo 	/*
2835e159489bSTejun Heo 	 * If @max_active is 1 or rescuer is in use, flushing another work
2836e159489bSTejun Heo 	 * item on the same workqueue may lead to deadlock.  Make sure the
2837e159489bSTejun Heo 	 * flusher is not running on the same workqueue by verifying write
2838e159489bSTejun Heo 	 * access.
2839e159489bSTejun Heo 	 */
2840e159489bSTejun Heo 	if (cwq->wq->saved_max_active == 1 || cwq->wq->flags & WQ_RESCUER)
2841baf59022STejun Heo 		lock_map_acquire(&cwq->wq->lockdep_map);
2842e159489bSTejun Heo 	else
2843e159489bSTejun Heo 		lock_map_acquire_read(&cwq->wq->lockdep_map);
2844baf59022STejun Heo 	lock_map_release(&cwq->wq->lockdep_map);
2845e159489bSTejun Heo 
2846baf59022STejun Heo 	return true;
2847baf59022STejun Heo already_gone:
2848baf59022STejun Heo 	spin_unlock_irq(&gcwq->lock);
2849baf59022STejun Heo 	return false;
2850baf59022STejun Heo }
2851baf59022STejun Heo 
2852db700897SOleg Nesterov /**
2853401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
2854401a8d04STejun Heo  * @work: the work to flush
2855db700897SOleg Nesterov  *
2856606a5020STejun Heo  * Wait until @work has finished execution.  @work is guaranteed to be idle
2857606a5020STejun Heo  * on return if it hasn't been requeued since flush started.
2858401a8d04STejun Heo  *
2859401a8d04STejun Heo  * RETURNS:
2860401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
2861401a8d04STejun Heo  * %false if it was already idle.
2862db700897SOleg Nesterov  */
2863401a8d04STejun Heo bool flush_work(struct work_struct *work)
2864db700897SOleg Nesterov {
2865db700897SOleg Nesterov 	struct wq_barrier barr;
2866db700897SOleg Nesterov 
28670976dfc1SStephen Boyd 	lock_map_acquire(&work->lockdep_map);
28680976dfc1SStephen Boyd 	lock_map_release(&work->lockdep_map);
28690976dfc1SStephen Boyd 
2870606a5020STejun Heo 	if (start_flush_work(work, &barr)) {
2871db700897SOleg Nesterov 		wait_for_completion(&barr.done);
2872dc186ad7SThomas Gleixner 		destroy_work_on_stack(&barr.work);
2873401a8d04STejun Heo 		return true;
2874606a5020STejun Heo 	} else {
2875401a8d04STejun Heo 		return false;
2876db700897SOleg Nesterov 	}
2877606a5020STejun Heo }
2878db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
2879db700897SOleg Nesterov 
288036e227d2STejun Heo static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
28811f1f642eSOleg Nesterov {
2882bbb68dfaSTejun Heo 	unsigned long flags;
28831f1f642eSOleg Nesterov 	int ret;
28841f1f642eSOleg Nesterov 
28851f1f642eSOleg Nesterov 	do {
2886bbb68dfaSTejun Heo 		ret = try_to_grab_pending(work, is_dwork, &flags);
2887bbb68dfaSTejun Heo 		/*
2888bbb68dfaSTejun Heo 		 * If someone else is canceling, wait for the same event it
2889bbb68dfaSTejun Heo 		 * would be waiting for before retrying.
2890bbb68dfaSTejun Heo 		 */
2891bbb68dfaSTejun Heo 		if (unlikely(ret == -ENOENT))
2892606a5020STejun Heo 			flush_work(work);
28931f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
28941f1f642eSOleg Nesterov 
2895bbb68dfaSTejun Heo 	/* tell other tasks trying to grab @work to back off */
2896bbb68dfaSTejun Heo 	mark_work_canceling(work);
2897bbb68dfaSTejun Heo 	local_irq_restore(flags);
2898bbb68dfaSTejun Heo 
2899606a5020STejun Heo 	flush_work(work);
29007a22ad75STejun Heo 	clear_work_data(work);
29011f1f642eSOleg Nesterov 	return ret;
29021f1f642eSOleg Nesterov }
29031f1f642eSOleg Nesterov 
29046e84d644SOleg Nesterov /**
2905401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
2906401a8d04STejun Heo  * @work: the work to cancel
29076e84d644SOleg Nesterov  *
2908401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
2909401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
2910401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
2911401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
29121f1f642eSOleg Nesterov  *
2913401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
2914401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
29156e84d644SOleg Nesterov  *
2916401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
29176e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
2918401a8d04STejun Heo  *
2919401a8d04STejun Heo  * RETURNS:
2920401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
29216e84d644SOleg Nesterov  */
2922401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
29236e84d644SOleg Nesterov {
292436e227d2STejun Heo 	return __cancel_work_timer(work, false);
2925b89deed3SOleg Nesterov }
292628e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
2927b89deed3SOleg Nesterov 
29286e84d644SOleg Nesterov /**
2929401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
2930401a8d04STejun Heo  * @dwork: the delayed work to flush
29316e84d644SOleg Nesterov  *
2932401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
2933401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
2934401a8d04STejun Heo  * considers the last queueing instance of @dwork.
29351f1f642eSOleg Nesterov  *
2936401a8d04STejun Heo  * RETURNS:
2937401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
2938401a8d04STejun Heo  * %false if it was already idle.
29396e84d644SOleg Nesterov  */
2940401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
2941401a8d04STejun Heo {
29428930cabaSTejun Heo 	local_irq_disable();
2943401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
29441265057fSTejun Heo 		__queue_work(dwork->cpu,
2945401a8d04STejun Heo 			     get_work_cwq(&dwork->work)->wq, &dwork->work);
29468930cabaSTejun Heo 	local_irq_enable();
2947401a8d04STejun Heo 	return flush_work(&dwork->work);
2948401a8d04STejun Heo }
2949401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
2950401a8d04STejun Heo 
2951401a8d04STejun Heo /**
2952401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2953401a8d04STejun Heo  * @dwork: the delayed work cancel
2954401a8d04STejun Heo  *
2955401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
2956401a8d04STejun Heo  *
2957401a8d04STejun Heo  * RETURNS:
2958401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
2959401a8d04STejun Heo  */
2960401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
29616e84d644SOleg Nesterov {
296236e227d2STejun Heo 	return __cancel_work_timer(&dwork->work, true);
29636e84d644SOleg Nesterov }
2964f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
29651da177e4SLinus Torvalds 
2966d4283e93STejun Heo /**
29670a13c00eSTejun Heo  * schedule_work_on - put work task on a specific cpu
29680a13c00eSTejun Heo  * @cpu: cpu to put the work task on
29690a13c00eSTejun Heo  * @work: job to be done
29700a13c00eSTejun Heo  *
29710a13c00eSTejun Heo  * This puts a job on a specific cpu
29720a13c00eSTejun Heo  */
2973d4283e93STejun Heo bool schedule_work_on(int cpu, struct work_struct *work)
29740a13c00eSTejun Heo {
29750a13c00eSTejun Heo 	return queue_work_on(cpu, system_wq, work);
29760a13c00eSTejun Heo }
29770a13c00eSTejun Heo EXPORT_SYMBOL(schedule_work_on);
29780a13c00eSTejun Heo 
29790fcb78c2SRolf Eike Beer /**
29800fcb78c2SRolf Eike Beer  * schedule_work - put work task in global workqueue
29810fcb78c2SRolf Eike Beer  * @work: job to be done
29820fcb78c2SRolf Eike Beer  *
2983d4283e93STejun Heo  * Returns %false if @work was already on the kernel-global workqueue and
2984d4283e93STejun Heo  * %true otherwise.
29855b0f437dSBart Van Assche  *
29865b0f437dSBart Van Assche  * This puts a job in the kernel-global workqueue if it was not already
29875b0f437dSBart Van Assche  * queued and leaves it in the same position on the kernel-global
29885b0f437dSBart Van Assche  * workqueue otherwise.
29890fcb78c2SRolf Eike Beer  */
2990d4283e93STejun Heo bool schedule_work(struct work_struct *work)
29911da177e4SLinus Torvalds {
2992d320c038STejun Heo 	return queue_work(system_wq, work);
29931da177e4SLinus Torvalds }
2994ae90dd5dSDave Jones EXPORT_SYMBOL(schedule_work);
29951da177e4SLinus Torvalds 
29960fcb78c2SRolf Eike Beer /**
29970fcb78c2SRolf Eike Beer  * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
29980fcb78c2SRolf Eike Beer  * @cpu: cpu to use
299952bad64dSDavid Howells  * @dwork: job to be done
30000fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait
30010fcb78c2SRolf Eike Beer  *
30020fcb78c2SRolf Eike Beer  * After waiting for a given time this puts a job in the kernel-global
30030fcb78c2SRolf Eike Beer  * workqueue on the specified CPU.
30040fcb78c2SRolf Eike Beer  */
3005d4283e93STejun Heo bool schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
3006d4283e93STejun Heo 			      unsigned long delay)
30071da177e4SLinus Torvalds {
3008d320c038STejun Heo 	return queue_delayed_work_on(cpu, system_wq, dwork, delay);
30091da177e4SLinus Torvalds }
3010ae90dd5dSDave Jones EXPORT_SYMBOL(schedule_delayed_work_on);
30111da177e4SLinus Torvalds 
3012b6136773SAndrew Morton /**
30130a13c00eSTejun Heo  * schedule_delayed_work - put work task in global workqueue after delay
30140a13c00eSTejun Heo  * @dwork: job to be done
30150a13c00eSTejun Heo  * @delay: number of jiffies to wait or 0 for immediate execution
30160a13c00eSTejun Heo  *
30170a13c00eSTejun Heo  * After waiting for a given time this puts a job in the kernel-global
30180a13c00eSTejun Heo  * workqueue.
30190a13c00eSTejun Heo  */
3020d4283e93STejun Heo bool schedule_delayed_work(struct delayed_work *dwork, unsigned long delay)
30210a13c00eSTejun Heo {
30220a13c00eSTejun Heo 	return queue_delayed_work(system_wq, dwork, delay);
30230a13c00eSTejun Heo }
30240a13c00eSTejun Heo EXPORT_SYMBOL(schedule_delayed_work);
30250a13c00eSTejun Heo 
30260a13c00eSTejun Heo /**
302731ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
3028b6136773SAndrew Morton  * @func: the function to call
3029b6136773SAndrew Morton  *
303031ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
303131ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
3032b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
303331ddd871STejun Heo  *
303431ddd871STejun Heo  * RETURNS:
303531ddd871STejun Heo  * 0 on success, -errno on failure.
3036b6136773SAndrew Morton  */
303765f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
303815316ba8SChristoph Lameter {
303915316ba8SChristoph Lameter 	int cpu;
304038f51568SNamhyung Kim 	struct work_struct __percpu *works;
304115316ba8SChristoph Lameter 
3042b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
3043b6136773SAndrew Morton 	if (!works)
304415316ba8SChristoph Lameter 		return -ENOMEM;
3045b6136773SAndrew Morton 
304695402b38SGautham R Shenoy 	get_online_cpus();
304793981800STejun Heo 
304815316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
30499bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
30509bfb1839SIngo Molnar 
30519bfb1839SIngo Molnar 		INIT_WORK(work, func);
30528de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
305315316ba8SChristoph Lameter 	}
305493981800STejun Heo 
305593981800STejun Heo 	for_each_online_cpu(cpu)
30568616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
305793981800STejun Heo 
305895402b38SGautham R Shenoy 	put_online_cpus();
3059b6136773SAndrew Morton 	free_percpu(works);
306015316ba8SChristoph Lameter 	return 0;
306115316ba8SChristoph Lameter }
306215316ba8SChristoph Lameter 
3063eef6a7d5SAlan Stern /**
3064eef6a7d5SAlan Stern  * flush_scheduled_work - ensure that any scheduled work has run to completion.
3065eef6a7d5SAlan Stern  *
3066eef6a7d5SAlan Stern  * Forces execution of the kernel-global workqueue and blocks until its
3067eef6a7d5SAlan Stern  * completion.
3068eef6a7d5SAlan Stern  *
3069eef6a7d5SAlan Stern  * Think twice before calling this function!  It's very easy to get into
3070eef6a7d5SAlan Stern  * trouble if you don't take great care.  Either of the following situations
3071eef6a7d5SAlan Stern  * will lead to deadlock:
3072eef6a7d5SAlan Stern  *
3073eef6a7d5SAlan Stern  *	One of the work items currently on the workqueue needs to acquire
3074eef6a7d5SAlan Stern  *	a lock held by your code or its caller.
3075eef6a7d5SAlan Stern  *
3076eef6a7d5SAlan Stern  *	Your code is running in the context of a work routine.
3077eef6a7d5SAlan Stern  *
3078eef6a7d5SAlan Stern  * They will be detected by lockdep when they occur, but the first might not
3079eef6a7d5SAlan Stern  * occur very often.  It depends on what work items are on the workqueue and
3080eef6a7d5SAlan Stern  * what locks they need, which you have no control over.
3081eef6a7d5SAlan Stern  *
3082eef6a7d5SAlan Stern  * In most situations flushing the entire workqueue is overkill; you merely
3083eef6a7d5SAlan Stern  * need to know that a particular work item isn't queued and isn't running.
3084eef6a7d5SAlan Stern  * In such cases you should use cancel_delayed_work_sync() or
3085eef6a7d5SAlan Stern  * cancel_work_sync() instead.
3086eef6a7d5SAlan Stern  */
30871da177e4SLinus Torvalds void flush_scheduled_work(void)
30881da177e4SLinus Torvalds {
3089d320c038STejun Heo 	flush_workqueue(system_wq);
30901da177e4SLinus Torvalds }
3091ae90dd5dSDave Jones EXPORT_SYMBOL(flush_scheduled_work);
30921da177e4SLinus Torvalds 
30931da177e4SLinus Torvalds /**
30941fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
30951fa44ecaSJames Bottomley  * @fn:		the function to execute
30961fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
30971fa44ecaSJames Bottomley  *		be available when the work executes)
30981fa44ecaSJames Bottomley  *
30991fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
31001fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
31011fa44ecaSJames Bottomley  *
31021fa44ecaSJames Bottomley  * Returns:	0 - function was executed
31031fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
31041fa44ecaSJames Bottomley  */
310565f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
31061fa44ecaSJames Bottomley {
31071fa44ecaSJames Bottomley 	if (!in_interrupt()) {
310865f27f38SDavid Howells 		fn(&ew->work);
31091fa44ecaSJames Bottomley 		return 0;
31101fa44ecaSJames Bottomley 	}
31111fa44ecaSJames Bottomley 
311265f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
31131fa44ecaSJames Bottomley 	schedule_work(&ew->work);
31141fa44ecaSJames Bottomley 
31151fa44ecaSJames Bottomley 	return 1;
31161fa44ecaSJames Bottomley }
31171fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
31181fa44ecaSJames Bottomley 
31191da177e4SLinus Torvalds int keventd_up(void)
31201da177e4SLinus Torvalds {
3121d320c038STejun Heo 	return system_wq != NULL;
31221da177e4SLinus Torvalds }
31231da177e4SLinus Torvalds 
3124bdbc5dd7STejun Heo static int alloc_cwqs(struct workqueue_struct *wq)
31251da177e4SLinus Torvalds {
31263af24433SOleg Nesterov 	/*
31270f900049STejun Heo 	 * cwqs are forced aligned according to WORK_STRUCT_FLAG_BITS.
31280f900049STejun Heo 	 * Make sure that the alignment isn't lower than that of
31290f900049STejun Heo 	 * unsigned long long.
31303af24433SOleg Nesterov 	 */
31310f900049STejun Heo 	const size_t size = sizeof(struct cpu_workqueue_struct);
31320f900049STejun Heo 	const size_t align = max_t(size_t, 1 << WORK_STRUCT_FLAG_BITS,
31330f900049STejun Heo 				   __alignof__(unsigned long long));
31343af24433SOleg Nesterov 
3135e06ffa1eSLai Jiangshan 	if (!(wq->flags & WQ_UNBOUND))
3136f3421797STejun Heo 		wq->cpu_wq.pcpu = __alloc_percpu(size, align);
3137931ac77eSTejun Heo 	else {
31380f900049STejun Heo 		void *ptr;
3139e1d8aa9fSFrederic Weisbecker 
31400f900049STejun Heo 		/*
3141f3421797STejun Heo 		 * Allocate enough room to align cwq and put an extra
3142f3421797STejun Heo 		 * pointer at the end pointing back to the originally
3143f3421797STejun Heo 		 * allocated pointer which will be used for free.
31440f900049STejun Heo 		 */
3145bdbc5dd7STejun Heo 		ptr = kzalloc(size + align + sizeof(void *), GFP_KERNEL);
3146bdbc5dd7STejun Heo 		if (ptr) {
3147bdbc5dd7STejun Heo 			wq->cpu_wq.single = PTR_ALIGN(ptr, align);
3148bdbc5dd7STejun Heo 			*(void **)(wq->cpu_wq.single + 1) = ptr;
3149bdbc5dd7STejun Heo 		}
31503af24433SOleg Nesterov 	}
31513af24433SOleg Nesterov 
31520415b00dSTejun Heo 	/* just in case, make sure it's actually aligned */
3153bdbc5dd7STejun Heo 	BUG_ON(!IS_ALIGNED(wq->cpu_wq.v, align));
3154bdbc5dd7STejun Heo 	return wq->cpu_wq.v ? 0 : -ENOMEM;
31550f900049STejun Heo }
31560f900049STejun Heo 
3157bdbc5dd7STejun Heo static void free_cwqs(struct workqueue_struct *wq)
315806ba38a9SOleg Nesterov {
3159e06ffa1eSLai Jiangshan 	if (!(wq->flags & WQ_UNBOUND))
3160bdbc5dd7STejun Heo 		free_percpu(wq->cpu_wq.pcpu);
3161f3421797STejun Heo 	else if (wq->cpu_wq.single) {
3162f3421797STejun Heo 		/* the pointer to free is stored right after the cwq */
3163f3421797STejun Heo 		kfree(*(void **)(wq->cpu_wq.single + 1));
316406ba38a9SOleg Nesterov 	}
316506ba38a9SOleg Nesterov }
316606ba38a9SOleg Nesterov 
3167f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
3168f3421797STejun Heo 			       const char *name)
3169b71ab8c2STejun Heo {
3170f3421797STejun Heo 	int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3171f3421797STejun Heo 
3172f3421797STejun Heo 	if (max_active < 1 || max_active > lim)
3173044c782cSValentin Ilie 		pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3174f3421797STejun Heo 			max_active, name, 1, lim);
3175b71ab8c2STejun Heo 
3176f3421797STejun Heo 	return clamp_val(max_active, 1, lim);
3177b71ab8c2STejun Heo }
3178b71ab8c2STejun Heo 
3179b196be89STejun Heo struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
318097e37d7bSTejun Heo 					       unsigned int flags,
31811e19ffc6STejun Heo 					       int max_active,
3182eb13ba87SJohannes Berg 					       struct lock_class_key *key,
3183b196be89STejun Heo 					       const char *lock_name, ...)
31843af24433SOleg Nesterov {
3185b196be89STejun Heo 	va_list args, args1;
31863af24433SOleg Nesterov 	struct workqueue_struct *wq;
3187c34056a3STejun Heo 	unsigned int cpu;
3188b196be89STejun Heo 	size_t namelen;
3189b196be89STejun Heo 
3190b196be89STejun Heo 	/* determine namelen, allocate wq and format name */
3191b196be89STejun Heo 	va_start(args, lock_name);
3192b196be89STejun Heo 	va_copy(args1, args);
3193b196be89STejun Heo 	namelen = vsnprintf(NULL, 0, fmt, args) + 1;
3194b196be89STejun Heo 
3195b196be89STejun Heo 	wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
3196b196be89STejun Heo 	if (!wq)
3197b196be89STejun Heo 		goto err;
3198b196be89STejun Heo 
3199b196be89STejun Heo 	vsnprintf(wq->name, namelen, fmt, args1);
3200b196be89STejun Heo 	va_end(args);
3201b196be89STejun Heo 	va_end(args1);
32023af24433SOleg Nesterov 
3203f3421797STejun Heo 	/*
32046370a6adSTejun Heo 	 * Workqueues which may be used during memory reclaim should
32056370a6adSTejun Heo 	 * have a rescuer to guarantee forward progress.
32066370a6adSTejun Heo 	 */
32076370a6adSTejun Heo 	if (flags & WQ_MEM_RECLAIM)
32086370a6adSTejun Heo 		flags |= WQ_RESCUER;
32096370a6adSTejun Heo 
3210d320c038STejun Heo 	max_active = max_active ?: WQ_DFL_ACTIVE;
3211b196be89STejun Heo 	max_active = wq_clamp_max_active(max_active, flags, wq->name);
32123af24433SOleg Nesterov 
3213b196be89STejun Heo 	/* init wq */
321497e37d7bSTejun Heo 	wq->flags = flags;
3215a0a1a5fdSTejun Heo 	wq->saved_max_active = max_active;
321673f53c4aSTejun Heo 	mutex_init(&wq->flush_mutex);
321773f53c4aSTejun Heo 	atomic_set(&wq->nr_cwqs_to_flush, 0);
321873f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
321973f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
32203af24433SOleg Nesterov 
3221eb13ba87SJohannes Berg 	lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3222cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
32233af24433SOleg Nesterov 
3224bdbc5dd7STejun Heo 	if (alloc_cwqs(wq) < 0)
3225bdbc5dd7STejun Heo 		goto err;
3226bdbc5dd7STejun Heo 
3227f3421797STejun Heo 	for_each_cwq_cpu(cpu, wq) {
32281537663fSTejun Heo 		struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
32298b03ae3cSTejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
32303270476aSTejun Heo 		int pool_idx = (bool)(flags & WQ_HIGHPRI);
32311537663fSTejun Heo 
32320f900049STejun Heo 		BUG_ON((unsigned long)cwq & WORK_STRUCT_FLAG_MASK);
32333270476aSTejun Heo 		cwq->pool = &gcwq->pools[pool_idx];
3234c34056a3STejun Heo 		cwq->wq = wq;
323573f53c4aSTejun Heo 		cwq->flush_color = -1;
32361e19ffc6STejun Heo 		cwq->max_active = max_active;
32371e19ffc6STejun Heo 		INIT_LIST_HEAD(&cwq->delayed_works);
3238e22bee78STejun Heo 	}
32391537663fSTejun Heo 
3240e22bee78STejun Heo 	if (flags & WQ_RESCUER) {
3241e22bee78STejun Heo 		struct worker *rescuer;
3242e22bee78STejun Heo 
3243f2e005aaSTejun Heo 		if (!alloc_mayday_mask(&wq->mayday_mask, GFP_KERNEL))
3244e22bee78STejun Heo 			goto err;
3245e22bee78STejun Heo 
3246e22bee78STejun Heo 		wq->rescuer = rescuer = alloc_worker();
3247e22bee78STejun Heo 		if (!rescuer)
3248e22bee78STejun Heo 			goto err;
3249e22bee78STejun Heo 
3250b196be89STejun Heo 		rescuer->task = kthread_create(rescuer_thread, wq, "%s",
3251b196be89STejun Heo 					       wq->name);
3252e22bee78STejun Heo 		if (IS_ERR(rescuer->task))
3253e22bee78STejun Heo 			goto err;
3254e22bee78STejun Heo 
3255e22bee78STejun Heo 		rescuer->task->flags |= PF_THREAD_BOUND;
3256e22bee78STejun Heo 		wake_up_process(rescuer->task);
32573af24433SOleg Nesterov 	}
32581537663fSTejun Heo 
32593af24433SOleg Nesterov 	/*
3260a0a1a5fdSTejun Heo 	 * workqueue_lock protects global freeze state and workqueues
3261a0a1a5fdSTejun Heo 	 * list.  Grab it, set max_active accordingly and add the new
3262a0a1a5fdSTejun Heo 	 * workqueue to workqueues list.
32633af24433SOleg Nesterov 	 */
32643af24433SOleg Nesterov 	spin_lock(&workqueue_lock);
3265a0a1a5fdSTejun Heo 
326658a69cb4STejun Heo 	if (workqueue_freezing && wq->flags & WQ_FREEZABLE)
3267f3421797STejun Heo 		for_each_cwq_cpu(cpu, wq)
3268a0a1a5fdSTejun Heo 			get_cwq(cpu, wq)->max_active = 0;
3269a0a1a5fdSTejun Heo 
32703af24433SOleg Nesterov 	list_add(&wq->list, &workqueues);
3271a0a1a5fdSTejun Heo 
32723af24433SOleg Nesterov 	spin_unlock(&workqueue_lock);
32733af24433SOleg Nesterov 
32743af24433SOleg Nesterov 	return wq;
32754690c4abSTejun Heo err:
32764690c4abSTejun Heo 	if (wq) {
3277bdbc5dd7STejun Heo 		free_cwqs(wq);
3278f2e005aaSTejun Heo 		free_mayday_mask(wq->mayday_mask);
3279e22bee78STejun Heo 		kfree(wq->rescuer);
32804690c4abSTejun Heo 		kfree(wq);
32813af24433SOleg Nesterov 	}
32824690c4abSTejun Heo 	return NULL;
32831da177e4SLinus Torvalds }
3284d320c038STejun Heo EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
32851da177e4SLinus Torvalds 
32863af24433SOleg Nesterov /**
32873af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
32883af24433SOleg Nesterov  * @wq: target workqueue
32893af24433SOleg Nesterov  *
32903af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
32913af24433SOleg Nesterov  */
32923af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
32933af24433SOleg Nesterov {
3294c8e55f36STejun Heo 	unsigned int cpu;
32953af24433SOleg Nesterov 
32969c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
32979c5a2ba7STejun Heo 	drain_workqueue(wq);
3298c8efcc25STejun Heo 
3299a0a1a5fdSTejun Heo 	/*
3300a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
3301a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
3302a0a1a5fdSTejun Heo 	 */
330395402b38SGautham R Shenoy 	spin_lock(&workqueue_lock);
33043af24433SOleg Nesterov 	list_del(&wq->list);
330595402b38SGautham R Shenoy 	spin_unlock(&workqueue_lock);
33063af24433SOleg Nesterov 
3307e22bee78STejun Heo 	/* sanity check */
3308f3421797STejun Heo 	for_each_cwq_cpu(cpu, wq) {
330973f53c4aSTejun Heo 		struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
331073f53c4aSTejun Heo 		int i;
33113af24433SOleg Nesterov 
331273f53c4aSTejun Heo 		for (i = 0; i < WORK_NR_COLORS; i++)
331373f53c4aSTejun Heo 			BUG_ON(cwq->nr_in_flight[i]);
33141e19ffc6STejun Heo 		BUG_ON(cwq->nr_active);
33151e19ffc6STejun Heo 		BUG_ON(!list_empty(&cwq->delayed_works));
331673f53c4aSTejun Heo 	}
33171537663fSTejun Heo 
3318e22bee78STejun Heo 	if (wq->flags & WQ_RESCUER) {
3319e22bee78STejun Heo 		kthread_stop(wq->rescuer->task);
3320f2e005aaSTejun Heo 		free_mayday_mask(wq->mayday_mask);
33218d9df9f0SXiaotian Feng 		kfree(wq->rescuer);
3322e22bee78STejun Heo 	}
3323e22bee78STejun Heo 
3324bdbc5dd7STejun Heo 	free_cwqs(wq);
33253af24433SOleg Nesterov 	kfree(wq);
33263af24433SOleg Nesterov }
33273af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
33283af24433SOleg Nesterov 
3329dcd989cbSTejun Heo /**
3330dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
3331dcd989cbSTejun Heo  * @wq: target workqueue
3332dcd989cbSTejun Heo  * @max_active: new max_active value.
3333dcd989cbSTejun Heo  *
3334dcd989cbSTejun Heo  * Set max_active of @wq to @max_active.
3335dcd989cbSTejun Heo  *
3336dcd989cbSTejun Heo  * CONTEXT:
3337dcd989cbSTejun Heo  * Don't call from IRQ context.
3338dcd989cbSTejun Heo  */
3339dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
3340dcd989cbSTejun Heo {
3341dcd989cbSTejun Heo 	unsigned int cpu;
3342dcd989cbSTejun Heo 
3343f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
3344dcd989cbSTejun Heo 
3345dcd989cbSTejun Heo 	spin_lock(&workqueue_lock);
3346dcd989cbSTejun Heo 
3347dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
3348dcd989cbSTejun Heo 
3349f3421797STejun Heo 	for_each_cwq_cpu(cpu, wq) {
3350dcd989cbSTejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
3351dcd989cbSTejun Heo 
3352dcd989cbSTejun Heo 		spin_lock_irq(&gcwq->lock);
3353dcd989cbSTejun Heo 
335458a69cb4STejun Heo 		if (!(wq->flags & WQ_FREEZABLE) ||
3355dcd989cbSTejun Heo 		    !(gcwq->flags & GCWQ_FREEZING))
3356dcd989cbSTejun Heo 			get_cwq(gcwq->cpu, wq)->max_active = max_active;
3357dcd989cbSTejun Heo 
3358dcd989cbSTejun Heo 		spin_unlock_irq(&gcwq->lock);
3359dcd989cbSTejun Heo 	}
3360dcd989cbSTejun Heo 
3361dcd989cbSTejun Heo 	spin_unlock(&workqueue_lock);
3362dcd989cbSTejun Heo }
3363dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
3364dcd989cbSTejun Heo 
3365dcd989cbSTejun Heo /**
3366dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
3367dcd989cbSTejun Heo  * @cpu: CPU in question
3368dcd989cbSTejun Heo  * @wq: target workqueue
3369dcd989cbSTejun Heo  *
3370dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
3371dcd989cbSTejun Heo  * no synchronization around this function and the test result is
3372dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
3373dcd989cbSTejun Heo  *
3374dcd989cbSTejun Heo  * RETURNS:
3375dcd989cbSTejun Heo  * %true if congested, %false otherwise.
3376dcd989cbSTejun Heo  */
3377dcd989cbSTejun Heo bool workqueue_congested(unsigned int cpu, struct workqueue_struct *wq)
3378dcd989cbSTejun Heo {
3379dcd989cbSTejun Heo 	struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3380dcd989cbSTejun Heo 
3381dcd989cbSTejun Heo 	return !list_empty(&cwq->delayed_works);
3382dcd989cbSTejun Heo }
3383dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
3384dcd989cbSTejun Heo 
3385dcd989cbSTejun Heo /**
3386dcd989cbSTejun Heo  * work_cpu - return the last known associated cpu for @work
3387dcd989cbSTejun Heo  * @work: the work of interest
3388dcd989cbSTejun Heo  *
3389dcd989cbSTejun Heo  * RETURNS:
3390bdbc5dd7STejun Heo  * CPU number if @work was ever queued.  WORK_CPU_NONE otherwise.
3391dcd989cbSTejun Heo  */
3392dcd989cbSTejun Heo unsigned int work_cpu(struct work_struct *work)
3393dcd989cbSTejun Heo {
3394dcd989cbSTejun Heo 	struct global_cwq *gcwq = get_work_gcwq(work);
3395dcd989cbSTejun Heo 
3396bdbc5dd7STejun Heo 	return gcwq ? gcwq->cpu : WORK_CPU_NONE;
3397dcd989cbSTejun Heo }
3398dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_cpu);
3399dcd989cbSTejun Heo 
3400dcd989cbSTejun Heo /**
3401dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
3402dcd989cbSTejun Heo  * @work: the work to be tested
3403dcd989cbSTejun Heo  *
3404dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
3405dcd989cbSTejun Heo  * synchronization around this function and the test result is
3406dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
3407dcd989cbSTejun Heo  * Especially for reentrant wqs, the pending state might hide the
3408dcd989cbSTejun Heo  * running state.
3409dcd989cbSTejun Heo  *
3410dcd989cbSTejun Heo  * RETURNS:
3411dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
3412dcd989cbSTejun Heo  */
3413dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
3414dcd989cbSTejun Heo {
3415dcd989cbSTejun Heo 	struct global_cwq *gcwq = get_work_gcwq(work);
3416dcd989cbSTejun Heo 	unsigned long flags;
3417dcd989cbSTejun Heo 	unsigned int ret = 0;
3418dcd989cbSTejun Heo 
3419dcd989cbSTejun Heo 	if (!gcwq)
3420dcd989cbSTejun Heo 		return false;
3421dcd989cbSTejun Heo 
3422dcd989cbSTejun Heo 	spin_lock_irqsave(&gcwq->lock, flags);
3423dcd989cbSTejun Heo 
3424dcd989cbSTejun Heo 	if (work_pending(work))
3425dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
3426dcd989cbSTejun Heo 	if (find_worker_executing_work(gcwq, work))
3427dcd989cbSTejun Heo 		ret |= WORK_BUSY_RUNNING;
3428dcd989cbSTejun Heo 
3429dcd989cbSTejun Heo 	spin_unlock_irqrestore(&gcwq->lock, flags);
3430dcd989cbSTejun Heo 
3431dcd989cbSTejun Heo 	return ret;
3432dcd989cbSTejun Heo }
3433dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
3434dcd989cbSTejun Heo 
3435db7bccf4STejun Heo /*
3436db7bccf4STejun Heo  * CPU hotplug.
3437db7bccf4STejun Heo  *
3438e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
3439e22bee78STejun Heo  * are a lot of assumptions on strong associations among work, cwq and
3440e22bee78STejun Heo  * gcwq which make migrating pending and scheduled works very
3441e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
3442e22bee78STejun Heo  * gcwqs serve mix of short, long and very long running works making
3443e22bee78STejun Heo  * blocked draining impractical.
3444e22bee78STejun Heo  *
3445628c78e7STejun Heo  * This is solved by allowing a gcwq to be disassociated from the CPU
3446628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
3447628c78e7STejun Heo  * cpu comes back online.
3448db7bccf4STejun Heo  */
3449db7bccf4STejun Heo 
345060373152STejun Heo /* claim manager positions of all pools */
34518db25e78STejun Heo static void gcwq_claim_management_and_lock(struct global_cwq *gcwq)
345260373152STejun Heo {
345360373152STejun Heo 	struct worker_pool *pool;
345460373152STejun Heo 
345560373152STejun Heo 	for_each_worker_pool(pool, gcwq)
345660373152STejun Heo 		mutex_lock_nested(&pool->manager_mutex, pool - gcwq->pools);
34578db25e78STejun Heo 	spin_lock_irq(&gcwq->lock);
345860373152STejun Heo }
345960373152STejun Heo 
346060373152STejun Heo /* release manager positions */
34618db25e78STejun Heo static void gcwq_release_management_and_unlock(struct global_cwq *gcwq)
346260373152STejun Heo {
346360373152STejun Heo 	struct worker_pool *pool;
346460373152STejun Heo 
34658db25e78STejun Heo 	spin_unlock_irq(&gcwq->lock);
346660373152STejun Heo 	for_each_worker_pool(pool, gcwq)
346760373152STejun Heo 		mutex_unlock(&pool->manager_mutex);
346860373152STejun Heo }
346960373152STejun Heo 
3470628c78e7STejun Heo static void gcwq_unbind_fn(struct work_struct *work)
3471db7bccf4STejun Heo {
3472628c78e7STejun Heo 	struct global_cwq *gcwq = get_gcwq(smp_processor_id());
34734ce62e9eSTejun Heo 	struct worker_pool *pool;
3474db7bccf4STejun Heo 	struct worker *worker;
3475db7bccf4STejun Heo 	struct hlist_node *pos;
3476db7bccf4STejun Heo 	int i;
3477db7bccf4STejun Heo 
3478db7bccf4STejun Heo 	BUG_ON(gcwq->cpu != smp_processor_id());
3479db7bccf4STejun Heo 
34808db25e78STejun Heo 	gcwq_claim_management_and_lock(gcwq);
3481e22bee78STejun Heo 
3482f2d5a0eeSTejun Heo 	/*
3483f2d5a0eeSTejun Heo 	 * We've claimed all manager positions.  Make all workers unbound
3484f2d5a0eeSTejun Heo 	 * and set DISASSOCIATED.  Before this, all workers except for the
3485f2d5a0eeSTejun Heo 	 * ones which are still executing works from before the last CPU
3486f2d5a0eeSTejun Heo 	 * down must be on the cpu.  After this, they may become diasporas.
3487f2d5a0eeSTejun Heo 	 */
348860373152STejun Heo 	for_each_worker_pool(pool, gcwq)
34894ce62e9eSTejun Heo 		list_for_each_entry(worker, &pool->idle_list, entry)
3490403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
3491db7bccf4STejun Heo 
3492db7bccf4STejun Heo 	for_each_busy_worker(worker, i, pos, gcwq)
3493403c821dSTejun Heo 		worker->flags |= WORKER_UNBOUND;
3494db7bccf4STejun Heo 
3495f2d5a0eeSTejun Heo 	gcwq->flags |= GCWQ_DISASSOCIATED;
3496f2d5a0eeSTejun Heo 
34978db25e78STejun Heo 	gcwq_release_management_and_unlock(gcwq);
3498e22bee78STejun Heo 
3499e22bee78STejun Heo 	/*
3500628c78e7STejun Heo 	 * Call schedule() so that we cross rq->lock and thus can guarantee
3501628c78e7STejun Heo 	 * sched callbacks see the %WORKER_UNBOUND flag.  This is necessary
3502628c78e7STejun Heo 	 * as scheduler callbacks may be invoked from other cpus.
3503628c78e7STejun Heo 	 */
3504628c78e7STejun Heo 	schedule();
3505628c78e7STejun Heo 
3506628c78e7STejun Heo 	/*
3507628c78e7STejun Heo 	 * Sched callbacks are disabled now.  Zap nr_running.  After this,
3508628c78e7STejun Heo 	 * nr_running stays zero and need_more_worker() and keep_working()
3509628c78e7STejun Heo 	 * are always true as long as the worklist is not empty.  @gcwq now
3510628c78e7STejun Heo 	 * behaves as unbound (in terms of concurrency management) gcwq
3511628c78e7STejun Heo 	 * which is served by workers tied to the CPU.
3512628c78e7STejun Heo 	 *
3513628c78e7STejun Heo 	 * On return from this function, the current worker would trigger
3514628c78e7STejun Heo 	 * unbound chain execution of pending work items if other workers
3515628c78e7STejun Heo 	 * didn't already.
3516e22bee78STejun Heo 	 */
35174ce62e9eSTejun Heo 	for_each_worker_pool(pool, gcwq)
35184ce62e9eSTejun Heo 		atomic_set(get_pool_nr_running(pool), 0);
3519db7bccf4STejun Heo }
3520db7bccf4STejun Heo 
35218db25e78STejun Heo /*
35228db25e78STejun Heo  * Workqueues should be brought up before normal priority CPU notifiers.
35238db25e78STejun Heo  * This will be registered high priority CPU notifier.
35248db25e78STejun Heo  */
35258db25e78STejun Heo static int __devinit workqueue_cpu_up_callback(struct notifier_block *nfb,
35261da177e4SLinus Torvalds 					       unsigned long action,
35271da177e4SLinus Torvalds 					       void *hcpu)
35281da177e4SLinus Torvalds {
35293af24433SOleg Nesterov 	unsigned int cpu = (unsigned long)hcpu;
3530db7bccf4STejun Heo 	struct global_cwq *gcwq = get_gcwq(cpu);
35314ce62e9eSTejun Heo 	struct worker_pool *pool;
35321da177e4SLinus Torvalds 
35338db25e78STejun Heo 	switch (action & ~CPU_TASKS_FROZEN) {
35343af24433SOleg Nesterov 	case CPU_UP_PREPARE:
35354ce62e9eSTejun Heo 		for_each_worker_pool(pool, gcwq) {
35363ce63377STejun Heo 			struct worker *worker;
35373ce63377STejun Heo 
35383ce63377STejun Heo 			if (pool->nr_workers)
35393ce63377STejun Heo 				continue;
35403ce63377STejun Heo 
35413ce63377STejun Heo 			worker = create_worker(pool);
35423ce63377STejun Heo 			if (!worker)
35433ce63377STejun Heo 				return NOTIFY_BAD;
35443ce63377STejun Heo 
35453ce63377STejun Heo 			spin_lock_irq(&gcwq->lock);
35463ce63377STejun Heo 			start_worker(worker);
35473ce63377STejun Heo 			spin_unlock_irq(&gcwq->lock);
35483af24433SOleg Nesterov 		}
35491da177e4SLinus Torvalds 		break;
35501da177e4SLinus Torvalds 
355165758202STejun Heo 	case CPU_DOWN_FAILED:
355265758202STejun Heo 	case CPU_ONLINE:
35538db25e78STejun Heo 		gcwq_claim_management_and_lock(gcwq);
35548db25e78STejun Heo 		gcwq->flags &= ~GCWQ_DISASSOCIATED;
35558db25e78STejun Heo 		rebind_workers(gcwq);
35568db25e78STejun Heo 		gcwq_release_management_and_unlock(gcwq);
35578db25e78STejun Heo 		break;
355865758202STejun Heo 	}
355965758202STejun Heo 	return NOTIFY_OK;
356065758202STejun Heo }
356165758202STejun Heo 
356265758202STejun Heo /*
356365758202STejun Heo  * Workqueues should be brought down after normal priority CPU notifiers.
356465758202STejun Heo  * This will be registered as low priority CPU notifier.
356565758202STejun Heo  */
356665758202STejun Heo static int __devinit workqueue_cpu_down_callback(struct notifier_block *nfb,
356765758202STejun Heo 						 unsigned long action,
356865758202STejun Heo 						 void *hcpu)
356965758202STejun Heo {
35708db25e78STejun Heo 	unsigned int cpu = (unsigned long)hcpu;
35718db25e78STejun Heo 	struct work_struct unbind_work;
35728db25e78STejun Heo 
357365758202STejun Heo 	switch (action & ~CPU_TASKS_FROZEN) {
357465758202STejun Heo 	case CPU_DOWN_PREPARE:
35758db25e78STejun Heo 		/* unbinding should happen on the local CPU */
35768db25e78STejun Heo 		INIT_WORK_ONSTACK(&unbind_work, gcwq_unbind_fn);
35777635d2fdSJoonsoo Kim 		queue_work_on(cpu, system_highpri_wq, &unbind_work);
35788db25e78STejun Heo 		flush_work(&unbind_work);
35798db25e78STejun Heo 		break;
358065758202STejun Heo 	}
358165758202STejun Heo 	return NOTIFY_OK;
358265758202STejun Heo }
358365758202STejun Heo 
35842d3854a3SRusty Russell #ifdef CONFIG_SMP
35858ccad40dSRusty Russell 
35862d3854a3SRusty Russell struct work_for_cpu {
35876b44003eSAndrew Morton 	struct completion completion;
35882d3854a3SRusty Russell 	long (*fn)(void *);
35892d3854a3SRusty Russell 	void *arg;
35902d3854a3SRusty Russell 	long ret;
35912d3854a3SRusty Russell };
35922d3854a3SRusty Russell 
35936b44003eSAndrew Morton static int do_work_for_cpu(void *_wfc)
35942d3854a3SRusty Russell {
35956b44003eSAndrew Morton 	struct work_for_cpu *wfc = _wfc;
35962d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
35976b44003eSAndrew Morton 	complete(&wfc->completion);
35986b44003eSAndrew Morton 	return 0;
35992d3854a3SRusty Russell }
36002d3854a3SRusty Russell 
36012d3854a3SRusty Russell /**
36022d3854a3SRusty Russell  * work_on_cpu - run a function in user context on a particular cpu
36032d3854a3SRusty Russell  * @cpu: the cpu to run on
36042d3854a3SRusty Russell  * @fn: the function to run
36052d3854a3SRusty Russell  * @arg: the function arg
36062d3854a3SRusty Russell  *
360731ad9081SRusty Russell  * This will return the value @fn returns.
360831ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
36096b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
36102d3854a3SRusty Russell  */
36112d3854a3SRusty Russell long work_on_cpu(unsigned int cpu, long (*fn)(void *), void *arg)
36122d3854a3SRusty Russell {
36136b44003eSAndrew Morton 	struct task_struct *sub_thread;
36146b44003eSAndrew Morton 	struct work_for_cpu wfc = {
36156b44003eSAndrew Morton 		.completion = COMPLETION_INITIALIZER_ONSTACK(wfc.completion),
36166b44003eSAndrew Morton 		.fn = fn,
36176b44003eSAndrew Morton 		.arg = arg,
36186b44003eSAndrew Morton 	};
36192d3854a3SRusty Russell 
36206b44003eSAndrew Morton 	sub_thread = kthread_create(do_work_for_cpu, &wfc, "work_for_cpu");
36216b44003eSAndrew Morton 	if (IS_ERR(sub_thread))
36226b44003eSAndrew Morton 		return PTR_ERR(sub_thread);
36236b44003eSAndrew Morton 	kthread_bind(sub_thread, cpu);
36246b44003eSAndrew Morton 	wake_up_process(sub_thread);
36256b44003eSAndrew Morton 	wait_for_completion(&wfc.completion);
36262d3854a3SRusty Russell 	return wfc.ret;
36272d3854a3SRusty Russell }
36282d3854a3SRusty Russell EXPORT_SYMBOL_GPL(work_on_cpu);
36292d3854a3SRusty Russell #endif /* CONFIG_SMP */
36302d3854a3SRusty Russell 
3631a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
3632e7577c50SRusty Russell 
3633a0a1a5fdSTejun Heo /**
3634a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
3635a0a1a5fdSTejun Heo  *
363658a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
363758a69cb4STejun Heo  * workqueues will queue new works to their frozen_works list instead of
363858a69cb4STejun Heo  * gcwq->worklist.
3639a0a1a5fdSTejun Heo  *
3640a0a1a5fdSTejun Heo  * CONTEXT:
36418b03ae3cSTejun Heo  * Grabs and releases workqueue_lock and gcwq->lock's.
3642a0a1a5fdSTejun Heo  */
3643a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
3644a0a1a5fdSTejun Heo {
3645a0a1a5fdSTejun Heo 	unsigned int cpu;
3646a0a1a5fdSTejun Heo 
3647a0a1a5fdSTejun Heo 	spin_lock(&workqueue_lock);
3648a0a1a5fdSTejun Heo 
3649a0a1a5fdSTejun Heo 	BUG_ON(workqueue_freezing);
3650a0a1a5fdSTejun Heo 	workqueue_freezing = true;
3651a0a1a5fdSTejun Heo 
3652f3421797STejun Heo 	for_each_gcwq_cpu(cpu) {
36538b03ae3cSTejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
3654bdbc5dd7STejun Heo 		struct workqueue_struct *wq;
36558b03ae3cSTejun Heo 
36568b03ae3cSTejun Heo 		spin_lock_irq(&gcwq->lock);
36578b03ae3cSTejun Heo 
3658db7bccf4STejun Heo 		BUG_ON(gcwq->flags & GCWQ_FREEZING);
3659db7bccf4STejun Heo 		gcwq->flags |= GCWQ_FREEZING;
3660db7bccf4STejun Heo 
3661a0a1a5fdSTejun Heo 		list_for_each_entry(wq, &workqueues, list) {
3662a0a1a5fdSTejun Heo 			struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3663a0a1a5fdSTejun Heo 
366458a69cb4STejun Heo 			if (cwq && wq->flags & WQ_FREEZABLE)
3665a0a1a5fdSTejun Heo 				cwq->max_active = 0;
36661da177e4SLinus Torvalds 		}
36678b03ae3cSTejun Heo 
36688b03ae3cSTejun Heo 		spin_unlock_irq(&gcwq->lock);
3669a0a1a5fdSTejun Heo 	}
3670a0a1a5fdSTejun Heo 
3671a0a1a5fdSTejun Heo 	spin_unlock(&workqueue_lock);
3672a0a1a5fdSTejun Heo }
3673a0a1a5fdSTejun Heo 
3674a0a1a5fdSTejun Heo /**
367558a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
3676a0a1a5fdSTejun Heo  *
3677a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
3678a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
3679a0a1a5fdSTejun Heo  *
3680a0a1a5fdSTejun Heo  * CONTEXT:
3681a0a1a5fdSTejun Heo  * Grabs and releases workqueue_lock.
3682a0a1a5fdSTejun Heo  *
3683a0a1a5fdSTejun Heo  * RETURNS:
368458a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
368558a69cb4STejun Heo  * is complete.
3686a0a1a5fdSTejun Heo  */
3687a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
3688a0a1a5fdSTejun Heo {
3689a0a1a5fdSTejun Heo 	unsigned int cpu;
3690a0a1a5fdSTejun Heo 	bool busy = false;
3691a0a1a5fdSTejun Heo 
3692a0a1a5fdSTejun Heo 	spin_lock(&workqueue_lock);
3693a0a1a5fdSTejun Heo 
3694a0a1a5fdSTejun Heo 	BUG_ON(!workqueue_freezing);
3695a0a1a5fdSTejun Heo 
3696f3421797STejun Heo 	for_each_gcwq_cpu(cpu) {
3697bdbc5dd7STejun Heo 		struct workqueue_struct *wq;
3698a0a1a5fdSTejun Heo 		/*
3699a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
3700a0a1a5fdSTejun Heo 		 * to peek without lock.
3701a0a1a5fdSTejun Heo 		 */
3702a0a1a5fdSTejun Heo 		list_for_each_entry(wq, &workqueues, list) {
3703a0a1a5fdSTejun Heo 			struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3704a0a1a5fdSTejun Heo 
370558a69cb4STejun Heo 			if (!cwq || !(wq->flags & WQ_FREEZABLE))
3706a0a1a5fdSTejun Heo 				continue;
3707a0a1a5fdSTejun Heo 
3708a0a1a5fdSTejun Heo 			BUG_ON(cwq->nr_active < 0);
3709a0a1a5fdSTejun Heo 			if (cwq->nr_active) {
3710a0a1a5fdSTejun Heo 				busy = true;
3711a0a1a5fdSTejun Heo 				goto out_unlock;
3712a0a1a5fdSTejun Heo 			}
3713a0a1a5fdSTejun Heo 		}
3714a0a1a5fdSTejun Heo 	}
3715a0a1a5fdSTejun Heo out_unlock:
3716a0a1a5fdSTejun Heo 	spin_unlock(&workqueue_lock);
3717a0a1a5fdSTejun Heo 	return busy;
3718a0a1a5fdSTejun Heo }
3719a0a1a5fdSTejun Heo 
3720a0a1a5fdSTejun Heo /**
3721a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
3722a0a1a5fdSTejun Heo  *
3723a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
37247e11629dSTejun Heo  * frozen works are transferred to their respective gcwq worklists.
3725a0a1a5fdSTejun Heo  *
3726a0a1a5fdSTejun Heo  * CONTEXT:
37278b03ae3cSTejun Heo  * Grabs and releases workqueue_lock and gcwq->lock's.
3728a0a1a5fdSTejun Heo  */
3729a0a1a5fdSTejun Heo void thaw_workqueues(void)
3730a0a1a5fdSTejun Heo {
3731a0a1a5fdSTejun Heo 	unsigned int cpu;
3732a0a1a5fdSTejun Heo 
3733a0a1a5fdSTejun Heo 	spin_lock(&workqueue_lock);
3734a0a1a5fdSTejun Heo 
3735a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
3736a0a1a5fdSTejun Heo 		goto out_unlock;
3737a0a1a5fdSTejun Heo 
3738f3421797STejun Heo 	for_each_gcwq_cpu(cpu) {
37398b03ae3cSTejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
37404ce62e9eSTejun Heo 		struct worker_pool *pool;
3741bdbc5dd7STejun Heo 		struct workqueue_struct *wq;
37428b03ae3cSTejun Heo 
37438b03ae3cSTejun Heo 		spin_lock_irq(&gcwq->lock);
37448b03ae3cSTejun Heo 
3745db7bccf4STejun Heo 		BUG_ON(!(gcwq->flags & GCWQ_FREEZING));
3746db7bccf4STejun Heo 		gcwq->flags &= ~GCWQ_FREEZING;
3747db7bccf4STejun Heo 
3748a0a1a5fdSTejun Heo 		list_for_each_entry(wq, &workqueues, list) {
3749a0a1a5fdSTejun Heo 			struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3750a0a1a5fdSTejun Heo 
375158a69cb4STejun Heo 			if (!cwq || !(wq->flags & WQ_FREEZABLE))
3752a0a1a5fdSTejun Heo 				continue;
3753a0a1a5fdSTejun Heo 
3754a0a1a5fdSTejun Heo 			/* restore max_active and repopulate worklist */
3755a0a1a5fdSTejun Heo 			cwq->max_active = wq->saved_max_active;
3756a0a1a5fdSTejun Heo 
3757a0a1a5fdSTejun Heo 			while (!list_empty(&cwq->delayed_works) &&
3758a0a1a5fdSTejun Heo 			       cwq->nr_active < cwq->max_active)
3759a0a1a5fdSTejun Heo 				cwq_activate_first_delayed(cwq);
3760a0a1a5fdSTejun Heo 		}
37618b03ae3cSTejun Heo 
37624ce62e9eSTejun Heo 		for_each_worker_pool(pool, gcwq)
37634ce62e9eSTejun Heo 			wake_up_worker(pool);
3764e22bee78STejun Heo 
37658b03ae3cSTejun Heo 		spin_unlock_irq(&gcwq->lock);
3766a0a1a5fdSTejun Heo 	}
3767a0a1a5fdSTejun Heo 
3768a0a1a5fdSTejun Heo 	workqueue_freezing = false;
3769a0a1a5fdSTejun Heo out_unlock:
3770a0a1a5fdSTejun Heo 	spin_unlock(&workqueue_lock);
3771a0a1a5fdSTejun Heo }
3772a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
3773a0a1a5fdSTejun Heo 
37746ee0578bSSuresh Siddha static int __init init_workqueues(void)
37751da177e4SLinus Torvalds {
3776c34056a3STejun Heo 	unsigned int cpu;
3777c8e55f36STejun Heo 	int i;
3778c34056a3STejun Heo 
3779b5490077STejun Heo 	/* make sure we have enough bits for OFFQ CPU number */
3780b5490077STejun Heo 	BUILD_BUG_ON((1LU << (BITS_PER_LONG - WORK_OFFQ_CPU_SHIFT)) <
3781b5490077STejun Heo 		     WORK_CPU_LAST);
3782b5490077STejun Heo 
378365758202STejun Heo 	cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
378465758202STejun Heo 	cpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
37858b03ae3cSTejun Heo 
37868b03ae3cSTejun Heo 	/* initialize gcwqs */
3787f3421797STejun Heo 	for_each_gcwq_cpu(cpu) {
37888b03ae3cSTejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
37894ce62e9eSTejun Heo 		struct worker_pool *pool;
37908b03ae3cSTejun Heo 
37918b03ae3cSTejun Heo 		spin_lock_init(&gcwq->lock);
37928b03ae3cSTejun Heo 		gcwq->cpu = cpu;
3793f3421797STejun Heo 		gcwq->flags |= GCWQ_DISASSOCIATED;
37948b03ae3cSTejun Heo 
3795c8e55f36STejun Heo 		for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)
3796c8e55f36STejun Heo 			INIT_HLIST_HEAD(&gcwq->busy_hash[i]);
3797c8e55f36STejun Heo 
37984ce62e9eSTejun Heo 		for_each_worker_pool(pool, gcwq) {
37994ce62e9eSTejun Heo 			pool->gcwq = gcwq;
38004ce62e9eSTejun Heo 			INIT_LIST_HEAD(&pool->worklist);
38014ce62e9eSTejun Heo 			INIT_LIST_HEAD(&pool->idle_list);
3802e22bee78STejun Heo 
38034ce62e9eSTejun Heo 			init_timer_deferrable(&pool->idle_timer);
38044ce62e9eSTejun Heo 			pool->idle_timer.function = idle_worker_timeout;
38054ce62e9eSTejun Heo 			pool->idle_timer.data = (unsigned long)pool;
3806e22bee78STejun Heo 
38074ce62e9eSTejun Heo 			setup_timer(&pool->mayday_timer, gcwq_mayday_timeout,
38084ce62e9eSTejun Heo 				    (unsigned long)pool);
38094ce62e9eSTejun Heo 
381060373152STejun Heo 			mutex_init(&pool->manager_mutex);
38114ce62e9eSTejun Heo 			ida_init(&pool->worker_ida);
38124ce62e9eSTejun Heo 		}
3813db7bccf4STejun Heo 
381425511a47STejun Heo 		init_waitqueue_head(&gcwq->rebind_hold);
38158b03ae3cSTejun Heo 	}
38168b03ae3cSTejun Heo 
3817e22bee78STejun Heo 	/* create the initial worker */
3818f3421797STejun Heo 	for_each_online_gcwq_cpu(cpu) {
3819e22bee78STejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
38204ce62e9eSTejun Heo 		struct worker_pool *pool;
3821e22bee78STejun Heo 
3822477a3c33STejun Heo 		if (cpu != WORK_CPU_UNBOUND)
3823477a3c33STejun Heo 			gcwq->flags &= ~GCWQ_DISASSOCIATED;
38244ce62e9eSTejun Heo 
38254ce62e9eSTejun Heo 		for_each_worker_pool(pool, gcwq) {
38264ce62e9eSTejun Heo 			struct worker *worker;
38274ce62e9eSTejun Heo 
3828bc2ae0f5STejun Heo 			worker = create_worker(pool);
3829e22bee78STejun Heo 			BUG_ON(!worker);
3830e22bee78STejun Heo 			spin_lock_irq(&gcwq->lock);
3831e22bee78STejun Heo 			start_worker(worker);
3832e22bee78STejun Heo 			spin_unlock_irq(&gcwq->lock);
3833e22bee78STejun Heo 		}
38344ce62e9eSTejun Heo 	}
3835e22bee78STejun Heo 
3836d320c038STejun Heo 	system_wq = alloc_workqueue("events", 0, 0);
38371aabe902SJoonsoo Kim 	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
3838d320c038STejun Heo 	system_long_wq = alloc_workqueue("events_long", 0, 0);
3839f3421797STejun Heo 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
3840f3421797STejun Heo 					    WQ_UNBOUND_MAX_ACTIVE);
384124d51addSTejun Heo 	system_freezable_wq = alloc_workqueue("events_freezable",
384224d51addSTejun Heo 					      WQ_FREEZABLE, 0);
38431aabe902SJoonsoo Kim 	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
3844ae930e0fSTejun Heo 	       !system_unbound_wq || !system_freezable_wq);
38456ee0578bSSuresh Siddha 	return 0;
38461da177e4SLinus Torvalds }
38476ee0578bSSuresh Siddha early_initcall(init_workqueues);
3848