xref: /linux-6.15/kernel/workqueue.c (revision 04d4e665)
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 
15784f91c62SLai Jiangshan 	/* The current concurrency level. */
15884f91c62SLai Jiangshan 	atomic_t		nr_running;
15984f91c62SLai Jiangshan 
160bd7bdd43STejun Heo 	struct list_head	worklist;	/* L: list of pending works */
161ea1abd61SLai Jiangshan 
1625826cc8fSLai Jiangshan 	int			nr_workers;	/* L: total number of workers */
1635826cc8fSLai Jiangshan 	int			nr_idle;	/* L: currently idle workers */
164bd7bdd43STejun Heo 
165bd7bdd43STejun Heo 	struct list_head	idle_list;	/* X: list of idle workers */
166bd7bdd43STejun Heo 	struct timer_list	idle_timer;	/* L: worker idle timeout */
167bd7bdd43STejun Heo 	struct timer_list	mayday_timer;	/* L: SOS timer for workers */
168bd7bdd43STejun Heo 
169c5aa87bbSTejun Heo 	/* a workers is either on busy_hash or idle_list, or the manager */
170c9e7cf27STejun Heo 	DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
171c9e7cf27STejun Heo 						/* L: hash of busy workers */
172c9e7cf27STejun Heo 
1732607d7a6STejun Heo 	struct worker		*manager;	/* L: purely informational */
17492f9c5c4SLai Jiangshan 	struct list_head	workers;	/* A: attached workers */
17560f5a4bcSLai Jiangshan 	struct completion	*detach_completion; /* all workers detached */
176e19e397aSTejun Heo 
1777cda9aaeSLai Jiangshan 	struct ida		worker_ida;	/* worker IDs for task name */
178e19e397aSTejun Heo 
1797a4e344cSTejun Heo 	struct workqueue_attrs	*attrs;		/* I: worker attributes */
18068e13a67SLai Jiangshan 	struct hlist_node	hash_node;	/* PL: unbound_pool_hash node */
18168e13a67SLai Jiangshan 	int			refcnt;		/* PL: refcnt for unbound pools */
1827a4e344cSTejun Heo 
183e19e397aSTejun Heo 	/*
18424acfb71SThomas Gleixner 	 * Destruction of pool is RCU protected to allow dereferences
18529c91e99STejun Heo 	 * from get_work_pool().
18629c91e99STejun Heo 	 */
18729c91e99STejun Heo 	struct rcu_head		rcu;
18884f91c62SLai Jiangshan };
1898b03ae3cSTejun Heo 
1908b03ae3cSTejun Heo /*
191112202d9STejun Heo  * The per-pool workqueue.  While queued, the lower WORK_STRUCT_FLAG_BITS
192112202d9STejun Heo  * of work_struct->data are used for flags and the remaining high bits
193112202d9STejun Heo  * point to the pwq; thus, pwqs need to be aligned at two's power of the
194112202d9STejun Heo  * number of flag bits.
1951da177e4SLinus Torvalds  */
196112202d9STejun Heo struct pool_workqueue {
197bd7bdd43STejun Heo 	struct worker_pool	*pool;		/* I: the associated pool */
1984690c4abSTejun Heo 	struct workqueue_struct *wq;		/* I: the owning workqueue */
19973f53c4aSTejun Heo 	int			work_color;	/* L: current color */
20073f53c4aSTejun Heo 	int			flush_color;	/* L: flushing color */
2018864b4e5STejun Heo 	int			refcnt;		/* L: reference count */
20273f53c4aSTejun Heo 	int			nr_in_flight[WORK_NR_COLORS];
20373f53c4aSTejun Heo 						/* L: nr of in_flight works */
204018f3a13SLai Jiangshan 
205018f3a13SLai Jiangshan 	/*
206018f3a13SLai Jiangshan 	 * nr_active management and WORK_STRUCT_INACTIVE:
207018f3a13SLai Jiangshan 	 *
208018f3a13SLai Jiangshan 	 * When pwq->nr_active >= max_active, new work item is queued to
209018f3a13SLai Jiangshan 	 * pwq->inactive_works instead of pool->worklist and marked with
210018f3a13SLai Jiangshan 	 * WORK_STRUCT_INACTIVE.
211018f3a13SLai Jiangshan 	 *
212018f3a13SLai Jiangshan 	 * All work items marked with WORK_STRUCT_INACTIVE do not participate
213018f3a13SLai Jiangshan 	 * in pwq->nr_active and all work items in pwq->inactive_works are
214018f3a13SLai Jiangshan 	 * marked with WORK_STRUCT_INACTIVE.  But not all WORK_STRUCT_INACTIVE
215018f3a13SLai Jiangshan 	 * work items are in pwq->inactive_works.  Some of them are ready to
216018f3a13SLai Jiangshan 	 * run in pool->worklist or worker->scheduled.  Those work itmes are
217018f3a13SLai Jiangshan 	 * only struct wq_barrier which is used for flush_work() and should
218018f3a13SLai Jiangshan 	 * not participate in pwq->nr_active.  For non-barrier work item, it
219018f3a13SLai Jiangshan 	 * is marked with WORK_STRUCT_INACTIVE iff it is in pwq->inactive_works.
220018f3a13SLai Jiangshan 	 */
2211e19ffc6STejun Heo 	int			nr_active;	/* L: nr of active works */
222a0a1a5fdSTejun Heo 	int			max_active;	/* L: max active works */
223f97a4a1aSLai Jiangshan 	struct list_head	inactive_works;	/* L: inactive works */
2243c25a55dSLai Jiangshan 	struct list_head	pwqs_node;	/* WR: node on wq->pwqs */
2252e109a28STejun Heo 	struct list_head	mayday_node;	/* MD: node on wq->maydays */
2268864b4e5STejun Heo 
2278864b4e5STejun Heo 	/*
2288864b4e5STejun Heo 	 * Release of unbound pwq is punted to system_wq.  See put_pwq()
2298864b4e5STejun Heo 	 * and pwq_unbound_release_workfn() for details.  pool_workqueue
23024acfb71SThomas Gleixner 	 * itself is also RCU protected so that the first pwq can be
231b09f4fd3SLai Jiangshan 	 * determined without grabbing wq->mutex.
2328864b4e5STejun Heo 	 */
2338864b4e5STejun Heo 	struct work_struct	unbound_release_work;
2348864b4e5STejun Heo 	struct rcu_head		rcu;
235e904e6c2STejun Heo } __aligned(1 << WORK_STRUCT_FLAG_BITS);
2361da177e4SLinus Torvalds 
2371da177e4SLinus Torvalds /*
23873f53c4aSTejun Heo  * Structure used to wait for workqueue flush.
23973f53c4aSTejun Heo  */
24073f53c4aSTejun Heo struct wq_flusher {
2413c25a55dSLai Jiangshan 	struct list_head	list;		/* WQ: list of flushers */
2423c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: flush color waiting for */
24373f53c4aSTejun Heo 	struct completion	done;		/* flush completion */
24473f53c4aSTejun Heo };
2451da177e4SLinus Torvalds 
246226223abSTejun Heo struct wq_device;
247226223abSTejun Heo 
24873f53c4aSTejun Heo /*
249c5aa87bbSTejun Heo  * The externally visible workqueue.  It relays the issued work items to
250c5aa87bbSTejun Heo  * the appropriate worker_pool through its pool_workqueues.
2511da177e4SLinus Torvalds  */
2521da177e4SLinus Torvalds struct workqueue_struct {
2533c25a55dSLai Jiangshan 	struct list_head	pwqs;		/* WR: all pwqs of this wq */
254e2dca7adSTejun Heo 	struct list_head	list;		/* PR: list of all workqueues */
25573f53c4aSTejun Heo 
2563c25a55dSLai Jiangshan 	struct mutex		mutex;		/* protects this wq */
2573c25a55dSLai Jiangshan 	int			work_color;	/* WQ: current work color */
2583c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: current flush color */
259112202d9STejun Heo 	atomic_t		nr_pwqs_to_flush; /* flush in progress */
2603c25a55dSLai Jiangshan 	struct wq_flusher	*first_flusher;	/* WQ: first flusher */
2613c25a55dSLai Jiangshan 	struct list_head	flusher_queue;	/* WQ: flush waiters */
2623c25a55dSLai Jiangshan 	struct list_head	flusher_overflow; /* WQ: flush overflow list */
26373f53c4aSTejun Heo 
2642e109a28STejun Heo 	struct list_head	maydays;	/* MD: pwqs requesting rescue */
26530ae2fc0STejun Heo 	struct worker		*rescuer;	/* MD: rescue worker */
266e22bee78STejun Heo 
26787fc741eSLai Jiangshan 	int			nr_drainers;	/* WQ: drain in progress */
268a357fc03SLai Jiangshan 	int			saved_max_active; /* WQ: saved pwq max_active */
269226223abSTejun Heo 
2705b95e1afSLai Jiangshan 	struct workqueue_attrs	*unbound_attrs;	/* PW: only for unbound wqs */
2715b95e1afSLai Jiangshan 	struct pool_workqueue	*dfl_pwq;	/* PW: only for unbound wqs */
2726029a918STejun Heo 
273226223abSTejun Heo #ifdef CONFIG_SYSFS
274226223abSTejun Heo 	struct wq_device	*wq_dev;	/* I: for sysfs interface */
275226223abSTejun Heo #endif
2764e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
277669de8bdSBart Van Assche 	char			*lock_name;
278669de8bdSBart Van Assche 	struct lock_class_key	key;
2794e6045f1SJohannes Berg 	struct lockdep_map	lockdep_map;
2804e6045f1SJohannes Berg #endif
281ecf6881fSTejun Heo 	char			name[WQ_NAME_LEN]; /* I: workqueue name */
2822728fd2fSTejun Heo 
283e2dca7adSTejun Heo 	/*
28424acfb71SThomas Gleixner 	 * Destruction of workqueue_struct is RCU protected to allow walking
28524acfb71SThomas Gleixner 	 * the workqueues list without grabbing wq_pool_mutex.
286e2dca7adSTejun Heo 	 * This is used to dump all workqueues from sysrq.
287e2dca7adSTejun Heo 	 */
288e2dca7adSTejun Heo 	struct rcu_head		rcu;
289e2dca7adSTejun Heo 
2902728fd2fSTejun Heo 	/* hot fields used during command issue, aligned to cacheline */
2912728fd2fSTejun Heo 	unsigned int		flags ____cacheline_aligned; /* WQ: WQ_* flags */
2922728fd2fSTejun Heo 	struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */
2935b95e1afSLai Jiangshan 	struct pool_workqueue __rcu *numa_pwq_tbl[]; /* PWR: unbound pwqs indexed by node */
2941da177e4SLinus Torvalds };
2951da177e4SLinus Torvalds 
296e904e6c2STejun Heo static struct kmem_cache *pwq_cache;
297e904e6c2STejun Heo 
298bce90380STejun Heo static cpumask_var_t *wq_numa_possible_cpumask;
299bce90380STejun Heo 					/* possible CPUs of each node */
300bce90380STejun Heo 
301d55262c4STejun Heo static bool wq_disable_numa;
302d55262c4STejun Heo module_param_named(disable_numa, wq_disable_numa, bool, 0444);
303d55262c4STejun Heo 
304cee22a15SViresh Kumar /* see the comment above the definition of WQ_POWER_EFFICIENT */
305552f530cSLuis R. Rodriguez static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
306cee22a15SViresh Kumar module_param_named(power_efficient, wq_power_efficient, bool, 0444);
307cee22a15SViresh Kumar 
308863b710bSTejun Heo static bool wq_online;			/* can kworkers be created yet? */
3093347fa09STejun Heo 
310bce90380STejun Heo static bool wq_numa_enabled;		/* unbound NUMA affinity enabled */
311bce90380STejun Heo 
3124c16bd32STejun Heo /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
3134c16bd32STejun Heo static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf;
3144c16bd32STejun Heo 
31568e13a67SLai Jiangshan static DEFINE_MUTEX(wq_pool_mutex);	/* protects pools and workqueues list */
3161258fae7STejun Heo static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
317a9b8a985SSebastian Andrzej Siewior static DEFINE_RAW_SPINLOCK(wq_mayday_lock);	/* protects wq->maydays list */
318d8bb65abSSebastian Andrzej Siewior /* wait for manager to go away */
319d8bb65abSSebastian Andrzej Siewior static struct rcuwait manager_wait = __RCUWAIT_INITIALIZER(manager_wait);
3205bcab335STejun Heo 
321e2dca7adSTejun Heo static LIST_HEAD(workqueues);		/* PR: list of all workqueues */
32268e13a67SLai Jiangshan static bool workqueue_freezing;		/* PL: have wqs started freezing? */
3237d19c5ceSTejun Heo 
324ef557180SMike Galbraith /* PL: allowable cpus for unbound wqs and work items */
325ef557180SMike Galbraith static cpumask_var_t wq_unbound_cpumask;
326ef557180SMike Galbraith 
327ef557180SMike Galbraith /* CPU where unbound work was last round robin scheduled from this CPU */
328ef557180SMike Galbraith static DEFINE_PER_CPU(int, wq_rr_cpu_last);
329b05a7928SFrederic Weisbecker 
330f303fccbSTejun Heo /*
331f303fccbSTejun Heo  * Local execution of unbound work items is no longer guaranteed.  The
332f303fccbSTejun Heo  * following always forces round-robin CPU selection on unbound work items
333f303fccbSTejun Heo  * to uncover usages which depend on it.
334f303fccbSTejun Heo  */
335f303fccbSTejun Heo #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
336f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = true;
337f303fccbSTejun Heo #else
338f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = false;
339f303fccbSTejun Heo #endif
340f303fccbSTejun Heo module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
341f303fccbSTejun Heo 
3427d19c5ceSTejun Heo /* the per-cpu worker pools */
34325528213SPeter Zijlstra static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools);
3447d19c5ceSTejun Heo 
34568e13a67SLai Jiangshan static DEFINE_IDR(worker_pool_idr);	/* PR: idr of all pools */
3467d19c5ceSTejun Heo 
34768e13a67SLai Jiangshan /* PL: hash of all unbound pools keyed by pool->attrs */
34829c91e99STejun Heo static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
34929c91e99STejun Heo 
350c5aa87bbSTejun Heo /* I: attributes used when instantiating standard unbound pools on demand */
35129c91e99STejun Heo static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
35229c91e99STejun Heo 
3538a2b7538STejun Heo /* I: attributes used when instantiating ordered pools on demand */
3548a2b7538STejun Heo static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
3558a2b7538STejun Heo 
356d320c038STejun Heo struct workqueue_struct *system_wq __read_mostly;
357ad7b1f84SMarc Dionne EXPORT_SYMBOL(system_wq);
358044c782cSValentin Ilie struct workqueue_struct *system_highpri_wq __read_mostly;
3591aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
360044c782cSValentin Ilie struct workqueue_struct *system_long_wq __read_mostly;
361d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
362044c782cSValentin Ilie struct workqueue_struct *system_unbound_wq __read_mostly;
363f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
364044c782cSValentin Ilie struct workqueue_struct *system_freezable_wq __read_mostly;
36524d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
3660668106cSViresh Kumar struct workqueue_struct *system_power_efficient_wq __read_mostly;
3670668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_power_efficient_wq);
3680668106cSViresh Kumar struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
3690668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
370d320c038STejun Heo 
3717d19c5ceSTejun Heo static int worker_thread(void *__worker);
3726ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
373c29eb853STejun Heo static void show_pwq(struct pool_workqueue *pwq);
37455df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool);
3757d19c5ceSTejun Heo 
37697bd2347STejun Heo #define CREATE_TRACE_POINTS
37797bd2347STejun Heo #include <trace/events/workqueue.h>
37897bd2347STejun Heo 
37968e13a67SLai Jiangshan #define assert_rcu_or_pool_mutex()					\
38024acfb71SThomas Gleixner 	RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&			\
381f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
38224acfb71SThomas Gleixner 			 "RCU or wq_pool_mutex should be held")
3835bcab335STejun Heo 
3845b95e1afSLai Jiangshan #define assert_rcu_or_wq_mutex_or_pool_mutex(wq)			\
38524acfb71SThomas Gleixner 	RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&			\
386f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq->mutex) &&		\
387f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
38824acfb71SThomas Gleixner 			 "RCU, wq->mutex or wq_pool_mutex should be held")
3895b95e1afSLai Jiangshan 
390f02ae73aSTejun Heo #define for_each_cpu_worker_pool(pool, cpu)				\
391f02ae73aSTejun Heo 	for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0];		\
392f02ae73aSTejun Heo 	     (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
3937a62c2c8STejun Heo 	     (pool)++)
3944ce62e9eSTejun Heo 
39549e3cf44STejun Heo /**
39617116969STejun Heo  * for_each_pool - iterate through all worker_pools in the system
39717116969STejun Heo  * @pool: iteration cursor
398611c92a0STejun Heo  * @pi: integer used for iteration
399fa1b54e6STejun Heo  *
40024acfb71SThomas Gleixner  * This must be called either with wq_pool_mutex held or RCU read
40168e13a67SLai Jiangshan  * locked.  If the pool needs to be used beyond the locking in effect, the
40268e13a67SLai Jiangshan  * caller is responsible for guaranteeing that the pool stays online.
403fa1b54e6STejun Heo  *
404fa1b54e6STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
405fa1b54e6STejun Heo  * ignored.
40617116969STejun Heo  */
407611c92a0STejun Heo #define for_each_pool(pool, pi)						\
408611c92a0STejun Heo 	idr_for_each_entry(&worker_pool_idr, pool, pi)			\
40968e13a67SLai Jiangshan 		if (({ assert_rcu_or_pool_mutex(); false; })) { }	\
410fa1b54e6STejun Heo 		else
41117116969STejun Heo 
41217116969STejun Heo /**
413822d8405STejun Heo  * for_each_pool_worker - iterate through all workers of a worker_pool
414822d8405STejun Heo  * @worker: iteration cursor
415822d8405STejun Heo  * @pool: worker_pool to iterate workers of
416822d8405STejun Heo  *
4171258fae7STejun Heo  * This must be called with wq_pool_attach_mutex.
418822d8405STejun Heo  *
419822d8405STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
420822d8405STejun Heo  * ignored.
421822d8405STejun Heo  */
422da028469SLai Jiangshan #define for_each_pool_worker(worker, pool)				\
423da028469SLai Jiangshan 	list_for_each_entry((worker), &(pool)->workers, node)		\
4241258fae7STejun Heo 		if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
425822d8405STejun Heo 		else
426822d8405STejun Heo 
427822d8405STejun Heo /**
42849e3cf44STejun Heo  * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
42949e3cf44STejun Heo  * @pwq: iteration cursor
43049e3cf44STejun Heo  * @wq: the target workqueue
43176af4d93STejun Heo  *
43224acfb71SThomas Gleixner  * This must be called either with wq->mutex held or RCU read locked.
433794b18bcSTejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
434794b18bcSTejun Heo  * responsible for guaranteeing that the pwq stays online.
43576af4d93STejun Heo  *
43676af4d93STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
43776af4d93STejun Heo  * ignored.
43849e3cf44STejun Heo  */
43949e3cf44STejun Heo #define for_each_pwq(pwq, wq)						\
44049e9d1a9SSebastian Andrzej Siewior 	list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node,		\
4415a644662SJoel Fernandes (Google) 				 lockdep_is_held(&(wq->mutex)))
442f3421797STejun Heo 
443dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
444dc186ad7SThomas Gleixner 
445f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr;
446dc186ad7SThomas Gleixner 
44799777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
44899777288SStanislaw Gruszka {
44999777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
45099777288SStanislaw Gruszka }
45199777288SStanislaw Gruszka 
452b9fdac7fSDu, Changbin static bool work_is_static_object(void *addr)
453b9fdac7fSDu, Changbin {
454b9fdac7fSDu, Changbin 	struct work_struct *work = addr;
455b9fdac7fSDu, Changbin 
456b9fdac7fSDu, Changbin 	return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
457b9fdac7fSDu, Changbin }
458b9fdac7fSDu, Changbin 
459dc186ad7SThomas Gleixner /*
460dc186ad7SThomas Gleixner  * fixup_init is called when:
461dc186ad7SThomas Gleixner  * - an active object is initialized
462dc186ad7SThomas Gleixner  */
46302a982a6SDu, Changbin static bool work_fixup_init(void *addr, enum debug_obj_state state)
464dc186ad7SThomas Gleixner {
465dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
466dc186ad7SThomas Gleixner 
467dc186ad7SThomas Gleixner 	switch (state) {
468dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
469dc186ad7SThomas Gleixner 		cancel_work_sync(work);
470dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
47102a982a6SDu, Changbin 		return true;
472dc186ad7SThomas Gleixner 	default:
47302a982a6SDu, Changbin 		return false;
474dc186ad7SThomas Gleixner 	}
475dc186ad7SThomas Gleixner }
476dc186ad7SThomas Gleixner 
477dc186ad7SThomas Gleixner /*
478dc186ad7SThomas Gleixner  * fixup_free is called when:
479dc186ad7SThomas Gleixner  * - an active object is freed
480dc186ad7SThomas Gleixner  */
48102a982a6SDu, Changbin static bool work_fixup_free(void *addr, enum debug_obj_state state)
482dc186ad7SThomas Gleixner {
483dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
484dc186ad7SThomas Gleixner 
485dc186ad7SThomas Gleixner 	switch (state) {
486dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
487dc186ad7SThomas Gleixner 		cancel_work_sync(work);
488dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
48902a982a6SDu, Changbin 		return true;
490dc186ad7SThomas Gleixner 	default:
49102a982a6SDu, Changbin 		return false;
492dc186ad7SThomas Gleixner 	}
493dc186ad7SThomas Gleixner }
494dc186ad7SThomas Gleixner 
495f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr = {
496dc186ad7SThomas Gleixner 	.name		= "work_struct",
49799777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
498b9fdac7fSDu, Changbin 	.is_static_object = work_is_static_object,
499dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
500dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
501dc186ad7SThomas Gleixner };
502dc186ad7SThomas Gleixner 
503dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
504dc186ad7SThomas Gleixner {
505dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
506dc186ad7SThomas Gleixner }
507dc186ad7SThomas Gleixner 
508dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
509dc186ad7SThomas Gleixner {
510dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
511dc186ad7SThomas Gleixner }
512dc186ad7SThomas Gleixner 
513dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
514dc186ad7SThomas Gleixner {
515dc186ad7SThomas Gleixner 	if (onstack)
516dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
517dc186ad7SThomas Gleixner 	else
518dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
519dc186ad7SThomas Gleixner }
520dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
521dc186ad7SThomas Gleixner 
522dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
523dc186ad7SThomas Gleixner {
524dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
525dc186ad7SThomas Gleixner }
526dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
527dc186ad7SThomas Gleixner 
528ea2e64f2SThomas Gleixner void destroy_delayed_work_on_stack(struct delayed_work *work)
529ea2e64f2SThomas Gleixner {
530ea2e64f2SThomas Gleixner 	destroy_timer_on_stack(&work->timer);
531ea2e64f2SThomas Gleixner 	debug_object_free(&work->work, &work_debug_descr);
532ea2e64f2SThomas Gleixner }
533ea2e64f2SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
534ea2e64f2SThomas Gleixner 
535dc186ad7SThomas Gleixner #else
536dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
537dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
538dc186ad7SThomas Gleixner #endif
539dc186ad7SThomas Gleixner 
5404e8b22bdSLi Bin /**
54167dc8325SCai Huoqing  * worker_pool_assign_id - allocate ID and assign it to @pool
5424e8b22bdSLi Bin  * @pool: the pool pointer of interest
5434e8b22bdSLi Bin  *
5444e8b22bdSLi Bin  * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
5454e8b22bdSLi Bin  * successfully, -errno on failure.
5464e8b22bdSLi Bin  */
5479daf9e67STejun Heo static int worker_pool_assign_id(struct worker_pool *pool)
5489daf9e67STejun Heo {
5499daf9e67STejun Heo 	int ret;
5509daf9e67STejun Heo 
55168e13a67SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5525bcab335STejun Heo 
5534e8b22bdSLi Bin 	ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
5544e8b22bdSLi Bin 			GFP_KERNEL);
555229641a6STejun Heo 	if (ret >= 0) {
556e68035fbSTejun Heo 		pool->id = ret;
557229641a6STejun Heo 		return 0;
558229641a6STejun Heo 	}
5599daf9e67STejun Heo 	return ret;
5609daf9e67STejun Heo }
5619daf9e67STejun Heo 
56276af4d93STejun Heo /**
563df2d5ae4STejun Heo  * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
564df2d5ae4STejun Heo  * @wq: the target workqueue
565df2d5ae4STejun Heo  * @node: the node ID
566df2d5ae4STejun Heo  *
56724acfb71SThomas Gleixner  * This must be called with any of wq_pool_mutex, wq->mutex or RCU
5685b95e1afSLai Jiangshan  * read locked.
569df2d5ae4STejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
570df2d5ae4STejun Heo  * responsible for guaranteeing that the pwq stays online.
571d185af30SYacine Belkadi  *
572d185af30SYacine Belkadi  * Return: The unbound pool_workqueue for @node.
573df2d5ae4STejun Heo  */
574df2d5ae4STejun Heo static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
575df2d5ae4STejun Heo 						  int node)
576df2d5ae4STejun Heo {
5775b95e1afSLai Jiangshan 	assert_rcu_or_wq_mutex_or_pool_mutex(wq);
578d6e022f1STejun Heo 
579d6e022f1STejun Heo 	/*
580d6e022f1STejun Heo 	 * XXX: @node can be NUMA_NO_NODE if CPU goes offline while a
581d6e022f1STejun Heo 	 * delayed item is pending.  The plan is to keep CPU -> NODE
582d6e022f1STejun Heo 	 * mapping valid and stable across CPU on/offlines.  Once that
583d6e022f1STejun Heo 	 * happens, this workaround can be removed.
584d6e022f1STejun Heo 	 */
585d6e022f1STejun Heo 	if (unlikely(node == NUMA_NO_NODE))
586d6e022f1STejun Heo 		return wq->dfl_pwq;
587d6e022f1STejun Heo 
588df2d5ae4STejun Heo 	return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
589df2d5ae4STejun Heo }
590df2d5ae4STejun Heo 
59173f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
59273f53c4aSTejun Heo {
59373f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
59473f53c4aSTejun Heo }
59573f53c4aSTejun Heo 
596c4560c2cSLai Jiangshan static int get_work_color(unsigned long work_data)
59773f53c4aSTejun Heo {
598c4560c2cSLai Jiangshan 	return (work_data >> WORK_STRUCT_COLOR_SHIFT) &
59973f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
60073f53c4aSTejun Heo }
60173f53c4aSTejun Heo 
60273f53c4aSTejun Heo static int work_next_color(int color)
60373f53c4aSTejun Heo {
60473f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
605a848e3b6SOleg Nesterov }
606a848e3b6SOleg Nesterov 
6074594bf15SDavid Howells /*
608112202d9STejun Heo  * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
609112202d9STejun Heo  * contain the pointer to the queued pwq.  Once execution starts, the flag
6107c3eed5cSTejun Heo  * is cleared and the high bits contain OFFQ flags and pool ID.
6117a22ad75STejun Heo  *
612112202d9STejun Heo  * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
613112202d9STejun Heo  * and clear_work_data() can be used to set the pwq, pool or clear
614bbb68dfaSTejun Heo  * work->data.  These functions should only be called while the work is
615bbb68dfaSTejun Heo  * owned - ie. while the PENDING bit is set.
6167a22ad75STejun Heo  *
617112202d9STejun Heo  * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
6187c3eed5cSTejun Heo  * corresponding to a work.  Pool is available once the work has been
619112202d9STejun Heo  * queued anywhere after initialization until it is sync canceled.  pwq is
6207c3eed5cSTejun Heo  * available only while the work item is queued.
621bbb68dfaSTejun Heo  *
622bbb68dfaSTejun Heo  * %WORK_OFFQ_CANCELING is used to mark a work item which is being
623bbb68dfaSTejun Heo  * canceled.  While being canceled, a work item may have its PENDING set
624bbb68dfaSTejun Heo  * but stay off timer and worklist for arbitrarily long and nobody should
625bbb68dfaSTejun Heo  * try to steal the PENDING bit.
6264594bf15SDavid Howells  */
6277a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
6287a22ad75STejun Heo 				 unsigned long flags)
6297a22ad75STejun Heo {
6306183c009STejun Heo 	WARN_ON_ONCE(!work_pending(work));
6317a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
6327a22ad75STejun Heo }
6337a22ad75STejun Heo 
634112202d9STejun Heo static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
6354690c4abSTejun Heo 			 unsigned long extra_flags)
636365970a1SDavid Howells {
637112202d9STejun Heo 	set_work_data(work, (unsigned long)pwq,
638112202d9STejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
639365970a1SDavid Howells }
640365970a1SDavid Howells 
6414468a00fSLai Jiangshan static void set_work_pool_and_keep_pending(struct work_struct *work,
6424468a00fSLai Jiangshan 					   int pool_id)
6434468a00fSLai Jiangshan {
6444468a00fSLai Jiangshan 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
6454468a00fSLai Jiangshan 		      WORK_STRUCT_PENDING);
6464468a00fSLai Jiangshan }
6474468a00fSLai Jiangshan 
6487c3eed5cSTejun Heo static void set_work_pool_and_clear_pending(struct work_struct *work,
6497c3eed5cSTejun Heo 					    int pool_id)
6504d707b9fSOleg Nesterov {
65123657bb1STejun Heo 	/*
65223657bb1STejun Heo 	 * The following wmb is paired with the implied mb in
65323657bb1STejun Heo 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
65423657bb1STejun Heo 	 * here are visible to and precede any updates by the next PENDING
65523657bb1STejun Heo 	 * owner.
65623657bb1STejun Heo 	 */
65723657bb1STejun Heo 	smp_wmb();
6587c3eed5cSTejun Heo 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
659346c09f8SRoman Pen 	/*
660346c09f8SRoman Pen 	 * The following mb guarantees that previous clear of a PENDING bit
661346c09f8SRoman Pen 	 * will not be reordered with any speculative LOADS or STORES from
662346c09f8SRoman Pen 	 * work->current_func, which is executed afterwards.  This possible
6638bdc6201SLiu Song 	 * reordering can lead to a missed execution on attempt to queue
664346c09f8SRoman Pen 	 * the same @work.  E.g. consider this case:
665346c09f8SRoman Pen 	 *
666346c09f8SRoman Pen 	 *   CPU#0                         CPU#1
667346c09f8SRoman Pen 	 *   ----------------------------  --------------------------------
668346c09f8SRoman Pen 	 *
669346c09f8SRoman Pen 	 * 1  STORE event_indicated
670346c09f8SRoman Pen 	 * 2  queue_work_on() {
671346c09f8SRoman Pen 	 * 3    test_and_set_bit(PENDING)
672346c09f8SRoman Pen 	 * 4 }                             set_..._and_clear_pending() {
673346c09f8SRoman Pen 	 * 5                                 set_work_data() # clear bit
674346c09f8SRoman Pen 	 * 6                                 smp_mb()
675346c09f8SRoman Pen 	 * 7                               work->current_func() {
676346c09f8SRoman Pen 	 * 8				      LOAD event_indicated
677346c09f8SRoman Pen 	 *				   }
678346c09f8SRoman Pen 	 *
679346c09f8SRoman Pen 	 * Without an explicit full barrier speculative LOAD on line 8 can
680346c09f8SRoman Pen 	 * be executed before CPU#0 does STORE on line 1.  If that happens,
681346c09f8SRoman Pen 	 * CPU#0 observes the PENDING bit is still set and new execution of
682346c09f8SRoman Pen 	 * a @work is not queued in a hope, that CPU#1 will eventually
683346c09f8SRoman Pen 	 * finish the queued @work.  Meanwhile CPU#1 does not see
684346c09f8SRoman Pen 	 * event_indicated is set, because speculative LOAD was executed
685346c09f8SRoman Pen 	 * before actual STORE.
686346c09f8SRoman Pen 	 */
687346c09f8SRoman Pen 	smp_mb();
6884d707b9fSOleg Nesterov }
6894d707b9fSOleg Nesterov 
6907a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
691365970a1SDavid Howells {
6927c3eed5cSTejun Heo 	smp_wmb();	/* see set_work_pool_and_clear_pending() */
6937c3eed5cSTejun Heo 	set_work_data(work, WORK_STRUCT_NO_POOL, 0);
6947a22ad75STejun Heo }
6957a22ad75STejun Heo 
696112202d9STejun Heo static struct pool_workqueue *get_work_pwq(struct work_struct *work)
6977a22ad75STejun Heo {
698e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
6997a22ad75STejun Heo 
700112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
701e120153dSTejun Heo 		return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
702e120153dSTejun Heo 	else
703e120153dSTejun Heo 		return NULL;
7047a22ad75STejun Heo }
7057a22ad75STejun Heo 
7067c3eed5cSTejun Heo /**
7077c3eed5cSTejun Heo  * get_work_pool - return the worker_pool a given work was associated with
7087c3eed5cSTejun Heo  * @work: the work item of interest
7097c3eed5cSTejun Heo  *
71068e13a67SLai Jiangshan  * Pools are created and destroyed under wq_pool_mutex, and allows read
71124acfb71SThomas Gleixner  * access under RCU read lock.  As such, this function should be
71224acfb71SThomas Gleixner  * called under wq_pool_mutex or inside of a rcu_read_lock() region.
713fa1b54e6STejun Heo  *
714fa1b54e6STejun Heo  * All fields of the returned pool are accessible as long as the above
715fa1b54e6STejun Heo  * mentioned locking is in effect.  If the returned pool needs to be used
716fa1b54e6STejun Heo  * beyond the critical section, the caller is responsible for ensuring the
717fa1b54e6STejun Heo  * returned pool is and stays online.
718d185af30SYacine Belkadi  *
719d185af30SYacine Belkadi  * Return: The worker_pool @work was last associated with.  %NULL if none.
7207c3eed5cSTejun Heo  */
7217c3eed5cSTejun Heo static struct worker_pool *get_work_pool(struct work_struct *work)
7227a22ad75STejun Heo {
723e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
7247c3eed5cSTejun Heo 	int pool_id;
7257a22ad75STejun Heo 
72668e13a67SLai Jiangshan 	assert_rcu_or_pool_mutex();
727fa1b54e6STejun Heo 
728112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
729112202d9STejun Heo 		return ((struct pool_workqueue *)
7307c3eed5cSTejun Heo 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool;
7317a22ad75STejun Heo 
7327c3eed5cSTejun Heo 	pool_id = data >> WORK_OFFQ_POOL_SHIFT;
7337c3eed5cSTejun Heo 	if (pool_id == WORK_OFFQ_POOL_NONE)
7347a22ad75STejun Heo 		return NULL;
7357a22ad75STejun Heo 
736fa1b54e6STejun Heo 	return idr_find(&worker_pool_idr, pool_id);
7377c3eed5cSTejun Heo }
7387c3eed5cSTejun Heo 
7397c3eed5cSTejun Heo /**
7407c3eed5cSTejun Heo  * get_work_pool_id - return the worker pool ID a given work is associated with
7417c3eed5cSTejun Heo  * @work: the work item of interest
7427c3eed5cSTejun Heo  *
743d185af30SYacine Belkadi  * Return: The worker_pool ID @work was last associated with.
7447c3eed5cSTejun Heo  * %WORK_OFFQ_POOL_NONE if none.
7457c3eed5cSTejun Heo  */
7467c3eed5cSTejun Heo static int get_work_pool_id(struct work_struct *work)
7477c3eed5cSTejun Heo {
74854d5b7d0SLai Jiangshan 	unsigned long data = atomic_long_read(&work->data);
7497c3eed5cSTejun Heo 
750112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
751112202d9STejun Heo 		return ((struct pool_workqueue *)
75254d5b7d0SLai Jiangshan 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
75354d5b7d0SLai Jiangshan 
75454d5b7d0SLai Jiangshan 	return data >> WORK_OFFQ_POOL_SHIFT;
7557c3eed5cSTejun Heo }
7567c3eed5cSTejun Heo 
757bbb68dfaSTejun Heo static void mark_work_canceling(struct work_struct *work)
758bbb68dfaSTejun Heo {
7597c3eed5cSTejun Heo 	unsigned long pool_id = get_work_pool_id(work);
760bbb68dfaSTejun Heo 
7617c3eed5cSTejun Heo 	pool_id <<= WORK_OFFQ_POOL_SHIFT;
7627c3eed5cSTejun Heo 	set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
763bbb68dfaSTejun Heo }
764bbb68dfaSTejun Heo 
765bbb68dfaSTejun Heo static bool work_is_canceling(struct work_struct *work)
766bbb68dfaSTejun Heo {
767bbb68dfaSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
768bbb68dfaSTejun Heo 
769112202d9STejun Heo 	return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
770bbb68dfaSTejun Heo }
771bbb68dfaSTejun Heo 
772e22bee78STejun Heo /*
7733270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
7743270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
775d565ed63STejun Heo  * they're being called with pool->lock held.
776e22bee78STejun Heo  */
777e22bee78STejun Heo 
77863d95a91STejun Heo static bool __need_more_worker(struct worker_pool *pool)
779649027d7STejun Heo {
780e19e397aSTejun Heo 	return !atomic_read(&pool->nr_running);
781649027d7STejun Heo }
782649027d7STejun Heo 
783e22bee78STejun Heo /*
784e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
785e22bee78STejun Heo  * running workers.
786974271c4STejun Heo  *
787974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
788706026c2STejun Heo  * function will always return %true for unbound pools as long as the
789974271c4STejun Heo  * worklist isn't empty.
790e22bee78STejun Heo  */
79163d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
792e22bee78STejun Heo {
79363d95a91STejun Heo 	return !list_empty(&pool->worklist) && __need_more_worker(pool);
794e22bee78STejun Heo }
795e22bee78STejun Heo 
796e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
79763d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
798e22bee78STejun Heo {
79963d95a91STejun Heo 	return pool->nr_idle;
800e22bee78STejun Heo }
801e22bee78STejun Heo 
802e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
80363d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
804e22bee78STejun Heo {
805e19e397aSTejun Heo 	return !list_empty(&pool->worklist) &&
806e19e397aSTejun Heo 		atomic_read(&pool->nr_running) <= 1;
807e22bee78STejun Heo }
808e22bee78STejun Heo 
809e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
81063d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
811e22bee78STejun Heo {
81263d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
813e22bee78STejun Heo }
814e22bee78STejun Heo 
815e22bee78STejun Heo /* Do we have too many workers and should some go away? */
81663d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
817e22bee78STejun Heo {
818692b4825STejun Heo 	bool managing = pool->flags & POOL_MANAGER_ACTIVE;
81963d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
82063d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
821e22bee78STejun Heo 
822e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
823e22bee78STejun Heo }
824e22bee78STejun Heo 
825e22bee78STejun Heo /*
826e22bee78STejun Heo  * Wake up functions.
827e22bee78STejun Heo  */
828e22bee78STejun Heo 
8291037de36SLai Jiangshan /* Return the first idle worker.  Safe with preemption disabled */
8301037de36SLai Jiangshan static struct worker *first_idle_worker(struct worker_pool *pool)
8317e11629dSTejun Heo {
83263d95a91STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
8337e11629dSTejun Heo 		return NULL;
8347e11629dSTejun Heo 
83563d95a91STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
8367e11629dSTejun Heo }
8377e11629dSTejun Heo 
8387e11629dSTejun Heo /**
8397e11629dSTejun Heo  * wake_up_worker - wake up an idle worker
84063d95a91STejun Heo  * @pool: worker pool to wake worker from
8417e11629dSTejun Heo  *
84263d95a91STejun Heo  * Wake up the first idle worker of @pool.
8437e11629dSTejun Heo  *
8447e11629dSTejun Heo  * CONTEXT:
845a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
8467e11629dSTejun Heo  */
84763d95a91STejun Heo static void wake_up_worker(struct worker_pool *pool)
8487e11629dSTejun Heo {
8491037de36SLai Jiangshan 	struct worker *worker = first_idle_worker(pool);
8507e11629dSTejun Heo 
8517e11629dSTejun Heo 	if (likely(worker))
8527e11629dSTejun Heo 		wake_up_process(worker->task);
8537e11629dSTejun Heo }
8547e11629dSTejun Heo 
8554690c4abSTejun Heo /**
8566d25be57SThomas Gleixner  * wq_worker_running - a worker is running again
857e22bee78STejun Heo  * @task: task waking up
858e22bee78STejun Heo  *
8596d25be57SThomas Gleixner  * This function is called when a worker returns from schedule()
860e22bee78STejun Heo  */
8616d25be57SThomas Gleixner void wq_worker_running(struct task_struct *task)
862e22bee78STejun Heo {
863e22bee78STejun Heo 	struct worker *worker = kthread_data(task);
864e22bee78STejun Heo 
8656d25be57SThomas Gleixner 	if (!worker->sleeping)
8666d25be57SThomas Gleixner 		return;
86707edfeceSFrederic Weisbecker 
86807edfeceSFrederic Weisbecker 	/*
86907edfeceSFrederic Weisbecker 	 * If preempted by unbind_workers() between the WORKER_NOT_RUNNING check
87007edfeceSFrederic Weisbecker 	 * and the nr_running increment below, we may ruin the nr_running reset
87107edfeceSFrederic Weisbecker 	 * and leave with an unexpected pool->nr_running == 1 on the newly unbound
87207edfeceSFrederic Weisbecker 	 * pool. Protect against such race.
87307edfeceSFrederic Weisbecker 	 */
87407edfeceSFrederic Weisbecker 	preempt_disable();
8756d25be57SThomas Gleixner 	if (!(worker->flags & WORKER_NOT_RUNNING))
876e19e397aSTejun Heo 		atomic_inc(&worker->pool->nr_running);
87707edfeceSFrederic Weisbecker 	preempt_enable();
8786d25be57SThomas Gleixner 	worker->sleeping = 0;
87936576000SJoonsoo Kim }
880e22bee78STejun Heo 
881e22bee78STejun Heo /**
882e22bee78STejun Heo  * wq_worker_sleeping - a worker is going to sleep
883e22bee78STejun Heo  * @task: task going to sleep
884e22bee78STejun Heo  *
8856d25be57SThomas Gleixner  * This function is called from schedule() when a busy worker is
886ccf45156SLai Jiangshan  * going to sleep.
887e22bee78STejun Heo  */
8886d25be57SThomas Gleixner void wq_worker_sleeping(struct task_struct *task)
889e22bee78STejun Heo {
8906d25be57SThomas Gleixner 	struct worker *next, *worker = kthread_data(task);
891111c225aSTejun Heo 	struct worker_pool *pool;
892e22bee78STejun Heo 
893111c225aSTejun Heo 	/*
894111c225aSTejun Heo 	 * Rescuers, which may not have all the fields set up like normal
895111c225aSTejun Heo 	 * workers, also reach here, let's not access anything before
896111c225aSTejun Heo 	 * checking NOT_RUNNING.
897111c225aSTejun Heo 	 */
8982d64672eSSteven Rostedt 	if (worker->flags & WORKER_NOT_RUNNING)
8996d25be57SThomas Gleixner 		return;
900e22bee78STejun Heo 
901111c225aSTejun Heo 	pool = worker->pool;
902111c225aSTejun Heo 
90362849a96SSebastian Andrzej Siewior 	/* Return if preempted before wq_worker_running() was reached */
90462849a96SSebastian Andrzej Siewior 	if (worker->sleeping)
9056d25be57SThomas Gleixner 		return;
9066d25be57SThomas Gleixner 
9076d25be57SThomas Gleixner 	worker->sleeping = 1;
908a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
909e22bee78STejun Heo 
910e22bee78STejun Heo 	/*
91145c753f5SFrederic Weisbecker 	 * Recheck in case unbind_workers() preempted us. We don't
91245c753f5SFrederic Weisbecker 	 * want to decrement nr_running after the worker is unbound
91345c753f5SFrederic Weisbecker 	 * and nr_running has been reset.
91445c753f5SFrederic Weisbecker 	 */
91545c753f5SFrederic Weisbecker 	if (worker->flags & WORKER_NOT_RUNNING) {
91645c753f5SFrederic Weisbecker 		raw_spin_unlock_irq(&pool->lock);
91745c753f5SFrederic Weisbecker 		return;
91845c753f5SFrederic Weisbecker 	}
91945c753f5SFrederic Weisbecker 
92045c753f5SFrederic Weisbecker 	/*
921e22bee78STejun Heo 	 * The counterpart of the following dec_and_test, implied mb,
922e22bee78STejun Heo 	 * worklist not empty test sequence is in insert_work().
923e22bee78STejun Heo 	 * Please read comment there.
924e22bee78STejun Heo 	 *
925628c78e7STejun Heo 	 * NOT_RUNNING is clear.  This means that we're bound to and
926628c78e7STejun Heo 	 * running on the local cpu w/ rq lock held and preemption
927628c78e7STejun Heo 	 * disabled, which in turn means that none else could be
928d565ed63STejun Heo 	 * manipulating idle_list, so dereferencing idle_list without pool
929628c78e7STejun Heo 	 * lock is safe.
930e22bee78STejun Heo 	 */
931e19e397aSTejun Heo 	if (atomic_dec_and_test(&pool->nr_running) &&
9326d25be57SThomas Gleixner 	    !list_empty(&pool->worklist)) {
9336d25be57SThomas Gleixner 		next = first_idle_worker(pool);
9346d25be57SThomas Gleixner 		if (next)
9356d25be57SThomas Gleixner 			wake_up_process(next->task);
9366d25be57SThomas Gleixner 	}
937a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
938e22bee78STejun Heo }
939e22bee78STejun Heo 
940e22bee78STejun Heo /**
9411b69ac6bSJohannes Weiner  * wq_worker_last_func - retrieve worker's last work function
9428194fe94SBart Van Assche  * @task: Task to retrieve last work function of.
9431b69ac6bSJohannes Weiner  *
9441b69ac6bSJohannes Weiner  * Determine the last function a worker executed. This is called from
9451b69ac6bSJohannes Weiner  * the scheduler to get a worker's last known identity.
9461b69ac6bSJohannes Weiner  *
9471b69ac6bSJohannes Weiner  * CONTEXT:
948a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(rq->lock)
9491b69ac6bSJohannes Weiner  *
9504b047002SJohannes Weiner  * This function is called during schedule() when a kworker is going
9514b047002SJohannes Weiner  * to sleep. It's used by psi to identify aggregation workers during
9524b047002SJohannes Weiner  * dequeuing, to allow periodic aggregation to shut-off when that
9534b047002SJohannes Weiner  * worker is the last task in the system or cgroup to go to sleep.
9544b047002SJohannes Weiner  *
9554b047002SJohannes Weiner  * As this function doesn't involve any workqueue-related locking, it
9564b047002SJohannes Weiner  * only returns stable values when called from inside the scheduler's
9574b047002SJohannes Weiner  * queuing and dequeuing paths, when @task, which must be a kworker,
9584b047002SJohannes Weiner  * is guaranteed to not be processing any works.
9594b047002SJohannes Weiner  *
9601b69ac6bSJohannes Weiner  * Return:
9611b69ac6bSJohannes Weiner  * The last work function %current executed as a worker, NULL if it
9621b69ac6bSJohannes Weiner  * hasn't executed any work yet.
9631b69ac6bSJohannes Weiner  */
9641b69ac6bSJohannes Weiner work_func_t wq_worker_last_func(struct task_struct *task)
9651b69ac6bSJohannes Weiner {
9661b69ac6bSJohannes Weiner 	struct worker *worker = kthread_data(task);
9671b69ac6bSJohannes Weiner 
9681b69ac6bSJohannes Weiner 	return worker->last_func;
9691b69ac6bSJohannes Weiner }
9701b69ac6bSJohannes Weiner 
9711b69ac6bSJohannes Weiner /**
972e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
973cb444766STejun Heo  * @worker: self
974d302f017STejun Heo  * @flags: flags to set
975d302f017STejun Heo  *
976228f1d00SLai Jiangshan  * Set @flags in @worker->flags and adjust nr_running accordingly.
977d302f017STejun Heo  *
978cb444766STejun Heo  * CONTEXT:
979a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock)
980d302f017STejun Heo  */
981228f1d00SLai Jiangshan static inline void worker_set_flags(struct worker *worker, unsigned int flags)
982d302f017STejun Heo {
983bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
984e22bee78STejun Heo 
985cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
986cb444766STejun Heo 
987228f1d00SLai Jiangshan 	/* If transitioning into NOT_RUNNING, adjust nr_running. */
988e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
989e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
990e19e397aSTejun Heo 		atomic_dec(&pool->nr_running);
991e22bee78STejun Heo 	}
992e22bee78STejun Heo 
993d302f017STejun Heo 	worker->flags |= flags;
994d302f017STejun Heo }
995d302f017STejun Heo 
996d302f017STejun Heo /**
997e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
998cb444766STejun Heo  * @worker: self
999d302f017STejun Heo  * @flags: flags to clear
1000d302f017STejun Heo  *
1001e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
1002d302f017STejun Heo  *
1003cb444766STejun Heo  * CONTEXT:
1004a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock)
1005d302f017STejun Heo  */
1006d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
1007d302f017STejun Heo {
100863d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
1009e22bee78STejun Heo 	unsigned int oflags = worker->flags;
1010e22bee78STejun Heo 
1011cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
1012cb444766STejun Heo 
1013d302f017STejun Heo 	worker->flags &= ~flags;
1014e22bee78STejun Heo 
101542c025f3STejun Heo 	/*
101642c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
101742c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
101842c025f3STejun Heo 	 * of multiple flags, not a single flag.
101942c025f3STejun Heo 	 */
1020e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
1021e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
1022e19e397aSTejun Heo 			atomic_inc(&pool->nr_running);
1023d302f017STejun Heo }
1024d302f017STejun Heo 
1025d302f017STejun Heo /**
10268cca0eeaSTejun Heo  * find_worker_executing_work - find worker which is executing a work
1027c9e7cf27STejun Heo  * @pool: pool of interest
10288cca0eeaSTejun Heo  * @work: work to find worker for
10298cca0eeaSTejun Heo  *
1030c9e7cf27STejun Heo  * Find a worker which is executing @work on @pool by searching
1031c9e7cf27STejun Heo  * @pool->busy_hash which is keyed by the address of @work.  For a worker
1032a2c1c57bSTejun Heo  * to match, its current execution should match the address of @work and
1033a2c1c57bSTejun Heo  * its work function.  This is to avoid unwanted dependency between
1034a2c1c57bSTejun Heo  * unrelated work executions through a work item being recycled while still
1035a2c1c57bSTejun Heo  * being executed.
1036a2c1c57bSTejun Heo  *
1037a2c1c57bSTejun Heo  * This is a bit tricky.  A work item may be freed once its execution
1038a2c1c57bSTejun Heo  * starts and nothing prevents the freed area from being recycled for
1039a2c1c57bSTejun Heo  * another work item.  If the same work item address ends up being reused
1040a2c1c57bSTejun Heo  * before the original execution finishes, workqueue will identify the
1041a2c1c57bSTejun Heo  * recycled work item as currently executing and make it wait until the
1042a2c1c57bSTejun Heo  * current execution finishes, introducing an unwanted dependency.
1043a2c1c57bSTejun Heo  *
1044c5aa87bbSTejun Heo  * This function checks the work item address and work function to avoid
1045c5aa87bbSTejun Heo  * false positives.  Note that this isn't complete as one may construct a
1046c5aa87bbSTejun Heo  * work function which can introduce dependency onto itself through a
1047c5aa87bbSTejun Heo  * recycled work item.  Well, if somebody wants to shoot oneself in the
1048c5aa87bbSTejun Heo  * foot that badly, there's only so much we can do, and if such deadlock
1049c5aa87bbSTejun Heo  * actually occurs, it should be easy to locate the culprit work function.
10508cca0eeaSTejun Heo  *
10518cca0eeaSTejun Heo  * CONTEXT:
1052a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
10538cca0eeaSTejun Heo  *
1054d185af30SYacine Belkadi  * Return:
1055d185af30SYacine Belkadi  * Pointer to worker which is executing @work if found, %NULL
10568cca0eeaSTejun Heo  * otherwise.
10578cca0eeaSTejun Heo  */
1058c9e7cf27STejun Heo static struct worker *find_worker_executing_work(struct worker_pool *pool,
10598cca0eeaSTejun Heo 						 struct work_struct *work)
10608cca0eeaSTejun Heo {
106142f8570fSSasha Levin 	struct worker *worker;
106242f8570fSSasha Levin 
1063b67bfe0dSSasha Levin 	hash_for_each_possible(pool->busy_hash, worker, hentry,
1064a2c1c57bSTejun Heo 			       (unsigned long)work)
1065a2c1c57bSTejun Heo 		if (worker->current_work == work &&
1066a2c1c57bSTejun Heo 		    worker->current_func == work->func)
106742f8570fSSasha Levin 			return worker;
106842f8570fSSasha Levin 
106942f8570fSSasha Levin 	return NULL;
10708cca0eeaSTejun Heo }
10718cca0eeaSTejun Heo 
10728cca0eeaSTejun Heo /**
1073bf4ede01STejun Heo  * move_linked_works - move linked works to a list
1074bf4ede01STejun Heo  * @work: start of series of works to be scheduled
1075bf4ede01STejun Heo  * @head: target list to append @work to
1076402dd89dSShailendra Verma  * @nextp: out parameter for nested worklist walking
1077bf4ede01STejun Heo  *
1078bf4ede01STejun Heo  * Schedule linked works starting from @work to @head.  Work series to
1079bf4ede01STejun Heo  * be scheduled starts at @work and includes any consecutive work with
1080bf4ede01STejun Heo  * WORK_STRUCT_LINKED set in its predecessor.
1081bf4ede01STejun Heo  *
1082bf4ede01STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of
1083bf4ede01STejun Heo  * the last scheduled work.  This allows move_linked_works() to be
1084bf4ede01STejun Heo  * nested inside outer list_for_each_entry_safe().
1085bf4ede01STejun Heo  *
1086bf4ede01STejun Heo  * CONTEXT:
1087a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1088bf4ede01STejun Heo  */
1089bf4ede01STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
1090bf4ede01STejun Heo 			      struct work_struct **nextp)
1091bf4ede01STejun Heo {
1092bf4ede01STejun Heo 	struct work_struct *n;
1093bf4ede01STejun Heo 
1094bf4ede01STejun Heo 	/*
1095bf4ede01STejun Heo 	 * Linked worklist will always end before the end of the list,
1096bf4ede01STejun Heo 	 * use NULL for list head.
1097bf4ede01STejun Heo 	 */
1098bf4ede01STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
1099bf4ede01STejun Heo 		list_move_tail(&work->entry, head);
1100bf4ede01STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1101bf4ede01STejun Heo 			break;
1102bf4ede01STejun Heo 	}
1103bf4ede01STejun Heo 
1104bf4ede01STejun Heo 	/*
1105bf4ede01STejun Heo 	 * If we're already inside safe list traversal and have moved
1106bf4ede01STejun Heo 	 * multiple works to the scheduled queue, the next position
1107bf4ede01STejun Heo 	 * needs to be updated.
1108bf4ede01STejun Heo 	 */
1109bf4ede01STejun Heo 	if (nextp)
1110bf4ede01STejun Heo 		*nextp = n;
1111bf4ede01STejun Heo }
1112bf4ede01STejun Heo 
11138864b4e5STejun Heo /**
11148864b4e5STejun Heo  * get_pwq - get an extra reference on the specified pool_workqueue
11158864b4e5STejun Heo  * @pwq: pool_workqueue to get
11168864b4e5STejun Heo  *
11178864b4e5STejun Heo  * Obtain an extra reference on @pwq.  The caller should guarantee that
11188864b4e5STejun Heo  * @pwq has positive refcnt and be holding the matching pool->lock.
11198864b4e5STejun Heo  */
11208864b4e5STejun Heo static void get_pwq(struct pool_workqueue *pwq)
11218864b4e5STejun Heo {
11228864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
11238864b4e5STejun Heo 	WARN_ON_ONCE(pwq->refcnt <= 0);
11248864b4e5STejun Heo 	pwq->refcnt++;
11258864b4e5STejun Heo }
11268864b4e5STejun Heo 
11278864b4e5STejun Heo /**
11288864b4e5STejun Heo  * put_pwq - put a pool_workqueue reference
11298864b4e5STejun Heo  * @pwq: pool_workqueue to put
11308864b4e5STejun Heo  *
11318864b4e5STejun Heo  * Drop a reference of @pwq.  If its refcnt reaches zero, schedule its
11328864b4e5STejun Heo  * destruction.  The caller should be holding the matching pool->lock.
11338864b4e5STejun Heo  */
11348864b4e5STejun Heo static void put_pwq(struct pool_workqueue *pwq)
11358864b4e5STejun Heo {
11368864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
11378864b4e5STejun Heo 	if (likely(--pwq->refcnt))
11388864b4e5STejun Heo 		return;
11398864b4e5STejun Heo 	if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
11408864b4e5STejun Heo 		return;
11418864b4e5STejun Heo 	/*
11428864b4e5STejun Heo 	 * @pwq can't be released under pool->lock, bounce to
11438864b4e5STejun Heo 	 * pwq_unbound_release_workfn().  This never recurses on the same
11448864b4e5STejun Heo 	 * pool->lock as this path is taken only for unbound workqueues and
11458864b4e5STejun Heo 	 * the release work item is scheduled on a per-cpu workqueue.  To
11468864b4e5STejun Heo 	 * avoid lockdep warning, unbound pool->locks are given lockdep
11478864b4e5STejun Heo 	 * subclass of 1 in get_unbound_pool().
11488864b4e5STejun Heo 	 */
11498864b4e5STejun Heo 	schedule_work(&pwq->unbound_release_work);
11508864b4e5STejun Heo }
11518864b4e5STejun Heo 
1152dce90d47STejun Heo /**
1153dce90d47STejun Heo  * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1154dce90d47STejun Heo  * @pwq: pool_workqueue to put (can be %NULL)
1155dce90d47STejun Heo  *
1156dce90d47STejun Heo  * put_pwq() with locking.  This function also allows %NULL @pwq.
1157dce90d47STejun Heo  */
1158dce90d47STejun Heo static void put_pwq_unlocked(struct pool_workqueue *pwq)
1159dce90d47STejun Heo {
1160dce90d47STejun Heo 	if (pwq) {
1161dce90d47STejun Heo 		/*
116224acfb71SThomas Gleixner 		 * As both pwqs and pools are RCU protected, the
1163dce90d47STejun Heo 		 * following lock operations are safe.
1164dce90d47STejun Heo 		 */
1165a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
1166dce90d47STejun Heo 		put_pwq(pwq);
1167a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
1168dce90d47STejun Heo 	}
1169dce90d47STejun Heo }
1170dce90d47STejun Heo 
1171f97a4a1aSLai Jiangshan static void pwq_activate_inactive_work(struct work_struct *work)
1172bf4ede01STejun Heo {
1173112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1174bf4ede01STejun Heo 
1175bf4ede01STejun Heo 	trace_workqueue_activate_work(work);
117682607adcSTejun Heo 	if (list_empty(&pwq->pool->worklist))
117782607adcSTejun Heo 		pwq->pool->watchdog_ts = jiffies;
1178112202d9STejun Heo 	move_linked_works(work, &pwq->pool->worklist, NULL);
1179f97a4a1aSLai Jiangshan 	__clear_bit(WORK_STRUCT_INACTIVE_BIT, work_data_bits(work));
1180112202d9STejun Heo 	pwq->nr_active++;
1181bf4ede01STejun Heo }
1182bf4ede01STejun Heo 
1183f97a4a1aSLai Jiangshan static void pwq_activate_first_inactive(struct pool_workqueue *pwq)
11843aa62497SLai Jiangshan {
1185f97a4a1aSLai Jiangshan 	struct work_struct *work = list_first_entry(&pwq->inactive_works,
11863aa62497SLai Jiangshan 						    struct work_struct, entry);
11873aa62497SLai Jiangshan 
1188f97a4a1aSLai Jiangshan 	pwq_activate_inactive_work(work);
11893aa62497SLai Jiangshan }
11903aa62497SLai Jiangshan 
1191bf4ede01STejun Heo /**
1192112202d9STejun Heo  * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1193112202d9STejun Heo  * @pwq: pwq of interest
1194c4560c2cSLai Jiangshan  * @work_data: work_data of work which left the queue
1195bf4ede01STejun Heo  *
1196bf4ede01STejun Heo  * A work either has completed or is removed from pending queue,
1197112202d9STejun Heo  * decrement nr_in_flight of its pwq and handle workqueue flushing.
1198bf4ede01STejun Heo  *
1199bf4ede01STejun Heo  * CONTEXT:
1200a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1201bf4ede01STejun Heo  */
1202c4560c2cSLai Jiangshan static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data)
1203bf4ede01STejun Heo {
1204c4560c2cSLai Jiangshan 	int color = get_work_color(work_data);
1205c4560c2cSLai Jiangshan 
1206018f3a13SLai Jiangshan 	if (!(work_data & WORK_STRUCT_INACTIVE)) {
1207112202d9STejun Heo 		pwq->nr_active--;
1208f97a4a1aSLai Jiangshan 		if (!list_empty(&pwq->inactive_works)) {
1209f97a4a1aSLai Jiangshan 			/* one down, submit an inactive one */
1210112202d9STejun Heo 			if (pwq->nr_active < pwq->max_active)
1211f97a4a1aSLai Jiangshan 				pwq_activate_first_inactive(pwq);
1212bf4ede01STejun Heo 		}
1213018f3a13SLai Jiangshan 	}
1214018f3a13SLai Jiangshan 
1215018f3a13SLai Jiangshan 	pwq->nr_in_flight[color]--;
1216bf4ede01STejun Heo 
1217bf4ede01STejun Heo 	/* is flush in progress and are we at the flushing tip? */
1218112202d9STejun Heo 	if (likely(pwq->flush_color != color))
12198864b4e5STejun Heo 		goto out_put;
1220bf4ede01STejun Heo 
1221bf4ede01STejun Heo 	/* are there still in-flight works? */
1222112202d9STejun Heo 	if (pwq->nr_in_flight[color])
12238864b4e5STejun Heo 		goto out_put;
1224bf4ede01STejun Heo 
1225112202d9STejun Heo 	/* this pwq is done, clear flush_color */
1226112202d9STejun Heo 	pwq->flush_color = -1;
1227bf4ede01STejun Heo 
1228bf4ede01STejun Heo 	/*
1229112202d9STejun Heo 	 * If this was the last pwq, wake up the first flusher.  It
1230bf4ede01STejun Heo 	 * will handle the rest.
1231bf4ede01STejun Heo 	 */
1232112202d9STejun Heo 	if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1233112202d9STejun Heo 		complete(&pwq->wq->first_flusher->done);
12348864b4e5STejun Heo out_put:
12358864b4e5STejun Heo 	put_pwq(pwq);
1236bf4ede01STejun Heo }
1237bf4ede01STejun Heo 
123836e227d2STejun Heo /**
1239bbb68dfaSTejun Heo  * try_to_grab_pending - steal work item from worklist and disable irq
124036e227d2STejun Heo  * @work: work item to steal
124136e227d2STejun Heo  * @is_dwork: @work is a delayed_work
1242bbb68dfaSTejun Heo  * @flags: place to store irq state
124336e227d2STejun Heo  *
124436e227d2STejun Heo  * Try to grab PENDING bit of @work.  This function can handle @work in any
1245d185af30SYacine Belkadi  * stable state - idle, on timer or on worklist.
124636e227d2STejun Heo  *
1247d185af30SYacine Belkadi  * Return:
12483eb6b31bSMauro Carvalho Chehab  *
12493eb6b31bSMauro Carvalho Chehab  *  ========	================================================================
125036e227d2STejun Heo  *  1		if @work was pending and we successfully stole PENDING
125136e227d2STejun Heo  *  0		if @work was idle and we claimed PENDING
125236e227d2STejun Heo  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
1253bbb68dfaSTejun Heo  *  -ENOENT	if someone else is canceling @work, this state may persist
1254bbb68dfaSTejun Heo  *		for arbitrarily long
12553eb6b31bSMauro Carvalho Chehab  *  ========	================================================================
125636e227d2STejun Heo  *
1257d185af30SYacine Belkadi  * Note:
1258bbb68dfaSTejun Heo  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
1259e0aecdd8STejun Heo  * interrupted while holding PENDING and @work off queue, irq must be
1260e0aecdd8STejun Heo  * disabled on entry.  This, combined with delayed_work->timer being
1261e0aecdd8STejun Heo  * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1262bbb68dfaSTejun Heo  *
1263bbb68dfaSTejun Heo  * On successful return, >= 0, irq is disabled and the caller is
1264bbb68dfaSTejun Heo  * responsible for releasing it using local_irq_restore(*@flags).
1265bbb68dfaSTejun Heo  *
1266e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
1267bf4ede01STejun Heo  */
1268bbb68dfaSTejun Heo static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1269bbb68dfaSTejun Heo 			       unsigned long *flags)
1270bf4ede01STejun Heo {
1271d565ed63STejun Heo 	struct worker_pool *pool;
1272112202d9STejun Heo 	struct pool_workqueue *pwq;
1273bf4ede01STejun Heo 
1274bbb68dfaSTejun Heo 	local_irq_save(*flags);
1275bbb68dfaSTejun Heo 
127636e227d2STejun Heo 	/* try to steal the timer if it exists */
127736e227d2STejun Heo 	if (is_dwork) {
127836e227d2STejun Heo 		struct delayed_work *dwork = to_delayed_work(work);
127936e227d2STejun Heo 
1280e0aecdd8STejun Heo 		/*
1281e0aecdd8STejun Heo 		 * dwork->timer is irqsafe.  If del_timer() fails, it's
1282e0aecdd8STejun Heo 		 * guaranteed that the timer is not queued anywhere and not
1283e0aecdd8STejun Heo 		 * running on the local CPU.
1284e0aecdd8STejun Heo 		 */
128536e227d2STejun Heo 		if (likely(del_timer(&dwork->timer)))
128636e227d2STejun Heo 			return 1;
128736e227d2STejun Heo 	}
128836e227d2STejun Heo 
128936e227d2STejun Heo 	/* try to claim PENDING the normal way */
1290bf4ede01STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1291bf4ede01STejun Heo 		return 0;
1292bf4ede01STejun Heo 
129324acfb71SThomas Gleixner 	rcu_read_lock();
1294bf4ede01STejun Heo 	/*
1295bf4ede01STejun Heo 	 * The queueing is in progress, or it is already queued. Try to
1296bf4ede01STejun Heo 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1297bf4ede01STejun Heo 	 */
1298d565ed63STejun Heo 	pool = get_work_pool(work);
1299d565ed63STejun Heo 	if (!pool)
1300bbb68dfaSTejun Heo 		goto fail;
1301bf4ede01STejun Heo 
1302a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock(&pool->lock);
1303bf4ede01STejun Heo 	/*
1304112202d9STejun Heo 	 * work->data is guaranteed to point to pwq only while the work
1305112202d9STejun Heo 	 * item is queued on pwq->wq, and both updating work->data to point
1306112202d9STejun Heo 	 * to pwq on queueing and to pool on dequeueing are done under
1307112202d9STejun Heo 	 * pwq->pool->lock.  This in turn guarantees that, if work->data
1308112202d9STejun Heo 	 * points to pwq which is associated with a locked pool, the work
13090b3dae68SLai Jiangshan 	 * item is currently queued on that pool.
1310bf4ede01STejun Heo 	 */
1311112202d9STejun Heo 	pwq = get_work_pwq(work);
1312112202d9STejun Heo 	if (pwq && pwq->pool == pool) {
1313bf4ede01STejun Heo 		debug_work_deactivate(work);
13143aa62497SLai Jiangshan 
13153aa62497SLai Jiangshan 		/*
1316018f3a13SLai Jiangshan 		 * A cancelable inactive work item must be in the
1317018f3a13SLai Jiangshan 		 * pwq->inactive_works since a queued barrier can't be
1318018f3a13SLai Jiangshan 		 * canceled (see the comments in insert_wq_barrier()).
1319018f3a13SLai Jiangshan 		 *
1320f97a4a1aSLai Jiangshan 		 * An inactive work item cannot be grabbed directly because
1321d812796eSLai Jiangshan 		 * it might have linked barrier work items which, if left
1322f97a4a1aSLai Jiangshan 		 * on the inactive_works list, will confuse pwq->nr_active
132316062836STejun Heo 		 * management later on and cause stall.  Make sure the work
132416062836STejun Heo 		 * item is activated before grabbing.
13253aa62497SLai Jiangshan 		 */
1326f97a4a1aSLai Jiangshan 		if (*work_data_bits(work) & WORK_STRUCT_INACTIVE)
1327f97a4a1aSLai Jiangshan 			pwq_activate_inactive_work(work);
13283aa62497SLai Jiangshan 
1329bf4ede01STejun Heo 		list_del_init(&work->entry);
1330c4560c2cSLai Jiangshan 		pwq_dec_nr_in_flight(pwq, *work_data_bits(work));
133136e227d2STejun Heo 
1332112202d9STejun Heo 		/* work->data points to pwq iff queued, point to pool */
13334468a00fSLai Jiangshan 		set_work_pool_and_keep_pending(work, pool->id);
13344468a00fSLai Jiangshan 
1335a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock(&pool->lock);
133624acfb71SThomas Gleixner 		rcu_read_unlock();
133736e227d2STejun Heo 		return 1;
1338bf4ede01STejun Heo 	}
1339a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&pool->lock);
1340bbb68dfaSTejun Heo fail:
134124acfb71SThomas Gleixner 	rcu_read_unlock();
1342bbb68dfaSTejun Heo 	local_irq_restore(*flags);
1343bbb68dfaSTejun Heo 	if (work_is_canceling(work))
1344bbb68dfaSTejun Heo 		return -ENOENT;
1345bbb68dfaSTejun Heo 	cpu_relax();
134636e227d2STejun Heo 	return -EAGAIN;
1347bf4ede01STejun Heo }
1348bf4ede01STejun Heo 
1349bf4ede01STejun Heo /**
1350706026c2STejun Heo  * insert_work - insert a work into a pool
1351112202d9STejun Heo  * @pwq: pwq @work belongs to
13524690c4abSTejun Heo  * @work: work to insert
13534690c4abSTejun Heo  * @head: insertion point
13544690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
13554690c4abSTejun Heo  *
1356112202d9STejun Heo  * Insert @work which belongs to @pwq after @head.  @extra_flags is or'd to
1357706026c2STejun Heo  * work_struct flags.
13584690c4abSTejun Heo  *
13594690c4abSTejun Heo  * CONTEXT:
1360a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1361365970a1SDavid Howells  */
1362112202d9STejun Heo static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1363112202d9STejun Heo 			struct list_head *head, unsigned int extra_flags)
1364b89deed3SOleg Nesterov {
1365112202d9STejun Heo 	struct worker_pool *pool = pwq->pool;
1366e1d8aa9fSFrederic Weisbecker 
1367e89a85d6SWalter Wu 	/* record the work call stack in order to print it in KASAN reports */
1368f70da745SMarco Elver 	kasan_record_aux_stack_noalloc(work);
1369e89a85d6SWalter Wu 
13704690c4abSTejun Heo 	/* we own @work, set data and link */
1371112202d9STejun Heo 	set_work_pwq(work, pwq, extra_flags);
13721a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
13738864b4e5STejun Heo 	get_pwq(pwq);
1374e22bee78STejun Heo 
1375e22bee78STejun Heo 	/*
1376c5aa87bbSTejun Heo 	 * Ensure either wq_worker_sleeping() sees the above
1377c5aa87bbSTejun Heo 	 * list_add_tail() or we see zero nr_running to avoid workers lying
1378c5aa87bbSTejun Heo 	 * around lazily while there are works to be processed.
1379e22bee78STejun Heo 	 */
1380e22bee78STejun Heo 	smp_mb();
1381e22bee78STejun Heo 
138263d95a91STejun Heo 	if (__need_more_worker(pool))
138363d95a91STejun Heo 		wake_up_worker(pool);
1384b89deed3SOleg Nesterov }
1385b89deed3SOleg Nesterov 
1386c8efcc25STejun Heo /*
1387c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
13888d03ecfeSTejun Heo  * same workqueue.
1389c8efcc25STejun Heo  */
1390c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
1391c8efcc25STejun Heo {
1392c8efcc25STejun Heo 	struct worker *worker;
1393c8efcc25STejun Heo 
13948d03ecfeSTejun Heo 	worker = current_wq_worker();
1395c8efcc25STejun Heo 	/*
1396bf393fd4SBart Van Assche 	 * Return %true iff I'm a worker executing a work item on @wq.  If
13978d03ecfeSTejun Heo 	 * I'm @worker, it's safe to dereference it without locking.
1398c8efcc25STejun Heo 	 */
1399112202d9STejun Heo 	return worker && worker->current_pwq->wq == wq;
1400c8efcc25STejun Heo }
1401c8efcc25STejun Heo 
1402ef557180SMike Galbraith /*
1403ef557180SMike Galbraith  * When queueing an unbound work item to a wq, prefer local CPU if allowed
1404ef557180SMike Galbraith  * by wq_unbound_cpumask.  Otherwise, round robin among the allowed ones to
1405ef557180SMike Galbraith  * avoid perturbing sensitive tasks.
1406ef557180SMike Galbraith  */
1407ef557180SMike Galbraith static int wq_select_unbound_cpu(int cpu)
1408ef557180SMike Galbraith {
1409f303fccbSTejun Heo 	static bool printed_dbg_warning;
1410ef557180SMike Galbraith 	int new_cpu;
1411ef557180SMike Galbraith 
1412f303fccbSTejun Heo 	if (likely(!wq_debug_force_rr_cpu)) {
1413ef557180SMike Galbraith 		if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
1414ef557180SMike Galbraith 			return cpu;
1415f303fccbSTejun Heo 	} else if (!printed_dbg_warning) {
1416f303fccbSTejun Heo 		pr_warn("workqueue: round-robin CPU selection forced, expect performance impact\n");
1417f303fccbSTejun Heo 		printed_dbg_warning = true;
1418f303fccbSTejun Heo 	}
1419f303fccbSTejun Heo 
1420ef557180SMike Galbraith 	if (cpumask_empty(wq_unbound_cpumask))
1421ef557180SMike Galbraith 		return cpu;
1422ef557180SMike Galbraith 
1423ef557180SMike Galbraith 	new_cpu = __this_cpu_read(wq_rr_cpu_last);
1424ef557180SMike Galbraith 	new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
1425ef557180SMike Galbraith 	if (unlikely(new_cpu >= nr_cpu_ids)) {
1426ef557180SMike Galbraith 		new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
1427ef557180SMike Galbraith 		if (unlikely(new_cpu >= nr_cpu_ids))
1428ef557180SMike Galbraith 			return cpu;
1429ef557180SMike Galbraith 	}
1430ef557180SMike Galbraith 	__this_cpu_write(wq_rr_cpu_last, new_cpu);
1431ef557180SMike Galbraith 
1432ef557180SMike Galbraith 	return new_cpu;
1433ef557180SMike Galbraith }
1434ef557180SMike Galbraith 
1435d84ff051STejun Heo static void __queue_work(int cpu, struct workqueue_struct *wq,
14361da177e4SLinus Torvalds 			 struct work_struct *work)
14371da177e4SLinus Torvalds {
1438112202d9STejun Heo 	struct pool_workqueue *pwq;
1439c9178087STejun Heo 	struct worker_pool *last_pool;
14401e19ffc6STejun Heo 	struct list_head *worklist;
14418a2e8e5dSTejun Heo 	unsigned int work_flags;
1442b75cac93SJoonsoo Kim 	unsigned int req_cpu = cpu;
14438930cabaSTejun Heo 
14448930cabaSTejun Heo 	/*
14458930cabaSTejun Heo 	 * While a work item is PENDING && off queue, a task trying to
14468930cabaSTejun Heo 	 * steal the PENDING will busy-loop waiting for it to either get
14478930cabaSTejun Heo 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
14488930cabaSTejun Heo 	 * happen with IRQ disabled.
14498930cabaSTejun Heo 	 */
14508e8eb730SFrederic Weisbecker 	lockdep_assert_irqs_disabled();
14511da177e4SLinus Torvalds 
14521e19ffc6STejun Heo 
14539ef28a73SLi Bin 	/* if draining, only works from the same workqueue are allowed */
1454618b01ebSTejun Heo 	if (unlikely(wq->flags & __WQ_DRAINING) &&
1455c8efcc25STejun Heo 	    WARN_ON_ONCE(!is_chained_work(wq)))
1456e41e704bSTejun Heo 		return;
145724acfb71SThomas Gleixner 	rcu_read_lock();
14589e8cd2f5STejun Heo retry:
1459aa202f1fSHillf Danton 	/* pwq which will be used unless @work is executing elsewhere */
1460aa202f1fSHillf Danton 	if (wq->flags & WQ_UNBOUND) {
1461df2d5ae4STejun Heo 		if (req_cpu == WORK_CPU_UNBOUND)
1462ef557180SMike Galbraith 			cpu = wq_select_unbound_cpu(raw_smp_processor_id());
1463df2d5ae4STejun Heo 		pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1464aa202f1fSHillf Danton 	} else {
1465aa202f1fSHillf Danton 		if (req_cpu == WORK_CPU_UNBOUND)
1466aa202f1fSHillf Danton 			cpu = raw_smp_processor_id();
1467aa202f1fSHillf Danton 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1468aa202f1fSHillf Danton 	}
1469f3421797STejun Heo 
147018aa9effSTejun Heo 	/*
1471c9178087STejun Heo 	 * If @work was previously on a different pool, it might still be
1472c9178087STejun Heo 	 * running there, in which case the work needs to be queued on that
1473c9178087STejun Heo 	 * pool to guarantee non-reentrancy.
147418aa9effSTejun Heo 	 */
1475c9e7cf27STejun Heo 	last_pool = get_work_pool(work);
1476112202d9STejun Heo 	if (last_pool && last_pool != pwq->pool) {
147718aa9effSTejun Heo 		struct worker *worker;
147818aa9effSTejun Heo 
1479a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock(&last_pool->lock);
148018aa9effSTejun Heo 
1481c9e7cf27STejun Heo 		worker = find_worker_executing_work(last_pool, work);
148218aa9effSTejun Heo 
1483112202d9STejun Heo 		if (worker && worker->current_pwq->wq == wq) {
1484c9178087STejun Heo 			pwq = worker->current_pwq;
14858594fadeSLai Jiangshan 		} else {
148618aa9effSTejun Heo 			/* meh... not running there, queue here */
1487a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock(&last_pool->lock);
1488a9b8a985SSebastian Andrzej Siewior 			raw_spin_lock(&pwq->pool->lock);
148918aa9effSTejun Heo 		}
14908930cabaSTejun Heo 	} else {
1491a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock(&pwq->pool->lock);
14928930cabaSTejun Heo 	}
1493502ca9d8STejun Heo 
14949e8cd2f5STejun Heo 	/*
14959e8cd2f5STejun Heo 	 * pwq is determined and locked.  For unbound pools, we could have
14969e8cd2f5STejun Heo 	 * raced with pwq release and it could already be dead.  If its
14979e8cd2f5STejun Heo 	 * refcnt is zero, repeat pwq selection.  Note that pwqs never die
1498df2d5ae4STejun Heo 	 * without another pwq replacing it in the numa_pwq_tbl or while
1499df2d5ae4STejun Heo 	 * work items are executing on it, so the retrying is guaranteed to
15009e8cd2f5STejun Heo 	 * make forward-progress.
15019e8cd2f5STejun Heo 	 */
15029e8cd2f5STejun Heo 	if (unlikely(!pwq->refcnt)) {
15039e8cd2f5STejun Heo 		if (wq->flags & WQ_UNBOUND) {
1504a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock(&pwq->pool->lock);
15059e8cd2f5STejun Heo 			cpu_relax();
15069e8cd2f5STejun Heo 			goto retry;
15079e8cd2f5STejun Heo 		}
15089e8cd2f5STejun Heo 		/* oops */
15099e8cd2f5STejun Heo 		WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
15109e8cd2f5STejun Heo 			  wq->name, cpu);
15119e8cd2f5STejun Heo 	}
15129e8cd2f5STejun Heo 
1513112202d9STejun Heo 	/* pwq determined, queue */
1514112202d9STejun Heo 	trace_workqueue_queue_work(req_cpu, pwq, work);
1515502ca9d8STejun Heo 
151624acfb71SThomas Gleixner 	if (WARN_ON(!list_empty(&work->entry)))
151724acfb71SThomas Gleixner 		goto out;
15181e19ffc6STejun Heo 
1519112202d9STejun Heo 	pwq->nr_in_flight[pwq->work_color]++;
1520112202d9STejun Heo 	work_flags = work_color_to_flags(pwq->work_color);
15211e19ffc6STejun Heo 
1522112202d9STejun Heo 	if (likely(pwq->nr_active < pwq->max_active)) {
1523cdadf009STejun Heo 		trace_workqueue_activate_work(work);
1524112202d9STejun Heo 		pwq->nr_active++;
1525112202d9STejun Heo 		worklist = &pwq->pool->worklist;
152682607adcSTejun Heo 		if (list_empty(worklist))
152782607adcSTejun Heo 			pwq->pool->watchdog_ts = jiffies;
15288a2e8e5dSTejun Heo 	} else {
1529f97a4a1aSLai Jiangshan 		work_flags |= WORK_STRUCT_INACTIVE;
1530f97a4a1aSLai Jiangshan 		worklist = &pwq->inactive_works;
15318a2e8e5dSTejun Heo 	}
15321e19ffc6STejun Heo 
15330687c66bSZqiang 	debug_work_activate(work);
1534112202d9STejun Heo 	insert_work(pwq, work, worklist, work_flags);
15351e19ffc6STejun Heo 
153624acfb71SThomas Gleixner out:
1537a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&pwq->pool->lock);
153824acfb71SThomas Gleixner 	rcu_read_unlock();
15391da177e4SLinus Torvalds }
15401da177e4SLinus Torvalds 
15410fcb78c2SRolf Eike Beer /**
1542c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
1543c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
1544c1a220e7SZhang Rui  * @wq: workqueue to use
1545c1a220e7SZhang Rui  * @work: work to queue
1546c1a220e7SZhang Rui  *
1547c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
1548443378f0SPaul E. McKenney  * can't go away.  Callers that fail to ensure that the specified
1549443378f0SPaul E. McKenney  * CPU cannot go away will execute on a randomly chosen CPU.
1550d185af30SYacine Belkadi  *
1551d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.
1552c1a220e7SZhang Rui  */
1553d4283e93STejun Heo bool queue_work_on(int cpu, struct workqueue_struct *wq,
1554d4283e93STejun Heo 		   struct work_struct *work)
1555c1a220e7SZhang Rui {
1556d4283e93STejun Heo 	bool ret = false;
15578930cabaSTejun Heo 	unsigned long flags;
15588930cabaSTejun Heo 
15598930cabaSTejun Heo 	local_irq_save(flags);
1560c1a220e7SZhang Rui 
156122df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
15624690c4abSTejun Heo 		__queue_work(cpu, wq, work);
1563d4283e93STejun Heo 		ret = true;
1564c1a220e7SZhang Rui 	}
15658930cabaSTejun Heo 
15668930cabaSTejun Heo 	local_irq_restore(flags);
1567c1a220e7SZhang Rui 	return ret;
1568c1a220e7SZhang Rui }
1569ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_work_on);
1570c1a220e7SZhang Rui 
15718204e0c1SAlexander Duyck /**
15728204e0c1SAlexander Duyck  * workqueue_select_cpu_near - Select a CPU based on NUMA node
15738204e0c1SAlexander Duyck  * @node: NUMA node ID that we want to select a CPU from
15748204e0c1SAlexander Duyck  *
15758204e0c1SAlexander Duyck  * This function will attempt to find a "random" cpu available on a given
15768204e0c1SAlexander Duyck  * node. If there are no CPUs available on the given node it will return
15778204e0c1SAlexander Duyck  * WORK_CPU_UNBOUND indicating that we should just schedule to any
15788204e0c1SAlexander Duyck  * available CPU if we need to schedule this work.
15798204e0c1SAlexander Duyck  */
15808204e0c1SAlexander Duyck static int workqueue_select_cpu_near(int node)
15818204e0c1SAlexander Duyck {
15828204e0c1SAlexander Duyck 	int cpu;
15838204e0c1SAlexander Duyck 
15848204e0c1SAlexander Duyck 	/* No point in doing this if NUMA isn't enabled for workqueues */
15858204e0c1SAlexander Duyck 	if (!wq_numa_enabled)
15868204e0c1SAlexander Duyck 		return WORK_CPU_UNBOUND;
15878204e0c1SAlexander Duyck 
15888204e0c1SAlexander Duyck 	/* Delay binding to CPU if node is not valid or online */
15898204e0c1SAlexander Duyck 	if (node < 0 || node >= MAX_NUMNODES || !node_online(node))
15908204e0c1SAlexander Duyck 		return WORK_CPU_UNBOUND;
15918204e0c1SAlexander Duyck 
15928204e0c1SAlexander Duyck 	/* Use local node/cpu if we are already there */
15938204e0c1SAlexander Duyck 	cpu = raw_smp_processor_id();
15948204e0c1SAlexander Duyck 	if (node == cpu_to_node(cpu))
15958204e0c1SAlexander Duyck 		return cpu;
15968204e0c1SAlexander Duyck 
15978204e0c1SAlexander Duyck 	/* Use "random" otherwise know as "first" online CPU of node */
15988204e0c1SAlexander Duyck 	cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
15998204e0c1SAlexander Duyck 
16008204e0c1SAlexander Duyck 	/* If CPU is valid return that, otherwise just defer */
16018204e0c1SAlexander Duyck 	return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND;
16028204e0c1SAlexander Duyck }
16038204e0c1SAlexander Duyck 
16048204e0c1SAlexander Duyck /**
16058204e0c1SAlexander Duyck  * queue_work_node - queue work on a "random" cpu for a given NUMA node
16068204e0c1SAlexander Duyck  * @node: NUMA node that we are targeting the work for
16078204e0c1SAlexander Duyck  * @wq: workqueue to use
16088204e0c1SAlexander Duyck  * @work: work to queue
16098204e0c1SAlexander Duyck  *
16108204e0c1SAlexander Duyck  * We queue the work to a "random" CPU within a given NUMA node. The basic
16118204e0c1SAlexander Duyck  * idea here is to provide a way to somehow associate work with a given
16128204e0c1SAlexander Duyck  * NUMA node.
16138204e0c1SAlexander Duyck  *
16148204e0c1SAlexander Duyck  * This function will only make a best effort attempt at getting this onto
16158204e0c1SAlexander Duyck  * the right NUMA node. If no node is requested or the requested node is
16168204e0c1SAlexander Duyck  * offline then we just fall back to standard queue_work behavior.
16178204e0c1SAlexander Duyck  *
16188204e0c1SAlexander Duyck  * Currently the "random" CPU ends up being the first available CPU in the
16198204e0c1SAlexander Duyck  * intersection of cpu_online_mask and the cpumask of the node, unless we
16208204e0c1SAlexander Duyck  * are running on the node. In that case we just use the current CPU.
16218204e0c1SAlexander Duyck  *
16228204e0c1SAlexander Duyck  * Return: %false if @work was already on a queue, %true otherwise.
16238204e0c1SAlexander Duyck  */
16248204e0c1SAlexander Duyck bool queue_work_node(int node, struct workqueue_struct *wq,
16258204e0c1SAlexander Duyck 		     struct work_struct *work)
16268204e0c1SAlexander Duyck {
16278204e0c1SAlexander Duyck 	unsigned long flags;
16288204e0c1SAlexander Duyck 	bool ret = false;
16298204e0c1SAlexander Duyck 
16308204e0c1SAlexander Duyck 	/*
16318204e0c1SAlexander Duyck 	 * This current implementation is specific to unbound workqueues.
16328204e0c1SAlexander Duyck 	 * Specifically we only return the first available CPU for a given
16338204e0c1SAlexander Duyck 	 * node instead of cycling through individual CPUs within the node.
16348204e0c1SAlexander Duyck 	 *
16358204e0c1SAlexander Duyck 	 * If this is used with a per-cpu workqueue then the logic in
16368204e0c1SAlexander Duyck 	 * workqueue_select_cpu_near would need to be updated to allow for
16378204e0c1SAlexander Duyck 	 * some round robin type logic.
16388204e0c1SAlexander Duyck 	 */
16398204e0c1SAlexander Duyck 	WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND));
16408204e0c1SAlexander Duyck 
16418204e0c1SAlexander Duyck 	local_irq_save(flags);
16428204e0c1SAlexander Duyck 
16438204e0c1SAlexander Duyck 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
16448204e0c1SAlexander Duyck 		int cpu = workqueue_select_cpu_near(node);
16458204e0c1SAlexander Duyck 
16468204e0c1SAlexander Duyck 		__queue_work(cpu, wq, work);
16478204e0c1SAlexander Duyck 		ret = true;
16488204e0c1SAlexander Duyck 	}
16498204e0c1SAlexander Duyck 
16508204e0c1SAlexander Duyck 	local_irq_restore(flags);
16518204e0c1SAlexander Duyck 	return ret;
16528204e0c1SAlexander Duyck }
16538204e0c1SAlexander Duyck EXPORT_SYMBOL_GPL(queue_work_node);
16548204e0c1SAlexander Duyck 
16558c20feb6SKees Cook void delayed_work_timer_fn(struct timer_list *t)
16561da177e4SLinus Torvalds {
16578c20feb6SKees Cook 	struct delayed_work *dwork = from_timer(dwork, t, timer);
16581da177e4SLinus Torvalds 
1659e0aecdd8STejun Heo 	/* should have been called from irqsafe timer with irq already off */
166060c057bcSLai Jiangshan 	__queue_work(dwork->cpu, dwork->wq, &dwork->work);
16611da177e4SLinus Torvalds }
16621438ade5SKonstantin Khlebnikov EXPORT_SYMBOL(delayed_work_timer_fn);
16631da177e4SLinus Torvalds 
16647beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
166552bad64dSDavid Howells 				struct delayed_work *dwork, unsigned long delay)
16661da177e4SLinus Torvalds {
16677beb2edfSTejun Heo 	struct timer_list *timer = &dwork->timer;
16687beb2edfSTejun Heo 	struct work_struct *work = &dwork->work;
16691da177e4SLinus Torvalds 
1670637fdbaeSTejun Heo 	WARN_ON_ONCE(!wq);
167198173112SSami Tolvanen 	WARN_ON_FUNCTION_MISMATCH(timer->function, delayed_work_timer_fn);
1672fc4b514fSTejun Heo 	WARN_ON_ONCE(timer_pending(timer));
1673fc4b514fSTejun Heo 	WARN_ON_ONCE(!list_empty(&work->entry));
16747beb2edfSTejun Heo 
16758852aac2STejun Heo 	/*
16768852aac2STejun Heo 	 * If @delay is 0, queue @dwork->work immediately.  This is for
16778852aac2STejun Heo 	 * both optimization and correctness.  The earliest @timer can
16788852aac2STejun Heo 	 * expire is on the closest next tick and delayed_work users depend
16798852aac2STejun Heo 	 * on that there's no such delay when @delay is 0.
16808852aac2STejun Heo 	 */
16818852aac2STejun Heo 	if (!delay) {
16828852aac2STejun Heo 		__queue_work(cpu, wq, &dwork->work);
16838852aac2STejun Heo 		return;
16848852aac2STejun Heo 	}
16858852aac2STejun Heo 
168660c057bcSLai Jiangshan 	dwork->wq = wq;
16871265057fSTejun Heo 	dwork->cpu = cpu;
16887beb2edfSTejun Heo 	timer->expires = jiffies + delay;
16897beb2edfSTejun Heo 
1690041bd12eSTejun Heo 	if (unlikely(cpu != WORK_CPU_UNBOUND))
16917beb2edfSTejun Heo 		add_timer_on(timer, cpu);
1692041bd12eSTejun Heo 	else
1693041bd12eSTejun Heo 		add_timer(timer);
16947beb2edfSTejun Heo }
16951da177e4SLinus Torvalds 
16960fcb78c2SRolf Eike Beer /**
16970fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
16980fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
16990fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1700af9997e4SRandy Dunlap  * @dwork: work to queue
17010fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
17020fcb78c2SRolf Eike Beer  *
1703d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.  If
1704715f1300STejun Heo  * @delay is zero and @dwork is idle, it will be scheduled for immediate
1705715f1300STejun Heo  * execution.
17060fcb78c2SRolf Eike Beer  */
1707d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
170852bad64dSDavid Howells 			   struct delayed_work *dwork, unsigned long delay)
17097a6bc1cdSVenkatesh Pallipadi {
171052bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
1711d4283e93STejun Heo 	bool ret = false;
17128930cabaSTejun Heo 	unsigned long flags;
17138930cabaSTejun Heo 
17148930cabaSTejun Heo 	/* read the comment in __queue_work() */
17158930cabaSTejun Heo 	local_irq_save(flags);
17167a6bc1cdSVenkatesh Pallipadi 
171722df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
17187beb2edfSTejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
1719d4283e93STejun Heo 		ret = true;
17207a6bc1cdSVenkatesh Pallipadi 	}
17218930cabaSTejun Heo 
17228930cabaSTejun Heo 	local_irq_restore(flags);
17237a6bc1cdSVenkatesh Pallipadi 	return ret;
17247a6bc1cdSVenkatesh Pallipadi }
1725ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_delayed_work_on);
17261da177e4SLinus Torvalds 
1727c8e55f36STejun Heo /**
17288376fe22STejun Heo  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
17298376fe22STejun Heo  * @cpu: CPU number to execute work on
17308376fe22STejun Heo  * @wq: workqueue to use
17318376fe22STejun Heo  * @dwork: work to queue
17328376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
17338376fe22STejun Heo  *
17348376fe22STejun Heo  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
17358376fe22STejun Heo  * modify @dwork's timer so that it expires after @delay.  If @delay is
17368376fe22STejun Heo  * zero, @work is guaranteed to be scheduled immediately regardless of its
17378376fe22STejun Heo  * current state.
17388376fe22STejun Heo  *
1739d185af30SYacine Belkadi  * Return: %false if @dwork was idle and queued, %true if @dwork was
17408376fe22STejun Heo  * pending and its timer was modified.
17418376fe22STejun Heo  *
1742e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
17438376fe22STejun Heo  * See try_to_grab_pending() for details.
17448376fe22STejun Heo  */
17458376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
17468376fe22STejun Heo 			 struct delayed_work *dwork, unsigned long delay)
17478376fe22STejun Heo {
17488376fe22STejun Heo 	unsigned long flags;
17498376fe22STejun Heo 	int ret;
17508376fe22STejun Heo 
17518376fe22STejun Heo 	do {
17528376fe22STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
17538376fe22STejun Heo 	} while (unlikely(ret == -EAGAIN));
17548376fe22STejun Heo 
17558376fe22STejun Heo 	if (likely(ret >= 0)) {
17568376fe22STejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
17578376fe22STejun Heo 		local_irq_restore(flags);
17588376fe22STejun Heo 	}
17598376fe22STejun Heo 
17608376fe22STejun Heo 	/* -ENOENT from try_to_grab_pending() becomes %true */
17618376fe22STejun Heo 	return ret;
17628376fe22STejun Heo }
17638376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
17648376fe22STejun Heo 
176505f0fe6bSTejun Heo static void rcu_work_rcufn(struct rcu_head *rcu)
176605f0fe6bSTejun Heo {
176705f0fe6bSTejun Heo 	struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
176805f0fe6bSTejun Heo 
176905f0fe6bSTejun Heo 	/* read the comment in __queue_work() */
177005f0fe6bSTejun Heo 	local_irq_disable();
177105f0fe6bSTejun Heo 	__queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
177205f0fe6bSTejun Heo 	local_irq_enable();
177305f0fe6bSTejun Heo }
177405f0fe6bSTejun Heo 
177505f0fe6bSTejun Heo /**
177605f0fe6bSTejun Heo  * queue_rcu_work - queue work after a RCU grace period
177705f0fe6bSTejun Heo  * @wq: workqueue to use
177805f0fe6bSTejun Heo  * @rwork: work to queue
177905f0fe6bSTejun Heo  *
178005f0fe6bSTejun Heo  * Return: %false if @rwork was already pending, %true otherwise.  Note
178105f0fe6bSTejun Heo  * that a full RCU grace period is guaranteed only after a %true return.
1782bf393fd4SBart Van Assche  * While @rwork is guaranteed to be executed after a %false return, the
178305f0fe6bSTejun Heo  * execution may happen before a full RCU grace period has passed.
178405f0fe6bSTejun Heo  */
178505f0fe6bSTejun Heo bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
178605f0fe6bSTejun Heo {
178705f0fe6bSTejun Heo 	struct work_struct *work = &rwork->work;
178805f0fe6bSTejun Heo 
178905f0fe6bSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
179005f0fe6bSTejun Heo 		rwork->wq = wq;
179105f0fe6bSTejun Heo 		call_rcu(&rwork->rcu, rcu_work_rcufn);
179205f0fe6bSTejun Heo 		return true;
179305f0fe6bSTejun Heo 	}
179405f0fe6bSTejun Heo 
179505f0fe6bSTejun Heo 	return false;
179605f0fe6bSTejun Heo }
179705f0fe6bSTejun Heo EXPORT_SYMBOL(queue_rcu_work);
179805f0fe6bSTejun Heo 
17998376fe22STejun Heo /**
1800c8e55f36STejun Heo  * worker_enter_idle - enter idle state
1801c8e55f36STejun Heo  * @worker: worker which is entering idle state
1802c8e55f36STejun Heo  *
1803c8e55f36STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
1804c8e55f36STejun Heo  * necessary.
1805c8e55f36STejun Heo  *
1806c8e55f36STejun Heo  * LOCKING:
1807a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1808c8e55f36STejun Heo  */
1809c8e55f36STejun Heo static void worker_enter_idle(struct worker *worker)
18101da177e4SLinus Torvalds {
1811bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1812c8e55f36STejun Heo 
18136183c009STejun Heo 	if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
18146183c009STejun Heo 	    WARN_ON_ONCE(!list_empty(&worker->entry) &&
18156183c009STejun Heo 			 (worker->hentry.next || worker->hentry.pprev)))
18166183c009STejun Heo 		return;
1817c8e55f36STejun Heo 
1818051e1850SLai Jiangshan 	/* can't use worker_set_flags(), also called from create_worker() */
1819cb444766STejun Heo 	worker->flags |= WORKER_IDLE;
1820bd7bdd43STejun Heo 	pool->nr_idle++;
1821e22bee78STejun Heo 	worker->last_active = jiffies;
1822c8e55f36STejun Heo 
1823c8e55f36STejun Heo 	/* idle_list is LIFO */
1824bd7bdd43STejun Heo 	list_add(&worker->entry, &pool->idle_list);
1825db7bccf4STejun Heo 
182663d95a91STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1827628c78e7STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1828cb444766STejun Heo 
1829989442d7SLai Jiangshan 	/* Sanity check nr_running. */
1830989442d7SLai Jiangshan 	WARN_ON_ONCE(pool->nr_workers == pool->nr_idle &&
1831e19e397aSTejun Heo 		     atomic_read(&pool->nr_running));
1832c8e55f36STejun Heo }
1833c8e55f36STejun Heo 
1834c8e55f36STejun Heo /**
1835c8e55f36STejun Heo  * worker_leave_idle - leave idle state
1836c8e55f36STejun Heo  * @worker: worker which is leaving idle state
1837c8e55f36STejun Heo  *
1838c8e55f36STejun Heo  * @worker is leaving idle state.  Update stats.
1839c8e55f36STejun Heo  *
1840c8e55f36STejun Heo  * LOCKING:
1841a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1842c8e55f36STejun Heo  */
1843c8e55f36STejun Heo static void worker_leave_idle(struct worker *worker)
1844c8e55f36STejun Heo {
1845bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1846c8e55f36STejun Heo 
18476183c009STejun Heo 	if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
18486183c009STejun Heo 		return;
1849d302f017STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
1850bd7bdd43STejun Heo 	pool->nr_idle--;
1851c8e55f36STejun Heo 	list_del_init(&worker->entry);
1852c8e55f36STejun Heo }
1853c8e55f36STejun Heo 
1854f7537df5SLai Jiangshan static struct worker *alloc_worker(int node)
1855c34056a3STejun Heo {
1856c34056a3STejun Heo 	struct worker *worker;
1857c34056a3STejun Heo 
1858f7537df5SLai Jiangshan 	worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
1859c8e55f36STejun Heo 	if (worker) {
1860c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
1861affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
1862da028469SLai Jiangshan 		INIT_LIST_HEAD(&worker->node);
1863e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
1864e22bee78STejun Heo 		worker->flags = WORKER_PREP;
1865c8e55f36STejun Heo 	}
1866c34056a3STejun Heo 	return worker;
1867c34056a3STejun Heo }
1868c34056a3STejun Heo 
1869c34056a3STejun Heo /**
18704736cbf7SLai Jiangshan  * worker_attach_to_pool() - attach a worker to a pool
18714736cbf7SLai Jiangshan  * @worker: worker to be attached
18724736cbf7SLai Jiangshan  * @pool: the target pool
18734736cbf7SLai Jiangshan  *
18744736cbf7SLai Jiangshan  * Attach @worker to @pool.  Once attached, the %WORKER_UNBOUND flag and
18754736cbf7SLai Jiangshan  * cpu-binding of @worker are kept coordinated with the pool across
18764736cbf7SLai Jiangshan  * cpu-[un]hotplugs.
18774736cbf7SLai Jiangshan  */
18784736cbf7SLai Jiangshan static void worker_attach_to_pool(struct worker *worker,
18794736cbf7SLai Jiangshan 				   struct worker_pool *pool)
18804736cbf7SLai Jiangshan {
18811258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
18824736cbf7SLai Jiangshan 
18834736cbf7SLai Jiangshan 	/*
18841258fae7STejun Heo 	 * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains
18851258fae7STejun Heo 	 * stable across this function.  See the comments above the flag
18861258fae7STejun Heo 	 * definition for details.
18874736cbf7SLai Jiangshan 	 */
18884736cbf7SLai Jiangshan 	if (pool->flags & POOL_DISASSOCIATED)
18894736cbf7SLai Jiangshan 		worker->flags |= WORKER_UNBOUND;
18905c25b5ffSPeter Zijlstra 	else
18915c25b5ffSPeter Zijlstra 		kthread_set_per_cpu(worker->task, pool->cpu);
18924736cbf7SLai Jiangshan 
1893640f17c8SPeter Zijlstra 	if (worker->rescue_wq)
1894640f17c8SPeter Zijlstra 		set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
1895640f17c8SPeter Zijlstra 
18964736cbf7SLai Jiangshan 	list_add_tail(&worker->node, &pool->workers);
1897a2d812a2STejun Heo 	worker->pool = pool;
18984736cbf7SLai Jiangshan 
18991258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
19004736cbf7SLai Jiangshan }
19014736cbf7SLai Jiangshan 
19024736cbf7SLai Jiangshan /**
190360f5a4bcSLai Jiangshan  * worker_detach_from_pool() - detach a worker from its pool
190460f5a4bcSLai Jiangshan  * @worker: worker which is attached to its pool
190560f5a4bcSLai Jiangshan  *
19064736cbf7SLai Jiangshan  * Undo the attaching which had been done in worker_attach_to_pool().  The
19074736cbf7SLai Jiangshan  * caller worker shouldn't access to the pool after detached except it has
19084736cbf7SLai Jiangshan  * other reference to the pool.
190960f5a4bcSLai Jiangshan  */
1910a2d812a2STejun Heo static void worker_detach_from_pool(struct worker *worker)
191160f5a4bcSLai Jiangshan {
1912a2d812a2STejun Heo 	struct worker_pool *pool = worker->pool;
191360f5a4bcSLai Jiangshan 	struct completion *detach_completion = NULL;
191460f5a4bcSLai Jiangshan 
19151258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
1916a2d812a2STejun Heo 
19175c25b5ffSPeter Zijlstra 	kthread_set_per_cpu(worker->task, -1);
1918da028469SLai Jiangshan 	list_del(&worker->node);
1919a2d812a2STejun Heo 	worker->pool = NULL;
1920a2d812a2STejun Heo 
1921da028469SLai Jiangshan 	if (list_empty(&pool->workers))
192260f5a4bcSLai Jiangshan 		detach_completion = pool->detach_completion;
19231258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
192460f5a4bcSLai Jiangshan 
1925b62c0751SLai Jiangshan 	/* clear leftover flags without pool->lock after it is detached */
1926b62c0751SLai Jiangshan 	worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
1927b62c0751SLai Jiangshan 
192860f5a4bcSLai Jiangshan 	if (detach_completion)
192960f5a4bcSLai Jiangshan 		complete(detach_completion);
193060f5a4bcSLai Jiangshan }
193160f5a4bcSLai Jiangshan 
193260f5a4bcSLai Jiangshan /**
1933c34056a3STejun Heo  * create_worker - create a new workqueue worker
193463d95a91STejun Heo  * @pool: pool the new worker will belong to
1935c34056a3STejun Heo  *
1936051e1850SLai Jiangshan  * Create and start a new worker which is attached to @pool.
1937c34056a3STejun Heo  *
1938c34056a3STejun Heo  * CONTEXT:
1939c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
1940c34056a3STejun Heo  *
1941d185af30SYacine Belkadi  * Return:
1942c34056a3STejun Heo  * Pointer to the newly created worker.
1943c34056a3STejun Heo  */
1944bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
1945c34056a3STejun Heo {
1946e441b56fSZhen Lei 	struct worker *worker;
1947e441b56fSZhen Lei 	int id;
1948e3c916a4STejun Heo 	char id_buf[16];
1949c34056a3STejun Heo 
19507cda9aaeSLai Jiangshan 	/* ID is needed to determine kthread name */
1951e441b56fSZhen Lei 	id = ida_alloc(&pool->worker_ida, GFP_KERNEL);
1952822d8405STejun Heo 	if (id < 0)
1953e441b56fSZhen Lei 		return NULL;
1954c34056a3STejun Heo 
1955f7537df5SLai Jiangshan 	worker = alloc_worker(pool->node);
1956c34056a3STejun Heo 	if (!worker)
1957c34056a3STejun Heo 		goto fail;
1958c34056a3STejun Heo 
1959c34056a3STejun Heo 	worker->id = id;
1960c34056a3STejun Heo 
196129c91e99STejun Heo 	if (pool->cpu >= 0)
1962e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
1963e3c916a4STejun Heo 			 pool->attrs->nice < 0  ? "H" : "");
1964f3421797STejun Heo 	else
1965e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
1966e3c916a4STejun Heo 
1967f3f90ad4STejun Heo 	worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
1968e3c916a4STejun Heo 					      "kworker/%s", id_buf);
1969c34056a3STejun Heo 	if (IS_ERR(worker->task))
1970c34056a3STejun Heo 		goto fail;
1971c34056a3STejun Heo 
197291151228SOleg Nesterov 	set_user_nice(worker->task, pool->attrs->nice);
197325834c73SPeter Zijlstra 	kthread_bind_mask(worker->task, pool->attrs->cpumask);
197491151228SOleg Nesterov 
1975da028469SLai Jiangshan 	/* successful, attach the worker to the pool */
19764736cbf7SLai Jiangshan 	worker_attach_to_pool(worker, pool);
1977822d8405STejun Heo 
1978051e1850SLai Jiangshan 	/* start the newly created worker */
1979a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
1980051e1850SLai Jiangshan 	worker->pool->nr_workers++;
1981051e1850SLai Jiangshan 	worker_enter_idle(worker);
1982051e1850SLai Jiangshan 	wake_up_process(worker->task);
1983a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
1984051e1850SLai Jiangshan 
1985c34056a3STejun Heo 	return worker;
1986822d8405STejun Heo 
1987c34056a3STejun Heo fail:
1988e441b56fSZhen Lei 	ida_free(&pool->worker_ida, id);
1989c34056a3STejun Heo 	kfree(worker);
1990c34056a3STejun Heo 	return NULL;
1991c34056a3STejun Heo }
1992c34056a3STejun Heo 
1993c34056a3STejun Heo /**
1994c34056a3STejun Heo  * destroy_worker - destroy a workqueue worker
1995c34056a3STejun Heo  * @worker: worker to be destroyed
1996c34056a3STejun Heo  *
199773eb7fe7SLai Jiangshan  * Destroy @worker and adjust @pool stats accordingly.  The worker should
199873eb7fe7SLai Jiangshan  * be idle.
1999c8e55f36STejun Heo  *
2000c8e55f36STejun Heo  * CONTEXT:
2001a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
2002c34056a3STejun Heo  */
2003c34056a3STejun Heo static void destroy_worker(struct worker *worker)
2004c34056a3STejun Heo {
2005bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2006c34056a3STejun Heo 
2007cd549687STejun Heo 	lockdep_assert_held(&pool->lock);
2008cd549687STejun Heo 
2009c34056a3STejun Heo 	/* sanity check frenzy */
20106183c009STejun Heo 	if (WARN_ON(worker->current_work) ||
201173eb7fe7SLai Jiangshan 	    WARN_ON(!list_empty(&worker->scheduled)) ||
201273eb7fe7SLai Jiangshan 	    WARN_ON(!(worker->flags & WORKER_IDLE)))
20136183c009STejun Heo 		return;
2014c34056a3STejun Heo 
2015bd7bdd43STejun Heo 	pool->nr_workers--;
2016bd7bdd43STejun Heo 	pool->nr_idle--;
2017c8e55f36STejun Heo 
2018c8e55f36STejun Heo 	list_del_init(&worker->entry);
2019cb444766STejun Heo 	worker->flags |= WORKER_DIE;
202060f5a4bcSLai Jiangshan 	wake_up_process(worker->task);
2021c34056a3STejun Heo }
2022c34056a3STejun Heo 
202332a6c723SKees Cook static void idle_worker_timeout(struct timer_list *t)
2024e22bee78STejun Heo {
202532a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, idle_timer);
2026e22bee78STejun Heo 
2027a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2028e22bee78STejun Heo 
20293347fc9fSLai Jiangshan 	while (too_many_workers(pool)) {
2030e22bee78STejun Heo 		struct worker *worker;
2031e22bee78STejun Heo 		unsigned long expires;
2032e22bee78STejun Heo 
2033e22bee78STejun Heo 		/* idle_list is kept in LIFO order, check the last one */
203463d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
2035e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2036e22bee78STejun Heo 
20373347fc9fSLai Jiangshan 		if (time_before(jiffies, expires)) {
203863d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
20393347fc9fSLai Jiangshan 			break;
2040e22bee78STejun Heo 		}
20413347fc9fSLai Jiangshan 
20423347fc9fSLai Jiangshan 		destroy_worker(worker);
2043e22bee78STejun Heo 	}
2044e22bee78STejun Heo 
2045a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2046e22bee78STejun Heo }
2047e22bee78STejun Heo 
2048493a1724STejun Heo static void send_mayday(struct work_struct *work)
2049e22bee78STejun Heo {
2050112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2051112202d9STejun Heo 	struct workqueue_struct *wq = pwq->wq;
2052493a1724STejun Heo 
20532e109a28STejun Heo 	lockdep_assert_held(&wq_mayday_lock);
2054e22bee78STejun Heo 
2055493008a8STejun Heo 	if (!wq->rescuer)
2056493a1724STejun Heo 		return;
2057e22bee78STejun Heo 
2058e22bee78STejun Heo 	/* mayday mayday mayday */
2059493a1724STejun Heo 	if (list_empty(&pwq->mayday_node)) {
206077668c8bSLai Jiangshan 		/*
206177668c8bSLai Jiangshan 		 * If @pwq is for an unbound wq, its base ref may be put at
206277668c8bSLai Jiangshan 		 * any time due to an attribute change.  Pin @pwq until the
206377668c8bSLai Jiangshan 		 * rescuer is done with it.
206477668c8bSLai Jiangshan 		 */
206577668c8bSLai Jiangshan 		get_pwq(pwq);
2066493a1724STejun Heo 		list_add_tail(&pwq->mayday_node, &wq->maydays);
2067e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
2068493a1724STejun Heo 	}
2069e22bee78STejun Heo }
2070e22bee78STejun Heo 
207132a6c723SKees Cook static void pool_mayday_timeout(struct timer_list *t)
2072e22bee78STejun Heo {
207332a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, mayday_timer);
2074e22bee78STejun Heo 	struct work_struct *work;
2075e22bee78STejun Heo 
2076a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2077a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock(&wq_mayday_lock);		/* for wq->maydays */
2078e22bee78STejun Heo 
207963d95a91STejun Heo 	if (need_to_create_worker(pool)) {
2080e22bee78STejun Heo 		/*
2081e22bee78STejun Heo 		 * We've been trying to create a new worker but
2082e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
2083e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
2084e22bee78STejun Heo 		 * rescuers.
2085e22bee78STejun Heo 		 */
208663d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
2087e22bee78STejun Heo 			send_mayday(work);
2088e22bee78STejun Heo 	}
2089e22bee78STejun Heo 
2090a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&wq_mayday_lock);
2091a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2092e22bee78STejun Heo 
209363d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
2094e22bee78STejun Heo }
2095e22bee78STejun Heo 
2096e22bee78STejun Heo /**
2097e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
209863d95a91STejun Heo  * @pool: pool to create a new worker for
2099e22bee78STejun Heo  *
210063d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
2101e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
2102e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
210363d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
2104e22bee78STejun Heo  * possible allocation deadlock.
2105e22bee78STejun Heo  *
2106c5aa87bbSTejun Heo  * On return, need_to_create_worker() is guaranteed to be %false and
2107c5aa87bbSTejun Heo  * may_start_working() %true.
2108e22bee78STejun Heo  *
2109e22bee78STejun Heo  * LOCKING:
2110a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2111e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
2112e22bee78STejun Heo  * manager.
2113e22bee78STejun Heo  */
211429187a9eSTejun Heo static void maybe_create_worker(struct worker_pool *pool)
2115d565ed63STejun Heo __releases(&pool->lock)
2116d565ed63STejun Heo __acquires(&pool->lock)
2117e22bee78STejun Heo {
2118e22bee78STejun Heo restart:
2119a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
21209f9c2364STejun Heo 
2121e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
212263d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
2123e22bee78STejun Heo 
2124e22bee78STejun Heo 	while (true) {
2125051e1850SLai Jiangshan 		if (create_worker(pool) || !need_to_create_worker(pool))
2126e22bee78STejun Heo 			break;
2127e22bee78STejun Heo 
2128e212f361SLai Jiangshan 		schedule_timeout_interruptible(CREATE_COOLDOWN);
21299f9c2364STejun Heo 
213063d95a91STejun Heo 		if (!need_to_create_worker(pool))
2131e22bee78STejun Heo 			break;
2132e22bee78STejun Heo 	}
2133e22bee78STejun Heo 
213463d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
2135a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2136051e1850SLai Jiangshan 	/*
2137051e1850SLai Jiangshan 	 * This is necessary even after a new worker was just successfully
2138051e1850SLai Jiangshan 	 * created as @pool->lock was dropped and the new worker might have
2139051e1850SLai Jiangshan 	 * already become busy.
2140051e1850SLai Jiangshan 	 */
214163d95a91STejun Heo 	if (need_to_create_worker(pool))
2142e22bee78STejun Heo 		goto restart;
2143e22bee78STejun Heo }
2144e22bee78STejun Heo 
2145e22bee78STejun Heo /**
2146e22bee78STejun Heo  * manage_workers - manage worker pool
2147e22bee78STejun Heo  * @worker: self
2148e22bee78STejun Heo  *
2149706026c2STejun Heo  * Assume the manager role and manage the worker pool @worker belongs
2150e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
2151706026c2STejun Heo  * pool.  The exclusion is handled automatically by this function.
2152e22bee78STejun Heo  *
2153e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
2154e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
2155e22bee78STejun Heo  * and may_start_working() is true.
2156e22bee78STejun Heo  *
2157e22bee78STejun Heo  * CONTEXT:
2158a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2159e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
2160e22bee78STejun Heo  *
2161d185af30SYacine Belkadi  * Return:
216229187a9eSTejun Heo  * %false if the pool doesn't need management and the caller can safely
216329187a9eSTejun Heo  * start processing works, %true if management function was performed and
216429187a9eSTejun Heo  * the conditions that the caller verified before calling the function may
216529187a9eSTejun Heo  * no longer be true.
2166e22bee78STejun Heo  */
2167e22bee78STejun Heo static bool manage_workers(struct worker *worker)
2168e22bee78STejun Heo {
216963d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
2170e22bee78STejun Heo 
2171692b4825STejun Heo 	if (pool->flags & POOL_MANAGER_ACTIVE)
217229187a9eSTejun Heo 		return false;
2173692b4825STejun Heo 
2174692b4825STejun Heo 	pool->flags |= POOL_MANAGER_ACTIVE;
21752607d7a6STejun Heo 	pool->manager = worker;
2176e22bee78STejun Heo 
217729187a9eSTejun Heo 	maybe_create_worker(pool);
2178e22bee78STejun Heo 
21792607d7a6STejun Heo 	pool->manager = NULL;
2180692b4825STejun Heo 	pool->flags &= ~POOL_MANAGER_ACTIVE;
2181d8bb65abSSebastian Andrzej Siewior 	rcuwait_wake_up(&manager_wait);
218229187a9eSTejun Heo 	return true;
2183e22bee78STejun Heo }
2184e22bee78STejun Heo 
2185a62428c0STejun Heo /**
2186a62428c0STejun Heo  * process_one_work - process single work
2187c34056a3STejun Heo  * @worker: self
2188a62428c0STejun Heo  * @work: work to process
2189a62428c0STejun Heo  *
2190a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
2191a62428c0STejun Heo  * process a single work including synchronization against and
2192a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
2193a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
2194a62428c0STejun Heo  * call this function to process a work.
2195a62428c0STejun Heo  *
2196a62428c0STejun Heo  * CONTEXT:
2197a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which is released and regrabbed.
2198a62428c0STejun Heo  */
2199c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
2200d565ed63STejun Heo __releases(&pool->lock)
2201d565ed63STejun Heo __acquires(&pool->lock)
22021da177e4SLinus Torvalds {
2203112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2204bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2205112202d9STejun Heo 	bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
2206c4560c2cSLai Jiangshan 	unsigned long work_data;
22077e11629dSTejun Heo 	struct worker *collision;
22084e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
22094e6045f1SJohannes Berg 	/*
2210a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
2211a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
2212a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
2213a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
2214a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
22154e6045f1SJohannes Berg 	 */
22164d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
22174d82a1deSPeter Zijlstra 
22184d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
22194e6045f1SJohannes Berg #endif
2220807407c0SLai Jiangshan 	/* ensure we're on the correct CPU */
222185327af6SLai Jiangshan 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2222ec22ca5eSTejun Heo 		     raw_smp_processor_id() != pool->cpu);
222325511a47STejun Heo 
22247e11629dSTejun Heo 	/*
22257e11629dSTejun Heo 	 * A single work shouldn't be executed concurrently by
22267e11629dSTejun Heo 	 * multiple workers on a single cpu.  Check whether anyone is
22277e11629dSTejun Heo 	 * already processing the work.  If so, defer the work to the
22287e11629dSTejun Heo 	 * currently executing one.
22297e11629dSTejun Heo 	 */
2230c9e7cf27STejun Heo 	collision = find_worker_executing_work(pool, work);
22317e11629dSTejun Heo 	if (unlikely(collision)) {
22327e11629dSTejun Heo 		move_linked_works(work, &collision->scheduled, NULL);
22337e11629dSTejun Heo 		return;
22347e11629dSTejun Heo 	}
22351da177e4SLinus Torvalds 
22368930cabaSTejun Heo 	/* claim and dequeue */
22371da177e4SLinus Torvalds 	debug_work_deactivate(work);
2238c9e7cf27STejun Heo 	hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2239c34056a3STejun Heo 	worker->current_work = work;
2240a2c1c57bSTejun Heo 	worker->current_func = work->func;
2241112202d9STejun Heo 	worker->current_pwq = pwq;
2242c4560c2cSLai Jiangshan 	work_data = *work_data_bits(work);
2243d812796eSLai Jiangshan 	worker->current_color = get_work_color(work_data);
22447a22ad75STejun Heo 
22458bf89593STejun Heo 	/*
22468bf89593STejun Heo 	 * Record wq name for cmdline and debug reporting, may get
22478bf89593STejun Heo 	 * overridden through set_worker_desc().
22488bf89593STejun Heo 	 */
22498bf89593STejun Heo 	strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
22508bf89593STejun Heo 
2251a62428c0STejun Heo 	list_del_init(&work->entry);
2252a62428c0STejun Heo 
2253649027d7STejun Heo 	/*
2254228f1d00SLai Jiangshan 	 * CPU intensive works don't participate in concurrency management.
2255228f1d00SLai Jiangshan 	 * They're the scheduler's responsibility.  This takes @worker out
2256228f1d00SLai Jiangshan 	 * of concurrency management and the next code block will chain
2257228f1d00SLai Jiangshan 	 * execution of the pending work items.
2258fb0e7bebSTejun Heo 	 */
2259fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2260228f1d00SLai Jiangshan 		worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2261fb0e7bebSTejun Heo 
2262974271c4STejun Heo 	/*
2263a489a03eSLai Jiangshan 	 * Wake up another worker if necessary.  The condition is always
2264a489a03eSLai Jiangshan 	 * false for normal per-cpu workers since nr_running would always
2265a489a03eSLai Jiangshan 	 * be >= 1 at this point.  This is used to chain execution of the
2266a489a03eSLai Jiangshan 	 * pending work items for WORKER_NOT_RUNNING workers such as the
2267228f1d00SLai Jiangshan 	 * UNBOUND and CPU_INTENSIVE ones.
2268974271c4STejun Heo 	 */
2269a489a03eSLai Jiangshan 	if (need_more_worker(pool))
227063d95a91STejun Heo 		wake_up_worker(pool);
2271974271c4STejun Heo 
22728930cabaSTejun Heo 	/*
22737c3eed5cSTejun Heo 	 * Record the last pool and clear PENDING which should be the last
2274d565ed63STejun Heo 	 * update to @work.  Also, do this inside @pool->lock so that
227523657bb1STejun Heo 	 * PENDING and queued state changes happen together while IRQ is
227623657bb1STejun Heo 	 * disabled.
22778930cabaSTejun Heo 	 */
22787c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(work, pool->id);
22791da177e4SLinus Torvalds 
2280a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2281365970a1SDavid Howells 
2282a1d14934SPeter Zijlstra 	lock_map_acquire(&pwq->wq->lockdep_map);
22833295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
2284e6f3faa7SPeter Zijlstra 	/*
2285f52be570SPeter Zijlstra 	 * Strictly speaking we should mark the invariant state without holding
2286f52be570SPeter Zijlstra 	 * any locks, that is, before these two lock_map_acquire()'s.
2287e6f3faa7SPeter Zijlstra 	 *
2288e6f3faa7SPeter Zijlstra 	 * However, that would result in:
2289e6f3faa7SPeter Zijlstra 	 *
2290e6f3faa7SPeter Zijlstra 	 *   A(W1)
2291e6f3faa7SPeter Zijlstra 	 *   WFC(C)
2292e6f3faa7SPeter Zijlstra 	 *		A(W1)
2293e6f3faa7SPeter Zijlstra 	 *		C(C)
2294e6f3faa7SPeter Zijlstra 	 *
2295e6f3faa7SPeter Zijlstra 	 * Which would create W1->C->W1 dependencies, even though there is no
2296e6f3faa7SPeter Zijlstra 	 * actual deadlock possible. There are two solutions, using a
2297e6f3faa7SPeter Zijlstra 	 * read-recursive acquire on the work(queue) 'locks', but this will then
2298f52be570SPeter Zijlstra 	 * hit the lockdep limitation on recursive locks, or simply discard
2299e6f3faa7SPeter Zijlstra 	 * these locks.
2300e6f3faa7SPeter Zijlstra 	 *
2301e6f3faa7SPeter Zijlstra 	 * AFAICT there is no possible deadlock scenario between the
2302e6f3faa7SPeter Zijlstra 	 * flush_work() and complete() primitives (except for single-threaded
2303e6f3faa7SPeter Zijlstra 	 * workqueues), so hiding them isn't a problem.
2304e6f3faa7SPeter Zijlstra 	 */
2305f52be570SPeter Zijlstra 	lockdep_invariant_state(true);
2306e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
2307a2c1c57bSTejun Heo 	worker->current_func(work);
2308e36c886aSArjan van de Ven 	/*
2309e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
2310e36c886aSArjan van de Ven 	 * point will only record its address.
2311e36c886aSArjan van de Ven 	 */
23121c5da0ecSDaniel Jordan 	trace_workqueue_execute_end(work, worker->current_func);
23133295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
2314112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
23151da177e4SLinus Torvalds 
2316d5abe669SPeter Zijlstra 	if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2317044c782cSValentin Ilie 		pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2318d75f773cSSakari Ailus 		       "     last function: %ps\n",
2319a2c1c57bSTejun Heo 		       current->comm, preempt_count(), task_pid_nr(current),
2320a2c1c57bSTejun Heo 		       worker->current_func);
2321d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
2322d5abe669SPeter Zijlstra 		dump_stack();
2323d5abe669SPeter Zijlstra 	}
2324d5abe669SPeter Zijlstra 
2325b22ce278STejun Heo 	/*
2326025f50f3SSebastian Andrzej Siewior 	 * The following prevents a kworker from hogging CPU on !PREEMPTION
2327b22ce278STejun Heo 	 * kernels, where a requeueing work item waiting for something to
2328b22ce278STejun Heo 	 * happen could deadlock with stop_machine as such work item could
2329b22ce278STejun Heo 	 * indefinitely requeue itself while all other CPUs are trapped in
2330789cbbecSJoe Lawrence 	 * stop_machine. At the same time, report a quiescent RCU state so
2331789cbbecSJoe Lawrence 	 * the same condition doesn't freeze RCU.
2332b22ce278STejun Heo 	 */
2333a7e6425eSPaul E. McKenney 	cond_resched();
2334b22ce278STejun Heo 
2335a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2336a62428c0STejun Heo 
2337fb0e7bebSTejun Heo 	/* clear cpu intensive status */
2338fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2339fb0e7bebSTejun Heo 		worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2340fb0e7bebSTejun Heo 
23411b69ac6bSJohannes Weiner 	/* tag the worker for identification in schedule() */
23421b69ac6bSJohannes Weiner 	worker->last_func = worker->current_func;
23431b69ac6bSJohannes Weiner 
2344a62428c0STejun Heo 	/* we're done with it, release */
234542f8570fSSasha Levin 	hash_del(&worker->hentry);
2346c34056a3STejun Heo 	worker->current_work = NULL;
2347a2c1c57bSTejun Heo 	worker->current_func = NULL;
2348112202d9STejun Heo 	worker->current_pwq = NULL;
2349d812796eSLai Jiangshan 	worker->current_color = INT_MAX;
2350c4560c2cSLai Jiangshan 	pwq_dec_nr_in_flight(pwq, work_data);
23511da177e4SLinus Torvalds }
23521da177e4SLinus Torvalds 
2353affee4b2STejun Heo /**
2354affee4b2STejun Heo  * process_scheduled_works - process scheduled works
2355affee4b2STejun Heo  * @worker: self
2356affee4b2STejun Heo  *
2357affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
2358affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
2359affee4b2STejun Heo  * fetches a work from the top and executes it.
2360affee4b2STejun Heo  *
2361affee4b2STejun Heo  * CONTEXT:
2362a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2363affee4b2STejun Heo  * multiple times.
2364affee4b2STejun Heo  */
2365affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
23661da177e4SLinus Torvalds {
2367affee4b2STejun Heo 	while (!list_empty(&worker->scheduled)) {
2368affee4b2STejun Heo 		struct work_struct *work = list_first_entry(&worker->scheduled,
2369a62428c0STejun Heo 						struct work_struct, entry);
2370c34056a3STejun Heo 		process_one_work(worker, work);
2371a62428c0STejun Heo 	}
23721da177e4SLinus Torvalds }
23731da177e4SLinus Torvalds 
2374197f6accSTejun Heo static void set_pf_worker(bool val)
2375197f6accSTejun Heo {
2376197f6accSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
2377197f6accSTejun Heo 	if (val)
2378197f6accSTejun Heo 		current->flags |= PF_WQ_WORKER;
2379197f6accSTejun Heo 	else
2380197f6accSTejun Heo 		current->flags &= ~PF_WQ_WORKER;
2381197f6accSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
2382197f6accSTejun Heo }
2383197f6accSTejun Heo 
23844690c4abSTejun Heo /**
23854690c4abSTejun Heo  * worker_thread - the worker thread function
2386c34056a3STejun Heo  * @__worker: self
23874690c4abSTejun Heo  *
2388c5aa87bbSTejun Heo  * The worker thread function.  All workers belong to a worker_pool -
2389c5aa87bbSTejun Heo  * either a per-cpu one or dynamic unbound one.  These workers process all
2390c5aa87bbSTejun Heo  * work items regardless of their specific target workqueue.  The only
2391c5aa87bbSTejun Heo  * exception is work items which belong to workqueues with a rescuer which
2392c5aa87bbSTejun Heo  * will be explained in rescuer_thread().
2393d185af30SYacine Belkadi  *
2394d185af30SYacine Belkadi  * Return: 0
23954690c4abSTejun Heo  */
2396c34056a3STejun Heo static int worker_thread(void *__worker)
23971da177e4SLinus Torvalds {
2398c34056a3STejun Heo 	struct worker *worker = __worker;
2399bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
24001da177e4SLinus Torvalds 
2401e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
2402197f6accSTejun Heo 	set_pf_worker(true);
2403c8e55f36STejun Heo woke_up:
2404a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2405affee4b2STejun Heo 
2406a9ab775bSTejun Heo 	/* am I supposed to die? */
2407a9ab775bSTejun Heo 	if (unlikely(worker->flags & WORKER_DIE)) {
2408a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
2409a9ab775bSTejun Heo 		WARN_ON_ONCE(!list_empty(&worker->entry));
2410197f6accSTejun Heo 		set_pf_worker(false);
241160f5a4bcSLai Jiangshan 
241260f5a4bcSLai Jiangshan 		set_task_comm(worker->task, "kworker/dying");
2413e441b56fSZhen Lei 		ida_free(&pool->worker_ida, worker->id);
2414a2d812a2STejun Heo 		worker_detach_from_pool(worker);
241560f5a4bcSLai Jiangshan 		kfree(worker);
2416c8e55f36STejun Heo 		return 0;
2417c8e55f36STejun Heo 	}
2418c8e55f36STejun Heo 
2419c8e55f36STejun Heo 	worker_leave_idle(worker);
2420db7bccf4STejun Heo recheck:
2421e22bee78STejun Heo 	/* no more worker necessary? */
242263d95a91STejun Heo 	if (!need_more_worker(pool))
2423e22bee78STejun Heo 		goto sleep;
2424e22bee78STejun Heo 
2425e22bee78STejun Heo 	/* do we need to manage? */
242663d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2427e22bee78STejun Heo 		goto recheck;
2428e22bee78STejun Heo 
2429c8e55f36STejun Heo 	/*
2430c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
2431c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
2432c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
2433c8e55f36STejun Heo 	 */
24346183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
2435c8e55f36STejun Heo 
2436e22bee78STejun Heo 	/*
2437a9ab775bSTejun Heo 	 * Finish PREP stage.  We're guaranteed to have at least one idle
2438a9ab775bSTejun Heo 	 * worker or that someone else has already assumed the manager
2439a9ab775bSTejun Heo 	 * role.  This is where @worker starts participating in concurrency
2440a9ab775bSTejun Heo 	 * management if applicable and concurrency management is restored
2441a9ab775bSTejun Heo 	 * after being rebound.  See rebind_workers() for details.
2442e22bee78STejun Heo 	 */
2443a9ab775bSTejun Heo 	worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2444e22bee78STejun Heo 
2445e22bee78STejun Heo 	do {
2446affee4b2STejun Heo 		struct work_struct *work =
2447bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
2448affee4b2STejun Heo 					 struct work_struct, entry);
2449affee4b2STejun Heo 
245082607adcSTejun Heo 		pool->watchdog_ts = jiffies;
245182607adcSTejun Heo 
2452c8e55f36STejun Heo 		if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2453affee4b2STejun Heo 			/* optimization path, not strictly necessary */
2454affee4b2STejun Heo 			process_one_work(worker, work);
2455affee4b2STejun Heo 			if (unlikely(!list_empty(&worker->scheduled)))
2456affee4b2STejun Heo 				process_scheduled_works(worker);
2457affee4b2STejun Heo 		} else {
2458c8e55f36STejun Heo 			move_linked_works(work, &worker->scheduled, NULL);
2459affee4b2STejun Heo 			process_scheduled_works(worker);
2460affee4b2STejun Heo 		}
246163d95a91STejun Heo 	} while (keep_working(pool));
2462affee4b2STejun Heo 
2463228f1d00SLai Jiangshan 	worker_set_flags(worker, WORKER_PREP);
2464d313dd85STejun Heo sleep:
2465c8e55f36STejun Heo 	/*
2466d565ed63STejun Heo 	 * pool->lock is held and there's no work to process and no need to
2467d565ed63STejun Heo 	 * manage, sleep.  Workers are woken up only while holding
2468d565ed63STejun Heo 	 * pool->lock or from local cpu, so setting the current state
2469d565ed63STejun Heo 	 * before releasing pool->lock is enough to prevent losing any
2470d565ed63STejun Heo 	 * event.
2471c8e55f36STejun Heo 	 */
2472c8e55f36STejun Heo 	worker_enter_idle(worker);
2473c5a94a61SPeter Zijlstra 	__set_current_state(TASK_IDLE);
2474a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
24751da177e4SLinus Torvalds 	schedule();
2476c8e55f36STejun Heo 	goto woke_up;
24771da177e4SLinus Torvalds }
24781da177e4SLinus Torvalds 
2479e22bee78STejun Heo /**
2480e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
2481111c225aSTejun Heo  * @__rescuer: self
2482e22bee78STejun Heo  *
2483e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
2484493008a8STejun Heo  * workqueue which has WQ_MEM_RECLAIM set.
2485e22bee78STejun Heo  *
2486706026c2STejun Heo  * Regular work processing on a pool may block trying to create a new
2487e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
2488e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
2489e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2490e22bee78STejun Heo  * the problem rescuer solves.
2491e22bee78STejun Heo  *
2492706026c2STejun Heo  * When such condition is possible, the pool summons rescuers of all
2493706026c2STejun Heo  * workqueues which have works queued on the pool and let them process
2494e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
2495e22bee78STejun Heo  *
2496e22bee78STejun Heo  * This should happen rarely.
2497d185af30SYacine Belkadi  *
2498d185af30SYacine Belkadi  * Return: 0
2499e22bee78STejun Heo  */
2500111c225aSTejun Heo static int rescuer_thread(void *__rescuer)
2501e22bee78STejun Heo {
2502111c225aSTejun Heo 	struct worker *rescuer = __rescuer;
2503111c225aSTejun Heo 	struct workqueue_struct *wq = rescuer->rescue_wq;
2504e22bee78STejun Heo 	struct list_head *scheduled = &rescuer->scheduled;
25054d595b86SLai Jiangshan 	bool should_stop;
2506e22bee78STejun Heo 
2507e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
2508111c225aSTejun Heo 
2509111c225aSTejun Heo 	/*
2510111c225aSTejun Heo 	 * Mark rescuer as worker too.  As WORKER_PREP is never cleared, it
2511111c225aSTejun Heo 	 * doesn't participate in concurrency management.
2512111c225aSTejun Heo 	 */
2513197f6accSTejun Heo 	set_pf_worker(true);
2514e22bee78STejun Heo repeat:
2515c5a94a61SPeter Zijlstra 	set_current_state(TASK_IDLE);
25161da177e4SLinus Torvalds 
25174d595b86SLai Jiangshan 	/*
25184d595b86SLai Jiangshan 	 * By the time the rescuer is requested to stop, the workqueue
25194d595b86SLai Jiangshan 	 * shouldn't have any work pending, but @wq->maydays may still have
25204d595b86SLai Jiangshan 	 * pwq(s) queued.  This can happen by non-rescuer workers consuming
25214d595b86SLai Jiangshan 	 * all the work items before the rescuer got to them.  Go through
25224d595b86SLai Jiangshan 	 * @wq->maydays processing before acting on should_stop so that the
25234d595b86SLai Jiangshan 	 * list is always empty on exit.
25244d595b86SLai Jiangshan 	 */
25254d595b86SLai Jiangshan 	should_stop = kthread_should_stop();
25261da177e4SLinus Torvalds 
2527493a1724STejun Heo 	/* see whether any pwq is asking for help */
2528a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&wq_mayday_lock);
2529493a1724STejun Heo 
2530493a1724STejun Heo 	while (!list_empty(&wq->maydays)) {
2531493a1724STejun Heo 		struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2532493a1724STejun Heo 					struct pool_workqueue, mayday_node);
2533112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
2534e22bee78STejun Heo 		struct work_struct *work, *n;
253582607adcSTejun Heo 		bool first = true;
2536e22bee78STejun Heo 
2537e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
2538493a1724STejun Heo 		list_del_init(&pwq->mayday_node);
2539493a1724STejun Heo 
2540a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&wq_mayday_lock);
2541e22bee78STejun Heo 
254251697d39SLai Jiangshan 		worker_attach_to_pool(rescuer, pool);
254351697d39SLai Jiangshan 
2544a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
2545e22bee78STejun Heo 
2546e22bee78STejun Heo 		/*
2547e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
2548e22bee78STejun Heo 		 * process'em.
2549e22bee78STejun Heo 		 */
25500479c8c5STejun Heo 		WARN_ON_ONCE(!list_empty(scheduled));
255182607adcSTejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry) {
255282607adcSTejun Heo 			if (get_work_pwq(work) == pwq) {
255382607adcSTejun Heo 				if (first)
255482607adcSTejun Heo 					pool->watchdog_ts = jiffies;
2555e22bee78STejun Heo 				move_linked_works(work, scheduled, &n);
255682607adcSTejun Heo 			}
255782607adcSTejun Heo 			first = false;
255882607adcSTejun Heo 		}
2559e22bee78STejun Heo 
2560008847f6SNeilBrown 		if (!list_empty(scheduled)) {
2561e22bee78STejun Heo 			process_scheduled_works(rescuer);
25627576958aSTejun Heo 
25637576958aSTejun Heo 			/*
2564008847f6SNeilBrown 			 * The above execution of rescued work items could
2565008847f6SNeilBrown 			 * have created more to rescue through
2566f97a4a1aSLai Jiangshan 			 * pwq_activate_first_inactive() or chained
2567008847f6SNeilBrown 			 * queueing.  Let's put @pwq back on mayday list so
2568008847f6SNeilBrown 			 * that such back-to-back work items, which may be
2569008847f6SNeilBrown 			 * being used to relieve memory pressure, don't
2570008847f6SNeilBrown 			 * incur MAYDAY_INTERVAL delay inbetween.
2571008847f6SNeilBrown 			 */
25724f3f4cf3SLai Jiangshan 			if (pwq->nr_active && need_to_create_worker(pool)) {
2573a9b8a985SSebastian Andrzej Siewior 				raw_spin_lock(&wq_mayday_lock);
2574e66b39afSTejun Heo 				/*
2575e66b39afSTejun Heo 				 * Queue iff we aren't racing destruction
2576e66b39afSTejun Heo 				 * and somebody else hasn't queued it already.
2577e66b39afSTejun Heo 				 */
2578e66b39afSTejun Heo 				if (wq->rescuer && list_empty(&pwq->mayday_node)) {
2579008847f6SNeilBrown 					get_pwq(pwq);
2580e66b39afSTejun Heo 					list_add_tail(&pwq->mayday_node, &wq->maydays);
2581e66b39afSTejun Heo 				}
2582a9b8a985SSebastian Andrzej Siewior 				raw_spin_unlock(&wq_mayday_lock);
2583008847f6SNeilBrown 			}
2584008847f6SNeilBrown 		}
2585008847f6SNeilBrown 
2586008847f6SNeilBrown 		/*
258777668c8bSLai Jiangshan 		 * Put the reference grabbed by send_mayday().  @pool won't
258813b1d625SLai Jiangshan 		 * go away while we're still attached to it.
258977668c8bSLai Jiangshan 		 */
259077668c8bSLai Jiangshan 		put_pwq(pwq);
259177668c8bSLai Jiangshan 
259277668c8bSLai Jiangshan 		/*
2593d8ca83e6SLai Jiangshan 		 * Leave this pool.  If need_more_worker() is %true, notify a
25947576958aSTejun Heo 		 * regular worker; otherwise, we end up with 0 concurrency
25957576958aSTejun Heo 		 * and stalling the execution.
25967576958aSTejun Heo 		 */
2597d8ca83e6SLai Jiangshan 		if (need_more_worker(pool))
259863d95a91STejun Heo 			wake_up_worker(pool);
25997576958aSTejun Heo 
2600a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
260113b1d625SLai Jiangshan 
2602a2d812a2STejun Heo 		worker_detach_from_pool(rescuer);
260313b1d625SLai Jiangshan 
2604a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&wq_mayday_lock);
26051da177e4SLinus Torvalds 	}
26061da177e4SLinus Torvalds 
2607a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&wq_mayday_lock);
2608493a1724STejun Heo 
26094d595b86SLai Jiangshan 	if (should_stop) {
26104d595b86SLai Jiangshan 		__set_current_state(TASK_RUNNING);
2611197f6accSTejun Heo 		set_pf_worker(false);
26124d595b86SLai Jiangshan 		return 0;
26134d595b86SLai Jiangshan 	}
26144d595b86SLai Jiangshan 
2615111c225aSTejun Heo 	/* rescuers should never participate in concurrency management */
2616111c225aSTejun Heo 	WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2617e22bee78STejun Heo 	schedule();
2618e22bee78STejun Heo 	goto repeat;
26191da177e4SLinus Torvalds }
26201da177e4SLinus Torvalds 
2621fca839c0STejun Heo /**
2622fca839c0STejun Heo  * check_flush_dependency - check for flush dependency sanity
2623fca839c0STejun Heo  * @target_wq: workqueue being flushed
2624fca839c0STejun Heo  * @target_work: work item being flushed (NULL for workqueue flushes)
2625fca839c0STejun Heo  *
2626fca839c0STejun Heo  * %current is trying to flush the whole @target_wq or @target_work on it.
2627fca839c0STejun Heo  * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
2628fca839c0STejun Heo  * reclaiming memory or running on a workqueue which doesn't have
2629fca839c0STejun Heo  * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
2630fca839c0STejun Heo  * a deadlock.
2631fca839c0STejun Heo  */
2632fca839c0STejun Heo static void check_flush_dependency(struct workqueue_struct *target_wq,
2633fca839c0STejun Heo 				   struct work_struct *target_work)
2634fca839c0STejun Heo {
2635fca839c0STejun Heo 	work_func_t target_func = target_work ? target_work->func : NULL;
2636fca839c0STejun Heo 	struct worker *worker;
2637fca839c0STejun Heo 
2638fca839c0STejun Heo 	if (target_wq->flags & WQ_MEM_RECLAIM)
2639fca839c0STejun Heo 		return;
2640fca839c0STejun Heo 
2641fca839c0STejun Heo 	worker = current_wq_worker();
2642fca839c0STejun Heo 
2643fca839c0STejun Heo 	WARN_ONCE(current->flags & PF_MEMALLOC,
2644d75f773cSSakari Ailus 		  "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps",
2645fca839c0STejun Heo 		  current->pid, current->comm, target_wq->name, target_func);
264623d11a58STejun Heo 	WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
264723d11a58STejun Heo 			      (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
2648d75f773cSSakari Ailus 		  "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps",
2649fca839c0STejun Heo 		  worker->current_pwq->wq->name, worker->current_func,
2650fca839c0STejun Heo 		  target_wq->name, target_func);
2651fca839c0STejun Heo }
2652fca839c0STejun Heo 
2653fc2e4d70SOleg Nesterov struct wq_barrier {
2654fc2e4d70SOleg Nesterov 	struct work_struct	work;
2655fc2e4d70SOleg Nesterov 	struct completion	done;
26562607d7a6STejun Heo 	struct task_struct	*task;	/* purely informational */
2657fc2e4d70SOleg Nesterov };
2658fc2e4d70SOleg Nesterov 
2659fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
2660fc2e4d70SOleg Nesterov {
2661fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2662fc2e4d70SOleg Nesterov 	complete(&barr->done);
2663fc2e4d70SOleg Nesterov }
2664fc2e4d70SOleg Nesterov 
26654690c4abSTejun Heo /**
26664690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
2667112202d9STejun Heo  * @pwq: pwq to insert barrier into
26684690c4abSTejun Heo  * @barr: wq_barrier to insert
2669affee4b2STejun Heo  * @target: target work to attach @barr to
2670affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
26714690c4abSTejun Heo  *
2672affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
2673affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
2674affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
2675affee4b2STejun Heo  * cpu.
2676affee4b2STejun Heo  *
2677affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
2678affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
2679affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
2680affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
2681affee4b2STejun Heo  * after a work with LINKED flag set.
2682affee4b2STejun Heo  *
2683affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
2684112202d9STejun Heo  * underneath us, so we can't reliably determine pwq from @target.
26854690c4abSTejun Heo  *
26864690c4abSTejun Heo  * CONTEXT:
2687a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
26884690c4abSTejun Heo  */
2689112202d9STejun Heo static void insert_wq_barrier(struct pool_workqueue *pwq,
2690affee4b2STejun Heo 			      struct wq_barrier *barr,
2691affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
2692fc2e4d70SOleg Nesterov {
2693d812796eSLai Jiangshan 	unsigned int work_flags = 0;
2694d812796eSLai Jiangshan 	unsigned int work_color;
2695affee4b2STejun Heo 	struct list_head *head;
2696affee4b2STejun Heo 
2697dc186ad7SThomas Gleixner 	/*
2698d565ed63STejun Heo 	 * debugobject calls are safe here even with pool->lock locked
2699dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
2700dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
2701dc186ad7SThomas Gleixner 	 * might deadlock.
2702dc186ad7SThomas Gleixner 	 */
2703ca1cab37SAndrew Morton 	INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
270422df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
270552fa5bc5SBoqun Feng 
2706fd1a5b04SByungchul Park 	init_completion_map(&barr->done, &target->lockdep_map);
2707fd1a5b04SByungchul Park 
27082607d7a6STejun Heo 	barr->task = current;
270983c22520SOleg Nesterov 
2710018f3a13SLai Jiangshan 	/* The barrier work item does not participate in pwq->nr_active. */
2711018f3a13SLai Jiangshan 	work_flags |= WORK_STRUCT_INACTIVE;
2712018f3a13SLai Jiangshan 
2713affee4b2STejun Heo 	/*
2714affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
2715affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
2716affee4b2STejun Heo 	 */
2717d812796eSLai Jiangshan 	if (worker) {
2718affee4b2STejun Heo 		head = worker->scheduled.next;
2719d812796eSLai Jiangshan 		work_color = worker->current_color;
2720d812796eSLai Jiangshan 	} else {
2721affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
2722affee4b2STejun Heo 
2723affee4b2STejun Heo 		head = target->entry.next;
2724affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
2725d21cece0SLai Jiangshan 		work_flags |= *bits & WORK_STRUCT_LINKED;
2726d812796eSLai Jiangshan 		work_color = get_work_color(*bits);
2727affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
2728affee4b2STejun Heo 	}
2729affee4b2STejun Heo 
2730d812796eSLai Jiangshan 	pwq->nr_in_flight[work_color]++;
2731d812796eSLai Jiangshan 	work_flags |= work_color_to_flags(work_color);
2732d812796eSLai Jiangshan 
2733dc186ad7SThomas Gleixner 	debug_work_activate(&barr->work);
2734d21cece0SLai Jiangshan 	insert_work(pwq, &barr->work, head, work_flags);
2735fc2e4d70SOleg Nesterov }
2736fc2e4d70SOleg Nesterov 
273773f53c4aSTejun Heo /**
2738112202d9STejun Heo  * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
273973f53c4aSTejun Heo  * @wq: workqueue being flushed
274073f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
274173f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
274273f53c4aSTejun Heo  *
2743112202d9STejun Heo  * Prepare pwqs for workqueue flushing.
274473f53c4aSTejun Heo  *
2745112202d9STejun Heo  * If @flush_color is non-negative, flush_color on all pwqs should be
2746112202d9STejun Heo  * -1.  If no pwq has in-flight commands at the specified color, all
2747112202d9STejun Heo  * pwq->flush_color's stay at -1 and %false is returned.  If any pwq
2748112202d9STejun Heo  * has in flight commands, its pwq->flush_color is set to
2749112202d9STejun Heo  * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
275073f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
275173f53c4aSTejun Heo  *
275273f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
275373f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
275473f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
275573f53c4aSTejun Heo  * is returned.
275673f53c4aSTejun Heo  *
2757112202d9STejun Heo  * If @work_color is non-negative, all pwqs should have the same
275873f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
275973f53c4aSTejun Heo  * advanced to @work_color.
276073f53c4aSTejun Heo  *
276173f53c4aSTejun Heo  * CONTEXT:
27623c25a55dSLai Jiangshan  * mutex_lock(wq->mutex).
276373f53c4aSTejun Heo  *
2764d185af30SYacine Belkadi  * Return:
276573f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
276673f53c4aSTejun Heo  * otherwise.
276773f53c4aSTejun Heo  */
2768112202d9STejun Heo static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
276973f53c4aSTejun Heo 				      int flush_color, int work_color)
27701da177e4SLinus Torvalds {
277173f53c4aSTejun Heo 	bool wait = false;
277249e3cf44STejun Heo 	struct pool_workqueue *pwq;
27731da177e4SLinus Torvalds 
277473f53c4aSTejun Heo 	if (flush_color >= 0) {
27756183c009STejun Heo 		WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2776112202d9STejun Heo 		atomic_set(&wq->nr_pwqs_to_flush, 1);
2777dc186ad7SThomas Gleixner 	}
277814441960SOleg Nesterov 
277949e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2780112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
27811da177e4SLinus Torvalds 
2782a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
278373f53c4aSTejun Heo 
278473f53c4aSTejun Heo 		if (flush_color >= 0) {
27856183c009STejun Heo 			WARN_ON_ONCE(pwq->flush_color != -1);
278673f53c4aSTejun Heo 
2787112202d9STejun Heo 			if (pwq->nr_in_flight[flush_color]) {
2788112202d9STejun Heo 				pwq->flush_color = flush_color;
2789112202d9STejun Heo 				atomic_inc(&wq->nr_pwqs_to_flush);
279073f53c4aSTejun Heo 				wait = true;
27911da177e4SLinus Torvalds 			}
279273f53c4aSTejun Heo 		}
279373f53c4aSTejun Heo 
279473f53c4aSTejun Heo 		if (work_color >= 0) {
27956183c009STejun Heo 			WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2796112202d9STejun Heo 			pwq->work_color = work_color;
279773f53c4aSTejun Heo 		}
279873f53c4aSTejun Heo 
2799a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
28001da177e4SLinus Torvalds 	}
28011da177e4SLinus Torvalds 
2802112202d9STejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
280373f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
280473f53c4aSTejun Heo 
280573f53c4aSTejun Heo 	return wait;
280683c22520SOleg Nesterov }
28071da177e4SLinus Torvalds 
28080fcb78c2SRolf Eike Beer /**
28091da177e4SLinus Torvalds  * flush_workqueue - ensure that any scheduled work has run to completion.
28100fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
28111da177e4SLinus Torvalds  *
2812c5aa87bbSTejun Heo  * This function sleeps until all work items which were queued on entry
2813c5aa87bbSTejun Heo  * have finished execution, but it is not livelocked by new incoming ones.
28141da177e4SLinus Torvalds  */
28157ad5b3a5SHarvey Harrison void flush_workqueue(struct workqueue_struct *wq)
28161da177e4SLinus Torvalds {
281773f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
281873f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
281973f53c4aSTejun Heo 		.flush_color = -1,
2820fd1a5b04SByungchul Park 		.done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map),
282173f53c4aSTejun Heo 	};
282273f53c4aSTejun Heo 	int next_color;
2823b1f4ec17SOleg Nesterov 
28243347fa09STejun Heo 	if (WARN_ON(!wq_online))
28253347fa09STejun Heo 		return;
28263347fa09STejun Heo 
282787915adcSJohannes Berg 	lock_map_acquire(&wq->lockdep_map);
282887915adcSJohannes Berg 	lock_map_release(&wq->lockdep_map);
282987915adcSJohannes Berg 
28303c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
283173f53c4aSTejun Heo 
283273f53c4aSTejun Heo 	/*
283373f53c4aSTejun Heo 	 * Start-to-wait phase
283473f53c4aSTejun Heo 	 */
283573f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
283673f53c4aSTejun Heo 
283773f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
283873f53c4aSTejun Heo 		/*
283973f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
284073f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
284173f53c4aSTejun Heo 		 * by one.
284273f53c4aSTejun Heo 		 */
28436183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
284473f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
284573f53c4aSTejun Heo 		wq->work_color = next_color;
284673f53c4aSTejun Heo 
284773f53c4aSTejun Heo 		if (!wq->first_flusher) {
284873f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
28496183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
285073f53c4aSTejun Heo 
285173f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
285273f53c4aSTejun Heo 
2853112202d9STejun Heo 			if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
285473f53c4aSTejun Heo 						       wq->work_color)) {
285573f53c4aSTejun Heo 				/* nothing to flush, done */
285673f53c4aSTejun Heo 				wq->flush_color = next_color;
285773f53c4aSTejun Heo 				wq->first_flusher = NULL;
285873f53c4aSTejun Heo 				goto out_unlock;
285973f53c4aSTejun Heo 			}
286073f53c4aSTejun Heo 		} else {
286173f53c4aSTejun Heo 			/* wait in queue */
28626183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
286373f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
2864112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
286573f53c4aSTejun Heo 		}
286673f53c4aSTejun Heo 	} else {
286773f53c4aSTejun Heo 		/*
286873f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
286973f53c4aSTejun Heo 		 * The next flush completion will assign us
287073f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
287173f53c4aSTejun Heo 		 */
287273f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
287373f53c4aSTejun Heo 	}
287473f53c4aSTejun Heo 
2875fca839c0STejun Heo 	check_flush_dependency(wq, NULL);
2876fca839c0STejun Heo 
28773c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
287873f53c4aSTejun Heo 
287973f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
288073f53c4aSTejun Heo 
288173f53c4aSTejun Heo 	/*
288273f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
288373f53c4aSTejun Heo 	 *
288473f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
288573f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
288673f53c4aSTejun Heo 	 */
288700d5d15bSChris Wilson 	if (READ_ONCE(wq->first_flusher) != &this_flusher)
288873f53c4aSTejun Heo 		return;
288973f53c4aSTejun Heo 
28903c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
289173f53c4aSTejun Heo 
28924ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
28934ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
28944ce48b37STejun Heo 		goto out_unlock;
28954ce48b37STejun Heo 
289600d5d15bSChris Wilson 	WRITE_ONCE(wq->first_flusher, NULL);
289773f53c4aSTejun Heo 
28986183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&this_flusher.list));
28996183c009STejun Heo 	WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
290073f53c4aSTejun Heo 
290173f53c4aSTejun Heo 	while (true) {
290273f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
290373f53c4aSTejun Heo 
290473f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
290573f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
290673f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
290773f53c4aSTejun Heo 				break;
290873f53c4aSTejun Heo 			list_del_init(&next->list);
290973f53c4aSTejun Heo 			complete(&next->done);
291073f53c4aSTejun Heo 		}
291173f53c4aSTejun Heo 
29126183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
291373f53c4aSTejun Heo 			     wq->flush_color != work_next_color(wq->work_color));
291473f53c4aSTejun Heo 
291573f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
291673f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
291773f53c4aSTejun Heo 
291873f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
291973f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
292073f53c4aSTejun Heo 			/*
292173f53c4aSTejun Heo 			 * Assign the same color to all overflowed
292273f53c4aSTejun Heo 			 * flushers, advance work_color and append to
292373f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
292473f53c4aSTejun Heo 			 * phase for these overflowed flushers.
292573f53c4aSTejun Heo 			 */
292673f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
292773f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
292873f53c4aSTejun Heo 
292973f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
293073f53c4aSTejun Heo 
293173f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
293273f53c4aSTejun Heo 					      &wq->flusher_queue);
2933112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
293473f53c4aSTejun Heo 		}
293573f53c4aSTejun Heo 
293673f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
29376183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != wq->work_color);
293873f53c4aSTejun Heo 			break;
293973f53c4aSTejun Heo 		}
294073f53c4aSTejun Heo 
294173f53c4aSTejun Heo 		/*
294273f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
2943112202d9STejun Heo 		 * the new first flusher and arm pwqs.
294473f53c4aSTejun Heo 		 */
29456183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color == wq->work_color);
29466183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color != next->flush_color);
294773f53c4aSTejun Heo 
294873f53c4aSTejun Heo 		list_del_init(&next->list);
294973f53c4aSTejun Heo 		wq->first_flusher = next;
295073f53c4aSTejun Heo 
2951112202d9STejun Heo 		if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
295273f53c4aSTejun Heo 			break;
295373f53c4aSTejun Heo 
295473f53c4aSTejun Heo 		/*
295573f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
295673f53c4aSTejun Heo 		 * flusher and repeat cascading.
295773f53c4aSTejun Heo 		 */
295873f53c4aSTejun Heo 		wq->first_flusher = NULL;
295973f53c4aSTejun Heo 	}
296073f53c4aSTejun Heo 
296173f53c4aSTejun Heo out_unlock:
29623c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
29631da177e4SLinus Torvalds }
29641dadafa8STim Gardner EXPORT_SYMBOL(flush_workqueue);
29651da177e4SLinus Torvalds 
29669c5a2ba7STejun Heo /**
29679c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
29689c5a2ba7STejun Heo  * @wq: workqueue to drain
29699c5a2ba7STejun Heo  *
29709c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
29719c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
29729c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
2973b749b1b6SChen Hanxiao  * repeatedly until it becomes empty.  The number of flushing is determined
29749c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
29759c5a2ba7STejun Heo  * takes too long.
29769c5a2ba7STejun Heo  */
29779c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
29789c5a2ba7STejun Heo {
29799c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
298049e3cf44STejun Heo 	struct pool_workqueue *pwq;
29819c5a2ba7STejun Heo 
29829c5a2ba7STejun Heo 	/*
29839c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
29849c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
2985618b01ebSTejun Heo 	 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
29869c5a2ba7STejun Heo 	 */
298787fc741eSLai Jiangshan 	mutex_lock(&wq->mutex);
29889c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
2989618b01ebSTejun Heo 		wq->flags |= __WQ_DRAINING;
299087fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
29919c5a2ba7STejun Heo reflush:
29929c5a2ba7STejun Heo 	flush_workqueue(wq);
29939c5a2ba7STejun Heo 
2994b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
299576af4d93STejun Heo 
299649e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2997fa2563e4SThomas Tuttle 		bool drained;
29989c5a2ba7STejun Heo 
2999a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
3000f97a4a1aSLai Jiangshan 		drained = !pwq->nr_active && list_empty(&pwq->inactive_works);
3001a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
3002fa2563e4SThomas Tuttle 
3003fa2563e4SThomas Tuttle 		if (drained)
30049c5a2ba7STejun Heo 			continue;
30059c5a2ba7STejun Heo 
30069c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
30079c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
3008e9ad2eb3SStephen Zhang 			pr_warn("workqueue %s: %s() isn't complete after %u tries\n",
3009e9ad2eb3SStephen Zhang 				wq->name, __func__, flush_cnt);
301076af4d93STejun Heo 
3011b09f4fd3SLai Jiangshan 		mutex_unlock(&wq->mutex);
30129c5a2ba7STejun Heo 		goto reflush;
30139c5a2ba7STejun Heo 	}
30149c5a2ba7STejun Heo 
30159c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
3016618b01ebSTejun Heo 		wq->flags &= ~__WQ_DRAINING;
301787fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
30189c5a2ba7STejun Heo }
30199c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
30209c5a2ba7STejun Heo 
3021d6e89786SJohannes Berg static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
3022d6e89786SJohannes Berg 			     bool from_cancel)
3023baf59022STejun Heo {
3024baf59022STejun Heo 	struct worker *worker = NULL;
3025c9e7cf27STejun Heo 	struct worker_pool *pool;
3026112202d9STejun Heo 	struct pool_workqueue *pwq;
3027baf59022STejun Heo 
3028baf59022STejun Heo 	might_sleep();
3029baf59022STejun Heo 
303024acfb71SThomas Gleixner 	rcu_read_lock();
3031fa1b54e6STejun Heo 	pool = get_work_pool(work);
3032fa1b54e6STejun Heo 	if (!pool) {
303324acfb71SThomas Gleixner 		rcu_read_unlock();
3034fa1b54e6STejun Heo 		return false;
3035fa1b54e6STejun Heo 	}
3036fa1b54e6STejun Heo 
3037a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
30380b3dae68SLai Jiangshan 	/* see the comment in try_to_grab_pending() with the same code */
3039112202d9STejun Heo 	pwq = get_work_pwq(work);
3040112202d9STejun Heo 	if (pwq) {
3041112202d9STejun Heo 		if (unlikely(pwq->pool != pool))
3042baf59022STejun Heo 			goto already_gone;
3043606a5020STejun Heo 	} else {
3044c9e7cf27STejun Heo 		worker = find_worker_executing_work(pool, work);
3045baf59022STejun Heo 		if (!worker)
3046baf59022STejun Heo 			goto already_gone;
3047112202d9STejun Heo 		pwq = worker->current_pwq;
3048606a5020STejun Heo 	}
3049baf59022STejun Heo 
3050fca839c0STejun Heo 	check_flush_dependency(pwq->wq, work);
3051fca839c0STejun Heo 
3052112202d9STejun Heo 	insert_wq_barrier(pwq, barr, work, worker);
3053a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
3054baf59022STejun Heo 
3055e159489bSTejun Heo 	/*
3056a1d14934SPeter Zijlstra 	 * Force a lock recursion deadlock when using flush_work() inside a
3057a1d14934SPeter Zijlstra 	 * single-threaded or rescuer equipped workqueue.
3058a1d14934SPeter Zijlstra 	 *
3059a1d14934SPeter Zijlstra 	 * For single threaded workqueues the deadlock happens when the work
3060a1d14934SPeter Zijlstra 	 * is after the work issuing the flush_work(). For rescuer equipped
3061a1d14934SPeter Zijlstra 	 * workqueues the deadlock happens when the rescuer stalls, blocking
3062a1d14934SPeter Zijlstra 	 * forward progress.
3063e159489bSTejun Heo 	 */
3064d6e89786SJohannes Berg 	if (!from_cancel &&
3065d6e89786SJohannes Berg 	    (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)) {
3066112202d9STejun Heo 		lock_map_acquire(&pwq->wq->lockdep_map);
3067112202d9STejun Heo 		lock_map_release(&pwq->wq->lockdep_map);
3068a1d14934SPeter Zijlstra 	}
306924acfb71SThomas Gleixner 	rcu_read_unlock();
3070baf59022STejun Heo 	return true;
3071baf59022STejun Heo already_gone:
3072a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
307324acfb71SThomas Gleixner 	rcu_read_unlock();
3074baf59022STejun Heo 	return false;
3075baf59022STejun Heo }
3076baf59022STejun Heo 
3077d6e89786SJohannes Berg static bool __flush_work(struct work_struct *work, bool from_cancel)
3078d6e89786SJohannes Berg {
3079d6e89786SJohannes Berg 	struct wq_barrier barr;
3080d6e89786SJohannes Berg 
3081d6e89786SJohannes Berg 	if (WARN_ON(!wq_online))
3082d6e89786SJohannes Berg 		return false;
3083d6e89786SJohannes Berg 
30844d43d395STetsuo Handa 	if (WARN_ON(!work->func))
30854d43d395STetsuo Handa 		return false;
30864d43d395STetsuo Handa 
308787915adcSJohannes Berg 	if (!from_cancel) {
308887915adcSJohannes Berg 		lock_map_acquire(&work->lockdep_map);
308987915adcSJohannes Berg 		lock_map_release(&work->lockdep_map);
309087915adcSJohannes Berg 	}
309187915adcSJohannes Berg 
3092d6e89786SJohannes Berg 	if (start_flush_work(work, &barr, from_cancel)) {
3093d6e89786SJohannes Berg 		wait_for_completion(&barr.done);
3094d6e89786SJohannes Berg 		destroy_work_on_stack(&barr.work);
3095d6e89786SJohannes Berg 		return true;
3096d6e89786SJohannes Berg 	} else {
3097d6e89786SJohannes Berg 		return false;
3098d6e89786SJohannes Berg 	}
3099d6e89786SJohannes Berg }
3100d6e89786SJohannes Berg 
3101db700897SOleg Nesterov /**
3102401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
3103401a8d04STejun Heo  * @work: the work to flush
3104db700897SOleg Nesterov  *
3105606a5020STejun Heo  * Wait until @work has finished execution.  @work is guaranteed to be idle
3106606a5020STejun Heo  * on return if it hasn't been requeued since flush started.
3107401a8d04STejun Heo  *
3108d185af30SYacine Belkadi  * Return:
3109401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3110401a8d04STejun Heo  * %false if it was already idle.
3111db700897SOleg Nesterov  */
3112401a8d04STejun Heo bool flush_work(struct work_struct *work)
3113db700897SOleg Nesterov {
3114d6e89786SJohannes Berg 	return __flush_work(work, false);
3115606a5020STejun Heo }
3116db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
3117db700897SOleg Nesterov 
31188603e1b3STejun Heo struct cwt_wait {
3119ac6424b9SIngo Molnar 	wait_queue_entry_t		wait;
31208603e1b3STejun Heo 	struct work_struct	*work;
31218603e1b3STejun Heo };
31228603e1b3STejun Heo 
3123ac6424b9SIngo Molnar static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
31248603e1b3STejun Heo {
31258603e1b3STejun Heo 	struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
31268603e1b3STejun Heo 
31278603e1b3STejun Heo 	if (cwait->work != key)
31288603e1b3STejun Heo 		return 0;
31298603e1b3STejun Heo 	return autoremove_wake_function(wait, mode, sync, key);
31308603e1b3STejun Heo }
31318603e1b3STejun Heo 
313236e227d2STejun Heo static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
3133401a8d04STejun Heo {
31348603e1b3STejun Heo 	static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
3135bbb68dfaSTejun Heo 	unsigned long flags;
31361f1f642eSOleg Nesterov 	int ret;
31371f1f642eSOleg Nesterov 
31381f1f642eSOleg Nesterov 	do {
3139bbb68dfaSTejun Heo 		ret = try_to_grab_pending(work, is_dwork, &flags);
3140bbb68dfaSTejun Heo 		/*
31418603e1b3STejun Heo 		 * If someone else is already canceling, wait for it to
31428603e1b3STejun Heo 		 * finish.  flush_work() doesn't work for PREEMPT_NONE
31438603e1b3STejun Heo 		 * because we may get scheduled between @work's completion
31448603e1b3STejun Heo 		 * and the other canceling task resuming and clearing
31458603e1b3STejun Heo 		 * CANCELING - flush_work() will return false immediately
31468603e1b3STejun Heo 		 * as @work is no longer busy, try_to_grab_pending() will
31478603e1b3STejun Heo 		 * return -ENOENT as @work is still being canceled and the
31488603e1b3STejun Heo 		 * other canceling task won't be able to clear CANCELING as
31498603e1b3STejun Heo 		 * we're hogging the CPU.
31508603e1b3STejun Heo 		 *
31518603e1b3STejun Heo 		 * Let's wait for completion using a waitqueue.  As this
31528603e1b3STejun Heo 		 * may lead to the thundering herd problem, use a custom
31538603e1b3STejun Heo 		 * wake function which matches @work along with exclusive
31548603e1b3STejun Heo 		 * wait and wakeup.
3155bbb68dfaSTejun Heo 		 */
31568603e1b3STejun Heo 		if (unlikely(ret == -ENOENT)) {
31578603e1b3STejun Heo 			struct cwt_wait cwait;
31588603e1b3STejun Heo 
31598603e1b3STejun Heo 			init_wait(&cwait.wait);
31608603e1b3STejun Heo 			cwait.wait.func = cwt_wakefn;
31618603e1b3STejun Heo 			cwait.work = work;
31628603e1b3STejun Heo 
31638603e1b3STejun Heo 			prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
31648603e1b3STejun Heo 						  TASK_UNINTERRUPTIBLE);
31658603e1b3STejun Heo 			if (work_is_canceling(work))
31668603e1b3STejun Heo 				schedule();
31678603e1b3STejun Heo 			finish_wait(&cancel_waitq, &cwait.wait);
31688603e1b3STejun Heo 		}
31691f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
31701f1f642eSOleg Nesterov 
3171bbb68dfaSTejun Heo 	/* tell other tasks trying to grab @work to back off */
3172bbb68dfaSTejun Heo 	mark_work_canceling(work);
3173bbb68dfaSTejun Heo 	local_irq_restore(flags);
3174bbb68dfaSTejun Heo 
31753347fa09STejun Heo 	/*
31763347fa09STejun Heo 	 * This allows canceling during early boot.  We know that @work
31773347fa09STejun Heo 	 * isn't executing.
31783347fa09STejun Heo 	 */
31793347fa09STejun Heo 	if (wq_online)
3180d6e89786SJohannes Berg 		__flush_work(work, true);
31813347fa09STejun Heo 
31827a22ad75STejun Heo 	clear_work_data(work);
31838603e1b3STejun Heo 
31848603e1b3STejun Heo 	/*
31858603e1b3STejun Heo 	 * Paired with prepare_to_wait() above so that either
31868603e1b3STejun Heo 	 * waitqueue_active() is visible here or !work_is_canceling() is
31878603e1b3STejun Heo 	 * visible there.
31888603e1b3STejun Heo 	 */
31898603e1b3STejun Heo 	smp_mb();
31908603e1b3STejun Heo 	if (waitqueue_active(&cancel_waitq))
31918603e1b3STejun Heo 		__wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
31928603e1b3STejun Heo 
31931f1f642eSOleg Nesterov 	return ret;
31941f1f642eSOleg Nesterov }
31951f1f642eSOleg Nesterov 
31966e84d644SOleg Nesterov /**
3197401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
3198401a8d04STejun Heo  * @work: the work to cancel
31996e84d644SOleg Nesterov  *
3200401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
3201401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
3202401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
3203401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
32041f1f642eSOleg Nesterov  *
3205401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
3206401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
32076e84d644SOleg Nesterov  *
3208401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
32096e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
3210401a8d04STejun Heo  *
3211d185af30SYacine Belkadi  * Return:
3212401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
32136e84d644SOleg Nesterov  */
3214401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
32156e84d644SOleg Nesterov {
321636e227d2STejun Heo 	return __cancel_work_timer(work, false);
3217b89deed3SOleg Nesterov }
321828e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
3219b89deed3SOleg Nesterov 
32206e84d644SOleg Nesterov /**
3221401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
3222401a8d04STejun Heo  * @dwork: the delayed work to flush
32236e84d644SOleg Nesterov  *
3224401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
3225401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
3226401a8d04STejun Heo  * considers the last queueing instance of @dwork.
32271f1f642eSOleg Nesterov  *
3228d185af30SYacine Belkadi  * Return:
3229401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3230401a8d04STejun Heo  * %false if it was already idle.
32316e84d644SOleg Nesterov  */
3232401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
3233401a8d04STejun Heo {
32348930cabaSTejun Heo 	local_irq_disable();
3235401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
323660c057bcSLai Jiangshan 		__queue_work(dwork->cpu, dwork->wq, &dwork->work);
32378930cabaSTejun Heo 	local_irq_enable();
3238401a8d04STejun Heo 	return flush_work(&dwork->work);
3239401a8d04STejun Heo }
3240401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
3241401a8d04STejun Heo 
324205f0fe6bSTejun Heo /**
324305f0fe6bSTejun Heo  * flush_rcu_work - wait for a rwork to finish executing the last queueing
324405f0fe6bSTejun Heo  * @rwork: the rcu work to flush
324505f0fe6bSTejun Heo  *
324605f0fe6bSTejun Heo  * Return:
324705f0fe6bSTejun Heo  * %true if flush_rcu_work() waited for the work to finish execution,
324805f0fe6bSTejun Heo  * %false if it was already idle.
324905f0fe6bSTejun Heo  */
325005f0fe6bSTejun Heo bool flush_rcu_work(struct rcu_work *rwork)
325105f0fe6bSTejun Heo {
325205f0fe6bSTejun Heo 	if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
325305f0fe6bSTejun Heo 		rcu_barrier();
325405f0fe6bSTejun Heo 		flush_work(&rwork->work);
325505f0fe6bSTejun Heo 		return true;
325605f0fe6bSTejun Heo 	} else {
325705f0fe6bSTejun Heo 		return flush_work(&rwork->work);
325805f0fe6bSTejun Heo 	}
325905f0fe6bSTejun Heo }
326005f0fe6bSTejun Heo EXPORT_SYMBOL(flush_rcu_work);
326105f0fe6bSTejun Heo 
3262f72b8792SJens Axboe static bool __cancel_work(struct work_struct *work, bool is_dwork)
3263f72b8792SJens Axboe {
3264f72b8792SJens Axboe 	unsigned long flags;
3265f72b8792SJens Axboe 	int ret;
3266f72b8792SJens Axboe 
3267f72b8792SJens Axboe 	do {
3268f72b8792SJens Axboe 		ret = try_to_grab_pending(work, is_dwork, &flags);
3269f72b8792SJens Axboe 	} while (unlikely(ret == -EAGAIN));
3270f72b8792SJens Axboe 
3271f72b8792SJens Axboe 	if (unlikely(ret < 0))
3272f72b8792SJens Axboe 		return false;
3273f72b8792SJens Axboe 
3274f72b8792SJens Axboe 	set_work_pool_and_clear_pending(work, get_work_pool_id(work));
3275f72b8792SJens Axboe 	local_irq_restore(flags);
3276f72b8792SJens Axboe 	return ret;
3277f72b8792SJens Axboe }
3278f72b8792SJens Axboe 
3279401a8d04STejun Heo /**
328057b30ae7STejun Heo  * cancel_delayed_work - cancel a delayed work
328157b30ae7STejun Heo  * @dwork: delayed_work to cancel
328209383498STejun Heo  *
3283d185af30SYacine Belkadi  * Kill off a pending delayed_work.
3284d185af30SYacine Belkadi  *
3285d185af30SYacine Belkadi  * Return: %true if @dwork was pending and canceled; %false if it wasn't
3286d185af30SYacine Belkadi  * pending.
3287d185af30SYacine Belkadi  *
3288d185af30SYacine Belkadi  * Note:
3289d185af30SYacine Belkadi  * The work callback function may still be running on return, unless
3290d185af30SYacine Belkadi  * it returns %true and the work doesn't re-arm itself.  Explicitly flush or
3291d185af30SYacine Belkadi  * use cancel_delayed_work_sync() to wait on it.
329209383498STejun Heo  *
329357b30ae7STejun Heo  * This function is safe to call from any context including IRQ handler.
329409383498STejun Heo  */
329557b30ae7STejun Heo bool cancel_delayed_work(struct delayed_work *dwork)
329609383498STejun Heo {
3297f72b8792SJens Axboe 	return __cancel_work(&dwork->work, true);
329809383498STejun Heo }
329957b30ae7STejun Heo EXPORT_SYMBOL(cancel_delayed_work);
330009383498STejun Heo 
330109383498STejun Heo /**
3302401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3303401a8d04STejun Heo  * @dwork: the delayed work cancel
3304401a8d04STejun Heo  *
3305401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
3306401a8d04STejun Heo  *
3307d185af30SYacine Belkadi  * Return:
3308401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
3309401a8d04STejun Heo  */
3310401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
33116e84d644SOleg Nesterov {
331236e227d2STejun Heo 	return __cancel_work_timer(&dwork->work, true);
33136e84d644SOleg Nesterov }
3314f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
33151da177e4SLinus Torvalds 
33160fcb78c2SRolf Eike Beer /**
331731ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
3318b6136773SAndrew Morton  * @func: the function to call
3319b6136773SAndrew Morton  *
332031ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
332131ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
3322b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
332331ddd871STejun Heo  *
3324d185af30SYacine Belkadi  * Return:
332531ddd871STejun Heo  * 0 on success, -errno on failure.
3326b6136773SAndrew Morton  */
332765f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
332815316ba8SChristoph Lameter {
332915316ba8SChristoph Lameter 	int cpu;
333038f51568SNamhyung Kim 	struct work_struct __percpu *works;
333115316ba8SChristoph Lameter 
3332b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
3333b6136773SAndrew Morton 	if (!works)
333415316ba8SChristoph Lameter 		return -ENOMEM;
3335b6136773SAndrew Morton 
3336ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
333793981800STejun Heo 
333815316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
33399bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
33409bfb1839SIngo Molnar 
33419bfb1839SIngo Molnar 		INIT_WORK(work, func);
33428de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
334315316ba8SChristoph Lameter 	}
334493981800STejun Heo 
334593981800STejun Heo 	for_each_online_cpu(cpu)
33468616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
334793981800STejun Heo 
3348ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
3349b6136773SAndrew Morton 	free_percpu(works);
335015316ba8SChristoph Lameter 	return 0;
335115316ba8SChristoph Lameter }
335215316ba8SChristoph Lameter 
3353eef6a7d5SAlan Stern /**
33541fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
33551fa44ecaSJames Bottomley  * @fn:		the function to execute
33561fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
33571fa44ecaSJames Bottomley  *		be available when the work executes)
33581fa44ecaSJames Bottomley  *
33591fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
33601fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
33611fa44ecaSJames Bottomley  *
3362d185af30SYacine Belkadi  * Return:	0 - function was executed
33631fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
33641fa44ecaSJames Bottomley  */
336565f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
33661fa44ecaSJames Bottomley {
33671fa44ecaSJames Bottomley 	if (!in_interrupt()) {
336865f27f38SDavid Howells 		fn(&ew->work);
33691fa44ecaSJames Bottomley 		return 0;
33701fa44ecaSJames Bottomley 	}
33711fa44ecaSJames Bottomley 
337265f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
33731fa44ecaSJames Bottomley 	schedule_work(&ew->work);
33741fa44ecaSJames Bottomley 
33751fa44ecaSJames Bottomley 	return 1;
33761fa44ecaSJames Bottomley }
33771fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
33781fa44ecaSJames Bottomley 
33797a4e344cSTejun Heo /**
33807a4e344cSTejun Heo  * free_workqueue_attrs - free a workqueue_attrs
33817a4e344cSTejun Heo  * @attrs: workqueue_attrs to free
33827a4e344cSTejun Heo  *
33837a4e344cSTejun Heo  * Undo alloc_workqueue_attrs().
33847a4e344cSTejun Heo  */
3385513c98d0SDaniel Jordan void free_workqueue_attrs(struct workqueue_attrs *attrs)
33867a4e344cSTejun Heo {
33877a4e344cSTejun Heo 	if (attrs) {
33887a4e344cSTejun Heo 		free_cpumask_var(attrs->cpumask);
33897a4e344cSTejun Heo 		kfree(attrs);
33907a4e344cSTejun Heo 	}
33917a4e344cSTejun Heo }
33927a4e344cSTejun Heo 
33937a4e344cSTejun Heo /**
33947a4e344cSTejun Heo  * alloc_workqueue_attrs - allocate a workqueue_attrs
33957a4e344cSTejun Heo  *
33967a4e344cSTejun Heo  * Allocate a new workqueue_attrs, initialize with default settings and
3397d185af30SYacine Belkadi  * return it.
3398d185af30SYacine Belkadi  *
3399d185af30SYacine Belkadi  * Return: The allocated new workqueue_attr on success. %NULL on failure.
34007a4e344cSTejun Heo  */
3401513c98d0SDaniel Jordan struct workqueue_attrs *alloc_workqueue_attrs(void)
34027a4e344cSTejun Heo {
34037a4e344cSTejun Heo 	struct workqueue_attrs *attrs;
34047a4e344cSTejun Heo 
3405be69d00dSThomas Gleixner 	attrs = kzalloc(sizeof(*attrs), GFP_KERNEL);
34067a4e344cSTejun Heo 	if (!attrs)
34077a4e344cSTejun Heo 		goto fail;
3408be69d00dSThomas Gleixner 	if (!alloc_cpumask_var(&attrs->cpumask, GFP_KERNEL))
34097a4e344cSTejun Heo 		goto fail;
34107a4e344cSTejun Heo 
341113e2e556STejun Heo 	cpumask_copy(attrs->cpumask, cpu_possible_mask);
34127a4e344cSTejun Heo 	return attrs;
34137a4e344cSTejun Heo fail:
34147a4e344cSTejun Heo 	free_workqueue_attrs(attrs);
34157a4e344cSTejun Heo 	return NULL;
34167a4e344cSTejun Heo }
34177a4e344cSTejun Heo 
341829c91e99STejun Heo static void copy_workqueue_attrs(struct workqueue_attrs *to,
341929c91e99STejun Heo 				 const struct workqueue_attrs *from)
342029c91e99STejun Heo {
342129c91e99STejun Heo 	to->nice = from->nice;
342229c91e99STejun Heo 	cpumask_copy(to->cpumask, from->cpumask);
34232865a8fbSShaohua Li 	/*
34242865a8fbSShaohua Li 	 * Unlike hash and equality test, this function doesn't ignore
34252865a8fbSShaohua Li 	 * ->no_numa as it is used for both pool and wq attrs.  Instead,
34262865a8fbSShaohua Li 	 * get_unbound_pool() explicitly clears ->no_numa after copying.
34272865a8fbSShaohua Li 	 */
34282865a8fbSShaohua Li 	to->no_numa = from->no_numa;
342929c91e99STejun Heo }
343029c91e99STejun Heo 
343129c91e99STejun Heo /* hash value of the content of @attr */
343229c91e99STejun Heo static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
343329c91e99STejun Heo {
343429c91e99STejun Heo 	u32 hash = 0;
343529c91e99STejun Heo 
343629c91e99STejun Heo 	hash = jhash_1word(attrs->nice, hash);
343713e2e556STejun Heo 	hash = jhash(cpumask_bits(attrs->cpumask),
343813e2e556STejun Heo 		     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
343929c91e99STejun Heo 	return hash;
344029c91e99STejun Heo }
344129c91e99STejun Heo 
344229c91e99STejun Heo /* content equality test */
344329c91e99STejun Heo static bool wqattrs_equal(const struct workqueue_attrs *a,
344429c91e99STejun Heo 			  const struct workqueue_attrs *b)
344529c91e99STejun Heo {
344629c91e99STejun Heo 	if (a->nice != b->nice)
344729c91e99STejun Heo 		return false;
344829c91e99STejun Heo 	if (!cpumask_equal(a->cpumask, b->cpumask))
344929c91e99STejun Heo 		return false;
345029c91e99STejun Heo 	return true;
345129c91e99STejun Heo }
345229c91e99STejun Heo 
34537a4e344cSTejun Heo /**
34547a4e344cSTejun Heo  * init_worker_pool - initialize a newly zalloc'd worker_pool
34557a4e344cSTejun Heo  * @pool: worker_pool to initialize
34567a4e344cSTejun Heo  *
3457402dd89dSShailendra Verma  * Initialize a newly zalloc'd @pool.  It also allocates @pool->attrs.
3458d185af30SYacine Belkadi  *
3459d185af30SYacine Belkadi  * Return: 0 on success, -errno on failure.  Even on failure, all fields
346029c91e99STejun Heo  * inside @pool proper are initialized and put_unbound_pool() can be called
346129c91e99STejun Heo  * on @pool safely to release it.
34627a4e344cSTejun Heo  */
34637a4e344cSTejun Heo static int init_worker_pool(struct worker_pool *pool)
34644e1a1f9aSTejun Heo {
3465a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_init(&pool->lock);
346629c91e99STejun Heo 	pool->id = -1;
346729c91e99STejun Heo 	pool->cpu = -1;
3468f3f90ad4STejun Heo 	pool->node = NUMA_NO_NODE;
34694e1a1f9aSTejun Heo 	pool->flags |= POOL_DISASSOCIATED;
347082607adcSTejun Heo 	pool->watchdog_ts = jiffies;
34714e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->worklist);
34724e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->idle_list);
34734e1a1f9aSTejun Heo 	hash_init(pool->busy_hash);
34744e1a1f9aSTejun Heo 
347532a6c723SKees Cook 	timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
34764e1a1f9aSTejun Heo 
347732a6c723SKees Cook 	timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
34784e1a1f9aSTejun Heo 
3479da028469SLai Jiangshan 	INIT_LIST_HEAD(&pool->workers);
34807a4e344cSTejun Heo 
34817cda9aaeSLai Jiangshan 	ida_init(&pool->worker_ida);
348229c91e99STejun Heo 	INIT_HLIST_NODE(&pool->hash_node);
348329c91e99STejun Heo 	pool->refcnt = 1;
348429c91e99STejun Heo 
348529c91e99STejun Heo 	/* shouldn't fail above this point */
3486be69d00dSThomas Gleixner 	pool->attrs = alloc_workqueue_attrs();
34877a4e344cSTejun Heo 	if (!pool->attrs)
34887a4e344cSTejun Heo 		return -ENOMEM;
34897a4e344cSTejun Heo 	return 0;
34904e1a1f9aSTejun Heo }
34914e1a1f9aSTejun Heo 
3492669de8bdSBart Van Assche #ifdef CONFIG_LOCKDEP
3493669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
3494669de8bdSBart Van Assche {
3495669de8bdSBart Van Assche 	char *lock_name;
3496669de8bdSBart Van Assche 
3497669de8bdSBart Van Assche 	lockdep_register_key(&wq->key);
3498669de8bdSBart Van Assche 	lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name);
3499669de8bdSBart Van Assche 	if (!lock_name)
3500669de8bdSBart Van Assche 		lock_name = wq->name;
350169a106c0SQian Cai 
350269a106c0SQian Cai 	wq->lock_name = lock_name;
3503669de8bdSBart Van Assche 	lockdep_init_map(&wq->lockdep_map, lock_name, &wq->key, 0);
3504669de8bdSBart Van Assche }
3505669de8bdSBart Van Assche 
3506669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
3507669de8bdSBart Van Assche {
3508669de8bdSBart Van Assche 	lockdep_unregister_key(&wq->key);
3509669de8bdSBart Van Assche }
3510669de8bdSBart Van Assche 
3511669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
3512669de8bdSBart Van Assche {
3513669de8bdSBart Van Assche 	if (wq->lock_name != wq->name)
3514669de8bdSBart Van Assche 		kfree(wq->lock_name);
3515669de8bdSBart Van Assche }
3516669de8bdSBart Van Assche #else
3517669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
3518669de8bdSBart Van Assche {
3519669de8bdSBart Van Assche }
3520669de8bdSBart Van Assche 
3521669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
3522669de8bdSBart Van Assche {
3523669de8bdSBart Van Assche }
3524669de8bdSBart Van Assche 
3525669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
3526669de8bdSBart Van Assche {
3527669de8bdSBart Van Assche }
3528669de8bdSBart Van Assche #endif
3529669de8bdSBart Van Assche 
3530e2dca7adSTejun Heo static void rcu_free_wq(struct rcu_head *rcu)
3531e2dca7adSTejun Heo {
3532e2dca7adSTejun Heo 	struct workqueue_struct *wq =
3533e2dca7adSTejun Heo 		container_of(rcu, struct workqueue_struct, rcu);
3534e2dca7adSTejun Heo 
3535669de8bdSBart Van Assche 	wq_free_lockdep(wq);
3536669de8bdSBart Van Assche 
3537e2dca7adSTejun Heo 	if (!(wq->flags & WQ_UNBOUND))
3538e2dca7adSTejun Heo 		free_percpu(wq->cpu_pwqs);
3539e2dca7adSTejun Heo 	else
3540e2dca7adSTejun Heo 		free_workqueue_attrs(wq->unbound_attrs);
3541e2dca7adSTejun Heo 
3542e2dca7adSTejun Heo 	kfree(wq);
3543e2dca7adSTejun Heo }
3544e2dca7adSTejun Heo 
354529c91e99STejun Heo static void rcu_free_pool(struct rcu_head *rcu)
354629c91e99STejun Heo {
354729c91e99STejun Heo 	struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
354829c91e99STejun Heo 
35497cda9aaeSLai Jiangshan 	ida_destroy(&pool->worker_ida);
355029c91e99STejun Heo 	free_workqueue_attrs(pool->attrs);
355129c91e99STejun Heo 	kfree(pool);
355229c91e99STejun Heo }
355329c91e99STejun Heo 
3554d8bb65abSSebastian Andrzej Siewior /* This returns with the lock held on success (pool manager is inactive). */
3555d8bb65abSSebastian Andrzej Siewior static bool wq_manager_inactive(struct worker_pool *pool)
3556d8bb65abSSebastian Andrzej Siewior {
3557a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
3558d8bb65abSSebastian Andrzej Siewior 
3559d8bb65abSSebastian Andrzej Siewior 	if (pool->flags & POOL_MANAGER_ACTIVE) {
3560a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
3561d8bb65abSSebastian Andrzej Siewior 		return false;
3562d8bb65abSSebastian Andrzej Siewior 	}
3563d8bb65abSSebastian Andrzej Siewior 	return true;
3564d8bb65abSSebastian Andrzej Siewior }
3565d8bb65abSSebastian Andrzej Siewior 
356629c91e99STejun Heo /**
356729c91e99STejun Heo  * put_unbound_pool - put a worker_pool
356829c91e99STejun Heo  * @pool: worker_pool to put
356929c91e99STejun Heo  *
357024acfb71SThomas Gleixner  * Put @pool.  If its refcnt reaches zero, it gets destroyed in RCU
3571c5aa87bbSTejun Heo  * safe manner.  get_unbound_pool() calls this function on its failure path
3572c5aa87bbSTejun Heo  * and this function should be able to release pools which went through,
3573c5aa87bbSTejun Heo  * successfully or not, init_worker_pool().
3574a892caccSTejun Heo  *
3575a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
357629c91e99STejun Heo  */
357729c91e99STejun Heo static void put_unbound_pool(struct worker_pool *pool)
357829c91e99STejun Heo {
357960f5a4bcSLai Jiangshan 	DECLARE_COMPLETION_ONSTACK(detach_completion);
358029c91e99STejun Heo 	struct worker *worker;
358129c91e99STejun Heo 
3582a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3583a892caccSTejun Heo 
3584a892caccSTejun Heo 	if (--pool->refcnt)
358529c91e99STejun Heo 		return;
358629c91e99STejun Heo 
358729c91e99STejun Heo 	/* sanity checks */
358861d0fbb4SLai Jiangshan 	if (WARN_ON(!(pool->cpu < 0)) ||
3589a892caccSTejun Heo 	    WARN_ON(!list_empty(&pool->worklist)))
359029c91e99STejun Heo 		return;
359129c91e99STejun Heo 
359229c91e99STejun Heo 	/* release id and unhash */
359329c91e99STejun Heo 	if (pool->id >= 0)
359429c91e99STejun Heo 		idr_remove(&worker_pool_idr, pool->id);
359529c91e99STejun Heo 	hash_del(&pool->hash_node);
359629c91e99STejun Heo 
3597c5aa87bbSTejun Heo 	/*
3598692b4825STejun Heo 	 * Become the manager and destroy all workers.  This prevents
3599692b4825STejun Heo 	 * @pool's workers from blocking on attach_mutex.  We're the last
3600692b4825STejun Heo 	 * manager and @pool gets freed with the flag set.
3601d8bb65abSSebastian Andrzej Siewior 	 * Because of how wq_manager_inactive() works, we will hold the
3602d8bb65abSSebastian Andrzej Siewior 	 * spinlock after a successful wait.
3603c5aa87bbSTejun Heo 	 */
3604d8bb65abSSebastian Andrzej Siewior 	rcuwait_wait_event(&manager_wait, wq_manager_inactive(pool),
3605d8bb65abSSebastian Andrzej Siewior 			   TASK_UNINTERRUPTIBLE);
3606692b4825STejun Heo 	pool->flags |= POOL_MANAGER_ACTIVE;
3607692b4825STejun Heo 
36081037de36SLai Jiangshan 	while ((worker = first_idle_worker(pool)))
360929c91e99STejun Heo 		destroy_worker(worker);
361029c91e99STejun Heo 	WARN_ON(pool->nr_workers || pool->nr_idle);
3611a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
361260f5a4bcSLai Jiangshan 
36131258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
3614da028469SLai Jiangshan 	if (!list_empty(&pool->workers))
361560f5a4bcSLai Jiangshan 		pool->detach_completion = &detach_completion;
36161258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
361760f5a4bcSLai Jiangshan 
361860f5a4bcSLai Jiangshan 	if (pool->detach_completion)
361960f5a4bcSLai Jiangshan 		wait_for_completion(pool->detach_completion);
362060f5a4bcSLai Jiangshan 
362129c91e99STejun Heo 	/* shut down the timers */
362229c91e99STejun Heo 	del_timer_sync(&pool->idle_timer);
362329c91e99STejun Heo 	del_timer_sync(&pool->mayday_timer);
362429c91e99STejun Heo 
362524acfb71SThomas Gleixner 	/* RCU protected to allow dereferences from get_work_pool() */
362625b00775SPaul E. McKenney 	call_rcu(&pool->rcu, rcu_free_pool);
362729c91e99STejun Heo }
362829c91e99STejun Heo 
362929c91e99STejun Heo /**
363029c91e99STejun Heo  * get_unbound_pool - get a worker_pool with the specified attributes
363129c91e99STejun Heo  * @attrs: the attributes of the worker_pool to get
363229c91e99STejun Heo  *
363329c91e99STejun Heo  * Obtain a worker_pool which has the same attributes as @attrs, bump the
363429c91e99STejun Heo  * reference count and return it.  If there already is a matching
363529c91e99STejun Heo  * worker_pool, it will be used; otherwise, this function attempts to
3636d185af30SYacine Belkadi  * create a new one.
3637a892caccSTejun Heo  *
3638a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
3639d185af30SYacine Belkadi  *
3640d185af30SYacine Belkadi  * Return: On success, a worker_pool with the same attributes as @attrs.
3641d185af30SYacine Belkadi  * On failure, %NULL.
364229c91e99STejun Heo  */
364329c91e99STejun Heo static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
364429c91e99STejun Heo {
364529c91e99STejun Heo 	u32 hash = wqattrs_hash(attrs);
364629c91e99STejun Heo 	struct worker_pool *pool;
3647f3f90ad4STejun Heo 	int node;
3648e2273584SXunlei Pang 	int target_node = NUMA_NO_NODE;
364929c91e99STejun Heo 
3650a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
365129c91e99STejun Heo 
365229c91e99STejun Heo 	/* do we already have a matching pool? */
365329c91e99STejun Heo 	hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
365429c91e99STejun Heo 		if (wqattrs_equal(pool->attrs, attrs)) {
365529c91e99STejun Heo 			pool->refcnt++;
36563fb1823cSLai Jiangshan 			return pool;
365729c91e99STejun Heo 		}
365829c91e99STejun Heo 	}
365929c91e99STejun Heo 
3660e2273584SXunlei Pang 	/* if cpumask is contained inside a NUMA node, we belong to that node */
3661e2273584SXunlei Pang 	if (wq_numa_enabled) {
3662e2273584SXunlei Pang 		for_each_node(node) {
3663e2273584SXunlei Pang 			if (cpumask_subset(attrs->cpumask,
3664e2273584SXunlei Pang 					   wq_numa_possible_cpumask[node])) {
3665e2273584SXunlei Pang 				target_node = node;
3666e2273584SXunlei Pang 				break;
3667e2273584SXunlei Pang 			}
3668e2273584SXunlei Pang 		}
3669e2273584SXunlei Pang 	}
3670e2273584SXunlei Pang 
367129c91e99STejun Heo 	/* nope, create a new one */
3672e2273584SXunlei Pang 	pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, target_node);
367329c91e99STejun Heo 	if (!pool || init_worker_pool(pool) < 0)
367429c91e99STejun Heo 		goto fail;
367529c91e99STejun Heo 
36768864b4e5STejun Heo 	lockdep_set_subclass(&pool->lock, 1);	/* see put_pwq() */
367729c91e99STejun Heo 	copy_workqueue_attrs(pool->attrs, attrs);
3678e2273584SXunlei Pang 	pool->node = target_node;
367929c91e99STejun Heo 
36802865a8fbSShaohua Li 	/*
36812865a8fbSShaohua Li 	 * no_numa isn't a worker_pool attribute, always clear it.  See
36822865a8fbSShaohua Li 	 * 'struct workqueue_attrs' comments for detail.
36832865a8fbSShaohua Li 	 */
36842865a8fbSShaohua Li 	pool->attrs->no_numa = false;
36852865a8fbSShaohua Li 
368629c91e99STejun Heo 	if (worker_pool_assign_id(pool) < 0)
368729c91e99STejun Heo 		goto fail;
368829c91e99STejun Heo 
368929c91e99STejun Heo 	/* create and start the initial worker */
36903347fa09STejun Heo 	if (wq_online && !create_worker(pool))
369129c91e99STejun Heo 		goto fail;
369229c91e99STejun Heo 
369329c91e99STejun Heo 	/* install */
369429c91e99STejun Heo 	hash_add(unbound_pool_hash, &pool->hash_node, hash);
36953fb1823cSLai Jiangshan 
369629c91e99STejun Heo 	return pool;
369729c91e99STejun Heo fail:
369829c91e99STejun Heo 	if (pool)
369929c91e99STejun Heo 		put_unbound_pool(pool);
370029c91e99STejun Heo 	return NULL;
370129c91e99STejun Heo }
370229c91e99STejun Heo 
37038864b4e5STejun Heo static void rcu_free_pwq(struct rcu_head *rcu)
37048864b4e5STejun Heo {
37058864b4e5STejun Heo 	kmem_cache_free(pwq_cache,
37068864b4e5STejun Heo 			container_of(rcu, struct pool_workqueue, rcu));
37078864b4e5STejun Heo }
37088864b4e5STejun Heo 
37098864b4e5STejun Heo /*
37108864b4e5STejun Heo  * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
37118864b4e5STejun Heo  * and needs to be destroyed.
37128864b4e5STejun Heo  */
37138864b4e5STejun Heo static void pwq_unbound_release_workfn(struct work_struct *work)
37148864b4e5STejun Heo {
37158864b4e5STejun Heo 	struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
37168864b4e5STejun Heo 						  unbound_release_work);
37178864b4e5STejun Heo 	struct workqueue_struct *wq = pwq->wq;
37188864b4e5STejun Heo 	struct worker_pool *pool = pwq->pool;
3719b42b0bddSYang Yingliang 	bool is_last = false;
37208864b4e5STejun Heo 
3721b42b0bddSYang Yingliang 	/*
3722b42b0bddSYang Yingliang 	 * when @pwq is not linked, it doesn't hold any reference to the
3723b42b0bddSYang Yingliang 	 * @wq, and @wq is invalid to access.
3724b42b0bddSYang Yingliang 	 */
3725b42b0bddSYang Yingliang 	if (!list_empty(&pwq->pwqs_node)) {
37268864b4e5STejun Heo 		if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
37278864b4e5STejun Heo 			return;
37288864b4e5STejun Heo 
37293c25a55dSLai Jiangshan 		mutex_lock(&wq->mutex);
37308864b4e5STejun Heo 		list_del_rcu(&pwq->pwqs_node);
3731bc0caf09STejun Heo 		is_last = list_empty(&wq->pwqs);
37323c25a55dSLai Jiangshan 		mutex_unlock(&wq->mutex);
3733b42b0bddSYang Yingliang 	}
37348864b4e5STejun Heo 
3735a892caccSTejun Heo 	mutex_lock(&wq_pool_mutex);
37368864b4e5STejun Heo 	put_unbound_pool(pool);
3737a892caccSTejun Heo 	mutex_unlock(&wq_pool_mutex);
3738a892caccSTejun Heo 
373925b00775SPaul E. McKenney 	call_rcu(&pwq->rcu, rcu_free_pwq);
37408864b4e5STejun Heo 
37418864b4e5STejun Heo 	/*
37428864b4e5STejun Heo 	 * If we're the last pwq going away, @wq is already dead and no one
3743e2dca7adSTejun Heo 	 * is gonna access it anymore.  Schedule RCU free.
37448864b4e5STejun Heo 	 */
3745669de8bdSBart Van Assche 	if (is_last) {
3746669de8bdSBart Van Assche 		wq_unregister_lockdep(wq);
374725b00775SPaul E. McKenney 		call_rcu(&wq->rcu, rcu_free_wq);
37486029a918STejun Heo 	}
3749669de8bdSBart Van Assche }
37508864b4e5STejun Heo 
37510fbd95aaSTejun Heo /**
3752699ce097STejun Heo  * pwq_adjust_max_active - update a pwq's max_active to the current setting
37530fbd95aaSTejun Heo  * @pwq: target pool_workqueue
37540fbd95aaSTejun Heo  *
3755699ce097STejun Heo  * If @pwq isn't freezing, set @pwq->max_active to the associated
3756f97a4a1aSLai Jiangshan  * workqueue's saved_max_active and activate inactive work items
3757699ce097STejun Heo  * accordingly.  If @pwq is freezing, clear @pwq->max_active to zero.
37580fbd95aaSTejun Heo  */
3759699ce097STejun Heo static void pwq_adjust_max_active(struct pool_workqueue *pwq)
37600fbd95aaSTejun Heo {
3761699ce097STejun Heo 	struct workqueue_struct *wq = pwq->wq;
3762699ce097STejun Heo 	bool freezable = wq->flags & WQ_FREEZABLE;
37633347fa09STejun Heo 	unsigned long flags;
3764699ce097STejun Heo 
3765699ce097STejun Heo 	/* for @wq->saved_max_active */
3766a357fc03SLai Jiangshan 	lockdep_assert_held(&wq->mutex);
3767699ce097STejun Heo 
3768699ce097STejun Heo 	/* fast exit for non-freezable wqs */
3769699ce097STejun Heo 	if (!freezable && pwq->max_active == wq->saved_max_active)
3770699ce097STejun Heo 		return;
3771699ce097STejun Heo 
37723347fa09STejun Heo 	/* this function can be called during early boot w/ irq disabled */
3773a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irqsave(&pwq->pool->lock, flags);
3774699ce097STejun Heo 
377574b414eaSLai Jiangshan 	/*
377674b414eaSLai Jiangshan 	 * During [un]freezing, the caller is responsible for ensuring that
377774b414eaSLai Jiangshan 	 * this function is called at least once after @workqueue_freezing
377874b414eaSLai Jiangshan 	 * is updated and visible.
377974b414eaSLai Jiangshan 	 */
378074b414eaSLai Jiangshan 	if (!freezable || !workqueue_freezing) {
378101341fbdSYunfeng Ye 		bool kick = false;
378201341fbdSYunfeng Ye 
3783699ce097STejun Heo 		pwq->max_active = wq->saved_max_active;
37840fbd95aaSTejun Heo 
3785f97a4a1aSLai Jiangshan 		while (!list_empty(&pwq->inactive_works) &&
378601341fbdSYunfeng Ye 		       pwq->nr_active < pwq->max_active) {
3787f97a4a1aSLai Jiangshan 			pwq_activate_first_inactive(pwq);
378801341fbdSYunfeng Ye 			kick = true;
378901341fbdSYunfeng Ye 		}
3790951a078aSLai Jiangshan 
3791951a078aSLai Jiangshan 		/*
3792951a078aSLai Jiangshan 		 * Need to kick a worker after thawed or an unbound wq's
379301341fbdSYunfeng Ye 		 * max_active is bumped. In realtime scenarios, always kicking a
379401341fbdSYunfeng Ye 		 * worker will cause interference on the isolated cpu cores, so
379501341fbdSYunfeng Ye 		 * let's kick iff work items were activated.
3796951a078aSLai Jiangshan 		 */
379701341fbdSYunfeng Ye 		if (kick)
3798951a078aSLai Jiangshan 			wake_up_worker(pwq->pool);
3799699ce097STejun Heo 	} else {
3800699ce097STejun Heo 		pwq->max_active = 0;
3801699ce097STejun Heo 	}
3802699ce097STejun Heo 
3803a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
38040fbd95aaSTejun Heo }
38050fbd95aaSTejun Heo 
380667dc8325SCai Huoqing /* initialize newly allocated @pwq which is associated with @wq and @pool */
3807f147f29eSTejun Heo static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
3808f147f29eSTejun Heo 		     struct worker_pool *pool)
3809d2c1d404STejun Heo {
3810d2c1d404STejun Heo 	BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3811d2c1d404STejun Heo 
3812e50aba9aSTejun Heo 	memset(pwq, 0, sizeof(*pwq));
3813e50aba9aSTejun Heo 
3814d2c1d404STejun Heo 	pwq->pool = pool;
3815d2c1d404STejun Heo 	pwq->wq = wq;
3816d2c1d404STejun Heo 	pwq->flush_color = -1;
38178864b4e5STejun Heo 	pwq->refcnt = 1;
3818f97a4a1aSLai Jiangshan 	INIT_LIST_HEAD(&pwq->inactive_works);
38191befcf30STejun Heo 	INIT_LIST_HEAD(&pwq->pwqs_node);
3820d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->mayday_node);
38218864b4e5STejun Heo 	INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
3822f147f29eSTejun Heo }
3823d2c1d404STejun Heo 
3824f147f29eSTejun Heo /* sync @pwq with the current state of its associated wq and link it */
38251befcf30STejun Heo static void link_pwq(struct pool_workqueue *pwq)
3826f147f29eSTejun Heo {
3827f147f29eSTejun Heo 	struct workqueue_struct *wq = pwq->wq;
3828f147f29eSTejun Heo 
3829f147f29eSTejun Heo 	lockdep_assert_held(&wq->mutex);
383075ccf595STejun Heo 
38311befcf30STejun Heo 	/* may be called multiple times, ignore if already linked */
38321befcf30STejun Heo 	if (!list_empty(&pwq->pwqs_node))
38331befcf30STejun Heo 		return;
38341befcf30STejun Heo 
383529b1cb41SLai Jiangshan 	/* set the matching work_color */
383675ccf595STejun Heo 	pwq->work_color = wq->work_color;
3837983ca25eSTejun Heo 
3838983ca25eSTejun Heo 	/* sync max_active to the current setting */
3839983ca25eSTejun Heo 	pwq_adjust_max_active(pwq);
3840983ca25eSTejun Heo 
3841983ca25eSTejun Heo 	/* link in @pwq */
38429e8cd2f5STejun Heo 	list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
3843df2d5ae4STejun Heo }
38446029a918STejun Heo 
3845f147f29eSTejun Heo /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
3846f147f29eSTejun Heo static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
3847f147f29eSTejun Heo 					const struct workqueue_attrs *attrs)
3848f147f29eSTejun Heo {
3849f147f29eSTejun Heo 	struct worker_pool *pool;
3850f147f29eSTejun Heo 	struct pool_workqueue *pwq;
3851f147f29eSTejun Heo 
3852f147f29eSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3853f147f29eSTejun Heo 
3854f147f29eSTejun Heo 	pool = get_unbound_pool(attrs);
3855f147f29eSTejun Heo 	if (!pool)
3856f147f29eSTejun Heo 		return NULL;
3857f147f29eSTejun Heo 
3858e50aba9aSTejun Heo 	pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
3859f147f29eSTejun Heo 	if (!pwq) {
3860f147f29eSTejun Heo 		put_unbound_pool(pool);
3861f147f29eSTejun Heo 		return NULL;
3862f147f29eSTejun Heo 	}
3863f147f29eSTejun Heo 
3864f147f29eSTejun Heo 	init_pwq(pwq, wq, pool);
3865f147f29eSTejun Heo 	return pwq;
3866d2c1d404STejun Heo }
3867d2c1d404STejun Heo 
38684c16bd32STejun Heo /**
386930186c6fSGong Zhaogang  * wq_calc_node_cpumask - calculate a wq_attrs' cpumask for the specified node
3870042f7df1SLai Jiangshan  * @attrs: the wq_attrs of the default pwq of the target workqueue
38714c16bd32STejun Heo  * @node: the target NUMA node
38724c16bd32STejun Heo  * @cpu_going_down: if >= 0, the CPU to consider as offline
38734c16bd32STejun Heo  * @cpumask: outarg, the resulting cpumask
38744c16bd32STejun Heo  *
38754c16bd32STejun Heo  * Calculate the cpumask a workqueue with @attrs should use on @node.  If
38764c16bd32STejun Heo  * @cpu_going_down is >= 0, that cpu is considered offline during
3877d185af30SYacine Belkadi  * calculation.  The result is stored in @cpumask.
38784c16bd32STejun Heo  *
38794c16bd32STejun Heo  * If NUMA affinity is not enabled, @attrs->cpumask is always used.  If
38804c16bd32STejun Heo  * enabled and @node has online CPUs requested by @attrs, the returned
38814c16bd32STejun Heo  * cpumask is the intersection of the possible CPUs of @node and
38824c16bd32STejun Heo  * @attrs->cpumask.
38834c16bd32STejun Heo  *
38844c16bd32STejun Heo  * The caller is responsible for ensuring that the cpumask of @node stays
38854c16bd32STejun Heo  * stable.
3886d185af30SYacine Belkadi  *
3887d185af30SYacine Belkadi  * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
3888d185af30SYacine Belkadi  * %false if equal.
38894c16bd32STejun Heo  */
38904c16bd32STejun Heo static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
38914c16bd32STejun Heo 				 int cpu_going_down, cpumask_t *cpumask)
38924c16bd32STejun Heo {
3893d55262c4STejun Heo 	if (!wq_numa_enabled || attrs->no_numa)
38944c16bd32STejun Heo 		goto use_dfl;
38954c16bd32STejun Heo 
38964c16bd32STejun Heo 	/* does @node have any online CPUs @attrs wants? */
38974c16bd32STejun Heo 	cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
38984c16bd32STejun Heo 	if (cpu_going_down >= 0)
38994c16bd32STejun Heo 		cpumask_clear_cpu(cpu_going_down, cpumask);
39004c16bd32STejun Heo 
39014c16bd32STejun Heo 	if (cpumask_empty(cpumask))
39024c16bd32STejun Heo 		goto use_dfl;
39034c16bd32STejun Heo 
39044c16bd32STejun Heo 	/* yeap, return possible CPUs in @node that @attrs wants */
39054c16bd32STejun Heo 	cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
39061ad0f0a7SMichael Bringmann 
39071ad0f0a7SMichael Bringmann 	if (cpumask_empty(cpumask)) {
39081ad0f0a7SMichael Bringmann 		pr_warn_once("WARNING: workqueue cpumask: online intersect > "
39091ad0f0a7SMichael Bringmann 				"possible intersect\n");
39101ad0f0a7SMichael Bringmann 		return false;
39111ad0f0a7SMichael Bringmann 	}
39121ad0f0a7SMichael Bringmann 
39134c16bd32STejun Heo 	return !cpumask_equal(cpumask, attrs->cpumask);
39144c16bd32STejun Heo 
39154c16bd32STejun Heo use_dfl:
39164c16bd32STejun Heo 	cpumask_copy(cpumask, attrs->cpumask);
39174c16bd32STejun Heo 	return false;
39184c16bd32STejun Heo }
39194c16bd32STejun Heo 
39201befcf30STejun Heo /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
39211befcf30STejun Heo static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
39221befcf30STejun Heo 						   int node,
39231befcf30STejun Heo 						   struct pool_workqueue *pwq)
39241befcf30STejun Heo {
39251befcf30STejun Heo 	struct pool_workqueue *old_pwq;
39261befcf30STejun Heo 
39275b95e1afSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
39281befcf30STejun Heo 	lockdep_assert_held(&wq->mutex);
39291befcf30STejun Heo 
39301befcf30STejun Heo 	/* link_pwq() can handle duplicate calls */
39311befcf30STejun Heo 	link_pwq(pwq);
39321befcf30STejun Heo 
39331befcf30STejun Heo 	old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
39341befcf30STejun Heo 	rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
39351befcf30STejun Heo 	return old_pwq;
39361befcf30STejun Heo }
39371befcf30STejun Heo 
39382d5f0764SLai Jiangshan /* context to store the prepared attrs & pwqs before applying */
39392d5f0764SLai Jiangshan struct apply_wqattrs_ctx {
39402d5f0764SLai Jiangshan 	struct workqueue_struct	*wq;		/* target workqueue */
39412d5f0764SLai Jiangshan 	struct workqueue_attrs	*attrs;		/* attrs to apply */
3942042f7df1SLai Jiangshan 	struct list_head	list;		/* queued for batching commit */
39432d5f0764SLai Jiangshan 	struct pool_workqueue	*dfl_pwq;
39442d5f0764SLai Jiangshan 	struct pool_workqueue	*pwq_tbl[];
39452d5f0764SLai Jiangshan };
39462d5f0764SLai Jiangshan 
39472d5f0764SLai Jiangshan /* free the resources after success or abort */
39482d5f0764SLai Jiangshan static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
39492d5f0764SLai Jiangshan {
39502d5f0764SLai Jiangshan 	if (ctx) {
39512d5f0764SLai Jiangshan 		int node;
39522d5f0764SLai Jiangshan 
39532d5f0764SLai Jiangshan 		for_each_node(node)
39542d5f0764SLai Jiangshan 			put_pwq_unlocked(ctx->pwq_tbl[node]);
39552d5f0764SLai Jiangshan 		put_pwq_unlocked(ctx->dfl_pwq);
39562d5f0764SLai Jiangshan 
39572d5f0764SLai Jiangshan 		free_workqueue_attrs(ctx->attrs);
39582d5f0764SLai Jiangshan 
39592d5f0764SLai Jiangshan 		kfree(ctx);
39602d5f0764SLai Jiangshan 	}
39612d5f0764SLai Jiangshan }
39622d5f0764SLai Jiangshan 
39632d5f0764SLai Jiangshan /* allocate the attrs and pwqs for later installation */
39642d5f0764SLai Jiangshan static struct apply_wqattrs_ctx *
39652d5f0764SLai Jiangshan apply_wqattrs_prepare(struct workqueue_struct *wq,
39662d5f0764SLai Jiangshan 		      const struct workqueue_attrs *attrs)
39672d5f0764SLai Jiangshan {
39682d5f0764SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
39692d5f0764SLai Jiangshan 	struct workqueue_attrs *new_attrs, *tmp_attrs;
39702d5f0764SLai Jiangshan 	int node;
39712d5f0764SLai Jiangshan 
39722d5f0764SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
39732d5f0764SLai Jiangshan 
3974acafe7e3SKees Cook 	ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_node_ids), GFP_KERNEL);
39752d5f0764SLai Jiangshan 
3976be69d00dSThomas Gleixner 	new_attrs = alloc_workqueue_attrs();
3977be69d00dSThomas Gleixner 	tmp_attrs = alloc_workqueue_attrs();
39782d5f0764SLai Jiangshan 	if (!ctx || !new_attrs || !tmp_attrs)
39792d5f0764SLai Jiangshan 		goto out_free;
39802d5f0764SLai Jiangshan 
3981042f7df1SLai Jiangshan 	/*
3982042f7df1SLai Jiangshan 	 * Calculate the attrs of the default pwq.
3983042f7df1SLai Jiangshan 	 * If the user configured cpumask doesn't overlap with the
3984042f7df1SLai Jiangshan 	 * wq_unbound_cpumask, we fallback to the wq_unbound_cpumask.
3985042f7df1SLai Jiangshan 	 */
39862d5f0764SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
3987b05a7928SFrederic Weisbecker 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, wq_unbound_cpumask);
3988042f7df1SLai Jiangshan 	if (unlikely(cpumask_empty(new_attrs->cpumask)))
3989042f7df1SLai Jiangshan 		cpumask_copy(new_attrs->cpumask, wq_unbound_cpumask);
39902d5f0764SLai Jiangshan 
39912d5f0764SLai Jiangshan 	/*
39922d5f0764SLai Jiangshan 	 * We may create multiple pwqs with differing cpumasks.  Make a
39932d5f0764SLai Jiangshan 	 * copy of @new_attrs which will be modified and used to obtain
39942d5f0764SLai Jiangshan 	 * pools.
39952d5f0764SLai Jiangshan 	 */
39962d5f0764SLai Jiangshan 	copy_workqueue_attrs(tmp_attrs, new_attrs);
39972d5f0764SLai Jiangshan 
39982d5f0764SLai Jiangshan 	/*
39992d5f0764SLai Jiangshan 	 * If something goes wrong during CPU up/down, we'll fall back to
40002d5f0764SLai Jiangshan 	 * the default pwq covering whole @attrs->cpumask.  Always create
40012d5f0764SLai Jiangshan 	 * it even if we don't use it immediately.
40022d5f0764SLai Jiangshan 	 */
40032d5f0764SLai Jiangshan 	ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
40042d5f0764SLai Jiangshan 	if (!ctx->dfl_pwq)
40052d5f0764SLai Jiangshan 		goto out_free;
40062d5f0764SLai Jiangshan 
40072d5f0764SLai Jiangshan 	for_each_node(node) {
4008042f7df1SLai Jiangshan 		if (wq_calc_node_cpumask(new_attrs, node, -1, tmp_attrs->cpumask)) {
40092d5f0764SLai Jiangshan 			ctx->pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
40102d5f0764SLai Jiangshan 			if (!ctx->pwq_tbl[node])
40112d5f0764SLai Jiangshan 				goto out_free;
40122d5f0764SLai Jiangshan 		} else {
40132d5f0764SLai Jiangshan 			ctx->dfl_pwq->refcnt++;
40142d5f0764SLai Jiangshan 			ctx->pwq_tbl[node] = ctx->dfl_pwq;
40152d5f0764SLai Jiangshan 		}
40162d5f0764SLai Jiangshan 	}
40172d5f0764SLai Jiangshan 
4018042f7df1SLai Jiangshan 	/* save the user configured attrs and sanitize it. */
4019042f7df1SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
4020042f7df1SLai Jiangshan 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
40212d5f0764SLai Jiangshan 	ctx->attrs = new_attrs;
4022042f7df1SLai Jiangshan 
40232d5f0764SLai Jiangshan 	ctx->wq = wq;
40242d5f0764SLai Jiangshan 	free_workqueue_attrs(tmp_attrs);
40252d5f0764SLai Jiangshan 	return ctx;
40262d5f0764SLai Jiangshan 
40272d5f0764SLai Jiangshan out_free:
40282d5f0764SLai Jiangshan 	free_workqueue_attrs(tmp_attrs);
40292d5f0764SLai Jiangshan 	free_workqueue_attrs(new_attrs);
40302d5f0764SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
40312d5f0764SLai Jiangshan 	return NULL;
40322d5f0764SLai Jiangshan }
40332d5f0764SLai Jiangshan 
40342d5f0764SLai Jiangshan /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
40352d5f0764SLai Jiangshan static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
40362d5f0764SLai Jiangshan {
40372d5f0764SLai Jiangshan 	int node;
40382d5f0764SLai Jiangshan 
40392d5f0764SLai Jiangshan 	/* all pwqs have been created successfully, let's install'em */
40402d5f0764SLai Jiangshan 	mutex_lock(&ctx->wq->mutex);
40412d5f0764SLai Jiangshan 
40422d5f0764SLai Jiangshan 	copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
40432d5f0764SLai Jiangshan 
40442d5f0764SLai Jiangshan 	/* save the previous pwq and install the new one */
40452d5f0764SLai Jiangshan 	for_each_node(node)
40462d5f0764SLai Jiangshan 		ctx->pwq_tbl[node] = numa_pwq_tbl_install(ctx->wq, node,
40472d5f0764SLai Jiangshan 							  ctx->pwq_tbl[node]);
40482d5f0764SLai Jiangshan 
40492d5f0764SLai Jiangshan 	/* @dfl_pwq might not have been used, ensure it's linked */
40502d5f0764SLai Jiangshan 	link_pwq(ctx->dfl_pwq);
40512d5f0764SLai Jiangshan 	swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
40522d5f0764SLai Jiangshan 
40532d5f0764SLai Jiangshan 	mutex_unlock(&ctx->wq->mutex);
40542d5f0764SLai Jiangshan }
40552d5f0764SLai Jiangshan 
4056a0111cf6SLai Jiangshan static void apply_wqattrs_lock(void)
4057a0111cf6SLai Jiangshan {
4058a0111cf6SLai Jiangshan 	/* CPUs should stay stable across pwq creations and installations */
4059ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
4060a0111cf6SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4061a0111cf6SLai Jiangshan }
4062a0111cf6SLai Jiangshan 
4063a0111cf6SLai Jiangshan static void apply_wqattrs_unlock(void)
4064a0111cf6SLai Jiangshan {
4065a0111cf6SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
4066ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
4067a0111cf6SLai Jiangshan }
4068a0111cf6SLai Jiangshan 
4069a0111cf6SLai Jiangshan static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
4070a0111cf6SLai Jiangshan 					const struct workqueue_attrs *attrs)
4071a0111cf6SLai Jiangshan {
4072a0111cf6SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
4073a0111cf6SLai Jiangshan 
4074a0111cf6SLai Jiangshan 	/* only unbound workqueues can change attributes */
4075a0111cf6SLai Jiangshan 	if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
4076a0111cf6SLai Jiangshan 		return -EINVAL;
4077a0111cf6SLai Jiangshan 
4078a0111cf6SLai Jiangshan 	/* creating multiple pwqs breaks ordering guarantee */
40790a94efb5STejun Heo 	if (!list_empty(&wq->pwqs)) {
40800a94efb5STejun Heo 		if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
4081a0111cf6SLai Jiangshan 			return -EINVAL;
4082a0111cf6SLai Jiangshan 
40830a94efb5STejun Heo 		wq->flags &= ~__WQ_ORDERED;
40840a94efb5STejun Heo 	}
40850a94efb5STejun Heo 
4086a0111cf6SLai Jiangshan 	ctx = apply_wqattrs_prepare(wq, attrs);
40876201171eSwanghaibin 	if (!ctx)
40886201171eSwanghaibin 		return -ENOMEM;
4089a0111cf6SLai Jiangshan 
4090a0111cf6SLai Jiangshan 	/* the ctx has been prepared successfully, let's commit it */
4091a0111cf6SLai Jiangshan 	apply_wqattrs_commit(ctx);
4092a0111cf6SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
4093a0111cf6SLai Jiangshan 
40946201171eSwanghaibin 	return 0;
4095a0111cf6SLai Jiangshan }
4096a0111cf6SLai Jiangshan 
40979e8cd2f5STejun Heo /**
40989e8cd2f5STejun Heo  * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
40999e8cd2f5STejun Heo  * @wq: the target workqueue
41009e8cd2f5STejun Heo  * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
41019e8cd2f5STejun Heo  *
41024c16bd32STejun Heo  * Apply @attrs to an unbound workqueue @wq.  Unless disabled, on NUMA
41034c16bd32STejun Heo  * machines, this function maps a separate pwq to each NUMA node with
41044c16bd32STejun Heo  * possibles CPUs in @attrs->cpumask so that work items are affine to the
41054c16bd32STejun Heo  * NUMA node it was issued on.  Older pwqs are released as in-flight work
41064c16bd32STejun Heo  * items finish.  Note that a work item which repeatedly requeues itself
41074c16bd32STejun Heo  * back-to-back will stay on its current pwq.
41089e8cd2f5STejun Heo  *
4109d185af30SYacine Belkadi  * Performs GFP_KERNEL allocations.
4110d185af30SYacine Belkadi  *
4111ffd8bea8SSebastian Andrzej Siewior  * Assumes caller has CPU hotplug read exclusion, i.e. cpus_read_lock().
4112509b3204SDaniel Jordan  *
4113d185af30SYacine Belkadi  * Return: 0 on success and -errno on failure.
41149e8cd2f5STejun Heo  */
4115513c98d0SDaniel Jordan int apply_workqueue_attrs(struct workqueue_struct *wq,
41169e8cd2f5STejun Heo 			  const struct workqueue_attrs *attrs)
41179e8cd2f5STejun Heo {
4118a0111cf6SLai Jiangshan 	int ret;
41199e8cd2f5STejun Heo 
4120509b3204SDaniel Jordan 	lockdep_assert_cpus_held();
4121509b3204SDaniel Jordan 
4122509b3204SDaniel Jordan 	mutex_lock(&wq_pool_mutex);
4123a0111cf6SLai Jiangshan 	ret = apply_workqueue_attrs_locked(wq, attrs);
4124509b3204SDaniel Jordan 	mutex_unlock(&wq_pool_mutex);
41252d5f0764SLai Jiangshan 
41262d5f0764SLai Jiangshan 	return ret;
41279e8cd2f5STejun Heo }
41289e8cd2f5STejun Heo 
41294c16bd32STejun Heo /**
41304c16bd32STejun Heo  * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
41314c16bd32STejun Heo  * @wq: the target workqueue
41324c16bd32STejun Heo  * @cpu: the CPU coming up or going down
41334c16bd32STejun Heo  * @online: whether @cpu is coming up or going down
41344c16bd32STejun Heo  *
41354c16bd32STejun Heo  * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
41364c16bd32STejun Heo  * %CPU_DOWN_FAILED.  @cpu is being hot[un]plugged, update NUMA affinity of
41374c16bd32STejun Heo  * @wq accordingly.
41384c16bd32STejun Heo  *
41394c16bd32STejun Heo  * If NUMA affinity can't be adjusted due to memory allocation failure, it
41404c16bd32STejun Heo  * falls back to @wq->dfl_pwq which may not be optimal but is always
41414c16bd32STejun Heo  * correct.
41424c16bd32STejun Heo  *
41434c16bd32STejun Heo  * Note that when the last allowed CPU of a NUMA node goes offline for a
41444c16bd32STejun Heo  * workqueue with a cpumask spanning multiple nodes, the workers which were
41454c16bd32STejun Heo  * already executing the work items for the workqueue will lose their CPU
41464c16bd32STejun Heo  * affinity and may execute on any CPU.  This is similar to how per-cpu
41474c16bd32STejun Heo  * workqueues behave on CPU_DOWN.  If a workqueue user wants strict
41484c16bd32STejun Heo  * affinity, it's the user's responsibility to flush the work item from
41494c16bd32STejun Heo  * CPU_DOWN_PREPARE.
41504c16bd32STejun Heo  */
41514c16bd32STejun Heo static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
41524c16bd32STejun Heo 				   bool online)
41534c16bd32STejun Heo {
41544c16bd32STejun Heo 	int node = cpu_to_node(cpu);
41554c16bd32STejun Heo 	int cpu_off = online ? -1 : cpu;
41564c16bd32STejun Heo 	struct pool_workqueue *old_pwq = NULL, *pwq;
41574c16bd32STejun Heo 	struct workqueue_attrs *target_attrs;
41584c16bd32STejun Heo 	cpumask_t *cpumask;
41594c16bd32STejun Heo 
41604c16bd32STejun Heo 	lockdep_assert_held(&wq_pool_mutex);
41614c16bd32STejun Heo 
4162f7142ed4SLai Jiangshan 	if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND) ||
4163f7142ed4SLai Jiangshan 	    wq->unbound_attrs->no_numa)
41644c16bd32STejun Heo 		return;
41654c16bd32STejun Heo 
41664c16bd32STejun Heo 	/*
41674c16bd32STejun Heo 	 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
41684c16bd32STejun Heo 	 * Let's use a preallocated one.  The following buf is protected by
41694c16bd32STejun Heo 	 * CPU hotplug exclusion.
41704c16bd32STejun Heo 	 */
41714c16bd32STejun Heo 	target_attrs = wq_update_unbound_numa_attrs_buf;
41724c16bd32STejun Heo 	cpumask = target_attrs->cpumask;
41734c16bd32STejun Heo 
41744c16bd32STejun Heo 	copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
41754c16bd32STejun Heo 	pwq = unbound_pwq_by_node(wq, node);
41764c16bd32STejun Heo 
41774c16bd32STejun Heo 	/*
41784c16bd32STejun Heo 	 * Let's determine what needs to be done.  If the target cpumask is
4179042f7df1SLai Jiangshan 	 * different from the default pwq's, we need to compare it to @pwq's
4180042f7df1SLai Jiangshan 	 * and create a new one if they don't match.  If the target cpumask
4181042f7df1SLai Jiangshan 	 * equals the default pwq's, the default pwq should be used.
41824c16bd32STejun Heo 	 */
4183042f7df1SLai Jiangshan 	if (wq_calc_node_cpumask(wq->dfl_pwq->pool->attrs, node, cpu_off, cpumask)) {
41844c16bd32STejun Heo 		if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
4185f7142ed4SLai Jiangshan 			return;
41864c16bd32STejun Heo 	} else {
41874c16bd32STejun Heo 		goto use_dfl_pwq;
41884c16bd32STejun Heo 	}
41894c16bd32STejun Heo 
41904c16bd32STejun Heo 	/* create a new pwq */
41914c16bd32STejun Heo 	pwq = alloc_unbound_pwq(wq, target_attrs);
41924c16bd32STejun Heo 	if (!pwq) {
41932d916033SFabian Frederick 		pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
41944c16bd32STejun Heo 			wq->name);
419577f300b1SDaeseok Youn 		goto use_dfl_pwq;
41964c16bd32STejun Heo 	}
41974c16bd32STejun Heo 
4198f7142ed4SLai Jiangshan 	/* Install the new pwq. */
41994c16bd32STejun Heo 	mutex_lock(&wq->mutex);
42004c16bd32STejun Heo 	old_pwq = numa_pwq_tbl_install(wq, node, pwq);
42014c16bd32STejun Heo 	goto out_unlock;
42024c16bd32STejun Heo 
42034c16bd32STejun Heo use_dfl_pwq:
4204f7142ed4SLai Jiangshan 	mutex_lock(&wq->mutex);
4205a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&wq->dfl_pwq->pool->lock);
42064c16bd32STejun Heo 	get_pwq(wq->dfl_pwq);
4207a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&wq->dfl_pwq->pool->lock);
42084c16bd32STejun Heo 	old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
42094c16bd32STejun Heo out_unlock:
42104c16bd32STejun Heo 	mutex_unlock(&wq->mutex);
42114c16bd32STejun Heo 	put_pwq_unlocked(old_pwq);
42124c16bd32STejun Heo }
42134c16bd32STejun Heo 
421430cdf249STejun Heo static int alloc_and_link_pwqs(struct workqueue_struct *wq)
42151da177e4SLinus Torvalds {
421649e3cf44STejun Heo 	bool highpri = wq->flags & WQ_HIGHPRI;
42178a2b7538STejun Heo 	int cpu, ret;
4218e1d8aa9fSFrederic Weisbecker 
421930cdf249STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
4220420c0ddbSTejun Heo 		wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
4221420c0ddbSTejun Heo 		if (!wq->cpu_pwqs)
422230cdf249STejun Heo 			return -ENOMEM;
422330cdf249STejun Heo 
422430cdf249STejun Heo 		for_each_possible_cpu(cpu) {
42257fb98ea7STejun Heo 			struct pool_workqueue *pwq =
42267fb98ea7STejun Heo 				per_cpu_ptr(wq->cpu_pwqs, cpu);
42277a62c2c8STejun Heo 			struct worker_pool *cpu_pools =
4228f02ae73aSTejun Heo 				per_cpu(cpu_worker_pools, cpu);
422930cdf249STejun Heo 
4230f147f29eSTejun Heo 			init_pwq(pwq, wq, &cpu_pools[highpri]);
4231f147f29eSTejun Heo 
4232f147f29eSTejun Heo 			mutex_lock(&wq->mutex);
42331befcf30STejun Heo 			link_pwq(pwq);
4234f147f29eSTejun Heo 			mutex_unlock(&wq->mutex);
423530cdf249STejun Heo 		}
423630cdf249STejun Heo 		return 0;
4237509b3204SDaniel Jordan 	}
4238509b3204SDaniel Jordan 
4239ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
4240509b3204SDaniel Jordan 	if (wq->flags & __WQ_ORDERED) {
42418a2b7538STejun Heo 		ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
42428a2b7538STejun Heo 		/* there should only be single pwq for ordering guarantee */
42438a2b7538STejun Heo 		WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
42448a2b7538STejun Heo 			      wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
42458a2b7538STejun Heo 		     "ordering guarantee broken for workqueue %s\n", wq->name);
42469e8cd2f5STejun Heo 	} else {
4247509b3204SDaniel Jordan 		ret = apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
42489e8cd2f5STejun Heo 	}
4249ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
4250509b3204SDaniel Jordan 
4251509b3204SDaniel Jordan 	return ret;
42520f900049STejun Heo }
42530f900049STejun Heo 
4254f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
4255f3421797STejun Heo 			       const char *name)
4256b71ab8c2STejun Heo {
4257f3421797STejun Heo 	int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
4258f3421797STejun Heo 
4259f3421797STejun Heo 	if (max_active < 1 || max_active > lim)
4260044c782cSValentin Ilie 		pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
4261f3421797STejun Heo 			max_active, name, 1, lim);
4262b71ab8c2STejun Heo 
4263f3421797STejun Heo 	return clamp_val(max_active, 1, lim);
4264b71ab8c2STejun Heo }
4265b71ab8c2STejun Heo 
4266983c7515STejun Heo /*
4267983c7515STejun Heo  * Workqueues which may be used during memory reclaim should have a rescuer
4268983c7515STejun Heo  * to guarantee forward progress.
4269983c7515STejun Heo  */
4270983c7515STejun Heo static int init_rescuer(struct workqueue_struct *wq)
4271983c7515STejun Heo {
4272983c7515STejun Heo 	struct worker *rescuer;
4273b92b36eaSDan Carpenter 	int ret;
4274983c7515STejun Heo 
4275983c7515STejun Heo 	if (!(wq->flags & WQ_MEM_RECLAIM))
4276983c7515STejun Heo 		return 0;
4277983c7515STejun Heo 
4278983c7515STejun Heo 	rescuer = alloc_worker(NUMA_NO_NODE);
4279983c7515STejun Heo 	if (!rescuer)
4280983c7515STejun Heo 		return -ENOMEM;
4281983c7515STejun Heo 
4282983c7515STejun Heo 	rescuer->rescue_wq = wq;
4283983c7515STejun Heo 	rescuer->task = kthread_create(rescuer_thread, rescuer, "%s", wq->name);
4284f187b697SSean Fu 	if (IS_ERR(rescuer->task)) {
4285b92b36eaSDan Carpenter 		ret = PTR_ERR(rescuer->task);
4286983c7515STejun Heo 		kfree(rescuer);
4287b92b36eaSDan Carpenter 		return ret;
4288983c7515STejun Heo 	}
4289983c7515STejun Heo 
4290983c7515STejun Heo 	wq->rescuer = rescuer;
4291983c7515STejun Heo 	kthread_bind_mask(rescuer->task, cpu_possible_mask);
4292983c7515STejun Heo 	wake_up_process(rescuer->task);
4293983c7515STejun Heo 
4294983c7515STejun Heo 	return 0;
4295983c7515STejun Heo }
4296983c7515STejun Heo 
4297a2775bbcSMathieu Malaterre __printf(1, 4)
4298669de8bdSBart Van Assche struct workqueue_struct *alloc_workqueue(const char *fmt,
429997e37d7bSTejun Heo 					 unsigned int flags,
4300669de8bdSBart Van Assche 					 int max_active, ...)
43013af24433SOleg Nesterov {
4302df2d5ae4STejun Heo 	size_t tbl_size = 0;
4303ecf6881fSTejun Heo 	va_list args;
43043af24433SOleg Nesterov 	struct workqueue_struct *wq;
430549e3cf44STejun Heo 	struct pool_workqueue *pwq;
4306b196be89STejun Heo 
43075c0338c6STejun Heo 	/*
43085c0338c6STejun Heo 	 * Unbound && max_active == 1 used to imply ordered, which is no
43095c0338c6STejun Heo 	 * longer the case on NUMA machines due to per-node pools.  While
43105c0338c6STejun Heo 	 * alloc_ordered_workqueue() is the right way to create an ordered
43115c0338c6STejun Heo 	 * workqueue, keep the previous behavior to avoid subtle breakages
43125c0338c6STejun Heo 	 * on NUMA.
43135c0338c6STejun Heo 	 */
43145c0338c6STejun Heo 	if ((flags & WQ_UNBOUND) && max_active == 1)
43155c0338c6STejun Heo 		flags |= __WQ_ORDERED;
43165c0338c6STejun Heo 
4317cee22a15SViresh Kumar 	/* see the comment above the definition of WQ_POWER_EFFICIENT */
4318cee22a15SViresh Kumar 	if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
4319cee22a15SViresh Kumar 		flags |= WQ_UNBOUND;
4320cee22a15SViresh Kumar 
4321ecf6881fSTejun Heo 	/* allocate wq and format name */
4322df2d5ae4STejun Heo 	if (flags & WQ_UNBOUND)
4323ddcb57e2SLai Jiangshan 		tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
4324df2d5ae4STejun Heo 
4325df2d5ae4STejun Heo 	wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
4326b196be89STejun Heo 	if (!wq)
4327d2c1d404STejun Heo 		return NULL;
4328b196be89STejun Heo 
43296029a918STejun Heo 	if (flags & WQ_UNBOUND) {
4330be69d00dSThomas Gleixner 		wq->unbound_attrs = alloc_workqueue_attrs();
43316029a918STejun Heo 		if (!wq->unbound_attrs)
43326029a918STejun Heo 			goto err_free_wq;
43336029a918STejun Heo 	}
43346029a918STejun Heo 
4335669de8bdSBart Van Assche 	va_start(args, max_active);
4336ecf6881fSTejun Heo 	vsnprintf(wq->name, sizeof(wq->name), fmt, args);
4337b196be89STejun Heo 	va_end(args);
43383af24433SOleg Nesterov 
4339d320c038STejun Heo 	max_active = max_active ?: WQ_DFL_ACTIVE;
4340b196be89STejun Heo 	max_active = wq_clamp_max_active(max_active, flags, wq->name);
43413af24433SOleg Nesterov 
4342b196be89STejun Heo 	/* init wq */
434397e37d7bSTejun Heo 	wq->flags = flags;
4344a0a1a5fdSTejun Heo 	wq->saved_max_active = max_active;
43453c25a55dSLai Jiangshan 	mutex_init(&wq->mutex);
4346112202d9STejun Heo 	atomic_set(&wq->nr_pwqs_to_flush, 0);
434730cdf249STejun Heo 	INIT_LIST_HEAD(&wq->pwqs);
434873f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
434973f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
4350493a1724STejun Heo 	INIT_LIST_HEAD(&wq->maydays);
43513af24433SOleg Nesterov 
4352669de8bdSBart Van Assche 	wq_init_lockdep(wq);
4353cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
43543af24433SOleg Nesterov 
435530cdf249STejun Heo 	if (alloc_and_link_pwqs(wq) < 0)
435682efcab3SBart Van Assche 		goto err_unreg_lockdep;
43571537663fSTejun Heo 
435840c17f75STejun Heo 	if (wq_online && init_rescuer(wq) < 0)
4359d2c1d404STejun Heo 		goto err_destroy;
4360e22bee78STejun Heo 
4361226223abSTejun Heo 	if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
4362226223abSTejun Heo 		goto err_destroy;
4363226223abSTejun Heo 
43646af8bf3dSOleg Nesterov 	/*
436568e13a67SLai Jiangshan 	 * wq_pool_mutex protects global freeze state and workqueues list.
436668e13a67SLai Jiangshan 	 * Grab it, adjust max_active and add the new @wq to workqueues
436768e13a67SLai Jiangshan 	 * list.
43686af8bf3dSOleg Nesterov 	 */
436968e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4370a0a1a5fdSTejun Heo 
4371a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
437249e3cf44STejun Heo 	for_each_pwq(pwq, wq)
4373699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4374a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4375a0a1a5fdSTejun Heo 
4376e2dca7adSTejun Heo 	list_add_tail_rcu(&wq->list, &workqueues);
4377a0a1a5fdSTejun Heo 
437868e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
43793af24433SOleg Nesterov 
43803af24433SOleg Nesterov 	return wq;
4381d2c1d404STejun Heo 
438282efcab3SBart Van Assche err_unreg_lockdep:
4383009bb421SBart Van Assche 	wq_unregister_lockdep(wq);
4384009bb421SBart Van Assche 	wq_free_lockdep(wq);
438582efcab3SBart Van Assche err_free_wq:
43866029a918STejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
43874690c4abSTejun Heo 	kfree(wq);
4388d2c1d404STejun Heo 	return NULL;
4389d2c1d404STejun Heo err_destroy:
4390d2c1d404STejun Heo 	destroy_workqueue(wq);
43914690c4abSTejun Heo 	return NULL;
43921da177e4SLinus Torvalds }
4393669de8bdSBart Van Assche EXPORT_SYMBOL_GPL(alloc_workqueue);
43941da177e4SLinus Torvalds 
4395c29eb853STejun Heo static bool pwq_busy(struct pool_workqueue *pwq)
4396c29eb853STejun Heo {
4397c29eb853STejun Heo 	int i;
4398c29eb853STejun Heo 
4399c29eb853STejun Heo 	for (i = 0; i < WORK_NR_COLORS; i++)
4400c29eb853STejun Heo 		if (pwq->nr_in_flight[i])
4401c29eb853STejun Heo 			return true;
4402c29eb853STejun Heo 
4403c29eb853STejun Heo 	if ((pwq != pwq->wq->dfl_pwq) && (pwq->refcnt > 1))
4404c29eb853STejun Heo 		return true;
4405f97a4a1aSLai Jiangshan 	if (pwq->nr_active || !list_empty(&pwq->inactive_works))
4406c29eb853STejun Heo 		return true;
4407c29eb853STejun Heo 
4408c29eb853STejun Heo 	return false;
4409c29eb853STejun Heo }
4410c29eb853STejun Heo 
44113af24433SOleg Nesterov /**
44123af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
44133af24433SOleg Nesterov  * @wq: target workqueue
44143af24433SOleg Nesterov  *
44153af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
44163af24433SOleg Nesterov  */
44173af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
44183af24433SOleg Nesterov {
441949e3cf44STejun Heo 	struct pool_workqueue *pwq;
44204c16bd32STejun Heo 	int node;
44213af24433SOleg Nesterov 
4422def98c84STejun Heo 	/*
4423def98c84STejun Heo 	 * Remove it from sysfs first so that sanity check failure doesn't
4424def98c84STejun Heo 	 * lead to sysfs name conflicts.
4425def98c84STejun Heo 	 */
4426def98c84STejun Heo 	workqueue_sysfs_unregister(wq);
4427def98c84STejun Heo 
44289c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
44299c5a2ba7STejun Heo 	drain_workqueue(wq);
4430c8efcc25STejun Heo 
4431def98c84STejun Heo 	/* kill rescuer, if sanity checks fail, leave it w/o rescuer */
4432def98c84STejun Heo 	if (wq->rescuer) {
4433def98c84STejun Heo 		struct worker *rescuer = wq->rescuer;
4434def98c84STejun Heo 
4435def98c84STejun Heo 		/* this prevents new queueing */
4436a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&wq_mayday_lock);
4437def98c84STejun Heo 		wq->rescuer = NULL;
4438a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&wq_mayday_lock);
4439def98c84STejun Heo 
4440def98c84STejun Heo 		/* rescuer will empty maydays list before exiting */
4441def98c84STejun Heo 		kthread_stop(rescuer->task);
44428efe1223STejun Heo 		kfree(rescuer);
4443def98c84STejun Heo 	}
4444def98c84STejun Heo 
4445c29eb853STejun Heo 	/*
4446c29eb853STejun Heo 	 * Sanity checks - grab all the locks so that we wait for all
4447c29eb853STejun Heo 	 * in-flight operations which may do put_pwq().
4448c29eb853STejun Heo 	 */
4449c29eb853STejun Heo 	mutex_lock(&wq_pool_mutex);
4450b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
445149e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
4452a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
4453c29eb853STejun Heo 		if (WARN_ON(pwq_busy(pwq))) {
44541d9a6159SKefeng Wang 			pr_warn("%s: %s has the following busy pwq\n",
4455e66b39afSTejun Heo 				__func__, wq->name);
4456c29eb853STejun Heo 			show_pwq(pwq);
4457a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&pwq->pool->lock);
4458b09f4fd3SLai Jiangshan 			mutex_unlock(&wq->mutex);
4459c29eb853STejun Heo 			mutex_unlock(&wq_pool_mutex);
446055df0933SImran Khan 			show_one_workqueue(wq);
44616183c009STejun Heo 			return;
446276af4d93STejun Heo 		}
4463a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
446476af4d93STejun Heo 	}
4465b09f4fd3SLai Jiangshan 	mutex_unlock(&wq->mutex);
44666183c009STejun Heo 
4467a0a1a5fdSTejun Heo 	/*
4468a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
4469a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
4470a0a1a5fdSTejun Heo 	 */
4471e2dca7adSTejun Heo 	list_del_rcu(&wq->list);
447268e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
44733af24433SOleg Nesterov 
44748864b4e5STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
4475669de8bdSBart Van Assche 		wq_unregister_lockdep(wq);
447629c91e99STejun Heo 		/*
44778864b4e5STejun Heo 		 * The base ref is never dropped on per-cpu pwqs.  Directly
4478e2dca7adSTejun Heo 		 * schedule RCU free.
447929c91e99STejun Heo 		 */
448025b00775SPaul E. McKenney 		call_rcu(&wq->rcu, rcu_free_wq);
44818864b4e5STejun Heo 	} else {
44828864b4e5STejun Heo 		/*
44838864b4e5STejun Heo 		 * We're the sole accessor of @wq at this point.  Directly
44844c16bd32STejun Heo 		 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
44854c16bd32STejun Heo 		 * @wq will be freed when the last pwq is released.
44868864b4e5STejun Heo 		 */
44874c16bd32STejun Heo 		for_each_node(node) {
44884c16bd32STejun Heo 			pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
44894c16bd32STejun Heo 			RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
44904c16bd32STejun Heo 			put_pwq_unlocked(pwq);
44914c16bd32STejun Heo 		}
44924c16bd32STejun Heo 
44934c16bd32STejun Heo 		/*
44944c16bd32STejun Heo 		 * Put dfl_pwq.  @wq may be freed any time after dfl_pwq is
44954c16bd32STejun Heo 		 * put.  Don't access it afterwards.
44964c16bd32STejun Heo 		 */
44974c16bd32STejun Heo 		pwq = wq->dfl_pwq;
44984c16bd32STejun Heo 		wq->dfl_pwq = NULL;
4499dce90d47STejun Heo 		put_pwq_unlocked(pwq);
450029c91e99STejun Heo 	}
45013af24433SOleg Nesterov }
45023af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
45033af24433SOleg Nesterov 
4504dcd989cbSTejun Heo /**
4505dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
4506dcd989cbSTejun Heo  * @wq: target workqueue
4507dcd989cbSTejun Heo  * @max_active: new max_active value.
4508dcd989cbSTejun Heo  *
4509dcd989cbSTejun Heo  * Set max_active of @wq to @max_active.
4510dcd989cbSTejun Heo  *
4511dcd989cbSTejun Heo  * CONTEXT:
4512dcd989cbSTejun Heo  * Don't call from IRQ context.
4513dcd989cbSTejun Heo  */
4514dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4515dcd989cbSTejun Heo {
451649e3cf44STejun Heo 	struct pool_workqueue *pwq;
4517dcd989cbSTejun Heo 
45188719dceaSTejun Heo 	/* disallow meddling with max_active for ordered workqueues */
45190a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
45208719dceaSTejun Heo 		return;
45218719dceaSTejun Heo 
4522f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4523dcd989cbSTejun Heo 
4524a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
4525dcd989cbSTejun Heo 
45260a94efb5STejun Heo 	wq->flags &= ~__WQ_ORDERED;
4527dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
4528dcd989cbSTejun Heo 
4529699ce097STejun Heo 	for_each_pwq(pwq, wq)
4530699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4531dcd989cbSTejun Heo 
4532a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4533dcd989cbSTejun Heo }
4534dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4535dcd989cbSTejun Heo 
4536dcd989cbSTejun Heo /**
453727d4ee03SLukas Wunner  * current_work - retrieve %current task's work struct
453827d4ee03SLukas Wunner  *
453927d4ee03SLukas Wunner  * Determine if %current task is a workqueue worker and what it's working on.
454027d4ee03SLukas Wunner  * Useful to find out the context that the %current task is running in.
454127d4ee03SLukas Wunner  *
454227d4ee03SLukas Wunner  * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
454327d4ee03SLukas Wunner  */
454427d4ee03SLukas Wunner struct work_struct *current_work(void)
454527d4ee03SLukas Wunner {
454627d4ee03SLukas Wunner 	struct worker *worker = current_wq_worker();
454727d4ee03SLukas Wunner 
454827d4ee03SLukas Wunner 	return worker ? worker->current_work : NULL;
454927d4ee03SLukas Wunner }
455027d4ee03SLukas Wunner EXPORT_SYMBOL(current_work);
455127d4ee03SLukas Wunner 
455227d4ee03SLukas Wunner /**
4553e6267616STejun Heo  * current_is_workqueue_rescuer - is %current workqueue rescuer?
4554e6267616STejun Heo  *
4555e6267616STejun Heo  * Determine whether %current is a workqueue rescuer.  Can be used from
4556e6267616STejun Heo  * work functions to determine whether it's being run off the rescuer task.
4557d185af30SYacine Belkadi  *
4558d185af30SYacine Belkadi  * Return: %true if %current is a workqueue rescuer. %false otherwise.
4559e6267616STejun Heo  */
4560e6267616STejun Heo bool current_is_workqueue_rescuer(void)
4561e6267616STejun Heo {
4562e6267616STejun Heo 	struct worker *worker = current_wq_worker();
4563e6267616STejun Heo 
45646a092dfdSLai Jiangshan 	return worker && worker->rescue_wq;
4565e6267616STejun Heo }
4566e6267616STejun Heo 
4567e6267616STejun Heo /**
4568dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
4569dcd989cbSTejun Heo  * @cpu: CPU in question
4570dcd989cbSTejun Heo  * @wq: target workqueue
4571dcd989cbSTejun Heo  *
4572dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
4573dcd989cbSTejun Heo  * no synchronization around this function and the test result is
4574dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4575dcd989cbSTejun Heo  *
4576d3251859STejun Heo  * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4577d3251859STejun Heo  * Note that both per-cpu and unbound workqueues may be associated with
4578d3251859STejun Heo  * multiple pool_workqueues which have separate congested states.  A
4579d3251859STejun Heo  * workqueue being congested on one CPU doesn't mean the workqueue is also
4580d3251859STejun Heo  * contested on other CPUs / NUMA nodes.
4581d3251859STejun Heo  *
4582d185af30SYacine Belkadi  * Return:
4583dcd989cbSTejun Heo  * %true if congested, %false otherwise.
4584dcd989cbSTejun Heo  */
4585d84ff051STejun Heo bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4586dcd989cbSTejun Heo {
45877fb98ea7STejun Heo 	struct pool_workqueue *pwq;
458876af4d93STejun Heo 	bool ret;
458976af4d93STejun Heo 
459024acfb71SThomas Gleixner 	rcu_read_lock();
459124acfb71SThomas Gleixner 	preempt_disable();
45927fb98ea7STejun Heo 
4593d3251859STejun Heo 	if (cpu == WORK_CPU_UNBOUND)
4594d3251859STejun Heo 		cpu = smp_processor_id();
4595d3251859STejun Heo 
45967fb98ea7STejun Heo 	if (!(wq->flags & WQ_UNBOUND))
45977fb98ea7STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
45987fb98ea7STejun Heo 	else
4599df2d5ae4STejun Heo 		pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4600dcd989cbSTejun Heo 
4601f97a4a1aSLai Jiangshan 	ret = !list_empty(&pwq->inactive_works);
460224acfb71SThomas Gleixner 	preempt_enable();
460324acfb71SThomas Gleixner 	rcu_read_unlock();
460476af4d93STejun Heo 
460576af4d93STejun Heo 	return ret;
4606dcd989cbSTejun Heo }
4607dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
4608dcd989cbSTejun Heo 
4609dcd989cbSTejun Heo /**
4610dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
4611dcd989cbSTejun Heo  * @work: the work to be tested
4612dcd989cbSTejun Heo  *
4613dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
4614dcd989cbSTejun Heo  * synchronization around this function and the test result is
4615dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4616dcd989cbSTejun Heo  *
4617d185af30SYacine Belkadi  * Return:
4618dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
4619dcd989cbSTejun Heo  */
4620dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
4621dcd989cbSTejun Heo {
4622fa1b54e6STejun Heo 	struct worker_pool *pool;
4623dcd989cbSTejun Heo 	unsigned long flags;
4624dcd989cbSTejun Heo 	unsigned int ret = 0;
4625dcd989cbSTejun Heo 
4626dcd989cbSTejun Heo 	if (work_pending(work))
4627dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
4628038366c5SLai Jiangshan 
462924acfb71SThomas Gleixner 	rcu_read_lock();
4630fa1b54e6STejun Heo 	pool = get_work_pool(work);
4631038366c5SLai Jiangshan 	if (pool) {
4632a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irqsave(&pool->lock, flags);
4633c9e7cf27STejun Heo 		if (find_worker_executing_work(pool, work))
4634dcd989cbSTejun Heo 			ret |= WORK_BUSY_RUNNING;
4635a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&pool->lock, flags);
4636038366c5SLai Jiangshan 	}
463724acfb71SThomas Gleixner 	rcu_read_unlock();
4638dcd989cbSTejun Heo 
4639dcd989cbSTejun Heo 	return ret;
4640dcd989cbSTejun Heo }
4641dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
4642dcd989cbSTejun Heo 
46433d1cb205STejun Heo /**
46443d1cb205STejun Heo  * set_worker_desc - set description for the current work item
46453d1cb205STejun Heo  * @fmt: printf-style format string
46463d1cb205STejun Heo  * @...: arguments for the format string
46473d1cb205STejun Heo  *
46483d1cb205STejun Heo  * This function can be called by a running work function to describe what
46493d1cb205STejun Heo  * the work item is about.  If the worker task gets dumped, this
46503d1cb205STejun Heo  * information will be printed out together to help debugging.  The
46513d1cb205STejun Heo  * description can be at most WORKER_DESC_LEN including the trailing '\0'.
46523d1cb205STejun Heo  */
46533d1cb205STejun Heo void set_worker_desc(const char *fmt, ...)
46543d1cb205STejun Heo {
46553d1cb205STejun Heo 	struct worker *worker = current_wq_worker();
46563d1cb205STejun Heo 	va_list args;
46573d1cb205STejun Heo 
46583d1cb205STejun Heo 	if (worker) {
46593d1cb205STejun Heo 		va_start(args, fmt);
46603d1cb205STejun Heo 		vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
46613d1cb205STejun Heo 		va_end(args);
46623d1cb205STejun Heo 	}
46633d1cb205STejun Heo }
46645c750d58SSteffen Maier EXPORT_SYMBOL_GPL(set_worker_desc);
46653d1cb205STejun Heo 
46663d1cb205STejun Heo /**
46673d1cb205STejun Heo  * print_worker_info - print out worker information and description
46683d1cb205STejun Heo  * @log_lvl: the log level to use when printing
46693d1cb205STejun Heo  * @task: target task
46703d1cb205STejun Heo  *
46713d1cb205STejun Heo  * If @task is a worker and currently executing a work item, print out the
46723d1cb205STejun Heo  * name of the workqueue being serviced and worker description set with
46733d1cb205STejun Heo  * set_worker_desc() by the currently executing work item.
46743d1cb205STejun Heo  *
46753d1cb205STejun Heo  * This function can be safely called on any task as long as the
46763d1cb205STejun Heo  * task_struct itself is accessible.  While safe, this function isn't
46773d1cb205STejun Heo  * synchronized and may print out mixups or garbages of limited length.
46783d1cb205STejun Heo  */
46793d1cb205STejun Heo void print_worker_info(const char *log_lvl, struct task_struct *task)
46803d1cb205STejun Heo {
46813d1cb205STejun Heo 	work_func_t *fn = NULL;
46823d1cb205STejun Heo 	char name[WQ_NAME_LEN] = { };
46833d1cb205STejun Heo 	char desc[WORKER_DESC_LEN] = { };
46843d1cb205STejun Heo 	struct pool_workqueue *pwq = NULL;
46853d1cb205STejun Heo 	struct workqueue_struct *wq = NULL;
46863d1cb205STejun Heo 	struct worker *worker;
46873d1cb205STejun Heo 
46883d1cb205STejun Heo 	if (!(task->flags & PF_WQ_WORKER))
46893d1cb205STejun Heo 		return;
46903d1cb205STejun Heo 
46913d1cb205STejun Heo 	/*
46923d1cb205STejun Heo 	 * This function is called without any synchronization and @task
46933d1cb205STejun Heo 	 * could be in any state.  Be careful with dereferences.
46943d1cb205STejun Heo 	 */
4695e700591aSPetr Mladek 	worker = kthread_probe_data(task);
46963d1cb205STejun Heo 
46973d1cb205STejun Heo 	/*
46988bf89593STejun Heo 	 * Carefully copy the associated workqueue's workfn, name and desc.
46998bf89593STejun Heo 	 * Keep the original last '\0' in case the original is garbage.
47003d1cb205STejun Heo 	 */
4701fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&fn, &worker->current_func, sizeof(fn));
4702fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&pwq, &worker->current_pwq, sizeof(pwq));
4703fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&wq, &pwq->wq, sizeof(wq));
4704fe557319SChristoph Hellwig 	copy_from_kernel_nofault(name, wq->name, sizeof(name) - 1);
4705fe557319SChristoph Hellwig 	copy_from_kernel_nofault(desc, worker->desc, sizeof(desc) - 1);
47063d1cb205STejun Heo 
47073d1cb205STejun Heo 	if (fn || name[0] || desc[0]) {
4708d75f773cSSakari Ailus 		printk("%sWorkqueue: %s %ps", log_lvl, name, fn);
47098bf89593STejun Heo 		if (strcmp(name, desc))
47103d1cb205STejun Heo 			pr_cont(" (%s)", desc);
47113d1cb205STejun Heo 		pr_cont("\n");
47123d1cb205STejun Heo 	}
47133d1cb205STejun Heo }
47143d1cb205STejun Heo 
47153494fc30STejun Heo static void pr_cont_pool_info(struct worker_pool *pool)
47163494fc30STejun Heo {
47173494fc30STejun Heo 	pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
47183494fc30STejun Heo 	if (pool->node != NUMA_NO_NODE)
47193494fc30STejun Heo 		pr_cont(" node=%d", pool->node);
47203494fc30STejun Heo 	pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
47213494fc30STejun Heo }
47223494fc30STejun Heo 
47233494fc30STejun Heo static void pr_cont_work(bool comma, struct work_struct *work)
47243494fc30STejun Heo {
47253494fc30STejun Heo 	if (work->func == wq_barrier_func) {
47263494fc30STejun Heo 		struct wq_barrier *barr;
47273494fc30STejun Heo 
47283494fc30STejun Heo 		barr = container_of(work, struct wq_barrier, work);
47293494fc30STejun Heo 
47303494fc30STejun Heo 		pr_cont("%s BAR(%d)", comma ? "," : "",
47313494fc30STejun Heo 			task_pid_nr(barr->task));
47323494fc30STejun Heo 	} else {
4733d75f773cSSakari Ailus 		pr_cont("%s %ps", comma ? "," : "", work->func);
47343494fc30STejun Heo 	}
47353494fc30STejun Heo }
47363494fc30STejun Heo 
47373494fc30STejun Heo static void show_pwq(struct pool_workqueue *pwq)
47383494fc30STejun Heo {
47393494fc30STejun Heo 	struct worker_pool *pool = pwq->pool;
47403494fc30STejun Heo 	struct work_struct *work;
47413494fc30STejun Heo 	struct worker *worker;
47423494fc30STejun Heo 	bool has_in_flight = false, has_pending = false;
47433494fc30STejun Heo 	int bkt;
47443494fc30STejun Heo 
47453494fc30STejun Heo 	pr_info("  pwq %d:", pool->id);
47463494fc30STejun Heo 	pr_cont_pool_info(pool);
47473494fc30STejun Heo 
4748e66b39afSTejun Heo 	pr_cont(" active=%d/%d refcnt=%d%s\n",
4749e66b39afSTejun Heo 		pwq->nr_active, pwq->max_active, pwq->refcnt,
47503494fc30STejun Heo 		!list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
47513494fc30STejun Heo 
47523494fc30STejun Heo 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
47533494fc30STejun Heo 		if (worker->current_pwq == pwq) {
47543494fc30STejun Heo 			has_in_flight = true;
47553494fc30STejun Heo 			break;
47563494fc30STejun Heo 		}
47573494fc30STejun Heo 	}
47583494fc30STejun Heo 	if (has_in_flight) {
47593494fc30STejun Heo 		bool comma = false;
47603494fc30STejun Heo 
47613494fc30STejun Heo 		pr_info("    in-flight:");
47623494fc30STejun Heo 		hash_for_each(pool->busy_hash, bkt, worker, hentry) {
47633494fc30STejun Heo 			if (worker->current_pwq != pwq)
47643494fc30STejun Heo 				continue;
47653494fc30STejun Heo 
4766d75f773cSSakari Ailus 			pr_cont("%s %d%s:%ps", comma ? "," : "",
47673494fc30STejun Heo 				task_pid_nr(worker->task),
476830ae2fc0STejun Heo 				worker->rescue_wq ? "(RESCUER)" : "",
47693494fc30STejun Heo 				worker->current_func);
47703494fc30STejun Heo 			list_for_each_entry(work, &worker->scheduled, entry)
47713494fc30STejun Heo 				pr_cont_work(false, work);
47723494fc30STejun Heo 			comma = true;
47733494fc30STejun Heo 		}
47743494fc30STejun Heo 		pr_cont("\n");
47753494fc30STejun Heo 	}
47763494fc30STejun Heo 
47773494fc30STejun Heo 	list_for_each_entry(work, &pool->worklist, entry) {
47783494fc30STejun Heo 		if (get_work_pwq(work) == pwq) {
47793494fc30STejun Heo 			has_pending = true;
47803494fc30STejun Heo 			break;
47813494fc30STejun Heo 		}
47823494fc30STejun Heo 	}
47833494fc30STejun Heo 	if (has_pending) {
47843494fc30STejun Heo 		bool comma = false;
47853494fc30STejun Heo 
47863494fc30STejun Heo 		pr_info("    pending:");
47873494fc30STejun Heo 		list_for_each_entry(work, &pool->worklist, entry) {
47883494fc30STejun Heo 			if (get_work_pwq(work) != pwq)
47893494fc30STejun Heo 				continue;
47903494fc30STejun Heo 
47913494fc30STejun Heo 			pr_cont_work(comma, work);
47923494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
47933494fc30STejun Heo 		}
47943494fc30STejun Heo 		pr_cont("\n");
47953494fc30STejun Heo 	}
47963494fc30STejun Heo 
4797f97a4a1aSLai Jiangshan 	if (!list_empty(&pwq->inactive_works)) {
47983494fc30STejun Heo 		bool comma = false;
47993494fc30STejun Heo 
4800f97a4a1aSLai Jiangshan 		pr_info("    inactive:");
4801f97a4a1aSLai Jiangshan 		list_for_each_entry(work, &pwq->inactive_works, entry) {
48023494fc30STejun Heo 			pr_cont_work(comma, work);
48033494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
48043494fc30STejun Heo 		}
48053494fc30STejun Heo 		pr_cont("\n");
48063494fc30STejun Heo 	}
48073494fc30STejun Heo }
48083494fc30STejun Heo 
48093494fc30STejun Heo /**
481055df0933SImran Khan  * show_one_workqueue - dump state of specified workqueue
481155df0933SImran Khan  * @wq: workqueue whose state will be printed
48123494fc30STejun Heo  */
481355df0933SImran Khan void show_one_workqueue(struct workqueue_struct *wq)
48143494fc30STejun Heo {
48153494fc30STejun Heo 	struct pool_workqueue *pwq;
48163494fc30STejun Heo 	bool idle = true;
481755df0933SImran Khan 	unsigned long flags;
48183494fc30STejun Heo 
48193494fc30STejun Heo 	for_each_pwq(pwq, wq) {
4820f97a4a1aSLai Jiangshan 		if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
48213494fc30STejun Heo 			idle = false;
48223494fc30STejun Heo 			break;
48233494fc30STejun Heo 		}
48243494fc30STejun Heo 	}
482555df0933SImran Khan 	if (idle) /* Nothing to print for idle workqueue */
482655df0933SImran Khan 		return;
48273494fc30STejun Heo 
48283494fc30STejun Heo 	pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
48293494fc30STejun Heo 
48303494fc30STejun Heo 	for_each_pwq(pwq, wq) {
4831a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irqsave(&pwq->pool->lock, flags);
483257116ce1SJohan Hovold 		if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
483357116ce1SJohan Hovold 			/*
483457116ce1SJohan Hovold 			 * Defer printing to avoid deadlocks in console
483557116ce1SJohan Hovold 			 * drivers that queue work while holding locks
483657116ce1SJohan Hovold 			 * also taken in their write paths.
483757116ce1SJohan Hovold 			 */
483857116ce1SJohan Hovold 			printk_deferred_enter();
48393494fc30STejun Heo 			show_pwq(pwq);
484057116ce1SJohan Hovold 			printk_deferred_exit();
484157116ce1SJohan Hovold 		}
4842a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
484362635ea8SSergey Senozhatsky 		/*
484462635ea8SSergey Senozhatsky 		 * We could be printing a lot from atomic context, e.g.
484555df0933SImran Khan 		 * sysrq-t -> show_all_workqueues(). Avoid triggering
484662635ea8SSergey Senozhatsky 		 * hard lockup.
484762635ea8SSergey Senozhatsky 		 */
484862635ea8SSergey Senozhatsky 		touch_nmi_watchdog();
48493494fc30STejun Heo 	}
485055df0933SImran Khan 
48513494fc30STejun Heo }
48523494fc30STejun Heo 
485355df0933SImran Khan /**
485455df0933SImran Khan  * show_one_worker_pool - dump state of specified worker pool
485555df0933SImran Khan  * @pool: worker pool whose state will be printed
485655df0933SImran Khan  */
485755df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool)
485855df0933SImran Khan {
48593494fc30STejun Heo 	struct worker *worker;
48603494fc30STejun Heo 	bool first = true;
486155df0933SImran Khan 	unsigned long flags;
48623494fc30STejun Heo 
4863a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irqsave(&pool->lock, flags);
48643494fc30STejun Heo 	if (pool->nr_workers == pool->nr_idle)
48653494fc30STejun Heo 		goto next_pool;
486657116ce1SJohan Hovold 	/*
486757116ce1SJohan Hovold 	 * Defer printing to avoid deadlocks in console drivers that
486857116ce1SJohan Hovold 	 * queue work while holding locks also taken in their write
486957116ce1SJohan Hovold 	 * paths.
487057116ce1SJohan Hovold 	 */
487157116ce1SJohan Hovold 	printk_deferred_enter();
48723494fc30STejun Heo 	pr_info("pool %d:", pool->id);
48733494fc30STejun Heo 	pr_cont_pool_info(pool);
487482607adcSTejun Heo 	pr_cont(" hung=%us workers=%d",
487582607adcSTejun Heo 		jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000,
487682607adcSTejun Heo 		pool->nr_workers);
48773494fc30STejun Heo 	if (pool->manager)
48783494fc30STejun Heo 		pr_cont(" manager: %d",
48793494fc30STejun Heo 			task_pid_nr(pool->manager->task));
48803494fc30STejun Heo 	list_for_each_entry(worker, &pool->idle_list, entry) {
48813494fc30STejun Heo 		pr_cont(" %s%d", first ? "idle: " : "",
48823494fc30STejun Heo 			task_pid_nr(worker->task));
48833494fc30STejun Heo 		first = false;
48843494fc30STejun Heo 	}
48853494fc30STejun Heo 	pr_cont("\n");
488657116ce1SJohan Hovold 	printk_deferred_exit();
48873494fc30STejun Heo next_pool:
4888a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&pool->lock, flags);
488962635ea8SSergey Senozhatsky 	/*
489062635ea8SSergey Senozhatsky 	 * We could be printing a lot from atomic context, e.g.
489155df0933SImran Khan 	 * sysrq-t -> show_all_workqueues(). Avoid triggering
489262635ea8SSergey Senozhatsky 	 * hard lockup.
489362635ea8SSergey Senozhatsky 	 */
489462635ea8SSergey Senozhatsky 	touch_nmi_watchdog();
489555df0933SImran Khan 
48963494fc30STejun Heo }
48973494fc30STejun Heo 
489855df0933SImran Khan /**
489955df0933SImran Khan  * show_all_workqueues - dump workqueue state
490055df0933SImran Khan  *
490155df0933SImran Khan  * Called from a sysrq handler or try_to_freeze_tasks() and prints out
490255df0933SImran Khan  * all busy workqueues and pools.
490355df0933SImran Khan  */
490455df0933SImran Khan void show_all_workqueues(void)
490555df0933SImran Khan {
490655df0933SImran Khan 	struct workqueue_struct *wq;
490755df0933SImran Khan 	struct worker_pool *pool;
490855df0933SImran Khan 	int pi;
490955df0933SImran Khan 
491055df0933SImran Khan 	rcu_read_lock();
491155df0933SImran Khan 
491255df0933SImran Khan 	pr_info("Showing busy workqueues and worker pools:\n");
491355df0933SImran Khan 
491455df0933SImran Khan 	list_for_each_entry_rcu(wq, &workqueues, list)
491555df0933SImran Khan 		show_one_workqueue(wq);
491655df0933SImran Khan 
491755df0933SImran Khan 	for_each_pool(pool, pi)
491855df0933SImran Khan 		show_one_worker_pool(pool);
491955df0933SImran Khan 
492024acfb71SThomas Gleixner 	rcu_read_unlock();
49213494fc30STejun Heo }
49223494fc30STejun Heo 
49236b59808bSTejun Heo /* used to show worker information through /proc/PID/{comm,stat,status} */
49246b59808bSTejun Heo void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
49256b59808bSTejun Heo {
49266b59808bSTejun Heo 	int off;
49276b59808bSTejun Heo 
49286b59808bSTejun Heo 	/* always show the actual comm */
49296b59808bSTejun Heo 	off = strscpy(buf, task->comm, size);
49306b59808bSTejun Heo 	if (off < 0)
49316b59808bSTejun Heo 		return;
49326b59808bSTejun Heo 
4933197f6accSTejun Heo 	/* stabilize PF_WQ_WORKER and worker pool association */
49346b59808bSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
49356b59808bSTejun Heo 
4936197f6accSTejun Heo 	if (task->flags & PF_WQ_WORKER) {
4937197f6accSTejun Heo 		struct worker *worker = kthread_data(task);
4938197f6accSTejun Heo 		struct worker_pool *pool = worker->pool;
49396b59808bSTejun Heo 
49406b59808bSTejun Heo 		if (pool) {
4941a9b8a985SSebastian Andrzej Siewior 			raw_spin_lock_irq(&pool->lock);
49426b59808bSTejun Heo 			/*
4943197f6accSTejun Heo 			 * ->desc tracks information (wq name or
4944197f6accSTejun Heo 			 * set_worker_desc()) for the latest execution.  If
4945197f6accSTejun Heo 			 * current, prepend '+', otherwise '-'.
49466b59808bSTejun Heo 			 */
49476b59808bSTejun Heo 			if (worker->desc[0] != '\0') {
49486b59808bSTejun Heo 				if (worker->current_work)
49496b59808bSTejun Heo 					scnprintf(buf + off, size - off, "+%s",
49506b59808bSTejun Heo 						  worker->desc);
49516b59808bSTejun Heo 				else
49526b59808bSTejun Heo 					scnprintf(buf + off, size - off, "-%s",
49536b59808bSTejun Heo 						  worker->desc);
49546b59808bSTejun Heo 			}
4955a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&pool->lock);
49566b59808bSTejun Heo 		}
4957197f6accSTejun Heo 	}
49586b59808bSTejun Heo 
49596b59808bSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
49606b59808bSTejun Heo }
49616b59808bSTejun Heo 
496266448bc2SMathieu Malaterre #ifdef CONFIG_SMP
496366448bc2SMathieu Malaterre 
4964db7bccf4STejun Heo /*
4965db7bccf4STejun Heo  * CPU hotplug.
4966db7bccf4STejun Heo  *
4967e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
4968112202d9STejun Heo  * are a lot of assumptions on strong associations among work, pwq and
4969706026c2STejun Heo  * pool which make migrating pending and scheduled works very
4970e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
497194cf58bbSTejun Heo  * worker pools serve mix of short, long and very long running works making
4972e22bee78STejun Heo  * blocked draining impractical.
4973e22bee78STejun Heo  *
497424647570STejun Heo  * This is solved by allowing the pools to be disassociated from the CPU
4975628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
4976628c78e7STejun Heo  * cpu comes back online.
4977db7bccf4STejun Heo  */
4978db7bccf4STejun Heo 
4979e8b3f8dbSLai Jiangshan static void unbind_workers(int cpu)
4980db7bccf4STejun Heo {
49814ce62e9eSTejun Heo 	struct worker_pool *pool;
4982db7bccf4STejun Heo 	struct worker *worker;
4983db7bccf4STejun Heo 
4984f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
49851258fae7STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
4986a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
4987e22bee78STejun Heo 
4988f2d5a0eeSTejun Heo 		/*
498992f9c5c4SLai Jiangshan 		 * We've blocked all attach/detach operations. Make all workers
499094cf58bbSTejun Heo 		 * unbound and set DISASSOCIATED.  Before this, all workers
499111b45b0bSLai Jiangshan 		 * must be on the cpu.  After this, they may become diasporas.
4992b4ac9384SLai Jiangshan 		 * And the preemption disabled section in their sched callbacks
4993b4ac9384SLai Jiangshan 		 * are guaranteed to see WORKER_UNBOUND since the code here
4994b4ac9384SLai Jiangshan 		 * is on the same cpu.
4995f2d5a0eeSTejun Heo 		 */
4996da028469SLai Jiangshan 		for_each_pool_worker(worker, pool)
4997403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
4998db7bccf4STejun Heo 
499924647570STejun Heo 		pool->flags |= POOL_DISASSOCIATED;
5000f2d5a0eeSTejun Heo 
5001e22bee78STejun Heo 		/*
5002989442d7SLai Jiangshan 		 * The handling of nr_running in sched callbacks are disabled
5003989442d7SLai Jiangshan 		 * now.  Zap nr_running.  After this, nr_running stays zero and
5004989442d7SLai Jiangshan 		 * need_more_worker() and keep_working() are always true as
5005989442d7SLai Jiangshan 		 * long as the worklist is not empty.  This pool now behaves as
5006989442d7SLai Jiangshan 		 * an unbound (in terms of concurrency management) pool which
5007eb283428SLai Jiangshan 		 * are served by workers tied to the pool.
5008e22bee78STejun Heo 		 */
5009e19e397aSTejun Heo 		atomic_set(&pool->nr_running, 0);
5010eb283428SLai Jiangshan 
5011eb283428SLai Jiangshan 		/*
5012eb283428SLai Jiangshan 		 * With concurrency management just turned off, a busy
5013eb283428SLai Jiangshan 		 * worker blocking could lead to lengthy stalls.  Kick off
5014eb283428SLai Jiangshan 		 * unbound chain execution of currently pending work items.
5015eb283428SLai Jiangshan 		 */
5016eb283428SLai Jiangshan 		wake_up_worker(pool);
5017989442d7SLai Jiangshan 
5018a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
5019989442d7SLai Jiangshan 
5020989442d7SLai Jiangshan 		for_each_pool_worker(worker, pool) {
5021989442d7SLai Jiangshan 			kthread_set_per_cpu(worker->task, -1);
5022989442d7SLai Jiangshan 			WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, cpu_possible_mask) < 0);
5023989442d7SLai Jiangshan 		}
5024989442d7SLai Jiangshan 
5025989442d7SLai Jiangshan 		mutex_unlock(&wq_pool_attach_mutex);
5026eb283428SLai Jiangshan 	}
5027db7bccf4STejun Heo }
5028db7bccf4STejun Heo 
5029bd7c089eSTejun Heo /**
5030bd7c089eSTejun Heo  * rebind_workers - rebind all workers of a pool to the associated CPU
5031bd7c089eSTejun Heo  * @pool: pool of interest
5032bd7c089eSTejun Heo  *
5033a9ab775bSTejun Heo  * @pool->cpu is coming online.  Rebind all workers to the CPU.
5034bd7c089eSTejun Heo  */
5035bd7c089eSTejun Heo static void rebind_workers(struct worker_pool *pool)
5036bd7c089eSTejun Heo {
5037a9ab775bSTejun Heo 	struct worker *worker;
5038bd7c089eSTejun Heo 
50391258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
5040bd7c089eSTejun Heo 
5041bd7c089eSTejun Heo 	/*
5042a9ab775bSTejun Heo 	 * Restore CPU affinity of all workers.  As all idle workers should
5043a9ab775bSTejun Heo 	 * be on the run-queue of the associated CPU before any local
5044402dd89dSShailendra Verma 	 * wake-ups for concurrency management happen, restore CPU affinity
5045a9ab775bSTejun Heo 	 * of all workers first and then clear UNBOUND.  As we're called
5046a9ab775bSTejun Heo 	 * from CPU_ONLINE, the following shouldn't fail.
5047bd7c089eSTejun Heo 	 */
50485c25b5ffSPeter Zijlstra 	for_each_pool_worker(worker, pool) {
50495c25b5ffSPeter Zijlstra 		kthread_set_per_cpu(worker->task, pool->cpu);
5050a9ab775bSTejun Heo 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
5051a9ab775bSTejun Heo 						  pool->attrs->cpumask) < 0);
50525c25b5ffSPeter Zijlstra 	}
5053a9ab775bSTejun Heo 
5054a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
5055f7c17d26SWanpeng Li 
50563de5e884SLai Jiangshan 	pool->flags &= ~POOL_DISASSOCIATED;
5057a9ab775bSTejun Heo 
5058da028469SLai Jiangshan 	for_each_pool_worker(worker, pool) {
5059a9ab775bSTejun Heo 		unsigned int worker_flags = worker->flags;
5060a9ab775bSTejun Heo 
5061a9ab775bSTejun Heo 		/*
5062a9ab775bSTejun Heo 		 * We want to clear UNBOUND but can't directly call
5063a9ab775bSTejun Heo 		 * worker_clr_flags() or adjust nr_running.  Atomically
5064a9ab775bSTejun Heo 		 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
5065a9ab775bSTejun Heo 		 * @worker will clear REBOUND using worker_clr_flags() when
5066a9ab775bSTejun Heo 		 * it initiates the next execution cycle thus restoring
5067a9ab775bSTejun Heo 		 * concurrency management.  Note that when or whether
5068a9ab775bSTejun Heo 		 * @worker clears REBOUND doesn't affect correctness.
5069a9ab775bSTejun Heo 		 *
5070c95491edSMark Rutland 		 * WRITE_ONCE() is necessary because @worker->flags may be
5071a9ab775bSTejun Heo 		 * tested without holding any lock in
50726d25be57SThomas Gleixner 		 * wq_worker_running().  Without it, NOT_RUNNING test may
5073a9ab775bSTejun Heo 		 * fail incorrectly leading to premature concurrency
5074a9ab775bSTejun Heo 		 * management operations.
5075bd7c089eSTejun Heo 		 */
5076a9ab775bSTejun Heo 		WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
5077a9ab775bSTejun Heo 		worker_flags |= WORKER_REBOUND;
5078a9ab775bSTejun Heo 		worker_flags &= ~WORKER_UNBOUND;
5079c95491edSMark Rutland 		WRITE_ONCE(worker->flags, worker_flags);
5080bd7c089eSTejun Heo 	}
5081a9ab775bSTejun Heo 
5082a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
5083bd7c089eSTejun Heo }
5084bd7c089eSTejun Heo 
50857dbc725eSTejun Heo /**
50867dbc725eSTejun Heo  * restore_unbound_workers_cpumask - restore cpumask of unbound workers
50877dbc725eSTejun Heo  * @pool: unbound pool of interest
50887dbc725eSTejun Heo  * @cpu: the CPU which is coming up
50897dbc725eSTejun Heo  *
50907dbc725eSTejun Heo  * An unbound pool may end up with a cpumask which doesn't have any online
50917dbc725eSTejun Heo  * CPUs.  When a worker of such pool get scheduled, the scheduler resets
50927dbc725eSTejun Heo  * its cpus_allowed.  If @cpu is in @pool's cpumask which didn't have any
50937dbc725eSTejun Heo  * online CPU before, cpus_allowed of all its workers should be restored.
50947dbc725eSTejun Heo  */
50957dbc725eSTejun Heo static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
50967dbc725eSTejun Heo {
50977dbc725eSTejun Heo 	static cpumask_t cpumask;
50987dbc725eSTejun Heo 	struct worker *worker;
50997dbc725eSTejun Heo 
51001258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
51017dbc725eSTejun Heo 
51027dbc725eSTejun Heo 	/* is @cpu allowed for @pool? */
51037dbc725eSTejun Heo 	if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
51047dbc725eSTejun Heo 		return;
51057dbc725eSTejun Heo 
51067dbc725eSTejun Heo 	cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
51077dbc725eSTejun Heo 
51087dbc725eSTejun Heo 	/* as we're called from CPU_ONLINE, the following shouldn't fail */
5109da028469SLai Jiangshan 	for_each_pool_worker(worker, pool)
5110d945b5e9SPeter Zijlstra 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
51117dbc725eSTejun Heo }
51127dbc725eSTejun Heo 
51137ee681b2SThomas Gleixner int workqueue_prepare_cpu(unsigned int cpu)
51141da177e4SLinus Torvalds {
51154ce62e9eSTejun Heo 	struct worker_pool *pool;
51161da177e4SLinus Torvalds 
5117f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
51183ce63377STejun Heo 		if (pool->nr_workers)
51193ce63377STejun Heo 			continue;
5120051e1850SLai Jiangshan 		if (!create_worker(pool))
51217ee681b2SThomas Gleixner 			return -ENOMEM;
51223af24433SOleg Nesterov 	}
51237ee681b2SThomas Gleixner 	return 0;
51247ee681b2SThomas Gleixner }
51251da177e4SLinus Torvalds 
51267ee681b2SThomas Gleixner int workqueue_online_cpu(unsigned int cpu)
51277ee681b2SThomas Gleixner {
51287ee681b2SThomas Gleixner 	struct worker_pool *pool;
51297ee681b2SThomas Gleixner 	struct workqueue_struct *wq;
51307ee681b2SThomas Gleixner 	int pi;
51317ee681b2SThomas Gleixner 
513268e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
51337dbc725eSTejun Heo 
51347dbc725eSTejun Heo 	for_each_pool(pool, pi) {
51351258fae7STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
513694cf58bbSTejun Heo 
5137f05b558dSLai Jiangshan 		if (pool->cpu == cpu)
513894cf58bbSTejun Heo 			rebind_workers(pool);
5139f05b558dSLai Jiangshan 		else if (pool->cpu < 0)
51407dbc725eSTejun Heo 			restore_unbound_workers_cpumask(pool, cpu);
514194cf58bbSTejun Heo 
51421258fae7STejun Heo 		mutex_unlock(&wq_pool_attach_mutex);
514394cf58bbSTejun Heo 	}
51447dbc725eSTejun Heo 
51454c16bd32STejun Heo 	/* update NUMA affinity of unbound workqueues */
51464c16bd32STejun Heo 	list_for_each_entry(wq, &workqueues, list)
51474c16bd32STejun Heo 		wq_update_unbound_numa(wq, cpu, true);
51484c16bd32STejun Heo 
514968e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
51507ee681b2SThomas Gleixner 	return 0;
515165758202STejun Heo }
515265758202STejun Heo 
51537ee681b2SThomas Gleixner int workqueue_offline_cpu(unsigned int cpu)
515465758202STejun Heo {
51554c16bd32STejun Heo 	struct workqueue_struct *wq;
51568db25e78STejun Heo 
51574c16bd32STejun Heo 	/* unbinding per-cpu workers should happen on the local CPU */
5158e8b3f8dbSLai Jiangshan 	if (WARN_ON(cpu != smp_processor_id()))
5159e8b3f8dbSLai Jiangshan 		return -1;
5160e8b3f8dbSLai Jiangshan 
5161e8b3f8dbSLai Jiangshan 	unbind_workers(cpu);
51624c16bd32STejun Heo 
51634c16bd32STejun Heo 	/* update NUMA affinity of unbound workqueues */
51644c16bd32STejun Heo 	mutex_lock(&wq_pool_mutex);
51654c16bd32STejun Heo 	list_for_each_entry(wq, &workqueues, list)
51664c16bd32STejun Heo 		wq_update_unbound_numa(wq, cpu, false);
51674c16bd32STejun Heo 	mutex_unlock(&wq_pool_mutex);
51684c16bd32STejun Heo 
51697ee681b2SThomas Gleixner 	return 0;
517065758202STejun Heo }
517165758202STejun Heo 
51722d3854a3SRusty Russell struct work_for_cpu {
5173ed48ece2STejun Heo 	struct work_struct work;
51742d3854a3SRusty Russell 	long (*fn)(void *);
51752d3854a3SRusty Russell 	void *arg;
51762d3854a3SRusty Russell 	long ret;
51772d3854a3SRusty Russell };
51782d3854a3SRusty Russell 
5179ed48ece2STejun Heo static void work_for_cpu_fn(struct work_struct *work)
51802d3854a3SRusty Russell {
5181ed48ece2STejun Heo 	struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
5182ed48ece2STejun Heo 
51832d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
51842d3854a3SRusty Russell }
51852d3854a3SRusty Russell 
51862d3854a3SRusty Russell /**
518722aceb31SAnna-Maria Gleixner  * work_on_cpu - run a function in thread context on a particular cpu
51882d3854a3SRusty Russell  * @cpu: the cpu to run on
51892d3854a3SRusty Russell  * @fn: the function to run
51902d3854a3SRusty Russell  * @arg: the function arg
51912d3854a3SRusty Russell  *
519231ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
51936b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
5194d185af30SYacine Belkadi  *
5195d185af30SYacine Belkadi  * Return: The value @fn returns.
51962d3854a3SRusty Russell  */
5197d84ff051STejun Heo long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
51982d3854a3SRusty Russell {
5199ed48ece2STejun Heo 	struct work_for_cpu wfc = { .fn = fn, .arg = arg };
52002d3854a3SRusty Russell 
5201ed48ece2STejun Heo 	INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
5202ed48ece2STejun Heo 	schedule_work_on(cpu, &wfc.work);
520312997d1aSBjorn Helgaas 	flush_work(&wfc.work);
5204440a1136SChuansheng Liu 	destroy_work_on_stack(&wfc.work);
52052d3854a3SRusty Russell 	return wfc.ret;
52062d3854a3SRusty Russell }
52072d3854a3SRusty Russell EXPORT_SYMBOL_GPL(work_on_cpu);
52080e8d6a93SThomas Gleixner 
52090e8d6a93SThomas Gleixner /**
52100e8d6a93SThomas Gleixner  * work_on_cpu_safe - run a function in thread context on a particular cpu
52110e8d6a93SThomas Gleixner  * @cpu: the cpu to run on
52120e8d6a93SThomas Gleixner  * @fn:  the function to run
52130e8d6a93SThomas Gleixner  * @arg: the function argument
52140e8d6a93SThomas Gleixner  *
52150e8d6a93SThomas Gleixner  * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
52160e8d6a93SThomas Gleixner  * any locks which would prevent @fn from completing.
52170e8d6a93SThomas Gleixner  *
52180e8d6a93SThomas Gleixner  * Return: The value @fn returns.
52190e8d6a93SThomas Gleixner  */
52200e8d6a93SThomas Gleixner long work_on_cpu_safe(int cpu, long (*fn)(void *), void *arg)
52210e8d6a93SThomas Gleixner {
52220e8d6a93SThomas Gleixner 	long ret = -ENODEV;
52230e8d6a93SThomas Gleixner 
5224ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
52250e8d6a93SThomas Gleixner 	if (cpu_online(cpu))
52260e8d6a93SThomas Gleixner 		ret = work_on_cpu(cpu, fn, arg);
5227ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
52280e8d6a93SThomas Gleixner 	return ret;
52290e8d6a93SThomas Gleixner }
52300e8d6a93SThomas Gleixner EXPORT_SYMBOL_GPL(work_on_cpu_safe);
52312d3854a3SRusty Russell #endif /* CONFIG_SMP */
52322d3854a3SRusty Russell 
5233a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
5234e7577c50SRusty Russell 
5235a0a1a5fdSTejun Heo /**
5236a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
5237a0a1a5fdSTejun Heo  *
523858a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
5239f97a4a1aSLai Jiangshan  * workqueues will queue new works to their inactive_works list instead of
5240706026c2STejun Heo  * pool->worklist.
5241a0a1a5fdSTejun Heo  *
5242a0a1a5fdSTejun Heo  * CONTEXT:
5243a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5244a0a1a5fdSTejun Heo  */
5245a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
5246a0a1a5fdSTejun Heo {
524724b8a847STejun Heo 	struct workqueue_struct *wq;
524824b8a847STejun Heo 	struct pool_workqueue *pwq;
5249a0a1a5fdSTejun Heo 
525068e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5251a0a1a5fdSTejun Heo 
52526183c009STejun Heo 	WARN_ON_ONCE(workqueue_freezing);
5253a0a1a5fdSTejun Heo 	workqueue_freezing = true;
5254a0a1a5fdSTejun Heo 
525524b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5256a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
5257699ce097STejun Heo 		for_each_pwq(pwq, wq)
5258699ce097STejun Heo 			pwq_adjust_max_active(pwq);
5259a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
5260a1056305STejun Heo 	}
52615bcab335STejun Heo 
526268e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5263a0a1a5fdSTejun Heo }
5264a0a1a5fdSTejun Heo 
5265a0a1a5fdSTejun Heo /**
526658a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
5267a0a1a5fdSTejun Heo  *
5268a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
5269a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
5270a0a1a5fdSTejun Heo  *
5271a0a1a5fdSTejun Heo  * CONTEXT:
527268e13a67SLai Jiangshan  * Grabs and releases wq_pool_mutex.
5273a0a1a5fdSTejun Heo  *
5274d185af30SYacine Belkadi  * Return:
527558a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
527658a69cb4STejun Heo  * is complete.
5277a0a1a5fdSTejun Heo  */
5278a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
5279a0a1a5fdSTejun Heo {
5280a0a1a5fdSTejun Heo 	bool busy = false;
528124b8a847STejun Heo 	struct workqueue_struct *wq;
528224b8a847STejun Heo 	struct pool_workqueue *pwq;
5283a0a1a5fdSTejun Heo 
528468e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5285a0a1a5fdSTejun Heo 
52866183c009STejun Heo 	WARN_ON_ONCE(!workqueue_freezing);
5287a0a1a5fdSTejun Heo 
528824b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
528924b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
529024b8a847STejun Heo 			continue;
5291a0a1a5fdSTejun Heo 		/*
5292a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
5293a0a1a5fdSTejun Heo 		 * to peek without lock.
5294a0a1a5fdSTejun Heo 		 */
529524acfb71SThomas Gleixner 		rcu_read_lock();
529624b8a847STejun Heo 		for_each_pwq(pwq, wq) {
52976183c009STejun Heo 			WARN_ON_ONCE(pwq->nr_active < 0);
5298112202d9STejun Heo 			if (pwq->nr_active) {
5299a0a1a5fdSTejun Heo 				busy = true;
530024acfb71SThomas Gleixner 				rcu_read_unlock();
5301a0a1a5fdSTejun Heo 				goto out_unlock;
5302a0a1a5fdSTejun Heo 			}
5303a0a1a5fdSTejun Heo 		}
530424acfb71SThomas Gleixner 		rcu_read_unlock();
5305a0a1a5fdSTejun Heo 	}
5306a0a1a5fdSTejun Heo out_unlock:
530768e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5308a0a1a5fdSTejun Heo 	return busy;
5309a0a1a5fdSTejun Heo }
5310a0a1a5fdSTejun Heo 
5311a0a1a5fdSTejun Heo /**
5312a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
5313a0a1a5fdSTejun Heo  *
5314a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
5315706026c2STejun Heo  * frozen works are transferred to their respective pool worklists.
5316a0a1a5fdSTejun Heo  *
5317a0a1a5fdSTejun Heo  * CONTEXT:
5318a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5319a0a1a5fdSTejun Heo  */
5320a0a1a5fdSTejun Heo void thaw_workqueues(void)
5321a0a1a5fdSTejun Heo {
532224b8a847STejun Heo 	struct workqueue_struct *wq;
532324b8a847STejun Heo 	struct pool_workqueue *pwq;
5324a0a1a5fdSTejun Heo 
532568e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5326a0a1a5fdSTejun Heo 
5327a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
5328a0a1a5fdSTejun Heo 		goto out_unlock;
5329a0a1a5fdSTejun Heo 
533074b414eaSLai Jiangshan 	workqueue_freezing = false;
533124b8a847STejun Heo 
533224b8a847STejun Heo 	/* restore max_active and repopulate worklist */
533324b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5334a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
5335699ce097STejun Heo 		for_each_pwq(pwq, wq)
5336699ce097STejun Heo 			pwq_adjust_max_active(pwq);
5337a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
533824b8a847STejun Heo 	}
533924b8a847STejun Heo 
5340a0a1a5fdSTejun Heo out_unlock:
534168e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5342a0a1a5fdSTejun Heo }
5343a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
5344a0a1a5fdSTejun Heo 
5345042f7df1SLai Jiangshan static int workqueue_apply_unbound_cpumask(void)
5346042f7df1SLai Jiangshan {
5347042f7df1SLai Jiangshan 	LIST_HEAD(ctxs);
5348042f7df1SLai Jiangshan 	int ret = 0;
5349042f7df1SLai Jiangshan 	struct workqueue_struct *wq;
5350042f7df1SLai Jiangshan 	struct apply_wqattrs_ctx *ctx, *n;
5351042f7df1SLai Jiangshan 
5352042f7df1SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5353042f7df1SLai Jiangshan 
5354042f7df1SLai Jiangshan 	list_for_each_entry(wq, &workqueues, list) {
5355042f7df1SLai Jiangshan 		if (!(wq->flags & WQ_UNBOUND))
5356042f7df1SLai Jiangshan 			continue;
5357042f7df1SLai Jiangshan 		/* creating multiple pwqs breaks ordering guarantee */
5358042f7df1SLai Jiangshan 		if (wq->flags & __WQ_ORDERED)
5359042f7df1SLai Jiangshan 			continue;
5360042f7df1SLai Jiangshan 
5361042f7df1SLai Jiangshan 		ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs);
5362042f7df1SLai Jiangshan 		if (!ctx) {
5363042f7df1SLai Jiangshan 			ret = -ENOMEM;
5364042f7df1SLai Jiangshan 			break;
5365042f7df1SLai Jiangshan 		}
5366042f7df1SLai Jiangshan 
5367042f7df1SLai Jiangshan 		list_add_tail(&ctx->list, &ctxs);
5368042f7df1SLai Jiangshan 	}
5369042f7df1SLai Jiangshan 
5370042f7df1SLai Jiangshan 	list_for_each_entry_safe(ctx, n, &ctxs, list) {
5371042f7df1SLai Jiangshan 		if (!ret)
5372042f7df1SLai Jiangshan 			apply_wqattrs_commit(ctx);
5373042f7df1SLai Jiangshan 		apply_wqattrs_cleanup(ctx);
5374042f7df1SLai Jiangshan 	}
5375042f7df1SLai Jiangshan 
5376042f7df1SLai Jiangshan 	return ret;
5377042f7df1SLai Jiangshan }
5378042f7df1SLai Jiangshan 
5379042f7df1SLai Jiangshan /**
5380042f7df1SLai Jiangshan  *  workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
5381042f7df1SLai Jiangshan  *  @cpumask: the cpumask to set
5382042f7df1SLai Jiangshan  *
5383042f7df1SLai Jiangshan  *  The low-level workqueues cpumask is a global cpumask that limits
5384042f7df1SLai Jiangshan  *  the affinity of all unbound workqueues.  This function check the @cpumask
5385042f7df1SLai Jiangshan  *  and apply it to all unbound workqueues and updates all pwqs of them.
5386042f7df1SLai Jiangshan  *
538767dc8325SCai Huoqing  *  Return:	0	- Success
5388042f7df1SLai Jiangshan  *  		-EINVAL	- Invalid @cpumask
5389042f7df1SLai Jiangshan  *  		-ENOMEM	- Failed to allocate memory for attrs or pwqs.
5390042f7df1SLai Jiangshan  */
5391042f7df1SLai Jiangshan int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
5392042f7df1SLai Jiangshan {
5393042f7df1SLai Jiangshan 	int ret = -EINVAL;
5394042f7df1SLai Jiangshan 	cpumask_var_t saved_cpumask;
5395042f7df1SLai Jiangshan 
5396c98a9805STal Shorer 	/*
5397c98a9805STal Shorer 	 * Not excluding isolated cpus on purpose.
5398c98a9805STal Shorer 	 * If the user wishes to include them, we allow that.
5399c98a9805STal Shorer 	 */
5400042f7df1SLai Jiangshan 	cpumask_and(cpumask, cpumask, cpu_possible_mask);
5401042f7df1SLai Jiangshan 	if (!cpumask_empty(cpumask)) {
5402a0111cf6SLai Jiangshan 		apply_wqattrs_lock();
5403d25302e4SMenglong Dong 		if (cpumask_equal(cpumask, wq_unbound_cpumask)) {
5404d25302e4SMenglong Dong 			ret = 0;
5405d25302e4SMenglong Dong 			goto out_unlock;
5406d25302e4SMenglong Dong 		}
5407d25302e4SMenglong Dong 
5408d25302e4SMenglong Dong 		if (!zalloc_cpumask_var(&saved_cpumask, GFP_KERNEL)) {
5409d25302e4SMenglong Dong 			ret = -ENOMEM;
5410d25302e4SMenglong Dong 			goto out_unlock;
5411d25302e4SMenglong Dong 		}
5412042f7df1SLai Jiangshan 
5413042f7df1SLai Jiangshan 		/* save the old wq_unbound_cpumask. */
5414042f7df1SLai Jiangshan 		cpumask_copy(saved_cpumask, wq_unbound_cpumask);
5415042f7df1SLai Jiangshan 
5416042f7df1SLai Jiangshan 		/* update wq_unbound_cpumask at first and apply it to wqs. */
5417042f7df1SLai Jiangshan 		cpumask_copy(wq_unbound_cpumask, cpumask);
5418042f7df1SLai Jiangshan 		ret = workqueue_apply_unbound_cpumask();
5419042f7df1SLai Jiangshan 
5420042f7df1SLai Jiangshan 		/* restore the wq_unbound_cpumask when failed. */
5421042f7df1SLai Jiangshan 		if (ret < 0)
5422042f7df1SLai Jiangshan 			cpumask_copy(wq_unbound_cpumask, saved_cpumask);
5423042f7df1SLai Jiangshan 
5424d25302e4SMenglong Dong 		free_cpumask_var(saved_cpumask);
5425d25302e4SMenglong Dong out_unlock:
5426a0111cf6SLai Jiangshan 		apply_wqattrs_unlock();
5427042f7df1SLai Jiangshan 	}
5428042f7df1SLai Jiangshan 
5429042f7df1SLai Jiangshan 	return ret;
5430042f7df1SLai Jiangshan }
5431042f7df1SLai Jiangshan 
54326ba94429SFrederic Weisbecker #ifdef CONFIG_SYSFS
54336ba94429SFrederic Weisbecker /*
54346ba94429SFrederic Weisbecker  * Workqueues with WQ_SYSFS flag set is visible to userland via
54356ba94429SFrederic Weisbecker  * /sys/bus/workqueue/devices/WQ_NAME.  All visible workqueues have the
54366ba94429SFrederic Weisbecker  * following attributes.
54376ba94429SFrederic Weisbecker  *
54386ba94429SFrederic Weisbecker  *  per_cpu	RO bool	: whether the workqueue is per-cpu or unbound
54396ba94429SFrederic Weisbecker  *  max_active	RW int	: maximum number of in-flight work items
54406ba94429SFrederic Weisbecker  *
54416ba94429SFrederic Weisbecker  * Unbound workqueues have the following extra attributes.
54426ba94429SFrederic Weisbecker  *
54439a19b463SWang Long  *  pool_ids	RO int	: the associated pool IDs for each node
54446ba94429SFrederic Weisbecker  *  nice	RW int	: nice value of the workers
54456ba94429SFrederic Weisbecker  *  cpumask	RW mask	: bitmask of allowed CPUs for the workers
54469a19b463SWang Long  *  numa	RW bool	: whether enable NUMA affinity
54476ba94429SFrederic Weisbecker  */
54486ba94429SFrederic Weisbecker struct wq_device {
54496ba94429SFrederic Weisbecker 	struct workqueue_struct		*wq;
54506ba94429SFrederic Weisbecker 	struct device			dev;
54516ba94429SFrederic Weisbecker };
54526ba94429SFrederic Weisbecker 
54536ba94429SFrederic Weisbecker static struct workqueue_struct *dev_to_wq(struct device *dev)
54546ba94429SFrederic Weisbecker {
54556ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
54566ba94429SFrederic Weisbecker 
54576ba94429SFrederic Weisbecker 	return wq_dev->wq;
54586ba94429SFrederic Weisbecker }
54596ba94429SFrederic Weisbecker 
54606ba94429SFrederic Weisbecker static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
54616ba94429SFrederic Weisbecker 			    char *buf)
54626ba94429SFrederic Weisbecker {
54636ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
54646ba94429SFrederic Weisbecker 
54656ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
54666ba94429SFrederic Weisbecker }
54676ba94429SFrederic Weisbecker static DEVICE_ATTR_RO(per_cpu);
54686ba94429SFrederic Weisbecker 
54696ba94429SFrederic Weisbecker static ssize_t max_active_show(struct device *dev,
54706ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
54716ba94429SFrederic Weisbecker {
54726ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
54736ba94429SFrederic Weisbecker 
54746ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
54756ba94429SFrederic Weisbecker }
54766ba94429SFrederic Weisbecker 
54776ba94429SFrederic Weisbecker static ssize_t max_active_store(struct device *dev,
54786ba94429SFrederic Weisbecker 				struct device_attribute *attr, const char *buf,
54796ba94429SFrederic Weisbecker 				size_t count)
54806ba94429SFrederic Weisbecker {
54816ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
54826ba94429SFrederic Weisbecker 	int val;
54836ba94429SFrederic Weisbecker 
54846ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &val) != 1 || val <= 0)
54856ba94429SFrederic Weisbecker 		return -EINVAL;
54866ba94429SFrederic Weisbecker 
54876ba94429SFrederic Weisbecker 	workqueue_set_max_active(wq, val);
54886ba94429SFrederic Weisbecker 	return count;
54896ba94429SFrederic Weisbecker }
54906ba94429SFrederic Weisbecker static DEVICE_ATTR_RW(max_active);
54916ba94429SFrederic Weisbecker 
54926ba94429SFrederic Weisbecker static struct attribute *wq_sysfs_attrs[] = {
54936ba94429SFrederic Weisbecker 	&dev_attr_per_cpu.attr,
54946ba94429SFrederic Weisbecker 	&dev_attr_max_active.attr,
54956ba94429SFrederic Weisbecker 	NULL,
54966ba94429SFrederic Weisbecker };
54976ba94429SFrederic Weisbecker ATTRIBUTE_GROUPS(wq_sysfs);
54986ba94429SFrederic Weisbecker 
54996ba94429SFrederic Weisbecker static ssize_t wq_pool_ids_show(struct device *dev,
55006ba94429SFrederic Weisbecker 				struct device_attribute *attr, char *buf)
55016ba94429SFrederic Weisbecker {
55026ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
55036ba94429SFrederic Weisbecker 	const char *delim = "";
55046ba94429SFrederic Weisbecker 	int node, written = 0;
55056ba94429SFrederic Weisbecker 
5506ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
550724acfb71SThomas Gleixner 	rcu_read_lock();
55086ba94429SFrederic Weisbecker 	for_each_node(node) {
55096ba94429SFrederic Weisbecker 		written += scnprintf(buf + written, PAGE_SIZE - written,
55106ba94429SFrederic Weisbecker 				     "%s%d:%d", delim, node,
55116ba94429SFrederic Weisbecker 				     unbound_pwq_by_node(wq, node)->pool->id);
55126ba94429SFrederic Weisbecker 		delim = " ";
55136ba94429SFrederic Weisbecker 	}
55146ba94429SFrederic Weisbecker 	written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
551524acfb71SThomas Gleixner 	rcu_read_unlock();
5516ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
55176ba94429SFrederic Weisbecker 
55186ba94429SFrederic Weisbecker 	return written;
55196ba94429SFrederic Weisbecker }
55206ba94429SFrederic Weisbecker 
55216ba94429SFrederic Weisbecker static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
55226ba94429SFrederic Weisbecker 			    char *buf)
55236ba94429SFrederic Weisbecker {
55246ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
55256ba94429SFrederic Weisbecker 	int written;
55266ba94429SFrederic Weisbecker 
55276ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
55286ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
55296ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
55306ba94429SFrederic Weisbecker 
55316ba94429SFrederic Weisbecker 	return written;
55326ba94429SFrederic Weisbecker }
55336ba94429SFrederic Weisbecker 
55346ba94429SFrederic Weisbecker /* prepare workqueue_attrs for sysfs store operations */
55356ba94429SFrederic Weisbecker static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
55366ba94429SFrederic Weisbecker {
55376ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
55386ba94429SFrederic Weisbecker 
5539899a94feSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5540899a94feSLai Jiangshan 
5541be69d00dSThomas Gleixner 	attrs = alloc_workqueue_attrs();
55426ba94429SFrederic Weisbecker 	if (!attrs)
55436ba94429SFrederic Weisbecker 		return NULL;
55446ba94429SFrederic Weisbecker 
55456ba94429SFrederic Weisbecker 	copy_workqueue_attrs(attrs, wq->unbound_attrs);
55466ba94429SFrederic Weisbecker 	return attrs;
55476ba94429SFrederic Weisbecker }
55486ba94429SFrederic Weisbecker 
55496ba94429SFrederic Weisbecker static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
55506ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
55516ba94429SFrederic Weisbecker {
55526ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
55536ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5554d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
5555d4d3e257SLai Jiangshan 
5556d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
55576ba94429SFrederic Weisbecker 
55586ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
55596ba94429SFrederic Weisbecker 	if (!attrs)
5560d4d3e257SLai Jiangshan 		goto out_unlock;
55616ba94429SFrederic Weisbecker 
55626ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &attrs->nice) == 1 &&
55636ba94429SFrederic Weisbecker 	    attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
5564d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
55656ba94429SFrederic Weisbecker 	else
55666ba94429SFrederic Weisbecker 		ret = -EINVAL;
55676ba94429SFrederic Weisbecker 
5568d4d3e257SLai Jiangshan out_unlock:
5569d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
55706ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
55716ba94429SFrederic Weisbecker 	return ret ?: count;
55726ba94429SFrederic Weisbecker }
55736ba94429SFrederic Weisbecker 
55746ba94429SFrederic Weisbecker static ssize_t wq_cpumask_show(struct device *dev,
55756ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
55766ba94429SFrederic Weisbecker {
55776ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
55786ba94429SFrederic Weisbecker 	int written;
55796ba94429SFrederic Weisbecker 
55806ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
55816ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
55826ba94429SFrederic Weisbecker 			    cpumask_pr_args(wq->unbound_attrs->cpumask));
55836ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
55846ba94429SFrederic Weisbecker 	return written;
55856ba94429SFrederic Weisbecker }
55866ba94429SFrederic Weisbecker 
55876ba94429SFrederic Weisbecker static ssize_t wq_cpumask_store(struct device *dev,
55886ba94429SFrederic Weisbecker 				struct device_attribute *attr,
55896ba94429SFrederic Weisbecker 				const char *buf, size_t count)
55906ba94429SFrederic Weisbecker {
55916ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
55926ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5593d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
5594d4d3e257SLai Jiangshan 
5595d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
55966ba94429SFrederic Weisbecker 
55976ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
55986ba94429SFrederic Weisbecker 	if (!attrs)
5599d4d3e257SLai Jiangshan 		goto out_unlock;
56006ba94429SFrederic Weisbecker 
56016ba94429SFrederic Weisbecker 	ret = cpumask_parse(buf, attrs->cpumask);
56026ba94429SFrederic Weisbecker 	if (!ret)
5603d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
56046ba94429SFrederic Weisbecker 
5605d4d3e257SLai Jiangshan out_unlock:
5606d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
56076ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
56086ba94429SFrederic Weisbecker 	return ret ?: count;
56096ba94429SFrederic Weisbecker }
56106ba94429SFrederic Weisbecker 
56116ba94429SFrederic Weisbecker static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
56126ba94429SFrederic Weisbecker 			    char *buf)
56136ba94429SFrederic Weisbecker {
56146ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
56156ba94429SFrederic Weisbecker 	int written;
56166ba94429SFrederic Weisbecker 
56176ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
56186ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n",
56196ba94429SFrederic Weisbecker 			    !wq->unbound_attrs->no_numa);
56206ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
56216ba94429SFrederic Weisbecker 
56226ba94429SFrederic Weisbecker 	return written;
56236ba94429SFrederic Weisbecker }
56246ba94429SFrederic Weisbecker 
56256ba94429SFrederic Weisbecker static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
56266ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
56276ba94429SFrederic Weisbecker {
56286ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
56296ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5630d4d3e257SLai Jiangshan 	int v, ret = -ENOMEM;
5631d4d3e257SLai Jiangshan 
5632d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
56336ba94429SFrederic Weisbecker 
56346ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
56356ba94429SFrederic Weisbecker 	if (!attrs)
5636d4d3e257SLai Jiangshan 		goto out_unlock;
56376ba94429SFrederic Weisbecker 
56386ba94429SFrederic Weisbecker 	ret = -EINVAL;
56396ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &v) == 1) {
56406ba94429SFrederic Weisbecker 		attrs->no_numa = !v;
5641d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
56426ba94429SFrederic Weisbecker 	}
56436ba94429SFrederic Weisbecker 
5644d4d3e257SLai Jiangshan out_unlock:
5645d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
56466ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
56476ba94429SFrederic Weisbecker 	return ret ?: count;
56486ba94429SFrederic Weisbecker }
56496ba94429SFrederic Weisbecker 
56506ba94429SFrederic Weisbecker static struct device_attribute wq_sysfs_unbound_attrs[] = {
56516ba94429SFrederic Weisbecker 	__ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
56526ba94429SFrederic Weisbecker 	__ATTR(nice, 0644, wq_nice_show, wq_nice_store),
56536ba94429SFrederic Weisbecker 	__ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
56546ba94429SFrederic Weisbecker 	__ATTR(numa, 0644, wq_numa_show, wq_numa_store),
56556ba94429SFrederic Weisbecker 	__ATTR_NULL,
56566ba94429SFrederic Weisbecker };
56576ba94429SFrederic Weisbecker 
56586ba94429SFrederic Weisbecker static struct bus_type wq_subsys = {
56596ba94429SFrederic Weisbecker 	.name				= "workqueue",
56606ba94429SFrederic Weisbecker 	.dev_groups			= wq_sysfs_groups,
56616ba94429SFrederic Weisbecker };
56626ba94429SFrederic Weisbecker 
5663b05a7928SFrederic Weisbecker static ssize_t wq_unbound_cpumask_show(struct device *dev,
5664b05a7928SFrederic Weisbecker 		struct device_attribute *attr, char *buf)
5665b05a7928SFrederic Weisbecker {
5666b05a7928SFrederic Weisbecker 	int written;
5667b05a7928SFrederic Weisbecker 
5668042f7df1SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5669b05a7928SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
5670b05a7928SFrederic Weisbecker 			    cpumask_pr_args(wq_unbound_cpumask));
5671042f7df1SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5672b05a7928SFrederic Weisbecker 
5673b05a7928SFrederic Weisbecker 	return written;
5674b05a7928SFrederic Weisbecker }
5675b05a7928SFrederic Weisbecker 
5676042f7df1SLai Jiangshan static ssize_t wq_unbound_cpumask_store(struct device *dev,
5677042f7df1SLai Jiangshan 		struct device_attribute *attr, const char *buf, size_t count)
5678042f7df1SLai Jiangshan {
5679042f7df1SLai Jiangshan 	cpumask_var_t cpumask;
5680042f7df1SLai Jiangshan 	int ret;
5681042f7df1SLai Jiangshan 
5682042f7df1SLai Jiangshan 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
5683042f7df1SLai Jiangshan 		return -ENOMEM;
5684042f7df1SLai Jiangshan 
5685042f7df1SLai Jiangshan 	ret = cpumask_parse(buf, cpumask);
5686042f7df1SLai Jiangshan 	if (!ret)
5687042f7df1SLai Jiangshan 		ret = workqueue_set_unbound_cpumask(cpumask);
5688042f7df1SLai Jiangshan 
5689042f7df1SLai Jiangshan 	free_cpumask_var(cpumask);
5690042f7df1SLai Jiangshan 	return ret ? ret : count;
5691042f7df1SLai Jiangshan }
5692042f7df1SLai Jiangshan 
5693b05a7928SFrederic Weisbecker static struct device_attribute wq_sysfs_cpumask_attr =
5694042f7df1SLai Jiangshan 	__ATTR(cpumask, 0644, wq_unbound_cpumask_show,
5695042f7df1SLai Jiangshan 	       wq_unbound_cpumask_store);
5696b05a7928SFrederic Weisbecker 
56976ba94429SFrederic Weisbecker static int __init wq_sysfs_init(void)
56986ba94429SFrederic Weisbecker {
5699b05a7928SFrederic Weisbecker 	int err;
5700b05a7928SFrederic Weisbecker 
5701b05a7928SFrederic Weisbecker 	err = subsys_virtual_register(&wq_subsys, NULL);
5702b05a7928SFrederic Weisbecker 	if (err)
5703b05a7928SFrederic Weisbecker 		return err;
5704b05a7928SFrederic Weisbecker 
5705b05a7928SFrederic Weisbecker 	return device_create_file(wq_subsys.dev_root, &wq_sysfs_cpumask_attr);
57066ba94429SFrederic Weisbecker }
57076ba94429SFrederic Weisbecker core_initcall(wq_sysfs_init);
57086ba94429SFrederic Weisbecker 
57096ba94429SFrederic Weisbecker static void wq_device_release(struct device *dev)
57106ba94429SFrederic Weisbecker {
57116ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
57126ba94429SFrederic Weisbecker 
57136ba94429SFrederic Weisbecker 	kfree(wq_dev);
57146ba94429SFrederic Weisbecker }
57156ba94429SFrederic Weisbecker 
57166ba94429SFrederic Weisbecker /**
57176ba94429SFrederic Weisbecker  * workqueue_sysfs_register - make a workqueue visible in sysfs
57186ba94429SFrederic Weisbecker  * @wq: the workqueue to register
57196ba94429SFrederic Weisbecker  *
57206ba94429SFrederic Weisbecker  * Expose @wq in sysfs under /sys/bus/workqueue/devices.
57216ba94429SFrederic Weisbecker  * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
57226ba94429SFrederic Weisbecker  * which is the preferred method.
57236ba94429SFrederic Weisbecker  *
57246ba94429SFrederic Weisbecker  * Workqueue user should use this function directly iff it wants to apply
57256ba94429SFrederic Weisbecker  * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
57266ba94429SFrederic Weisbecker  * apply_workqueue_attrs() may race against userland updating the
57276ba94429SFrederic Weisbecker  * attributes.
57286ba94429SFrederic Weisbecker  *
57296ba94429SFrederic Weisbecker  * Return: 0 on success, -errno on failure.
57306ba94429SFrederic Weisbecker  */
57316ba94429SFrederic Weisbecker int workqueue_sysfs_register(struct workqueue_struct *wq)
57326ba94429SFrederic Weisbecker {
57336ba94429SFrederic Weisbecker 	struct wq_device *wq_dev;
57346ba94429SFrederic Weisbecker 	int ret;
57356ba94429SFrederic Weisbecker 
57366ba94429SFrederic Weisbecker 	/*
5737402dd89dSShailendra Verma 	 * Adjusting max_active or creating new pwqs by applying
57386ba94429SFrederic Weisbecker 	 * attributes breaks ordering guarantee.  Disallow exposing ordered
57396ba94429SFrederic Weisbecker 	 * workqueues.
57406ba94429SFrederic Weisbecker 	 */
57410a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
57426ba94429SFrederic Weisbecker 		return -EINVAL;
57436ba94429SFrederic Weisbecker 
57446ba94429SFrederic Weisbecker 	wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
57456ba94429SFrederic Weisbecker 	if (!wq_dev)
57466ba94429SFrederic Weisbecker 		return -ENOMEM;
57476ba94429SFrederic Weisbecker 
57486ba94429SFrederic Weisbecker 	wq_dev->wq = wq;
57496ba94429SFrederic Weisbecker 	wq_dev->dev.bus = &wq_subsys;
57506ba94429SFrederic Weisbecker 	wq_dev->dev.release = wq_device_release;
575123217b44SLars-Peter Clausen 	dev_set_name(&wq_dev->dev, "%s", wq->name);
57526ba94429SFrederic Weisbecker 
57536ba94429SFrederic Weisbecker 	/*
57546ba94429SFrederic Weisbecker 	 * unbound_attrs are created separately.  Suppress uevent until
57556ba94429SFrederic Weisbecker 	 * everything is ready.
57566ba94429SFrederic Weisbecker 	 */
57576ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, true);
57586ba94429SFrederic Weisbecker 
57596ba94429SFrederic Weisbecker 	ret = device_register(&wq_dev->dev);
57606ba94429SFrederic Weisbecker 	if (ret) {
5761537f4146SArvind Yadav 		put_device(&wq_dev->dev);
57626ba94429SFrederic Weisbecker 		wq->wq_dev = NULL;
57636ba94429SFrederic Weisbecker 		return ret;
57646ba94429SFrederic Weisbecker 	}
57656ba94429SFrederic Weisbecker 
57666ba94429SFrederic Weisbecker 	if (wq->flags & WQ_UNBOUND) {
57676ba94429SFrederic Weisbecker 		struct device_attribute *attr;
57686ba94429SFrederic Weisbecker 
57696ba94429SFrederic Weisbecker 		for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
57706ba94429SFrederic Weisbecker 			ret = device_create_file(&wq_dev->dev, attr);
57716ba94429SFrederic Weisbecker 			if (ret) {
57726ba94429SFrederic Weisbecker 				device_unregister(&wq_dev->dev);
57736ba94429SFrederic Weisbecker 				wq->wq_dev = NULL;
57746ba94429SFrederic Weisbecker 				return ret;
57756ba94429SFrederic Weisbecker 			}
57766ba94429SFrederic Weisbecker 		}
57776ba94429SFrederic Weisbecker 	}
57786ba94429SFrederic Weisbecker 
57796ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, false);
57806ba94429SFrederic Weisbecker 	kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
57816ba94429SFrederic Weisbecker 	return 0;
57826ba94429SFrederic Weisbecker }
57836ba94429SFrederic Weisbecker 
57846ba94429SFrederic Weisbecker /**
57856ba94429SFrederic Weisbecker  * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
57866ba94429SFrederic Weisbecker  * @wq: the workqueue to unregister
57876ba94429SFrederic Weisbecker  *
57886ba94429SFrederic Weisbecker  * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
57896ba94429SFrederic Weisbecker  */
57906ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
57916ba94429SFrederic Weisbecker {
57926ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = wq->wq_dev;
57936ba94429SFrederic Weisbecker 
57946ba94429SFrederic Weisbecker 	if (!wq->wq_dev)
57956ba94429SFrederic Weisbecker 		return;
57966ba94429SFrederic Weisbecker 
57976ba94429SFrederic Weisbecker 	wq->wq_dev = NULL;
57986ba94429SFrederic Weisbecker 	device_unregister(&wq_dev->dev);
57996ba94429SFrederic Weisbecker }
58006ba94429SFrederic Weisbecker #else	/* CONFIG_SYSFS */
58016ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)	{ }
58026ba94429SFrederic Weisbecker #endif	/* CONFIG_SYSFS */
58036ba94429SFrederic Weisbecker 
580482607adcSTejun Heo /*
580582607adcSTejun Heo  * Workqueue watchdog.
580682607adcSTejun Heo  *
580782607adcSTejun Heo  * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
580882607adcSTejun Heo  * flush dependency, a concurrency managed work item which stays RUNNING
580982607adcSTejun Heo  * indefinitely.  Workqueue stalls can be very difficult to debug as the
581082607adcSTejun Heo  * usual warning mechanisms don't trigger and internal workqueue state is
581182607adcSTejun Heo  * largely opaque.
581282607adcSTejun Heo  *
581382607adcSTejun Heo  * Workqueue watchdog monitors all worker pools periodically and dumps
581482607adcSTejun Heo  * state if some pools failed to make forward progress for a while where
581582607adcSTejun Heo  * forward progress is defined as the first item on ->worklist changing.
581682607adcSTejun Heo  *
581782607adcSTejun Heo  * This mechanism is controlled through the kernel parameter
581882607adcSTejun Heo  * "workqueue.watchdog_thresh" which can be updated at runtime through the
581982607adcSTejun Heo  * corresponding sysfs parameter file.
582082607adcSTejun Heo  */
582182607adcSTejun Heo #ifdef CONFIG_WQ_WATCHDOG
582282607adcSTejun Heo 
582382607adcSTejun Heo static unsigned long wq_watchdog_thresh = 30;
58245cd79d6aSKees Cook static struct timer_list wq_watchdog_timer;
582582607adcSTejun Heo 
582682607adcSTejun Heo static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
582782607adcSTejun Heo static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
582882607adcSTejun Heo 
582982607adcSTejun Heo static void wq_watchdog_reset_touched(void)
583082607adcSTejun Heo {
583182607adcSTejun Heo 	int cpu;
583282607adcSTejun Heo 
583382607adcSTejun Heo 	wq_watchdog_touched = jiffies;
583482607adcSTejun Heo 	for_each_possible_cpu(cpu)
583582607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
583682607adcSTejun Heo }
583782607adcSTejun Heo 
58385cd79d6aSKees Cook static void wq_watchdog_timer_fn(struct timer_list *unused)
583982607adcSTejun Heo {
584082607adcSTejun Heo 	unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
584182607adcSTejun Heo 	bool lockup_detected = false;
5842940d71c6SSergey Senozhatsky 	unsigned long now = jiffies;
584382607adcSTejun Heo 	struct worker_pool *pool;
584482607adcSTejun Heo 	int pi;
584582607adcSTejun Heo 
584682607adcSTejun Heo 	if (!thresh)
584782607adcSTejun Heo 		return;
584882607adcSTejun Heo 
584982607adcSTejun Heo 	rcu_read_lock();
585082607adcSTejun Heo 
585182607adcSTejun Heo 	for_each_pool(pool, pi) {
585282607adcSTejun Heo 		unsigned long pool_ts, touched, ts;
585382607adcSTejun Heo 
585482607adcSTejun Heo 		if (list_empty(&pool->worklist))
585582607adcSTejun Heo 			continue;
585682607adcSTejun Heo 
5857940d71c6SSergey Senozhatsky 		/*
5858940d71c6SSergey Senozhatsky 		 * If a virtual machine is stopped by the host it can look to
5859940d71c6SSergey Senozhatsky 		 * the watchdog like a stall.
5860940d71c6SSergey Senozhatsky 		 */
5861940d71c6SSergey Senozhatsky 		kvm_check_and_clear_guest_paused();
5862940d71c6SSergey Senozhatsky 
586382607adcSTejun Heo 		/* get the latest of pool and touched timestamps */
586489e28ce6SWang Qing 		if (pool->cpu >= 0)
586589e28ce6SWang Qing 			touched = READ_ONCE(per_cpu(wq_watchdog_touched_cpu, pool->cpu));
586689e28ce6SWang Qing 		else
586782607adcSTejun Heo 			touched = READ_ONCE(wq_watchdog_touched);
586889e28ce6SWang Qing 		pool_ts = READ_ONCE(pool->watchdog_ts);
586982607adcSTejun Heo 
587082607adcSTejun Heo 		if (time_after(pool_ts, touched))
587182607adcSTejun Heo 			ts = pool_ts;
587282607adcSTejun Heo 		else
587382607adcSTejun Heo 			ts = touched;
587482607adcSTejun Heo 
587582607adcSTejun Heo 		/* did we stall? */
5876940d71c6SSergey Senozhatsky 		if (time_after(now, ts + thresh)) {
587782607adcSTejun Heo 			lockup_detected = true;
587882607adcSTejun Heo 			pr_emerg("BUG: workqueue lockup - pool");
587982607adcSTejun Heo 			pr_cont_pool_info(pool);
588082607adcSTejun Heo 			pr_cont(" stuck for %us!\n",
5881940d71c6SSergey Senozhatsky 				jiffies_to_msecs(now - pool_ts) / 1000);
588282607adcSTejun Heo 		}
588382607adcSTejun Heo 	}
588482607adcSTejun Heo 
588582607adcSTejun Heo 	rcu_read_unlock();
588682607adcSTejun Heo 
588782607adcSTejun Heo 	if (lockup_detected)
588855df0933SImran Khan 		show_all_workqueues();
588982607adcSTejun Heo 
589082607adcSTejun Heo 	wq_watchdog_reset_touched();
589182607adcSTejun Heo 	mod_timer(&wq_watchdog_timer, jiffies + thresh);
589282607adcSTejun Heo }
589382607adcSTejun Heo 
5894cb9d7fd5SVincent Whitchurch notrace void wq_watchdog_touch(int cpu)
589582607adcSTejun Heo {
589682607adcSTejun Heo 	if (cpu >= 0)
589782607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
589889e28ce6SWang Qing 
589982607adcSTejun Heo 	wq_watchdog_touched = jiffies;
590082607adcSTejun Heo }
590182607adcSTejun Heo 
590282607adcSTejun Heo static void wq_watchdog_set_thresh(unsigned long thresh)
590382607adcSTejun Heo {
590482607adcSTejun Heo 	wq_watchdog_thresh = 0;
590582607adcSTejun Heo 	del_timer_sync(&wq_watchdog_timer);
590682607adcSTejun Heo 
590782607adcSTejun Heo 	if (thresh) {
590882607adcSTejun Heo 		wq_watchdog_thresh = thresh;
590982607adcSTejun Heo 		wq_watchdog_reset_touched();
591082607adcSTejun Heo 		mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
591182607adcSTejun Heo 	}
591282607adcSTejun Heo }
591382607adcSTejun Heo 
591482607adcSTejun Heo static int wq_watchdog_param_set_thresh(const char *val,
591582607adcSTejun Heo 					const struct kernel_param *kp)
591682607adcSTejun Heo {
591782607adcSTejun Heo 	unsigned long thresh;
591882607adcSTejun Heo 	int ret;
591982607adcSTejun Heo 
592082607adcSTejun Heo 	ret = kstrtoul(val, 0, &thresh);
592182607adcSTejun Heo 	if (ret)
592282607adcSTejun Heo 		return ret;
592382607adcSTejun Heo 
592482607adcSTejun Heo 	if (system_wq)
592582607adcSTejun Heo 		wq_watchdog_set_thresh(thresh);
592682607adcSTejun Heo 	else
592782607adcSTejun Heo 		wq_watchdog_thresh = thresh;
592882607adcSTejun Heo 
592982607adcSTejun Heo 	return 0;
593082607adcSTejun Heo }
593182607adcSTejun Heo 
593282607adcSTejun Heo static const struct kernel_param_ops wq_watchdog_thresh_ops = {
593382607adcSTejun Heo 	.set	= wq_watchdog_param_set_thresh,
593482607adcSTejun Heo 	.get	= param_get_ulong,
593582607adcSTejun Heo };
593682607adcSTejun Heo 
593782607adcSTejun Heo module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
593882607adcSTejun Heo 		0644);
593982607adcSTejun Heo 
594082607adcSTejun Heo static void wq_watchdog_init(void)
594182607adcSTejun Heo {
59425cd79d6aSKees Cook 	timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
594382607adcSTejun Heo 	wq_watchdog_set_thresh(wq_watchdog_thresh);
594482607adcSTejun Heo }
594582607adcSTejun Heo 
594682607adcSTejun Heo #else	/* CONFIG_WQ_WATCHDOG */
594782607adcSTejun Heo 
594882607adcSTejun Heo static inline void wq_watchdog_init(void) { }
594982607adcSTejun Heo 
595082607adcSTejun Heo #endif	/* CONFIG_WQ_WATCHDOG */
595182607adcSTejun Heo 
5952bce90380STejun Heo static void __init wq_numa_init(void)
5953bce90380STejun Heo {
5954bce90380STejun Heo 	cpumask_var_t *tbl;
5955bce90380STejun Heo 	int node, cpu;
5956bce90380STejun Heo 
5957bce90380STejun Heo 	if (num_possible_nodes() <= 1)
5958bce90380STejun Heo 		return;
5959bce90380STejun Heo 
5960d55262c4STejun Heo 	if (wq_disable_numa) {
5961d55262c4STejun Heo 		pr_info("workqueue: NUMA affinity support disabled\n");
5962d55262c4STejun Heo 		return;
5963d55262c4STejun Heo 	}
5964d55262c4STejun Heo 
5965f728c4a9SZhen Lei 	for_each_possible_cpu(cpu) {
5966f728c4a9SZhen Lei 		if (WARN_ON(cpu_to_node(cpu) == NUMA_NO_NODE)) {
5967f728c4a9SZhen Lei 			pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
5968f728c4a9SZhen Lei 			return;
5969f728c4a9SZhen Lei 		}
5970f728c4a9SZhen Lei 	}
5971f728c4a9SZhen Lei 
5972be69d00dSThomas Gleixner 	wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs();
59734c16bd32STejun Heo 	BUG_ON(!wq_update_unbound_numa_attrs_buf);
59744c16bd32STejun Heo 
5975bce90380STejun Heo 	/*
5976bce90380STejun Heo 	 * We want masks of possible CPUs of each node which isn't readily
5977bce90380STejun Heo 	 * available.  Build one from cpu_to_node() which should have been
5978bce90380STejun Heo 	 * fully initialized by now.
5979bce90380STejun Heo 	 */
59806396bb22SKees Cook 	tbl = kcalloc(nr_node_ids, sizeof(tbl[0]), GFP_KERNEL);
5981bce90380STejun Heo 	BUG_ON(!tbl);
5982bce90380STejun Heo 
5983bce90380STejun Heo 	for_each_node(node)
59845a6024f1SYasuaki Ishimatsu 		BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
59851be0c25dSTejun Heo 				node_online(node) ? node : NUMA_NO_NODE));
5986bce90380STejun Heo 
5987bce90380STejun Heo 	for_each_possible_cpu(cpu) {
5988bce90380STejun Heo 		node = cpu_to_node(cpu);
5989bce90380STejun Heo 		cpumask_set_cpu(cpu, tbl[node]);
5990bce90380STejun Heo 	}
5991bce90380STejun Heo 
5992bce90380STejun Heo 	wq_numa_possible_cpumask = tbl;
5993bce90380STejun Heo 	wq_numa_enabled = true;
5994bce90380STejun Heo }
5995bce90380STejun Heo 
59963347fa09STejun Heo /**
59973347fa09STejun Heo  * workqueue_init_early - early init for workqueue subsystem
59983347fa09STejun Heo  *
59993347fa09STejun Heo  * This is the first half of two-staged workqueue subsystem initialization
60003347fa09STejun Heo  * and invoked as soon as the bare basics - memory allocation, cpumasks and
60013347fa09STejun Heo  * idr are up.  It sets up all the data structures and system workqueues
60023347fa09STejun Heo  * and allows early boot code to create workqueues and queue/cancel work
60033347fa09STejun Heo  * items.  Actual work item execution starts only after kthreads can be
60043347fa09STejun Heo  * created and scheduled right before early initcalls.
60053347fa09STejun Heo  */
60062333e829SYu Chen void __init workqueue_init_early(void)
60071da177e4SLinus Torvalds {
60087a4e344cSTejun Heo 	int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
60097a4e344cSTejun Heo 	int i, cpu;
6010c34056a3STejun Heo 
601110cdb157SLai Jiangshan 	BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
6012e904e6c2STejun Heo 
6013b05a7928SFrederic Weisbecker 	BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
6014*04d4e665SFrederic Weisbecker 	cpumask_copy(wq_unbound_cpumask, housekeeping_cpumask(HK_TYPE_WQ));
6015*04d4e665SFrederic Weisbecker 	cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, housekeeping_cpumask(HK_TYPE_DOMAIN));
6016b05a7928SFrederic Weisbecker 
6017e904e6c2STejun Heo 	pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
6018e904e6c2STejun Heo 
6019706026c2STejun Heo 	/* initialize CPU pools */
602029c91e99STejun Heo 	for_each_possible_cpu(cpu) {
60214ce62e9eSTejun Heo 		struct worker_pool *pool;
60228b03ae3cSTejun Heo 
60237a4e344cSTejun Heo 		i = 0;
6024f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
60257a4e344cSTejun Heo 			BUG_ON(init_worker_pool(pool));
6026ec22ca5eSTejun Heo 			pool->cpu = cpu;
60277a4e344cSTejun Heo 			cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
60287a4e344cSTejun Heo 			pool->attrs->nice = std_nice[i++];
6029f3f90ad4STejun Heo 			pool->node = cpu_to_node(cpu);
60307a4e344cSTejun Heo 
60319daf9e67STejun Heo 			/* alloc pool ID */
603268e13a67SLai Jiangshan 			mutex_lock(&wq_pool_mutex);
60339daf9e67STejun Heo 			BUG_ON(worker_pool_assign_id(pool));
603468e13a67SLai Jiangshan 			mutex_unlock(&wq_pool_mutex);
60354ce62e9eSTejun Heo 		}
60368b03ae3cSTejun Heo 	}
60378b03ae3cSTejun Heo 
60388a2b7538STejun Heo 	/* create default unbound and ordered wq attrs */
603929c91e99STejun Heo 	for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
604029c91e99STejun Heo 		struct workqueue_attrs *attrs;
604129c91e99STejun Heo 
6042be69d00dSThomas Gleixner 		BUG_ON(!(attrs = alloc_workqueue_attrs()));
604329c91e99STejun Heo 		attrs->nice = std_nice[i];
604429c91e99STejun Heo 		unbound_std_wq_attrs[i] = attrs;
60458a2b7538STejun Heo 
60468a2b7538STejun Heo 		/*
60478a2b7538STejun Heo 		 * An ordered wq should have only one pwq as ordering is
60488a2b7538STejun Heo 		 * guaranteed by max_active which is enforced by pwqs.
60498a2b7538STejun Heo 		 * Turn off NUMA so that dfl_pwq is used for all nodes.
60508a2b7538STejun Heo 		 */
6051be69d00dSThomas Gleixner 		BUG_ON(!(attrs = alloc_workqueue_attrs()));
60528a2b7538STejun Heo 		attrs->nice = std_nice[i];
60538a2b7538STejun Heo 		attrs->no_numa = true;
60548a2b7538STejun Heo 		ordered_wq_attrs[i] = attrs;
605529c91e99STejun Heo 	}
605629c91e99STejun Heo 
6057d320c038STejun Heo 	system_wq = alloc_workqueue("events", 0, 0);
60581aabe902SJoonsoo Kim 	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
6059d320c038STejun Heo 	system_long_wq = alloc_workqueue("events_long", 0, 0);
6060f3421797STejun Heo 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
6061f3421797STejun Heo 					    WQ_UNBOUND_MAX_ACTIVE);
606224d51addSTejun Heo 	system_freezable_wq = alloc_workqueue("events_freezable",
606324d51addSTejun Heo 					      WQ_FREEZABLE, 0);
60640668106cSViresh Kumar 	system_power_efficient_wq = alloc_workqueue("events_power_efficient",
60650668106cSViresh Kumar 					      WQ_POWER_EFFICIENT, 0);
60660668106cSViresh Kumar 	system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
60670668106cSViresh Kumar 					      WQ_FREEZABLE | WQ_POWER_EFFICIENT,
60680668106cSViresh Kumar 					      0);
60691aabe902SJoonsoo Kim 	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
60700668106cSViresh Kumar 	       !system_unbound_wq || !system_freezable_wq ||
60710668106cSViresh Kumar 	       !system_power_efficient_wq ||
60720668106cSViresh Kumar 	       !system_freezable_power_efficient_wq);
60733347fa09STejun Heo }
60743347fa09STejun Heo 
60753347fa09STejun Heo /**
60763347fa09STejun Heo  * workqueue_init - bring workqueue subsystem fully online
60773347fa09STejun Heo  *
60783347fa09STejun Heo  * This is the latter half of two-staged workqueue subsystem initialization
60793347fa09STejun Heo  * and invoked as soon as kthreads can be created and scheduled.
60803347fa09STejun Heo  * Workqueues have been created and work items queued on them, but there
60813347fa09STejun Heo  * are no kworkers executing the work items yet.  Populate the worker pools
60823347fa09STejun Heo  * with the initial workers and enable future kworker creations.
60833347fa09STejun Heo  */
60842333e829SYu Chen void __init workqueue_init(void)
60853347fa09STejun Heo {
60862186d9f9STejun Heo 	struct workqueue_struct *wq;
60873347fa09STejun Heo 	struct worker_pool *pool;
60883347fa09STejun Heo 	int cpu, bkt;
60893347fa09STejun Heo 
60902186d9f9STejun Heo 	/*
60912186d9f9STejun Heo 	 * It'd be simpler to initialize NUMA in workqueue_init_early() but
60922186d9f9STejun Heo 	 * CPU to node mapping may not be available that early on some
60932186d9f9STejun Heo 	 * archs such as power and arm64.  As per-cpu pools created
60942186d9f9STejun Heo 	 * previously could be missing node hint and unbound pools NUMA
60952186d9f9STejun Heo 	 * affinity, fix them up.
609640c17f75STejun Heo 	 *
609740c17f75STejun Heo 	 * Also, while iterating workqueues, create rescuers if requested.
60982186d9f9STejun Heo 	 */
60992186d9f9STejun Heo 	wq_numa_init();
61002186d9f9STejun Heo 
61012186d9f9STejun Heo 	mutex_lock(&wq_pool_mutex);
61022186d9f9STejun Heo 
61032186d9f9STejun Heo 	for_each_possible_cpu(cpu) {
61042186d9f9STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
61052186d9f9STejun Heo 			pool->node = cpu_to_node(cpu);
61062186d9f9STejun Heo 		}
61072186d9f9STejun Heo 	}
61082186d9f9STejun Heo 
610940c17f75STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
61102186d9f9STejun Heo 		wq_update_unbound_numa(wq, smp_processor_id(), true);
611140c17f75STejun Heo 		WARN(init_rescuer(wq),
611240c17f75STejun Heo 		     "workqueue: failed to create early rescuer for %s",
611340c17f75STejun Heo 		     wq->name);
611440c17f75STejun Heo 	}
61152186d9f9STejun Heo 
61162186d9f9STejun Heo 	mutex_unlock(&wq_pool_mutex);
61172186d9f9STejun Heo 
61183347fa09STejun Heo 	/* create the initial workers */
61193347fa09STejun Heo 	for_each_online_cpu(cpu) {
61203347fa09STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
61213347fa09STejun Heo 			pool->flags &= ~POOL_DISASSOCIATED;
61223347fa09STejun Heo 			BUG_ON(!create_worker(pool));
61233347fa09STejun Heo 		}
61243347fa09STejun Heo 	}
61253347fa09STejun Heo 
61263347fa09STejun Heo 	hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
61273347fa09STejun Heo 		BUG_ON(!create_worker(pool));
61283347fa09STejun Heo 
61293347fa09STejun Heo 	wq_online = true;
613082607adcSTejun Heo 	wq_watchdog_init();
61311da177e4SLinus Torvalds }
6132