xref: /linux-6.15/kernel/workqueue.c (revision fa1b54e6)
11da177e4SLinus Torvalds /*
2c54fce6eSTejun Heo  * kernel/workqueue.c - generic async execution with shared worker pool
31da177e4SLinus Torvalds  *
4c54fce6eSTejun Heo  * Copyright (C) 2002		Ingo Molnar
51da177e4SLinus Torvalds  *
61da177e4SLinus Torvalds  *   Derived from the taskqueue/keventd code by:
71da177e4SLinus Torvalds  *     David Woodhouse <[email protected]>
8e1f8e874SFrancois Cami  *     Andrew Morton
91da177e4SLinus Torvalds  *     Kai Petzke <[email protected]>
101da177e4SLinus Torvalds  *     Theodore Ts'o <[email protected]>
1189ada679SChristoph Lameter  *
12cde53535SChristoph Lameter  * Made to use alloc_percpu by Christoph Lameter.
13c54fce6eSTejun Heo  *
14c54fce6eSTejun Heo  * Copyright (C) 2010		SUSE Linux Products GmbH
15c54fce6eSTejun Heo  * Copyright (C) 2010		Tejun Heo <[email protected]>
16c54fce6eSTejun Heo  *
17c54fce6eSTejun Heo  * This is the generic async execution mechanism.  Work items as are
18c54fce6eSTejun Heo  * executed in process context.  The worker pool is shared and
19c54fce6eSTejun Heo  * automatically managed.  There is one worker pool for each CPU and
20c54fce6eSTejun Heo  * one extra for works which are better served by workers which are
21c54fce6eSTejun Heo  * not bound to any specific CPU.
22c54fce6eSTejun Heo  *
23c54fce6eSTejun Heo  * Please read Documentation/workqueue.txt for details.
241da177e4SLinus Torvalds  */
251da177e4SLinus Torvalds 
269984de1aSPaul Gortmaker #include <linux/export.h>
271da177e4SLinus Torvalds #include <linux/kernel.h>
281da177e4SLinus Torvalds #include <linux/sched.h>
291da177e4SLinus Torvalds #include <linux/init.h>
301da177e4SLinus Torvalds #include <linux/signal.h>
311da177e4SLinus Torvalds #include <linux/completion.h>
321da177e4SLinus Torvalds #include <linux/workqueue.h>
331da177e4SLinus Torvalds #include <linux/slab.h>
341da177e4SLinus Torvalds #include <linux/cpu.h>
351da177e4SLinus Torvalds #include <linux/notifier.h>
361da177e4SLinus Torvalds #include <linux/kthread.h>
371fa44ecaSJames Bottomley #include <linux/hardirq.h>
3846934023SChristoph Lameter #include <linux/mempolicy.h>
39341a5958SRafael J. Wysocki #include <linux/freezer.h>
40d5abe669SPeter Zijlstra #include <linux/kallsyms.h>
41d5abe669SPeter Zijlstra #include <linux/debug_locks.h>
424e6045f1SJohannes Berg #include <linux/lockdep.h>
43c34056a3STejun Heo #include <linux/idr.h>
4442f8570fSSasha Levin #include <linux/hashtable.h>
4576af4d93STejun Heo #include <linux/rculist.h>
46e22bee78STejun Heo 
47ea138446STejun Heo #include "workqueue_internal.h"
481da177e4SLinus Torvalds 
49c8e55f36STejun Heo enum {
50bc2ae0f5STejun Heo 	/*
5124647570STejun Heo 	 * worker_pool flags
52bc2ae0f5STejun Heo 	 *
5324647570STejun Heo 	 * A bound pool is either associated or disassociated with its CPU.
54bc2ae0f5STejun Heo 	 * While associated (!DISASSOCIATED), all workers are bound to the
55bc2ae0f5STejun Heo 	 * CPU and none has %WORKER_UNBOUND set and concurrency management
56bc2ae0f5STejun Heo 	 * is in effect.
57bc2ae0f5STejun Heo 	 *
58bc2ae0f5STejun Heo 	 * While DISASSOCIATED, the cpu may be offline and all workers have
59bc2ae0f5STejun Heo 	 * %WORKER_UNBOUND set and concurrency management disabled, and may
6024647570STejun Heo 	 * be executing on any CPU.  The pool behaves as an unbound one.
61bc2ae0f5STejun Heo 	 *
62bc2ae0f5STejun Heo 	 * Note that DISASSOCIATED can be flipped only while holding
6324647570STejun Heo 	 * assoc_mutex to avoid changing binding state while
6424647570STejun Heo 	 * create_worker() is in progress.
65bc2ae0f5STejun Heo 	 */
6611ebea50STejun Heo 	POOL_MANAGE_WORKERS	= 1 << 0,	/* need to manage workers */
67552a37e9SLai Jiangshan 	POOL_MANAGING_WORKERS   = 1 << 1,       /* managing workers */
6824647570STejun Heo 	POOL_DISASSOCIATED	= 1 << 2,	/* cpu can't serve workers */
6935b6bb63STejun Heo 	POOL_FREEZING		= 1 << 3,	/* freeze in progress */
70db7bccf4STejun Heo 
71c8e55f36STejun Heo 	/* worker flags */
72c8e55f36STejun Heo 	WORKER_STARTED		= 1 << 0,	/* started */
73c8e55f36STejun Heo 	WORKER_DIE		= 1 << 1,	/* die die die */
74c8e55f36STejun Heo 	WORKER_IDLE		= 1 << 2,	/* is idle */
75e22bee78STejun Heo 	WORKER_PREP		= 1 << 3,	/* preparing to run works */
76fb0e7bebSTejun Heo 	WORKER_CPU_INTENSIVE	= 1 << 6,	/* cpu intensive */
77f3421797STejun Heo 	WORKER_UNBOUND		= 1 << 7,	/* worker is unbound */
78e22bee78STejun Heo 
795f7dabfdSLai Jiangshan 	WORKER_NOT_RUNNING	= WORKER_PREP | WORKER_UNBOUND |
80403c821dSTejun Heo 				  WORKER_CPU_INTENSIVE,
81db7bccf4STejun Heo 
82e34cdddbSTejun Heo 	NR_STD_WORKER_POOLS	= 2,		/* # standard pools per cpu */
834ce62e9eSTejun Heo 
84c8e55f36STejun Heo 	BUSY_WORKER_HASH_ORDER	= 6,		/* 64 pointers */
85db7bccf4STejun Heo 
86e22bee78STejun Heo 	MAX_IDLE_WORKERS_RATIO	= 4,		/* 1/4 of busy can be idle */
87e22bee78STejun Heo 	IDLE_WORKER_TIMEOUT	= 300 * HZ,	/* keep idle ones for 5 mins */
88e22bee78STejun Heo 
893233cdbdSTejun Heo 	MAYDAY_INITIAL_TIMEOUT  = HZ / 100 >= 2 ? HZ / 100 : 2,
903233cdbdSTejun Heo 						/* call for help after 10ms
913233cdbdSTejun Heo 						   (min two ticks) */
92e22bee78STejun Heo 	MAYDAY_INTERVAL		= HZ / 10,	/* and then every 100ms */
93e22bee78STejun Heo 	CREATE_COOLDOWN		= HZ,		/* time to breath after fail */
941da177e4SLinus Torvalds 
951da177e4SLinus Torvalds 	/*
96e22bee78STejun Heo 	 * Rescue workers are used only on emergencies and shared by
97e22bee78STejun Heo 	 * all cpus.  Give -20.
98e22bee78STejun Heo 	 */
99e22bee78STejun Heo 	RESCUER_NICE_LEVEL	= -20,
1003270476aSTejun Heo 	HIGHPRI_NICE_LEVEL	= -20,
101c8e55f36STejun Heo };
102c8e55f36STejun Heo 
1031da177e4SLinus Torvalds /*
1044690c4abSTejun Heo  * Structure fields follow one of the following exclusion rules.
1054690c4abSTejun Heo  *
106e41e704bSTejun Heo  * I: Modifiable by initialization/destruction paths and read-only for
107e41e704bSTejun Heo  *    everyone else.
1084690c4abSTejun Heo  *
109e22bee78STejun Heo  * P: Preemption protected.  Disabling preemption is enough and should
110e22bee78STejun Heo  *    only be modified and accessed from the local cpu.
111e22bee78STejun Heo  *
112d565ed63STejun Heo  * L: pool->lock protected.  Access with pool->lock held.
1134690c4abSTejun Heo  *
114d565ed63STejun Heo  * X: During normal operation, modification requires pool->lock and should
115d565ed63STejun Heo  *    be done only from local cpu.  Either disabling preemption on local
116d565ed63STejun Heo  *    cpu or grabbing pool->lock is enough for read access.  If
117d565ed63STejun Heo  *    POOL_DISASSOCIATED is set, it's identical to L.
118e22bee78STejun Heo  *
11973f53c4aSTejun Heo  * F: wq->flush_mutex protected.
12073f53c4aSTejun Heo  *
1214690c4abSTejun Heo  * W: workqueue_lock protected.
12276af4d93STejun Heo  *
12376af4d93STejun Heo  * R: workqueue_lock protected for writes.  Sched-RCU protected for reads.
1244690c4abSTejun Heo  */
1254690c4abSTejun Heo 
1262eaebdb3STejun Heo /* struct worker is defined in workqueue_internal.h */
127c34056a3STejun Heo 
128bd7bdd43STejun Heo struct worker_pool {
129d565ed63STejun Heo 	spinlock_t		lock;		/* the pool lock */
130d84ff051STejun Heo 	int			cpu;		/* I: the associated cpu */
1319daf9e67STejun Heo 	int			id;		/* I: pool ID */
13211ebea50STejun Heo 	unsigned int		flags;		/* X: flags */
133bd7bdd43STejun Heo 
134bd7bdd43STejun Heo 	struct list_head	worklist;	/* L: list of pending works */
135bd7bdd43STejun Heo 	int			nr_workers;	/* L: total number of workers */
136ea1abd61SLai Jiangshan 
137ea1abd61SLai Jiangshan 	/* nr_idle includes the ones off idle_list for rebinding */
138bd7bdd43STejun Heo 	int			nr_idle;	/* L: currently idle ones */
139bd7bdd43STejun Heo 
140bd7bdd43STejun Heo 	struct list_head	idle_list;	/* X: list of idle workers */
141bd7bdd43STejun Heo 	struct timer_list	idle_timer;	/* L: worker idle timeout */
142bd7bdd43STejun Heo 	struct timer_list	mayday_timer;	/* L: SOS timer for workers */
143bd7bdd43STejun Heo 
144c9e7cf27STejun Heo 	/* workers are chained either in busy_hash or idle_list */
145c9e7cf27STejun Heo 	DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
146c9e7cf27STejun Heo 						/* L: hash of busy workers */
147c9e7cf27STejun Heo 
14824647570STejun Heo 	struct mutex		assoc_mutex;	/* protect POOL_DISASSOCIATED */
149bd7bdd43STejun Heo 	struct ida		worker_ida;	/* L: for worker IDs */
150e19e397aSTejun Heo 
151e19e397aSTejun Heo 	/*
152e19e397aSTejun Heo 	 * The current concurrency level.  As it's likely to be accessed
153e19e397aSTejun Heo 	 * from other CPUs during try_to_wake_up(), put it in a separate
154e19e397aSTejun Heo 	 * cacheline.
155e19e397aSTejun Heo 	 */
156e19e397aSTejun Heo 	atomic_t		nr_running ____cacheline_aligned_in_smp;
1578b03ae3cSTejun Heo } ____cacheline_aligned_in_smp;
1588b03ae3cSTejun Heo 
1598b03ae3cSTejun Heo /*
160112202d9STejun Heo  * The per-pool workqueue.  While queued, the lower WORK_STRUCT_FLAG_BITS
161112202d9STejun Heo  * of work_struct->data are used for flags and the remaining high bits
162112202d9STejun Heo  * point to the pwq; thus, pwqs need to be aligned at two's power of the
163112202d9STejun Heo  * number of flag bits.
1641da177e4SLinus Torvalds  */
165112202d9STejun Heo struct pool_workqueue {
166bd7bdd43STejun Heo 	struct worker_pool	*pool;		/* I: the associated pool */
1674690c4abSTejun Heo 	struct workqueue_struct *wq;		/* I: the owning workqueue */
16873f53c4aSTejun Heo 	int			work_color;	/* L: current color */
16973f53c4aSTejun Heo 	int			flush_color;	/* L: flushing color */
17073f53c4aSTejun Heo 	int			nr_in_flight[WORK_NR_COLORS];
17173f53c4aSTejun Heo 						/* L: nr of in_flight works */
1721e19ffc6STejun Heo 	int			nr_active;	/* L: nr of active works */
173a0a1a5fdSTejun Heo 	int			max_active;	/* L: max active works */
1741e19ffc6STejun Heo 	struct list_head	delayed_works;	/* L: delayed works */
17576af4d93STejun Heo 	struct list_head	pwqs_node;	/* R: node on wq->pwqs */
176493a1724STejun Heo 	struct list_head	mayday_node;	/* W: node on wq->maydays */
177e904e6c2STejun Heo } __aligned(1 << WORK_STRUCT_FLAG_BITS);
1781da177e4SLinus Torvalds 
1791da177e4SLinus Torvalds /*
18073f53c4aSTejun Heo  * Structure used to wait for workqueue flush.
18173f53c4aSTejun Heo  */
18273f53c4aSTejun Heo struct wq_flusher {
18373f53c4aSTejun Heo 	struct list_head	list;		/* F: list of flushers */
18473f53c4aSTejun Heo 	int			flush_color;	/* F: flush color waiting for */
18573f53c4aSTejun Heo 	struct completion	done;		/* flush completion */
18673f53c4aSTejun Heo };
1871da177e4SLinus Torvalds 
18873f53c4aSTejun Heo /*
1891da177e4SLinus Torvalds  * The externally visible workqueue abstraction is an array of
1901da177e4SLinus Torvalds  * per-CPU workqueues:
1911da177e4SLinus Torvalds  */
1921da177e4SLinus Torvalds struct workqueue_struct {
1939c5a2ba7STejun Heo 	unsigned int		flags;		/* W: WQ_* flags */
194420c0ddbSTejun Heo 	struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwq's */
19576af4d93STejun Heo 	struct list_head	pwqs;		/* R: all pwqs of this wq */
1964690c4abSTejun Heo 	struct list_head	list;		/* W: list of all workqueues */
19773f53c4aSTejun Heo 
19873f53c4aSTejun Heo 	struct mutex		flush_mutex;	/* protects wq flushing */
19973f53c4aSTejun Heo 	int			work_color;	/* F: current work color */
20073f53c4aSTejun Heo 	int			flush_color;	/* F: current flush color */
201112202d9STejun Heo 	atomic_t		nr_pwqs_to_flush; /* flush in progress */
20273f53c4aSTejun Heo 	struct wq_flusher	*first_flusher;	/* F: first flusher */
20373f53c4aSTejun Heo 	struct list_head	flusher_queue;	/* F: flush waiters */
20473f53c4aSTejun Heo 	struct list_head	flusher_overflow; /* F: flush overflow list */
20573f53c4aSTejun Heo 
206493a1724STejun Heo 	struct list_head	maydays;	/* W: pwqs requesting rescue */
207e22bee78STejun Heo 	struct worker		*rescuer;	/* I: rescue worker */
208e22bee78STejun Heo 
2099c5a2ba7STejun Heo 	int			nr_drainers;	/* W: drain in progress */
210112202d9STejun Heo 	int			saved_max_active; /* W: saved pwq max_active */
2114e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
2124e6045f1SJohannes Berg 	struct lockdep_map	lockdep_map;
2134e6045f1SJohannes Berg #endif
214b196be89STejun Heo 	char			name[];		/* I: workqueue name */
2151da177e4SLinus Torvalds };
2161da177e4SLinus Torvalds 
217e904e6c2STejun Heo static struct kmem_cache *pwq_cache;
218e904e6c2STejun Heo 
219d320c038STejun Heo struct workqueue_struct *system_wq __read_mostly;
220d320c038STejun Heo EXPORT_SYMBOL_GPL(system_wq);
221044c782cSValentin Ilie struct workqueue_struct *system_highpri_wq __read_mostly;
2221aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
223044c782cSValentin Ilie struct workqueue_struct *system_long_wq __read_mostly;
224d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
225044c782cSValentin Ilie struct workqueue_struct *system_unbound_wq __read_mostly;
226f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
227044c782cSValentin Ilie struct workqueue_struct *system_freezable_wq __read_mostly;
22824d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
229d320c038STejun Heo 
23097bd2347STejun Heo #define CREATE_TRACE_POINTS
23197bd2347STejun Heo #include <trace/events/workqueue.h>
23297bd2347STejun Heo 
23376af4d93STejun Heo #define assert_rcu_or_wq_lock()						\
23476af4d93STejun Heo 	rcu_lockdep_assert(rcu_read_lock_sched_held() ||		\
23576af4d93STejun Heo 			   lockdep_is_held(&workqueue_lock),		\
23676af4d93STejun Heo 			   "sched RCU or workqueue lock should be held")
23776af4d93STejun Heo 
23838db41d9STejun Heo #define for_each_std_worker_pool(pool, cpu)				\
239a60dc39cSTejun Heo 	for ((pool) = &std_worker_pools(cpu)[0];			\
240a60dc39cSTejun Heo 	     (pool) < &std_worker_pools(cpu)[NR_STD_WORKER_POOLS]; (pool)++)
2414ce62e9eSTejun Heo 
242b67bfe0dSSasha Levin #define for_each_busy_worker(worker, i, pool)				\
243b67bfe0dSSasha Levin 	hash_for_each(pool->busy_hash, i, worker, hentry)
244db7bccf4STejun Heo 
245706026c2STejun Heo static inline int __next_wq_cpu(int cpu, const struct cpumask *mask,
246f3421797STejun Heo 				unsigned int sw)
247f3421797STejun Heo {
248f3421797STejun Heo 	if (cpu < nr_cpu_ids) {
249f3421797STejun Heo 		if (sw & 1) {
250f3421797STejun Heo 			cpu = cpumask_next(cpu, mask);
251f3421797STejun Heo 			if (cpu < nr_cpu_ids)
252f3421797STejun Heo 				return cpu;
253f3421797STejun Heo 		}
254f3421797STejun Heo 		if (sw & 2)
255f3421797STejun Heo 			return WORK_CPU_UNBOUND;
256f3421797STejun Heo 	}
2576be19588SLai Jiangshan 	return WORK_CPU_END;
258f3421797STejun Heo }
259f3421797STejun Heo 
26009884951STejun Heo /*
26109884951STejun Heo  * CPU iterators
26209884951STejun Heo  *
263706026c2STejun Heo  * An extra cpu number is defined using an invalid cpu number
26409884951STejun Heo  * (WORK_CPU_UNBOUND) to host workqueues which are not bound to any
265706026c2STejun Heo  * specific CPU.  The following iterators are similar to for_each_*_cpu()
266706026c2STejun Heo  * iterators but also considers the unbound CPU.
26709884951STejun Heo  *
268706026c2STejun Heo  * for_each_wq_cpu()		: possible CPUs + WORK_CPU_UNBOUND
269706026c2STejun Heo  * for_each_online_wq_cpu()	: online CPUs + WORK_CPU_UNBOUND
27009884951STejun Heo  */
271706026c2STejun Heo #define for_each_wq_cpu(cpu)						\
272706026c2STejun Heo 	for ((cpu) = __next_wq_cpu(-1, cpu_possible_mask, 3);		\
2736be19588SLai Jiangshan 	     (cpu) < WORK_CPU_END;					\
274706026c2STejun Heo 	     (cpu) = __next_wq_cpu((cpu), cpu_possible_mask, 3))
275f3421797STejun Heo 
276706026c2STejun Heo #define for_each_online_wq_cpu(cpu)					\
277706026c2STejun Heo 	for ((cpu) = __next_wq_cpu(-1, cpu_online_mask, 3);		\
2786be19588SLai Jiangshan 	     (cpu) < WORK_CPU_END;					\
279706026c2STejun Heo 	     (cpu) = __next_wq_cpu((cpu), cpu_online_mask, 3))
280f3421797STejun Heo 
28149e3cf44STejun Heo /**
28217116969STejun Heo  * for_each_pool - iterate through all worker_pools in the system
28317116969STejun Heo  * @pool: iteration cursor
28417116969STejun Heo  * @id: integer used for iteration
285*fa1b54e6STejun Heo  *
286*fa1b54e6STejun Heo  * This must be called either with workqueue_lock held or sched RCU read
287*fa1b54e6STejun Heo  * locked.  If the pool needs to be used beyond the locking in effect, the
288*fa1b54e6STejun Heo  * caller is responsible for guaranteeing that the pool stays online.
289*fa1b54e6STejun Heo  *
290*fa1b54e6STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
291*fa1b54e6STejun Heo  * ignored.
29217116969STejun Heo  */
29317116969STejun Heo #define for_each_pool(pool, id)						\
294*fa1b54e6STejun Heo 	idr_for_each_entry(&worker_pool_idr, pool, id)			\
295*fa1b54e6STejun Heo 		if (({ assert_rcu_or_wq_lock(); false; })) { }		\
296*fa1b54e6STejun Heo 		else
29717116969STejun Heo 
29817116969STejun Heo /**
29949e3cf44STejun Heo  * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
30049e3cf44STejun Heo  * @pwq: iteration cursor
30149e3cf44STejun Heo  * @wq: the target workqueue
30276af4d93STejun Heo  *
30376af4d93STejun Heo  * This must be called either with workqueue_lock held or sched RCU read
30476af4d93STejun Heo  * locked.  If the pwq needs to be used beyond the locking in effect, the
30576af4d93STejun Heo  * caller is responsible for guaranteeing that the pwq stays online.
30676af4d93STejun Heo  *
30776af4d93STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
30876af4d93STejun Heo  * ignored.
30949e3cf44STejun Heo  */
31049e3cf44STejun Heo #define for_each_pwq(pwq, wq)						\
31176af4d93STejun Heo 	list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node)		\
31276af4d93STejun Heo 		if (({ assert_rcu_or_wq_lock(); false; })) { }		\
31376af4d93STejun Heo 		else
314f3421797STejun Heo 
315dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
316dc186ad7SThomas Gleixner 
317dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr;
318dc186ad7SThomas Gleixner 
31999777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
32099777288SStanislaw Gruszka {
32199777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
32299777288SStanislaw Gruszka }
32399777288SStanislaw Gruszka 
324dc186ad7SThomas Gleixner /*
325dc186ad7SThomas Gleixner  * fixup_init is called when:
326dc186ad7SThomas Gleixner  * - an active object is initialized
327dc186ad7SThomas Gleixner  */
328dc186ad7SThomas Gleixner static int work_fixup_init(void *addr, enum debug_obj_state state)
329dc186ad7SThomas Gleixner {
330dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
331dc186ad7SThomas Gleixner 
332dc186ad7SThomas Gleixner 	switch (state) {
333dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
334dc186ad7SThomas Gleixner 		cancel_work_sync(work);
335dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
336dc186ad7SThomas Gleixner 		return 1;
337dc186ad7SThomas Gleixner 	default:
338dc186ad7SThomas Gleixner 		return 0;
339dc186ad7SThomas Gleixner 	}
340dc186ad7SThomas Gleixner }
341dc186ad7SThomas Gleixner 
342dc186ad7SThomas Gleixner /*
343dc186ad7SThomas Gleixner  * fixup_activate is called when:
344dc186ad7SThomas Gleixner  * - an active object is activated
345dc186ad7SThomas Gleixner  * - an unknown object is activated (might be a statically initialized object)
346dc186ad7SThomas Gleixner  */
347dc186ad7SThomas Gleixner static int work_fixup_activate(void *addr, enum debug_obj_state state)
348dc186ad7SThomas Gleixner {
349dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
350dc186ad7SThomas Gleixner 
351dc186ad7SThomas Gleixner 	switch (state) {
352dc186ad7SThomas Gleixner 
353dc186ad7SThomas Gleixner 	case ODEBUG_STATE_NOTAVAILABLE:
354dc186ad7SThomas Gleixner 		/*
355dc186ad7SThomas Gleixner 		 * This is not really a fixup. The work struct was
356dc186ad7SThomas Gleixner 		 * statically initialized. We just make sure that it
357dc186ad7SThomas Gleixner 		 * is tracked in the object tracker.
358dc186ad7SThomas Gleixner 		 */
35922df02bbSTejun Heo 		if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
360dc186ad7SThomas Gleixner 			debug_object_init(work, &work_debug_descr);
361dc186ad7SThomas Gleixner 			debug_object_activate(work, &work_debug_descr);
362dc186ad7SThomas Gleixner 			return 0;
363dc186ad7SThomas Gleixner 		}
364dc186ad7SThomas Gleixner 		WARN_ON_ONCE(1);
365dc186ad7SThomas Gleixner 		return 0;
366dc186ad7SThomas Gleixner 
367dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
368dc186ad7SThomas Gleixner 		WARN_ON(1);
369dc186ad7SThomas Gleixner 
370dc186ad7SThomas Gleixner 	default:
371dc186ad7SThomas Gleixner 		return 0;
372dc186ad7SThomas Gleixner 	}
373dc186ad7SThomas Gleixner }
374dc186ad7SThomas Gleixner 
375dc186ad7SThomas Gleixner /*
376dc186ad7SThomas Gleixner  * fixup_free is called when:
377dc186ad7SThomas Gleixner  * - an active object is freed
378dc186ad7SThomas Gleixner  */
379dc186ad7SThomas Gleixner static int work_fixup_free(void *addr, enum debug_obj_state state)
380dc186ad7SThomas Gleixner {
381dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
382dc186ad7SThomas Gleixner 
383dc186ad7SThomas Gleixner 	switch (state) {
384dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
385dc186ad7SThomas Gleixner 		cancel_work_sync(work);
386dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
387dc186ad7SThomas Gleixner 		return 1;
388dc186ad7SThomas Gleixner 	default:
389dc186ad7SThomas Gleixner 		return 0;
390dc186ad7SThomas Gleixner 	}
391dc186ad7SThomas Gleixner }
392dc186ad7SThomas Gleixner 
393dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr = {
394dc186ad7SThomas Gleixner 	.name		= "work_struct",
39599777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
396dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
397dc186ad7SThomas Gleixner 	.fixup_activate	= work_fixup_activate,
398dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
399dc186ad7SThomas Gleixner };
400dc186ad7SThomas Gleixner 
401dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
402dc186ad7SThomas Gleixner {
403dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
404dc186ad7SThomas Gleixner }
405dc186ad7SThomas Gleixner 
406dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
407dc186ad7SThomas Gleixner {
408dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
409dc186ad7SThomas Gleixner }
410dc186ad7SThomas Gleixner 
411dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
412dc186ad7SThomas Gleixner {
413dc186ad7SThomas Gleixner 	if (onstack)
414dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
415dc186ad7SThomas Gleixner 	else
416dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
417dc186ad7SThomas Gleixner }
418dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
419dc186ad7SThomas Gleixner 
420dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
421dc186ad7SThomas Gleixner {
422dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
423dc186ad7SThomas Gleixner }
424dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
425dc186ad7SThomas Gleixner 
426dc186ad7SThomas Gleixner #else
427dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
428dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
429dc186ad7SThomas Gleixner #endif
430dc186ad7SThomas Gleixner 
43195402b38SGautham R Shenoy /* Serializes the accesses to the list of workqueues. */
43295402b38SGautham R Shenoy static DEFINE_SPINLOCK(workqueue_lock);
4331da177e4SLinus Torvalds static LIST_HEAD(workqueues);
434a0a1a5fdSTejun Heo static bool workqueue_freezing;		/* W: have wqs started freezing? */
4351da177e4SLinus Torvalds 
43614441960SOleg Nesterov /*
437e19e397aSTejun Heo  * The CPU and unbound standard worker pools.  The unbound ones have
438e19e397aSTejun Heo  * POOL_DISASSOCIATED set, and their workers have WORKER_UNBOUND set.
43914441960SOleg Nesterov  */
440e19e397aSTejun Heo static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
441a60dc39cSTejun Heo 				     cpu_std_worker_pools);
442a60dc39cSTejun Heo static struct worker_pool unbound_std_worker_pools[NR_STD_WORKER_POOLS];
443f3421797STejun Heo 
444*fa1b54e6STejun Heo /*
445*fa1b54e6STejun Heo  * idr of all pools.  Modifications are protected by workqueue_lock.  Read
446*fa1b54e6STejun Heo  * accesses are protected by sched-RCU protected.
447*fa1b54e6STejun Heo  */
4489daf9e67STejun Heo static DEFINE_IDR(worker_pool_idr);
4499daf9e67STejun Heo 
450c34056a3STejun Heo static int worker_thread(void *__worker);
4511da177e4SLinus Torvalds 
452a60dc39cSTejun Heo static struct worker_pool *std_worker_pools(int cpu)
4531da177e4SLinus Torvalds {
454f3421797STejun Heo 	if (cpu != WORK_CPU_UNBOUND)
455a60dc39cSTejun Heo 		return per_cpu(cpu_std_worker_pools, cpu);
456f3421797STejun Heo 	else
457a60dc39cSTejun Heo 		return unbound_std_worker_pools;
4581da177e4SLinus Torvalds }
4591da177e4SLinus Torvalds 
4604e8f0a60STejun Heo static int std_worker_pool_pri(struct worker_pool *pool)
4614e8f0a60STejun Heo {
462a60dc39cSTejun Heo 	return pool - std_worker_pools(pool->cpu);
4634e8f0a60STejun Heo }
4644e8f0a60STejun Heo 
4659daf9e67STejun Heo /* allocate ID and assign it to @pool */
4669daf9e67STejun Heo static int worker_pool_assign_id(struct worker_pool *pool)
4679daf9e67STejun Heo {
4689daf9e67STejun Heo 	int ret;
4699daf9e67STejun Heo 
470*fa1b54e6STejun Heo 	do {
471*fa1b54e6STejun Heo 		if (!idr_pre_get(&worker_pool_idr, GFP_KERNEL))
472*fa1b54e6STejun Heo 			return -ENOMEM;
473*fa1b54e6STejun Heo 
474*fa1b54e6STejun Heo 		spin_lock_irq(&workqueue_lock);
4759daf9e67STejun Heo 		ret = idr_get_new(&worker_pool_idr, pool, &pool->id);
476*fa1b54e6STejun Heo 		spin_unlock_irq(&workqueue_lock);
477*fa1b54e6STejun Heo 	} while (ret == -EAGAIN);
4789daf9e67STejun Heo 
4799daf9e67STejun Heo 	return ret;
4809daf9e67STejun Heo }
4819daf9e67STejun Heo 
482d565ed63STejun Heo static struct worker_pool *get_std_worker_pool(int cpu, bool highpri)
483d565ed63STejun Heo {
484a60dc39cSTejun Heo 	struct worker_pool *pools = std_worker_pools(cpu);
485d565ed63STejun Heo 
486a60dc39cSTejun Heo 	return &pools[highpri];
487d565ed63STejun Heo }
488d565ed63STejun Heo 
48976af4d93STejun Heo /**
49076af4d93STejun Heo  * first_pwq - return the first pool_workqueue of the specified workqueue
49176af4d93STejun Heo  * @wq: the target workqueue
49276af4d93STejun Heo  *
49376af4d93STejun Heo  * This must be called either with workqueue_lock held or sched RCU read
49476af4d93STejun Heo  * locked.  If the pwq needs to be used beyond the locking in effect, the
49576af4d93STejun Heo  * caller is responsible for guaranteeing that the pwq stays online.
49676af4d93STejun Heo  */
4977fb98ea7STejun Heo static struct pool_workqueue *first_pwq(struct workqueue_struct *wq)
498a848e3b6SOleg Nesterov {
49976af4d93STejun Heo 	assert_rcu_or_wq_lock();
50076af4d93STejun Heo 	return list_first_or_null_rcu(&wq->pwqs, struct pool_workqueue,
50176af4d93STejun Heo 				      pwqs_node);
502f3421797STejun Heo }
503a848e3b6SOleg Nesterov 
50473f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
50573f53c4aSTejun Heo {
50673f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
50773f53c4aSTejun Heo }
50873f53c4aSTejun Heo 
50973f53c4aSTejun Heo static int get_work_color(struct work_struct *work)
51073f53c4aSTejun Heo {
51173f53c4aSTejun Heo 	return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
51273f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
51373f53c4aSTejun Heo }
51473f53c4aSTejun Heo 
51573f53c4aSTejun Heo static int work_next_color(int color)
51673f53c4aSTejun Heo {
51773f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
518b1f4ec17SOleg Nesterov }
519b1f4ec17SOleg Nesterov 
5204594bf15SDavid Howells /*
521112202d9STejun Heo  * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
522112202d9STejun Heo  * contain the pointer to the queued pwq.  Once execution starts, the flag
5237c3eed5cSTejun Heo  * is cleared and the high bits contain OFFQ flags and pool ID.
5247a22ad75STejun Heo  *
525112202d9STejun Heo  * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
526112202d9STejun Heo  * and clear_work_data() can be used to set the pwq, pool or clear
527bbb68dfaSTejun Heo  * work->data.  These functions should only be called while the work is
528bbb68dfaSTejun Heo  * owned - ie. while the PENDING bit is set.
5297a22ad75STejun Heo  *
530112202d9STejun Heo  * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
5317c3eed5cSTejun Heo  * corresponding to a work.  Pool is available once the work has been
532112202d9STejun Heo  * queued anywhere after initialization until it is sync canceled.  pwq is
5337c3eed5cSTejun Heo  * available only while the work item is queued.
534bbb68dfaSTejun Heo  *
535bbb68dfaSTejun Heo  * %WORK_OFFQ_CANCELING is used to mark a work item which is being
536bbb68dfaSTejun Heo  * canceled.  While being canceled, a work item may have its PENDING set
537bbb68dfaSTejun Heo  * but stay off timer and worklist for arbitrarily long and nobody should
538bbb68dfaSTejun Heo  * try to steal the PENDING bit.
5394594bf15SDavid Howells  */
5407a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
5417a22ad75STejun Heo 				 unsigned long flags)
5427a22ad75STejun Heo {
5436183c009STejun Heo 	WARN_ON_ONCE(!work_pending(work));
5447a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
5457a22ad75STejun Heo }
5467a22ad75STejun Heo 
547112202d9STejun Heo static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
5484690c4abSTejun Heo 			 unsigned long extra_flags)
549365970a1SDavid Howells {
550112202d9STejun Heo 	set_work_data(work, (unsigned long)pwq,
551112202d9STejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
552365970a1SDavid Howells }
553365970a1SDavid Howells 
5544468a00fSLai Jiangshan static void set_work_pool_and_keep_pending(struct work_struct *work,
5554468a00fSLai Jiangshan 					   int pool_id)
5564468a00fSLai Jiangshan {
5574468a00fSLai Jiangshan 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
5584468a00fSLai Jiangshan 		      WORK_STRUCT_PENDING);
5594468a00fSLai Jiangshan }
5604468a00fSLai Jiangshan 
5617c3eed5cSTejun Heo static void set_work_pool_and_clear_pending(struct work_struct *work,
5627c3eed5cSTejun Heo 					    int pool_id)
5634d707b9fSOleg Nesterov {
56423657bb1STejun Heo 	/*
56523657bb1STejun Heo 	 * The following wmb is paired with the implied mb in
56623657bb1STejun Heo 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
56723657bb1STejun Heo 	 * here are visible to and precede any updates by the next PENDING
56823657bb1STejun Heo 	 * owner.
56923657bb1STejun Heo 	 */
57023657bb1STejun Heo 	smp_wmb();
5717c3eed5cSTejun Heo 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
5724d707b9fSOleg Nesterov }
5734d707b9fSOleg Nesterov 
5747a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
575365970a1SDavid Howells {
5767c3eed5cSTejun Heo 	smp_wmb();	/* see set_work_pool_and_clear_pending() */
5777c3eed5cSTejun Heo 	set_work_data(work, WORK_STRUCT_NO_POOL, 0);
5787a22ad75STejun Heo }
5797a22ad75STejun Heo 
580112202d9STejun Heo static struct pool_workqueue *get_work_pwq(struct work_struct *work)
5817a22ad75STejun Heo {
582e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
5837a22ad75STejun Heo 
584112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
585e120153dSTejun Heo 		return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
586e120153dSTejun Heo 	else
587e120153dSTejun Heo 		return NULL;
5887a22ad75STejun Heo }
5897a22ad75STejun Heo 
5907c3eed5cSTejun Heo /**
5917c3eed5cSTejun Heo  * get_work_pool - return the worker_pool a given work was associated with
5927c3eed5cSTejun Heo  * @work: the work item of interest
5937c3eed5cSTejun Heo  *
5947c3eed5cSTejun Heo  * Return the worker_pool @work was last associated with.  %NULL if none.
595*fa1b54e6STejun Heo  *
596*fa1b54e6STejun Heo  * Pools are created and destroyed under workqueue_lock, and allows read
597*fa1b54e6STejun Heo  * access under sched-RCU read lock.  As such, this function should be
598*fa1b54e6STejun Heo  * called under workqueue_lock or with preemption disabled.
599*fa1b54e6STejun Heo  *
600*fa1b54e6STejun Heo  * All fields of the returned pool are accessible as long as the above
601*fa1b54e6STejun Heo  * mentioned locking is in effect.  If the returned pool needs to be used
602*fa1b54e6STejun Heo  * beyond the critical section, the caller is responsible for ensuring the
603*fa1b54e6STejun Heo  * returned pool is and stays online.
6047c3eed5cSTejun Heo  */
6057c3eed5cSTejun Heo static struct worker_pool *get_work_pool(struct work_struct *work)
6067a22ad75STejun Heo {
607e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
6087c3eed5cSTejun Heo 	int pool_id;
6097a22ad75STejun Heo 
610*fa1b54e6STejun Heo 	assert_rcu_or_wq_lock();
611*fa1b54e6STejun Heo 
612112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
613112202d9STejun Heo 		return ((struct pool_workqueue *)
6147c3eed5cSTejun Heo 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool;
6157a22ad75STejun Heo 
6167c3eed5cSTejun Heo 	pool_id = data >> WORK_OFFQ_POOL_SHIFT;
6177c3eed5cSTejun Heo 	if (pool_id == WORK_OFFQ_POOL_NONE)
6187a22ad75STejun Heo 		return NULL;
6197a22ad75STejun Heo 
620*fa1b54e6STejun Heo 	return idr_find(&worker_pool_idr, pool_id);
6217c3eed5cSTejun Heo }
6227c3eed5cSTejun Heo 
6237c3eed5cSTejun Heo /**
6247c3eed5cSTejun Heo  * get_work_pool_id - return the worker pool ID a given work is associated with
6257c3eed5cSTejun Heo  * @work: the work item of interest
6267c3eed5cSTejun Heo  *
6277c3eed5cSTejun Heo  * Return the worker_pool ID @work was last associated with.
6287c3eed5cSTejun Heo  * %WORK_OFFQ_POOL_NONE if none.
6297c3eed5cSTejun Heo  */
6307c3eed5cSTejun Heo static int get_work_pool_id(struct work_struct *work)
6317c3eed5cSTejun Heo {
63254d5b7d0SLai Jiangshan 	unsigned long data = atomic_long_read(&work->data);
6337c3eed5cSTejun Heo 
634112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
635112202d9STejun Heo 		return ((struct pool_workqueue *)
63654d5b7d0SLai Jiangshan 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
63754d5b7d0SLai Jiangshan 
63854d5b7d0SLai Jiangshan 	return data >> WORK_OFFQ_POOL_SHIFT;
6397c3eed5cSTejun Heo }
6407c3eed5cSTejun Heo 
641bbb68dfaSTejun Heo static void mark_work_canceling(struct work_struct *work)
642bbb68dfaSTejun Heo {
6437c3eed5cSTejun Heo 	unsigned long pool_id = get_work_pool_id(work);
644bbb68dfaSTejun Heo 
6457c3eed5cSTejun Heo 	pool_id <<= WORK_OFFQ_POOL_SHIFT;
6467c3eed5cSTejun Heo 	set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
647bbb68dfaSTejun Heo }
648bbb68dfaSTejun Heo 
649bbb68dfaSTejun Heo static bool work_is_canceling(struct work_struct *work)
650bbb68dfaSTejun Heo {
651bbb68dfaSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
652bbb68dfaSTejun Heo 
653112202d9STejun Heo 	return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
654bbb68dfaSTejun Heo }
655bbb68dfaSTejun Heo 
656e22bee78STejun Heo /*
6573270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
6583270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
659d565ed63STejun Heo  * they're being called with pool->lock held.
660e22bee78STejun Heo  */
661e22bee78STejun Heo 
66263d95a91STejun Heo static bool __need_more_worker(struct worker_pool *pool)
663649027d7STejun Heo {
664e19e397aSTejun Heo 	return !atomic_read(&pool->nr_running);
665649027d7STejun Heo }
666649027d7STejun Heo 
667e22bee78STejun Heo /*
668e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
669e22bee78STejun Heo  * running workers.
670974271c4STejun Heo  *
671974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
672706026c2STejun Heo  * function will always return %true for unbound pools as long as the
673974271c4STejun Heo  * worklist isn't empty.
674e22bee78STejun Heo  */
67563d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
676e22bee78STejun Heo {
67763d95a91STejun Heo 	return !list_empty(&pool->worklist) && __need_more_worker(pool);
678e22bee78STejun Heo }
679e22bee78STejun Heo 
680e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
68163d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
682e22bee78STejun Heo {
68363d95a91STejun Heo 	return pool->nr_idle;
684e22bee78STejun Heo }
685e22bee78STejun Heo 
686e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
68763d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
688e22bee78STejun Heo {
689e19e397aSTejun Heo 	return !list_empty(&pool->worklist) &&
690e19e397aSTejun Heo 		atomic_read(&pool->nr_running) <= 1;
691e22bee78STejun Heo }
692e22bee78STejun Heo 
693e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
69463d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
695e22bee78STejun Heo {
69663d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
697e22bee78STejun Heo }
698e22bee78STejun Heo 
699e22bee78STejun Heo /* Do I need to be the manager? */
70063d95a91STejun Heo static bool need_to_manage_workers(struct worker_pool *pool)
701e22bee78STejun Heo {
70263d95a91STejun Heo 	return need_to_create_worker(pool) ||
70311ebea50STejun Heo 		(pool->flags & POOL_MANAGE_WORKERS);
704e22bee78STejun Heo }
705e22bee78STejun Heo 
706e22bee78STejun Heo /* Do we have too many workers and should some go away? */
70763d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
708e22bee78STejun Heo {
709552a37e9SLai Jiangshan 	bool managing = pool->flags & POOL_MANAGING_WORKERS;
71063d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
71163d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
712e22bee78STejun Heo 
713ea1abd61SLai Jiangshan 	/*
714ea1abd61SLai Jiangshan 	 * nr_idle and idle_list may disagree if idle rebinding is in
715ea1abd61SLai Jiangshan 	 * progress.  Never return %true if idle_list is empty.
716ea1abd61SLai Jiangshan 	 */
717ea1abd61SLai Jiangshan 	if (list_empty(&pool->idle_list))
718ea1abd61SLai Jiangshan 		return false;
719ea1abd61SLai Jiangshan 
720e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
721e22bee78STejun Heo }
722e22bee78STejun Heo 
723e22bee78STejun Heo /*
724e22bee78STejun Heo  * Wake up functions.
725e22bee78STejun Heo  */
726e22bee78STejun Heo 
7277e11629dSTejun Heo /* Return the first worker.  Safe with preemption disabled */
72863d95a91STejun Heo static struct worker *first_worker(struct worker_pool *pool)
7297e11629dSTejun Heo {
73063d95a91STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
7317e11629dSTejun Heo 		return NULL;
7327e11629dSTejun Heo 
73363d95a91STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
7347e11629dSTejun Heo }
7357e11629dSTejun Heo 
7367e11629dSTejun Heo /**
7377e11629dSTejun Heo  * wake_up_worker - wake up an idle worker
73863d95a91STejun Heo  * @pool: worker pool to wake worker from
7397e11629dSTejun Heo  *
74063d95a91STejun Heo  * Wake up the first idle worker of @pool.
7417e11629dSTejun Heo  *
7427e11629dSTejun Heo  * CONTEXT:
743d565ed63STejun Heo  * spin_lock_irq(pool->lock).
7447e11629dSTejun Heo  */
74563d95a91STejun Heo static void wake_up_worker(struct worker_pool *pool)
7467e11629dSTejun Heo {
74763d95a91STejun Heo 	struct worker *worker = first_worker(pool);
7487e11629dSTejun Heo 
7497e11629dSTejun Heo 	if (likely(worker))
7507e11629dSTejun Heo 		wake_up_process(worker->task);
7517e11629dSTejun Heo }
7527e11629dSTejun Heo 
7534690c4abSTejun Heo /**
754e22bee78STejun Heo  * wq_worker_waking_up - a worker is waking up
755e22bee78STejun Heo  * @task: task waking up
756e22bee78STejun Heo  * @cpu: CPU @task is waking up to
757e22bee78STejun Heo  *
758e22bee78STejun Heo  * This function is called during try_to_wake_up() when a worker is
759e22bee78STejun Heo  * being awoken.
760e22bee78STejun Heo  *
761e22bee78STejun Heo  * CONTEXT:
762e22bee78STejun Heo  * spin_lock_irq(rq->lock)
763e22bee78STejun Heo  */
764d84ff051STejun Heo void wq_worker_waking_up(struct task_struct *task, int cpu)
765e22bee78STejun Heo {
766e22bee78STejun Heo 	struct worker *worker = kthread_data(task);
767e22bee78STejun Heo 
76836576000SJoonsoo Kim 	if (!(worker->flags & WORKER_NOT_RUNNING)) {
769ec22ca5eSTejun Heo 		WARN_ON_ONCE(worker->pool->cpu != cpu);
770e19e397aSTejun Heo 		atomic_inc(&worker->pool->nr_running);
771e22bee78STejun Heo 	}
77236576000SJoonsoo Kim }
773e22bee78STejun Heo 
774e22bee78STejun Heo /**
775e22bee78STejun Heo  * wq_worker_sleeping - a worker is going to sleep
776e22bee78STejun Heo  * @task: task going to sleep
777e22bee78STejun Heo  * @cpu: CPU in question, must be the current CPU number
778e22bee78STejun Heo  *
779e22bee78STejun Heo  * This function is called during schedule() when a busy worker is
780e22bee78STejun Heo  * going to sleep.  Worker on the same cpu can be woken up by
781e22bee78STejun Heo  * returning pointer to its task.
782e22bee78STejun Heo  *
783e22bee78STejun Heo  * CONTEXT:
784e22bee78STejun Heo  * spin_lock_irq(rq->lock)
785e22bee78STejun Heo  *
786e22bee78STejun Heo  * RETURNS:
787e22bee78STejun Heo  * Worker task on @cpu to wake up, %NULL if none.
788e22bee78STejun Heo  */
789d84ff051STejun Heo struct task_struct *wq_worker_sleeping(struct task_struct *task, int cpu)
790e22bee78STejun Heo {
791e22bee78STejun Heo 	struct worker *worker = kthread_data(task), *to_wakeup = NULL;
792111c225aSTejun Heo 	struct worker_pool *pool;
793e22bee78STejun Heo 
794111c225aSTejun Heo 	/*
795111c225aSTejun Heo 	 * Rescuers, which may not have all the fields set up like normal
796111c225aSTejun Heo 	 * workers, also reach here, let's not access anything before
797111c225aSTejun Heo 	 * checking NOT_RUNNING.
798111c225aSTejun Heo 	 */
7992d64672eSSteven Rostedt 	if (worker->flags & WORKER_NOT_RUNNING)
800e22bee78STejun Heo 		return NULL;
801e22bee78STejun Heo 
802111c225aSTejun Heo 	pool = worker->pool;
803111c225aSTejun Heo 
804e22bee78STejun Heo 	/* this can only happen on the local cpu */
8056183c009STejun Heo 	if (WARN_ON_ONCE(cpu != raw_smp_processor_id()))
8066183c009STejun Heo 		return NULL;
807e22bee78STejun Heo 
808e22bee78STejun Heo 	/*
809e22bee78STejun Heo 	 * The counterpart of the following dec_and_test, implied mb,
810e22bee78STejun Heo 	 * worklist not empty test sequence is in insert_work().
811e22bee78STejun Heo 	 * Please read comment there.
812e22bee78STejun Heo 	 *
813628c78e7STejun Heo 	 * NOT_RUNNING is clear.  This means that we're bound to and
814628c78e7STejun Heo 	 * running on the local cpu w/ rq lock held and preemption
815628c78e7STejun Heo 	 * disabled, which in turn means that none else could be
816d565ed63STejun Heo 	 * manipulating idle_list, so dereferencing idle_list without pool
817628c78e7STejun Heo 	 * lock is safe.
818e22bee78STejun Heo 	 */
819e19e397aSTejun Heo 	if (atomic_dec_and_test(&pool->nr_running) &&
820e19e397aSTejun Heo 	    !list_empty(&pool->worklist))
82163d95a91STejun Heo 		to_wakeup = first_worker(pool);
822e22bee78STejun Heo 	return to_wakeup ? to_wakeup->task : NULL;
823e22bee78STejun Heo }
824e22bee78STejun Heo 
825e22bee78STejun Heo /**
826e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
827cb444766STejun Heo  * @worker: self
828d302f017STejun Heo  * @flags: flags to set
829d302f017STejun Heo  * @wakeup: wakeup an idle worker if necessary
830d302f017STejun Heo  *
831e22bee78STejun Heo  * Set @flags in @worker->flags and adjust nr_running accordingly.  If
832e22bee78STejun Heo  * nr_running becomes zero and @wakeup is %true, an idle worker is
833e22bee78STejun Heo  * woken up.
834d302f017STejun Heo  *
835cb444766STejun Heo  * CONTEXT:
836d565ed63STejun Heo  * spin_lock_irq(pool->lock)
837d302f017STejun Heo  */
838d302f017STejun Heo static inline void worker_set_flags(struct worker *worker, unsigned int flags,
839d302f017STejun Heo 				    bool wakeup)
840d302f017STejun Heo {
841bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
842e22bee78STejun Heo 
843cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
844cb444766STejun Heo 
845e22bee78STejun Heo 	/*
846e22bee78STejun Heo 	 * If transitioning into NOT_RUNNING, adjust nr_running and
847e22bee78STejun Heo 	 * wake up an idle worker as necessary if requested by
848e22bee78STejun Heo 	 * @wakeup.
849e22bee78STejun Heo 	 */
850e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
851e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
852e22bee78STejun Heo 		if (wakeup) {
853e19e397aSTejun Heo 			if (atomic_dec_and_test(&pool->nr_running) &&
854bd7bdd43STejun Heo 			    !list_empty(&pool->worklist))
85563d95a91STejun Heo 				wake_up_worker(pool);
856e22bee78STejun Heo 		} else
857e19e397aSTejun Heo 			atomic_dec(&pool->nr_running);
858e22bee78STejun Heo 	}
859e22bee78STejun Heo 
860d302f017STejun Heo 	worker->flags |= flags;
861d302f017STejun Heo }
862d302f017STejun Heo 
863d302f017STejun Heo /**
864e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
865cb444766STejun Heo  * @worker: self
866d302f017STejun Heo  * @flags: flags to clear
867d302f017STejun Heo  *
868e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
869d302f017STejun Heo  *
870cb444766STejun Heo  * CONTEXT:
871d565ed63STejun Heo  * spin_lock_irq(pool->lock)
872d302f017STejun Heo  */
873d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
874d302f017STejun Heo {
87563d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
876e22bee78STejun Heo 	unsigned int oflags = worker->flags;
877e22bee78STejun Heo 
878cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
879cb444766STejun Heo 
880d302f017STejun Heo 	worker->flags &= ~flags;
881e22bee78STejun Heo 
88242c025f3STejun Heo 	/*
88342c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
88442c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
88542c025f3STejun Heo 	 * of multiple flags, not a single flag.
88642c025f3STejun Heo 	 */
887e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
888e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
889e19e397aSTejun Heo 			atomic_inc(&pool->nr_running);
890d302f017STejun Heo }
891d302f017STejun Heo 
892d302f017STejun Heo /**
8938cca0eeaSTejun Heo  * find_worker_executing_work - find worker which is executing a work
894c9e7cf27STejun Heo  * @pool: pool of interest
8958cca0eeaSTejun Heo  * @work: work to find worker for
8968cca0eeaSTejun Heo  *
897c9e7cf27STejun Heo  * Find a worker which is executing @work on @pool by searching
898c9e7cf27STejun Heo  * @pool->busy_hash which is keyed by the address of @work.  For a worker
899a2c1c57bSTejun Heo  * to match, its current execution should match the address of @work and
900a2c1c57bSTejun Heo  * its work function.  This is to avoid unwanted dependency between
901a2c1c57bSTejun Heo  * unrelated work executions through a work item being recycled while still
902a2c1c57bSTejun Heo  * being executed.
903a2c1c57bSTejun Heo  *
904a2c1c57bSTejun Heo  * This is a bit tricky.  A work item may be freed once its execution
905a2c1c57bSTejun Heo  * starts and nothing prevents the freed area from being recycled for
906a2c1c57bSTejun Heo  * another work item.  If the same work item address ends up being reused
907a2c1c57bSTejun Heo  * before the original execution finishes, workqueue will identify the
908a2c1c57bSTejun Heo  * recycled work item as currently executing and make it wait until the
909a2c1c57bSTejun Heo  * current execution finishes, introducing an unwanted dependency.
910a2c1c57bSTejun Heo  *
911a2c1c57bSTejun Heo  * This function checks the work item address, work function and workqueue
912a2c1c57bSTejun Heo  * to avoid false positives.  Note that this isn't complete as one may
913a2c1c57bSTejun Heo  * construct a work function which can introduce dependency onto itself
914a2c1c57bSTejun Heo  * through a recycled work item.  Well, if somebody wants to shoot oneself
915a2c1c57bSTejun Heo  * in the foot that badly, there's only so much we can do, and if such
916a2c1c57bSTejun Heo  * deadlock actually occurs, it should be easy to locate the culprit work
917a2c1c57bSTejun Heo  * function.
9188cca0eeaSTejun Heo  *
9198cca0eeaSTejun Heo  * CONTEXT:
920d565ed63STejun Heo  * spin_lock_irq(pool->lock).
9218cca0eeaSTejun Heo  *
9228cca0eeaSTejun Heo  * RETURNS:
9238cca0eeaSTejun Heo  * Pointer to worker which is executing @work if found, NULL
9248cca0eeaSTejun Heo  * otherwise.
9258cca0eeaSTejun Heo  */
926c9e7cf27STejun Heo static struct worker *find_worker_executing_work(struct worker_pool *pool,
9278cca0eeaSTejun Heo 						 struct work_struct *work)
9288cca0eeaSTejun Heo {
92942f8570fSSasha Levin 	struct worker *worker;
93042f8570fSSasha Levin 
931b67bfe0dSSasha Levin 	hash_for_each_possible(pool->busy_hash, worker, hentry,
932a2c1c57bSTejun Heo 			       (unsigned long)work)
933a2c1c57bSTejun Heo 		if (worker->current_work == work &&
934a2c1c57bSTejun Heo 		    worker->current_func == work->func)
93542f8570fSSasha Levin 			return worker;
93642f8570fSSasha Levin 
93742f8570fSSasha Levin 	return NULL;
9388cca0eeaSTejun Heo }
9398cca0eeaSTejun Heo 
9408cca0eeaSTejun Heo /**
941bf4ede01STejun Heo  * move_linked_works - move linked works to a list
942bf4ede01STejun Heo  * @work: start of series of works to be scheduled
943bf4ede01STejun Heo  * @head: target list to append @work to
944bf4ede01STejun Heo  * @nextp: out paramter for nested worklist walking
945bf4ede01STejun Heo  *
946bf4ede01STejun Heo  * Schedule linked works starting from @work to @head.  Work series to
947bf4ede01STejun Heo  * be scheduled starts at @work and includes any consecutive work with
948bf4ede01STejun Heo  * WORK_STRUCT_LINKED set in its predecessor.
949bf4ede01STejun Heo  *
950bf4ede01STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of
951bf4ede01STejun Heo  * the last scheduled work.  This allows move_linked_works() to be
952bf4ede01STejun Heo  * nested inside outer list_for_each_entry_safe().
953bf4ede01STejun Heo  *
954bf4ede01STejun Heo  * CONTEXT:
955d565ed63STejun Heo  * spin_lock_irq(pool->lock).
956bf4ede01STejun Heo  */
957bf4ede01STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
958bf4ede01STejun Heo 			      struct work_struct **nextp)
959bf4ede01STejun Heo {
960bf4ede01STejun Heo 	struct work_struct *n;
961bf4ede01STejun Heo 
962bf4ede01STejun Heo 	/*
963bf4ede01STejun Heo 	 * Linked worklist will always end before the end of the list,
964bf4ede01STejun Heo 	 * use NULL for list head.
965bf4ede01STejun Heo 	 */
966bf4ede01STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
967bf4ede01STejun Heo 		list_move_tail(&work->entry, head);
968bf4ede01STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
969bf4ede01STejun Heo 			break;
970bf4ede01STejun Heo 	}
971bf4ede01STejun Heo 
972bf4ede01STejun Heo 	/*
973bf4ede01STejun Heo 	 * If we're already inside safe list traversal and have moved
974bf4ede01STejun Heo 	 * multiple works to the scheduled queue, the next position
975bf4ede01STejun Heo 	 * needs to be updated.
976bf4ede01STejun Heo 	 */
977bf4ede01STejun Heo 	if (nextp)
978bf4ede01STejun Heo 		*nextp = n;
979bf4ede01STejun Heo }
980bf4ede01STejun Heo 
981112202d9STejun Heo static void pwq_activate_delayed_work(struct work_struct *work)
982bf4ede01STejun Heo {
983112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
984bf4ede01STejun Heo 
985bf4ede01STejun Heo 	trace_workqueue_activate_work(work);
986112202d9STejun Heo 	move_linked_works(work, &pwq->pool->worklist, NULL);
987bf4ede01STejun Heo 	__clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
988112202d9STejun Heo 	pwq->nr_active++;
989bf4ede01STejun Heo }
990bf4ede01STejun Heo 
991112202d9STejun Heo static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
9923aa62497SLai Jiangshan {
993112202d9STejun Heo 	struct work_struct *work = list_first_entry(&pwq->delayed_works,
9943aa62497SLai Jiangshan 						    struct work_struct, entry);
9953aa62497SLai Jiangshan 
996112202d9STejun Heo 	pwq_activate_delayed_work(work);
9973aa62497SLai Jiangshan }
9983aa62497SLai Jiangshan 
999bf4ede01STejun Heo /**
1000112202d9STejun Heo  * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1001112202d9STejun Heo  * @pwq: pwq of interest
1002bf4ede01STejun Heo  * @color: color of work which left the queue
1003bf4ede01STejun Heo  *
1004bf4ede01STejun Heo  * A work either has completed or is removed from pending queue,
1005112202d9STejun Heo  * decrement nr_in_flight of its pwq and handle workqueue flushing.
1006bf4ede01STejun Heo  *
1007bf4ede01STejun Heo  * CONTEXT:
1008d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1009bf4ede01STejun Heo  */
1010112202d9STejun Heo static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
1011bf4ede01STejun Heo {
1012bf4ede01STejun Heo 	/* ignore uncolored works */
1013bf4ede01STejun Heo 	if (color == WORK_NO_COLOR)
1014bf4ede01STejun Heo 		return;
1015bf4ede01STejun Heo 
1016112202d9STejun Heo 	pwq->nr_in_flight[color]--;
1017bf4ede01STejun Heo 
1018112202d9STejun Heo 	pwq->nr_active--;
1019112202d9STejun Heo 	if (!list_empty(&pwq->delayed_works)) {
1020bf4ede01STejun Heo 		/* one down, submit a delayed one */
1021112202d9STejun Heo 		if (pwq->nr_active < pwq->max_active)
1022112202d9STejun Heo 			pwq_activate_first_delayed(pwq);
1023bf4ede01STejun Heo 	}
1024bf4ede01STejun Heo 
1025bf4ede01STejun Heo 	/* is flush in progress and are we at the flushing tip? */
1026112202d9STejun Heo 	if (likely(pwq->flush_color != color))
1027bf4ede01STejun Heo 		return;
1028bf4ede01STejun Heo 
1029bf4ede01STejun Heo 	/* are there still in-flight works? */
1030112202d9STejun Heo 	if (pwq->nr_in_flight[color])
1031bf4ede01STejun Heo 		return;
1032bf4ede01STejun Heo 
1033112202d9STejun Heo 	/* this pwq is done, clear flush_color */
1034112202d9STejun Heo 	pwq->flush_color = -1;
1035bf4ede01STejun Heo 
1036bf4ede01STejun Heo 	/*
1037112202d9STejun Heo 	 * If this was the last pwq, wake up the first flusher.  It
1038bf4ede01STejun Heo 	 * will handle the rest.
1039bf4ede01STejun Heo 	 */
1040112202d9STejun Heo 	if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1041112202d9STejun Heo 		complete(&pwq->wq->first_flusher->done);
1042bf4ede01STejun Heo }
1043bf4ede01STejun Heo 
104436e227d2STejun Heo /**
1045bbb68dfaSTejun Heo  * try_to_grab_pending - steal work item from worklist and disable irq
104636e227d2STejun Heo  * @work: work item to steal
104736e227d2STejun Heo  * @is_dwork: @work is a delayed_work
1048bbb68dfaSTejun Heo  * @flags: place to store irq state
104936e227d2STejun Heo  *
105036e227d2STejun Heo  * Try to grab PENDING bit of @work.  This function can handle @work in any
105136e227d2STejun Heo  * stable state - idle, on timer or on worklist.  Return values are
105236e227d2STejun Heo  *
105336e227d2STejun Heo  *  1		if @work was pending and we successfully stole PENDING
105436e227d2STejun Heo  *  0		if @work was idle and we claimed PENDING
105536e227d2STejun Heo  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
1056bbb68dfaSTejun Heo  *  -ENOENT	if someone else is canceling @work, this state may persist
1057bbb68dfaSTejun Heo  *		for arbitrarily long
105836e227d2STejun Heo  *
1059bbb68dfaSTejun Heo  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
1060e0aecdd8STejun Heo  * interrupted while holding PENDING and @work off queue, irq must be
1061e0aecdd8STejun Heo  * disabled on entry.  This, combined with delayed_work->timer being
1062e0aecdd8STejun Heo  * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1063bbb68dfaSTejun Heo  *
1064bbb68dfaSTejun Heo  * On successful return, >= 0, irq is disabled and the caller is
1065bbb68dfaSTejun Heo  * responsible for releasing it using local_irq_restore(*@flags).
1066bbb68dfaSTejun Heo  *
1067e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
1068bf4ede01STejun Heo  */
1069bbb68dfaSTejun Heo static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1070bbb68dfaSTejun Heo 			       unsigned long *flags)
1071bf4ede01STejun Heo {
1072d565ed63STejun Heo 	struct worker_pool *pool;
1073112202d9STejun Heo 	struct pool_workqueue *pwq;
1074bf4ede01STejun Heo 
1075bbb68dfaSTejun Heo 	local_irq_save(*flags);
1076bbb68dfaSTejun Heo 
107736e227d2STejun Heo 	/* try to steal the timer if it exists */
107836e227d2STejun Heo 	if (is_dwork) {
107936e227d2STejun Heo 		struct delayed_work *dwork = to_delayed_work(work);
108036e227d2STejun Heo 
1081e0aecdd8STejun Heo 		/*
1082e0aecdd8STejun Heo 		 * dwork->timer is irqsafe.  If del_timer() fails, it's
1083e0aecdd8STejun Heo 		 * guaranteed that the timer is not queued anywhere and not
1084e0aecdd8STejun Heo 		 * running on the local CPU.
1085e0aecdd8STejun Heo 		 */
108636e227d2STejun Heo 		if (likely(del_timer(&dwork->timer)))
108736e227d2STejun Heo 			return 1;
108836e227d2STejun Heo 	}
108936e227d2STejun Heo 
109036e227d2STejun Heo 	/* try to claim PENDING the normal way */
1091bf4ede01STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1092bf4ede01STejun Heo 		return 0;
1093bf4ede01STejun Heo 
1094bf4ede01STejun Heo 	/*
1095bf4ede01STejun Heo 	 * The queueing is in progress, or it is already queued. Try to
1096bf4ede01STejun Heo 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1097bf4ede01STejun Heo 	 */
1098d565ed63STejun Heo 	pool = get_work_pool(work);
1099d565ed63STejun Heo 	if (!pool)
1100bbb68dfaSTejun Heo 		goto fail;
1101bf4ede01STejun Heo 
1102d565ed63STejun Heo 	spin_lock(&pool->lock);
1103bf4ede01STejun Heo 	/*
1104112202d9STejun Heo 	 * work->data is guaranteed to point to pwq only while the work
1105112202d9STejun Heo 	 * item is queued on pwq->wq, and both updating work->data to point
1106112202d9STejun Heo 	 * to pwq on queueing and to pool on dequeueing are done under
1107112202d9STejun Heo 	 * pwq->pool->lock.  This in turn guarantees that, if work->data
1108112202d9STejun Heo 	 * points to pwq which is associated with a locked pool, the work
11090b3dae68SLai Jiangshan 	 * item is currently queued on that pool.
1110bf4ede01STejun Heo 	 */
1111112202d9STejun Heo 	pwq = get_work_pwq(work);
1112112202d9STejun Heo 	if (pwq && pwq->pool == pool) {
1113bf4ede01STejun Heo 		debug_work_deactivate(work);
11143aa62497SLai Jiangshan 
11153aa62497SLai Jiangshan 		/*
111616062836STejun Heo 		 * A delayed work item cannot be grabbed directly because
111716062836STejun Heo 		 * it might have linked NO_COLOR work items which, if left
1118112202d9STejun Heo 		 * on the delayed_list, will confuse pwq->nr_active
111916062836STejun Heo 		 * management later on and cause stall.  Make sure the work
112016062836STejun Heo 		 * item is activated before grabbing.
11213aa62497SLai Jiangshan 		 */
11223aa62497SLai Jiangshan 		if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1123112202d9STejun Heo 			pwq_activate_delayed_work(work);
11243aa62497SLai Jiangshan 
1125bf4ede01STejun Heo 		list_del_init(&work->entry);
1126112202d9STejun Heo 		pwq_dec_nr_in_flight(get_work_pwq(work), get_work_color(work));
112736e227d2STejun Heo 
1128112202d9STejun Heo 		/* work->data points to pwq iff queued, point to pool */
11294468a00fSLai Jiangshan 		set_work_pool_and_keep_pending(work, pool->id);
11304468a00fSLai Jiangshan 
1131d565ed63STejun Heo 		spin_unlock(&pool->lock);
113236e227d2STejun Heo 		return 1;
1133bf4ede01STejun Heo 	}
1134d565ed63STejun Heo 	spin_unlock(&pool->lock);
1135bbb68dfaSTejun Heo fail:
1136bbb68dfaSTejun Heo 	local_irq_restore(*flags);
1137bbb68dfaSTejun Heo 	if (work_is_canceling(work))
1138bbb68dfaSTejun Heo 		return -ENOENT;
1139bbb68dfaSTejun Heo 	cpu_relax();
114036e227d2STejun Heo 	return -EAGAIN;
1141bf4ede01STejun Heo }
1142bf4ede01STejun Heo 
1143bf4ede01STejun Heo /**
1144706026c2STejun Heo  * insert_work - insert a work into a pool
1145112202d9STejun Heo  * @pwq: pwq @work belongs to
11464690c4abSTejun Heo  * @work: work to insert
11474690c4abSTejun Heo  * @head: insertion point
11484690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
11494690c4abSTejun Heo  *
1150112202d9STejun Heo  * Insert @work which belongs to @pwq after @head.  @extra_flags is or'd to
1151706026c2STejun Heo  * work_struct flags.
11524690c4abSTejun Heo  *
11534690c4abSTejun Heo  * CONTEXT:
1154d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1155365970a1SDavid Howells  */
1156112202d9STejun Heo static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1157112202d9STejun Heo 			struct list_head *head, unsigned int extra_flags)
1158b89deed3SOleg Nesterov {
1159112202d9STejun Heo 	struct worker_pool *pool = pwq->pool;
1160e1d8aa9fSFrederic Weisbecker 
11614690c4abSTejun Heo 	/* we own @work, set data and link */
1162112202d9STejun Heo 	set_work_pwq(work, pwq, extra_flags);
11631a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
1164e22bee78STejun Heo 
1165e22bee78STejun Heo 	/*
1166e22bee78STejun Heo 	 * Ensure either worker_sched_deactivated() sees the above
1167e22bee78STejun Heo 	 * list_add_tail() or we see zero nr_running to avoid workers
1168e22bee78STejun Heo 	 * lying around lazily while there are works to be processed.
1169e22bee78STejun Heo 	 */
1170e22bee78STejun Heo 	smp_mb();
1171e22bee78STejun Heo 
117263d95a91STejun Heo 	if (__need_more_worker(pool))
117363d95a91STejun Heo 		wake_up_worker(pool);
1174b89deed3SOleg Nesterov }
1175b89deed3SOleg Nesterov 
1176c8efcc25STejun Heo /*
1177c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
11788d03ecfeSTejun Heo  * same workqueue.
1179c8efcc25STejun Heo  */
1180c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
1181c8efcc25STejun Heo {
1182c8efcc25STejun Heo 	struct worker *worker;
1183c8efcc25STejun Heo 
11848d03ecfeSTejun Heo 	worker = current_wq_worker();
1185c8efcc25STejun Heo 	/*
11868d03ecfeSTejun Heo 	 * Return %true iff I'm a worker execuing a work item on @wq.  If
11878d03ecfeSTejun Heo 	 * I'm @worker, it's safe to dereference it without locking.
1188c8efcc25STejun Heo 	 */
1189112202d9STejun Heo 	return worker && worker->current_pwq->wq == wq;
1190c8efcc25STejun Heo }
1191c8efcc25STejun Heo 
1192d84ff051STejun Heo static void __queue_work(int cpu, struct workqueue_struct *wq,
11931da177e4SLinus Torvalds 			 struct work_struct *work)
11941da177e4SLinus Torvalds {
1195112202d9STejun Heo 	struct pool_workqueue *pwq;
11961e19ffc6STejun Heo 	struct list_head *worklist;
11978a2e8e5dSTejun Heo 	unsigned int work_flags;
1198b75cac93SJoonsoo Kim 	unsigned int req_cpu = cpu;
11998930cabaSTejun Heo 
12008930cabaSTejun Heo 	/*
12018930cabaSTejun Heo 	 * While a work item is PENDING && off queue, a task trying to
12028930cabaSTejun Heo 	 * steal the PENDING will busy-loop waiting for it to either get
12038930cabaSTejun Heo 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
12048930cabaSTejun Heo 	 * happen with IRQ disabled.
12058930cabaSTejun Heo 	 */
12068930cabaSTejun Heo 	WARN_ON_ONCE(!irqs_disabled());
12071da177e4SLinus Torvalds 
1208dc186ad7SThomas Gleixner 	debug_work_activate(work);
12091e19ffc6STejun Heo 
1210c8efcc25STejun Heo 	/* if dying, only works from the same workqueue are allowed */
12119c5a2ba7STejun Heo 	if (unlikely(wq->flags & WQ_DRAINING) &&
1212c8efcc25STejun Heo 	    WARN_ON_ONCE(!is_chained_work(wq)))
1213e41e704bSTejun Heo 		return;
1214e41e704bSTejun Heo 
1215112202d9STejun Heo 	/* determine the pwq to use */
1216c7fc77f7STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
1217c9e7cf27STejun Heo 		struct worker_pool *last_pool;
1218c7fc77f7STejun Heo 
121957469821STejun Heo 		if (cpu == WORK_CPU_UNBOUND)
1220f3421797STejun Heo 			cpu = raw_smp_processor_id();
1221f3421797STejun Heo 
122218aa9effSTejun Heo 		/*
1223dbf2576eSTejun Heo 		 * It's multi cpu.  If @work was previously on a different
1224dbf2576eSTejun Heo 		 * cpu, it might still be running there, in which case the
1225dbf2576eSTejun Heo 		 * work needs to be queued on that cpu to guarantee
1226dbf2576eSTejun Heo 		 * non-reentrancy.
122718aa9effSTejun Heo 		 */
12287fb98ea7STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1229c9e7cf27STejun Heo 		last_pool = get_work_pool(work);
1230dbf2576eSTejun Heo 
1231112202d9STejun Heo 		if (last_pool && last_pool != pwq->pool) {
123218aa9effSTejun Heo 			struct worker *worker;
123318aa9effSTejun Heo 
1234d565ed63STejun Heo 			spin_lock(&last_pool->lock);
123518aa9effSTejun Heo 
1236c9e7cf27STejun Heo 			worker = find_worker_executing_work(last_pool, work);
123718aa9effSTejun Heo 
1238112202d9STejun Heo 			if (worker && worker->current_pwq->wq == wq) {
12397fb98ea7STejun Heo 				pwq = per_cpu_ptr(wq->cpu_pwqs, last_pool->cpu);
12408594fadeSLai Jiangshan 			} else {
124118aa9effSTejun Heo 				/* meh... not running there, queue here */
1242d565ed63STejun Heo 				spin_unlock(&last_pool->lock);
1243112202d9STejun Heo 				spin_lock(&pwq->pool->lock);
124418aa9effSTejun Heo 			}
12458930cabaSTejun Heo 		} else {
1246112202d9STejun Heo 			spin_lock(&pwq->pool->lock);
12478930cabaSTejun Heo 		}
1248f3421797STejun Heo 	} else {
12497fb98ea7STejun Heo 		pwq = first_pwq(wq);
1250112202d9STejun Heo 		spin_lock(&pwq->pool->lock);
1251502ca9d8STejun Heo 	}
1252502ca9d8STejun Heo 
1253112202d9STejun Heo 	/* pwq determined, queue */
1254112202d9STejun Heo 	trace_workqueue_queue_work(req_cpu, pwq, work);
1255502ca9d8STejun Heo 
1256f5b2552bSDan Carpenter 	if (WARN_ON(!list_empty(&work->entry))) {
1257112202d9STejun Heo 		spin_unlock(&pwq->pool->lock);
1258f5b2552bSDan Carpenter 		return;
1259f5b2552bSDan Carpenter 	}
12601e19ffc6STejun Heo 
1261112202d9STejun Heo 	pwq->nr_in_flight[pwq->work_color]++;
1262112202d9STejun Heo 	work_flags = work_color_to_flags(pwq->work_color);
12631e19ffc6STejun Heo 
1264112202d9STejun Heo 	if (likely(pwq->nr_active < pwq->max_active)) {
1265cdadf009STejun Heo 		trace_workqueue_activate_work(work);
1266112202d9STejun Heo 		pwq->nr_active++;
1267112202d9STejun Heo 		worklist = &pwq->pool->worklist;
12688a2e8e5dSTejun Heo 	} else {
12698a2e8e5dSTejun Heo 		work_flags |= WORK_STRUCT_DELAYED;
1270112202d9STejun Heo 		worklist = &pwq->delayed_works;
12718a2e8e5dSTejun Heo 	}
12721e19ffc6STejun Heo 
1273112202d9STejun Heo 	insert_work(pwq, work, worklist, work_flags);
12741e19ffc6STejun Heo 
1275112202d9STejun Heo 	spin_unlock(&pwq->pool->lock);
12761da177e4SLinus Torvalds }
12771da177e4SLinus Torvalds 
12780fcb78c2SRolf Eike Beer /**
1279c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
1280c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
1281c1a220e7SZhang Rui  * @wq: workqueue to use
1282c1a220e7SZhang Rui  * @work: work to queue
1283c1a220e7SZhang Rui  *
1284d4283e93STejun Heo  * Returns %false if @work was already on a queue, %true otherwise.
1285c1a220e7SZhang Rui  *
1286c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
1287c1a220e7SZhang Rui  * can't go away.
1288c1a220e7SZhang Rui  */
1289d4283e93STejun Heo bool queue_work_on(int cpu, struct workqueue_struct *wq,
1290d4283e93STejun Heo 		   struct work_struct *work)
1291c1a220e7SZhang Rui {
1292d4283e93STejun Heo 	bool ret = false;
12938930cabaSTejun Heo 	unsigned long flags;
12948930cabaSTejun Heo 
12958930cabaSTejun Heo 	local_irq_save(flags);
1296c1a220e7SZhang Rui 
129722df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
12984690c4abSTejun Heo 		__queue_work(cpu, wq, work);
1299d4283e93STejun Heo 		ret = true;
1300c1a220e7SZhang Rui 	}
13018930cabaSTejun Heo 
13028930cabaSTejun Heo 	local_irq_restore(flags);
1303c1a220e7SZhang Rui 	return ret;
1304c1a220e7SZhang Rui }
1305c1a220e7SZhang Rui EXPORT_SYMBOL_GPL(queue_work_on);
1306c1a220e7SZhang Rui 
13070a13c00eSTejun Heo /**
13080a13c00eSTejun Heo  * queue_work - queue work on a workqueue
13090a13c00eSTejun Heo  * @wq: workqueue to use
13100a13c00eSTejun Heo  * @work: work to queue
13110a13c00eSTejun Heo  *
1312d4283e93STejun Heo  * Returns %false if @work was already on a queue, %true otherwise.
13130a13c00eSTejun Heo  *
13140a13c00eSTejun Heo  * We queue the work to the CPU on which it was submitted, but if the CPU dies
13150a13c00eSTejun Heo  * it can be processed by another CPU.
13160a13c00eSTejun Heo  */
1317d4283e93STejun Heo bool queue_work(struct workqueue_struct *wq, struct work_struct *work)
13180a13c00eSTejun Heo {
131957469821STejun Heo 	return queue_work_on(WORK_CPU_UNBOUND, wq, work);
13200a13c00eSTejun Heo }
13210a13c00eSTejun Heo EXPORT_SYMBOL_GPL(queue_work);
13220a13c00eSTejun Heo 
1323d8e794dfSTejun Heo void delayed_work_timer_fn(unsigned long __data)
13241da177e4SLinus Torvalds {
132552bad64dSDavid Howells 	struct delayed_work *dwork = (struct delayed_work *)__data;
13261da177e4SLinus Torvalds 
1327e0aecdd8STejun Heo 	/* should have been called from irqsafe timer with irq already off */
132860c057bcSLai Jiangshan 	__queue_work(dwork->cpu, dwork->wq, &dwork->work);
13291da177e4SLinus Torvalds }
13301438ade5SKonstantin Khlebnikov EXPORT_SYMBOL(delayed_work_timer_fn);
13311da177e4SLinus Torvalds 
13327beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
133352bad64dSDavid Howells 				struct delayed_work *dwork, unsigned long delay)
13341da177e4SLinus Torvalds {
13357beb2edfSTejun Heo 	struct timer_list *timer = &dwork->timer;
13367beb2edfSTejun Heo 	struct work_struct *work = &dwork->work;
13371da177e4SLinus Torvalds 
13387beb2edfSTejun Heo 	WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
13397beb2edfSTejun Heo 		     timer->data != (unsigned long)dwork);
1340fc4b514fSTejun Heo 	WARN_ON_ONCE(timer_pending(timer));
1341fc4b514fSTejun Heo 	WARN_ON_ONCE(!list_empty(&work->entry));
13427beb2edfSTejun Heo 
13438852aac2STejun Heo 	/*
13448852aac2STejun Heo 	 * If @delay is 0, queue @dwork->work immediately.  This is for
13458852aac2STejun Heo 	 * both optimization and correctness.  The earliest @timer can
13468852aac2STejun Heo 	 * expire is on the closest next tick and delayed_work users depend
13478852aac2STejun Heo 	 * on that there's no such delay when @delay is 0.
13488852aac2STejun Heo 	 */
13498852aac2STejun Heo 	if (!delay) {
13508852aac2STejun Heo 		__queue_work(cpu, wq, &dwork->work);
13518852aac2STejun Heo 		return;
13528852aac2STejun Heo 	}
13538852aac2STejun Heo 
13547beb2edfSTejun Heo 	timer_stats_timer_set_start_info(&dwork->timer);
13557beb2edfSTejun Heo 
135660c057bcSLai Jiangshan 	dwork->wq = wq;
13571265057fSTejun Heo 	dwork->cpu = cpu;
13587beb2edfSTejun Heo 	timer->expires = jiffies + delay;
13597beb2edfSTejun Heo 
13607beb2edfSTejun Heo 	if (unlikely(cpu != WORK_CPU_UNBOUND))
13617beb2edfSTejun Heo 		add_timer_on(timer, cpu);
13627beb2edfSTejun Heo 	else
13637beb2edfSTejun Heo 		add_timer(timer);
13647beb2edfSTejun Heo }
13651da177e4SLinus Torvalds 
13660fcb78c2SRolf Eike Beer /**
13670fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
13680fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
13690fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1370af9997e4SRandy Dunlap  * @dwork: work to queue
13710fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
13720fcb78c2SRolf Eike Beer  *
1373715f1300STejun Heo  * Returns %false if @work was already on a queue, %true otherwise.  If
1374715f1300STejun Heo  * @delay is zero and @dwork is idle, it will be scheduled for immediate
1375715f1300STejun Heo  * execution.
13760fcb78c2SRolf Eike Beer  */
1377d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
137852bad64dSDavid Howells 			   struct delayed_work *dwork, unsigned long delay)
13797a6bc1cdSVenkatesh Pallipadi {
138052bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
1381d4283e93STejun Heo 	bool ret = false;
13828930cabaSTejun Heo 	unsigned long flags;
13838930cabaSTejun Heo 
13848930cabaSTejun Heo 	/* read the comment in __queue_work() */
13858930cabaSTejun Heo 	local_irq_save(flags);
13867a6bc1cdSVenkatesh Pallipadi 
138722df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
13887beb2edfSTejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
1389d4283e93STejun Heo 		ret = true;
13907a6bc1cdSVenkatesh Pallipadi 	}
13918930cabaSTejun Heo 
13928930cabaSTejun Heo 	local_irq_restore(flags);
13937a6bc1cdSVenkatesh Pallipadi 	return ret;
13947a6bc1cdSVenkatesh Pallipadi }
1395ae90dd5dSDave Jones EXPORT_SYMBOL_GPL(queue_delayed_work_on);
13961da177e4SLinus Torvalds 
1397c8e55f36STejun Heo /**
13980a13c00eSTejun Heo  * queue_delayed_work - queue work on a workqueue after delay
13990a13c00eSTejun Heo  * @wq: workqueue to use
14000a13c00eSTejun Heo  * @dwork: delayable work to queue
14010a13c00eSTejun Heo  * @delay: number of jiffies to wait before queueing
14020a13c00eSTejun Heo  *
1403715f1300STejun Heo  * Equivalent to queue_delayed_work_on() but tries to use the local CPU.
14040a13c00eSTejun Heo  */
1405d4283e93STejun Heo bool queue_delayed_work(struct workqueue_struct *wq,
14060a13c00eSTejun Heo 			struct delayed_work *dwork, unsigned long delay)
14070a13c00eSTejun Heo {
140857469821STejun Heo 	return queue_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
14090a13c00eSTejun Heo }
14100a13c00eSTejun Heo EXPORT_SYMBOL_GPL(queue_delayed_work);
14110a13c00eSTejun Heo 
14120a13c00eSTejun Heo /**
14138376fe22STejun Heo  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
14148376fe22STejun Heo  * @cpu: CPU number to execute work on
14158376fe22STejun Heo  * @wq: workqueue to use
14168376fe22STejun Heo  * @dwork: work to queue
14178376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
14188376fe22STejun Heo  *
14198376fe22STejun Heo  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
14208376fe22STejun Heo  * modify @dwork's timer so that it expires after @delay.  If @delay is
14218376fe22STejun Heo  * zero, @work is guaranteed to be scheduled immediately regardless of its
14228376fe22STejun Heo  * current state.
14238376fe22STejun Heo  *
14248376fe22STejun Heo  * Returns %false if @dwork was idle and queued, %true if @dwork was
14258376fe22STejun Heo  * pending and its timer was modified.
14268376fe22STejun Heo  *
1427e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
14288376fe22STejun Heo  * See try_to_grab_pending() for details.
14298376fe22STejun Heo  */
14308376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
14318376fe22STejun Heo 			 struct delayed_work *dwork, unsigned long delay)
14328376fe22STejun Heo {
14338376fe22STejun Heo 	unsigned long flags;
14348376fe22STejun Heo 	int ret;
14358376fe22STejun Heo 
14368376fe22STejun Heo 	do {
14378376fe22STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
14388376fe22STejun Heo 	} while (unlikely(ret == -EAGAIN));
14398376fe22STejun Heo 
14408376fe22STejun Heo 	if (likely(ret >= 0)) {
14418376fe22STejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
14428376fe22STejun Heo 		local_irq_restore(flags);
14438376fe22STejun Heo 	}
14448376fe22STejun Heo 
14458376fe22STejun Heo 	/* -ENOENT from try_to_grab_pending() becomes %true */
14468376fe22STejun Heo 	return ret;
14478376fe22STejun Heo }
14488376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
14498376fe22STejun Heo 
14508376fe22STejun Heo /**
14518376fe22STejun Heo  * mod_delayed_work - modify delay of or queue a delayed work
14528376fe22STejun Heo  * @wq: workqueue to use
14538376fe22STejun Heo  * @dwork: work to queue
14548376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
14558376fe22STejun Heo  *
14568376fe22STejun Heo  * mod_delayed_work_on() on local CPU.
14578376fe22STejun Heo  */
14588376fe22STejun Heo bool mod_delayed_work(struct workqueue_struct *wq, struct delayed_work *dwork,
14598376fe22STejun Heo 		      unsigned long delay)
14608376fe22STejun Heo {
14618376fe22STejun Heo 	return mod_delayed_work_on(WORK_CPU_UNBOUND, wq, dwork, delay);
14628376fe22STejun Heo }
14638376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work);
14648376fe22STejun Heo 
14658376fe22STejun Heo /**
1466c8e55f36STejun Heo  * worker_enter_idle - enter idle state
1467c8e55f36STejun Heo  * @worker: worker which is entering idle state
1468c8e55f36STejun Heo  *
1469c8e55f36STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
1470c8e55f36STejun Heo  * necessary.
1471c8e55f36STejun Heo  *
1472c8e55f36STejun Heo  * LOCKING:
1473d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1474c8e55f36STejun Heo  */
1475c8e55f36STejun Heo static void worker_enter_idle(struct worker *worker)
14761da177e4SLinus Torvalds {
1477bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1478c8e55f36STejun Heo 
14796183c009STejun Heo 	if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
14806183c009STejun Heo 	    WARN_ON_ONCE(!list_empty(&worker->entry) &&
14816183c009STejun Heo 			 (worker->hentry.next || worker->hentry.pprev)))
14826183c009STejun Heo 		return;
1483c8e55f36STejun Heo 
1484cb444766STejun Heo 	/* can't use worker_set_flags(), also called from start_worker() */
1485cb444766STejun Heo 	worker->flags |= WORKER_IDLE;
1486bd7bdd43STejun Heo 	pool->nr_idle++;
1487e22bee78STejun Heo 	worker->last_active = jiffies;
1488c8e55f36STejun Heo 
1489c8e55f36STejun Heo 	/* idle_list is LIFO */
1490bd7bdd43STejun Heo 	list_add(&worker->entry, &pool->idle_list);
1491db7bccf4STejun Heo 
149263d95a91STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1493628c78e7STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1494cb444766STejun Heo 
1495544ecf31STejun Heo 	/*
1496706026c2STejun Heo 	 * Sanity check nr_running.  Because wq_unbind_fn() releases
1497d565ed63STejun Heo 	 * pool->lock between setting %WORKER_UNBOUND and zapping
1498628c78e7STejun Heo 	 * nr_running, the warning may trigger spuriously.  Check iff
1499628c78e7STejun Heo 	 * unbind is not in progress.
1500544ecf31STejun Heo 	 */
150124647570STejun Heo 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1502bd7bdd43STejun Heo 		     pool->nr_workers == pool->nr_idle &&
1503e19e397aSTejun Heo 		     atomic_read(&pool->nr_running));
1504c8e55f36STejun Heo }
1505c8e55f36STejun Heo 
1506c8e55f36STejun Heo /**
1507c8e55f36STejun Heo  * worker_leave_idle - leave idle state
1508c8e55f36STejun Heo  * @worker: worker which is leaving idle state
1509c8e55f36STejun Heo  *
1510c8e55f36STejun Heo  * @worker is leaving idle state.  Update stats.
1511c8e55f36STejun Heo  *
1512c8e55f36STejun Heo  * LOCKING:
1513d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1514c8e55f36STejun Heo  */
1515c8e55f36STejun Heo static void worker_leave_idle(struct worker *worker)
1516c8e55f36STejun Heo {
1517bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1518c8e55f36STejun Heo 
15196183c009STejun Heo 	if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
15206183c009STejun Heo 		return;
1521d302f017STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
1522bd7bdd43STejun Heo 	pool->nr_idle--;
1523c8e55f36STejun Heo 	list_del_init(&worker->entry);
1524c8e55f36STejun Heo }
1525c8e55f36STejun Heo 
1526e22bee78STejun Heo /**
1527f36dc67bSLai Jiangshan  * worker_maybe_bind_and_lock - try to bind %current to worker_pool and lock it
1528f36dc67bSLai Jiangshan  * @pool: target worker_pool
1529f36dc67bSLai Jiangshan  *
1530f36dc67bSLai Jiangshan  * Bind %current to the cpu of @pool if it is associated and lock @pool.
1531e22bee78STejun Heo  *
1532e22bee78STejun Heo  * Works which are scheduled while the cpu is online must at least be
1533e22bee78STejun Heo  * scheduled to a worker which is bound to the cpu so that if they are
1534e22bee78STejun Heo  * flushed from cpu callbacks while cpu is going down, they are
1535e22bee78STejun Heo  * guaranteed to execute on the cpu.
1536e22bee78STejun Heo  *
1537f5faa077SLai Jiangshan  * This function is to be used by unbound workers and rescuers to bind
1538e22bee78STejun Heo  * themselves to the target cpu and may race with cpu going down or
1539e22bee78STejun Heo  * coming online.  kthread_bind() can't be used because it may put the
1540e22bee78STejun Heo  * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1541706026c2STejun Heo  * verbatim as it's best effort and blocking and pool may be
1542e22bee78STejun Heo  * [dis]associated in the meantime.
1543e22bee78STejun Heo  *
1544706026c2STejun Heo  * This function tries set_cpus_allowed() and locks pool and verifies the
154524647570STejun Heo  * binding against %POOL_DISASSOCIATED which is set during
1546f2d5a0eeSTejun Heo  * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
1547f2d5a0eeSTejun Heo  * enters idle state or fetches works without dropping lock, it can
1548f2d5a0eeSTejun Heo  * guarantee the scheduling requirement described in the first paragraph.
1549e22bee78STejun Heo  *
1550e22bee78STejun Heo  * CONTEXT:
1551d565ed63STejun Heo  * Might sleep.  Called without any lock but returns with pool->lock
1552e22bee78STejun Heo  * held.
1553e22bee78STejun Heo  *
1554e22bee78STejun Heo  * RETURNS:
1555706026c2STejun Heo  * %true if the associated pool is online (@worker is successfully
1556e22bee78STejun Heo  * bound), %false if offline.
1557e22bee78STejun Heo  */
1558f36dc67bSLai Jiangshan static bool worker_maybe_bind_and_lock(struct worker_pool *pool)
1559d565ed63STejun Heo __acquires(&pool->lock)
1560e22bee78STejun Heo {
1561e22bee78STejun Heo 	while (true) {
1562e22bee78STejun Heo 		/*
1563e22bee78STejun Heo 		 * The following call may fail, succeed or succeed
1564e22bee78STejun Heo 		 * without actually migrating the task to the cpu if
1565e22bee78STejun Heo 		 * it races with cpu hotunplug operation.  Verify
156624647570STejun Heo 		 * against POOL_DISASSOCIATED.
1567e22bee78STejun Heo 		 */
156824647570STejun Heo 		if (!(pool->flags & POOL_DISASSOCIATED))
1569f5faa077SLai Jiangshan 			set_cpus_allowed_ptr(current, get_cpu_mask(pool->cpu));
1570e22bee78STejun Heo 
1571d565ed63STejun Heo 		spin_lock_irq(&pool->lock);
157224647570STejun Heo 		if (pool->flags & POOL_DISASSOCIATED)
1573e22bee78STejun Heo 			return false;
1574f5faa077SLai Jiangshan 		if (task_cpu(current) == pool->cpu &&
1575e22bee78STejun Heo 		    cpumask_equal(&current->cpus_allowed,
1576ec22ca5eSTejun Heo 				  get_cpu_mask(pool->cpu)))
1577e22bee78STejun Heo 			return true;
1578d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
1579e22bee78STejun Heo 
15805035b20fSTejun Heo 		/*
15815035b20fSTejun Heo 		 * We've raced with CPU hot[un]plug.  Give it a breather
15825035b20fSTejun Heo 		 * and retry migration.  cond_resched() is required here;
15835035b20fSTejun Heo 		 * otherwise, we might deadlock against cpu_stop trying to
15845035b20fSTejun Heo 		 * bring down the CPU on non-preemptive kernel.
15855035b20fSTejun Heo 		 */
1586e22bee78STejun Heo 		cpu_relax();
15875035b20fSTejun Heo 		cond_resched();
1588e22bee78STejun Heo 	}
1589e22bee78STejun Heo }
1590e22bee78STejun Heo 
1591e22bee78STejun Heo /*
1592ea1abd61SLai Jiangshan  * Rebind an idle @worker to its CPU.  worker_thread() will test
15935f7dabfdSLai Jiangshan  * list_empty(@worker->entry) before leaving idle and call this function.
159425511a47STejun Heo  */
159525511a47STejun Heo static void idle_worker_rebind(struct worker *worker)
159625511a47STejun Heo {
15975f7dabfdSLai Jiangshan 	/* CPU may go down again inbetween, clear UNBOUND only on success */
1598f36dc67bSLai Jiangshan 	if (worker_maybe_bind_and_lock(worker->pool))
15995f7dabfdSLai Jiangshan 		worker_clr_flags(worker, WORKER_UNBOUND);
160025511a47STejun Heo 
1601ea1abd61SLai Jiangshan 	/* rebind complete, become available again */
1602ea1abd61SLai Jiangshan 	list_add(&worker->entry, &worker->pool->idle_list);
1603d565ed63STejun Heo 	spin_unlock_irq(&worker->pool->lock);
160425511a47STejun Heo }
160525511a47STejun Heo 
160625511a47STejun Heo /*
160725511a47STejun Heo  * Function for @worker->rebind.work used to rebind unbound busy workers to
1608403c821dSTejun Heo  * the associated cpu which is coming back online.  This is scheduled by
1609403c821dSTejun Heo  * cpu up but can race with other cpu hotplug operations and may be
1610403c821dSTejun Heo  * executed twice without intervening cpu down.
1611e22bee78STejun Heo  */
161225511a47STejun Heo static void busy_worker_rebind_fn(struct work_struct *work)
1613e22bee78STejun Heo {
1614e22bee78STejun Heo 	struct worker *worker = container_of(work, struct worker, rebind_work);
1615e22bee78STejun Heo 
1616f36dc67bSLai Jiangshan 	if (worker_maybe_bind_and_lock(worker->pool))
1617eab6d828SLai Jiangshan 		worker_clr_flags(worker, WORKER_UNBOUND);
1618e22bee78STejun Heo 
1619d565ed63STejun Heo 	spin_unlock_irq(&worker->pool->lock);
1620e22bee78STejun Heo }
1621e22bee78STejun Heo 
162225511a47STejun Heo /**
162394cf58bbSTejun Heo  * rebind_workers - rebind all workers of a pool to the associated CPU
162494cf58bbSTejun Heo  * @pool: pool of interest
162525511a47STejun Heo  *
162694cf58bbSTejun Heo  * @pool->cpu is coming online.  Rebind all workers to the CPU.  Rebinding
162725511a47STejun Heo  * is different for idle and busy ones.
162825511a47STejun Heo  *
1629ea1abd61SLai Jiangshan  * Idle ones will be removed from the idle_list and woken up.  They will
1630ea1abd61SLai Jiangshan  * add themselves back after completing rebind.  This ensures that the
1631ea1abd61SLai Jiangshan  * idle_list doesn't contain any unbound workers when re-bound busy workers
1632ea1abd61SLai Jiangshan  * try to perform local wake-ups for concurrency management.
163325511a47STejun Heo  *
1634ea1abd61SLai Jiangshan  * Busy workers can rebind after they finish their current work items.
1635ea1abd61SLai Jiangshan  * Queueing the rebind work item at the head of the scheduled list is
1636ea1abd61SLai Jiangshan  * enough.  Note that nr_running will be properly bumped as busy workers
1637ea1abd61SLai Jiangshan  * rebind.
163825511a47STejun Heo  *
1639ea1abd61SLai Jiangshan  * On return, all non-manager workers are scheduled for rebind - see
1640ea1abd61SLai Jiangshan  * manage_workers() for the manager special case.  Any idle worker
1641ea1abd61SLai Jiangshan  * including the manager will not appear on @idle_list until rebind is
1642ea1abd61SLai Jiangshan  * complete, making local wake-ups safe.
164325511a47STejun Heo  */
164494cf58bbSTejun Heo static void rebind_workers(struct worker_pool *pool)
164525511a47STejun Heo {
1646ea1abd61SLai Jiangshan 	struct worker *worker, *n;
164725511a47STejun Heo 	int i;
164825511a47STejun Heo 
1649b2eb83d1SLai Jiangshan 	lockdep_assert_held(&pool->assoc_mutex);
1650d565ed63STejun Heo 	lockdep_assert_held(&pool->lock);
165125511a47STejun Heo 
16525f7dabfdSLai Jiangshan 	/* dequeue and kick idle ones */
1653ea1abd61SLai Jiangshan 	list_for_each_entry_safe(worker, n, &pool->idle_list, entry) {
1654ea1abd61SLai Jiangshan 		/*
165594cf58bbSTejun Heo 		 * idle workers should be off @pool->idle_list until rebind
165694cf58bbSTejun Heo 		 * is complete to avoid receiving premature local wake-ups.
1657ea1abd61SLai Jiangshan 		 */
1658ea1abd61SLai Jiangshan 		list_del_init(&worker->entry);
165925511a47STejun Heo 
166025511a47STejun Heo 		/*
166194cf58bbSTejun Heo 		 * worker_thread() will see the above dequeuing and call
166294cf58bbSTejun Heo 		 * idle_worker_rebind().
166325511a47STejun Heo 		 */
166425511a47STejun Heo 		wake_up_process(worker->task);
166525511a47STejun Heo 	}
166625511a47STejun Heo 
1667ea1abd61SLai Jiangshan 	/* rebind busy workers */
1668b67bfe0dSSasha Levin 	for_each_busy_worker(worker, i, pool) {
166925511a47STejun Heo 		struct work_struct *rebind_work = &worker->rebind_work;
1670e2b6a6d5SJoonsoo Kim 		struct workqueue_struct *wq;
167125511a47STejun Heo 
167225511a47STejun Heo 		if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
167325511a47STejun Heo 				     work_data_bits(rebind_work)))
167425511a47STejun Heo 			continue;
167525511a47STejun Heo 
167625511a47STejun Heo 		debug_work_activate(rebind_work);
167790beca5dSTejun Heo 
167890beca5dSTejun Heo 		/*
167994cf58bbSTejun Heo 		 * wq doesn't really matter but let's keep @worker->pool
1680112202d9STejun Heo 		 * and @pwq->pool consistent for sanity.
168190beca5dSTejun Heo 		 */
1682e34cdddbSTejun Heo 		if (std_worker_pool_pri(worker->pool))
1683e2b6a6d5SJoonsoo Kim 			wq = system_highpri_wq;
1684e2b6a6d5SJoonsoo Kim 		else
1685e2b6a6d5SJoonsoo Kim 			wq = system_wq;
1686ec58815aSTejun Heo 
16877fb98ea7STejun Heo 		insert_work(per_cpu_ptr(wq->cpu_pwqs, pool->cpu), rebind_work,
168825511a47STejun Heo 			    worker->scheduled.next,
168925511a47STejun Heo 			    work_color_to_flags(WORK_NO_COLOR));
1690ec58815aSTejun Heo 	}
169125511a47STejun Heo }
169225511a47STejun Heo 
1693c34056a3STejun Heo static struct worker *alloc_worker(void)
1694c34056a3STejun Heo {
1695c34056a3STejun Heo 	struct worker *worker;
1696c34056a3STejun Heo 
1697c34056a3STejun Heo 	worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1698c8e55f36STejun Heo 	if (worker) {
1699c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
1700affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
170125511a47STejun Heo 		INIT_WORK(&worker->rebind_work, busy_worker_rebind_fn);
1702e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
1703e22bee78STejun Heo 		worker->flags = WORKER_PREP;
1704c8e55f36STejun Heo 	}
1705c34056a3STejun Heo 	return worker;
1706c34056a3STejun Heo }
1707c34056a3STejun Heo 
1708c34056a3STejun Heo /**
1709c34056a3STejun Heo  * create_worker - create a new workqueue worker
171063d95a91STejun Heo  * @pool: pool the new worker will belong to
1711c34056a3STejun Heo  *
171263d95a91STejun Heo  * Create a new worker which is bound to @pool.  The returned worker
1713c34056a3STejun Heo  * can be started by calling start_worker() or destroyed using
1714c34056a3STejun Heo  * destroy_worker().
1715c34056a3STejun Heo  *
1716c34056a3STejun Heo  * CONTEXT:
1717c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
1718c34056a3STejun Heo  *
1719c34056a3STejun Heo  * RETURNS:
1720c34056a3STejun Heo  * Pointer to the newly created worker.
1721c34056a3STejun Heo  */
1722bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
1723c34056a3STejun Heo {
1724e34cdddbSTejun Heo 	const char *pri = std_worker_pool_pri(pool) ? "H" : "";
1725c34056a3STejun Heo 	struct worker *worker = NULL;
1726f3421797STejun Heo 	int id = -1;
1727c34056a3STejun Heo 
1728d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
1729bd7bdd43STejun Heo 	while (ida_get_new(&pool->worker_ida, &id)) {
1730d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
1731bd7bdd43STejun Heo 		if (!ida_pre_get(&pool->worker_ida, GFP_KERNEL))
1732c34056a3STejun Heo 			goto fail;
1733d565ed63STejun Heo 		spin_lock_irq(&pool->lock);
1734c34056a3STejun Heo 	}
1735d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
1736c34056a3STejun Heo 
1737c34056a3STejun Heo 	worker = alloc_worker();
1738c34056a3STejun Heo 	if (!worker)
1739c34056a3STejun Heo 		goto fail;
1740c34056a3STejun Heo 
1741bd7bdd43STejun Heo 	worker->pool = pool;
1742c34056a3STejun Heo 	worker->id = id;
1743c34056a3STejun Heo 
1744ec22ca5eSTejun Heo 	if (pool->cpu != WORK_CPU_UNBOUND)
174594dcf29aSEric Dumazet 		worker->task = kthread_create_on_node(worker_thread,
1746ec22ca5eSTejun Heo 					worker, cpu_to_node(pool->cpu),
1747d84ff051STejun Heo 					"kworker/%d:%d%s", pool->cpu, id, pri);
1748f3421797STejun Heo 	else
1749f3421797STejun Heo 		worker->task = kthread_create(worker_thread, worker,
17503270476aSTejun Heo 					      "kworker/u:%d%s", id, pri);
1751c34056a3STejun Heo 	if (IS_ERR(worker->task))
1752c34056a3STejun Heo 		goto fail;
1753c34056a3STejun Heo 
1754e34cdddbSTejun Heo 	if (std_worker_pool_pri(pool))
17553270476aSTejun Heo 		set_user_nice(worker->task, HIGHPRI_NICE_LEVEL);
17563270476aSTejun Heo 
1757db7bccf4STejun Heo 	/*
1758bc2ae0f5STejun Heo 	 * Determine CPU binding of the new worker depending on
175924647570STejun Heo 	 * %POOL_DISASSOCIATED.  The caller is responsible for ensuring the
1760bc2ae0f5STejun Heo 	 * flag remains stable across this function.  See the comments
1761bc2ae0f5STejun Heo 	 * above the flag definition for details.
1762bc2ae0f5STejun Heo 	 *
1763bc2ae0f5STejun Heo 	 * As an unbound worker may later become a regular one if CPU comes
1764bc2ae0f5STejun Heo 	 * online, make sure every worker has %PF_THREAD_BOUND set.
1765db7bccf4STejun Heo 	 */
176624647570STejun Heo 	if (!(pool->flags & POOL_DISASSOCIATED)) {
1767ec22ca5eSTejun Heo 		kthread_bind(worker->task, pool->cpu);
1768bc2ae0f5STejun Heo 	} else {
1769db7bccf4STejun Heo 		worker->task->flags |= PF_THREAD_BOUND;
1770f3421797STejun Heo 		worker->flags |= WORKER_UNBOUND;
1771f3421797STejun Heo 	}
1772c34056a3STejun Heo 
1773c34056a3STejun Heo 	return worker;
1774c34056a3STejun Heo fail:
1775c34056a3STejun Heo 	if (id >= 0) {
1776d565ed63STejun Heo 		spin_lock_irq(&pool->lock);
1777bd7bdd43STejun Heo 		ida_remove(&pool->worker_ida, id);
1778d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
1779c34056a3STejun Heo 	}
1780c34056a3STejun Heo 	kfree(worker);
1781c34056a3STejun Heo 	return NULL;
1782c34056a3STejun Heo }
1783c34056a3STejun Heo 
1784c34056a3STejun Heo /**
1785c34056a3STejun Heo  * start_worker - start a newly created worker
1786c34056a3STejun Heo  * @worker: worker to start
1787c34056a3STejun Heo  *
1788706026c2STejun Heo  * Make the pool aware of @worker and start it.
1789c34056a3STejun Heo  *
1790c34056a3STejun Heo  * CONTEXT:
1791d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1792c34056a3STejun Heo  */
1793c34056a3STejun Heo static void start_worker(struct worker *worker)
1794c34056a3STejun Heo {
1795cb444766STejun Heo 	worker->flags |= WORKER_STARTED;
1796bd7bdd43STejun Heo 	worker->pool->nr_workers++;
1797c8e55f36STejun Heo 	worker_enter_idle(worker);
1798c34056a3STejun Heo 	wake_up_process(worker->task);
1799c34056a3STejun Heo }
1800c34056a3STejun Heo 
1801c34056a3STejun Heo /**
1802c34056a3STejun Heo  * destroy_worker - destroy a workqueue worker
1803c34056a3STejun Heo  * @worker: worker to be destroyed
1804c34056a3STejun Heo  *
1805706026c2STejun Heo  * Destroy @worker and adjust @pool stats accordingly.
1806c8e55f36STejun Heo  *
1807c8e55f36STejun Heo  * CONTEXT:
1808d565ed63STejun Heo  * spin_lock_irq(pool->lock) which is released and regrabbed.
1809c34056a3STejun Heo  */
1810c34056a3STejun Heo static void destroy_worker(struct worker *worker)
1811c34056a3STejun Heo {
1812bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1813c34056a3STejun Heo 	int id = worker->id;
1814c34056a3STejun Heo 
1815c34056a3STejun Heo 	/* sanity check frenzy */
18166183c009STejun Heo 	if (WARN_ON(worker->current_work) ||
18176183c009STejun Heo 	    WARN_ON(!list_empty(&worker->scheduled)))
18186183c009STejun Heo 		return;
1819c34056a3STejun Heo 
1820c8e55f36STejun Heo 	if (worker->flags & WORKER_STARTED)
1821bd7bdd43STejun Heo 		pool->nr_workers--;
1822c8e55f36STejun Heo 	if (worker->flags & WORKER_IDLE)
1823bd7bdd43STejun Heo 		pool->nr_idle--;
1824c8e55f36STejun Heo 
1825c8e55f36STejun Heo 	list_del_init(&worker->entry);
1826cb444766STejun Heo 	worker->flags |= WORKER_DIE;
1827c8e55f36STejun Heo 
1828d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
1829c8e55f36STejun Heo 
1830c34056a3STejun Heo 	kthread_stop(worker->task);
1831c34056a3STejun Heo 	kfree(worker);
1832c34056a3STejun Heo 
1833d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
1834bd7bdd43STejun Heo 	ida_remove(&pool->worker_ida, id);
1835c34056a3STejun Heo }
1836c34056a3STejun Heo 
183763d95a91STejun Heo static void idle_worker_timeout(unsigned long __pool)
1838e22bee78STejun Heo {
183963d95a91STejun Heo 	struct worker_pool *pool = (void *)__pool;
1840e22bee78STejun Heo 
1841d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
1842e22bee78STejun Heo 
184363d95a91STejun Heo 	if (too_many_workers(pool)) {
1844e22bee78STejun Heo 		struct worker *worker;
1845e22bee78STejun Heo 		unsigned long expires;
1846e22bee78STejun Heo 
1847e22bee78STejun Heo 		/* idle_list is kept in LIFO order, check the last one */
184863d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
1849e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1850e22bee78STejun Heo 
1851e22bee78STejun Heo 		if (time_before(jiffies, expires))
185263d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
1853e22bee78STejun Heo 		else {
1854e22bee78STejun Heo 			/* it's been idle for too long, wake up manager */
185511ebea50STejun Heo 			pool->flags |= POOL_MANAGE_WORKERS;
185663d95a91STejun Heo 			wake_up_worker(pool);
1857e22bee78STejun Heo 		}
1858e22bee78STejun Heo 	}
1859e22bee78STejun Heo 
1860d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
1861e22bee78STejun Heo }
1862e22bee78STejun Heo 
1863493a1724STejun Heo static void send_mayday(struct work_struct *work)
1864e22bee78STejun Heo {
1865112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1866112202d9STejun Heo 	struct workqueue_struct *wq = pwq->wq;
1867493a1724STejun Heo 
1868493a1724STejun Heo 	lockdep_assert_held(&workqueue_lock);
1869e22bee78STejun Heo 
1870e22bee78STejun Heo 	if (!(wq->flags & WQ_RESCUER))
1871493a1724STejun Heo 		return;
1872e22bee78STejun Heo 
1873e22bee78STejun Heo 	/* mayday mayday mayday */
1874493a1724STejun Heo 	if (list_empty(&pwq->mayday_node)) {
1875493a1724STejun Heo 		list_add_tail(&pwq->mayday_node, &wq->maydays);
1876e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
1877493a1724STejun Heo 	}
1878e22bee78STejun Heo }
1879e22bee78STejun Heo 
1880706026c2STejun Heo static void pool_mayday_timeout(unsigned long __pool)
1881e22bee78STejun Heo {
188263d95a91STejun Heo 	struct worker_pool *pool = (void *)__pool;
1883e22bee78STejun Heo 	struct work_struct *work;
1884e22bee78STejun Heo 
1885493a1724STejun Heo 	spin_lock_irq(&workqueue_lock);		/* for wq->maydays */
1886493a1724STejun Heo 	spin_lock(&pool->lock);
1887e22bee78STejun Heo 
188863d95a91STejun Heo 	if (need_to_create_worker(pool)) {
1889e22bee78STejun Heo 		/*
1890e22bee78STejun Heo 		 * We've been trying to create a new worker but
1891e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
1892e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
1893e22bee78STejun Heo 		 * rescuers.
1894e22bee78STejun Heo 		 */
189563d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
1896e22bee78STejun Heo 			send_mayday(work);
1897e22bee78STejun Heo 	}
1898e22bee78STejun Heo 
1899493a1724STejun Heo 	spin_unlock(&pool->lock);
1900493a1724STejun Heo 	spin_unlock_irq(&workqueue_lock);
1901e22bee78STejun Heo 
190263d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1903e22bee78STejun Heo }
1904e22bee78STejun Heo 
1905e22bee78STejun Heo /**
1906e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
190763d95a91STejun Heo  * @pool: pool to create a new worker for
1908e22bee78STejun Heo  *
190963d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
1910e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
1911e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
191263d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
1913e22bee78STejun Heo  * possible allocation deadlock.
1914e22bee78STejun Heo  *
1915e22bee78STejun Heo  * On return, need_to_create_worker() is guaranteed to be false and
1916e22bee78STejun Heo  * may_start_working() true.
1917e22bee78STejun Heo  *
1918e22bee78STejun Heo  * LOCKING:
1919d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
1920e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
1921e22bee78STejun Heo  * manager.
1922e22bee78STejun Heo  *
1923e22bee78STejun Heo  * RETURNS:
1924d565ed63STejun Heo  * false if no action was taken and pool->lock stayed locked, true
1925e22bee78STejun Heo  * otherwise.
1926e22bee78STejun Heo  */
192763d95a91STejun Heo static bool maybe_create_worker(struct worker_pool *pool)
1928d565ed63STejun Heo __releases(&pool->lock)
1929d565ed63STejun Heo __acquires(&pool->lock)
1930e22bee78STejun Heo {
193163d95a91STejun Heo 	if (!need_to_create_worker(pool))
1932e22bee78STejun Heo 		return false;
1933e22bee78STejun Heo restart:
1934d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
19359f9c2364STejun Heo 
1936e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
193763d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1938e22bee78STejun Heo 
1939e22bee78STejun Heo 	while (true) {
1940e22bee78STejun Heo 		struct worker *worker;
1941e22bee78STejun Heo 
1942bc2ae0f5STejun Heo 		worker = create_worker(pool);
1943e22bee78STejun Heo 		if (worker) {
194463d95a91STejun Heo 			del_timer_sync(&pool->mayday_timer);
1945d565ed63STejun Heo 			spin_lock_irq(&pool->lock);
1946e22bee78STejun Heo 			start_worker(worker);
19476183c009STejun Heo 			if (WARN_ON_ONCE(need_to_create_worker(pool)))
19486183c009STejun Heo 				goto restart;
1949e22bee78STejun Heo 			return true;
1950e22bee78STejun Heo 		}
1951e22bee78STejun Heo 
195263d95a91STejun Heo 		if (!need_to_create_worker(pool))
1953e22bee78STejun Heo 			break;
1954e22bee78STejun Heo 
1955e22bee78STejun Heo 		__set_current_state(TASK_INTERRUPTIBLE);
1956e22bee78STejun Heo 		schedule_timeout(CREATE_COOLDOWN);
19579f9c2364STejun Heo 
195863d95a91STejun Heo 		if (!need_to_create_worker(pool))
1959e22bee78STejun Heo 			break;
1960e22bee78STejun Heo 	}
1961e22bee78STejun Heo 
196263d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
1963d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
196463d95a91STejun Heo 	if (need_to_create_worker(pool))
1965e22bee78STejun Heo 		goto restart;
1966e22bee78STejun Heo 	return true;
1967e22bee78STejun Heo }
1968e22bee78STejun Heo 
1969e22bee78STejun Heo /**
1970e22bee78STejun Heo  * maybe_destroy_worker - destroy workers which have been idle for a while
197163d95a91STejun Heo  * @pool: pool to destroy workers for
1972e22bee78STejun Heo  *
197363d95a91STejun Heo  * Destroy @pool workers which have been idle for longer than
1974e22bee78STejun Heo  * IDLE_WORKER_TIMEOUT.
1975e22bee78STejun Heo  *
1976e22bee78STejun Heo  * LOCKING:
1977d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
1978e22bee78STejun Heo  * multiple times.  Called only from manager.
1979e22bee78STejun Heo  *
1980e22bee78STejun Heo  * RETURNS:
1981d565ed63STejun Heo  * false if no action was taken and pool->lock stayed locked, true
1982e22bee78STejun Heo  * otherwise.
1983e22bee78STejun Heo  */
198463d95a91STejun Heo static bool maybe_destroy_workers(struct worker_pool *pool)
1985e22bee78STejun Heo {
1986e22bee78STejun Heo 	bool ret = false;
1987e22bee78STejun Heo 
198863d95a91STejun Heo 	while (too_many_workers(pool)) {
1989e22bee78STejun Heo 		struct worker *worker;
1990e22bee78STejun Heo 		unsigned long expires;
1991e22bee78STejun Heo 
199263d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
1993e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1994e22bee78STejun Heo 
1995e22bee78STejun Heo 		if (time_before(jiffies, expires)) {
199663d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
1997e22bee78STejun Heo 			break;
1998e22bee78STejun Heo 		}
1999e22bee78STejun Heo 
2000e22bee78STejun Heo 		destroy_worker(worker);
2001e22bee78STejun Heo 		ret = true;
2002e22bee78STejun Heo 	}
2003e22bee78STejun Heo 
2004e22bee78STejun Heo 	return ret;
2005e22bee78STejun Heo }
2006e22bee78STejun Heo 
2007e22bee78STejun Heo /**
2008e22bee78STejun Heo  * manage_workers - manage worker pool
2009e22bee78STejun Heo  * @worker: self
2010e22bee78STejun Heo  *
2011706026c2STejun Heo  * Assume the manager role and manage the worker pool @worker belongs
2012e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
2013706026c2STejun Heo  * pool.  The exclusion is handled automatically by this function.
2014e22bee78STejun Heo  *
2015e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
2016e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
2017e22bee78STejun Heo  * and may_start_working() is true.
2018e22bee78STejun Heo  *
2019e22bee78STejun Heo  * CONTEXT:
2020d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
2021e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
2022e22bee78STejun Heo  *
2023e22bee78STejun Heo  * RETURNS:
2024d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
2025d565ed63STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
2026e22bee78STejun Heo  */
2027e22bee78STejun Heo static bool manage_workers(struct worker *worker)
2028e22bee78STejun Heo {
202963d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
2030e22bee78STejun Heo 	bool ret = false;
2031e22bee78STejun Heo 
2032ee378aa4SLai Jiangshan 	if (pool->flags & POOL_MANAGING_WORKERS)
2033e22bee78STejun Heo 		return ret;
2034e22bee78STejun Heo 
2035552a37e9SLai Jiangshan 	pool->flags |= POOL_MANAGING_WORKERS;
2036ee378aa4SLai Jiangshan 
2037ee378aa4SLai Jiangshan 	/*
2038ee378aa4SLai Jiangshan 	 * To simplify both worker management and CPU hotplug, hold off
2039ee378aa4SLai Jiangshan 	 * management while hotplug is in progress.  CPU hotplug path can't
2040ee378aa4SLai Jiangshan 	 * grab %POOL_MANAGING_WORKERS to achieve this because that can
2041ee378aa4SLai Jiangshan 	 * lead to idle worker depletion (all become busy thinking someone
2042ee378aa4SLai Jiangshan 	 * else is managing) which in turn can result in deadlock under
2043b2eb83d1SLai Jiangshan 	 * extreme circumstances.  Use @pool->assoc_mutex to synchronize
2044ee378aa4SLai Jiangshan 	 * manager against CPU hotplug.
2045ee378aa4SLai Jiangshan 	 *
2046b2eb83d1SLai Jiangshan 	 * assoc_mutex would always be free unless CPU hotplug is in
2047d565ed63STejun Heo 	 * progress.  trylock first without dropping @pool->lock.
2048ee378aa4SLai Jiangshan 	 */
2049b2eb83d1SLai Jiangshan 	if (unlikely(!mutex_trylock(&pool->assoc_mutex))) {
2050d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
2051b2eb83d1SLai Jiangshan 		mutex_lock(&pool->assoc_mutex);
2052ee378aa4SLai Jiangshan 		/*
2053ee378aa4SLai Jiangshan 		 * CPU hotplug could have happened while we were waiting
2054b2eb83d1SLai Jiangshan 		 * for assoc_mutex.  Hotplug itself can't handle us
2055ee378aa4SLai Jiangshan 		 * because manager isn't either on idle or busy list, and
2056706026c2STejun Heo 		 * @pool's state and ours could have deviated.
2057ee378aa4SLai Jiangshan 		 *
2058b2eb83d1SLai Jiangshan 		 * As hotplug is now excluded via assoc_mutex, we can
2059ee378aa4SLai Jiangshan 		 * simply try to bind.  It will succeed or fail depending
2060706026c2STejun Heo 		 * on @pool's current state.  Try it and adjust
2061ee378aa4SLai Jiangshan 		 * %WORKER_UNBOUND accordingly.
2062ee378aa4SLai Jiangshan 		 */
2063f36dc67bSLai Jiangshan 		if (worker_maybe_bind_and_lock(pool))
2064ee378aa4SLai Jiangshan 			worker->flags &= ~WORKER_UNBOUND;
2065ee378aa4SLai Jiangshan 		else
2066ee378aa4SLai Jiangshan 			worker->flags |= WORKER_UNBOUND;
2067ee378aa4SLai Jiangshan 
2068ee378aa4SLai Jiangshan 		ret = true;
2069ee378aa4SLai Jiangshan 	}
2070ee378aa4SLai Jiangshan 
207111ebea50STejun Heo 	pool->flags &= ~POOL_MANAGE_WORKERS;
2072e22bee78STejun Heo 
2073e22bee78STejun Heo 	/*
2074e22bee78STejun Heo 	 * Destroy and then create so that may_start_working() is true
2075e22bee78STejun Heo 	 * on return.
2076e22bee78STejun Heo 	 */
207763d95a91STejun Heo 	ret |= maybe_destroy_workers(pool);
207863d95a91STejun Heo 	ret |= maybe_create_worker(pool);
2079e22bee78STejun Heo 
2080552a37e9SLai Jiangshan 	pool->flags &= ~POOL_MANAGING_WORKERS;
2081b2eb83d1SLai Jiangshan 	mutex_unlock(&pool->assoc_mutex);
2082e22bee78STejun Heo 	return ret;
2083e22bee78STejun Heo }
2084e22bee78STejun Heo 
2085a62428c0STejun Heo /**
2086a62428c0STejun Heo  * process_one_work - process single work
2087c34056a3STejun Heo  * @worker: self
2088a62428c0STejun Heo  * @work: work to process
2089a62428c0STejun Heo  *
2090a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
2091a62428c0STejun Heo  * process a single work including synchronization against and
2092a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
2093a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
2094a62428c0STejun Heo  * call this function to process a work.
2095a62428c0STejun Heo  *
2096a62428c0STejun Heo  * CONTEXT:
2097d565ed63STejun Heo  * spin_lock_irq(pool->lock) which is released and regrabbed.
2098a62428c0STejun Heo  */
2099c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
2100d565ed63STejun Heo __releases(&pool->lock)
2101d565ed63STejun Heo __acquires(&pool->lock)
21021da177e4SLinus Torvalds {
2103112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2104bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2105112202d9STejun Heo 	bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
210673f53c4aSTejun Heo 	int work_color;
21077e11629dSTejun Heo 	struct worker *collision;
21084e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
21094e6045f1SJohannes Berg 	/*
2110a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
2111a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
2112a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
2113a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
2114a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
21154e6045f1SJohannes Berg 	 */
21164d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
21174d82a1deSPeter Zijlstra 
21184d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
21194e6045f1SJohannes Berg #endif
21206fec10a1STejun Heo 	/*
21216fec10a1STejun Heo 	 * Ensure we're on the correct CPU.  DISASSOCIATED test is
21226fec10a1STejun Heo 	 * necessary to avoid spurious warnings from rescuers servicing the
212324647570STejun Heo 	 * unbound or a disassociated pool.
21246fec10a1STejun Heo 	 */
21255f7dabfdSLai Jiangshan 	WARN_ON_ONCE(!(worker->flags & WORKER_UNBOUND) &&
212624647570STejun Heo 		     !(pool->flags & POOL_DISASSOCIATED) &&
2127ec22ca5eSTejun Heo 		     raw_smp_processor_id() != pool->cpu);
212825511a47STejun Heo 
21297e11629dSTejun Heo 	/*
21307e11629dSTejun Heo 	 * A single work shouldn't be executed concurrently by
21317e11629dSTejun Heo 	 * multiple workers on a single cpu.  Check whether anyone is
21327e11629dSTejun Heo 	 * already processing the work.  If so, defer the work to the
21337e11629dSTejun Heo 	 * currently executing one.
21347e11629dSTejun Heo 	 */
2135c9e7cf27STejun Heo 	collision = find_worker_executing_work(pool, work);
21367e11629dSTejun Heo 	if (unlikely(collision)) {
21377e11629dSTejun Heo 		move_linked_works(work, &collision->scheduled, NULL);
21387e11629dSTejun Heo 		return;
21397e11629dSTejun Heo 	}
21401da177e4SLinus Torvalds 
21418930cabaSTejun Heo 	/* claim and dequeue */
21421da177e4SLinus Torvalds 	debug_work_deactivate(work);
2143c9e7cf27STejun Heo 	hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2144c34056a3STejun Heo 	worker->current_work = work;
2145a2c1c57bSTejun Heo 	worker->current_func = work->func;
2146112202d9STejun Heo 	worker->current_pwq = pwq;
214773f53c4aSTejun Heo 	work_color = get_work_color(work);
21487a22ad75STejun Heo 
2149a62428c0STejun Heo 	list_del_init(&work->entry);
2150a62428c0STejun Heo 
2151649027d7STejun Heo 	/*
2152fb0e7bebSTejun Heo 	 * CPU intensive works don't participate in concurrency
2153fb0e7bebSTejun Heo 	 * management.  They're the scheduler's responsibility.
2154fb0e7bebSTejun Heo 	 */
2155fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2156fb0e7bebSTejun Heo 		worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
2157fb0e7bebSTejun Heo 
2158974271c4STejun Heo 	/*
2159d565ed63STejun Heo 	 * Unbound pool isn't concurrency managed and work items should be
2160974271c4STejun Heo 	 * executed ASAP.  Wake up another worker if necessary.
2161974271c4STejun Heo 	 */
216263d95a91STejun Heo 	if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
216363d95a91STejun Heo 		wake_up_worker(pool);
2164974271c4STejun Heo 
21658930cabaSTejun Heo 	/*
21667c3eed5cSTejun Heo 	 * Record the last pool and clear PENDING which should be the last
2167d565ed63STejun Heo 	 * update to @work.  Also, do this inside @pool->lock so that
216823657bb1STejun Heo 	 * PENDING and queued state changes happen together while IRQ is
216923657bb1STejun Heo 	 * disabled.
21708930cabaSTejun Heo 	 */
21717c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(work, pool->id);
21721da177e4SLinus Torvalds 
2173d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2174365970a1SDavid Howells 
2175112202d9STejun Heo 	lock_map_acquire_read(&pwq->wq->lockdep_map);
21763295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
2177e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
2178a2c1c57bSTejun Heo 	worker->current_func(work);
2179e36c886aSArjan van de Ven 	/*
2180e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
2181e36c886aSArjan van de Ven 	 * point will only record its address.
2182e36c886aSArjan van de Ven 	 */
2183e36c886aSArjan van de Ven 	trace_workqueue_execute_end(work);
21843295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
2185112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
21861da177e4SLinus Torvalds 
2187d5abe669SPeter Zijlstra 	if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2188044c782cSValentin Ilie 		pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2189044c782cSValentin Ilie 		       "     last function: %pf\n",
2190a2c1c57bSTejun Heo 		       current->comm, preempt_count(), task_pid_nr(current),
2191a2c1c57bSTejun Heo 		       worker->current_func);
2192d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
2193d5abe669SPeter Zijlstra 		dump_stack();
2194d5abe669SPeter Zijlstra 	}
2195d5abe669SPeter Zijlstra 
2196d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
2197a62428c0STejun Heo 
2198fb0e7bebSTejun Heo 	/* clear cpu intensive status */
2199fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2200fb0e7bebSTejun Heo 		worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2201fb0e7bebSTejun Heo 
2202a62428c0STejun Heo 	/* we're done with it, release */
220342f8570fSSasha Levin 	hash_del(&worker->hentry);
2204c34056a3STejun Heo 	worker->current_work = NULL;
2205a2c1c57bSTejun Heo 	worker->current_func = NULL;
2206112202d9STejun Heo 	worker->current_pwq = NULL;
2207112202d9STejun Heo 	pwq_dec_nr_in_flight(pwq, work_color);
22081da177e4SLinus Torvalds }
22091da177e4SLinus Torvalds 
2210affee4b2STejun Heo /**
2211affee4b2STejun Heo  * process_scheduled_works - process scheduled works
2212affee4b2STejun Heo  * @worker: self
2213affee4b2STejun Heo  *
2214affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
2215affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
2216affee4b2STejun Heo  * fetches a work from the top and executes it.
2217affee4b2STejun Heo  *
2218affee4b2STejun Heo  * CONTEXT:
2219d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
2220affee4b2STejun Heo  * multiple times.
2221affee4b2STejun Heo  */
2222affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
22231da177e4SLinus Torvalds {
2224affee4b2STejun Heo 	while (!list_empty(&worker->scheduled)) {
2225affee4b2STejun Heo 		struct work_struct *work = list_first_entry(&worker->scheduled,
2226a62428c0STejun Heo 						struct work_struct, entry);
2227c34056a3STejun Heo 		process_one_work(worker, work);
2228a62428c0STejun Heo 	}
22291da177e4SLinus Torvalds }
22301da177e4SLinus Torvalds 
22314690c4abSTejun Heo /**
22324690c4abSTejun Heo  * worker_thread - the worker thread function
2233c34056a3STejun Heo  * @__worker: self
22344690c4abSTejun Heo  *
2235706026c2STejun Heo  * The worker thread function.  There are NR_CPU_WORKER_POOLS dynamic pools
2236706026c2STejun Heo  * of these per each cpu.  These workers process all works regardless of
2237e22bee78STejun Heo  * their specific target workqueue.  The only exception is works which
2238e22bee78STejun Heo  * belong to workqueues with a rescuer which will be explained in
2239e22bee78STejun Heo  * rescuer_thread().
22404690c4abSTejun Heo  */
2241c34056a3STejun Heo static int worker_thread(void *__worker)
22421da177e4SLinus Torvalds {
2243c34056a3STejun Heo 	struct worker *worker = __worker;
2244bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
22451da177e4SLinus Torvalds 
2246e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
2247e22bee78STejun Heo 	worker->task->flags |= PF_WQ_WORKER;
2248c8e55f36STejun Heo woke_up:
2249d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
2250affee4b2STejun Heo 
22515f7dabfdSLai Jiangshan 	/* we are off idle list if destruction or rebind is requested */
22525f7dabfdSLai Jiangshan 	if (unlikely(list_empty(&worker->entry))) {
2253d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
225425511a47STejun Heo 
22555f7dabfdSLai Jiangshan 		/* if DIE is set, destruction is requested */
225625511a47STejun Heo 		if (worker->flags & WORKER_DIE) {
2257e22bee78STejun Heo 			worker->task->flags &= ~PF_WQ_WORKER;
2258c8e55f36STejun Heo 			return 0;
2259c8e55f36STejun Heo 		}
2260c8e55f36STejun Heo 
22615f7dabfdSLai Jiangshan 		/* otherwise, rebind */
226225511a47STejun Heo 		idle_worker_rebind(worker);
226325511a47STejun Heo 		goto woke_up;
226425511a47STejun Heo 	}
226525511a47STejun Heo 
2266c8e55f36STejun Heo 	worker_leave_idle(worker);
2267db7bccf4STejun Heo recheck:
2268e22bee78STejun Heo 	/* no more worker necessary? */
226963d95a91STejun Heo 	if (!need_more_worker(pool))
2270e22bee78STejun Heo 		goto sleep;
2271e22bee78STejun Heo 
2272e22bee78STejun Heo 	/* do we need to manage? */
227363d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2274e22bee78STejun Heo 		goto recheck;
2275e22bee78STejun Heo 
2276c8e55f36STejun Heo 	/*
2277c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
2278c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
2279c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
2280c8e55f36STejun Heo 	 */
22816183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
2282c8e55f36STejun Heo 
2283e22bee78STejun Heo 	/*
2284e22bee78STejun Heo 	 * When control reaches this point, we're guaranteed to have
2285e22bee78STejun Heo 	 * at least one idle worker or that someone else has already
2286e22bee78STejun Heo 	 * assumed the manager role.
2287e22bee78STejun Heo 	 */
2288e22bee78STejun Heo 	worker_clr_flags(worker, WORKER_PREP);
2289e22bee78STejun Heo 
2290e22bee78STejun Heo 	do {
2291affee4b2STejun Heo 		struct work_struct *work =
2292bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
2293affee4b2STejun Heo 					 struct work_struct, entry);
2294affee4b2STejun Heo 
2295c8e55f36STejun Heo 		if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2296affee4b2STejun Heo 			/* optimization path, not strictly necessary */
2297affee4b2STejun Heo 			process_one_work(worker, work);
2298affee4b2STejun Heo 			if (unlikely(!list_empty(&worker->scheduled)))
2299affee4b2STejun Heo 				process_scheduled_works(worker);
2300affee4b2STejun Heo 		} else {
2301c8e55f36STejun Heo 			move_linked_works(work, &worker->scheduled, NULL);
2302affee4b2STejun Heo 			process_scheduled_works(worker);
2303affee4b2STejun Heo 		}
230463d95a91STejun Heo 	} while (keep_working(pool));
2305affee4b2STejun Heo 
2306e22bee78STejun Heo 	worker_set_flags(worker, WORKER_PREP, false);
2307d313dd85STejun Heo sleep:
230863d95a91STejun Heo 	if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
2309e22bee78STejun Heo 		goto recheck;
2310d313dd85STejun Heo 
2311c8e55f36STejun Heo 	/*
2312d565ed63STejun Heo 	 * pool->lock is held and there's no work to process and no need to
2313d565ed63STejun Heo 	 * manage, sleep.  Workers are woken up only while holding
2314d565ed63STejun Heo 	 * pool->lock or from local cpu, so setting the current state
2315d565ed63STejun Heo 	 * before releasing pool->lock is enough to prevent losing any
2316d565ed63STejun Heo 	 * event.
2317c8e55f36STejun Heo 	 */
2318c8e55f36STejun Heo 	worker_enter_idle(worker);
2319c8e55f36STejun Heo 	__set_current_state(TASK_INTERRUPTIBLE);
2320d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
23211da177e4SLinus Torvalds 	schedule();
2322c8e55f36STejun Heo 	goto woke_up;
23231da177e4SLinus Torvalds }
23241da177e4SLinus Torvalds 
2325e22bee78STejun Heo /**
2326e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
2327111c225aSTejun Heo  * @__rescuer: self
2328e22bee78STejun Heo  *
2329e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
2330e22bee78STejun Heo  * workqueue which has WQ_RESCUER set.
2331e22bee78STejun Heo  *
2332706026c2STejun Heo  * Regular work processing on a pool may block trying to create a new
2333e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
2334e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
2335e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2336e22bee78STejun Heo  * the problem rescuer solves.
2337e22bee78STejun Heo  *
2338706026c2STejun Heo  * When such condition is possible, the pool summons rescuers of all
2339706026c2STejun Heo  * workqueues which have works queued on the pool and let them process
2340e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
2341e22bee78STejun Heo  *
2342e22bee78STejun Heo  * This should happen rarely.
2343e22bee78STejun Heo  */
2344111c225aSTejun Heo static int rescuer_thread(void *__rescuer)
2345e22bee78STejun Heo {
2346111c225aSTejun Heo 	struct worker *rescuer = __rescuer;
2347111c225aSTejun Heo 	struct workqueue_struct *wq = rescuer->rescue_wq;
2348e22bee78STejun Heo 	struct list_head *scheduled = &rescuer->scheduled;
2349e22bee78STejun Heo 
2350e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
2351111c225aSTejun Heo 
2352111c225aSTejun Heo 	/*
2353111c225aSTejun Heo 	 * Mark rescuer as worker too.  As WORKER_PREP is never cleared, it
2354111c225aSTejun Heo 	 * doesn't participate in concurrency management.
2355111c225aSTejun Heo 	 */
2356111c225aSTejun Heo 	rescuer->task->flags |= PF_WQ_WORKER;
2357e22bee78STejun Heo repeat:
2358e22bee78STejun Heo 	set_current_state(TASK_INTERRUPTIBLE);
23591da177e4SLinus Torvalds 
2360412d32e6SMike Galbraith 	if (kthread_should_stop()) {
2361412d32e6SMike Galbraith 		__set_current_state(TASK_RUNNING);
2362111c225aSTejun Heo 		rescuer->task->flags &= ~PF_WQ_WORKER;
2363e22bee78STejun Heo 		return 0;
2364412d32e6SMike Galbraith 	}
23651da177e4SLinus Torvalds 
2366493a1724STejun Heo 	/* see whether any pwq is asking for help */
2367493a1724STejun Heo 	spin_lock_irq(&workqueue_lock);
2368493a1724STejun Heo 
2369493a1724STejun Heo 	while (!list_empty(&wq->maydays)) {
2370493a1724STejun Heo 		struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2371493a1724STejun Heo 					struct pool_workqueue, mayday_node);
2372112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
2373e22bee78STejun Heo 		struct work_struct *work, *n;
2374e22bee78STejun Heo 
2375e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
2376493a1724STejun Heo 		list_del_init(&pwq->mayday_node);
2377493a1724STejun Heo 
2378493a1724STejun Heo 		spin_unlock_irq(&workqueue_lock);
2379e22bee78STejun Heo 
2380e22bee78STejun Heo 		/* migrate to the target cpu if possible */
2381f36dc67bSLai Jiangshan 		worker_maybe_bind_and_lock(pool);
2382b3104104SLai Jiangshan 		rescuer->pool = pool;
2383e22bee78STejun Heo 
2384e22bee78STejun Heo 		/*
2385e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
2386e22bee78STejun Heo 		 * process'em.
2387e22bee78STejun Heo 		 */
23886183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&rescuer->scheduled));
2389bd7bdd43STejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry)
2390112202d9STejun Heo 			if (get_work_pwq(work) == pwq)
2391e22bee78STejun Heo 				move_linked_works(work, scheduled, &n);
2392e22bee78STejun Heo 
2393e22bee78STejun Heo 		process_scheduled_works(rescuer);
23947576958aSTejun Heo 
23957576958aSTejun Heo 		/*
2396d565ed63STejun Heo 		 * Leave this pool.  If keep_working() is %true, notify a
23977576958aSTejun Heo 		 * regular worker; otherwise, we end up with 0 concurrency
23987576958aSTejun Heo 		 * and stalling the execution.
23997576958aSTejun Heo 		 */
240063d95a91STejun Heo 		if (keep_working(pool))
240163d95a91STejun Heo 			wake_up_worker(pool);
24027576958aSTejun Heo 
2403b3104104SLai Jiangshan 		rescuer->pool = NULL;
2404493a1724STejun Heo 		spin_unlock(&pool->lock);
2405493a1724STejun Heo 		spin_lock(&workqueue_lock);
24061da177e4SLinus Torvalds 	}
24071da177e4SLinus Torvalds 
2408493a1724STejun Heo 	spin_unlock_irq(&workqueue_lock);
2409493a1724STejun Heo 
2410111c225aSTejun Heo 	/* rescuers should never participate in concurrency management */
2411111c225aSTejun Heo 	WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2412e22bee78STejun Heo 	schedule();
2413e22bee78STejun Heo 	goto repeat;
24141da177e4SLinus Torvalds }
24151da177e4SLinus Torvalds 
2416fc2e4d70SOleg Nesterov struct wq_barrier {
2417fc2e4d70SOleg Nesterov 	struct work_struct	work;
2418fc2e4d70SOleg Nesterov 	struct completion	done;
2419fc2e4d70SOleg Nesterov };
2420fc2e4d70SOleg Nesterov 
2421fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
2422fc2e4d70SOleg Nesterov {
2423fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2424fc2e4d70SOleg Nesterov 	complete(&barr->done);
2425fc2e4d70SOleg Nesterov }
2426fc2e4d70SOleg Nesterov 
24274690c4abSTejun Heo /**
24284690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
2429112202d9STejun Heo  * @pwq: pwq to insert barrier into
24304690c4abSTejun Heo  * @barr: wq_barrier to insert
2431affee4b2STejun Heo  * @target: target work to attach @barr to
2432affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
24334690c4abSTejun Heo  *
2434affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
2435affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
2436affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
2437affee4b2STejun Heo  * cpu.
2438affee4b2STejun Heo  *
2439affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
2440affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
2441affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
2442affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
2443affee4b2STejun Heo  * after a work with LINKED flag set.
2444affee4b2STejun Heo  *
2445affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
2446112202d9STejun Heo  * underneath us, so we can't reliably determine pwq from @target.
24474690c4abSTejun Heo  *
24484690c4abSTejun Heo  * CONTEXT:
2449d565ed63STejun Heo  * spin_lock_irq(pool->lock).
24504690c4abSTejun Heo  */
2451112202d9STejun Heo static void insert_wq_barrier(struct pool_workqueue *pwq,
2452affee4b2STejun Heo 			      struct wq_barrier *barr,
2453affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
2454fc2e4d70SOleg Nesterov {
2455affee4b2STejun Heo 	struct list_head *head;
2456affee4b2STejun Heo 	unsigned int linked = 0;
2457affee4b2STejun Heo 
2458dc186ad7SThomas Gleixner 	/*
2459d565ed63STejun Heo 	 * debugobject calls are safe here even with pool->lock locked
2460dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
2461dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
2462dc186ad7SThomas Gleixner 	 * might deadlock.
2463dc186ad7SThomas Gleixner 	 */
2464ca1cab37SAndrew Morton 	INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
246522df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2466fc2e4d70SOleg Nesterov 	init_completion(&barr->done);
246783c22520SOleg Nesterov 
2468affee4b2STejun Heo 	/*
2469affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
2470affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
2471affee4b2STejun Heo 	 */
2472affee4b2STejun Heo 	if (worker)
2473affee4b2STejun Heo 		head = worker->scheduled.next;
2474affee4b2STejun Heo 	else {
2475affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
2476affee4b2STejun Heo 
2477affee4b2STejun Heo 		head = target->entry.next;
2478affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
2479affee4b2STejun Heo 		linked = *bits & WORK_STRUCT_LINKED;
2480affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
2481affee4b2STejun Heo 	}
2482affee4b2STejun Heo 
2483dc186ad7SThomas Gleixner 	debug_work_activate(&barr->work);
2484112202d9STejun Heo 	insert_work(pwq, &barr->work, head,
2485affee4b2STejun Heo 		    work_color_to_flags(WORK_NO_COLOR) | linked);
2486fc2e4d70SOleg Nesterov }
2487fc2e4d70SOleg Nesterov 
248873f53c4aSTejun Heo /**
2489112202d9STejun Heo  * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
249073f53c4aSTejun Heo  * @wq: workqueue being flushed
249173f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
249273f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
249373f53c4aSTejun Heo  *
2494112202d9STejun Heo  * Prepare pwqs for workqueue flushing.
249573f53c4aSTejun Heo  *
2496112202d9STejun Heo  * If @flush_color is non-negative, flush_color on all pwqs should be
2497112202d9STejun Heo  * -1.  If no pwq has in-flight commands at the specified color, all
2498112202d9STejun Heo  * pwq->flush_color's stay at -1 and %false is returned.  If any pwq
2499112202d9STejun Heo  * has in flight commands, its pwq->flush_color is set to
2500112202d9STejun Heo  * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
250173f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
250273f53c4aSTejun Heo  *
250373f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
250473f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
250573f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
250673f53c4aSTejun Heo  * is returned.
250773f53c4aSTejun Heo  *
2508112202d9STejun Heo  * If @work_color is non-negative, all pwqs should have the same
250973f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
251073f53c4aSTejun Heo  * advanced to @work_color.
251173f53c4aSTejun Heo  *
251273f53c4aSTejun Heo  * CONTEXT:
251373f53c4aSTejun Heo  * mutex_lock(wq->flush_mutex).
251473f53c4aSTejun Heo  *
251573f53c4aSTejun Heo  * RETURNS:
251673f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
251773f53c4aSTejun Heo  * otherwise.
251873f53c4aSTejun Heo  */
2519112202d9STejun Heo static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
252073f53c4aSTejun Heo 				      int flush_color, int work_color)
25211da177e4SLinus Torvalds {
252273f53c4aSTejun Heo 	bool wait = false;
252349e3cf44STejun Heo 	struct pool_workqueue *pwq;
25241da177e4SLinus Torvalds 
252573f53c4aSTejun Heo 	if (flush_color >= 0) {
25266183c009STejun Heo 		WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2527112202d9STejun Heo 		atomic_set(&wq->nr_pwqs_to_flush, 1);
2528dc186ad7SThomas Gleixner 	}
252914441960SOleg Nesterov 
253076af4d93STejun Heo 	local_irq_disable();
253176af4d93STejun Heo 
253249e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2533112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
25341da177e4SLinus Torvalds 
253576af4d93STejun Heo 		spin_lock(&pool->lock);
253673f53c4aSTejun Heo 
253773f53c4aSTejun Heo 		if (flush_color >= 0) {
25386183c009STejun Heo 			WARN_ON_ONCE(pwq->flush_color != -1);
253973f53c4aSTejun Heo 
2540112202d9STejun Heo 			if (pwq->nr_in_flight[flush_color]) {
2541112202d9STejun Heo 				pwq->flush_color = flush_color;
2542112202d9STejun Heo 				atomic_inc(&wq->nr_pwqs_to_flush);
254373f53c4aSTejun Heo 				wait = true;
25441da177e4SLinus Torvalds 			}
254573f53c4aSTejun Heo 		}
254673f53c4aSTejun Heo 
254773f53c4aSTejun Heo 		if (work_color >= 0) {
25486183c009STejun Heo 			WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2549112202d9STejun Heo 			pwq->work_color = work_color;
255073f53c4aSTejun Heo 		}
255173f53c4aSTejun Heo 
255276af4d93STejun Heo 		spin_unlock(&pool->lock);
25531da177e4SLinus Torvalds 	}
25541da177e4SLinus Torvalds 
255576af4d93STejun Heo 	local_irq_enable();
255676af4d93STejun Heo 
2557112202d9STejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
255873f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
255973f53c4aSTejun Heo 
256073f53c4aSTejun Heo 	return wait;
256183c22520SOleg Nesterov }
25621da177e4SLinus Torvalds 
25630fcb78c2SRolf Eike Beer /**
25641da177e4SLinus Torvalds  * flush_workqueue - ensure that any scheduled work has run to completion.
25650fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
25661da177e4SLinus Torvalds  *
25671da177e4SLinus Torvalds  * Forces execution of the workqueue and blocks until its completion.
25681da177e4SLinus Torvalds  * This is typically used in driver shutdown handlers.
25691da177e4SLinus Torvalds  *
2570fc2e4d70SOleg Nesterov  * We sleep until all works which were queued on entry have been handled,
2571fc2e4d70SOleg Nesterov  * but we are not livelocked by new incoming ones.
25721da177e4SLinus Torvalds  */
25737ad5b3a5SHarvey Harrison void flush_workqueue(struct workqueue_struct *wq)
25741da177e4SLinus Torvalds {
257573f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
257673f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
257773f53c4aSTejun Heo 		.flush_color = -1,
257873f53c4aSTejun Heo 		.done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
257973f53c4aSTejun Heo 	};
258073f53c4aSTejun Heo 	int next_color;
2581b1f4ec17SOleg Nesterov 
25823295f0efSIngo Molnar 	lock_map_acquire(&wq->lockdep_map);
25833295f0efSIngo Molnar 	lock_map_release(&wq->lockdep_map);
258473f53c4aSTejun Heo 
258573f53c4aSTejun Heo 	mutex_lock(&wq->flush_mutex);
258673f53c4aSTejun Heo 
258773f53c4aSTejun Heo 	/*
258873f53c4aSTejun Heo 	 * Start-to-wait phase
258973f53c4aSTejun Heo 	 */
259073f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
259173f53c4aSTejun Heo 
259273f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
259373f53c4aSTejun Heo 		/*
259473f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
259573f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
259673f53c4aSTejun Heo 		 * by one.
259773f53c4aSTejun Heo 		 */
25986183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
259973f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
260073f53c4aSTejun Heo 		wq->work_color = next_color;
260173f53c4aSTejun Heo 
260273f53c4aSTejun Heo 		if (!wq->first_flusher) {
260373f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
26046183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
260573f53c4aSTejun Heo 
260673f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
260773f53c4aSTejun Heo 
2608112202d9STejun Heo 			if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
260973f53c4aSTejun Heo 						       wq->work_color)) {
261073f53c4aSTejun Heo 				/* nothing to flush, done */
261173f53c4aSTejun Heo 				wq->flush_color = next_color;
261273f53c4aSTejun Heo 				wq->first_flusher = NULL;
261373f53c4aSTejun Heo 				goto out_unlock;
261473f53c4aSTejun Heo 			}
261573f53c4aSTejun Heo 		} else {
261673f53c4aSTejun Heo 			/* wait in queue */
26176183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
261873f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
2619112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
262073f53c4aSTejun Heo 		}
262173f53c4aSTejun Heo 	} else {
262273f53c4aSTejun Heo 		/*
262373f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
262473f53c4aSTejun Heo 		 * The next flush completion will assign us
262573f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
262673f53c4aSTejun Heo 		 */
262773f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
262873f53c4aSTejun Heo 	}
262973f53c4aSTejun Heo 
263073f53c4aSTejun Heo 	mutex_unlock(&wq->flush_mutex);
263173f53c4aSTejun Heo 
263273f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
263373f53c4aSTejun Heo 
263473f53c4aSTejun Heo 	/*
263573f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
263673f53c4aSTejun Heo 	 *
263773f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
263873f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
263973f53c4aSTejun Heo 	 */
264073f53c4aSTejun Heo 	if (wq->first_flusher != &this_flusher)
264173f53c4aSTejun Heo 		return;
264273f53c4aSTejun Heo 
264373f53c4aSTejun Heo 	mutex_lock(&wq->flush_mutex);
264473f53c4aSTejun Heo 
26454ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
26464ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
26474ce48b37STejun Heo 		goto out_unlock;
26484ce48b37STejun Heo 
264973f53c4aSTejun Heo 	wq->first_flusher = NULL;
265073f53c4aSTejun Heo 
26516183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&this_flusher.list));
26526183c009STejun Heo 	WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
265373f53c4aSTejun Heo 
265473f53c4aSTejun Heo 	while (true) {
265573f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
265673f53c4aSTejun Heo 
265773f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
265873f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
265973f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
266073f53c4aSTejun Heo 				break;
266173f53c4aSTejun Heo 			list_del_init(&next->list);
266273f53c4aSTejun Heo 			complete(&next->done);
266373f53c4aSTejun Heo 		}
266473f53c4aSTejun Heo 
26656183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
266673f53c4aSTejun Heo 			     wq->flush_color != work_next_color(wq->work_color));
266773f53c4aSTejun Heo 
266873f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
266973f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
267073f53c4aSTejun Heo 
267173f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
267273f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
267373f53c4aSTejun Heo 			/*
267473f53c4aSTejun Heo 			 * Assign the same color to all overflowed
267573f53c4aSTejun Heo 			 * flushers, advance work_color and append to
267673f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
267773f53c4aSTejun Heo 			 * phase for these overflowed flushers.
267873f53c4aSTejun Heo 			 */
267973f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
268073f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
268173f53c4aSTejun Heo 
268273f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
268373f53c4aSTejun Heo 
268473f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
268573f53c4aSTejun Heo 					      &wq->flusher_queue);
2686112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
268773f53c4aSTejun Heo 		}
268873f53c4aSTejun Heo 
268973f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
26906183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != wq->work_color);
269173f53c4aSTejun Heo 			break;
269273f53c4aSTejun Heo 		}
269373f53c4aSTejun Heo 
269473f53c4aSTejun Heo 		/*
269573f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
2696112202d9STejun Heo 		 * the new first flusher and arm pwqs.
269773f53c4aSTejun Heo 		 */
26986183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color == wq->work_color);
26996183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color != next->flush_color);
270073f53c4aSTejun Heo 
270173f53c4aSTejun Heo 		list_del_init(&next->list);
270273f53c4aSTejun Heo 		wq->first_flusher = next;
270373f53c4aSTejun Heo 
2704112202d9STejun Heo 		if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
270573f53c4aSTejun Heo 			break;
270673f53c4aSTejun Heo 
270773f53c4aSTejun Heo 		/*
270873f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
270973f53c4aSTejun Heo 		 * flusher and repeat cascading.
271073f53c4aSTejun Heo 		 */
271173f53c4aSTejun Heo 		wq->first_flusher = NULL;
271273f53c4aSTejun Heo 	}
271373f53c4aSTejun Heo 
271473f53c4aSTejun Heo out_unlock:
271573f53c4aSTejun Heo 	mutex_unlock(&wq->flush_mutex);
27161da177e4SLinus Torvalds }
2717ae90dd5dSDave Jones EXPORT_SYMBOL_GPL(flush_workqueue);
27181da177e4SLinus Torvalds 
27199c5a2ba7STejun Heo /**
27209c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
27219c5a2ba7STejun Heo  * @wq: workqueue to drain
27229c5a2ba7STejun Heo  *
27239c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
27249c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
27259c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
27269c5a2ba7STejun Heo  * repeatedly until it becomes empty.  The number of flushing is detemined
27279c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
27289c5a2ba7STejun Heo  * takes too long.
27299c5a2ba7STejun Heo  */
27309c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
27319c5a2ba7STejun Heo {
27329c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
273349e3cf44STejun Heo 	struct pool_workqueue *pwq;
27349c5a2ba7STejun Heo 
27359c5a2ba7STejun Heo 	/*
27369c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
27379c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
27389c5a2ba7STejun Heo 	 * Use WQ_DRAINING so that queue doesn't have to check nr_drainers.
27399c5a2ba7STejun Heo 	 */
2740e98d5b16STejun Heo 	spin_lock_irq(&workqueue_lock);
27419c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
27429c5a2ba7STejun Heo 		wq->flags |= WQ_DRAINING;
2743e98d5b16STejun Heo 	spin_unlock_irq(&workqueue_lock);
27449c5a2ba7STejun Heo reflush:
27459c5a2ba7STejun Heo 	flush_workqueue(wq);
27469c5a2ba7STejun Heo 
274776af4d93STejun Heo 	local_irq_disable();
274876af4d93STejun Heo 
274949e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2750fa2563e4SThomas Tuttle 		bool drained;
27519c5a2ba7STejun Heo 
275276af4d93STejun Heo 		spin_lock(&pwq->pool->lock);
2753112202d9STejun Heo 		drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
275476af4d93STejun Heo 		spin_unlock(&pwq->pool->lock);
2755fa2563e4SThomas Tuttle 
2756fa2563e4SThomas Tuttle 		if (drained)
27579c5a2ba7STejun Heo 			continue;
27589c5a2ba7STejun Heo 
27599c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
27609c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2761044c782cSValentin Ilie 			pr_warn("workqueue %s: flush on destruction isn't complete after %u tries\n",
27629c5a2ba7STejun Heo 				wq->name, flush_cnt);
276376af4d93STejun Heo 
276476af4d93STejun Heo 		local_irq_enable();
27659c5a2ba7STejun Heo 		goto reflush;
27669c5a2ba7STejun Heo 	}
27679c5a2ba7STejun Heo 
276876af4d93STejun Heo 	spin_lock(&workqueue_lock);
27699c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
27709c5a2ba7STejun Heo 		wq->flags &= ~WQ_DRAINING;
277176af4d93STejun Heo 	spin_unlock(&workqueue_lock);
277276af4d93STejun Heo 
277376af4d93STejun Heo 	local_irq_enable();
27749c5a2ba7STejun Heo }
27759c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
27769c5a2ba7STejun Heo 
2777606a5020STejun Heo static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2778baf59022STejun Heo {
2779baf59022STejun Heo 	struct worker *worker = NULL;
2780c9e7cf27STejun Heo 	struct worker_pool *pool;
2781112202d9STejun Heo 	struct pool_workqueue *pwq;
2782baf59022STejun Heo 
2783baf59022STejun Heo 	might_sleep();
2784baf59022STejun Heo 
2785*fa1b54e6STejun Heo 	local_irq_disable();
2786*fa1b54e6STejun Heo 	pool = get_work_pool(work);
2787*fa1b54e6STejun Heo 	if (!pool) {
2788*fa1b54e6STejun Heo 		local_irq_enable();
2789*fa1b54e6STejun Heo 		return false;
2790*fa1b54e6STejun Heo 	}
2791*fa1b54e6STejun Heo 
2792*fa1b54e6STejun Heo 	spin_lock(&pool->lock);
27930b3dae68SLai Jiangshan 	/* see the comment in try_to_grab_pending() with the same code */
2794112202d9STejun Heo 	pwq = get_work_pwq(work);
2795112202d9STejun Heo 	if (pwq) {
2796112202d9STejun Heo 		if (unlikely(pwq->pool != pool))
2797baf59022STejun Heo 			goto already_gone;
2798606a5020STejun Heo 	} else {
2799c9e7cf27STejun Heo 		worker = find_worker_executing_work(pool, work);
2800baf59022STejun Heo 		if (!worker)
2801baf59022STejun Heo 			goto already_gone;
2802112202d9STejun Heo 		pwq = worker->current_pwq;
2803606a5020STejun Heo 	}
2804baf59022STejun Heo 
2805112202d9STejun Heo 	insert_wq_barrier(pwq, barr, work, worker);
2806d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2807baf59022STejun Heo 
2808e159489bSTejun Heo 	/*
2809e159489bSTejun Heo 	 * If @max_active is 1 or rescuer is in use, flushing another work
2810e159489bSTejun Heo 	 * item on the same workqueue may lead to deadlock.  Make sure the
2811e159489bSTejun Heo 	 * flusher is not running on the same workqueue by verifying write
2812e159489bSTejun Heo 	 * access.
2813e159489bSTejun Heo 	 */
2814112202d9STejun Heo 	if (pwq->wq->saved_max_active == 1 || pwq->wq->flags & WQ_RESCUER)
2815112202d9STejun Heo 		lock_map_acquire(&pwq->wq->lockdep_map);
2816e159489bSTejun Heo 	else
2817112202d9STejun Heo 		lock_map_acquire_read(&pwq->wq->lockdep_map);
2818112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
2819e159489bSTejun Heo 
2820baf59022STejun Heo 	return true;
2821baf59022STejun Heo already_gone:
2822d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2823baf59022STejun Heo 	return false;
2824baf59022STejun Heo }
2825baf59022STejun Heo 
2826db700897SOleg Nesterov /**
2827401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
2828401a8d04STejun Heo  * @work: the work to flush
2829db700897SOleg Nesterov  *
2830606a5020STejun Heo  * Wait until @work has finished execution.  @work is guaranteed to be idle
2831606a5020STejun Heo  * on return if it hasn't been requeued since flush started.
2832401a8d04STejun Heo  *
2833401a8d04STejun Heo  * RETURNS:
2834401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
2835401a8d04STejun Heo  * %false if it was already idle.
2836db700897SOleg Nesterov  */
2837401a8d04STejun Heo bool flush_work(struct work_struct *work)
2838db700897SOleg Nesterov {
2839db700897SOleg Nesterov 	struct wq_barrier barr;
2840db700897SOleg Nesterov 
28410976dfc1SStephen Boyd 	lock_map_acquire(&work->lockdep_map);
28420976dfc1SStephen Boyd 	lock_map_release(&work->lockdep_map);
28430976dfc1SStephen Boyd 
2844606a5020STejun Heo 	if (start_flush_work(work, &barr)) {
2845db700897SOleg Nesterov 		wait_for_completion(&barr.done);
2846dc186ad7SThomas Gleixner 		destroy_work_on_stack(&barr.work);
2847401a8d04STejun Heo 		return true;
2848606a5020STejun Heo 	} else {
2849401a8d04STejun Heo 		return false;
2850db700897SOleg Nesterov 	}
2851606a5020STejun Heo }
2852db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
2853db700897SOleg Nesterov 
285436e227d2STejun Heo static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2855401a8d04STejun Heo {
2856bbb68dfaSTejun Heo 	unsigned long flags;
28571f1f642eSOleg Nesterov 	int ret;
28581f1f642eSOleg Nesterov 
28591f1f642eSOleg Nesterov 	do {
2860bbb68dfaSTejun Heo 		ret = try_to_grab_pending(work, is_dwork, &flags);
2861bbb68dfaSTejun Heo 		/*
2862bbb68dfaSTejun Heo 		 * If someone else is canceling, wait for the same event it
2863bbb68dfaSTejun Heo 		 * would be waiting for before retrying.
2864bbb68dfaSTejun Heo 		 */
2865bbb68dfaSTejun Heo 		if (unlikely(ret == -ENOENT))
2866606a5020STejun Heo 			flush_work(work);
28671f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
28681f1f642eSOleg Nesterov 
2869bbb68dfaSTejun Heo 	/* tell other tasks trying to grab @work to back off */
2870bbb68dfaSTejun Heo 	mark_work_canceling(work);
2871bbb68dfaSTejun Heo 	local_irq_restore(flags);
2872bbb68dfaSTejun Heo 
2873606a5020STejun Heo 	flush_work(work);
28747a22ad75STejun Heo 	clear_work_data(work);
28751f1f642eSOleg Nesterov 	return ret;
28761f1f642eSOleg Nesterov }
28771f1f642eSOleg Nesterov 
28786e84d644SOleg Nesterov /**
2879401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
2880401a8d04STejun Heo  * @work: the work to cancel
28816e84d644SOleg Nesterov  *
2882401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
2883401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
2884401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
2885401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
28861f1f642eSOleg Nesterov  *
2887401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
2888401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
28896e84d644SOleg Nesterov  *
2890401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
28916e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
2892401a8d04STejun Heo  *
2893401a8d04STejun Heo  * RETURNS:
2894401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
28956e84d644SOleg Nesterov  */
2896401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
28976e84d644SOleg Nesterov {
289836e227d2STejun Heo 	return __cancel_work_timer(work, false);
2899b89deed3SOleg Nesterov }
290028e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
2901b89deed3SOleg Nesterov 
29026e84d644SOleg Nesterov /**
2903401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
2904401a8d04STejun Heo  * @dwork: the delayed work to flush
29056e84d644SOleg Nesterov  *
2906401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
2907401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
2908401a8d04STejun Heo  * considers the last queueing instance of @dwork.
29091f1f642eSOleg Nesterov  *
2910401a8d04STejun Heo  * RETURNS:
2911401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
2912401a8d04STejun Heo  * %false if it was already idle.
29136e84d644SOleg Nesterov  */
2914401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
2915401a8d04STejun Heo {
29168930cabaSTejun Heo 	local_irq_disable();
2917401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
291860c057bcSLai Jiangshan 		__queue_work(dwork->cpu, dwork->wq, &dwork->work);
29198930cabaSTejun Heo 	local_irq_enable();
2920401a8d04STejun Heo 	return flush_work(&dwork->work);
2921401a8d04STejun Heo }
2922401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
2923401a8d04STejun Heo 
2924401a8d04STejun Heo /**
292557b30ae7STejun Heo  * cancel_delayed_work - cancel a delayed work
292657b30ae7STejun Heo  * @dwork: delayed_work to cancel
292709383498STejun Heo  *
292857b30ae7STejun Heo  * Kill off a pending delayed_work.  Returns %true if @dwork was pending
292957b30ae7STejun Heo  * and canceled; %false if wasn't pending.  Note that the work callback
293057b30ae7STejun Heo  * function may still be running on return, unless it returns %true and the
293157b30ae7STejun Heo  * work doesn't re-arm itself.  Explicitly flush or use
293257b30ae7STejun Heo  * cancel_delayed_work_sync() to wait on it.
293309383498STejun Heo  *
293457b30ae7STejun Heo  * This function is safe to call from any context including IRQ handler.
293509383498STejun Heo  */
293657b30ae7STejun Heo bool cancel_delayed_work(struct delayed_work *dwork)
293709383498STejun Heo {
293857b30ae7STejun Heo 	unsigned long flags;
293957b30ae7STejun Heo 	int ret;
294057b30ae7STejun Heo 
294157b30ae7STejun Heo 	do {
294257b30ae7STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
294357b30ae7STejun Heo 	} while (unlikely(ret == -EAGAIN));
294457b30ae7STejun Heo 
294557b30ae7STejun Heo 	if (unlikely(ret < 0))
294657b30ae7STejun Heo 		return false;
294757b30ae7STejun Heo 
29487c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(&dwork->work,
29497c3eed5cSTejun Heo 					get_work_pool_id(&dwork->work));
295057b30ae7STejun Heo 	local_irq_restore(flags);
2951c0158ca6SDan Magenheimer 	return ret;
295209383498STejun Heo }
295357b30ae7STejun Heo EXPORT_SYMBOL(cancel_delayed_work);
295409383498STejun Heo 
295509383498STejun Heo /**
2956401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2957401a8d04STejun Heo  * @dwork: the delayed work cancel
2958401a8d04STejun Heo  *
2959401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
2960401a8d04STejun Heo  *
2961401a8d04STejun Heo  * RETURNS:
2962401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
2963401a8d04STejun Heo  */
2964401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
29656e84d644SOleg Nesterov {
296636e227d2STejun Heo 	return __cancel_work_timer(&dwork->work, true);
29676e84d644SOleg Nesterov }
2968f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
29691da177e4SLinus Torvalds 
29700fcb78c2SRolf Eike Beer /**
2971c1a220e7SZhang Rui  * schedule_work_on - put work task on a specific cpu
2972c1a220e7SZhang Rui  * @cpu: cpu to put the work task on
2973c1a220e7SZhang Rui  * @work: job to be done
2974c1a220e7SZhang Rui  *
2975c1a220e7SZhang Rui  * This puts a job on a specific cpu
2976c1a220e7SZhang Rui  */
2977d4283e93STejun Heo bool schedule_work_on(int cpu, struct work_struct *work)
2978c1a220e7SZhang Rui {
2979d320c038STejun Heo 	return queue_work_on(cpu, system_wq, work);
2980c1a220e7SZhang Rui }
2981c1a220e7SZhang Rui EXPORT_SYMBOL(schedule_work_on);
2982c1a220e7SZhang Rui 
29830fcb78c2SRolf Eike Beer /**
2984ae90dd5dSDave Jones  * schedule_work - put work task in global workqueue
29851da177e4SLinus Torvalds  * @work: job to be done
29861da177e4SLinus Torvalds  *
2987d4283e93STejun Heo  * Returns %false if @work was already on the kernel-global workqueue and
2988d4283e93STejun Heo  * %true otherwise.
298952bad64dSDavid Howells  *
29900fcb78c2SRolf Eike Beer  * This puts a job in the kernel-global workqueue if it was not already
29910fcb78c2SRolf Eike Beer  * queued and leaves it in the same position on the kernel-global
29920fcb78c2SRolf Eike Beer  * workqueue otherwise.
29931da177e4SLinus Torvalds  */
2994d4283e93STejun Heo bool schedule_work(struct work_struct *work)
29951da177e4SLinus Torvalds {
29960fcb78c2SRolf Eike Beer 	return queue_work(system_wq, work);
29971da177e4SLinus Torvalds }
29980fcb78c2SRolf Eike Beer EXPORT_SYMBOL(schedule_work);
29991da177e4SLinus Torvalds 
30000fcb78c2SRolf Eike Beer /**
30010fcb78c2SRolf Eike Beer  * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
30020fcb78c2SRolf Eike Beer  * @cpu: cpu to use
30030fcb78c2SRolf Eike Beer  * @dwork: job to be done
30040fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait
30050fcb78c2SRolf Eike Beer  *
30060fcb78c2SRolf Eike Beer  * After waiting for a given time this puts a job in the kernel-global
30070fcb78c2SRolf Eike Beer  * workqueue on the specified CPU.
30080fcb78c2SRolf Eike Beer  */
3009d4283e93STejun Heo bool schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
3010d4283e93STejun Heo 			      unsigned long delay)
30111da177e4SLinus Torvalds {
3012d320c038STejun Heo 	return queue_delayed_work_on(cpu, system_wq, dwork, delay);
30131da177e4SLinus Torvalds }
3014ae90dd5dSDave Jones EXPORT_SYMBOL(schedule_delayed_work_on);
30151da177e4SLinus Torvalds 
3016b6136773SAndrew Morton /**
30170a13c00eSTejun Heo  * schedule_delayed_work - put work task in global workqueue after delay
30180a13c00eSTejun Heo  * @dwork: job to be done
30190a13c00eSTejun Heo  * @delay: number of jiffies to wait or 0 for immediate execution
30200a13c00eSTejun Heo  *
30210a13c00eSTejun Heo  * After waiting for a given time this puts a job in the kernel-global
30220a13c00eSTejun Heo  * workqueue.
30230a13c00eSTejun Heo  */
3024d4283e93STejun Heo bool schedule_delayed_work(struct delayed_work *dwork, unsigned long delay)
30250a13c00eSTejun Heo {
30260a13c00eSTejun Heo 	return queue_delayed_work(system_wq, dwork, delay);
30270a13c00eSTejun Heo }
30280a13c00eSTejun Heo EXPORT_SYMBOL(schedule_delayed_work);
30290a13c00eSTejun Heo 
30300a13c00eSTejun Heo /**
303131ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
3032b6136773SAndrew Morton  * @func: the function to call
3033b6136773SAndrew Morton  *
303431ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
303531ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
3036b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
303731ddd871STejun Heo  *
303831ddd871STejun Heo  * RETURNS:
303931ddd871STejun Heo  * 0 on success, -errno on failure.
3040b6136773SAndrew Morton  */
304165f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
304215316ba8SChristoph Lameter {
304315316ba8SChristoph Lameter 	int cpu;
304438f51568SNamhyung Kim 	struct work_struct __percpu *works;
304515316ba8SChristoph Lameter 
3046b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
3047b6136773SAndrew Morton 	if (!works)
304815316ba8SChristoph Lameter 		return -ENOMEM;
3049b6136773SAndrew Morton 
305095402b38SGautham R Shenoy 	get_online_cpus();
305193981800STejun Heo 
305215316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
30539bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
30549bfb1839SIngo Molnar 
30559bfb1839SIngo Molnar 		INIT_WORK(work, func);
30568de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
305715316ba8SChristoph Lameter 	}
305893981800STejun Heo 
305993981800STejun Heo 	for_each_online_cpu(cpu)
30608616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
306193981800STejun Heo 
306295402b38SGautham R Shenoy 	put_online_cpus();
3063b6136773SAndrew Morton 	free_percpu(works);
306415316ba8SChristoph Lameter 	return 0;
306515316ba8SChristoph Lameter }
306615316ba8SChristoph Lameter 
3067eef6a7d5SAlan Stern /**
3068eef6a7d5SAlan Stern  * flush_scheduled_work - ensure that any scheduled work has run to completion.
3069eef6a7d5SAlan Stern  *
3070eef6a7d5SAlan Stern  * Forces execution of the kernel-global workqueue and blocks until its
3071eef6a7d5SAlan Stern  * completion.
3072eef6a7d5SAlan Stern  *
3073eef6a7d5SAlan Stern  * Think twice before calling this function!  It's very easy to get into
3074eef6a7d5SAlan Stern  * trouble if you don't take great care.  Either of the following situations
3075eef6a7d5SAlan Stern  * will lead to deadlock:
3076eef6a7d5SAlan Stern  *
3077eef6a7d5SAlan Stern  *	One of the work items currently on the workqueue needs to acquire
3078eef6a7d5SAlan Stern  *	a lock held by your code or its caller.
3079eef6a7d5SAlan Stern  *
3080eef6a7d5SAlan Stern  *	Your code is running in the context of a work routine.
3081eef6a7d5SAlan Stern  *
3082eef6a7d5SAlan Stern  * They will be detected by lockdep when they occur, but the first might not
3083eef6a7d5SAlan Stern  * occur very often.  It depends on what work items are on the workqueue and
3084eef6a7d5SAlan Stern  * what locks they need, which you have no control over.
3085eef6a7d5SAlan Stern  *
3086eef6a7d5SAlan Stern  * In most situations flushing the entire workqueue is overkill; you merely
3087eef6a7d5SAlan Stern  * need to know that a particular work item isn't queued and isn't running.
3088eef6a7d5SAlan Stern  * In such cases you should use cancel_delayed_work_sync() or
3089eef6a7d5SAlan Stern  * cancel_work_sync() instead.
3090eef6a7d5SAlan Stern  */
30911da177e4SLinus Torvalds void flush_scheduled_work(void)
30921da177e4SLinus Torvalds {
3093d320c038STejun Heo 	flush_workqueue(system_wq);
30941da177e4SLinus Torvalds }
3095ae90dd5dSDave Jones EXPORT_SYMBOL(flush_scheduled_work);
30961da177e4SLinus Torvalds 
30971da177e4SLinus Torvalds /**
30981fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
30991fa44ecaSJames Bottomley  * @fn:		the function to execute
31001fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
31011fa44ecaSJames Bottomley  *		be available when the work executes)
31021fa44ecaSJames Bottomley  *
31031fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
31041fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
31051fa44ecaSJames Bottomley  *
31061fa44ecaSJames Bottomley  * Returns:	0 - function was executed
31071fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
31081fa44ecaSJames Bottomley  */
310965f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
31101fa44ecaSJames Bottomley {
31111fa44ecaSJames Bottomley 	if (!in_interrupt()) {
311265f27f38SDavid Howells 		fn(&ew->work);
31131fa44ecaSJames Bottomley 		return 0;
31141fa44ecaSJames Bottomley 	}
31151fa44ecaSJames Bottomley 
311665f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
31171fa44ecaSJames Bottomley 	schedule_work(&ew->work);
31181fa44ecaSJames Bottomley 
31191fa44ecaSJames Bottomley 	return 1;
31201fa44ecaSJames Bottomley }
31211fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
31221fa44ecaSJames Bottomley 
31231da177e4SLinus Torvalds int keventd_up(void)
31241da177e4SLinus Torvalds {
3125d320c038STejun Heo 	return system_wq != NULL;
31261da177e4SLinus Torvalds }
31271da177e4SLinus Torvalds 
312830cdf249STejun Heo static int alloc_and_link_pwqs(struct workqueue_struct *wq)
31291da177e4SLinus Torvalds {
313049e3cf44STejun Heo 	bool highpri = wq->flags & WQ_HIGHPRI;
313130cdf249STejun Heo 	int cpu;
3132e1d8aa9fSFrederic Weisbecker 
313330cdf249STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
3134420c0ddbSTejun Heo 		wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
3135420c0ddbSTejun Heo 		if (!wq->cpu_pwqs)
313630cdf249STejun Heo 			return -ENOMEM;
313730cdf249STejun Heo 
313830cdf249STejun Heo 		for_each_possible_cpu(cpu) {
31397fb98ea7STejun Heo 			struct pool_workqueue *pwq =
31407fb98ea7STejun Heo 				per_cpu_ptr(wq->cpu_pwqs, cpu);
314130cdf249STejun Heo 
314249e3cf44STejun Heo 			pwq->pool = get_std_worker_pool(cpu, highpri);
314376af4d93STejun Heo 			list_add_tail_rcu(&pwq->pwqs_node, &wq->pwqs);
314430cdf249STejun Heo 		}
314530cdf249STejun Heo 	} else {
314630cdf249STejun Heo 		struct pool_workqueue *pwq;
314730cdf249STejun Heo 
314830cdf249STejun Heo 		pwq = kmem_cache_zalloc(pwq_cache, GFP_KERNEL);
314930cdf249STejun Heo 		if (!pwq)
315030cdf249STejun Heo 			return -ENOMEM;
315130cdf249STejun Heo 
315249e3cf44STejun Heo 		pwq->pool = get_std_worker_pool(WORK_CPU_UNBOUND, highpri);
315376af4d93STejun Heo 		list_add_tail_rcu(&pwq->pwqs_node, &wq->pwqs);
315430cdf249STejun Heo 	}
315530cdf249STejun Heo 
315630cdf249STejun Heo 	return 0;
31570f900049STejun Heo }
31580f900049STejun Heo 
3159112202d9STejun Heo static void free_pwqs(struct workqueue_struct *wq)
316006ba38a9SOleg Nesterov {
3161e06ffa1eSLai Jiangshan 	if (!(wq->flags & WQ_UNBOUND))
3162420c0ddbSTejun Heo 		free_percpu(wq->cpu_pwqs);
3163420c0ddbSTejun Heo 	else if (!list_empty(&wq->pwqs))
3164420c0ddbSTejun Heo 		kmem_cache_free(pwq_cache, list_first_entry(&wq->pwqs,
3165420c0ddbSTejun Heo 					struct pool_workqueue, pwqs_node));
316606ba38a9SOleg Nesterov }
316706ba38a9SOleg Nesterov 
3168f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
3169f3421797STejun Heo 			       const char *name)
3170b71ab8c2STejun Heo {
3171f3421797STejun Heo 	int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3172f3421797STejun Heo 
3173f3421797STejun Heo 	if (max_active < 1 || max_active > lim)
3174044c782cSValentin Ilie 		pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3175f3421797STejun Heo 			max_active, name, 1, lim);
3176b71ab8c2STejun Heo 
3177f3421797STejun Heo 	return clamp_val(max_active, 1, lim);
3178b71ab8c2STejun Heo }
3179b71ab8c2STejun Heo 
3180b196be89STejun Heo struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
318197e37d7bSTejun Heo 					       unsigned int flags,
31821e19ffc6STejun Heo 					       int max_active,
3183eb13ba87SJohannes Berg 					       struct lock_class_key *key,
3184b196be89STejun Heo 					       const char *lock_name, ...)
31853af24433SOleg Nesterov {
3186b196be89STejun Heo 	va_list args, args1;
31873af24433SOleg Nesterov 	struct workqueue_struct *wq;
318849e3cf44STejun Heo 	struct pool_workqueue *pwq;
3189b196be89STejun Heo 	size_t namelen;
3190b196be89STejun Heo 
3191b196be89STejun Heo 	/* determine namelen, allocate wq and format name */
3192b196be89STejun Heo 	va_start(args, lock_name);
3193b196be89STejun Heo 	va_copy(args1, args);
3194b196be89STejun Heo 	namelen = vsnprintf(NULL, 0, fmt, args) + 1;
3195b196be89STejun Heo 
3196b196be89STejun Heo 	wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
3197b196be89STejun Heo 	if (!wq)
3198b196be89STejun Heo 		goto err;
3199b196be89STejun Heo 
3200b196be89STejun Heo 	vsnprintf(wq->name, namelen, fmt, args1);
3201b196be89STejun Heo 	va_end(args);
3202b196be89STejun Heo 	va_end(args1);
32033af24433SOleg Nesterov 
3204f3421797STejun Heo 	/*
32056370a6adSTejun Heo 	 * Workqueues which may be used during memory reclaim should
32066370a6adSTejun Heo 	 * have a rescuer to guarantee forward progress.
32076370a6adSTejun Heo 	 */
32086370a6adSTejun Heo 	if (flags & WQ_MEM_RECLAIM)
32096370a6adSTejun Heo 		flags |= WQ_RESCUER;
32106370a6adSTejun Heo 
3211d320c038STejun Heo 	max_active = max_active ?: WQ_DFL_ACTIVE;
3212b196be89STejun Heo 	max_active = wq_clamp_max_active(max_active, flags, wq->name);
32133af24433SOleg Nesterov 
3214b196be89STejun Heo 	/* init wq */
321597e37d7bSTejun Heo 	wq->flags = flags;
3216a0a1a5fdSTejun Heo 	wq->saved_max_active = max_active;
321773f53c4aSTejun Heo 	mutex_init(&wq->flush_mutex);
3218112202d9STejun Heo 	atomic_set(&wq->nr_pwqs_to_flush, 0);
321930cdf249STejun Heo 	INIT_LIST_HEAD(&wq->pwqs);
322073f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
322173f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
3222493a1724STejun Heo 	INIT_LIST_HEAD(&wq->maydays);
32233af24433SOleg Nesterov 
3224eb13ba87SJohannes Berg 	lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3225cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
32263af24433SOleg Nesterov 
322730cdf249STejun Heo 	if (alloc_and_link_pwqs(wq) < 0)
3228bdbc5dd7STejun Heo 		goto err;
3229bdbc5dd7STejun Heo 
323076af4d93STejun Heo 	local_irq_disable();
323149e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
3232112202d9STejun Heo 		BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3233112202d9STejun Heo 		pwq->wq = wq;
3234112202d9STejun Heo 		pwq->flush_color = -1;
3235112202d9STejun Heo 		pwq->max_active = max_active;
3236112202d9STejun Heo 		INIT_LIST_HEAD(&pwq->delayed_works);
3237493a1724STejun Heo 		INIT_LIST_HEAD(&pwq->mayday_node);
3238e22bee78STejun Heo 	}
323976af4d93STejun Heo 	local_irq_enable();
32401537663fSTejun Heo 
3241e22bee78STejun Heo 	if (flags & WQ_RESCUER) {
3242e22bee78STejun Heo 		struct worker *rescuer;
3243e22bee78STejun Heo 
3244e22bee78STejun Heo 		wq->rescuer = rescuer = alloc_worker();
3245e22bee78STejun Heo 		if (!rescuer)
3246e22bee78STejun Heo 			goto err;
3247e22bee78STejun Heo 
3248111c225aSTejun Heo 		rescuer->rescue_wq = wq;
3249111c225aSTejun Heo 		rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
3250b196be89STejun Heo 					       wq->name);
3251e22bee78STejun Heo 		if (IS_ERR(rescuer->task))
3252e22bee78STejun Heo 			goto err;
3253e22bee78STejun Heo 
3254e22bee78STejun Heo 		rescuer->task->flags |= PF_THREAD_BOUND;
3255e22bee78STejun Heo 		wake_up_process(rescuer->task);
32563af24433SOleg Nesterov 	}
32571537663fSTejun Heo 
32583af24433SOleg Nesterov 	/*
3259a0a1a5fdSTejun Heo 	 * workqueue_lock protects global freeze state and workqueues
3260a0a1a5fdSTejun Heo 	 * list.  Grab it, set max_active accordingly and add the new
3261a0a1a5fdSTejun Heo 	 * workqueue to workqueues list.
32623af24433SOleg Nesterov 	 */
3263e98d5b16STejun Heo 	spin_lock_irq(&workqueue_lock);
3264a0a1a5fdSTejun Heo 
326558a69cb4STejun Heo 	if (workqueue_freezing && wq->flags & WQ_FREEZABLE)
326649e3cf44STejun Heo 		for_each_pwq(pwq, wq)
326749e3cf44STejun Heo 			pwq->max_active = 0;
3268a0a1a5fdSTejun Heo 
32693af24433SOleg Nesterov 	list_add(&wq->list, &workqueues);
3270a0a1a5fdSTejun Heo 
3271e98d5b16STejun Heo 	spin_unlock_irq(&workqueue_lock);
32723af24433SOleg Nesterov 
32733af24433SOleg Nesterov 	return wq;
32744690c4abSTejun Heo err:
32754690c4abSTejun Heo 	if (wq) {
3276112202d9STejun Heo 		free_pwqs(wq);
3277e22bee78STejun Heo 		kfree(wq->rescuer);
32784690c4abSTejun Heo 		kfree(wq);
32793af24433SOleg Nesterov 	}
32804690c4abSTejun Heo 	return NULL;
32811da177e4SLinus Torvalds }
3282d320c038STejun Heo EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
32831da177e4SLinus Torvalds 
32843af24433SOleg Nesterov /**
32853af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
32863af24433SOleg Nesterov  * @wq: target workqueue
32873af24433SOleg Nesterov  *
32883af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
32893af24433SOleg Nesterov  */
32903af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
32913af24433SOleg Nesterov {
329249e3cf44STejun Heo 	struct pool_workqueue *pwq;
32933af24433SOleg Nesterov 
32949c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
32959c5a2ba7STejun Heo 	drain_workqueue(wq);
3296c8efcc25STejun Heo 
329776af4d93STejun Heo 	spin_lock_irq(&workqueue_lock);
329876af4d93STejun Heo 
32996183c009STejun Heo 	/* sanity checks */
330049e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
33016183c009STejun Heo 		int i;
33026183c009STejun Heo 
330376af4d93STejun Heo 		for (i = 0; i < WORK_NR_COLORS; i++) {
330476af4d93STejun Heo 			if (WARN_ON(pwq->nr_in_flight[i])) {
330576af4d93STejun Heo 				spin_unlock_irq(&workqueue_lock);
33066183c009STejun Heo 				return;
330776af4d93STejun Heo 			}
330876af4d93STejun Heo 		}
330976af4d93STejun Heo 
33106183c009STejun Heo 		if (WARN_ON(pwq->nr_active) ||
331176af4d93STejun Heo 		    WARN_ON(!list_empty(&pwq->delayed_works))) {
331276af4d93STejun Heo 			spin_unlock_irq(&workqueue_lock);
33136183c009STejun Heo 			return;
33146183c009STejun Heo 		}
331576af4d93STejun Heo 	}
33166183c009STejun Heo 
3317a0a1a5fdSTejun Heo 	/*
3318a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
3319a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
3320a0a1a5fdSTejun Heo 	 */
33213af24433SOleg Nesterov 	list_del(&wq->list);
332276af4d93STejun Heo 
3323e98d5b16STejun Heo 	spin_unlock_irq(&workqueue_lock);
33243af24433SOleg Nesterov 
3325e22bee78STejun Heo 	if (wq->flags & WQ_RESCUER) {
3326e22bee78STejun Heo 		kthread_stop(wq->rescuer->task);
33278d9df9f0SXiaotian Feng 		kfree(wq->rescuer);
3328e22bee78STejun Heo 	}
3329e22bee78STejun Heo 
3330112202d9STejun Heo 	free_pwqs(wq);
33313af24433SOleg Nesterov 	kfree(wq);
33323af24433SOleg Nesterov }
33333af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
33343af24433SOleg Nesterov 
3335dcd989cbSTejun Heo /**
3336112202d9STejun Heo  * pwq_set_max_active - adjust max_active of a pwq
3337112202d9STejun Heo  * @pwq: target pool_workqueue
33389f4bd4cdSLai Jiangshan  * @max_active: new max_active value.
33399f4bd4cdSLai Jiangshan  *
3340112202d9STejun Heo  * Set @pwq->max_active to @max_active and activate delayed works if
33419f4bd4cdSLai Jiangshan  * increased.
33429f4bd4cdSLai Jiangshan  *
33439f4bd4cdSLai Jiangshan  * CONTEXT:
3344d565ed63STejun Heo  * spin_lock_irq(pool->lock).
33459f4bd4cdSLai Jiangshan  */
3346112202d9STejun Heo static void pwq_set_max_active(struct pool_workqueue *pwq, int max_active)
33479f4bd4cdSLai Jiangshan {
3348112202d9STejun Heo 	pwq->max_active = max_active;
33499f4bd4cdSLai Jiangshan 
3350112202d9STejun Heo 	while (!list_empty(&pwq->delayed_works) &&
3351112202d9STejun Heo 	       pwq->nr_active < pwq->max_active)
3352112202d9STejun Heo 		pwq_activate_first_delayed(pwq);
33539f4bd4cdSLai Jiangshan }
33549f4bd4cdSLai Jiangshan 
33559f4bd4cdSLai Jiangshan /**
3356dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
3357dcd989cbSTejun Heo  * @wq: target workqueue
3358dcd989cbSTejun Heo  * @max_active: new max_active value.
3359dcd989cbSTejun Heo  *
3360dcd989cbSTejun Heo  * Set max_active of @wq to @max_active.
3361dcd989cbSTejun Heo  *
3362dcd989cbSTejun Heo  * CONTEXT:
3363dcd989cbSTejun Heo  * Don't call from IRQ context.
3364dcd989cbSTejun Heo  */
3365dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
3366dcd989cbSTejun Heo {
336749e3cf44STejun Heo 	struct pool_workqueue *pwq;
3368dcd989cbSTejun Heo 
3369f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
3370dcd989cbSTejun Heo 
3371e98d5b16STejun Heo 	spin_lock_irq(&workqueue_lock);
3372dcd989cbSTejun Heo 
3373dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
3374dcd989cbSTejun Heo 
337549e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
3376112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
3377dcd989cbSTejun Heo 
3378e98d5b16STejun Heo 		spin_lock(&pool->lock);
3379dcd989cbSTejun Heo 
338058a69cb4STejun Heo 		if (!(wq->flags & WQ_FREEZABLE) ||
338135b6bb63STejun Heo 		    !(pool->flags & POOL_FREEZING))
3382112202d9STejun Heo 			pwq_set_max_active(pwq, max_active);
3383dcd989cbSTejun Heo 
3384e98d5b16STejun Heo 		spin_unlock(&pool->lock);
3385dcd989cbSTejun Heo 	}
3386dcd989cbSTejun Heo 
3387e98d5b16STejun Heo 	spin_unlock_irq(&workqueue_lock);
3388dcd989cbSTejun Heo }
3389dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
3390dcd989cbSTejun Heo 
3391dcd989cbSTejun Heo /**
3392dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
3393dcd989cbSTejun Heo  * @cpu: CPU in question
3394dcd989cbSTejun Heo  * @wq: target workqueue
3395dcd989cbSTejun Heo  *
3396dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
3397dcd989cbSTejun Heo  * no synchronization around this function and the test result is
3398dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
3399dcd989cbSTejun Heo  *
3400dcd989cbSTejun Heo  * RETURNS:
3401dcd989cbSTejun Heo  * %true if congested, %false otherwise.
3402dcd989cbSTejun Heo  */
3403d84ff051STejun Heo bool workqueue_congested(int cpu, struct workqueue_struct *wq)
3404dcd989cbSTejun Heo {
34057fb98ea7STejun Heo 	struct pool_workqueue *pwq;
340676af4d93STejun Heo 	bool ret;
340776af4d93STejun Heo 
340876af4d93STejun Heo 	preempt_disable();
34097fb98ea7STejun Heo 
34107fb98ea7STejun Heo 	if (!(wq->flags & WQ_UNBOUND))
34117fb98ea7STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
34127fb98ea7STejun Heo 	else
34137fb98ea7STejun Heo 		pwq = first_pwq(wq);
3414dcd989cbSTejun Heo 
341576af4d93STejun Heo 	ret = !list_empty(&pwq->delayed_works);
341676af4d93STejun Heo 	preempt_enable();
341776af4d93STejun Heo 
341876af4d93STejun Heo 	return ret;
3419dcd989cbSTejun Heo }
3420dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
3421dcd989cbSTejun Heo 
3422dcd989cbSTejun Heo /**
3423dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
3424dcd989cbSTejun Heo  * @work: the work to be tested
3425dcd989cbSTejun Heo  *
3426dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
3427dcd989cbSTejun Heo  * synchronization around this function and the test result is
3428dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
3429dcd989cbSTejun Heo  *
3430dcd989cbSTejun Heo  * RETURNS:
3431dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
3432dcd989cbSTejun Heo  */
3433dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
3434dcd989cbSTejun Heo {
3435*fa1b54e6STejun Heo 	struct worker_pool *pool;
3436dcd989cbSTejun Heo 	unsigned long flags;
3437dcd989cbSTejun Heo 	unsigned int ret = 0;
3438dcd989cbSTejun Heo 
3439dcd989cbSTejun Heo 	if (work_pending(work))
3440dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
3441038366c5SLai Jiangshan 
3442*fa1b54e6STejun Heo 	local_irq_save(flags);
3443*fa1b54e6STejun Heo 	pool = get_work_pool(work);
3444038366c5SLai Jiangshan 	if (pool) {
3445*fa1b54e6STejun Heo 		spin_lock(&pool->lock);
3446c9e7cf27STejun Heo 		if (find_worker_executing_work(pool, work))
3447dcd989cbSTejun Heo 			ret |= WORK_BUSY_RUNNING;
3448*fa1b54e6STejun Heo 		spin_unlock(&pool->lock);
3449038366c5SLai Jiangshan 	}
3450*fa1b54e6STejun Heo 	local_irq_restore(flags);
3451dcd989cbSTejun Heo 
3452dcd989cbSTejun Heo 	return ret;
3453dcd989cbSTejun Heo }
3454dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
3455dcd989cbSTejun Heo 
3456db7bccf4STejun Heo /*
3457db7bccf4STejun Heo  * CPU hotplug.
3458db7bccf4STejun Heo  *
3459e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
3460112202d9STejun Heo  * are a lot of assumptions on strong associations among work, pwq and
3461706026c2STejun Heo  * pool which make migrating pending and scheduled works very
3462e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
346394cf58bbSTejun Heo  * worker pools serve mix of short, long and very long running works making
3464e22bee78STejun Heo  * blocked draining impractical.
3465e22bee78STejun Heo  *
346624647570STejun Heo  * This is solved by allowing the pools to be disassociated from the CPU
3467628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
3468628c78e7STejun Heo  * cpu comes back online.
3469db7bccf4STejun Heo  */
3470db7bccf4STejun Heo 
3471706026c2STejun Heo static void wq_unbind_fn(struct work_struct *work)
3472db7bccf4STejun Heo {
347338db41d9STejun Heo 	int cpu = smp_processor_id();
34744ce62e9eSTejun Heo 	struct worker_pool *pool;
3475db7bccf4STejun Heo 	struct worker *worker;
3476db7bccf4STejun Heo 	int i;
3477db7bccf4STejun Heo 
347838db41d9STejun Heo 	for_each_std_worker_pool(pool, cpu) {
34796183c009STejun Heo 		WARN_ON_ONCE(cpu != smp_processor_id());
3480db7bccf4STejun Heo 
348194cf58bbSTejun Heo 		mutex_lock(&pool->assoc_mutex);
348294cf58bbSTejun Heo 		spin_lock_irq(&pool->lock);
3483e22bee78STejun Heo 
3484f2d5a0eeSTejun Heo 		/*
348594cf58bbSTejun Heo 		 * We've claimed all manager positions.  Make all workers
348694cf58bbSTejun Heo 		 * unbound and set DISASSOCIATED.  Before this, all workers
348794cf58bbSTejun Heo 		 * except for the ones which are still executing works from
348894cf58bbSTejun Heo 		 * before the last CPU down must be on the cpu.  After
348994cf58bbSTejun Heo 		 * this, they may become diasporas.
3490f2d5a0eeSTejun Heo 		 */
34914ce62e9eSTejun Heo 		list_for_each_entry(worker, &pool->idle_list, entry)
3492403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
3493db7bccf4STejun Heo 
3494b67bfe0dSSasha Levin 		for_each_busy_worker(worker, i, pool)
3495403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
3496db7bccf4STejun Heo 
349724647570STejun Heo 		pool->flags |= POOL_DISASSOCIATED;
3498f2d5a0eeSTejun Heo 
349994cf58bbSTejun Heo 		spin_unlock_irq(&pool->lock);
350094cf58bbSTejun Heo 		mutex_unlock(&pool->assoc_mutex);
350194cf58bbSTejun Heo 	}
3502e22bee78STejun Heo 
3503e22bee78STejun Heo 	/*
3504628c78e7STejun Heo 	 * Call schedule() so that we cross rq->lock and thus can guarantee
3505628c78e7STejun Heo 	 * sched callbacks see the %WORKER_UNBOUND flag.  This is necessary
3506628c78e7STejun Heo 	 * as scheduler callbacks may be invoked from other cpus.
3507628c78e7STejun Heo 	 */
3508628c78e7STejun Heo 	schedule();
3509628c78e7STejun Heo 
3510628c78e7STejun Heo 	/*
3511628c78e7STejun Heo 	 * Sched callbacks are disabled now.  Zap nr_running.  After this,
3512628c78e7STejun Heo 	 * nr_running stays zero and need_more_worker() and keep_working()
351338db41d9STejun Heo 	 * are always true as long as the worklist is not empty.  Pools on
351438db41d9STejun Heo 	 * @cpu now behave as unbound (in terms of concurrency management)
351538db41d9STejun Heo 	 * pools which are served by workers tied to the CPU.
3516628c78e7STejun Heo 	 *
3517628c78e7STejun Heo 	 * On return from this function, the current worker would trigger
3518628c78e7STejun Heo 	 * unbound chain execution of pending work items if other workers
3519628c78e7STejun Heo 	 * didn't already.
3520e22bee78STejun Heo 	 */
352138db41d9STejun Heo 	for_each_std_worker_pool(pool, cpu)
3522e19e397aSTejun Heo 		atomic_set(&pool->nr_running, 0);
3523db7bccf4STejun Heo }
3524db7bccf4STejun Heo 
35258db25e78STejun Heo /*
35268db25e78STejun Heo  * Workqueues should be brought up before normal priority CPU notifiers.
35278db25e78STejun Heo  * This will be registered high priority CPU notifier.
35288db25e78STejun Heo  */
35299fdf9b73SLai Jiangshan static int __cpuinit workqueue_cpu_up_callback(struct notifier_block *nfb,
35301da177e4SLinus Torvalds 					       unsigned long action,
35311da177e4SLinus Torvalds 					       void *hcpu)
35321da177e4SLinus Torvalds {
3533d84ff051STejun Heo 	int cpu = (unsigned long)hcpu;
35344ce62e9eSTejun Heo 	struct worker_pool *pool;
35351da177e4SLinus Torvalds 
35368db25e78STejun Heo 	switch (action & ~CPU_TASKS_FROZEN) {
35373af24433SOleg Nesterov 	case CPU_UP_PREPARE:
353838db41d9STejun Heo 		for_each_std_worker_pool(pool, cpu) {
35393ce63377STejun Heo 			struct worker *worker;
35403ce63377STejun Heo 
35413ce63377STejun Heo 			if (pool->nr_workers)
35423ce63377STejun Heo 				continue;
35433ce63377STejun Heo 
35443ce63377STejun Heo 			worker = create_worker(pool);
35453ce63377STejun Heo 			if (!worker)
35463ce63377STejun Heo 				return NOTIFY_BAD;
35473ce63377STejun Heo 
3548d565ed63STejun Heo 			spin_lock_irq(&pool->lock);
35493ce63377STejun Heo 			start_worker(worker);
3550d565ed63STejun Heo 			spin_unlock_irq(&pool->lock);
35513af24433SOleg Nesterov 		}
35521da177e4SLinus Torvalds 		break;
35531da177e4SLinus Torvalds 
355465758202STejun Heo 	case CPU_DOWN_FAILED:
355565758202STejun Heo 	case CPU_ONLINE:
355638db41d9STejun Heo 		for_each_std_worker_pool(pool, cpu) {
355794cf58bbSTejun Heo 			mutex_lock(&pool->assoc_mutex);
355894cf58bbSTejun Heo 			spin_lock_irq(&pool->lock);
355994cf58bbSTejun Heo 
356024647570STejun Heo 			pool->flags &= ~POOL_DISASSOCIATED;
356194cf58bbSTejun Heo 			rebind_workers(pool);
356294cf58bbSTejun Heo 
356394cf58bbSTejun Heo 			spin_unlock_irq(&pool->lock);
356494cf58bbSTejun Heo 			mutex_unlock(&pool->assoc_mutex);
356594cf58bbSTejun Heo 		}
35668db25e78STejun Heo 		break;
356765758202STejun Heo 	}
356865758202STejun Heo 	return NOTIFY_OK;
356965758202STejun Heo }
357065758202STejun Heo 
357165758202STejun Heo /*
357265758202STejun Heo  * Workqueues should be brought down after normal priority CPU notifiers.
357365758202STejun Heo  * This will be registered as low priority CPU notifier.
357465758202STejun Heo  */
35759fdf9b73SLai Jiangshan static int __cpuinit workqueue_cpu_down_callback(struct notifier_block *nfb,
357665758202STejun Heo 						 unsigned long action,
357765758202STejun Heo 						 void *hcpu)
357865758202STejun Heo {
3579d84ff051STejun Heo 	int cpu = (unsigned long)hcpu;
35808db25e78STejun Heo 	struct work_struct unbind_work;
35818db25e78STejun Heo 
358265758202STejun Heo 	switch (action & ~CPU_TASKS_FROZEN) {
358365758202STejun Heo 	case CPU_DOWN_PREPARE:
35848db25e78STejun Heo 		/* unbinding should happen on the local CPU */
3585706026c2STejun Heo 		INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
35867635d2fdSJoonsoo Kim 		queue_work_on(cpu, system_highpri_wq, &unbind_work);
35878db25e78STejun Heo 		flush_work(&unbind_work);
35888db25e78STejun Heo 		break;
358965758202STejun Heo 	}
359065758202STejun Heo 	return NOTIFY_OK;
359165758202STejun Heo }
359265758202STejun Heo 
35932d3854a3SRusty Russell #ifdef CONFIG_SMP
35948ccad40dSRusty Russell 
35952d3854a3SRusty Russell struct work_for_cpu {
3596ed48ece2STejun Heo 	struct work_struct work;
35972d3854a3SRusty Russell 	long (*fn)(void *);
35982d3854a3SRusty Russell 	void *arg;
35992d3854a3SRusty Russell 	long ret;
36002d3854a3SRusty Russell };
36012d3854a3SRusty Russell 
3602ed48ece2STejun Heo static void work_for_cpu_fn(struct work_struct *work)
36032d3854a3SRusty Russell {
3604ed48ece2STejun Heo 	struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
3605ed48ece2STejun Heo 
36062d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
36072d3854a3SRusty Russell }
36082d3854a3SRusty Russell 
36092d3854a3SRusty Russell /**
36102d3854a3SRusty Russell  * work_on_cpu - run a function in user context on a particular cpu
36112d3854a3SRusty Russell  * @cpu: the cpu to run on
36122d3854a3SRusty Russell  * @fn: the function to run
36132d3854a3SRusty Russell  * @arg: the function arg
36142d3854a3SRusty Russell  *
361531ad9081SRusty Russell  * This will return the value @fn returns.
361631ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
36176b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
36182d3854a3SRusty Russell  */
3619d84ff051STejun Heo long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
36202d3854a3SRusty Russell {
3621ed48ece2STejun Heo 	struct work_for_cpu wfc = { .fn = fn, .arg = arg };
36222d3854a3SRusty Russell 
3623ed48ece2STejun Heo 	INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
3624ed48ece2STejun Heo 	schedule_work_on(cpu, &wfc.work);
3625ed48ece2STejun Heo 	flush_work(&wfc.work);
36262d3854a3SRusty Russell 	return wfc.ret;
36272d3854a3SRusty Russell }
36282d3854a3SRusty Russell EXPORT_SYMBOL_GPL(work_on_cpu);
36292d3854a3SRusty Russell #endif /* CONFIG_SMP */
36302d3854a3SRusty Russell 
3631a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
3632e7577c50SRusty Russell 
3633a0a1a5fdSTejun Heo /**
3634a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
3635a0a1a5fdSTejun Heo  *
363658a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
363758a69cb4STejun Heo  * workqueues will queue new works to their frozen_works list instead of
3638706026c2STejun Heo  * pool->worklist.
3639a0a1a5fdSTejun Heo  *
3640a0a1a5fdSTejun Heo  * CONTEXT:
3641d565ed63STejun Heo  * Grabs and releases workqueue_lock and pool->lock's.
3642a0a1a5fdSTejun Heo  */
3643a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
3644a0a1a5fdSTejun Heo {
364517116969STejun Heo 	struct worker_pool *pool;
364624b8a847STejun Heo 	struct workqueue_struct *wq;
364724b8a847STejun Heo 	struct pool_workqueue *pwq;
364817116969STejun Heo 	int id;
3649a0a1a5fdSTejun Heo 
3650e98d5b16STejun Heo 	spin_lock_irq(&workqueue_lock);
3651a0a1a5fdSTejun Heo 
36526183c009STejun Heo 	WARN_ON_ONCE(workqueue_freezing);
3653a0a1a5fdSTejun Heo 	workqueue_freezing = true;
3654a0a1a5fdSTejun Heo 
365524b8a847STejun Heo 	/* set FREEZING */
365617116969STejun Heo 	for_each_pool(pool, id) {
3657e98d5b16STejun Heo 		spin_lock(&pool->lock);
365835b6bb63STejun Heo 		WARN_ON_ONCE(pool->flags & POOL_FREEZING);
365935b6bb63STejun Heo 		pool->flags |= POOL_FREEZING;
366024b8a847STejun Heo 		spin_unlock(&pool->lock);
36611da177e4SLinus Torvalds 	}
36628b03ae3cSTejun Heo 
366324b8a847STejun Heo 	/* suppress further executions by setting max_active to zero */
366424b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
366524b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
366624b8a847STejun Heo 			continue;
366724b8a847STejun Heo 
366824b8a847STejun Heo 		for_each_pwq(pwq, wq) {
366924b8a847STejun Heo 			spin_lock(&pwq->pool->lock);
367024b8a847STejun Heo 			pwq->max_active = 0;
367124b8a847STejun Heo 			spin_unlock(&pwq->pool->lock);
367224b8a847STejun Heo 		}
3673a1056305STejun Heo 	}
3674a0a1a5fdSTejun Heo 
3675e98d5b16STejun Heo 	spin_unlock_irq(&workqueue_lock);
3676a0a1a5fdSTejun Heo }
3677a0a1a5fdSTejun Heo 
3678a0a1a5fdSTejun Heo /**
367958a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
3680a0a1a5fdSTejun Heo  *
3681a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
3682a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
3683a0a1a5fdSTejun Heo  *
3684a0a1a5fdSTejun Heo  * CONTEXT:
3685a0a1a5fdSTejun Heo  * Grabs and releases workqueue_lock.
3686a0a1a5fdSTejun Heo  *
3687a0a1a5fdSTejun Heo  * RETURNS:
368858a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
368958a69cb4STejun Heo  * is complete.
3690a0a1a5fdSTejun Heo  */
3691a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
3692a0a1a5fdSTejun Heo {
3693a0a1a5fdSTejun Heo 	bool busy = false;
369424b8a847STejun Heo 	struct workqueue_struct *wq;
369524b8a847STejun Heo 	struct pool_workqueue *pwq;
3696a0a1a5fdSTejun Heo 
3697e98d5b16STejun Heo 	spin_lock_irq(&workqueue_lock);
3698a0a1a5fdSTejun Heo 
36996183c009STejun Heo 	WARN_ON_ONCE(!workqueue_freezing);
3700a0a1a5fdSTejun Heo 
370124b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
370224b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
370324b8a847STejun Heo 			continue;
3704a0a1a5fdSTejun Heo 		/*
3705a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
3706a0a1a5fdSTejun Heo 		 * to peek without lock.
3707a0a1a5fdSTejun Heo 		 */
370824b8a847STejun Heo 		for_each_pwq(pwq, wq) {
37096183c009STejun Heo 			WARN_ON_ONCE(pwq->nr_active < 0);
3710112202d9STejun Heo 			if (pwq->nr_active) {
3711a0a1a5fdSTejun Heo 				busy = true;
3712a0a1a5fdSTejun Heo 				goto out_unlock;
3713a0a1a5fdSTejun Heo 			}
3714a0a1a5fdSTejun Heo 		}
3715a0a1a5fdSTejun Heo 	}
3716a0a1a5fdSTejun Heo out_unlock:
3717e98d5b16STejun Heo 	spin_unlock_irq(&workqueue_lock);
3718a0a1a5fdSTejun Heo 	return busy;
3719a0a1a5fdSTejun Heo }
3720a0a1a5fdSTejun Heo 
3721a0a1a5fdSTejun Heo /**
3722a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
3723a0a1a5fdSTejun Heo  *
3724a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
3725706026c2STejun Heo  * frozen works are transferred to their respective pool worklists.
3726a0a1a5fdSTejun Heo  *
3727a0a1a5fdSTejun Heo  * CONTEXT:
3728d565ed63STejun Heo  * Grabs and releases workqueue_lock and pool->lock's.
3729a0a1a5fdSTejun Heo  */
3730a0a1a5fdSTejun Heo void thaw_workqueues(void)
3731a0a1a5fdSTejun Heo {
373224b8a847STejun Heo 	struct workqueue_struct *wq;
373324b8a847STejun Heo 	struct pool_workqueue *pwq;
373424b8a847STejun Heo 	struct worker_pool *pool;
373524b8a847STejun Heo 	int id;
3736a0a1a5fdSTejun Heo 
3737e98d5b16STejun Heo 	spin_lock_irq(&workqueue_lock);
3738a0a1a5fdSTejun Heo 
3739a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
3740a0a1a5fdSTejun Heo 		goto out_unlock;
3741a0a1a5fdSTejun Heo 
374224b8a847STejun Heo 	/* clear FREEZING */
374324b8a847STejun Heo 	for_each_pool(pool, id) {
3744e98d5b16STejun Heo 		spin_lock(&pool->lock);
374535b6bb63STejun Heo 		WARN_ON_ONCE(!(pool->flags & POOL_FREEZING));
374635b6bb63STejun Heo 		pool->flags &= ~POOL_FREEZING;
3747e98d5b16STejun Heo 		spin_unlock(&pool->lock);
3748d565ed63STejun Heo 	}
374924b8a847STejun Heo 
375024b8a847STejun Heo 	/* restore max_active and repopulate worklist */
375124b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
375224b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
375324b8a847STejun Heo 			continue;
375424b8a847STejun Heo 
375524b8a847STejun Heo 		for_each_pwq(pwq, wq) {
375624b8a847STejun Heo 			spin_lock(&pwq->pool->lock);
375724b8a847STejun Heo 			pwq_set_max_active(pwq, wq->saved_max_active);
375824b8a847STejun Heo 			spin_unlock(&pwq->pool->lock);
375924b8a847STejun Heo 		}
376024b8a847STejun Heo 	}
376124b8a847STejun Heo 
376224b8a847STejun Heo 	/* kick workers */
376324b8a847STejun Heo 	for_each_pool(pool, id) {
376424b8a847STejun Heo 		spin_lock(&pool->lock);
376524b8a847STejun Heo 		wake_up_worker(pool);
376624b8a847STejun Heo 		spin_unlock(&pool->lock);
3767a0a1a5fdSTejun Heo 	}
3768a0a1a5fdSTejun Heo 
3769a0a1a5fdSTejun Heo 	workqueue_freezing = false;
3770a0a1a5fdSTejun Heo out_unlock:
3771e98d5b16STejun Heo 	spin_unlock_irq(&workqueue_lock);
3772a0a1a5fdSTejun Heo }
3773a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
3774a0a1a5fdSTejun Heo 
37756ee0578bSSuresh Siddha static int __init init_workqueues(void)
37761da177e4SLinus Torvalds {
3777d84ff051STejun Heo 	int cpu;
3778c34056a3STejun Heo 
37797c3eed5cSTejun Heo 	/* make sure we have enough bits for OFFQ pool ID */
37807c3eed5cSTejun Heo 	BUILD_BUG_ON((1LU << (BITS_PER_LONG - WORK_OFFQ_POOL_SHIFT)) <
37816be19588SLai Jiangshan 		     WORK_CPU_END * NR_STD_WORKER_POOLS);
3782b5490077STejun Heo 
3783e904e6c2STejun Heo 	WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
3784e904e6c2STejun Heo 
3785e904e6c2STejun Heo 	pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
3786e904e6c2STejun Heo 
378765758202STejun Heo 	cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
3788a5b4e57dSLai Jiangshan 	hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
37898b03ae3cSTejun Heo 
3790706026c2STejun Heo 	/* initialize CPU pools */
3791706026c2STejun Heo 	for_each_wq_cpu(cpu) {
37924ce62e9eSTejun Heo 		struct worker_pool *pool;
37938b03ae3cSTejun Heo 
379438db41d9STejun Heo 		for_each_std_worker_pool(pool, cpu) {
3795d565ed63STejun Heo 			spin_lock_init(&pool->lock);
3796ec22ca5eSTejun Heo 			pool->cpu = cpu;
379724647570STejun Heo 			pool->flags |= POOL_DISASSOCIATED;
37984ce62e9eSTejun Heo 			INIT_LIST_HEAD(&pool->worklist);
37994ce62e9eSTejun Heo 			INIT_LIST_HEAD(&pool->idle_list);
3800c9e7cf27STejun Heo 			hash_init(pool->busy_hash);
3801e22bee78STejun Heo 
38024ce62e9eSTejun Heo 			init_timer_deferrable(&pool->idle_timer);
38034ce62e9eSTejun Heo 			pool->idle_timer.function = idle_worker_timeout;
38044ce62e9eSTejun Heo 			pool->idle_timer.data = (unsigned long)pool;
3805e22bee78STejun Heo 
3806706026c2STejun Heo 			setup_timer(&pool->mayday_timer, pool_mayday_timeout,
38074ce62e9eSTejun Heo 				    (unsigned long)pool);
38084ce62e9eSTejun Heo 
3809b2eb83d1SLai Jiangshan 			mutex_init(&pool->assoc_mutex);
38104ce62e9eSTejun Heo 			ida_init(&pool->worker_ida);
38119daf9e67STejun Heo 
38129daf9e67STejun Heo 			/* alloc pool ID */
38139daf9e67STejun Heo 			BUG_ON(worker_pool_assign_id(pool));
38144ce62e9eSTejun Heo 		}
38158b03ae3cSTejun Heo 	}
38168b03ae3cSTejun Heo 
3817e22bee78STejun Heo 	/* create the initial worker */
3818706026c2STejun Heo 	for_each_online_wq_cpu(cpu) {
38194ce62e9eSTejun Heo 		struct worker_pool *pool;
3820e22bee78STejun Heo 
382138db41d9STejun Heo 		for_each_std_worker_pool(pool, cpu) {
38224ce62e9eSTejun Heo 			struct worker *worker;
38234ce62e9eSTejun Heo 
382424647570STejun Heo 			if (cpu != WORK_CPU_UNBOUND)
382524647570STejun Heo 				pool->flags &= ~POOL_DISASSOCIATED;
382624647570STejun Heo 
3827bc2ae0f5STejun Heo 			worker = create_worker(pool);
3828e22bee78STejun Heo 			BUG_ON(!worker);
3829d565ed63STejun Heo 			spin_lock_irq(&pool->lock);
3830e22bee78STejun Heo 			start_worker(worker);
3831d565ed63STejun Heo 			spin_unlock_irq(&pool->lock);
3832e22bee78STejun Heo 		}
38334ce62e9eSTejun Heo 	}
3834e22bee78STejun Heo 
3835d320c038STejun Heo 	system_wq = alloc_workqueue("events", 0, 0);
38361aabe902SJoonsoo Kim 	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
3837d320c038STejun Heo 	system_long_wq = alloc_workqueue("events_long", 0, 0);
3838f3421797STejun Heo 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
3839f3421797STejun Heo 					    WQ_UNBOUND_MAX_ACTIVE);
384024d51addSTejun Heo 	system_freezable_wq = alloc_workqueue("events_freezable",
384124d51addSTejun Heo 					      WQ_FREEZABLE, 0);
38421aabe902SJoonsoo Kim 	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
3843ae930e0fSTejun Heo 	       !system_unbound_wq || !system_freezable_wq);
38446ee0578bSSuresh Siddha 	return 0;
38451da177e4SLinus Torvalds }
38466ee0578bSSuresh Siddha early_initcall(init_workqueues);
3847