xref: /linux-6.15/kernel/workqueue.c (revision ed48ece2)
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 */
69552a37e9SLai Jiangshan 	POOL_MANAGING_WORKERS   = 1 << 1,       /* managing workers */
70db7bccf4STejun Heo 
71c8e55f36STejun Heo 	/* worker flags */
72c8e55f36STejun Heo 	WORKER_STARTED		= 1 << 0,	/* started */
73c8e55f36STejun Heo 	WORKER_DIE		= 1 << 1,	/* die die die */
74c8e55f36STejun Heo 	WORKER_IDLE		= 1 << 2,	/* is idle */
75e22bee78STejun Heo 	WORKER_PREP		= 1 << 3,	/* preparing to run works */
76e22bee78STejun Heo 	WORKER_REBIND		= 1 << 5,	/* mom is home, come back */
77fb0e7bebSTejun Heo 	WORKER_CPU_INTENSIVE	= 1 << 6,	/* cpu intensive */
78f3421797STejun Heo 	WORKER_UNBOUND		= 1 << 7,	/* worker is unbound */
79e22bee78STejun Heo 
80403c821dSTejun Heo 	WORKER_NOT_RUNNING	= WORKER_PREP | WORKER_REBIND | WORKER_UNBOUND |
81403c821dSTejun Heo 				  WORKER_CPU_INTENSIVE,
82db7bccf4STejun Heo 
833270476aSTejun Heo 	NR_WORKER_POOLS		= 2,		/* # worker pools per gcwq */
844ce62e9eSTejun Heo 
85c8e55f36STejun Heo 	BUSY_WORKER_HASH_ORDER	= 6,		/* 64 pointers */
86c8e55f36STejun Heo 	BUSY_WORKER_HASH_SIZE	= 1 << BUSY_WORKER_HASH_ORDER,
87c8e55f36STejun Heo 	BUSY_WORKER_HASH_MASK	= BUSY_WORKER_HASH_SIZE - 1,
88db7bccf4STejun Heo 
89e22bee78STejun Heo 	MAX_IDLE_WORKERS_RATIO	= 4,		/* 1/4 of busy can be idle */
90e22bee78STejun Heo 	IDLE_WORKER_TIMEOUT	= 300 * HZ,	/* keep idle ones for 5 mins */
91e22bee78STejun Heo 
923233cdbdSTejun Heo 	MAYDAY_INITIAL_TIMEOUT  = HZ / 100 >= 2 ? HZ / 100 : 2,
933233cdbdSTejun Heo 						/* call for help after 10ms
943233cdbdSTejun Heo 						   (min two ticks) */
95e22bee78STejun Heo 	MAYDAY_INTERVAL		= HZ / 10,	/* and then every 100ms */
96e22bee78STejun Heo 	CREATE_COOLDOWN		= HZ,		/* time to breath after fail */
971da177e4SLinus Torvalds 
981da177e4SLinus Torvalds 	/*
99e22bee78STejun Heo 	 * Rescue workers are used only on emergencies and shared by
100e22bee78STejun Heo 	 * all cpus.  Give -20.
101e22bee78STejun Heo 	 */
102e22bee78STejun Heo 	RESCUER_NICE_LEVEL	= -20,
1033270476aSTejun Heo 	HIGHPRI_NICE_LEVEL	= -20,
104c8e55f36STejun Heo };
105c8e55f36STejun Heo 
1061da177e4SLinus Torvalds /*
1074690c4abSTejun Heo  * Structure fields follow one of the following exclusion rules.
1084690c4abSTejun Heo  *
109e41e704bSTejun Heo  * I: Modifiable by initialization/destruction paths and read-only for
110e41e704bSTejun Heo  *    everyone else.
1114690c4abSTejun Heo  *
112e22bee78STejun Heo  * P: Preemption protected.  Disabling preemption is enough and should
113e22bee78STejun Heo  *    only be modified and accessed from the local cpu.
114e22bee78STejun Heo  *
1158b03ae3cSTejun Heo  * L: gcwq->lock protected.  Access with gcwq->lock held.
1164690c4abSTejun Heo  *
117e22bee78STejun Heo  * X: During normal operation, modification requires gcwq->lock and
118e22bee78STejun Heo  *    should be done only from local cpu.  Either disabling preemption
119e22bee78STejun Heo  *    on local cpu or grabbing gcwq->lock is enough for read access.
120f3421797STejun Heo  *    If GCWQ_DISASSOCIATED is set, it's identical to L.
121e22bee78STejun Heo  *
12273f53c4aSTejun Heo  * F: wq->flush_mutex protected.
12373f53c4aSTejun Heo  *
1244690c4abSTejun Heo  * W: workqueue_lock protected.
1254690c4abSTejun Heo  */
1264690c4abSTejun Heo 
1278b03ae3cSTejun Heo struct global_cwq;
128bd7bdd43STejun Heo struct worker_pool;
12925511a47STejun Heo struct idle_rebind;
130c34056a3STejun Heo 
131e22bee78STejun Heo /*
132e22bee78STejun Heo  * The poor guys doing the actual heavy lifting.  All on-duty workers
133e22bee78STejun Heo  * are either serving the manager role, on idle list or on busy hash.
134e22bee78STejun Heo  */
135c34056a3STejun Heo struct worker {
136c8e55f36STejun Heo 	/* on idle list while idle, on busy hash table while busy */
137c8e55f36STejun Heo 	union {
138c8e55f36STejun Heo 		struct list_head	entry;	/* L: while idle */
139c8e55f36STejun Heo 		struct hlist_node	hentry;	/* L: while busy */
140c8e55f36STejun Heo 	};
141c8e55f36STejun Heo 
142c34056a3STejun Heo 	struct work_struct	*current_work;	/* L: work being processed */
1438cca0eeaSTejun Heo 	struct cpu_workqueue_struct *current_cwq; /* L: current_work's cwq */
144affee4b2STejun Heo 	struct list_head	scheduled;	/* L: scheduled works */
145c34056a3STejun Heo 	struct task_struct	*task;		/* I: worker task */
146bd7bdd43STejun Heo 	struct worker_pool	*pool;		/* I: the associated pool */
147e22bee78STejun Heo 	/* 64 bytes boundary on 64bit, 32 on 32bit */
148e22bee78STejun Heo 	unsigned long		last_active;	/* L: last active timestamp */
149e22bee78STejun Heo 	unsigned int		flags;		/* X: flags */
150c34056a3STejun Heo 	int			id;		/* I: worker id */
15125511a47STejun Heo 
15225511a47STejun Heo 	/* for rebinding worker to CPU */
15325511a47STejun Heo 	struct idle_rebind	*idle_rebind;	/* L: for idle worker */
15425511a47STejun Heo 	struct work_struct	rebind_work;	/* L: for busy worker */
155c34056a3STejun Heo };
156c34056a3STejun Heo 
157bd7bdd43STejun Heo struct worker_pool {
158bd7bdd43STejun Heo 	struct global_cwq	*gcwq;		/* I: the owning gcwq */
15911ebea50STejun Heo 	unsigned int		flags;		/* X: flags */
160bd7bdd43STejun Heo 
161bd7bdd43STejun Heo 	struct list_head	worklist;	/* L: list of pending works */
162bd7bdd43STejun Heo 	int			nr_workers;	/* L: total number of workers */
163bd7bdd43STejun Heo 	int			nr_idle;	/* L: currently idle ones */
164bd7bdd43STejun Heo 
165bd7bdd43STejun Heo 	struct list_head	idle_list;	/* X: list of idle workers */
166bd7bdd43STejun Heo 	struct timer_list	idle_timer;	/* L: worker idle timeout */
167bd7bdd43STejun Heo 	struct timer_list	mayday_timer;	/* L: SOS timer for workers */
168bd7bdd43STejun Heo 
16960373152STejun Heo 	struct mutex		manager_mutex;	/* mutex manager should hold */
170bd7bdd43STejun Heo 	struct ida		worker_ida;	/* L: for worker IDs */
171bd7bdd43STejun Heo };
172bd7bdd43STejun Heo 
1734690c4abSTejun Heo /*
174e22bee78STejun Heo  * Global per-cpu workqueue.  There's one and only one for each cpu
175e22bee78STejun Heo  * and all works are queued and processed here regardless of their
176e22bee78STejun Heo  * target workqueues.
1778b03ae3cSTejun Heo  */
1788b03ae3cSTejun Heo struct global_cwq {
1798b03ae3cSTejun Heo 	spinlock_t		lock;		/* the gcwq lock */
1808b03ae3cSTejun Heo 	unsigned int		cpu;		/* I: the associated cpu */
181db7bccf4STejun Heo 	unsigned int		flags;		/* L: GCWQ_* flags */
182c8e55f36STejun Heo 
183bd7bdd43STejun Heo 	/* workers are chained either in busy_hash or pool idle_list */
184c8e55f36STejun Heo 	struct hlist_head	busy_hash[BUSY_WORKER_HASH_SIZE];
185c8e55f36STejun Heo 						/* L: hash of busy workers */
186c8e55f36STejun Heo 
1873270476aSTejun Heo 	struct worker_pool	pools[2];	/* 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 struct workqueue_struct *system_long_wq __read_mostly;
273d320c038STejun Heo struct workqueue_struct *system_nrt_wq __read_mostly;
274f3421797STejun Heo struct workqueue_struct *system_unbound_wq __read_mostly;
27524d51addSTejun Heo struct workqueue_struct *system_freezable_wq __read_mostly;
27662d3c543SAlan Stern struct workqueue_struct *system_nrt_freezable_wq __read_mostly;
277d320c038STejun Heo EXPORT_SYMBOL_GPL(system_wq);
278d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
279d320c038STejun Heo EXPORT_SYMBOL_GPL(system_nrt_wq);
280f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
28124d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
28262d3c543SAlan Stern EXPORT_SYMBOL_GPL(system_nrt_freezable_wq);
283d320c038STejun Heo 
28497bd2347STejun Heo #define CREATE_TRACE_POINTS
28597bd2347STejun Heo #include <trace/events/workqueue.h>
28697bd2347STejun Heo 
2874ce62e9eSTejun Heo #define for_each_worker_pool(pool, gcwq)				\
2883270476aSTejun Heo 	for ((pool) = &(gcwq)->pools[0];				\
2893270476aSTejun Heo 	     (pool) < &(gcwq)->pools[NR_WORKER_POOLS]; (pool)++)
2904ce62e9eSTejun Heo 
291db7bccf4STejun Heo #define for_each_busy_worker(worker, i, pos, gcwq)			\
292db7bccf4STejun Heo 	for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)			\
293db7bccf4STejun Heo 		hlist_for_each_entry(worker, pos, &gcwq->busy_hash[i], hentry)
294db7bccf4STejun Heo 
295f3421797STejun Heo static inline int __next_gcwq_cpu(int cpu, const struct cpumask *mask,
296f3421797STejun Heo 				  unsigned int sw)
297f3421797STejun Heo {
298f3421797STejun Heo 	if (cpu < nr_cpu_ids) {
299f3421797STejun Heo 		if (sw & 1) {
300f3421797STejun Heo 			cpu = cpumask_next(cpu, mask);
301f3421797STejun Heo 			if (cpu < nr_cpu_ids)
302f3421797STejun Heo 				return cpu;
303f3421797STejun Heo 		}
304f3421797STejun Heo 		if (sw & 2)
305f3421797STejun Heo 			return WORK_CPU_UNBOUND;
306f3421797STejun Heo 	}
307f3421797STejun Heo 	return WORK_CPU_NONE;
308f3421797STejun Heo }
309f3421797STejun Heo 
310f3421797STejun Heo static inline int __next_wq_cpu(int cpu, const struct cpumask *mask,
311f3421797STejun Heo 				struct workqueue_struct *wq)
312f3421797STejun Heo {
313f3421797STejun Heo 	return __next_gcwq_cpu(cpu, mask, !(wq->flags & WQ_UNBOUND) ? 1 : 2);
314f3421797STejun Heo }
315f3421797STejun Heo 
31609884951STejun Heo /*
31709884951STejun Heo  * CPU iterators
31809884951STejun Heo  *
31909884951STejun Heo  * An extra gcwq is defined for an invalid cpu number
32009884951STejun Heo  * (WORK_CPU_UNBOUND) to host workqueues which are not bound to any
32109884951STejun Heo  * specific CPU.  The following iterators are similar to
32209884951STejun Heo  * for_each_*_cpu() iterators but also considers the unbound gcwq.
32309884951STejun Heo  *
32409884951STejun Heo  * for_each_gcwq_cpu()		: possible CPUs + WORK_CPU_UNBOUND
32509884951STejun Heo  * for_each_online_gcwq_cpu()	: online CPUs + WORK_CPU_UNBOUND
32609884951STejun Heo  * for_each_cwq_cpu()		: possible CPUs for bound workqueues,
32709884951STejun Heo  *				  WORK_CPU_UNBOUND for unbound workqueues
32809884951STejun Heo  */
329f3421797STejun Heo #define for_each_gcwq_cpu(cpu)						\
330f3421797STejun Heo 	for ((cpu) = __next_gcwq_cpu(-1, cpu_possible_mask, 3);		\
331f3421797STejun Heo 	     (cpu) < WORK_CPU_NONE;					\
332f3421797STejun Heo 	     (cpu) = __next_gcwq_cpu((cpu), cpu_possible_mask, 3))
333f3421797STejun Heo 
334f3421797STejun Heo #define for_each_online_gcwq_cpu(cpu)					\
335f3421797STejun Heo 	for ((cpu) = __next_gcwq_cpu(-1, cpu_online_mask, 3);		\
336f3421797STejun Heo 	     (cpu) < WORK_CPU_NONE;					\
337f3421797STejun Heo 	     (cpu) = __next_gcwq_cpu((cpu), cpu_online_mask, 3))
338f3421797STejun Heo 
339f3421797STejun Heo #define for_each_cwq_cpu(cpu, wq)					\
340f3421797STejun Heo 	for ((cpu) = __next_wq_cpu(-1, cpu_possible_mask, (wq));	\
341f3421797STejun Heo 	     (cpu) < WORK_CPU_NONE;					\
342f3421797STejun Heo 	     (cpu) = __next_wq_cpu((cpu), cpu_possible_mask, (wq)))
343f3421797STejun Heo 
344dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
345dc186ad7SThomas Gleixner 
346dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr;
347dc186ad7SThomas Gleixner 
34899777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
34999777288SStanislaw Gruszka {
35099777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
35199777288SStanislaw Gruszka }
35299777288SStanislaw Gruszka 
353dc186ad7SThomas Gleixner /*
354dc186ad7SThomas Gleixner  * fixup_init is called when:
355dc186ad7SThomas Gleixner  * - an active object is initialized
356dc186ad7SThomas Gleixner  */
357dc186ad7SThomas Gleixner static int work_fixup_init(void *addr, enum debug_obj_state state)
358dc186ad7SThomas Gleixner {
359dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
360dc186ad7SThomas Gleixner 
361dc186ad7SThomas Gleixner 	switch (state) {
362dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
363dc186ad7SThomas Gleixner 		cancel_work_sync(work);
364dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
365dc186ad7SThomas Gleixner 		return 1;
366dc186ad7SThomas Gleixner 	default:
367dc186ad7SThomas Gleixner 		return 0;
368dc186ad7SThomas Gleixner 	}
369dc186ad7SThomas Gleixner }
370dc186ad7SThomas Gleixner 
371dc186ad7SThomas Gleixner /*
372dc186ad7SThomas Gleixner  * fixup_activate is called when:
373dc186ad7SThomas Gleixner  * - an active object is activated
374dc186ad7SThomas Gleixner  * - an unknown object is activated (might be a statically initialized object)
375dc186ad7SThomas Gleixner  */
376dc186ad7SThomas Gleixner static int work_fixup_activate(void *addr, enum debug_obj_state state)
377dc186ad7SThomas Gleixner {
378dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
379dc186ad7SThomas Gleixner 
380dc186ad7SThomas Gleixner 	switch (state) {
381dc186ad7SThomas Gleixner 
382dc186ad7SThomas Gleixner 	case ODEBUG_STATE_NOTAVAILABLE:
383dc186ad7SThomas Gleixner 		/*
384dc186ad7SThomas Gleixner 		 * This is not really a fixup. The work struct was
385dc186ad7SThomas Gleixner 		 * statically initialized. We just make sure that it
386dc186ad7SThomas Gleixner 		 * is tracked in the object tracker.
387dc186ad7SThomas Gleixner 		 */
38822df02bbSTejun Heo 		if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
389dc186ad7SThomas Gleixner 			debug_object_init(work, &work_debug_descr);
390dc186ad7SThomas Gleixner 			debug_object_activate(work, &work_debug_descr);
391dc186ad7SThomas Gleixner 			return 0;
392dc186ad7SThomas Gleixner 		}
393dc186ad7SThomas Gleixner 		WARN_ON_ONCE(1);
394dc186ad7SThomas Gleixner 		return 0;
395dc186ad7SThomas Gleixner 
396dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
397dc186ad7SThomas Gleixner 		WARN_ON(1);
398dc186ad7SThomas Gleixner 
399dc186ad7SThomas Gleixner 	default:
400dc186ad7SThomas Gleixner 		return 0;
401dc186ad7SThomas Gleixner 	}
402dc186ad7SThomas Gleixner }
403dc186ad7SThomas Gleixner 
404dc186ad7SThomas Gleixner /*
405dc186ad7SThomas Gleixner  * fixup_free is called when:
406dc186ad7SThomas Gleixner  * - an active object is freed
407dc186ad7SThomas Gleixner  */
408dc186ad7SThomas Gleixner static int work_fixup_free(void *addr, enum debug_obj_state state)
409dc186ad7SThomas Gleixner {
410dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
411dc186ad7SThomas Gleixner 
412dc186ad7SThomas Gleixner 	switch (state) {
413dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
414dc186ad7SThomas Gleixner 		cancel_work_sync(work);
415dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
416dc186ad7SThomas Gleixner 		return 1;
417dc186ad7SThomas Gleixner 	default:
418dc186ad7SThomas Gleixner 		return 0;
419dc186ad7SThomas Gleixner 	}
420dc186ad7SThomas Gleixner }
421dc186ad7SThomas Gleixner 
422dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr = {
423dc186ad7SThomas Gleixner 	.name		= "work_struct",
42499777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
425dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
426dc186ad7SThomas Gleixner 	.fixup_activate	= work_fixup_activate,
427dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
428dc186ad7SThomas Gleixner };
429dc186ad7SThomas Gleixner 
430dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
431dc186ad7SThomas Gleixner {
432dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
433dc186ad7SThomas Gleixner }
434dc186ad7SThomas Gleixner 
435dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
436dc186ad7SThomas Gleixner {
437dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
438dc186ad7SThomas Gleixner }
439dc186ad7SThomas Gleixner 
440dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
441dc186ad7SThomas Gleixner {
442dc186ad7SThomas Gleixner 	if (onstack)
443dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
444dc186ad7SThomas Gleixner 	else
445dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
446dc186ad7SThomas Gleixner }
447dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
448dc186ad7SThomas Gleixner 
449dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
450dc186ad7SThomas Gleixner {
451dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
452dc186ad7SThomas Gleixner }
453dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
454dc186ad7SThomas Gleixner 
455dc186ad7SThomas Gleixner #else
456dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
457dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
458dc186ad7SThomas Gleixner #endif
459dc186ad7SThomas Gleixner 
46095402b38SGautham R Shenoy /* Serializes the accesses to the list of workqueues. */
46195402b38SGautham R Shenoy static DEFINE_SPINLOCK(workqueue_lock);
4621da177e4SLinus Torvalds static LIST_HEAD(workqueues);
463a0a1a5fdSTejun Heo static bool workqueue_freezing;		/* W: have wqs started freezing? */
4641da177e4SLinus Torvalds 
46514441960SOleg Nesterov /*
466e22bee78STejun Heo  * The almighty global cpu workqueues.  nr_running is the only field
467e22bee78STejun Heo  * which is expected to be used frequently by other cpus via
468e22bee78STejun Heo  * try_to_wake_up().  Put it in a separate cacheline.
46914441960SOleg Nesterov  */
4708b03ae3cSTejun Heo static DEFINE_PER_CPU(struct global_cwq, global_cwq);
4714ce62e9eSTejun Heo static DEFINE_PER_CPU_SHARED_ALIGNED(atomic_t, pool_nr_running[NR_WORKER_POOLS]);
472f756d5e2SNathan Lynch 
473f3421797STejun Heo /*
474f3421797STejun Heo  * Global cpu workqueue and nr_running counter for unbound gcwq.  The
475f3421797STejun Heo  * gcwq is always online, has GCWQ_DISASSOCIATED set, and all its
476f3421797STejun Heo  * workers have WORKER_UNBOUND set.
477f3421797STejun Heo  */
478f3421797STejun Heo static struct global_cwq unbound_global_cwq;
4794ce62e9eSTejun Heo static atomic_t unbound_pool_nr_running[NR_WORKER_POOLS] = {
4804ce62e9eSTejun Heo 	[0 ... NR_WORKER_POOLS - 1]	= ATOMIC_INIT(0),	/* always 0 */
4814ce62e9eSTejun Heo };
482f3421797STejun Heo 
483c34056a3STejun Heo static int worker_thread(void *__worker);
4841da177e4SLinus Torvalds 
4853270476aSTejun Heo static int worker_pool_pri(struct worker_pool *pool)
4863270476aSTejun Heo {
4873270476aSTejun Heo 	return pool - pool->gcwq->pools;
4883270476aSTejun Heo }
4893270476aSTejun Heo 
4908b03ae3cSTejun Heo static struct global_cwq *get_gcwq(unsigned int cpu)
4911da177e4SLinus Torvalds {
492f3421797STejun Heo 	if (cpu != WORK_CPU_UNBOUND)
4938b03ae3cSTejun Heo 		return &per_cpu(global_cwq, cpu);
494f3421797STejun Heo 	else
495f3421797STejun Heo 		return &unbound_global_cwq;
4961da177e4SLinus Torvalds }
4971da177e4SLinus Torvalds 
49863d95a91STejun Heo static atomic_t *get_pool_nr_running(struct worker_pool *pool)
499b1f4ec17SOleg Nesterov {
50063d95a91STejun Heo 	int cpu = pool->gcwq->cpu;
5013270476aSTejun Heo 	int idx = worker_pool_pri(pool);
50263d95a91STejun Heo 
503f3421797STejun Heo 	if (cpu != WORK_CPU_UNBOUND)
5044ce62e9eSTejun Heo 		return &per_cpu(pool_nr_running, cpu)[idx];
505f3421797STejun Heo 	else
5064ce62e9eSTejun Heo 		return &unbound_pool_nr_running[idx];
507b1f4ec17SOleg Nesterov }
508b1f4ec17SOleg Nesterov 
5094690c4abSTejun Heo static struct cpu_workqueue_struct *get_cwq(unsigned int cpu,
5104690c4abSTejun Heo 					    struct workqueue_struct *wq)
511a848e3b6SOleg Nesterov {
512f3421797STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
513e06ffa1eSLai Jiangshan 		if (likely(cpu < nr_cpu_ids))
514bdbc5dd7STejun Heo 			return per_cpu_ptr(wq->cpu_wq.pcpu, cpu);
515f3421797STejun Heo 	} else if (likely(cpu == WORK_CPU_UNBOUND))
516f3421797STejun Heo 		return wq->cpu_wq.single;
517f3421797STejun Heo 	return NULL;
518f3421797STejun Heo }
519a848e3b6SOleg Nesterov 
52073f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
52173f53c4aSTejun Heo {
52273f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
52373f53c4aSTejun Heo }
52473f53c4aSTejun Heo 
52573f53c4aSTejun Heo static int get_work_color(struct work_struct *work)
52673f53c4aSTejun Heo {
52773f53c4aSTejun Heo 	return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
52873f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
52973f53c4aSTejun Heo }
53073f53c4aSTejun Heo 
53173f53c4aSTejun Heo static int work_next_color(int color)
53273f53c4aSTejun Heo {
53373f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
5341da177e4SLinus Torvalds }
5351da177e4SLinus Torvalds 
5364594bf15SDavid Howells /*
537e120153dSTejun Heo  * A work's data points to the cwq with WORK_STRUCT_CWQ set while the
538e120153dSTejun Heo  * work is on queue.  Once execution starts, WORK_STRUCT_CWQ is
539e120153dSTejun Heo  * cleared and the work data contains the cpu number it was last on.
5407a22ad75STejun Heo  *
5417a22ad75STejun Heo  * set_work_{cwq|cpu}() and clear_work_data() can be used to set the
5427a22ad75STejun Heo  * cwq, cpu or clear work->data.  These functions should only be
5437a22ad75STejun Heo  * called while the work is owned - ie. while the PENDING bit is set.
5447a22ad75STejun Heo  *
5457a22ad75STejun Heo  * get_work_[g]cwq() can be used to obtain the gcwq or cwq
5467a22ad75STejun Heo  * corresponding to a work.  gcwq is available once the work has been
5477a22ad75STejun Heo  * queued anywhere after initialization.  cwq is available only from
5487a22ad75STejun Heo  * queueing until execution starts.
5494594bf15SDavid Howells  */
5507a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
5517a22ad75STejun Heo 				 unsigned long flags)
5527a22ad75STejun Heo {
5537a22ad75STejun Heo 	BUG_ON(!work_pending(work));
5547a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
5557a22ad75STejun Heo }
5567a22ad75STejun Heo 
5577a22ad75STejun Heo static void set_work_cwq(struct work_struct *work,
5584690c4abSTejun Heo 			 struct cpu_workqueue_struct *cwq,
5594690c4abSTejun Heo 			 unsigned long extra_flags)
560365970a1SDavid Howells {
5617a22ad75STejun Heo 	set_work_data(work, (unsigned long)cwq,
562e120153dSTejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_CWQ | extra_flags);
563365970a1SDavid Howells }
564365970a1SDavid Howells 
5657a22ad75STejun Heo static void set_work_cpu(struct work_struct *work, unsigned int cpu)
5664d707b9fSOleg Nesterov {
5677a22ad75STejun Heo 	set_work_data(work, cpu << WORK_STRUCT_FLAG_BITS, WORK_STRUCT_PENDING);
5684d707b9fSOleg Nesterov }
5694d707b9fSOleg Nesterov 
5707a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
571365970a1SDavid Howells {
5727a22ad75STejun Heo 	set_work_data(work, WORK_STRUCT_NO_CPU, 0);
5737a22ad75STejun Heo }
5747a22ad75STejun Heo 
5757a22ad75STejun Heo static struct cpu_workqueue_struct *get_work_cwq(struct work_struct *work)
5767a22ad75STejun Heo {
577e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
5787a22ad75STejun Heo 
579e120153dSTejun Heo 	if (data & WORK_STRUCT_CWQ)
580e120153dSTejun Heo 		return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
581e120153dSTejun Heo 	else
582e120153dSTejun Heo 		return NULL;
5837a22ad75STejun Heo }
5847a22ad75STejun Heo 
5857a22ad75STejun Heo static struct global_cwq *get_work_gcwq(struct work_struct *work)
5867a22ad75STejun Heo {
587e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
5887a22ad75STejun Heo 	unsigned int cpu;
5897a22ad75STejun Heo 
590e120153dSTejun Heo 	if (data & WORK_STRUCT_CWQ)
591e120153dSTejun Heo 		return ((struct cpu_workqueue_struct *)
592bd7bdd43STejun Heo 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool->gcwq;
5937a22ad75STejun Heo 
5947a22ad75STejun Heo 	cpu = data >> WORK_STRUCT_FLAG_BITS;
595bdbc5dd7STejun Heo 	if (cpu == WORK_CPU_NONE)
5967a22ad75STejun Heo 		return NULL;
5977a22ad75STejun Heo 
598f3421797STejun Heo 	BUG_ON(cpu >= nr_cpu_ids && cpu != WORK_CPU_UNBOUND);
5997a22ad75STejun Heo 	return get_gcwq(cpu);
600365970a1SDavid Howells }
601365970a1SDavid Howells 
602e22bee78STejun Heo /*
6033270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
6043270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
6053270476aSTejun Heo  * they're being called with gcwq->lock held.
606e22bee78STejun Heo  */
607e22bee78STejun Heo 
60863d95a91STejun Heo static bool __need_more_worker(struct worker_pool *pool)
609649027d7STejun Heo {
6103270476aSTejun Heo 	return !atomic_read(get_pool_nr_running(pool));
611649027d7STejun Heo }
612649027d7STejun Heo 
613e22bee78STejun Heo /*
614e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
615e22bee78STejun Heo  * running workers.
616974271c4STejun Heo  *
617974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
618974271c4STejun Heo  * function will always return %true for unbound gcwq as long as the
619974271c4STejun Heo  * worklist isn't empty.
620e22bee78STejun Heo  */
62163d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
622e22bee78STejun Heo {
62363d95a91STejun Heo 	return !list_empty(&pool->worklist) && __need_more_worker(pool);
624e22bee78STejun Heo }
625e22bee78STejun Heo 
626e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
62763d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
628e22bee78STejun Heo {
62963d95a91STejun Heo 	return pool->nr_idle;
630e22bee78STejun Heo }
631e22bee78STejun Heo 
632e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
63363d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
634e22bee78STejun Heo {
63563d95a91STejun Heo 	atomic_t *nr_running = get_pool_nr_running(pool);
636e22bee78STejun Heo 
6373270476aSTejun Heo 	return !list_empty(&pool->worklist) && atomic_read(nr_running) <= 1;
638e22bee78STejun Heo }
639e22bee78STejun Heo 
640e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
64163d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
642e22bee78STejun Heo {
64363d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
644e22bee78STejun Heo }
645e22bee78STejun Heo 
646e22bee78STejun Heo /* Do I need to be the manager? */
64763d95a91STejun Heo static bool need_to_manage_workers(struct worker_pool *pool)
648e22bee78STejun Heo {
64963d95a91STejun Heo 	return need_to_create_worker(pool) ||
65011ebea50STejun Heo 		(pool->flags & POOL_MANAGE_WORKERS);
651e22bee78STejun Heo }
652e22bee78STejun Heo 
653e22bee78STejun Heo /* Do we have too many workers and should some go away? */
65463d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
655e22bee78STejun Heo {
656552a37e9SLai Jiangshan 	bool managing = pool->flags & POOL_MANAGING_WORKERS;
65763d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
65863d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
659e22bee78STejun Heo 
660e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
661e22bee78STejun Heo }
662e22bee78STejun Heo 
663e22bee78STejun Heo /*
664e22bee78STejun Heo  * Wake up functions.
665e22bee78STejun Heo  */
666e22bee78STejun Heo 
6677e11629dSTejun Heo /* Return the first worker.  Safe with preemption disabled */
66863d95a91STejun Heo static struct worker *first_worker(struct worker_pool *pool)
6697e11629dSTejun Heo {
67063d95a91STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
6717e11629dSTejun Heo 		return NULL;
6727e11629dSTejun Heo 
67363d95a91STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
6747e11629dSTejun Heo }
6757e11629dSTejun Heo 
6767e11629dSTejun Heo /**
6777e11629dSTejun Heo  * wake_up_worker - wake up an idle worker
67863d95a91STejun Heo  * @pool: worker pool to wake worker from
6797e11629dSTejun Heo  *
68063d95a91STejun Heo  * Wake up the first idle worker of @pool.
6817e11629dSTejun Heo  *
6827e11629dSTejun Heo  * CONTEXT:
6837e11629dSTejun Heo  * spin_lock_irq(gcwq->lock).
6847e11629dSTejun Heo  */
68563d95a91STejun Heo static void wake_up_worker(struct worker_pool *pool)
6867e11629dSTejun Heo {
68763d95a91STejun Heo 	struct worker *worker = first_worker(pool);
6887e11629dSTejun Heo 
6897e11629dSTejun Heo 	if (likely(worker))
6907e11629dSTejun Heo 		wake_up_process(worker->task);
6917e11629dSTejun Heo }
6927e11629dSTejun Heo 
6934690c4abSTejun Heo /**
694e22bee78STejun Heo  * wq_worker_waking_up - a worker is waking up
695e22bee78STejun Heo  * @task: task waking up
696e22bee78STejun Heo  * @cpu: CPU @task is waking up to
697e22bee78STejun Heo  *
698e22bee78STejun Heo  * This function is called during try_to_wake_up() when a worker is
699e22bee78STejun Heo  * being awoken.
700e22bee78STejun Heo  *
701e22bee78STejun Heo  * CONTEXT:
702e22bee78STejun Heo  * spin_lock_irq(rq->lock)
703e22bee78STejun Heo  */
704e22bee78STejun Heo void wq_worker_waking_up(struct task_struct *task, unsigned int cpu)
705e22bee78STejun Heo {
706e22bee78STejun Heo 	struct worker *worker = kthread_data(task);
707e22bee78STejun Heo 
7082d64672eSSteven Rostedt 	if (!(worker->flags & WORKER_NOT_RUNNING))
70963d95a91STejun Heo 		atomic_inc(get_pool_nr_running(worker->pool));
710e22bee78STejun Heo }
711e22bee78STejun Heo 
712e22bee78STejun Heo /**
713e22bee78STejun Heo  * wq_worker_sleeping - a worker is going to sleep
714e22bee78STejun Heo  * @task: task going to sleep
715e22bee78STejun Heo  * @cpu: CPU in question, must be the current CPU number
716e22bee78STejun Heo  *
717e22bee78STejun Heo  * This function is called during schedule() when a busy worker is
718e22bee78STejun Heo  * going to sleep.  Worker on the same cpu can be woken up by
719e22bee78STejun Heo  * returning pointer to its task.
720e22bee78STejun Heo  *
721e22bee78STejun Heo  * CONTEXT:
722e22bee78STejun Heo  * spin_lock_irq(rq->lock)
723e22bee78STejun Heo  *
724e22bee78STejun Heo  * RETURNS:
725e22bee78STejun Heo  * Worker task on @cpu to wake up, %NULL if none.
726e22bee78STejun Heo  */
727e22bee78STejun Heo struct task_struct *wq_worker_sleeping(struct task_struct *task,
728e22bee78STejun Heo 				       unsigned int cpu)
729e22bee78STejun Heo {
730e22bee78STejun Heo 	struct worker *worker = kthread_data(task), *to_wakeup = NULL;
731bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
73263d95a91STejun Heo 	atomic_t *nr_running = get_pool_nr_running(pool);
733e22bee78STejun Heo 
7342d64672eSSteven Rostedt 	if (worker->flags & WORKER_NOT_RUNNING)
735e22bee78STejun Heo 		return NULL;
736e22bee78STejun Heo 
737e22bee78STejun Heo 	/* this can only happen on the local cpu */
738e22bee78STejun Heo 	BUG_ON(cpu != raw_smp_processor_id());
739e22bee78STejun Heo 
740e22bee78STejun Heo 	/*
741e22bee78STejun Heo 	 * The counterpart of the following dec_and_test, implied mb,
742e22bee78STejun Heo 	 * worklist not empty test sequence is in insert_work().
743e22bee78STejun Heo 	 * Please read comment there.
744e22bee78STejun Heo 	 *
745628c78e7STejun Heo 	 * NOT_RUNNING is clear.  This means that we're bound to and
746628c78e7STejun Heo 	 * running on the local cpu w/ rq lock held and preemption
747628c78e7STejun Heo 	 * disabled, which in turn means that none else could be
748628c78e7STejun Heo 	 * manipulating idle_list, so dereferencing idle_list without gcwq
749628c78e7STejun Heo 	 * lock is safe.
750e22bee78STejun Heo 	 */
751bd7bdd43STejun Heo 	if (atomic_dec_and_test(nr_running) && !list_empty(&pool->worklist))
75263d95a91STejun Heo 		to_wakeup = first_worker(pool);
753e22bee78STejun Heo 	return to_wakeup ? to_wakeup->task : NULL;
754e22bee78STejun Heo }
755e22bee78STejun Heo 
756e22bee78STejun Heo /**
757e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
758cb444766STejun Heo  * @worker: self
759d302f017STejun Heo  * @flags: flags to set
760d302f017STejun Heo  * @wakeup: wakeup an idle worker if necessary
761d302f017STejun Heo  *
762e22bee78STejun Heo  * Set @flags in @worker->flags and adjust nr_running accordingly.  If
763e22bee78STejun Heo  * nr_running becomes zero and @wakeup is %true, an idle worker is
764e22bee78STejun Heo  * woken up.
765d302f017STejun Heo  *
766cb444766STejun Heo  * CONTEXT:
767cb444766STejun Heo  * spin_lock_irq(gcwq->lock)
768d302f017STejun Heo  */
769d302f017STejun Heo static inline void worker_set_flags(struct worker *worker, unsigned int flags,
770d302f017STejun Heo 				    bool wakeup)
771d302f017STejun Heo {
772bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
773e22bee78STejun Heo 
774cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
775cb444766STejun Heo 
776e22bee78STejun Heo 	/*
777e22bee78STejun Heo 	 * If transitioning into NOT_RUNNING, adjust nr_running and
778e22bee78STejun Heo 	 * wake up an idle worker as necessary if requested by
779e22bee78STejun Heo 	 * @wakeup.
780e22bee78STejun Heo 	 */
781e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
782e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
78363d95a91STejun Heo 		atomic_t *nr_running = get_pool_nr_running(pool);
784e22bee78STejun Heo 
785e22bee78STejun Heo 		if (wakeup) {
786e22bee78STejun Heo 			if (atomic_dec_and_test(nr_running) &&
787bd7bdd43STejun Heo 			    !list_empty(&pool->worklist))
78863d95a91STejun Heo 				wake_up_worker(pool);
789e22bee78STejun Heo 		} else
790e22bee78STejun Heo 			atomic_dec(nr_running);
791e22bee78STejun Heo 	}
792e22bee78STejun Heo 
793d302f017STejun Heo 	worker->flags |= flags;
794d302f017STejun Heo }
795d302f017STejun Heo 
796d302f017STejun Heo /**
797e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
798cb444766STejun Heo  * @worker: self
799d302f017STejun Heo  * @flags: flags to clear
800d302f017STejun Heo  *
801e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
802d302f017STejun Heo  *
803cb444766STejun Heo  * CONTEXT:
804cb444766STejun Heo  * spin_lock_irq(gcwq->lock)
805d302f017STejun Heo  */
806d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
807d302f017STejun Heo {
80863d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
809e22bee78STejun Heo 	unsigned int oflags = worker->flags;
810e22bee78STejun Heo 
811cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
812cb444766STejun Heo 
813d302f017STejun Heo 	worker->flags &= ~flags;
814e22bee78STejun Heo 
81542c025f3STejun Heo 	/*
81642c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
81742c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
81842c025f3STejun Heo 	 * of multiple flags, not a single flag.
81942c025f3STejun Heo 	 */
820e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
821e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
82263d95a91STejun Heo 			atomic_inc(get_pool_nr_running(pool));
823d302f017STejun Heo }
824d302f017STejun Heo 
825d302f017STejun Heo /**
826c8e55f36STejun Heo  * busy_worker_head - return the busy hash head for a work
827c8e55f36STejun Heo  * @gcwq: gcwq of interest
828c8e55f36STejun Heo  * @work: work to be hashed
829c8e55f36STejun Heo  *
830c8e55f36STejun Heo  * Return hash head of @gcwq for @work.
831c8e55f36STejun Heo  *
832c8e55f36STejun Heo  * CONTEXT:
833c8e55f36STejun Heo  * spin_lock_irq(gcwq->lock).
834c8e55f36STejun Heo  *
835c8e55f36STejun Heo  * RETURNS:
836c8e55f36STejun Heo  * Pointer to the hash head.
837c8e55f36STejun Heo  */
838c8e55f36STejun Heo static struct hlist_head *busy_worker_head(struct global_cwq *gcwq,
839c8e55f36STejun Heo 					   struct work_struct *work)
840c8e55f36STejun Heo {
841c8e55f36STejun Heo 	const int base_shift = ilog2(sizeof(struct work_struct));
842c8e55f36STejun Heo 	unsigned long v = (unsigned long)work;
843c8e55f36STejun Heo 
844c8e55f36STejun Heo 	/* simple shift and fold hash, do we need something better? */
845c8e55f36STejun Heo 	v >>= base_shift;
846c8e55f36STejun Heo 	v += v >> BUSY_WORKER_HASH_ORDER;
847c8e55f36STejun Heo 	v &= BUSY_WORKER_HASH_MASK;
848c8e55f36STejun Heo 
849c8e55f36STejun Heo 	return &gcwq->busy_hash[v];
850c8e55f36STejun Heo }
851c8e55f36STejun Heo 
852c8e55f36STejun Heo /**
8538cca0eeaSTejun Heo  * __find_worker_executing_work - find worker which is executing a work
8548cca0eeaSTejun Heo  * @gcwq: gcwq of interest
8558cca0eeaSTejun Heo  * @bwh: hash head as returned by busy_worker_head()
8568cca0eeaSTejun Heo  * @work: work to find worker for
8578cca0eeaSTejun Heo  *
8588cca0eeaSTejun Heo  * Find a worker which is executing @work on @gcwq.  @bwh should be
8598cca0eeaSTejun Heo  * the hash head obtained by calling busy_worker_head() with the same
8608cca0eeaSTejun Heo  * work.
8618cca0eeaSTejun Heo  *
8628cca0eeaSTejun Heo  * CONTEXT:
8638cca0eeaSTejun Heo  * spin_lock_irq(gcwq->lock).
8648cca0eeaSTejun Heo  *
8658cca0eeaSTejun Heo  * RETURNS:
8668cca0eeaSTejun Heo  * Pointer to worker which is executing @work if found, NULL
8678cca0eeaSTejun Heo  * otherwise.
8688cca0eeaSTejun Heo  */
8698cca0eeaSTejun Heo static struct worker *__find_worker_executing_work(struct global_cwq *gcwq,
8708cca0eeaSTejun Heo 						   struct hlist_head *bwh,
8718cca0eeaSTejun Heo 						   struct work_struct *work)
8728cca0eeaSTejun Heo {
8738cca0eeaSTejun Heo 	struct worker *worker;
8748cca0eeaSTejun Heo 	struct hlist_node *tmp;
8758cca0eeaSTejun Heo 
8768cca0eeaSTejun Heo 	hlist_for_each_entry(worker, tmp, bwh, hentry)
8778cca0eeaSTejun Heo 		if (worker->current_work == work)
8788cca0eeaSTejun Heo 			return worker;
8798cca0eeaSTejun Heo 	return NULL;
8808cca0eeaSTejun Heo }
8818cca0eeaSTejun Heo 
8828cca0eeaSTejun Heo /**
8838cca0eeaSTejun Heo  * find_worker_executing_work - find worker which is executing a work
8848cca0eeaSTejun Heo  * @gcwq: gcwq of interest
8858cca0eeaSTejun Heo  * @work: work to find worker for
8868cca0eeaSTejun Heo  *
8878cca0eeaSTejun Heo  * Find a worker which is executing @work on @gcwq.  This function is
8888cca0eeaSTejun Heo  * identical to __find_worker_executing_work() except that this
8898cca0eeaSTejun Heo  * function calculates @bwh itself.
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 work_struct *work)
9008cca0eeaSTejun Heo {
9018cca0eeaSTejun Heo 	return __find_worker_executing_work(gcwq, busy_worker_head(gcwq, work),
9028cca0eeaSTejun Heo 					    work);
9038cca0eeaSTejun Heo }
9048cca0eeaSTejun Heo 
9058cca0eeaSTejun Heo /**
9067e11629dSTejun Heo  * insert_work - insert a work into gcwq
9074690c4abSTejun Heo  * @cwq: cwq @work belongs to
9084690c4abSTejun Heo  * @work: work to insert
9094690c4abSTejun Heo  * @head: insertion point
9104690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
9114690c4abSTejun Heo  *
9127e11629dSTejun Heo  * Insert @work which belongs to @cwq into @gcwq after @head.
9137e11629dSTejun Heo  * @extra_flags is or'd to work_struct flags.
9144690c4abSTejun Heo  *
9154690c4abSTejun Heo  * CONTEXT:
9168b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock).
9171da177e4SLinus Torvalds  */
918b89deed3SOleg Nesterov static void insert_work(struct cpu_workqueue_struct *cwq,
9194690c4abSTejun Heo 			struct work_struct *work, struct list_head *head,
9204690c4abSTejun Heo 			unsigned int extra_flags)
921b89deed3SOleg Nesterov {
92263d95a91STejun Heo 	struct worker_pool *pool = cwq->pool;
923e1d8aa9fSFrederic Weisbecker 
9244690c4abSTejun Heo 	/* we own @work, set data and link */
9257a22ad75STejun Heo 	set_work_cwq(work, cwq, extra_flags);
9264690c4abSTejun Heo 
9276e84d644SOleg Nesterov 	/*
9286e84d644SOleg Nesterov 	 * Ensure that we get the right work->data if we see the
9296e84d644SOleg Nesterov 	 * result of list_add() below, see try_to_grab_pending().
9306e84d644SOleg Nesterov 	 */
9316e84d644SOleg Nesterov 	smp_wmb();
9324690c4abSTejun Heo 
9331a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
934e22bee78STejun Heo 
935e22bee78STejun Heo 	/*
936e22bee78STejun Heo 	 * Ensure either worker_sched_deactivated() sees the above
937e22bee78STejun Heo 	 * list_add_tail() or we see zero nr_running to avoid workers
938e22bee78STejun Heo 	 * lying around lazily while there are works to be processed.
939e22bee78STejun Heo 	 */
940e22bee78STejun Heo 	smp_mb();
941e22bee78STejun Heo 
94263d95a91STejun Heo 	if (__need_more_worker(pool))
94363d95a91STejun Heo 		wake_up_worker(pool);
944b89deed3SOleg Nesterov }
945b89deed3SOleg Nesterov 
946c8efcc25STejun Heo /*
947c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
948c8efcc25STejun Heo  * same workqueue.  This is rather expensive and should only be used from
949c8efcc25STejun Heo  * cold paths.
950c8efcc25STejun Heo  */
951c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
952c8efcc25STejun Heo {
953c8efcc25STejun Heo 	unsigned long flags;
954c8efcc25STejun Heo 	unsigned int cpu;
955c8efcc25STejun Heo 
956c8efcc25STejun Heo 	for_each_gcwq_cpu(cpu) {
957c8efcc25STejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
958c8efcc25STejun Heo 		struct worker *worker;
959c8efcc25STejun Heo 		struct hlist_node *pos;
960c8efcc25STejun Heo 		int i;
961c8efcc25STejun Heo 
962c8efcc25STejun Heo 		spin_lock_irqsave(&gcwq->lock, flags);
963c8efcc25STejun Heo 		for_each_busy_worker(worker, i, pos, gcwq) {
964c8efcc25STejun Heo 			if (worker->task != current)
965c8efcc25STejun Heo 				continue;
966c8efcc25STejun Heo 			spin_unlock_irqrestore(&gcwq->lock, flags);
967c8efcc25STejun Heo 			/*
968c8efcc25STejun Heo 			 * I'm @worker, no locking necessary.  See if @work
969c8efcc25STejun Heo 			 * is headed to the same workqueue.
970c8efcc25STejun Heo 			 */
971c8efcc25STejun Heo 			return worker->current_cwq->wq == wq;
972c8efcc25STejun Heo 		}
973c8efcc25STejun Heo 		spin_unlock_irqrestore(&gcwq->lock, flags);
974c8efcc25STejun Heo 	}
975c8efcc25STejun Heo 	return false;
976c8efcc25STejun Heo }
977c8efcc25STejun Heo 
9784690c4abSTejun Heo static void __queue_work(unsigned int cpu, struct workqueue_struct *wq,
9791da177e4SLinus Torvalds 			 struct work_struct *work)
9801da177e4SLinus Torvalds {
981502ca9d8STejun Heo 	struct global_cwq *gcwq;
982502ca9d8STejun Heo 	struct cpu_workqueue_struct *cwq;
9831e19ffc6STejun Heo 	struct list_head *worklist;
9848a2e8e5dSTejun Heo 	unsigned int work_flags;
9851da177e4SLinus Torvalds 	unsigned long flags;
9861da177e4SLinus Torvalds 
987dc186ad7SThomas Gleixner 	debug_work_activate(work);
9881e19ffc6STejun Heo 
989c8efcc25STejun Heo 	/* if dying, only works from the same workqueue are allowed */
9909c5a2ba7STejun Heo 	if (unlikely(wq->flags & WQ_DRAINING) &&
991c8efcc25STejun Heo 	    WARN_ON_ONCE(!is_chained_work(wq)))
992e41e704bSTejun Heo 		return;
993e41e704bSTejun Heo 
994c7fc77f7STejun Heo 	/* determine gcwq to use */
995c7fc77f7STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
996c7fc77f7STejun Heo 		struct global_cwq *last_gcwq;
997c7fc77f7STejun Heo 
998f3421797STejun Heo 		if (unlikely(cpu == WORK_CPU_UNBOUND))
999f3421797STejun Heo 			cpu = raw_smp_processor_id();
1000f3421797STejun Heo 
100118aa9effSTejun Heo 		/*
100218aa9effSTejun Heo 		 * It's multi cpu.  If @wq is non-reentrant and @work
100318aa9effSTejun Heo 		 * was previously on a different cpu, it might still
100418aa9effSTejun Heo 		 * be running there, in which case the work needs to
100518aa9effSTejun Heo 		 * be queued on that cpu to guarantee non-reentrance.
100618aa9effSTejun Heo 		 */
1007502ca9d8STejun Heo 		gcwq = get_gcwq(cpu);
100818aa9effSTejun Heo 		if (wq->flags & WQ_NON_REENTRANT &&
100918aa9effSTejun Heo 		    (last_gcwq = get_work_gcwq(work)) && last_gcwq != gcwq) {
101018aa9effSTejun Heo 			struct worker *worker;
101118aa9effSTejun Heo 
101218aa9effSTejun Heo 			spin_lock_irqsave(&last_gcwq->lock, flags);
101318aa9effSTejun Heo 
101418aa9effSTejun Heo 			worker = find_worker_executing_work(last_gcwq, work);
101518aa9effSTejun Heo 
101618aa9effSTejun Heo 			if (worker && worker->current_cwq->wq == wq)
101718aa9effSTejun Heo 				gcwq = last_gcwq;
101818aa9effSTejun Heo 			else {
101918aa9effSTejun Heo 				/* meh... not running there, queue here */
102018aa9effSTejun Heo 				spin_unlock_irqrestore(&last_gcwq->lock, flags);
102118aa9effSTejun Heo 				spin_lock_irqsave(&gcwq->lock, flags);
102218aa9effSTejun Heo 			}
102318aa9effSTejun Heo 		} else
10248b03ae3cSTejun Heo 			spin_lock_irqsave(&gcwq->lock, flags);
1025f3421797STejun Heo 	} else {
1026f3421797STejun Heo 		gcwq = get_gcwq(WORK_CPU_UNBOUND);
1027f3421797STejun Heo 		spin_lock_irqsave(&gcwq->lock, flags);
1028502ca9d8STejun Heo 	}
1029502ca9d8STejun Heo 
1030502ca9d8STejun Heo 	/* gcwq determined, get cwq and queue */
1031502ca9d8STejun Heo 	cwq = get_cwq(gcwq->cpu, wq);
1032cdadf009STejun Heo 	trace_workqueue_queue_work(cpu, cwq, work);
1033502ca9d8STejun Heo 
1034f5b2552bSDan Carpenter 	if (WARN_ON(!list_empty(&work->entry))) {
1035f5b2552bSDan Carpenter 		spin_unlock_irqrestore(&gcwq->lock, flags);
1036f5b2552bSDan Carpenter 		return;
1037f5b2552bSDan Carpenter 	}
10381e19ffc6STejun Heo 
103973f53c4aSTejun Heo 	cwq->nr_in_flight[cwq->work_color]++;
10408a2e8e5dSTejun Heo 	work_flags = work_color_to_flags(cwq->work_color);
10411e19ffc6STejun Heo 
10421e19ffc6STejun Heo 	if (likely(cwq->nr_active < cwq->max_active)) {
1043cdadf009STejun Heo 		trace_workqueue_activate_work(work);
10441e19ffc6STejun Heo 		cwq->nr_active++;
10453270476aSTejun Heo 		worklist = &cwq->pool->worklist;
10468a2e8e5dSTejun Heo 	} else {
10478a2e8e5dSTejun Heo 		work_flags |= WORK_STRUCT_DELAYED;
10481e19ffc6STejun Heo 		worklist = &cwq->delayed_works;
10498a2e8e5dSTejun Heo 	}
10501e19ffc6STejun Heo 
10518a2e8e5dSTejun Heo 	insert_work(cwq, work, worklist, work_flags);
10521e19ffc6STejun Heo 
10538b03ae3cSTejun Heo 	spin_unlock_irqrestore(&gcwq->lock, flags);
10541da177e4SLinus Torvalds }
10551da177e4SLinus Torvalds 
10560fcb78c2SRolf Eike Beer /**
10570fcb78c2SRolf Eike Beer  * queue_work - queue work on a workqueue
10580fcb78c2SRolf Eike Beer  * @wq: workqueue to use
10590fcb78c2SRolf Eike Beer  * @work: work to queue
10600fcb78c2SRolf Eike Beer  *
1061057647fcSAlan Stern  * Returns 0 if @work was already on a queue, non-zero otherwise.
10621da177e4SLinus Torvalds  *
106300dfcaf7SOleg Nesterov  * We queue the work to the CPU on which it was submitted, but if the CPU dies
106400dfcaf7SOleg Nesterov  * it can be processed by another CPU.
10651da177e4SLinus Torvalds  */
10667ad5b3a5SHarvey Harrison int queue_work(struct workqueue_struct *wq, struct work_struct *work)
10671da177e4SLinus Torvalds {
1068ef1ca236SOleg Nesterov 	int ret;
10691da177e4SLinus Torvalds 
1070ef1ca236SOleg Nesterov 	ret = queue_work_on(get_cpu(), wq, work);
1071a848e3b6SOleg Nesterov 	put_cpu();
1072ef1ca236SOleg Nesterov 
10731da177e4SLinus Torvalds 	return ret;
10741da177e4SLinus Torvalds }
1075ae90dd5dSDave Jones EXPORT_SYMBOL_GPL(queue_work);
10761da177e4SLinus Torvalds 
1077c1a220e7SZhang Rui /**
1078c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
1079c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
1080c1a220e7SZhang Rui  * @wq: workqueue to use
1081c1a220e7SZhang Rui  * @work: work to queue
1082c1a220e7SZhang Rui  *
1083c1a220e7SZhang Rui  * Returns 0 if @work was already on a queue, non-zero otherwise.
1084c1a220e7SZhang Rui  *
1085c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
1086c1a220e7SZhang Rui  * can't go away.
1087c1a220e7SZhang Rui  */
1088c1a220e7SZhang Rui int
1089c1a220e7SZhang Rui queue_work_on(int cpu, struct workqueue_struct *wq, struct work_struct *work)
1090c1a220e7SZhang Rui {
1091c1a220e7SZhang Rui 	int ret = 0;
1092c1a220e7SZhang Rui 
109322df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
10944690c4abSTejun Heo 		__queue_work(cpu, wq, work);
1095c1a220e7SZhang Rui 		ret = 1;
1096c1a220e7SZhang Rui 	}
1097c1a220e7SZhang Rui 	return ret;
1098c1a220e7SZhang Rui }
1099c1a220e7SZhang Rui EXPORT_SYMBOL_GPL(queue_work_on);
1100c1a220e7SZhang Rui 
11016d141c3fSLi Zefan static void delayed_work_timer_fn(unsigned long __data)
11021da177e4SLinus Torvalds {
110352bad64dSDavid Howells 	struct delayed_work *dwork = (struct delayed_work *)__data;
11047a22ad75STejun Heo 	struct cpu_workqueue_struct *cwq = get_work_cwq(&dwork->work);
11051da177e4SLinus Torvalds 
11064690c4abSTejun Heo 	__queue_work(smp_processor_id(), cwq->wq, &dwork->work);
11071da177e4SLinus Torvalds }
11081da177e4SLinus Torvalds 
11090fcb78c2SRolf Eike Beer /**
11100fcb78c2SRolf Eike Beer  * queue_delayed_work - queue work on a workqueue after delay
11110fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1112af9997e4SRandy Dunlap  * @dwork: delayable work to queue
11130fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
11140fcb78c2SRolf Eike Beer  *
1115057647fcSAlan Stern  * Returns 0 if @work was already on a queue, non-zero otherwise.
11160fcb78c2SRolf Eike Beer  */
11177ad5b3a5SHarvey Harrison int queue_delayed_work(struct workqueue_struct *wq,
111852bad64dSDavid Howells 			struct delayed_work *dwork, unsigned long delay)
11191da177e4SLinus Torvalds {
112052bad64dSDavid Howells 	if (delay == 0)
112163bc0362SOleg Nesterov 		return queue_work(wq, &dwork->work);
11221da177e4SLinus Torvalds 
112363bc0362SOleg Nesterov 	return queue_delayed_work_on(-1, wq, dwork, delay);
11241da177e4SLinus Torvalds }
1125ae90dd5dSDave Jones EXPORT_SYMBOL_GPL(queue_delayed_work);
11261da177e4SLinus Torvalds 
11270fcb78c2SRolf Eike Beer /**
11280fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
11290fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
11300fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1131af9997e4SRandy Dunlap  * @dwork: work to queue
11320fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
11330fcb78c2SRolf Eike Beer  *
1134057647fcSAlan Stern  * Returns 0 if @work was already on a queue, non-zero otherwise.
11350fcb78c2SRolf Eike Beer  */
11367a6bc1cdSVenkatesh Pallipadi int queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
113752bad64dSDavid Howells 			struct delayed_work *dwork, unsigned long delay)
11387a6bc1cdSVenkatesh Pallipadi {
11397a6bc1cdSVenkatesh Pallipadi 	int ret = 0;
114052bad64dSDavid Howells 	struct timer_list *timer = &dwork->timer;
114152bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
11427a6bc1cdSVenkatesh Pallipadi 
114322df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1144c7fc77f7STejun Heo 		unsigned int lcpu;
11457a22ad75STejun Heo 
11467a6bc1cdSVenkatesh Pallipadi 		BUG_ON(timer_pending(timer));
11477a6bc1cdSVenkatesh Pallipadi 		BUG_ON(!list_empty(&work->entry));
11487a6bc1cdSVenkatesh Pallipadi 
11498a3e77ccSAndrew Liu 		timer_stats_timer_set_start_info(&dwork->timer);
11508a3e77ccSAndrew Liu 
11517a22ad75STejun Heo 		/*
11527a22ad75STejun Heo 		 * This stores cwq for the moment, for the timer_fn.
11537a22ad75STejun Heo 		 * Note that the work's gcwq is preserved to allow
11547a22ad75STejun Heo 		 * reentrance detection for delayed works.
11557a22ad75STejun Heo 		 */
1156c7fc77f7STejun Heo 		if (!(wq->flags & WQ_UNBOUND)) {
1157c7fc77f7STejun Heo 			struct global_cwq *gcwq = get_work_gcwq(work);
1158c7fc77f7STejun Heo 
1159c7fc77f7STejun Heo 			if (gcwq && gcwq->cpu != WORK_CPU_UNBOUND)
1160c7fc77f7STejun Heo 				lcpu = gcwq->cpu;
1161c7fc77f7STejun Heo 			else
1162c7fc77f7STejun Heo 				lcpu = raw_smp_processor_id();
1163c7fc77f7STejun Heo 		} else
1164c7fc77f7STejun Heo 			lcpu = WORK_CPU_UNBOUND;
1165c7fc77f7STejun Heo 
11667a22ad75STejun Heo 		set_work_cwq(work, get_cwq(lcpu, wq), 0);
1167c7fc77f7STejun Heo 
11687a6bc1cdSVenkatesh Pallipadi 		timer->expires = jiffies + delay;
116952bad64dSDavid Howells 		timer->data = (unsigned long)dwork;
11707a6bc1cdSVenkatesh Pallipadi 		timer->function = delayed_work_timer_fn;
117163bc0362SOleg Nesterov 
117263bc0362SOleg Nesterov 		if (unlikely(cpu >= 0))
11737a6bc1cdSVenkatesh Pallipadi 			add_timer_on(timer, cpu);
117463bc0362SOleg Nesterov 		else
117563bc0362SOleg Nesterov 			add_timer(timer);
11767a6bc1cdSVenkatesh Pallipadi 		ret = 1;
11777a6bc1cdSVenkatesh Pallipadi 	}
11787a6bc1cdSVenkatesh Pallipadi 	return ret;
11797a6bc1cdSVenkatesh Pallipadi }
1180ae90dd5dSDave Jones EXPORT_SYMBOL_GPL(queue_delayed_work_on);
11811da177e4SLinus Torvalds 
1182c8e55f36STejun Heo /**
1183c8e55f36STejun Heo  * worker_enter_idle - enter idle state
1184c8e55f36STejun Heo  * @worker: worker which is entering idle state
1185c8e55f36STejun Heo  *
1186c8e55f36STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
1187c8e55f36STejun Heo  * necessary.
1188c8e55f36STejun Heo  *
1189c8e55f36STejun Heo  * LOCKING:
1190c8e55f36STejun Heo  * spin_lock_irq(gcwq->lock).
1191c8e55f36STejun Heo  */
1192c8e55f36STejun Heo static void worker_enter_idle(struct worker *worker)
11931da177e4SLinus Torvalds {
1194bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1195bd7bdd43STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
1196c8e55f36STejun Heo 
1197c8e55f36STejun Heo 	BUG_ON(worker->flags & WORKER_IDLE);
1198c8e55f36STejun Heo 	BUG_ON(!list_empty(&worker->entry) &&
1199c8e55f36STejun Heo 	       (worker->hentry.next || worker->hentry.pprev));
1200c8e55f36STejun Heo 
1201cb444766STejun Heo 	/* can't use worker_set_flags(), also called from start_worker() */
1202cb444766STejun Heo 	worker->flags |= WORKER_IDLE;
1203bd7bdd43STejun Heo 	pool->nr_idle++;
1204e22bee78STejun Heo 	worker->last_active = jiffies;
1205c8e55f36STejun Heo 
1206c8e55f36STejun Heo 	/* idle_list is LIFO */
1207bd7bdd43STejun Heo 	list_add(&worker->entry, &pool->idle_list);
1208db7bccf4STejun Heo 
120963d95a91STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1210628c78e7STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1211cb444766STejun Heo 
1212544ecf31STejun Heo 	/*
1213628c78e7STejun Heo 	 * Sanity check nr_running.  Because gcwq_unbind_fn() releases
1214628c78e7STejun Heo 	 * gcwq->lock between setting %WORKER_UNBOUND and zapping
1215628c78e7STejun Heo 	 * nr_running, the warning may trigger spuriously.  Check iff
1216628c78e7STejun Heo 	 * unbind is not in progress.
1217544ecf31STejun Heo 	 */
1218628c78e7STejun Heo 	WARN_ON_ONCE(!(gcwq->flags & GCWQ_DISASSOCIATED) &&
1219bd7bdd43STejun Heo 		     pool->nr_workers == pool->nr_idle &&
122063d95a91STejun Heo 		     atomic_read(get_pool_nr_running(pool)));
1221c8e55f36STejun Heo }
1222c8e55f36STejun Heo 
1223c8e55f36STejun Heo /**
1224c8e55f36STejun Heo  * worker_leave_idle - leave idle state
1225c8e55f36STejun Heo  * @worker: worker which is leaving idle state
1226c8e55f36STejun Heo  *
1227c8e55f36STejun Heo  * @worker is leaving idle state.  Update stats.
1228c8e55f36STejun Heo  *
1229c8e55f36STejun Heo  * LOCKING:
1230c8e55f36STejun Heo  * spin_lock_irq(gcwq->lock).
1231c8e55f36STejun Heo  */
1232c8e55f36STejun Heo static void worker_leave_idle(struct worker *worker)
1233c8e55f36STejun Heo {
1234bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1235c8e55f36STejun Heo 
1236c8e55f36STejun Heo 	BUG_ON(!(worker->flags & WORKER_IDLE));
1237d302f017STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
1238bd7bdd43STejun Heo 	pool->nr_idle--;
1239c8e55f36STejun Heo 	list_del_init(&worker->entry);
1240c8e55f36STejun Heo }
1241c8e55f36STejun Heo 
1242e22bee78STejun Heo /**
1243e22bee78STejun Heo  * worker_maybe_bind_and_lock - bind worker to its cpu if possible and lock gcwq
1244e22bee78STejun Heo  * @worker: self
1245e22bee78STejun Heo  *
1246e22bee78STejun Heo  * Works which are scheduled while the cpu is online must at least be
1247e22bee78STejun Heo  * scheduled to a worker which is bound to the cpu so that if they are
1248e22bee78STejun Heo  * flushed from cpu callbacks while cpu is going down, they are
1249e22bee78STejun Heo  * guaranteed to execute on the cpu.
1250e22bee78STejun Heo  *
1251e22bee78STejun Heo  * This function is to be used by rogue workers and rescuers to bind
1252e22bee78STejun Heo  * themselves to the target cpu and may race with cpu going down or
1253e22bee78STejun Heo  * coming online.  kthread_bind() can't be used because it may put the
1254e22bee78STejun Heo  * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1255e22bee78STejun Heo  * verbatim as it's best effort and blocking and gcwq may be
1256e22bee78STejun Heo  * [dis]associated in the meantime.
1257e22bee78STejun Heo  *
1258f2d5a0eeSTejun Heo  * This function tries set_cpus_allowed() and locks gcwq and verifies the
1259f2d5a0eeSTejun Heo  * binding against %GCWQ_DISASSOCIATED which is set during
1260f2d5a0eeSTejun Heo  * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
1261f2d5a0eeSTejun Heo  * enters idle state or fetches works without dropping lock, it can
1262f2d5a0eeSTejun Heo  * guarantee the scheduling requirement described in the first paragraph.
1263e22bee78STejun Heo  *
1264e22bee78STejun Heo  * CONTEXT:
1265e22bee78STejun Heo  * Might sleep.  Called without any lock but returns with gcwq->lock
1266e22bee78STejun Heo  * held.
1267e22bee78STejun Heo  *
1268e22bee78STejun Heo  * RETURNS:
1269e22bee78STejun Heo  * %true if the associated gcwq is online (@worker is successfully
1270e22bee78STejun Heo  * bound), %false if offline.
1271e22bee78STejun Heo  */
1272e22bee78STejun Heo static bool worker_maybe_bind_and_lock(struct worker *worker)
1273972fa1c5SNamhyung Kim __acquires(&gcwq->lock)
1274e22bee78STejun Heo {
1275bd7bdd43STejun Heo 	struct global_cwq *gcwq = worker->pool->gcwq;
1276e22bee78STejun Heo 	struct task_struct *task = worker->task;
1277e22bee78STejun Heo 
1278e22bee78STejun Heo 	while (true) {
1279e22bee78STejun Heo 		/*
1280e22bee78STejun Heo 		 * The following call may fail, succeed or succeed
1281e22bee78STejun Heo 		 * without actually migrating the task to the cpu if
1282e22bee78STejun Heo 		 * it races with cpu hotunplug operation.  Verify
1283e22bee78STejun Heo 		 * against GCWQ_DISASSOCIATED.
1284e22bee78STejun Heo 		 */
1285f3421797STejun Heo 		if (!(gcwq->flags & GCWQ_DISASSOCIATED))
1286e22bee78STejun Heo 			set_cpus_allowed_ptr(task, get_cpu_mask(gcwq->cpu));
1287e22bee78STejun Heo 
1288e22bee78STejun Heo 		spin_lock_irq(&gcwq->lock);
1289e22bee78STejun Heo 		if (gcwq->flags & GCWQ_DISASSOCIATED)
1290e22bee78STejun Heo 			return false;
1291e22bee78STejun Heo 		if (task_cpu(task) == gcwq->cpu &&
1292e22bee78STejun Heo 		    cpumask_equal(&current->cpus_allowed,
1293e22bee78STejun Heo 				  get_cpu_mask(gcwq->cpu)))
1294e22bee78STejun Heo 			return true;
1295e22bee78STejun Heo 		spin_unlock_irq(&gcwq->lock);
1296e22bee78STejun Heo 
12975035b20fSTejun Heo 		/*
12985035b20fSTejun Heo 		 * We've raced with CPU hot[un]plug.  Give it a breather
12995035b20fSTejun Heo 		 * and retry migration.  cond_resched() is required here;
13005035b20fSTejun Heo 		 * otherwise, we might deadlock against cpu_stop trying to
13015035b20fSTejun Heo 		 * bring down the CPU on non-preemptive kernel.
13025035b20fSTejun Heo 		 */
1303e22bee78STejun Heo 		cpu_relax();
13045035b20fSTejun Heo 		cond_resched();
1305e22bee78STejun Heo 	}
1306e22bee78STejun Heo }
1307e22bee78STejun Heo 
130825511a47STejun Heo struct idle_rebind {
130925511a47STejun Heo 	int			cnt;		/* # workers to be rebound */
131025511a47STejun Heo 	struct completion	done;		/* all workers rebound */
131125511a47STejun Heo };
131225511a47STejun Heo 
1313e22bee78STejun Heo /*
131425511a47STejun Heo  * Rebind an idle @worker to its CPU.  During CPU onlining, this has to
131525511a47STejun Heo  * happen synchronously for idle workers.  worker_thread() will test
131625511a47STejun Heo  * %WORKER_REBIND before leaving idle and call this function.
131725511a47STejun Heo  */
131825511a47STejun Heo static void idle_worker_rebind(struct worker *worker)
131925511a47STejun Heo {
132025511a47STejun Heo 	struct global_cwq *gcwq = worker->pool->gcwq;
132125511a47STejun Heo 
132225511a47STejun Heo 	/* CPU must be online at this point */
132325511a47STejun Heo 	WARN_ON(!worker_maybe_bind_and_lock(worker));
132425511a47STejun Heo 	if (!--worker->idle_rebind->cnt)
132525511a47STejun Heo 		complete(&worker->idle_rebind->done);
132625511a47STejun Heo 	spin_unlock_irq(&worker->pool->gcwq->lock);
132725511a47STejun Heo 
132825511a47STejun Heo 	/* we did our part, wait for rebind_workers() to finish up */
132925511a47STejun Heo 	wait_event(gcwq->rebind_hold, !(worker->flags & WORKER_REBIND));
1330ec58815aSTejun Heo 
1331ec58815aSTejun Heo 	/*
1332ec58815aSTejun Heo 	 * rebind_workers() shouldn't finish until all workers passed the
1333ec58815aSTejun Heo 	 * above WORKER_REBIND wait.  Tell it when done.
1334ec58815aSTejun Heo 	 */
1335ec58815aSTejun Heo 	spin_lock_irq(&worker->pool->gcwq->lock);
1336ec58815aSTejun Heo 	if (!--worker->idle_rebind->cnt)
1337ec58815aSTejun Heo 		complete(&worker->idle_rebind->done);
1338ec58815aSTejun Heo 	spin_unlock_irq(&worker->pool->gcwq->lock);
133925511a47STejun Heo }
134025511a47STejun Heo 
134125511a47STejun Heo /*
134225511a47STejun Heo  * Function for @worker->rebind.work used to rebind unbound busy workers to
1343403c821dSTejun Heo  * the associated cpu which is coming back online.  This is scheduled by
1344403c821dSTejun Heo  * cpu up but can race with other cpu hotplug operations and may be
1345403c821dSTejun Heo  * executed twice without intervening cpu down.
1346e22bee78STejun Heo  */
134725511a47STejun Heo static void busy_worker_rebind_fn(struct work_struct *work)
1348e22bee78STejun Heo {
1349e22bee78STejun Heo 	struct worker *worker = container_of(work, struct worker, rebind_work);
1350bd7bdd43STejun Heo 	struct global_cwq *gcwq = worker->pool->gcwq;
1351e22bee78STejun Heo 
1352960bd11bSLai Jiangshan 	worker_maybe_bind_and_lock(worker);
1353960bd11bSLai Jiangshan 
1354960bd11bSLai Jiangshan 	/*
1355960bd11bSLai Jiangshan 	 * %WORKER_REBIND must be cleared even if the above binding failed;
1356960bd11bSLai Jiangshan 	 * otherwise, we may confuse the next CPU_UP cycle or oops / get
1357960bd11bSLai Jiangshan 	 * stuck by calling idle_worker_rebind() prematurely.  If CPU went
1358960bd11bSLai Jiangshan 	 * down again inbetween, %WORKER_UNBOUND would be set, so clearing
1359960bd11bSLai Jiangshan 	 * %WORKER_REBIND is always safe.
1360960bd11bSLai Jiangshan 	 */
1361e22bee78STejun Heo 	worker_clr_flags(worker, WORKER_REBIND);
1362e22bee78STejun Heo 
1363e22bee78STejun Heo 	spin_unlock_irq(&gcwq->lock);
1364e22bee78STejun Heo }
1365e22bee78STejun Heo 
136625511a47STejun Heo /**
136725511a47STejun Heo  * rebind_workers - rebind all workers of a gcwq to the associated CPU
136825511a47STejun Heo  * @gcwq: gcwq of interest
136925511a47STejun Heo  *
137025511a47STejun Heo  * @gcwq->cpu is coming online.  Rebind all workers to the CPU.  Rebinding
137125511a47STejun Heo  * is different for idle and busy ones.
137225511a47STejun Heo  *
137325511a47STejun Heo  * The idle ones should be rebound synchronously and idle rebinding should
137425511a47STejun Heo  * be complete before any worker starts executing work items with
137525511a47STejun Heo  * concurrency management enabled; otherwise, scheduler may oops trying to
137625511a47STejun Heo  * wake up non-local idle worker from wq_worker_sleeping().
137725511a47STejun Heo  *
137825511a47STejun Heo  * This is achieved by repeatedly requesting rebinding until all idle
137925511a47STejun Heo  * workers are known to have been rebound under @gcwq->lock and holding all
138025511a47STejun Heo  * idle workers from becoming busy until idle rebinding is complete.
138125511a47STejun Heo  *
138225511a47STejun Heo  * Once idle workers are rebound, busy workers can be rebound as they
138325511a47STejun Heo  * finish executing their current work items.  Queueing the rebind work at
138425511a47STejun Heo  * the head of their scheduled lists is enough.  Note that nr_running will
138525511a47STejun Heo  * be properbly bumped as busy workers rebind.
138625511a47STejun Heo  *
138725511a47STejun Heo  * On return, all workers are guaranteed to either be bound or have rebind
138825511a47STejun Heo  * work item scheduled.
138925511a47STejun Heo  */
139025511a47STejun Heo static void rebind_workers(struct global_cwq *gcwq)
139125511a47STejun Heo 	__releases(&gcwq->lock) __acquires(&gcwq->lock)
139225511a47STejun Heo {
139325511a47STejun Heo 	struct idle_rebind idle_rebind;
139425511a47STejun Heo 	struct worker_pool *pool;
139525511a47STejun Heo 	struct worker *worker;
139625511a47STejun Heo 	struct hlist_node *pos;
139725511a47STejun Heo 	int i;
139825511a47STejun Heo 
139925511a47STejun Heo 	lockdep_assert_held(&gcwq->lock);
140025511a47STejun Heo 
140125511a47STejun Heo 	for_each_worker_pool(pool, gcwq)
140225511a47STejun Heo 		lockdep_assert_held(&pool->manager_mutex);
140325511a47STejun Heo 
140425511a47STejun Heo 	/*
140525511a47STejun Heo 	 * Rebind idle workers.  Interlocked both ways.  We wait for
140625511a47STejun Heo 	 * workers to rebind via @idle_rebind.done.  Workers will wait for
140725511a47STejun Heo 	 * us to finish up by watching %WORKER_REBIND.
140825511a47STejun Heo 	 */
140925511a47STejun Heo 	init_completion(&idle_rebind.done);
141025511a47STejun Heo retry:
141125511a47STejun Heo 	idle_rebind.cnt = 1;
141225511a47STejun Heo 	INIT_COMPLETION(idle_rebind.done);
141325511a47STejun Heo 
141425511a47STejun Heo 	/* set REBIND and kick idle ones, we'll wait for these later */
141525511a47STejun Heo 	for_each_worker_pool(pool, gcwq) {
141625511a47STejun Heo 		list_for_each_entry(worker, &pool->idle_list, entry) {
141796e65306SLai Jiangshan 			unsigned long worker_flags = worker->flags;
141896e65306SLai Jiangshan 
141925511a47STejun Heo 			if (worker->flags & WORKER_REBIND)
142025511a47STejun Heo 				continue;
142125511a47STejun Heo 
142296e65306SLai Jiangshan 			/* morph UNBOUND to REBIND atomically */
142396e65306SLai Jiangshan 			worker_flags &= ~WORKER_UNBOUND;
142496e65306SLai Jiangshan 			worker_flags |= WORKER_REBIND;
142596e65306SLai Jiangshan 			ACCESS_ONCE(worker->flags) = worker_flags;
142625511a47STejun Heo 
142725511a47STejun Heo 			idle_rebind.cnt++;
142825511a47STejun Heo 			worker->idle_rebind = &idle_rebind;
142925511a47STejun Heo 
143025511a47STejun Heo 			/* worker_thread() will call idle_worker_rebind() */
143125511a47STejun Heo 			wake_up_process(worker->task);
143225511a47STejun Heo 		}
143325511a47STejun Heo 	}
143425511a47STejun Heo 
143525511a47STejun Heo 	if (--idle_rebind.cnt) {
143625511a47STejun Heo 		spin_unlock_irq(&gcwq->lock);
143725511a47STejun Heo 		wait_for_completion(&idle_rebind.done);
143825511a47STejun Heo 		spin_lock_irq(&gcwq->lock);
143925511a47STejun Heo 		/* busy ones might have become idle while waiting, retry */
144025511a47STejun Heo 		goto retry;
144125511a47STejun Heo 	}
144225511a47STejun Heo 
144390beca5dSTejun Heo 	/* all idle workers are rebound, rebind busy workers */
144425511a47STejun Heo 	for_each_busy_worker(worker, i, pos, gcwq) {
144525511a47STejun Heo 		struct work_struct *rebind_work = &worker->rebind_work;
144696e65306SLai Jiangshan 		unsigned long worker_flags = worker->flags;
144725511a47STejun Heo 
144896e65306SLai Jiangshan 		/* morph UNBOUND to REBIND atomically */
144996e65306SLai Jiangshan 		worker_flags &= ~WORKER_UNBOUND;
145096e65306SLai Jiangshan 		worker_flags |= WORKER_REBIND;
145196e65306SLai Jiangshan 		ACCESS_ONCE(worker->flags) = worker_flags;
145225511a47STejun Heo 
145325511a47STejun Heo 		if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
145425511a47STejun Heo 				     work_data_bits(rebind_work)))
145525511a47STejun Heo 			continue;
145625511a47STejun Heo 
145725511a47STejun Heo 		/* wq doesn't matter, use the default one */
145825511a47STejun Heo 		debug_work_activate(rebind_work);
145925511a47STejun Heo 		insert_work(get_cwq(gcwq->cpu, system_wq), rebind_work,
146025511a47STejun Heo 			    worker->scheduled.next,
146125511a47STejun Heo 			    work_color_to_flags(WORK_NO_COLOR));
146225511a47STejun Heo 	}
146390beca5dSTejun Heo 
146490beca5dSTejun Heo 	/*
146590beca5dSTejun Heo 	 * All idle workers are rebound and waiting for %WORKER_REBIND to
146690beca5dSTejun Heo 	 * be cleared inside idle_worker_rebind().  Clear and release.
146790beca5dSTejun Heo 	 * Clearing %WORKER_REBIND from this foreign context is safe
146890beca5dSTejun Heo 	 * because these workers are still guaranteed to be idle.
1469ec58815aSTejun Heo 	 *
1470ec58815aSTejun Heo 	 * We need to make sure all idle workers passed WORKER_REBIND wait
1471ec58815aSTejun Heo 	 * in idle_worker_rebind() before returning; otherwise, workers can
1472ec58815aSTejun Heo 	 * get stuck at the wait if hotplug cycle repeats.
147390beca5dSTejun Heo 	 */
1474ec58815aSTejun Heo 	idle_rebind.cnt = 1;
1475ec58815aSTejun Heo 	INIT_COMPLETION(idle_rebind.done);
1476ec58815aSTejun Heo 
1477ec58815aSTejun Heo 	for_each_worker_pool(pool, gcwq) {
1478ec58815aSTejun Heo 		list_for_each_entry(worker, &pool->idle_list, entry) {
147990beca5dSTejun Heo 			worker->flags &= ~WORKER_REBIND;
1480ec58815aSTejun Heo 			idle_rebind.cnt++;
1481ec58815aSTejun Heo 		}
1482ec58815aSTejun Heo 	}
148390beca5dSTejun Heo 
148490beca5dSTejun Heo 	wake_up_all(&gcwq->rebind_hold);
1485ec58815aSTejun Heo 
1486ec58815aSTejun Heo 	if (--idle_rebind.cnt) {
1487ec58815aSTejun Heo 		spin_unlock_irq(&gcwq->lock);
1488ec58815aSTejun Heo 		wait_for_completion(&idle_rebind.done);
1489ec58815aSTejun Heo 		spin_lock_irq(&gcwq->lock);
1490ec58815aSTejun Heo 	}
149125511a47STejun Heo }
149225511a47STejun Heo 
1493c34056a3STejun Heo static struct worker *alloc_worker(void)
1494c34056a3STejun Heo {
1495c34056a3STejun Heo 	struct worker *worker;
1496c34056a3STejun Heo 
1497c34056a3STejun Heo 	worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1498c8e55f36STejun Heo 	if (worker) {
1499c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
1500affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
150125511a47STejun Heo 		INIT_WORK(&worker->rebind_work, busy_worker_rebind_fn);
1502e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
1503e22bee78STejun Heo 		worker->flags = WORKER_PREP;
1504c8e55f36STejun Heo 	}
1505c34056a3STejun Heo 	return worker;
1506c34056a3STejun Heo }
1507c34056a3STejun Heo 
1508c34056a3STejun Heo /**
1509c34056a3STejun Heo  * create_worker - create a new workqueue worker
151063d95a91STejun Heo  * @pool: pool the new worker will belong to
1511c34056a3STejun Heo  *
151263d95a91STejun Heo  * Create a new worker which is bound to @pool.  The returned worker
1513c34056a3STejun Heo  * can be started by calling start_worker() or destroyed using
1514c34056a3STejun Heo  * destroy_worker().
1515c34056a3STejun Heo  *
1516c34056a3STejun Heo  * CONTEXT:
1517c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
1518c34056a3STejun Heo  *
1519c34056a3STejun Heo  * RETURNS:
1520c34056a3STejun Heo  * Pointer to the newly created worker.
1521c34056a3STejun Heo  */
1522bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
1523c34056a3STejun Heo {
152463d95a91STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
15253270476aSTejun Heo 	const char *pri = worker_pool_pri(pool) ? "H" : "";
1526c34056a3STejun Heo 	struct worker *worker = NULL;
1527f3421797STejun Heo 	int id = -1;
1528c34056a3STejun Heo 
15298b03ae3cSTejun Heo 	spin_lock_irq(&gcwq->lock);
1530bd7bdd43STejun Heo 	while (ida_get_new(&pool->worker_ida, &id)) {
15318b03ae3cSTejun Heo 		spin_unlock_irq(&gcwq->lock);
1532bd7bdd43STejun Heo 		if (!ida_pre_get(&pool->worker_ida, GFP_KERNEL))
1533c34056a3STejun Heo 			goto fail;
15348b03ae3cSTejun Heo 		spin_lock_irq(&gcwq->lock);
1535c34056a3STejun Heo 	}
15368b03ae3cSTejun Heo 	spin_unlock_irq(&gcwq->lock);
1537c34056a3STejun Heo 
1538c34056a3STejun Heo 	worker = alloc_worker();
1539c34056a3STejun Heo 	if (!worker)
1540c34056a3STejun Heo 		goto fail;
1541c34056a3STejun Heo 
1542bd7bdd43STejun Heo 	worker->pool = pool;
1543c34056a3STejun Heo 	worker->id = id;
1544c34056a3STejun Heo 
1545bc2ae0f5STejun Heo 	if (gcwq->cpu != WORK_CPU_UNBOUND)
154694dcf29aSEric Dumazet 		worker->task = kthread_create_on_node(worker_thread,
15473270476aSTejun Heo 					worker, cpu_to_node(gcwq->cpu),
15483270476aSTejun Heo 					"kworker/%u:%d%s", gcwq->cpu, id, pri);
1549f3421797STejun Heo 	else
1550f3421797STejun Heo 		worker->task = kthread_create(worker_thread, worker,
15513270476aSTejun Heo 					      "kworker/u:%d%s", id, pri);
1552c34056a3STejun Heo 	if (IS_ERR(worker->task))
1553c34056a3STejun Heo 		goto fail;
1554c34056a3STejun Heo 
15553270476aSTejun Heo 	if (worker_pool_pri(pool))
15563270476aSTejun Heo 		set_user_nice(worker->task, HIGHPRI_NICE_LEVEL);
15573270476aSTejun Heo 
1558db7bccf4STejun Heo 	/*
1559bc2ae0f5STejun Heo 	 * Determine CPU binding of the new worker depending on
1560bc2ae0f5STejun Heo 	 * %GCWQ_DISASSOCIATED.  The caller is responsible for ensuring the
1561bc2ae0f5STejun Heo 	 * flag remains stable across this function.  See the comments
1562bc2ae0f5STejun Heo 	 * above the flag definition for details.
1563bc2ae0f5STejun Heo 	 *
1564bc2ae0f5STejun Heo 	 * As an unbound worker may later become a regular one if CPU comes
1565bc2ae0f5STejun Heo 	 * online, make sure every worker has %PF_THREAD_BOUND set.
1566db7bccf4STejun Heo 	 */
1567bc2ae0f5STejun Heo 	if (!(gcwq->flags & GCWQ_DISASSOCIATED)) {
15688b03ae3cSTejun Heo 		kthread_bind(worker->task, gcwq->cpu);
1569bc2ae0f5STejun Heo 	} else {
1570db7bccf4STejun Heo 		worker->task->flags |= PF_THREAD_BOUND;
1571f3421797STejun Heo 		worker->flags |= WORKER_UNBOUND;
1572f3421797STejun Heo 	}
1573c34056a3STejun Heo 
1574c34056a3STejun Heo 	return worker;
1575c34056a3STejun Heo fail:
1576c34056a3STejun Heo 	if (id >= 0) {
15778b03ae3cSTejun Heo 		spin_lock_irq(&gcwq->lock);
1578bd7bdd43STejun Heo 		ida_remove(&pool->worker_ida, id);
15798b03ae3cSTejun Heo 		spin_unlock_irq(&gcwq->lock);
1580c34056a3STejun Heo 	}
1581c34056a3STejun Heo 	kfree(worker);
1582c34056a3STejun Heo 	return NULL;
1583c34056a3STejun Heo }
1584c34056a3STejun Heo 
1585c34056a3STejun Heo /**
1586c34056a3STejun Heo  * start_worker - start a newly created worker
1587c34056a3STejun Heo  * @worker: worker to start
1588c34056a3STejun Heo  *
1589c8e55f36STejun Heo  * Make the gcwq aware of @worker and start it.
1590c34056a3STejun Heo  *
1591c34056a3STejun Heo  * CONTEXT:
15928b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock).
1593c34056a3STejun Heo  */
1594c34056a3STejun Heo static void start_worker(struct worker *worker)
1595c34056a3STejun Heo {
1596cb444766STejun Heo 	worker->flags |= WORKER_STARTED;
1597bd7bdd43STejun Heo 	worker->pool->nr_workers++;
1598c8e55f36STejun Heo 	worker_enter_idle(worker);
1599c34056a3STejun Heo 	wake_up_process(worker->task);
1600c34056a3STejun Heo }
1601c34056a3STejun Heo 
1602c34056a3STejun Heo /**
1603c34056a3STejun Heo  * destroy_worker - destroy a workqueue worker
1604c34056a3STejun Heo  * @worker: worker to be destroyed
1605c34056a3STejun Heo  *
1606c8e55f36STejun Heo  * Destroy @worker and adjust @gcwq stats accordingly.
1607c8e55f36STejun Heo  *
1608c8e55f36STejun Heo  * CONTEXT:
1609c8e55f36STejun Heo  * spin_lock_irq(gcwq->lock) which is released and regrabbed.
1610c34056a3STejun Heo  */
1611c34056a3STejun Heo static void destroy_worker(struct worker *worker)
1612c34056a3STejun Heo {
1613bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1614bd7bdd43STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
1615c34056a3STejun Heo 	int id = worker->id;
1616c34056a3STejun Heo 
1617c34056a3STejun Heo 	/* sanity check frenzy */
1618c34056a3STejun Heo 	BUG_ON(worker->current_work);
1619affee4b2STejun Heo 	BUG_ON(!list_empty(&worker->scheduled));
1620c34056a3STejun Heo 
1621c8e55f36STejun Heo 	if (worker->flags & WORKER_STARTED)
1622bd7bdd43STejun Heo 		pool->nr_workers--;
1623c8e55f36STejun Heo 	if (worker->flags & WORKER_IDLE)
1624bd7bdd43STejun Heo 		pool->nr_idle--;
1625c8e55f36STejun Heo 
1626c8e55f36STejun Heo 	list_del_init(&worker->entry);
1627cb444766STejun Heo 	worker->flags |= WORKER_DIE;
1628c8e55f36STejun Heo 
1629c8e55f36STejun Heo 	spin_unlock_irq(&gcwq->lock);
1630c8e55f36STejun Heo 
1631c34056a3STejun Heo 	kthread_stop(worker->task);
1632c34056a3STejun Heo 	kfree(worker);
1633c34056a3STejun Heo 
16348b03ae3cSTejun Heo 	spin_lock_irq(&gcwq->lock);
1635bd7bdd43STejun Heo 	ida_remove(&pool->worker_ida, id);
1636c34056a3STejun Heo }
1637c34056a3STejun Heo 
163863d95a91STejun Heo static void idle_worker_timeout(unsigned long __pool)
1639e22bee78STejun Heo {
164063d95a91STejun Heo 	struct worker_pool *pool = (void *)__pool;
164163d95a91STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
1642e22bee78STejun Heo 
1643e22bee78STejun Heo 	spin_lock_irq(&gcwq->lock);
1644e22bee78STejun Heo 
164563d95a91STejun Heo 	if (too_many_workers(pool)) {
1646e22bee78STejun Heo 		struct worker *worker;
1647e22bee78STejun Heo 		unsigned long expires;
1648e22bee78STejun Heo 
1649e22bee78STejun Heo 		/* idle_list is kept in LIFO order, check the last one */
165063d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
1651e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1652e22bee78STejun Heo 
1653e22bee78STejun Heo 		if (time_before(jiffies, expires))
165463d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
1655e22bee78STejun Heo 		else {
1656e22bee78STejun Heo 			/* it's been idle for too long, wake up manager */
165711ebea50STejun Heo 			pool->flags |= POOL_MANAGE_WORKERS;
165863d95a91STejun Heo 			wake_up_worker(pool);
1659e22bee78STejun Heo 		}
1660e22bee78STejun Heo 	}
1661e22bee78STejun Heo 
1662e22bee78STejun Heo 	spin_unlock_irq(&gcwq->lock);
1663e22bee78STejun Heo }
1664e22bee78STejun Heo 
1665e22bee78STejun Heo static bool send_mayday(struct work_struct *work)
1666e22bee78STejun Heo {
1667e22bee78STejun Heo 	struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1668e22bee78STejun Heo 	struct workqueue_struct *wq = cwq->wq;
1669f3421797STejun Heo 	unsigned int cpu;
1670e22bee78STejun Heo 
1671e22bee78STejun Heo 	if (!(wq->flags & WQ_RESCUER))
1672e22bee78STejun Heo 		return false;
1673e22bee78STejun Heo 
1674e22bee78STejun Heo 	/* mayday mayday mayday */
1675bd7bdd43STejun Heo 	cpu = cwq->pool->gcwq->cpu;
1676f3421797STejun Heo 	/* WORK_CPU_UNBOUND can't be set in cpumask, use cpu 0 instead */
1677f3421797STejun Heo 	if (cpu == WORK_CPU_UNBOUND)
1678f3421797STejun Heo 		cpu = 0;
1679f2e005aaSTejun Heo 	if (!mayday_test_and_set_cpu(cpu, wq->mayday_mask))
1680e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
1681e22bee78STejun Heo 	return true;
1682e22bee78STejun Heo }
1683e22bee78STejun Heo 
168463d95a91STejun Heo static void gcwq_mayday_timeout(unsigned long __pool)
1685e22bee78STejun Heo {
168663d95a91STejun Heo 	struct worker_pool *pool = (void *)__pool;
168763d95a91STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
1688e22bee78STejun Heo 	struct work_struct *work;
1689e22bee78STejun Heo 
1690e22bee78STejun Heo 	spin_lock_irq(&gcwq->lock);
1691e22bee78STejun Heo 
169263d95a91STejun Heo 	if (need_to_create_worker(pool)) {
1693e22bee78STejun Heo 		/*
1694e22bee78STejun Heo 		 * We've been trying to create a new worker but
1695e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
1696e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
1697e22bee78STejun Heo 		 * rescuers.
1698e22bee78STejun Heo 		 */
169963d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
1700e22bee78STejun Heo 			send_mayday(work);
1701e22bee78STejun Heo 	}
1702e22bee78STejun Heo 
1703e22bee78STejun Heo 	spin_unlock_irq(&gcwq->lock);
1704e22bee78STejun Heo 
170563d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1706e22bee78STejun Heo }
1707e22bee78STejun Heo 
1708e22bee78STejun Heo /**
1709e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
171063d95a91STejun Heo  * @pool: pool to create a new worker for
1711e22bee78STejun Heo  *
171263d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
1713e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
1714e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
171563d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
1716e22bee78STejun Heo  * possible allocation deadlock.
1717e22bee78STejun Heo  *
1718e22bee78STejun Heo  * On return, need_to_create_worker() is guaranteed to be false and
1719e22bee78STejun Heo  * may_start_working() true.
1720e22bee78STejun Heo  *
1721e22bee78STejun Heo  * LOCKING:
1722e22bee78STejun Heo  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1723e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
1724e22bee78STejun Heo  * manager.
1725e22bee78STejun Heo  *
1726e22bee78STejun Heo  * RETURNS:
1727e22bee78STejun Heo  * false if no action was taken and gcwq->lock stayed locked, true
1728e22bee78STejun Heo  * otherwise.
1729e22bee78STejun Heo  */
173063d95a91STejun Heo static bool maybe_create_worker(struct worker_pool *pool)
173106bd6ebfSNamhyung Kim __releases(&gcwq->lock)
173206bd6ebfSNamhyung Kim __acquires(&gcwq->lock)
1733e22bee78STejun Heo {
173463d95a91STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
173563d95a91STejun Heo 
173663d95a91STejun Heo 	if (!need_to_create_worker(pool))
1737e22bee78STejun Heo 		return false;
1738e22bee78STejun Heo restart:
17399f9c2364STejun Heo 	spin_unlock_irq(&gcwq->lock);
17409f9c2364STejun Heo 
1741e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
174263d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1743e22bee78STejun Heo 
1744e22bee78STejun Heo 	while (true) {
1745e22bee78STejun Heo 		struct worker *worker;
1746e22bee78STejun Heo 
1747bc2ae0f5STejun Heo 		worker = create_worker(pool);
1748e22bee78STejun Heo 		if (worker) {
174963d95a91STejun Heo 			del_timer_sync(&pool->mayday_timer);
1750e22bee78STejun Heo 			spin_lock_irq(&gcwq->lock);
1751e22bee78STejun Heo 			start_worker(worker);
175263d95a91STejun Heo 			BUG_ON(need_to_create_worker(pool));
1753e22bee78STejun Heo 			return true;
1754e22bee78STejun Heo 		}
1755e22bee78STejun Heo 
175663d95a91STejun Heo 		if (!need_to_create_worker(pool))
1757e22bee78STejun Heo 			break;
1758e22bee78STejun Heo 
1759e22bee78STejun Heo 		__set_current_state(TASK_INTERRUPTIBLE);
1760e22bee78STejun Heo 		schedule_timeout(CREATE_COOLDOWN);
17619f9c2364STejun Heo 
176263d95a91STejun Heo 		if (!need_to_create_worker(pool))
1763e22bee78STejun Heo 			break;
1764e22bee78STejun Heo 	}
1765e22bee78STejun Heo 
176663d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
1767e22bee78STejun Heo 	spin_lock_irq(&gcwq->lock);
176863d95a91STejun Heo 	if (need_to_create_worker(pool))
1769e22bee78STejun Heo 		goto restart;
1770e22bee78STejun Heo 	return true;
1771e22bee78STejun Heo }
1772e22bee78STejun Heo 
1773e22bee78STejun Heo /**
1774e22bee78STejun Heo  * maybe_destroy_worker - destroy workers which have been idle for a while
177563d95a91STejun Heo  * @pool: pool to destroy workers for
1776e22bee78STejun Heo  *
177763d95a91STejun Heo  * Destroy @pool workers which have been idle for longer than
1778e22bee78STejun Heo  * IDLE_WORKER_TIMEOUT.
1779e22bee78STejun Heo  *
1780e22bee78STejun Heo  * LOCKING:
1781e22bee78STejun Heo  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1782e22bee78STejun Heo  * multiple times.  Called only from manager.
1783e22bee78STejun Heo  *
1784e22bee78STejun Heo  * RETURNS:
1785e22bee78STejun Heo  * false if no action was taken and gcwq->lock stayed locked, true
1786e22bee78STejun Heo  * otherwise.
1787e22bee78STejun Heo  */
178863d95a91STejun Heo static bool maybe_destroy_workers(struct worker_pool *pool)
1789e22bee78STejun Heo {
1790e22bee78STejun Heo 	bool ret = false;
1791e22bee78STejun Heo 
179263d95a91STejun Heo 	while (too_many_workers(pool)) {
1793e22bee78STejun Heo 		struct worker *worker;
1794e22bee78STejun Heo 		unsigned long expires;
1795e22bee78STejun Heo 
179663d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
1797e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1798e22bee78STejun Heo 
1799e22bee78STejun Heo 		if (time_before(jiffies, expires)) {
180063d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
1801e22bee78STejun Heo 			break;
1802e22bee78STejun Heo 		}
1803e22bee78STejun Heo 
1804e22bee78STejun Heo 		destroy_worker(worker);
1805e22bee78STejun Heo 		ret = true;
1806e22bee78STejun Heo 	}
1807e22bee78STejun Heo 
1808e22bee78STejun Heo 	return ret;
1809e22bee78STejun Heo }
1810e22bee78STejun Heo 
1811e22bee78STejun Heo /**
1812e22bee78STejun Heo  * manage_workers - manage worker pool
1813e22bee78STejun Heo  * @worker: self
1814e22bee78STejun Heo  *
1815e22bee78STejun Heo  * Assume the manager role and manage gcwq worker pool @worker belongs
1816e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
1817e22bee78STejun Heo  * gcwq.  The exclusion is handled automatically by this function.
1818e22bee78STejun Heo  *
1819e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
1820e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
1821e22bee78STejun Heo  * and may_start_working() is true.
1822e22bee78STejun Heo  *
1823e22bee78STejun Heo  * CONTEXT:
1824e22bee78STejun Heo  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1825e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
1826e22bee78STejun Heo  *
1827e22bee78STejun Heo  * RETURNS:
1828e22bee78STejun Heo  * false if no action was taken and gcwq->lock stayed locked, true if
1829e22bee78STejun Heo  * some action was taken.
1830e22bee78STejun Heo  */
1831e22bee78STejun Heo static bool manage_workers(struct worker *worker)
1832e22bee78STejun Heo {
183363d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
1834e22bee78STejun Heo 	bool ret = false;
1835e22bee78STejun Heo 
1836ee378aa4SLai Jiangshan 	if (pool->flags & POOL_MANAGING_WORKERS)
1837e22bee78STejun Heo 		return ret;
1838e22bee78STejun Heo 
1839552a37e9SLai Jiangshan 	pool->flags |= POOL_MANAGING_WORKERS;
1840ee378aa4SLai Jiangshan 
1841ee378aa4SLai Jiangshan 	/*
1842ee378aa4SLai Jiangshan 	 * To simplify both worker management and CPU hotplug, hold off
1843ee378aa4SLai Jiangshan 	 * management while hotplug is in progress.  CPU hotplug path can't
1844ee378aa4SLai Jiangshan 	 * grab %POOL_MANAGING_WORKERS to achieve this because that can
1845ee378aa4SLai Jiangshan 	 * lead to idle worker depletion (all become busy thinking someone
1846ee378aa4SLai Jiangshan 	 * else is managing) which in turn can result in deadlock under
1847ee378aa4SLai Jiangshan 	 * extreme circumstances.  Use @pool->manager_mutex to synchronize
1848ee378aa4SLai Jiangshan 	 * manager against CPU hotplug.
1849ee378aa4SLai Jiangshan 	 *
1850ee378aa4SLai Jiangshan 	 * manager_mutex would always be free unless CPU hotplug is in
1851ee378aa4SLai Jiangshan 	 * progress.  trylock first without dropping @gcwq->lock.
1852ee378aa4SLai Jiangshan 	 */
1853ee378aa4SLai Jiangshan 	if (unlikely(!mutex_trylock(&pool->manager_mutex))) {
1854ee378aa4SLai Jiangshan 		spin_unlock_irq(&pool->gcwq->lock);
1855ee378aa4SLai Jiangshan 		mutex_lock(&pool->manager_mutex);
1856ee378aa4SLai Jiangshan 		/*
1857ee378aa4SLai Jiangshan 		 * CPU hotplug could have happened while we were waiting
1858ee378aa4SLai Jiangshan 		 * for manager_mutex.  Hotplug itself can't handle us
1859ee378aa4SLai Jiangshan 		 * because manager isn't either on idle or busy list, and
1860ee378aa4SLai Jiangshan 		 * @gcwq's state and ours could have deviated.
1861ee378aa4SLai Jiangshan 		 *
1862ee378aa4SLai Jiangshan 		 * As hotplug is now excluded via manager_mutex, we can
1863ee378aa4SLai Jiangshan 		 * simply try to bind.  It will succeed or fail depending
1864ee378aa4SLai Jiangshan 		 * on @gcwq's current state.  Try it and adjust
1865ee378aa4SLai Jiangshan 		 * %WORKER_UNBOUND accordingly.
1866ee378aa4SLai Jiangshan 		 */
1867ee378aa4SLai Jiangshan 		if (worker_maybe_bind_and_lock(worker))
1868ee378aa4SLai Jiangshan 			worker->flags &= ~WORKER_UNBOUND;
1869ee378aa4SLai Jiangshan 		else
1870ee378aa4SLai Jiangshan 			worker->flags |= WORKER_UNBOUND;
1871ee378aa4SLai Jiangshan 
1872ee378aa4SLai Jiangshan 		ret = true;
1873ee378aa4SLai Jiangshan 	}
1874ee378aa4SLai Jiangshan 
187511ebea50STejun Heo 	pool->flags &= ~POOL_MANAGE_WORKERS;
1876e22bee78STejun Heo 
1877e22bee78STejun Heo 	/*
1878e22bee78STejun Heo 	 * Destroy and then create so that may_start_working() is true
1879e22bee78STejun Heo 	 * on return.
1880e22bee78STejun Heo 	 */
188163d95a91STejun Heo 	ret |= maybe_destroy_workers(pool);
188263d95a91STejun Heo 	ret |= maybe_create_worker(pool);
1883e22bee78STejun Heo 
1884552a37e9SLai Jiangshan 	pool->flags &= ~POOL_MANAGING_WORKERS;
188560373152STejun Heo 	mutex_unlock(&pool->manager_mutex);
1886e22bee78STejun Heo 	return ret;
1887e22bee78STejun Heo }
1888e22bee78STejun Heo 
1889a62428c0STejun Heo /**
1890affee4b2STejun Heo  * move_linked_works - move linked works to a list
1891affee4b2STejun Heo  * @work: start of series of works to be scheduled
1892affee4b2STejun Heo  * @head: target list to append @work to
1893affee4b2STejun Heo  * @nextp: out paramter for nested worklist walking
1894affee4b2STejun Heo  *
1895affee4b2STejun Heo  * Schedule linked works starting from @work to @head.  Work series to
1896affee4b2STejun Heo  * be scheduled starts at @work and includes any consecutive work with
1897affee4b2STejun Heo  * WORK_STRUCT_LINKED set in its predecessor.
1898affee4b2STejun Heo  *
1899affee4b2STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of
1900affee4b2STejun Heo  * the last scheduled work.  This allows move_linked_works() to be
1901affee4b2STejun Heo  * nested inside outer list_for_each_entry_safe().
1902affee4b2STejun Heo  *
1903affee4b2STejun Heo  * CONTEXT:
19048b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock).
1905affee4b2STejun Heo  */
1906affee4b2STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
1907affee4b2STejun Heo 			      struct work_struct **nextp)
1908affee4b2STejun Heo {
1909affee4b2STejun Heo 	struct work_struct *n;
1910affee4b2STejun Heo 
1911affee4b2STejun Heo 	/*
1912affee4b2STejun Heo 	 * Linked worklist will always end before the end of the list,
1913affee4b2STejun Heo 	 * use NULL for list head.
1914affee4b2STejun Heo 	 */
1915affee4b2STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
1916affee4b2STejun Heo 		list_move_tail(&work->entry, head);
1917affee4b2STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1918affee4b2STejun Heo 			break;
1919affee4b2STejun Heo 	}
1920affee4b2STejun Heo 
1921affee4b2STejun Heo 	/*
1922affee4b2STejun Heo 	 * If we're already inside safe list traversal and have moved
1923affee4b2STejun Heo 	 * multiple works to the scheduled queue, the next position
1924affee4b2STejun Heo 	 * needs to be updated.
1925affee4b2STejun Heo 	 */
1926affee4b2STejun Heo 	if (nextp)
1927affee4b2STejun Heo 		*nextp = n;
1928affee4b2STejun Heo }
1929affee4b2STejun Heo 
19301e19ffc6STejun Heo static void cwq_activate_first_delayed(struct cpu_workqueue_struct *cwq)
19311e19ffc6STejun Heo {
19321e19ffc6STejun Heo 	struct work_struct *work = list_first_entry(&cwq->delayed_works,
19331da177e4SLinus Torvalds 						    struct work_struct, entry);
19341e19ffc6STejun Heo 
1935cdadf009STejun Heo 	trace_workqueue_activate_work(work);
19363270476aSTejun Heo 	move_linked_works(work, &cwq->pool->worklist, NULL);
19378a2e8e5dSTejun Heo 	__clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
19381e19ffc6STejun Heo 	cwq->nr_active++;
19391e19ffc6STejun Heo }
19401e19ffc6STejun Heo 
1941affee4b2STejun Heo /**
194273f53c4aSTejun Heo  * cwq_dec_nr_in_flight - decrement cwq's nr_in_flight
194373f53c4aSTejun Heo  * @cwq: cwq of interest
194473f53c4aSTejun Heo  * @color: color of work which left the queue
19458a2e8e5dSTejun Heo  * @delayed: for a delayed work
194673f53c4aSTejun Heo  *
194773f53c4aSTejun Heo  * A work either has completed or is removed from pending queue,
194873f53c4aSTejun Heo  * decrement nr_in_flight of its cwq and handle workqueue flushing.
194973f53c4aSTejun Heo  *
195073f53c4aSTejun Heo  * CONTEXT:
19518b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock).
195273f53c4aSTejun Heo  */
19538a2e8e5dSTejun Heo static void cwq_dec_nr_in_flight(struct cpu_workqueue_struct *cwq, int color,
19548a2e8e5dSTejun Heo 				 bool delayed)
195573f53c4aSTejun Heo {
195673f53c4aSTejun Heo 	/* ignore uncolored works */
195773f53c4aSTejun Heo 	if (color == WORK_NO_COLOR)
195873f53c4aSTejun Heo 		return;
195973f53c4aSTejun Heo 
196073f53c4aSTejun Heo 	cwq->nr_in_flight[color]--;
19611e19ffc6STejun Heo 
19628a2e8e5dSTejun Heo 	if (!delayed) {
19638a2e8e5dSTejun Heo 		cwq->nr_active--;
1964502ca9d8STejun Heo 		if (!list_empty(&cwq->delayed_works)) {
19651e19ffc6STejun Heo 			/* one down, submit a delayed one */
1966502ca9d8STejun Heo 			if (cwq->nr_active < cwq->max_active)
19671e19ffc6STejun Heo 				cwq_activate_first_delayed(cwq);
1968502ca9d8STejun Heo 		}
19698a2e8e5dSTejun Heo 	}
197073f53c4aSTejun Heo 
197173f53c4aSTejun Heo 	/* is flush in progress and are we at the flushing tip? */
197273f53c4aSTejun Heo 	if (likely(cwq->flush_color != color))
197373f53c4aSTejun Heo 		return;
197473f53c4aSTejun Heo 
197573f53c4aSTejun Heo 	/* are there still in-flight works? */
197673f53c4aSTejun Heo 	if (cwq->nr_in_flight[color])
197773f53c4aSTejun Heo 		return;
197873f53c4aSTejun Heo 
197973f53c4aSTejun Heo 	/* this cwq is done, clear flush_color */
198073f53c4aSTejun Heo 	cwq->flush_color = -1;
198173f53c4aSTejun Heo 
198273f53c4aSTejun Heo 	/*
198373f53c4aSTejun Heo 	 * If this was the last cwq, wake up the first flusher.  It
198473f53c4aSTejun Heo 	 * will handle the rest.
198573f53c4aSTejun Heo 	 */
198673f53c4aSTejun Heo 	if (atomic_dec_and_test(&cwq->wq->nr_cwqs_to_flush))
198773f53c4aSTejun Heo 		complete(&cwq->wq->first_flusher->done);
198873f53c4aSTejun Heo }
198973f53c4aSTejun Heo 
199073f53c4aSTejun Heo /**
1991a62428c0STejun Heo  * process_one_work - process single work
1992c34056a3STejun Heo  * @worker: self
1993a62428c0STejun Heo  * @work: work to process
1994a62428c0STejun Heo  *
1995a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
1996a62428c0STejun Heo  * process a single work including synchronization against and
1997a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
1998a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
1999a62428c0STejun Heo  * call this function to process a work.
2000a62428c0STejun Heo  *
2001a62428c0STejun Heo  * CONTEXT:
20028b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock) which is released and regrabbed.
2003a62428c0STejun Heo  */
2004c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
200506bd6ebfSNamhyung Kim __releases(&gcwq->lock)
200606bd6ebfSNamhyung Kim __acquires(&gcwq->lock)
20071da177e4SLinus Torvalds {
20087e11629dSTejun Heo 	struct cpu_workqueue_struct *cwq = get_work_cwq(work);
2009bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2010bd7bdd43STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
2011c8e55f36STejun Heo 	struct hlist_head *bwh = busy_worker_head(gcwq, work);
2012fb0e7bebSTejun Heo 	bool cpu_intensive = cwq->wq->flags & WQ_CPU_INTENSIVE;
20136bb49e59SDavid Howells 	work_func_t f = work->func;
201473f53c4aSTejun Heo 	int work_color;
20157e11629dSTejun Heo 	struct worker *collision;
20164e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
20174e6045f1SJohannes Berg 	/*
2018a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
2019a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
2020a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
2021a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
2022a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
20234e6045f1SJohannes Berg 	 */
20244d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
20254d82a1deSPeter Zijlstra 
20264d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
20274e6045f1SJohannes Berg #endif
20286fec10a1STejun Heo 	/*
20296fec10a1STejun Heo 	 * Ensure we're on the correct CPU.  DISASSOCIATED test is
20306fec10a1STejun Heo 	 * necessary to avoid spurious warnings from rescuers servicing the
20316fec10a1STejun Heo 	 * unbound or a disassociated gcwq.
20326fec10a1STejun Heo 	 */
203325511a47STejun Heo 	WARN_ON_ONCE(!(worker->flags & (WORKER_UNBOUND | WORKER_REBIND)) &&
20346fec10a1STejun Heo 		     !(gcwq->flags & GCWQ_DISASSOCIATED) &&
203525511a47STejun Heo 		     raw_smp_processor_id() != gcwq->cpu);
203625511a47STejun Heo 
20377e11629dSTejun Heo 	/*
20387e11629dSTejun Heo 	 * A single work shouldn't be executed concurrently by
20397e11629dSTejun Heo 	 * multiple workers on a single cpu.  Check whether anyone is
20407e11629dSTejun Heo 	 * already processing the work.  If so, defer the work to the
20417e11629dSTejun Heo 	 * currently executing one.
20427e11629dSTejun Heo 	 */
20437e11629dSTejun Heo 	collision = __find_worker_executing_work(gcwq, bwh, work);
20447e11629dSTejun Heo 	if (unlikely(collision)) {
20457e11629dSTejun Heo 		move_linked_works(work, &collision->scheduled, NULL);
20467e11629dSTejun Heo 		return;
20477e11629dSTejun Heo 	}
20481da177e4SLinus Torvalds 
2049a62428c0STejun Heo 	/* claim and process */
20501da177e4SLinus Torvalds 	debug_work_deactivate(work);
2051c8e55f36STejun Heo 	hlist_add_head(&worker->hentry, bwh);
2052c34056a3STejun Heo 	worker->current_work = work;
20538cca0eeaSTejun Heo 	worker->current_cwq = cwq;
205473f53c4aSTejun Heo 	work_color = get_work_color(work);
20557a22ad75STejun Heo 
20567a22ad75STejun Heo 	/* record the current cpu number in the work data and dequeue */
20577a22ad75STejun Heo 	set_work_cpu(work, gcwq->cpu);
2058a62428c0STejun Heo 	list_del_init(&work->entry);
2059a62428c0STejun Heo 
2060649027d7STejun Heo 	/*
2061fb0e7bebSTejun Heo 	 * CPU intensive works don't participate in concurrency
2062fb0e7bebSTejun Heo 	 * management.  They're the scheduler's responsibility.
2063fb0e7bebSTejun Heo 	 */
2064fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2065fb0e7bebSTejun Heo 		worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
2066fb0e7bebSTejun Heo 
2067974271c4STejun Heo 	/*
2068974271c4STejun Heo 	 * Unbound gcwq isn't concurrency managed and work items should be
2069974271c4STejun Heo 	 * executed ASAP.  Wake up another worker if necessary.
2070974271c4STejun Heo 	 */
207163d95a91STejun Heo 	if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
207263d95a91STejun Heo 		wake_up_worker(pool);
2073974271c4STejun Heo 
20748b03ae3cSTejun Heo 	spin_unlock_irq(&gcwq->lock);
20751da177e4SLinus Torvalds 
207623b2e599SOleg Nesterov 	work_clear_pending(work);
2077e159489bSTejun Heo 	lock_map_acquire_read(&cwq->wq->lockdep_map);
20783295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
2079e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
208065f27f38SDavid Howells 	f(work);
2081e36c886aSArjan van de Ven 	/*
2082e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
2083e36c886aSArjan van de Ven 	 * point will only record its address.
2084e36c886aSArjan van de Ven 	 */
2085e36c886aSArjan van de Ven 	trace_workqueue_execute_end(work);
20863295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
20873295f0efSIngo Molnar 	lock_map_release(&cwq->wq->lockdep_map);
20881da177e4SLinus Torvalds 
2089d5abe669SPeter Zijlstra 	if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2090d5abe669SPeter Zijlstra 		printk(KERN_ERR "BUG: workqueue leaked lock or atomic: "
2091d5abe669SPeter Zijlstra 		       "%s/0x%08x/%d\n",
2092a62428c0STejun Heo 		       current->comm, preempt_count(), task_pid_nr(current));
2093d5abe669SPeter Zijlstra 		printk(KERN_ERR "    last function: ");
2094d5abe669SPeter Zijlstra 		print_symbol("%s\n", (unsigned long)f);
2095d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
2096d5abe669SPeter Zijlstra 		dump_stack();
2097d5abe669SPeter Zijlstra 	}
2098d5abe669SPeter Zijlstra 
20998b03ae3cSTejun Heo 	spin_lock_irq(&gcwq->lock);
2100a62428c0STejun Heo 
2101fb0e7bebSTejun Heo 	/* clear cpu intensive status */
2102fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2103fb0e7bebSTejun Heo 		worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2104fb0e7bebSTejun Heo 
2105a62428c0STejun Heo 	/* we're done with it, release */
2106c8e55f36STejun Heo 	hlist_del_init(&worker->hentry);
2107c34056a3STejun Heo 	worker->current_work = NULL;
21088cca0eeaSTejun Heo 	worker->current_cwq = NULL;
21098a2e8e5dSTejun Heo 	cwq_dec_nr_in_flight(cwq, work_color, false);
21101da177e4SLinus Torvalds }
21111da177e4SLinus Torvalds 
2112affee4b2STejun Heo /**
2113affee4b2STejun Heo  * process_scheduled_works - process scheduled works
2114affee4b2STejun Heo  * @worker: self
2115affee4b2STejun Heo  *
2116affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
2117affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
2118affee4b2STejun Heo  * fetches a work from the top and executes it.
2119affee4b2STejun Heo  *
2120affee4b2STejun Heo  * CONTEXT:
21218b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2122affee4b2STejun Heo  * multiple times.
2123affee4b2STejun Heo  */
2124affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
21251da177e4SLinus Torvalds {
2126affee4b2STejun Heo 	while (!list_empty(&worker->scheduled)) {
2127affee4b2STejun Heo 		struct work_struct *work = list_first_entry(&worker->scheduled,
2128a62428c0STejun Heo 						struct work_struct, entry);
2129c34056a3STejun Heo 		process_one_work(worker, work);
2130a62428c0STejun Heo 	}
21311da177e4SLinus Torvalds }
21321da177e4SLinus Torvalds 
21334690c4abSTejun Heo /**
21344690c4abSTejun Heo  * worker_thread - the worker thread function
2135c34056a3STejun Heo  * @__worker: self
21364690c4abSTejun Heo  *
2137e22bee78STejun Heo  * The gcwq worker thread function.  There's a single dynamic pool of
2138e22bee78STejun Heo  * these per each cpu.  These workers process all works regardless of
2139e22bee78STejun Heo  * their specific target workqueue.  The only exception is works which
2140e22bee78STejun Heo  * belong to workqueues with a rescuer which will be explained in
2141e22bee78STejun Heo  * rescuer_thread().
21424690c4abSTejun Heo  */
2143c34056a3STejun Heo static int worker_thread(void *__worker)
21441da177e4SLinus Torvalds {
2145c34056a3STejun Heo 	struct worker *worker = __worker;
2146bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2147bd7bdd43STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
21481da177e4SLinus Torvalds 
2149e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
2150e22bee78STejun Heo 	worker->task->flags |= PF_WQ_WORKER;
2151c8e55f36STejun Heo woke_up:
21528b03ae3cSTejun Heo 	spin_lock_irq(&gcwq->lock);
2153affee4b2STejun Heo 
215425511a47STejun Heo 	/*
215525511a47STejun Heo 	 * DIE can be set only while idle and REBIND set while busy has
215625511a47STejun Heo 	 * @worker->rebind_work scheduled.  Checking here is enough.
215725511a47STejun Heo 	 */
215825511a47STejun Heo 	if (unlikely(worker->flags & (WORKER_REBIND | WORKER_DIE))) {
2159c8e55f36STejun Heo 		spin_unlock_irq(&gcwq->lock);
216025511a47STejun Heo 
216125511a47STejun Heo 		if (worker->flags & WORKER_DIE) {
2162e22bee78STejun Heo 			worker->task->flags &= ~PF_WQ_WORKER;
2163c8e55f36STejun Heo 			return 0;
2164c8e55f36STejun Heo 		}
2165c8e55f36STejun Heo 
216625511a47STejun Heo 		idle_worker_rebind(worker);
216725511a47STejun Heo 		goto woke_up;
216825511a47STejun Heo 	}
216925511a47STejun Heo 
2170c8e55f36STejun Heo 	worker_leave_idle(worker);
2171db7bccf4STejun Heo recheck:
2172e22bee78STejun Heo 	/* no more worker necessary? */
217363d95a91STejun Heo 	if (!need_more_worker(pool))
2174e22bee78STejun Heo 		goto sleep;
2175e22bee78STejun Heo 
2176e22bee78STejun Heo 	/* do we need to manage? */
217763d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2178e22bee78STejun Heo 		goto recheck;
2179e22bee78STejun Heo 
2180c8e55f36STejun Heo 	/*
2181c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
2182c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
2183c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
2184c8e55f36STejun Heo 	 */
2185c8e55f36STejun Heo 	BUG_ON(!list_empty(&worker->scheduled));
2186c8e55f36STejun Heo 
2187e22bee78STejun Heo 	/*
2188e22bee78STejun Heo 	 * When control reaches this point, we're guaranteed to have
2189e22bee78STejun Heo 	 * at least one idle worker or that someone else has already
2190e22bee78STejun Heo 	 * assumed the manager role.
2191e22bee78STejun Heo 	 */
2192e22bee78STejun Heo 	worker_clr_flags(worker, WORKER_PREP);
2193e22bee78STejun Heo 
2194e22bee78STejun Heo 	do {
2195affee4b2STejun Heo 		struct work_struct *work =
2196bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
2197affee4b2STejun Heo 					 struct work_struct, entry);
2198affee4b2STejun Heo 
2199c8e55f36STejun Heo 		if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2200affee4b2STejun Heo 			/* optimization path, not strictly necessary */
2201affee4b2STejun Heo 			process_one_work(worker, work);
2202affee4b2STejun Heo 			if (unlikely(!list_empty(&worker->scheduled)))
2203affee4b2STejun Heo 				process_scheduled_works(worker);
2204affee4b2STejun Heo 		} else {
2205c8e55f36STejun Heo 			move_linked_works(work, &worker->scheduled, NULL);
2206affee4b2STejun Heo 			process_scheduled_works(worker);
2207affee4b2STejun Heo 		}
220863d95a91STejun Heo 	} while (keep_working(pool));
2209affee4b2STejun Heo 
2210e22bee78STejun Heo 	worker_set_flags(worker, WORKER_PREP, false);
2211d313dd85STejun Heo sleep:
221263d95a91STejun Heo 	if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
2213e22bee78STejun Heo 		goto recheck;
2214d313dd85STejun Heo 
2215c8e55f36STejun Heo 	/*
2216e22bee78STejun Heo 	 * gcwq->lock is held and there's no work to process and no
2217e22bee78STejun Heo 	 * need to manage, sleep.  Workers are woken up only while
2218e22bee78STejun Heo 	 * holding gcwq->lock or from local cpu, so setting the
2219e22bee78STejun Heo 	 * current state before releasing gcwq->lock is enough to
2220e22bee78STejun Heo 	 * prevent losing any event.
2221c8e55f36STejun Heo 	 */
2222c8e55f36STejun Heo 	worker_enter_idle(worker);
2223c8e55f36STejun Heo 	__set_current_state(TASK_INTERRUPTIBLE);
22248b03ae3cSTejun Heo 	spin_unlock_irq(&gcwq->lock);
22251da177e4SLinus Torvalds 	schedule();
2226c8e55f36STejun Heo 	goto woke_up;
22271da177e4SLinus Torvalds }
22281da177e4SLinus Torvalds 
2229e22bee78STejun Heo /**
2230e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
2231e22bee78STejun Heo  * @__wq: the associated workqueue
2232e22bee78STejun Heo  *
2233e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
2234e22bee78STejun Heo  * workqueue which has WQ_RESCUER set.
2235e22bee78STejun Heo  *
2236e22bee78STejun Heo  * Regular work processing on a gcwq may block trying to create a new
2237e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
2238e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
2239e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2240e22bee78STejun Heo  * the problem rescuer solves.
2241e22bee78STejun Heo  *
2242e22bee78STejun Heo  * When such condition is possible, the gcwq summons rescuers of all
2243e22bee78STejun Heo  * workqueues which have works queued on the gcwq and let them process
2244e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
2245e22bee78STejun Heo  *
2246e22bee78STejun Heo  * This should happen rarely.
2247e22bee78STejun Heo  */
2248e22bee78STejun Heo static int rescuer_thread(void *__wq)
2249e22bee78STejun Heo {
2250e22bee78STejun Heo 	struct workqueue_struct *wq = __wq;
2251e22bee78STejun Heo 	struct worker *rescuer = wq->rescuer;
2252e22bee78STejun Heo 	struct list_head *scheduled = &rescuer->scheduled;
2253f3421797STejun Heo 	bool is_unbound = wq->flags & WQ_UNBOUND;
2254e22bee78STejun Heo 	unsigned int cpu;
2255e22bee78STejun Heo 
2256e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
2257e22bee78STejun Heo repeat:
2258e22bee78STejun Heo 	set_current_state(TASK_INTERRUPTIBLE);
22591da177e4SLinus Torvalds 
22601da177e4SLinus Torvalds 	if (kthread_should_stop())
2261e22bee78STejun Heo 		return 0;
22621da177e4SLinus Torvalds 
2263f3421797STejun Heo 	/*
2264f3421797STejun Heo 	 * See whether any cpu is asking for help.  Unbounded
2265f3421797STejun Heo 	 * workqueues use cpu 0 in mayday_mask for CPU_UNBOUND.
2266f3421797STejun Heo 	 */
2267f2e005aaSTejun Heo 	for_each_mayday_cpu(cpu, wq->mayday_mask) {
2268f3421797STejun Heo 		unsigned int tcpu = is_unbound ? WORK_CPU_UNBOUND : cpu;
2269f3421797STejun Heo 		struct cpu_workqueue_struct *cwq = get_cwq(tcpu, wq);
2270bd7bdd43STejun Heo 		struct worker_pool *pool = cwq->pool;
2271bd7bdd43STejun Heo 		struct global_cwq *gcwq = pool->gcwq;
2272e22bee78STejun Heo 		struct work_struct *work, *n;
2273e22bee78STejun Heo 
2274e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
2275f2e005aaSTejun Heo 		mayday_clear_cpu(cpu, wq->mayday_mask);
2276e22bee78STejun Heo 
2277e22bee78STejun Heo 		/* migrate to the target cpu if possible */
2278bd7bdd43STejun Heo 		rescuer->pool = pool;
2279e22bee78STejun Heo 		worker_maybe_bind_and_lock(rescuer);
2280e22bee78STejun Heo 
2281e22bee78STejun Heo 		/*
2282e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
2283e22bee78STejun Heo 		 * process'em.
2284e22bee78STejun Heo 		 */
2285e22bee78STejun Heo 		BUG_ON(!list_empty(&rescuer->scheduled));
2286bd7bdd43STejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry)
2287e22bee78STejun Heo 			if (get_work_cwq(work) == cwq)
2288e22bee78STejun Heo 				move_linked_works(work, scheduled, &n);
2289e22bee78STejun Heo 
2290e22bee78STejun Heo 		process_scheduled_works(rescuer);
22917576958aSTejun Heo 
22927576958aSTejun Heo 		/*
22937576958aSTejun Heo 		 * Leave this gcwq.  If keep_working() is %true, notify a
22947576958aSTejun Heo 		 * regular worker; otherwise, we end up with 0 concurrency
22957576958aSTejun Heo 		 * and stalling the execution.
22967576958aSTejun Heo 		 */
229763d95a91STejun Heo 		if (keep_working(pool))
229863d95a91STejun Heo 			wake_up_worker(pool);
22997576958aSTejun Heo 
2300e22bee78STejun Heo 		spin_unlock_irq(&gcwq->lock);
23011da177e4SLinus Torvalds 	}
23021da177e4SLinus Torvalds 
2303e22bee78STejun Heo 	schedule();
2304e22bee78STejun Heo 	goto repeat;
23051da177e4SLinus Torvalds }
23061da177e4SLinus Torvalds 
2307fc2e4d70SOleg Nesterov struct wq_barrier {
2308fc2e4d70SOleg Nesterov 	struct work_struct	work;
2309fc2e4d70SOleg Nesterov 	struct completion	done;
2310fc2e4d70SOleg Nesterov };
2311fc2e4d70SOleg Nesterov 
2312fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
2313fc2e4d70SOleg Nesterov {
2314fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2315fc2e4d70SOleg Nesterov 	complete(&barr->done);
2316fc2e4d70SOleg Nesterov }
2317fc2e4d70SOleg Nesterov 
23184690c4abSTejun Heo /**
23194690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
23204690c4abSTejun Heo  * @cwq: cwq to insert barrier into
23214690c4abSTejun Heo  * @barr: wq_barrier to insert
2322affee4b2STejun Heo  * @target: target work to attach @barr to
2323affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
23244690c4abSTejun Heo  *
2325affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
2326affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
2327affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
2328affee4b2STejun Heo  * cpu.
2329affee4b2STejun Heo  *
2330affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
2331affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
2332affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
2333affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
2334affee4b2STejun Heo  * after a work with LINKED flag set.
2335affee4b2STejun Heo  *
2336affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
2337affee4b2STejun Heo  * underneath us, so we can't reliably determine cwq from @target.
23384690c4abSTejun Heo  *
23394690c4abSTejun Heo  * CONTEXT:
23408b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock).
23414690c4abSTejun Heo  */
234283c22520SOleg Nesterov static void insert_wq_barrier(struct cpu_workqueue_struct *cwq,
2343affee4b2STejun Heo 			      struct wq_barrier *barr,
2344affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
2345fc2e4d70SOleg Nesterov {
2346affee4b2STejun Heo 	struct list_head *head;
2347affee4b2STejun Heo 	unsigned int linked = 0;
2348affee4b2STejun Heo 
2349dc186ad7SThomas Gleixner 	/*
23508b03ae3cSTejun Heo 	 * debugobject calls are safe here even with gcwq->lock locked
2351dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
2352dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
2353dc186ad7SThomas Gleixner 	 * might deadlock.
2354dc186ad7SThomas Gleixner 	 */
2355ca1cab37SAndrew Morton 	INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
235622df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2357fc2e4d70SOleg Nesterov 	init_completion(&barr->done);
235883c22520SOleg Nesterov 
2359affee4b2STejun Heo 	/*
2360affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
2361affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
2362affee4b2STejun Heo 	 */
2363affee4b2STejun Heo 	if (worker)
2364affee4b2STejun Heo 		head = worker->scheduled.next;
2365affee4b2STejun Heo 	else {
2366affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
2367affee4b2STejun Heo 
2368affee4b2STejun Heo 		head = target->entry.next;
2369affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
2370affee4b2STejun Heo 		linked = *bits & WORK_STRUCT_LINKED;
2371affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
2372affee4b2STejun Heo 	}
2373affee4b2STejun Heo 
2374dc186ad7SThomas Gleixner 	debug_work_activate(&barr->work);
2375affee4b2STejun Heo 	insert_work(cwq, &barr->work, head,
2376affee4b2STejun Heo 		    work_color_to_flags(WORK_NO_COLOR) | linked);
2377fc2e4d70SOleg Nesterov }
2378fc2e4d70SOleg Nesterov 
237973f53c4aSTejun Heo /**
238073f53c4aSTejun Heo  * flush_workqueue_prep_cwqs - prepare cwqs for workqueue flushing
238173f53c4aSTejun Heo  * @wq: workqueue being flushed
238273f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
238373f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
238473f53c4aSTejun Heo  *
238573f53c4aSTejun Heo  * Prepare cwqs for workqueue flushing.
238673f53c4aSTejun Heo  *
238773f53c4aSTejun Heo  * If @flush_color is non-negative, flush_color on all cwqs should be
238873f53c4aSTejun Heo  * -1.  If no cwq has in-flight commands at the specified color, all
238973f53c4aSTejun Heo  * cwq->flush_color's stay at -1 and %false is returned.  If any cwq
239073f53c4aSTejun Heo  * has in flight commands, its cwq->flush_color is set to
239173f53c4aSTejun Heo  * @flush_color, @wq->nr_cwqs_to_flush is updated accordingly, cwq
239273f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
239373f53c4aSTejun Heo  *
239473f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
239573f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
239673f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
239773f53c4aSTejun Heo  * is returned.
239873f53c4aSTejun Heo  *
239973f53c4aSTejun Heo  * If @work_color is non-negative, all cwqs should have the same
240073f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
240173f53c4aSTejun Heo  * advanced to @work_color.
240273f53c4aSTejun Heo  *
240373f53c4aSTejun Heo  * CONTEXT:
240473f53c4aSTejun Heo  * mutex_lock(wq->flush_mutex).
240573f53c4aSTejun Heo  *
240673f53c4aSTejun Heo  * RETURNS:
240773f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
240873f53c4aSTejun Heo  * otherwise.
240973f53c4aSTejun Heo  */
241073f53c4aSTejun Heo static bool flush_workqueue_prep_cwqs(struct workqueue_struct *wq,
241173f53c4aSTejun Heo 				      int flush_color, int work_color)
24121da177e4SLinus Torvalds {
241373f53c4aSTejun Heo 	bool wait = false;
241473f53c4aSTejun Heo 	unsigned int cpu;
24151da177e4SLinus Torvalds 
241673f53c4aSTejun Heo 	if (flush_color >= 0) {
241773f53c4aSTejun Heo 		BUG_ON(atomic_read(&wq->nr_cwqs_to_flush));
241873f53c4aSTejun Heo 		atomic_set(&wq->nr_cwqs_to_flush, 1);
2419dc186ad7SThomas Gleixner 	}
242014441960SOleg Nesterov 
2421f3421797STejun Heo 	for_each_cwq_cpu(cpu, wq) {
242273f53c4aSTejun Heo 		struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2423bd7bdd43STejun Heo 		struct global_cwq *gcwq = cwq->pool->gcwq;
24241da177e4SLinus Torvalds 
24258b03ae3cSTejun Heo 		spin_lock_irq(&gcwq->lock);
242673f53c4aSTejun Heo 
242773f53c4aSTejun Heo 		if (flush_color >= 0) {
242873f53c4aSTejun Heo 			BUG_ON(cwq->flush_color != -1);
242973f53c4aSTejun Heo 
243073f53c4aSTejun Heo 			if (cwq->nr_in_flight[flush_color]) {
243173f53c4aSTejun Heo 				cwq->flush_color = flush_color;
243273f53c4aSTejun Heo 				atomic_inc(&wq->nr_cwqs_to_flush);
243373f53c4aSTejun Heo 				wait = true;
24341da177e4SLinus Torvalds 			}
243573f53c4aSTejun Heo 		}
243673f53c4aSTejun Heo 
243773f53c4aSTejun Heo 		if (work_color >= 0) {
243873f53c4aSTejun Heo 			BUG_ON(work_color != work_next_color(cwq->work_color));
243973f53c4aSTejun Heo 			cwq->work_color = work_color;
244073f53c4aSTejun Heo 		}
244173f53c4aSTejun Heo 
24428b03ae3cSTejun Heo 		spin_unlock_irq(&gcwq->lock);
24431da177e4SLinus Torvalds 	}
24441da177e4SLinus Torvalds 
244573f53c4aSTejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_cwqs_to_flush))
244673f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
244773f53c4aSTejun Heo 
244873f53c4aSTejun Heo 	return wait;
244983c22520SOleg Nesterov }
24501da177e4SLinus Torvalds 
24510fcb78c2SRolf Eike Beer /**
24521da177e4SLinus Torvalds  * flush_workqueue - ensure that any scheduled work has run to completion.
24530fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
24541da177e4SLinus Torvalds  *
24551da177e4SLinus Torvalds  * Forces execution of the workqueue and blocks until its completion.
24561da177e4SLinus Torvalds  * This is typically used in driver shutdown handlers.
24571da177e4SLinus Torvalds  *
2458fc2e4d70SOleg Nesterov  * We sleep until all works which were queued on entry have been handled,
2459fc2e4d70SOleg Nesterov  * but we are not livelocked by new incoming ones.
24601da177e4SLinus Torvalds  */
24617ad5b3a5SHarvey Harrison void flush_workqueue(struct workqueue_struct *wq)
24621da177e4SLinus Torvalds {
246373f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
246473f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
246573f53c4aSTejun Heo 		.flush_color = -1,
246673f53c4aSTejun Heo 		.done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
246773f53c4aSTejun Heo 	};
246873f53c4aSTejun Heo 	int next_color;
2469b1f4ec17SOleg Nesterov 
24703295f0efSIngo Molnar 	lock_map_acquire(&wq->lockdep_map);
24713295f0efSIngo Molnar 	lock_map_release(&wq->lockdep_map);
247273f53c4aSTejun Heo 
247373f53c4aSTejun Heo 	mutex_lock(&wq->flush_mutex);
247473f53c4aSTejun Heo 
247573f53c4aSTejun Heo 	/*
247673f53c4aSTejun Heo 	 * Start-to-wait phase
247773f53c4aSTejun Heo 	 */
247873f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
247973f53c4aSTejun Heo 
248073f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
248173f53c4aSTejun Heo 		/*
248273f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
248373f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
248473f53c4aSTejun Heo 		 * by one.
248573f53c4aSTejun Heo 		 */
248673f53c4aSTejun Heo 		BUG_ON(!list_empty(&wq->flusher_overflow));
248773f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
248873f53c4aSTejun Heo 		wq->work_color = next_color;
248973f53c4aSTejun Heo 
249073f53c4aSTejun Heo 		if (!wq->first_flusher) {
249173f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
249273f53c4aSTejun Heo 			BUG_ON(wq->flush_color != this_flusher.flush_color);
249373f53c4aSTejun Heo 
249473f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
249573f53c4aSTejun Heo 
249673f53c4aSTejun Heo 			if (!flush_workqueue_prep_cwqs(wq, wq->flush_color,
249773f53c4aSTejun Heo 						       wq->work_color)) {
249873f53c4aSTejun Heo 				/* nothing to flush, done */
249973f53c4aSTejun Heo 				wq->flush_color = next_color;
250073f53c4aSTejun Heo 				wq->first_flusher = NULL;
250173f53c4aSTejun Heo 				goto out_unlock;
250273f53c4aSTejun Heo 			}
250373f53c4aSTejun Heo 		} else {
250473f53c4aSTejun Heo 			/* wait in queue */
250573f53c4aSTejun Heo 			BUG_ON(wq->flush_color == this_flusher.flush_color);
250673f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
250773f53c4aSTejun Heo 			flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
250873f53c4aSTejun Heo 		}
250973f53c4aSTejun Heo 	} else {
251073f53c4aSTejun Heo 		/*
251173f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
251273f53c4aSTejun Heo 		 * The next flush completion will assign us
251373f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
251473f53c4aSTejun Heo 		 */
251573f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
251673f53c4aSTejun Heo 	}
251773f53c4aSTejun Heo 
251873f53c4aSTejun Heo 	mutex_unlock(&wq->flush_mutex);
251973f53c4aSTejun Heo 
252073f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
252173f53c4aSTejun Heo 
252273f53c4aSTejun Heo 	/*
252373f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
252473f53c4aSTejun Heo 	 *
252573f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
252673f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
252773f53c4aSTejun Heo 	 */
252873f53c4aSTejun Heo 	if (wq->first_flusher != &this_flusher)
252973f53c4aSTejun Heo 		return;
253073f53c4aSTejun Heo 
253173f53c4aSTejun Heo 	mutex_lock(&wq->flush_mutex);
253273f53c4aSTejun Heo 
25334ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
25344ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
25354ce48b37STejun Heo 		goto out_unlock;
25364ce48b37STejun Heo 
253773f53c4aSTejun Heo 	wq->first_flusher = NULL;
253873f53c4aSTejun Heo 
253973f53c4aSTejun Heo 	BUG_ON(!list_empty(&this_flusher.list));
254073f53c4aSTejun Heo 	BUG_ON(wq->flush_color != this_flusher.flush_color);
254173f53c4aSTejun Heo 
254273f53c4aSTejun Heo 	while (true) {
254373f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
254473f53c4aSTejun Heo 
254573f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
254673f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
254773f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
254873f53c4aSTejun Heo 				break;
254973f53c4aSTejun Heo 			list_del_init(&next->list);
255073f53c4aSTejun Heo 			complete(&next->done);
255173f53c4aSTejun Heo 		}
255273f53c4aSTejun Heo 
255373f53c4aSTejun Heo 		BUG_ON(!list_empty(&wq->flusher_overflow) &&
255473f53c4aSTejun Heo 		       wq->flush_color != work_next_color(wq->work_color));
255573f53c4aSTejun Heo 
255673f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
255773f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
255873f53c4aSTejun Heo 
255973f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
256073f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
256173f53c4aSTejun Heo 			/*
256273f53c4aSTejun Heo 			 * Assign the same color to all overflowed
256373f53c4aSTejun Heo 			 * flushers, advance work_color and append to
256473f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
256573f53c4aSTejun Heo 			 * phase for these overflowed flushers.
256673f53c4aSTejun Heo 			 */
256773f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
256873f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
256973f53c4aSTejun Heo 
257073f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
257173f53c4aSTejun Heo 
257273f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
257373f53c4aSTejun Heo 					      &wq->flusher_queue);
257473f53c4aSTejun Heo 			flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
257573f53c4aSTejun Heo 		}
257673f53c4aSTejun Heo 
257773f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
257873f53c4aSTejun Heo 			BUG_ON(wq->flush_color != wq->work_color);
257973f53c4aSTejun Heo 			break;
258073f53c4aSTejun Heo 		}
258173f53c4aSTejun Heo 
258273f53c4aSTejun Heo 		/*
258373f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
258473f53c4aSTejun Heo 		 * the new first flusher and arm cwqs.
258573f53c4aSTejun Heo 		 */
258673f53c4aSTejun Heo 		BUG_ON(wq->flush_color == wq->work_color);
258773f53c4aSTejun Heo 		BUG_ON(wq->flush_color != next->flush_color);
258873f53c4aSTejun Heo 
258973f53c4aSTejun Heo 		list_del_init(&next->list);
259073f53c4aSTejun Heo 		wq->first_flusher = next;
259173f53c4aSTejun Heo 
259273f53c4aSTejun Heo 		if (flush_workqueue_prep_cwqs(wq, wq->flush_color, -1))
259373f53c4aSTejun Heo 			break;
259473f53c4aSTejun Heo 
259573f53c4aSTejun Heo 		/*
259673f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
259773f53c4aSTejun Heo 		 * flusher and repeat cascading.
259873f53c4aSTejun Heo 		 */
259973f53c4aSTejun Heo 		wq->first_flusher = NULL;
260073f53c4aSTejun Heo 	}
260173f53c4aSTejun Heo 
260273f53c4aSTejun Heo out_unlock:
260373f53c4aSTejun Heo 	mutex_unlock(&wq->flush_mutex);
26041da177e4SLinus Torvalds }
2605ae90dd5dSDave Jones EXPORT_SYMBOL_GPL(flush_workqueue);
26061da177e4SLinus Torvalds 
26079c5a2ba7STejun Heo /**
26089c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
26099c5a2ba7STejun Heo  * @wq: workqueue to drain
26109c5a2ba7STejun Heo  *
26119c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
26129c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
26139c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
26149c5a2ba7STejun Heo  * repeatedly until it becomes empty.  The number of flushing is detemined
26159c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
26169c5a2ba7STejun Heo  * takes too long.
26179c5a2ba7STejun Heo  */
26189c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
26199c5a2ba7STejun Heo {
26209c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
26219c5a2ba7STejun Heo 	unsigned int cpu;
26229c5a2ba7STejun Heo 
26239c5a2ba7STejun Heo 	/*
26249c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
26259c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
26269c5a2ba7STejun Heo 	 * Use WQ_DRAINING so that queue doesn't have to check nr_drainers.
26279c5a2ba7STejun Heo 	 */
26289c5a2ba7STejun Heo 	spin_lock(&workqueue_lock);
26299c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
26309c5a2ba7STejun Heo 		wq->flags |= WQ_DRAINING;
26319c5a2ba7STejun Heo 	spin_unlock(&workqueue_lock);
26329c5a2ba7STejun Heo reflush:
26339c5a2ba7STejun Heo 	flush_workqueue(wq);
26349c5a2ba7STejun Heo 
26359c5a2ba7STejun Heo 	for_each_cwq_cpu(cpu, wq) {
26369c5a2ba7STejun Heo 		struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2637fa2563e4SThomas Tuttle 		bool drained;
26389c5a2ba7STejun Heo 
2639bd7bdd43STejun Heo 		spin_lock_irq(&cwq->pool->gcwq->lock);
2640fa2563e4SThomas Tuttle 		drained = !cwq->nr_active && list_empty(&cwq->delayed_works);
2641bd7bdd43STejun Heo 		spin_unlock_irq(&cwq->pool->gcwq->lock);
2642fa2563e4SThomas Tuttle 
2643fa2563e4SThomas Tuttle 		if (drained)
26449c5a2ba7STejun Heo 			continue;
26459c5a2ba7STejun Heo 
26469c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
26479c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
26489c5a2ba7STejun Heo 			pr_warning("workqueue %s: flush on destruction isn't complete after %u tries\n",
26499c5a2ba7STejun Heo 				   wq->name, flush_cnt);
26509c5a2ba7STejun Heo 		goto reflush;
26519c5a2ba7STejun Heo 	}
26529c5a2ba7STejun Heo 
26539c5a2ba7STejun Heo 	spin_lock(&workqueue_lock);
26549c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
26559c5a2ba7STejun Heo 		wq->flags &= ~WQ_DRAINING;
26569c5a2ba7STejun Heo 	spin_unlock(&workqueue_lock);
26579c5a2ba7STejun Heo }
26589c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
26599c5a2ba7STejun Heo 
2660baf59022STejun Heo static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
2661baf59022STejun Heo 			     bool wait_executing)
2662baf59022STejun Heo {
2663baf59022STejun Heo 	struct worker *worker = NULL;
2664baf59022STejun Heo 	struct global_cwq *gcwq;
2665baf59022STejun Heo 	struct cpu_workqueue_struct *cwq;
2666baf59022STejun Heo 
2667baf59022STejun Heo 	might_sleep();
2668baf59022STejun Heo 	gcwq = get_work_gcwq(work);
2669baf59022STejun Heo 	if (!gcwq)
2670baf59022STejun Heo 		return false;
2671baf59022STejun Heo 
2672baf59022STejun Heo 	spin_lock_irq(&gcwq->lock);
2673baf59022STejun Heo 	if (!list_empty(&work->entry)) {
2674baf59022STejun Heo 		/*
2675baf59022STejun Heo 		 * See the comment near try_to_grab_pending()->smp_rmb().
2676baf59022STejun Heo 		 * If it was re-queued to a different gcwq under us, we
2677baf59022STejun Heo 		 * are not going to wait.
2678baf59022STejun Heo 		 */
2679baf59022STejun Heo 		smp_rmb();
2680baf59022STejun Heo 		cwq = get_work_cwq(work);
2681bd7bdd43STejun Heo 		if (unlikely(!cwq || gcwq != cwq->pool->gcwq))
2682baf59022STejun Heo 			goto already_gone;
2683baf59022STejun Heo 	} else if (wait_executing) {
2684baf59022STejun Heo 		worker = find_worker_executing_work(gcwq, work);
2685baf59022STejun Heo 		if (!worker)
2686baf59022STejun Heo 			goto already_gone;
2687baf59022STejun Heo 		cwq = worker->current_cwq;
2688baf59022STejun Heo 	} else
2689baf59022STejun Heo 		goto already_gone;
2690baf59022STejun Heo 
2691baf59022STejun Heo 	insert_wq_barrier(cwq, barr, work, worker);
2692baf59022STejun Heo 	spin_unlock_irq(&gcwq->lock);
2693baf59022STejun Heo 
2694e159489bSTejun Heo 	/*
2695e159489bSTejun Heo 	 * If @max_active is 1 or rescuer is in use, flushing another work
2696e159489bSTejun Heo 	 * item on the same workqueue may lead to deadlock.  Make sure the
2697e159489bSTejun Heo 	 * flusher is not running on the same workqueue by verifying write
2698e159489bSTejun Heo 	 * access.
2699e159489bSTejun Heo 	 */
2700e159489bSTejun Heo 	if (cwq->wq->saved_max_active == 1 || cwq->wq->flags & WQ_RESCUER)
2701baf59022STejun Heo 		lock_map_acquire(&cwq->wq->lockdep_map);
2702e159489bSTejun Heo 	else
2703e159489bSTejun Heo 		lock_map_acquire_read(&cwq->wq->lockdep_map);
2704baf59022STejun Heo 	lock_map_release(&cwq->wq->lockdep_map);
2705e159489bSTejun Heo 
2706baf59022STejun Heo 	return true;
2707baf59022STejun Heo already_gone:
2708baf59022STejun Heo 	spin_unlock_irq(&gcwq->lock);
2709baf59022STejun Heo 	return false;
2710baf59022STejun Heo }
2711baf59022STejun Heo 
2712db700897SOleg Nesterov /**
2713401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
2714401a8d04STejun Heo  * @work: the work to flush
2715db700897SOleg Nesterov  *
2716401a8d04STejun Heo  * Wait until @work has finished execution.  This function considers
2717401a8d04STejun Heo  * only the last queueing instance of @work.  If @work has been
2718401a8d04STejun Heo  * enqueued across different CPUs on a non-reentrant workqueue or on
2719401a8d04STejun Heo  * multiple workqueues, @work might still be executing on return on
2720401a8d04STejun Heo  * some of the CPUs from earlier queueing.
2721a67da70dSOleg Nesterov  *
2722401a8d04STejun Heo  * If @work was queued only on a non-reentrant, ordered or unbound
2723401a8d04STejun Heo  * workqueue, @work is guaranteed to be idle on return if it hasn't
2724401a8d04STejun Heo  * been requeued since flush started.
2725401a8d04STejun Heo  *
2726401a8d04STejun Heo  * RETURNS:
2727401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
2728401a8d04STejun Heo  * %false if it was already idle.
2729db700897SOleg Nesterov  */
2730401a8d04STejun Heo bool flush_work(struct work_struct *work)
2731db700897SOleg Nesterov {
2732db700897SOleg Nesterov 	struct wq_barrier barr;
2733db700897SOleg Nesterov 
27340976dfc1SStephen Boyd 	lock_map_acquire(&work->lockdep_map);
27350976dfc1SStephen Boyd 	lock_map_release(&work->lockdep_map);
27360976dfc1SStephen Boyd 
2737baf59022STejun Heo 	if (start_flush_work(work, &barr, true)) {
2738db700897SOleg Nesterov 		wait_for_completion(&barr.done);
2739dc186ad7SThomas Gleixner 		destroy_work_on_stack(&barr.work);
2740401a8d04STejun Heo 		return true;
2741baf59022STejun Heo 	} else
2742401a8d04STejun Heo 		return false;
2743db700897SOleg Nesterov }
2744db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
2745db700897SOleg Nesterov 
2746401a8d04STejun Heo static bool wait_on_cpu_work(struct global_cwq *gcwq, struct work_struct *work)
2747401a8d04STejun Heo {
2748401a8d04STejun Heo 	struct wq_barrier barr;
2749401a8d04STejun Heo 	struct worker *worker;
2750401a8d04STejun Heo 
2751401a8d04STejun Heo 	spin_lock_irq(&gcwq->lock);
2752401a8d04STejun Heo 
2753401a8d04STejun Heo 	worker = find_worker_executing_work(gcwq, work);
2754401a8d04STejun Heo 	if (unlikely(worker))
2755401a8d04STejun Heo 		insert_wq_barrier(worker->current_cwq, &barr, work, worker);
2756401a8d04STejun Heo 
2757401a8d04STejun Heo 	spin_unlock_irq(&gcwq->lock);
2758401a8d04STejun Heo 
2759401a8d04STejun Heo 	if (unlikely(worker)) {
2760401a8d04STejun Heo 		wait_for_completion(&barr.done);
2761401a8d04STejun Heo 		destroy_work_on_stack(&barr.work);
2762401a8d04STejun Heo 		return true;
2763401a8d04STejun Heo 	} else
2764401a8d04STejun Heo 		return false;
2765401a8d04STejun Heo }
2766401a8d04STejun Heo 
2767401a8d04STejun Heo static bool wait_on_work(struct work_struct *work)
2768401a8d04STejun Heo {
2769401a8d04STejun Heo 	bool ret = false;
2770401a8d04STejun Heo 	int cpu;
2771401a8d04STejun Heo 
2772401a8d04STejun Heo 	might_sleep();
2773401a8d04STejun Heo 
2774401a8d04STejun Heo 	lock_map_acquire(&work->lockdep_map);
2775401a8d04STejun Heo 	lock_map_release(&work->lockdep_map);
2776401a8d04STejun Heo 
2777401a8d04STejun Heo 	for_each_gcwq_cpu(cpu)
2778401a8d04STejun Heo 		ret |= wait_on_cpu_work(get_gcwq(cpu), work);
2779401a8d04STejun Heo 	return ret;
2780401a8d04STejun Heo }
2781401a8d04STejun Heo 
278209383498STejun Heo /**
278309383498STejun Heo  * flush_work_sync - wait until a work has finished execution
278409383498STejun Heo  * @work: the work to flush
278509383498STejun Heo  *
278609383498STejun Heo  * Wait until @work has finished execution.  On return, it's
278709383498STejun Heo  * guaranteed that all queueing instances of @work which happened
278809383498STejun Heo  * before this function is called are finished.  In other words, if
278909383498STejun Heo  * @work hasn't been requeued since this function was called, @work is
279009383498STejun Heo  * guaranteed to be idle on return.
279109383498STejun Heo  *
279209383498STejun Heo  * RETURNS:
279309383498STejun Heo  * %true if flush_work_sync() waited for the work to finish execution,
279409383498STejun Heo  * %false if it was already idle.
279509383498STejun Heo  */
279609383498STejun Heo bool flush_work_sync(struct work_struct *work)
279709383498STejun Heo {
279809383498STejun Heo 	struct wq_barrier barr;
279909383498STejun Heo 	bool pending, waited;
280009383498STejun Heo 
280109383498STejun Heo 	/* we'll wait for executions separately, queue barr only if pending */
280209383498STejun Heo 	pending = start_flush_work(work, &barr, false);
280309383498STejun Heo 
280409383498STejun Heo 	/* wait for executions to finish */
280509383498STejun Heo 	waited = wait_on_work(work);
280609383498STejun Heo 
280709383498STejun Heo 	/* wait for the pending one */
280809383498STejun Heo 	if (pending) {
280909383498STejun Heo 		wait_for_completion(&barr.done);
281009383498STejun Heo 		destroy_work_on_stack(&barr.work);
281109383498STejun Heo 	}
281209383498STejun Heo 
281309383498STejun Heo 	return pending || waited;
281409383498STejun Heo }
281509383498STejun Heo EXPORT_SYMBOL_GPL(flush_work_sync);
281609383498STejun Heo 
28176e84d644SOleg Nesterov /*
28181f1f642eSOleg Nesterov  * Upon a successful return (>= 0), the caller "owns" WORK_STRUCT_PENDING bit,
28196e84d644SOleg Nesterov  * so this work can't be re-armed in any way.
28206e84d644SOleg Nesterov  */
28216e84d644SOleg Nesterov static int try_to_grab_pending(struct work_struct *work)
28226e84d644SOleg Nesterov {
28238b03ae3cSTejun Heo 	struct global_cwq *gcwq;
28241f1f642eSOleg Nesterov 	int ret = -1;
28256e84d644SOleg Nesterov 
282622df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
28271f1f642eSOleg Nesterov 		return 0;
28286e84d644SOleg Nesterov 
28296e84d644SOleg Nesterov 	/*
28306e84d644SOleg Nesterov 	 * The queueing is in progress, or it is already queued. Try to
28316e84d644SOleg Nesterov 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
28326e84d644SOleg Nesterov 	 */
28337a22ad75STejun Heo 	gcwq = get_work_gcwq(work);
28347a22ad75STejun Heo 	if (!gcwq)
28356e84d644SOleg Nesterov 		return ret;
28366e84d644SOleg Nesterov 
28378b03ae3cSTejun Heo 	spin_lock_irq(&gcwq->lock);
28386e84d644SOleg Nesterov 	if (!list_empty(&work->entry)) {
28396e84d644SOleg Nesterov 		/*
28407a22ad75STejun Heo 		 * This work is queued, but perhaps we locked the wrong gcwq.
28416e84d644SOleg Nesterov 		 * In that case we must see the new value after rmb(), see
28426e84d644SOleg Nesterov 		 * insert_work()->wmb().
28436e84d644SOleg Nesterov 		 */
28446e84d644SOleg Nesterov 		smp_rmb();
28457a22ad75STejun Heo 		if (gcwq == get_work_gcwq(work)) {
2846dc186ad7SThomas Gleixner 			debug_work_deactivate(work);
28476e84d644SOleg Nesterov 			list_del_init(&work->entry);
28487a22ad75STejun Heo 			cwq_dec_nr_in_flight(get_work_cwq(work),
28498a2e8e5dSTejun Heo 				get_work_color(work),
28508a2e8e5dSTejun Heo 				*work_data_bits(work) & WORK_STRUCT_DELAYED);
28516e84d644SOleg Nesterov 			ret = 1;
28526e84d644SOleg Nesterov 		}
28536e84d644SOleg Nesterov 	}
28548b03ae3cSTejun Heo 	spin_unlock_irq(&gcwq->lock);
28556e84d644SOleg Nesterov 
28566e84d644SOleg Nesterov 	return ret;
28576e84d644SOleg Nesterov }
28586e84d644SOleg Nesterov 
2859401a8d04STejun Heo static bool __cancel_work_timer(struct work_struct *work,
28601f1f642eSOleg Nesterov 				struct timer_list* timer)
28611f1f642eSOleg Nesterov {
28621f1f642eSOleg Nesterov 	int ret;
28631f1f642eSOleg Nesterov 
28641f1f642eSOleg Nesterov 	do {
28651f1f642eSOleg Nesterov 		ret = (timer && likely(del_timer(timer)));
28661f1f642eSOleg Nesterov 		if (!ret)
28671f1f642eSOleg Nesterov 			ret = try_to_grab_pending(work);
28681f1f642eSOleg Nesterov 		wait_on_work(work);
28691f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
28701f1f642eSOleg Nesterov 
28717a22ad75STejun Heo 	clear_work_data(work);
28721f1f642eSOleg Nesterov 	return ret;
28731f1f642eSOleg Nesterov }
28741f1f642eSOleg Nesterov 
28756e84d644SOleg Nesterov /**
2876401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
2877401a8d04STejun Heo  * @work: the work to cancel
28786e84d644SOleg Nesterov  *
2879401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
2880401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
2881401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
2882401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
28831f1f642eSOleg Nesterov  *
2884401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
2885401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
28866e84d644SOleg Nesterov  *
2887401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
28886e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
2889401a8d04STejun Heo  *
2890401a8d04STejun Heo  * RETURNS:
2891401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
28926e84d644SOleg Nesterov  */
2893401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
28946e84d644SOleg Nesterov {
28951f1f642eSOleg Nesterov 	return __cancel_work_timer(work, NULL);
2896b89deed3SOleg Nesterov }
289728e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
2898b89deed3SOleg Nesterov 
28996e84d644SOleg Nesterov /**
2900401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
2901401a8d04STejun Heo  * @dwork: the delayed work to flush
29026e84d644SOleg Nesterov  *
2903401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
2904401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
2905401a8d04STejun Heo  * considers the last queueing instance of @dwork.
29061f1f642eSOleg Nesterov  *
2907401a8d04STejun Heo  * RETURNS:
2908401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
2909401a8d04STejun Heo  * %false if it was already idle.
29106e84d644SOleg Nesterov  */
2911401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
2912401a8d04STejun Heo {
2913401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
2914401a8d04STejun Heo 		__queue_work(raw_smp_processor_id(),
2915401a8d04STejun Heo 			     get_work_cwq(&dwork->work)->wq, &dwork->work);
2916401a8d04STejun Heo 	return flush_work(&dwork->work);
2917401a8d04STejun Heo }
2918401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
2919401a8d04STejun Heo 
2920401a8d04STejun Heo /**
292109383498STejun Heo  * flush_delayed_work_sync - wait for a dwork to finish
292209383498STejun Heo  * @dwork: the delayed work to flush
292309383498STejun Heo  *
292409383498STejun Heo  * Delayed timer is cancelled and the pending work is queued for
292509383498STejun Heo  * execution immediately.  Other than timer handling, its behavior
292609383498STejun Heo  * is identical to flush_work_sync().
292709383498STejun Heo  *
292809383498STejun Heo  * RETURNS:
292909383498STejun Heo  * %true if flush_work_sync() waited for the work to finish execution,
293009383498STejun Heo  * %false if it was already idle.
293109383498STejun Heo  */
293209383498STejun Heo bool flush_delayed_work_sync(struct delayed_work *dwork)
293309383498STejun Heo {
293409383498STejun Heo 	if (del_timer_sync(&dwork->timer))
293509383498STejun Heo 		__queue_work(raw_smp_processor_id(),
293609383498STejun Heo 			     get_work_cwq(&dwork->work)->wq, &dwork->work);
293709383498STejun Heo 	return flush_work_sync(&dwork->work);
293809383498STejun Heo }
293909383498STejun Heo EXPORT_SYMBOL(flush_delayed_work_sync);
294009383498STejun Heo 
294109383498STejun Heo /**
2942401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2943401a8d04STejun Heo  * @dwork: the delayed work cancel
2944401a8d04STejun Heo  *
2945401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
2946401a8d04STejun Heo  *
2947401a8d04STejun Heo  * RETURNS:
2948401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
2949401a8d04STejun Heo  */
2950401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
29516e84d644SOleg Nesterov {
29521f1f642eSOleg Nesterov 	return __cancel_work_timer(&dwork->work, &dwork->timer);
29536e84d644SOleg Nesterov }
2954f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
29551da177e4SLinus Torvalds 
29560fcb78c2SRolf Eike Beer /**
29570fcb78c2SRolf Eike Beer  * schedule_work - put work task in global workqueue
29580fcb78c2SRolf Eike Beer  * @work: job to be done
29590fcb78c2SRolf Eike Beer  *
29605b0f437dSBart Van Assche  * Returns zero if @work was already on the kernel-global workqueue and
29615b0f437dSBart Van Assche  * non-zero otherwise.
29625b0f437dSBart Van Assche  *
29635b0f437dSBart Van Assche  * This puts a job in the kernel-global workqueue if it was not already
29645b0f437dSBart Van Assche  * queued and leaves it in the same position on the kernel-global
29655b0f437dSBart Van Assche  * workqueue otherwise.
29660fcb78c2SRolf Eike Beer  */
29677ad5b3a5SHarvey Harrison int schedule_work(struct work_struct *work)
29681da177e4SLinus Torvalds {
2969d320c038STejun Heo 	return queue_work(system_wq, work);
29701da177e4SLinus Torvalds }
2971ae90dd5dSDave Jones EXPORT_SYMBOL(schedule_work);
29721da177e4SLinus Torvalds 
2973c1a220e7SZhang Rui /*
2974c1a220e7SZhang Rui  * schedule_work_on - put work task on a specific cpu
2975c1a220e7SZhang Rui  * @cpu: cpu to put the work task on
2976c1a220e7SZhang Rui  * @work: job to be done
2977c1a220e7SZhang Rui  *
2978c1a220e7SZhang Rui  * This puts a job on a specific cpu
2979c1a220e7SZhang Rui  */
2980c1a220e7SZhang Rui int schedule_work_on(int cpu, struct work_struct *work)
2981c1a220e7SZhang Rui {
2982d320c038STejun Heo 	return queue_work_on(cpu, system_wq, work);
2983c1a220e7SZhang Rui }
2984c1a220e7SZhang Rui EXPORT_SYMBOL(schedule_work_on);
2985c1a220e7SZhang Rui 
29860fcb78c2SRolf Eike Beer /**
29870fcb78c2SRolf Eike Beer  * schedule_delayed_work - put work task in global workqueue after delay
298852bad64dSDavid Howells  * @dwork: job to be done
298952bad64dSDavid Howells  * @delay: number of jiffies to wait or 0 for immediate execution
29900fcb78c2SRolf Eike Beer  *
29910fcb78c2SRolf Eike Beer  * After waiting for a given time this puts a job in the kernel-global
29920fcb78c2SRolf Eike Beer  * workqueue.
29930fcb78c2SRolf Eike Beer  */
29947ad5b3a5SHarvey Harrison int schedule_delayed_work(struct delayed_work *dwork,
299582f67cd9SIngo Molnar 					unsigned long delay)
29961da177e4SLinus Torvalds {
2997d320c038STejun Heo 	return queue_delayed_work(system_wq, dwork, delay);
29981da177e4SLinus Torvalds }
2999ae90dd5dSDave Jones EXPORT_SYMBOL(schedule_delayed_work);
30001da177e4SLinus Torvalds 
30010fcb78c2SRolf Eike Beer /**
30020fcb78c2SRolf Eike Beer  * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
30030fcb78c2SRolf Eike Beer  * @cpu: cpu to use
300452bad64dSDavid Howells  * @dwork: job to be done
30050fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait
30060fcb78c2SRolf Eike Beer  *
30070fcb78c2SRolf Eike Beer  * After waiting for a given time this puts a job in the kernel-global
30080fcb78c2SRolf Eike Beer  * workqueue on the specified CPU.
30090fcb78c2SRolf Eike Beer  */
30101da177e4SLinus Torvalds int schedule_delayed_work_on(int cpu,
301152bad64dSDavid Howells 			struct delayed_work *dwork, unsigned long delay)
30121da177e4SLinus Torvalds {
3013d320c038STejun Heo 	return queue_delayed_work_on(cpu, system_wq, dwork, delay);
30141da177e4SLinus Torvalds }
3015ae90dd5dSDave Jones EXPORT_SYMBOL(schedule_delayed_work_on);
30161da177e4SLinus Torvalds 
3017b6136773SAndrew Morton /**
301831ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
3019b6136773SAndrew Morton  * @func: the function to call
3020b6136773SAndrew Morton  *
302131ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
302231ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
3023b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
302431ddd871STejun Heo  *
302531ddd871STejun Heo  * RETURNS:
302631ddd871STejun Heo  * 0 on success, -errno on failure.
3027b6136773SAndrew Morton  */
302865f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
302915316ba8SChristoph Lameter {
303015316ba8SChristoph Lameter 	int cpu;
303138f51568SNamhyung Kim 	struct work_struct __percpu *works;
303215316ba8SChristoph Lameter 
3033b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
3034b6136773SAndrew Morton 	if (!works)
303515316ba8SChristoph Lameter 		return -ENOMEM;
3036b6136773SAndrew Morton 
303795402b38SGautham R Shenoy 	get_online_cpus();
303893981800STejun Heo 
303915316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
30409bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
30419bfb1839SIngo Molnar 
30429bfb1839SIngo Molnar 		INIT_WORK(work, func);
30438de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
304415316ba8SChristoph Lameter 	}
304593981800STejun Heo 
304693981800STejun Heo 	for_each_online_cpu(cpu)
30478616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
304893981800STejun Heo 
304995402b38SGautham R Shenoy 	put_online_cpus();
3050b6136773SAndrew Morton 	free_percpu(works);
305115316ba8SChristoph Lameter 	return 0;
305215316ba8SChristoph Lameter }
305315316ba8SChristoph Lameter 
3054eef6a7d5SAlan Stern /**
3055eef6a7d5SAlan Stern  * flush_scheduled_work - ensure that any scheduled work has run to completion.
3056eef6a7d5SAlan Stern  *
3057eef6a7d5SAlan Stern  * Forces execution of the kernel-global workqueue and blocks until its
3058eef6a7d5SAlan Stern  * completion.
3059eef6a7d5SAlan Stern  *
3060eef6a7d5SAlan Stern  * Think twice before calling this function!  It's very easy to get into
3061eef6a7d5SAlan Stern  * trouble if you don't take great care.  Either of the following situations
3062eef6a7d5SAlan Stern  * will lead to deadlock:
3063eef6a7d5SAlan Stern  *
3064eef6a7d5SAlan Stern  *	One of the work items currently on the workqueue needs to acquire
3065eef6a7d5SAlan Stern  *	a lock held by your code or its caller.
3066eef6a7d5SAlan Stern  *
3067eef6a7d5SAlan Stern  *	Your code is running in the context of a work routine.
3068eef6a7d5SAlan Stern  *
3069eef6a7d5SAlan Stern  * They will be detected by lockdep when they occur, but the first might not
3070eef6a7d5SAlan Stern  * occur very often.  It depends on what work items are on the workqueue and
3071eef6a7d5SAlan Stern  * what locks they need, which you have no control over.
3072eef6a7d5SAlan Stern  *
3073eef6a7d5SAlan Stern  * In most situations flushing the entire workqueue is overkill; you merely
3074eef6a7d5SAlan Stern  * need to know that a particular work item isn't queued and isn't running.
3075eef6a7d5SAlan Stern  * In such cases you should use cancel_delayed_work_sync() or
3076eef6a7d5SAlan Stern  * cancel_work_sync() instead.
3077eef6a7d5SAlan Stern  */
30781da177e4SLinus Torvalds void flush_scheduled_work(void)
30791da177e4SLinus Torvalds {
3080d320c038STejun Heo 	flush_workqueue(system_wq);
30811da177e4SLinus Torvalds }
3082ae90dd5dSDave Jones EXPORT_SYMBOL(flush_scheduled_work);
30831da177e4SLinus Torvalds 
30841da177e4SLinus Torvalds /**
30851fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
30861fa44ecaSJames Bottomley  * @fn:		the function to execute
30871fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
30881fa44ecaSJames Bottomley  *		be available when the work executes)
30891fa44ecaSJames Bottomley  *
30901fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
30911fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
30921fa44ecaSJames Bottomley  *
30931fa44ecaSJames Bottomley  * Returns:	0 - function was executed
30941fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
30951fa44ecaSJames Bottomley  */
309665f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
30971fa44ecaSJames Bottomley {
30981fa44ecaSJames Bottomley 	if (!in_interrupt()) {
309965f27f38SDavid Howells 		fn(&ew->work);
31001fa44ecaSJames Bottomley 		return 0;
31011fa44ecaSJames Bottomley 	}
31021fa44ecaSJames Bottomley 
310365f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
31041fa44ecaSJames Bottomley 	schedule_work(&ew->work);
31051fa44ecaSJames Bottomley 
31061fa44ecaSJames Bottomley 	return 1;
31071fa44ecaSJames Bottomley }
31081fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
31091fa44ecaSJames Bottomley 
31101da177e4SLinus Torvalds int keventd_up(void)
31111da177e4SLinus Torvalds {
3112d320c038STejun Heo 	return system_wq != NULL;
31131da177e4SLinus Torvalds }
31141da177e4SLinus Torvalds 
3115bdbc5dd7STejun Heo static int alloc_cwqs(struct workqueue_struct *wq)
31161da177e4SLinus Torvalds {
31173af24433SOleg Nesterov 	/*
31180f900049STejun Heo 	 * cwqs are forced aligned according to WORK_STRUCT_FLAG_BITS.
31190f900049STejun Heo 	 * Make sure that the alignment isn't lower than that of
31200f900049STejun Heo 	 * unsigned long long.
31213af24433SOleg Nesterov 	 */
31220f900049STejun Heo 	const size_t size = sizeof(struct cpu_workqueue_struct);
31230f900049STejun Heo 	const size_t align = max_t(size_t, 1 << WORK_STRUCT_FLAG_BITS,
31240f900049STejun Heo 				   __alignof__(unsigned long long));
31253af24433SOleg Nesterov 
3126e06ffa1eSLai Jiangshan 	if (!(wq->flags & WQ_UNBOUND))
3127f3421797STejun Heo 		wq->cpu_wq.pcpu = __alloc_percpu(size, align);
3128931ac77eSTejun Heo 	else {
31290f900049STejun Heo 		void *ptr;
3130e1d8aa9fSFrederic Weisbecker 
31310f900049STejun Heo 		/*
3132f3421797STejun Heo 		 * Allocate enough room to align cwq and put an extra
3133f3421797STejun Heo 		 * pointer at the end pointing back to the originally
3134f3421797STejun Heo 		 * allocated pointer which will be used for free.
31350f900049STejun Heo 		 */
3136bdbc5dd7STejun Heo 		ptr = kzalloc(size + align + sizeof(void *), GFP_KERNEL);
3137bdbc5dd7STejun Heo 		if (ptr) {
3138bdbc5dd7STejun Heo 			wq->cpu_wq.single = PTR_ALIGN(ptr, align);
3139bdbc5dd7STejun Heo 			*(void **)(wq->cpu_wq.single + 1) = ptr;
3140bdbc5dd7STejun Heo 		}
31413af24433SOleg Nesterov 	}
31423af24433SOleg Nesterov 
31430415b00dSTejun Heo 	/* just in case, make sure it's actually aligned */
3144bdbc5dd7STejun Heo 	BUG_ON(!IS_ALIGNED(wq->cpu_wq.v, align));
3145bdbc5dd7STejun Heo 	return wq->cpu_wq.v ? 0 : -ENOMEM;
31460f900049STejun Heo }
31470f900049STejun Heo 
3148bdbc5dd7STejun Heo static void free_cwqs(struct workqueue_struct *wq)
314906ba38a9SOleg Nesterov {
3150e06ffa1eSLai Jiangshan 	if (!(wq->flags & WQ_UNBOUND))
3151bdbc5dd7STejun Heo 		free_percpu(wq->cpu_wq.pcpu);
3152f3421797STejun Heo 	else if (wq->cpu_wq.single) {
3153f3421797STejun Heo 		/* the pointer to free is stored right after the cwq */
3154f3421797STejun Heo 		kfree(*(void **)(wq->cpu_wq.single + 1));
315506ba38a9SOleg Nesterov 	}
315606ba38a9SOleg Nesterov }
315706ba38a9SOleg Nesterov 
3158f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
3159f3421797STejun Heo 			       const char *name)
3160b71ab8c2STejun Heo {
3161f3421797STejun Heo 	int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3162f3421797STejun Heo 
3163f3421797STejun Heo 	if (max_active < 1 || max_active > lim)
3164b71ab8c2STejun Heo 		printk(KERN_WARNING "workqueue: max_active %d requested for %s "
3165b71ab8c2STejun Heo 		       "is out of range, clamping between %d and %d\n",
3166f3421797STejun Heo 		       max_active, name, 1, lim);
3167b71ab8c2STejun Heo 
3168f3421797STejun Heo 	return clamp_val(max_active, 1, lim);
3169b71ab8c2STejun Heo }
3170b71ab8c2STejun Heo 
3171b196be89STejun Heo struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
317297e37d7bSTejun Heo 					       unsigned int flags,
31731e19ffc6STejun Heo 					       int max_active,
3174eb13ba87SJohannes Berg 					       struct lock_class_key *key,
3175b196be89STejun Heo 					       const char *lock_name, ...)
31763af24433SOleg Nesterov {
3177b196be89STejun Heo 	va_list args, args1;
31783af24433SOleg Nesterov 	struct workqueue_struct *wq;
3179c34056a3STejun Heo 	unsigned int cpu;
3180b196be89STejun Heo 	size_t namelen;
3181b196be89STejun Heo 
3182b196be89STejun Heo 	/* determine namelen, allocate wq and format name */
3183b196be89STejun Heo 	va_start(args, lock_name);
3184b196be89STejun Heo 	va_copy(args1, args);
3185b196be89STejun Heo 	namelen = vsnprintf(NULL, 0, fmt, args) + 1;
3186b196be89STejun Heo 
3187b196be89STejun Heo 	wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
3188b196be89STejun Heo 	if (!wq)
3189b196be89STejun Heo 		goto err;
3190b196be89STejun Heo 
3191b196be89STejun Heo 	vsnprintf(wq->name, namelen, fmt, args1);
3192b196be89STejun Heo 	va_end(args);
3193b196be89STejun Heo 	va_end(args1);
31943af24433SOleg Nesterov 
3195f3421797STejun Heo 	/*
31966370a6adSTejun Heo 	 * Workqueues which may be used during memory reclaim should
31976370a6adSTejun Heo 	 * have a rescuer to guarantee forward progress.
31986370a6adSTejun Heo 	 */
31996370a6adSTejun Heo 	if (flags & WQ_MEM_RECLAIM)
32006370a6adSTejun Heo 		flags |= WQ_RESCUER;
32016370a6adSTejun Heo 
3202d320c038STejun Heo 	max_active = max_active ?: WQ_DFL_ACTIVE;
3203b196be89STejun Heo 	max_active = wq_clamp_max_active(max_active, flags, wq->name);
32043af24433SOleg Nesterov 
3205b196be89STejun Heo 	/* init wq */
320697e37d7bSTejun Heo 	wq->flags = flags;
3207a0a1a5fdSTejun Heo 	wq->saved_max_active = max_active;
320873f53c4aSTejun Heo 	mutex_init(&wq->flush_mutex);
320973f53c4aSTejun Heo 	atomic_set(&wq->nr_cwqs_to_flush, 0);
321073f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
321173f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
32123af24433SOleg Nesterov 
3213eb13ba87SJohannes Berg 	lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3214cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
32153af24433SOleg Nesterov 
3216bdbc5dd7STejun Heo 	if (alloc_cwqs(wq) < 0)
3217bdbc5dd7STejun Heo 		goto err;
3218bdbc5dd7STejun Heo 
3219f3421797STejun Heo 	for_each_cwq_cpu(cpu, wq) {
32201537663fSTejun Heo 		struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
32218b03ae3cSTejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
32223270476aSTejun Heo 		int pool_idx = (bool)(flags & WQ_HIGHPRI);
32231537663fSTejun Heo 
32240f900049STejun Heo 		BUG_ON((unsigned long)cwq & WORK_STRUCT_FLAG_MASK);
32253270476aSTejun Heo 		cwq->pool = &gcwq->pools[pool_idx];
3226c34056a3STejun Heo 		cwq->wq = wq;
322773f53c4aSTejun Heo 		cwq->flush_color = -1;
32281e19ffc6STejun Heo 		cwq->max_active = max_active;
32291e19ffc6STejun Heo 		INIT_LIST_HEAD(&cwq->delayed_works);
3230e22bee78STejun Heo 	}
32311537663fSTejun Heo 
3232e22bee78STejun Heo 	if (flags & WQ_RESCUER) {
3233e22bee78STejun Heo 		struct worker *rescuer;
3234e22bee78STejun Heo 
3235f2e005aaSTejun Heo 		if (!alloc_mayday_mask(&wq->mayday_mask, GFP_KERNEL))
3236e22bee78STejun Heo 			goto err;
3237e22bee78STejun Heo 
3238e22bee78STejun Heo 		wq->rescuer = rescuer = alloc_worker();
3239e22bee78STejun Heo 		if (!rescuer)
3240e22bee78STejun Heo 			goto err;
3241e22bee78STejun Heo 
3242b196be89STejun Heo 		rescuer->task = kthread_create(rescuer_thread, wq, "%s",
3243b196be89STejun Heo 					       wq->name);
3244e22bee78STejun Heo 		if (IS_ERR(rescuer->task))
3245e22bee78STejun Heo 			goto err;
3246e22bee78STejun Heo 
3247e22bee78STejun Heo 		rescuer->task->flags |= PF_THREAD_BOUND;
3248e22bee78STejun Heo 		wake_up_process(rescuer->task);
32493af24433SOleg Nesterov 	}
32501537663fSTejun Heo 
32513af24433SOleg Nesterov 	/*
3252a0a1a5fdSTejun Heo 	 * workqueue_lock protects global freeze state and workqueues
3253a0a1a5fdSTejun Heo 	 * list.  Grab it, set max_active accordingly and add the new
3254a0a1a5fdSTejun Heo 	 * workqueue to workqueues list.
32553af24433SOleg Nesterov 	 */
32563af24433SOleg Nesterov 	spin_lock(&workqueue_lock);
3257a0a1a5fdSTejun Heo 
325858a69cb4STejun Heo 	if (workqueue_freezing && wq->flags & WQ_FREEZABLE)
3259f3421797STejun Heo 		for_each_cwq_cpu(cpu, wq)
3260a0a1a5fdSTejun Heo 			get_cwq(cpu, wq)->max_active = 0;
3261a0a1a5fdSTejun Heo 
32623af24433SOleg Nesterov 	list_add(&wq->list, &workqueues);
3263a0a1a5fdSTejun Heo 
32643af24433SOleg Nesterov 	spin_unlock(&workqueue_lock);
32653af24433SOleg Nesterov 
32663af24433SOleg Nesterov 	return wq;
32674690c4abSTejun Heo err:
32684690c4abSTejun Heo 	if (wq) {
3269bdbc5dd7STejun Heo 		free_cwqs(wq);
3270f2e005aaSTejun Heo 		free_mayday_mask(wq->mayday_mask);
3271e22bee78STejun Heo 		kfree(wq->rescuer);
32724690c4abSTejun Heo 		kfree(wq);
32733af24433SOleg Nesterov 	}
32744690c4abSTejun Heo 	return NULL;
32751da177e4SLinus Torvalds }
3276d320c038STejun Heo EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
32771da177e4SLinus Torvalds 
32783af24433SOleg Nesterov /**
32793af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
32803af24433SOleg Nesterov  * @wq: target workqueue
32813af24433SOleg Nesterov  *
32823af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
32833af24433SOleg Nesterov  */
32843af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
32853af24433SOleg Nesterov {
3286c8e55f36STejun Heo 	unsigned int cpu;
32873af24433SOleg Nesterov 
32889c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
32899c5a2ba7STejun Heo 	drain_workqueue(wq);
3290c8efcc25STejun Heo 
3291a0a1a5fdSTejun Heo 	/*
3292a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
3293a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
3294a0a1a5fdSTejun Heo 	 */
329595402b38SGautham R Shenoy 	spin_lock(&workqueue_lock);
32963af24433SOleg Nesterov 	list_del(&wq->list);
329795402b38SGautham R Shenoy 	spin_unlock(&workqueue_lock);
32983af24433SOleg Nesterov 
3299e22bee78STejun Heo 	/* sanity check */
3300f3421797STejun Heo 	for_each_cwq_cpu(cpu, wq) {
330173f53c4aSTejun Heo 		struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
330273f53c4aSTejun Heo 		int i;
33033af24433SOleg Nesterov 
330473f53c4aSTejun Heo 		for (i = 0; i < WORK_NR_COLORS; i++)
330573f53c4aSTejun Heo 			BUG_ON(cwq->nr_in_flight[i]);
33061e19ffc6STejun Heo 		BUG_ON(cwq->nr_active);
33071e19ffc6STejun Heo 		BUG_ON(!list_empty(&cwq->delayed_works));
330873f53c4aSTejun Heo 	}
33091537663fSTejun Heo 
3310e22bee78STejun Heo 	if (wq->flags & WQ_RESCUER) {
3311e22bee78STejun Heo 		kthread_stop(wq->rescuer->task);
3312f2e005aaSTejun Heo 		free_mayday_mask(wq->mayday_mask);
33138d9df9f0SXiaotian Feng 		kfree(wq->rescuer);
3314e22bee78STejun Heo 	}
3315e22bee78STejun Heo 
3316bdbc5dd7STejun Heo 	free_cwqs(wq);
33173af24433SOleg Nesterov 	kfree(wq);
33183af24433SOleg Nesterov }
33193af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
33203af24433SOleg Nesterov 
3321dcd989cbSTejun Heo /**
3322dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
3323dcd989cbSTejun Heo  * @wq: target workqueue
3324dcd989cbSTejun Heo  * @max_active: new max_active value.
3325dcd989cbSTejun Heo  *
3326dcd989cbSTejun Heo  * Set max_active of @wq to @max_active.
3327dcd989cbSTejun Heo  *
3328dcd989cbSTejun Heo  * CONTEXT:
3329dcd989cbSTejun Heo  * Don't call from IRQ context.
3330dcd989cbSTejun Heo  */
3331dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
3332dcd989cbSTejun Heo {
3333dcd989cbSTejun Heo 	unsigned int cpu;
3334dcd989cbSTejun Heo 
3335f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
3336dcd989cbSTejun Heo 
3337dcd989cbSTejun Heo 	spin_lock(&workqueue_lock);
3338dcd989cbSTejun Heo 
3339dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
3340dcd989cbSTejun Heo 
3341f3421797STejun Heo 	for_each_cwq_cpu(cpu, wq) {
3342dcd989cbSTejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
3343dcd989cbSTejun Heo 
3344dcd989cbSTejun Heo 		spin_lock_irq(&gcwq->lock);
3345dcd989cbSTejun Heo 
334658a69cb4STejun Heo 		if (!(wq->flags & WQ_FREEZABLE) ||
3347dcd989cbSTejun Heo 		    !(gcwq->flags & GCWQ_FREEZING))
3348dcd989cbSTejun Heo 			get_cwq(gcwq->cpu, wq)->max_active = max_active;
3349dcd989cbSTejun Heo 
3350dcd989cbSTejun Heo 		spin_unlock_irq(&gcwq->lock);
3351dcd989cbSTejun Heo 	}
3352dcd989cbSTejun Heo 
3353dcd989cbSTejun Heo 	spin_unlock(&workqueue_lock);
3354dcd989cbSTejun Heo }
3355dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
3356dcd989cbSTejun Heo 
3357dcd989cbSTejun Heo /**
3358dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
3359dcd989cbSTejun Heo  * @cpu: CPU in question
3360dcd989cbSTejun Heo  * @wq: target workqueue
3361dcd989cbSTejun Heo  *
3362dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
3363dcd989cbSTejun Heo  * no synchronization around this function and the test result is
3364dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
3365dcd989cbSTejun Heo  *
3366dcd989cbSTejun Heo  * RETURNS:
3367dcd989cbSTejun Heo  * %true if congested, %false otherwise.
3368dcd989cbSTejun Heo  */
3369dcd989cbSTejun Heo bool workqueue_congested(unsigned int cpu, struct workqueue_struct *wq)
3370dcd989cbSTejun Heo {
3371dcd989cbSTejun Heo 	struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3372dcd989cbSTejun Heo 
3373dcd989cbSTejun Heo 	return !list_empty(&cwq->delayed_works);
3374dcd989cbSTejun Heo }
3375dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
3376dcd989cbSTejun Heo 
3377dcd989cbSTejun Heo /**
3378dcd989cbSTejun Heo  * work_cpu - return the last known associated cpu for @work
3379dcd989cbSTejun Heo  * @work: the work of interest
3380dcd989cbSTejun Heo  *
3381dcd989cbSTejun Heo  * RETURNS:
3382bdbc5dd7STejun Heo  * CPU number if @work was ever queued.  WORK_CPU_NONE otherwise.
3383dcd989cbSTejun Heo  */
3384dcd989cbSTejun Heo unsigned int work_cpu(struct work_struct *work)
3385dcd989cbSTejun Heo {
3386dcd989cbSTejun Heo 	struct global_cwq *gcwq = get_work_gcwq(work);
3387dcd989cbSTejun Heo 
3388bdbc5dd7STejun Heo 	return gcwq ? gcwq->cpu : WORK_CPU_NONE;
3389dcd989cbSTejun Heo }
3390dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_cpu);
3391dcd989cbSTejun Heo 
3392dcd989cbSTejun Heo /**
3393dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
3394dcd989cbSTejun Heo  * @work: the work to be tested
3395dcd989cbSTejun Heo  *
3396dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
3397dcd989cbSTejun Heo  * synchronization around this function and the test result is
3398dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
3399dcd989cbSTejun Heo  * Especially for reentrant wqs, the pending state might hide the
3400dcd989cbSTejun Heo  * running state.
3401dcd989cbSTejun Heo  *
3402dcd989cbSTejun Heo  * RETURNS:
3403dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
3404dcd989cbSTejun Heo  */
3405dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
3406dcd989cbSTejun Heo {
3407dcd989cbSTejun Heo 	struct global_cwq *gcwq = get_work_gcwq(work);
3408dcd989cbSTejun Heo 	unsigned long flags;
3409dcd989cbSTejun Heo 	unsigned int ret = 0;
3410dcd989cbSTejun Heo 
3411dcd989cbSTejun Heo 	if (!gcwq)
3412dcd989cbSTejun Heo 		return false;
3413dcd989cbSTejun Heo 
3414dcd989cbSTejun Heo 	spin_lock_irqsave(&gcwq->lock, flags);
3415dcd989cbSTejun Heo 
3416dcd989cbSTejun Heo 	if (work_pending(work))
3417dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
3418dcd989cbSTejun Heo 	if (find_worker_executing_work(gcwq, work))
3419dcd989cbSTejun Heo 		ret |= WORK_BUSY_RUNNING;
3420dcd989cbSTejun Heo 
3421dcd989cbSTejun Heo 	spin_unlock_irqrestore(&gcwq->lock, flags);
3422dcd989cbSTejun Heo 
3423dcd989cbSTejun Heo 	return ret;
3424dcd989cbSTejun Heo }
3425dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
3426dcd989cbSTejun Heo 
3427db7bccf4STejun Heo /*
3428db7bccf4STejun Heo  * CPU hotplug.
3429db7bccf4STejun Heo  *
3430e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
3431e22bee78STejun Heo  * are a lot of assumptions on strong associations among work, cwq and
3432e22bee78STejun Heo  * gcwq which make migrating pending and scheduled works very
3433e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
3434e22bee78STejun Heo  * gcwqs serve mix of short, long and very long running works making
3435e22bee78STejun Heo  * blocked draining impractical.
3436e22bee78STejun Heo  *
3437628c78e7STejun Heo  * This is solved by allowing a gcwq to be disassociated from the CPU
3438628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
3439628c78e7STejun Heo  * cpu comes back online.
3440db7bccf4STejun Heo  */
3441db7bccf4STejun Heo 
344260373152STejun Heo /* claim manager positions of all pools */
34438db25e78STejun Heo static void gcwq_claim_management_and_lock(struct global_cwq *gcwq)
344460373152STejun Heo {
344560373152STejun Heo 	struct worker_pool *pool;
344660373152STejun Heo 
344760373152STejun Heo 	for_each_worker_pool(pool, gcwq)
344860373152STejun Heo 		mutex_lock_nested(&pool->manager_mutex, pool - gcwq->pools);
34498db25e78STejun Heo 	spin_lock_irq(&gcwq->lock);
345060373152STejun Heo }
345160373152STejun Heo 
345260373152STejun Heo /* release manager positions */
34538db25e78STejun Heo static void gcwq_release_management_and_unlock(struct global_cwq *gcwq)
345460373152STejun Heo {
345560373152STejun Heo 	struct worker_pool *pool;
345660373152STejun Heo 
34578db25e78STejun Heo 	spin_unlock_irq(&gcwq->lock);
345860373152STejun Heo 	for_each_worker_pool(pool, gcwq)
345960373152STejun Heo 		mutex_unlock(&pool->manager_mutex);
346060373152STejun Heo }
346160373152STejun Heo 
3462628c78e7STejun Heo static void gcwq_unbind_fn(struct work_struct *work)
3463db7bccf4STejun Heo {
3464628c78e7STejun Heo 	struct global_cwq *gcwq = get_gcwq(smp_processor_id());
34654ce62e9eSTejun Heo 	struct worker_pool *pool;
3466db7bccf4STejun Heo 	struct worker *worker;
3467db7bccf4STejun Heo 	struct hlist_node *pos;
3468db7bccf4STejun Heo 	int i;
3469db7bccf4STejun Heo 
3470db7bccf4STejun Heo 	BUG_ON(gcwq->cpu != smp_processor_id());
3471db7bccf4STejun Heo 
34728db25e78STejun Heo 	gcwq_claim_management_and_lock(gcwq);
3473e22bee78STejun Heo 
3474f2d5a0eeSTejun Heo 	/*
3475f2d5a0eeSTejun Heo 	 * We've claimed all manager positions.  Make all workers unbound
3476f2d5a0eeSTejun Heo 	 * and set DISASSOCIATED.  Before this, all workers except for the
3477f2d5a0eeSTejun Heo 	 * ones which are still executing works from before the last CPU
3478f2d5a0eeSTejun Heo 	 * down must be on the cpu.  After this, they may become diasporas.
3479f2d5a0eeSTejun Heo 	 */
348060373152STejun Heo 	for_each_worker_pool(pool, gcwq)
34814ce62e9eSTejun Heo 		list_for_each_entry(worker, &pool->idle_list, entry)
3482403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
3483db7bccf4STejun Heo 
3484db7bccf4STejun Heo 	for_each_busy_worker(worker, i, pos, gcwq)
3485403c821dSTejun Heo 		worker->flags |= WORKER_UNBOUND;
3486db7bccf4STejun Heo 
3487f2d5a0eeSTejun Heo 	gcwq->flags |= GCWQ_DISASSOCIATED;
3488f2d5a0eeSTejun Heo 
34898db25e78STejun Heo 	gcwq_release_management_and_unlock(gcwq);
3490e22bee78STejun Heo 
3491e22bee78STejun Heo 	/*
3492628c78e7STejun Heo 	 * Call schedule() so that we cross rq->lock and thus can guarantee
3493628c78e7STejun Heo 	 * sched callbacks see the %WORKER_UNBOUND flag.  This is necessary
3494628c78e7STejun Heo 	 * as scheduler callbacks may be invoked from other cpus.
3495628c78e7STejun Heo 	 */
3496628c78e7STejun Heo 	schedule();
3497628c78e7STejun Heo 
3498628c78e7STejun Heo 	/*
3499628c78e7STejun Heo 	 * Sched callbacks are disabled now.  Zap nr_running.  After this,
3500628c78e7STejun Heo 	 * nr_running stays zero and need_more_worker() and keep_working()
3501628c78e7STejun Heo 	 * are always true as long as the worklist is not empty.  @gcwq now
3502628c78e7STejun Heo 	 * behaves as unbound (in terms of concurrency management) gcwq
3503628c78e7STejun Heo 	 * which is served by workers tied to the CPU.
3504628c78e7STejun Heo 	 *
3505628c78e7STejun Heo 	 * On return from this function, the current worker would trigger
3506628c78e7STejun Heo 	 * unbound chain execution of pending work items if other workers
3507628c78e7STejun Heo 	 * didn't already.
3508e22bee78STejun Heo 	 */
35094ce62e9eSTejun Heo 	for_each_worker_pool(pool, gcwq)
35104ce62e9eSTejun Heo 		atomic_set(get_pool_nr_running(pool), 0);
3511db7bccf4STejun Heo }
3512db7bccf4STejun Heo 
35138db25e78STejun Heo /*
35148db25e78STejun Heo  * Workqueues should be brought up before normal priority CPU notifiers.
35158db25e78STejun Heo  * This will be registered high priority CPU notifier.
35168db25e78STejun Heo  */
35178db25e78STejun Heo static int __devinit workqueue_cpu_up_callback(struct notifier_block *nfb,
35181da177e4SLinus Torvalds 					       unsigned long action,
35191da177e4SLinus Torvalds 					       void *hcpu)
35201da177e4SLinus Torvalds {
35213af24433SOleg Nesterov 	unsigned int cpu = (unsigned long)hcpu;
3522db7bccf4STejun Heo 	struct global_cwq *gcwq = get_gcwq(cpu);
35234ce62e9eSTejun Heo 	struct worker_pool *pool;
35241da177e4SLinus Torvalds 
35258db25e78STejun Heo 	switch (action & ~CPU_TASKS_FROZEN) {
35263af24433SOleg Nesterov 	case CPU_UP_PREPARE:
35274ce62e9eSTejun Heo 		for_each_worker_pool(pool, gcwq) {
35283ce63377STejun Heo 			struct worker *worker;
35293ce63377STejun Heo 
35303ce63377STejun Heo 			if (pool->nr_workers)
35313ce63377STejun Heo 				continue;
35323ce63377STejun Heo 
35333ce63377STejun Heo 			worker = create_worker(pool);
35343ce63377STejun Heo 			if (!worker)
35353ce63377STejun Heo 				return NOTIFY_BAD;
35363ce63377STejun Heo 
35373ce63377STejun Heo 			spin_lock_irq(&gcwq->lock);
35383ce63377STejun Heo 			start_worker(worker);
35393ce63377STejun Heo 			spin_unlock_irq(&gcwq->lock);
35403af24433SOleg Nesterov 		}
35411da177e4SLinus Torvalds 		break;
35421da177e4SLinus Torvalds 
354365758202STejun Heo 	case CPU_DOWN_FAILED:
354465758202STejun Heo 	case CPU_ONLINE:
35458db25e78STejun Heo 		gcwq_claim_management_and_lock(gcwq);
35468db25e78STejun Heo 		gcwq->flags &= ~GCWQ_DISASSOCIATED;
35478db25e78STejun Heo 		rebind_workers(gcwq);
35488db25e78STejun Heo 		gcwq_release_management_and_unlock(gcwq);
35498db25e78STejun Heo 		break;
355065758202STejun Heo 	}
355165758202STejun Heo 	return NOTIFY_OK;
355265758202STejun Heo }
355365758202STejun Heo 
355465758202STejun Heo /*
355565758202STejun Heo  * Workqueues should be brought down after normal priority CPU notifiers.
355665758202STejun Heo  * This will be registered as low priority CPU notifier.
355765758202STejun Heo  */
355865758202STejun Heo static int __devinit workqueue_cpu_down_callback(struct notifier_block *nfb,
355965758202STejun Heo 						 unsigned long action,
356065758202STejun Heo 						 void *hcpu)
356165758202STejun Heo {
35628db25e78STejun Heo 	unsigned int cpu = (unsigned long)hcpu;
35638db25e78STejun Heo 	struct work_struct unbind_work;
35648db25e78STejun Heo 
356565758202STejun Heo 	switch (action & ~CPU_TASKS_FROZEN) {
356665758202STejun Heo 	case CPU_DOWN_PREPARE:
35678db25e78STejun Heo 		/* unbinding should happen on the local CPU */
35688db25e78STejun Heo 		INIT_WORK_ONSTACK(&unbind_work, gcwq_unbind_fn);
35698db25e78STejun Heo 		schedule_work_on(cpu, &unbind_work);
35708db25e78STejun Heo 		flush_work(&unbind_work);
35718db25e78STejun Heo 		break;
357265758202STejun Heo 	}
357365758202STejun Heo 	return NOTIFY_OK;
357465758202STejun Heo }
357565758202STejun Heo 
35762d3854a3SRusty Russell #ifdef CONFIG_SMP
35778ccad40dSRusty Russell 
35782d3854a3SRusty Russell struct work_for_cpu {
3579*ed48ece2STejun Heo 	struct work_struct work;
35802d3854a3SRusty Russell 	long (*fn)(void *);
35812d3854a3SRusty Russell 	void *arg;
35822d3854a3SRusty Russell 	long ret;
35832d3854a3SRusty Russell };
35842d3854a3SRusty Russell 
3585*ed48ece2STejun Heo static void work_for_cpu_fn(struct work_struct *work)
35862d3854a3SRusty Russell {
3587*ed48ece2STejun Heo 	struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
3588*ed48ece2STejun Heo 
35892d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
35902d3854a3SRusty Russell }
35912d3854a3SRusty Russell 
35922d3854a3SRusty Russell /**
35932d3854a3SRusty Russell  * work_on_cpu - run a function in user context on a particular cpu
35942d3854a3SRusty Russell  * @cpu: the cpu to run on
35952d3854a3SRusty Russell  * @fn: the function to run
35962d3854a3SRusty Russell  * @arg: the function arg
35972d3854a3SRusty Russell  *
359831ad9081SRusty Russell  * This will return the value @fn returns.
359931ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
36006b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
36012d3854a3SRusty Russell  */
36022d3854a3SRusty Russell long work_on_cpu(unsigned int cpu, long (*fn)(void *), void *arg)
36032d3854a3SRusty Russell {
3604*ed48ece2STejun Heo 	struct work_for_cpu wfc = { .fn = fn, .arg = arg };
36052d3854a3SRusty Russell 
3606*ed48ece2STejun Heo 	INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
3607*ed48ece2STejun Heo 	schedule_work_on(cpu, &wfc.work);
3608*ed48ece2STejun Heo 	flush_work(&wfc.work);
36092d3854a3SRusty Russell 	return wfc.ret;
36102d3854a3SRusty Russell }
36112d3854a3SRusty Russell EXPORT_SYMBOL_GPL(work_on_cpu);
36122d3854a3SRusty Russell #endif /* CONFIG_SMP */
36132d3854a3SRusty Russell 
3614a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
3615e7577c50SRusty Russell 
3616a0a1a5fdSTejun Heo /**
3617a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
3618a0a1a5fdSTejun Heo  *
361958a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
362058a69cb4STejun Heo  * workqueues will queue new works to their frozen_works list instead of
362158a69cb4STejun Heo  * gcwq->worklist.
3622a0a1a5fdSTejun Heo  *
3623a0a1a5fdSTejun Heo  * CONTEXT:
36248b03ae3cSTejun Heo  * Grabs and releases workqueue_lock and gcwq->lock's.
3625a0a1a5fdSTejun Heo  */
3626a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
3627a0a1a5fdSTejun Heo {
3628a0a1a5fdSTejun Heo 	unsigned int cpu;
3629a0a1a5fdSTejun Heo 
3630a0a1a5fdSTejun Heo 	spin_lock(&workqueue_lock);
3631a0a1a5fdSTejun Heo 
3632a0a1a5fdSTejun Heo 	BUG_ON(workqueue_freezing);
3633a0a1a5fdSTejun Heo 	workqueue_freezing = true;
3634a0a1a5fdSTejun Heo 
3635f3421797STejun Heo 	for_each_gcwq_cpu(cpu) {
36368b03ae3cSTejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
3637bdbc5dd7STejun Heo 		struct workqueue_struct *wq;
36388b03ae3cSTejun Heo 
36398b03ae3cSTejun Heo 		spin_lock_irq(&gcwq->lock);
36408b03ae3cSTejun Heo 
3641db7bccf4STejun Heo 		BUG_ON(gcwq->flags & GCWQ_FREEZING);
3642db7bccf4STejun Heo 		gcwq->flags |= GCWQ_FREEZING;
3643db7bccf4STejun Heo 
3644a0a1a5fdSTejun Heo 		list_for_each_entry(wq, &workqueues, list) {
3645a0a1a5fdSTejun Heo 			struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3646a0a1a5fdSTejun Heo 
364758a69cb4STejun Heo 			if (cwq && wq->flags & WQ_FREEZABLE)
3648a0a1a5fdSTejun Heo 				cwq->max_active = 0;
36491da177e4SLinus Torvalds 		}
36508b03ae3cSTejun Heo 
36518b03ae3cSTejun Heo 		spin_unlock_irq(&gcwq->lock);
3652a0a1a5fdSTejun Heo 	}
3653a0a1a5fdSTejun Heo 
3654a0a1a5fdSTejun Heo 	spin_unlock(&workqueue_lock);
3655a0a1a5fdSTejun Heo }
3656a0a1a5fdSTejun Heo 
3657a0a1a5fdSTejun Heo /**
365858a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
3659a0a1a5fdSTejun Heo  *
3660a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
3661a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
3662a0a1a5fdSTejun Heo  *
3663a0a1a5fdSTejun Heo  * CONTEXT:
3664a0a1a5fdSTejun Heo  * Grabs and releases workqueue_lock.
3665a0a1a5fdSTejun Heo  *
3666a0a1a5fdSTejun Heo  * RETURNS:
366758a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
366858a69cb4STejun Heo  * is complete.
3669a0a1a5fdSTejun Heo  */
3670a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
3671a0a1a5fdSTejun Heo {
3672a0a1a5fdSTejun Heo 	unsigned int cpu;
3673a0a1a5fdSTejun Heo 	bool busy = false;
3674a0a1a5fdSTejun Heo 
3675a0a1a5fdSTejun Heo 	spin_lock(&workqueue_lock);
3676a0a1a5fdSTejun Heo 
3677a0a1a5fdSTejun Heo 	BUG_ON(!workqueue_freezing);
3678a0a1a5fdSTejun Heo 
3679f3421797STejun Heo 	for_each_gcwq_cpu(cpu) {
3680bdbc5dd7STejun Heo 		struct workqueue_struct *wq;
3681a0a1a5fdSTejun Heo 		/*
3682a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
3683a0a1a5fdSTejun Heo 		 * to peek without lock.
3684a0a1a5fdSTejun Heo 		 */
3685a0a1a5fdSTejun Heo 		list_for_each_entry(wq, &workqueues, list) {
3686a0a1a5fdSTejun Heo 			struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3687a0a1a5fdSTejun Heo 
368858a69cb4STejun Heo 			if (!cwq || !(wq->flags & WQ_FREEZABLE))
3689a0a1a5fdSTejun Heo 				continue;
3690a0a1a5fdSTejun Heo 
3691a0a1a5fdSTejun Heo 			BUG_ON(cwq->nr_active < 0);
3692a0a1a5fdSTejun Heo 			if (cwq->nr_active) {
3693a0a1a5fdSTejun Heo 				busy = true;
3694a0a1a5fdSTejun Heo 				goto out_unlock;
3695a0a1a5fdSTejun Heo 			}
3696a0a1a5fdSTejun Heo 		}
3697a0a1a5fdSTejun Heo 	}
3698a0a1a5fdSTejun Heo out_unlock:
3699a0a1a5fdSTejun Heo 	spin_unlock(&workqueue_lock);
3700a0a1a5fdSTejun Heo 	return busy;
3701a0a1a5fdSTejun Heo }
3702a0a1a5fdSTejun Heo 
3703a0a1a5fdSTejun Heo /**
3704a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
3705a0a1a5fdSTejun Heo  *
3706a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
37077e11629dSTejun Heo  * frozen works are transferred to their respective gcwq worklists.
3708a0a1a5fdSTejun Heo  *
3709a0a1a5fdSTejun Heo  * CONTEXT:
37108b03ae3cSTejun Heo  * Grabs and releases workqueue_lock and gcwq->lock's.
3711a0a1a5fdSTejun Heo  */
3712a0a1a5fdSTejun Heo void thaw_workqueues(void)
3713a0a1a5fdSTejun Heo {
3714a0a1a5fdSTejun Heo 	unsigned int cpu;
3715a0a1a5fdSTejun Heo 
3716a0a1a5fdSTejun Heo 	spin_lock(&workqueue_lock);
3717a0a1a5fdSTejun Heo 
3718a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
3719a0a1a5fdSTejun Heo 		goto out_unlock;
3720a0a1a5fdSTejun Heo 
3721f3421797STejun Heo 	for_each_gcwq_cpu(cpu) {
37228b03ae3cSTejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
37234ce62e9eSTejun Heo 		struct worker_pool *pool;
3724bdbc5dd7STejun Heo 		struct workqueue_struct *wq;
37258b03ae3cSTejun Heo 
37268b03ae3cSTejun Heo 		spin_lock_irq(&gcwq->lock);
37278b03ae3cSTejun Heo 
3728db7bccf4STejun Heo 		BUG_ON(!(gcwq->flags & GCWQ_FREEZING));
3729db7bccf4STejun Heo 		gcwq->flags &= ~GCWQ_FREEZING;
3730db7bccf4STejun Heo 
3731a0a1a5fdSTejun Heo 		list_for_each_entry(wq, &workqueues, list) {
3732a0a1a5fdSTejun Heo 			struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3733a0a1a5fdSTejun Heo 
373458a69cb4STejun Heo 			if (!cwq || !(wq->flags & WQ_FREEZABLE))
3735a0a1a5fdSTejun Heo 				continue;
3736a0a1a5fdSTejun Heo 
3737a0a1a5fdSTejun Heo 			/* restore max_active and repopulate worklist */
3738a0a1a5fdSTejun Heo 			cwq->max_active = wq->saved_max_active;
3739a0a1a5fdSTejun Heo 
3740a0a1a5fdSTejun Heo 			while (!list_empty(&cwq->delayed_works) &&
3741a0a1a5fdSTejun Heo 			       cwq->nr_active < cwq->max_active)
3742a0a1a5fdSTejun Heo 				cwq_activate_first_delayed(cwq);
3743a0a1a5fdSTejun Heo 		}
37448b03ae3cSTejun Heo 
37454ce62e9eSTejun Heo 		for_each_worker_pool(pool, gcwq)
37464ce62e9eSTejun Heo 			wake_up_worker(pool);
3747e22bee78STejun Heo 
37488b03ae3cSTejun Heo 		spin_unlock_irq(&gcwq->lock);
3749a0a1a5fdSTejun Heo 	}
3750a0a1a5fdSTejun Heo 
3751a0a1a5fdSTejun Heo 	workqueue_freezing = false;
3752a0a1a5fdSTejun Heo out_unlock:
3753a0a1a5fdSTejun Heo 	spin_unlock(&workqueue_lock);
3754a0a1a5fdSTejun Heo }
3755a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
3756a0a1a5fdSTejun Heo 
37576ee0578bSSuresh Siddha static int __init init_workqueues(void)
37581da177e4SLinus Torvalds {
3759c34056a3STejun Heo 	unsigned int cpu;
3760c8e55f36STejun Heo 	int i;
3761c34056a3STejun Heo 
376265758202STejun Heo 	cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
376365758202STejun Heo 	cpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
37648b03ae3cSTejun Heo 
37658b03ae3cSTejun Heo 	/* initialize gcwqs */
3766f3421797STejun Heo 	for_each_gcwq_cpu(cpu) {
37678b03ae3cSTejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
37684ce62e9eSTejun Heo 		struct worker_pool *pool;
37698b03ae3cSTejun Heo 
37708b03ae3cSTejun Heo 		spin_lock_init(&gcwq->lock);
37718b03ae3cSTejun Heo 		gcwq->cpu = cpu;
3772f3421797STejun Heo 		gcwq->flags |= GCWQ_DISASSOCIATED;
37738b03ae3cSTejun Heo 
3774c8e55f36STejun Heo 		for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)
3775c8e55f36STejun Heo 			INIT_HLIST_HEAD(&gcwq->busy_hash[i]);
3776c8e55f36STejun Heo 
37774ce62e9eSTejun Heo 		for_each_worker_pool(pool, gcwq) {
37784ce62e9eSTejun Heo 			pool->gcwq = gcwq;
37794ce62e9eSTejun Heo 			INIT_LIST_HEAD(&pool->worklist);
37804ce62e9eSTejun Heo 			INIT_LIST_HEAD(&pool->idle_list);
3781e22bee78STejun Heo 
37824ce62e9eSTejun Heo 			init_timer_deferrable(&pool->idle_timer);
37834ce62e9eSTejun Heo 			pool->idle_timer.function = idle_worker_timeout;
37844ce62e9eSTejun Heo 			pool->idle_timer.data = (unsigned long)pool;
3785e22bee78STejun Heo 
37864ce62e9eSTejun Heo 			setup_timer(&pool->mayday_timer, gcwq_mayday_timeout,
37874ce62e9eSTejun Heo 				    (unsigned long)pool);
37884ce62e9eSTejun Heo 
378960373152STejun Heo 			mutex_init(&pool->manager_mutex);
37904ce62e9eSTejun Heo 			ida_init(&pool->worker_ida);
37914ce62e9eSTejun Heo 		}
3792db7bccf4STejun Heo 
379325511a47STejun Heo 		init_waitqueue_head(&gcwq->rebind_hold);
37948b03ae3cSTejun Heo 	}
37958b03ae3cSTejun Heo 
3796e22bee78STejun Heo 	/* create the initial worker */
3797f3421797STejun Heo 	for_each_online_gcwq_cpu(cpu) {
3798e22bee78STejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
37994ce62e9eSTejun Heo 		struct worker_pool *pool;
3800e22bee78STejun Heo 
3801477a3c33STejun Heo 		if (cpu != WORK_CPU_UNBOUND)
3802477a3c33STejun Heo 			gcwq->flags &= ~GCWQ_DISASSOCIATED;
38034ce62e9eSTejun Heo 
38044ce62e9eSTejun Heo 		for_each_worker_pool(pool, gcwq) {
38054ce62e9eSTejun Heo 			struct worker *worker;
38064ce62e9eSTejun Heo 
3807bc2ae0f5STejun Heo 			worker = create_worker(pool);
3808e22bee78STejun Heo 			BUG_ON(!worker);
3809e22bee78STejun Heo 			spin_lock_irq(&gcwq->lock);
3810e22bee78STejun Heo 			start_worker(worker);
3811e22bee78STejun Heo 			spin_unlock_irq(&gcwq->lock);
3812e22bee78STejun Heo 		}
38134ce62e9eSTejun Heo 	}
3814e22bee78STejun Heo 
3815d320c038STejun Heo 	system_wq = alloc_workqueue("events", 0, 0);
3816d320c038STejun Heo 	system_long_wq = alloc_workqueue("events_long", 0, 0);
3817d320c038STejun Heo 	system_nrt_wq = alloc_workqueue("events_nrt", WQ_NON_REENTRANT, 0);
3818f3421797STejun Heo 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
3819f3421797STejun Heo 					    WQ_UNBOUND_MAX_ACTIVE);
382024d51addSTejun Heo 	system_freezable_wq = alloc_workqueue("events_freezable",
382124d51addSTejun Heo 					      WQ_FREEZABLE, 0);
382262d3c543SAlan Stern 	system_nrt_freezable_wq = alloc_workqueue("events_nrt_freezable",
382362d3c543SAlan Stern 			WQ_NON_REENTRANT | WQ_FREEZABLE, 0);
3824e5cba24eSHitoshi Mitake 	BUG_ON(!system_wq || !system_long_wq || !system_nrt_wq ||
382562d3c543SAlan Stern 	       !system_unbound_wq || !system_freezable_wq ||
382662d3c543SAlan Stern 		!system_nrt_freezable_wq);
38276ee0578bSSuresh Siddha 	return 0;
38281da177e4SLinus Torvalds }
38296ee0578bSSuresh Siddha early_initcall(init_workqueues);
3830