xref: /linux-6.15/kernel/workqueue.c (revision 3ce63377)
11da177e4SLinus Torvalds /*
2c54fce6eSTejun Heo  * kernel/workqueue.c - generic async execution with shared worker pool
31da177e4SLinus Torvalds  *
4c54fce6eSTejun Heo  * Copyright (C) 2002		Ingo Molnar
51da177e4SLinus Torvalds  *
61da177e4SLinus Torvalds  *   Derived from the taskqueue/keventd code by:
71da177e4SLinus Torvalds  *     David Woodhouse <[email protected]>
8e1f8e874SFrancois Cami  *     Andrew Morton
91da177e4SLinus Torvalds  *     Kai Petzke <[email protected]>
101da177e4SLinus Torvalds  *     Theodore Ts'o <[email protected]>
1189ada679SChristoph Lameter  *
12cde53535SChristoph Lameter  * Made to use alloc_percpu by Christoph Lameter.
13c54fce6eSTejun Heo  *
14c54fce6eSTejun Heo  * Copyright (C) 2010		SUSE Linux Products GmbH
15c54fce6eSTejun Heo  * Copyright (C) 2010		Tejun Heo <[email protected]>
16c54fce6eSTejun Heo  *
17c54fce6eSTejun Heo  * This is the generic async execution mechanism.  Work items as are
18c54fce6eSTejun Heo  * executed in process context.  The worker pool is shared and
19c54fce6eSTejun Heo  * automatically managed.  There is one worker pool for each CPU and
20c54fce6eSTejun Heo  * one extra for works which are better served by workers which are
21c54fce6eSTejun Heo  * not bound to any specific CPU.
22c54fce6eSTejun Heo  *
23c54fce6eSTejun Heo  * Please read Documentation/workqueue.txt for details.
241da177e4SLinus Torvalds  */
251da177e4SLinus Torvalds 
269984de1aSPaul Gortmaker #include <linux/export.h>
271da177e4SLinus Torvalds #include <linux/kernel.h>
281da177e4SLinus Torvalds #include <linux/sched.h>
291da177e4SLinus Torvalds #include <linux/init.h>
301da177e4SLinus Torvalds #include <linux/signal.h>
311da177e4SLinus Torvalds #include <linux/completion.h>
321da177e4SLinus Torvalds #include <linux/workqueue.h>
331da177e4SLinus Torvalds #include <linux/slab.h>
341da177e4SLinus Torvalds #include <linux/cpu.h>
351da177e4SLinus Torvalds #include <linux/notifier.h>
361da177e4SLinus Torvalds #include <linux/kthread.h>
371fa44ecaSJames Bottomley #include <linux/hardirq.h>
3846934023SChristoph Lameter #include <linux/mempolicy.h>
39341a5958SRafael J. Wysocki #include <linux/freezer.h>
40d5abe669SPeter Zijlstra #include <linux/kallsyms.h>
41d5abe669SPeter Zijlstra #include <linux/debug_locks.h>
424e6045f1SJohannes Berg #include <linux/lockdep.h>
43c34056a3STejun Heo #include <linux/idr.h>
44e22bee78STejun Heo 
45e22bee78STejun Heo #include "workqueue_sched.h"
461da177e4SLinus Torvalds 
47c8e55f36STejun Heo enum {
48bc2ae0f5STejun Heo 	/*
49bc2ae0f5STejun Heo 	 * global_cwq flags
50bc2ae0f5STejun Heo 	 *
51bc2ae0f5STejun Heo 	 * A bound gcwq is either associated or disassociated with its CPU.
52bc2ae0f5STejun Heo 	 * While associated (!DISASSOCIATED), all workers are bound to the
53bc2ae0f5STejun Heo 	 * CPU and none has %WORKER_UNBOUND set and concurrency management
54bc2ae0f5STejun Heo 	 * is in effect.
55bc2ae0f5STejun Heo 	 *
56bc2ae0f5STejun Heo 	 * While DISASSOCIATED, the cpu may be offline and all workers have
57bc2ae0f5STejun Heo 	 * %WORKER_UNBOUND set and concurrency management disabled, and may
58bc2ae0f5STejun Heo 	 * be executing on any CPU.  The gcwq behaves as an unbound one.
59bc2ae0f5STejun Heo 	 *
60bc2ae0f5STejun Heo 	 * Note that DISASSOCIATED can be flipped only while holding
61bc2ae0f5STejun Heo 	 * managership of all pools on the gcwq to avoid changing binding
62bc2ae0f5STejun Heo 	 * state while create_worker() is in progress.
63bc2ae0f5STejun Heo 	 */
6411ebea50STejun Heo 	GCWQ_DISASSOCIATED	= 1 << 0,	/* cpu can't serve workers */
6511ebea50STejun Heo 	GCWQ_FREEZING		= 1 << 1,	/* freeze in progress */
6611ebea50STejun Heo 
6711ebea50STejun Heo 	/* pool flags */
6811ebea50STejun Heo 	POOL_MANAGE_WORKERS	= 1 << 0,	/* need to manage workers */
69db7bccf4STejun Heo 
70c8e55f36STejun Heo 	/* worker flags */
71c8e55f36STejun Heo 	WORKER_STARTED		= 1 << 0,	/* started */
72c8e55f36STejun Heo 	WORKER_DIE		= 1 << 1,	/* die die die */
73c8e55f36STejun Heo 	WORKER_IDLE		= 1 << 2,	/* is idle */
74e22bee78STejun Heo 	WORKER_PREP		= 1 << 3,	/* preparing to run works */
75e22bee78STejun Heo 	WORKER_REBIND		= 1 << 5,	/* mom is home, come back */
76fb0e7bebSTejun Heo 	WORKER_CPU_INTENSIVE	= 1 << 6,	/* cpu intensive */
77f3421797STejun Heo 	WORKER_UNBOUND		= 1 << 7,	/* worker is unbound */
78e22bee78STejun Heo 
79403c821dSTejun Heo 	WORKER_NOT_RUNNING	= WORKER_PREP | WORKER_REBIND | WORKER_UNBOUND |
80403c821dSTejun Heo 				  WORKER_CPU_INTENSIVE,
81db7bccf4STejun Heo 
82db7bccf4STejun Heo 	/* gcwq->trustee_state */
83db7bccf4STejun Heo 	TRUSTEE_START		= 0,		/* start */
84db7bccf4STejun Heo 	TRUSTEE_IN_CHARGE	= 1,		/* trustee in charge of gcwq */
85db7bccf4STejun Heo 	TRUSTEE_BUTCHER		= 2,		/* butcher workers */
86db7bccf4STejun Heo 	TRUSTEE_RELEASE		= 3,		/* release workers */
87db7bccf4STejun Heo 	TRUSTEE_DONE		= 4,		/* trustee is done */
88c8e55f36STejun Heo 
893270476aSTejun Heo 	NR_WORKER_POOLS		= 2,		/* # worker pools per gcwq */
904ce62e9eSTejun Heo 
91c8e55f36STejun Heo 	BUSY_WORKER_HASH_ORDER	= 6,		/* 64 pointers */
92c8e55f36STejun Heo 	BUSY_WORKER_HASH_SIZE	= 1 << BUSY_WORKER_HASH_ORDER,
93c8e55f36STejun Heo 	BUSY_WORKER_HASH_MASK	= BUSY_WORKER_HASH_SIZE - 1,
94db7bccf4STejun Heo 
95e22bee78STejun Heo 	MAX_IDLE_WORKERS_RATIO	= 4,		/* 1/4 of busy can be idle */
96e22bee78STejun Heo 	IDLE_WORKER_TIMEOUT	= 300 * HZ,	/* keep idle ones for 5 mins */
97e22bee78STejun Heo 
983233cdbdSTejun Heo 	MAYDAY_INITIAL_TIMEOUT  = HZ / 100 >= 2 ? HZ / 100 : 2,
993233cdbdSTejun Heo 						/* call for help after 10ms
1003233cdbdSTejun Heo 						   (min two ticks) */
101e22bee78STejun Heo 	MAYDAY_INTERVAL		= HZ / 10,	/* and then every 100ms */
102e22bee78STejun Heo 	CREATE_COOLDOWN		= HZ,		/* time to breath after fail */
103db7bccf4STejun Heo 	TRUSTEE_COOLDOWN	= HZ / 10,	/* for trustee draining */
1041da177e4SLinus Torvalds 
1051da177e4SLinus Torvalds 	/*
106e22bee78STejun Heo 	 * Rescue workers are used only on emergencies and shared by
107e22bee78STejun Heo 	 * all cpus.  Give -20.
108e22bee78STejun Heo 	 */
109e22bee78STejun Heo 	RESCUER_NICE_LEVEL	= -20,
1103270476aSTejun Heo 	HIGHPRI_NICE_LEVEL	= -20,
111c8e55f36STejun Heo };
112c8e55f36STejun Heo 
1131da177e4SLinus Torvalds /*
1144690c4abSTejun Heo  * Structure fields follow one of the following exclusion rules.
1154690c4abSTejun Heo  *
116e41e704bSTejun Heo  * I: Modifiable by initialization/destruction paths and read-only for
117e41e704bSTejun Heo  *    everyone else.
1184690c4abSTejun Heo  *
119e22bee78STejun Heo  * P: Preemption protected.  Disabling preemption is enough and should
120e22bee78STejun Heo  *    only be modified and accessed from the local cpu.
121e22bee78STejun Heo  *
1228b03ae3cSTejun Heo  * L: gcwq->lock protected.  Access with gcwq->lock held.
1234690c4abSTejun Heo  *
124e22bee78STejun Heo  * X: During normal operation, modification requires gcwq->lock and
125e22bee78STejun Heo  *    should be done only from local cpu.  Either disabling preemption
126e22bee78STejun Heo  *    on local cpu or grabbing gcwq->lock is enough for read access.
127f3421797STejun Heo  *    If GCWQ_DISASSOCIATED is set, it's identical to L.
128e22bee78STejun Heo  *
12973f53c4aSTejun Heo  * F: wq->flush_mutex protected.
13073f53c4aSTejun Heo  *
1314690c4abSTejun Heo  * W: workqueue_lock protected.
1324690c4abSTejun Heo  */
1334690c4abSTejun Heo 
1348b03ae3cSTejun Heo struct global_cwq;
135bd7bdd43STejun Heo struct worker_pool;
13625511a47STejun Heo struct idle_rebind;
137c34056a3STejun Heo 
138e22bee78STejun Heo /*
139e22bee78STejun Heo  * The poor guys doing the actual heavy lifting.  All on-duty workers
140e22bee78STejun Heo  * are either serving the manager role, on idle list or on busy hash.
141e22bee78STejun Heo  */
142c34056a3STejun Heo struct worker {
143c8e55f36STejun Heo 	/* on idle list while idle, on busy hash table while busy */
144c8e55f36STejun Heo 	union {
145c8e55f36STejun Heo 		struct list_head	entry;	/* L: while idle */
146c8e55f36STejun Heo 		struct hlist_node	hentry;	/* L: while busy */
147c8e55f36STejun Heo 	};
148c8e55f36STejun Heo 
149c34056a3STejun Heo 	struct work_struct	*current_work;	/* L: work being processed */
1508cca0eeaSTejun Heo 	struct cpu_workqueue_struct *current_cwq; /* L: current_work's cwq */
151affee4b2STejun Heo 	struct list_head	scheduled;	/* L: scheduled works */
152c34056a3STejun Heo 	struct task_struct	*task;		/* I: worker task */
153bd7bdd43STejun Heo 	struct worker_pool	*pool;		/* I: the associated pool */
154e22bee78STejun Heo 	/* 64 bytes boundary on 64bit, 32 on 32bit */
155e22bee78STejun Heo 	unsigned long		last_active;	/* L: last active timestamp */
156e22bee78STejun Heo 	unsigned int		flags;		/* X: flags */
157c34056a3STejun Heo 	int			id;		/* I: worker id */
15825511a47STejun Heo 
15925511a47STejun Heo 	/* for rebinding worker to CPU */
16025511a47STejun Heo 	struct idle_rebind	*idle_rebind;	/* L: for idle worker */
16125511a47STejun Heo 	struct work_struct	rebind_work;	/* L: for busy worker */
162c34056a3STejun Heo };
163c34056a3STejun Heo 
164bd7bdd43STejun Heo struct worker_pool {
165bd7bdd43STejun Heo 	struct global_cwq	*gcwq;		/* I: the owning gcwq */
16611ebea50STejun Heo 	unsigned int		flags;		/* X: flags */
167bd7bdd43STejun Heo 
168bd7bdd43STejun Heo 	struct list_head	worklist;	/* L: list of pending works */
169bd7bdd43STejun Heo 	int			nr_workers;	/* L: total number of workers */
170bd7bdd43STejun Heo 	int			nr_idle;	/* L: currently idle ones */
171bd7bdd43STejun Heo 
172bd7bdd43STejun Heo 	struct list_head	idle_list;	/* X: list of idle workers */
173bd7bdd43STejun Heo 	struct timer_list	idle_timer;	/* L: worker idle timeout */
174bd7bdd43STejun Heo 	struct timer_list	mayday_timer;	/* L: SOS timer for workers */
175bd7bdd43STejun Heo 
17660373152STejun Heo 	struct mutex		manager_mutex;	/* mutex manager should hold */
177bd7bdd43STejun Heo 	struct ida		worker_ida;	/* L: for worker IDs */
178bd7bdd43STejun Heo };
179bd7bdd43STejun Heo 
1804690c4abSTejun Heo /*
181e22bee78STejun Heo  * Global per-cpu workqueue.  There's one and only one for each cpu
182e22bee78STejun Heo  * and all works are queued and processed here regardless of their
183e22bee78STejun Heo  * target workqueues.
1848b03ae3cSTejun Heo  */
1858b03ae3cSTejun Heo struct global_cwq {
1868b03ae3cSTejun Heo 	spinlock_t		lock;		/* the gcwq lock */
1878b03ae3cSTejun Heo 	unsigned int		cpu;		/* I: the associated cpu */
188db7bccf4STejun Heo 	unsigned int		flags;		/* L: GCWQ_* flags */
189c8e55f36STejun Heo 
190bd7bdd43STejun Heo 	/* workers are chained either in busy_hash or pool idle_list */
191c8e55f36STejun Heo 	struct hlist_head	busy_hash[BUSY_WORKER_HASH_SIZE];
192c8e55f36STejun Heo 						/* L: hash of busy workers */
193c8e55f36STejun Heo 
1943270476aSTejun Heo 	struct worker_pool	pools[2];	/* normal and highpri pools */
195db7bccf4STejun Heo 
19625511a47STejun Heo 	wait_queue_head_t	rebind_hold;	/* rebind hold wait */
19725511a47STejun Heo 
198db7bccf4STejun Heo 	struct task_struct	*trustee;	/* L: for gcwq shutdown */
199db7bccf4STejun Heo 	unsigned int		trustee_state;	/* L: trustee state */
200db7bccf4STejun Heo 	wait_queue_head_t	trustee_wait;	/* trustee wait */
2018b03ae3cSTejun Heo } ____cacheline_aligned_in_smp;
2028b03ae3cSTejun Heo 
2038b03ae3cSTejun Heo /*
204502ca9d8STejun Heo  * The per-CPU workqueue.  The lower WORK_STRUCT_FLAG_BITS of
2050f900049STejun Heo  * work_struct->data are used for flags and thus cwqs need to be
2060f900049STejun Heo  * aligned at two's power of the number of flag bits.
2071da177e4SLinus Torvalds  */
2081da177e4SLinus Torvalds struct cpu_workqueue_struct {
209bd7bdd43STejun Heo 	struct worker_pool	*pool;		/* I: the associated pool */
2104690c4abSTejun Heo 	struct workqueue_struct *wq;		/* I: the owning workqueue */
21173f53c4aSTejun Heo 	int			work_color;	/* L: current color */
21273f53c4aSTejun Heo 	int			flush_color;	/* L: flushing color */
21373f53c4aSTejun Heo 	int			nr_in_flight[WORK_NR_COLORS];
21473f53c4aSTejun Heo 						/* L: nr of in_flight works */
2151e19ffc6STejun Heo 	int			nr_active;	/* L: nr of active works */
216a0a1a5fdSTejun Heo 	int			max_active;	/* L: max active works */
2171e19ffc6STejun Heo 	struct list_head	delayed_works;	/* L: delayed works */
2180f900049STejun Heo };
2191da177e4SLinus Torvalds 
2201da177e4SLinus Torvalds /*
22173f53c4aSTejun Heo  * Structure used to wait for workqueue flush.
22273f53c4aSTejun Heo  */
22373f53c4aSTejun Heo struct wq_flusher {
22473f53c4aSTejun Heo 	struct list_head	list;		/* F: list of flushers */
22573f53c4aSTejun Heo 	int			flush_color;	/* F: flush color waiting for */
22673f53c4aSTejun Heo 	struct completion	done;		/* flush completion */
22773f53c4aSTejun Heo };
2281da177e4SLinus Torvalds 
22973f53c4aSTejun Heo /*
230f2e005aaSTejun Heo  * All cpumasks are assumed to be always set on UP and thus can't be
231f2e005aaSTejun Heo  * used to determine whether there's something to be done.
232f2e005aaSTejun Heo  */
233f2e005aaSTejun Heo #ifdef CONFIG_SMP
234f2e005aaSTejun Heo typedef cpumask_var_t mayday_mask_t;
235f2e005aaSTejun Heo #define mayday_test_and_set_cpu(cpu, mask)	\
236f2e005aaSTejun Heo 	cpumask_test_and_set_cpu((cpu), (mask))
237f2e005aaSTejun Heo #define mayday_clear_cpu(cpu, mask)		cpumask_clear_cpu((cpu), (mask))
238f2e005aaSTejun Heo #define for_each_mayday_cpu(cpu, mask)		for_each_cpu((cpu), (mask))
2399c37547aSTejun Heo #define alloc_mayday_mask(maskp, gfp)		zalloc_cpumask_var((maskp), (gfp))
240f2e005aaSTejun Heo #define free_mayday_mask(mask)			free_cpumask_var((mask))
241f2e005aaSTejun Heo #else
242f2e005aaSTejun Heo typedef unsigned long mayday_mask_t;
243f2e005aaSTejun Heo #define mayday_test_and_set_cpu(cpu, mask)	test_and_set_bit(0, &(mask))
244f2e005aaSTejun Heo #define mayday_clear_cpu(cpu, mask)		clear_bit(0, &(mask))
245f2e005aaSTejun Heo #define for_each_mayday_cpu(cpu, mask)		if ((cpu) = 0, (mask))
246f2e005aaSTejun Heo #define alloc_mayday_mask(maskp, gfp)		true
247f2e005aaSTejun Heo #define free_mayday_mask(mask)			do { } while (0)
248f2e005aaSTejun Heo #endif
2491da177e4SLinus Torvalds 
2501da177e4SLinus Torvalds /*
2511da177e4SLinus Torvalds  * The externally visible workqueue abstraction is an array of
2521da177e4SLinus Torvalds  * per-CPU workqueues:
2531da177e4SLinus Torvalds  */
2541da177e4SLinus Torvalds struct workqueue_struct {
2559c5a2ba7STejun Heo 	unsigned int		flags;		/* W: WQ_* flags */
256bdbc5dd7STejun Heo 	union {
257bdbc5dd7STejun Heo 		struct cpu_workqueue_struct __percpu	*pcpu;
258bdbc5dd7STejun Heo 		struct cpu_workqueue_struct		*single;
259bdbc5dd7STejun Heo 		unsigned long				v;
260bdbc5dd7STejun Heo 	} cpu_wq;				/* I: cwq's */
2614690c4abSTejun Heo 	struct list_head	list;		/* W: list of all workqueues */
26273f53c4aSTejun Heo 
26373f53c4aSTejun Heo 	struct mutex		flush_mutex;	/* protects wq flushing */
26473f53c4aSTejun Heo 	int			work_color;	/* F: current work color */
26573f53c4aSTejun Heo 	int			flush_color;	/* F: current flush color */
26673f53c4aSTejun Heo 	atomic_t		nr_cwqs_to_flush; /* flush in progress */
26773f53c4aSTejun Heo 	struct wq_flusher	*first_flusher;	/* F: first flusher */
26873f53c4aSTejun Heo 	struct list_head	flusher_queue;	/* F: flush waiters */
26973f53c4aSTejun Heo 	struct list_head	flusher_overflow; /* F: flush overflow list */
27073f53c4aSTejun Heo 
271f2e005aaSTejun Heo 	mayday_mask_t		mayday_mask;	/* cpus requesting rescue */
272e22bee78STejun Heo 	struct worker		*rescuer;	/* I: rescue worker */
273e22bee78STejun Heo 
2749c5a2ba7STejun Heo 	int			nr_drainers;	/* W: drain in progress */
275dcd989cbSTejun Heo 	int			saved_max_active; /* W: saved cwq max_active */
2764e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
2774e6045f1SJohannes Berg 	struct lockdep_map	lockdep_map;
2784e6045f1SJohannes Berg #endif
279b196be89STejun Heo 	char			name[];		/* I: workqueue name */
2801da177e4SLinus Torvalds };
2811da177e4SLinus Torvalds 
282d320c038STejun Heo struct workqueue_struct *system_wq __read_mostly;
283d320c038STejun Heo struct workqueue_struct *system_long_wq __read_mostly;
284d320c038STejun Heo struct workqueue_struct *system_nrt_wq __read_mostly;
285f3421797STejun Heo struct workqueue_struct *system_unbound_wq __read_mostly;
28624d51addSTejun Heo struct workqueue_struct *system_freezable_wq __read_mostly;
28762d3c543SAlan Stern struct workqueue_struct *system_nrt_freezable_wq __read_mostly;
288d320c038STejun Heo EXPORT_SYMBOL_GPL(system_wq);
289d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
290d320c038STejun Heo EXPORT_SYMBOL_GPL(system_nrt_wq);
291f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
29224d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
29362d3c543SAlan Stern EXPORT_SYMBOL_GPL(system_nrt_freezable_wq);
294d320c038STejun Heo 
29597bd2347STejun Heo #define CREATE_TRACE_POINTS
29697bd2347STejun Heo #include <trace/events/workqueue.h>
29797bd2347STejun Heo 
2984ce62e9eSTejun Heo #define for_each_worker_pool(pool, gcwq)				\
2993270476aSTejun Heo 	for ((pool) = &(gcwq)->pools[0];				\
3003270476aSTejun Heo 	     (pool) < &(gcwq)->pools[NR_WORKER_POOLS]; (pool)++)
3014ce62e9eSTejun Heo 
302db7bccf4STejun Heo #define for_each_busy_worker(worker, i, pos, gcwq)			\
303db7bccf4STejun Heo 	for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)			\
304db7bccf4STejun Heo 		hlist_for_each_entry(worker, pos, &gcwq->busy_hash[i], hentry)
305db7bccf4STejun Heo 
306f3421797STejun Heo static inline int __next_gcwq_cpu(int cpu, const struct cpumask *mask,
307f3421797STejun Heo 				  unsigned int sw)
308f3421797STejun Heo {
309f3421797STejun Heo 	if (cpu < nr_cpu_ids) {
310f3421797STejun Heo 		if (sw & 1) {
311f3421797STejun Heo 			cpu = cpumask_next(cpu, mask);
312f3421797STejun Heo 			if (cpu < nr_cpu_ids)
313f3421797STejun Heo 				return cpu;
314f3421797STejun Heo 		}
315f3421797STejun Heo 		if (sw & 2)
316f3421797STejun Heo 			return WORK_CPU_UNBOUND;
317f3421797STejun Heo 	}
318f3421797STejun Heo 	return WORK_CPU_NONE;
319f3421797STejun Heo }
320f3421797STejun Heo 
321f3421797STejun Heo static inline int __next_wq_cpu(int cpu, const struct cpumask *mask,
322f3421797STejun Heo 				struct workqueue_struct *wq)
323f3421797STejun Heo {
324f3421797STejun Heo 	return __next_gcwq_cpu(cpu, mask, !(wq->flags & WQ_UNBOUND) ? 1 : 2);
325f3421797STejun Heo }
326f3421797STejun Heo 
32709884951STejun Heo /*
32809884951STejun Heo  * CPU iterators
32909884951STejun Heo  *
33009884951STejun Heo  * An extra gcwq is defined for an invalid cpu number
33109884951STejun Heo  * (WORK_CPU_UNBOUND) to host workqueues which are not bound to any
33209884951STejun Heo  * specific CPU.  The following iterators are similar to
33309884951STejun Heo  * for_each_*_cpu() iterators but also considers the unbound gcwq.
33409884951STejun Heo  *
33509884951STejun Heo  * for_each_gcwq_cpu()		: possible CPUs + WORK_CPU_UNBOUND
33609884951STejun Heo  * for_each_online_gcwq_cpu()	: online CPUs + WORK_CPU_UNBOUND
33709884951STejun Heo  * for_each_cwq_cpu()		: possible CPUs for bound workqueues,
33809884951STejun Heo  *				  WORK_CPU_UNBOUND for unbound workqueues
33909884951STejun Heo  */
340f3421797STejun Heo #define for_each_gcwq_cpu(cpu)						\
341f3421797STejun Heo 	for ((cpu) = __next_gcwq_cpu(-1, cpu_possible_mask, 3);		\
342f3421797STejun Heo 	     (cpu) < WORK_CPU_NONE;					\
343f3421797STejun Heo 	     (cpu) = __next_gcwq_cpu((cpu), cpu_possible_mask, 3))
344f3421797STejun Heo 
345f3421797STejun Heo #define for_each_online_gcwq_cpu(cpu)					\
346f3421797STejun Heo 	for ((cpu) = __next_gcwq_cpu(-1, cpu_online_mask, 3);		\
347f3421797STejun Heo 	     (cpu) < WORK_CPU_NONE;					\
348f3421797STejun Heo 	     (cpu) = __next_gcwq_cpu((cpu), cpu_online_mask, 3))
349f3421797STejun Heo 
350f3421797STejun Heo #define for_each_cwq_cpu(cpu, wq)					\
351f3421797STejun Heo 	for ((cpu) = __next_wq_cpu(-1, cpu_possible_mask, (wq));	\
352f3421797STejun Heo 	     (cpu) < WORK_CPU_NONE;					\
353f3421797STejun Heo 	     (cpu) = __next_wq_cpu((cpu), cpu_possible_mask, (wq)))
354f3421797STejun Heo 
355dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
356dc186ad7SThomas Gleixner 
357dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr;
358dc186ad7SThomas Gleixner 
35999777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
36099777288SStanislaw Gruszka {
36199777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
36299777288SStanislaw Gruszka }
36399777288SStanislaw Gruszka 
364dc186ad7SThomas Gleixner /*
365dc186ad7SThomas Gleixner  * fixup_init is called when:
366dc186ad7SThomas Gleixner  * - an active object is initialized
367dc186ad7SThomas Gleixner  */
368dc186ad7SThomas Gleixner static int work_fixup_init(void *addr, enum debug_obj_state state)
369dc186ad7SThomas Gleixner {
370dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
371dc186ad7SThomas Gleixner 
372dc186ad7SThomas Gleixner 	switch (state) {
373dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
374dc186ad7SThomas Gleixner 		cancel_work_sync(work);
375dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
376dc186ad7SThomas Gleixner 		return 1;
377dc186ad7SThomas Gleixner 	default:
378dc186ad7SThomas Gleixner 		return 0;
379dc186ad7SThomas Gleixner 	}
380dc186ad7SThomas Gleixner }
381dc186ad7SThomas Gleixner 
382dc186ad7SThomas Gleixner /*
383dc186ad7SThomas Gleixner  * fixup_activate is called when:
384dc186ad7SThomas Gleixner  * - an active object is activated
385dc186ad7SThomas Gleixner  * - an unknown object is activated (might be a statically initialized object)
386dc186ad7SThomas Gleixner  */
387dc186ad7SThomas Gleixner static int work_fixup_activate(void *addr, enum debug_obj_state state)
388dc186ad7SThomas Gleixner {
389dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
390dc186ad7SThomas Gleixner 
391dc186ad7SThomas Gleixner 	switch (state) {
392dc186ad7SThomas Gleixner 
393dc186ad7SThomas Gleixner 	case ODEBUG_STATE_NOTAVAILABLE:
394dc186ad7SThomas Gleixner 		/*
395dc186ad7SThomas Gleixner 		 * This is not really a fixup. The work struct was
396dc186ad7SThomas Gleixner 		 * statically initialized. We just make sure that it
397dc186ad7SThomas Gleixner 		 * is tracked in the object tracker.
398dc186ad7SThomas Gleixner 		 */
39922df02bbSTejun Heo 		if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
400dc186ad7SThomas Gleixner 			debug_object_init(work, &work_debug_descr);
401dc186ad7SThomas Gleixner 			debug_object_activate(work, &work_debug_descr);
402dc186ad7SThomas Gleixner 			return 0;
403dc186ad7SThomas Gleixner 		}
404dc186ad7SThomas Gleixner 		WARN_ON_ONCE(1);
405dc186ad7SThomas Gleixner 		return 0;
406dc186ad7SThomas Gleixner 
407dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
408dc186ad7SThomas Gleixner 		WARN_ON(1);
409dc186ad7SThomas Gleixner 
410dc186ad7SThomas Gleixner 	default:
411dc186ad7SThomas Gleixner 		return 0;
412dc186ad7SThomas Gleixner 	}
413dc186ad7SThomas Gleixner }
414dc186ad7SThomas Gleixner 
415dc186ad7SThomas Gleixner /*
416dc186ad7SThomas Gleixner  * fixup_free is called when:
417dc186ad7SThomas Gleixner  * - an active object is freed
418dc186ad7SThomas Gleixner  */
419dc186ad7SThomas Gleixner static int work_fixup_free(void *addr, enum debug_obj_state state)
420dc186ad7SThomas Gleixner {
421dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
422dc186ad7SThomas Gleixner 
423dc186ad7SThomas Gleixner 	switch (state) {
424dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
425dc186ad7SThomas Gleixner 		cancel_work_sync(work);
426dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
427dc186ad7SThomas Gleixner 		return 1;
428dc186ad7SThomas Gleixner 	default:
429dc186ad7SThomas Gleixner 		return 0;
430dc186ad7SThomas Gleixner 	}
431dc186ad7SThomas Gleixner }
432dc186ad7SThomas Gleixner 
433dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr = {
434dc186ad7SThomas Gleixner 	.name		= "work_struct",
43599777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
436dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
437dc186ad7SThomas Gleixner 	.fixup_activate	= work_fixup_activate,
438dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
439dc186ad7SThomas Gleixner };
440dc186ad7SThomas Gleixner 
441dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
442dc186ad7SThomas Gleixner {
443dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
444dc186ad7SThomas Gleixner }
445dc186ad7SThomas Gleixner 
446dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
447dc186ad7SThomas Gleixner {
448dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
449dc186ad7SThomas Gleixner }
450dc186ad7SThomas Gleixner 
451dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
452dc186ad7SThomas Gleixner {
453dc186ad7SThomas Gleixner 	if (onstack)
454dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
455dc186ad7SThomas Gleixner 	else
456dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
457dc186ad7SThomas Gleixner }
458dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
459dc186ad7SThomas Gleixner 
460dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
461dc186ad7SThomas Gleixner {
462dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
463dc186ad7SThomas Gleixner }
464dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
465dc186ad7SThomas Gleixner 
466dc186ad7SThomas Gleixner #else
467dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
468dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
469dc186ad7SThomas Gleixner #endif
470dc186ad7SThomas Gleixner 
47195402b38SGautham R Shenoy /* Serializes the accesses to the list of workqueues. */
47295402b38SGautham R Shenoy static DEFINE_SPINLOCK(workqueue_lock);
4731da177e4SLinus Torvalds static LIST_HEAD(workqueues);
474a0a1a5fdSTejun Heo static bool workqueue_freezing;		/* W: have wqs started freezing? */
4751da177e4SLinus Torvalds 
47614441960SOleg Nesterov /*
477e22bee78STejun Heo  * The almighty global cpu workqueues.  nr_running is the only field
478e22bee78STejun Heo  * which is expected to be used frequently by other cpus via
479e22bee78STejun Heo  * try_to_wake_up().  Put it in a separate cacheline.
48014441960SOleg Nesterov  */
4818b03ae3cSTejun Heo static DEFINE_PER_CPU(struct global_cwq, global_cwq);
4824ce62e9eSTejun Heo static DEFINE_PER_CPU_SHARED_ALIGNED(atomic_t, pool_nr_running[NR_WORKER_POOLS]);
483f756d5e2SNathan Lynch 
484f3421797STejun Heo /*
485f3421797STejun Heo  * Global cpu workqueue and nr_running counter for unbound gcwq.  The
486f3421797STejun Heo  * gcwq is always online, has GCWQ_DISASSOCIATED set, and all its
487f3421797STejun Heo  * workers have WORKER_UNBOUND set.
488f3421797STejun Heo  */
489f3421797STejun Heo static struct global_cwq unbound_global_cwq;
4904ce62e9eSTejun Heo static atomic_t unbound_pool_nr_running[NR_WORKER_POOLS] = {
4914ce62e9eSTejun Heo 	[0 ... NR_WORKER_POOLS - 1]	= ATOMIC_INIT(0),	/* always 0 */
4924ce62e9eSTejun Heo };
493f3421797STejun Heo 
494c34056a3STejun Heo static int worker_thread(void *__worker);
4951da177e4SLinus Torvalds 
4963270476aSTejun Heo static int worker_pool_pri(struct worker_pool *pool)
4973270476aSTejun Heo {
4983270476aSTejun Heo 	return pool - pool->gcwq->pools;
4993270476aSTejun Heo }
5003270476aSTejun Heo 
5018b03ae3cSTejun Heo static struct global_cwq *get_gcwq(unsigned int cpu)
5021da177e4SLinus Torvalds {
503f3421797STejun Heo 	if (cpu != WORK_CPU_UNBOUND)
5048b03ae3cSTejun Heo 		return &per_cpu(global_cwq, cpu);
505f3421797STejun Heo 	else
506f3421797STejun Heo 		return &unbound_global_cwq;
5071da177e4SLinus Torvalds }
5081da177e4SLinus Torvalds 
50963d95a91STejun Heo static atomic_t *get_pool_nr_running(struct worker_pool *pool)
510b1f4ec17SOleg Nesterov {
51163d95a91STejun Heo 	int cpu = pool->gcwq->cpu;
5123270476aSTejun Heo 	int idx = worker_pool_pri(pool);
51363d95a91STejun Heo 
514f3421797STejun Heo 	if (cpu != WORK_CPU_UNBOUND)
5154ce62e9eSTejun Heo 		return &per_cpu(pool_nr_running, cpu)[idx];
516f3421797STejun Heo 	else
5174ce62e9eSTejun Heo 		return &unbound_pool_nr_running[idx];
518b1f4ec17SOleg Nesterov }
519b1f4ec17SOleg Nesterov 
5204690c4abSTejun Heo static struct cpu_workqueue_struct *get_cwq(unsigned int cpu,
5214690c4abSTejun Heo 					    struct workqueue_struct *wq)
522a848e3b6SOleg Nesterov {
523f3421797STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
524e06ffa1eSLai Jiangshan 		if (likely(cpu < nr_cpu_ids))
525bdbc5dd7STejun Heo 			return per_cpu_ptr(wq->cpu_wq.pcpu, cpu);
526f3421797STejun Heo 	} else if (likely(cpu == WORK_CPU_UNBOUND))
527f3421797STejun Heo 		return wq->cpu_wq.single;
528f3421797STejun Heo 	return NULL;
529f3421797STejun Heo }
530a848e3b6SOleg Nesterov 
53173f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
53273f53c4aSTejun Heo {
53373f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
53473f53c4aSTejun Heo }
53573f53c4aSTejun Heo 
53673f53c4aSTejun Heo static int get_work_color(struct work_struct *work)
53773f53c4aSTejun Heo {
53873f53c4aSTejun Heo 	return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
53973f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
54073f53c4aSTejun Heo }
54173f53c4aSTejun Heo 
54273f53c4aSTejun Heo static int work_next_color(int color)
54373f53c4aSTejun Heo {
54473f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
5451da177e4SLinus Torvalds }
5461da177e4SLinus Torvalds 
5474594bf15SDavid Howells /*
548e120153dSTejun Heo  * A work's data points to the cwq with WORK_STRUCT_CWQ set while the
549e120153dSTejun Heo  * work is on queue.  Once execution starts, WORK_STRUCT_CWQ is
550e120153dSTejun Heo  * cleared and the work data contains the cpu number it was last on.
5517a22ad75STejun Heo  *
5527a22ad75STejun Heo  * set_work_{cwq|cpu}() and clear_work_data() can be used to set the
5537a22ad75STejun Heo  * cwq, cpu or clear work->data.  These functions should only be
5547a22ad75STejun Heo  * called while the work is owned - ie. while the PENDING bit is set.
5557a22ad75STejun Heo  *
5567a22ad75STejun Heo  * get_work_[g]cwq() can be used to obtain the gcwq or cwq
5577a22ad75STejun Heo  * corresponding to a work.  gcwq is available once the work has been
5587a22ad75STejun Heo  * queued anywhere after initialization.  cwq is available only from
5597a22ad75STejun Heo  * queueing until execution starts.
5604594bf15SDavid Howells  */
5617a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
5627a22ad75STejun Heo 				 unsigned long flags)
5637a22ad75STejun Heo {
5647a22ad75STejun Heo 	BUG_ON(!work_pending(work));
5657a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
5667a22ad75STejun Heo }
5677a22ad75STejun Heo 
5687a22ad75STejun Heo static void set_work_cwq(struct work_struct *work,
5694690c4abSTejun Heo 			 struct cpu_workqueue_struct *cwq,
5704690c4abSTejun Heo 			 unsigned long extra_flags)
571365970a1SDavid Howells {
5727a22ad75STejun Heo 	set_work_data(work, (unsigned long)cwq,
573e120153dSTejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_CWQ | extra_flags);
574365970a1SDavid Howells }
575365970a1SDavid Howells 
5767a22ad75STejun Heo static void set_work_cpu(struct work_struct *work, unsigned int cpu)
5774d707b9fSOleg Nesterov {
5787a22ad75STejun Heo 	set_work_data(work, cpu << WORK_STRUCT_FLAG_BITS, WORK_STRUCT_PENDING);
5794d707b9fSOleg Nesterov }
5804d707b9fSOleg Nesterov 
5817a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
582365970a1SDavid Howells {
5837a22ad75STejun Heo 	set_work_data(work, WORK_STRUCT_NO_CPU, 0);
5847a22ad75STejun Heo }
5857a22ad75STejun Heo 
5867a22ad75STejun Heo static struct cpu_workqueue_struct *get_work_cwq(struct work_struct *work)
5877a22ad75STejun Heo {
588e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
5897a22ad75STejun Heo 
590e120153dSTejun Heo 	if (data & WORK_STRUCT_CWQ)
591e120153dSTejun Heo 		return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
592e120153dSTejun Heo 	else
593e120153dSTejun Heo 		return NULL;
5947a22ad75STejun Heo }
5957a22ad75STejun Heo 
5967a22ad75STejun Heo static struct global_cwq *get_work_gcwq(struct work_struct *work)
5977a22ad75STejun Heo {
598e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
5997a22ad75STejun Heo 	unsigned int cpu;
6007a22ad75STejun Heo 
601e120153dSTejun Heo 	if (data & WORK_STRUCT_CWQ)
602e120153dSTejun Heo 		return ((struct cpu_workqueue_struct *)
603bd7bdd43STejun Heo 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool->gcwq;
6047a22ad75STejun Heo 
6057a22ad75STejun Heo 	cpu = data >> WORK_STRUCT_FLAG_BITS;
606bdbc5dd7STejun Heo 	if (cpu == WORK_CPU_NONE)
6077a22ad75STejun Heo 		return NULL;
6087a22ad75STejun Heo 
609f3421797STejun Heo 	BUG_ON(cpu >= nr_cpu_ids && cpu != WORK_CPU_UNBOUND);
6107a22ad75STejun Heo 	return get_gcwq(cpu);
611365970a1SDavid Howells }
612365970a1SDavid Howells 
613e22bee78STejun Heo /*
6143270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
6153270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
6163270476aSTejun Heo  * they're being called with gcwq->lock held.
617e22bee78STejun Heo  */
618e22bee78STejun Heo 
61963d95a91STejun Heo static bool __need_more_worker(struct worker_pool *pool)
620649027d7STejun Heo {
6213270476aSTejun Heo 	return !atomic_read(get_pool_nr_running(pool));
622649027d7STejun Heo }
623649027d7STejun Heo 
624e22bee78STejun Heo /*
625e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
626e22bee78STejun Heo  * running workers.
627974271c4STejun Heo  *
628974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
629974271c4STejun Heo  * function will always return %true for unbound gcwq as long as the
630974271c4STejun Heo  * worklist isn't empty.
631e22bee78STejun Heo  */
63263d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
633e22bee78STejun Heo {
63463d95a91STejun Heo 	return !list_empty(&pool->worklist) && __need_more_worker(pool);
635e22bee78STejun Heo }
636e22bee78STejun Heo 
637e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
63863d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
639e22bee78STejun Heo {
64063d95a91STejun Heo 	return pool->nr_idle;
641e22bee78STejun Heo }
642e22bee78STejun Heo 
643e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
64463d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
645e22bee78STejun Heo {
64663d95a91STejun Heo 	atomic_t *nr_running = get_pool_nr_running(pool);
647e22bee78STejun Heo 
6483270476aSTejun Heo 	return !list_empty(&pool->worklist) && atomic_read(nr_running) <= 1;
649e22bee78STejun Heo }
650e22bee78STejun Heo 
651e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
65263d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
653e22bee78STejun Heo {
65463d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
655e22bee78STejun Heo }
656e22bee78STejun Heo 
657e22bee78STejun Heo /* Do I need to be the manager? */
65863d95a91STejun Heo static bool need_to_manage_workers(struct worker_pool *pool)
659e22bee78STejun Heo {
66063d95a91STejun Heo 	return need_to_create_worker(pool) ||
66111ebea50STejun Heo 		(pool->flags & POOL_MANAGE_WORKERS);
662e22bee78STejun Heo }
663e22bee78STejun Heo 
664e22bee78STejun Heo /* Do we have too many workers and should some go away? */
66563d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
666e22bee78STejun Heo {
66760373152STejun Heo 	bool managing = mutex_is_locked(&pool->manager_mutex);
66863d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
66963d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
670e22bee78STejun Heo 
671e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
672e22bee78STejun Heo }
673e22bee78STejun Heo 
674e22bee78STejun Heo /*
675e22bee78STejun Heo  * Wake up functions.
676e22bee78STejun Heo  */
677e22bee78STejun Heo 
6787e11629dSTejun Heo /* Return the first worker.  Safe with preemption disabled */
67963d95a91STejun Heo static struct worker *first_worker(struct worker_pool *pool)
6807e11629dSTejun Heo {
68163d95a91STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
6827e11629dSTejun Heo 		return NULL;
6837e11629dSTejun Heo 
68463d95a91STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
6857e11629dSTejun Heo }
6867e11629dSTejun Heo 
6877e11629dSTejun Heo /**
6887e11629dSTejun Heo  * wake_up_worker - wake up an idle worker
68963d95a91STejun Heo  * @pool: worker pool to wake worker from
6907e11629dSTejun Heo  *
69163d95a91STejun Heo  * Wake up the first idle worker of @pool.
6927e11629dSTejun Heo  *
6937e11629dSTejun Heo  * CONTEXT:
6947e11629dSTejun Heo  * spin_lock_irq(gcwq->lock).
6957e11629dSTejun Heo  */
69663d95a91STejun Heo static void wake_up_worker(struct worker_pool *pool)
6977e11629dSTejun Heo {
69863d95a91STejun Heo 	struct worker *worker = first_worker(pool);
6997e11629dSTejun Heo 
7007e11629dSTejun Heo 	if (likely(worker))
7017e11629dSTejun Heo 		wake_up_process(worker->task);
7027e11629dSTejun Heo }
7037e11629dSTejun Heo 
7044690c4abSTejun Heo /**
705e22bee78STejun Heo  * wq_worker_waking_up - a worker is waking up
706e22bee78STejun Heo  * @task: task waking up
707e22bee78STejun Heo  * @cpu: CPU @task is waking up to
708e22bee78STejun Heo  *
709e22bee78STejun Heo  * This function is called during try_to_wake_up() when a worker is
710e22bee78STejun Heo  * being awoken.
711e22bee78STejun Heo  *
712e22bee78STejun Heo  * CONTEXT:
713e22bee78STejun Heo  * spin_lock_irq(rq->lock)
714e22bee78STejun Heo  */
715e22bee78STejun Heo void wq_worker_waking_up(struct task_struct *task, unsigned int cpu)
716e22bee78STejun Heo {
717e22bee78STejun Heo 	struct worker *worker = kthread_data(task);
718e22bee78STejun Heo 
7192d64672eSSteven Rostedt 	if (!(worker->flags & WORKER_NOT_RUNNING))
72063d95a91STejun Heo 		atomic_inc(get_pool_nr_running(worker->pool));
721e22bee78STejun Heo }
722e22bee78STejun Heo 
723e22bee78STejun Heo /**
724e22bee78STejun Heo  * wq_worker_sleeping - a worker is going to sleep
725e22bee78STejun Heo  * @task: task going to sleep
726e22bee78STejun Heo  * @cpu: CPU in question, must be the current CPU number
727e22bee78STejun Heo  *
728e22bee78STejun Heo  * This function is called during schedule() when a busy worker is
729e22bee78STejun Heo  * going to sleep.  Worker on the same cpu can be woken up by
730e22bee78STejun Heo  * returning pointer to its task.
731e22bee78STejun Heo  *
732e22bee78STejun Heo  * CONTEXT:
733e22bee78STejun Heo  * spin_lock_irq(rq->lock)
734e22bee78STejun Heo  *
735e22bee78STejun Heo  * RETURNS:
736e22bee78STejun Heo  * Worker task on @cpu to wake up, %NULL if none.
737e22bee78STejun Heo  */
738e22bee78STejun Heo struct task_struct *wq_worker_sleeping(struct task_struct *task,
739e22bee78STejun Heo 				       unsigned int cpu)
740e22bee78STejun Heo {
741e22bee78STejun Heo 	struct worker *worker = kthread_data(task), *to_wakeup = NULL;
742bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
74363d95a91STejun Heo 	atomic_t *nr_running = get_pool_nr_running(pool);
744e22bee78STejun Heo 
7452d64672eSSteven Rostedt 	if (worker->flags & WORKER_NOT_RUNNING)
746e22bee78STejun Heo 		return NULL;
747e22bee78STejun Heo 
748e22bee78STejun Heo 	/* this can only happen on the local cpu */
749e22bee78STejun Heo 	BUG_ON(cpu != raw_smp_processor_id());
750e22bee78STejun Heo 
751e22bee78STejun Heo 	/*
752e22bee78STejun Heo 	 * The counterpart of the following dec_and_test, implied mb,
753e22bee78STejun Heo 	 * worklist not empty test sequence is in insert_work().
754e22bee78STejun Heo 	 * Please read comment there.
755e22bee78STejun Heo 	 *
756e22bee78STejun Heo 	 * NOT_RUNNING is clear.  This means that trustee is not in
757e22bee78STejun Heo 	 * charge and we're running on the local cpu w/ rq lock held
758e22bee78STejun Heo 	 * and preemption disabled, which in turn means that none else
759e22bee78STejun Heo 	 * could be manipulating idle_list, so dereferencing idle_list
760e22bee78STejun Heo 	 * without gcwq lock is safe.
761e22bee78STejun Heo 	 */
762bd7bdd43STejun Heo 	if (atomic_dec_and_test(nr_running) && !list_empty(&pool->worklist))
76363d95a91STejun Heo 		to_wakeup = first_worker(pool);
764e22bee78STejun Heo 	return to_wakeup ? to_wakeup->task : NULL;
765e22bee78STejun Heo }
766e22bee78STejun Heo 
767e22bee78STejun Heo /**
768e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
769cb444766STejun Heo  * @worker: self
770d302f017STejun Heo  * @flags: flags to set
771d302f017STejun Heo  * @wakeup: wakeup an idle worker if necessary
772d302f017STejun Heo  *
773e22bee78STejun Heo  * Set @flags in @worker->flags and adjust nr_running accordingly.  If
774e22bee78STejun Heo  * nr_running becomes zero and @wakeup is %true, an idle worker is
775e22bee78STejun Heo  * woken up.
776d302f017STejun Heo  *
777cb444766STejun Heo  * CONTEXT:
778cb444766STejun Heo  * spin_lock_irq(gcwq->lock)
779d302f017STejun Heo  */
780d302f017STejun Heo static inline void worker_set_flags(struct worker *worker, unsigned int flags,
781d302f017STejun Heo 				    bool wakeup)
782d302f017STejun Heo {
783bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
784e22bee78STejun Heo 
785cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
786cb444766STejun Heo 
787e22bee78STejun Heo 	/*
788e22bee78STejun Heo 	 * If transitioning into NOT_RUNNING, adjust nr_running and
789e22bee78STejun Heo 	 * wake up an idle worker as necessary if requested by
790e22bee78STejun Heo 	 * @wakeup.
791e22bee78STejun Heo 	 */
792e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
793e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
79463d95a91STejun Heo 		atomic_t *nr_running = get_pool_nr_running(pool);
795e22bee78STejun Heo 
796e22bee78STejun Heo 		if (wakeup) {
797e22bee78STejun Heo 			if (atomic_dec_and_test(nr_running) &&
798bd7bdd43STejun Heo 			    !list_empty(&pool->worklist))
79963d95a91STejun Heo 				wake_up_worker(pool);
800e22bee78STejun Heo 		} else
801e22bee78STejun Heo 			atomic_dec(nr_running);
802e22bee78STejun Heo 	}
803e22bee78STejun Heo 
804d302f017STejun Heo 	worker->flags |= flags;
805d302f017STejun Heo }
806d302f017STejun Heo 
807d302f017STejun Heo /**
808e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
809cb444766STejun Heo  * @worker: self
810d302f017STejun Heo  * @flags: flags to clear
811d302f017STejun Heo  *
812e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
813d302f017STejun Heo  *
814cb444766STejun Heo  * CONTEXT:
815cb444766STejun Heo  * spin_lock_irq(gcwq->lock)
816d302f017STejun Heo  */
817d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
818d302f017STejun Heo {
81963d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
820e22bee78STejun Heo 	unsigned int oflags = worker->flags;
821e22bee78STejun Heo 
822cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
823cb444766STejun Heo 
824d302f017STejun Heo 	worker->flags &= ~flags;
825e22bee78STejun Heo 
82642c025f3STejun Heo 	/*
82742c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
82842c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
82942c025f3STejun Heo 	 * of multiple flags, not a single flag.
83042c025f3STejun Heo 	 */
831e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
832e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
83363d95a91STejun Heo 			atomic_inc(get_pool_nr_running(pool));
834d302f017STejun Heo }
835d302f017STejun Heo 
836d302f017STejun Heo /**
837c8e55f36STejun Heo  * busy_worker_head - return the busy hash head for a work
838c8e55f36STejun Heo  * @gcwq: gcwq of interest
839c8e55f36STejun Heo  * @work: work to be hashed
840c8e55f36STejun Heo  *
841c8e55f36STejun Heo  * Return hash head of @gcwq for @work.
842c8e55f36STejun Heo  *
843c8e55f36STejun Heo  * CONTEXT:
844c8e55f36STejun Heo  * spin_lock_irq(gcwq->lock).
845c8e55f36STejun Heo  *
846c8e55f36STejun Heo  * RETURNS:
847c8e55f36STejun Heo  * Pointer to the hash head.
848c8e55f36STejun Heo  */
849c8e55f36STejun Heo static struct hlist_head *busy_worker_head(struct global_cwq *gcwq,
850c8e55f36STejun Heo 					   struct work_struct *work)
851c8e55f36STejun Heo {
852c8e55f36STejun Heo 	const int base_shift = ilog2(sizeof(struct work_struct));
853c8e55f36STejun Heo 	unsigned long v = (unsigned long)work;
854c8e55f36STejun Heo 
855c8e55f36STejun Heo 	/* simple shift and fold hash, do we need something better? */
856c8e55f36STejun Heo 	v >>= base_shift;
857c8e55f36STejun Heo 	v += v >> BUSY_WORKER_HASH_ORDER;
858c8e55f36STejun Heo 	v &= BUSY_WORKER_HASH_MASK;
859c8e55f36STejun Heo 
860c8e55f36STejun Heo 	return &gcwq->busy_hash[v];
861c8e55f36STejun Heo }
862c8e55f36STejun Heo 
863c8e55f36STejun Heo /**
8648cca0eeaSTejun Heo  * __find_worker_executing_work - find worker which is executing a work
8658cca0eeaSTejun Heo  * @gcwq: gcwq of interest
8668cca0eeaSTejun Heo  * @bwh: hash head as returned by busy_worker_head()
8678cca0eeaSTejun Heo  * @work: work to find worker for
8688cca0eeaSTejun Heo  *
8698cca0eeaSTejun Heo  * Find a worker which is executing @work on @gcwq.  @bwh should be
8708cca0eeaSTejun Heo  * the hash head obtained by calling busy_worker_head() with the same
8718cca0eeaSTejun Heo  * work.
8728cca0eeaSTejun Heo  *
8738cca0eeaSTejun Heo  * CONTEXT:
8748cca0eeaSTejun Heo  * spin_lock_irq(gcwq->lock).
8758cca0eeaSTejun Heo  *
8768cca0eeaSTejun Heo  * RETURNS:
8778cca0eeaSTejun Heo  * Pointer to worker which is executing @work if found, NULL
8788cca0eeaSTejun Heo  * otherwise.
8798cca0eeaSTejun Heo  */
8808cca0eeaSTejun Heo static struct worker *__find_worker_executing_work(struct global_cwq *gcwq,
8818cca0eeaSTejun Heo 						   struct hlist_head *bwh,
8828cca0eeaSTejun Heo 						   struct work_struct *work)
8838cca0eeaSTejun Heo {
8848cca0eeaSTejun Heo 	struct worker *worker;
8858cca0eeaSTejun Heo 	struct hlist_node *tmp;
8868cca0eeaSTejun Heo 
8878cca0eeaSTejun Heo 	hlist_for_each_entry(worker, tmp, bwh, hentry)
8888cca0eeaSTejun Heo 		if (worker->current_work == work)
8898cca0eeaSTejun Heo 			return worker;
8908cca0eeaSTejun Heo 	return NULL;
8918cca0eeaSTejun Heo }
8928cca0eeaSTejun Heo 
8938cca0eeaSTejun Heo /**
8948cca0eeaSTejun Heo  * find_worker_executing_work - find worker which is executing a work
8958cca0eeaSTejun Heo  * @gcwq: gcwq of interest
8968cca0eeaSTejun Heo  * @work: work to find worker for
8978cca0eeaSTejun Heo  *
8988cca0eeaSTejun Heo  * Find a worker which is executing @work on @gcwq.  This function is
8998cca0eeaSTejun Heo  * identical to __find_worker_executing_work() except that this
9008cca0eeaSTejun Heo  * function calculates @bwh itself.
9018cca0eeaSTejun Heo  *
9028cca0eeaSTejun Heo  * CONTEXT:
9038cca0eeaSTejun Heo  * spin_lock_irq(gcwq->lock).
9048cca0eeaSTejun Heo  *
9058cca0eeaSTejun Heo  * RETURNS:
9068cca0eeaSTejun Heo  * Pointer to worker which is executing @work if found, NULL
9078cca0eeaSTejun Heo  * otherwise.
9088cca0eeaSTejun Heo  */
9098cca0eeaSTejun Heo static struct worker *find_worker_executing_work(struct global_cwq *gcwq,
9108cca0eeaSTejun Heo 						 struct work_struct *work)
9118cca0eeaSTejun Heo {
9128cca0eeaSTejun Heo 	return __find_worker_executing_work(gcwq, busy_worker_head(gcwq, work),
9138cca0eeaSTejun Heo 					    work);
9148cca0eeaSTejun Heo }
9158cca0eeaSTejun Heo 
9168cca0eeaSTejun Heo /**
9177e11629dSTejun Heo  * insert_work - insert a work into gcwq
9184690c4abSTejun Heo  * @cwq: cwq @work belongs to
9194690c4abSTejun Heo  * @work: work to insert
9204690c4abSTejun Heo  * @head: insertion point
9214690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
9224690c4abSTejun Heo  *
9237e11629dSTejun Heo  * Insert @work which belongs to @cwq into @gcwq after @head.
9247e11629dSTejun Heo  * @extra_flags is or'd to work_struct flags.
9254690c4abSTejun Heo  *
9264690c4abSTejun Heo  * CONTEXT:
9278b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock).
9281da177e4SLinus Torvalds  */
929b89deed3SOleg Nesterov static void insert_work(struct cpu_workqueue_struct *cwq,
9304690c4abSTejun Heo 			struct work_struct *work, struct list_head *head,
9314690c4abSTejun Heo 			unsigned int extra_flags)
932b89deed3SOleg Nesterov {
93363d95a91STejun Heo 	struct worker_pool *pool = cwq->pool;
934e1d8aa9fSFrederic Weisbecker 
9354690c4abSTejun Heo 	/* we own @work, set data and link */
9367a22ad75STejun Heo 	set_work_cwq(work, cwq, extra_flags);
9374690c4abSTejun Heo 
9386e84d644SOleg Nesterov 	/*
9396e84d644SOleg Nesterov 	 * Ensure that we get the right work->data if we see the
9406e84d644SOleg Nesterov 	 * result of list_add() below, see try_to_grab_pending().
9416e84d644SOleg Nesterov 	 */
9426e84d644SOleg Nesterov 	smp_wmb();
9434690c4abSTejun Heo 
9441a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
945e22bee78STejun Heo 
946e22bee78STejun Heo 	/*
947e22bee78STejun Heo 	 * Ensure either worker_sched_deactivated() sees the above
948e22bee78STejun Heo 	 * list_add_tail() or we see zero nr_running to avoid workers
949e22bee78STejun Heo 	 * lying around lazily while there are works to be processed.
950e22bee78STejun Heo 	 */
951e22bee78STejun Heo 	smp_mb();
952e22bee78STejun Heo 
95363d95a91STejun Heo 	if (__need_more_worker(pool))
95463d95a91STejun Heo 		wake_up_worker(pool);
955b89deed3SOleg Nesterov }
956b89deed3SOleg Nesterov 
957c8efcc25STejun Heo /*
958c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
959c8efcc25STejun Heo  * same workqueue.  This is rather expensive and should only be used from
960c8efcc25STejun Heo  * cold paths.
961c8efcc25STejun Heo  */
962c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
963c8efcc25STejun Heo {
964c8efcc25STejun Heo 	unsigned long flags;
965c8efcc25STejun Heo 	unsigned int cpu;
966c8efcc25STejun Heo 
967c8efcc25STejun Heo 	for_each_gcwq_cpu(cpu) {
968c8efcc25STejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
969c8efcc25STejun Heo 		struct worker *worker;
970c8efcc25STejun Heo 		struct hlist_node *pos;
971c8efcc25STejun Heo 		int i;
972c8efcc25STejun Heo 
973c8efcc25STejun Heo 		spin_lock_irqsave(&gcwq->lock, flags);
974c8efcc25STejun Heo 		for_each_busy_worker(worker, i, pos, gcwq) {
975c8efcc25STejun Heo 			if (worker->task != current)
976c8efcc25STejun Heo 				continue;
977c8efcc25STejun Heo 			spin_unlock_irqrestore(&gcwq->lock, flags);
978c8efcc25STejun Heo 			/*
979c8efcc25STejun Heo 			 * I'm @worker, no locking necessary.  See if @work
980c8efcc25STejun Heo 			 * is headed to the same workqueue.
981c8efcc25STejun Heo 			 */
982c8efcc25STejun Heo 			return worker->current_cwq->wq == wq;
983c8efcc25STejun Heo 		}
984c8efcc25STejun Heo 		spin_unlock_irqrestore(&gcwq->lock, flags);
985c8efcc25STejun Heo 	}
986c8efcc25STejun Heo 	return false;
987c8efcc25STejun Heo }
988c8efcc25STejun Heo 
9894690c4abSTejun Heo static void __queue_work(unsigned int cpu, struct workqueue_struct *wq,
9901da177e4SLinus Torvalds 			 struct work_struct *work)
9911da177e4SLinus Torvalds {
992502ca9d8STejun Heo 	struct global_cwq *gcwq;
993502ca9d8STejun Heo 	struct cpu_workqueue_struct *cwq;
9941e19ffc6STejun Heo 	struct list_head *worklist;
9958a2e8e5dSTejun Heo 	unsigned int work_flags;
9961da177e4SLinus Torvalds 	unsigned long flags;
9971da177e4SLinus Torvalds 
998dc186ad7SThomas Gleixner 	debug_work_activate(work);
9991e19ffc6STejun Heo 
1000c8efcc25STejun Heo 	/* if dying, only works from the same workqueue are allowed */
10019c5a2ba7STejun Heo 	if (unlikely(wq->flags & WQ_DRAINING) &&
1002c8efcc25STejun Heo 	    WARN_ON_ONCE(!is_chained_work(wq)))
1003e41e704bSTejun Heo 		return;
1004e41e704bSTejun Heo 
1005c7fc77f7STejun Heo 	/* determine gcwq to use */
1006c7fc77f7STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
1007c7fc77f7STejun Heo 		struct global_cwq *last_gcwq;
1008c7fc77f7STejun Heo 
1009f3421797STejun Heo 		if (unlikely(cpu == WORK_CPU_UNBOUND))
1010f3421797STejun Heo 			cpu = raw_smp_processor_id();
1011f3421797STejun Heo 
101218aa9effSTejun Heo 		/*
101318aa9effSTejun Heo 		 * It's multi cpu.  If @wq is non-reentrant and @work
101418aa9effSTejun Heo 		 * was previously on a different cpu, it might still
101518aa9effSTejun Heo 		 * be running there, in which case the work needs to
101618aa9effSTejun Heo 		 * be queued on that cpu to guarantee non-reentrance.
101718aa9effSTejun Heo 		 */
1018502ca9d8STejun Heo 		gcwq = get_gcwq(cpu);
101918aa9effSTejun Heo 		if (wq->flags & WQ_NON_REENTRANT &&
102018aa9effSTejun Heo 		    (last_gcwq = get_work_gcwq(work)) && last_gcwq != gcwq) {
102118aa9effSTejun Heo 			struct worker *worker;
102218aa9effSTejun Heo 
102318aa9effSTejun Heo 			spin_lock_irqsave(&last_gcwq->lock, flags);
102418aa9effSTejun Heo 
102518aa9effSTejun Heo 			worker = find_worker_executing_work(last_gcwq, work);
102618aa9effSTejun Heo 
102718aa9effSTejun Heo 			if (worker && worker->current_cwq->wq == wq)
102818aa9effSTejun Heo 				gcwq = last_gcwq;
102918aa9effSTejun Heo 			else {
103018aa9effSTejun Heo 				/* meh... not running there, queue here */
103118aa9effSTejun Heo 				spin_unlock_irqrestore(&last_gcwq->lock, flags);
103218aa9effSTejun Heo 				spin_lock_irqsave(&gcwq->lock, flags);
103318aa9effSTejun Heo 			}
103418aa9effSTejun Heo 		} else
10358b03ae3cSTejun Heo 			spin_lock_irqsave(&gcwq->lock, flags);
1036f3421797STejun Heo 	} else {
1037f3421797STejun Heo 		gcwq = get_gcwq(WORK_CPU_UNBOUND);
1038f3421797STejun Heo 		spin_lock_irqsave(&gcwq->lock, flags);
1039502ca9d8STejun Heo 	}
1040502ca9d8STejun Heo 
1041502ca9d8STejun Heo 	/* gcwq determined, get cwq and queue */
1042502ca9d8STejun Heo 	cwq = get_cwq(gcwq->cpu, wq);
1043cdadf009STejun Heo 	trace_workqueue_queue_work(cpu, cwq, work);
1044502ca9d8STejun Heo 
1045f5b2552bSDan Carpenter 	if (WARN_ON(!list_empty(&work->entry))) {
1046f5b2552bSDan Carpenter 		spin_unlock_irqrestore(&gcwq->lock, flags);
1047f5b2552bSDan Carpenter 		return;
1048f5b2552bSDan Carpenter 	}
10491e19ffc6STejun Heo 
105073f53c4aSTejun Heo 	cwq->nr_in_flight[cwq->work_color]++;
10518a2e8e5dSTejun Heo 	work_flags = work_color_to_flags(cwq->work_color);
10521e19ffc6STejun Heo 
10531e19ffc6STejun Heo 	if (likely(cwq->nr_active < cwq->max_active)) {
1054cdadf009STejun Heo 		trace_workqueue_activate_work(work);
10551e19ffc6STejun Heo 		cwq->nr_active++;
10563270476aSTejun Heo 		worklist = &cwq->pool->worklist;
10578a2e8e5dSTejun Heo 	} else {
10588a2e8e5dSTejun Heo 		work_flags |= WORK_STRUCT_DELAYED;
10591e19ffc6STejun Heo 		worklist = &cwq->delayed_works;
10608a2e8e5dSTejun Heo 	}
10611e19ffc6STejun Heo 
10628a2e8e5dSTejun Heo 	insert_work(cwq, work, worklist, work_flags);
10631e19ffc6STejun Heo 
10648b03ae3cSTejun Heo 	spin_unlock_irqrestore(&gcwq->lock, flags);
10651da177e4SLinus Torvalds }
10661da177e4SLinus Torvalds 
10670fcb78c2SRolf Eike Beer /**
10680fcb78c2SRolf Eike Beer  * queue_work - queue work on a workqueue
10690fcb78c2SRolf Eike Beer  * @wq: workqueue to use
10700fcb78c2SRolf Eike Beer  * @work: work to queue
10710fcb78c2SRolf Eike Beer  *
1072057647fcSAlan Stern  * Returns 0 if @work was already on a queue, non-zero otherwise.
10731da177e4SLinus Torvalds  *
107400dfcaf7SOleg Nesterov  * We queue the work to the CPU on which it was submitted, but if the CPU dies
107500dfcaf7SOleg Nesterov  * it can be processed by another CPU.
10761da177e4SLinus Torvalds  */
10777ad5b3a5SHarvey Harrison int queue_work(struct workqueue_struct *wq, struct work_struct *work)
10781da177e4SLinus Torvalds {
1079ef1ca236SOleg Nesterov 	int ret;
10801da177e4SLinus Torvalds 
1081ef1ca236SOleg Nesterov 	ret = queue_work_on(get_cpu(), wq, work);
1082a848e3b6SOleg Nesterov 	put_cpu();
1083ef1ca236SOleg Nesterov 
10841da177e4SLinus Torvalds 	return ret;
10851da177e4SLinus Torvalds }
1086ae90dd5dSDave Jones EXPORT_SYMBOL_GPL(queue_work);
10871da177e4SLinus Torvalds 
1088c1a220e7SZhang Rui /**
1089c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
1090c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
1091c1a220e7SZhang Rui  * @wq: workqueue to use
1092c1a220e7SZhang Rui  * @work: work to queue
1093c1a220e7SZhang Rui  *
1094c1a220e7SZhang Rui  * Returns 0 if @work was already on a queue, non-zero otherwise.
1095c1a220e7SZhang Rui  *
1096c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
1097c1a220e7SZhang Rui  * can't go away.
1098c1a220e7SZhang Rui  */
1099c1a220e7SZhang Rui int
1100c1a220e7SZhang Rui queue_work_on(int cpu, struct workqueue_struct *wq, struct work_struct *work)
1101c1a220e7SZhang Rui {
1102c1a220e7SZhang Rui 	int ret = 0;
1103c1a220e7SZhang Rui 
110422df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
11054690c4abSTejun Heo 		__queue_work(cpu, wq, work);
1106c1a220e7SZhang Rui 		ret = 1;
1107c1a220e7SZhang Rui 	}
1108c1a220e7SZhang Rui 	return ret;
1109c1a220e7SZhang Rui }
1110c1a220e7SZhang Rui EXPORT_SYMBOL_GPL(queue_work_on);
1111c1a220e7SZhang Rui 
11126d141c3fSLi Zefan static void delayed_work_timer_fn(unsigned long __data)
11131da177e4SLinus Torvalds {
111452bad64dSDavid Howells 	struct delayed_work *dwork = (struct delayed_work *)__data;
11157a22ad75STejun Heo 	struct cpu_workqueue_struct *cwq = get_work_cwq(&dwork->work);
11161da177e4SLinus Torvalds 
11174690c4abSTejun Heo 	__queue_work(smp_processor_id(), cwq->wq, &dwork->work);
11181da177e4SLinus Torvalds }
11191da177e4SLinus Torvalds 
11200fcb78c2SRolf Eike Beer /**
11210fcb78c2SRolf Eike Beer  * queue_delayed_work - queue work on a workqueue after delay
11220fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1123af9997e4SRandy Dunlap  * @dwork: delayable work to queue
11240fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
11250fcb78c2SRolf Eike Beer  *
1126057647fcSAlan Stern  * Returns 0 if @work was already on a queue, non-zero otherwise.
11270fcb78c2SRolf Eike Beer  */
11287ad5b3a5SHarvey Harrison int queue_delayed_work(struct workqueue_struct *wq,
112952bad64dSDavid Howells 			struct delayed_work *dwork, unsigned long delay)
11301da177e4SLinus Torvalds {
113152bad64dSDavid Howells 	if (delay == 0)
113263bc0362SOleg Nesterov 		return queue_work(wq, &dwork->work);
11331da177e4SLinus Torvalds 
113463bc0362SOleg Nesterov 	return queue_delayed_work_on(-1, wq, dwork, delay);
11351da177e4SLinus Torvalds }
1136ae90dd5dSDave Jones EXPORT_SYMBOL_GPL(queue_delayed_work);
11371da177e4SLinus Torvalds 
11380fcb78c2SRolf Eike Beer /**
11390fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
11400fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
11410fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1142af9997e4SRandy Dunlap  * @dwork: work to queue
11430fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
11440fcb78c2SRolf Eike Beer  *
1145057647fcSAlan Stern  * Returns 0 if @work was already on a queue, non-zero otherwise.
11460fcb78c2SRolf Eike Beer  */
11477a6bc1cdSVenkatesh Pallipadi int queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
114852bad64dSDavid Howells 			struct delayed_work *dwork, unsigned long delay)
11497a6bc1cdSVenkatesh Pallipadi {
11507a6bc1cdSVenkatesh Pallipadi 	int ret = 0;
115152bad64dSDavid Howells 	struct timer_list *timer = &dwork->timer;
115252bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
11537a6bc1cdSVenkatesh Pallipadi 
115422df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1155c7fc77f7STejun Heo 		unsigned int lcpu;
11567a22ad75STejun Heo 
11577a6bc1cdSVenkatesh Pallipadi 		BUG_ON(timer_pending(timer));
11587a6bc1cdSVenkatesh Pallipadi 		BUG_ON(!list_empty(&work->entry));
11597a6bc1cdSVenkatesh Pallipadi 
11608a3e77ccSAndrew Liu 		timer_stats_timer_set_start_info(&dwork->timer);
11618a3e77ccSAndrew Liu 
11627a22ad75STejun Heo 		/*
11637a22ad75STejun Heo 		 * This stores cwq for the moment, for the timer_fn.
11647a22ad75STejun Heo 		 * Note that the work's gcwq is preserved to allow
11657a22ad75STejun Heo 		 * reentrance detection for delayed works.
11667a22ad75STejun Heo 		 */
1167c7fc77f7STejun Heo 		if (!(wq->flags & WQ_UNBOUND)) {
1168c7fc77f7STejun Heo 			struct global_cwq *gcwq = get_work_gcwq(work);
1169c7fc77f7STejun Heo 
1170c7fc77f7STejun Heo 			if (gcwq && gcwq->cpu != WORK_CPU_UNBOUND)
1171c7fc77f7STejun Heo 				lcpu = gcwq->cpu;
1172c7fc77f7STejun Heo 			else
1173c7fc77f7STejun Heo 				lcpu = raw_smp_processor_id();
1174c7fc77f7STejun Heo 		} else
1175c7fc77f7STejun Heo 			lcpu = WORK_CPU_UNBOUND;
1176c7fc77f7STejun Heo 
11777a22ad75STejun Heo 		set_work_cwq(work, get_cwq(lcpu, wq), 0);
1178c7fc77f7STejun Heo 
11797a6bc1cdSVenkatesh Pallipadi 		timer->expires = jiffies + delay;
118052bad64dSDavid Howells 		timer->data = (unsigned long)dwork;
11817a6bc1cdSVenkatesh Pallipadi 		timer->function = delayed_work_timer_fn;
118263bc0362SOleg Nesterov 
118363bc0362SOleg Nesterov 		if (unlikely(cpu >= 0))
11847a6bc1cdSVenkatesh Pallipadi 			add_timer_on(timer, cpu);
118563bc0362SOleg Nesterov 		else
118663bc0362SOleg Nesterov 			add_timer(timer);
11877a6bc1cdSVenkatesh Pallipadi 		ret = 1;
11887a6bc1cdSVenkatesh Pallipadi 	}
11897a6bc1cdSVenkatesh Pallipadi 	return ret;
11907a6bc1cdSVenkatesh Pallipadi }
1191ae90dd5dSDave Jones EXPORT_SYMBOL_GPL(queue_delayed_work_on);
11921da177e4SLinus Torvalds 
1193c8e55f36STejun Heo /**
1194c8e55f36STejun Heo  * worker_enter_idle - enter idle state
1195c8e55f36STejun Heo  * @worker: worker which is entering idle state
1196c8e55f36STejun Heo  *
1197c8e55f36STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
1198c8e55f36STejun Heo  * necessary.
1199c8e55f36STejun Heo  *
1200c8e55f36STejun Heo  * LOCKING:
1201c8e55f36STejun Heo  * spin_lock_irq(gcwq->lock).
1202c8e55f36STejun Heo  */
1203c8e55f36STejun Heo static void worker_enter_idle(struct worker *worker)
12041da177e4SLinus Torvalds {
1205bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1206bd7bdd43STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
1207c8e55f36STejun Heo 
1208c8e55f36STejun Heo 	BUG_ON(worker->flags & WORKER_IDLE);
1209c8e55f36STejun Heo 	BUG_ON(!list_empty(&worker->entry) &&
1210c8e55f36STejun Heo 	       (worker->hentry.next || worker->hentry.pprev));
1211c8e55f36STejun Heo 
1212cb444766STejun Heo 	/* can't use worker_set_flags(), also called from start_worker() */
1213cb444766STejun Heo 	worker->flags |= WORKER_IDLE;
1214bd7bdd43STejun Heo 	pool->nr_idle++;
1215e22bee78STejun Heo 	worker->last_active = jiffies;
1216c8e55f36STejun Heo 
1217c8e55f36STejun Heo 	/* idle_list is LIFO */
1218bd7bdd43STejun Heo 	list_add(&worker->entry, &pool->idle_list);
1219db7bccf4STejun Heo 
1220403c821dSTejun Heo 	if (likely(gcwq->trustee_state != TRUSTEE_DONE)) {
122163d95a91STejun Heo 		if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1222bd7bdd43STejun Heo 			mod_timer(&pool->idle_timer,
1223e22bee78STejun Heo 				  jiffies + IDLE_WORKER_TIMEOUT);
1224e22bee78STejun Heo 	} else
1225db7bccf4STejun Heo 		wake_up_all(&gcwq->trustee_wait);
1226cb444766STejun Heo 
1227544ecf31STejun Heo 	/*
1228544ecf31STejun Heo 	 * Sanity check nr_running.  Because trustee releases gcwq->lock
1229403c821dSTejun Heo 	 * between setting %WORKER_UNBOUND and zapping nr_running, the
1230544ecf31STejun Heo 	 * warning may trigger spuriously.  Check iff trustee is idle.
1231544ecf31STejun Heo 	 */
1232544ecf31STejun Heo 	WARN_ON_ONCE(gcwq->trustee_state == TRUSTEE_DONE &&
1233bd7bdd43STejun Heo 		     pool->nr_workers == pool->nr_idle &&
123463d95a91STejun Heo 		     atomic_read(get_pool_nr_running(pool)));
1235c8e55f36STejun Heo }
1236c8e55f36STejun Heo 
1237c8e55f36STejun Heo /**
1238c8e55f36STejun Heo  * worker_leave_idle - leave idle state
1239c8e55f36STejun Heo  * @worker: worker which is leaving idle state
1240c8e55f36STejun Heo  *
1241c8e55f36STejun Heo  * @worker is leaving idle state.  Update stats.
1242c8e55f36STejun Heo  *
1243c8e55f36STejun Heo  * LOCKING:
1244c8e55f36STejun Heo  * spin_lock_irq(gcwq->lock).
1245c8e55f36STejun Heo  */
1246c8e55f36STejun Heo static void worker_leave_idle(struct worker *worker)
1247c8e55f36STejun Heo {
1248bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1249c8e55f36STejun Heo 
1250c8e55f36STejun Heo 	BUG_ON(!(worker->flags & WORKER_IDLE));
1251d302f017STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
1252bd7bdd43STejun Heo 	pool->nr_idle--;
1253c8e55f36STejun Heo 	list_del_init(&worker->entry);
1254c8e55f36STejun Heo }
1255c8e55f36STejun Heo 
1256e22bee78STejun Heo /**
1257e22bee78STejun Heo  * worker_maybe_bind_and_lock - bind worker to its cpu if possible and lock gcwq
1258e22bee78STejun Heo  * @worker: self
1259e22bee78STejun Heo  *
1260e22bee78STejun Heo  * Works which are scheduled while the cpu is online must at least be
1261e22bee78STejun Heo  * scheduled to a worker which is bound to the cpu so that if they are
1262e22bee78STejun Heo  * flushed from cpu callbacks while cpu is going down, they are
1263e22bee78STejun Heo  * guaranteed to execute on the cpu.
1264e22bee78STejun Heo  *
1265e22bee78STejun Heo  * This function is to be used by rogue workers and rescuers to bind
1266e22bee78STejun Heo  * themselves to the target cpu and may race with cpu going down or
1267e22bee78STejun Heo  * coming online.  kthread_bind() can't be used because it may put the
1268e22bee78STejun Heo  * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1269e22bee78STejun Heo  * verbatim as it's best effort and blocking and gcwq may be
1270e22bee78STejun Heo  * [dis]associated in the meantime.
1271e22bee78STejun Heo  *
1272f2d5a0eeSTejun Heo  * This function tries set_cpus_allowed() and locks gcwq and verifies the
1273f2d5a0eeSTejun Heo  * binding against %GCWQ_DISASSOCIATED which is set during
1274f2d5a0eeSTejun Heo  * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
1275f2d5a0eeSTejun Heo  * enters idle state or fetches works without dropping lock, it can
1276f2d5a0eeSTejun Heo  * guarantee the scheduling requirement described in the first paragraph.
1277e22bee78STejun Heo  *
1278e22bee78STejun Heo  * CONTEXT:
1279e22bee78STejun Heo  * Might sleep.  Called without any lock but returns with gcwq->lock
1280e22bee78STejun Heo  * held.
1281e22bee78STejun Heo  *
1282e22bee78STejun Heo  * RETURNS:
1283e22bee78STejun Heo  * %true if the associated gcwq is online (@worker is successfully
1284e22bee78STejun Heo  * bound), %false if offline.
1285e22bee78STejun Heo  */
1286e22bee78STejun Heo static bool worker_maybe_bind_and_lock(struct worker *worker)
1287972fa1c5SNamhyung Kim __acquires(&gcwq->lock)
1288e22bee78STejun Heo {
1289bd7bdd43STejun Heo 	struct global_cwq *gcwq = worker->pool->gcwq;
1290e22bee78STejun Heo 	struct task_struct *task = worker->task;
1291e22bee78STejun Heo 
1292e22bee78STejun Heo 	while (true) {
1293e22bee78STejun Heo 		/*
1294e22bee78STejun Heo 		 * The following call may fail, succeed or succeed
1295e22bee78STejun Heo 		 * without actually migrating the task to the cpu if
1296e22bee78STejun Heo 		 * it races with cpu hotunplug operation.  Verify
1297e22bee78STejun Heo 		 * against GCWQ_DISASSOCIATED.
1298e22bee78STejun Heo 		 */
1299f3421797STejun Heo 		if (!(gcwq->flags & GCWQ_DISASSOCIATED))
1300e22bee78STejun Heo 			set_cpus_allowed_ptr(task, get_cpu_mask(gcwq->cpu));
1301e22bee78STejun Heo 
1302e22bee78STejun Heo 		spin_lock_irq(&gcwq->lock);
1303e22bee78STejun Heo 		if (gcwq->flags & GCWQ_DISASSOCIATED)
1304e22bee78STejun Heo 			return false;
1305e22bee78STejun Heo 		if (task_cpu(task) == gcwq->cpu &&
1306e22bee78STejun Heo 		    cpumask_equal(&current->cpus_allowed,
1307e22bee78STejun Heo 				  get_cpu_mask(gcwq->cpu)))
1308e22bee78STejun Heo 			return true;
1309e22bee78STejun Heo 		spin_unlock_irq(&gcwq->lock);
1310e22bee78STejun Heo 
13115035b20fSTejun Heo 		/*
13125035b20fSTejun Heo 		 * We've raced with CPU hot[un]plug.  Give it a breather
13135035b20fSTejun Heo 		 * and retry migration.  cond_resched() is required here;
13145035b20fSTejun Heo 		 * otherwise, we might deadlock against cpu_stop trying to
13155035b20fSTejun Heo 		 * bring down the CPU on non-preemptive kernel.
13165035b20fSTejun Heo 		 */
1317e22bee78STejun Heo 		cpu_relax();
13185035b20fSTejun Heo 		cond_resched();
1319e22bee78STejun Heo 	}
1320e22bee78STejun Heo }
1321e22bee78STejun Heo 
132225511a47STejun Heo struct idle_rebind {
132325511a47STejun Heo 	int			cnt;		/* # workers to be rebound */
132425511a47STejun Heo 	struct completion	done;		/* all workers rebound */
132525511a47STejun Heo };
132625511a47STejun Heo 
1327e22bee78STejun Heo /*
132825511a47STejun Heo  * Rebind an idle @worker to its CPU.  During CPU onlining, this has to
132925511a47STejun Heo  * happen synchronously for idle workers.  worker_thread() will test
133025511a47STejun Heo  * %WORKER_REBIND before leaving idle and call this function.
133125511a47STejun Heo  */
133225511a47STejun Heo static void idle_worker_rebind(struct worker *worker)
133325511a47STejun Heo {
133425511a47STejun Heo 	struct global_cwq *gcwq = worker->pool->gcwq;
133525511a47STejun Heo 
133625511a47STejun Heo 	/* CPU must be online at this point */
133725511a47STejun Heo 	WARN_ON(!worker_maybe_bind_and_lock(worker));
133825511a47STejun Heo 	if (!--worker->idle_rebind->cnt)
133925511a47STejun Heo 		complete(&worker->idle_rebind->done);
134025511a47STejun Heo 	spin_unlock_irq(&worker->pool->gcwq->lock);
134125511a47STejun Heo 
134225511a47STejun Heo 	/* we did our part, wait for rebind_workers() to finish up */
134325511a47STejun Heo 	wait_event(gcwq->rebind_hold, !(worker->flags & WORKER_REBIND));
134425511a47STejun Heo }
134525511a47STejun Heo 
134625511a47STejun Heo /*
134725511a47STejun Heo  * Function for @worker->rebind.work used to rebind unbound busy workers to
1348403c821dSTejun Heo  * the associated cpu which is coming back online.  This is scheduled by
1349403c821dSTejun Heo  * cpu up but can race with other cpu hotplug operations and may be
1350403c821dSTejun Heo  * executed twice without intervening cpu down.
1351e22bee78STejun Heo  */
135225511a47STejun Heo static void busy_worker_rebind_fn(struct work_struct *work)
1353e22bee78STejun Heo {
1354e22bee78STejun Heo 	struct worker *worker = container_of(work, struct worker, rebind_work);
1355bd7bdd43STejun Heo 	struct global_cwq *gcwq = worker->pool->gcwq;
1356e22bee78STejun Heo 
1357e22bee78STejun Heo 	if (worker_maybe_bind_and_lock(worker))
1358e22bee78STejun Heo 		worker_clr_flags(worker, WORKER_REBIND);
1359e22bee78STejun Heo 
1360e22bee78STejun Heo 	spin_unlock_irq(&gcwq->lock);
1361e22bee78STejun Heo }
1362e22bee78STejun Heo 
136325511a47STejun Heo /**
136425511a47STejun Heo  * rebind_workers - rebind all workers of a gcwq to the associated CPU
136525511a47STejun Heo  * @gcwq: gcwq of interest
136625511a47STejun Heo  *
136725511a47STejun Heo  * @gcwq->cpu is coming online.  Rebind all workers to the CPU.  Rebinding
136825511a47STejun Heo  * is different for idle and busy ones.
136925511a47STejun Heo  *
137025511a47STejun Heo  * The idle ones should be rebound synchronously and idle rebinding should
137125511a47STejun Heo  * be complete before any worker starts executing work items with
137225511a47STejun Heo  * concurrency management enabled; otherwise, scheduler may oops trying to
137325511a47STejun Heo  * wake up non-local idle worker from wq_worker_sleeping().
137425511a47STejun Heo  *
137525511a47STejun Heo  * This is achieved by repeatedly requesting rebinding until all idle
137625511a47STejun Heo  * workers are known to have been rebound under @gcwq->lock and holding all
137725511a47STejun Heo  * idle workers from becoming busy until idle rebinding is complete.
137825511a47STejun Heo  *
137925511a47STejun Heo  * Once idle workers are rebound, busy workers can be rebound as they
138025511a47STejun Heo  * finish executing their current work items.  Queueing the rebind work at
138125511a47STejun Heo  * the head of their scheduled lists is enough.  Note that nr_running will
138225511a47STejun Heo  * be properbly bumped as busy workers rebind.
138325511a47STejun Heo  *
138425511a47STejun Heo  * On return, all workers are guaranteed to either be bound or have rebind
138525511a47STejun Heo  * work item scheduled.
138625511a47STejun Heo  */
138725511a47STejun Heo static void rebind_workers(struct global_cwq *gcwq)
138825511a47STejun Heo 	__releases(&gcwq->lock) __acquires(&gcwq->lock)
138925511a47STejun Heo {
139025511a47STejun Heo 	struct idle_rebind idle_rebind;
139125511a47STejun Heo 	struct worker_pool *pool;
139225511a47STejun Heo 	struct worker *worker;
139325511a47STejun Heo 	struct hlist_node *pos;
139425511a47STejun Heo 	int i;
139525511a47STejun Heo 
139625511a47STejun Heo 	lockdep_assert_held(&gcwq->lock);
139725511a47STejun Heo 
139825511a47STejun Heo 	for_each_worker_pool(pool, gcwq)
139925511a47STejun Heo 		lockdep_assert_held(&pool->manager_mutex);
140025511a47STejun Heo 
140125511a47STejun Heo 	/*
140225511a47STejun Heo 	 * Rebind idle workers.  Interlocked both ways.  We wait for
140325511a47STejun Heo 	 * workers to rebind via @idle_rebind.done.  Workers will wait for
140425511a47STejun Heo 	 * us to finish up by watching %WORKER_REBIND.
140525511a47STejun Heo 	 */
140625511a47STejun Heo 	init_completion(&idle_rebind.done);
140725511a47STejun Heo retry:
140825511a47STejun Heo 	idle_rebind.cnt = 1;
140925511a47STejun Heo 	INIT_COMPLETION(idle_rebind.done);
141025511a47STejun Heo 
141125511a47STejun Heo 	/* set REBIND and kick idle ones, we'll wait for these later */
141225511a47STejun Heo 	for_each_worker_pool(pool, gcwq) {
141325511a47STejun Heo 		list_for_each_entry(worker, &pool->idle_list, entry) {
141425511a47STejun Heo 			if (worker->flags & WORKER_REBIND)
141525511a47STejun Heo 				continue;
141625511a47STejun Heo 
141725511a47STejun Heo 			/* morph UNBOUND to REBIND */
141825511a47STejun Heo 			worker->flags &= ~WORKER_UNBOUND;
141925511a47STejun Heo 			worker->flags |= WORKER_REBIND;
142025511a47STejun Heo 
142125511a47STejun Heo 			idle_rebind.cnt++;
142225511a47STejun Heo 			worker->idle_rebind = &idle_rebind;
142325511a47STejun Heo 
142425511a47STejun Heo 			/* worker_thread() will call idle_worker_rebind() */
142525511a47STejun Heo 			wake_up_process(worker->task);
142625511a47STejun Heo 		}
142725511a47STejun Heo 	}
142825511a47STejun Heo 
142925511a47STejun Heo 	if (--idle_rebind.cnt) {
143025511a47STejun Heo 		spin_unlock_irq(&gcwq->lock);
143125511a47STejun Heo 		wait_for_completion(&idle_rebind.done);
143225511a47STejun Heo 		spin_lock_irq(&gcwq->lock);
143325511a47STejun Heo 		/* busy ones might have become idle while waiting, retry */
143425511a47STejun Heo 		goto retry;
143525511a47STejun Heo 	}
143625511a47STejun Heo 
143725511a47STejun Heo 	/*
143825511a47STejun Heo 	 * All idle workers are rebound and waiting for %WORKER_REBIND to
143925511a47STejun Heo 	 * be cleared inside idle_worker_rebind().  Clear and release.
144025511a47STejun Heo 	 * Clearing %WORKER_REBIND from this foreign context is safe
144125511a47STejun Heo 	 * because these workers are still guaranteed to be idle.
144225511a47STejun Heo 	 */
144325511a47STejun Heo 	for_each_worker_pool(pool, gcwq)
144425511a47STejun Heo 		list_for_each_entry(worker, &pool->idle_list, entry)
144525511a47STejun Heo 			worker->flags &= ~WORKER_REBIND;
144625511a47STejun Heo 
144725511a47STejun Heo 	wake_up_all(&gcwq->rebind_hold);
144825511a47STejun Heo 
144925511a47STejun Heo 	/* rebind busy workers */
145025511a47STejun Heo 	for_each_busy_worker(worker, i, pos, gcwq) {
145125511a47STejun Heo 		struct work_struct *rebind_work = &worker->rebind_work;
145225511a47STejun Heo 
145325511a47STejun Heo 		/* morph UNBOUND to REBIND */
145425511a47STejun Heo 		worker->flags &= ~WORKER_UNBOUND;
145525511a47STejun Heo 		worker->flags |= WORKER_REBIND;
145625511a47STejun Heo 
145725511a47STejun Heo 		if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
145825511a47STejun Heo 				     work_data_bits(rebind_work)))
145925511a47STejun Heo 			continue;
146025511a47STejun Heo 
146125511a47STejun Heo 		/* wq doesn't matter, use the default one */
146225511a47STejun Heo 		debug_work_activate(rebind_work);
146325511a47STejun Heo 		insert_work(get_cwq(gcwq->cpu, system_wq), rebind_work,
146425511a47STejun Heo 			    worker->scheduled.next,
146525511a47STejun Heo 			    work_color_to_flags(WORK_NO_COLOR));
146625511a47STejun Heo 	}
146725511a47STejun Heo }
146825511a47STejun Heo 
1469c34056a3STejun Heo static struct worker *alloc_worker(void)
1470c34056a3STejun Heo {
1471c34056a3STejun Heo 	struct worker *worker;
1472c34056a3STejun Heo 
1473c34056a3STejun Heo 	worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1474c8e55f36STejun Heo 	if (worker) {
1475c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
1476affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
147725511a47STejun Heo 		INIT_WORK(&worker->rebind_work, busy_worker_rebind_fn);
1478e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
1479e22bee78STejun Heo 		worker->flags = WORKER_PREP;
1480c8e55f36STejun Heo 	}
1481c34056a3STejun Heo 	return worker;
1482c34056a3STejun Heo }
1483c34056a3STejun Heo 
1484c34056a3STejun Heo /**
1485c34056a3STejun Heo  * create_worker - create a new workqueue worker
148663d95a91STejun Heo  * @pool: pool the new worker will belong to
1487c34056a3STejun Heo  *
148863d95a91STejun Heo  * Create a new worker which is bound to @pool.  The returned worker
1489c34056a3STejun Heo  * can be started by calling start_worker() or destroyed using
1490c34056a3STejun Heo  * destroy_worker().
1491c34056a3STejun Heo  *
1492c34056a3STejun Heo  * CONTEXT:
1493c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
1494c34056a3STejun Heo  *
1495c34056a3STejun Heo  * RETURNS:
1496c34056a3STejun Heo  * Pointer to the newly created worker.
1497c34056a3STejun Heo  */
1498bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
1499c34056a3STejun Heo {
150063d95a91STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
15013270476aSTejun Heo 	const char *pri = worker_pool_pri(pool) ? "H" : "";
1502c34056a3STejun Heo 	struct worker *worker = NULL;
1503f3421797STejun Heo 	int id = -1;
1504c34056a3STejun Heo 
15058b03ae3cSTejun Heo 	spin_lock_irq(&gcwq->lock);
1506bd7bdd43STejun Heo 	while (ida_get_new(&pool->worker_ida, &id)) {
15078b03ae3cSTejun Heo 		spin_unlock_irq(&gcwq->lock);
1508bd7bdd43STejun Heo 		if (!ida_pre_get(&pool->worker_ida, GFP_KERNEL))
1509c34056a3STejun Heo 			goto fail;
15108b03ae3cSTejun Heo 		spin_lock_irq(&gcwq->lock);
1511c34056a3STejun Heo 	}
15128b03ae3cSTejun Heo 	spin_unlock_irq(&gcwq->lock);
1513c34056a3STejun Heo 
1514c34056a3STejun Heo 	worker = alloc_worker();
1515c34056a3STejun Heo 	if (!worker)
1516c34056a3STejun Heo 		goto fail;
1517c34056a3STejun Heo 
1518bd7bdd43STejun Heo 	worker->pool = pool;
1519c34056a3STejun Heo 	worker->id = id;
1520c34056a3STejun Heo 
1521bc2ae0f5STejun Heo 	if (gcwq->cpu != WORK_CPU_UNBOUND)
152294dcf29aSEric Dumazet 		worker->task = kthread_create_on_node(worker_thread,
15233270476aSTejun Heo 					worker, cpu_to_node(gcwq->cpu),
15243270476aSTejun Heo 					"kworker/%u:%d%s", gcwq->cpu, id, pri);
1525f3421797STejun Heo 	else
1526f3421797STejun Heo 		worker->task = kthread_create(worker_thread, worker,
15273270476aSTejun Heo 					      "kworker/u:%d%s", id, pri);
1528c34056a3STejun Heo 	if (IS_ERR(worker->task))
1529c34056a3STejun Heo 		goto fail;
1530c34056a3STejun Heo 
15313270476aSTejun Heo 	if (worker_pool_pri(pool))
15323270476aSTejun Heo 		set_user_nice(worker->task, HIGHPRI_NICE_LEVEL);
15333270476aSTejun Heo 
1534db7bccf4STejun Heo 	/*
1535bc2ae0f5STejun Heo 	 * Determine CPU binding of the new worker depending on
1536bc2ae0f5STejun Heo 	 * %GCWQ_DISASSOCIATED.  The caller is responsible for ensuring the
1537bc2ae0f5STejun Heo 	 * flag remains stable across this function.  See the comments
1538bc2ae0f5STejun Heo 	 * above the flag definition for details.
1539bc2ae0f5STejun Heo 	 *
1540bc2ae0f5STejun Heo 	 * As an unbound worker may later become a regular one if CPU comes
1541bc2ae0f5STejun Heo 	 * online, make sure every worker has %PF_THREAD_BOUND set.
1542db7bccf4STejun Heo 	 */
1543bc2ae0f5STejun Heo 	if (!(gcwq->flags & GCWQ_DISASSOCIATED)) {
15448b03ae3cSTejun Heo 		kthread_bind(worker->task, gcwq->cpu);
1545bc2ae0f5STejun Heo 	} else {
1546db7bccf4STejun Heo 		worker->task->flags |= PF_THREAD_BOUND;
1547f3421797STejun Heo 		worker->flags |= WORKER_UNBOUND;
1548f3421797STejun Heo 	}
1549c34056a3STejun Heo 
1550c34056a3STejun Heo 	return worker;
1551c34056a3STejun Heo fail:
1552c34056a3STejun Heo 	if (id >= 0) {
15538b03ae3cSTejun Heo 		spin_lock_irq(&gcwq->lock);
1554bd7bdd43STejun Heo 		ida_remove(&pool->worker_ida, id);
15558b03ae3cSTejun Heo 		spin_unlock_irq(&gcwq->lock);
1556c34056a3STejun Heo 	}
1557c34056a3STejun Heo 	kfree(worker);
1558c34056a3STejun Heo 	return NULL;
1559c34056a3STejun Heo }
1560c34056a3STejun Heo 
1561c34056a3STejun Heo /**
1562c34056a3STejun Heo  * start_worker - start a newly created worker
1563c34056a3STejun Heo  * @worker: worker to start
1564c34056a3STejun Heo  *
1565c8e55f36STejun Heo  * Make the gcwq aware of @worker and start it.
1566c34056a3STejun Heo  *
1567c34056a3STejun Heo  * CONTEXT:
15688b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock).
1569c34056a3STejun Heo  */
1570c34056a3STejun Heo static void start_worker(struct worker *worker)
1571c34056a3STejun Heo {
1572cb444766STejun Heo 	worker->flags |= WORKER_STARTED;
1573bd7bdd43STejun Heo 	worker->pool->nr_workers++;
1574c8e55f36STejun Heo 	worker_enter_idle(worker);
1575c34056a3STejun Heo 	wake_up_process(worker->task);
1576c34056a3STejun Heo }
1577c34056a3STejun Heo 
1578c34056a3STejun Heo /**
1579c34056a3STejun Heo  * destroy_worker - destroy a workqueue worker
1580c34056a3STejun Heo  * @worker: worker to be destroyed
1581c34056a3STejun Heo  *
1582c8e55f36STejun Heo  * Destroy @worker and adjust @gcwq stats accordingly.
1583c8e55f36STejun Heo  *
1584c8e55f36STejun Heo  * CONTEXT:
1585c8e55f36STejun Heo  * spin_lock_irq(gcwq->lock) which is released and regrabbed.
1586c34056a3STejun Heo  */
1587c34056a3STejun Heo static void destroy_worker(struct worker *worker)
1588c34056a3STejun Heo {
1589bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1590bd7bdd43STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
1591c34056a3STejun Heo 	int id = worker->id;
1592c34056a3STejun Heo 
1593c34056a3STejun Heo 	/* sanity check frenzy */
1594c34056a3STejun Heo 	BUG_ON(worker->current_work);
1595affee4b2STejun Heo 	BUG_ON(!list_empty(&worker->scheduled));
1596c34056a3STejun Heo 
1597c8e55f36STejun Heo 	if (worker->flags & WORKER_STARTED)
1598bd7bdd43STejun Heo 		pool->nr_workers--;
1599c8e55f36STejun Heo 	if (worker->flags & WORKER_IDLE)
1600bd7bdd43STejun Heo 		pool->nr_idle--;
1601c8e55f36STejun Heo 
1602c8e55f36STejun Heo 	list_del_init(&worker->entry);
1603cb444766STejun Heo 	worker->flags |= WORKER_DIE;
1604c8e55f36STejun Heo 
1605c8e55f36STejun Heo 	spin_unlock_irq(&gcwq->lock);
1606c8e55f36STejun Heo 
1607c34056a3STejun Heo 	kthread_stop(worker->task);
1608c34056a3STejun Heo 	kfree(worker);
1609c34056a3STejun Heo 
16108b03ae3cSTejun Heo 	spin_lock_irq(&gcwq->lock);
1611bd7bdd43STejun Heo 	ida_remove(&pool->worker_ida, id);
1612c34056a3STejun Heo }
1613c34056a3STejun Heo 
161463d95a91STejun Heo static void idle_worker_timeout(unsigned long __pool)
1615e22bee78STejun Heo {
161663d95a91STejun Heo 	struct worker_pool *pool = (void *)__pool;
161763d95a91STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
1618e22bee78STejun Heo 
1619e22bee78STejun Heo 	spin_lock_irq(&gcwq->lock);
1620e22bee78STejun Heo 
162163d95a91STejun Heo 	if (too_many_workers(pool)) {
1622e22bee78STejun Heo 		struct worker *worker;
1623e22bee78STejun Heo 		unsigned long expires;
1624e22bee78STejun Heo 
1625e22bee78STejun Heo 		/* idle_list is kept in LIFO order, check the last one */
162663d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
1627e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1628e22bee78STejun Heo 
1629e22bee78STejun Heo 		if (time_before(jiffies, expires))
163063d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
1631e22bee78STejun Heo 		else {
1632e22bee78STejun Heo 			/* it's been idle for too long, wake up manager */
163311ebea50STejun Heo 			pool->flags |= POOL_MANAGE_WORKERS;
163463d95a91STejun Heo 			wake_up_worker(pool);
1635e22bee78STejun Heo 		}
1636e22bee78STejun Heo 	}
1637e22bee78STejun Heo 
1638e22bee78STejun Heo 	spin_unlock_irq(&gcwq->lock);
1639e22bee78STejun Heo }
1640e22bee78STejun Heo 
1641e22bee78STejun Heo static bool send_mayday(struct work_struct *work)
1642e22bee78STejun Heo {
1643e22bee78STejun Heo 	struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1644e22bee78STejun Heo 	struct workqueue_struct *wq = cwq->wq;
1645f3421797STejun Heo 	unsigned int cpu;
1646e22bee78STejun Heo 
1647e22bee78STejun Heo 	if (!(wq->flags & WQ_RESCUER))
1648e22bee78STejun Heo 		return false;
1649e22bee78STejun Heo 
1650e22bee78STejun Heo 	/* mayday mayday mayday */
1651bd7bdd43STejun Heo 	cpu = cwq->pool->gcwq->cpu;
1652f3421797STejun Heo 	/* WORK_CPU_UNBOUND can't be set in cpumask, use cpu 0 instead */
1653f3421797STejun Heo 	if (cpu == WORK_CPU_UNBOUND)
1654f3421797STejun Heo 		cpu = 0;
1655f2e005aaSTejun Heo 	if (!mayday_test_and_set_cpu(cpu, wq->mayday_mask))
1656e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
1657e22bee78STejun Heo 	return true;
1658e22bee78STejun Heo }
1659e22bee78STejun Heo 
166063d95a91STejun Heo static void gcwq_mayday_timeout(unsigned long __pool)
1661e22bee78STejun Heo {
166263d95a91STejun Heo 	struct worker_pool *pool = (void *)__pool;
166363d95a91STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
1664e22bee78STejun Heo 	struct work_struct *work;
1665e22bee78STejun Heo 
1666e22bee78STejun Heo 	spin_lock_irq(&gcwq->lock);
1667e22bee78STejun Heo 
166863d95a91STejun Heo 	if (need_to_create_worker(pool)) {
1669e22bee78STejun Heo 		/*
1670e22bee78STejun Heo 		 * We've been trying to create a new worker but
1671e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
1672e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
1673e22bee78STejun Heo 		 * rescuers.
1674e22bee78STejun Heo 		 */
167563d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
1676e22bee78STejun Heo 			send_mayday(work);
1677e22bee78STejun Heo 	}
1678e22bee78STejun Heo 
1679e22bee78STejun Heo 	spin_unlock_irq(&gcwq->lock);
1680e22bee78STejun Heo 
168163d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1682e22bee78STejun Heo }
1683e22bee78STejun Heo 
1684e22bee78STejun Heo /**
1685e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
168663d95a91STejun Heo  * @pool: pool to create a new worker for
1687e22bee78STejun Heo  *
168863d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
1689e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
1690e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
169163d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
1692e22bee78STejun Heo  * possible allocation deadlock.
1693e22bee78STejun Heo  *
1694e22bee78STejun Heo  * On return, need_to_create_worker() is guaranteed to be false and
1695e22bee78STejun Heo  * may_start_working() true.
1696e22bee78STejun Heo  *
1697e22bee78STejun Heo  * LOCKING:
1698e22bee78STejun Heo  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1699e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
1700e22bee78STejun Heo  * manager.
1701e22bee78STejun Heo  *
1702e22bee78STejun Heo  * RETURNS:
1703e22bee78STejun Heo  * false if no action was taken and gcwq->lock stayed locked, true
1704e22bee78STejun Heo  * otherwise.
1705e22bee78STejun Heo  */
170663d95a91STejun Heo static bool maybe_create_worker(struct worker_pool *pool)
170706bd6ebfSNamhyung Kim __releases(&gcwq->lock)
170806bd6ebfSNamhyung Kim __acquires(&gcwq->lock)
1709e22bee78STejun Heo {
171063d95a91STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
171163d95a91STejun Heo 
171263d95a91STejun Heo 	if (!need_to_create_worker(pool))
1713e22bee78STejun Heo 		return false;
1714e22bee78STejun Heo restart:
17159f9c2364STejun Heo 	spin_unlock_irq(&gcwq->lock);
17169f9c2364STejun Heo 
1717e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
171863d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1719e22bee78STejun Heo 
1720e22bee78STejun Heo 	while (true) {
1721e22bee78STejun Heo 		struct worker *worker;
1722e22bee78STejun Heo 
1723bc2ae0f5STejun Heo 		worker = create_worker(pool);
1724e22bee78STejun Heo 		if (worker) {
172563d95a91STejun Heo 			del_timer_sync(&pool->mayday_timer);
1726e22bee78STejun Heo 			spin_lock_irq(&gcwq->lock);
1727e22bee78STejun Heo 			start_worker(worker);
172863d95a91STejun Heo 			BUG_ON(need_to_create_worker(pool));
1729e22bee78STejun Heo 			return true;
1730e22bee78STejun Heo 		}
1731e22bee78STejun Heo 
173263d95a91STejun Heo 		if (!need_to_create_worker(pool))
1733e22bee78STejun Heo 			break;
1734e22bee78STejun Heo 
1735e22bee78STejun Heo 		__set_current_state(TASK_INTERRUPTIBLE);
1736e22bee78STejun Heo 		schedule_timeout(CREATE_COOLDOWN);
17379f9c2364STejun Heo 
173863d95a91STejun Heo 		if (!need_to_create_worker(pool))
1739e22bee78STejun Heo 			break;
1740e22bee78STejun Heo 	}
1741e22bee78STejun Heo 
174263d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
1743e22bee78STejun Heo 	spin_lock_irq(&gcwq->lock);
174463d95a91STejun Heo 	if (need_to_create_worker(pool))
1745e22bee78STejun Heo 		goto restart;
1746e22bee78STejun Heo 	return true;
1747e22bee78STejun Heo }
1748e22bee78STejun Heo 
1749e22bee78STejun Heo /**
1750e22bee78STejun Heo  * maybe_destroy_worker - destroy workers which have been idle for a while
175163d95a91STejun Heo  * @pool: pool to destroy workers for
1752e22bee78STejun Heo  *
175363d95a91STejun Heo  * Destroy @pool workers which have been idle for longer than
1754e22bee78STejun Heo  * IDLE_WORKER_TIMEOUT.
1755e22bee78STejun Heo  *
1756e22bee78STejun Heo  * LOCKING:
1757e22bee78STejun Heo  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1758e22bee78STejun Heo  * multiple times.  Called only from manager.
1759e22bee78STejun Heo  *
1760e22bee78STejun Heo  * RETURNS:
1761e22bee78STejun Heo  * false if no action was taken and gcwq->lock stayed locked, true
1762e22bee78STejun Heo  * otherwise.
1763e22bee78STejun Heo  */
176463d95a91STejun Heo static bool maybe_destroy_workers(struct worker_pool *pool)
1765e22bee78STejun Heo {
1766e22bee78STejun Heo 	bool ret = false;
1767e22bee78STejun Heo 
176863d95a91STejun Heo 	while (too_many_workers(pool)) {
1769e22bee78STejun Heo 		struct worker *worker;
1770e22bee78STejun Heo 		unsigned long expires;
1771e22bee78STejun Heo 
177263d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
1773e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1774e22bee78STejun Heo 
1775e22bee78STejun Heo 		if (time_before(jiffies, expires)) {
177663d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
1777e22bee78STejun Heo 			break;
1778e22bee78STejun Heo 		}
1779e22bee78STejun Heo 
1780e22bee78STejun Heo 		destroy_worker(worker);
1781e22bee78STejun Heo 		ret = true;
1782e22bee78STejun Heo 	}
1783e22bee78STejun Heo 
1784e22bee78STejun Heo 	return ret;
1785e22bee78STejun Heo }
1786e22bee78STejun Heo 
1787e22bee78STejun Heo /**
1788e22bee78STejun Heo  * manage_workers - manage worker pool
1789e22bee78STejun Heo  * @worker: self
1790e22bee78STejun Heo  *
1791e22bee78STejun Heo  * Assume the manager role and manage gcwq worker pool @worker belongs
1792e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
1793e22bee78STejun Heo  * gcwq.  The exclusion is handled automatically by this function.
1794e22bee78STejun Heo  *
1795e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
1796e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
1797e22bee78STejun Heo  * and may_start_working() is true.
1798e22bee78STejun Heo  *
1799e22bee78STejun Heo  * CONTEXT:
1800e22bee78STejun Heo  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1801e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
1802e22bee78STejun Heo  *
1803e22bee78STejun Heo  * RETURNS:
1804e22bee78STejun Heo  * false if no action was taken and gcwq->lock stayed locked, true if
1805e22bee78STejun Heo  * some action was taken.
1806e22bee78STejun Heo  */
1807e22bee78STejun Heo static bool manage_workers(struct worker *worker)
1808e22bee78STejun Heo {
180963d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
1810e22bee78STejun Heo 	bool ret = false;
1811e22bee78STejun Heo 
181260373152STejun Heo 	if (!mutex_trylock(&pool->manager_mutex))
1813e22bee78STejun Heo 		return ret;
1814e22bee78STejun Heo 
181511ebea50STejun Heo 	pool->flags &= ~POOL_MANAGE_WORKERS;
1816e22bee78STejun Heo 
1817e22bee78STejun Heo 	/*
1818e22bee78STejun Heo 	 * Destroy and then create so that may_start_working() is true
1819e22bee78STejun Heo 	 * on return.
1820e22bee78STejun Heo 	 */
182163d95a91STejun Heo 	ret |= maybe_destroy_workers(pool);
182263d95a91STejun Heo 	ret |= maybe_create_worker(pool);
1823e22bee78STejun Heo 
182460373152STejun Heo 	mutex_unlock(&pool->manager_mutex);
1825e22bee78STejun Heo 	return ret;
1826e22bee78STejun Heo }
1827e22bee78STejun Heo 
1828a62428c0STejun Heo /**
1829affee4b2STejun Heo  * move_linked_works - move linked works to a list
1830affee4b2STejun Heo  * @work: start of series of works to be scheduled
1831affee4b2STejun Heo  * @head: target list to append @work to
1832affee4b2STejun Heo  * @nextp: out paramter for nested worklist walking
1833affee4b2STejun Heo  *
1834affee4b2STejun Heo  * Schedule linked works starting from @work to @head.  Work series to
1835affee4b2STejun Heo  * be scheduled starts at @work and includes any consecutive work with
1836affee4b2STejun Heo  * WORK_STRUCT_LINKED set in its predecessor.
1837affee4b2STejun Heo  *
1838affee4b2STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of
1839affee4b2STejun Heo  * the last scheduled work.  This allows move_linked_works() to be
1840affee4b2STejun Heo  * nested inside outer list_for_each_entry_safe().
1841affee4b2STejun Heo  *
1842affee4b2STejun Heo  * CONTEXT:
18438b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock).
1844affee4b2STejun Heo  */
1845affee4b2STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
1846affee4b2STejun Heo 			      struct work_struct **nextp)
1847affee4b2STejun Heo {
1848affee4b2STejun Heo 	struct work_struct *n;
1849affee4b2STejun Heo 
1850affee4b2STejun Heo 	/*
1851affee4b2STejun Heo 	 * Linked worklist will always end before the end of the list,
1852affee4b2STejun Heo 	 * use NULL for list head.
1853affee4b2STejun Heo 	 */
1854affee4b2STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
1855affee4b2STejun Heo 		list_move_tail(&work->entry, head);
1856affee4b2STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1857affee4b2STejun Heo 			break;
1858affee4b2STejun Heo 	}
1859affee4b2STejun Heo 
1860affee4b2STejun Heo 	/*
1861affee4b2STejun Heo 	 * If we're already inside safe list traversal and have moved
1862affee4b2STejun Heo 	 * multiple works to the scheduled queue, the next position
1863affee4b2STejun Heo 	 * needs to be updated.
1864affee4b2STejun Heo 	 */
1865affee4b2STejun Heo 	if (nextp)
1866affee4b2STejun Heo 		*nextp = n;
1867affee4b2STejun Heo }
1868affee4b2STejun Heo 
18691e19ffc6STejun Heo static void cwq_activate_first_delayed(struct cpu_workqueue_struct *cwq)
18701e19ffc6STejun Heo {
18711e19ffc6STejun Heo 	struct work_struct *work = list_first_entry(&cwq->delayed_works,
18721da177e4SLinus Torvalds 						    struct work_struct, entry);
18731e19ffc6STejun Heo 
1874cdadf009STejun Heo 	trace_workqueue_activate_work(work);
18753270476aSTejun Heo 	move_linked_works(work, &cwq->pool->worklist, NULL);
18768a2e8e5dSTejun Heo 	__clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
18771e19ffc6STejun Heo 	cwq->nr_active++;
18781e19ffc6STejun Heo }
18791e19ffc6STejun Heo 
1880affee4b2STejun Heo /**
188173f53c4aSTejun Heo  * cwq_dec_nr_in_flight - decrement cwq's nr_in_flight
188273f53c4aSTejun Heo  * @cwq: cwq of interest
188373f53c4aSTejun Heo  * @color: color of work which left the queue
18848a2e8e5dSTejun Heo  * @delayed: for a delayed work
188573f53c4aSTejun Heo  *
188673f53c4aSTejun Heo  * A work either has completed or is removed from pending queue,
188773f53c4aSTejun Heo  * decrement nr_in_flight of its cwq and handle workqueue flushing.
188873f53c4aSTejun Heo  *
188973f53c4aSTejun Heo  * CONTEXT:
18908b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock).
189173f53c4aSTejun Heo  */
18928a2e8e5dSTejun Heo static void cwq_dec_nr_in_flight(struct cpu_workqueue_struct *cwq, int color,
18938a2e8e5dSTejun Heo 				 bool delayed)
189473f53c4aSTejun Heo {
189573f53c4aSTejun Heo 	/* ignore uncolored works */
189673f53c4aSTejun Heo 	if (color == WORK_NO_COLOR)
189773f53c4aSTejun Heo 		return;
189873f53c4aSTejun Heo 
189973f53c4aSTejun Heo 	cwq->nr_in_flight[color]--;
19001e19ffc6STejun Heo 
19018a2e8e5dSTejun Heo 	if (!delayed) {
19028a2e8e5dSTejun Heo 		cwq->nr_active--;
1903502ca9d8STejun Heo 		if (!list_empty(&cwq->delayed_works)) {
19041e19ffc6STejun Heo 			/* one down, submit a delayed one */
1905502ca9d8STejun Heo 			if (cwq->nr_active < cwq->max_active)
19061e19ffc6STejun Heo 				cwq_activate_first_delayed(cwq);
1907502ca9d8STejun Heo 		}
19088a2e8e5dSTejun Heo 	}
190973f53c4aSTejun Heo 
191073f53c4aSTejun Heo 	/* is flush in progress and are we at the flushing tip? */
191173f53c4aSTejun Heo 	if (likely(cwq->flush_color != color))
191273f53c4aSTejun Heo 		return;
191373f53c4aSTejun Heo 
191473f53c4aSTejun Heo 	/* are there still in-flight works? */
191573f53c4aSTejun Heo 	if (cwq->nr_in_flight[color])
191673f53c4aSTejun Heo 		return;
191773f53c4aSTejun Heo 
191873f53c4aSTejun Heo 	/* this cwq is done, clear flush_color */
191973f53c4aSTejun Heo 	cwq->flush_color = -1;
192073f53c4aSTejun Heo 
192173f53c4aSTejun Heo 	/*
192273f53c4aSTejun Heo 	 * If this was the last cwq, wake up the first flusher.  It
192373f53c4aSTejun Heo 	 * will handle the rest.
192473f53c4aSTejun Heo 	 */
192573f53c4aSTejun Heo 	if (atomic_dec_and_test(&cwq->wq->nr_cwqs_to_flush))
192673f53c4aSTejun Heo 		complete(&cwq->wq->first_flusher->done);
192773f53c4aSTejun Heo }
192873f53c4aSTejun Heo 
192973f53c4aSTejun Heo /**
1930a62428c0STejun Heo  * process_one_work - process single work
1931c34056a3STejun Heo  * @worker: self
1932a62428c0STejun Heo  * @work: work to process
1933a62428c0STejun Heo  *
1934a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
1935a62428c0STejun Heo  * process a single work including synchronization against and
1936a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
1937a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
1938a62428c0STejun Heo  * call this function to process a work.
1939a62428c0STejun Heo  *
1940a62428c0STejun Heo  * CONTEXT:
19418b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock) which is released and regrabbed.
1942a62428c0STejun Heo  */
1943c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
194406bd6ebfSNamhyung Kim __releases(&gcwq->lock)
194506bd6ebfSNamhyung Kim __acquires(&gcwq->lock)
19461da177e4SLinus Torvalds {
19477e11629dSTejun Heo 	struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1948bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1949bd7bdd43STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
1950c8e55f36STejun Heo 	struct hlist_head *bwh = busy_worker_head(gcwq, work);
1951fb0e7bebSTejun Heo 	bool cpu_intensive = cwq->wq->flags & WQ_CPU_INTENSIVE;
19526bb49e59SDavid Howells 	work_func_t f = work->func;
195373f53c4aSTejun Heo 	int work_color;
19547e11629dSTejun Heo 	struct worker *collision;
19554e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
19564e6045f1SJohannes Berg 	/*
1957a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
1958a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
1959a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
1960a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
1961a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
19624e6045f1SJohannes Berg 	 */
19634d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
19644d82a1deSPeter Zijlstra 
19654d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
19664e6045f1SJohannes Berg #endif
196725511a47STejun Heo 	WARN_ON_ONCE(!(worker->flags & (WORKER_UNBOUND | WORKER_REBIND)) &&
196825511a47STejun Heo 		     raw_smp_processor_id() != gcwq->cpu);
196925511a47STejun Heo 
19707e11629dSTejun Heo 	/*
19717e11629dSTejun Heo 	 * A single work shouldn't be executed concurrently by
19727e11629dSTejun Heo 	 * multiple workers on a single cpu.  Check whether anyone is
19737e11629dSTejun Heo 	 * already processing the work.  If so, defer the work to the
19747e11629dSTejun Heo 	 * currently executing one.
19757e11629dSTejun Heo 	 */
19767e11629dSTejun Heo 	collision = __find_worker_executing_work(gcwq, bwh, work);
19777e11629dSTejun Heo 	if (unlikely(collision)) {
19787e11629dSTejun Heo 		move_linked_works(work, &collision->scheduled, NULL);
19797e11629dSTejun Heo 		return;
19807e11629dSTejun Heo 	}
19811da177e4SLinus Torvalds 
1982a62428c0STejun Heo 	/* claim and process */
19831da177e4SLinus Torvalds 	debug_work_deactivate(work);
1984c8e55f36STejun Heo 	hlist_add_head(&worker->hentry, bwh);
1985c34056a3STejun Heo 	worker->current_work = work;
19868cca0eeaSTejun Heo 	worker->current_cwq = cwq;
198773f53c4aSTejun Heo 	work_color = get_work_color(work);
19887a22ad75STejun Heo 
19897a22ad75STejun Heo 	/* record the current cpu number in the work data and dequeue */
19907a22ad75STejun Heo 	set_work_cpu(work, gcwq->cpu);
1991a62428c0STejun Heo 	list_del_init(&work->entry);
1992a62428c0STejun Heo 
1993649027d7STejun Heo 	/*
1994fb0e7bebSTejun Heo 	 * CPU intensive works don't participate in concurrency
1995fb0e7bebSTejun Heo 	 * management.  They're the scheduler's responsibility.
1996fb0e7bebSTejun Heo 	 */
1997fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
1998fb0e7bebSTejun Heo 		worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
1999fb0e7bebSTejun Heo 
2000974271c4STejun Heo 	/*
2001974271c4STejun Heo 	 * Unbound gcwq isn't concurrency managed and work items should be
2002974271c4STejun Heo 	 * executed ASAP.  Wake up another worker if necessary.
2003974271c4STejun Heo 	 */
200463d95a91STejun Heo 	if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
200563d95a91STejun Heo 		wake_up_worker(pool);
2006974271c4STejun Heo 
20078b03ae3cSTejun Heo 	spin_unlock_irq(&gcwq->lock);
20081da177e4SLinus Torvalds 
200923b2e599SOleg Nesterov 	work_clear_pending(work);
2010e159489bSTejun Heo 	lock_map_acquire_read(&cwq->wq->lockdep_map);
20113295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
2012e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
201365f27f38SDavid Howells 	f(work);
2014e36c886aSArjan van de Ven 	/*
2015e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
2016e36c886aSArjan van de Ven 	 * point will only record its address.
2017e36c886aSArjan van de Ven 	 */
2018e36c886aSArjan van de Ven 	trace_workqueue_execute_end(work);
20193295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
20203295f0efSIngo Molnar 	lock_map_release(&cwq->wq->lockdep_map);
20211da177e4SLinus Torvalds 
2022d5abe669SPeter Zijlstra 	if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2023d5abe669SPeter Zijlstra 		printk(KERN_ERR "BUG: workqueue leaked lock or atomic: "
2024d5abe669SPeter Zijlstra 		       "%s/0x%08x/%d\n",
2025a62428c0STejun Heo 		       current->comm, preempt_count(), task_pid_nr(current));
2026d5abe669SPeter Zijlstra 		printk(KERN_ERR "    last function: ");
2027d5abe669SPeter Zijlstra 		print_symbol("%s\n", (unsigned long)f);
2028d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
2029d5abe669SPeter Zijlstra 		dump_stack();
2030d5abe669SPeter Zijlstra 	}
2031d5abe669SPeter Zijlstra 
20328b03ae3cSTejun Heo 	spin_lock_irq(&gcwq->lock);
2033a62428c0STejun Heo 
2034fb0e7bebSTejun Heo 	/* clear cpu intensive status */
2035fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2036fb0e7bebSTejun Heo 		worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2037fb0e7bebSTejun Heo 
2038a62428c0STejun Heo 	/* we're done with it, release */
2039c8e55f36STejun Heo 	hlist_del_init(&worker->hentry);
2040c34056a3STejun Heo 	worker->current_work = NULL;
20418cca0eeaSTejun Heo 	worker->current_cwq = NULL;
20428a2e8e5dSTejun Heo 	cwq_dec_nr_in_flight(cwq, work_color, false);
20431da177e4SLinus Torvalds }
20441da177e4SLinus Torvalds 
2045affee4b2STejun Heo /**
2046affee4b2STejun Heo  * process_scheduled_works - process scheduled works
2047affee4b2STejun Heo  * @worker: self
2048affee4b2STejun Heo  *
2049affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
2050affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
2051affee4b2STejun Heo  * fetches a work from the top and executes it.
2052affee4b2STejun Heo  *
2053affee4b2STejun Heo  * CONTEXT:
20548b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
2055affee4b2STejun Heo  * multiple times.
2056affee4b2STejun Heo  */
2057affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
20581da177e4SLinus Torvalds {
2059affee4b2STejun Heo 	while (!list_empty(&worker->scheduled)) {
2060affee4b2STejun Heo 		struct work_struct *work = list_first_entry(&worker->scheduled,
2061a62428c0STejun Heo 						struct work_struct, entry);
2062c34056a3STejun Heo 		process_one_work(worker, work);
2063a62428c0STejun Heo 	}
20641da177e4SLinus Torvalds }
20651da177e4SLinus Torvalds 
20664690c4abSTejun Heo /**
20674690c4abSTejun Heo  * worker_thread - the worker thread function
2068c34056a3STejun Heo  * @__worker: self
20694690c4abSTejun Heo  *
2070e22bee78STejun Heo  * The gcwq worker thread function.  There's a single dynamic pool of
2071e22bee78STejun Heo  * these per each cpu.  These workers process all works regardless of
2072e22bee78STejun Heo  * their specific target workqueue.  The only exception is works which
2073e22bee78STejun Heo  * belong to workqueues with a rescuer which will be explained in
2074e22bee78STejun Heo  * rescuer_thread().
20754690c4abSTejun Heo  */
2076c34056a3STejun Heo static int worker_thread(void *__worker)
20771da177e4SLinus Torvalds {
2078c34056a3STejun Heo 	struct worker *worker = __worker;
2079bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2080bd7bdd43STejun Heo 	struct global_cwq *gcwq = pool->gcwq;
20811da177e4SLinus Torvalds 
2082e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
2083e22bee78STejun Heo 	worker->task->flags |= PF_WQ_WORKER;
2084c8e55f36STejun Heo woke_up:
20858b03ae3cSTejun Heo 	spin_lock_irq(&gcwq->lock);
2086affee4b2STejun Heo 
208725511a47STejun Heo 	/*
208825511a47STejun Heo 	 * DIE can be set only while idle and REBIND set while busy has
208925511a47STejun Heo 	 * @worker->rebind_work scheduled.  Checking here is enough.
209025511a47STejun Heo 	 */
209125511a47STejun Heo 	if (unlikely(worker->flags & (WORKER_REBIND | WORKER_DIE))) {
2092c8e55f36STejun Heo 		spin_unlock_irq(&gcwq->lock);
209325511a47STejun Heo 
209425511a47STejun Heo 		if (worker->flags & WORKER_DIE) {
2095e22bee78STejun Heo 			worker->task->flags &= ~PF_WQ_WORKER;
2096c8e55f36STejun Heo 			return 0;
2097c8e55f36STejun Heo 		}
2098c8e55f36STejun Heo 
209925511a47STejun Heo 		idle_worker_rebind(worker);
210025511a47STejun Heo 		goto woke_up;
210125511a47STejun Heo 	}
210225511a47STejun Heo 
2103c8e55f36STejun Heo 	worker_leave_idle(worker);
2104db7bccf4STejun Heo recheck:
2105e22bee78STejun Heo 	/* no more worker necessary? */
210663d95a91STejun Heo 	if (!need_more_worker(pool))
2107e22bee78STejun Heo 		goto sleep;
2108e22bee78STejun Heo 
2109e22bee78STejun Heo 	/* do we need to manage? */
211063d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2111e22bee78STejun Heo 		goto recheck;
2112e22bee78STejun Heo 
2113c8e55f36STejun Heo 	/*
2114c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
2115c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
2116c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
2117c8e55f36STejun Heo 	 */
2118c8e55f36STejun Heo 	BUG_ON(!list_empty(&worker->scheduled));
2119c8e55f36STejun Heo 
2120e22bee78STejun Heo 	/*
2121e22bee78STejun Heo 	 * When control reaches this point, we're guaranteed to have
2122e22bee78STejun Heo 	 * at least one idle worker or that someone else has already
2123e22bee78STejun Heo 	 * assumed the manager role.
2124e22bee78STejun Heo 	 */
2125e22bee78STejun Heo 	worker_clr_flags(worker, WORKER_PREP);
2126e22bee78STejun Heo 
2127e22bee78STejun Heo 	do {
2128affee4b2STejun Heo 		struct work_struct *work =
2129bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
2130affee4b2STejun Heo 					 struct work_struct, entry);
2131affee4b2STejun Heo 
2132c8e55f36STejun Heo 		if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2133affee4b2STejun Heo 			/* optimization path, not strictly necessary */
2134affee4b2STejun Heo 			process_one_work(worker, work);
2135affee4b2STejun Heo 			if (unlikely(!list_empty(&worker->scheduled)))
2136affee4b2STejun Heo 				process_scheduled_works(worker);
2137affee4b2STejun Heo 		} else {
2138c8e55f36STejun Heo 			move_linked_works(work, &worker->scheduled, NULL);
2139affee4b2STejun Heo 			process_scheduled_works(worker);
2140affee4b2STejun Heo 		}
214163d95a91STejun Heo 	} while (keep_working(pool));
2142affee4b2STejun Heo 
2143e22bee78STejun Heo 	worker_set_flags(worker, WORKER_PREP, false);
2144d313dd85STejun Heo sleep:
214563d95a91STejun Heo 	if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
2146e22bee78STejun Heo 		goto recheck;
2147d313dd85STejun Heo 
2148c8e55f36STejun Heo 	/*
2149e22bee78STejun Heo 	 * gcwq->lock is held and there's no work to process and no
2150e22bee78STejun Heo 	 * need to manage, sleep.  Workers are woken up only while
2151e22bee78STejun Heo 	 * holding gcwq->lock or from local cpu, so setting the
2152e22bee78STejun Heo 	 * current state before releasing gcwq->lock is enough to
2153e22bee78STejun Heo 	 * prevent losing any event.
2154c8e55f36STejun Heo 	 */
2155c8e55f36STejun Heo 	worker_enter_idle(worker);
2156c8e55f36STejun Heo 	__set_current_state(TASK_INTERRUPTIBLE);
21578b03ae3cSTejun Heo 	spin_unlock_irq(&gcwq->lock);
21581da177e4SLinus Torvalds 	schedule();
2159c8e55f36STejun Heo 	goto woke_up;
21601da177e4SLinus Torvalds }
21611da177e4SLinus Torvalds 
2162e22bee78STejun Heo /**
2163e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
2164e22bee78STejun Heo  * @__wq: the associated workqueue
2165e22bee78STejun Heo  *
2166e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
2167e22bee78STejun Heo  * workqueue which has WQ_RESCUER set.
2168e22bee78STejun Heo  *
2169e22bee78STejun Heo  * Regular work processing on a gcwq may block trying to create a new
2170e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
2171e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
2172e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2173e22bee78STejun Heo  * the problem rescuer solves.
2174e22bee78STejun Heo  *
2175e22bee78STejun Heo  * When such condition is possible, the gcwq summons rescuers of all
2176e22bee78STejun Heo  * workqueues which have works queued on the gcwq and let them process
2177e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
2178e22bee78STejun Heo  *
2179e22bee78STejun Heo  * This should happen rarely.
2180e22bee78STejun Heo  */
2181e22bee78STejun Heo static int rescuer_thread(void *__wq)
2182e22bee78STejun Heo {
2183e22bee78STejun Heo 	struct workqueue_struct *wq = __wq;
2184e22bee78STejun Heo 	struct worker *rescuer = wq->rescuer;
2185e22bee78STejun Heo 	struct list_head *scheduled = &rescuer->scheduled;
2186f3421797STejun Heo 	bool is_unbound = wq->flags & WQ_UNBOUND;
2187e22bee78STejun Heo 	unsigned int cpu;
2188e22bee78STejun Heo 
2189e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
2190e22bee78STejun Heo repeat:
2191e22bee78STejun Heo 	set_current_state(TASK_INTERRUPTIBLE);
21921da177e4SLinus Torvalds 
21931da177e4SLinus Torvalds 	if (kthread_should_stop())
2194e22bee78STejun Heo 		return 0;
21951da177e4SLinus Torvalds 
2196f3421797STejun Heo 	/*
2197f3421797STejun Heo 	 * See whether any cpu is asking for help.  Unbounded
2198f3421797STejun Heo 	 * workqueues use cpu 0 in mayday_mask for CPU_UNBOUND.
2199f3421797STejun Heo 	 */
2200f2e005aaSTejun Heo 	for_each_mayday_cpu(cpu, wq->mayday_mask) {
2201f3421797STejun Heo 		unsigned int tcpu = is_unbound ? WORK_CPU_UNBOUND : cpu;
2202f3421797STejun Heo 		struct cpu_workqueue_struct *cwq = get_cwq(tcpu, wq);
2203bd7bdd43STejun Heo 		struct worker_pool *pool = cwq->pool;
2204bd7bdd43STejun Heo 		struct global_cwq *gcwq = pool->gcwq;
2205e22bee78STejun Heo 		struct work_struct *work, *n;
2206e22bee78STejun Heo 
2207e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
2208f2e005aaSTejun Heo 		mayday_clear_cpu(cpu, wq->mayday_mask);
2209e22bee78STejun Heo 
2210e22bee78STejun Heo 		/* migrate to the target cpu if possible */
2211bd7bdd43STejun Heo 		rescuer->pool = pool;
2212e22bee78STejun Heo 		worker_maybe_bind_and_lock(rescuer);
2213e22bee78STejun Heo 
2214e22bee78STejun Heo 		/*
2215e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
2216e22bee78STejun Heo 		 * process'em.
2217e22bee78STejun Heo 		 */
2218e22bee78STejun Heo 		BUG_ON(!list_empty(&rescuer->scheduled));
2219bd7bdd43STejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry)
2220e22bee78STejun Heo 			if (get_work_cwq(work) == cwq)
2221e22bee78STejun Heo 				move_linked_works(work, scheduled, &n);
2222e22bee78STejun Heo 
2223e22bee78STejun Heo 		process_scheduled_works(rescuer);
22247576958aSTejun Heo 
22257576958aSTejun Heo 		/*
22267576958aSTejun Heo 		 * Leave this gcwq.  If keep_working() is %true, notify a
22277576958aSTejun Heo 		 * regular worker; otherwise, we end up with 0 concurrency
22287576958aSTejun Heo 		 * and stalling the execution.
22297576958aSTejun Heo 		 */
223063d95a91STejun Heo 		if (keep_working(pool))
223163d95a91STejun Heo 			wake_up_worker(pool);
22327576958aSTejun Heo 
2233e22bee78STejun Heo 		spin_unlock_irq(&gcwq->lock);
22341da177e4SLinus Torvalds 	}
22351da177e4SLinus Torvalds 
2236e22bee78STejun Heo 	schedule();
2237e22bee78STejun Heo 	goto repeat;
22381da177e4SLinus Torvalds }
22391da177e4SLinus Torvalds 
2240fc2e4d70SOleg Nesterov struct wq_barrier {
2241fc2e4d70SOleg Nesterov 	struct work_struct	work;
2242fc2e4d70SOleg Nesterov 	struct completion	done;
2243fc2e4d70SOleg Nesterov };
2244fc2e4d70SOleg Nesterov 
2245fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
2246fc2e4d70SOleg Nesterov {
2247fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2248fc2e4d70SOleg Nesterov 	complete(&barr->done);
2249fc2e4d70SOleg Nesterov }
2250fc2e4d70SOleg Nesterov 
22514690c4abSTejun Heo /**
22524690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
22534690c4abSTejun Heo  * @cwq: cwq to insert barrier into
22544690c4abSTejun Heo  * @barr: wq_barrier to insert
2255affee4b2STejun Heo  * @target: target work to attach @barr to
2256affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
22574690c4abSTejun Heo  *
2258affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
2259affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
2260affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
2261affee4b2STejun Heo  * cpu.
2262affee4b2STejun Heo  *
2263affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
2264affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
2265affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
2266affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
2267affee4b2STejun Heo  * after a work with LINKED flag set.
2268affee4b2STejun Heo  *
2269affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
2270affee4b2STejun Heo  * underneath us, so we can't reliably determine cwq from @target.
22714690c4abSTejun Heo  *
22724690c4abSTejun Heo  * CONTEXT:
22738b03ae3cSTejun Heo  * spin_lock_irq(gcwq->lock).
22744690c4abSTejun Heo  */
227583c22520SOleg Nesterov static void insert_wq_barrier(struct cpu_workqueue_struct *cwq,
2276affee4b2STejun Heo 			      struct wq_barrier *barr,
2277affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
2278fc2e4d70SOleg Nesterov {
2279affee4b2STejun Heo 	struct list_head *head;
2280affee4b2STejun Heo 	unsigned int linked = 0;
2281affee4b2STejun Heo 
2282dc186ad7SThomas Gleixner 	/*
22838b03ae3cSTejun Heo 	 * debugobject calls are safe here even with gcwq->lock locked
2284dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
2285dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
2286dc186ad7SThomas Gleixner 	 * might deadlock.
2287dc186ad7SThomas Gleixner 	 */
2288ca1cab37SAndrew Morton 	INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
228922df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2290fc2e4d70SOleg Nesterov 	init_completion(&barr->done);
229183c22520SOleg Nesterov 
2292affee4b2STejun Heo 	/*
2293affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
2294affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
2295affee4b2STejun Heo 	 */
2296affee4b2STejun Heo 	if (worker)
2297affee4b2STejun Heo 		head = worker->scheduled.next;
2298affee4b2STejun Heo 	else {
2299affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
2300affee4b2STejun Heo 
2301affee4b2STejun Heo 		head = target->entry.next;
2302affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
2303affee4b2STejun Heo 		linked = *bits & WORK_STRUCT_LINKED;
2304affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
2305affee4b2STejun Heo 	}
2306affee4b2STejun Heo 
2307dc186ad7SThomas Gleixner 	debug_work_activate(&barr->work);
2308affee4b2STejun Heo 	insert_work(cwq, &barr->work, head,
2309affee4b2STejun Heo 		    work_color_to_flags(WORK_NO_COLOR) | linked);
2310fc2e4d70SOleg Nesterov }
2311fc2e4d70SOleg Nesterov 
231273f53c4aSTejun Heo /**
231373f53c4aSTejun Heo  * flush_workqueue_prep_cwqs - prepare cwqs for workqueue flushing
231473f53c4aSTejun Heo  * @wq: workqueue being flushed
231573f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
231673f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
231773f53c4aSTejun Heo  *
231873f53c4aSTejun Heo  * Prepare cwqs for workqueue flushing.
231973f53c4aSTejun Heo  *
232073f53c4aSTejun Heo  * If @flush_color is non-negative, flush_color on all cwqs should be
232173f53c4aSTejun Heo  * -1.  If no cwq has in-flight commands at the specified color, all
232273f53c4aSTejun Heo  * cwq->flush_color's stay at -1 and %false is returned.  If any cwq
232373f53c4aSTejun Heo  * has in flight commands, its cwq->flush_color is set to
232473f53c4aSTejun Heo  * @flush_color, @wq->nr_cwqs_to_flush is updated accordingly, cwq
232573f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
232673f53c4aSTejun Heo  *
232773f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
232873f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
232973f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
233073f53c4aSTejun Heo  * is returned.
233173f53c4aSTejun Heo  *
233273f53c4aSTejun Heo  * If @work_color is non-negative, all cwqs should have the same
233373f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
233473f53c4aSTejun Heo  * advanced to @work_color.
233573f53c4aSTejun Heo  *
233673f53c4aSTejun Heo  * CONTEXT:
233773f53c4aSTejun Heo  * mutex_lock(wq->flush_mutex).
233873f53c4aSTejun Heo  *
233973f53c4aSTejun Heo  * RETURNS:
234073f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
234173f53c4aSTejun Heo  * otherwise.
234273f53c4aSTejun Heo  */
234373f53c4aSTejun Heo static bool flush_workqueue_prep_cwqs(struct workqueue_struct *wq,
234473f53c4aSTejun Heo 				      int flush_color, int work_color)
23451da177e4SLinus Torvalds {
234673f53c4aSTejun Heo 	bool wait = false;
234773f53c4aSTejun Heo 	unsigned int cpu;
23481da177e4SLinus Torvalds 
234973f53c4aSTejun Heo 	if (flush_color >= 0) {
235073f53c4aSTejun Heo 		BUG_ON(atomic_read(&wq->nr_cwqs_to_flush));
235173f53c4aSTejun Heo 		atomic_set(&wq->nr_cwqs_to_flush, 1);
2352dc186ad7SThomas Gleixner 	}
235314441960SOleg Nesterov 
2354f3421797STejun Heo 	for_each_cwq_cpu(cpu, wq) {
235573f53c4aSTejun Heo 		struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2356bd7bdd43STejun Heo 		struct global_cwq *gcwq = cwq->pool->gcwq;
23571da177e4SLinus Torvalds 
23588b03ae3cSTejun Heo 		spin_lock_irq(&gcwq->lock);
235973f53c4aSTejun Heo 
236073f53c4aSTejun Heo 		if (flush_color >= 0) {
236173f53c4aSTejun Heo 			BUG_ON(cwq->flush_color != -1);
236273f53c4aSTejun Heo 
236373f53c4aSTejun Heo 			if (cwq->nr_in_flight[flush_color]) {
236473f53c4aSTejun Heo 				cwq->flush_color = flush_color;
236573f53c4aSTejun Heo 				atomic_inc(&wq->nr_cwqs_to_flush);
236673f53c4aSTejun Heo 				wait = true;
23671da177e4SLinus Torvalds 			}
236873f53c4aSTejun Heo 		}
236973f53c4aSTejun Heo 
237073f53c4aSTejun Heo 		if (work_color >= 0) {
237173f53c4aSTejun Heo 			BUG_ON(work_color != work_next_color(cwq->work_color));
237273f53c4aSTejun Heo 			cwq->work_color = work_color;
237373f53c4aSTejun Heo 		}
237473f53c4aSTejun Heo 
23758b03ae3cSTejun Heo 		spin_unlock_irq(&gcwq->lock);
23761da177e4SLinus Torvalds 	}
23771da177e4SLinus Torvalds 
237873f53c4aSTejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_cwqs_to_flush))
237973f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
238073f53c4aSTejun Heo 
238173f53c4aSTejun Heo 	return wait;
238283c22520SOleg Nesterov }
23831da177e4SLinus Torvalds 
23840fcb78c2SRolf Eike Beer /**
23851da177e4SLinus Torvalds  * flush_workqueue - ensure that any scheduled work has run to completion.
23860fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
23871da177e4SLinus Torvalds  *
23881da177e4SLinus Torvalds  * Forces execution of the workqueue and blocks until its completion.
23891da177e4SLinus Torvalds  * This is typically used in driver shutdown handlers.
23901da177e4SLinus Torvalds  *
2391fc2e4d70SOleg Nesterov  * We sleep until all works which were queued on entry have been handled,
2392fc2e4d70SOleg Nesterov  * but we are not livelocked by new incoming ones.
23931da177e4SLinus Torvalds  */
23947ad5b3a5SHarvey Harrison void flush_workqueue(struct workqueue_struct *wq)
23951da177e4SLinus Torvalds {
239673f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
239773f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
239873f53c4aSTejun Heo 		.flush_color = -1,
239973f53c4aSTejun Heo 		.done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
240073f53c4aSTejun Heo 	};
240173f53c4aSTejun Heo 	int next_color;
2402b1f4ec17SOleg Nesterov 
24033295f0efSIngo Molnar 	lock_map_acquire(&wq->lockdep_map);
24043295f0efSIngo Molnar 	lock_map_release(&wq->lockdep_map);
240573f53c4aSTejun Heo 
240673f53c4aSTejun Heo 	mutex_lock(&wq->flush_mutex);
240773f53c4aSTejun Heo 
240873f53c4aSTejun Heo 	/*
240973f53c4aSTejun Heo 	 * Start-to-wait phase
241073f53c4aSTejun Heo 	 */
241173f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
241273f53c4aSTejun Heo 
241373f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
241473f53c4aSTejun Heo 		/*
241573f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
241673f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
241773f53c4aSTejun Heo 		 * by one.
241873f53c4aSTejun Heo 		 */
241973f53c4aSTejun Heo 		BUG_ON(!list_empty(&wq->flusher_overflow));
242073f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
242173f53c4aSTejun Heo 		wq->work_color = next_color;
242273f53c4aSTejun Heo 
242373f53c4aSTejun Heo 		if (!wq->first_flusher) {
242473f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
242573f53c4aSTejun Heo 			BUG_ON(wq->flush_color != this_flusher.flush_color);
242673f53c4aSTejun Heo 
242773f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
242873f53c4aSTejun Heo 
242973f53c4aSTejun Heo 			if (!flush_workqueue_prep_cwqs(wq, wq->flush_color,
243073f53c4aSTejun Heo 						       wq->work_color)) {
243173f53c4aSTejun Heo 				/* nothing to flush, done */
243273f53c4aSTejun Heo 				wq->flush_color = next_color;
243373f53c4aSTejun Heo 				wq->first_flusher = NULL;
243473f53c4aSTejun Heo 				goto out_unlock;
243573f53c4aSTejun Heo 			}
243673f53c4aSTejun Heo 		} else {
243773f53c4aSTejun Heo 			/* wait in queue */
243873f53c4aSTejun Heo 			BUG_ON(wq->flush_color == this_flusher.flush_color);
243973f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
244073f53c4aSTejun Heo 			flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
244173f53c4aSTejun Heo 		}
244273f53c4aSTejun Heo 	} else {
244373f53c4aSTejun Heo 		/*
244473f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
244573f53c4aSTejun Heo 		 * The next flush completion will assign us
244673f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
244773f53c4aSTejun Heo 		 */
244873f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
244973f53c4aSTejun Heo 	}
245073f53c4aSTejun Heo 
245173f53c4aSTejun Heo 	mutex_unlock(&wq->flush_mutex);
245273f53c4aSTejun Heo 
245373f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
245473f53c4aSTejun Heo 
245573f53c4aSTejun Heo 	/*
245673f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
245773f53c4aSTejun Heo 	 *
245873f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
245973f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
246073f53c4aSTejun Heo 	 */
246173f53c4aSTejun Heo 	if (wq->first_flusher != &this_flusher)
246273f53c4aSTejun Heo 		return;
246373f53c4aSTejun Heo 
246473f53c4aSTejun Heo 	mutex_lock(&wq->flush_mutex);
246573f53c4aSTejun Heo 
24664ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
24674ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
24684ce48b37STejun Heo 		goto out_unlock;
24694ce48b37STejun Heo 
247073f53c4aSTejun Heo 	wq->first_flusher = NULL;
247173f53c4aSTejun Heo 
247273f53c4aSTejun Heo 	BUG_ON(!list_empty(&this_flusher.list));
247373f53c4aSTejun Heo 	BUG_ON(wq->flush_color != this_flusher.flush_color);
247473f53c4aSTejun Heo 
247573f53c4aSTejun Heo 	while (true) {
247673f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
247773f53c4aSTejun Heo 
247873f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
247973f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
248073f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
248173f53c4aSTejun Heo 				break;
248273f53c4aSTejun Heo 			list_del_init(&next->list);
248373f53c4aSTejun Heo 			complete(&next->done);
248473f53c4aSTejun Heo 		}
248573f53c4aSTejun Heo 
248673f53c4aSTejun Heo 		BUG_ON(!list_empty(&wq->flusher_overflow) &&
248773f53c4aSTejun Heo 		       wq->flush_color != work_next_color(wq->work_color));
248873f53c4aSTejun Heo 
248973f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
249073f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
249173f53c4aSTejun Heo 
249273f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
249373f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
249473f53c4aSTejun Heo 			/*
249573f53c4aSTejun Heo 			 * Assign the same color to all overflowed
249673f53c4aSTejun Heo 			 * flushers, advance work_color and append to
249773f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
249873f53c4aSTejun Heo 			 * phase for these overflowed flushers.
249973f53c4aSTejun Heo 			 */
250073f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
250173f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
250273f53c4aSTejun Heo 
250373f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
250473f53c4aSTejun Heo 
250573f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
250673f53c4aSTejun Heo 					      &wq->flusher_queue);
250773f53c4aSTejun Heo 			flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
250873f53c4aSTejun Heo 		}
250973f53c4aSTejun Heo 
251073f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
251173f53c4aSTejun Heo 			BUG_ON(wq->flush_color != wq->work_color);
251273f53c4aSTejun Heo 			break;
251373f53c4aSTejun Heo 		}
251473f53c4aSTejun Heo 
251573f53c4aSTejun Heo 		/*
251673f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
251773f53c4aSTejun Heo 		 * the new first flusher and arm cwqs.
251873f53c4aSTejun Heo 		 */
251973f53c4aSTejun Heo 		BUG_ON(wq->flush_color == wq->work_color);
252073f53c4aSTejun Heo 		BUG_ON(wq->flush_color != next->flush_color);
252173f53c4aSTejun Heo 
252273f53c4aSTejun Heo 		list_del_init(&next->list);
252373f53c4aSTejun Heo 		wq->first_flusher = next;
252473f53c4aSTejun Heo 
252573f53c4aSTejun Heo 		if (flush_workqueue_prep_cwqs(wq, wq->flush_color, -1))
252673f53c4aSTejun Heo 			break;
252773f53c4aSTejun Heo 
252873f53c4aSTejun Heo 		/*
252973f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
253073f53c4aSTejun Heo 		 * flusher and repeat cascading.
253173f53c4aSTejun Heo 		 */
253273f53c4aSTejun Heo 		wq->first_flusher = NULL;
253373f53c4aSTejun Heo 	}
253473f53c4aSTejun Heo 
253573f53c4aSTejun Heo out_unlock:
253673f53c4aSTejun Heo 	mutex_unlock(&wq->flush_mutex);
25371da177e4SLinus Torvalds }
2538ae90dd5dSDave Jones EXPORT_SYMBOL_GPL(flush_workqueue);
25391da177e4SLinus Torvalds 
25409c5a2ba7STejun Heo /**
25419c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
25429c5a2ba7STejun Heo  * @wq: workqueue to drain
25439c5a2ba7STejun Heo  *
25449c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
25459c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
25469c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
25479c5a2ba7STejun Heo  * repeatedly until it becomes empty.  The number of flushing is detemined
25489c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
25499c5a2ba7STejun Heo  * takes too long.
25509c5a2ba7STejun Heo  */
25519c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
25529c5a2ba7STejun Heo {
25539c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
25549c5a2ba7STejun Heo 	unsigned int cpu;
25559c5a2ba7STejun Heo 
25569c5a2ba7STejun Heo 	/*
25579c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
25589c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
25599c5a2ba7STejun Heo 	 * Use WQ_DRAINING so that queue doesn't have to check nr_drainers.
25609c5a2ba7STejun Heo 	 */
25619c5a2ba7STejun Heo 	spin_lock(&workqueue_lock);
25629c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
25639c5a2ba7STejun Heo 		wq->flags |= WQ_DRAINING;
25649c5a2ba7STejun Heo 	spin_unlock(&workqueue_lock);
25659c5a2ba7STejun Heo reflush:
25669c5a2ba7STejun Heo 	flush_workqueue(wq);
25679c5a2ba7STejun Heo 
25689c5a2ba7STejun Heo 	for_each_cwq_cpu(cpu, wq) {
25699c5a2ba7STejun Heo 		struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2570fa2563e4SThomas Tuttle 		bool drained;
25719c5a2ba7STejun Heo 
2572bd7bdd43STejun Heo 		spin_lock_irq(&cwq->pool->gcwq->lock);
2573fa2563e4SThomas Tuttle 		drained = !cwq->nr_active && list_empty(&cwq->delayed_works);
2574bd7bdd43STejun Heo 		spin_unlock_irq(&cwq->pool->gcwq->lock);
2575fa2563e4SThomas Tuttle 
2576fa2563e4SThomas Tuttle 		if (drained)
25779c5a2ba7STejun Heo 			continue;
25789c5a2ba7STejun Heo 
25799c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
25809c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
25819c5a2ba7STejun Heo 			pr_warning("workqueue %s: flush on destruction isn't complete after %u tries\n",
25829c5a2ba7STejun Heo 				   wq->name, flush_cnt);
25839c5a2ba7STejun Heo 		goto reflush;
25849c5a2ba7STejun Heo 	}
25859c5a2ba7STejun Heo 
25869c5a2ba7STejun Heo 	spin_lock(&workqueue_lock);
25879c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
25889c5a2ba7STejun Heo 		wq->flags &= ~WQ_DRAINING;
25899c5a2ba7STejun Heo 	spin_unlock(&workqueue_lock);
25909c5a2ba7STejun Heo }
25919c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
25929c5a2ba7STejun Heo 
2593baf59022STejun Heo static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
2594baf59022STejun Heo 			     bool wait_executing)
2595baf59022STejun Heo {
2596baf59022STejun Heo 	struct worker *worker = NULL;
2597baf59022STejun Heo 	struct global_cwq *gcwq;
2598baf59022STejun Heo 	struct cpu_workqueue_struct *cwq;
2599baf59022STejun Heo 
2600baf59022STejun Heo 	might_sleep();
2601baf59022STejun Heo 	gcwq = get_work_gcwq(work);
2602baf59022STejun Heo 	if (!gcwq)
2603baf59022STejun Heo 		return false;
2604baf59022STejun Heo 
2605baf59022STejun Heo 	spin_lock_irq(&gcwq->lock);
2606baf59022STejun Heo 	if (!list_empty(&work->entry)) {
2607baf59022STejun Heo 		/*
2608baf59022STejun Heo 		 * See the comment near try_to_grab_pending()->smp_rmb().
2609baf59022STejun Heo 		 * If it was re-queued to a different gcwq under us, we
2610baf59022STejun Heo 		 * are not going to wait.
2611baf59022STejun Heo 		 */
2612baf59022STejun Heo 		smp_rmb();
2613baf59022STejun Heo 		cwq = get_work_cwq(work);
2614bd7bdd43STejun Heo 		if (unlikely(!cwq || gcwq != cwq->pool->gcwq))
2615baf59022STejun Heo 			goto already_gone;
2616baf59022STejun Heo 	} else if (wait_executing) {
2617baf59022STejun Heo 		worker = find_worker_executing_work(gcwq, work);
2618baf59022STejun Heo 		if (!worker)
2619baf59022STejun Heo 			goto already_gone;
2620baf59022STejun Heo 		cwq = worker->current_cwq;
2621baf59022STejun Heo 	} else
2622baf59022STejun Heo 		goto already_gone;
2623baf59022STejun Heo 
2624baf59022STejun Heo 	insert_wq_barrier(cwq, barr, work, worker);
2625baf59022STejun Heo 	spin_unlock_irq(&gcwq->lock);
2626baf59022STejun Heo 
2627e159489bSTejun Heo 	/*
2628e159489bSTejun Heo 	 * If @max_active is 1 or rescuer is in use, flushing another work
2629e159489bSTejun Heo 	 * item on the same workqueue may lead to deadlock.  Make sure the
2630e159489bSTejun Heo 	 * flusher is not running on the same workqueue by verifying write
2631e159489bSTejun Heo 	 * access.
2632e159489bSTejun Heo 	 */
2633e159489bSTejun Heo 	if (cwq->wq->saved_max_active == 1 || cwq->wq->flags & WQ_RESCUER)
2634baf59022STejun Heo 		lock_map_acquire(&cwq->wq->lockdep_map);
2635e159489bSTejun Heo 	else
2636e159489bSTejun Heo 		lock_map_acquire_read(&cwq->wq->lockdep_map);
2637baf59022STejun Heo 	lock_map_release(&cwq->wq->lockdep_map);
2638e159489bSTejun Heo 
2639baf59022STejun Heo 	return true;
2640baf59022STejun Heo already_gone:
2641baf59022STejun Heo 	spin_unlock_irq(&gcwq->lock);
2642baf59022STejun Heo 	return false;
2643baf59022STejun Heo }
2644baf59022STejun Heo 
2645db700897SOleg Nesterov /**
2646401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
2647401a8d04STejun Heo  * @work: the work to flush
2648db700897SOleg Nesterov  *
2649401a8d04STejun Heo  * Wait until @work has finished execution.  This function considers
2650401a8d04STejun Heo  * only the last queueing instance of @work.  If @work has been
2651401a8d04STejun Heo  * enqueued across different CPUs on a non-reentrant workqueue or on
2652401a8d04STejun Heo  * multiple workqueues, @work might still be executing on return on
2653401a8d04STejun Heo  * some of the CPUs from earlier queueing.
2654a67da70dSOleg Nesterov  *
2655401a8d04STejun Heo  * If @work was queued only on a non-reentrant, ordered or unbound
2656401a8d04STejun Heo  * workqueue, @work is guaranteed to be idle on return if it hasn't
2657401a8d04STejun Heo  * been requeued since flush started.
2658401a8d04STejun Heo  *
2659401a8d04STejun Heo  * RETURNS:
2660401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
2661401a8d04STejun Heo  * %false if it was already idle.
2662db700897SOleg Nesterov  */
2663401a8d04STejun Heo bool flush_work(struct work_struct *work)
2664db700897SOleg Nesterov {
2665db700897SOleg Nesterov 	struct wq_barrier barr;
2666db700897SOleg Nesterov 
26670976dfc1SStephen Boyd 	lock_map_acquire(&work->lockdep_map);
26680976dfc1SStephen Boyd 	lock_map_release(&work->lockdep_map);
26690976dfc1SStephen Boyd 
2670baf59022STejun Heo 	if (start_flush_work(work, &barr, true)) {
2671db700897SOleg Nesterov 		wait_for_completion(&barr.done);
2672dc186ad7SThomas Gleixner 		destroy_work_on_stack(&barr.work);
2673401a8d04STejun Heo 		return true;
2674baf59022STejun Heo 	} else
2675401a8d04STejun Heo 		return false;
2676db700897SOleg Nesterov }
2677db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
2678db700897SOleg Nesterov 
2679401a8d04STejun Heo static bool wait_on_cpu_work(struct global_cwq *gcwq, struct work_struct *work)
2680401a8d04STejun Heo {
2681401a8d04STejun Heo 	struct wq_barrier barr;
2682401a8d04STejun Heo 	struct worker *worker;
2683401a8d04STejun Heo 
2684401a8d04STejun Heo 	spin_lock_irq(&gcwq->lock);
2685401a8d04STejun Heo 
2686401a8d04STejun Heo 	worker = find_worker_executing_work(gcwq, work);
2687401a8d04STejun Heo 	if (unlikely(worker))
2688401a8d04STejun Heo 		insert_wq_barrier(worker->current_cwq, &barr, work, worker);
2689401a8d04STejun Heo 
2690401a8d04STejun Heo 	spin_unlock_irq(&gcwq->lock);
2691401a8d04STejun Heo 
2692401a8d04STejun Heo 	if (unlikely(worker)) {
2693401a8d04STejun Heo 		wait_for_completion(&barr.done);
2694401a8d04STejun Heo 		destroy_work_on_stack(&barr.work);
2695401a8d04STejun Heo 		return true;
2696401a8d04STejun Heo 	} else
2697401a8d04STejun Heo 		return false;
2698401a8d04STejun Heo }
2699401a8d04STejun Heo 
2700401a8d04STejun Heo static bool wait_on_work(struct work_struct *work)
2701401a8d04STejun Heo {
2702401a8d04STejun Heo 	bool ret = false;
2703401a8d04STejun Heo 	int cpu;
2704401a8d04STejun Heo 
2705401a8d04STejun Heo 	might_sleep();
2706401a8d04STejun Heo 
2707401a8d04STejun Heo 	lock_map_acquire(&work->lockdep_map);
2708401a8d04STejun Heo 	lock_map_release(&work->lockdep_map);
2709401a8d04STejun Heo 
2710401a8d04STejun Heo 	for_each_gcwq_cpu(cpu)
2711401a8d04STejun Heo 		ret |= wait_on_cpu_work(get_gcwq(cpu), work);
2712401a8d04STejun Heo 	return ret;
2713401a8d04STejun Heo }
2714401a8d04STejun Heo 
271509383498STejun Heo /**
271609383498STejun Heo  * flush_work_sync - wait until a work has finished execution
271709383498STejun Heo  * @work: the work to flush
271809383498STejun Heo  *
271909383498STejun Heo  * Wait until @work has finished execution.  On return, it's
272009383498STejun Heo  * guaranteed that all queueing instances of @work which happened
272109383498STejun Heo  * before this function is called are finished.  In other words, if
272209383498STejun Heo  * @work hasn't been requeued since this function was called, @work is
272309383498STejun Heo  * guaranteed to be idle on return.
272409383498STejun Heo  *
272509383498STejun Heo  * RETURNS:
272609383498STejun Heo  * %true if flush_work_sync() waited for the work to finish execution,
272709383498STejun Heo  * %false if it was already idle.
272809383498STejun Heo  */
272909383498STejun Heo bool flush_work_sync(struct work_struct *work)
273009383498STejun Heo {
273109383498STejun Heo 	struct wq_barrier barr;
273209383498STejun Heo 	bool pending, waited;
273309383498STejun Heo 
273409383498STejun Heo 	/* we'll wait for executions separately, queue barr only if pending */
273509383498STejun Heo 	pending = start_flush_work(work, &barr, false);
273609383498STejun Heo 
273709383498STejun Heo 	/* wait for executions to finish */
273809383498STejun Heo 	waited = wait_on_work(work);
273909383498STejun Heo 
274009383498STejun Heo 	/* wait for the pending one */
274109383498STejun Heo 	if (pending) {
274209383498STejun Heo 		wait_for_completion(&barr.done);
274309383498STejun Heo 		destroy_work_on_stack(&barr.work);
274409383498STejun Heo 	}
274509383498STejun Heo 
274609383498STejun Heo 	return pending || waited;
274709383498STejun Heo }
274809383498STejun Heo EXPORT_SYMBOL_GPL(flush_work_sync);
274909383498STejun Heo 
27506e84d644SOleg Nesterov /*
27511f1f642eSOleg Nesterov  * Upon a successful return (>= 0), the caller "owns" WORK_STRUCT_PENDING bit,
27526e84d644SOleg Nesterov  * so this work can't be re-armed in any way.
27536e84d644SOleg Nesterov  */
27546e84d644SOleg Nesterov static int try_to_grab_pending(struct work_struct *work)
27556e84d644SOleg Nesterov {
27568b03ae3cSTejun Heo 	struct global_cwq *gcwq;
27571f1f642eSOleg Nesterov 	int ret = -1;
27586e84d644SOleg Nesterov 
275922df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
27601f1f642eSOleg Nesterov 		return 0;
27616e84d644SOleg Nesterov 
27626e84d644SOleg Nesterov 	/*
27636e84d644SOleg Nesterov 	 * The queueing is in progress, or it is already queued. Try to
27646e84d644SOleg Nesterov 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
27656e84d644SOleg Nesterov 	 */
27667a22ad75STejun Heo 	gcwq = get_work_gcwq(work);
27677a22ad75STejun Heo 	if (!gcwq)
27686e84d644SOleg Nesterov 		return ret;
27696e84d644SOleg Nesterov 
27708b03ae3cSTejun Heo 	spin_lock_irq(&gcwq->lock);
27716e84d644SOleg Nesterov 	if (!list_empty(&work->entry)) {
27726e84d644SOleg Nesterov 		/*
27737a22ad75STejun Heo 		 * This work is queued, but perhaps we locked the wrong gcwq.
27746e84d644SOleg Nesterov 		 * In that case we must see the new value after rmb(), see
27756e84d644SOleg Nesterov 		 * insert_work()->wmb().
27766e84d644SOleg Nesterov 		 */
27776e84d644SOleg Nesterov 		smp_rmb();
27787a22ad75STejun Heo 		if (gcwq == get_work_gcwq(work)) {
2779dc186ad7SThomas Gleixner 			debug_work_deactivate(work);
27806e84d644SOleg Nesterov 			list_del_init(&work->entry);
27817a22ad75STejun Heo 			cwq_dec_nr_in_flight(get_work_cwq(work),
27828a2e8e5dSTejun Heo 				get_work_color(work),
27838a2e8e5dSTejun Heo 				*work_data_bits(work) & WORK_STRUCT_DELAYED);
27846e84d644SOleg Nesterov 			ret = 1;
27856e84d644SOleg Nesterov 		}
27866e84d644SOleg Nesterov 	}
27878b03ae3cSTejun Heo 	spin_unlock_irq(&gcwq->lock);
27886e84d644SOleg Nesterov 
27896e84d644SOleg Nesterov 	return ret;
27906e84d644SOleg Nesterov }
27916e84d644SOleg Nesterov 
2792401a8d04STejun Heo static bool __cancel_work_timer(struct work_struct *work,
27931f1f642eSOleg Nesterov 				struct timer_list* timer)
27941f1f642eSOleg Nesterov {
27951f1f642eSOleg Nesterov 	int ret;
27961f1f642eSOleg Nesterov 
27971f1f642eSOleg Nesterov 	do {
27981f1f642eSOleg Nesterov 		ret = (timer && likely(del_timer(timer)));
27991f1f642eSOleg Nesterov 		if (!ret)
28001f1f642eSOleg Nesterov 			ret = try_to_grab_pending(work);
28011f1f642eSOleg Nesterov 		wait_on_work(work);
28021f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
28031f1f642eSOleg Nesterov 
28047a22ad75STejun Heo 	clear_work_data(work);
28051f1f642eSOleg Nesterov 	return ret;
28061f1f642eSOleg Nesterov }
28071f1f642eSOleg Nesterov 
28086e84d644SOleg Nesterov /**
2809401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
2810401a8d04STejun Heo  * @work: the work to cancel
28116e84d644SOleg Nesterov  *
2812401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
2813401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
2814401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
2815401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
28161f1f642eSOleg Nesterov  *
2817401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
2818401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
28196e84d644SOleg Nesterov  *
2820401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
28216e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
2822401a8d04STejun Heo  *
2823401a8d04STejun Heo  * RETURNS:
2824401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
28256e84d644SOleg Nesterov  */
2826401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
28276e84d644SOleg Nesterov {
28281f1f642eSOleg Nesterov 	return __cancel_work_timer(work, NULL);
2829b89deed3SOleg Nesterov }
283028e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
2831b89deed3SOleg Nesterov 
28326e84d644SOleg Nesterov /**
2833401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
2834401a8d04STejun Heo  * @dwork: the delayed work to flush
28356e84d644SOleg Nesterov  *
2836401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
2837401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
2838401a8d04STejun Heo  * considers the last queueing instance of @dwork.
28391f1f642eSOleg Nesterov  *
2840401a8d04STejun Heo  * RETURNS:
2841401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
2842401a8d04STejun Heo  * %false if it was already idle.
28436e84d644SOleg Nesterov  */
2844401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
2845401a8d04STejun Heo {
2846401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
2847401a8d04STejun Heo 		__queue_work(raw_smp_processor_id(),
2848401a8d04STejun Heo 			     get_work_cwq(&dwork->work)->wq, &dwork->work);
2849401a8d04STejun Heo 	return flush_work(&dwork->work);
2850401a8d04STejun Heo }
2851401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
2852401a8d04STejun Heo 
2853401a8d04STejun Heo /**
285409383498STejun Heo  * flush_delayed_work_sync - wait for a dwork to finish
285509383498STejun Heo  * @dwork: the delayed work to flush
285609383498STejun Heo  *
285709383498STejun Heo  * Delayed timer is cancelled and the pending work is queued for
285809383498STejun Heo  * execution immediately.  Other than timer handling, its behavior
285909383498STejun Heo  * is identical to flush_work_sync().
286009383498STejun Heo  *
286109383498STejun Heo  * RETURNS:
286209383498STejun Heo  * %true if flush_work_sync() waited for the work to finish execution,
286309383498STejun Heo  * %false if it was already idle.
286409383498STejun Heo  */
286509383498STejun Heo bool flush_delayed_work_sync(struct delayed_work *dwork)
286609383498STejun Heo {
286709383498STejun Heo 	if (del_timer_sync(&dwork->timer))
286809383498STejun Heo 		__queue_work(raw_smp_processor_id(),
286909383498STejun Heo 			     get_work_cwq(&dwork->work)->wq, &dwork->work);
287009383498STejun Heo 	return flush_work_sync(&dwork->work);
287109383498STejun Heo }
287209383498STejun Heo EXPORT_SYMBOL(flush_delayed_work_sync);
287309383498STejun Heo 
287409383498STejun Heo /**
2875401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2876401a8d04STejun Heo  * @dwork: the delayed work cancel
2877401a8d04STejun Heo  *
2878401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
2879401a8d04STejun Heo  *
2880401a8d04STejun Heo  * RETURNS:
2881401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
2882401a8d04STejun Heo  */
2883401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
28846e84d644SOleg Nesterov {
28851f1f642eSOleg Nesterov 	return __cancel_work_timer(&dwork->work, &dwork->timer);
28866e84d644SOleg Nesterov }
2887f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
28881da177e4SLinus Torvalds 
28890fcb78c2SRolf Eike Beer /**
28900fcb78c2SRolf Eike Beer  * schedule_work - put work task in global workqueue
28910fcb78c2SRolf Eike Beer  * @work: job to be done
28920fcb78c2SRolf Eike Beer  *
28935b0f437dSBart Van Assche  * Returns zero if @work was already on the kernel-global workqueue and
28945b0f437dSBart Van Assche  * non-zero otherwise.
28955b0f437dSBart Van Assche  *
28965b0f437dSBart Van Assche  * This puts a job in the kernel-global workqueue if it was not already
28975b0f437dSBart Van Assche  * queued and leaves it in the same position on the kernel-global
28985b0f437dSBart Van Assche  * workqueue otherwise.
28990fcb78c2SRolf Eike Beer  */
29007ad5b3a5SHarvey Harrison int schedule_work(struct work_struct *work)
29011da177e4SLinus Torvalds {
2902d320c038STejun Heo 	return queue_work(system_wq, work);
29031da177e4SLinus Torvalds }
2904ae90dd5dSDave Jones EXPORT_SYMBOL(schedule_work);
29051da177e4SLinus Torvalds 
2906c1a220e7SZhang Rui /*
2907c1a220e7SZhang Rui  * schedule_work_on - put work task on a specific cpu
2908c1a220e7SZhang Rui  * @cpu: cpu to put the work task on
2909c1a220e7SZhang Rui  * @work: job to be done
2910c1a220e7SZhang Rui  *
2911c1a220e7SZhang Rui  * This puts a job on a specific cpu
2912c1a220e7SZhang Rui  */
2913c1a220e7SZhang Rui int schedule_work_on(int cpu, struct work_struct *work)
2914c1a220e7SZhang Rui {
2915d320c038STejun Heo 	return queue_work_on(cpu, system_wq, work);
2916c1a220e7SZhang Rui }
2917c1a220e7SZhang Rui EXPORT_SYMBOL(schedule_work_on);
2918c1a220e7SZhang Rui 
29190fcb78c2SRolf Eike Beer /**
29200fcb78c2SRolf Eike Beer  * schedule_delayed_work - put work task in global workqueue after delay
292152bad64dSDavid Howells  * @dwork: job to be done
292252bad64dSDavid Howells  * @delay: number of jiffies to wait or 0 for immediate execution
29230fcb78c2SRolf Eike Beer  *
29240fcb78c2SRolf Eike Beer  * After waiting for a given time this puts a job in the kernel-global
29250fcb78c2SRolf Eike Beer  * workqueue.
29260fcb78c2SRolf Eike Beer  */
29277ad5b3a5SHarvey Harrison int schedule_delayed_work(struct delayed_work *dwork,
292882f67cd9SIngo Molnar 					unsigned long delay)
29291da177e4SLinus Torvalds {
2930d320c038STejun Heo 	return queue_delayed_work(system_wq, dwork, delay);
29311da177e4SLinus Torvalds }
2932ae90dd5dSDave Jones EXPORT_SYMBOL(schedule_delayed_work);
29331da177e4SLinus Torvalds 
29340fcb78c2SRolf Eike Beer /**
29350fcb78c2SRolf Eike Beer  * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
29360fcb78c2SRolf Eike Beer  * @cpu: cpu to use
293752bad64dSDavid Howells  * @dwork: job to be done
29380fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait
29390fcb78c2SRolf Eike Beer  *
29400fcb78c2SRolf Eike Beer  * After waiting for a given time this puts a job in the kernel-global
29410fcb78c2SRolf Eike Beer  * workqueue on the specified CPU.
29420fcb78c2SRolf Eike Beer  */
29431da177e4SLinus Torvalds int schedule_delayed_work_on(int cpu,
294452bad64dSDavid Howells 			struct delayed_work *dwork, unsigned long delay)
29451da177e4SLinus Torvalds {
2946d320c038STejun Heo 	return queue_delayed_work_on(cpu, system_wq, dwork, delay);
29471da177e4SLinus Torvalds }
2948ae90dd5dSDave Jones EXPORT_SYMBOL(schedule_delayed_work_on);
29491da177e4SLinus Torvalds 
2950b6136773SAndrew Morton /**
295131ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
2952b6136773SAndrew Morton  * @func: the function to call
2953b6136773SAndrew Morton  *
295431ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
295531ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
2956b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
295731ddd871STejun Heo  *
295831ddd871STejun Heo  * RETURNS:
295931ddd871STejun Heo  * 0 on success, -errno on failure.
2960b6136773SAndrew Morton  */
296165f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
296215316ba8SChristoph Lameter {
296315316ba8SChristoph Lameter 	int cpu;
296438f51568SNamhyung Kim 	struct work_struct __percpu *works;
296515316ba8SChristoph Lameter 
2966b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
2967b6136773SAndrew Morton 	if (!works)
296815316ba8SChristoph Lameter 		return -ENOMEM;
2969b6136773SAndrew Morton 
297095402b38SGautham R Shenoy 	get_online_cpus();
297193981800STejun Heo 
297215316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
29739bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
29749bfb1839SIngo Molnar 
29759bfb1839SIngo Molnar 		INIT_WORK(work, func);
29768de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
297715316ba8SChristoph Lameter 	}
297893981800STejun Heo 
297993981800STejun Heo 	for_each_online_cpu(cpu)
29808616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
298193981800STejun Heo 
298295402b38SGautham R Shenoy 	put_online_cpus();
2983b6136773SAndrew Morton 	free_percpu(works);
298415316ba8SChristoph Lameter 	return 0;
298515316ba8SChristoph Lameter }
298615316ba8SChristoph Lameter 
2987eef6a7d5SAlan Stern /**
2988eef6a7d5SAlan Stern  * flush_scheduled_work - ensure that any scheduled work has run to completion.
2989eef6a7d5SAlan Stern  *
2990eef6a7d5SAlan Stern  * Forces execution of the kernel-global workqueue and blocks until its
2991eef6a7d5SAlan Stern  * completion.
2992eef6a7d5SAlan Stern  *
2993eef6a7d5SAlan Stern  * Think twice before calling this function!  It's very easy to get into
2994eef6a7d5SAlan Stern  * trouble if you don't take great care.  Either of the following situations
2995eef6a7d5SAlan Stern  * will lead to deadlock:
2996eef6a7d5SAlan Stern  *
2997eef6a7d5SAlan Stern  *	One of the work items currently on the workqueue needs to acquire
2998eef6a7d5SAlan Stern  *	a lock held by your code or its caller.
2999eef6a7d5SAlan Stern  *
3000eef6a7d5SAlan Stern  *	Your code is running in the context of a work routine.
3001eef6a7d5SAlan Stern  *
3002eef6a7d5SAlan Stern  * They will be detected by lockdep when they occur, but the first might not
3003eef6a7d5SAlan Stern  * occur very often.  It depends on what work items are on the workqueue and
3004eef6a7d5SAlan Stern  * what locks they need, which you have no control over.
3005eef6a7d5SAlan Stern  *
3006eef6a7d5SAlan Stern  * In most situations flushing the entire workqueue is overkill; you merely
3007eef6a7d5SAlan Stern  * need to know that a particular work item isn't queued and isn't running.
3008eef6a7d5SAlan Stern  * In such cases you should use cancel_delayed_work_sync() or
3009eef6a7d5SAlan Stern  * cancel_work_sync() instead.
3010eef6a7d5SAlan Stern  */
30111da177e4SLinus Torvalds void flush_scheduled_work(void)
30121da177e4SLinus Torvalds {
3013d320c038STejun Heo 	flush_workqueue(system_wq);
30141da177e4SLinus Torvalds }
3015ae90dd5dSDave Jones EXPORT_SYMBOL(flush_scheduled_work);
30161da177e4SLinus Torvalds 
30171da177e4SLinus Torvalds /**
30181fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
30191fa44ecaSJames Bottomley  * @fn:		the function to execute
30201fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
30211fa44ecaSJames Bottomley  *		be available when the work executes)
30221fa44ecaSJames Bottomley  *
30231fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
30241fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
30251fa44ecaSJames Bottomley  *
30261fa44ecaSJames Bottomley  * Returns:	0 - function was executed
30271fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
30281fa44ecaSJames Bottomley  */
302965f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
30301fa44ecaSJames Bottomley {
30311fa44ecaSJames Bottomley 	if (!in_interrupt()) {
303265f27f38SDavid Howells 		fn(&ew->work);
30331fa44ecaSJames Bottomley 		return 0;
30341fa44ecaSJames Bottomley 	}
30351fa44ecaSJames Bottomley 
303665f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
30371fa44ecaSJames Bottomley 	schedule_work(&ew->work);
30381fa44ecaSJames Bottomley 
30391fa44ecaSJames Bottomley 	return 1;
30401fa44ecaSJames Bottomley }
30411fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
30421fa44ecaSJames Bottomley 
30431da177e4SLinus Torvalds int keventd_up(void)
30441da177e4SLinus Torvalds {
3045d320c038STejun Heo 	return system_wq != NULL;
30461da177e4SLinus Torvalds }
30471da177e4SLinus Torvalds 
3048bdbc5dd7STejun Heo static int alloc_cwqs(struct workqueue_struct *wq)
30491da177e4SLinus Torvalds {
30503af24433SOleg Nesterov 	/*
30510f900049STejun Heo 	 * cwqs are forced aligned according to WORK_STRUCT_FLAG_BITS.
30520f900049STejun Heo 	 * Make sure that the alignment isn't lower than that of
30530f900049STejun Heo 	 * unsigned long long.
30543af24433SOleg Nesterov 	 */
30550f900049STejun Heo 	const size_t size = sizeof(struct cpu_workqueue_struct);
30560f900049STejun Heo 	const size_t align = max_t(size_t, 1 << WORK_STRUCT_FLAG_BITS,
30570f900049STejun Heo 				   __alignof__(unsigned long long));
30583af24433SOleg Nesterov 
3059e06ffa1eSLai Jiangshan 	if (!(wq->flags & WQ_UNBOUND))
3060f3421797STejun Heo 		wq->cpu_wq.pcpu = __alloc_percpu(size, align);
3061931ac77eSTejun Heo 	else {
30620f900049STejun Heo 		void *ptr;
3063e1d8aa9fSFrederic Weisbecker 
30640f900049STejun Heo 		/*
3065f3421797STejun Heo 		 * Allocate enough room to align cwq and put an extra
3066f3421797STejun Heo 		 * pointer at the end pointing back to the originally
3067f3421797STejun Heo 		 * allocated pointer which will be used for free.
30680f900049STejun Heo 		 */
3069bdbc5dd7STejun Heo 		ptr = kzalloc(size + align + sizeof(void *), GFP_KERNEL);
3070bdbc5dd7STejun Heo 		if (ptr) {
3071bdbc5dd7STejun Heo 			wq->cpu_wq.single = PTR_ALIGN(ptr, align);
3072bdbc5dd7STejun Heo 			*(void **)(wq->cpu_wq.single + 1) = ptr;
3073bdbc5dd7STejun Heo 		}
30743af24433SOleg Nesterov 	}
30753af24433SOleg Nesterov 
30760415b00dSTejun Heo 	/* just in case, make sure it's actually aligned */
3077bdbc5dd7STejun Heo 	BUG_ON(!IS_ALIGNED(wq->cpu_wq.v, align));
3078bdbc5dd7STejun Heo 	return wq->cpu_wq.v ? 0 : -ENOMEM;
30790f900049STejun Heo }
30800f900049STejun Heo 
3081bdbc5dd7STejun Heo static void free_cwqs(struct workqueue_struct *wq)
308206ba38a9SOleg Nesterov {
3083e06ffa1eSLai Jiangshan 	if (!(wq->flags & WQ_UNBOUND))
3084bdbc5dd7STejun Heo 		free_percpu(wq->cpu_wq.pcpu);
3085f3421797STejun Heo 	else if (wq->cpu_wq.single) {
3086f3421797STejun Heo 		/* the pointer to free is stored right after the cwq */
3087f3421797STejun Heo 		kfree(*(void **)(wq->cpu_wq.single + 1));
308806ba38a9SOleg Nesterov 	}
308906ba38a9SOleg Nesterov }
309006ba38a9SOleg Nesterov 
3091f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
3092f3421797STejun Heo 			       const char *name)
3093b71ab8c2STejun Heo {
3094f3421797STejun Heo 	int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3095f3421797STejun Heo 
3096f3421797STejun Heo 	if (max_active < 1 || max_active > lim)
3097b71ab8c2STejun Heo 		printk(KERN_WARNING "workqueue: max_active %d requested for %s "
3098b71ab8c2STejun Heo 		       "is out of range, clamping between %d and %d\n",
3099f3421797STejun Heo 		       max_active, name, 1, lim);
3100b71ab8c2STejun Heo 
3101f3421797STejun Heo 	return clamp_val(max_active, 1, lim);
3102b71ab8c2STejun Heo }
3103b71ab8c2STejun Heo 
3104b196be89STejun Heo struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
310597e37d7bSTejun Heo 					       unsigned int flags,
31061e19ffc6STejun Heo 					       int max_active,
3107eb13ba87SJohannes Berg 					       struct lock_class_key *key,
3108b196be89STejun Heo 					       const char *lock_name, ...)
31093af24433SOleg Nesterov {
3110b196be89STejun Heo 	va_list args, args1;
31113af24433SOleg Nesterov 	struct workqueue_struct *wq;
3112c34056a3STejun Heo 	unsigned int cpu;
3113b196be89STejun Heo 	size_t namelen;
3114b196be89STejun Heo 
3115b196be89STejun Heo 	/* determine namelen, allocate wq and format name */
3116b196be89STejun Heo 	va_start(args, lock_name);
3117b196be89STejun Heo 	va_copy(args1, args);
3118b196be89STejun Heo 	namelen = vsnprintf(NULL, 0, fmt, args) + 1;
3119b196be89STejun Heo 
3120b196be89STejun Heo 	wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
3121b196be89STejun Heo 	if (!wq)
3122b196be89STejun Heo 		goto err;
3123b196be89STejun Heo 
3124b196be89STejun Heo 	vsnprintf(wq->name, namelen, fmt, args1);
3125b196be89STejun Heo 	va_end(args);
3126b196be89STejun Heo 	va_end(args1);
31273af24433SOleg Nesterov 
3128f3421797STejun Heo 	/*
31296370a6adSTejun Heo 	 * Workqueues which may be used during memory reclaim should
31306370a6adSTejun Heo 	 * have a rescuer to guarantee forward progress.
31316370a6adSTejun Heo 	 */
31326370a6adSTejun Heo 	if (flags & WQ_MEM_RECLAIM)
31336370a6adSTejun Heo 		flags |= WQ_RESCUER;
31346370a6adSTejun Heo 
3135d320c038STejun Heo 	max_active = max_active ?: WQ_DFL_ACTIVE;
3136b196be89STejun Heo 	max_active = wq_clamp_max_active(max_active, flags, wq->name);
31373af24433SOleg Nesterov 
3138b196be89STejun Heo 	/* init wq */
313997e37d7bSTejun Heo 	wq->flags = flags;
3140a0a1a5fdSTejun Heo 	wq->saved_max_active = max_active;
314173f53c4aSTejun Heo 	mutex_init(&wq->flush_mutex);
314273f53c4aSTejun Heo 	atomic_set(&wq->nr_cwqs_to_flush, 0);
314373f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
314473f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
31453af24433SOleg Nesterov 
3146eb13ba87SJohannes Berg 	lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3147cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
31483af24433SOleg Nesterov 
3149bdbc5dd7STejun Heo 	if (alloc_cwqs(wq) < 0)
3150bdbc5dd7STejun Heo 		goto err;
3151bdbc5dd7STejun Heo 
3152f3421797STejun Heo 	for_each_cwq_cpu(cpu, wq) {
31531537663fSTejun Heo 		struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
31548b03ae3cSTejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
31553270476aSTejun Heo 		int pool_idx = (bool)(flags & WQ_HIGHPRI);
31561537663fSTejun Heo 
31570f900049STejun Heo 		BUG_ON((unsigned long)cwq & WORK_STRUCT_FLAG_MASK);
31583270476aSTejun Heo 		cwq->pool = &gcwq->pools[pool_idx];
3159c34056a3STejun Heo 		cwq->wq = wq;
316073f53c4aSTejun Heo 		cwq->flush_color = -1;
31611e19ffc6STejun Heo 		cwq->max_active = max_active;
31621e19ffc6STejun Heo 		INIT_LIST_HEAD(&cwq->delayed_works);
3163e22bee78STejun Heo 	}
31641537663fSTejun Heo 
3165e22bee78STejun Heo 	if (flags & WQ_RESCUER) {
3166e22bee78STejun Heo 		struct worker *rescuer;
3167e22bee78STejun Heo 
3168f2e005aaSTejun Heo 		if (!alloc_mayday_mask(&wq->mayday_mask, GFP_KERNEL))
3169e22bee78STejun Heo 			goto err;
3170e22bee78STejun Heo 
3171e22bee78STejun Heo 		wq->rescuer = rescuer = alloc_worker();
3172e22bee78STejun Heo 		if (!rescuer)
3173e22bee78STejun Heo 			goto err;
3174e22bee78STejun Heo 
3175b196be89STejun Heo 		rescuer->task = kthread_create(rescuer_thread, wq, "%s",
3176b196be89STejun Heo 					       wq->name);
3177e22bee78STejun Heo 		if (IS_ERR(rescuer->task))
3178e22bee78STejun Heo 			goto err;
3179e22bee78STejun Heo 
3180e22bee78STejun Heo 		rescuer->task->flags |= PF_THREAD_BOUND;
3181e22bee78STejun Heo 		wake_up_process(rescuer->task);
31823af24433SOleg Nesterov 	}
31831537663fSTejun Heo 
31843af24433SOleg Nesterov 	/*
3185a0a1a5fdSTejun Heo 	 * workqueue_lock protects global freeze state and workqueues
3186a0a1a5fdSTejun Heo 	 * list.  Grab it, set max_active accordingly and add the new
3187a0a1a5fdSTejun Heo 	 * workqueue to workqueues list.
31883af24433SOleg Nesterov 	 */
31893af24433SOleg Nesterov 	spin_lock(&workqueue_lock);
3190a0a1a5fdSTejun Heo 
319158a69cb4STejun Heo 	if (workqueue_freezing && wq->flags & WQ_FREEZABLE)
3192f3421797STejun Heo 		for_each_cwq_cpu(cpu, wq)
3193a0a1a5fdSTejun Heo 			get_cwq(cpu, wq)->max_active = 0;
3194a0a1a5fdSTejun Heo 
31953af24433SOleg Nesterov 	list_add(&wq->list, &workqueues);
3196a0a1a5fdSTejun Heo 
31973af24433SOleg Nesterov 	spin_unlock(&workqueue_lock);
31983af24433SOleg Nesterov 
31993af24433SOleg Nesterov 	return wq;
32004690c4abSTejun Heo err:
32014690c4abSTejun Heo 	if (wq) {
3202bdbc5dd7STejun Heo 		free_cwqs(wq);
3203f2e005aaSTejun Heo 		free_mayday_mask(wq->mayday_mask);
3204e22bee78STejun Heo 		kfree(wq->rescuer);
32054690c4abSTejun Heo 		kfree(wq);
32063af24433SOleg Nesterov 	}
32074690c4abSTejun Heo 	return NULL;
32081da177e4SLinus Torvalds }
3209d320c038STejun Heo EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
32101da177e4SLinus Torvalds 
32113af24433SOleg Nesterov /**
32123af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
32133af24433SOleg Nesterov  * @wq: target workqueue
32143af24433SOleg Nesterov  *
32153af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
32163af24433SOleg Nesterov  */
32173af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
32183af24433SOleg Nesterov {
3219c8e55f36STejun Heo 	unsigned int cpu;
32203af24433SOleg Nesterov 
32219c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
32229c5a2ba7STejun Heo 	drain_workqueue(wq);
3223c8efcc25STejun Heo 
3224a0a1a5fdSTejun Heo 	/*
3225a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
3226a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
3227a0a1a5fdSTejun Heo 	 */
322895402b38SGautham R Shenoy 	spin_lock(&workqueue_lock);
32293af24433SOleg Nesterov 	list_del(&wq->list);
323095402b38SGautham R Shenoy 	spin_unlock(&workqueue_lock);
32313af24433SOleg Nesterov 
3232e22bee78STejun Heo 	/* sanity check */
3233f3421797STejun Heo 	for_each_cwq_cpu(cpu, wq) {
323473f53c4aSTejun Heo 		struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
323573f53c4aSTejun Heo 		int i;
32363af24433SOleg Nesterov 
323773f53c4aSTejun Heo 		for (i = 0; i < WORK_NR_COLORS; i++)
323873f53c4aSTejun Heo 			BUG_ON(cwq->nr_in_flight[i]);
32391e19ffc6STejun Heo 		BUG_ON(cwq->nr_active);
32401e19ffc6STejun Heo 		BUG_ON(!list_empty(&cwq->delayed_works));
324173f53c4aSTejun Heo 	}
32421537663fSTejun Heo 
3243e22bee78STejun Heo 	if (wq->flags & WQ_RESCUER) {
3244e22bee78STejun Heo 		kthread_stop(wq->rescuer->task);
3245f2e005aaSTejun Heo 		free_mayday_mask(wq->mayday_mask);
32468d9df9f0SXiaotian Feng 		kfree(wq->rescuer);
3247e22bee78STejun Heo 	}
3248e22bee78STejun Heo 
3249bdbc5dd7STejun Heo 	free_cwqs(wq);
32503af24433SOleg Nesterov 	kfree(wq);
32513af24433SOleg Nesterov }
32523af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
32533af24433SOleg Nesterov 
3254dcd989cbSTejun Heo /**
3255dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
3256dcd989cbSTejun Heo  * @wq: target workqueue
3257dcd989cbSTejun Heo  * @max_active: new max_active value.
3258dcd989cbSTejun Heo  *
3259dcd989cbSTejun Heo  * Set max_active of @wq to @max_active.
3260dcd989cbSTejun Heo  *
3261dcd989cbSTejun Heo  * CONTEXT:
3262dcd989cbSTejun Heo  * Don't call from IRQ context.
3263dcd989cbSTejun Heo  */
3264dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
3265dcd989cbSTejun Heo {
3266dcd989cbSTejun Heo 	unsigned int cpu;
3267dcd989cbSTejun Heo 
3268f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
3269dcd989cbSTejun Heo 
3270dcd989cbSTejun Heo 	spin_lock(&workqueue_lock);
3271dcd989cbSTejun Heo 
3272dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
3273dcd989cbSTejun Heo 
3274f3421797STejun Heo 	for_each_cwq_cpu(cpu, wq) {
3275dcd989cbSTejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
3276dcd989cbSTejun Heo 
3277dcd989cbSTejun Heo 		spin_lock_irq(&gcwq->lock);
3278dcd989cbSTejun Heo 
327958a69cb4STejun Heo 		if (!(wq->flags & WQ_FREEZABLE) ||
3280dcd989cbSTejun Heo 		    !(gcwq->flags & GCWQ_FREEZING))
3281dcd989cbSTejun Heo 			get_cwq(gcwq->cpu, wq)->max_active = max_active;
3282dcd989cbSTejun Heo 
3283dcd989cbSTejun Heo 		spin_unlock_irq(&gcwq->lock);
3284dcd989cbSTejun Heo 	}
3285dcd989cbSTejun Heo 
3286dcd989cbSTejun Heo 	spin_unlock(&workqueue_lock);
3287dcd989cbSTejun Heo }
3288dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
3289dcd989cbSTejun Heo 
3290dcd989cbSTejun Heo /**
3291dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
3292dcd989cbSTejun Heo  * @cpu: CPU in question
3293dcd989cbSTejun Heo  * @wq: target workqueue
3294dcd989cbSTejun Heo  *
3295dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
3296dcd989cbSTejun Heo  * no synchronization around this function and the test result is
3297dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
3298dcd989cbSTejun Heo  *
3299dcd989cbSTejun Heo  * RETURNS:
3300dcd989cbSTejun Heo  * %true if congested, %false otherwise.
3301dcd989cbSTejun Heo  */
3302dcd989cbSTejun Heo bool workqueue_congested(unsigned int cpu, struct workqueue_struct *wq)
3303dcd989cbSTejun Heo {
3304dcd989cbSTejun Heo 	struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3305dcd989cbSTejun Heo 
3306dcd989cbSTejun Heo 	return !list_empty(&cwq->delayed_works);
3307dcd989cbSTejun Heo }
3308dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
3309dcd989cbSTejun Heo 
3310dcd989cbSTejun Heo /**
3311dcd989cbSTejun Heo  * work_cpu - return the last known associated cpu for @work
3312dcd989cbSTejun Heo  * @work: the work of interest
3313dcd989cbSTejun Heo  *
3314dcd989cbSTejun Heo  * RETURNS:
3315bdbc5dd7STejun Heo  * CPU number if @work was ever queued.  WORK_CPU_NONE otherwise.
3316dcd989cbSTejun Heo  */
3317dcd989cbSTejun Heo unsigned int work_cpu(struct work_struct *work)
3318dcd989cbSTejun Heo {
3319dcd989cbSTejun Heo 	struct global_cwq *gcwq = get_work_gcwq(work);
3320dcd989cbSTejun Heo 
3321bdbc5dd7STejun Heo 	return gcwq ? gcwq->cpu : WORK_CPU_NONE;
3322dcd989cbSTejun Heo }
3323dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_cpu);
3324dcd989cbSTejun Heo 
3325dcd989cbSTejun Heo /**
3326dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
3327dcd989cbSTejun Heo  * @work: the work to be tested
3328dcd989cbSTejun Heo  *
3329dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
3330dcd989cbSTejun Heo  * synchronization around this function and the test result is
3331dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
3332dcd989cbSTejun Heo  * Especially for reentrant wqs, the pending state might hide the
3333dcd989cbSTejun Heo  * running state.
3334dcd989cbSTejun Heo  *
3335dcd989cbSTejun Heo  * RETURNS:
3336dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
3337dcd989cbSTejun Heo  */
3338dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
3339dcd989cbSTejun Heo {
3340dcd989cbSTejun Heo 	struct global_cwq *gcwq = get_work_gcwq(work);
3341dcd989cbSTejun Heo 	unsigned long flags;
3342dcd989cbSTejun Heo 	unsigned int ret = 0;
3343dcd989cbSTejun Heo 
3344dcd989cbSTejun Heo 	if (!gcwq)
3345dcd989cbSTejun Heo 		return false;
3346dcd989cbSTejun Heo 
3347dcd989cbSTejun Heo 	spin_lock_irqsave(&gcwq->lock, flags);
3348dcd989cbSTejun Heo 
3349dcd989cbSTejun Heo 	if (work_pending(work))
3350dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
3351dcd989cbSTejun Heo 	if (find_worker_executing_work(gcwq, work))
3352dcd989cbSTejun Heo 		ret |= WORK_BUSY_RUNNING;
3353dcd989cbSTejun Heo 
3354dcd989cbSTejun Heo 	spin_unlock_irqrestore(&gcwq->lock, flags);
3355dcd989cbSTejun Heo 
3356dcd989cbSTejun Heo 	return ret;
3357dcd989cbSTejun Heo }
3358dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
3359dcd989cbSTejun Heo 
3360db7bccf4STejun Heo /*
3361db7bccf4STejun Heo  * CPU hotplug.
3362db7bccf4STejun Heo  *
3363e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
3364e22bee78STejun Heo  * are a lot of assumptions on strong associations among work, cwq and
3365e22bee78STejun Heo  * gcwq which make migrating pending and scheduled works very
3366e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
3367e22bee78STejun Heo  * gcwqs serve mix of short, long and very long running works making
3368e22bee78STejun Heo  * blocked draining impractical.
3369e22bee78STejun Heo  *
3370403c821dSTejun Heo  * This is solved by allowing a gcwq to be detached from CPU, running it
3371403c821dSTejun Heo  * with unbound workers and allowing it to be reattached later if the cpu
3372403c821dSTejun Heo  * comes back online.  A separate thread is created to govern a gcwq in
3373403c821dSTejun Heo  * such state and is called the trustee of the gcwq.
3374db7bccf4STejun Heo  *
3375db7bccf4STejun Heo  * Trustee states and their descriptions.
3376db7bccf4STejun Heo  *
3377db7bccf4STejun Heo  * START	Command state used on startup.  On CPU_DOWN_PREPARE, a
3378db7bccf4STejun Heo  *		new trustee is started with this state.
3379db7bccf4STejun Heo  *
3380db7bccf4STejun Heo  * IN_CHARGE	Once started, trustee will enter this state after
3381e22bee78STejun Heo  *		assuming the manager role and making all existing
3382e22bee78STejun Heo  *		workers rogue.  DOWN_PREPARE waits for trustee to
3383e22bee78STejun Heo  *		enter this state.  After reaching IN_CHARGE, trustee
3384e22bee78STejun Heo  *		tries to execute the pending worklist until it's empty
3385e22bee78STejun Heo  *		and the state is set to BUTCHER, or the state is set
3386e22bee78STejun Heo  *		to RELEASE.
3387db7bccf4STejun Heo  *
3388db7bccf4STejun Heo  * BUTCHER	Command state which is set by the cpu callback after
3389db7bccf4STejun Heo  *		the cpu has went down.  Once this state is set trustee
3390db7bccf4STejun Heo  *		knows that there will be no new works on the worklist
3391db7bccf4STejun Heo  *		and once the worklist is empty it can proceed to
3392db7bccf4STejun Heo  *		killing idle workers.
3393db7bccf4STejun Heo  *
3394db7bccf4STejun Heo  * RELEASE	Command state which is set by the cpu callback if the
3395db7bccf4STejun Heo  *		cpu down has been canceled or it has come online
3396db7bccf4STejun Heo  *		again.  After recognizing this state, trustee stops
3397e22bee78STejun Heo  *		trying to drain or butcher and clears ROGUE, rebinds
3398e22bee78STejun Heo  *		all remaining workers back to the cpu and releases
3399e22bee78STejun Heo  *		manager role.
3400db7bccf4STejun Heo  *
3401db7bccf4STejun Heo  * DONE		Trustee will enter this state after BUTCHER or RELEASE
3402db7bccf4STejun Heo  *		is complete.
3403db7bccf4STejun Heo  *
3404db7bccf4STejun Heo  *          trustee                 CPU                draining
3405db7bccf4STejun Heo  *         took over                down               complete
3406db7bccf4STejun Heo  * START -----------> IN_CHARGE -----------> BUTCHER -----------> DONE
3407db7bccf4STejun Heo  *                        |                     |                  ^
3408db7bccf4STejun Heo  *                        | CPU is back online  v   return workers |
3409db7bccf4STejun Heo  *                         ----------------> RELEASE --------------
3410db7bccf4STejun Heo  */
3411db7bccf4STejun Heo 
341260373152STejun Heo /* claim manager positions of all pools */
341360373152STejun Heo static void gcwq_claim_management(struct global_cwq *gcwq)
341460373152STejun Heo {
341560373152STejun Heo 	struct worker_pool *pool;
341660373152STejun Heo 
341760373152STejun Heo 	for_each_worker_pool(pool, gcwq)
341860373152STejun Heo 		mutex_lock_nested(&pool->manager_mutex, pool - gcwq->pools);
341960373152STejun Heo }
342060373152STejun Heo 
342160373152STejun Heo /* release manager positions */
342260373152STejun Heo static void gcwq_release_management(struct global_cwq *gcwq)
342360373152STejun Heo {
342460373152STejun Heo 	struct worker_pool *pool;
342560373152STejun Heo 
342660373152STejun Heo 	for_each_worker_pool(pool, gcwq)
342760373152STejun Heo 		mutex_unlock(&pool->manager_mutex);
342860373152STejun Heo }
342960373152STejun Heo 
3430db7bccf4STejun Heo /**
3431db7bccf4STejun Heo  * trustee_wait_event_timeout - timed event wait for trustee
3432db7bccf4STejun Heo  * @cond: condition to wait for
3433db7bccf4STejun Heo  * @timeout: timeout in jiffies
3434db7bccf4STejun Heo  *
3435db7bccf4STejun Heo  * wait_event_timeout() for trustee to use.  Handles locking and
3436db7bccf4STejun Heo  * checks for RELEASE request.
3437db7bccf4STejun Heo  *
3438db7bccf4STejun Heo  * CONTEXT:
3439db7bccf4STejun Heo  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
3440db7bccf4STejun Heo  * multiple times.  To be used by trustee.
3441db7bccf4STejun Heo  *
3442db7bccf4STejun Heo  * RETURNS:
3443db7bccf4STejun Heo  * Positive indicating left time if @cond is satisfied, 0 if timed
3444db7bccf4STejun Heo  * out, -1 if canceled.
3445db7bccf4STejun Heo  */
3446db7bccf4STejun Heo #define trustee_wait_event_timeout(cond, timeout) ({			\
3447db7bccf4STejun Heo 	long __ret = (timeout);						\
3448db7bccf4STejun Heo 	while (!((cond) || (gcwq->trustee_state == TRUSTEE_RELEASE)) &&	\
3449db7bccf4STejun Heo 	       __ret) {							\
3450db7bccf4STejun Heo 		spin_unlock_irq(&gcwq->lock);				\
3451db7bccf4STejun Heo 		__wait_event_timeout(gcwq->trustee_wait, (cond) ||	\
3452db7bccf4STejun Heo 			(gcwq->trustee_state == TRUSTEE_RELEASE),	\
3453db7bccf4STejun Heo 			__ret);						\
3454db7bccf4STejun Heo 		spin_lock_irq(&gcwq->lock);				\
3455db7bccf4STejun Heo 	}								\
3456db7bccf4STejun Heo 	gcwq->trustee_state == TRUSTEE_RELEASE ? -1 : (__ret);		\
3457db7bccf4STejun Heo })
3458db7bccf4STejun Heo 
3459db7bccf4STejun Heo /**
3460db7bccf4STejun Heo  * trustee_wait_event - event wait for trustee
3461db7bccf4STejun Heo  * @cond: condition to wait for
3462db7bccf4STejun Heo  *
3463db7bccf4STejun Heo  * wait_event() for trustee to use.  Automatically handles locking and
3464db7bccf4STejun Heo  * checks for CANCEL request.
3465db7bccf4STejun Heo  *
3466db7bccf4STejun Heo  * CONTEXT:
3467db7bccf4STejun Heo  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
3468db7bccf4STejun Heo  * multiple times.  To be used by trustee.
3469db7bccf4STejun Heo  *
3470db7bccf4STejun Heo  * RETURNS:
3471db7bccf4STejun Heo  * 0 if @cond is satisfied, -1 if canceled.
3472db7bccf4STejun Heo  */
3473db7bccf4STejun Heo #define trustee_wait_event(cond) ({					\
3474db7bccf4STejun Heo 	long __ret1;							\
3475db7bccf4STejun Heo 	__ret1 = trustee_wait_event_timeout(cond, MAX_SCHEDULE_TIMEOUT);\
3476db7bccf4STejun Heo 	__ret1 < 0 ? -1 : 0;						\
3477db7bccf4STejun Heo })
3478db7bccf4STejun Heo 
3479db7bccf4STejun Heo static int __cpuinit trustee_thread(void *__gcwq)
3480db7bccf4STejun Heo {
3481db7bccf4STejun Heo 	struct global_cwq *gcwq = __gcwq;
34824ce62e9eSTejun Heo 	struct worker_pool *pool;
3483db7bccf4STejun Heo 	struct worker *worker;
3484e22bee78STejun Heo 	struct work_struct *work;
3485db7bccf4STejun Heo 	struct hlist_node *pos;
3486db7bccf4STejun Heo 	int i;
3487db7bccf4STejun Heo 
3488db7bccf4STejun Heo 	BUG_ON(gcwq->cpu != smp_processor_id());
3489db7bccf4STejun Heo 
349060373152STejun Heo 	gcwq_claim_management(gcwq);
3491db7bccf4STejun Heo 	spin_lock_irq(&gcwq->lock);
3492e22bee78STejun Heo 
3493f2d5a0eeSTejun Heo 	/*
3494f2d5a0eeSTejun Heo 	 * We've claimed all manager positions.  Make all workers unbound
3495f2d5a0eeSTejun Heo 	 * and set DISASSOCIATED.  Before this, all workers except for the
3496f2d5a0eeSTejun Heo 	 * ones which are still executing works from before the last CPU
3497f2d5a0eeSTejun Heo 	 * down must be on the cpu.  After this, they may become diasporas.
3498f2d5a0eeSTejun Heo 	 */
349960373152STejun Heo 	for_each_worker_pool(pool, gcwq)
35004ce62e9eSTejun Heo 		list_for_each_entry(worker, &pool->idle_list, entry)
3501403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
3502db7bccf4STejun Heo 
3503db7bccf4STejun Heo 	for_each_busy_worker(worker, i, pos, gcwq)
3504403c821dSTejun Heo 		worker->flags |= WORKER_UNBOUND;
3505db7bccf4STejun Heo 
3506f2d5a0eeSTejun Heo 	gcwq->flags |= GCWQ_DISASSOCIATED;
3507f2d5a0eeSTejun Heo 
3508db7bccf4STejun Heo 	/*
3509403c821dSTejun Heo 	 * Call schedule() so that we cross rq->lock and thus can guarantee
3510403c821dSTejun Heo 	 * sched callbacks see the unbound flag.  This is necessary as
3511403c821dSTejun Heo 	 * scheduler callbacks may be invoked from other cpus.
3512e22bee78STejun Heo 	 */
3513e22bee78STejun Heo 	spin_unlock_irq(&gcwq->lock);
3514e22bee78STejun Heo 	schedule();
3515e22bee78STejun Heo 	spin_lock_irq(&gcwq->lock);
3516e22bee78STejun Heo 
3517e22bee78STejun Heo 	/*
3518cb444766STejun Heo 	 * Sched callbacks are disabled now.  Zap nr_running.  After
3519cb444766STejun Heo 	 * this, nr_running stays zero and need_more_worker() and
3520cb444766STejun Heo 	 * keep_working() are always true as long as the worklist is
3521cb444766STejun Heo 	 * not empty.
3522e22bee78STejun Heo 	 */
35234ce62e9eSTejun Heo 	for_each_worker_pool(pool, gcwq)
35244ce62e9eSTejun Heo 		atomic_set(get_pool_nr_running(pool), 0);
3525e22bee78STejun Heo 
3526e22bee78STejun Heo 	spin_unlock_irq(&gcwq->lock);
35274ce62e9eSTejun Heo 	for_each_worker_pool(pool, gcwq)
35284ce62e9eSTejun Heo 		del_timer_sync(&pool->idle_timer);
3529e22bee78STejun Heo 	spin_lock_irq(&gcwq->lock);
3530e22bee78STejun Heo 
3531e22bee78STejun Heo 	/*
3532db7bccf4STejun Heo 	 * We're now in charge.  Notify and proceed to drain.  We need
3533db7bccf4STejun Heo 	 * to keep the gcwq running during the whole CPU down
3534db7bccf4STejun Heo 	 * procedure as other cpu hotunplug callbacks may need to
3535db7bccf4STejun Heo 	 * flush currently running tasks.
3536db7bccf4STejun Heo 	 */
3537db7bccf4STejun Heo 	gcwq->trustee_state = TRUSTEE_IN_CHARGE;
3538db7bccf4STejun Heo 	wake_up_all(&gcwq->trustee_wait);
3539db7bccf4STejun Heo 
3540db7bccf4STejun Heo 	/*
3541db7bccf4STejun Heo 	 * The original cpu is in the process of dying and may go away
3542db7bccf4STejun Heo 	 * anytime now.  When that happens, we and all workers would
3543e22bee78STejun Heo 	 * be migrated to other cpus.  Try draining any left work.  We
3544e22bee78STejun Heo 	 * want to get it over with ASAP - spam rescuers, wake up as
3545e22bee78STejun Heo 	 * many idlers as necessary and create new ones till the
3546e22bee78STejun Heo 	 * worklist is empty.  Note that if the gcwq is frozen, there
354758a69cb4STejun Heo 	 * may be frozen works in freezable cwqs.  Don't declare
3548e22bee78STejun Heo 	 * completion while frozen.
3549db7bccf4STejun Heo 	 */
35504ce62e9eSTejun Heo 	while (true) {
35514ce62e9eSTejun Heo 		bool busy = false;
35524ce62e9eSTejun Heo 
35534ce62e9eSTejun Heo 		for_each_worker_pool(pool, gcwq)
35544ce62e9eSTejun Heo 			busy |= pool->nr_workers != pool->nr_idle;
35554ce62e9eSTejun Heo 
35564ce62e9eSTejun Heo 		if (!busy && !(gcwq->flags & GCWQ_FREEZING) &&
35574ce62e9eSTejun Heo 		    gcwq->trustee_state != TRUSTEE_IN_CHARGE)
35584ce62e9eSTejun Heo 			break;
35594ce62e9eSTejun Heo 
35604ce62e9eSTejun Heo 		for_each_worker_pool(pool, gcwq) {
3561e22bee78STejun Heo 			int nr_works = 0;
3562e22bee78STejun Heo 
35634ce62e9eSTejun Heo 			list_for_each_entry(work, &pool->worklist, entry) {
3564e22bee78STejun Heo 				send_mayday(work);
3565e22bee78STejun Heo 				nr_works++;
3566e22bee78STejun Heo 			}
3567e22bee78STejun Heo 
35684ce62e9eSTejun Heo 			list_for_each_entry(worker, &pool->idle_list, entry) {
3569e22bee78STejun Heo 				if (!nr_works--)
3570e22bee78STejun Heo 					break;
3571e22bee78STejun Heo 				wake_up_process(worker->task);
3572e22bee78STejun Heo 			}
3573e22bee78STejun Heo 
35744ce62e9eSTejun Heo 			if (need_to_create_worker(pool)) {
3575e22bee78STejun Heo 				spin_unlock_irq(&gcwq->lock);
3576bc2ae0f5STejun Heo 				worker = create_worker(pool);
3577e22bee78STejun Heo 				spin_lock_irq(&gcwq->lock);
3578bc2ae0f5STejun Heo 				if (worker)
3579e22bee78STejun Heo 					start_worker(worker);
3580e22bee78STejun Heo 			}
3581e22bee78STejun Heo 		}
3582e22bee78STejun Heo 
3583db7bccf4STejun Heo 		/* give a breather */
3584db7bccf4STejun Heo 		if (trustee_wait_event_timeout(false, TRUSTEE_COOLDOWN) < 0)
3585db7bccf4STejun Heo 			break;
3586db7bccf4STejun Heo 	}
3587db7bccf4STejun Heo 
358860373152STejun Heo 	gcwq_release_management(gcwq);
3589e22bee78STejun Heo 
3590db7bccf4STejun Heo 	/* notify completion */
3591db7bccf4STejun Heo 	gcwq->trustee = NULL;
3592db7bccf4STejun Heo 	gcwq->trustee_state = TRUSTEE_DONE;
3593db7bccf4STejun Heo 	wake_up_all(&gcwq->trustee_wait);
3594db7bccf4STejun Heo 	spin_unlock_irq(&gcwq->lock);
3595db7bccf4STejun Heo 	return 0;
3596db7bccf4STejun Heo }
3597db7bccf4STejun Heo 
3598db7bccf4STejun Heo /**
3599db7bccf4STejun Heo  * wait_trustee_state - wait for trustee to enter the specified state
3600db7bccf4STejun Heo  * @gcwq: gcwq the trustee of interest belongs to
3601db7bccf4STejun Heo  * @state: target state to wait for
3602db7bccf4STejun Heo  *
3603db7bccf4STejun Heo  * Wait for the trustee to reach @state.  DONE is already matched.
3604db7bccf4STejun Heo  *
3605db7bccf4STejun Heo  * CONTEXT:
3606db7bccf4STejun Heo  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
3607db7bccf4STejun Heo  * multiple times.  To be used by cpu_callback.
3608db7bccf4STejun Heo  */
3609db7bccf4STejun Heo static void __cpuinit wait_trustee_state(struct global_cwq *gcwq, int state)
361006bd6ebfSNamhyung Kim __releases(&gcwq->lock)
361106bd6ebfSNamhyung Kim __acquires(&gcwq->lock)
3612db7bccf4STejun Heo {
3613db7bccf4STejun Heo 	if (!(gcwq->trustee_state == state ||
3614db7bccf4STejun Heo 	      gcwq->trustee_state == TRUSTEE_DONE)) {
3615db7bccf4STejun Heo 		spin_unlock_irq(&gcwq->lock);
3616db7bccf4STejun Heo 		__wait_event(gcwq->trustee_wait,
3617db7bccf4STejun Heo 			     gcwq->trustee_state == state ||
3618db7bccf4STejun Heo 			     gcwq->trustee_state == TRUSTEE_DONE);
3619db7bccf4STejun Heo 		spin_lock_irq(&gcwq->lock);
3620db7bccf4STejun Heo 	}
3621db7bccf4STejun Heo }
3622db7bccf4STejun Heo 
36239c7b216dSChandra Seetharaman static int __devinit workqueue_cpu_callback(struct notifier_block *nfb,
36241da177e4SLinus Torvalds 						unsigned long action,
36251da177e4SLinus Torvalds 						void *hcpu)
36261da177e4SLinus Torvalds {
36273af24433SOleg Nesterov 	unsigned int cpu = (unsigned long)hcpu;
3628db7bccf4STejun Heo 	struct global_cwq *gcwq = get_gcwq(cpu);
3629db7bccf4STejun Heo 	struct task_struct *new_trustee = NULL;
36304ce62e9eSTejun Heo 	struct worker_pool *pool;
3631db7bccf4STejun Heo 	unsigned long flags;
36321da177e4SLinus Torvalds 
36338bb78442SRafael J. Wysocki 	action &= ~CPU_TASKS_FROZEN;
36348bb78442SRafael J. Wysocki 
36351da177e4SLinus Torvalds 	switch (action) {
3636db7bccf4STejun Heo 	case CPU_DOWN_PREPARE:
3637db7bccf4STejun Heo 		new_trustee = kthread_create(trustee_thread, gcwq,
3638db7bccf4STejun Heo 					     "workqueue_trustee/%d\n", cpu);
3639db7bccf4STejun Heo 		if (IS_ERR(new_trustee))
3640db7bccf4STejun Heo 			return notifier_from_errno(PTR_ERR(new_trustee));
3641db7bccf4STejun Heo 		kthread_bind(new_trustee, cpu);
3642*3ce63377STejun Heo 		break;
3643*3ce63377STejun Heo 
36443af24433SOleg Nesterov 	case CPU_UP_PREPARE:
36454ce62e9eSTejun Heo 		for_each_worker_pool(pool, gcwq) {
3646*3ce63377STejun Heo 			struct worker *worker;
3647*3ce63377STejun Heo 
3648*3ce63377STejun Heo 			if (pool->nr_workers)
3649*3ce63377STejun Heo 				continue;
3650*3ce63377STejun Heo 
3651*3ce63377STejun Heo 			worker = create_worker(pool);
3652*3ce63377STejun Heo 			if (!worker)
3653*3ce63377STejun Heo 				return NOTIFY_BAD;
3654*3ce63377STejun Heo 
3655*3ce63377STejun Heo 			spin_lock_irq(&gcwq->lock);
3656*3ce63377STejun Heo 			start_worker(worker);
3657*3ce63377STejun Heo 			spin_unlock_irq(&gcwq->lock);
36583af24433SOleg Nesterov 		}
3659db7bccf4STejun Heo 	}
36601537663fSTejun Heo 
3661db7bccf4STejun Heo 	/* some are called w/ irq disabled, don't disturb irq status */
3662db7bccf4STejun Heo 	spin_lock_irqsave(&gcwq->lock, flags);
36633af24433SOleg Nesterov 
36643af24433SOleg Nesterov 	switch (action) {
3665db7bccf4STejun Heo 	case CPU_DOWN_PREPARE:
3666db7bccf4STejun Heo 		/* initialize trustee and tell it to acquire the gcwq */
3667db7bccf4STejun Heo 		BUG_ON(gcwq->trustee || gcwq->trustee_state != TRUSTEE_DONE);
3668db7bccf4STejun Heo 		gcwq->trustee = new_trustee;
3669db7bccf4STejun Heo 		gcwq->trustee_state = TRUSTEE_START;
3670db7bccf4STejun Heo 		wake_up_process(gcwq->trustee);
3671db7bccf4STejun Heo 		wait_trustee_state(gcwq, TRUSTEE_IN_CHARGE);
36721da177e4SLinus Torvalds 		break;
36731da177e4SLinus Torvalds 
36743da1c84cSOleg Nesterov 	case CPU_POST_DEAD:
3675db7bccf4STejun Heo 		gcwq->trustee_state = TRUSTEE_BUTCHER;
3676db7bccf4STejun Heo 		break;
3677db7bccf4STejun Heo 
3678db7bccf4STejun Heo 	case CPU_DOWN_FAILED:
36791da177e4SLinus Torvalds 	case CPU_ONLINE:
3680db7bccf4STejun Heo 		if (gcwq->trustee_state != TRUSTEE_DONE) {
3681db7bccf4STejun Heo 			gcwq->trustee_state = TRUSTEE_RELEASE;
3682db7bccf4STejun Heo 			wake_up_process(gcwq->trustee);
3683db7bccf4STejun Heo 			wait_trustee_state(gcwq, TRUSTEE_DONE);
3684db7bccf4STejun Heo 		}
36851da177e4SLinus Torvalds 
368625511a47STejun Heo 		spin_unlock_irq(&gcwq->lock);
368725511a47STejun Heo 		gcwq_claim_management(gcwq);
368825511a47STejun Heo 		spin_lock_irq(&gcwq->lock);
368925511a47STejun Heo 
3690bc2ae0f5STejun Heo 		gcwq->flags &= ~GCWQ_DISASSOCIATED;
3691bc2ae0f5STejun Heo 
369225511a47STejun Heo 		rebind_workers(gcwq);
369325511a47STejun Heo 
369425511a47STejun Heo 		gcwq_release_management(gcwq);
36951da177e4SLinus Torvalds 		break;
36961da177e4SLinus Torvalds 	}
36971da177e4SLinus Torvalds 
3698db7bccf4STejun Heo 	spin_unlock_irqrestore(&gcwq->lock, flags);
369900dfcaf7SOleg Nesterov 
37001537663fSTejun Heo 	return notifier_from_errno(0);
37011da177e4SLinus Torvalds }
37021da177e4SLinus Torvalds 
370365758202STejun Heo /*
370465758202STejun Heo  * Workqueues should be brought up before normal priority CPU notifiers.
370565758202STejun Heo  * This will be registered high priority CPU notifier.
370665758202STejun Heo  */
370765758202STejun Heo static int __devinit workqueue_cpu_up_callback(struct notifier_block *nfb,
370865758202STejun Heo 					       unsigned long action,
370965758202STejun Heo 					       void *hcpu)
371065758202STejun Heo {
371165758202STejun Heo 	switch (action & ~CPU_TASKS_FROZEN) {
371265758202STejun Heo 	case CPU_UP_PREPARE:
371365758202STejun Heo 	case CPU_DOWN_FAILED:
371465758202STejun Heo 	case CPU_ONLINE:
371565758202STejun Heo 		return workqueue_cpu_callback(nfb, action, hcpu);
371665758202STejun Heo 	}
371765758202STejun Heo 	return NOTIFY_OK;
371865758202STejun Heo }
371965758202STejun Heo 
372065758202STejun Heo /*
372165758202STejun Heo  * Workqueues should be brought down after normal priority CPU notifiers.
372265758202STejun Heo  * This will be registered as low priority CPU notifier.
372365758202STejun Heo  */
372465758202STejun Heo static int __devinit workqueue_cpu_down_callback(struct notifier_block *nfb,
372565758202STejun Heo 						 unsigned long action,
372665758202STejun Heo 						 void *hcpu)
372765758202STejun Heo {
372865758202STejun Heo 	switch (action & ~CPU_TASKS_FROZEN) {
372965758202STejun Heo 	case CPU_DOWN_PREPARE:
373065758202STejun Heo 	case CPU_POST_DEAD:
373165758202STejun Heo 		return workqueue_cpu_callback(nfb, action, hcpu);
373265758202STejun Heo 	}
373365758202STejun Heo 	return NOTIFY_OK;
373465758202STejun Heo }
373565758202STejun Heo 
37362d3854a3SRusty Russell #ifdef CONFIG_SMP
37378ccad40dSRusty Russell 
37382d3854a3SRusty Russell struct work_for_cpu {
37396b44003eSAndrew Morton 	struct completion completion;
37402d3854a3SRusty Russell 	long (*fn)(void *);
37412d3854a3SRusty Russell 	void *arg;
37422d3854a3SRusty Russell 	long ret;
37432d3854a3SRusty Russell };
37442d3854a3SRusty Russell 
37456b44003eSAndrew Morton static int do_work_for_cpu(void *_wfc)
37462d3854a3SRusty Russell {
37476b44003eSAndrew Morton 	struct work_for_cpu *wfc = _wfc;
37482d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
37496b44003eSAndrew Morton 	complete(&wfc->completion);
37506b44003eSAndrew Morton 	return 0;
37512d3854a3SRusty Russell }
37522d3854a3SRusty Russell 
37532d3854a3SRusty Russell /**
37542d3854a3SRusty Russell  * work_on_cpu - run a function in user context on a particular cpu
37552d3854a3SRusty Russell  * @cpu: the cpu to run on
37562d3854a3SRusty Russell  * @fn: the function to run
37572d3854a3SRusty Russell  * @arg: the function arg
37582d3854a3SRusty Russell  *
375931ad9081SRusty Russell  * This will return the value @fn returns.
376031ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
37616b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
37622d3854a3SRusty Russell  */
37632d3854a3SRusty Russell long work_on_cpu(unsigned int cpu, long (*fn)(void *), void *arg)
37642d3854a3SRusty Russell {
37656b44003eSAndrew Morton 	struct task_struct *sub_thread;
37666b44003eSAndrew Morton 	struct work_for_cpu wfc = {
37676b44003eSAndrew Morton 		.completion = COMPLETION_INITIALIZER_ONSTACK(wfc.completion),
37686b44003eSAndrew Morton 		.fn = fn,
37696b44003eSAndrew Morton 		.arg = arg,
37706b44003eSAndrew Morton 	};
37712d3854a3SRusty Russell 
37726b44003eSAndrew Morton 	sub_thread = kthread_create(do_work_for_cpu, &wfc, "work_for_cpu");
37736b44003eSAndrew Morton 	if (IS_ERR(sub_thread))
37746b44003eSAndrew Morton 		return PTR_ERR(sub_thread);
37756b44003eSAndrew Morton 	kthread_bind(sub_thread, cpu);
37766b44003eSAndrew Morton 	wake_up_process(sub_thread);
37776b44003eSAndrew Morton 	wait_for_completion(&wfc.completion);
37782d3854a3SRusty Russell 	return wfc.ret;
37792d3854a3SRusty Russell }
37802d3854a3SRusty Russell EXPORT_SYMBOL_GPL(work_on_cpu);
37812d3854a3SRusty Russell #endif /* CONFIG_SMP */
37822d3854a3SRusty Russell 
3783a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
3784e7577c50SRusty Russell 
3785a0a1a5fdSTejun Heo /**
3786a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
3787a0a1a5fdSTejun Heo  *
378858a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
378958a69cb4STejun Heo  * workqueues will queue new works to their frozen_works list instead of
379058a69cb4STejun Heo  * gcwq->worklist.
3791a0a1a5fdSTejun Heo  *
3792a0a1a5fdSTejun Heo  * CONTEXT:
37938b03ae3cSTejun Heo  * Grabs and releases workqueue_lock and gcwq->lock's.
3794a0a1a5fdSTejun Heo  */
3795a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
3796a0a1a5fdSTejun Heo {
3797a0a1a5fdSTejun Heo 	unsigned int cpu;
3798a0a1a5fdSTejun Heo 
3799a0a1a5fdSTejun Heo 	spin_lock(&workqueue_lock);
3800a0a1a5fdSTejun Heo 
3801a0a1a5fdSTejun Heo 	BUG_ON(workqueue_freezing);
3802a0a1a5fdSTejun Heo 	workqueue_freezing = true;
3803a0a1a5fdSTejun Heo 
3804f3421797STejun Heo 	for_each_gcwq_cpu(cpu) {
38058b03ae3cSTejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
3806bdbc5dd7STejun Heo 		struct workqueue_struct *wq;
38078b03ae3cSTejun Heo 
38088b03ae3cSTejun Heo 		spin_lock_irq(&gcwq->lock);
38098b03ae3cSTejun Heo 
3810db7bccf4STejun Heo 		BUG_ON(gcwq->flags & GCWQ_FREEZING);
3811db7bccf4STejun Heo 		gcwq->flags |= GCWQ_FREEZING;
3812db7bccf4STejun Heo 
3813a0a1a5fdSTejun Heo 		list_for_each_entry(wq, &workqueues, list) {
3814a0a1a5fdSTejun Heo 			struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3815a0a1a5fdSTejun Heo 
381658a69cb4STejun Heo 			if (cwq && wq->flags & WQ_FREEZABLE)
3817a0a1a5fdSTejun Heo 				cwq->max_active = 0;
38181da177e4SLinus Torvalds 		}
38198b03ae3cSTejun Heo 
38208b03ae3cSTejun Heo 		spin_unlock_irq(&gcwq->lock);
3821a0a1a5fdSTejun Heo 	}
3822a0a1a5fdSTejun Heo 
3823a0a1a5fdSTejun Heo 	spin_unlock(&workqueue_lock);
3824a0a1a5fdSTejun Heo }
3825a0a1a5fdSTejun Heo 
3826a0a1a5fdSTejun Heo /**
382758a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
3828a0a1a5fdSTejun Heo  *
3829a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
3830a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
3831a0a1a5fdSTejun Heo  *
3832a0a1a5fdSTejun Heo  * CONTEXT:
3833a0a1a5fdSTejun Heo  * Grabs and releases workqueue_lock.
3834a0a1a5fdSTejun Heo  *
3835a0a1a5fdSTejun Heo  * RETURNS:
383658a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
383758a69cb4STejun Heo  * is complete.
3838a0a1a5fdSTejun Heo  */
3839a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
3840a0a1a5fdSTejun Heo {
3841a0a1a5fdSTejun Heo 	unsigned int cpu;
3842a0a1a5fdSTejun Heo 	bool busy = false;
3843a0a1a5fdSTejun Heo 
3844a0a1a5fdSTejun Heo 	spin_lock(&workqueue_lock);
3845a0a1a5fdSTejun Heo 
3846a0a1a5fdSTejun Heo 	BUG_ON(!workqueue_freezing);
3847a0a1a5fdSTejun Heo 
3848f3421797STejun Heo 	for_each_gcwq_cpu(cpu) {
3849bdbc5dd7STejun Heo 		struct workqueue_struct *wq;
3850a0a1a5fdSTejun Heo 		/*
3851a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
3852a0a1a5fdSTejun Heo 		 * to peek without lock.
3853a0a1a5fdSTejun Heo 		 */
3854a0a1a5fdSTejun Heo 		list_for_each_entry(wq, &workqueues, list) {
3855a0a1a5fdSTejun Heo 			struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3856a0a1a5fdSTejun Heo 
385758a69cb4STejun Heo 			if (!cwq || !(wq->flags & WQ_FREEZABLE))
3858a0a1a5fdSTejun Heo 				continue;
3859a0a1a5fdSTejun Heo 
3860a0a1a5fdSTejun Heo 			BUG_ON(cwq->nr_active < 0);
3861a0a1a5fdSTejun Heo 			if (cwq->nr_active) {
3862a0a1a5fdSTejun Heo 				busy = true;
3863a0a1a5fdSTejun Heo 				goto out_unlock;
3864a0a1a5fdSTejun Heo 			}
3865a0a1a5fdSTejun Heo 		}
3866a0a1a5fdSTejun Heo 	}
3867a0a1a5fdSTejun Heo out_unlock:
3868a0a1a5fdSTejun Heo 	spin_unlock(&workqueue_lock);
3869a0a1a5fdSTejun Heo 	return busy;
3870a0a1a5fdSTejun Heo }
3871a0a1a5fdSTejun Heo 
3872a0a1a5fdSTejun Heo /**
3873a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
3874a0a1a5fdSTejun Heo  *
3875a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
38767e11629dSTejun Heo  * frozen works are transferred to their respective gcwq worklists.
3877a0a1a5fdSTejun Heo  *
3878a0a1a5fdSTejun Heo  * CONTEXT:
38798b03ae3cSTejun Heo  * Grabs and releases workqueue_lock and gcwq->lock's.
3880a0a1a5fdSTejun Heo  */
3881a0a1a5fdSTejun Heo void thaw_workqueues(void)
3882a0a1a5fdSTejun Heo {
3883a0a1a5fdSTejun Heo 	unsigned int cpu;
3884a0a1a5fdSTejun Heo 
3885a0a1a5fdSTejun Heo 	spin_lock(&workqueue_lock);
3886a0a1a5fdSTejun Heo 
3887a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
3888a0a1a5fdSTejun Heo 		goto out_unlock;
3889a0a1a5fdSTejun Heo 
3890f3421797STejun Heo 	for_each_gcwq_cpu(cpu) {
38918b03ae3cSTejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
38924ce62e9eSTejun Heo 		struct worker_pool *pool;
3893bdbc5dd7STejun Heo 		struct workqueue_struct *wq;
38948b03ae3cSTejun Heo 
38958b03ae3cSTejun Heo 		spin_lock_irq(&gcwq->lock);
38968b03ae3cSTejun Heo 
3897db7bccf4STejun Heo 		BUG_ON(!(gcwq->flags & GCWQ_FREEZING));
3898db7bccf4STejun Heo 		gcwq->flags &= ~GCWQ_FREEZING;
3899db7bccf4STejun Heo 
3900a0a1a5fdSTejun Heo 		list_for_each_entry(wq, &workqueues, list) {
3901a0a1a5fdSTejun Heo 			struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3902a0a1a5fdSTejun Heo 
390358a69cb4STejun Heo 			if (!cwq || !(wq->flags & WQ_FREEZABLE))
3904a0a1a5fdSTejun Heo 				continue;
3905a0a1a5fdSTejun Heo 
3906a0a1a5fdSTejun Heo 			/* restore max_active and repopulate worklist */
3907a0a1a5fdSTejun Heo 			cwq->max_active = wq->saved_max_active;
3908a0a1a5fdSTejun Heo 
3909a0a1a5fdSTejun Heo 			while (!list_empty(&cwq->delayed_works) &&
3910a0a1a5fdSTejun Heo 			       cwq->nr_active < cwq->max_active)
3911a0a1a5fdSTejun Heo 				cwq_activate_first_delayed(cwq);
3912a0a1a5fdSTejun Heo 		}
39138b03ae3cSTejun Heo 
39144ce62e9eSTejun Heo 		for_each_worker_pool(pool, gcwq)
39154ce62e9eSTejun Heo 			wake_up_worker(pool);
3916e22bee78STejun Heo 
39178b03ae3cSTejun Heo 		spin_unlock_irq(&gcwq->lock);
3918a0a1a5fdSTejun Heo 	}
3919a0a1a5fdSTejun Heo 
3920a0a1a5fdSTejun Heo 	workqueue_freezing = false;
3921a0a1a5fdSTejun Heo out_unlock:
3922a0a1a5fdSTejun Heo 	spin_unlock(&workqueue_lock);
3923a0a1a5fdSTejun Heo }
3924a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
3925a0a1a5fdSTejun Heo 
39266ee0578bSSuresh Siddha static int __init init_workqueues(void)
39271da177e4SLinus Torvalds {
3928c34056a3STejun Heo 	unsigned int cpu;
3929c8e55f36STejun Heo 	int i;
3930c34056a3STejun Heo 
393165758202STejun Heo 	cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
393265758202STejun Heo 	cpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
39338b03ae3cSTejun Heo 
39348b03ae3cSTejun Heo 	/* initialize gcwqs */
3935f3421797STejun Heo 	for_each_gcwq_cpu(cpu) {
39368b03ae3cSTejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
39374ce62e9eSTejun Heo 		struct worker_pool *pool;
39388b03ae3cSTejun Heo 
39398b03ae3cSTejun Heo 		spin_lock_init(&gcwq->lock);
39408b03ae3cSTejun Heo 		gcwq->cpu = cpu;
3941f3421797STejun Heo 		gcwq->flags |= GCWQ_DISASSOCIATED;
39428b03ae3cSTejun Heo 
3943c8e55f36STejun Heo 		for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)
3944c8e55f36STejun Heo 			INIT_HLIST_HEAD(&gcwq->busy_hash[i]);
3945c8e55f36STejun Heo 
39464ce62e9eSTejun Heo 		for_each_worker_pool(pool, gcwq) {
39474ce62e9eSTejun Heo 			pool->gcwq = gcwq;
39484ce62e9eSTejun Heo 			INIT_LIST_HEAD(&pool->worklist);
39494ce62e9eSTejun Heo 			INIT_LIST_HEAD(&pool->idle_list);
3950e22bee78STejun Heo 
39514ce62e9eSTejun Heo 			init_timer_deferrable(&pool->idle_timer);
39524ce62e9eSTejun Heo 			pool->idle_timer.function = idle_worker_timeout;
39534ce62e9eSTejun Heo 			pool->idle_timer.data = (unsigned long)pool;
3954e22bee78STejun Heo 
39554ce62e9eSTejun Heo 			setup_timer(&pool->mayday_timer, gcwq_mayday_timeout,
39564ce62e9eSTejun Heo 				    (unsigned long)pool);
39574ce62e9eSTejun Heo 
395860373152STejun Heo 			mutex_init(&pool->manager_mutex);
39594ce62e9eSTejun Heo 			ida_init(&pool->worker_ida);
39604ce62e9eSTejun Heo 		}
3961db7bccf4STejun Heo 
396225511a47STejun Heo 		init_waitqueue_head(&gcwq->rebind_hold);
396325511a47STejun Heo 
3964db7bccf4STejun Heo 		gcwq->trustee_state = TRUSTEE_DONE;
3965db7bccf4STejun Heo 		init_waitqueue_head(&gcwq->trustee_wait);
39668b03ae3cSTejun Heo 	}
39678b03ae3cSTejun Heo 
3968e22bee78STejun Heo 	/* create the initial worker */
3969f3421797STejun Heo 	for_each_online_gcwq_cpu(cpu) {
3970e22bee78STejun Heo 		struct global_cwq *gcwq = get_gcwq(cpu);
39714ce62e9eSTejun Heo 		struct worker_pool *pool;
3972e22bee78STejun Heo 
3973477a3c33STejun Heo 		if (cpu != WORK_CPU_UNBOUND)
3974477a3c33STejun Heo 			gcwq->flags &= ~GCWQ_DISASSOCIATED;
39754ce62e9eSTejun Heo 
39764ce62e9eSTejun Heo 		for_each_worker_pool(pool, gcwq) {
39774ce62e9eSTejun Heo 			struct worker *worker;
39784ce62e9eSTejun Heo 
3979bc2ae0f5STejun Heo 			worker = create_worker(pool);
3980e22bee78STejun Heo 			BUG_ON(!worker);
3981e22bee78STejun Heo 			spin_lock_irq(&gcwq->lock);
3982e22bee78STejun Heo 			start_worker(worker);
3983e22bee78STejun Heo 			spin_unlock_irq(&gcwq->lock);
3984e22bee78STejun Heo 		}
39854ce62e9eSTejun Heo 	}
3986e22bee78STejun Heo 
3987d320c038STejun Heo 	system_wq = alloc_workqueue("events", 0, 0);
3988d320c038STejun Heo 	system_long_wq = alloc_workqueue("events_long", 0, 0);
3989d320c038STejun Heo 	system_nrt_wq = alloc_workqueue("events_nrt", WQ_NON_REENTRANT, 0);
3990f3421797STejun Heo 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
3991f3421797STejun Heo 					    WQ_UNBOUND_MAX_ACTIVE);
399224d51addSTejun Heo 	system_freezable_wq = alloc_workqueue("events_freezable",
399324d51addSTejun Heo 					      WQ_FREEZABLE, 0);
399462d3c543SAlan Stern 	system_nrt_freezable_wq = alloc_workqueue("events_nrt_freezable",
399562d3c543SAlan Stern 			WQ_NON_REENTRANT | WQ_FREEZABLE, 0);
3996e5cba24eSHitoshi Mitake 	BUG_ON(!system_wq || !system_long_wq || !system_nrt_wq ||
399762d3c543SAlan Stern 	       !system_unbound_wq || !system_freezable_wq ||
399862d3c543SAlan Stern 		!system_nrt_freezable_wq);
39996ee0578bSSuresh Siddha 	return 0;
40001da177e4SLinus Torvalds }
40016ee0578bSSuresh Siddha early_initcall(init_workqueues);
4002