xref: /linux-6.15/kernel/workqueue.c (revision 5bcab335)
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>
4429c91e99STejun Heo #include <linux/jhash.h>
4542f8570fSSasha Levin #include <linux/hashtable.h>
4676af4d93STejun Heo #include <linux/rculist.h>
47e22bee78STejun Heo 
48ea138446STejun Heo #include "workqueue_internal.h"
491da177e4SLinus Torvalds 
50c8e55f36STejun Heo enum {
51bc2ae0f5STejun Heo 	/*
5224647570STejun Heo 	 * worker_pool flags
53bc2ae0f5STejun Heo 	 *
5424647570STejun Heo 	 * A bound pool is either associated or disassociated with its CPU.
55bc2ae0f5STejun Heo 	 * While associated (!DISASSOCIATED), all workers are bound to the
56bc2ae0f5STejun Heo 	 * CPU and none has %WORKER_UNBOUND set and concurrency management
57bc2ae0f5STejun Heo 	 * is in effect.
58bc2ae0f5STejun Heo 	 *
59bc2ae0f5STejun Heo 	 * While DISASSOCIATED, the cpu may be offline and all workers have
60bc2ae0f5STejun Heo 	 * %WORKER_UNBOUND set and concurrency management disabled, and may
6124647570STejun Heo 	 * be executing on any CPU.  The pool behaves as an unbound one.
62bc2ae0f5STejun Heo 	 *
63bc3a1afcSTejun Heo 	 * Note that DISASSOCIATED should be flipped only while holding
64bc3a1afcSTejun Heo 	 * manager_mutex to avoid changing binding state while
6524647570STejun Heo 	 * create_worker() is in progress.
66bc2ae0f5STejun Heo 	 */
6711ebea50STejun Heo 	POOL_MANAGE_WORKERS	= 1 << 0,	/* need to manage 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 
8429c91e99STejun Heo 	UNBOUND_POOL_HASH_ORDER	= 6,		/* hashed by pool->attrs */
85c8e55f36STejun Heo 	BUSY_WORKER_HASH_ORDER	= 6,		/* 64 pointers */
86db7bccf4STejun Heo 
87e22bee78STejun Heo 	MAX_IDLE_WORKERS_RATIO	= 4,		/* 1/4 of busy can be idle */
88e22bee78STejun Heo 	IDLE_WORKER_TIMEOUT	= 300 * HZ,	/* keep idle ones for 5 mins */
89e22bee78STejun Heo 
903233cdbdSTejun Heo 	MAYDAY_INITIAL_TIMEOUT  = HZ / 100 >= 2 ? HZ / 100 : 2,
913233cdbdSTejun Heo 						/* call for help after 10ms
923233cdbdSTejun Heo 						   (min two ticks) */
93e22bee78STejun Heo 	MAYDAY_INTERVAL		= HZ / 10,	/* and then every 100ms */
94e22bee78STejun Heo 	CREATE_COOLDOWN		= HZ,		/* time to breath after fail */
951da177e4SLinus Torvalds 
961da177e4SLinus Torvalds 	/*
97e22bee78STejun Heo 	 * Rescue workers are used only on emergencies and shared by
98e22bee78STejun Heo 	 * all cpus.  Give -20.
99e22bee78STejun Heo 	 */
100e22bee78STejun Heo 	RESCUER_NICE_LEVEL	= -20,
1013270476aSTejun Heo 	HIGHPRI_NICE_LEVEL	= -20,
102c8e55f36STejun Heo };
103c8e55f36STejun Heo 
1041da177e4SLinus Torvalds /*
1054690c4abSTejun Heo  * Structure fields follow one of the following exclusion rules.
1064690c4abSTejun Heo  *
107e41e704bSTejun Heo  * I: Modifiable by initialization/destruction paths and read-only for
108e41e704bSTejun Heo  *    everyone else.
1094690c4abSTejun Heo  *
110e22bee78STejun Heo  * P: Preemption protected.  Disabling preemption is enough and should
111e22bee78STejun Heo  *    only be modified and accessed from the local cpu.
112e22bee78STejun Heo  *
113d565ed63STejun Heo  * L: pool->lock protected.  Access with pool->lock held.
1144690c4abSTejun Heo  *
115d565ed63STejun Heo  * X: During normal operation, modification requires pool->lock and should
116d565ed63STejun Heo  *    be done only from local cpu.  Either disabling preemption on local
117d565ed63STejun Heo  *    cpu or grabbing pool->lock is enough for read access.  If
118d565ed63STejun Heo  *    POOL_DISASSOCIATED is set, it's identical to L.
119e22bee78STejun Heo  *
12073f53c4aSTejun Heo  * F: wq->flush_mutex protected.
12173f53c4aSTejun Heo  *
122*5bcab335STejun Heo  * WQ: wq_mutex protected.
12376af4d93STejun Heo  *
124*5bcab335STejun Heo  * WR: wq_mutex protected for writes.  Sched-RCU protected for reads.
125*5bcab335STejun Heo  *
126*5bcab335STejun Heo  * W: workqueue_lock protected.
12775ccf595STejun Heo  *
12875ccf595STejun Heo  * FR: wq->flush_mutex and workqueue_lock protected for writes.  Sched-RCU
12975ccf595STejun Heo  *     protected for reads.
1304690c4abSTejun Heo  */
1314690c4abSTejun Heo 
1322eaebdb3STejun Heo /* struct worker is defined in workqueue_internal.h */
133c34056a3STejun Heo 
134bd7bdd43STejun Heo struct worker_pool {
135d565ed63STejun Heo 	spinlock_t		lock;		/* the pool lock */
136d84ff051STejun Heo 	int			cpu;		/* I: the associated cpu */
1379daf9e67STejun Heo 	int			id;		/* I: pool ID */
13811ebea50STejun Heo 	unsigned int		flags;		/* X: flags */
139bd7bdd43STejun Heo 
140bd7bdd43STejun Heo 	struct list_head	worklist;	/* L: list of pending works */
141bd7bdd43STejun Heo 	int			nr_workers;	/* L: total number of workers */
142ea1abd61SLai Jiangshan 
143ea1abd61SLai Jiangshan 	/* nr_idle includes the ones off idle_list for rebinding */
144bd7bdd43STejun Heo 	int			nr_idle;	/* L: currently idle ones */
145bd7bdd43STejun Heo 
146bd7bdd43STejun Heo 	struct list_head	idle_list;	/* X: list of idle workers */
147bd7bdd43STejun Heo 	struct timer_list	idle_timer;	/* L: worker idle timeout */
148bd7bdd43STejun Heo 	struct timer_list	mayday_timer;	/* L: SOS timer for workers */
149bd7bdd43STejun Heo 
150c5aa87bbSTejun Heo 	/* a workers is either on busy_hash or idle_list, or the manager */
151c9e7cf27STejun Heo 	DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
152c9e7cf27STejun Heo 						/* L: hash of busy workers */
153c9e7cf27STejun Heo 
154bc3a1afcSTejun Heo 	/* see manage_workers() for details on the two manager mutexes */
15534a06bd6STejun Heo 	struct mutex		manager_arb;	/* manager arbitration */
156bc3a1afcSTejun Heo 	struct mutex		manager_mutex;	/* manager exclusion */
157bd7bdd43STejun Heo 	struct ida		worker_ida;	/* L: for worker IDs */
158e19e397aSTejun Heo 
1597a4e344cSTejun Heo 	struct workqueue_attrs	*attrs;		/* I: worker attributes */
160*5bcab335STejun Heo 	struct hlist_node	hash_node;	/* WQ: unbound_pool_hash node */
161*5bcab335STejun Heo 	int			refcnt;		/* WQ: refcnt for unbound pools */
1627a4e344cSTejun Heo 
163e19e397aSTejun Heo 	/*
164e19e397aSTejun Heo 	 * The current concurrency level.  As it's likely to be accessed
165e19e397aSTejun Heo 	 * from other CPUs during try_to_wake_up(), put it in a separate
166e19e397aSTejun Heo 	 * cacheline.
167e19e397aSTejun Heo 	 */
168e19e397aSTejun Heo 	atomic_t		nr_running ____cacheline_aligned_in_smp;
16929c91e99STejun Heo 
17029c91e99STejun Heo 	/*
17129c91e99STejun Heo 	 * Destruction of pool is sched-RCU protected to allow dereferences
17229c91e99STejun Heo 	 * from get_work_pool().
17329c91e99STejun Heo 	 */
17429c91e99STejun Heo 	struct rcu_head		rcu;
1758b03ae3cSTejun Heo } ____cacheline_aligned_in_smp;
1768b03ae3cSTejun Heo 
1778b03ae3cSTejun Heo /*
178112202d9STejun Heo  * The per-pool workqueue.  While queued, the lower WORK_STRUCT_FLAG_BITS
179112202d9STejun Heo  * of work_struct->data are used for flags and the remaining high bits
180112202d9STejun Heo  * point to the pwq; thus, pwqs need to be aligned at two's power of the
181112202d9STejun Heo  * number of flag bits.
1821da177e4SLinus Torvalds  */
183112202d9STejun Heo struct pool_workqueue {
184bd7bdd43STejun Heo 	struct worker_pool	*pool;		/* I: the associated pool */
1854690c4abSTejun Heo 	struct workqueue_struct *wq;		/* I: the owning workqueue */
18673f53c4aSTejun Heo 	int			work_color;	/* L: current color */
18773f53c4aSTejun Heo 	int			flush_color;	/* L: flushing color */
1888864b4e5STejun Heo 	int			refcnt;		/* L: reference count */
18973f53c4aSTejun Heo 	int			nr_in_flight[WORK_NR_COLORS];
19073f53c4aSTejun Heo 						/* L: nr of in_flight works */
1911e19ffc6STejun Heo 	int			nr_active;	/* L: nr of active works */
192a0a1a5fdSTejun Heo 	int			max_active;	/* L: max active works */
1931e19ffc6STejun Heo 	struct list_head	delayed_works;	/* L: delayed works */
19475ccf595STejun Heo 	struct list_head	pwqs_node;	/* FR: node on wq->pwqs */
195493a1724STejun Heo 	struct list_head	mayday_node;	/* W: node on wq->maydays */
1968864b4e5STejun Heo 
1978864b4e5STejun Heo 	/*
1988864b4e5STejun Heo 	 * Release of unbound pwq is punted to system_wq.  See put_pwq()
1998864b4e5STejun Heo 	 * and pwq_unbound_release_workfn() for details.  pool_workqueue
2008864b4e5STejun Heo 	 * itself is also sched-RCU protected so that the first pwq can be
2018864b4e5STejun Heo 	 * determined without grabbing workqueue_lock.
2028864b4e5STejun Heo 	 */
2038864b4e5STejun Heo 	struct work_struct	unbound_release_work;
2048864b4e5STejun Heo 	struct rcu_head		rcu;
205e904e6c2STejun Heo } __aligned(1 << WORK_STRUCT_FLAG_BITS);
2061da177e4SLinus Torvalds 
2071da177e4SLinus Torvalds /*
20873f53c4aSTejun Heo  * Structure used to wait for workqueue flush.
20973f53c4aSTejun Heo  */
21073f53c4aSTejun Heo struct wq_flusher {
21173f53c4aSTejun Heo 	struct list_head	list;		/* F: list of flushers */
21273f53c4aSTejun Heo 	int			flush_color;	/* F: flush color waiting for */
21373f53c4aSTejun Heo 	struct completion	done;		/* flush completion */
21473f53c4aSTejun Heo };
2151da177e4SLinus Torvalds 
216226223abSTejun Heo struct wq_device;
217226223abSTejun Heo 
21873f53c4aSTejun Heo /*
219c5aa87bbSTejun Heo  * The externally visible workqueue.  It relays the issued work items to
220c5aa87bbSTejun Heo  * the appropriate worker_pool through its pool_workqueues.
2211da177e4SLinus Torvalds  */
2221da177e4SLinus Torvalds struct workqueue_struct {
223*5bcab335STejun Heo 	unsigned int		flags;		/* WQ: WQ_* flags */
224420c0ddbSTejun Heo 	struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwq's */
22575ccf595STejun Heo 	struct list_head	pwqs;		/* FR: all pwqs of this wq */
226*5bcab335STejun Heo 	struct list_head	list;		/* WQ: list of all workqueues */
22773f53c4aSTejun Heo 
22873f53c4aSTejun Heo 	struct mutex		flush_mutex;	/* protects wq flushing */
22973f53c4aSTejun Heo 	int			work_color;	/* F: current work color */
23073f53c4aSTejun Heo 	int			flush_color;	/* F: current flush color */
231112202d9STejun Heo 	atomic_t		nr_pwqs_to_flush; /* flush in progress */
23273f53c4aSTejun Heo 	struct wq_flusher	*first_flusher;	/* F: first flusher */
23373f53c4aSTejun Heo 	struct list_head	flusher_queue;	/* F: flush waiters */
23473f53c4aSTejun Heo 	struct list_head	flusher_overflow; /* F: flush overflow list */
23573f53c4aSTejun Heo 
236493a1724STejun Heo 	struct list_head	maydays;	/* W: pwqs requesting rescue */
237e22bee78STejun Heo 	struct worker		*rescuer;	/* I: rescue worker */
238e22bee78STejun Heo 
239*5bcab335STejun Heo 	int			nr_drainers;	/* WQ: drain in progress */
240112202d9STejun Heo 	int			saved_max_active; /* W: saved pwq max_active */
241226223abSTejun Heo 
242226223abSTejun Heo #ifdef CONFIG_SYSFS
243226223abSTejun Heo 	struct wq_device	*wq_dev;	/* I: for sysfs interface */
244226223abSTejun Heo #endif
2454e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
2464e6045f1SJohannes Berg 	struct lockdep_map	lockdep_map;
2474e6045f1SJohannes Berg #endif
248b196be89STejun Heo 	char			name[];		/* I: workqueue name */
2491da177e4SLinus Torvalds };
2501da177e4SLinus Torvalds 
251e904e6c2STejun Heo static struct kmem_cache *pwq_cache;
252e904e6c2STejun Heo 
253*5bcab335STejun Heo static DEFINE_MUTEX(wq_mutex);		/* protects workqueues and pools */
2547d19c5ceSTejun Heo static DEFINE_SPINLOCK(workqueue_lock);
255*5bcab335STejun Heo 
256*5bcab335STejun Heo static LIST_HEAD(workqueues);		/* WQ: list of all workqueues */
257*5bcab335STejun Heo static bool workqueue_freezing;		/* WQ: have wqs started freezing? */
2587d19c5ceSTejun Heo 
2597d19c5ceSTejun Heo /* the per-cpu worker pools */
2607d19c5ceSTejun Heo static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
2617d19c5ceSTejun Heo 				     cpu_worker_pools);
2627d19c5ceSTejun Heo 
263*5bcab335STejun Heo static DEFINE_IDR(worker_pool_idr);	/* WR: idr of all pools */
2647d19c5ceSTejun Heo 
265*5bcab335STejun Heo /* WQ: hash of all unbound pools keyed by pool->attrs */
26629c91e99STejun Heo static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
26729c91e99STejun Heo 
268c5aa87bbSTejun Heo /* I: attributes used when instantiating standard unbound pools on demand */
26929c91e99STejun Heo static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
27029c91e99STejun Heo 
271d320c038STejun Heo struct workqueue_struct *system_wq __read_mostly;
272d320c038STejun Heo EXPORT_SYMBOL_GPL(system_wq);
273044c782cSValentin Ilie struct workqueue_struct *system_highpri_wq __read_mostly;
2741aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
275044c782cSValentin Ilie struct workqueue_struct *system_long_wq __read_mostly;
276d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
277044c782cSValentin Ilie struct workqueue_struct *system_unbound_wq __read_mostly;
278f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
279044c782cSValentin Ilie struct workqueue_struct *system_freezable_wq __read_mostly;
28024d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
281d320c038STejun Heo 
2827d19c5ceSTejun Heo static int worker_thread(void *__worker);
2837d19c5ceSTejun Heo static void copy_workqueue_attrs(struct workqueue_attrs *to,
2847d19c5ceSTejun Heo 				 const struct workqueue_attrs *from);
2857d19c5ceSTejun Heo 
28697bd2347STejun Heo #define CREATE_TRACE_POINTS
28797bd2347STejun Heo #include <trace/events/workqueue.h>
28897bd2347STejun Heo 
289*5bcab335STejun Heo #define assert_rcu_or_wq_mutex()					\
290*5bcab335STejun Heo 	rcu_lockdep_assert(rcu_read_lock_sched_held() ||		\
291*5bcab335STejun Heo 			   lockdep_is_held(&wq_mutex),			\
292*5bcab335STejun Heo 			   "sched RCU or wq_mutex should be held")
293*5bcab335STejun Heo 
29476af4d93STejun Heo #define assert_rcu_or_wq_lock()						\
29576af4d93STejun Heo 	rcu_lockdep_assert(rcu_read_lock_sched_held() ||		\
29676af4d93STejun Heo 			   lockdep_is_held(&workqueue_lock),		\
29776af4d93STejun Heo 			   "sched RCU or workqueue lock should be held")
29876af4d93STejun Heo 
299f02ae73aSTejun Heo #define for_each_cpu_worker_pool(pool, cpu)				\
300f02ae73aSTejun Heo 	for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0];		\
301f02ae73aSTejun Heo 	     (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
3027a62c2c8STejun Heo 	     (pool)++)
3034ce62e9eSTejun Heo 
304b67bfe0dSSasha Levin #define for_each_busy_worker(worker, i, pool)				\
305b67bfe0dSSasha Levin 	hash_for_each(pool->busy_hash, i, worker, hentry)
306db7bccf4STejun Heo 
30749e3cf44STejun Heo /**
30817116969STejun Heo  * for_each_pool - iterate through all worker_pools in the system
30917116969STejun Heo  * @pool: iteration cursor
310611c92a0STejun Heo  * @pi: integer used for iteration
311fa1b54e6STejun Heo  *
312*5bcab335STejun Heo  * This must be called either with wq_mutex held or sched RCU read locked.
313*5bcab335STejun Heo  * If the pool needs to be used beyond the locking in effect, the caller is
314*5bcab335STejun Heo  * responsible for guaranteeing that the pool stays online.
315fa1b54e6STejun Heo  *
316fa1b54e6STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
317fa1b54e6STejun Heo  * ignored.
31817116969STejun Heo  */
319611c92a0STejun Heo #define for_each_pool(pool, pi)						\
320611c92a0STejun Heo 	idr_for_each_entry(&worker_pool_idr, pool, pi)			\
321*5bcab335STejun Heo 		if (({ assert_rcu_or_wq_mutex(); false; })) { }		\
322fa1b54e6STejun Heo 		else
32317116969STejun Heo 
32417116969STejun Heo /**
32549e3cf44STejun Heo  * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
32649e3cf44STejun Heo  * @pwq: iteration cursor
32749e3cf44STejun Heo  * @wq: the target workqueue
32876af4d93STejun Heo  *
32976af4d93STejun Heo  * This must be called either with workqueue_lock held or sched RCU read
33076af4d93STejun Heo  * locked.  If the pwq needs to be used beyond the locking in effect, the
33176af4d93STejun Heo  * caller is responsible for guaranteeing that the pwq stays online.
33276af4d93STejun Heo  *
33376af4d93STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
33476af4d93STejun Heo  * ignored.
33549e3cf44STejun Heo  */
33649e3cf44STejun Heo #define for_each_pwq(pwq, wq)						\
33776af4d93STejun Heo 	list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node)		\
33876af4d93STejun Heo 		if (({ assert_rcu_or_wq_lock(); false; })) { }		\
33976af4d93STejun Heo 		else
340f3421797STejun Heo 
341dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
342dc186ad7SThomas Gleixner 
343dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr;
344dc186ad7SThomas Gleixner 
34599777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
34699777288SStanislaw Gruszka {
34799777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
34899777288SStanislaw Gruszka }
34999777288SStanislaw Gruszka 
350dc186ad7SThomas Gleixner /*
351dc186ad7SThomas Gleixner  * fixup_init is called when:
352dc186ad7SThomas Gleixner  * - an active object is initialized
353dc186ad7SThomas Gleixner  */
354dc186ad7SThomas Gleixner static int work_fixup_init(void *addr, enum debug_obj_state state)
355dc186ad7SThomas Gleixner {
356dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
357dc186ad7SThomas Gleixner 
358dc186ad7SThomas Gleixner 	switch (state) {
359dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
360dc186ad7SThomas Gleixner 		cancel_work_sync(work);
361dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
362dc186ad7SThomas Gleixner 		return 1;
363dc186ad7SThomas Gleixner 	default:
364dc186ad7SThomas Gleixner 		return 0;
365dc186ad7SThomas Gleixner 	}
366dc186ad7SThomas Gleixner }
367dc186ad7SThomas Gleixner 
368dc186ad7SThomas Gleixner /*
369dc186ad7SThomas Gleixner  * fixup_activate is called when:
370dc186ad7SThomas Gleixner  * - an active object is activated
371dc186ad7SThomas Gleixner  * - an unknown object is activated (might be a statically initialized object)
372dc186ad7SThomas Gleixner  */
373dc186ad7SThomas Gleixner static int work_fixup_activate(void *addr, enum debug_obj_state state)
374dc186ad7SThomas Gleixner {
375dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
376dc186ad7SThomas Gleixner 
377dc186ad7SThomas Gleixner 	switch (state) {
378dc186ad7SThomas Gleixner 
379dc186ad7SThomas Gleixner 	case ODEBUG_STATE_NOTAVAILABLE:
380dc186ad7SThomas Gleixner 		/*
381dc186ad7SThomas Gleixner 		 * This is not really a fixup. The work struct was
382dc186ad7SThomas Gleixner 		 * statically initialized. We just make sure that it
383dc186ad7SThomas Gleixner 		 * is tracked in the object tracker.
384dc186ad7SThomas Gleixner 		 */
38522df02bbSTejun Heo 		if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
386dc186ad7SThomas Gleixner 			debug_object_init(work, &work_debug_descr);
387dc186ad7SThomas Gleixner 			debug_object_activate(work, &work_debug_descr);
388dc186ad7SThomas Gleixner 			return 0;
389dc186ad7SThomas Gleixner 		}
390dc186ad7SThomas Gleixner 		WARN_ON_ONCE(1);
391dc186ad7SThomas Gleixner 		return 0;
392dc186ad7SThomas Gleixner 
393dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
394dc186ad7SThomas Gleixner 		WARN_ON(1);
395dc186ad7SThomas Gleixner 
396dc186ad7SThomas Gleixner 	default:
397dc186ad7SThomas Gleixner 		return 0;
398dc186ad7SThomas Gleixner 	}
399dc186ad7SThomas Gleixner }
400dc186ad7SThomas Gleixner 
401dc186ad7SThomas Gleixner /*
402dc186ad7SThomas Gleixner  * fixup_free is called when:
403dc186ad7SThomas Gleixner  * - an active object is freed
404dc186ad7SThomas Gleixner  */
405dc186ad7SThomas Gleixner static int work_fixup_free(void *addr, enum debug_obj_state state)
406dc186ad7SThomas Gleixner {
407dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
408dc186ad7SThomas Gleixner 
409dc186ad7SThomas Gleixner 	switch (state) {
410dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
411dc186ad7SThomas Gleixner 		cancel_work_sync(work);
412dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
413dc186ad7SThomas Gleixner 		return 1;
414dc186ad7SThomas Gleixner 	default:
415dc186ad7SThomas Gleixner 		return 0;
416dc186ad7SThomas Gleixner 	}
417dc186ad7SThomas Gleixner }
418dc186ad7SThomas Gleixner 
419dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr = {
420dc186ad7SThomas Gleixner 	.name		= "work_struct",
42199777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
422dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
423dc186ad7SThomas Gleixner 	.fixup_activate	= work_fixup_activate,
424dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
425dc186ad7SThomas Gleixner };
426dc186ad7SThomas Gleixner 
427dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
428dc186ad7SThomas Gleixner {
429dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
430dc186ad7SThomas Gleixner }
431dc186ad7SThomas Gleixner 
432dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
433dc186ad7SThomas Gleixner {
434dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
435dc186ad7SThomas Gleixner }
436dc186ad7SThomas Gleixner 
437dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
438dc186ad7SThomas Gleixner {
439dc186ad7SThomas Gleixner 	if (onstack)
440dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
441dc186ad7SThomas Gleixner 	else
442dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
443dc186ad7SThomas Gleixner }
444dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
445dc186ad7SThomas Gleixner 
446dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
447dc186ad7SThomas Gleixner {
448dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
449dc186ad7SThomas Gleixner }
450dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
451dc186ad7SThomas Gleixner 
452dc186ad7SThomas Gleixner #else
453dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
454dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
455dc186ad7SThomas Gleixner #endif
456dc186ad7SThomas Gleixner 
4579daf9e67STejun Heo /* allocate ID and assign it to @pool */
4589daf9e67STejun Heo static int worker_pool_assign_id(struct worker_pool *pool)
4599daf9e67STejun Heo {
4609daf9e67STejun Heo 	int ret;
4619daf9e67STejun Heo 
462*5bcab335STejun Heo 	lockdep_assert_held(&wq_mutex);
463*5bcab335STejun Heo 
464fa1b54e6STejun Heo 	do {
465fa1b54e6STejun Heo 		if (!idr_pre_get(&worker_pool_idr, GFP_KERNEL))
466fa1b54e6STejun Heo 			return -ENOMEM;
4679daf9e67STejun Heo 		ret = idr_get_new(&worker_pool_idr, pool, &pool->id);
468fa1b54e6STejun Heo 	} while (ret == -EAGAIN);
4699daf9e67STejun Heo 
4709daf9e67STejun Heo 	return ret;
4719daf9e67STejun Heo }
4729daf9e67STejun Heo 
47376af4d93STejun Heo /**
47476af4d93STejun Heo  * first_pwq - return the first pool_workqueue of the specified workqueue
47576af4d93STejun Heo  * @wq: the target workqueue
47676af4d93STejun Heo  *
47776af4d93STejun Heo  * This must be called either with workqueue_lock held or sched RCU read
47876af4d93STejun Heo  * locked.  If the pwq needs to be used beyond the locking in effect, the
47976af4d93STejun Heo  * caller is responsible for guaranteeing that the pwq stays online.
48076af4d93STejun Heo  */
4817fb98ea7STejun Heo static struct pool_workqueue *first_pwq(struct workqueue_struct *wq)
482a848e3b6SOleg Nesterov {
48376af4d93STejun Heo 	assert_rcu_or_wq_lock();
48476af4d93STejun Heo 	return list_first_or_null_rcu(&wq->pwqs, struct pool_workqueue,
48576af4d93STejun Heo 				      pwqs_node);
486f3421797STejun Heo }
487a848e3b6SOleg Nesterov 
48873f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
48973f53c4aSTejun Heo {
49073f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
49173f53c4aSTejun Heo }
49273f53c4aSTejun Heo 
49373f53c4aSTejun Heo static int get_work_color(struct work_struct *work)
49473f53c4aSTejun Heo {
49573f53c4aSTejun Heo 	return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
49673f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
49773f53c4aSTejun Heo }
49873f53c4aSTejun Heo 
49973f53c4aSTejun Heo static int work_next_color(int color)
50073f53c4aSTejun Heo {
50173f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
502b1f4ec17SOleg Nesterov }
503b1f4ec17SOleg Nesterov 
5044594bf15SDavid Howells /*
505112202d9STejun Heo  * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
506112202d9STejun Heo  * contain the pointer to the queued pwq.  Once execution starts, the flag
5077c3eed5cSTejun Heo  * is cleared and the high bits contain OFFQ flags and pool ID.
5087a22ad75STejun Heo  *
509112202d9STejun Heo  * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
510112202d9STejun Heo  * and clear_work_data() can be used to set the pwq, pool or clear
511bbb68dfaSTejun Heo  * work->data.  These functions should only be called while the work is
512bbb68dfaSTejun Heo  * owned - ie. while the PENDING bit is set.
5137a22ad75STejun Heo  *
514112202d9STejun Heo  * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
5157c3eed5cSTejun Heo  * corresponding to a work.  Pool is available once the work has been
516112202d9STejun Heo  * queued anywhere after initialization until it is sync canceled.  pwq is
5177c3eed5cSTejun Heo  * available only while the work item is queued.
518bbb68dfaSTejun Heo  *
519bbb68dfaSTejun Heo  * %WORK_OFFQ_CANCELING is used to mark a work item which is being
520bbb68dfaSTejun Heo  * canceled.  While being canceled, a work item may have its PENDING set
521bbb68dfaSTejun Heo  * but stay off timer and worklist for arbitrarily long and nobody should
522bbb68dfaSTejun Heo  * try to steal the PENDING bit.
5234594bf15SDavid Howells  */
5247a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
5257a22ad75STejun Heo 				 unsigned long flags)
5267a22ad75STejun Heo {
5276183c009STejun Heo 	WARN_ON_ONCE(!work_pending(work));
5287a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
5297a22ad75STejun Heo }
5307a22ad75STejun Heo 
531112202d9STejun Heo static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
5324690c4abSTejun Heo 			 unsigned long extra_flags)
533365970a1SDavid Howells {
534112202d9STejun Heo 	set_work_data(work, (unsigned long)pwq,
535112202d9STejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
536365970a1SDavid Howells }
537365970a1SDavid Howells 
5384468a00fSLai Jiangshan static void set_work_pool_and_keep_pending(struct work_struct *work,
5394468a00fSLai Jiangshan 					   int pool_id)
5404468a00fSLai Jiangshan {
5414468a00fSLai Jiangshan 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
5424468a00fSLai Jiangshan 		      WORK_STRUCT_PENDING);
5434468a00fSLai Jiangshan }
5444468a00fSLai Jiangshan 
5457c3eed5cSTejun Heo static void set_work_pool_and_clear_pending(struct work_struct *work,
5467c3eed5cSTejun Heo 					    int pool_id)
5474d707b9fSOleg Nesterov {
54823657bb1STejun Heo 	/*
54923657bb1STejun Heo 	 * The following wmb is paired with the implied mb in
55023657bb1STejun Heo 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
55123657bb1STejun Heo 	 * here are visible to and precede any updates by the next PENDING
55223657bb1STejun Heo 	 * owner.
55323657bb1STejun Heo 	 */
55423657bb1STejun Heo 	smp_wmb();
5557c3eed5cSTejun Heo 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
5564d707b9fSOleg Nesterov }
5574d707b9fSOleg Nesterov 
5587a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
559365970a1SDavid Howells {
5607c3eed5cSTejun Heo 	smp_wmb();	/* see set_work_pool_and_clear_pending() */
5617c3eed5cSTejun Heo 	set_work_data(work, WORK_STRUCT_NO_POOL, 0);
5627a22ad75STejun Heo }
5637a22ad75STejun Heo 
564112202d9STejun Heo static struct pool_workqueue *get_work_pwq(struct work_struct *work)
5657a22ad75STejun Heo {
566e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
5677a22ad75STejun Heo 
568112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
569e120153dSTejun Heo 		return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
570e120153dSTejun Heo 	else
571e120153dSTejun Heo 		return NULL;
5727a22ad75STejun Heo }
5737a22ad75STejun Heo 
5747c3eed5cSTejun Heo /**
5757c3eed5cSTejun Heo  * get_work_pool - return the worker_pool a given work was associated with
5767c3eed5cSTejun Heo  * @work: the work item of interest
5777c3eed5cSTejun Heo  *
5787c3eed5cSTejun Heo  * Return the worker_pool @work was last associated with.  %NULL if none.
579fa1b54e6STejun Heo  *
580*5bcab335STejun Heo  * Pools are created and destroyed under wq_mutex, and allows read access
581*5bcab335STejun Heo  * under sched-RCU read lock.  As such, this function should be called
582*5bcab335STejun Heo  * under wq_mutex or with preemption disabled.
583fa1b54e6STejun Heo  *
584fa1b54e6STejun Heo  * All fields of the returned pool are accessible as long as the above
585fa1b54e6STejun Heo  * mentioned locking is in effect.  If the returned pool needs to be used
586fa1b54e6STejun Heo  * beyond the critical section, the caller is responsible for ensuring the
587fa1b54e6STejun Heo  * returned pool is and stays online.
5887c3eed5cSTejun Heo  */
5897c3eed5cSTejun Heo static struct worker_pool *get_work_pool(struct work_struct *work)
5907a22ad75STejun Heo {
591e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
5927c3eed5cSTejun Heo 	int pool_id;
5937a22ad75STejun Heo 
594*5bcab335STejun Heo 	assert_rcu_or_wq_mutex();
595fa1b54e6STejun Heo 
596112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
597112202d9STejun Heo 		return ((struct pool_workqueue *)
5987c3eed5cSTejun Heo 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool;
5997a22ad75STejun Heo 
6007c3eed5cSTejun Heo 	pool_id = data >> WORK_OFFQ_POOL_SHIFT;
6017c3eed5cSTejun Heo 	if (pool_id == WORK_OFFQ_POOL_NONE)
6027a22ad75STejun Heo 		return NULL;
6037a22ad75STejun Heo 
604fa1b54e6STejun Heo 	return idr_find(&worker_pool_idr, pool_id);
6057c3eed5cSTejun Heo }
6067c3eed5cSTejun Heo 
6077c3eed5cSTejun Heo /**
6087c3eed5cSTejun Heo  * get_work_pool_id - return the worker pool ID a given work is associated with
6097c3eed5cSTejun Heo  * @work: the work item of interest
6107c3eed5cSTejun Heo  *
6117c3eed5cSTejun Heo  * Return the worker_pool ID @work was last associated with.
6127c3eed5cSTejun Heo  * %WORK_OFFQ_POOL_NONE if none.
6137c3eed5cSTejun Heo  */
6147c3eed5cSTejun Heo static int get_work_pool_id(struct work_struct *work)
6157c3eed5cSTejun Heo {
61654d5b7d0SLai Jiangshan 	unsigned long data = atomic_long_read(&work->data);
6177c3eed5cSTejun Heo 
618112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
619112202d9STejun Heo 		return ((struct pool_workqueue *)
62054d5b7d0SLai Jiangshan 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
62154d5b7d0SLai Jiangshan 
62254d5b7d0SLai Jiangshan 	return data >> WORK_OFFQ_POOL_SHIFT;
6237c3eed5cSTejun Heo }
6247c3eed5cSTejun Heo 
625bbb68dfaSTejun Heo static void mark_work_canceling(struct work_struct *work)
626bbb68dfaSTejun Heo {
6277c3eed5cSTejun Heo 	unsigned long pool_id = get_work_pool_id(work);
628bbb68dfaSTejun Heo 
6297c3eed5cSTejun Heo 	pool_id <<= WORK_OFFQ_POOL_SHIFT;
6307c3eed5cSTejun Heo 	set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
631bbb68dfaSTejun Heo }
632bbb68dfaSTejun Heo 
633bbb68dfaSTejun Heo static bool work_is_canceling(struct work_struct *work)
634bbb68dfaSTejun Heo {
635bbb68dfaSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
636bbb68dfaSTejun Heo 
637112202d9STejun Heo 	return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
638bbb68dfaSTejun Heo }
639bbb68dfaSTejun Heo 
640e22bee78STejun Heo /*
6413270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
6423270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
643d565ed63STejun Heo  * they're being called with pool->lock held.
644e22bee78STejun Heo  */
645e22bee78STejun Heo 
64663d95a91STejun Heo static bool __need_more_worker(struct worker_pool *pool)
647649027d7STejun Heo {
648e19e397aSTejun Heo 	return !atomic_read(&pool->nr_running);
649649027d7STejun Heo }
650649027d7STejun Heo 
651e22bee78STejun Heo /*
652e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
653e22bee78STejun Heo  * running workers.
654974271c4STejun Heo  *
655974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
656706026c2STejun Heo  * function will always return %true for unbound pools as long as the
657974271c4STejun Heo  * worklist isn't empty.
658e22bee78STejun Heo  */
65963d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
660e22bee78STejun Heo {
66163d95a91STejun Heo 	return !list_empty(&pool->worklist) && __need_more_worker(pool);
662e22bee78STejun Heo }
663e22bee78STejun Heo 
664e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
66563d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
666e22bee78STejun Heo {
66763d95a91STejun Heo 	return pool->nr_idle;
668e22bee78STejun Heo }
669e22bee78STejun Heo 
670e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
67163d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
672e22bee78STejun Heo {
673e19e397aSTejun Heo 	return !list_empty(&pool->worklist) &&
674e19e397aSTejun Heo 		atomic_read(&pool->nr_running) <= 1;
675e22bee78STejun Heo }
676e22bee78STejun Heo 
677e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
67863d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
679e22bee78STejun Heo {
68063d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
681e22bee78STejun Heo }
682e22bee78STejun Heo 
683e22bee78STejun Heo /* Do I need to be the manager? */
68463d95a91STejun Heo static bool need_to_manage_workers(struct worker_pool *pool)
685e22bee78STejun Heo {
68663d95a91STejun Heo 	return need_to_create_worker(pool) ||
68711ebea50STejun Heo 		(pool->flags & POOL_MANAGE_WORKERS);
688e22bee78STejun Heo }
689e22bee78STejun Heo 
690e22bee78STejun Heo /* Do we have too many workers and should some go away? */
69163d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
692e22bee78STejun Heo {
69334a06bd6STejun Heo 	bool managing = mutex_is_locked(&pool->manager_arb);
69463d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
69563d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
696e22bee78STejun Heo 
697ea1abd61SLai Jiangshan 	/*
698ea1abd61SLai Jiangshan 	 * nr_idle and idle_list may disagree if idle rebinding is in
699ea1abd61SLai Jiangshan 	 * progress.  Never return %true if idle_list is empty.
700ea1abd61SLai Jiangshan 	 */
701ea1abd61SLai Jiangshan 	if (list_empty(&pool->idle_list))
702ea1abd61SLai Jiangshan 		return false;
703ea1abd61SLai Jiangshan 
704e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
705e22bee78STejun Heo }
706e22bee78STejun Heo 
707e22bee78STejun Heo /*
708e22bee78STejun Heo  * Wake up functions.
709e22bee78STejun Heo  */
710e22bee78STejun Heo 
7117e11629dSTejun Heo /* Return the first worker.  Safe with preemption disabled */
71263d95a91STejun Heo static struct worker *first_worker(struct worker_pool *pool)
7137e11629dSTejun Heo {
71463d95a91STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
7157e11629dSTejun Heo 		return NULL;
7167e11629dSTejun Heo 
71763d95a91STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
7187e11629dSTejun Heo }
7197e11629dSTejun Heo 
7207e11629dSTejun Heo /**
7217e11629dSTejun Heo  * wake_up_worker - wake up an idle worker
72263d95a91STejun Heo  * @pool: worker pool to wake worker from
7237e11629dSTejun Heo  *
72463d95a91STejun Heo  * Wake up the first idle worker of @pool.
7257e11629dSTejun Heo  *
7267e11629dSTejun Heo  * CONTEXT:
727d565ed63STejun Heo  * spin_lock_irq(pool->lock).
7287e11629dSTejun Heo  */
72963d95a91STejun Heo static void wake_up_worker(struct worker_pool *pool)
7307e11629dSTejun Heo {
73163d95a91STejun Heo 	struct worker *worker = first_worker(pool);
7327e11629dSTejun Heo 
7337e11629dSTejun Heo 	if (likely(worker))
7347e11629dSTejun Heo 		wake_up_process(worker->task);
7357e11629dSTejun Heo }
7367e11629dSTejun Heo 
7374690c4abSTejun Heo /**
738e22bee78STejun Heo  * wq_worker_waking_up - a worker is waking up
739e22bee78STejun Heo  * @task: task waking up
740e22bee78STejun Heo  * @cpu: CPU @task is waking up to
741e22bee78STejun Heo  *
742e22bee78STejun Heo  * This function is called during try_to_wake_up() when a worker is
743e22bee78STejun Heo  * being awoken.
744e22bee78STejun Heo  *
745e22bee78STejun Heo  * CONTEXT:
746e22bee78STejun Heo  * spin_lock_irq(rq->lock)
747e22bee78STejun Heo  */
748d84ff051STejun Heo void wq_worker_waking_up(struct task_struct *task, int cpu)
749e22bee78STejun Heo {
750e22bee78STejun Heo 	struct worker *worker = kthread_data(task);
751e22bee78STejun Heo 
75236576000SJoonsoo Kim 	if (!(worker->flags & WORKER_NOT_RUNNING)) {
753ec22ca5eSTejun Heo 		WARN_ON_ONCE(worker->pool->cpu != cpu);
754e19e397aSTejun Heo 		atomic_inc(&worker->pool->nr_running);
755e22bee78STejun Heo 	}
75636576000SJoonsoo Kim }
757e22bee78STejun Heo 
758e22bee78STejun Heo /**
759e22bee78STejun Heo  * wq_worker_sleeping - a worker is going to sleep
760e22bee78STejun Heo  * @task: task going to sleep
761e22bee78STejun Heo  * @cpu: CPU in question, must be the current CPU number
762e22bee78STejun Heo  *
763e22bee78STejun Heo  * This function is called during schedule() when a busy worker is
764e22bee78STejun Heo  * going to sleep.  Worker on the same cpu can be woken up by
765e22bee78STejun Heo  * returning pointer to its task.
766e22bee78STejun Heo  *
767e22bee78STejun Heo  * CONTEXT:
768e22bee78STejun Heo  * spin_lock_irq(rq->lock)
769e22bee78STejun Heo  *
770e22bee78STejun Heo  * RETURNS:
771e22bee78STejun Heo  * Worker task on @cpu to wake up, %NULL if none.
772e22bee78STejun Heo  */
773d84ff051STejun Heo struct task_struct *wq_worker_sleeping(struct task_struct *task, int cpu)
774e22bee78STejun Heo {
775e22bee78STejun Heo 	struct worker *worker = kthread_data(task), *to_wakeup = NULL;
776111c225aSTejun Heo 	struct worker_pool *pool;
777e22bee78STejun Heo 
778111c225aSTejun Heo 	/*
779111c225aSTejun Heo 	 * Rescuers, which may not have all the fields set up like normal
780111c225aSTejun Heo 	 * workers, also reach here, let's not access anything before
781111c225aSTejun Heo 	 * checking NOT_RUNNING.
782111c225aSTejun Heo 	 */
7832d64672eSSteven Rostedt 	if (worker->flags & WORKER_NOT_RUNNING)
784e22bee78STejun Heo 		return NULL;
785e22bee78STejun Heo 
786111c225aSTejun Heo 	pool = worker->pool;
787111c225aSTejun Heo 
788e22bee78STejun Heo 	/* this can only happen on the local cpu */
7896183c009STejun Heo 	if (WARN_ON_ONCE(cpu != raw_smp_processor_id()))
7906183c009STejun Heo 		return NULL;
791e22bee78STejun Heo 
792e22bee78STejun Heo 	/*
793e22bee78STejun Heo 	 * The counterpart of the following dec_and_test, implied mb,
794e22bee78STejun Heo 	 * worklist not empty test sequence is in insert_work().
795e22bee78STejun Heo 	 * Please read comment there.
796e22bee78STejun Heo 	 *
797628c78e7STejun Heo 	 * NOT_RUNNING is clear.  This means that we're bound to and
798628c78e7STejun Heo 	 * running on the local cpu w/ rq lock held and preemption
799628c78e7STejun Heo 	 * disabled, which in turn means that none else could be
800d565ed63STejun Heo 	 * manipulating idle_list, so dereferencing idle_list without pool
801628c78e7STejun Heo 	 * lock is safe.
802e22bee78STejun Heo 	 */
803e19e397aSTejun Heo 	if (atomic_dec_and_test(&pool->nr_running) &&
804e19e397aSTejun Heo 	    !list_empty(&pool->worklist))
80563d95a91STejun Heo 		to_wakeup = first_worker(pool);
806e22bee78STejun Heo 	return to_wakeup ? to_wakeup->task : NULL;
807e22bee78STejun Heo }
808e22bee78STejun Heo 
809e22bee78STejun Heo /**
810e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
811cb444766STejun Heo  * @worker: self
812d302f017STejun Heo  * @flags: flags to set
813d302f017STejun Heo  * @wakeup: wakeup an idle worker if necessary
814d302f017STejun Heo  *
815e22bee78STejun Heo  * Set @flags in @worker->flags and adjust nr_running accordingly.  If
816e22bee78STejun Heo  * nr_running becomes zero and @wakeup is %true, an idle worker is
817e22bee78STejun Heo  * woken up.
818d302f017STejun Heo  *
819cb444766STejun Heo  * CONTEXT:
820d565ed63STejun Heo  * spin_lock_irq(pool->lock)
821d302f017STejun Heo  */
822d302f017STejun Heo static inline void worker_set_flags(struct worker *worker, unsigned int flags,
823d302f017STejun Heo 				    bool wakeup)
824d302f017STejun Heo {
825bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
826e22bee78STejun Heo 
827cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
828cb444766STejun Heo 
829e22bee78STejun Heo 	/*
830e22bee78STejun Heo 	 * If transitioning into NOT_RUNNING, adjust nr_running and
831e22bee78STejun Heo 	 * wake up an idle worker as necessary if requested by
832e22bee78STejun Heo 	 * @wakeup.
833e22bee78STejun Heo 	 */
834e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
835e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
836e22bee78STejun Heo 		if (wakeup) {
837e19e397aSTejun Heo 			if (atomic_dec_and_test(&pool->nr_running) &&
838bd7bdd43STejun Heo 			    !list_empty(&pool->worklist))
83963d95a91STejun Heo 				wake_up_worker(pool);
840e22bee78STejun Heo 		} else
841e19e397aSTejun Heo 			atomic_dec(&pool->nr_running);
842e22bee78STejun Heo 	}
843e22bee78STejun Heo 
844d302f017STejun Heo 	worker->flags |= flags;
845d302f017STejun Heo }
846d302f017STejun Heo 
847d302f017STejun Heo /**
848e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
849cb444766STejun Heo  * @worker: self
850d302f017STejun Heo  * @flags: flags to clear
851d302f017STejun Heo  *
852e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
853d302f017STejun Heo  *
854cb444766STejun Heo  * CONTEXT:
855d565ed63STejun Heo  * spin_lock_irq(pool->lock)
856d302f017STejun Heo  */
857d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
858d302f017STejun Heo {
85963d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
860e22bee78STejun Heo 	unsigned int oflags = worker->flags;
861e22bee78STejun Heo 
862cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
863cb444766STejun Heo 
864d302f017STejun Heo 	worker->flags &= ~flags;
865e22bee78STejun Heo 
86642c025f3STejun Heo 	/*
86742c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
86842c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
86942c025f3STejun Heo 	 * of multiple flags, not a single flag.
87042c025f3STejun Heo 	 */
871e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
872e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
873e19e397aSTejun Heo 			atomic_inc(&pool->nr_running);
874d302f017STejun Heo }
875d302f017STejun Heo 
876d302f017STejun Heo /**
8778cca0eeaSTejun Heo  * find_worker_executing_work - find worker which is executing a work
878c9e7cf27STejun Heo  * @pool: pool of interest
8798cca0eeaSTejun Heo  * @work: work to find worker for
8808cca0eeaSTejun Heo  *
881c9e7cf27STejun Heo  * Find a worker which is executing @work on @pool by searching
882c9e7cf27STejun Heo  * @pool->busy_hash which is keyed by the address of @work.  For a worker
883a2c1c57bSTejun Heo  * to match, its current execution should match the address of @work and
884a2c1c57bSTejun Heo  * its work function.  This is to avoid unwanted dependency between
885a2c1c57bSTejun Heo  * unrelated work executions through a work item being recycled while still
886a2c1c57bSTejun Heo  * being executed.
887a2c1c57bSTejun Heo  *
888a2c1c57bSTejun Heo  * This is a bit tricky.  A work item may be freed once its execution
889a2c1c57bSTejun Heo  * starts and nothing prevents the freed area from being recycled for
890a2c1c57bSTejun Heo  * another work item.  If the same work item address ends up being reused
891a2c1c57bSTejun Heo  * before the original execution finishes, workqueue will identify the
892a2c1c57bSTejun Heo  * recycled work item as currently executing and make it wait until the
893a2c1c57bSTejun Heo  * current execution finishes, introducing an unwanted dependency.
894a2c1c57bSTejun Heo  *
895c5aa87bbSTejun Heo  * This function checks the work item address and work function to avoid
896c5aa87bbSTejun Heo  * false positives.  Note that this isn't complete as one may construct a
897c5aa87bbSTejun Heo  * work function which can introduce dependency onto itself through a
898c5aa87bbSTejun Heo  * recycled work item.  Well, if somebody wants to shoot oneself in the
899c5aa87bbSTejun Heo  * foot that badly, there's only so much we can do, and if such deadlock
900c5aa87bbSTejun Heo  * actually occurs, it should be easy to locate the culprit work function.
9018cca0eeaSTejun Heo  *
9028cca0eeaSTejun Heo  * CONTEXT:
903d565ed63STejun Heo  * spin_lock_irq(pool->lock).
9048cca0eeaSTejun Heo  *
9058cca0eeaSTejun Heo  * RETURNS:
9068cca0eeaSTejun Heo  * Pointer to worker which is executing @work if found, NULL
9078cca0eeaSTejun Heo  * otherwise.
9088cca0eeaSTejun Heo  */
909c9e7cf27STejun Heo static struct worker *find_worker_executing_work(struct worker_pool *pool,
9108cca0eeaSTejun Heo 						 struct work_struct *work)
9118cca0eeaSTejun Heo {
91242f8570fSSasha Levin 	struct worker *worker;
91342f8570fSSasha Levin 
914b67bfe0dSSasha Levin 	hash_for_each_possible(pool->busy_hash, worker, hentry,
915a2c1c57bSTejun Heo 			       (unsigned long)work)
916a2c1c57bSTejun Heo 		if (worker->current_work == work &&
917a2c1c57bSTejun Heo 		    worker->current_func == work->func)
91842f8570fSSasha Levin 			return worker;
91942f8570fSSasha Levin 
92042f8570fSSasha Levin 	return NULL;
9218cca0eeaSTejun Heo }
9228cca0eeaSTejun Heo 
9238cca0eeaSTejun Heo /**
924bf4ede01STejun Heo  * move_linked_works - move linked works to a list
925bf4ede01STejun Heo  * @work: start of series of works to be scheduled
926bf4ede01STejun Heo  * @head: target list to append @work to
927bf4ede01STejun Heo  * @nextp: out paramter for nested worklist walking
928bf4ede01STejun Heo  *
929bf4ede01STejun Heo  * Schedule linked works starting from @work to @head.  Work series to
930bf4ede01STejun Heo  * be scheduled starts at @work and includes any consecutive work with
931bf4ede01STejun Heo  * WORK_STRUCT_LINKED set in its predecessor.
932bf4ede01STejun Heo  *
933bf4ede01STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of
934bf4ede01STejun Heo  * the last scheduled work.  This allows move_linked_works() to be
935bf4ede01STejun Heo  * nested inside outer list_for_each_entry_safe().
936bf4ede01STejun Heo  *
937bf4ede01STejun Heo  * CONTEXT:
938d565ed63STejun Heo  * spin_lock_irq(pool->lock).
939bf4ede01STejun Heo  */
940bf4ede01STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
941bf4ede01STejun Heo 			      struct work_struct **nextp)
942bf4ede01STejun Heo {
943bf4ede01STejun Heo 	struct work_struct *n;
944bf4ede01STejun Heo 
945bf4ede01STejun Heo 	/*
946bf4ede01STejun Heo 	 * Linked worklist will always end before the end of the list,
947bf4ede01STejun Heo 	 * use NULL for list head.
948bf4ede01STejun Heo 	 */
949bf4ede01STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
950bf4ede01STejun Heo 		list_move_tail(&work->entry, head);
951bf4ede01STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
952bf4ede01STejun Heo 			break;
953bf4ede01STejun Heo 	}
954bf4ede01STejun Heo 
955bf4ede01STejun Heo 	/*
956bf4ede01STejun Heo 	 * If we're already inside safe list traversal and have moved
957bf4ede01STejun Heo 	 * multiple works to the scheduled queue, the next position
958bf4ede01STejun Heo 	 * needs to be updated.
959bf4ede01STejun Heo 	 */
960bf4ede01STejun Heo 	if (nextp)
961bf4ede01STejun Heo 		*nextp = n;
962bf4ede01STejun Heo }
963bf4ede01STejun Heo 
9648864b4e5STejun Heo /**
9658864b4e5STejun Heo  * get_pwq - get an extra reference on the specified pool_workqueue
9668864b4e5STejun Heo  * @pwq: pool_workqueue to get
9678864b4e5STejun Heo  *
9688864b4e5STejun Heo  * Obtain an extra reference on @pwq.  The caller should guarantee that
9698864b4e5STejun Heo  * @pwq has positive refcnt and be holding the matching pool->lock.
9708864b4e5STejun Heo  */
9718864b4e5STejun Heo static void get_pwq(struct pool_workqueue *pwq)
9728864b4e5STejun Heo {
9738864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
9748864b4e5STejun Heo 	WARN_ON_ONCE(pwq->refcnt <= 0);
9758864b4e5STejun Heo 	pwq->refcnt++;
9768864b4e5STejun Heo }
9778864b4e5STejun Heo 
9788864b4e5STejun Heo /**
9798864b4e5STejun Heo  * put_pwq - put a pool_workqueue reference
9808864b4e5STejun Heo  * @pwq: pool_workqueue to put
9818864b4e5STejun Heo  *
9828864b4e5STejun Heo  * Drop a reference of @pwq.  If its refcnt reaches zero, schedule its
9838864b4e5STejun Heo  * destruction.  The caller should be holding the matching pool->lock.
9848864b4e5STejun Heo  */
9858864b4e5STejun Heo static void put_pwq(struct pool_workqueue *pwq)
9868864b4e5STejun Heo {
9878864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
9888864b4e5STejun Heo 	if (likely(--pwq->refcnt))
9898864b4e5STejun Heo 		return;
9908864b4e5STejun Heo 	if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
9918864b4e5STejun Heo 		return;
9928864b4e5STejun Heo 	/*
9938864b4e5STejun Heo 	 * @pwq can't be released under pool->lock, bounce to
9948864b4e5STejun Heo 	 * pwq_unbound_release_workfn().  This never recurses on the same
9958864b4e5STejun Heo 	 * pool->lock as this path is taken only for unbound workqueues and
9968864b4e5STejun Heo 	 * the release work item is scheduled on a per-cpu workqueue.  To
9978864b4e5STejun Heo 	 * avoid lockdep warning, unbound pool->locks are given lockdep
9988864b4e5STejun Heo 	 * subclass of 1 in get_unbound_pool().
9998864b4e5STejun Heo 	 */
10008864b4e5STejun Heo 	schedule_work(&pwq->unbound_release_work);
10018864b4e5STejun Heo }
10028864b4e5STejun Heo 
1003112202d9STejun Heo static void pwq_activate_delayed_work(struct work_struct *work)
1004bf4ede01STejun Heo {
1005112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1006bf4ede01STejun Heo 
1007bf4ede01STejun Heo 	trace_workqueue_activate_work(work);
1008112202d9STejun Heo 	move_linked_works(work, &pwq->pool->worklist, NULL);
1009bf4ede01STejun Heo 	__clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
1010112202d9STejun Heo 	pwq->nr_active++;
1011bf4ede01STejun Heo }
1012bf4ede01STejun Heo 
1013112202d9STejun Heo static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
10143aa62497SLai Jiangshan {
1015112202d9STejun Heo 	struct work_struct *work = list_first_entry(&pwq->delayed_works,
10163aa62497SLai Jiangshan 						    struct work_struct, entry);
10173aa62497SLai Jiangshan 
1018112202d9STejun Heo 	pwq_activate_delayed_work(work);
10193aa62497SLai Jiangshan }
10203aa62497SLai Jiangshan 
1021bf4ede01STejun Heo /**
1022112202d9STejun Heo  * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1023112202d9STejun Heo  * @pwq: pwq of interest
1024bf4ede01STejun Heo  * @color: color of work which left the queue
1025bf4ede01STejun Heo  *
1026bf4ede01STejun Heo  * A work either has completed or is removed from pending queue,
1027112202d9STejun Heo  * decrement nr_in_flight of its pwq and handle workqueue flushing.
1028bf4ede01STejun Heo  *
1029bf4ede01STejun Heo  * CONTEXT:
1030d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1031bf4ede01STejun Heo  */
1032112202d9STejun Heo static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
1033bf4ede01STejun Heo {
10348864b4e5STejun Heo 	/* uncolored work items don't participate in flushing or nr_active */
1035bf4ede01STejun Heo 	if (color == WORK_NO_COLOR)
10368864b4e5STejun Heo 		goto out_put;
1037bf4ede01STejun Heo 
1038112202d9STejun Heo 	pwq->nr_in_flight[color]--;
1039bf4ede01STejun Heo 
1040112202d9STejun Heo 	pwq->nr_active--;
1041112202d9STejun Heo 	if (!list_empty(&pwq->delayed_works)) {
1042bf4ede01STejun Heo 		/* one down, submit a delayed one */
1043112202d9STejun Heo 		if (pwq->nr_active < pwq->max_active)
1044112202d9STejun Heo 			pwq_activate_first_delayed(pwq);
1045bf4ede01STejun Heo 	}
1046bf4ede01STejun Heo 
1047bf4ede01STejun Heo 	/* is flush in progress and are we at the flushing tip? */
1048112202d9STejun Heo 	if (likely(pwq->flush_color != color))
10498864b4e5STejun Heo 		goto out_put;
1050bf4ede01STejun Heo 
1051bf4ede01STejun Heo 	/* are there still in-flight works? */
1052112202d9STejun Heo 	if (pwq->nr_in_flight[color])
10538864b4e5STejun Heo 		goto out_put;
1054bf4ede01STejun Heo 
1055112202d9STejun Heo 	/* this pwq is done, clear flush_color */
1056112202d9STejun Heo 	pwq->flush_color = -1;
1057bf4ede01STejun Heo 
1058bf4ede01STejun Heo 	/*
1059112202d9STejun Heo 	 * If this was the last pwq, wake up the first flusher.  It
1060bf4ede01STejun Heo 	 * will handle the rest.
1061bf4ede01STejun Heo 	 */
1062112202d9STejun Heo 	if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1063112202d9STejun Heo 		complete(&pwq->wq->first_flusher->done);
10648864b4e5STejun Heo out_put:
10658864b4e5STejun Heo 	put_pwq(pwq);
1066bf4ede01STejun Heo }
1067bf4ede01STejun Heo 
106836e227d2STejun Heo /**
1069bbb68dfaSTejun Heo  * try_to_grab_pending - steal work item from worklist and disable irq
107036e227d2STejun Heo  * @work: work item to steal
107136e227d2STejun Heo  * @is_dwork: @work is a delayed_work
1072bbb68dfaSTejun Heo  * @flags: place to store irq state
107336e227d2STejun Heo  *
107436e227d2STejun Heo  * Try to grab PENDING bit of @work.  This function can handle @work in any
107536e227d2STejun Heo  * stable state - idle, on timer or on worklist.  Return values are
107636e227d2STejun Heo  *
107736e227d2STejun Heo  *  1		if @work was pending and we successfully stole PENDING
107836e227d2STejun Heo  *  0		if @work was idle and we claimed PENDING
107936e227d2STejun Heo  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
1080bbb68dfaSTejun Heo  *  -ENOENT	if someone else is canceling @work, this state may persist
1081bbb68dfaSTejun Heo  *		for arbitrarily long
108236e227d2STejun Heo  *
1083bbb68dfaSTejun Heo  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
1084e0aecdd8STejun Heo  * interrupted while holding PENDING and @work off queue, irq must be
1085e0aecdd8STejun Heo  * disabled on entry.  This, combined with delayed_work->timer being
1086e0aecdd8STejun Heo  * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1087bbb68dfaSTejun Heo  *
1088bbb68dfaSTejun Heo  * On successful return, >= 0, irq is disabled and the caller is
1089bbb68dfaSTejun Heo  * responsible for releasing it using local_irq_restore(*@flags).
1090bbb68dfaSTejun Heo  *
1091e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
1092bf4ede01STejun Heo  */
1093bbb68dfaSTejun Heo static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1094bbb68dfaSTejun Heo 			       unsigned long *flags)
1095bf4ede01STejun Heo {
1096d565ed63STejun Heo 	struct worker_pool *pool;
1097112202d9STejun Heo 	struct pool_workqueue *pwq;
1098bf4ede01STejun Heo 
1099bbb68dfaSTejun Heo 	local_irq_save(*flags);
1100bbb68dfaSTejun Heo 
110136e227d2STejun Heo 	/* try to steal the timer if it exists */
110236e227d2STejun Heo 	if (is_dwork) {
110336e227d2STejun Heo 		struct delayed_work *dwork = to_delayed_work(work);
110436e227d2STejun Heo 
1105e0aecdd8STejun Heo 		/*
1106e0aecdd8STejun Heo 		 * dwork->timer is irqsafe.  If del_timer() fails, it's
1107e0aecdd8STejun Heo 		 * guaranteed that the timer is not queued anywhere and not
1108e0aecdd8STejun Heo 		 * running on the local CPU.
1109e0aecdd8STejun Heo 		 */
111036e227d2STejun Heo 		if (likely(del_timer(&dwork->timer)))
111136e227d2STejun Heo 			return 1;
111236e227d2STejun Heo 	}
111336e227d2STejun Heo 
111436e227d2STejun Heo 	/* try to claim PENDING the normal way */
1115bf4ede01STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1116bf4ede01STejun Heo 		return 0;
1117bf4ede01STejun Heo 
1118bf4ede01STejun Heo 	/*
1119bf4ede01STejun Heo 	 * The queueing is in progress, or it is already queued. Try to
1120bf4ede01STejun Heo 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1121bf4ede01STejun Heo 	 */
1122d565ed63STejun Heo 	pool = get_work_pool(work);
1123d565ed63STejun Heo 	if (!pool)
1124bbb68dfaSTejun Heo 		goto fail;
1125bf4ede01STejun Heo 
1126d565ed63STejun Heo 	spin_lock(&pool->lock);
1127bf4ede01STejun Heo 	/*
1128112202d9STejun Heo 	 * work->data is guaranteed to point to pwq only while the work
1129112202d9STejun Heo 	 * item is queued on pwq->wq, and both updating work->data to point
1130112202d9STejun Heo 	 * to pwq on queueing and to pool on dequeueing are done under
1131112202d9STejun Heo 	 * pwq->pool->lock.  This in turn guarantees that, if work->data
1132112202d9STejun Heo 	 * points to pwq which is associated with a locked pool, the work
11330b3dae68SLai Jiangshan 	 * item is currently queued on that pool.
1134bf4ede01STejun Heo 	 */
1135112202d9STejun Heo 	pwq = get_work_pwq(work);
1136112202d9STejun Heo 	if (pwq && pwq->pool == pool) {
1137bf4ede01STejun Heo 		debug_work_deactivate(work);
11383aa62497SLai Jiangshan 
11393aa62497SLai Jiangshan 		/*
114016062836STejun Heo 		 * A delayed work item cannot be grabbed directly because
114116062836STejun Heo 		 * it might have linked NO_COLOR work items which, if left
1142112202d9STejun Heo 		 * on the delayed_list, will confuse pwq->nr_active
114316062836STejun Heo 		 * management later on and cause stall.  Make sure the work
114416062836STejun Heo 		 * item is activated before grabbing.
11453aa62497SLai Jiangshan 		 */
11463aa62497SLai Jiangshan 		if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1147112202d9STejun Heo 			pwq_activate_delayed_work(work);
11483aa62497SLai Jiangshan 
1149bf4ede01STejun Heo 		list_del_init(&work->entry);
1150112202d9STejun Heo 		pwq_dec_nr_in_flight(get_work_pwq(work), get_work_color(work));
115136e227d2STejun Heo 
1152112202d9STejun Heo 		/* work->data points to pwq iff queued, point to pool */
11534468a00fSLai Jiangshan 		set_work_pool_and_keep_pending(work, pool->id);
11544468a00fSLai Jiangshan 
1155d565ed63STejun Heo 		spin_unlock(&pool->lock);
115636e227d2STejun Heo 		return 1;
1157bf4ede01STejun Heo 	}
1158d565ed63STejun Heo 	spin_unlock(&pool->lock);
1159bbb68dfaSTejun Heo fail:
1160bbb68dfaSTejun Heo 	local_irq_restore(*flags);
1161bbb68dfaSTejun Heo 	if (work_is_canceling(work))
1162bbb68dfaSTejun Heo 		return -ENOENT;
1163bbb68dfaSTejun Heo 	cpu_relax();
116436e227d2STejun Heo 	return -EAGAIN;
1165bf4ede01STejun Heo }
1166bf4ede01STejun Heo 
1167bf4ede01STejun Heo /**
1168706026c2STejun Heo  * insert_work - insert a work into a pool
1169112202d9STejun Heo  * @pwq: pwq @work belongs to
11704690c4abSTejun Heo  * @work: work to insert
11714690c4abSTejun Heo  * @head: insertion point
11724690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
11734690c4abSTejun Heo  *
1174112202d9STejun Heo  * Insert @work which belongs to @pwq after @head.  @extra_flags is or'd to
1175706026c2STejun Heo  * work_struct flags.
11764690c4abSTejun Heo  *
11774690c4abSTejun Heo  * CONTEXT:
1178d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1179365970a1SDavid Howells  */
1180112202d9STejun Heo static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1181112202d9STejun Heo 			struct list_head *head, unsigned int extra_flags)
1182b89deed3SOleg Nesterov {
1183112202d9STejun Heo 	struct worker_pool *pool = pwq->pool;
1184e1d8aa9fSFrederic Weisbecker 
11854690c4abSTejun Heo 	/* we own @work, set data and link */
1186112202d9STejun Heo 	set_work_pwq(work, pwq, extra_flags);
11871a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
11888864b4e5STejun Heo 	get_pwq(pwq);
1189e22bee78STejun Heo 
1190e22bee78STejun Heo 	/*
1191c5aa87bbSTejun Heo 	 * Ensure either wq_worker_sleeping() sees the above
1192c5aa87bbSTejun Heo 	 * list_add_tail() or we see zero nr_running to avoid workers lying
1193c5aa87bbSTejun Heo 	 * around lazily while there are works to be processed.
1194e22bee78STejun Heo 	 */
1195e22bee78STejun Heo 	smp_mb();
1196e22bee78STejun Heo 
119763d95a91STejun Heo 	if (__need_more_worker(pool))
119863d95a91STejun Heo 		wake_up_worker(pool);
1199b89deed3SOleg Nesterov }
1200b89deed3SOleg Nesterov 
1201c8efcc25STejun Heo /*
1202c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
12038d03ecfeSTejun Heo  * same workqueue.
1204c8efcc25STejun Heo  */
1205c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
1206c8efcc25STejun Heo {
1207c8efcc25STejun Heo 	struct worker *worker;
1208c8efcc25STejun Heo 
12098d03ecfeSTejun Heo 	worker = current_wq_worker();
1210c8efcc25STejun Heo 	/*
12118d03ecfeSTejun Heo 	 * Return %true iff I'm a worker execuing a work item on @wq.  If
12128d03ecfeSTejun Heo 	 * I'm @worker, it's safe to dereference it without locking.
1213c8efcc25STejun Heo 	 */
1214112202d9STejun Heo 	return worker && worker->current_pwq->wq == wq;
1215c8efcc25STejun Heo }
1216c8efcc25STejun Heo 
1217d84ff051STejun Heo static void __queue_work(int cpu, struct workqueue_struct *wq,
12181da177e4SLinus Torvalds 			 struct work_struct *work)
12191da177e4SLinus Torvalds {
1220112202d9STejun Heo 	struct pool_workqueue *pwq;
1221c9178087STejun Heo 	struct worker_pool *last_pool;
12221e19ffc6STejun Heo 	struct list_head *worklist;
12238a2e8e5dSTejun Heo 	unsigned int work_flags;
1224b75cac93SJoonsoo Kim 	unsigned int req_cpu = cpu;
12258930cabaSTejun Heo 
12268930cabaSTejun Heo 	/*
12278930cabaSTejun Heo 	 * While a work item is PENDING && off queue, a task trying to
12288930cabaSTejun Heo 	 * steal the PENDING will busy-loop waiting for it to either get
12298930cabaSTejun Heo 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
12308930cabaSTejun Heo 	 * happen with IRQ disabled.
12318930cabaSTejun Heo 	 */
12328930cabaSTejun Heo 	WARN_ON_ONCE(!irqs_disabled());
12331da177e4SLinus Torvalds 
1234dc186ad7SThomas Gleixner 	debug_work_activate(work);
12351e19ffc6STejun Heo 
1236c8efcc25STejun Heo 	/* if dying, only works from the same workqueue are allowed */
1237618b01ebSTejun Heo 	if (unlikely(wq->flags & __WQ_DRAINING) &&
1238c8efcc25STejun Heo 	    WARN_ON_ONCE(!is_chained_work(wq)))
1239e41e704bSTejun Heo 		return;
12409e8cd2f5STejun Heo retry:
1241c9178087STejun Heo 	/* pwq which will be used unless @work is executing elsewhere */
1242c7fc77f7STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
124357469821STejun Heo 		if (cpu == WORK_CPU_UNBOUND)
1244f3421797STejun Heo 			cpu = raw_smp_processor_id();
1245c9178087STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1246c9178087STejun Heo 	} else {
1247c9178087STejun Heo 		pwq = first_pwq(wq);
1248c9178087STejun Heo 	}
1249f3421797STejun Heo 
125018aa9effSTejun Heo 	/*
1251c9178087STejun Heo 	 * If @work was previously on a different pool, it might still be
1252c9178087STejun Heo 	 * running there, in which case the work needs to be queued on that
1253c9178087STejun Heo 	 * pool to guarantee non-reentrancy.
125418aa9effSTejun Heo 	 */
1255c9e7cf27STejun Heo 	last_pool = get_work_pool(work);
1256112202d9STejun Heo 	if (last_pool && last_pool != pwq->pool) {
125718aa9effSTejun Heo 		struct worker *worker;
125818aa9effSTejun Heo 
1259d565ed63STejun Heo 		spin_lock(&last_pool->lock);
126018aa9effSTejun Heo 
1261c9e7cf27STejun Heo 		worker = find_worker_executing_work(last_pool, work);
126218aa9effSTejun Heo 
1263112202d9STejun Heo 		if (worker && worker->current_pwq->wq == wq) {
1264c9178087STejun Heo 			pwq = worker->current_pwq;
12658594fadeSLai Jiangshan 		} else {
126618aa9effSTejun Heo 			/* meh... not running there, queue here */
1267d565ed63STejun Heo 			spin_unlock(&last_pool->lock);
1268112202d9STejun Heo 			spin_lock(&pwq->pool->lock);
126918aa9effSTejun Heo 		}
12708930cabaSTejun Heo 	} else {
1271112202d9STejun Heo 		spin_lock(&pwq->pool->lock);
12728930cabaSTejun Heo 	}
1273502ca9d8STejun Heo 
12749e8cd2f5STejun Heo 	/*
12759e8cd2f5STejun Heo 	 * pwq is determined and locked.  For unbound pools, we could have
12769e8cd2f5STejun Heo 	 * raced with pwq release and it could already be dead.  If its
12779e8cd2f5STejun Heo 	 * refcnt is zero, repeat pwq selection.  Note that pwqs never die
12789e8cd2f5STejun Heo 	 * without another pwq replacing it as the first pwq or while a
12799e8cd2f5STejun Heo 	 * work item is executing on it, so the retying is guaranteed to
12809e8cd2f5STejun Heo 	 * make forward-progress.
12819e8cd2f5STejun Heo 	 */
12829e8cd2f5STejun Heo 	if (unlikely(!pwq->refcnt)) {
12839e8cd2f5STejun Heo 		if (wq->flags & WQ_UNBOUND) {
12849e8cd2f5STejun Heo 			spin_unlock(&pwq->pool->lock);
12859e8cd2f5STejun Heo 			cpu_relax();
12869e8cd2f5STejun Heo 			goto retry;
12879e8cd2f5STejun Heo 		}
12889e8cd2f5STejun Heo 		/* oops */
12899e8cd2f5STejun Heo 		WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
12909e8cd2f5STejun Heo 			  wq->name, cpu);
12919e8cd2f5STejun Heo 	}
12929e8cd2f5STejun Heo 
1293112202d9STejun Heo 	/* pwq determined, queue */
1294112202d9STejun Heo 	trace_workqueue_queue_work(req_cpu, pwq, work);
1295502ca9d8STejun Heo 
1296f5b2552bSDan Carpenter 	if (WARN_ON(!list_empty(&work->entry))) {
1297112202d9STejun Heo 		spin_unlock(&pwq->pool->lock);
1298f5b2552bSDan Carpenter 		return;
1299f5b2552bSDan Carpenter 	}
13001e19ffc6STejun Heo 
1301112202d9STejun Heo 	pwq->nr_in_flight[pwq->work_color]++;
1302112202d9STejun Heo 	work_flags = work_color_to_flags(pwq->work_color);
13031e19ffc6STejun Heo 
1304112202d9STejun Heo 	if (likely(pwq->nr_active < pwq->max_active)) {
1305cdadf009STejun Heo 		trace_workqueue_activate_work(work);
1306112202d9STejun Heo 		pwq->nr_active++;
1307112202d9STejun Heo 		worklist = &pwq->pool->worklist;
13088a2e8e5dSTejun Heo 	} else {
13098a2e8e5dSTejun Heo 		work_flags |= WORK_STRUCT_DELAYED;
1310112202d9STejun Heo 		worklist = &pwq->delayed_works;
13118a2e8e5dSTejun Heo 	}
13121e19ffc6STejun Heo 
1313112202d9STejun Heo 	insert_work(pwq, work, worklist, work_flags);
13141e19ffc6STejun Heo 
1315112202d9STejun Heo 	spin_unlock(&pwq->pool->lock);
13161da177e4SLinus Torvalds }
13171da177e4SLinus Torvalds 
13180fcb78c2SRolf Eike Beer /**
1319c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
1320c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
1321c1a220e7SZhang Rui  * @wq: workqueue to use
1322c1a220e7SZhang Rui  * @work: work to queue
1323c1a220e7SZhang Rui  *
1324d4283e93STejun Heo  * Returns %false if @work was already on a queue, %true otherwise.
1325c1a220e7SZhang Rui  *
1326c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
1327c1a220e7SZhang Rui  * can't go away.
1328c1a220e7SZhang Rui  */
1329d4283e93STejun Heo bool queue_work_on(int cpu, struct workqueue_struct *wq,
1330d4283e93STejun Heo 		   struct work_struct *work)
1331c1a220e7SZhang Rui {
1332d4283e93STejun Heo 	bool ret = false;
13338930cabaSTejun Heo 	unsigned long flags;
13348930cabaSTejun Heo 
13358930cabaSTejun Heo 	local_irq_save(flags);
1336c1a220e7SZhang Rui 
133722df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
13384690c4abSTejun Heo 		__queue_work(cpu, wq, work);
1339d4283e93STejun Heo 		ret = true;
1340c1a220e7SZhang Rui 	}
13418930cabaSTejun Heo 
13428930cabaSTejun Heo 	local_irq_restore(flags);
1343c1a220e7SZhang Rui 	return ret;
1344c1a220e7SZhang Rui }
1345c1a220e7SZhang Rui EXPORT_SYMBOL_GPL(queue_work_on);
1346c1a220e7SZhang Rui 
1347d8e794dfSTejun Heo void delayed_work_timer_fn(unsigned long __data)
13481da177e4SLinus Torvalds {
134952bad64dSDavid Howells 	struct delayed_work *dwork = (struct delayed_work *)__data;
13501da177e4SLinus Torvalds 
1351e0aecdd8STejun Heo 	/* should have been called from irqsafe timer with irq already off */
135260c057bcSLai Jiangshan 	__queue_work(dwork->cpu, dwork->wq, &dwork->work);
13531da177e4SLinus Torvalds }
13541438ade5SKonstantin Khlebnikov EXPORT_SYMBOL(delayed_work_timer_fn);
13551da177e4SLinus Torvalds 
13567beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
135752bad64dSDavid Howells 				struct delayed_work *dwork, unsigned long delay)
13581da177e4SLinus Torvalds {
13597beb2edfSTejun Heo 	struct timer_list *timer = &dwork->timer;
13607beb2edfSTejun Heo 	struct work_struct *work = &dwork->work;
13611da177e4SLinus Torvalds 
13627beb2edfSTejun Heo 	WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
13637beb2edfSTejun Heo 		     timer->data != (unsigned long)dwork);
1364fc4b514fSTejun Heo 	WARN_ON_ONCE(timer_pending(timer));
1365fc4b514fSTejun Heo 	WARN_ON_ONCE(!list_empty(&work->entry));
13667beb2edfSTejun Heo 
13678852aac2STejun Heo 	/*
13688852aac2STejun Heo 	 * If @delay is 0, queue @dwork->work immediately.  This is for
13698852aac2STejun Heo 	 * both optimization and correctness.  The earliest @timer can
13708852aac2STejun Heo 	 * expire is on the closest next tick and delayed_work users depend
13718852aac2STejun Heo 	 * on that there's no such delay when @delay is 0.
13728852aac2STejun Heo 	 */
13738852aac2STejun Heo 	if (!delay) {
13748852aac2STejun Heo 		__queue_work(cpu, wq, &dwork->work);
13758852aac2STejun Heo 		return;
13768852aac2STejun Heo 	}
13778852aac2STejun Heo 
13787beb2edfSTejun Heo 	timer_stats_timer_set_start_info(&dwork->timer);
13797beb2edfSTejun Heo 
138060c057bcSLai Jiangshan 	dwork->wq = wq;
13811265057fSTejun Heo 	dwork->cpu = cpu;
13827beb2edfSTejun Heo 	timer->expires = jiffies + delay;
13837beb2edfSTejun Heo 
13847beb2edfSTejun Heo 	if (unlikely(cpu != WORK_CPU_UNBOUND))
13857beb2edfSTejun Heo 		add_timer_on(timer, cpu);
13867beb2edfSTejun Heo 	else
13877beb2edfSTejun Heo 		add_timer(timer);
13887beb2edfSTejun Heo }
13891da177e4SLinus Torvalds 
13900fcb78c2SRolf Eike Beer /**
13910fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
13920fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
13930fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1394af9997e4SRandy Dunlap  * @dwork: work to queue
13950fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
13960fcb78c2SRolf Eike Beer  *
1397715f1300STejun Heo  * Returns %false if @work was already on a queue, %true otherwise.  If
1398715f1300STejun Heo  * @delay is zero and @dwork is idle, it will be scheduled for immediate
1399715f1300STejun Heo  * execution.
14000fcb78c2SRolf Eike Beer  */
1401d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
140252bad64dSDavid Howells 			   struct delayed_work *dwork, unsigned long delay)
14037a6bc1cdSVenkatesh Pallipadi {
140452bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
1405d4283e93STejun Heo 	bool ret = false;
14068930cabaSTejun Heo 	unsigned long flags;
14078930cabaSTejun Heo 
14088930cabaSTejun Heo 	/* read the comment in __queue_work() */
14098930cabaSTejun Heo 	local_irq_save(flags);
14107a6bc1cdSVenkatesh Pallipadi 
141122df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
14127beb2edfSTejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
1413d4283e93STejun Heo 		ret = true;
14147a6bc1cdSVenkatesh Pallipadi 	}
14158930cabaSTejun Heo 
14168930cabaSTejun Heo 	local_irq_restore(flags);
14177a6bc1cdSVenkatesh Pallipadi 	return ret;
14187a6bc1cdSVenkatesh Pallipadi }
1419ae90dd5dSDave Jones EXPORT_SYMBOL_GPL(queue_delayed_work_on);
14201da177e4SLinus Torvalds 
1421c8e55f36STejun Heo /**
14228376fe22STejun Heo  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
14238376fe22STejun Heo  * @cpu: CPU number to execute work on
14248376fe22STejun Heo  * @wq: workqueue to use
14258376fe22STejun Heo  * @dwork: work to queue
14268376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
14278376fe22STejun Heo  *
14288376fe22STejun Heo  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
14298376fe22STejun Heo  * modify @dwork's timer so that it expires after @delay.  If @delay is
14308376fe22STejun Heo  * zero, @work is guaranteed to be scheduled immediately regardless of its
14318376fe22STejun Heo  * current state.
14328376fe22STejun Heo  *
14338376fe22STejun Heo  * Returns %false if @dwork was idle and queued, %true if @dwork was
14348376fe22STejun Heo  * pending and its timer was modified.
14358376fe22STejun Heo  *
1436e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
14378376fe22STejun Heo  * See try_to_grab_pending() for details.
14388376fe22STejun Heo  */
14398376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
14408376fe22STejun Heo 			 struct delayed_work *dwork, unsigned long delay)
14418376fe22STejun Heo {
14428376fe22STejun Heo 	unsigned long flags;
14438376fe22STejun Heo 	int ret;
14448376fe22STejun Heo 
14458376fe22STejun Heo 	do {
14468376fe22STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
14478376fe22STejun Heo 	} while (unlikely(ret == -EAGAIN));
14488376fe22STejun Heo 
14498376fe22STejun Heo 	if (likely(ret >= 0)) {
14508376fe22STejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
14518376fe22STejun Heo 		local_irq_restore(flags);
14528376fe22STejun Heo 	}
14538376fe22STejun Heo 
14548376fe22STejun Heo 	/* -ENOENT from try_to_grab_pending() becomes %true */
14558376fe22STejun Heo 	return ret;
14568376fe22STejun Heo }
14578376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
14588376fe22STejun Heo 
14598376fe22STejun Heo /**
1460c8e55f36STejun Heo  * worker_enter_idle - enter idle state
1461c8e55f36STejun Heo  * @worker: worker which is entering idle state
1462c8e55f36STejun Heo  *
1463c8e55f36STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
1464c8e55f36STejun Heo  * necessary.
1465c8e55f36STejun Heo  *
1466c8e55f36STejun Heo  * LOCKING:
1467d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1468c8e55f36STejun Heo  */
1469c8e55f36STejun Heo static void worker_enter_idle(struct worker *worker)
14701da177e4SLinus Torvalds {
1471bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1472c8e55f36STejun Heo 
14736183c009STejun Heo 	if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
14746183c009STejun Heo 	    WARN_ON_ONCE(!list_empty(&worker->entry) &&
14756183c009STejun Heo 			 (worker->hentry.next || worker->hentry.pprev)))
14766183c009STejun Heo 		return;
1477c8e55f36STejun Heo 
1478cb444766STejun Heo 	/* can't use worker_set_flags(), also called from start_worker() */
1479cb444766STejun Heo 	worker->flags |= WORKER_IDLE;
1480bd7bdd43STejun Heo 	pool->nr_idle++;
1481e22bee78STejun Heo 	worker->last_active = jiffies;
1482c8e55f36STejun Heo 
1483c8e55f36STejun Heo 	/* idle_list is LIFO */
1484bd7bdd43STejun Heo 	list_add(&worker->entry, &pool->idle_list);
1485db7bccf4STejun Heo 
148663d95a91STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1487628c78e7STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1488cb444766STejun Heo 
1489544ecf31STejun Heo 	/*
1490706026c2STejun Heo 	 * Sanity check nr_running.  Because wq_unbind_fn() releases
1491d565ed63STejun Heo 	 * pool->lock between setting %WORKER_UNBOUND and zapping
1492628c78e7STejun Heo 	 * nr_running, the warning may trigger spuriously.  Check iff
1493628c78e7STejun Heo 	 * unbind is not in progress.
1494544ecf31STejun Heo 	 */
149524647570STejun Heo 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1496bd7bdd43STejun Heo 		     pool->nr_workers == pool->nr_idle &&
1497e19e397aSTejun Heo 		     atomic_read(&pool->nr_running));
1498c8e55f36STejun Heo }
1499c8e55f36STejun Heo 
1500c8e55f36STejun Heo /**
1501c8e55f36STejun Heo  * worker_leave_idle - leave idle state
1502c8e55f36STejun Heo  * @worker: worker which is leaving idle state
1503c8e55f36STejun Heo  *
1504c8e55f36STejun Heo  * @worker is leaving idle state.  Update stats.
1505c8e55f36STejun Heo  *
1506c8e55f36STejun Heo  * LOCKING:
1507d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1508c8e55f36STejun Heo  */
1509c8e55f36STejun Heo static void worker_leave_idle(struct worker *worker)
1510c8e55f36STejun Heo {
1511bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1512c8e55f36STejun Heo 
15136183c009STejun Heo 	if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
15146183c009STejun Heo 		return;
1515d302f017STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
1516bd7bdd43STejun Heo 	pool->nr_idle--;
1517c8e55f36STejun Heo 	list_del_init(&worker->entry);
1518c8e55f36STejun Heo }
1519c8e55f36STejun Heo 
1520e22bee78STejun Heo /**
1521f36dc67bSLai Jiangshan  * worker_maybe_bind_and_lock - try to bind %current to worker_pool and lock it
1522f36dc67bSLai Jiangshan  * @pool: target worker_pool
1523f36dc67bSLai Jiangshan  *
1524f36dc67bSLai Jiangshan  * Bind %current to the cpu of @pool if it is associated and lock @pool.
1525e22bee78STejun Heo  *
1526e22bee78STejun Heo  * Works which are scheduled while the cpu is online must at least be
1527e22bee78STejun Heo  * scheduled to a worker which is bound to the cpu so that if they are
1528e22bee78STejun Heo  * flushed from cpu callbacks while cpu is going down, they are
1529e22bee78STejun Heo  * guaranteed to execute on the cpu.
1530e22bee78STejun Heo  *
1531f5faa077SLai Jiangshan  * This function is to be used by unbound workers and rescuers to bind
1532e22bee78STejun Heo  * themselves to the target cpu and may race with cpu going down or
1533e22bee78STejun Heo  * coming online.  kthread_bind() can't be used because it may put the
1534e22bee78STejun Heo  * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1535706026c2STejun Heo  * verbatim as it's best effort and blocking and pool may be
1536e22bee78STejun Heo  * [dis]associated in the meantime.
1537e22bee78STejun Heo  *
1538706026c2STejun Heo  * This function tries set_cpus_allowed() and locks pool and verifies the
153924647570STejun Heo  * binding against %POOL_DISASSOCIATED which is set during
1540f2d5a0eeSTejun Heo  * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
1541f2d5a0eeSTejun Heo  * enters idle state or fetches works without dropping lock, it can
1542f2d5a0eeSTejun Heo  * guarantee the scheduling requirement described in the first paragraph.
1543e22bee78STejun Heo  *
1544e22bee78STejun Heo  * CONTEXT:
1545d565ed63STejun Heo  * Might sleep.  Called without any lock but returns with pool->lock
1546e22bee78STejun Heo  * held.
1547e22bee78STejun Heo  *
1548e22bee78STejun Heo  * RETURNS:
1549706026c2STejun Heo  * %true if the associated pool is online (@worker is successfully
1550e22bee78STejun Heo  * bound), %false if offline.
1551e22bee78STejun Heo  */
1552f36dc67bSLai Jiangshan static bool worker_maybe_bind_and_lock(struct worker_pool *pool)
1553d565ed63STejun Heo __acquires(&pool->lock)
1554e22bee78STejun Heo {
1555e22bee78STejun Heo 	while (true) {
1556e22bee78STejun Heo 		/*
1557e22bee78STejun Heo 		 * The following call may fail, succeed or succeed
1558e22bee78STejun Heo 		 * without actually migrating the task to the cpu if
1559e22bee78STejun Heo 		 * it races with cpu hotunplug operation.  Verify
156024647570STejun Heo 		 * against POOL_DISASSOCIATED.
1561e22bee78STejun Heo 		 */
156224647570STejun Heo 		if (!(pool->flags & POOL_DISASSOCIATED))
15637a4e344cSTejun Heo 			set_cpus_allowed_ptr(current, pool->attrs->cpumask);
1564e22bee78STejun Heo 
1565d565ed63STejun Heo 		spin_lock_irq(&pool->lock);
156624647570STejun Heo 		if (pool->flags & POOL_DISASSOCIATED)
1567e22bee78STejun Heo 			return false;
1568f5faa077SLai Jiangshan 		if (task_cpu(current) == pool->cpu &&
15697a4e344cSTejun Heo 		    cpumask_equal(&current->cpus_allowed, pool->attrs->cpumask))
1570e22bee78STejun Heo 			return true;
1571d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
1572e22bee78STejun Heo 
15735035b20fSTejun Heo 		/*
15745035b20fSTejun Heo 		 * We've raced with CPU hot[un]plug.  Give it a breather
15755035b20fSTejun Heo 		 * and retry migration.  cond_resched() is required here;
15765035b20fSTejun Heo 		 * otherwise, we might deadlock against cpu_stop trying to
15775035b20fSTejun Heo 		 * bring down the CPU on non-preemptive kernel.
15785035b20fSTejun Heo 		 */
1579e22bee78STejun Heo 		cpu_relax();
15805035b20fSTejun Heo 		cond_resched();
1581e22bee78STejun Heo 	}
1582e22bee78STejun Heo }
1583e22bee78STejun Heo 
1584e22bee78STejun Heo /*
1585ea1abd61SLai Jiangshan  * Rebind an idle @worker to its CPU.  worker_thread() will test
15865f7dabfdSLai Jiangshan  * list_empty(@worker->entry) before leaving idle and call this function.
158725511a47STejun Heo  */
158825511a47STejun Heo static void idle_worker_rebind(struct worker *worker)
158925511a47STejun Heo {
15905f7dabfdSLai Jiangshan 	/* CPU may go down again inbetween, clear UNBOUND only on success */
1591f36dc67bSLai Jiangshan 	if (worker_maybe_bind_and_lock(worker->pool))
15925f7dabfdSLai Jiangshan 		worker_clr_flags(worker, WORKER_UNBOUND);
159325511a47STejun Heo 
1594ea1abd61SLai Jiangshan 	/* rebind complete, become available again */
1595ea1abd61SLai Jiangshan 	list_add(&worker->entry, &worker->pool->idle_list);
1596d565ed63STejun Heo 	spin_unlock_irq(&worker->pool->lock);
159725511a47STejun Heo }
159825511a47STejun Heo 
159925511a47STejun Heo /*
160025511a47STejun Heo  * Function for @worker->rebind.work used to rebind unbound busy workers to
1601403c821dSTejun Heo  * the associated cpu which is coming back online.  This is scheduled by
1602403c821dSTejun Heo  * cpu up but can race with other cpu hotplug operations and may be
1603403c821dSTejun Heo  * executed twice without intervening cpu down.
1604e22bee78STejun Heo  */
160525511a47STejun Heo static void busy_worker_rebind_fn(struct work_struct *work)
1606e22bee78STejun Heo {
1607e22bee78STejun Heo 	struct worker *worker = container_of(work, struct worker, rebind_work);
1608e22bee78STejun Heo 
1609f36dc67bSLai Jiangshan 	if (worker_maybe_bind_and_lock(worker->pool))
1610eab6d828SLai Jiangshan 		worker_clr_flags(worker, WORKER_UNBOUND);
1611e22bee78STejun Heo 
1612d565ed63STejun Heo 	spin_unlock_irq(&worker->pool->lock);
1613e22bee78STejun Heo }
1614e22bee78STejun Heo 
161525511a47STejun Heo /**
161694cf58bbSTejun Heo  * rebind_workers - rebind all workers of a pool to the associated CPU
161794cf58bbSTejun Heo  * @pool: pool of interest
161825511a47STejun Heo  *
161994cf58bbSTejun Heo  * @pool->cpu is coming online.  Rebind all workers to the CPU.  Rebinding
162025511a47STejun Heo  * is different for idle and busy ones.
162125511a47STejun Heo  *
1622ea1abd61SLai Jiangshan  * Idle ones will be removed from the idle_list and woken up.  They will
1623ea1abd61SLai Jiangshan  * add themselves back after completing rebind.  This ensures that the
1624ea1abd61SLai Jiangshan  * idle_list doesn't contain any unbound workers when re-bound busy workers
1625ea1abd61SLai Jiangshan  * try to perform local wake-ups for concurrency management.
162625511a47STejun Heo  *
1627ea1abd61SLai Jiangshan  * Busy workers can rebind after they finish their current work items.
1628ea1abd61SLai Jiangshan  * Queueing the rebind work item at the head of the scheduled list is
1629ea1abd61SLai Jiangshan  * enough.  Note that nr_running will be properly bumped as busy workers
1630ea1abd61SLai Jiangshan  * rebind.
163125511a47STejun Heo  *
1632ea1abd61SLai Jiangshan  * On return, all non-manager workers are scheduled for rebind - see
1633ea1abd61SLai Jiangshan  * manage_workers() for the manager special case.  Any idle worker
1634ea1abd61SLai Jiangshan  * including the manager will not appear on @idle_list until rebind is
1635ea1abd61SLai Jiangshan  * complete, making local wake-ups safe.
163625511a47STejun Heo  */
163794cf58bbSTejun Heo static void rebind_workers(struct worker_pool *pool)
163825511a47STejun Heo {
1639ea1abd61SLai Jiangshan 	struct worker *worker, *n;
164025511a47STejun Heo 	int i;
164125511a47STejun Heo 
1642bc3a1afcSTejun Heo 	lockdep_assert_held(&pool->manager_mutex);
1643d565ed63STejun Heo 	lockdep_assert_held(&pool->lock);
164425511a47STejun Heo 
16455f7dabfdSLai Jiangshan 	/* dequeue and kick idle ones */
1646ea1abd61SLai Jiangshan 	list_for_each_entry_safe(worker, n, &pool->idle_list, entry) {
1647ea1abd61SLai Jiangshan 		/*
164894cf58bbSTejun Heo 		 * idle workers should be off @pool->idle_list until rebind
164994cf58bbSTejun Heo 		 * is complete to avoid receiving premature local wake-ups.
1650ea1abd61SLai Jiangshan 		 */
1651ea1abd61SLai Jiangshan 		list_del_init(&worker->entry);
165225511a47STejun Heo 
165325511a47STejun Heo 		/*
165494cf58bbSTejun Heo 		 * worker_thread() will see the above dequeuing and call
165594cf58bbSTejun Heo 		 * idle_worker_rebind().
165625511a47STejun Heo 		 */
165725511a47STejun Heo 		wake_up_process(worker->task);
165825511a47STejun Heo 	}
165925511a47STejun Heo 
1660ea1abd61SLai Jiangshan 	/* rebind busy workers */
1661b67bfe0dSSasha Levin 	for_each_busy_worker(worker, i, pool) {
166225511a47STejun Heo 		struct work_struct *rebind_work = &worker->rebind_work;
1663e2b6a6d5SJoonsoo Kim 		struct workqueue_struct *wq;
166425511a47STejun Heo 
166525511a47STejun Heo 		if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
166625511a47STejun Heo 				     work_data_bits(rebind_work)))
166725511a47STejun Heo 			continue;
166825511a47STejun Heo 
166925511a47STejun Heo 		debug_work_activate(rebind_work);
167090beca5dSTejun Heo 
167190beca5dSTejun Heo 		/*
167294cf58bbSTejun Heo 		 * wq doesn't really matter but let's keep @worker->pool
1673112202d9STejun Heo 		 * and @pwq->pool consistent for sanity.
167490beca5dSTejun Heo 		 */
16757a4e344cSTejun Heo 		if (worker->pool->attrs->nice < 0)
1676e2b6a6d5SJoonsoo Kim 			wq = system_highpri_wq;
1677e2b6a6d5SJoonsoo Kim 		else
1678e2b6a6d5SJoonsoo Kim 			wq = system_wq;
1679ec58815aSTejun Heo 
16807fb98ea7STejun Heo 		insert_work(per_cpu_ptr(wq->cpu_pwqs, pool->cpu), rebind_work,
168125511a47STejun Heo 			    worker->scheduled.next,
168225511a47STejun Heo 			    work_color_to_flags(WORK_NO_COLOR));
1683ec58815aSTejun Heo 	}
168425511a47STejun Heo }
168525511a47STejun Heo 
1686c34056a3STejun Heo static struct worker *alloc_worker(void)
1687c34056a3STejun Heo {
1688c34056a3STejun Heo 	struct worker *worker;
1689c34056a3STejun Heo 
1690c34056a3STejun Heo 	worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1691c8e55f36STejun Heo 	if (worker) {
1692c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
1693affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
169425511a47STejun Heo 		INIT_WORK(&worker->rebind_work, busy_worker_rebind_fn);
1695e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
1696e22bee78STejun Heo 		worker->flags = WORKER_PREP;
1697c8e55f36STejun Heo 	}
1698c34056a3STejun Heo 	return worker;
1699c34056a3STejun Heo }
1700c34056a3STejun Heo 
1701c34056a3STejun Heo /**
1702c34056a3STejun Heo  * create_worker - create a new workqueue worker
170363d95a91STejun Heo  * @pool: pool the new worker will belong to
1704c34056a3STejun Heo  *
170563d95a91STejun Heo  * Create a new worker which is bound to @pool.  The returned worker
1706c34056a3STejun Heo  * can be started by calling start_worker() or destroyed using
1707c34056a3STejun Heo  * destroy_worker().
1708c34056a3STejun Heo  *
1709c34056a3STejun Heo  * CONTEXT:
1710c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
1711c34056a3STejun Heo  *
1712c34056a3STejun Heo  * RETURNS:
1713c34056a3STejun Heo  * Pointer to the newly created worker.
1714c34056a3STejun Heo  */
1715bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
1716c34056a3STejun Heo {
17177a4e344cSTejun Heo 	const char *pri = pool->attrs->nice < 0  ? "H" : "";
1718c34056a3STejun Heo 	struct worker *worker = NULL;
1719f3421797STejun Heo 	int id = -1;
1720c34056a3STejun Heo 
1721cd549687STejun Heo 	lockdep_assert_held(&pool->manager_mutex);
1722cd549687STejun Heo 
1723d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
1724bd7bdd43STejun Heo 	while (ida_get_new(&pool->worker_ida, &id)) {
1725d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
1726bd7bdd43STejun Heo 		if (!ida_pre_get(&pool->worker_ida, GFP_KERNEL))
1727c34056a3STejun Heo 			goto fail;
1728d565ed63STejun Heo 		spin_lock_irq(&pool->lock);
1729c34056a3STejun Heo 	}
1730d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
1731c34056a3STejun Heo 
1732c34056a3STejun Heo 	worker = alloc_worker();
1733c34056a3STejun Heo 	if (!worker)
1734c34056a3STejun Heo 		goto fail;
1735c34056a3STejun Heo 
1736bd7bdd43STejun Heo 	worker->pool = pool;
1737c34056a3STejun Heo 	worker->id = id;
1738c34056a3STejun Heo 
173929c91e99STejun Heo 	if (pool->cpu >= 0)
174094dcf29aSEric Dumazet 		worker->task = kthread_create_on_node(worker_thread,
1741ec22ca5eSTejun Heo 					worker, cpu_to_node(pool->cpu),
1742d84ff051STejun Heo 					"kworker/%d:%d%s", pool->cpu, id, pri);
1743f3421797STejun Heo 	else
1744f3421797STejun Heo 		worker->task = kthread_create(worker_thread, worker,
1745ac6104cdSTejun Heo 					      "kworker/u%d:%d%s",
1746ac6104cdSTejun Heo 					      pool->id, id, pri);
1747c34056a3STejun Heo 	if (IS_ERR(worker->task))
1748c34056a3STejun Heo 		goto fail;
1749c34056a3STejun Heo 
1750c5aa87bbSTejun Heo 	/*
1751c5aa87bbSTejun Heo 	 * set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
1752c5aa87bbSTejun Heo 	 * online CPUs.  It'll be re-applied when any of the CPUs come up.
1753c5aa87bbSTejun Heo 	 */
17547a4e344cSTejun Heo 	set_user_nice(worker->task, pool->attrs->nice);
17557a4e344cSTejun Heo 	set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
17563270476aSTejun Heo 
1757db7bccf4STejun Heo 	/*
17587a4e344cSTejun Heo 	 * %PF_THREAD_BOUND is used to prevent userland from meddling with
17597a4e344cSTejun Heo 	 * cpumask of workqueue workers.  This is an abuse.  We need
17607a4e344cSTejun Heo 	 * %PF_NO_SETAFFINITY.
1761db7bccf4STejun Heo 	 */
1762db7bccf4STejun Heo 	worker->task->flags |= PF_THREAD_BOUND;
17637a4e344cSTejun Heo 
17647a4e344cSTejun Heo 	/*
17657a4e344cSTejun Heo 	 * The caller is responsible for ensuring %POOL_DISASSOCIATED
17667a4e344cSTejun Heo 	 * remains stable across this function.  See the comments above the
17677a4e344cSTejun Heo 	 * flag definition for details.
17687a4e344cSTejun Heo 	 */
17697a4e344cSTejun Heo 	if (pool->flags & POOL_DISASSOCIATED)
1770f3421797STejun Heo 		worker->flags |= WORKER_UNBOUND;
1771c34056a3STejun Heo 
1772c34056a3STejun Heo 	return worker;
1773c34056a3STejun Heo fail:
1774c34056a3STejun Heo 	if (id >= 0) {
1775d565ed63STejun Heo 		spin_lock_irq(&pool->lock);
1776bd7bdd43STejun Heo 		ida_remove(&pool->worker_ida, id);
1777d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
1778c34056a3STejun Heo 	}
1779c34056a3STejun Heo 	kfree(worker);
1780c34056a3STejun Heo 	return NULL;
1781c34056a3STejun Heo }
1782c34056a3STejun Heo 
1783c34056a3STejun Heo /**
1784c34056a3STejun Heo  * start_worker - start a newly created worker
1785c34056a3STejun Heo  * @worker: worker to start
1786c34056a3STejun Heo  *
1787706026c2STejun Heo  * Make the pool aware of @worker and start it.
1788c34056a3STejun Heo  *
1789c34056a3STejun Heo  * CONTEXT:
1790d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1791c34056a3STejun Heo  */
1792c34056a3STejun Heo static void start_worker(struct worker *worker)
1793c34056a3STejun Heo {
1794cb444766STejun Heo 	worker->flags |= WORKER_STARTED;
1795bd7bdd43STejun Heo 	worker->pool->nr_workers++;
1796c8e55f36STejun Heo 	worker_enter_idle(worker);
1797c34056a3STejun Heo 	wake_up_process(worker->task);
1798c34056a3STejun Heo }
1799c34056a3STejun Heo 
1800c34056a3STejun Heo /**
1801ebf44d16STejun Heo  * create_and_start_worker - create and start a worker for a pool
1802ebf44d16STejun Heo  * @pool: the target pool
1803ebf44d16STejun Heo  *
1804cd549687STejun Heo  * Grab the managership of @pool and create and start a new worker for it.
1805ebf44d16STejun Heo  */
1806ebf44d16STejun Heo static int create_and_start_worker(struct worker_pool *pool)
1807ebf44d16STejun Heo {
1808ebf44d16STejun Heo 	struct worker *worker;
1809ebf44d16STejun Heo 
1810cd549687STejun Heo 	mutex_lock(&pool->manager_mutex);
1811cd549687STejun Heo 
1812ebf44d16STejun Heo 	worker = create_worker(pool);
1813ebf44d16STejun Heo 	if (worker) {
1814ebf44d16STejun Heo 		spin_lock_irq(&pool->lock);
1815ebf44d16STejun Heo 		start_worker(worker);
1816ebf44d16STejun Heo 		spin_unlock_irq(&pool->lock);
1817ebf44d16STejun Heo 	}
1818ebf44d16STejun Heo 
1819cd549687STejun Heo 	mutex_unlock(&pool->manager_mutex);
1820cd549687STejun Heo 
1821ebf44d16STejun Heo 	return worker ? 0 : -ENOMEM;
1822ebf44d16STejun Heo }
1823ebf44d16STejun Heo 
1824ebf44d16STejun Heo /**
1825c34056a3STejun Heo  * destroy_worker - destroy a workqueue worker
1826c34056a3STejun Heo  * @worker: worker to be destroyed
1827c34056a3STejun Heo  *
1828706026c2STejun Heo  * Destroy @worker and adjust @pool stats accordingly.
1829c8e55f36STejun Heo  *
1830c8e55f36STejun Heo  * CONTEXT:
1831d565ed63STejun Heo  * spin_lock_irq(pool->lock) which is released and regrabbed.
1832c34056a3STejun Heo  */
1833c34056a3STejun Heo static void destroy_worker(struct worker *worker)
1834c34056a3STejun Heo {
1835bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1836c34056a3STejun Heo 	int id = worker->id;
1837c34056a3STejun Heo 
1838cd549687STejun Heo 	lockdep_assert_held(&pool->manager_mutex);
1839cd549687STejun Heo 	lockdep_assert_held(&pool->lock);
1840cd549687STejun Heo 
1841c34056a3STejun Heo 	/* sanity check frenzy */
18426183c009STejun Heo 	if (WARN_ON(worker->current_work) ||
18436183c009STejun Heo 	    WARN_ON(!list_empty(&worker->scheduled)))
18446183c009STejun Heo 		return;
1845c34056a3STejun Heo 
1846c8e55f36STejun Heo 	if (worker->flags & WORKER_STARTED)
1847bd7bdd43STejun Heo 		pool->nr_workers--;
1848c8e55f36STejun Heo 	if (worker->flags & WORKER_IDLE)
1849bd7bdd43STejun Heo 		pool->nr_idle--;
1850c8e55f36STejun Heo 
1851c8e55f36STejun Heo 	list_del_init(&worker->entry);
1852cb444766STejun Heo 	worker->flags |= WORKER_DIE;
1853c8e55f36STejun Heo 
1854d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
1855c8e55f36STejun Heo 
1856c34056a3STejun Heo 	kthread_stop(worker->task);
1857c34056a3STejun Heo 	kfree(worker);
1858c34056a3STejun Heo 
1859d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
1860bd7bdd43STejun Heo 	ida_remove(&pool->worker_ida, id);
1861c34056a3STejun Heo }
1862c34056a3STejun Heo 
186363d95a91STejun Heo static void idle_worker_timeout(unsigned long __pool)
1864e22bee78STejun Heo {
186563d95a91STejun Heo 	struct worker_pool *pool = (void *)__pool;
1866e22bee78STejun Heo 
1867d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
1868e22bee78STejun Heo 
186963d95a91STejun Heo 	if (too_many_workers(pool)) {
1870e22bee78STejun Heo 		struct worker *worker;
1871e22bee78STejun Heo 		unsigned long expires;
1872e22bee78STejun Heo 
1873e22bee78STejun Heo 		/* idle_list is kept in LIFO order, check the last one */
187463d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
1875e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1876e22bee78STejun Heo 
1877e22bee78STejun Heo 		if (time_before(jiffies, expires))
187863d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
1879e22bee78STejun Heo 		else {
1880e22bee78STejun Heo 			/* it's been idle for too long, wake up manager */
188111ebea50STejun Heo 			pool->flags |= POOL_MANAGE_WORKERS;
188263d95a91STejun Heo 			wake_up_worker(pool);
1883e22bee78STejun Heo 		}
1884e22bee78STejun Heo 	}
1885e22bee78STejun Heo 
1886d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
1887e22bee78STejun Heo }
1888e22bee78STejun Heo 
1889493a1724STejun Heo static void send_mayday(struct work_struct *work)
1890e22bee78STejun Heo {
1891112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1892112202d9STejun Heo 	struct workqueue_struct *wq = pwq->wq;
1893493a1724STejun Heo 
1894493a1724STejun Heo 	lockdep_assert_held(&workqueue_lock);
1895e22bee78STejun Heo 
1896493008a8STejun Heo 	if (!wq->rescuer)
1897493a1724STejun Heo 		return;
1898e22bee78STejun Heo 
1899e22bee78STejun Heo 	/* mayday mayday mayday */
1900493a1724STejun Heo 	if (list_empty(&pwq->mayday_node)) {
1901493a1724STejun Heo 		list_add_tail(&pwq->mayday_node, &wq->maydays);
1902e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
1903493a1724STejun Heo 	}
1904e22bee78STejun Heo }
1905e22bee78STejun Heo 
1906706026c2STejun Heo static void pool_mayday_timeout(unsigned long __pool)
1907e22bee78STejun Heo {
190863d95a91STejun Heo 	struct worker_pool *pool = (void *)__pool;
1909e22bee78STejun Heo 	struct work_struct *work;
1910e22bee78STejun Heo 
1911493a1724STejun Heo 	spin_lock_irq(&workqueue_lock);		/* for wq->maydays */
1912493a1724STejun Heo 	spin_lock(&pool->lock);
1913e22bee78STejun Heo 
191463d95a91STejun Heo 	if (need_to_create_worker(pool)) {
1915e22bee78STejun Heo 		/*
1916e22bee78STejun Heo 		 * We've been trying to create a new worker but
1917e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
1918e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
1919e22bee78STejun Heo 		 * rescuers.
1920e22bee78STejun Heo 		 */
192163d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
1922e22bee78STejun Heo 			send_mayday(work);
1923e22bee78STejun Heo 	}
1924e22bee78STejun Heo 
1925493a1724STejun Heo 	spin_unlock(&pool->lock);
1926493a1724STejun Heo 	spin_unlock_irq(&workqueue_lock);
1927e22bee78STejun Heo 
192863d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1929e22bee78STejun Heo }
1930e22bee78STejun Heo 
1931e22bee78STejun Heo /**
1932e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
193363d95a91STejun Heo  * @pool: pool to create a new worker for
1934e22bee78STejun Heo  *
193563d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
1936e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
1937e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
193863d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
1939e22bee78STejun Heo  * possible allocation deadlock.
1940e22bee78STejun Heo  *
1941c5aa87bbSTejun Heo  * On return, need_to_create_worker() is guaranteed to be %false and
1942c5aa87bbSTejun Heo  * may_start_working() %true.
1943e22bee78STejun Heo  *
1944e22bee78STejun Heo  * LOCKING:
1945d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
1946e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
1947e22bee78STejun Heo  * manager.
1948e22bee78STejun Heo  *
1949e22bee78STejun Heo  * RETURNS:
1950c5aa87bbSTejun Heo  * %false if no action was taken and pool->lock stayed locked, %true
1951e22bee78STejun Heo  * otherwise.
1952e22bee78STejun Heo  */
195363d95a91STejun Heo static bool maybe_create_worker(struct worker_pool *pool)
1954d565ed63STejun Heo __releases(&pool->lock)
1955d565ed63STejun Heo __acquires(&pool->lock)
1956e22bee78STejun Heo {
195763d95a91STejun Heo 	if (!need_to_create_worker(pool))
1958e22bee78STejun Heo 		return false;
1959e22bee78STejun Heo restart:
1960d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
19619f9c2364STejun Heo 
1962e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
196363d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1964e22bee78STejun Heo 
1965e22bee78STejun Heo 	while (true) {
1966e22bee78STejun Heo 		struct worker *worker;
1967e22bee78STejun Heo 
1968bc2ae0f5STejun Heo 		worker = create_worker(pool);
1969e22bee78STejun Heo 		if (worker) {
197063d95a91STejun Heo 			del_timer_sync(&pool->mayday_timer);
1971d565ed63STejun Heo 			spin_lock_irq(&pool->lock);
1972e22bee78STejun Heo 			start_worker(worker);
19736183c009STejun Heo 			if (WARN_ON_ONCE(need_to_create_worker(pool)))
19746183c009STejun Heo 				goto restart;
1975e22bee78STejun Heo 			return true;
1976e22bee78STejun Heo 		}
1977e22bee78STejun Heo 
197863d95a91STejun Heo 		if (!need_to_create_worker(pool))
1979e22bee78STejun Heo 			break;
1980e22bee78STejun Heo 
1981e22bee78STejun Heo 		__set_current_state(TASK_INTERRUPTIBLE);
1982e22bee78STejun Heo 		schedule_timeout(CREATE_COOLDOWN);
19839f9c2364STejun Heo 
198463d95a91STejun Heo 		if (!need_to_create_worker(pool))
1985e22bee78STejun Heo 			break;
1986e22bee78STejun Heo 	}
1987e22bee78STejun Heo 
198863d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
1989d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
199063d95a91STejun Heo 	if (need_to_create_worker(pool))
1991e22bee78STejun Heo 		goto restart;
1992e22bee78STejun Heo 	return true;
1993e22bee78STejun Heo }
1994e22bee78STejun Heo 
1995e22bee78STejun Heo /**
1996e22bee78STejun Heo  * maybe_destroy_worker - destroy workers which have been idle for a while
199763d95a91STejun Heo  * @pool: pool to destroy workers for
1998e22bee78STejun Heo  *
199963d95a91STejun Heo  * Destroy @pool workers which have been idle for longer than
2000e22bee78STejun Heo  * IDLE_WORKER_TIMEOUT.
2001e22bee78STejun Heo  *
2002e22bee78STejun Heo  * LOCKING:
2003d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
2004e22bee78STejun Heo  * multiple times.  Called only from manager.
2005e22bee78STejun Heo  *
2006e22bee78STejun Heo  * RETURNS:
2007c5aa87bbSTejun Heo  * %false if no action was taken and pool->lock stayed locked, %true
2008e22bee78STejun Heo  * otherwise.
2009e22bee78STejun Heo  */
201063d95a91STejun Heo static bool maybe_destroy_workers(struct worker_pool *pool)
2011e22bee78STejun Heo {
2012e22bee78STejun Heo 	bool ret = false;
2013e22bee78STejun Heo 
201463d95a91STejun Heo 	while (too_many_workers(pool)) {
2015e22bee78STejun Heo 		struct worker *worker;
2016e22bee78STejun Heo 		unsigned long expires;
2017e22bee78STejun Heo 
201863d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
2019e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2020e22bee78STejun Heo 
2021e22bee78STejun Heo 		if (time_before(jiffies, expires)) {
202263d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
2023e22bee78STejun Heo 			break;
2024e22bee78STejun Heo 		}
2025e22bee78STejun Heo 
2026e22bee78STejun Heo 		destroy_worker(worker);
2027e22bee78STejun Heo 		ret = true;
2028e22bee78STejun Heo 	}
2029e22bee78STejun Heo 
2030e22bee78STejun Heo 	return ret;
2031e22bee78STejun Heo }
2032e22bee78STejun Heo 
2033e22bee78STejun Heo /**
2034e22bee78STejun Heo  * manage_workers - manage worker pool
2035e22bee78STejun Heo  * @worker: self
2036e22bee78STejun Heo  *
2037706026c2STejun Heo  * Assume the manager role and manage the worker pool @worker belongs
2038e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
2039706026c2STejun Heo  * pool.  The exclusion is handled automatically by this function.
2040e22bee78STejun Heo  *
2041e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
2042e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
2043e22bee78STejun Heo  * and may_start_working() is true.
2044e22bee78STejun Heo  *
2045e22bee78STejun Heo  * CONTEXT:
2046d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
2047e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
2048e22bee78STejun Heo  *
2049e22bee78STejun Heo  * RETURNS:
2050d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
2051d565ed63STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
2052e22bee78STejun Heo  */
2053e22bee78STejun Heo static bool manage_workers(struct worker *worker)
2054e22bee78STejun Heo {
205563d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
2056e22bee78STejun Heo 	bool ret = false;
2057e22bee78STejun Heo 
2058bc3a1afcSTejun Heo 	/*
2059bc3a1afcSTejun Heo 	 * Managership is governed by two mutexes - manager_arb and
2060bc3a1afcSTejun Heo 	 * manager_mutex.  manager_arb handles arbitration of manager role.
2061bc3a1afcSTejun Heo 	 * Anyone who successfully grabs manager_arb wins the arbitration
2062bc3a1afcSTejun Heo 	 * and becomes the manager.  mutex_trylock() on pool->manager_arb
2063bc3a1afcSTejun Heo 	 * failure while holding pool->lock reliably indicates that someone
2064bc3a1afcSTejun Heo 	 * else is managing the pool and the worker which failed trylock
2065bc3a1afcSTejun Heo 	 * can proceed to executing work items.  This means that anyone
2066bc3a1afcSTejun Heo 	 * grabbing manager_arb is responsible for actually performing
2067bc3a1afcSTejun Heo 	 * manager duties.  If manager_arb is grabbed and released without
2068bc3a1afcSTejun Heo 	 * actual management, the pool may stall indefinitely.
2069bc3a1afcSTejun Heo 	 *
2070bc3a1afcSTejun Heo 	 * manager_mutex is used for exclusion of actual management
2071bc3a1afcSTejun Heo 	 * operations.  The holder of manager_mutex can be sure that none
2072bc3a1afcSTejun Heo 	 * of management operations, including creation and destruction of
2073bc3a1afcSTejun Heo 	 * workers, won't take place until the mutex is released.  Because
2074bc3a1afcSTejun Heo 	 * manager_mutex doesn't interfere with manager role arbitration,
2075bc3a1afcSTejun Heo 	 * it is guaranteed that the pool's management, while may be
2076bc3a1afcSTejun Heo 	 * delayed, won't be disturbed by someone else grabbing
2077bc3a1afcSTejun Heo 	 * manager_mutex.
2078bc3a1afcSTejun Heo 	 */
207934a06bd6STejun Heo 	if (!mutex_trylock(&pool->manager_arb))
2080e22bee78STejun Heo 		return ret;
2081e22bee78STejun Heo 
2082ee378aa4SLai Jiangshan 	/*
2083bc3a1afcSTejun Heo 	 * With manager arbitration won, manager_mutex would be free in
2084bc3a1afcSTejun Heo 	 * most cases.  trylock first without dropping @pool->lock.
2085ee378aa4SLai Jiangshan 	 */
2086bc3a1afcSTejun Heo 	if (unlikely(!mutex_trylock(&pool->manager_mutex))) {
2087d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
2088bc3a1afcSTejun Heo 		mutex_lock(&pool->manager_mutex);
2089ee378aa4SLai Jiangshan 		/*
2090ee378aa4SLai Jiangshan 		 * CPU hotplug could have happened while we were waiting
2091b2eb83d1SLai Jiangshan 		 * for assoc_mutex.  Hotplug itself can't handle us
2092ee378aa4SLai Jiangshan 		 * because manager isn't either on idle or busy list, and
2093706026c2STejun Heo 		 * @pool's state and ours could have deviated.
2094ee378aa4SLai Jiangshan 		 *
2095bc3a1afcSTejun Heo 		 * As hotplug is now excluded via manager_mutex, we can
2096ee378aa4SLai Jiangshan 		 * simply try to bind.  It will succeed or fail depending
2097706026c2STejun Heo 		 * on @pool's current state.  Try it and adjust
2098ee378aa4SLai Jiangshan 		 * %WORKER_UNBOUND accordingly.
2099ee378aa4SLai Jiangshan 		 */
2100f36dc67bSLai Jiangshan 		if (worker_maybe_bind_and_lock(pool))
2101ee378aa4SLai Jiangshan 			worker->flags &= ~WORKER_UNBOUND;
2102ee378aa4SLai Jiangshan 		else
2103ee378aa4SLai Jiangshan 			worker->flags |= WORKER_UNBOUND;
2104ee378aa4SLai Jiangshan 
2105ee378aa4SLai Jiangshan 		ret = true;
2106ee378aa4SLai Jiangshan 	}
2107ee378aa4SLai Jiangshan 
210811ebea50STejun Heo 	pool->flags &= ~POOL_MANAGE_WORKERS;
2109e22bee78STejun Heo 
2110e22bee78STejun Heo 	/*
2111e22bee78STejun Heo 	 * Destroy and then create so that may_start_working() is true
2112e22bee78STejun Heo 	 * on return.
2113e22bee78STejun Heo 	 */
211463d95a91STejun Heo 	ret |= maybe_destroy_workers(pool);
211563d95a91STejun Heo 	ret |= maybe_create_worker(pool);
2116e22bee78STejun Heo 
2117bc3a1afcSTejun Heo 	mutex_unlock(&pool->manager_mutex);
211834a06bd6STejun Heo 	mutex_unlock(&pool->manager_arb);
2119e22bee78STejun Heo 	return ret;
2120e22bee78STejun Heo }
2121e22bee78STejun Heo 
2122a62428c0STejun Heo /**
2123a62428c0STejun Heo  * process_one_work - process single work
2124c34056a3STejun Heo  * @worker: self
2125a62428c0STejun Heo  * @work: work to process
2126a62428c0STejun Heo  *
2127a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
2128a62428c0STejun Heo  * process a single work including synchronization against and
2129a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
2130a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
2131a62428c0STejun Heo  * call this function to process a work.
2132a62428c0STejun Heo  *
2133a62428c0STejun Heo  * CONTEXT:
2134d565ed63STejun Heo  * spin_lock_irq(pool->lock) which is released and regrabbed.
2135a62428c0STejun Heo  */
2136c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
2137d565ed63STejun Heo __releases(&pool->lock)
2138d565ed63STejun Heo __acquires(&pool->lock)
21391da177e4SLinus Torvalds {
2140112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2141bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2142112202d9STejun Heo 	bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
214373f53c4aSTejun Heo 	int work_color;
21447e11629dSTejun Heo 	struct worker *collision;
21454e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
21464e6045f1SJohannes Berg 	/*
2147a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
2148a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
2149a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
2150a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
2151a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
21524e6045f1SJohannes Berg 	 */
21534d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
21544d82a1deSPeter Zijlstra 
21554d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
21564e6045f1SJohannes Berg #endif
21576fec10a1STejun Heo 	/*
21586fec10a1STejun Heo 	 * Ensure we're on the correct CPU.  DISASSOCIATED test is
21596fec10a1STejun Heo 	 * necessary to avoid spurious warnings from rescuers servicing the
216024647570STejun Heo 	 * unbound or a disassociated pool.
21616fec10a1STejun Heo 	 */
21625f7dabfdSLai Jiangshan 	WARN_ON_ONCE(!(worker->flags & WORKER_UNBOUND) &&
216324647570STejun Heo 		     !(pool->flags & POOL_DISASSOCIATED) &&
2164ec22ca5eSTejun Heo 		     raw_smp_processor_id() != pool->cpu);
216525511a47STejun Heo 
21667e11629dSTejun Heo 	/*
21677e11629dSTejun Heo 	 * A single work shouldn't be executed concurrently by
21687e11629dSTejun Heo 	 * multiple workers on a single cpu.  Check whether anyone is
21697e11629dSTejun Heo 	 * already processing the work.  If so, defer the work to the
21707e11629dSTejun Heo 	 * currently executing one.
21717e11629dSTejun Heo 	 */
2172c9e7cf27STejun Heo 	collision = find_worker_executing_work(pool, work);
21737e11629dSTejun Heo 	if (unlikely(collision)) {
21747e11629dSTejun Heo 		move_linked_works(work, &collision->scheduled, NULL);
21757e11629dSTejun Heo 		return;
21767e11629dSTejun Heo 	}
21771da177e4SLinus Torvalds 
21788930cabaSTejun Heo 	/* claim and dequeue */
21791da177e4SLinus Torvalds 	debug_work_deactivate(work);
2180c9e7cf27STejun Heo 	hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2181c34056a3STejun Heo 	worker->current_work = work;
2182a2c1c57bSTejun Heo 	worker->current_func = work->func;
2183112202d9STejun Heo 	worker->current_pwq = pwq;
218473f53c4aSTejun Heo 	work_color = get_work_color(work);
21857a22ad75STejun Heo 
2186a62428c0STejun Heo 	list_del_init(&work->entry);
2187a62428c0STejun Heo 
2188649027d7STejun Heo 	/*
2189fb0e7bebSTejun Heo 	 * CPU intensive works don't participate in concurrency
2190fb0e7bebSTejun Heo 	 * management.  They're the scheduler's responsibility.
2191fb0e7bebSTejun Heo 	 */
2192fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2193fb0e7bebSTejun Heo 		worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
2194fb0e7bebSTejun Heo 
2195974271c4STejun Heo 	/*
2196d565ed63STejun Heo 	 * Unbound pool isn't concurrency managed and work items should be
2197974271c4STejun Heo 	 * executed ASAP.  Wake up another worker if necessary.
2198974271c4STejun Heo 	 */
219963d95a91STejun Heo 	if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
220063d95a91STejun Heo 		wake_up_worker(pool);
2201974271c4STejun Heo 
22028930cabaSTejun Heo 	/*
22037c3eed5cSTejun Heo 	 * Record the last pool and clear PENDING which should be the last
2204d565ed63STejun Heo 	 * update to @work.  Also, do this inside @pool->lock so that
220523657bb1STejun Heo 	 * PENDING and queued state changes happen together while IRQ is
220623657bb1STejun Heo 	 * disabled.
22078930cabaSTejun Heo 	 */
22087c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(work, pool->id);
22091da177e4SLinus Torvalds 
2210d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2211365970a1SDavid Howells 
2212112202d9STejun Heo 	lock_map_acquire_read(&pwq->wq->lockdep_map);
22133295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
2214e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
2215a2c1c57bSTejun Heo 	worker->current_func(work);
2216e36c886aSArjan van de Ven 	/*
2217e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
2218e36c886aSArjan van de Ven 	 * point will only record its address.
2219e36c886aSArjan van de Ven 	 */
2220e36c886aSArjan van de Ven 	trace_workqueue_execute_end(work);
22213295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
2222112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
22231da177e4SLinus Torvalds 
2224d5abe669SPeter Zijlstra 	if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2225044c782cSValentin Ilie 		pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2226044c782cSValentin Ilie 		       "     last function: %pf\n",
2227a2c1c57bSTejun Heo 		       current->comm, preempt_count(), task_pid_nr(current),
2228a2c1c57bSTejun Heo 		       worker->current_func);
2229d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
2230d5abe669SPeter Zijlstra 		dump_stack();
2231d5abe669SPeter Zijlstra 	}
2232d5abe669SPeter Zijlstra 
2233d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
2234a62428c0STejun Heo 
2235fb0e7bebSTejun Heo 	/* clear cpu intensive status */
2236fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2237fb0e7bebSTejun Heo 		worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2238fb0e7bebSTejun Heo 
2239a62428c0STejun Heo 	/* we're done with it, release */
224042f8570fSSasha Levin 	hash_del(&worker->hentry);
2241c34056a3STejun Heo 	worker->current_work = NULL;
2242a2c1c57bSTejun Heo 	worker->current_func = NULL;
2243112202d9STejun Heo 	worker->current_pwq = NULL;
2244112202d9STejun Heo 	pwq_dec_nr_in_flight(pwq, work_color);
22451da177e4SLinus Torvalds }
22461da177e4SLinus Torvalds 
2247affee4b2STejun Heo /**
2248affee4b2STejun Heo  * process_scheduled_works - process scheduled works
2249affee4b2STejun Heo  * @worker: self
2250affee4b2STejun Heo  *
2251affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
2252affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
2253affee4b2STejun Heo  * fetches a work from the top and executes it.
2254affee4b2STejun Heo  *
2255affee4b2STejun Heo  * CONTEXT:
2256d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
2257affee4b2STejun Heo  * multiple times.
2258affee4b2STejun Heo  */
2259affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
22601da177e4SLinus Torvalds {
2261affee4b2STejun Heo 	while (!list_empty(&worker->scheduled)) {
2262affee4b2STejun Heo 		struct work_struct *work = list_first_entry(&worker->scheduled,
2263a62428c0STejun Heo 						struct work_struct, entry);
2264c34056a3STejun Heo 		process_one_work(worker, work);
2265a62428c0STejun Heo 	}
22661da177e4SLinus Torvalds }
22671da177e4SLinus Torvalds 
22684690c4abSTejun Heo /**
22694690c4abSTejun Heo  * worker_thread - the worker thread function
2270c34056a3STejun Heo  * @__worker: self
22714690c4abSTejun Heo  *
2272c5aa87bbSTejun Heo  * The worker thread function.  All workers belong to a worker_pool -
2273c5aa87bbSTejun Heo  * either a per-cpu one or dynamic unbound one.  These workers process all
2274c5aa87bbSTejun Heo  * work items regardless of their specific target workqueue.  The only
2275c5aa87bbSTejun Heo  * exception is work items which belong to workqueues with a rescuer which
2276c5aa87bbSTejun Heo  * will be explained in rescuer_thread().
22774690c4abSTejun Heo  */
2278c34056a3STejun Heo static int worker_thread(void *__worker)
22791da177e4SLinus Torvalds {
2280c34056a3STejun Heo 	struct worker *worker = __worker;
2281bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
22821da177e4SLinus Torvalds 
2283e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
2284e22bee78STejun Heo 	worker->task->flags |= PF_WQ_WORKER;
2285c8e55f36STejun Heo woke_up:
2286d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
2287affee4b2STejun Heo 
22885f7dabfdSLai Jiangshan 	/* we are off idle list if destruction or rebind is requested */
22895f7dabfdSLai Jiangshan 	if (unlikely(list_empty(&worker->entry))) {
2290d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
229125511a47STejun Heo 
22925f7dabfdSLai Jiangshan 		/* if DIE is set, destruction is requested */
229325511a47STejun Heo 		if (worker->flags & WORKER_DIE) {
2294e22bee78STejun Heo 			worker->task->flags &= ~PF_WQ_WORKER;
2295c8e55f36STejun Heo 			return 0;
2296c8e55f36STejun Heo 		}
2297c8e55f36STejun Heo 
22985f7dabfdSLai Jiangshan 		/* otherwise, rebind */
229925511a47STejun Heo 		idle_worker_rebind(worker);
230025511a47STejun Heo 		goto woke_up;
230125511a47STejun Heo 	}
230225511a47STejun Heo 
2303c8e55f36STejun Heo 	worker_leave_idle(worker);
2304db7bccf4STejun Heo recheck:
2305e22bee78STejun Heo 	/* no more worker necessary? */
230663d95a91STejun Heo 	if (!need_more_worker(pool))
2307e22bee78STejun Heo 		goto sleep;
2308e22bee78STejun Heo 
2309e22bee78STejun Heo 	/* do we need to manage? */
231063d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2311e22bee78STejun Heo 		goto recheck;
2312e22bee78STejun Heo 
2313c8e55f36STejun Heo 	/*
2314c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
2315c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
2316c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
2317c8e55f36STejun Heo 	 */
23186183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
2319c8e55f36STejun Heo 
2320e22bee78STejun Heo 	/*
2321e22bee78STejun Heo 	 * When control reaches this point, we're guaranteed to have
2322e22bee78STejun Heo 	 * at least one idle worker or that someone else has already
2323e22bee78STejun Heo 	 * assumed the manager role.
2324e22bee78STejun Heo 	 */
2325e22bee78STejun Heo 	worker_clr_flags(worker, WORKER_PREP);
2326e22bee78STejun Heo 
2327e22bee78STejun Heo 	do {
2328affee4b2STejun Heo 		struct work_struct *work =
2329bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
2330affee4b2STejun Heo 					 struct work_struct, entry);
2331affee4b2STejun Heo 
2332c8e55f36STejun Heo 		if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2333affee4b2STejun Heo 			/* optimization path, not strictly necessary */
2334affee4b2STejun Heo 			process_one_work(worker, work);
2335affee4b2STejun Heo 			if (unlikely(!list_empty(&worker->scheduled)))
2336affee4b2STejun Heo 				process_scheduled_works(worker);
2337affee4b2STejun Heo 		} else {
2338c8e55f36STejun Heo 			move_linked_works(work, &worker->scheduled, NULL);
2339affee4b2STejun Heo 			process_scheduled_works(worker);
2340affee4b2STejun Heo 		}
234163d95a91STejun Heo 	} while (keep_working(pool));
2342affee4b2STejun Heo 
2343e22bee78STejun Heo 	worker_set_flags(worker, WORKER_PREP, false);
2344d313dd85STejun Heo sleep:
234563d95a91STejun Heo 	if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
2346e22bee78STejun Heo 		goto recheck;
2347d313dd85STejun Heo 
2348c8e55f36STejun Heo 	/*
2349d565ed63STejun Heo 	 * pool->lock is held and there's no work to process and no need to
2350d565ed63STejun Heo 	 * manage, sleep.  Workers are woken up only while holding
2351d565ed63STejun Heo 	 * pool->lock or from local cpu, so setting the current state
2352d565ed63STejun Heo 	 * before releasing pool->lock is enough to prevent losing any
2353d565ed63STejun Heo 	 * event.
2354c8e55f36STejun Heo 	 */
2355c8e55f36STejun Heo 	worker_enter_idle(worker);
2356c8e55f36STejun Heo 	__set_current_state(TASK_INTERRUPTIBLE);
2357d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
23581da177e4SLinus Torvalds 	schedule();
2359c8e55f36STejun Heo 	goto woke_up;
23601da177e4SLinus Torvalds }
23611da177e4SLinus Torvalds 
2362e22bee78STejun Heo /**
2363e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
2364111c225aSTejun Heo  * @__rescuer: self
2365e22bee78STejun Heo  *
2366e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
2367493008a8STejun Heo  * workqueue which has WQ_MEM_RECLAIM set.
2368e22bee78STejun Heo  *
2369706026c2STejun Heo  * Regular work processing on a pool may block trying to create a new
2370e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
2371e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
2372e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2373e22bee78STejun Heo  * the problem rescuer solves.
2374e22bee78STejun Heo  *
2375706026c2STejun Heo  * When such condition is possible, the pool summons rescuers of all
2376706026c2STejun Heo  * workqueues which have works queued on the pool and let them process
2377e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
2378e22bee78STejun Heo  *
2379e22bee78STejun Heo  * This should happen rarely.
2380e22bee78STejun Heo  */
2381111c225aSTejun Heo static int rescuer_thread(void *__rescuer)
2382e22bee78STejun Heo {
2383111c225aSTejun Heo 	struct worker *rescuer = __rescuer;
2384111c225aSTejun Heo 	struct workqueue_struct *wq = rescuer->rescue_wq;
2385e22bee78STejun Heo 	struct list_head *scheduled = &rescuer->scheduled;
2386e22bee78STejun Heo 
2387e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
2388111c225aSTejun Heo 
2389111c225aSTejun Heo 	/*
2390111c225aSTejun Heo 	 * Mark rescuer as worker too.  As WORKER_PREP is never cleared, it
2391111c225aSTejun Heo 	 * doesn't participate in concurrency management.
2392111c225aSTejun Heo 	 */
2393111c225aSTejun Heo 	rescuer->task->flags |= PF_WQ_WORKER;
2394e22bee78STejun Heo repeat:
2395e22bee78STejun Heo 	set_current_state(TASK_INTERRUPTIBLE);
23961da177e4SLinus Torvalds 
2397412d32e6SMike Galbraith 	if (kthread_should_stop()) {
2398412d32e6SMike Galbraith 		__set_current_state(TASK_RUNNING);
2399111c225aSTejun Heo 		rescuer->task->flags &= ~PF_WQ_WORKER;
2400e22bee78STejun Heo 		return 0;
2401412d32e6SMike Galbraith 	}
24021da177e4SLinus Torvalds 
2403493a1724STejun Heo 	/* see whether any pwq is asking for help */
2404493a1724STejun Heo 	spin_lock_irq(&workqueue_lock);
2405493a1724STejun Heo 
2406493a1724STejun Heo 	while (!list_empty(&wq->maydays)) {
2407493a1724STejun Heo 		struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2408493a1724STejun Heo 					struct pool_workqueue, mayday_node);
2409112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
2410e22bee78STejun Heo 		struct work_struct *work, *n;
2411e22bee78STejun Heo 
2412e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
2413493a1724STejun Heo 		list_del_init(&pwq->mayday_node);
2414493a1724STejun Heo 
2415493a1724STejun Heo 		spin_unlock_irq(&workqueue_lock);
2416e22bee78STejun Heo 
2417e22bee78STejun Heo 		/* migrate to the target cpu if possible */
2418f36dc67bSLai Jiangshan 		worker_maybe_bind_and_lock(pool);
2419b3104104SLai Jiangshan 		rescuer->pool = pool;
2420e22bee78STejun Heo 
2421e22bee78STejun Heo 		/*
2422e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
2423e22bee78STejun Heo 		 * process'em.
2424e22bee78STejun Heo 		 */
24256183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&rescuer->scheduled));
2426bd7bdd43STejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry)
2427112202d9STejun Heo 			if (get_work_pwq(work) == pwq)
2428e22bee78STejun Heo 				move_linked_works(work, scheduled, &n);
2429e22bee78STejun Heo 
2430e22bee78STejun Heo 		process_scheduled_works(rescuer);
24317576958aSTejun Heo 
24327576958aSTejun Heo 		/*
2433d565ed63STejun Heo 		 * Leave this pool.  If keep_working() is %true, notify a
24347576958aSTejun Heo 		 * regular worker; otherwise, we end up with 0 concurrency
24357576958aSTejun Heo 		 * and stalling the execution.
24367576958aSTejun Heo 		 */
243763d95a91STejun Heo 		if (keep_working(pool))
243863d95a91STejun Heo 			wake_up_worker(pool);
24397576958aSTejun Heo 
2440b3104104SLai Jiangshan 		rescuer->pool = NULL;
2441493a1724STejun Heo 		spin_unlock(&pool->lock);
2442493a1724STejun Heo 		spin_lock(&workqueue_lock);
24431da177e4SLinus Torvalds 	}
24441da177e4SLinus Torvalds 
2445493a1724STejun Heo 	spin_unlock_irq(&workqueue_lock);
2446493a1724STejun Heo 
2447111c225aSTejun Heo 	/* rescuers should never participate in concurrency management */
2448111c225aSTejun Heo 	WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2449e22bee78STejun Heo 	schedule();
2450e22bee78STejun Heo 	goto repeat;
24511da177e4SLinus Torvalds }
24521da177e4SLinus Torvalds 
2453fc2e4d70SOleg Nesterov struct wq_barrier {
2454fc2e4d70SOleg Nesterov 	struct work_struct	work;
2455fc2e4d70SOleg Nesterov 	struct completion	done;
2456fc2e4d70SOleg Nesterov };
2457fc2e4d70SOleg Nesterov 
2458fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
2459fc2e4d70SOleg Nesterov {
2460fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2461fc2e4d70SOleg Nesterov 	complete(&barr->done);
2462fc2e4d70SOleg Nesterov }
2463fc2e4d70SOleg Nesterov 
24644690c4abSTejun Heo /**
24654690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
2466112202d9STejun Heo  * @pwq: pwq to insert barrier into
24674690c4abSTejun Heo  * @barr: wq_barrier to insert
2468affee4b2STejun Heo  * @target: target work to attach @barr to
2469affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
24704690c4abSTejun Heo  *
2471affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
2472affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
2473affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
2474affee4b2STejun Heo  * cpu.
2475affee4b2STejun Heo  *
2476affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
2477affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
2478affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
2479affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
2480affee4b2STejun Heo  * after a work with LINKED flag set.
2481affee4b2STejun Heo  *
2482affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
2483112202d9STejun Heo  * underneath us, so we can't reliably determine pwq from @target.
24844690c4abSTejun Heo  *
24854690c4abSTejun Heo  * CONTEXT:
2486d565ed63STejun Heo  * spin_lock_irq(pool->lock).
24874690c4abSTejun Heo  */
2488112202d9STejun Heo static void insert_wq_barrier(struct pool_workqueue *pwq,
2489affee4b2STejun Heo 			      struct wq_barrier *barr,
2490affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
2491fc2e4d70SOleg Nesterov {
2492affee4b2STejun Heo 	struct list_head *head;
2493affee4b2STejun Heo 	unsigned int linked = 0;
2494affee4b2STejun Heo 
2495dc186ad7SThomas Gleixner 	/*
2496d565ed63STejun Heo 	 * debugobject calls are safe here even with pool->lock locked
2497dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
2498dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
2499dc186ad7SThomas Gleixner 	 * might deadlock.
2500dc186ad7SThomas Gleixner 	 */
2501ca1cab37SAndrew Morton 	INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
250222df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2503fc2e4d70SOleg Nesterov 	init_completion(&barr->done);
250483c22520SOleg Nesterov 
2505affee4b2STejun Heo 	/*
2506affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
2507affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
2508affee4b2STejun Heo 	 */
2509affee4b2STejun Heo 	if (worker)
2510affee4b2STejun Heo 		head = worker->scheduled.next;
2511affee4b2STejun Heo 	else {
2512affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
2513affee4b2STejun Heo 
2514affee4b2STejun Heo 		head = target->entry.next;
2515affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
2516affee4b2STejun Heo 		linked = *bits & WORK_STRUCT_LINKED;
2517affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
2518affee4b2STejun Heo 	}
2519affee4b2STejun Heo 
2520dc186ad7SThomas Gleixner 	debug_work_activate(&barr->work);
2521112202d9STejun Heo 	insert_work(pwq, &barr->work, head,
2522affee4b2STejun Heo 		    work_color_to_flags(WORK_NO_COLOR) | linked);
2523fc2e4d70SOleg Nesterov }
2524fc2e4d70SOleg Nesterov 
252573f53c4aSTejun Heo /**
2526112202d9STejun Heo  * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
252773f53c4aSTejun Heo  * @wq: workqueue being flushed
252873f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
252973f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
253073f53c4aSTejun Heo  *
2531112202d9STejun Heo  * Prepare pwqs for workqueue flushing.
253273f53c4aSTejun Heo  *
2533112202d9STejun Heo  * If @flush_color is non-negative, flush_color on all pwqs should be
2534112202d9STejun Heo  * -1.  If no pwq has in-flight commands at the specified color, all
2535112202d9STejun Heo  * pwq->flush_color's stay at -1 and %false is returned.  If any pwq
2536112202d9STejun Heo  * has in flight commands, its pwq->flush_color is set to
2537112202d9STejun Heo  * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
253873f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
253973f53c4aSTejun Heo  *
254073f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
254173f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
254273f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
254373f53c4aSTejun Heo  * is returned.
254473f53c4aSTejun Heo  *
2545112202d9STejun Heo  * If @work_color is non-negative, all pwqs should have the same
254673f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
254773f53c4aSTejun Heo  * advanced to @work_color.
254873f53c4aSTejun Heo  *
254973f53c4aSTejun Heo  * CONTEXT:
255073f53c4aSTejun Heo  * mutex_lock(wq->flush_mutex).
255173f53c4aSTejun Heo  *
255273f53c4aSTejun Heo  * RETURNS:
255373f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
255473f53c4aSTejun Heo  * otherwise.
255573f53c4aSTejun Heo  */
2556112202d9STejun Heo static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
255773f53c4aSTejun Heo 				      int flush_color, int work_color)
25581da177e4SLinus Torvalds {
255973f53c4aSTejun Heo 	bool wait = false;
256049e3cf44STejun Heo 	struct pool_workqueue *pwq;
25611da177e4SLinus Torvalds 
256273f53c4aSTejun Heo 	if (flush_color >= 0) {
25636183c009STejun Heo 		WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2564112202d9STejun Heo 		atomic_set(&wq->nr_pwqs_to_flush, 1);
2565dc186ad7SThomas Gleixner 	}
256614441960SOleg Nesterov 
256776af4d93STejun Heo 	local_irq_disable();
256876af4d93STejun Heo 
256949e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2570112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
25711da177e4SLinus Torvalds 
257276af4d93STejun Heo 		spin_lock(&pool->lock);
257373f53c4aSTejun Heo 
257473f53c4aSTejun Heo 		if (flush_color >= 0) {
25756183c009STejun Heo 			WARN_ON_ONCE(pwq->flush_color != -1);
257673f53c4aSTejun Heo 
2577112202d9STejun Heo 			if (pwq->nr_in_flight[flush_color]) {
2578112202d9STejun Heo 				pwq->flush_color = flush_color;
2579112202d9STejun Heo 				atomic_inc(&wq->nr_pwqs_to_flush);
258073f53c4aSTejun Heo 				wait = true;
25811da177e4SLinus Torvalds 			}
258273f53c4aSTejun Heo 		}
258373f53c4aSTejun Heo 
258473f53c4aSTejun Heo 		if (work_color >= 0) {
25856183c009STejun Heo 			WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2586112202d9STejun Heo 			pwq->work_color = work_color;
258773f53c4aSTejun Heo 		}
258873f53c4aSTejun Heo 
258976af4d93STejun Heo 		spin_unlock(&pool->lock);
25901da177e4SLinus Torvalds 	}
25911da177e4SLinus Torvalds 
259276af4d93STejun Heo 	local_irq_enable();
259376af4d93STejun Heo 
2594112202d9STejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
259573f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
259673f53c4aSTejun Heo 
259773f53c4aSTejun Heo 	return wait;
259883c22520SOleg Nesterov }
25991da177e4SLinus Torvalds 
26000fcb78c2SRolf Eike Beer /**
26011da177e4SLinus Torvalds  * flush_workqueue - ensure that any scheduled work has run to completion.
26020fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
26031da177e4SLinus Torvalds  *
2604c5aa87bbSTejun Heo  * This function sleeps until all work items which were queued on entry
2605c5aa87bbSTejun Heo  * have finished execution, but it is not livelocked by new incoming ones.
26061da177e4SLinus Torvalds  */
26077ad5b3a5SHarvey Harrison void flush_workqueue(struct workqueue_struct *wq)
26081da177e4SLinus Torvalds {
260973f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
261073f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
261173f53c4aSTejun Heo 		.flush_color = -1,
261273f53c4aSTejun Heo 		.done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
261373f53c4aSTejun Heo 	};
261473f53c4aSTejun Heo 	int next_color;
2615b1f4ec17SOleg Nesterov 
26163295f0efSIngo Molnar 	lock_map_acquire(&wq->lockdep_map);
26173295f0efSIngo Molnar 	lock_map_release(&wq->lockdep_map);
261873f53c4aSTejun Heo 
261973f53c4aSTejun Heo 	mutex_lock(&wq->flush_mutex);
262073f53c4aSTejun Heo 
262173f53c4aSTejun Heo 	/*
262273f53c4aSTejun Heo 	 * Start-to-wait phase
262373f53c4aSTejun Heo 	 */
262473f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
262573f53c4aSTejun Heo 
262673f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
262773f53c4aSTejun Heo 		/*
262873f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
262973f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
263073f53c4aSTejun Heo 		 * by one.
263173f53c4aSTejun Heo 		 */
26326183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
263373f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
263473f53c4aSTejun Heo 		wq->work_color = next_color;
263573f53c4aSTejun Heo 
263673f53c4aSTejun Heo 		if (!wq->first_flusher) {
263773f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
26386183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
263973f53c4aSTejun Heo 
264073f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
264173f53c4aSTejun Heo 
2642112202d9STejun Heo 			if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
264373f53c4aSTejun Heo 						       wq->work_color)) {
264473f53c4aSTejun Heo 				/* nothing to flush, done */
264573f53c4aSTejun Heo 				wq->flush_color = next_color;
264673f53c4aSTejun Heo 				wq->first_flusher = NULL;
264773f53c4aSTejun Heo 				goto out_unlock;
264873f53c4aSTejun Heo 			}
264973f53c4aSTejun Heo 		} else {
265073f53c4aSTejun Heo 			/* wait in queue */
26516183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
265273f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
2653112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
265473f53c4aSTejun Heo 		}
265573f53c4aSTejun Heo 	} else {
265673f53c4aSTejun Heo 		/*
265773f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
265873f53c4aSTejun Heo 		 * The next flush completion will assign us
265973f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
266073f53c4aSTejun Heo 		 */
266173f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
266273f53c4aSTejun Heo 	}
266373f53c4aSTejun Heo 
266473f53c4aSTejun Heo 	mutex_unlock(&wq->flush_mutex);
266573f53c4aSTejun Heo 
266673f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
266773f53c4aSTejun Heo 
266873f53c4aSTejun Heo 	/*
266973f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
267073f53c4aSTejun Heo 	 *
267173f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
267273f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
267373f53c4aSTejun Heo 	 */
267473f53c4aSTejun Heo 	if (wq->first_flusher != &this_flusher)
267573f53c4aSTejun Heo 		return;
267673f53c4aSTejun Heo 
267773f53c4aSTejun Heo 	mutex_lock(&wq->flush_mutex);
267873f53c4aSTejun Heo 
26794ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
26804ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
26814ce48b37STejun Heo 		goto out_unlock;
26824ce48b37STejun Heo 
268373f53c4aSTejun Heo 	wq->first_flusher = NULL;
268473f53c4aSTejun Heo 
26856183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&this_flusher.list));
26866183c009STejun Heo 	WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
268773f53c4aSTejun Heo 
268873f53c4aSTejun Heo 	while (true) {
268973f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
269073f53c4aSTejun Heo 
269173f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
269273f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
269373f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
269473f53c4aSTejun Heo 				break;
269573f53c4aSTejun Heo 			list_del_init(&next->list);
269673f53c4aSTejun Heo 			complete(&next->done);
269773f53c4aSTejun Heo 		}
269873f53c4aSTejun Heo 
26996183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
270073f53c4aSTejun Heo 			     wq->flush_color != work_next_color(wq->work_color));
270173f53c4aSTejun Heo 
270273f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
270373f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
270473f53c4aSTejun Heo 
270573f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
270673f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
270773f53c4aSTejun Heo 			/*
270873f53c4aSTejun Heo 			 * Assign the same color to all overflowed
270973f53c4aSTejun Heo 			 * flushers, advance work_color and append to
271073f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
271173f53c4aSTejun Heo 			 * phase for these overflowed flushers.
271273f53c4aSTejun Heo 			 */
271373f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
271473f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
271573f53c4aSTejun Heo 
271673f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
271773f53c4aSTejun Heo 
271873f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
271973f53c4aSTejun Heo 					      &wq->flusher_queue);
2720112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
272173f53c4aSTejun Heo 		}
272273f53c4aSTejun Heo 
272373f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
27246183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != wq->work_color);
272573f53c4aSTejun Heo 			break;
272673f53c4aSTejun Heo 		}
272773f53c4aSTejun Heo 
272873f53c4aSTejun Heo 		/*
272973f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
2730112202d9STejun Heo 		 * the new first flusher and arm pwqs.
273173f53c4aSTejun Heo 		 */
27326183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color == wq->work_color);
27336183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color != next->flush_color);
273473f53c4aSTejun Heo 
273573f53c4aSTejun Heo 		list_del_init(&next->list);
273673f53c4aSTejun Heo 		wq->first_flusher = next;
273773f53c4aSTejun Heo 
2738112202d9STejun Heo 		if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
273973f53c4aSTejun Heo 			break;
274073f53c4aSTejun Heo 
274173f53c4aSTejun Heo 		/*
274273f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
274373f53c4aSTejun Heo 		 * flusher and repeat cascading.
274473f53c4aSTejun Heo 		 */
274573f53c4aSTejun Heo 		wq->first_flusher = NULL;
274673f53c4aSTejun Heo 	}
274773f53c4aSTejun Heo 
274873f53c4aSTejun Heo out_unlock:
274973f53c4aSTejun Heo 	mutex_unlock(&wq->flush_mutex);
27501da177e4SLinus Torvalds }
2751ae90dd5dSDave Jones EXPORT_SYMBOL_GPL(flush_workqueue);
27521da177e4SLinus Torvalds 
27539c5a2ba7STejun Heo /**
27549c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
27559c5a2ba7STejun Heo  * @wq: workqueue to drain
27569c5a2ba7STejun Heo  *
27579c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
27589c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
27599c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
27609c5a2ba7STejun Heo  * repeatedly until it becomes empty.  The number of flushing is detemined
27619c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
27629c5a2ba7STejun Heo  * takes too long.
27639c5a2ba7STejun Heo  */
27649c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
27659c5a2ba7STejun Heo {
27669c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
276749e3cf44STejun Heo 	struct pool_workqueue *pwq;
27689c5a2ba7STejun Heo 
27699c5a2ba7STejun Heo 	/*
27709c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
27719c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
2772618b01ebSTejun Heo 	 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
27739c5a2ba7STejun Heo 	 */
2774*5bcab335STejun Heo 	mutex_lock(&wq_mutex);
27759c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
2776618b01ebSTejun Heo 		wq->flags |= __WQ_DRAINING;
2777*5bcab335STejun Heo 	mutex_unlock(&wq_mutex);
27789c5a2ba7STejun Heo reflush:
27799c5a2ba7STejun Heo 	flush_workqueue(wq);
27809c5a2ba7STejun Heo 
278176af4d93STejun Heo 	local_irq_disable();
278276af4d93STejun Heo 
278349e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2784fa2563e4SThomas Tuttle 		bool drained;
27859c5a2ba7STejun Heo 
278676af4d93STejun Heo 		spin_lock(&pwq->pool->lock);
2787112202d9STejun Heo 		drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
278876af4d93STejun Heo 		spin_unlock(&pwq->pool->lock);
2789fa2563e4SThomas Tuttle 
2790fa2563e4SThomas Tuttle 		if (drained)
27919c5a2ba7STejun Heo 			continue;
27929c5a2ba7STejun Heo 
27939c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
27949c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2795c5aa87bbSTejun Heo 			pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
27969c5a2ba7STejun Heo 				wq->name, flush_cnt);
279776af4d93STejun Heo 
279876af4d93STejun Heo 		local_irq_enable();
27999c5a2ba7STejun Heo 		goto reflush;
28009c5a2ba7STejun Heo 	}
28019c5a2ba7STejun Heo 
2802*5bcab335STejun Heo 	local_irq_enable();
2803*5bcab335STejun Heo 
2804*5bcab335STejun Heo 	mutex_lock(&wq_mutex);
28059c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
2806618b01ebSTejun Heo 		wq->flags &= ~__WQ_DRAINING;
2807*5bcab335STejun Heo 	mutex_unlock(&wq_mutex);
28089c5a2ba7STejun Heo }
28099c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
28109c5a2ba7STejun Heo 
2811606a5020STejun Heo static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2812baf59022STejun Heo {
2813baf59022STejun Heo 	struct worker *worker = NULL;
2814c9e7cf27STejun Heo 	struct worker_pool *pool;
2815112202d9STejun Heo 	struct pool_workqueue *pwq;
2816baf59022STejun Heo 
2817baf59022STejun Heo 	might_sleep();
2818baf59022STejun Heo 
2819fa1b54e6STejun Heo 	local_irq_disable();
2820fa1b54e6STejun Heo 	pool = get_work_pool(work);
2821fa1b54e6STejun Heo 	if (!pool) {
2822fa1b54e6STejun Heo 		local_irq_enable();
2823fa1b54e6STejun Heo 		return false;
2824fa1b54e6STejun Heo 	}
2825fa1b54e6STejun Heo 
2826fa1b54e6STejun Heo 	spin_lock(&pool->lock);
28270b3dae68SLai Jiangshan 	/* see the comment in try_to_grab_pending() with the same code */
2828112202d9STejun Heo 	pwq = get_work_pwq(work);
2829112202d9STejun Heo 	if (pwq) {
2830112202d9STejun Heo 		if (unlikely(pwq->pool != pool))
2831baf59022STejun Heo 			goto already_gone;
2832606a5020STejun Heo 	} else {
2833c9e7cf27STejun Heo 		worker = find_worker_executing_work(pool, work);
2834baf59022STejun Heo 		if (!worker)
2835baf59022STejun Heo 			goto already_gone;
2836112202d9STejun Heo 		pwq = worker->current_pwq;
2837606a5020STejun Heo 	}
2838baf59022STejun Heo 
2839112202d9STejun Heo 	insert_wq_barrier(pwq, barr, work, worker);
2840d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2841baf59022STejun Heo 
2842e159489bSTejun Heo 	/*
2843e159489bSTejun Heo 	 * If @max_active is 1 or rescuer is in use, flushing another work
2844e159489bSTejun Heo 	 * item on the same workqueue may lead to deadlock.  Make sure the
2845e159489bSTejun Heo 	 * flusher is not running on the same workqueue by verifying write
2846e159489bSTejun Heo 	 * access.
2847e159489bSTejun Heo 	 */
2848493008a8STejun Heo 	if (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)
2849112202d9STejun Heo 		lock_map_acquire(&pwq->wq->lockdep_map);
2850e159489bSTejun Heo 	else
2851112202d9STejun Heo 		lock_map_acquire_read(&pwq->wq->lockdep_map);
2852112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
2853e159489bSTejun Heo 
2854baf59022STejun Heo 	return true;
2855baf59022STejun Heo already_gone:
2856d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2857baf59022STejun Heo 	return false;
2858baf59022STejun Heo }
2859baf59022STejun Heo 
2860db700897SOleg Nesterov /**
2861401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
2862401a8d04STejun Heo  * @work: the work to flush
2863db700897SOleg Nesterov  *
2864606a5020STejun Heo  * Wait until @work has finished execution.  @work is guaranteed to be idle
2865606a5020STejun Heo  * on return if it hasn't been requeued since flush started.
2866401a8d04STejun Heo  *
2867401a8d04STejun Heo  * RETURNS:
2868401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
2869401a8d04STejun Heo  * %false if it was already idle.
2870db700897SOleg Nesterov  */
2871401a8d04STejun Heo bool flush_work(struct work_struct *work)
2872db700897SOleg Nesterov {
2873db700897SOleg Nesterov 	struct wq_barrier barr;
2874db700897SOleg Nesterov 
28750976dfc1SStephen Boyd 	lock_map_acquire(&work->lockdep_map);
28760976dfc1SStephen Boyd 	lock_map_release(&work->lockdep_map);
28770976dfc1SStephen Boyd 
2878606a5020STejun Heo 	if (start_flush_work(work, &barr)) {
2879db700897SOleg Nesterov 		wait_for_completion(&barr.done);
2880dc186ad7SThomas Gleixner 		destroy_work_on_stack(&barr.work);
2881401a8d04STejun Heo 		return true;
2882606a5020STejun Heo 	} else {
2883401a8d04STejun Heo 		return false;
2884db700897SOleg Nesterov 	}
2885606a5020STejun Heo }
2886db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
2887db700897SOleg Nesterov 
288836e227d2STejun Heo static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2889401a8d04STejun Heo {
2890bbb68dfaSTejun Heo 	unsigned long flags;
28911f1f642eSOleg Nesterov 	int ret;
28921f1f642eSOleg Nesterov 
28931f1f642eSOleg Nesterov 	do {
2894bbb68dfaSTejun Heo 		ret = try_to_grab_pending(work, is_dwork, &flags);
2895bbb68dfaSTejun Heo 		/*
2896bbb68dfaSTejun Heo 		 * If someone else is canceling, wait for the same event it
2897bbb68dfaSTejun Heo 		 * would be waiting for before retrying.
2898bbb68dfaSTejun Heo 		 */
2899bbb68dfaSTejun Heo 		if (unlikely(ret == -ENOENT))
2900606a5020STejun Heo 			flush_work(work);
29011f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
29021f1f642eSOleg Nesterov 
2903bbb68dfaSTejun Heo 	/* tell other tasks trying to grab @work to back off */
2904bbb68dfaSTejun Heo 	mark_work_canceling(work);
2905bbb68dfaSTejun Heo 	local_irq_restore(flags);
2906bbb68dfaSTejun Heo 
2907606a5020STejun Heo 	flush_work(work);
29087a22ad75STejun Heo 	clear_work_data(work);
29091f1f642eSOleg Nesterov 	return ret;
29101f1f642eSOleg Nesterov }
29111f1f642eSOleg Nesterov 
29126e84d644SOleg Nesterov /**
2913401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
2914401a8d04STejun Heo  * @work: the work to cancel
29156e84d644SOleg Nesterov  *
2916401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
2917401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
2918401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
2919401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
29201f1f642eSOleg Nesterov  *
2921401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
2922401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
29236e84d644SOleg Nesterov  *
2924401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
29256e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
2926401a8d04STejun Heo  *
2927401a8d04STejun Heo  * RETURNS:
2928401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
29296e84d644SOleg Nesterov  */
2930401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
29316e84d644SOleg Nesterov {
293236e227d2STejun Heo 	return __cancel_work_timer(work, false);
2933b89deed3SOleg Nesterov }
293428e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
2935b89deed3SOleg Nesterov 
29366e84d644SOleg Nesterov /**
2937401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
2938401a8d04STejun Heo  * @dwork: the delayed work to flush
29396e84d644SOleg Nesterov  *
2940401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
2941401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
2942401a8d04STejun Heo  * considers the last queueing instance of @dwork.
29431f1f642eSOleg Nesterov  *
2944401a8d04STejun Heo  * RETURNS:
2945401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
2946401a8d04STejun Heo  * %false if it was already idle.
29476e84d644SOleg Nesterov  */
2948401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
2949401a8d04STejun Heo {
29508930cabaSTejun Heo 	local_irq_disable();
2951401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
295260c057bcSLai Jiangshan 		__queue_work(dwork->cpu, dwork->wq, &dwork->work);
29538930cabaSTejun Heo 	local_irq_enable();
2954401a8d04STejun Heo 	return flush_work(&dwork->work);
2955401a8d04STejun Heo }
2956401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
2957401a8d04STejun Heo 
2958401a8d04STejun Heo /**
295957b30ae7STejun Heo  * cancel_delayed_work - cancel a delayed work
296057b30ae7STejun Heo  * @dwork: delayed_work to cancel
296109383498STejun Heo  *
296257b30ae7STejun Heo  * Kill off a pending delayed_work.  Returns %true if @dwork was pending
296357b30ae7STejun Heo  * and canceled; %false if wasn't pending.  Note that the work callback
296457b30ae7STejun Heo  * function may still be running on return, unless it returns %true and the
296557b30ae7STejun Heo  * work doesn't re-arm itself.  Explicitly flush or use
296657b30ae7STejun Heo  * cancel_delayed_work_sync() to wait on it.
296709383498STejun Heo  *
296857b30ae7STejun Heo  * This function is safe to call from any context including IRQ handler.
296909383498STejun Heo  */
297057b30ae7STejun Heo bool cancel_delayed_work(struct delayed_work *dwork)
297109383498STejun Heo {
297257b30ae7STejun Heo 	unsigned long flags;
297357b30ae7STejun Heo 	int ret;
297457b30ae7STejun Heo 
297557b30ae7STejun Heo 	do {
297657b30ae7STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
297757b30ae7STejun Heo 	} while (unlikely(ret == -EAGAIN));
297857b30ae7STejun Heo 
297957b30ae7STejun Heo 	if (unlikely(ret < 0))
298057b30ae7STejun Heo 		return false;
298157b30ae7STejun Heo 
29827c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(&dwork->work,
29837c3eed5cSTejun Heo 					get_work_pool_id(&dwork->work));
298457b30ae7STejun Heo 	local_irq_restore(flags);
2985c0158ca6SDan Magenheimer 	return ret;
298609383498STejun Heo }
298757b30ae7STejun Heo EXPORT_SYMBOL(cancel_delayed_work);
298809383498STejun Heo 
298909383498STejun Heo /**
2990401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2991401a8d04STejun Heo  * @dwork: the delayed work cancel
2992401a8d04STejun Heo  *
2993401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
2994401a8d04STejun Heo  *
2995401a8d04STejun Heo  * RETURNS:
2996401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
2997401a8d04STejun Heo  */
2998401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
29996e84d644SOleg Nesterov {
300036e227d2STejun Heo 	return __cancel_work_timer(&dwork->work, true);
30016e84d644SOleg Nesterov }
3002f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
30031da177e4SLinus Torvalds 
30040fcb78c2SRolf Eike Beer /**
300531ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
3006b6136773SAndrew Morton  * @func: the function to call
3007b6136773SAndrew Morton  *
300831ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
300931ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
3010b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
301131ddd871STejun Heo  *
301231ddd871STejun Heo  * RETURNS:
301331ddd871STejun Heo  * 0 on success, -errno on failure.
3014b6136773SAndrew Morton  */
301565f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
301615316ba8SChristoph Lameter {
301715316ba8SChristoph Lameter 	int cpu;
301838f51568SNamhyung Kim 	struct work_struct __percpu *works;
301915316ba8SChristoph Lameter 
3020b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
3021b6136773SAndrew Morton 	if (!works)
302215316ba8SChristoph Lameter 		return -ENOMEM;
3023b6136773SAndrew Morton 
302495402b38SGautham R Shenoy 	get_online_cpus();
302593981800STejun Heo 
302615316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
30279bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
30289bfb1839SIngo Molnar 
30299bfb1839SIngo Molnar 		INIT_WORK(work, func);
30308de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
303115316ba8SChristoph Lameter 	}
303293981800STejun Heo 
303393981800STejun Heo 	for_each_online_cpu(cpu)
30348616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
303593981800STejun Heo 
303695402b38SGautham R Shenoy 	put_online_cpus();
3037b6136773SAndrew Morton 	free_percpu(works);
303815316ba8SChristoph Lameter 	return 0;
303915316ba8SChristoph Lameter }
304015316ba8SChristoph Lameter 
3041eef6a7d5SAlan Stern /**
3042eef6a7d5SAlan Stern  * flush_scheduled_work - ensure that any scheduled work has run to completion.
3043eef6a7d5SAlan Stern  *
3044eef6a7d5SAlan Stern  * Forces execution of the kernel-global workqueue and blocks until its
3045eef6a7d5SAlan Stern  * completion.
3046eef6a7d5SAlan Stern  *
3047eef6a7d5SAlan Stern  * Think twice before calling this function!  It's very easy to get into
3048eef6a7d5SAlan Stern  * trouble if you don't take great care.  Either of the following situations
3049eef6a7d5SAlan Stern  * will lead to deadlock:
3050eef6a7d5SAlan Stern  *
3051eef6a7d5SAlan Stern  *	One of the work items currently on the workqueue needs to acquire
3052eef6a7d5SAlan Stern  *	a lock held by your code or its caller.
3053eef6a7d5SAlan Stern  *
3054eef6a7d5SAlan Stern  *	Your code is running in the context of a work routine.
3055eef6a7d5SAlan Stern  *
3056eef6a7d5SAlan Stern  * They will be detected by lockdep when they occur, but the first might not
3057eef6a7d5SAlan Stern  * occur very often.  It depends on what work items are on the workqueue and
3058eef6a7d5SAlan Stern  * what locks they need, which you have no control over.
3059eef6a7d5SAlan Stern  *
3060eef6a7d5SAlan Stern  * In most situations flushing the entire workqueue is overkill; you merely
3061eef6a7d5SAlan Stern  * need to know that a particular work item isn't queued and isn't running.
3062eef6a7d5SAlan Stern  * In such cases you should use cancel_delayed_work_sync() or
3063eef6a7d5SAlan Stern  * cancel_work_sync() instead.
3064eef6a7d5SAlan Stern  */
30651da177e4SLinus Torvalds void flush_scheduled_work(void)
30661da177e4SLinus Torvalds {
3067d320c038STejun Heo 	flush_workqueue(system_wq);
30681da177e4SLinus Torvalds }
3069ae90dd5dSDave Jones EXPORT_SYMBOL(flush_scheduled_work);
30701da177e4SLinus Torvalds 
30711da177e4SLinus Torvalds /**
30721fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
30731fa44ecaSJames Bottomley  * @fn:		the function to execute
30741fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
30751fa44ecaSJames Bottomley  *		be available when the work executes)
30761fa44ecaSJames Bottomley  *
30771fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
30781fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
30791fa44ecaSJames Bottomley  *
30801fa44ecaSJames Bottomley  * Returns:	0 - function was executed
30811fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
30821fa44ecaSJames Bottomley  */
308365f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
30841fa44ecaSJames Bottomley {
30851fa44ecaSJames Bottomley 	if (!in_interrupt()) {
308665f27f38SDavid Howells 		fn(&ew->work);
30871fa44ecaSJames Bottomley 		return 0;
30881fa44ecaSJames Bottomley 	}
30891fa44ecaSJames Bottomley 
309065f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
30911fa44ecaSJames Bottomley 	schedule_work(&ew->work);
30921fa44ecaSJames Bottomley 
30931fa44ecaSJames Bottomley 	return 1;
30941fa44ecaSJames Bottomley }
30951fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
30961fa44ecaSJames Bottomley 
3097226223abSTejun Heo #ifdef CONFIG_SYSFS
3098226223abSTejun Heo /*
3099226223abSTejun Heo  * Workqueues with WQ_SYSFS flag set is visible to userland via
3100226223abSTejun Heo  * /sys/bus/workqueue/devices/WQ_NAME.  All visible workqueues have the
3101226223abSTejun Heo  * following attributes.
3102226223abSTejun Heo  *
3103226223abSTejun Heo  *  per_cpu	RO bool	: whether the workqueue is per-cpu or unbound
3104226223abSTejun Heo  *  max_active	RW int	: maximum number of in-flight work items
3105226223abSTejun Heo  *
3106226223abSTejun Heo  * Unbound workqueues have the following extra attributes.
3107226223abSTejun Heo  *
3108226223abSTejun Heo  *  id		RO int	: the associated pool ID
3109226223abSTejun Heo  *  nice	RW int	: nice value of the workers
3110226223abSTejun Heo  *  cpumask	RW mask	: bitmask of allowed CPUs for the workers
3111226223abSTejun Heo  */
3112226223abSTejun Heo struct wq_device {
3113226223abSTejun Heo 	struct workqueue_struct		*wq;
3114226223abSTejun Heo 	struct device			dev;
3115226223abSTejun Heo };
3116226223abSTejun Heo 
3117226223abSTejun Heo static struct workqueue_struct *dev_to_wq(struct device *dev)
3118226223abSTejun Heo {
3119226223abSTejun Heo 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
3120226223abSTejun Heo 
3121226223abSTejun Heo 	return wq_dev->wq;
3122226223abSTejun Heo }
3123226223abSTejun Heo 
3124226223abSTejun Heo static ssize_t wq_per_cpu_show(struct device *dev,
3125226223abSTejun Heo 			       struct device_attribute *attr, char *buf)
3126226223abSTejun Heo {
3127226223abSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
3128226223abSTejun Heo 
3129226223abSTejun Heo 	return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
3130226223abSTejun Heo }
3131226223abSTejun Heo 
3132226223abSTejun Heo static ssize_t wq_max_active_show(struct device *dev,
3133226223abSTejun Heo 				  struct device_attribute *attr, char *buf)
3134226223abSTejun Heo {
3135226223abSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
3136226223abSTejun Heo 
3137226223abSTejun Heo 	return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
3138226223abSTejun Heo }
3139226223abSTejun Heo 
3140226223abSTejun Heo static ssize_t wq_max_active_store(struct device *dev,
3141226223abSTejun Heo 				   struct device_attribute *attr,
3142226223abSTejun Heo 				   const char *buf, size_t count)
3143226223abSTejun Heo {
3144226223abSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
3145226223abSTejun Heo 	int val;
3146226223abSTejun Heo 
3147226223abSTejun Heo 	if (sscanf(buf, "%d", &val) != 1 || val <= 0)
3148226223abSTejun Heo 		return -EINVAL;
3149226223abSTejun Heo 
3150226223abSTejun Heo 	workqueue_set_max_active(wq, val);
3151226223abSTejun Heo 	return count;
3152226223abSTejun Heo }
3153226223abSTejun Heo 
3154226223abSTejun Heo static struct device_attribute wq_sysfs_attrs[] = {
3155226223abSTejun Heo 	__ATTR(per_cpu, 0444, wq_per_cpu_show, NULL),
3156226223abSTejun Heo 	__ATTR(max_active, 0644, wq_max_active_show, wq_max_active_store),
3157226223abSTejun Heo 	__ATTR_NULL,
3158226223abSTejun Heo };
3159226223abSTejun Heo 
3160226223abSTejun Heo static ssize_t wq_pool_id_show(struct device *dev,
3161226223abSTejun Heo 			       struct device_attribute *attr, char *buf)
3162226223abSTejun Heo {
3163226223abSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
3164226223abSTejun Heo 	struct worker_pool *pool;
3165226223abSTejun Heo 	int written;
3166226223abSTejun Heo 
3167226223abSTejun Heo 	rcu_read_lock_sched();
3168226223abSTejun Heo 	pool = first_pwq(wq)->pool;
3169226223abSTejun Heo 	written = scnprintf(buf, PAGE_SIZE, "%d\n", pool->id);
3170226223abSTejun Heo 	rcu_read_unlock_sched();
3171226223abSTejun Heo 
3172226223abSTejun Heo 	return written;
3173226223abSTejun Heo }
3174226223abSTejun Heo 
3175226223abSTejun Heo static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
3176226223abSTejun Heo 			    char *buf)
3177226223abSTejun Heo {
3178226223abSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
3179226223abSTejun Heo 	int written;
3180226223abSTejun Heo 
3181226223abSTejun Heo 	rcu_read_lock_sched();
3182226223abSTejun Heo 	written = scnprintf(buf, PAGE_SIZE, "%d\n",
3183226223abSTejun Heo 			    first_pwq(wq)->pool->attrs->nice);
3184226223abSTejun Heo 	rcu_read_unlock_sched();
3185226223abSTejun Heo 
3186226223abSTejun Heo 	return written;
3187226223abSTejun Heo }
3188226223abSTejun Heo 
3189226223abSTejun Heo /* prepare workqueue_attrs for sysfs store operations */
3190226223abSTejun Heo static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
3191226223abSTejun Heo {
3192226223abSTejun Heo 	struct workqueue_attrs *attrs;
3193226223abSTejun Heo 
3194226223abSTejun Heo 	attrs = alloc_workqueue_attrs(GFP_KERNEL);
3195226223abSTejun Heo 	if (!attrs)
3196226223abSTejun Heo 		return NULL;
3197226223abSTejun Heo 
3198226223abSTejun Heo 	rcu_read_lock_sched();
3199226223abSTejun Heo 	copy_workqueue_attrs(attrs, first_pwq(wq)->pool->attrs);
3200226223abSTejun Heo 	rcu_read_unlock_sched();
3201226223abSTejun Heo 	return attrs;
3202226223abSTejun Heo }
3203226223abSTejun Heo 
3204226223abSTejun Heo static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
3205226223abSTejun Heo 			     const char *buf, size_t count)
3206226223abSTejun Heo {
3207226223abSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
3208226223abSTejun Heo 	struct workqueue_attrs *attrs;
3209226223abSTejun Heo 	int ret;
3210226223abSTejun Heo 
3211226223abSTejun Heo 	attrs = wq_sysfs_prep_attrs(wq);
3212226223abSTejun Heo 	if (!attrs)
3213226223abSTejun Heo 		return -ENOMEM;
3214226223abSTejun Heo 
3215226223abSTejun Heo 	if (sscanf(buf, "%d", &attrs->nice) == 1 &&
3216226223abSTejun Heo 	    attrs->nice >= -20 && attrs->nice <= 19)
3217226223abSTejun Heo 		ret = apply_workqueue_attrs(wq, attrs);
3218226223abSTejun Heo 	else
3219226223abSTejun Heo 		ret = -EINVAL;
3220226223abSTejun Heo 
3221226223abSTejun Heo 	free_workqueue_attrs(attrs);
3222226223abSTejun Heo 	return ret ?: count;
3223226223abSTejun Heo }
3224226223abSTejun Heo 
3225226223abSTejun Heo static ssize_t wq_cpumask_show(struct device *dev,
3226226223abSTejun Heo 			       struct device_attribute *attr, char *buf)
3227226223abSTejun Heo {
3228226223abSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
3229226223abSTejun Heo 	int written;
3230226223abSTejun Heo 
3231226223abSTejun Heo 	rcu_read_lock_sched();
3232226223abSTejun Heo 	written = cpumask_scnprintf(buf, PAGE_SIZE,
3233226223abSTejun Heo 				    first_pwq(wq)->pool->attrs->cpumask);
3234226223abSTejun Heo 	rcu_read_unlock_sched();
3235226223abSTejun Heo 
3236226223abSTejun Heo 	written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
3237226223abSTejun Heo 	return written;
3238226223abSTejun Heo }
3239226223abSTejun Heo 
3240226223abSTejun Heo static ssize_t wq_cpumask_store(struct device *dev,
3241226223abSTejun Heo 				struct device_attribute *attr,
3242226223abSTejun Heo 				const char *buf, size_t count)
3243226223abSTejun Heo {
3244226223abSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
3245226223abSTejun Heo 	struct workqueue_attrs *attrs;
3246226223abSTejun Heo 	int ret;
3247226223abSTejun Heo 
3248226223abSTejun Heo 	attrs = wq_sysfs_prep_attrs(wq);
3249226223abSTejun Heo 	if (!attrs)
3250226223abSTejun Heo 		return -ENOMEM;
3251226223abSTejun Heo 
3252226223abSTejun Heo 	ret = cpumask_parse(buf, attrs->cpumask);
3253226223abSTejun Heo 	if (!ret)
3254226223abSTejun Heo 		ret = apply_workqueue_attrs(wq, attrs);
3255226223abSTejun Heo 
3256226223abSTejun Heo 	free_workqueue_attrs(attrs);
3257226223abSTejun Heo 	return ret ?: count;
3258226223abSTejun Heo }
3259226223abSTejun Heo 
3260226223abSTejun Heo static struct device_attribute wq_sysfs_unbound_attrs[] = {
3261226223abSTejun Heo 	__ATTR(pool_id, 0444, wq_pool_id_show, NULL),
3262226223abSTejun Heo 	__ATTR(nice, 0644, wq_nice_show, wq_nice_store),
3263226223abSTejun Heo 	__ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
3264226223abSTejun Heo 	__ATTR_NULL,
3265226223abSTejun Heo };
3266226223abSTejun Heo 
3267226223abSTejun Heo static struct bus_type wq_subsys = {
3268226223abSTejun Heo 	.name				= "workqueue",
3269226223abSTejun Heo 	.dev_attrs			= wq_sysfs_attrs,
3270226223abSTejun Heo };
3271226223abSTejun Heo 
3272226223abSTejun Heo static int __init wq_sysfs_init(void)
3273226223abSTejun Heo {
3274226223abSTejun Heo 	return subsys_virtual_register(&wq_subsys, NULL);
3275226223abSTejun Heo }
3276226223abSTejun Heo core_initcall(wq_sysfs_init);
3277226223abSTejun Heo 
3278226223abSTejun Heo static void wq_device_release(struct device *dev)
3279226223abSTejun Heo {
3280226223abSTejun Heo 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
3281226223abSTejun Heo 
3282226223abSTejun Heo 	kfree(wq_dev);
3283226223abSTejun Heo }
3284226223abSTejun Heo 
3285226223abSTejun Heo /**
3286226223abSTejun Heo  * workqueue_sysfs_register - make a workqueue visible in sysfs
3287226223abSTejun Heo  * @wq: the workqueue to register
3288226223abSTejun Heo  *
3289226223abSTejun Heo  * Expose @wq in sysfs under /sys/bus/workqueue/devices.
3290226223abSTejun Heo  * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
3291226223abSTejun Heo  * which is the preferred method.
3292226223abSTejun Heo  *
3293226223abSTejun Heo  * Workqueue user should use this function directly iff it wants to apply
3294226223abSTejun Heo  * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
3295226223abSTejun Heo  * apply_workqueue_attrs() may race against userland updating the
3296226223abSTejun Heo  * attributes.
3297226223abSTejun Heo  *
3298226223abSTejun Heo  * Returns 0 on success, -errno on failure.
3299226223abSTejun Heo  */
3300226223abSTejun Heo int workqueue_sysfs_register(struct workqueue_struct *wq)
3301226223abSTejun Heo {
3302226223abSTejun Heo 	struct wq_device *wq_dev;
3303226223abSTejun Heo 	int ret;
3304226223abSTejun Heo 
3305226223abSTejun Heo 	/*
3306226223abSTejun Heo 	 * Adjusting max_active or creating new pwqs by applyting
3307226223abSTejun Heo 	 * attributes breaks ordering guarantee.  Disallow exposing ordered
3308226223abSTejun Heo 	 * workqueues.
3309226223abSTejun Heo 	 */
3310226223abSTejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED))
3311226223abSTejun Heo 		return -EINVAL;
3312226223abSTejun Heo 
3313226223abSTejun Heo 	wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
3314226223abSTejun Heo 	if (!wq_dev)
3315226223abSTejun Heo 		return -ENOMEM;
3316226223abSTejun Heo 
3317226223abSTejun Heo 	wq_dev->wq = wq;
3318226223abSTejun Heo 	wq_dev->dev.bus = &wq_subsys;
3319226223abSTejun Heo 	wq_dev->dev.init_name = wq->name;
3320226223abSTejun Heo 	wq_dev->dev.release = wq_device_release;
3321226223abSTejun Heo 
3322226223abSTejun Heo 	/*
3323226223abSTejun Heo 	 * unbound_attrs are created separately.  Suppress uevent until
3324226223abSTejun Heo 	 * everything is ready.
3325226223abSTejun Heo 	 */
3326226223abSTejun Heo 	dev_set_uevent_suppress(&wq_dev->dev, true);
3327226223abSTejun Heo 
3328226223abSTejun Heo 	ret = device_register(&wq_dev->dev);
3329226223abSTejun Heo 	if (ret) {
3330226223abSTejun Heo 		kfree(wq_dev);
3331226223abSTejun Heo 		wq->wq_dev = NULL;
3332226223abSTejun Heo 		return ret;
3333226223abSTejun Heo 	}
3334226223abSTejun Heo 
3335226223abSTejun Heo 	if (wq->flags & WQ_UNBOUND) {
3336226223abSTejun Heo 		struct device_attribute *attr;
3337226223abSTejun Heo 
3338226223abSTejun Heo 		for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
3339226223abSTejun Heo 			ret = device_create_file(&wq_dev->dev, attr);
3340226223abSTejun Heo 			if (ret) {
3341226223abSTejun Heo 				device_unregister(&wq_dev->dev);
3342226223abSTejun Heo 				wq->wq_dev = NULL;
3343226223abSTejun Heo 				return ret;
3344226223abSTejun Heo 			}
3345226223abSTejun Heo 		}
3346226223abSTejun Heo 	}
3347226223abSTejun Heo 
3348226223abSTejun Heo 	kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
3349226223abSTejun Heo 	return 0;
3350226223abSTejun Heo }
3351226223abSTejun Heo 
3352226223abSTejun Heo /**
3353226223abSTejun Heo  * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
3354226223abSTejun Heo  * @wq: the workqueue to unregister
3355226223abSTejun Heo  *
3356226223abSTejun Heo  * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
3357226223abSTejun Heo  */
3358226223abSTejun Heo static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
3359226223abSTejun Heo {
3360226223abSTejun Heo 	struct wq_device *wq_dev = wq->wq_dev;
3361226223abSTejun Heo 
3362226223abSTejun Heo 	if (!wq->wq_dev)
3363226223abSTejun Heo 		return;
3364226223abSTejun Heo 
3365226223abSTejun Heo 	wq->wq_dev = NULL;
3366226223abSTejun Heo 	device_unregister(&wq_dev->dev);
3367226223abSTejun Heo }
3368226223abSTejun Heo #else	/* CONFIG_SYSFS */
3369226223abSTejun Heo static void workqueue_sysfs_unregister(struct workqueue_struct *wq)	{ }
3370226223abSTejun Heo #endif	/* CONFIG_SYSFS */
3371226223abSTejun Heo 
33727a4e344cSTejun Heo /**
33737a4e344cSTejun Heo  * free_workqueue_attrs - free a workqueue_attrs
33747a4e344cSTejun Heo  * @attrs: workqueue_attrs to free
33757a4e344cSTejun Heo  *
33767a4e344cSTejun Heo  * Undo alloc_workqueue_attrs().
33777a4e344cSTejun Heo  */
33787a4e344cSTejun Heo void free_workqueue_attrs(struct workqueue_attrs *attrs)
33797a4e344cSTejun Heo {
33807a4e344cSTejun Heo 	if (attrs) {
33817a4e344cSTejun Heo 		free_cpumask_var(attrs->cpumask);
33827a4e344cSTejun Heo 		kfree(attrs);
33837a4e344cSTejun Heo 	}
33847a4e344cSTejun Heo }
33857a4e344cSTejun Heo 
33867a4e344cSTejun Heo /**
33877a4e344cSTejun Heo  * alloc_workqueue_attrs - allocate a workqueue_attrs
33887a4e344cSTejun Heo  * @gfp_mask: allocation mask to use
33897a4e344cSTejun Heo  *
33907a4e344cSTejun Heo  * Allocate a new workqueue_attrs, initialize with default settings and
33917a4e344cSTejun Heo  * return it.  Returns NULL on failure.
33927a4e344cSTejun Heo  */
33937a4e344cSTejun Heo struct workqueue_attrs *alloc_workqueue_attrs(gfp_t gfp_mask)
33947a4e344cSTejun Heo {
33957a4e344cSTejun Heo 	struct workqueue_attrs *attrs;
33967a4e344cSTejun Heo 
33977a4e344cSTejun Heo 	attrs = kzalloc(sizeof(*attrs), gfp_mask);
33987a4e344cSTejun Heo 	if (!attrs)
33997a4e344cSTejun Heo 		goto fail;
34007a4e344cSTejun Heo 	if (!alloc_cpumask_var(&attrs->cpumask, gfp_mask))
34017a4e344cSTejun Heo 		goto fail;
34027a4e344cSTejun Heo 
34037a4e344cSTejun Heo 	cpumask_setall(attrs->cpumask);
34047a4e344cSTejun Heo 	return attrs;
34057a4e344cSTejun Heo fail:
34067a4e344cSTejun Heo 	free_workqueue_attrs(attrs);
34077a4e344cSTejun Heo 	return NULL;
34087a4e344cSTejun Heo }
34097a4e344cSTejun Heo 
341029c91e99STejun Heo static void copy_workqueue_attrs(struct workqueue_attrs *to,
341129c91e99STejun Heo 				 const struct workqueue_attrs *from)
341229c91e99STejun Heo {
341329c91e99STejun Heo 	to->nice = from->nice;
341429c91e99STejun Heo 	cpumask_copy(to->cpumask, from->cpumask);
341529c91e99STejun Heo }
341629c91e99STejun Heo 
341729c91e99STejun Heo /*
341829c91e99STejun Heo  * Hacky implementation of jhash of bitmaps which only considers the
341929c91e99STejun Heo  * specified number of bits.  We probably want a proper implementation in
342029c91e99STejun Heo  * include/linux/jhash.h.
342129c91e99STejun Heo  */
342229c91e99STejun Heo static u32 jhash_bitmap(const unsigned long *bitmap, int bits, u32 hash)
342329c91e99STejun Heo {
342429c91e99STejun Heo 	int nr_longs = bits / BITS_PER_LONG;
342529c91e99STejun Heo 	int nr_leftover = bits % BITS_PER_LONG;
342629c91e99STejun Heo 	unsigned long leftover = 0;
342729c91e99STejun Heo 
342829c91e99STejun Heo 	if (nr_longs)
342929c91e99STejun Heo 		hash = jhash(bitmap, nr_longs * sizeof(long), hash);
343029c91e99STejun Heo 	if (nr_leftover) {
343129c91e99STejun Heo 		bitmap_copy(&leftover, bitmap + nr_longs, nr_leftover);
343229c91e99STejun Heo 		hash = jhash(&leftover, sizeof(long), hash);
343329c91e99STejun Heo 	}
343429c91e99STejun Heo 	return hash;
343529c91e99STejun Heo }
343629c91e99STejun Heo 
343729c91e99STejun Heo /* hash value of the content of @attr */
343829c91e99STejun Heo static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
343929c91e99STejun Heo {
344029c91e99STejun Heo 	u32 hash = 0;
344129c91e99STejun Heo 
344229c91e99STejun Heo 	hash = jhash_1word(attrs->nice, hash);
344329c91e99STejun Heo 	hash = jhash_bitmap(cpumask_bits(attrs->cpumask), nr_cpu_ids, hash);
344429c91e99STejun Heo 	return hash;
344529c91e99STejun Heo }
344629c91e99STejun Heo 
344729c91e99STejun Heo /* content equality test */
344829c91e99STejun Heo static bool wqattrs_equal(const struct workqueue_attrs *a,
344929c91e99STejun Heo 			  const struct workqueue_attrs *b)
345029c91e99STejun Heo {
345129c91e99STejun Heo 	if (a->nice != b->nice)
345229c91e99STejun Heo 		return false;
345329c91e99STejun Heo 	if (!cpumask_equal(a->cpumask, b->cpumask))
345429c91e99STejun Heo 		return false;
345529c91e99STejun Heo 	return true;
345629c91e99STejun Heo }
345729c91e99STejun Heo 
34587a4e344cSTejun Heo /**
34597a4e344cSTejun Heo  * init_worker_pool - initialize a newly zalloc'd worker_pool
34607a4e344cSTejun Heo  * @pool: worker_pool to initialize
34617a4e344cSTejun Heo  *
34627a4e344cSTejun Heo  * Initiailize a newly zalloc'd @pool.  It also allocates @pool->attrs.
346329c91e99STejun Heo  * Returns 0 on success, -errno on failure.  Even on failure, all fields
346429c91e99STejun Heo  * inside @pool proper are initialized and put_unbound_pool() can be called
346529c91e99STejun Heo  * on @pool safely to release it.
34667a4e344cSTejun Heo  */
34677a4e344cSTejun Heo static int init_worker_pool(struct worker_pool *pool)
34684e1a1f9aSTejun Heo {
34694e1a1f9aSTejun Heo 	spin_lock_init(&pool->lock);
347029c91e99STejun Heo 	pool->id = -1;
347129c91e99STejun Heo 	pool->cpu = -1;
34724e1a1f9aSTejun Heo 	pool->flags |= POOL_DISASSOCIATED;
34734e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->worklist);
34744e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->idle_list);
34754e1a1f9aSTejun Heo 	hash_init(pool->busy_hash);
34764e1a1f9aSTejun Heo 
34774e1a1f9aSTejun Heo 	init_timer_deferrable(&pool->idle_timer);
34784e1a1f9aSTejun Heo 	pool->idle_timer.function = idle_worker_timeout;
34794e1a1f9aSTejun Heo 	pool->idle_timer.data = (unsigned long)pool;
34804e1a1f9aSTejun Heo 
34814e1a1f9aSTejun Heo 	setup_timer(&pool->mayday_timer, pool_mayday_timeout,
34824e1a1f9aSTejun Heo 		    (unsigned long)pool);
34834e1a1f9aSTejun Heo 
34844e1a1f9aSTejun Heo 	mutex_init(&pool->manager_arb);
3485bc3a1afcSTejun Heo 	mutex_init(&pool->manager_mutex);
34864e1a1f9aSTejun Heo 	ida_init(&pool->worker_ida);
34877a4e344cSTejun Heo 
348829c91e99STejun Heo 	INIT_HLIST_NODE(&pool->hash_node);
348929c91e99STejun Heo 	pool->refcnt = 1;
349029c91e99STejun Heo 
349129c91e99STejun Heo 	/* shouldn't fail above this point */
34927a4e344cSTejun Heo 	pool->attrs = alloc_workqueue_attrs(GFP_KERNEL);
34937a4e344cSTejun Heo 	if (!pool->attrs)
34947a4e344cSTejun Heo 		return -ENOMEM;
34957a4e344cSTejun Heo 	return 0;
34964e1a1f9aSTejun Heo }
34974e1a1f9aSTejun Heo 
349829c91e99STejun Heo static void rcu_free_pool(struct rcu_head *rcu)
349929c91e99STejun Heo {
350029c91e99STejun Heo 	struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
350129c91e99STejun Heo 
350229c91e99STejun Heo 	ida_destroy(&pool->worker_ida);
350329c91e99STejun Heo 	free_workqueue_attrs(pool->attrs);
350429c91e99STejun Heo 	kfree(pool);
350529c91e99STejun Heo }
350629c91e99STejun Heo 
350729c91e99STejun Heo /**
350829c91e99STejun Heo  * put_unbound_pool - put a worker_pool
350929c91e99STejun Heo  * @pool: worker_pool to put
351029c91e99STejun Heo  *
351129c91e99STejun Heo  * Put @pool.  If its refcnt reaches zero, it gets destroyed in sched-RCU
3512c5aa87bbSTejun Heo  * safe manner.  get_unbound_pool() calls this function on its failure path
3513c5aa87bbSTejun Heo  * and this function should be able to release pools which went through,
3514c5aa87bbSTejun Heo  * successfully or not, init_worker_pool().
351529c91e99STejun Heo  */
351629c91e99STejun Heo static void put_unbound_pool(struct worker_pool *pool)
351729c91e99STejun Heo {
351829c91e99STejun Heo 	struct worker *worker;
351929c91e99STejun Heo 
3520*5bcab335STejun Heo 	mutex_lock(&wq_mutex);
352129c91e99STejun Heo 	if (--pool->refcnt) {
3522*5bcab335STejun Heo 		mutex_unlock(&wq_mutex);
352329c91e99STejun Heo 		return;
352429c91e99STejun Heo 	}
352529c91e99STejun Heo 
352629c91e99STejun Heo 	/* sanity checks */
352729c91e99STejun Heo 	if (WARN_ON(!(pool->flags & POOL_DISASSOCIATED)) ||
352829c91e99STejun Heo 	    WARN_ON(!list_empty(&pool->worklist))) {
3529*5bcab335STejun Heo 		mutex_unlock(&wq_mutex);
353029c91e99STejun Heo 		return;
353129c91e99STejun Heo 	}
353229c91e99STejun Heo 
353329c91e99STejun Heo 	/* release id and unhash */
353429c91e99STejun Heo 	if (pool->id >= 0)
353529c91e99STejun Heo 		idr_remove(&worker_pool_idr, pool->id);
353629c91e99STejun Heo 	hash_del(&pool->hash_node);
353729c91e99STejun Heo 
3538*5bcab335STejun Heo 	mutex_unlock(&wq_mutex);
353929c91e99STejun Heo 
3540c5aa87bbSTejun Heo 	/*
3541c5aa87bbSTejun Heo 	 * Become the manager and destroy all workers.  Grabbing
3542c5aa87bbSTejun Heo 	 * manager_arb prevents @pool's workers from blocking on
3543c5aa87bbSTejun Heo 	 * manager_mutex.
3544c5aa87bbSTejun Heo 	 */
354529c91e99STejun Heo 	mutex_lock(&pool->manager_arb);
3546cd549687STejun Heo 	mutex_lock(&pool->manager_mutex);
354729c91e99STejun Heo 	spin_lock_irq(&pool->lock);
354829c91e99STejun Heo 
354929c91e99STejun Heo 	while ((worker = first_worker(pool)))
355029c91e99STejun Heo 		destroy_worker(worker);
355129c91e99STejun Heo 	WARN_ON(pool->nr_workers || pool->nr_idle);
355229c91e99STejun Heo 
355329c91e99STejun Heo 	spin_unlock_irq(&pool->lock);
3554cd549687STejun Heo 	mutex_unlock(&pool->manager_mutex);
355529c91e99STejun Heo 	mutex_unlock(&pool->manager_arb);
355629c91e99STejun Heo 
355729c91e99STejun Heo 	/* shut down the timers */
355829c91e99STejun Heo 	del_timer_sync(&pool->idle_timer);
355929c91e99STejun Heo 	del_timer_sync(&pool->mayday_timer);
356029c91e99STejun Heo 
356129c91e99STejun Heo 	/* sched-RCU protected to allow dereferences from get_work_pool() */
356229c91e99STejun Heo 	call_rcu_sched(&pool->rcu, rcu_free_pool);
356329c91e99STejun Heo }
356429c91e99STejun Heo 
356529c91e99STejun Heo /**
356629c91e99STejun Heo  * get_unbound_pool - get a worker_pool with the specified attributes
356729c91e99STejun Heo  * @attrs: the attributes of the worker_pool to get
356829c91e99STejun Heo  *
356929c91e99STejun Heo  * Obtain a worker_pool which has the same attributes as @attrs, bump the
357029c91e99STejun Heo  * reference count and return it.  If there already is a matching
357129c91e99STejun Heo  * worker_pool, it will be used; otherwise, this function attempts to
357229c91e99STejun Heo  * create a new one.  On failure, returns NULL.
357329c91e99STejun Heo  */
357429c91e99STejun Heo static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
357529c91e99STejun Heo {
357629c91e99STejun Heo 	u32 hash = wqattrs_hash(attrs);
357729c91e99STejun Heo 	struct worker_pool *pool;
357829c91e99STejun Heo 
3579*5bcab335STejun Heo 	mutex_lock(&wq_mutex);
358029c91e99STejun Heo 
358129c91e99STejun Heo 	/* do we already have a matching pool? */
358229c91e99STejun Heo 	hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
358329c91e99STejun Heo 		if (wqattrs_equal(pool->attrs, attrs)) {
358429c91e99STejun Heo 			pool->refcnt++;
358529c91e99STejun Heo 			goto out_unlock;
358629c91e99STejun Heo 		}
358729c91e99STejun Heo 	}
358829c91e99STejun Heo 
358929c91e99STejun Heo 	/* nope, create a new one */
359029c91e99STejun Heo 	pool = kzalloc(sizeof(*pool), GFP_KERNEL);
359129c91e99STejun Heo 	if (!pool || init_worker_pool(pool) < 0)
359229c91e99STejun Heo 		goto fail;
359329c91e99STejun Heo 
35948864b4e5STejun Heo 	lockdep_set_subclass(&pool->lock, 1);	/* see put_pwq() */
359529c91e99STejun Heo 	copy_workqueue_attrs(pool->attrs, attrs);
359629c91e99STejun Heo 
359729c91e99STejun Heo 	if (worker_pool_assign_id(pool) < 0)
359829c91e99STejun Heo 		goto fail;
359929c91e99STejun Heo 
360029c91e99STejun Heo 	/* create and start the initial worker */
3601ebf44d16STejun Heo 	if (create_and_start_worker(pool) < 0)
360229c91e99STejun Heo 		goto fail;
360329c91e99STejun Heo 
360429c91e99STejun Heo 	/* install */
360529c91e99STejun Heo 	hash_add(unbound_pool_hash, &pool->hash_node, hash);
360629c91e99STejun Heo out_unlock:
3607*5bcab335STejun Heo 	mutex_unlock(&wq_mutex);
360829c91e99STejun Heo 	return pool;
360929c91e99STejun Heo fail:
3610*5bcab335STejun Heo 	mutex_unlock(&wq_mutex);
361129c91e99STejun Heo 	if (pool)
361229c91e99STejun Heo 		put_unbound_pool(pool);
361329c91e99STejun Heo 	return NULL;
361429c91e99STejun Heo }
361529c91e99STejun Heo 
36168864b4e5STejun Heo static void rcu_free_pwq(struct rcu_head *rcu)
36178864b4e5STejun Heo {
36188864b4e5STejun Heo 	kmem_cache_free(pwq_cache,
36198864b4e5STejun Heo 			container_of(rcu, struct pool_workqueue, rcu));
36208864b4e5STejun Heo }
36218864b4e5STejun Heo 
36228864b4e5STejun Heo /*
36238864b4e5STejun Heo  * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
36248864b4e5STejun Heo  * and needs to be destroyed.
36258864b4e5STejun Heo  */
36268864b4e5STejun Heo static void pwq_unbound_release_workfn(struct work_struct *work)
36278864b4e5STejun Heo {
36288864b4e5STejun Heo 	struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
36298864b4e5STejun Heo 						  unbound_release_work);
36308864b4e5STejun Heo 	struct workqueue_struct *wq = pwq->wq;
36318864b4e5STejun Heo 	struct worker_pool *pool = pwq->pool;
36328864b4e5STejun Heo 
36338864b4e5STejun Heo 	if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
36348864b4e5STejun Heo 		return;
36358864b4e5STejun Heo 
363675ccf595STejun Heo 	/*
363775ccf595STejun Heo 	 * Unlink @pwq.  Synchronization against flush_mutex isn't strictly
363875ccf595STejun Heo 	 * necessary on release but do it anyway.  It's easier to verify
363975ccf595STejun Heo 	 * and consistent with the linking path.
364075ccf595STejun Heo 	 */
364175ccf595STejun Heo 	mutex_lock(&wq->flush_mutex);
36428864b4e5STejun Heo 	spin_lock_irq(&workqueue_lock);
36438864b4e5STejun Heo 	list_del_rcu(&pwq->pwqs_node);
36448864b4e5STejun Heo 	spin_unlock_irq(&workqueue_lock);
364575ccf595STejun Heo 	mutex_unlock(&wq->flush_mutex);
36468864b4e5STejun Heo 
36478864b4e5STejun Heo 	put_unbound_pool(pool);
36488864b4e5STejun Heo 	call_rcu_sched(&pwq->rcu, rcu_free_pwq);
36498864b4e5STejun Heo 
36508864b4e5STejun Heo 	/*
36518864b4e5STejun Heo 	 * If we're the last pwq going away, @wq is already dead and no one
36528864b4e5STejun Heo 	 * is gonna access it anymore.  Free it.
36538864b4e5STejun Heo 	 */
36548864b4e5STejun Heo 	if (list_empty(&wq->pwqs))
36558864b4e5STejun Heo 		kfree(wq);
36568864b4e5STejun Heo }
36578864b4e5STejun Heo 
36580fbd95aaSTejun Heo /**
3659699ce097STejun Heo  * pwq_adjust_max_active - update a pwq's max_active to the current setting
36600fbd95aaSTejun Heo  * @pwq: target pool_workqueue
36610fbd95aaSTejun Heo  *
3662699ce097STejun Heo  * If @pwq isn't freezing, set @pwq->max_active to the associated
3663699ce097STejun Heo  * workqueue's saved_max_active and activate delayed work items
3664699ce097STejun Heo  * accordingly.  If @pwq is freezing, clear @pwq->max_active to zero.
36650fbd95aaSTejun Heo  */
3666699ce097STejun Heo static void pwq_adjust_max_active(struct pool_workqueue *pwq)
36670fbd95aaSTejun Heo {
3668699ce097STejun Heo 	struct workqueue_struct *wq = pwq->wq;
3669699ce097STejun Heo 	bool freezable = wq->flags & WQ_FREEZABLE;
3670699ce097STejun Heo 
3671699ce097STejun Heo 	/* for @wq->saved_max_active */
3672699ce097STejun Heo 	lockdep_assert_held(&workqueue_lock);
3673699ce097STejun Heo 
3674699ce097STejun Heo 	/* fast exit for non-freezable wqs */
3675699ce097STejun Heo 	if (!freezable && pwq->max_active == wq->saved_max_active)
3676699ce097STejun Heo 		return;
3677699ce097STejun Heo 
3678699ce097STejun Heo 	spin_lock(&pwq->pool->lock);
3679699ce097STejun Heo 
3680699ce097STejun Heo 	if (!freezable || !(pwq->pool->flags & POOL_FREEZING)) {
3681699ce097STejun Heo 		pwq->max_active = wq->saved_max_active;
36820fbd95aaSTejun Heo 
36830fbd95aaSTejun Heo 		while (!list_empty(&pwq->delayed_works) &&
36840fbd95aaSTejun Heo 		       pwq->nr_active < pwq->max_active)
36850fbd95aaSTejun Heo 			pwq_activate_first_delayed(pwq);
3686699ce097STejun Heo 	} else {
3687699ce097STejun Heo 		pwq->max_active = 0;
3688699ce097STejun Heo 	}
3689699ce097STejun Heo 
3690699ce097STejun Heo 	spin_unlock(&pwq->pool->lock);
36910fbd95aaSTejun Heo }
36920fbd95aaSTejun Heo 
3693d2c1d404STejun Heo static void init_and_link_pwq(struct pool_workqueue *pwq,
3694d2c1d404STejun Heo 			      struct workqueue_struct *wq,
36959e8cd2f5STejun Heo 			      struct worker_pool *pool,
36969e8cd2f5STejun Heo 			      struct pool_workqueue **p_last_pwq)
3697d2c1d404STejun Heo {
3698d2c1d404STejun Heo 	BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3699d2c1d404STejun Heo 
3700d2c1d404STejun Heo 	pwq->pool = pool;
3701d2c1d404STejun Heo 	pwq->wq = wq;
3702d2c1d404STejun Heo 	pwq->flush_color = -1;
37038864b4e5STejun Heo 	pwq->refcnt = 1;
3704d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->delayed_works);
3705d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->mayday_node);
37068864b4e5STejun Heo 	INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
3707d2c1d404STejun Heo 
370875ccf595STejun Heo 	mutex_lock(&wq->flush_mutex);
370975ccf595STejun Heo 	spin_lock_irq(&workqueue_lock);
371075ccf595STejun Heo 
3711983ca25eSTejun Heo 	/*
3712983ca25eSTejun Heo 	 * Set the matching work_color.  This is synchronized with
3713983ca25eSTejun Heo 	 * flush_mutex to avoid confusing flush_workqueue().
3714983ca25eSTejun Heo 	 */
37159e8cd2f5STejun Heo 	if (p_last_pwq)
37169e8cd2f5STejun Heo 		*p_last_pwq = first_pwq(wq);
371775ccf595STejun Heo 	pwq->work_color = wq->work_color;
3718983ca25eSTejun Heo 
3719983ca25eSTejun Heo 	/* sync max_active to the current setting */
3720983ca25eSTejun Heo 	pwq_adjust_max_active(pwq);
3721983ca25eSTejun Heo 
3722983ca25eSTejun Heo 	/* link in @pwq */
37239e8cd2f5STejun Heo 	list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
372475ccf595STejun Heo 
372575ccf595STejun Heo 	spin_unlock_irq(&workqueue_lock);
372675ccf595STejun Heo 	mutex_unlock(&wq->flush_mutex);
3727d2c1d404STejun Heo }
3728d2c1d404STejun Heo 
37299e8cd2f5STejun Heo /**
37309e8cd2f5STejun Heo  * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
37319e8cd2f5STejun Heo  * @wq: the target workqueue
37329e8cd2f5STejun Heo  * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
37339e8cd2f5STejun Heo  *
37349e8cd2f5STejun Heo  * Apply @attrs to an unbound workqueue @wq.  If @attrs doesn't match the
37359e8cd2f5STejun Heo  * current attributes, a new pwq is created and made the first pwq which
37369e8cd2f5STejun Heo  * will serve all new work items.  Older pwqs are released as in-flight
37379e8cd2f5STejun Heo  * work items finish.  Note that a work item which repeatedly requeues
37389e8cd2f5STejun Heo  * itself back-to-back will stay on its current pwq.
37399e8cd2f5STejun Heo  *
37409e8cd2f5STejun Heo  * Performs GFP_KERNEL allocations.  Returns 0 on success and -errno on
37419e8cd2f5STejun Heo  * failure.
37429e8cd2f5STejun Heo  */
37439e8cd2f5STejun Heo int apply_workqueue_attrs(struct workqueue_struct *wq,
37449e8cd2f5STejun Heo 			  const struct workqueue_attrs *attrs)
37459e8cd2f5STejun Heo {
37469e8cd2f5STejun Heo 	struct pool_workqueue *pwq, *last_pwq;
37479e8cd2f5STejun Heo 	struct worker_pool *pool;
37489e8cd2f5STejun Heo 
37498719dceaSTejun Heo 	/* only unbound workqueues can change attributes */
37509e8cd2f5STejun Heo 	if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
37519e8cd2f5STejun Heo 		return -EINVAL;
37529e8cd2f5STejun Heo 
37538719dceaSTejun Heo 	/* creating multiple pwqs breaks ordering guarantee */
37548719dceaSTejun Heo 	if (WARN_ON((wq->flags & __WQ_ORDERED) && !list_empty(&wq->pwqs)))
37558719dceaSTejun Heo 		return -EINVAL;
37568719dceaSTejun Heo 
37579e8cd2f5STejun Heo 	pwq = kmem_cache_zalloc(pwq_cache, GFP_KERNEL);
37589e8cd2f5STejun Heo 	if (!pwq)
37599e8cd2f5STejun Heo 		return -ENOMEM;
37609e8cd2f5STejun Heo 
37619e8cd2f5STejun Heo 	pool = get_unbound_pool(attrs);
37629e8cd2f5STejun Heo 	if (!pool) {
37639e8cd2f5STejun Heo 		kmem_cache_free(pwq_cache, pwq);
37649e8cd2f5STejun Heo 		return -ENOMEM;
37659e8cd2f5STejun Heo 	}
37669e8cd2f5STejun Heo 
37679e8cd2f5STejun Heo 	init_and_link_pwq(pwq, wq, pool, &last_pwq);
37689e8cd2f5STejun Heo 	if (last_pwq) {
37699e8cd2f5STejun Heo 		spin_lock_irq(&last_pwq->pool->lock);
37709e8cd2f5STejun Heo 		put_pwq(last_pwq);
37719e8cd2f5STejun Heo 		spin_unlock_irq(&last_pwq->pool->lock);
37729e8cd2f5STejun Heo 	}
37739e8cd2f5STejun Heo 
37749e8cd2f5STejun Heo 	return 0;
37759e8cd2f5STejun Heo }
37769e8cd2f5STejun Heo 
377730cdf249STejun Heo static int alloc_and_link_pwqs(struct workqueue_struct *wq)
37781da177e4SLinus Torvalds {
377949e3cf44STejun Heo 	bool highpri = wq->flags & WQ_HIGHPRI;
378030cdf249STejun Heo 	int cpu;
3781e1d8aa9fSFrederic Weisbecker 
378230cdf249STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
3783420c0ddbSTejun Heo 		wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
3784420c0ddbSTejun Heo 		if (!wq->cpu_pwqs)
378530cdf249STejun Heo 			return -ENOMEM;
378630cdf249STejun Heo 
378730cdf249STejun Heo 		for_each_possible_cpu(cpu) {
37887fb98ea7STejun Heo 			struct pool_workqueue *pwq =
37897fb98ea7STejun Heo 				per_cpu_ptr(wq->cpu_pwqs, cpu);
37907a62c2c8STejun Heo 			struct worker_pool *cpu_pools =
3791f02ae73aSTejun Heo 				per_cpu(cpu_worker_pools, cpu);
379230cdf249STejun Heo 
37939e8cd2f5STejun Heo 			init_and_link_pwq(pwq, wq, &cpu_pools[highpri], NULL);
379430cdf249STejun Heo 		}
379530cdf249STejun Heo 		return 0;
37969e8cd2f5STejun Heo 	} else {
37979e8cd2f5STejun Heo 		return apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
37989e8cd2f5STejun Heo 	}
37990f900049STejun Heo }
38000f900049STejun Heo 
3801f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
3802f3421797STejun Heo 			       const char *name)
3803b71ab8c2STejun Heo {
3804f3421797STejun Heo 	int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3805f3421797STejun Heo 
3806f3421797STejun Heo 	if (max_active < 1 || max_active > lim)
3807044c782cSValentin Ilie 		pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3808f3421797STejun Heo 			max_active, name, 1, lim);
3809b71ab8c2STejun Heo 
3810f3421797STejun Heo 	return clamp_val(max_active, 1, lim);
3811b71ab8c2STejun Heo }
3812b71ab8c2STejun Heo 
3813b196be89STejun Heo struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
381497e37d7bSTejun Heo 					       unsigned int flags,
38151e19ffc6STejun Heo 					       int max_active,
3816eb13ba87SJohannes Berg 					       struct lock_class_key *key,
3817b196be89STejun Heo 					       const char *lock_name, ...)
38183af24433SOleg Nesterov {
3819b196be89STejun Heo 	va_list args, args1;
38203af24433SOleg Nesterov 	struct workqueue_struct *wq;
382149e3cf44STejun Heo 	struct pool_workqueue *pwq;
3822b196be89STejun Heo 	size_t namelen;
3823b196be89STejun Heo 
3824b196be89STejun Heo 	/* determine namelen, allocate wq and format name */
3825b196be89STejun Heo 	va_start(args, lock_name);
3826b196be89STejun Heo 	va_copy(args1, args);
3827b196be89STejun Heo 	namelen = vsnprintf(NULL, 0, fmt, args) + 1;
3828b196be89STejun Heo 
3829b196be89STejun Heo 	wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
3830b196be89STejun Heo 	if (!wq)
3831d2c1d404STejun Heo 		return NULL;
3832b196be89STejun Heo 
3833b196be89STejun Heo 	vsnprintf(wq->name, namelen, fmt, args1);
3834b196be89STejun Heo 	va_end(args);
3835b196be89STejun Heo 	va_end(args1);
38363af24433SOleg Nesterov 
3837d320c038STejun Heo 	max_active = max_active ?: WQ_DFL_ACTIVE;
3838b196be89STejun Heo 	max_active = wq_clamp_max_active(max_active, flags, wq->name);
38393af24433SOleg Nesterov 
3840b196be89STejun Heo 	/* init wq */
384197e37d7bSTejun Heo 	wq->flags = flags;
3842a0a1a5fdSTejun Heo 	wq->saved_max_active = max_active;
384373f53c4aSTejun Heo 	mutex_init(&wq->flush_mutex);
3844112202d9STejun Heo 	atomic_set(&wq->nr_pwqs_to_flush, 0);
384530cdf249STejun Heo 	INIT_LIST_HEAD(&wq->pwqs);
384673f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
384773f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
3848493a1724STejun Heo 	INIT_LIST_HEAD(&wq->maydays);
38493af24433SOleg Nesterov 
3850eb13ba87SJohannes Berg 	lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3851cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
38523af24433SOleg Nesterov 
385330cdf249STejun Heo 	if (alloc_and_link_pwqs(wq) < 0)
3854d2c1d404STejun Heo 		goto err_free_wq;
38551537663fSTejun Heo 
3856493008a8STejun Heo 	/*
3857493008a8STejun Heo 	 * Workqueues which may be used during memory reclaim should
3858493008a8STejun Heo 	 * have a rescuer to guarantee forward progress.
3859493008a8STejun Heo 	 */
3860493008a8STejun Heo 	if (flags & WQ_MEM_RECLAIM) {
3861e22bee78STejun Heo 		struct worker *rescuer;
3862e22bee78STejun Heo 
3863d2c1d404STejun Heo 		rescuer = alloc_worker();
3864e22bee78STejun Heo 		if (!rescuer)
3865d2c1d404STejun Heo 			goto err_destroy;
3866e22bee78STejun Heo 
3867111c225aSTejun Heo 		rescuer->rescue_wq = wq;
3868111c225aSTejun Heo 		rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
3869b196be89STejun Heo 					       wq->name);
3870d2c1d404STejun Heo 		if (IS_ERR(rescuer->task)) {
3871d2c1d404STejun Heo 			kfree(rescuer);
3872d2c1d404STejun Heo 			goto err_destroy;
3873d2c1d404STejun Heo 		}
3874e22bee78STejun Heo 
3875d2c1d404STejun Heo 		wq->rescuer = rescuer;
3876e22bee78STejun Heo 		rescuer->task->flags |= PF_THREAD_BOUND;
3877e22bee78STejun Heo 		wake_up_process(rescuer->task);
38783af24433SOleg Nesterov 	}
38791537663fSTejun Heo 
3880226223abSTejun Heo 	if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
3881226223abSTejun Heo 		goto err_destroy;
3882226223abSTejun Heo 
38833af24433SOleg Nesterov 	/*
3884*5bcab335STejun Heo 	 * wq_mutex protects global freeze state and workqueues list.  Grab
3885*5bcab335STejun Heo 	 * it, adjust max_active and add the new @wq to workqueues list.
38863af24433SOleg Nesterov 	 */
3887*5bcab335STejun Heo 	mutex_lock(&wq_mutex);
3888a0a1a5fdSTejun Heo 
3889*5bcab335STejun Heo 	spin_lock_irq(&workqueue_lock);
389049e3cf44STejun Heo 	for_each_pwq(pwq, wq)
3891699ce097STejun Heo 		pwq_adjust_max_active(pwq);
3892*5bcab335STejun Heo 	spin_unlock_irq(&workqueue_lock);
3893a0a1a5fdSTejun Heo 
38943af24433SOleg Nesterov 	list_add(&wq->list, &workqueues);
3895a0a1a5fdSTejun Heo 
3896*5bcab335STejun Heo 	mutex_unlock(&wq_mutex);
38973af24433SOleg Nesterov 
38983af24433SOleg Nesterov 	return wq;
3899d2c1d404STejun Heo 
3900d2c1d404STejun Heo err_free_wq:
39014690c4abSTejun Heo 	kfree(wq);
3902d2c1d404STejun Heo 	return NULL;
3903d2c1d404STejun Heo err_destroy:
3904d2c1d404STejun Heo 	destroy_workqueue(wq);
39054690c4abSTejun Heo 	return NULL;
39061da177e4SLinus Torvalds }
3907d320c038STejun Heo EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
39081da177e4SLinus Torvalds 
39093af24433SOleg Nesterov /**
39103af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
39113af24433SOleg Nesterov  * @wq: target workqueue
39123af24433SOleg Nesterov  *
39133af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
39143af24433SOleg Nesterov  */
39153af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
39163af24433SOleg Nesterov {
391749e3cf44STejun Heo 	struct pool_workqueue *pwq;
39183af24433SOleg Nesterov 
39199c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
39209c5a2ba7STejun Heo 	drain_workqueue(wq);
3921c8efcc25STejun Heo 
39226183c009STejun Heo 	/* sanity checks */
3923*5bcab335STejun Heo 	spin_lock_irq(&workqueue_lock);
392449e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
39256183c009STejun Heo 		int i;
39266183c009STejun Heo 
392776af4d93STejun Heo 		for (i = 0; i < WORK_NR_COLORS; i++) {
392876af4d93STejun Heo 			if (WARN_ON(pwq->nr_in_flight[i])) {
392976af4d93STejun Heo 				spin_unlock_irq(&workqueue_lock);
39306183c009STejun Heo 				return;
393176af4d93STejun Heo 			}
393276af4d93STejun Heo 		}
393376af4d93STejun Heo 
39348864b4e5STejun Heo 		if (WARN_ON(pwq->refcnt > 1) ||
39358864b4e5STejun Heo 		    WARN_ON(pwq->nr_active) ||
393676af4d93STejun Heo 		    WARN_ON(!list_empty(&pwq->delayed_works))) {
393776af4d93STejun Heo 			spin_unlock_irq(&workqueue_lock);
39386183c009STejun Heo 			return;
39396183c009STejun Heo 		}
394076af4d93STejun Heo 	}
3941*5bcab335STejun Heo 	spin_unlock_irq(&workqueue_lock);
39426183c009STejun Heo 
3943a0a1a5fdSTejun Heo 	/*
3944a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
3945a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
3946a0a1a5fdSTejun Heo 	 */
3947*5bcab335STejun Heo 	mutex_lock(&wq_mutex);
3948d2c1d404STejun Heo 	list_del_init(&wq->list);
3949*5bcab335STejun Heo 	mutex_unlock(&wq_mutex);
39503af24433SOleg Nesterov 
3951226223abSTejun Heo 	workqueue_sysfs_unregister(wq);
3952226223abSTejun Heo 
3953493008a8STejun Heo 	if (wq->rescuer) {
3954e22bee78STejun Heo 		kthread_stop(wq->rescuer->task);
39558d9df9f0SXiaotian Feng 		kfree(wq->rescuer);
3956493008a8STejun Heo 		wq->rescuer = NULL;
3957e22bee78STejun Heo 	}
3958e22bee78STejun Heo 
39598864b4e5STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
396029c91e99STejun Heo 		/*
39618864b4e5STejun Heo 		 * The base ref is never dropped on per-cpu pwqs.  Directly
39628864b4e5STejun Heo 		 * free the pwqs and wq.
396329c91e99STejun Heo 		 */
39648864b4e5STejun Heo 		free_percpu(wq->cpu_pwqs);
39658864b4e5STejun Heo 		kfree(wq);
39668864b4e5STejun Heo 	} else {
39678864b4e5STejun Heo 		/*
39688864b4e5STejun Heo 		 * We're the sole accessor of @wq at this point.  Directly
39698864b4e5STejun Heo 		 * access the first pwq and put the base ref.  As both pwqs
39708864b4e5STejun Heo 		 * and pools are sched-RCU protected, the lock operations
39718864b4e5STejun Heo 		 * are safe.  @wq will be freed when the last pwq is
39728864b4e5STejun Heo 		 * released.
39738864b4e5STejun Heo 		 */
397429c91e99STejun Heo 		pwq = list_first_entry(&wq->pwqs, struct pool_workqueue,
397529c91e99STejun Heo 				       pwqs_node);
39768864b4e5STejun Heo 		spin_lock_irq(&pwq->pool->lock);
39778864b4e5STejun Heo 		put_pwq(pwq);
39788864b4e5STejun Heo 		spin_unlock_irq(&pwq->pool->lock);
397929c91e99STejun Heo 	}
39803af24433SOleg Nesterov }
39813af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
39823af24433SOleg Nesterov 
3983dcd989cbSTejun Heo /**
3984dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
3985dcd989cbSTejun Heo  * @wq: target workqueue
3986dcd989cbSTejun Heo  * @max_active: new max_active value.
3987dcd989cbSTejun Heo  *
3988dcd989cbSTejun Heo  * Set max_active of @wq to @max_active.
3989dcd989cbSTejun Heo  *
3990dcd989cbSTejun Heo  * CONTEXT:
3991dcd989cbSTejun Heo  * Don't call from IRQ context.
3992dcd989cbSTejun Heo  */
3993dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
3994dcd989cbSTejun Heo {
399549e3cf44STejun Heo 	struct pool_workqueue *pwq;
3996dcd989cbSTejun Heo 
39978719dceaSTejun Heo 	/* disallow meddling with max_active for ordered workqueues */
39988719dceaSTejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED))
39998719dceaSTejun Heo 		return;
40008719dceaSTejun Heo 
4001f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4002dcd989cbSTejun Heo 
4003e98d5b16STejun Heo 	spin_lock_irq(&workqueue_lock);
4004dcd989cbSTejun Heo 
4005dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
4006dcd989cbSTejun Heo 
4007699ce097STejun Heo 	for_each_pwq(pwq, wq)
4008699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4009dcd989cbSTejun Heo 
4010e98d5b16STejun Heo 	spin_unlock_irq(&workqueue_lock);
4011dcd989cbSTejun Heo }
4012dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4013dcd989cbSTejun Heo 
4014dcd989cbSTejun Heo /**
4015e6267616STejun Heo  * current_is_workqueue_rescuer - is %current workqueue rescuer?
4016e6267616STejun Heo  *
4017e6267616STejun Heo  * Determine whether %current is a workqueue rescuer.  Can be used from
4018e6267616STejun Heo  * work functions to determine whether it's being run off the rescuer task.
4019e6267616STejun Heo  */
4020e6267616STejun Heo bool current_is_workqueue_rescuer(void)
4021e6267616STejun Heo {
4022e6267616STejun Heo 	struct worker *worker = current_wq_worker();
4023e6267616STejun Heo 
4024e6267616STejun Heo 	return worker && worker == worker->current_pwq->wq->rescuer;
4025e6267616STejun Heo }
4026e6267616STejun Heo 
4027e6267616STejun Heo /**
4028dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
4029dcd989cbSTejun Heo  * @cpu: CPU in question
4030dcd989cbSTejun Heo  * @wq: target workqueue
4031dcd989cbSTejun Heo  *
4032dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
4033dcd989cbSTejun Heo  * no synchronization around this function and the test result is
4034dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4035dcd989cbSTejun Heo  *
4036dcd989cbSTejun Heo  * RETURNS:
4037dcd989cbSTejun Heo  * %true if congested, %false otherwise.
4038dcd989cbSTejun Heo  */
4039d84ff051STejun Heo bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4040dcd989cbSTejun Heo {
40417fb98ea7STejun Heo 	struct pool_workqueue *pwq;
404276af4d93STejun Heo 	bool ret;
404376af4d93STejun Heo 
404476af4d93STejun Heo 	preempt_disable();
40457fb98ea7STejun Heo 
40467fb98ea7STejun Heo 	if (!(wq->flags & WQ_UNBOUND))
40477fb98ea7STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
40487fb98ea7STejun Heo 	else
40497fb98ea7STejun Heo 		pwq = first_pwq(wq);
4050dcd989cbSTejun Heo 
405176af4d93STejun Heo 	ret = !list_empty(&pwq->delayed_works);
405276af4d93STejun Heo 	preempt_enable();
405376af4d93STejun Heo 
405476af4d93STejun Heo 	return ret;
4055dcd989cbSTejun Heo }
4056dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
4057dcd989cbSTejun Heo 
4058dcd989cbSTejun Heo /**
4059dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
4060dcd989cbSTejun Heo  * @work: the work to be tested
4061dcd989cbSTejun Heo  *
4062dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
4063dcd989cbSTejun Heo  * synchronization around this function and the test result is
4064dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4065dcd989cbSTejun Heo  *
4066dcd989cbSTejun Heo  * RETURNS:
4067dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
4068dcd989cbSTejun Heo  */
4069dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
4070dcd989cbSTejun Heo {
4071fa1b54e6STejun Heo 	struct worker_pool *pool;
4072dcd989cbSTejun Heo 	unsigned long flags;
4073dcd989cbSTejun Heo 	unsigned int ret = 0;
4074dcd989cbSTejun Heo 
4075dcd989cbSTejun Heo 	if (work_pending(work))
4076dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
4077038366c5SLai Jiangshan 
4078fa1b54e6STejun Heo 	local_irq_save(flags);
4079fa1b54e6STejun Heo 	pool = get_work_pool(work);
4080038366c5SLai Jiangshan 	if (pool) {
4081fa1b54e6STejun Heo 		spin_lock(&pool->lock);
4082c9e7cf27STejun Heo 		if (find_worker_executing_work(pool, work))
4083dcd989cbSTejun Heo 			ret |= WORK_BUSY_RUNNING;
4084fa1b54e6STejun Heo 		spin_unlock(&pool->lock);
4085038366c5SLai Jiangshan 	}
4086fa1b54e6STejun Heo 	local_irq_restore(flags);
4087dcd989cbSTejun Heo 
4088dcd989cbSTejun Heo 	return ret;
4089dcd989cbSTejun Heo }
4090dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
4091dcd989cbSTejun Heo 
4092db7bccf4STejun Heo /*
4093db7bccf4STejun Heo  * CPU hotplug.
4094db7bccf4STejun Heo  *
4095e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
4096112202d9STejun Heo  * are a lot of assumptions on strong associations among work, pwq and
4097706026c2STejun Heo  * pool which make migrating pending and scheduled works very
4098e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
409994cf58bbSTejun Heo  * worker pools serve mix of short, long and very long running works making
4100e22bee78STejun Heo  * blocked draining impractical.
4101e22bee78STejun Heo  *
410224647570STejun Heo  * This is solved by allowing the pools to be disassociated from the CPU
4103628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
4104628c78e7STejun Heo  * cpu comes back online.
4105db7bccf4STejun Heo  */
4106db7bccf4STejun Heo 
4107706026c2STejun Heo static void wq_unbind_fn(struct work_struct *work)
4108db7bccf4STejun Heo {
410938db41d9STejun Heo 	int cpu = smp_processor_id();
41104ce62e9eSTejun Heo 	struct worker_pool *pool;
4111db7bccf4STejun Heo 	struct worker *worker;
4112db7bccf4STejun Heo 	int i;
4113db7bccf4STejun Heo 
4114f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
41156183c009STejun Heo 		WARN_ON_ONCE(cpu != smp_processor_id());
4116db7bccf4STejun Heo 
4117bc3a1afcSTejun Heo 		mutex_lock(&pool->manager_mutex);
411894cf58bbSTejun Heo 		spin_lock_irq(&pool->lock);
4119e22bee78STejun Heo 
4120f2d5a0eeSTejun Heo 		/*
4121bc3a1afcSTejun Heo 		 * We've blocked all manager operations.  Make all workers
412294cf58bbSTejun Heo 		 * unbound and set DISASSOCIATED.  Before this, all workers
412394cf58bbSTejun Heo 		 * except for the ones which are still executing works from
412494cf58bbSTejun Heo 		 * before the last CPU down must be on the cpu.  After
412594cf58bbSTejun Heo 		 * this, they may become diasporas.
4126f2d5a0eeSTejun Heo 		 */
41274ce62e9eSTejun Heo 		list_for_each_entry(worker, &pool->idle_list, entry)
4128403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
4129db7bccf4STejun Heo 
4130b67bfe0dSSasha Levin 		for_each_busy_worker(worker, i, pool)
4131403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
4132db7bccf4STejun Heo 
413324647570STejun Heo 		pool->flags |= POOL_DISASSOCIATED;
4134f2d5a0eeSTejun Heo 
413594cf58bbSTejun Heo 		spin_unlock_irq(&pool->lock);
4136bc3a1afcSTejun Heo 		mutex_unlock(&pool->manager_mutex);
413794cf58bbSTejun Heo 	}
4138e22bee78STejun Heo 
4139e22bee78STejun Heo 	/*
4140628c78e7STejun Heo 	 * Call schedule() so that we cross rq->lock and thus can guarantee
4141628c78e7STejun Heo 	 * sched callbacks see the %WORKER_UNBOUND flag.  This is necessary
4142628c78e7STejun Heo 	 * as scheduler callbacks may be invoked from other cpus.
4143628c78e7STejun Heo 	 */
4144628c78e7STejun Heo 	schedule();
4145628c78e7STejun Heo 
4146628c78e7STejun Heo 	/*
4147628c78e7STejun Heo 	 * Sched callbacks are disabled now.  Zap nr_running.  After this,
4148628c78e7STejun Heo 	 * nr_running stays zero and need_more_worker() and keep_working()
414938db41d9STejun Heo 	 * are always true as long as the worklist is not empty.  Pools on
415038db41d9STejun Heo 	 * @cpu now behave as unbound (in terms of concurrency management)
415138db41d9STejun Heo 	 * pools which are served by workers tied to the CPU.
4152628c78e7STejun Heo 	 *
4153628c78e7STejun Heo 	 * On return from this function, the current worker would trigger
4154628c78e7STejun Heo 	 * unbound chain execution of pending work items if other workers
4155628c78e7STejun Heo 	 * didn't already.
4156e22bee78STejun Heo 	 */
4157f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu)
4158e19e397aSTejun Heo 		atomic_set(&pool->nr_running, 0);
4159db7bccf4STejun Heo }
4160db7bccf4STejun Heo 
41618db25e78STejun Heo /*
41628db25e78STejun Heo  * Workqueues should be brought up before normal priority CPU notifiers.
41638db25e78STejun Heo  * This will be registered high priority CPU notifier.
41648db25e78STejun Heo  */
41659fdf9b73SLai Jiangshan static int __cpuinit workqueue_cpu_up_callback(struct notifier_block *nfb,
41661da177e4SLinus Torvalds 					       unsigned long action,
41671da177e4SLinus Torvalds 					       void *hcpu)
41681da177e4SLinus Torvalds {
4169d84ff051STejun Heo 	int cpu = (unsigned long)hcpu;
41704ce62e9eSTejun Heo 	struct worker_pool *pool;
41711da177e4SLinus Torvalds 
41728db25e78STejun Heo 	switch (action & ~CPU_TASKS_FROZEN) {
41733af24433SOleg Nesterov 	case CPU_UP_PREPARE:
4174f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
41753ce63377STejun Heo 			if (pool->nr_workers)
41763ce63377STejun Heo 				continue;
4177ebf44d16STejun Heo 			if (create_and_start_worker(pool) < 0)
41783ce63377STejun Heo 				return NOTIFY_BAD;
41793af24433SOleg Nesterov 		}
41801da177e4SLinus Torvalds 		break;
41811da177e4SLinus Torvalds 
418265758202STejun Heo 	case CPU_DOWN_FAILED:
418365758202STejun Heo 	case CPU_ONLINE:
4184f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
4185bc3a1afcSTejun Heo 			mutex_lock(&pool->manager_mutex);
418694cf58bbSTejun Heo 			spin_lock_irq(&pool->lock);
418794cf58bbSTejun Heo 
418824647570STejun Heo 			pool->flags &= ~POOL_DISASSOCIATED;
418994cf58bbSTejun Heo 			rebind_workers(pool);
419094cf58bbSTejun Heo 
419194cf58bbSTejun Heo 			spin_unlock_irq(&pool->lock);
4192bc3a1afcSTejun Heo 			mutex_unlock(&pool->manager_mutex);
419394cf58bbSTejun Heo 		}
41948db25e78STejun Heo 		break;
419565758202STejun Heo 	}
419665758202STejun Heo 	return NOTIFY_OK;
419765758202STejun Heo }
419865758202STejun Heo 
419965758202STejun Heo /*
420065758202STejun Heo  * Workqueues should be brought down after normal priority CPU notifiers.
420165758202STejun Heo  * This will be registered as low priority CPU notifier.
420265758202STejun Heo  */
42039fdf9b73SLai Jiangshan static int __cpuinit workqueue_cpu_down_callback(struct notifier_block *nfb,
420465758202STejun Heo 						 unsigned long action,
420565758202STejun Heo 						 void *hcpu)
420665758202STejun Heo {
4207d84ff051STejun Heo 	int cpu = (unsigned long)hcpu;
42088db25e78STejun Heo 	struct work_struct unbind_work;
42098db25e78STejun Heo 
421065758202STejun Heo 	switch (action & ~CPU_TASKS_FROZEN) {
421165758202STejun Heo 	case CPU_DOWN_PREPARE:
42128db25e78STejun Heo 		/* unbinding should happen on the local CPU */
4213706026c2STejun Heo 		INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
42147635d2fdSJoonsoo Kim 		queue_work_on(cpu, system_highpri_wq, &unbind_work);
42158db25e78STejun Heo 		flush_work(&unbind_work);
42168db25e78STejun Heo 		break;
421765758202STejun Heo 	}
421865758202STejun Heo 	return NOTIFY_OK;
421965758202STejun Heo }
422065758202STejun Heo 
42212d3854a3SRusty Russell #ifdef CONFIG_SMP
42228ccad40dSRusty Russell 
42232d3854a3SRusty Russell struct work_for_cpu {
4224ed48ece2STejun Heo 	struct work_struct work;
42252d3854a3SRusty Russell 	long (*fn)(void *);
42262d3854a3SRusty Russell 	void *arg;
42272d3854a3SRusty Russell 	long ret;
42282d3854a3SRusty Russell };
42292d3854a3SRusty Russell 
4230ed48ece2STejun Heo static void work_for_cpu_fn(struct work_struct *work)
42312d3854a3SRusty Russell {
4232ed48ece2STejun Heo 	struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
4233ed48ece2STejun Heo 
42342d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
42352d3854a3SRusty Russell }
42362d3854a3SRusty Russell 
42372d3854a3SRusty Russell /**
42382d3854a3SRusty Russell  * work_on_cpu - run a function in user context on a particular cpu
42392d3854a3SRusty Russell  * @cpu: the cpu to run on
42402d3854a3SRusty Russell  * @fn: the function to run
42412d3854a3SRusty Russell  * @arg: the function arg
42422d3854a3SRusty Russell  *
424331ad9081SRusty Russell  * This will return the value @fn returns.
424431ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
42456b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
42462d3854a3SRusty Russell  */
4247d84ff051STejun Heo long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
42482d3854a3SRusty Russell {
4249ed48ece2STejun Heo 	struct work_for_cpu wfc = { .fn = fn, .arg = arg };
42502d3854a3SRusty Russell 
4251ed48ece2STejun Heo 	INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
4252ed48ece2STejun Heo 	schedule_work_on(cpu, &wfc.work);
4253ed48ece2STejun Heo 	flush_work(&wfc.work);
42542d3854a3SRusty Russell 	return wfc.ret;
42552d3854a3SRusty Russell }
42562d3854a3SRusty Russell EXPORT_SYMBOL_GPL(work_on_cpu);
42572d3854a3SRusty Russell #endif /* CONFIG_SMP */
42582d3854a3SRusty Russell 
4259a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
4260e7577c50SRusty Russell 
4261a0a1a5fdSTejun Heo /**
4262a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
4263a0a1a5fdSTejun Heo  *
426458a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
4265c5aa87bbSTejun Heo  * workqueues will queue new works to their delayed_works list instead of
4266706026c2STejun Heo  * pool->worklist.
4267a0a1a5fdSTejun Heo  *
4268a0a1a5fdSTejun Heo  * CONTEXT:
4269*5bcab335STejun Heo  * Grabs and releases wq_mutex, workqueue_lock and pool->lock's.
4270a0a1a5fdSTejun Heo  */
4271a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
4272a0a1a5fdSTejun Heo {
427317116969STejun Heo 	struct worker_pool *pool;
427424b8a847STejun Heo 	struct workqueue_struct *wq;
427524b8a847STejun Heo 	struct pool_workqueue *pwq;
4276611c92a0STejun Heo 	int pi;
4277a0a1a5fdSTejun Heo 
4278*5bcab335STejun Heo 	mutex_lock(&wq_mutex);
4279a0a1a5fdSTejun Heo 
42806183c009STejun Heo 	WARN_ON_ONCE(workqueue_freezing);
4281a0a1a5fdSTejun Heo 	workqueue_freezing = true;
4282a0a1a5fdSTejun Heo 
428324b8a847STejun Heo 	/* set FREEZING */
4284611c92a0STejun Heo 	for_each_pool(pool, pi) {
4285*5bcab335STejun Heo 		spin_lock_irq(&pool->lock);
428635b6bb63STejun Heo 		WARN_ON_ONCE(pool->flags & POOL_FREEZING);
428735b6bb63STejun Heo 		pool->flags |= POOL_FREEZING;
4288*5bcab335STejun Heo 		spin_unlock_irq(&pool->lock);
42891da177e4SLinus Torvalds 	}
42908b03ae3cSTejun Heo 
429124b8a847STejun Heo 	/* suppress further executions by setting max_active to zero */
4292*5bcab335STejun Heo 	spin_lock_irq(&workqueue_lock);
429324b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
4294699ce097STejun Heo 		for_each_pwq(pwq, wq)
4295699ce097STejun Heo 			pwq_adjust_max_active(pwq);
4296a1056305STejun Heo 	}
4297e98d5b16STejun Heo 	spin_unlock_irq(&workqueue_lock);
4298*5bcab335STejun Heo 
4299*5bcab335STejun Heo 	mutex_unlock(&wq_mutex);
4300a0a1a5fdSTejun Heo }
4301a0a1a5fdSTejun Heo 
4302a0a1a5fdSTejun Heo /**
430358a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
4304a0a1a5fdSTejun Heo  *
4305a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
4306a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
4307a0a1a5fdSTejun Heo  *
4308a0a1a5fdSTejun Heo  * CONTEXT:
4309*5bcab335STejun Heo  * Grabs and releases wq_mutex.
4310a0a1a5fdSTejun Heo  *
4311a0a1a5fdSTejun Heo  * RETURNS:
431258a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
431358a69cb4STejun Heo  * is complete.
4314a0a1a5fdSTejun Heo  */
4315a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
4316a0a1a5fdSTejun Heo {
4317a0a1a5fdSTejun Heo 	bool busy = false;
431824b8a847STejun Heo 	struct workqueue_struct *wq;
431924b8a847STejun Heo 	struct pool_workqueue *pwq;
4320a0a1a5fdSTejun Heo 
4321*5bcab335STejun Heo 	mutex_lock(&wq_mutex);
4322a0a1a5fdSTejun Heo 
43236183c009STejun Heo 	WARN_ON_ONCE(!workqueue_freezing);
4324a0a1a5fdSTejun Heo 
432524b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
432624b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
432724b8a847STejun Heo 			continue;
4328a0a1a5fdSTejun Heo 		/*
4329a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
4330a0a1a5fdSTejun Heo 		 * to peek without lock.
4331a0a1a5fdSTejun Heo 		 */
4332*5bcab335STejun Heo 		preempt_disable();
433324b8a847STejun Heo 		for_each_pwq(pwq, wq) {
43346183c009STejun Heo 			WARN_ON_ONCE(pwq->nr_active < 0);
4335112202d9STejun Heo 			if (pwq->nr_active) {
4336a0a1a5fdSTejun Heo 				busy = true;
4337*5bcab335STejun Heo 				preempt_enable();
4338a0a1a5fdSTejun Heo 				goto out_unlock;
4339a0a1a5fdSTejun Heo 			}
4340a0a1a5fdSTejun Heo 		}
4341*5bcab335STejun Heo 		preempt_enable();
4342a0a1a5fdSTejun Heo 	}
4343a0a1a5fdSTejun Heo out_unlock:
4344*5bcab335STejun Heo 	mutex_unlock(&wq_mutex);
4345a0a1a5fdSTejun Heo 	return busy;
4346a0a1a5fdSTejun Heo }
4347a0a1a5fdSTejun Heo 
4348a0a1a5fdSTejun Heo /**
4349a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
4350a0a1a5fdSTejun Heo  *
4351a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
4352706026c2STejun Heo  * frozen works are transferred to their respective pool worklists.
4353a0a1a5fdSTejun Heo  *
4354a0a1a5fdSTejun Heo  * CONTEXT:
4355*5bcab335STejun Heo  * Grabs and releases wq_mutex, workqueue_lock and pool->lock's.
4356a0a1a5fdSTejun Heo  */
4357a0a1a5fdSTejun Heo void thaw_workqueues(void)
4358a0a1a5fdSTejun Heo {
435924b8a847STejun Heo 	struct workqueue_struct *wq;
436024b8a847STejun Heo 	struct pool_workqueue *pwq;
436124b8a847STejun Heo 	struct worker_pool *pool;
4362611c92a0STejun Heo 	int pi;
4363a0a1a5fdSTejun Heo 
4364*5bcab335STejun Heo 	mutex_lock(&wq_mutex);
4365a0a1a5fdSTejun Heo 
4366a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
4367a0a1a5fdSTejun Heo 		goto out_unlock;
4368a0a1a5fdSTejun Heo 
436924b8a847STejun Heo 	/* clear FREEZING */
4370611c92a0STejun Heo 	for_each_pool(pool, pi) {
4371*5bcab335STejun Heo 		spin_lock_irq(&pool->lock);
437235b6bb63STejun Heo 		WARN_ON_ONCE(!(pool->flags & POOL_FREEZING));
437335b6bb63STejun Heo 		pool->flags &= ~POOL_FREEZING;
4374*5bcab335STejun Heo 		spin_unlock_irq(&pool->lock);
4375d565ed63STejun Heo 	}
437624b8a847STejun Heo 
437724b8a847STejun Heo 	/* restore max_active and repopulate worklist */
4378*5bcab335STejun Heo 	spin_lock_irq(&workqueue_lock);
437924b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
4380699ce097STejun Heo 		for_each_pwq(pwq, wq)
4381699ce097STejun Heo 			pwq_adjust_max_active(pwq);
438224b8a847STejun Heo 	}
4383*5bcab335STejun Heo 	spin_unlock_irq(&workqueue_lock);
438424b8a847STejun Heo 
438524b8a847STejun Heo 	/* kick workers */
4386611c92a0STejun Heo 	for_each_pool(pool, pi) {
4387*5bcab335STejun Heo 		spin_lock_irq(&pool->lock);
438824b8a847STejun Heo 		wake_up_worker(pool);
4389*5bcab335STejun Heo 		spin_unlock_irq(&pool->lock);
4390a0a1a5fdSTejun Heo 	}
4391a0a1a5fdSTejun Heo 
4392a0a1a5fdSTejun Heo 	workqueue_freezing = false;
4393a0a1a5fdSTejun Heo out_unlock:
4394*5bcab335STejun Heo 	mutex_unlock(&wq_mutex);
4395a0a1a5fdSTejun Heo }
4396a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
4397a0a1a5fdSTejun Heo 
43986ee0578bSSuresh Siddha static int __init init_workqueues(void)
43991da177e4SLinus Torvalds {
44007a4e344cSTejun Heo 	int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
44017a4e344cSTejun Heo 	int i, cpu;
4402c34056a3STejun Heo 
44037c3eed5cSTejun Heo 	/* make sure we have enough bits for OFFQ pool ID */
44047c3eed5cSTejun Heo 	BUILD_BUG_ON((1LU << (BITS_PER_LONG - WORK_OFFQ_POOL_SHIFT)) <
44056be19588SLai Jiangshan 		     WORK_CPU_END * NR_STD_WORKER_POOLS);
4406b5490077STejun Heo 
4407e904e6c2STejun Heo 	WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
4408e904e6c2STejun Heo 
4409e904e6c2STejun Heo 	pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
4410e904e6c2STejun Heo 
441165758202STejun Heo 	cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
4412a5b4e57dSLai Jiangshan 	hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
44138b03ae3cSTejun Heo 
4414706026c2STejun Heo 	/* initialize CPU pools */
441529c91e99STejun Heo 	for_each_possible_cpu(cpu) {
44164ce62e9eSTejun Heo 		struct worker_pool *pool;
44178b03ae3cSTejun Heo 
44187a4e344cSTejun Heo 		i = 0;
4419f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
44207a4e344cSTejun Heo 			BUG_ON(init_worker_pool(pool));
4421ec22ca5eSTejun Heo 			pool->cpu = cpu;
44227a4e344cSTejun Heo 			cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
44237a4e344cSTejun Heo 			pool->attrs->nice = std_nice[i++];
44247a4e344cSTejun Heo 
44259daf9e67STejun Heo 			/* alloc pool ID */
4426*5bcab335STejun Heo 			mutex_lock(&wq_mutex);
44279daf9e67STejun Heo 			BUG_ON(worker_pool_assign_id(pool));
4428*5bcab335STejun Heo 			mutex_unlock(&wq_mutex);
44294ce62e9eSTejun Heo 		}
44308b03ae3cSTejun Heo 	}
44318b03ae3cSTejun Heo 
4432e22bee78STejun Heo 	/* create the initial worker */
443329c91e99STejun Heo 	for_each_online_cpu(cpu) {
44344ce62e9eSTejun Heo 		struct worker_pool *pool;
4435e22bee78STejun Heo 
4436f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
443724647570STejun Heo 			pool->flags &= ~POOL_DISASSOCIATED;
4438ebf44d16STejun Heo 			BUG_ON(create_and_start_worker(pool) < 0);
4439e22bee78STejun Heo 		}
44404ce62e9eSTejun Heo 	}
4441e22bee78STejun Heo 
444229c91e99STejun Heo 	/* create default unbound wq attrs */
444329c91e99STejun Heo 	for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
444429c91e99STejun Heo 		struct workqueue_attrs *attrs;
444529c91e99STejun Heo 
444629c91e99STejun Heo 		BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
444729c91e99STejun Heo 
444829c91e99STejun Heo 		attrs->nice = std_nice[i];
444929c91e99STejun Heo 		cpumask_setall(attrs->cpumask);
445029c91e99STejun Heo 
445129c91e99STejun Heo 		unbound_std_wq_attrs[i] = attrs;
445229c91e99STejun Heo 	}
445329c91e99STejun Heo 
4454d320c038STejun Heo 	system_wq = alloc_workqueue("events", 0, 0);
44551aabe902SJoonsoo Kim 	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
4456d320c038STejun Heo 	system_long_wq = alloc_workqueue("events_long", 0, 0);
4457f3421797STejun Heo 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
4458f3421797STejun Heo 					    WQ_UNBOUND_MAX_ACTIVE);
445924d51addSTejun Heo 	system_freezable_wq = alloc_workqueue("events_freezable",
446024d51addSTejun Heo 					      WQ_FREEZABLE, 0);
44611aabe902SJoonsoo Kim 	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
4462ae930e0fSTejun Heo 	       !system_unbound_wq || !system_freezable_wq);
44636ee0578bSSuresh Siddha 	return 0;
44641da177e4SLinus Torvalds }
44656ee0578bSSuresh Siddha early_initcall(init_workqueues);
4466