xref: /openbmc/linux/kernel/workqueue.c (revision 1befcf30)
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 <dwmw2@infradead.org>
8e1f8e874SFrancois Cami  *     Andrew Morton
91da177e4SLinus Torvalds  *     Kai Petzke <wpp@marie.physik.tu-berlin.de>
101da177e4SLinus Torvalds  *     Theodore Ts'o <tytso@mit.edu>
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 <tj@kernel.org>
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>
47bce90380STejun Heo #include <linux/nodemask.h>
48e22bee78STejun Heo 
49ea138446STejun Heo #include "workqueue_internal.h"
501da177e4SLinus Torvalds 
51c8e55f36STejun Heo enum {
52bc2ae0f5STejun Heo 	/*
5324647570STejun Heo 	 * worker_pool flags
54bc2ae0f5STejun Heo 	 *
5524647570STejun Heo 	 * A bound pool is either associated or disassociated with its CPU.
56bc2ae0f5STejun Heo 	 * While associated (!DISASSOCIATED), all workers are bound to the
57bc2ae0f5STejun Heo 	 * CPU and none has %WORKER_UNBOUND set and concurrency management
58bc2ae0f5STejun Heo 	 * is in effect.
59bc2ae0f5STejun Heo 	 *
60bc2ae0f5STejun Heo 	 * While DISASSOCIATED, the cpu may be offline and all workers have
61bc2ae0f5STejun Heo 	 * %WORKER_UNBOUND set and concurrency management disabled, and may
6224647570STejun Heo 	 * be executing on any CPU.  The pool behaves as an unbound one.
63bc2ae0f5STejun Heo 	 *
64bc3a1afcSTejun Heo 	 * Note that DISASSOCIATED should be flipped only while holding
65bc3a1afcSTejun Heo 	 * manager_mutex to avoid changing binding state while
6624647570STejun Heo 	 * create_worker() is in progress.
67bc2ae0f5STejun Heo 	 */
6811ebea50STejun Heo 	POOL_MANAGE_WORKERS	= 1 << 0,	/* need to manage workers */
6924647570STejun Heo 	POOL_DISASSOCIATED	= 1 << 2,	/* cpu can't serve workers */
7035b6bb63STejun Heo 	POOL_FREEZING		= 1 << 3,	/* freeze in progress */
71db7bccf4STejun Heo 
72c8e55f36STejun Heo 	/* worker flags */
73c8e55f36STejun Heo 	WORKER_STARTED		= 1 << 0,	/* started */
74c8e55f36STejun Heo 	WORKER_DIE		= 1 << 1,	/* die die die */
75c8e55f36STejun Heo 	WORKER_IDLE		= 1 << 2,	/* is idle */
76e22bee78STejun Heo 	WORKER_PREP		= 1 << 3,	/* preparing to run works */
77fb0e7bebSTejun Heo 	WORKER_CPU_INTENSIVE	= 1 << 6,	/* cpu intensive */
78f3421797STejun Heo 	WORKER_UNBOUND		= 1 << 7,	/* worker is unbound */
79a9ab775bSTejun Heo 	WORKER_REBOUND		= 1 << 8,	/* worker was rebound */
80e22bee78STejun Heo 
81a9ab775bSTejun Heo 	WORKER_NOT_RUNNING	= WORKER_PREP | WORKER_CPU_INTENSIVE |
82a9ab775bSTejun Heo 				  WORKER_UNBOUND | WORKER_REBOUND,
83db7bccf4STejun Heo 
84e34cdddbSTejun Heo 	NR_STD_WORKER_POOLS	= 2,		/* # standard pools per cpu */
854ce62e9eSTejun Heo 
8629c91e99STejun Heo 	UNBOUND_POOL_HASH_ORDER	= 6,		/* hashed by pool->attrs */
87c8e55f36STejun Heo 	BUSY_WORKER_HASH_ORDER	= 6,		/* 64 pointers */
88db7bccf4STejun Heo 
89e22bee78STejun Heo 	MAX_IDLE_WORKERS_RATIO	= 4,		/* 1/4 of busy can be idle */
90e22bee78STejun Heo 	IDLE_WORKER_TIMEOUT	= 300 * HZ,	/* keep idle ones for 5 mins */
91e22bee78STejun Heo 
923233cdbdSTejun Heo 	MAYDAY_INITIAL_TIMEOUT  = HZ / 100 >= 2 ? HZ / 100 : 2,
933233cdbdSTejun Heo 						/* call for help after 10ms
943233cdbdSTejun Heo 						   (min two ticks) */
95e22bee78STejun Heo 	MAYDAY_INTERVAL		= HZ / 10,	/* and then every 100ms */
96e22bee78STejun Heo 	CREATE_COOLDOWN		= HZ,		/* time to breath after fail */
971da177e4SLinus Torvalds 
981da177e4SLinus Torvalds 	/*
99e22bee78STejun Heo 	 * Rescue workers are used only on emergencies and shared by
100e22bee78STejun Heo 	 * all cpus.  Give -20.
101e22bee78STejun Heo 	 */
102e22bee78STejun Heo 	RESCUER_NICE_LEVEL	= -20,
1033270476aSTejun Heo 	HIGHPRI_NICE_LEVEL	= -20,
104ecf6881fSTejun Heo 
105ecf6881fSTejun Heo 	WQ_NAME_LEN		= 24,
106c8e55f36STejun Heo };
107c8e55f36STejun Heo 
1081da177e4SLinus Torvalds /*
1094690c4abSTejun Heo  * Structure fields follow one of the following exclusion rules.
1104690c4abSTejun Heo  *
111e41e704bSTejun Heo  * I: Modifiable by initialization/destruction paths and read-only for
112e41e704bSTejun Heo  *    everyone else.
1134690c4abSTejun Heo  *
114e22bee78STejun Heo  * P: Preemption protected.  Disabling preemption is enough and should
115e22bee78STejun Heo  *    only be modified and accessed from the local cpu.
116e22bee78STejun Heo  *
117d565ed63STejun Heo  * L: pool->lock protected.  Access with pool->lock held.
1184690c4abSTejun Heo  *
119d565ed63STejun Heo  * X: During normal operation, modification requires pool->lock and should
120d565ed63STejun Heo  *    be done only from local cpu.  Either disabling preemption on local
121d565ed63STejun Heo  *    cpu or grabbing pool->lock is enough for read access.  If
122d565ed63STejun Heo  *    POOL_DISASSOCIATED is set, it's identical to L.
123e22bee78STejun Heo  *
124822d8405STejun Heo  * MG: pool->manager_mutex and pool->lock protected.  Writes require both
125822d8405STejun Heo  *     locks.  Reads can happen under either lock.
126822d8405STejun Heo  *
12768e13a67SLai Jiangshan  * PL: wq_pool_mutex protected.
12876af4d93STejun Heo  *
12968e13a67SLai Jiangshan  * PR: wq_pool_mutex protected for writes.  Sched-RCU protected for reads.
1305bcab335STejun Heo  *
1313c25a55dSLai Jiangshan  * WQ: wq->mutex protected.
1323c25a55dSLai Jiangshan  *
133b5927605SLai Jiangshan  * WR: wq->mutex protected for writes.  Sched-RCU protected for reads.
1342e109a28STejun Heo  *
1352e109a28STejun Heo  * MD: wq_mayday_lock protected.
1364690c4abSTejun Heo  */
1374690c4abSTejun Heo 
1382eaebdb3STejun Heo /* struct worker is defined in workqueue_internal.h */
139c34056a3STejun Heo 
140bd7bdd43STejun Heo struct worker_pool {
141d565ed63STejun Heo 	spinlock_t		lock;		/* the pool lock */
142d84ff051STejun Heo 	int			cpu;		/* I: the associated cpu */
143f3f90ad4STejun Heo 	int			node;		/* I: the associated node ID */
1449daf9e67STejun Heo 	int			id;		/* I: pool ID */
14511ebea50STejun Heo 	unsigned int		flags;		/* X: flags */
146bd7bdd43STejun Heo 
147bd7bdd43STejun Heo 	struct list_head	worklist;	/* L: list of pending works */
148bd7bdd43STejun Heo 	int			nr_workers;	/* L: total number of workers */
149ea1abd61SLai Jiangshan 
150ea1abd61SLai Jiangshan 	/* nr_idle includes the ones off idle_list for rebinding */
151bd7bdd43STejun Heo 	int			nr_idle;	/* L: currently idle ones */
152bd7bdd43STejun Heo 
153bd7bdd43STejun Heo 	struct list_head	idle_list;	/* X: list of idle workers */
154bd7bdd43STejun Heo 	struct timer_list	idle_timer;	/* L: worker idle timeout */
155bd7bdd43STejun Heo 	struct timer_list	mayday_timer;	/* L: SOS timer for workers */
156bd7bdd43STejun Heo 
157c5aa87bbSTejun Heo 	/* a workers is either on busy_hash or idle_list, or the manager */
158c9e7cf27STejun Heo 	DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
159c9e7cf27STejun Heo 						/* L: hash of busy workers */
160c9e7cf27STejun Heo 
161bc3a1afcSTejun Heo 	/* see manage_workers() for details on the two manager mutexes */
16234a06bd6STejun Heo 	struct mutex		manager_arb;	/* manager arbitration */
163bc3a1afcSTejun Heo 	struct mutex		manager_mutex;	/* manager exclusion */
164822d8405STejun Heo 	struct idr		worker_idr;	/* MG: worker IDs and iteration */
165e19e397aSTejun Heo 
1667a4e344cSTejun Heo 	struct workqueue_attrs	*attrs;		/* I: worker attributes */
16768e13a67SLai Jiangshan 	struct hlist_node	hash_node;	/* PL: unbound_pool_hash node */
16868e13a67SLai Jiangshan 	int			refcnt;		/* PL: refcnt for unbound pools */
1697a4e344cSTejun Heo 
170e19e397aSTejun Heo 	/*
171e19e397aSTejun Heo 	 * The current concurrency level.  As it's likely to be accessed
172e19e397aSTejun Heo 	 * from other CPUs during try_to_wake_up(), put it in a separate
173e19e397aSTejun Heo 	 * cacheline.
174e19e397aSTejun Heo 	 */
175e19e397aSTejun Heo 	atomic_t		nr_running ____cacheline_aligned_in_smp;
17629c91e99STejun Heo 
17729c91e99STejun Heo 	/*
17829c91e99STejun Heo 	 * Destruction of pool is sched-RCU protected to allow dereferences
17929c91e99STejun Heo 	 * from get_work_pool().
18029c91e99STejun Heo 	 */
18129c91e99STejun Heo 	struct rcu_head		rcu;
1828b03ae3cSTejun Heo } ____cacheline_aligned_in_smp;
1838b03ae3cSTejun Heo 
1848b03ae3cSTejun Heo /*
185112202d9STejun Heo  * The per-pool workqueue.  While queued, the lower WORK_STRUCT_FLAG_BITS
186112202d9STejun Heo  * of work_struct->data are used for flags and the remaining high bits
187112202d9STejun Heo  * point to the pwq; thus, pwqs need to be aligned at two's power of the
188112202d9STejun Heo  * number of flag bits.
1891da177e4SLinus Torvalds  */
190112202d9STejun Heo struct pool_workqueue {
191bd7bdd43STejun Heo 	struct worker_pool	*pool;		/* I: the associated pool */
1924690c4abSTejun Heo 	struct workqueue_struct *wq;		/* I: the owning workqueue */
19373f53c4aSTejun Heo 	int			work_color;	/* L: current color */
19473f53c4aSTejun Heo 	int			flush_color;	/* L: flushing color */
1958864b4e5STejun Heo 	int			refcnt;		/* L: reference count */
19673f53c4aSTejun Heo 	int			nr_in_flight[WORK_NR_COLORS];
19773f53c4aSTejun Heo 						/* L: nr of in_flight works */
1981e19ffc6STejun Heo 	int			nr_active;	/* L: nr of active works */
199a0a1a5fdSTejun Heo 	int			max_active;	/* L: max active works */
2001e19ffc6STejun Heo 	struct list_head	delayed_works;	/* L: delayed works */
2013c25a55dSLai Jiangshan 	struct list_head	pwqs_node;	/* WR: node on wq->pwqs */
2022e109a28STejun Heo 	struct list_head	mayday_node;	/* MD: node on wq->maydays */
2038864b4e5STejun Heo 
2048864b4e5STejun Heo 	/*
2058864b4e5STejun Heo 	 * Release of unbound pwq is punted to system_wq.  See put_pwq()
2068864b4e5STejun Heo 	 * and pwq_unbound_release_workfn() for details.  pool_workqueue
2078864b4e5STejun Heo 	 * itself is also sched-RCU protected so that the first pwq can be
208b09f4fd3SLai Jiangshan 	 * determined without grabbing wq->mutex.
2098864b4e5STejun Heo 	 */
2108864b4e5STejun Heo 	struct work_struct	unbound_release_work;
2118864b4e5STejun Heo 	struct rcu_head		rcu;
212e904e6c2STejun Heo } __aligned(1 << WORK_STRUCT_FLAG_BITS);
2131da177e4SLinus Torvalds 
2141da177e4SLinus Torvalds /*
21573f53c4aSTejun Heo  * Structure used to wait for workqueue flush.
21673f53c4aSTejun Heo  */
21773f53c4aSTejun Heo struct wq_flusher {
2183c25a55dSLai Jiangshan 	struct list_head	list;		/* WQ: list of flushers */
2193c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: flush color waiting for */
22073f53c4aSTejun Heo 	struct completion	done;		/* flush completion */
22173f53c4aSTejun Heo };
2221da177e4SLinus Torvalds 
223226223abSTejun Heo struct wq_device;
224226223abSTejun Heo 
22573f53c4aSTejun Heo /*
226c5aa87bbSTejun Heo  * The externally visible workqueue.  It relays the issued work items to
227c5aa87bbSTejun Heo  * the appropriate worker_pool through its pool_workqueues.
2281da177e4SLinus Torvalds  */
2291da177e4SLinus Torvalds struct workqueue_struct {
2303c25a55dSLai Jiangshan 	struct list_head	pwqs;		/* WR: all pwqs of this wq */
23168e13a67SLai Jiangshan 	struct list_head	list;		/* PL: list of all workqueues */
23273f53c4aSTejun Heo 
2333c25a55dSLai Jiangshan 	struct mutex		mutex;		/* protects this wq */
2343c25a55dSLai Jiangshan 	int			work_color;	/* WQ: current work color */
2353c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: current flush color */
236112202d9STejun Heo 	atomic_t		nr_pwqs_to_flush; /* flush in progress */
2373c25a55dSLai Jiangshan 	struct wq_flusher	*first_flusher;	/* WQ: first flusher */
2383c25a55dSLai Jiangshan 	struct list_head	flusher_queue;	/* WQ: flush waiters */
2393c25a55dSLai Jiangshan 	struct list_head	flusher_overflow; /* WQ: flush overflow list */
24073f53c4aSTejun Heo 
2412e109a28STejun Heo 	struct list_head	maydays;	/* MD: pwqs requesting rescue */
242e22bee78STejun Heo 	struct worker		*rescuer;	/* I: rescue worker */
243e22bee78STejun Heo 
24487fc741eSLai Jiangshan 	int			nr_drainers;	/* WQ: drain in progress */
245a357fc03SLai Jiangshan 	int			saved_max_active; /* WQ: saved pwq max_active */
246226223abSTejun Heo 
2476029a918STejun Heo 	struct workqueue_attrs	*unbound_attrs;	/* WQ: only for unbound wqs */
2486029a918STejun Heo 
249226223abSTejun Heo #ifdef CONFIG_SYSFS
250226223abSTejun Heo 	struct wq_device	*wq_dev;	/* I: for sysfs interface */
251226223abSTejun Heo #endif
2524e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
2534e6045f1SJohannes Berg 	struct lockdep_map	lockdep_map;
2544e6045f1SJohannes Berg #endif
255ecf6881fSTejun Heo 	char			name[WQ_NAME_LEN]; /* I: workqueue name */
2562728fd2fSTejun Heo 
2572728fd2fSTejun Heo 	/* hot fields used during command issue, aligned to cacheline */
2582728fd2fSTejun Heo 	unsigned int		flags ____cacheline_aligned; /* WQ: WQ_* flags */
2592728fd2fSTejun Heo 	struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */
260df2d5ae4STejun Heo 	struct pool_workqueue __rcu *numa_pwq_tbl[]; /* FR: unbound pwqs indexed by node */
2611da177e4SLinus Torvalds };
2621da177e4SLinus Torvalds 
263e904e6c2STejun Heo static struct kmem_cache *pwq_cache;
264e904e6c2STejun Heo 
265bce90380STejun Heo static int wq_numa_tbl_len;		/* highest possible NUMA node id + 1 */
266bce90380STejun Heo static cpumask_var_t *wq_numa_possible_cpumask;
267bce90380STejun Heo 					/* possible CPUs of each node */
268bce90380STejun Heo 
269bce90380STejun Heo static bool wq_numa_enabled;		/* unbound NUMA affinity enabled */
270bce90380STejun Heo 
27168e13a67SLai Jiangshan static DEFINE_MUTEX(wq_pool_mutex);	/* protects pools and workqueues list */
2722e109a28STejun Heo static DEFINE_SPINLOCK(wq_mayday_lock);	/* protects wq->maydays list */
2735bcab335STejun Heo 
27468e13a67SLai Jiangshan static LIST_HEAD(workqueues);		/* PL: list of all workqueues */
27568e13a67SLai Jiangshan static bool workqueue_freezing;		/* PL: have wqs started freezing? */
2767d19c5ceSTejun Heo 
2777d19c5ceSTejun Heo /* the per-cpu worker pools */
2787d19c5ceSTejun Heo static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
2797d19c5ceSTejun Heo 				     cpu_worker_pools);
2807d19c5ceSTejun Heo 
28168e13a67SLai Jiangshan static DEFINE_IDR(worker_pool_idr);	/* PR: idr of all pools */
2827d19c5ceSTejun Heo 
28368e13a67SLai Jiangshan /* PL: hash of all unbound pools keyed by pool->attrs */
28429c91e99STejun Heo static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
28529c91e99STejun Heo 
286c5aa87bbSTejun Heo /* I: attributes used when instantiating standard unbound pools on demand */
28729c91e99STejun Heo static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
28829c91e99STejun Heo 
289d320c038STejun Heo struct workqueue_struct *system_wq __read_mostly;
290d320c038STejun Heo EXPORT_SYMBOL_GPL(system_wq);
291044c782cSValentin Ilie struct workqueue_struct *system_highpri_wq __read_mostly;
2921aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
293044c782cSValentin Ilie struct workqueue_struct *system_long_wq __read_mostly;
294d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
295044c782cSValentin Ilie struct workqueue_struct *system_unbound_wq __read_mostly;
296f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
297044c782cSValentin Ilie struct workqueue_struct *system_freezable_wq __read_mostly;
29824d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
299d320c038STejun Heo 
3007d19c5ceSTejun Heo static int worker_thread(void *__worker);
3017d19c5ceSTejun Heo static void copy_workqueue_attrs(struct workqueue_attrs *to,
3027d19c5ceSTejun Heo 				 const struct workqueue_attrs *from);
3037d19c5ceSTejun Heo 
30497bd2347STejun Heo #define CREATE_TRACE_POINTS
30597bd2347STejun Heo #include <trace/events/workqueue.h>
30697bd2347STejun Heo 
30768e13a67SLai Jiangshan #define assert_rcu_or_pool_mutex()					\
3085bcab335STejun Heo 	rcu_lockdep_assert(rcu_read_lock_sched_held() ||		\
30968e13a67SLai Jiangshan 			   lockdep_is_held(&wq_pool_mutex),		\
31068e13a67SLai Jiangshan 			   "sched RCU or wq_pool_mutex should be held")
3115bcab335STejun Heo 
312b09f4fd3SLai Jiangshan #define assert_rcu_or_wq_mutex(wq)					\
31376af4d93STejun Heo 	rcu_lockdep_assert(rcu_read_lock_sched_held() ||		\
314b5927605SLai Jiangshan 			   lockdep_is_held(&wq->mutex),			\
315b09f4fd3SLai Jiangshan 			   "sched RCU or wq->mutex should be held")
31676af4d93STejun Heo 
317822d8405STejun Heo #ifdef CONFIG_LOCKDEP
318822d8405STejun Heo #define assert_manager_or_pool_lock(pool)				\
319519e3c11SLai Jiangshan 	WARN_ONCE(debug_locks &&					\
320519e3c11SLai Jiangshan 		  !lockdep_is_held(&(pool)->manager_mutex) &&		\
321822d8405STejun Heo 		  !lockdep_is_held(&(pool)->lock),			\
322822d8405STejun Heo 		  "pool->manager_mutex or ->lock should be held")
323822d8405STejun Heo #else
324822d8405STejun Heo #define assert_manager_or_pool_lock(pool)	do { } while (0)
325822d8405STejun Heo #endif
326822d8405STejun Heo 
327f02ae73aSTejun Heo #define for_each_cpu_worker_pool(pool, cpu)				\
328f02ae73aSTejun Heo 	for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0];		\
329f02ae73aSTejun Heo 	     (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
3307a62c2c8STejun Heo 	     (pool)++)
3314ce62e9eSTejun Heo 
33249e3cf44STejun Heo /**
33317116969STejun Heo  * for_each_pool - iterate through all worker_pools in the system
33417116969STejun Heo  * @pool: iteration cursor
335611c92a0STejun Heo  * @pi: integer used for iteration
336fa1b54e6STejun Heo  *
33768e13a67SLai Jiangshan  * This must be called either with wq_pool_mutex held or sched RCU read
33868e13a67SLai Jiangshan  * locked.  If the pool needs to be used beyond the locking in effect, the
33968e13a67SLai Jiangshan  * caller is responsible for guaranteeing that the pool stays online.
340fa1b54e6STejun Heo  *
341fa1b54e6STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
342fa1b54e6STejun Heo  * ignored.
34317116969STejun Heo  */
344611c92a0STejun Heo #define for_each_pool(pool, pi)						\
345611c92a0STejun Heo 	idr_for_each_entry(&worker_pool_idr, pool, pi)			\
34668e13a67SLai Jiangshan 		if (({ assert_rcu_or_pool_mutex(); false; })) { }	\
347fa1b54e6STejun Heo 		else
34817116969STejun Heo 
34917116969STejun Heo /**
350822d8405STejun Heo  * for_each_pool_worker - iterate through all workers of a worker_pool
351822d8405STejun Heo  * @worker: iteration cursor
352822d8405STejun Heo  * @wi: integer used for iteration
353822d8405STejun Heo  * @pool: worker_pool to iterate workers of
354822d8405STejun Heo  *
355822d8405STejun Heo  * This must be called with either @pool->manager_mutex or ->lock held.
356822d8405STejun Heo  *
357822d8405STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
358822d8405STejun Heo  * ignored.
359822d8405STejun Heo  */
360822d8405STejun Heo #define for_each_pool_worker(worker, wi, pool)				\
361822d8405STejun Heo 	idr_for_each_entry(&(pool)->worker_idr, (worker), (wi))		\
362822d8405STejun Heo 		if (({ assert_manager_or_pool_lock((pool)); false; })) { } \
363822d8405STejun Heo 		else
364822d8405STejun Heo 
365822d8405STejun Heo /**
36649e3cf44STejun Heo  * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
36749e3cf44STejun Heo  * @pwq: iteration cursor
36849e3cf44STejun Heo  * @wq: the target workqueue
36976af4d93STejun Heo  *
370b09f4fd3SLai Jiangshan  * This must be called either with wq->mutex held or sched RCU read locked.
371794b18bcSTejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
372794b18bcSTejun Heo  * responsible for guaranteeing that the pwq stays online.
37376af4d93STejun Heo  *
37476af4d93STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
37576af4d93STejun Heo  * ignored.
37649e3cf44STejun Heo  */
37749e3cf44STejun Heo #define for_each_pwq(pwq, wq)						\
37876af4d93STejun Heo 	list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node)		\
379b09f4fd3SLai Jiangshan 		if (({ assert_rcu_or_wq_mutex(wq); false; })) { }	\
38076af4d93STejun Heo 		else
381f3421797STejun Heo 
382dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
383dc186ad7SThomas Gleixner 
384dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr;
385dc186ad7SThomas Gleixner 
38699777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
38799777288SStanislaw Gruszka {
38899777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
38999777288SStanislaw Gruszka }
39099777288SStanislaw Gruszka 
391dc186ad7SThomas Gleixner /*
392dc186ad7SThomas Gleixner  * fixup_init is called when:
393dc186ad7SThomas Gleixner  * - an active object is initialized
394dc186ad7SThomas Gleixner  */
395dc186ad7SThomas Gleixner static int work_fixup_init(void *addr, enum debug_obj_state state)
396dc186ad7SThomas Gleixner {
397dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
398dc186ad7SThomas Gleixner 
399dc186ad7SThomas Gleixner 	switch (state) {
400dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
401dc186ad7SThomas Gleixner 		cancel_work_sync(work);
402dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
403dc186ad7SThomas Gleixner 		return 1;
404dc186ad7SThomas Gleixner 	default:
405dc186ad7SThomas Gleixner 		return 0;
406dc186ad7SThomas Gleixner 	}
407dc186ad7SThomas Gleixner }
408dc186ad7SThomas Gleixner 
409dc186ad7SThomas Gleixner /*
410dc186ad7SThomas Gleixner  * fixup_activate is called when:
411dc186ad7SThomas Gleixner  * - an active object is activated
412dc186ad7SThomas Gleixner  * - an unknown object is activated (might be a statically initialized object)
413dc186ad7SThomas Gleixner  */
414dc186ad7SThomas Gleixner static int work_fixup_activate(void *addr, enum debug_obj_state state)
415dc186ad7SThomas Gleixner {
416dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
417dc186ad7SThomas Gleixner 
418dc186ad7SThomas Gleixner 	switch (state) {
419dc186ad7SThomas Gleixner 
420dc186ad7SThomas Gleixner 	case ODEBUG_STATE_NOTAVAILABLE:
421dc186ad7SThomas Gleixner 		/*
422dc186ad7SThomas Gleixner 		 * This is not really a fixup. The work struct was
423dc186ad7SThomas Gleixner 		 * statically initialized. We just make sure that it
424dc186ad7SThomas Gleixner 		 * is tracked in the object tracker.
425dc186ad7SThomas Gleixner 		 */
42622df02bbSTejun Heo 		if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
427dc186ad7SThomas Gleixner 			debug_object_init(work, &work_debug_descr);
428dc186ad7SThomas Gleixner 			debug_object_activate(work, &work_debug_descr);
429dc186ad7SThomas Gleixner 			return 0;
430dc186ad7SThomas Gleixner 		}
431dc186ad7SThomas Gleixner 		WARN_ON_ONCE(1);
432dc186ad7SThomas Gleixner 		return 0;
433dc186ad7SThomas Gleixner 
434dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
435dc186ad7SThomas Gleixner 		WARN_ON(1);
436dc186ad7SThomas Gleixner 
437dc186ad7SThomas Gleixner 	default:
438dc186ad7SThomas Gleixner 		return 0;
439dc186ad7SThomas Gleixner 	}
440dc186ad7SThomas Gleixner }
441dc186ad7SThomas Gleixner 
442dc186ad7SThomas Gleixner /*
443dc186ad7SThomas Gleixner  * fixup_free is called when:
444dc186ad7SThomas Gleixner  * - an active object is freed
445dc186ad7SThomas Gleixner  */
446dc186ad7SThomas Gleixner static int work_fixup_free(void *addr, enum debug_obj_state state)
447dc186ad7SThomas Gleixner {
448dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
449dc186ad7SThomas Gleixner 
450dc186ad7SThomas Gleixner 	switch (state) {
451dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
452dc186ad7SThomas Gleixner 		cancel_work_sync(work);
453dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
454dc186ad7SThomas Gleixner 		return 1;
455dc186ad7SThomas Gleixner 	default:
456dc186ad7SThomas Gleixner 		return 0;
457dc186ad7SThomas Gleixner 	}
458dc186ad7SThomas Gleixner }
459dc186ad7SThomas Gleixner 
460dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr = {
461dc186ad7SThomas Gleixner 	.name		= "work_struct",
46299777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
463dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
464dc186ad7SThomas Gleixner 	.fixup_activate	= work_fixup_activate,
465dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
466dc186ad7SThomas Gleixner };
467dc186ad7SThomas Gleixner 
468dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
469dc186ad7SThomas Gleixner {
470dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
471dc186ad7SThomas Gleixner }
472dc186ad7SThomas Gleixner 
473dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
474dc186ad7SThomas Gleixner {
475dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
476dc186ad7SThomas Gleixner }
477dc186ad7SThomas Gleixner 
478dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
479dc186ad7SThomas Gleixner {
480dc186ad7SThomas Gleixner 	if (onstack)
481dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
482dc186ad7SThomas Gleixner 	else
483dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
484dc186ad7SThomas Gleixner }
485dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
486dc186ad7SThomas Gleixner 
487dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
488dc186ad7SThomas Gleixner {
489dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
490dc186ad7SThomas Gleixner }
491dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
492dc186ad7SThomas Gleixner 
493dc186ad7SThomas Gleixner #else
494dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
495dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
496dc186ad7SThomas Gleixner #endif
497dc186ad7SThomas Gleixner 
4989daf9e67STejun Heo /* allocate ID and assign it to @pool */
4999daf9e67STejun Heo static int worker_pool_assign_id(struct worker_pool *pool)
5009daf9e67STejun Heo {
5019daf9e67STejun Heo 	int ret;
5029daf9e67STejun Heo 
50368e13a67SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5045bcab335STejun Heo 
505fa1b54e6STejun Heo 	do {
506fa1b54e6STejun Heo 		if (!idr_pre_get(&worker_pool_idr, GFP_KERNEL))
507fa1b54e6STejun Heo 			return -ENOMEM;
5089daf9e67STejun Heo 		ret = idr_get_new(&worker_pool_idr, pool, &pool->id);
509fa1b54e6STejun Heo 	} while (ret == -EAGAIN);
5109daf9e67STejun Heo 
5119daf9e67STejun Heo 	return ret;
5129daf9e67STejun Heo }
5139daf9e67STejun Heo 
51476af4d93STejun Heo /**
51576af4d93STejun Heo  * first_pwq - return the first pool_workqueue of the specified workqueue
51676af4d93STejun Heo  * @wq: the target workqueue
51776af4d93STejun Heo  *
518b09f4fd3SLai Jiangshan  * This must be called either with wq->mutex held or sched RCU read locked.
519794b18bcSTejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
520794b18bcSTejun Heo  * responsible for guaranteeing that the pwq stays online.
52176af4d93STejun Heo  */
5227fb98ea7STejun Heo static struct pool_workqueue *first_pwq(struct workqueue_struct *wq)
523a848e3b6SOleg Nesterov {
524b09f4fd3SLai Jiangshan 	assert_rcu_or_wq_mutex(wq);
52576af4d93STejun Heo 	return list_first_or_null_rcu(&wq->pwqs, struct pool_workqueue,
52676af4d93STejun Heo 				      pwqs_node);
527f3421797STejun Heo }
528a848e3b6SOleg Nesterov 
529df2d5ae4STejun Heo /**
530df2d5ae4STejun Heo  * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
531df2d5ae4STejun Heo  * @wq: the target workqueue
532df2d5ae4STejun Heo  * @node: the node ID
533df2d5ae4STejun Heo  *
534df2d5ae4STejun Heo  * This must be called either with pwq_lock held or sched RCU read locked.
535df2d5ae4STejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
536df2d5ae4STejun Heo  * responsible for guaranteeing that the pwq stays online.
537df2d5ae4STejun Heo  */
538df2d5ae4STejun Heo static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
539df2d5ae4STejun Heo 						  int node)
540df2d5ae4STejun Heo {
541df2d5ae4STejun Heo 	assert_rcu_or_wq_mutex(wq);
542df2d5ae4STejun Heo 	return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
543df2d5ae4STejun Heo }
544df2d5ae4STejun Heo 
54573f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
54673f53c4aSTejun Heo {
54773f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
54873f53c4aSTejun Heo }
54973f53c4aSTejun Heo 
55073f53c4aSTejun Heo static int get_work_color(struct work_struct *work)
55173f53c4aSTejun Heo {
55273f53c4aSTejun Heo 	return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
55373f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
55473f53c4aSTejun Heo }
55573f53c4aSTejun Heo 
55673f53c4aSTejun Heo static int work_next_color(int color)
55773f53c4aSTejun Heo {
55873f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
559b1f4ec17SOleg Nesterov }
560b1f4ec17SOleg Nesterov 
5614594bf15SDavid Howells /*
562112202d9STejun Heo  * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
563112202d9STejun Heo  * contain the pointer to the queued pwq.  Once execution starts, the flag
5647c3eed5cSTejun Heo  * is cleared and the high bits contain OFFQ flags and pool ID.
5657a22ad75STejun Heo  *
566112202d9STejun Heo  * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
567112202d9STejun Heo  * and clear_work_data() can be used to set the pwq, pool or clear
568bbb68dfaSTejun Heo  * work->data.  These functions should only be called while the work is
569bbb68dfaSTejun Heo  * owned - ie. while the PENDING bit is set.
5707a22ad75STejun Heo  *
571112202d9STejun Heo  * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
5727c3eed5cSTejun Heo  * corresponding to a work.  Pool is available once the work has been
573112202d9STejun Heo  * queued anywhere after initialization until it is sync canceled.  pwq is
5747c3eed5cSTejun Heo  * available only while the work item is queued.
575bbb68dfaSTejun Heo  *
576bbb68dfaSTejun Heo  * %WORK_OFFQ_CANCELING is used to mark a work item which is being
577bbb68dfaSTejun Heo  * canceled.  While being canceled, a work item may have its PENDING set
578bbb68dfaSTejun Heo  * but stay off timer and worklist for arbitrarily long and nobody should
579bbb68dfaSTejun Heo  * try to steal the PENDING bit.
5804594bf15SDavid Howells  */
5817a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
5827a22ad75STejun Heo 				 unsigned long flags)
5837a22ad75STejun Heo {
5846183c009STejun Heo 	WARN_ON_ONCE(!work_pending(work));
5857a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
5867a22ad75STejun Heo }
5877a22ad75STejun Heo 
588112202d9STejun Heo static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
5894690c4abSTejun Heo 			 unsigned long extra_flags)
590365970a1SDavid Howells {
591112202d9STejun Heo 	set_work_data(work, (unsigned long)pwq,
592112202d9STejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
593365970a1SDavid Howells }
594365970a1SDavid Howells 
5954468a00fSLai Jiangshan static void set_work_pool_and_keep_pending(struct work_struct *work,
5964468a00fSLai Jiangshan 					   int pool_id)
5974468a00fSLai Jiangshan {
5984468a00fSLai Jiangshan 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
5994468a00fSLai Jiangshan 		      WORK_STRUCT_PENDING);
6004468a00fSLai Jiangshan }
6014468a00fSLai Jiangshan 
6027c3eed5cSTejun Heo static void set_work_pool_and_clear_pending(struct work_struct *work,
6037c3eed5cSTejun Heo 					    int pool_id)
6044d707b9fSOleg Nesterov {
60523657bb1STejun Heo 	/*
60623657bb1STejun Heo 	 * The following wmb is paired with the implied mb in
60723657bb1STejun Heo 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
60823657bb1STejun Heo 	 * here are visible to and precede any updates by the next PENDING
60923657bb1STejun Heo 	 * owner.
61023657bb1STejun Heo 	 */
61123657bb1STejun Heo 	smp_wmb();
6127c3eed5cSTejun Heo 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
6134d707b9fSOleg Nesterov }
6144d707b9fSOleg Nesterov 
6157a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
616365970a1SDavid Howells {
6177c3eed5cSTejun Heo 	smp_wmb();	/* see set_work_pool_and_clear_pending() */
6187c3eed5cSTejun Heo 	set_work_data(work, WORK_STRUCT_NO_POOL, 0);
6197a22ad75STejun Heo }
6207a22ad75STejun Heo 
621112202d9STejun Heo static struct pool_workqueue *get_work_pwq(struct work_struct *work)
6227a22ad75STejun Heo {
623e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
6247a22ad75STejun Heo 
625112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
626e120153dSTejun Heo 		return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
627e120153dSTejun Heo 	else
628e120153dSTejun Heo 		return NULL;
6297a22ad75STejun Heo }
6307a22ad75STejun Heo 
6317c3eed5cSTejun Heo /**
6327c3eed5cSTejun Heo  * get_work_pool - return the worker_pool a given work was associated with
6337c3eed5cSTejun Heo  * @work: the work item of interest
6347c3eed5cSTejun Heo  *
6357c3eed5cSTejun Heo  * Return the worker_pool @work was last associated with.  %NULL if none.
636fa1b54e6STejun Heo  *
63768e13a67SLai Jiangshan  * Pools are created and destroyed under wq_pool_mutex, and allows read
63868e13a67SLai Jiangshan  * access under sched-RCU read lock.  As such, this function should be
63968e13a67SLai Jiangshan  * called under wq_pool_mutex or with preemption disabled.
640fa1b54e6STejun Heo  *
641fa1b54e6STejun Heo  * All fields of the returned pool are accessible as long as the above
642fa1b54e6STejun Heo  * mentioned locking is in effect.  If the returned pool needs to be used
643fa1b54e6STejun Heo  * beyond the critical section, the caller is responsible for ensuring the
644fa1b54e6STejun Heo  * returned pool is and stays online.
6457c3eed5cSTejun Heo  */
6467c3eed5cSTejun Heo static struct worker_pool *get_work_pool(struct work_struct *work)
6477a22ad75STejun Heo {
648e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
6497c3eed5cSTejun Heo 	int pool_id;
6507a22ad75STejun Heo 
65168e13a67SLai Jiangshan 	assert_rcu_or_pool_mutex();
652fa1b54e6STejun Heo 
653112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
654112202d9STejun Heo 		return ((struct pool_workqueue *)
6557c3eed5cSTejun Heo 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool;
6567a22ad75STejun Heo 
6577c3eed5cSTejun Heo 	pool_id = data >> WORK_OFFQ_POOL_SHIFT;
6587c3eed5cSTejun Heo 	if (pool_id == WORK_OFFQ_POOL_NONE)
6597a22ad75STejun Heo 		return NULL;
6607a22ad75STejun Heo 
661fa1b54e6STejun Heo 	return idr_find(&worker_pool_idr, pool_id);
6627c3eed5cSTejun Heo }
6637c3eed5cSTejun Heo 
6647c3eed5cSTejun Heo /**
6657c3eed5cSTejun Heo  * get_work_pool_id - return the worker pool ID a given work is associated with
6667c3eed5cSTejun Heo  * @work: the work item of interest
6677c3eed5cSTejun Heo  *
6687c3eed5cSTejun Heo  * Return the worker_pool ID @work was last associated with.
6697c3eed5cSTejun Heo  * %WORK_OFFQ_POOL_NONE if none.
6707c3eed5cSTejun Heo  */
6717c3eed5cSTejun Heo static int get_work_pool_id(struct work_struct *work)
6727c3eed5cSTejun Heo {
67354d5b7d0SLai Jiangshan 	unsigned long data = atomic_long_read(&work->data);
6747c3eed5cSTejun Heo 
675112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
676112202d9STejun Heo 		return ((struct pool_workqueue *)
67754d5b7d0SLai Jiangshan 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
67854d5b7d0SLai Jiangshan 
67954d5b7d0SLai Jiangshan 	return data >> WORK_OFFQ_POOL_SHIFT;
6807c3eed5cSTejun Heo }
6817c3eed5cSTejun Heo 
682bbb68dfaSTejun Heo static void mark_work_canceling(struct work_struct *work)
683bbb68dfaSTejun Heo {
6847c3eed5cSTejun Heo 	unsigned long pool_id = get_work_pool_id(work);
685bbb68dfaSTejun Heo 
6867c3eed5cSTejun Heo 	pool_id <<= WORK_OFFQ_POOL_SHIFT;
6877c3eed5cSTejun Heo 	set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
688bbb68dfaSTejun Heo }
689bbb68dfaSTejun Heo 
690bbb68dfaSTejun Heo static bool work_is_canceling(struct work_struct *work)
691bbb68dfaSTejun Heo {
692bbb68dfaSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
693bbb68dfaSTejun Heo 
694112202d9STejun Heo 	return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
695bbb68dfaSTejun Heo }
696bbb68dfaSTejun Heo 
697e22bee78STejun Heo /*
6983270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
6993270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
700d565ed63STejun Heo  * they're being called with pool->lock held.
701e22bee78STejun Heo  */
702e22bee78STejun Heo 
70363d95a91STejun Heo static bool __need_more_worker(struct worker_pool *pool)
704649027d7STejun Heo {
705e19e397aSTejun Heo 	return !atomic_read(&pool->nr_running);
706649027d7STejun Heo }
707649027d7STejun Heo 
708e22bee78STejun Heo /*
709e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
710e22bee78STejun Heo  * running workers.
711974271c4STejun Heo  *
712974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
713706026c2STejun Heo  * function will always return %true for unbound pools as long as the
714974271c4STejun Heo  * worklist isn't empty.
715e22bee78STejun Heo  */
71663d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
717e22bee78STejun Heo {
71863d95a91STejun Heo 	return !list_empty(&pool->worklist) && __need_more_worker(pool);
719e22bee78STejun Heo }
720e22bee78STejun Heo 
721e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
72263d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
723e22bee78STejun Heo {
72463d95a91STejun Heo 	return pool->nr_idle;
725e22bee78STejun Heo }
726e22bee78STejun Heo 
727e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
72863d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
729e22bee78STejun Heo {
730e19e397aSTejun Heo 	return !list_empty(&pool->worklist) &&
731e19e397aSTejun Heo 		atomic_read(&pool->nr_running) <= 1;
732e22bee78STejun Heo }
733e22bee78STejun Heo 
734e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
73563d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
736e22bee78STejun Heo {
73763d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
738e22bee78STejun Heo }
739e22bee78STejun Heo 
740e22bee78STejun Heo /* Do I need to be the manager? */
74163d95a91STejun Heo static bool need_to_manage_workers(struct worker_pool *pool)
742e22bee78STejun Heo {
74363d95a91STejun Heo 	return need_to_create_worker(pool) ||
74411ebea50STejun Heo 		(pool->flags & POOL_MANAGE_WORKERS);
745e22bee78STejun Heo }
746e22bee78STejun Heo 
747e22bee78STejun Heo /* Do we have too many workers and should some go away? */
74863d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
749e22bee78STejun Heo {
75034a06bd6STejun Heo 	bool managing = mutex_is_locked(&pool->manager_arb);
75163d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
75263d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
753e22bee78STejun Heo 
754ea1abd61SLai Jiangshan 	/*
755ea1abd61SLai Jiangshan 	 * nr_idle and idle_list may disagree if idle rebinding is in
756ea1abd61SLai Jiangshan 	 * progress.  Never return %true if idle_list is empty.
757ea1abd61SLai Jiangshan 	 */
758ea1abd61SLai Jiangshan 	if (list_empty(&pool->idle_list))
759ea1abd61SLai Jiangshan 		return false;
760ea1abd61SLai Jiangshan 
761e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
762e22bee78STejun Heo }
763e22bee78STejun Heo 
764e22bee78STejun Heo /*
765e22bee78STejun Heo  * Wake up functions.
766e22bee78STejun Heo  */
767e22bee78STejun Heo 
7687e11629dSTejun Heo /* Return the first worker.  Safe with preemption disabled */
76963d95a91STejun Heo static struct worker *first_worker(struct worker_pool *pool)
7707e11629dSTejun Heo {
77163d95a91STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
7727e11629dSTejun Heo 		return NULL;
7737e11629dSTejun Heo 
77463d95a91STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
7757e11629dSTejun Heo }
7767e11629dSTejun Heo 
7777e11629dSTejun Heo /**
7787e11629dSTejun Heo  * wake_up_worker - wake up an idle worker
77963d95a91STejun Heo  * @pool: worker pool to wake worker from
7807e11629dSTejun Heo  *
78163d95a91STejun Heo  * Wake up the first idle worker of @pool.
7827e11629dSTejun Heo  *
7837e11629dSTejun Heo  * CONTEXT:
784d565ed63STejun Heo  * spin_lock_irq(pool->lock).
7857e11629dSTejun Heo  */
78663d95a91STejun Heo static void wake_up_worker(struct worker_pool *pool)
7877e11629dSTejun Heo {
78863d95a91STejun Heo 	struct worker *worker = first_worker(pool);
7897e11629dSTejun Heo 
7907e11629dSTejun Heo 	if (likely(worker))
7917e11629dSTejun Heo 		wake_up_process(worker->task);
7927e11629dSTejun Heo }
7937e11629dSTejun Heo 
7944690c4abSTejun Heo /**
795e22bee78STejun Heo  * wq_worker_waking_up - a worker is waking up
796e22bee78STejun Heo  * @task: task waking up
797e22bee78STejun Heo  * @cpu: CPU @task is waking up to
798e22bee78STejun Heo  *
799e22bee78STejun Heo  * This function is called during try_to_wake_up() when a worker is
800e22bee78STejun Heo  * being awoken.
801e22bee78STejun Heo  *
802e22bee78STejun Heo  * CONTEXT:
803e22bee78STejun Heo  * spin_lock_irq(rq->lock)
804e22bee78STejun Heo  */
805d84ff051STejun Heo void wq_worker_waking_up(struct task_struct *task, int cpu)
806e22bee78STejun Heo {
807e22bee78STejun Heo 	struct worker *worker = kthread_data(task);
808e22bee78STejun Heo 
80936576000SJoonsoo Kim 	if (!(worker->flags & WORKER_NOT_RUNNING)) {
810ec22ca5eSTejun Heo 		WARN_ON_ONCE(worker->pool->cpu != cpu);
811e19e397aSTejun Heo 		atomic_inc(&worker->pool->nr_running);
812e22bee78STejun Heo 	}
81336576000SJoonsoo Kim }
814e22bee78STejun Heo 
815e22bee78STejun Heo /**
816e22bee78STejun Heo  * wq_worker_sleeping - a worker is going to sleep
817e22bee78STejun Heo  * @task: task going to sleep
818e22bee78STejun Heo  * @cpu: CPU in question, must be the current CPU number
819e22bee78STejun Heo  *
820e22bee78STejun Heo  * This function is called during schedule() when a busy worker is
821e22bee78STejun Heo  * going to sleep.  Worker on the same cpu can be woken up by
822e22bee78STejun Heo  * returning pointer to its task.
823e22bee78STejun Heo  *
824e22bee78STejun Heo  * CONTEXT:
825e22bee78STejun Heo  * spin_lock_irq(rq->lock)
826e22bee78STejun Heo  *
827e22bee78STejun Heo  * RETURNS:
828e22bee78STejun Heo  * Worker task on @cpu to wake up, %NULL if none.
829e22bee78STejun Heo  */
830d84ff051STejun Heo struct task_struct *wq_worker_sleeping(struct task_struct *task, int cpu)
831e22bee78STejun Heo {
832e22bee78STejun Heo 	struct worker *worker = kthread_data(task), *to_wakeup = NULL;
833111c225aSTejun Heo 	struct worker_pool *pool;
834e22bee78STejun Heo 
835111c225aSTejun Heo 	/*
836111c225aSTejun Heo 	 * Rescuers, which may not have all the fields set up like normal
837111c225aSTejun Heo 	 * workers, also reach here, let's not access anything before
838111c225aSTejun Heo 	 * checking NOT_RUNNING.
839111c225aSTejun Heo 	 */
8402d64672eSSteven Rostedt 	if (worker->flags & WORKER_NOT_RUNNING)
841e22bee78STejun Heo 		return NULL;
842e22bee78STejun Heo 
843111c225aSTejun Heo 	pool = worker->pool;
844111c225aSTejun Heo 
845e22bee78STejun Heo 	/* this can only happen on the local cpu */
8466183c009STejun Heo 	if (WARN_ON_ONCE(cpu != raw_smp_processor_id()))
8476183c009STejun Heo 		return NULL;
848e22bee78STejun Heo 
849e22bee78STejun Heo 	/*
850e22bee78STejun Heo 	 * The counterpart of the following dec_and_test, implied mb,
851e22bee78STejun Heo 	 * worklist not empty test sequence is in insert_work().
852e22bee78STejun Heo 	 * Please read comment there.
853e22bee78STejun Heo 	 *
854628c78e7STejun Heo 	 * NOT_RUNNING is clear.  This means that we're bound to and
855628c78e7STejun Heo 	 * running on the local cpu w/ rq lock held and preemption
856628c78e7STejun Heo 	 * disabled, which in turn means that none else could be
857d565ed63STejun Heo 	 * manipulating idle_list, so dereferencing idle_list without pool
858628c78e7STejun Heo 	 * lock is safe.
859e22bee78STejun Heo 	 */
860e19e397aSTejun Heo 	if (atomic_dec_and_test(&pool->nr_running) &&
861e19e397aSTejun Heo 	    !list_empty(&pool->worklist))
86263d95a91STejun Heo 		to_wakeup = first_worker(pool);
863e22bee78STejun Heo 	return to_wakeup ? to_wakeup->task : NULL;
864e22bee78STejun Heo }
865e22bee78STejun Heo 
866e22bee78STejun Heo /**
867e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
868cb444766STejun Heo  * @worker: self
869d302f017STejun Heo  * @flags: flags to set
870d302f017STejun Heo  * @wakeup: wakeup an idle worker if necessary
871d302f017STejun Heo  *
872e22bee78STejun Heo  * Set @flags in @worker->flags and adjust nr_running accordingly.  If
873e22bee78STejun Heo  * nr_running becomes zero and @wakeup is %true, an idle worker is
874e22bee78STejun Heo  * woken up.
875d302f017STejun Heo  *
876cb444766STejun Heo  * CONTEXT:
877d565ed63STejun Heo  * spin_lock_irq(pool->lock)
878d302f017STejun Heo  */
879d302f017STejun Heo static inline void worker_set_flags(struct worker *worker, unsigned int flags,
880d302f017STejun Heo 				    bool wakeup)
881d302f017STejun Heo {
882bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
883e22bee78STejun Heo 
884cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
885cb444766STejun Heo 
886e22bee78STejun Heo 	/*
887e22bee78STejun Heo 	 * If transitioning into NOT_RUNNING, adjust nr_running and
888e22bee78STejun Heo 	 * wake up an idle worker as necessary if requested by
889e22bee78STejun Heo 	 * @wakeup.
890e22bee78STejun Heo 	 */
891e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
892e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
893e22bee78STejun Heo 		if (wakeup) {
894e19e397aSTejun Heo 			if (atomic_dec_and_test(&pool->nr_running) &&
895bd7bdd43STejun Heo 			    !list_empty(&pool->worklist))
89663d95a91STejun Heo 				wake_up_worker(pool);
897e22bee78STejun Heo 		} else
898e19e397aSTejun Heo 			atomic_dec(&pool->nr_running);
899e22bee78STejun Heo 	}
900e22bee78STejun Heo 
901d302f017STejun Heo 	worker->flags |= flags;
902d302f017STejun Heo }
903d302f017STejun Heo 
904d302f017STejun Heo /**
905e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
906cb444766STejun Heo  * @worker: self
907d302f017STejun Heo  * @flags: flags to clear
908d302f017STejun Heo  *
909e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
910d302f017STejun Heo  *
911cb444766STejun Heo  * CONTEXT:
912d565ed63STejun Heo  * spin_lock_irq(pool->lock)
913d302f017STejun Heo  */
914d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
915d302f017STejun Heo {
91663d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
917e22bee78STejun Heo 	unsigned int oflags = worker->flags;
918e22bee78STejun Heo 
919cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
920cb444766STejun Heo 
921d302f017STejun Heo 	worker->flags &= ~flags;
922e22bee78STejun Heo 
92342c025f3STejun Heo 	/*
92442c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
92542c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
92642c025f3STejun Heo 	 * of multiple flags, not a single flag.
92742c025f3STejun Heo 	 */
928e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
929e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
930e19e397aSTejun Heo 			atomic_inc(&pool->nr_running);
931d302f017STejun Heo }
932d302f017STejun Heo 
933d302f017STejun Heo /**
9348cca0eeaSTejun Heo  * find_worker_executing_work - find worker which is executing a work
935c9e7cf27STejun Heo  * @pool: pool of interest
9368cca0eeaSTejun Heo  * @work: work to find worker for
9378cca0eeaSTejun Heo  *
938c9e7cf27STejun Heo  * Find a worker which is executing @work on @pool by searching
939c9e7cf27STejun Heo  * @pool->busy_hash which is keyed by the address of @work.  For a worker
940a2c1c57bSTejun Heo  * to match, its current execution should match the address of @work and
941a2c1c57bSTejun Heo  * its work function.  This is to avoid unwanted dependency between
942a2c1c57bSTejun Heo  * unrelated work executions through a work item being recycled while still
943a2c1c57bSTejun Heo  * being executed.
944a2c1c57bSTejun Heo  *
945a2c1c57bSTejun Heo  * This is a bit tricky.  A work item may be freed once its execution
946a2c1c57bSTejun Heo  * starts and nothing prevents the freed area from being recycled for
947a2c1c57bSTejun Heo  * another work item.  If the same work item address ends up being reused
948a2c1c57bSTejun Heo  * before the original execution finishes, workqueue will identify the
949a2c1c57bSTejun Heo  * recycled work item as currently executing and make it wait until the
950a2c1c57bSTejun Heo  * current execution finishes, introducing an unwanted dependency.
951a2c1c57bSTejun Heo  *
952c5aa87bbSTejun Heo  * This function checks the work item address and work function to avoid
953c5aa87bbSTejun Heo  * false positives.  Note that this isn't complete as one may construct a
954c5aa87bbSTejun Heo  * work function which can introduce dependency onto itself through a
955c5aa87bbSTejun Heo  * recycled work item.  Well, if somebody wants to shoot oneself in the
956c5aa87bbSTejun Heo  * foot that badly, there's only so much we can do, and if such deadlock
957c5aa87bbSTejun Heo  * actually occurs, it should be easy to locate the culprit work function.
9588cca0eeaSTejun Heo  *
9598cca0eeaSTejun Heo  * CONTEXT:
960d565ed63STejun Heo  * spin_lock_irq(pool->lock).
9618cca0eeaSTejun Heo  *
9628cca0eeaSTejun Heo  * RETURNS:
9638cca0eeaSTejun Heo  * Pointer to worker which is executing @work if found, NULL
9648cca0eeaSTejun Heo  * otherwise.
9658cca0eeaSTejun Heo  */
966c9e7cf27STejun Heo static struct worker *find_worker_executing_work(struct worker_pool *pool,
9678cca0eeaSTejun Heo 						 struct work_struct *work)
9688cca0eeaSTejun Heo {
96942f8570fSSasha Levin 	struct worker *worker;
97042f8570fSSasha Levin 
971b67bfe0dSSasha Levin 	hash_for_each_possible(pool->busy_hash, worker, hentry,
972a2c1c57bSTejun Heo 			       (unsigned long)work)
973a2c1c57bSTejun Heo 		if (worker->current_work == work &&
974a2c1c57bSTejun Heo 		    worker->current_func == work->func)
97542f8570fSSasha Levin 			return worker;
97642f8570fSSasha Levin 
97742f8570fSSasha Levin 	return NULL;
9788cca0eeaSTejun Heo }
9798cca0eeaSTejun Heo 
9808cca0eeaSTejun Heo /**
981bf4ede01STejun Heo  * move_linked_works - move linked works to a list
982bf4ede01STejun Heo  * @work: start of series of works to be scheduled
983bf4ede01STejun Heo  * @head: target list to append @work to
984bf4ede01STejun Heo  * @nextp: out paramter for nested worklist walking
985bf4ede01STejun Heo  *
986bf4ede01STejun Heo  * Schedule linked works starting from @work to @head.  Work series to
987bf4ede01STejun Heo  * be scheduled starts at @work and includes any consecutive work with
988bf4ede01STejun Heo  * WORK_STRUCT_LINKED set in its predecessor.
989bf4ede01STejun Heo  *
990bf4ede01STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of
991bf4ede01STejun Heo  * the last scheduled work.  This allows move_linked_works() to be
992bf4ede01STejun Heo  * nested inside outer list_for_each_entry_safe().
993bf4ede01STejun Heo  *
994bf4ede01STejun Heo  * CONTEXT:
995d565ed63STejun Heo  * spin_lock_irq(pool->lock).
996bf4ede01STejun Heo  */
997bf4ede01STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
998bf4ede01STejun Heo 			      struct work_struct **nextp)
999bf4ede01STejun Heo {
1000bf4ede01STejun Heo 	struct work_struct *n;
1001bf4ede01STejun Heo 
1002bf4ede01STejun Heo 	/*
1003bf4ede01STejun Heo 	 * Linked worklist will always end before the end of the list,
1004bf4ede01STejun Heo 	 * use NULL for list head.
1005bf4ede01STejun Heo 	 */
1006bf4ede01STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
1007bf4ede01STejun Heo 		list_move_tail(&work->entry, head);
1008bf4ede01STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1009bf4ede01STejun Heo 			break;
1010bf4ede01STejun Heo 	}
1011bf4ede01STejun Heo 
1012bf4ede01STejun Heo 	/*
1013bf4ede01STejun Heo 	 * If we're already inside safe list traversal and have moved
1014bf4ede01STejun Heo 	 * multiple works to the scheduled queue, the next position
1015bf4ede01STejun Heo 	 * needs to be updated.
1016bf4ede01STejun Heo 	 */
1017bf4ede01STejun Heo 	if (nextp)
1018bf4ede01STejun Heo 		*nextp = n;
1019bf4ede01STejun Heo }
1020bf4ede01STejun Heo 
10218864b4e5STejun Heo /**
10228864b4e5STejun Heo  * get_pwq - get an extra reference on the specified pool_workqueue
10238864b4e5STejun Heo  * @pwq: pool_workqueue to get
10248864b4e5STejun Heo  *
10258864b4e5STejun Heo  * Obtain an extra reference on @pwq.  The caller should guarantee that
10268864b4e5STejun Heo  * @pwq has positive refcnt and be holding the matching pool->lock.
10278864b4e5STejun Heo  */
10288864b4e5STejun Heo static void get_pwq(struct pool_workqueue *pwq)
10298864b4e5STejun Heo {
10308864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
10318864b4e5STejun Heo 	WARN_ON_ONCE(pwq->refcnt <= 0);
10328864b4e5STejun Heo 	pwq->refcnt++;
10338864b4e5STejun Heo }
10348864b4e5STejun Heo 
10358864b4e5STejun Heo /**
10368864b4e5STejun Heo  * put_pwq - put a pool_workqueue reference
10378864b4e5STejun Heo  * @pwq: pool_workqueue to put
10388864b4e5STejun Heo  *
10398864b4e5STejun Heo  * Drop a reference of @pwq.  If its refcnt reaches zero, schedule its
10408864b4e5STejun Heo  * destruction.  The caller should be holding the matching pool->lock.
10418864b4e5STejun Heo  */
10428864b4e5STejun Heo static void put_pwq(struct pool_workqueue *pwq)
10438864b4e5STejun Heo {
10448864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
10458864b4e5STejun Heo 	if (likely(--pwq->refcnt))
10468864b4e5STejun Heo 		return;
10478864b4e5STejun Heo 	if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
10488864b4e5STejun Heo 		return;
10498864b4e5STejun Heo 	/*
10508864b4e5STejun Heo 	 * @pwq can't be released under pool->lock, bounce to
10518864b4e5STejun Heo 	 * pwq_unbound_release_workfn().  This never recurses on the same
10528864b4e5STejun Heo 	 * pool->lock as this path is taken only for unbound workqueues and
10538864b4e5STejun Heo 	 * the release work item is scheduled on a per-cpu workqueue.  To
10548864b4e5STejun Heo 	 * avoid lockdep warning, unbound pool->locks are given lockdep
10558864b4e5STejun Heo 	 * subclass of 1 in get_unbound_pool().
10568864b4e5STejun Heo 	 */
10578864b4e5STejun Heo 	schedule_work(&pwq->unbound_release_work);
10588864b4e5STejun Heo }
10598864b4e5STejun Heo 
1060112202d9STejun Heo static void pwq_activate_delayed_work(struct work_struct *work)
1061bf4ede01STejun Heo {
1062112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1063bf4ede01STejun Heo 
1064bf4ede01STejun Heo 	trace_workqueue_activate_work(work);
1065112202d9STejun Heo 	move_linked_works(work, &pwq->pool->worklist, NULL);
1066bf4ede01STejun Heo 	__clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
1067112202d9STejun Heo 	pwq->nr_active++;
1068bf4ede01STejun Heo }
1069bf4ede01STejun Heo 
1070112202d9STejun Heo static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
10713aa62497SLai Jiangshan {
1072112202d9STejun Heo 	struct work_struct *work = list_first_entry(&pwq->delayed_works,
10733aa62497SLai Jiangshan 						    struct work_struct, entry);
10743aa62497SLai Jiangshan 
1075112202d9STejun Heo 	pwq_activate_delayed_work(work);
10763aa62497SLai Jiangshan }
10773aa62497SLai Jiangshan 
1078bf4ede01STejun Heo /**
1079112202d9STejun Heo  * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1080112202d9STejun Heo  * @pwq: pwq of interest
1081bf4ede01STejun Heo  * @color: color of work which left the queue
1082bf4ede01STejun Heo  *
1083bf4ede01STejun Heo  * A work either has completed or is removed from pending queue,
1084112202d9STejun Heo  * decrement nr_in_flight of its pwq and handle workqueue flushing.
1085bf4ede01STejun Heo  *
1086bf4ede01STejun Heo  * CONTEXT:
1087d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1088bf4ede01STejun Heo  */
1089112202d9STejun Heo static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
1090bf4ede01STejun Heo {
10918864b4e5STejun Heo 	/* uncolored work items don't participate in flushing or nr_active */
1092bf4ede01STejun Heo 	if (color == WORK_NO_COLOR)
10938864b4e5STejun Heo 		goto out_put;
1094bf4ede01STejun Heo 
1095112202d9STejun Heo 	pwq->nr_in_flight[color]--;
1096bf4ede01STejun Heo 
1097112202d9STejun Heo 	pwq->nr_active--;
1098112202d9STejun Heo 	if (!list_empty(&pwq->delayed_works)) {
1099bf4ede01STejun Heo 		/* one down, submit a delayed one */
1100112202d9STejun Heo 		if (pwq->nr_active < pwq->max_active)
1101112202d9STejun Heo 			pwq_activate_first_delayed(pwq);
1102bf4ede01STejun Heo 	}
1103bf4ede01STejun Heo 
1104bf4ede01STejun Heo 	/* is flush in progress and are we at the flushing tip? */
1105112202d9STejun Heo 	if (likely(pwq->flush_color != color))
11068864b4e5STejun Heo 		goto out_put;
1107bf4ede01STejun Heo 
1108bf4ede01STejun Heo 	/* are there still in-flight works? */
1109112202d9STejun Heo 	if (pwq->nr_in_flight[color])
11108864b4e5STejun Heo 		goto out_put;
1111bf4ede01STejun Heo 
1112112202d9STejun Heo 	/* this pwq is done, clear flush_color */
1113112202d9STejun Heo 	pwq->flush_color = -1;
1114bf4ede01STejun Heo 
1115bf4ede01STejun Heo 	/*
1116112202d9STejun Heo 	 * If this was the last pwq, wake up the first flusher.  It
1117bf4ede01STejun Heo 	 * will handle the rest.
1118bf4ede01STejun Heo 	 */
1119112202d9STejun Heo 	if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1120112202d9STejun Heo 		complete(&pwq->wq->first_flusher->done);
11218864b4e5STejun Heo out_put:
11228864b4e5STejun Heo 	put_pwq(pwq);
1123bf4ede01STejun Heo }
1124bf4ede01STejun Heo 
112536e227d2STejun Heo /**
1126bbb68dfaSTejun Heo  * try_to_grab_pending - steal work item from worklist and disable irq
112736e227d2STejun Heo  * @work: work item to steal
112836e227d2STejun Heo  * @is_dwork: @work is a delayed_work
1129bbb68dfaSTejun Heo  * @flags: place to store irq state
113036e227d2STejun Heo  *
113136e227d2STejun Heo  * Try to grab PENDING bit of @work.  This function can handle @work in any
113236e227d2STejun Heo  * stable state - idle, on timer or on worklist.  Return values are
113336e227d2STejun Heo  *
113436e227d2STejun Heo  *  1		if @work was pending and we successfully stole PENDING
113536e227d2STejun Heo  *  0		if @work was idle and we claimed PENDING
113636e227d2STejun Heo  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
1137bbb68dfaSTejun Heo  *  -ENOENT	if someone else is canceling @work, this state may persist
1138bbb68dfaSTejun Heo  *		for arbitrarily long
113936e227d2STejun Heo  *
1140bbb68dfaSTejun Heo  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
1141e0aecdd8STejun Heo  * interrupted while holding PENDING and @work off queue, irq must be
1142e0aecdd8STejun Heo  * disabled on entry.  This, combined with delayed_work->timer being
1143e0aecdd8STejun Heo  * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1144bbb68dfaSTejun Heo  *
1145bbb68dfaSTejun Heo  * On successful return, >= 0, irq is disabled and the caller is
1146bbb68dfaSTejun Heo  * responsible for releasing it using local_irq_restore(*@flags).
1147bbb68dfaSTejun Heo  *
1148e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
1149bf4ede01STejun Heo  */
1150bbb68dfaSTejun Heo static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1151bbb68dfaSTejun Heo 			       unsigned long *flags)
1152bf4ede01STejun Heo {
1153d565ed63STejun Heo 	struct worker_pool *pool;
1154112202d9STejun Heo 	struct pool_workqueue *pwq;
1155bf4ede01STejun Heo 
1156bbb68dfaSTejun Heo 	local_irq_save(*flags);
1157bbb68dfaSTejun Heo 
115836e227d2STejun Heo 	/* try to steal the timer if it exists */
115936e227d2STejun Heo 	if (is_dwork) {
116036e227d2STejun Heo 		struct delayed_work *dwork = to_delayed_work(work);
116136e227d2STejun Heo 
1162e0aecdd8STejun Heo 		/*
1163e0aecdd8STejun Heo 		 * dwork->timer is irqsafe.  If del_timer() fails, it's
1164e0aecdd8STejun Heo 		 * guaranteed that the timer is not queued anywhere and not
1165e0aecdd8STejun Heo 		 * running on the local CPU.
1166e0aecdd8STejun Heo 		 */
116736e227d2STejun Heo 		if (likely(del_timer(&dwork->timer)))
116836e227d2STejun Heo 			return 1;
116936e227d2STejun Heo 	}
117036e227d2STejun Heo 
117136e227d2STejun Heo 	/* try to claim PENDING the normal way */
1172bf4ede01STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1173bf4ede01STejun Heo 		return 0;
1174bf4ede01STejun Heo 
1175bf4ede01STejun Heo 	/*
1176bf4ede01STejun Heo 	 * The queueing is in progress, or it is already queued. Try to
1177bf4ede01STejun Heo 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1178bf4ede01STejun Heo 	 */
1179d565ed63STejun Heo 	pool = get_work_pool(work);
1180d565ed63STejun Heo 	if (!pool)
1181bbb68dfaSTejun Heo 		goto fail;
1182bf4ede01STejun Heo 
1183d565ed63STejun Heo 	spin_lock(&pool->lock);
1184bf4ede01STejun Heo 	/*
1185112202d9STejun Heo 	 * work->data is guaranteed to point to pwq only while the work
1186112202d9STejun Heo 	 * item is queued on pwq->wq, and both updating work->data to point
1187112202d9STejun Heo 	 * to pwq on queueing and to pool on dequeueing are done under
1188112202d9STejun Heo 	 * pwq->pool->lock.  This in turn guarantees that, if work->data
1189112202d9STejun Heo 	 * points to pwq which is associated with a locked pool, the work
11900b3dae68SLai Jiangshan 	 * item is currently queued on that pool.
1191bf4ede01STejun Heo 	 */
1192112202d9STejun Heo 	pwq = get_work_pwq(work);
1193112202d9STejun Heo 	if (pwq && pwq->pool == pool) {
1194bf4ede01STejun Heo 		debug_work_deactivate(work);
11953aa62497SLai Jiangshan 
11963aa62497SLai Jiangshan 		/*
119716062836STejun Heo 		 * A delayed work item cannot be grabbed directly because
119816062836STejun Heo 		 * it might have linked NO_COLOR work items which, if left
1199112202d9STejun Heo 		 * on the delayed_list, will confuse pwq->nr_active
120016062836STejun Heo 		 * management later on and cause stall.  Make sure the work
120116062836STejun Heo 		 * item is activated before grabbing.
12023aa62497SLai Jiangshan 		 */
12033aa62497SLai Jiangshan 		if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1204112202d9STejun Heo 			pwq_activate_delayed_work(work);
12053aa62497SLai Jiangshan 
1206bf4ede01STejun Heo 		list_del_init(&work->entry);
1207112202d9STejun Heo 		pwq_dec_nr_in_flight(get_work_pwq(work), get_work_color(work));
120836e227d2STejun Heo 
1209112202d9STejun Heo 		/* work->data points to pwq iff queued, point to pool */
12104468a00fSLai Jiangshan 		set_work_pool_and_keep_pending(work, pool->id);
12114468a00fSLai Jiangshan 
1212d565ed63STejun Heo 		spin_unlock(&pool->lock);
121336e227d2STejun Heo 		return 1;
1214bf4ede01STejun Heo 	}
1215d565ed63STejun Heo 	spin_unlock(&pool->lock);
1216bbb68dfaSTejun Heo fail:
1217bbb68dfaSTejun Heo 	local_irq_restore(*flags);
1218bbb68dfaSTejun Heo 	if (work_is_canceling(work))
1219bbb68dfaSTejun Heo 		return -ENOENT;
1220bbb68dfaSTejun Heo 	cpu_relax();
122136e227d2STejun Heo 	return -EAGAIN;
1222bf4ede01STejun Heo }
1223bf4ede01STejun Heo 
1224bf4ede01STejun Heo /**
1225706026c2STejun Heo  * insert_work - insert a work into a pool
1226112202d9STejun Heo  * @pwq: pwq @work belongs to
12274690c4abSTejun Heo  * @work: work to insert
12284690c4abSTejun Heo  * @head: insertion point
12294690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
12304690c4abSTejun Heo  *
1231112202d9STejun Heo  * Insert @work which belongs to @pwq after @head.  @extra_flags is or'd to
1232706026c2STejun Heo  * work_struct flags.
12334690c4abSTejun Heo  *
12344690c4abSTejun Heo  * CONTEXT:
1235d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1236365970a1SDavid Howells  */
1237112202d9STejun Heo static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1238112202d9STejun Heo 			struct list_head *head, unsigned int extra_flags)
1239b89deed3SOleg Nesterov {
1240112202d9STejun Heo 	struct worker_pool *pool = pwq->pool;
1241e1d8aa9fSFrederic Weisbecker 
12424690c4abSTejun Heo 	/* we own @work, set data and link */
1243112202d9STejun Heo 	set_work_pwq(work, pwq, extra_flags);
12441a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
12458864b4e5STejun Heo 	get_pwq(pwq);
1246e22bee78STejun Heo 
1247e22bee78STejun Heo 	/*
1248c5aa87bbSTejun Heo 	 * Ensure either wq_worker_sleeping() sees the above
1249c5aa87bbSTejun Heo 	 * list_add_tail() or we see zero nr_running to avoid workers lying
1250c5aa87bbSTejun Heo 	 * around lazily while there are works to be processed.
1251e22bee78STejun Heo 	 */
1252e22bee78STejun Heo 	smp_mb();
1253e22bee78STejun Heo 
125463d95a91STejun Heo 	if (__need_more_worker(pool))
125563d95a91STejun Heo 		wake_up_worker(pool);
1256b89deed3SOleg Nesterov }
1257b89deed3SOleg Nesterov 
1258c8efcc25STejun Heo /*
1259c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
12608d03ecfeSTejun Heo  * same workqueue.
1261c8efcc25STejun Heo  */
1262c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
1263c8efcc25STejun Heo {
1264c8efcc25STejun Heo 	struct worker *worker;
1265c8efcc25STejun Heo 
12668d03ecfeSTejun Heo 	worker = current_wq_worker();
1267c8efcc25STejun Heo 	/*
12688d03ecfeSTejun Heo 	 * Return %true iff I'm a worker execuing a work item on @wq.  If
12698d03ecfeSTejun Heo 	 * I'm @worker, it's safe to dereference it without locking.
1270c8efcc25STejun Heo 	 */
1271112202d9STejun Heo 	return worker && worker->current_pwq->wq == wq;
1272c8efcc25STejun Heo }
1273c8efcc25STejun Heo 
1274d84ff051STejun Heo static void __queue_work(int cpu, struct workqueue_struct *wq,
12751da177e4SLinus Torvalds 			 struct work_struct *work)
12761da177e4SLinus Torvalds {
1277112202d9STejun Heo 	struct pool_workqueue *pwq;
1278c9178087STejun Heo 	struct worker_pool *last_pool;
12791e19ffc6STejun Heo 	struct list_head *worklist;
12808a2e8e5dSTejun Heo 	unsigned int work_flags;
1281b75cac93SJoonsoo Kim 	unsigned int req_cpu = cpu;
12828930cabaSTejun Heo 
12838930cabaSTejun Heo 	/*
12848930cabaSTejun Heo 	 * While a work item is PENDING && off queue, a task trying to
12858930cabaSTejun Heo 	 * steal the PENDING will busy-loop waiting for it to either get
12868930cabaSTejun Heo 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
12878930cabaSTejun Heo 	 * happen with IRQ disabled.
12888930cabaSTejun Heo 	 */
12898930cabaSTejun Heo 	WARN_ON_ONCE(!irqs_disabled());
12901da177e4SLinus Torvalds 
1291dc186ad7SThomas Gleixner 	debug_work_activate(work);
12921e19ffc6STejun Heo 
1293c8efcc25STejun Heo 	/* if dying, only works from the same workqueue are allowed */
1294618b01ebSTejun Heo 	if (unlikely(wq->flags & __WQ_DRAINING) &&
1295c8efcc25STejun Heo 	    WARN_ON_ONCE(!is_chained_work(wq)))
1296e41e704bSTejun Heo 		return;
12979e8cd2f5STejun Heo retry:
1298df2d5ae4STejun Heo 	if (req_cpu == WORK_CPU_UNBOUND)
1299f3421797STejun Heo 		cpu = raw_smp_processor_id();
1300df2d5ae4STejun Heo 
1301df2d5ae4STejun Heo 	/* pwq which will be used unless @work is executing elsewhere */
1302df2d5ae4STejun Heo 	if (!(wq->flags & WQ_UNBOUND))
1303c9178087STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1304df2d5ae4STejun Heo 	else
1305df2d5ae4STejun Heo 		pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1306f3421797STejun Heo 
130718aa9effSTejun Heo 	/*
1308c9178087STejun Heo 	 * If @work was previously on a different pool, it might still be
1309c9178087STejun Heo 	 * running there, in which case the work needs to be queued on that
1310c9178087STejun Heo 	 * pool to guarantee non-reentrancy.
131118aa9effSTejun Heo 	 */
1312c9e7cf27STejun Heo 	last_pool = get_work_pool(work);
1313112202d9STejun Heo 	if (last_pool && last_pool != pwq->pool) {
131418aa9effSTejun Heo 		struct worker *worker;
131518aa9effSTejun Heo 
1316d565ed63STejun Heo 		spin_lock(&last_pool->lock);
131718aa9effSTejun Heo 
1318c9e7cf27STejun Heo 		worker = find_worker_executing_work(last_pool, work);
131918aa9effSTejun Heo 
1320112202d9STejun Heo 		if (worker && worker->current_pwq->wq == wq) {
1321c9178087STejun Heo 			pwq = worker->current_pwq;
13228594fadeSLai Jiangshan 		} else {
132318aa9effSTejun Heo 			/* meh... not running there, queue here */
1324d565ed63STejun Heo 			spin_unlock(&last_pool->lock);
1325112202d9STejun Heo 			spin_lock(&pwq->pool->lock);
132618aa9effSTejun Heo 		}
13278930cabaSTejun Heo 	} else {
1328112202d9STejun Heo 		spin_lock(&pwq->pool->lock);
13298930cabaSTejun Heo 	}
1330502ca9d8STejun Heo 
13319e8cd2f5STejun Heo 	/*
13329e8cd2f5STejun Heo 	 * pwq is determined and locked.  For unbound pools, we could have
13339e8cd2f5STejun Heo 	 * raced with pwq release and it could already be dead.  If its
13349e8cd2f5STejun Heo 	 * refcnt is zero, repeat pwq selection.  Note that pwqs never die
1335df2d5ae4STejun Heo 	 * without another pwq replacing it in the numa_pwq_tbl or while
1336df2d5ae4STejun Heo 	 * work items are executing on it, so the retrying is guaranteed to
13379e8cd2f5STejun Heo 	 * make forward-progress.
13389e8cd2f5STejun Heo 	 */
13399e8cd2f5STejun Heo 	if (unlikely(!pwq->refcnt)) {
13409e8cd2f5STejun Heo 		if (wq->flags & WQ_UNBOUND) {
13419e8cd2f5STejun Heo 			spin_unlock(&pwq->pool->lock);
13429e8cd2f5STejun Heo 			cpu_relax();
13439e8cd2f5STejun Heo 			goto retry;
13449e8cd2f5STejun Heo 		}
13459e8cd2f5STejun Heo 		/* oops */
13469e8cd2f5STejun Heo 		WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
13479e8cd2f5STejun Heo 			  wq->name, cpu);
13489e8cd2f5STejun Heo 	}
13499e8cd2f5STejun Heo 
1350112202d9STejun Heo 	/* pwq determined, queue */
1351112202d9STejun Heo 	trace_workqueue_queue_work(req_cpu, pwq, work);
1352502ca9d8STejun Heo 
1353f5b2552bSDan Carpenter 	if (WARN_ON(!list_empty(&work->entry))) {
1354112202d9STejun Heo 		spin_unlock(&pwq->pool->lock);
1355f5b2552bSDan Carpenter 		return;
1356f5b2552bSDan Carpenter 	}
13571e19ffc6STejun Heo 
1358112202d9STejun Heo 	pwq->nr_in_flight[pwq->work_color]++;
1359112202d9STejun Heo 	work_flags = work_color_to_flags(pwq->work_color);
13601e19ffc6STejun Heo 
1361112202d9STejun Heo 	if (likely(pwq->nr_active < pwq->max_active)) {
1362cdadf009STejun Heo 		trace_workqueue_activate_work(work);
1363112202d9STejun Heo 		pwq->nr_active++;
1364112202d9STejun Heo 		worklist = &pwq->pool->worklist;
13658a2e8e5dSTejun Heo 	} else {
13668a2e8e5dSTejun Heo 		work_flags |= WORK_STRUCT_DELAYED;
1367112202d9STejun Heo 		worklist = &pwq->delayed_works;
13688a2e8e5dSTejun Heo 	}
13691e19ffc6STejun Heo 
1370112202d9STejun Heo 	insert_work(pwq, work, worklist, work_flags);
13711e19ffc6STejun Heo 
1372112202d9STejun Heo 	spin_unlock(&pwq->pool->lock);
13731da177e4SLinus Torvalds }
13741da177e4SLinus Torvalds 
13750fcb78c2SRolf Eike Beer /**
1376c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
1377c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
1378c1a220e7SZhang Rui  * @wq: workqueue to use
1379c1a220e7SZhang Rui  * @work: work to queue
1380c1a220e7SZhang Rui  *
1381d4283e93STejun Heo  * Returns %false if @work was already on a queue, %true otherwise.
1382c1a220e7SZhang Rui  *
1383c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
1384c1a220e7SZhang Rui  * can't go away.
1385c1a220e7SZhang Rui  */
1386d4283e93STejun Heo bool queue_work_on(int cpu, struct workqueue_struct *wq,
1387d4283e93STejun Heo 		   struct work_struct *work)
1388c1a220e7SZhang Rui {
1389d4283e93STejun Heo 	bool ret = false;
13908930cabaSTejun Heo 	unsigned long flags;
13918930cabaSTejun Heo 
13928930cabaSTejun Heo 	local_irq_save(flags);
1393c1a220e7SZhang Rui 
139422df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
13954690c4abSTejun Heo 		__queue_work(cpu, wq, work);
1396d4283e93STejun Heo 		ret = true;
1397c1a220e7SZhang Rui 	}
13988930cabaSTejun Heo 
13998930cabaSTejun Heo 	local_irq_restore(flags);
1400c1a220e7SZhang Rui 	return ret;
1401c1a220e7SZhang Rui }
1402c1a220e7SZhang Rui EXPORT_SYMBOL_GPL(queue_work_on);
1403c1a220e7SZhang Rui 
1404d8e794dfSTejun Heo void delayed_work_timer_fn(unsigned long __data)
14051da177e4SLinus Torvalds {
140652bad64dSDavid Howells 	struct delayed_work *dwork = (struct delayed_work *)__data;
14071da177e4SLinus Torvalds 
1408e0aecdd8STejun Heo 	/* should have been called from irqsafe timer with irq already off */
140960c057bcSLai Jiangshan 	__queue_work(dwork->cpu, dwork->wq, &dwork->work);
14101da177e4SLinus Torvalds }
14111438ade5SKonstantin Khlebnikov EXPORT_SYMBOL(delayed_work_timer_fn);
14121da177e4SLinus Torvalds 
14137beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
141452bad64dSDavid Howells 				struct delayed_work *dwork, unsigned long delay)
14151da177e4SLinus Torvalds {
14167beb2edfSTejun Heo 	struct timer_list *timer = &dwork->timer;
14177beb2edfSTejun Heo 	struct work_struct *work = &dwork->work;
14181da177e4SLinus Torvalds 
14197beb2edfSTejun Heo 	WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
14207beb2edfSTejun Heo 		     timer->data != (unsigned long)dwork);
1421fc4b514fSTejun Heo 	WARN_ON_ONCE(timer_pending(timer));
1422fc4b514fSTejun Heo 	WARN_ON_ONCE(!list_empty(&work->entry));
14237beb2edfSTejun Heo 
14248852aac2STejun Heo 	/*
14258852aac2STejun Heo 	 * If @delay is 0, queue @dwork->work immediately.  This is for
14268852aac2STejun Heo 	 * both optimization and correctness.  The earliest @timer can
14278852aac2STejun Heo 	 * expire is on the closest next tick and delayed_work users depend
14288852aac2STejun Heo 	 * on that there's no such delay when @delay is 0.
14298852aac2STejun Heo 	 */
14308852aac2STejun Heo 	if (!delay) {
14318852aac2STejun Heo 		__queue_work(cpu, wq, &dwork->work);
14328852aac2STejun Heo 		return;
14338852aac2STejun Heo 	}
14348852aac2STejun Heo 
14357beb2edfSTejun Heo 	timer_stats_timer_set_start_info(&dwork->timer);
14367beb2edfSTejun Heo 
143760c057bcSLai Jiangshan 	dwork->wq = wq;
14381265057fSTejun Heo 	dwork->cpu = cpu;
14397beb2edfSTejun Heo 	timer->expires = jiffies + delay;
14407beb2edfSTejun Heo 
14417beb2edfSTejun Heo 	if (unlikely(cpu != WORK_CPU_UNBOUND))
14427beb2edfSTejun Heo 		add_timer_on(timer, cpu);
14437beb2edfSTejun Heo 	else
14447beb2edfSTejun Heo 		add_timer(timer);
14457beb2edfSTejun Heo }
14461da177e4SLinus Torvalds 
14470fcb78c2SRolf Eike Beer /**
14480fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
14490fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
14500fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1451af9997e4SRandy Dunlap  * @dwork: work to queue
14520fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
14530fcb78c2SRolf Eike Beer  *
1454715f1300STejun Heo  * Returns %false if @work was already on a queue, %true otherwise.  If
1455715f1300STejun Heo  * @delay is zero and @dwork is idle, it will be scheduled for immediate
1456715f1300STejun Heo  * execution.
14570fcb78c2SRolf Eike Beer  */
1458d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
145952bad64dSDavid Howells 			   struct delayed_work *dwork, unsigned long delay)
14607a6bc1cdSVenkatesh Pallipadi {
146152bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
1462d4283e93STejun Heo 	bool ret = false;
14638930cabaSTejun Heo 	unsigned long flags;
14648930cabaSTejun Heo 
14658930cabaSTejun Heo 	/* read the comment in __queue_work() */
14668930cabaSTejun Heo 	local_irq_save(flags);
14677a6bc1cdSVenkatesh Pallipadi 
146822df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
14697beb2edfSTejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
1470d4283e93STejun Heo 		ret = true;
14717a6bc1cdSVenkatesh Pallipadi 	}
14728930cabaSTejun Heo 
14738930cabaSTejun Heo 	local_irq_restore(flags);
14747a6bc1cdSVenkatesh Pallipadi 	return ret;
14757a6bc1cdSVenkatesh Pallipadi }
1476ae90dd5dSDave Jones EXPORT_SYMBOL_GPL(queue_delayed_work_on);
14771da177e4SLinus Torvalds 
1478c8e55f36STejun Heo /**
14798376fe22STejun Heo  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
14808376fe22STejun Heo  * @cpu: CPU number to execute work on
14818376fe22STejun Heo  * @wq: workqueue to use
14828376fe22STejun Heo  * @dwork: work to queue
14838376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
14848376fe22STejun Heo  *
14858376fe22STejun Heo  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
14868376fe22STejun Heo  * modify @dwork's timer so that it expires after @delay.  If @delay is
14878376fe22STejun Heo  * zero, @work is guaranteed to be scheduled immediately regardless of its
14888376fe22STejun Heo  * current state.
14898376fe22STejun Heo  *
14908376fe22STejun Heo  * Returns %false if @dwork was idle and queued, %true if @dwork was
14918376fe22STejun Heo  * pending and its timer was modified.
14928376fe22STejun Heo  *
1493e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
14948376fe22STejun Heo  * See try_to_grab_pending() for details.
14958376fe22STejun Heo  */
14968376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
14978376fe22STejun Heo 			 struct delayed_work *dwork, unsigned long delay)
14988376fe22STejun Heo {
14998376fe22STejun Heo 	unsigned long flags;
15008376fe22STejun Heo 	int ret;
15018376fe22STejun Heo 
15028376fe22STejun Heo 	do {
15038376fe22STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
15048376fe22STejun Heo 	} while (unlikely(ret == -EAGAIN));
15058376fe22STejun Heo 
15068376fe22STejun Heo 	if (likely(ret >= 0)) {
15078376fe22STejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
15088376fe22STejun Heo 		local_irq_restore(flags);
15098376fe22STejun Heo 	}
15108376fe22STejun Heo 
15118376fe22STejun Heo 	/* -ENOENT from try_to_grab_pending() becomes %true */
15128376fe22STejun Heo 	return ret;
15138376fe22STejun Heo }
15148376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
15158376fe22STejun Heo 
15168376fe22STejun Heo /**
1517c8e55f36STejun Heo  * worker_enter_idle - enter idle state
1518c8e55f36STejun Heo  * @worker: worker which is entering idle state
1519c8e55f36STejun Heo  *
1520c8e55f36STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
1521c8e55f36STejun Heo  * necessary.
1522c8e55f36STejun Heo  *
1523c8e55f36STejun Heo  * LOCKING:
1524d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1525c8e55f36STejun Heo  */
1526c8e55f36STejun Heo static void worker_enter_idle(struct worker *worker)
15271da177e4SLinus Torvalds {
1528bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1529c8e55f36STejun Heo 
15306183c009STejun Heo 	if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
15316183c009STejun Heo 	    WARN_ON_ONCE(!list_empty(&worker->entry) &&
15326183c009STejun Heo 			 (worker->hentry.next || worker->hentry.pprev)))
15336183c009STejun Heo 		return;
1534c8e55f36STejun Heo 
1535cb444766STejun Heo 	/* can't use worker_set_flags(), also called from start_worker() */
1536cb444766STejun Heo 	worker->flags |= WORKER_IDLE;
1537bd7bdd43STejun Heo 	pool->nr_idle++;
1538e22bee78STejun Heo 	worker->last_active = jiffies;
1539c8e55f36STejun Heo 
1540c8e55f36STejun Heo 	/* idle_list is LIFO */
1541bd7bdd43STejun Heo 	list_add(&worker->entry, &pool->idle_list);
1542db7bccf4STejun Heo 
154363d95a91STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1544628c78e7STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1545cb444766STejun Heo 
1546544ecf31STejun Heo 	/*
1547706026c2STejun Heo 	 * Sanity check nr_running.  Because wq_unbind_fn() releases
1548d565ed63STejun Heo 	 * pool->lock between setting %WORKER_UNBOUND and zapping
1549628c78e7STejun Heo 	 * nr_running, the warning may trigger spuriously.  Check iff
1550628c78e7STejun Heo 	 * unbind is not in progress.
1551544ecf31STejun Heo 	 */
155224647570STejun Heo 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1553bd7bdd43STejun Heo 		     pool->nr_workers == pool->nr_idle &&
1554e19e397aSTejun Heo 		     atomic_read(&pool->nr_running));
1555c8e55f36STejun Heo }
1556c8e55f36STejun Heo 
1557c8e55f36STejun Heo /**
1558c8e55f36STejun Heo  * worker_leave_idle - leave idle state
1559c8e55f36STejun Heo  * @worker: worker which is leaving idle state
1560c8e55f36STejun Heo  *
1561c8e55f36STejun Heo  * @worker is leaving idle state.  Update stats.
1562c8e55f36STejun Heo  *
1563c8e55f36STejun Heo  * LOCKING:
1564d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1565c8e55f36STejun Heo  */
1566c8e55f36STejun Heo static void worker_leave_idle(struct worker *worker)
1567c8e55f36STejun Heo {
1568bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1569c8e55f36STejun Heo 
15706183c009STejun Heo 	if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
15716183c009STejun Heo 		return;
1572d302f017STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
1573bd7bdd43STejun Heo 	pool->nr_idle--;
1574c8e55f36STejun Heo 	list_del_init(&worker->entry);
1575c8e55f36STejun Heo }
1576c8e55f36STejun Heo 
1577e22bee78STejun Heo /**
1578f36dc67bSLai Jiangshan  * worker_maybe_bind_and_lock - try to bind %current to worker_pool and lock it
1579f36dc67bSLai Jiangshan  * @pool: target worker_pool
1580f36dc67bSLai Jiangshan  *
1581f36dc67bSLai Jiangshan  * Bind %current to the cpu of @pool if it is associated and lock @pool.
1582e22bee78STejun Heo  *
1583e22bee78STejun Heo  * Works which are scheduled while the cpu is online must at least be
1584e22bee78STejun Heo  * scheduled to a worker which is bound to the cpu so that if they are
1585e22bee78STejun Heo  * flushed from cpu callbacks while cpu is going down, they are
1586e22bee78STejun Heo  * guaranteed to execute on the cpu.
1587e22bee78STejun Heo  *
1588f5faa077SLai Jiangshan  * This function is to be used by unbound workers and rescuers to bind
1589e22bee78STejun Heo  * themselves to the target cpu and may race with cpu going down or
1590e22bee78STejun Heo  * coming online.  kthread_bind() can't be used because it may put the
1591e22bee78STejun Heo  * worker to already dead cpu and set_cpus_allowed_ptr() can't be used
1592706026c2STejun Heo  * verbatim as it's best effort and blocking and pool may be
1593e22bee78STejun Heo  * [dis]associated in the meantime.
1594e22bee78STejun Heo  *
1595706026c2STejun Heo  * This function tries set_cpus_allowed() and locks pool and verifies the
159624647570STejun Heo  * binding against %POOL_DISASSOCIATED which is set during
1597f2d5a0eeSTejun Heo  * %CPU_DOWN_PREPARE and cleared during %CPU_ONLINE, so if the worker
1598f2d5a0eeSTejun Heo  * enters idle state or fetches works without dropping lock, it can
1599f2d5a0eeSTejun Heo  * guarantee the scheduling requirement described in the first paragraph.
1600e22bee78STejun Heo  *
1601e22bee78STejun Heo  * CONTEXT:
1602d565ed63STejun Heo  * Might sleep.  Called without any lock but returns with pool->lock
1603e22bee78STejun Heo  * held.
1604e22bee78STejun Heo  *
1605e22bee78STejun Heo  * RETURNS:
1606706026c2STejun Heo  * %true if the associated pool is online (@worker is successfully
1607e22bee78STejun Heo  * bound), %false if offline.
1608e22bee78STejun Heo  */
1609f36dc67bSLai Jiangshan static bool worker_maybe_bind_and_lock(struct worker_pool *pool)
1610d565ed63STejun Heo __acquires(&pool->lock)
1611e22bee78STejun Heo {
1612e22bee78STejun Heo 	while (true) {
1613e22bee78STejun Heo 		/*
1614e22bee78STejun Heo 		 * The following call may fail, succeed or succeed
1615e22bee78STejun Heo 		 * without actually migrating the task to the cpu if
1616e22bee78STejun Heo 		 * it races with cpu hotunplug operation.  Verify
161724647570STejun Heo 		 * against POOL_DISASSOCIATED.
1618e22bee78STejun Heo 		 */
161924647570STejun Heo 		if (!(pool->flags & POOL_DISASSOCIATED))
16207a4e344cSTejun Heo 			set_cpus_allowed_ptr(current, pool->attrs->cpumask);
1621e22bee78STejun Heo 
1622d565ed63STejun Heo 		spin_lock_irq(&pool->lock);
162324647570STejun Heo 		if (pool->flags & POOL_DISASSOCIATED)
1624e22bee78STejun Heo 			return false;
1625f5faa077SLai Jiangshan 		if (task_cpu(current) == pool->cpu &&
16267a4e344cSTejun Heo 		    cpumask_equal(&current->cpus_allowed, pool->attrs->cpumask))
1627e22bee78STejun Heo 			return true;
1628d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
1629e22bee78STejun Heo 
16305035b20fSTejun Heo 		/*
16315035b20fSTejun Heo 		 * We've raced with CPU hot[un]plug.  Give it a breather
16325035b20fSTejun Heo 		 * and retry migration.  cond_resched() is required here;
16335035b20fSTejun Heo 		 * otherwise, we might deadlock against cpu_stop trying to
16345035b20fSTejun Heo 		 * bring down the CPU on non-preemptive kernel.
16355035b20fSTejun Heo 		 */
1636e22bee78STejun Heo 		cpu_relax();
16375035b20fSTejun Heo 		cond_resched();
1638e22bee78STejun Heo 	}
1639e22bee78STejun Heo }
1640e22bee78STejun Heo 
1641c34056a3STejun Heo static struct worker *alloc_worker(void)
1642c34056a3STejun Heo {
1643c34056a3STejun Heo 	struct worker *worker;
1644c34056a3STejun Heo 
1645c34056a3STejun Heo 	worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1646c8e55f36STejun Heo 	if (worker) {
1647c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
1648affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
1649e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
1650e22bee78STejun Heo 		worker->flags = WORKER_PREP;
1651c8e55f36STejun Heo 	}
1652c34056a3STejun Heo 	return worker;
1653c34056a3STejun Heo }
1654c34056a3STejun Heo 
1655c34056a3STejun Heo /**
1656c34056a3STejun Heo  * create_worker - create a new workqueue worker
165763d95a91STejun Heo  * @pool: pool the new worker will belong to
1658c34056a3STejun Heo  *
165963d95a91STejun Heo  * Create a new worker which is bound to @pool.  The returned worker
1660c34056a3STejun Heo  * can be started by calling start_worker() or destroyed using
1661c34056a3STejun Heo  * destroy_worker().
1662c34056a3STejun Heo  *
1663c34056a3STejun Heo  * CONTEXT:
1664c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
1665c34056a3STejun Heo  *
1666c34056a3STejun Heo  * RETURNS:
1667c34056a3STejun Heo  * Pointer to the newly created worker.
1668c34056a3STejun Heo  */
1669bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
1670c34056a3STejun Heo {
1671c34056a3STejun Heo 	struct worker *worker = NULL;
1672f3421797STejun Heo 	int id = -1;
1673e3c916a4STejun Heo 	char id_buf[16];
1674c34056a3STejun Heo 
1675cd549687STejun Heo 	lockdep_assert_held(&pool->manager_mutex);
1676cd549687STejun Heo 
1677822d8405STejun Heo 	/*
1678822d8405STejun Heo 	 * ID is needed to determine kthread name.  Allocate ID first
1679822d8405STejun Heo 	 * without installing the pointer.
1680822d8405STejun Heo 	 */
1681822d8405STejun Heo 	idr_preload(GFP_KERNEL);
1682d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
1683822d8405STejun Heo 
1684822d8405STejun Heo 	id = idr_alloc(&pool->worker_idr, NULL, 0, 0, GFP_NOWAIT);
1685822d8405STejun Heo 
1686d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
1687822d8405STejun Heo 	idr_preload_end();
1688822d8405STejun Heo 	if (id < 0)
1689c34056a3STejun Heo 		goto fail;
1690c34056a3STejun Heo 
1691c34056a3STejun Heo 	worker = alloc_worker();
1692c34056a3STejun Heo 	if (!worker)
1693c34056a3STejun Heo 		goto fail;
1694c34056a3STejun Heo 
1695bd7bdd43STejun Heo 	worker->pool = pool;
1696c34056a3STejun Heo 	worker->id = id;
1697c34056a3STejun Heo 
169829c91e99STejun Heo 	if (pool->cpu >= 0)
1699e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
1700e3c916a4STejun Heo 			 pool->attrs->nice < 0  ? "H" : "");
1701f3421797STejun Heo 	else
1702e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
1703e3c916a4STejun Heo 
1704f3f90ad4STejun Heo 	worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
1705e3c916a4STejun Heo 					      "kworker/%s", id_buf);
1706c34056a3STejun Heo 	if (IS_ERR(worker->task))
1707c34056a3STejun Heo 		goto fail;
1708c34056a3STejun Heo 
1709c5aa87bbSTejun Heo 	/*
1710c5aa87bbSTejun Heo 	 * set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
1711c5aa87bbSTejun Heo 	 * online CPUs.  It'll be re-applied when any of the CPUs come up.
1712c5aa87bbSTejun Heo 	 */
17137a4e344cSTejun Heo 	set_user_nice(worker->task, pool->attrs->nice);
17147a4e344cSTejun Heo 	set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
17153270476aSTejun Heo 
171614a40ffcSTejun Heo 	/* prevent userland from meddling with cpumask of workqueue workers */
171714a40ffcSTejun Heo 	worker->task->flags |= PF_NO_SETAFFINITY;
17187a4e344cSTejun Heo 
17197a4e344cSTejun Heo 	/*
17207a4e344cSTejun Heo 	 * The caller is responsible for ensuring %POOL_DISASSOCIATED
17217a4e344cSTejun Heo 	 * remains stable across this function.  See the comments above the
17227a4e344cSTejun Heo 	 * flag definition for details.
17237a4e344cSTejun Heo 	 */
17247a4e344cSTejun Heo 	if (pool->flags & POOL_DISASSOCIATED)
1725f3421797STejun Heo 		worker->flags |= WORKER_UNBOUND;
1726c34056a3STejun Heo 
1727822d8405STejun Heo 	/* successful, commit the pointer to idr */
1728822d8405STejun Heo 	spin_lock_irq(&pool->lock);
1729822d8405STejun Heo 	idr_replace(&pool->worker_idr, worker, worker->id);
1730822d8405STejun Heo 	spin_unlock_irq(&pool->lock);
1731822d8405STejun Heo 
1732c34056a3STejun Heo 	return worker;
1733822d8405STejun Heo 
1734c34056a3STejun Heo fail:
1735c34056a3STejun Heo 	if (id >= 0) {
1736d565ed63STejun Heo 		spin_lock_irq(&pool->lock);
1737822d8405STejun Heo 		idr_remove(&pool->worker_idr, id);
1738d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
1739c34056a3STejun Heo 	}
1740c34056a3STejun Heo 	kfree(worker);
1741c34056a3STejun Heo 	return NULL;
1742c34056a3STejun Heo }
1743c34056a3STejun Heo 
1744c34056a3STejun Heo /**
1745c34056a3STejun Heo  * start_worker - start a newly created worker
1746c34056a3STejun Heo  * @worker: worker to start
1747c34056a3STejun Heo  *
1748706026c2STejun Heo  * Make the pool aware of @worker and start it.
1749c34056a3STejun Heo  *
1750c34056a3STejun Heo  * CONTEXT:
1751d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1752c34056a3STejun Heo  */
1753c34056a3STejun Heo static void start_worker(struct worker *worker)
1754c34056a3STejun Heo {
1755cb444766STejun Heo 	worker->flags |= WORKER_STARTED;
1756bd7bdd43STejun Heo 	worker->pool->nr_workers++;
1757c8e55f36STejun Heo 	worker_enter_idle(worker);
1758c34056a3STejun Heo 	wake_up_process(worker->task);
1759c34056a3STejun Heo }
1760c34056a3STejun Heo 
1761c34056a3STejun Heo /**
1762ebf44d16STejun Heo  * create_and_start_worker - create and start a worker for a pool
1763ebf44d16STejun Heo  * @pool: the target pool
1764ebf44d16STejun Heo  *
1765cd549687STejun Heo  * Grab the managership of @pool and create and start a new worker for it.
1766ebf44d16STejun Heo  */
1767ebf44d16STejun Heo static int create_and_start_worker(struct worker_pool *pool)
1768ebf44d16STejun Heo {
1769ebf44d16STejun Heo 	struct worker *worker;
1770ebf44d16STejun Heo 
1771cd549687STejun Heo 	mutex_lock(&pool->manager_mutex);
1772cd549687STejun Heo 
1773ebf44d16STejun Heo 	worker = create_worker(pool);
1774ebf44d16STejun Heo 	if (worker) {
1775ebf44d16STejun Heo 		spin_lock_irq(&pool->lock);
1776ebf44d16STejun Heo 		start_worker(worker);
1777ebf44d16STejun Heo 		spin_unlock_irq(&pool->lock);
1778ebf44d16STejun Heo 	}
1779ebf44d16STejun Heo 
1780cd549687STejun Heo 	mutex_unlock(&pool->manager_mutex);
1781cd549687STejun Heo 
1782ebf44d16STejun Heo 	return worker ? 0 : -ENOMEM;
1783ebf44d16STejun Heo }
1784ebf44d16STejun Heo 
1785ebf44d16STejun Heo /**
1786c34056a3STejun Heo  * destroy_worker - destroy a workqueue worker
1787c34056a3STejun Heo  * @worker: worker to be destroyed
1788c34056a3STejun Heo  *
1789706026c2STejun Heo  * Destroy @worker and adjust @pool stats accordingly.
1790c8e55f36STejun Heo  *
1791c8e55f36STejun Heo  * CONTEXT:
1792d565ed63STejun Heo  * spin_lock_irq(pool->lock) which is released and regrabbed.
1793c34056a3STejun Heo  */
1794c34056a3STejun Heo static void destroy_worker(struct worker *worker)
1795c34056a3STejun Heo {
1796bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1797c34056a3STejun Heo 
1798cd549687STejun Heo 	lockdep_assert_held(&pool->manager_mutex);
1799cd549687STejun Heo 	lockdep_assert_held(&pool->lock);
1800cd549687STejun Heo 
1801c34056a3STejun Heo 	/* sanity check frenzy */
18026183c009STejun Heo 	if (WARN_ON(worker->current_work) ||
18036183c009STejun Heo 	    WARN_ON(!list_empty(&worker->scheduled)))
18046183c009STejun Heo 		return;
1805c34056a3STejun Heo 
1806c8e55f36STejun Heo 	if (worker->flags & WORKER_STARTED)
1807bd7bdd43STejun Heo 		pool->nr_workers--;
1808c8e55f36STejun Heo 	if (worker->flags & WORKER_IDLE)
1809bd7bdd43STejun Heo 		pool->nr_idle--;
1810c8e55f36STejun Heo 
1811c8e55f36STejun Heo 	list_del_init(&worker->entry);
1812cb444766STejun Heo 	worker->flags |= WORKER_DIE;
1813c8e55f36STejun Heo 
1814822d8405STejun Heo 	idr_remove(&pool->worker_idr, worker->id);
1815822d8405STejun Heo 
1816d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
1817c8e55f36STejun Heo 
1818c34056a3STejun Heo 	kthread_stop(worker->task);
1819c34056a3STejun Heo 	kfree(worker);
1820c34056a3STejun Heo 
1821d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
1822c34056a3STejun Heo }
1823c34056a3STejun Heo 
182463d95a91STejun Heo static void idle_worker_timeout(unsigned long __pool)
1825e22bee78STejun Heo {
182663d95a91STejun Heo 	struct worker_pool *pool = (void *)__pool;
1827e22bee78STejun Heo 
1828d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
1829e22bee78STejun Heo 
183063d95a91STejun Heo 	if (too_many_workers(pool)) {
1831e22bee78STejun Heo 		struct worker *worker;
1832e22bee78STejun Heo 		unsigned long expires;
1833e22bee78STejun Heo 
1834e22bee78STejun Heo 		/* idle_list is kept in LIFO order, check the last one */
183563d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
1836e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1837e22bee78STejun Heo 
1838e22bee78STejun Heo 		if (time_before(jiffies, expires))
183963d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
1840e22bee78STejun Heo 		else {
1841e22bee78STejun Heo 			/* it's been idle for too long, wake up manager */
184211ebea50STejun Heo 			pool->flags |= POOL_MANAGE_WORKERS;
184363d95a91STejun Heo 			wake_up_worker(pool);
1844e22bee78STejun Heo 		}
1845e22bee78STejun Heo 	}
1846e22bee78STejun Heo 
1847d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
1848e22bee78STejun Heo }
1849e22bee78STejun Heo 
1850493a1724STejun Heo static void send_mayday(struct work_struct *work)
1851e22bee78STejun Heo {
1852112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1853112202d9STejun Heo 	struct workqueue_struct *wq = pwq->wq;
1854493a1724STejun Heo 
18552e109a28STejun Heo 	lockdep_assert_held(&wq_mayday_lock);
1856e22bee78STejun Heo 
1857493008a8STejun Heo 	if (!wq->rescuer)
1858493a1724STejun Heo 		return;
1859e22bee78STejun Heo 
1860e22bee78STejun Heo 	/* mayday mayday mayday */
1861493a1724STejun Heo 	if (list_empty(&pwq->mayday_node)) {
1862493a1724STejun Heo 		list_add_tail(&pwq->mayday_node, &wq->maydays);
1863e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
1864493a1724STejun Heo 	}
1865e22bee78STejun Heo }
1866e22bee78STejun Heo 
1867706026c2STejun Heo static void pool_mayday_timeout(unsigned long __pool)
1868e22bee78STejun Heo {
186963d95a91STejun Heo 	struct worker_pool *pool = (void *)__pool;
1870e22bee78STejun Heo 	struct work_struct *work;
1871e22bee78STejun Heo 
18722e109a28STejun Heo 	spin_lock_irq(&wq_mayday_lock);		/* for wq->maydays */
1873493a1724STejun Heo 	spin_lock(&pool->lock);
1874e22bee78STejun Heo 
187563d95a91STejun Heo 	if (need_to_create_worker(pool)) {
1876e22bee78STejun Heo 		/*
1877e22bee78STejun Heo 		 * We've been trying to create a new worker but
1878e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
1879e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
1880e22bee78STejun Heo 		 * rescuers.
1881e22bee78STejun Heo 		 */
188263d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
1883e22bee78STejun Heo 			send_mayday(work);
1884e22bee78STejun Heo 	}
1885e22bee78STejun Heo 
1886493a1724STejun Heo 	spin_unlock(&pool->lock);
18872e109a28STejun Heo 	spin_unlock_irq(&wq_mayday_lock);
1888e22bee78STejun Heo 
188963d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1890e22bee78STejun Heo }
1891e22bee78STejun Heo 
1892e22bee78STejun Heo /**
1893e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
189463d95a91STejun Heo  * @pool: pool to create a new worker for
1895e22bee78STejun Heo  *
189663d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
1897e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
1898e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
189963d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
1900e22bee78STejun Heo  * possible allocation deadlock.
1901e22bee78STejun Heo  *
1902c5aa87bbSTejun Heo  * On return, need_to_create_worker() is guaranteed to be %false and
1903c5aa87bbSTejun Heo  * may_start_working() %true.
1904e22bee78STejun Heo  *
1905e22bee78STejun Heo  * LOCKING:
1906d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
1907e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
1908e22bee78STejun Heo  * manager.
1909e22bee78STejun Heo  *
1910e22bee78STejun Heo  * RETURNS:
1911c5aa87bbSTejun Heo  * %false if no action was taken and pool->lock stayed locked, %true
1912e22bee78STejun Heo  * otherwise.
1913e22bee78STejun Heo  */
191463d95a91STejun Heo static bool maybe_create_worker(struct worker_pool *pool)
1915d565ed63STejun Heo __releases(&pool->lock)
1916d565ed63STejun Heo __acquires(&pool->lock)
1917e22bee78STejun Heo {
191863d95a91STejun Heo 	if (!need_to_create_worker(pool))
1919e22bee78STejun Heo 		return false;
1920e22bee78STejun Heo restart:
1921d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
19229f9c2364STejun Heo 
1923e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
192463d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1925e22bee78STejun Heo 
1926e22bee78STejun Heo 	while (true) {
1927e22bee78STejun Heo 		struct worker *worker;
1928e22bee78STejun Heo 
1929bc2ae0f5STejun Heo 		worker = create_worker(pool);
1930e22bee78STejun Heo 		if (worker) {
193163d95a91STejun Heo 			del_timer_sync(&pool->mayday_timer);
1932d565ed63STejun Heo 			spin_lock_irq(&pool->lock);
1933e22bee78STejun Heo 			start_worker(worker);
19346183c009STejun Heo 			if (WARN_ON_ONCE(need_to_create_worker(pool)))
19356183c009STejun Heo 				goto restart;
1936e22bee78STejun Heo 			return true;
1937e22bee78STejun Heo 		}
1938e22bee78STejun Heo 
193963d95a91STejun Heo 		if (!need_to_create_worker(pool))
1940e22bee78STejun Heo 			break;
1941e22bee78STejun Heo 
1942e22bee78STejun Heo 		__set_current_state(TASK_INTERRUPTIBLE);
1943e22bee78STejun Heo 		schedule_timeout(CREATE_COOLDOWN);
19449f9c2364STejun Heo 
194563d95a91STejun Heo 		if (!need_to_create_worker(pool))
1946e22bee78STejun Heo 			break;
1947e22bee78STejun Heo 	}
1948e22bee78STejun Heo 
194963d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
1950d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
195163d95a91STejun Heo 	if (need_to_create_worker(pool))
1952e22bee78STejun Heo 		goto restart;
1953e22bee78STejun Heo 	return true;
1954e22bee78STejun Heo }
1955e22bee78STejun Heo 
1956e22bee78STejun Heo /**
1957e22bee78STejun Heo  * maybe_destroy_worker - destroy workers which have been idle for a while
195863d95a91STejun Heo  * @pool: pool to destroy workers for
1959e22bee78STejun Heo  *
196063d95a91STejun Heo  * Destroy @pool workers which have been idle for longer than
1961e22bee78STejun Heo  * IDLE_WORKER_TIMEOUT.
1962e22bee78STejun Heo  *
1963e22bee78STejun Heo  * LOCKING:
1964d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
1965e22bee78STejun Heo  * multiple times.  Called only from manager.
1966e22bee78STejun Heo  *
1967e22bee78STejun Heo  * RETURNS:
1968c5aa87bbSTejun Heo  * %false if no action was taken and pool->lock stayed locked, %true
1969e22bee78STejun Heo  * otherwise.
1970e22bee78STejun Heo  */
197163d95a91STejun Heo static bool maybe_destroy_workers(struct worker_pool *pool)
1972e22bee78STejun Heo {
1973e22bee78STejun Heo 	bool ret = false;
1974e22bee78STejun Heo 
197563d95a91STejun Heo 	while (too_many_workers(pool)) {
1976e22bee78STejun Heo 		struct worker *worker;
1977e22bee78STejun Heo 		unsigned long expires;
1978e22bee78STejun Heo 
197963d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
1980e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1981e22bee78STejun Heo 
1982e22bee78STejun Heo 		if (time_before(jiffies, expires)) {
198363d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
1984e22bee78STejun Heo 			break;
1985e22bee78STejun Heo 		}
1986e22bee78STejun Heo 
1987e22bee78STejun Heo 		destroy_worker(worker);
1988e22bee78STejun Heo 		ret = true;
1989e22bee78STejun Heo 	}
1990e22bee78STejun Heo 
1991e22bee78STejun Heo 	return ret;
1992e22bee78STejun Heo }
1993e22bee78STejun Heo 
1994e22bee78STejun Heo /**
1995e22bee78STejun Heo  * manage_workers - manage worker pool
1996e22bee78STejun Heo  * @worker: self
1997e22bee78STejun Heo  *
1998706026c2STejun Heo  * Assume the manager role and manage the worker pool @worker belongs
1999e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
2000706026c2STejun Heo  * pool.  The exclusion is handled automatically by this function.
2001e22bee78STejun Heo  *
2002e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
2003e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
2004e22bee78STejun Heo  * and may_start_working() is true.
2005e22bee78STejun Heo  *
2006e22bee78STejun Heo  * CONTEXT:
2007d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
2008e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
2009e22bee78STejun Heo  *
2010e22bee78STejun Heo  * RETURNS:
2011d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
2012d565ed63STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
2013e22bee78STejun Heo  */
2014e22bee78STejun Heo static bool manage_workers(struct worker *worker)
2015e22bee78STejun Heo {
201663d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
2017e22bee78STejun Heo 	bool ret = false;
2018e22bee78STejun Heo 
2019bc3a1afcSTejun Heo 	/*
2020bc3a1afcSTejun Heo 	 * Managership is governed by two mutexes - manager_arb and
2021bc3a1afcSTejun Heo 	 * manager_mutex.  manager_arb handles arbitration of manager role.
2022bc3a1afcSTejun Heo 	 * Anyone who successfully grabs manager_arb wins the arbitration
2023bc3a1afcSTejun Heo 	 * and becomes the manager.  mutex_trylock() on pool->manager_arb
2024bc3a1afcSTejun Heo 	 * failure while holding pool->lock reliably indicates that someone
2025bc3a1afcSTejun Heo 	 * else is managing the pool and the worker which failed trylock
2026bc3a1afcSTejun Heo 	 * can proceed to executing work items.  This means that anyone
2027bc3a1afcSTejun Heo 	 * grabbing manager_arb is responsible for actually performing
2028bc3a1afcSTejun Heo 	 * manager duties.  If manager_arb is grabbed and released without
2029bc3a1afcSTejun Heo 	 * actual management, the pool may stall indefinitely.
2030bc3a1afcSTejun Heo 	 *
2031bc3a1afcSTejun Heo 	 * manager_mutex is used for exclusion of actual management
2032bc3a1afcSTejun Heo 	 * operations.  The holder of manager_mutex can be sure that none
2033bc3a1afcSTejun Heo 	 * of management operations, including creation and destruction of
2034bc3a1afcSTejun Heo 	 * workers, won't take place until the mutex is released.  Because
2035bc3a1afcSTejun Heo 	 * manager_mutex doesn't interfere with manager role arbitration,
2036bc3a1afcSTejun Heo 	 * it is guaranteed that the pool's management, while may be
2037bc3a1afcSTejun Heo 	 * delayed, won't be disturbed by someone else grabbing
2038bc3a1afcSTejun Heo 	 * manager_mutex.
2039bc3a1afcSTejun Heo 	 */
204034a06bd6STejun Heo 	if (!mutex_trylock(&pool->manager_arb))
2041e22bee78STejun Heo 		return ret;
2042e22bee78STejun Heo 
2043ee378aa4SLai Jiangshan 	/*
2044bc3a1afcSTejun Heo 	 * With manager arbitration won, manager_mutex would be free in
2045bc3a1afcSTejun Heo 	 * most cases.  trylock first without dropping @pool->lock.
2046ee378aa4SLai Jiangshan 	 */
2047bc3a1afcSTejun Heo 	if (unlikely(!mutex_trylock(&pool->manager_mutex))) {
2048d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
2049bc3a1afcSTejun Heo 		mutex_lock(&pool->manager_mutex);
2050ee378aa4SLai Jiangshan 		ret = true;
2051ee378aa4SLai Jiangshan 	}
2052ee378aa4SLai Jiangshan 
205311ebea50STejun Heo 	pool->flags &= ~POOL_MANAGE_WORKERS;
2054e22bee78STejun Heo 
2055e22bee78STejun Heo 	/*
2056e22bee78STejun Heo 	 * Destroy and then create so that may_start_working() is true
2057e22bee78STejun Heo 	 * on return.
2058e22bee78STejun Heo 	 */
205963d95a91STejun Heo 	ret |= maybe_destroy_workers(pool);
206063d95a91STejun Heo 	ret |= maybe_create_worker(pool);
2061e22bee78STejun Heo 
2062bc3a1afcSTejun Heo 	mutex_unlock(&pool->manager_mutex);
206334a06bd6STejun Heo 	mutex_unlock(&pool->manager_arb);
2064e22bee78STejun Heo 	return ret;
2065e22bee78STejun Heo }
2066e22bee78STejun Heo 
2067a62428c0STejun Heo /**
2068a62428c0STejun Heo  * process_one_work - process single work
2069c34056a3STejun Heo  * @worker: self
2070a62428c0STejun Heo  * @work: work to process
2071a62428c0STejun Heo  *
2072a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
2073a62428c0STejun Heo  * process a single work including synchronization against and
2074a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
2075a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
2076a62428c0STejun Heo  * call this function to process a work.
2077a62428c0STejun Heo  *
2078a62428c0STejun Heo  * CONTEXT:
2079d565ed63STejun Heo  * spin_lock_irq(pool->lock) which is released and regrabbed.
2080a62428c0STejun Heo  */
2081c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
2082d565ed63STejun Heo __releases(&pool->lock)
2083d565ed63STejun Heo __acquires(&pool->lock)
20841da177e4SLinus Torvalds {
2085112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2086bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2087112202d9STejun Heo 	bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
208873f53c4aSTejun Heo 	int work_color;
20897e11629dSTejun Heo 	struct worker *collision;
20904e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
20914e6045f1SJohannes Berg 	/*
2092a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
2093a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
2094a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
2095a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
2096a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
20974e6045f1SJohannes Berg 	 */
20984d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
20994d82a1deSPeter Zijlstra 
21004d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
21014e6045f1SJohannes Berg #endif
21026fec10a1STejun Heo 	/*
21036fec10a1STejun Heo 	 * Ensure we're on the correct CPU.  DISASSOCIATED test is
21046fec10a1STejun Heo 	 * necessary to avoid spurious warnings from rescuers servicing the
210524647570STejun Heo 	 * unbound or a disassociated pool.
21066fec10a1STejun Heo 	 */
21075f7dabfdSLai Jiangshan 	WARN_ON_ONCE(!(worker->flags & WORKER_UNBOUND) &&
210824647570STejun Heo 		     !(pool->flags & POOL_DISASSOCIATED) &&
2109ec22ca5eSTejun Heo 		     raw_smp_processor_id() != pool->cpu);
211025511a47STejun Heo 
21117e11629dSTejun Heo 	/*
21127e11629dSTejun Heo 	 * A single work shouldn't be executed concurrently by
21137e11629dSTejun Heo 	 * multiple workers on a single cpu.  Check whether anyone is
21147e11629dSTejun Heo 	 * already processing the work.  If so, defer the work to the
21157e11629dSTejun Heo 	 * currently executing one.
21167e11629dSTejun Heo 	 */
2117c9e7cf27STejun Heo 	collision = find_worker_executing_work(pool, work);
21187e11629dSTejun Heo 	if (unlikely(collision)) {
21197e11629dSTejun Heo 		move_linked_works(work, &collision->scheduled, NULL);
21207e11629dSTejun Heo 		return;
21217e11629dSTejun Heo 	}
21221da177e4SLinus Torvalds 
21238930cabaSTejun Heo 	/* claim and dequeue */
21241da177e4SLinus Torvalds 	debug_work_deactivate(work);
2125c9e7cf27STejun Heo 	hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2126c34056a3STejun Heo 	worker->current_work = work;
2127a2c1c57bSTejun Heo 	worker->current_func = work->func;
2128112202d9STejun Heo 	worker->current_pwq = pwq;
212973f53c4aSTejun Heo 	work_color = get_work_color(work);
21307a22ad75STejun Heo 
2131a62428c0STejun Heo 	list_del_init(&work->entry);
2132a62428c0STejun Heo 
2133649027d7STejun Heo 	/*
2134fb0e7bebSTejun Heo 	 * CPU intensive works don't participate in concurrency
2135fb0e7bebSTejun Heo 	 * management.  They're the scheduler's responsibility.
2136fb0e7bebSTejun Heo 	 */
2137fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2138fb0e7bebSTejun Heo 		worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
2139fb0e7bebSTejun Heo 
2140974271c4STejun Heo 	/*
2141d565ed63STejun Heo 	 * Unbound pool isn't concurrency managed and work items should be
2142974271c4STejun Heo 	 * executed ASAP.  Wake up another worker if necessary.
2143974271c4STejun Heo 	 */
214463d95a91STejun Heo 	if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
214563d95a91STejun Heo 		wake_up_worker(pool);
2146974271c4STejun Heo 
21478930cabaSTejun Heo 	/*
21487c3eed5cSTejun Heo 	 * Record the last pool and clear PENDING which should be the last
2149d565ed63STejun Heo 	 * update to @work.  Also, do this inside @pool->lock so that
215023657bb1STejun Heo 	 * PENDING and queued state changes happen together while IRQ is
215123657bb1STejun Heo 	 * disabled.
21528930cabaSTejun Heo 	 */
21537c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(work, pool->id);
21541da177e4SLinus Torvalds 
2155d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2156365970a1SDavid Howells 
2157112202d9STejun Heo 	lock_map_acquire_read(&pwq->wq->lockdep_map);
21583295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
2159e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
2160a2c1c57bSTejun Heo 	worker->current_func(work);
2161e36c886aSArjan van de Ven 	/*
2162e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
2163e36c886aSArjan van de Ven 	 * point will only record its address.
2164e36c886aSArjan van de Ven 	 */
2165e36c886aSArjan van de Ven 	trace_workqueue_execute_end(work);
21663295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
2167112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
21681da177e4SLinus Torvalds 
2169d5abe669SPeter Zijlstra 	if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2170044c782cSValentin Ilie 		pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2171044c782cSValentin Ilie 		       "     last function: %pf\n",
2172a2c1c57bSTejun Heo 		       current->comm, preempt_count(), task_pid_nr(current),
2173a2c1c57bSTejun Heo 		       worker->current_func);
2174d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
2175d5abe669SPeter Zijlstra 		dump_stack();
2176d5abe669SPeter Zijlstra 	}
2177d5abe669SPeter Zijlstra 
2178d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
2179a62428c0STejun Heo 
2180fb0e7bebSTejun Heo 	/* clear cpu intensive status */
2181fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2182fb0e7bebSTejun Heo 		worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2183fb0e7bebSTejun Heo 
2184a62428c0STejun Heo 	/* we're done with it, release */
218542f8570fSSasha Levin 	hash_del(&worker->hentry);
2186c34056a3STejun Heo 	worker->current_work = NULL;
2187a2c1c57bSTejun Heo 	worker->current_func = NULL;
2188112202d9STejun Heo 	worker->current_pwq = NULL;
2189112202d9STejun Heo 	pwq_dec_nr_in_flight(pwq, work_color);
21901da177e4SLinus Torvalds }
21911da177e4SLinus Torvalds 
2192affee4b2STejun Heo /**
2193affee4b2STejun Heo  * process_scheduled_works - process scheduled works
2194affee4b2STejun Heo  * @worker: self
2195affee4b2STejun Heo  *
2196affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
2197affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
2198affee4b2STejun Heo  * fetches a work from the top and executes it.
2199affee4b2STejun Heo  *
2200affee4b2STejun Heo  * CONTEXT:
2201d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
2202affee4b2STejun Heo  * multiple times.
2203affee4b2STejun Heo  */
2204affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
22051da177e4SLinus Torvalds {
2206affee4b2STejun Heo 	while (!list_empty(&worker->scheduled)) {
2207affee4b2STejun Heo 		struct work_struct *work = list_first_entry(&worker->scheduled,
2208a62428c0STejun Heo 						struct work_struct, entry);
2209c34056a3STejun Heo 		process_one_work(worker, work);
2210a62428c0STejun Heo 	}
22111da177e4SLinus Torvalds }
22121da177e4SLinus Torvalds 
22134690c4abSTejun Heo /**
22144690c4abSTejun Heo  * worker_thread - the worker thread function
2215c34056a3STejun Heo  * @__worker: self
22164690c4abSTejun Heo  *
2217c5aa87bbSTejun Heo  * The worker thread function.  All workers belong to a worker_pool -
2218c5aa87bbSTejun Heo  * either a per-cpu one or dynamic unbound one.  These workers process all
2219c5aa87bbSTejun Heo  * work items regardless of their specific target workqueue.  The only
2220c5aa87bbSTejun Heo  * exception is work items which belong to workqueues with a rescuer which
2221c5aa87bbSTejun Heo  * will be explained in rescuer_thread().
22224690c4abSTejun Heo  */
2223c34056a3STejun Heo static int worker_thread(void *__worker)
22241da177e4SLinus Torvalds {
2225c34056a3STejun Heo 	struct worker *worker = __worker;
2226bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
22271da177e4SLinus Torvalds 
2228e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
2229e22bee78STejun Heo 	worker->task->flags |= PF_WQ_WORKER;
2230c8e55f36STejun Heo woke_up:
2231d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
2232affee4b2STejun Heo 
2233a9ab775bSTejun Heo 	/* am I supposed to die? */
2234a9ab775bSTejun Heo 	if (unlikely(worker->flags & WORKER_DIE)) {
2235d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
2236a9ab775bSTejun Heo 		WARN_ON_ONCE(!list_empty(&worker->entry));
2237e22bee78STejun Heo 		worker->task->flags &= ~PF_WQ_WORKER;
2238c8e55f36STejun Heo 		return 0;
2239c8e55f36STejun Heo 	}
2240c8e55f36STejun Heo 
2241c8e55f36STejun Heo 	worker_leave_idle(worker);
2242db7bccf4STejun Heo recheck:
2243e22bee78STejun Heo 	/* no more worker necessary? */
224463d95a91STejun Heo 	if (!need_more_worker(pool))
2245e22bee78STejun Heo 		goto sleep;
2246e22bee78STejun Heo 
2247e22bee78STejun Heo 	/* do we need to manage? */
224863d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2249e22bee78STejun Heo 		goto recheck;
2250e22bee78STejun Heo 
2251c8e55f36STejun Heo 	/*
2252c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
2253c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
2254c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
2255c8e55f36STejun Heo 	 */
22566183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
2257c8e55f36STejun Heo 
2258e22bee78STejun Heo 	/*
2259a9ab775bSTejun Heo 	 * Finish PREP stage.  We're guaranteed to have at least one idle
2260a9ab775bSTejun Heo 	 * worker or that someone else has already assumed the manager
2261a9ab775bSTejun Heo 	 * role.  This is where @worker starts participating in concurrency
2262a9ab775bSTejun Heo 	 * management if applicable and concurrency management is restored
2263a9ab775bSTejun Heo 	 * after being rebound.  See rebind_workers() for details.
2264e22bee78STejun Heo 	 */
2265a9ab775bSTejun Heo 	worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2266e22bee78STejun Heo 
2267e22bee78STejun Heo 	do {
2268affee4b2STejun Heo 		struct work_struct *work =
2269bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
2270affee4b2STejun Heo 					 struct work_struct, entry);
2271affee4b2STejun Heo 
2272c8e55f36STejun Heo 		if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2273affee4b2STejun Heo 			/* optimization path, not strictly necessary */
2274affee4b2STejun Heo 			process_one_work(worker, work);
2275affee4b2STejun Heo 			if (unlikely(!list_empty(&worker->scheduled)))
2276affee4b2STejun Heo 				process_scheduled_works(worker);
2277affee4b2STejun Heo 		} else {
2278c8e55f36STejun Heo 			move_linked_works(work, &worker->scheduled, NULL);
2279affee4b2STejun Heo 			process_scheduled_works(worker);
2280affee4b2STejun Heo 		}
228163d95a91STejun Heo 	} while (keep_working(pool));
2282affee4b2STejun Heo 
2283e22bee78STejun Heo 	worker_set_flags(worker, WORKER_PREP, false);
2284d313dd85STejun Heo sleep:
228563d95a91STejun Heo 	if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
2286e22bee78STejun Heo 		goto recheck;
2287d313dd85STejun Heo 
2288c8e55f36STejun Heo 	/*
2289d565ed63STejun Heo 	 * pool->lock is held and there's no work to process and no need to
2290d565ed63STejun Heo 	 * manage, sleep.  Workers are woken up only while holding
2291d565ed63STejun Heo 	 * pool->lock or from local cpu, so setting the current state
2292d565ed63STejun Heo 	 * before releasing pool->lock is enough to prevent losing any
2293d565ed63STejun Heo 	 * event.
2294c8e55f36STejun Heo 	 */
2295c8e55f36STejun Heo 	worker_enter_idle(worker);
2296c8e55f36STejun Heo 	__set_current_state(TASK_INTERRUPTIBLE);
2297d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
22981da177e4SLinus Torvalds 	schedule();
2299c8e55f36STejun Heo 	goto woke_up;
23001da177e4SLinus Torvalds }
23011da177e4SLinus Torvalds 
2302e22bee78STejun Heo /**
2303e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
2304111c225aSTejun Heo  * @__rescuer: self
2305e22bee78STejun Heo  *
2306e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
2307493008a8STejun Heo  * workqueue which has WQ_MEM_RECLAIM set.
2308e22bee78STejun Heo  *
2309706026c2STejun Heo  * Regular work processing on a pool may block trying to create a new
2310e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
2311e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
2312e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2313e22bee78STejun Heo  * the problem rescuer solves.
2314e22bee78STejun Heo  *
2315706026c2STejun Heo  * When such condition is possible, the pool summons rescuers of all
2316706026c2STejun Heo  * workqueues which have works queued on the pool and let them process
2317e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
2318e22bee78STejun Heo  *
2319e22bee78STejun Heo  * This should happen rarely.
2320e22bee78STejun Heo  */
2321111c225aSTejun Heo static int rescuer_thread(void *__rescuer)
2322e22bee78STejun Heo {
2323111c225aSTejun Heo 	struct worker *rescuer = __rescuer;
2324111c225aSTejun Heo 	struct workqueue_struct *wq = rescuer->rescue_wq;
2325e22bee78STejun Heo 	struct list_head *scheduled = &rescuer->scheduled;
2326e22bee78STejun Heo 
2327e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
2328111c225aSTejun Heo 
2329111c225aSTejun Heo 	/*
2330111c225aSTejun Heo 	 * Mark rescuer as worker too.  As WORKER_PREP is never cleared, it
2331111c225aSTejun Heo 	 * doesn't participate in concurrency management.
2332111c225aSTejun Heo 	 */
2333111c225aSTejun Heo 	rescuer->task->flags |= PF_WQ_WORKER;
2334e22bee78STejun Heo repeat:
2335e22bee78STejun Heo 	set_current_state(TASK_INTERRUPTIBLE);
23361da177e4SLinus Torvalds 
2337412d32e6SMike Galbraith 	if (kthread_should_stop()) {
2338412d32e6SMike Galbraith 		__set_current_state(TASK_RUNNING);
2339111c225aSTejun Heo 		rescuer->task->flags &= ~PF_WQ_WORKER;
2340e22bee78STejun Heo 		return 0;
2341412d32e6SMike Galbraith 	}
23421da177e4SLinus Torvalds 
2343493a1724STejun Heo 	/* see whether any pwq is asking for help */
23442e109a28STejun Heo 	spin_lock_irq(&wq_mayday_lock);
2345493a1724STejun Heo 
2346493a1724STejun Heo 	while (!list_empty(&wq->maydays)) {
2347493a1724STejun Heo 		struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2348493a1724STejun Heo 					struct pool_workqueue, mayday_node);
2349112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
2350e22bee78STejun Heo 		struct work_struct *work, *n;
2351e22bee78STejun Heo 
2352e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
2353493a1724STejun Heo 		list_del_init(&pwq->mayday_node);
2354493a1724STejun Heo 
23552e109a28STejun Heo 		spin_unlock_irq(&wq_mayday_lock);
2356e22bee78STejun Heo 
2357e22bee78STejun Heo 		/* migrate to the target cpu if possible */
2358f36dc67bSLai Jiangshan 		worker_maybe_bind_and_lock(pool);
2359b3104104SLai Jiangshan 		rescuer->pool = pool;
2360e22bee78STejun Heo 
2361e22bee78STejun Heo 		/*
2362e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
2363e22bee78STejun Heo 		 * process'em.
2364e22bee78STejun Heo 		 */
23656183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&rescuer->scheduled));
2366bd7bdd43STejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry)
2367112202d9STejun Heo 			if (get_work_pwq(work) == pwq)
2368e22bee78STejun Heo 				move_linked_works(work, scheduled, &n);
2369e22bee78STejun Heo 
2370e22bee78STejun Heo 		process_scheduled_works(rescuer);
23717576958aSTejun Heo 
23727576958aSTejun Heo 		/*
2373d565ed63STejun Heo 		 * Leave this pool.  If keep_working() is %true, notify a
23747576958aSTejun Heo 		 * regular worker; otherwise, we end up with 0 concurrency
23757576958aSTejun Heo 		 * and stalling the execution.
23767576958aSTejun Heo 		 */
237763d95a91STejun Heo 		if (keep_working(pool))
237863d95a91STejun Heo 			wake_up_worker(pool);
23797576958aSTejun Heo 
2380b3104104SLai Jiangshan 		rescuer->pool = NULL;
2381493a1724STejun Heo 		spin_unlock(&pool->lock);
23822e109a28STejun Heo 		spin_lock(&wq_mayday_lock);
23831da177e4SLinus Torvalds 	}
23841da177e4SLinus Torvalds 
23852e109a28STejun Heo 	spin_unlock_irq(&wq_mayday_lock);
2386493a1724STejun Heo 
2387111c225aSTejun Heo 	/* rescuers should never participate in concurrency management */
2388111c225aSTejun Heo 	WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2389e22bee78STejun Heo 	schedule();
2390e22bee78STejun Heo 	goto repeat;
23911da177e4SLinus Torvalds }
23921da177e4SLinus Torvalds 
2393fc2e4d70SOleg Nesterov struct wq_barrier {
2394fc2e4d70SOleg Nesterov 	struct work_struct	work;
2395fc2e4d70SOleg Nesterov 	struct completion	done;
2396fc2e4d70SOleg Nesterov };
2397fc2e4d70SOleg Nesterov 
2398fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
2399fc2e4d70SOleg Nesterov {
2400fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2401fc2e4d70SOleg Nesterov 	complete(&barr->done);
2402fc2e4d70SOleg Nesterov }
2403fc2e4d70SOleg Nesterov 
24044690c4abSTejun Heo /**
24054690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
2406112202d9STejun Heo  * @pwq: pwq to insert barrier into
24074690c4abSTejun Heo  * @barr: wq_barrier to insert
2408affee4b2STejun Heo  * @target: target work to attach @barr to
2409affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
24104690c4abSTejun Heo  *
2411affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
2412affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
2413affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
2414affee4b2STejun Heo  * cpu.
2415affee4b2STejun Heo  *
2416affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
2417affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
2418affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
2419affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
2420affee4b2STejun Heo  * after a work with LINKED flag set.
2421affee4b2STejun Heo  *
2422affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
2423112202d9STejun Heo  * underneath us, so we can't reliably determine pwq from @target.
24244690c4abSTejun Heo  *
24254690c4abSTejun Heo  * CONTEXT:
2426d565ed63STejun Heo  * spin_lock_irq(pool->lock).
24274690c4abSTejun Heo  */
2428112202d9STejun Heo static void insert_wq_barrier(struct pool_workqueue *pwq,
2429affee4b2STejun Heo 			      struct wq_barrier *barr,
2430affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
2431fc2e4d70SOleg Nesterov {
2432affee4b2STejun Heo 	struct list_head *head;
2433affee4b2STejun Heo 	unsigned int linked = 0;
2434affee4b2STejun Heo 
2435dc186ad7SThomas Gleixner 	/*
2436d565ed63STejun Heo 	 * debugobject calls are safe here even with pool->lock locked
2437dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
2438dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
2439dc186ad7SThomas Gleixner 	 * might deadlock.
2440dc186ad7SThomas Gleixner 	 */
2441ca1cab37SAndrew Morton 	INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
244222df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2443fc2e4d70SOleg Nesterov 	init_completion(&barr->done);
244483c22520SOleg Nesterov 
2445affee4b2STejun Heo 	/*
2446affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
2447affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
2448affee4b2STejun Heo 	 */
2449affee4b2STejun Heo 	if (worker)
2450affee4b2STejun Heo 		head = worker->scheduled.next;
2451affee4b2STejun Heo 	else {
2452affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
2453affee4b2STejun Heo 
2454affee4b2STejun Heo 		head = target->entry.next;
2455affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
2456affee4b2STejun Heo 		linked = *bits & WORK_STRUCT_LINKED;
2457affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
2458affee4b2STejun Heo 	}
2459affee4b2STejun Heo 
2460dc186ad7SThomas Gleixner 	debug_work_activate(&barr->work);
2461112202d9STejun Heo 	insert_work(pwq, &barr->work, head,
2462affee4b2STejun Heo 		    work_color_to_flags(WORK_NO_COLOR) | linked);
2463fc2e4d70SOleg Nesterov }
2464fc2e4d70SOleg Nesterov 
246573f53c4aSTejun Heo /**
2466112202d9STejun Heo  * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
246773f53c4aSTejun Heo  * @wq: workqueue being flushed
246873f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
246973f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
247073f53c4aSTejun Heo  *
2471112202d9STejun Heo  * Prepare pwqs for workqueue flushing.
247273f53c4aSTejun Heo  *
2473112202d9STejun Heo  * If @flush_color is non-negative, flush_color on all pwqs should be
2474112202d9STejun Heo  * -1.  If no pwq has in-flight commands at the specified color, all
2475112202d9STejun Heo  * pwq->flush_color's stay at -1 and %false is returned.  If any pwq
2476112202d9STejun Heo  * has in flight commands, its pwq->flush_color is set to
2477112202d9STejun Heo  * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
247873f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
247973f53c4aSTejun Heo  *
248073f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
248173f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
248273f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
248373f53c4aSTejun Heo  * is returned.
248473f53c4aSTejun Heo  *
2485112202d9STejun Heo  * If @work_color is non-negative, all pwqs should have the same
248673f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
248773f53c4aSTejun Heo  * advanced to @work_color.
248873f53c4aSTejun Heo  *
248973f53c4aSTejun Heo  * CONTEXT:
24903c25a55dSLai Jiangshan  * mutex_lock(wq->mutex).
249173f53c4aSTejun Heo  *
249273f53c4aSTejun Heo  * RETURNS:
249373f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
249473f53c4aSTejun Heo  * otherwise.
249573f53c4aSTejun Heo  */
2496112202d9STejun Heo static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
249773f53c4aSTejun Heo 				      int flush_color, int work_color)
24981da177e4SLinus Torvalds {
249973f53c4aSTejun Heo 	bool wait = false;
250049e3cf44STejun Heo 	struct pool_workqueue *pwq;
25011da177e4SLinus Torvalds 
250273f53c4aSTejun Heo 	if (flush_color >= 0) {
25036183c009STejun Heo 		WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2504112202d9STejun Heo 		atomic_set(&wq->nr_pwqs_to_flush, 1);
2505dc186ad7SThomas Gleixner 	}
250614441960SOleg Nesterov 
250749e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2508112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
25091da177e4SLinus Torvalds 
2510b09f4fd3SLai Jiangshan 		spin_lock_irq(&pool->lock);
251173f53c4aSTejun Heo 
251273f53c4aSTejun Heo 		if (flush_color >= 0) {
25136183c009STejun Heo 			WARN_ON_ONCE(pwq->flush_color != -1);
251473f53c4aSTejun Heo 
2515112202d9STejun Heo 			if (pwq->nr_in_flight[flush_color]) {
2516112202d9STejun Heo 				pwq->flush_color = flush_color;
2517112202d9STejun Heo 				atomic_inc(&wq->nr_pwqs_to_flush);
251873f53c4aSTejun Heo 				wait = true;
25191da177e4SLinus Torvalds 			}
252073f53c4aSTejun Heo 		}
252173f53c4aSTejun Heo 
252273f53c4aSTejun Heo 		if (work_color >= 0) {
25236183c009STejun Heo 			WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2524112202d9STejun Heo 			pwq->work_color = work_color;
252573f53c4aSTejun Heo 		}
252673f53c4aSTejun Heo 
2527b09f4fd3SLai Jiangshan 		spin_unlock_irq(&pool->lock);
25281da177e4SLinus Torvalds 	}
25291da177e4SLinus Torvalds 
2530112202d9STejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
253173f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
253273f53c4aSTejun Heo 
253373f53c4aSTejun Heo 	return wait;
253483c22520SOleg Nesterov }
25351da177e4SLinus Torvalds 
25360fcb78c2SRolf Eike Beer /**
25371da177e4SLinus Torvalds  * flush_workqueue - ensure that any scheduled work has run to completion.
25380fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
25391da177e4SLinus Torvalds  *
2540c5aa87bbSTejun Heo  * This function sleeps until all work items which were queued on entry
2541c5aa87bbSTejun Heo  * have finished execution, but it is not livelocked by new incoming ones.
25421da177e4SLinus Torvalds  */
25437ad5b3a5SHarvey Harrison void flush_workqueue(struct workqueue_struct *wq)
25441da177e4SLinus Torvalds {
254573f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
254673f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
254773f53c4aSTejun Heo 		.flush_color = -1,
254873f53c4aSTejun Heo 		.done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
254973f53c4aSTejun Heo 	};
255073f53c4aSTejun Heo 	int next_color;
2551b1f4ec17SOleg Nesterov 
25523295f0efSIngo Molnar 	lock_map_acquire(&wq->lockdep_map);
25533295f0efSIngo Molnar 	lock_map_release(&wq->lockdep_map);
255473f53c4aSTejun Heo 
25553c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
255673f53c4aSTejun Heo 
255773f53c4aSTejun Heo 	/*
255873f53c4aSTejun Heo 	 * Start-to-wait phase
255973f53c4aSTejun Heo 	 */
256073f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
256173f53c4aSTejun Heo 
256273f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
256373f53c4aSTejun Heo 		/*
256473f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
256573f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
256673f53c4aSTejun Heo 		 * by one.
256773f53c4aSTejun Heo 		 */
25686183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
256973f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
257073f53c4aSTejun Heo 		wq->work_color = next_color;
257173f53c4aSTejun Heo 
257273f53c4aSTejun Heo 		if (!wq->first_flusher) {
257373f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
25746183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
257573f53c4aSTejun Heo 
257673f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
257773f53c4aSTejun Heo 
2578112202d9STejun Heo 			if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
257973f53c4aSTejun Heo 						       wq->work_color)) {
258073f53c4aSTejun Heo 				/* nothing to flush, done */
258173f53c4aSTejun Heo 				wq->flush_color = next_color;
258273f53c4aSTejun Heo 				wq->first_flusher = NULL;
258373f53c4aSTejun Heo 				goto out_unlock;
258473f53c4aSTejun Heo 			}
258573f53c4aSTejun Heo 		} else {
258673f53c4aSTejun Heo 			/* wait in queue */
25876183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
258873f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
2589112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
259073f53c4aSTejun Heo 		}
259173f53c4aSTejun Heo 	} else {
259273f53c4aSTejun Heo 		/*
259373f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
259473f53c4aSTejun Heo 		 * The next flush completion will assign us
259573f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
259673f53c4aSTejun Heo 		 */
259773f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
259873f53c4aSTejun Heo 	}
259973f53c4aSTejun Heo 
26003c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
260173f53c4aSTejun Heo 
260273f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
260373f53c4aSTejun Heo 
260473f53c4aSTejun Heo 	/*
260573f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
260673f53c4aSTejun Heo 	 *
260773f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
260873f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
260973f53c4aSTejun Heo 	 */
261073f53c4aSTejun Heo 	if (wq->first_flusher != &this_flusher)
261173f53c4aSTejun Heo 		return;
261273f53c4aSTejun Heo 
26133c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
261473f53c4aSTejun Heo 
26154ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
26164ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
26174ce48b37STejun Heo 		goto out_unlock;
26184ce48b37STejun Heo 
261973f53c4aSTejun Heo 	wq->first_flusher = NULL;
262073f53c4aSTejun Heo 
26216183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&this_flusher.list));
26226183c009STejun Heo 	WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
262373f53c4aSTejun Heo 
262473f53c4aSTejun Heo 	while (true) {
262573f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
262673f53c4aSTejun Heo 
262773f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
262873f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
262973f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
263073f53c4aSTejun Heo 				break;
263173f53c4aSTejun Heo 			list_del_init(&next->list);
263273f53c4aSTejun Heo 			complete(&next->done);
263373f53c4aSTejun Heo 		}
263473f53c4aSTejun Heo 
26356183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
263673f53c4aSTejun Heo 			     wq->flush_color != work_next_color(wq->work_color));
263773f53c4aSTejun Heo 
263873f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
263973f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
264073f53c4aSTejun Heo 
264173f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
264273f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
264373f53c4aSTejun Heo 			/*
264473f53c4aSTejun Heo 			 * Assign the same color to all overflowed
264573f53c4aSTejun Heo 			 * flushers, advance work_color and append to
264673f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
264773f53c4aSTejun Heo 			 * phase for these overflowed flushers.
264873f53c4aSTejun Heo 			 */
264973f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
265073f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
265173f53c4aSTejun Heo 
265273f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
265373f53c4aSTejun Heo 
265473f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
265573f53c4aSTejun Heo 					      &wq->flusher_queue);
2656112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
265773f53c4aSTejun Heo 		}
265873f53c4aSTejun Heo 
265973f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
26606183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != wq->work_color);
266173f53c4aSTejun Heo 			break;
266273f53c4aSTejun Heo 		}
266373f53c4aSTejun Heo 
266473f53c4aSTejun Heo 		/*
266573f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
2666112202d9STejun Heo 		 * the new first flusher and arm pwqs.
266773f53c4aSTejun Heo 		 */
26686183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color == wq->work_color);
26696183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color != next->flush_color);
267073f53c4aSTejun Heo 
267173f53c4aSTejun Heo 		list_del_init(&next->list);
267273f53c4aSTejun Heo 		wq->first_flusher = next;
267373f53c4aSTejun Heo 
2674112202d9STejun Heo 		if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
267573f53c4aSTejun Heo 			break;
267673f53c4aSTejun Heo 
267773f53c4aSTejun Heo 		/*
267873f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
267973f53c4aSTejun Heo 		 * flusher and repeat cascading.
268073f53c4aSTejun Heo 		 */
268173f53c4aSTejun Heo 		wq->first_flusher = NULL;
268273f53c4aSTejun Heo 	}
268373f53c4aSTejun Heo 
268473f53c4aSTejun Heo out_unlock:
26853c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
26861da177e4SLinus Torvalds }
2687ae90dd5dSDave Jones EXPORT_SYMBOL_GPL(flush_workqueue);
26881da177e4SLinus Torvalds 
26899c5a2ba7STejun Heo /**
26909c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
26919c5a2ba7STejun Heo  * @wq: workqueue to drain
26929c5a2ba7STejun Heo  *
26939c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
26949c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
26959c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
26969c5a2ba7STejun Heo  * repeatedly until it becomes empty.  The number of flushing is detemined
26979c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
26989c5a2ba7STejun Heo  * takes too long.
26999c5a2ba7STejun Heo  */
27009c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
27019c5a2ba7STejun Heo {
27029c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
270349e3cf44STejun Heo 	struct pool_workqueue *pwq;
27049c5a2ba7STejun Heo 
27059c5a2ba7STejun Heo 	/*
27069c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
27079c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
2708618b01ebSTejun Heo 	 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
27099c5a2ba7STejun Heo 	 */
271087fc741eSLai Jiangshan 	mutex_lock(&wq->mutex);
27119c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
2712618b01ebSTejun Heo 		wq->flags |= __WQ_DRAINING;
271387fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
27149c5a2ba7STejun Heo reflush:
27159c5a2ba7STejun Heo 	flush_workqueue(wq);
27169c5a2ba7STejun Heo 
2717b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
271876af4d93STejun Heo 
271949e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2720fa2563e4SThomas Tuttle 		bool drained;
27219c5a2ba7STejun Heo 
2722b09f4fd3SLai Jiangshan 		spin_lock_irq(&pwq->pool->lock);
2723112202d9STejun Heo 		drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
2724b09f4fd3SLai Jiangshan 		spin_unlock_irq(&pwq->pool->lock);
2725fa2563e4SThomas Tuttle 
2726fa2563e4SThomas Tuttle 		if (drained)
27279c5a2ba7STejun Heo 			continue;
27289c5a2ba7STejun Heo 
27299c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
27309c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2731c5aa87bbSTejun Heo 			pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
27329c5a2ba7STejun Heo 				wq->name, flush_cnt);
273376af4d93STejun Heo 
2734b09f4fd3SLai Jiangshan 		mutex_unlock(&wq->mutex);
27359c5a2ba7STejun Heo 		goto reflush;
27369c5a2ba7STejun Heo 	}
27379c5a2ba7STejun Heo 
27389c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
2739618b01ebSTejun Heo 		wq->flags &= ~__WQ_DRAINING;
274087fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
27419c5a2ba7STejun Heo }
27429c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
27439c5a2ba7STejun Heo 
2744606a5020STejun Heo static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2745baf59022STejun Heo {
2746baf59022STejun Heo 	struct worker *worker = NULL;
2747c9e7cf27STejun Heo 	struct worker_pool *pool;
2748112202d9STejun Heo 	struct pool_workqueue *pwq;
2749baf59022STejun Heo 
2750baf59022STejun Heo 	might_sleep();
2751baf59022STejun Heo 
2752fa1b54e6STejun Heo 	local_irq_disable();
2753fa1b54e6STejun Heo 	pool = get_work_pool(work);
2754fa1b54e6STejun Heo 	if (!pool) {
2755fa1b54e6STejun Heo 		local_irq_enable();
2756fa1b54e6STejun Heo 		return false;
2757fa1b54e6STejun Heo 	}
2758fa1b54e6STejun Heo 
2759fa1b54e6STejun Heo 	spin_lock(&pool->lock);
27600b3dae68SLai Jiangshan 	/* see the comment in try_to_grab_pending() with the same code */
2761112202d9STejun Heo 	pwq = get_work_pwq(work);
2762112202d9STejun Heo 	if (pwq) {
2763112202d9STejun Heo 		if (unlikely(pwq->pool != pool))
2764baf59022STejun Heo 			goto already_gone;
2765606a5020STejun Heo 	} else {
2766c9e7cf27STejun Heo 		worker = find_worker_executing_work(pool, work);
2767baf59022STejun Heo 		if (!worker)
2768baf59022STejun Heo 			goto already_gone;
2769112202d9STejun Heo 		pwq = worker->current_pwq;
2770606a5020STejun Heo 	}
2771baf59022STejun Heo 
2772112202d9STejun Heo 	insert_wq_barrier(pwq, barr, work, worker);
2773d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2774baf59022STejun Heo 
2775e159489bSTejun Heo 	/*
2776e159489bSTejun Heo 	 * If @max_active is 1 or rescuer is in use, flushing another work
2777e159489bSTejun Heo 	 * item on the same workqueue may lead to deadlock.  Make sure the
2778e159489bSTejun Heo 	 * flusher is not running on the same workqueue by verifying write
2779e159489bSTejun Heo 	 * access.
2780e159489bSTejun Heo 	 */
2781493008a8STejun Heo 	if (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)
2782112202d9STejun Heo 		lock_map_acquire(&pwq->wq->lockdep_map);
2783e159489bSTejun Heo 	else
2784112202d9STejun Heo 		lock_map_acquire_read(&pwq->wq->lockdep_map);
2785112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
2786e159489bSTejun Heo 
2787baf59022STejun Heo 	return true;
2788baf59022STejun Heo already_gone:
2789d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2790baf59022STejun Heo 	return false;
2791baf59022STejun Heo }
2792baf59022STejun Heo 
2793db700897SOleg Nesterov /**
2794401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
2795401a8d04STejun Heo  * @work: the work to flush
2796db700897SOleg Nesterov  *
2797606a5020STejun Heo  * Wait until @work has finished execution.  @work is guaranteed to be idle
2798606a5020STejun Heo  * on return if it hasn't been requeued since flush started.
2799401a8d04STejun Heo  *
2800401a8d04STejun Heo  * RETURNS:
2801401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
2802401a8d04STejun Heo  * %false if it was already idle.
2803db700897SOleg Nesterov  */
2804401a8d04STejun Heo bool flush_work(struct work_struct *work)
2805db700897SOleg Nesterov {
2806db700897SOleg Nesterov 	struct wq_barrier barr;
2807db700897SOleg Nesterov 
28080976dfc1SStephen Boyd 	lock_map_acquire(&work->lockdep_map);
28090976dfc1SStephen Boyd 	lock_map_release(&work->lockdep_map);
28100976dfc1SStephen Boyd 
2811606a5020STejun Heo 	if (start_flush_work(work, &barr)) {
2812db700897SOleg Nesterov 		wait_for_completion(&barr.done);
2813dc186ad7SThomas Gleixner 		destroy_work_on_stack(&barr.work);
2814401a8d04STejun Heo 		return true;
2815606a5020STejun Heo 	} else {
2816401a8d04STejun Heo 		return false;
2817db700897SOleg Nesterov 	}
2818606a5020STejun Heo }
2819db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
2820db700897SOleg Nesterov 
282136e227d2STejun Heo static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2822401a8d04STejun Heo {
2823bbb68dfaSTejun Heo 	unsigned long flags;
28241f1f642eSOleg Nesterov 	int ret;
28251f1f642eSOleg Nesterov 
28261f1f642eSOleg Nesterov 	do {
2827bbb68dfaSTejun Heo 		ret = try_to_grab_pending(work, is_dwork, &flags);
2828bbb68dfaSTejun Heo 		/*
2829bbb68dfaSTejun Heo 		 * If someone else is canceling, wait for the same event it
2830bbb68dfaSTejun Heo 		 * would be waiting for before retrying.
2831bbb68dfaSTejun Heo 		 */
2832bbb68dfaSTejun Heo 		if (unlikely(ret == -ENOENT))
2833606a5020STejun Heo 			flush_work(work);
28341f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
28351f1f642eSOleg Nesterov 
2836bbb68dfaSTejun Heo 	/* tell other tasks trying to grab @work to back off */
2837bbb68dfaSTejun Heo 	mark_work_canceling(work);
2838bbb68dfaSTejun Heo 	local_irq_restore(flags);
2839bbb68dfaSTejun Heo 
2840606a5020STejun Heo 	flush_work(work);
28417a22ad75STejun Heo 	clear_work_data(work);
28421f1f642eSOleg Nesterov 	return ret;
28431f1f642eSOleg Nesterov }
28441f1f642eSOleg Nesterov 
28456e84d644SOleg Nesterov /**
2846401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
2847401a8d04STejun Heo  * @work: the work to cancel
28486e84d644SOleg Nesterov  *
2849401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
2850401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
2851401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
2852401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
28531f1f642eSOleg Nesterov  *
2854401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
2855401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
28566e84d644SOleg Nesterov  *
2857401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
28586e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
2859401a8d04STejun Heo  *
2860401a8d04STejun Heo  * RETURNS:
2861401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
28626e84d644SOleg Nesterov  */
2863401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
28646e84d644SOleg Nesterov {
286536e227d2STejun Heo 	return __cancel_work_timer(work, false);
2866b89deed3SOleg Nesterov }
286728e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
2868b89deed3SOleg Nesterov 
28696e84d644SOleg Nesterov /**
2870401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
2871401a8d04STejun Heo  * @dwork: the delayed work to flush
28726e84d644SOleg Nesterov  *
2873401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
2874401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
2875401a8d04STejun Heo  * considers the last queueing instance of @dwork.
28761f1f642eSOleg Nesterov  *
2877401a8d04STejun Heo  * RETURNS:
2878401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
2879401a8d04STejun Heo  * %false if it was already idle.
28806e84d644SOleg Nesterov  */
2881401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
2882401a8d04STejun Heo {
28838930cabaSTejun Heo 	local_irq_disable();
2884401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
288560c057bcSLai Jiangshan 		__queue_work(dwork->cpu, dwork->wq, &dwork->work);
28868930cabaSTejun Heo 	local_irq_enable();
2887401a8d04STejun Heo 	return flush_work(&dwork->work);
2888401a8d04STejun Heo }
2889401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
2890401a8d04STejun Heo 
2891401a8d04STejun Heo /**
289257b30ae7STejun Heo  * cancel_delayed_work - cancel a delayed work
289357b30ae7STejun Heo  * @dwork: delayed_work to cancel
289409383498STejun Heo  *
289557b30ae7STejun Heo  * Kill off a pending delayed_work.  Returns %true if @dwork was pending
289657b30ae7STejun Heo  * and canceled; %false if wasn't pending.  Note that the work callback
289757b30ae7STejun Heo  * function may still be running on return, unless it returns %true and the
289857b30ae7STejun Heo  * work doesn't re-arm itself.  Explicitly flush or use
289957b30ae7STejun Heo  * cancel_delayed_work_sync() to wait on it.
290009383498STejun Heo  *
290157b30ae7STejun Heo  * This function is safe to call from any context including IRQ handler.
290209383498STejun Heo  */
290357b30ae7STejun Heo bool cancel_delayed_work(struct delayed_work *dwork)
290409383498STejun Heo {
290557b30ae7STejun Heo 	unsigned long flags;
290657b30ae7STejun Heo 	int ret;
290757b30ae7STejun Heo 
290857b30ae7STejun Heo 	do {
290957b30ae7STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
291057b30ae7STejun Heo 	} while (unlikely(ret == -EAGAIN));
291157b30ae7STejun Heo 
291257b30ae7STejun Heo 	if (unlikely(ret < 0))
291357b30ae7STejun Heo 		return false;
291457b30ae7STejun Heo 
29157c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(&dwork->work,
29167c3eed5cSTejun Heo 					get_work_pool_id(&dwork->work));
291757b30ae7STejun Heo 	local_irq_restore(flags);
2918c0158ca6SDan Magenheimer 	return ret;
291909383498STejun Heo }
292057b30ae7STejun Heo EXPORT_SYMBOL(cancel_delayed_work);
292109383498STejun Heo 
292209383498STejun Heo /**
2923401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2924401a8d04STejun Heo  * @dwork: the delayed work cancel
2925401a8d04STejun Heo  *
2926401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
2927401a8d04STejun Heo  *
2928401a8d04STejun Heo  * RETURNS:
2929401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
2930401a8d04STejun Heo  */
2931401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
29326e84d644SOleg Nesterov {
293336e227d2STejun Heo 	return __cancel_work_timer(&dwork->work, true);
29346e84d644SOleg Nesterov }
2935f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
29361da177e4SLinus Torvalds 
29370fcb78c2SRolf Eike Beer /**
293831ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
2939b6136773SAndrew Morton  * @func: the function to call
2940b6136773SAndrew Morton  *
294131ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
294231ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
2943b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
294431ddd871STejun Heo  *
294531ddd871STejun Heo  * RETURNS:
294631ddd871STejun Heo  * 0 on success, -errno on failure.
2947b6136773SAndrew Morton  */
294865f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
294915316ba8SChristoph Lameter {
295015316ba8SChristoph Lameter 	int cpu;
295138f51568SNamhyung Kim 	struct work_struct __percpu *works;
295215316ba8SChristoph Lameter 
2953b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
2954b6136773SAndrew Morton 	if (!works)
295515316ba8SChristoph Lameter 		return -ENOMEM;
2956b6136773SAndrew Morton 
295795402b38SGautham R Shenoy 	get_online_cpus();
295893981800STejun Heo 
295915316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
29609bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
29619bfb1839SIngo Molnar 
29629bfb1839SIngo Molnar 		INIT_WORK(work, func);
29638de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
296415316ba8SChristoph Lameter 	}
296593981800STejun Heo 
296693981800STejun Heo 	for_each_online_cpu(cpu)
29678616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
296893981800STejun Heo 
296995402b38SGautham R Shenoy 	put_online_cpus();
2970b6136773SAndrew Morton 	free_percpu(works);
297115316ba8SChristoph Lameter 	return 0;
297215316ba8SChristoph Lameter }
297315316ba8SChristoph Lameter 
2974eef6a7d5SAlan Stern /**
2975eef6a7d5SAlan Stern  * flush_scheduled_work - ensure that any scheduled work has run to completion.
2976eef6a7d5SAlan Stern  *
2977eef6a7d5SAlan Stern  * Forces execution of the kernel-global workqueue and blocks until its
2978eef6a7d5SAlan Stern  * completion.
2979eef6a7d5SAlan Stern  *
2980eef6a7d5SAlan Stern  * Think twice before calling this function!  It's very easy to get into
2981eef6a7d5SAlan Stern  * trouble if you don't take great care.  Either of the following situations
2982eef6a7d5SAlan Stern  * will lead to deadlock:
2983eef6a7d5SAlan Stern  *
2984eef6a7d5SAlan Stern  *	One of the work items currently on the workqueue needs to acquire
2985eef6a7d5SAlan Stern  *	a lock held by your code or its caller.
2986eef6a7d5SAlan Stern  *
2987eef6a7d5SAlan Stern  *	Your code is running in the context of a work routine.
2988eef6a7d5SAlan Stern  *
2989eef6a7d5SAlan Stern  * They will be detected by lockdep when they occur, but the first might not
2990eef6a7d5SAlan Stern  * occur very often.  It depends on what work items are on the workqueue and
2991eef6a7d5SAlan Stern  * what locks they need, which you have no control over.
2992eef6a7d5SAlan Stern  *
2993eef6a7d5SAlan Stern  * In most situations flushing the entire workqueue is overkill; you merely
2994eef6a7d5SAlan Stern  * need to know that a particular work item isn't queued and isn't running.
2995eef6a7d5SAlan Stern  * In such cases you should use cancel_delayed_work_sync() or
2996eef6a7d5SAlan Stern  * cancel_work_sync() instead.
2997eef6a7d5SAlan Stern  */
29981da177e4SLinus Torvalds void flush_scheduled_work(void)
29991da177e4SLinus Torvalds {
3000d320c038STejun Heo 	flush_workqueue(system_wq);
30011da177e4SLinus Torvalds }
3002ae90dd5dSDave Jones EXPORT_SYMBOL(flush_scheduled_work);
30031da177e4SLinus Torvalds 
30041da177e4SLinus Torvalds /**
30051fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
30061fa44ecaSJames Bottomley  * @fn:		the function to execute
30071fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
30081fa44ecaSJames Bottomley  *		be available when the work executes)
30091fa44ecaSJames Bottomley  *
30101fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
30111fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
30121fa44ecaSJames Bottomley  *
30131fa44ecaSJames Bottomley  * Returns:	0 - function was executed
30141fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
30151fa44ecaSJames Bottomley  */
301665f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
30171fa44ecaSJames Bottomley {
30181fa44ecaSJames Bottomley 	if (!in_interrupt()) {
301965f27f38SDavid Howells 		fn(&ew->work);
30201fa44ecaSJames Bottomley 		return 0;
30211fa44ecaSJames Bottomley 	}
30221fa44ecaSJames Bottomley 
302365f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
30241fa44ecaSJames Bottomley 	schedule_work(&ew->work);
30251fa44ecaSJames Bottomley 
30261fa44ecaSJames Bottomley 	return 1;
30271fa44ecaSJames Bottomley }
30281fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
30291fa44ecaSJames Bottomley 
3030226223abSTejun Heo #ifdef CONFIG_SYSFS
3031226223abSTejun Heo /*
3032226223abSTejun Heo  * Workqueues with WQ_SYSFS flag set is visible to userland via
3033226223abSTejun Heo  * /sys/bus/workqueue/devices/WQ_NAME.  All visible workqueues have the
3034226223abSTejun Heo  * following attributes.
3035226223abSTejun Heo  *
3036226223abSTejun Heo  *  per_cpu	RO bool	: whether the workqueue is per-cpu or unbound
3037226223abSTejun Heo  *  max_active	RW int	: maximum number of in-flight work items
3038226223abSTejun Heo  *
3039226223abSTejun Heo  * Unbound workqueues have the following extra attributes.
3040226223abSTejun Heo  *
3041226223abSTejun Heo  *  id		RO int	: the associated pool ID
3042226223abSTejun Heo  *  nice	RW int	: nice value of the workers
3043226223abSTejun Heo  *  cpumask	RW mask	: bitmask of allowed CPUs for the workers
3044226223abSTejun Heo  */
3045226223abSTejun Heo struct wq_device {
3046226223abSTejun Heo 	struct workqueue_struct		*wq;
3047226223abSTejun Heo 	struct device			dev;
3048226223abSTejun Heo };
3049226223abSTejun Heo 
3050226223abSTejun Heo static struct workqueue_struct *dev_to_wq(struct device *dev)
3051226223abSTejun Heo {
3052226223abSTejun Heo 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
3053226223abSTejun Heo 
3054226223abSTejun Heo 	return wq_dev->wq;
3055226223abSTejun Heo }
3056226223abSTejun Heo 
3057226223abSTejun Heo static ssize_t wq_per_cpu_show(struct device *dev,
3058226223abSTejun Heo 			       struct device_attribute *attr, char *buf)
3059226223abSTejun Heo {
3060226223abSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
3061226223abSTejun Heo 
3062226223abSTejun Heo 	return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
3063226223abSTejun Heo }
3064226223abSTejun Heo 
3065226223abSTejun Heo static ssize_t wq_max_active_show(struct device *dev,
3066226223abSTejun Heo 				  struct device_attribute *attr, char *buf)
3067226223abSTejun Heo {
3068226223abSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
3069226223abSTejun Heo 
3070226223abSTejun Heo 	return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
3071226223abSTejun Heo }
3072226223abSTejun Heo 
3073226223abSTejun Heo static ssize_t wq_max_active_store(struct device *dev,
3074226223abSTejun Heo 				   struct device_attribute *attr,
3075226223abSTejun Heo 				   const char *buf, size_t count)
3076226223abSTejun Heo {
3077226223abSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
3078226223abSTejun Heo 	int val;
3079226223abSTejun Heo 
3080226223abSTejun Heo 	if (sscanf(buf, "%d", &val) != 1 || val <= 0)
3081226223abSTejun Heo 		return -EINVAL;
3082226223abSTejun Heo 
3083226223abSTejun Heo 	workqueue_set_max_active(wq, val);
3084226223abSTejun Heo 	return count;
3085226223abSTejun Heo }
3086226223abSTejun Heo 
3087226223abSTejun Heo static struct device_attribute wq_sysfs_attrs[] = {
3088226223abSTejun Heo 	__ATTR(per_cpu, 0444, wq_per_cpu_show, NULL),
3089226223abSTejun Heo 	__ATTR(max_active, 0644, wq_max_active_show, wq_max_active_store),
3090226223abSTejun Heo 	__ATTR_NULL,
3091226223abSTejun Heo };
3092226223abSTejun Heo 
3093226223abSTejun Heo static ssize_t wq_pool_id_show(struct device *dev,
3094226223abSTejun Heo 			       struct device_attribute *attr, char *buf)
3095226223abSTejun Heo {
3096226223abSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
3097226223abSTejun Heo 	struct worker_pool *pool;
3098226223abSTejun Heo 	int written;
3099226223abSTejun Heo 
3100226223abSTejun Heo 	rcu_read_lock_sched();
3101226223abSTejun Heo 	pool = first_pwq(wq)->pool;
3102226223abSTejun Heo 	written = scnprintf(buf, PAGE_SIZE, "%d\n", pool->id);
3103226223abSTejun Heo 	rcu_read_unlock_sched();
3104226223abSTejun Heo 
3105226223abSTejun Heo 	return written;
3106226223abSTejun Heo }
3107226223abSTejun Heo 
3108226223abSTejun Heo static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
3109226223abSTejun Heo 			    char *buf)
3110226223abSTejun Heo {
3111226223abSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
3112226223abSTejun Heo 	int written;
3113226223abSTejun Heo 
31146029a918STejun Heo 	mutex_lock(&wq->mutex);
31156029a918STejun Heo 	written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
31166029a918STejun Heo 	mutex_unlock(&wq->mutex);
3117226223abSTejun Heo 
3118226223abSTejun Heo 	return written;
3119226223abSTejun Heo }
3120226223abSTejun Heo 
3121226223abSTejun Heo /* prepare workqueue_attrs for sysfs store operations */
3122226223abSTejun Heo static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
3123226223abSTejun Heo {
3124226223abSTejun Heo 	struct workqueue_attrs *attrs;
3125226223abSTejun Heo 
3126226223abSTejun Heo 	attrs = alloc_workqueue_attrs(GFP_KERNEL);
3127226223abSTejun Heo 	if (!attrs)
3128226223abSTejun Heo 		return NULL;
3129226223abSTejun Heo 
31306029a918STejun Heo 	mutex_lock(&wq->mutex);
31316029a918STejun Heo 	copy_workqueue_attrs(attrs, wq->unbound_attrs);
31326029a918STejun Heo 	mutex_unlock(&wq->mutex);
3133226223abSTejun Heo 	return attrs;
3134226223abSTejun Heo }
3135226223abSTejun Heo 
3136226223abSTejun Heo static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
3137226223abSTejun Heo 			     const char *buf, size_t count)
3138226223abSTejun Heo {
3139226223abSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
3140226223abSTejun Heo 	struct workqueue_attrs *attrs;
3141226223abSTejun Heo 	int ret;
3142226223abSTejun Heo 
3143226223abSTejun Heo 	attrs = wq_sysfs_prep_attrs(wq);
3144226223abSTejun Heo 	if (!attrs)
3145226223abSTejun Heo 		return -ENOMEM;
3146226223abSTejun Heo 
3147226223abSTejun Heo 	if (sscanf(buf, "%d", &attrs->nice) == 1 &&
3148226223abSTejun Heo 	    attrs->nice >= -20 && attrs->nice <= 19)
3149226223abSTejun Heo 		ret = apply_workqueue_attrs(wq, attrs);
3150226223abSTejun Heo 	else
3151226223abSTejun Heo 		ret = -EINVAL;
3152226223abSTejun Heo 
3153226223abSTejun Heo 	free_workqueue_attrs(attrs);
3154226223abSTejun Heo 	return ret ?: count;
3155226223abSTejun Heo }
3156226223abSTejun Heo 
3157226223abSTejun Heo static ssize_t wq_cpumask_show(struct device *dev,
3158226223abSTejun Heo 			       struct device_attribute *attr, char *buf)
3159226223abSTejun Heo {
3160226223abSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
3161226223abSTejun Heo 	int written;
3162226223abSTejun Heo 
31636029a918STejun Heo 	mutex_lock(&wq->mutex);
31646029a918STejun Heo 	written = cpumask_scnprintf(buf, PAGE_SIZE, wq->unbound_attrs->cpumask);
31656029a918STejun Heo 	mutex_unlock(&wq->mutex);
3166226223abSTejun Heo 
3167226223abSTejun Heo 	written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
3168226223abSTejun Heo 	return written;
3169226223abSTejun Heo }
3170226223abSTejun Heo 
3171226223abSTejun Heo static ssize_t wq_cpumask_store(struct device *dev,
3172226223abSTejun Heo 				struct device_attribute *attr,
3173226223abSTejun Heo 				const char *buf, size_t count)
3174226223abSTejun Heo {
3175226223abSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
3176226223abSTejun Heo 	struct workqueue_attrs *attrs;
3177226223abSTejun Heo 	int ret;
3178226223abSTejun Heo 
3179226223abSTejun Heo 	attrs = wq_sysfs_prep_attrs(wq);
3180226223abSTejun Heo 	if (!attrs)
3181226223abSTejun Heo 		return -ENOMEM;
3182226223abSTejun Heo 
3183226223abSTejun Heo 	ret = cpumask_parse(buf, attrs->cpumask);
3184226223abSTejun Heo 	if (!ret)
3185226223abSTejun Heo 		ret = apply_workqueue_attrs(wq, attrs);
3186226223abSTejun Heo 
3187226223abSTejun Heo 	free_workqueue_attrs(attrs);
3188226223abSTejun Heo 	return ret ?: count;
3189226223abSTejun Heo }
3190226223abSTejun Heo 
3191226223abSTejun Heo static struct device_attribute wq_sysfs_unbound_attrs[] = {
3192226223abSTejun Heo 	__ATTR(pool_id, 0444, wq_pool_id_show, NULL),
3193226223abSTejun Heo 	__ATTR(nice, 0644, wq_nice_show, wq_nice_store),
3194226223abSTejun Heo 	__ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
3195226223abSTejun Heo 	__ATTR_NULL,
3196226223abSTejun Heo };
3197226223abSTejun Heo 
3198226223abSTejun Heo static struct bus_type wq_subsys = {
3199226223abSTejun Heo 	.name				= "workqueue",
3200226223abSTejun Heo 	.dev_attrs			= wq_sysfs_attrs,
3201226223abSTejun Heo };
3202226223abSTejun Heo 
3203226223abSTejun Heo static int __init wq_sysfs_init(void)
3204226223abSTejun Heo {
3205226223abSTejun Heo 	return subsys_virtual_register(&wq_subsys, NULL);
3206226223abSTejun Heo }
3207226223abSTejun Heo core_initcall(wq_sysfs_init);
3208226223abSTejun Heo 
3209226223abSTejun Heo static void wq_device_release(struct device *dev)
3210226223abSTejun Heo {
3211226223abSTejun Heo 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
3212226223abSTejun Heo 
3213226223abSTejun Heo 	kfree(wq_dev);
3214226223abSTejun Heo }
3215226223abSTejun Heo 
3216226223abSTejun Heo /**
3217226223abSTejun Heo  * workqueue_sysfs_register - make a workqueue visible in sysfs
3218226223abSTejun Heo  * @wq: the workqueue to register
3219226223abSTejun Heo  *
3220226223abSTejun Heo  * Expose @wq in sysfs under /sys/bus/workqueue/devices.
3221226223abSTejun Heo  * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
3222226223abSTejun Heo  * which is the preferred method.
3223226223abSTejun Heo  *
3224226223abSTejun Heo  * Workqueue user should use this function directly iff it wants to apply
3225226223abSTejun Heo  * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
3226226223abSTejun Heo  * apply_workqueue_attrs() may race against userland updating the
3227226223abSTejun Heo  * attributes.
3228226223abSTejun Heo  *
3229226223abSTejun Heo  * Returns 0 on success, -errno on failure.
3230226223abSTejun Heo  */
3231226223abSTejun Heo int workqueue_sysfs_register(struct workqueue_struct *wq)
3232226223abSTejun Heo {
3233226223abSTejun Heo 	struct wq_device *wq_dev;
3234226223abSTejun Heo 	int ret;
3235226223abSTejun Heo 
3236226223abSTejun Heo 	/*
3237226223abSTejun Heo 	 * Adjusting max_active or creating new pwqs by applyting
3238226223abSTejun Heo 	 * attributes breaks ordering guarantee.  Disallow exposing ordered
3239226223abSTejun Heo 	 * workqueues.
3240226223abSTejun Heo 	 */
3241226223abSTejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED))
3242226223abSTejun Heo 		return -EINVAL;
3243226223abSTejun Heo 
3244226223abSTejun Heo 	wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
3245226223abSTejun Heo 	if (!wq_dev)
3246226223abSTejun Heo 		return -ENOMEM;
3247226223abSTejun Heo 
3248226223abSTejun Heo 	wq_dev->wq = wq;
3249226223abSTejun Heo 	wq_dev->dev.bus = &wq_subsys;
3250226223abSTejun Heo 	wq_dev->dev.init_name = wq->name;
3251226223abSTejun Heo 	wq_dev->dev.release = wq_device_release;
3252226223abSTejun Heo 
3253226223abSTejun Heo 	/*
3254226223abSTejun Heo 	 * unbound_attrs are created separately.  Suppress uevent until
3255226223abSTejun Heo 	 * everything is ready.
3256226223abSTejun Heo 	 */
3257226223abSTejun Heo 	dev_set_uevent_suppress(&wq_dev->dev, true);
3258226223abSTejun Heo 
3259226223abSTejun Heo 	ret = device_register(&wq_dev->dev);
3260226223abSTejun Heo 	if (ret) {
3261226223abSTejun Heo 		kfree(wq_dev);
3262226223abSTejun Heo 		wq->wq_dev = NULL;
3263226223abSTejun Heo 		return ret;
3264226223abSTejun Heo 	}
3265226223abSTejun Heo 
3266226223abSTejun Heo 	if (wq->flags & WQ_UNBOUND) {
3267226223abSTejun Heo 		struct device_attribute *attr;
3268226223abSTejun Heo 
3269226223abSTejun Heo 		for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
3270226223abSTejun Heo 			ret = device_create_file(&wq_dev->dev, attr);
3271226223abSTejun Heo 			if (ret) {
3272226223abSTejun Heo 				device_unregister(&wq_dev->dev);
3273226223abSTejun Heo 				wq->wq_dev = NULL;
3274226223abSTejun Heo 				return ret;
3275226223abSTejun Heo 			}
3276226223abSTejun Heo 		}
3277226223abSTejun Heo 	}
3278226223abSTejun Heo 
3279226223abSTejun Heo 	kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
3280226223abSTejun Heo 	return 0;
3281226223abSTejun Heo }
3282226223abSTejun Heo 
3283226223abSTejun Heo /**
3284226223abSTejun Heo  * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
3285226223abSTejun Heo  * @wq: the workqueue to unregister
3286226223abSTejun Heo  *
3287226223abSTejun Heo  * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
3288226223abSTejun Heo  */
3289226223abSTejun Heo static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
3290226223abSTejun Heo {
3291226223abSTejun Heo 	struct wq_device *wq_dev = wq->wq_dev;
3292226223abSTejun Heo 
3293226223abSTejun Heo 	if (!wq->wq_dev)
3294226223abSTejun Heo 		return;
3295226223abSTejun Heo 
3296226223abSTejun Heo 	wq->wq_dev = NULL;
3297226223abSTejun Heo 	device_unregister(&wq_dev->dev);
3298226223abSTejun Heo }
3299226223abSTejun Heo #else	/* CONFIG_SYSFS */
3300226223abSTejun Heo static void workqueue_sysfs_unregister(struct workqueue_struct *wq)	{ }
3301226223abSTejun Heo #endif	/* CONFIG_SYSFS */
3302226223abSTejun Heo 
33037a4e344cSTejun Heo /**
33047a4e344cSTejun Heo  * free_workqueue_attrs - free a workqueue_attrs
33057a4e344cSTejun Heo  * @attrs: workqueue_attrs to free
33067a4e344cSTejun Heo  *
33077a4e344cSTejun Heo  * Undo alloc_workqueue_attrs().
33087a4e344cSTejun Heo  */
33097a4e344cSTejun Heo void free_workqueue_attrs(struct workqueue_attrs *attrs)
33107a4e344cSTejun Heo {
33117a4e344cSTejun Heo 	if (attrs) {
33127a4e344cSTejun Heo 		free_cpumask_var(attrs->cpumask);
33137a4e344cSTejun Heo 		kfree(attrs);
33147a4e344cSTejun Heo 	}
33157a4e344cSTejun Heo }
33167a4e344cSTejun Heo 
33177a4e344cSTejun Heo /**
33187a4e344cSTejun Heo  * alloc_workqueue_attrs - allocate a workqueue_attrs
33197a4e344cSTejun Heo  * @gfp_mask: allocation mask to use
33207a4e344cSTejun Heo  *
33217a4e344cSTejun Heo  * Allocate a new workqueue_attrs, initialize with default settings and
33227a4e344cSTejun Heo  * return it.  Returns NULL on failure.
33237a4e344cSTejun Heo  */
33247a4e344cSTejun Heo struct workqueue_attrs *alloc_workqueue_attrs(gfp_t gfp_mask)
33257a4e344cSTejun Heo {
33267a4e344cSTejun Heo 	struct workqueue_attrs *attrs;
33277a4e344cSTejun Heo 
33287a4e344cSTejun Heo 	attrs = kzalloc(sizeof(*attrs), gfp_mask);
33297a4e344cSTejun Heo 	if (!attrs)
33307a4e344cSTejun Heo 		goto fail;
33317a4e344cSTejun Heo 	if (!alloc_cpumask_var(&attrs->cpumask, gfp_mask))
33327a4e344cSTejun Heo 		goto fail;
33337a4e344cSTejun Heo 
333413e2e556STejun Heo 	cpumask_copy(attrs->cpumask, cpu_possible_mask);
33357a4e344cSTejun Heo 	return attrs;
33367a4e344cSTejun Heo fail:
33377a4e344cSTejun Heo 	free_workqueue_attrs(attrs);
33387a4e344cSTejun Heo 	return NULL;
33397a4e344cSTejun Heo }
33407a4e344cSTejun Heo 
334129c91e99STejun Heo static void copy_workqueue_attrs(struct workqueue_attrs *to,
334229c91e99STejun Heo 				 const struct workqueue_attrs *from)
334329c91e99STejun Heo {
334429c91e99STejun Heo 	to->nice = from->nice;
334529c91e99STejun Heo 	cpumask_copy(to->cpumask, from->cpumask);
334629c91e99STejun Heo }
334729c91e99STejun Heo 
334829c91e99STejun Heo /* hash value of the content of @attr */
334929c91e99STejun Heo static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
335029c91e99STejun Heo {
335129c91e99STejun Heo 	u32 hash = 0;
335229c91e99STejun Heo 
335329c91e99STejun Heo 	hash = jhash_1word(attrs->nice, hash);
335413e2e556STejun Heo 	hash = jhash(cpumask_bits(attrs->cpumask),
335513e2e556STejun Heo 		     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
335629c91e99STejun Heo 	return hash;
335729c91e99STejun Heo }
335829c91e99STejun Heo 
335929c91e99STejun Heo /* content equality test */
336029c91e99STejun Heo static bool wqattrs_equal(const struct workqueue_attrs *a,
336129c91e99STejun Heo 			  const struct workqueue_attrs *b)
336229c91e99STejun Heo {
336329c91e99STejun Heo 	if (a->nice != b->nice)
336429c91e99STejun Heo 		return false;
336529c91e99STejun Heo 	if (!cpumask_equal(a->cpumask, b->cpumask))
336629c91e99STejun Heo 		return false;
336729c91e99STejun Heo 	return true;
336829c91e99STejun Heo }
336929c91e99STejun Heo 
33707a4e344cSTejun Heo /**
33717a4e344cSTejun Heo  * init_worker_pool - initialize a newly zalloc'd worker_pool
33727a4e344cSTejun Heo  * @pool: worker_pool to initialize
33737a4e344cSTejun Heo  *
33747a4e344cSTejun Heo  * Initiailize a newly zalloc'd @pool.  It also allocates @pool->attrs.
337529c91e99STejun Heo  * Returns 0 on success, -errno on failure.  Even on failure, all fields
337629c91e99STejun Heo  * inside @pool proper are initialized and put_unbound_pool() can be called
337729c91e99STejun Heo  * on @pool safely to release it.
33787a4e344cSTejun Heo  */
33797a4e344cSTejun Heo static int init_worker_pool(struct worker_pool *pool)
33804e1a1f9aSTejun Heo {
33814e1a1f9aSTejun Heo 	spin_lock_init(&pool->lock);
338229c91e99STejun Heo 	pool->id = -1;
338329c91e99STejun Heo 	pool->cpu = -1;
3384f3f90ad4STejun Heo 	pool->node = NUMA_NO_NODE;
33854e1a1f9aSTejun Heo 	pool->flags |= POOL_DISASSOCIATED;
33864e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->worklist);
33874e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->idle_list);
33884e1a1f9aSTejun Heo 	hash_init(pool->busy_hash);
33894e1a1f9aSTejun Heo 
33904e1a1f9aSTejun Heo 	init_timer_deferrable(&pool->idle_timer);
33914e1a1f9aSTejun Heo 	pool->idle_timer.function = idle_worker_timeout;
33924e1a1f9aSTejun Heo 	pool->idle_timer.data = (unsigned long)pool;
33934e1a1f9aSTejun Heo 
33944e1a1f9aSTejun Heo 	setup_timer(&pool->mayday_timer, pool_mayday_timeout,
33954e1a1f9aSTejun Heo 		    (unsigned long)pool);
33964e1a1f9aSTejun Heo 
33974e1a1f9aSTejun Heo 	mutex_init(&pool->manager_arb);
3398bc3a1afcSTejun Heo 	mutex_init(&pool->manager_mutex);
3399822d8405STejun Heo 	idr_init(&pool->worker_idr);
34007a4e344cSTejun Heo 
340129c91e99STejun Heo 	INIT_HLIST_NODE(&pool->hash_node);
340229c91e99STejun Heo 	pool->refcnt = 1;
340329c91e99STejun Heo 
340429c91e99STejun Heo 	/* shouldn't fail above this point */
34057a4e344cSTejun Heo 	pool->attrs = alloc_workqueue_attrs(GFP_KERNEL);
34067a4e344cSTejun Heo 	if (!pool->attrs)
34077a4e344cSTejun Heo 		return -ENOMEM;
34087a4e344cSTejun Heo 	return 0;
34094e1a1f9aSTejun Heo }
34104e1a1f9aSTejun Heo 
341129c91e99STejun Heo static void rcu_free_pool(struct rcu_head *rcu)
341229c91e99STejun Heo {
341329c91e99STejun Heo 	struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
341429c91e99STejun Heo 
3415822d8405STejun Heo 	idr_destroy(&pool->worker_idr);
341629c91e99STejun Heo 	free_workqueue_attrs(pool->attrs);
341729c91e99STejun Heo 	kfree(pool);
341829c91e99STejun Heo }
341929c91e99STejun Heo 
342029c91e99STejun Heo /**
342129c91e99STejun Heo  * put_unbound_pool - put a worker_pool
342229c91e99STejun Heo  * @pool: worker_pool to put
342329c91e99STejun Heo  *
342429c91e99STejun Heo  * Put @pool.  If its refcnt reaches zero, it gets destroyed in sched-RCU
3425c5aa87bbSTejun Heo  * safe manner.  get_unbound_pool() calls this function on its failure path
3426c5aa87bbSTejun Heo  * and this function should be able to release pools which went through,
3427c5aa87bbSTejun Heo  * successfully or not, init_worker_pool().
3428a892caccSTejun Heo  *
3429a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
343029c91e99STejun Heo  */
343129c91e99STejun Heo static void put_unbound_pool(struct worker_pool *pool)
343229c91e99STejun Heo {
343329c91e99STejun Heo 	struct worker *worker;
343429c91e99STejun Heo 
3435a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3436a892caccSTejun Heo 
3437a892caccSTejun Heo 	if (--pool->refcnt)
343829c91e99STejun Heo 		return;
343929c91e99STejun Heo 
344029c91e99STejun Heo 	/* sanity checks */
344129c91e99STejun Heo 	if (WARN_ON(!(pool->flags & POOL_DISASSOCIATED)) ||
3442a892caccSTejun Heo 	    WARN_ON(!list_empty(&pool->worklist)))
344329c91e99STejun Heo 		return;
344429c91e99STejun Heo 
344529c91e99STejun Heo 	/* release id and unhash */
344629c91e99STejun Heo 	if (pool->id >= 0)
344729c91e99STejun Heo 		idr_remove(&worker_pool_idr, pool->id);
344829c91e99STejun Heo 	hash_del(&pool->hash_node);
344929c91e99STejun Heo 
3450c5aa87bbSTejun Heo 	/*
3451c5aa87bbSTejun Heo 	 * Become the manager and destroy all workers.  Grabbing
3452c5aa87bbSTejun Heo 	 * manager_arb prevents @pool's workers from blocking on
3453c5aa87bbSTejun Heo 	 * manager_mutex.
3454c5aa87bbSTejun Heo 	 */
345529c91e99STejun Heo 	mutex_lock(&pool->manager_arb);
3456cd549687STejun Heo 	mutex_lock(&pool->manager_mutex);
345729c91e99STejun Heo 	spin_lock_irq(&pool->lock);
345829c91e99STejun Heo 
345929c91e99STejun Heo 	while ((worker = first_worker(pool)))
346029c91e99STejun Heo 		destroy_worker(worker);
346129c91e99STejun Heo 	WARN_ON(pool->nr_workers || pool->nr_idle);
346229c91e99STejun Heo 
346329c91e99STejun Heo 	spin_unlock_irq(&pool->lock);
3464cd549687STejun Heo 	mutex_unlock(&pool->manager_mutex);
346529c91e99STejun Heo 	mutex_unlock(&pool->manager_arb);
346629c91e99STejun Heo 
346729c91e99STejun Heo 	/* shut down the timers */
346829c91e99STejun Heo 	del_timer_sync(&pool->idle_timer);
346929c91e99STejun Heo 	del_timer_sync(&pool->mayday_timer);
347029c91e99STejun Heo 
347129c91e99STejun Heo 	/* sched-RCU protected to allow dereferences from get_work_pool() */
347229c91e99STejun Heo 	call_rcu_sched(&pool->rcu, rcu_free_pool);
347329c91e99STejun Heo }
347429c91e99STejun Heo 
347529c91e99STejun Heo /**
347629c91e99STejun Heo  * get_unbound_pool - get a worker_pool with the specified attributes
347729c91e99STejun Heo  * @attrs: the attributes of the worker_pool to get
347829c91e99STejun Heo  *
347929c91e99STejun Heo  * Obtain a worker_pool which has the same attributes as @attrs, bump the
348029c91e99STejun Heo  * reference count and return it.  If there already is a matching
348129c91e99STejun Heo  * worker_pool, it will be used; otherwise, this function attempts to
348229c91e99STejun Heo  * create a new one.  On failure, returns NULL.
3483a892caccSTejun Heo  *
3484a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
348529c91e99STejun Heo  */
348629c91e99STejun Heo static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
348729c91e99STejun Heo {
348829c91e99STejun Heo 	u32 hash = wqattrs_hash(attrs);
348929c91e99STejun Heo 	struct worker_pool *pool;
3490f3f90ad4STejun Heo 	int node;
349129c91e99STejun Heo 
3492a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
349329c91e99STejun Heo 
349429c91e99STejun Heo 	/* do we already have a matching pool? */
349529c91e99STejun Heo 	hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
349629c91e99STejun Heo 		if (wqattrs_equal(pool->attrs, attrs)) {
349729c91e99STejun Heo 			pool->refcnt++;
349829c91e99STejun Heo 			goto out_unlock;
349929c91e99STejun Heo 		}
350029c91e99STejun Heo 	}
350129c91e99STejun Heo 
350229c91e99STejun Heo 	/* nope, create a new one */
350329c91e99STejun Heo 	pool = kzalloc(sizeof(*pool), GFP_KERNEL);
350429c91e99STejun Heo 	if (!pool || init_worker_pool(pool) < 0)
350529c91e99STejun Heo 		goto fail;
350629c91e99STejun Heo 
350712ee4fc6SLai Jiangshan 	if (workqueue_freezing)
350812ee4fc6SLai Jiangshan 		pool->flags |= POOL_FREEZING;
350912ee4fc6SLai Jiangshan 
35108864b4e5STejun Heo 	lockdep_set_subclass(&pool->lock, 1);	/* see put_pwq() */
351129c91e99STejun Heo 	copy_workqueue_attrs(pool->attrs, attrs);
351229c91e99STejun Heo 
3513f3f90ad4STejun Heo 	/* if cpumask is contained inside a NUMA node, we belong to that node */
3514f3f90ad4STejun Heo 	if (wq_numa_enabled) {
3515f3f90ad4STejun Heo 		for_each_node(node) {
3516f3f90ad4STejun Heo 			if (cpumask_subset(pool->attrs->cpumask,
3517f3f90ad4STejun Heo 					   wq_numa_possible_cpumask[node])) {
3518f3f90ad4STejun Heo 				pool->node = node;
3519f3f90ad4STejun Heo 				break;
3520f3f90ad4STejun Heo 			}
3521f3f90ad4STejun Heo 		}
3522f3f90ad4STejun Heo 	}
3523f3f90ad4STejun Heo 
352429c91e99STejun Heo 	if (worker_pool_assign_id(pool) < 0)
352529c91e99STejun Heo 		goto fail;
352629c91e99STejun Heo 
352729c91e99STejun Heo 	/* create and start the initial worker */
3528ebf44d16STejun Heo 	if (create_and_start_worker(pool) < 0)
352929c91e99STejun Heo 		goto fail;
353029c91e99STejun Heo 
353129c91e99STejun Heo 	/* install */
353229c91e99STejun Heo 	hash_add(unbound_pool_hash, &pool->hash_node, hash);
353329c91e99STejun Heo out_unlock:
353429c91e99STejun Heo 	return pool;
353529c91e99STejun Heo fail:
353629c91e99STejun Heo 	if (pool)
353729c91e99STejun Heo 		put_unbound_pool(pool);
353829c91e99STejun Heo 	return NULL;
353929c91e99STejun Heo }
354029c91e99STejun Heo 
35418864b4e5STejun Heo static void rcu_free_pwq(struct rcu_head *rcu)
35428864b4e5STejun Heo {
35438864b4e5STejun Heo 	kmem_cache_free(pwq_cache,
35448864b4e5STejun Heo 			container_of(rcu, struct pool_workqueue, rcu));
35458864b4e5STejun Heo }
35468864b4e5STejun Heo 
35478864b4e5STejun Heo /*
35488864b4e5STejun Heo  * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
35498864b4e5STejun Heo  * and needs to be destroyed.
35508864b4e5STejun Heo  */
35518864b4e5STejun Heo static void pwq_unbound_release_workfn(struct work_struct *work)
35528864b4e5STejun Heo {
35538864b4e5STejun Heo 	struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
35548864b4e5STejun Heo 						  unbound_release_work);
35558864b4e5STejun Heo 	struct workqueue_struct *wq = pwq->wq;
35568864b4e5STejun Heo 	struct worker_pool *pool = pwq->pool;
3557bc0caf09STejun Heo 	bool is_last;
35588864b4e5STejun Heo 
35598864b4e5STejun Heo 	if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
35608864b4e5STejun Heo 		return;
35618864b4e5STejun Heo 
356275ccf595STejun Heo 	/*
35633c25a55dSLai Jiangshan 	 * Unlink @pwq.  Synchronization against wq->mutex isn't strictly
356475ccf595STejun Heo 	 * necessary on release but do it anyway.  It's easier to verify
356575ccf595STejun Heo 	 * and consistent with the linking path.
356675ccf595STejun Heo 	 */
35673c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
35688864b4e5STejun Heo 	list_del_rcu(&pwq->pwqs_node);
3569bc0caf09STejun Heo 	is_last = list_empty(&wq->pwqs);
35703c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
35718864b4e5STejun Heo 
3572a892caccSTejun Heo 	mutex_lock(&wq_pool_mutex);
35738864b4e5STejun Heo 	put_unbound_pool(pool);
3574a892caccSTejun Heo 	mutex_unlock(&wq_pool_mutex);
3575a892caccSTejun Heo 
35768864b4e5STejun Heo 	call_rcu_sched(&pwq->rcu, rcu_free_pwq);
35778864b4e5STejun Heo 
35788864b4e5STejun Heo 	/*
35798864b4e5STejun Heo 	 * If we're the last pwq going away, @wq is already dead and no one
35808864b4e5STejun Heo 	 * is gonna access it anymore.  Free it.
35818864b4e5STejun Heo 	 */
35826029a918STejun Heo 	if (is_last) {
35836029a918STejun Heo 		free_workqueue_attrs(wq->unbound_attrs);
35848864b4e5STejun Heo 		kfree(wq);
35858864b4e5STejun Heo 	}
35866029a918STejun Heo }
35878864b4e5STejun Heo 
35880fbd95aaSTejun Heo /**
3589699ce097STejun Heo  * pwq_adjust_max_active - update a pwq's max_active to the current setting
35900fbd95aaSTejun Heo  * @pwq: target pool_workqueue
35910fbd95aaSTejun Heo  *
3592699ce097STejun Heo  * If @pwq isn't freezing, set @pwq->max_active to the associated
3593699ce097STejun Heo  * workqueue's saved_max_active and activate delayed work items
3594699ce097STejun Heo  * accordingly.  If @pwq is freezing, clear @pwq->max_active to zero.
35950fbd95aaSTejun Heo  */
3596699ce097STejun Heo static void pwq_adjust_max_active(struct pool_workqueue *pwq)
35970fbd95aaSTejun Heo {
3598699ce097STejun Heo 	struct workqueue_struct *wq = pwq->wq;
3599699ce097STejun Heo 	bool freezable = wq->flags & WQ_FREEZABLE;
3600699ce097STejun Heo 
3601699ce097STejun Heo 	/* for @wq->saved_max_active */
3602a357fc03SLai Jiangshan 	lockdep_assert_held(&wq->mutex);
3603699ce097STejun Heo 
3604699ce097STejun Heo 	/* fast exit for non-freezable wqs */
3605699ce097STejun Heo 	if (!freezable && pwq->max_active == wq->saved_max_active)
3606699ce097STejun Heo 		return;
3607699ce097STejun Heo 
3608a357fc03SLai Jiangshan 	spin_lock_irq(&pwq->pool->lock);
3609699ce097STejun Heo 
3610699ce097STejun Heo 	if (!freezable || !(pwq->pool->flags & POOL_FREEZING)) {
3611699ce097STejun Heo 		pwq->max_active = wq->saved_max_active;
36120fbd95aaSTejun Heo 
36130fbd95aaSTejun Heo 		while (!list_empty(&pwq->delayed_works) &&
36140fbd95aaSTejun Heo 		       pwq->nr_active < pwq->max_active)
36150fbd95aaSTejun Heo 			pwq_activate_first_delayed(pwq);
3616951a078aSLai Jiangshan 
3617951a078aSLai Jiangshan 		/*
3618951a078aSLai Jiangshan 		 * Need to kick a worker after thawed or an unbound wq's
3619951a078aSLai Jiangshan 		 * max_active is bumped.  It's a slow path.  Do it always.
3620951a078aSLai Jiangshan 		 */
3621951a078aSLai Jiangshan 		wake_up_worker(pwq->pool);
3622699ce097STejun Heo 	} else {
3623699ce097STejun Heo 		pwq->max_active = 0;
3624699ce097STejun Heo 	}
3625699ce097STejun Heo 
3626a357fc03SLai Jiangshan 	spin_unlock_irq(&pwq->pool->lock);
36270fbd95aaSTejun Heo }
36280fbd95aaSTejun Heo 
3629e50aba9aSTejun Heo /* initialize newly alloced @pwq which is associated with @wq and @pool */
3630f147f29eSTejun Heo static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
3631f147f29eSTejun Heo 		     struct worker_pool *pool)
3632d2c1d404STejun Heo {
3633d2c1d404STejun Heo 	BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3634d2c1d404STejun Heo 
3635e50aba9aSTejun Heo 	memset(pwq, 0, sizeof(*pwq));
3636e50aba9aSTejun Heo 
3637d2c1d404STejun Heo 	pwq->pool = pool;
3638d2c1d404STejun Heo 	pwq->wq = wq;
3639d2c1d404STejun Heo 	pwq->flush_color = -1;
36408864b4e5STejun Heo 	pwq->refcnt = 1;
3641d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->delayed_works);
36421befcf30STejun Heo 	INIT_LIST_HEAD(&pwq->pwqs_node);
3643d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->mayday_node);
36448864b4e5STejun Heo 	INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
3645f147f29eSTejun Heo }
3646d2c1d404STejun Heo 
3647f147f29eSTejun Heo /* sync @pwq with the current state of its associated wq and link it */
36481befcf30STejun Heo static void link_pwq(struct pool_workqueue *pwq)
3649f147f29eSTejun Heo {
3650f147f29eSTejun Heo 	struct workqueue_struct *wq = pwq->wq;
3651f147f29eSTejun Heo 
3652f147f29eSTejun Heo 	lockdep_assert_held(&wq->mutex);
365375ccf595STejun Heo 
36541befcf30STejun Heo 	/* may be called multiple times, ignore if already linked */
36551befcf30STejun Heo 	if (!list_empty(&pwq->pwqs_node))
36561befcf30STejun Heo 		return;
36571befcf30STejun Heo 
3658983ca25eSTejun Heo 	/*
3659983ca25eSTejun Heo 	 * Set the matching work_color.  This is synchronized with
36603c25a55dSLai Jiangshan 	 * wq->mutex to avoid confusing flush_workqueue().
3661983ca25eSTejun Heo 	 */
366275ccf595STejun Heo 	pwq->work_color = wq->work_color;
3663983ca25eSTejun Heo 
3664983ca25eSTejun Heo 	/* sync max_active to the current setting */
3665983ca25eSTejun Heo 	pwq_adjust_max_active(pwq);
3666983ca25eSTejun Heo 
3667983ca25eSTejun Heo 	/* link in @pwq */
36689e8cd2f5STejun Heo 	list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
3669df2d5ae4STejun Heo }
36706029a918STejun Heo 
3671f147f29eSTejun Heo /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
3672f147f29eSTejun Heo static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
3673f147f29eSTejun Heo 					const struct workqueue_attrs *attrs)
3674f147f29eSTejun Heo {
3675f147f29eSTejun Heo 	struct worker_pool *pool;
3676f147f29eSTejun Heo 	struct pool_workqueue *pwq;
3677f147f29eSTejun Heo 
3678f147f29eSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3679f147f29eSTejun Heo 
3680f147f29eSTejun Heo 	pool = get_unbound_pool(attrs);
3681f147f29eSTejun Heo 	if (!pool)
3682f147f29eSTejun Heo 		return NULL;
3683f147f29eSTejun Heo 
3684e50aba9aSTejun Heo 	pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
3685f147f29eSTejun Heo 	if (!pwq) {
3686f147f29eSTejun Heo 		put_unbound_pool(pool);
3687f147f29eSTejun Heo 		return NULL;
3688f147f29eSTejun Heo 	}
3689f147f29eSTejun Heo 
3690f147f29eSTejun Heo 	init_pwq(pwq, wq, pool);
3691f147f29eSTejun Heo 	return pwq;
3692d2c1d404STejun Heo }
3693d2c1d404STejun Heo 
36941befcf30STejun Heo /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
36951befcf30STejun Heo static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
36961befcf30STejun Heo 						   int node,
36971befcf30STejun Heo 						   struct pool_workqueue *pwq)
36981befcf30STejun Heo {
36991befcf30STejun Heo 	struct pool_workqueue *old_pwq;
37001befcf30STejun Heo 
37011befcf30STejun Heo 	lockdep_assert_held(&wq->mutex);
37021befcf30STejun Heo 
37031befcf30STejun Heo 	/* link_pwq() can handle duplicate calls */
37041befcf30STejun Heo 	link_pwq(pwq);
37051befcf30STejun Heo 
37061befcf30STejun Heo 	old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
37071befcf30STejun Heo 	rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
37081befcf30STejun Heo 	return old_pwq;
37091befcf30STejun Heo }
37101befcf30STejun Heo 
37119e8cd2f5STejun Heo /**
37129e8cd2f5STejun Heo  * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
37139e8cd2f5STejun Heo  * @wq: the target workqueue
37149e8cd2f5STejun Heo  * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
37159e8cd2f5STejun Heo  *
37169e8cd2f5STejun Heo  * Apply @attrs to an unbound workqueue @wq.  If @attrs doesn't match the
37179e8cd2f5STejun Heo  * current attributes, a new pwq is created and made the first pwq which
37189e8cd2f5STejun Heo  * will serve all new work items.  Older pwqs are released as in-flight
37199e8cd2f5STejun Heo  * work items finish.  Note that a work item which repeatedly requeues
37209e8cd2f5STejun Heo  * itself back-to-back will stay on its current pwq.
37219e8cd2f5STejun Heo  *
37229e8cd2f5STejun Heo  * Performs GFP_KERNEL allocations.  Returns 0 on success and -errno on
37239e8cd2f5STejun Heo  * failure.
37249e8cd2f5STejun Heo  */
37259e8cd2f5STejun Heo int apply_workqueue_attrs(struct workqueue_struct *wq,
37269e8cd2f5STejun Heo 			  const struct workqueue_attrs *attrs)
37279e8cd2f5STejun Heo {
372813e2e556STejun Heo 	struct workqueue_attrs *new_attrs;
37291befcf30STejun Heo 	struct pool_workqueue *pwq, *last_pwq = NULL;
3730f147f29eSTejun Heo 	int node, ret;
37319e8cd2f5STejun Heo 
37328719dceaSTejun Heo 	/* only unbound workqueues can change attributes */
37339e8cd2f5STejun Heo 	if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
37349e8cd2f5STejun Heo 		return -EINVAL;
37359e8cd2f5STejun Heo 
37368719dceaSTejun Heo 	/* creating multiple pwqs breaks ordering guarantee */
37378719dceaSTejun Heo 	if (WARN_ON((wq->flags & __WQ_ORDERED) && !list_empty(&wq->pwqs)))
37388719dceaSTejun Heo 		return -EINVAL;
37398719dceaSTejun Heo 
374013e2e556STejun Heo 	/* make a copy of @attrs and sanitize it */
374113e2e556STejun Heo 	new_attrs = alloc_workqueue_attrs(GFP_KERNEL);
374213e2e556STejun Heo 	if (!new_attrs)
374313e2e556STejun Heo 		goto enomem;
374413e2e556STejun Heo 
374513e2e556STejun Heo 	copy_workqueue_attrs(new_attrs, attrs);
374613e2e556STejun Heo 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
374713e2e556STejun Heo 
3748a892caccSTejun Heo 	mutex_lock(&wq_pool_mutex);
3749f147f29eSTejun Heo 	pwq = alloc_unbound_pwq(wq, new_attrs);
3750a892caccSTejun Heo 	mutex_unlock(&wq_pool_mutex);
3751f147f29eSTejun Heo 	if (!pwq)
375213e2e556STejun Heo 		goto enomem;
37539e8cd2f5STejun Heo 
3754f147f29eSTejun Heo 	mutex_lock(&wq->mutex);
3755a892caccSTejun Heo 
3756f147f29eSTejun Heo 	copy_workqueue_attrs(wq->unbound_attrs, new_attrs);
3757f147f29eSTejun Heo 	for_each_node(node)
37581befcf30STejun Heo 		last_pwq = numa_pwq_tbl_install(wq, node, pwq);
3759f147f29eSTejun Heo 
3760f147f29eSTejun Heo 	mutex_unlock(&wq->mutex);
3761f147f29eSTejun Heo 
37629e8cd2f5STejun Heo 	if (last_pwq) {
37639e8cd2f5STejun Heo 		spin_lock_irq(&last_pwq->pool->lock);
37649e8cd2f5STejun Heo 		put_pwq(last_pwq);
37659e8cd2f5STejun Heo 		spin_unlock_irq(&last_pwq->pool->lock);
37669e8cd2f5STejun Heo 	}
37679e8cd2f5STejun Heo 
37684862125bSTejun Heo 	ret = 0;
37694862125bSTejun Heo 	/* fall through */
37704862125bSTejun Heo out_free:
37714862125bSTejun Heo 	free_workqueue_attrs(new_attrs);
37724862125bSTejun Heo 	return ret;
377313e2e556STejun Heo 
377413e2e556STejun Heo enomem:
37754862125bSTejun Heo 	ret = -ENOMEM;
37764862125bSTejun Heo 	goto out_free;
37779e8cd2f5STejun Heo }
37789e8cd2f5STejun Heo 
377930cdf249STejun Heo static int alloc_and_link_pwqs(struct workqueue_struct *wq)
37801da177e4SLinus Torvalds {
378149e3cf44STejun Heo 	bool highpri = wq->flags & WQ_HIGHPRI;
378230cdf249STejun Heo 	int cpu;
3783e1d8aa9fSFrederic Weisbecker 
378430cdf249STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
3785420c0ddbSTejun Heo 		wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
3786420c0ddbSTejun Heo 		if (!wq->cpu_pwqs)
378730cdf249STejun Heo 			return -ENOMEM;
378830cdf249STejun Heo 
378930cdf249STejun Heo 		for_each_possible_cpu(cpu) {
37907fb98ea7STejun Heo 			struct pool_workqueue *pwq =
37917fb98ea7STejun Heo 				per_cpu_ptr(wq->cpu_pwqs, cpu);
37927a62c2c8STejun Heo 			struct worker_pool *cpu_pools =
3793f02ae73aSTejun Heo 				per_cpu(cpu_worker_pools, cpu);
379430cdf249STejun Heo 
3795f147f29eSTejun Heo 			init_pwq(pwq, wq, &cpu_pools[highpri]);
3796f147f29eSTejun Heo 
3797f147f29eSTejun Heo 			mutex_lock(&wq->mutex);
37981befcf30STejun Heo 			link_pwq(pwq);
3799f147f29eSTejun Heo 			mutex_unlock(&wq->mutex);
380030cdf249STejun Heo 		}
380130cdf249STejun Heo 		return 0;
38029e8cd2f5STejun Heo 	} else {
38039e8cd2f5STejun Heo 		return apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
38049e8cd2f5STejun Heo 	}
38050f900049STejun Heo }
38060f900049STejun Heo 
3807f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
3808f3421797STejun Heo 			       const char *name)
3809b71ab8c2STejun Heo {
3810f3421797STejun Heo 	int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3811f3421797STejun Heo 
3812f3421797STejun Heo 	if (max_active < 1 || max_active > lim)
3813044c782cSValentin Ilie 		pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3814f3421797STejun Heo 			max_active, name, 1, lim);
3815b71ab8c2STejun Heo 
3816f3421797STejun Heo 	return clamp_val(max_active, 1, lim);
3817b71ab8c2STejun Heo }
3818b71ab8c2STejun Heo 
3819b196be89STejun Heo struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
382097e37d7bSTejun Heo 					       unsigned int flags,
38211e19ffc6STejun Heo 					       int max_active,
3822eb13ba87SJohannes Berg 					       struct lock_class_key *key,
3823b196be89STejun Heo 					       const char *lock_name, ...)
38243af24433SOleg Nesterov {
3825df2d5ae4STejun Heo 	size_t tbl_size = 0;
3826ecf6881fSTejun Heo 	va_list args;
38273af24433SOleg Nesterov 	struct workqueue_struct *wq;
382849e3cf44STejun Heo 	struct pool_workqueue *pwq;
3829b196be89STejun Heo 
3830ecf6881fSTejun Heo 	/* allocate wq and format name */
3831df2d5ae4STejun Heo 	if (flags & WQ_UNBOUND)
3832df2d5ae4STejun Heo 		tbl_size = wq_numa_tbl_len * sizeof(wq->numa_pwq_tbl[0]);
3833df2d5ae4STejun Heo 
3834df2d5ae4STejun Heo 	wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
3835b196be89STejun Heo 	if (!wq)
3836d2c1d404STejun Heo 		return NULL;
3837b196be89STejun Heo 
38386029a918STejun Heo 	if (flags & WQ_UNBOUND) {
38396029a918STejun Heo 		wq->unbound_attrs = alloc_workqueue_attrs(GFP_KERNEL);
38406029a918STejun Heo 		if (!wq->unbound_attrs)
38416029a918STejun Heo 			goto err_free_wq;
38426029a918STejun Heo 	}
38436029a918STejun Heo 
3844ecf6881fSTejun Heo 	va_start(args, lock_name);
3845ecf6881fSTejun Heo 	vsnprintf(wq->name, sizeof(wq->name), fmt, args);
3846b196be89STejun Heo 	va_end(args);
38473af24433SOleg Nesterov 
3848d320c038STejun Heo 	max_active = max_active ?: WQ_DFL_ACTIVE;
3849b196be89STejun Heo 	max_active = wq_clamp_max_active(max_active, flags, wq->name);
38503af24433SOleg Nesterov 
3851b196be89STejun Heo 	/* init wq */
385297e37d7bSTejun Heo 	wq->flags = flags;
3853a0a1a5fdSTejun Heo 	wq->saved_max_active = max_active;
38543c25a55dSLai Jiangshan 	mutex_init(&wq->mutex);
3855112202d9STejun Heo 	atomic_set(&wq->nr_pwqs_to_flush, 0);
385630cdf249STejun Heo 	INIT_LIST_HEAD(&wq->pwqs);
385773f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
385873f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
3859493a1724STejun Heo 	INIT_LIST_HEAD(&wq->maydays);
38603af24433SOleg Nesterov 
3861eb13ba87SJohannes Berg 	lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3862cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
38633af24433SOleg Nesterov 
386430cdf249STejun Heo 	if (alloc_and_link_pwqs(wq) < 0)
3865d2c1d404STejun Heo 		goto err_free_wq;
38661537663fSTejun Heo 
3867493008a8STejun Heo 	/*
3868493008a8STejun Heo 	 * Workqueues which may be used during memory reclaim should
3869493008a8STejun Heo 	 * have a rescuer to guarantee forward progress.
3870493008a8STejun Heo 	 */
3871493008a8STejun Heo 	if (flags & WQ_MEM_RECLAIM) {
3872e22bee78STejun Heo 		struct worker *rescuer;
3873e22bee78STejun Heo 
3874d2c1d404STejun Heo 		rescuer = alloc_worker();
3875e22bee78STejun Heo 		if (!rescuer)
3876d2c1d404STejun Heo 			goto err_destroy;
3877e22bee78STejun Heo 
3878111c225aSTejun Heo 		rescuer->rescue_wq = wq;
3879111c225aSTejun Heo 		rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
3880b196be89STejun Heo 					       wq->name);
3881d2c1d404STejun Heo 		if (IS_ERR(rescuer->task)) {
3882d2c1d404STejun Heo 			kfree(rescuer);
3883d2c1d404STejun Heo 			goto err_destroy;
3884d2c1d404STejun Heo 		}
3885e22bee78STejun Heo 
3886d2c1d404STejun Heo 		wq->rescuer = rescuer;
388714a40ffcSTejun Heo 		rescuer->task->flags |= PF_NO_SETAFFINITY;
3888e22bee78STejun Heo 		wake_up_process(rescuer->task);
38893af24433SOleg Nesterov 	}
38901537663fSTejun Heo 
3891226223abSTejun Heo 	if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
3892226223abSTejun Heo 		goto err_destroy;
3893226223abSTejun Heo 
38943af24433SOleg Nesterov 	/*
389568e13a67SLai Jiangshan 	 * wq_pool_mutex protects global freeze state and workqueues list.
389668e13a67SLai Jiangshan 	 * Grab it, adjust max_active and add the new @wq to workqueues
389768e13a67SLai Jiangshan 	 * list.
38983af24433SOleg Nesterov 	 */
389968e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
3900a0a1a5fdSTejun Heo 
3901a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
390249e3cf44STejun Heo 	for_each_pwq(pwq, wq)
3903699ce097STejun Heo 		pwq_adjust_max_active(pwq);
3904a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
3905a0a1a5fdSTejun Heo 
39063af24433SOleg Nesterov 	list_add(&wq->list, &workqueues);
3907a0a1a5fdSTejun Heo 
390868e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
39093af24433SOleg Nesterov 
39103af24433SOleg Nesterov 	return wq;
3911d2c1d404STejun Heo 
3912d2c1d404STejun Heo err_free_wq:
39136029a918STejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
39144690c4abSTejun Heo 	kfree(wq);
3915d2c1d404STejun Heo 	return NULL;
3916d2c1d404STejun Heo err_destroy:
3917d2c1d404STejun Heo 	destroy_workqueue(wq);
39184690c4abSTejun Heo 	return NULL;
39191da177e4SLinus Torvalds }
3920d320c038STejun Heo EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
39211da177e4SLinus Torvalds 
39223af24433SOleg Nesterov /**
39233af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
39243af24433SOleg Nesterov  * @wq: target workqueue
39253af24433SOleg Nesterov  *
39263af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
39273af24433SOleg Nesterov  */
39283af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
39293af24433SOleg Nesterov {
393049e3cf44STejun Heo 	struct pool_workqueue *pwq;
39313af24433SOleg Nesterov 
39329c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
39339c5a2ba7STejun Heo 	drain_workqueue(wq);
3934c8efcc25STejun Heo 
39356183c009STejun Heo 	/* sanity checks */
3936b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
393749e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
39386183c009STejun Heo 		int i;
39396183c009STejun Heo 
394076af4d93STejun Heo 		for (i = 0; i < WORK_NR_COLORS; i++) {
394176af4d93STejun Heo 			if (WARN_ON(pwq->nr_in_flight[i])) {
3942b09f4fd3SLai Jiangshan 				mutex_unlock(&wq->mutex);
39436183c009STejun Heo 				return;
394476af4d93STejun Heo 			}
394576af4d93STejun Heo 		}
394676af4d93STejun Heo 
39478864b4e5STejun Heo 		if (WARN_ON(pwq->refcnt > 1) ||
39488864b4e5STejun Heo 		    WARN_ON(pwq->nr_active) ||
394976af4d93STejun Heo 		    WARN_ON(!list_empty(&pwq->delayed_works))) {
3950b09f4fd3SLai Jiangshan 			mutex_unlock(&wq->mutex);
39516183c009STejun Heo 			return;
39526183c009STejun Heo 		}
395376af4d93STejun Heo 	}
3954b09f4fd3SLai Jiangshan 	mutex_unlock(&wq->mutex);
39556183c009STejun Heo 
3956a0a1a5fdSTejun Heo 	/*
3957a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
3958a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
3959a0a1a5fdSTejun Heo 	 */
396068e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
3961d2c1d404STejun Heo 	list_del_init(&wq->list);
396268e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
39633af24433SOleg Nesterov 
3964226223abSTejun Heo 	workqueue_sysfs_unregister(wq);
3965226223abSTejun Heo 
3966493008a8STejun Heo 	if (wq->rescuer) {
3967e22bee78STejun Heo 		kthread_stop(wq->rescuer->task);
39688d9df9f0SXiaotian Feng 		kfree(wq->rescuer);
3969493008a8STejun Heo 		wq->rescuer = NULL;
3970e22bee78STejun Heo 	}
3971e22bee78STejun Heo 
39728864b4e5STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
397329c91e99STejun Heo 		/*
39748864b4e5STejun Heo 		 * The base ref is never dropped on per-cpu pwqs.  Directly
39758864b4e5STejun Heo 		 * free the pwqs and wq.
397629c91e99STejun Heo 		 */
39778864b4e5STejun Heo 		free_percpu(wq->cpu_pwqs);
39788864b4e5STejun Heo 		kfree(wq);
39798864b4e5STejun Heo 	} else {
39808864b4e5STejun Heo 		/*
39818864b4e5STejun Heo 		 * We're the sole accessor of @wq at this point.  Directly
39828864b4e5STejun Heo 		 * access the first pwq and put the base ref.  As both pwqs
39838864b4e5STejun Heo 		 * and pools are sched-RCU protected, the lock operations
39848864b4e5STejun Heo 		 * are safe.  @wq will be freed when the last pwq is
39858864b4e5STejun Heo 		 * released.
39868864b4e5STejun Heo 		 */
398729c91e99STejun Heo 		pwq = list_first_entry(&wq->pwqs, struct pool_workqueue,
398829c91e99STejun Heo 				       pwqs_node);
39898864b4e5STejun Heo 		spin_lock_irq(&pwq->pool->lock);
39908864b4e5STejun Heo 		put_pwq(pwq);
39918864b4e5STejun Heo 		spin_unlock_irq(&pwq->pool->lock);
399229c91e99STejun Heo 	}
39933af24433SOleg Nesterov }
39943af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
39953af24433SOleg Nesterov 
3996dcd989cbSTejun Heo /**
3997dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
3998dcd989cbSTejun Heo  * @wq: target workqueue
3999dcd989cbSTejun Heo  * @max_active: new max_active value.
4000dcd989cbSTejun Heo  *
4001dcd989cbSTejun Heo  * Set max_active of @wq to @max_active.
4002dcd989cbSTejun Heo  *
4003dcd989cbSTejun Heo  * CONTEXT:
4004dcd989cbSTejun Heo  * Don't call from IRQ context.
4005dcd989cbSTejun Heo  */
4006dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4007dcd989cbSTejun Heo {
400849e3cf44STejun Heo 	struct pool_workqueue *pwq;
4009dcd989cbSTejun Heo 
40108719dceaSTejun Heo 	/* disallow meddling with max_active for ordered workqueues */
40118719dceaSTejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED))
40128719dceaSTejun Heo 		return;
40138719dceaSTejun Heo 
4014f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4015dcd989cbSTejun Heo 
4016a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
4017dcd989cbSTejun Heo 
4018dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
4019dcd989cbSTejun Heo 
4020699ce097STejun Heo 	for_each_pwq(pwq, wq)
4021699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4022dcd989cbSTejun Heo 
4023a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4024dcd989cbSTejun Heo }
4025dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4026dcd989cbSTejun Heo 
4027dcd989cbSTejun Heo /**
4028e6267616STejun Heo  * current_is_workqueue_rescuer - is %current workqueue rescuer?
4029e6267616STejun Heo  *
4030e6267616STejun Heo  * Determine whether %current is a workqueue rescuer.  Can be used from
4031e6267616STejun Heo  * work functions to determine whether it's being run off the rescuer task.
4032e6267616STejun Heo  */
4033e6267616STejun Heo bool current_is_workqueue_rescuer(void)
4034e6267616STejun Heo {
4035e6267616STejun Heo 	struct worker *worker = current_wq_worker();
4036e6267616STejun Heo 
40376a092dfdSLai Jiangshan 	return worker && worker->rescue_wq;
4038e6267616STejun Heo }
4039e6267616STejun Heo 
4040e6267616STejun Heo /**
4041dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
4042dcd989cbSTejun Heo  * @cpu: CPU in question
4043dcd989cbSTejun Heo  * @wq: target workqueue
4044dcd989cbSTejun Heo  *
4045dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
4046dcd989cbSTejun Heo  * no synchronization around this function and the test result is
4047dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4048dcd989cbSTejun Heo  *
4049dcd989cbSTejun Heo  * RETURNS:
4050dcd989cbSTejun Heo  * %true if congested, %false otherwise.
4051dcd989cbSTejun Heo  */
4052d84ff051STejun Heo bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4053dcd989cbSTejun Heo {
40547fb98ea7STejun Heo 	struct pool_workqueue *pwq;
405576af4d93STejun Heo 	bool ret;
405676af4d93STejun Heo 
405788109453SLai Jiangshan 	rcu_read_lock_sched();
40587fb98ea7STejun Heo 
40597fb98ea7STejun Heo 	if (!(wq->flags & WQ_UNBOUND))
40607fb98ea7STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
40617fb98ea7STejun Heo 	else
4062df2d5ae4STejun Heo 		pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4063dcd989cbSTejun Heo 
406476af4d93STejun Heo 	ret = !list_empty(&pwq->delayed_works);
406588109453SLai Jiangshan 	rcu_read_unlock_sched();
406676af4d93STejun Heo 
406776af4d93STejun Heo 	return ret;
4068dcd989cbSTejun Heo }
4069dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
4070dcd989cbSTejun Heo 
4071dcd989cbSTejun Heo /**
4072dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
4073dcd989cbSTejun Heo  * @work: the work to be tested
4074dcd989cbSTejun Heo  *
4075dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
4076dcd989cbSTejun Heo  * synchronization around this function and the test result is
4077dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4078dcd989cbSTejun Heo  *
4079dcd989cbSTejun Heo  * RETURNS:
4080dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
4081dcd989cbSTejun Heo  */
4082dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
4083dcd989cbSTejun Heo {
4084fa1b54e6STejun Heo 	struct worker_pool *pool;
4085dcd989cbSTejun Heo 	unsigned long flags;
4086dcd989cbSTejun Heo 	unsigned int ret = 0;
4087dcd989cbSTejun Heo 
4088dcd989cbSTejun Heo 	if (work_pending(work))
4089dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
4090038366c5SLai Jiangshan 
4091fa1b54e6STejun Heo 	local_irq_save(flags);
4092fa1b54e6STejun Heo 	pool = get_work_pool(work);
4093038366c5SLai Jiangshan 	if (pool) {
4094fa1b54e6STejun Heo 		spin_lock(&pool->lock);
4095c9e7cf27STejun Heo 		if (find_worker_executing_work(pool, work))
4096dcd989cbSTejun Heo 			ret |= WORK_BUSY_RUNNING;
4097fa1b54e6STejun Heo 		spin_unlock(&pool->lock);
4098038366c5SLai Jiangshan 	}
4099fa1b54e6STejun Heo 	local_irq_restore(flags);
4100dcd989cbSTejun Heo 
4101dcd989cbSTejun Heo 	return ret;
4102dcd989cbSTejun Heo }
4103dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
4104dcd989cbSTejun Heo 
4105db7bccf4STejun Heo /*
4106db7bccf4STejun Heo  * CPU hotplug.
4107db7bccf4STejun Heo  *
4108e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
4109112202d9STejun Heo  * are a lot of assumptions on strong associations among work, pwq and
4110706026c2STejun Heo  * pool which make migrating pending and scheduled works very
4111e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
411294cf58bbSTejun Heo  * worker pools serve mix of short, long and very long running works making
4113e22bee78STejun Heo  * blocked draining impractical.
4114e22bee78STejun Heo  *
411524647570STejun Heo  * This is solved by allowing the pools to be disassociated from the CPU
4116628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
4117628c78e7STejun Heo  * cpu comes back online.
4118db7bccf4STejun Heo  */
4119db7bccf4STejun Heo 
4120706026c2STejun Heo static void wq_unbind_fn(struct work_struct *work)
4121db7bccf4STejun Heo {
412238db41d9STejun Heo 	int cpu = smp_processor_id();
41234ce62e9eSTejun Heo 	struct worker_pool *pool;
4124db7bccf4STejun Heo 	struct worker *worker;
4125a9ab775bSTejun Heo 	int wi;
4126db7bccf4STejun Heo 
4127f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
41286183c009STejun Heo 		WARN_ON_ONCE(cpu != smp_processor_id());
4129db7bccf4STejun Heo 
4130bc3a1afcSTejun Heo 		mutex_lock(&pool->manager_mutex);
413194cf58bbSTejun Heo 		spin_lock_irq(&pool->lock);
4132e22bee78STejun Heo 
4133f2d5a0eeSTejun Heo 		/*
4134bc3a1afcSTejun Heo 		 * We've blocked all manager operations.  Make all workers
413594cf58bbSTejun Heo 		 * unbound and set DISASSOCIATED.  Before this, all workers
413694cf58bbSTejun Heo 		 * except for the ones which are still executing works from
413794cf58bbSTejun Heo 		 * before the last CPU down must be on the cpu.  After
413894cf58bbSTejun Heo 		 * this, they may become diasporas.
4139f2d5a0eeSTejun Heo 		 */
4140a9ab775bSTejun Heo 		for_each_pool_worker(worker, wi, pool)
4141403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
4142db7bccf4STejun Heo 
414324647570STejun Heo 		pool->flags |= POOL_DISASSOCIATED;
4144f2d5a0eeSTejun Heo 
414594cf58bbSTejun Heo 		spin_unlock_irq(&pool->lock);
4146bc3a1afcSTejun Heo 		mutex_unlock(&pool->manager_mutex);
414794cf58bbSTejun Heo 	}
4148e22bee78STejun Heo 
4149e22bee78STejun Heo 	/*
4150628c78e7STejun Heo 	 * Call schedule() so that we cross rq->lock and thus can guarantee
4151628c78e7STejun Heo 	 * sched callbacks see the %WORKER_UNBOUND flag.  This is necessary
4152628c78e7STejun Heo 	 * as scheduler callbacks may be invoked from other cpus.
4153628c78e7STejun Heo 	 */
4154628c78e7STejun Heo 	schedule();
4155628c78e7STejun Heo 
4156628c78e7STejun Heo 	/*
4157628c78e7STejun Heo 	 * Sched callbacks are disabled now.  Zap nr_running.  After this,
4158628c78e7STejun Heo 	 * nr_running stays zero and need_more_worker() and keep_working()
415938db41d9STejun Heo 	 * are always true as long as the worklist is not empty.  Pools on
416038db41d9STejun Heo 	 * @cpu now behave as unbound (in terms of concurrency management)
416138db41d9STejun Heo 	 * pools which are served by workers tied to the CPU.
4162628c78e7STejun Heo 	 *
4163628c78e7STejun Heo 	 * On return from this function, the current worker would trigger
4164628c78e7STejun Heo 	 * unbound chain execution of pending work items if other workers
4165628c78e7STejun Heo 	 * didn't already.
4166e22bee78STejun Heo 	 */
4167f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu)
4168e19e397aSTejun Heo 		atomic_set(&pool->nr_running, 0);
4169db7bccf4STejun Heo }
4170db7bccf4STejun Heo 
4171bd7c089eSTejun Heo /**
4172bd7c089eSTejun Heo  * rebind_workers - rebind all workers of a pool to the associated CPU
4173bd7c089eSTejun Heo  * @pool: pool of interest
4174bd7c089eSTejun Heo  *
4175a9ab775bSTejun Heo  * @pool->cpu is coming online.  Rebind all workers to the CPU.
4176bd7c089eSTejun Heo  */
4177bd7c089eSTejun Heo static void rebind_workers(struct worker_pool *pool)
4178bd7c089eSTejun Heo {
4179a9ab775bSTejun Heo 	struct worker *worker;
4180a9ab775bSTejun Heo 	int wi;
4181bd7c089eSTejun Heo 
4182bd7c089eSTejun Heo 	lockdep_assert_held(&pool->manager_mutex);
4183bd7c089eSTejun Heo 
4184bd7c089eSTejun Heo 	/*
4185a9ab775bSTejun Heo 	 * Restore CPU affinity of all workers.  As all idle workers should
4186a9ab775bSTejun Heo 	 * be on the run-queue of the associated CPU before any local
4187a9ab775bSTejun Heo 	 * wake-ups for concurrency management happen, restore CPU affinty
4188a9ab775bSTejun Heo 	 * of all workers first and then clear UNBOUND.  As we're called
4189a9ab775bSTejun Heo 	 * from CPU_ONLINE, the following shouldn't fail.
4190bd7c089eSTejun Heo 	 */
4191a9ab775bSTejun Heo 	for_each_pool_worker(worker, wi, pool)
4192a9ab775bSTejun Heo 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4193a9ab775bSTejun Heo 						  pool->attrs->cpumask) < 0);
4194a9ab775bSTejun Heo 
4195a9ab775bSTejun Heo 	spin_lock_irq(&pool->lock);
4196a9ab775bSTejun Heo 
4197a9ab775bSTejun Heo 	for_each_pool_worker(worker, wi, pool) {
4198a9ab775bSTejun Heo 		unsigned int worker_flags = worker->flags;
4199a9ab775bSTejun Heo 
4200a9ab775bSTejun Heo 		/*
4201a9ab775bSTejun Heo 		 * A bound idle worker should actually be on the runqueue
4202a9ab775bSTejun Heo 		 * of the associated CPU for local wake-ups targeting it to
4203a9ab775bSTejun Heo 		 * work.  Kick all idle workers so that they migrate to the
4204a9ab775bSTejun Heo 		 * associated CPU.  Doing this in the same loop as
4205a9ab775bSTejun Heo 		 * replacing UNBOUND with REBOUND is safe as no worker will
4206a9ab775bSTejun Heo 		 * be bound before @pool->lock is released.
4207a9ab775bSTejun Heo 		 */
4208a9ab775bSTejun Heo 		if (worker_flags & WORKER_IDLE)
4209bd7c089eSTejun Heo 			wake_up_process(worker->task);
4210bd7c089eSTejun Heo 
4211bd7c089eSTejun Heo 		/*
4212a9ab775bSTejun Heo 		 * We want to clear UNBOUND but can't directly call
4213a9ab775bSTejun Heo 		 * worker_clr_flags() or adjust nr_running.  Atomically
4214a9ab775bSTejun Heo 		 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
4215a9ab775bSTejun Heo 		 * @worker will clear REBOUND using worker_clr_flags() when
4216a9ab775bSTejun Heo 		 * it initiates the next execution cycle thus restoring
4217a9ab775bSTejun Heo 		 * concurrency management.  Note that when or whether
4218a9ab775bSTejun Heo 		 * @worker clears REBOUND doesn't affect correctness.
4219a9ab775bSTejun Heo 		 *
4220a9ab775bSTejun Heo 		 * ACCESS_ONCE() is necessary because @worker->flags may be
4221a9ab775bSTejun Heo 		 * tested without holding any lock in
4222a9ab775bSTejun Heo 		 * wq_worker_waking_up().  Without it, NOT_RUNNING test may
4223a9ab775bSTejun Heo 		 * fail incorrectly leading to premature concurrency
4224a9ab775bSTejun Heo 		 * management operations.
4225bd7c089eSTejun Heo 		 */
4226a9ab775bSTejun Heo 		WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
4227a9ab775bSTejun Heo 		worker_flags |= WORKER_REBOUND;
4228a9ab775bSTejun Heo 		worker_flags &= ~WORKER_UNBOUND;
4229a9ab775bSTejun Heo 		ACCESS_ONCE(worker->flags) = worker_flags;
4230bd7c089eSTejun Heo 	}
4231a9ab775bSTejun Heo 
4232a9ab775bSTejun Heo 	spin_unlock_irq(&pool->lock);
4233bd7c089eSTejun Heo }
4234bd7c089eSTejun Heo 
42357dbc725eSTejun Heo /**
42367dbc725eSTejun Heo  * restore_unbound_workers_cpumask - restore cpumask of unbound workers
42377dbc725eSTejun Heo  * @pool: unbound pool of interest
42387dbc725eSTejun Heo  * @cpu: the CPU which is coming up
42397dbc725eSTejun Heo  *
42407dbc725eSTejun Heo  * An unbound pool may end up with a cpumask which doesn't have any online
42417dbc725eSTejun Heo  * CPUs.  When a worker of such pool get scheduled, the scheduler resets
42427dbc725eSTejun Heo  * its cpus_allowed.  If @cpu is in @pool's cpumask which didn't have any
42437dbc725eSTejun Heo  * online CPU before, cpus_allowed of all its workers should be restored.
42447dbc725eSTejun Heo  */
42457dbc725eSTejun Heo static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
42467dbc725eSTejun Heo {
42477dbc725eSTejun Heo 	static cpumask_t cpumask;
42487dbc725eSTejun Heo 	struct worker *worker;
42497dbc725eSTejun Heo 	int wi;
42507dbc725eSTejun Heo 
42517dbc725eSTejun Heo 	lockdep_assert_held(&pool->manager_mutex);
42527dbc725eSTejun Heo 
42537dbc725eSTejun Heo 	/* is @cpu allowed for @pool? */
42547dbc725eSTejun Heo 	if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
42557dbc725eSTejun Heo 		return;
42567dbc725eSTejun Heo 
42577dbc725eSTejun Heo 	/* is @cpu the only online CPU? */
42587dbc725eSTejun Heo 	cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
42597dbc725eSTejun Heo 	if (cpumask_weight(&cpumask) != 1)
42607dbc725eSTejun Heo 		return;
42617dbc725eSTejun Heo 
42627dbc725eSTejun Heo 	/* as we're called from CPU_ONLINE, the following shouldn't fail */
42637dbc725eSTejun Heo 	for_each_pool_worker(worker, wi, pool)
42647dbc725eSTejun Heo 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
42657dbc725eSTejun Heo 						  pool->attrs->cpumask) < 0);
42667dbc725eSTejun Heo }
42677dbc725eSTejun Heo 
42688db25e78STejun Heo /*
42698db25e78STejun Heo  * Workqueues should be brought up before normal priority CPU notifiers.
42708db25e78STejun Heo  * This will be registered high priority CPU notifier.
42718db25e78STejun Heo  */
42729fdf9b73SLai Jiangshan static int __cpuinit workqueue_cpu_up_callback(struct notifier_block *nfb,
42731da177e4SLinus Torvalds 					       unsigned long action,
42741da177e4SLinus Torvalds 					       void *hcpu)
42751da177e4SLinus Torvalds {
4276d84ff051STejun Heo 	int cpu = (unsigned long)hcpu;
42774ce62e9eSTejun Heo 	struct worker_pool *pool;
42787dbc725eSTejun Heo 	int pi;
42791da177e4SLinus Torvalds 
42808db25e78STejun Heo 	switch (action & ~CPU_TASKS_FROZEN) {
42813af24433SOleg Nesterov 	case CPU_UP_PREPARE:
4282f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
42833ce63377STejun Heo 			if (pool->nr_workers)
42843ce63377STejun Heo 				continue;
4285ebf44d16STejun Heo 			if (create_and_start_worker(pool) < 0)
42863ce63377STejun Heo 				return NOTIFY_BAD;
42873af24433SOleg Nesterov 		}
42881da177e4SLinus Torvalds 		break;
42891da177e4SLinus Torvalds 
429065758202STejun Heo 	case CPU_DOWN_FAILED:
429165758202STejun Heo 	case CPU_ONLINE:
429268e13a67SLai Jiangshan 		mutex_lock(&wq_pool_mutex);
42937dbc725eSTejun Heo 
42947dbc725eSTejun Heo 		for_each_pool(pool, pi) {
4295bc3a1afcSTejun Heo 			mutex_lock(&pool->manager_mutex);
429694cf58bbSTejun Heo 
42977dbc725eSTejun Heo 			if (pool->cpu == cpu) {
4298a9ab775bSTejun Heo 				spin_lock_irq(&pool->lock);
429924647570STejun Heo 				pool->flags &= ~POOL_DISASSOCIATED;
4300a9ab775bSTejun Heo 				spin_unlock_irq(&pool->lock);
4301a9ab775bSTejun Heo 
430294cf58bbSTejun Heo 				rebind_workers(pool);
43037dbc725eSTejun Heo 			} else if (pool->cpu < 0) {
43047dbc725eSTejun Heo 				restore_unbound_workers_cpumask(pool, cpu);
43057dbc725eSTejun Heo 			}
430694cf58bbSTejun Heo 
4307bc3a1afcSTejun Heo 			mutex_unlock(&pool->manager_mutex);
430894cf58bbSTejun Heo 		}
43097dbc725eSTejun Heo 
431068e13a67SLai Jiangshan 		mutex_unlock(&wq_pool_mutex);
43118db25e78STejun Heo 		break;
431265758202STejun Heo 	}
431365758202STejun Heo 	return NOTIFY_OK;
431465758202STejun Heo }
431565758202STejun Heo 
431665758202STejun Heo /*
431765758202STejun Heo  * Workqueues should be brought down after normal priority CPU notifiers.
431865758202STejun Heo  * This will be registered as low priority CPU notifier.
431965758202STejun Heo  */
43209fdf9b73SLai Jiangshan static int __cpuinit workqueue_cpu_down_callback(struct notifier_block *nfb,
432165758202STejun Heo 						 unsigned long action,
432265758202STejun Heo 						 void *hcpu)
432365758202STejun Heo {
4324d84ff051STejun Heo 	int cpu = (unsigned long)hcpu;
43258db25e78STejun Heo 	struct work_struct unbind_work;
43268db25e78STejun Heo 
432765758202STejun Heo 	switch (action & ~CPU_TASKS_FROZEN) {
432865758202STejun Heo 	case CPU_DOWN_PREPARE:
43298db25e78STejun Heo 		/* unbinding should happen on the local CPU */
4330706026c2STejun Heo 		INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
43317635d2fdSJoonsoo Kim 		queue_work_on(cpu, system_highpri_wq, &unbind_work);
43328db25e78STejun Heo 		flush_work(&unbind_work);
43338db25e78STejun Heo 		break;
433465758202STejun Heo 	}
433565758202STejun Heo 	return NOTIFY_OK;
433665758202STejun Heo }
433765758202STejun Heo 
43382d3854a3SRusty Russell #ifdef CONFIG_SMP
43398ccad40dSRusty Russell 
43402d3854a3SRusty Russell struct work_for_cpu {
4341ed48ece2STejun Heo 	struct work_struct work;
43422d3854a3SRusty Russell 	long (*fn)(void *);
43432d3854a3SRusty Russell 	void *arg;
43442d3854a3SRusty Russell 	long ret;
43452d3854a3SRusty Russell };
43462d3854a3SRusty Russell 
4347ed48ece2STejun Heo static void work_for_cpu_fn(struct work_struct *work)
43482d3854a3SRusty Russell {
4349ed48ece2STejun Heo 	struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
4350ed48ece2STejun Heo 
43512d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
43522d3854a3SRusty Russell }
43532d3854a3SRusty Russell 
43542d3854a3SRusty Russell /**
43552d3854a3SRusty Russell  * work_on_cpu - run a function in user context on a particular cpu
43562d3854a3SRusty Russell  * @cpu: the cpu to run on
43572d3854a3SRusty Russell  * @fn: the function to run
43582d3854a3SRusty Russell  * @arg: the function arg
43592d3854a3SRusty Russell  *
436031ad9081SRusty Russell  * This will return the value @fn returns.
436131ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
43626b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
43632d3854a3SRusty Russell  */
4364d84ff051STejun Heo long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
43652d3854a3SRusty Russell {
4366ed48ece2STejun Heo 	struct work_for_cpu wfc = { .fn = fn, .arg = arg };
43672d3854a3SRusty Russell 
4368ed48ece2STejun Heo 	INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
4369ed48ece2STejun Heo 	schedule_work_on(cpu, &wfc.work);
4370ed48ece2STejun Heo 	flush_work(&wfc.work);
43712d3854a3SRusty Russell 	return wfc.ret;
43722d3854a3SRusty Russell }
43732d3854a3SRusty Russell EXPORT_SYMBOL_GPL(work_on_cpu);
43742d3854a3SRusty Russell #endif /* CONFIG_SMP */
43752d3854a3SRusty Russell 
4376a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
4377e7577c50SRusty Russell 
4378a0a1a5fdSTejun Heo /**
4379a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
4380a0a1a5fdSTejun Heo  *
438158a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
4382c5aa87bbSTejun Heo  * workqueues will queue new works to their delayed_works list instead of
4383706026c2STejun Heo  * pool->worklist.
4384a0a1a5fdSTejun Heo  *
4385a0a1a5fdSTejun Heo  * CONTEXT:
4386a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4387a0a1a5fdSTejun Heo  */
4388a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
4389a0a1a5fdSTejun Heo {
439017116969STejun Heo 	struct worker_pool *pool;
439124b8a847STejun Heo 	struct workqueue_struct *wq;
439224b8a847STejun Heo 	struct pool_workqueue *pwq;
4393611c92a0STejun Heo 	int pi;
4394a0a1a5fdSTejun Heo 
439568e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4396a0a1a5fdSTejun Heo 
43976183c009STejun Heo 	WARN_ON_ONCE(workqueue_freezing);
4398a0a1a5fdSTejun Heo 	workqueue_freezing = true;
4399a0a1a5fdSTejun Heo 
440024b8a847STejun Heo 	/* set FREEZING */
4401611c92a0STejun Heo 	for_each_pool(pool, pi) {
44025bcab335STejun Heo 		spin_lock_irq(&pool->lock);
440335b6bb63STejun Heo 		WARN_ON_ONCE(pool->flags & POOL_FREEZING);
440435b6bb63STejun Heo 		pool->flags |= POOL_FREEZING;
44055bcab335STejun Heo 		spin_unlock_irq(&pool->lock);
44061da177e4SLinus Torvalds 	}
44078b03ae3cSTejun Heo 
440824b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
4409a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
4410699ce097STejun Heo 		for_each_pwq(pwq, wq)
4411699ce097STejun Heo 			pwq_adjust_max_active(pwq);
4412a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
4413a1056305STejun Heo 	}
44145bcab335STejun Heo 
441568e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
4416a0a1a5fdSTejun Heo }
4417a0a1a5fdSTejun Heo 
4418a0a1a5fdSTejun Heo /**
441958a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
4420a0a1a5fdSTejun Heo  *
4421a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
4422a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
4423a0a1a5fdSTejun Heo  *
4424a0a1a5fdSTejun Heo  * CONTEXT:
442568e13a67SLai Jiangshan  * Grabs and releases wq_pool_mutex.
4426a0a1a5fdSTejun Heo  *
4427a0a1a5fdSTejun Heo  * RETURNS:
442858a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
442958a69cb4STejun Heo  * is complete.
4430a0a1a5fdSTejun Heo  */
4431a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
4432a0a1a5fdSTejun Heo {
4433a0a1a5fdSTejun Heo 	bool busy = false;
443424b8a847STejun Heo 	struct workqueue_struct *wq;
443524b8a847STejun Heo 	struct pool_workqueue *pwq;
4436a0a1a5fdSTejun Heo 
443768e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4438a0a1a5fdSTejun Heo 
44396183c009STejun Heo 	WARN_ON_ONCE(!workqueue_freezing);
4440a0a1a5fdSTejun Heo 
444124b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
444224b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
444324b8a847STejun Heo 			continue;
4444a0a1a5fdSTejun Heo 		/*
4445a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
4446a0a1a5fdSTejun Heo 		 * to peek without lock.
4447a0a1a5fdSTejun Heo 		 */
444888109453SLai Jiangshan 		rcu_read_lock_sched();
444924b8a847STejun Heo 		for_each_pwq(pwq, wq) {
44506183c009STejun Heo 			WARN_ON_ONCE(pwq->nr_active < 0);
4451112202d9STejun Heo 			if (pwq->nr_active) {
4452a0a1a5fdSTejun Heo 				busy = true;
445388109453SLai Jiangshan 				rcu_read_unlock_sched();
4454a0a1a5fdSTejun Heo 				goto out_unlock;
4455a0a1a5fdSTejun Heo 			}
4456a0a1a5fdSTejun Heo 		}
445788109453SLai Jiangshan 		rcu_read_unlock_sched();
4458a0a1a5fdSTejun Heo 	}
4459a0a1a5fdSTejun Heo out_unlock:
446068e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
4461a0a1a5fdSTejun Heo 	return busy;
4462a0a1a5fdSTejun Heo }
4463a0a1a5fdSTejun Heo 
4464a0a1a5fdSTejun Heo /**
4465a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
4466a0a1a5fdSTejun Heo  *
4467a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
4468706026c2STejun Heo  * frozen works are transferred to their respective pool worklists.
4469a0a1a5fdSTejun Heo  *
4470a0a1a5fdSTejun Heo  * CONTEXT:
4471a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4472a0a1a5fdSTejun Heo  */
4473a0a1a5fdSTejun Heo void thaw_workqueues(void)
4474a0a1a5fdSTejun Heo {
447524b8a847STejun Heo 	struct workqueue_struct *wq;
447624b8a847STejun Heo 	struct pool_workqueue *pwq;
447724b8a847STejun Heo 	struct worker_pool *pool;
4478611c92a0STejun Heo 	int pi;
4479a0a1a5fdSTejun Heo 
448068e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4481a0a1a5fdSTejun Heo 
4482a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
4483a0a1a5fdSTejun Heo 		goto out_unlock;
4484a0a1a5fdSTejun Heo 
448524b8a847STejun Heo 	/* clear FREEZING */
4486611c92a0STejun Heo 	for_each_pool(pool, pi) {
44875bcab335STejun Heo 		spin_lock_irq(&pool->lock);
448835b6bb63STejun Heo 		WARN_ON_ONCE(!(pool->flags & POOL_FREEZING));
448935b6bb63STejun Heo 		pool->flags &= ~POOL_FREEZING;
44905bcab335STejun Heo 		spin_unlock_irq(&pool->lock);
4491d565ed63STejun Heo 	}
449224b8a847STejun Heo 
449324b8a847STejun Heo 	/* restore max_active and repopulate worklist */
449424b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
4495a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
4496699ce097STejun Heo 		for_each_pwq(pwq, wq)
4497699ce097STejun Heo 			pwq_adjust_max_active(pwq);
4498a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
449924b8a847STejun Heo 	}
450024b8a847STejun Heo 
4501a0a1a5fdSTejun Heo 	workqueue_freezing = false;
4502a0a1a5fdSTejun Heo out_unlock:
450368e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
4504a0a1a5fdSTejun Heo }
4505a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
4506a0a1a5fdSTejun Heo 
4507bce90380STejun Heo static void __init wq_numa_init(void)
4508bce90380STejun Heo {
4509bce90380STejun Heo 	cpumask_var_t *tbl;
4510bce90380STejun Heo 	int node, cpu;
4511bce90380STejun Heo 
4512bce90380STejun Heo 	/* determine NUMA pwq table len - highest node id + 1 */
4513bce90380STejun Heo 	for_each_node(node)
4514bce90380STejun Heo 		wq_numa_tbl_len = max(wq_numa_tbl_len, node + 1);
4515bce90380STejun Heo 
4516bce90380STejun Heo 	if (num_possible_nodes() <= 1)
4517bce90380STejun Heo 		return;
4518bce90380STejun Heo 
4519bce90380STejun Heo 	/*
4520bce90380STejun Heo 	 * We want masks of possible CPUs of each node which isn't readily
4521bce90380STejun Heo 	 * available.  Build one from cpu_to_node() which should have been
4522bce90380STejun Heo 	 * fully initialized by now.
4523bce90380STejun Heo 	 */
4524bce90380STejun Heo 	tbl = kzalloc(wq_numa_tbl_len * sizeof(tbl[0]), GFP_KERNEL);
4525bce90380STejun Heo 	BUG_ON(!tbl);
4526bce90380STejun Heo 
4527bce90380STejun Heo 	for_each_node(node)
4528bce90380STejun Heo 		BUG_ON(!alloc_cpumask_var_node(&tbl[node], GFP_KERNEL, node));
4529bce90380STejun Heo 
4530bce90380STejun Heo 	for_each_possible_cpu(cpu) {
4531bce90380STejun Heo 		node = cpu_to_node(cpu);
4532bce90380STejun Heo 		if (WARN_ON(node == NUMA_NO_NODE)) {
4533bce90380STejun Heo 			pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
4534bce90380STejun Heo 			/* happens iff arch is bonkers, let's just proceed */
4535bce90380STejun Heo 			return;
4536bce90380STejun Heo 		}
4537bce90380STejun Heo 		cpumask_set_cpu(cpu, tbl[node]);
4538bce90380STejun Heo 	}
4539bce90380STejun Heo 
4540bce90380STejun Heo 	wq_numa_possible_cpumask = tbl;
4541bce90380STejun Heo 	wq_numa_enabled = true;
4542bce90380STejun Heo }
4543bce90380STejun Heo 
45446ee0578bSSuresh Siddha static int __init init_workqueues(void)
45451da177e4SLinus Torvalds {
45467a4e344cSTejun Heo 	int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
45477a4e344cSTejun Heo 	int i, cpu;
4548c34056a3STejun Heo 
45497c3eed5cSTejun Heo 	/* make sure we have enough bits for OFFQ pool ID */
45507c3eed5cSTejun Heo 	BUILD_BUG_ON((1LU << (BITS_PER_LONG - WORK_OFFQ_POOL_SHIFT)) <
45516be19588SLai Jiangshan 		     WORK_CPU_END * NR_STD_WORKER_POOLS);
4552b5490077STejun Heo 
4553e904e6c2STejun Heo 	WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
4554e904e6c2STejun Heo 
4555e904e6c2STejun Heo 	pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
4556e904e6c2STejun Heo 
455765758202STejun Heo 	cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
4558a5b4e57dSLai Jiangshan 	hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
45598b03ae3cSTejun Heo 
4560bce90380STejun Heo 	wq_numa_init();
4561bce90380STejun Heo 
4562706026c2STejun Heo 	/* initialize CPU pools */
456329c91e99STejun Heo 	for_each_possible_cpu(cpu) {
45644ce62e9eSTejun Heo 		struct worker_pool *pool;
45658b03ae3cSTejun Heo 
45667a4e344cSTejun Heo 		i = 0;
4567f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
45687a4e344cSTejun Heo 			BUG_ON(init_worker_pool(pool));
4569ec22ca5eSTejun Heo 			pool->cpu = cpu;
45707a4e344cSTejun Heo 			cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
45717a4e344cSTejun Heo 			pool->attrs->nice = std_nice[i++];
4572f3f90ad4STejun Heo 			pool->node = cpu_to_node(cpu);
45737a4e344cSTejun Heo 
45749daf9e67STejun Heo 			/* alloc pool ID */
457568e13a67SLai Jiangshan 			mutex_lock(&wq_pool_mutex);
45769daf9e67STejun Heo 			BUG_ON(worker_pool_assign_id(pool));
457768e13a67SLai Jiangshan 			mutex_unlock(&wq_pool_mutex);
45784ce62e9eSTejun Heo 		}
45798b03ae3cSTejun Heo 	}
45808b03ae3cSTejun Heo 
4581e22bee78STejun Heo 	/* create the initial worker */
458229c91e99STejun Heo 	for_each_online_cpu(cpu) {
45834ce62e9eSTejun Heo 		struct worker_pool *pool;
4584e22bee78STejun Heo 
4585f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
458624647570STejun Heo 			pool->flags &= ~POOL_DISASSOCIATED;
4587ebf44d16STejun Heo 			BUG_ON(create_and_start_worker(pool) < 0);
4588e22bee78STejun Heo 		}
45894ce62e9eSTejun Heo 	}
4590e22bee78STejun Heo 
459129c91e99STejun Heo 	/* create default unbound wq attrs */
459229c91e99STejun Heo 	for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
459329c91e99STejun Heo 		struct workqueue_attrs *attrs;
459429c91e99STejun Heo 
459529c91e99STejun Heo 		BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
459629c91e99STejun Heo 		attrs->nice = std_nice[i];
459729c91e99STejun Heo 		unbound_std_wq_attrs[i] = attrs;
459829c91e99STejun Heo 	}
459929c91e99STejun Heo 
4600d320c038STejun Heo 	system_wq = alloc_workqueue("events", 0, 0);
46011aabe902SJoonsoo Kim 	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
4602d320c038STejun Heo 	system_long_wq = alloc_workqueue("events_long", 0, 0);
4603f3421797STejun Heo 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
4604f3421797STejun Heo 					    WQ_UNBOUND_MAX_ACTIVE);
460524d51addSTejun Heo 	system_freezable_wq = alloc_workqueue("events_freezable",
460624d51addSTejun Heo 					      WQ_FREEZABLE, 0);
46071aabe902SJoonsoo Kim 	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
4608ae930e0fSTejun Heo 	       !system_unbound_wq || !system_freezable_wq);
46096ee0578bSSuresh Siddha 	return 0;
46101da177e4SLinus Torvalds }
46116ee0578bSSuresh Siddha early_initcall(init_workqueues);
4612