xref: /linux-6.15/kernel/workqueue.c (revision 793777bc)
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 
157bc35f7efSLai Jiangshan 	/*
158bc35f7efSLai Jiangshan 	 * The counter is incremented in a process context on the associated CPU
159bc35f7efSLai Jiangshan 	 * w/ preemption disabled, and decremented or reset in the same context
160bc35f7efSLai Jiangshan 	 * but w/ pool->lock held. The readers grab pool->lock and are
161bc35f7efSLai Jiangshan 	 * guaranteed to see if the counter reached zero.
162bc35f7efSLai Jiangshan 	 */
163bc35f7efSLai Jiangshan 	int			nr_running;
16484f91c62SLai Jiangshan 
165bd7bdd43STejun Heo 	struct list_head	worklist;	/* L: list of pending works */
166ea1abd61SLai Jiangshan 
1675826cc8fSLai Jiangshan 	int			nr_workers;	/* L: total number of workers */
1685826cc8fSLai Jiangshan 	int			nr_idle;	/* L: currently idle workers */
169bd7bdd43STejun Heo 
1702c1f1a91SLai Jiangshan 	struct list_head	idle_list;	/* L: list of idle workers */
171bd7bdd43STejun Heo 	struct timer_list	idle_timer;	/* L: worker idle timeout */
172bd7bdd43STejun Heo 	struct timer_list	mayday_timer;	/* L: SOS timer for workers */
173bd7bdd43STejun Heo 
174c5aa87bbSTejun Heo 	/* a workers is either on busy_hash or idle_list, or the manager */
175c9e7cf27STejun Heo 	DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
176c9e7cf27STejun Heo 						/* L: hash of busy workers */
177c9e7cf27STejun Heo 
1782607d7a6STejun Heo 	struct worker		*manager;	/* L: purely informational */
17992f9c5c4SLai Jiangshan 	struct list_head	workers;	/* A: attached workers */
18060f5a4bcSLai Jiangshan 	struct completion	*detach_completion; /* all workers detached */
181e19e397aSTejun Heo 
1827cda9aaeSLai Jiangshan 	struct ida		worker_ida;	/* worker IDs for task name */
183e19e397aSTejun Heo 
1847a4e344cSTejun Heo 	struct workqueue_attrs	*attrs;		/* I: worker attributes */
18568e13a67SLai Jiangshan 	struct hlist_node	hash_node;	/* PL: unbound_pool_hash node */
18668e13a67SLai Jiangshan 	int			refcnt;		/* PL: refcnt for unbound pools */
1877a4e344cSTejun Heo 
188e19e397aSTejun Heo 	/*
18924acfb71SThomas Gleixner 	 * Destruction of pool is RCU protected to allow dereferences
19029c91e99STejun Heo 	 * from get_work_pool().
19129c91e99STejun Heo 	 */
19229c91e99STejun Heo 	struct rcu_head		rcu;
19384f91c62SLai Jiangshan };
1948b03ae3cSTejun Heo 
1958b03ae3cSTejun Heo /*
196112202d9STejun Heo  * The per-pool workqueue.  While queued, the lower WORK_STRUCT_FLAG_BITS
197112202d9STejun Heo  * of work_struct->data are used for flags and the remaining high bits
198112202d9STejun Heo  * point to the pwq; thus, pwqs need to be aligned at two's power of the
199112202d9STejun Heo  * number of flag bits.
2001da177e4SLinus Torvalds  */
201112202d9STejun Heo struct pool_workqueue {
202bd7bdd43STejun Heo 	struct worker_pool	*pool;		/* I: the associated pool */
2034690c4abSTejun Heo 	struct workqueue_struct *wq;		/* I: the owning workqueue */
20473f53c4aSTejun Heo 	int			work_color;	/* L: current color */
20573f53c4aSTejun Heo 	int			flush_color;	/* L: flushing color */
2068864b4e5STejun Heo 	int			refcnt;		/* L: reference count */
20773f53c4aSTejun Heo 	int			nr_in_flight[WORK_NR_COLORS];
20873f53c4aSTejun Heo 						/* L: nr of in_flight works */
209018f3a13SLai Jiangshan 
210018f3a13SLai Jiangshan 	/*
211018f3a13SLai Jiangshan 	 * nr_active management and WORK_STRUCT_INACTIVE:
212018f3a13SLai Jiangshan 	 *
213018f3a13SLai Jiangshan 	 * When pwq->nr_active >= max_active, new work item is queued to
214018f3a13SLai Jiangshan 	 * pwq->inactive_works instead of pool->worklist and marked with
215018f3a13SLai Jiangshan 	 * WORK_STRUCT_INACTIVE.
216018f3a13SLai Jiangshan 	 *
217018f3a13SLai Jiangshan 	 * All work items marked with WORK_STRUCT_INACTIVE do not participate
218018f3a13SLai Jiangshan 	 * in pwq->nr_active and all work items in pwq->inactive_works are
219018f3a13SLai Jiangshan 	 * marked with WORK_STRUCT_INACTIVE.  But not all WORK_STRUCT_INACTIVE
220018f3a13SLai Jiangshan 	 * work items are in pwq->inactive_works.  Some of them are ready to
221018f3a13SLai Jiangshan 	 * run in pool->worklist or worker->scheduled.  Those work itmes are
222018f3a13SLai Jiangshan 	 * only struct wq_barrier which is used for flush_work() and should
223018f3a13SLai Jiangshan 	 * not participate in pwq->nr_active.  For non-barrier work item, it
224018f3a13SLai Jiangshan 	 * is marked with WORK_STRUCT_INACTIVE iff it is in pwq->inactive_works.
225018f3a13SLai Jiangshan 	 */
2261e19ffc6STejun Heo 	int			nr_active;	/* L: nr of active works */
227a0a1a5fdSTejun Heo 	int			max_active;	/* L: max active works */
228f97a4a1aSLai Jiangshan 	struct list_head	inactive_works;	/* L: inactive works */
2293c25a55dSLai Jiangshan 	struct list_head	pwqs_node;	/* WR: node on wq->pwqs */
2302e109a28STejun Heo 	struct list_head	mayday_node;	/* MD: node on wq->maydays */
2318864b4e5STejun Heo 
2328864b4e5STejun Heo 	/*
2338864b4e5STejun Heo 	 * Release of unbound pwq is punted to system_wq.  See put_pwq()
2348864b4e5STejun Heo 	 * and pwq_unbound_release_workfn() for details.  pool_workqueue
23524acfb71SThomas Gleixner 	 * itself is also RCU protected so that the first pwq can be
236b09f4fd3SLai Jiangshan 	 * determined without grabbing wq->mutex.
2378864b4e5STejun Heo 	 */
2388864b4e5STejun Heo 	struct work_struct	unbound_release_work;
2398864b4e5STejun Heo 	struct rcu_head		rcu;
240e904e6c2STejun Heo } __aligned(1 << WORK_STRUCT_FLAG_BITS);
2411da177e4SLinus Torvalds 
2421da177e4SLinus Torvalds /*
24373f53c4aSTejun Heo  * Structure used to wait for workqueue flush.
24473f53c4aSTejun Heo  */
24573f53c4aSTejun Heo struct wq_flusher {
2463c25a55dSLai Jiangshan 	struct list_head	list;		/* WQ: list of flushers */
2473c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: flush color waiting for */
24873f53c4aSTejun Heo 	struct completion	done;		/* flush completion */
24973f53c4aSTejun Heo };
2501da177e4SLinus Torvalds 
251226223abSTejun Heo struct wq_device;
252226223abSTejun Heo 
25373f53c4aSTejun Heo /*
254c5aa87bbSTejun Heo  * The externally visible workqueue.  It relays the issued work items to
255c5aa87bbSTejun Heo  * the appropriate worker_pool through its pool_workqueues.
2561da177e4SLinus Torvalds  */
2571da177e4SLinus Torvalds struct workqueue_struct {
2583c25a55dSLai Jiangshan 	struct list_head	pwqs;		/* WR: all pwqs of this wq */
259e2dca7adSTejun Heo 	struct list_head	list;		/* PR: list of all workqueues */
26073f53c4aSTejun Heo 
2613c25a55dSLai Jiangshan 	struct mutex		mutex;		/* protects this wq */
2623c25a55dSLai Jiangshan 	int			work_color;	/* WQ: current work color */
2633c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: current flush color */
264112202d9STejun Heo 	atomic_t		nr_pwqs_to_flush; /* flush in progress */
2653c25a55dSLai Jiangshan 	struct wq_flusher	*first_flusher;	/* WQ: first flusher */
2663c25a55dSLai Jiangshan 	struct list_head	flusher_queue;	/* WQ: flush waiters */
2673c25a55dSLai Jiangshan 	struct list_head	flusher_overflow; /* WQ: flush overflow list */
26873f53c4aSTejun Heo 
2692e109a28STejun Heo 	struct list_head	maydays;	/* MD: pwqs requesting rescue */
27030ae2fc0STejun Heo 	struct worker		*rescuer;	/* MD: rescue worker */
271e22bee78STejun Heo 
27287fc741eSLai Jiangshan 	int			nr_drainers;	/* WQ: drain in progress */
273a357fc03SLai Jiangshan 	int			saved_max_active; /* WQ: saved pwq max_active */
274226223abSTejun Heo 
2755b95e1afSLai Jiangshan 	struct workqueue_attrs	*unbound_attrs;	/* PW: only for unbound wqs */
2765b95e1afSLai Jiangshan 	struct pool_workqueue	*dfl_pwq;	/* PW: only for unbound wqs */
2776029a918STejun Heo 
278226223abSTejun Heo #ifdef CONFIG_SYSFS
279226223abSTejun Heo 	struct wq_device	*wq_dev;	/* I: for sysfs interface */
280226223abSTejun Heo #endif
2814e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
282669de8bdSBart Van Assche 	char			*lock_name;
283669de8bdSBart Van Assche 	struct lock_class_key	key;
2844e6045f1SJohannes Berg 	struct lockdep_map	lockdep_map;
2854e6045f1SJohannes Berg #endif
286ecf6881fSTejun Heo 	char			name[WQ_NAME_LEN]; /* I: workqueue name */
2872728fd2fSTejun Heo 
288e2dca7adSTejun Heo 	/*
28924acfb71SThomas Gleixner 	 * Destruction of workqueue_struct is RCU protected to allow walking
29024acfb71SThomas Gleixner 	 * the workqueues list without grabbing wq_pool_mutex.
291e2dca7adSTejun Heo 	 * This is used to dump all workqueues from sysrq.
292e2dca7adSTejun Heo 	 */
293e2dca7adSTejun Heo 	struct rcu_head		rcu;
294e2dca7adSTejun Heo 
2952728fd2fSTejun Heo 	/* hot fields used during command issue, aligned to cacheline */
2962728fd2fSTejun Heo 	unsigned int		flags ____cacheline_aligned; /* WQ: WQ_* flags */
2972728fd2fSTejun Heo 	struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */
2985b95e1afSLai Jiangshan 	struct pool_workqueue __rcu *numa_pwq_tbl[]; /* PWR: unbound pwqs indexed by node */
2991da177e4SLinus Torvalds };
3001da177e4SLinus Torvalds 
301e904e6c2STejun Heo static struct kmem_cache *pwq_cache;
302e904e6c2STejun Heo 
303bce90380STejun Heo static cpumask_var_t *wq_numa_possible_cpumask;
304bce90380STejun Heo 					/* possible CPUs of each node */
305bce90380STejun Heo 
306d55262c4STejun Heo static bool wq_disable_numa;
307d55262c4STejun Heo module_param_named(disable_numa, wq_disable_numa, bool, 0444);
308d55262c4STejun Heo 
309cee22a15SViresh Kumar /* see the comment above the definition of WQ_POWER_EFFICIENT */
310552f530cSLuis R. Rodriguez static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
311cee22a15SViresh Kumar module_param_named(power_efficient, wq_power_efficient, bool, 0444);
312cee22a15SViresh Kumar 
313863b710bSTejun Heo static bool wq_online;			/* can kworkers be created yet? */
3143347fa09STejun Heo 
315bce90380STejun Heo static bool wq_numa_enabled;		/* unbound NUMA affinity enabled */
316bce90380STejun Heo 
3174c16bd32STejun Heo /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
3184c16bd32STejun Heo static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf;
3194c16bd32STejun Heo 
32068e13a67SLai Jiangshan static DEFINE_MUTEX(wq_pool_mutex);	/* protects pools and workqueues list */
3211258fae7STejun Heo static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
322a9b8a985SSebastian Andrzej Siewior static DEFINE_RAW_SPINLOCK(wq_mayday_lock);	/* protects wq->maydays list */
323d8bb65abSSebastian Andrzej Siewior /* wait for manager to go away */
324d8bb65abSSebastian Andrzej Siewior static struct rcuwait manager_wait = __RCUWAIT_INITIALIZER(manager_wait);
3255bcab335STejun Heo 
326e2dca7adSTejun Heo static LIST_HEAD(workqueues);		/* PR: list of all workqueues */
32768e13a67SLai Jiangshan static bool workqueue_freezing;		/* PL: have wqs started freezing? */
3287d19c5ceSTejun Heo 
32999c621efSLai Jiangshan /* PL&A: allowable cpus for unbound wqs and work items */
330ef557180SMike Galbraith static cpumask_var_t wq_unbound_cpumask;
331ef557180SMike Galbraith 
332ef557180SMike Galbraith /* CPU where unbound work was last round robin scheduled from this CPU */
333ef557180SMike Galbraith static DEFINE_PER_CPU(int, wq_rr_cpu_last);
334b05a7928SFrederic Weisbecker 
335f303fccbSTejun Heo /*
336f303fccbSTejun Heo  * Local execution of unbound work items is no longer guaranteed.  The
337f303fccbSTejun Heo  * following always forces round-robin CPU selection on unbound work items
338f303fccbSTejun Heo  * to uncover usages which depend on it.
339f303fccbSTejun Heo  */
340f303fccbSTejun Heo #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
341f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = true;
342f303fccbSTejun Heo #else
343f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = false;
344f303fccbSTejun Heo #endif
345f303fccbSTejun Heo module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
346f303fccbSTejun Heo 
3477d19c5ceSTejun Heo /* the per-cpu worker pools */
34825528213SPeter Zijlstra static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools);
3497d19c5ceSTejun Heo 
35068e13a67SLai Jiangshan static DEFINE_IDR(worker_pool_idr);	/* PR: idr of all pools */
3517d19c5ceSTejun Heo 
35268e13a67SLai Jiangshan /* PL: hash of all unbound pools keyed by pool->attrs */
35329c91e99STejun Heo static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
35429c91e99STejun Heo 
355c5aa87bbSTejun Heo /* I: attributes used when instantiating standard unbound pools on demand */
35629c91e99STejun Heo static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
35729c91e99STejun Heo 
3588a2b7538STejun Heo /* I: attributes used when instantiating ordered pools on demand */
3598a2b7538STejun Heo static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
3608a2b7538STejun Heo 
361d320c038STejun Heo struct workqueue_struct *system_wq __read_mostly;
362ad7b1f84SMarc Dionne EXPORT_SYMBOL(system_wq);
363044c782cSValentin Ilie struct workqueue_struct *system_highpri_wq __read_mostly;
3641aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
365044c782cSValentin Ilie struct workqueue_struct *system_long_wq __read_mostly;
366d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
367044c782cSValentin Ilie struct workqueue_struct *system_unbound_wq __read_mostly;
368f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
369044c782cSValentin Ilie struct workqueue_struct *system_freezable_wq __read_mostly;
37024d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
3710668106cSViresh Kumar struct workqueue_struct *system_power_efficient_wq __read_mostly;
3720668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_power_efficient_wq);
3730668106cSViresh Kumar struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
3740668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
375d320c038STejun Heo 
3767d19c5ceSTejun Heo static int worker_thread(void *__worker);
3776ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
378c29eb853STejun Heo static void show_pwq(struct pool_workqueue *pwq);
37955df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool);
3807d19c5ceSTejun Heo 
38197bd2347STejun Heo #define CREATE_TRACE_POINTS
38297bd2347STejun Heo #include <trace/events/workqueue.h>
38397bd2347STejun Heo 
38468e13a67SLai Jiangshan #define assert_rcu_or_pool_mutex()					\
38524acfb71SThomas Gleixner 	RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&			\
386f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
38724acfb71SThomas Gleixner 			 "RCU or wq_pool_mutex should be held")
3885bcab335STejun Heo 
3895b95e1afSLai Jiangshan #define assert_rcu_or_wq_mutex_or_pool_mutex(wq)			\
39024acfb71SThomas Gleixner 	RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&			\
391f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq->mutex) &&		\
392f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
39324acfb71SThomas Gleixner 			 "RCU, wq->mutex or wq_pool_mutex should be held")
3945b95e1afSLai Jiangshan 
395f02ae73aSTejun Heo #define for_each_cpu_worker_pool(pool, cpu)				\
396f02ae73aSTejun Heo 	for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0];		\
397f02ae73aSTejun Heo 	     (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
3987a62c2c8STejun Heo 	     (pool)++)
3994ce62e9eSTejun Heo 
40049e3cf44STejun Heo /**
40117116969STejun Heo  * for_each_pool - iterate through all worker_pools in the system
40217116969STejun Heo  * @pool: iteration cursor
403611c92a0STejun Heo  * @pi: integer used for iteration
404fa1b54e6STejun Heo  *
40524acfb71SThomas Gleixner  * This must be called either with wq_pool_mutex held or RCU read
40668e13a67SLai Jiangshan  * locked.  If the pool needs to be used beyond the locking in effect, the
40768e13a67SLai Jiangshan  * caller is responsible for guaranteeing that the pool stays online.
408fa1b54e6STejun Heo  *
409fa1b54e6STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
410fa1b54e6STejun Heo  * ignored.
41117116969STejun Heo  */
412611c92a0STejun Heo #define for_each_pool(pool, pi)						\
413611c92a0STejun Heo 	idr_for_each_entry(&worker_pool_idr, pool, pi)			\
41468e13a67SLai Jiangshan 		if (({ assert_rcu_or_pool_mutex(); false; })) { }	\
415fa1b54e6STejun Heo 		else
41617116969STejun Heo 
41717116969STejun Heo /**
418822d8405STejun Heo  * for_each_pool_worker - iterate through all workers of a worker_pool
419822d8405STejun Heo  * @worker: iteration cursor
420822d8405STejun Heo  * @pool: worker_pool to iterate workers of
421822d8405STejun Heo  *
4221258fae7STejun Heo  * This must be called with wq_pool_attach_mutex.
423822d8405STejun Heo  *
424822d8405STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
425822d8405STejun Heo  * ignored.
426822d8405STejun Heo  */
427da028469SLai Jiangshan #define for_each_pool_worker(worker, pool)				\
428da028469SLai Jiangshan 	list_for_each_entry((worker), &(pool)->workers, node)		\
4291258fae7STejun Heo 		if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
430822d8405STejun Heo 		else
431822d8405STejun Heo 
432822d8405STejun Heo /**
43349e3cf44STejun Heo  * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
43449e3cf44STejun Heo  * @pwq: iteration cursor
43549e3cf44STejun Heo  * @wq: the target workqueue
43676af4d93STejun Heo  *
43724acfb71SThomas Gleixner  * This must be called either with wq->mutex held or RCU read locked.
438794b18bcSTejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
439794b18bcSTejun Heo  * responsible for guaranteeing that the pwq stays online.
44076af4d93STejun Heo  *
44176af4d93STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
44276af4d93STejun Heo  * ignored.
44349e3cf44STejun Heo  */
44449e3cf44STejun Heo #define for_each_pwq(pwq, wq)						\
44549e9d1a9SSebastian Andrzej Siewior 	list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node,		\
4465a644662SJoel Fernandes (Google) 				 lockdep_is_held(&(wq->mutex)))
447f3421797STejun Heo 
448dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
449dc186ad7SThomas Gleixner 
450f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr;
451dc186ad7SThomas Gleixner 
45299777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
45399777288SStanislaw Gruszka {
45499777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
45599777288SStanislaw Gruszka }
45699777288SStanislaw Gruszka 
457b9fdac7fSDu, Changbin static bool work_is_static_object(void *addr)
458b9fdac7fSDu, Changbin {
459b9fdac7fSDu, Changbin 	struct work_struct *work = addr;
460b9fdac7fSDu, Changbin 
461b9fdac7fSDu, Changbin 	return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
462b9fdac7fSDu, Changbin }
463b9fdac7fSDu, Changbin 
464dc186ad7SThomas Gleixner /*
465dc186ad7SThomas Gleixner  * fixup_init is called when:
466dc186ad7SThomas Gleixner  * - an active object is initialized
467dc186ad7SThomas Gleixner  */
46802a982a6SDu, Changbin static bool work_fixup_init(void *addr, enum debug_obj_state state)
469dc186ad7SThomas Gleixner {
470dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
471dc186ad7SThomas Gleixner 
472dc186ad7SThomas Gleixner 	switch (state) {
473dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
474dc186ad7SThomas Gleixner 		cancel_work_sync(work);
475dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
47602a982a6SDu, Changbin 		return true;
477dc186ad7SThomas Gleixner 	default:
47802a982a6SDu, Changbin 		return false;
479dc186ad7SThomas Gleixner 	}
480dc186ad7SThomas Gleixner }
481dc186ad7SThomas Gleixner 
482dc186ad7SThomas Gleixner /*
483dc186ad7SThomas Gleixner  * fixup_free is called when:
484dc186ad7SThomas Gleixner  * - an active object is freed
485dc186ad7SThomas Gleixner  */
48602a982a6SDu, Changbin static bool work_fixup_free(void *addr, enum debug_obj_state state)
487dc186ad7SThomas Gleixner {
488dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
489dc186ad7SThomas Gleixner 
490dc186ad7SThomas Gleixner 	switch (state) {
491dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
492dc186ad7SThomas Gleixner 		cancel_work_sync(work);
493dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
49402a982a6SDu, Changbin 		return true;
495dc186ad7SThomas Gleixner 	default:
49602a982a6SDu, Changbin 		return false;
497dc186ad7SThomas Gleixner 	}
498dc186ad7SThomas Gleixner }
499dc186ad7SThomas Gleixner 
500f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr = {
501dc186ad7SThomas Gleixner 	.name		= "work_struct",
50299777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
503b9fdac7fSDu, Changbin 	.is_static_object = work_is_static_object,
504dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
505dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
506dc186ad7SThomas Gleixner };
507dc186ad7SThomas Gleixner 
508dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
509dc186ad7SThomas Gleixner {
510dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
511dc186ad7SThomas Gleixner }
512dc186ad7SThomas Gleixner 
513dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
514dc186ad7SThomas Gleixner {
515dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
516dc186ad7SThomas Gleixner }
517dc186ad7SThomas Gleixner 
518dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
519dc186ad7SThomas Gleixner {
520dc186ad7SThomas Gleixner 	if (onstack)
521dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
522dc186ad7SThomas Gleixner 	else
523dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
524dc186ad7SThomas Gleixner }
525dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
526dc186ad7SThomas Gleixner 
527dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
528dc186ad7SThomas Gleixner {
529dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
530dc186ad7SThomas Gleixner }
531dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
532dc186ad7SThomas Gleixner 
533ea2e64f2SThomas Gleixner void destroy_delayed_work_on_stack(struct delayed_work *work)
534ea2e64f2SThomas Gleixner {
535ea2e64f2SThomas Gleixner 	destroy_timer_on_stack(&work->timer);
536ea2e64f2SThomas Gleixner 	debug_object_free(&work->work, &work_debug_descr);
537ea2e64f2SThomas Gleixner }
538ea2e64f2SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
539ea2e64f2SThomas Gleixner 
540dc186ad7SThomas Gleixner #else
541dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
542dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
543dc186ad7SThomas Gleixner #endif
544dc186ad7SThomas Gleixner 
5454e8b22bdSLi Bin /**
54667dc8325SCai Huoqing  * worker_pool_assign_id - allocate ID and assign it to @pool
5474e8b22bdSLi Bin  * @pool: the pool pointer of interest
5484e8b22bdSLi Bin  *
5494e8b22bdSLi Bin  * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
5504e8b22bdSLi Bin  * successfully, -errno on failure.
5514e8b22bdSLi Bin  */
5529daf9e67STejun Heo static int worker_pool_assign_id(struct worker_pool *pool)
5539daf9e67STejun Heo {
5549daf9e67STejun Heo 	int ret;
5559daf9e67STejun Heo 
55668e13a67SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5575bcab335STejun Heo 
5584e8b22bdSLi Bin 	ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
5594e8b22bdSLi Bin 			GFP_KERNEL);
560229641a6STejun Heo 	if (ret >= 0) {
561e68035fbSTejun Heo 		pool->id = ret;
562229641a6STejun Heo 		return 0;
563229641a6STejun Heo 	}
5649daf9e67STejun Heo 	return ret;
5659daf9e67STejun Heo }
5669daf9e67STejun Heo 
56776af4d93STejun Heo /**
568df2d5ae4STejun Heo  * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
569df2d5ae4STejun Heo  * @wq: the target workqueue
570df2d5ae4STejun Heo  * @node: the node ID
571df2d5ae4STejun Heo  *
57224acfb71SThomas Gleixner  * This must be called with any of wq_pool_mutex, wq->mutex or RCU
5735b95e1afSLai Jiangshan  * read locked.
574df2d5ae4STejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
575df2d5ae4STejun Heo  * responsible for guaranteeing that the pwq stays online.
576d185af30SYacine Belkadi  *
577d185af30SYacine Belkadi  * Return: The unbound pool_workqueue for @node.
578df2d5ae4STejun Heo  */
579df2d5ae4STejun Heo static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
580df2d5ae4STejun Heo 						  int node)
581df2d5ae4STejun Heo {
5825b95e1afSLai Jiangshan 	assert_rcu_or_wq_mutex_or_pool_mutex(wq);
583d6e022f1STejun Heo 
584d6e022f1STejun Heo 	/*
585d6e022f1STejun Heo 	 * XXX: @node can be NUMA_NO_NODE if CPU goes offline while a
586d6e022f1STejun Heo 	 * delayed item is pending.  The plan is to keep CPU -> NODE
587d6e022f1STejun Heo 	 * mapping valid and stable across CPU on/offlines.  Once that
588d6e022f1STejun Heo 	 * happens, this workaround can be removed.
589d6e022f1STejun Heo 	 */
590d6e022f1STejun Heo 	if (unlikely(node == NUMA_NO_NODE))
591d6e022f1STejun Heo 		return wq->dfl_pwq;
592d6e022f1STejun Heo 
593df2d5ae4STejun Heo 	return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
594df2d5ae4STejun Heo }
595df2d5ae4STejun Heo 
59673f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
59773f53c4aSTejun Heo {
59873f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
59973f53c4aSTejun Heo }
60073f53c4aSTejun Heo 
601c4560c2cSLai Jiangshan static int get_work_color(unsigned long work_data)
60273f53c4aSTejun Heo {
603c4560c2cSLai Jiangshan 	return (work_data >> WORK_STRUCT_COLOR_SHIFT) &
60473f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
60573f53c4aSTejun Heo }
60673f53c4aSTejun Heo 
60773f53c4aSTejun Heo static int work_next_color(int color)
60873f53c4aSTejun Heo {
60973f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
610a848e3b6SOleg Nesterov }
611a848e3b6SOleg Nesterov 
6124594bf15SDavid Howells /*
613112202d9STejun Heo  * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
614112202d9STejun Heo  * contain the pointer to the queued pwq.  Once execution starts, the flag
6157c3eed5cSTejun Heo  * is cleared and the high bits contain OFFQ flags and pool ID.
6167a22ad75STejun Heo  *
617112202d9STejun Heo  * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
618112202d9STejun Heo  * and clear_work_data() can be used to set the pwq, pool or clear
619bbb68dfaSTejun Heo  * work->data.  These functions should only be called while the work is
620bbb68dfaSTejun Heo  * owned - ie. while the PENDING bit is set.
6217a22ad75STejun Heo  *
622112202d9STejun Heo  * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
6237c3eed5cSTejun Heo  * corresponding to a work.  Pool is available once the work has been
624112202d9STejun Heo  * queued anywhere after initialization until it is sync canceled.  pwq is
6257c3eed5cSTejun Heo  * available only while the work item is queued.
626bbb68dfaSTejun Heo  *
627bbb68dfaSTejun Heo  * %WORK_OFFQ_CANCELING is used to mark a work item which is being
628bbb68dfaSTejun Heo  * canceled.  While being canceled, a work item may have its PENDING set
629bbb68dfaSTejun Heo  * but stay off timer and worklist for arbitrarily long and nobody should
630bbb68dfaSTejun Heo  * try to steal the PENDING bit.
6314594bf15SDavid Howells  */
6327a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
6337a22ad75STejun Heo 				 unsigned long flags)
6347a22ad75STejun Heo {
6356183c009STejun Heo 	WARN_ON_ONCE(!work_pending(work));
6367a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
6377a22ad75STejun Heo }
6387a22ad75STejun Heo 
639112202d9STejun Heo static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
6404690c4abSTejun Heo 			 unsigned long extra_flags)
641365970a1SDavid Howells {
642112202d9STejun Heo 	set_work_data(work, (unsigned long)pwq,
643112202d9STejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
644365970a1SDavid Howells }
645365970a1SDavid Howells 
6464468a00fSLai Jiangshan static void set_work_pool_and_keep_pending(struct work_struct *work,
6474468a00fSLai Jiangshan 					   int pool_id)
6484468a00fSLai Jiangshan {
6494468a00fSLai Jiangshan 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
6504468a00fSLai Jiangshan 		      WORK_STRUCT_PENDING);
6514468a00fSLai Jiangshan }
6524468a00fSLai Jiangshan 
6537c3eed5cSTejun Heo static void set_work_pool_and_clear_pending(struct work_struct *work,
6547c3eed5cSTejun Heo 					    int pool_id)
6554d707b9fSOleg Nesterov {
65623657bb1STejun Heo 	/*
65723657bb1STejun Heo 	 * The following wmb is paired with the implied mb in
65823657bb1STejun Heo 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
65923657bb1STejun Heo 	 * here are visible to and precede any updates by the next PENDING
66023657bb1STejun Heo 	 * owner.
66123657bb1STejun Heo 	 */
66223657bb1STejun Heo 	smp_wmb();
6637c3eed5cSTejun Heo 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
664346c09f8SRoman Pen 	/*
665346c09f8SRoman Pen 	 * The following mb guarantees that previous clear of a PENDING bit
666346c09f8SRoman Pen 	 * will not be reordered with any speculative LOADS or STORES from
667346c09f8SRoman Pen 	 * work->current_func, which is executed afterwards.  This possible
6688bdc6201SLiu Song 	 * reordering can lead to a missed execution on attempt to queue
669346c09f8SRoman Pen 	 * the same @work.  E.g. consider this case:
670346c09f8SRoman Pen 	 *
671346c09f8SRoman Pen 	 *   CPU#0                         CPU#1
672346c09f8SRoman Pen 	 *   ----------------------------  --------------------------------
673346c09f8SRoman Pen 	 *
674346c09f8SRoman Pen 	 * 1  STORE event_indicated
675346c09f8SRoman Pen 	 * 2  queue_work_on() {
676346c09f8SRoman Pen 	 * 3    test_and_set_bit(PENDING)
677346c09f8SRoman Pen 	 * 4 }                             set_..._and_clear_pending() {
678346c09f8SRoman Pen 	 * 5                                 set_work_data() # clear bit
679346c09f8SRoman Pen 	 * 6                                 smp_mb()
680346c09f8SRoman Pen 	 * 7                               work->current_func() {
681346c09f8SRoman Pen 	 * 8				      LOAD event_indicated
682346c09f8SRoman Pen 	 *				   }
683346c09f8SRoman Pen 	 *
684346c09f8SRoman Pen 	 * Without an explicit full barrier speculative LOAD on line 8 can
685346c09f8SRoman Pen 	 * be executed before CPU#0 does STORE on line 1.  If that happens,
686346c09f8SRoman Pen 	 * CPU#0 observes the PENDING bit is still set and new execution of
687346c09f8SRoman Pen 	 * a @work is not queued in a hope, that CPU#1 will eventually
688346c09f8SRoman Pen 	 * finish the queued @work.  Meanwhile CPU#1 does not see
689346c09f8SRoman Pen 	 * event_indicated is set, because speculative LOAD was executed
690346c09f8SRoman Pen 	 * before actual STORE.
691346c09f8SRoman Pen 	 */
692346c09f8SRoman Pen 	smp_mb();
6934d707b9fSOleg Nesterov }
6944d707b9fSOleg Nesterov 
6957a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
696365970a1SDavid Howells {
6977c3eed5cSTejun Heo 	smp_wmb();	/* see set_work_pool_and_clear_pending() */
6987c3eed5cSTejun Heo 	set_work_data(work, WORK_STRUCT_NO_POOL, 0);
6997a22ad75STejun Heo }
7007a22ad75STejun Heo 
701112202d9STejun Heo static struct pool_workqueue *get_work_pwq(struct work_struct *work)
7027a22ad75STejun Heo {
703e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
7047a22ad75STejun Heo 
705112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
706e120153dSTejun Heo 		return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
707e120153dSTejun Heo 	else
708e120153dSTejun Heo 		return NULL;
7097a22ad75STejun Heo }
7107a22ad75STejun Heo 
7117c3eed5cSTejun Heo /**
7127c3eed5cSTejun Heo  * get_work_pool - return the worker_pool a given work was associated with
7137c3eed5cSTejun Heo  * @work: the work item of interest
7147c3eed5cSTejun Heo  *
71568e13a67SLai Jiangshan  * Pools are created and destroyed under wq_pool_mutex, and allows read
71624acfb71SThomas Gleixner  * access under RCU read lock.  As such, this function should be
71724acfb71SThomas Gleixner  * called under wq_pool_mutex or inside of a rcu_read_lock() region.
718fa1b54e6STejun Heo  *
719fa1b54e6STejun Heo  * All fields of the returned pool are accessible as long as the above
720fa1b54e6STejun Heo  * mentioned locking is in effect.  If the returned pool needs to be used
721fa1b54e6STejun Heo  * beyond the critical section, the caller is responsible for ensuring the
722fa1b54e6STejun Heo  * returned pool is and stays online.
723d185af30SYacine Belkadi  *
724d185af30SYacine Belkadi  * Return: The worker_pool @work was last associated with.  %NULL if none.
7257c3eed5cSTejun Heo  */
7267c3eed5cSTejun Heo static struct worker_pool *get_work_pool(struct work_struct *work)
7277a22ad75STejun Heo {
728e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
7297c3eed5cSTejun Heo 	int pool_id;
7307a22ad75STejun Heo 
73168e13a67SLai Jiangshan 	assert_rcu_or_pool_mutex();
732fa1b54e6STejun Heo 
733112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
734112202d9STejun Heo 		return ((struct pool_workqueue *)
7357c3eed5cSTejun Heo 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool;
7367a22ad75STejun Heo 
7377c3eed5cSTejun Heo 	pool_id = data >> WORK_OFFQ_POOL_SHIFT;
7387c3eed5cSTejun Heo 	if (pool_id == WORK_OFFQ_POOL_NONE)
7397a22ad75STejun Heo 		return NULL;
7407a22ad75STejun Heo 
741fa1b54e6STejun Heo 	return idr_find(&worker_pool_idr, pool_id);
7427c3eed5cSTejun Heo }
7437c3eed5cSTejun Heo 
7447c3eed5cSTejun Heo /**
7457c3eed5cSTejun Heo  * get_work_pool_id - return the worker pool ID a given work is associated with
7467c3eed5cSTejun Heo  * @work: the work item of interest
7477c3eed5cSTejun Heo  *
748d185af30SYacine Belkadi  * Return: The worker_pool ID @work was last associated with.
7497c3eed5cSTejun Heo  * %WORK_OFFQ_POOL_NONE if none.
7507c3eed5cSTejun Heo  */
7517c3eed5cSTejun Heo static int get_work_pool_id(struct work_struct *work)
7527c3eed5cSTejun Heo {
75354d5b7d0SLai Jiangshan 	unsigned long data = atomic_long_read(&work->data);
7547c3eed5cSTejun Heo 
755112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
756112202d9STejun Heo 		return ((struct pool_workqueue *)
75754d5b7d0SLai Jiangshan 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
75854d5b7d0SLai Jiangshan 
75954d5b7d0SLai Jiangshan 	return data >> WORK_OFFQ_POOL_SHIFT;
7607c3eed5cSTejun Heo }
7617c3eed5cSTejun Heo 
762bbb68dfaSTejun Heo static void mark_work_canceling(struct work_struct *work)
763bbb68dfaSTejun Heo {
7647c3eed5cSTejun Heo 	unsigned long pool_id = get_work_pool_id(work);
765bbb68dfaSTejun Heo 
7667c3eed5cSTejun Heo 	pool_id <<= WORK_OFFQ_POOL_SHIFT;
7677c3eed5cSTejun Heo 	set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
768bbb68dfaSTejun Heo }
769bbb68dfaSTejun Heo 
770bbb68dfaSTejun Heo static bool work_is_canceling(struct work_struct *work)
771bbb68dfaSTejun Heo {
772bbb68dfaSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
773bbb68dfaSTejun Heo 
774112202d9STejun Heo 	return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
775bbb68dfaSTejun Heo }
776bbb68dfaSTejun Heo 
777e22bee78STejun Heo /*
7783270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
7793270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
780d565ed63STejun Heo  * they're being called with pool->lock held.
781e22bee78STejun Heo  */
782e22bee78STejun Heo 
78363d95a91STejun Heo static bool __need_more_worker(struct worker_pool *pool)
784649027d7STejun Heo {
785bc35f7efSLai Jiangshan 	return !pool->nr_running;
786649027d7STejun Heo }
787649027d7STejun Heo 
788e22bee78STejun Heo /*
789e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
790e22bee78STejun Heo  * running workers.
791974271c4STejun Heo  *
792974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
793706026c2STejun Heo  * function will always return %true for unbound pools as long as the
794974271c4STejun Heo  * worklist isn't empty.
795e22bee78STejun Heo  */
79663d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
797e22bee78STejun Heo {
79863d95a91STejun Heo 	return !list_empty(&pool->worklist) && __need_more_worker(pool);
799e22bee78STejun Heo }
800e22bee78STejun Heo 
801e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
80263d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
803e22bee78STejun Heo {
80463d95a91STejun Heo 	return pool->nr_idle;
805e22bee78STejun Heo }
806e22bee78STejun Heo 
807e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
80863d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
809e22bee78STejun Heo {
810bc35f7efSLai Jiangshan 	return !list_empty(&pool->worklist) && (pool->nr_running <= 1);
811e22bee78STejun Heo }
812e22bee78STejun Heo 
813e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
81463d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
815e22bee78STejun Heo {
81663d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
817e22bee78STejun Heo }
818e22bee78STejun Heo 
819e22bee78STejun Heo /* Do we have too many workers and should some go away? */
82063d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
821e22bee78STejun Heo {
822692b4825STejun Heo 	bool managing = pool->flags & POOL_MANAGER_ACTIVE;
82363d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
82463d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
825e22bee78STejun Heo 
826e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
827e22bee78STejun Heo }
828e22bee78STejun Heo 
829e22bee78STejun Heo /*
830e22bee78STejun Heo  * Wake up functions.
831e22bee78STejun Heo  */
832e22bee78STejun Heo 
8332c1f1a91SLai Jiangshan /* Return the first idle worker.  Called with pool->lock held. */
8341037de36SLai Jiangshan static struct worker *first_idle_worker(struct worker_pool *pool)
8357e11629dSTejun Heo {
83663d95a91STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
8377e11629dSTejun Heo 		return NULL;
8387e11629dSTejun Heo 
83963d95a91STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
8407e11629dSTejun Heo }
8417e11629dSTejun Heo 
8427e11629dSTejun Heo /**
8437e11629dSTejun Heo  * wake_up_worker - wake up an idle worker
84463d95a91STejun Heo  * @pool: worker pool to wake worker from
8457e11629dSTejun Heo  *
84663d95a91STejun Heo  * Wake up the first idle worker of @pool.
8477e11629dSTejun Heo  *
8487e11629dSTejun Heo  * CONTEXT:
849a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
8507e11629dSTejun Heo  */
85163d95a91STejun Heo static void wake_up_worker(struct worker_pool *pool)
8527e11629dSTejun Heo {
8531037de36SLai Jiangshan 	struct worker *worker = first_idle_worker(pool);
8547e11629dSTejun Heo 
8557e11629dSTejun Heo 	if (likely(worker))
8567e11629dSTejun Heo 		wake_up_process(worker->task);
8577e11629dSTejun Heo }
8587e11629dSTejun Heo 
8594690c4abSTejun Heo /**
8606d25be57SThomas Gleixner  * wq_worker_running - a worker is running again
861e22bee78STejun Heo  * @task: task waking up
862e22bee78STejun Heo  *
8636d25be57SThomas Gleixner  * This function is called when a worker returns from schedule()
864e22bee78STejun Heo  */
8656d25be57SThomas Gleixner void wq_worker_running(struct task_struct *task)
866e22bee78STejun Heo {
867e22bee78STejun Heo 	struct worker *worker = kthread_data(task);
868e22bee78STejun Heo 
8696d25be57SThomas Gleixner 	if (!worker->sleeping)
8706d25be57SThomas Gleixner 		return;
87107edfeceSFrederic Weisbecker 
87207edfeceSFrederic Weisbecker 	/*
87307edfeceSFrederic Weisbecker 	 * If preempted by unbind_workers() between the WORKER_NOT_RUNNING check
87407edfeceSFrederic Weisbecker 	 * and the nr_running increment below, we may ruin the nr_running reset
87507edfeceSFrederic Weisbecker 	 * and leave with an unexpected pool->nr_running == 1 on the newly unbound
87607edfeceSFrederic Weisbecker 	 * pool. Protect against such race.
87707edfeceSFrederic Weisbecker 	 */
87807edfeceSFrederic Weisbecker 	preempt_disable();
8796d25be57SThomas Gleixner 	if (!(worker->flags & WORKER_NOT_RUNNING))
880bc35f7efSLai Jiangshan 		worker->pool->nr_running++;
88107edfeceSFrederic Weisbecker 	preempt_enable();
8826d25be57SThomas Gleixner 	worker->sleeping = 0;
88336576000SJoonsoo Kim }
884e22bee78STejun Heo 
885e22bee78STejun Heo /**
886e22bee78STejun Heo  * wq_worker_sleeping - a worker is going to sleep
887e22bee78STejun Heo  * @task: task going to sleep
888e22bee78STejun Heo  *
8896d25be57SThomas Gleixner  * This function is called from schedule() when a busy worker is
890ccf45156SLai Jiangshan  * going to sleep.
891e22bee78STejun Heo  */
8926d25be57SThomas Gleixner void wq_worker_sleeping(struct task_struct *task)
893e22bee78STejun Heo {
894cc5bff38SLai Jiangshan 	struct worker *worker = kthread_data(task);
895111c225aSTejun Heo 	struct worker_pool *pool;
896e22bee78STejun Heo 
897111c225aSTejun Heo 	/*
898111c225aSTejun Heo 	 * Rescuers, which may not have all the fields set up like normal
899111c225aSTejun Heo 	 * workers, also reach here, let's not access anything before
900111c225aSTejun Heo 	 * checking NOT_RUNNING.
901111c225aSTejun Heo 	 */
9022d64672eSSteven Rostedt 	if (worker->flags & WORKER_NOT_RUNNING)
9036d25be57SThomas Gleixner 		return;
904e22bee78STejun Heo 
905111c225aSTejun Heo 	pool = worker->pool;
906111c225aSTejun Heo 
90762849a96SSebastian Andrzej Siewior 	/* Return if preempted before wq_worker_running() was reached */
90862849a96SSebastian Andrzej Siewior 	if (worker->sleeping)
9096d25be57SThomas Gleixner 		return;
9106d25be57SThomas Gleixner 
9116d25be57SThomas Gleixner 	worker->sleeping = 1;
912a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
913e22bee78STejun Heo 
914e22bee78STejun Heo 	/*
91545c753f5SFrederic Weisbecker 	 * Recheck in case unbind_workers() preempted us. We don't
91645c753f5SFrederic Weisbecker 	 * want to decrement nr_running after the worker is unbound
91745c753f5SFrederic Weisbecker 	 * and nr_running has been reset.
91845c753f5SFrederic Weisbecker 	 */
91945c753f5SFrederic Weisbecker 	if (worker->flags & WORKER_NOT_RUNNING) {
92045c753f5SFrederic Weisbecker 		raw_spin_unlock_irq(&pool->lock);
92145c753f5SFrederic Weisbecker 		return;
92245c753f5SFrederic Weisbecker 	}
92345c753f5SFrederic Weisbecker 
924bc35f7efSLai Jiangshan 	pool->nr_running--;
925bc35f7efSLai Jiangshan 	if (need_more_worker(pool))
926cc5bff38SLai Jiangshan 		wake_up_worker(pool);
927a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
928e22bee78STejun Heo }
929e22bee78STejun Heo 
930e22bee78STejun Heo /**
9311b69ac6bSJohannes Weiner  * wq_worker_last_func - retrieve worker's last work function
9328194fe94SBart Van Assche  * @task: Task to retrieve last work function of.
9331b69ac6bSJohannes Weiner  *
9341b69ac6bSJohannes Weiner  * Determine the last function a worker executed. This is called from
9351b69ac6bSJohannes Weiner  * the scheduler to get a worker's last known identity.
9361b69ac6bSJohannes Weiner  *
9371b69ac6bSJohannes Weiner  * CONTEXT:
938a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(rq->lock)
9391b69ac6bSJohannes Weiner  *
9404b047002SJohannes Weiner  * This function is called during schedule() when a kworker is going
9414b047002SJohannes Weiner  * to sleep. It's used by psi to identify aggregation workers during
9424b047002SJohannes Weiner  * dequeuing, to allow periodic aggregation to shut-off when that
9434b047002SJohannes Weiner  * worker is the last task in the system or cgroup to go to sleep.
9444b047002SJohannes Weiner  *
9454b047002SJohannes Weiner  * As this function doesn't involve any workqueue-related locking, it
9464b047002SJohannes Weiner  * only returns stable values when called from inside the scheduler's
9474b047002SJohannes Weiner  * queuing and dequeuing paths, when @task, which must be a kworker,
9484b047002SJohannes Weiner  * is guaranteed to not be processing any works.
9494b047002SJohannes Weiner  *
9501b69ac6bSJohannes Weiner  * Return:
9511b69ac6bSJohannes Weiner  * The last work function %current executed as a worker, NULL if it
9521b69ac6bSJohannes Weiner  * hasn't executed any work yet.
9531b69ac6bSJohannes Weiner  */
9541b69ac6bSJohannes Weiner work_func_t wq_worker_last_func(struct task_struct *task)
9551b69ac6bSJohannes Weiner {
9561b69ac6bSJohannes Weiner 	struct worker *worker = kthread_data(task);
9571b69ac6bSJohannes Weiner 
9581b69ac6bSJohannes Weiner 	return worker->last_func;
9591b69ac6bSJohannes Weiner }
9601b69ac6bSJohannes Weiner 
9611b69ac6bSJohannes Weiner /**
962e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
963cb444766STejun Heo  * @worker: self
964d302f017STejun Heo  * @flags: flags to set
965d302f017STejun Heo  *
966228f1d00SLai Jiangshan  * Set @flags in @worker->flags and adjust nr_running accordingly.
967d302f017STejun Heo  *
968cb444766STejun Heo  * CONTEXT:
969a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock)
970d302f017STejun Heo  */
971228f1d00SLai Jiangshan static inline void worker_set_flags(struct worker *worker, unsigned int flags)
972d302f017STejun Heo {
973bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
974e22bee78STejun Heo 
975cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
976cb444766STejun Heo 
977228f1d00SLai Jiangshan 	/* If transitioning into NOT_RUNNING, adjust nr_running. */
978e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
979e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
980bc35f7efSLai Jiangshan 		pool->nr_running--;
981e22bee78STejun Heo 	}
982e22bee78STejun Heo 
983d302f017STejun Heo 	worker->flags |= flags;
984d302f017STejun Heo }
985d302f017STejun Heo 
986d302f017STejun Heo /**
987e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
988cb444766STejun Heo  * @worker: self
989d302f017STejun Heo  * @flags: flags to clear
990d302f017STejun Heo  *
991e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
992d302f017STejun Heo  *
993cb444766STejun Heo  * CONTEXT:
994a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock)
995d302f017STejun Heo  */
996d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
997d302f017STejun Heo {
99863d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
999e22bee78STejun Heo 	unsigned int oflags = worker->flags;
1000e22bee78STejun Heo 
1001cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
1002cb444766STejun Heo 
1003d302f017STejun Heo 	worker->flags &= ~flags;
1004e22bee78STejun Heo 
100542c025f3STejun Heo 	/*
100642c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
100742c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
100842c025f3STejun Heo 	 * of multiple flags, not a single flag.
100942c025f3STejun Heo 	 */
1010e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
1011e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
1012bc35f7efSLai Jiangshan 			pool->nr_running++;
1013d302f017STejun Heo }
1014d302f017STejun Heo 
1015d302f017STejun Heo /**
10168cca0eeaSTejun Heo  * find_worker_executing_work - find worker which is executing a work
1017c9e7cf27STejun Heo  * @pool: pool of interest
10188cca0eeaSTejun Heo  * @work: work to find worker for
10198cca0eeaSTejun Heo  *
1020c9e7cf27STejun Heo  * Find a worker which is executing @work on @pool by searching
1021c9e7cf27STejun Heo  * @pool->busy_hash which is keyed by the address of @work.  For a worker
1022a2c1c57bSTejun Heo  * to match, its current execution should match the address of @work and
1023a2c1c57bSTejun Heo  * its work function.  This is to avoid unwanted dependency between
1024a2c1c57bSTejun Heo  * unrelated work executions through a work item being recycled while still
1025a2c1c57bSTejun Heo  * being executed.
1026a2c1c57bSTejun Heo  *
1027a2c1c57bSTejun Heo  * This is a bit tricky.  A work item may be freed once its execution
1028a2c1c57bSTejun Heo  * starts and nothing prevents the freed area from being recycled for
1029a2c1c57bSTejun Heo  * another work item.  If the same work item address ends up being reused
1030a2c1c57bSTejun Heo  * before the original execution finishes, workqueue will identify the
1031a2c1c57bSTejun Heo  * recycled work item as currently executing and make it wait until the
1032a2c1c57bSTejun Heo  * current execution finishes, introducing an unwanted dependency.
1033a2c1c57bSTejun Heo  *
1034c5aa87bbSTejun Heo  * This function checks the work item address and work function to avoid
1035c5aa87bbSTejun Heo  * false positives.  Note that this isn't complete as one may construct a
1036c5aa87bbSTejun Heo  * work function which can introduce dependency onto itself through a
1037c5aa87bbSTejun Heo  * recycled work item.  Well, if somebody wants to shoot oneself in the
1038c5aa87bbSTejun Heo  * foot that badly, there's only so much we can do, and if such deadlock
1039c5aa87bbSTejun Heo  * actually occurs, it should be easy to locate the culprit work function.
10408cca0eeaSTejun Heo  *
10418cca0eeaSTejun Heo  * CONTEXT:
1042a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
10438cca0eeaSTejun Heo  *
1044d185af30SYacine Belkadi  * Return:
1045d185af30SYacine Belkadi  * Pointer to worker which is executing @work if found, %NULL
10468cca0eeaSTejun Heo  * otherwise.
10478cca0eeaSTejun Heo  */
1048c9e7cf27STejun Heo static struct worker *find_worker_executing_work(struct worker_pool *pool,
10498cca0eeaSTejun Heo 						 struct work_struct *work)
10508cca0eeaSTejun Heo {
105142f8570fSSasha Levin 	struct worker *worker;
105242f8570fSSasha Levin 
1053b67bfe0dSSasha Levin 	hash_for_each_possible(pool->busy_hash, worker, hentry,
1054a2c1c57bSTejun Heo 			       (unsigned long)work)
1055a2c1c57bSTejun Heo 		if (worker->current_work == work &&
1056a2c1c57bSTejun Heo 		    worker->current_func == work->func)
105742f8570fSSasha Levin 			return worker;
105842f8570fSSasha Levin 
105942f8570fSSasha Levin 	return NULL;
10608cca0eeaSTejun Heo }
10618cca0eeaSTejun Heo 
10628cca0eeaSTejun Heo /**
1063bf4ede01STejun Heo  * move_linked_works - move linked works to a list
1064bf4ede01STejun Heo  * @work: start of series of works to be scheduled
1065bf4ede01STejun Heo  * @head: target list to append @work to
1066402dd89dSShailendra Verma  * @nextp: out parameter for nested worklist walking
1067bf4ede01STejun Heo  *
1068bf4ede01STejun Heo  * Schedule linked works starting from @work to @head.  Work series to
1069bf4ede01STejun Heo  * be scheduled starts at @work and includes any consecutive work with
1070bf4ede01STejun Heo  * WORK_STRUCT_LINKED set in its predecessor.
1071bf4ede01STejun Heo  *
1072bf4ede01STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of
1073bf4ede01STejun Heo  * the last scheduled work.  This allows move_linked_works() to be
1074bf4ede01STejun Heo  * nested inside outer list_for_each_entry_safe().
1075bf4ede01STejun Heo  *
1076bf4ede01STejun Heo  * CONTEXT:
1077a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1078bf4ede01STejun Heo  */
1079bf4ede01STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
1080bf4ede01STejun Heo 			      struct work_struct **nextp)
1081bf4ede01STejun Heo {
1082bf4ede01STejun Heo 	struct work_struct *n;
1083bf4ede01STejun Heo 
1084bf4ede01STejun Heo 	/*
1085bf4ede01STejun Heo 	 * Linked worklist will always end before the end of the list,
1086bf4ede01STejun Heo 	 * use NULL for list head.
1087bf4ede01STejun Heo 	 */
1088bf4ede01STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
1089bf4ede01STejun Heo 		list_move_tail(&work->entry, head);
1090bf4ede01STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1091bf4ede01STejun Heo 			break;
1092bf4ede01STejun Heo 	}
1093bf4ede01STejun Heo 
1094bf4ede01STejun Heo 	/*
1095bf4ede01STejun Heo 	 * If we're already inside safe list traversal and have moved
1096bf4ede01STejun Heo 	 * multiple works to the scheduled queue, the next position
1097bf4ede01STejun Heo 	 * needs to be updated.
1098bf4ede01STejun Heo 	 */
1099bf4ede01STejun Heo 	if (nextp)
1100bf4ede01STejun Heo 		*nextp = n;
1101bf4ede01STejun Heo }
1102bf4ede01STejun Heo 
11038864b4e5STejun Heo /**
11048864b4e5STejun Heo  * get_pwq - get an extra reference on the specified pool_workqueue
11058864b4e5STejun Heo  * @pwq: pool_workqueue to get
11068864b4e5STejun Heo  *
11078864b4e5STejun Heo  * Obtain an extra reference on @pwq.  The caller should guarantee that
11088864b4e5STejun Heo  * @pwq has positive refcnt and be holding the matching pool->lock.
11098864b4e5STejun Heo  */
11108864b4e5STejun Heo static void get_pwq(struct pool_workqueue *pwq)
11118864b4e5STejun Heo {
11128864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
11138864b4e5STejun Heo 	WARN_ON_ONCE(pwq->refcnt <= 0);
11148864b4e5STejun Heo 	pwq->refcnt++;
11158864b4e5STejun Heo }
11168864b4e5STejun Heo 
11178864b4e5STejun Heo /**
11188864b4e5STejun Heo  * put_pwq - put a pool_workqueue reference
11198864b4e5STejun Heo  * @pwq: pool_workqueue to put
11208864b4e5STejun Heo  *
11218864b4e5STejun Heo  * Drop a reference of @pwq.  If its refcnt reaches zero, schedule its
11228864b4e5STejun Heo  * destruction.  The caller should be holding the matching pool->lock.
11238864b4e5STejun Heo  */
11248864b4e5STejun Heo static void put_pwq(struct pool_workqueue *pwq)
11258864b4e5STejun Heo {
11268864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
11278864b4e5STejun Heo 	if (likely(--pwq->refcnt))
11288864b4e5STejun Heo 		return;
11298864b4e5STejun Heo 	if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
11308864b4e5STejun Heo 		return;
11318864b4e5STejun Heo 	/*
11328864b4e5STejun Heo 	 * @pwq can't be released under pool->lock, bounce to
11338864b4e5STejun Heo 	 * pwq_unbound_release_workfn().  This never recurses on the same
11348864b4e5STejun Heo 	 * pool->lock as this path is taken only for unbound workqueues and
11358864b4e5STejun Heo 	 * the release work item is scheduled on a per-cpu workqueue.  To
11368864b4e5STejun Heo 	 * avoid lockdep warning, unbound pool->locks are given lockdep
11378864b4e5STejun Heo 	 * subclass of 1 in get_unbound_pool().
11388864b4e5STejun Heo 	 */
11398864b4e5STejun Heo 	schedule_work(&pwq->unbound_release_work);
11408864b4e5STejun Heo }
11418864b4e5STejun Heo 
1142dce90d47STejun Heo /**
1143dce90d47STejun Heo  * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1144dce90d47STejun Heo  * @pwq: pool_workqueue to put (can be %NULL)
1145dce90d47STejun Heo  *
1146dce90d47STejun Heo  * put_pwq() with locking.  This function also allows %NULL @pwq.
1147dce90d47STejun Heo  */
1148dce90d47STejun Heo static void put_pwq_unlocked(struct pool_workqueue *pwq)
1149dce90d47STejun Heo {
1150dce90d47STejun Heo 	if (pwq) {
1151dce90d47STejun Heo 		/*
115224acfb71SThomas Gleixner 		 * As both pwqs and pools are RCU protected, the
1153dce90d47STejun Heo 		 * following lock operations are safe.
1154dce90d47STejun Heo 		 */
1155a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
1156dce90d47STejun Heo 		put_pwq(pwq);
1157a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
1158dce90d47STejun Heo 	}
1159dce90d47STejun Heo }
1160dce90d47STejun Heo 
1161f97a4a1aSLai Jiangshan static void pwq_activate_inactive_work(struct work_struct *work)
1162bf4ede01STejun Heo {
1163112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1164bf4ede01STejun Heo 
1165bf4ede01STejun Heo 	trace_workqueue_activate_work(work);
116682607adcSTejun Heo 	if (list_empty(&pwq->pool->worklist))
116782607adcSTejun Heo 		pwq->pool->watchdog_ts = jiffies;
1168112202d9STejun Heo 	move_linked_works(work, &pwq->pool->worklist, NULL);
1169f97a4a1aSLai Jiangshan 	__clear_bit(WORK_STRUCT_INACTIVE_BIT, work_data_bits(work));
1170112202d9STejun Heo 	pwq->nr_active++;
1171bf4ede01STejun Heo }
1172bf4ede01STejun Heo 
1173f97a4a1aSLai Jiangshan static void pwq_activate_first_inactive(struct pool_workqueue *pwq)
11743aa62497SLai Jiangshan {
1175f97a4a1aSLai Jiangshan 	struct work_struct *work = list_first_entry(&pwq->inactive_works,
11763aa62497SLai Jiangshan 						    struct work_struct, entry);
11773aa62497SLai Jiangshan 
1178f97a4a1aSLai Jiangshan 	pwq_activate_inactive_work(work);
11793aa62497SLai Jiangshan }
11803aa62497SLai Jiangshan 
1181bf4ede01STejun Heo /**
1182112202d9STejun Heo  * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1183112202d9STejun Heo  * @pwq: pwq of interest
1184c4560c2cSLai Jiangshan  * @work_data: work_data of work which left the queue
1185bf4ede01STejun Heo  *
1186bf4ede01STejun Heo  * A work either has completed or is removed from pending queue,
1187112202d9STejun Heo  * decrement nr_in_flight of its pwq and handle workqueue flushing.
1188bf4ede01STejun Heo  *
1189bf4ede01STejun Heo  * CONTEXT:
1190a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1191bf4ede01STejun Heo  */
1192c4560c2cSLai Jiangshan static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data)
1193bf4ede01STejun Heo {
1194c4560c2cSLai Jiangshan 	int color = get_work_color(work_data);
1195c4560c2cSLai Jiangshan 
1196018f3a13SLai Jiangshan 	if (!(work_data & WORK_STRUCT_INACTIVE)) {
1197112202d9STejun Heo 		pwq->nr_active--;
1198f97a4a1aSLai Jiangshan 		if (!list_empty(&pwq->inactive_works)) {
1199f97a4a1aSLai Jiangshan 			/* one down, submit an inactive one */
1200112202d9STejun Heo 			if (pwq->nr_active < pwq->max_active)
1201f97a4a1aSLai Jiangshan 				pwq_activate_first_inactive(pwq);
1202bf4ede01STejun Heo 		}
1203018f3a13SLai Jiangshan 	}
1204018f3a13SLai Jiangshan 
1205018f3a13SLai Jiangshan 	pwq->nr_in_flight[color]--;
1206bf4ede01STejun Heo 
1207bf4ede01STejun Heo 	/* is flush in progress and are we at the flushing tip? */
1208112202d9STejun Heo 	if (likely(pwq->flush_color != color))
12098864b4e5STejun Heo 		goto out_put;
1210bf4ede01STejun Heo 
1211bf4ede01STejun Heo 	/* are there still in-flight works? */
1212112202d9STejun Heo 	if (pwq->nr_in_flight[color])
12138864b4e5STejun Heo 		goto out_put;
1214bf4ede01STejun Heo 
1215112202d9STejun Heo 	/* this pwq is done, clear flush_color */
1216112202d9STejun Heo 	pwq->flush_color = -1;
1217bf4ede01STejun Heo 
1218bf4ede01STejun Heo 	/*
1219112202d9STejun Heo 	 * If this was the last pwq, wake up the first flusher.  It
1220bf4ede01STejun Heo 	 * will handle the rest.
1221bf4ede01STejun Heo 	 */
1222112202d9STejun Heo 	if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1223112202d9STejun Heo 		complete(&pwq->wq->first_flusher->done);
12248864b4e5STejun Heo out_put:
12258864b4e5STejun Heo 	put_pwq(pwq);
1226bf4ede01STejun Heo }
1227bf4ede01STejun Heo 
122836e227d2STejun Heo /**
1229bbb68dfaSTejun Heo  * try_to_grab_pending - steal work item from worklist and disable irq
123036e227d2STejun Heo  * @work: work item to steal
123136e227d2STejun Heo  * @is_dwork: @work is a delayed_work
1232bbb68dfaSTejun Heo  * @flags: place to store irq state
123336e227d2STejun Heo  *
123436e227d2STejun Heo  * Try to grab PENDING bit of @work.  This function can handle @work in any
1235d185af30SYacine Belkadi  * stable state - idle, on timer or on worklist.
123636e227d2STejun Heo  *
1237d185af30SYacine Belkadi  * Return:
12383eb6b31bSMauro Carvalho Chehab  *
12393eb6b31bSMauro Carvalho Chehab  *  ========	================================================================
124036e227d2STejun Heo  *  1		if @work was pending and we successfully stole PENDING
124136e227d2STejun Heo  *  0		if @work was idle and we claimed PENDING
124236e227d2STejun Heo  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
1243bbb68dfaSTejun Heo  *  -ENOENT	if someone else is canceling @work, this state may persist
1244bbb68dfaSTejun Heo  *		for arbitrarily long
12453eb6b31bSMauro Carvalho Chehab  *  ========	================================================================
124636e227d2STejun Heo  *
1247d185af30SYacine Belkadi  * Note:
1248bbb68dfaSTejun Heo  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
1249e0aecdd8STejun Heo  * interrupted while holding PENDING and @work off queue, irq must be
1250e0aecdd8STejun Heo  * disabled on entry.  This, combined with delayed_work->timer being
1251e0aecdd8STejun Heo  * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1252bbb68dfaSTejun Heo  *
1253bbb68dfaSTejun Heo  * On successful return, >= 0, irq is disabled and the caller is
1254bbb68dfaSTejun Heo  * responsible for releasing it using local_irq_restore(*@flags).
1255bbb68dfaSTejun Heo  *
1256e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
1257bf4ede01STejun Heo  */
1258bbb68dfaSTejun Heo static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1259bbb68dfaSTejun Heo 			       unsigned long *flags)
1260bf4ede01STejun Heo {
1261d565ed63STejun Heo 	struct worker_pool *pool;
1262112202d9STejun Heo 	struct pool_workqueue *pwq;
1263bf4ede01STejun Heo 
1264bbb68dfaSTejun Heo 	local_irq_save(*flags);
1265bbb68dfaSTejun Heo 
126636e227d2STejun Heo 	/* try to steal the timer if it exists */
126736e227d2STejun Heo 	if (is_dwork) {
126836e227d2STejun Heo 		struct delayed_work *dwork = to_delayed_work(work);
126936e227d2STejun Heo 
1270e0aecdd8STejun Heo 		/*
1271e0aecdd8STejun Heo 		 * dwork->timer is irqsafe.  If del_timer() fails, it's
1272e0aecdd8STejun Heo 		 * guaranteed that the timer is not queued anywhere and not
1273e0aecdd8STejun Heo 		 * running on the local CPU.
1274e0aecdd8STejun Heo 		 */
127536e227d2STejun Heo 		if (likely(del_timer(&dwork->timer)))
127636e227d2STejun Heo 			return 1;
127736e227d2STejun Heo 	}
127836e227d2STejun Heo 
127936e227d2STejun Heo 	/* try to claim PENDING the normal way */
1280bf4ede01STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1281bf4ede01STejun Heo 		return 0;
1282bf4ede01STejun Heo 
128324acfb71SThomas Gleixner 	rcu_read_lock();
1284bf4ede01STejun Heo 	/*
1285bf4ede01STejun Heo 	 * The queueing is in progress, or it is already queued. Try to
1286bf4ede01STejun Heo 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1287bf4ede01STejun Heo 	 */
1288d565ed63STejun Heo 	pool = get_work_pool(work);
1289d565ed63STejun Heo 	if (!pool)
1290bbb68dfaSTejun Heo 		goto fail;
1291bf4ede01STejun Heo 
1292a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock(&pool->lock);
1293bf4ede01STejun Heo 	/*
1294112202d9STejun Heo 	 * work->data is guaranteed to point to pwq only while the work
1295112202d9STejun Heo 	 * item is queued on pwq->wq, and both updating work->data to point
1296112202d9STejun Heo 	 * to pwq on queueing and to pool on dequeueing are done under
1297112202d9STejun Heo 	 * pwq->pool->lock.  This in turn guarantees that, if work->data
1298112202d9STejun Heo 	 * points to pwq which is associated with a locked pool, the work
12990b3dae68SLai Jiangshan 	 * item is currently queued on that pool.
1300bf4ede01STejun Heo 	 */
1301112202d9STejun Heo 	pwq = get_work_pwq(work);
1302112202d9STejun Heo 	if (pwq && pwq->pool == pool) {
1303bf4ede01STejun Heo 		debug_work_deactivate(work);
13043aa62497SLai Jiangshan 
13053aa62497SLai Jiangshan 		/*
1306018f3a13SLai Jiangshan 		 * A cancelable inactive work item must be in the
1307018f3a13SLai Jiangshan 		 * pwq->inactive_works since a queued barrier can't be
1308018f3a13SLai Jiangshan 		 * canceled (see the comments in insert_wq_barrier()).
1309018f3a13SLai Jiangshan 		 *
1310f97a4a1aSLai Jiangshan 		 * An inactive work item cannot be grabbed directly because
1311d812796eSLai Jiangshan 		 * it might have linked barrier work items which, if left
1312f97a4a1aSLai Jiangshan 		 * on the inactive_works list, will confuse pwq->nr_active
131316062836STejun Heo 		 * management later on and cause stall.  Make sure the work
131416062836STejun Heo 		 * item is activated before grabbing.
13153aa62497SLai Jiangshan 		 */
1316f97a4a1aSLai Jiangshan 		if (*work_data_bits(work) & WORK_STRUCT_INACTIVE)
1317f97a4a1aSLai Jiangshan 			pwq_activate_inactive_work(work);
13183aa62497SLai Jiangshan 
1319bf4ede01STejun Heo 		list_del_init(&work->entry);
1320c4560c2cSLai Jiangshan 		pwq_dec_nr_in_flight(pwq, *work_data_bits(work));
132136e227d2STejun Heo 
1322112202d9STejun Heo 		/* work->data points to pwq iff queued, point to pool */
13234468a00fSLai Jiangshan 		set_work_pool_and_keep_pending(work, pool->id);
13244468a00fSLai Jiangshan 
1325a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock(&pool->lock);
132624acfb71SThomas Gleixner 		rcu_read_unlock();
132736e227d2STejun Heo 		return 1;
1328bf4ede01STejun Heo 	}
1329a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&pool->lock);
1330bbb68dfaSTejun Heo fail:
133124acfb71SThomas Gleixner 	rcu_read_unlock();
1332bbb68dfaSTejun Heo 	local_irq_restore(*flags);
1333bbb68dfaSTejun Heo 	if (work_is_canceling(work))
1334bbb68dfaSTejun Heo 		return -ENOENT;
1335bbb68dfaSTejun Heo 	cpu_relax();
133636e227d2STejun Heo 	return -EAGAIN;
1337bf4ede01STejun Heo }
1338bf4ede01STejun Heo 
1339bf4ede01STejun Heo /**
1340706026c2STejun Heo  * insert_work - insert a work into a pool
1341112202d9STejun Heo  * @pwq: pwq @work belongs to
13424690c4abSTejun Heo  * @work: work to insert
13434690c4abSTejun Heo  * @head: insertion point
13444690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
13454690c4abSTejun Heo  *
1346112202d9STejun Heo  * Insert @work which belongs to @pwq after @head.  @extra_flags is or'd to
1347706026c2STejun Heo  * work_struct flags.
13484690c4abSTejun Heo  *
13494690c4abSTejun Heo  * CONTEXT:
1350a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1351365970a1SDavid Howells  */
1352112202d9STejun Heo static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1353112202d9STejun Heo 			struct list_head *head, unsigned int extra_flags)
1354b89deed3SOleg Nesterov {
1355112202d9STejun Heo 	struct worker_pool *pool = pwq->pool;
1356e1d8aa9fSFrederic Weisbecker 
1357e89a85d6SWalter Wu 	/* record the work call stack in order to print it in KASAN reports */
1358f70da745SMarco Elver 	kasan_record_aux_stack_noalloc(work);
1359e89a85d6SWalter Wu 
13604690c4abSTejun Heo 	/* we own @work, set data and link */
1361112202d9STejun Heo 	set_work_pwq(work, pwq, extra_flags);
13621a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
13638864b4e5STejun Heo 	get_pwq(pwq);
1364e22bee78STejun Heo 
136563d95a91STejun Heo 	if (__need_more_worker(pool))
136663d95a91STejun Heo 		wake_up_worker(pool);
1367b89deed3SOleg Nesterov }
1368b89deed3SOleg Nesterov 
1369c8efcc25STejun Heo /*
1370c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
13718d03ecfeSTejun Heo  * same workqueue.
1372c8efcc25STejun Heo  */
1373c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
1374c8efcc25STejun Heo {
1375c8efcc25STejun Heo 	struct worker *worker;
1376c8efcc25STejun Heo 
13778d03ecfeSTejun Heo 	worker = current_wq_worker();
1378c8efcc25STejun Heo 	/*
1379bf393fd4SBart Van Assche 	 * Return %true iff I'm a worker executing a work item on @wq.  If
13808d03ecfeSTejun Heo 	 * I'm @worker, it's safe to dereference it without locking.
1381c8efcc25STejun Heo 	 */
1382112202d9STejun Heo 	return worker && worker->current_pwq->wq == wq;
1383c8efcc25STejun Heo }
1384c8efcc25STejun Heo 
1385ef557180SMike Galbraith /*
1386ef557180SMike Galbraith  * When queueing an unbound work item to a wq, prefer local CPU if allowed
1387ef557180SMike Galbraith  * by wq_unbound_cpumask.  Otherwise, round robin among the allowed ones to
1388ef557180SMike Galbraith  * avoid perturbing sensitive tasks.
1389ef557180SMike Galbraith  */
1390ef557180SMike Galbraith static int wq_select_unbound_cpu(int cpu)
1391ef557180SMike Galbraith {
1392f303fccbSTejun Heo 	static bool printed_dbg_warning;
1393ef557180SMike Galbraith 	int new_cpu;
1394ef557180SMike Galbraith 
1395f303fccbSTejun Heo 	if (likely(!wq_debug_force_rr_cpu)) {
1396ef557180SMike Galbraith 		if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
1397ef557180SMike Galbraith 			return cpu;
1398f303fccbSTejun Heo 	} else if (!printed_dbg_warning) {
1399f303fccbSTejun Heo 		pr_warn("workqueue: round-robin CPU selection forced, expect performance impact\n");
1400f303fccbSTejun Heo 		printed_dbg_warning = true;
1401f303fccbSTejun Heo 	}
1402f303fccbSTejun Heo 
1403ef557180SMike Galbraith 	if (cpumask_empty(wq_unbound_cpumask))
1404ef557180SMike Galbraith 		return cpu;
1405ef557180SMike Galbraith 
1406ef557180SMike Galbraith 	new_cpu = __this_cpu_read(wq_rr_cpu_last);
1407ef557180SMike Galbraith 	new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
1408ef557180SMike Galbraith 	if (unlikely(new_cpu >= nr_cpu_ids)) {
1409ef557180SMike Galbraith 		new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
1410ef557180SMike Galbraith 		if (unlikely(new_cpu >= nr_cpu_ids))
1411ef557180SMike Galbraith 			return cpu;
1412ef557180SMike Galbraith 	}
1413ef557180SMike Galbraith 	__this_cpu_write(wq_rr_cpu_last, new_cpu);
1414ef557180SMike Galbraith 
1415ef557180SMike Galbraith 	return new_cpu;
1416ef557180SMike Galbraith }
1417ef557180SMike Galbraith 
1418d84ff051STejun Heo static void __queue_work(int cpu, struct workqueue_struct *wq,
14191da177e4SLinus Torvalds 			 struct work_struct *work)
14201da177e4SLinus Torvalds {
1421112202d9STejun Heo 	struct pool_workqueue *pwq;
1422c9178087STejun Heo 	struct worker_pool *last_pool;
14231e19ffc6STejun Heo 	struct list_head *worklist;
14248a2e8e5dSTejun Heo 	unsigned int work_flags;
1425b75cac93SJoonsoo Kim 	unsigned int req_cpu = cpu;
14268930cabaSTejun Heo 
14278930cabaSTejun Heo 	/*
14288930cabaSTejun Heo 	 * While a work item is PENDING && off queue, a task trying to
14298930cabaSTejun Heo 	 * steal the PENDING will busy-loop waiting for it to either get
14308930cabaSTejun Heo 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
14318930cabaSTejun Heo 	 * happen with IRQ disabled.
14328930cabaSTejun Heo 	 */
14338e8eb730SFrederic Weisbecker 	lockdep_assert_irqs_disabled();
14341da177e4SLinus Torvalds 
14351e19ffc6STejun Heo 
143633e3f0a3SRichard Clark 	/*
143733e3f0a3SRichard Clark 	 * For a draining wq, only works from the same workqueue are
143833e3f0a3SRichard Clark 	 * allowed. The __WQ_DESTROYING helps to spot the issue that
143933e3f0a3SRichard Clark 	 * queues a new work item to a wq after destroy_workqueue(wq).
144033e3f0a3SRichard Clark 	 */
144133e3f0a3SRichard Clark 	if (unlikely(wq->flags & (__WQ_DESTROYING | __WQ_DRAINING) &&
144233e3f0a3SRichard Clark 		     WARN_ON_ONCE(!is_chained_work(wq))))
1443e41e704bSTejun Heo 		return;
144424acfb71SThomas Gleixner 	rcu_read_lock();
14459e8cd2f5STejun Heo retry:
1446aa202f1fSHillf Danton 	/* pwq which will be used unless @work is executing elsewhere */
1447aa202f1fSHillf Danton 	if (wq->flags & WQ_UNBOUND) {
1448df2d5ae4STejun Heo 		if (req_cpu == WORK_CPU_UNBOUND)
1449ef557180SMike Galbraith 			cpu = wq_select_unbound_cpu(raw_smp_processor_id());
1450df2d5ae4STejun Heo 		pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1451aa202f1fSHillf Danton 	} else {
1452aa202f1fSHillf Danton 		if (req_cpu == WORK_CPU_UNBOUND)
1453aa202f1fSHillf Danton 			cpu = raw_smp_processor_id();
1454aa202f1fSHillf Danton 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1455aa202f1fSHillf Danton 	}
1456f3421797STejun Heo 
145718aa9effSTejun Heo 	/*
1458c9178087STejun Heo 	 * If @work was previously on a different pool, it might still be
1459c9178087STejun Heo 	 * running there, in which case the work needs to be queued on that
1460c9178087STejun Heo 	 * pool to guarantee non-reentrancy.
146118aa9effSTejun Heo 	 */
1462c9e7cf27STejun Heo 	last_pool = get_work_pool(work);
1463112202d9STejun Heo 	if (last_pool && last_pool != pwq->pool) {
146418aa9effSTejun Heo 		struct worker *worker;
146518aa9effSTejun Heo 
1466a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock(&last_pool->lock);
146718aa9effSTejun Heo 
1468c9e7cf27STejun Heo 		worker = find_worker_executing_work(last_pool, work);
146918aa9effSTejun Heo 
1470112202d9STejun Heo 		if (worker && worker->current_pwq->wq == wq) {
1471c9178087STejun Heo 			pwq = worker->current_pwq;
14728594fadeSLai Jiangshan 		} else {
147318aa9effSTejun Heo 			/* meh... not running there, queue here */
1474a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock(&last_pool->lock);
1475a9b8a985SSebastian Andrzej Siewior 			raw_spin_lock(&pwq->pool->lock);
147618aa9effSTejun Heo 		}
14778930cabaSTejun Heo 	} else {
1478a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock(&pwq->pool->lock);
14798930cabaSTejun Heo 	}
1480502ca9d8STejun Heo 
14819e8cd2f5STejun Heo 	/*
14829e8cd2f5STejun Heo 	 * pwq is determined and locked.  For unbound pools, we could have
14839e8cd2f5STejun Heo 	 * raced with pwq release and it could already be dead.  If its
14849e8cd2f5STejun Heo 	 * refcnt is zero, repeat pwq selection.  Note that pwqs never die
1485df2d5ae4STejun Heo 	 * without another pwq replacing it in the numa_pwq_tbl or while
1486df2d5ae4STejun Heo 	 * work items are executing on it, so the retrying is guaranteed to
14879e8cd2f5STejun Heo 	 * make forward-progress.
14889e8cd2f5STejun Heo 	 */
14899e8cd2f5STejun Heo 	if (unlikely(!pwq->refcnt)) {
14909e8cd2f5STejun Heo 		if (wq->flags & WQ_UNBOUND) {
1491a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock(&pwq->pool->lock);
14929e8cd2f5STejun Heo 			cpu_relax();
14939e8cd2f5STejun Heo 			goto retry;
14949e8cd2f5STejun Heo 		}
14959e8cd2f5STejun Heo 		/* oops */
14969e8cd2f5STejun Heo 		WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
14979e8cd2f5STejun Heo 			  wq->name, cpu);
14989e8cd2f5STejun Heo 	}
14999e8cd2f5STejun Heo 
1500112202d9STejun Heo 	/* pwq determined, queue */
1501112202d9STejun Heo 	trace_workqueue_queue_work(req_cpu, pwq, work);
1502502ca9d8STejun Heo 
150324acfb71SThomas Gleixner 	if (WARN_ON(!list_empty(&work->entry)))
150424acfb71SThomas Gleixner 		goto out;
15051e19ffc6STejun Heo 
1506112202d9STejun Heo 	pwq->nr_in_flight[pwq->work_color]++;
1507112202d9STejun Heo 	work_flags = work_color_to_flags(pwq->work_color);
15081e19ffc6STejun Heo 
1509112202d9STejun Heo 	if (likely(pwq->nr_active < pwq->max_active)) {
1510cdadf009STejun Heo 		trace_workqueue_activate_work(work);
1511112202d9STejun Heo 		pwq->nr_active++;
1512112202d9STejun Heo 		worklist = &pwq->pool->worklist;
151382607adcSTejun Heo 		if (list_empty(worklist))
151482607adcSTejun Heo 			pwq->pool->watchdog_ts = jiffies;
15158a2e8e5dSTejun Heo 	} else {
1516f97a4a1aSLai Jiangshan 		work_flags |= WORK_STRUCT_INACTIVE;
1517f97a4a1aSLai Jiangshan 		worklist = &pwq->inactive_works;
15188a2e8e5dSTejun Heo 	}
15191e19ffc6STejun Heo 
15200687c66bSZqiang 	debug_work_activate(work);
1521112202d9STejun Heo 	insert_work(pwq, work, worklist, work_flags);
15221e19ffc6STejun Heo 
152324acfb71SThomas Gleixner out:
1524a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&pwq->pool->lock);
152524acfb71SThomas Gleixner 	rcu_read_unlock();
15261da177e4SLinus Torvalds }
15271da177e4SLinus Torvalds 
15280fcb78c2SRolf Eike Beer /**
1529c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
1530c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
1531c1a220e7SZhang Rui  * @wq: workqueue to use
1532c1a220e7SZhang Rui  * @work: work to queue
1533c1a220e7SZhang Rui  *
1534c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
1535443378f0SPaul E. McKenney  * can't go away.  Callers that fail to ensure that the specified
1536443378f0SPaul E. McKenney  * CPU cannot go away will execute on a randomly chosen CPU.
1537d185af30SYacine Belkadi  *
1538d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.
1539c1a220e7SZhang Rui  */
1540d4283e93STejun Heo bool queue_work_on(int cpu, struct workqueue_struct *wq,
1541d4283e93STejun Heo 		   struct work_struct *work)
1542c1a220e7SZhang Rui {
1543d4283e93STejun Heo 	bool ret = false;
15448930cabaSTejun Heo 	unsigned long flags;
15458930cabaSTejun Heo 
15468930cabaSTejun Heo 	local_irq_save(flags);
1547c1a220e7SZhang Rui 
154822df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
15494690c4abSTejun Heo 		__queue_work(cpu, wq, work);
1550d4283e93STejun Heo 		ret = true;
1551c1a220e7SZhang Rui 	}
15528930cabaSTejun Heo 
15538930cabaSTejun Heo 	local_irq_restore(flags);
1554c1a220e7SZhang Rui 	return ret;
1555c1a220e7SZhang Rui }
1556ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_work_on);
1557c1a220e7SZhang Rui 
15588204e0c1SAlexander Duyck /**
15598204e0c1SAlexander Duyck  * workqueue_select_cpu_near - Select a CPU based on NUMA node
15608204e0c1SAlexander Duyck  * @node: NUMA node ID that we want to select a CPU from
15618204e0c1SAlexander Duyck  *
15628204e0c1SAlexander Duyck  * This function will attempt to find a "random" cpu available on a given
15638204e0c1SAlexander Duyck  * node. If there are no CPUs available on the given node it will return
15648204e0c1SAlexander Duyck  * WORK_CPU_UNBOUND indicating that we should just schedule to any
15658204e0c1SAlexander Duyck  * available CPU if we need to schedule this work.
15668204e0c1SAlexander Duyck  */
15678204e0c1SAlexander Duyck static int workqueue_select_cpu_near(int node)
15688204e0c1SAlexander Duyck {
15698204e0c1SAlexander Duyck 	int cpu;
15708204e0c1SAlexander Duyck 
15718204e0c1SAlexander Duyck 	/* No point in doing this if NUMA isn't enabled for workqueues */
15728204e0c1SAlexander Duyck 	if (!wq_numa_enabled)
15738204e0c1SAlexander Duyck 		return WORK_CPU_UNBOUND;
15748204e0c1SAlexander Duyck 
15758204e0c1SAlexander Duyck 	/* Delay binding to CPU if node is not valid or online */
15768204e0c1SAlexander Duyck 	if (node < 0 || node >= MAX_NUMNODES || !node_online(node))
15778204e0c1SAlexander Duyck 		return WORK_CPU_UNBOUND;
15788204e0c1SAlexander Duyck 
15798204e0c1SAlexander Duyck 	/* Use local node/cpu if we are already there */
15808204e0c1SAlexander Duyck 	cpu = raw_smp_processor_id();
15818204e0c1SAlexander Duyck 	if (node == cpu_to_node(cpu))
15828204e0c1SAlexander Duyck 		return cpu;
15838204e0c1SAlexander Duyck 
15848204e0c1SAlexander Duyck 	/* Use "random" otherwise know as "first" online CPU of node */
15858204e0c1SAlexander Duyck 	cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
15868204e0c1SAlexander Duyck 
15878204e0c1SAlexander Duyck 	/* If CPU is valid return that, otherwise just defer */
15888204e0c1SAlexander Duyck 	return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND;
15898204e0c1SAlexander Duyck }
15908204e0c1SAlexander Duyck 
15918204e0c1SAlexander Duyck /**
15928204e0c1SAlexander Duyck  * queue_work_node - queue work on a "random" cpu for a given NUMA node
15938204e0c1SAlexander Duyck  * @node: NUMA node that we are targeting the work for
15948204e0c1SAlexander Duyck  * @wq: workqueue to use
15958204e0c1SAlexander Duyck  * @work: work to queue
15968204e0c1SAlexander Duyck  *
15978204e0c1SAlexander Duyck  * We queue the work to a "random" CPU within a given NUMA node. The basic
15988204e0c1SAlexander Duyck  * idea here is to provide a way to somehow associate work with a given
15998204e0c1SAlexander Duyck  * NUMA node.
16008204e0c1SAlexander Duyck  *
16018204e0c1SAlexander Duyck  * This function will only make a best effort attempt at getting this onto
16028204e0c1SAlexander Duyck  * the right NUMA node. If no node is requested or the requested node is
16038204e0c1SAlexander Duyck  * offline then we just fall back to standard queue_work behavior.
16048204e0c1SAlexander Duyck  *
16058204e0c1SAlexander Duyck  * Currently the "random" CPU ends up being the first available CPU in the
16068204e0c1SAlexander Duyck  * intersection of cpu_online_mask and the cpumask of the node, unless we
16078204e0c1SAlexander Duyck  * are running on the node. In that case we just use the current CPU.
16088204e0c1SAlexander Duyck  *
16098204e0c1SAlexander Duyck  * Return: %false if @work was already on a queue, %true otherwise.
16108204e0c1SAlexander Duyck  */
16118204e0c1SAlexander Duyck bool queue_work_node(int node, struct workqueue_struct *wq,
16128204e0c1SAlexander Duyck 		     struct work_struct *work)
16138204e0c1SAlexander Duyck {
16148204e0c1SAlexander Duyck 	unsigned long flags;
16158204e0c1SAlexander Duyck 	bool ret = false;
16168204e0c1SAlexander Duyck 
16178204e0c1SAlexander Duyck 	/*
16188204e0c1SAlexander Duyck 	 * This current implementation is specific to unbound workqueues.
16198204e0c1SAlexander Duyck 	 * Specifically we only return the first available CPU for a given
16208204e0c1SAlexander Duyck 	 * node instead of cycling through individual CPUs within the node.
16218204e0c1SAlexander Duyck 	 *
16228204e0c1SAlexander Duyck 	 * If this is used with a per-cpu workqueue then the logic in
16238204e0c1SAlexander Duyck 	 * workqueue_select_cpu_near would need to be updated to allow for
16248204e0c1SAlexander Duyck 	 * some round robin type logic.
16258204e0c1SAlexander Duyck 	 */
16268204e0c1SAlexander Duyck 	WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND));
16278204e0c1SAlexander Duyck 
16288204e0c1SAlexander Duyck 	local_irq_save(flags);
16298204e0c1SAlexander Duyck 
16308204e0c1SAlexander Duyck 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
16318204e0c1SAlexander Duyck 		int cpu = workqueue_select_cpu_near(node);
16328204e0c1SAlexander Duyck 
16338204e0c1SAlexander Duyck 		__queue_work(cpu, wq, work);
16348204e0c1SAlexander Duyck 		ret = true;
16358204e0c1SAlexander Duyck 	}
16368204e0c1SAlexander Duyck 
16378204e0c1SAlexander Duyck 	local_irq_restore(flags);
16388204e0c1SAlexander Duyck 	return ret;
16398204e0c1SAlexander Duyck }
16408204e0c1SAlexander Duyck EXPORT_SYMBOL_GPL(queue_work_node);
16418204e0c1SAlexander Duyck 
16428c20feb6SKees Cook void delayed_work_timer_fn(struct timer_list *t)
16431da177e4SLinus Torvalds {
16448c20feb6SKees Cook 	struct delayed_work *dwork = from_timer(dwork, t, timer);
16451da177e4SLinus Torvalds 
1646e0aecdd8STejun Heo 	/* should have been called from irqsafe timer with irq already off */
164760c057bcSLai Jiangshan 	__queue_work(dwork->cpu, dwork->wq, &dwork->work);
16481da177e4SLinus Torvalds }
16491438ade5SKonstantin Khlebnikov EXPORT_SYMBOL(delayed_work_timer_fn);
16501da177e4SLinus Torvalds 
16517beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
165252bad64dSDavid Howells 				struct delayed_work *dwork, unsigned long delay)
16531da177e4SLinus Torvalds {
16547beb2edfSTejun Heo 	struct timer_list *timer = &dwork->timer;
16557beb2edfSTejun Heo 	struct work_struct *work = &dwork->work;
16561da177e4SLinus Torvalds 
1657637fdbaeSTejun Heo 	WARN_ON_ONCE(!wq);
16584b243563SSami Tolvanen 	WARN_ON_ONCE(timer->function != delayed_work_timer_fn);
1659fc4b514fSTejun Heo 	WARN_ON_ONCE(timer_pending(timer));
1660fc4b514fSTejun Heo 	WARN_ON_ONCE(!list_empty(&work->entry));
16617beb2edfSTejun Heo 
16628852aac2STejun Heo 	/*
16638852aac2STejun Heo 	 * If @delay is 0, queue @dwork->work immediately.  This is for
16648852aac2STejun Heo 	 * both optimization and correctness.  The earliest @timer can
16658852aac2STejun Heo 	 * expire is on the closest next tick and delayed_work users depend
16668852aac2STejun Heo 	 * on that there's no such delay when @delay is 0.
16678852aac2STejun Heo 	 */
16688852aac2STejun Heo 	if (!delay) {
16698852aac2STejun Heo 		__queue_work(cpu, wq, &dwork->work);
16708852aac2STejun Heo 		return;
16718852aac2STejun Heo 	}
16728852aac2STejun Heo 
167360c057bcSLai Jiangshan 	dwork->wq = wq;
16741265057fSTejun Heo 	dwork->cpu = cpu;
16757beb2edfSTejun Heo 	timer->expires = jiffies + delay;
16767beb2edfSTejun Heo 
1677041bd12eSTejun Heo 	if (unlikely(cpu != WORK_CPU_UNBOUND))
16787beb2edfSTejun Heo 		add_timer_on(timer, cpu);
1679041bd12eSTejun Heo 	else
1680041bd12eSTejun Heo 		add_timer(timer);
16817beb2edfSTejun Heo }
16821da177e4SLinus Torvalds 
16830fcb78c2SRolf Eike Beer /**
16840fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
16850fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
16860fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1687af9997e4SRandy Dunlap  * @dwork: work to queue
16880fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
16890fcb78c2SRolf Eike Beer  *
1690d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.  If
1691715f1300STejun Heo  * @delay is zero and @dwork is idle, it will be scheduled for immediate
1692715f1300STejun Heo  * execution.
16930fcb78c2SRolf Eike Beer  */
1694d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
169552bad64dSDavid Howells 			   struct delayed_work *dwork, unsigned long delay)
16967a6bc1cdSVenkatesh Pallipadi {
169752bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
1698d4283e93STejun Heo 	bool ret = false;
16998930cabaSTejun Heo 	unsigned long flags;
17008930cabaSTejun Heo 
17018930cabaSTejun Heo 	/* read the comment in __queue_work() */
17028930cabaSTejun Heo 	local_irq_save(flags);
17037a6bc1cdSVenkatesh Pallipadi 
170422df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
17057beb2edfSTejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
1706d4283e93STejun Heo 		ret = true;
17077a6bc1cdSVenkatesh Pallipadi 	}
17088930cabaSTejun Heo 
17098930cabaSTejun Heo 	local_irq_restore(flags);
17107a6bc1cdSVenkatesh Pallipadi 	return ret;
17117a6bc1cdSVenkatesh Pallipadi }
1712ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_delayed_work_on);
17131da177e4SLinus Torvalds 
1714c8e55f36STejun Heo /**
17158376fe22STejun Heo  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
17168376fe22STejun Heo  * @cpu: CPU number to execute work on
17178376fe22STejun Heo  * @wq: workqueue to use
17188376fe22STejun Heo  * @dwork: work to queue
17198376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
17208376fe22STejun Heo  *
17218376fe22STejun Heo  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
17228376fe22STejun Heo  * modify @dwork's timer so that it expires after @delay.  If @delay is
17238376fe22STejun Heo  * zero, @work is guaranteed to be scheduled immediately regardless of its
17248376fe22STejun Heo  * current state.
17258376fe22STejun Heo  *
1726d185af30SYacine Belkadi  * Return: %false if @dwork was idle and queued, %true if @dwork was
17278376fe22STejun Heo  * pending and its timer was modified.
17288376fe22STejun Heo  *
1729e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
17308376fe22STejun Heo  * See try_to_grab_pending() for details.
17318376fe22STejun Heo  */
17328376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
17338376fe22STejun Heo 			 struct delayed_work *dwork, unsigned long delay)
17348376fe22STejun Heo {
17358376fe22STejun Heo 	unsigned long flags;
17368376fe22STejun Heo 	int ret;
17378376fe22STejun Heo 
17388376fe22STejun Heo 	do {
17398376fe22STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
17408376fe22STejun Heo 	} while (unlikely(ret == -EAGAIN));
17418376fe22STejun Heo 
17428376fe22STejun Heo 	if (likely(ret >= 0)) {
17438376fe22STejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
17448376fe22STejun Heo 		local_irq_restore(flags);
17458376fe22STejun Heo 	}
17468376fe22STejun Heo 
17478376fe22STejun Heo 	/* -ENOENT from try_to_grab_pending() becomes %true */
17488376fe22STejun Heo 	return ret;
17498376fe22STejun Heo }
17508376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
17518376fe22STejun Heo 
175205f0fe6bSTejun Heo static void rcu_work_rcufn(struct rcu_head *rcu)
175305f0fe6bSTejun Heo {
175405f0fe6bSTejun Heo 	struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
175505f0fe6bSTejun Heo 
175605f0fe6bSTejun Heo 	/* read the comment in __queue_work() */
175705f0fe6bSTejun Heo 	local_irq_disable();
175805f0fe6bSTejun Heo 	__queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
175905f0fe6bSTejun Heo 	local_irq_enable();
176005f0fe6bSTejun Heo }
176105f0fe6bSTejun Heo 
176205f0fe6bSTejun Heo /**
176305f0fe6bSTejun Heo  * queue_rcu_work - queue work after a RCU grace period
176405f0fe6bSTejun Heo  * @wq: workqueue to use
176505f0fe6bSTejun Heo  * @rwork: work to queue
176605f0fe6bSTejun Heo  *
176705f0fe6bSTejun Heo  * Return: %false if @rwork was already pending, %true otherwise.  Note
176805f0fe6bSTejun Heo  * that a full RCU grace period is guaranteed only after a %true return.
1769bf393fd4SBart Van Assche  * While @rwork is guaranteed to be executed after a %false return, the
177005f0fe6bSTejun Heo  * execution may happen before a full RCU grace period has passed.
177105f0fe6bSTejun Heo  */
177205f0fe6bSTejun Heo bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
177305f0fe6bSTejun Heo {
177405f0fe6bSTejun Heo 	struct work_struct *work = &rwork->work;
177505f0fe6bSTejun Heo 
177605f0fe6bSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
177705f0fe6bSTejun Heo 		rwork->wq = wq;
1778a7e30c0eSUladzislau Rezki 		call_rcu_hurry(&rwork->rcu, rcu_work_rcufn);
177905f0fe6bSTejun Heo 		return true;
178005f0fe6bSTejun Heo 	}
178105f0fe6bSTejun Heo 
178205f0fe6bSTejun Heo 	return false;
178305f0fe6bSTejun Heo }
178405f0fe6bSTejun Heo EXPORT_SYMBOL(queue_rcu_work);
178505f0fe6bSTejun Heo 
17868376fe22STejun Heo /**
1787c8e55f36STejun Heo  * worker_enter_idle - enter idle state
1788c8e55f36STejun Heo  * @worker: worker which is entering idle state
1789c8e55f36STejun Heo  *
1790c8e55f36STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
1791c8e55f36STejun Heo  * necessary.
1792c8e55f36STejun Heo  *
1793c8e55f36STejun Heo  * LOCKING:
1794a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1795c8e55f36STejun Heo  */
1796c8e55f36STejun Heo static void worker_enter_idle(struct worker *worker)
17971da177e4SLinus Torvalds {
1798bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1799c8e55f36STejun Heo 
18006183c009STejun Heo 	if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
18016183c009STejun Heo 	    WARN_ON_ONCE(!list_empty(&worker->entry) &&
18026183c009STejun Heo 			 (worker->hentry.next || worker->hentry.pprev)))
18036183c009STejun Heo 		return;
1804c8e55f36STejun Heo 
1805051e1850SLai Jiangshan 	/* can't use worker_set_flags(), also called from create_worker() */
1806cb444766STejun Heo 	worker->flags |= WORKER_IDLE;
1807bd7bdd43STejun Heo 	pool->nr_idle++;
1808e22bee78STejun Heo 	worker->last_active = jiffies;
1809c8e55f36STejun Heo 
1810c8e55f36STejun Heo 	/* idle_list is LIFO */
1811bd7bdd43STejun Heo 	list_add(&worker->entry, &pool->idle_list);
1812db7bccf4STejun Heo 
181363d95a91STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1814628c78e7STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1815cb444766STejun Heo 
1816989442d7SLai Jiangshan 	/* Sanity check nr_running. */
1817bc35f7efSLai Jiangshan 	WARN_ON_ONCE(pool->nr_workers == pool->nr_idle && pool->nr_running);
1818c8e55f36STejun Heo }
1819c8e55f36STejun Heo 
1820c8e55f36STejun Heo /**
1821c8e55f36STejun Heo  * worker_leave_idle - leave idle state
1822c8e55f36STejun Heo  * @worker: worker which is leaving idle state
1823c8e55f36STejun Heo  *
1824c8e55f36STejun Heo  * @worker is leaving idle state.  Update stats.
1825c8e55f36STejun Heo  *
1826c8e55f36STejun Heo  * LOCKING:
1827a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1828c8e55f36STejun Heo  */
1829c8e55f36STejun Heo static void worker_leave_idle(struct worker *worker)
1830c8e55f36STejun Heo {
1831bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1832c8e55f36STejun Heo 
18336183c009STejun Heo 	if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
18346183c009STejun Heo 		return;
1835d302f017STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
1836bd7bdd43STejun Heo 	pool->nr_idle--;
1837c8e55f36STejun Heo 	list_del_init(&worker->entry);
1838c8e55f36STejun Heo }
1839c8e55f36STejun Heo 
1840f7537df5SLai Jiangshan static struct worker *alloc_worker(int node)
1841c34056a3STejun Heo {
1842c34056a3STejun Heo 	struct worker *worker;
1843c34056a3STejun Heo 
1844f7537df5SLai Jiangshan 	worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
1845c8e55f36STejun Heo 	if (worker) {
1846c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
1847affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
1848da028469SLai Jiangshan 		INIT_LIST_HEAD(&worker->node);
1849e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
1850e22bee78STejun Heo 		worker->flags = WORKER_PREP;
1851c8e55f36STejun Heo 	}
1852c34056a3STejun Heo 	return worker;
1853c34056a3STejun Heo }
1854c34056a3STejun Heo 
1855c34056a3STejun Heo /**
18564736cbf7SLai Jiangshan  * worker_attach_to_pool() - attach a worker to a pool
18574736cbf7SLai Jiangshan  * @worker: worker to be attached
18584736cbf7SLai Jiangshan  * @pool: the target pool
18594736cbf7SLai Jiangshan  *
18604736cbf7SLai Jiangshan  * Attach @worker to @pool.  Once attached, the %WORKER_UNBOUND flag and
18614736cbf7SLai Jiangshan  * cpu-binding of @worker are kept coordinated with the pool across
18624736cbf7SLai Jiangshan  * cpu-[un]hotplugs.
18634736cbf7SLai Jiangshan  */
18644736cbf7SLai Jiangshan static void worker_attach_to_pool(struct worker *worker,
18654736cbf7SLai Jiangshan 				   struct worker_pool *pool)
18664736cbf7SLai Jiangshan {
18671258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
18684736cbf7SLai Jiangshan 
18694736cbf7SLai Jiangshan 	/*
18701258fae7STejun Heo 	 * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains
18711258fae7STejun Heo 	 * stable across this function.  See the comments above the flag
18721258fae7STejun Heo 	 * definition for details.
18734736cbf7SLai Jiangshan 	 */
18744736cbf7SLai Jiangshan 	if (pool->flags & POOL_DISASSOCIATED)
18754736cbf7SLai Jiangshan 		worker->flags |= WORKER_UNBOUND;
18765c25b5ffSPeter Zijlstra 	else
18775c25b5ffSPeter Zijlstra 		kthread_set_per_cpu(worker->task, pool->cpu);
18784736cbf7SLai Jiangshan 
1879640f17c8SPeter Zijlstra 	if (worker->rescue_wq)
1880640f17c8SPeter Zijlstra 		set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
1881640f17c8SPeter Zijlstra 
18824736cbf7SLai Jiangshan 	list_add_tail(&worker->node, &pool->workers);
1883a2d812a2STejun Heo 	worker->pool = pool;
18844736cbf7SLai Jiangshan 
18851258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
18864736cbf7SLai Jiangshan }
18874736cbf7SLai Jiangshan 
18884736cbf7SLai Jiangshan /**
188960f5a4bcSLai Jiangshan  * worker_detach_from_pool() - detach a worker from its pool
189060f5a4bcSLai Jiangshan  * @worker: worker which is attached to its pool
189160f5a4bcSLai Jiangshan  *
18924736cbf7SLai Jiangshan  * Undo the attaching which had been done in worker_attach_to_pool().  The
18934736cbf7SLai Jiangshan  * caller worker shouldn't access to the pool after detached except it has
18944736cbf7SLai Jiangshan  * other reference to the pool.
189560f5a4bcSLai Jiangshan  */
1896a2d812a2STejun Heo static void worker_detach_from_pool(struct worker *worker)
189760f5a4bcSLai Jiangshan {
1898a2d812a2STejun Heo 	struct worker_pool *pool = worker->pool;
189960f5a4bcSLai Jiangshan 	struct completion *detach_completion = NULL;
190060f5a4bcSLai Jiangshan 
19011258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
1902a2d812a2STejun Heo 
19035c25b5ffSPeter Zijlstra 	kthread_set_per_cpu(worker->task, -1);
1904da028469SLai Jiangshan 	list_del(&worker->node);
1905a2d812a2STejun Heo 	worker->pool = NULL;
1906a2d812a2STejun Heo 
1907da028469SLai Jiangshan 	if (list_empty(&pool->workers))
190860f5a4bcSLai Jiangshan 		detach_completion = pool->detach_completion;
19091258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
191060f5a4bcSLai Jiangshan 
1911b62c0751SLai Jiangshan 	/* clear leftover flags without pool->lock after it is detached */
1912b62c0751SLai Jiangshan 	worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
1913b62c0751SLai Jiangshan 
191460f5a4bcSLai Jiangshan 	if (detach_completion)
191560f5a4bcSLai Jiangshan 		complete(detach_completion);
191660f5a4bcSLai Jiangshan }
191760f5a4bcSLai Jiangshan 
191860f5a4bcSLai Jiangshan /**
1919c34056a3STejun Heo  * create_worker - create a new workqueue worker
192063d95a91STejun Heo  * @pool: pool the new worker will belong to
1921c34056a3STejun Heo  *
1922051e1850SLai Jiangshan  * Create and start a new worker which is attached to @pool.
1923c34056a3STejun Heo  *
1924c34056a3STejun Heo  * CONTEXT:
1925c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
1926c34056a3STejun Heo  *
1927d185af30SYacine Belkadi  * Return:
1928c34056a3STejun Heo  * Pointer to the newly created worker.
1929c34056a3STejun Heo  */
1930bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
1931c34056a3STejun Heo {
1932e441b56fSZhen Lei 	struct worker *worker;
1933e441b56fSZhen Lei 	int id;
1934e3c916a4STejun Heo 	char id_buf[16];
1935c34056a3STejun Heo 
19367cda9aaeSLai Jiangshan 	/* ID is needed to determine kthread name */
1937e441b56fSZhen Lei 	id = ida_alloc(&pool->worker_ida, GFP_KERNEL);
1938822d8405STejun Heo 	if (id < 0)
1939e441b56fSZhen Lei 		return NULL;
1940c34056a3STejun Heo 
1941f7537df5SLai Jiangshan 	worker = alloc_worker(pool->node);
1942c34056a3STejun Heo 	if (!worker)
1943c34056a3STejun Heo 		goto fail;
1944c34056a3STejun Heo 
1945c34056a3STejun Heo 	worker->id = id;
1946c34056a3STejun Heo 
194729c91e99STejun Heo 	if (pool->cpu >= 0)
1948e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
1949e3c916a4STejun Heo 			 pool->attrs->nice < 0  ? "H" : "");
1950f3421797STejun Heo 	else
1951e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
1952e3c916a4STejun Heo 
1953f3f90ad4STejun Heo 	worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
1954e3c916a4STejun Heo 					      "kworker/%s", id_buf);
1955c34056a3STejun Heo 	if (IS_ERR(worker->task))
1956c34056a3STejun Heo 		goto fail;
1957c34056a3STejun Heo 
195891151228SOleg Nesterov 	set_user_nice(worker->task, pool->attrs->nice);
195925834c73SPeter Zijlstra 	kthread_bind_mask(worker->task, pool->attrs->cpumask);
196091151228SOleg Nesterov 
1961da028469SLai Jiangshan 	/* successful, attach the worker to the pool */
19624736cbf7SLai Jiangshan 	worker_attach_to_pool(worker, pool);
1963822d8405STejun Heo 
1964051e1850SLai Jiangshan 	/* start the newly created worker */
1965a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
1966051e1850SLai Jiangshan 	worker->pool->nr_workers++;
1967051e1850SLai Jiangshan 	worker_enter_idle(worker);
1968051e1850SLai Jiangshan 	wake_up_process(worker->task);
1969a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
1970051e1850SLai Jiangshan 
1971c34056a3STejun Heo 	return worker;
1972822d8405STejun Heo 
1973c34056a3STejun Heo fail:
1974e441b56fSZhen Lei 	ida_free(&pool->worker_ida, id);
1975c34056a3STejun Heo 	kfree(worker);
1976c34056a3STejun Heo 	return NULL;
1977c34056a3STejun Heo }
1978c34056a3STejun Heo 
1979*793777bcSValentin Schneider static void unbind_worker(struct worker *worker)
1980*793777bcSValentin Schneider {
1981*793777bcSValentin Schneider 	lockdep_assert_held(&wq_pool_attach_mutex);
1982*793777bcSValentin Schneider 
1983*793777bcSValentin Schneider 	kthread_set_per_cpu(worker->task, -1);
1984*793777bcSValentin Schneider 	if (cpumask_intersects(wq_unbound_cpumask, cpu_active_mask))
1985*793777bcSValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, wq_unbound_cpumask) < 0);
1986*793777bcSValentin Schneider 	else
1987*793777bcSValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, cpu_possible_mask) < 0);
1988*793777bcSValentin Schneider }
1989*793777bcSValentin Schneider 
1990*793777bcSValentin Schneider static void rebind_worker(struct worker *worker, struct worker_pool *pool)
1991*793777bcSValentin Schneider {
1992*793777bcSValentin Schneider 	kthread_set_per_cpu(worker->task, pool->cpu);
1993*793777bcSValentin Schneider 	WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask) < 0);
1994*793777bcSValentin Schneider }
1995*793777bcSValentin Schneider 
1996c34056a3STejun Heo /**
1997c34056a3STejun Heo  * destroy_worker - destroy a workqueue worker
1998c34056a3STejun Heo  * @worker: worker to be destroyed
1999c34056a3STejun Heo  *
200073eb7fe7SLai Jiangshan  * Destroy @worker and adjust @pool stats accordingly.  The worker should
200173eb7fe7SLai Jiangshan  * be idle.
2002c8e55f36STejun Heo  *
2003c8e55f36STejun Heo  * CONTEXT:
2004a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
2005c34056a3STejun Heo  */
2006c34056a3STejun Heo static void destroy_worker(struct worker *worker)
2007c34056a3STejun Heo {
2008bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2009c34056a3STejun Heo 
2010cd549687STejun Heo 	lockdep_assert_held(&pool->lock);
2011cd549687STejun Heo 
2012c34056a3STejun Heo 	/* sanity check frenzy */
20136183c009STejun Heo 	if (WARN_ON(worker->current_work) ||
201473eb7fe7SLai Jiangshan 	    WARN_ON(!list_empty(&worker->scheduled)) ||
201573eb7fe7SLai Jiangshan 	    WARN_ON(!(worker->flags & WORKER_IDLE)))
20166183c009STejun Heo 		return;
2017c34056a3STejun Heo 
2018bd7bdd43STejun Heo 	pool->nr_workers--;
2019bd7bdd43STejun Heo 	pool->nr_idle--;
2020c8e55f36STejun Heo 
2021c8e55f36STejun Heo 	list_del_init(&worker->entry);
2022cb444766STejun Heo 	worker->flags |= WORKER_DIE;
202360f5a4bcSLai Jiangshan 	wake_up_process(worker->task);
2024c34056a3STejun Heo }
2025c34056a3STejun Heo 
202632a6c723SKees Cook static void idle_worker_timeout(struct timer_list *t)
2027e22bee78STejun Heo {
202832a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, idle_timer);
2029e22bee78STejun Heo 
2030a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2031e22bee78STejun Heo 
20323347fc9fSLai Jiangshan 	while (too_many_workers(pool)) {
2033e22bee78STejun Heo 		struct worker *worker;
2034e22bee78STejun Heo 		unsigned long expires;
2035e22bee78STejun Heo 
2036e22bee78STejun Heo 		/* idle_list is kept in LIFO order, check the last one */
203763d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
2038e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2039e22bee78STejun Heo 
20403347fc9fSLai Jiangshan 		if (time_before(jiffies, expires)) {
204163d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
20423347fc9fSLai Jiangshan 			break;
2043e22bee78STejun Heo 		}
20443347fc9fSLai Jiangshan 
20453347fc9fSLai Jiangshan 		destroy_worker(worker);
2046e22bee78STejun Heo 	}
2047e22bee78STejun Heo 
2048a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2049e22bee78STejun Heo }
2050e22bee78STejun Heo 
2051493a1724STejun Heo static void send_mayday(struct work_struct *work)
2052e22bee78STejun Heo {
2053112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2054112202d9STejun Heo 	struct workqueue_struct *wq = pwq->wq;
2055493a1724STejun Heo 
20562e109a28STejun Heo 	lockdep_assert_held(&wq_mayday_lock);
2057e22bee78STejun Heo 
2058493008a8STejun Heo 	if (!wq->rescuer)
2059493a1724STejun Heo 		return;
2060e22bee78STejun Heo 
2061e22bee78STejun Heo 	/* mayday mayday mayday */
2062493a1724STejun Heo 	if (list_empty(&pwq->mayday_node)) {
206377668c8bSLai Jiangshan 		/*
206477668c8bSLai Jiangshan 		 * If @pwq is for an unbound wq, its base ref may be put at
206577668c8bSLai Jiangshan 		 * any time due to an attribute change.  Pin @pwq until the
206677668c8bSLai Jiangshan 		 * rescuer is done with it.
206777668c8bSLai Jiangshan 		 */
206877668c8bSLai Jiangshan 		get_pwq(pwq);
2069493a1724STejun Heo 		list_add_tail(&pwq->mayday_node, &wq->maydays);
2070e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
2071493a1724STejun Heo 	}
2072e22bee78STejun Heo }
2073e22bee78STejun Heo 
207432a6c723SKees Cook static void pool_mayday_timeout(struct timer_list *t)
2075e22bee78STejun Heo {
207632a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, mayday_timer);
2077e22bee78STejun Heo 	struct work_struct *work;
2078e22bee78STejun Heo 
2079a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2080a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock(&wq_mayday_lock);		/* for wq->maydays */
2081e22bee78STejun Heo 
208263d95a91STejun Heo 	if (need_to_create_worker(pool)) {
2083e22bee78STejun Heo 		/*
2084e22bee78STejun Heo 		 * We've been trying to create a new worker but
2085e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
2086e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
2087e22bee78STejun Heo 		 * rescuers.
2088e22bee78STejun Heo 		 */
208963d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
2090e22bee78STejun Heo 			send_mayday(work);
2091e22bee78STejun Heo 	}
2092e22bee78STejun Heo 
2093a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&wq_mayday_lock);
2094a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2095e22bee78STejun Heo 
209663d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
2097e22bee78STejun Heo }
2098e22bee78STejun Heo 
2099e22bee78STejun Heo /**
2100e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
210163d95a91STejun Heo  * @pool: pool to create a new worker for
2102e22bee78STejun Heo  *
210363d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
2104e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
2105e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
210663d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
2107e22bee78STejun Heo  * possible allocation deadlock.
2108e22bee78STejun Heo  *
2109c5aa87bbSTejun Heo  * On return, need_to_create_worker() is guaranteed to be %false and
2110c5aa87bbSTejun Heo  * may_start_working() %true.
2111e22bee78STejun Heo  *
2112e22bee78STejun Heo  * LOCKING:
2113a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2114e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
2115e22bee78STejun Heo  * manager.
2116e22bee78STejun Heo  */
211729187a9eSTejun Heo static void maybe_create_worker(struct worker_pool *pool)
2118d565ed63STejun Heo __releases(&pool->lock)
2119d565ed63STejun Heo __acquires(&pool->lock)
2120e22bee78STejun Heo {
2121e22bee78STejun Heo restart:
2122a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
21239f9c2364STejun Heo 
2124e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
212563d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
2126e22bee78STejun Heo 
2127e22bee78STejun Heo 	while (true) {
2128051e1850SLai Jiangshan 		if (create_worker(pool) || !need_to_create_worker(pool))
2129e22bee78STejun Heo 			break;
2130e22bee78STejun Heo 
2131e212f361SLai Jiangshan 		schedule_timeout_interruptible(CREATE_COOLDOWN);
21329f9c2364STejun Heo 
213363d95a91STejun Heo 		if (!need_to_create_worker(pool))
2134e22bee78STejun Heo 			break;
2135e22bee78STejun Heo 	}
2136e22bee78STejun Heo 
213763d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
2138a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2139051e1850SLai Jiangshan 	/*
2140051e1850SLai Jiangshan 	 * This is necessary even after a new worker was just successfully
2141051e1850SLai Jiangshan 	 * created as @pool->lock was dropped and the new worker might have
2142051e1850SLai Jiangshan 	 * already become busy.
2143051e1850SLai Jiangshan 	 */
214463d95a91STejun Heo 	if (need_to_create_worker(pool))
2145e22bee78STejun Heo 		goto restart;
2146e22bee78STejun Heo }
2147e22bee78STejun Heo 
2148e22bee78STejun Heo /**
2149e22bee78STejun Heo  * manage_workers - manage worker pool
2150e22bee78STejun Heo  * @worker: self
2151e22bee78STejun Heo  *
2152706026c2STejun Heo  * Assume the manager role and manage the worker pool @worker belongs
2153e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
2154706026c2STejun Heo  * pool.  The exclusion is handled automatically by this function.
2155e22bee78STejun Heo  *
2156e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
2157e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
2158e22bee78STejun Heo  * and may_start_working() is true.
2159e22bee78STejun Heo  *
2160e22bee78STejun Heo  * CONTEXT:
2161a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2162e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
2163e22bee78STejun Heo  *
2164d185af30SYacine Belkadi  * Return:
216529187a9eSTejun Heo  * %false if the pool doesn't need management and the caller can safely
216629187a9eSTejun Heo  * start processing works, %true if management function was performed and
216729187a9eSTejun Heo  * the conditions that the caller verified before calling the function may
216829187a9eSTejun Heo  * no longer be true.
2169e22bee78STejun Heo  */
2170e22bee78STejun Heo static bool manage_workers(struct worker *worker)
2171e22bee78STejun Heo {
217263d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
2173e22bee78STejun Heo 
2174692b4825STejun Heo 	if (pool->flags & POOL_MANAGER_ACTIVE)
217529187a9eSTejun Heo 		return false;
2176692b4825STejun Heo 
2177692b4825STejun Heo 	pool->flags |= POOL_MANAGER_ACTIVE;
21782607d7a6STejun Heo 	pool->manager = worker;
2179e22bee78STejun Heo 
218029187a9eSTejun Heo 	maybe_create_worker(pool);
2181e22bee78STejun Heo 
21822607d7a6STejun Heo 	pool->manager = NULL;
2183692b4825STejun Heo 	pool->flags &= ~POOL_MANAGER_ACTIVE;
2184d8bb65abSSebastian Andrzej Siewior 	rcuwait_wake_up(&manager_wait);
218529187a9eSTejun Heo 	return true;
2186e22bee78STejun Heo }
2187e22bee78STejun Heo 
2188a62428c0STejun Heo /**
2189a62428c0STejun Heo  * process_one_work - process single work
2190c34056a3STejun Heo  * @worker: self
2191a62428c0STejun Heo  * @work: work to process
2192a62428c0STejun Heo  *
2193a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
2194a62428c0STejun Heo  * process a single work including synchronization against and
2195a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
2196a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
2197a62428c0STejun Heo  * call this function to process a work.
2198a62428c0STejun Heo  *
2199a62428c0STejun Heo  * CONTEXT:
2200a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which is released and regrabbed.
2201a62428c0STejun Heo  */
2202c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
2203d565ed63STejun Heo __releases(&pool->lock)
2204d565ed63STejun Heo __acquires(&pool->lock)
22051da177e4SLinus Torvalds {
2206112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2207bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2208112202d9STejun Heo 	bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
2209c4560c2cSLai Jiangshan 	unsigned long work_data;
22107e11629dSTejun Heo 	struct worker *collision;
22114e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
22124e6045f1SJohannes Berg 	/*
2213a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
2214a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
2215a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
2216a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
2217a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
22184e6045f1SJohannes Berg 	 */
22194d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
22204d82a1deSPeter Zijlstra 
22214d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
22224e6045f1SJohannes Berg #endif
2223807407c0SLai Jiangshan 	/* ensure we're on the correct CPU */
222485327af6SLai Jiangshan 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2225ec22ca5eSTejun Heo 		     raw_smp_processor_id() != pool->cpu);
222625511a47STejun Heo 
22277e11629dSTejun Heo 	/*
22287e11629dSTejun Heo 	 * A single work shouldn't be executed concurrently by
22297e11629dSTejun Heo 	 * multiple workers on a single cpu.  Check whether anyone is
22307e11629dSTejun Heo 	 * already processing the work.  If so, defer the work to the
22317e11629dSTejun Heo 	 * currently executing one.
22327e11629dSTejun Heo 	 */
2233c9e7cf27STejun Heo 	collision = find_worker_executing_work(pool, work);
22347e11629dSTejun Heo 	if (unlikely(collision)) {
22357e11629dSTejun Heo 		move_linked_works(work, &collision->scheduled, NULL);
22367e11629dSTejun Heo 		return;
22377e11629dSTejun Heo 	}
22381da177e4SLinus Torvalds 
22398930cabaSTejun Heo 	/* claim and dequeue */
22401da177e4SLinus Torvalds 	debug_work_deactivate(work);
2241c9e7cf27STejun Heo 	hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2242c34056a3STejun Heo 	worker->current_work = work;
2243a2c1c57bSTejun Heo 	worker->current_func = work->func;
2244112202d9STejun Heo 	worker->current_pwq = pwq;
2245c4560c2cSLai Jiangshan 	work_data = *work_data_bits(work);
2246d812796eSLai Jiangshan 	worker->current_color = get_work_color(work_data);
22477a22ad75STejun Heo 
22488bf89593STejun Heo 	/*
22498bf89593STejun Heo 	 * Record wq name for cmdline and debug reporting, may get
22508bf89593STejun Heo 	 * overridden through set_worker_desc().
22518bf89593STejun Heo 	 */
22528bf89593STejun Heo 	strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
22538bf89593STejun Heo 
2254a62428c0STejun Heo 	list_del_init(&work->entry);
2255a62428c0STejun Heo 
2256649027d7STejun Heo 	/*
2257228f1d00SLai Jiangshan 	 * CPU intensive works don't participate in concurrency management.
2258228f1d00SLai Jiangshan 	 * They're the scheduler's responsibility.  This takes @worker out
2259228f1d00SLai Jiangshan 	 * of concurrency management and the next code block will chain
2260228f1d00SLai Jiangshan 	 * execution of the pending work items.
2261fb0e7bebSTejun Heo 	 */
2262fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2263228f1d00SLai Jiangshan 		worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2264fb0e7bebSTejun Heo 
2265974271c4STejun Heo 	/*
2266a489a03eSLai Jiangshan 	 * Wake up another worker if necessary.  The condition is always
2267a489a03eSLai Jiangshan 	 * false for normal per-cpu workers since nr_running would always
2268a489a03eSLai Jiangshan 	 * be >= 1 at this point.  This is used to chain execution of the
2269a489a03eSLai Jiangshan 	 * pending work items for WORKER_NOT_RUNNING workers such as the
2270228f1d00SLai Jiangshan 	 * UNBOUND and CPU_INTENSIVE ones.
2271974271c4STejun Heo 	 */
2272a489a03eSLai Jiangshan 	if (need_more_worker(pool))
227363d95a91STejun Heo 		wake_up_worker(pool);
2274974271c4STejun Heo 
22758930cabaSTejun Heo 	/*
22767c3eed5cSTejun Heo 	 * Record the last pool and clear PENDING which should be the last
2277d565ed63STejun Heo 	 * update to @work.  Also, do this inside @pool->lock so that
227823657bb1STejun Heo 	 * PENDING and queued state changes happen together while IRQ is
227923657bb1STejun Heo 	 * disabled.
22808930cabaSTejun Heo 	 */
22817c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(work, pool->id);
22821da177e4SLinus Torvalds 
2283a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2284365970a1SDavid Howells 
2285a1d14934SPeter Zijlstra 	lock_map_acquire(&pwq->wq->lockdep_map);
22863295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
2287e6f3faa7SPeter Zijlstra 	/*
2288f52be570SPeter Zijlstra 	 * Strictly speaking we should mark the invariant state without holding
2289f52be570SPeter Zijlstra 	 * any locks, that is, before these two lock_map_acquire()'s.
2290e6f3faa7SPeter Zijlstra 	 *
2291e6f3faa7SPeter Zijlstra 	 * However, that would result in:
2292e6f3faa7SPeter Zijlstra 	 *
2293e6f3faa7SPeter Zijlstra 	 *   A(W1)
2294e6f3faa7SPeter Zijlstra 	 *   WFC(C)
2295e6f3faa7SPeter Zijlstra 	 *		A(W1)
2296e6f3faa7SPeter Zijlstra 	 *		C(C)
2297e6f3faa7SPeter Zijlstra 	 *
2298e6f3faa7SPeter Zijlstra 	 * Which would create W1->C->W1 dependencies, even though there is no
2299e6f3faa7SPeter Zijlstra 	 * actual deadlock possible. There are two solutions, using a
2300e6f3faa7SPeter Zijlstra 	 * read-recursive acquire on the work(queue) 'locks', but this will then
2301f52be570SPeter Zijlstra 	 * hit the lockdep limitation on recursive locks, or simply discard
2302e6f3faa7SPeter Zijlstra 	 * these locks.
2303e6f3faa7SPeter Zijlstra 	 *
2304e6f3faa7SPeter Zijlstra 	 * AFAICT there is no possible deadlock scenario between the
2305e6f3faa7SPeter Zijlstra 	 * flush_work() and complete() primitives (except for single-threaded
2306e6f3faa7SPeter Zijlstra 	 * workqueues), so hiding them isn't a problem.
2307e6f3faa7SPeter Zijlstra 	 */
2308f52be570SPeter Zijlstra 	lockdep_invariant_state(true);
2309e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
2310a2c1c57bSTejun Heo 	worker->current_func(work);
2311e36c886aSArjan van de Ven 	/*
2312e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
2313e36c886aSArjan van de Ven 	 * point will only record its address.
2314e36c886aSArjan van de Ven 	 */
23151c5da0ecSDaniel Jordan 	trace_workqueue_execute_end(work, worker->current_func);
23163295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
2317112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
23181da177e4SLinus Torvalds 
2319d5abe669SPeter Zijlstra 	if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2320044c782cSValentin Ilie 		pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2321d75f773cSSakari Ailus 		       "     last function: %ps\n",
2322a2c1c57bSTejun Heo 		       current->comm, preempt_count(), task_pid_nr(current),
2323a2c1c57bSTejun Heo 		       worker->current_func);
2324d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
2325d5abe669SPeter Zijlstra 		dump_stack();
2326d5abe669SPeter Zijlstra 	}
2327d5abe669SPeter Zijlstra 
2328b22ce278STejun Heo 	/*
2329025f50f3SSebastian Andrzej Siewior 	 * The following prevents a kworker from hogging CPU on !PREEMPTION
2330b22ce278STejun Heo 	 * kernels, where a requeueing work item waiting for something to
2331b22ce278STejun Heo 	 * happen could deadlock with stop_machine as such work item could
2332b22ce278STejun Heo 	 * indefinitely requeue itself while all other CPUs are trapped in
2333789cbbecSJoe Lawrence 	 * stop_machine. At the same time, report a quiescent RCU state so
2334789cbbecSJoe Lawrence 	 * the same condition doesn't freeze RCU.
2335b22ce278STejun Heo 	 */
2336a7e6425eSPaul E. McKenney 	cond_resched();
2337b22ce278STejun Heo 
2338a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2339a62428c0STejun Heo 
2340fb0e7bebSTejun Heo 	/* clear cpu intensive status */
2341fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2342fb0e7bebSTejun Heo 		worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2343fb0e7bebSTejun Heo 
23441b69ac6bSJohannes Weiner 	/* tag the worker for identification in schedule() */
23451b69ac6bSJohannes Weiner 	worker->last_func = worker->current_func;
23461b69ac6bSJohannes Weiner 
2347a62428c0STejun Heo 	/* we're done with it, release */
234842f8570fSSasha Levin 	hash_del(&worker->hentry);
2349c34056a3STejun Heo 	worker->current_work = NULL;
2350a2c1c57bSTejun Heo 	worker->current_func = NULL;
2351112202d9STejun Heo 	worker->current_pwq = NULL;
2352d812796eSLai Jiangshan 	worker->current_color = INT_MAX;
2353c4560c2cSLai Jiangshan 	pwq_dec_nr_in_flight(pwq, work_data);
23541da177e4SLinus Torvalds }
23551da177e4SLinus Torvalds 
2356affee4b2STejun Heo /**
2357affee4b2STejun Heo  * process_scheduled_works - process scheduled works
2358affee4b2STejun Heo  * @worker: self
2359affee4b2STejun Heo  *
2360affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
2361affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
2362affee4b2STejun Heo  * fetches a work from the top and executes it.
2363affee4b2STejun Heo  *
2364affee4b2STejun Heo  * CONTEXT:
2365a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2366affee4b2STejun Heo  * multiple times.
2367affee4b2STejun Heo  */
2368affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
23691da177e4SLinus Torvalds {
2370affee4b2STejun Heo 	while (!list_empty(&worker->scheduled)) {
2371affee4b2STejun Heo 		struct work_struct *work = list_first_entry(&worker->scheduled,
2372a62428c0STejun Heo 						struct work_struct, entry);
2373c34056a3STejun Heo 		process_one_work(worker, work);
2374a62428c0STejun Heo 	}
23751da177e4SLinus Torvalds }
23761da177e4SLinus Torvalds 
2377197f6accSTejun Heo static void set_pf_worker(bool val)
2378197f6accSTejun Heo {
2379197f6accSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
2380197f6accSTejun Heo 	if (val)
2381197f6accSTejun Heo 		current->flags |= PF_WQ_WORKER;
2382197f6accSTejun Heo 	else
2383197f6accSTejun Heo 		current->flags &= ~PF_WQ_WORKER;
2384197f6accSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
2385197f6accSTejun Heo }
2386197f6accSTejun Heo 
23874690c4abSTejun Heo /**
23884690c4abSTejun Heo  * worker_thread - the worker thread function
2389c34056a3STejun Heo  * @__worker: self
23904690c4abSTejun Heo  *
2391c5aa87bbSTejun Heo  * The worker thread function.  All workers belong to a worker_pool -
2392c5aa87bbSTejun Heo  * either a per-cpu one or dynamic unbound one.  These workers process all
2393c5aa87bbSTejun Heo  * work items regardless of their specific target workqueue.  The only
2394c5aa87bbSTejun Heo  * exception is work items which belong to workqueues with a rescuer which
2395c5aa87bbSTejun Heo  * will be explained in rescuer_thread().
2396d185af30SYacine Belkadi  *
2397d185af30SYacine Belkadi  * Return: 0
23984690c4abSTejun Heo  */
2399c34056a3STejun Heo static int worker_thread(void *__worker)
24001da177e4SLinus Torvalds {
2401c34056a3STejun Heo 	struct worker *worker = __worker;
2402bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
24031da177e4SLinus Torvalds 
2404e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
2405197f6accSTejun Heo 	set_pf_worker(true);
2406c8e55f36STejun Heo woke_up:
2407a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2408affee4b2STejun Heo 
2409a9ab775bSTejun Heo 	/* am I supposed to die? */
2410a9ab775bSTejun Heo 	if (unlikely(worker->flags & WORKER_DIE)) {
2411a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
2412a9ab775bSTejun Heo 		WARN_ON_ONCE(!list_empty(&worker->entry));
2413197f6accSTejun Heo 		set_pf_worker(false);
241460f5a4bcSLai Jiangshan 
241560f5a4bcSLai Jiangshan 		set_task_comm(worker->task, "kworker/dying");
2416e441b56fSZhen Lei 		ida_free(&pool->worker_ida, worker->id);
2417a2d812a2STejun Heo 		worker_detach_from_pool(worker);
241860f5a4bcSLai Jiangshan 		kfree(worker);
2419c8e55f36STejun Heo 		return 0;
2420c8e55f36STejun Heo 	}
2421c8e55f36STejun Heo 
2422c8e55f36STejun Heo 	worker_leave_idle(worker);
2423db7bccf4STejun Heo recheck:
2424e22bee78STejun Heo 	/* no more worker necessary? */
242563d95a91STejun Heo 	if (!need_more_worker(pool))
2426e22bee78STejun Heo 		goto sleep;
2427e22bee78STejun Heo 
2428e22bee78STejun Heo 	/* do we need to manage? */
242963d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2430e22bee78STejun Heo 		goto recheck;
2431e22bee78STejun Heo 
2432c8e55f36STejun Heo 	/*
2433c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
2434c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
2435c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
2436c8e55f36STejun Heo 	 */
24376183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
2438c8e55f36STejun Heo 
2439e22bee78STejun Heo 	/*
2440a9ab775bSTejun Heo 	 * Finish PREP stage.  We're guaranteed to have at least one idle
2441a9ab775bSTejun Heo 	 * worker or that someone else has already assumed the manager
2442a9ab775bSTejun Heo 	 * role.  This is where @worker starts participating in concurrency
2443a9ab775bSTejun Heo 	 * management if applicable and concurrency management is restored
2444a9ab775bSTejun Heo 	 * after being rebound.  See rebind_workers() for details.
2445e22bee78STejun Heo 	 */
2446a9ab775bSTejun Heo 	worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2447e22bee78STejun Heo 
2448e22bee78STejun Heo 	do {
2449affee4b2STejun Heo 		struct work_struct *work =
2450bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
2451affee4b2STejun Heo 					 struct work_struct, entry);
2452affee4b2STejun Heo 
245382607adcSTejun Heo 		pool->watchdog_ts = jiffies;
245482607adcSTejun Heo 
2455c8e55f36STejun Heo 		if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2456affee4b2STejun Heo 			/* optimization path, not strictly necessary */
2457affee4b2STejun Heo 			process_one_work(worker, work);
2458affee4b2STejun Heo 			if (unlikely(!list_empty(&worker->scheduled)))
2459affee4b2STejun Heo 				process_scheduled_works(worker);
2460affee4b2STejun Heo 		} else {
2461c8e55f36STejun Heo 			move_linked_works(work, &worker->scheduled, NULL);
2462affee4b2STejun Heo 			process_scheduled_works(worker);
2463affee4b2STejun Heo 		}
246463d95a91STejun Heo 	} while (keep_working(pool));
2465affee4b2STejun Heo 
2466228f1d00SLai Jiangshan 	worker_set_flags(worker, WORKER_PREP);
2467d313dd85STejun Heo sleep:
2468c8e55f36STejun Heo 	/*
2469d565ed63STejun Heo 	 * pool->lock is held and there's no work to process and no need to
2470d565ed63STejun Heo 	 * manage, sleep.  Workers are woken up only while holding
2471d565ed63STejun Heo 	 * pool->lock or from local cpu, so setting the current state
2472d565ed63STejun Heo 	 * before releasing pool->lock is enough to prevent losing any
2473d565ed63STejun Heo 	 * event.
2474c8e55f36STejun Heo 	 */
2475c8e55f36STejun Heo 	worker_enter_idle(worker);
2476c5a94a61SPeter Zijlstra 	__set_current_state(TASK_IDLE);
2477a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
24781da177e4SLinus Torvalds 	schedule();
2479c8e55f36STejun Heo 	goto woke_up;
24801da177e4SLinus Torvalds }
24811da177e4SLinus Torvalds 
2482e22bee78STejun Heo /**
2483e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
2484111c225aSTejun Heo  * @__rescuer: self
2485e22bee78STejun Heo  *
2486e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
2487493008a8STejun Heo  * workqueue which has WQ_MEM_RECLAIM set.
2488e22bee78STejun Heo  *
2489706026c2STejun Heo  * Regular work processing on a pool may block trying to create a new
2490e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
2491e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
2492e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2493e22bee78STejun Heo  * the problem rescuer solves.
2494e22bee78STejun Heo  *
2495706026c2STejun Heo  * When such condition is possible, the pool summons rescuers of all
2496706026c2STejun Heo  * workqueues which have works queued on the pool and let them process
2497e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
2498e22bee78STejun Heo  *
2499e22bee78STejun Heo  * This should happen rarely.
2500d185af30SYacine Belkadi  *
2501d185af30SYacine Belkadi  * Return: 0
2502e22bee78STejun Heo  */
2503111c225aSTejun Heo static int rescuer_thread(void *__rescuer)
2504e22bee78STejun Heo {
2505111c225aSTejun Heo 	struct worker *rescuer = __rescuer;
2506111c225aSTejun Heo 	struct workqueue_struct *wq = rescuer->rescue_wq;
2507e22bee78STejun Heo 	struct list_head *scheduled = &rescuer->scheduled;
25084d595b86SLai Jiangshan 	bool should_stop;
2509e22bee78STejun Heo 
2510e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
2511111c225aSTejun Heo 
2512111c225aSTejun Heo 	/*
2513111c225aSTejun Heo 	 * Mark rescuer as worker too.  As WORKER_PREP is never cleared, it
2514111c225aSTejun Heo 	 * doesn't participate in concurrency management.
2515111c225aSTejun Heo 	 */
2516197f6accSTejun Heo 	set_pf_worker(true);
2517e22bee78STejun Heo repeat:
2518c5a94a61SPeter Zijlstra 	set_current_state(TASK_IDLE);
25191da177e4SLinus Torvalds 
25204d595b86SLai Jiangshan 	/*
25214d595b86SLai Jiangshan 	 * By the time the rescuer is requested to stop, the workqueue
25224d595b86SLai Jiangshan 	 * shouldn't have any work pending, but @wq->maydays may still have
25234d595b86SLai Jiangshan 	 * pwq(s) queued.  This can happen by non-rescuer workers consuming
25244d595b86SLai Jiangshan 	 * all the work items before the rescuer got to them.  Go through
25254d595b86SLai Jiangshan 	 * @wq->maydays processing before acting on should_stop so that the
25264d595b86SLai Jiangshan 	 * list is always empty on exit.
25274d595b86SLai Jiangshan 	 */
25284d595b86SLai Jiangshan 	should_stop = kthread_should_stop();
25291da177e4SLinus Torvalds 
2530493a1724STejun Heo 	/* see whether any pwq is asking for help */
2531a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&wq_mayday_lock);
2532493a1724STejun Heo 
2533493a1724STejun Heo 	while (!list_empty(&wq->maydays)) {
2534493a1724STejun Heo 		struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2535493a1724STejun Heo 					struct pool_workqueue, mayday_node);
2536112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
2537e22bee78STejun Heo 		struct work_struct *work, *n;
253882607adcSTejun Heo 		bool first = true;
2539e22bee78STejun Heo 
2540e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
2541493a1724STejun Heo 		list_del_init(&pwq->mayday_node);
2542493a1724STejun Heo 
2543a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&wq_mayday_lock);
2544e22bee78STejun Heo 
254551697d39SLai Jiangshan 		worker_attach_to_pool(rescuer, pool);
254651697d39SLai Jiangshan 
2547a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
2548e22bee78STejun Heo 
2549e22bee78STejun Heo 		/*
2550e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
2551e22bee78STejun Heo 		 * process'em.
2552e22bee78STejun Heo 		 */
25530479c8c5STejun Heo 		WARN_ON_ONCE(!list_empty(scheduled));
255482607adcSTejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry) {
255582607adcSTejun Heo 			if (get_work_pwq(work) == pwq) {
255682607adcSTejun Heo 				if (first)
255782607adcSTejun Heo 					pool->watchdog_ts = jiffies;
2558e22bee78STejun Heo 				move_linked_works(work, scheduled, &n);
255982607adcSTejun Heo 			}
256082607adcSTejun Heo 			first = false;
256182607adcSTejun Heo 		}
2562e22bee78STejun Heo 
2563008847f6SNeilBrown 		if (!list_empty(scheduled)) {
2564e22bee78STejun Heo 			process_scheduled_works(rescuer);
25657576958aSTejun Heo 
25667576958aSTejun Heo 			/*
2567008847f6SNeilBrown 			 * The above execution of rescued work items could
2568008847f6SNeilBrown 			 * have created more to rescue through
2569f97a4a1aSLai Jiangshan 			 * pwq_activate_first_inactive() or chained
2570008847f6SNeilBrown 			 * queueing.  Let's put @pwq back on mayday list so
2571008847f6SNeilBrown 			 * that such back-to-back work items, which may be
2572008847f6SNeilBrown 			 * being used to relieve memory pressure, don't
2573008847f6SNeilBrown 			 * incur MAYDAY_INTERVAL delay inbetween.
2574008847f6SNeilBrown 			 */
25754f3f4cf3SLai Jiangshan 			if (pwq->nr_active && need_to_create_worker(pool)) {
2576a9b8a985SSebastian Andrzej Siewior 				raw_spin_lock(&wq_mayday_lock);
2577e66b39afSTejun Heo 				/*
2578e66b39afSTejun Heo 				 * Queue iff we aren't racing destruction
2579e66b39afSTejun Heo 				 * and somebody else hasn't queued it already.
2580e66b39afSTejun Heo 				 */
2581e66b39afSTejun Heo 				if (wq->rescuer && list_empty(&pwq->mayday_node)) {
2582008847f6SNeilBrown 					get_pwq(pwq);
2583e66b39afSTejun Heo 					list_add_tail(&pwq->mayday_node, &wq->maydays);
2584e66b39afSTejun Heo 				}
2585a9b8a985SSebastian Andrzej Siewior 				raw_spin_unlock(&wq_mayday_lock);
2586008847f6SNeilBrown 			}
2587008847f6SNeilBrown 		}
2588008847f6SNeilBrown 
2589008847f6SNeilBrown 		/*
259077668c8bSLai Jiangshan 		 * Put the reference grabbed by send_mayday().  @pool won't
259113b1d625SLai Jiangshan 		 * go away while we're still attached to it.
259277668c8bSLai Jiangshan 		 */
259377668c8bSLai Jiangshan 		put_pwq(pwq);
259477668c8bSLai Jiangshan 
259577668c8bSLai Jiangshan 		/*
2596d8ca83e6SLai Jiangshan 		 * Leave this pool.  If need_more_worker() is %true, notify a
25977576958aSTejun Heo 		 * regular worker; otherwise, we end up with 0 concurrency
25987576958aSTejun Heo 		 * and stalling the execution.
25997576958aSTejun Heo 		 */
2600d8ca83e6SLai Jiangshan 		if (need_more_worker(pool))
260163d95a91STejun Heo 			wake_up_worker(pool);
26027576958aSTejun Heo 
2603a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
260413b1d625SLai Jiangshan 
2605a2d812a2STejun Heo 		worker_detach_from_pool(rescuer);
260613b1d625SLai Jiangshan 
2607a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&wq_mayday_lock);
26081da177e4SLinus Torvalds 	}
26091da177e4SLinus Torvalds 
2610a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&wq_mayday_lock);
2611493a1724STejun Heo 
26124d595b86SLai Jiangshan 	if (should_stop) {
26134d595b86SLai Jiangshan 		__set_current_state(TASK_RUNNING);
2614197f6accSTejun Heo 		set_pf_worker(false);
26154d595b86SLai Jiangshan 		return 0;
26164d595b86SLai Jiangshan 	}
26174d595b86SLai Jiangshan 
2618111c225aSTejun Heo 	/* rescuers should never participate in concurrency management */
2619111c225aSTejun Heo 	WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2620e22bee78STejun Heo 	schedule();
2621e22bee78STejun Heo 	goto repeat;
26221da177e4SLinus Torvalds }
26231da177e4SLinus Torvalds 
2624fca839c0STejun Heo /**
2625fca839c0STejun Heo  * check_flush_dependency - check for flush dependency sanity
2626fca839c0STejun Heo  * @target_wq: workqueue being flushed
2627fca839c0STejun Heo  * @target_work: work item being flushed (NULL for workqueue flushes)
2628fca839c0STejun Heo  *
2629fca839c0STejun Heo  * %current is trying to flush the whole @target_wq or @target_work on it.
2630fca839c0STejun Heo  * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
2631fca839c0STejun Heo  * reclaiming memory or running on a workqueue which doesn't have
2632fca839c0STejun Heo  * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
2633fca839c0STejun Heo  * a deadlock.
2634fca839c0STejun Heo  */
2635fca839c0STejun Heo static void check_flush_dependency(struct workqueue_struct *target_wq,
2636fca839c0STejun Heo 				   struct work_struct *target_work)
2637fca839c0STejun Heo {
2638fca839c0STejun Heo 	work_func_t target_func = target_work ? target_work->func : NULL;
2639fca839c0STejun Heo 	struct worker *worker;
2640fca839c0STejun Heo 
2641fca839c0STejun Heo 	if (target_wq->flags & WQ_MEM_RECLAIM)
2642fca839c0STejun Heo 		return;
2643fca839c0STejun Heo 
2644fca839c0STejun Heo 	worker = current_wq_worker();
2645fca839c0STejun Heo 
2646fca839c0STejun Heo 	WARN_ONCE(current->flags & PF_MEMALLOC,
2647d75f773cSSakari Ailus 		  "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps",
2648fca839c0STejun Heo 		  current->pid, current->comm, target_wq->name, target_func);
264923d11a58STejun Heo 	WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
265023d11a58STejun Heo 			      (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
2651d75f773cSSakari Ailus 		  "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps",
2652fca839c0STejun Heo 		  worker->current_pwq->wq->name, worker->current_func,
2653fca839c0STejun Heo 		  target_wq->name, target_func);
2654fca839c0STejun Heo }
2655fca839c0STejun Heo 
2656fc2e4d70SOleg Nesterov struct wq_barrier {
2657fc2e4d70SOleg Nesterov 	struct work_struct	work;
2658fc2e4d70SOleg Nesterov 	struct completion	done;
26592607d7a6STejun Heo 	struct task_struct	*task;	/* purely informational */
2660fc2e4d70SOleg Nesterov };
2661fc2e4d70SOleg Nesterov 
2662fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
2663fc2e4d70SOleg Nesterov {
2664fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2665fc2e4d70SOleg Nesterov 	complete(&barr->done);
2666fc2e4d70SOleg Nesterov }
2667fc2e4d70SOleg Nesterov 
26684690c4abSTejun Heo /**
26694690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
2670112202d9STejun Heo  * @pwq: pwq to insert barrier into
26714690c4abSTejun Heo  * @barr: wq_barrier to insert
2672affee4b2STejun Heo  * @target: target work to attach @barr to
2673affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
26744690c4abSTejun Heo  *
2675affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
2676affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
2677affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
2678affee4b2STejun Heo  * cpu.
2679affee4b2STejun Heo  *
2680affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
2681affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
2682affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
2683affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
2684affee4b2STejun Heo  * after a work with LINKED flag set.
2685affee4b2STejun Heo  *
2686affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
2687112202d9STejun Heo  * underneath us, so we can't reliably determine pwq from @target.
26884690c4abSTejun Heo  *
26894690c4abSTejun Heo  * CONTEXT:
2690a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
26914690c4abSTejun Heo  */
2692112202d9STejun Heo static void insert_wq_barrier(struct pool_workqueue *pwq,
2693affee4b2STejun Heo 			      struct wq_barrier *barr,
2694affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
2695fc2e4d70SOleg Nesterov {
2696d812796eSLai Jiangshan 	unsigned int work_flags = 0;
2697d812796eSLai Jiangshan 	unsigned int work_color;
2698affee4b2STejun Heo 	struct list_head *head;
2699affee4b2STejun Heo 
2700dc186ad7SThomas Gleixner 	/*
2701d565ed63STejun Heo 	 * debugobject calls are safe here even with pool->lock locked
2702dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
2703dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
2704dc186ad7SThomas Gleixner 	 * might deadlock.
2705dc186ad7SThomas Gleixner 	 */
2706ca1cab37SAndrew Morton 	INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
270722df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
270852fa5bc5SBoqun Feng 
2709fd1a5b04SByungchul Park 	init_completion_map(&barr->done, &target->lockdep_map);
2710fd1a5b04SByungchul Park 
27112607d7a6STejun Heo 	barr->task = current;
271283c22520SOleg Nesterov 
2713018f3a13SLai Jiangshan 	/* The barrier work item does not participate in pwq->nr_active. */
2714018f3a13SLai Jiangshan 	work_flags |= WORK_STRUCT_INACTIVE;
2715018f3a13SLai Jiangshan 
2716affee4b2STejun Heo 	/*
2717affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
2718affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
2719affee4b2STejun Heo 	 */
2720d812796eSLai Jiangshan 	if (worker) {
2721affee4b2STejun Heo 		head = worker->scheduled.next;
2722d812796eSLai Jiangshan 		work_color = worker->current_color;
2723d812796eSLai Jiangshan 	} else {
2724affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
2725affee4b2STejun Heo 
2726affee4b2STejun Heo 		head = target->entry.next;
2727affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
2728d21cece0SLai Jiangshan 		work_flags |= *bits & WORK_STRUCT_LINKED;
2729d812796eSLai Jiangshan 		work_color = get_work_color(*bits);
2730affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
2731affee4b2STejun Heo 	}
2732affee4b2STejun Heo 
2733d812796eSLai Jiangshan 	pwq->nr_in_flight[work_color]++;
2734d812796eSLai Jiangshan 	work_flags |= work_color_to_flags(work_color);
2735d812796eSLai Jiangshan 
2736dc186ad7SThomas Gleixner 	debug_work_activate(&barr->work);
2737d21cece0SLai Jiangshan 	insert_work(pwq, &barr->work, head, work_flags);
2738fc2e4d70SOleg Nesterov }
2739fc2e4d70SOleg Nesterov 
274073f53c4aSTejun Heo /**
2741112202d9STejun Heo  * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
274273f53c4aSTejun Heo  * @wq: workqueue being flushed
274373f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
274473f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
274573f53c4aSTejun Heo  *
2746112202d9STejun Heo  * Prepare pwqs for workqueue flushing.
274773f53c4aSTejun Heo  *
2748112202d9STejun Heo  * If @flush_color is non-negative, flush_color on all pwqs should be
2749112202d9STejun Heo  * -1.  If no pwq has in-flight commands at the specified color, all
2750112202d9STejun Heo  * pwq->flush_color's stay at -1 and %false is returned.  If any pwq
2751112202d9STejun Heo  * has in flight commands, its pwq->flush_color is set to
2752112202d9STejun Heo  * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
275373f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
275473f53c4aSTejun Heo  *
275573f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
275673f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
275773f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
275873f53c4aSTejun Heo  * is returned.
275973f53c4aSTejun Heo  *
2760112202d9STejun Heo  * If @work_color is non-negative, all pwqs should have the same
276173f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
276273f53c4aSTejun Heo  * advanced to @work_color.
276373f53c4aSTejun Heo  *
276473f53c4aSTejun Heo  * CONTEXT:
27653c25a55dSLai Jiangshan  * mutex_lock(wq->mutex).
276673f53c4aSTejun Heo  *
2767d185af30SYacine Belkadi  * Return:
276873f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
276973f53c4aSTejun Heo  * otherwise.
277073f53c4aSTejun Heo  */
2771112202d9STejun Heo static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
277273f53c4aSTejun Heo 				      int flush_color, int work_color)
27731da177e4SLinus Torvalds {
277473f53c4aSTejun Heo 	bool wait = false;
277549e3cf44STejun Heo 	struct pool_workqueue *pwq;
27761da177e4SLinus Torvalds 
277773f53c4aSTejun Heo 	if (flush_color >= 0) {
27786183c009STejun Heo 		WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2779112202d9STejun Heo 		atomic_set(&wq->nr_pwqs_to_flush, 1);
2780dc186ad7SThomas Gleixner 	}
278114441960SOleg Nesterov 
278249e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2783112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
27841da177e4SLinus Torvalds 
2785a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
278673f53c4aSTejun Heo 
278773f53c4aSTejun Heo 		if (flush_color >= 0) {
27886183c009STejun Heo 			WARN_ON_ONCE(pwq->flush_color != -1);
278973f53c4aSTejun Heo 
2790112202d9STejun Heo 			if (pwq->nr_in_flight[flush_color]) {
2791112202d9STejun Heo 				pwq->flush_color = flush_color;
2792112202d9STejun Heo 				atomic_inc(&wq->nr_pwqs_to_flush);
279373f53c4aSTejun Heo 				wait = true;
27941da177e4SLinus Torvalds 			}
279573f53c4aSTejun Heo 		}
279673f53c4aSTejun Heo 
279773f53c4aSTejun Heo 		if (work_color >= 0) {
27986183c009STejun Heo 			WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2799112202d9STejun Heo 			pwq->work_color = work_color;
280073f53c4aSTejun Heo 		}
280173f53c4aSTejun Heo 
2802a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
28031da177e4SLinus Torvalds 	}
28041da177e4SLinus Torvalds 
2805112202d9STejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
280673f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
280773f53c4aSTejun Heo 
280873f53c4aSTejun Heo 	return wait;
280983c22520SOleg Nesterov }
28101da177e4SLinus Torvalds 
28110fcb78c2SRolf Eike Beer /**
2812c4f135d6STetsuo Handa  * __flush_workqueue - ensure that any scheduled work has run to completion.
28130fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
28141da177e4SLinus Torvalds  *
2815c5aa87bbSTejun Heo  * This function sleeps until all work items which were queued on entry
2816c5aa87bbSTejun Heo  * have finished execution, but it is not livelocked by new incoming ones.
28171da177e4SLinus Torvalds  */
2818c4f135d6STetsuo Handa void __flush_workqueue(struct workqueue_struct *wq)
28191da177e4SLinus Torvalds {
282073f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
282173f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
282273f53c4aSTejun Heo 		.flush_color = -1,
2823fd1a5b04SByungchul Park 		.done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map),
282473f53c4aSTejun Heo 	};
282573f53c4aSTejun Heo 	int next_color;
2826b1f4ec17SOleg Nesterov 
28273347fa09STejun Heo 	if (WARN_ON(!wq_online))
28283347fa09STejun Heo 		return;
28293347fa09STejun Heo 
283087915adcSJohannes Berg 	lock_map_acquire(&wq->lockdep_map);
283187915adcSJohannes Berg 	lock_map_release(&wq->lockdep_map);
283287915adcSJohannes Berg 
28333c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
283473f53c4aSTejun Heo 
283573f53c4aSTejun Heo 	/*
283673f53c4aSTejun Heo 	 * Start-to-wait phase
283773f53c4aSTejun Heo 	 */
283873f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
283973f53c4aSTejun Heo 
284073f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
284173f53c4aSTejun Heo 		/*
284273f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
284373f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
284473f53c4aSTejun Heo 		 * by one.
284573f53c4aSTejun Heo 		 */
28466183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
284773f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
284873f53c4aSTejun Heo 		wq->work_color = next_color;
284973f53c4aSTejun Heo 
285073f53c4aSTejun Heo 		if (!wq->first_flusher) {
285173f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
28526183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
285373f53c4aSTejun Heo 
285473f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
285573f53c4aSTejun Heo 
2856112202d9STejun Heo 			if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
285773f53c4aSTejun Heo 						       wq->work_color)) {
285873f53c4aSTejun Heo 				/* nothing to flush, done */
285973f53c4aSTejun Heo 				wq->flush_color = next_color;
286073f53c4aSTejun Heo 				wq->first_flusher = NULL;
286173f53c4aSTejun Heo 				goto out_unlock;
286273f53c4aSTejun Heo 			}
286373f53c4aSTejun Heo 		} else {
286473f53c4aSTejun Heo 			/* wait in queue */
28656183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
286673f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
2867112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
286873f53c4aSTejun Heo 		}
286973f53c4aSTejun Heo 	} else {
287073f53c4aSTejun Heo 		/*
287173f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
287273f53c4aSTejun Heo 		 * The next flush completion will assign us
287373f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
287473f53c4aSTejun Heo 		 */
287573f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
287673f53c4aSTejun Heo 	}
287773f53c4aSTejun Heo 
2878fca839c0STejun Heo 	check_flush_dependency(wq, NULL);
2879fca839c0STejun Heo 
28803c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
288173f53c4aSTejun Heo 
288273f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
288373f53c4aSTejun Heo 
288473f53c4aSTejun Heo 	/*
288573f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
288673f53c4aSTejun Heo 	 *
288773f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
288873f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
288973f53c4aSTejun Heo 	 */
289000d5d15bSChris Wilson 	if (READ_ONCE(wq->first_flusher) != &this_flusher)
289173f53c4aSTejun Heo 		return;
289273f53c4aSTejun Heo 
28933c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
289473f53c4aSTejun Heo 
28954ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
28964ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
28974ce48b37STejun Heo 		goto out_unlock;
28984ce48b37STejun Heo 
289900d5d15bSChris Wilson 	WRITE_ONCE(wq->first_flusher, NULL);
290073f53c4aSTejun Heo 
29016183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&this_flusher.list));
29026183c009STejun Heo 	WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
290373f53c4aSTejun Heo 
290473f53c4aSTejun Heo 	while (true) {
290573f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
290673f53c4aSTejun Heo 
290773f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
290873f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
290973f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
291073f53c4aSTejun Heo 				break;
291173f53c4aSTejun Heo 			list_del_init(&next->list);
291273f53c4aSTejun Heo 			complete(&next->done);
291373f53c4aSTejun Heo 		}
291473f53c4aSTejun Heo 
29156183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
291673f53c4aSTejun Heo 			     wq->flush_color != work_next_color(wq->work_color));
291773f53c4aSTejun Heo 
291873f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
291973f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
292073f53c4aSTejun Heo 
292173f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
292273f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
292373f53c4aSTejun Heo 			/*
292473f53c4aSTejun Heo 			 * Assign the same color to all overflowed
292573f53c4aSTejun Heo 			 * flushers, advance work_color and append to
292673f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
292773f53c4aSTejun Heo 			 * phase for these overflowed flushers.
292873f53c4aSTejun Heo 			 */
292973f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
293073f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
293173f53c4aSTejun Heo 
293273f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
293373f53c4aSTejun Heo 
293473f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
293573f53c4aSTejun Heo 					      &wq->flusher_queue);
2936112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
293773f53c4aSTejun Heo 		}
293873f53c4aSTejun Heo 
293973f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
29406183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != wq->work_color);
294173f53c4aSTejun Heo 			break;
294273f53c4aSTejun Heo 		}
294373f53c4aSTejun Heo 
294473f53c4aSTejun Heo 		/*
294573f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
2946112202d9STejun Heo 		 * the new first flusher and arm pwqs.
294773f53c4aSTejun Heo 		 */
29486183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color == wq->work_color);
29496183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color != next->flush_color);
295073f53c4aSTejun Heo 
295173f53c4aSTejun Heo 		list_del_init(&next->list);
295273f53c4aSTejun Heo 		wq->first_flusher = next;
295373f53c4aSTejun Heo 
2954112202d9STejun Heo 		if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
295573f53c4aSTejun Heo 			break;
295673f53c4aSTejun Heo 
295773f53c4aSTejun Heo 		/*
295873f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
295973f53c4aSTejun Heo 		 * flusher and repeat cascading.
296073f53c4aSTejun Heo 		 */
296173f53c4aSTejun Heo 		wq->first_flusher = NULL;
296273f53c4aSTejun Heo 	}
296373f53c4aSTejun Heo 
296473f53c4aSTejun Heo out_unlock:
29653c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
29661da177e4SLinus Torvalds }
2967c4f135d6STetsuo Handa EXPORT_SYMBOL(__flush_workqueue);
29681da177e4SLinus Torvalds 
29699c5a2ba7STejun Heo /**
29709c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
29719c5a2ba7STejun Heo  * @wq: workqueue to drain
29729c5a2ba7STejun Heo  *
29739c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
29749c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
29759c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
2976b749b1b6SChen Hanxiao  * repeatedly until it becomes empty.  The number of flushing is determined
29779c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
29789c5a2ba7STejun Heo  * takes too long.
29799c5a2ba7STejun Heo  */
29809c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
29819c5a2ba7STejun Heo {
29829c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
298349e3cf44STejun Heo 	struct pool_workqueue *pwq;
29849c5a2ba7STejun Heo 
29859c5a2ba7STejun Heo 	/*
29869c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
29879c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
2988618b01ebSTejun Heo 	 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
29899c5a2ba7STejun Heo 	 */
299087fc741eSLai Jiangshan 	mutex_lock(&wq->mutex);
29919c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
2992618b01ebSTejun Heo 		wq->flags |= __WQ_DRAINING;
299387fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
29949c5a2ba7STejun Heo reflush:
2995c4f135d6STetsuo Handa 	__flush_workqueue(wq);
29969c5a2ba7STejun Heo 
2997b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
299876af4d93STejun Heo 
299949e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
3000fa2563e4SThomas Tuttle 		bool drained;
30019c5a2ba7STejun Heo 
3002a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
3003f97a4a1aSLai Jiangshan 		drained = !pwq->nr_active && list_empty(&pwq->inactive_works);
3004a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
3005fa2563e4SThomas Tuttle 
3006fa2563e4SThomas Tuttle 		if (drained)
30079c5a2ba7STejun Heo 			continue;
30089c5a2ba7STejun Heo 
30099c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
30109c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
3011e9ad2eb3SStephen Zhang 			pr_warn("workqueue %s: %s() isn't complete after %u tries\n",
3012e9ad2eb3SStephen Zhang 				wq->name, __func__, flush_cnt);
301376af4d93STejun Heo 
3014b09f4fd3SLai Jiangshan 		mutex_unlock(&wq->mutex);
30159c5a2ba7STejun Heo 		goto reflush;
30169c5a2ba7STejun Heo 	}
30179c5a2ba7STejun Heo 
30189c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
3019618b01ebSTejun Heo 		wq->flags &= ~__WQ_DRAINING;
302087fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
30219c5a2ba7STejun Heo }
30229c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
30239c5a2ba7STejun Heo 
3024d6e89786SJohannes Berg static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
3025d6e89786SJohannes Berg 			     bool from_cancel)
3026baf59022STejun Heo {
3027baf59022STejun Heo 	struct worker *worker = NULL;
3028c9e7cf27STejun Heo 	struct worker_pool *pool;
3029112202d9STejun Heo 	struct pool_workqueue *pwq;
3030baf59022STejun Heo 
3031baf59022STejun Heo 	might_sleep();
3032baf59022STejun Heo 
303324acfb71SThomas Gleixner 	rcu_read_lock();
3034fa1b54e6STejun Heo 	pool = get_work_pool(work);
3035fa1b54e6STejun Heo 	if (!pool) {
303624acfb71SThomas Gleixner 		rcu_read_unlock();
3037fa1b54e6STejun Heo 		return false;
3038fa1b54e6STejun Heo 	}
3039fa1b54e6STejun Heo 
3040a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
30410b3dae68SLai Jiangshan 	/* see the comment in try_to_grab_pending() with the same code */
3042112202d9STejun Heo 	pwq = get_work_pwq(work);
3043112202d9STejun Heo 	if (pwq) {
3044112202d9STejun Heo 		if (unlikely(pwq->pool != pool))
3045baf59022STejun Heo 			goto already_gone;
3046606a5020STejun Heo 	} else {
3047c9e7cf27STejun Heo 		worker = find_worker_executing_work(pool, work);
3048baf59022STejun Heo 		if (!worker)
3049baf59022STejun Heo 			goto already_gone;
3050112202d9STejun Heo 		pwq = worker->current_pwq;
3051606a5020STejun Heo 	}
3052baf59022STejun Heo 
3053fca839c0STejun Heo 	check_flush_dependency(pwq->wq, work);
3054fca839c0STejun Heo 
3055112202d9STejun Heo 	insert_wq_barrier(pwq, barr, work, worker);
3056a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
3057baf59022STejun Heo 
3058e159489bSTejun Heo 	/*
3059a1d14934SPeter Zijlstra 	 * Force a lock recursion deadlock when using flush_work() inside a
3060a1d14934SPeter Zijlstra 	 * single-threaded or rescuer equipped workqueue.
3061a1d14934SPeter Zijlstra 	 *
3062a1d14934SPeter Zijlstra 	 * For single threaded workqueues the deadlock happens when the work
3063a1d14934SPeter Zijlstra 	 * is after the work issuing the flush_work(). For rescuer equipped
3064a1d14934SPeter Zijlstra 	 * workqueues the deadlock happens when the rescuer stalls, blocking
3065a1d14934SPeter Zijlstra 	 * forward progress.
3066e159489bSTejun Heo 	 */
3067d6e89786SJohannes Berg 	if (!from_cancel &&
3068d6e89786SJohannes Berg 	    (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)) {
3069112202d9STejun Heo 		lock_map_acquire(&pwq->wq->lockdep_map);
3070112202d9STejun Heo 		lock_map_release(&pwq->wq->lockdep_map);
3071a1d14934SPeter Zijlstra 	}
307224acfb71SThomas Gleixner 	rcu_read_unlock();
3073baf59022STejun Heo 	return true;
3074baf59022STejun Heo already_gone:
3075a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
307624acfb71SThomas Gleixner 	rcu_read_unlock();
3077baf59022STejun Heo 	return false;
3078baf59022STejun Heo }
3079baf59022STejun Heo 
3080d6e89786SJohannes Berg static bool __flush_work(struct work_struct *work, bool from_cancel)
3081d6e89786SJohannes Berg {
3082d6e89786SJohannes Berg 	struct wq_barrier barr;
3083d6e89786SJohannes Berg 
3084d6e89786SJohannes Berg 	if (WARN_ON(!wq_online))
3085d6e89786SJohannes Berg 		return false;
3086d6e89786SJohannes Berg 
30874d43d395STetsuo Handa 	if (WARN_ON(!work->func))
30884d43d395STetsuo Handa 		return false;
30894d43d395STetsuo Handa 
309087915adcSJohannes Berg 	lock_map_acquire(&work->lockdep_map);
309187915adcSJohannes Berg 	lock_map_release(&work->lockdep_map);
309287915adcSJohannes Berg 
3093d6e89786SJohannes Berg 	if (start_flush_work(work, &barr, from_cancel)) {
3094d6e89786SJohannes Berg 		wait_for_completion(&barr.done);
3095d6e89786SJohannes Berg 		destroy_work_on_stack(&barr.work);
3096d6e89786SJohannes Berg 		return true;
3097d6e89786SJohannes Berg 	} else {
3098d6e89786SJohannes Berg 		return false;
3099d6e89786SJohannes Berg 	}
3100d6e89786SJohannes Berg }
3101d6e89786SJohannes Berg 
3102db700897SOleg Nesterov /**
3103401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
3104401a8d04STejun Heo  * @work: the work to flush
3105db700897SOleg Nesterov  *
3106606a5020STejun Heo  * Wait until @work has finished execution.  @work is guaranteed to be idle
3107606a5020STejun Heo  * on return if it hasn't been requeued since flush started.
3108401a8d04STejun Heo  *
3109d185af30SYacine Belkadi  * Return:
3110401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3111401a8d04STejun Heo  * %false if it was already idle.
3112db700897SOleg Nesterov  */
3113401a8d04STejun Heo bool flush_work(struct work_struct *work)
3114db700897SOleg Nesterov {
3115d6e89786SJohannes Berg 	return __flush_work(work, false);
3116606a5020STejun Heo }
3117db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
3118db700897SOleg Nesterov 
31198603e1b3STejun Heo struct cwt_wait {
3120ac6424b9SIngo Molnar 	wait_queue_entry_t		wait;
31218603e1b3STejun Heo 	struct work_struct	*work;
31228603e1b3STejun Heo };
31238603e1b3STejun Heo 
3124ac6424b9SIngo Molnar static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
31258603e1b3STejun Heo {
31268603e1b3STejun Heo 	struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
31278603e1b3STejun Heo 
31288603e1b3STejun Heo 	if (cwait->work != key)
31298603e1b3STejun Heo 		return 0;
31308603e1b3STejun Heo 	return autoremove_wake_function(wait, mode, sync, key);
31318603e1b3STejun Heo }
31328603e1b3STejun Heo 
313336e227d2STejun Heo static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
3134401a8d04STejun Heo {
31358603e1b3STejun Heo 	static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
3136bbb68dfaSTejun Heo 	unsigned long flags;
31371f1f642eSOleg Nesterov 	int ret;
31381f1f642eSOleg Nesterov 
31391f1f642eSOleg Nesterov 	do {
3140bbb68dfaSTejun Heo 		ret = try_to_grab_pending(work, is_dwork, &flags);
3141bbb68dfaSTejun Heo 		/*
31428603e1b3STejun Heo 		 * If someone else is already canceling, wait for it to
31438603e1b3STejun Heo 		 * finish.  flush_work() doesn't work for PREEMPT_NONE
31448603e1b3STejun Heo 		 * because we may get scheduled between @work's completion
31458603e1b3STejun Heo 		 * and the other canceling task resuming and clearing
31468603e1b3STejun Heo 		 * CANCELING - flush_work() will return false immediately
31478603e1b3STejun Heo 		 * as @work is no longer busy, try_to_grab_pending() will
31488603e1b3STejun Heo 		 * return -ENOENT as @work is still being canceled and the
31498603e1b3STejun Heo 		 * other canceling task won't be able to clear CANCELING as
31508603e1b3STejun Heo 		 * we're hogging the CPU.
31518603e1b3STejun Heo 		 *
31528603e1b3STejun Heo 		 * Let's wait for completion using a waitqueue.  As this
31538603e1b3STejun Heo 		 * may lead to the thundering herd problem, use a custom
31548603e1b3STejun Heo 		 * wake function which matches @work along with exclusive
31558603e1b3STejun Heo 		 * wait and wakeup.
3156bbb68dfaSTejun Heo 		 */
31578603e1b3STejun Heo 		if (unlikely(ret == -ENOENT)) {
31588603e1b3STejun Heo 			struct cwt_wait cwait;
31598603e1b3STejun Heo 
31608603e1b3STejun Heo 			init_wait(&cwait.wait);
31618603e1b3STejun Heo 			cwait.wait.func = cwt_wakefn;
31628603e1b3STejun Heo 			cwait.work = work;
31638603e1b3STejun Heo 
31648603e1b3STejun Heo 			prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
31658603e1b3STejun Heo 						  TASK_UNINTERRUPTIBLE);
31668603e1b3STejun Heo 			if (work_is_canceling(work))
31678603e1b3STejun Heo 				schedule();
31688603e1b3STejun Heo 			finish_wait(&cancel_waitq, &cwait.wait);
31698603e1b3STejun Heo 		}
31701f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
31711f1f642eSOleg Nesterov 
3172bbb68dfaSTejun Heo 	/* tell other tasks trying to grab @work to back off */
3173bbb68dfaSTejun Heo 	mark_work_canceling(work);
3174bbb68dfaSTejun Heo 	local_irq_restore(flags);
3175bbb68dfaSTejun Heo 
31763347fa09STejun Heo 	/*
31773347fa09STejun Heo 	 * This allows canceling during early boot.  We know that @work
31783347fa09STejun Heo 	 * isn't executing.
31793347fa09STejun Heo 	 */
31803347fa09STejun Heo 	if (wq_online)
3181d6e89786SJohannes Berg 		__flush_work(work, true);
31823347fa09STejun Heo 
31837a22ad75STejun Heo 	clear_work_data(work);
31848603e1b3STejun Heo 
31858603e1b3STejun Heo 	/*
31868603e1b3STejun Heo 	 * Paired with prepare_to_wait() above so that either
31878603e1b3STejun Heo 	 * waitqueue_active() is visible here or !work_is_canceling() is
31888603e1b3STejun Heo 	 * visible there.
31898603e1b3STejun Heo 	 */
31908603e1b3STejun Heo 	smp_mb();
31918603e1b3STejun Heo 	if (waitqueue_active(&cancel_waitq))
31928603e1b3STejun Heo 		__wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
31938603e1b3STejun Heo 
31941f1f642eSOleg Nesterov 	return ret;
31951f1f642eSOleg Nesterov }
31961f1f642eSOleg Nesterov 
31976e84d644SOleg Nesterov /**
3198401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
3199401a8d04STejun Heo  * @work: the work to cancel
32006e84d644SOleg Nesterov  *
3201401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
3202401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
3203401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
3204401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
32051f1f642eSOleg Nesterov  *
3206401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
3207401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
32086e84d644SOleg Nesterov  *
3209401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
32106e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
3211401a8d04STejun Heo  *
3212d185af30SYacine Belkadi  * Return:
3213401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
32146e84d644SOleg Nesterov  */
3215401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
32166e84d644SOleg Nesterov {
321736e227d2STejun Heo 	return __cancel_work_timer(work, false);
3218b89deed3SOleg Nesterov }
321928e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
3220b89deed3SOleg Nesterov 
32216e84d644SOleg Nesterov /**
3222401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
3223401a8d04STejun Heo  * @dwork: the delayed work to flush
32246e84d644SOleg Nesterov  *
3225401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
3226401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
3227401a8d04STejun Heo  * considers the last queueing instance of @dwork.
32281f1f642eSOleg Nesterov  *
3229d185af30SYacine Belkadi  * Return:
3230401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3231401a8d04STejun Heo  * %false if it was already idle.
32326e84d644SOleg Nesterov  */
3233401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
3234401a8d04STejun Heo {
32358930cabaSTejun Heo 	local_irq_disable();
3236401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
323760c057bcSLai Jiangshan 		__queue_work(dwork->cpu, dwork->wq, &dwork->work);
32388930cabaSTejun Heo 	local_irq_enable();
3239401a8d04STejun Heo 	return flush_work(&dwork->work);
3240401a8d04STejun Heo }
3241401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
3242401a8d04STejun Heo 
324305f0fe6bSTejun Heo /**
324405f0fe6bSTejun Heo  * flush_rcu_work - wait for a rwork to finish executing the last queueing
324505f0fe6bSTejun Heo  * @rwork: the rcu work to flush
324605f0fe6bSTejun Heo  *
324705f0fe6bSTejun Heo  * Return:
324805f0fe6bSTejun Heo  * %true if flush_rcu_work() waited for the work to finish execution,
324905f0fe6bSTejun Heo  * %false if it was already idle.
325005f0fe6bSTejun Heo  */
325105f0fe6bSTejun Heo bool flush_rcu_work(struct rcu_work *rwork)
325205f0fe6bSTejun Heo {
325305f0fe6bSTejun Heo 	if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
325405f0fe6bSTejun Heo 		rcu_barrier();
325505f0fe6bSTejun Heo 		flush_work(&rwork->work);
325605f0fe6bSTejun Heo 		return true;
325705f0fe6bSTejun Heo 	} else {
325805f0fe6bSTejun Heo 		return flush_work(&rwork->work);
325905f0fe6bSTejun Heo 	}
326005f0fe6bSTejun Heo }
326105f0fe6bSTejun Heo EXPORT_SYMBOL(flush_rcu_work);
326205f0fe6bSTejun Heo 
3263f72b8792SJens Axboe static bool __cancel_work(struct work_struct *work, bool is_dwork)
3264f72b8792SJens Axboe {
3265f72b8792SJens Axboe 	unsigned long flags;
3266f72b8792SJens Axboe 	int ret;
3267f72b8792SJens Axboe 
3268f72b8792SJens Axboe 	do {
3269f72b8792SJens Axboe 		ret = try_to_grab_pending(work, is_dwork, &flags);
3270f72b8792SJens Axboe 	} while (unlikely(ret == -EAGAIN));
3271f72b8792SJens Axboe 
3272f72b8792SJens Axboe 	if (unlikely(ret < 0))
3273f72b8792SJens Axboe 		return false;
3274f72b8792SJens Axboe 
3275f72b8792SJens Axboe 	set_work_pool_and_clear_pending(work, get_work_pool_id(work));
3276f72b8792SJens Axboe 	local_irq_restore(flags);
3277f72b8792SJens Axboe 	return ret;
3278f72b8792SJens Axboe }
3279f72b8792SJens Axboe 
328073b4b532SAndrey Grodzovsky /*
328173b4b532SAndrey Grodzovsky  * See cancel_delayed_work()
328273b4b532SAndrey Grodzovsky  */
328373b4b532SAndrey Grodzovsky bool cancel_work(struct work_struct *work)
328473b4b532SAndrey Grodzovsky {
328573b4b532SAndrey Grodzovsky 	return __cancel_work(work, false);
328673b4b532SAndrey Grodzovsky }
328773b4b532SAndrey Grodzovsky EXPORT_SYMBOL(cancel_work);
328873b4b532SAndrey Grodzovsky 
3289401a8d04STejun Heo /**
329057b30ae7STejun Heo  * cancel_delayed_work - cancel a delayed work
329157b30ae7STejun Heo  * @dwork: delayed_work to cancel
329209383498STejun Heo  *
3293d185af30SYacine Belkadi  * Kill off a pending delayed_work.
3294d185af30SYacine Belkadi  *
3295d185af30SYacine Belkadi  * Return: %true if @dwork was pending and canceled; %false if it wasn't
3296d185af30SYacine Belkadi  * pending.
3297d185af30SYacine Belkadi  *
3298d185af30SYacine Belkadi  * Note:
3299d185af30SYacine Belkadi  * The work callback function may still be running on return, unless
3300d185af30SYacine Belkadi  * it returns %true and the work doesn't re-arm itself.  Explicitly flush or
3301d185af30SYacine Belkadi  * use cancel_delayed_work_sync() to wait on it.
330209383498STejun Heo  *
330357b30ae7STejun Heo  * This function is safe to call from any context including IRQ handler.
330409383498STejun Heo  */
330557b30ae7STejun Heo bool cancel_delayed_work(struct delayed_work *dwork)
330609383498STejun Heo {
3307f72b8792SJens Axboe 	return __cancel_work(&dwork->work, true);
330809383498STejun Heo }
330957b30ae7STejun Heo EXPORT_SYMBOL(cancel_delayed_work);
331009383498STejun Heo 
331109383498STejun Heo /**
3312401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3313401a8d04STejun Heo  * @dwork: the delayed work cancel
3314401a8d04STejun Heo  *
3315401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
3316401a8d04STejun Heo  *
3317d185af30SYacine Belkadi  * Return:
3318401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
3319401a8d04STejun Heo  */
3320401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
33216e84d644SOleg Nesterov {
332236e227d2STejun Heo 	return __cancel_work_timer(&dwork->work, true);
33236e84d644SOleg Nesterov }
3324f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
33251da177e4SLinus Torvalds 
33260fcb78c2SRolf Eike Beer /**
332731ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
3328b6136773SAndrew Morton  * @func: the function to call
3329b6136773SAndrew Morton  *
333031ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
333131ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
3332b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
333331ddd871STejun Heo  *
3334d185af30SYacine Belkadi  * Return:
333531ddd871STejun Heo  * 0 on success, -errno on failure.
3336b6136773SAndrew Morton  */
333765f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
333815316ba8SChristoph Lameter {
333915316ba8SChristoph Lameter 	int cpu;
334038f51568SNamhyung Kim 	struct work_struct __percpu *works;
334115316ba8SChristoph Lameter 
3342b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
3343b6136773SAndrew Morton 	if (!works)
334415316ba8SChristoph Lameter 		return -ENOMEM;
3345b6136773SAndrew Morton 
3346ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
334793981800STejun Heo 
334815316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
33499bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
33509bfb1839SIngo Molnar 
33519bfb1839SIngo Molnar 		INIT_WORK(work, func);
33528de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
335315316ba8SChristoph Lameter 	}
335493981800STejun Heo 
335593981800STejun Heo 	for_each_online_cpu(cpu)
33568616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
335793981800STejun Heo 
3358ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
3359b6136773SAndrew Morton 	free_percpu(works);
336015316ba8SChristoph Lameter 	return 0;
336115316ba8SChristoph Lameter }
336215316ba8SChristoph Lameter 
3363eef6a7d5SAlan Stern /**
33641fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
33651fa44ecaSJames Bottomley  * @fn:		the function to execute
33661fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
33671fa44ecaSJames Bottomley  *		be available when the work executes)
33681fa44ecaSJames Bottomley  *
33691fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
33701fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
33711fa44ecaSJames Bottomley  *
3372d185af30SYacine Belkadi  * Return:	0 - function was executed
33731fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
33741fa44ecaSJames Bottomley  */
337565f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
33761fa44ecaSJames Bottomley {
33771fa44ecaSJames Bottomley 	if (!in_interrupt()) {
337865f27f38SDavid Howells 		fn(&ew->work);
33791fa44ecaSJames Bottomley 		return 0;
33801fa44ecaSJames Bottomley 	}
33811fa44ecaSJames Bottomley 
338265f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
33831fa44ecaSJames Bottomley 	schedule_work(&ew->work);
33841fa44ecaSJames Bottomley 
33851fa44ecaSJames Bottomley 	return 1;
33861fa44ecaSJames Bottomley }
33871fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
33881fa44ecaSJames Bottomley 
33897a4e344cSTejun Heo /**
33907a4e344cSTejun Heo  * free_workqueue_attrs - free a workqueue_attrs
33917a4e344cSTejun Heo  * @attrs: workqueue_attrs to free
33927a4e344cSTejun Heo  *
33937a4e344cSTejun Heo  * Undo alloc_workqueue_attrs().
33947a4e344cSTejun Heo  */
3395513c98d0SDaniel Jordan void free_workqueue_attrs(struct workqueue_attrs *attrs)
33967a4e344cSTejun Heo {
33977a4e344cSTejun Heo 	if (attrs) {
33987a4e344cSTejun Heo 		free_cpumask_var(attrs->cpumask);
33997a4e344cSTejun Heo 		kfree(attrs);
34007a4e344cSTejun Heo 	}
34017a4e344cSTejun Heo }
34027a4e344cSTejun Heo 
34037a4e344cSTejun Heo /**
34047a4e344cSTejun Heo  * alloc_workqueue_attrs - allocate a workqueue_attrs
34057a4e344cSTejun Heo  *
34067a4e344cSTejun Heo  * Allocate a new workqueue_attrs, initialize with default settings and
3407d185af30SYacine Belkadi  * return it.
3408d185af30SYacine Belkadi  *
3409d185af30SYacine Belkadi  * Return: The allocated new workqueue_attr on success. %NULL on failure.
34107a4e344cSTejun Heo  */
3411513c98d0SDaniel Jordan struct workqueue_attrs *alloc_workqueue_attrs(void)
34127a4e344cSTejun Heo {
34137a4e344cSTejun Heo 	struct workqueue_attrs *attrs;
34147a4e344cSTejun Heo 
3415be69d00dSThomas Gleixner 	attrs = kzalloc(sizeof(*attrs), GFP_KERNEL);
34167a4e344cSTejun Heo 	if (!attrs)
34177a4e344cSTejun Heo 		goto fail;
3418be69d00dSThomas Gleixner 	if (!alloc_cpumask_var(&attrs->cpumask, GFP_KERNEL))
34197a4e344cSTejun Heo 		goto fail;
34207a4e344cSTejun Heo 
342113e2e556STejun Heo 	cpumask_copy(attrs->cpumask, cpu_possible_mask);
34227a4e344cSTejun Heo 	return attrs;
34237a4e344cSTejun Heo fail:
34247a4e344cSTejun Heo 	free_workqueue_attrs(attrs);
34257a4e344cSTejun Heo 	return NULL;
34267a4e344cSTejun Heo }
34277a4e344cSTejun Heo 
342829c91e99STejun Heo static void copy_workqueue_attrs(struct workqueue_attrs *to,
342929c91e99STejun Heo 				 const struct workqueue_attrs *from)
343029c91e99STejun Heo {
343129c91e99STejun Heo 	to->nice = from->nice;
343229c91e99STejun Heo 	cpumask_copy(to->cpumask, from->cpumask);
34332865a8fbSShaohua Li 	/*
34342865a8fbSShaohua Li 	 * Unlike hash and equality test, this function doesn't ignore
34352865a8fbSShaohua Li 	 * ->no_numa as it is used for both pool and wq attrs.  Instead,
34362865a8fbSShaohua Li 	 * get_unbound_pool() explicitly clears ->no_numa after copying.
34372865a8fbSShaohua Li 	 */
34382865a8fbSShaohua Li 	to->no_numa = from->no_numa;
343929c91e99STejun Heo }
344029c91e99STejun Heo 
344129c91e99STejun Heo /* hash value of the content of @attr */
344229c91e99STejun Heo static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
344329c91e99STejun Heo {
344429c91e99STejun Heo 	u32 hash = 0;
344529c91e99STejun Heo 
344629c91e99STejun Heo 	hash = jhash_1word(attrs->nice, hash);
344713e2e556STejun Heo 	hash = jhash(cpumask_bits(attrs->cpumask),
344813e2e556STejun Heo 		     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
344929c91e99STejun Heo 	return hash;
345029c91e99STejun Heo }
345129c91e99STejun Heo 
345229c91e99STejun Heo /* content equality test */
345329c91e99STejun Heo static bool wqattrs_equal(const struct workqueue_attrs *a,
345429c91e99STejun Heo 			  const struct workqueue_attrs *b)
345529c91e99STejun Heo {
345629c91e99STejun Heo 	if (a->nice != b->nice)
345729c91e99STejun Heo 		return false;
345829c91e99STejun Heo 	if (!cpumask_equal(a->cpumask, b->cpumask))
345929c91e99STejun Heo 		return false;
346029c91e99STejun Heo 	return true;
346129c91e99STejun Heo }
346229c91e99STejun Heo 
34637a4e344cSTejun Heo /**
34647a4e344cSTejun Heo  * init_worker_pool - initialize a newly zalloc'd worker_pool
34657a4e344cSTejun Heo  * @pool: worker_pool to initialize
34667a4e344cSTejun Heo  *
3467402dd89dSShailendra Verma  * Initialize a newly zalloc'd @pool.  It also allocates @pool->attrs.
3468d185af30SYacine Belkadi  *
3469d185af30SYacine Belkadi  * Return: 0 on success, -errno on failure.  Even on failure, all fields
347029c91e99STejun Heo  * inside @pool proper are initialized and put_unbound_pool() can be called
347129c91e99STejun Heo  * on @pool safely to release it.
34727a4e344cSTejun Heo  */
34737a4e344cSTejun Heo static int init_worker_pool(struct worker_pool *pool)
34744e1a1f9aSTejun Heo {
3475a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_init(&pool->lock);
347629c91e99STejun Heo 	pool->id = -1;
347729c91e99STejun Heo 	pool->cpu = -1;
3478f3f90ad4STejun Heo 	pool->node = NUMA_NO_NODE;
34794e1a1f9aSTejun Heo 	pool->flags |= POOL_DISASSOCIATED;
348082607adcSTejun Heo 	pool->watchdog_ts = jiffies;
34814e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->worklist);
34824e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->idle_list);
34834e1a1f9aSTejun Heo 	hash_init(pool->busy_hash);
34844e1a1f9aSTejun Heo 
348532a6c723SKees Cook 	timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
34864e1a1f9aSTejun Heo 
348732a6c723SKees Cook 	timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
34884e1a1f9aSTejun Heo 
3489da028469SLai Jiangshan 	INIT_LIST_HEAD(&pool->workers);
34907a4e344cSTejun Heo 
34917cda9aaeSLai Jiangshan 	ida_init(&pool->worker_ida);
349229c91e99STejun Heo 	INIT_HLIST_NODE(&pool->hash_node);
349329c91e99STejun Heo 	pool->refcnt = 1;
349429c91e99STejun Heo 
349529c91e99STejun Heo 	/* shouldn't fail above this point */
3496be69d00dSThomas Gleixner 	pool->attrs = alloc_workqueue_attrs();
34977a4e344cSTejun Heo 	if (!pool->attrs)
34987a4e344cSTejun Heo 		return -ENOMEM;
34997a4e344cSTejun Heo 	return 0;
35004e1a1f9aSTejun Heo }
35014e1a1f9aSTejun Heo 
3502669de8bdSBart Van Assche #ifdef CONFIG_LOCKDEP
3503669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
3504669de8bdSBart Van Assche {
3505669de8bdSBart Van Assche 	char *lock_name;
3506669de8bdSBart Van Assche 
3507669de8bdSBart Van Assche 	lockdep_register_key(&wq->key);
3508669de8bdSBart Van Assche 	lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name);
3509669de8bdSBart Van Assche 	if (!lock_name)
3510669de8bdSBart Van Assche 		lock_name = wq->name;
351169a106c0SQian Cai 
351269a106c0SQian Cai 	wq->lock_name = lock_name;
3513669de8bdSBart Van Assche 	lockdep_init_map(&wq->lockdep_map, lock_name, &wq->key, 0);
3514669de8bdSBart Van Assche }
3515669de8bdSBart Van Assche 
3516669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
3517669de8bdSBart Van Assche {
3518669de8bdSBart Van Assche 	lockdep_unregister_key(&wq->key);
3519669de8bdSBart Van Assche }
3520669de8bdSBart Van Assche 
3521669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
3522669de8bdSBart Van Assche {
3523669de8bdSBart Van Assche 	if (wq->lock_name != wq->name)
3524669de8bdSBart Van Assche 		kfree(wq->lock_name);
3525669de8bdSBart Van Assche }
3526669de8bdSBart Van Assche #else
3527669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
3528669de8bdSBart Van Assche {
3529669de8bdSBart Van Assche }
3530669de8bdSBart Van Assche 
3531669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
3532669de8bdSBart Van Assche {
3533669de8bdSBart Van Assche }
3534669de8bdSBart Van Assche 
3535669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
3536669de8bdSBart Van Assche {
3537669de8bdSBart Van Assche }
3538669de8bdSBart Van Assche #endif
3539669de8bdSBart Van Assche 
3540e2dca7adSTejun Heo static void rcu_free_wq(struct rcu_head *rcu)
3541e2dca7adSTejun Heo {
3542e2dca7adSTejun Heo 	struct workqueue_struct *wq =
3543e2dca7adSTejun Heo 		container_of(rcu, struct workqueue_struct, rcu);
3544e2dca7adSTejun Heo 
3545669de8bdSBart Van Assche 	wq_free_lockdep(wq);
3546669de8bdSBart Van Assche 
3547e2dca7adSTejun Heo 	if (!(wq->flags & WQ_UNBOUND))
3548e2dca7adSTejun Heo 		free_percpu(wq->cpu_pwqs);
3549e2dca7adSTejun Heo 	else
3550e2dca7adSTejun Heo 		free_workqueue_attrs(wq->unbound_attrs);
3551e2dca7adSTejun Heo 
3552e2dca7adSTejun Heo 	kfree(wq);
3553e2dca7adSTejun Heo }
3554e2dca7adSTejun Heo 
355529c91e99STejun Heo static void rcu_free_pool(struct rcu_head *rcu)
355629c91e99STejun Heo {
355729c91e99STejun Heo 	struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
355829c91e99STejun Heo 
35597cda9aaeSLai Jiangshan 	ida_destroy(&pool->worker_ida);
356029c91e99STejun Heo 	free_workqueue_attrs(pool->attrs);
356129c91e99STejun Heo 	kfree(pool);
356229c91e99STejun Heo }
356329c91e99STejun Heo 
3564d8bb65abSSebastian Andrzej Siewior /* This returns with the lock held on success (pool manager is inactive). */
3565d8bb65abSSebastian Andrzej Siewior static bool wq_manager_inactive(struct worker_pool *pool)
3566d8bb65abSSebastian Andrzej Siewior {
3567a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
3568d8bb65abSSebastian Andrzej Siewior 
3569d8bb65abSSebastian Andrzej Siewior 	if (pool->flags & POOL_MANAGER_ACTIVE) {
3570a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
3571d8bb65abSSebastian Andrzej Siewior 		return false;
3572d8bb65abSSebastian Andrzej Siewior 	}
3573d8bb65abSSebastian Andrzej Siewior 	return true;
3574d8bb65abSSebastian Andrzej Siewior }
3575d8bb65abSSebastian Andrzej Siewior 
357629c91e99STejun Heo /**
357729c91e99STejun Heo  * put_unbound_pool - put a worker_pool
357829c91e99STejun Heo  * @pool: worker_pool to put
357929c91e99STejun Heo  *
358024acfb71SThomas Gleixner  * Put @pool.  If its refcnt reaches zero, it gets destroyed in RCU
3581c5aa87bbSTejun Heo  * safe manner.  get_unbound_pool() calls this function on its failure path
3582c5aa87bbSTejun Heo  * and this function should be able to release pools which went through,
3583c5aa87bbSTejun Heo  * successfully or not, init_worker_pool().
3584a892caccSTejun Heo  *
3585a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
358629c91e99STejun Heo  */
358729c91e99STejun Heo static void put_unbound_pool(struct worker_pool *pool)
358829c91e99STejun Heo {
358960f5a4bcSLai Jiangshan 	DECLARE_COMPLETION_ONSTACK(detach_completion);
359029c91e99STejun Heo 	struct worker *worker;
359129c91e99STejun Heo 
3592a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3593a892caccSTejun Heo 
3594a892caccSTejun Heo 	if (--pool->refcnt)
359529c91e99STejun Heo 		return;
359629c91e99STejun Heo 
359729c91e99STejun Heo 	/* sanity checks */
359861d0fbb4SLai Jiangshan 	if (WARN_ON(!(pool->cpu < 0)) ||
3599a892caccSTejun Heo 	    WARN_ON(!list_empty(&pool->worklist)))
360029c91e99STejun Heo 		return;
360129c91e99STejun Heo 
360229c91e99STejun Heo 	/* release id and unhash */
360329c91e99STejun Heo 	if (pool->id >= 0)
360429c91e99STejun Heo 		idr_remove(&worker_pool_idr, pool->id);
360529c91e99STejun Heo 	hash_del(&pool->hash_node);
360629c91e99STejun Heo 
3607c5aa87bbSTejun Heo 	/*
3608692b4825STejun Heo 	 * Become the manager and destroy all workers.  This prevents
3609692b4825STejun Heo 	 * @pool's workers from blocking on attach_mutex.  We're the last
3610692b4825STejun Heo 	 * manager and @pool gets freed with the flag set.
3611d8bb65abSSebastian Andrzej Siewior 	 * Because of how wq_manager_inactive() works, we will hold the
3612d8bb65abSSebastian Andrzej Siewior 	 * spinlock after a successful wait.
3613c5aa87bbSTejun Heo 	 */
3614d8bb65abSSebastian Andrzej Siewior 	rcuwait_wait_event(&manager_wait, wq_manager_inactive(pool),
3615d8bb65abSSebastian Andrzej Siewior 			   TASK_UNINTERRUPTIBLE);
3616692b4825STejun Heo 	pool->flags |= POOL_MANAGER_ACTIVE;
3617692b4825STejun Heo 
36181037de36SLai Jiangshan 	while ((worker = first_idle_worker(pool)))
361929c91e99STejun Heo 		destroy_worker(worker);
362029c91e99STejun Heo 	WARN_ON(pool->nr_workers || pool->nr_idle);
3621a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
362260f5a4bcSLai Jiangshan 
36231258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
3624da028469SLai Jiangshan 	if (!list_empty(&pool->workers))
362560f5a4bcSLai Jiangshan 		pool->detach_completion = &detach_completion;
36261258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
362760f5a4bcSLai Jiangshan 
362860f5a4bcSLai Jiangshan 	if (pool->detach_completion)
362960f5a4bcSLai Jiangshan 		wait_for_completion(pool->detach_completion);
363060f5a4bcSLai Jiangshan 
363129c91e99STejun Heo 	/* shut down the timers */
363229c91e99STejun Heo 	del_timer_sync(&pool->idle_timer);
363329c91e99STejun Heo 	del_timer_sync(&pool->mayday_timer);
363429c91e99STejun Heo 
363524acfb71SThomas Gleixner 	/* RCU protected to allow dereferences from get_work_pool() */
363625b00775SPaul E. McKenney 	call_rcu(&pool->rcu, rcu_free_pool);
363729c91e99STejun Heo }
363829c91e99STejun Heo 
363929c91e99STejun Heo /**
364029c91e99STejun Heo  * get_unbound_pool - get a worker_pool with the specified attributes
364129c91e99STejun Heo  * @attrs: the attributes of the worker_pool to get
364229c91e99STejun Heo  *
364329c91e99STejun Heo  * Obtain a worker_pool which has the same attributes as @attrs, bump the
364429c91e99STejun Heo  * reference count and return it.  If there already is a matching
364529c91e99STejun Heo  * worker_pool, it will be used; otherwise, this function attempts to
3646d185af30SYacine Belkadi  * create a new one.
3647a892caccSTejun Heo  *
3648a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
3649d185af30SYacine Belkadi  *
3650d185af30SYacine Belkadi  * Return: On success, a worker_pool with the same attributes as @attrs.
3651d185af30SYacine Belkadi  * On failure, %NULL.
365229c91e99STejun Heo  */
365329c91e99STejun Heo static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
365429c91e99STejun Heo {
365529c91e99STejun Heo 	u32 hash = wqattrs_hash(attrs);
365629c91e99STejun Heo 	struct worker_pool *pool;
3657f3f90ad4STejun Heo 	int node;
3658e2273584SXunlei Pang 	int target_node = NUMA_NO_NODE;
365929c91e99STejun Heo 
3660a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
366129c91e99STejun Heo 
366229c91e99STejun Heo 	/* do we already have a matching pool? */
366329c91e99STejun Heo 	hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
366429c91e99STejun Heo 		if (wqattrs_equal(pool->attrs, attrs)) {
366529c91e99STejun Heo 			pool->refcnt++;
36663fb1823cSLai Jiangshan 			return pool;
366729c91e99STejun Heo 		}
366829c91e99STejun Heo 	}
366929c91e99STejun Heo 
3670e2273584SXunlei Pang 	/* if cpumask is contained inside a NUMA node, we belong to that node */
3671e2273584SXunlei Pang 	if (wq_numa_enabled) {
3672e2273584SXunlei Pang 		for_each_node(node) {
3673e2273584SXunlei Pang 			if (cpumask_subset(attrs->cpumask,
3674e2273584SXunlei Pang 					   wq_numa_possible_cpumask[node])) {
3675e2273584SXunlei Pang 				target_node = node;
3676e2273584SXunlei Pang 				break;
3677e2273584SXunlei Pang 			}
3678e2273584SXunlei Pang 		}
3679e2273584SXunlei Pang 	}
3680e2273584SXunlei Pang 
368129c91e99STejun Heo 	/* nope, create a new one */
3682e2273584SXunlei Pang 	pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, target_node);
368329c91e99STejun Heo 	if (!pool || init_worker_pool(pool) < 0)
368429c91e99STejun Heo 		goto fail;
368529c91e99STejun Heo 
36868864b4e5STejun Heo 	lockdep_set_subclass(&pool->lock, 1);	/* see put_pwq() */
368729c91e99STejun Heo 	copy_workqueue_attrs(pool->attrs, attrs);
3688e2273584SXunlei Pang 	pool->node = target_node;
368929c91e99STejun Heo 
36902865a8fbSShaohua Li 	/*
36912865a8fbSShaohua Li 	 * no_numa isn't a worker_pool attribute, always clear it.  See
36922865a8fbSShaohua Li 	 * 'struct workqueue_attrs' comments for detail.
36932865a8fbSShaohua Li 	 */
36942865a8fbSShaohua Li 	pool->attrs->no_numa = false;
36952865a8fbSShaohua Li 
369629c91e99STejun Heo 	if (worker_pool_assign_id(pool) < 0)
369729c91e99STejun Heo 		goto fail;
369829c91e99STejun Heo 
369929c91e99STejun Heo 	/* create and start the initial worker */
37003347fa09STejun Heo 	if (wq_online && !create_worker(pool))
370129c91e99STejun Heo 		goto fail;
370229c91e99STejun Heo 
370329c91e99STejun Heo 	/* install */
370429c91e99STejun Heo 	hash_add(unbound_pool_hash, &pool->hash_node, hash);
37053fb1823cSLai Jiangshan 
370629c91e99STejun Heo 	return pool;
370729c91e99STejun Heo fail:
370829c91e99STejun Heo 	if (pool)
370929c91e99STejun Heo 		put_unbound_pool(pool);
371029c91e99STejun Heo 	return NULL;
371129c91e99STejun Heo }
371229c91e99STejun Heo 
37138864b4e5STejun Heo static void rcu_free_pwq(struct rcu_head *rcu)
37148864b4e5STejun Heo {
37158864b4e5STejun Heo 	kmem_cache_free(pwq_cache,
37168864b4e5STejun Heo 			container_of(rcu, struct pool_workqueue, rcu));
37178864b4e5STejun Heo }
37188864b4e5STejun Heo 
37198864b4e5STejun Heo /*
37208864b4e5STejun Heo  * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
37218864b4e5STejun Heo  * and needs to be destroyed.
37228864b4e5STejun Heo  */
37238864b4e5STejun Heo static void pwq_unbound_release_workfn(struct work_struct *work)
37248864b4e5STejun Heo {
37258864b4e5STejun Heo 	struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
37268864b4e5STejun Heo 						  unbound_release_work);
37278864b4e5STejun Heo 	struct workqueue_struct *wq = pwq->wq;
37288864b4e5STejun Heo 	struct worker_pool *pool = pwq->pool;
3729b42b0bddSYang Yingliang 	bool is_last = false;
37308864b4e5STejun Heo 
3731b42b0bddSYang Yingliang 	/*
3732b42b0bddSYang Yingliang 	 * when @pwq is not linked, it doesn't hold any reference to the
3733b42b0bddSYang Yingliang 	 * @wq, and @wq is invalid to access.
3734b42b0bddSYang Yingliang 	 */
3735b42b0bddSYang Yingliang 	if (!list_empty(&pwq->pwqs_node)) {
37368864b4e5STejun Heo 		if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
37378864b4e5STejun Heo 			return;
37388864b4e5STejun Heo 
37393c25a55dSLai Jiangshan 		mutex_lock(&wq->mutex);
37408864b4e5STejun Heo 		list_del_rcu(&pwq->pwqs_node);
3741bc0caf09STejun Heo 		is_last = list_empty(&wq->pwqs);
37423c25a55dSLai Jiangshan 		mutex_unlock(&wq->mutex);
3743b42b0bddSYang Yingliang 	}
37448864b4e5STejun Heo 
3745a892caccSTejun Heo 	mutex_lock(&wq_pool_mutex);
37468864b4e5STejun Heo 	put_unbound_pool(pool);
3747a892caccSTejun Heo 	mutex_unlock(&wq_pool_mutex);
3748a892caccSTejun Heo 
374925b00775SPaul E. McKenney 	call_rcu(&pwq->rcu, rcu_free_pwq);
37508864b4e5STejun Heo 
37518864b4e5STejun Heo 	/*
37528864b4e5STejun Heo 	 * If we're the last pwq going away, @wq is already dead and no one
3753e2dca7adSTejun Heo 	 * is gonna access it anymore.  Schedule RCU free.
37548864b4e5STejun Heo 	 */
3755669de8bdSBart Van Assche 	if (is_last) {
3756669de8bdSBart Van Assche 		wq_unregister_lockdep(wq);
375725b00775SPaul E. McKenney 		call_rcu(&wq->rcu, rcu_free_wq);
37586029a918STejun Heo 	}
3759669de8bdSBart Van Assche }
37608864b4e5STejun Heo 
37610fbd95aaSTejun Heo /**
3762699ce097STejun Heo  * pwq_adjust_max_active - update a pwq's max_active to the current setting
37630fbd95aaSTejun Heo  * @pwq: target pool_workqueue
37640fbd95aaSTejun Heo  *
3765699ce097STejun Heo  * If @pwq isn't freezing, set @pwq->max_active to the associated
3766f97a4a1aSLai Jiangshan  * workqueue's saved_max_active and activate inactive work items
3767699ce097STejun Heo  * accordingly.  If @pwq is freezing, clear @pwq->max_active to zero.
37680fbd95aaSTejun Heo  */
3769699ce097STejun Heo static void pwq_adjust_max_active(struct pool_workqueue *pwq)
37700fbd95aaSTejun Heo {
3771699ce097STejun Heo 	struct workqueue_struct *wq = pwq->wq;
3772699ce097STejun Heo 	bool freezable = wq->flags & WQ_FREEZABLE;
37733347fa09STejun Heo 	unsigned long flags;
3774699ce097STejun Heo 
3775699ce097STejun Heo 	/* for @wq->saved_max_active */
3776a357fc03SLai Jiangshan 	lockdep_assert_held(&wq->mutex);
3777699ce097STejun Heo 
3778699ce097STejun Heo 	/* fast exit for non-freezable wqs */
3779699ce097STejun Heo 	if (!freezable && pwq->max_active == wq->saved_max_active)
3780699ce097STejun Heo 		return;
3781699ce097STejun Heo 
37823347fa09STejun Heo 	/* this function can be called during early boot w/ irq disabled */
3783a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irqsave(&pwq->pool->lock, flags);
3784699ce097STejun Heo 
378574b414eaSLai Jiangshan 	/*
378674b414eaSLai Jiangshan 	 * During [un]freezing, the caller is responsible for ensuring that
378774b414eaSLai Jiangshan 	 * this function is called at least once after @workqueue_freezing
378874b414eaSLai Jiangshan 	 * is updated and visible.
378974b414eaSLai Jiangshan 	 */
379074b414eaSLai Jiangshan 	if (!freezable || !workqueue_freezing) {
379101341fbdSYunfeng Ye 		bool kick = false;
379201341fbdSYunfeng Ye 
3793699ce097STejun Heo 		pwq->max_active = wq->saved_max_active;
37940fbd95aaSTejun Heo 
3795f97a4a1aSLai Jiangshan 		while (!list_empty(&pwq->inactive_works) &&
379601341fbdSYunfeng Ye 		       pwq->nr_active < pwq->max_active) {
3797f97a4a1aSLai Jiangshan 			pwq_activate_first_inactive(pwq);
379801341fbdSYunfeng Ye 			kick = true;
379901341fbdSYunfeng Ye 		}
3800951a078aSLai Jiangshan 
3801951a078aSLai Jiangshan 		/*
3802951a078aSLai Jiangshan 		 * Need to kick a worker after thawed or an unbound wq's
380301341fbdSYunfeng Ye 		 * max_active is bumped. In realtime scenarios, always kicking a
380401341fbdSYunfeng Ye 		 * worker will cause interference on the isolated cpu cores, so
380501341fbdSYunfeng Ye 		 * let's kick iff work items were activated.
3806951a078aSLai Jiangshan 		 */
380701341fbdSYunfeng Ye 		if (kick)
3808951a078aSLai Jiangshan 			wake_up_worker(pwq->pool);
3809699ce097STejun Heo 	} else {
3810699ce097STejun Heo 		pwq->max_active = 0;
3811699ce097STejun Heo 	}
3812699ce097STejun Heo 
3813a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
38140fbd95aaSTejun Heo }
38150fbd95aaSTejun Heo 
381667dc8325SCai Huoqing /* initialize newly allocated @pwq which is associated with @wq and @pool */
3817f147f29eSTejun Heo static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
3818f147f29eSTejun Heo 		     struct worker_pool *pool)
3819d2c1d404STejun Heo {
3820d2c1d404STejun Heo 	BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3821d2c1d404STejun Heo 
3822e50aba9aSTejun Heo 	memset(pwq, 0, sizeof(*pwq));
3823e50aba9aSTejun Heo 
3824d2c1d404STejun Heo 	pwq->pool = pool;
3825d2c1d404STejun Heo 	pwq->wq = wq;
3826d2c1d404STejun Heo 	pwq->flush_color = -1;
38278864b4e5STejun Heo 	pwq->refcnt = 1;
3828f97a4a1aSLai Jiangshan 	INIT_LIST_HEAD(&pwq->inactive_works);
38291befcf30STejun Heo 	INIT_LIST_HEAD(&pwq->pwqs_node);
3830d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->mayday_node);
38318864b4e5STejun Heo 	INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
3832f147f29eSTejun Heo }
3833d2c1d404STejun Heo 
3834f147f29eSTejun Heo /* sync @pwq with the current state of its associated wq and link it */
38351befcf30STejun Heo static void link_pwq(struct pool_workqueue *pwq)
3836f147f29eSTejun Heo {
3837f147f29eSTejun Heo 	struct workqueue_struct *wq = pwq->wq;
3838f147f29eSTejun Heo 
3839f147f29eSTejun Heo 	lockdep_assert_held(&wq->mutex);
384075ccf595STejun Heo 
38411befcf30STejun Heo 	/* may be called multiple times, ignore if already linked */
38421befcf30STejun Heo 	if (!list_empty(&pwq->pwqs_node))
38431befcf30STejun Heo 		return;
38441befcf30STejun Heo 
384529b1cb41SLai Jiangshan 	/* set the matching work_color */
384675ccf595STejun Heo 	pwq->work_color = wq->work_color;
3847983ca25eSTejun Heo 
3848983ca25eSTejun Heo 	/* sync max_active to the current setting */
3849983ca25eSTejun Heo 	pwq_adjust_max_active(pwq);
3850983ca25eSTejun Heo 
3851983ca25eSTejun Heo 	/* link in @pwq */
38529e8cd2f5STejun Heo 	list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
3853df2d5ae4STejun Heo }
38546029a918STejun Heo 
3855f147f29eSTejun Heo /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
3856f147f29eSTejun Heo static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
3857f147f29eSTejun Heo 					const struct workqueue_attrs *attrs)
3858f147f29eSTejun Heo {
3859f147f29eSTejun Heo 	struct worker_pool *pool;
3860f147f29eSTejun Heo 	struct pool_workqueue *pwq;
3861f147f29eSTejun Heo 
3862f147f29eSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3863f147f29eSTejun Heo 
3864f147f29eSTejun Heo 	pool = get_unbound_pool(attrs);
3865f147f29eSTejun Heo 	if (!pool)
3866f147f29eSTejun Heo 		return NULL;
3867f147f29eSTejun Heo 
3868e50aba9aSTejun Heo 	pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
3869f147f29eSTejun Heo 	if (!pwq) {
3870f147f29eSTejun Heo 		put_unbound_pool(pool);
3871f147f29eSTejun Heo 		return NULL;
3872f147f29eSTejun Heo 	}
3873f147f29eSTejun Heo 
3874f147f29eSTejun Heo 	init_pwq(pwq, wq, pool);
3875f147f29eSTejun Heo 	return pwq;
3876d2c1d404STejun Heo }
3877d2c1d404STejun Heo 
38784c16bd32STejun Heo /**
387930186c6fSGong Zhaogang  * wq_calc_node_cpumask - calculate a wq_attrs' cpumask for the specified node
3880042f7df1SLai Jiangshan  * @attrs: the wq_attrs of the default pwq of the target workqueue
38814c16bd32STejun Heo  * @node: the target NUMA node
38824c16bd32STejun Heo  * @cpu_going_down: if >= 0, the CPU to consider as offline
38834c16bd32STejun Heo  * @cpumask: outarg, the resulting cpumask
38844c16bd32STejun Heo  *
38854c16bd32STejun Heo  * Calculate the cpumask a workqueue with @attrs should use on @node.  If
38864c16bd32STejun Heo  * @cpu_going_down is >= 0, that cpu is considered offline during
3887d185af30SYacine Belkadi  * calculation.  The result is stored in @cpumask.
38884c16bd32STejun Heo  *
38894c16bd32STejun Heo  * If NUMA affinity is not enabled, @attrs->cpumask is always used.  If
38904c16bd32STejun Heo  * enabled and @node has online CPUs requested by @attrs, the returned
38914c16bd32STejun Heo  * cpumask is the intersection of the possible CPUs of @node and
38924c16bd32STejun Heo  * @attrs->cpumask.
38934c16bd32STejun Heo  *
38944c16bd32STejun Heo  * The caller is responsible for ensuring that the cpumask of @node stays
38954c16bd32STejun Heo  * stable.
3896d185af30SYacine Belkadi  *
3897d185af30SYacine Belkadi  * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
3898d185af30SYacine Belkadi  * %false if equal.
38994c16bd32STejun Heo  */
39004c16bd32STejun Heo static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
39014c16bd32STejun Heo 				 int cpu_going_down, cpumask_t *cpumask)
39024c16bd32STejun Heo {
3903d55262c4STejun Heo 	if (!wq_numa_enabled || attrs->no_numa)
39044c16bd32STejun Heo 		goto use_dfl;
39054c16bd32STejun Heo 
39064c16bd32STejun Heo 	/* does @node have any online CPUs @attrs wants? */
39074c16bd32STejun Heo 	cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
39084c16bd32STejun Heo 	if (cpu_going_down >= 0)
39094c16bd32STejun Heo 		cpumask_clear_cpu(cpu_going_down, cpumask);
39104c16bd32STejun Heo 
39114c16bd32STejun Heo 	if (cpumask_empty(cpumask))
39124c16bd32STejun Heo 		goto use_dfl;
39134c16bd32STejun Heo 
39144c16bd32STejun Heo 	/* yeap, return possible CPUs in @node that @attrs wants */
39154c16bd32STejun Heo 	cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
39161ad0f0a7SMichael Bringmann 
39171ad0f0a7SMichael Bringmann 	if (cpumask_empty(cpumask)) {
39181ad0f0a7SMichael Bringmann 		pr_warn_once("WARNING: workqueue cpumask: online intersect > "
39191ad0f0a7SMichael Bringmann 				"possible intersect\n");
39201ad0f0a7SMichael Bringmann 		return false;
39211ad0f0a7SMichael Bringmann 	}
39221ad0f0a7SMichael Bringmann 
39234c16bd32STejun Heo 	return !cpumask_equal(cpumask, attrs->cpumask);
39244c16bd32STejun Heo 
39254c16bd32STejun Heo use_dfl:
39264c16bd32STejun Heo 	cpumask_copy(cpumask, attrs->cpumask);
39274c16bd32STejun Heo 	return false;
39284c16bd32STejun Heo }
39294c16bd32STejun Heo 
39301befcf30STejun Heo /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
39311befcf30STejun Heo static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
39321befcf30STejun Heo 						   int node,
39331befcf30STejun Heo 						   struct pool_workqueue *pwq)
39341befcf30STejun Heo {
39351befcf30STejun Heo 	struct pool_workqueue *old_pwq;
39361befcf30STejun Heo 
39375b95e1afSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
39381befcf30STejun Heo 	lockdep_assert_held(&wq->mutex);
39391befcf30STejun Heo 
39401befcf30STejun Heo 	/* link_pwq() can handle duplicate calls */
39411befcf30STejun Heo 	link_pwq(pwq);
39421befcf30STejun Heo 
39431befcf30STejun Heo 	old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
39441befcf30STejun Heo 	rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
39451befcf30STejun Heo 	return old_pwq;
39461befcf30STejun Heo }
39471befcf30STejun Heo 
39482d5f0764SLai Jiangshan /* context to store the prepared attrs & pwqs before applying */
39492d5f0764SLai Jiangshan struct apply_wqattrs_ctx {
39502d5f0764SLai Jiangshan 	struct workqueue_struct	*wq;		/* target workqueue */
39512d5f0764SLai Jiangshan 	struct workqueue_attrs	*attrs;		/* attrs to apply */
3952042f7df1SLai Jiangshan 	struct list_head	list;		/* queued for batching commit */
39532d5f0764SLai Jiangshan 	struct pool_workqueue	*dfl_pwq;
39542d5f0764SLai Jiangshan 	struct pool_workqueue	*pwq_tbl[];
39552d5f0764SLai Jiangshan };
39562d5f0764SLai Jiangshan 
39572d5f0764SLai Jiangshan /* free the resources after success or abort */
39582d5f0764SLai Jiangshan static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
39592d5f0764SLai Jiangshan {
39602d5f0764SLai Jiangshan 	if (ctx) {
39612d5f0764SLai Jiangshan 		int node;
39622d5f0764SLai Jiangshan 
39632d5f0764SLai Jiangshan 		for_each_node(node)
39642d5f0764SLai Jiangshan 			put_pwq_unlocked(ctx->pwq_tbl[node]);
39652d5f0764SLai Jiangshan 		put_pwq_unlocked(ctx->dfl_pwq);
39662d5f0764SLai Jiangshan 
39672d5f0764SLai Jiangshan 		free_workqueue_attrs(ctx->attrs);
39682d5f0764SLai Jiangshan 
39692d5f0764SLai Jiangshan 		kfree(ctx);
39702d5f0764SLai Jiangshan 	}
39712d5f0764SLai Jiangshan }
39722d5f0764SLai Jiangshan 
39732d5f0764SLai Jiangshan /* allocate the attrs and pwqs for later installation */
39742d5f0764SLai Jiangshan static struct apply_wqattrs_ctx *
39752d5f0764SLai Jiangshan apply_wqattrs_prepare(struct workqueue_struct *wq,
397699c621efSLai Jiangshan 		      const struct workqueue_attrs *attrs,
397799c621efSLai Jiangshan 		      const cpumask_var_t unbound_cpumask)
39782d5f0764SLai Jiangshan {
39792d5f0764SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
39802d5f0764SLai Jiangshan 	struct workqueue_attrs *new_attrs, *tmp_attrs;
39812d5f0764SLai Jiangshan 	int node;
39822d5f0764SLai Jiangshan 
39832d5f0764SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
39842d5f0764SLai Jiangshan 
3985acafe7e3SKees Cook 	ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_node_ids), GFP_KERNEL);
39862d5f0764SLai Jiangshan 
3987be69d00dSThomas Gleixner 	new_attrs = alloc_workqueue_attrs();
3988be69d00dSThomas Gleixner 	tmp_attrs = alloc_workqueue_attrs();
39892d5f0764SLai Jiangshan 	if (!ctx || !new_attrs || !tmp_attrs)
39902d5f0764SLai Jiangshan 		goto out_free;
39912d5f0764SLai Jiangshan 
3992042f7df1SLai Jiangshan 	/*
399399c621efSLai Jiangshan 	 * Calculate the attrs of the default pwq with unbound_cpumask
399499c621efSLai Jiangshan 	 * which is wq_unbound_cpumask or to set to wq_unbound_cpumask.
3995042f7df1SLai Jiangshan 	 * If the user configured cpumask doesn't overlap with the
3996042f7df1SLai Jiangshan 	 * wq_unbound_cpumask, we fallback to the wq_unbound_cpumask.
3997042f7df1SLai Jiangshan 	 */
39982d5f0764SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
399999c621efSLai Jiangshan 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, unbound_cpumask);
4000042f7df1SLai Jiangshan 	if (unlikely(cpumask_empty(new_attrs->cpumask)))
400199c621efSLai Jiangshan 		cpumask_copy(new_attrs->cpumask, unbound_cpumask);
40022d5f0764SLai Jiangshan 
40032d5f0764SLai Jiangshan 	/*
40042d5f0764SLai Jiangshan 	 * We may create multiple pwqs with differing cpumasks.  Make a
40052d5f0764SLai Jiangshan 	 * copy of @new_attrs which will be modified and used to obtain
40062d5f0764SLai Jiangshan 	 * pools.
40072d5f0764SLai Jiangshan 	 */
40082d5f0764SLai Jiangshan 	copy_workqueue_attrs(tmp_attrs, new_attrs);
40092d5f0764SLai Jiangshan 
40102d5f0764SLai Jiangshan 	/*
40112d5f0764SLai Jiangshan 	 * If something goes wrong during CPU up/down, we'll fall back to
40122d5f0764SLai Jiangshan 	 * the default pwq covering whole @attrs->cpumask.  Always create
40132d5f0764SLai Jiangshan 	 * it even if we don't use it immediately.
40142d5f0764SLai Jiangshan 	 */
40152d5f0764SLai Jiangshan 	ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
40162d5f0764SLai Jiangshan 	if (!ctx->dfl_pwq)
40172d5f0764SLai Jiangshan 		goto out_free;
40182d5f0764SLai Jiangshan 
40192d5f0764SLai Jiangshan 	for_each_node(node) {
4020042f7df1SLai Jiangshan 		if (wq_calc_node_cpumask(new_attrs, node, -1, tmp_attrs->cpumask)) {
40212d5f0764SLai Jiangshan 			ctx->pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
40222d5f0764SLai Jiangshan 			if (!ctx->pwq_tbl[node])
40232d5f0764SLai Jiangshan 				goto out_free;
40242d5f0764SLai Jiangshan 		} else {
40252d5f0764SLai Jiangshan 			ctx->dfl_pwq->refcnt++;
40262d5f0764SLai Jiangshan 			ctx->pwq_tbl[node] = ctx->dfl_pwq;
40272d5f0764SLai Jiangshan 		}
40282d5f0764SLai Jiangshan 	}
40292d5f0764SLai Jiangshan 
4030042f7df1SLai Jiangshan 	/* save the user configured attrs and sanitize it. */
4031042f7df1SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
4032042f7df1SLai Jiangshan 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
40332d5f0764SLai Jiangshan 	ctx->attrs = new_attrs;
4034042f7df1SLai Jiangshan 
40352d5f0764SLai Jiangshan 	ctx->wq = wq;
40362d5f0764SLai Jiangshan 	free_workqueue_attrs(tmp_attrs);
40372d5f0764SLai Jiangshan 	return ctx;
40382d5f0764SLai Jiangshan 
40392d5f0764SLai Jiangshan out_free:
40402d5f0764SLai Jiangshan 	free_workqueue_attrs(tmp_attrs);
40412d5f0764SLai Jiangshan 	free_workqueue_attrs(new_attrs);
40422d5f0764SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
40432d5f0764SLai Jiangshan 	return NULL;
40442d5f0764SLai Jiangshan }
40452d5f0764SLai Jiangshan 
40462d5f0764SLai Jiangshan /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
40472d5f0764SLai Jiangshan static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
40482d5f0764SLai Jiangshan {
40492d5f0764SLai Jiangshan 	int node;
40502d5f0764SLai Jiangshan 
40512d5f0764SLai Jiangshan 	/* all pwqs have been created successfully, let's install'em */
40522d5f0764SLai Jiangshan 	mutex_lock(&ctx->wq->mutex);
40532d5f0764SLai Jiangshan 
40542d5f0764SLai Jiangshan 	copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
40552d5f0764SLai Jiangshan 
40562d5f0764SLai Jiangshan 	/* save the previous pwq and install the new one */
40572d5f0764SLai Jiangshan 	for_each_node(node)
40582d5f0764SLai Jiangshan 		ctx->pwq_tbl[node] = numa_pwq_tbl_install(ctx->wq, node,
40592d5f0764SLai Jiangshan 							  ctx->pwq_tbl[node]);
40602d5f0764SLai Jiangshan 
40612d5f0764SLai Jiangshan 	/* @dfl_pwq might not have been used, ensure it's linked */
40622d5f0764SLai Jiangshan 	link_pwq(ctx->dfl_pwq);
40632d5f0764SLai Jiangshan 	swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
40642d5f0764SLai Jiangshan 
40652d5f0764SLai Jiangshan 	mutex_unlock(&ctx->wq->mutex);
40662d5f0764SLai Jiangshan }
40672d5f0764SLai Jiangshan 
4068a0111cf6SLai Jiangshan static void apply_wqattrs_lock(void)
4069a0111cf6SLai Jiangshan {
4070a0111cf6SLai Jiangshan 	/* CPUs should stay stable across pwq creations and installations */
4071ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
4072a0111cf6SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4073a0111cf6SLai Jiangshan }
4074a0111cf6SLai Jiangshan 
4075a0111cf6SLai Jiangshan static void apply_wqattrs_unlock(void)
4076a0111cf6SLai Jiangshan {
4077a0111cf6SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
4078ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
4079a0111cf6SLai Jiangshan }
4080a0111cf6SLai Jiangshan 
4081a0111cf6SLai Jiangshan static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
4082a0111cf6SLai Jiangshan 					const struct workqueue_attrs *attrs)
4083a0111cf6SLai Jiangshan {
4084a0111cf6SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
4085a0111cf6SLai Jiangshan 
4086a0111cf6SLai Jiangshan 	/* only unbound workqueues can change attributes */
4087a0111cf6SLai Jiangshan 	if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
4088a0111cf6SLai Jiangshan 		return -EINVAL;
4089a0111cf6SLai Jiangshan 
4090a0111cf6SLai Jiangshan 	/* creating multiple pwqs breaks ordering guarantee */
40910a94efb5STejun Heo 	if (!list_empty(&wq->pwqs)) {
40920a94efb5STejun Heo 		if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
4093a0111cf6SLai Jiangshan 			return -EINVAL;
4094a0111cf6SLai Jiangshan 
40950a94efb5STejun Heo 		wq->flags &= ~__WQ_ORDERED;
40960a94efb5STejun Heo 	}
40970a94efb5STejun Heo 
409899c621efSLai Jiangshan 	ctx = apply_wqattrs_prepare(wq, attrs, wq_unbound_cpumask);
40996201171eSwanghaibin 	if (!ctx)
41006201171eSwanghaibin 		return -ENOMEM;
4101a0111cf6SLai Jiangshan 
4102a0111cf6SLai Jiangshan 	/* the ctx has been prepared successfully, let's commit it */
4103a0111cf6SLai Jiangshan 	apply_wqattrs_commit(ctx);
4104a0111cf6SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
4105a0111cf6SLai Jiangshan 
41066201171eSwanghaibin 	return 0;
4107a0111cf6SLai Jiangshan }
4108a0111cf6SLai Jiangshan 
41099e8cd2f5STejun Heo /**
41109e8cd2f5STejun Heo  * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
41119e8cd2f5STejun Heo  * @wq: the target workqueue
41129e8cd2f5STejun Heo  * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
41139e8cd2f5STejun Heo  *
41144c16bd32STejun Heo  * Apply @attrs to an unbound workqueue @wq.  Unless disabled, on NUMA
41154c16bd32STejun Heo  * machines, this function maps a separate pwq to each NUMA node with
41164c16bd32STejun Heo  * possibles CPUs in @attrs->cpumask so that work items are affine to the
41174c16bd32STejun Heo  * NUMA node it was issued on.  Older pwqs are released as in-flight work
41184c16bd32STejun Heo  * items finish.  Note that a work item which repeatedly requeues itself
41194c16bd32STejun Heo  * back-to-back will stay on its current pwq.
41209e8cd2f5STejun Heo  *
4121d185af30SYacine Belkadi  * Performs GFP_KERNEL allocations.
4122d185af30SYacine Belkadi  *
4123ffd8bea8SSebastian Andrzej Siewior  * Assumes caller has CPU hotplug read exclusion, i.e. cpus_read_lock().
4124509b3204SDaniel Jordan  *
4125d185af30SYacine Belkadi  * Return: 0 on success and -errno on failure.
41269e8cd2f5STejun Heo  */
4127513c98d0SDaniel Jordan int apply_workqueue_attrs(struct workqueue_struct *wq,
41289e8cd2f5STejun Heo 			  const struct workqueue_attrs *attrs)
41299e8cd2f5STejun Heo {
4130a0111cf6SLai Jiangshan 	int ret;
41319e8cd2f5STejun Heo 
4132509b3204SDaniel Jordan 	lockdep_assert_cpus_held();
4133509b3204SDaniel Jordan 
4134509b3204SDaniel Jordan 	mutex_lock(&wq_pool_mutex);
4135a0111cf6SLai Jiangshan 	ret = apply_workqueue_attrs_locked(wq, attrs);
4136509b3204SDaniel Jordan 	mutex_unlock(&wq_pool_mutex);
41372d5f0764SLai Jiangshan 
41382d5f0764SLai Jiangshan 	return ret;
41399e8cd2f5STejun Heo }
41409e8cd2f5STejun Heo 
41414c16bd32STejun Heo /**
41424c16bd32STejun Heo  * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
41434c16bd32STejun Heo  * @wq: the target workqueue
41444c16bd32STejun Heo  * @cpu: the CPU coming up or going down
41454c16bd32STejun Heo  * @online: whether @cpu is coming up or going down
41464c16bd32STejun Heo  *
41474c16bd32STejun Heo  * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
41484c16bd32STejun Heo  * %CPU_DOWN_FAILED.  @cpu is being hot[un]plugged, update NUMA affinity of
41494c16bd32STejun Heo  * @wq accordingly.
41504c16bd32STejun Heo  *
41514c16bd32STejun Heo  * If NUMA affinity can't be adjusted due to memory allocation failure, it
41524c16bd32STejun Heo  * falls back to @wq->dfl_pwq which may not be optimal but is always
41534c16bd32STejun Heo  * correct.
41544c16bd32STejun Heo  *
41554c16bd32STejun Heo  * Note that when the last allowed CPU of a NUMA node goes offline for a
41564c16bd32STejun Heo  * workqueue with a cpumask spanning multiple nodes, the workers which were
41574c16bd32STejun Heo  * already executing the work items for the workqueue will lose their CPU
41584c16bd32STejun Heo  * affinity and may execute on any CPU.  This is similar to how per-cpu
41594c16bd32STejun Heo  * workqueues behave on CPU_DOWN.  If a workqueue user wants strict
41604c16bd32STejun Heo  * affinity, it's the user's responsibility to flush the work item from
41614c16bd32STejun Heo  * CPU_DOWN_PREPARE.
41624c16bd32STejun Heo  */
41634c16bd32STejun Heo static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
41644c16bd32STejun Heo 				   bool online)
41654c16bd32STejun Heo {
41664c16bd32STejun Heo 	int node = cpu_to_node(cpu);
41674c16bd32STejun Heo 	int cpu_off = online ? -1 : cpu;
41684c16bd32STejun Heo 	struct pool_workqueue *old_pwq = NULL, *pwq;
41694c16bd32STejun Heo 	struct workqueue_attrs *target_attrs;
41704c16bd32STejun Heo 	cpumask_t *cpumask;
41714c16bd32STejun Heo 
41724c16bd32STejun Heo 	lockdep_assert_held(&wq_pool_mutex);
41734c16bd32STejun Heo 
4174f7142ed4SLai Jiangshan 	if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND) ||
4175f7142ed4SLai Jiangshan 	    wq->unbound_attrs->no_numa)
41764c16bd32STejun Heo 		return;
41774c16bd32STejun Heo 
41784c16bd32STejun Heo 	/*
41794c16bd32STejun Heo 	 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
41804c16bd32STejun Heo 	 * Let's use a preallocated one.  The following buf is protected by
41814c16bd32STejun Heo 	 * CPU hotplug exclusion.
41824c16bd32STejun Heo 	 */
41834c16bd32STejun Heo 	target_attrs = wq_update_unbound_numa_attrs_buf;
41844c16bd32STejun Heo 	cpumask = target_attrs->cpumask;
41854c16bd32STejun Heo 
41864c16bd32STejun Heo 	copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
41874c16bd32STejun Heo 	pwq = unbound_pwq_by_node(wq, node);
41884c16bd32STejun Heo 
41894c16bd32STejun Heo 	/*
41904c16bd32STejun Heo 	 * Let's determine what needs to be done.  If the target cpumask is
4191042f7df1SLai Jiangshan 	 * different from the default pwq's, we need to compare it to @pwq's
4192042f7df1SLai Jiangshan 	 * and create a new one if they don't match.  If the target cpumask
4193042f7df1SLai Jiangshan 	 * equals the default pwq's, the default pwq should be used.
41944c16bd32STejun Heo 	 */
4195042f7df1SLai Jiangshan 	if (wq_calc_node_cpumask(wq->dfl_pwq->pool->attrs, node, cpu_off, cpumask)) {
41964c16bd32STejun Heo 		if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
4197f7142ed4SLai Jiangshan 			return;
41984c16bd32STejun Heo 	} else {
41994c16bd32STejun Heo 		goto use_dfl_pwq;
42004c16bd32STejun Heo 	}
42014c16bd32STejun Heo 
42024c16bd32STejun Heo 	/* create a new pwq */
42034c16bd32STejun Heo 	pwq = alloc_unbound_pwq(wq, target_attrs);
42044c16bd32STejun Heo 	if (!pwq) {
42052d916033SFabian Frederick 		pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
42064c16bd32STejun Heo 			wq->name);
420777f300b1SDaeseok Youn 		goto use_dfl_pwq;
42084c16bd32STejun Heo 	}
42094c16bd32STejun Heo 
4210f7142ed4SLai Jiangshan 	/* Install the new pwq. */
42114c16bd32STejun Heo 	mutex_lock(&wq->mutex);
42124c16bd32STejun Heo 	old_pwq = numa_pwq_tbl_install(wq, node, pwq);
42134c16bd32STejun Heo 	goto out_unlock;
42144c16bd32STejun Heo 
42154c16bd32STejun Heo use_dfl_pwq:
4216f7142ed4SLai Jiangshan 	mutex_lock(&wq->mutex);
4217a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&wq->dfl_pwq->pool->lock);
42184c16bd32STejun Heo 	get_pwq(wq->dfl_pwq);
4219a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&wq->dfl_pwq->pool->lock);
42204c16bd32STejun Heo 	old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
42214c16bd32STejun Heo out_unlock:
42224c16bd32STejun Heo 	mutex_unlock(&wq->mutex);
42234c16bd32STejun Heo 	put_pwq_unlocked(old_pwq);
42244c16bd32STejun Heo }
42254c16bd32STejun Heo 
422630cdf249STejun Heo static int alloc_and_link_pwqs(struct workqueue_struct *wq)
42271da177e4SLinus Torvalds {
422849e3cf44STejun Heo 	bool highpri = wq->flags & WQ_HIGHPRI;
42298a2b7538STejun Heo 	int cpu, ret;
4230e1d8aa9fSFrederic Weisbecker 
423130cdf249STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
4232420c0ddbSTejun Heo 		wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
4233420c0ddbSTejun Heo 		if (!wq->cpu_pwqs)
423430cdf249STejun Heo 			return -ENOMEM;
423530cdf249STejun Heo 
423630cdf249STejun Heo 		for_each_possible_cpu(cpu) {
42377fb98ea7STejun Heo 			struct pool_workqueue *pwq =
42387fb98ea7STejun Heo 				per_cpu_ptr(wq->cpu_pwqs, cpu);
42397a62c2c8STejun Heo 			struct worker_pool *cpu_pools =
4240f02ae73aSTejun Heo 				per_cpu(cpu_worker_pools, cpu);
424130cdf249STejun Heo 
4242f147f29eSTejun Heo 			init_pwq(pwq, wq, &cpu_pools[highpri]);
4243f147f29eSTejun Heo 
4244f147f29eSTejun Heo 			mutex_lock(&wq->mutex);
42451befcf30STejun Heo 			link_pwq(pwq);
4246f147f29eSTejun Heo 			mutex_unlock(&wq->mutex);
424730cdf249STejun Heo 		}
424830cdf249STejun Heo 		return 0;
4249509b3204SDaniel Jordan 	}
4250509b3204SDaniel Jordan 
4251ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
4252509b3204SDaniel Jordan 	if (wq->flags & __WQ_ORDERED) {
42538a2b7538STejun Heo 		ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
42548a2b7538STejun Heo 		/* there should only be single pwq for ordering guarantee */
42558a2b7538STejun Heo 		WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
42568a2b7538STejun Heo 			      wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
42578a2b7538STejun Heo 		     "ordering guarantee broken for workqueue %s\n", wq->name);
42589e8cd2f5STejun Heo 	} else {
4259509b3204SDaniel Jordan 		ret = apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
42609e8cd2f5STejun Heo 	}
4261ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
4262509b3204SDaniel Jordan 
4263509b3204SDaniel Jordan 	return ret;
42640f900049STejun Heo }
42650f900049STejun Heo 
4266f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
4267f3421797STejun Heo 			       const char *name)
4268b71ab8c2STejun Heo {
4269f3421797STejun Heo 	int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
4270f3421797STejun Heo 
4271f3421797STejun Heo 	if (max_active < 1 || max_active > lim)
4272044c782cSValentin Ilie 		pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
4273f3421797STejun Heo 			max_active, name, 1, lim);
4274b71ab8c2STejun Heo 
4275f3421797STejun Heo 	return clamp_val(max_active, 1, lim);
4276b71ab8c2STejun Heo }
4277b71ab8c2STejun Heo 
4278983c7515STejun Heo /*
4279983c7515STejun Heo  * Workqueues which may be used during memory reclaim should have a rescuer
4280983c7515STejun Heo  * to guarantee forward progress.
4281983c7515STejun Heo  */
4282983c7515STejun Heo static int init_rescuer(struct workqueue_struct *wq)
4283983c7515STejun Heo {
4284983c7515STejun Heo 	struct worker *rescuer;
4285b92b36eaSDan Carpenter 	int ret;
4286983c7515STejun Heo 
4287983c7515STejun Heo 	if (!(wq->flags & WQ_MEM_RECLAIM))
4288983c7515STejun Heo 		return 0;
4289983c7515STejun Heo 
4290983c7515STejun Heo 	rescuer = alloc_worker(NUMA_NO_NODE);
4291983c7515STejun Heo 	if (!rescuer)
4292983c7515STejun Heo 		return -ENOMEM;
4293983c7515STejun Heo 
4294983c7515STejun Heo 	rescuer->rescue_wq = wq;
4295983c7515STejun Heo 	rescuer->task = kthread_create(rescuer_thread, rescuer, "%s", wq->name);
4296f187b697SSean Fu 	if (IS_ERR(rescuer->task)) {
4297b92b36eaSDan Carpenter 		ret = PTR_ERR(rescuer->task);
4298983c7515STejun Heo 		kfree(rescuer);
4299b92b36eaSDan Carpenter 		return ret;
4300983c7515STejun Heo 	}
4301983c7515STejun Heo 
4302983c7515STejun Heo 	wq->rescuer = rescuer;
4303983c7515STejun Heo 	kthread_bind_mask(rescuer->task, cpu_possible_mask);
4304983c7515STejun Heo 	wake_up_process(rescuer->task);
4305983c7515STejun Heo 
4306983c7515STejun Heo 	return 0;
4307983c7515STejun Heo }
4308983c7515STejun Heo 
4309a2775bbcSMathieu Malaterre __printf(1, 4)
4310669de8bdSBart Van Assche struct workqueue_struct *alloc_workqueue(const char *fmt,
431197e37d7bSTejun Heo 					 unsigned int flags,
4312669de8bdSBart Van Assche 					 int max_active, ...)
43133af24433SOleg Nesterov {
4314df2d5ae4STejun Heo 	size_t tbl_size = 0;
4315ecf6881fSTejun Heo 	va_list args;
43163af24433SOleg Nesterov 	struct workqueue_struct *wq;
431749e3cf44STejun Heo 	struct pool_workqueue *pwq;
4318b196be89STejun Heo 
43195c0338c6STejun Heo 	/*
43205c0338c6STejun Heo 	 * Unbound && max_active == 1 used to imply ordered, which is no
43215c0338c6STejun Heo 	 * longer the case on NUMA machines due to per-node pools.  While
43225c0338c6STejun Heo 	 * alloc_ordered_workqueue() is the right way to create an ordered
43235c0338c6STejun Heo 	 * workqueue, keep the previous behavior to avoid subtle breakages
43245c0338c6STejun Heo 	 * on NUMA.
43255c0338c6STejun Heo 	 */
43265c0338c6STejun Heo 	if ((flags & WQ_UNBOUND) && max_active == 1)
43275c0338c6STejun Heo 		flags |= __WQ_ORDERED;
43285c0338c6STejun Heo 
4329cee22a15SViresh Kumar 	/* see the comment above the definition of WQ_POWER_EFFICIENT */
4330cee22a15SViresh Kumar 	if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
4331cee22a15SViresh Kumar 		flags |= WQ_UNBOUND;
4332cee22a15SViresh Kumar 
4333ecf6881fSTejun Heo 	/* allocate wq and format name */
4334df2d5ae4STejun Heo 	if (flags & WQ_UNBOUND)
4335ddcb57e2SLai Jiangshan 		tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
4336df2d5ae4STejun Heo 
4337df2d5ae4STejun Heo 	wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
4338b196be89STejun Heo 	if (!wq)
4339d2c1d404STejun Heo 		return NULL;
4340b196be89STejun Heo 
43416029a918STejun Heo 	if (flags & WQ_UNBOUND) {
4342be69d00dSThomas Gleixner 		wq->unbound_attrs = alloc_workqueue_attrs();
43436029a918STejun Heo 		if (!wq->unbound_attrs)
43446029a918STejun Heo 			goto err_free_wq;
43456029a918STejun Heo 	}
43466029a918STejun Heo 
4347669de8bdSBart Van Assche 	va_start(args, max_active);
4348ecf6881fSTejun Heo 	vsnprintf(wq->name, sizeof(wq->name), fmt, args);
4349b196be89STejun Heo 	va_end(args);
43503af24433SOleg Nesterov 
4351d320c038STejun Heo 	max_active = max_active ?: WQ_DFL_ACTIVE;
4352b196be89STejun Heo 	max_active = wq_clamp_max_active(max_active, flags, wq->name);
43533af24433SOleg Nesterov 
4354b196be89STejun Heo 	/* init wq */
435597e37d7bSTejun Heo 	wq->flags = flags;
4356a0a1a5fdSTejun Heo 	wq->saved_max_active = max_active;
43573c25a55dSLai Jiangshan 	mutex_init(&wq->mutex);
4358112202d9STejun Heo 	atomic_set(&wq->nr_pwqs_to_flush, 0);
435930cdf249STejun Heo 	INIT_LIST_HEAD(&wq->pwqs);
436073f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
436173f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
4362493a1724STejun Heo 	INIT_LIST_HEAD(&wq->maydays);
43633af24433SOleg Nesterov 
4364669de8bdSBart Van Assche 	wq_init_lockdep(wq);
4365cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
43663af24433SOleg Nesterov 
436730cdf249STejun Heo 	if (alloc_and_link_pwqs(wq) < 0)
436882efcab3SBart Van Assche 		goto err_unreg_lockdep;
43691537663fSTejun Heo 
437040c17f75STejun Heo 	if (wq_online && init_rescuer(wq) < 0)
4371d2c1d404STejun Heo 		goto err_destroy;
4372e22bee78STejun Heo 
4373226223abSTejun Heo 	if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
4374226223abSTejun Heo 		goto err_destroy;
4375226223abSTejun Heo 
43766af8bf3dSOleg Nesterov 	/*
437768e13a67SLai Jiangshan 	 * wq_pool_mutex protects global freeze state and workqueues list.
437868e13a67SLai Jiangshan 	 * Grab it, adjust max_active and add the new @wq to workqueues
437968e13a67SLai Jiangshan 	 * list.
43806af8bf3dSOleg Nesterov 	 */
438168e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4382a0a1a5fdSTejun Heo 
4383a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
438449e3cf44STejun Heo 	for_each_pwq(pwq, wq)
4385699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4386a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4387a0a1a5fdSTejun Heo 
4388e2dca7adSTejun Heo 	list_add_tail_rcu(&wq->list, &workqueues);
4389a0a1a5fdSTejun Heo 
439068e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
43913af24433SOleg Nesterov 
43923af24433SOleg Nesterov 	return wq;
4393d2c1d404STejun Heo 
439482efcab3SBart Van Assche err_unreg_lockdep:
4395009bb421SBart Van Assche 	wq_unregister_lockdep(wq);
4396009bb421SBart Van Assche 	wq_free_lockdep(wq);
439782efcab3SBart Van Assche err_free_wq:
43986029a918STejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
43994690c4abSTejun Heo 	kfree(wq);
4400d2c1d404STejun Heo 	return NULL;
4401d2c1d404STejun Heo err_destroy:
4402d2c1d404STejun Heo 	destroy_workqueue(wq);
44034690c4abSTejun Heo 	return NULL;
44041da177e4SLinus Torvalds }
4405669de8bdSBart Van Assche EXPORT_SYMBOL_GPL(alloc_workqueue);
44061da177e4SLinus Torvalds 
4407c29eb853STejun Heo static bool pwq_busy(struct pool_workqueue *pwq)
4408c29eb853STejun Heo {
4409c29eb853STejun Heo 	int i;
4410c29eb853STejun Heo 
4411c29eb853STejun Heo 	for (i = 0; i < WORK_NR_COLORS; i++)
4412c29eb853STejun Heo 		if (pwq->nr_in_flight[i])
4413c29eb853STejun Heo 			return true;
4414c29eb853STejun Heo 
4415c29eb853STejun Heo 	if ((pwq != pwq->wq->dfl_pwq) && (pwq->refcnt > 1))
4416c29eb853STejun Heo 		return true;
4417f97a4a1aSLai Jiangshan 	if (pwq->nr_active || !list_empty(&pwq->inactive_works))
4418c29eb853STejun Heo 		return true;
4419c29eb853STejun Heo 
4420c29eb853STejun Heo 	return false;
4421c29eb853STejun Heo }
4422c29eb853STejun Heo 
44233af24433SOleg Nesterov /**
44243af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
44253af24433SOleg Nesterov  * @wq: target workqueue
44263af24433SOleg Nesterov  *
44273af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
44283af24433SOleg Nesterov  */
44293af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
44303af24433SOleg Nesterov {
443149e3cf44STejun Heo 	struct pool_workqueue *pwq;
44324c16bd32STejun Heo 	int node;
44333af24433SOleg Nesterov 
4434def98c84STejun Heo 	/*
4435def98c84STejun Heo 	 * Remove it from sysfs first so that sanity check failure doesn't
4436def98c84STejun Heo 	 * lead to sysfs name conflicts.
4437def98c84STejun Heo 	 */
4438def98c84STejun Heo 	workqueue_sysfs_unregister(wq);
4439def98c84STejun Heo 
444033e3f0a3SRichard Clark 	/* mark the workqueue destruction is in progress */
444133e3f0a3SRichard Clark 	mutex_lock(&wq->mutex);
444233e3f0a3SRichard Clark 	wq->flags |= __WQ_DESTROYING;
444333e3f0a3SRichard Clark 	mutex_unlock(&wq->mutex);
444433e3f0a3SRichard Clark 
44459c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
44469c5a2ba7STejun Heo 	drain_workqueue(wq);
4447c8efcc25STejun Heo 
4448def98c84STejun Heo 	/* kill rescuer, if sanity checks fail, leave it w/o rescuer */
4449def98c84STejun Heo 	if (wq->rescuer) {
4450def98c84STejun Heo 		struct worker *rescuer = wq->rescuer;
4451def98c84STejun Heo 
4452def98c84STejun Heo 		/* this prevents new queueing */
4453a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&wq_mayday_lock);
4454def98c84STejun Heo 		wq->rescuer = NULL;
4455a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&wq_mayday_lock);
4456def98c84STejun Heo 
4457def98c84STejun Heo 		/* rescuer will empty maydays list before exiting */
4458def98c84STejun Heo 		kthread_stop(rescuer->task);
44598efe1223STejun Heo 		kfree(rescuer);
4460def98c84STejun Heo 	}
4461def98c84STejun Heo 
4462c29eb853STejun Heo 	/*
4463c29eb853STejun Heo 	 * Sanity checks - grab all the locks so that we wait for all
4464c29eb853STejun Heo 	 * in-flight operations which may do put_pwq().
4465c29eb853STejun Heo 	 */
4466c29eb853STejun Heo 	mutex_lock(&wq_pool_mutex);
4467b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
446849e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
4469a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
4470c29eb853STejun Heo 		if (WARN_ON(pwq_busy(pwq))) {
44711d9a6159SKefeng Wang 			pr_warn("%s: %s has the following busy pwq\n",
4472e66b39afSTejun Heo 				__func__, wq->name);
4473c29eb853STejun Heo 			show_pwq(pwq);
4474a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&pwq->pool->lock);
4475b09f4fd3SLai Jiangshan 			mutex_unlock(&wq->mutex);
4476c29eb853STejun Heo 			mutex_unlock(&wq_pool_mutex);
447755df0933SImran Khan 			show_one_workqueue(wq);
44786183c009STejun Heo 			return;
447976af4d93STejun Heo 		}
4480a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
448176af4d93STejun Heo 	}
4482b09f4fd3SLai Jiangshan 	mutex_unlock(&wq->mutex);
44836183c009STejun Heo 
4484a0a1a5fdSTejun Heo 	/*
4485a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
4486a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
4487a0a1a5fdSTejun Heo 	 */
4488e2dca7adSTejun Heo 	list_del_rcu(&wq->list);
448968e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
44903af24433SOleg Nesterov 
44918864b4e5STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
4492669de8bdSBart Van Assche 		wq_unregister_lockdep(wq);
449329c91e99STejun Heo 		/*
44948864b4e5STejun Heo 		 * The base ref is never dropped on per-cpu pwqs.  Directly
4495e2dca7adSTejun Heo 		 * schedule RCU free.
449629c91e99STejun Heo 		 */
449725b00775SPaul E. McKenney 		call_rcu(&wq->rcu, rcu_free_wq);
44988864b4e5STejun Heo 	} else {
44998864b4e5STejun Heo 		/*
45008864b4e5STejun Heo 		 * We're the sole accessor of @wq at this point.  Directly
45014c16bd32STejun Heo 		 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
45024c16bd32STejun Heo 		 * @wq will be freed when the last pwq is released.
45038864b4e5STejun Heo 		 */
45044c16bd32STejun Heo 		for_each_node(node) {
45054c16bd32STejun Heo 			pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
45064c16bd32STejun Heo 			RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
45074c16bd32STejun Heo 			put_pwq_unlocked(pwq);
45084c16bd32STejun Heo 		}
45094c16bd32STejun Heo 
45104c16bd32STejun Heo 		/*
45114c16bd32STejun Heo 		 * Put dfl_pwq.  @wq may be freed any time after dfl_pwq is
45124c16bd32STejun Heo 		 * put.  Don't access it afterwards.
45134c16bd32STejun Heo 		 */
45144c16bd32STejun Heo 		pwq = wq->dfl_pwq;
45154c16bd32STejun Heo 		wq->dfl_pwq = NULL;
4516dce90d47STejun Heo 		put_pwq_unlocked(pwq);
451729c91e99STejun Heo 	}
45183af24433SOleg Nesterov }
45193af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
45203af24433SOleg Nesterov 
4521dcd989cbSTejun Heo /**
4522dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
4523dcd989cbSTejun Heo  * @wq: target workqueue
4524dcd989cbSTejun Heo  * @max_active: new max_active value.
4525dcd989cbSTejun Heo  *
4526dcd989cbSTejun Heo  * Set max_active of @wq to @max_active.
4527dcd989cbSTejun Heo  *
4528dcd989cbSTejun Heo  * CONTEXT:
4529dcd989cbSTejun Heo  * Don't call from IRQ context.
4530dcd989cbSTejun Heo  */
4531dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4532dcd989cbSTejun Heo {
453349e3cf44STejun Heo 	struct pool_workqueue *pwq;
4534dcd989cbSTejun Heo 
45358719dceaSTejun Heo 	/* disallow meddling with max_active for ordered workqueues */
45360a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
45378719dceaSTejun Heo 		return;
45388719dceaSTejun Heo 
4539f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4540dcd989cbSTejun Heo 
4541a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
4542dcd989cbSTejun Heo 
45430a94efb5STejun Heo 	wq->flags &= ~__WQ_ORDERED;
4544dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
4545dcd989cbSTejun Heo 
4546699ce097STejun Heo 	for_each_pwq(pwq, wq)
4547699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4548dcd989cbSTejun Heo 
4549a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4550dcd989cbSTejun Heo }
4551dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4552dcd989cbSTejun Heo 
4553dcd989cbSTejun Heo /**
455427d4ee03SLukas Wunner  * current_work - retrieve %current task's work struct
455527d4ee03SLukas Wunner  *
455627d4ee03SLukas Wunner  * Determine if %current task is a workqueue worker and what it's working on.
455727d4ee03SLukas Wunner  * Useful to find out the context that the %current task is running in.
455827d4ee03SLukas Wunner  *
455927d4ee03SLukas Wunner  * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
456027d4ee03SLukas Wunner  */
456127d4ee03SLukas Wunner struct work_struct *current_work(void)
456227d4ee03SLukas Wunner {
456327d4ee03SLukas Wunner 	struct worker *worker = current_wq_worker();
456427d4ee03SLukas Wunner 
456527d4ee03SLukas Wunner 	return worker ? worker->current_work : NULL;
456627d4ee03SLukas Wunner }
456727d4ee03SLukas Wunner EXPORT_SYMBOL(current_work);
456827d4ee03SLukas Wunner 
456927d4ee03SLukas Wunner /**
4570e6267616STejun Heo  * current_is_workqueue_rescuer - is %current workqueue rescuer?
4571e6267616STejun Heo  *
4572e6267616STejun Heo  * Determine whether %current is a workqueue rescuer.  Can be used from
4573e6267616STejun Heo  * work functions to determine whether it's being run off the rescuer task.
4574d185af30SYacine Belkadi  *
4575d185af30SYacine Belkadi  * Return: %true if %current is a workqueue rescuer. %false otherwise.
4576e6267616STejun Heo  */
4577e6267616STejun Heo bool current_is_workqueue_rescuer(void)
4578e6267616STejun Heo {
4579e6267616STejun Heo 	struct worker *worker = current_wq_worker();
4580e6267616STejun Heo 
45816a092dfdSLai Jiangshan 	return worker && worker->rescue_wq;
4582e6267616STejun Heo }
4583e6267616STejun Heo 
4584e6267616STejun Heo /**
4585dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
4586dcd989cbSTejun Heo  * @cpu: CPU in question
4587dcd989cbSTejun Heo  * @wq: target workqueue
4588dcd989cbSTejun Heo  *
4589dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
4590dcd989cbSTejun Heo  * no synchronization around this function and the test result is
4591dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4592dcd989cbSTejun Heo  *
4593d3251859STejun Heo  * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4594d3251859STejun Heo  * Note that both per-cpu and unbound workqueues may be associated with
4595d3251859STejun Heo  * multiple pool_workqueues which have separate congested states.  A
4596d3251859STejun Heo  * workqueue being congested on one CPU doesn't mean the workqueue is also
4597d3251859STejun Heo  * contested on other CPUs / NUMA nodes.
4598d3251859STejun Heo  *
4599d185af30SYacine Belkadi  * Return:
4600dcd989cbSTejun Heo  * %true if congested, %false otherwise.
4601dcd989cbSTejun Heo  */
4602d84ff051STejun Heo bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4603dcd989cbSTejun Heo {
46047fb98ea7STejun Heo 	struct pool_workqueue *pwq;
460576af4d93STejun Heo 	bool ret;
460676af4d93STejun Heo 
460724acfb71SThomas Gleixner 	rcu_read_lock();
460824acfb71SThomas Gleixner 	preempt_disable();
46097fb98ea7STejun Heo 
4610d3251859STejun Heo 	if (cpu == WORK_CPU_UNBOUND)
4611d3251859STejun Heo 		cpu = smp_processor_id();
4612d3251859STejun Heo 
46137fb98ea7STejun Heo 	if (!(wq->flags & WQ_UNBOUND))
46147fb98ea7STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
46157fb98ea7STejun Heo 	else
4616df2d5ae4STejun Heo 		pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4617dcd989cbSTejun Heo 
4618f97a4a1aSLai Jiangshan 	ret = !list_empty(&pwq->inactive_works);
461924acfb71SThomas Gleixner 	preempt_enable();
462024acfb71SThomas Gleixner 	rcu_read_unlock();
462176af4d93STejun Heo 
462276af4d93STejun Heo 	return ret;
4623dcd989cbSTejun Heo }
4624dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
4625dcd989cbSTejun Heo 
4626dcd989cbSTejun Heo /**
4627dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
4628dcd989cbSTejun Heo  * @work: the work to be tested
4629dcd989cbSTejun Heo  *
4630dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
4631dcd989cbSTejun Heo  * synchronization around this function and the test result is
4632dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4633dcd989cbSTejun Heo  *
4634d185af30SYacine Belkadi  * Return:
4635dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
4636dcd989cbSTejun Heo  */
4637dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
4638dcd989cbSTejun Heo {
4639fa1b54e6STejun Heo 	struct worker_pool *pool;
4640dcd989cbSTejun Heo 	unsigned long flags;
4641dcd989cbSTejun Heo 	unsigned int ret = 0;
4642dcd989cbSTejun Heo 
4643dcd989cbSTejun Heo 	if (work_pending(work))
4644dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
4645038366c5SLai Jiangshan 
464624acfb71SThomas Gleixner 	rcu_read_lock();
4647fa1b54e6STejun Heo 	pool = get_work_pool(work);
4648038366c5SLai Jiangshan 	if (pool) {
4649a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irqsave(&pool->lock, flags);
4650c9e7cf27STejun Heo 		if (find_worker_executing_work(pool, work))
4651dcd989cbSTejun Heo 			ret |= WORK_BUSY_RUNNING;
4652a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&pool->lock, flags);
4653038366c5SLai Jiangshan 	}
465424acfb71SThomas Gleixner 	rcu_read_unlock();
4655dcd989cbSTejun Heo 
4656dcd989cbSTejun Heo 	return ret;
4657dcd989cbSTejun Heo }
4658dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
4659dcd989cbSTejun Heo 
46603d1cb205STejun Heo /**
46613d1cb205STejun Heo  * set_worker_desc - set description for the current work item
46623d1cb205STejun Heo  * @fmt: printf-style format string
46633d1cb205STejun Heo  * @...: arguments for the format string
46643d1cb205STejun Heo  *
46653d1cb205STejun Heo  * This function can be called by a running work function to describe what
46663d1cb205STejun Heo  * the work item is about.  If the worker task gets dumped, this
46673d1cb205STejun Heo  * information will be printed out together to help debugging.  The
46683d1cb205STejun Heo  * description can be at most WORKER_DESC_LEN including the trailing '\0'.
46693d1cb205STejun Heo  */
46703d1cb205STejun Heo void set_worker_desc(const char *fmt, ...)
46713d1cb205STejun Heo {
46723d1cb205STejun Heo 	struct worker *worker = current_wq_worker();
46733d1cb205STejun Heo 	va_list args;
46743d1cb205STejun Heo 
46753d1cb205STejun Heo 	if (worker) {
46763d1cb205STejun Heo 		va_start(args, fmt);
46773d1cb205STejun Heo 		vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
46783d1cb205STejun Heo 		va_end(args);
46793d1cb205STejun Heo 	}
46803d1cb205STejun Heo }
46815c750d58SSteffen Maier EXPORT_SYMBOL_GPL(set_worker_desc);
46823d1cb205STejun Heo 
46833d1cb205STejun Heo /**
46843d1cb205STejun Heo  * print_worker_info - print out worker information and description
46853d1cb205STejun Heo  * @log_lvl: the log level to use when printing
46863d1cb205STejun Heo  * @task: target task
46873d1cb205STejun Heo  *
46883d1cb205STejun Heo  * If @task is a worker and currently executing a work item, print out the
46893d1cb205STejun Heo  * name of the workqueue being serviced and worker description set with
46903d1cb205STejun Heo  * set_worker_desc() by the currently executing work item.
46913d1cb205STejun Heo  *
46923d1cb205STejun Heo  * This function can be safely called on any task as long as the
46933d1cb205STejun Heo  * task_struct itself is accessible.  While safe, this function isn't
46943d1cb205STejun Heo  * synchronized and may print out mixups or garbages of limited length.
46953d1cb205STejun Heo  */
46963d1cb205STejun Heo void print_worker_info(const char *log_lvl, struct task_struct *task)
46973d1cb205STejun Heo {
46983d1cb205STejun Heo 	work_func_t *fn = NULL;
46993d1cb205STejun Heo 	char name[WQ_NAME_LEN] = { };
47003d1cb205STejun Heo 	char desc[WORKER_DESC_LEN] = { };
47013d1cb205STejun Heo 	struct pool_workqueue *pwq = NULL;
47023d1cb205STejun Heo 	struct workqueue_struct *wq = NULL;
47033d1cb205STejun Heo 	struct worker *worker;
47043d1cb205STejun Heo 
47053d1cb205STejun Heo 	if (!(task->flags & PF_WQ_WORKER))
47063d1cb205STejun Heo 		return;
47073d1cb205STejun Heo 
47083d1cb205STejun Heo 	/*
47093d1cb205STejun Heo 	 * This function is called without any synchronization and @task
47103d1cb205STejun Heo 	 * could be in any state.  Be careful with dereferences.
47113d1cb205STejun Heo 	 */
4712e700591aSPetr Mladek 	worker = kthread_probe_data(task);
47133d1cb205STejun Heo 
47143d1cb205STejun Heo 	/*
47158bf89593STejun Heo 	 * Carefully copy the associated workqueue's workfn, name and desc.
47168bf89593STejun Heo 	 * Keep the original last '\0' in case the original is garbage.
47173d1cb205STejun Heo 	 */
4718fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&fn, &worker->current_func, sizeof(fn));
4719fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&pwq, &worker->current_pwq, sizeof(pwq));
4720fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&wq, &pwq->wq, sizeof(wq));
4721fe557319SChristoph Hellwig 	copy_from_kernel_nofault(name, wq->name, sizeof(name) - 1);
4722fe557319SChristoph Hellwig 	copy_from_kernel_nofault(desc, worker->desc, sizeof(desc) - 1);
47233d1cb205STejun Heo 
47243d1cb205STejun Heo 	if (fn || name[0] || desc[0]) {
4725d75f773cSSakari Ailus 		printk("%sWorkqueue: %s %ps", log_lvl, name, fn);
47268bf89593STejun Heo 		if (strcmp(name, desc))
47273d1cb205STejun Heo 			pr_cont(" (%s)", desc);
47283d1cb205STejun Heo 		pr_cont("\n");
47293d1cb205STejun Heo 	}
47303d1cb205STejun Heo }
47313d1cb205STejun Heo 
47323494fc30STejun Heo static void pr_cont_pool_info(struct worker_pool *pool)
47333494fc30STejun Heo {
47343494fc30STejun Heo 	pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
47353494fc30STejun Heo 	if (pool->node != NUMA_NO_NODE)
47363494fc30STejun Heo 		pr_cont(" node=%d", pool->node);
47373494fc30STejun Heo 	pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
47383494fc30STejun Heo }
47393494fc30STejun Heo 
4740c76feb0dSPaul E. McKenney struct pr_cont_work_struct {
4741c76feb0dSPaul E. McKenney 	bool comma;
4742c76feb0dSPaul E. McKenney 	work_func_t func;
4743c76feb0dSPaul E. McKenney 	long ctr;
4744c76feb0dSPaul E. McKenney };
4745c76feb0dSPaul E. McKenney 
4746c76feb0dSPaul E. McKenney static void pr_cont_work_flush(bool comma, work_func_t func, struct pr_cont_work_struct *pcwsp)
4747c76feb0dSPaul E. McKenney {
4748c76feb0dSPaul E. McKenney 	if (!pcwsp->ctr)
4749c76feb0dSPaul E. McKenney 		goto out_record;
4750c76feb0dSPaul E. McKenney 	if (func == pcwsp->func) {
4751c76feb0dSPaul E. McKenney 		pcwsp->ctr++;
4752c76feb0dSPaul E. McKenney 		return;
4753c76feb0dSPaul E. McKenney 	}
4754c76feb0dSPaul E. McKenney 	if (pcwsp->ctr == 1)
4755c76feb0dSPaul E. McKenney 		pr_cont("%s %ps", pcwsp->comma ? "," : "", pcwsp->func);
4756c76feb0dSPaul E. McKenney 	else
4757c76feb0dSPaul E. McKenney 		pr_cont("%s %ld*%ps", pcwsp->comma ? "," : "", pcwsp->ctr, pcwsp->func);
4758c76feb0dSPaul E. McKenney 	pcwsp->ctr = 0;
4759c76feb0dSPaul E. McKenney out_record:
4760c76feb0dSPaul E. McKenney 	if ((long)func == -1L)
4761c76feb0dSPaul E. McKenney 		return;
4762c76feb0dSPaul E. McKenney 	pcwsp->comma = comma;
4763c76feb0dSPaul E. McKenney 	pcwsp->func = func;
4764c76feb0dSPaul E. McKenney 	pcwsp->ctr = 1;
4765c76feb0dSPaul E. McKenney }
4766c76feb0dSPaul E. McKenney 
4767c76feb0dSPaul E. McKenney static void pr_cont_work(bool comma, struct work_struct *work, struct pr_cont_work_struct *pcwsp)
47683494fc30STejun Heo {
47693494fc30STejun Heo 	if (work->func == wq_barrier_func) {
47703494fc30STejun Heo 		struct wq_barrier *barr;
47713494fc30STejun Heo 
47723494fc30STejun Heo 		barr = container_of(work, struct wq_barrier, work);
47733494fc30STejun Heo 
4774c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
47753494fc30STejun Heo 		pr_cont("%s BAR(%d)", comma ? "," : "",
47763494fc30STejun Heo 			task_pid_nr(barr->task));
47773494fc30STejun Heo 	} else {
4778c76feb0dSPaul E. McKenney 		if (!comma)
4779c76feb0dSPaul E. McKenney 			pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
4780c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, work->func, pcwsp);
47813494fc30STejun Heo 	}
47823494fc30STejun Heo }
47833494fc30STejun Heo 
47843494fc30STejun Heo static void show_pwq(struct pool_workqueue *pwq)
47853494fc30STejun Heo {
4786c76feb0dSPaul E. McKenney 	struct pr_cont_work_struct pcws = { .ctr = 0, };
47873494fc30STejun Heo 	struct worker_pool *pool = pwq->pool;
47883494fc30STejun Heo 	struct work_struct *work;
47893494fc30STejun Heo 	struct worker *worker;
47903494fc30STejun Heo 	bool has_in_flight = false, has_pending = false;
47913494fc30STejun Heo 	int bkt;
47923494fc30STejun Heo 
47933494fc30STejun Heo 	pr_info("  pwq %d:", pool->id);
47943494fc30STejun Heo 	pr_cont_pool_info(pool);
47953494fc30STejun Heo 
4796e66b39afSTejun Heo 	pr_cont(" active=%d/%d refcnt=%d%s\n",
4797e66b39afSTejun Heo 		pwq->nr_active, pwq->max_active, pwq->refcnt,
47983494fc30STejun Heo 		!list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
47993494fc30STejun Heo 
48003494fc30STejun Heo 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
48013494fc30STejun Heo 		if (worker->current_pwq == pwq) {
48023494fc30STejun Heo 			has_in_flight = true;
48033494fc30STejun Heo 			break;
48043494fc30STejun Heo 		}
48053494fc30STejun Heo 	}
48063494fc30STejun Heo 	if (has_in_flight) {
48073494fc30STejun Heo 		bool comma = false;
48083494fc30STejun Heo 
48093494fc30STejun Heo 		pr_info("    in-flight:");
48103494fc30STejun Heo 		hash_for_each(pool->busy_hash, bkt, worker, hentry) {
48113494fc30STejun Heo 			if (worker->current_pwq != pwq)
48123494fc30STejun Heo 				continue;
48133494fc30STejun Heo 
4814d75f773cSSakari Ailus 			pr_cont("%s %d%s:%ps", comma ? "," : "",
48153494fc30STejun Heo 				task_pid_nr(worker->task),
481630ae2fc0STejun Heo 				worker->rescue_wq ? "(RESCUER)" : "",
48173494fc30STejun Heo 				worker->current_func);
48183494fc30STejun Heo 			list_for_each_entry(work, &worker->scheduled, entry)
4819c76feb0dSPaul E. McKenney 				pr_cont_work(false, work, &pcws);
4820c76feb0dSPaul E. McKenney 			pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
48213494fc30STejun Heo 			comma = true;
48223494fc30STejun Heo 		}
48233494fc30STejun Heo 		pr_cont("\n");
48243494fc30STejun Heo 	}
48253494fc30STejun Heo 
48263494fc30STejun Heo 	list_for_each_entry(work, &pool->worklist, entry) {
48273494fc30STejun Heo 		if (get_work_pwq(work) == pwq) {
48283494fc30STejun Heo 			has_pending = true;
48293494fc30STejun Heo 			break;
48303494fc30STejun Heo 		}
48313494fc30STejun Heo 	}
48323494fc30STejun Heo 	if (has_pending) {
48333494fc30STejun Heo 		bool comma = false;
48343494fc30STejun Heo 
48353494fc30STejun Heo 		pr_info("    pending:");
48363494fc30STejun Heo 		list_for_each_entry(work, &pool->worklist, entry) {
48373494fc30STejun Heo 			if (get_work_pwq(work) != pwq)
48383494fc30STejun Heo 				continue;
48393494fc30STejun Heo 
4840c76feb0dSPaul E. McKenney 			pr_cont_work(comma, work, &pcws);
48413494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
48423494fc30STejun Heo 		}
4843c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
48443494fc30STejun Heo 		pr_cont("\n");
48453494fc30STejun Heo 	}
48463494fc30STejun Heo 
4847f97a4a1aSLai Jiangshan 	if (!list_empty(&pwq->inactive_works)) {
48483494fc30STejun Heo 		bool comma = false;
48493494fc30STejun Heo 
4850f97a4a1aSLai Jiangshan 		pr_info("    inactive:");
4851f97a4a1aSLai Jiangshan 		list_for_each_entry(work, &pwq->inactive_works, entry) {
4852c76feb0dSPaul E. McKenney 			pr_cont_work(comma, work, &pcws);
48533494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
48543494fc30STejun Heo 		}
4855c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
48563494fc30STejun Heo 		pr_cont("\n");
48573494fc30STejun Heo 	}
48583494fc30STejun Heo }
48593494fc30STejun Heo 
48603494fc30STejun Heo /**
486155df0933SImran Khan  * show_one_workqueue - dump state of specified workqueue
486255df0933SImran Khan  * @wq: workqueue whose state will be printed
48633494fc30STejun Heo  */
486455df0933SImran Khan void show_one_workqueue(struct workqueue_struct *wq)
48653494fc30STejun Heo {
48663494fc30STejun Heo 	struct pool_workqueue *pwq;
48673494fc30STejun Heo 	bool idle = true;
486855df0933SImran Khan 	unsigned long flags;
48693494fc30STejun Heo 
48703494fc30STejun Heo 	for_each_pwq(pwq, wq) {
4871f97a4a1aSLai Jiangshan 		if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
48723494fc30STejun Heo 			idle = false;
48733494fc30STejun Heo 			break;
48743494fc30STejun Heo 		}
48753494fc30STejun Heo 	}
487655df0933SImran Khan 	if (idle) /* Nothing to print for idle workqueue */
487755df0933SImran Khan 		return;
48783494fc30STejun Heo 
48793494fc30STejun Heo 	pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
48803494fc30STejun Heo 
48813494fc30STejun Heo 	for_each_pwq(pwq, wq) {
4882a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irqsave(&pwq->pool->lock, flags);
488357116ce1SJohan Hovold 		if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
488457116ce1SJohan Hovold 			/*
488557116ce1SJohan Hovold 			 * Defer printing to avoid deadlocks in console
488657116ce1SJohan Hovold 			 * drivers that queue work while holding locks
488757116ce1SJohan Hovold 			 * also taken in their write paths.
488857116ce1SJohan Hovold 			 */
488957116ce1SJohan Hovold 			printk_deferred_enter();
48903494fc30STejun Heo 			show_pwq(pwq);
489157116ce1SJohan Hovold 			printk_deferred_exit();
489257116ce1SJohan Hovold 		}
4893a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
489462635ea8SSergey Senozhatsky 		/*
489562635ea8SSergey Senozhatsky 		 * We could be printing a lot from atomic context, e.g.
489655df0933SImran Khan 		 * sysrq-t -> show_all_workqueues(). Avoid triggering
489762635ea8SSergey Senozhatsky 		 * hard lockup.
489862635ea8SSergey Senozhatsky 		 */
489962635ea8SSergey Senozhatsky 		touch_nmi_watchdog();
49003494fc30STejun Heo 	}
490155df0933SImran Khan 
49023494fc30STejun Heo }
49033494fc30STejun Heo 
490455df0933SImran Khan /**
490555df0933SImran Khan  * show_one_worker_pool - dump state of specified worker pool
490655df0933SImran Khan  * @pool: worker pool whose state will be printed
490755df0933SImran Khan  */
490855df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool)
490955df0933SImran Khan {
49103494fc30STejun Heo 	struct worker *worker;
49113494fc30STejun Heo 	bool first = true;
491255df0933SImran Khan 	unsigned long flags;
49133494fc30STejun Heo 
4914a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irqsave(&pool->lock, flags);
49153494fc30STejun Heo 	if (pool->nr_workers == pool->nr_idle)
49163494fc30STejun Heo 		goto next_pool;
491757116ce1SJohan Hovold 	/*
491857116ce1SJohan Hovold 	 * Defer printing to avoid deadlocks in console drivers that
491957116ce1SJohan Hovold 	 * queue work while holding locks also taken in their write
492057116ce1SJohan Hovold 	 * paths.
492157116ce1SJohan Hovold 	 */
492257116ce1SJohan Hovold 	printk_deferred_enter();
49233494fc30STejun Heo 	pr_info("pool %d:", pool->id);
49243494fc30STejun Heo 	pr_cont_pool_info(pool);
492582607adcSTejun Heo 	pr_cont(" hung=%us workers=%d",
492682607adcSTejun Heo 		jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000,
492782607adcSTejun Heo 		pool->nr_workers);
49283494fc30STejun Heo 	if (pool->manager)
49293494fc30STejun Heo 		pr_cont(" manager: %d",
49303494fc30STejun Heo 			task_pid_nr(pool->manager->task));
49313494fc30STejun Heo 	list_for_each_entry(worker, &pool->idle_list, entry) {
49323494fc30STejun Heo 		pr_cont(" %s%d", first ? "idle: " : "",
49333494fc30STejun Heo 			task_pid_nr(worker->task));
49343494fc30STejun Heo 		first = false;
49353494fc30STejun Heo 	}
49363494fc30STejun Heo 	pr_cont("\n");
493757116ce1SJohan Hovold 	printk_deferred_exit();
49383494fc30STejun Heo next_pool:
4939a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&pool->lock, flags);
494062635ea8SSergey Senozhatsky 	/*
494162635ea8SSergey Senozhatsky 	 * We could be printing a lot from atomic context, e.g.
494255df0933SImran Khan 	 * sysrq-t -> show_all_workqueues(). Avoid triggering
494362635ea8SSergey Senozhatsky 	 * hard lockup.
494462635ea8SSergey Senozhatsky 	 */
494562635ea8SSergey Senozhatsky 	touch_nmi_watchdog();
494655df0933SImran Khan 
49473494fc30STejun Heo }
49483494fc30STejun Heo 
494955df0933SImran Khan /**
495055df0933SImran Khan  * show_all_workqueues - dump workqueue state
495155df0933SImran Khan  *
495255df0933SImran Khan  * Called from a sysrq handler or try_to_freeze_tasks() and prints out
495355df0933SImran Khan  * all busy workqueues and pools.
495455df0933SImran Khan  */
495555df0933SImran Khan void show_all_workqueues(void)
495655df0933SImran Khan {
495755df0933SImran Khan 	struct workqueue_struct *wq;
495855df0933SImran Khan 	struct worker_pool *pool;
495955df0933SImran Khan 	int pi;
496055df0933SImran Khan 
496155df0933SImran Khan 	rcu_read_lock();
496255df0933SImran Khan 
496355df0933SImran Khan 	pr_info("Showing busy workqueues and worker pools:\n");
496455df0933SImran Khan 
496555df0933SImran Khan 	list_for_each_entry_rcu(wq, &workqueues, list)
496655df0933SImran Khan 		show_one_workqueue(wq);
496755df0933SImran Khan 
496855df0933SImran Khan 	for_each_pool(pool, pi)
496955df0933SImran Khan 		show_one_worker_pool(pool);
497055df0933SImran Khan 
497124acfb71SThomas Gleixner 	rcu_read_unlock();
49723494fc30STejun Heo }
49733494fc30STejun Heo 
49746b59808bSTejun Heo /* used to show worker information through /proc/PID/{comm,stat,status} */
49756b59808bSTejun Heo void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
49766b59808bSTejun Heo {
49776b59808bSTejun Heo 	int off;
49786b59808bSTejun Heo 
49796b59808bSTejun Heo 	/* always show the actual comm */
49806b59808bSTejun Heo 	off = strscpy(buf, task->comm, size);
49816b59808bSTejun Heo 	if (off < 0)
49826b59808bSTejun Heo 		return;
49836b59808bSTejun Heo 
4984197f6accSTejun Heo 	/* stabilize PF_WQ_WORKER and worker pool association */
49856b59808bSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
49866b59808bSTejun Heo 
4987197f6accSTejun Heo 	if (task->flags & PF_WQ_WORKER) {
4988197f6accSTejun Heo 		struct worker *worker = kthread_data(task);
4989197f6accSTejun Heo 		struct worker_pool *pool = worker->pool;
49906b59808bSTejun Heo 
49916b59808bSTejun Heo 		if (pool) {
4992a9b8a985SSebastian Andrzej Siewior 			raw_spin_lock_irq(&pool->lock);
49936b59808bSTejun Heo 			/*
4994197f6accSTejun Heo 			 * ->desc tracks information (wq name or
4995197f6accSTejun Heo 			 * set_worker_desc()) for the latest execution.  If
4996197f6accSTejun Heo 			 * current, prepend '+', otherwise '-'.
49976b59808bSTejun Heo 			 */
49986b59808bSTejun Heo 			if (worker->desc[0] != '\0') {
49996b59808bSTejun Heo 				if (worker->current_work)
50006b59808bSTejun Heo 					scnprintf(buf + off, size - off, "+%s",
50016b59808bSTejun Heo 						  worker->desc);
50026b59808bSTejun Heo 				else
50036b59808bSTejun Heo 					scnprintf(buf + off, size - off, "-%s",
50046b59808bSTejun Heo 						  worker->desc);
50056b59808bSTejun Heo 			}
5006a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&pool->lock);
50076b59808bSTejun Heo 		}
5008197f6accSTejun Heo 	}
50096b59808bSTejun Heo 
50106b59808bSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
50116b59808bSTejun Heo }
50126b59808bSTejun Heo 
501366448bc2SMathieu Malaterre #ifdef CONFIG_SMP
501466448bc2SMathieu Malaterre 
5015db7bccf4STejun Heo /*
5016db7bccf4STejun Heo  * CPU hotplug.
5017db7bccf4STejun Heo  *
5018e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
5019112202d9STejun Heo  * are a lot of assumptions on strong associations among work, pwq and
5020706026c2STejun Heo  * pool which make migrating pending and scheduled works very
5021e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
502294cf58bbSTejun Heo  * worker pools serve mix of short, long and very long running works making
5023e22bee78STejun Heo  * blocked draining impractical.
5024e22bee78STejun Heo  *
502524647570STejun Heo  * This is solved by allowing the pools to be disassociated from the CPU
5026628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
5027628c78e7STejun Heo  * cpu comes back online.
5028db7bccf4STejun Heo  */
5029db7bccf4STejun Heo 
5030e8b3f8dbSLai Jiangshan static void unbind_workers(int cpu)
5031db7bccf4STejun Heo {
50324ce62e9eSTejun Heo 	struct worker_pool *pool;
5033db7bccf4STejun Heo 	struct worker *worker;
5034db7bccf4STejun Heo 
5035f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
50361258fae7STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
5037a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
5038e22bee78STejun Heo 
5039f2d5a0eeSTejun Heo 		/*
504092f9c5c4SLai Jiangshan 		 * We've blocked all attach/detach operations. Make all workers
504194cf58bbSTejun Heo 		 * unbound and set DISASSOCIATED.  Before this, all workers
504211b45b0bSLai Jiangshan 		 * must be on the cpu.  After this, they may become diasporas.
5043b4ac9384SLai Jiangshan 		 * And the preemption disabled section in their sched callbacks
5044b4ac9384SLai Jiangshan 		 * are guaranteed to see WORKER_UNBOUND since the code here
5045b4ac9384SLai Jiangshan 		 * is on the same cpu.
5046f2d5a0eeSTejun Heo 		 */
5047da028469SLai Jiangshan 		for_each_pool_worker(worker, pool)
5048403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
5049db7bccf4STejun Heo 
505024647570STejun Heo 		pool->flags |= POOL_DISASSOCIATED;
5051f2d5a0eeSTejun Heo 
5052e22bee78STejun Heo 		/*
5053989442d7SLai Jiangshan 		 * The handling of nr_running in sched callbacks are disabled
5054989442d7SLai Jiangshan 		 * now.  Zap nr_running.  After this, nr_running stays zero and
5055989442d7SLai Jiangshan 		 * need_more_worker() and keep_working() are always true as
5056989442d7SLai Jiangshan 		 * long as the worklist is not empty.  This pool now behaves as
5057989442d7SLai Jiangshan 		 * an unbound (in terms of concurrency management) pool which
5058eb283428SLai Jiangshan 		 * are served by workers tied to the pool.
5059e22bee78STejun Heo 		 */
5060bc35f7efSLai Jiangshan 		pool->nr_running = 0;
5061eb283428SLai Jiangshan 
5062eb283428SLai Jiangshan 		/*
5063eb283428SLai Jiangshan 		 * With concurrency management just turned off, a busy
5064eb283428SLai Jiangshan 		 * worker blocking could lead to lengthy stalls.  Kick off
5065eb283428SLai Jiangshan 		 * unbound chain execution of currently pending work items.
5066eb283428SLai Jiangshan 		 */
5067eb283428SLai Jiangshan 		wake_up_worker(pool);
5068989442d7SLai Jiangshan 
5069a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
5070989442d7SLai Jiangshan 
5071*793777bcSValentin Schneider 		for_each_pool_worker(worker, pool)
5072*793777bcSValentin Schneider 			unbind_worker(worker);
5073989442d7SLai Jiangshan 
5074989442d7SLai Jiangshan 		mutex_unlock(&wq_pool_attach_mutex);
5075eb283428SLai Jiangshan 	}
5076db7bccf4STejun Heo }
5077db7bccf4STejun Heo 
5078bd7c089eSTejun Heo /**
5079bd7c089eSTejun Heo  * rebind_workers - rebind all workers of a pool to the associated CPU
5080bd7c089eSTejun Heo  * @pool: pool of interest
5081bd7c089eSTejun Heo  *
5082a9ab775bSTejun Heo  * @pool->cpu is coming online.  Rebind all workers to the CPU.
5083bd7c089eSTejun Heo  */
5084bd7c089eSTejun Heo static void rebind_workers(struct worker_pool *pool)
5085bd7c089eSTejun Heo {
5086a9ab775bSTejun Heo 	struct worker *worker;
5087bd7c089eSTejun Heo 
50881258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
5089bd7c089eSTejun Heo 
5090bd7c089eSTejun Heo 	/*
5091a9ab775bSTejun Heo 	 * Restore CPU affinity of all workers.  As all idle workers should
5092a9ab775bSTejun Heo 	 * be on the run-queue of the associated CPU before any local
5093402dd89dSShailendra Verma 	 * wake-ups for concurrency management happen, restore CPU affinity
5094a9ab775bSTejun Heo 	 * of all workers first and then clear UNBOUND.  As we're called
5095a9ab775bSTejun Heo 	 * from CPU_ONLINE, the following shouldn't fail.
5096bd7c089eSTejun Heo 	 */
5097*793777bcSValentin Schneider 	for_each_pool_worker(worker, pool)
5098*793777bcSValentin Schneider 		rebind_worker(worker, pool);
5099a9ab775bSTejun Heo 
5100a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
5101f7c17d26SWanpeng Li 
51023de5e884SLai Jiangshan 	pool->flags &= ~POOL_DISASSOCIATED;
5103a9ab775bSTejun Heo 
5104da028469SLai Jiangshan 	for_each_pool_worker(worker, pool) {
5105a9ab775bSTejun Heo 		unsigned int worker_flags = worker->flags;
5106a9ab775bSTejun Heo 
5107a9ab775bSTejun Heo 		/*
5108a9ab775bSTejun Heo 		 * We want to clear UNBOUND but can't directly call
5109a9ab775bSTejun Heo 		 * worker_clr_flags() or adjust nr_running.  Atomically
5110a9ab775bSTejun Heo 		 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
5111a9ab775bSTejun Heo 		 * @worker will clear REBOUND using worker_clr_flags() when
5112a9ab775bSTejun Heo 		 * it initiates the next execution cycle thus restoring
5113a9ab775bSTejun Heo 		 * concurrency management.  Note that when or whether
5114a9ab775bSTejun Heo 		 * @worker clears REBOUND doesn't affect correctness.
5115a9ab775bSTejun Heo 		 *
5116c95491edSMark Rutland 		 * WRITE_ONCE() is necessary because @worker->flags may be
5117a9ab775bSTejun Heo 		 * tested without holding any lock in
51186d25be57SThomas Gleixner 		 * wq_worker_running().  Without it, NOT_RUNNING test may
5119a9ab775bSTejun Heo 		 * fail incorrectly leading to premature concurrency
5120a9ab775bSTejun Heo 		 * management operations.
5121bd7c089eSTejun Heo 		 */
5122a9ab775bSTejun Heo 		WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
5123a9ab775bSTejun Heo 		worker_flags |= WORKER_REBOUND;
5124a9ab775bSTejun Heo 		worker_flags &= ~WORKER_UNBOUND;
5125c95491edSMark Rutland 		WRITE_ONCE(worker->flags, worker_flags);
5126bd7c089eSTejun Heo 	}
5127a9ab775bSTejun Heo 
5128a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
5129bd7c089eSTejun Heo }
5130bd7c089eSTejun Heo 
51317dbc725eSTejun Heo /**
51327dbc725eSTejun Heo  * restore_unbound_workers_cpumask - restore cpumask of unbound workers
51337dbc725eSTejun Heo  * @pool: unbound pool of interest
51347dbc725eSTejun Heo  * @cpu: the CPU which is coming up
51357dbc725eSTejun Heo  *
51367dbc725eSTejun Heo  * An unbound pool may end up with a cpumask which doesn't have any online
51377dbc725eSTejun Heo  * CPUs.  When a worker of such pool get scheduled, the scheduler resets
51387dbc725eSTejun Heo  * its cpus_allowed.  If @cpu is in @pool's cpumask which didn't have any
51397dbc725eSTejun Heo  * online CPU before, cpus_allowed of all its workers should be restored.
51407dbc725eSTejun Heo  */
51417dbc725eSTejun Heo static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
51427dbc725eSTejun Heo {
51437dbc725eSTejun Heo 	static cpumask_t cpumask;
51447dbc725eSTejun Heo 	struct worker *worker;
51457dbc725eSTejun Heo 
51461258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
51477dbc725eSTejun Heo 
51487dbc725eSTejun Heo 	/* is @cpu allowed for @pool? */
51497dbc725eSTejun Heo 	if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
51507dbc725eSTejun Heo 		return;
51517dbc725eSTejun Heo 
51527dbc725eSTejun Heo 	cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
51537dbc725eSTejun Heo 
51547dbc725eSTejun Heo 	/* as we're called from CPU_ONLINE, the following shouldn't fail */
5155da028469SLai Jiangshan 	for_each_pool_worker(worker, pool)
5156d945b5e9SPeter Zijlstra 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
51577dbc725eSTejun Heo }
51587dbc725eSTejun Heo 
51597ee681b2SThomas Gleixner int workqueue_prepare_cpu(unsigned int cpu)
51601da177e4SLinus Torvalds {
51614ce62e9eSTejun Heo 	struct worker_pool *pool;
51621da177e4SLinus Torvalds 
5163f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
51643ce63377STejun Heo 		if (pool->nr_workers)
51653ce63377STejun Heo 			continue;
5166051e1850SLai Jiangshan 		if (!create_worker(pool))
51677ee681b2SThomas Gleixner 			return -ENOMEM;
51683af24433SOleg Nesterov 	}
51697ee681b2SThomas Gleixner 	return 0;
51707ee681b2SThomas Gleixner }
51711da177e4SLinus Torvalds 
51727ee681b2SThomas Gleixner int workqueue_online_cpu(unsigned int cpu)
51737ee681b2SThomas Gleixner {
51747ee681b2SThomas Gleixner 	struct worker_pool *pool;
51757ee681b2SThomas Gleixner 	struct workqueue_struct *wq;
51767ee681b2SThomas Gleixner 	int pi;
51777ee681b2SThomas Gleixner 
517868e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
51797dbc725eSTejun Heo 
51807dbc725eSTejun Heo 	for_each_pool(pool, pi) {
51811258fae7STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
518294cf58bbSTejun Heo 
5183f05b558dSLai Jiangshan 		if (pool->cpu == cpu)
518494cf58bbSTejun Heo 			rebind_workers(pool);
5185f05b558dSLai Jiangshan 		else if (pool->cpu < 0)
51867dbc725eSTejun Heo 			restore_unbound_workers_cpumask(pool, cpu);
518794cf58bbSTejun Heo 
51881258fae7STejun Heo 		mutex_unlock(&wq_pool_attach_mutex);
518994cf58bbSTejun Heo 	}
51907dbc725eSTejun Heo 
51914c16bd32STejun Heo 	/* update NUMA affinity of unbound workqueues */
51924c16bd32STejun Heo 	list_for_each_entry(wq, &workqueues, list)
51934c16bd32STejun Heo 		wq_update_unbound_numa(wq, cpu, true);
51944c16bd32STejun Heo 
519568e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
51967ee681b2SThomas Gleixner 	return 0;
519765758202STejun Heo }
519865758202STejun Heo 
51997ee681b2SThomas Gleixner int workqueue_offline_cpu(unsigned int cpu)
520065758202STejun Heo {
52014c16bd32STejun Heo 	struct workqueue_struct *wq;
52028db25e78STejun Heo 
52034c16bd32STejun Heo 	/* unbinding per-cpu workers should happen on the local CPU */
5204e8b3f8dbSLai Jiangshan 	if (WARN_ON(cpu != smp_processor_id()))
5205e8b3f8dbSLai Jiangshan 		return -1;
5206e8b3f8dbSLai Jiangshan 
5207e8b3f8dbSLai Jiangshan 	unbind_workers(cpu);
52084c16bd32STejun Heo 
52094c16bd32STejun Heo 	/* update NUMA affinity of unbound workqueues */
52104c16bd32STejun Heo 	mutex_lock(&wq_pool_mutex);
52114c16bd32STejun Heo 	list_for_each_entry(wq, &workqueues, list)
52124c16bd32STejun Heo 		wq_update_unbound_numa(wq, cpu, false);
52134c16bd32STejun Heo 	mutex_unlock(&wq_pool_mutex);
52144c16bd32STejun Heo 
52157ee681b2SThomas Gleixner 	return 0;
521665758202STejun Heo }
521765758202STejun Heo 
52182d3854a3SRusty Russell struct work_for_cpu {
5219ed48ece2STejun Heo 	struct work_struct work;
52202d3854a3SRusty Russell 	long (*fn)(void *);
52212d3854a3SRusty Russell 	void *arg;
52222d3854a3SRusty Russell 	long ret;
52232d3854a3SRusty Russell };
52242d3854a3SRusty Russell 
5225ed48ece2STejun Heo static void work_for_cpu_fn(struct work_struct *work)
52262d3854a3SRusty Russell {
5227ed48ece2STejun Heo 	struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
5228ed48ece2STejun Heo 
52292d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
52302d3854a3SRusty Russell }
52312d3854a3SRusty Russell 
52322d3854a3SRusty Russell /**
523322aceb31SAnna-Maria Gleixner  * work_on_cpu - run a function in thread context on a particular cpu
52342d3854a3SRusty Russell  * @cpu: the cpu to run on
52352d3854a3SRusty Russell  * @fn: the function to run
52362d3854a3SRusty Russell  * @arg: the function arg
52372d3854a3SRusty Russell  *
523831ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
52396b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
5240d185af30SYacine Belkadi  *
5241d185af30SYacine Belkadi  * Return: The value @fn returns.
52422d3854a3SRusty Russell  */
5243d84ff051STejun Heo long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
52442d3854a3SRusty Russell {
5245ed48ece2STejun Heo 	struct work_for_cpu wfc = { .fn = fn, .arg = arg };
52462d3854a3SRusty Russell 
5247ed48ece2STejun Heo 	INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
5248ed48ece2STejun Heo 	schedule_work_on(cpu, &wfc.work);
524912997d1aSBjorn Helgaas 	flush_work(&wfc.work);
5250440a1136SChuansheng Liu 	destroy_work_on_stack(&wfc.work);
52512d3854a3SRusty Russell 	return wfc.ret;
52522d3854a3SRusty Russell }
52532d3854a3SRusty Russell EXPORT_SYMBOL_GPL(work_on_cpu);
52540e8d6a93SThomas Gleixner 
52550e8d6a93SThomas Gleixner /**
52560e8d6a93SThomas Gleixner  * work_on_cpu_safe - run a function in thread context on a particular cpu
52570e8d6a93SThomas Gleixner  * @cpu: the cpu to run on
52580e8d6a93SThomas Gleixner  * @fn:  the function to run
52590e8d6a93SThomas Gleixner  * @arg: the function argument
52600e8d6a93SThomas Gleixner  *
52610e8d6a93SThomas Gleixner  * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
52620e8d6a93SThomas Gleixner  * any locks which would prevent @fn from completing.
52630e8d6a93SThomas Gleixner  *
52640e8d6a93SThomas Gleixner  * Return: The value @fn returns.
52650e8d6a93SThomas Gleixner  */
52660e8d6a93SThomas Gleixner long work_on_cpu_safe(int cpu, long (*fn)(void *), void *arg)
52670e8d6a93SThomas Gleixner {
52680e8d6a93SThomas Gleixner 	long ret = -ENODEV;
52690e8d6a93SThomas Gleixner 
5270ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
52710e8d6a93SThomas Gleixner 	if (cpu_online(cpu))
52720e8d6a93SThomas Gleixner 		ret = work_on_cpu(cpu, fn, arg);
5273ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
52740e8d6a93SThomas Gleixner 	return ret;
52750e8d6a93SThomas Gleixner }
52760e8d6a93SThomas Gleixner EXPORT_SYMBOL_GPL(work_on_cpu_safe);
52772d3854a3SRusty Russell #endif /* CONFIG_SMP */
52782d3854a3SRusty Russell 
5279a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
5280e7577c50SRusty Russell 
5281a0a1a5fdSTejun Heo /**
5282a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
5283a0a1a5fdSTejun Heo  *
528458a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
5285f97a4a1aSLai Jiangshan  * workqueues will queue new works to their inactive_works list instead of
5286706026c2STejun Heo  * pool->worklist.
5287a0a1a5fdSTejun Heo  *
5288a0a1a5fdSTejun Heo  * CONTEXT:
5289a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5290a0a1a5fdSTejun Heo  */
5291a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
5292a0a1a5fdSTejun Heo {
529324b8a847STejun Heo 	struct workqueue_struct *wq;
529424b8a847STejun Heo 	struct pool_workqueue *pwq;
5295a0a1a5fdSTejun Heo 
529668e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5297a0a1a5fdSTejun Heo 
52986183c009STejun Heo 	WARN_ON_ONCE(workqueue_freezing);
5299a0a1a5fdSTejun Heo 	workqueue_freezing = true;
5300a0a1a5fdSTejun Heo 
530124b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5302a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
5303699ce097STejun Heo 		for_each_pwq(pwq, wq)
5304699ce097STejun Heo 			pwq_adjust_max_active(pwq);
5305a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
5306a1056305STejun Heo 	}
53075bcab335STejun Heo 
530868e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5309a0a1a5fdSTejun Heo }
5310a0a1a5fdSTejun Heo 
5311a0a1a5fdSTejun Heo /**
531258a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
5313a0a1a5fdSTejun Heo  *
5314a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
5315a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
5316a0a1a5fdSTejun Heo  *
5317a0a1a5fdSTejun Heo  * CONTEXT:
531868e13a67SLai Jiangshan  * Grabs and releases wq_pool_mutex.
5319a0a1a5fdSTejun Heo  *
5320d185af30SYacine Belkadi  * Return:
532158a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
532258a69cb4STejun Heo  * is complete.
5323a0a1a5fdSTejun Heo  */
5324a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
5325a0a1a5fdSTejun Heo {
5326a0a1a5fdSTejun Heo 	bool busy = false;
532724b8a847STejun Heo 	struct workqueue_struct *wq;
532824b8a847STejun Heo 	struct pool_workqueue *pwq;
5329a0a1a5fdSTejun Heo 
533068e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5331a0a1a5fdSTejun Heo 
53326183c009STejun Heo 	WARN_ON_ONCE(!workqueue_freezing);
5333a0a1a5fdSTejun Heo 
533424b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
533524b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
533624b8a847STejun Heo 			continue;
5337a0a1a5fdSTejun Heo 		/*
5338a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
5339a0a1a5fdSTejun Heo 		 * to peek without lock.
5340a0a1a5fdSTejun Heo 		 */
534124acfb71SThomas Gleixner 		rcu_read_lock();
534224b8a847STejun Heo 		for_each_pwq(pwq, wq) {
53436183c009STejun Heo 			WARN_ON_ONCE(pwq->nr_active < 0);
5344112202d9STejun Heo 			if (pwq->nr_active) {
5345a0a1a5fdSTejun Heo 				busy = true;
534624acfb71SThomas Gleixner 				rcu_read_unlock();
5347a0a1a5fdSTejun Heo 				goto out_unlock;
5348a0a1a5fdSTejun Heo 			}
5349a0a1a5fdSTejun Heo 		}
535024acfb71SThomas Gleixner 		rcu_read_unlock();
5351a0a1a5fdSTejun Heo 	}
5352a0a1a5fdSTejun Heo out_unlock:
535368e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5354a0a1a5fdSTejun Heo 	return busy;
5355a0a1a5fdSTejun Heo }
5356a0a1a5fdSTejun Heo 
5357a0a1a5fdSTejun Heo /**
5358a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
5359a0a1a5fdSTejun Heo  *
5360a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
5361706026c2STejun Heo  * frozen works are transferred to their respective pool worklists.
5362a0a1a5fdSTejun Heo  *
5363a0a1a5fdSTejun Heo  * CONTEXT:
5364a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5365a0a1a5fdSTejun Heo  */
5366a0a1a5fdSTejun Heo void thaw_workqueues(void)
5367a0a1a5fdSTejun Heo {
536824b8a847STejun Heo 	struct workqueue_struct *wq;
536924b8a847STejun Heo 	struct pool_workqueue *pwq;
5370a0a1a5fdSTejun Heo 
537168e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5372a0a1a5fdSTejun Heo 
5373a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
5374a0a1a5fdSTejun Heo 		goto out_unlock;
5375a0a1a5fdSTejun Heo 
537674b414eaSLai Jiangshan 	workqueue_freezing = false;
537724b8a847STejun Heo 
537824b8a847STejun Heo 	/* restore max_active and repopulate worklist */
537924b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5380a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
5381699ce097STejun Heo 		for_each_pwq(pwq, wq)
5382699ce097STejun Heo 			pwq_adjust_max_active(pwq);
5383a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
538424b8a847STejun Heo 	}
538524b8a847STejun Heo 
5386a0a1a5fdSTejun Heo out_unlock:
538768e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5388a0a1a5fdSTejun Heo }
5389a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
5390a0a1a5fdSTejun Heo 
539199c621efSLai Jiangshan static int workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask)
5392042f7df1SLai Jiangshan {
5393042f7df1SLai Jiangshan 	LIST_HEAD(ctxs);
5394042f7df1SLai Jiangshan 	int ret = 0;
5395042f7df1SLai Jiangshan 	struct workqueue_struct *wq;
5396042f7df1SLai Jiangshan 	struct apply_wqattrs_ctx *ctx, *n;
5397042f7df1SLai Jiangshan 
5398042f7df1SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5399042f7df1SLai Jiangshan 
5400042f7df1SLai Jiangshan 	list_for_each_entry(wq, &workqueues, list) {
5401042f7df1SLai Jiangshan 		if (!(wq->flags & WQ_UNBOUND))
5402042f7df1SLai Jiangshan 			continue;
5403042f7df1SLai Jiangshan 		/* creating multiple pwqs breaks ordering guarantee */
5404042f7df1SLai Jiangshan 		if (wq->flags & __WQ_ORDERED)
5405042f7df1SLai Jiangshan 			continue;
5406042f7df1SLai Jiangshan 
540799c621efSLai Jiangshan 		ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs, unbound_cpumask);
5408042f7df1SLai Jiangshan 		if (!ctx) {
5409042f7df1SLai Jiangshan 			ret = -ENOMEM;
5410042f7df1SLai Jiangshan 			break;
5411042f7df1SLai Jiangshan 		}
5412042f7df1SLai Jiangshan 
5413042f7df1SLai Jiangshan 		list_add_tail(&ctx->list, &ctxs);
5414042f7df1SLai Jiangshan 	}
5415042f7df1SLai Jiangshan 
5416042f7df1SLai Jiangshan 	list_for_each_entry_safe(ctx, n, &ctxs, list) {
5417042f7df1SLai Jiangshan 		if (!ret)
5418042f7df1SLai Jiangshan 			apply_wqattrs_commit(ctx);
5419042f7df1SLai Jiangshan 		apply_wqattrs_cleanup(ctx);
5420042f7df1SLai Jiangshan 	}
5421042f7df1SLai Jiangshan 
542299c621efSLai Jiangshan 	if (!ret) {
542399c621efSLai Jiangshan 		mutex_lock(&wq_pool_attach_mutex);
542499c621efSLai Jiangshan 		cpumask_copy(wq_unbound_cpumask, unbound_cpumask);
542599c621efSLai Jiangshan 		mutex_unlock(&wq_pool_attach_mutex);
542699c621efSLai Jiangshan 	}
5427042f7df1SLai Jiangshan 	return ret;
5428042f7df1SLai Jiangshan }
5429042f7df1SLai Jiangshan 
5430042f7df1SLai Jiangshan /**
5431042f7df1SLai Jiangshan  *  workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
5432042f7df1SLai Jiangshan  *  @cpumask: the cpumask to set
5433042f7df1SLai Jiangshan  *
5434042f7df1SLai Jiangshan  *  The low-level workqueues cpumask is a global cpumask that limits
5435042f7df1SLai Jiangshan  *  the affinity of all unbound workqueues.  This function check the @cpumask
5436042f7df1SLai Jiangshan  *  and apply it to all unbound workqueues and updates all pwqs of them.
5437042f7df1SLai Jiangshan  *
543867dc8325SCai Huoqing  *  Return:	0	- Success
5439042f7df1SLai Jiangshan  *  		-EINVAL	- Invalid @cpumask
5440042f7df1SLai Jiangshan  *  		-ENOMEM	- Failed to allocate memory for attrs or pwqs.
5441042f7df1SLai Jiangshan  */
5442042f7df1SLai Jiangshan int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
5443042f7df1SLai Jiangshan {
5444042f7df1SLai Jiangshan 	int ret = -EINVAL;
5445042f7df1SLai Jiangshan 
5446c98a9805STal Shorer 	/*
5447c98a9805STal Shorer 	 * Not excluding isolated cpus on purpose.
5448c98a9805STal Shorer 	 * If the user wishes to include them, we allow that.
5449c98a9805STal Shorer 	 */
5450042f7df1SLai Jiangshan 	cpumask_and(cpumask, cpumask, cpu_possible_mask);
5451042f7df1SLai Jiangshan 	if (!cpumask_empty(cpumask)) {
5452a0111cf6SLai Jiangshan 		apply_wqattrs_lock();
5453d25302e4SMenglong Dong 		if (cpumask_equal(cpumask, wq_unbound_cpumask)) {
5454d25302e4SMenglong Dong 			ret = 0;
5455d25302e4SMenglong Dong 			goto out_unlock;
5456d25302e4SMenglong Dong 		}
5457d25302e4SMenglong Dong 
545899c621efSLai Jiangshan 		ret = workqueue_apply_unbound_cpumask(cpumask);
5459042f7df1SLai Jiangshan 
5460d25302e4SMenglong Dong out_unlock:
5461a0111cf6SLai Jiangshan 		apply_wqattrs_unlock();
5462042f7df1SLai Jiangshan 	}
5463042f7df1SLai Jiangshan 
5464042f7df1SLai Jiangshan 	return ret;
5465042f7df1SLai Jiangshan }
5466042f7df1SLai Jiangshan 
54676ba94429SFrederic Weisbecker #ifdef CONFIG_SYSFS
54686ba94429SFrederic Weisbecker /*
54696ba94429SFrederic Weisbecker  * Workqueues with WQ_SYSFS flag set is visible to userland via
54706ba94429SFrederic Weisbecker  * /sys/bus/workqueue/devices/WQ_NAME.  All visible workqueues have the
54716ba94429SFrederic Weisbecker  * following attributes.
54726ba94429SFrederic Weisbecker  *
54736ba94429SFrederic Weisbecker  *  per_cpu	RO bool	: whether the workqueue is per-cpu or unbound
54746ba94429SFrederic Weisbecker  *  max_active	RW int	: maximum number of in-flight work items
54756ba94429SFrederic Weisbecker  *
54766ba94429SFrederic Weisbecker  * Unbound workqueues have the following extra attributes.
54776ba94429SFrederic Weisbecker  *
54789a19b463SWang Long  *  pool_ids	RO int	: the associated pool IDs for each node
54796ba94429SFrederic Weisbecker  *  nice	RW int	: nice value of the workers
54806ba94429SFrederic Weisbecker  *  cpumask	RW mask	: bitmask of allowed CPUs for the workers
54819a19b463SWang Long  *  numa	RW bool	: whether enable NUMA affinity
54826ba94429SFrederic Weisbecker  */
54836ba94429SFrederic Weisbecker struct wq_device {
54846ba94429SFrederic Weisbecker 	struct workqueue_struct		*wq;
54856ba94429SFrederic Weisbecker 	struct device			dev;
54866ba94429SFrederic Weisbecker };
54876ba94429SFrederic Weisbecker 
54886ba94429SFrederic Weisbecker static struct workqueue_struct *dev_to_wq(struct device *dev)
54896ba94429SFrederic Weisbecker {
54906ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
54916ba94429SFrederic Weisbecker 
54926ba94429SFrederic Weisbecker 	return wq_dev->wq;
54936ba94429SFrederic Weisbecker }
54946ba94429SFrederic Weisbecker 
54956ba94429SFrederic Weisbecker static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
54966ba94429SFrederic Weisbecker 			    char *buf)
54976ba94429SFrederic Weisbecker {
54986ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
54996ba94429SFrederic Weisbecker 
55006ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
55016ba94429SFrederic Weisbecker }
55026ba94429SFrederic Weisbecker static DEVICE_ATTR_RO(per_cpu);
55036ba94429SFrederic Weisbecker 
55046ba94429SFrederic Weisbecker static ssize_t max_active_show(struct device *dev,
55056ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
55066ba94429SFrederic Weisbecker {
55076ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
55086ba94429SFrederic Weisbecker 
55096ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
55106ba94429SFrederic Weisbecker }
55116ba94429SFrederic Weisbecker 
55126ba94429SFrederic Weisbecker static ssize_t max_active_store(struct device *dev,
55136ba94429SFrederic Weisbecker 				struct device_attribute *attr, const char *buf,
55146ba94429SFrederic Weisbecker 				size_t count)
55156ba94429SFrederic Weisbecker {
55166ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
55176ba94429SFrederic Weisbecker 	int val;
55186ba94429SFrederic Weisbecker 
55196ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &val) != 1 || val <= 0)
55206ba94429SFrederic Weisbecker 		return -EINVAL;
55216ba94429SFrederic Weisbecker 
55226ba94429SFrederic Weisbecker 	workqueue_set_max_active(wq, val);
55236ba94429SFrederic Weisbecker 	return count;
55246ba94429SFrederic Weisbecker }
55256ba94429SFrederic Weisbecker static DEVICE_ATTR_RW(max_active);
55266ba94429SFrederic Weisbecker 
55276ba94429SFrederic Weisbecker static struct attribute *wq_sysfs_attrs[] = {
55286ba94429SFrederic Weisbecker 	&dev_attr_per_cpu.attr,
55296ba94429SFrederic Weisbecker 	&dev_attr_max_active.attr,
55306ba94429SFrederic Weisbecker 	NULL,
55316ba94429SFrederic Weisbecker };
55326ba94429SFrederic Weisbecker ATTRIBUTE_GROUPS(wq_sysfs);
55336ba94429SFrederic Weisbecker 
55346ba94429SFrederic Weisbecker static ssize_t wq_pool_ids_show(struct device *dev,
55356ba94429SFrederic Weisbecker 				struct device_attribute *attr, char *buf)
55366ba94429SFrederic Weisbecker {
55376ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
55386ba94429SFrederic Weisbecker 	const char *delim = "";
55396ba94429SFrederic Weisbecker 	int node, written = 0;
55406ba94429SFrederic Weisbecker 
5541ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
554224acfb71SThomas Gleixner 	rcu_read_lock();
55436ba94429SFrederic Weisbecker 	for_each_node(node) {
55446ba94429SFrederic Weisbecker 		written += scnprintf(buf + written, PAGE_SIZE - written,
55456ba94429SFrederic Weisbecker 				     "%s%d:%d", delim, node,
55466ba94429SFrederic Weisbecker 				     unbound_pwq_by_node(wq, node)->pool->id);
55476ba94429SFrederic Weisbecker 		delim = " ";
55486ba94429SFrederic Weisbecker 	}
55496ba94429SFrederic Weisbecker 	written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
555024acfb71SThomas Gleixner 	rcu_read_unlock();
5551ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
55526ba94429SFrederic Weisbecker 
55536ba94429SFrederic Weisbecker 	return written;
55546ba94429SFrederic Weisbecker }
55556ba94429SFrederic Weisbecker 
55566ba94429SFrederic Weisbecker static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
55576ba94429SFrederic Weisbecker 			    char *buf)
55586ba94429SFrederic Weisbecker {
55596ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
55606ba94429SFrederic Weisbecker 	int written;
55616ba94429SFrederic Weisbecker 
55626ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
55636ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
55646ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
55656ba94429SFrederic Weisbecker 
55666ba94429SFrederic Weisbecker 	return written;
55676ba94429SFrederic Weisbecker }
55686ba94429SFrederic Weisbecker 
55696ba94429SFrederic Weisbecker /* prepare workqueue_attrs for sysfs store operations */
55706ba94429SFrederic Weisbecker static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
55716ba94429SFrederic Weisbecker {
55726ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
55736ba94429SFrederic Weisbecker 
5574899a94feSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5575899a94feSLai Jiangshan 
5576be69d00dSThomas Gleixner 	attrs = alloc_workqueue_attrs();
55776ba94429SFrederic Weisbecker 	if (!attrs)
55786ba94429SFrederic Weisbecker 		return NULL;
55796ba94429SFrederic Weisbecker 
55806ba94429SFrederic Weisbecker 	copy_workqueue_attrs(attrs, wq->unbound_attrs);
55816ba94429SFrederic Weisbecker 	return attrs;
55826ba94429SFrederic Weisbecker }
55836ba94429SFrederic Weisbecker 
55846ba94429SFrederic Weisbecker static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
55856ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
55866ba94429SFrederic Weisbecker {
55876ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
55886ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5589d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
5590d4d3e257SLai Jiangshan 
5591d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
55926ba94429SFrederic Weisbecker 
55936ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
55946ba94429SFrederic Weisbecker 	if (!attrs)
5595d4d3e257SLai Jiangshan 		goto out_unlock;
55966ba94429SFrederic Weisbecker 
55976ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &attrs->nice) == 1 &&
55986ba94429SFrederic Weisbecker 	    attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
5599d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
56006ba94429SFrederic Weisbecker 	else
56016ba94429SFrederic Weisbecker 		ret = -EINVAL;
56026ba94429SFrederic Weisbecker 
5603d4d3e257SLai Jiangshan out_unlock:
5604d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
56056ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
56066ba94429SFrederic Weisbecker 	return ret ?: count;
56076ba94429SFrederic Weisbecker }
56086ba94429SFrederic Weisbecker 
56096ba94429SFrederic Weisbecker static ssize_t wq_cpumask_show(struct device *dev,
56106ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
56116ba94429SFrederic Weisbecker {
56126ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
56136ba94429SFrederic Weisbecker 	int written;
56146ba94429SFrederic Weisbecker 
56156ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
56166ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
56176ba94429SFrederic Weisbecker 			    cpumask_pr_args(wq->unbound_attrs->cpumask));
56186ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
56196ba94429SFrederic Weisbecker 	return written;
56206ba94429SFrederic Weisbecker }
56216ba94429SFrederic Weisbecker 
56226ba94429SFrederic Weisbecker static ssize_t wq_cpumask_store(struct device *dev,
56236ba94429SFrederic Weisbecker 				struct device_attribute *attr,
56246ba94429SFrederic Weisbecker 				const char *buf, size_t count)
56256ba94429SFrederic Weisbecker {
56266ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
56276ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5628d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
5629d4d3e257SLai Jiangshan 
5630d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
56316ba94429SFrederic Weisbecker 
56326ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
56336ba94429SFrederic Weisbecker 	if (!attrs)
5634d4d3e257SLai Jiangshan 		goto out_unlock;
56356ba94429SFrederic Weisbecker 
56366ba94429SFrederic Weisbecker 	ret = cpumask_parse(buf, attrs->cpumask);
56376ba94429SFrederic Weisbecker 	if (!ret)
5638d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
56396ba94429SFrederic Weisbecker 
5640d4d3e257SLai Jiangshan out_unlock:
5641d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
56426ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
56436ba94429SFrederic Weisbecker 	return ret ?: count;
56446ba94429SFrederic Weisbecker }
56456ba94429SFrederic Weisbecker 
56466ba94429SFrederic Weisbecker static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
56476ba94429SFrederic Weisbecker 			    char *buf)
56486ba94429SFrederic Weisbecker {
56496ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
56506ba94429SFrederic Weisbecker 	int written;
56516ba94429SFrederic Weisbecker 
56526ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
56536ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n",
56546ba94429SFrederic Weisbecker 			    !wq->unbound_attrs->no_numa);
56556ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
56566ba94429SFrederic Weisbecker 
56576ba94429SFrederic Weisbecker 	return written;
56586ba94429SFrederic Weisbecker }
56596ba94429SFrederic Weisbecker 
56606ba94429SFrederic Weisbecker static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
56616ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
56626ba94429SFrederic Weisbecker {
56636ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
56646ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5665d4d3e257SLai Jiangshan 	int v, ret = -ENOMEM;
5666d4d3e257SLai Jiangshan 
5667d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
56686ba94429SFrederic Weisbecker 
56696ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
56706ba94429SFrederic Weisbecker 	if (!attrs)
5671d4d3e257SLai Jiangshan 		goto out_unlock;
56726ba94429SFrederic Weisbecker 
56736ba94429SFrederic Weisbecker 	ret = -EINVAL;
56746ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &v) == 1) {
56756ba94429SFrederic Weisbecker 		attrs->no_numa = !v;
5676d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
56776ba94429SFrederic Weisbecker 	}
56786ba94429SFrederic Weisbecker 
5679d4d3e257SLai Jiangshan out_unlock:
5680d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
56816ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
56826ba94429SFrederic Weisbecker 	return ret ?: count;
56836ba94429SFrederic Weisbecker }
56846ba94429SFrederic Weisbecker 
56856ba94429SFrederic Weisbecker static struct device_attribute wq_sysfs_unbound_attrs[] = {
56866ba94429SFrederic Weisbecker 	__ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
56876ba94429SFrederic Weisbecker 	__ATTR(nice, 0644, wq_nice_show, wq_nice_store),
56886ba94429SFrederic Weisbecker 	__ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
56896ba94429SFrederic Weisbecker 	__ATTR(numa, 0644, wq_numa_show, wq_numa_store),
56906ba94429SFrederic Weisbecker 	__ATTR_NULL,
56916ba94429SFrederic Weisbecker };
56926ba94429SFrederic Weisbecker 
56936ba94429SFrederic Weisbecker static struct bus_type wq_subsys = {
56946ba94429SFrederic Weisbecker 	.name				= "workqueue",
56956ba94429SFrederic Weisbecker 	.dev_groups			= wq_sysfs_groups,
56966ba94429SFrederic Weisbecker };
56976ba94429SFrederic Weisbecker 
5698b05a7928SFrederic Weisbecker static ssize_t wq_unbound_cpumask_show(struct device *dev,
5699b05a7928SFrederic Weisbecker 		struct device_attribute *attr, char *buf)
5700b05a7928SFrederic Weisbecker {
5701b05a7928SFrederic Weisbecker 	int written;
5702b05a7928SFrederic Weisbecker 
5703042f7df1SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5704b05a7928SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
5705b05a7928SFrederic Weisbecker 			    cpumask_pr_args(wq_unbound_cpumask));
5706042f7df1SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5707b05a7928SFrederic Weisbecker 
5708b05a7928SFrederic Weisbecker 	return written;
5709b05a7928SFrederic Weisbecker }
5710b05a7928SFrederic Weisbecker 
5711042f7df1SLai Jiangshan static ssize_t wq_unbound_cpumask_store(struct device *dev,
5712042f7df1SLai Jiangshan 		struct device_attribute *attr, const char *buf, size_t count)
5713042f7df1SLai Jiangshan {
5714042f7df1SLai Jiangshan 	cpumask_var_t cpumask;
5715042f7df1SLai Jiangshan 	int ret;
5716042f7df1SLai Jiangshan 
5717042f7df1SLai Jiangshan 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
5718042f7df1SLai Jiangshan 		return -ENOMEM;
5719042f7df1SLai Jiangshan 
5720042f7df1SLai Jiangshan 	ret = cpumask_parse(buf, cpumask);
5721042f7df1SLai Jiangshan 	if (!ret)
5722042f7df1SLai Jiangshan 		ret = workqueue_set_unbound_cpumask(cpumask);
5723042f7df1SLai Jiangshan 
5724042f7df1SLai Jiangshan 	free_cpumask_var(cpumask);
5725042f7df1SLai Jiangshan 	return ret ? ret : count;
5726042f7df1SLai Jiangshan }
5727042f7df1SLai Jiangshan 
5728b05a7928SFrederic Weisbecker static struct device_attribute wq_sysfs_cpumask_attr =
5729042f7df1SLai Jiangshan 	__ATTR(cpumask, 0644, wq_unbound_cpumask_show,
5730042f7df1SLai Jiangshan 	       wq_unbound_cpumask_store);
5731b05a7928SFrederic Weisbecker 
57326ba94429SFrederic Weisbecker static int __init wq_sysfs_init(void)
57336ba94429SFrederic Weisbecker {
5734b05a7928SFrederic Weisbecker 	int err;
5735b05a7928SFrederic Weisbecker 
5736b05a7928SFrederic Weisbecker 	err = subsys_virtual_register(&wq_subsys, NULL);
5737b05a7928SFrederic Weisbecker 	if (err)
5738b05a7928SFrederic Weisbecker 		return err;
5739b05a7928SFrederic Weisbecker 
5740b05a7928SFrederic Weisbecker 	return device_create_file(wq_subsys.dev_root, &wq_sysfs_cpumask_attr);
57416ba94429SFrederic Weisbecker }
57426ba94429SFrederic Weisbecker core_initcall(wq_sysfs_init);
57436ba94429SFrederic Weisbecker 
57446ba94429SFrederic Weisbecker static void wq_device_release(struct device *dev)
57456ba94429SFrederic Weisbecker {
57466ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
57476ba94429SFrederic Weisbecker 
57486ba94429SFrederic Weisbecker 	kfree(wq_dev);
57496ba94429SFrederic Weisbecker }
57506ba94429SFrederic Weisbecker 
57516ba94429SFrederic Weisbecker /**
57526ba94429SFrederic Weisbecker  * workqueue_sysfs_register - make a workqueue visible in sysfs
57536ba94429SFrederic Weisbecker  * @wq: the workqueue to register
57546ba94429SFrederic Weisbecker  *
57556ba94429SFrederic Weisbecker  * Expose @wq in sysfs under /sys/bus/workqueue/devices.
57566ba94429SFrederic Weisbecker  * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
57576ba94429SFrederic Weisbecker  * which is the preferred method.
57586ba94429SFrederic Weisbecker  *
57596ba94429SFrederic Weisbecker  * Workqueue user should use this function directly iff it wants to apply
57606ba94429SFrederic Weisbecker  * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
57616ba94429SFrederic Weisbecker  * apply_workqueue_attrs() may race against userland updating the
57626ba94429SFrederic Weisbecker  * attributes.
57636ba94429SFrederic Weisbecker  *
57646ba94429SFrederic Weisbecker  * Return: 0 on success, -errno on failure.
57656ba94429SFrederic Weisbecker  */
57666ba94429SFrederic Weisbecker int workqueue_sysfs_register(struct workqueue_struct *wq)
57676ba94429SFrederic Weisbecker {
57686ba94429SFrederic Weisbecker 	struct wq_device *wq_dev;
57696ba94429SFrederic Weisbecker 	int ret;
57706ba94429SFrederic Weisbecker 
57716ba94429SFrederic Weisbecker 	/*
5772402dd89dSShailendra Verma 	 * Adjusting max_active or creating new pwqs by applying
57736ba94429SFrederic Weisbecker 	 * attributes breaks ordering guarantee.  Disallow exposing ordered
57746ba94429SFrederic Weisbecker 	 * workqueues.
57756ba94429SFrederic Weisbecker 	 */
57760a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
57776ba94429SFrederic Weisbecker 		return -EINVAL;
57786ba94429SFrederic Weisbecker 
57796ba94429SFrederic Weisbecker 	wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
57806ba94429SFrederic Weisbecker 	if (!wq_dev)
57816ba94429SFrederic Weisbecker 		return -ENOMEM;
57826ba94429SFrederic Weisbecker 
57836ba94429SFrederic Weisbecker 	wq_dev->wq = wq;
57846ba94429SFrederic Weisbecker 	wq_dev->dev.bus = &wq_subsys;
57856ba94429SFrederic Weisbecker 	wq_dev->dev.release = wq_device_release;
578623217b44SLars-Peter Clausen 	dev_set_name(&wq_dev->dev, "%s", wq->name);
57876ba94429SFrederic Weisbecker 
57886ba94429SFrederic Weisbecker 	/*
57896ba94429SFrederic Weisbecker 	 * unbound_attrs are created separately.  Suppress uevent until
57906ba94429SFrederic Weisbecker 	 * everything is ready.
57916ba94429SFrederic Weisbecker 	 */
57926ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, true);
57936ba94429SFrederic Weisbecker 
57946ba94429SFrederic Weisbecker 	ret = device_register(&wq_dev->dev);
57956ba94429SFrederic Weisbecker 	if (ret) {
5796537f4146SArvind Yadav 		put_device(&wq_dev->dev);
57976ba94429SFrederic Weisbecker 		wq->wq_dev = NULL;
57986ba94429SFrederic Weisbecker 		return ret;
57996ba94429SFrederic Weisbecker 	}
58006ba94429SFrederic Weisbecker 
58016ba94429SFrederic Weisbecker 	if (wq->flags & WQ_UNBOUND) {
58026ba94429SFrederic Weisbecker 		struct device_attribute *attr;
58036ba94429SFrederic Weisbecker 
58046ba94429SFrederic Weisbecker 		for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
58056ba94429SFrederic Weisbecker 			ret = device_create_file(&wq_dev->dev, attr);
58066ba94429SFrederic Weisbecker 			if (ret) {
58076ba94429SFrederic Weisbecker 				device_unregister(&wq_dev->dev);
58086ba94429SFrederic Weisbecker 				wq->wq_dev = NULL;
58096ba94429SFrederic Weisbecker 				return ret;
58106ba94429SFrederic Weisbecker 			}
58116ba94429SFrederic Weisbecker 		}
58126ba94429SFrederic Weisbecker 	}
58136ba94429SFrederic Weisbecker 
58146ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, false);
58156ba94429SFrederic Weisbecker 	kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
58166ba94429SFrederic Weisbecker 	return 0;
58176ba94429SFrederic Weisbecker }
58186ba94429SFrederic Weisbecker 
58196ba94429SFrederic Weisbecker /**
58206ba94429SFrederic Weisbecker  * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
58216ba94429SFrederic Weisbecker  * @wq: the workqueue to unregister
58226ba94429SFrederic Weisbecker  *
58236ba94429SFrederic Weisbecker  * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
58246ba94429SFrederic Weisbecker  */
58256ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
58266ba94429SFrederic Weisbecker {
58276ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = wq->wq_dev;
58286ba94429SFrederic Weisbecker 
58296ba94429SFrederic Weisbecker 	if (!wq->wq_dev)
58306ba94429SFrederic Weisbecker 		return;
58316ba94429SFrederic Weisbecker 
58326ba94429SFrederic Weisbecker 	wq->wq_dev = NULL;
58336ba94429SFrederic Weisbecker 	device_unregister(&wq_dev->dev);
58346ba94429SFrederic Weisbecker }
58356ba94429SFrederic Weisbecker #else	/* CONFIG_SYSFS */
58366ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)	{ }
58376ba94429SFrederic Weisbecker #endif	/* CONFIG_SYSFS */
58386ba94429SFrederic Weisbecker 
583982607adcSTejun Heo /*
584082607adcSTejun Heo  * Workqueue watchdog.
584182607adcSTejun Heo  *
584282607adcSTejun Heo  * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
584382607adcSTejun Heo  * flush dependency, a concurrency managed work item which stays RUNNING
584482607adcSTejun Heo  * indefinitely.  Workqueue stalls can be very difficult to debug as the
584582607adcSTejun Heo  * usual warning mechanisms don't trigger and internal workqueue state is
584682607adcSTejun Heo  * largely opaque.
584782607adcSTejun Heo  *
584882607adcSTejun Heo  * Workqueue watchdog monitors all worker pools periodically and dumps
584982607adcSTejun Heo  * state if some pools failed to make forward progress for a while where
585082607adcSTejun Heo  * forward progress is defined as the first item on ->worklist changing.
585182607adcSTejun Heo  *
585282607adcSTejun Heo  * This mechanism is controlled through the kernel parameter
585382607adcSTejun Heo  * "workqueue.watchdog_thresh" which can be updated at runtime through the
585482607adcSTejun Heo  * corresponding sysfs parameter file.
585582607adcSTejun Heo  */
585682607adcSTejun Heo #ifdef CONFIG_WQ_WATCHDOG
585782607adcSTejun Heo 
585882607adcSTejun Heo static unsigned long wq_watchdog_thresh = 30;
58595cd79d6aSKees Cook static struct timer_list wq_watchdog_timer;
586082607adcSTejun Heo 
586182607adcSTejun Heo static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
586282607adcSTejun Heo static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
586382607adcSTejun Heo 
586482607adcSTejun Heo static void wq_watchdog_reset_touched(void)
586582607adcSTejun Heo {
586682607adcSTejun Heo 	int cpu;
586782607adcSTejun Heo 
586882607adcSTejun Heo 	wq_watchdog_touched = jiffies;
586982607adcSTejun Heo 	for_each_possible_cpu(cpu)
587082607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
587182607adcSTejun Heo }
587282607adcSTejun Heo 
58735cd79d6aSKees Cook static void wq_watchdog_timer_fn(struct timer_list *unused)
587482607adcSTejun Heo {
587582607adcSTejun Heo 	unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
587682607adcSTejun Heo 	bool lockup_detected = false;
5877940d71c6SSergey Senozhatsky 	unsigned long now = jiffies;
587882607adcSTejun Heo 	struct worker_pool *pool;
587982607adcSTejun Heo 	int pi;
588082607adcSTejun Heo 
588182607adcSTejun Heo 	if (!thresh)
588282607adcSTejun Heo 		return;
588382607adcSTejun Heo 
588482607adcSTejun Heo 	rcu_read_lock();
588582607adcSTejun Heo 
588682607adcSTejun Heo 	for_each_pool(pool, pi) {
588782607adcSTejun Heo 		unsigned long pool_ts, touched, ts;
588882607adcSTejun Heo 
588982607adcSTejun Heo 		if (list_empty(&pool->worklist))
589082607adcSTejun Heo 			continue;
589182607adcSTejun Heo 
5892940d71c6SSergey Senozhatsky 		/*
5893940d71c6SSergey Senozhatsky 		 * If a virtual machine is stopped by the host it can look to
5894940d71c6SSergey Senozhatsky 		 * the watchdog like a stall.
5895940d71c6SSergey Senozhatsky 		 */
5896940d71c6SSergey Senozhatsky 		kvm_check_and_clear_guest_paused();
5897940d71c6SSergey Senozhatsky 
589882607adcSTejun Heo 		/* get the latest of pool and touched timestamps */
589989e28ce6SWang Qing 		if (pool->cpu >= 0)
590089e28ce6SWang Qing 			touched = READ_ONCE(per_cpu(wq_watchdog_touched_cpu, pool->cpu));
590189e28ce6SWang Qing 		else
590282607adcSTejun Heo 			touched = READ_ONCE(wq_watchdog_touched);
590389e28ce6SWang Qing 		pool_ts = READ_ONCE(pool->watchdog_ts);
590482607adcSTejun Heo 
590582607adcSTejun Heo 		if (time_after(pool_ts, touched))
590682607adcSTejun Heo 			ts = pool_ts;
590782607adcSTejun Heo 		else
590882607adcSTejun Heo 			ts = touched;
590982607adcSTejun Heo 
591082607adcSTejun Heo 		/* did we stall? */
5911940d71c6SSergey Senozhatsky 		if (time_after(now, ts + thresh)) {
591282607adcSTejun Heo 			lockup_detected = true;
591382607adcSTejun Heo 			pr_emerg("BUG: workqueue lockup - pool");
591482607adcSTejun Heo 			pr_cont_pool_info(pool);
591582607adcSTejun Heo 			pr_cont(" stuck for %us!\n",
5916940d71c6SSergey Senozhatsky 				jiffies_to_msecs(now - pool_ts) / 1000);
591782607adcSTejun Heo 		}
591882607adcSTejun Heo 	}
591982607adcSTejun Heo 
592082607adcSTejun Heo 	rcu_read_unlock();
592182607adcSTejun Heo 
592282607adcSTejun Heo 	if (lockup_detected)
592355df0933SImran Khan 		show_all_workqueues();
592482607adcSTejun Heo 
592582607adcSTejun Heo 	wq_watchdog_reset_touched();
592682607adcSTejun Heo 	mod_timer(&wq_watchdog_timer, jiffies + thresh);
592782607adcSTejun Heo }
592882607adcSTejun Heo 
5929cb9d7fd5SVincent Whitchurch notrace void wq_watchdog_touch(int cpu)
593082607adcSTejun Heo {
593182607adcSTejun Heo 	if (cpu >= 0)
593282607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
593389e28ce6SWang Qing 
593482607adcSTejun Heo 	wq_watchdog_touched = jiffies;
593582607adcSTejun Heo }
593682607adcSTejun Heo 
593782607adcSTejun Heo static void wq_watchdog_set_thresh(unsigned long thresh)
593882607adcSTejun Heo {
593982607adcSTejun Heo 	wq_watchdog_thresh = 0;
594082607adcSTejun Heo 	del_timer_sync(&wq_watchdog_timer);
594182607adcSTejun Heo 
594282607adcSTejun Heo 	if (thresh) {
594382607adcSTejun Heo 		wq_watchdog_thresh = thresh;
594482607adcSTejun Heo 		wq_watchdog_reset_touched();
594582607adcSTejun Heo 		mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
594682607adcSTejun Heo 	}
594782607adcSTejun Heo }
594882607adcSTejun Heo 
594982607adcSTejun Heo static int wq_watchdog_param_set_thresh(const char *val,
595082607adcSTejun Heo 					const struct kernel_param *kp)
595182607adcSTejun Heo {
595282607adcSTejun Heo 	unsigned long thresh;
595382607adcSTejun Heo 	int ret;
595482607adcSTejun Heo 
595582607adcSTejun Heo 	ret = kstrtoul(val, 0, &thresh);
595682607adcSTejun Heo 	if (ret)
595782607adcSTejun Heo 		return ret;
595882607adcSTejun Heo 
595982607adcSTejun Heo 	if (system_wq)
596082607adcSTejun Heo 		wq_watchdog_set_thresh(thresh);
596182607adcSTejun Heo 	else
596282607adcSTejun Heo 		wq_watchdog_thresh = thresh;
596382607adcSTejun Heo 
596482607adcSTejun Heo 	return 0;
596582607adcSTejun Heo }
596682607adcSTejun Heo 
596782607adcSTejun Heo static const struct kernel_param_ops wq_watchdog_thresh_ops = {
596882607adcSTejun Heo 	.set	= wq_watchdog_param_set_thresh,
596982607adcSTejun Heo 	.get	= param_get_ulong,
597082607adcSTejun Heo };
597182607adcSTejun Heo 
597282607adcSTejun Heo module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
597382607adcSTejun Heo 		0644);
597482607adcSTejun Heo 
597582607adcSTejun Heo static void wq_watchdog_init(void)
597682607adcSTejun Heo {
59775cd79d6aSKees Cook 	timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
597882607adcSTejun Heo 	wq_watchdog_set_thresh(wq_watchdog_thresh);
597982607adcSTejun Heo }
598082607adcSTejun Heo 
598182607adcSTejun Heo #else	/* CONFIG_WQ_WATCHDOG */
598282607adcSTejun Heo 
598382607adcSTejun Heo static inline void wq_watchdog_init(void) { }
598482607adcSTejun Heo 
598582607adcSTejun Heo #endif	/* CONFIG_WQ_WATCHDOG */
598682607adcSTejun Heo 
5987bce90380STejun Heo static void __init wq_numa_init(void)
5988bce90380STejun Heo {
5989bce90380STejun Heo 	cpumask_var_t *tbl;
5990bce90380STejun Heo 	int node, cpu;
5991bce90380STejun Heo 
5992bce90380STejun Heo 	if (num_possible_nodes() <= 1)
5993bce90380STejun Heo 		return;
5994bce90380STejun Heo 
5995d55262c4STejun Heo 	if (wq_disable_numa) {
5996d55262c4STejun Heo 		pr_info("workqueue: NUMA affinity support disabled\n");
5997d55262c4STejun Heo 		return;
5998d55262c4STejun Heo 	}
5999d55262c4STejun Heo 
6000f728c4a9SZhen Lei 	for_each_possible_cpu(cpu) {
6001f728c4a9SZhen Lei 		if (WARN_ON(cpu_to_node(cpu) == NUMA_NO_NODE)) {
6002f728c4a9SZhen Lei 			pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
6003f728c4a9SZhen Lei 			return;
6004f728c4a9SZhen Lei 		}
6005f728c4a9SZhen Lei 	}
6006f728c4a9SZhen Lei 
6007be69d00dSThomas Gleixner 	wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs();
60084c16bd32STejun Heo 	BUG_ON(!wq_update_unbound_numa_attrs_buf);
60094c16bd32STejun Heo 
6010bce90380STejun Heo 	/*
6011bce90380STejun Heo 	 * We want masks of possible CPUs of each node which isn't readily
6012bce90380STejun Heo 	 * available.  Build one from cpu_to_node() which should have been
6013bce90380STejun Heo 	 * fully initialized by now.
6014bce90380STejun Heo 	 */
60156396bb22SKees Cook 	tbl = kcalloc(nr_node_ids, sizeof(tbl[0]), GFP_KERNEL);
6016bce90380STejun Heo 	BUG_ON(!tbl);
6017bce90380STejun Heo 
6018bce90380STejun Heo 	for_each_node(node)
60195a6024f1SYasuaki Ishimatsu 		BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
60201be0c25dSTejun Heo 				node_online(node) ? node : NUMA_NO_NODE));
6021bce90380STejun Heo 
6022bce90380STejun Heo 	for_each_possible_cpu(cpu) {
6023bce90380STejun Heo 		node = cpu_to_node(cpu);
6024bce90380STejun Heo 		cpumask_set_cpu(cpu, tbl[node]);
6025bce90380STejun Heo 	}
6026bce90380STejun Heo 
6027bce90380STejun Heo 	wq_numa_possible_cpumask = tbl;
6028bce90380STejun Heo 	wq_numa_enabled = true;
6029bce90380STejun Heo }
6030bce90380STejun Heo 
60313347fa09STejun Heo /**
60323347fa09STejun Heo  * workqueue_init_early - early init for workqueue subsystem
60333347fa09STejun Heo  *
60343347fa09STejun Heo  * This is the first half of two-staged workqueue subsystem initialization
60353347fa09STejun Heo  * and invoked as soon as the bare basics - memory allocation, cpumasks and
60363347fa09STejun Heo  * idr are up.  It sets up all the data structures and system workqueues
60373347fa09STejun Heo  * and allows early boot code to create workqueues and queue/cancel work
60383347fa09STejun Heo  * items.  Actual work item execution starts only after kthreads can be
60393347fa09STejun Heo  * created and scheduled right before early initcalls.
60403347fa09STejun Heo  */
60412333e829SYu Chen void __init workqueue_init_early(void)
60421da177e4SLinus Torvalds {
60437a4e344cSTejun Heo 	int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
60447a4e344cSTejun Heo 	int i, cpu;
6045c34056a3STejun Heo 
604610cdb157SLai Jiangshan 	BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
6047e904e6c2STejun Heo 
6048b05a7928SFrederic Weisbecker 	BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
604904d4e665SFrederic Weisbecker 	cpumask_copy(wq_unbound_cpumask, housekeeping_cpumask(HK_TYPE_WQ));
605004d4e665SFrederic Weisbecker 	cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, housekeeping_cpumask(HK_TYPE_DOMAIN));
6051b05a7928SFrederic Weisbecker 
6052e904e6c2STejun Heo 	pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
6053e904e6c2STejun Heo 
6054706026c2STejun Heo 	/* initialize CPU pools */
605529c91e99STejun Heo 	for_each_possible_cpu(cpu) {
60564ce62e9eSTejun Heo 		struct worker_pool *pool;
60578b03ae3cSTejun Heo 
60587a4e344cSTejun Heo 		i = 0;
6059f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
60607a4e344cSTejun Heo 			BUG_ON(init_worker_pool(pool));
6061ec22ca5eSTejun Heo 			pool->cpu = cpu;
60627a4e344cSTejun Heo 			cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
60637a4e344cSTejun Heo 			pool->attrs->nice = std_nice[i++];
6064f3f90ad4STejun Heo 			pool->node = cpu_to_node(cpu);
60657a4e344cSTejun Heo 
60669daf9e67STejun Heo 			/* alloc pool ID */
606768e13a67SLai Jiangshan 			mutex_lock(&wq_pool_mutex);
60689daf9e67STejun Heo 			BUG_ON(worker_pool_assign_id(pool));
606968e13a67SLai Jiangshan 			mutex_unlock(&wq_pool_mutex);
60704ce62e9eSTejun Heo 		}
60718b03ae3cSTejun Heo 	}
60728b03ae3cSTejun Heo 
60738a2b7538STejun Heo 	/* create default unbound and ordered wq attrs */
607429c91e99STejun Heo 	for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
607529c91e99STejun Heo 		struct workqueue_attrs *attrs;
607629c91e99STejun Heo 
6077be69d00dSThomas Gleixner 		BUG_ON(!(attrs = alloc_workqueue_attrs()));
607829c91e99STejun Heo 		attrs->nice = std_nice[i];
607929c91e99STejun Heo 		unbound_std_wq_attrs[i] = attrs;
60808a2b7538STejun Heo 
60818a2b7538STejun Heo 		/*
60828a2b7538STejun Heo 		 * An ordered wq should have only one pwq as ordering is
60838a2b7538STejun Heo 		 * guaranteed by max_active which is enforced by pwqs.
60848a2b7538STejun Heo 		 * Turn off NUMA so that dfl_pwq is used for all nodes.
60858a2b7538STejun Heo 		 */
6086be69d00dSThomas Gleixner 		BUG_ON(!(attrs = alloc_workqueue_attrs()));
60878a2b7538STejun Heo 		attrs->nice = std_nice[i];
60888a2b7538STejun Heo 		attrs->no_numa = true;
60898a2b7538STejun Heo 		ordered_wq_attrs[i] = attrs;
609029c91e99STejun Heo 	}
609129c91e99STejun Heo 
6092d320c038STejun Heo 	system_wq = alloc_workqueue("events", 0, 0);
60931aabe902SJoonsoo Kim 	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
6094d320c038STejun Heo 	system_long_wq = alloc_workqueue("events_long", 0, 0);
6095f3421797STejun Heo 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
6096f3421797STejun Heo 					    WQ_UNBOUND_MAX_ACTIVE);
609724d51addSTejun Heo 	system_freezable_wq = alloc_workqueue("events_freezable",
609824d51addSTejun Heo 					      WQ_FREEZABLE, 0);
60990668106cSViresh Kumar 	system_power_efficient_wq = alloc_workqueue("events_power_efficient",
61000668106cSViresh Kumar 					      WQ_POWER_EFFICIENT, 0);
61010668106cSViresh Kumar 	system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
61020668106cSViresh Kumar 					      WQ_FREEZABLE | WQ_POWER_EFFICIENT,
61030668106cSViresh Kumar 					      0);
61041aabe902SJoonsoo Kim 	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
61050668106cSViresh Kumar 	       !system_unbound_wq || !system_freezable_wq ||
61060668106cSViresh Kumar 	       !system_power_efficient_wq ||
61070668106cSViresh Kumar 	       !system_freezable_power_efficient_wq);
61083347fa09STejun Heo }
61093347fa09STejun Heo 
61103347fa09STejun Heo /**
61113347fa09STejun Heo  * workqueue_init - bring workqueue subsystem fully online
61123347fa09STejun Heo  *
61133347fa09STejun Heo  * This is the latter half of two-staged workqueue subsystem initialization
61143347fa09STejun Heo  * and invoked as soon as kthreads can be created and scheduled.
61153347fa09STejun Heo  * Workqueues have been created and work items queued on them, but there
61163347fa09STejun Heo  * are no kworkers executing the work items yet.  Populate the worker pools
61173347fa09STejun Heo  * with the initial workers and enable future kworker creations.
61183347fa09STejun Heo  */
61192333e829SYu Chen void __init workqueue_init(void)
61203347fa09STejun Heo {
61212186d9f9STejun Heo 	struct workqueue_struct *wq;
61223347fa09STejun Heo 	struct worker_pool *pool;
61233347fa09STejun Heo 	int cpu, bkt;
61243347fa09STejun Heo 
61252186d9f9STejun Heo 	/*
61262186d9f9STejun Heo 	 * It'd be simpler to initialize NUMA in workqueue_init_early() but
61272186d9f9STejun Heo 	 * CPU to node mapping may not be available that early on some
61282186d9f9STejun Heo 	 * archs such as power and arm64.  As per-cpu pools created
61292186d9f9STejun Heo 	 * previously could be missing node hint and unbound pools NUMA
61302186d9f9STejun Heo 	 * affinity, fix them up.
613140c17f75STejun Heo 	 *
613240c17f75STejun Heo 	 * Also, while iterating workqueues, create rescuers if requested.
61332186d9f9STejun Heo 	 */
61342186d9f9STejun Heo 	wq_numa_init();
61352186d9f9STejun Heo 
61362186d9f9STejun Heo 	mutex_lock(&wq_pool_mutex);
61372186d9f9STejun Heo 
61382186d9f9STejun Heo 	for_each_possible_cpu(cpu) {
61392186d9f9STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
61402186d9f9STejun Heo 			pool->node = cpu_to_node(cpu);
61412186d9f9STejun Heo 		}
61422186d9f9STejun Heo 	}
61432186d9f9STejun Heo 
614440c17f75STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
61452186d9f9STejun Heo 		wq_update_unbound_numa(wq, smp_processor_id(), true);
614640c17f75STejun Heo 		WARN(init_rescuer(wq),
614740c17f75STejun Heo 		     "workqueue: failed to create early rescuer for %s",
614840c17f75STejun Heo 		     wq->name);
614940c17f75STejun Heo 	}
61502186d9f9STejun Heo 
61512186d9f9STejun Heo 	mutex_unlock(&wq_pool_mutex);
61522186d9f9STejun Heo 
61533347fa09STejun Heo 	/* create the initial workers */
61543347fa09STejun Heo 	for_each_online_cpu(cpu) {
61553347fa09STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
61563347fa09STejun Heo 			pool->flags &= ~POOL_DISASSOCIATED;
61573347fa09STejun Heo 			BUG_ON(!create_worker(pool));
61583347fa09STejun Heo 		}
61593347fa09STejun Heo 	}
61603347fa09STejun Heo 
61613347fa09STejun Heo 	hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
61623347fa09STejun Heo 		BUG_ON(!create_worker(pool));
61633347fa09STejun Heo 
61643347fa09STejun Heo 	wq_online = true;
616582607adcSTejun Heo 	wq_watchdog_init();
61661da177e4SLinus Torvalds }
6167c4f135d6STetsuo Handa 
6168c4f135d6STetsuo Handa /*
6169c4f135d6STetsuo Handa  * Despite the naming, this is a no-op function which is here only for avoiding
6170c4f135d6STetsuo Handa  * link error. Since compile-time warning may fail to catch, we will need to
6171c4f135d6STetsuo Handa  * emit run-time warning from __flush_workqueue().
6172c4f135d6STetsuo Handa  */
6173c4f135d6STetsuo Handa void __warn_flushing_systemwide_wq(void) { }
6174c4f135d6STetsuo Handa EXPORT_SYMBOL(__warn_flushing_systemwide_wq);
6175