xref: /linux-6.15/kernel/workqueue.c (revision 989442d7)
1457c8996SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
21da177e4SLinus Torvalds /*
3c54fce6eSTejun Heo  * kernel/workqueue.c - generic async execution with shared worker pool
41da177e4SLinus Torvalds  *
5c54fce6eSTejun Heo  * Copyright (C) 2002		Ingo Molnar
61da177e4SLinus Torvalds  *
71da177e4SLinus Torvalds  *   Derived from the taskqueue/keventd code by:
81da177e4SLinus Torvalds  *     David Woodhouse <[email protected]>
9e1f8e874SFrancois Cami  *     Andrew Morton
101da177e4SLinus Torvalds  *     Kai Petzke <[email protected]>
111da177e4SLinus Torvalds  *     Theodore Ts'o <[email protected]>
1289ada679SChristoph Lameter  *
13cde53535SChristoph Lameter  * Made to use alloc_percpu by Christoph Lameter.
14c54fce6eSTejun Heo  *
15c54fce6eSTejun Heo  * Copyright (C) 2010		SUSE Linux Products GmbH
16c54fce6eSTejun Heo  * Copyright (C) 2010		Tejun Heo <[email protected]>
17c54fce6eSTejun Heo  *
18c54fce6eSTejun Heo  * This is the generic async execution mechanism.  Work items as are
19c54fce6eSTejun Heo  * executed in process context.  The worker pool is shared and
20b11895c4SLibin  * automatically managed.  There are two worker pools for each CPU (one for
21b11895c4SLibin  * normal work items and the other for high priority ones) and some extra
22b11895c4SLibin  * pools for workqueues which are not bound to any specific CPU - the
23b11895c4SLibin  * number of these backing pools is dynamic.
24c54fce6eSTejun Heo  *
259a261491SBenjamin Peterson  * Please read Documentation/core-api/workqueue.rst for details.
261da177e4SLinus Torvalds  */
271da177e4SLinus Torvalds 
289984de1aSPaul Gortmaker #include <linux/export.h>
291da177e4SLinus Torvalds #include <linux/kernel.h>
301da177e4SLinus Torvalds #include <linux/sched.h>
311da177e4SLinus Torvalds #include <linux/init.h>
321da177e4SLinus Torvalds #include <linux/signal.h>
331da177e4SLinus Torvalds #include <linux/completion.h>
341da177e4SLinus Torvalds #include <linux/workqueue.h>
351da177e4SLinus Torvalds #include <linux/slab.h>
361da177e4SLinus Torvalds #include <linux/cpu.h>
371da177e4SLinus Torvalds #include <linux/notifier.h>
381da177e4SLinus Torvalds #include <linux/kthread.h>
391fa44ecaSJames Bottomley #include <linux/hardirq.h>
4046934023SChristoph Lameter #include <linux/mempolicy.h>
41341a5958SRafael J. Wysocki #include <linux/freezer.h>
42d5abe669SPeter Zijlstra #include <linux/debug_locks.h>
434e6045f1SJohannes Berg #include <linux/lockdep.h>
44c34056a3STejun Heo #include <linux/idr.h>
4529c91e99STejun Heo #include <linux/jhash.h>
4642f8570fSSasha Levin #include <linux/hashtable.h>
4776af4d93STejun Heo #include <linux/rculist.h>
48bce90380STejun Heo #include <linux/nodemask.h>
494c16bd32STejun Heo #include <linux/moduleparam.h>
503d1cb205STejun Heo #include <linux/uaccess.h>
51c98a9805STal Shorer #include <linux/sched/isolation.h>
5262635ea8SSergey Senozhatsky #include <linux/nmi.h>
53940d71c6SSergey Senozhatsky #include <linux/kvm_para.h>
54e22bee78STejun Heo 
55ea138446STejun Heo #include "workqueue_internal.h"
561da177e4SLinus Torvalds 
57c8e55f36STejun Heo enum {
58bc2ae0f5STejun Heo 	/*
5924647570STejun Heo 	 * worker_pool flags
60bc2ae0f5STejun Heo 	 *
6124647570STejun Heo 	 * A bound pool is either associated or disassociated with its CPU.
62bc2ae0f5STejun Heo 	 * While associated (!DISASSOCIATED), all workers are bound to the
63bc2ae0f5STejun Heo 	 * CPU and none has %WORKER_UNBOUND set and concurrency management
64bc2ae0f5STejun Heo 	 * is in effect.
65bc2ae0f5STejun Heo 	 *
66bc2ae0f5STejun Heo 	 * While DISASSOCIATED, the cpu may be offline and all workers have
67bc2ae0f5STejun Heo 	 * %WORKER_UNBOUND set and concurrency management disabled, and may
6824647570STejun Heo 	 * be executing on any CPU.  The pool behaves as an unbound one.
69bc2ae0f5STejun Heo 	 *
70bc3a1afcSTejun Heo 	 * Note that DISASSOCIATED should be flipped only while holding
711258fae7STejun Heo 	 * wq_pool_attach_mutex to avoid changing binding state while
724736cbf7SLai Jiangshan 	 * worker_attach_to_pool() is in progress.
73bc2ae0f5STejun Heo 	 */
74692b4825STejun Heo 	POOL_MANAGER_ACTIVE	= 1 << 0,	/* being managed */
7524647570STejun Heo 	POOL_DISASSOCIATED	= 1 << 2,	/* cpu can't serve workers */
76db7bccf4STejun Heo 
77c8e55f36STejun Heo 	/* worker flags */
78c8e55f36STejun Heo 	WORKER_DIE		= 1 << 1,	/* die die die */
79c8e55f36STejun Heo 	WORKER_IDLE		= 1 << 2,	/* is idle */
80e22bee78STejun Heo 	WORKER_PREP		= 1 << 3,	/* preparing to run works */
81fb0e7bebSTejun Heo 	WORKER_CPU_INTENSIVE	= 1 << 6,	/* cpu intensive */
82f3421797STejun Heo 	WORKER_UNBOUND		= 1 << 7,	/* worker is unbound */
83a9ab775bSTejun Heo 	WORKER_REBOUND		= 1 << 8,	/* worker was rebound */
84e22bee78STejun Heo 
85a9ab775bSTejun Heo 	WORKER_NOT_RUNNING	= WORKER_PREP | WORKER_CPU_INTENSIVE |
86a9ab775bSTejun Heo 				  WORKER_UNBOUND | WORKER_REBOUND,
87db7bccf4STejun Heo 
88e34cdddbSTejun Heo 	NR_STD_WORKER_POOLS	= 2,		/* # standard pools per cpu */
894ce62e9eSTejun Heo 
9029c91e99STejun Heo 	UNBOUND_POOL_HASH_ORDER	= 6,		/* hashed by pool->attrs */
91c8e55f36STejun Heo 	BUSY_WORKER_HASH_ORDER	= 6,		/* 64 pointers */
92db7bccf4STejun Heo 
93e22bee78STejun Heo 	MAX_IDLE_WORKERS_RATIO	= 4,		/* 1/4 of busy can be idle */
94e22bee78STejun Heo 	IDLE_WORKER_TIMEOUT	= 300 * HZ,	/* keep idle ones for 5 mins */
95e22bee78STejun Heo 
963233cdbdSTejun Heo 	MAYDAY_INITIAL_TIMEOUT  = HZ / 100 >= 2 ? HZ / 100 : 2,
973233cdbdSTejun Heo 						/* call for help after 10ms
983233cdbdSTejun Heo 						   (min two ticks) */
99e22bee78STejun Heo 	MAYDAY_INTERVAL		= HZ / 10,	/* and then every 100ms */
100e22bee78STejun Heo 	CREATE_COOLDOWN		= HZ,		/* time to breath after fail */
1011da177e4SLinus Torvalds 
1021da177e4SLinus Torvalds 	/*
103e22bee78STejun Heo 	 * Rescue workers are used only on emergencies and shared by
1048698a745SDongsheng Yang 	 * all cpus.  Give MIN_NICE.
105e22bee78STejun Heo 	 */
1068698a745SDongsheng Yang 	RESCUER_NICE_LEVEL	= MIN_NICE,
1078698a745SDongsheng Yang 	HIGHPRI_NICE_LEVEL	= MIN_NICE,
108ecf6881fSTejun Heo 
109ecf6881fSTejun Heo 	WQ_NAME_LEN		= 24,
110c8e55f36STejun Heo };
111c8e55f36STejun Heo 
1121da177e4SLinus Torvalds /*
1134690c4abSTejun Heo  * Structure fields follow one of the following exclusion rules.
1144690c4abSTejun Heo  *
115e41e704bSTejun Heo  * I: Modifiable by initialization/destruction paths and read-only for
116e41e704bSTejun Heo  *    everyone else.
1174690c4abSTejun Heo  *
118e22bee78STejun Heo  * P: Preemption protected.  Disabling preemption is enough and should
119e22bee78STejun Heo  *    only be modified and accessed from the local cpu.
120e22bee78STejun Heo  *
121d565ed63STejun Heo  * L: pool->lock protected.  Access with pool->lock held.
1224690c4abSTejun Heo  *
123d565ed63STejun Heo  * X: During normal operation, modification requires pool->lock and should
124d565ed63STejun Heo  *    be done only from local cpu.  Either disabling preemption on local
125d565ed63STejun Heo  *    cpu or grabbing pool->lock is enough for read access.  If
126d565ed63STejun Heo  *    POOL_DISASSOCIATED is set, it's identical to L.
127e22bee78STejun Heo  *
1281258fae7STejun Heo  * A: wq_pool_attach_mutex protected.
129822d8405STejun Heo  *
13068e13a67SLai Jiangshan  * PL: wq_pool_mutex protected.
13176af4d93STejun Heo  *
13224acfb71SThomas Gleixner  * PR: wq_pool_mutex protected for writes.  RCU protected for reads.
1335bcab335STejun Heo  *
1345b95e1afSLai Jiangshan  * PW: wq_pool_mutex and wq->mutex protected for writes.  Either for reads.
1355b95e1afSLai Jiangshan  *
1365b95e1afSLai Jiangshan  * PWR: wq_pool_mutex and wq->mutex protected for writes.  Either or
13724acfb71SThomas Gleixner  *      RCU for reads.
1385b95e1afSLai Jiangshan  *
1393c25a55dSLai Jiangshan  * WQ: wq->mutex protected.
1403c25a55dSLai Jiangshan  *
14124acfb71SThomas Gleixner  * WR: wq->mutex protected for writes.  RCU protected for reads.
1422e109a28STejun Heo  *
1432e109a28STejun Heo  * MD: wq_mayday_lock protected.
1444690c4abSTejun Heo  */
1454690c4abSTejun Heo 
1462eaebdb3STejun Heo /* struct worker is defined in workqueue_internal.h */
147c34056a3STejun Heo 
148bd7bdd43STejun Heo struct worker_pool {
149a9b8a985SSebastian Andrzej Siewior 	raw_spinlock_t		lock;		/* the pool lock */
150d84ff051STejun Heo 	int			cpu;		/* I: the associated cpu */
151f3f90ad4STejun Heo 	int			node;		/* I: the associated node ID */
1529daf9e67STejun Heo 	int			id;		/* I: pool ID */
15311ebea50STejun Heo 	unsigned int		flags;		/* X: flags */
154bd7bdd43STejun Heo 
15582607adcSTejun Heo 	unsigned long		watchdog_ts;	/* L: watchdog timestamp */
15682607adcSTejun Heo 
157bd7bdd43STejun Heo 	struct list_head	worklist;	/* L: list of pending works */
158ea1abd61SLai Jiangshan 
1595826cc8fSLai Jiangshan 	int			nr_workers;	/* L: total number of workers */
1605826cc8fSLai Jiangshan 	int			nr_idle;	/* L: currently idle workers */
161bd7bdd43STejun Heo 
162bd7bdd43STejun Heo 	struct list_head	idle_list;	/* X: list of idle workers */
163bd7bdd43STejun Heo 	struct timer_list	idle_timer;	/* L: worker idle timeout */
164bd7bdd43STejun Heo 	struct timer_list	mayday_timer;	/* L: SOS timer for workers */
165bd7bdd43STejun Heo 
166c5aa87bbSTejun Heo 	/* a workers is either on busy_hash or idle_list, or the manager */
167c9e7cf27STejun Heo 	DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
168c9e7cf27STejun Heo 						/* L: hash of busy workers */
169c9e7cf27STejun Heo 
1702607d7a6STejun Heo 	struct worker		*manager;	/* L: purely informational */
17192f9c5c4SLai Jiangshan 	struct list_head	workers;	/* A: attached workers */
17260f5a4bcSLai Jiangshan 	struct completion	*detach_completion; /* all workers detached */
173e19e397aSTejun Heo 
1747cda9aaeSLai Jiangshan 	struct ida		worker_ida;	/* worker IDs for task name */
175e19e397aSTejun Heo 
1767a4e344cSTejun Heo 	struct workqueue_attrs	*attrs;		/* I: worker attributes */
17768e13a67SLai Jiangshan 	struct hlist_node	hash_node;	/* PL: unbound_pool_hash node */
17868e13a67SLai Jiangshan 	int			refcnt;		/* PL: refcnt for unbound pools */
1797a4e344cSTejun Heo 
180e19e397aSTejun Heo 	/*
181e19e397aSTejun Heo 	 * The current concurrency level.  As it's likely to be accessed
182e19e397aSTejun Heo 	 * from other CPUs during try_to_wake_up(), put it in a separate
183e19e397aSTejun Heo 	 * cacheline.
184e19e397aSTejun Heo 	 */
185e19e397aSTejun Heo 	atomic_t		nr_running ____cacheline_aligned_in_smp;
18629c91e99STejun Heo 
18729c91e99STejun Heo 	/*
18824acfb71SThomas Gleixner 	 * Destruction of pool is RCU protected to allow dereferences
18929c91e99STejun Heo 	 * from get_work_pool().
19029c91e99STejun Heo 	 */
19129c91e99STejun Heo 	struct rcu_head		rcu;
1928b03ae3cSTejun Heo } ____cacheline_aligned_in_smp;
1938b03ae3cSTejun Heo 
1948b03ae3cSTejun Heo /*
195112202d9STejun Heo  * The per-pool workqueue.  While queued, the lower WORK_STRUCT_FLAG_BITS
196112202d9STejun Heo  * of work_struct->data are used for flags and the remaining high bits
197112202d9STejun Heo  * point to the pwq; thus, pwqs need to be aligned at two's power of the
198112202d9STejun Heo  * number of flag bits.
1991da177e4SLinus Torvalds  */
200112202d9STejun Heo struct pool_workqueue {
201bd7bdd43STejun Heo 	struct worker_pool	*pool;		/* I: the associated pool */
2024690c4abSTejun Heo 	struct workqueue_struct *wq;		/* I: the owning workqueue */
20373f53c4aSTejun Heo 	int			work_color;	/* L: current color */
20473f53c4aSTejun Heo 	int			flush_color;	/* L: flushing color */
2058864b4e5STejun Heo 	int			refcnt;		/* L: reference count */
20673f53c4aSTejun Heo 	int			nr_in_flight[WORK_NR_COLORS];
20773f53c4aSTejun Heo 						/* L: nr of in_flight works */
208018f3a13SLai Jiangshan 
209018f3a13SLai Jiangshan 	/*
210018f3a13SLai Jiangshan 	 * nr_active management and WORK_STRUCT_INACTIVE:
211018f3a13SLai Jiangshan 	 *
212018f3a13SLai Jiangshan 	 * When pwq->nr_active >= max_active, new work item is queued to
213018f3a13SLai Jiangshan 	 * pwq->inactive_works instead of pool->worklist and marked with
214018f3a13SLai Jiangshan 	 * WORK_STRUCT_INACTIVE.
215018f3a13SLai Jiangshan 	 *
216018f3a13SLai Jiangshan 	 * All work items marked with WORK_STRUCT_INACTIVE do not participate
217018f3a13SLai Jiangshan 	 * in pwq->nr_active and all work items in pwq->inactive_works are
218018f3a13SLai Jiangshan 	 * marked with WORK_STRUCT_INACTIVE.  But not all WORK_STRUCT_INACTIVE
219018f3a13SLai Jiangshan 	 * work items are in pwq->inactive_works.  Some of them are ready to
220018f3a13SLai Jiangshan 	 * run in pool->worklist or worker->scheduled.  Those work itmes are
221018f3a13SLai Jiangshan 	 * only struct wq_barrier which is used for flush_work() and should
222018f3a13SLai Jiangshan 	 * not participate in pwq->nr_active.  For non-barrier work item, it
223018f3a13SLai Jiangshan 	 * is marked with WORK_STRUCT_INACTIVE iff it is in pwq->inactive_works.
224018f3a13SLai Jiangshan 	 */
2251e19ffc6STejun Heo 	int			nr_active;	/* L: nr of active works */
226a0a1a5fdSTejun Heo 	int			max_active;	/* L: max active works */
227f97a4a1aSLai Jiangshan 	struct list_head	inactive_works;	/* L: inactive works */
2283c25a55dSLai Jiangshan 	struct list_head	pwqs_node;	/* WR: node on wq->pwqs */
2292e109a28STejun Heo 	struct list_head	mayday_node;	/* MD: node on wq->maydays */
2308864b4e5STejun Heo 
2318864b4e5STejun Heo 	/*
2328864b4e5STejun Heo 	 * Release of unbound pwq is punted to system_wq.  See put_pwq()
2338864b4e5STejun Heo 	 * and pwq_unbound_release_workfn() for details.  pool_workqueue
23424acfb71SThomas Gleixner 	 * itself is also RCU protected so that the first pwq can be
235b09f4fd3SLai Jiangshan 	 * determined without grabbing wq->mutex.
2368864b4e5STejun Heo 	 */
2378864b4e5STejun Heo 	struct work_struct	unbound_release_work;
2388864b4e5STejun Heo 	struct rcu_head		rcu;
239e904e6c2STejun Heo } __aligned(1 << WORK_STRUCT_FLAG_BITS);
2401da177e4SLinus Torvalds 
2411da177e4SLinus Torvalds /*
24273f53c4aSTejun Heo  * Structure used to wait for workqueue flush.
24373f53c4aSTejun Heo  */
24473f53c4aSTejun Heo struct wq_flusher {
2453c25a55dSLai Jiangshan 	struct list_head	list;		/* WQ: list of flushers */
2463c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: flush color waiting for */
24773f53c4aSTejun Heo 	struct completion	done;		/* flush completion */
24873f53c4aSTejun Heo };
2491da177e4SLinus Torvalds 
250226223abSTejun Heo struct wq_device;
251226223abSTejun Heo 
25273f53c4aSTejun Heo /*
253c5aa87bbSTejun Heo  * The externally visible workqueue.  It relays the issued work items to
254c5aa87bbSTejun Heo  * the appropriate worker_pool through its pool_workqueues.
2551da177e4SLinus Torvalds  */
2561da177e4SLinus Torvalds struct workqueue_struct {
2573c25a55dSLai Jiangshan 	struct list_head	pwqs;		/* WR: all pwqs of this wq */
258e2dca7adSTejun Heo 	struct list_head	list;		/* PR: list of all workqueues */
25973f53c4aSTejun Heo 
2603c25a55dSLai Jiangshan 	struct mutex		mutex;		/* protects this wq */
2613c25a55dSLai Jiangshan 	int			work_color;	/* WQ: current work color */
2623c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: current flush color */
263112202d9STejun Heo 	atomic_t		nr_pwqs_to_flush; /* flush in progress */
2643c25a55dSLai Jiangshan 	struct wq_flusher	*first_flusher;	/* WQ: first flusher */
2653c25a55dSLai Jiangshan 	struct list_head	flusher_queue;	/* WQ: flush waiters */
2663c25a55dSLai Jiangshan 	struct list_head	flusher_overflow; /* WQ: flush overflow list */
26773f53c4aSTejun Heo 
2682e109a28STejun Heo 	struct list_head	maydays;	/* MD: pwqs requesting rescue */
26930ae2fc0STejun Heo 	struct worker		*rescuer;	/* MD: rescue worker */
270e22bee78STejun Heo 
27187fc741eSLai Jiangshan 	int			nr_drainers;	/* WQ: drain in progress */
272a357fc03SLai Jiangshan 	int			saved_max_active; /* WQ: saved pwq max_active */
273226223abSTejun Heo 
2745b95e1afSLai Jiangshan 	struct workqueue_attrs	*unbound_attrs;	/* PW: only for unbound wqs */
2755b95e1afSLai Jiangshan 	struct pool_workqueue	*dfl_pwq;	/* PW: only for unbound wqs */
2766029a918STejun Heo 
277226223abSTejun Heo #ifdef CONFIG_SYSFS
278226223abSTejun Heo 	struct wq_device	*wq_dev;	/* I: for sysfs interface */
279226223abSTejun Heo #endif
2804e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
281669de8bdSBart Van Assche 	char			*lock_name;
282669de8bdSBart Van Assche 	struct lock_class_key	key;
2834e6045f1SJohannes Berg 	struct lockdep_map	lockdep_map;
2844e6045f1SJohannes Berg #endif
285ecf6881fSTejun Heo 	char			name[WQ_NAME_LEN]; /* I: workqueue name */
2862728fd2fSTejun Heo 
287e2dca7adSTejun Heo 	/*
28824acfb71SThomas Gleixner 	 * Destruction of workqueue_struct is RCU protected to allow walking
28924acfb71SThomas Gleixner 	 * the workqueues list without grabbing wq_pool_mutex.
290e2dca7adSTejun Heo 	 * This is used to dump all workqueues from sysrq.
291e2dca7adSTejun Heo 	 */
292e2dca7adSTejun Heo 	struct rcu_head		rcu;
293e2dca7adSTejun Heo 
2942728fd2fSTejun Heo 	/* hot fields used during command issue, aligned to cacheline */
2952728fd2fSTejun Heo 	unsigned int		flags ____cacheline_aligned; /* WQ: WQ_* flags */
2962728fd2fSTejun Heo 	struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */
2975b95e1afSLai Jiangshan 	struct pool_workqueue __rcu *numa_pwq_tbl[]; /* PWR: unbound pwqs indexed by node */
2981da177e4SLinus Torvalds };
2991da177e4SLinus Torvalds 
300e904e6c2STejun Heo static struct kmem_cache *pwq_cache;
301e904e6c2STejun Heo 
302bce90380STejun Heo static cpumask_var_t *wq_numa_possible_cpumask;
303bce90380STejun Heo 					/* possible CPUs of each node */
304bce90380STejun Heo 
305d55262c4STejun Heo static bool wq_disable_numa;
306d55262c4STejun Heo module_param_named(disable_numa, wq_disable_numa, bool, 0444);
307d55262c4STejun Heo 
308cee22a15SViresh Kumar /* see the comment above the definition of WQ_POWER_EFFICIENT */
309552f530cSLuis R. Rodriguez static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
310cee22a15SViresh Kumar module_param_named(power_efficient, wq_power_efficient, bool, 0444);
311cee22a15SViresh Kumar 
312863b710bSTejun Heo static bool wq_online;			/* can kworkers be created yet? */
3133347fa09STejun Heo 
314bce90380STejun Heo static bool wq_numa_enabled;		/* unbound NUMA affinity enabled */
315bce90380STejun Heo 
3164c16bd32STejun Heo /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
3174c16bd32STejun Heo static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf;
3184c16bd32STejun Heo 
31968e13a67SLai Jiangshan static DEFINE_MUTEX(wq_pool_mutex);	/* protects pools and workqueues list */
3201258fae7STejun Heo static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
321a9b8a985SSebastian Andrzej Siewior static DEFINE_RAW_SPINLOCK(wq_mayday_lock);	/* protects wq->maydays list */
322d8bb65abSSebastian Andrzej Siewior /* wait for manager to go away */
323d8bb65abSSebastian Andrzej Siewior static struct rcuwait manager_wait = __RCUWAIT_INITIALIZER(manager_wait);
3245bcab335STejun Heo 
325e2dca7adSTejun Heo static LIST_HEAD(workqueues);		/* PR: list of all workqueues */
32668e13a67SLai Jiangshan static bool workqueue_freezing;		/* PL: have wqs started freezing? */
3277d19c5ceSTejun Heo 
328ef557180SMike Galbraith /* PL: allowable cpus for unbound wqs and work items */
329ef557180SMike Galbraith static cpumask_var_t wq_unbound_cpumask;
330ef557180SMike Galbraith 
331ef557180SMike Galbraith /* CPU where unbound work was last round robin scheduled from this CPU */
332ef557180SMike Galbraith static DEFINE_PER_CPU(int, wq_rr_cpu_last);
333b05a7928SFrederic Weisbecker 
334f303fccbSTejun Heo /*
335f303fccbSTejun Heo  * Local execution of unbound work items is no longer guaranteed.  The
336f303fccbSTejun Heo  * following always forces round-robin CPU selection on unbound work items
337f303fccbSTejun Heo  * to uncover usages which depend on it.
338f303fccbSTejun Heo  */
339f303fccbSTejun Heo #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
340f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = true;
341f303fccbSTejun Heo #else
342f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = false;
343f303fccbSTejun Heo #endif
344f303fccbSTejun Heo module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
345f303fccbSTejun Heo 
3467d19c5ceSTejun Heo /* the per-cpu worker pools */
34725528213SPeter Zijlstra static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools);
3487d19c5ceSTejun Heo 
34968e13a67SLai Jiangshan static DEFINE_IDR(worker_pool_idr);	/* PR: idr of all pools */
3507d19c5ceSTejun Heo 
35168e13a67SLai Jiangshan /* PL: hash of all unbound pools keyed by pool->attrs */
35229c91e99STejun Heo static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
35329c91e99STejun Heo 
354c5aa87bbSTejun Heo /* I: attributes used when instantiating standard unbound pools on demand */
35529c91e99STejun Heo static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
35629c91e99STejun Heo 
3578a2b7538STejun Heo /* I: attributes used when instantiating ordered pools on demand */
3588a2b7538STejun Heo static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
3598a2b7538STejun Heo 
360d320c038STejun Heo struct workqueue_struct *system_wq __read_mostly;
361ad7b1f84SMarc Dionne EXPORT_SYMBOL(system_wq);
362044c782cSValentin Ilie struct workqueue_struct *system_highpri_wq __read_mostly;
3631aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
364044c782cSValentin Ilie struct workqueue_struct *system_long_wq __read_mostly;
365d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
366044c782cSValentin Ilie struct workqueue_struct *system_unbound_wq __read_mostly;
367f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
368044c782cSValentin Ilie struct workqueue_struct *system_freezable_wq __read_mostly;
36924d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
3700668106cSViresh Kumar struct workqueue_struct *system_power_efficient_wq __read_mostly;
3710668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_power_efficient_wq);
3720668106cSViresh Kumar struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
3730668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
374d320c038STejun Heo 
3757d19c5ceSTejun Heo static int worker_thread(void *__worker);
3766ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
377c29eb853STejun Heo static void show_pwq(struct pool_workqueue *pwq);
37855df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool);
3797d19c5ceSTejun Heo 
38097bd2347STejun Heo #define CREATE_TRACE_POINTS
38197bd2347STejun Heo #include <trace/events/workqueue.h>
38297bd2347STejun Heo 
38368e13a67SLai Jiangshan #define assert_rcu_or_pool_mutex()					\
38424acfb71SThomas Gleixner 	RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&			\
385f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
38624acfb71SThomas Gleixner 			 "RCU or wq_pool_mutex should be held")
3875bcab335STejun Heo 
3885b95e1afSLai Jiangshan #define assert_rcu_or_wq_mutex_or_pool_mutex(wq)			\
38924acfb71SThomas Gleixner 	RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&			\
390f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq->mutex) &&		\
391f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
39224acfb71SThomas Gleixner 			 "RCU, wq->mutex or wq_pool_mutex should be held")
3935b95e1afSLai Jiangshan 
394f02ae73aSTejun Heo #define for_each_cpu_worker_pool(pool, cpu)				\
395f02ae73aSTejun Heo 	for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0];		\
396f02ae73aSTejun Heo 	     (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
3977a62c2c8STejun Heo 	     (pool)++)
3984ce62e9eSTejun Heo 
39949e3cf44STejun Heo /**
40017116969STejun Heo  * for_each_pool - iterate through all worker_pools in the system
40117116969STejun Heo  * @pool: iteration cursor
402611c92a0STejun Heo  * @pi: integer used for iteration
403fa1b54e6STejun Heo  *
40424acfb71SThomas Gleixner  * This must be called either with wq_pool_mutex held or RCU read
40568e13a67SLai Jiangshan  * locked.  If the pool needs to be used beyond the locking in effect, the
40668e13a67SLai Jiangshan  * caller is responsible for guaranteeing that the pool stays online.
407fa1b54e6STejun Heo  *
408fa1b54e6STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
409fa1b54e6STejun Heo  * ignored.
41017116969STejun Heo  */
411611c92a0STejun Heo #define for_each_pool(pool, pi)						\
412611c92a0STejun Heo 	idr_for_each_entry(&worker_pool_idr, pool, pi)			\
41368e13a67SLai Jiangshan 		if (({ assert_rcu_or_pool_mutex(); false; })) { }	\
414fa1b54e6STejun Heo 		else
41517116969STejun Heo 
41617116969STejun Heo /**
417822d8405STejun Heo  * for_each_pool_worker - iterate through all workers of a worker_pool
418822d8405STejun Heo  * @worker: iteration cursor
419822d8405STejun Heo  * @pool: worker_pool to iterate workers of
420822d8405STejun Heo  *
4211258fae7STejun Heo  * This must be called with wq_pool_attach_mutex.
422822d8405STejun Heo  *
423822d8405STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
424822d8405STejun Heo  * ignored.
425822d8405STejun Heo  */
426da028469SLai Jiangshan #define for_each_pool_worker(worker, pool)				\
427da028469SLai Jiangshan 	list_for_each_entry((worker), &(pool)->workers, node)		\
4281258fae7STejun Heo 		if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
429822d8405STejun Heo 		else
430822d8405STejun Heo 
431822d8405STejun Heo /**
43249e3cf44STejun Heo  * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
43349e3cf44STejun Heo  * @pwq: iteration cursor
43449e3cf44STejun Heo  * @wq: the target workqueue
43576af4d93STejun Heo  *
43624acfb71SThomas Gleixner  * This must be called either with wq->mutex held or RCU read locked.
437794b18bcSTejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
438794b18bcSTejun Heo  * responsible for guaranteeing that the pwq stays online.
43976af4d93STejun Heo  *
44076af4d93STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
44176af4d93STejun Heo  * ignored.
44249e3cf44STejun Heo  */
44349e3cf44STejun Heo #define for_each_pwq(pwq, wq)						\
44449e9d1a9SSebastian Andrzej Siewior 	list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node,		\
4455a644662SJoel Fernandes (Google) 				 lockdep_is_held(&(wq->mutex)))
446f3421797STejun Heo 
447dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
448dc186ad7SThomas Gleixner 
449f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr;
450dc186ad7SThomas Gleixner 
45199777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
45299777288SStanislaw Gruszka {
45399777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
45499777288SStanislaw Gruszka }
45599777288SStanislaw Gruszka 
456b9fdac7fSDu, Changbin static bool work_is_static_object(void *addr)
457b9fdac7fSDu, Changbin {
458b9fdac7fSDu, Changbin 	struct work_struct *work = addr;
459b9fdac7fSDu, Changbin 
460b9fdac7fSDu, Changbin 	return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
461b9fdac7fSDu, Changbin }
462b9fdac7fSDu, Changbin 
463dc186ad7SThomas Gleixner /*
464dc186ad7SThomas Gleixner  * fixup_init is called when:
465dc186ad7SThomas Gleixner  * - an active object is initialized
466dc186ad7SThomas Gleixner  */
46702a982a6SDu, Changbin static bool work_fixup_init(void *addr, enum debug_obj_state state)
468dc186ad7SThomas Gleixner {
469dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
470dc186ad7SThomas Gleixner 
471dc186ad7SThomas Gleixner 	switch (state) {
472dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
473dc186ad7SThomas Gleixner 		cancel_work_sync(work);
474dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
47502a982a6SDu, Changbin 		return true;
476dc186ad7SThomas Gleixner 	default:
47702a982a6SDu, Changbin 		return false;
478dc186ad7SThomas Gleixner 	}
479dc186ad7SThomas Gleixner }
480dc186ad7SThomas Gleixner 
481dc186ad7SThomas Gleixner /*
482dc186ad7SThomas Gleixner  * fixup_free is called when:
483dc186ad7SThomas Gleixner  * - an active object is freed
484dc186ad7SThomas Gleixner  */
48502a982a6SDu, Changbin static bool work_fixup_free(void *addr, enum debug_obj_state state)
486dc186ad7SThomas Gleixner {
487dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
488dc186ad7SThomas Gleixner 
489dc186ad7SThomas Gleixner 	switch (state) {
490dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
491dc186ad7SThomas Gleixner 		cancel_work_sync(work);
492dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
49302a982a6SDu, Changbin 		return true;
494dc186ad7SThomas Gleixner 	default:
49502a982a6SDu, Changbin 		return false;
496dc186ad7SThomas Gleixner 	}
497dc186ad7SThomas Gleixner }
498dc186ad7SThomas Gleixner 
499f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr = {
500dc186ad7SThomas Gleixner 	.name		= "work_struct",
50199777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
502b9fdac7fSDu, Changbin 	.is_static_object = work_is_static_object,
503dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
504dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
505dc186ad7SThomas Gleixner };
506dc186ad7SThomas Gleixner 
507dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
508dc186ad7SThomas Gleixner {
509dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
510dc186ad7SThomas Gleixner }
511dc186ad7SThomas Gleixner 
512dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
513dc186ad7SThomas Gleixner {
514dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
515dc186ad7SThomas Gleixner }
516dc186ad7SThomas Gleixner 
517dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
518dc186ad7SThomas Gleixner {
519dc186ad7SThomas Gleixner 	if (onstack)
520dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
521dc186ad7SThomas Gleixner 	else
522dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
523dc186ad7SThomas Gleixner }
524dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
525dc186ad7SThomas Gleixner 
526dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
527dc186ad7SThomas Gleixner {
528dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
529dc186ad7SThomas Gleixner }
530dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
531dc186ad7SThomas Gleixner 
532ea2e64f2SThomas Gleixner void destroy_delayed_work_on_stack(struct delayed_work *work)
533ea2e64f2SThomas Gleixner {
534ea2e64f2SThomas Gleixner 	destroy_timer_on_stack(&work->timer);
535ea2e64f2SThomas Gleixner 	debug_object_free(&work->work, &work_debug_descr);
536ea2e64f2SThomas Gleixner }
537ea2e64f2SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
538ea2e64f2SThomas Gleixner 
539dc186ad7SThomas Gleixner #else
540dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
541dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
542dc186ad7SThomas Gleixner #endif
543dc186ad7SThomas Gleixner 
5444e8b22bdSLi Bin /**
54567dc8325SCai Huoqing  * worker_pool_assign_id - allocate ID and assign it to @pool
5464e8b22bdSLi Bin  * @pool: the pool pointer of interest
5474e8b22bdSLi Bin  *
5484e8b22bdSLi Bin  * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
5494e8b22bdSLi Bin  * successfully, -errno on failure.
5504e8b22bdSLi Bin  */
5519daf9e67STejun Heo static int worker_pool_assign_id(struct worker_pool *pool)
5529daf9e67STejun Heo {
5539daf9e67STejun Heo 	int ret;
5549daf9e67STejun Heo 
55568e13a67SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5565bcab335STejun Heo 
5574e8b22bdSLi Bin 	ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
5584e8b22bdSLi Bin 			GFP_KERNEL);
559229641a6STejun Heo 	if (ret >= 0) {
560e68035fbSTejun Heo 		pool->id = ret;
561229641a6STejun Heo 		return 0;
562229641a6STejun Heo 	}
5639daf9e67STejun Heo 	return ret;
5649daf9e67STejun Heo }
5659daf9e67STejun Heo 
56676af4d93STejun Heo /**
567df2d5ae4STejun Heo  * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
568df2d5ae4STejun Heo  * @wq: the target workqueue
569df2d5ae4STejun Heo  * @node: the node ID
570df2d5ae4STejun Heo  *
57124acfb71SThomas Gleixner  * This must be called with any of wq_pool_mutex, wq->mutex or RCU
5725b95e1afSLai Jiangshan  * read locked.
573df2d5ae4STejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
574df2d5ae4STejun Heo  * responsible for guaranteeing that the pwq stays online.
575d185af30SYacine Belkadi  *
576d185af30SYacine Belkadi  * Return: The unbound pool_workqueue for @node.
577df2d5ae4STejun Heo  */
578df2d5ae4STejun Heo static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
579df2d5ae4STejun Heo 						  int node)
580df2d5ae4STejun Heo {
5815b95e1afSLai Jiangshan 	assert_rcu_or_wq_mutex_or_pool_mutex(wq);
582d6e022f1STejun Heo 
583d6e022f1STejun Heo 	/*
584d6e022f1STejun Heo 	 * XXX: @node can be NUMA_NO_NODE if CPU goes offline while a
585d6e022f1STejun Heo 	 * delayed item is pending.  The plan is to keep CPU -> NODE
586d6e022f1STejun Heo 	 * mapping valid and stable across CPU on/offlines.  Once that
587d6e022f1STejun Heo 	 * happens, this workaround can be removed.
588d6e022f1STejun Heo 	 */
589d6e022f1STejun Heo 	if (unlikely(node == NUMA_NO_NODE))
590d6e022f1STejun Heo 		return wq->dfl_pwq;
591d6e022f1STejun Heo 
592df2d5ae4STejun Heo 	return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
593df2d5ae4STejun Heo }
594df2d5ae4STejun Heo 
59573f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
59673f53c4aSTejun Heo {
59773f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
59873f53c4aSTejun Heo }
59973f53c4aSTejun Heo 
600c4560c2cSLai Jiangshan static int get_work_color(unsigned long work_data)
60173f53c4aSTejun Heo {
602c4560c2cSLai Jiangshan 	return (work_data >> WORK_STRUCT_COLOR_SHIFT) &
60373f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
60473f53c4aSTejun Heo }
60573f53c4aSTejun Heo 
60673f53c4aSTejun Heo static int work_next_color(int color)
60773f53c4aSTejun Heo {
60873f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
609a848e3b6SOleg Nesterov }
610a848e3b6SOleg Nesterov 
6114594bf15SDavid Howells /*
612112202d9STejun Heo  * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
613112202d9STejun Heo  * contain the pointer to the queued pwq.  Once execution starts, the flag
6147c3eed5cSTejun Heo  * is cleared and the high bits contain OFFQ flags and pool ID.
6157a22ad75STejun Heo  *
616112202d9STejun Heo  * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
617112202d9STejun Heo  * and clear_work_data() can be used to set the pwq, pool or clear
618bbb68dfaSTejun Heo  * work->data.  These functions should only be called while the work is
619bbb68dfaSTejun Heo  * owned - ie. while the PENDING bit is set.
6207a22ad75STejun Heo  *
621112202d9STejun Heo  * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
6227c3eed5cSTejun Heo  * corresponding to a work.  Pool is available once the work has been
623112202d9STejun Heo  * queued anywhere after initialization until it is sync canceled.  pwq is
6247c3eed5cSTejun Heo  * available only while the work item is queued.
625bbb68dfaSTejun Heo  *
626bbb68dfaSTejun Heo  * %WORK_OFFQ_CANCELING is used to mark a work item which is being
627bbb68dfaSTejun Heo  * canceled.  While being canceled, a work item may have its PENDING set
628bbb68dfaSTejun Heo  * but stay off timer and worklist for arbitrarily long and nobody should
629bbb68dfaSTejun Heo  * try to steal the PENDING bit.
6304594bf15SDavid Howells  */
6317a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
6327a22ad75STejun Heo 				 unsigned long flags)
6337a22ad75STejun Heo {
6346183c009STejun Heo 	WARN_ON_ONCE(!work_pending(work));
6357a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
6367a22ad75STejun Heo }
6377a22ad75STejun Heo 
638112202d9STejun Heo static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
6394690c4abSTejun Heo 			 unsigned long extra_flags)
640365970a1SDavid Howells {
641112202d9STejun Heo 	set_work_data(work, (unsigned long)pwq,
642112202d9STejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
643365970a1SDavid Howells }
644365970a1SDavid Howells 
6454468a00fSLai Jiangshan static void set_work_pool_and_keep_pending(struct work_struct *work,
6464468a00fSLai Jiangshan 					   int pool_id)
6474468a00fSLai Jiangshan {
6484468a00fSLai Jiangshan 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
6494468a00fSLai Jiangshan 		      WORK_STRUCT_PENDING);
6504468a00fSLai Jiangshan }
6514468a00fSLai Jiangshan 
6527c3eed5cSTejun Heo static void set_work_pool_and_clear_pending(struct work_struct *work,
6537c3eed5cSTejun Heo 					    int pool_id)
6544d707b9fSOleg Nesterov {
65523657bb1STejun Heo 	/*
65623657bb1STejun Heo 	 * The following wmb is paired with the implied mb in
65723657bb1STejun Heo 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
65823657bb1STejun Heo 	 * here are visible to and precede any updates by the next PENDING
65923657bb1STejun Heo 	 * owner.
66023657bb1STejun Heo 	 */
66123657bb1STejun Heo 	smp_wmb();
6627c3eed5cSTejun Heo 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
663346c09f8SRoman Pen 	/*
664346c09f8SRoman Pen 	 * The following mb guarantees that previous clear of a PENDING bit
665346c09f8SRoman Pen 	 * will not be reordered with any speculative LOADS or STORES from
666346c09f8SRoman Pen 	 * work->current_func, which is executed afterwards.  This possible
6678bdc6201SLiu Song 	 * reordering can lead to a missed execution on attempt to queue
668346c09f8SRoman Pen 	 * the same @work.  E.g. consider this case:
669346c09f8SRoman Pen 	 *
670346c09f8SRoman Pen 	 *   CPU#0                         CPU#1
671346c09f8SRoman Pen 	 *   ----------------------------  --------------------------------
672346c09f8SRoman Pen 	 *
673346c09f8SRoman Pen 	 * 1  STORE event_indicated
674346c09f8SRoman Pen 	 * 2  queue_work_on() {
675346c09f8SRoman Pen 	 * 3    test_and_set_bit(PENDING)
676346c09f8SRoman Pen 	 * 4 }                             set_..._and_clear_pending() {
677346c09f8SRoman Pen 	 * 5                                 set_work_data() # clear bit
678346c09f8SRoman Pen 	 * 6                                 smp_mb()
679346c09f8SRoman Pen 	 * 7                               work->current_func() {
680346c09f8SRoman Pen 	 * 8				      LOAD event_indicated
681346c09f8SRoman Pen 	 *				   }
682346c09f8SRoman Pen 	 *
683346c09f8SRoman Pen 	 * Without an explicit full barrier speculative LOAD on line 8 can
684346c09f8SRoman Pen 	 * be executed before CPU#0 does STORE on line 1.  If that happens,
685346c09f8SRoman Pen 	 * CPU#0 observes the PENDING bit is still set and new execution of
686346c09f8SRoman Pen 	 * a @work is not queued in a hope, that CPU#1 will eventually
687346c09f8SRoman Pen 	 * finish the queued @work.  Meanwhile CPU#1 does not see
688346c09f8SRoman Pen 	 * event_indicated is set, because speculative LOAD was executed
689346c09f8SRoman Pen 	 * before actual STORE.
690346c09f8SRoman Pen 	 */
691346c09f8SRoman Pen 	smp_mb();
6924d707b9fSOleg Nesterov }
6934d707b9fSOleg Nesterov 
6947a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
695365970a1SDavid Howells {
6967c3eed5cSTejun Heo 	smp_wmb();	/* see set_work_pool_and_clear_pending() */
6977c3eed5cSTejun Heo 	set_work_data(work, WORK_STRUCT_NO_POOL, 0);
6987a22ad75STejun Heo }
6997a22ad75STejun Heo 
700112202d9STejun Heo static struct pool_workqueue *get_work_pwq(struct work_struct *work)
7017a22ad75STejun Heo {
702e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
7037a22ad75STejun Heo 
704112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
705e120153dSTejun Heo 		return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
706e120153dSTejun Heo 	else
707e120153dSTejun Heo 		return NULL;
7087a22ad75STejun Heo }
7097a22ad75STejun Heo 
7107c3eed5cSTejun Heo /**
7117c3eed5cSTejun Heo  * get_work_pool - return the worker_pool a given work was associated with
7127c3eed5cSTejun Heo  * @work: the work item of interest
7137c3eed5cSTejun Heo  *
71468e13a67SLai Jiangshan  * Pools are created and destroyed under wq_pool_mutex, and allows read
71524acfb71SThomas Gleixner  * access under RCU read lock.  As such, this function should be
71624acfb71SThomas Gleixner  * called under wq_pool_mutex or inside of a rcu_read_lock() region.
717fa1b54e6STejun Heo  *
718fa1b54e6STejun Heo  * All fields of the returned pool are accessible as long as the above
719fa1b54e6STejun Heo  * mentioned locking is in effect.  If the returned pool needs to be used
720fa1b54e6STejun Heo  * beyond the critical section, the caller is responsible for ensuring the
721fa1b54e6STejun Heo  * returned pool is and stays online.
722d185af30SYacine Belkadi  *
723d185af30SYacine Belkadi  * Return: The worker_pool @work was last associated with.  %NULL if none.
7247c3eed5cSTejun Heo  */
7257c3eed5cSTejun Heo static struct worker_pool *get_work_pool(struct work_struct *work)
7267a22ad75STejun Heo {
727e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
7287c3eed5cSTejun Heo 	int pool_id;
7297a22ad75STejun Heo 
73068e13a67SLai Jiangshan 	assert_rcu_or_pool_mutex();
731fa1b54e6STejun Heo 
732112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
733112202d9STejun Heo 		return ((struct pool_workqueue *)
7347c3eed5cSTejun Heo 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool;
7357a22ad75STejun Heo 
7367c3eed5cSTejun Heo 	pool_id = data >> WORK_OFFQ_POOL_SHIFT;
7377c3eed5cSTejun Heo 	if (pool_id == WORK_OFFQ_POOL_NONE)
7387a22ad75STejun Heo 		return NULL;
7397a22ad75STejun Heo 
740fa1b54e6STejun Heo 	return idr_find(&worker_pool_idr, pool_id);
7417c3eed5cSTejun Heo }
7427c3eed5cSTejun Heo 
7437c3eed5cSTejun Heo /**
7447c3eed5cSTejun Heo  * get_work_pool_id - return the worker pool ID a given work is associated with
7457c3eed5cSTejun Heo  * @work: the work item of interest
7467c3eed5cSTejun Heo  *
747d185af30SYacine Belkadi  * Return: The worker_pool ID @work was last associated with.
7487c3eed5cSTejun Heo  * %WORK_OFFQ_POOL_NONE if none.
7497c3eed5cSTejun Heo  */
7507c3eed5cSTejun Heo static int get_work_pool_id(struct work_struct *work)
7517c3eed5cSTejun Heo {
75254d5b7d0SLai Jiangshan 	unsigned long data = atomic_long_read(&work->data);
7537c3eed5cSTejun Heo 
754112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
755112202d9STejun Heo 		return ((struct pool_workqueue *)
75654d5b7d0SLai Jiangshan 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
75754d5b7d0SLai Jiangshan 
75854d5b7d0SLai Jiangshan 	return data >> WORK_OFFQ_POOL_SHIFT;
7597c3eed5cSTejun Heo }
7607c3eed5cSTejun Heo 
761bbb68dfaSTejun Heo static void mark_work_canceling(struct work_struct *work)
762bbb68dfaSTejun Heo {
7637c3eed5cSTejun Heo 	unsigned long pool_id = get_work_pool_id(work);
764bbb68dfaSTejun Heo 
7657c3eed5cSTejun Heo 	pool_id <<= WORK_OFFQ_POOL_SHIFT;
7667c3eed5cSTejun Heo 	set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
767bbb68dfaSTejun Heo }
768bbb68dfaSTejun Heo 
769bbb68dfaSTejun Heo static bool work_is_canceling(struct work_struct *work)
770bbb68dfaSTejun Heo {
771bbb68dfaSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
772bbb68dfaSTejun Heo 
773112202d9STejun Heo 	return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
774bbb68dfaSTejun Heo }
775bbb68dfaSTejun Heo 
776e22bee78STejun Heo /*
7773270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
7783270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
779d565ed63STejun Heo  * they're being called with pool->lock held.
780e22bee78STejun Heo  */
781e22bee78STejun Heo 
78263d95a91STejun Heo static bool __need_more_worker(struct worker_pool *pool)
783649027d7STejun Heo {
784e19e397aSTejun Heo 	return !atomic_read(&pool->nr_running);
785649027d7STejun Heo }
786649027d7STejun Heo 
787e22bee78STejun Heo /*
788e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
789e22bee78STejun Heo  * running workers.
790974271c4STejun Heo  *
791974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
792706026c2STejun Heo  * function will always return %true for unbound pools as long as the
793974271c4STejun Heo  * worklist isn't empty.
794e22bee78STejun Heo  */
79563d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
796e22bee78STejun Heo {
79763d95a91STejun Heo 	return !list_empty(&pool->worklist) && __need_more_worker(pool);
798e22bee78STejun Heo }
799e22bee78STejun Heo 
800e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
80163d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
802e22bee78STejun Heo {
80363d95a91STejun Heo 	return pool->nr_idle;
804e22bee78STejun Heo }
805e22bee78STejun Heo 
806e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
80763d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
808e22bee78STejun Heo {
809e19e397aSTejun Heo 	return !list_empty(&pool->worklist) &&
810e19e397aSTejun Heo 		atomic_read(&pool->nr_running) <= 1;
811e22bee78STejun Heo }
812e22bee78STejun Heo 
813e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
81463d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
815e22bee78STejun Heo {
81663d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
817e22bee78STejun Heo }
818e22bee78STejun Heo 
819e22bee78STejun Heo /* Do we have too many workers and should some go away? */
82063d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
821e22bee78STejun Heo {
822692b4825STejun Heo 	bool managing = pool->flags & POOL_MANAGER_ACTIVE;
82363d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
82463d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
825e22bee78STejun Heo 
826e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
827e22bee78STejun Heo }
828e22bee78STejun Heo 
829e22bee78STejun Heo /*
830e22bee78STejun Heo  * Wake up functions.
831e22bee78STejun Heo  */
832e22bee78STejun Heo 
8331037de36SLai Jiangshan /* Return the first idle worker.  Safe with preemption disabled */
8341037de36SLai Jiangshan static struct worker *first_idle_worker(struct worker_pool *pool)
8357e11629dSTejun Heo {
83663d95a91STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
8377e11629dSTejun Heo 		return NULL;
8387e11629dSTejun Heo 
83963d95a91STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
8407e11629dSTejun Heo }
8417e11629dSTejun Heo 
8427e11629dSTejun Heo /**
8437e11629dSTejun Heo  * wake_up_worker - wake up an idle worker
84463d95a91STejun Heo  * @pool: worker pool to wake worker from
8457e11629dSTejun Heo  *
84663d95a91STejun Heo  * Wake up the first idle worker of @pool.
8477e11629dSTejun Heo  *
8487e11629dSTejun Heo  * CONTEXT:
849a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
8507e11629dSTejun Heo  */
85163d95a91STejun Heo static void wake_up_worker(struct worker_pool *pool)
8527e11629dSTejun Heo {
8531037de36SLai Jiangshan 	struct worker *worker = first_idle_worker(pool);
8547e11629dSTejun Heo 
8557e11629dSTejun Heo 	if (likely(worker))
8567e11629dSTejun Heo 		wake_up_process(worker->task);
8577e11629dSTejun Heo }
8587e11629dSTejun Heo 
8594690c4abSTejun Heo /**
8606d25be57SThomas Gleixner  * wq_worker_running - a worker is running again
861e22bee78STejun Heo  * @task: task waking up
862e22bee78STejun Heo  *
8636d25be57SThomas Gleixner  * This function is called when a worker returns from schedule()
864e22bee78STejun Heo  */
8656d25be57SThomas Gleixner void wq_worker_running(struct task_struct *task)
866e22bee78STejun Heo {
867e22bee78STejun Heo 	struct worker *worker = kthread_data(task);
868e22bee78STejun Heo 
8696d25be57SThomas Gleixner 	if (!worker->sleeping)
8706d25be57SThomas Gleixner 		return;
8716d25be57SThomas Gleixner 	if (!(worker->flags & WORKER_NOT_RUNNING))
872e19e397aSTejun Heo 		atomic_inc(&worker->pool->nr_running);
8736d25be57SThomas Gleixner 	worker->sleeping = 0;
87436576000SJoonsoo Kim }
875e22bee78STejun Heo 
876e22bee78STejun Heo /**
877e22bee78STejun Heo  * wq_worker_sleeping - a worker is going to sleep
878e22bee78STejun Heo  * @task: task going to sleep
879e22bee78STejun Heo  *
8806d25be57SThomas Gleixner  * This function is called from schedule() when a busy worker is
881ccf45156SLai Jiangshan  * going to sleep.
882e22bee78STejun Heo  */
8836d25be57SThomas Gleixner void wq_worker_sleeping(struct task_struct *task)
884e22bee78STejun Heo {
8856d25be57SThomas Gleixner 	struct worker *next, *worker = kthread_data(task);
886111c225aSTejun Heo 	struct worker_pool *pool;
887e22bee78STejun Heo 
888111c225aSTejun Heo 	/*
889111c225aSTejun Heo 	 * Rescuers, which may not have all the fields set up like normal
890111c225aSTejun Heo 	 * workers, also reach here, let's not access anything before
891111c225aSTejun Heo 	 * checking NOT_RUNNING.
892111c225aSTejun Heo 	 */
8932d64672eSSteven Rostedt 	if (worker->flags & WORKER_NOT_RUNNING)
8946d25be57SThomas Gleixner 		return;
895e22bee78STejun Heo 
896111c225aSTejun Heo 	pool = worker->pool;
897111c225aSTejun Heo 
89862849a96SSebastian Andrzej Siewior 	/* Return if preempted before wq_worker_running() was reached */
89962849a96SSebastian Andrzej Siewior 	if (worker->sleeping)
9006d25be57SThomas Gleixner 		return;
9016d25be57SThomas Gleixner 
9026d25be57SThomas Gleixner 	worker->sleeping = 1;
903a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
904e22bee78STejun Heo 
905e22bee78STejun Heo 	/*
906e22bee78STejun Heo 	 * The counterpart of the following dec_and_test, implied mb,
907e22bee78STejun Heo 	 * worklist not empty test sequence is in insert_work().
908e22bee78STejun Heo 	 * Please read comment there.
909e22bee78STejun Heo 	 *
910628c78e7STejun Heo 	 * NOT_RUNNING is clear.  This means that we're bound to and
911628c78e7STejun Heo 	 * running on the local cpu w/ rq lock held and preemption
912628c78e7STejun Heo 	 * disabled, which in turn means that none else could be
913d565ed63STejun Heo 	 * manipulating idle_list, so dereferencing idle_list without pool
914628c78e7STejun Heo 	 * lock is safe.
915e22bee78STejun Heo 	 */
916e19e397aSTejun Heo 	if (atomic_dec_and_test(&pool->nr_running) &&
9176d25be57SThomas Gleixner 	    !list_empty(&pool->worklist)) {
9186d25be57SThomas Gleixner 		next = first_idle_worker(pool);
9196d25be57SThomas Gleixner 		if (next)
9206d25be57SThomas Gleixner 			wake_up_process(next->task);
9216d25be57SThomas Gleixner 	}
922a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
923e22bee78STejun Heo }
924e22bee78STejun Heo 
925e22bee78STejun Heo /**
9261b69ac6bSJohannes Weiner  * wq_worker_last_func - retrieve worker's last work function
9278194fe94SBart Van Assche  * @task: Task to retrieve last work function of.
9281b69ac6bSJohannes Weiner  *
9291b69ac6bSJohannes Weiner  * Determine the last function a worker executed. This is called from
9301b69ac6bSJohannes Weiner  * the scheduler to get a worker's last known identity.
9311b69ac6bSJohannes Weiner  *
9321b69ac6bSJohannes Weiner  * CONTEXT:
933a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(rq->lock)
9341b69ac6bSJohannes Weiner  *
9354b047002SJohannes Weiner  * This function is called during schedule() when a kworker is going
9364b047002SJohannes Weiner  * to sleep. It's used by psi to identify aggregation workers during
9374b047002SJohannes Weiner  * dequeuing, to allow periodic aggregation to shut-off when that
9384b047002SJohannes Weiner  * worker is the last task in the system or cgroup to go to sleep.
9394b047002SJohannes Weiner  *
9404b047002SJohannes Weiner  * As this function doesn't involve any workqueue-related locking, it
9414b047002SJohannes Weiner  * only returns stable values when called from inside the scheduler's
9424b047002SJohannes Weiner  * queuing and dequeuing paths, when @task, which must be a kworker,
9434b047002SJohannes Weiner  * is guaranteed to not be processing any works.
9444b047002SJohannes Weiner  *
9451b69ac6bSJohannes Weiner  * Return:
9461b69ac6bSJohannes Weiner  * The last work function %current executed as a worker, NULL if it
9471b69ac6bSJohannes Weiner  * hasn't executed any work yet.
9481b69ac6bSJohannes Weiner  */
9491b69ac6bSJohannes Weiner work_func_t wq_worker_last_func(struct task_struct *task)
9501b69ac6bSJohannes Weiner {
9511b69ac6bSJohannes Weiner 	struct worker *worker = kthread_data(task);
9521b69ac6bSJohannes Weiner 
9531b69ac6bSJohannes Weiner 	return worker->last_func;
9541b69ac6bSJohannes Weiner }
9551b69ac6bSJohannes Weiner 
9561b69ac6bSJohannes Weiner /**
957e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
958cb444766STejun Heo  * @worker: self
959d302f017STejun Heo  * @flags: flags to set
960d302f017STejun Heo  *
961228f1d00SLai Jiangshan  * Set @flags in @worker->flags and adjust nr_running accordingly.
962d302f017STejun Heo  *
963cb444766STejun Heo  * CONTEXT:
964a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock)
965d302f017STejun Heo  */
966228f1d00SLai Jiangshan static inline void worker_set_flags(struct worker *worker, unsigned int flags)
967d302f017STejun Heo {
968bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
969e22bee78STejun Heo 
970cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
971cb444766STejun Heo 
972228f1d00SLai Jiangshan 	/* If transitioning into NOT_RUNNING, adjust nr_running. */
973e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
974e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
975e19e397aSTejun Heo 		atomic_dec(&pool->nr_running);
976e22bee78STejun Heo 	}
977e22bee78STejun Heo 
978d302f017STejun Heo 	worker->flags |= flags;
979d302f017STejun Heo }
980d302f017STejun Heo 
981d302f017STejun Heo /**
982e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
983cb444766STejun Heo  * @worker: self
984d302f017STejun Heo  * @flags: flags to clear
985d302f017STejun Heo  *
986e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
987d302f017STejun Heo  *
988cb444766STejun Heo  * CONTEXT:
989a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock)
990d302f017STejun Heo  */
991d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
992d302f017STejun Heo {
99363d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
994e22bee78STejun Heo 	unsigned int oflags = worker->flags;
995e22bee78STejun Heo 
996cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
997cb444766STejun Heo 
998d302f017STejun Heo 	worker->flags &= ~flags;
999e22bee78STejun Heo 
100042c025f3STejun Heo 	/*
100142c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
100242c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
100342c025f3STejun Heo 	 * of multiple flags, not a single flag.
100442c025f3STejun Heo 	 */
1005e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
1006e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
1007e19e397aSTejun Heo 			atomic_inc(&pool->nr_running);
1008d302f017STejun Heo }
1009d302f017STejun Heo 
1010d302f017STejun Heo /**
10118cca0eeaSTejun Heo  * find_worker_executing_work - find worker which is executing a work
1012c9e7cf27STejun Heo  * @pool: pool of interest
10138cca0eeaSTejun Heo  * @work: work to find worker for
10148cca0eeaSTejun Heo  *
1015c9e7cf27STejun Heo  * Find a worker which is executing @work on @pool by searching
1016c9e7cf27STejun Heo  * @pool->busy_hash which is keyed by the address of @work.  For a worker
1017a2c1c57bSTejun Heo  * to match, its current execution should match the address of @work and
1018a2c1c57bSTejun Heo  * its work function.  This is to avoid unwanted dependency between
1019a2c1c57bSTejun Heo  * unrelated work executions through a work item being recycled while still
1020a2c1c57bSTejun Heo  * being executed.
1021a2c1c57bSTejun Heo  *
1022a2c1c57bSTejun Heo  * This is a bit tricky.  A work item may be freed once its execution
1023a2c1c57bSTejun Heo  * starts and nothing prevents the freed area from being recycled for
1024a2c1c57bSTejun Heo  * another work item.  If the same work item address ends up being reused
1025a2c1c57bSTejun Heo  * before the original execution finishes, workqueue will identify the
1026a2c1c57bSTejun Heo  * recycled work item as currently executing and make it wait until the
1027a2c1c57bSTejun Heo  * current execution finishes, introducing an unwanted dependency.
1028a2c1c57bSTejun Heo  *
1029c5aa87bbSTejun Heo  * This function checks the work item address and work function to avoid
1030c5aa87bbSTejun Heo  * false positives.  Note that this isn't complete as one may construct a
1031c5aa87bbSTejun Heo  * work function which can introduce dependency onto itself through a
1032c5aa87bbSTejun Heo  * recycled work item.  Well, if somebody wants to shoot oneself in the
1033c5aa87bbSTejun Heo  * foot that badly, there's only so much we can do, and if such deadlock
1034c5aa87bbSTejun Heo  * actually occurs, it should be easy to locate the culprit work function.
10358cca0eeaSTejun Heo  *
10368cca0eeaSTejun Heo  * CONTEXT:
1037a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
10388cca0eeaSTejun Heo  *
1039d185af30SYacine Belkadi  * Return:
1040d185af30SYacine Belkadi  * Pointer to worker which is executing @work if found, %NULL
10418cca0eeaSTejun Heo  * otherwise.
10428cca0eeaSTejun Heo  */
1043c9e7cf27STejun Heo static struct worker *find_worker_executing_work(struct worker_pool *pool,
10448cca0eeaSTejun Heo 						 struct work_struct *work)
10458cca0eeaSTejun Heo {
104642f8570fSSasha Levin 	struct worker *worker;
104742f8570fSSasha Levin 
1048b67bfe0dSSasha Levin 	hash_for_each_possible(pool->busy_hash, worker, hentry,
1049a2c1c57bSTejun Heo 			       (unsigned long)work)
1050a2c1c57bSTejun Heo 		if (worker->current_work == work &&
1051a2c1c57bSTejun Heo 		    worker->current_func == work->func)
105242f8570fSSasha Levin 			return worker;
105342f8570fSSasha Levin 
105442f8570fSSasha Levin 	return NULL;
10558cca0eeaSTejun Heo }
10568cca0eeaSTejun Heo 
10578cca0eeaSTejun Heo /**
1058bf4ede01STejun Heo  * move_linked_works - move linked works to a list
1059bf4ede01STejun Heo  * @work: start of series of works to be scheduled
1060bf4ede01STejun Heo  * @head: target list to append @work to
1061402dd89dSShailendra Verma  * @nextp: out parameter for nested worklist walking
1062bf4ede01STejun Heo  *
1063bf4ede01STejun Heo  * Schedule linked works starting from @work to @head.  Work series to
1064bf4ede01STejun Heo  * be scheduled starts at @work and includes any consecutive work with
1065bf4ede01STejun Heo  * WORK_STRUCT_LINKED set in its predecessor.
1066bf4ede01STejun Heo  *
1067bf4ede01STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of
1068bf4ede01STejun Heo  * the last scheduled work.  This allows move_linked_works() to be
1069bf4ede01STejun Heo  * nested inside outer list_for_each_entry_safe().
1070bf4ede01STejun Heo  *
1071bf4ede01STejun Heo  * CONTEXT:
1072a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1073bf4ede01STejun Heo  */
1074bf4ede01STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
1075bf4ede01STejun Heo 			      struct work_struct **nextp)
1076bf4ede01STejun Heo {
1077bf4ede01STejun Heo 	struct work_struct *n;
1078bf4ede01STejun Heo 
1079bf4ede01STejun Heo 	/*
1080bf4ede01STejun Heo 	 * Linked worklist will always end before the end of the list,
1081bf4ede01STejun Heo 	 * use NULL for list head.
1082bf4ede01STejun Heo 	 */
1083bf4ede01STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
1084bf4ede01STejun Heo 		list_move_tail(&work->entry, head);
1085bf4ede01STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1086bf4ede01STejun Heo 			break;
1087bf4ede01STejun Heo 	}
1088bf4ede01STejun Heo 
1089bf4ede01STejun Heo 	/*
1090bf4ede01STejun Heo 	 * If we're already inside safe list traversal and have moved
1091bf4ede01STejun Heo 	 * multiple works to the scheduled queue, the next position
1092bf4ede01STejun Heo 	 * needs to be updated.
1093bf4ede01STejun Heo 	 */
1094bf4ede01STejun Heo 	if (nextp)
1095bf4ede01STejun Heo 		*nextp = n;
1096bf4ede01STejun Heo }
1097bf4ede01STejun Heo 
10988864b4e5STejun Heo /**
10998864b4e5STejun Heo  * get_pwq - get an extra reference on the specified pool_workqueue
11008864b4e5STejun Heo  * @pwq: pool_workqueue to get
11018864b4e5STejun Heo  *
11028864b4e5STejun Heo  * Obtain an extra reference on @pwq.  The caller should guarantee that
11038864b4e5STejun Heo  * @pwq has positive refcnt and be holding the matching pool->lock.
11048864b4e5STejun Heo  */
11058864b4e5STejun Heo static void get_pwq(struct pool_workqueue *pwq)
11068864b4e5STejun Heo {
11078864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
11088864b4e5STejun Heo 	WARN_ON_ONCE(pwq->refcnt <= 0);
11098864b4e5STejun Heo 	pwq->refcnt++;
11108864b4e5STejun Heo }
11118864b4e5STejun Heo 
11128864b4e5STejun Heo /**
11138864b4e5STejun Heo  * put_pwq - put a pool_workqueue reference
11148864b4e5STejun Heo  * @pwq: pool_workqueue to put
11158864b4e5STejun Heo  *
11168864b4e5STejun Heo  * Drop a reference of @pwq.  If its refcnt reaches zero, schedule its
11178864b4e5STejun Heo  * destruction.  The caller should be holding the matching pool->lock.
11188864b4e5STejun Heo  */
11198864b4e5STejun Heo static void put_pwq(struct pool_workqueue *pwq)
11208864b4e5STejun Heo {
11218864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
11228864b4e5STejun Heo 	if (likely(--pwq->refcnt))
11238864b4e5STejun Heo 		return;
11248864b4e5STejun Heo 	if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
11258864b4e5STejun Heo 		return;
11268864b4e5STejun Heo 	/*
11278864b4e5STejun Heo 	 * @pwq can't be released under pool->lock, bounce to
11288864b4e5STejun Heo 	 * pwq_unbound_release_workfn().  This never recurses on the same
11298864b4e5STejun Heo 	 * pool->lock as this path is taken only for unbound workqueues and
11308864b4e5STejun Heo 	 * the release work item is scheduled on a per-cpu workqueue.  To
11318864b4e5STejun Heo 	 * avoid lockdep warning, unbound pool->locks are given lockdep
11328864b4e5STejun Heo 	 * subclass of 1 in get_unbound_pool().
11338864b4e5STejun Heo 	 */
11348864b4e5STejun Heo 	schedule_work(&pwq->unbound_release_work);
11358864b4e5STejun Heo }
11368864b4e5STejun Heo 
1137dce90d47STejun Heo /**
1138dce90d47STejun Heo  * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1139dce90d47STejun Heo  * @pwq: pool_workqueue to put (can be %NULL)
1140dce90d47STejun Heo  *
1141dce90d47STejun Heo  * put_pwq() with locking.  This function also allows %NULL @pwq.
1142dce90d47STejun Heo  */
1143dce90d47STejun Heo static void put_pwq_unlocked(struct pool_workqueue *pwq)
1144dce90d47STejun Heo {
1145dce90d47STejun Heo 	if (pwq) {
1146dce90d47STejun Heo 		/*
114724acfb71SThomas Gleixner 		 * As both pwqs and pools are RCU protected, the
1148dce90d47STejun Heo 		 * following lock operations are safe.
1149dce90d47STejun Heo 		 */
1150a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
1151dce90d47STejun Heo 		put_pwq(pwq);
1152a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
1153dce90d47STejun Heo 	}
1154dce90d47STejun Heo }
1155dce90d47STejun Heo 
1156f97a4a1aSLai Jiangshan static void pwq_activate_inactive_work(struct work_struct *work)
1157bf4ede01STejun Heo {
1158112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1159bf4ede01STejun Heo 
1160bf4ede01STejun Heo 	trace_workqueue_activate_work(work);
116182607adcSTejun Heo 	if (list_empty(&pwq->pool->worklist))
116282607adcSTejun Heo 		pwq->pool->watchdog_ts = jiffies;
1163112202d9STejun Heo 	move_linked_works(work, &pwq->pool->worklist, NULL);
1164f97a4a1aSLai Jiangshan 	__clear_bit(WORK_STRUCT_INACTIVE_BIT, work_data_bits(work));
1165112202d9STejun Heo 	pwq->nr_active++;
1166bf4ede01STejun Heo }
1167bf4ede01STejun Heo 
1168f97a4a1aSLai Jiangshan static void pwq_activate_first_inactive(struct pool_workqueue *pwq)
11693aa62497SLai Jiangshan {
1170f97a4a1aSLai Jiangshan 	struct work_struct *work = list_first_entry(&pwq->inactive_works,
11713aa62497SLai Jiangshan 						    struct work_struct, entry);
11723aa62497SLai Jiangshan 
1173f97a4a1aSLai Jiangshan 	pwq_activate_inactive_work(work);
11743aa62497SLai Jiangshan }
11753aa62497SLai Jiangshan 
1176bf4ede01STejun Heo /**
1177112202d9STejun Heo  * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1178112202d9STejun Heo  * @pwq: pwq of interest
1179c4560c2cSLai Jiangshan  * @work_data: work_data of work which left the queue
1180bf4ede01STejun Heo  *
1181bf4ede01STejun Heo  * A work either has completed or is removed from pending queue,
1182112202d9STejun Heo  * decrement nr_in_flight of its pwq and handle workqueue flushing.
1183bf4ede01STejun Heo  *
1184bf4ede01STejun Heo  * CONTEXT:
1185a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1186bf4ede01STejun Heo  */
1187c4560c2cSLai Jiangshan static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data)
1188bf4ede01STejun Heo {
1189c4560c2cSLai Jiangshan 	int color = get_work_color(work_data);
1190c4560c2cSLai Jiangshan 
1191018f3a13SLai Jiangshan 	if (!(work_data & WORK_STRUCT_INACTIVE)) {
1192112202d9STejun Heo 		pwq->nr_active--;
1193f97a4a1aSLai Jiangshan 		if (!list_empty(&pwq->inactive_works)) {
1194f97a4a1aSLai Jiangshan 			/* one down, submit an inactive one */
1195112202d9STejun Heo 			if (pwq->nr_active < pwq->max_active)
1196f97a4a1aSLai Jiangshan 				pwq_activate_first_inactive(pwq);
1197bf4ede01STejun Heo 		}
1198018f3a13SLai Jiangshan 	}
1199018f3a13SLai Jiangshan 
1200018f3a13SLai Jiangshan 	pwq->nr_in_flight[color]--;
1201bf4ede01STejun Heo 
1202bf4ede01STejun Heo 	/* is flush in progress and are we at the flushing tip? */
1203112202d9STejun Heo 	if (likely(pwq->flush_color != color))
12048864b4e5STejun Heo 		goto out_put;
1205bf4ede01STejun Heo 
1206bf4ede01STejun Heo 	/* are there still in-flight works? */
1207112202d9STejun Heo 	if (pwq->nr_in_flight[color])
12088864b4e5STejun Heo 		goto out_put;
1209bf4ede01STejun Heo 
1210112202d9STejun Heo 	/* this pwq is done, clear flush_color */
1211112202d9STejun Heo 	pwq->flush_color = -1;
1212bf4ede01STejun Heo 
1213bf4ede01STejun Heo 	/*
1214112202d9STejun Heo 	 * If this was the last pwq, wake up the first flusher.  It
1215bf4ede01STejun Heo 	 * will handle the rest.
1216bf4ede01STejun Heo 	 */
1217112202d9STejun Heo 	if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1218112202d9STejun Heo 		complete(&pwq->wq->first_flusher->done);
12198864b4e5STejun Heo out_put:
12208864b4e5STejun Heo 	put_pwq(pwq);
1221bf4ede01STejun Heo }
1222bf4ede01STejun Heo 
122336e227d2STejun Heo /**
1224bbb68dfaSTejun Heo  * try_to_grab_pending - steal work item from worklist and disable irq
122536e227d2STejun Heo  * @work: work item to steal
122636e227d2STejun Heo  * @is_dwork: @work is a delayed_work
1227bbb68dfaSTejun Heo  * @flags: place to store irq state
122836e227d2STejun Heo  *
122936e227d2STejun Heo  * Try to grab PENDING bit of @work.  This function can handle @work in any
1230d185af30SYacine Belkadi  * stable state - idle, on timer or on worklist.
123136e227d2STejun Heo  *
1232d185af30SYacine Belkadi  * Return:
12333eb6b31bSMauro Carvalho Chehab  *
12343eb6b31bSMauro Carvalho Chehab  *  ========	================================================================
123536e227d2STejun Heo  *  1		if @work was pending and we successfully stole PENDING
123636e227d2STejun Heo  *  0		if @work was idle and we claimed PENDING
123736e227d2STejun Heo  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
1238bbb68dfaSTejun Heo  *  -ENOENT	if someone else is canceling @work, this state may persist
1239bbb68dfaSTejun Heo  *		for arbitrarily long
12403eb6b31bSMauro Carvalho Chehab  *  ========	================================================================
124136e227d2STejun Heo  *
1242d185af30SYacine Belkadi  * Note:
1243bbb68dfaSTejun Heo  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
1244e0aecdd8STejun Heo  * interrupted while holding PENDING and @work off queue, irq must be
1245e0aecdd8STejun Heo  * disabled on entry.  This, combined with delayed_work->timer being
1246e0aecdd8STejun Heo  * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1247bbb68dfaSTejun Heo  *
1248bbb68dfaSTejun Heo  * On successful return, >= 0, irq is disabled and the caller is
1249bbb68dfaSTejun Heo  * responsible for releasing it using local_irq_restore(*@flags).
1250bbb68dfaSTejun Heo  *
1251e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
1252bf4ede01STejun Heo  */
1253bbb68dfaSTejun Heo static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1254bbb68dfaSTejun Heo 			       unsigned long *flags)
1255bf4ede01STejun Heo {
1256d565ed63STejun Heo 	struct worker_pool *pool;
1257112202d9STejun Heo 	struct pool_workqueue *pwq;
1258bf4ede01STejun Heo 
1259bbb68dfaSTejun Heo 	local_irq_save(*flags);
1260bbb68dfaSTejun Heo 
126136e227d2STejun Heo 	/* try to steal the timer if it exists */
126236e227d2STejun Heo 	if (is_dwork) {
126336e227d2STejun Heo 		struct delayed_work *dwork = to_delayed_work(work);
126436e227d2STejun Heo 
1265e0aecdd8STejun Heo 		/*
1266e0aecdd8STejun Heo 		 * dwork->timer is irqsafe.  If del_timer() fails, it's
1267e0aecdd8STejun Heo 		 * guaranteed that the timer is not queued anywhere and not
1268e0aecdd8STejun Heo 		 * running on the local CPU.
1269e0aecdd8STejun Heo 		 */
127036e227d2STejun Heo 		if (likely(del_timer(&dwork->timer)))
127136e227d2STejun Heo 			return 1;
127236e227d2STejun Heo 	}
127336e227d2STejun Heo 
127436e227d2STejun Heo 	/* try to claim PENDING the normal way */
1275bf4ede01STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1276bf4ede01STejun Heo 		return 0;
1277bf4ede01STejun Heo 
127824acfb71SThomas Gleixner 	rcu_read_lock();
1279bf4ede01STejun Heo 	/*
1280bf4ede01STejun Heo 	 * The queueing is in progress, or it is already queued. Try to
1281bf4ede01STejun Heo 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1282bf4ede01STejun Heo 	 */
1283d565ed63STejun Heo 	pool = get_work_pool(work);
1284d565ed63STejun Heo 	if (!pool)
1285bbb68dfaSTejun Heo 		goto fail;
1286bf4ede01STejun Heo 
1287a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock(&pool->lock);
1288bf4ede01STejun Heo 	/*
1289112202d9STejun Heo 	 * work->data is guaranteed to point to pwq only while the work
1290112202d9STejun Heo 	 * item is queued on pwq->wq, and both updating work->data to point
1291112202d9STejun Heo 	 * to pwq on queueing and to pool on dequeueing are done under
1292112202d9STejun Heo 	 * pwq->pool->lock.  This in turn guarantees that, if work->data
1293112202d9STejun Heo 	 * points to pwq which is associated with a locked pool, the work
12940b3dae68SLai Jiangshan 	 * item is currently queued on that pool.
1295bf4ede01STejun Heo 	 */
1296112202d9STejun Heo 	pwq = get_work_pwq(work);
1297112202d9STejun Heo 	if (pwq && pwq->pool == pool) {
1298bf4ede01STejun Heo 		debug_work_deactivate(work);
12993aa62497SLai Jiangshan 
13003aa62497SLai Jiangshan 		/*
1301018f3a13SLai Jiangshan 		 * A cancelable inactive work item must be in the
1302018f3a13SLai Jiangshan 		 * pwq->inactive_works since a queued barrier can't be
1303018f3a13SLai Jiangshan 		 * canceled (see the comments in insert_wq_barrier()).
1304018f3a13SLai Jiangshan 		 *
1305f97a4a1aSLai Jiangshan 		 * An inactive work item cannot be grabbed directly because
1306d812796eSLai Jiangshan 		 * it might have linked barrier work items which, if left
1307f97a4a1aSLai Jiangshan 		 * on the inactive_works list, will confuse pwq->nr_active
130816062836STejun Heo 		 * management later on and cause stall.  Make sure the work
130916062836STejun Heo 		 * item is activated before grabbing.
13103aa62497SLai Jiangshan 		 */
1311f97a4a1aSLai Jiangshan 		if (*work_data_bits(work) & WORK_STRUCT_INACTIVE)
1312f97a4a1aSLai Jiangshan 			pwq_activate_inactive_work(work);
13133aa62497SLai Jiangshan 
1314bf4ede01STejun Heo 		list_del_init(&work->entry);
1315c4560c2cSLai Jiangshan 		pwq_dec_nr_in_flight(pwq, *work_data_bits(work));
131636e227d2STejun Heo 
1317112202d9STejun Heo 		/* work->data points to pwq iff queued, point to pool */
13184468a00fSLai Jiangshan 		set_work_pool_and_keep_pending(work, pool->id);
13194468a00fSLai Jiangshan 
1320a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock(&pool->lock);
132124acfb71SThomas Gleixner 		rcu_read_unlock();
132236e227d2STejun Heo 		return 1;
1323bf4ede01STejun Heo 	}
1324a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&pool->lock);
1325bbb68dfaSTejun Heo fail:
132624acfb71SThomas Gleixner 	rcu_read_unlock();
1327bbb68dfaSTejun Heo 	local_irq_restore(*flags);
1328bbb68dfaSTejun Heo 	if (work_is_canceling(work))
1329bbb68dfaSTejun Heo 		return -ENOENT;
1330bbb68dfaSTejun Heo 	cpu_relax();
133136e227d2STejun Heo 	return -EAGAIN;
1332bf4ede01STejun Heo }
1333bf4ede01STejun Heo 
1334bf4ede01STejun Heo /**
1335706026c2STejun Heo  * insert_work - insert a work into a pool
1336112202d9STejun Heo  * @pwq: pwq @work belongs to
13374690c4abSTejun Heo  * @work: work to insert
13384690c4abSTejun Heo  * @head: insertion point
13394690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
13404690c4abSTejun Heo  *
1341112202d9STejun Heo  * Insert @work which belongs to @pwq after @head.  @extra_flags is or'd to
1342706026c2STejun Heo  * work_struct flags.
13434690c4abSTejun Heo  *
13444690c4abSTejun Heo  * CONTEXT:
1345a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1346365970a1SDavid Howells  */
1347112202d9STejun Heo static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1348112202d9STejun Heo 			struct list_head *head, unsigned int extra_flags)
1349b89deed3SOleg Nesterov {
1350112202d9STejun Heo 	struct worker_pool *pool = pwq->pool;
1351e1d8aa9fSFrederic Weisbecker 
1352e89a85d6SWalter Wu 	/* record the work call stack in order to print it in KASAN reports */
1353f70da745SMarco Elver 	kasan_record_aux_stack_noalloc(work);
1354e89a85d6SWalter Wu 
13554690c4abSTejun Heo 	/* we own @work, set data and link */
1356112202d9STejun Heo 	set_work_pwq(work, pwq, extra_flags);
13571a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
13588864b4e5STejun Heo 	get_pwq(pwq);
1359e22bee78STejun Heo 
1360e22bee78STejun Heo 	/*
1361c5aa87bbSTejun Heo 	 * Ensure either wq_worker_sleeping() sees the above
1362c5aa87bbSTejun Heo 	 * list_add_tail() or we see zero nr_running to avoid workers lying
1363c5aa87bbSTejun Heo 	 * around lazily while there are works to be processed.
1364e22bee78STejun Heo 	 */
1365e22bee78STejun Heo 	smp_mb();
1366e22bee78STejun Heo 
136763d95a91STejun Heo 	if (__need_more_worker(pool))
136863d95a91STejun Heo 		wake_up_worker(pool);
1369b89deed3SOleg Nesterov }
1370b89deed3SOleg Nesterov 
1371c8efcc25STejun Heo /*
1372c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
13738d03ecfeSTejun Heo  * same workqueue.
1374c8efcc25STejun Heo  */
1375c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
1376c8efcc25STejun Heo {
1377c8efcc25STejun Heo 	struct worker *worker;
1378c8efcc25STejun Heo 
13798d03ecfeSTejun Heo 	worker = current_wq_worker();
1380c8efcc25STejun Heo 	/*
1381bf393fd4SBart Van Assche 	 * Return %true iff I'm a worker executing a work item on @wq.  If
13828d03ecfeSTejun Heo 	 * I'm @worker, it's safe to dereference it without locking.
1383c8efcc25STejun Heo 	 */
1384112202d9STejun Heo 	return worker && worker->current_pwq->wq == wq;
1385c8efcc25STejun Heo }
1386c8efcc25STejun Heo 
1387ef557180SMike Galbraith /*
1388ef557180SMike Galbraith  * When queueing an unbound work item to a wq, prefer local CPU if allowed
1389ef557180SMike Galbraith  * by wq_unbound_cpumask.  Otherwise, round robin among the allowed ones to
1390ef557180SMike Galbraith  * avoid perturbing sensitive tasks.
1391ef557180SMike Galbraith  */
1392ef557180SMike Galbraith static int wq_select_unbound_cpu(int cpu)
1393ef557180SMike Galbraith {
1394f303fccbSTejun Heo 	static bool printed_dbg_warning;
1395ef557180SMike Galbraith 	int new_cpu;
1396ef557180SMike Galbraith 
1397f303fccbSTejun Heo 	if (likely(!wq_debug_force_rr_cpu)) {
1398ef557180SMike Galbraith 		if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
1399ef557180SMike Galbraith 			return cpu;
1400f303fccbSTejun Heo 	} else if (!printed_dbg_warning) {
1401f303fccbSTejun Heo 		pr_warn("workqueue: round-robin CPU selection forced, expect performance impact\n");
1402f303fccbSTejun Heo 		printed_dbg_warning = true;
1403f303fccbSTejun Heo 	}
1404f303fccbSTejun Heo 
1405ef557180SMike Galbraith 	if (cpumask_empty(wq_unbound_cpumask))
1406ef557180SMike Galbraith 		return cpu;
1407ef557180SMike Galbraith 
1408ef557180SMike Galbraith 	new_cpu = __this_cpu_read(wq_rr_cpu_last);
1409ef557180SMike Galbraith 	new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
1410ef557180SMike Galbraith 	if (unlikely(new_cpu >= nr_cpu_ids)) {
1411ef557180SMike Galbraith 		new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
1412ef557180SMike Galbraith 		if (unlikely(new_cpu >= nr_cpu_ids))
1413ef557180SMike Galbraith 			return cpu;
1414ef557180SMike Galbraith 	}
1415ef557180SMike Galbraith 	__this_cpu_write(wq_rr_cpu_last, new_cpu);
1416ef557180SMike Galbraith 
1417ef557180SMike Galbraith 	return new_cpu;
1418ef557180SMike Galbraith }
1419ef557180SMike Galbraith 
1420d84ff051STejun Heo static void __queue_work(int cpu, struct workqueue_struct *wq,
14211da177e4SLinus Torvalds 			 struct work_struct *work)
14221da177e4SLinus Torvalds {
1423112202d9STejun Heo 	struct pool_workqueue *pwq;
1424c9178087STejun Heo 	struct worker_pool *last_pool;
14251e19ffc6STejun Heo 	struct list_head *worklist;
14268a2e8e5dSTejun Heo 	unsigned int work_flags;
1427b75cac93SJoonsoo Kim 	unsigned int req_cpu = cpu;
14288930cabaSTejun Heo 
14298930cabaSTejun Heo 	/*
14308930cabaSTejun Heo 	 * While a work item is PENDING && off queue, a task trying to
14318930cabaSTejun Heo 	 * steal the PENDING will busy-loop waiting for it to either get
14328930cabaSTejun Heo 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
14338930cabaSTejun Heo 	 * happen with IRQ disabled.
14348930cabaSTejun Heo 	 */
14358e8eb730SFrederic Weisbecker 	lockdep_assert_irqs_disabled();
14361da177e4SLinus Torvalds 
14371e19ffc6STejun Heo 
14389ef28a73SLi Bin 	/* if draining, only works from the same workqueue are allowed */
1439618b01ebSTejun Heo 	if (unlikely(wq->flags & __WQ_DRAINING) &&
1440c8efcc25STejun Heo 	    WARN_ON_ONCE(!is_chained_work(wq)))
1441e41e704bSTejun Heo 		return;
144224acfb71SThomas Gleixner 	rcu_read_lock();
14439e8cd2f5STejun Heo retry:
1444aa202f1fSHillf Danton 	/* pwq which will be used unless @work is executing elsewhere */
1445aa202f1fSHillf Danton 	if (wq->flags & WQ_UNBOUND) {
1446df2d5ae4STejun Heo 		if (req_cpu == WORK_CPU_UNBOUND)
1447ef557180SMike Galbraith 			cpu = wq_select_unbound_cpu(raw_smp_processor_id());
1448df2d5ae4STejun Heo 		pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1449aa202f1fSHillf Danton 	} else {
1450aa202f1fSHillf Danton 		if (req_cpu == WORK_CPU_UNBOUND)
1451aa202f1fSHillf Danton 			cpu = raw_smp_processor_id();
1452aa202f1fSHillf Danton 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1453aa202f1fSHillf Danton 	}
1454f3421797STejun Heo 
145518aa9effSTejun Heo 	/*
1456c9178087STejun Heo 	 * If @work was previously on a different pool, it might still be
1457c9178087STejun Heo 	 * running there, in which case the work needs to be queued on that
1458c9178087STejun Heo 	 * pool to guarantee non-reentrancy.
145918aa9effSTejun Heo 	 */
1460c9e7cf27STejun Heo 	last_pool = get_work_pool(work);
1461112202d9STejun Heo 	if (last_pool && last_pool != pwq->pool) {
146218aa9effSTejun Heo 		struct worker *worker;
146318aa9effSTejun Heo 
1464a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock(&last_pool->lock);
146518aa9effSTejun Heo 
1466c9e7cf27STejun Heo 		worker = find_worker_executing_work(last_pool, work);
146718aa9effSTejun Heo 
1468112202d9STejun Heo 		if (worker && worker->current_pwq->wq == wq) {
1469c9178087STejun Heo 			pwq = worker->current_pwq;
14708594fadeSLai Jiangshan 		} else {
147118aa9effSTejun Heo 			/* meh... not running there, queue here */
1472a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock(&last_pool->lock);
1473a9b8a985SSebastian Andrzej Siewior 			raw_spin_lock(&pwq->pool->lock);
147418aa9effSTejun Heo 		}
14758930cabaSTejun Heo 	} else {
1476a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock(&pwq->pool->lock);
14778930cabaSTejun Heo 	}
1478502ca9d8STejun Heo 
14799e8cd2f5STejun Heo 	/*
14809e8cd2f5STejun Heo 	 * pwq is determined and locked.  For unbound pools, we could have
14819e8cd2f5STejun Heo 	 * raced with pwq release and it could already be dead.  If its
14829e8cd2f5STejun Heo 	 * refcnt is zero, repeat pwq selection.  Note that pwqs never die
1483df2d5ae4STejun Heo 	 * without another pwq replacing it in the numa_pwq_tbl or while
1484df2d5ae4STejun Heo 	 * work items are executing on it, so the retrying is guaranteed to
14859e8cd2f5STejun Heo 	 * make forward-progress.
14869e8cd2f5STejun Heo 	 */
14879e8cd2f5STejun Heo 	if (unlikely(!pwq->refcnt)) {
14889e8cd2f5STejun Heo 		if (wq->flags & WQ_UNBOUND) {
1489a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock(&pwq->pool->lock);
14909e8cd2f5STejun Heo 			cpu_relax();
14919e8cd2f5STejun Heo 			goto retry;
14929e8cd2f5STejun Heo 		}
14939e8cd2f5STejun Heo 		/* oops */
14949e8cd2f5STejun Heo 		WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
14959e8cd2f5STejun Heo 			  wq->name, cpu);
14969e8cd2f5STejun Heo 	}
14979e8cd2f5STejun Heo 
1498112202d9STejun Heo 	/* pwq determined, queue */
1499112202d9STejun Heo 	trace_workqueue_queue_work(req_cpu, pwq, work);
1500502ca9d8STejun Heo 
150124acfb71SThomas Gleixner 	if (WARN_ON(!list_empty(&work->entry)))
150224acfb71SThomas Gleixner 		goto out;
15031e19ffc6STejun Heo 
1504112202d9STejun Heo 	pwq->nr_in_flight[pwq->work_color]++;
1505112202d9STejun Heo 	work_flags = work_color_to_flags(pwq->work_color);
15061e19ffc6STejun Heo 
1507112202d9STejun Heo 	if (likely(pwq->nr_active < pwq->max_active)) {
1508cdadf009STejun Heo 		trace_workqueue_activate_work(work);
1509112202d9STejun Heo 		pwq->nr_active++;
1510112202d9STejun Heo 		worklist = &pwq->pool->worklist;
151182607adcSTejun Heo 		if (list_empty(worklist))
151282607adcSTejun Heo 			pwq->pool->watchdog_ts = jiffies;
15138a2e8e5dSTejun Heo 	} else {
1514f97a4a1aSLai Jiangshan 		work_flags |= WORK_STRUCT_INACTIVE;
1515f97a4a1aSLai Jiangshan 		worklist = &pwq->inactive_works;
15168a2e8e5dSTejun Heo 	}
15171e19ffc6STejun Heo 
15180687c66bSZqiang 	debug_work_activate(work);
1519112202d9STejun Heo 	insert_work(pwq, work, worklist, work_flags);
15201e19ffc6STejun Heo 
152124acfb71SThomas Gleixner out:
1522a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&pwq->pool->lock);
152324acfb71SThomas Gleixner 	rcu_read_unlock();
15241da177e4SLinus Torvalds }
15251da177e4SLinus Torvalds 
15260fcb78c2SRolf Eike Beer /**
1527c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
1528c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
1529c1a220e7SZhang Rui  * @wq: workqueue to use
1530c1a220e7SZhang Rui  * @work: work to queue
1531c1a220e7SZhang Rui  *
1532c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
1533c1a220e7SZhang Rui  * can't go away.
1534d185af30SYacine Belkadi  *
1535d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.
1536c1a220e7SZhang Rui  */
1537d4283e93STejun Heo bool queue_work_on(int cpu, struct workqueue_struct *wq,
1538d4283e93STejun Heo 		   struct work_struct *work)
1539c1a220e7SZhang Rui {
1540d4283e93STejun Heo 	bool ret = false;
15418930cabaSTejun Heo 	unsigned long flags;
15428930cabaSTejun Heo 
15438930cabaSTejun Heo 	local_irq_save(flags);
1544c1a220e7SZhang Rui 
154522df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
15464690c4abSTejun Heo 		__queue_work(cpu, wq, work);
1547d4283e93STejun Heo 		ret = true;
1548c1a220e7SZhang Rui 	}
15498930cabaSTejun Heo 
15508930cabaSTejun Heo 	local_irq_restore(flags);
1551c1a220e7SZhang Rui 	return ret;
1552c1a220e7SZhang Rui }
1553ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_work_on);
1554c1a220e7SZhang Rui 
15558204e0c1SAlexander Duyck /**
15568204e0c1SAlexander Duyck  * workqueue_select_cpu_near - Select a CPU based on NUMA node
15578204e0c1SAlexander Duyck  * @node: NUMA node ID that we want to select a CPU from
15588204e0c1SAlexander Duyck  *
15598204e0c1SAlexander Duyck  * This function will attempt to find a "random" cpu available on a given
15608204e0c1SAlexander Duyck  * node. If there are no CPUs available on the given node it will return
15618204e0c1SAlexander Duyck  * WORK_CPU_UNBOUND indicating that we should just schedule to any
15628204e0c1SAlexander Duyck  * available CPU if we need to schedule this work.
15638204e0c1SAlexander Duyck  */
15648204e0c1SAlexander Duyck static int workqueue_select_cpu_near(int node)
15658204e0c1SAlexander Duyck {
15668204e0c1SAlexander Duyck 	int cpu;
15678204e0c1SAlexander Duyck 
15688204e0c1SAlexander Duyck 	/* No point in doing this if NUMA isn't enabled for workqueues */
15698204e0c1SAlexander Duyck 	if (!wq_numa_enabled)
15708204e0c1SAlexander Duyck 		return WORK_CPU_UNBOUND;
15718204e0c1SAlexander Duyck 
15728204e0c1SAlexander Duyck 	/* Delay binding to CPU if node is not valid or online */
15738204e0c1SAlexander Duyck 	if (node < 0 || node >= MAX_NUMNODES || !node_online(node))
15748204e0c1SAlexander Duyck 		return WORK_CPU_UNBOUND;
15758204e0c1SAlexander Duyck 
15768204e0c1SAlexander Duyck 	/* Use local node/cpu if we are already there */
15778204e0c1SAlexander Duyck 	cpu = raw_smp_processor_id();
15788204e0c1SAlexander Duyck 	if (node == cpu_to_node(cpu))
15798204e0c1SAlexander Duyck 		return cpu;
15808204e0c1SAlexander Duyck 
15818204e0c1SAlexander Duyck 	/* Use "random" otherwise know as "first" online CPU of node */
15828204e0c1SAlexander Duyck 	cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
15838204e0c1SAlexander Duyck 
15848204e0c1SAlexander Duyck 	/* If CPU is valid return that, otherwise just defer */
15858204e0c1SAlexander Duyck 	return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND;
15868204e0c1SAlexander Duyck }
15878204e0c1SAlexander Duyck 
15888204e0c1SAlexander Duyck /**
15898204e0c1SAlexander Duyck  * queue_work_node - queue work on a "random" cpu for a given NUMA node
15908204e0c1SAlexander Duyck  * @node: NUMA node that we are targeting the work for
15918204e0c1SAlexander Duyck  * @wq: workqueue to use
15928204e0c1SAlexander Duyck  * @work: work to queue
15938204e0c1SAlexander Duyck  *
15948204e0c1SAlexander Duyck  * We queue the work to a "random" CPU within a given NUMA node. The basic
15958204e0c1SAlexander Duyck  * idea here is to provide a way to somehow associate work with a given
15968204e0c1SAlexander Duyck  * NUMA node.
15978204e0c1SAlexander Duyck  *
15988204e0c1SAlexander Duyck  * This function will only make a best effort attempt at getting this onto
15998204e0c1SAlexander Duyck  * the right NUMA node. If no node is requested or the requested node is
16008204e0c1SAlexander Duyck  * offline then we just fall back to standard queue_work behavior.
16018204e0c1SAlexander Duyck  *
16028204e0c1SAlexander Duyck  * Currently the "random" CPU ends up being the first available CPU in the
16038204e0c1SAlexander Duyck  * intersection of cpu_online_mask and the cpumask of the node, unless we
16048204e0c1SAlexander Duyck  * are running on the node. In that case we just use the current CPU.
16058204e0c1SAlexander Duyck  *
16068204e0c1SAlexander Duyck  * Return: %false if @work was already on a queue, %true otherwise.
16078204e0c1SAlexander Duyck  */
16088204e0c1SAlexander Duyck bool queue_work_node(int node, struct workqueue_struct *wq,
16098204e0c1SAlexander Duyck 		     struct work_struct *work)
16108204e0c1SAlexander Duyck {
16118204e0c1SAlexander Duyck 	unsigned long flags;
16128204e0c1SAlexander Duyck 	bool ret = false;
16138204e0c1SAlexander Duyck 
16148204e0c1SAlexander Duyck 	/*
16158204e0c1SAlexander Duyck 	 * This current implementation is specific to unbound workqueues.
16168204e0c1SAlexander Duyck 	 * Specifically we only return the first available CPU for a given
16178204e0c1SAlexander Duyck 	 * node instead of cycling through individual CPUs within the node.
16188204e0c1SAlexander Duyck 	 *
16198204e0c1SAlexander Duyck 	 * If this is used with a per-cpu workqueue then the logic in
16208204e0c1SAlexander Duyck 	 * workqueue_select_cpu_near would need to be updated to allow for
16218204e0c1SAlexander Duyck 	 * some round robin type logic.
16228204e0c1SAlexander Duyck 	 */
16238204e0c1SAlexander Duyck 	WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND));
16248204e0c1SAlexander Duyck 
16258204e0c1SAlexander Duyck 	local_irq_save(flags);
16268204e0c1SAlexander Duyck 
16278204e0c1SAlexander Duyck 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
16288204e0c1SAlexander Duyck 		int cpu = workqueue_select_cpu_near(node);
16298204e0c1SAlexander Duyck 
16308204e0c1SAlexander Duyck 		__queue_work(cpu, wq, work);
16318204e0c1SAlexander Duyck 		ret = true;
16328204e0c1SAlexander Duyck 	}
16338204e0c1SAlexander Duyck 
16348204e0c1SAlexander Duyck 	local_irq_restore(flags);
16358204e0c1SAlexander Duyck 	return ret;
16368204e0c1SAlexander Duyck }
16378204e0c1SAlexander Duyck EXPORT_SYMBOL_GPL(queue_work_node);
16388204e0c1SAlexander Duyck 
16398c20feb6SKees Cook void delayed_work_timer_fn(struct timer_list *t)
16401da177e4SLinus Torvalds {
16418c20feb6SKees Cook 	struct delayed_work *dwork = from_timer(dwork, t, timer);
16421da177e4SLinus Torvalds 
1643e0aecdd8STejun Heo 	/* should have been called from irqsafe timer with irq already off */
164460c057bcSLai Jiangshan 	__queue_work(dwork->cpu, dwork->wq, &dwork->work);
16451da177e4SLinus Torvalds }
16461438ade5SKonstantin Khlebnikov EXPORT_SYMBOL(delayed_work_timer_fn);
16471da177e4SLinus Torvalds 
16487beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
164952bad64dSDavid Howells 				struct delayed_work *dwork, unsigned long delay)
16501da177e4SLinus Torvalds {
16517beb2edfSTejun Heo 	struct timer_list *timer = &dwork->timer;
16527beb2edfSTejun Heo 	struct work_struct *work = &dwork->work;
16531da177e4SLinus Torvalds 
1654637fdbaeSTejun Heo 	WARN_ON_ONCE(!wq);
165598173112SSami Tolvanen 	WARN_ON_FUNCTION_MISMATCH(timer->function, delayed_work_timer_fn);
1656fc4b514fSTejun Heo 	WARN_ON_ONCE(timer_pending(timer));
1657fc4b514fSTejun Heo 	WARN_ON_ONCE(!list_empty(&work->entry));
16587beb2edfSTejun Heo 
16598852aac2STejun Heo 	/*
16608852aac2STejun Heo 	 * If @delay is 0, queue @dwork->work immediately.  This is for
16618852aac2STejun Heo 	 * both optimization and correctness.  The earliest @timer can
16628852aac2STejun Heo 	 * expire is on the closest next tick and delayed_work users depend
16638852aac2STejun Heo 	 * on that there's no such delay when @delay is 0.
16648852aac2STejun Heo 	 */
16658852aac2STejun Heo 	if (!delay) {
16668852aac2STejun Heo 		__queue_work(cpu, wq, &dwork->work);
16678852aac2STejun Heo 		return;
16688852aac2STejun Heo 	}
16698852aac2STejun Heo 
167060c057bcSLai Jiangshan 	dwork->wq = wq;
16711265057fSTejun Heo 	dwork->cpu = cpu;
16727beb2edfSTejun Heo 	timer->expires = jiffies + delay;
16737beb2edfSTejun Heo 
1674041bd12eSTejun Heo 	if (unlikely(cpu != WORK_CPU_UNBOUND))
16757beb2edfSTejun Heo 		add_timer_on(timer, cpu);
1676041bd12eSTejun Heo 	else
1677041bd12eSTejun Heo 		add_timer(timer);
16787beb2edfSTejun Heo }
16791da177e4SLinus Torvalds 
16800fcb78c2SRolf Eike Beer /**
16810fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
16820fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
16830fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1684af9997e4SRandy Dunlap  * @dwork: work to queue
16850fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
16860fcb78c2SRolf Eike Beer  *
1687d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.  If
1688715f1300STejun Heo  * @delay is zero and @dwork is idle, it will be scheduled for immediate
1689715f1300STejun Heo  * execution.
16900fcb78c2SRolf Eike Beer  */
1691d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
169252bad64dSDavid Howells 			   struct delayed_work *dwork, unsigned long delay)
16937a6bc1cdSVenkatesh Pallipadi {
169452bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
1695d4283e93STejun Heo 	bool ret = false;
16968930cabaSTejun Heo 	unsigned long flags;
16978930cabaSTejun Heo 
16988930cabaSTejun Heo 	/* read the comment in __queue_work() */
16998930cabaSTejun Heo 	local_irq_save(flags);
17007a6bc1cdSVenkatesh Pallipadi 
170122df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
17027beb2edfSTejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
1703d4283e93STejun Heo 		ret = true;
17047a6bc1cdSVenkatesh Pallipadi 	}
17058930cabaSTejun Heo 
17068930cabaSTejun Heo 	local_irq_restore(flags);
17077a6bc1cdSVenkatesh Pallipadi 	return ret;
17087a6bc1cdSVenkatesh Pallipadi }
1709ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_delayed_work_on);
17101da177e4SLinus Torvalds 
1711c8e55f36STejun Heo /**
17128376fe22STejun Heo  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
17138376fe22STejun Heo  * @cpu: CPU number to execute work on
17148376fe22STejun Heo  * @wq: workqueue to use
17158376fe22STejun Heo  * @dwork: work to queue
17168376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
17178376fe22STejun Heo  *
17188376fe22STejun Heo  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
17198376fe22STejun Heo  * modify @dwork's timer so that it expires after @delay.  If @delay is
17208376fe22STejun Heo  * zero, @work is guaranteed to be scheduled immediately regardless of its
17218376fe22STejun Heo  * current state.
17228376fe22STejun Heo  *
1723d185af30SYacine Belkadi  * Return: %false if @dwork was idle and queued, %true if @dwork was
17248376fe22STejun Heo  * pending and its timer was modified.
17258376fe22STejun Heo  *
1726e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
17278376fe22STejun Heo  * See try_to_grab_pending() for details.
17288376fe22STejun Heo  */
17298376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
17308376fe22STejun Heo 			 struct delayed_work *dwork, unsigned long delay)
17318376fe22STejun Heo {
17328376fe22STejun Heo 	unsigned long flags;
17338376fe22STejun Heo 	int ret;
17348376fe22STejun Heo 
17358376fe22STejun Heo 	do {
17368376fe22STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
17378376fe22STejun Heo 	} while (unlikely(ret == -EAGAIN));
17388376fe22STejun Heo 
17398376fe22STejun Heo 	if (likely(ret >= 0)) {
17408376fe22STejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
17418376fe22STejun Heo 		local_irq_restore(flags);
17428376fe22STejun Heo 	}
17438376fe22STejun Heo 
17448376fe22STejun Heo 	/* -ENOENT from try_to_grab_pending() becomes %true */
17458376fe22STejun Heo 	return ret;
17468376fe22STejun Heo }
17478376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
17488376fe22STejun Heo 
174905f0fe6bSTejun Heo static void rcu_work_rcufn(struct rcu_head *rcu)
175005f0fe6bSTejun Heo {
175105f0fe6bSTejun Heo 	struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
175205f0fe6bSTejun Heo 
175305f0fe6bSTejun Heo 	/* read the comment in __queue_work() */
175405f0fe6bSTejun Heo 	local_irq_disable();
175505f0fe6bSTejun Heo 	__queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
175605f0fe6bSTejun Heo 	local_irq_enable();
175705f0fe6bSTejun Heo }
175805f0fe6bSTejun Heo 
175905f0fe6bSTejun Heo /**
176005f0fe6bSTejun Heo  * queue_rcu_work - queue work after a RCU grace period
176105f0fe6bSTejun Heo  * @wq: workqueue to use
176205f0fe6bSTejun Heo  * @rwork: work to queue
176305f0fe6bSTejun Heo  *
176405f0fe6bSTejun Heo  * Return: %false if @rwork was already pending, %true otherwise.  Note
176505f0fe6bSTejun Heo  * that a full RCU grace period is guaranteed only after a %true return.
1766bf393fd4SBart Van Assche  * While @rwork is guaranteed to be executed after a %false return, the
176705f0fe6bSTejun Heo  * execution may happen before a full RCU grace period has passed.
176805f0fe6bSTejun Heo  */
176905f0fe6bSTejun Heo bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
177005f0fe6bSTejun Heo {
177105f0fe6bSTejun Heo 	struct work_struct *work = &rwork->work;
177205f0fe6bSTejun Heo 
177305f0fe6bSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
177405f0fe6bSTejun Heo 		rwork->wq = wq;
177505f0fe6bSTejun Heo 		call_rcu(&rwork->rcu, rcu_work_rcufn);
177605f0fe6bSTejun Heo 		return true;
177705f0fe6bSTejun Heo 	}
177805f0fe6bSTejun Heo 
177905f0fe6bSTejun Heo 	return false;
178005f0fe6bSTejun Heo }
178105f0fe6bSTejun Heo EXPORT_SYMBOL(queue_rcu_work);
178205f0fe6bSTejun Heo 
17838376fe22STejun Heo /**
1784c8e55f36STejun Heo  * worker_enter_idle - enter idle state
1785c8e55f36STejun Heo  * @worker: worker which is entering idle state
1786c8e55f36STejun Heo  *
1787c8e55f36STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
1788c8e55f36STejun Heo  * necessary.
1789c8e55f36STejun Heo  *
1790c8e55f36STejun Heo  * LOCKING:
1791a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1792c8e55f36STejun Heo  */
1793c8e55f36STejun Heo static void worker_enter_idle(struct worker *worker)
17941da177e4SLinus Torvalds {
1795bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1796c8e55f36STejun Heo 
17976183c009STejun Heo 	if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
17986183c009STejun Heo 	    WARN_ON_ONCE(!list_empty(&worker->entry) &&
17996183c009STejun Heo 			 (worker->hentry.next || worker->hentry.pprev)))
18006183c009STejun Heo 		return;
1801c8e55f36STejun Heo 
1802051e1850SLai Jiangshan 	/* can't use worker_set_flags(), also called from create_worker() */
1803cb444766STejun Heo 	worker->flags |= WORKER_IDLE;
1804bd7bdd43STejun Heo 	pool->nr_idle++;
1805e22bee78STejun Heo 	worker->last_active = jiffies;
1806c8e55f36STejun Heo 
1807c8e55f36STejun Heo 	/* idle_list is LIFO */
1808bd7bdd43STejun Heo 	list_add(&worker->entry, &pool->idle_list);
1809db7bccf4STejun Heo 
181063d95a91STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1811628c78e7STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1812cb444766STejun Heo 
1813*989442d7SLai Jiangshan 	/* Sanity check nr_running. */
1814*989442d7SLai Jiangshan 	WARN_ON_ONCE(pool->nr_workers == pool->nr_idle &&
1815e19e397aSTejun Heo 		     atomic_read(&pool->nr_running));
1816c8e55f36STejun Heo }
1817c8e55f36STejun Heo 
1818c8e55f36STejun Heo /**
1819c8e55f36STejun Heo  * worker_leave_idle - leave idle state
1820c8e55f36STejun Heo  * @worker: worker which is leaving idle state
1821c8e55f36STejun Heo  *
1822c8e55f36STejun Heo  * @worker is leaving idle state.  Update stats.
1823c8e55f36STejun Heo  *
1824c8e55f36STejun Heo  * LOCKING:
1825a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1826c8e55f36STejun Heo  */
1827c8e55f36STejun Heo static void worker_leave_idle(struct worker *worker)
1828c8e55f36STejun Heo {
1829bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1830c8e55f36STejun Heo 
18316183c009STejun Heo 	if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
18326183c009STejun Heo 		return;
1833d302f017STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
1834bd7bdd43STejun Heo 	pool->nr_idle--;
1835c8e55f36STejun Heo 	list_del_init(&worker->entry);
1836c8e55f36STejun Heo }
1837c8e55f36STejun Heo 
1838f7537df5SLai Jiangshan static struct worker *alloc_worker(int node)
1839c34056a3STejun Heo {
1840c34056a3STejun Heo 	struct worker *worker;
1841c34056a3STejun Heo 
1842f7537df5SLai Jiangshan 	worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
1843c8e55f36STejun Heo 	if (worker) {
1844c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
1845affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
1846da028469SLai Jiangshan 		INIT_LIST_HEAD(&worker->node);
1847e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
1848e22bee78STejun Heo 		worker->flags = WORKER_PREP;
1849c8e55f36STejun Heo 	}
1850c34056a3STejun Heo 	return worker;
1851c34056a3STejun Heo }
1852c34056a3STejun Heo 
1853c34056a3STejun Heo /**
18544736cbf7SLai Jiangshan  * worker_attach_to_pool() - attach a worker to a pool
18554736cbf7SLai Jiangshan  * @worker: worker to be attached
18564736cbf7SLai Jiangshan  * @pool: the target pool
18574736cbf7SLai Jiangshan  *
18584736cbf7SLai Jiangshan  * Attach @worker to @pool.  Once attached, the %WORKER_UNBOUND flag and
18594736cbf7SLai Jiangshan  * cpu-binding of @worker are kept coordinated with the pool across
18604736cbf7SLai Jiangshan  * cpu-[un]hotplugs.
18614736cbf7SLai Jiangshan  */
18624736cbf7SLai Jiangshan static void worker_attach_to_pool(struct worker *worker,
18634736cbf7SLai Jiangshan 				   struct worker_pool *pool)
18644736cbf7SLai Jiangshan {
18651258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
18664736cbf7SLai Jiangshan 
18674736cbf7SLai Jiangshan 	/*
18681258fae7STejun Heo 	 * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains
18691258fae7STejun Heo 	 * stable across this function.  See the comments above the flag
18701258fae7STejun Heo 	 * definition for details.
18714736cbf7SLai Jiangshan 	 */
18724736cbf7SLai Jiangshan 	if (pool->flags & POOL_DISASSOCIATED)
18734736cbf7SLai Jiangshan 		worker->flags |= WORKER_UNBOUND;
18745c25b5ffSPeter Zijlstra 	else
18755c25b5ffSPeter Zijlstra 		kthread_set_per_cpu(worker->task, pool->cpu);
18764736cbf7SLai Jiangshan 
1877640f17c8SPeter Zijlstra 	if (worker->rescue_wq)
1878640f17c8SPeter Zijlstra 		set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
1879640f17c8SPeter Zijlstra 
18804736cbf7SLai Jiangshan 	list_add_tail(&worker->node, &pool->workers);
1881a2d812a2STejun Heo 	worker->pool = pool;
18824736cbf7SLai Jiangshan 
18831258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
18844736cbf7SLai Jiangshan }
18854736cbf7SLai Jiangshan 
18864736cbf7SLai Jiangshan /**
188760f5a4bcSLai Jiangshan  * worker_detach_from_pool() - detach a worker from its pool
188860f5a4bcSLai Jiangshan  * @worker: worker which is attached to its pool
188960f5a4bcSLai Jiangshan  *
18904736cbf7SLai Jiangshan  * Undo the attaching which had been done in worker_attach_to_pool().  The
18914736cbf7SLai Jiangshan  * caller worker shouldn't access to the pool after detached except it has
18924736cbf7SLai Jiangshan  * other reference to the pool.
189360f5a4bcSLai Jiangshan  */
1894a2d812a2STejun Heo static void worker_detach_from_pool(struct worker *worker)
189560f5a4bcSLai Jiangshan {
1896a2d812a2STejun Heo 	struct worker_pool *pool = worker->pool;
189760f5a4bcSLai Jiangshan 	struct completion *detach_completion = NULL;
189860f5a4bcSLai Jiangshan 
18991258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
1900a2d812a2STejun Heo 
19015c25b5ffSPeter Zijlstra 	kthread_set_per_cpu(worker->task, -1);
1902da028469SLai Jiangshan 	list_del(&worker->node);
1903a2d812a2STejun Heo 	worker->pool = NULL;
1904a2d812a2STejun Heo 
1905da028469SLai Jiangshan 	if (list_empty(&pool->workers))
190660f5a4bcSLai Jiangshan 		detach_completion = pool->detach_completion;
19071258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
190860f5a4bcSLai Jiangshan 
1909b62c0751SLai Jiangshan 	/* clear leftover flags without pool->lock after it is detached */
1910b62c0751SLai Jiangshan 	worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
1911b62c0751SLai Jiangshan 
191260f5a4bcSLai Jiangshan 	if (detach_completion)
191360f5a4bcSLai Jiangshan 		complete(detach_completion);
191460f5a4bcSLai Jiangshan }
191560f5a4bcSLai Jiangshan 
191660f5a4bcSLai Jiangshan /**
1917c34056a3STejun Heo  * create_worker - create a new workqueue worker
191863d95a91STejun Heo  * @pool: pool the new worker will belong to
1919c34056a3STejun Heo  *
1920051e1850SLai Jiangshan  * Create and start a new worker which is attached to @pool.
1921c34056a3STejun Heo  *
1922c34056a3STejun Heo  * CONTEXT:
1923c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
1924c34056a3STejun Heo  *
1925d185af30SYacine Belkadi  * Return:
1926c34056a3STejun Heo  * Pointer to the newly created worker.
1927c34056a3STejun Heo  */
1928bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
1929c34056a3STejun Heo {
1930e441b56fSZhen Lei 	struct worker *worker;
1931e441b56fSZhen Lei 	int id;
1932e3c916a4STejun Heo 	char id_buf[16];
1933c34056a3STejun Heo 
19347cda9aaeSLai Jiangshan 	/* ID is needed to determine kthread name */
1935e441b56fSZhen Lei 	id = ida_alloc(&pool->worker_ida, GFP_KERNEL);
1936822d8405STejun Heo 	if (id < 0)
1937e441b56fSZhen Lei 		return NULL;
1938c34056a3STejun Heo 
1939f7537df5SLai Jiangshan 	worker = alloc_worker(pool->node);
1940c34056a3STejun Heo 	if (!worker)
1941c34056a3STejun Heo 		goto fail;
1942c34056a3STejun Heo 
1943c34056a3STejun Heo 	worker->id = id;
1944c34056a3STejun Heo 
194529c91e99STejun Heo 	if (pool->cpu >= 0)
1946e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
1947e3c916a4STejun Heo 			 pool->attrs->nice < 0  ? "H" : "");
1948f3421797STejun Heo 	else
1949e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
1950e3c916a4STejun Heo 
1951f3f90ad4STejun Heo 	worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
1952e3c916a4STejun Heo 					      "kworker/%s", id_buf);
1953c34056a3STejun Heo 	if (IS_ERR(worker->task))
1954c34056a3STejun Heo 		goto fail;
1955c34056a3STejun Heo 
195691151228SOleg Nesterov 	set_user_nice(worker->task, pool->attrs->nice);
195725834c73SPeter Zijlstra 	kthread_bind_mask(worker->task, pool->attrs->cpumask);
195891151228SOleg Nesterov 
1959da028469SLai Jiangshan 	/* successful, attach the worker to the pool */
19604736cbf7SLai Jiangshan 	worker_attach_to_pool(worker, pool);
1961822d8405STejun Heo 
1962051e1850SLai Jiangshan 	/* start the newly created worker */
1963a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
1964051e1850SLai Jiangshan 	worker->pool->nr_workers++;
1965051e1850SLai Jiangshan 	worker_enter_idle(worker);
1966051e1850SLai Jiangshan 	wake_up_process(worker->task);
1967a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
1968051e1850SLai Jiangshan 
1969c34056a3STejun Heo 	return worker;
1970822d8405STejun Heo 
1971c34056a3STejun Heo fail:
1972e441b56fSZhen Lei 	ida_free(&pool->worker_ida, id);
1973c34056a3STejun Heo 	kfree(worker);
1974c34056a3STejun Heo 	return NULL;
1975c34056a3STejun Heo }
1976c34056a3STejun Heo 
1977c34056a3STejun Heo /**
1978c34056a3STejun Heo  * destroy_worker - destroy a workqueue worker
1979c34056a3STejun Heo  * @worker: worker to be destroyed
1980c34056a3STejun Heo  *
198173eb7fe7SLai Jiangshan  * Destroy @worker and adjust @pool stats accordingly.  The worker should
198273eb7fe7SLai Jiangshan  * be idle.
1983c8e55f36STejun Heo  *
1984c8e55f36STejun Heo  * CONTEXT:
1985a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1986c34056a3STejun Heo  */
1987c34056a3STejun Heo static void destroy_worker(struct worker *worker)
1988c34056a3STejun Heo {
1989bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1990c34056a3STejun Heo 
1991cd549687STejun Heo 	lockdep_assert_held(&pool->lock);
1992cd549687STejun Heo 
1993c34056a3STejun Heo 	/* sanity check frenzy */
19946183c009STejun Heo 	if (WARN_ON(worker->current_work) ||
199573eb7fe7SLai Jiangshan 	    WARN_ON(!list_empty(&worker->scheduled)) ||
199673eb7fe7SLai Jiangshan 	    WARN_ON(!(worker->flags & WORKER_IDLE)))
19976183c009STejun Heo 		return;
1998c34056a3STejun Heo 
1999bd7bdd43STejun Heo 	pool->nr_workers--;
2000bd7bdd43STejun Heo 	pool->nr_idle--;
2001c8e55f36STejun Heo 
2002c8e55f36STejun Heo 	list_del_init(&worker->entry);
2003cb444766STejun Heo 	worker->flags |= WORKER_DIE;
200460f5a4bcSLai Jiangshan 	wake_up_process(worker->task);
2005c34056a3STejun Heo }
2006c34056a3STejun Heo 
200732a6c723SKees Cook static void idle_worker_timeout(struct timer_list *t)
2008e22bee78STejun Heo {
200932a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, idle_timer);
2010e22bee78STejun Heo 
2011a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2012e22bee78STejun Heo 
20133347fc9fSLai Jiangshan 	while (too_many_workers(pool)) {
2014e22bee78STejun Heo 		struct worker *worker;
2015e22bee78STejun Heo 		unsigned long expires;
2016e22bee78STejun Heo 
2017e22bee78STejun Heo 		/* idle_list is kept in LIFO order, check the last one */
201863d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
2019e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2020e22bee78STejun Heo 
20213347fc9fSLai Jiangshan 		if (time_before(jiffies, expires)) {
202263d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
20233347fc9fSLai Jiangshan 			break;
2024e22bee78STejun Heo 		}
20253347fc9fSLai Jiangshan 
20263347fc9fSLai Jiangshan 		destroy_worker(worker);
2027e22bee78STejun Heo 	}
2028e22bee78STejun Heo 
2029a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2030e22bee78STejun Heo }
2031e22bee78STejun Heo 
2032493a1724STejun Heo static void send_mayday(struct work_struct *work)
2033e22bee78STejun Heo {
2034112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2035112202d9STejun Heo 	struct workqueue_struct *wq = pwq->wq;
2036493a1724STejun Heo 
20372e109a28STejun Heo 	lockdep_assert_held(&wq_mayday_lock);
2038e22bee78STejun Heo 
2039493008a8STejun Heo 	if (!wq->rescuer)
2040493a1724STejun Heo 		return;
2041e22bee78STejun Heo 
2042e22bee78STejun Heo 	/* mayday mayday mayday */
2043493a1724STejun Heo 	if (list_empty(&pwq->mayday_node)) {
204477668c8bSLai Jiangshan 		/*
204577668c8bSLai Jiangshan 		 * If @pwq is for an unbound wq, its base ref may be put at
204677668c8bSLai Jiangshan 		 * any time due to an attribute change.  Pin @pwq until the
204777668c8bSLai Jiangshan 		 * rescuer is done with it.
204877668c8bSLai Jiangshan 		 */
204977668c8bSLai Jiangshan 		get_pwq(pwq);
2050493a1724STejun Heo 		list_add_tail(&pwq->mayday_node, &wq->maydays);
2051e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
2052493a1724STejun Heo 	}
2053e22bee78STejun Heo }
2054e22bee78STejun Heo 
205532a6c723SKees Cook static void pool_mayday_timeout(struct timer_list *t)
2056e22bee78STejun Heo {
205732a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, mayday_timer);
2058e22bee78STejun Heo 	struct work_struct *work;
2059e22bee78STejun Heo 
2060a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2061a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock(&wq_mayday_lock);		/* for wq->maydays */
2062e22bee78STejun Heo 
206363d95a91STejun Heo 	if (need_to_create_worker(pool)) {
2064e22bee78STejun Heo 		/*
2065e22bee78STejun Heo 		 * We've been trying to create a new worker but
2066e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
2067e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
2068e22bee78STejun Heo 		 * rescuers.
2069e22bee78STejun Heo 		 */
207063d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
2071e22bee78STejun Heo 			send_mayday(work);
2072e22bee78STejun Heo 	}
2073e22bee78STejun Heo 
2074a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&wq_mayday_lock);
2075a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2076e22bee78STejun Heo 
207763d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
2078e22bee78STejun Heo }
2079e22bee78STejun Heo 
2080e22bee78STejun Heo /**
2081e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
208263d95a91STejun Heo  * @pool: pool to create a new worker for
2083e22bee78STejun Heo  *
208463d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
2085e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
2086e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
208763d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
2088e22bee78STejun Heo  * possible allocation deadlock.
2089e22bee78STejun Heo  *
2090c5aa87bbSTejun Heo  * On return, need_to_create_worker() is guaranteed to be %false and
2091c5aa87bbSTejun Heo  * may_start_working() %true.
2092e22bee78STejun Heo  *
2093e22bee78STejun Heo  * LOCKING:
2094a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2095e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
2096e22bee78STejun Heo  * manager.
2097e22bee78STejun Heo  */
209829187a9eSTejun Heo static void maybe_create_worker(struct worker_pool *pool)
2099d565ed63STejun Heo __releases(&pool->lock)
2100d565ed63STejun Heo __acquires(&pool->lock)
2101e22bee78STejun Heo {
2102e22bee78STejun Heo restart:
2103a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
21049f9c2364STejun Heo 
2105e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
210663d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
2107e22bee78STejun Heo 
2108e22bee78STejun Heo 	while (true) {
2109051e1850SLai Jiangshan 		if (create_worker(pool) || !need_to_create_worker(pool))
2110e22bee78STejun Heo 			break;
2111e22bee78STejun Heo 
2112e212f361SLai Jiangshan 		schedule_timeout_interruptible(CREATE_COOLDOWN);
21139f9c2364STejun Heo 
211463d95a91STejun Heo 		if (!need_to_create_worker(pool))
2115e22bee78STejun Heo 			break;
2116e22bee78STejun Heo 	}
2117e22bee78STejun Heo 
211863d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
2119a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2120051e1850SLai Jiangshan 	/*
2121051e1850SLai Jiangshan 	 * This is necessary even after a new worker was just successfully
2122051e1850SLai Jiangshan 	 * created as @pool->lock was dropped and the new worker might have
2123051e1850SLai Jiangshan 	 * already become busy.
2124051e1850SLai Jiangshan 	 */
212563d95a91STejun Heo 	if (need_to_create_worker(pool))
2126e22bee78STejun Heo 		goto restart;
2127e22bee78STejun Heo }
2128e22bee78STejun Heo 
2129e22bee78STejun Heo /**
2130e22bee78STejun Heo  * manage_workers - manage worker pool
2131e22bee78STejun Heo  * @worker: self
2132e22bee78STejun Heo  *
2133706026c2STejun Heo  * Assume the manager role and manage the worker pool @worker belongs
2134e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
2135706026c2STejun Heo  * pool.  The exclusion is handled automatically by this function.
2136e22bee78STejun Heo  *
2137e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
2138e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
2139e22bee78STejun Heo  * and may_start_working() is true.
2140e22bee78STejun Heo  *
2141e22bee78STejun Heo  * CONTEXT:
2142a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2143e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
2144e22bee78STejun Heo  *
2145d185af30SYacine Belkadi  * Return:
214629187a9eSTejun Heo  * %false if the pool doesn't need management and the caller can safely
214729187a9eSTejun Heo  * start processing works, %true if management function was performed and
214829187a9eSTejun Heo  * the conditions that the caller verified before calling the function may
214929187a9eSTejun Heo  * no longer be true.
2150e22bee78STejun Heo  */
2151e22bee78STejun Heo static bool manage_workers(struct worker *worker)
2152e22bee78STejun Heo {
215363d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
2154e22bee78STejun Heo 
2155692b4825STejun Heo 	if (pool->flags & POOL_MANAGER_ACTIVE)
215629187a9eSTejun Heo 		return false;
2157692b4825STejun Heo 
2158692b4825STejun Heo 	pool->flags |= POOL_MANAGER_ACTIVE;
21592607d7a6STejun Heo 	pool->manager = worker;
2160e22bee78STejun Heo 
216129187a9eSTejun Heo 	maybe_create_worker(pool);
2162e22bee78STejun Heo 
21632607d7a6STejun Heo 	pool->manager = NULL;
2164692b4825STejun Heo 	pool->flags &= ~POOL_MANAGER_ACTIVE;
2165d8bb65abSSebastian Andrzej Siewior 	rcuwait_wake_up(&manager_wait);
216629187a9eSTejun Heo 	return true;
2167e22bee78STejun Heo }
2168e22bee78STejun Heo 
2169a62428c0STejun Heo /**
2170a62428c0STejun Heo  * process_one_work - process single work
2171c34056a3STejun Heo  * @worker: self
2172a62428c0STejun Heo  * @work: work to process
2173a62428c0STejun Heo  *
2174a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
2175a62428c0STejun Heo  * process a single work including synchronization against and
2176a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
2177a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
2178a62428c0STejun Heo  * call this function to process a work.
2179a62428c0STejun Heo  *
2180a62428c0STejun Heo  * CONTEXT:
2181a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which is released and regrabbed.
2182a62428c0STejun Heo  */
2183c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
2184d565ed63STejun Heo __releases(&pool->lock)
2185d565ed63STejun Heo __acquires(&pool->lock)
21861da177e4SLinus Torvalds {
2187112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2188bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2189112202d9STejun Heo 	bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
2190c4560c2cSLai Jiangshan 	unsigned long work_data;
21917e11629dSTejun Heo 	struct worker *collision;
21924e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
21934e6045f1SJohannes Berg 	/*
2194a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
2195a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
2196a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
2197a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
2198a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
21994e6045f1SJohannes Berg 	 */
22004d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
22014d82a1deSPeter Zijlstra 
22024d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
22034e6045f1SJohannes Berg #endif
2204807407c0SLai Jiangshan 	/* ensure we're on the correct CPU */
220585327af6SLai Jiangshan 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2206ec22ca5eSTejun Heo 		     raw_smp_processor_id() != pool->cpu);
220725511a47STejun Heo 
22087e11629dSTejun Heo 	/*
22097e11629dSTejun Heo 	 * A single work shouldn't be executed concurrently by
22107e11629dSTejun Heo 	 * multiple workers on a single cpu.  Check whether anyone is
22117e11629dSTejun Heo 	 * already processing the work.  If so, defer the work to the
22127e11629dSTejun Heo 	 * currently executing one.
22137e11629dSTejun Heo 	 */
2214c9e7cf27STejun Heo 	collision = find_worker_executing_work(pool, work);
22157e11629dSTejun Heo 	if (unlikely(collision)) {
22167e11629dSTejun Heo 		move_linked_works(work, &collision->scheduled, NULL);
22177e11629dSTejun Heo 		return;
22187e11629dSTejun Heo 	}
22191da177e4SLinus Torvalds 
22208930cabaSTejun Heo 	/* claim and dequeue */
22211da177e4SLinus Torvalds 	debug_work_deactivate(work);
2222c9e7cf27STejun Heo 	hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2223c34056a3STejun Heo 	worker->current_work = work;
2224a2c1c57bSTejun Heo 	worker->current_func = work->func;
2225112202d9STejun Heo 	worker->current_pwq = pwq;
2226c4560c2cSLai Jiangshan 	work_data = *work_data_bits(work);
2227d812796eSLai Jiangshan 	worker->current_color = get_work_color(work_data);
22287a22ad75STejun Heo 
22298bf89593STejun Heo 	/*
22308bf89593STejun Heo 	 * Record wq name for cmdline and debug reporting, may get
22318bf89593STejun Heo 	 * overridden through set_worker_desc().
22328bf89593STejun Heo 	 */
22338bf89593STejun Heo 	strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
22348bf89593STejun Heo 
2235a62428c0STejun Heo 	list_del_init(&work->entry);
2236a62428c0STejun Heo 
2237649027d7STejun Heo 	/*
2238228f1d00SLai Jiangshan 	 * CPU intensive works don't participate in concurrency management.
2239228f1d00SLai Jiangshan 	 * They're the scheduler's responsibility.  This takes @worker out
2240228f1d00SLai Jiangshan 	 * of concurrency management and the next code block will chain
2241228f1d00SLai Jiangshan 	 * execution of the pending work items.
2242fb0e7bebSTejun Heo 	 */
2243fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2244228f1d00SLai Jiangshan 		worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2245fb0e7bebSTejun Heo 
2246974271c4STejun Heo 	/*
2247a489a03eSLai Jiangshan 	 * Wake up another worker if necessary.  The condition is always
2248a489a03eSLai Jiangshan 	 * false for normal per-cpu workers since nr_running would always
2249a489a03eSLai Jiangshan 	 * be >= 1 at this point.  This is used to chain execution of the
2250a489a03eSLai Jiangshan 	 * pending work items for WORKER_NOT_RUNNING workers such as the
2251228f1d00SLai Jiangshan 	 * UNBOUND and CPU_INTENSIVE ones.
2252974271c4STejun Heo 	 */
2253a489a03eSLai Jiangshan 	if (need_more_worker(pool))
225463d95a91STejun Heo 		wake_up_worker(pool);
2255974271c4STejun Heo 
22568930cabaSTejun Heo 	/*
22577c3eed5cSTejun Heo 	 * Record the last pool and clear PENDING which should be the last
2258d565ed63STejun Heo 	 * update to @work.  Also, do this inside @pool->lock so that
225923657bb1STejun Heo 	 * PENDING and queued state changes happen together while IRQ is
226023657bb1STejun Heo 	 * disabled.
22618930cabaSTejun Heo 	 */
22627c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(work, pool->id);
22631da177e4SLinus Torvalds 
2264a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2265365970a1SDavid Howells 
2266a1d14934SPeter Zijlstra 	lock_map_acquire(&pwq->wq->lockdep_map);
22673295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
2268e6f3faa7SPeter Zijlstra 	/*
2269f52be570SPeter Zijlstra 	 * Strictly speaking we should mark the invariant state without holding
2270f52be570SPeter Zijlstra 	 * any locks, that is, before these two lock_map_acquire()'s.
2271e6f3faa7SPeter Zijlstra 	 *
2272e6f3faa7SPeter Zijlstra 	 * However, that would result in:
2273e6f3faa7SPeter Zijlstra 	 *
2274e6f3faa7SPeter Zijlstra 	 *   A(W1)
2275e6f3faa7SPeter Zijlstra 	 *   WFC(C)
2276e6f3faa7SPeter Zijlstra 	 *		A(W1)
2277e6f3faa7SPeter Zijlstra 	 *		C(C)
2278e6f3faa7SPeter Zijlstra 	 *
2279e6f3faa7SPeter Zijlstra 	 * Which would create W1->C->W1 dependencies, even though there is no
2280e6f3faa7SPeter Zijlstra 	 * actual deadlock possible. There are two solutions, using a
2281e6f3faa7SPeter Zijlstra 	 * read-recursive acquire on the work(queue) 'locks', but this will then
2282f52be570SPeter Zijlstra 	 * hit the lockdep limitation on recursive locks, or simply discard
2283e6f3faa7SPeter Zijlstra 	 * these locks.
2284e6f3faa7SPeter Zijlstra 	 *
2285e6f3faa7SPeter Zijlstra 	 * AFAICT there is no possible deadlock scenario between the
2286e6f3faa7SPeter Zijlstra 	 * flush_work() and complete() primitives (except for single-threaded
2287e6f3faa7SPeter Zijlstra 	 * workqueues), so hiding them isn't a problem.
2288e6f3faa7SPeter Zijlstra 	 */
2289f52be570SPeter Zijlstra 	lockdep_invariant_state(true);
2290e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
2291a2c1c57bSTejun Heo 	worker->current_func(work);
2292e36c886aSArjan van de Ven 	/*
2293e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
2294e36c886aSArjan van de Ven 	 * point will only record its address.
2295e36c886aSArjan van de Ven 	 */
22961c5da0ecSDaniel Jordan 	trace_workqueue_execute_end(work, worker->current_func);
22973295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
2298112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
22991da177e4SLinus Torvalds 
2300d5abe669SPeter Zijlstra 	if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2301044c782cSValentin Ilie 		pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2302d75f773cSSakari Ailus 		       "     last function: %ps\n",
2303a2c1c57bSTejun Heo 		       current->comm, preempt_count(), task_pid_nr(current),
2304a2c1c57bSTejun Heo 		       worker->current_func);
2305d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
2306d5abe669SPeter Zijlstra 		dump_stack();
2307d5abe669SPeter Zijlstra 	}
2308d5abe669SPeter Zijlstra 
2309b22ce278STejun Heo 	/*
2310025f50f3SSebastian Andrzej Siewior 	 * The following prevents a kworker from hogging CPU on !PREEMPTION
2311b22ce278STejun Heo 	 * kernels, where a requeueing work item waiting for something to
2312b22ce278STejun Heo 	 * happen could deadlock with stop_machine as such work item could
2313b22ce278STejun Heo 	 * indefinitely requeue itself while all other CPUs are trapped in
2314789cbbecSJoe Lawrence 	 * stop_machine. At the same time, report a quiescent RCU state so
2315789cbbecSJoe Lawrence 	 * the same condition doesn't freeze RCU.
2316b22ce278STejun Heo 	 */
2317a7e6425eSPaul E. McKenney 	cond_resched();
2318b22ce278STejun Heo 
2319a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2320a62428c0STejun Heo 
2321fb0e7bebSTejun Heo 	/* clear cpu intensive status */
2322fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2323fb0e7bebSTejun Heo 		worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2324fb0e7bebSTejun Heo 
23251b69ac6bSJohannes Weiner 	/* tag the worker for identification in schedule() */
23261b69ac6bSJohannes Weiner 	worker->last_func = worker->current_func;
23271b69ac6bSJohannes Weiner 
2328a62428c0STejun Heo 	/* we're done with it, release */
232942f8570fSSasha Levin 	hash_del(&worker->hentry);
2330c34056a3STejun Heo 	worker->current_work = NULL;
2331a2c1c57bSTejun Heo 	worker->current_func = NULL;
2332112202d9STejun Heo 	worker->current_pwq = NULL;
2333d812796eSLai Jiangshan 	worker->current_color = INT_MAX;
2334c4560c2cSLai Jiangshan 	pwq_dec_nr_in_flight(pwq, work_data);
23351da177e4SLinus Torvalds }
23361da177e4SLinus Torvalds 
2337affee4b2STejun Heo /**
2338affee4b2STejun Heo  * process_scheduled_works - process scheduled works
2339affee4b2STejun Heo  * @worker: self
2340affee4b2STejun Heo  *
2341affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
2342affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
2343affee4b2STejun Heo  * fetches a work from the top and executes it.
2344affee4b2STejun Heo  *
2345affee4b2STejun Heo  * CONTEXT:
2346a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2347affee4b2STejun Heo  * multiple times.
2348affee4b2STejun Heo  */
2349affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
23501da177e4SLinus Torvalds {
2351affee4b2STejun Heo 	while (!list_empty(&worker->scheduled)) {
2352affee4b2STejun Heo 		struct work_struct *work = list_first_entry(&worker->scheduled,
2353a62428c0STejun Heo 						struct work_struct, entry);
2354c34056a3STejun Heo 		process_one_work(worker, work);
2355a62428c0STejun Heo 	}
23561da177e4SLinus Torvalds }
23571da177e4SLinus Torvalds 
2358197f6accSTejun Heo static void set_pf_worker(bool val)
2359197f6accSTejun Heo {
2360197f6accSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
2361197f6accSTejun Heo 	if (val)
2362197f6accSTejun Heo 		current->flags |= PF_WQ_WORKER;
2363197f6accSTejun Heo 	else
2364197f6accSTejun Heo 		current->flags &= ~PF_WQ_WORKER;
2365197f6accSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
2366197f6accSTejun Heo }
2367197f6accSTejun Heo 
23684690c4abSTejun Heo /**
23694690c4abSTejun Heo  * worker_thread - the worker thread function
2370c34056a3STejun Heo  * @__worker: self
23714690c4abSTejun Heo  *
2372c5aa87bbSTejun Heo  * The worker thread function.  All workers belong to a worker_pool -
2373c5aa87bbSTejun Heo  * either a per-cpu one or dynamic unbound one.  These workers process all
2374c5aa87bbSTejun Heo  * work items regardless of their specific target workqueue.  The only
2375c5aa87bbSTejun Heo  * exception is work items which belong to workqueues with a rescuer which
2376c5aa87bbSTejun Heo  * will be explained in rescuer_thread().
2377d185af30SYacine Belkadi  *
2378d185af30SYacine Belkadi  * Return: 0
23794690c4abSTejun Heo  */
2380c34056a3STejun Heo static int worker_thread(void *__worker)
23811da177e4SLinus Torvalds {
2382c34056a3STejun Heo 	struct worker *worker = __worker;
2383bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
23841da177e4SLinus Torvalds 
2385e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
2386197f6accSTejun Heo 	set_pf_worker(true);
2387c8e55f36STejun Heo woke_up:
2388a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2389affee4b2STejun Heo 
2390a9ab775bSTejun Heo 	/* am I supposed to die? */
2391a9ab775bSTejun Heo 	if (unlikely(worker->flags & WORKER_DIE)) {
2392a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
2393a9ab775bSTejun Heo 		WARN_ON_ONCE(!list_empty(&worker->entry));
2394197f6accSTejun Heo 		set_pf_worker(false);
239560f5a4bcSLai Jiangshan 
239660f5a4bcSLai Jiangshan 		set_task_comm(worker->task, "kworker/dying");
2397e441b56fSZhen Lei 		ida_free(&pool->worker_ida, worker->id);
2398a2d812a2STejun Heo 		worker_detach_from_pool(worker);
239960f5a4bcSLai Jiangshan 		kfree(worker);
2400c8e55f36STejun Heo 		return 0;
2401c8e55f36STejun Heo 	}
2402c8e55f36STejun Heo 
2403c8e55f36STejun Heo 	worker_leave_idle(worker);
2404db7bccf4STejun Heo recheck:
2405e22bee78STejun Heo 	/* no more worker necessary? */
240663d95a91STejun Heo 	if (!need_more_worker(pool))
2407e22bee78STejun Heo 		goto sleep;
2408e22bee78STejun Heo 
2409e22bee78STejun Heo 	/* do we need to manage? */
241063d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2411e22bee78STejun Heo 		goto recheck;
2412e22bee78STejun Heo 
2413c8e55f36STejun Heo 	/*
2414c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
2415c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
2416c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
2417c8e55f36STejun Heo 	 */
24186183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
2419c8e55f36STejun Heo 
2420e22bee78STejun Heo 	/*
2421a9ab775bSTejun Heo 	 * Finish PREP stage.  We're guaranteed to have at least one idle
2422a9ab775bSTejun Heo 	 * worker or that someone else has already assumed the manager
2423a9ab775bSTejun Heo 	 * role.  This is where @worker starts participating in concurrency
2424a9ab775bSTejun Heo 	 * management if applicable and concurrency management is restored
2425a9ab775bSTejun Heo 	 * after being rebound.  See rebind_workers() for details.
2426e22bee78STejun Heo 	 */
2427a9ab775bSTejun Heo 	worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2428e22bee78STejun Heo 
2429e22bee78STejun Heo 	do {
2430affee4b2STejun Heo 		struct work_struct *work =
2431bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
2432affee4b2STejun Heo 					 struct work_struct, entry);
2433affee4b2STejun Heo 
243482607adcSTejun Heo 		pool->watchdog_ts = jiffies;
243582607adcSTejun Heo 
2436c8e55f36STejun Heo 		if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2437affee4b2STejun Heo 			/* optimization path, not strictly necessary */
2438affee4b2STejun Heo 			process_one_work(worker, work);
2439affee4b2STejun Heo 			if (unlikely(!list_empty(&worker->scheduled)))
2440affee4b2STejun Heo 				process_scheduled_works(worker);
2441affee4b2STejun Heo 		} else {
2442c8e55f36STejun Heo 			move_linked_works(work, &worker->scheduled, NULL);
2443affee4b2STejun Heo 			process_scheduled_works(worker);
2444affee4b2STejun Heo 		}
244563d95a91STejun Heo 	} while (keep_working(pool));
2446affee4b2STejun Heo 
2447228f1d00SLai Jiangshan 	worker_set_flags(worker, WORKER_PREP);
2448d313dd85STejun Heo sleep:
2449c8e55f36STejun Heo 	/*
2450d565ed63STejun Heo 	 * pool->lock is held and there's no work to process and no need to
2451d565ed63STejun Heo 	 * manage, sleep.  Workers are woken up only while holding
2452d565ed63STejun Heo 	 * pool->lock or from local cpu, so setting the current state
2453d565ed63STejun Heo 	 * before releasing pool->lock is enough to prevent losing any
2454d565ed63STejun Heo 	 * event.
2455c8e55f36STejun Heo 	 */
2456c8e55f36STejun Heo 	worker_enter_idle(worker);
2457c5a94a61SPeter Zijlstra 	__set_current_state(TASK_IDLE);
2458a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
24591da177e4SLinus Torvalds 	schedule();
2460c8e55f36STejun Heo 	goto woke_up;
24611da177e4SLinus Torvalds }
24621da177e4SLinus Torvalds 
2463e22bee78STejun Heo /**
2464e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
2465111c225aSTejun Heo  * @__rescuer: self
2466e22bee78STejun Heo  *
2467e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
2468493008a8STejun Heo  * workqueue which has WQ_MEM_RECLAIM set.
2469e22bee78STejun Heo  *
2470706026c2STejun Heo  * Regular work processing on a pool may block trying to create a new
2471e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
2472e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
2473e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2474e22bee78STejun Heo  * the problem rescuer solves.
2475e22bee78STejun Heo  *
2476706026c2STejun Heo  * When such condition is possible, the pool summons rescuers of all
2477706026c2STejun Heo  * workqueues which have works queued on the pool and let them process
2478e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
2479e22bee78STejun Heo  *
2480e22bee78STejun Heo  * This should happen rarely.
2481d185af30SYacine Belkadi  *
2482d185af30SYacine Belkadi  * Return: 0
2483e22bee78STejun Heo  */
2484111c225aSTejun Heo static int rescuer_thread(void *__rescuer)
2485e22bee78STejun Heo {
2486111c225aSTejun Heo 	struct worker *rescuer = __rescuer;
2487111c225aSTejun Heo 	struct workqueue_struct *wq = rescuer->rescue_wq;
2488e22bee78STejun Heo 	struct list_head *scheduled = &rescuer->scheduled;
24894d595b86SLai Jiangshan 	bool should_stop;
2490e22bee78STejun Heo 
2491e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
2492111c225aSTejun Heo 
2493111c225aSTejun Heo 	/*
2494111c225aSTejun Heo 	 * Mark rescuer as worker too.  As WORKER_PREP is never cleared, it
2495111c225aSTejun Heo 	 * doesn't participate in concurrency management.
2496111c225aSTejun Heo 	 */
2497197f6accSTejun Heo 	set_pf_worker(true);
2498e22bee78STejun Heo repeat:
2499c5a94a61SPeter Zijlstra 	set_current_state(TASK_IDLE);
25001da177e4SLinus Torvalds 
25014d595b86SLai Jiangshan 	/*
25024d595b86SLai Jiangshan 	 * By the time the rescuer is requested to stop, the workqueue
25034d595b86SLai Jiangshan 	 * shouldn't have any work pending, but @wq->maydays may still have
25044d595b86SLai Jiangshan 	 * pwq(s) queued.  This can happen by non-rescuer workers consuming
25054d595b86SLai Jiangshan 	 * all the work items before the rescuer got to them.  Go through
25064d595b86SLai Jiangshan 	 * @wq->maydays processing before acting on should_stop so that the
25074d595b86SLai Jiangshan 	 * list is always empty on exit.
25084d595b86SLai Jiangshan 	 */
25094d595b86SLai Jiangshan 	should_stop = kthread_should_stop();
25101da177e4SLinus Torvalds 
2511493a1724STejun Heo 	/* see whether any pwq is asking for help */
2512a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&wq_mayday_lock);
2513493a1724STejun Heo 
2514493a1724STejun Heo 	while (!list_empty(&wq->maydays)) {
2515493a1724STejun Heo 		struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2516493a1724STejun Heo 					struct pool_workqueue, mayday_node);
2517112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
2518e22bee78STejun Heo 		struct work_struct *work, *n;
251982607adcSTejun Heo 		bool first = true;
2520e22bee78STejun Heo 
2521e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
2522493a1724STejun Heo 		list_del_init(&pwq->mayday_node);
2523493a1724STejun Heo 
2524a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&wq_mayday_lock);
2525e22bee78STejun Heo 
252651697d39SLai Jiangshan 		worker_attach_to_pool(rescuer, pool);
252751697d39SLai Jiangshan 
2528a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
2529e22bee78STejun Heo 
2530e22bee78STejun Heo 		/*
2531e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
2532e22bee78STejun Heo 		 * process'em.
2533e22bee78STejun Heo 		 */
25340479c8c5STejun Heo 		WARN_ON_ONCE(!list_empty(scheduled));
253582607adcSTejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry) {
253682607adcSTejun Heo 			if (get_work_pwq(work) == pwq) {
253782607adcSTejun Heo 				if (first)
253882607adcSTejun Heo 					pool->watchdog_ts = jiffies;
2539e22bee78STejun Heo 				move_linked_works(work, scheduled, &n);
254082607adcSTejun Heo 			}
254182607adcSTejun Heo 			first = false;
254282607adcSTejun Heo 		}
2543e22bee78STejun Heo 
2544008847f6SNeilBrown 		if (!list_empty(scheduled)) {
2545e22bee78STejun Heo 			process_scheduled_works(rescuer);
25467576958aSTejun Heo 
25477576958aSTejun Heo 			/*
2548008847f6SNeilBrown 			 * The above execution of rescued work items could
2549008847f6SNeilBrown 			 * have created more to rescue through
2550f97a4a1aSLai Jiangshan 			 * pwq_activate_first_inactive() or chained
2551008847f6SNeilBrown 			 * queueing.  Let's put @pwq back on mayday list so
2552008847f6SNeilBrown 			 * that such back-to-back work items, which may be
2553008847f6SNeilBrown 			 * being used to relieve memory pressure, don't
2554008847f6SNeilBrown 			 * incur MAYDAY_INTERVAL delay inbetween.
2555008847f6SNeilBrown 			 */
25564f3f4cf3SLai Jiangshan 			if (pwq->nr_active && need_to_create_worker(pool)) {
2557a9b8a985SSebastian Andrzej Siewior 				raw_spin_lock(&wq_mayday_lock);
2558e66b39afSTejun Heo 				/*
2559e66b39afSTejun Heo 				 * Queue iff we aren't racing destruction
2560e66b39afSTejun Heo 				 * and somebody else hasn't queued it already.
2561e66b39afSTejun Heo 				 */
2562e66b39afSTejun Heo 				if (wq->rescuer && list_empty(&pwq->mayday_node)) {
2563008847f6SNeilBrown 					get_pwq(pwq);
2564e66b39afSTejun Heo 					list_add_tail(&pwq->mayday_node, &wq->maydays);
2565e66b39afSTejun Heo 				}
2566a9b8a985SSebastian Andrzej Siewior 				raw_spin_unlock(&wq_mayday_lock);
2567008847f6SNeilBrown 			}
2568008847f6SNeilBrown 		}
2569008847f6SNeilBrown 
2570008847f6SNeilBrown 		/*
257177668c8bSLai Jiangshan 		 * Put the reference grabbed by send_mayday().  @pool won't
257213b1d625SLai Jiangshan 		 * go away while we're still attached to it.
257377668c8bSLai Jiangshan 		 */
257477668c8bSLai Jiangshan 		put_pwq(pwq);
257577668c8bSLai Jiangshan 
257677668c8bSLai Jiangshan 		/*
2577d8ca83e6SLai Jiangshan 		 * Leave this pool.  If need_more_worker() is %true, notify a
25787576958aSTejun Heo 		 * regular worker; otherwise, we end up with 0 concurrency
25797576958aSTejun Heo 		 * and stalling the execution.
25807576958aSTejun Heo 		 */
2581d8ca83e6SLai Jiangshan 		if (need_more_worker(pool))
258263d95a91STejun Heo 			wake_up_worker(pool);
25837576958aSTejun Heo 
2584a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
258513b1d625SLai Jiangshan 
2586a2d812a2STejun Heo 		worker_detach_from_pool(rescuer);
258713b1d625SLai Jiangshan 
2588a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&wq_mayday_lock);
25891da177e4SLinus Torvalds 	}
25901da177e4SLinus Torvalds 
2591a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&wq_mayday_lock);
2592493a1724STejun Heo 
25934d595b86SLai Jiangshan 	if (should_stop) {
25944d595b86SLai Jiangshan 		__set_current_state(TASK_RUNNING);
2595197f6accSTejun Heo 		set_pf_worker(false);
25964d595b86SLai Jiangshan 		return 0;
25974d595b86SLai Jiangshan 	}
25984d595b86SLai Jiangshan 
2599111c225aSTejun Heo 	/* rescuers should never participate in concurrency management */
2600111c225aSTejun Heo 	WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2601e22bee78STejun Heo 	schedule();
2602e22bee78STejun Heo 	goto repeat;
26031da177e4SLinus Torvalds }
26041da177e4SLinus Torvalds 
2605fca839c0STejun Heo /**
2606fca839c0STejun Heo  * check_flush_dependency - check for flush dependency sanity
2607fca839c0STejun Heo  * @target_wq: workqueue being flushed
2608fca839c0STejun Heo  * @target_work: work item being flushed (NULL for workqueue flushes)
2609fca839c0STejun Heo  *
2610fca839c0STejun Heo  * %current is trying to flush the whole @target_wq or @target_work on it.
2611fca839c0STejun Heo  * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
2612fca839c0STejun Heo  * reclaiming memory or running on a workqueue which doesn't have
2613fca839c0STejun Heo  * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
2614fca839c0STejun Heo  * a deadlock.
2615fca839c0STejun Heo  */
2616fca839c0STejun Heo static void check_flush_dependency(struct workqueue_struct *target_wq,
2617fca839c0STejun Heo 				   struct work_struct *target_work)
2618fca839c0STejun Heo {
2619fca839c0STejun Heo 	work_func_t target_func = target_work ? target_work->func : NULL;
2620fca839c0STejun Heo 	struct worker *worker;
2621fca839c0STejun Heo 
2622fca839c0STejun Heo 	if (target_wq->flags & WQ_MEM_RECLAIM)
2623fca839c0STejun Heo 		return;
2624fca839c0STejun Heo 
2625fca839c0STejun Heo 	worker = current_wq_worker();
2626fca839c0STejun Heo 
2627fca839c0STejun Heo 	WARN_ONCE(current->flags & PF_MEMALLOC,
2628d75f773cSSakari Ailus 		  "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps",
2629fca839c0STejun Heo 		  current->pid, current->comm, target_wq->name, target_func);
263023d11a58STejun Heo 	WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
263123d11a58STejun Heo 			      (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
2632d75f773cSSakari Ailus 		  "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps",
2633fca839c0STejun Heo 		  worker->current_pwq->wq->name, worker->current_func,
2634fca839c0STejun Heo 		  target_wq->name, target_func);
2635fca839c0STejun Heo }
2636fca839c0STejun Heo 
2637fc2e4d70SOleg Nesterov struct wq_barrier {
2638fc2e4d70SOleg Nesterov 	struct work_struct	work;
2639fc2e4d70SOleg Nesterov 	struct completion	done;
26402607d7a6STejun Heo 	struct task_struct	*task;	/* purely informational */
2641fc2e4d70SOleg Nesterov };
2642fc2e4d70SOleg Nesterov 
2643fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
2644fc2e4d70SOleg Nesterov {
2645fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2646fc2e4d70SOleg Nesterov 	complete(&barr->done);
2647fc2e4d70SOleg Nesterov }
2648fc2e4d70SOleg Nesterov 
26494690c4abSTejun Heo /**
26504690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
2651112202d9STejun Heo  * @pwq: pwq to insert barrier into
26524690c4abSTejun Heo  * @barr: wq_barrier to insert
2653affee4b2STejun Heo  * @target: target work to attach @barr to
2654affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
26554690c4abSTejun Heo  *
2656affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
2657affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
2658affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
2659affee4b2STejun Heo  * cpu.
2660affee4b2STejun Heo  *
2661affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
2662affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
2663affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
2664affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
2665affee4b2STejun Heo  * after a work with LINKED flag set.
2666affee4b2STejun Heo  *
2667affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
2668112202d9STejun Heo  * underneath us, so we can't reliably determine pwq from @target.
26694690c4abSTejun Heo  *
26704690c4abSTejun Heo  * CONTEXT:
2671a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
26724690c4abSTejun Heo  */
2673112202d9STejun Heo static void insert_wq_barrier(struct pool_workqueue *pwq,
2674affee4b2STejun Heo 			      struct wq_barrier *barr,
2675affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
2676fc2e4d70SOleg Nesterov {
2677d812796eSLai Jiangshan 	unsigned int work_flags = 0;
2678d812796eSLai Jiangshan 	unsigned int work_color;
2679affee4b2STejun Heo 	struct list_head *head;
2680affee4b2STejun Heo 
2681dc186ad7SThomas Gleixner 	/*
2682d565ed63STejun Heo 	 * debugobject calls are safe here even with pool->lock locked
2683dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
2684dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
2685dc186ad7SThomas Gleixner 	 * might deadlock.
2686dc186ad7SThomas Gleixner 	 */
2687ca1cab37SAndrew Morton 	INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
268822df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
268952fa5bc5SBoqun Feng 
2690fd1a5b04SByungchul Park 	init_completion_map(&barr->done, &target->lockdep_map);
2691fd1a5b04SByungchul Park 
26922607d7a6STejun Heo 	barr->task = current;
269383c22520SOleg Nesterov 
2694018f3a13SLai Jiangshan 	/* The barrier work item does not participate in pwq->nr_active. */
2695018f3a13SLai Jiangshan 	work_flags |= WORK_STRUCT_INACTIVE;
2696018f3a13SLai Jiangshan 
2697affee4b2STejun Heo 	/*
2698affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
2699affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
2700affee4b2STejun Heo 	 */
2701d812796eSLai Jiangshan 	if (worker) {
2702affee4b2STejun Heo 		head = worker->scheduled.next;
2703d812796eSLai Jiangshan 		work_color = worker->current_color;
2704d812796eSLai Jiangshan 	} else {
2705affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
2706affee4b2STejun Heo 
2707affee4b2STejun Heo 		head = target->entry.next;
2708affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
2709d21cece0SLai Jiangshan 		work_flags |= *bits & WORK_STRUCT_LINKED;
2710d812796eSLai Jiangshan 		work_color = get_work_color(*bits);
2711affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
2712affee4b2STejun Heo 	}
2713affee4b2STejun Heo 
2714d812796eSLai Jiangshan 	pwq->nr_in_flight[work_color]++;
2715d812796eSLai Jiangshan 	work_flags |= work_color_to_flags(work_color);
2716d812796eSLai Jiangshan 
2717dc186ad7SThomas Gleixner 	debug_work_activate(&barr->work);
2718d21cece0SLai Jiangshan 	insert_work(pwq, &barr->work, head, work_flags);
2719fc2e4d70SOleg Nesterov }
2720fc2e4d70SOleg Nesterov 
272173f53c4aSTejun Heo /**
2722112202d9STejun Heo  * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
272373f53c4aSTejun Heo  * @wq: workqueue being flushed
272473f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
272573f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
272673f53c4aSTejun Heo  *
2727112202d9STejun Heo  * Prepare pwqs for workqueue flushing.
272873f53c4aSTejun Heo  *
2729112202d9STejun Heo  * If @flush_color is non-negative, flush_color on all pwqs should be
2730112202d9STejun Heo  * -1.  If no pwq has in-flight commands at the specified color, all
2731112202d9STejun Heo  * pwq->flush_color's stay at -1 and %false is returned.  If any pwq
2732112202d9STejun Heo  * has in flight commands, its pwq->flush_color is set to
2733112202d9STejun Heo  * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
273473f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
273573f53c4aSTejun Heo  *
273673f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
273773f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
273873f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
273973f53c4aSTejun Heo  * is returned.
274073f53c4aSTejun Heo  *
2741112202d9STejun Heo  * If @work_color is non-negative, all pwqs should have the same
274273f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
274373f53c4aSTejun Heo  * advanced to @work_color.
274473f53c4aSTejun Heo  *
274573f53c4aSTejun Heo  * CONTEXT:
27463c25a55dSLai Jiangshan  * mutex_lock(wq->mutex).
274773f53c4aSTejun Heo  *
2748d185af30SYacine Belkadi  * Return:
274973f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
275073f53c4aSTejun Heo  * otherwise.
275173f53c4aSTejun Heo  */
2752112202d9STejun Heo static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
275373f53c4aSTejun Heo 				      int flush_color, int work_color)
27541da177e4SLinus Torvalds {
275573f53c4aSTejun Heo 	bool wait = false;
275649e3cf44STejun Heo 	struct pool_workqueue *pwq;
27571da177e4SLinus Torvalds 
275873f53c4aSTejun Heo 	if (flush_color >= 0) {
27596183c009STejun Heo 		WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2760112202d9STejun Heo 		atomic_set(&wq->nr_pwqs_to_flush, 1);
2761dc186ad7SThomas Gleixner 	}
276214441960SOleg Nesterov 
276349e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2764112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
27651da177e4SLinus Torvalds 
2766a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
276773f53c4aSTejun Heo 
276873f53c4aSTejun Heo 		if (flush_color >= 0) {
27696183c009STejun Heo 			WARN_ON_ONCE(pwq->flush_color != -1);
277073f53c4aSTejun Heo 
2771112202d9STejun Heo 			if (pwq->nr_in_flight[flush_color]) {
2772112202d9STejun Heo 				pwq->flush_color = flush_color;
2773112202d9STejun Heo 				atomic_inc(&wq->nr_pwqs_to_flush);
277473f53c4aSTejun Heo 				wait = true;
27751da177e4SLinus Torvalds 			}
277673f53c4aSTejun Heo 		}
277773f53c4aSTejun Heo 
277873f53c4aSTejun Heo 		if (work_color >= 0) {
27796183c009STejun Heo 			WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2780112202d9STejun Heo 			pwq->work_color = work_color;
278173f53c4aSTejun Heo 		}
278273f53c4aSTejun Heo 
2783a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
27841da177e4SLinus Torvalds 	}
27851da177e4SLinus Torvalds 
2786112202d9STejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
278773f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
278873f53c4aSTejun Heo 
278973f53c4aSTejun Heo 	return wait;
279083c22520SOleg Nesterov }
27911da177e4SLinus Torvalds 
27920fcb78c2SRolf Eike Beer /**
27931da177e4SLinus Torvalds  * flush_workqueue - ensure that any scheduled work has run to completion.
27940fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
27951da177e4SLinus Torvalds  *
2796c5aa87bbSTejun Heo  * This function sleeps until all work items which were queued on entry
2797c5aa87bbSTejun Heo  * have finished execution, but it is not livelocked by new incoming ones.
27981da177e4SLinus Torvalds  */
27997ad5b3a5SHarvey Harrison void flush_workqueue(struct workqueue_struct *wq)
28001da177e4SLinus Torvalds {
280173f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
280273f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
280373f53c4aSTejun Heo 		.flush_color = -1,
2804fd1a5b04SByungchul Park 		.done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map),
280573f53c4aSTejun Heo 	};
280673f53c4aSTejun Heo 	int next_color;
2807b1f4ec17SOleg Nesterov 
28083347fa09STejun Heo 	if (WARN_ON(!wq_online))
28093347fa09STejun Heo 		return;
28103347fa09STejun Heo 
281187915adcSJohannes Berg 	lock_map_acquire(&wq->lockdep_map);
281287915adcSJohannes Berg 	lock_map_release(&wq->lockdep_map);
281387915adcSJohannes Berg 
28143c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
281573f53c4aSTejun Heo 
281673f53c4aSTejun Heo 	/*
281773f53c4aSTejun Heo 	 * Start-to-wait phase
281873f53c4aSTejun Heo 	 */
281973f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
282073f53c4aSTejun Heo 
282173f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
282273f53c4aSTejun Heo 		/*
282373f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
282473f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
282573f53c4aSTejun Heo 		 * by one.
282673f53c4aSTejun Heo 		 */
28276183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
282873f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
282973f53c4aSTejun Heo 		wq->work_color = next_color;
283073f53c4aSTejun Heo 
283173f53c4aSTejun Heo 		if (!wq->first_flusher) {
283273f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
28336183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
283473f53c4aSTejun Heo 
283573f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
283673f53c4aSTejun Heo 
2837112202d9STejun Heo 			if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
283873f53c4aSTejun Heo 						       wq->work_color)) {
283973f53c4aSTejun Heo 				/* nothing to flush, done */
284073f53c4aSTejun Heo 				wq->flush_color = next_color;
284173f53c4aSTejun Heo 				wq->first_flusher = NULL;
284273f53c4aSTejun Heo 				goto out_unlock;
284373f53c4aSTejun Heo 			}
284473f53c4aSTejun Heo 		} else {
284573f53c4aSTejun Heo 			/* wait in queue */
28466183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
284773f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
2848112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
284973f53c4aSTejun Heo 		}
285073f53c4aSTejun Heo 	} else {
285173f53c4aSTejun Heo 		/*
285273f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
285373f53c4aSTejun Heo 		 * The next flush completion will assign us
285473f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
285573f53c4aSTejun Heo 		 */
285673f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
285773f53c4aSTejun Heo 	}
285873f53c4aSTejun Heo 
2859fca839c0STejun Heo 	check_flush_dependency(wq, NULL);
2860fca839c0STejun Heo 
28613c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
286273f53c4aSTejun Heo 
286373f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
286473f53c4aSTejun Heo 
286573f53c4aSTejun Heo 	/*
286673f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
286773f53c4aSTejun Heo 	 *
286873f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
286973f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
287073f53c4aSTejun Heo 	 */
287100d5d15bSChris Wilson 	if (READ_ONCE(wq->first_flusher) != &this_flusher)
287273f53c4aSTejun Heo 		return;
287373f53c4aSTejun Heo 
28743c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
287573f53c4aSTejun Heo 
28764ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
28774ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
28784ce48b37STejun Heo 		goto out_unlock;
28794ce48b37STejun Heo 
288000d5d15bSChris Wilson 	WRITE_ONCE(wq->first_flusher, NULL);
288173f53c4aSTejun Heo 
28826183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&this_flusher.list));
28836183c009STejun Heo 	WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
288473f53c4aSTejun Heo 
288573f53c4aSTejun Heo 	while (true) {
288673f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
288773f53c4aSTejun Heo 
288873f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
288973f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
289073f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
289173f53c4aSTejun Heo 				break;
289273f53c4aSTejun Heo 			list_del_init(&next->list);
289373f53c4aSTejun Heo 			complete(&next->done);
289473f53c4aSTejun Heo 		}
289573f53c4aSTejun Heo 
28966183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
289773f53c4aSTejun Heo 			     wq->flush_color != work_next_color(wq->work_color));
289873f53c4aSTejun Heo 
289973f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
290073f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
290173f53c4aSTejun Heo 
290273f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
290373f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
290473f53c4aSTejun Heo 			/*
290573f53c4aSTejun Heo 			 * Assign the same color to all overflowed
290673f53c4aSTejun Heo 			 * flushers, advance work_color and append to
290773f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
290873f53c4aSTejun Heo 			 * phase for these overflowed flushers.
290973f53c4aSTejun Heo 			 */
291073f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
291173f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
291273f53c4aSTejun Heo 
291373f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
291473f53c4aSTejun Heo 
291573f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
291673f53c4aSTejun Heo 					      &wq->flusher_queue);
2917112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
291873f53c4aSTejun Heo 		}
291973f53c4aSTejun Heo 
292073f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
29216183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != wq->work_color);
292273f53c4aSTejun Heo 			break;
292373f53c4aSTejun Heo 		}
292473f53c4aSTejun Heo 
292573f53c4aSTejun Heo 		/*
292673f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
2927112202d9STejun Heo 		 * the new first flusher and arm pwqs.
292873f53c4aSTejun Heo 		 */
29296183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color == wq->work_color);
29306183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color != next->flush_color);
293173f53c4aSTejun Heo 
293273f53c4aSTejun Heo 		list_del_init(&next->list);
293373f53c4aSTejun Heo 		wq->first_flusher = next;
293473f53c4aSTejun Heo 
2935112202d9STejun Heo 		if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
293673f53c4aSTejun Heo 			break;
293773f53c4aSTejun Heo 
293873f53c4aSTejun Heo 		/*
293973f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
294073f53c4aSTejun Heo 		 * flusher and repeat cascading.
294173f53c4aSTejun Heo 		 */
294273f53c4aSTejun Heo 		wq->first_flusher = NULL;
294373f53c4aSTejun Heo 	}
294473f53c4aSTejun Heo 
294573f53c4aSTejun Heo out_unlock:
29463c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
29471da177e4SLinus Torvalds }
29481dadafa8STim Gardner EXPORT_SYMBOL(flush_workqueue);
29491da177e4SLinus Torvalds 
29509c5a2ba7STejun Heo /**
29519c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
29529c5a2ba7STejun Heo  * @wq: workqueue to drain
29539c5a2ba7STejun Heo  *
29549c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
29559c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
29569c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
2957b749b1b6SChen Hanxiao  * repeatedly until it becomes empty.  The number of flushing is determined
29589c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
29599c5a2ba7STejun Heo  * takes too long.
29609c5a2ba7STejun Heo  */
29619c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
29629c5a2ba7STejun Heo {
29639c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
296449e3cf44STejun Heo 	struct pool_workqueue *pwq;
29659c5a2ba7STejun Heo 
29669c5a2ba7STejun Heo 	/*
29679c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
29689c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
2969618b01ebSTejun Heo 	 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
29709c5a2ba7STejun Heo 	 */
297187fc741eSLai Jiangshan 	mutex_lock(&wq->mutex);
29729c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
2973618b01ebSTejun Heo 		wq->flags |= __WQ_DRAINING;
297487fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
29759c5a2ba7STejun Heo reflush:
29769c5a2ba7STejun Heo 	flush_workqueue(wq);
29779c5a2ba7STejun Heo 
2978b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
297976af4d93STejun Heo 
298049e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2981fa2563e4SThomas Tuttle 		bool drained;
29829c5a2ba7STejun Heo 
2983a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
2984f97a4a1aSLai Jiangshan 		drained = !pwq->nr_active && list_empty(&pwq->inactive_works);
2985a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
2986fa2563e4SThomas Tuttle 
2987fa2563e4SThomas Tuttle 		if (drained)
29889c5a2ba7STejun Heo 			continue;
29899c5a2ba7STejun Heo 
29909c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
29919c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2992e9ad2eb3SStephen Zhang 			pr_warn("workqueue %s: %s() isn't complete after %u tries\n",
2993e9ad2eb3SStephen Zhang 				wq->name, __func__, flush_cnt);
299476af4d93STejun Heo 
2995b09f4fd3SLai Jiangshan 		mutex_unlock(&wq->mutex);
29969c5a2ba7STejun Heo 		goto reflush;
29979c5a2ba7STejun Heo 	}
29989c5a2ba7STejun Heo 
29999c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
3000618b01ebSTejun Heo 		wq->flags &= ~__WQ_DRAINING;
300187fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
30029c5a2ba7STejun Heo }
30039c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
30049c5a2ba7STejun Heo 
3005d6e89786SJohannes Berg static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
3006d6e89786SJohannes Berg 			     bool from_cancel)
3007baf59022STejun Heo {
3008baf59022STejun Heo 	struct worker *worker = NULL;
3009c9e7cf27STejun Heo 	struct worker_pool *pool;
3010112202d9STejun Heo 	struct pool_workqueue *pwq;
3011baf59022STejun Heo 
3012baf59022STejun Heo 	might_sleep();
3013baf59022STejun Heo 
301424acfb71SThomas Gleixner 	rcu_read_lock();
3015fa1b54e6STejun Heo 	pool = get_work_pool(work);
3016fa1b54e6STejun Heo 	if (!pool) {
301724acfb71SThomas Gleixner 		rcu_read_unlock();
3018fa1b54e6STejun Heo 		return false;
3019fa1b54e6STejun Heo 	}
3020fa1b54e6STejun Heo 
3021a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
30220b3dae68SLai Jiangshan 	/* see the comment in try_to_grab_pending() with the same code */
3023112202d9STejun Heo 	pwq = get_work_pwq(work);
3024112202d9STejun Heo 	if (pwq) {
3025112202d9STejun Heo 		if (unlikely(pwq->pool != pool))
3026baf59022STejun Heo 			goto already_gone;
3027606a5020STejun Heo 	} else {
3028c9e7cf27STejun Heo 		worker = find_worker_executing_work(pool, work);
3029baf59022STejun Heo 		if (!worker)
3030baf59022STejun Heo 			goto already_gone;
3031112202d9STejun Heo 		pwq = worker->current_pwq;
3032606a5020STejun Heo 	}
3033baf59022STejun Heo 
3034fca839c0STejun Heo 	check_flush_dependency(pwq->wq, work);
3035fca839c0STejun Heo 
3036112202d9STejun Heo 	insert_wq_barrier(pwq, barr, work, worker);
3037a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
3038baf59022STejun Heo 
3039e159489bSTejun Heo 	/*
3040a1d14934SPeter Zijlstra 	 * Force a lock recursion deadlock when using flush_work() inside a
3041a1d14934SPeter Zijlstra 	 * single-threaded or rescuer equipped workqueue.
3042a1d14934SPeter Zijlstra 	 *
3043a1d14934SPeter Zijlstra 	 * For single threaded workqueues the deadlock happens when the work
3044a1d14934SPeter Zijlstra 	 * is after the work issuing the flush_work(). For rescuer equipped
3045a1d14934SPeter Zijlstra 	 * workqueues the deadlock happens when the rescuer stalls, blocking
3046a1d14934SPeter Zijlstra 	 * forward progress.
3047e159489bSTejun Heo 	 */
3048d6e89786SJohannes Berg 	if (!from_cancel &&
3049d6e89786SJohannes Berg 	    (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)) {
3050112202d9STejun Heo 		lock_map_acquire(&pwq->wq->lockdep_map);
3051112202d9STejun Heo 		lock_map_release(&pwq->wq->lockdep_map);
3052a1d14934SPeter Zijlstra 	}
305324acfb71SThomas Gleixner 	rcu_read_unlock();
3054baf59022STejun Heo 	return true;
3055baf59022STejun Heo already_gone:
3056a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
305724acfb71SThomas Gleixner 	rcu_read_unlock();
3058baf59022STejun Heo 	return false;
3059baf59022STejun Heo }
3060baf59022STejun Heo 
3061d6e89786SJohannes Berg static bool __flush_work(struct work_struct *work, bool from_cancel)
3062d6e89786SJohannes Berg {
3063d6e89786SJohannes Berg 	struct wq_barrier barr;
3064d6e89786SJohannes Berg 
3065d6e89786SJohannes Berg 	if (WARN_ON(!wq_online))
3066d6e89786SJohannes Berg 		return false;
3067d6e89786SJohannes Berg 
30684d43d395STetsuo Handa 	if (WARN_ON(!work->func))
30694d43d395STetsuo Handa 		return false;
30704d43d395STetsuo Handa 
307187915adcSJohannes Berg 	if (!from_cancel) {
307287915adcSJohannes Berg 		lock_map_acquire(&work->lockdep_map);
307387915adcSJohannes Berg 		lock_map_release(&work->lockdep_map);
307487915adcSJohannes Berg 	}
307587915adcSJohannes Berg 
3076d6e89786SJohannes Berg 	if (start_flush_work(work, &barr, from_cancel)) {
3077d6e89786SJohannes Berg 		wait_for_completion(&barr.done);
3078d6e89786SJohannes Berg 		destroy_work_on_stack(&barr.work);
3079d6e89786SJohannes Berg 		return true;
3080d6e89786SJohannes Berg 	} else {
3081d6e89786SJohannes Berg 		return false;
3082d6e89786SJohannes Berg 	}
3083d6e89786SJohannes Berg }
3084d6e89786SJohannes Berg 
3085db700897SOleg Nesterov /**
3086401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
3087401a8d04STejun Heo  * @work: the work to flush
3088db700897SOleg Nesterov  *
3089606a5020STejun Heo  * Wait until @work has finished execution.  @work is guaranteed to be idle
3090606a5020STejun Heo  * on return if it hasn't been requeued since flush started.
3091401a8d04STejun Heo  *
3092d185af30SYacine Belkadi  * Return:
3093401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3094401a8d04STejun Heo  * %false if it was already idle.
3095db700897SOleg Nesterov  */
3096401a8d04STejun Heo bool flush_work(struct work_struct *work)
3097db700897SOleg Nesterov {
3098d6e89786SJohannes Berg 	return __flush_work(work, false);
3099606a5020STejun Heo }
3100db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
3101db700897SOleg Nesterov 
31028603e1b3STejun Heo struct cwt_wait {
3103ac6424b9SIngo Molnar 	wait_queue_entry_t		wait;
31048603e1b3STejun Heo 	struct work_struct	*work;
31058603e1b3STejun Heo };
31068603e1b3STejun Heo 
3107ac6424b9SIngo Molnar static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
31088603e1b3STejun Heo {
31098603e1b3STejun Heo 	struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
31108603e1b3STejun Heo 
31118603e1b3STejun Heo 	if (cwait->work != key)
31128603e1b3STejun Heo 		return 0;
31138603e1b3STejun Heo 	return autoremove_wake_function(wait, mode, sync, key);
31148603e1b3STejun Heo }
31158603e1b3STejun Heo 
311636e227d2STejun Heo static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
3117401a8d04STejun Heo {
31188603e1b3STejun Heo 	static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
3119bbb68dfaSTejun Heo 	unsigned long flags;
31201f1f642eSOleg Nesterov 	int ret;
31211f1f642eSOleg Nesterov 
31221f1f642eSOleg Nesterov 	do {
3123bbb68dfaSTejun Heo 		ret = try_to_grab_pending(work, is_dwork, &flags);
3124bbb68dfaSTejun Heo 		/*
31258603e1b3STejun Heo 		 * If someone else is already canceling, wait for it to
31268603e1b3STejun Heo 		 * finish.  flush_work() doesn't work for PREEMPT_NONE
31278603e1b3STejun Heo 		 * because we may get scheduled between @work's completion
31288603e1b3STejun Heo 		 * and the other canceling task resuming and clearing
31298603e1b3STejun Heo 		 * CANCELING - flush_work() will return false immediately
31308603e1b3STejun Heo 		 * as @work is no longer busy, try_to_grab_pending() will
31318603e1b3STejun Heo 		 * return -ENOENT as @work is still being canceled and the
31328603e1b3STejun Heo 		 * other canceling task won't be able to clear CANCELING as
31338603e1b3STejun Heo 		 * we're hogging the CPU.
31348603e1b3STejun Heo 		 *
31358603e1b3STejun Heo 		 * Let's wait for completion using a waitqueue.  As this
31368603e1b3STejun Heo 		 * may lead to the thundering herd problem, use a custom
31378603e1b3STejun Heo 		 * wake function which matches @work along with exclusive
31388603e1b3STejun Heo 		 * wait and wakeup.
3139bbb68dfaSTejun Heo 		 */
31408603e1b3STejun Heo 		if (unlikely(ret == -ENOENT)) {
31418603e1b3STejun Heo 			struct cwt_wait cwait;
31428603e1b3STejun Heo 
31438603e1b3STejun Heo 			init_wait(&cwait.wait);
31448603e1b3STejun Heo 			cwait.wait.func = cwt_wakefn;
31458603e1b3STejun Heo 			cwait.work = work;
31468603e1b3STejun Heo 
31478603e1b3STejun Heo 			prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
31488603e1b3STejun Heo 						  TASK_UNINTERRUPTIBLE);
31498603e1b3STejun Heo 			if (work_is_canceling(work))
31508603e1b3STejun Heo 				schedule();
31518603e1b3STejun Heo 			finish_wait(&cancel_waitq, &cwait.wait);
31528603e1b3STejun Heo 		}
31531f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
31541f1f642eSOleg Nesterov 
3155bbb68dfaSTejun Heo 	/* tell other tasks trying to grab @work to back off */
3156bbb68dfaSTejun Heo 	mark_work_canceling(work);
3157bbb68dfaSTejun Heo 	local_irq_restore(flags);
3158bbb68dfaSTejun Heo 
31593347fa09STejun Heo 	/*
31603347fa09STejun Heo 	 * This allows canceling during early boot.  We know that @work
31613347fa09STejun Heo 	 * isn't executing.
31623347fa09STejun Heo 	 */
31633347fa09STejun Heo 	if (wq_online)
3164d6e89786SJohannes Berg 		__flush_work(work, true);
31653347fa09STejun Heo 
31667a22ad75STejun Heo 	clear_work_data(work);
31678603e1b3STejun Heo 
31688603e1b3STejun Heo 	/*
31698603e1b3STejun Heo 	 * Paired with prepare_to_wait() above so that either
31708603e1b3STejun Heo 	 * waitqueue_active() is visible here or !work_is_canceling() is
31718603e1b3STejun Heo 	 * visible there.
31728603e1b3STejun Heo 	 */
31738603e1b3STejun Heo 	smp_mb();
31748603e1b3STejun Heo 	if (waitqueue_active(&cancel_waitq))
31758603e1b3STejun Heo 		__wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
31768603e1b3STejun Heo 
31771f1f642eSOleg Nesterov 	return ret;
31781f1f642eSOleg Nesterov }
31791f1f642eSOleg Nesterov 
31806e84d644SOleg Nesterov /**
3181401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
3182401a8d04STejun Heo  * @work: the work to cancel
31836e84d644SOleg Nesterov  *
3184401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
3185401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
3186401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
3187401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
31881f1f642eSOleg Nesterov  *
3189401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
3190401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
31916e84d644SOleg Nesterov  *
3192401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
31936e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
3194401a8d04STejun Heo  *
3195d185af30SYacine Belkadi  * Return:
3196401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
31976e84d644SOleg Nesterov  */
3198401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
31996e84d644SOleg Nesterov {
320036e227d2STejun Heo 	return __cancel_work_timer(work, false);
3201b89deed3SOleg Nesterov }
320228e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
3203b89deed3SOleg Nesterov 
32046e84d644SOleg Nesterov /**
3205401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
3206401a8d04STejun Heo  * @dwork: the delayed work to flush
32076e84d644SOleg Nesterov  *
3208401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
3209401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
3210401a8d04STejun Heo  * considers the last queueing instance of @dwork.
32111f1f642eSOleg Nesterov  *
3212d185af30SYacine Belkadi  * Return:
3213401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3214401a8d04STejun Heo  * %false if it was already idle.
32156e84d644SOleg Nesterov  */
3216401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
3217401a8d04STejun Heo {
32188930cabaSTejun Heo 	local_irq_disable();
3219401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
322060c057bcSLai Jiangshan 		__queue_work(dwork->cpu, dwork->wq, &dwork->work);
32218930cabaSTejun Heo 	local_irq_enable();
3222401a8d04STejun Heo 	return flush_work(&dwork->work);
3223401a8d04STejun Heo }
3224401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
3225401a8d04STejun Heo 
322605f0fe6bSTejun Heo /**
322705f0fe6bSTejun Heo  * flush_rcu_work - wait for a rwork to finish executing the last queueing
322805f0fe6bSTejun Heo  * @rwork: the rcu work to flush
322905f0fe6bSTejun Heo  *
323005f0fe6bSTejun Heo  * Return:
323105f0fe6bSTejun Heo  * %true if flush_rcu_work() waited for the work to finish execution,
323205f0fe6bSTejun Heo  * %false if it was already idle.
323305f0fe6bSTejun Heo  */
323405f0fe6bSTejun Heo bool flush_rcu_work(struct rcu_work *rwork)
323505f0fe6bSTejun Heo {
323605f0fe6bSTejun Heo 	if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
323705f0fe6bSTejun Heo 		rcu_barrier();
323805f0fe6bSTejun Heo 		flush_work(&rwork->work);
323905f0fe6bSTejun Heo 		return true;
324005f0fe6bSTejun Heo 	} else {
324105f0fe6bSTejun Heo 		return flush_work(&rwork->work);
324205f0fe6bSTejun Heo 	}
324305f0fe6bSTejun Heo }
324405f0fe6bSTejun Heo EXPORT_SYMBOL(flush_rcu_work);
324505f0fe6bSTejun Heo 
3246f72b8792SJens Axboe static bool __cancel_work(struct work_struct *work, bool is_dwork)
3247f72b8792SJens Axboe {
3248f72b8792SJens Axboe 	unsigned long flags;
3249f72b8792SJens Axboe 	int ret;
3250f72b8792SJens Axboe 
3251f72b8792SJens Axboe 	do {
3252f72b8792SJens Axboe 		ret = try_to_grab_pending(work, is_dwork, &flags);
3253f72b8792SJens Axboe 	} while (unlikely(ret == -EAGAIN));
3254f72b8792SJens Axboe 
3255f72b8792SJens Axboe 	if (unlikely(ret < 0))
3256f72b8792SJens Axboe 		return false;
3257f72b8792SJens Axboe 
3258f72b8792SJens Axboe 	set_work_pool_and_clear_pending(work, get_work_pool_id(work));
3259f72b8792SJens Axboe 	local_irq_restore(flags);
3260f72b8792SJens Axboe 	return ret;
3261f72b8792SJens Axboe }
3262f72b8792SJens Axboe 
3263401a8d04STejun Heo /**
326457b30ae7STejun Heo  * cancel_delayed_work - cancel a delayed work
326557b30ae7STejun Heo  * @dwork: delayed_work to cancel
326609383498STejun Heo  *
3267d185af30SYacine Belkadi  * Kill off a pending delayed_work.
3268d185af30SYacine Belkadi  *
3269d185af30SYacine Belkadi  * Return: %true if @dwork was pending and canceled; %false if it wasn't
3270d185af30SYacine Belkadi  * pending.
3271d185af30SYacine Belkadi  *
3272d185af30SYacine Belkadi  * Note:
3273d185af30SYacine Belkadi  * The work callback function may still be running on return, unless
3274d185af30SYacine Belkadi  * it returns %true and the work doesn't re-arm itself.  Explicitly flush or
3275d185af30SYacine Belkadi  * use cancel_delayed_work_sync() to wait on it.
327609383498STejun Heo  *
327757b30ae7STejun Heo  * This function is safe to call from any context including IRQ handler.
327809383498STejun Heo  */
327957b30ae7STejun Heo bool cancel_delayed_work(struct delayed_work *dwork)
328009383498STejun Heo {
3281f72b8792SJens Axboe 	return __cancel_work(&dwork->work, true);
328209383498STejun Heo }
328357b30ae7STejun Heo EXPORT_SYMBOL(cancel_delayed_work);
328409383498STejun Heo 
328509383498STejun Heo /**
3286401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3287401a8d04STejun Heo  * @dwork: the delayed work cancel
3288401a8d04STejun Heo  *
3289401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
3290401a8d04STejun Heo  *
3291d185af30SYacine Belkadi  * Return:
3292401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
3293401a8d04STejun Heo  */
3294401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
32956e84d644SOleg Nesterov {
329636e227d2STejun Heo 	return __cancel_work_timer(&dwork->work, true);
32976e84d644SOleg Nesterov }
3298f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
32991da177e4SLinus Torvalds 
33000fcb78c2SRolf Eike Beer /**
330131ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
3302b6136773SAndrew Morton  * @func: the function to call
3303b6136773SAndrew Morton  *
330431ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
330531ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
3306b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
330731ddd871STejun Heo  *
3308d185af30SYacine Belkadi  * Return:
330931ddd871STejun Heo  * 0 on success, -errno on failure.
3310b6136773SAndrew Morton  */
331165f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
331215316ba8SChristoph Lameter {
331315316ba8SChristoph Lameter 	int cpu;
331438f51568SNamhyung Kim 	struct work_struct __percpu *works;
331515316ba8SChristoph Lameter 
3316b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
3317b6136773SAndrew Morton 	if (!works)
331815316ba8SChristoph Lameter 		return -ENOMEM;
3319b6136773SAndrew Morton 
3320ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
332193981800STejun Heo 
332215316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
33239bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
33249bfb1839SIngo Molnar 
33259bfb1839SIngo Molnar 		INIT_WORK(work, func);
33268de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
332715316ba8SChristoph Lameter 	}
332893981800STejun Heo 
332993981800STejun Heo 	for_each_online_cpu(cpu)
33308616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
333193981800STejun Heo 
3332ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
3333b6136773SAndrew Morton 	free_percpu(works);
333415316ba8SChristoph Lameter 	return 0;
333515316ba8SChristoph Lameter }
333615316ba8SChristoph Lameter 
3337eef6a7d5SAlan Stern /**
33381fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
33391fa44ecaSJames Bottomley  * @fn:		the function to execute
33401fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
33411fa44ecaSJames Bottomley  *		be available when the work executes)
33421fa44ecaSJames Bottomley  *
33431fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
33441fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
33451fa44ecaSJames Bottomley  *
3346d185af30SYacine Belkadi  * Return:	0 - function was executed
33471fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
33481fa44ecaSJames Bottomley  */
334965f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
33501fa44ecaSJames Bottomley {
33511fa44ecaSJames Bottomley 	if (!in_interrupt()) {
335265f27f38SDavid Howells 		fn(&ew->work);
33531fa44ecaSJames Bottomley 		return 0;
33541fa44ecaSJames Bottomley 	}
33551fa44ecaSJames Bottomley 
335665f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
33571fa44ecaSJames Bottomley 	schedule_work(&ew->work);
33581fa44ecaSJames Bottomley 
33591fa44ecaSJames Bottomley 	return 1;
33601fa44ecaSJames Bottomley }
33611fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
33621fa44ecaSJames Bottomley 
33637a4e344cSTejun Heo /**
33647a4e344cSTejun Heo  * free_workqueue_attrs - free a workqueue_attrs
33657a4e344cSTejun Heo  * @attrs: workqueue_attrs to free
33667a4e344cSTejun Heo  *
33677a4e344cSTejun Heo  * Undo alloc_workqueue_attrs().
33687a4e344cSTejun Heo  */
3369513c98d0SDaniel Jordan void free_workqueue_attrs(struct workqueue_attrs *attrs)
33707a4e344cSTejun Heo {
33717a4e344cSTejun Heo 	if (attrs) {
33727a4e344cSTejun Heo 		free_cpumask_var(attrs->cpumask);
33737a4e344cSTejun Heo 		kfree(attrs);
33747a4e344cSTejun Heo 	}
33757a4e344cSTejun Heo }
33767a4e344cSTejun Heo 
33777a4e344cSTejun Heo /**
33787a4e344cSTejun Heo  * alloc_workqueue_attrs - allocate a workqueue_attrs
33797a4e344cSTejun Heo  *
33807a4e344cSTejun Heo  * Allocate a new workqueue_attrs, initialize with default settings and
3381d185af30SYacine Belkadi  * return it.
3382d185af30SYacine Belkadi  *
3383d185af30SYacine Belkadi  * Return: The allocated new workqueue_attr on success. %NULL on failure.
33847a4e344cSTejun Heo  */
3385513c98d0SDaniel Jordan struct workqueue_attrs *alloc_workqueue_attrs(void)
33867a4e344cSTejun Heo {
33877a4e344cSTejun Heo 	struct workqueue_attrs *attrs;
33887a4e344cSTejun Heo 
3389be69d00dSThomas Gleixner 	attrs = kzalloc(sizeof(*attrs), GFP_KERNEL);
33907a4e344cSTejun Heo 	if (!attrs)
33917a4e344cSTejun Heo 		goto fail;
3392be69d00dSThomas Gleixner 	if (!alloc_cpumask_var(&attrs->cpumask, GFP_KERNEL))
33937a4e344cSTejun Heo 		goto fail;
33947a4e344cSTejun Heo 
339513e2e556STejun Heo 	cpumask_copy(attrs->cpumask, cpu_possible_mask);
33967a4e344cSTejun Heo 	return attrs;
33977a4e344cSTejun Heo fail:
33987a4e344cSTejun Heo 	free_workqueue_attrs(attrs);
33997a4e344cSTejun Heo 	return NULL;
34007a4e344cSTejun Heo }
34017a4e344cSTejun Heo 
340229c91e99STejun Heo static void copy_workqueue_attrs(struct workqueue_attrs *to,
340329c91e99STejun Heo 				 const struct workqueue_attrs *from)
340429c91e99STejun Heo {
340529c91e99STejun Heo 	to->nice = from->nice;
340629c91e99STejun Heo 	cpumask_copy(to->cpumask, from->cpumask);
34072865a8fbSShaohua Li 	/*
34082865a8fbSShaohua Li 	 * Unlike hash and equality test, this function doesn't ignore
34092865a8fbSShaohua Li 	 * ->no_numa as it is used for both pool and wq attrs.  Instead,
34102865a8fbSShaohua Li 	 * get_unbound_pool() explicitly clears ->no_numa after copying.
34112865a8fbSShaohua Li 	 */
34122865a8fbSShaohua Li 	to->no_numa = from->no_numa;
341329c91e99STejun Heo }
341429c91e99STejun Heo 
341529c91e99STejun Heo /* hash value of the content of @attr */
341629c91e99STejun Heo static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
341729c91e99STejun Heo {
341829c91e99STejun Heo 	u32 hash = 0;
341929c91e99STejun Heo 
342029c91e99STejun Heo 	hash = jhash_1word(attrs->nice, hash);
342113e2e556STejun Heo 	hash = jhash(cpumask_bits(attrs->cpumask),
342213e2e556STejun Heo 		     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
342329c91e99STejun Heo 	return hash;
342429c91e99STejun Heo }
342529c91e99STejun Heo 
342629c91e99STejun Heo /* content equality test */
342729c91e99STejun Heo static bool wqattrs_equal(const struct workqueue_attrs *a,
342829c91e99STejun Heo 			  const struct workqueue_attrs *b)
342929c91e99STejun Heo {
343029c91e99STejun Heo 	if (a->nice != b->nice)
343129c91e99STejun Heo 		return false;
343229c91e99STejun Heo 	if (!cpumask_equal(a->cpumask, b->cpumask))
343329c91e99STejun Heo 		return false;
343429c91e99STejun Heo 	return true;
343529c91e99STejun Heo }
343629c91e99STejun Heo 
34377a4e344cSTejun Heo /**
34387a4e344cSTejun Heo  * init_worker_pool - initialize a newly zalloc'd worker_pool
34397a4e344cSTejun Heo  * @pool: worker_pool to initialize
34407a4e344cSTejun Heo  *
3441402dd89dSShailendra Verma  * Initialize a newly zalloc'd @pool.  It also allocates @pool->attrs.
3442d185af30SYacine Belkadi  *
3443d185af30SYacine Belkadi  * Return: 0 on success, -errno on failure.  Even on failure, all fields
344429c91e99STejun Heo  * inside @pool proper are initialized and put_unbound_pool() can be called
344529c91e99STejun Heo  * on @pool safely to release it.
34467a4e344cSTejun Heo  */
34477a4e344cSTejun Heo static int init_worker_pool(struct worker_pool *pool)
34484e1a1f9aSTejun Heo {
3449a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_init(&pool->lock);
345029c91e99STejun Heo 	pool->id = -1;
345129c91e99STejun Heo 	pool->cpu = -1;
3452f3f90ad4STejun Heo 	pool->node = NUMA_NO_NODE;
34534e1a1f9aSTejun Heo 	pool->flags |= POOL_DISASSOCIATED;
345482607adcSTejun Heo 	pool->watchdog_ts = jiffies;
34554e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->worklist);
34564e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->idle_list);
34574e1a1f9aSTejun Heo 	hash_init(pool->busy_hash);
34584e1a1f9aSTejun Heo 
345932a6c723SKees Cook 	timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
34604e1a1f9aSTejun Heo 
346132a6c723SKees Cook 	timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
34624e1a1f9aSTejun Heo 
3463da028469SLai Jiangshan 	INIT_LIST_HEAD(&pool->workers);
34647a4e344cSTejun Heo 
34657cda9aaeSLai Jiangshan 	ida_init(&pool->worker_ida);
346629c91e99STejun Heo 	INIT_HLIST_NODE(&pool->hash_node);
346729c91e99STejun Heo 	pool->refcnt = 1;
346829c91e99STejun Heo 
346929c91e99STejun Heo 	/* shouldn't fail above this point */
3470be69d00dSThomas Gleixner 	pool->attrs = alloc_workqueue_attrs();
34717a4e344cSTejun Heo 	if (!pool->attrs)
34727a4e344cSTejun Heo 		return -ENOMEM;
34737a4e344cSTejun Heo 	return 0;
34744e1a1f9aSTejun Heo }
34754e1a1f9aSTejun Heo 
3476669de8bdSBart Van Assche #ifdef CONFIG_LOCKDEP
3477669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
3478669de8bdSBart Van Assche {
3479669de8bdSBart Van Assche 	char *lock_name;
3480669de8bdSBart Van Assche 
3481669de8bdSBart Van Assche 	lockdep_register_key(&wq->key);
3482669de8bdSBart Van Assche 	lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name);
3483669de8bdSBart Van Assche 	if (!lock_name)
3484669de8bdSBart Van Assche 		lock_name = wq->name;
348569a106c0SQian Cai 
348669a106c0SQian Cai 	wq->lock_name = lock_name;
3487669de8bdSBart Van Assche 	lockdep_init_map(&wq->lockdep_map, lock_name, &wq->key, 0);
3488669de8bdSBart Van Assche }
3489669de8bdSBart Van Assche 
3490669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
3491669de8bdSBart Van Assche {
3492669de8bdSBart Van Assche 	lockdep_unregister_key(&wq->key);
3493669de8bdSBart Van Assche }
3494669de8bdSBart Van Assche 
3495669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
3496669de8bdSBart Van Assche {
3497669de8bdSBart Van Assche 	if (wq->lock_name != wq->name)
3498669de8bdSBart Van Assche 		kfree(wq->lock_name);
3499669de8bdSBart Van Assche }
3500669de8bdSBart Van Assche #else
3501669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
3502669de8bdSBart Van Assche {
3503669de8bdSBart Van Assche }
3504669de8bdSBart Van Assche 
3505669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
3506669de8bdSBart Van Assche {
3507669de8bdSBart Van Assche }
3508669de8bdSBart Van Assche 
3509669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
3510669de8bdSBart Van Assche {
3511669de8bdSBart Van Assche }
3512669de8bdSBart Van Assche #endif
3513669de8bdSBart Van Assche 
3514e2dca7adSTejun Heo static void rcu_free_wq(struct rcu_head *rcu)
3515e2dca7adSTejun Heo {
3516e2dca7adSTejun Heo 	struct workqueue_struct *wq =
3517e2dca7adSTejun Heo 		container_of(rcu, struct workqueue_struct, rcu);
3518e2dca7adSTejun Heo 
3519669de8bdSBart Van Assche 	wq_free_lockdep(wq);
3520669de8bdSBart Van Assche 
3521e2dca7adSTejun Heo 	if (!(wq->flags & WQ_UNBOUND))
3522e2dca7adSTejun Heo 		free_percpu(wq->cpu_pwqs);
3523e2dca7adSTejun Heo 	else
3524e2dca7adSTejun Heo 		free_workqueue_attrs(wq->unbound_attrs);
3525e2dca7adSTejun Heo 
3526e2dca7adSTejun Heo 	kfree(wq);
3527e2dca7adSTejun Heo }
3528e2dca7adSTejun Heo 
352929c91e99STejun Heo static void rcu_free_pool(struct rcu_head *rcu)
353029c91e99STejun Heo {
353129c91e99STejun Heo 	struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
353229c91e99STejun Heo 
35337cda9aaeSLai Jiangshan 	ida_destroy(&pool->worker_ida);
353429c91e99STejun Heo 	free_workqueue_attrs(pool->attrs);
353529c91e99STejun Heo 	kfree(pool);
353629c91e99STejun Heo }
353729c91e99STejun Heo 
3538d8bb65abSSebastian Andrzej Siewior /* This returns with the lock held on success (pool manager is inactive). */
3539d8bb65abSSebastian Andrzej Siewior static bool wq_manager_inactive(struct worker_pool *pool)
3540d8bb65abSSebastian Andrzej Siewior {
3541a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
3542d8bb65abSSebastian Andrzej Siewior 
3543d8bb65abSSebastian Andrzej Siewior 	if (pool->flags & POOL_MANAGER_ACTIVE) {
3544a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
3545d8bb65abSSebastian Andrzej Siewior 		return false;
3546d8bb65abSSebastian Andrzej Siewior 	}
3547d8bb65abSSebastian Andrzej Siewior 	return true;
3548d8bb65abSSebastian Andrzej Siewior }
3549d8bb65abSSebastian Andrzej Siewior 
355029c91e99STejun Heo /**
355129c91e99STejun Heo  * put_unbound_pool - put a worker_pool
355229c91e99STejun Heo  * @pool: worker_pool to put
355329c91e99STejun Heo  *
355424acfb71SThomas Gleixner  * Put @pool.  If its refcnt reaches zero, it gets destroyed in RCU
3555c5aa87bbSTejun Heo  * safe manner.  get_unbound_pool() calls this function on its failure path
3556c5aa87bbSTejun Heo  * and this function should be able to release pools which went through,
3557c5aa87bbSTejun Heo  * successfully or not, init_worker_pool().
3558a892caccSTejun Heo  *
3559a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
356029c91e99STejun Heo  */
356129c91e99STejun Heo static void put_unbound_pool(struct worker_pool *pool)
356229c91e99STejun Heo {
356360f5a4bcSLai Jiangshan 	DECLARE_COMPLETION_ONSTACK(detach_completion);
356429c91e99STejun Heo 	struct worker *worker;
356529c91e99STejun Heo 
3566a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3567a892caccSTejun Heo 
3568a892caccSTejun Heo 	if (--pool->refcnt)
356929c91e99STejun Heo 		return;
357029c91e99STejun Heo 
357129c91e99STejun Heo 	/* sanity checks */
357261d0fbb4SLai Jiangshan 	if (WARN_ON(!(pool->cpu < 0)) ||
3573a892caccSTejun Heo 	    WARN_ON(!list_empty(&pool->worklist)))
357429c91e99STejun Heo 		return;
357529c91e99STejun Heo 
357629c91e99STejun Heo 	/* release id and unhash */
357729c91e99STejun Heo 	if (pool->id >= 0)
357829c91e99STejun Heo 		idr_remove(&worker_pool_idr, pool->id);
357929c91e99STejun Heo 	hash_del(&pool->hash_node);
358029c91e99STejun Heo 
3581c5aa87bbSTejun Heo 	/*
3582692b4825STejun Heo 	 * Become the manager and destroy all workers.  This prevents
3583692b4825STejun Heo 	 * @pool's workers from blocking on attach_mutex.  We're the last
3584692b4825STejun Heo 	 * manager and @pool gets freed with the flag set.
3585d8bb65abSSebastian Andrzej Siewior 	 * Because of how wq_manager_inactive() works, we will hold the
3586d8bb65abSSebastian Andrzej Siewior 	 * spinlock after a successful wait.
3587c5aa87bbSTejun Heo 	 */
3588d8bb65abSSebastian Andrzej Siewior 	rcuwait_wait_event(&manager_wait, wq_manager_inactive(pool),
3589d8bb65abSSebastian Andrzej Siewior 			   TASK_UNINTERRUPTIBLE);
3590692b4825STejun Heo 	pool->flags |= POOL_MANAGER_ACTIVE;
3591692b4825STejun Heo 
35921037de36SLai Jiangshan 	while ((worker = first_idle_worker(pool)))
359329c91e99STejun Heo 		destroy_worker(worker);
359429c91e99STejun Heo 	WARN_ON(pool->nr_workers || pool->nr_idle);
3595a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
359660f5a4bcSLai Jiangshan 
35971258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
3598da028469SLai Jiangshan 	if (!list_empty(&pool->workers))
359960f5a4bcSLai Jiangshan 		pool->detach_completion = &detach_completion;
36001258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
360160f5a4bcSLai Jiangshan 
360260f5a4bcSLai Jiangshan 	if (pool->detach_completion)
360360f5a4bcSLai Jiangshan 		wait_for_completion(pool->detach_completion);
360460f5a4bcSLai Jiangshan 
360529c91e99STejun Heo 	/* shut down the timers */
360629c91e99STejun Heo 	del_timer_sync(&pool->idle_timer);
360729c91e99STejun Heo 	del_timer_sync(&pool->mayday_timer);
360829c91e99STejun Heo 
360924acfb71SThomas Gleixner 	/* RCU protected to allow dereferences from get_work_pool() */
361025b00775SPaul E. McKenney 	call_rcu(&pool->rcu, rcu_free_pool);
361129c91e99STejun Heo }
361229c91e99STejun Heo 
361329c91e99STejun Heo /**
361429c91e99STejun Heo  * get_unbound_pool - get a worker_pool with the specified attributes
361529c91e99STejun Heo  * @attrs: the attributes of the worker_pool to get
361629c91e99STejun Heo  *
361729c91e99STejun Heo  * Obtain a worker_pool which has the same attributes as @attrs, bump the
361829c91e99STejun Heo  * reference count and return it.  If there already is a matching
361929c91e99STejun Heo  * worker_pool, it will be used; otherwise, this function attempts to
3620d185af30SYacine Belkadi  * create a new one.
3621a892caccSTejun Heo  *
3622a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
3623d185af30SYacine Belkadi  *
3624d185af30SYacine Belkadi  * Return: On success, a worker_pool with the same attributes as @attrs.
3625d185af30SYacine Belkadi  * On failure, %NULL.
362629c91e99STejun Heo  */
362729c91e99STejun Heo static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
362829c91e99STejun Heo {
362929c91e99STejun Heo 	u32 hash = wqattrs_hash(attrs);
363029c91e99STejun Heo 	struct worker_pool *pool;
3631f3f90ad4STejun Heo 	int node;
3632e2273584SXunlei Pang 	int target_node = NUMA_NO_NODE;
363329c91e99STejun Heo 
3634a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
363529c91e99STejun Heo 
363629c91e99STejun Heo 	/* do we already have a matching pool? */
363729c91e99STejun Heo 	hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
363829c91e99STejun Heo 		if (wqattrs_equal(pool->attrs, attrs)) {
363929c91e99STejun Heo 			pool->refcnt++;
36403fb1823cSLai Jiangshan 			return pool;
364129c91e99STejun Heo 		}
364229c91e99STejun Heo 	}
364329c91e99STejun Heo 
3644e2273584SXunlei Pang 	/* if cpumask is contained inside a NUMA node, we belong to that node */
3645e2273584SXunlei Pang 	if (wq_numa_enabled) {
3646e2273584SXunlei Pang 		for_each_node(node) {
3647e2273584SXunlei Pang 			if (cpumask_subset(attrs->cpumask,
3648e2273584SXunlei Pang 					   wq_numa_possible_cpumask[node])) {
3649e2273584SXunlei Pang 				target_node = node;
3650e2273584SXunlei Pang 				break;
3651e2273584SXunlei Pang 			}
3652e2273584SXunlei Pang 		}
3653e2273584SXunlei Pang 	}
3654e2273584SXunlei Pang 
365529c91e99STejun Heo 	/* nope, create a new one */
3656e2273584SXunlei Pang 	pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, target_node);
365729c91e99STejun Heo 	if (!pool || init_worker_pool(pool) < 0)
365829c91e99STejun Heo 		goto fail;
365929c91e99STejun Heo 
36608864b4e5STejun Heo 	lockdep_set_subclass(&pool->lock, 1);	/* see put_pwq() */
366129c91e99STejun Heo 	copy_workqueue_attrs(pool->attrs, attrs);
3662e2273584SXunlei Pang 	pool->node = target_node;
366329c91e99STejun Heo 
36642865a8fbSShaohua Li 	/*
36652865a8fbSShaohua Li 	 * no_numa isn't a worker_pool attribute, always clear it.  See
36662865a8fbSShaohua Li 	 * 'struct workqueue_attrs' comments for detail.
36672865a8fbSShaohua Li 	 */
36682865a8fbSShaohua Li 	pool->attrs->no_numa = false;
36692865a8fbSShaohua Li 
367029c91e99STejun Heo 	if (worker_pool_assign_id(pool) < 0)
367129c91e99STejun Heo 		goto fail;
367229c91e99STejun Heo 
367329c91e99STejun Heo 	/* create and start the initial worker */
36743347fa09STejun Heo 	if (wq_online && !create_worker(pool))
367529c91e99STejun Heo 		goto fail;
367629c91e99STejun Heo 
367729c91e99STejun Heo 	/* install */
367829c91e99STejun Heo 	hash_add(unbound_pool_hash, &pool->hash_node, hash);
36793fb1823cSLai Jiangshan 
368029c91e99STejun Heo 	return pool;
368129c91e99STejun Heo fail:
368229c91e99STejun Heo 	if (pool)
368329c91e99STejun Heo 		put_unbound_pool(pool);
368429c91e99STejun Heo 	return NULL;
368529c91e99STejun Heo }
368629c91e99STejun Heo 
36878864b4e5STejun Heo static void rcu_free_pwq(struct rcu_head *rcu)
36888864b4e5STejun Heo {
36898864b4e5STejun Heo 	kmem_cache_free(pwq_cache,
36908864b4e5STejun Heo 			container_of(rcu, struct pool_workqueue, rcu));
36918864b4e5STejun Heo }
36928864b4e5STejun Heo 
36938864b4e5STejun Heo /*
36948864b4e5STejun Heo  * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
36958864b4e5STejun Heo  * and needs to be destroyed.
36968864b4e5STejun Heo  */
36978864b4e5STejun Heo static void pwq_unbound_release_workfn(struct work_struct *work)
36988864b4e5STejun Heo {
36998864b4e5STejun Heo 	struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
37008864b4e5STejun Heo 						  unbound_release_work);
37018864b4e5STejun Heo 	struct workqueue_struct *wq = pwq->wq;
37028864b4e5STejun Heo 	struct worker_pool *pool = pwq->pool;
3703b42b0bddSYang Yingliang 	bool is_last = false;
37048864b4e5STejun Heo 
3705b42b0bddSYang Yingliang 	/*
3706b42b0bddSYang Yingliang 	 * when @pwq is not linked, it doesn't hold any reference to the
3707b42b0bddSYang Yingliang 	 * @wq, and @wq is invalid to access.
3708b42b0bddSYang Yingliang 	 */
3709b42b0bddSYang Yingliang 	if (!list_empty(&pwq->pwqs_node)) {
37108864b4e5STejun Heo 		if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
37118864b4e5STejun Heo 			return;
37128864b4e5STejun Heo 
37133c25a55dSLai Jiangshan 		mutex_lock(&wq->mutex);
37148864b4e5STejun Heo 		list_del_rcu(&pwq->pwqs_node);
3715bc0caf09STejun Heo 		is_last = list_empty(&wq->pwqs);
37163c25a55dSLai Jiangshan 		mutex_unlock(&wq->mutex);
3717b42b0bddSYang Yingliang 	}
37188864b4e5STejun Heo 
3719a892caccSTejun Heo 	mutex_lock(&wq_pool_mutex);
37208864b4e5STejun Heo 	put_unbound_pool(pool);
3721a892caccSTejun Heo 	mutex_unlock(&wq_pool_mutex);
3722a892caccSTejun Heo 
372325b00775SPaul E. McKenney 	call_rcu(&pwq->rcu, rcu_free_pwq);
37248864b4e5STejun Heo 
37258864b4e5STejun Heo 	/*
37268864b4e5STejun Heo 	 * If we're the last pwq going away, @wq is already dead and no one
3727e2dca7adSTejun Heo 	 * is gonna access it anymore.  Schedule RCU free.
37288864b4e5STejun Heo 	 */
3729669de8bdSBart Van Assche 	if (is_last) {
3730669de8bdSBart Van Assche 		wq_unregister_lockdep(wq);
373125b00775SPaul E. McKenney 		call_rcu(&wq->rcu, rcu_free_wq);
37326029a918STejun Heo 	}
3733669de8bdSBart Van Assche }
37348864b4e5STejun Heo 
37350fbd95aaSTejun Heo /**
3736699ce097STejun Heo  * pwq_adjust_max_active - update a pwq's max_active to the current setting
37370fbd95aaSTejun Heo  * @pwq: target pool_workqueue
37380fbd95aaSTejun Heo  *
3739699ce097STejun Heo  * If @pwq isn't freezing, set @pwq->max_active to the associated
3740f97a4a1aSLai Jiangshan  * workqueue's saved_max_active and activate inactive work items
3741699ce097STejun Heo  * accordingly.  If @pwq is freezing, clear @pwq->max_active to zero.
37420fbd95aaSTejun Heo  */
3743699ce097STejun Heo static void pwq_adjust_max_active(struct pool_workqueue *pwq)
37440fbd95aaSTejun Heo {
3745699ce097STejun Heo 	struct workqueue_struct *wq = pwq->wq;
3746699ce097STejun Heo 	bool freezable = wq->flags & WQ_FREEZABLE;
37473347fa09STejun Heo 	unsigned long flags;
3748699ce097STejun Heo 
3749699ce097STejun Heo 	/* for @wq->saved_max_active */
3750a357fc03SLai Jiangshan 	lockdep_assert_held(&wq->mutex);
3751699ce097STejun Heo 
3752699ce097STejun Heo 	/* fast exit for non-freezable wqs */
3753699ce097STejun Heo 	if (!freezable && pwq->max_active == wq->saved_max_active)
3754699ce097STejun Heo 		return;
3755699ce097STejun Heo 
37563347fa09STejun Heo 	/* this function can be called during early boot w/ irq disabled */
3757a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irqsave(&pwq->pool->lock, flags);
3758699ce097STejun Heo 
375974b414eaSLai Jiangshan 	/*
376074b414eaSLai Jiangshan 	 * During [un]freezing, the caller is responsible for ensuring that
376174b414eaSLai Jiangshan 	 * this function is called at least once after @workqueue_freezing
376274b414eaSLai Jiangshan 	 * is updated and visible.
376374b414eaSLai Jiangshan 	 */
376474b414eaSLai Jiangshan 	if (!freezable || !workqueue_freezing) {
376501341fbdSYunfeng Ye 		bool kick = false;
376601341fbdSYunfeng Ye 
3767699ce097STejun Heo 		pwq->max_active = wq->saved_max_active;
37680fbd95aaSTejun Heo 
3769f97a4a1aSLai Jiangshan 		while (!list_empty(&pwq->inactive_works) &&
377001341fbdSYunfeng Ye 		       pwq->nr_active < pwq->max_active) {
3771f97a4a1aSLai Jiangshan 			pwq_activate_first_inactive(pwq);
377201341fbdSYunfeng Ye 			kick = true;
377301341fbdSYunfeng Ye 		}
3774951a078aSLai Jiangshan 
3775951a078aSLai Jiangshan 		/*
3776951a078aSLai Jiangshan 		 * Need to kick a worker after thawed or an unbound wq's
377701341fbdSYunfeng Ye 		 * max_active is bumped. In realtime scenarios, always kicking a
377801341fbdSYunfeng Ye 		 * worker will cause interference on the isolated cpu cores, so
377901341fbdSYunfeng Ye 		 * let's kick iff work items were activated.
3780951a078aSLai Jiangshan 		 */
378101341fbdSYunfeng Ye 		if (kick)
3782951a078aSLai Jiangshan 			wake_up_worker(pwq->pool);
3783699ce097STejun Heo 	} else {
3784699ce097STejun Heo 		pwq->max_active = 0;
3785699ce097STejun Heo 	}
3786699ce097STejun Heo 
3787a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
37880fbd95aaSTejun Heo }
37890fbd95aaSTejun Heo 
379067dc8325SCai Huoqing /* initialize newly allocated @pwq which is associated with @wq and @pool */
3791f147f29eSTejun Heo static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
3792f147f29eSTejun Heo 		     struct worker_pool *pool)
3793d2c1d404STejun Heo {
3794d2c1d404STejun Heo 	BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3795d2c1d404STejun Heo 
3796e50aba9aSTejun Heo 	memset(pwq, 0, sizeof(*pwq));
3797e50aba9aSTejun Heo 
3798d2c1d404STejun Heo 	pwq->pool = pool;
3799d2c1d404STejun Heo 	pwq->wq = wq;
3800d2c1d404STejun Heo 	pwq->flush_color = -1;
38018864b4e5STejun Heo 	pwq->refcnt = 1;
3802f97a4a1aSLai Jiangshan 	INIT_LIST_HEAD(&pwq->inactive_works);
38031befcf30STejun Heo 	INIT_LIST_HEAD(&pwq->pwqs_node);
3804d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->mayday_node);
38058864b4e5STejun Heo 	INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
3806f147f29eSTejun Heo }
3807d2c1d404STejun Heo 
3808f147f29eSTejun Heo /* sync @pwq with the current state of its associated wq and link it */
38091befcf30STejun Heo static void link_pwq(struct pool_workqueue *pwq)
3810f147f29eSTejun Heo {
3811f147f29eSTejun Heo 	struct workqueue_struct *wq = pwq->wq;
3812f147f29eSTejun Heo 
3813f147f29eSTejun Heo 	lockdep_assert_held(&wq->mutex);
381475ccf595STejun Heo 
38151befcf30STejun Heo 	/* may be called multiple times, ignore if already linked */
38161befcf30STejun Heo 	if (!list_empty(&pwq->pwqs_node))
38171befcf30STejun Heo 		return;
38181befcf30STejun Heo 
381929b1cb41SLai Jiangshan 	/* set the matching work_color */
382075ccf595STejun Heo 	pwq->work_color = wq->work_color;
3821983ca25eSTejun Heo 
3822983ca25eSTejun Heo 	/* sync max_active to the current setting */
3823983ca25eSTejun Heo 	pwq_adjust_max_active(pwq);
3824983ca25eSTejun Heo 
3825983ca25eSTejun Heo 	/* link in @pwq */
38269e8cd2f5STejun Heo 	list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
3827df2d5ae4STejun Heo }
38286029a918STejun Heo 
3829f147f29eSTejun Heo /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
3830f147f29eSTejun Heo static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
3831f147f29eSTejun Heo 					const struct workqueue_attrs *attrs)
3832f147f29eSTejun Heo {
3833f147f29eSTejun Heo 	struct worker_pool *pool;
3834f147f29eSTejun Heo 	struct pool_workqueue *pwq;
3835f147f29eSTejun Heo 
3836f147f29eSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3837f147f29eSTejun Heo 
3838f147f29eSTejun Heo 	pool = get_unbound_pool(attrs);
3839f147f29eSTejun Heo 	if (!pool)
3840f147f29eSTejun Heo 		return NULL;
3841f147f29eSTejun Heo 
3842e50aba9aSTejun Heo 	pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
3843f147f29eSTejun Heo 	if (!pwq) {
3844f147f29eSTejun Heo 		put_unbound_pool(pool);
3845f147f29eSTejun Heo 		return NULL;
3846f147f29eSTejun Heo 	}
3847f147f29eSTejun Heo 
3848f147f29eSTejun Heo 	init_pwq(pwq, wq, pool);
3849f147f29eSTejun Heo 	return pwq;
3850d2c1d404STejun Heo }
3851d2c1d404STejun Heo 
38524c16bd32STejun Heo /**
385330186c6fSGong Zhaogang  * wq_calc_node_cpumask - calculate a wq_attrs' cpumask for the specified node
3854042f7df1SLai Jiangshan  * @attrs: the wq_attrs of the default pwq of the target workqueue
38554c16bd32STejun Heo  * @node: the target NUMA node
38564c16bd32STejun Heo  * @cpu_going_down: if >= 0, the CPU to consider as offline
38574c16bd32STejun Heo  * @cpumask: outarg, the resulting cpumask
38584c16bd32STejun Heo  *
38594c16bd32STejun Heo  * Calculate the cpumask a workqueue with @attrs should use on @node.  If
38604c16bd32STejun Heo  * @cpu_going_down is >= 0, that cpu is considered offline during
3861d185af30SYacine Belkadi  * calculation.  The result is stored in @cpumask.
38624c16bd32STejun Heo  *
38634c16bd32STejun Heo  * If NUMA affinity is not enabled, @attrs->cpumask is always used.  If
38644c16bd32STejun Heo  * enabled and @node has online CPUs requested by @attrs, the returned
38654c16bd32STejun Heo  * cpumask is the intersection of the possible CPUs of @node and
38664c16bd32STejun Heo  * @attrs->cpumask.
38674c16bd32STejun Heo  *
38684c16bd32STejun Heo  * The caller is responsible for ensuring that the cpumask of @node stays
38694c16bd32STejun Heo  * stable.
3870d185af30SYacine Belkadi  *
3871d185af30SYacine Belkadi  * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
3872d185af30SYacine Belkadi  * %false if equal.
38734c16bd32STejun Heo  */
38744c16bd32STejun Heo static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
38754c16bd32STejun Heo 				 int cpu_going_down, cpumask_t *cpumask)
38764c16bd32STejun Heo {
3877d55262c4STejun Heo 	if (!wq_numa_enabled || attrs->no_numa)
38784c16bd32STejun Heo 		goto use_dfl;
38794c16bd32STejun Heo 
38804c16bd32STejun Heo 	/* does @node have any online CPUs @attrs wants? */
38814c16bd32STejun Heo 	cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
38824c16bd32STejun Heo 	if (cpu_going_down >= 0)
38834c16bd32STejun Heo 		cpumask_clear_cpu(cpu_going_down, cpumask);
38844c16bd32STejun Heo 
38854c16bd32STejun Heo 	if (cpumask_empty(cpumask))
38864c16bd32STejun Heo 		goto use_dfl;
38874c16bd32STejun Heo 
38884c16bd32STejun Heo 	/* yeap, return possible CPUs in @node that @attrs wants */
38894c16bd32STejun Heo 	cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
38901ad0f0a7SMichael Bringmann 
38911ad0f0a7SMichael Bringmann 	if (cpumask_empty(cpumask)) {
38921ad0f0a7SMichael Bringmann 		pr_warn_once("WARNING: workqueue cpumask: online intersect > "
38931ad0f0a7SMichael Bringmann 				"possible intersect\n");
38941ad0f0a7SMichael Bringmann 		return false;
38951ad0f0a7SMichael Bringmann 	}
38961ad0f0a7SMichael Bringmann 
38974c16bd32STejun Heo 	return !cpumask_equal(cpumask, attrs->cpumask);
38984c16bd32STejun Heo 
38994c16bd32STejun Heo use_dfl:
39004c16bd32STejun Heo 	cpumask_copy(cpumask, attrs->cpumask);
39014c16bd32STejun Heo 	return false;
39024c16bd32STejun Heo }
39034c16bd32STejun Heo 
39041befcf30STejun Heo /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
39051befcf30STejun Heo static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
39061befcf30STejun Heo 						   int node,
39071befcf30STejun Heo 						   struct pool_workqueue *pwq)
39081befcf30STejun Heo {
39091befcf30STejun Heo 	struct pool_workqueue *old_pwq;
39101befcf30STejun Heo 
39115b95e1afSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
39121befcf30STejun Heo 	lockdep_assert_held(&wq->mutex);
39131befcf30STejun Heo 
39141befcf30STejun Heo 	/* link_pwq() can handle duplicate calls */
39151befcf30STejun Heo 	link_pwq(pwq);
39161befcf30STejun Heo 
39171befcf30STejun Heo 	old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
39181befcf30STejun Heo 	rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
39191befcf30STejun Heo 	return old_pwq;
39201befcf30STejun Heo }
39211befcf30STejun Heo 
39222d5f0764SLai Jiangshan /* context to store the prepared attrs & pwqs before applying */
39232d5f0764SLai Jiangshan struct apply_wqattrs_ctx {
39242d5f0764SLai Jiangshan 	struct workqueue_struct	*wq;		/* target workqueue */
39252d5f0764SLai Jiangshan 	struct workqueue_attrs	*attrs;		/* attrs to apply */
3926042f7df1SLai Jiangshan 	struct list_head	list;		/* queued for batching commit */
39272d5f0764SLai Jiangshan 	struct pool_workqueue	*dfl_pwq;
39282d5f0764SLai Jiangshan 	struct pool_workqueue	*pwq_tbl[];
39292d5f0764SLai Jiangshan };
39302d5f0764SLai Jiangshan 
39312d5f0764SLai Jiangshan /* free the resources after success or abort */
39322d5f0764SLai Jiangshan static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
39332d5f0764SLai Jiangshan {
39342d5f0764SLai Jiangshan 	if (ctx) {
39352d5f0764SLai Jiangshan 		int node;
39362d5f0764SLai Jiangshan 
39372d5f0764SLai Jiangshan 		for_each_node(node)
39382d5f0764SLai Jiangshan 			put_pwq_unlocked(ctx->pwq_tbl[node]);
39392d5f0764SLai Jiangshan 		put_pwq_unlocked(ctx->dfl_pwq);
39402d5f0764SLai Jiangshan 
39412d5f0764SLai Jiangshan 		free_workqueue_attrs(ctx->attrs);
39422d5f0764SLai Jiangshan 
39432d5f0764SLai Jiangshan 		kfree(ctx);
39442d5f0764SLai Jiangshan 	}
39452d5f0764SLai Jiangshan }
39462d5f0764SLai Jiangshan 
39472d5f0764SLai Jiangshan /* allocate the attrs and pwqs for later installation */
39482d5f0764SLai Jiangshan static struct apply_wqattrs_ctx *
39492d5f0764SLai Jiangshan apply_wqattrs_prepare(struct workqueue_struct *wq,
39502d5f0764SLai Jiangshan 		      const struct workqueue_attrs *attrs)
39512d5f0764SLai Jiangshan {
39522d5f0764SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
39532d5f0764SLai Jiangshan 	struct workqueue_attrs *new_attrs, *tmp_attrs;
39542d5f0764SLai Jiangshan 	int node;
39552d5f0764SLai Jiangshan 
39562d5f0764SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
39572d5f0764SLai Jiangshan 
3958acafe7e3SKees Cook 	ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_node_ids), GFP_KERNEL);
39592d5f0764SLai Jiangshan 
3960be69d00dSThomas Gleixner 	new_attrs = alloc_workqueue_attrs();
3961be69d00dSThomas Gleixner 	tmp_attrs = alloc_workqueue_attrs();
39622d5f0764SLai Jiangshan 	if (!ctx || !new_attrs || !tmp_attrs)
39632d5f0764SLai Jiangshan 		goto out_free;
39642d5f0764SLai Jiangshan 
3965042f7df1SLai Jiangshan 	/*
3966042f7df1SLai Jiangshan 	 * Calculate the attrs of the default pwq.
3967042f7df1SLai Jiangshan 	 * If the user configured cpumask doesn't overlap with the
3968042f7df1SLai Jiangshan 	 * wq_unbound_cpumask, we fallback to the wq_unbound_cpumask.
3969042f7df1SLai Jiangshan 	 */
39702d5f0764SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
3971b05a7928SFrederic Weisbecker 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, wq_unbound_cpumask);
3972042f7df1SLai Jiangshan 	if (unlikely(cpumask_empty(new_attrs->cpumask)))
3973042f7df1SLai Jiangshan 		cpumask_copy(new_attrs->cpumask, wq_unbound_cpumask);
39742d5f0764SLai Jiangshan 
39752d5f0764SLai Jiangshan 	/*
39762d5f0764SLai Jiangshan 	 * We may create multiple pwqs with differing cpumasks.  Make a
39772d5f0764SLai Jiangshan 	 * copy of @new_attrs which will be modified and used to obtain
39782d5f0764SLai Jiangshan 	 * pools.
39792d5f0764SLai Jiangshan 	 */
39802d5f0764SLai Jiangshan 	copy_workqueue_attrs(tmp_attrs, new_attrs);
39812d5f0764SLai Jiangshan 
39822d5f0764SLai Jiangshan 	/*
39832d5f0764SLai Jiangshan 	 * If something goes wrong during CPU up/down, we'll fall back to
39842d5f0764SLai Jiangshan 	 * the default pwq covering whole @attrs->cpumask.  Always create
39852d5f0764SLai Jiangshan 	 * it even if we don't use it immediately.
39862d5f0764SLai Jiangshan 	 */
39872d5f0764SLai Jiangshan 	ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
39882d5f0764SLai Jiangshan 	if (!ctx->dfl_pwq)
39892d5f0764SLai Jiangshan 		goto out_free;
39902d5f0764SLai Jiangshan 
39912d5f0764SLai Jiangshan 	for_each_node(node) {
3992042f7df1SLai Jiangshan 		if (wq_calc_node_cpumask(new_attrs, node, -1, tmp_attrs->cpumask)) {
39932d5f0764SLai Jiangshan 			ctx->pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
39942d5f0764SLai Jiangshan 			if (!ctx->pwq_tbl[node])
39952d5f0764SLai Jiangshan 				goto out_free;
39962d5f0764SLai Jiangshan 		} else {
39972d5f0764SLai Jiangshan 			ctx->dfl_pwq->refcnt++;
39982d5f0764SLai Jiangshan 			ctx->pwq_tbl[node] = ctx->dfl_pwq;
39992d5f0764SLai Jiangshan 		}
40002d5f0764SLai Jiangshan 	}
40012d5f0764SLai Jiangshan 
4002042f7df1SLai Jiangshan 	/* save the user configured attrs and sanitize it. */
4003042f7df1SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
4004042f7df1SLai Jiangshan 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
40052d5f0764SLai Jiangshan 	ctx->attrs = new_attrs;
4006042f7df1SLai Jiangshan 
40072d5f0764SLai Jiangshan 	ctx->wq = wq;
40082d5f0764SLai Jiangshan 	free_workqueue_attrs(tmp_attrs);
40092d5f0764SLai Jiangshan 	return ctx;
40102d5f0764SLai Jiangshan 
40112d5f0764SLai Jiangshan out_free:
40122d5f0764SLai Jiangshan 	free_workqueue_attrs(tmp_attrs);
40132d5f0764SLai Jiangshan 	free_workqueue_attrs(new_attrs);
40142d5f0764SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
40152d5f0764SLai Jiangshan 	return NULL;
40162d5f0764SLai Jiangshan }
40172d5f0764SLai Jiangshan 
40182d5f0764SLai Jiangshan /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
40192d5f0764SLai Jiangshan static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
40202d5f0764SLai Jiangshan {
40212d5f0764SLai Jiangshan 	int node;
40222d5f0764SLai Jiangshan 
40232d5f0764SLai Jiangshan 	/* all pwqs have been created successfully, let's install'em */
40242d5f0764SLai Jiangshan 	mutex_lock(&ctx->wq->mutex);
40252d5f0764SLai Jiangshan 
40262d5f0764SLai Jiangshan 	copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
40272d5f0764SLai Jiangshan 
40282d5f0764SLai Jiangshan 	/* save the previous pwq and install the new one */
40292d5f0764SLai Jiangshan 	for_each_node(node)
40302d5f0764SLai Jiangshan 		ctx->pwq_tbl[node] = numa_pwq_tbl_install(ctx->wq, node,
40312d5f0764SLai Jiangshan 							  ctx->pwq_tbl[node]);
40322d5f0764SLai Jiangshan 
40332d5f0764SLai Jiangshan 	/* @dfl_pwq might not have been used, ensure it's linked */
40342d5f0764SLai Jiangshan 	link_pwq(ctx->dfl_pwq);
40352d5f0764SLai Jiangshan 	swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
40362d5f0764SLai Jiangshan 
40372d5f0764SLai Jiangshan 	mutex_unlock(&ctx->wq->mutex);
40382d5f0764SLai Jiangshan }
40392d5f0764SLai Jiangshan 
4040a0111cf6SLai Jiangshan static void apply_wqattrs_lock(void)
4041a0111cf6SLai Jiangshan {
4042a0111cf6SLai Jiangshan 	/* CPUs should stay stable across pwq creations and installations */
4043ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
4044a0111cf6SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4045a0111cf6SLai Jiangshan }
4046a0111cf6SLai Jiangshan 
4047a0111cf6SLai Jiangshan static void apply_wqattrs_unlock(void)
4048a0111cf6SLai Jiangshan {
4049a0111cf6SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
4050ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
4051a0111cf6SLai Jiangshan }
4052a0111cf6SLai Jiangshan 
4053a0111cf6SLai Jiangshan static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
4054a0111cf6SLai Jiangshan 					const struct workqueue_attrs *attrs)
4055a0111cf6SLai Jiangshan {
4056a0111cf6SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
4057a0111cf6SLai Jiangshan 
4058a0111cf6SLai Jiangshan 	/* only unbound workqueues can change attributes */
4059a0111cf6SLai Jiangshan 	if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
4060a0111cf6SLai Jiangshan 		return -EINVAL;
4061a0111cf6SLai Jiangshan 
4062a0111cf6SLai Jiangshan 	/* creating multiple pwqs breaks ordering guarantee */
40630a94efb5STejun Heo 	if (!list_empty(&wq->pwqs)) {
40640a94efb5STejun Heo 		if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
4065a0111cf6SLai Jiangshan 			return -EINVAL;
4066a0111cf6SLai Jiangshan 
40670a94efb5STejun Heo 		wq->flags &= ~__WQ_ORDERED;
40680a94efb5STejun Heo 	}
40690a94efb5STejun Heo 
4070a0111cf6SLai Jiangshan 	ctx = apply_wqattrs_prepare(wq, attrs);
40716201171eSwanghaibin 	if (!ctx)
40726201171eSwanghaibin 		return -ENOMEM;
4073a0111cf6SLai Jiangshan 
4074a0111cf6SLai Jiangshan 	/* the ctx has been prepared successfully, let's commit it */
4075a0111cf6SLai Jiangshan 	apply_wqattrs_commit(ctx);
4076a0111cf6SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
4077a0111cf6SLai Jiangshan 
40786201171eSwanghaibin 	return 0;
4079a0111cf6SLai Jiangshan }
4080a0111cf6SLai Jiangshan 
40819e8cd2f5STejun Heo /**
40829e8cd2f5STejun Heo  * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
40839e8cd2f5STejun Heo  * @wq: the target workqueue
40849e8cd2f5STejun Heo  * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
40859e8cd2f5STejun Heo  *
40864c16bd32STejun Heo  * Apply @attrs to an unbound workqueue @wq.  Unless disabled, on NUMA
40874c16bd32STejun Heo  * machines, this function maps a separate pwq to each NUMA node with
40884c16bd32STejun Heo  * possibles CPUs in @attrs->cpumask so that work items are affine to the
40894c16bd32STejun Heo  * NUMA node it was issued on.  Older pwqs are released as in-flight work
40904c16bd32STejun Heo  * items finish.  Note that a work item which repeatedly requeues itself
40914c16bd32STejun Heo  * back-to-back will stay on its current pwq.
40929e8cd2f5STejun Heo  *
4093d185af30SYacine Belkadi  * Performs GFP_KERNEL allocations.
4094d185af30SYacine Belkadi  *
4095ffd8bea8SSebastian Andrzej Siewior  * Assumes caller has CPU hotplug read exclusion, i.e. cpus_read_lock().
4096509b3204SDaniel Jordan  *
4097d185af30SYacine Belkadi  * Return: 0 on success and -errno on failure.
40989e8cd2f5STejun Heo  */
4099513c98d0SDaniel Jordan int apply_workqueue_attrs(struct workqueue_struct *wq,
41009e8cd2f5STejun Heo 			  const struct workqueue_attrs *attrs)
41019e8cd2f5STejun Heo {
4102a0111cf6SLai Jiangshan 	int ret;
41039e8cd2f5STejun Heo 
4104509b3204SDaniel Jordan 	lockdep_assert_cpus_held();
4105509b3204SDaniel Jordan 
4106509b3204SDaniel Jordan 	mutex_lock(&wq_pool_mutex);
4107a0111cf6SLai Jiangshan 	ret = apply_workqueue_attrs_locked(wq, attrs);
4108509b3204SDaniel Jordan 	mutex_unlock(&wq_pool_mutex);
41092d5f0764SLai Jiangshan 
41102d5f0764SLai Jiangshan 	return ret;
41119e8cd2f5STejun Heo }
41129e8cd2f5STejun Heo 
41134c16bd32STejun Heo /**
41144c16bd32STejun Heo  * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
41154c16bd32STejun Heo  * @wq: the target workqueue
41164c16bd32STejun Heo  * @cpu: the CPU coming up or going down
41174c16bd32STejun Heo  * @online: whether @cpu is coming up or going down
41184c16bd32STejun Heo  *
41194c16bd32STejun Heo  * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
41204c16bd32STejun Heo  * %CPU_DOWN_FAILED.  @cpu is being hot[un]plugged, update NUMA affinity of
41214c16bd32STejun Heo  * @wq accordingly.
41224c16bd32STejun Heo  *
41234c16bd32STejun Heo  * If NUMA affinity can't be adjusted due to memory allocation failure, it
41244c16bd32STejun Heo  * falls back to @wq->dfl_pwq which may not be optimal but is always
41254c16bd32STejun Heo  * correct.
41264c16bd32STejun Heo  *
41274c16bd32STejun Heo  * Note that when the last allowed CPU of a NUMA node goes offline for a
41284c16bd32STejun Heo  * workqueue with a cpumask spanning multiple nodes, the workers which were
41294c16bd32STejun Heo  * already executing the work items for the workqueue will lose their CPU
41304c16bd32STejun Heo  * affinity and may execute on any CPU.  This is similar to how per-cpu
41314c16bd32STejun Heo  * workqueues behave on CPU_DOWN.  If a workqueue user wants strict
41324c16bd32STejun Heo  * affinity, it's the user's responsibility to flush the work item from
41334c16bd32STejun Heo  * CPU_DOWN_PREPARE.
41344c16bd32STejun Heo  */
41354c16bd32STejun Heo static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
41364c16bd32STejun Heo 				   bool online)
41374c16bd32STejun Heo {
41384c16bd32STejun Heo 	int node = cpu_to_node(cpu);
41394c16bd32STejun Heo 	int cpu_off = online ? -1 : cpu;
41404c16bd32STejun Heo 	struct pool_workqueue *old_pwq = NULL, *pwq;
41414c16bd32STejun Heo 	struct workqueue_attrs *target_attrs;
41424c16bd32STejun Heo 	cpumask_t *cpumask;
41434c16bd32STejun Heo 
41444c16bd32STejun Heo 	lockdep_assert_held(&wq_pool_mutex);
41454c16bd32STejun Heo 
4146f7142ed4SLai Jiangshan 	if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND) ||
4147f7142ed4SLai Jiangshan 	    wq->unbound_attrs->no_numa)
41484c16bd32STejun Heo 		return;
41494c16bd32STejun Heo 
41504c16bd32STejun Heo 	/*
41514c16bd32STejun Heo 	 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
41524c16bd32STejun Heo 	 * Let's use a preallocated one.  The following buf is protected by
41534c16bd32STejun Heo 	 * CPU hotplug exclusion.
41544c16bd32STejun Heo 	 */
41554c16bd32STejun Heo 	target_attrs = wq_update_unbound_numa_attrs_buf;
41564c16bd32STejun Heo 	cpumask = target_attrs->cpumask;
41574c16bd32STejun Heo 
41584c16bd32STejun Heo 	copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
41594c16bd32STejun Heo 	pwq = unbound_pwq_by_node(wq, node);
41604c16bd32STejun Heo 
41614c16bd32STejun Heo 	/*
41624c16bd32STejun Heo 	 * Let's determine what needs to be done.  If the target cpumask is
4163042f7df1SLai Jiangshan 	 * different from the default pwq's, we need to compare it to @pwq's
4164042f7df1SLai Jiangshan 	 * and create a new one if they don't match.  If the target cpumask
4165042f7df1SLai Jiangshan 	 * equals the default pwq's, the default pwq should be used.
41664c16bd32STejun Heo 	 */
4167042f7df1SLai Jiangshan 	if (wq_calc_node_cpumask(wq->dfl_pwq->pool->attrs, node, cpu_off, cpumask)) {
41684c16bd32STejun Heo 		if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
4169f7142ed4SLai Jiangshan 			return;
41704c16bd32STejun Heo 	} else {
41714c16bd32STejun Heo 		goto use_dfl_pwq;
41724c16bd32STejun Heo 	}
41734c16bd32STejun Heo 
41744c16bd32STejun Heo 	/* create a new pwq */
41754c16bd32STejun Heo 	pwq = alloc_unbound_pwq(wq, target_attrs);
41764c16bd32STejun Heo 	if (!pwq) {
41772d916033SFabian Frederick 		pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
41784c16bd32STejun Heo 			wq->name);
417977f300b1SDaeseok Youn 		goto use_dfl_pwq;
41804c16bd32STejun Heo 	}
41814c16bd32STejun Heo 
4182f7142ed4SLai Jiangshan 	/* Install the new pwq. */
41834c16bd32STejun Heo 	mutex_lock(&wq->mutex);
41844c16bd32STejun Heo 	old_pwq = numa_pwq_tbl_install(wq, node, pwq);
41854c16bd32STejun Heo 	goto out_unlock;
41864c16bd32STejun Heo 
41874c16bd32STejun Heo use_dfl_pwq:
4188f7142ed4SLai Jiangshan 	mutex_lock(&wq->mutex);
4189a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&wq->dfl_pwq->pool->lock);
41904c16bd32STejun Heo 	get_pwq(wq->dfl_pwq);
4191a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&wq->dfl_pwq->pool->lock);
41924c16bd32STejun Heo 	old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
41934c16bd32STejun Heo out_unlock:
41944c16bd32STejun Heo 	mutex_unlock(&wq->mutex);
41954c16bd32STejun Heo 	put_pwq_unlocked(old_pwq);
41964c16bd32STejun Heo }
41974c16bd32STejun Heo 
419830cdf249STejun Heo static int alloc_and_link_pwqs(struct workqueue_struct *wq)
41991da177e4SLinus Torvalds {
420049e3cf44STejun Heo 	bool highpri = wq->flags & WQ_HIGHPRI;
42018a2b7538STejun Heo 	int cpu, ret;
4202e1d8aa9fSFrederic Weisbecker 
420330cdf249STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
4204420c0ddbSTejun Heo 		wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
4205420c0ddbSTejun Heo 		if (!wq->cpu_pwqs)
420630cdf249STejun Heo 			return -ENOMEM;
420730cdf249STejun Heo 
420830cdf249STejun Heo 		for_each_possible_cpu(cpu) {
42097fb98ea7STejun Heo 			struct pool_workqueue *pwq =
42107fb98ea7STejun Heo 				per_cpu_ptr(wq->cpu_pwqs, cpu);
42117a62c2c8STejun Heo 			struct worker_pool *cpu_pools =
4212f02ae73aSTejun Heo 				per_cpu(cpu_worker_pools, cpu);
421330cdf249STejun Heo 
4214f147f29eSTejun Heo 			init_pwq(pwq, wq, &cpu_pools[highpri]);
4215f147f29eSTejun Heo 
4216f147f29eSTejun Heo 			mutex_lock(&wq->mutex);
42171befcf30STejun Heo 			link_pwq(pwq);
4218f147f29eSTejun Heo 			mutex_unlock(&wq->mutex);
421930cdf249STejun Heo 		}
422030cdf249STejun Heo 		return 0;
4221509b3204SDaniel Jordan 	}
4222509b3204SDaniel Jordan 
4223ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
4224509b3204SDaniel Jordan 	if (wq->flags & __WQ_ORDERED) {
42258a2b7538STejun Heo 		ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
42268a2b7538STejun Heo 		/* there should only be single pwq for ordering guarantee */
42278a2b7538STejun Heo 		WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
42288a2b7538STejun Heo 			      wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
42298a2b7538STejun Heo 		     "ordering guarantee broken for workqueue %s\n", wq->name);
42309e8cd2f5STejun Heo 	} else {
4231509b3204SDaniel Jordan 		ret = apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
42329e8cd2f5STejun Heo 	}
4233ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
4234509b3204SDaniel Jordan 
4235509b3204SDaniel Jordan 	return ret;
42360f900049STejun Heo }
42370f900049STejun Heo 
4238f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
4239f3421797STejun Heo 			       const char *name)
4240b71ab8c2STejun Heo {
4241f3421797STejun Heo 	int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
4242f3421797STejun Heo 
4243f3421797STejun Heo 	if (max_active < 1 || max_active > lim)
4244044c782cSValentin Ilie 		pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
4245f3421797STejun Heo 			max_active, name, 1, lim);
4246b71ab8c2STejun Heo 
4247f3421797STejun Heo 	return clamp_val(max_active, 1, lim);
4248b71ab8c2STejun Heo }
4249b71ab8c2STejun Heo 
4250983c7515STejun Heo /*
4251983c7515STejun Heo  * Workqueues which may be used during memory reclaim should have a rescuer
4252983c7515STejun Heo  * to guarantee forward progress.
4253983c7515STejun Heo  */
4254983c7515STejun Heo static int init_rescuer(struct workqueue_struct *wq)
4255983c7515STejun Heo {
4256983c7515STejun Heo 	struct worker *rescuer;
4257b92b36eaSDan Carpenter 	int ret;
4258983c7515STejun Heo 
4259983c7515STejun Heo 	if (!(wq->flags & WQ_MEM_RECLAIM))
4260983c7515STejun Heo 		return 0;
4261983c7515STejun Heo 
4262983c7515STejun Heo 	rescuer = alloc_worker(NUMA_NO_NODE);
4263983c7515STejun Heo 	if (!rescuer)
4264983c7515STejun Heo 		return -ENOMEM;
4265983c7515STejun Heo 
4266983c7515STejun Heo 	rescuer->rescue_wq = wq;
4267983c7515STejun Heo 	rescuer->task = kthread_create(rescuer_thread, rescuer, "%s", wq->name);
4268f187b697SSean Fu 	if (IS_ERR(rescuer->task)) {
4269b92b36eaSDan Carpenter 		ret = PTR_ERR(rescuer->task);
4270983c7515STejun Heo 		kfree(rescuer);
4271b92b36eaSDan Carpenter 		return ret;
4272983c7515STejun Heo 	}
4273983c7515STejun Heo 
4274983c7515STejun Heo 	wq->rescuer = rescuer;
4275983c7515STejun Heo 	kthread_bind_mask(rescuer->task, cpu_possible_mask);
4276983c7515STejun Heo 	wake_up_process(rescuer->task);
4277983c7515STejun Heo 
4278983c7515STejun Heo 	return 0;
4279983c7515STejun Heo }
4280983c7515STejun Heo 
4281a2775bbcSMathieu Malaterre __printf(1, 4)
4282669de8bdSBart Van Assche struct workqueue_struct *alloc_workqueue(const char *fmt,
428397e37d7bSTejun Heo 					 unsigned int flags,
4284669de8bdSBart Van Assche 					 int max_active, ...)
42853af24433SOleg Nesterov {
4286df2d5ae4STejun Heo 	size_t tbl_size = 0;
4287ecf6881fSTejun Heo 	va_list args;
42883af24433SOleg Nesterov 	struct workqueue_struct *wq;
428949e3cf44STejun Heo 	struct pool_workqueue *pwq;
4290b196be89STejun Heo 
42915c0338c6STejun Heo 	/*
42925c0338c6STejun Heo 	 * Unbound && max_active == 1 used to imply ordered, which is no
42935c0338c6STejun Heo 	 * longer the case on NUMA machines due to per-node pools.  While
42945c0338c6STejun Heo 	 * alloc_ordered_workqueue() is the right way to create an ordered
42955c0338c6STejun Heo 	 * workqueue, keep the previous behavior to avoid subtle breakages
42965c0338c6STejun Heo 	 * on NUMA.
42975c0338c6STejun Heo 	 */
42985c0338c6STejun Heo 	if ((flags & WQ_UNBOUND) && max_active == 1)
42995c0338c6STejun Heo 		flags |= __WQ_ORDERED;
43005c0338c6STejun Heo 
4301cee22a15SViresh Kumar 	/* see the comment above the definition of WQ_POWER_EFFICIENT */
4302cee22a15SViresh Kumar 	if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
4303cee22a15SViresh Kumar 		flags |= WQ_UNBOUND;
4304cee22a15SViresh Kumar 
4305ecf6881fSTejun Heo 	/* allocate wq and format name */
4306df2d5ae4STejun Heo 	if (flags & WQ_UNBOUND)
4307ddcb57e2SLai Jiangshan 		tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
4308df2d5ae4STejun Heo 
4309df2d5ae4STejun Heo 	wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
4310b196be89STejun Heo 	if (!wq)
4311d2c1d404STejun Heo 		return NULL;
4312b196be89STejun Heo 
43136029a918STejun Heo 	if (flags & WQ_UNBOUND) {
4314be69d00dSThomas Gleixner 		wq->unbound_attrs = alloc_workqueue_attrs();
43156029a918STejun Heo 		if (!wq->unbound_attrs)
43166029a918STejun Heo 			goto err_free_wq;
43176029a918STejun Heo 	}
43186029a918STejun Heo 
4319669de8bdSBart Van Assche 	va_start(args, max_active);
4320ecf6881fSTejun Heo 	vsnprintf(wq->name, sizeof(wq->name), fmt, args);
4321b196be89STejun Heo 	va_end(args);
43223af24433SOleg Nesterov 
4323d320c038STejun Heo 	max_active = max_active ?: WQ_DFL_ACTIVE;
4324b196be89STejun Heo 	max_active = wq_clamp_max_active(max_active, flags, wq->name);
43253af24433SOleg Nesterov 
4326b196be89STejun Heo 	/* init wq */
432797e37d7bSTejun Heo 	wq->flags = flags;
4328a0a1a5fdSTejun Heo 	wq->saved_max_active = max_active;
43293c25a55dSLai Jiangshan 	mutex_init(&wq->mutex);
4330112202d9STejun Heo 	atomic_set(&wq->nr_pwqs_to_flush, 0);
433130cdf249STejun Heo 	INIT_LIST_HEAD(&wq->pwqs);
433273f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
433373f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
4334493a1724STejun Heo 	INIT_LIST_HEAD(&wq->maydays);
43353af24433SOleg Nesterov 
4336669de8bdSBart Van Assche 	wq_init_lockdep(wq);
4337cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
43383af24433SOleg Nesterov 
433930cdf249STejun Heo 	if (alloc_and_link_pwqs(wq) < 0)
434082efcab3SBart Van Assche 		goto err_unreg_lockdep;
43411537663fSTejun Heo 
434240c17f75STejun Heo 	if (wq_online && init_rescuer(wq) < 0)
4343d2c1d404STejun Heo 		goto err_destroy;
4344e22bee78STejun Heo 
4345226223abSTejun Heo 	if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
4346226223abSTejun Heo 		goto err_destroy;
4347226223abSTejun Heo 
43486af8bf3dSOleg Nesterov 	/*
434968e13a67SLai Jiangshan 	 * wq_pool_mutex protects global freeze state and workqueues list.
435068e13a67SLai Jiangshan 	 * Grab it, adjust max_active and add the new @wq to workqueues
435168e13a67SLai Jiangshan 	 * list.
43526af8bf3dSOleg Nesterov 	 */
435368e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4354a0a1a5fdSTejun Heo 
4355a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
435649e3cf44STejun Heo 	for_each_pwq(pwq, wq)
4357699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4358a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4359a0a1a5fdSTejun Heo 
4360e2dca7adSTejun Heo 	list_add_tail_rcu(&wq->list, &workqueues);
4361a0a1a5fdSTejun Heo 
436268e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
43633af24433SOleg Nesterov 
43643af24433SOleg Nesterov 	return wq;
4365d2c1d404STejun Heo 
436682efcab3SBart Van Assche err_unreg_lockdep:
4367009bb421SBart Van Assche 	wq_unregister_lockdep(wq);
4368009bb421SBart Van Assche 	wq_free_lockdep(wq);
436982efcab3SBart Van Assche err_free_wq:
43706029a918STejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
43714690c4abSTejun Heo 	kfree(wq);
4372d2c1d404STejun Heo 	return NULL;
4373d2c1d404STejun Heo err_destroy:
4374d2c1d404STejun Heo 	destroy_workqueue(wq);
43754690c4abSTejun Heo 	return NULL;
43761da177e4SLinus Torvalds }
4377669de8bdSBart Van Assche EXPORT_SYMBOL_GPL(alloc_workqueue);
43781da177e4SLinus Torvalds 
4379c29eb853STejun Heo static bool pwq_busy(struct pool_workqueue *pwq)
4380c29eb853STejun Heo {
4381c29eb853STejun Heo 	int i;
4382c29eb853STejun Heo 
4383c29eb853STejun Heo 	for (i = 0; i < WORK_NR_COLORS; i++)
4384c29eb853STejun Heo 		if (pwq->nr_in_flight[i])
4385c29eb853STejun Heo 			return true;
4386c29eb853STejun Heo 
4387c29eb853STejun Heo 	if ((pwq != pwq->wq->dfl_pwq) && (pwq->refcnt > 1))
4388c29eb853STejun Heo 		return true;
4389f97a4a1aSLai Jiangshan 	if (pwq->nr_active || !list_empty(&pwq->inactive_works))
4390c29eb853STejun Heo 		return true;
4391c29eb853STejun Heo 
4392c29eb853STejun Heo 	return false;
4393c29eb853STejun Heo }
4394c29eb853STejun Heo 
43953af24433SOleg Nesterov /**
43963af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
43973af24433SOleg Nesterov  * @wq: target workqueue
43983af24433SOleg Nesterov  *
43993af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
44003af24433SOleg Nesterov  */
44013af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
44023af24433SOleg Nesterov {
440349e3cf44STejun Heo 	struct pool_workqueue *pwq;
44044c16bd32STejun Heo 	int node;
44053af24433SOleg Nesterov 
4406def98c84STejun Heo 	/*
4407def98c84STejun Heo 	 * Remove it from sysfs first so that sanity check failure doesn't
4408def98c84STejun Heo 	 * lead to sysfs name conflicts.
4409def98c84STejun Heo 	 */
4410def98c84STejun Heo 	workqueue_sysfs_unregister(wq);
4411def98c84STejun Heo 
44129c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
44139c5a2ba7STejun Heo 	drain_workqueue(wq);
4414c8efcc25STejun Heo 
4415def98c84STejun Heo 	/* kill rescuer, if sanity checks fail, leave it w/o rescuer */
4416def98c84STejun Heo 	if (wq->rescuer) {
4417def98c84STejun Heo 		struct worker *rescuer = wq->rescuer;
4418def98c84STejun Heo 
4419def98c84STejun Heo 		/* this prevents new queueing */
4420a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&wq_mayday_lock);
4421def98c84STejun Heo 		wq->rescuer = NULL;
4422a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&wq_mayday_lock);
4423def98c84STejun Heo 
4424def98c84STejun Heo 		/* rescuer will empty maydays list before exiting */
4425def98c84STejun Heo 		kthread_stop(rescuer->task);
44268efe1223STejun Heo 		kfree(rescuer);
4427def98c84STejun Heo 	}
4428def98c84STejun Heo 
4429c29eb853STejun Heo 	/*
4430c29eb853STejun Heo 	 * Sanity checks - grab all the locks so that we wait for all
4431c29eb853STejun Heo 	 * in-flight operations which may do put_pwq().
4432c29eb853STejun Heo 	 */
4433c29eb853STejun Heo 	mutex_lock(&wq_pool_mutex);
4434b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
443549e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
4436a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
4437c29eb853STejun Heo 		if (WARN_ON(pwq_busy(pwq))) {
44381d9a6159SKefeng Wang 			pr_warn("%s: %s has the following busy pwq\n",
4439e66b39afSTejun Heo 				__func__, wq->name);
4440c29eb853STejun Heo 			show_pwq(pwq);
4441a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&pwq->pool->lock);
4442b09f4fd3SLai Jiangshan 			mutex_unlock(&wq->mutex);
4443c29eb853STejun Heo 			mutex_unlock(&wq_pool_mutex);
444455df0933SImran Khan 			show_one_workqueue(wq);
44456183c009STejun Heo 			return;
444676af4d93STejun Heo 		}
4447a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
444876af4d93STejun Heo 	}
4449b09f4fd3SLai Jiangshan 	mutex_unlock(&wq->mutex);
44506183c009STejun Heo 
4451a0a1a5fdSTejun Heo 	/*
4452a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
4453a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
4454a0a1a5fdSTejun Heo 	 */
4455e2dca7adSTejun Heo 	list_del_rcu(&wq->list);
445668e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
44573af24433SOleg Nesterov 
44588864b4e5STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
4459669de8bdSBart Van Assche 		wq_unregister_lockdep(wq);
446029c91e99STejun Heo 		/*
44618864b4e5STejun Heo 		 * The base ref is never dropped on per-cpu pwqs.  Directly
4462e2dca7adSTejun Heo 		 * schedule RCU free.
446329c91e99STejun Heo 		 */
446425b00775SPaul E. McKenney 		call_rcu(&wq->rcu, rcu_free_wq);
44658864b4e5STejun Heo 	} else {
44668864b4e5STejun Heo 		/*
44678864b4e5STejun Heo 		 * We're the sole accessor of @wq at this point.  Directly
44684c16bd32STejun Heo 		 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
44694c16bd32STejun Heo 		 * @wq will be freed when the last pwq is released.
44708864b4e5STejun Heo 		 */
44714c16bd32STejun Heo 		for_each_node(node) {
44724c16bd32STejun Heo 			pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
44734c16bd32STejun Heo 			RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
44744c16bd32STejun Heo 			put_pwq_unlocked(pwq);
44754c16bd32STejun Heo 		}
44764c16bd32STejun Heo 
44774c16bd32STejun Heo 		/*
44784c16bd32STejun Heo 		 * Put dfl_pwq.  @wq may be freed any time after dfl_pwq is
44794c16bd32STejun Heo 		 * put.  Don't access it afterwards.
44804c16bd32STejun Heo 		 */
44814c16bd32STejun Heo 		pwq = wq->dfl_pwq;
44824c16bd32STejun Heo 		wq->dfl_pwq = NULL;
4483dce90d47STejun Heo 		put_pwq_unlocked(pwq);
448429c91e99STejun Heo 	}
44853af24433SOleg Nesterov }
44863af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
44873af24433SOleg Nesterov 
4488dcd989cbSTejun Heo /**
4489dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
4490dcd989cbSTejun Heo  * @wq: target workqueue
4491dcd989cbSTejun Heo  * @max_active: new max_active value.
4492dcd989cbSTejun Heo  *
4493dcd989cbSTejun Heo  * Set max_active of @wq to @max_active.
4494dcd989cbSTejun Heo  *
4495dcd989cbSTejun Heo  * CONTEXT:
4496dcd989cbSTejun Heo  * Don't call from IRQ context.
4497dcd989cbSTejun Heo  */
4498dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4499dcd989cbSTejun Heo {
450049e3cf44STejun Heo 	struct pool_workqueue *pwq;
4501dcd989cbSTejun Heo 
45028719dceaSTejun Heo 	/* disallow meddling with max_active for ordered workqueues */
45030a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
45048719dceaSTejun Heo 		return;
45058719dceaSTejun Heo 
4506f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4507dcd989cbSTejun Heo 
4508a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
4509dcd989cbSTejun Heo 
45100a94efb5STejun Heo 	wq->flags &= ~__WQ_ORDERED;
4511dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
4512dcd989cbSTejun Heo 
4513699ce097STejun Heo 	for_each_pwq(pwq, wq)
4514699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4515dcd989cbSTejun Heo 
4516a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4517dcd989cbSTejun Heo }
4518dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4519dcd989cbSTejun Heo 
4520dcd989cbSTejun Heo /**
452127d4ee03SLukas Wunner  * current_work - retrieve %current task's work struct
452227d4ee03SLukas Wunner  *
452327d4ee03SLukas Wunner  * Determine if %current task is a workqueue worker and what it's working on.
452427d4ee03SLukas Wunner  * Useful to find out the context that the %current task is running in.
452527d4ee03SLukas Wunner  *
452627d4ee03SLukas Wunner  * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
452727d4ee03SLukas Wunner  */
452827d4ee03SLukas Wunner struct work_struct *current_work(void)
452927d4ee03SLukas Wunner {
453027d4ee03SLukas Wunner 	struct worker *worker = current_wq_worker();
453127d4ee03SLukas Wunner 
453227d4ee03SLukas Wunner 	return worker ? worker->current_work : NULL;
453327d4ee03SLukas Wunner }
453427d4ee03SLukas Wunner EXPORT_SYMBOL(current_work);
453527d4ee03SLukas Wunner 
453627d4ee03SLukas Wunner /**
4537e6267616STejun Heo  * current_is_workqueue_rescuer - is %current workqueue rescuer?
4538e6267616STejun Heo  *
4539e6267616STejun Heo  * Determine whether %current is a workqueue rescuer.  Can be used from
4540e6267616STejun Heo  * work functions to determine whether it's being run off the rescuer task.
4541d185af30SYacine Belkadi  *
4542d185af30SYacine Belkadi  * Return: %true if %current is a workqueue rescuer. %false otherwise.
4543e6267616STejun Heo  */
4544e6267616STejun Heo bool current_is_workqueue_rescuer(void)
4545e6267616STejun Heo {
4546e6267616STejun Heo 	struct worker *worker = current_wq_worker();
4547e6267616STejun Heo 
45486a092dfdSLai Jiangshan 	return worker && worker->rescue_wq;
4549e6267616STejun Heo }
4550e6267616STejun Heo 
4551e6267616STejun Heo /**
4552dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
4553dcd989cbSTejun Heo  * @cpu: CPU in question
4554dcd989cbSTejun Heo  * @wq: target workqueue
4555dcd989cbSTejun Heo  *
4556dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
4557dcd989cbSTejun Heo  * no synchronization around this function and the test result is
4558dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4559dcd989cbSTejun Heo  *
4560d3251859STejun Heo  * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4561d3251859STejun Heo  * Note that both per-cpu and unbound workqueues may be associated with
4562d3251859STejun Heo  * multiple pool_workqueues which have separate congested states.  A
4563d3251859STejun Heo  * workqueue being congested on one CPU doesn't mean the workqueue is also
4564d3251859STejun Heo  * contested on other CPUs / NUMA nodes.
4565d3251859STejun Heo  *
4566d185af30SYacine Belkadi  * Return:
4567dcd989cbSTejun Heo  * %true if congested, %false otherwise.
4568dcd989cbSTejun Heo  */
4569d84ff051STejun Heo bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4570dcd989cbSTejun Heo {
45717fb98ea7STejun Heo 	struct pool_workqueue *pwq;
457276af4d93STejun Heo 	bool ret;
457376af4d93STejun Heo 
457424acfb71SThomas Gleixner 	rcu_read_lock();
457524acfb71SThomas Gleixner 	preempt_disable();
45767fb98ea7STejun Heo 
4577d3251859STejun Heo 	if (cpu == WORK_CPU_UNBOUND)
4578d3251859STejun Heo 		cpu = smp_processor_id();
4579d3251859STejun Heo 
45807fb98ea7STejun Heo 	if (!(wq->flags & WQ_UNBOUND))
45817fb98ea7STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
45827fb98ea7STejun Heo 	else
4583df2d5ae4STejun Heo 		pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4584dcd989cbSTejun Heo 
4585f97a4a1aSLai Jiangshan 	ret = !list_empty(&pwq->inactive_works);
458624acfb71SThomas Gleixner 	preempt_enable();
458724acfb71SThomas Gleixner 	rcu_read_unlock();
458876af4d93STejun Heo 
458976af4d93STejun Heo 	return ret;
4590dcd989cbSTejun Heo }
4591dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
4592dcd989cbSTejun Heo 
4593dcd989cbSTejun Heo /**
4594dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
4595dcd989cbSTejun Heo  * @work: the work to be tested
4596dcd989cbSTejun Heo  *
4597dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
4598dcd989cbSTejun Heo  * synchronization around this function and the test result is
4599dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4600dcd989cbSTejun Heo  *
4601d185af30SYacine Belkadi  * Return:
4602dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
4603dcd989cbSTejun Heo  */
4604dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
4605dcd989cbSTejun Heo {
4606fa1b54e6STejun Heo 	struct worker_pool *pool;
4607dcd989cbSTejun Heo 	unsigned long flags;
4608dcd989cbSTejun Heo 	unsigned int ret = 0;
4609dcd989cbSTejun Heo 
4610dcd989cbSTejun Heo 	if (work_pending(work))
4611dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
4612038366c5SLai Jiangshan 
461324acfb71SThomas Gleixner 	rcu_read_lock();
4614fa1b54e6STejun Heo 	pool = get_work_pool(work);
4615038366c5SLai Jiangshan 	if (pool) {
4616a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irqsave(&pool->lock, flags);
4617c9e7cf27STejun Heo 		if (find_worker_executing_work(pool, work))
4618dcd989cbSTejun Heo 			ret |= WORK_BUSY_RUNNING;
4619a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&pool->lock, flags);
4620038366c5SLai Jiangshan 	}
462124acfb71SThomas Gleixner 	rcu_read_unlock();
4622dcd989cbSTejun Heo 
4623dcd989cbSTejun Heo 	return ret;
4624dcd989cbSTejun Heo }
4625dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
4626dcd989cbSTejun Heo 
46273d1cb205STejun Heo /**
46283d1cb205STejun Heo  * set_worker_desc - set description for the current work item
46293d1cb205STejun Heo  * @fmt: printf-style format string
46303d1cb205STejun Heo  * @...: arguments for the format string
46313d1cb205STejun Heo  *
46323d1cb205STejun Heo  * This function can be called by a running work function to describe what
46333d1cb205STejun Heo  * the work item is about.  If the worker task gets dumped, this
46343d1cb205STejun Heo  * information will be printed out together to help debugging.  The
46353d1cb205STejun Heo  * description can be at most WORKER_DESC_LEN including the trailing '\0'.
46363d1cb205STejun Heo  */
46373d1cb205STejun Heo void set_worker_desc(const char *fmt, ...)
46383d1cb205STejun Heo {
46393d1cb205STejun Heo 	struct worker *worker = current_wq_worker();
46403d1cb205STejun Heo 	va_list args;
46413d1cb205STejun Heo 
46423d1cb205STejun Heo 	if (worker) {
46433d1cb205STejun Heo 		va_start(args, fmt);
46443d1cb205STejun Heo 		vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
46453d1cb205STejun Heo 		va_end(args);
46463d1cb205STejun Heo 	}
46473d1cb205STejun Heo }
46485c750d58SSteffen Maier EXPORT_SYMBOL_GPL(set_worker_desc);
46493d1cb205STejun Heo 
46503d1cb205STejun Heo /**
46513d1cb205STejun Heo  * print_worker_info - print out worker information and description
46523d1cb205STejun Heo  * @log_lvl: the log level to use when printing
46533d1cb205STejun Heo  * @task: target task
46543d1cb205STejun Heo  *
46553d1cb205STejun Heo  * If @task is a worker and currently executing a work item, print out the
46563d1cb205STejun Heo  * name of the workqueue being serviced and worker description set with
46573d1cb205STejun Heo  * set_worker_desc() by the currently executing work item.
46583d1cb205STejun Heo  *
46593d1cb205STejun Heo  * This function can be safely called on any task as long as the
46603d1cb205STejun Heo  * task_struct itself is accessible.  While safe, this function isn't
46613d1cb205STejun Heo  * synchronized and may print out mixups or garbages of limited length.
46623d1cb205STejun Heo  */
46633d1cb205STejun Heo void print_worker_info(const char *log_lvl, struct task_struct *task)
46643d1cb205STejun Heo {
46653d1cb205STejun Heo 	work_func_t *fn = NULL;
46663d1cb205STejun Heo 	char name[WQ_NAME_LEN] = { };
46673d1cb205STejun Heo 	char desc[WORKER_DESC_LEN] = { };
46683d1cb205STejun Heo 	struct pool_workqueue *pwq = NULL;
46693d1cb205STejun Heo 	struct workqueue_struct *wq = NULL;
46703d1cb205STejun Heo 	struct worker *worker;
46713d1cb205STejun Heo 
46723d1cb205STejun Heo 	if (!(task->flags & PF_WQ_WORKER))
46733d1cb205STejun Heo 		return;
46743d1cb205STejun Heo 
46753d1cb205STejun Heo 	/*
46763d1cb205STejun Heo 	 * This function is called without any synchronization and @task
46773d1cb205STejun Heo 	 * could be in any state.  Be careful with dereferences.
46783d1cb205STejun Heo 	 */
4679e700591aSPetr Mladek 	worker = kthread_probe_data(task);
46803d1cb205STejun Heo 
46813d1cb205STejun Heo 	/*
46828bf89593STejun Heo 	 * Carefully copy the associated workqueue's workfn, name and desc.
46838bf89593STejun Heo 	 * Keep the original last '\0' in case the original is garbage.
46843d1cb205STejun Heo 	 */
4685fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&fn, &worker->current_func, sizeof(fn));
4686fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&pwq, &worker->current_pwq, sizeof(pwq));
4687fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&wq, &pwq->wq, sizeof(wq));
4688fe557319SChristoph Hellwig 	copy_from_kernel_nofault(name, wq->name, sizeof(name) - 1);
4689fe557319SChristoph Hellwig 	copy_from_kernel_nofault(desc, worker->desc, sizeof(desc) - 1);
46903d1cb205STejun Heo 
46913d1cb205STejun Heo 	if (fn || name[0] || desc[0]) {
4692d75f773cSSakari Ailus 		printk("%sWorkqueue: %s %ps", log_lvl, name, fn);
46938bf89593STejun Heo 		if (strcmp(name, desc))
46943d1cb205STejun Heo 			pr_cont(" (%s)", desc);
46953d1cb205STejun Heo 		pr_cont("\n");
46963d1cb205STejun Heo 	}
46973d1cb205STejun Heo }
46983d1cb205STejun Heo 
46993494fc30STejun Heo static void pr_cont_pool_info(struct worker_pool *pool)
47003494fc30STejun Heo {
47013494fc30STejun Heo 	pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
47023494fc30STejun Heo 	if (pool->node != NUMA_NO_NODE)
47033494fc30STejun Heo 		pr_cont(" node=%d", pool->node);
47043494fc30STejun Heo 	pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
47053494fc30STejun Heo }
47063494fc30STejun Heo 
47073494fc30STejun Heo static void pr_cont_work(bool comma, struct work_struct *work)
47083494fc30STejun Heo {
47093494fc30STejun Heo 	if (work->func == wq_barrier_func) {
47103494fc30STejun Heo 		struct wq_barrier *barr;
47113494fc30STejun Heo 
47123494fc30STejun Heo 		barr = container_of(work, struct wq_barrier, work);
47133494fc30STejun Heo 
47143494fc30STejun Heo 		pr_cont("%s BAR(%d)", comma ? "," : "",
47153494fc30STejun Heo 			task_pid_nr(barr->task));
47163494fc30STejun Heo 	} else {
4717d75f773cSSakari Ailus 		pr_cont("%s %ps", comma ? "," : "", work->func);
47183494fc30STejun Heo 	}
47193494fc30STejun Heo }
47203494fc30STejun Heo 
47213494fc30STejun Heo static void show_pwq(struct pool_workqueue *pwq)
47223494fc30STejun Heo {
47233494fc30STejun Heo 	struct worker_pool *pool = pwq->pool;
47243494fc30STejun Heo 	struct work_struct *work;
47253494fc30STejun Heo 	struct worker *worker;
47263494fc30STejun Heo 	bool has_in_flight = false, has_pending = false;
47273494fc30STejun Heo 	int bkt;
47283494fc30STejun Heo 
47293494fc30STejun Heo 	pr_info("  pwq %d:", pool->id);
47303494fc30STejun Heo 	pr_cont_pool_info(pool);
47313494fc30STejun Heo 
4732e66b39afSTejun Heo 	pr_cont(" active=%d/%d refcnt=%d%s\n",
4733e66b39afSTejun Heo 		pwq->nr_active, pwq->max_active, pwq->refcnt,
47343494fc30STejun Heo 		!list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
47353494fc30STejun Heo 
47363494fc30STejun Heo 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
47373494fc30STejun Heo 		if (worker->current_pwq == pwq) {
47383494fc30STejun Heo 			has_in_flight = true;
47393494fc30STejun Heo 			break;
47403494fc30STejun Heo 		}
47413494fc30STejun Heo 	}
47423494fc30STejun Heo 	if (has_in_flight) {
47433494fc30STejun Heo 		bool comma = false;
47443494fc30STejun Heo 
47453494fc30STejun Heo 		pr_info("    in-flight:");
47463494fc30STejun Heo 		hash_for_each(pool->busy_hash, bkt, worker, hentry) {
47473494fc30STejun Heo 			if (worker->current_pwq != pwq)
47483494fc30STejun Heo 				continue;
47493494fc30STejun Heo 
4750d75f773cSSakari Ailus 			pr_cont("%s %d%s:%ps", comma ? "," : "",
47513494fc30STejun Heo 				task_pid_nr(worker->task),
475230ae2fc0STejun Heo 				worker->rescue_wq ? "(RESCUER)" : "",
47533494fc30STejun Heo 				worker->current_func);
47543494fc30STejun Heo 			list_for_each_entry(work, &worker->scheduled, entry)
47553494fc30STejun Heo 				pr_cont_work(false, work);
47563494fc30STejun Heo 			comma = true;
47573494fc30STejun Heo 		}
47583494fc30STejun Heo 		pr_cont("\n");
47593494fc30STejun Heo 	}
47603494fc30STejun Heo 
47613494fc30STejun Heo 	list_for_each_entry(work, &pool->worklist, entry) {
47623494fc30STejun Heo 		if (get_work_pwq(work) == pwq) {
47633494fc30STejun Heo 			has_pending = true;
47643494fc30STejun Heo 			break;
47653494fc30STejun Heo 		}
47663494fc30STejun Heo 	}
47673494fc30STejun Heo 	if (has_pending) {
47683494fc30STejun Heo 		bool comma = false;
47693494fc30STejun Heo 
47703494fc30STejun Heo 		pr_info("    pending:");
47713494fc30STejun Heo 		list_for_each_entry(work, &pool->worklist, entry) {
47723494fc30STejun Heo 			if (get_work_pwq(work) != pwq)
47733494fc30STejun Heo 				continue;
47743494fc30STejun Heo 
47753494fc30STejun Heo 			pr_cont_work(comma, work);
47763494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
47773494fc30STejun Heo 		}
47783494fc30STejun Heo 		pr_cont("\n");
47793494fc30STejun Heo 	}
47803494fc30STejun Heo 
4781f97a4a1aSLai Jiangshan 	if (!list_empty(&pwq->inactive_works)) {
47823494fc30STejun Heo 		bool comma = false;
47833494fc30STejun Heo 
4784f97a4a1aSLai Jiangshan 		pr_info("    inactive:");
4785f97a4a1aSLai Jiangshan 		list_for_each_entry(work, &pwq->inactive_works, entry) {
47863494fc30STejun Heo 			pr_cont_work(comma, work);
47873494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
47883494fc30STejun Heo 		}
47893494fc30STejun Heo 		pr_cont("\n");
47903494fc30STejun Heo 	}
47913494fc30STejun Heo }
47923494fc30STejun Heo 
47933494fc30STejun Heo /**
479455df0933SImran Khan  * show_one_workqueue - dump state of specified workqueue
479555df0933SImran Khan  * @wq: workqueue whose state will be printed
47963494fc30STejun Heo  */
479755df0933SImran Khan void show_one_workqueue(struct workqueue_struct *wq)
47983494fc30STejun Heo {
47993494fc30STejun Heo 	struct pool_workqueue *pwq;
48003494fc30STejun Heo 	bool idle = true;
480155df0933SImran Khan 	unsigned long flags;
48023494fc30STejun Heo 
48033494fc30STejun Heo 	for_each_pwq(pwq, wq) {
4804f97a4a1aSLai Jiangshan 		if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
48053494fc30STejun Heo 			idle = false;
48063494fc30STejun Heo 			break;
48073494fc30STejun Heo 		}
48083494fc30STejun Heo 	}
480955df0933SImran Khan 	if (idle) /* Nothing to print for idle workqueue */
481055df0933SImran Khan 		return;
48113494fc30STejun Heo 
48123494fc30STejun Heo 	pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
48133494fc30STejun Heo 
48143494fc30STejun Heo 	for_each_pwq(pwq, wq) {
4815a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irqsave(&pwq->pool->lock, flags);
481657116ce1SJohan Hovold 		if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
481757116ce1SJohan Hovold 			/*
481857116ce1SJohan Hovold 			 * Defer printing to avoid deadlocks in console
481957116ce1SJohan Hovold 			 * drivers that queue work while holding locks
482057116ce1SJohan Hovold 			 * also taken in their write paths.
482157116ce1SJohan Hovold 			 */
482257116ce1SJohan Hovold 			printk_deferred_enter();
48233494fc30STejun Heo 			show_pwq(pwq);
482457116ce1SJohan Hovold 			printk_deferred_exit();
482557116ce1SJohan Hovold 		}
4826a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
482762635ea8SSergey Senozhatsky 		/*
482862635ea8SSergey Senozhatsky 		 * We could be printing a lot from atomic context, e.g.
482955df0933SImran Khan 		 * sysrq-t -> show_all_workqueues(). Avoid triggering
483062635ea8SSergey Senozhatsky 		 * hard lockup.
483162635ea8SSergey Senozhatsky 		 */
483262635ea8SSergey Senozhatsky 		touch_nmi_watchdog();
48333494fc30STejun Heo 	}
483455df0933SImran Khan 
48353494fc30STejun Heo }
48363494fc30STejun Heo 
483755df0933SImran Khan /**
483855df0933SImran Khan  * show_one_worker_pool - dump state of specified worker pool
483955df0933SImran Khan  * @pool: worker pool whose state will be printed
484055df0933SImran Khan  */
484155df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool)
484255df0933SImran Khan {
48433494fc30STejun Heo 	struct worker *worker;
48443494fc30STejun Heo 	bool first = true;
484555df0933SImran Khan 	unsigned long flags;
48463494fc30STejun Heo 
4847a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irqsave(&pool->lock, flags);
48483494fc30STejun Heo 	if (pool->nr_workers == pool->nr_idle)
48493494fc30STejun Heo 		goto next_pool;
485057116ce1SJohan Hovold 	/*
485157116ce1SJohan Hovold 	 * Defer printing to avoid deadlocks in console drivers that
485257116ce1SJohan Hovold 	 * queue work while holding locks also taken in their write
485357116ce1SJohan Hovold 	 * paths.
485457116ce1SJohan Hovold 	 */
485557116ce1SJohan Hovold 	printk_deferred_enter();
48563494fc30STejun Heo 	pr_info("pool %d:", pool->id);
48573494fc30STejun Heo 	pr_cont_pool_info(pool);
485882607adcSTejun Heo 	pr_cont(" hung=%us workers=%d",
485982607adcSTejun Heo 		jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000,
486082607adcSTejun Heo 		pool->nr_workers);
48613494fc30STejun Heo 	if (pool->manager)
48623494fc30STejun Heo 		pr_cont(" manager: %d",
48633494fc30STejun Heo 			task_pid_nr(pool->manager->task));
48643494fc30STejun Heo 	list_for_each_entry(worker, &pool->idle_list, entry) {
48653494fc30STejun Heo 		pr_cont(" %s%d", first ? "idle: " : "",
48663494fc30STejun Heo 			task_pid_nr(worker->task));
48673494fc30STejun Heo 		first = false;
48683494fc30STejun Heo 	}
48693494fc30STejun Heo 	pr_cont("\n");
487057116ce1SJohan Hovold 	printk_deferred_exit();
48713494fc30STejun Heo next_pool:
4872a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&pool->lock, flags);
487362635ea8SSergey Senozhatsky 	/*
487462635ea8SSergey Senozhatsky 	 * We could be printing a lot from atomic context, e.g.
487555df0933SImran Khan 	 * sysrq-t -> show_all_workqueues(). Avoid triggering
487662635ea8SSergey Senozhatsky 	 * hard lockup.
487762635ea8SSergey Senozhatsky 	 */
487862635ea8SSergey Senozhatsky 	touch_nmi_watchdog();
487955df0933SImran Khan 
48803494fc30STejun Heo }
48813494fc30STejun Heo 
488255df0933SImran Khan /**
488355df0933SImran Khan  * show_all_workqueues - dump workqueue state
488455df0933SImran Khan  *
488555df0933SImran Khan  * Called from a sysrq handler or try_to_freeze_tasks() and prints out
488655df0933SImran Khan  * all busy workqueues and pools.
488755df0933SImran Khan  */
488855df0933SImran Khan void show_all_workqueues(void)
488955df0933SImran Khan {
489055df0933SImran Khan 	struct workqueue_struct *wq;
489155df0933SImran Khan 	struct worker_pool *pool;
489255df0933SImran Khan 	int pi;
489355df0933SImran Khan 
489455df0933SImran Khan 	rcu_read_lock();
489555df0933SImran Khan 
489655df0933SImran Khan 	pr_info("Showing busy workqueues and worker pools:\n");
489755df0933SImran Khan 
489855df0933SImran Khan 	list_for_each_entry_rcu(wq, &workqueues, list)
489955df0933SImran Khan 		show_one_workqueue(wq);
490055df0933SImran Khan 
490155df0933SImran Khan 	for_each_pool(pool, pi)
490255df0933SImran Khan 		show_one_worker_pool(pool);
490355df0933SImran Khan 
490424acfb71SThomas Gleixner 	rcu_read_unlock();
49053494fc30STejun Heo }
49063494fc30STejun Heo 
49076b59808bSTejun Heo /* used to show worker information through /proc/PID/{comm,stat,status} */
49086b59808bSTejun Heo void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
49096b59808bSTejun Heo {
49106b59808bSTejun Heo 	int off;
49116b59808bSTejun Heo 
49126b59808bSTejun Heo 	/* always show the actual comm */
49136b59808bSTejun Heo 	off = strscpy(buf, task->comm, size);
49146b59808bSTejun Heo 	if (off < 0)
49156b59808bSTejun Heo 		return;
49166b59808bSTejun Heo 
4917197f6accSTejun Heo 	/* stabilize PF_WQ_WORKER and worker pool association */
49186b59808bSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
49196b59808bSTejun Heo 
4920197f6accSTejun Heo 	if (task->flags & PF_WQ_WORKER) {
4921197f6accSTejun Heo 		struct worker *worker = kthread_data(task);
4922197f6accSTejun Heo 		struct worker_pool *pool = worker->pool;
49236b59808bSTejun Heo 
49246b59808bSTejun Heo 		if (pool) {
4925a9b8a985SSebastian Andrzej Siewior 			raw_spin_lock_irq(&pool->lock);
49266b59808bSTejun Heo 			/*
4927197f6accSTejun Heo 			 * ->desc tracks information (wq name or
4928197f6accSTejun Heo 			 * set_worker_desc()) for the latest execution.  If
4929197f6accSTejun Heo 			 * current, prepend '+', otherwise '-'.
49306b59808bSTejun Heo 			 */
49316b59808bSTejun Heo 			if (worker->desc[0] != '\0') {
49326b59808bSTejun Heo 				if (worker->current_work)
49336b59808bSTejun Heo 					scnprintf(buf + off, size - off, "+%s",
49346b59808bSTejun Heo 						  worker->desc);
49356b59808bSTejun Heo 				else
49366b59808bSTejun Heo 					scnprintf(buf + off, size - off, "-%s",
49376b59808bSTejun Heo 						  worker->desc);
49386b59808bSTejun Heo 			}
4939a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&pool->lock);
49406b59808bSTejun Heo 		}
4941197f6accSTejun Heo 	}
49426b59808bSTejun Heo 
49436b59808bSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
49446b59808bSTejun Heo }
49456b59808bSTejun Heo 
494666448bc2SMathieu Malaterre #ifdef CONFIG_SMP
494766448bc2SMathieu Malaterre 
4948db7bccf4STejun Heo /*
4949db7bccf4STejun Heo  * CPU hotplug.
4950db7bccf4STejun Heo  *
4951e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
4952112202d9STejun Heo  * are a lot of assumptions on strong associations among work, pwq and
4953706026c2STejun Heo  * pool which make migrating pending and scheduled works very
4954e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
495594cf58bbSTejun Heo  * worker pools serve mix of short, long and very long running works making
4956e22bee78STejun Heo  * blocked draining impractical.
4957e22bee78STejun Heo  *
495824647570STejun Heo  * This is solved by allowing the pools to be disassociated from the CPU
4959628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
4960628c78e7STejun Heo  * cpu comes back online.
4961db7bccf4STejun Heo  */
4962db7bccf4STejun Heo 
4963e8b3f8dbSLai Jiangshan static void unbind_workers(int cpu)
4964db7bccf4STejun Heo {
49654ce62e9eSTejun Heo 	struct worker_pool *pool;
4966db7bccf4STejun Heo 	struct worker *worker;
4967db7bccf4STejun Heo 
4968f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
49691258fae7STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
4970a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
4971e22bee78STejun Heo 
4972f2d5a0eeSTejun Heo 		/*
497392f9c5c4SLai Jiangshan 		 * We've blocked all attach/detach operations. Make all workers
497494cf58bbSTejun Heo 		 * unbound and set DISASSOCIATED.  Before this, all workers
497511b45b0bSLai Jiangshan 		 * must be on the cpu.  After this, they may become diasporas.
4976b4ac9384SLai Jiangshan 		 * And the preemption disabled section in their sched callbacks
4977b4ac9384SLai Jiangshan 		 * are guaranteed to see WORKER_UNBOUND since the code here
4978b4ac9384SLai Jiangshan 		 * is on the same cpu.
4979f2d5a0eeSTejun Heo 		 */
4980da028469SLai Jiangshan 		for_each_pool_worker(worker, pool)
4981403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
4982db7bccf4STejun Heo 
498324647570STejun Heo 		pool->flags |= POOL_DISASSOCIATED;
4984f2d5a0eeSTejun Heo 
4985e22bee78STejun Heo 		/*
4986*989442d7SLai Jiangshan 		 * The handling of nr_running in sched callbacks are disabled
4987*989442d7SLai Jiangshan 		 * now.  Zap nr_running.  After this, nr_running stays zero and
4988*989442d7SLai Jiangshan 		 * need_more_worker() and keep_working() are always true as
4989*989442d7SLai Jiangshan 		 * long as the worklist is not empty.  This pool now behaves as
4990*989442d7SLai Jiangshan 		 * an unbound (in terms of concurrency management) pool which
4991eb283428SLai Jiangshan 		 * are served by workers tied to the pool.
4992e22bee78STejun Heo 		 */
4993e19e397aSTejun Heo 		atomic_set(&pool->nr_running, 0);
4994eb283428SLai Jiangshan 
4995eb283428SLai Jiangshan 		/*
4996eb283428SLai Jiangshan 		 * With concurrency management just turned off, a busy
4997eb283428SLai Jiangshan 		 * worker blocking could lead to lengthy stalls.  Kick off
4998eb283428SLai Jiangshan 		 * unbound chain execution of currently pending work items.
4999eb283428SLai Jiangshan 		 */
5000eb283428SLai Jiangshan 		wake_up_worker(pool);
5001*989442d7SLai Jiangshan 
5002a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
5003*989442d7SLai Jiangshan 
5004*989442d7SLai Jiangshan 		for_each_pool_worker(worker, pool) {
5005*989442d7SLai Jiangshan 			kthread_set_per_cpu(worker->task, -1);
5006*989442d7SLai Jiangshan 			WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, cpu_possible_mask) < 0);
5007*989442d7SLai Jiangshan 		}
5008*989442d7SLai Jiangshan 
5009*989442d7SLai Jiangshan 		mutex_unlock(&wq_pool_attach_mutex);
5010eb283428SLai Jiangshan 	}
5011db7bccf4STejun Heo }
5012db7bccf4STejun Heo 
5013bd7c089eSTejun Heo /**
5014bd7c089eSTejun Heo  * rebind_workers - rebind all workers of a pool to the associated CPU
5015bd7c089eSTejun Heo  * @pool: pool of interest
5016bd7c089eSTejun Heo  *
5017a9ab775bSTejun Heo  * @pool->cpu is coming online.  Rebind all workers to the CPU.
5018bd7c089eSTejun Heo  */
5019bd7c089eSTejun Heo static void rebind_workers(struct worker_pool *pool)
5020bd7c089eSTejun Heo {
5021a9ab775bSTejun Heo 	struct worker *worker;
5022bd7c089eSTejun Heo 
50231258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
5024bd7c089eSTejun Heo 
5025bd7c089eSTejun Heo 	/*
5026a9ab775bSTejun Heo 	 * Restore CPU affinity of all workers.  As all idle workers should
5027a9ab775bSTejun Heo 	 * be on the run-queue of the associated CPU before any local
5028402dd89dSShailendra Verma 	 * wake-ups for concurrency management happen, restore CPU affinity
5029a9ab775bSTejun Heo 	 * of all workers first and then clear UNBOUND.  As we're called
5030a9ab775bSTejun Heo 	 * from CPU_ONLINE, the following shouldn't fail.
5031bd7c089eSTejun Heo 	 */
50325c25b5ffSPeter Zijlstra 	for_each_pool_worker(worker, pool) {
50335c25b5ffSPeter Zijlstra 		kthread_set_per_cpu(worker->task, pool->cpu);
5034a9ab775bSTejun Heo 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
5035a9ab775bSTejun Heo 						  pool->attrs->cpumask) < 0);
50365c25b5ffSPeter Zijlstra 	}
5037a9ab775bSTejun Heo 
5038a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
5039f7c17d26SWanpeng Li 
50403de5e884SLai Jiangshan 	pool->flags &= ~POOL_DISASSOCIATED;
5041a9ab775bSTejun Heo 
5042da028469SLai Jiangshan 	for_each_pool_worker(worker, pool) {
5043a9ab775bSTejun Heo 		unsigned int worker_flags = worker->flags;
5044a9ab775bSTejun Heo 
5045a9ab775bSTejun Heo 		/*
5046a9ab775bSTejun Heo 		 * We want to clear UNBOUND but can't directly call
5047a9ab775bSTejun Heo 		 * worker_clr_flags() or adjust nr_running.  Atomically
5048a9ab775bSTejun Heo 		 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
5049a9ab775bSTejun Heo 		 * @worker will clear REBOUND using worker_clr_flags() when
5050a9ab775bSTejun Heo 		 * it initiates the next execution cycle thus restoring
5051a9ab775bSTejun Heo 		 * concurrency management.  Note that when or whether
5052a9ab775bSTejun Heo 		 * @worker clears REBOUND doesn't affect correctness.
5053a9ab775bSTejun Heo 		 *
5054c95491edSMark Rutland 		 * WRITE_ONCE() is necessary because @worker->flags may be
5055a9ab775bSTejun Heo 		 * tested without holding any lock in
50566d25be57SThomas Gleixner 		 * wq_worker_running().  Without it, NOT_RUNNING test may
5057a9ab775bSTejun Heo 		 * fail incorrectly leading to premature concurrency
5058a9ab775bSTejun Heo 		 * management operations.
5059bd7c089eSTejun Heo 		 */
5060a9ab775bSTejun Heo 		WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
5061a9ab775bSTejun Heo 		worker_flags |= WORKER_REBOUND;
5062a9ab775bSTejun Heo 		worker_flags &= ~WORKER_UNBOUND;
5063c95491edSMark Rutland 		WRITE_ONCE(worker->flags, worker_flags);
5064bd7c089eSTejun Heo 	}
5065a9ab775bSTejun Heo 
5066a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
5067bd7c089eSTejun Heo }
5068bd7c089eSTejun Heo 
50697dbc725eSTejun Heo /**
50707dbc725eSTejun Heo  * restore_unbound_workers_cpumask - restore cpumask of unbound workers
50717dbc725eSTejun Heo  * @pool: unbound pool of interest
50727dbc725eSTejun Heo  * @cpu: the CPU which is coming up
50737dbc725eSTejun Heo  *
50747dbc725eSTejun Heo  * An unbound pool may end up with a cpumask which doesn't have any online
50757dbc725eSTejun Heo  * CPUs.  When a worker of such pool get scheduled, the scheduler resets
50767dbc725eSTejun Heo  * its cpus_allowed.  If @cpu is in @pool's cpumask which didn't have any
50777dbc725eSTejun Heo  * online CPU before, cpus_allowed of all its workers should be restored.
50787dbc725eSTejun Heo  */
50797dbc725eSTejun Heo static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
50807dbc725eSTejun Heo {
50817dbc725eSTejun Heo 	static cpumask_t cpumask;
50827dbc725eSTejun Heo 	struct worker *worker;
50837dbc725eSTejun Heo 
50841258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
50857dbc725eSTejun Heo 
50867dbc725eSTejun Heo 	/* is @cpu allowed for @pool? */
50877dbc725eSTejun Heo 	if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
50887dbc725eSTejun Heo 		return;
50897dbc725eSTejun Heo 
50907dbc725eSTejun Heo 	cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
50917dbc725eSTejun Heo 
50927dbc725eSTejun Heo 	/* as we're called from CPU_ONLINE, the following shouldn't fail */
5093da028469SLai Jiangshan 	for_each_pool_worker(worker, pool)
5094d945b5e9SPeter Zijlstra 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
50957dbc725eSTejun Heo }
50967dbc725eSTejun Heo 
50977ee681b2SThomas Gleixner int workqueue_prepare_cpu(unsigned int cpu)
50981da177e4SLinus Torvalds {
50994ce62e9eSTejun Heo 	struct worker_pool *pool;
51001da177e4SLinus Torvalds 
5101f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
51023ce63377STejun Heo 		if (pool->nr_workers)
51033ce63377STejun Heo 			continue;
5104051e1850SLai Jiangshan 		if (!create_worker(pool))
51057ee681b2SThomas Gleixner 			return -ENOMEM;
51063af24433SOleg Nesterov 	}
51077ee681b2SThomas Gleixner 	return 0;
51087ee681b2SThomas Gleixner }
51091da177e4SLinus Torvalds 
51107ee681b2SThomas Gleixner int workqueue_online_cpu(unsigned int cpu)
51117ee681b2SThomas Gleixner {
51127ee681b2SThomas Gleixner 	struct worker_pool *pool;
51137ee681b2SThomas Gleixner 	struct workqueue_struct *wq;
51147ee681b2SThomas Gleixner 	int pi;
51157ee681b2SThomas Gleixner 
511668e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
51177dbc725eSTejun Heo 
51187dbc725eSTejun Heo 	for_each_pool(pool, pi) {
51191258fae7STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
512094cf58bbSTejun Heo 
5121f05b558dSLai Jiangshan 		if (pool->cpu == cpu)
512294cf58bbSTejun Heo 			rebind_workers(pool);
5123f05b558dSLai Jiangshan 		else if (pool->cpu < 0)
51247dbc725eSTejun Heo 			restore_unbound_workers_cpumask(pool, cpu);
512594cf58bbSTejun Heo 
51261258fae7STejun Heo 		mutex_unlock(&wq_pool_attach_mutex);
512794cf58bbSTejun Heo 	}
51287dbc725eSTejun Heo 
51294c16bd32STejun Heo 	/* update NUMA affinity of unbound workqueues */
51304c16bd32STejun Heo 	list_for_each_entry(wq, &workqueues, list)
51314c16bd32STejun Heo 		wq_update_unbound_numa(wq, cpu, true);
51324c16bd32STejun Heo 
513368e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
51347ee681b2SThomas Gleixner 	return 0;
513565758202STejun Heo }
513665758202STejun Heo 
51377ee681b2SThomas Gleixner int workqueue_offline_cpu(unsigned int cpu)
513865758202STejun Heo {
51394c16bd32STejun Heo 	struct workqueue_struct *wq;
51408db25e78STejun Heo 
51414c16bd32STejun Heo 	/* unbinding per-cpu workers should happen on the local CPU */
5142e8b3f8dbSLai Jiangshan 	if (WARN_ON(cpu != smp_processor_id()))
5143e8b3f8dbSLai Jiangshan 		return -1;
5144e8b3f8dbSLai Jiangshan 
5145e8b3f8dbSLai Jiangshan 	unbind_workers(cpu);
51464c16bd32STejun Heo 
51474c16bd32STejun Heo 	/* update NUMA affinity of unbound workqueues */
51484c16bd32STejun Heo 	mutex_lock(&wq_pool_mutex);
51494c16bd32STejun Heo 	list_for_each_entry(wq, &workqueues, list)
51504c16bd32STejun Heo 		wq_update_unbound_numa(wq, cpu, false);
51514c16bd32STejun Heo 	mutex_unlock(&wq_pool_mutex);
51524c16bd32STejun Heo 
51537ee681b2SThomas Gleixner 	return 0;
515465758202STejun Heo }
515565758202STejun Heo 
51562d3854a3SRusty Russell struct work_for_cpu {
5157ed48ece2STejun Heo 	struct work_struct work;
51582d3854a3SRusty Russell 	long (*fn)(void *);
51592d3854a3SRusty Russell 	void *arg;
51602d3854a3SRusty Russell 	long ret;
51612d3854a3SRusty Russell };
51622d3854a3SRusty Russell 
5163ed48ece2STejun Heo static void work_for_cpu_fn(struct work_struct *work)
51642d3854a3SRusty Russell {
5165ed48ece2STejun Heo 	struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
5166ed48ece2STejun Heo 
51672d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
51682d3854a3SRusty Russell }
51692d3854a3SRusty Russell 
51702d3854a3SRusty Russell /**
517122aceb31SAnna-Maria Gleixner  * work_on_cpu - run a function in thread context on a particular cpu
51722d3854a3SRusty Russell  * @cpu: the cpu to run on
51732d3854a3SRusty Russell  * @fn: the function to run
51742d3854a3SRusty Russell  * @arg: the function arg
51752d3854a3SRusty Russell  *
517631ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
51776b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
5178d185af30SYacine Belkadi  *
5179d185af30SYacine Belkadi  * Return: The value @fn returns.
51802d3854a3SRusty Russell  */
5181d84ff051STejun Heo long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
51822d3854a3SRusty Russell {
5183ed48ece2STejun Heo 	struct work_for_cpu wfc = { .fn = fn, .arg = arg };
51842d3854a3SRusty Russell 
5185ed48ece2STejun Heo 	INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
5186ed48ece2STejun Heo 	schedule_work_on(cpu, &wfc.work);
518712997d1aSBjorn Helgaas 	flush_work(&wfc.work);
5188440a1136SChuansheng Liu 	destroy_work_on_stack(&wfc.work);
51892d3854a3SRusty Russell 	return wfc.ret;
51902d3854a3SRusty Russell }
51912d3854a3SRusty Russell EXPORT_SYMBOL_GPL(work_on_cpu);
51920e8d6a93SThomas Gleixner 
51930e8d6a93SThomas Gleixner /**
51940e8d6a93SThomas Gleixner  * work_on_cpu_safe - run a function in thread context on a particular cpu
51950e8d6a93SThomas Gleixner  * @cpu: the cpu to run on
51960e8d6a93SThomas Gleixner  * @fn:  the function to run
51970e8d6a93SThomas Gleixner  * @arg: the function argument
51980e8d6a93SThomas Gleixner  *
51990e8d6a93SThomas Gleixner  * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
52000e8d6a93SThomas Gleixner  * any locks which would prevent @fn from completing.
52010e8d6a93SThomas Gleixner  *
52020e8d6a93SThomas Gleixner  * Return: The value @fn returns.
52030e8d6a93SThomas Gleixner  */
52040e8d6a93SThomas Gleixner long work_on_cpu_safe(int cpu, long (*fn)(void *), void *arg)
52050e8d6a93SThomas Gleixner {
52060e8d6a93SThomas Gleixner 	long ret = -ENODEV;
52070e8d6a93SThomas Gleixner 
5208ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
52090e8d6a93SThomas Gleixner 	if (cpu_online(cpu))
52100e8d6a93SThomas Gleixner 		ret = work_on_cpu(cpu, fn, arg);
5211ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
52120e8d6a93SThomas Gleixner 	return ret;
52130e8d6a93SThomas Gleixner }
52140e8d6a93SThomas Gleixner EXPORT_SYMBOL_GPL(work_on_cpu_safe);
52152d3854a3SRusty Russell #endif /* CONFIG_SMP */
52162d3854a3SRusty Russell 
5217a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
5218e7577c50SRusty Russell 
5219a0a1a5fdSTejun Heo /**
5220a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
5221a0a1a5fdSTejun Heo  *
522258a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
5223f97a4a1aSLai Jiangshan  * workqueues will queue new works to their inactive_works list instead of
5224706026c2STejun Heo  * pool->worklist.
5225a0a1a5fdSTejun Heo  *
5226a0a1a5fdSTejun Heo  * CONTEXT:
5227a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5228a0a1a5fdSTejun Heo  */
5229a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
5230a0a1a5fdSTejun Heo {
523124b8a847STejun Heo 	struct workqueue_struct *wq;
523224b8a847STejun Heo 	struct pool_workqueue *pwq;
5233a0a1a5fdSTejun Heo 
523468e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5235a0a1a5fdSTejun Heo 
52366183c009STejun Heo 	WARN_ON_ONCE(workqueue_freezing);
5237a0a1a5fdSTejun Heo 	workqueue_freezing = true;
5238a0a1a5fdSTejun Heo 
523924b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5240a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
5241699ce097STejun Heo 		for_each_pwq(pwq, wq)
5242699ce097STejun Heo 			pwq_adjust_max_active(pwq);
5243a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
5244a1056305STejun Heo 	}
52455bcab335STejun Heo 
524668e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5247a0a1a5fdSTejun Heo }
5248a0a1a5fdSTejun Heo 
5249a0a1a5fdSTejun Heo /**
525058a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
5251a0a1a5fdSTejun Heo  *
5252a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
5253a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
5254a0a1a5fdSTejun Heo  *
5255a0a1a5fdSTejun Heo  * CONTEXT:
525668e13a67SLai Jiangshan  * Grabs and releases wq_pool_mutex.
5257a0a1a5fdSTejun Heo  *
5258d185af30SYacine Belkadi  * Return:
525958a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
526058a69cb4STejun Heo  * is complete.
5261a0a1a5fdSTejun Heo  */
5262a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
5263a0a1a5fdSTejun Heo {
5264a0a1a5fdSTejun Heo 	bool busy = false;
526524b8a847STejun Heo 	struct workqueue_struct *wq;
526624b8a847STejun Heo 	struct pool_workqueue *pwq;
5267a0a1a5fdSTejun Heo 
526868e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5269a0a1a5fdSTejun Heo 
52706183c009STejun Heo 	WARN_ON_ONCE(!workqueue_freezing);
5271a0a1a5fdSTejun Heo 
527224b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
527324b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
527424b8a847STejun Heo 			continue;
5275a0a1a5fdSTejun Heo 		/*
5276a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
5277a0a1a5fdSTejun Heo 		 * to peek without lock.
5278a0a1a5fdSTejun Heo 		 */
527924acfb71SThomas Gleixner 		rcu_read_lock();
528024b8a847STejun Heo 		for_each_pwq(pwq, wq) {
52816183c009STejun Heo 			WARN_ON_ONCE(pwq->nr_active < 0);
5282112202d9STejun Heo 			if (pwq->nr_active) {
5283a0a1a5fdSTejun Heo 				busy = true;
528424acfb71SThomas Gleixner 				rcu_read_unlock();
5285a0a1a5fdSTejun Heo 				goto out_unlock;
5286a0a1a5fdSTejun Heo 			}
5287a0a1a5fdSTejun Heo 		}
528824acfb71SThomas Gleixner 		rcu_read_unlock();
5289a0a1a5fdSTejun Heo 	}
5290a0a1a5fdSTejun Heo out_unlock:
529168e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5292a0a1a5fdSTejun Heo 	return busy;
5293a0a1a5fdSTejun Heo }
5294a0a1a5fdSTejun Heo 
5295a0a1a5fdSTejun Heo /**
5296a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
5297a0a1a5fdSTejun Heo  *
5298a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
5299706026c2STejun Heo  * frozen works are transferred to their respective pool worklists.
5300a0a1a5fdSTejun Heo  *
5301a0a1a5fdSTejun Heo  * CONTEXT:
5302a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5303a0a1a5fdSTejun Heo  */
5304a0a1a5fdSTejun Heo void thaw_workqueues(void)
5305a0a1a5fdSTejun Heo {
530624b8a847STejun Heo 	struct workqueue_struct *wq;
530724b8a847STejun Heo 	struct pool_workqueue *pwq;
5308a0a1a5fdSTejun Heo 
530968e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5310a0a1a5fdSTejun Heo 
5311a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
5312a0a1a5fdSTejun Heo 		goto out_unlock;
5313a0a1a5fdSTejun Heo 
531474b414eaSLai Jiangshan 	workqueue_freezing = false;
531524b8a847STejun Heo 
531624b8a847STejun Heo 	/* restore max_active and repopulate worklist */
531724b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5318a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
5319699ce097STejun Heo 		for_each_pwq(pwq, wq)
5320699ce097STejun Heo 			pwq_adjust_max_active(pwq);
5321a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
532224b8a847STejun Heo 	}
532324b8a847STejun Heo 
5324a0a1a5fdSTejun Heo out_unlock:
532568e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5326a0a1a5fdSTejun Heo }
5327a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
5328a0a1a5fdSTejun Heo 
5329042f7df1SLai Jiangshan static int workqueue_apply_unbound_cpumask(void)
5330042f7df1SLai Jiangshan {
5331042f7df1SLai Jiangshan 	LIST_HEAD(ctxs);
5332042f7df1SLai Jiangshan 	int ret = 0;
5333042f7df1SLai Jiangshan 	struct workqueue_struct *wq;
5334042f7df1SLai Jiangshan 	struct apply_wqattrs_ctx *ctx, *n;
5335042f7df1SLai Jiangshan 
5336042f7df1SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5337042f7df1SLai Jiangshan 
5338042f7df1SLai Jiangshan 	list_for_each_entry(wq, &workqueues, list) {
5339042f7df1SLai Jiangshan 		if (!(wq->flags & WQ_UNBOUND))
5340042f7df1SLai Jiangshan 			continue;
5341042f7df1SLai Jiangshan 		/* creating multiple pwqs breaks ordering guarantee */
5342042f7df1SLai Jiangshan 		if (wq->flags & __WQ_ORDERED)
5343042f7df1SLai Jiangshan 			continue;
5344042f7df1SLai Jiangshan 
5345042f7df1SLai Jiangshan 		ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs);
5346042f7df1SLai Jiangshan 		if (!ctx) {
5347042f7df1SLai Jiangshan 			ret = -ENOMEM;
5348042f7df1SLai Jiangshan 			break;
5349042f7df1SLai Jiangshan 		}
5350042f7df1SLai Jiangshan 
5351042f7df1SLai Jiangshan 		list_add_tail(&ctx->list, &ctxs);
5352042f7df1SLai Jiangshan 	}
5353042f7df1SLai Jiangshan 
5354042f7df1SLai Jiangshan 	list_for_each_entry_safe(ctx, n, &ctxs, list) {
5355042f7df1SLai Jiangshan 		if (!ret)
5356042f7df1SLai Jiangshan 			apply_wqattrs_commit(ctx);
5357042f7df1SLai Jiangshan 		apply_wqattrs_cleanup(ctx);
5358042f7df1SLai Jiangshan 	}
5359042f7df1SLai Jiangshan 
5360042f7df1SLai Jiangshan 	return ret;
5361042f7df1SLai Jiangshan }
5362042f7df1SLai Jiangshan 
5363042f7df1SLai Jiangshan /**
5364042f7df1SLai Jiangshan  *  workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
5365042f7df1SLai Jiangshan  *  @cpumask: the cpumask to set
5366042f7df1SLai Jiangshan  *
5367042f7df1SLai Jiangshan  *  The low-level workqueues cpumask is a global cpumask that limits
5368042f7df1SLai Jiangshan  *  the affinity of all unbound workqueues.  This function check the @cpumask
5369042f7df1SLai Jiangshan  *  and apply it to all unbound workqueues and updates all pwqs of them.
5370042f7df1SLai Jiangshan  *
537167dc8325SCai Huoqing  *  Return:	0	- Success
5372042f7df1SLai Jiangshan  *  		-EINVAL	- Invalid @cpumask
5373042f7df1SLai Jiangshan  *  		-ENOMEM	- Failed to allocate memory for attrs or pwqs.
5374042f7df1SLai Jiangshan  */
5375042f7df1SLai Jiangshan int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
5376042f7df1SLai Jiangshan {
5377042f7df1SLai Jiangshan 	int ret = -EINVAL;
5378042f7df1SLai Jiangshan 	cpumask_var_t saved_cpumask;
5379042f7df1SLai Jiangshan 
5380c98a9805STal Shorer 	/*
5381c98a9805STal Shorer 	 * Not excluding isolated cpus on purpose.
5382c98a9805STal Shorer 	 * If the user wishes to include them, we allow that.
5383c98a9805STal Shorer 	 */
5384042f7df1SLai Jiangshan 	cpumask_and(cpumask, cpumask, cpu_possible_mask);
5385042f7df1SLai Jiangshan 	if (!cpumask_empty(cpumask)) {
5386a0111cf6SLai Jiangshan 		apply_wqattrs_lock();
5387d25302e4SMenglong Dong 		if (cpumask_equal(cpumask, wq_unbound_cpumask)) {
5388d25302e4SMenglong Dong 			ret = 0;
5389d25302e4SMenglong Dong 			goto out_unlock;
5390d25302e4SMenglong Dong 		}
5391d25302e4SMenglong Dong 
5392d25302e4SMenglong Dong 		if (!zalloc_cpumask_var(&saved_cpumask, GFP_KERNEL)) {
5393d25302e4SMenglong Dong 			ret = -ENOMEM;
5394d25302e4SMenglong Dong 			goto out_unlock;
5395d25302e4SMenglong Dong 		}
5396042f7df1SLai Jiangshan 
5397042f7df1SLai Jiangshan 		/* save the old wq_unbound_cpumask. */
5398042f7df1SLai Jiangshan 		cpumask_copy(saved_cpumask, wq_unbound_cpumask);
5399042f7df1SLai Jiangshan 
5400042f7df1SLai Jiangshan 		/* update wq_unbound_cpumask at first and apply it to wqs. */
5401042f7df1SLai Jiangshan 		cpumask_copy(wq_unbound_cpumask, cpumask);
5402042f7df1SLai Jiangshan 		ret = workqueue_apply_unbound_cpumask();
5403042f7df1SLai Jiangshan 
5404042f7df1SLai Jiangshan 		/* restore the wq_unbound_cpumask when failed. */
5405042f7df1SLai Jiangshan 		if (ret < 0)
5406042f7df1SLai Jiangshan 			cpumask_copy(wq_unbound_cpumask, saved_cpumask);
5407042f7df1SLai Jiangshan 
5408d25302e4SMenglong Dong 		free_cpumask_var(saved_cpumask);
5409d25302e4SMenglong Dong out_unlock:
5410a0111cf6SLai Jiangshan 		apply_wqattrs_unlock();
5411042f7df1SLai Jiangshan 	}
5412042f7df1SLai Jiangshan 
5413042f7df1SLai Jiangshan 	return ret;
5414042f7df1SLai Jiangshan }
5415042f7df1SLai Jiangshan 
54166ba94429SFrederic Weisbecker #ifdef CONFIG_SYSFS
54176ba94429SFrederic Weisbecker /*
54186ba94429SFrederic Weisbecker  * Workqueues with WQ_SYSFS flag set is visible to userland via
54196ba94429SFrederic Weisbecker  * /sys/bus/workqueue/devices/WQ_NAME.  All visible workqueues have the
54206ba94429SFrederic Weisbecker  * following attributes.
54216ba94429SFrederic Weisbecker  *
54226ba94429SFrederic Weisbecker  *  per_cpu	RO bool	: whether the workqueue is per-cpu or unbound
54236ba94429SFrederic Weisbecker  *  max_active	RW int	: maximum number of in-flight work items
54246ba94429SFrederic Weisbecker  *
54256ba94429SFrederic Weisbecker  * Unbound workqueues have the following extra attributes.
54266ba94429SFrederic Weisbecker  *
54279a19b463SWang Long  *  pool_ids	RO int	: the associated pool IDs for each node
54286ba94429SFrederic Weisbecker  *  nice	RW int	: nice value of the workers
54296ba94429SFrederic Weisbecker  *  cpumask	RW mask	: bitmask of allowed CPUs for the workers
54309a19b463SWang Long  *  numa	RW bool	: whether enable NUMA affinity
54316ba94429SFrederic Weisbecker  */
54326ba94429SFrederic Weisbecker struct wq_device {
54336ba94429SFrederic Weisbecker 	struct workqueue_struct		*wq;
54346ba94429SFrederic Weisbecker 	struct device			dev;
54356ba94429SFrederic Weisbecker };
54366ba94429SFrederic Weisbecker 
54376ba94429SFrederic Weisbecker static struct workqueue_struct *dev_to_wq(struct device *dev)
54386ba94429SFrederic Weisbecker {
54396ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
54406ba94429SFrederic Weisbecker 
54416ba94429SFrederic Weisbecker 	return wq_dev->wq;
54426ba94429SFrederic Weisbecker }
54436ba94429SFrederic Weisbecker 
54446ba94429SFrederic Weisbecker static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
54456ba94429SFrederic Weisbecker 			    char *buf)
54466ba94429SFrederic Weisbecker {
54476ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
54486ba94429SFrederic Weisbecker 
54496ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
54506ba94429SFrederic Weisbecker }
54516ba94429SFrederic Weisbecker static DEVICE_ATTR_RO(per_cpu);
54526ba94429SFrederic Weisbecker 
54536ba94429SFrederic Weisbecker static ssize_t max_active_show(struct device *dev,
54546ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
54556ba94429SFrederic Weisbecker {
54566ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
54576ba94429SFrederic Weisbecker 
54586ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
54596ba94429SFrederic Weisbecker }
54606ba94429SFrederic Weisbecker 
54616ba94429SFrederic Weisbecker static ssize_t max_active_store(struct device *dev,
54626ba94429SFrederic Weisbecker 				struct device_attribute *attr, const char *buf,
54636ba94429SFrederic Weisbecker 				size_t count)
54646ba94429SFrederic Weisbecker {
54656ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
54666ba94429SFrederic Weisbecker 	int val;
54676ba94429SFrederic Weisbecker 
54686ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &val) != 1 || val <= 0)
54696ba94429SFrederic Weisbecker 		return -EINVAL;
54706ba94429SFrederic Weisbecker 
54716ba94429SFrederic Weisbecker 	workqueue_set_max_active(wq, val);
54726ba94429SFrederic Weisbecker 	return count;
54736ba94429SFrederic Weisbecker }
54746ba94429SFrederic Weisbecker static DEVICE_ATTR_RW(max_active);
54756ba94429SFrederic Weisbecker 
54766ba94429SFrederic Weisbecker static struct attribute *wq_sysfs_attrs[] = {
54776ba94429SFrederic Weisbecker 	&dev_attr_per_cpu.attr,
54786ba94429SFrederic Weisbecker 	&dev_attr_max_active.attr,
54796ba94429SFrederic Weisbecker 	NULL,
54806ba94429SFrederic Weisbecker };
54816ba94429SFrederic Weisbecker ATTRIBUTE_GROUPS(wq_sysfs);
54826ba94429SFrederic Weisbecker 
54836ba94429SFrederic Weisbecker static ssize_t wq_pool_ids_show(struct device *dev,
54846ba94429SFrederic Weisbecker 				struct device_attribute *attr, char *buf)
54856ba94429SFrederic Weisbecker {
54866ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
54876ba94429SFrederic Weisbecker 	const char *delim = "";
54886ba94429SFrederic Weisbecker 	int node, written = 0;
54896ba94429SFrederic Weisbecker 
5490ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
549124acfb71SThomas Gleixner 	rcu_read_lock();
54926ba94429SFrederic Weisbecker 	for_each_node(node) {
54936ba94429SFrederic Weisbecker 		written += scnprintf(buf + written, PAGE_SIZE - written,
54946ba94429SFrederic Weisbecker 				     "%s%d:%d", delim, node,
54956ba94429SFrederic Weisbecker 				     unbound_pwq_by_node(wq, node)->pool->id);
54966ba94429SFrederic Weisbecker 		delim = " ";
54976ba94429SFrederic Weisbecker 	}
54986ba94429SFrederic Weisbecker 	written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
549924acfb71SThomas Gleixner 	rcu_read_unlock();
5500ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
55016ba94429SFrederic Weisbecker 
55026ba94429SFrederic Weisbecker 	return written;
55036ba94429SFrederic Weisbecker }
55046ba94429SFrederic Weisbecker 
55056ba94429SFrederic Weisbecker static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
55066ba94429SFrederic Weisbecker 			    char *buf)
55076ba94429SFrederic Weisbecker {
55086ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
55096ba94429SFrederic Weisbecker 	int written;
55106ba94429SFrederic Weisbecker 
55116ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
55126ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
55136ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
55146ba94429SFrederic Weisbecker 
55156ba94429SFrederic Weisbecker 	return written;
55166ba94429SFrederic Weisbecker }
55176ba94429SFrederic Weisbecker 
55186ba94429SFrederic Weisbecker /* prepare workqueue_attrs for sysfs store operations */
55196ba94429SFrederic Weisbecker static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
55206ba94429SFrederic Weisbecker {
55216ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
55226ba94429SFrederic Weisbecker 
5523899a94feSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5524899a94feSLai Jiangshan 
5525be69d00dSThomas Gleixner 	attrs = alloc_workqueue_attrs();
55266ba94429SFrederic Weisbecker 	if (!attrs)
55276ba94429SFrederic Weisbecker 		return NULL;
55286ba94429SFrederic Weisbecker 
55296ba94429SFrederic Weisbecker 	copy_workqueue_attrs(attrs, wq->unbound_attrs);
55306ba94429SFrederic Weisbecker 	return attrs;
55316ba94429SFrederic Weisbecker }
55326ba94429SFrederic Weisbecker 
55336ba94429SFrederic Weisbecker static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
55346ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
55356ba94429SFrederic Weisbecker {
55366ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
55376ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5538d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
5539d4d3e257SLai Jiangshan 
5540d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
55416ba94429SFrederic Weisbecker 
55426ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
55436ba94429SFrederic Weisbecker 	if (!attrs)
5544d4d3e257SLai Jiangshan 		goto out_unlock;
55456ba94429SFrederic Weisbecker 
55466ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &attrs->nice) == 1 &&
55476ba94429SFrederic Weisbecker 	    attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
5548d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
55496ba94429SFrederic Weisbecker 	else
55506ba94429SFrederic Weisbecker 		ret = -EINVAL;
55516ba94429SFrederic Weisbecker 
5552d4d3e257SLai Jiangshan out_unlock:
5553d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
55546ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
55556ba94429SFrederic Weisbecker 	return ret ?: count;
55566ba94429SFrederic Weisbecker }
55576ba94429SFrederic Weisbecker 
55586ba94429SFrederic Weisbecker static ssize_t wq_cpumask_show(struct device *dev,
55596ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
55606ba94429SFrederic Weisbecker {
55616ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
55626ba94429SFrederic Weisbecker 	int written;
55636ba94429SFrederic Weisbecker 
55646ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
55656ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
55666ba94429SFrederic Weisbecker 			    cpumask_pr_args(wq->unbound_attrs->cpumask));
55676ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
55686ba94429SFrederic Weisbecker 	return written;
55696ba94429SFrederic Weisbecker }
55706ba94429SFrederic Weisbecker 
55716ba94429SFrederic Weisbecker static ssize_t wq_cpumask_store(struct device *dev,
55726ba94429SFrederic Weisbecker 				struct device_attribute *attr,
55736ba94429SFrederic Weisbecker 				const char *buf, size_t count)
55746ba94429SFrederic Weisbecker {
55756ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
55766ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5577d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
5578d4d3e257SLai Jiangshan 
5579d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
55806ba94429SFrederic Weisbecker 
55816ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
55826ba94429SFrederic Weisbecker 	if (!attrs)
5583d4d3e257SLai Jiangshan 		goto out_unlock;
55846ba94429SFrederic Weisbecker 
55856ba94429SFrederic Weisbecker 	ret = cpumask_parse(buf, attrs->cpumask);
55866ba94429SFrederic Weisbecker 	if (!ret)
5587d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
55886ba94429SFrederic Weisbecker 
5589d4d3e257SLai Jiangshan out_unlock:
5590d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
55916ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
55926ba94429SFrederic Weisbecker 	return ret ?: count;
55936ba94429SFrederic Weisbecker }
55946ba94429SFrederic Weisbecker 
55956ba94429SFrederic Weisbecker static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
55966ba94429SFrederic Weisbecker 			    char *buf)
55976ba94429SFrederic Weisbecker {
55986ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
55996ba94429SFrederic Weisbecker 	int written;
56006ba94429SFrederic Weisbecker 
56016ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
56026ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n",
56036ba94429SFrederic Weisbecker 			    !wq->unbound_attrs->no_numa);
56046ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
56056ba94429SFrederic Weisbecker 
56066ba94429SFrederic Weisbecker 	return written;
56076ba94429SFrederic Weisbecker }
56086ba94429SFrederic Weisbecker 
56096ba94429SFrederic Weisbecker static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
56106ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
56116ba94429SFrederic Weisbecker {
56126ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
56136ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5614d4d3e257SLai Jiangshan 	int v, ret = -ENOMEM;
5615d4d3e257SLai Jiangshan 
5616d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
56176ba94429SFrederic Weisbecker 
56186ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
56196ba94429SFrederic Weisbecker 	if (!attrs)
5620d4d3e257SLai Jiangshan 		goto out_unlock;
56216ba94429SFrederic Weisbecker 
56226ba94429SFrederic Weisbecker 	ret = -EINVAL;
56236ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &v) == 1) {
56246ba94429SFrederic Weisbecker 		attrs->no_numa = !v;
5625d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
56266ba94429SFrederic Weisbecker 	}
56276ba94429SFrederic Weisbecker 
5628d4d3e257SLai Jiangshan out_unlock:
5629d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
56306ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
56316ba94429SFrederic Weisbecker 	return ret ?: count;
56326ba94429SFrederic Weisbecker }
56336ba94429SFrederic Weisbecker 
56346ba94429SFrederic Weisbecker static struct device_attribute wq_sysfs_unbound_attrs[] = {
56356ba94429SFrederic Weisbecker 	__ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
56366ba94429SFrederic Weisbecker 	__ATTR(nice, 0644, wq_nice_show, wq_nice_store),
56376ba94429SFrederic Weisbecker 	__ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
56386ba94429SFrederic Weisbecker 	__ATTR(numa, 0644, wq_numa_show, wq_numa_store),
56396ba94429SFrederic Weisbecker 	__ATTR_NULL,
56406ba94429SFrederic Weisbecker };
56416ba94429SFrederic Weisbecker 
56426ba94429SFrederic Weisbecker static struct bus_type wq_subsys = {
56436ba94429SFrederic Weisbecker 	.name				= "workqueue",
56446ba94429SFrederic Weisbecker 	.dev_groups			= wq_sysfs_groups,
56456ba94429SFrederic Weisbecker };
56466ba94429SFrederic Weisbecker 
5647b05a7928SFrederic Weisbecker static ssize_t wq_unbound_cpumask_show(struct device *dev,
5648b05a7928SFrederic Weisbecker 		struct device_attribute *attr, char *buf)
5649b05a7928SFrederic Weisbecker {
5650b05a7928SFrederic Weisbecker 	int written;
5651b05a7928SFrederic Weisbecker 
5652042f7df1SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5653b05a7928SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
5654b05a7928SFrederic Weisbecker 			    cpumask_pr_args(wq_unbound_cpumask));
5655042f7df1SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5656b05a7928SFrederic Weisbecker 
5657b05a7928SFrederic Weisbecker 	return written;
5658b05a7928SFrederic Weisbecker }
5659b05a7928SFrederic Weisbecker 
5660042f7df1SLai Jiangshan static ssize_t wq_unbound_cpumask_store(struct device *dev,
5661042f7df1SLai Jiangshan 		struct device_attribute *attr, const char *buf, size_t count)
5662042f7df1SLai Jiangshan {
5663042f7df1SLai Jiangshan 	cpumask_var_t cpumask;
5664042f7df1SLai Jiangshan 	int ret;
5665042f7df1SLai Jiangshan 
5666042f7df1SLai Jiangshan 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
5667042f7df1SLai Jiangshan 		return -ENOMEM;
5668042f7df1SLai Jiangshan 
5669042f7df1SLai Jiangshan 	ret = cpumask_parse(buf, cpumask);
5670042f7df1SLai Jiangshan 	if (!ret)
5671042f7df1SLai Jiangshan 		ret = workqueue_set_unbound_cpumask(cpumask);
5672042f7df1SLai Jiangshan 
5673042f7df1SLai Jiangshan 	free_cpumask_var(cpumask);
5674042f7df1SLai Jiangshan 	return ret ? ret : count;
5675042f7df1SLai Jiangshan }
5676042f7df1SLai Jiangshan 
5677b05a7928SFrederic Weisbecker static struct device_attribute wq_sysfs_cpumask_attr =
5678042f7df1SLai Jiangshan 	__ATTR(cpumask, 0644, wq_unbound_cpumask_show,
5679042f7df1SLai Jiangshan 	       wq_unbound_cpumask_store);
5680b05a7928SFrederic Weisbecker 
56816ba94429SFrederic Weisbecker static int __init wq_sysfs_init(void)
56826ba94429SFrederic Weisbecker {
5683b05a7928SFrederic Weisbecker 	int err;
5684b05a7928SFrederic Weisbecker 
5685b05a7928SFrederic Weisbecker 	err = subsys_virtual_register(&wq_subsys, NULL);
5686b05a7928SFrederic Weisbecker 	if (err)
5687b05a7928SFrederic Weisbecker 		return err;
5688b05a7928SFrederic Weisbecker 
5689b05a7928SFrederic Weisbecker 	return device_create_file(wq_subsys.dev_root, &wq_sysfs_cpumask_attr);
56906ba94429SFrederic Weisbecker }
56916ba94429SFrederic Weisbecker core_initcall(wq_sysfs_init);
56926ba94429SFrederic Weisbecker 
56936ba94429SFrederic Weisbecker static void wq_device_release(struct device *dev)
56946ba94429SFrederic Weisbecker {
56956ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
56966ba94429SFrederic Weisbecker 
56976ba94429SFrederic Weisbecker 	kfree(wq_dev);
56986ba94429SFrederic Weisbecker }
56996ba94429SFrederic Weisbecker 
57006ba94429SFrederic Weisbecker /**
57016ba94429SFrederic Weisbecker  * workqueue_sysfs_register - make a workqueue visible in sysfs
57026ba94429SFrederic Weisbecker  * @wq: the workqueue to register
57036ba94429SFrederic Weisbecker  *
57046ba94429SFrederic Weisbecker  * Expose @wq in sysfs under /sys/bus/workqueue/devices.
57056ba94429SFrederic Weisbecker  * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
57066ba94429SFrederic Weisbecker  * which is the preferred method.
57076ba94429SFrederic Weisbecker  *
57086ba94429SFrederic Weisbecker  * Workqueue user should use this function directly iff it wants to apply
57096ba94429SFrederic Weisbecker  * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
57106ba94429SFrederic Weisbecker  * apply_workqueue_attrs() may race against userland updating the
57116ba94429SFrederic Weisbecker  * attributes.
57126ba94429SFrederic Weisbecker  *
57136ba94429SFrederic Weisbecker  * Return: 0 on success, -errno on failure.
57146ba94429SFrederic Weisbecker  */
57156ba94429SFrederic Weisbecker int workqueue_sysfs_register(struct workqueue_struct *wq)
57166ba94429SFrederic Weisbecker {
57176ba94429SFrederic Weisbecker 	struct wq_device *wq_dev;
57186ba94429SFrederic Weisbecker 	int ret;
57196ba94429SFrederic Weisbecker 
57206ba94429SFrederic Weisbecker 	/*
5721402dd89dSShailendra Verma 	 * Adjusting max_active or creating new pwqs by applying
57226ba94429SFrederic Weisbecker 	 * attributes breaks ordering guarantee.  Disallow exposing ordered
57236ba94429SFrederic Weisbecker 	 * workqueues.
57246ba94429SFrederic Weisbecker 	 */
57250a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
57266ba94429SFrederic Weisbecker 		return -EINVAL;
57276ba94429SFrederic Weisbecker 
57286ba94429SFrederic Weisbecker 	wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
57296ba94429SFrederic Weisbecker 	if (!wq_dev)
57306ba94429SFrederic Weisbecker 		return -ENOMEM;
57316ba94429SFrederic Weisbecker 
57326ba94429SFrederic Weisbecker 	wq_dev->wq = wq;
57336ba94429SFrederic Weisbecker 	wq_dev->dev.bus = &wq_subsys;
57346ba94429SFrederic Weisbecker 	wq_dev->dev.release = wq_device_release;
573523217b44SLars-Peter Clausen 	dev_set_name(&wq_dev->dev, "%s", wq->name);
57366ba94429SFrederic Weisbecker 
57376ba94429SFrederic Weisbecker 	/*
57386ba94429SFrederic Weisbecker 	 * unbound_attrs are created separately.  Suppress uevent until
57396ba94429SFrederic Weisbecker 	 * everything is ready.
57406ba94429SFrederic Weisbecker 	 */
57416ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, true);
57426ba94429SFrederic Weisbecker 
57436ba94429SFrederic Weisbecker 	ret = device_register(&wq_dev->dev);
57446ba94429SFrederic Weisbecker 	if (ret) {
5745537f4146SArvind Yadav 		put_device(&wq_dev->dev);
57466ba94429SFrederic Weisbecker 		wq->wq_dev = NULL;
57476ba94429SFrederic Weisbecker 		return ret;
57486ba94429SFrederic Weisbecker 	}
57496ba94429SFrederic Weisbecker 
57506ba94429SFrederic Weisbecker 	if (wq->flags & WQ_UNBOUND) {
57516ba94429SFrederic Weisbecker 		struct device_attribute *attr;
57526ba94429SFrederic Weisbecker 
57536ba94429SFrederic Weisbecker 		for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
57546ba94429SFrederic Weisbecker 			ret = device_create_file(&wq_dev->dev, attr);
57556ba94429SFrederic Weisbecker 			if (ret) {
57566ba94429SFrederic Weisbecker 				device_unregister(&wq_dev->dev);
57576ba94429SFrederic Weisbecker 				wq->wq_dev = NULL;
57586ba94429SFrederic Weisbecker 				return ret;
57596ba94429SFrederic Weisbecker 			}
57606ba94429SFrederic Weisbecker 		}
57616ba94429SFrederic Weisbecker 	}
57626ba94429SFrederic Weisbecker 
57636ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, false);
57646ba94429SFrederic Weisbecker 	kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
57656ba94429SFrederic Weisbecker 	return 0;
57666ba94429SFrederic Weisbecker }
57676ba94429SFrederic Weisbecker 
57686ba94429SFrederic Weisbecker /**
57696ba94429SFrederic Weisbecker  * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
57706ba94429SFrederic Weisbecker  * @wq: the workqueue to unregister
57716ba94429SFrederic Weisbecker  *
57726ba94429SFrederic Weisbecker  * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
57736ba94429SFrederic Weisbecker  */
57746ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
57756ba94429SFrederic Weisbecker {
57766ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = wq->wq_dev;
57776ba94429SFrederic Weisbecker 
57786ba94429SFrederic Weisbecker 	if (!wq->wq_dev)
57796ba94429SFrederic Weisbecker 		return;
57806ba94429SFrederic Weisbecker 
57816ba94429SFrederic Weisbecker 	wq->wq_dev = NULL;
57826ba94429SFrederic Weisbecker 	device_unregister(&wq_dev->dev);
57836ba94429SFrederic Weisbecker }
57846ba94429SFrederic Weisbecker #else	/* CONFIG_SYSFS */
57856ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)	{ }
57866ba94429SFrederic Weisbecker #endif	/* CONFIG_SYSFS */
57876ba94429SFrederic Weisbecker 
578882607adcSTejun Heo /*
578982607adcSTejun Heo  * Workqueue watchdog.
579082607adcSTejun Heo  *
579182607adcSTejun Heo  * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
579282607adcSTejun Heo  * flush dependency, a concurrency managed work item which stays RUNNING
579382607adcSTejun Heo  * indefinitely.  Workqueue stalls can be very difficult to debug as the
579482607adcSTejun Heo  * usual warning mechanisms don't trigger and internal workqueue state is
579582607adcSTejun Heo  * largely opaque.
579682607adcSTejun Heo  *
579782607adcSTejun Heo  * Workqueue watchdog monitors all worker pools periodically and dumps
579882607adcSTejun Heo  * state if some pools failed to make forward progress for a while where
579982607adcSTejun Heo  * forward progress is defined as the first item on ->worklist changing.
580082607adcSTejun Heo  *
580182607adcSTejun Heo  * This mechanism is controlled through the kernel parameter
580282607adcSTejun Heo  * "workqueue.watchdog_thresh" which can be updated at runtime through the
580382607adcSTejun Heo  * corresponding sysfs parameter file.
580482607adcSTejun Heo  */
580582607adcSTejun Heo #ifdef CONFIG_WQ_WATCHDOG
580682607adcSTejun Heo 
580782607adcSTejun Heo static unsigned long wq_watchdog_thresh = 30;
58085cd79d6aSKees Cook static struct timer_list wq_watchdog_timer;
580982607adcSTejun Heo 
581082607adcSTejun Heo static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
581182607adcSTejun Heo static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
581282607adcSTejun Heo 
581382607adcSTejun Heo static void wq_watchdog_reset_touched(void)
581482607adcSTejun Heo {
581582607adcSTejun Heo 	int cpu;
581682607adcSTejun Heo 
581782607adcSTejun Heo 	wq_watchdog_touched = jiffies;
581882607adcSTejun Heo 	for_each_possible_cpu(cpu)
581982607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
582082607adcSTejun Heo }
582182607adcSTejun Heo 
58225cd79d6aSKees Cook static void wq_watchdog_timer_fn(struct timer_list *unused)
582382607adcSTejun Heo {
582482607adcSTejun Heo 	unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
582582607adcSTejun Heo 	bool lockup_detected = false;
5826940d71c6SSergey Senozhatsky 	unsigned long now = jiffies;
582782607adcSTejun Heo 	struct worker_pool *pool;
582882607adcSTejun Heo 	int pi;
582982607adcSTejun Heo 
583082607adcSTejun Heo 	if (!thresh)
583182607adcSTejun Heo 		return;
583282607adcSTejun Heo 
583382607adcSTejun Heo 	rcu_read_lock();
583482607adcSTejun Heo 
583582607adcSTejun Heo 	for_each_pool(pool, pi) {
583682607adcSTejun Heo 		unsigned long pool_ts, touched, ts;
583782607adcSTejun Heo 
583882607adcSTejun Heo 		if (list_empty(&pool->worklist))
583982607adcSTejun Heo 			continue;
584082607adcSTejun Heo 
5841940d71c6SSergey Senozhatsky 		/*
5842940d71c6SSergey Senozhatsky 		 * If a virtual machine is stopped by the host it can look to
5843940d71c6SSergey Senozhatsky 		 * the watchdog like a stall.
5844940d71c6SSergey Senozhatsky 		 */
5845940d71c6SSergey Senozhatsky 		kvm_check_and_clear_guest_paused();
5846940d71c6SSergey Senozhatsky 
584782607adcSTejun Heo 		/* get the latest of pool and touched timestamps */
584889e28ce6SWang Qing 		if (pool->cpu >= 0)
584989e28ce6SWang Qing 			touched = READ_ONCE(per_cpu(wq_watchdog_touched_cpu, pool->cpu));
585089e28ce6SWang Qing 		else
585182607adcSTejun Heo 			touched = READ_ONCE(wq_watchdog_touched);
585289e28ce6SWang Qing 		pool_ts = READ_ONCE(pool->watchdog_ts);
585382607adcSTejun Heo 
585482607adcSTejun Heo 		if (time_after(pool_ts, touched))
585582607adcSTejun Heo 			ts = pool_ts;
585682607adcSTejun Heo 		else
585782607adcSTejun Heo 			ts = touched;
585882607adcSTejun Heo 
585982607adcSTejun Heo 		/* did we stall? */
5860940d71c6SSergey Senozhatsky 		if (time_after(now, ts + thresh)) {
586182607adcSTejun Heo 			lockup_detected = true;
586282607adcSTejun Heo 			pr_emerg("BUG: workqueue lockup - pool");
586382607adcSTejun Heo 			pr_cont_pool_info(pool);
586482607adcSTejun Heo 			pr_cont(" stuck for %us!\n",
5865940d71c6SSergey Senozhatsky 				jiffies_to_msecs(now - pool_ts) / 1000);
586682607adcSTejun Heo 		}
586782607adcSTejun Heo 	}
586882607adcSTejun Heo 
586982607adcSTejun Heo 	rcu_read_unlock();
587082607adcSTejun Heo 
587182607adcSTejun Heo 	if (lockup_detected)
587255df0933SImran Khan 		show_all_workqueues();
587382607adcSTejun Heo 
587482607adcSTejun Heo 	wq_watchdog_reset_touched();
587582607adcSTejun Heo 	mod_timer(&wq_watchdog_timer, jiffies + thresh);
587682607adcSTejun Heo }
587782607adcSTejun Heo 
5878cb9d7fd5SVincent Whitchurch notrace void wq_watchdog_touch(int cpu)
587982607adcSTejun Heo {
588082607adcSTejun Heo 	if (cpu >= 0)
588182607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
588289e28ce6SWang Qing 
588382607adcSTejun Heo 	wq_watchdog_touched = jiffies;
588482607adcSTejun Heo }
588582607adcSTejun Heo 
588682607adcSTejun Heo static void wq_watchdog_set_thresh(unsigned long thresh)
588782607adcSTejun Heo {
588882607adcSTejun Heo 	wq_watchdog_thresh = 0;
588982607adcSTejun Heo 	del_timer_sync(&wq_watchdog_timer);
589082607adcSTejun Heo 
589182607adcSTejun Heo 	if (thresh) {
589282607adcSTejun Heo 		wq_watchdog_thresh = thresh;
589382607adcSTejun Heo 		wq_watchdog_reset_touched();
589482607adcSTejun Heo 		mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
589582607adcSTejun Heo 	}
589682607adcSTejun Heo }
589782607adcSTejun Heo 
589882607adcSTejun Heo static int wq_watchdog_param_set_thresh(const char *val,
589982607adcSTejun Heo 					const struct kernel_param *kp)
590082607adcSTejun Heo {
590182607adcSTejun Heo 	unsigned long thresh;
590282607adcSTejun Heo 	int ret;
590382607adcSTejun Heo 
590482607adcSTejun Heo 	ret = kstrtoul(val, 0, &thresh);
590582607adcSTejun Heo 	if (ret)
590682607adcSTejun Heo 		return ret;
590782607adcSTejun Heo 
590882607adcSTejun Heo 	if (system_wq)
590982607adcSTejun Heo 		wq_watchdog_set_thresh(thresh);
591082607adcSTejun Heo 	else
591182607adcSTejun Heo 		wq_watchdog_thresh = thresh;
591282607adcSTejun Heo 
591382607adcSTejun Heo 	return 0;
591482607adcSTejun Heo }
591582607adcSTejun Heo 
591682607adcSTejun Heo static const struct kernel_param_ops wq_watchdog_thresh_ops = {
591782607adcSTejun Heo 	.set	= wq_watchdog_param_set_thresh,
591882607adcSTejun Heo 	.get	= param_get_ulong,
591982607adcSTejun Heo };
592082607adcSTejun Heo 
592182607adcSTejun Heo module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
592282607adcSTejun Heo 		0644);
592382607adcSTejun Heo 
592482607adcSTejun Heo static void wq_watchdog_init(void)
592582607adcSTejun Heo {
59265cd79d6aSKees Cook 	timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
592782607adcSTejun Heo 	wq_watchdog_set_thresh(wq_watchdog_thresh);
592882607adcSTejun Heo }
592982607adcSTejun Heo 
593082607adcSTejun Heo #else	/* CONFIG_WQ_WATCHDOG */
593182607adcSTejun Heo 
593282607adcSTejun Heo static inline void wq_watchdog_init(void) { }
593382607adcSTejun Heo 
593482607adcSTejun Heo #endif	/* CONFIG_WQ_WATCHDOG */
593582607adcSTejun Heo 
5936bce90380STejun Heo static void __init wq_numa_init(void)
5937bce90380STejun Heo {
5938bce90380STejun Heo 	cpumask_var_t *tbl;
5939bce90380STejun Heo 	int node, cpu;
5940bce90380STejun Heo 
5941bce90380STejun Heo 	if (num_possible_nodes() <= 1)
5942bce90380STejun Heo 		return;
5943bce90380STejun Heo 
5944d55262c4STejun Heo 	if (wq_disable_numa) {
5945d55262c4STejun Heo 		pr_info("workqueue: NUMA affinity support disabled\n");
5946d55262c4STejun Heo 		return;
5947d55262c4STejun Heo 	}
5948d55262c4STejun Heo 
5949f728c4a9SZhen Lei 	for_each_possible_cpu(cpu) {
5950f728c4a9SZhen Lei 		if (WARN_ON(cpu_to_node(cpu) == NUMA_NO_NODE)) {
5951f728c4a9SZhen Lei 			pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
5952f728c4a9SZhen Lei 			return;
5953f728c4a9SZhen Lei 		}
5954f728c4a9SZhen Lei 	}
5955f728c4a9SZhen Lei 
5956be69d00dSThomas Gleixner 	wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs();
59574c16bd32STejun Heo 	BUG_ON(!wq_update_unbound_numa_attrs_buf);
59584c16bd32STejun Heo 
5959bce90380STejun Heo 	/*
5960bce90380STejun Heo 	 * We want masks of possible CPUs of each node which isn't readily
5961bce90380STejun Heo 	 * available.  Build one from cpu_to_node() which should have been
5962bce90380STejun Heo 	 * fully initialized by now.
5963bce90380STejun Heo 	 */
59646396bb22SKees Cook 	tbl = kcalloc(nr_node_ids, sizeof(tbl[0]), GFP_KERNEL);
5965bce90380STejun Heo 	BUG_ON(!tbl);
5966bce90380STejun Heo 
5967bce90380STejun Heo 	for_each_node(node)
59685a6024f1SYasuaki Ishimatsu 		BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
59691be0c25dSTejun Heo 				node_online(node) ? node : NUMA_NO_NODE));
5970bce90380STejun Heo 
5971bce90380STejun Heo 	for_each_possible_cpu(cpu) {
5972bce90380STejun Heo 		node = cpu_to_node(cpu);
5973bce90380STejun Heo 		cpumask_set_cpu(cpu, tbl[node]);
5974bce90380STejun Heo 	}
5975bce90380STejun Heo 
5976bce90380STejun Heo 	wq_numa_possible_cpumask = tbl;
5977bce90380STejun Heo 	wq_numa_enabled = true;
5978bce90380STejun Heo }
5979bce90380STejun Heo 
59803347fa09STejun Heo /**
59813347fa09STejun Heo  * workqueue_init_early - early init for workqueue subsystem
59823347fa09STejun Heo  *
59833347fa09STejun Heo  * This is the first half of two-staged workqueue subsystem initialization
59843347fa09STejun Heo  * and invoked as soon as the bare basics - memory allocation, cpumasks and
59853347fa09STejun Heo  * idr are up.  It sets up all the data structures and system workqueues
59863347fa09STejun Heo  * and allows early boot code to create workqueues and queue/cancel work
59873347fa09STejun Heo  * items.  Actual work item execution starts only after kthreads can be
59883347fa09STejun Heo  * created and scheduled right before early initcalls.
59893347fa09STejun Heo  */
59902333e829SYu Chen void __init workqueue_init_early(void)
59911da177e4SLinus Torvalds {
59927a4e344cSTejun Heo 	int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
59931bda3f80SFrederic Weisbecker 	int hk_flags = HK_FLAG_DOMAIN | HK_FLAG_WQ;
59947a4e344cSTejun Heo 	int i, cpu;
5995c34056a3STejun Heo 
599610cdb157SLai Jiangshan 	BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
5997e904e6c2STejun Heo 
5998b05a7928SFrederic Weisbecker 	BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
59991bda3f80SFrederic Weisbecker 	cpumask_copy(wq_unbound_cpumask, housekeeping_cpumask(hk_flags));
6000b05a7928SFrederic Weisbecker 
6001e904e6c2STejun Heo 	pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
6002e904e6c2STejun Heo 
6003706026c2STejun Heo 	/* initialize CPU pools */
600429c91e99STejun Heo 	for_each_possible_cpu(cpu) {
60054ce62e9eSTejun Heo 		struct worker_pool *pool;
60068b03ae3cSTejun Heo 
60077a4e344cSTejun Heo 		i = 0;
6008f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
60097a4e344cSTejun Heo 			BUG_ON(init_worker_pool(pool));
6010ec22ca5eSTejun Heo 			pool->cpu = cpu;
60117a4e344cSTejun Heo 			cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
60127a4e344cSTejun Heo 			pool->attrs->nice = std_nice[i++];
6013f3f90ad4STejun Heo 			pool->node = cpu_to_node(cpu);
60147a4e344cSTejun Heo 
60159daf9e67STejun Heo 			/* alloc pool ID */
601668e13a67SLai Jiangshan 			mutex_lock(&wq_pool_mutex);
60179daf9e67STejun Heo 			BUG_ON(worker_pool_assign_id(pool));
601868e13a67SLai Jiangshan 			mutex_unlock(&wq_pool_mutex);
60194ce62e9eSTejun Heo 		}
60208b03ae3cSTejun Heo 	}
60218b03ae3cSTejun Heo 
60228a2b7538STejun Heo 	/* create default unbound and ordered wq attrs */
602329c91e99STejun Heo 	for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
602429c91e99STejun Heo 		struct workqueue_attrs *attrs;
602529c91e99STejun Heo 
6026be69d00dSThomas Gleixner 		BUG_ON(!(attrs = alloc_workqueue_attrs()));
602729c91e99STejun Heo 		attrs->nice = std_nice[i];
602829c91e99STejun Heo 		unbound_std_wq_attrs[i] = attrs;
60298a2b7538STejun Heo 
60308a2b7538STejun Heo 		/*
60318a2b7538STejun Heo 		 * An ordered wq should have only one pwq as ordering is
60328a2b7538STejun Heo 		 * guaranteed by max_active which is enforced by pwqs.
60338a2b7538STejun Heo 		 * Turn off NUMA so that dfl_pwq is used for all nodes.
60348a2b7538STejun Heo 		 */
6035be69d00dSThomas Gleixner 		BUG_ON(!(attrs = alloc_workqueue_attrs()));
60368a2b7538STejun Heo 		attrs->nice = std_nice[i];
60378a2b7538STejun Heo 		attrs->no_numa = true;
60388a2b7538STejun Heo 		ordered_wq_attrs[i] = attrs;
603929c91e99STejun Heo 	}
604029c91e99STejun Heo 
6041d320c038STejun Heo 	system_wq = alloc_workqueue("events", 0, 0);
60421aabe902SJoonsoo Kim 	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
6043d320c038STejun Heo 	system_long_wq = alloc_workqueue("events_long", 0, 0);
6044f3421797STejun Heo 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
6045f3421797STejun Heo 					    WQ_UNBOUND_MAX_ACTIVE);
604624d51addSTejun Heo 	system_freezable_wq = alloc_workqueue("events_freezable",
604724d51addSTejun Heo 					      WQ_FREEZABLE, 0);
60480668106cSViresh Kumar 	system_power_efficient_wq = alloc_workqueue("events_power_efficient",
60490668106cSViresh Kumar 					      WQ_POWER_EFFICIENT, 0);
60500668106cSViresh Kumar 	system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
60510668106cSViresh Kumar 					      WQ_FREEZABLE | WQ_POWER_EFFICIENT,
60520668106cSViresh Kumar 					      0);
60531aabe902SJoonsoo Kim 	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
60540668106cSViresh Kumar 	       !system_unbound_wq || !system_freezable_wq ||
60550668106cSViresh Kumar 	       !system_power_efficient_wq ||
60560668106cSViresh Kumar 	       !system_freezable_power_efficient_wq);
60573347fa09STejun Heo }
60583347fa09STejun Heo 
60593347fa09STejun Heo /**
60603347fa09STejun Heo  * workqueue_init - bring workqueue subsystem fully online
60613347fa09STejun Heo  *
60623347fa09STejun Heo  * This is the latter half of two-staged workqueue subsystem initialization
60633347fa09STejun Heo  * and invoked as soon as kthreads can be created and scheduled.
60643347fa09STejun Heo  * Workqueues have been created and work items queued on them, but there
60653347fa09STejun Heo  * are no kworkers executing the work items yet.  Populate the worker pools
60663347fa09STejun Heo  * with the initial workers and enable future kworker creations.
60673347fa09STejun Heo  */
60682333e829SYu Chen void __init workqueue_init(void)
60693347fa09STejun Heo {
60702186d9f9STejun Heo 	struct workqueue_struct *wq;
60713347fa09STejun Heo 	struct worker_pool *pool;
60723347fa09STejun Heo 	int cpu, bkt;
60733347fa09STejun Heo 
60742186d9f9STejun Heo 	/*
60752186d9f9STejun Heo 	 * It'd be simpler to initialize NUMA in workqueue_init_early() but
60762186d9f9STejun Heo 	 * CPU to node mapping may not be available that early on some
60772186d9f9STejun Heo 	 * archs such as power and arm64.  As per-cpu pools created
60782186d9f9STejun Heo 	 * previously could be missing node hint and unbound pools NUMA
60792186d9f9STejun Heo 	 * affinity, fix them up.
608040c17f75STejun Heo 	 *
608140c17f75STejun Heo 	 * Also, while iterating workqueues, create rescuers if requested.
60822186d9f9STejun Heo 	 */
60832186d9f9STejun Heo 	wq_numa_init();
60842186d9f9STejun Heo 
60852186d9f9STejun Heo 	mutex_lock(&wq_pool_mutex);
60862186d9f9STejun Heo 
60872186d9f9STejun Heo 	for_each_possible_cpu(cpu) {
60882186d9f9STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
60892186d9f9STejun Heo 			pool->node = cpu_to_node(cpu);
60902186d9f9STejun Heo 		}
60912186d9f9STejun Heo 	}
60922186d9f9STejun Heo 
609340c17f75STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
60942186d9f9STejun Heo 		wq_update_unbound_numa(wq, smp_processor_id(), true);
609540c17f75STejun Heo 		WARN(init_rescuer(wq),
609640c17f75STejun Heo 		     "workqueue: failed to create early rescuer for %s",
609740c17f75STejun Heo 		     wq->name);
609840c17f75STejun Heo 	}
60992186d9f9STejun Heo 
61002186d9f9STejun Heo 	mutex_unlock(&wq_pool_mutex);
61012186d9f9STejun Heo 
61023347fa09STejun Heo 	/* create the initial workers */
61033347fa09STejun Heo 	for_each_online_cpu(cpu) {
61043347fa09STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
61053347fa09STejun Heo 			pool->flags &= ~POOL_DISASSOCIATED;
61063347fa09STejun Heo 			BUG_ON(!create_worker(pool));
61073347fa09STejun Heo 		}
61083347fa09STejun Heo 	}
61093347fa09STejun Heo 
61103347fa09STejun Heo 	hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
61113347fa09STejun Heo 		BUG_ON(!create_worker(pool));
61123347fa09STejun Heo 
61133347fa09STejun Heo 	wq_online = true;
611482607adcSTejun Heo 	wq_watchdog_init();
61151da177e4SLinus Torvalds }
6116