xref: /linux-6.15/kernel/workqueue.c (revision c5404d4e)
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>
52cd2440d6SPetr Mladek #include <linux/sched/debug.h>
5362635ea8SSergey Senozhatsky #include <linux/nmi.h>
54940d71c6SSergey Senozhatsky #include <linux/kvm_para.h>
55aa6fde93STejun Heo #include <linux/delay.h>
56e22bee78STejun Heo 
57ea138446STejun Heo #include "workqueue_internal.h"
581da177e4SLinus Torvalds 
59e563d0a7STejun Heo enum worker_pool_flags {
60bc2ae0f5STejun Heo 	/*
6124647570STejun Heo 	 * worker_pool flags
62bc2ae0f5STejun Heo 	 *
6324647570STejun Heo 	 * A bound pool is either associated or disassociated with its CPU.
64bc2ae0f5STejun Heo 	 * While associated (!DISASSOCIATED), all workers are bound to the
65bc2ae0f5STejun Heo 	 * CPU and none has %WORKER_UNBOUND set and concurrency management
66bc2ae0f5STejun Heo 	 * is in effect.
67bc2ae0f5STejun Heo 	 *
68bc2ae0f5STejun Heo 	 * While DISASSOCIATED, the cpu may be offline and all workers have
69bc2ae0f5STejun Heo 	 * %WORKER_UNBOUND set and concurrency management disabled, and may
7024647570STejun Heo 	 * be executing on any CPU.  The pool behaves as an unbound one.
71bc2ae0f5STejun Heo 	 *
72bc3a1afcSTejun Heo 	 * Note that DISASSOCIATED should be flipped only while holding
731258fae7STejun Heo 	 * wq_pool_attach_mutex to avoid changing binding state while
744736cbf7SLai Jiangshan 	 * worker_attach_to_pool() is in progress.
75bc2ae0f5STejun Heo 	 */
76692b4825STejun Heo 	POOL_MANAGER_ACTIVE	= 1 << 0,	/* being managed */
7724647570STejun Heo 	POOL_DISASSOCIATED	= 1 << 2,	/* cpu can't serve workers */
78e563d0a7STejun Heo };
79db7bccf4STejun Heo 
80e563d0a7STejun Heo enum worker_flags {
81c8e55f36STejun Heo 	/* worker flags */
82c8e55f36STejun Heo 	WORKER_DIE		= 1 << 1,	/* die die die */
83c8e55f36STejun Heo 	WORKER_IDLE		= 1 << 2,	/* is idle */
84e22bee78STejun Heo 	WORKER_PREP		= 1 << 3,	/* preparing to run works */
85fb0e7bebSTejun Heo 	WORKER_CPU_INTENSIVE	= 1 << 6,	/* cpu intensive */
86f3421797STejun Heo 	WORKER_UNBOUND		= 1 << 7,	/* worker is unbound */
87a9ab775bSTejun Heo 	WORKER_REBOUND		= 1 << 8,	/* worker was rebound */
88e22bee78STejun Heo 
89a9ab775bSTejun Heo 	WORKER_NOT_RUNNING	= WORKER_PREP | WORKER_CPU_INTENSIVE |
90a9ab775bSTejun Heo 				  WORKER_UNBOUND | WORKER_REBOUND,
91e563d0a7STejun Heo };
92db7bccf4STejun Heo 
93e563d0a7STejun Heo enum wq_internal_consts {
94e34cdddbSTejun Heo 	NR_STD_WORKER_POOLS	= 2,		/* # standard pools per cpu */
954ce62e9eSTejun Heo 
9629c91e99STejun Heo 	UNBOUND_POOL_HASH_ORDER	= 6,		/* hashed by pool->attrs */
97c8e55f36STejun Heo 	BUSY_WORKER_HASH_ORDER	= 6,		/* 64 pointers */
98db7bccf4STejun Heo 
99e22bee78STejun Heo 	MAX_IDLE_WORKERS_RATIO	= 4,		/* 1/4 of busy can be idle */
100e22bee78STejun Heo 	IDLE_WORKER_TIMEOUT	= 300 * HZ,	/* keep idle ones for 5 mins */
101e22bee78STejun Heo 
1023233cdbdSTejun Heo 	MAYDAY_INITIAL_TIMEOUT  = HZ / 100 >= 2 ? HZ / 100 : 2,
1033233cdbdSTejun Heo 						/* call for help after 10ms
1043233cdbdSTejun Heo 						   (min two ticks) */
105e22bee78STejun Heo 	MAYDAY_INTERVAL		= HZ / 10,	/* and then every 100ms */
106e22bee78STejun Heo 	CREATE_COOLDOWN		= HZ,		/* time to breath after fail */
1071da177e4SLinus Torvalds 
1081da177e4SLinus Torvalds 	/*
109e22bee78STejun Heo 	 * Rescue workers are used only on emergencies and shared by
1108698a745SDongsheng Yang 	 * all cpus.  Give MIN_NICE.
111e22bee78STejun Heo 	 */
1128698a745SDongsheng Yang 	RESCUER_NICE_LEVEL	= MIN_NICE,
1138698a745SDongsheng Yang 	HIGHPRI_NICE_LEVEL	= MIN_NICE,
114ecf6881fSTejun Heo 
11531c89007SAudra Mitchell 	WQ_NAME_LEN		= 32,
116c8e55f36STejun Heo };
117c8e55f36STejun Heo 
1181da177e4SLinus Torvalds /*
1194690c4abSTejun Heo  * Structure fields follow one of the following exclusion rules.
1204690c4abSTejun Heo  *
121e41e704bSTejun Heo  * I: Modifiable by initialization/destruction paths and read-only for
122e41e704bSTejun Heo  *    everyone else.
1234690c4abSTejun Heo  *
124e22bee78STejun Heo  * P: Preemption protected.  Disabling preemption is enough and should
125e22bee78STejun Heo  *    only be modified and accessed from the local cpu.
126e22bee78STejun Heo  *
127d565ed63STejun Heo  * L: pool->lock protected.  Access with pool->lock held.
1284690c4abSTejun Heo  *
129bdf8b9bfSTejun Heo  * K: Only modified by worker while holding pool->lock. Can be safely read by
130bdf8b9bfSTejun Heo  *    self, while holding pool->lock or from IRQ context if %current is the
131bdf8b9bfSTejun Heo  *    kworker.
132bdf8b9bfSTejun Heo  *
133bdf8b9bfSTejun Heo  * S: Only modified by worker self.
134bdf8b9bfSTejun Heo  *
1351258fae7STejun Heo  * A: wq_pool_attach_mutex protected.
136822d8405STejun Heo  *
13768e13a67SLai Jiangshan  * PL: wq_pool_mutex protected.
13876af4d93STejun Heo  *
13924acfb71SThomas Gleixner  * PR: wq_pool_mutex protected for writes.  RCU protected for reads.
1405bcab335STejun Heo  *
1415b95e1afSLai Jiangshan  * PW: wq_pool_mutex and wq->mutex protected for writes.  Either for reads.
1425b95e1afSLai Jiangshan  *
1435b95e1afSLai Jiangshan  * PWR: wq_pool_mutex and wq->mutex protected for writes.  Either or
14424acfb71SThomas Gleixner  *      RCU for reads.
1455b95e1afSLai Jiangshan  *
1463c25a55dSLai Jiangshan  * WQ: wq->mutex protected.
1473c25a55dSLai Jiangshan  *
14824acfb71SThomas Gleixner  * WR: wq->mutex protected for writes.  RCU protected for reads.
1492e109a28STejun Heo  *
150a045a272STejun Heo  * WO: wq->mutex protected for writes. Updated with WRITE_ONCE() and can be read
151a045a272STejun Heo  *     with READ_ONCE() without locking.
152a045a272STejun Heo  *
1532e109a28STejun Heo  * MD: wq_mayday_lock protected.
154cd2440d6SPetr Mladek  *
155cd2440d6SPetr Mladek  * WD: Used internally by the watchdog.
1564690c4abSTejun Heo  */
1574690c4abSTejun Heo 
1582eaebdb3STejun Heo /* struct worker is defined in workqueue_internal.h */
159c34056a3STejun Heo 
160bd7bdd43STejun Heo struct worker_pool {
161a9b8a985SSebastian Andrzej Siewior 	raw_spinlock_t		lock;		/* the pool lock */
162d84ff051STejun Heo 	int			cpu;		/* I: the associated cpu */
163f3f90ad4STejun Heo 	int			node;		/* I: the associated node ID */
1649daf9e67STejun Heo 	int			id;		/* I: pool ID */
165bc8b50c2STejun Heo 	unsigned int		flags;		/* L: flags */
166bd7bdd43STejun Heo 
16782607adcSTejun Heo 	unsigned long		watchdog_ts;	/* L: watchdog timestamp */
168cd2440d6SPetr Mladek 	bool			cpu_stall;	/* WD: stalled cpu bound pool */
16982607adcSTejun Heo 
170bc35f7efSLai Jiangshan 	/*
171bc35f7efSLai Jiangshan 	 * The counter is incremented in a process context on the associated CPU
172bc35f7efSLai Jiangshan 	 * w/ preemption disabled, and decremented or reset in the same context
173bc35f7efSLai Jiangshan 	 * but w/ pool->lock held. The readers grab pool->lock and are
174bc35f7efSLai Jiangshan 	 * guaranteed to see if the counter reached zero.
175bc35f7efSLai Jiangshan 	 */
176bc35f7efSLai Jiangshan 	int			nr_running;
17784f91c62SLai Jiangshan 
178bd7bdd43STejun Heo 	struct list_head	worklist;	/* L: list of pending works */
179ea1abd61SLai Jiangshan 
1805826cc8fSLai Jiangshan 	int			nr_workers;	/* L: total number of workers */
1815826cc8fSLai Jiangshan 	int			nr_idle;	/* L: currently idle workers */
182bd7bdd43STejun Heo 
1832c1f1a91SLai Jiangshan 	struct list_head	idle_list;	/* L: list of idle workers */
184bd7bdd43STejun Heo 	struct timer_list	idle_timer;	/* L: worker idle timeout */
1853f959aa3SValentin Schneider 	struct work_struct      idle_cull_work; /* L: worker idle cleanup */
1863f959aa3SValentin Schneider 
187bd7bdd43STejun Heo 	struct timer_list	mayday_timer;	  /* L: SOS timer for workers */
188bd7bdd43STejun Heo 
189c5aa87bbSTejun Heo 	/* a workers is either on busy_hash or idle_list, or the manager */
190c9e7cf27STejun Heo 	DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
191c9e7cf27STejun Heo 						/* L: hash of busy workers */
192c9e7cf27STejun Heo 
1932607d7a6STejun Heo 	struct worker		*manager;	/* L: purely informational */
19492f9c5c4SLai Jiangshan 	struct list_head	workers;	/* A: attached workers */
195e02b9312SValentin Schneider 	struct list_head        dying_workers;  /* A: workers about to die */
19660f5a4bcSLai Jiangshan 	struct completion	*detach_completion; /* all workers detached */
197e19e397aSTejun Heo 
1987cda9aaeSLai Jiangshan 	struct ida		worker_ida;	/* worker IDs for task name */
199e19e397aSTejun Heo 
2007a4e344cSTejun Heo 	struct workqueue_attrs	*attrs;		/* I: worker attributes */
20168e13a67SLai Jiangshan 	struct hlist_node	hash_node;	/* PL: unbound_pool_hash node */
20268e13a67SLai Jiangshan 	int			refcnt;		/* PL: refcnt for unbound pools */
2037a4e344cSTejun Heo 
204e19e397aSTejun Heo 	/*
20524acfb71SThomas Gleixner 	 * Destruction of pool is RCU protected to allow dereferences
20629c91e99STejun Heo 	 * from get_work_pool().
20729c91e99STejun Heo 	 */
20829c91e99STejun Heo 	struct rcu_head		rcu;
20984f91c62SLai Jiangshan };
2108b03ae3cSTejun Heo 
2118b03ae3cSTejun Heo /*
212725e8ec5STejun Heo  * Per-pool_workqueue statistics. These can be monitored using
213725e8ec5STejun Heo  * tools/workqueue/wq_monitor.py.
214725e8ec5STejun Heo  */
215725e8ec5STejun Heo enum pool_workqueue_stats {
216725e8ec5STejun Heo 	PWQ_STAT_STARTED,	/* work items started execution */
217725e8ec5STejun Heo 	PWQ_STAT_COMPLETED,	/* work items completed execution */
2188a1dd1e5STejun Heo 	PWQ_STAT_CPU_TIME,	/* total CPU time consumed */
219616db877STejun Heo 	PWQ_STAT_CPU_INTENSIVE,	/* wq_cpu_intensive_thresh_us violations */
220725e8ec5STejun Heo 	PWQ_STAT_CM_WAKEUP,	/* concurrency-management worker wakeups */
2218639ecebSTejun Heo 	PWQ_STAT_REPATRIATED,	/* unbound workers brought back into scope */
222725e8ec5STejun Heo 	PWQ_STAT_MAYDAY,	/* maydays to rescuer */
223725e8ec5STejun Heo 	PWQ_STAT_RESCUED,	/* linked work items executed by rescuer */
224725e8ec5STejun Heo 
225725e8ec5STejun Heo 	PWQ_NR_STATS,
226725e8ec5STejun Heo };
227725e8ec5STejun Heo 
228725e8ec5STejun Heo /*
229112202d9STejun Heo  * The per-pool workqueue.  While queued, the lower WORK_STRUCT_FLAG_BITS
230112202d9STejun Heo  * of work_struct->data are used for flags and the remaining high bits
231112202d9STejun Heo  * point to the pwq; thus, pwqs need to be aligned at two's power of the
232112202d9STejun Heo  * number of flag bits.
2331da177e4SLinus Torvalds  */
234112202d9STejun Heo struct pool_workqueue {
235bd7bdd43STejun Heo 	struct worker_pool	*pool;		/* I: the associated pool */
2364690c4abSTejun Heo 	struct workqueue_struct *wq;		/* I: the owning workqueue */
23773f53c4aSTejun Heo 	int			work_color;	/* L: current color */
23873f53c4aSTejun Heo 	int			flush_color;	/* L: flushing color */
2398864b4e5STejun Heo 	int			refcnt;		/* L: reference count */
24073f53c4aSTejun Heo 	int			nr_in_flight[WORK_NR_COLORS];
24173f53c4aSTejun Heo 						/* L: nr of in_flight works */
242018f3a13SLai Jiangshan 
243018f3a13SLai Jiangshan 	/*
244018f3a13SLai Jiangshan 	 * nr_active management and WORK_STRUCT_INACTIVE:
245018f3a13SLai Jiangshan 	 *
246018f3a13SLai Jiangshan 	 * When pwq->nr_active >= max_active, new work item is queued to
247018f3a13SLai Jiangshan 	 * pwq->inactive_works instead of pool->worklist and marked with
248018f3a13SLai Jiangshan 	 * WORK_STRUCT_INACTIVE.
249018f3a13SLai Jiangshan 	 *
250018f3a13SLai Jiangshan 	 * All work items marked with WORK_STRUCT_INACTIVE do not participate
251018f3a13SLai Jiangshan 	 * in pwq->nr_active and all work items in pwq->inactive_works are
252018f3a13SLai Jiangshan 	 * marked with WORK_STRUCT_INACTIVE.  But not all WORK_STRUCT_INACTIVE
253018f3a13SLai Jiangshan 	 * work items are in pwq->inactive_works.  Some of them are ready to
254018f3a13SLai Jiangshan 	 * run in pool->worklist or worker->scheduled.  Those work itmes are
255018f3a13SLai Jiangshan 	 * only struct wq_barrier which is used for flush_work() and should
256018f3a13SLai Jiangshan 	 * not participate in pwq->nr_active.  For non-barrier work item, it
257018f3a13SLai Jiangshan 	 * is marked with WORK_STRUCT_INACTIVE iff it is in pwq->inactive_works.
258018f3a13SLai Jiangshan 	 */
2591e19ffc6STejun Heo 	int			nr_active;	/* L: nr of active works */
260f97a4a1aSLai Jiangshan 	struct list_head	inactive_works;	/* L: inactive works */
2613c25a55dSLai Jiangshan 	struct list_head	pwqs_node;	/* WR: node on wq->pwqs */
2622e109a28STejun Heo 	struct list_head	mayday_node;	/* MD: node on wq->maydays */
2638864b4e5STejun Heo 
264725e8ec5STejun Heo 	u64			stats[PWQ_NR_STATS];
265725e8ec5STejun Heo 
2668864b4e5STejun Heo 	/*
267967b494eSTejun Heo 	 * Release of unbound pwq is punted to a kthread_worker. See put_pwq()
268687a9aa5STejun Heo 	 * and pwq_release_workfn() for details. pool_workqueue itself is also
269687a9aa5STejun Heo 	 * RCU protected so that the first pwq can be determined without
270967b494eSTejun Heo 	 * grabbing wq->mutex.
2718864b4e5STejun Heo 	 */
272687a9aa5STejun Heo 	struct kthread_work	release_work;
2738864b4e5STejun Heo 	struct rcu_head		rcu;
274e904e6c2STejun Heo } __aligned(1 << WORK_STRUCT_FLAG_BITS);
2751da177e4SLinus Torvalds 
2761da177e4SLinus Torvalds /*
27773f53c4aSTejun Heo  * Structure used to wait for workqueue flush.
27873f53c4aSTejun Heo  */
27973f53c4aSTejun Heo struct wq_flusher {
2803c25a55dSLai Jiangshan 	struct list_head	list;		/* WQ: list of flushers */
2813c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: flush color waiting for */
28273f53c4aSTejun Heo 	struct completion	done;		/* flush completion */
28373f53c4aSTejun Heo };
2841da177e4SLinus Torvalds 
285226223abSTejun Heo struct wq_device;
286226223abSTejun Heo 
28773f53c4aSTejun Heo /*
288c5aa87bbSTejun Heo  * The externally visible workqueue.  It relays the issued work items to
289c5aa87bbSTejun Heo  * the appropriate worker_pool through its pool_workqueues.
2901da177e4SLinus Torvalds  */
2911da177e4SLinus Torvalds struct workqueue_struct {
2923c25a55dSLai Jiangshan 	struct list_head	pwqs;		/* WR: all pwqs of this wq */
293e2dca7adSTejun Heo 	struct list_head	list;		/* PR: list of all workqueues */
29473f53c4aSTejun Heo 
2953c25a55dSLai Jiangshan 	struct mutex		mutex;		/* protects this wq */
2963c25a55dSLai Jiangshan 	int			work_color;	/* WQ: current work color */
2973c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: current flush color */
298112202d9STejun Heo 	atomic_t		nr_pwqs_to_flush; /* flush in progress */
2993c25a55dSLai Jiangshan 	struct wq_flusher	*first_flusher;	/* WQ: first flusher */
3003c25a55dSLai Jiangshan 	struct list_head	flusher_queue;	/* WQ: flush waiters */
3013c25a55dSLai Jiangshan 	struct list_head	flusher_overflow; /* WQ: flush overflow list */
30273f53c4aSTejun Heo 
3032e109a28STejun Heo 	struct list_head	maydays;	/* MD: pwqs requesting rescue */
30430ae2fc0STejun Heo 	struct worker		*rescuer;	/* MD: rescue worker */
305e22bee78STejun Heo 
30687fc741eSLai Jiangshan 	int			nr_drainers;	/* WQ: drain in progress */
307a045a272STejun Heo 	int			max_active;	/* WO: max active works */
308a045a272STejun Heo 	int			saved_max_active; /* WQ: saved max_active */
309226223abSTejun Heo 
3105b95e1afSLai Jiangshan 	struct workqueue_attrs	*unbound_attrs;	/* PW: only for unbound wqs */
3115b95e1afSLai Jiangshan 	struct pool_workqueue	*dfl_pwq;	/* PW: only for unbound wqs */
3126029a918STejun Heo 
313226223abSTejun Heo #ifdef CONFIG_SYSFS
314226223abSTejun Heo 	struct wq_device	*wq_dev;	/* I: for sysfs interface */
315226223abSTejun Heo #endif
3164e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
317669de8bdSBart Van Assche 	char			*lock_name;
318669de8bdSBart Van Assche 	struct lock_class_key	key;
3194e6045f1SJohannes Berg 	struct lockdep_map	lockdep_map;
3204e6045f1SJohannes Berg #endif
321ecf6881fSTejun Heo 	char			name[WQ_NAME_LEN]; /* I: workqueue name */
3222728fd2fSTejun Heo 
323e2dca7adSTejun Heo 	/*
32424acfb71SThomas Gleixner 	 * Destruction of workqueue_struct is RCU protected to allow walking
32524acfb71SThomas Gleixner 	 * the workqueues list without grabbing wq_pool_mutex.
326e2dca7adSTejun Heo 	 * This is used to dump all workqueues from sysrq.
327e2dca7adSTejun Heo 	 */
328e2dca7adSTejun Heo 	struct rcu_head		rcu;
329e2dca7adSTejun Heo 
3302728fd2fSTejun Heo 	/* hot fields used during command issue, aligned to cacheline */
3312728fd2fSTejun Heo 	unsigned int		flags ____cacheline_aligned; /* WQ: WQ_* flags */
332636b927eSTejun Heo 	struct pool_workqueue __percpu __rcu **cpu_pwq; /* I: per-cpu pwqs */
3331da177e4SLinus Torvalds };
3341da177e4SLinus Torvalds 
335e904e6c2STejun Heo static struct kmem_cache *pwq_cache;
336e904e6c2STejun Heo 
33784193c07STejun Heo /*
33884193c07STejun Heo  * Each pod type describes how CPUs should be grouped for unbound workqueues.
33984193c07STejun Heo  * See the comment above workqueue_attrs->affn_scope.
34084193c07STejun Heo  */
34184193c07STejun Heo struct wq_pod_type {
34284193c07STejun Heo 	int			nr_pods;	/* number of pods */
34384193c07STejun Heo 	cpumask_var_t		*pod_cpus;	/* pod -> cpus */
34484193c07STejun Heo 	int			*pod_node;	/* pod -> node */
34584193c07STejun Heo 	int			*cpu_pod;	/* cpu -> pod */
34684193c07STejun Heo };
34784193c07STejun Heo 
34884193c07STejun Heo static struct wq_pod_type wq_pod_types[WQ_AFFN_NR_TYPES];
349523a301eSTejun Heo static enum wq_affn_scope wq_affn_dfl = WQ_AFFN_CACHE;
35063c5484eSTejun Heo 
35163c5484eSTejun Heo static const char *wq_affn_names[WQ_AFFN_NR_TYPES] = {
352523a301eSTejun Heo 	[WQ_AFFN_DFL]			= "default",
35363c5484eSTejun Heo 	[WQ_AFFN_CPU]			= "cpu",
35463c5484eSTejun Heo 	[WQ_AFFN_SMT]			= "smt",
35563c5484eSTejun Heo 	[WQ_AFFN_CACHE]			= "cache",
35663c5484eSTejun Heo 	[WQ_AFFN_NUMA]			= "numa",
35763c5484eSTejun Heo 	[WQ_AFFN_SYSTEM]		= "system",
35863c5484eSTejun Heo };
359bce90380STejun Heo 
360616db877STejun Heo /*
361616db877STejun Heo  * Per-cpu work items which run for longer than the following threshold are
362616db877STejun Heo  * automatically considered CPU intensive and excluded from concurrency
363616db877STejun Heo  * management to prevent them from noticeably delaying other per-cpu work items.
364aa6fde93STejun Heo  * ULONG_MAX indicates that the user hasn't overridden it with a boot parameter.
365aa6fde93STejun Heo  * The actual value is initialized in wq_cpu_intensive_thresh_init().
366616db877STejun Heo  */
367aa6fde93STejun Heo static unsigned long wq_cpu_intensive_thresh_us = ULONG_MAX;
368616db877STejun Heo module_param_named(cpu_intensive_thresh_us, wq_cpu_intensive_thresh_us, ulong, 0644);
369616db877STejun Heo 
370cee22a15SViresh Kumar /* see the comment above the definition of WQ_POWER_EFFICIENT */
371552f530cSLuis R. Rodriguez static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
372cee22a15SViresh Kumar module_param_named(power_efficient, wq_power_efficient, bool, 0444);
373cee22a15SViresh Kumar 
374863b710bSTejun Heo static bool wq_online;			/* can kworkers be created yet? */
3753347fa09STejun Heo 
376fef59c9cSTejun Heo /* buf for wq_update_unbound_pod_attrs(), protected by CPU hotplug exclusion */
377fef59c9cSTejun Heo static struct workqueue_attrs *wq_update_pod_attrs_buf;
3784c16bd32STejun Heo 
37968e13a67SLai Jiangshan static DEFINE_MUTEX(wq_pool_mutex);	/* protects pools and workqueues list */
3801258fae7STejun Heo static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
381a9b8a985SSebastian Andrzej Siewior static DEFINE_RAW_SPINLOCK(wq_mayday_lock);	/* protects wq->maydays list */
382d8bb65abSSebastian Andrzej Siewior /* wait for manager to go away */
383d8bb65abSSebastian Andrzej Siewior static struct rcuwait manager_wait = __RCUWAIT_INITIALIZER(manager_wait);
3845bcab335STejun Heo 
385e2dca7adSTejun Heo static LIST_HEAD(workqueues);		/* PR: list of all workqueues */
38668e13a67SLai Jiangshan static bool workqueue_freezing;		/* PL: have wqs started freezing? */
3877d19c5ceSTejun Heo 
38899c621efSLai Jiangshan /* PL&A: allowable cpus for unbound wqs and work items */
389ef557180SMike Galbraith static cpumask_var_t wq_unbound_cpumask;
390ef557180SMike Galbraith 
391fe28f631SWaiman Long /* PL: user requested unbound cpumask via sysfs */
392fe28f631SWaiman Long static cpumask_var_t wq_requested_unbound_cpumask;
393fe28f631SWaiman Long 
394fe28f631SWaiman Long /* PL: isolated cpumask to be excluded from unbound cpumask */
395fe28f631SWaiman Long static cpumask_var_t wq_isolated_cpumask;
396fe28f631SWaiman Long 
397ace3c549Stiozhang /* for further constrain wq_unbound_cpumask by cmdline parameter*/
398ace3c549Stiozhang static struct cpumask wq_cmdline_cpumask __initdata;
399ace3c549Stiozhang 
400ef557180SMike Galbraith /* CPU where unbound work was last round robin scheduled from this CPU */
401ef557180SMike Galbraith static DEFINE_PER_CPU(int, wq_rr_cpu_last);
402b05a7928SFrederic Weisbecker 
403f303fccbSTejun Heo /*
404f303fccbSTejun Heo  * Local execution of unbound work items is no longer guaranteed.  The
405f303fccbSTejun Heo  * following always forces round-robin CPU selection on unbound work items
406f303fccbSTejun Heo  * to uncover usages which depend on it.
407f303fccbSTejun Heo  */
408f303fccbSTejun Heo #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
409f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = true;
410f303fccbSTejun Heo #else
411f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = false;
412f303fccbSTejun Heo #endif
413f303fccbSTejun Heo module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
414f303fccbSTejun Heo 
4157d19c5ceSTejun Heo /* the per-cpu worker pools */
41625528213SPeter Zijlstra static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools);
4177d19c5ceSTejun Heo 
41868e13a67SLai Jiangshan static DEFINE_IDR(worker_pool_idr);	/* PR: idr of all pools */
4197d19c5ceSTejun Heo 
42068e13a67SLai Jiangshan /* PL: hash of all unbound pools keyed by pool->attrs */
42129c91e99STejun Heo static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
42229c91e99STejun Heo 
423c5aa87bbSTejun Heo /* I: attributes used when instantiating standard unbound pools on demand */
42429c91e99STejun Heo static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
42529c91e99STejun Heo 
4268a2b7538STejun Heo /* I: attributes used when instantiating ordered pools on demand */
4278a2b7538STejun Heo static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
4288a2b7538STejun Heo 
429967b494eSTejun Heo /*
430967b494eSTejun Heo  * I: kthread_worker to release pwq's. pwq release needs to be bounced to a
431967b494eSTejun Heo  * process context while holding a pool lock. Bounce to a dedicated kthread
432967b494eSTejun Heo  * worker to avoid A-A deadlocks.
433967b494eSTejun Heo  */
43468279f9cSAlexey Dobriyan static struct kthread_worker *pwq_release_worker __ro_after_init;
435967b494eSTejun Heo 
43668279f9cSAlexey Dobriyan struct workqueue_struct *system_wq __ro_after_init;
437ad7b1f84SMarc Dionne EXPORT_SYMBOL(system_wq);
43868279f9cSAlexey Dobriyan struct workqueue_struct *system_highpri_wq __ro_after_init;
4391aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
44068279f9cSAlexey Dobriyan struct workqueue_struct *system_long_wq __ro_after_init;
441d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
44268279f9cSAlexey Dobriyan struct workqueue_struct *system_unbound_wq __ro_after_init;
443f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
44468279f9cSAlexey Dobriyan struct workqueue_struct *system_freezable_wq __ro_after_init;
44524d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
44668279f9cSAlexey Dobriyan struct workqueue_struct *system_power_efficient_wq __ro_after_init;
4470668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_power_efficient_wq);
44868279f9cSAlexey Dobriyan struct workqueue_struct *system_freezable_power_efficient_wq __ro_after_init;
4490668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
450d320c038STejun Heo 
4517d19c5ceSTejun Heo static int worker_thread(void *__worker);
4526ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
453c29eb853STejun Heo static void show_pwq(struct pool_workqueue *pwq);
45455df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool);
4557d19c5ceSTejun Heo 
45697bd2347STejun Heo #define CREATE_TRACE_POINTS
45797bd2347STejun Heo #include <trace/events/workqueue.h>
45897bd2347STejun Heo 
45968e13a67SLai Jiangshan #define assert_rcu_or_pool_mutex()					\
46024acfb71SThomas Gleixner 	RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&			\
461f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
46224acfb71SThomas Gleixner 			 "RCU or wq_pool_mutex should be held")
4635bcab335STejun Heo 
4645b95e1afSLai Jiangshan #define assert_rcu_or_wq_mutex_or_pool_mutex(wq)			\
46524acfb71SThomas Gleixner 	RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&			\
466f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq->mutex) &&		\
467f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
46824acfb71SThomas Gleixner 			 "RCU, wq->mutex or wq_pool_mutex should be held")
4695b95e1afSLai Jiangshan 
470f02ae73aSTejun Heo #define for_each_cpu_worker_pool(pool, cpu)				\
471f02ae73aSTejun Heo 	for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0];		\
472f02ae73aSTejun Heo 	     (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
4737a62c2c8STejun Heo 	     (pool)++)
4744ce62e9eSTejun Heo 
47549e3cf44STejun Heo /**
47617116969STejun Heo  * for_each_pool - iterate through all worker_pools in the system
47717116969STejun Heo  * @pool: iteration cursor
478611c92a0STejun Heo  * @pi: integer used for iteration
479fa1b54e6STejun Heo  *
48024acfb71SThomas Gleixner  * This must be called either with wq_pool_mutex held or RCU read
48168e13a67SLai Jiangshan  * locked.  If the pool needs to be used beyond the locking in effect, the
48268e13a67SLai Jiangshan  * caller is responsible for guaranteeing that the pool stays online.
483fa1b54e6STejun Heo  *
484fa1b54e6STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
485fa1b54e6STejun Heo  * ignored.
48617116969STejun Heo  */
487611c92a0STejun Heo #define for_each_pool(pool, pi)						\
488611c92a0STejun Heo 	idr_for_each_entry(&worker_pool_idr, pool, pi)			\
48968e13a67SLai Jiangshan 		if (({ assert_rcu_or_pool_mutex(); false; })) { }	\
490fa1b54e6STejun Heo 		else
49117116969STejun Heo 
49217116969STejun Heo /**
493822d8405STejun Heo  * for_each_pool_worker - iterate through all workers of a worker_pool
494822d8405STejun Heo  * @worker: iteration cursor
495822d8405STejun Heo  * @pool: worker_pool to iterate workers of
496822d8405STejun Heo  *
4971258fae7STejun Heo  * This must be called with wq_pool_attach_mutex.
498822d8405STejun Heo  *
499822d8405STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
500822d8405STejun Heo  * ignored.
501822d8405STejun Heo  */
502da028469SLai Jiangshan #define for_each_pool_worker(worker, pool)				\
503da028469SLai Jiangshan 	list_for_each_entry((worker), &(pool)->workers, node)		\
5041258fae7STejun Heo 		if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
505822d8405STejun Heo 		else
506822d8405STejun Heo 
507822d8405STejun Heo /**
50849e3cf44STejun Heo  * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
50949e3cf44STejun Heo  * @pwq: iteration cursor
51049e3cf44STejun Heo  * @wq: the target workqueue
51176af4d93STejun Heo  *
51224acfb71SThomas Gleixner  * This must be called either with wq->mutex held or RCU read locked.
513794b18bcSTejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
514794b18bcSTejun Heo  * responsible for guaranteeing that the pwq stays online.
51576af4d93STejun Heo  *
51676af4d93STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
51776af4d93STejun Heo  * ignored.
51849e3cf44STejun Heo  */
51949e3cf44STejun Heo #define for_each_pwq(pwq, wq)						\
52049e9d1a9SSebastian Andrzej Siewior 	list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node,		\
5215a644662SJoel Fernandes (Google) 				 lockdep_is_held(&(wq->mutex)))
522f3421797STejun Heo 
523dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
524dc186ad7SThomas Gleixner 
525f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr;
526dc186ad7SThomas Gleixner 
52799777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
52899777288SStanislaw Gruszka {
52999777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
53099777288SStanislaw Gruszka }
53199777288SStanislaw Gruszka 
532b9fdac7fSDu, Changbin static bool work_is_static_object(void *addr)
533b9fdac7fSDu, Changbin {
534b9fdac7fSDu, Changbin 	struct work_struct *work = addr;
535b9fdac7fSDu, Changbin 
536b9fdac7fSDu, Changbin 	return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
537b9fdac7fSDu, Changbin }
538b9fdac7fSDu, Changbin 
539dc186ad7SThomas Gleixner /*
540dc186ad7SThomas Gleixner  * fixup_init is called when:
541dc186ad7SThomas Gleixner  * - an active object is initialized
542dc186ad7SThomas Gleixner  */
54302a982a6SDu, Changbin static bool work_fixup_init(void *addr, enum debug_obj_state state)
544dc186ad7SThomas Gleixner {
545dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
546dc186ad7SThomas Gleixner 
547dc186ad7SThomas Gleixner 	switch (state) {
548dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
549dc186ad7SThomas Gleixner 		cancel_work_sync(work);
550dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
55102a982a6SDu, Changbin 		return true;
552dc186ad7SThomas Gleixner 	default:
55302a982a6SDu, Changbin 		return false;
554dc186ad7SThomas Gleixner 	}
555dc186ad7SThomas Gleixner }
556dc186ad7SThomas Gleixner 
557dc186ad7SThomas Gleixner /*
558dc186ad7SThomas Gleixner  * fixup_free is called when:
559dc186ad7SThomas Gleixner  * - an active object is freed
560dc186ad7SThomas Gleixner  */
56102a982a6SDu, Changbin static bool work_fixup_free(void *addr, enum debug_obj_state state)
562dc186ad7SThomas Gleixner {
563dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
564dc186ad7SThomas Gleixner 
565dc186ad7SThomas Gleixner 	switch (state) {
566dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
567dc186ad7SThomas Gleixner 		cancel_work_sync(work);
568dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
56902a982a6SDu, Changbin 		return true;
570dc186ad7SThomas Gleixner 	default:
57102a982a6SDu, Changbin 		return false;
572dc186ad7SThomas Gleixner 	}
573dc186ad7SThomas Gleixner }
574dc186ad7SThomas Gleixner 
575f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr = {
576dc186ad7SThomas Gleixner 	.name		= "work_struct",
57799777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
578b9fdac7fSDu, Changbin 	.is_static_object = work_is_static_object,
579dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
580dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
581dc186ad7SThomas Gleixner };
582dc186ad7SThomas Gleixner 
583dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
584dc186ad7SThomas Gleixner {
585dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
586dc186ad7SThomas Gleixner }
587dc186ad7SThomas Gleixner 
588dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
589dc186ad7SThomas Gleixner {
590dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
591dc186ad7SThomas Gleixner }
592dc186ad7SThomas Gleixner 
593dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
594dc186ad7SThomas Gleixner {
595dc186ad7SThomas Gleixner 	if (onstack)
596dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
597dc186ad7SThomas Gleixner 	else
598dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
599dc186ad7SThomas Gleixner }
600dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
601dc186ad7SThomas Gleixner 
602dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
603dc186ad7SThomas Gleixner {
604dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
605dc186ad7SThomas Gleixner }
606dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
607dc186ad7SThomas Gleixner 
608ea2e64f2SThomas Gleixner void destroy_delayed_work_on_stack(struct delayed_work *work)
609ea2e64f2SThomas Gleixner {
610ea2e64f2SThomas Gleixner 	destroy_timer_on_stack(&work->timer);
611ea2e64f2SThomas Gleixner 	debug_object_free(&work->work, &work_debug_descr);
612ea2e64f2SThomas Gleixner }
613ea2e64f2SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
614ea2e64f2SThomas Gleixner 
615dc186ad7SThomas Gleixner #else
616dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
617dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
618dc186ad7SThomas Gleixner #endif
619dc186ad7SThomas Gleixner 
6204e8b22bdSLi Bin /**
62167dc8325SCai Huoqing  * worker_pool_assign_id - allocate ID and assign it to @pool
6224e8b22bdSLi Bin  * @pool: the pool pointer of interest
6234e8b22bdSLi Bin  *
6244e8b22bdSLi Bin  * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
6254e8b22bdSLi Bin  * successfully, -errno on failure.
6264e8b22bdSLi Bin  */
6279daf9e67STejun Heo static int worker_pool_assign_id(struct worker_pool *pool)
6289daf9e67STejun Heo {
6299daf9e67STejun Heo 	int ret;
6309daf9e67STejun Heo 
63168e13a67SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
6325bcab335STejun Heo 
6334e8b22bdSLi Bin 	ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
6344e8b22bdSLi Bin 			GFP_KERNEL);
635229641a6STejun Heo 	if (ret >= 0) {
636e68035fbSTejun Heo 		pool->id = ret;
637229641a6STejun Heo 		return 0;
638229641a6STejun Heo 	}
6399daf9e67STejun Heo 	return ret;
6409daf9e67STejun Heo }
6419daf9e67STejun Heo 
64273f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
64373f53c4aSTejun Heo {
64473f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
64573f53c4aSTejun Heo }
64673f53c4aSTejun Heo 
647c4560c2cSLai Jiangshan static int get_work_color(unsigned long work_data)
64873f53c4aSTejun Heo {
649c4560c2cSLai Jiangshan 	return (work_data >> WORK_STRUCT_COLOR_SHIFT) &
65073f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
65173f53c4aSTejun Heo }
65273f53c4aSTejun Heo 
65373f53c4aSTejun Heo static int work_next_color(int color)
65473f53c4aSTejun Heo {
65573f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
656a848e3b6SOleg Nesterov }
657a848e3b6SOleg Nesterov 
6584594bf15SDavid Howells /*
659112202d9STejun Heo  * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
660112202d9STejun Heo  * contain the pointer to the queued pwq.  Once execution starts, the flag
6617c3eed5cSTejun Heo  * is cleared and the high bits contain OFFQ flags and pool ID.
6627a22ad75STejun Heo  *
663112202d9STejun Heo  * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
664112202d9STejun Heo  * and clear_work_data() can be used to set the pwq, pool or clear
665bbb68dfaSTejun Heo  * work->data.  These functions should only be called while the work is
666bbb68dfaSTejun Heo  * owned - ie. while the PENDING bit is set.
6677a22ad75STejun Heo  *
668112202d9STejun Heo  * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
6697c3eed5cSTejun Heo  * corresponding to a work.  Pool is available once the work has been
670112202d9STejun Heo  * queued anywhere after initialization until it is sync canceled.  pwq is
6717c3eed5cSTejun Heo  * available only while the work item is queued.
672bbb68dfaSTejun Heo  *
673bbb68dfaSTejun Heo  * %WORK_OFFQ_CANCELING is used to mark a work item which is being
674bbb68dfaSTejun Heo  * canceled.  While being canceled, a work item may have its PENDING set
675bbb68dfaSTejun Heo  * but stay off timer and worklist for arbitrarily long and nobody should
676bbb68dfaSTejun Heo  * try to steal the PENDING bit.
6774594bf15SDavid Howells  */
6787a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
6797a22ad75STejun Heo 				 unsigned long flags)
6807a22ad75STejun Heo {
6816183c009STejun Heo 	WARN_ON_ONCE(!work_pending(work));
6827a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
6837a22ad75STejun Heo }
6847a22ad75STejun Heo 
685112202d9STejun Heo static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
6864690c4abSTejun Heo 			 unsigned long extra_flags)
687365970a1SDavid Howells {
688112202d9STejun Heo 	set_work_data(work, (unsigned long)pwq,
689112202d9STejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
690365970a1SDavid Howells }
691365970a1SDavid Howells 
6924468a00fSLai Jiangshan static void set_work_pool_and_keep_pending(struct work_struct *work,
6934468a00fSLai Jiangshan 					   int pool_id)
6944468a00fSLai Jiangshan {
6954468a00fSLai Jiangshan 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
6964468a00fSLai Jiangshan 		      WORK_STRUCT_PENDING);
6974468a00fSLai Jiangshan }
6984468a00fSLai Jiangshan 
6997c3eed5cSTejun Heo static void set_work_pool_and_clear_pending(struct work_struct *work,
7007c3eed5cSTejun Heo 					    int pool_id)
7014d707b9fSOleg Nesterov {
70223657bb1STejun Heo 	/*
70323657bb1STejun Heo 	 * The following wmb is paired with the implied mb in
70423657bb1STejun Heo 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
70523657bb1STejun Heo 	 * here are visible to and precede any updates by the next PENDING
70623657bb1STejun Heo 	 * owner.
70723657bb1STejun Heo 	 */
70823657bb1STejun Heo 	smp_wmb();
7097c3eed5cSTejun Heo 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
710346c09f8SRoman Pen 	/*
711346c09f8SRoman Pen 	 * The following mb guarantees that previous clear of a PENDING bit
712346c09f8SRoman Pen 	 * will not be reordered with any speculative LOADS or STORES from
713346c09f8SRoman Pen 	 * work->current_func, which is executed afterwards.  This possible
7148bdc6201SLiu Song 	 * reordering can lead to a missed execution on attempt to queue
715346c09f8SRoman Pen 	 * the same @work.  E.g. consider this case:
716346c09f8SRoman Pen 	 *
717346c09f8SRoman Pen 	 *   CPU#0                         CPU#1
718346c09f8SRoman Pen 	 *   ----------------------------  --------------------------------
719346c09f8SRoman Pen 	 *
720346c09f8SRoman Pen 	 * 1  STORE event_indicated
721346c09f8SRoman Pen 	 * 2  queue_work_on() {
722346c09f8SRoman Pen 	 * 3    test_and_set_bit(PENDING)
723346c09f8SRoman Pen 	 * 4 }                             set_..._and_clear_pending() {
724346c09f8SRoman Pen 	 * 5                                 set_work_data() # clear bit
725346c09f8SRoman Pen 	 * 6                                 smp_mb()
726346c09f8SRoman Pen 	 * 7                               work->current_func() {
727346c09f8SRoman Pen 	 * 8				      LOAD event_indicated
728346c09f8SRoman Pen 	 *				   }
729346c09f8SRoman Pen 	 *
730346c09f8SRoman Pen 	 * Without an explicit full barrier speculative LOAD on line 8 can
731346c09f8SRoman Pen 	 * be executed before CPU#0 does STORE on line 1.  If that happens,
732346c09f8SRoman Pen 	 * CPU#0 observes the PENDING bit is still set and new execution of
733346c09f8SRoman Pen 	 * a @work is not queued in a hope, that CPU#1 will eventually
734346c09f8SRoman Pen 	 * finish the queued @work.  Meanwhile CPU#1 does not see
735346c09f8SRoman Pen 	 * event_indicated is set, because speculative LOAD was executed
736346c09f8SRoman Pen 	 * before actual STORE.
737346c09f8SRoman Pen 	 */
738346c09f8SRoman Pen 	smp_mb();
7394d707b9fSOleg Nesterov }
7404d707b9fSOleg Nesterov 
7417a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
742365970a1SDavid Howells {
7437c3eed5cSTejun Heo 	smp_wmb();	/* see set_work_pool_and_clear_pending() */
7447c3eed5cSTejun Heo 	set_work_data(work, WORK_STRUCT_NO_POOL, 0);
7457a22ad75STejun Heo }
7467a22ad75STejun Heo 
747afa4bb77SLinus Torvalds static inline struct pool_workqueue *work_struct_pwq(unsigned long data)
748afa4bb77SLinus Torvalds {
749afa4bb77SLinus Torvalds 	return (struct pool_workqueue *)(data & WORK_STRUCT_WQ_DATA_MASK);
750afa4bb77SLinus Torvalds }
751afa4bb77SLinus Torvalds 
752112202d9STejun Heo static struct pool_workqueue *get_work_pwq(struct work_struct *work)
7537a22ad75STejun Heo {
754e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
7557a22ad75STejun Heo 
756112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
757afa4bb77SLinus Torvalds 		return work_struct_pwq(data);
758e120153dSTejun Heo 	else
759e120153dSTejun Heo 		return NULL;
7607a22ad75STejun Heo }
7617a22ad75STejun Heo 
7627c3eed5cSTejun Heo /**
7637c3eed5cSTejun Heo  * get_work_pool - return the worker_pool a given work was associated with
7647c3eed5cSTejun Heo  * @work: the work item of interest
7657c3eed5cSTejun Heo  *
76668e13a67SLai Jiangshan  * Pools are created and destroyed under wq_pool_mutex, and allows read
76724acfb71SThomas Gleixner  * access under RCU read lock.  As such, this function should be
76824acfb71SThomas Gleixner  * called under wq_pool_mutex or inside of a rcu_read_lock() region.
769fa1b54e6STejun Heo  *
770fa1b54e6STejun Heo  * All fields of the returned pool are accessible as long as the above
771fa1b54e6STejun Heo  * mentioned locking is in effect.  If the returned pool needs to be used
772fa1b54e6STejun Heo  * beyond the critical section, the caller is responsible for ensuring the
773fa1b54e6STejun Heo  * returned pool is and stays online.
774d185af30SYacine Belkadi  *
775d185af30SYacine Belkadi  * Return: The worker_pool @work was last associated with.  %NULL if none.
7767c3eed5cSTejun Heo  */
7777c3eed5cSTejun Heo static struct worker_pool *get_work_pool(struct work_struct *work)
7787a22ad75STejun Heo {
779e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
7807c3eed5cSTejun Heo 	int pool_id;
7817a22ad75STejun Heo 
78268e13a67SLai Jiangshan 	assert_rcu_or_pool_mutex();
783fa1b54e6STejun Heo 
784112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
785afa4bb77SLinus Torvalds 		return work_struct_pwq(data)->pool;
7867a22ad75STejun Heo 
7877c3eed5cSTejun Heo 	pool_id = data >> WORK_OFFQ_POOL_SHIFT;
7887c3eed5cSTejun Heo 	if (pool_id == WORK_OFFQ_POOL_NONE)
7897a22ad75STejun Heo 		return NULL;
7907a22ad75STejun Heo 
791fa1b54e6STejun Heo 	return idr_find(&worker_pool_idr, pool_id);
7927c3eed5cSTejun Heo }
7937c3eed5cSTejun Heo 
7947c3eed5cSTejun Heo /**
7957c3eed5cSTejun Heo  * get_work_pool_id - return the worker pool ID a given work is associated with
7967c3eed5cSTejun Heo  * @work: the work item of interest
7977c3eed5cSTejun Heo  *
798d185af30SYacine Belkadi  * Return: The worker_pool ID @work was last associated with.
7997c3eed5cSTejun Heo  * %WORK_OFFQ_POOL_NONE if none.
8007c3eed5cSTejun Heo  */
8017c3eed5cSTejun Heo static int get_work_pool_id(struct work_struct *work)
8027c3eed5cSTejun Heo {
80354d5b7d0SLai Jiangshan 	unsigned long data = atomic_long_read(&work->data);
8047c3eed5cSTejun Heo 
805112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
806afa4bb77SLinus Torvalds 		return work_struct_pwq(data)->pool->id;
80754d5b7d0SLai Jiangshan 
80854d5b7d0SLai Jiangshan 	return data >> WORK_OFFQ_POOL_SHIFT;
8097c3eed5cSTejun Heo }
8107c3eed5cSTejun Heo 
811bbb68dfaSTejun Heo static void mark_work_canceling(struct work_struct *work)
812bbb68dfaSTejun Heo {
8137c3eed5cSTejun Heo 	unsigned long pool_id = get_work_pool_id(work);
814bbb68dfaSTejun Heo 
8157c3eed5cSTejun Heo 	pool_id <<= WORK_OFFQ_POOL_SHIFT;
8167c3eed5cSTejun Heo 	set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
817bbb68dfaSTejun Heo }
818bbb68dfaSTejun Heo 
819bbb68dfaSTejun Heo static bool work_is_canceling(struct work_struct *work)
820bbb68dfaSTejun Heo {
821bbb68dfaSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
822bbb68dfaSTejun Heo 
823112202d9STejun Heo 	return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
824bbb68dfaSTejun Heo }
825bbb68dfaSTejun Heo 
826e22bee78STejun Heo /*
8273270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
8283270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
829d565ed63STejun Heo  * they're being called with pool->lock held.
830e22bee78STejun Heo  */
831e22bee78STejun Heo 
832e22bee78STejun Heo /*
833e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
834e22bee78STejun Heo  * running workers.
835974271c4STejun Heo  *
836974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
837706026c2STejun Heo  * function will always return %true for unbound pools as long as the
838974271c4STejun Heo  * worklist isn't empty.
839e22bee78STejun Heo  */
84063d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
841e22bee78STejun Heo {
8420219a352STejun Heo 	return !list_empty(&pool->worklist) && !pool->nr_running;
843e22bee78STejun Heo }
844e22bee78STejun Heo 
845e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
84663d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
847e22bee78STejun Heo {
84863d95a91STejun Heo 	return pool->nr_idle;
849e22bee78STejun Heo }
850e22bee78STejun Heo 
851e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
85263d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
853e22bee78STejun Heo {
854bc35f7efSLai Jiangshan 	return !list_empty(&pool->worklist) && (pool->nr_running <= 1);
855e22bee78STejun Heo }
856e22bee78STejun Heo 
857e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
85863d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
859e22bee78STejun Heo {
86063d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
861e22bee78STejun Heo }
862e22bee78STejun Heo 
863e22bee78STejun Heo /* Do we have too many workers and should some go away? */
86463d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
865e22bee78STejun Heo {
866692b4825STejun Heo 	bool managing = pool->flags & POOL_MANAGER_ACTIVE;
86763d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
86863d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
869e22bee78STejun Heo 
870e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
871e22bee78STejun Heo }
872e22bee78STejun Heo 
8734690c4abSTejun Heo /**
874e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
875cb444766STejun Heo  * @worker: self
876d302f017STejun Heo  * @flags: flags to set
877d302f017STejun Heo  *
878228f1d00SLai Jiangshan  * Set @flags in @worker->flags and adjust nr_running accordingly.
879d302f017STejun Heo  */
880228f1d00SLai Jiangshan static inline void worker_set_flags(struct worker *worker, unsigned int flags)
881d302f017STejun Heo {
882bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
883e22bee78STejun Heo 
884bc8b50c2STejun Heo 	lockdep_assert_held(&pool->lock);
885cb444766STejun Heo 
886228f1d00SLai Jiangshan 	/* If transitioning into NOT_RUNNING, adjust nr_running. */
887e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
888e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
889bc35f7efSLai Jiangshan 		pool->nr_running--;
890e22bee78STejun Heo 	}
891e22bee78STejun Heo 
892d302f017STejun Heo 	worker->flags |= flags;
893d302f017STejun Heo }
894d302f017STejun Heo 
895d302f017STejun Heo /**
896e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
897cb444766STejun Heo  * @worker: self
898d302f017STejun Heo  * @flags: flags to clear
899d302f017STejun Heo  *
900e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
901d302f017STejun Heo  */
902d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
903d302f017STejun Heo {
90463d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
905e22bee78STejun Heo 	unsigned int oflags = worker->flags;
906e22bee78STejun Heo 
907bc8b50c2STejun Heo 	lockdep_assert_held(&pool->lock);
908cb444766STejun Heo 
909d302f017STejun Heo 	worker->flags &= ~flags;
910e22bee78STejun Heo 
91142c025f3STejun Heo 	/*
91242c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
91342c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
91442c025f3STejun Heo 	 * of multiple flags, not a single flag.
91542c025f3STejun Heo 	 */
916e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
917e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
918bc35f7efSLai Jiangshan 			pool->nr_running++;
919d302f017STejun Heo }
920d302f017STejun Heo 
921797e8345STejun Heo /* Return the first idle worker.  Called with pool->lock held. */
922797e8345STejun Heo static struct worker *first_idle_worker(struct worker_pool *pool)
923797e8345STejun Heo {
924797e8345STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
925797e8345STejun Heo 		return NULL;
926797e8345STejun Heo 
927797e8345STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
928797e8345STejun Heo }
929797e8345STejun Heo 
930797e8345STejun Heo /**
931797e8345STejun Heo  * worker_enter_idle - enter idle state
932797e8345STejun Heo  * @worker: worker which is entering idle state
933797e8345STejun Heo  *
934797e8345STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
935797e8345STejun Heo  * necessary.
936797e8345STejun Heo  *
937797e8345STejun Heo  * LOCKING:
938797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
939797e8345STejun Heo  */
940797e8345STejun Heo static void worker_enter_idle(struct worker *worker)
941797e8345STejun Heo {
942797e8345STejun Heo 	struct worker_pool *pool = worker->pool;
943797e8345STejun Heo 
944797e8345STejun Heo 	if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
945797e8345STejun Heo 	    WARN_ON_ONCE(!list_empty(&worker->entry) &&
946797e8345STejun Heo 			 (worker->hentry.next || worker->hentry.pprev)))
947797e8345STejun Heo 		return;
948797e8345STejun Heo 
949797e8345STejun Heo 	/* can't use worker_set_flags(), also called from create_worker() */
950797e8345STejun Heo 	worker->flags |= WORKER_IDLE;
951797e8345STejun Heo 	pool->nr_idle++;
952797e8345STejun Heo 	worker->last_active = jiffies;
953797e8345STejun Heo 
954797e8345STejun Heo 	/* idle_list is LIFO */
955797e8345STejun Heo 	list_add(&worker->entry, &pool->idle_list);
956797e8345STejun Heo 
957797e8345STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
958797e8345STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
959797e8345STejun Heo 
960797e8345STejun Heo 	/* Sanity check nr_running. */
961797e8345STejun Heo 	WARN_ON_ONCE(pool->nr_workers == pool->nr_idle && pool->nr_running);
962797e8345STejun Heo }
963797e8345STejun Heo 
964797e8345STejun Heo /**
965797e8345STejun Heo  * worker_leave_idle - leave idle state
966797e8345STejun Heo  * @worker: worker which is leaving idle state
967797e8345STejun Heo  *
968797e8345STejun Heo  * @worker is leaving idle state.  Update stats.
969797e8345STejun Heo  *
970797e8345STejun Heo  * LOCKING:
971797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
972797e8345STejun Heo  */
973797e8345STejun Heo static void worker_leave_idle(struct worker *worker)
974797e8345STejun Heo {
975797e8345STejun Heo 	struct worker_pool *pool = worker->pool;
976797e8345STejun Heo 
977797e8345STejun Heo 	if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
978797e8345STejun Heo 		return;
979797e8345STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
980797e8345STejun Heo 	pool->nr_idle--;
981797e8345STejun Heo 	list_del_init(&worker->entry);
982797e8345STejun Heo }
983797e8345STejun Heo 
984797e8345STejun Heo /**
985797e8345STejun Heo  * find_worker_executing_work - find worker which is executing a work
986797e8345STejun Heo  * @pool: pool of interest
987797e8345STejun Heo  * @work: work to find worker for
988797e8345STejun Heo  *
989797e8345STejun Heo  * Find a worker which is executing @work on @pool by searching
990797e8345STejun Heo  * @pool->busy_hash which is keyed by the address of @work.  For a worker
991797e8345STejun Heo  * to match, its current execution should match the address of @work and
992797e8345STejun Heo  * its work function.  This is to avoid unwanted dependency between
993797e8345STejun Heo  * unrelated work executions through a work item being recycled while still
994797e8345STejun Heo  * being executed.
995797e8345STejun Heo  *
996797e8345STejun Heo  * This is a bit tricky.  A work item may be freed once its execution
997797e8345STejun Heo  * starts and nothing prevents the freed area from being recycled for
998797e8345STejun Heo  * another work item.  If the same work item address ends up being reused
999797e8345STejun Heo  * before the original execution finishes, workqueue will identify the
1000797e8345STejun Heo  * recycled work item as currently executing and make it wait until the
1001797e8345STejun Heo  * current execution finishes, introducing an unwanted dependency.
1002797e8345STejun Heo  *
1003797e8345STejun Heo  * This function checks the work item address and work function to avoid
1004797e8345STejun Heo  * false positives.  Note that this isn't complete as one may construct a
1005797e8345STejun Heo  * work function which can introduce dependency onto itself through a
1006797e8345STejun Heo  * recycled work item.  Well, if somebody wants to shoot oneself in the
1007797e8345STejun Heo  * foot that badly, there's only so much we can do, and if such deadlock
1008797e8345STejun Heo  * actually occurs, it should be easy to locate the culprit work function.
1009797e8345STejun Heo  *
1010797e8345STejun Heo  * CONTEXT:
1011797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
1012797e8345STejun Heo  *
1013797e8345STejun Heo  * Return:
1014797e8345STejun Heo  * Pointer to worker which is executing @work if found, %NULL
1015797e8345STejun Heo  * otherwise.
1016797e8345STejun Heo  */
1017797e8345STejun Heo static struct worker *find_worker_executing_work(struct worker_pool *pool,
1018797e8345STejun Heo 						 struct work_struct *work)
1019797e8345STejun Heo {
1020797e8345STejun Heo 	struct worker *worker;
1021797e8345STejun Heo 
1022797e8345STejun Heo 	hash_for_each_possible(pool->busy_hash, worker, hentry,
1023797e8345STejun Heo 			       (unsigned long)work)
1024797e8345STejun Heo 		if (worker->current_work == work &&
1025797e8345STejun Heo 		    worker->current_func == work->func)
1026797e8345STejun Heo 			return worker;
1027797e8345STejun Heo 
1028797e8345STejun Heo 	return NULL;
1029797e8345STejun Heo }
1030797e8345STejun Heo 
1031797e8345STejun Heo /**
1032797e8345STejun Heo  * move_linked_works - move linked works to a list
1033797e8345STejun Heo  * @work: start of series of works to be scheduled
1034797e8345STejun Heo  * @head: target list to append @work to
1035797e8345STejun Heo  * @nextp: out parameter for nested worklist walking
1036797e8345STejun Heo  *
1037873eaca6STejun Heo  * Schedule linked works starting from @work to @head. Work series to be
1038873eaca6STejun Heo  * scheduled starts at @work and includes any consecutive work with
1039873eaca6STejun Heo  * WORK_STRUCT_LINKED set in its predecessor. See assign_work() for details on
1040873eaca6STejun Heo  * @nextp.
1041797e8345STejun Heo  *
1042797e8345STejun Heo  * CONTEXT:
1043797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
1044797e8345STejun Heo  */
1045797e8345STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
1046797e8345STejun Heo 			      struct work_struct **nextp)
1047797e8345STejun Heo {
1048797e8345STejun Heo 	struct work_struct *n;
1049797e8345STejun Heo 
1050797e8345STejun Heo 	/*
1051797e8345STejun Heo 	 * Linked worklist will always end before the end of the list,
1052797e8345STejun Heo 	 * use NULL for list head.
1053797e8345STejun Heo 	 */
1054797e8345STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
1055797e8345STejun Heo 		list_move_tail(&work->entry, head);
1056797e8345STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1057797e8345STejun Heo 			break;
1058797e8345STejun Heo 	}
1059797e8345STejun Heo 
1060797e8345STejun Heo 	/*
1061797e8345STejun Heo 	 * If we're already inside safe list traversal and have moved
1062797e8345STejun Heo 	 * multiple works to the scheduled queue, the next position
1063797e8345STejun Heo 	 * needs to be updated.
1064797e8345STejun Heo 	 */
1065797e8345STejun Heo 	if (nextp)
1066797e8345STejun Heo 		*nextp = n;
1067797e8345STejun Heo }
1068797e8345STejun Heo 
1069797e8345STejun Heo /**
1070873eaca6STejun Heo  * assign_work - assign a work item and its linked work items to a worker
1071873eaca6STejun Heo  * @work: work to assign
1072873eaca6STejun Heo  * @worker: worker to assign to
1073873eaca6STejun Heo  * @nextp: out parameter for nested worklist walking
1074873eaca6STejun Heo  *
1075873eaca6STejun Heo  * Assign @work and its linked work items to @worker. If @work is already being
1076873eaca6STejun Heo  * executed by another worker in the same pool, it'll be punted there.
1077873eaca6STejun Heo  *
1078873eaca6STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of the last
1079873eaca6STejun Heo  * scheduled work. This allows assign_work() to be nested inside
1080873eaca6STejun Heo  * list_for_each_entry_safe().
1081873eaca6STejun Heo  *
1082873eaca6STejun Heo  * Returns %true if @work was successfully assigned to @worker. %false if @work
1083873eaca6STejun Heo  * was punted to another worker already executing it.
1084873eaca6STejun Heo  */
1085873eaca6STejun Heo static bool assign_work(struct work_struct *work, struct worker *worker,
1086873eaca6STejun Heo 			struct work_struct **nextp)
1087873eaca6STejun Heo {
1088873eaca6STejun Heo 	struct worker_pool *pool = worker->pool;
1089873eaca6STejun Heo 	struct worker *collision;
1090873eaca6STejun Heo 
1091873eaca6STejun Heo 	lockdep_assert_held(&pool->lock);
1092873eaca6STejun Heo 
1093873eaca6STejun Heo 	/*
1094873eaca6STejun Heo 	 * A single work shouldn't be executed concurrently by multiple workers.
1095873eaca6STejun Heo 	 * __queue_work() ensures that @work doesn't jump to a different pool
1096873eaca6STejun Heo 	 * while still running in the previous pool. Here, we should ensure that
1097873eaca6STejun Heo 	 * @work is not executed concurrently by multiple workers from the same
1098873eaca6STejun Heo 	 * pool. Check whether anyone is already processing the work. If so,
1099873eaca6STejun Heo 	 * defer the work to the currently executing one.
1100873eaca6STejun Heo 	 */
1101873eaca6STejun Heo 	collision = find_worker_executing_work(pool, work);
1102873eaca6STejun Heo 	if (unlikely(collision)) {
1103873eaca6STejun Heo 		move_linked_works(work, &collision->scheduled, nextp);
1104873eaca6STejun Heo 		return false;
1105873eaca6STejun Heo 	}
1106873eaca6STejun Heo 
1107873eaca6STejun Heo 	move_linked_works(work, &worker->scheduled, nextp);
1108873eaca6STejun Heo 	return true;
1109873eaca6STejun Heo }
1110873eaca6STejun Heo 
1111873eaca6STejun Heo /**
11120219a352STejun Heo  * kick_pool - wake up an idle worker if necessary
11130219a352STejun Heo  * @pool: pool to kick
1114797e8345STejun Heo  *
11150219a352STejun Heo  * @pool may have pending work items. Wake up worker if necessary. Returns
11160219a352STejun Heo  * whether a worker was woken up.
1117797e8345STejun Heo  */
11180219a352STejun Heo static bool kick_pool(struct worker_pool *pool)
1119797e8345STejun Heo {
1120797e8345STejun Heo 	struct worker *worker = first_idle_worker(pool);
11218639ecebSTejun Heo 	struct task_struct *p;
1122797e8345STejun Heo 
11230219a352STejun Heo 	lockdep_assert_held(&pool->lock);
11240219a352STejun Heo 
11250219a352STejun Heo 	if (!need_more_worker(pool) || !worker)
11260219a352STejun Heo 		return false;
11270219a352STejun Heo 
11288639ecebSTejun Heo 	p = worker->task;
11298639ecebSTejun Heo 
11308639ecebSTejun Heo #ifdef CONFIG_SMP
11318639ecebSTejun Heo 	/*
11328639ecebSTejun Heo 	 * Idle @worker is about to execute @work and waking up provides an
11338639ecebSTejun Heo 	 * opportunity to migrate @worker at a lower cost by setting the task's
11348639ecebSTejun Heo 	 * wake_cpu field. Let's see if we want to move @worker to improve
11358639ecebSTejun Heo 	 * execution locality.
11368639ecebSTejun Heo 	 *
11378639ecebSTejun Heo 	 * We're waking the worker that went idle the latest and there's some
11388639ecebSTejun Heo 	 * chance that @worker is marked idle but hasn't gone off CPU yet. If
11398639ecebSTejun Heo 	 * so, setting the wake_cpu won't do anything. As this is a best-effort
11408639ecebSTejun Heo 	 * optimization and the race window is narrow, let's leave as-is for
11418639ecebSTejun Heo 	 * now. If this becomes pronounced, we can skip over workers which are
11428639ecebSTejun Heo 	 * still on cpu when picking an idle worker.
11438639ecebSTejun Heo 	 *
11448639ecebSTejun Heo 	 * If @pool has non-strict affinity, @worker might have ended up outside
11458639ecebSTejun Heo 	 * its affinity scope. Repatriate.
11468639ecebSTejun Heo 	 */
11478639ecebSTejun Heo 	if (!pool->attrs->affn_strict &&
11488639ecebSTejun Heo 	    !cpumask_test_cpu(p->wake_cpu, pool->attrs->__pod_cpumask)) {
11498639ecebSTejun Heo 		struct work_struct *work = list_first_entry(&pool->worklist,
11508639ecebSTejun Heo 						struct work_struct, entry);
11518639ecebSTejun Heo 		p->wake_cpu = cpumask_any_distribute(pool->attrs->__pod_cpumask);
11528639ecebSTejun Heo 		get_work_pwq(work)->stats[PWQ_STAT_REPATRIATED]++;
11538639ecebSTejun Heo 	}
11548639ecebSTejun Heo #endif
11558639ecebSTejun Heo 	wake_up_process(p);
11560219a352STejun Heo 	return true;
1157797e8345STejun Heo }
1158797e8345STejun Heo 
115963638450STejun Heo #ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
116063638450STejun Heo 
116163638450STejun Heo /*
116263638450STejun Heo  * Concurrency-managed per-cpu work items that hog CPU for longer than
116363638450STejun Heo  * wq_cpu_intensive_thresh_us trigger the automatic CPU_INTENSIVE mechanism,
116463638450STejun Heo  * which prevents them from stalling other concurrency-managed work items. If a
116563638450STejun Heo  * work function keeps triggering this mechanism, it's likely that the work item
116663638450STejun Heo  * should be using an unbound workqueue instead.
116763638450STejun Heo  *
116863638450STejun Heo  * wq_cpu_intensive_report() tracks work functions which trigger such conditions
116963638450STejun Heo  * and report them so that they can be examined and converted to use unbound
117063638450STejun Heo  * workqueues as appropriate. To avoid flooding the console, each violating work
117163638450STejun Heo  * function is tracked and reported with exponential backoff.
117263638450STejun Heo  */
117363638450STejun Heo #define WCI_MAX_ENTS 128
117463638450STejun Heo 
117563638450STejun Heo struct wci_ent {
117663638450STejun Heo 	work_func_t		func;
117763638450STejun Heo 	atomic64_t		cnt;
117863638450STejun Heo 	struct hlist_node	hash_node;
117963638450STejun Heo };
118063638450STejun Heo 
118163638450STejun Heo static struct wci_ent wci_ents[WCI_MAX_ENTS];
118263638450STejun Heo static int wci_nr_ents;
118363638450STejun Heo static DEFINE_RAW_SPINLOCK(wci_lock);
118463638450STejun Heo static DEFINE_HASHTABLE(wci_hash, ilog2(WCI_MAX_ENTS));
118563638450STejun Heo 
118663638450STejun Heo static struct wci_ent *wci_find_ent(work_func_t func)
118763638450STejun Heo {
118863638450STejun Heo 	struct wci_ent *ent;
118963638450STejun Heo 
119063638450STejun Heo 	hash_for_each_possible_rcu(wci_hash, ent, hash_node,
119163638450STejun Heo 				   (unsigned long)func) {
119263638450STejun Heo 		if (ent->func == func)
119363638450STejun Heo 			return ent;
119463638450STejun Heo 	}
119563638450STejun Heo 	return NULL;
119663638450STejun Heo }
119763638450STejun Heo 
119863638450STejun Heo static void wq_cpu_intensive_report(work_func_t func)
119963638450STejun Heo {
120063638450STejun Heo 	struct wci_ent *ent;
120163638450STejun Heo 
120263638450STejun Heo restart:
120363638450STejun Heo 	ent = wci_find_ent(func);
120463638450STejun Heo 	if (ent) {
120563638450STejun Heo 		u64 cnt;
120663638450STejun Heo 
120763638450STejun Heo 		/*
120863638450STejun Heo 		 * Start reporting from the fourth time and back off
120963638450STejun Heo 		 * exponentially.
121063638450STejun Heo 		 */
121163638450STejun Heo 		cnt = atomic64_inc_return_relaxed(&ent->cnt);
121263638450STejun Heo 		if (cnt >= 4 && is_power_of_2(cnt))
121363638450STejun Heo 			printk_deferred(KERN_WARNING "workqueue: %ps hogged CPU for >%luus %llu times, consider switching to WQ_UNBOUND\n",
121463638450STejun Heo 					ent->func, wq_cpu_intensive_thresh_us,
121563638450STejun Heo 					atomic64_read(&ent->cnt));
121663638450STejun Heo 		return;
121763638450STejun Heo 	}
121863638450STejun Heo 
121963638450STejun Heo 	/*
122063638450STejun Heo 	 * @func is a new violation. Allocate a new entry for it. If wcn_ents[]
122163638450STejun Heo 	 * is exhausted, something went really wrong and we probably made enough
122263638450STejun Heo 	 * noise already.
122363638450STejun Heo 	 */
122463638450STejun Heo 	if (wci_nr_ents >= WCI_MAX_ENTS)
122563638450STejun Heo 		return;
122663638450STejun Heo 
122763638450STejun Heo 	raw_spin_lock(&wci_lock);
122863638450STejun Heo 
122963638450STejun Heo 	if (wci_nr_ents >= WCI_MAX_ENTS) {
123063638450STejun Heo 		raw_spin_unlock(&wci_lock);
123163638450STejun Heo 		return;
123263638450STejun Heo 	}
123363638450STejun Heo 
123463638450STejun Heo 	if (wci_find_ent(func)) {
123563638450STejun Heo 		raw_spin_unlock(&wci_lock);
123663638450STejun Heo 		goto restart;
123763638450STejun Heo 	}
123863638450STejun Heo 
123963638450STejun Heo 	ent = &wci_ents[wci_nr_ents++];
124063638450STejun Heo 	ent->func = func;
124163638450STejun Heo 	atomic64_set(&ent->cnt, 1);
124263638450STejun Heo 	hash_add_rcu(wci_hash, &ent->hash_node, (unsigned long)func);
124363638450STejun Heo 
124463638450STejun Heo 	raw_spin_unlock(&wci_lock);
124563638450STejun Heo }
124663638450STejun Heo 
124763638450STejun Heo #else	/* CONFIG_WQ_CPU_INTENSIVE_REPORT */
124863638450STejun Heo static void wq_cpu_intensive_report(work_func_t func) {}
124963638450STejun Heo #endif	/* CONFIG_WQ_CPU_INTENSIVE_REPORT */
125063638450STejun Heo 
1251c54d5046STejun Heo /**
12521da177e4SLinus Torvalds  * wq_worker_running - a worker is running again
12531da177e4SLinus Torvalds  * @task: task waking up
12541da177e4SLinus Torvalds  *
12551da177e4SLinus Torvalds  * This function is called when a worker returns from schedule()
12561da177e4SLinus Torvalds  */
12571da177e4SLinus Torvalds void wq_worker_running(struct task_struct *task)
12581da177e4SLinus Torvalds {
12591da177e4SLinus Torvalds 	struct worker *worker = kthread_data(task);
12601da177e4SLinus Torvalds 
1261c8f6219bSZqiang 	if (!READ_ONCE(worker->sleeping))
12621da177e4SLinus Torvalds 		return;
12631da177e4SLinus Torvalds 
12641da177e4SLinus Torvalds 	/*
12651da177e4SLinus Torvalds 	 * If preempted by unbind_workers() between the WORKER_NOT_RUNNING check
12661da177e4SLinus Torvalds 	 * and the nr_running increment below, we may ruin the nr_running reset
12671da177e4SLinus Torvalds 	 * and leave with an unexpected pool->nr_running == 1 on the newly unbound
12681da177e4SLinus Torvalds 	 * pool. Protect against such race.
12691da177e4SLinus Torvalds 	 */
12701da177e4SLinus Torvalds 	preempt_disable();
12711da177e4SLinus Torvalds 	if (!(worker->flags & WORKER_NOT_RUNNING))
12721da177e4SLinus Torvalds 		worker->pool->nr_running++;
12731da177e4SLinus Torvalds 	preempt_enable();
1274616db877STejun Heo 
1275616db877STejun Heo 	/*
1276616db877STejun Heo 	 * CPU intensive auto-detection cares about how long a work item hogged
1277616db877STejun Heo 	 * CPU without sleeping. Reset the starting timestamp on wakeup.
1278616db877STejun Heo 	 */
1279616db877STejun Heo 	worker->current_at = worker->task->se.sum_exec_runtime;
1280616db877STejun Heo 
1281c8f6219bSZqiang 	WRITE_ONCE(worker->sleeping, 0);
12821da177e4SLinus Torvalds }
12831da177e4SLinus Torvalds 
12841da177e4SLinus Torvalds /**
12851da177e4SLinus Torvalds  * wq_worker_sleeping - a worker is going to sleep
12861da177e4SLinus Torvalds  * @task: task going to sleep
12871da177e4SLinus Torvalds  *
12881da177e4SLinus Torvalds  * This function is called from schedule() when a busy worker is
12891da177e4SLinus Torvalds  * going to sleep.
12901da177e4SLinus Torvalds  */
12911da177e4SLinus Torvalds void wq_worker_sleeping(struct task_struct *task)
12921da177e4SLinus Torvalds {
12931da177e4SLinus Torvalds 	struct worker *worker = kthread_data(task);
12941da177e4SLinus Torvalds 	struct worker_pool *pool;
12951da177e4SLinus Torvalds 
12961da177e4SLinus Torvalds 	/*
12971da177e4SLinus Torvalds 	 * Rescuers, which may not have all the fields set up like normal
12981da177e4SLinus Torvalds 	 * workers, also reach here, let's not access anything before
12991da177e4SLinus Torvalds 	 * checking NOT_RUNNING.
13001da177e4SLinus Torvalds 	 */
13011da177e4SLinus Torvalds 	if (worker->flags & WORKER_NOT_RUNNING)
13021da177e4SLinus Torvalds 		return;
13031da177e4SLinus Torvalds 
13041da177e4SLinus Torvalds 	pool = worker->pool;
13051da177e4SLinus Torvalds 
13061da177e4SLinus Torvalds 	/* Return if preempted before wq_worker_running() was reached */
1307c8f6219bSZqiang 	if (READ_ONCE(worker->sleeping))
13081da177e4SLinus Torvalds 		return;
13091da177e4SLinus Torvalds 
1310c8f6219bSZqiang 	WRITE_ONCE(worker->sleeping, 1);
13111da177e4SLinus Torvalds 	raw_spin_lock_irq(&pool->lock);
13121da177e4SLinus Torvalds 
13131da177e4SLinus Torvalds 	/*
13141da177e4SLinus Torvalds 	 * Recheck in case unbind_workers() preempted us. We don't
13151da177e4SLinus Torvalds 	 * want to decrement nr_running after the worker is unbound
13161da177e4SLinus Torvalds 	 * and nr_running has been reset.
13171da177e4SLinus Torvalds 	 */
13181da177e4SLinus Torvalds 	if (worker->flags & WORKER_NOT_RUNNING) {
13191da177e4SLinus Torvalds 		raw_spin_unlock_irq(&pool->lock);
13201da177e4SLinus Torvalds 		return;
13211da177e4SLinus Torvalds 	}
13221da177e4SLinus Torvalds 
13231da177e4SLinus Torvalds 	pool->nr_running--;
13240219a352STejun Heo 	if (kick_pool(pool))
1325725e8ec5STejun Heo 		worker->current_pwq->stats[PWQ_STAT_CM_WAKEUP]++;
13260219a352STejun Heo 
13271da177e4SLinus Torvalds 	raw_spin_unlock_irq(&pool->lock);
13281da177e4SLinus Torvalds }
13291da177e4SLinus Torvalds 
13301da177e4SLinus Torvalds /**
1331616db877STejun Heo  * wq_worker_tick - a scheduler tick occurred while a kworker is running
1332616db877STejun Heo  * @task: task currently running
1333616db877STejun Heo  *
1334616db877STejun Heo  * Called from scheduler_tick(). We're in the IRQ context and the current
1335616db877STejun Heo  * worker's fields which follow the 'K' locking rule can be accessed safely.
1336616db877STejun Heo  */
1337616db877STejun Heo void wq_worker_tick(struct task_struct *task)
1338616db877STejun Heo {
1339616db877STejun Heo 	struct worker *worker = kthread_data(task);
1340616db877STejun Heo 	struct pool_workqueue *pwq = worker->current_pwq;
1341616db877STejun Heo 	struct worker_pool *pool = worker->pool;
1342616db877STejun Heo 
1343616db877STejun Heo 	if (!pwq)
1344616db877STejun Heo 		return;
1345616db877STejun Heo 
13468a1dd1e5STejun Heo 	pwq->stats[PWQ_STAT_CPU_TIME] += TICK_USEC;
13478a1dd1e5STejun Heo 
134818c8ae81SZqiang 	if (!wq_cpu_intensive_thresh_us)
134918c8ae81SZqiang 		return;
135018c8ae81SZqiang 
1351616db877STejun Heo 	/*
1352616db877STejun Heo 	 * If the current worker is concurrency managed and hogged the CPU for
1353616db877STejun Heo 	 * longer than wq_cpu_intensive_thresh_us, it's automatically marked
1354616db877STejun Heo 	 * CPU_INTENSIVE to avoid stalling other concurrency-managed work items.
1355c8f6219bSZqiang 	 *
1356c8f6219bSZqiang 	 * Set @worker->sleeping means that @worker is in the process of
1357c8f6219bSZqiang 	 * switching out voluntarily and won't be contributing to
1358c8f6219bSZqiang 	 * @pool->nr_running until it wakes up. As wq_worker_sleeping() also
1359c8f6219bSZqiang 	 * decrements ->nr_running, setting CPU_INTENSIVE here can lead to
1360c8f6219bSZqiang 	 * double decrements. The task is releasing the CPU anyway. Let's skip.
1361c8f6219bSZqiang 	 * We probably want to make this prettier in the future.
1362616db877STejun Heo 	 */
1363c8f6219bSZqiang 	if ((worker->flags & WORKER_NOT_RUNNING) || READ_ONCE(worker->sleeping) ||
1364616db877STejun Heo 	    worker->task->se.sum_exec_runtime - worker->current_at <
1365616db877STejun Heo 	    wq_cpu_intensive_thresh_us * NSEC_PER_USEC)
1366616db877STejun Heo 		return;
1367616db877STejun Heo 
1368616db877STejun Heo 	raw_spin_lock(&pool->lock);
1369616db877STejun Heo 
1370616db877STejun Heo 	worker_set_flags(worker, WORKER_CPU_INTENSIVE);
137163638450STejun Heo 	wq_cpu_intensive_report(worker->current_func);
1372616db877STejun Heo 	pwq->stats[PWQ_STAT_CPU_INTENSIVE]++;
1373616db877STejun Heo 
13740219a352STejun Heo 	if (kick_pool(pool))
1375616db877STejun Heo 		pwq->stats[PWQ_STAT_CM_WAKEUP]++;
1376616db877STejun Heo 
1377616db877STejun Heo 	raw_spin_unlock(&pool->lock);
1378616db877STejun Heo }
1379616db877STejun Heo 
1380616db877STejun Heo /**
13811da177e4SLinus Torvalds  * wq_worker_last_func - retrieve worker's last work function
13821da177e4SLinus Torvalds  * @task: Task to retrieve last work function of.
13831da177e4SLinus Torvalds  *
13841da177e4SLinus Torvalds  * Determine the last function a worker executed. This is called from
13851da177e4SLinus Torvalds  * the scheduler to get a worker's last known identity.
13861da177e4SLinus Torvalds  *
13871da177e4SLinus Torvalds  * CONTEXT:
13889b41ea72SAndrew Morton  * raw_spin_lock_irq(rq->lock)
13891da177e4SLinus Torvalds  *
13901da177e4SLinus Torvalds  * This function is called during schedule() when a kworker is going
1391f756d5e2SNathan Lynch  * to sleep. It's used by psi to identify aggregation workers during
1392f756d5e2SNathan Lynch  * dequeuing, to allow periodic aggregation to shut-off when that
13931da177e4SLinus Torvalds  * worker is the last task in the system or cgroup to go to sleep.
13941da177e4SLinus Torvalds  *
13951da177e4SLinus Torvalds  * As this function doesn't involve any workqueue-related locking, it
13961da177e4SLinus Torvalds  * only returns stable values when called from inside the scheduler's
13971da177e4SLinus Torvalds  * queuing and dequeuing paths, when @task, which must be a kworker,
13981da177e4SLinus Torvalds  * is guaranteed to not be processing any works.
1399365970a1SDavid Howells  *
1400365970a1SDavid Howells  * Return:
1401365970a1SDavid Howells  * The last work function %current executed as a worker, NULL if it
1402365970a1SDavid Howells  * hasn't executed any work yet.
1403365970a1SDavid Howells  */
1404365970a1SDavid Howells work_func_t wq_worker_last_func(struct task_struct *task)
1405365970a1SDavid Howells {
1406365970a1SDavid Howells 	struct worker *worker = kthread_data(task);
1407365970a1SDavid Howells 
1408365970a1SDavid Howells 	return worker->last_func;
1409365970a1SDavid Howells }
1410365970a1SDavid Howells 
1411d302f017STejun Heo /**
14128864b4e5STejun Heo  * get_pwq - get an extra reference on the specified pool_workqueue
14138864b4e5STejun Heo  * @pwq: pool_workqueue to get
14148864b4e5STejun Heo  *
14158864b4e5STejun Heo  * Obtain an extra reference on @pwq.  The caller should guarantee that
14168864b4e5STejun Heo  * @pwq has positive refcnt and be holding the matching pool->lock.
14178864b4e5STejun Heo  */
14188864b4e5STejun Heo static void get_pwq(struct pool_workqueue *pwq)
14198864b4e5STejun Heo {
14208864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
14218864b4e5STejun Heo 	WARN_ON_ONCE(pwq->refcnt <= 0);
14228864b4e5STejun Heo 	pwq->refcnt++;
14238864b4e5STejun Heo }
14248864b4e5STejun Heo 
14258864b4e5STejun Heo /**
14268864b4e5STejun Heo  * put_pwq - put a pool_workqueue reference
14278864b4e5STejun Heo  * @pwq: pool_workqueue to put
14288864b4e5STejun Heo  *
14298864b4e5STejun Heo  * Drop a reference of @pwq.  If its refcnt reaches zero, schedule its
14308864b4e5STejun Heo  * destruction.  The caller should be holding the matching pool->lock.
14318864b4e5STejun Heo  */
14328864b4e5STejun Heo static void put_pwq(struct pool_workqueue *pwq)
14338864b4e5STejun Heo {
14348864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
14358864b4e5STejun Heo 	if (likely(--pwq->refcnt))
14368864b4e5STejun Heo 		return;
14378864b4e5STejun Heo 	/*
1438967b494eSTejun Heo 	 * @pwq can't be released under pool->lock, bounce to a dedicated
1439967b494eSTejun Heo 	 * kthread_worker to avoid A-A deadlocks.
14408864b4e5STejun Heo 	 */
1441687a9aa5STejun Heo 	kthread_queue_work(pwq_release_worker, &pwq->release_work);
14428864b4e5STejun Heo }
14438864b4e5STejun Heo 
1444dce90d47STejun Heo /**
1445dce90d47STejun Heo  * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1446dce90d47STejun Heo  * @pwq: pool_workqueue to put (can be %NULL)
1447dce90d47STejun Heo  *
1448dce90d47STejun Heo  * put_pwq() with locking.  This function also allows %NULL @pwq.
1449dce90d47STejun Heo  */
1450dce90d47STejun Heo static void put_pwq_unlocked(struct pool_workqueue *pwq)
1451dce90d47STejun Heo {
1452dce90d47STejun Heo 	if (pwq) {
1453dce90d47STejun Heo 		/*
145424acfb71SThomas Gleixner 		 * As both pwqs and pools are RCU protected, the
1455dce90d47STejun Heo 		 * following lock operations are safe.
1456dce90d47STejun Heo 		 */
1457a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
1458dce90d47STejun Heo 		put_pwq(pwq);
1459a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
1460dce90d47STejun Heo 	}
1461dce90d47STejun Heo }
1462dce90d47STejun Heo 
1463afa87ce8STejun Heo static bool pwq_is_empty(struct pool_workqueue *pwq)
1464afa87ce8STejun Heo {
1465afa87ce8STejun Heo 	return !pwq->nr_active && list_empty(&pwq->inactive_works);
1466afa87ce8STejun Heo }
1467afa87ce8STejun Heo 
14684c638030STejun Heo static void __pwq_activate_work(struct pool_workqueue *pwq,
14694c638030STejun Heo 				struct work_struct *work)
1470bf4ede01STejun Heo {
14711c270b79STejun Heo 	unsigned long *wdb = work_data_bits(work);
14721c270b79STejun Heo 
14731c270b79STejun Heo 	WARN_ON_ONCE(!(*wdb & WORK_STRUCT_INACTIVE));
1474bf4ede01STejun Heo 	trace_workqueue_activate_work(work);
147582607adcSTejun Heo 	if (list_empty(&pwq->pool->worklist))
147682607adcSTejun Heo 		pwq->pool->watchdog_ts = jiffies;
1477112202d9STejun Heo 	move_linked_works(work, &pwq->pool->worklist, NULL);
14781c270b79STejun Heo 	__clear_bit(WORK_STRUCT_INACTIVE_BIT, wdb);
14794c638030STejun Heo }
14804c638030STejun Heo 
14814c638030STejun Heo /**
14824c638030STejun Heo  * pwq_activate_work - Activate a work item if inactive
14834c638030STejun Heo  * @pwq: pool_workqueue @work belongs to
14844c638030STejun Heo  * @work: work item to activate
14854c638030STejun Heo  *
14864c638030STejun Heo  * Returns %true if activated. %false if already active.
14874c638030STejun Heo  */
14884c638030STejun Heo static bool pwq_activate_work(struct pool_workqueue *pwq,
14894c638030STejun Heo 			      struct work_struct *work)
14904c638030STejun Heo {
14914c638030STejun Heo 	struct worker_pool *pool = pwq->pool;
14924c638030STejun Heo 
14934c638030STejun Heo 	lockdep_assert_held(&pool->lock);
14944c638030STejun Heo 
14954c638030STejun Heo 	if (!(*work_data_bits(work) & WORK_STRUCT_INACTIVE))
14964c638030STejun Heo 		return false;
14974c638030STejun Heo 
1498112202d9STejun Heo 	pwq->nr_active++;
14994c638030STejun Heo 	__pwq_activate_work(pwq, work);
15004c638030STejun Heo 	return true;
1501bf4ede01STejun Heo }
1502bf4ede01STejun Heo 
15031c270b79STejun Heo /**
15041c270b79STejun Heo  * pwq_tryinc_nr_active - Try to increment nr_active for a pwq
15051c270b79STejun Heo  * @pwq: pool_workqueue of interest
15061c270b79STejun Heo  *
15071c270b79STejun Heo  * Try to increment nr_active for @pwq. Returns %true if an nr_active count is
15081c270b79STejun Heo  * successfully obtained. %false otherwise.
15091c270b79STejun Heo  */
15101c270b79STejun Heo static bool pwq_tryinc_nr_active(struct pool_workqueue *pwq)
15113aa62497SLai Jiangshan {
15121c270b79STejun Heo 	struct workqueue_struct *wq = pwq->wq;
15131c270b79STejun Heo 	struct worker_pool *pool = pwq->pool;
15141c270b79STejun Heo 	bool obtained;
15151c270b79STejun Heo 
15161c270b79STejun Heo 	lockdep_assert_held(&pool->lock);
15171c270b79STejun Heo 
15181c270b79STejun Heo 	obtained = pwq->nr_active < READ_ONCE(wq->max_active);
15191c270b79STejun Heo 
15201c270b79STejun Heo 	if (obtained)
15211c270b79STejun Heo 		pwq->nr_active++;
15221c270b79STejun Heo 	return obtained;
15231c270b79STejun Heo }
15241c270b79STejun Heo 
15251c270b79STejun Heo /**
15261c270b79STejun Heo  * pwq_activate_first_inactive - Activate the first inactive work item on a pwq
15271c270b79STejun Heo  * @pwq: pool_workqueue of interest
15281c270b79STejun Heo  *
15291c270b79STejun Heo  * Activate the first inactive work item of @pwq if available and allowed by
15301c270b79STejun Heo  * max_active limit.
15311c270b79STejun Heo  *
15321c270b79STejun Heo  * Returns %true if an inactive work item has been activated. %false if no
15331c270b79STejun Heo  * inactive work item is found or max_active limit is reached.
15341c270b79STejun Heo  */
15351c270b79STejun Heo static bool pwq_activate_first_inactive(struct pool_workqueue *pwq)
15361c270b79STejun Heo {
15371c270b79STejun Heo 	struct work_struct *work =
15381c270b79STejun Heo 		list_first_entry_or_null(&pwq->inactive_works,
15393aa62497SLai Jiangshan 					 struct work_struct, entry);
15403aa62497SLai Jiangshan 
15411c270b79STejun Heo 	if (work && pwq_tryinc_nr_active(pwq)) {
15421c270b79STejun Heo 		__pwq_activate_work(pwq, work);
15431c270b79STejun Heo 		return true;
15441c270b79STejun Heo 	} else {
15451c270b79STejun Heo 		return false;
15461c270b79STejun Heo 	}
15471c270b79STejun Heo }
15481c270b79STejun Heo 
15491c270b79STejun Heo /**
15501c270b79STejun Heo  * pwq_dec_nr_active - Retire an active count
15511c270b79STejun Heo  * @pwq: pool_workqueue of interest
15521c270b79STejun Heo  *
15531c270b79STejun Heo  * Decrement @pwq's nr_active and try to activate the first inactive work item.
15541c270b79STejun Heo  */
15551c270b79STejun Heo static void pwq_dec_nr_active(struct pool_workqueue *pwq)
15561c270b79STejun Heo {
15571c270b79STejun Heo 	struct worker_pool *pool = pwq->pool;
15581c270b79STejun Heo 
15591c270b79STejun Heo 	lockdep_assert_held(&pool->lock);
15601c270b79STejun Heo 
15611c270b79STejun Heo 	pwq->nr_active--;
15621c270b79STejun Heo 	pwq_activate_first_inactive(pwq);
15633aa62497SLai Jiangshan }
15643aa62497SLai Jiangshan 
1565bf4ede01STejun Heo /**
1566112202d9STejun Heo  * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1567112202d9STejun Heo  * @pwq: pwq of interest
1568c4560c2cSLai Jiangshan  * @work_data: work_data of work which left the queue
1569bf4ede01STejun Heo  *
1570bf4ede01STejun Heo  * A work either has completed or is removed from pending queue,
1571112202d9STejun Heo  * decrement nr_in_flight of its pwq and handle workqueue flushing.
1572bf4ede01STejun Heo  *
1573bf4ede01STejun Heo  * CONTEXT:
1574a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1575bf4ede01STejun Heo  */
1576c4560c2cSLai Jiangshan static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data)
1577bf4ede01STejun Heo {
1578c4560c2cSLai Jiangshan 	int color = get_work_color(work_data);
1579c4560c2cSLai Jiangshan 
15801c270b79STejun Heo 	if (!(work_data & WORK_STRUCT_INACTIVE))
15811c270b79STejun Heo 		pwq_dec_nr_active(pwq);
1582018f3a13SLai Jiangshan 
1583018f3a13SLai Jiangshan 	pwq->nr_in_flight[color]--;
1584bf4ede01STejun Heo 
1585bf4ede01STejun Heo 	/* is flush in progress and are we at the flushing tip? */
1586112202d9STejun Heo 	if (likely(pwq->flush_color != color))
15878864b4e5STejun Heo 		goto out_put;
1588bf4ede01STejun Heo 
1589bf4ede01STejun Heo 	/* are there still in-flight works? */
1590112202d9STejun Heo 	if (pwq->nr_in_flight[color])
15918864b4e5STejun Heo 		goto out_put;
1592bf4ede01STejun Heo 
1593112202d9STejun Heo 	/* this pwq is done, clear flush_color */
1594112202d9STejun Heo 	pwq->flush_color = -1;
1595bf4ede01STejun Heo 
1596bf4ede01STejun Heo 	/*
1597112202d9STejun Heo 	 * If this was the last pwq, wake up the first flusher.  It
1598bf4ede01STejun Heo 	 * will handle the rest.
1599bf4ede01STejun Heo 	 */
1600112202d9STejun Heo 	if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1601112202d9STejun Heo 		complete(&pwq->wq->first_flusher->done);
16028864b4e5STejun Heo out_put:
16038864b4e5STejun Heo 	put_pwq(pwq);
1604bf4ede01STejun Heo }
1605bf4ede01STejun Heo 
160636e227d2STejun Heo /**
1607bbb68dfaSTejun Heo  * try_to_grab_pending - steal work item from worklist and disable irq
160836e227d2STejun Heo  * @work: work item to steal
160936e227d2STejun Heo  * @is_dwork: @work is a delayed_work
1610bbb68dfaSTejun Heo  * @flags: place to store irq state
161136e227d2STejun Heo  *
161236e227d2STejun Heo  * Try to grab PENDING bit of @work.  This function can handle @work in any
1613d185af30SYacine Belkadi  * stable state - idle, on timer or on worklist.
161436e227d2STejun Heo  *
1615d185af30SYacine Belkadi  * Return:
16163eb6b31bSMauro Carvalho Chehab  *
16173eb6b31bSMauro Carvalho Chehab  *  ========	================================================================
161836e227d2STejun Heo  *  1		if @work was pending and we successfully stole PENDING
161936e227d2STejun Heo  *  0		if @work was idle and we claimed PENDING
162036e227d2STejun Heo  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
1621bbb68dfaSTejun Heo  *  -ENOENT	if someone else is canceling @work, this state may persist
1622bbb68dfaSTejun Heo  *		for arbitrarily long
16233eb6b31bSMauro Carvalho Chehab  *  ========	================================================================
162436e227d2STejun Heo  *
1625d185af30SYacine Belkadi  * Note:
1626bbb68dfaSTejun Heo  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
1627e0aecdd8STejun Heo  * interrupted while holding PENDING and @work off queue, irq must be
1628e0aecdd8STejun Heo  * disabled on entry.  This, combined with delayed_work->timer being
1629e0aecdd8STejun Heo  * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1630bbb68dfaSTejun Heo  *
1631bbb68dfaSTejun Heo  * On successful return, >= 0, irq is disabled and the caller is
1632bbb68dfaSTejun Heo  * responsible for releasing it using local_irq_restore(*@flags).
1633bbb68dfaSTejun Heo  *
1634e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
1635bf4ede01STejun Heo  */
1636bbb68dfaSTejun Heo static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1637bbb68dfaSTejun Heo 			       unsigned long *flags)
1638bf4ede01STejun Heo {
1639d565ed63STejun Heo 	struct worker_pool *pool;
1640112202d9STejun Heo 	struct pool_workqueue *pwq;
1641bf4ede01STejun Heo 
1642bbb68dfaSTejun Heo 	local_irq_save(*flags);
1643bbb68dfaSTejun Heo 
164436e227d2STejun Heo 	/* try to steal the timer if it exists */
164536e227d2STejun Heo 	if (is_dwork) {
164636e227d2STejun Heo 		struct delayed_work *dwork = to_delayed_work(work);
164736e227d2STejun Heo 
1648e0aecdd8STejun Heo 		/*
1649e0aecdd8STejun Heo 		 * dwork->timer is irqsafe.  If del_timer() fails, it's
1650e0aecdd8STejun Heo 		 * guaranteed that the timer is not queued anywhere and not
1651e0aecdd8STejun Heo 		 * running on the local CPU.
1652e0aecdd8STejun Heo 		 */
165336e227d2STejun Heo 		if (likely(del_timer(&dwork->timer)))
165436e227d2STejun Heo 			return 1;
165536e227d2STejun Heo 	}
165636e227d2STejun Heo 
165736e227d2STejun Heo 	/* try to claim PENDING the normal way */
1658bf4ede01STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1659bf4ede01STejun Heo 		return 0;
1660bf4ede01STejun Heo 
166124acfb71SThomas Gleixner 	rcu_read_lock();
1662bf4ede01STejun Heo 	/*
1663bf4ede01STejun Heo 	 * The queueing is in progress, or it is already queued. Try to
1664bf4ede01STejun Heo 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1665bf4ede01STejun Heo 	 */
1666d565ed63STejun Heo 	pool = get_work_pool(work);
1667d565ed63STejun Heo 	if (!pool)
1668bbb68dfaSTejun Heo 		goto fail;
1669bf4ede01STejun Heo 
1670a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock(&pool->lock);
1671bf4ede01STejun Heo 	/*
1672112202d9STejun Heo 	 * work->data is guaranteed to point to pwq only while the work
1673112202d9STejun Heo 	 * item is queued on pwq->wq, and both updating work->data to point
1674112202d9STejun Heo 	 * to pwq on queueing and to pool on dequeueing are done under
1675112202d9STejun Heo 	 * pwq->pool->lock.  This in turn guarantees that, if work->data
1676112202d9STejun Heo 	 * points to pwq which is associated with a locked pool, the work
16770b3dae68SLai Jiangshan 	 * item is currently queued on that pool.
1678bf4ede01STejun Heo 	 */
1679112202d9STejun Heo 	pwq = get_work_pwq(work);
1680112202d9STejun Heo 	if (pwq && pwq->pool == pool) {
1681bf4ede01STejun Heo 		debug_work_deactivate(work);
16823aa62497SLai Jiangshan 
16833aa62497SLai Jiangshan 		/*
1684018f3a13SLai Jiangshan 		 * A cancelable inactive work item must be in the
1685018f3a13SLai Jiangshan 		 * pwq->inactive_works since a queued barrier can't be
1686018f3a13SLai Jiangshan 		 * canceled (see the comments in insert_wq_barrier()).
1687018f3a13SLai Jiangshan 		 *
1688f97a4a1aSLai Jiangshan 		 * An inactive work item cannot be grabbed directly because
1689d812796eSLai Jiangshan 		 * it might have linked barrier work items which, if left
1690f97a4a1aSLai Jiangshan 		 * on the inactive_works list, will confuse pwq->nr_active
169116062836STejun Heo 		 * management later on and cause stall.  Make sure the work
169216062836STejun Heo 		 * item is activated before grabbing.
16933aa62497SLai Jiangshan 		 */
16944c638030STejun Heo 		pwq_activate_work(pwq, work);
16953aa62497SLai Jiangshan 
1696bf4ede01STejun Heo 		list_del_init(&work->entry);
1697c4560c2cSLai Jiangshan 		pwq_dec_nr_in_flight(pwq, *work_data_bits(work));
169836e227d2STejun Heo 
1699112202d9STejun Heo 		/* work->data points to pwq iff queued, point to pool */
17004468a00fSLai Jiangshan 		set_work_pool_and_keep_pending(work, pool->id);
17014468a00fSLai Jiangshan 
1702a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock(&pool->lock);
170324acfb71SThomas Gleixner 		rcu_read_unlock();
170436e227d2STejun Heo 		return 1;
1705bf4ede01STejun Heo 	}
1706a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&pool->lock);
1707bbb68dfaSTejun Heo fail:
170824acfb71SThomas Gleixner 	rcu_read_unlock();
1709bbb68dfaSTejun Heo 	local_irq_restore(*flags);
1710bbb68dfaSTejun Heo 	if (work_is_canceling(work))
1711bbb68dfaSTejun Heo 		return -ENOENT;
1712bbb68dfaSTejun Heo 	cpu_relax();
171336e227d2STejun Heo 	return -EAGAIN;
1714bf4ede01STejun Heo }
1715bf4ede01STejun Heo 
1716bf4ede01STejun Heo /**
1717706026c2STejun Heo  * insert_work - insert a work into a pool
1718112202d9STejun Heo  * @pwq: pwq @work belongs to
17194690c4abSTejun Heo  * @work: work to insert
17204690c4abSTejun Heo  * @head: insertion point
17214690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
17224690c4abSTejun Heo  *
1723112202d9STejun Heo  * Insert @work which belongs to @pwq after @head.  @extra_flags is or'd to
1724706026c2STejun Heo  * work_struct flags.
17254690c4abSTejun Heo  *
17264690c4abSTejun Heo  * CONTEXT:
1727a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1728365970a1SDavid Howells  */
1729112202d9STejun Heo static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1730112202d9STejun Heo 			struct list_head *head, unsigned int extra_flags)
1731b89deed3SOleg Nesterov {
1732fe089f87STejun Heo 	debug_work_activate(work);
1733e1d8aa9fSFrederic Weisbecker 
1734e89a85d6SWalter Wu 	/* record the work call stack in order to print it in KASAN reports */
1735f70da745SMarco Elver 	kasan_record_aux_stack_noalloc(work);
1736e89a85d6SWalter Wu 
17374690c4abSTejun Heo 	/* we own @work, set data and link */
1738112202d9STejun Heo 	set_work_pwq(work, pwq, extra_flags);
17391a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
17408864b4e5STejun Heo 	get_pwq(pwq);
1741b89deed3SOleg Nesterov }
1742b89deed3SOleg Nesterov 
1743c8efcc25STejun Heo /*
1744c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
17458d03ecfeSTejun Heo  * same workqueue.
1746c8efcc25STejun Heo  */
1747c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
1748c8efcc25STejun Heo {
1749c8efcc25STejun Heo 	struct worker *worker;
1750c8efcc25STejun Heo 
17518d03ecfeSTejun Heo 	worker = current_wq_worker();
1752c8efcc25STejun Heo 	/*
1753bf393fd4SBart Van Assche 	 * Return %true iff I'm a worker executing a work item on @wq.  If
17548d03ecfeSTejun Heo 	 * I'm @worker, it's safe to dereference it without locking.
1755c8efcc25STejun Heo 	 */
1756112202d9STejun Heo 	return worker && worker->current_pwq->wq == wq;
1757c8efcc25STejun Heo }
1758c8efcc25STejun Heo 
1759ef557180SMike Galbraith /*
1760ef557180SMike Galbraith  * When queueing an unbound work item to a wq, prefer local CPU if allowed
1761ef557180SMike Galbraith  * by wq_unbound_cpumask.  Otherwise, round robin among the allowed ones to
1762ef557180SMike Galbraith  * avoid perturbing sensitive tasks.
1763ef557180SMike Galbraith  */
1764ef557180SMike Galbraith static int wq_select_unbound_cpu(int cpu)
1765ef557180SMike Galbraith {
1766ef557180SMike Galbraith 	int new_cpu;
1767ef557180SMike Galbraith 
1768f303fccbSTejun Heo 	if (likely(!wq_debug_force_rr_cpu)) {
1769ef557180SMike Galbraith 		if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
1770ef557180SMike Galbraith 			return cpu;
1771a8ec5880SAmmar Faizi 	} else {
1772a8ec5880SAmmar Faizi 		pr_warn_once("workqueue: round-robin CPU selection forced, expect performance impact\n");
1773f303fccbSTejun Heo 	}
1774f303fccbSTejun Heo 
1775ef557180SMike Galbraith 	new_cpu = __this_cpu_read(wq_rr_cpu_last);
1776ef557180SMike Galbraith 	new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
1777ef557180SMike Galbraith 	if (unlikely(new_cpu >= nr_cpu_ids)) {
1778ef557180SMike Galbraith 		new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
1779ef557180SMike Galbraith 		if (unlikely(new_cpu >= nr_cpu_ids))
1780ef557180SMike Galbraith 			return cpu;
1781ef557180SMike Galbraith 	}
1782ef557180SMike Galbraith 	__this_cpu_write(wq_rr_cpu_last, new_cpu);
1783ef557180SMike Galbraith 
1784ef557180SMike Galbraith 	return new_cpu;
1785ef557180SMike Galbraith }
1786ef557180SMike Galbraith 
1787d84ff051STejun Heo static void __queue_work(int cpu, struct workqueue_struct *wq,
17881da177e4SLinus Torvalds 			 struct work_struct *work)
17891da177e4SLinus Torvalds {
1790112202d9STejun Heo 	struct pool_workqueue *pwq;
1791fe089f87STejun Heo 	struct worker_pool *last_pool, *pool;
17928a2e8e5dSTejun Heo 	unsigned int work_flags;
1793b75cac93SJoonsoo Kim 	unsigned int req_cpu = cpu;
17948930cabaSTejun Heo 
17958930cabaSTejun Heo 	/*
17968930cabaSTejun Heo 	 * While a work item is PENDING && off queue, a task trying to
17978930cabaSTejun Heo 	 * steal the PENDING will busy-loop waiting for it to either get
17988930cabaSTejun Heo 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
17998930cabaSTejun Heo 	 * happen with IRQ disabled.
18008930cabaSTejun Heo 	 */
18018e8eb730SFrederic Weisbecker 	lockdep_assert_irqs_disabled();
18021da177e4SLinus Torvalds 
18031e19ffc6STejun Heo 
180433e3f0a3SRichard Clark 	/*
180533e3f0a3SRichard Clark 	 * For a draining wq, only works from the same workqueue are
180633e3f0a3SRichard Clark 	 * allowed. The __WQ_DESTROYING helps to spot the issue that
180733e3f0a3SRichard Clark 	 * queues a new work item to a wq after destroy_workqueue(wq).
180833e3f0a3SRichard Clark 	 */
180933e3f0a3SRichard Clark 	if (unlikely(wq->flags & (__WQ_DESTROYING | __WQ_DRAINING) &&
181033e3f0a3SRichard Clark 		     WARN_ON_ONCE(!is_chained_work(wq))))
1811e41e704bSTejun Heo 		return;
181224acfb71SThomas Gleixner 	rcu_read_lock();
18139e8cd2f5STejun Heo retry:
1814aa202f1fSHillf Danton 	/* pwq which will be used unless @work is executing elsewhere */
1815636b927eSTejun Heo 	if (req_cpu == WORK_CPU_UNBOUND) {
1816636b927eSTejun Heo 		if (wq->flags & WQ_UNBOUND)
1817ef557180SMike Galbraith 			cpu = wq_select_unbound_cpu(raw_smp_processor_id());
1818636b927eSTejun Heo 		else
1819aa202f1fSHillf Danton 			cpu = raw_smp_processor_id();
1820aa202f1fSHillf Danton 	}
1821f3421797STejun Heo 
1822636b927eSTejun Heo 	pwq = rcu_dereference(*per_cpu_ptr(wq->cpu_pwq, cpu));
1823fe089f87STejun Heo 	pool = pwq->pool;
1824fe089f87STejun Heo 
182518aa9effSTejun Heo 	/*
1826c9178087STejun Heo 	 * If @work was previously on a different pool, it might still be
1827c9178087STejun Heo 	 * running there, in which case the work needs to be queued on that
1828c9178087STejun Heo 	 * pool to guarantee non-reentrancy.
182918aa9effSTejun Heo 	 */
1830c9e7cf27STejun Heo 	last_pool = get_work_pool(work);
1831fe089f87STejun Heo 	if (last_pool && last_pool != pool) {
183218aa9effSTejun Heo 		struct worker *worker;
183318aa9effSTejun Heo 
1834a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock(&last_pool->lock);
183518aa9effSTejun Heo 
1836c9e7cf27STejun Heo 		worker = find_worker_executing_work(last_pool, work);
183718aa9effSTejun Heo 
1838112202d9STejun Heo 		if (worker && worker->current_pwq->wq == wq) {
1839c9178087STejun Heo 			pwq = worker->current_pwq;
1840fe089f87STejun Heo 			pool = pwq->pool;
1841fe089f87STejun Heo 			WARN_ON_ONCE(pool != last_pool);
18428594fadeSLai Jiangshan 		} else {
184318aa9effSTejun Heo 			/* meh... not running there, queue here */
1844a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock(&last_pool->lock);
1845fe089f87STejun Heo 			raw_spin_lock(&pool->lock);
184618aa9effSTejun Heo 		}
18478930cabaSTejun Heo 	} else {
1848fe089f87STejun Heo 		raw_spin_lock(&pool->lock);
18498930cabaSTejun Heo 	}
1850502ca9d8STejun Heo 
18519e8cd2f5STejun Heo 	/*
1852636b927eSTejun Heo 	 * pwq is determined and locked. For unbound pools, we could have raced
1853636b927eSTejun Heo 	 * with pwq release and it could already be dead. If its refcnt is zero,
1854636b927eSTejun Heo 	 * repeat pwq selection. Note that unbound pwqs never die without
1855636b927eSTejun Heo 	 * another pwq replacing it in cpu_pwq or while work items are executing
1856636b927eSTejun Heo 	 * on it, so the retrying is guaranteed to make forward-progress.
18579e8cd2f5STejun Heo 	 */
18589e8cd2f5STejun Heo 	if (unlikely(!pwq->refcnt)) {
18599e8cd2f5STejun Heo 		if (wq->flags & WQ_UNBOUND) {
1860fe089f87STejun Heo 			raw_spin_unlock(&pool->lock);
18619e8cd2f5STejun Heo 			cpu_relax();
18629e8cd2f5STejun Heo 			goto retry;
18639e8cd2f5STejun Heo 		}
18649e8cd2f5STejun Heo 		/* oops */
18659e8cd2f5STejun Heo 		WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
18669e8cd2f5STejun Heo 			  wq->name, cpu);
18679e8cd2f5STejun Heo 	}
18689e8cd2f5STejun Heo 
1869112202d9STejun Heo 	/* pwq determined, queue */
1870112202d9STejun Heo 	trace_workqueue_queue_work(req_cpu, pwq, work);
1871502ca9d8STejun Heo 
187224acfb71SThomas Gleixner 	if (WARN_ON(!list_empty(&work->entry)))
187324acfb71SThomas Gleixner 		goto out;
18741e19ffc6STejun Heo 
1875112202d9STejun Heo 	pwq->nr_in_flight[pwq->work_color]++;
1876112202d9STejun Heo 	work_flags = work_color_to_flags(pwq->work_color);
18771e19ffc6STejun Heo 
1878a045a272STejun Heo 	/*
1879a045a272STejun Heo 	 * Limit the number of concurrently active work items to max_active.
1880a045a272STejun Heo 	 * @work must also queue behind existing inactive work items to maintain
1881a045a272STejun Heo 	 * ordering when max_active changes. See wq_adjust_max_active().
1882a045a272STejun Heo 	 */
18831c270b79STejun Heo 	if (list_empty(&pwq->inactive_works) && pwq_tryinc_nr_active(pwq)) {
1884fe089f87STejun Heo 		if (list_empty(&pool->worklist))
1885fe089f87STejun Heo 			pool->watchdog_ts = jiffies;
1886fe089f87STejun Heo 
1887cdadf009STejun Heo 		trace_workqueue_activate_work(work);
1888fe089f87STejun Heo 		insert_work(pwq, work, &pool->worklist, work_flags);
18890219a352STejun Heo 		kick_pool(pool);
18908a2e8e5dSTejun Heo 	} else {
1891f97a4a1aSLai Jiangshan 		work_flags |= WORK_STRUCT_INACTIVE;
1892fe089f87STejun Heo 		insert_work(pwq, work, &pwq->inactive_works, work_flags);
18938a2e8e5dSTejun Heo 	}
18941e19ffc6STejun Heo 
189524acfb71SThomas Gleixner out:
1896fe089f87STejun Heo 	raw_spin_unlock(&pool->lock);
189724acfb71SThomas Gleixner 	rcu_read_unlock();
18981da177e4SLinus Torvalds }
18991da177e4SLinus Torvalds 
19000fcb78c2SRolf Eike Beer /**
1901c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
1902c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
1903c1a220e7SZhang Rui  * @wq: workqueue to use
1904c1a220e7SZhang Rui  * @work: work to queue
1905c1a220e7SZhang Rui  *
1906c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
1907443378f0SPaul E. McKenney  * can't go away.  Callers that fail to ensure that the specified
1908443378f0SPaul E. McKenney  * CPU cannot go away will execute on a randomly chosen CPU.
1909854f5cc5SPaul E. McKenney  * But note well that callers specifying a CPU that never has been
1910854f5cc5SPaul E. McKenney  * online will get a splat.
1911d185af30SYacine Belkadi  *
1912d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.
1913c1a220e7SZhang Rui  */
1914d4283e93STejun Heo bool queue_work_on(int cpu, struct workqueue_struct *wq,
1915d4283e93STejun Heo 		   struct work_struct *work)
1916c1a220e7SZhang Rui {
1917d4283e93STejun Heo 	bool ret = false;
19188930cabaSTejun Heo 	unsigned long flags;
19198930cabaSTejun Heo 
19208930cabaSTejun Heo 	local_irq_save(flags);
1921c1a220e7SZhang Rui 
192222df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
19234690c4abSTejun Heo 		__queue_work(cpu, wq, work);
1924d4283e93STejun Heo 		ret = true;
1925c1a220e7SZhang Rui 	}
19268930cabaSTejun Heo 
19278930cabaSTejun Heo 	local_irq_restore(flags);
1928c1a220e7SZhang Rui 	return ret;
1929c1a220e7SZhang Rui }
1930ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_work_on);
1931c1a220e7SZhang Rui 
19328204e0c1SAlexander Duyck /**
1933fef59c9cSTejun Heo  * select_numa_node_cpu - Select a CPU based on NUMA node
19348204e0c1SAlexander Duyck  * @node: NUMA node ID that we want to select a CPU from
19358204e0c1SAlexander Duyck  *
19368204e0c1SAlexander Duyck  * This function will attempt to find a "random" cpu available on a given
19378204e0c1SAlexander Duyck  * node. If there are no CPUs available on the given node it will return
19388204e0c1SAlexander Duyck  * WORK_CPU_UNBOUND indicating that we should just schedule to any
19398204e0c1SAlexander Duyck  * available CPU if we need to schedule this work.
19408204e0c1SAlexander Duyck  */
1941fef59c9cSTejun Heo static int select_numa_node_cpu(int node)
19428204e0c1SAlexander Duyck {
19438204e0c1SAlexander Duyck 	int cpu;
19448204e0c1SAlexander Duyck 
19458204e0c1SAlexander Duyck 	/* Delay binding to CPU if node is not valid or online */
19468204e0c1SAlexander Duyck 	if (node < 0 || node >= MAX_NUMNODES || !node_online(node))
19478204e0c1SAlexander Duyck 		return WORK_CPU_UNBOUND;
19488204e0c1SAlexander Duyck 
19498204e0c1SAlexander Duyck 	/* Use local node/cpu if we are already there */
19508204e0c1SAlexander Duyck 	cpu = raw_smp_processor_id();
19518204e0c1SAlexander Duyck 	if (node == cpu_to_node(cpu))
19528204e0c1SAlexander Duyck 		return cpu;
19538204e0c1SAlexander Duyck 
19548204e0c1SAlexander Duyck 	/* Use "random" otherwise know as "first" online CPU of node */
19558204e0c1SAlexander Duyck 	cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
19568204e0c1SAlexander Duyck 
19578204e0c1SAlexander Duyck 	/* If CPU is valid return that, otherwise just defer */
19588204e0c1SAlexander Duyck 	return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND;
19598204e0c1SAlexander Duyck }
19608204e0c1SAlexander Duyck 
19618204e0c1SAlexander Duyck /**
19628204e0c1SAlexander Duyck  * queue_work_node - queue work on a "random" cpu for a given NUMA node
19638204e0c1SAlexander Duyck  * @node: NUMA node that we are targeting the work for
19648204e0c1SAlexander Duyck  * @wq: workqueue to use
19658204e0c1SAlexander Duyck  * @work: work to queue
19668204e0c1SAlexander Duyck  *
19678204e0c1SAlexander Duyck  * We queue the work to a "random" CPU within a given NUMA node. The basic
19688204e0c1SAlexander Duyck  * idea here is to provide a way to somehow associate work with a given
19698204e0c1SAlexander Duyck  * NUMA node.
19708204e0c1SAlexander Duyck  *
19718204e0c1SAlexander Duyck  * This function will only make a best effort attempt at getting this onto
19728204e0c1SAlexander Duyck  * the right NUMA node. If no node is requested or the requested node is
19738204e0c1SAlexander Duyck  * offline then we just fall back to standard queue_work behavior.
19748204e0c1SAlexander Duyck  *
19758204e0c1SAlexander Duyck  * Currently the "random" CPU ends up being the first available CPU in the
19768204e0c1SAlexander Duyck  * intersection of cpu_online_mask and the cpumask of the node, unless we
19778204e0c1SAlexander Duyck  * are running on the node. In that case we just use the current CPU.
19788204e0c1SAlexander Duyck  *
19798204e0c1SAlexander Duyck  * Return: %false if @work was already on a queue, %true otherwise.
19808204e0c1SAlexander Duyck  */
19818204e0c1SAlexander Duyck bool queue_work_node(int node, struct workqueue_struct *wq,
19828204e0c1SAlexander Duyck 		     struct work_struct *work)
19838204e0c1SAlexander Duyck {
19848204e0c1SAlexander Duyck 	unsigned long flags;
19858204e0c1SAlexander Duyck 	bool ret = false;
19868204e0c1SAlexander Duyck 
19878204e0c1SAlexander Duyck 	/*
19888204e0c1SAlexander Duyck 	 * This current implementation is specific to unbound workqueues.
19898204e0c1SAlexander Duyck 	 * Specifically we only return the first available CPU for a given
19908204e0c1SAlexander Duyck 	 * node instead of cycling through individual CPUs within the node.
19918204e0c1SAlexander Duyck 	 *
19928204e0c1SAlexander Duyck 	 * If this is used with a per-cpu workqueue then the logic in
19938204e0c1SAlexander Duyck 	 * workqueue_select_cpu_near would need to be updated to allow for
19948204e0c1SAlexander Duyck 	 * some round robin type logic.
19958204e0c1SAlexander Duyck 	 */
19968204e0c1SAlexander Duyck 	WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND));
19978204e0c1SAlexander Duyck 
19988204e0c1SAlexander Duyck 	local_irq_save(flags);
19998204e0c1SAlexander Duyck 
20008204e0c1SAlexander Duyck 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
2001fef59c9cSTejun Heo 		int cpu = select_numa_node_cpu(node);
20028204e0c1SAlexander Duyck 
20038204e0c1SAlexander Duyck 		__queue_work(cpu, wq, work);
20048204e0c1SAlexander Duyck 		ret = true;
20058204e0c1SAlexander Duyck 	}
20068204e0c1SAlexander Duyck 
20078204e0c1SAlexander Duyck 	local_irq_restore(flags);
20088204e0c1SAlexander Duyck 	return ret;
20098204e0c1SAlexander Duyck }
20108204e0c1SAlexander Duyck EXPORT_SYMBOL_GPL(queue_work_node);
20118204e0c1SAlexander Duyck 
20128c20feb6SKees Cook void delayed_work_timer_fn(struct timer_list *t)
20131da177e4SLinus Torvalds {
20148c20feb6SKees Cook 	struct delayed_work *dwork = from_timer(dwork, t, timer);
20151da177e4SLinus Torvalds 
2016e0aecdd8STejun Heo 	/* should have been called from irqsafe timer with irq already off */
201760c057bcSLai Jiangshan 	__queue_work(dwork->cpu, dwork->wq, &dwork->work);
20181da177e4SLinus Torvalds }
20191438ade5SKonstantin Khlebnikov EXPORT_SYMBOL(delayed_work_timer_fn);
20201da177e4SLinus Torvalds 
20217beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
202252bad64dSDavid Howells 				struct delayed_work *dwork, unsigned long delay)
20231da177e4SLinus Torvalds {
20247beb2edfSTejun Heo 	struct timer_list *timer = &dwork->timer;
20257beb2edfSTejun Heo 	struct work_struct *work = &dwork->work;
20261da177e4SLinus Torvalds 
2027637fdbaeSTejun Heo 	WARN_ON_ONCE(!wq);
20284b243563SSami Tolvanen 	WARN_ON_ONCE(timer->function != delayed_work_timer_fn);
2029fc4b514fSTejun Heo 	WARN_ON_ONCE(timer_pending(timer));
2030fc4b514fSTejun Heo 	WARN_ON_ONCE(!list_empty(&work->entry));
20317beb2edfSTejun Heo 
20328852aac2STejun Heo 	/*
20338852aac2STejun Heo 	 * If @delay is 0, queue @dwork->work immediately.  This is for
20348852aac2STejun Heo 	 * both optimization and correctness.  The earliest @timer can
20358852aac2STejun Heo 	 * expire is on the closest next tick and delayed_work users depend
20368852aac2STejun Heo 	 * on that there's no such delay when @delay is 0.
20378852aac2STejun Heo 	 */
20388852aac2STejun Heo 	if (!delay) {
20398852aac2STejun Heo 		__queue_work(cpu, wq, &dwork->work);
20408852aac2STejun Heo 		return;
20418852aac2STejun Heo 	}
20428852aac2STejun Heo 
204360c057bcSLai Jiangshan 	dwork->wq = wq;
20441265057fSTejun Heo 	dwork->cpu = cpu;
20457beb2edfSTejun Heo 	timer->expires = jiffies + delay;
20467beb2edfSTejun Heo 
2047041bd12eSTejun Heo 	if (unlikely(cpu != WORK_CPU_UNBOUND))
20487beb2edfSTejun Heo 		add_timer_on(timer, cpu);
2049041bd12eSTejun Heo 	else
2050041bd12eSTejun Heo 		add_timer(timer);
20517beb2edfSTejun Heo }
20521da177e4SLinus Torvalds 
20530fcb78c2SRolf Eike Beer /**
20540fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
20550fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
20560fcb78c2SRolf Eike Beer  * @wq: workqueue to use
2057af9997e4SRandy Dunlap  * @dwork: work to queue
20580fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
20590fcb78c2SRolf Eike Beer  *
2060d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.  If
2061715f1300STejun Heo  * @delay is zero and @dwork is idle, it will be scheduled for immediate
2062715f1300STejun Heo  * execution.
20630fcb78c2SRolf Eike Beer  */
2064d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
206552bad64dSDavid Howells 			   struct delayed_work *dwork, unsigned long delay)
20667a6bc1cdSVenkatesh Pallipadi {
206752bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
2068d4283e93STejun Heo 	bool ret = false;
20698930cabaSTejun Heo 	unsigned long flags;
20708930cabaSTejun Heo 
20718930cabaSTejun Heo 	/* read the comment in __queue_work() */
20728930cabaSTejun Heo 	local_irq_save(flags);
20737a6bc1cdSVenkatesh Pallipadi 
207422df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
20757beb2edfSTejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
2076d4283e93STejun Heo 		ret = true;
20777a6bc1cdSVenkatesh Pallipadi 	}
20788930cabaSTejun Heo 
20798930cabaSTejun Heo 	local_irq_restore(flags);
20807a6bc1cdSVenkatesh Pallipadi 	return ret;
20817a6bc1cdSVenkatesh Pallipadi }
2082ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_delayed_work_on);
20831da177e4SLinus Torvalds 
2084c8e55f36STejun Heo /**
20858376fe22STejun Heo  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
20868376fe22STejun Heo  * @cpu: CPU number to execute work on
20878376fe22STejun Heo  * @wq: workqueue to use
20888376fe22STejun Heo  * @dwork: work to queue
20898376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
20908376fe22STejun Heo  *
20918376fe22STejun Heo  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
20928376fe22STejun Heo  * modify @dwork's timer so that it expires after @delay.  If @delay is
20938376fe22STejun Heo  * zero, @work is guaranteed to be scheduled immediately regardless of its
20948376fe22STejun Heo  * current state.
20958376fe22STejun Heo  *
2096d185af30SYacine Belkadi  * Return: %false if @dwork was idle and queued, %true if @dwork was
20978376fe22STejun Heo  * pending and its timer was modified.
20988376fe22STejun Heo  *
2099e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
21008376fe22STejun Heo  * See try_to_grab_pending() for details.
21018376fe22STejun Heo  */
21028376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
21038376fe22STejun Heo 			 struct delayed_work *dwork, unsigned long delay)
21048376fe22STejun Heo {
21058376fe22STejun Heo 	unsigned long flags;
21068376fe22STejun Heo 	int ret;
21078376fe22STejun Heo 
21088376fe22STejun Heo 	do {
21098376fe22STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
21108376fe22STejun Heo 	} while (unlikely(ret == -EAGAIN));
21118376fe22STejun Heo 
21128376fe22STejun Heo 	if (likely(ret >= 0)) {
21138376fe22STejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
21148376fe22STejun Heo 		local_irq_restore(flags);
21158376fe22STejun Heo 	}
21168376fe22STejun Heo 
21178376fe22STejun Heo 	/* -ENOENT from try_to_grab_pending() becomes %true */
21188376fe22STejun Heo 	return ret;
21198376fe22STejun Heo }
21208376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
21218376fe22STejun Heo 
212205f0fe6bSTejun Heo static void rcu_work_rcufn(struct rcu_head *rcu)
212305f0fe6bSTejun Heo {
212405f0fe6bSTejun Heo 	struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
212505f0fe6bSTejun Heo 
212605f0fe6bSTejun Heo 	/* read the comment in __queue_work() */
212705f0fe6bSTejun Heo 	local_irq_disable();
212805f0fe6bSTejun Heo 	__queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
212905f0fe6bSTejun Heo 	local_irq_enable();
213005f0fe6bSTejun Heo }
213105f0fe6bSTejun Heo 
213205f0fe6bSTejun Heo /**
213305f0fe6bSTejun Heo  * queue_rcu_work - queue work after a RCU grace period
213405f0fe6bSTejun Heo  * @wq: workqueue to use
213505f0fe6bSTejun Heo  * @rwork: work to queue
213605f0fe6bSTejun Heo  *
213705f0fe6bSTejun Heo  * Return: %false if @rwork was already pending, %true otherwise.  Note
213805f0fe6bSTejun Heo  * that a full RCU grace period is guaranteed only after a %true return.
2139bf393fd4SBart Van Assche  * While @rwork is guaranteed to be executed after a %false return, the
214005f0fe6bSTejun Heo  * execution may happen before a full RCU grace period has passed.
214105f0fe6bSTejun Heo  */
214205f0fe6bSTejun Heo bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
214305f0fe6bSTejun Heo {
214405f0fe6bSTejun Heo 	struct work_struct *work = &rwork->work;
214505f0fe6bSTejun Heo 
214605f0fe6bSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
214705f0fe6bSTejun Heo 		rwork->wq = wq;
2148a7e30c0eSUladzislau Rezki 		call_rcu_hurry(&rwork->rcu, rcu_work_rcufn);
214905f0fe6bSTejun Heo 		return true;
215005f0fe6bSTejun Heo 	}
215105f0fe6bSTejun Heo 
215205f0fe6bSTejun Heo 	return false;
215305f0fe6bSTejun Heo }
215405f0fe6bSTejun Heo EXPORT_SYMBOL(queue_rcu_work);
215505f0fe6bSTejun Heo 
2156f7537df5SLai Jiangshan static struct worker *alloc_worker(int node)
2157c34056a3STejun Heo {
2158c34056a3STejun Heo 	struct worker *worker;
2159c34056a3STejun Heo 
2160f7537df5SLai Jiangshan 	worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
2161c8e55f36STejun Heo 	if (worker) {
2162c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
2163affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
2164da028469SLai Jiangshan 		INIT_LIST_HEAD(&worker->node);
2165e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
2166e22bee78STejun Heo 		worker->flags = WORKER_PREP;
2167c8e55f36STejun Heo 	}
2168c34056a3STejun Heo 	return worker;
2169c34056a3STejun Heo }
2170c34056a3STejun Heo 
21719546b29eSTejun Heo static cpumask_t *pool_allowed_cpus(struct worker_pool *pool)
21729546b29eSTejun Heo {
21738639ecebSTejun Heo 	if (pool->cpu < 0 && pool->attrs->affn_strict)
21749546b29eSTejun Heo 		return pool->attrs->__pod_cpumask;
21758639ecebSTejun Heo 	else
21768639ecebSTejun Heo 		return pool->attrs->cpumask;
21779546b29eSTejun Heo }
21789546b29eSTejun Heo 
2179c34056a3STejun Heo /**
21804736cbf7SLai Jiangshan  * worker_attach_to_pool() - attach a worker to a pool
21814736cbf7SLai Jiangshan  * @worker: worker to be attached
21824736cbf7SLai Jiangshan  * @pool: the target pool
21834736cbf7SLai Jiangshan  *
21844736cbf7SLai Jiangshan  * Attach @worker to @pool.  Once attached, the %WORKER_UNBOUND flag and
21854736cbf7SLai Jiangshan  * cpu-binding of @worker are kept coordinated with the pool across
21864736cbf7SLai Jiangshan  * cpu-[un]hotplugs.
21874736cbf7SLai Jiangshan  */
21884736cbf7SLai Jiangshan static void worker_attach_to_pool(struct worker *worker,
21894736cbf7SLai Jiangshan 				   struct worker_pool *pool)
21904736cbf7SLai Jiangshan {
21911258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
21924736cbf7SLai Jiangshan 
21934736cbf7SLai Jiangshan 	/*
21941258fae7STejun Heo 	 * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains
21951258fae7STejun Heo 	 * stable across this function.  See the comments above the flag
21961258fae7STejun Heo 	 * definition for details.
21974736cbf7SLai Jiangshan 	 */
21984736cbf7SLai Jiangshan 	if (pool->flags & POOL_DISASSOCIATED)
21994736cbf7SLai Jiangshan 		worker->flags |= WORKER_UNBOUND;
22005c25b5ffSPeter Zijlstra 	else
22015c25b5ffSPeter Zijlstra 		kthread_set_per_cpu(worker->task, pool->cpu);
22024736cbf7SLai Jiangshan 
2203640f17c8SPeter Zijlstra 	if (worker->rescue_wq)
22049546b29eSTejun Heo 		set_cpus_allowed_ptr(worker->task, pool_allowed_cpus(pool));
2205640f17c8SPeter Zijlstra 
22064736cbf7SLai Jiangshan 	list_add_tail(&worker->node, &pool->workers);
2207a2d812a2STejun Heo 	worker->pool = pool;
22084736cbf7SLai Jiangshan 
22091258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
22104736cbf7SLai Jiangshan }
22114736cbf7SLai Jiangshan 
22124736cbf7SLai Jiangshan /**
221360f5a4bcSLai Jiangshan  * worker_detach_from_pool() - detach a worker from its pool
221460f5a4bcSLai Jiangshan  * @worker: worker which is attached to its pool
221560f5a4bcSLai Jiangshan  *
22164736cbf7SLai Jiangshan  * Undo the attaching which had been done in worker_attach_to_pool().  The
22174736cbf7SLai Jiangshan  * caller worker shouldn't access to the pool after detached except it has
22184736cbf7SLai Jiangshan  * other reference to the pool.
221960f5a4bcSLai Jiangshan  */
2220a2d812a2STejun Heo static void worker_detach_from_pool(struct worker *worker)
222160f5a4bcSLai Jiangshan {
2222a2d812a2STejun Heo 	struct worker_pool *pool = worker->pool;
222360f5a4bcSLai Jiangshan 	struct completion *detach_completion = NULL;
222460f5a4bcSLai Jiangshan 
22251258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
2226a2d812a2STejun Heo 
22275c25b5ffSPeter Zijlstra 	kthread_set_per_cpu(worker->task, -1);
2228da028469SLai Jiangshan 	list_del(&worker->node);
2229a2d812a2STejun Heo 	worker->pool = NULL;
2230a2d812a2STejun Heo 
2231e02b9312SValentin Schneider 	if (list_empty(&pool->workers) && list_empty(&pool->dying_workers))
223260f5a4bcSLai Jiangshan 		detach_completion = pool->detach_completion;
22331258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
223460f5a4bcSLai Jiangshan 
2235b62c0751SLai Jiangshan 	/* clear leftover flags without pool->lock after it is detached */
2236b62c0751SLai Jiangshan 	worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
2237b62c0751SLai Jiangshan 
223860f5a4bcSLai Jiangshan 	if (detach_completion)
223960f5a4bcSLai Jiangshan 		complete(detach_completion);
224060f5a4bcSLai Jiangshan }
224160f5a4bcSLai Jiangshan 
224260f5a4bcSLai Jiangshan /**
2243c34056a3STejun Heo  * create_worker - create a new workqueue worker
224463d95a91STejun Heo  * @pool: pool the new worker will belong to
2245c34056a3STejun Heo  *
2246051e1850SLai Jiangshan  * Create and start a new worker which is attached to @pool.
2247c34056a3STejun Heo  *
2248c34056a3STejun Heo  * CONTEXT:
2249c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
2250c34056a3STejun Heo  *
2251d185af30SYacine Belkadi  * Return:
2252c34056a3STejun Heo  * Pointer to the newly created worker.
2253c34056a3STejun Heo  */
2254bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
2255c34056a3STejun Heo {
2256e441b56fSZhen Lei 	struct worker *worker;
2257e441b56fSZhen Lei 	int id;
22585d9c7a1eSLucy Mielke 	char id_buf[23];
2259c34056a3STejun Heo 
22607cda9aaeSLai Jiangshan 	/* ID is needed to determine kthread name */
2261e441b56fSZhen Lei 	id = ida_alloc(&pool->worker_ida, GFP_KERNEL);
22623f0ea0b8SPetr Mladek 	if (id < 0) {
22633f0ea0b8SPetr Mladek 		pr_err_once("workqueue: Failed to allocate a worker ID: %pe\n",
22643f0ea0b8SPetr Mladek 			    ERR_PTR(id));
2265e441b56fSZhen Lei 		return NULL;
22663f0ea0b8SPetr Mladek 	}
2267c34056a3STejun Heo 
2268f7537df5SLai Jiangshan 	worker = alloc_worker(pool->node);
22693f0ea0b8SPetr Mladek 	if (!worker) {
22703f0ea0b8SPetr Mladek 		pr_err_once("workqueue: Failed to allocate a worker\n");
2271c34056a3STejun Heo 		goto fail;
22723f0ea0b8SPetr Mladek 	}
2273c34056a3STejun Heo 
2274c34056a3STejun Heo 	worker->id = id;
2275c34056a3STejun Heo 
227629c91e99STejun Heo 	if (pool->cpu >= 0)
2277e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
2278e3c916a4STejun Heo 			 pool->attrs->nice < 0  ? "H" : "");
2279f3421797STejun Heo 	else
2280e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
2281e3c916a4STejun Heo 
2282f3f90ad4STejun Heo 	worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
2283e3c916a4STejun Heo 					      "kworker/%s", id_buf);
22843f0ea0b8SPetr Mladek 	if (IS_ERR(worker->task)) {
228560f54038SPetr Mladek 		if (PTR_ERR(worker->task) == -EINTR) {
228660f54038SPetr Mladek 			pr_err("workqueue: Interrupted when creating a worker thread \"kworker/%s\"\n",
228760f54038SPetr Mladek 			       id_buf);
228860f54038SPetr Mladek 		} else {
22893f0ea0b8SPetr Mladek 			pr_err_once("workqueue: Failed to create a worker thread: %pe",
22903f0ea0b8SPetr Mladek 				    worker->task);
229160f54038SPetr Mladek 		}
2292c34056a3STejun Heo 		goto fail;
22933f0ea0b8SPetr Mladek 	}
2294c34056a3STejun Heo 
229591151228SOleg Nesterov 	set_user_nice(worker->task, pool->attrs->nice);
22969546b29eSTejun Heo 	kthread_bind_mask(worker->task, pool_allowed_cpus(pool));
229791151228SOleg Nesterov 
2298da028469SLai Jiangshan 	/* successful, attach the worker to the pool */
22994736cbf7SLai Jiangshan 	worker_attach_to_pool(worker, pool);
2300822d8405STejun Heo 
2301051e1850SLai Jiangshan 	/* start the newly created worker */
2302a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
23030219a352STejun Heo 
2304051e1850SLai Jiangshan 	worker->pool->nr_workers++;
2305051e1850SLai Jiangshan 	worker_enter_idle(worker);
23060219a352STejun Heo 
23070219a352STejun Heo 	/*
23080219a352STejun Heo 	 * @worker is waiting on a completion in kthread() and will trigger hung
23096a229b0eSTejun Heo 	 * check if not woken up soon. As kick_pool() is noop if @pool is empty,
23106a229b0eSTejun Heo 	 * wake it up explicitly.
23110219a352STejun Heo 	 */
2312051e1850SLai Jiangshan 	wake_up_process(worker->task);
23130219a352STejun Heo 
2314a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2315051e1850SLai Jiangshan 
2316c34056a3STejun Heo 	return worker;
2317822d8405STejun Heo 
2318c34056a3STejun Heo fail:
2319e441b56fSZhen Lei 	ida_free(&pool->worker_ida, id);
2320c34056a3STejun Heo 	kfree(worker);
2321c34056a3STejun Heo 	return NULL;
2322c34056a3STejun Heo }
2323c34056a3STejun Heo 
2324793777bcSValentin Schneider static void unbind_worker(struct worker *worker)
2325793777bcSValentin Schneider {
2326793777bcSValentin Schneider 	lockdep_assert_held(&wq_pool_attach_mutex);
2327793777bcSValentin Schneider 
2328793777bcSValentin Schneider 	kthread_set_per_cpu(worker->task, -1);
2329793777bcSValentin Schneider 	if (cpumask_intersects(wq_unbound_cpumask, cpu_active_mask))
2330793777bcSValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, wq_unbound_cpumask) < 0);
2331793777bcSValentin Schneider 	else
2332793777bcSValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, cpu_possible_mask) < 0);
2333793777bcSValentin Schneider }
2334793777bcSValentin Schneider 
2335e02b9312SValentin Schneider static void wake_dying_workers(struct list_head *cull_list)
2336e02b9312SValentin Schneider {
2337e02b9312SValentin Schneider 	struct worker *worker, *tmp;
2338e02b9312SValentin Schneider 
2339e02b9312SValentin Schneider 	list_for_each_entry_safe(worker, tmp, cull_list, entry) {
2340e02b9312SValentin Schneider 		list_del_init(&worker->entry);
2341e02b9312SValentin Schneider 		unbind_worker(worker);
2342e02b9312SValentin Schneider 		/*
2343e02b9312SValentin Schneider 		 * If the worker was somehow already running, then it had to be
2344e02b9312SValentin Schneider 		 * in pool->idle_list when set_worker_dying() happened or we
2345e02b9312SValentin Schneider 		 * wouldn't have gotten here.
2346c34056a3STejun Heo 		 *
2347e02b9312SValentin Schneider 		 * Thus, the worker must either have observed the WORKER_DIE
2348e02b9312SValentin Schneider 		 * flag, or have set its state to TASK_IDLE. Either way, the
2349e02b9312SValentin Schneider 		 * below will be observed by the worker and is safe to do
2350e02b9312SValentin Schneider 		 * outside of pool->lock.
2351e02b9312SValentin Schneider 		 */
2352e02b9312SValentin Schneider 		wake_up_process(worker->task);
2353e02b9312SValentin Schneider 	}
2354e02b9312SValentin Schneider }
2355e02b9312SValentin Schneider 
2356e02b9312SValentin Schneider /**
2357e02b9312SValentin Schneider  * set_worker_dying - Tag a worker for destruction
2358e02b9312SValentin Schneider  * @worker: worker to be destroyed
2359e02b9312SValentin Schneider  * @list: transfer worker away from its pool->idle_list and into list
2360e02b9312SValentin Schneider  *
2361e02b9312SValentin Schneider  * Tag @worker for destruction and adjust @pool stats accordingly.  The worker
2362e02b9312SValentin Schneider  * should be idle.
2363c8e55f36STejun Heo  *
2364c8e55f36STejun Heo  * CONTEXT:
2365a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
2366c34056a3STejun Heo  */
2367e02b9312SValentin Schneider static void set_worker_dying(struct worker *worker, struct list_head *list)
2368c34056a3STejun Heo {
2369bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2370c34056a3STejun Heo 
2371cd549687STejun Heo 	lockdep_assert_held(&pool->lock);
2372e02b9312SValentin Schneider 	lockdep_assert_held(&wq_pool_attach_mutex);
2373cd549687STejun Heo 
2374c34056a3STejun Heo 	/* sanity check frenzy */
23756183c009STejun Heo 	if (WARN_ON(worker->current_work) ||
237673eb7fe7SLai Jiangshan 	    WARN_ON(!list_empty(&worker->scheduled)) ||
237773eb7fe7SLai Jiangshan 	    WARN_ON(!(worker->flags & WORKER_IDLE)))
23786183c009STejun Heo 		return;
2379c34056a3STejun Heo 
2380bd7bdd43STejun Heo 	pool->nr_workers--;
2381bd7bdd43STejun Heo 	pool->nr_idle--;
2382c8e55f36STejun Heo 
2383cb444766STejun Heo 	worker->flags |= WORKER_DIE;
2384e02b9312SValentin Schneider 
2385e02b9312SValentin Schneider 	list_move(&worker->entry, list);
2386e02b9312SValentin Schneider 	list_move(&worker->node, &pool->dying_workers);
2387c34056a3STejun Heo }
2388c34056a3STejun Heo 
23893f959aa3SValentin Schneider /**
23903f959aa3SValentin Schneider  * idle_worker_timeout - check if some idle workers can now be deleted.
23913f959aa3SValentin Schneider  * @t: The pool's idle_timer that just expired
23923f959aa3SValentin Schneider  *
23933f959aa3SValentin Schneider  * The timer is armed in worker_enter_idle(). Note that it isn't disarmed in
23943f959aa3SValentin Schneider  * worker_leave_idle(), as a worker flicking between idle and active while its
23953f959aa3SValentin Schneider  * pool is at the too_many_workers() tipping point would cause too much timer
23963f959aa3SValentin Schneider  * housekeeping overhead. Since IDLE_WORKER_TIMEOUT is long enough, we just let
23973f959aa3SValentin Schneider  * it expire and re-evaluate things from there.
23983f959aa3SValentin Schneider  */
239932a6c723SKees Cook static void idle_worker_timeout(struct timer_list *t)
2400e22bee78STejun Heo {
240132a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, idle_timer);
24023f959aa3SValentin Schneider 	bool do_cull = false;
24033f959aa3SValentin Schneider 
24043f959aa3SValentin Schneider 	if (work_pending(&pool->idle_cull_work))
24053f959aa3SValentin Schneider 		return;
24063f959aa3SValentin Schneider 
24073f959aa3SValentin Schneider 	raw_spin_lock_irq(&pool->lock);
24083f959aa3SValentin Schneider 
24093f959aa3SValentin Schneider 	if (too_many_workers(pool)) {
24103f959aa3SValentin Schneider 		struct worker *worker;
24113f959aa3SValentin Schneider 		unsigned long expires;
24123f959aa3SValentin Schneider 
24133f959aa3SValentin Schneider 		/* idle_list is kept in LIFO order, check the last one */
24143f959aa3SValentin Schneider 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
24153f959aa3SValentin Schneider 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
24163f959aa3SValentin Schneider 		do_cull = !time_before(jiffies, expires);
24173f959aa3SValentin Schneider 
24183f959aa3SValentin Schneider 		if (!do_cull)
24193f959aa3SValentin Schneider 			mod_timer(&pool->idle_timer, expires);
24203f959aa3SValentin Schneider 	}
24213f959aa3SValentin Schneider 	raw_spin_unlock_irq(&pool->lock);
24223f959aa3SValentin Schneider 
24233f959aa3SValentin Schneider 	if (do_cull)
24243f959aa3SValentin Schneider 		queue_work(system_unbound_wq, &pool->idle_cull_work);
24253f959aa3SValentin Schneider }
24263f959aa3SValentin Schneider 
24273f959aa3SValentin Schneider /**
24283f959aa3SValentin Schneider  * idle_cull_fn - cull workers that have been idle for too long.
24293f959aa3SValentin Schneider  * @work: the pool's work for handling these idle workers
24303f959aa3SValentin Schneider  *
24313f959aa3SValentin Schneider  * This goes through a pool's idle workers and gets rid of those that have been
24323f959aa3SValentin Schneider  * idle for at least IDLE_WORKER_TIMEOUT seconds.
2433e02b9312SValentin Schneider  *
2434e02b9312SValentin Schneider  * We don't want to disturb isolated CPUs because of a pcpu kworker being
2435e02b9312SValentin Schneider  * culled, so this also resets worker affinity. This requires a sleepable
2436e02b9312SValentin Schneider  * context, hence the split between timer callback and work item.
24373f959aa3SValentin Schneider  */
24383f959aa3SValentin Schneider static void idle_cull_fn(struct work_struct *work)
24393f959aa3SValentin Schneider {
24403f959aa3SValentin Schneider 	struct worker_pool *pool = container_of(work, struct worker_pool, idle_cull_work);
24419680540cSYang Yingliang 	LIST_HEAD(cull_list);
2442e22bee78STejun Heo 
2443e02b9312SValentin Schneider 	/*
2444e02b9312SValentin Schneider 	 * Grabbing wq_pool_attach_mutex here ensures an already-running worker
2445e02b9312SValentin Schneider 	 * cannot proceed beyong worker_detach_from_pool() in its self-destruct
2446e02b9312SValentin Schneider 	 * path. This is required as a previously-preempted worker could run after
2447e02b9312SValentin Schneider 	 * set_worker_dying() has happened but before wake_dying_workers() did.
2448e02b9312SValentin Schneider 	 */
2449e02b9312SValentin Schneider 	mutex_lock(&wq_pool_attach_mutex);
2450a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2451e22bee78STejun Heo 
24523347fc9fSLai Jiangshan 	while (too_many_workers(pool)) {
2453e22bee78STejun Heo 		struct worker *worker;
2454e22bee78STejun Heo 		unsigned long expires;
2455e22bee78STejun Heo 
245663d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
2457e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2458e22bee78STejun Heo 
24593347fc9fSLai Jiangshan 		if (time_before(jiffies, expires)) {
246063d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
24613347fc9fSLai Jiangshan 			break;
2462e22bee78STejun Heo 		}
24633347fc9fSLai Jiangshan 
2464e02b9312SValentin Schneider 		set_worker_dying(worker, &cull_list);
2465e22bee78STejun Heo 	}
2466e22bee78STejun Heo 
2467a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2468e02b9312SValentin Schneider 	wake_dying_workers(&cull_list);
2469e02b9312SValentin Schneider 	mutex_unlock(&wq_pool_attach_mutex);
2470e22bee78STejun Heo }
2471e22bee78STejun Heo 
2472493a1724STejun Heo static void send_mayday(struct work_struct *work)
2473e22bee78STejun Heo {
2474112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2475112202d9STejun Heo 	struct workqueue_struct *wq = pwq->wq;
2476493a1724STejun Heo 
24772e109a28STejun Heo 	lockdep_assert_held(&wq_mayday_lock);
2478e22bee78STejun Heo 
2479493008a8STejun Heo 	if (!wq->rescuer)
2480493a1724STejun Heo 		return;
2481e22bee78STejun Heo 
2482e22bee78STejun Heo 	/* mayday mayday mayday */
2483493a1724STejun Heo 	if (list_empty(&pwq->mayday_node)) {
248477668c8bSLai Jiangshan 		/*
248577668c8bSLai Jiangshan 		 * If @pwq is for an unbound wq, its base ref may be put at
248677668c8bSLai Jiangshan 		 * any time due to an attribute change.  Pin @pwq until the
248777668c8bSLai Jiangshan 		 * rescuer is done with it.
248877668c8bSLai Jiangshan 		 */
248977668c8bSLai Jiangshan 		get_pwq(pwq);
2490493a1724STejun Heo 		list_add_tail(&pwq->mayday_node, &wq->maydays);
2491e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
2492725e8ec5STejun Heo 		pwq->stats[PWQ_STAT_MAYDAY]++;
2493493a1724STejun Heo 	}
2494e22bee78STejun Heo }
2495e22bee78STejun Heo 
249632a6c723SKees Cook static void pool_mayday_timeout(struct timer_list *t)
2497e22bee78STejun Heo {
249832a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, mayday_timer);
2499e22bee78STejun Heo 	struct work_struct *work;
2500e22bee78STejun Heo 
2501a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2502a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock(&wq_mayday_lock);		/* for wq->maydays */
2503e22bee78STejun Heo 
250463d95a91STejun Heo 	if (need_to_create_worker(pool)) {
2505e22bee78STejun Heo 		/*
2506e22bee78STejun Heo 		 * We've been trying to create a new worker but
2507e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
2508e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
2509e22bee78STejun Heo 		 * rescuers.
2510e22bee78STejun Heo 		 */
251163d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
2512e22bee78STejun Heo 			send_mayday(work);
2513e22bee78STejun Heo 	}
2514e22bee78STejun Heo 
2515a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&wq_mayday_lock);
2516a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2517e22bee78STejun Heo 
251863d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
2519e22bee78STejun Heo }
2520e22bee78STejun Heo 
2521e22bee78STejun Heo /**
2522e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
252363d95a91STejun Heo  * @pool: pool to create a new worker for
2524e22bee78STejun Heo  *
252563d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
2526e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
2527e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
252863d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
2529e22bee78STejun Heo  * possible allocation deadlock.
2530e22bee78STejun Heo  *
2531c5aa87bbSTejun Heo  * On return, need_to_create_worker() is guaranteed to be %false and
2532c5aa87bbSTejun Heo  * may_start_working() %true.
2533e22bee78STejun Heo  *
2534e22bee78STejun Heo  * LOCKING:
2535a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2536e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
2537e22bee78STejun Heo  * manager.
2538e22bee78STejun Heo  */
253929187a9eSTejun Heo static void maybe_create_worker(struct worker_pool *pool)
2540d565ed63STejun Heo __releases(&pool->lock)
2541d565ed63STejun Heo __acquires(&pool->lock)
2542e22bee78STejun Heo {
2543e22bee78STejun Heo restart:
2544a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
25459f9c2364STejun Heo 
2546e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
254763d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
2548e22bee78STejun Heo 
2549e22bee78STejun Heo 	while (true) {
2550051e1850SLai Jiangshan 		if (create_worker(pool) || !need_to_create_worker(pool))
2551e22bee78STejun Heo 			break;
2552e22bee78STejun Heo 
2553e212f361SLai Jiangshan 		schedule_timeout_interruptible(CREATE_COOLDOWN);
25549f9c2364STejun Heo 
255563d95a91STejun Heo 		if (!need_to_create_worker(pool))
2556e22bee78STejun Heo 			break;
2557e22bee78STejun Heo 	}
2558e22bee78STejun Heo 
255963d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
2560a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2561051e1850SLai Jiangshan 	/*
2562051e1850SLai Jiangshan 	 * This is necessary even after a new worker was just successfully
2563051e1850SLai Jiangshan 	 * created as @pool->lock was dropped and the new worker might have
2564051e1850SLai Jiangshan 	 * already become busy.
2565051e1850SLai Jiangshan 	 */
256663d95a91STejun Heo 	if (need_to_create_worker(pool))
2567e22bee78STejun Heo 		goto restart;
2568e22bee78STejun Heo }
2569e22bee78STejun Heo 
2570e22bee78STejun Heo /**
2571e22bee78STejun Heo  * manage_workers - manage worker pool
2572e22bee78STejun Heo  * @worker: self
2573e22bee78STejun Heo  *
2574706026c2STejun Heo  * Assume the manager role and manage the worker pool @worker belongs
2575e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
2576706026c2STejun Heo  * pool.  The exclusion is handled automatically by this function.
2577e22bee78STejun Heo  *
2578e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
2579e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
2580e22bee78STejun Heo  * and may_start_working() is true.
2581e22bee78STejun Heo  *
2582e22bee78STejun Heo  * CONTEXT:
2583a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2584e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
2585e22bee78STejun Heo  *
2586d185af30SYacine Belkadi  * Return:
258729187a9eSTejun Heo  * %false if the pool doesn't need management and the caller can safely
258829187a9eSTejun Heo  * start processing works, %true if management function was performed and
258929187a9eSTejun Heo  * the conditions that the caller verified before calling the function may
259029187a9eSTejun Heo  * no longer be true.
2591e22bee78STejun Heo  */
2592e22bee78STejun Heo static bool manage_workers(struct worker *worker)
2593e22bee78STejun Heo {
259463d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
2595e22bee78STejun Heo 
2596692b4825STejun Heo 	if (pool->flags & POOL_MANAGER_ACTIVE)
259729187a9eSTejun Heo 		return false;
2598692b4825STejun Heo 
2599692b4825STejun Heo 	pool->flags |= POOL_MANAGER_ACTIVE;
26002607d7a6STejun Heo 	pool->manager = worker;
2601e22bee78STejun Heo 
260229187a9eSTejun Heo 	maybe_create_worker(pool);
2603e22bee78STejun Heo 
26042607d7a6STejun Heo 	pool->manager = NULL;
2605692b4825STejun Heo 	pool->flags &= ~POOL_MANAGER_ACTIVE;
2606d8bb65abSSebastian Andrzej Siewior 	rcuwait_wake_up(&manager_wait);
260729187a9eSTejun Heo 	return true;
2608e22bee78STejun Heo }
2609e22bee78STejun Heo 
2610a62428c0STejun Heo /**
2611a62428c0STejun Heo  * process_one_work - process single work
2612c34056a3STejun Heo  * @worker: self
2613a62428c0STejun Heo  * @work: work to process
2614a62428c0STejun Heo  *
2615a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
2616a62428c0STejun Heo  * process a single work including synchronization against and
2617a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
2618a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
2619a62428c0STejun Heo  * call this function to process a work.
2620a62428c0STejun Heo  *
2621a62428c0STejun Heo  * CONTEXT:
2622a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which is released and regrabbed.
2623a62428c0STejun Heo  */
2624c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
2625d565ed63STejun Heo __releases(&pool->lock)
2626d565ed63STejun Heo __acquires(&pool->lock)
26271da177e4SLinus Torvalds {
2628112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2629bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2630c4560c2cSLai Jiangshan 	unsigned long work_data;
26314e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
26324e6045f1SJohannes Berg 	/*
2633a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
2634a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
2635a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
2636a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
2637a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
26384e6045f1SJohannes Berg 	 */
26394d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
26404d82a1deSPeter Zijlstra 
26414d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
26424e6045f1SJohannes Berg #endif
2643807407c0SLai Jiangshan 	/* ensure we're on the correct CPU */
264485327af6SLai Jiangshan 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2645ec22ca5eSTejun Heo 		     raw_smp_processor_id() != pool->cpu);
264625511a47STejun Heo 
26478930cabaSTejun Heo 	/* claim and dequeue */
2648dc186ad7SThomas Gleixner 	debug_work_deactivate(work);
2649c9e7cf27STejun Heo 	hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2650c34056a3STejun Heo 	worker->current_work = work;
2651a2c1c57bSTejun Heo 	worker->current_func = work->func;
2652112202d9STejun Heo 	worker->current_pwq = pwq;
2653616db877STejun Heo 	worker->current_at = worker->task->se.sum_exec_runtime;
2654c4560c2cSLai Jiangshan 	work_data = *work_data_bits(work);
2655d812796eSLai Jiangshan 	worker->current_color = get_work_color(work_data);
26567a22ad75STejun Heo 
26578bf89593STejun Heo 	/*
26588bf89593STejun Heo 	 * Record wq name for cmdline and debug reporting, may get
26598bf89593STejun Heo 	 * overridden through set_worker_desc().
26608bf89593STejun Heo 	 */
26618bf89593STejun Heo 	strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
26628bf89593STejun Heo 
2663a62428c0STejun Heo 	list_del_init(&work->entry);
2664a62428c0STejun Heo 
2665649027d7STejun Heo 	/*
2666228f1d00SLai Jiangshan 	 * CPU intensive works don't participate in concurrency management.
2667228f1d00SLai Jiangshan 	 * They're the scheduler's responsibility.  This takes @worker out
2668228f1d00SLai Jiangshan 	 * of concurrency management and the next code block will chain
2669228f1d00SLai Jiangshan 	 * execution of the pending work items.
2670fb0e7bebSTejun Heo 	 */
2671616db877STejun Heo 	if (unlikely(pwq->wq->flags & WQ_CPU_INTENSIVE))
2672228f1d00SLai Jiangshan 		worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2673fb0e7bebSTejun Heo 
2674974271c4STejun Heo 	/*
26750219a352STejun Heo 	 * Kick @pool if necessary. It's always noop for per-cpu worker pools
26760219a352STejun Heo 	 * since nr_running would always be >= 1 at this point. This is used to
26770219a352STejun Heo 	 * chain execution of the pending work items for WORKER_NOT_RUNNING
26780219a352STejun Heo 	 * workers such as the UNBOUND and CPU_INTENSIVE ones.
2679974271c4STejun Heo 	 */
26800219a352STejun Heo 	kick_pool(pool);
2681974271c4STejun Heo 
26828930cabaSTejun Heo 	/*
26837c3eed5cSTejun Heo 	 * Record the last pool and clear PENDING which should be the last
2684d565ed63STejun Heo 	 * update to @work.  Also, do this inside @pool->lock so that
268523657bb1STejun Heo 	 * PENDING and queued state changes happen together while IRQ is
268623657bb1STejun Heo 	 * disabled.
26878930cabaSTejun Heo 	 */
26887c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(work, pool->id);
26891da177e4SLinus Torvalds 
2690fe48ba7dSMirsad Goran Todorovac 	pwq->stats[PWQ_STAT_STARTED]++;
2691a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2692365970a1SDavid Howells 
2693a1d14934SPeter Zijlstra 	lock_map_acquire(&pwq->wq->lockdep_map);
26943295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
2695e6f3faa7SPeter Zijlstra 	/*
2696f52be570SPeter Zijlstra 	 * Strictly speaking we should mark the invariant state without holding
2697f52be570SPeter Zijlstra 	 * any locks, that is, before these two lock_map_acquire()'s.
2698e6f3faa7SPeter Zijlstra 	 *
2699e6f3faa7SPeter Zijlstra 	 * However, that would result in:
2700e6f3faa7SPeter Zijlstra 	 *
2701e6f3faa7SPeter Zijlstra 	 *   A(W1)
2702e6f3faa7SPeter Zijlstra 	 *   WFC(C)
2703e6f3faa7SPeter Zijlstra 	 *		A(W1)
2704e6f3faa7SPeter Zijlstra 	 *		C(C)
2705e6f3faa7SPeter Zijlstra 	 *
2706e6f3faa7SPeter Zijlstra 	 * Which would create W1->C->W1 dependencies, even though there is no
2707e6f3faa7SPeter Zijlstra 	 * actual deadlock possible. There are two solutions, using a
2708e6f3faa7SPeter Zijlstra 	 * read-recursive acquire on the work(queue) 'locks', but this will then
2709f52be570SPeter Zijlstra 	 * hit the lockdep limitation on recursive locks, or simply discard
2710e6f3faa7SPeter Zijlstra 	 * these locks.
2711e6f3faa7SPeter Zijlstra 	 *
2712e6f3faa7SPeter Zijlstra 	 * AFAICT there is no possible deadlock scenario between the
2713e6f3faa7SPeter Zijlstra 	 * flush_work() and complete() primitives (except for single-threaded
2714e6f3faa7SPeter Zijlstra 	 * workqueues), so hiding them isn't a problem.
2715e6f3faa7SPeter Zijlstra 	 */
2716f52be570SPeter Zijlstra 	lockdep_invariant_state(true);
2717e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
2718a2c1c57bSTejun Heo 	worker->current_func(work);
2719e36c886aSArjan van de Ven 	/*
2720e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
2721e36c886aSArjan van de Ven 	 * point will only record its address.
2722e36c886aSArjan van de Ven 	 */
27231c5da0ecSDaniel Jordan 	trace_workqueue_execute_end(work, worker->current_func);
2724725e8ec5STejun Heo 	pwq->stats[PWQ_STAT_COMPLETED]++;
27253295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
2726112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
27271da177e4SLinus Torvalds 
27281a65a6d1SXuewen Yan 	if (unlikely(in_atomic() || lockdep_depth(current) > 0 ||
27291a65a6d1SXuewen Yan 		     rcu_preempt_depth() > 0)) {
27301a65a6d1SXuewen Yan 		pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d/%d\n"
2731d75f773cSSakari Ailus 		       "     last function: %ps\n",
27321a65a6d1SXuewen Yan 		       current->comm, preempt_count(), rcu_preempt_depth(),
27331a65a6d1SXuewen Yan 		       task_pid_nr(current), worker->current_func);
2734d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
2735d5abe669SPeter Zijlstra 		dump_stack();
2736d5abe669SPeter Zijlstra 	}
2737d5abe669SPeter Zijlstra 
2738b22ce278STejun Heo 	/*
2739025f50f3SSebastian Andrzej Siewior 	 * The following prevents a kworker from hogging CPU on !PREEMPTION
2740b22ce278STejun Heo 	 * kernels, where a requeueing work item waiting for something to
2741b22ce278STejun Heo 	 * happen could deadlock with stop_machine as such work item could
2742b22ce278STejun Heo 	 * indefinitely requeue itself while all other CPUs are trapped in
2743789cbbecSJoe Lawrence 	 * stop_machine. At the same time, report a quiescent RCU state so
2744789cbbecSJoe Lawrence 	 * the same condition doesn't freeze RCU.
2745b22ce278STejun Heo 	 */
2746a7e6425eSPaul E. McKenney 	cond_resched();
2747b22ce278STejun Heo 
2748a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2749a62428c0STejun Heo 
2750616db877STejun Heo 	/*
2751616db877STejun Heo 	 * In addition to %WQ_CPU_INTENSIVE, @worker may also have been marked
2752616db877STejun Heo 	 * CPU intensive by wq_worker_tick() if @work hogged CPU longer than
2753616db877STejun Heo 	 * wq_cpu_intensive_thresh_us. Clear it.
2754616db877STejun Heo 	 */
2755fb0e7bebSTejun Heo 	worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2756fb0e7bebSTejun Heo 
27571b69ac6bSJohannes Weiner 	/* tag the worker for identification in schedule() */
27581b69ac6bSJohannes Weiner 	worker->last_func = worker->current_func;
27591b69ac6bSJohannes Weiner 
2760a62428c0STejun Heo 	/* we're done with it, release */
276142f8570fSSasha Levin 	hash_del(&worker->hentry);
2762c34056a3STejun Heo 	worker->current_work = NULL;
2763a2c1c57bSTejun Heo 	worker->current_func = NULL;
2764112202d9STejun Heo 	worker->current_pwq = NULL;
2765d812796eSLai Jiangshan 	worker->current_color = INT_MAX;
2766c4560c2cSLai Jiangshan 	pwq_dec_nr_in_flight(pwq, work_data);
27671da177e4SLinus Torvalds }
27681da177e4SLinus Torvalds 
2769affee4b2STejun Heo /**
2770affee4b2STejun Heo  * process_scheduled_works - process scheduled works
2771affee4b2STejun Heo  * @worker: self
2772affee4b2STejun Heo  *
2773affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
2774affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
2775affee4b2STejun Heo  * fetches a work from the top and executes it.
2776affee4b2STejun Heo  *
2777affee4b2STejun Heo  * CONTEXT:
2778a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2779affee4b2STejun Heo  * multiple times.
2780affee4b2STejun Heo  */
2781affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
27821da177e4SLinus Torvalds {
2783c0ab017dSTejun Heo 	struct work_struct *work;
2784c0ab017dSTejun Heo 	bool first = true;
2785c0ab017dSTejun Heo 
2786c0ab017dSTejun Heo 	while ((work = list_first_entry_or_null(&worker->scheduled,
2787c0ab017dSTejun Heo 						struct work_struct, entry))) {
2788c0ab017dSTejun Heo 		if (first) {
2789c0ab017dSTejun Heo 			worker->pool->watchdog_ts = jiffies;
2790c0ab017dSTejun Heo 			first = false;
2791c0ab017dSTejun Heo 		}
2792c34056a3STejun Heo 		process_one_work(worker, work);
2793a62428c0STejun Heo 	}
27941da177e4SLinus Torvalds }
27951da177e4SLinus Torvalds 
2796197f6accSTejun Heo static void set_pf_worker(bool val)
2797197f6accSTejun Heo {
2798197f6accSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
2799197f6accSTejun Heo 	if (val)
2800197f6accSTejun Heo 		current->flags |= PF_WQ_WORKER;
2801197f6accSTejun Heo 	else
2802197f6accSTejun Heo 		current->flags &= ~PF_WQ_WORKER;
2803197f6accSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
2804197f6accSTejun Heo }
2805197f6accSTejun Heo 
28064690c4abSTejun Heo /**
28074690c4abSTejun Heo  * worker_thread - the worker thread function
2808c34056a3STejun Heo  * @__worker: self
28094690c4abSTejun Heo  *
2810c5aa87bbSTejun Heo  * The worker thread function.  All workers belong to a worker_pool -
2811c5aa87bbSTejun Heo  * either a per-cpu one or dynamic unbound one.  These workers process all
2812c5aa87bbSTejun Heo  * work items regardless of their specific target workqueue.  The only
2813c5aa87bbSTejun Heo  * exception is work items which belong to workqueues with a rescuer which
2814c5aa87bbSTejun Heo  * will be explained in rescuer_thread().
2815d185af30SYacine Belkadi  *
2816d185af30SYacine Belkadi  * Return: 0
28174690c4abSTejun Heo  */
2818c34056a3STejun Heo static int worker_thread(void *__worker)
28191da177e4SLinus Torvalds {
2820c34056a3STejun Heo 	struct worker *worker = __worker;
2821bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
28221da177e4SLinus Torvalds 
2823e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
2824197f6accSTejun Heo 	set_pf_worker(true);
2825c8e55f36STejun Heo woke_up:
2826a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2827affee4b2STejun Heo 
2828a9ab775bSTejun Heo 	/* am I supposed to die? */
2829a9ab775bSTejun Heo 	if (unlikely(worker->flags & WORKER_DIE)) {
2830a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
2831197f6accSTejun Heo 		set_pf_worker(false);
283260f5a4bcSLai Jiangshan 
283360f5a4bcSLai Jiangshan 		set_task_comm(worker->task, "kworker/dying");
2834e441b56fSZhen Lei 		ida_free(&pool->worker_ida, worker->id);
2835a2d812a2STejun Heo 		worker_detach_from_pool(worker);
2836e02b9312SValentin Schneider 		WARN_ON_ONCE(!list_empty(&worker->entry));
283760f5a4bcSLai Jiangshan 		kfree(worker);
2838c8e55f36STejun Heo 		return 0;
2839c8e55f36STejun Heo 	}
2840c8e55f36STejun Heo 
2841c8e55f36STejun Heo 	worker_leave_idle(worker);
2842db7bccf4STejun Heo recheck:
2843e22bee78STejun Heo 	/* no more worker necessary? */
284463d95a91STejun Heo 	if (!need_more_worker(pool))
2845e22bee78STejun Heo 		goto sleep;
2846e22bee78STejun Heo 
2847e22bee78STejun Heo 	/* do we need to manage? */
284863d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2849e22bee78STejun Heo 		goto recheck;
2850e22bee78STejun Heo 
2851c8e55f36STejun Heo 	/*
2852c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
2853c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
2854c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
2855c8e55f36STejun Heo 	 */
28566183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
2857c8e55f36STejun Heo 
2858e22bee78STejun Heo 	/*
2859a9ab775bSTejun Heo 	 * Finish PREP stage.  We're guaranteed to have at least one idle
2860a9ab775bSTejun Heo 	 * worker or that someone else has already assumed the manager
2861a9ab775bSTejun Heo 	 * role.  This is where @worker starts participating in concurrency
2862a9ab775bSTejun Heo 	 * management if applicable and concurrency management is restored
2863a9ab775bSTejun Heo 	 * after being rebound.  See rebind_workers() for details.
2864e22bee78STejun Heo 	 */
2865a9ab775bSTejun Heo 	worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2866e22bee78STejun Heo 
2867e22bee78STejun Heo 	do {
2868affee4b2STejun Heo 		struct work_struct *work =
2869bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
2870affee4b2STejun Heo 					 struct work_struct, entry);
2871affee4b2STejun Heo 
2872873eaca6STejun Heo 		if (assign_work(work, worker, NULL))
2873affee4b2STejun Heo 			process_scheduled_works(worker);
287463d95a91STejun Heo 	} while (keep_working(pool));
2875affee4b2STejun Heo 
2876228f1d00SLai Jiangshan 	worker_set_flags(worker, WORKER_PREP);
2877d313dd85STejun Heo sleep:
2878c8e55f36STejun Heo 	/*
2879d565ed63STejun Heo 	 * pool->lock is held and there's no work to process and no need to
2880d565ed63STejun Heo 	 * manage, sleep.  Workers are woken up only while holding
2881d565ed63STejun Heo 	 * pool->lock or from local cpu, so setting the current state
2882d565ed63STejun Heo 	 * before releasing pool->lock is enough to prevent losing any
2883d565ed63STejun Heo 	 * event.
2884c8e55f36STejun Heo 	 */
2885c8e55f36STejun Heo 	worker_enter_idle(worker);
2886c5a94a61SPeter Zijlstra 	__set_current_state(TASK_IDLE);
2887a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
28881da177e4SLinus Torvalds 	schedule();
2889c8e55f36STejun Heo 	goto woke_up;
28901da177e4SLinus Torvalds }
28911da177e4SLinus Torvalds 
2892e22bee78STejun Heo /**
2893e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
2894111c225aSTejun Heo  * @__rescuer: self
2895e22bee78STejun Heo  *
2896e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
2897493008a8STejun Heo  * workqueue which has WQ_MEM_RECLAIM set.
2898e22bee78STejun Heo  *
2899706026c2STejun Heo  * Regular work processing on a pool may block trying to create a new
2900e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
2901e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
2902e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2903e22bee78STejun Heo  * the problem rescuer solves.
2904e22bee78STejun Heo  *
2905706026c2STejun Heo  * When such condition is possible, the pool summons rescuers of all
2906706026c2STejun Heo  * workqueues which have works queued on the pool and let them process
2907e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
2908e22bee78STejun Heo  *
2909e22bee78STejun Heo  * This should happen rarely.
2910d185af30SYacine Belkadi  *
2911d185af30SYacine Belkadi  * Return: 0
2912e22bee78STejun Heo  */
2913111c225aSTejun Heo static int rescuer_thread(void *__rescuer)
2914e22bee78STejun Heo {
2915111c225aSTejun Heo 	struct worker *rescuer = __rescuer;
2916111c225aSTejun Heo 	struct workqueue_struct *wq = rescuer->rescue_wq;
29174d595b86SLai Jiangshan 	bool should_stop;
2918e22bee78STejun Heo 
2919e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
2920111c225aSTejun Heo 
2921111c225aSTejun Heo 	/*
2922111c225aSTejun Heo 	 * Mark rescuer as worker too.  As WORKER_PREP is never cleared, it
2923111c225aSTejun Heo 	 * doesn't participate in concurrency management.
2924111c225aSTejun Heo 	 */
2925197f6accSTejun Heo 	set_pf_worker(true);
2926e22bee78STejun Heo repeat:
2927c5a94a61SPeter Zijlstra 	set_current_state(TASK_IDLE);
29281da177e4SLinus Torvalds 
29294d595b86SLai Jiangshan 	/*
29304d595b86SLai Jiangshan 	 * By the time the rescuer is requested to stop, the workqueue
29314d595b86SLai Jiangshan 	 * shouldn't have any work pending, but @wq->maydays may still have
29324d595b86SLai Jiangshan 	 * pwq(s) queued.  This can happen by non-rescuer workers consuming
29334d595b86SLai Jiangshan 	 * all the work items before the rescuer got to them.  Go through
29344d595b86SLai Jiangshan 	 * @wq->maydays processing before acting on should_stop so that the
29354d595b86SLai Jiangshan 	 * list is always empty on exit.
29364d595b86SLai Jiangshan 	 */
29374d595b86SLai Jiangshan 	should_stop = kthread_should_stop();
29381da177e4SLinus Torvalds 
2939493a1724STejun Heo 	/* see whether any pwq is asking for help */
2940a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&wq_mayday_lock);
2941493a1724STejun Heo 
2942493a1724STejun Heo 	while (!list_empty(&wq->maydays)) {
2943493a1724STejun Heo 		struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2944493a1724STejun Heo 					struct pool_workqueue, mayday_node);
2945112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
2946e22bee78STejun Heo 		struct work_struct *work, *n;
2947e22bee78STejun Heo 
2948e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
2949493a1724STejun Heo 		list_del_init(&pwq->mayday_node);
2950493a1724STejun Heo 
2951a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&wq_mayday_lock);
2952e22bee78STejun Heo 
295351697d39SLai Jiangshan 		worker_attach_to_pool(rescuer, pool);
295451697d39SLai Jiangshan 
2955a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
2956e22bee78STejun Heo 
2957e22bee78STejun Heo 		/*
2958e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
2959e22bee78STejun Heo 		 * process'em.
2960e22bee78STejun Heo 		 */
2961873eaca6STejun Heo 		WARN_ON_ONCE(!list_empty(&rescuer->scheduled));
296282607adcSTejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry) {
2963873eaca6STejun Heo 			if (get_work_pwq(work) == pwq &&
2964873eaca6STejun Heo 			    assign_work(work, rescuer, &n))
2965725e8ec5STejun Heo 				pwq->stats[PWQ_STAT_RESCUED]++;
296682607adcSTejun Heo 		}
2967e22bee78STejun Heo 
2968873eaca6STejun Heo 		if (!list_empty(&rescuer->scheduled)) {
2969e22bee78STejun Heo 			process_scheduled_works(rescuer);
29707576958aSTejun Heo 
29717576958aSTejun Heo 			/*
2972008847f6SNeilBrown 			 * The above execution of rescued work items could
2973008847f6SNeilBrown 			 * have created more to rescue through
2974f97a4a1aSLai Jiangshan 			 * pwq_activate_first_inactive() or chained
2975008847f6SNeilBrown 			 * queueing.  Let's put @pwq back on mayday list so
2976008847f6SNeilBrown 			 * that such back-to-back work items, which may be
2977008847f6SNeilBrown 			 * being used to relieve memory pressure, don't
2978008847f6SNeilBrown 			 * incur MAYDAY_INTERVAL delay inbetween.
2979008847f6SNeilBrown 			 */
29804f3f4cf3SLai Jiangshan 			if (pwq->nr_active && need_to_create_worker(pool)) {
2981a9b8a985SSebastian Andrzej Siewior 				raw_spin_lock(&wq_mayday_lock);
2982e66b39afSTejun Heo 				/*
2983e66b39afSTejun Heo 				 * Queue iff we aren't racing destruction
2984e66b39afSTejun Heo 				 * and somebody else hasn't queued it already.
2985e66b39afSTejun Heo 				 */
2986e66b39afSTejun Heo 				if (wq->rescuer && list_empty(&pwq->mayday_node)) {
2987008847f6SNeilBrown 					get_pwq(pwq);
2988e66b39afSTejun Heo 					list_add_tail(&pwq->mayday_node, &wq->maydays);
2989e66b39afSTejun Heo 				}
2990a9b8a985SSebastian Andrzej Siewior 				raw_spin_unlock(&wq_mayday_lock);
2991008847f6SNeilBrown 			}
2992008847f6SNeilBrown 		}
2993008847f6SNeilBrown 
2994008847f6SNeilBrown 		/*
299577668c8bSLai Jiangshan 		 * Put the reference grabbed by send_mayday().  @pool won't
299613b1d625SLai Jiangshan 		 * go away while we're still attached to it.
299777668c8bSLai Jiangshan 		 */
299877668c8bSLai Jiangshan 		put_pwq(pwq);
299977668c8bSLai Jiangshan 
300077668c8bSLai Jiangshan 		/*
30010219a352STejun Heo 		 * Leave this pool. Notify regular workers; otherwise, we end up
30020219a352STejun Heo 		 * with 0 concurrency and stalling the execution.
30037576958aSTejun Heo 		 */
30040219a352STejun Heo 		kick_pool(pool);
30057576958aSTejun Heo 
3006a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
300713b1d625SLai Jiangshan 
3008a2d812a2STejun Heo 		worker_detach_from_pool(rescuer);
300913b1d625SLai Jiangshan 
3010a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&wq_mayday_lock);
30111da177e4SLinus Torvalds 	}
30121da177e4SLinus Torvalds 
3013a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&wq_mayday_lock);
3014493a1724STejun Heo 
30154d595b86SLai Jiangshan 	if (should_stop) {
30164d595b86SLai Jiangshan 		__set_current_state(TASK_RUNNING);
3017197f6accSTejun Heo 		set_pf_worker(false);
30184d595b86SLai Jiangshan 		return 0;
30194d595b86SLai Jiangshan 	}
30204d595b86SLai Jiangshan 
3021111c225aSTejun Heo 	/* rescuers should never participate in concurrency management */
3022111c225aSTejun Heo 	WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
3023e22bee78STejun Heo 	schedule();
3024e22bee78STejun Heo 	goto repeat;
30251da177e4SLinus Torvalds }
30261da177e4SLinus Torvalds 
3027fca839c0STejun Heo /**
3028fca839c0STejun Heo  * check_flush_dependency - check for flush dependency sanity
3029fca839c0STejun Heo  * @target_wq: workqueue being flushed
3030fca839c0STejun Heo  * @target_work: work item being flushed (NULL for workqueue flushes)
3031fca839c0STejun Heo  *
3032fca839c0STejun Heo  * %current is trying to flush the whole @target_wq or @target_work on it.
3033fca839c0STejun Heo  * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
3034fca839c0STejun Heo  * reclaiming memory or running on a workqueue which doesn't have
3035fca839c0STejun Heo  * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
3036fca839c0STejun Heo  * a deadlock.
3037fca839c0STejun Heo  */
3038fca839c0STejun Heo static void check_flush_dependency(struct workqueue_struct *target_wq,
3039fca839c0STejun Heo 				   struct work_struct *target_work)
3040fca839c0STejun Heo {
3041fca839c0STejun Heo 	work_func_t target_func = target_work ? target_work->func : NULL;
3042fca839c0STejun Heo 	struct worker *worker;
3043fca839c0STejun Heo 
3044fca839c0STejun Heo 	if (target_wq->flags & WQ_MEM_RECLAIM)
3045fca839c0STejun Heo 		return;
3046fca839c0STejun Heo 
3047fca839c0STejun Heo 	worker = current_wq_worker();
3048fca839c0STejun Heo 
3049fca839c0STejun Heo 	WARN_ONCE(current->flags & PF_MEMALLOC,
3050d75f773cSSakari Ailus 		  "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps",
3051fca839c0STejun Heo 		  current->pid, current->comm, target_wq->name, target_func);
305223d11a58STejun Heo 	WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
305323d11a58STejun Heo 			      (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
3054d75f773cSSakari Ailus 		  "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps",
3055fca839c0STejun Heo 		  worker->current_pwq->wq->name, worker->current_func,
3056fca839c0STejun Heo 		  target_wq->name, target_func);
3057fca839c0STejun Heo }
3058fca839c0STejun Heo 
3059fc2e4d70SOleg Nesterov struct wq_barrier {
3060fc2e4d70SOleg Nesterov 	struct work_struct	work;
3061fc2e4d70SOleg Nesterov 	struct completion	done;
30622607d7a6STejun Heo 	struct task_struct	*task;	/* purely informational */
3063fc2e4d70SOleg Nesterov };
3064fc2e4d70SOleg Nesterov 
3065fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
3066fc2e4d70SOleg Nesterov {
3067fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
3068fc2e4d70SOleg Nesterov 	complete(&barr->done);
3069fc2e4d70SOleg Nesterov }
3070fc2e4d70SOleg Nesterov 
30714690c4abSTejun Heo /**
30724690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
3073112202d9STejun Heo  * @pwq: pwq to insert barrier into
30744690c4abSTejun Heo  * @barr: wq_barrier to insert
3075affee4b2STejun Heo  * @target: target work to attach @barr to
3076affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
30774690c4abSTejun Heo  *
3078affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
3079affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
3080affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
3081affee4b2STejun Heo  * cpu.
3082affee4b2STejun Heo  *
3083affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
3084affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
3085affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
3086affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
3087affee4b2STejun Heo  * after a work with LINKED flag set.
3088affee4b2STejun Heo  *
3089affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
3090112202d9STejun Heo  * underneath us, so we can't reliably determine pwq from @target.
30914690c4abSTejun Heo  *
30924690c4abSTejun Heo  * CONTEXT:
3093a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
30944690c4abSTejun Heo  */
3095112202d9STejun Heo static void insert_wq_barrier(struct pool_workqueue *pwq,
3096affee4b2STejun Heo 			      struct wq_barrier *barr,
3097affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
3098fc2e4d70SOleg Nesterov {
3099d812796eSLai Jiangshan 	unsigned int work_flags = 0;
3100d812796eSLai Jiangshan 	unsigned int work_color;
3101affee4b2STejun Heo 	struct list_head *head;
3102affee4b2STejun Heo 
3103dc186ad7SThomas Gleixner 	/*
3104d565ed63STejun Heo 	 * debugobject calls are safe here even with pool->lock locked
3105dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
3106dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
3107dc186ad7SThomas Gleixner 	 * might deadlock.
3108dc186ad7SThomas Gleixner 	 */
3109ca1cab37SAndrew Morton 	INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
311022df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
311152fa5bc5SBoqun Feng 
3112fd1a5b04SByungchul Park 	init_completion_map(&barr->done, &target->lockdep_map);
3113fd1a5b04SByungchul Park 
31142607d7a6STejun Heo 	barr->task = current;
311583c22520SOleg Nesterov 
3116018f3a13SLai Jiangshan 	/* The barrier work item does not participate in pwq->nr_active. */
3117018f3a13SLai Jiangshan 	work_flags |= WORK_STRUCT_INACTIVE;
3118018f3a13SLai Jiangshan 
3119affee4b2STejun Heo 	/*
3120affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
3121affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
3122affee4b2STejun Heo 	 */
3123d812796eSLai Jiangshan 	if (worker) {
3124affee4b2STejun Heo 		head = worker->scheduled.next;
3125d812796eSLai Jiangshan 		work_color = worker->current_color;
3126d812796eSLai Jiangshan 	} else {
3127affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
3128affee4b2STejun Heo 
3129affee4b2STejun Heo 		head = target->entry.next;
3130affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
3131d21cece0SLai Jiangshan 		work_flags |= *bits & WORK_STRUCT_LINKED;
3132d812796eSLai Jiangshan 		work_color = get_work_color(*bits);
3133affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
3134affee4b2STejun Heo 	}
3135affee4b2STejun Heo 
3136d812796eSLai Jiangshan 	pwq->nr_in_flight[work_color]++;
3137d812796eSLai Jiangshan 	work_flags |= work_color_to_flags(work_color);
3138d812796eSLai Jiangshan 
3139d21cece0SLai Jiangshan 	insert_work(pwq, &barr->work, head, work_flags);
3140fc2e4d70SOleg Nesterov }
3141fc2e4d70SOleg Nesterov 
314273f53c4aSTejun Heo /**
3143112202d9STejun Heo  * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
314473f53c4aSTejun Heo  * @wq: workqueue being flushed
314573f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
314673f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
314773f53c4aSTejun Heo  *
3148112202d9STejun Heo  * Prepare pwqs for workqueue flushing.
314973f53c4aSTejun Heo  *
3150112202d9STejun Heo  * If @flush_color is non-negative, flush_color on all pwqs should be
3151112202d9STejun Heo  * -1.  If no pwq has in-flight commands at the specified color, all
3152112202d9STejun Heo  * pwq->flush_color's stay at -1 and %false is returned.  If any pwq
3153112202d9STejun Heo  * has in flight commands, its pwq->flush_color is set to
3154112202d9STejun Heo  * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
315573f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
315673f53c4aSTejun Heo  *
315773f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
315873f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
315973f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
316073f53c4aSTejun Heo  * is returned.
316173f53c4aSTejun Heo  *
3162112202d9STejun Heo  * If @work_color is non-negative, all pwqs should have the same
316373f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
316473f53c4aSTejun Heo  * advanced to @work_color.
316573f53c4aSTejun Heo  *
316673f53c4aSTejun Heo  * CONTEXT:
31673c25a55dSLai Jiangshan  * mutex_lock(wq->mutex).
316873f53c4aSTejun Heo  *
3169d185af30SYacine Belkadi  * Return:
317073f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
317173f53c4aSTejun Heo  * otherwise.
317273f53c4aSTejun Heo  */
3173112202d9STejun Heo static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
317473f53c4aSTejun Heo 				      int flush_color, int work_color)
31751da177e4SLinus Torvalds {
317673f53c4aSTejun Heo 	bool wait = false;
317749e3cf44STejun Heo 	struct pool_workqueue *pwq;
31781da177e4SLinus Torvalds 
317973f53c4aSTejun Heo 	if (flush_color >= 0) {
31806183c009STejun Heo 		WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
3181112202d9STejun Heo 		atomic_set(&wq->nr_pwqs_to_flush, 1);
3182dc186ad7SThomas Gleixner 	}
318314441960SOleg Nesterov 
318449e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
3185112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
31861da177e4SLinus Torvalds 
3187a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
318873f53c4aSTejun Heo 
318973f53c4aSTejun Heo 		if (flush_color >= 0) {
31906183c009STejun Heo 			WARN_ON_ONCE(pwq->flush_color != -1);
319173f53c4aSTejun Heo 
3192112202d9STejun Heo 			if (pwq->nr_in_flight[flush_color]) {
3193112202d9STejun Heo 				pwq->flush_color = flush_color;
3194112202d9STejun Heo 				atomic_inc(&wq->nr_pwqs_to_flush);
319573f53c4aSTejun Heo 				wait = true;
31961da177e4SLinus Torvalds 			}
319773f53c4aSTejun Heo 		}
319873f53c4aSTejun Heo 
319973f53c4aSTejun Heo 		if (work_color >= 0) {
32006183c009STejun Heo 			WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
3201112202d9STejun Heo 			pwq->work_color = work_color;
320273f53c4aSTejun Heo 		}
320373f53c4aSTejun Heo 
3204a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
32051da177e4SLinus Torvalds 	}
32061da177e4SLinus Torvalds 
3207112202d9STejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
320873f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
320973f53c4aSTejun Heo 
321073f53c4aSTejun Heo 	return wait;
321183c22520SOleg Nesterov }
32121da177e4SLinus Torvalds 
32130fcb78c2SRolf Eike Beer /**
3214c4f135d6STetsuo Handa  * __flush_workqueue - ensure that any scheduled work has run to completion.
32150fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
32161da177e4SLinus Torvalds  *
3217c5aa87bbSTejun Heo  * This function sleeps until all work items which were queued on entry
3218c5aa87bbSTejun Heo  * have finished execution, but it is not livelocked by new incoming ones.
32191da177e4SLinus Torvalds  */
3220c4f135d6STetsuo Handa void __flush_workqueue(struct workqueue_struct *wq)
32211da177e4SLinus Torvalds {
322273f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
322373f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
322473f53c4aSTejun Heo 		.flush_color = -1,
3225fd1a5b04SByungchul Park 		.done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map),
322673f53c4aSTejun Heo 	};
322773f53c4aSTejun Heo 	int next_color;
3228b1f4ec17SOleg Nesterov 
32293347fa09STejun Heo 	if (WARN_ON(!wq_online))
32303347fa09STejun Heo 		return;
32313347fa09STejun Heo 
323287915adcSJohannes Berg 	lock_map_acquire(&wq->lockdep_map);
323387915adcSJohannes Berg 	lock_map_release(&wq->lockdep_map);
323487915adcSJohannes Berg 
32353c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
323673f53c4aSTejun Heo 
323773f53c4aSTejun Heo 	/*
323873f53c4aSTejun Heo 	 * Start-to-wait phase
323973f53c4aSTejun Heo 	 */
324073f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
324173f53c4aSTejun Heo 
324273f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
324373f53c4aSTejun Heo 		/*
324473f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
324573f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
324673f53c4aSTejun Heo 		 * by one.
324773f53c4aSTejun Heo 		 */
32486183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
324973f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
325073f53c4aSTejun Heo 		wq->work_color = next_color;
325173f53c4aSTejun Heo 
325273f53c4aSTejun Heo 		if (!wq->first_flusher) {
325373f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
32546183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
325573f53c4aSTejun Heo 
325673f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
325773f53c4aSTejun Heo 
3258112202d9STejun Heo 			if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
325973f53c4aSTejun Heo 						       wq->work_color)) {
326073f53c4aSTejun Heo 				/* nothing to flush, done */
326173f53c4aSTejun Heo 				wq->flush_color = next_color;
326273f53c4aSTejun Heo 				wq->first_flusher = NULL;
326373f53c4aSTejun Heo 				goto out_unlock;
326473f53c4aSTejun Heo 			}
326573f53c4aSTejun Heo 		} else {
326673f53c4aSTejun Heo 			/* wait in queue */
32676183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
326873f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
3269112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
327073f53c4aSTejun Heo 		}
327173f53c4aSTejun Heo 	} else {
327273f53c4aSTejun Heo 		/*
327373f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
327473f53c4aSTejun Heo 		 * The next flush completion will assign us
327573f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
327673f53c4aSTejun Heo 		 */
327773f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
327873f53c4aSTejun Heo 	}
327973f53c4aSTejun Heo 
3280fca839c0STejun Heo 	check_flush_dependency(wq, NULL);
3281fca839c0STejun Heo 
32823c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
328373f53c4aSTejun Heo 
328473f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
328573f53c4aSTejun Heo 
328673f53c4aSTejun Heo 	/*
328773f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
328873f53c4aSTejun Heo 	 *
328973f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
329073f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
329173f53c4aSTejun Heo 	 */
329200d5d15bSChris Wilson 	if (READ_ONCE(wq->first_flusher) != &this_flusher)
329373f53c4aSTejun Heo 		return;
329473f53c4aSTejun Heo 
32953c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
329673f53c4aSTejun Heo 
32974ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
32984ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
32994ce48b37STejun Heo 		goto out_unlock;
33004ce48b37STejun Heo 
330100d5d15bSChris Wilson 	WRITE_ONCE(wq->first_flusher, NULL);
330273f53c4aSTejun Heo 
33036183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&this_flusher.list));
33046183c009STejun Heo 	WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
330573f53c4aSTejun Heo 
330673f53c4aSTejun Heo 	while (true) {
330773f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
330873f53c4aSTejun Heo 
330973f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
331073f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
331173f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
331273f53c4aSTejun Heo 				break;
331373f53c4aSTejun Heo 			list_del_init(&next->list);
331473f53c4aSTejun Heo 			complete(&next->done);
331573f53c4aSTejun Heo 		}
331673f53c4aSTejun Heo 
33176183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
331873f53c4aSTejun Heo 			     wq->flush_color != work_next_color(wq->work_color));
331973f53c4aSTejun Heo 
332073f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
332173f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
332273f53c4aSTejun Heo 
332373f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
332473f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
332573f53c4aSTejun Heo 			/*
332673f53c4aSTejun Heo 			 * Assign the same color to all overflowed
332773f53c4aSTejun Heo 			 * flushers, advance work_color and append to
332873f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
332973f53c4aSTejun Heo 			 * phase for these overflowed flushers.
333073f53c4aSTejun Heo 			 */
333173f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
333273f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
333373f53c4aSTejun Heo 
333473f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
333573f53c4aSTejun Heo 
333673f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
333773f53c4aSTejun Heo 					      &wq->flusher_queue);
3338112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
333973f53c4aSTejun Heo 		}
334073f53c4aSTejun Heo 
334173f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
33426183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != wq->work_color);
334373f53c4aSTejun Heo 			break;
334473f53c4aSTejun Heo 		}
334573f53c4aSTejun Heo 
334673f53c4aSTejun Heo 		/*
334773f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
3348112202d9STejun Heo 		 * the new first flusher and arm pwqs.
334973f53c4aSTejun Heo 		 */
33506183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color == wq->work_color);
33516183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color != next->flush_color);
335273f53c4aSTejun Heo 
335373f53c4aSTejun Heo 		list_del_init(&next->list);
335473f53c4aSTejun Heo 		wq->first_flusher = next;
335573f53c4aSTejun Heo 
3356112202d9STejun Heo 		if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
335773f53c4aSTejun Heo 			break;
335873f53c4aSTejun Heo 
335973f53c4aSTejun Heo 		/*
336073f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
336173f53c4aSTejun Heo 		 * flusher and repeat cascading.
336273f53c4aSTejun Heo 		 */
336373f53c4aSTejun Heo 		wq->first_flusher = NULL;
336473f53c4aSTejun Heo 	}
336573f53c4aSTejun Heo 
336673f53c4aSTejun Heo out_unlock:
33673c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
33681da177e4SLinus Torvalds }
3369c4f135d6STetsuo Handa EXPORT_SYMBOL(__flush_workqueue);
33701da177e4SLinus Torvalds 
33719c5a2ba7STejun Heo /**
33729c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
33739c5a2ba7STejun Heo  * @wq: workqueue to drain
33749c5a2ba7STejun Heo  *
33759c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
33769c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
33779c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
3378b749b1b6SChen Hanxiao  * repeatedly until it becomes empty.  The number of flushing is determined
33799c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
33809c5a2ba7STejun Heo  * takes too long.
33819c5a2ba7STejun Heo  */
33829c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
33839c5a2ba7STejun Heo {
33849c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
338549e3cf44STejun Heo 	struct pool_workqueue *pwq;
33869c5a2ba7STejun Heo 
33879c5a2ba7STejun Heo 	/*
33889c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
33899c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
3390618b01ebSTejun Heo 	 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
33919c5a2ba7STejun Heo 	 */
339287fc741eSLai Jiangshan 	mutex_lock(&wq->mutex);
33939c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
3394618b01ebSTejun Heo 		wq->flags |= __WQ_DRAINING;
339587fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
33969c5a2ba7STejun Heo reflush:
3397c4f135d6STetsuo Handa 	__flush_workqueue(wq);
33989c5a2ba7STejun Heo 
3399b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
340076af4d93STejun Heo 
340149e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
3402fa2563e4SThomas Tuttle 		bool drained;
34039c5a2ba7STejun Heo 
3404a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
3405afa87ce8STejun Heo 		drained = pwq_is_empty(pwq);
3406a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
3407fa2563e4SThomas Tuttle 
3408fa2563e4SThomas Tuttle 		if (drained)
34099c5a2ba7STejun Heo 			continue;
34109c5a2ba7STejun Heo 
34119c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
34129c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
3413e9ad2eb3SStephen Zhang 			pr_warn("workqueue %s: %s() isn't complete after %u tries\n",
3414e9ad2eb3SStephen Zhang 				wq->name, __func__, flush_cnt);
341576af4d93STejun Heo 
3416b09f4fd3SLai Jiangshan 		mutex_unlock(&wq->mutex);
34179c5a2ba7STejun Heo 		goto reflush;
34189c5a2ba7STejun Heo 	}
34199c5a2ba7STejun Heo 
34209c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
3421618b01ebSTejun Heo 		wq->flags &= ~__WQ_DRAINING;
342287fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
34239c5a2ba7STejun Heo }
34249c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
34259c5a2ba7STejun Heo 
3426d6e89786SJohannes Berg static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
3427d6e89786SJohannes Berg 			     bool from_cancel)
3428baf59022STejun Heo {
3429baf59022STejun Heo 	struct worker *worker = NULL;
3430c9e7cf27STejun Heo 	struct worker_pool *pool;
3431112202d9STejun Heo 	struct pool_workqueue *pwq;
3432baf59022STejun Heo 
3433baf59022STejun Heo 	might_sleep();
3434baf59022STejun Heo 
343524acfb71SThomas Gleixner 	rcu_read_lock();
3436fa1b54e6STejun Heo 	pool = get_work_pool(work);
3437fa1b54e6STejun Heo 	if (!pool) {
343824acfb71SThomas Gleixner 		rcu_read_unlock();
3439fa1b54e6STejun Heo 		return false;
3440fa1b54e6STejun Heo 	}
3441fa1b54e6STejun Heo 
3442a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
34430b3dae68SLai Jiangshan 	/* see the comment in try_to_grab_pending() with the same code */
3444112202d9STejun Heo 	pwq = get_work_pwq(work);
3445112202d9STejun Heo 	if (pwq) {
3446112202d9STejun Heo 		if (unlikely(pwq->pool != pool))
3447baf59022STejun Heo 			goto already_gone;
3448606a5020STejun Heo 	} else {
3449c9e7cf27STejun Heo 		worker = find_worker_executing_work(pool, work);
3450baf59022STejun Heo 		if (!worker)
3451baf59022STejun Heo 			goto already_gone;
3452112202d9STejun Heo 		pwq = worker->current_pwq;
3453606a5020STejun Heo 	}
3454baf59022STejun Heo 
3455fca839c0STejun Heo 	check_flush_dependency(pwq->wq, work);
3456fca839c0STejun Heo 
3457112202d9STejun Heo 	insert_wq_barrier(pwq, barr, work, worker);
3458a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
3459baf59022STejun Heo 
3460e159489bSTejun Heo 	/*
3461a1d14934SPeter Zijlstra 	 * Force a lock recursion deadlock when using flush_work() inside a
3462a1d14934SPeter Zijlstra 	 * single-threaded or rescuer equipped workqueue.
3463a1d14934SPeter Zijlstra 	 *
3464a1d14934SPeter Zijlstra 	 * For single threaded workqueues the deadlock happens when the work
3465a1d14934SPeter Zijlstra 	 * is after the work issuing the flush_work(). For rescuer equipped
3466a1d14934SPeter Zijlstra 	 * workqueues the deadlock happens when the rescuer stalls, blocking
3467a1d14934SPeter Zijlstra 	 * forward progress.
3468e159489bSTejun Heo 	 */
3469d6e89786SJohannes Berg 	if (!from_cancel &&
3470d6e89786SJohannes Berg 	    (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)) {
3471112202d9STejun Heo 		lock_map_acquire(&pwq->wq->lockdep_map);
3472112202d9STejun Heo 		lock_map_release(&pwq->wq->lockdep_map);
3473a1d14934SPeter Zijlstra 	}
347424acfb71SThomas Gleixner 	rcu_read_unlock();
3475baf59022STejun Heo 	return true;
3476baf59022STejun Heo already_gone:
3477a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
347824acfb71SThomas Gleixner 	rcu_read_unlock();
3479baf59022STejun Heo 	return false;
3480baf59022STejun Heo }
3481baf59022STejun Heo 
3482d6e89786SJohannes Berg static bool __flush_work(struct work_struct *work, bool from_cancel)
3483d6e89786SJohannes Berg {
3484d6e89786SJohannes Berg 	struct wq_barrier barr;
3485d6e89786SJohannes Berg 
3486d6e89786SJohannes Berg 	if (WARN_ON(!wq_online))
3487d6e89786SJohannes Berg 		return false;
3488d6e89786SJohannes Berg 
34894d43d395STetsuo Handa 	if (WARN_ON(!work->func))
34904d43d395STetsuo Handa 		return false;
34914d43d395STetsuo Handa 
349287915adcSJohannes Berg 	lock_map_acquire(&work->lockdep_map);
349387915adcSJohannes Berg 	lock_map_release(&work->lockdep_map);
349487915adcSJohannes Berg 
3495d6e89786SJohannes Berg 	if (start_flush_work(work, &barr, from_cancel)) {
3496d6e89786SJohannes Berg 		wait_for_completion(&barr.done);
3497d6e89786SJohannes Berg 		destroy_work_on_stack(&barr.work);
3498d6e89786SJohannes Berg 		return true;
3499d6e89786SJohannes Berg 	} else {
3500d6e89786SJohannes Berg 		return false;
3501d6e89786SJohannes Berg 	}
3502d6e89786SJohannes Berg }
3503d6e89786SJohannes Berg 
3504db700897SOleg Nesterov /**
3505401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
3506401a8d04STejun Heo  * @work: the work to flush
3507db700897SOleg Nesterov  *
3508606a5020STejun Heo  * Wait until @work has finished execution.  @work is guaranteed to be idle
3509606a5020STejun Heo  * on return if it hasn't been requeued since flush started.
3510401a8d04STejun Heo  *
3511d185af30SYacine Belkadi  * Return:
3512401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3513401a8d04STejun Heo  * %false if it was already idle.
3514db700897SOleg Nesterov  */
3515401a8d04STejun Heo bool flush_work(struct work_struct *work)
3516db700897SOleg Nesterov {
3517d6e89786SJohannes Berg 	return __flush_work(work, false);
3518606a5020STejun Heo }
3519db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
3520db700897SOleg Nesterov 
35218603e1b3STejun Heo struct cwt_wait {
3522ac6424b9SIngo Molnar 	wait_queue_entry_t		wait;
35238603e1b3STejun Heo 	struct work_struct	*work;
35248603e1b3STejun Heo };
35258603e1b3STejun Heo 
3526ac6424b9SIngo Molnar static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
35278603e1b3STejun Heo {
35288603e1b3STejun Heo 	struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
35298603e1b3STejun Heo 
35308603e1b3STejun Heo 	if (cwait->work != key)
35318603e1b3STejun Heo 		return 0;
35328603e1b3STejun Heo 	return autoremove_wake_function(wait, mode, sync, key);
35338603e1b3STejun Heo }
35348603e1b3STejun Heo 
353536e227d2STejun Heo static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
3536401a8d04STejun Heo {
35378603e1b3STejun Heo 	static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
3538bbb68dfaSTejun Heo 	unsigned long flags;
35391f1f642eSOleg Nesterov 	int ret;
35401f1f642eSOleg Nesterov 
35411f1f642eSOleg Nesterov 	do {
3542bbb68dfaSTejun Heo 		ret = try_to_grab_pending(work, is_dwork, &flags);
3543bbb68dfaSTejun Heo 		/*
35448603e1b3STejun Heo 		 * If someone else is already canceling, wait for it to
35458603e1b3STejun Heo 		 * finish.  flush_work() doesn't work for PREEMPT_NONE
35468603e1b3STejun Heo 		 * because we may get scheduled between @work's completion
35478603e1b3STejun Heo 		 * and the other canceling task resuming and clearing
35488603e1b3STejun Heo 		 * CANCELING - flush_work() will return false immediately
35498603e1b3STejun Heo 		 * as @work is no longer busy, try_to_grab_pending() will
35508603e1b3STejun Heo 		 * return -ENOENT as @work is still being canceled and the
35518603e1b3STejun Heo 		 * other canceling task won't be able to clear CANCELING as
35528603e1b3STejun Heo 		 * we're hogging the CPU.
35538603e1b3STejun Heo 		 *
35548603e1b3STejun Heo 		 * Let's wait for completion using a waitqueue.  As this
35558603e1b3STejun Heo 		 * may lead to the thundering herd problem, use a custom
35568603e1b3STejun Heo 		 * wake function which matches @work along with exclusive
35578603e1b3STejun Heo 		 * wait and wakeup.
3558bbb68dfaSTejun Heo 		 */
35598603e1b3STejun Heo 		if (unlikely(ret == -ENOENT)) {
35608603e1b3STejun Heo 			struct cwt_wait cwait;
35618603e1b3STejun Heo 
35628603e1b3STejun Heo 			init_wait(&cwait.wait);
35638603e1b3STejun Heo 			cwait.wait.func = cwt_wakefn;
35648603e1b3STejun Heo 			cwait.work = work;
35658603e1b3STejun Heo 
35668603e1b3STejun Heo 			prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
35678603e1b3STejun Heo 						  TASK_UNINTERRUPTIBLE);
35688603e1b3STejun Heo 			if (work_is_canceling(work))
35698603e1b3STejun Heo 				schedule();
35708603e1b3STejun Heo 			finish_wait(&cancel_waitq, &cwait.wait);
35718603e1b3STejun Heo 		}
35721f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
35731f1f642eSOleg Nesterov 
3574bbb68dfaSTejun Heo 	/* tell other tasks trying to grab @work to back off */
3575bbb68dfaSTejun Heo 	mark_work_canceling(work);
3576bbb68dfaSTejun Heo 	local_irq_restore(flags);
3577bbb68dfaSTejun Heo 
35783347fa09STejun Heo 	/*
35793347fa09STejun Heo 	 * This allows canceling during early boot.  We know that @work
35803347fa09STejun Heo 	 * isn't executing.
35813347fa09STejun Heo 	 */
35823347fa09STejun Heo 	if (wq_online)
3583d6e89786SJohannes Berg 		__flush_work(work, true);
35843347fa09STejun Heo 
35857a22ad75STejun Heo 	clear_work_data(work);
35868603e1b3STejun Heo 
35878603e1b3STejun Heo 	/*
35888603e1b3STejun Heo 	 * Paired with prepare_to_wait() above so that either
35898603e1b3STejun Heo 	 * waitqueue_active() is visible here or !work_is_canceling() is
35908603e1b3STejun Heo 	 * visible there.
35918603e1b3STejun Heo 	 */
35928603e1b3STejun Heo 	smp_mb();
35938603e1b3STejun Heo 	if (waitqueue_active(&cancel_waitq))
35948603e1b3STejun Heo 		__wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
35958603e1b3STejun Heo 
35961f1f642eSOleg Nesterov 	return ret;
35971f1f642eSOleg Nesterov }
35981f1f642eSOleg Nesterov 
35996e84d644SOleg Nesterov /**
3600401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
3601401a8d04STejun Heo  * @work: the work to cancel
36026e84d644SOleg Nesterov  *
3603401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
3604401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
3605401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
3606401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
36071f1f642eSOleg Nesterov  *
3608401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
3609401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
36106e84d644SOleg Nesterov  *
3611401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
36126e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
3613401a8d04STejun Heo  *
3614d185af30SYacine Belkadi  * Return:
3615401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
36166e84d644SOleg Nesterov  */
3617401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
36186e84d644SOleg Nesterov {
361936e227d2STejun Heo 	return __cancel_work_timer(work, false);
3620b89deed3SOleg Nesterov }
362128e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
3622b89deed3SOleg Nesterov 
36236e84d644SOleg Nesterov /**
3624401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
3625401a8d04STejun Heo  * @dwork: the delayed work to flush
36266e84d644SOleg Nesterov  *
3627401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
3628401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
3629401a8d04STejun Heo  * considers the last queueing instance of @dwork.
36301f1f642eSOleg Nesterov  *
3631d185af30SYacine Belkadi  * Return:
3632401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3633401a8d04STejun Heo  * %false if it was already idle.
36346e84d644SOleg Nesterov  */
3635401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
3636401a8d04STejun Heo {
36378930cabaSTejun Heo 	local_irq_disable();
3638401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
363960c057bcSLai Jiangshan 		__queue_work(dwork->cpu, dwork->wq, &dwork->work);
36408930cabaSTejun Heo 	local_irq_enable();
3641401a8d04STejun Heo 	return flush_work(&dwork->work);
3642401a8d04STejun Heo }
3643401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
3644401a8d04STejun Heo 
364505f0fe6bSTejun Heo /**
364605f0fe6bSTejun Heo  * flush_rcu_work - wait for a rwork to finish executing the last queueing
364705f0fe6bSTejun Heo  * @rwork: the rcu work to flush
364805f0fe6bSTejun Heo  *
364905f0fe6bSTejun Heo  * Return:
365005f0fe6bSTejun Heo  * %true if flush_rcu_work() waited for the work to finish execution,
365105f0fe6bSTejun Heo  * %false if it was already idle.
365205f0fe6bSTejun Heo  */
365305f0fe6bSTejun Heo bool flush_rcu_work(struct rcu_work *rwork)
365405f0fe6bSTejun Heo {
365505f0fe6bSTejun Heo 	if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
365605f0fe6bSTejun Heo 		rcu_barrier();
365705f0fe6bSTejun Heo 		flush_work(&rwork->work);
365805f0fe6bSTejun Heo 		return true;
365905f0fe6bSTejun Heo 	} else {
366005f0fe6bSTejun Heo 		return flush_work(&rwork->work);
366105f0fe6bSTejun Heo 	}
366205f0fe6bSTejun Heo }
366305f0fe6bSTejun Heo EXPORT_SYMBOL(flush_rcu_work);
366405f0fe6bSTejun Heo 
3665f72b8792SJens Axboe static bool __cancel_work(struct work_struct *work, bool is_dwork)
3666f72b8792SJens Axboe {
3667f72b8792SJens Axboe 	unsigned long flags;
3668f72b8792SJens Axboe 	int ret;
3669f72b8792SJens Axboe 
3670f72b8792SJens Axboe 	do {
3671f72b8792SJens Axboe 		ret = try_to_grab_pending(work, is_dwork, &flags);
3672f72b8792SJens Axboe 	} while (unlikely(ret == -EAGAIN));
3673f72b8792SJens Axboe 
3674f72b8792SJens Axboe 	if (unlikely(ret < 0))
3675f72b8792SJens Axboe 		return false;
3676f72b8792SJens Axboe 
3677f72b8792SJens Axboe 	set_work_pool_and_clear_pending(work, get_work_pool_id(work));
3678f72b8792SJens Axboe 	local_irq_restore(flags);
3679f72b8792SJens Axboe 	return ret;
3680f72b8792SJens Axboe }
3681f72b8792SJens Axboe 
368273b4b532SAndrey Grodzovsky /*
368373b4b532SAndrey Grodzovsky  * See cancel_delayed_work()
368473b4b532SAndrey Grodzovsky  */
368573b4b532SAndrey Grodzovsky bool cancel_work(struct work_struct *work)
368673b4b532SAndrey Grodzovsky {
368773b4b532SAndrey Grodzovsky 	return __cancel_work(work, false);
368873b4b532SAndrey Grodzovsky }
368973b4b532SAndrey Grodzovsky EXPORT_SYMBOL(cancel_work);
369073b4b532SAndrey Grodzovsky 
3691401a8d04STejun Heo /**
369257b30ae7STejun Heo  * cancel_delayed_work - cancel a delayed work
369357b30ae7STejun Heo  * @dwork: delayed_work to cancel
369409383498STejun Heo  *
3695d185af30SYacine Belkadi  * Kill off a pending delayed_work.
3696d185af30SYacine Belkadi  *
3697d185af30SYacine Belkadi  * Return: %true if @dwork was pending and canceled; %false if it wasn't
3698d185af30SYacine Belkadi  * pending.
3699d185af30SYacine Belkadi  *
3700d185af30SYacine Belkadi  * Note:
3701d185af30SYacine Belkadi  * The work callback function may still be running on return, unless
3702d185af30SYacine Belkadi  * it returns %true and the work doesn't re-arm itself.  Explicitly flush or
3703d185af30SYacine Belkadi  * use cancel_delayed_work_sync() to wait on it.
370409383498STejun Heo  *
370557b30ae7STejun Heo  * This function is safe to call from any context including IRQ handler.
370609383498STejun Heo  */
370757b30ae7STejun Heo bool cancel_delayed_work(struct delayed_work *dwork)
370809383498STejun Heo {
3709f72b8792SJens Axboe 	return __cancel_work(&dwork->work, true);
371009383498STejun Heo }
371157b30ae7STejun Heo EXPORT_SYMBOL(cancel_delayed_work);
371209383498STejun Heo 
371309383498STejun Heo /**
3714401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3715401a8d04STejun Heo  * @dwork: the delayed work cancel
3716401a8d04STejun Heo  *
3717401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
3718401a8d04STejun Heo  *
3719d185af30SYacine Belkadi  * Return:
3720401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
3721401a8d04STejun Heo  */
3722401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
37236e84d644SOleg Nesterov {
372436e227d2STejun Heo 	return __cancel_work_timer(&dwork->work, true);
37256e84d644SOleg Nesterov }
3726f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
37271da177e4SLinus Torvalds 
37280fcb78c2SRolf Eike Beer /**
372931ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
3730b6136773SAndrew Morton  * @func: the function to call
3731b6136773SAndrew Morton  *
373231ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
373331ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
3734b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
373531ddd871STejun Heo  *
3736d185af30SYacine Belkadi  * Return:
373731ddd871STejun Heo  * 0 on success, -errno on failure.
3738b6136773SAndrew Morton  */
373965f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
374015316ba8SChristoph Lameter {
374115316ba8SChristoph Lameter 	int cpu;
374238f51568SNamhyung Kim 	struct work_struct __percpu *works;
374315316ba8SChristoph Lameter 
3744b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
3745b6136773SAndrew Morton 	if (!works)
374615316ba8SChristoph Lameter 		return -ENOMEM;
3747b6136773SAndrew Morton 
3748ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
374993981800STejun Heo 
375015316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
37519bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
37529bfb1839SIngo Molnar 
37539bfb1839SIngo Molnar 		INIT_WORK(work, func);
37548de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
375515316ba8SChristoph Lameter 	}
375693981800STejun Heo 
375793981800STejun Heo 	for_each_online_cpu(cpu)
37588616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
375993981800STejun Heo 
3760ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
3761b6136773SAndrew Morton 	free_percpu(works);
376215316ba8SChristoph Lameter 	return 0;
376315316ba8SChristoph Lameter }
376415316ba8SChristoph Lameter 
3765eef6a7d5SAlan Stern /**
37661fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
37671fa44ecaSJames Bottomley  * @fn:		the function to execute
37681fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
37691fa44ecaSJames Bottomley  *		be available when the work executes)
37701fa44ecaSJames Bottomley  *
37711fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
37721fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
37731fa44ecaSJames Bottomley  *
3774d185af30SYacine Belkadi  * Return:	0 - function was executed
37751fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
37761fa44ecaSJames Bottomley  */
377765f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
37781fa44ecaSJames Bottomley {
37791fa44ecaSJames Bottomley 	if (!in_interrupt()) {
378065f27f38SDavid Howells 		fn(&ew->work);
37811fa44ecaSJames Bottomley 		return 0;
37821fa44ecaSJames Bottomley 	}
37831fa44ecaSJames Bottomley 
378465f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
37851fa44ecaSJames Bottomley 	schedule_work(&ew->work);
37861fa44ecaSJames Bottomley 
37871fa44ecaSJames Bottomley 	return 1;
37881fa44ecaSJames Bottomley }
37891fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
37901fa44ecaSJames Bottomley 
37917a4e344cSTejun Heo /**
37927a4e344cSTejun Heo  * free_workqueue_attrs - free a workqueue_attrs
37937a4e344cSTejun Heo  * @attrs: workqueue_attrs to free
37947a4e344cSTejun Heo  *
37957a4e344cSTejun Heo  * Undo alloc_workqueue_attrs().
37967a4e344cSTejun Heo  */
3797513c98d0SDaniel Jordan void free_workqueue_attrs(struct workqueue_attrs *attrs)
37987a4e344cSTejun Heo {
37997a4e344cSTejun Heo 	if (attrs) {
38007a4e344cSTejun Heo 		free_cpumask_var(attrs->cpumask);
38019546b29eSTejun Heo 		free_cpumask_var(attrs->__pod_cpumask);
38027a4e344cSTejun Heo 		kfree(attrs);
38037a4e344cSTejun Heo 	}
38047a4e344cSTejun Heo }
38057a4e344cSTejun Heo 
38067a4e344cSTejun Heo /**
38077a4e344cSTejun Heo  * alloc_workqueue_attrs - allocate a workqueue_attrs
38087a4e344cSTejun Heo  *
38097a4e344cSTejun Heo  * Allocate a new workqueue_attrs, initialize with default settings and
3810d185af30SYacine Belkadi  * return it.
3811d185af30SYacine Belkadi  *
3812d185af30SYacine Belkadi  * Return: The allocated new workqueue_attr on success. %NULL on failure.
38137a4e344cSTejun Heo  */
3814513c98d0SDaniel Jordan struct workqueue_attrs *alloc_workqueue_attrs(void)
38157a4e344cSTejun Heo {
38167a4e344cSTejun Heo 	struct workqueue_attrs *attrs;
38177a4e344cSTejun Heo 
3818be69d00dSThomas Gleixner 	attrs = kzalloc(sizeof(*attrs), GFP_KERNEL);
38197a4e344cSTejun Heo 	if (!attrs)
38207a4e344cSTejun Heo 		goto fail;
3821be69d00dSThomas Gleixner 	if (!alloc_cpumask_var(&attrs->cpumask, GFP_KERNEL))
38227a4e344cSTejun Heo 		goto fail;
38239546b29eSTejun Heo 	if (!alloc_cpumask_var(&attrs->__pod_cpumask, GFP_KERNEL))
38249546b29eSTejun Heo 		goto fail;
38257a4e344cSTejun Heo 
382613e2e556STejun Heo 	cpumask_copy(attrs->cpumask, cpu_possible_mask);
3827523a301eSTejun Heo 	attrs->affn_scope = WQ_AFFN_DFL;
38287a4e344cSTejun Heo 	return attrs;
38297a4e344cSTejun Heo fail:
38307a4e344cSTejun Heo 	free_workqueue_attrs(attrs);
38317a4e344cSTejun Heo 	return NULL;
38327a4e344cSTejun Heo }
38337a4e344cSTejun Heo 
383429c91e99STejun Heo static void copy_workqueue_attrs(struct workqueue_attrs *to,
383529c91e99STejun Heo 				 const struct workqueue_attrs *from)
383629c91e99STejun Heo {
383729c91e99STejun Heo 	to->nice = from->nice;
383829c91e99STejun Heo 	cpumask_copy(to->cpumask, from->cpumask);
38399546b29eSTejun Heo 	cpumask_copy(to->__pod_cpumask, from->__pod_cpumask);
38408639ecebSTejun Heo 	to->affn_strict = from->affn_strict;
384184193c07STejun Heo 
38422865a8fbSShaohua Li 	/*
384384193c07STejun Heo 	 * Unlike hash and equality test, copying shouldn't ignore wq-only
384484193c07STejun Heo 	 * fields as copying is used for both pool and wq attrs. Instead,
384584193c07STejun Heo 	 * get_unbound_pool() explicitly clears the fields.
38462865a8fbSShaohua Li 	 */
384784193c07STejun Heo 	to->affn_scope = from->affn_scope;
3848af73f5c9STejun Heo 	to->ordered = from->ordered;
384929c91e99STejun Heo }
385029c91e99STejun Heo 
38515de7a03cSTejun Heo /*
38525de7a03cSTejun Heo  * Some attrs fields are workqueue-only. Clear them for worker_pool's. See the
38535de7a03cSTejun Heo  * comments in 'struct workqueue_attrs' definition.
38545de7a03cSTejun Heo  */
38555de7a03cSTejun Heo static void wqattrs_clear_for_pool(struct workqueue_attrs *attrs)
38565de7a03cSTejun Heo {
385784193c07STejun Heo 	attrs->affn_scope = WQ_AFFN_NR_TYPES;
38585de7a03cSTejun Heo 	attrs->ordered = false;
38595de7a03cSTejun Heo }
38605de7a03cSTejun Heo 
386129c91e99STejun Heo /* hash value of the content of @attr */
386229c91e99STejun Heo static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
386329c91e99STejun Heo {
386429c91e99STejun Heo 	u32 hash = 0;
386529c91e99STejun Heo 
386629c91e99STejun Heo 	hash = jhash_1word(attrs->nice, hash);
386713e2e556STejun Heo 	hash = jhash(cpumask_bits(attrs->cpumask),
386813e2e556STejun Heo 		     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
38699546b29eSTejun Heo 	hash = jhash(cpumask_bits(attrs->__pod_cpumask),
38709546b29eSTejun Heo 		     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
38718639ecebSTejun Heo 	hash = jhash_1word(attrs->affn_strict, hash);
387229c91e99STejun Heo 	return hash;
387329c91e99STejun Heo }
387429c91e99STejun Heo 
387529c91e99STejun Heo /* content equality test */
387629c91e99STejun Heo static bool wqattrs_equal(const struct workqueue_attrs *a,
387729c91e99STejun Heo 			  const struct workqueue_attrs *b)
387829c91e99STejun Heo {
387929c91e99STejun Heo 	if (a->nice != b->nice)
388029c91e99STejun Heo 		return false;
388129c91e99STejun Heo 	if (!cpumask_equal(a->cpumask, b->cpumask))
388229c91e99STejun Heo 		return false;
38839546b29eSTejun Heo 	if (!cpumask_equal(a->__pod_cpumask, b->__pod_cpumask))
38849546b29eSTejun Heo 		return false;
38858639ecebSTejun Heo 	if (a->affn_strict != b->affn_strict)
38868639ecebSTejun Heo 		return false;
388729c91e99STejun Heo 	return true;
388829c91e99STejun Heo }
388929c91e99STejun Heo 
38900f36ee24STejun Heo /* Update @attrs with actually available CPUs */
38910f36ee24STejun Heo static void wqattrs_actualize_cpumask(struct workqueue_attrs *attrs,
38920f36ee24STejun Heo 				      const cpumask_t *unbound_cpumask)
38930f36ee24STejun Heo {
38940f36ee24STejun Heo 	/*
38950f36ee24STejun Heo 	 * Calculate the effective CPU mask of @attrs given @unbound_cpumask. If
38960f36ee24STejun Heo 	 * @attrs->cpumask doesn't overlap with @unbound_cpumask, we fallback to
38970f36ee24STejun Heo 	 * @unbound_cpumask.
38980f36ee24STejun Heo 	 */
38990f36ee24STejun Heo 	cpumask_and(attrs->cpumask, attrs->cpumask, unbound_cpumask);
39000f36ee24STejun Heo 	if (unlikely(cpumask_empty(attrs->cpumask)))
39010f36ee24STejun Heo 		cpumask_copy(attrs->cpumask, unbound_cpumask);
39020f36ee24STejun Heo }
39030f36ee24STejun Heo 
390484193c07STejun Heo /* find wq_pod_type to use for @attrs */
390584193c07STejun Heo static const struct wq_pod_type *
390684193c07STejun Heo wqattrs_pod_type(const struct workqueue_attrs *attrs)
390784193c07STejun Heo {
3908523a301eSTejun Heo 	enum wq_affn_scope scope;
3909523a301eSTejun Heo 	struct wq_pod_type *pt;
3910523a301eSTejun Heo 
3911523a301eSTejun Heo 	/* to synchronize access to wq_affn_dfl */
3912523a301eSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3913523a301eSTejun Heo 
3914523a301eSTejun Heo 	if (attrs->affn_scope == WQ_AFFN_DFL)
3915523a301eSTejun Heo 		scope = wq_affn_dfl;
3916523a301eSTejun Heo 	else
3917523a301eSTejun Heo 		scope = attrs->affn_scope;
3918523a301eSTejun Heo 
3919523a301eSTejun Heo 	pt = &wq_pod_types[scope];
392084193c07STejun Heo 
392184193c07STejun Heo 	if (!WARN_ON_ONCE(attrs->affn_scope == WQ_AFFN_NR_TYPES) &&
392284193c07STejun Heo 	    likely(pt->nr_pods))
392384193c07STejun Heo 		return pt;
392484193c07STejun Heo 
392584193c07STejun Heo 	/*
392684193c07STejun Heo 	 * Before workqueue_init_topology(), only SYSTEM is available which is
392784193c07STejun Heo 	 * initialized in workqueue_init_early().
392884193c07STejun Heo 	 */
392984193c07STejun Heo 	pt = &wq_pod_types[WQ_AFFN_SYSTEM];
393084193c07STejun Heo 	BUG_ON(!pt->nr_pods);
393184193c07STejun Heo 	return pt;
393284193c07STejun Heo }
393384193c07STejun Heo 
39347a4e344cSTejun Heo /**
39357a4e344cSTejun Heo  * init_worker_pool - initialize a newly zalloc'd worker_pool
39367a4e344cSTejun Heo  * @pool: worker_pool to initialize
39377a4e344cSTejun Heo  *
3938402dd89dSShailendra Verma  * Initialize a newly zalloc'd @pool.  It also allocates @pool->attrs.
3939d185af30SYacine Belkadi  *
3940d185af30SYacine Belkadi  * Return: 0 on success, -errno on failure.  Even on failure, all fields
394129c91e99STejun Heo  * inside @pool proper are initialized and put_unbound_pool() can be called
394229c91e99STejun Heo  * on @pool safely to release it.
39437a4e344cSTejun Heo  */
39447a4e344cSTejun Heo static int init_worker_pool(struct worker_pool *pool)
39454e1a1f9aSTejun Heo {
3946a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_init(&pool->lock);
394729c91e99STejun Heo 	pool->id = -1;
394829c91e99STejun Heo 	pool->cpu = -1;
3949f3f90ad4STejun Heo 	pool->node = NUMA_NO_NODE;
39504e1a1f9aSTejun Heo 	pool->flags |= POOL_DISASSOCIATED;
395182607adcSTejun Heo 	pool->watchdog_ts = jiffies;
39524e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->worklist);
39534e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->idle_list);
39544e1a1f9aSTejun Heo 	hash_init(pool->busy_hash);
39554e1a1f9aSTejun Heo 
395632a6c723SKees Cook 	timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
39573f959aa3SValentin Schneider 	INIT_WORK(&pool->idle_cull_work, idle_cull_fn);
39584e1a1f9aSTejun Heo 
395932a6c723SKees Cook 	timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
39604e1a1f9aSTejun Heo 
3961da028469SLai Jiangshan 	INIT_LIST_HEAD(&pool->workers);
3962e02b9312SValentin Schneider 	INIT_LIST_HEAD(&pool->dying_workers);
39637a4e344cSTejun Heo 
39647cda9aaeSLai Jiangshan 	ida_init(&pool->worker_ida);
396529c91e99STejun Heo 	INIT_HLIST_NODE(&pool->hash_node);
396629c91e99STejun Heo 	pool->refcnt = 1;
396729c91e99STejun Heo 
396829c91e99STejun Heo 	/* shouldn't fail above this point */
3969be69d00dSThomas Gleixner 	pool->attrs = alloc_workqueue_attrs();
39707a4e344cSTejun Heo 	if (!pool->attrs)
39717a4e344cSTejun Heo 		return -ENOMEM;
39725de7a03cSTejun Heo 
39735de7a03cSTejun Heo 	wqattrs_clear_for_pool(pool->attrs);
39745de7a03cSTejun Heo 
39757a4e344cSTejun Heo 	return 0;
39764e1a1f9aSTejun Heo }
39774e1a1f9aSTejun Heo 
3978669de8bdSBart Van Assche #ifdef CONFIG_LOCKDEP
3979669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
3980669de8bdSBart Van Assche {
3981669de8bdSBart Van Assche 	char *lock_name;
3982669de8bdSBart Van Assche 
3983669de8bdSBart Van Assche 	lockdep_register_key(&wq->key);
3984669de8bdSBart Van Assche 	lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name);
3985669de8bdSBart Van Assche 	if (!lock_name)
3986669de8bdSBart Van Assche 		lock_name = wq->name;
398769a106c0SQian Cai 
398869a106c0SQian Cai 	wq->lock_name = lock_name;
3989669de8bdSBart Van Assche 	lockdep_init_map(&wq->lockdep_map, lock_name, &wq->key, 0);
3990669de8bdSBart Van Assche }
3991669de8bdSBart Van Assche 
3992669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
3993669de8bdSBart Van Assche {
3994669de8bdSBart Van Assche 	lockdep_unregister_key(&wq->key);
3995669de8bdSBart Van Assche }
3996669de8bdSBart Van Assche 
3997669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
3998669de8bdSBart Van Assche {
3999669de8bdSBart Van Assche 	if (wq->lock_name != wq->name)
4000669de8bdSBart Van Assche 		kfree(wq->lock_name);
4001669de8bdSBart Van Assche }
4002669de8bdSBart Van Assche #else
4003669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
4004669de8bdSBart Van Assche {
4005669de8bdSBart Van Assche }
4006669de8bdSBart Van Assche 
4007669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
4008669de8bdSBart Van Assche {
4009669de8bdSBart Van Assche }
4010669de8bdSBart Van Assche 
4011669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
4012669de8bdSBart Van Assche {
4013669de8bdSBart Van Assche }
4014669de8bdSBart Van Assche #endif
4015669de8bdSBart Van Assche 
4016e2dca7adSTejun Heo static void rcu_free_wq(struct rcu_head *rcu)
4017e2dca7adSTejun Heo {
4018e2dca7adSTejun Heo 	struct workqueue_struct *wq =
4019e2dca7adSTejun Heo 		container_of(rcu, struct workqueue_struct, rcu);
4020e2dca7adSTejun Heo 
4021669de8bdSBart Van Assche 	wq_free_lockdep(wq);
4022ee1ceef7STejun Heo 	free_percpu(wq->cpu_pwq);
4023e2dca7adSTejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
4024e2dca7adSTejun Heo 	kfree(wq);
4025e2dca7adSTejun Heo }
4026e2dca7adSTejun Heo 
402729c91e99STejun Heo static void rcu_free_pool(struct rcu_head *rcu)
402829c91e99STejun Heo {
402929c91e99STejun Heo 	struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
403029c91e99STejun Heo 
40317cda9aaeSLai Jiangshan 	ida_destroy(&pool->worker_ida);
403229c91e99STejun Heo 	free_workqueue_attrs(pool->attrs);
403329c91e99STejun Heo 	kfree(pool);
403429c91e99STejun Heo }
403529c91e99STejun Heo 
403629c91e99STejun Heo /**
403729c91e99STejun Heo  * put_unbound_pool - put a worker_pool
403829c91e99STejun Heo  * @pool: worker_pool to put
403929c91e99STejun Heo  *
404024acfb71SThomas Gleixner  * Put @pool.  If its refcnt reaches zero, it gets destroyed in RCU
4041c5aa87bbSTejun Heo  * safe manner.  get_unbound_pool() calls this function on its failure path
4042c5aa87bbSTejun Heo  * and this function should be able to release pools which went through,
4043c5aa87bbSTejun Heo  * successfully or not, init_worker_pool().
4044a892caccSTejun Heo  *
4045a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
404629c91e99STejun Heo  */
404729c91e99STejun Heo static void put_unbound_pool(struct worker_pool *pool)
404829c91e99STejun Heo {
404960f5a4bcSLai Jiangshan 	DECLARE_COMPLETION_ONSTACK(detach_completion);
405029c91e99STejun Heo 	struct worker *worker;
40519680540cSYang Yingliang 	LIST_HEAD(cull_list);
4052e02b9312SValentin Schneider 
4053a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
4054a892caccSTejun Heo 
4055a892caccSTejun Heo 	if (--pool->refcnt)
405629c91e99STejun Heo 		return;
405729c91e99STejun Heo 
405829c91e99STejun Heo 	/* sanity checks */
405961d0fbb4SLai Jiangshan 	if (WARN_ON(!(pool->cpu < 0)) ||
4060a892caccSTejun Heo 	    WARN_ON(!list_empty(&pool->worklist)))
406129c91e99STejun Heo 		return;
406229c91e99STejun Heo 
406329c91e99STejun Heo 	/* release id and unhash */
406429c91e99STejun Heo 	if (pool->id >= 0)
406529c91e99STejun Heo 		idr_remove(&worker_pool_idr, pool->id);
406629c91e99STejun Heo 	hash_del(&pool->hash_node);
406729c91e99STejun Heo 
4068c5aa87bbSTejun Heo 	/*
4069692b4825STejun Heo 	 * Become the manager and destroy all workers.  This prevents
4070692b4825STejun Heo 	 * @pool's workers from blocking on attach_mutex.  We're the last
4071692b4825STejun Heo 	 * manager and @pool gets freed with the flag set.
40729ab03be4SValentin Schneider 	 *
40739ab03be4SValentin Schneider 	 * Having a concurrent manager is quite unlikely to happen as we can
40749ab03be4SValentin Schneider 	 * only get here with
40759ab03be4SValentin Schneider 	 *   pwq->refcnt == pool->refcnt == 0
40769ab03be4SValentin Schneider 	 * which implies no work queued to the pool, which implies no worker can
40779ab03be4SValentin Schneider 	 * become the manager. However a worker could have taken the role of
40789ab03be4SValentin Schneider 	 * manager before the refcnts dropped to 0, since maybe_create_worker()
40799ab03be4SValentin Schneider 	 * drops pool->lock
4080c5aa87bbSTejun Heo 	 */
40819ab03be4SValentin Schneider 	while (true) {
40829ab03be4SValentin Schneider 		rcuwait_wait_event(&manager_wait,
40839ab03be4SValentin Schneider 				   !(pool->flags & POOL_MANAGER_ACTIVE),
4084d8bb65abSSebastian Andrzej Siewior 				   TASK_UNINTERRUPTIBLE);
4085e02b9312SValentin Schneider 
4086e02b9312SValentin Schneider 		mutex_lock(&wq_pool_attach_mutex);
40879ab03be4SValentin Schneider 		raw_spin_lock_irq(&pool->lock);
40889ab03be4SValentin Schneider 		if (!(pool->flags & POOL_MANAGER_ACTIVE)) {
4089692b4825STejun Heo 			pool->flags |= POOL_MANAGER_ACTIVE;
40909ab03be4SValentin Schneider 			break;
40919ab03be4SValentin Schneider 		}
40929ab03be4SValentin Schneider 		raw_spin_unlock_irq(&pool->lock);
4093e02b9312SValentin Schneider 		mutex_unlock(&wq_pool_attach_mutex);
40949ab03be4SValentin Schneider 	}
4095692b4825STejun Heo 
40961037de36SLai Jiangshan 	while ((worker = first_idle_worker(pool)))
4097e02b9312SValentin Schneider 		set_worker_dying(worker, &cull_list);
409829c91e99STejun Heo 	WARN_ON(pool->nr_workers || pool->nr_idle);
4099a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
410060f5a4bcSLai Jiangshan 
4101e02b9312SValentin Schneider 	wake_dying_workers(&cull_list);
4102e02b9312SValentin Schneider 
4103e02b9312SValentin Schneider 	if (!list_empty(&pool->workers) || !list_empty(&pool->dying_workers))
410460f5a4bcSLai Jiangshan 		pool->detach_completion = &detach_completion;
41051258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
410660f5a4bcSLai Jiangshan 
410760f5a4bcSLai Jiangshan 	if (pool->detach_completion)
410860f5a4bcSLai Jiangshan 		wait_for_completion(pool->detach_completion);
410960f5a4bcSLai Jiangshan 
411029c91e99STejun Heo 	/* shut down the timers */
411129c91e99STejun Heo 	del_timer_sync(&pool->idle_timer);
41123f959aa3SValentin Schneider 	cancel_work_sync(&pool->idle_cull_work);
411329c91e99STejun Heo 	del_timer_sync(&pool->mayday_timer);
411429c91e99STejun Heo 
411524acfb71SThomas Gleixner 	/* RCU protected to allow dereferences from get_work_pool() */
411625b00775SPaul E. McKenney 	call_rcu(&pool->rcu, rcu_free_pool);
411729c91e99STejun Heo }
411829c91e99STejun Heo 
411929c91e99STejun Heo /**
412029c91e99STejun Heo  * get_unbound_pool - get a worker_pool with the specified attributes
412129c91e99STejun Heo  * @attrs: the attributes of the worker_pool to get
412229c91e99STejun Heo  *
412329c91e99STejun Heo  * Obtain a worker_pool which has the same attributes as @attrs, bump the
412429c91e99STejun Heo  * reference count and return it.  If there already is a matching
412529c91e99STejun Heo  * worker_pool, it will be used; otherwise, this function attempts to
4126d185af30SYacine Belkadi  * create a new one.
4127a892caccSTejun Heo  *
4128a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
4129d185af30SYacine Belkadi  *
4130d185af30SYacine Belkadi  * Return: On success, a worker_pool with the same attributes as @attrs.
4131d185af30SYacine Belkadi  * On failure, %NULL.
413229c91e99STejun Heo  */
413329c91e99STejun Heo static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
413429c91e99STejun Heo {
413584193c07STejun Heo 	struct wq_pod_type *pt = &wq_pod_types[WQ_AFFN_NUMA];
413629c91e99STejun Heo 	u32 hash = wqattrs_hash(attrs);
413729c91e99STejun Heo 	struct worker_pool *pool;
413884193c07STejun Heo 	int pod, node = NUMA_NO_NODE;
413929c91e99STejun Heo 
4140a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
414129c91e99STejun Heo 
414229c91e99STejun Heo 	/* do we already have a matching pool? */
414329c91e99STejun Heo 	hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
414429c91e99STejun Heo 		if (wqattrs_equal(pool->attrs, attrs)) {
414529c91e99STejun Heo 			pool->refcnt++;
41463fb1823cSLai Jiangshan 			return pool;
414729c91e99STejun Heo 		}
414829c91e99STejun Heo 	}
414929c91e99STejun Heo 
41509546b29eSTejun Heo 	/* If __pod_cpumask is contained inside a NUMA pod, that's our node */
415184193c07STejun Heo 	for (pod = 0; pod < pt->nr_pods; pod++) {
41529546b29eSTejun Heo 		if (cpumask_subset(attrs->__pod_cpumask, pt->pod_cpus[pod])) {
415384193c07STejun Heo 			node = pt->pod_node[pod];
4154e2273584SXunlei Pang 			break;
4155e2273584SXunlei Pang 		}
4156e2273584SXunlei Pang 	}
4157e2273584SXunlei Pang 
415829c91e99STejun Heo 	/* nope, create a new one */
415984193c07STejun Heo 	pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, node);
416029c91e99STejun Heo 	if (!pool || init_worker_pool(pool) < 0)
416129c91e99STejun Heo 		goto fail;
416229c91e99STejun Heo 
416384193c07STejun Heo 	pool->node = node;
41645de7a03cSTejun Heo 	copy_workqueue_attrs(pool->attrs, attrs);
41655de7a03cSTejun Heo 	wqattrs_clear_for_pool(pool->attrs);
41662865a8fbSShaohua Li 
416729c91e99STejun Heo 	if (worker_pool_assign_id(pool) < 0)
416829c91e99STejun Heo 		goto fail;
416929c91e99STejun Heo 
417029c91e99STejun Heo 	/* create and start the initial worker */
41713347fa09STejun Heo 	if (wq_online && !create_worker(pool))
417229c91e99STejun Heo 		goto fail;
417329c91e99STejun Heo 
417429c91e99STejun Heo 	/* install */
417529c91e99STejun Heo 	hash_add(unbound_pool_hash, &pool->hash_node, hash);
41763fb1823cSLai Jiangshan 
417729c91e99STejun Heo 	return pool;
417829c91e99STejun Heo fail:
417929c91e99STejun Heo 	if (pool)
418029c91e99STejun Heo 		put_unbound_pool(pool);
418129c91e99STejun Heo 	return NULL;
418229c91e99STejun Heo }
418329c91e99STejun Heo 
41848864b4e5STejun Heo static void rcu_free_pwq(struct rcu_head *rcu)
41858864b4e5STejun Heo {
41868864b4e5STejun Heo 	kmem_cache_free(pwq_cache,
41878864b4e5STejun Heo 			container_of(rcu, struct pool_workqueue, rcu));
41888864b4e5STejun Heo }
41898864b4e5STejun Heo 
41908864b4e5STejun Heo /*
4191967b494eSTejun Heo  * Scheduled on pwq_release_worker by put_pwq() when an unbound pwq hits zero
4192967b494eSTejun Heo  * refcnt and needs to be destroyed.
41938864b4e5STejun Heo  */
4194687a9aa5STejun Heo static void pwq_release_workfn(struct kthread_work *work)
41958864b4e5STejun Heo {
41968864b4e5STejun Heo 	struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
4197687a9aa5STejun Heo 						  release_work);
41988864b4e5STejun Heo 	struct workqueue_struct *wq = pwq->wq;
41998864b4e5STejun Heo 	struct worker_pool *pool = pwq->pool;
4200b42b0bddSYang Yingliang 	bool is_last = false;
42018864b4e5STejun Heo 
4202b42b0bddSYang Yingliang 	/*
4203687a9aa5STejun Heo 	 * When @pwq is not linked, it doesn't hold any reference to the
4204b42b0bddSYang Yingliang 	 * @wq, and @wq is invalid to access.
4205b42b0bddSYang Yingliang 	 */
4206b42b0bddSYang Yingliang 	if (!list_empty(&pwq->pwqs_node)) {
42073c25a55dSLai Jiangshan 		mutex_lock(&wq->mutex);
42088864b4e5STejun Heo 		list_del_rcu(&pwq->pwqs_node);
4209bc0caf09STejun Heo 		is_last = list_empty(&wq->pwqs);
42103c25a55dSLai Jiangshan 		mutex_unlock(&wq->mutex);
4211b42b0bddSYang Yingliang 	}
42128864b4e5STejun Heo 
4213687a9aa5STejun Heo 	if (wq->flags & WQ_UNBOUND) {
4214a892caccSTejun Heo 		mutex_lock(&wq_pool_mutex);
42158864b4e5STejun Heo 		put_unbound_pool(pool);
4216a892caccSTejun Heo 		mutex_unlock(&wq_pool_mutex);
4217687a9aa5STejun Heo 	}
4218a892caccSTejun Heo 
421925b00775SPaul E. McKenney 	call_rcu(&pwq->rcu, rcu_free_pwq);
42208864b4e5STejun Heo 
42218864b4e5STejun Heo 	/*
42228864b4e5STejun Heo 	 * If we're the last pwq going away, @wq is already dead and no one
4223e2dca7adSTejun Heo 	 * is gonna access it anymore.  Schedule RCU free.
42248864b4e5STejun Heo 	 */
4225669de8bdSBart Van Assche 	if (is_last) {
4226669de8bdSBart Van Assche 		wq_unregister_lockdep(wq);
422725b00775SPaul E. McKenney 		call_rcu(&wq->rcu, rcu_free_wq);
42286029a918STejun Heo 	}
4229669de8bdSBart Van Assche }
42308864b4e5STejun Heo 
423167dc8325SCai Huoqing /* initialize newly allocated @pwq which is associated with @wq and @pool */
4232f147f29eSTejun Heo static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
4233f147f29eSTejun Heo 		     struct worker_pool *pool)
4234d2c1d404STejun Heo {
4235d2c1d404STejun Heo 	BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
4236d2c1d404STejun Heo 
4237e50aba9aSTejun Heo 	memset(pwq, 0, sizeof(*pwq));
4238e50aba9aSTejun Heo 
4239d2c1d404STejun Heo 	pwq->pool = pool;
4240d2c1d404STejun Heo 	pwq->wq = wq;
4241d2c1d404STejun Heo 	pwq->flush_color = -1;
42428864b4e5STejun Heo 	pwq->refcnt = 1;
4243f97a4a1aSLai Jiangshan 	INIT_LIST_HEAD(&pwq->inactive_works);
42441befcf30STejun Heo 	INIT_LIST_HEAD(&pwq->pwqs_node);
4245d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->mayday_node);
4246687a9aa5STejun Heo 	kthread_init_work(&pwq->release_work, pwq_release_workfn);
4247f147f29eSTejun Heo }
4248d2c1d404STejun Heo 
4249f147f29eSTejun Heo /* sync @pwq with the current state of its associated wq and link it */
42501befcf30STejun Heo static void link_pwq(struct pool_workqueue *pwq)
4251f147f29eSTejun Heo {
4252f147f29eSTejun Heo 	struct workqueue_struct *wq = pwq->wq;
4253f147f29eSTejun Heo 
4254f147f29eSTejun Heo 	lockdep_assert_held(&wq->mutex);
425575ccf595STejun Heo 
42561befcf30STejun Heo 	/* may be called multiple times, ignore if already linked */
42571befcf30STejun Heo 	if (!list_empty(&pwq->pwqs_node))
42581befcf30STejun Heo 		return;
42591befcf30STejun Heo 
426029b1cb41SLai Jiangshan 	/* set the matching work_color */
426175ccf595STejun Heo 	pwq->work_color = wq->work_color;
4262983ca25eSTejun Heo 
4263983ca25eSTejun Heo 	/* link in @pwq */
42649e8cd2f5STejun Heo 	list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
4265df2d5ae4STejun Heo }
42666029a918STejun Heo 
4267f147f29eSTejun Heo /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
4268f147f29eSTejun Heo static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
4269f147f29eSTejun Heo 					const struct workqueue_attrs *attrs)
4270f147f29eSTejun Heo {
4271f147f29eSTejun Heo 	struct worker_pool *pool;
4272f147f29eSTejun Heo 	struct pool_workqueue *pwq;
4273f147f29eSTejun Heo 
4274f147f29eSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
4275f147f29eSTejun Heo 
4276f147f29eSTejun Heo 	pool = get_unbound_pool(attrs);
4277f147f29eSTejun Heo 	if (!pool)
4278f147f29eSTejun Heo 		return NULL;
4279f147f29eSTejun Heo 
4280e50aba9aSTejun Heo 	pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
4281f147f29eSTejun Heo 	if (!pwq) {
4282f147f29eSTejun Heo 		put_unbound_pool(pool);
4283f147f29eSTejun Heo 		return NULL;
4284f147f29eSTejun Heo 	}
4285f147f29eSTejun Heo 
4286f147f29eSTejun Heo 	init_pwq(pwq, wq, pool);
4287f147f29eSTejun Heo 	return pwq;
4288d2c1d404STejun Heo }
4289d2c1d404STejun Heo 
42904c16bd32STejun Heo /**
4291fef59c9cSTejun Heo  * wq_calc_pod_cpumask - calculate a wq_attrs' cpumask for a pod
4292042f7df1SLai Jiangshan  * @attrs: the wq_attrs of the default pwq of the target workqueue
429384193c07STejun Heo  * @cpu: the target CPU
42944c16bd32STejun Heo  * @cpu_going_down: if >= 0, the CPU to consider as offline
42954c16bd32STejun Heo  *
4296fef59c9cSTejun Heo  * Calculate the cpumask a workqueue with @attrs should use on @pod. If
4297fef59c9cSTejun Heo  * @cpu_going_down is >= 0, that cpu is considered offline during calculation.
42989546b29eSTejun Heo  * The result is stored in @attrs->__pod_cpumask.
42994c16bd32STejun Heo  *
4300fef59c9cSTejun Heo  * If pod affinity is not enabled, @attrs->cpumask is always used. If enabled
4301fef59c9cSTejun Heo  * and @pod has online CPUs requested by @attrs, the returned cpumask is the
4302fef59c9cSTejun Heo  * intersection of the possible CPUs of @pod and @attrs->cpumask.
43034c16bd32STejun Heo  *
4304fef59c9cSTejun Heo  * The caller is responsible for ensuring that the cpumask of @pod stays stable.
43054c16bd32STejun Heo  */
43069546b29eSTejun Heo static void wq_calc_pod_cpumask(struct workqueue_attrs *attrs, int cpu,
43079546b29eSTejun Heo 				int cpu_going_down)
43084c16bd32STejun Heo {
430984193c07STejun Heo 	const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
431084193c07STejun Heo 	int pod = pt->cpu_pod[cpu];
43114c16bd32STejun Heo 
4312fef59c9cSTejun Heo 	/* does @pod have any online CPUs @attrs wants? */
43139546b29eSTejun Heo 	cpumask_and(attrs->__pod_cpumask, pt->pod_cpus[pod], attrs->cpumask);
43149546b29eSTejun Heo 	cpumask_and(attrs->__pod_cpumask, attrs->__pod_cpumask, cpu_online_mask);
43154c16bd32STejun Heo 	if (cpu_going_down >= 0)
43169546b29eSTejun Heo 		cpumask_clear_cpu(cpu_going_down, attrs->__pod_cpumask);
43174c16bd32STejun Heo 
43189546b29eSTejun Heo 	if (cpumask_empty(attrs->__pod_cpumask)) {
43199546b29eSTejun Heo 		cpumask_copy(attrs->__pod_cpumask, attrs->cpumask);
432084193c07STejun Heo 		return;
432184193c07STejun Heo 	}
43224c16bd32STejun Heo 
4323fef59c9cSTejun Heo 	/* yeap, return possible CPUs in @pod that @attrs wants */
43249546b29eSTejun Heo 	cpumask_and(attrs->__pod_cpumask, attrs->cpumask, pt->pod_cpus[pod]);
43251ad0f0a7SMichael Bringmann 
43269546b29eSTejun Heo 	if (cpumask_empty(attrs->__pod_cpumask))
43271ad0f0a7SMichael Bringmann 		pr_warn_once("WARNING: workqueue cpumask: online intersect > "
43281ad0f0a7SMichael Bringmann 				"possible intersect\n");
43294c16bd32STejun Heo }
43304c16bd32STejun Heo 
4331636b927eSTejun Heo /* install @pwq into @wq's cpu_pwq and return the old pwq */
4332636b927eSTejun Heo static struct pool_workqueue *install_unbound_pwq(struct workqueue_struct *wq,
4333636b927eSTejun Heo 					int cpu, struct pool_workqueue *pwq)
43341befcf30STejun Heo {
43351befcf30STejun Heo 	struct pool_workqueue *old_pwq;
43361befcf30STejun Heo 
43375b95e1afSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
43381befcf30STejun Heo 	lockdep_assert_held(&wq->mutex);
43391befcf30STejun Heo 
43401befcf30STejun Heo 	/* link_pwq() can handle duplicate calls */
43411befcf30STejun Heo 	link_pwq(pwq);
43421befcf30STejun Heo 
4343636b927eSTejun Heo 	old_pwq = rcu_access_pointer(*per_cpu_ptr(wq->cpu_pwq, cpu));
4344636b927eSTejun Heo 	rcu_assign_pointer(*per_cpu_ptr(wq->cpu_pwq, cpu), pwq);
43451befcf30STejun Heo 	return old_pwq;
43461befcf30STejun Heo }
43471befcf30STejun Heo 
43482d5f0764SLai Jiangshan /* context to store the prepared attrs & pwqs before applying */
43492d5f0764SLai Jiangshan struct apply_wqattrs_ctx {
43502d5f0764SLai Jiangshan 	struct workqueue_struct	*wq;		/* target workqueue */
43512d5f0764SLai Jiangshan 	struct workqueue_attrs	*attrs;		/* attrs to apply */
4352042f7df1SLai Jiangshan 	struct list_head	list;		/* queued for batching commit */
43532d5f0764SLai Jiangshan 	struct pool_workqueue	*dfl_pwq;
43542d5f0764SLai Jiangshan 	struct pool_workqueue	*pwq_tbl[];
43552d5f0764SLai Jiangshan };
43562d5f0764SLai Jiangshan 
43572d5f0764SLai Jiangshan /* free the resources after success or abort */
43582d5f0764SLai Jiangshan static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
43592d5f0764SLai Jiangshan {
43602d5f0764SLai Jiangshan 	if (ctx) {
4361636b927eSTejun Heo 		int cpu;
43622d5f0764SLai Jiangshan 
4363636b927eSTejun Heo 		for_each_possible_cpu(cpu)
4364636b927eSTejun Heo 			put_pwq_unlocked(ctx->pwq_tbl[cpu]);
43652d5f0764SLai Jiangshan 		put_pwq_unlocked(ctx->dfl_pwq);
43662d5f0764SLai Jiangshan 
43672d5f0764SLai Jiangshan 		free_workqueue_attrs(ctx->attrs);
43682d5f0764SLai Jiangshan 
43692d5f0764SLai Jiangshan 		kfree(ctx);
43702d5f0764SLai Jiangshan 	}
43712d5f0764SLai Jiangshan }
43722d5f0764SLai Jiangshan 
43732d5f0764SLai Jiangshan /* allocate the attrs and pwqs for later installation */
43742d5f0764SLai Jiangshan static struct apply_wqattrs_ctx *
43752d5f0764SLai Jiangshan apply_wqattrs_prepare(struct workqueue_struct *wq,
437699c621efSLai Jiangshan 		      const struct workqueue_attrs *attrs,
437799c621efSLai Jiangshan 		      const cpumask_var_t unbound_cpumask)
43782d5f0764SLai Jiangshan {
43792d5f0764SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
43809546b29eSTejun Heo 	struct workqueue_attrs *new_attrs;
4381636b927eSTejun Heo 	int cpu;
43822d5f0764SLai Jiangshan 
43832d5f0764SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
43842d5f0764SLai Jiangshan 
438584193c07STejun Heo 	if (WARN_ON(attrs->affn_scope < 0 ||
438684193c07STejun Heo 		    attrs->affn_scope >= WQ_AFFN_NR_TYPES))
438784193c07STejun Heo 		return ERR_PTR(-EINVAL);
438884193c07STejun Heo 
4389636b927eSTejun Heo 	ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_cpu_ids), GFP_KERNEL);
43902d5f0764SLai Jiangshan 
4391be69d00dSThomas Gleixner 	new_attrs = alloc_workqueue_attrs();
43929546b29eSTejun Heo 	if (!ctx || !new_attrs)
43932d5f0764SLai Jiangshan 		goto out_free;
43942d5f0764SLai Jiangshan 
4395042f7df1SLai Jiangshan 	/*
43962d5f0764SLai Jiangshan 	 * If something goes wrong during CPU up/down, we'll fall back to
43972d5f0764SLai Jiangshan 	 * the default pwq covering whole @attrs->cpumask.  Always create
43982d5f0764SLai Jiangshan 	 * it even if we don't use it immediately.
43992d5f0764SLai Jiangshan 	 */
44000f36ee24STejun Heo 	copy_workqueue_attrs(new_attrs, attrs);
44010f36ee24STejun Heo 	wqattrs_actualize_cpumask(new_attrs, unbound_cpumask);
44029546b29eSTejun Heo 	cpumask_copy(new_attrs->__pod_cpumask, new_attrs->cpumask);
44032d5f0764SLai Jiangshan 	ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
44042d5f0764SLai Jiangshan 	if (!ctx->dfl_pwq)
44052d5f0764SLai Jiangshan 		goto out_free;
44062d5f0764SLai Jiangshan 
4407636b927eSTejun Heo 	for_each_possible_cpu(cpu) {
4408af73f5c9STejun Heo 		if (new_attrs->ordered) {
44092d5f0764SLai Jiangshan 			ctx->dfl_pwq->refcnt++;
4410636b927eSTejun Heo 			ctx->pwq_tbl[cpu] = ctx->dfl_pwq;
4411636b927eSTejun Heo 		} else {
44129546b29eSTejun Heo 			wq_calc_pod_cpumask(new_attrs, cpu, -1);
44139546b29eSTejun Heo 			ctx->pwq_tbl[cpu] = alloc_unbound_pwq(wq, new_attrs);
4414636b927eSTejun Heo 			if (!ctx->pwq_tbl[cpu])
4415636b927eSTejun Heo 				goto out_free;
44162d5f0764SLai Jiangshan 		}
44172d5f0764SLai Jiangshan 	}
44182d5f0764SLai Jiangshan 
4419042f7df1SLai Jiangshan 	/* save the user configured attrs and sanitize it. */
4420042f7df1SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
4421042f7df1SLai Jiangshan 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
44229546b29eSTejun Heo 	cpumask_copy(new_attrs->__pod_cpumask, new_attrs->cpumask);
44232d5f0764SLai Jiangshan 	ctx->attrs = new_attrs;
4424042f7df1SLai Jiangshan 
44252d5f0764SLai Jiangshan 	ctx->wq = wq;
44262d5f0764SLai Jiangshan 	return ctx;
44272d5f0764SLai Jiangshan 
44282d5f0764SLai Jiangshan out_free:
44292d5f0764SLai Jiangshan 	free_workqueue_attrs(new_attrs);
44302d5f0764SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
443184193c07STejun Heo 	return ERR_PTR(-ENOMEM);
44322d5f0764SLai Jiangshan }
44332d5f0764SLai Jiangshan 
44342d5f0764SLai Jiangshan /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
44352d5f0764SLai Jiangshan static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
44362d5f0764SLai Jiangshan {
4437636b927eSTejun Heo 	int cpu;
44382d5f0764SLai Jiangshan 
44392d5f0764SLai Jiangshan 	/* all pwqs have been created successfully, let's install'em */
44402d5f0764SLai Jiangshan 	mutex_lock(&ctx->wq->mutex);
44412d5f0764SLai Jiangshan 
44422d5f0764SLai Jiangshan 	copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
44432d5f0764SLai Jiangshan 
44442d5f0764SLai Jiangshan 	/* save the previous pwq and install the new one */
4445636b927eSTejun Heo 	for_each_possible_cpu(cpu)
4446636b927eSTejun Heo 		ctx->pwq_tbl[cpu] = install_unbound_pwq(ctx->wq, cpu,
4447636b927eSTejun Heo 							ctx->pwq_tbl[cpu]);
44482d5f0764SLai Jiangshan 
44492d5f0764SLai Jiangshan 	/* @dfl_pwq might not have been used, ensure it's linked */
44502d5f0764SLai Jiangshan 	link_pwq(ctx->dfl_pwq);
44512d5f0764SLai Jiangshan 	swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
44522d5f0764SLai Jiangshan 
44532d5f0764SLai Jiangshan 	mutex_unlock(&ctx->wq->mutex);
44542d5f0764SLai Jiangshan }
44552d5f0764SLai Jiangshan 
4456a0111cf6SLai Jiangshan static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
4457a0111cf6SLai Jiangshan 					const struct workqueue_attrs *attrs)
4458a0111cf6SLai Jiangshan {
4459a0111cf6SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
4460a0111cf6SLai Jiangshan 
4461a0111cf6SLai Jiangshan 	/* only unbound workqueues can change attributes */
4462a0111cf6SLai Jiangshan 	if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
4463a0111cf6SLai Jiangshan 		return -EINVAL;
4464a0111cf6SLai Jiangshan 
4465a0111cf6SLai Jiangshan 	/* creating multiple pwqs breaks ordering guarantee */
44660a94efb5STejun Heo 	if (!list_empty(&wq->pwqs)) {
44670a94efb5STejun Heo 		if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
4468a0111cf6SLai Jiangshan 			return -EINVAL;
4469a0111cf6SLai Jiangshan 
44700a94efb5STejun Heo 		wq->flags &= ~__WQ_ORDERED;
44710a94efb5STejun Heo 	}
44720a94efb5STejun Heo 
447399c621efSLai Jiangshan 	ctx = apply_wqattrs_prepare(wq, attrs, wq_unbound_cpumask);
447484193c07STejun Heo 	if (IS_ERR(ctx))
447584193c07STejun Heo 		return PTR_ERR(ctx);
4476a0111cf6SLai Jiangshan 
4477a0111cf6SLai Jiangshan 	/* the ctx has been prepared successfully, let's commit it */
4478a0111cf6SLai Jiangshan 	apply_wqattrs_commit(ctx);
4479a0111cf6SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
4480a0111cf6SLai Jiangshan 
44816201171eSwanghaibin 	return 0;
4482a0111cf6SLai Jiangshan }
4483a0111cf6SLai Jiangshan 
44849e8cd2f5STejun Heo /**
44859e8cd2f5STejun Heo  * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
44869e8cd2f5STejun Heo  * @wq: the target workqueue
44879e8cd2f5STejun Heo  * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
44889e8cd2f5STejun Heo  *
4489fef59c9cSTejun Heo  * Apply @attrs to an unbound workqueue @wq. Unless disabled, this function maps
4490fef59c9cSTejun Heo  * a separate pwq to each CPU pod with possibles CPUs in @attrs->cpumask so that
4491fef59c9cSTejun Heo  * work items are affine to the pod it was issued on. Older pwqs are released as
4492fef59c9cSTejun Heo  * in-flight work items finish. Note that a work item which repeatedly requeues
4493fef59c9cSTejun Heo  * itself back-to-back will stay on its current pwq.
44949e8cd2f5STejun Heo  *
4495d185af30SYacine Belkadi  * Performs GFP_KERNEL allocations.
4496d185af30SYacine Belkadi  *
4497ffd8bea8SSebastian Andrzej Siewior  * Assumes caller has CPU hotplug read exclusion, i.e. cpus_read_lock().
4498509b3204SDaniel Jordan  *
4499d185af30SYacine Belkadi  * Return: 0 on success and -errno on failure.
45009e8cd2f5STejun Heo  */
4501513c98d0SDaniel Jordan int apply_workqueue_attrs(struct workqueue_struct *wq,
45029e8cd2f5STejun Heo 			  const struct workqueue_attrs *attrs)
45039e8cd2f5STejun Heo {
4504a0111cf6SLai Jiangshan 	int ret;
45059e8cd2f5STejun Heo 
4506509b3204SDaniel Jordan 	lockdep_assert_cpus_held();
4507509b3204SDaniel Jordan 
4508509b3204SDaniel Jordan 	mutex_lock(&wq_pool_mutex);
4509a0111cf6SLai Jiangshan 	ret = apply_workqueue_attrs_locked(wq, attrs);
4510509b3204SDaniel Jordan 	mutex_unlock(&wq_pool_mutex);
45112d5f0764SLai Jiangshan 
45122d5f0764SLai Jiangshan 	return ret;
45139e8cd2f5STejun Heo }
45149e8cd2f5STejun Heo 
45154c16bd32STejun Heo /**
4516fef59c9cSTejun Heo  * wq_update_pod - update pod affinity of a wq for CPU hot[un]plug
45174c16bd32STejun Heo  * @wq: the target workqueue
45184cbfd3deSTejun Heo  * @cpu: the CPU to update pool association for
45194cbfd3deSTejun Heo  * @hotplug_cpu: the CPU coming up or going down
45204c16bd32STejun Heo  * @online: whether @cpu is coming up or going down
45214c16bd32STejun Heo  *
45224c16bd32STejun Heo  * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
4523fef59c9cSTejun Heo  * %CPU_DOWN_FAILED.  @cpu is being hot[un]plugged, update pod affinity of
45244c16bd32STejun Heo  * @wq accordingly.
45254c16bd32STejun Heo  *
45264c16bd32STejun Heo  *
4527fef59c9cSTejun Heo  * If pod affinity can't be adjusted due to memory allocation failure, it falls
4528fef59c9cSTejun Heo  * back to @wq->dfl_pwq which may not be optimal but is always correct.
4529fef59c9cSTejun Heo  *
4530fef59c9cSTejun Heo  * Note that when the last allowed CPU of a pod goes offline for a workqueue
4531fef59c9cSTejun Heo  * with a cpumask spanning multiple pods, the workers which were already
4532fef59c9cSTejun Heo  * executing the work items for the workqueue will lose their CPU affinity and
4533fef59c9cSTejun Heo  * may execute on any CPU. This is similar to how per-cpu workqueues behave on
4534fef59c9cSTejun Heo  * CPU_DOWN. If a workqueue user wants strict affinity, it's the user's
4535fef59c9cSTejun Heo  * responsibility to flush the work item from CPU_DOWN_PREPARE.
45364c16bd32STejun Heo  */
4537fef59c9cSTejun Heo static void wq_update_pod(struct workqueue_struct *wq, int cpu,
45384cbfd3deSTejun Heo 			  int hotplug_cpu, bool online)
45394c16bd32STejun Heo {
45404cbfd3deSTejun Heo 	int off_cpu = online ? -1 : hotplug_cpu;
45414c16bd32STejun Heo 	struct pool_workqueue *old_pwq = NULL, *pwq;
45424c16bd32STejun Heo 	struct workqueue_attrs *target_attrs;
45434c16bd32STejun Heo 
45444c16bd32STejun Heo 	lockdep_assert_held(&wq_pool_mutex);
45454c16bd32STejun Heo 
454684193c07STejun Heo 	if (!(wq->flags & WQ_UNBOUND) || wq->unbound_attrs->ordered)
45474c16bd32STejun Heo 		return;
45484c16bd32STejun Heo 
45494c16bd32STejun Heo 	/*
45504c16bd32STejun Heo 	 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
45514c16bd32STejun Heo 	 * Let's use a preallocated one.  The following buf is protected by
45524c16bd32STejun Heo 	 * CPU hotplug exclusion.
45534c16bd32STejun Heo 	 */
4554fef59c9cSTejun Heo 	target_attrs = wq_update_pod_attrs_buf;
45554c16bd32STejun Heo 
45564c16bd32STejun Heo 	copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
45570f36ee24STejun Heo 	wqattrs_actualize_cpumask(target_attrs, wq_unbound_cpumask);
45584c16bd32STejun Heo 
4559636b927eSTejun Heo 	/* nothing to do if the target cpumask matches the current pwq */
45609546b29eSTejun Heo 	wq_calc_pod_cpumask(target_attrs, cpu, off_cpu);
4561636b927eSTejun Heo 	pwq = rcu_dereference_protected(*per_cpu_ptr(wq->cpu_pwq, cpu),
4562636b927eSTejun Heo 					lockdep_is_held(&wq_pool_mutex));
45639546b29eSTejun Heo 	if (wqattrs_equal(target_attrs, pwq->pool->attrs))
4564f7142ed4SLai Jiangshan 		return;
45654c16bd32STejun Heo 
45664c16bd32STejun Heo 	/* create a new pwq */
45674c16bd32STejun Heo 	pwq = alloc_unbound_pwq(wq, target_attrs);
45684c16bd32STejun Heo 	if (!pwq) {
4569fef59c9cSTejun Heo 		pr_warn("workqueue: allocation failed while updating CPU pod affinity of \"%s\"\n",
45704c16bd32STejun Heo 			wq->name);
457177f300b1SDaeseok Youn 		goto use_dfl_pwq;
45724c16bd32STejun Heo 	}
45734c16bd32STejun Heo 
4574f7142ed4SLai Jiangshan 	/* Install the new pwq. */
45754c16bd32STejun Heo 	mutex_lock(&wq->mutex);
4576636b927eSTejun Heo 	old_pwq = install_unbound_pwq(wq, cpu, pwq);
45774c16bd32STejun Heo 	goto out_unlock;
45784c16bd32STejun Heo 
45794c16bd32STejun Heo use_dfl_pwq:
4580f7142ed4SLai Jiangshan 	mutex_lock(&wq->mutex);
4581a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&wq->dfl_pwq->pool->lock);
45824c16bd32STejun Heo 	get_pwq(wq->dfl_pwq);
4583a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&wq->dfl_pwq->pool->lock);
4584636b927eSTejun Heo 	old_pwq = install_unbound_pwq(wq, cpu, wq->dfl_pwq);
45854c16bd32STejun Heo out_unlock:
45864c16bd32STejun Heo 	mutex_unlock(&wq->mutex);
45874c16bd32STejun Heo 	put_pwq_unlocked(old_pwq);
45884c16bd32STejun Heo }
45894c16bd32STejun Heo 
459030cdf249STejun Heo static int alloc_and_link_pwqs(struct workqueue_struct *wq)
45911da177e4SLinus Torvalds {
459249e3cf44STejun Heo 	bool highpri = wq->flags & WQ_HIGHPRI;
45938a2b7538STejun Heo 	int cpu, ret;
4594e1d8aa9fSFrederic Weisbecker 
4595687a9aa5STejun Heo 	wq->cpu_pwq = alloc_percpu(struct pool_workqueue *);
4596ee1ceef7STejun Heo 	if (!wq->cpu_pwq)
4597687a9aa5STejun Heo 		goto enomem;
459830cdf249STejun Heo 
4599636b927eSTejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
460030cdf249STejun Heo 		for_each_possible_cpu(cpu) {
4601687a9aa5STejun Heo 			struct pool_workqueue **pwq_p =
4602ee1ceef7STejun Heo 				per_cpu_ptr(wq->cpu_pwq, cpu);
4603687a9aa5STejun Heo 			struct worker_pool *pool =
4604687a9aa5STejun Heo 				&(per_cpu_ptr(cpu_worker_pools, cpu)[highpri]);
460530cdf249STejun Heo 
4606687a9aa5STejun Heo 			*pwq_p = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL,
4607687a9aa5STejun Heo 						       pool->node);
4608687a9aa5STejun Heo 			if (!*pwq_p)
4609687a9aa5STejun Heo 				goto enomem;
4610687a9aa5STejun Heo 
4611687a9aa5STejun Heo 			init_pwq(*pwq_p, wq, pool);
4612f147f29eSTejun Heo 
4613f147f29eSTejun Heo 			mutex_lock(&wq->mutex);
4614687a9aa5STejun Heo 			link_pwq(*pwq_p);
4615f147f29eSTejun Heo 			mutex_unlock(&wq->mutex);
461630cdf249STejun Heo 		}
461730cdf249STejun Heo 		return 0;
4618509b3204SDaniel Jordan 	}
4619509b3204SDaniel Jordan 
4620ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
4621509b3204SDaniel Jordan 	if (wq->flags & __WQ_ORDERED) {
46228a2b7538STejun Heo 		ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
46238a2b7538STejun Heo 		/* there should only be single pwq for ordering guarantee */
46248a2b7538STejun Heo 		WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
46258a2b7538STejun Heo 			      wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
46268a2b7538STejun Heo 		     "ordering guarantee broken for workqueue %s\n", wq->name);
46279e8cd2f5STejun Heo 	} else {
4628509b3204SDaniel Jordan 		ret = apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
46299e8cd2f5STejun Heo 	}
4630ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
4631509b3204SDaniel Jordan 
463264344553SZqiang 	/* for unbound pwq, flush the pwq_release_worker ensures that the
463364344553SZqiang 	 * pwq_release_workfn() completes before calling kfree(wq).
463464344553SZqiang 	 */
463564344553SZqiang 	if (ret)
463664344553SZqiang 		kthread_flush_worker(pwq_release_worker);
463764344553SZqiang 
4638509b3204SDaniel Jordan 	return ret;
4639687a9aa5STejun Heo 
4640687a9aa5STejun Heo enomem:
4641687a9aa5STejun Heo 	if (wq->cpu_pwq) {
46427b42f401SZqiang 		for_each_possible_cpu(cpu) {
46437b42f401SZqiang 			struct pool_workqueue *pwq = *per_cpu_ptr(wq->cpu_pwq, cpu);
46447b42f401SZqiang 
46457b42f401SZqiang 			if (pwq)
46467b42f401SZqiang 				kmem_cache_free(pwq_cache, pwq);
46477b42f401SZqiang 		}
4648687a9aa5STejun Heo 		free_percpu(wq->cpu_pwq);
4649687a9aa5STejun Heo 		wq->cpu_pwq = NULL;
4650687a9aa5STejun Heo 	}
4651687a9aa5STejun Heo 	return -ENOMEM;
46520f900049STejun Heo }
46530f900049STejun Heo 
4654f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
4655f3421797STejun Heo 			       const char *name)
4656b71ab8c2STejun Heo {
4657636b927eSTejun Heo 	if (max_active < 1 || max_active > WQ_MAX_ACTIVE)
4658044c782cSValentin Ilie 		pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
4659636b927eSTejun Heo 			max_active, name, 1, WQ_MAX_ACTIVE);
4660b71ab8c2STejun Heo 
4661636b927eSTejun Heo 	return clamp_val(max_active, 1, WQ_MAX_ACTIVE);
4662b71ab8c2STejun Heo }
4663b71ab8c2STejun Heo 
4664983c7515STejun Heo /*
4665983c7515STejun Heo  * Workqueues which may be used during memory reclaim should have a rescuer
4666983c7515STejun Heo  * to guarantee forward progress.
4667983c7515STejun Heo  */
4668983c7515STejun Heo static int init_rescuer(struct workqueue_struct *wq)
4669983c7515STejun Heo {
4670983c7515STejun Heo 	struct worker *rescuer;
4671b92b36eaSDan Carpenter 	int ret;
4672983c7515STejun Heo 
4673983c7515STejun Heo 	if (!(wq->flags & WQ_MEM_RECLAIM))
4674983c7515STejun Heo 		return 0;
4675983c7515STejun Heo 
4676983c7515STejun Heo 	rescuer = alloc_worker(NUMA_NO_NODE);
46774c0736a7SPetr Mladek 	if (!rescuer) {
46784c0736a7SPetr Mladek 		pr_err("workqueue: Failed to allocate a rescuer for wq \"%s\"\n",
46794c0736a7SPetr Mladek 		       wq->name);
4680983c7515STejun Heo 		return -ENOMEM;
46814c0736a7SPetr Mladek 	}
4682983c7515STejun Heo 
4683983c7515STejun Heo 	rescuer->rescue_wq = wq;
4684b6a46f72SAaron Tomlin 	rescuer->task = kthread_create(rescuer_thread, rescuer, "kworker/R-%s", wq->name);
4685f187b697SSean Fu 	if (IS_ERR(rescuer->task)) {
4686b92b36eaSDan Carpenter 		ret = PTR_ERR(rescuer->task);
46874c0736a7SPetr Mladek 		pr_err("workqueue: Failed to create a rescuer kthread for wq \"%s\": %pe",
46884c0736a7SPetr Mladek 		       wq->name, ERR_PTR(ret));
4689983c7515STejun Heo 		kfree(rescuer);
4690b92b36eaSDan Carpenter 		return ret;
4691983c7515STejun Heo 	}
4692983c7515STejun Heo 
4693983c7515STejun Heo 	wq->rescuer = rescuer;
469485f0ab43SJuri Lelli 	if (wq->flags & WQ_UNBOUND)
469585f0ab43SJuri Lelli 		kthread_bind_mask(rescuer->task, wq->unbound_attrs->cpumask);
469685f0ab43SJuri Lelli 	else
4697983c7515STejun Heo 		kthread_bind_mask(rescuer->task, cpu_possible_mask);
4698983c7515STejun Heo 	wake_up_process(rescuer->task);
4699983c7515STejun Heo 
4700983c7515STejun Heo 	return 0;
4701983c7515STejun Heo }
4702983c7515STejun Heo 
4703a045a272STejun Heo /**
4704a045a272STejun Heo  * wq_adjust_max_active - update a wq's max_active to the current setting
4705a045a272STejun Heo  * @wq: target workqueue
4706a045a272STejun Heo  *
4707a045a272STejun Heo  * If @wq isn't freezing, set @wq->max_active to the saved_max_active and
4708a045a272STejun Heo  * activate inactive work items accordingly. If @wq is freezing, clear
4709a045a272STejun Heo  * @wq->max_active to zero.
4710a045a272STejun Heo  */
4711a045a272STejun Heo static void wq_adjust_max_active(struct workqueue_struct *wq)
4712a045a272STejun Heo {
4713*c5404d4eSTejun Heo 	bool activated;
4714a045a272STejun Heo 
4715a045a272STejun Heo 	lockdep_assert_held(&wq->mutex);
4716a045a272STejun Heo 
4717a045a272STejun Heo 	if ((wq->flags & WQ_FREEZABLE) && workqueue_freezing) {
4718a045a272STejun Heo 		WRITE_ONCE(wq->max_active, 0);
4719a045a272STejun Heo 		return;
4720a045a272STejun Heo 	}
4721a045a272STejun Heo 
4722a045a272STejun Heo 	if (wq->max_active == wq->saved_max_active)
4723a045a272STejun Heo 		return;
4724a045a272STejun Heo 
4725a045a272STejun Heo 	/*
4726a045a272STejun Heo 	 * Update @wq->max_active and then kick inactive work items if more
4727a045a272STejun Heo 	 * active work items are allowed. This doesn't break work item ordering
4728a045a272STejun Heo 	 * because new work items are always queued behind existing inactive
4729a045a272STejun Heo 	 * work items if there are any.
4730a045a272STejun Heo 	 */
4731a045a272STejun Heo 	WRITE_ONCE(wq->max_active, wq->saved_max_active);
4732a045a272STejun Heo 
4733*c5404d4eSTejun Heo 	/*
4734*c5404d4eSTejun Heo 	 * Round-robin through pwq's activating the first inactive work item
4735*c5404d4eSTejun Heo 	 * until max_active is filled.
4736*c5404d4eSTejun Heo 	 */
4737*c5404d4eSTejun Heo 	do {
4738*c5404d4eSTejun Heo 		struct pool_workqueue *pwq;
4739*c5404d4eSTejun Heo 
4740*c5404d4eSTejun Heo 		activated = false;
4741a045a272STejun Heo 		for_each_pwq(pwq, wq) {
4742a045a272STejun Heo 			unsigned long flags;
4743a045a272STejun Heo 
4744*c5404d4eSTejun Heo 			/* can be called during early boot w/ irq disabled */
4745a045a272STejun Heo 			raw_spin_lock_irqsave(&pwq->pool->lock, flags);
4746*c5404d4eSTejun Heo 			if (pwq_activate_first_inactive(pwq)) {
4747*c5404d4eSTejun Heo 				activated = true;
4748a045a272STejun Heo 				kick_pool(pwq->pool);
4749*c5404d4eSTejun Heo 			}
4750a045a272STejun Heo 			raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
4751a045a272STejun Heo 		}
4752*c5404d4eSTejun Heo 	} while (activated);
4753a045a272STejun Heo }
4754a045a272STejun Heo 
4755a2775bbcSMathieu Malaterre __printf(1, 4)
4756669de8bdSBart Van Assche struct workqueue_struct *alloc_workqueue(const char *fmt,
475797e37d7bSTejun Heo 					 unsigned int flags,
4758669de8bdSBart Van Assche 					 int max_active, ...)
47593af24433SOleg Nesterov {
4760ecf6881fSTejun Heo 	va_list args;
47613af24433SOleg Nesterov 	struct workqueue_struct *wq;
476231c89007SAudra Mitchell 	int len;
4763b196be89STejun Heo 
47645c0338c6STejun Heo 	/*
4765fef59c9cSTejun Heo 	 * Unbound && max_active == 1 used to imply ordered, which is no longer
4766fef59c9cSTejun Heo 	 * the case on many machines due to per-pod pools. While
47675c0338c6STejun Heo 	 * alloc_ordered_workqueue() is the right way to create an ordered
4768fef59c9cSTejun Heo 	 * workqueue, keep the previous behavior to avoid subtle breakages.
47695c0338c6STejun Heo 	 */
47705c0338c6STejun Heo 	if ((flags & WQ_UNBOUND) && max_active == 1)
47715c0338c6STejun Heo 		flags |= __WQ_ORDERED;
47725c0338c6STejun Heo 
4773cee22a15SViresh Kumar 	/* see the comment above the definition of WQ_POWER_EFFICIENT */
4774cee22a15SViresh Kumar 	if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
4775cee22a15SViresh Kumar 		flags |= WQ_UNBOUND;
4776cee22a15SViresh Kumar 
4777ecf6881fSTejun Heo 	/* allocate wq and format name */
4778636b927eSTejun Heo 	wq = kzalloc(sizeof(*wq), GFP_KERNEL);
4779b196be89STejun Heo 	if (!wq)
4780d2c1d404STejun Heo 		return NULL;
4781b196be89STejun Heo 
47826029a918STejun Heo 	if (flags & WQ_UNBOUND) {
4783be69d00dSThomas Gleixner 		wq->unbound_attrs = alloc_workqueue_attrs();
47846029a918STejun Heo 		if (!wq->unbound_attrs)
47856029a918STejun Heo 			goto err_free_wq;
47866029a918STejun Heo 	}
47876029a918STejun Heo 
4788669de8bdSBart Van Assche 	va_start(args, max_active);
478931c89007SAudra Mitchell 	len = vsnprintf(wq->name, sizeof(wq->name), fmt, args);
4790b196be89STejun Heo 	va_end(args);
47913af24433SOleg Nesterov 
479231c89007SAudra Mitchell 	if (len >= WQ_NAME_LEN)
479331c89007SAudra Mitchell 		pr_warn_once("workqueue: name exceeds WQ_NAME_LEN. Truncating to: %s\n", wq->name);
479431c89007SAudra Mitchell 
4795d320c038STejun Heo 	max_active = max_active ?: WQ_DFL_ACTIVE;
4796b196be89STejun Heo 	max_active = wq_clamp_max_active(max_active, flags, wq->name);
47973af24433SOleg Nesterov 
4798b196be89STejun Heo 	/* init wq */
479997e37d7bSTejun Heo 	wq->flags = flags;
4800a045a272STejun Heo 	wq->max_active = max_active;
4801a0a1a5fdSTejun Heo 	wq->saved_max_active = max_active;
48023c25a55dSLai Jiangshan 	mutex_init(&wq->mutex);
4803112202d9STejun Heo 	atomic_set(&wq->nr_pwqs_to_flush, 0);
480430cdf249STejun Heo 	INIT_LIST_HEAD(&wq->pwqs);
480573f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
480673f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
4807493a1724STejun Heo 	INIT_LIST_HEAD(&wq->maydays);
48083af24433SOleg Nesterov 
4809669de8bdSBart Van Assche 	wq_init_lockdep(wq);
4810cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
48113af24433SOleg Nesterov 
481230cdf249STejun Heo 	if (alloc_and_link_pwqs(wq) < 0)
481382efcab3SBart Van Assche 		goto err_unreg_lockdep;
48141537663fSTejun Heo 
481540c17f75STejun Heo 	if (wq_online && init_rescuer(wq) < 0)
4816d2c1d404STejun Heo 		goto err_destroy;
4817e22bee78STejun Heo 
4818226223abSTejun Heo 	if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
4819226223abSTejun Heo 		goto err_destroy;
4820226223abSTejun Heo 
48216af8bf3dSOleg Nesterov 	/*
482268e13a67SLai Jiangshan 	 * wq_pool_mutex protects global freeze state and workqueues list.
482368e13a67SLai Jiangshan 	 * Grab it, adjust max_active and add the new @wq to workqueues
482468e13a67SLai Jiangshan 	 * list.
48256af8bf3dSOleg Nesterov 	 */
482668e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4827a0a1a5fdSTejun Heo 
4828a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
4829a045a272STejun Heo 	wq_adjust_max_active(wq);
4830a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4831a0a1a5fdSTejun Heo 
4832e2dca7adSTejun Heo 	list_add_tail_rcu(&wq->list, &workqueues);
4833a0a1a5fdSTejun Heo 
483468e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
48353af24433SOleg Nesterov 
48363af24433SOleg Nesterov 	return wq;
4837d2c1d404STejun Heo 
483882efcab3SBart Van Assche err_unreg_lockdep:
4839009bb421SBart Van Assche 	wq_unregister_lockdep(wq);
4840009bb421SBart Van Assche 	wq_free_lockdep(wq);
484182efcab3SBart Van Assche err_free_wq:
48426029a918STejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
48434690c4abSTejun Heo 	kfree(wq);
4844d2c1d404STejun Heo 	return NULL;
4845d2c1d404STejun Heo err_destroy:
4846d2c1d404STejun Heo 	destroy_workqueue(wq);
48474690c4abSTejun Heo 	return NULL;
48481da177e4SLinus Torvalds }
4849669de8bdSBart Van Assche EXPORT_SYMBOL_GPL(alloc_workqueue);
48501da177e4SLinus Torvalds 
4851c29eb853STejun Heo static bool pwq_busy(struct pool_workqueue *pwq)
4852c29eb853STejun Heo {
4853c29eb853STejun Heo 	int i;
4854c29eb853STejun Heo 
4855c29eb853STejun Heo 	for (i = 0; i < WORK_NR_COLORS; i++)
4856c29eb853STejun Heo 		if (pwq->nr_in_flight[i])
4857c29eb853STejun Heo 			return true;
4858c29eb853STejun Heo 
4859c29eb853STejun Heo 	if ((pwq != pwq->wq->dfl_pwq) && (pwq->refcnt > 1))
4860c29eb853STejun Heo 		return true;
4861afa87ce8STejun Heo 	if (!pwq_is_empty(pwq))
4862c29eb853STejun Heo 		return true;
4863c29eb853STejun Heo 
4864c29eb853STejun Heo 	return false;
4865c29eb853STejun Heo }
4866c29eb853STejun Heo 
48673af24433SOleg Nesterov /**
48683af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
48693af24433SOleg Nesterov  * @wq: target workqueue
48703af24433SOleg Nesterov  *
48713af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
48723af24433SOleg Nesterov  */
48733af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
48743af24433SOleg Nesterov {
487549e3cf44STejun Heo 	struct pool_workqueue *pwq;
4876636b927eSTejun Heo 	int cpu;
48773af24433SOleg Nesterov 
4878def98c84STejun Heo 	/*
4879def98c84STejun Heo 	 * Remove it from sysfs first so that sanity check failure doesn't
4880def98c84STejun Heo 	 * lead to sysfs name conflicts.
4881def98c84STejun Heo 	 */
4882def98c84STejun Heo 	workqueue_sysfs_unregister(wq);
4883def98c84STejun Heo 
488433e3f0a3SRichard Clark 	/* mark the workqueue destruction is in progress */
488533e3f0a3SRichard Clark 	mutex_lock(&wq->mutex);
488633e3f0a3SRichard Clark 	wq->flags |= __WQ_DESTROYING;
488733e3f0a3SRichard Clark 	mutex_unlock(&wq->mutex);
488833e3f0a3SRichard Clark 
48899c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
48909c5a2ba7STejun Heo 	drain_workqueue(wq);
4891c8efcc25STejun Heo 
4892def98c84STejun Heo 	/* kill rescuer, if sanity checks fail, leave it w/o rescuer */
4893def98c84STejun Heo 	if (wq->rescuer) {
4894def98c84STejun Heo 		struct worker *rescuer = wq->rescuer;
4895def98c84STejun Heo 
4896def98c84STejun Heo 		/* this prevents new queueing */
4897a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&wq_mayday_lock);
4898def98c84STejun Heo 		wq->rescuer = NULL;
4899a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&wq_mayday_lock);
4900def98c84STejun Heo 
4901def98c84STejun Heo 		/* rescuer will empty maydays list before exiting */
4902def98c84STejun Heo 		kthread_stop(rescuer->task);
49038efe1223STejun Heo 		kfree(rescuer);
4904def98c84STejun Heo 	}
4905def98c84STejun Heo 
4906c29eb853STejun Heo 	/*
4907c29eb853STejun Heo 	 * Sanity checks - grab all the locks so that we wait for all
4908c29eb853STejun Heo 	 * in-flight operations which may do put_pwq().
4909c29eb853STejun Heo 	 */
4910c29eb853STejun Heo 	mutex_lock(&wq_pool_mutex);
4911b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
491249e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
4913a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
4914c29eb853STejun Heo 		if (WARN_ON(pwq_busy(pwq))) {
49151d9a6159SKefeng Wang 			pr_warn("%s: %s has the following busy pwq\n",
4916e66b39afSTejun Heo 				__func__, wq->name);
4917c29eb853STejun Heo 			show_pwq(pwq);
4918a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&pwq->pool->lock);
4919b09f4fd3SLai Jiangshan 			mutex_unlock(&wq->mutex);
4920c29eb853STejun Heo 			mutex_unlock(&wq_pool_mutex);
492155df0933SImran Khan 			show_one_workqueue(wq);
49226183c009STejun Heo 			return;
492376af4d93STejun Heo 		}
4924a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
492576af4d93STejun Heo 	}
4926b09f4fd3SLai Jiangshan 	mutex_unlock(&wq->mutex);
49276183c009STejun Heo 
4928a0a1a5fdSTejun Heo 	/*
4929a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
4930a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
4931a0a1a5fdSTejun Heo 	 */
4932e2dca7adSTejun Heo 	list_del_rcu(&wq->list);
493368e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
49343af24433SOleg Nesterov 
49358864b4e5STejun Heo 	/*
4936636b927eSTejun Heo 	 * We're the sole accessor of @wq. Directly access cpu_pwq and dfl_pwq
4937636b927eSTejun Heo 	 * to put the base refs. @wq will be auto-destroyed from the last
4938636b927eSTejun Heo 	 * pwq_put. RCU read lock prevents @wq from going away from under us.
49398864b4e5STejun Heo 	 */
4940636b927eSTejun Heo 	rcu_read_lock();
4941636b927eSTejun Heo 
4942636b927eSTejun Heo 	for_each_possible_cpu(cpu) {
4943636b927eSTejun Heo 		pwq = rcu_access_pointer(*per_cpu_ptr(wq->cpu_pwq, cpu));
4944636b927eSTejun Heo 		RCU_INIT_POINTER(*per_cpu_ptr(wq->cpu_pwq, cpu), NULL);
49454c16bd32STejun Heo 		put_pwq_unlocked(pwq);
49464c16bd32STejun Heo 	}
49474c16bd32STejun Heo 
4948636b927eSTejun Heo 	put_pwq_unlocked(wq->dfl_pwq);
49494c16bd32STejun Heo 	wq->dfl_pwq = NULL;
4950636b927eSTejun Heo 
4951636b927eSTejun Heo 	rcu_read_unlock();
49523af24433SOleg Nesterov }
49533af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
49543af24433SOleg Nesterov 
4955dcd989cbSTejun Heo /**
4956dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
4957dcd989cbSTejun Heo  * @wq: target workqueue
4958dcd989cbSTejun Heo  * @max_active: new max_active value.
4959dcd989cbSTejun Heo  *
4960dcd989cbSTejun Heo  * Set max_active of @wq to @max_active.
4961dcd989cbSTejun Heo  *
4962dcd989cbSTejun Heo  * CONTEXT:
4963dcd989cbSTejun Heo  * Don't call from IRQ context.
4964dcd989cbSTejun Heo  */
4965dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4966dcd989cbSTejun Heo {
49678719dceaSTejun Heo 	/* disallow meddling with max_active for ordered workqueues */
49680a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
49698719dceaSTejun Heo 		return;
49708719dceaSTejun Heo 
4971f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4972dcd989cbSTejun Heo 
4973a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
4974dcd989cbSTejun Heo 
49750a94efb5STejun Heo 	wq->flags &= ~__WQ_ORDERED;
4976dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
4977a045a272STejun Heo 	wq_adjust_max_active(wq);
4978dcd989cbSTejun Heo 
4979a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4980dcd989cbSTejun Heo }
4981dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4982dcd989cbSTejun Heo 
4983dcd989cbSTejun Heo /**
498427d4ee03SLukas Wunner  * current_work - retrieve %current task's work struct
498527d4ee03SLukas Wunner  *
498627d4ee03SLukas Wunner  * Determine if %current task is a workqueue worker and what it's working on.
498727d4ee03SLukas Wunner  * Useful to find out the context that the %current task is running in.
498827d4ee03SLukas Wunner  *
498927d4ee03SLukas Wunner  * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
499027d4ee03SLukas Wunner  */
499127d4ee03SLukas Wunner struct work_struct *current_work(void)
499227d4ee03SLukas Wunner {
499327d4ee03SLukas Wunner 	struct worker *worker = current_wq_worker();
499427d4ee03SLukas Wunner 
499527d4ee03SLukas Wunner 	return worker ? worker->current_work : NULL;
499627d4ee03SLukas Wunner }
499727d4ee03SLukas Wunner EXPORT_SYMBOL(current_work);
499827d4ee03SLukas Wunner 
499927d4ee03SLukas Wunner /**
5000e6267616STejun Heo  * current_is_workqueue_rescuer - is %current workqueue rescuer?
5001e6267616STejun Heo  *
5002e6267616STejun Heo  * Determine whether %current is a workqueue rescuer.  Can be used from
5003e6267616STejun Heo  * work functions to determine whether it's being run off the rescuer task.
5004d185af30SYacine Belkadi  *
5005d185af30SYacine Belkadi  * Return: %true if %current is a workqueue rescuer. %false otherwise.
5006e6267616STejun Heo  */
5007e6267616STejun Heo bool current_is_workqueue_rescuer(void)
5008e6267616STejun Heo {
5009e6267616STejun Heo 	struct worker *worker = current_wq_worker();
5010e6267616STejun Heo 
50116a092dfdSLai Jiangshan 	return worker && worker->rescue_wq;
5012e6267616STejun Heo }
5013e6267616STejun Heo 
5014e6267616STejun Heo /**
5015dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
5016dcd989cbSTejun Heo  * @cpu: CPU in question
5017dcd989cbSTejun Heo  * @wq: target workqueue
5018dcd989cbSTejun Heo  *
5019dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
5020dcd989cbSTejun Heo  * no synchronization around this function and the test result is
5021dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
5022dcd989cbSTejun Heo  *
5023d3251859STejun Heo  * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
5024636b927eSTejun Heo  *
5025636b927eSTejun Heo  * With the exception of ordered workqueues, all workqueues have per-cpu
5026636b927eSTejun Heo  * pool_workqueues, each with its own congested state. A workqueue being
5027636b927eSTejun Heo  * congested on one CPU doesn't mean that the workqueue is contested on any
5028636b927eSTejun Heo  * other CPUs.
5029d3251859STejun Heo  *
5030d185af30SYacine Belkadi  * Return:
5031dcd989cbSTejun Heo  * %true if congested, %false otherwise.
5032dcd989cbSTejun Heo  */
5033d84ff051STejun Heo bool workqueue_congested(int cpu, struct workqueue_struct *wq)
5034dcd989cbSTejun Heo {
50357fb98ea7STejun Heo 	struct pool_workqueue *pwq;
503676af4d93STejun Heo 	bool ret;
503776af4d93STejun Heo 
503824acfb71SThomas Gleixner 	rcu_read_lock();
503924acfb71SThomas Gleixner 	preempt_disable();
50407fb98ea7STejun Heo 
5041d3251859STejun Heo 	if (cpu == WORK_CPU_UNBOUND)
5042d3251859STejun Heo 		cpu = smp_processor_id();
5043d3251859STejun Heo 
5044687a9aa5STejun Heo 	pwq = *per_cpu_ptr(wq->cpu_pwq, cpu);
5045f97a4a1aSLai Jiangshan 	ret = !list_empty(&pwq->inactive_works);
5046636b927eSTejun Heo 
504724acfb71SThomas Gleixner 	preempt_enable();
504824acfb71SThomas Gleixner 	rcu_read_unlock();
504976af4d93STejun Heo 
505076af4d93STejun Heo 	return ret;
5051dcd989cbSTejun Heo }
5052dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
5053dcd989cbSTejun Heo 
5054dcd989cbSTejun Heo /**
5055dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
5056dcd989cbSTejun Heo  * @work: the work to be tested
5057dcd989cbSTejun Heo  *
5058dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
5059dcd989cbSTejun Heo  * synchronization around this function and the test result is
5060dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
5061dcd989cbSTejun Heo  *
5062d185af30SYacine Belkadi  * Return:
5063dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
5064dcd989cbSTejun Heo  */
5065dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
5066dcd989cbSTejun Heo {
5067fa1b54e6STejun Heo 	struct worker_pool *pool;
5068dcd989cbSTejun Heo 	unsigned long flags;
5069dcd989cbSTejun Heo 	unsigned int ret = 0;
5070dcd989cbSTejun Heo 
5071dcd989cbSTejun Heo 	if (work_pending(work))
5072dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
5073038366c5SLai Jiangshan 
507424acfb71SThomas Gleixner 	rcu_read_lock();
5075fa1b54e6STejun Heo 	pool = get_work_pool(work);
5076038366c5SLai Jiangshan 	if (pool) {
5077a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irqsave(&pool->lock, flags);
5078c9e7cf27STejun Heo 		if (find_worker_executing_work(pool, work))
5079dcd989cbSTejun Heo 			ret |= WORK_BUSY_RUNNING;
5080a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&pool->lock, flags);
5081038366c5SLai Jiangshan 	}
508224acfb71SThomas Gleixner 	rcu_read_unlock();
5083dcd989cbSTejun Heo 
5084dcd989cbSTejun Heo 	return ret;
5085dcd989cbSTejun Heo }
5086dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
5087dcd989cbSTejun Heo 
50883d1cb205STejun Heo /**
50893d1cb205STejun Heo  * set_worker_desc - set description for the current work item
50903d1cb205STejun Heo  * @fmt: printf-style format string
50913d1cb205STejun Heo  * @...: arguments for the format string
50923d1cb205STejun Heo  *
50933d1cb205STejun Heo  * This function can be called by a running work function to describe what
50943d1cb205STejun Heo  * the work item is about.  If the worker task gets dumped, this
50953d1cb205STejun Heo  * information will be printed out together to help debugging.  The
50963d1cb205STejun Heo  * description can be at most WORKER_DESC_LEN including the trailing '\0'.
50973d1cb205STejun Heo  */
50983d1cb205STejun Heo void set_worker_desc(const char *fmt, ...)
50993d1cb205STejun Heo {
51003d1cb205STejun Heo 	struct worker *worker = current_wq_worker();
51013d1cb205STejun Heo 	va_list args;
51023d1cb205STejun Heo 
51033d1cb205STejun Heo 	if (worker) {
51043d1cb205STejun Heo 		va_start(args, fmt);
51053d1cb205STejun Heo 		vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
51063d1cb205STejun Heo 		va_end(args);
51073d1cb205STejun Heo 	}
51083d1cb205STejun Heo }
51095c750d58SSteffen Maier EXPORT_SYMBOL_GPL(set_worker_desc);
51103d1cb205STejun Heo 
51113d1cb205STejun Heo /**
51123d1cb205STejun Heo  * print_worker_info - print out worker information and description
51133d1cb205STejun Heo  * @log_lvl: the log level to use when printing
51143d1cb205STejun Heo  * @task: target task
51153d1cb205STejun Heo  *
51163d1cb205STejun Heo  * If @task is a worker and currently executing a work item, print out the
51173d1cb205STejun Heo  * name of the workqueue being serviced and worker description set with
51183d1cb205STejun Heo  * set_worker_desc() by the currently executing work item.
51193d1cb205STejun Heo  *
51203d1cb205STejun Heo  * This function can be safely called on any task as long as the
51213d1cb205STejun Heo  * task_struct itself is accessible.  While safe, this function isn't
51223d1cb205STejun Heo  * synchronized and may print out mixups or garbages of limited length.
51233d1cb205STejun Heo  */
51243d1cb205STejun Heo void print_worker_info(const char *log_lvl, struct task_struct *task)
51253d1cb205STejun Heo {
51263d1cb205STejun Heo 	work_func_t *fn = NULL;
51273d1cb205STejun Heo 	char name[WQ_NAME_LEN] = { };
51283d1cb205STejun Heo 	char desc[WORKER_DESC_LEN] = { };
51293d1cb205STejun Heo 	struct pool_workqueue *pwq = NULL;
51303d1cb205STejun Heo 	struct workqueue_struct *wq = NULL;
51313d1cb205STejun Heo 	struct worker *worker;
51323d1cb205STejun Heo 
51333d1cb205STejun Heo 	if (!(task->flags & PF_WQ_WORKER))
51343d1cb205STejun Heo 		return;
51353d1cb205STejun Heo 
51363d1cb205STejun Heo 	/*
51373d1cb205STejun Heo 	 * This function is called without any synchronization and @task
51383d1cb205STejun Heo 	 * could be in any state.  Be careful with dereferences.
51393d1cb205STejun Heo 	 */
5140e700591aSPetr Mladek 	worker = kthread_probe_data(task);
51413d1cb205STejun Heo 
51423d1cb205STejun Heo 	/*
51438bf89593STejun Heo 	 * Carefully copy the associated workqueue's workfn, name and desc.
51448bf89593STejun Heo 	 * Keep the original last '\0' in case the original is garbage.
51453d1cb205STejun Heo 	 */
5146fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&fn, &worker->current_func, sizeof(fn));
5147fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&pwq, &worker->current_pwq, sizeof(pwq));
5148fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&wq, &pwq->wq, sizeof(wq));
5149fe557319SChristoph Hellwig 	copy_from_kernel_nofault(name, wq->name, sizeof(name) - 1);
5150fe557319SChristoph Hellwig 	copy_from_kernel_nofault(desc, worker->desc, sizeof(desc) - 1);
51513d1cb205STejun Heo 
51523d1cb205STejun Heo 	if (fn || name[0] || desc[0]) {
5153d75f773cSSakari Ailus 		printk("%sWorkqueue: %s %ps", log_lvl, name, fn);
51548bf89593STejun Heo 		if (strcmp(name, desc))
51553d1cb205STejun Heo 			pr_cont(" (%s)", desc);
51563d1cb205STejun Heo 		pr_cont("\n");
51573d1cb205STejun Heo 	}
51583d1cb205STejun Heo }
51593d1cb205STejun Heo 
51603494fc30STejun Heo static void pr_cont_pool_info(struct worker_pool *pool)
51613494fc30STejun Heo {
51623494fc30STejun Heo 	pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
51633494fc30STejun Heo 	if (pool->node != NUMA_NO_NODE)
51643494fc30STejun Heo 		pr_cont(" node=%d", pool->node);
51653494fc30STejun Heo 	pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
51663494fc30STejun Heo }
51673494fc30STejun Heo 
5168c76feb0dSPaul E. McKenney struct pr_cont_work_struct {
5169c76feb0dSPaul E. McKenney 	bool comma;
5170c76feb0dSPaul E. McKenney 	work_func_t func;
5171c76feb0dSPaul E. McKenney 	long ctr;
5172c76feb0dSPaul E. McKenney };
5173c76feb0dSPaul E. McKenney 
5174c76feb0dSPaul E. McKenney static void pr_cont_work_flush(bool comma, work_func_t func, struct pr_cont_work_struct *pcwsp)
5175c76feb0dSPaul E. McKenney {
5176c76feb0dSPaul E. McKenney 	if (!pcwsp->ctr)
5177c76feb0dSPaul E. McKenney 		goto out_record;
5178c76feb0dSPaul E. McKenney 	if (func == pcwsp->func) {
5179c76feb0dSPaul E. McKenney 		pcwsp->ctr++;
5180c76feb0dSPaul E. McKenney 		return;
5181c76feb0dSPaul E. McKenney 	}
5182c76feb0dSPaul E. McKenney 	if (pcwsp->ctr == 1)
5183c76feb0dSPaul E. McKenney 		pr_cont("%s %ps", pcwsp->comma ? "," : "", pcwsp->func);
5184c76feb0dSPaul E. McKenney 	else
5185c76feb0dSPaul E. McKenney 		pr_cont("%s %ld*%ps", pcwsp->comma ? "," : "", pcwsp->ctr, pcwsp->func);
5186c76feb0dSPaul E. McKenney 	pcwsp->ctr = 0;
5187c76feb0dSPaul E. McKenney out_record:
5188c76feb0dSPaul E. McKenney 	if ((long)func == -1L)
5189c76feb0dSPaul E. McKenney 		return;
5190c76feb0dSPaul E. McKenney 	pcwsp->comma = comma;
5191c76feb0dSPaul E. McKenney 	pcwsp->func = func;
5192c76feb0dSPaul E. McKenney 	pcwsp->ctr = 1;
5193c76feb0dSPaul E. McKenney }
5194c76feb0dSPaul E. McKenney 
5195c76feb0dSPaul E. McKenney static void pr_cont_work(bool comma, struct work_struct *work, struct pr_cont_work_struct *pcwsp)
51963494fc30STejun Heo {
51973494fc30STejun Heo 	if (work->func == wq_barrier_func) {
51983494fc30STejun Heo 		struct wq_barrier *barr;
51993494fc30STejun Heo 
52003494fc30STejun Heo 		barr = container_of(work, struct wq_barrier, work);
52013494fc30STejun Heo 
5202c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
52033494fc30STejun Heo 		pr_cont("%s BAR(%d)", comma ? "," : "",
52043494fc30STejun Heo 			task_pid_nr(barr->task));
52053494fc30STejun Heo 	} else {
5206c76feb0dSPaul E. McKenney 		if (!comma)
5207c76feb0dSPaul E. McKenney 			pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
5208c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, work->func, pcwsp);
52093494fc30STejun Heo 	}
52103494fc30STejun Heo }
52113494fc30STejun Heo 
52123494fc30STejun Heo static void show_pwq(struct pool_workqueue *pwq)
52133494fc30STejun Heo {
5214c76feb0dSPaul E. McKenney 	struct pr_cont_work_struct pcws = { .ctr = 0, };
52153494fc30STejun Heo 	struct worker_pool *pool = pwq->pool;
52163494fc30STejun Heo 	struct work_struct *work;
52173494fc30STejun Heo 	struct worker *worker;
52183494fc30STejun Heo 	bool has_in_flight = false, has_pending = false;
52193494fc30STejun Heo 	int bkt;
52203494fc30STejun Heo 
52213494fc30STejun Heo 	pr_info("  pwq %d:", pool->id);
52223494fc30STejun Heo 	pr_cont_pool_info(pool);
52233494fc30STejun Heo 
5224a045a272STejun Heo 	pr_cont(" active=%d refcnt=%d%s\n",
5225a045a272STejun Heo 		pwq->nr_active, pwq->refcnt,
52263494fc30STejun Heo 		!list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
52273494fc30STejun Heo 
52283494fc30STejun Heo 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
52293494fc30STejun Heo 		if (worker->current_pwq == pwq) {
52303494fc30STejun Heo 			has_in_flight = true;
52313494fc30STejun Heo 			break;
52323494fc30STejun Heo 		}
52333494fc30STejun Heo 	}
52343494fc30STejun Heo 	if (has_in_flight) {
52353494fc30STejun Heo 		bool comma = false;
52363494fc30STejun Heo 
52373494fc30STejun Heo 		pr_info("    in-flight:");
52383494fc30STejun Heo 		hash_for_each(pool->busy_hash, bkt, worker, hentry) {
52393494fc30STejun Heo 			if (worker->current_pwq != pwq)
52403494fc30STejun Heo 				continue;
52413494fc30STejun Heo 
5242d75f773cSSakari Ailus 			pr_cont("%s %d%s:%ps", comma ? "," : "",
52433494fc30STejun Heo 				task_pid_nr(worker->task),
524430ae2fc0STejun Heo 				worker->rescue_wq ? "(RESCUER)" : "",
52453494fc30STejun Heo 				worker->current_func);
52463494fc30STejun Heo 			list_for_each_entry(work, &worker->scheduled, entry)
5247c76feb0dSPaul E. McKenney 				pr_cont_work(false, work, &pcws);
5248c76feb0dSPaul E. McKenney 			pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
52493494fc30STejun Heo 			comma = true;
52503494fc30STejun Heo 		}
52513494fc30STejun Heo 		pr_cont("\n");
52523494fc30STejun Heo 	}
52533494fc30STejun Heo 
52543494fc30STejun Heo 	list_for_each_entry(work, &pool->worklist, entry) {
52553494fc30STejun Heo 		if (get_work_pwq(work) == pwq) {
52563494fc30STejun Heo 			has_pending = true;
52573494fc30STejun Heo 			break;
52583494fc30STejun Heo 		}
52593494fc30STejun Heo 	}
52603494fc30STejun Heo 	if (has_pending) {
52613494fc30STejun Heo 		bool comma = false;
52623494fc30STejun Heo 
52633494fc30STejun Heo 		pr_info("    pending:");
52643494fc30STejun Heo 		list_for_each_entry(work, &pool->worklist, entry) {
52653494fc30STejun Heo 			if (get_work_pwq(work) != pwq)
52663494fc30STejun Heo 				continue;
52673494fc30STejun Heo 
5268c76feb0dSPaul E. McKenney 			pr_cont_work(comma, work, &pcws);
52693494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
52703494fc30STejun Heo 		}
5271c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
52723494fc30STejun Heo 		pr_cont("\n");
52733494fc30STejun Heo 	}
52743494fc30STejun Heo 
5275f97a4a1aSLai Jiangshan 	if (!list_empty(&pwq->inactive_works)) {
52763494fc30STejun Heo 		bool comma = false;
52773494fc30STejun Heo 
5278f97a4a1aSLai Jiangshan 		pr_info("    inactive:");
5279f97a4a1aSLai Jiangshan 		list_for_each_entry(work, &pwq->inactive_works, entry) {
5280c76feb0dSPaul E. McKenney 			pr_cont_work(comma, work, &pcws);
52813494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
52823494fc30STejun Heo 		}
5283c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
52843494fc30STejun Heo 		pr_cont("\n");
52853494fc30STejun Heo 	}
52863494fc30STejun Heo }
52873494fc30STejun Heo 
52883494fc30STejun Heo /**
528955df0933SImran Khan  * show_one_workqueue - dump state of specified workqueue
529055df0933SImran Khan  * @wq: workqueue whose state will be printed
52913494fc30STejun Heo  */
529255df0933SImran Khan void show_one_workqueue(struct workqueue_struct *wq)
52933494fc30STejun Heo {
52943494fc30STejun Heo 	struct pool_workqueue *pwq;
52953494fc30STejun Heo 	bool idle = true;
529655df0933SImran Khan 	unsigned long flags;
52973494fc30STejun Heo 
52983494fc30STejun Heo 	for_each_pwq(pwq, wq) {
5299afa87ce8STejun Heo 		if (!pwq_is_empty(pwq)) {
53003494fc30STejun Heo 			idle = false;
53013494fc30STejun Heo 			break;
53023494fc30STejun Heo 		}
53033494fc30STejun Heo 	}
530455df0933SImran Khan 	if (idle) /* Nothing to print for idle workqueue */
530555df0933SImran Khan 		return;
53063494fc30STejun Heo 
53073494fc30STejun Heo 	pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
53083494fc30STejun Heo 
53093494fc30STejun Heo 	for_each_pwq(pwq, wq) {
5310a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irqsave(&pwq->pool->lock, flags);
5311afa87ce8STejun Heo 		if (!pwq_is_empty(pwq)) {
531257116ce1SJohan Hovold 			/*
531357116ce1SJohan Hovold 			 * Defer printing to avoid deadlocks in console
531457116ce1SJohan Hovold 			 * drivers that queue work while holding locks
531557116ce1SJohan Hovold 			 * also taken in their write paths.
531657116ce1SJohan Hovold 			 */
531757116ce1SJohan Hovold 			printk_deferred_enter();
53183494fc30STejun Heo 			show_pwq(pwq);
531957116ce1SJohan Hovold 			printk_deferred_exit();
532057116ce1SJohan Hovold 		}
5321a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
532262635ea8SSergey Senozhatsky 		/*
532362635ea8SSergey Senozhatsky 		 * We could be printing a lot from atomic context, e.g.
532455df0933SImran Khan 		 * sysrq-t -> show_all_workqueues(). Avoid triggering
532562635ea8SSergey Senozhatsky 		 * hard lockup.
532662635ea8SSergey Senozhatsky 		 */
532762635ea8SSergey Senozhatsky 		touch_nmi_watchdog();
53283494fc30STejun Heo 	}
532955df0933SImran Khan 
53303494fc30STejun Heo }
53313494fc30STejun Heo 
533255df0933SImran Khan /**
533355df0933SImran Khan  * show_one_worker_pool - dump state of specified worker pool
533455df0933SImran Khan  * @pool: worker pool whose state will be printed
533555df0933SImran Khan  */
533655df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool)
533755df0933SImran Khan {
53383494fc30STejun Heo 	struct worker *worker;
53393494fc30STejun Heo 	bool first = true;
534055df0933SImran Khan 	unsigned long flags;
5341335a42ebSPetr Mladek 	unsigned long hung = 0;
53423494fc30STejun Heo 
5343a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irqsave(&pool->lock, flags);
53443494fc30STejun Heo 	if (pool->nr_workers == pool->nr_idle)
53453494fc30STejun Heo 		goto next_pool;
5346335a42ebSPetr Mladek 
5347335a42ebSPetr Mladek 	/* How long the first pending work is waiting for a worker. */
5348335a42ebSPetr Mladek 	if (!list_empty(&pool->worklist))
5349335a42ebSPetr Mladek 		hung = jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000;
5350335a42ebSPetr Mladek 
535157116ce1SJohan Hovold 	/*
535257116ce1SJohan Hovold 	 * Defer printing to avoid deadlocks in console drivers that
535357116ce1SJohan Hovold 	 * queue work while holding locks also taken in their write
535457116ce1SJohan Hovold 	 * paths.
535557116ce1SJohan Hovold 	 */
535657116ce1SJohan Hovold 	printk_deferred_enter();
53573494fc30STejun Heo 	pr_info("pool %d:", pool->id);
53583494fc30STejun Heo 	pr_cont_pool_info(pool);
5359335a42ebSPetr Mladek 	pr_cont(" hung=%lus workers=%d", hung, pool->nr_workers);
53603494fc30STejun Heo 	if (pool->manager)
53613494fc30STejun Heo 		pr_cont(" manager: %d",
53623494fc30STejun Heo 			task_pid_nr(pool->manager->task));
53633494fc30STejun Heo 	list_for_each_entry(worker, &pool->idle_list, entry) {
53643494fc30STejun Heo 		pr_cont(" %s%d", first ? "idle: " : "",
53653494fc30STejun Heo 			task_pid_nr(worker->task));
53663494fc30STejun Heo 		first = false;
53673494fc30STejun Heo 	}
53683494fc30STejun Heo 	pr_cont("\n");
536957116ce1SJohan Hovold 	printk_deferred_exit();
53703494fc30STejun Heo next_pool:
5371a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&pool->lock, flags);
537262635ea8SSergey Senozhatsky 	/*
537362635ea8SSergey Senozhatsky 	 * We could be printing a lot from atomic context, e.g.
537455df0933SImran Khan 	 * sysrq-t -> show_all_workqueues(). Avoid triggering
537562635ea8SSergey Senozhatsky 	 * hard lockup.
537662635ea8SSergey Senozhatsky 	 */
537762635ea8SSergey Senozhatsky 	touch_nmi_watchdog();
537855df0933SImran Khan 
53793494fc30STejun Heo }
53803494fc30STejun Heo 
538155df0933SImran Khan /**
538255df0933SImran Khan  * show_all_workqueues - dump workqueue state
538355df0933SImran Khan  *
5384704bc669SJungseung Lee  * Called from a sysrq handler and prints out all busy workqueues and pools.
538555df0933SImran Khan  */
538655df0933SImran Khan void show_all_workqueues(void)
538755df0933SImran Khan {
538855df0933SImran Khan 	struct workqueue_struct *wq;
538955df0933SImran Khan 	struct worker_pool *pool;
539055df0933SImran Khan 	int pi;
539155df0933SImran Khan 
539255df0933SImran Khan 	rcu_read_lock();
539355df0933SImran Khan 
539455df0933SImran Khan 	pr_info("Showing busy workqueues and worker pools:\n");
539555df0933SImran Khan 
539655df0933SImran Khan 	list_for_each_entry_rcu(wq, &workqueues, list)
539755df0933SImran Khan 		show_one_workqueue(wq);
539855df0933SImran Khan 
539955df0933SImran Khan 	for_each_pool(pool, pi)
540055df0933SImran Khan 		show_one_worker_pool(pool);
540155df0933SImran Khan 
540224acfb71SThomas Gleixner 	rcu_read_unlock();
54033494fc30STejun Heo }
54043494fc30STejun Heo 
5405704bc669SJungseung Lee /**
5406704bc669SJungseung Lee  * show_freezable_workqueues - dump freezable workqueue state
5407704bc669SJungseung Lee  *
5408704bc669SJungseung Lee  * Called from try_to_freeze_tasks() and prints out all freezable workqueues
5409704bc669SJungseung Lee  * still busy.
5410704bc669SJungseung Lee  */
5411704bc669SJungseung Lee void show_freezable_workqueues(void)
5412704bc669SJungseung Lee {
5413704bc669SJungseung Lee 	struct workqueue_struct *wq;
5414704bc669SJungseung Lee 
5415704bc669SJungseung Lee 	rcu_read_lock();
5416704bc669SJungseung Lee 
5417704bc669SJungseung Lee 	pr_info("Showing freezable workqueues that are still busy:\n");
5418704bc669SJungseung Lee 
5419704bc669SJungseung Lee 	list_for_each_entry_rcu(wq, &workqueues, list) {
5420704bc669SJungseung Lee 		if (!(wq->flags & WQ_FREEZABLE))
5421704bc669SJungseung Lee 			continue;
5422704bc669SJungseung Lee 		show_one_workqueue(wq);
5423704bc669SJungseung Lee 	}
5424704bc669SJungseung Lee 
5425704bc669SJungseung Lee 	rcu_read_unlock();
5426704bc669SJungseung Lee }
5427704bc669SJungseung Lee 
54286b59808bSTejun Heo /* used to show worker information through /proc/PID/{comm,stat,status} */
54296b59808bSTejun Heo void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
54306b59808bSTejun Heo {
54316b59808bSTejun Heo 	int off;
54326b59808bSTejun Heo 
54336b59808bSTejun Heo 	/* always show the actual comm */
54346b59808bSTejun Heo 	off = strscpy(buf, task->comm, size);
54356b59808bSTejun Heo 	if (off < 0)
54366b59808bSTejun Heo 		return;
54376b59808bSTejun Heo 
5438197f6accSTejun Heo 	/* stabilize PF_WQ_WORKER and worker pool association */
54396b59808bSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
54406b59808bSTejun Heo 
5441197f6accSTejun Heo 	if (task->flags & PF_WQ_WORKER) {
5442197f6accSTejun Heo 		struct worker *worker = kthread_data(task);
5443197f6accSTejun Heo 		struct worker_pool *pool = worker->pool;
54446b59808bSTejun Heo 
54456b59808bSTejun Heo 		if (pool) {
5446a9b8a985SSebastian Andrzej Siewior 			raw_spin_lock_irq(&pool->lock);
54476b59808bSTejun Heo 			/*
5448197f6accSTejun Heo 			 * ->desc tracks information (wq name or
5449197f6accSTejun Heo 			 * set_worker_desc()) for the latest execution.  If
5450197f6accSTejun Heo 			 * current, prepend '+', otherwise '-'.
54516b59808bSTejun Heo 			 */
54526b59808bSTejun Heo 			if (worker->desc[0] != '\0') {
54536b59808bSTejun Heo 				if (worker->current_work)
54546b59808bSTejun Heo 					scnprintf(buf + off, size - off, "+%s",
54556b59808bSTejun Heo 						  worker->desc);
54566b59808bSTejun Heo 				else
54576b59808bSTejun Heo 					scnprintf(buf + off, size - off, "-%s",
54586b59808bSTejun Heo 						  worker->desc);
54596b59808bSTejun Heo 			}
5460a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&pool->lock);
54616b59808bSTejun Heo 		}
5462197f6accSTejun Heo 	}
54636b59808bSTejun Heo 
54646b59808bSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
54656b59808bSTejun Heo }
54666b59808bSTejun Heo 
546766448bc2SMathieu Malaterre #ifdef CONFIG_SMP
546866448bc2SMathieu Malaterre 
5469db7bccf4STejun Heo /*
5470db7bccf4STejun Heo  * CPU hotplug.
5471db7bccf4STejun Heo  *
5472e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
5473112202d9STejun Heo  * are a lot of assumptions on strong associations among work, pwq and
5474706026c2STejun Heo  * pool which make migrating pending and scheduled works very
5475e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
547694cf58bbSTejun Heo  * worker pools serve mix of short, long and very long running works making
5477e22bee78STejun Heo  * blocked draining impractical.
5478e22bee78STejun Heo  *
547924647570STejun Heo  * This is solved by allowing the pools to be disassociated from the CPU
5480628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
5481628c78e7STejun Heo  * cpu comes back online.
5482db7bccf4STejun Heo  */
5483db7bccf4STejun Heo 
5484e8b3f8dbSLai Jiangshan static void unbind_workers(int cpu)
5485db7bccf4STejun Heo {
54864ce62e9eSTejun Heo 	struct worker_pool *pool;
5487db7bccf4STejun Heo 	struct worker *worker;
5488db7bccf4STejun Heo 
5489f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
54901258fae7STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
5491a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
5492e22bee78STejun Heo 
5493f2d5a0eeSTejun Heo 		/*
549492f9c5c4SLai Jiangshan 		 * We've blocked all attach/detach operations. Make all workers
549594cf58bbSTejun Heo 		 * unbound and set DISASSOCIATED.  Before this, all workers
549611b45b0bSLai Jiangshan 		 * must be on the cpu.  After this, they may become diasporas.
5497b4ac9384SLai Jiangshan 		 * And the preemption disabled section in their sched callbacks
5498b4ac9384SLai Jiangshan 		 * are guaranteed to see WORKER_UNBOUND since the code here
5499b4ac9384SLai Jiangshan 		 * is on the same cpu.
5500f2d5a0eeSTejun Heo 		 */
5501da028469SLai Jiangshan 		for_each_pool_worker(worker, pool)
5502403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
5503db7bccf4STejun Heo 
550424647570STejun Heo 		pool->flags |= POOL_DISASSOCIATED;
5505f2d5a0eeSTejun Heo 
5506e22bee78STejun Heo 		/*
5507989442d7SLai Jiangshan 		 * The handling of nr_running in sched callbacks are disabled
5508989442d7SLai Jiangshan 		 * now.  Zap nr_running.  After this, nr_running stays zero and
5509989442d7SLai Jiangshan 		 * need_more_worker() and keep_working() are always true as
5510989442d7SLai Jiangshan 		 * long as the worklist is not empty.  This pool now behaves as
5511989442d7SLai Jiangshan 		 * an unbound (in terms of concurrency management) pool which
5512eb283428SLai Jiangshan 		 * are served by workers tied to the pool.
5513e22bee78STejun Heo 		 */
5514bc35f7efSLai Jiangshan 		pool->nr_running = 0;
5515eb283428SLai Jiangshan 
5516eb283428SLai Jiangshan 		/*
5517eb283428SLai Jiangshan 		 * With concurrency management just turned off, a busy
5518eb283428SLai Jiangshan 		 * worker blocking could lead to lengthy stalls.  Kick off
5519eb283428SLai Jiangshan 		 * unbound chain execution of currently pending work items.
5520eb283428SLai Jiangshan 		 */
55210219a352STejun Heo 		kick_pool(pool);
5522989442d7SLai Jiangshan 
5523a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
5524989442d7SLai Jiangshan 
5525793777bcSValentin Schneider 		for_each_pool_worker(worker, pool)
5526793777bcSValentin Schneider 			unbind_worker(worker);
5527989442d7SLai Jiangshan 
5528989442d7SLai Jiangshan 		mutex_unlock(&wq_pool_attach_mutex);
5529eb283428SLai Jiangshan 	}
5530db7bccf4STejun Heo }
5531db7bccf4STejun Heo 
5532bd7c089eSTejun Heo /**
5533bd7c089eSTejun Heo  * rebind_workers - rebind all workers of a pool to the associated CPU
5534bd7c089eSTejun Heo  * @pool: pool of interest
5535bd7c089eSTejun Heo  *
5536a9ab775bSTejun Heo  * @pool->cpu is coming online.  Rebind all workers to the CPU.
5537bd7c089eSTejun Heo  */
5538bd7c089eSTejun Heo static void rebind_workers(struct worker_pool *pool)
5539bd7c089eSTejun Heo {
5540a9ab775bSTejun Heo 	struct worker *worker;
5541bd7c089eSTejun Heo 
55421258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
5543bd7c089eSTejun Heo 
5544bd7c089eSTejun Heo 	/*
5545a9ab775bSTejun Heo 	 * Restore CPU affinity of all workers.  As all idle workers should
5546a9ab775bSTejun Heo 	 * be on the run-queue of the associated CPU before any local
5547402dd89dSShailendra Verma 	 * wake-ups for concurrency management happen, restore CPU affinity
5548a9ab775bSTejun Heo 	 * of all workers first and then clear UNBOUND.  As we're called
5549a9ab775bSTejun Heo 	 * from CPU_ONLINE, the following shouldn't fail.
5550bd7c089eSTejun Heo 	 */
5551c63a2e52SValentin Schneider 	for_each_pool_worker(worker, pool) {
5552c63a2e52SValentin Schneider 		kthread_set_per_cpu(worker->task, pool->cpu);
5553c63a2e52SValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
55549546b29eSTejun Heo 						  pool_allowed_cpus(pool)) < 0);
5555c63a2e52SValentin Schneider 	}
5556a9ab775bSTejun Heo 
5557a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
5558f7c17d26SWanpeng Li 
55593de5e884SLai Jiangshan 	pool->flags &= ~POOL_DISASSOCIATED;
5560a9ab775bSTejun Heo 
5561da028469SLai Jiangshan 	for_each_pool_worker(worker, pool) {
5562a9ab775bSTejun Heo 		unsigned int worker_flags = worker->flags;
5563a9ab775bSTejun Heo 
5564a9ab775bSTejun Heo 		/*
5565a9ab775bSTejun Heo 		 * We want to clear UNBOUND but can't directly call
5566a9ab775bSTejun Heo 		 * worker_clr_flags() or adjust nr_running.  Atomically
5567a9ab775bSTejun Heo 		 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
5568a9ab775bSTejun Heo 		 * @worker will clear REBOUND using worker_clr_flags() when
5569a9ab775bSTejun Heo 		 * it initiates the next execution cycle thus restoring
5570a9ab775bSTejun Heo 		 * concurrency management.  Note that when or whether
5571a9ab775bSTejun Heo 		 * @worker clears REBOUND doesn't affect correctness.
5572a9ab775bSTejun Heo 		 *
5573c95491edSMark Rutland 		 * WRITE_ONCE() is necessary because @worker->flags may be
5574a9ab775bSTejun Heo 		 * tested without holding any lock in
55756d25be57SThomas Gleixner 		 * wq_worker_running().  Without it, NOT_RUNNING test may
5576a9ab775bSTejun Heo 		 * fail incorrectly leading to premature concurrency
5577a9ab775bSTejun Heo 		 * management operations.
5578bd7c089eSTejun Heo 		 */
5579a9ab775bSTejun Heo 		WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
5580a9ab775bSTejun Heo 		worker_flags |= WORKER_REBOUND;
5581a9ab775bSTejun Heo 		worker_flags &= ~WORKER_UNBOUND;
5582c95491edSMark Rutland 		WRITE_ONCE(worker->flags, worker_flags);
5583bd7c089eSTejun Heo 	}
5584a9ab775bSTejun Heo 
5585a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
5586bd7c089eSTejun Heo }
5587bd7c089eSTejun Heo 
55887dbc725eSTejun Heo /**
55897dbc725eSTejun Heo  * restore_unbound_workers_cpumask - restore cpumask of unbound workers
55907dbc725eSTejun Heo  * @pool: unbound pool of interest
55917dbc725eSTejun Heo  * @cpu: the CPU which is coming up
55927dbc725eSTejun Heo  *
55937dbc725eSTejun Heo  * An unbound pool may end up with a cpumask which doesn't have any online
55947dbc725eSTejun Heo  * CPUs.  When a worker of such pool get scheduled, the scheduler resets
55957dbc725eSTejun Heo  * its cpus_allowed.  If @cpu is in @pool's cpumask which didn't have any
55967dbc725eSTejun Heo  * online CPU before, cpus_allowed of all its workers should be restored.
55977dbc725eSTejun Heo  */
55987dbc725eSTejun Heo static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
55997dbc725eSTejun Heo {
56007dbc725eSTejun Heo 	static cpumask_t cpumask;
56017dbc725eSTejun Heo 	struct worker *worker;
56027dbc725eSTejun Heo 
56031258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
56047dbc725eSTejun Heo 
56057dbc725eSTejun Heo 	/* is @cpu allowed for @pool? */
56067dbc725eSTejun Heo 	if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
56077dbc725eSTejun Heo 		return;
56087dbc725eSTejun Heo 
56097dbc725eSTejun Heo 	cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
56107dbc725eSTejun Heo 
56117dbc725eSTejun Heo 	/* as we're called from CPU_ONLINE, the following shouldn't fail */
5612da028469SLai Jiangshan 	for_each_pool_worker(worker, pool)
5613d945b5e9SPeter Zijlstra 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
56147dbc725eSTejun Heo }
56157dbc725eSTejun Heo 
56167ee681b2SThomas Gleixner int workqueue_prepare_cpu(unsigned int cpu)
56171da177e4SLinus Torvalds {
56184ce62e9eSTejun Heo 	struct worker_pool *pool;
56191da177e4SLinus Torvalds 
5620f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
56213ce63377STejun Heo 		if (pool->nr_workers)
56223ce63377STejun Heo 			continue;
5623051e1850SLai Jiangshan 		if (!create_worker(pool))
56247ee681b2SThomas Gleixner 			return -ENOMEM;
56253af24433SOleg Nesterov 	}
56267ee681b2SThomas Gleixner 	return 0;
56277ee681b2SThomas Gleixner }
56281da177e4SLinus Torvalds 
56297ee681b2SThomas Gleixner int workqueue_online_cpu(unsigned int cpu)
56307ee681b2SThomas Gleixner {
56317ee681b2SThomas Gleixner 	struct worker_pool *pool;
56327ee681b2SThomas Gleixner 	struct workqueue_struct *wq;
56337ee681b2SThomas Gleixner 	int pi;
56347ee681b2SThomas Gleixner 
563568e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
56367dbc725eSTejun Heo 
56377dbc725eSTejun Heo 	for_each_pool(pool, pi) {
56381258fae7STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
563994cf58bbSTejun Heo 
5640f05b558dSLai Jiangshan 		if (pool->cpu == cpu)
564194cf58bbSTejun Heo 			rebind_workers(pool);
5642f05b558dSLai Jiangshan 		else if (pool->cpu < 0)
56437dbc725eSTejun Heo 			restore_unbound_workers_cpumask(pool, cpu);
564494cf58bbSTejun Heo 
56451258fae7STejun Heo 		mutex_unlock(&wq_pool_attach_mutex);
564694cf58bbSTejun Heo 	}
56477dbc725eSTejun Heo 
5648fef59c9cSTejun Heo 	/* update pod affinity of unbound workqueues */
56494cbfd3deSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
565084193c07STejun Heo 		struct workqueue_attrs *attrs = wq->unbound_attrs;
565184193c07STejun Heo 
565284193c07STejun Heo 		if (attrs) {
565384193c07STejun Heo 			const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
56544cbfd3deSTejun Heo 			int tcpu;
56554cbfd3deSTejun Heo 
565684193c07STejun Heo 			for_each_cpu(tcpu, pt->pod_cpus[pt->cpu_pod[cpu]])
5657fef59c9cSTejun Heo 				wq_update_pod(wq, tcpu, cpu, true);
56584cbfd3deSTejun Heo 		}
56594cbfd3deSTejun Heo 	}
56604c16bd32STejun Heo 
566168e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
56627ee681b2SThomas Gleixner 	return 0;
566365758202STejun Heo }
566465758202STejun Heo 
56657ee681b2SThomas Gleixner int workqueue_offline_cpu(unsigned int cpu)
566665758202STejun Heo {
56674c16bd32STejun Heo 	struct workqueue_struct *wq;
56688db25e78STejun Heo 
56694c16bd32STejun Heo 	/* unbinding per-cpu workers should happen on the local CPU */
5670e8b3f8dbSLai Jiangshan 	if (WARN_ON(cpu != smp_processor_id()))
5671e8b3f8dbSLai Jiangshan 		return -1;
5672e8b3f8dbSLai Jiangshan 
5673e8b3f8dbSLai Jiangshan 	unbind_workers(cpu);
56744c16bd32STejun Heo 
5675fef59c9cSTejun Heo 	/* update pod affinity of unbound workqueues */
56764c16bd32STejun Heo 	mutex_lock(&wq_pool_mutex);
56774cbfd3deSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
567884193c07STejun Heo 		struct workqueue_attrs *attrs = wq->unbound_attrs;
567984193c07STejun Heo 
568084193c07STejun Heo 		if (attrs) {
568184193c07STejun Heo 			const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
56824cbfd3deSTejun Heo 			int tcpu;
56834cbfd3deSTejun Heo 
568484193c07STejun Heo 			for_each_cpu(tcpu, pt->pod_cpus[pt->cpu_pod[cpu]])
5685fef59c9cSTejun Heo 				wq_update_pod(wq, tcpu, cpu, false);
56864cbfd3deSTejun Heo 		}
56874cbfd3deSTejun Heo 	}
56884c16bd32STejun Heo 	mutex_unlock(&wq_pool_mutex);
56894c16bd32STejun Heo 
56907ee681b2SThomas Gleixner 	return 0;
569165758202STejun Heo }
569265758202STejun Heo 
56932d3854a3SRusty Russell struct work_for_cpu {
5694ed48ece2STejun Heo 	struct work_struct work;
56952d3854a3SRusty Russell 	long (*fn)(void *);
56962d3854a3SRusty Russell 	void *arg;
56972d3854a3SRusty Russell 	long ret;
56982d3854a3SRusty Russell };
56992d3854a3SRusty Russell 
5700ed48ece2STejun Heo static void work_for_cpu_fn(struct work_struct *work)
57012d3854a3SRusty Russell {
5702ed48ece2STejun Heo 	struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
5703ed48ece2STejun Heo 
57042d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
57052d3854a3SRusty Russell }
57062d3854a3SRusty Russell 
57072d3854a3SRusty Russell /**
5708265f3ed0SFrederic Weisbecker  * work_on_cpu_key - run a function in thread context on a particular cpu
57092d3854a3SRusty Russell  * @cpu: the cpu to run on
57102d3854a3SRusty Russell  * @fn: the function to run
57112d3854a3SRusty Russell  * @arg: the function arg
5712265f3ed0SFrederic Weisbecker  * @key: The lock class key for lock debugging purposes
57132d3854a3SRusty Russell  *
571431ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
57156b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
5716d185af30SYacine Belkadi  *
5717d185af30SYacine Belkadi  * Return: The value @fn returns.
57182d3854a3SRusty Russell  */
5719265f3ed0SFrederic Weisbecker long work_on_cpu_key(int cpu, long (*fn)(void *),
5720265f3ed0SFrederic Weisbecker 		     void *arg, struct lock_class_key *key)
57212d3854a3SRusty Russell {
5722ed48ece2STejun Heo 	struct work_for_cpu wfc = { .fn = fn, .arg = arg };
57232d3854a3SRusty Russell 
5724265f3ed0SFrederic Weisbecker 	INIT_WORK_ONSTACK_KEY(&wfc.work, work_for_cpu_fn, key);
5725ed48ece2STejun Heo 	schedule_work_on(cpu, &wfc.work);
572612997d1aSBjorn Helgaas 	flush_work(&wfc.work);
5727440a1136SChuansheng Liu 	destroy_work_on_stack(&wfc.work);
57282d3854a3SRusty Russell 	return wfc.ret;
57292d3854a3SRusty Russell }
5730265f3ed0SFrederic Weisbecker EXPORT_SYMBOL_GPL(work_on_cpu_key);
57310e8d6a93SThomas Gleixner 
57320e8d6a93SThomas Gleixner /**
5733265f3ed0SFrederic Weisbecker  * work_on_cpu_safe_key - run a function in thread context on a particular cpu
57340e8d6a93SThomas Gleixner  * @cpu: the cpu to run on
57350e8d6a93SThomas Gleixner  * @fn:  the function to run
57360e8d6a93SThomas Gleixner  * @arg: the function argument
5737265f3ed0SFrederic Weisbecker  * @key: The lock class key for lock debugging purposes
57380e8d6a93SThomas Gleixner  *
57390e8d6a93SThomas Gleixner  * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
57400e8d6a93SThomas Gleixner  * any locks which would prevent @fn from completing.
57410e8d6a93SThomas Gleixner  *
57420e8d6a93SThomas Gleixner  * Return: The value @fn returns.
57430e8d6a93SThomas Gleixner  */
5744265f3ed0SFrederic Weisbecker long work_on_cpu_safe_key(int cpu, long (*fn)(void *),
5745265f3ed0SFrederic Weisbecker 			  void *arg, struct lock_class_key *key)
57460e8d6a93SThomas Gleixner {
57470e8d6a93SThomas Gleixner 	long ret = -ENODEV;
57480e8d6a93SThomas Gleixner 
5749ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
57500e8d6a93SThomas Gleixner 	if (cpu_online(cpu))
5751265f3ed0SFrederic Weisbecker 		ret = work_on_cpu_key(cpu, fn, arg, key);
5752ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
57530e8d6a93SThomas Gleixner 	return ret;
57540e8d6a93SThomas Gleixner }
5755265f3ed0SFrederic Weisbecker EXPORT_SYMBOL_GPL(work_on_cpu_safe_key);
57562d3854a3SRusty Russell #endif /* CONFIG_SMP */
57572d3854a3SRusty Russell 
5758a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
5759e7577c50SRusty Russell 
5760a0a1a5fdSTejun Heo /**
5761a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
5762a0a1a5fdSTejun Heo  *
576358a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
5764f97a4a1aSLai Jiangshan  * workqueues will queue new works to their inactive_works list instead of
5765706026c2STejun Heo  * pool->worklist.
5766a0a1a5fdSTejun Heo  *
5767a0a1a5fdSTejun Heo  * CONTEXT:
5768a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5769a0a1a5fdSTejun Heo  */
5770a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
5771a0a1a5fdSTejun Heo {
577224b8a847STejun Heo 	struct workqueue_struct *wq;
5773a0a1a5fdSTejun Heo 
577468e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5775a0a1a5fdSTejun Heo 
57766183c009STejun Heo 	WARN_ON_ONCE(workqueue_freezing);
5777a0a1a5fdSTejun Heo 	workqueue_freezing = true;
5778a0a1a5fdSTejun Heo 
577924b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5780a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
5781a045a272STejun Heo 		wq_adjust_max_active(wq);
5782a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
5783a1056305STejun Heo 	}
57845bcab335STejun Heo 
578568e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5786a0a1a5fdSTejun Heo }
5787a0a1a5fdSTejun Heo 
5788a0a1a5fdSTejun Heo /**
578958a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
5790a0a1a5fdSTejun Heo  *
5791a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
5792a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
5793a0a1a5fdSTejun Heo  *
5794a0a1a5fdSTejun Heo  * CONTEXT:
579568e13a67SLai Jiangshan  * Grabs and releases wq_pool_mutex.
5796a0a1a5fdSTejun Heo  *
5797d185af30SYacine Belkadi  * Return:
579858a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
579958a69cb4STejun Heo  * is complete.
5800a0a1a5fdSTejun Heo  */
5801a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
5802a0a1a5fdSTejun Heo {
5803a0a1a5fdSTejun Heo 	bool busy = false;
580424b8a847STejun Heo 	struct workqueue_struct *wq;
580524b8a847STejun Heo 	struct pool_workqueue *pwq;
5806a0a1a5fdSTejun Heo 
580768e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5808a0a1a5fdSTejun Heo 
58096183c009STejun Heo 	WARN_ON_ONCE(!workqueue_freezing);
5810a0a1a5fdSTejun Heo 
581124b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
581224b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
581324b8a847STejun Heo 			continue;
5814a0a1a5fdSTejun Heo 		/*
5815a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
5816a0a1a5fdSTejun Heo 		 * to peek without lock.
5817a0a1a5fdSTejun Heo 		 */
581824acfb71SThomas Gleixner 		rcu_read_lock();
581924b8a847STejun Heo 		for_each_pwq(pwq, wq) {
58206183c009STejun Heo 			WARN_ON_ONCE(pwq->nr_active < 0);
5821112202d9STejun Heo 			if (pwq->nr_active) {
5822a0a1a5fdSTejun Heo 				busy = true;
582324acfb71SThomas Gleixner 				rcu_read_unlock();
5824a0a1a5fdSTejun Heo 				goto out_unlock;
5825a0a1a5fdSTejun Heo 			}
5826a0a1a5fdSTejun Heo 		}
582724acfb71SThomas Gleixner 		rcu_read_unlock();
5828a0a1a5fdSTejun Heo 	}
5829a0a1a5fdSTejun Heo out_unlock:
583068e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5831a0a1a5fdSTejun Heo 	return busy;
5832a0a1a5fdSTejun Heo }
5833a0a1a5fdSTejun Heo 
5834a0a1a5fdSTejun Heo /**
5835a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
5836a0a1a5fdSTejun Heo  *
5837a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
5838706026c2STejun Heo  * frozen works are transferred to their respective pool worklists.
5839a0a1a5fdSTejun Heo  *
5840a0a1a5fdSTejun Heo  * CONTEXT:
5841a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5842a0a1a5fdSTejun Heo  */
5843a0a1a5fdSTejun Heo void thaw_workqueues(void)
5844a0a1a5fdSTejun Heo {
584524b8a847STejun Heo 	struct workqueue_struct *wq;
5846a0a1a5fdSTejun Heo 
584768e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5848a0a1a5fdSTejun Heo 
5849a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
5850a0a1a5fdSTejun Heo 		goto out_unlock;
5851a0a1a5fdSTejun Heo 
585274b414eaSLai Jiangshan 	workqueue_freezing = false;
585324b8a847STejun Heo 
585424b8a847STejun Heo 	/* restore max_active and repopulate worklist */
585524b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5856a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
5857a045a272STejun Heo 		wq_adjust_max_active(wq);
5858a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
585924b8a847STejun Heo 	}
586024b8a847STejun Heo 
5861a0a1a5fdSTejun Heo out_unlock:
586268e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5863a0a1a5fdSTejun Heo }
5864a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
5865a0a1a5fdSTejun Heo 
586699c621efSLai Jiangshan static int workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask)
5867042f7df1SLai Jiangshan {
5868042f7df1SLai Jiangshan 	LIST_HEAD(ctxs);
5869042f7df1SLai Jiangshan 	int ret = 0;
5870042f7df1SLai Jiangshan 	struct workqueue_struct *wq;
5871042f7df1SLai Jiangshan 	struct apply_wqattrs_ctx *ctx, *n;
5872042f7df1SLai Jiangshan 
5873042f7df1SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5874042f7df1SLai Jiangshan 
5875042f7df1SLai Jiangshan 	list_for_each_entry(wq, &workqueues, list) {
5876042f7df1SLai Jiangshan 		if (!(wq->flags & WQ_UNBOUND))
5877042f7df1SLai Jiangshan 			continue;
5878ca10d851SWaiman Long 
5879042f7df1SLai Jiangshan 		/* creating multiple pwqs breaks ordering guarantee */
5880ca10d851SWaiman Long 		if (!list_empty(&wq->pwqs)) {
5881ca10d851SWaiman Long 			if (wq->flags & __WQ_ORDERED_EXPLICIT)
5882042f7df1SLai Jiangshan 				continue;
5883ca10d851SWaiman Long 			wq->flags &= ~__WQ_ORDERED;
5884ca10d851SWaiman Long 		}
5885042f7df1SLai Jiangshan 
588699c621efSLai Jiangshan 		ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs, unbound_cpumask);
588784193c07STejun Heo 		if (IS_ERR(ctx)) {
588884193c07STejun Heo 			ret = PTR_ERR(ctx);
5889042f7df1SLai Jiangshan 			break;
5890042f7df1SLai Jiangshan 		}
5891042f7df1SLai Jiangshan 
5892042f7df1SLai Jiangshan 		list_add_tail(&ctx->list, &ctxs);
5893042f7df1SLai Jiangshan 	}
5894042f7df1SLai Jiangshan 
5895042f7df1SLai Jiangshan 	list_for_each_entry_safe(ctx, n, &ctxs, list) {
5896042f7df1SLai Jiangshan 		if (!ret)
5897042f7df1SLai Jiangshan 			apply_wqattrs_commit(ctx);
5898042f7df1SLai Jiangshan 		apply_wqattrs_cleanup(ctx);
5899042f7df1SLai Jiangshan 	}
5900042f7df1SLai Jiangshan 
590199c621efSLai Jiangshan 	if (!ret) {
590299c621efSLai Jiangshan 		mutex_lock(&wq_pool_attach_mutex);
590399c621efSLai Jiangshan 		cpumask_copy(wq_unbound_cpumask, unbound_cpumask);
590499c621efSLai Jiangshan 		mutex_unlock(&wq_pool_attach_mutex);
590599c621efSLai Jiangshan 	}
5906042f7df1SLai Jiangshan 	return ret;
5907042f7df1SLai Jiangshan }
5908042f7df1SLai Jiangshan 
5909042f7df1SLai Jiangshan /**
5910fe28f631SWaiman Long  * workqueue_unbound_exclude_cpumask - Exclude given CPUs from unbound cpumask
5911fe28f631SWaiman Long  * @exclude_cpumask: the cpumask to be excluded from wq_unbound_cpumask
5912fe28f631SWaiman Long  *
5913fe28f631SWaiman Long  * This function can be called from cpuset code to provide a set of isolated
5914fe28f631SWaiman Long  * CPUs that should be excluded from wq_unbound_cpumask. The caller must hold
5915fe28f631SWaiman Long  * either cpus_read_lock or cpus_write_lock.
5916fe28f631SWaiman Long  */
5917fe28f631SWaiman Long int workqueue_unbound_exclude_cpumask(cpumask_var_t exclude_cpumask)
5918fe28f631SWaiman Long {
5919fe28f631SWaiman Long 	cpumask_var_t cpumask;
5920fe28f631SWaiman Long 	int ret = 0;
5921fe28f631SWaiman Long 
5922fe28f631SWaiman Long 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
5923fe28f631SWaiman Long 		return -ENOMEM;
5924fe28f631SWaiman Long 
5925fe28f631SWaiman Long 	lockdep_assert_cpus_held();
5926fe28f631SWaiman Long 	mutex_lock(&wq_pool_mutex);
5927fe28f631SWaiman Long 
5928fe28f631SWaiman Long 	/* Save the current isolated cpumask & export it via sysfs */
5929fe28f631SWaiman Long 	cpumask_copy(wq_isolated_cpumask, exclude_cpumask);
5930fe28f631SWaiman Long 
5931fe28f631SWaiman Long 	/*
5932fe28f631SWaiman Long 	 * If the operation fails, it will fall back to
5933fe28f631SWaiman Long 	 * wq_requested_unbound_cpumask which is initially set to
5934fe28f631SWaiman Long 	 * (HK_TYPE_WQ ∩ HK_TYPE_DOMAIN) house keeping mask and rewritten
5935fe28f631SWaiman Long 	 * by any subsequent write to workqueue/cpumask sysfs file.
5936fe28f631SWaiman Long 	 */
5937fe28f631SWaiman Long 	if (!cpumask_andnot(cpumask, wq_requested_unbound_cpumask, exclude_cpumask))
5938fe28f631SWaiman Long 		cpumask_copy(cpumask, wq_requested_unbound_cpumask);
5939fe28f631SWaiman Long 	if (!cpumask_equal(cpumask, wq_unbound_cpumask))
5940fe28f631SWaiman Long 		ret = workqueue_apply_unbound_cpumask(cpumask);
5941fe28f631SWaiman Long 
5942fe28f631SWaiman Long 	mutex_unlock(&wq_pool_mutex);
5943fe28f631SWaiman Long 	free_cpumask_var(cpumask);
5944fe28f631SWaiman Long 	return ret;
5945fe28f631SWaiman Long }
5946fe28f631SWaiman Long 
594763c5484eSTejun Heo static int parse_affn_scope(const char *val)
594863c5484eSTejun Heo {
594963c5484eSTejun Heo 	int i;
595063c5484eSTejun Heo 
595163c5484eSTejun Heo 	for (i = 0; i < ARRAY_SIZE(wq_affn_names); i++) {
595263c5484eSTejun Heo 		if (!strncasecmp(val, wq_affn_names[i], strlen(wq_affn_names[i])))
595363c5484eSTejun Heo 			return i;
595463c5484eSTejun Heo 	}
595563c5484eSTejun Heo 	return -EINVAL;
595663c5484eSTejun Heo }
595763c5484eSTejun Heo 
595863c5484eSTejun Heo static int wq_affn_dfl_set(const char *val, const struct kernel_param *kp)
595963c5484eSTejun Heo {
5960523a301eSTejun Heo 	struct workqueue_struct *wq;
5961523a301eSTejun Heo 	int affn, cpu;
596263c5484eSTejun Heo 
596363c5484eSTejun Heo 	affn = parse_affn_scope(val);
596463c5484eSTejun Heo 	if (affn < 0)
596563c5484eSTejun Heo 		return affn;
5966523a301eSTejun Heo 	if (affn == WQ_AFFN_DFL)
5967523a301eSTejun Heo 		return -EINVAL;
5968523a301eSTejun Heo 
5969523a301eSTejun Heo 	cpus_read_lock();
5970523a301eSTejun Heo 	mutex_lock(&wq_pool_mutex);
597163c5484eSTejun Heo 
597263c5484eSTejun Heo 	wq_affn_dfl = affn;
5973523a301eSTejun Heo 
5974523a301eSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5975523a301eSTejun Heo 		for_each_online_cpu(cpu) {
5976523a301eSTejun Heo 			wq_update_pod(wq, cpu, cpu, true);
5977523a301eSTejun Heo 		}
5978523a301eSTejun Heo 	}
5979523a301eSTejun Heo 
5980523a301eSTejun Heo 	mutex_unlock(&wq_pool_mutex);
5981523a301eSTejun Heo 	cpus_read_unlock();
5982523a301eSTejun Heo 
598363c5484eSTejun Heo 	return 0;
598463c5484eSTejun Heo }
598563c5484eSTejun Heo 
598663c5484eSTejun Heo static int wq_affn_dfl_get(char *buffer, const struct kernel_param *kp)
598763c5484eSTejun Heo {
598863c5484eSTejun Heo 	return scnprintf(buffer, PAGE_SIZE, "%s\n", wq_affn_names[wq_affn_dfl]);
598963c5484eSTejun Heo }
599063c5484eSTejun Heo 
599163c5484eSTejun Heo static const struct kernel_param_ops wq_affn_dfl_ops = {
599263c5484eSTejun Heo 	.set	= wq_affn_dfl_set,
599363c5484eSTejun Heo 	.get	= wq_affn_dfl_get,
599463c5484eSTejun Heo };
599563c5484eSTejun Heo 
599663c5484eSTejun Heo module_param_cb(default_affinity_scope, &wq_affn_dfl_ops, NULL, 0644);
599763c5484eSTejun Heo 
59986ba94429SFrederic Weisbecker #ifdef CONFIG_SYSFS
59996ba94429SFrederic Weisbecker /*
60006ba94429SFrederic Weisbecker  * Workqueues with WQ_SYSFS flag set is visible to userland via
60016ba94429SFrederic Weisbecker  * /sys/bus/workqueue/devices/WQ_NAME.  All visible workqueues have the
60026ba94429SFrederic Weisbecker  * following attributes.
60036ba94429SFrederic Weisbecker  *
60046ba94429SFrederic Weisbecker  *  per_cpu		RO bool	: whether the workqueue is per-cpu or unbound
60056ba94429SFrederic Weisbecker  *  max_active		RW int	: maximum number of in-flight work items
60066ba94429SFrederic Weisbecker  *
60076ba94429SFrederic Weisbecker  * Unbound workqueues have the following extra attributes.
60086ba94429SFrederic Weisbecker  *
60096ba94429SFrederic Weisbecker  *  nice		RW int	: nice value of the workers
60106ba94429SFrederic Weisbecker  *  cpumask		RW mask	: bitmask of allowed CPUs for the workers
601163c5484eSTejun Heo  *  affinity_scope	RW str  : worker CPU affinity scope (cache, numa, none)
60128639ecebSTejun Heo  *  affinity_strict	RW bool : worker CPU affinity is strict
60136ba94429SFrederic Weisbecker  */
60146ba94429SFrederic Weisbecker struct wq_device {
60156ba94429SFrederic Weisbecker 	struct workqueue_struct		*wq;
60166ba94429SFrederic Weisbecker 	struct device			dev;
60176ba94429SFrederic Weisbecker };
60186ba94429SFrederic Weisbecker 
60196ba94429SFrederic Weisbecker static struct workqueue_struct *dev_to_wq(struct device *dev)
60206ba94429SFrederic Weisbecker {
60216ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
60226ba94429SFrederic Weisbecker 
60236ba94429SFrederic Weisbecker 	return wq_dev->wq;
60246ba94429SFrederic Weisbecker }
60256ba94429SFrederic Weisbecker 
60266ba94429SFrederic Weisbecker static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
60276ba94429SFrederic Weisbecker 			    char *buf)
60286ba94429SFrederic Weisbecker {
60296ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
60306ba94429SFrederic Weisbecker 
60316ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
60326ba94429SFrederic Weisbecker }
60336ba94429SFrederic Weisbecker static DEVICE_ATTR_RO(per_cpu);
60346ba94429SFrederic Weisbecker 
60356ba94429SFrederic Weisbecker static ssize_t max_active_show(struct device *dev,
60366ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
60376ba94429SFrederic Weisbecker {
60386ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
60396ba94429SFrederic Weisbecker 
60406ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
60416ba94429SFrederic Weisbecker }
60426ba94429SFrederic Weisbecker 
60436ba94429SFrederic Weisbecker static ssize_t max_active_store(struct device *dev,
60446ba94429SFrederic Weisbecker 				struct device_attribute *attr, const char *buf,
60456ba94429SFrederic Weisbecker 				size_t count)
60466ba94429SFrederic Weisbecker {
60476ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
60486ba94429SFrederic Weisbecker 	int val;
60496ba94429SFrederic Weisbecker 
60506ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &val) != 1 || val <= 0)
60516ba94429SFrederic Weisbecker 		return -EINVAL;
60526ba94429SFrederic Weisbecker 
60536ba94429SFrederic Weisbecker 	workqueue_set_max_active(wq, val);
60546ba94429SFrederic Weisbecker 	return count;
60556ba94429SFrederic Weisbecker }
60566ba94429SFrederic Weisbecker static DEVICE_ATTR_RW(max_active);
60576ba94429SFrederic Weisbecker 
60586ba94429SFrederic Weisbecker static struct attribute *wq_sysfs_attrs[] = {
60596ba94429SFrederic Weisbecker 	&dev_attr_per_cpu.attr,
60606ba94429SFrederic Weisbecker 	&dev_attr_max_active.attr,
60616ba94429SFrederic Weisbecker 	NULL,
60626ba94429SFrederic Weisbecker };
60636ba94429SFrederic Weisbecker ATTRIBUTE_GROUPS(wq_sysfs);
60646ba94429SFrederic Weisbecker 
606549277a5bSWaiman Long static void apply_wqattrs_lock(void)
606649277a5bSWaiman Long {
606749277a5bSWaiman Long 	/* CPUs should stay stable across pwq creations and installations */
606849277a5bSWaiman Long 	cpus_read_lock();
606949277a5bSWaiman Long 	mutex_lock(&wq_pool_mutex);
607049277a5bSWaiman Long }
607149277a5bSWaiman Long 
607249277a5bSWaiman Long static void apply_wqattrs_unlock(void)
607349277a5bSWaiman Long {
607449277a5bSWaiman Long 	mutex_unlock(&wq_pool_mutex);
607549277a5bSWaiman Long 	cpus_read_unlock();
607649277a5bSWaiman Long }
607749277a5bSWaiman Long 
60786ba94429SFrederic Weisbecker static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
60796ba94429SFrederic Weisbecker 			    char *buf)
60806ba94429SFrederic Weisbecker {
60816ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
60826ba94429SFrederic Weisbecker 	int written;
60836ba94429SFrederic Weisbecker 
60846ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
60856ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
60866ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
60876ba94429SFrederic Weisbecker 
60886ba94429SFrederic Weisbecker 	return written;
60896ba94429SFrederic Weisbecker }
60906ba94429SFrederic Weisbecker 
60916ba94429SFrederic Weisbecker /* prepare workqueue_attrs for sysfs store operations */
60926ba94429SFrederic Weisbecker static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
60936ba94429SFrederic Weisbecker {
60946ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
60956ba94429SFrederic Weisbecker 
6096899a94feSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
6097899a94feSLai Jiangshan 
6098be69d00dSThomas Gleixner 	attrs = alloc_workqueue_attrs();
60996ba94429SFrederic Weisbecker 	if (!attrs)
61006ba94429SFrederic Weisbecker 		return NULL;
61016ba94429SFrederic Weisbecker 
61026ba94429SFrederic Weisbecker 	copy_workqueue_attrs(attrs, wq->unbound_attrs);
61036ba94429SFrederic Weisbecker 	return attrs;
61046ba94429SFrederic Weisbecker }
61056ba94429SFrederic Weisbecker 
61066ba94429SFrederic Weisbecker static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
61076ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
61086ba94429SFrederic Weisbecker {
61096ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
61106ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
6111d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
6112d4d3e257SLai Jiangshan 
6113d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
61146ba94429SFrederic Weisbecker 
61156ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
61166ba94429SFrederic Weisbecker 	if (!attrs)
6117d4d3e257SLai Jiangshan 		goto out_unlock;
61186ba94429SFrederic Weisbecker 
61196ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &attrs->nice) == 1 &&
61206ba94429SFrederic Weisbecker 	    attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
6121d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
61226ba94429SFrederic Weisbecker 	else
61236ba94429SFrederic Weisbecker 		ret = -EINVAL;
61246ba94429SFrederic Weisbecker 
6125d4d3e257SLai Jiangshan out_unlock:
6126d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
61276ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
61286ba94429SFrederic Weisbecker 	return ret ?: count;
61296ba94429SFrederic Weisbecker }
61306ba94429SFrederic Weisbecker 
61316ba94429SFrederic Weisbecker static ssize_t wq_cpumask_show(struct device *dev,
61326ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
61336ba94429SFrederic Weisbecker {
61346ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
61356ba94429SFrederic Weisbecker 	int written;
61366ba94429SFrederic Weisbecker 
61376ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
61386ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
61396ba94429SFrederic Weisbecker 			    cpumask_pr_args(wq->unbound_attrs->cpumask));
61406ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
61416ba94429SFrederic Weisbecker 	return written;
61426ba94429SFrederic Weisbecker }
61436ba94429SFrederic Weisbecker 
61446ba94429SFrederic Weisbecker static ssize_t wq_cpumask_store(struct device *dev,
61456ba94429SFrederic Weisbecker 				struct device_attribute *attr,
61466ba94429SFrederic Weisbecker 				const char *buf, size_t count)
61476ba94429SFrederic Weisbecker {
61486ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
61496ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
6150d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
6151d4d3e257SLai Jiangshan 
6152d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
61536ba94429SFrederic Weisbecker 
61546ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
61556ba94429SFrederic Weisbecker 	if (!attrs)
6156d4d3e257SLai Jiangshan 		goto out_unlock;
61576ba94429SFrederic Weisbecker 
61586ba94429SFrederic Weisbecker 	ret = cpumask_parse(buf, attrs->cpumask);
61596ba94429SFrederic Weisbecker 	if (!ret)
6160d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
61616ba94429SFrederic Weisbecker 
6162d4d3e257SLai Jiangshan out_unlock:
6163d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
61646ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
61656ba94429SFrederic Weisbecker 	return ret ?: count;
61666ba94429SFrederic Weisbecker }
61676ba94429SFrederic Weisbecker 
616863c5484eSTejun Heo static ssize_t wq_affn_scope_show(struct device *dev,
616963c5484eSTejun Heo 				  struct device_attribute *attr, char *buf)
617063c5484eSTejun Heo {
617163c5484eSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
617263c5484eSTejun Heo 	int written;
617363c5484eSTejun Heo 
617463c5484eSTejun Heo 	mutex_lock(&wq->mutex);
6175523a301eSTejun Heo 	if (wq->unbound_attrs->affn_scope == WQ_AFFN_DFL)
6176523a301eSTejun Heo 		written = scnprintf(buf, PAGE_SIZE, "%s (%s)\n",
6177523a301eSTejun Heo 				    wq_affn_names[WQ_AFFN_DFL],
6178523a301eSTejun Heo 				    wq_affn_names[wq_affn_dfl]);
6179523a301eSTejun Heo 	else
618063c5484eSTejun Heo 		written = scnprintf(buf, PAGE_SIZE, "%s\n",
618163c5484eSTejun Heo 				    wq_affn_names[wq->unbound_attrs->affn_scope]);
618263c5484eSTejun Heo 	mutex_unlock(&wq->mutex);
618363c5484eSTejun Heo 
618463c5484eSTejun Heo 	return written;
618563c5484eSTejun Heo }
618663c5484eSTejun Heo 
618763c5484eSTejun Heo static ssize_t wq_affn_scope_store(struct device *dev,
618863c5484eSTejun Heo 				   struct device_attribute *attr,
618963c5484eSTejun Heo 				   const char *buf, size_t count)
619063c5484eSTejun Heo {
619163c5484eSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
619263c5484eSTejun Heo 	struct workqueue_attrs *attrs;
619363c5484eSTejun Heo 	int affn, ret = -ENOMEM;
619463c5484eSTejun Heo 
619563c5484eSTejun Heo 	affn = parse_affn_scope(buf);
619663c5484eSTejun Heo 	if (affn < 0)
619763c5484eSTejun Heo 		return affn;
619863c5484eSTejun Heo 
619963c5484eSTejun Heo 	apply_wqattrs_lock();
620063c5484eSTejun Heo 	attrs = wq_sysfs_prep_attrs(wq);
620163c5484eSTejun Heo 	if (attrs) {
620263c5484eSTejun Heo 		attrs->affn_scope = affn;
620363c5484eSTejun Heo 		ret = apply_workqueue_attrs_locked(wq, attrs);
620463c5484eSTejun Heo 	}
620563c5484eSTejun Heo 	apply_wqattrs_unlock();
620663c5484eSTejun Heo 	free_workqueue_attrs(attrs);
620763c5484eSTejun Heo 	return ret ?: count;
620863c5484eSTejun Heo }
620963c5484eSTejun Heo 
62108639ecebSTejun Heo static ssize_t wq_affinity_strict_show(struct device *dev,
62118639ecebSTejun Heo 				       struct device_attribute *attr, char *buf)
62128639ecebSTejun Heo {
62138639ecebSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
62148639ecebSTejun Heo 
62158639ecebSTejun Heo 	return scnprintf(buf, PAGE_SIZE, "%d\n",
62168639ecebSTejun Heo 			 wq->unbound_attrs->affn_strict);
62178639ecebSTejun Heo }
62188639ecebSTejun Heo 
62198639ecebSTejun Heo static ssize_t wq_affinity_strict_store(struct device *dev,
62208639ecebSTejun Heo 					struct device_attribute *attr,
62218639ecebSTejun Heo 					const char *buf, size_t count)
62228639ecebSTejun Heo {
62238639ecebSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
62248639ecebSTejun Heo 	struct workqueue_attrs *attrs;
62258639ecebSTejun Heo 	int v, ret = -ENOMEM;
62268639ecebSTejun Heo 
62278639ecebSTejun Heo 	if (sscanf(buf, "%d", &v) != 1)
62288639ecebSTejun Heo 		return -EINVAL;
62298639ecebSTejun Heo 
62308639ecebSTejun Heo 	apply_wqattrs_lock();
62318639ecebSTejun Heo 	attrs = wq_sysfs_prep_attrs(wq);
62328639ecebSTejun Heo 	if (attrs) {
62338639ecebSTejun Heo 		attrs->affn_strict = (bool)v;
62348639ecebSTejun Heo 		ret = apply_workqueue_attrs_locked(wq, attrs);
62358639ecebSTejun Heo 	}
62368639ecebSTejun Heo 	apply_wqattrs_unlock();
62378639ecebSTejun Heo 	free_workqueue_attrs(attrs);
62388639ecebSTejun Heo 	return ret ?: count;
62398639ecebSTejun Heo }
62408639ecebSTejun Heo 
62416ba94429SFrederic Weisbecker static struct device_attribute wq_sysfs_unbound_attrs[] = {
62426ba94429SFrederic Weisbecker 	__ATTR(nice, 0644, wq_nice_show, wq_nice_store),
62436ba94429SFrederic Weisbecker 	__ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
624463c5484eSTejun Heo 	__ATTR(affinity_scope, 0644, wq_affn_scope_show, wq_affn_scope_store),
62458639ecebSTejun Heo 	__ATTR(affinity_strict, 0644, wq_affinity_strict_show, wq_affinity_strict_store),
62466ba94429SFrederic Weisbecker 	__ATTR_NULL,
62476ba94429SFrederic Weisbecker };
62486ba94429SFrederic Weisbecker 
62496ba94429SFrederic Weisbecker static struct bus_type wq_subsys = {
62506ba94429SFrederic Weisbecker 	.name				= "workqueue",
62516ba94429SFrederic Weisbecker 	.dev_groups			= wq_sysfs_groups,
62526ba94429SFrederic Weisbecker };
62536ba94429SFrederic Weisbecker 
625449277a5bSWaiman Long /**
625549277a5bSWaiman Long  *  workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
625649277a5bSWaiman Long  *  @cpumask: the cpumask to set
625749277a5bSWaiman Long  *
625849277a5bSWaiman Long  *  The low-level workqueues cpumask is a global cpumask that limits
625949277a5bSWaiman Long  *  the affinity of all unbound workqueues.  This function check the @cpumask
626049277a5bSWaiman Long  *  and apply it to all unbound workqueues and updates all pwqs of them.
626149277a5bSWaiman Long  *
626249277a5bSWaiman Long  *  Return:	0	- Success
626349277a5bSWaiman Long  *		-EINVAL	- Invalid @cpumask
626449277a5bSWaiman Long  *		-ENOMEM	- Failed to allocate memory for attrs or pwqs.
626549277a5bSWaiman Long  */
626649277a5bSWaiman Long static int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
626749277a5bSWaiman Long {
626849277a5bSWaiman Long 	int ret = -EINVAL;
626949277a5bSWaiman Long 
627049277a5bSWaiman Long 	/*
627149277a5bSWaiman Long 	 * Not excluding isolated cpus on purpose.
627249277a5bSWaiman Long 	 * If the user wishes to include them, we allow that.
627349277a5bSWaiman Long 	 */
627449277a5bSWaiman Long 	cpumask_and(cpumask, cpumask, cpu_possible_mask);
627549277a5bSWaiman Long 	if (!cpumask_empty(cpumask)) {
627649277a5bSWaiman Long 		apply_wqattrs_lock();
627749277a5bSWaiman Long 		cpumask_copy(wq_requested_unbound_cpumask, cpumask);
627849277a5bSWaiman Long 		if (cpumask_equal(cpumask, wq_unbound_cpumask)) {
627949277a5bSWaiman Long 			ret = 0;
628049277a5bSWaiman Long 			goto out_unlock;
628149277a5bSWaiman Long 		}
628249277a5bSWaiman Long 
628349277a5bSWaiman Long 		ret = workqueue_apply_unbound_cpumask(cpumask);
628449277a5bSWaiman Long 
628549277a5bSWaiman Long out_unlock:
628649277a5bSWaiman Long 		apply_wqattrs_unlock();
628749277a5bSWaiman Long 	}
628849277a5bSWaiman Long 
628949277a5bSWaiman Long 	return ret;
629049277a5bSWaiman Long }
629149277a5bSWaiman Long 
6292fe28f631SWaiman Long static ssize_t __wq_cpumask_show(struct device *dev,
6293fe28f631SWaiman Long 		struct device_attribute *attr, char *buf, cpumask_var_t mask)
6294b05a7928SFrederic Weisbecker {
6295b05a7928SFrederic Weisbecker 	int written;
6296b05a7928SFrederic Weisbecker 
6297042f7df1SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
6298fe28f631SWaiman Long 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n", cpumask_pr_args(mask));
6299042f7df1SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
6300b05a7928SFrederic Weisbecker 
6301b05a7928SFrederic Weisbecker 	return written;
6302b05a7928SFrederic Weisbecker }
6303b05a7928SFrederic Weisbecker 
6304fe28f631SWaiman Long static ssize_t wq_unbound_cpumask_show(struct device *dev,
6305fe28f631SWaiman Long 		struct device_attribute *attr, char *buf)
6306fe28f631SWaiman Long {
6307fe28f631SWaiman Long 	return __wq_cpumask_show(dev, attr, buf, wq_unbound_cpumask);
6308fe28f631SWaiman Long }
6309fe28f631SWaiman Long 
6310fe28f631SWaiman Long static ssize_t wq_requested_cpumask_show(struct device *dev,
6311fe28f631SWaiman Long 		struct device_attribute *attr, char *buf)
6312fe28f631SWaiman Long {
6313fe28f631SWaiman Long 	return __wq_cpumask_show(dev, attr, buf, wq_requested_unbound_cpumask);
6314fe28f631SWaiman Long }
6315fe28f631SWaiman Long 
6316fe28f631SWaiman Long static ssize_t wq_isolated_cpumask_show(struct device *dev,
6317fe28f631SWaiman Long 		struct device_attribute *attr, char *buf)
6318fe28f631SWaiman Long {
6319fe28f631SWaiman Long 	return __wq_cpumask_show(dev, attr, buf, wq_isolated_cpumask);
6320fe28f631SWaiman Long }
6321fe28f631SWaiman Long 
6322042f7df1SLai Jiangshan static ssize_t wq_unbound_cpumask_store(struct device *dev,
6323042f7df1SLai Jiangshan 		struct device_attribute *attr, const char *buf, size_t count)
6324042f7df1SLai Jiangshan {
6325042f7df1SLai Jiangshan 	cpumask_var_t cpumask;
6326042f7df1SLai Jiangshan 	int ret;
6327042f7df1SLai Jiangshan 
6328042f7df1SLai Jiangshan 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
6329042f7df1SLai Jiangshan 		return -ENOMEM;
6330042f7df1SLai Jiangshan 
6331042f7df1SLai Jiangshan 	ret = cpumask_parse(buf, cpumask);
6332042f7df1SLai Jiangshan 	if (!ret)
6333042f7df1SLai Jiangshan 		ret = workqueue_set_unbound_cpumask(cpumask);
6334042f7df1SLai Jiangshan 
6335042f7df1SLai Jiangshan 	free_cpumask_var(cpumask);
6336042f7df1SLai Jiangshan 	return ret ? ret : count;
6337042f7df1SLai Jiangshan }
6338042f7df1SLai Jiangshan 
6339fe28f631SWaiman Long static struct device_attribute wq_sysfs_cpumask_attrs[] = {
6340042f7df1SLai Jiangshan 	__ATTR(cpumask, 0644, wq_unbound_cpumask_show,
6341fe28f631SWaiman Long 	       wq_unbound_cpumask_store),
6342fe28f631SWaiman Long 	__ATTR(cpumask_requested, 0444, wq_requested_cpumask_show, NULL),
6343fe28f631SWaiman Long 	__ATTR(cpumask_isolated, 0444, wq_isolated_cpumask_show, NULL),
6344fe28f631SWaiman Long 	__ATTR_NULL,
6345fe28f631SWaiman Long };
6346b05a7928SFrederic Weisbecker 
63476ba94429SFrederic Weisbecker static int __init wq_sysfs_init(void)
63486ba94429SFrederic Weisbecker {
6349686f6697SGreg Kroah-Hartman 	struct device *dev_root;
6350b05a7928SFrederic Weisbecker 	int err;
6351b05a7928SFrederic Weisbecker 
6352b05a7928SFrederic Weisbecker 	err = subsys_virtual_register(&wq_subsys, NULL);
6353b05a7928SFrederic Weisbecker 	if (err)
6354b05a7928SFrederic Weisbecker 		return err;
6355b05a7928SFrederic Weisbecker 
6356686f6697SGreg Kroah-Hartman 	dev_root = bus_get_dev_root(&wq_subsys);
6357686f6697SGreg Kroah-Hartman 	if (dev_root) {
6358fe28f631SWaiman Long 		struct device_attribute *attr;
6359fe28f631SWaiman Long 
6360fe28f631SWaiman Long 		for (attr = wq_sysfs_cpumask_attrs; attr->attr.name; attr++) {
6361fe28f631SWaiman Long 			err = device_create_file(dev_root, attr);
6362fe28f631SWaiman Long 			if (err)
6363fe28f631SWaiman Long 				break;
6364fe28f631SWaiman Long 		}
6365686f6697SGreg Kroah-Hartman 		put_device(dev_root);
6366686f6697SGreg Kroah-Hartman 	}
6367686f6697SGreg Kroah-Hartman 	return err;
63686ba94429SFrederic Weisbecker }
63696ba94429SFrederic Weisbecker core_initcall(wq_sysfs_init);
63706ba94429SFrederic Weisbecker 
63716ba94429SFrederic Weisbecker static void wq_device_release(struct device *dev)
63726ba94429SFrederic Weisbecker {
63736ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
63746ba94429SFrederic Weisbecker 
63756ba94429SFrederic Weisbecker 	kfree(wq_dev);
63766ba94429SFrederic Weisbecker }
63776ba94429SFrederic Weisbecker 
63786ba94429SFrederic Weisbecker /**
63796ba94429SFrederic Weisbecker  * workqueue_sysfs_register - make a workqueue visible in sysfs
63806ba94429SFrederic Weisbecker  * @wq: the workqueue to register
63816ba94429SFrederic Weisbecker  *
63826ba94429SFrederic Weisbecker  * Expose @wq in sysfs under /sys/bus/workqueue/devices.
63836ba94429SFrederic Weisbecker  * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
63846ba94429SFrederic Weisbecker  * which is the preferred method.
63856ba94429SFrederic Weisbecker  *
63866ba94429SFrederic Weisbecker  * Workqueue user should use this function directly iff it wants to apply
63876ba94429SFrederic Weisbecker  * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
63886ba94429SFrederic Weisbecker  * apply_workqueue_attrs() may race against userland updating the
63896ba94429SFrederic Weisbecker  * attributes.
63906ba94429SFrederic Weisbecker  *
63916ba94429SFrederic Weisbecker  * Return: 0 on success, -errno on failure.
63926ba94429SFrederic Weisbecker  */
63936ba94429SFrederic Weisbecker int workqueue_sysfs_register(struct workqueue_struct *wq)
63946ba94429SFrederic Weisbecker {
63956ba94429SFrederic Weisbecker 	struct wq_device *wq_dev;
63966ba94429SFrederic Weisbecker 	int ret;
63976ba94429SFrederic Weisbecker 
63986ba94429SFrederic Weisbecker 	/*
6399402dd89dSShailendra Verma 	 * Adjusting max_active or creating new pwqs by applying
64006ba94429SFrederic Weisbecker 	 * attributes breaks ordering guarantee.  Disallow exposing ordered
64016ba94429SFrederic Weisbecker 	 * workqueues.
64026ba94429SFrederic Weisbecker 	 */
64030a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
64046ba94429SFrederic Weisbecker 		return -EINVAL;
64056ba94429SFrederic Weisbecker 
64066ba94429SFrederic Weisbecker 	wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
64076ba94429SFrederic Weisbecker 	if (!wq_dev)
64086ba94429SFrederic Weisbecker 		return -ENOMEM;
64096ba94429SFrederic Weisbecker 
64106ba94429SFrederic Weisbecker 	wq_dev->wq = wq;
64116ba94429SFrederic Weisbecker 	wq_dev->dev.bus = &wq_subsys;
64126ba94429SFrederic Weisbecker 	wq_dev->dev.release = wq_device_release;
641323217b44SLars-Peter Clausen 	dev_set_name(&wq_dev->dev, "%s", wq->name);
64146ba94429SFrederic Weisbecker 
64156ba94429SFrederic Weisbecker 	/*
64166ba94429SFrederic Weisbecker 	 * unbound_attrs are created separately.  Suppress uevent until
64176ba94429SFrederic Weisbecker 	 * everything is ready.
64186ba94429SFrederic Weisbecker 	 */
64196ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, true);
64206ba94429SFrederic Weisbecker 
64216ba94429SFrederic Weisbecker 	ret = device_register(&wq_dev->dev);
64226ba94429SFrederic Weisbecker 	if (ret) {
6423537f4146SArvind Yadav 		put_device(&wq_dev->dev);
64246ba94429SFrederic Weisbecker 		wq->wq_dev = NULL;
64256ba94429SFrederic Weisbecker 		return ret;
64266ba94429SFrederic Weisbecker 	}
64276ba94429SFrederic Weisbecker 
64286ba94429SFrederic Weisbecker 	if (wq->flags & WQ_UNBOUND) {
64296ba94429SFrederic Weisbecker 		struct device_attribute *attr;
64306ba94429SFrederic Weisbecker 
64316ba94429SFrederic Weisbecker 		for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
64326ba94429SFrederic Weisbecker 			ret = device_create_file(&wq_dev->dev, attr);
64336ba94429SFrederic Weisbecker 			if (ret) {
64346ba94429SFrederic Weisbecker 				device_unregister(&wq_dev->dev);
64356ba94429SFrederic Weisbecker 				wq->wq_dev = NULL;
64366ba94429SFrederic Weisbecker 				return ret;
64376ba94429SFrederic Weisbecker 			}
64386ba94429SFrederic Weisbecker 		}
64396ba94429SFrederic Weisbecker 	}
64406ba94429SFrederic Weisbecker 
64416ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, false);
64426ba94429SFrederic Weisbecker 	kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
64436ba94429SFrederic Weisbecker 	return 0;
64446ba94429SFrederic Weisbecker }
64456ba94429SFrederic Weisbecker 
64466ba94429SFrederic Weisbecker /**
64476ba94429SFrederic Weisbecker  * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
64486ba94429SFrederic Weisbecker  * @wq: the workqueue to unregister
64496ba94429SFrederic Weisbecker  *
64506ba94429SFrederic Weisbecker  * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
64516ba94429SFrederic Weisbecker  */
64526ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
64536ba94429SFrederic Weisbecker {
64546ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = wq->wq_dev;
64556ba94429SFrederic Weisbecker 
64566ba94429SFrederic Weisbecker 	if (!wq->wq_dev)
64576ba94429SFrederic Weisbecker 		return;
64586ba94429SFrederic Weisbecker 
64596ba94429SFrederic Weisbecker 	wq->wq_dev = NULL;
64606ba94429SFrederic Weisbecker 	device_unregister(&wq_dev->dev);
64616ba94429SFrederic Weisbecker }
64626ba94429SFrederic Weisbecker #else	/* CONFIG_SYSFS */
64636ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)	{ }
64646ba94429SFrederic Weisbecker #endif	/* CONFIG_SYSFS */
64656ba94429SFrederic Weisbecker 
646682607adcSTejun Heo /*
646782607adcSTejun Heo  * Workqueue watchdog.
646882607adcSTejun Heo  *
646982607adcSTejun Heo  * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
647082607adcSTejun Heo  * flush dependency, a concurrency managed work item which stays RUNNING
647182607adcSTejun Heo  * indefinitely.  Workqueue stalls can be very difficult to debug as the
647282607adcSTejun Heo  * usual warning mechanisms don't trigger and internal workqueue state is
647382607adcSTejun Heo  * largely opaque.
647482607adcSTejun Heo  *
647582607adcSTejun Heo  * Workqueue watchdog monitors all worker pools periodically and dumps
647682607adcSTejun Heo  * state if some pools failed to make forward progress for a while where
647782607adcSTejun Heo  * forward progress is defined as the first item on ->worklist changing.
647882607adcSTejun Heo  *
647982607adcSTejun Heo  * This mechanism is controlled through the kernel parameter
648082607adcSTejun Heo  * "workqueue.watchdog_thresh" which can be updated at runtime through the
648182607adcSTejun Heo  * corresponding sysfs parameter file.
648282607adcSTejun Heo  */
648382607adcSTejun Heo #ifdef CONFIG_WQ_WATCHDOG
648482607adcSTejun Heo 
648582607adcSTejun Heo static unsigned long wq_watchdog_thresh = 30;
64865cd79d6aSKees Cook static struct timer_list wq_watchdog_timer;
648782607adcSTejun Heo 
648882607adcSTejun Heo static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
648982607adcSTejun Heo static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
649082607adcSTejun Heo 
6491cd2440d6SPetr Mladek /*
6492cd2440d6SPetr Mladek  * Show workers that might prevent the processing of pending work items.
6493cd2440d6SPetr Mladek  * The only candidates are CPU-bound workers in the running state.
6494cd2440d6SPetr Mladek  * Pending work items should be handled by another idle worker
6495cd2440d6SPetr Mladek  * in all other situations.
6496cd2440d6SPetr Mladek  */
6497cd2440d6SPetr Mladek static void show_cpu_pool_hog(struct worker_pool *pool)
6498cd2440d6SPetr Mladek {
6499cd2440d6SPetr Mladek 	struct worker *worker;
6500cd2440d6SPetr Mladek 	unsigned long flags;
6501cd2440d6SPetr Mladek 	int bkt;
6502cd2440d6SPetr Mladek 
6503cd2440d6SPetr Mladek 	raw_spin_lock_irqsave(&pool->lock, flags);
6504cd2440d6SPetr Mladek 
6505cd2440d6SPetr Mladek 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
6506cd2440d6SPetr Mladek 		if (task_is_running(worker->task)) {
6507cd2440d6SPetr Mladek 			/*
6508cd2440d6SPetr Mladek 			 * Defer printing to avoid deadlocks in console
6509cd2440d6SPetr Mladek 			 * drivers that queue work while holding locks
6510cd2440d6SPetr Mladek 			 * also taken in their write paths.
6511cd2440d6SPetr Mladek 			 */
6512cd2440d6SPetr Mladek 			printk_deferred_enter();
6513cd2440d6SPetr Mladek 
6514cd2440d6SPetr Mladek 			pr_info("pool %d:\n", pool->id);
6515cd2440d6SPetr Mladek 			sched_show_task(worker->task);
6516cd2440d6SPetr Mladek 
6517cd2440d6SPetr Mladek 			printk_deferred_exit();
6518cd2440d6SPetr Mladek 		}
6519cd2440d6SPetr Mladek 	}
6520cd2440d6SPetr Mladek 
6521cd2440d6SPetr Mladek 	raw_spin_unlock_irqrestore(&pool->lock, flags);
6522cd2440d6SPetr Mladek }
6523cd2440d6SPetr Mladek 
6524cd2440d6SPetr Mladek static void show_cpu_pools_hogs(void)
6525cd2440d6SPetr Mladek {
6526cd2440d6SPetr Mladek 	struct worker_pool *pool;
6527cd2440d6SPetr Mladek 	int pi;
6528cd2440d6SPetr Mladek 
6529cd2440d6SPetr Mladek 	pr_info("Showing backtraces of running workers in stalled CPU-bound worker pools:\n");
6530cd2440d6SPetr Mladek 
6531cd2440d6SPetr Mladek 	rcu_read_lock();
6532cd2440d6SPetr Mladek 
6533cd2440d6SPetr Mladek 	for_each_pool(pool, pi) {
6534cd2440d6SPetr Mladek 		if (pool->cpu_stall)
6535cd2440d6SPetr Mladek 			show_cpu_pool_hog(pool);
6536cd2440d6SPetr Mladek 
6537cd2440d6SPetr Mladek 	}
6538cd2440d6SPetr Mladek 
6539cd2440d6SPetr Mladek 	rcu_read_unlock();
6540cd2440d6SPetr Mladek }
6541cd2440d6SPetr Mladek 
654282607adcSTejun Heo static void wq_watchdog_reset_touched(void)
654382607adcSTejun Heo {
654482607adcSTejun Heo 	int cpu;
654582607adcSTejun Heo 
654682607adcSTejun Heo 	wq_watchdog_touched = jiffies;
654782607adcSTejun Heo 	for_each_possible_cpu(cpu)
654882607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
654982607adcSTejun Heo }
655082607adcSTejun Heo 
65515cd79d6aSKees Cook static void wq_watchdog_timer_fn(struct timer_list *unused)
655282607adcSTejun Heo {
655382607adcSTejun Heo 	unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
655482607adcSTejun Heo 	bool lockup_detected = false;
6555cd2440d6SPetr Mladek 	bool cpu_pool_stall = false;
6556940d71c6SSergey Senozhatsky 	unsigned long now = jiffies;
655782607adcSTejun Heo 	struct worker_pool *pool;
655882607adcSTejun Heo 	int pi;
655982607adcSTejun Heo 
656082607adcSTejun Heo 	if (!thresh)
656182607adcSTejun Heo 		return;
656282607adcSTejun Heo 
656382607adcSTejun Heo 	rcu_read_lock();
656482607adcSTejun Heo 
656582607adcSTejun Heo 	for_each_pool(pool, pi) {
656682607adcSTejun Heo 		unsigned long pool_ts, touched, ts;
656782607adcSTejun Heo 
6568cd2440d6SPetr Mladek 		pool->cpu_stall = false;
656982607adcSTejun Heo 		if (list_empty(&pool->worklist))
657082607adcSTejun Heo 			continue;
657182607adcSTejun Heo 
6572940d71c6SSergey Senozhatsky 		/*
6573940d71c6SSergey Senozhatsky 		 * If a virtual machine is stopped by the host it can look to
6574940d71c6SSergey Senozhatsky 		 * the watchdog like a stall.
6575940d71c6SSergey Senozhatsky 		 */
6576940d71c6SSergey Senozhatsky 		kvm_check_and_clear_guest_paused();
6577940d71c6SSergey Senozhatsky 
657882607adcSTejun Heo 		/* get the latest of pool and touched timestamps */
657989e28ce6SWang Qing 		if (pool->cpu >= 0)
658089e28ce6SWang Qing 			touched = READ_ONCE(per_cpu(wq_watchdog_touched_cpu, pool->cpu));
658189e28ce6SWang Qing 		else
658282607adcSTejun Heo 			touched = READ_ONCE(wq_watchdog_touched);
658389e28ce6SWang Qing 		pool_ts = READ_ONCE(pool->watchdog_ts);
658482607adcSTejun Heo 
658582607adcSTejun Heo 		if (time_after(pool_ts, touched))
658682607adcSTejun Heo 			ts = pool_ts;
658782607adcSTejun Heo 		else
658882607adcSTejun Heo 			ts = touched;
658982607adcSTejun Heo 
659082607adcSTejun Heo 		/* did we stall? */
6591940d71c6SSergey Senozhatsky 		if (time_after(now, ts + thresh)) {
659282607adcSTejun Heo 			lockup_detected = true;
6593cd2440d6SPetr Mladek 			if (pool->cpu >= 0) {
6594cd2440d6SPetr Mladek 				pool->cpu_stall = true;
6595cd2440d6SPetr Mladek 				cpu_pool_stall = true;
6596cd2440d6SPetr Mladek 			}
659782607adcSTejun Heo 			pr_emerg("BUG: workqueue lockup - pool");
659882607adcSTejun Heo 			pr_cont_pool_info(pool);
659982607adcSTejun Heo 			pr_cont(" stuck for %us!\n",
6600940d71c6SSergey Senozhatsky 				jiffies_to_msecs(now - pool_ts) / 1000);
660182607adcSTejun Heo 		}
6602cd2440d6SPetr Mladek 
6603cd2440d6SPetr Mladek 
660482607adcSTejun Heo 	}
660582607adcSTejun Heo 
660682607adcSTejun Heo 	rcu_read_unlock();
660782607adcSTejun Heo 
660882607adcSTejun Heo 	if (lockup_detected)
660955df0933SImran Khan 		show_all_workqueues();
661082607adcSTejun Heo 
6611cd2440d6SPetr Mladek 	if (cpu_pool_stall)
6612cd2440d6SPetr Mladek 		show_cpu_pools_hogs();
6613cd2440d6SPetr Mladek 
661482607adcSTejun Heo 	wq_watchdog_reset_touched();
661582607adcSTejun Heo 	mod_timer(&wq_watchdog_timer, jiffies + thresh);
661682607adcSTejun Heo }
661782607adcSTejun Heo 
6618cb9d7fd5SVincent Whitchurch notrace void wq_watchdog_touch(int cpu)
661982607adcSTejun Heo {
662082607adcSTejun Heo 	if (cpu >= 0)
662182607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
662289e28ce6SWang Qing 
662382607adcSTejun Heo 	wq_watchdog_touched = jiffies;
662482607adcSTejun Heo }
662582607adcSTejun Heo 
662682607adcSTejun Heo static void wq_watchdog_set_thresh(unsigned long thresh)
662782607adcSTejun Heo {
662882607adcSTejun Heo 	wq_watchdog_thresh = 0;
662982607adcSTejun Heo 	del_timer_sync(&wq_watchdog_timer);
663082607adcSTejun Heo 
663182607adcSTejun Heo 	if (thresh) {
663282607adcSTejun Heo 		wq_watchdog_thresh = thresh;
663382607adcSTejun Heo 		wq_watchdog_reset_touched();
663482607adcSTejun Heo 		mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
663582607adcSTejun Heo 	}
663682607adcSTejun Heo }
663782607adcSTejun Heo 
663882607adcSTejun Heo static int wq_watchdog_param_set_thresh(const char *val,
663982607adcSTejun Heo 					const struct kernel_param *kp)
664082607adcSTejun Heo {
664182607adcSTejun Heo 	unsigned long thresh;
664282607adcSTejun Heo 	int ret;
664382607adcSTejun Heo 
664482607adcSTejun Heo 	ret = kstrtoul(val, 0, &thresh);
664582607adcSTejun Heo 	if (ret)
664682607adcSTejun Heo 		return ret;
664782607adcSTejun Heo 
664882607adcSTejun Heo 	if (system_wq)
664982607adcSTejun Heo 		wq_watchdog_set_thresh(thresh);
665082607adcSTejun Heo 	else
665182607adcSTejun Heo 		wq_watchdog_thresh = thresh;
665282607adcSTejun Heo 
665382607adcSTejun Heo 	return 0;
665482607adcSTejun Heo }
665582607adcSTejun Heo 
665682607adcSTejun Heo static const struct kernel_param_ops wq_watchdog_thresh_ops = {
665782607adcSTejun Heo 	.set	= wq_watchdog_param_set_thresh,
665882607adcSTejun Heo 	.get	= param_get_ulong,
665982607adcSTejun Heo };
666082607adcSTejun Heo 
666182607adcSTejun Heo module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
666282607adcSTejun Heo 		0644);
666382607adcSTejun Heo 
666482607adcSTejun Heo static void wq_watchdog_init(void)
666582607adcSTejun Heo {
66665cd79d6aSKees Cook 	timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
666782607adcSTejun Heo 	wq_watchdog_set_thresh(wq_watchdog_thresh);
666882607adcSTejun Heo }
666982607adcSTejun Heo 
667082607adcSTejun Heo #else	/* CONFIG_WQ_WATCHDOG */
667182607adcSTejun Heo 
667282607adcSTejun Heo static inline void wq_watchdog_init(void) { }
667382607adcSTejun Heo 
667482607adcSTejun Heo #endif	/* CONFIG_WQ_WATCHDOG */
667582607adcSTejun Heo 
66764a6c5607STejun Heo static void __init restrict_unbound_cpumask(const char *name, const struct cpumask *mask)
66774a6c5607STejun Heo {
66784a6c5607STejun Heo 	if (!cpumask_intersects(wq_unbound_cpumask, mask)) {
66794a6c5607STejun Heo 		pr_warn("workqueue: Restricting unbound_cpumask (%*pb) with %s (%*pb) leaves no CPU, ignoring\n",
66804a6c5607STejun Heo 			cpumask_pr_args(wq_unbound_cpumask), name, cpumask_pr_args(mask));
66814a6c5607STejun Heo 		return;
66824a6c5607STejun Heo 	}
66834a6c5607STejun Heo 
66844a6c5607STejun Heo 	cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, mask);
66854a6c5607STejun Heo }
66864a6c5607STejun Heo 
66873347fa09STejun Heo /**
66883347fa09STejun Heo  * workqueue_init_early - early init for workqueue subsystem
66893347fa09STejun Heo  *
66902930155bSTejun Heo  * This is the first step of three-staged workqueue subsystem initialization and
66912930155bSTejun Heo  * invoked as soon as the bare basics - memory allocation, cpumasks and idr are
66922930155bSTejun Heo  * up. It sets up all the data structures and system workqueues and allows early
66932930155bSTejun Heo  * boot code to create workqueues and queue/cancel work items. Actual work item
66942930155bSTejun Heo  * execution starts only after kthreads can be created and scheduled right
66952930155bSTejun Heo  * before early initcalls.
66963347fa09STejun Heo  */
66972333e829SYu Chen void __init workqueue_init_early(void)
66981da177e4SLinus Torvalds {
669984193c07STejun Heo 	struct wq_pod_type *pt = &wq_pod_types[WQ_AFFN_SYSTEM];
67007a4e344cSTejun Heo 	int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
67017a4e344cSTejun Heo 	int i, cpu;
6702c34056a3STejun Heo 
670310cdb157SLai Jiangshan 	BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
6704e904e6c2STejun Heo 
6705b05a7928SFrederic Weisbecker 	BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
6706fe28f631SWaiman Long 	BUG_ON(!alloc_cpumask_var(&wq_requested_unbound_cpumask, GFP_KERNEL));
6707fe28f631SWaiman Long 	BUG_ON(!zalloc_cpumask_var(&wq_isolated_cpumask, GFP_KERNEL));
6708b05a7928SFrederic Weisbecker 
67094a6c5607STejun Heo 	cpumask_copy(wq_unbound_cpumask, cpu_possible_mask);
67104a6c5607STejun Heo 	restrict_unbound_cpumask("HK_TYPE_WQ", housekeeping_cpumask(HK_TYPE_WQ));
67114a6c5607STejun Heo 	restrict_unbound_cpumask("HK_TYPE_DOMAIN", housekeeping_cpumask(HK_TYPE_DOMAIN));
6712ace3c549Stiozhang 	if (!cpumask_empty(&wq_cmdline_cpumask))
67134a6c5607STejun Heo 		restrict_unbound_cpumask("workqueue.unbound_cpus", &wq_cmdline_cpumask);
6714ace3c549Stiozhang 
6715fe28f631SWaiman Long 	cpumask_copy(wq_requested_unbound_cpumask, wq_unbound_cpumask);
67168b03ae3cSTejun Heo 
67178b03ae3cSTejun Heo 	pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
6718e22bee78STejun Heo 
67192930155bSTejun Heo 	wq_update_pod_attrs_buf = alloc_workqueue_attrs();
67202930155bSTejun Heo 	BUG_ON(!wq_update_pod_attrs_buf);
67212930155bSTejun Heo 
67227bd20b6bSMarcelo Tosatti 	/*
67237bd20b6bSMarcelo Tosatti 	 * If nohz_full is enabled, set power efficient workqueue as unbound.
67247bd20b6bSMarcelo Tosatti 	 * This allows workqueue items to be moved to HK CPUs.
67257bd20b6bSMarcelo Tosatti 	 */
67267bd20b6bSMarcelo Tosatti 	if (housekeeping_enabled(HK_TYPE_TICK))
67277bd20b6bSMarcelo Tosatti 		wq_power_efficient = true;
67287bd20b6bSMarcelo Tosatti 
672984193c07STejun Heo 	/* initialize WQ_AFFN_SYSTEM pods */
673084193c07STejun Heo 	pt->pod_cpus = kcalloc(1, sizeof(pt->pod_cpus[0]), GFP_KERNEL);
673184193c07STejun Heo 	pt->pod_node = kcalloc(1, sizeof(pt->pod_node[0]), GFP_KERNEL);
673284193c07STejun Heo 	pt->cpu_pod = kcalloc(nr_cpu_ids, sizeof(pt->cpu_pod[0]), GFP_KERNEL);
673384193c07STejun Heo 	BUG_ON(!pt->pod_cpus || !pt->pod_node || !pt->cpu_pod);
673484193c07STejun Heo 
673584193c07STejun Heo 	BUG_ON(!zalloc_cpumask_var_node(&pt->pod_cpus[0], GFP_KERNEL, NUMA_NO_NODE));
673684193c07STejun Heo 
673784193c07STejun Heo 	pt->nr_pods = 1;
673884193c07STejun Heo 	cpumask_copy(pt->pod_cpus[0], cpu_possible_mask);
673984193c07STejun Heo 	pt->pod_node[0] = NUMA_NO_NODE;
674084193c07STejun Heo 	pt->cpu_pod[0] = 0;
674184193c07STejun Heo 
6742f02ae73aSTejun Heo 	/* initialize CPU pools */
674324647570STejun Heo 	for_each_possible_cpu(cpu) {
6744ebf44d16STejun Heo 		struct worker_pool *pool;
6745e22bee78STejun Heo 
67464ce62e9eSTejun Heo 		i = 0;
6747e22bee78STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
674829c91e99STejun Heo 			BUG_ON(init_worker_pool(pool));
674929c91e99STejun Heo 			pool->cpu = cpu;
675029c91e99STejun Heo 			cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
67519546b29eSTejun Heo 			cpumask_copy(pool->attrs->__pod_cpumask, cpumask_of(cpu));
67521da177e4SLinus Torvalds 			pool->attrs->nice = std_nice[i++];
67538639ecebSTejun Heo 			pool->attrs->affn_strict = true;
67541da177e4SLinus Torvalds 			pool->node = cpu_to_node(cpu);
67551da177e4SLinus Torvalds 
67561da177e4SLinus Torvalds 			/* alloc pool ID */
67571da177e4SLinus Torvalds 			mutex_lock(&wq_pool_mutex);
67581da177e4SLinus Torvalds 			BUG_ON(worker_pool_assign_id(pool));
67591da177e4SLinus Torvalds 			mutex_unlock(&wq_pool_mutex);
676029c91e99STejun Heo 		}
676129c91e99STejun Heo 	}
676229c91e99STejun Heo 
67638a2b7538STejun Heo 	/* create default unbound and ordered wq attrs */
676429c91e99STejun Heo 	for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
676529c91e99STejun Heo 		struct workqueue_attrs *attrs;
676629c91e99STejun Heo 
6767be69d00dSThomas Gleixner 		BUG_ON(!(attrs = alloc_workqueue_attrs()));
676829c91e99STejun Heo 		attrs->nice = std_nice[i];
676929c91e99STejun Heo 		unbound_std_wq_attrs[i] = attrs;
67708a2b7538STejun Heo 
67718a2b7538STejun Heo 		/*
67728a2b7538STejun Heo 		 * An ordered wq should have only one pwq as ordering is
67738a2b7538STejun Heo 		 * guaranteed by max_active which is enforced by pwqs.
67748a2b7538STejun Heo 		 */
6775be69d00dSThomas Gleixner 		BUG_ON(!(attrs = alloc_workqueue_attrs()));
67768a2b7538STejun Heo 		attrs->nice = std_nice[i];
6777af73f5c9STejun Heo 		attrs->ordered = true;
67788a2b7538STejun Heo 		ordered_wq_attrs[i] = attrs;
677929c91e99STejun Heo 	}
678029c91e99STejun Heo 
67811da177e4SLinus Torvalds 	system_wq = alloc_workqueue("events", 0, 0);
67821aabe902SJoonsoo Kim 	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
67831da177e4SLinus Torvalds 	system_long_wq = alloc_workqueue("events_long", 0, 0);
67841da177e4SLinus Torvalds 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
6785636b927eSTejun Heo 					    WQ_MAX_ACTIVE);
67861da177e4SLinus Torvalds 	system_freezable_wq = alloc_workqueue("events_freezable",
67871da177e4SLinus Torvalds 					      WQ_FREEZABLE, 0);
67880668106cSViresh Kumar 	system_power_efficient_wq = alloc_workqueue("events_power_efficient",
67890668106cSViresh Kumar 					      WQ_POWER_EFFICIENT, 0);
67908318d6a6SAudra Mitchell 	system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_pwr_efficient",
67910668106cSViresh Kumar 					      WQ_FREEZABLE | WQ_POWER_EFFICIENT,
67920668106cSViresh Kumar 					      0);
67931aabe902SJoonsoo Kim 	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
67940668106cSViresh Kumar 	       !system_unbound_wq || !system_freezable_wq ||
67950668106cSViresh Kumar 	       !system_power_efficient_wq ||
67960668106cSViresh Kumar 	       !system_freezable_power_efficient_wq);
67973347fa09STejun Heo }
67983347fa09STejun Heo 
6799aa6fde93STejun Heo static void __init wq_cpu_intensive_thresh_init(void)
6800aa6fde93STejun Heo {
6801aa6fde93STejun Heo 	unsigned long thresh;
6802aa6fde93STejun Heo 	unsigned long bogo;
6803aa6fde93STejun Heo 
6804dd64c873SZqiang 	pwq_release_worker = kthread_create_worker(0, "pool_workqueue_release");
6805dd64c873SZqiang 	BUG_ON(IS_ERR(pwq_release_worker));
6806dd64c873SZqiang 
6807aa6fde93STejun Heo 	/* if the user set it to a specific value, keep it */
6808aa6fde93STejun Heo 	if (wq_cpu_intensive_thresh_us != ULONG_MAX)
6809aa6fde93STejun Heo 		return;
6810aa6fde93STejun Heo 
6811aa6fde93STejun Heo 	/*
6812aa6fde93STejun Heo 	 * The default of 10ms is derived from the fact that most modern (as of
6813aa6fde93STejun Heo 	 * 2023) processors can do a lot in 10ms and that it's just below what
6814aa6fde93STejun Heo 	 * most consider human-perceivable. However, the kernel also runs on a
6815aa6fde93STejun Heo 	 * lot slower CPUs including microcontrollers where the threshold is way
6816aa6fde93STejun Heo 	 * too low.
6817aa6fde93STejun Heo 	 *
6818aa6fde93STejun Heo 	 * Let's scale up the threshold upto 1 second if BogoMips is below 4000.
6819aa6fde93STejun Heo 	 * This is by no means accurate but it doesn't have to be. The mechanism
6820aa6fde93STejun Heo 	 * is still useful even when the threshold is fully scaled up. Also, as
6821aa6fde93STejun Heo 	 * the reports would usually be applicable to everyone, some machines
6822aa6fde93STejun Heo 	 * operating on longer thresholds won't significantly diminish their
6823aa6fde93STejun Heo 	 * usefulness.
6824aa6fde93STejun Heo 	 */
6825aa6fde93STejun Heo 	thresh = 10 * USEC_PER_MSEC;
6826aa6fde93STejun Heo 
6827aa6fde93STejun Heo 	/* see init/calibrate.c for lpj -> BogoMIPS calculation */
6828aa6fde93STejun Heo 	bogo = max_t(unsigned long, loops_per_jiffy / 500000 * HZ, 1);
6829aa6fde93STejun Heo 	if (bogo < 4000)
6830aa6fde93STejun Heo 		thresh = min_t(unsigned long, thresh * 4000 / bogo, USEC_PER_SEC);
6831aa6fde93STejun Heo 
6832aa6fde93STejun Heo 	pr_debug("wq_cpu_intensive_thresh: lpj=%lu BogoMIPS=%lu thresh_us=%lu\n",
6833aa6fde93STejun Heo 		 loops_per_jiffy, bogo, thresh);
6834aa6fde93STejun Heo 
6835aa6fde93STejun Heo 	wq_cpu_intensive_thresh_us = thresh;
6836aa6fde93STejun Heo }
6837aa6fde93STejun Heo 
68383347fa09STejun Heo /**
68393347fa09STejun Heo  * workqueue_init - bring workqueue subsystem fully online
68403347fa09STejun Heo  *
68412930155bSTejun Heo  * This is the second step of three-staged workqueue subsystem initialization
68422930155bSTejun Heo  * and invoked as soon as kthreads can be created and scheduled. Workqueues have
68432930155bSTejun Heo  * been created and work items queued on them, but there are no kworkers
68442930155bSTejun Heo  * executing the work items yet. Populate the worker pools with the initial
68452930155bSTejun Heo  * workers and enable future kworker creations.
68463347fa09STejun Heo  */
68472333e829SYu Chen void __init workqueue_init(void)
68483347fa09STejun Heo {
68492186d9f9STejun Heo 	struct workqueue_struct *wq;
68503347fa09STejun Heo 	struct worker_pool *pool;
68513347fa09STejun Heo 	int cpu, bkt;
68523347fa09STejun Heo 
6853aa6fde93STejun Heo 	wq_cpu_intensive_thresh_init();
6854aa6fde93STejun Heo 
68552186d9f9STejun Heo 	mutex_lock(&wq_pool_mutex);
68562186d9f9STejun Heo 
68572930155bSTejun Heo 	/*
68582930155bSTejun Heo 	 * Per-cpu pools created earlier could be missing node hint. Fix them
68592930155bSTejun Heo 	 * up. Also, create a rescuer for workqueues that requested it.
68602930155bSTejun Heo 	 */
68612186d9f9STejun Heo 	for_each_possible_cpu(cpu) {
68622186d9f9STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
68632186d9f9STejun Heo 			pool->node = cpu_to_node(cpu);
68642186d9f9STejun Heo 		}
68652186d9f9STejun Heo 	}
68662186d9f9STejun Heo 
686740c17f75STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
686840c17f75STejun Heo 		WARN(init_rescuer(wq),
686940c17f75STejun Heo 		     "workqueue: failed to create early rescuer for %s",
687040c17f75STejun Heo 		     wq->name);
687140c17f75STejun Heo 	}
68722186d9f9STejun Heo 
68732186d9f9STejun Heo 	mutex_unlock(&wq_pool_mutex);
68742186d9f9STejun Heo 
68753347fa09STejun Heo 	/* create the initial workers */
68763347fa09STejun Heo 	for_each_online_cpu(cpu) {
68773347fa09STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
68783347fa09STejun Heo 			pool->flags &= ~POOL_DISASSOCIATED;
68793347fa09STejun Heo 			BUG_ON(!create_worker(pool));
68803347fa09STejun Heo 		}
68813347fa09STejun Heo 	}
68823347fa09STejun Heo 
68833347fa09STejun Heo 	hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
68843347fa09STejun Heo 		BUG_ON(!create_worker(pool));
68853347fa09STejun Heo 
68863347fa09STejun Heo 	wq_online = true;
688782607adcSTejun Heo 	wq_watchdog_init();
68881da177e4SLinus Torvalds }
6889c4f135d6STetsuo Handa 
6890025e1684STejun Heo /*
6891025e1684STejun Heo  * Initialize @pt by first initializing @pt->cpu_pod[] with pod IDs according to
6892025e1684STejun Heo  * @cpu_shares_pod(). Each subset of CPUs that share a pod is assigned a unique
6893025e1684STejun Heo  * and consecutive pod ID. The rest of @pt is initialized accordingly.
6894025e1684STejun Heo  */
6895025e1684STejun Heo static void __init init_pod_type(struct wq_pod_type *pt,
6896025e1684STejun Heo 				 bool (*cpus_share_pod)(int, int))
6897025e1684STejun Heo {
6898025e1684STejun Heo 	int cur, pre, cpu, pod;
6899025e1684STejun Heo 
6900025e1684STejun Heo 	pt->nr_pods = 0;
6901025e1684STejun Heo 
6902025e1684STejun Heo 	/* init @pt->cpu_pod[] according to @cpus_share_pod() */
6903025e1684STejun Heo 	pt->cpu_pod = kcalloc(nr_cpu_ids, sizeof(pt->cpu_pod[0]), GFP_KERNEL);
6904025e1684STejun Heo 	BUG_ON(!pt->cpu_pod);
6905025e1684STejun Heo 
6906025e1684STejun Heo 	for_each_possible_cpu(cur) {
6907025e1684STejun Heo 		for_each_possible_cpu(pre) {
6908025e1684STejun Heo 			if (pre >= cur) {
6909025e1684STejun Heo 				pt->cpu_pod[cur] = pt->nr_pods++;
6910025e1684STejun Heo 				break;
6911025e1684STejun Heo 			}
6912025e1684STejun Heo 			if (cpus_share_pod(cur, pre)) {
6913025e1684STejun Heo 				pt->cpu_pod[cur] = pt->cpu_pod[pre];
6914025e1684STejun Heo 				break;
6915025e1684STejun Heo 			}
6916025e1684STejun Heo 		}
6917025e1684STejun Heo 	}
6918025e1684STejun Heo 
6919025e1684STejun Heo 	/* init the rest to match @pt->cpu_pod[] */
6920025e1684STejun Heo 	pt->pod_cpus = kcalloc(pt->nr_pods, sizeof(pt->pod_cpus[0]), GFP_KERNEL);
6921025e1684STejun Heo 	pt->pod_node = kcalloc(pt->nr_pods, sizeof(pt->pod_node[0]), GFP_KERNEL);
6922025e1684STejun Heo 	BUG_ON(!pt->pod_cpus || !pt->pod_node);
6923025e1684STejun Heo 
6924025e1684STejun Heo 	for (pod = 0; pod < pt->nr_pods; pod++)
6925025e1684STejun Heo 		BUG_ON(!zalloc_cpumask_var(&pt->pod_cpus[pod], GFP_KERNEL));
6926025e1684STejun Heo 
6927025e1684STejun Heo 	for_each_possible_cpu(cpu) {
6928025e1684STejun Heo 		cpumask_set_cpu(cpu, pt->pod_cpus[pt->cpu_pod[cpu]]);
6929025e1684STejun Heo 		pt->pod_node[pt->cpu_pod[cpu]] = cpu_to_node(cpu);
6930025e1684STejun Heo 	}
6931025e1684STejun Heo }
6932025e1684STejun Heo 
693363c5484eSTejun Heo static bool __init cpus_dont_share(int cpu0, int cpu1)
693463c5484eSTejun Heo {
693563c5484eSTejun Heo 	return false;
693663c5484eSTejun Heo }
693763c5484eSTejun Heo 
693863c5484eSTejun Heo static bool __init cpus_share_smt(int cpu0, int cpu1)
693963c5484eSTejun Heo {
694063c5484eSTejun Heo #ifdef CONFIG_SCHED_SMT
694163c5484eSTejun Heo 	return cpumask_test_cpu(cpu0, cpu_smt_mask(cpu1));
694263c5484eSTejun Heo #else
694363c5484eSTejun Heo 	return false;
694463c5484eSTejun Heo #endif
694563c5484eSTejun Heo }
694663c5484eSTejun Heo 
6947025e1684STejun Heo static bool __init cpus_share_numa(int cpu0, int cpu1)
6948025e1684STejun Heo {
6949025e1684STejun Heo 	return cpu_to_node(cpu0) == cpu_to_node(cpu1);
6950025e1684STejun Heo }
6951025e1684STejun Heo 
69522930155bSTejun Heo /**
69532930155bSTejun Heo  * workqueue_init_topology - initialize CPU pods for unbound workqueues
69542930155bSTejun Heo  *
69552930155bSTejun Heo  * This is the third step of there-staged workqueue subsystem initialization and
69562930155bSTejun Heo  * invoked after SMP and topology information are fully initialized. It
69572930155bSTejun Heo  * initializes the unbound CPU pods accordingly.
69582930155bSTejun Heo  */
69592930155bSTejun Heo void __init workqueue_init_topology(void)
6960a86feae6STejun Heo {
69612930155bSTejun Heo 	struct workqueue_struct *wq;
6962025e1684STejun Heo 	int cpu;
6963a86feae6STejun Heo 
696463c5484eSTejun Heo 	init_pod_type(&wq_pod_types[WQ_AFFN_CPU], cpus_dont_share);
696563c5484eSTejun Heo 	init_pod_type(&wq_pod_types[WQ_AFFN_SMT], cpus_share_smt);
696663c5484eSTejun Heo 	init_pod_type(&wq_pod_types[WQ_AFFN_CACHE], cpus_share_cache);
6967025e1684STejun Heo 	init_pod_type(&wq_pod_types[WQ_AFFN_NUMA], cpus_share_numa);
6968a86feae6STejun Heo 
69692930155bSTejun Heo 	mutex_lock(&wq_pool_mutex);
6970a86feae6STejun Heo 
6971a86feae6STejun Heo 	/*
69722930155bSTejun Heo 	 * Workqueues allocated earlier would have all CPUs sharing the default
69732930155bSTejun Heo 	 * worker pool. Explicitly call wq_update_pod() on all workqueue and CPU
69742930155bSTejun Heo 	 * combinations to apply per-pod sharing.
69752930155bSTejun Heo 	 */
69762930155bSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
69772930155bSTejun Heo 		for_each_online_cpu(cpu) {
69782930155bSTejun Heo 			wq_update_pod(wq, cpu, cpu, true);
69792930155bSTejun Heo 		}
69802930155bSTejun Heo 	}
69812930155bSTejun Heo 
69822930155bSTejun Heo 	mutex_unlock(&wq_pool_mutex);
6983a86feae6STejun Heo }
6984a86feae6STejun Heo 
698520bdedafSTetsuo Handa void __warn_flushing_systemwide_wq(void)
698620bdedafSTetsuo Handa {
698720bdedafSTetsuo Handa 	pr_warn("WARNING: Flushing system-wide workqueues will be prohibited in near future.\n");
698820bdedafSTetsuo Handa 	dump_stack();
698920bdedafSTetsuo Handa }
6990c4f135d6STetsuo Handa EXPORT_SYMBOL(__warn_flushing_systemwide_wq);
6991ace3c549Stiozhang 
6992ace3c549Stiozhang static int __init workqueue_unbound_cpus_setup(char *str)
6993ace3c549Stiozhang {
6994ace3c549Stiozhang 	if (cpulist_parse(str, &wq_cmdline_cpumask) < 0) {
6995ace3c549Stiozhang 		cpumask_clear(&wq_cmdline_cpumask);
6996ace3c549Stiozhang 		pr_warn("workqueue.unbound_cpus: incorrect CPU range, using default\n");
6997ace3c549Stiozhang 	}
6998ace3c549Stiozhang 
6999ace3c549Stiozhang 	return 1;
7000ace3c549Stiozhang }
7001ace3c549Stiozhang __setup("workqueue.unbound_cpus=", workqueue_unbound_cpus_setup);
7002